agentlanes-cli 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- agentlanes/__init__.py +10 -0
- agentlanes/__main__.py +3 -0
- agentlanes/claims.py +215 -0
- agentlanes/cli.py +323 -0
- agentlanes/core.py +184 -0
- agentlanes/hook.py +166 -0
- agentlanes/jobs.py +126 -0
- agentlanes/landlock.py +257 -0
- agentlanes/onboard.py +364 -0
- agentlanes/procs.py +255 -0
- agentlanes/run.py +201 -0
- agentlanes/slots.py +253 -0
- agentlanes_cli-0.1.0.dist-info/METADATA +323 -0
- agentlanes_cli-0.1.0.dist-info/RECORD +18 -0
- agentlanes_cli-0.1.0.dist-info/WHEEL +5 -0
- agentlanes_cli-0.1.0.dist-info/entry_points.txt +2 -0
- agentlanes_cli-0.1.0.dist-info/licenses/LICENSE +202 -0
- agentlanes_cli-0.1.0.dist-info/top_level.txt +1 -0
agentlanes/procs.py
ADDED
|
@@ -0,0 +1,255 @@
|
|
|
1
|
+
"""Process helpers that work on Linux (/proc) and macOS (ps). No daemon, no state."""
|
|
2
|
+
import os
|
|
3
|
+
import re
|
|
4
|
+
import subprocess
|
|
5
|
+
import sys
|
|
6
|
+
|
|
7
|
+
from . import core
|
|
8
|
+
|
|
9
|
+
# $AGENTLANES_NO_PROC=1 makes Linux use the portable `ps` code paths that macOS uses (for tests and odd systems).
|
|
10
|
+
LINUX = (sys.platform.startswith('linux') and os.path.isdir('/proc/self')
|
|
11
|
+
and not os.environ.get(core.ENV + '_NO_PROC'))
|
|
12
|
+
|
|
13
|
+
# Executable names of common coding-agent CLIs. Extend with AGENTLANES_AGENT_NAMES=name1,name2.
|
|
14
|
+
KNOWN_AGENTS = {'claude', 'codex', 'cursor-agent', 'aider', 'gemini', 'opencode', 'goose', 'amp', 'crush', 'qwen',
|
|
15
|
+
'copilot', 'cline', 'kiro'}
|
|
16
|
+
ALIASES = {'claude-code': 'claude', 'gemini-cli': 'gemini', 'qwen-code': 'qwen'}
|
|
17
|
+
INTERPRETERS = re.compile(r'^(node|nodejs|bun|deno|python[0-9.]*)$')
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def _read(p):
|
|
21
|
+
try:
|
|
22
|
+
with open(p, 'rb') as fh:
|
|
23
|
+
return fh.read().decode('utf-8', 'replace')
|
|
24
|
+
except OSError:
|
|
25
|
+
return ''
|
|
26
|
+
|
|
27
|
+
|
|
28
|
+
# `ps` output must not depend on the caller's locale: start tokens written by one agent are compared by another.
|
|
29
|
+
PS_ENV = dict(os.environ, LC_ALL='C', LANG='C')
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _ps(pid, *fields):
|
|
33
|
+
"""Run `ps -o f1= -o f2= ... -p PID` (one -o per field: portable to BSD/macOS and procps, never a header)."""
|
|
34
|
+
argv = ['ps']
|
|
35
|
+
for f in fields:
|
|
36
|
+
argv += ['-o', f + '=']
|
|
37
|
+
try:
|
|
38
|
+
r = subprocess.run(argv + ['-p', str(int(pid))], capture_output=True, text=True, timeout=5, env=PS_ENV)
|
|
39
|
+
return r.stdout.strip() if r.returncode == 0 else ''
|
|
40
|
+
except Exception:
|
|
41
|
+
return ''
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def pid_alive(pid):
|
|
45
|
+
try:
|
|
46
|
+
pid = int(pid)
|
|
47
|
+
if pid <= 0:
|
|
48
|
+
return False
|
|
49
|
+
os.kill(pid, 0)
|
|
50
|
+
except (ValueError, TypeError, ProcessLookupError, OverflowError):
|
|
51
|
+
return False
|
|
52
|
+
except PermissionError:
|
|
53
|
+
return True
|
|
54
|
+
if LINUX:
|
|
55
|
+
st = _read('/proc/%d/stat' % pid)
|
|
56
|
+
return bool(st) and st.rsplit(')', 1)[-1].split()[:1] != ['Z']
|
|
57
|
+
return not _ps(pid, 'stat').startswith('Z') # kill(0) said it exists; an empty answer (ps failed) is not death
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
def start_token(pid):
|
|
61
|
+
"""Opaque process start time, used to notice a recycled pid."""
|
|
62
|
+
if LINUX:
|
|
63
|
+
st = _read('/proc/%d/stat' % int(pid))
|
|
64
|
+
return st.rsplit(')', 1)[1].split()[19] if st else None
|
|
65
|
+
return _ps(pid, 'lstart') or None
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
def same_process(pid, token):
|
|
69
|
+
if not pid_alive(pid):
|
|
70
|
+
return False
|
|
71
|
+
if not token:
|
|
72
|
+
return True
|
|
73
|
+
now = start_token(pid)
|
|
74
|
+
return now is None or now == token # unknown (ps/proc read failed): keep the lease rather than drop a live one
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
def parent_and_argv(pid):
|
|
78
|
+
if LINUX:
|
|
79
|
+
st = _read('/proc/%d/stat' % pid)
|
|
80
|
+
if not st:
|
|
81
|
+
return None, []
|
|
82
|
+
ppid = int(st.rsplit(')', 1)[1].split()[1])
|
|
83
|
+
argv = [a for a in _read('/proc/%d/cmdline' % pid).split('\0') if a]
|
|
84
|
+
if not argv:
|
|
85
|
+
argv = [st[st.find('(') + 1:st.rfind(')')]]
|
|
86
|
+
return ppid, argv
|
|
87
|
+
out = _ps(pid, 'ppid', 'args')
|
|
88
|
+
f = out.split(None, 1)
|
|
89
|
+
try:
|
|
90
|
+
ppid = int(f[0])
|
|
91
|
+
except (IndexError, ValueError):
|
|
92
|
+
return None, []
|
|
93
|
+
return ppid, f[1].split() if len(f) > 1 else []
|
|
94
|
+
|
|
95
|
+
|
|
96
|
+
def known_agents():
|
|
97
|
+
extra = core.env('AGENT_NAMES', '')
|
|
98
|
+
return KNOWN_AGENTS | {x.strip() for x in extra.split(',') if x.strip()}
|
|
99
|
+
|
|
100
|
+
|
|
101
|
+
def agent_kind(argv, names=None):
|
|
102
|
+
"""'claude' / 'codex' / ... if argv looks like a coding-agent CLI, else None."""
|
|
103
|
+
if not argv:
|
|
104
|
+
return None
|
|
105
|
+
names = names or known_agents()
|
|
106
|
+
|
|
107
|
+
def match(word):
|
|
108
|
+
word = re.sub(r'\.(js|mjs|cjs|py|exe)$', '', os.path.basename(word))
|
|
109
|
+
word = ALIASES.get(word, word)
|
|
110
|
+
return word if word in names else None
|
|
111
|
+
hit = match(argv[0])
|
|
112
|
+
if hit:
|
|
113
|
+
return hit
|
|
114
|
+
if INTERPRETERS.match(os.path.basename(argv[0])) and len(argv) > 1:
|
|
115
|
+
script = next((a for a in argv[1:] if not a.startswith('-')), '')
|
|
116
|
+
for comp in reversed(script.split('/')):
|
|
117
|
+
hit = match(comp.lstrip('@'))
|
|
118
|
+
if hit:
|
|
119
|
+
return hit
|
|
120
|
+
return None
|
|
121
|
+
|
|
122
|
+
|
|
123
|
+
def agent_self():
|
|
124
|
+
"""(pid, kind) of the agent process this command runs under: $AGENTLANES_AGENT_PID, else nearest agent ancestor."""
|
|
125
|
+
forced = core.env('AGENT_PID')
|
|
126
|
+
if forced:
|
|
127
|
+
return int(forced), core.env('AGENT') or 'agent'
|
|
128
|
+
names = known_agents()
|
|
129
|
+
pid, hops = os.getppid(), 0
|
|
130
|
+
while pid and pid > 1 and hops < 64:
|
|
131
|
+
ppid, argv = parent_and_argv(pid)
|
|
132
|
+
if ppid is None:
|
|
133
|
+
return None, None
|
|
134
|
+
k = agent_kind(argv, names)
|
|
135
|
+
if k:
|
|
136
|
+
return pid, k
|
|
137
|
+
pid, hops = ppid, hops + 1
|
|
138
|
+
return None, None
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def default_by():
|
|
142
|
+
"""Who am I: $AGENTLANES_AGENT, else '<agent>-<pid>' of the enclosing agent, else $USER."""
|
|
143
|
+
name = core.env('AGENT')
|
|
144
|
+
if name:
|
|
145
|
+
return name
|
|
146
|
+
pid, kind = agent_self()
|
|
147
|
+
if pid:
|
|
148
|
+
return '%s-%d' % (kind, pid)
|
|
149
|
+
return os.environ.get('USER') or 'user'
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _etime(s):
|
|
153
|
+
"""ps etime '[[dd-]hh:]mm:ss' -> seconds."""
|
|
154
|
+
days, _, rest = s.rpartition('-')
|
|
155
|
+
parts = [int(x) for x in rest.split(':')]
|
|
156
|
+
while len(parts) < 3:
|
|
157
|
+
parts.insert(0, 0)
|
|
158
|
+
return (int(days) if days else 0) * 86400 + parts[0] * 3600 + parts[1] * 60 + parts[2]
|
|
159
|
+
|
|
160
|
+
|
|
161
|
+
def process_table():
|
|
162
|
+
"""{pid: {'ppid', 'rss_kb', 'age_s', 'argv'}} for every process (one `ps` call)."""
|
|
163
|
+
try:
|
|
164
|
+
argv = ['ps', '-ax']
|
|
165
|
+
for f in ('pid', 'ppid', 'rss', 'etime', 'args'):
|
|
166
|
+
argv += ['-o', f + '=']
|
|
167
|
+
out = subprocess.run(argv, capture_output=True, text=True, timeout=10, env=PS_ENV).stdout
|
|
168
|
+
except Exception:
|
|
169
|
+
return {}
|
|
170
|
+
table = {}
|
|
171
|
+
for line in out.splitlines():
|
|
172
|
+
f = line.split(None, 4)
|
|
173
|
+
if len(f) < 4:
|
|
174
|
+
continue
|
|
175
|
+
try:
|
|
176
|
+
table[int(f[0])] = {'ppid': int(f[1]), 'rss_kb': int(f[2]), 'age_s': _etime(f[3]),
|
|
177
|
+
'argv': f[4].split() if len(f) > 4 else []}
|
|
178
|
+
except ValueError:
|
|
179
|
+
continue
|
|
180
|
+
return table
|
|
181
|
+
|
|
182
|
+
|
|
183
|
+
def tree_rss_kb(root, table):
|
|
184
|
+
kids = {}
|
|
185
|
+
for p, i in table.items():
|
|
186
|
+
kids.setdefault(i['ppid'], []).append(p)
|
|
187
|
+
tot, stack, seen = 0, [root], set()
|
|
188
|
+
while stack:
|
|
189
|
+
p = stack.pop()
|
|
190
|
+
if p in seen:
|
|
191
|
+
continue
|
|
192
|
+
seen.add(p)
|
|
193
|
+
tot += table.get(p, {}).get('rss_kb', 0)
|
|
194
|
+
stack.extend(kids.get(p, ()))
|
|
195
|
+
return tot
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def list_agents(include_sub=False):
|
|
199
|
+
table = process_table()
|
|
200
|
+
names = known_agents()
|
|
201
|
+
agents = {p: agent_kind(i['argv'], names) for p, i in table.items()}
|
|
202
|
+
agents = {p: k for p, k in agents.items() if k}
|
|
203
|
+
out = []
|
|
204
|
+
for p, k in sorted(agents.items()):
|
|
205
|
+
anc, parent_agent = table[p]['ppid'], None
|
|
206
|
+
hops = 0
|
|
207
|
+
while anc in table and anc > 1 and hops < 64:
|
|
208
|
+
if anc in agents:
|
|
209
|
+
parent_agent = anc
|
|
210
|
+
break
|
|
211
|
+
anc, hops = table[anc]['ppid'], hops + 1
|
|
212
|
+
if parent_agent and not include_sub:
|
|
213
|
+
continue
|
|
214
|
+
cwd = process_cwd(p)
|
|
215
|
+
out.append({'pid': p, 'kind': k, 'parent_agent': parent_agent, 'age_s': table[p]['age_s'],
|
|
216
|
+
'mem_mb': tree_rss_kb(p, table) // 1024, 'cwd': cwd,
|
|
217
|
+
'headless': any(a in ('-p', '--print', 'exec') for a in table[p]['argv'][1:3])})
|
|
218
|
+
return out
|
|
219
|
+
|
|
220
|
+
|
|
221
|
+
def process_cwd(pid):
|
|
222
|
+
"""Working directory of PID: /proc on Linux, `lsof` elsewhere (macOS). None if unknown."""
|
|
223
|
+
if LINUX:
|
|
224
|
+
try:
|
|
225
|
+
return os.readlink('/proc/%d/cwd' % pid)
|
|
226
|
+
except OSError:
|
|
227
|
+
return None
|
|
228
|
+
try:
|
|
229
|
+
out = subprocess.run(['lsof', '-a', '-p', str(int(pid)), '-d', 'cwd', '-Fn'], capture_output=True, text=True,
|
|
230
|
+
timeout=5, env=PS_ENV).stdout
|
|
231
|
+
except Exception:
|
|
232
|
+
return None
|
|
233
|
+
return next((ln[1:] for ln in out.splitlines() if ln.startswith('n')), None)
|
|
234
|
+
|
|
235
|
+
|
|
236
|
+
def parse_vm_stat(out):
|
|
237
|
+
"""macOS `vm_stat` text -> available MB (free + inactive + speculative pages), or None."""
|
|
238
|
+
try:
|
|
239
|
+
page = int(re.search(r'page size of (\d+)', out).group(1))
|
|
240
|
+
pages = sum(int(re.search(r'%s:\s+(\d+)' % k, out).group(1))
|
|
241
|
+
for k in ('Pages free', 'Pages inactive', 'Pages speculative'))
|
|
242
|
+
return pages * page // 1048576
|
|
243
|
+
except (AttributeError, ValueError):
|
|
244
|
+
return None
|
|
245
|
+
|
|
246
|
+
|
|
247
|
+
def mem_available_mb():
|
|
248
|
+
if LINUX:
|
|
249
|
+
m = re.search(r'MemAvailable:\s+(\d+)', _read('/proc/meminfo'))
|
|
250
|
+
return int(m.group(1)) // 1024 if m else None
|
|
251
|
+
try:
|
|
252
|
+
out = subprocess.run(['vm_stat'], capture_output=True, text=True, timeout=5, env=PS_ENV).stdout
|
|
253
|
+
except Exception:
|
|
254
|
+
return None
|
|
255
|
+
return parse_vm_stat(out)
|
agentlanes/run.py
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
"""`agentlanes run`: start a command whose writes the Linux kernel confines to the agent's lanes (Landlock).
|
|
2
|
+
|
|
3
|
+
Writable: paths of the agent's claims (or --claim NAMEs), the agentlanes state directory, an optional private temp
|
|
4
|
+
dir and explicit --write paths. Everything else stays readable and executable, so tools keep working.
|
|
5
|
+
|
|
6
|
+
The ruleset is fixed when the command starts. A claim taken later does not widen it: restart the agent, or run the
|
|
7
|
+
sub-task under a new `agentlanes run` (nesting only ever narrows).
|
|
8
|
+
"""
|
|
9
|
+
import argparse
|
|
10
|
+
import os
|
|
11
|
+
import shlex
|
|
12
|
+
import shutil
|
|
13
|
+
import signal
|
|
14
|
+
import subprocess
|
|
15
|
+
import sys
|
|
16
|
+
import tempfile
|
|
17
|
+
import time
|
|
18
|
+
|
|
19
|
+
from . import ENV, NAME, claims, core, landlock, procs
|
|
20
|
+
|
|
21
|
+
# --allow-common: per-user places coding agents and build tools write to (caches, their own config/session state).
|
|
22
|
+
# Only the paths that exist are added. Extend with AGENTLANES_RUN_COMMON=path1:path2.
|
|
23
|
+
COMMON = ['~/.cache', '~/.claude', '~/.claude.json', '~/.codex', '~/.cursor', '~/.gemini', '~/.aider',
|
|
24
|
+
'~/.config/claude', '~/.config/gh', '~/.npm', '~/.local/state', '~/.local/share/claude']
|
|
25
|
+
|
|
26
|
+
USAGE = '%s run [--claim NAME]... [--write PATH]... [--allow-tmp] [--allow-common] [--no-net] [--allow-port N]... ' \
|
|
27
|
+
'[--isolate] [--best-effort] [--by WHO] [--dry-run] -- COMMAND...' % NAME
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def parser():
|
|
31
|
+
a = argparse.ArgumentParser(prog='%s run' % NAME, usage=USAGE, description=__doc__.split('\n\n')[0])
|
|
32
|
+
a.add_argument('--claim', action='append', default=[], metavar='NAME',
|
|
33
|
+
help='make this claim\'s paths writable (repeatable). Default: every claim held by --by')
|
|
34
|
+
a.add_argument('--write', action='append', default=[], metavar='PATH', help='extra writable path (repeatable)')
|
|
35
|
+
a.add_argument('--allow-tmp', action='store_true', help='create a private temp dir, export TMPDIR, delete it after')
|
|
36
|
+
a.add_argument('--allow-common', action='store_true',
|
|
37
|
+
help='also allow ~/.cache, agent config/session dirs (~/.claude, ~/.codex, ...) that exist')
|
|
38
|
+
a.add_argument('--no-net', action='store_true', help='deny TCP connect/bind (Landlock ABI 4+)')
|
|
39
|
+
a.add_argument('--allow-port', action='append', default=[], type=int, metavar='N',
|
|
40
|
+
help='with network restriction, allow TCP connect to port N (repeatable; implies --no-net)')
|
|
41
|
+
a.add_argument('--allow-bind', action='append', default=[], type=int, metavar='N',
|
|
42
|
+
help='allow listening on TCP port N (repeatable; implies --no-net)')
|
|
43
|
+
a.add_argument('--isolate', action='store_true',
|
|
44
|
+
help='block signals and abstract unix sockets to processes outside the run (Landlock ABI 6+)')
|
|
45
|
+
a.add_argument('--best-effort', action='store_true',
|
|
46
|
+
help='if Landlock is unavailable, run the command unconfined (with a warning) instead of refusing')
|
|
47
|
+
a.add_argument('--by', help='whose claims to use (default: $%s_AGENT / enclosing agent)' % ENV)
|
|
48
|
+
a.add_argument('--dry-run', action='store_true', help='print the ruleset and exit')
|
|
49
|
+
a.add_argument('-q', '--quiet', action='store_true', help='no summary line on stderr')
|
|
50
|
+
return a
|
|
51
|
+
|
|
52
|
+
|
|
53
|
+
def _err(msg):
|
|
54
|
+
print('%s run: %s' % (NAME, msg), file=sys.stderr)
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def claim_paths(names, by):
|
|
58
|
+
"""(paths, used_claim_names, error)."""
|
|
59
|
+
live = claims.snapshot()
|
|
60
|
+
if names:
|
|
61
|
+
missing = [n for n in names if n not in live]
|
|
62
|
+
if missing:
|
|
63
|
+
return None, None, 'no live claim named %s (see `%s list`)' % (', '.join(missing), NAME)
|
|
64
|
+
chosen = {n: live[n] for n in names}
|
|
65
|
+
for n, c in chosen.items():
|
|
66
|
+
if c.get('by') != by:
|
|
67
|
+
_err('note: claim %s is held by %s, not %s' % (n, c.get('by'), by))
|
|
68
|
+
else:
|
|
69
|
+
chosen = {k: c for k, c in live.items() if c.get('by') == by}
|
|
70
|
+
paths = []
|
|
71
|
+
for n, c in chosen.items():
|
|
72
|
+
if not c.get('paths'):
|
|
73
|
+
_err('note: claim %s has no paths, so it adds nothing writable' % n)
|
|
74
|
+
paths.extend(c.get('paths', []))
|
|
75
|
+
return paths, sorted(chosen), None
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def main(argv):
|
|
79
|
+
if '--' not in argv:
|
|
80
|
+
print('usage: ' + USAGE, file=sys.stderr)
|
|
81
|
+
return 2
|
|
82
|
+
i = argv.index('--')
|
|
83
|
+
o = parser().parse_args(argv[:i])
|
|
84
|
+
cmd = argv[i + 1:]
|
|
85
|
+
if not cmd:
|
|
86
|
+
print('usage: ' + USAGE, file=sys.stderr)
|
|
87
|
+
return 2
|
|
88
|
+
by = o.by or procs.default_by()
|
|
89
|
+
state = core.state_dir()
|
|
90
|
+
|
|
91
|
+
paths, used, err = claim_paths(o.claim, by)
|
|
92
|
+
if err:
|
|
93
|
+
_err(err)
|
|
94
|
+
return 1
|
|
95
|
+
for p in o.write:
|
|
96
|
+
if not os.path.exists(os.path.expanduser(p)):
|
|
97
|
+
_err('--write path does not exist: %s (create it first; a rule needs an existing file or directory)' % p)
|
|
98
|
+
return 2
|
|
99
|
+
if not paths and not o.write:
|
|
100
|
+
_err('nothing to make writable: %s holds no claims with paths and no --write was given '
|
|
101
|
+
'(claim first: `%s claim TOPIC --paths DIR`, or pass --write DIR)' % (by, NAME))
|
|
102
|
+
return 2
|
|
103
|
+
|
|
104
|
+
tmp = None
|
|
105
|
+
if o.allow_tmp:
|
|
106
|
+
base = os.environ.get('XDG_RUNTIME_DIR') if os.path.isdir(os.environ.get('XDG_RUNTIME_DIR', '')) else None
|
|
107
|
+
tmp = tempfile.mkdtemp(prefix='%s-run-' % NAME, dir=base)
|
|
108
|
+
common = []
|
|
109
|
+
if o.allow_common:
|
|
110
|
+
extra = [x for x in core.env('RUN_COMMON', '').split(':') if x]
|
|
111
|
+
common = [os.path.expanduser(p) for p in COMMON + extra if os.path.exists(os.path.expanduser(p))]
|
|
112
|
+
|
|
113
|
+
write = paths + list(o.write) + [state] + ([tmp] if tmp else []) + common
|
|
114
|
+
policy = landlock.Policy(write, no_net=o.no_net, connect_ports=o.allow_port, bind_ports=o.allow_bind,
|
|
115
|
+
isolate=o.isolate)
|
|
116
|
+
|
|
117
|
+
try:
|
|
118
|
+
abi = landlock.abi_version()
|
|
119
|
+
except landlock.Unsupported as e:
|
|
120
|
+
abi = 0
|
|
121
|
+
if not o.best_effort:
|
|
122
|
+
_err('refusing to run unconfined: %s. Use --best-effort to run anyway (hooks still apply), or use '
|
|
123
|
+
'a Linux 5.13+ kernel with Landlock enabled.' % e)
|
|
124
|
+
if tmp:
|
|
125
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
126
|
+
return 3
|
|
127
|
+
_err('WARNING: %s; running UNCONFINED (--best-effort)' % e)
|
|
128
|
+
|
|
129
|
+
plan = landlock.plan(policy, abi) if abi else None
|
|
130
|
+
summ = landlock.summary(plan) if plan else {'abi': 0, 'write': 'unrestricted (no Landlock)'}
|
|
131
|
+
summ['claims'] = used
|
|
132
|
+
for w in (plan or {}).get('warnings', []):
|
|
133
|
+
_err('warning: ' + w)
|
|
134
|
+
if o.dry_run:
|
|
135
|
+
import json
|
|
136
|
+
print(json.dumps(dict(summ, rules=[(p, hex(r)) for p, r in plan['rules']] if plan else []), indent=1))
|
|
137
|
+
if tmp:
|
|
138
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
139
|
+
return 0
|
|
140
|
+
|
|
141
|
+
fd = None
|
|
142
|
+
if plan:
|
|
143
|
+
try:
|
|
144
|
+
fd = landlock.build(plan)
|
|
145
|
+
except OSError as e:
|
|
146
|
+
_err('could not build the Landlock ruleset: %s' % e)
|
|
147
|
+
if tmp:
|
|
148
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
149
|
+
return 3
|
|
150
|
+
|
|
151
|
+
env = dict(os.environ)
|
|
152
|
+
env['%s_STATE_DIR' % ENV] = state # the child must find the same (writable) state dir
|
|
153
|
+
env.setdefault('%s_AGENT' % ENV, by)
|
|
154
|
+
env['%s_RUN' % ENV] = '1'
|
|
155
|
+
if tmp:
|
|
156
|
+
env['TMPDIR'] = tmp
|
|
157
|
+
|
|
158
|
+
def confine():
|
|
159
|
+
if fd is not None:
|
|
160
|
+
landlock.restrict_self(fd)
|
|
161
|
+
|
|
162
|
+
if not o.quiet:
|
|
163
|
+
_err('Landlock ABI %s; writable: %s%s' % (
|
|
164
|
+
abi or 'none', ', '.join(summ['write']) if isinstance(summ['write'], list) else summ['write'],
|
|
165
|
+
'; tcp: ' + summ['tcp'] if summ.get('tcp', 'unrestricted') != 'unrestricted' else ''))
|
|
166
|
+
t0 = time.time()
|
|
167
|
+
try:
|
|
168
|
+
child = subprocess.Popen(cmd, env=env, preexec_fn=confine)
|
|
169
|
+
except OSError as e:
|
|
170
|
+
_err('cannot start %s: %s' % (cmd[0], e))
|
|
171
|
+
rc = 127
|
|
172
|
+
child = None
|
|
173
|
+
except subprocess.SubprocessError as e:
|
|
174
|
+
_err('could not apply Landlock in the child: %s' % e)
|
|
175
|
+
rc = 3
|
|
176
|
+
child = None
|
|
177
|
+
finally:
|
|
178
|
+
if fd is not None:
|
|
179
|
+
os.close(fd)
|
|
180
|
+
if child:
|
|
181
|
+
core.emit('run.start', by=by, pid=child.pid, cmd=shlex.join(cmd)[:200], **{
|
|
182
|
+
k: (','.join(v) if isinstance(v, list) else v) for k, v in summ.items()})
|
|
183
|
+
old = {s: signal.signal(s, signal.SIG_IGN) for s in (signal.SIGINT, signal.SIGQUIT)}
|
|
184
|
+
|
|
185
|
+
def forward(sig, _frame):
|
|
186
|
+
try:
|
|
187
|
+
child.send_signal(sig)
|
|
188
|
+
except OSError:
|
|
189
|
+
pass
|
|
190
|
+
old[signal.SIGTERM] = signal.signal(signal.SIGTERM, forward)
|
|
191
|
+
old[signal.SIGHUP] = signal.signal(signal.SIGHUP, forward)
|
|
192
|
+
try:
|
|
193
|
+
rc = child.wait()
|
|
194
|
+
finally:
|
|
195
|
+
for s, h in old.items():
|
|
196
|
+
signal.signal(s, h)
|
|
197
|
+
rc = 128 - rc if rc < 0 else rc
|
|
198
|
+
core.emit('run.stop', by=by, pid=child.pid, rc=rc, dur_s=round(time.time() - t0, 1))
|
|
199
|
+
if tmp:
|
|
200
|
+
shutil.rmtree(tmp, ignore_errors=True)
|
|
201
|
+
return rc
|