coldrun 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.
- coldrun/__init__.py +12 -0
- coldrun/cli.py +53 -0
- coldrun/config.py +29 -0
- coldrun/detect.py +223 -0
- coldrun/doctor.py +208 -0
- coldrun/fetch/__init__.py +82 -0
- coldrun/fetch/base.py +137 -0
- coldrun/fetch/local.py +46 -0
- coldrun/fetch/url.py +136 -0
- coldrun/pipeline.py +1 -0
- coldrun/py.typed +0 -0
- coldrun/report.py +195 -0
- coldrun/runners/__init__.py +15 -0
- coldrun/runners/base.py +97 -0
- coldrun/runners/registry.py +125 -0
- coldrun/sandbox/__init__.py +29 -0
- coldrun/sandbox/base.py +219 -0
- coldrun/sandbox/bwrap.py +226 -0
- coldrun/vet/__init__.py +1 -0
- coldrun/vet/findings.py +66 -0
- coldrun-0.1.0.dist-info/METADATA +53 -0
- coldrun-0.1.0.dist-info/RECORD +25 -0
- coldrun-0.1.0.dist-info/WHEEL +4 -0
- coldrun-0.1.0.dist-info/entry_points.txt +2 -0
- coldrun-0.1.0.dist-info/licenses/LICENSE +21 -0
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
"""Discover runners through the ``coldrun.runners`` entry-point group.
|
|
2
|
+
|
|
3
|
+
Built-in runners and third-party ones register the same way, so a plugin
|
|
4
|
+
package only needs one line in its ``pyproject.toml``. A plugin that fails to
|
|
5
|
+
load is reported, not fatal: one broken plugin must not take the tool down.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import logging
|
|
11
|
+
from importlib.metadata import EntryPoint, entry_points
|
|
12
|
+
from typing import TYPE_CHECKING
|
|
13
|
+
|
|
14
|
+
from coldrun.runners.base import Runner, RunnerInfo
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from collections.abc import Iterable
|
|
18
|
+
|
|
19
|
+
GROUP = "coldrun.runners"
|
|
20
|
+
log = logging.getLogger(__name__)
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class RunnerNotFoundError(LookupError):
|
|
24
|
+
"""Raised when a runner name is asked for that is not registered."""
|
|
25
|
+
|
|
26
|
+
def __init__(self, name: str, available: Iterable[str]) -> None:
|
|
27
|
+
"""Build a message that lists what is available."""
|
|
28
|
+
names = ", ".join(sorted(available)) or "none"
|
|
29
|
+
super().__init__(f"no runner named {name!r}; available: {names}")
|
|
30
|
+
self.name = name
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
def _instantiate(ep: EntryPoint) -> Runner:
|
|
34
|
+
obj = ep.load()
|
|
35
|
+
runner = obj() if callable(obj) and not isinstance(obj, Runner) else obj
|
|
36
|
+
if not isinstance(runner, Runner):
|
|
37
|
+
msg = f"{ep.value} does not satisfy the Runner protocol"
|
|
38
|
+
raise TypeError(msg)
|
|
39
|
+
name = getattr(runner, "name", None)
|
|
40
|
+
if not isinstance(name, str) or not name:
|
|
41
|
+
msg = f"{ep.value} has no non-empty name"
|
|
42
|
+
raise TypeError(msg)
|
|
43
|
+
return runner
|
|
44
|
+
|
|
45
|
+
|
|
46
|
+
def discover(eps: Iterable[EntryPoint] | None = None) -> dict[str, RunnerInfo]:
|
|
47
|
+
"""Load every runner in the entry-point group.
|
|
48
|
+
|
|
49
|
+
Args:
|
|
50
|
+
eps: Entry points to load. Defaults to the installed ``coldrun.runners``
|
|
51
|
+
group; tests pass their own.
|
|
52
|
+
|
|
53
|
+
Returns:
|
|
54
|
+
Loaded runners keyed by name, in entry-point order. The first runner
|
|
55
|
+
to claim a name wins; later duplicates are logged and dropped. Entry
|
|
56
|
+
points that fail to load are left out and logged with the cause.
|
|
57
|
+
"""
|
|
58
|
+
if eps is None:
|
|
59
|
+
eps = entry_points(group=GROUP)
|
|
60
|
+
found: dict[str, RunnerInfo] = {}
|
|
61
|
+
for ep in eps:
|
|
62
|
+
dist = ep.dist.name if ep.dist is not None else None
|
|
63
|
+
try:
|
|
64
|
+
runner = _instantiate(ep)
|
|
65
|
+
except Exception as exc:
|
|
66
|
+
log.warning("runner entry point %s failed to load: %s", ep.value, exc)
|
|
67
|
+
continue
|
|
68
|
+
if runner.name in found:
|
|
69
|
+
log.warning(
|
|
70
|
+
"runner %r from %s ignored; already provided by %s",
|
|
71
|
+
runner.name,
|
|
72
|
+
ep.value,
|
|
73
|
+
found[runner.name].entry_point,
|
|
74
|
+
)
|
|
75
|
+
continue
|
|
76
|
+
found[runner.name] = RunnerInfo(runner=runner, entry_point=ep.value, distribution=dist)
|
|
77
|
+
return found
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
class Registry:
|
|
81
|
+
"""The set of runners available in this process.
|
|
82
|
+
|
|
83
|
+
Loading is lazy so ``coldrun --version`` never imports a plugin.
|
|
84
|
+
"""
|
|
85
|
+
|
|
86
|
+
def __init__(self, eps: Iterable[EntryPoint] | None = None) -> None:
|
|
87
|
+
"""Create a registry that will load ``eps`` on first use."""
|
|
88
|
+
self._eps = eps
|
|
89
|
+
self._loaded: dict[str, RunnerInfo] | None = None
|
|
90
|
+
|
|
91
|
+
def _ensure(self) -> dict[str, RunnerInfo]:
|
|
92
|
+
if self._loaded is None:
|
|
93
|
+
self._loaded = discover(self._eps)
|
|
94
|
+
return self._loaded
|
|
95
|
+
|
|
96
|
+
def names(self) -> list[str]:
|
|
97
|
+
"""Names of every loaded runner, sorted."""
|
|
98
|
+
return sorted(self._ensure())
|
|
99
|
+
|
|
100
|
+
def all(self) -> list[Runner]:
|
|
101
|
+
"""Every loaded runner, in registration order."""
|
|
102
|
+
return [info.runner for info in self._ensure().values()]
|
|
103
|
+
|
|
104
|
+
def info(self, name: str) -> RunnerInfo:
|
|
105
|
+
"""Loaded runner plus provenance, or :class:`RunnerNotFoundError`."""
|
|
106
|
+
loaded = self._ensure()
|
|
107
|
+
try:
|
|
108
|
+
return loaded[name]
|
|
109
|
+
except KeyError:
|
|
110
|
+
raise RunnerNotFoundError(name, loaded) from None
|
|
111
|
+
|
|
112
|
+
def get(self, name: str) -> Runner:
|
|
113
|
+
"""The runner called ``name``, or :class:`RunnerNotFoundError`."""
|
|
114
|
+
return self.info(name).runner
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
_default: Registry | None = None
|
|
118
|
+
|
|
119
|
+
|
|
120
|
+
def default_registry() -> Registry:
|
|
121
|
+
"""Process-wide registry backed by the installed entry points."""
|
|
122
|
+
global _default # noqa: PLW0603 - a single lazily-built registry per process
|
|
123
|
+
if _default is None:
|
|
124
|
+
_default = Registry()
|
|
125
|
+
return _default
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
"""Sandbox backends behind one policy interface."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from coldrun.sandbox.base import (
|
|
6
|
+
EXIT_SANDBOX_FAILED,
|
|
7
|
+
WORKDIR,
|
|
8
|
+
Availability,
|
|
9
|
+
Backend,
|
|
10
|
+
NetPolicy,
|
|
11
|
+
Policy,
|
|
12
|
+
PolicyError,
|
|
13
|
+
SandboxError,
|
|
14
|
+
scrub_env,
|
|
15
|
+
)
|
|
16
|
+
from coldrun.sandbox.bwrap import BwrapBackend
|
|
17
|
+
|
|
18
|
+
__all__ = [
|
|
19
|
+
"EXIT_SANDBOX_FAILED",
|
|
20
|
+
"WORKDIR",
|
|
21
|
+
"Availability",
|
|
22
|
+
"Backend",
|
|
23
|
+
"BwrapBackend",
|
|
24
|
+
"NetPolicy",
|
|
25
|
+
"Policy",
|
|
26
|
+
"PolicyError",
|
|
27
|
+
"SandboxError",
|
|
28
|
+
"scrub_env",
|
|
29
|
+
]
|
coldrun/sandbox/base.py
ADDED
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""The sandbox policy model and the backend contract.
|
|
2
|
+
|
|
3
|
+
A :class:`Policy` says what the script may see and do. Backends turn a policy
|
|
4
|
+
into a concrete sandbox. Every rule in the spec's security model is encoded
|
|
5
|
+
here or enforced by a backend, and all of this code is covered by tests.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import os
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from enum import Enum
|
|
13
|
+
from pathlib import Path
|
|
14
|
+
from typing import TYPE_CHECKING, Protocol
|
|
15
|
+
|
|
16
|
+
if TYPE_CHECKING:
|
|
17
|
+
from collections.abc import Mapping, Sequence
|
|
18
|
+
|
|
19
|
+
#: Where the script and its scratch space appear inside the sandbox.
|
|
20
|
+
WORKDIR = "/work"
|
|
21
|
+
#: Exit code the CLI uses when the sandbox itself could not be set up.
|
|
22
|
+
EXIT_SANDBOX_FAILED = 101
|
|
23
|
+
|
|
24
|
+
#: Variables copied from the host when present. Everything else is dropped.
|
|
25
|
+
ENV_PASSTHROUGH: frozenset[str] = frozenset(
|
|
26
|
+
{
|
|
27
|
+
"TERM",
|
|
28
|
+
"COLORTERM",
|
|
29
|
+
"NO_COLOR",
|
|
30
|
+
"FORCE_COLOR",
|
|
31
|
+
"LANG",
|
|
32
|
+
"LANGUAGE",
|
|
33
|
+
"LC_ALL",
|
|
34
|
+
"LC_CTYPE",
|
|
35
|
+
"TZ",
|
|
36
|
+
}
|
|
37
|
+
)
|
|
38
|
+
#: Variables set to fixed values regardless of the host.
|
|
39
|
+
ENV_FIXED: Mapping[str, str] = {
|
|
40
|
+
"PATH": "/usr/local/bin:/usr/bin:/bin",
|
|
41
|
+
"HOME": WORKDIR,
|
|
42
|
+
"TMPDIR": "/tmp", # noqa: S108 - guest path on a private tmpfs
|
|
43
|
+
"USER": "coldrun",
|
|
44
|
+
"LOGNAME": "coldrun",
|
|
45
|
+
"SHELL": "/bin/sh",
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
#: Host locations that may never be mounted read-write, even on request.
|
|
49
|
+
_FORBIDDEN_RW_NAMES = frozenset(
|
|
50
|
+
{
|
|
51
|
+
".ssh",
|
|
52
|
+
".gnupg",
|
|
53
|
+
".aws",
|
|
54
|
+
".azure",
|
|
55
|
+
".config",
|
|
56
|
+
".kube",
|
|
57
|
+
".docker",
|
|
58
|
+
".mozilla",
|
|
59
|
+
".password-store",
|
|
60
|
+
}
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
class NetPolicy(str, Enum):
|
|
65
|
+
"""Network access inside the sandbox."""
|
|
66
|
+
|
|
67
|
+
NONE = "none"
|
|
68
|
+
ALLOW = "allow" # only --allow-host destinations; enforced from M4
|
|
69
|
+
FULL = "full"
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
class SandboxError(Exception):
|
|
73
|
+
"""The sandbox could not be built or started.
|
|
74
|
+
|
|
75
|
+
Args:
|
|
76
|
+
what: What failed, in one sentence.
|
|
77
|
+
hint: The next command to try, usually ``coldrun doctor``.
|
|
78
|
+
"""
|
|
79
|
+
|
|
80
|
+
exit_code = EXIT_SANDBOX_FAILED
|
|
81
|
+
|
|
82
|
+
def __init__(self, what: str, hint: str) -> None:
|
|
83
|
+
"""Keep the halves separate for the report."""
|
|
84
|
+
super().__init__(f"{what} {hint}")
|
|
85
|
+
self.what = what
|
|
86
|
+
self.hint = hint
|
|
87
|
+
|
|
88
|
+
|
|
89
|
+
class PolicyError(ValueError):
|
|
90
|
+
"""A requested policy breaks a rule that is not negotiable."""
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
@dataclass(frozen=True, slots=True)
|
|
94
|
+
class Policy:
|
|
95
|
+
"""What one sandboxed run may access.
|
|
96
|
+
|
|
97
|
+
Attributes:
|
|
98
|
+
script: The quarantined file to run. Mounted read-only at
|
|
99
|
+
``/work/<name>``.
|
|
100
|
+
scratch: Private host directory mounted read-write at ``/work``; the
|
|
101
|
+
script's cwd. Files it writes land here and are copied to
|
|
102
|
+
``--out`` by the pipeline.
|
|
103
|
+
net: Network policy. ``NONE`` by default.
|
|
104
|
+
rw_paths: Host paths mounted read-write at the same location
|
|
105
|
+
(``--rw``). Validated against the forbidden list.
|
|
106
|
+
ro_paths: Host paths mounted read-only at the same location, for
|
|
107
|
+
dependency environments and interpreters.
|
|
108
|
+
env: Extra variables, already decided safe by the caller, layered on
|
|
109
|
+
top of the scrubbed allowlist.
|
|
110
|
+
tty: Whether stdin is a terminal and should pass through.
|
|
111
|
+
hostname: Hostname inside the sandbox.
|
|
112
|
+
"""
|
|
113
|
+
|
|
114
|
+
script: Path
|
|
115
|
+
scratch: Path
|
|
116
|
+
net: NetPolicy = NetPolicy.NONE
|
|
117
|
+
rw_paths: tuple[Path, ...] = ()
|
|
118
|
+
ro_paths: tuple[Path, ...] = ()
|
|
119
|
+
env: Mapping[str, str] = field(default_factory=dict)
|
|
120
|
+
tty: bool = False
|
|
121
|
+
hostname: str = "coldrun"
|
|
122
|
+
|
|
123
|
+
def __post_init__(self) -> None:
|
|
124
|
+
"""Reject policies that would hand the host to the script."""
|
|
125
|
+
if not self.script.is_absolute() or not self.scratch.is_absolute():
|
|
126
|
+
msg = "script and scratch must be absolute paths"
|
|
127
|
+
raise PolicyError(msg)
|
|
128
|
+
for p in self.rw_paths:
|
|
129
|
+
check_rw_path(p)
|
|
130
|
+
for p in self.ro_paths:
|
|
131
|
+
if not p.is_absolute():
|
|
132
|
+
msg = f"read-only path must be absolute: {p}"
|
|
133
|
+
raise PolicyError(msg)
|
|
134
|
+
|
|
135
|
+
@property
|
|
136
|
+
def guest_script(self) -> str:
|
|
137
|
+
"""Where the script appears inside the sandbox."""
|
|
138
|
+
return f"{WORKDIR}/{self.script.name}"
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def check_rw_path(path: Path) -> None:
|
|
142
|
+
"""Refuse read-write mounts that would expose the host.
|
|
143
|
+
|
|
144
|
+
Blocks ``/``, the home directory itself, anything under a credential
|
|
145
|
+
directory, and relative paths.
|
|
146
|
+
|
|
147
|
+
Raises:
|
|
148
|
+
PolicyError: With the reason.
|
|
149
|
+
"""
|
|
150
|
+
if not path.is_absolute():
|
|
151
|
+
msg = f"--rw path must be absolute: {path}"
|
|
152
|
+
raise PolicyError(msg)
|
|
153
|
+
resolved = Path(os.path.realpath(path))
|
|
154
|
+
home = Path.home().resolve()
|
|
155
|
+
if resolved == Path("/") or resolved == home:
|
|
156
|
+
msg = f"--rw {path} would expose the whole filesystem or home directory"
|
|
157
|
+
raise PolicyError(msg)
|
|
158
|
+
if any(part in _FORBIDDEN_RW_NAMES for part in resolved.parts):
|
|
159
|
+
msg = f"--rw {path} is inside a credential or configuration directory"
|
|
160
|
+
raise PolicyError(msg)
|
|
161
|
+
if not resolved.exists():
|
|
162
|
+
msg = f"--rw {path} does not exist"
|
|
163
|
+
raise PolicyError(msg)
|
|
164
|
+
|
|
165
|
+
|
|
166
|
+
def scrub_env(host: Mapping[str, str], extra: Mapping[str, str] | None = None) -> dict[str, str]:
|
|
167
|
+
"""Build the environment the script sees.
|
|
168
|
+
|
|
169
|
+
Fixed values first, then the allowlisted host variables, then ``extra``
|
|
170
|
+
from the caller. ``extra`` may not override the fixed values that keep
|
|
171
|
+
the script inside its scratch space.
|
|
172
|
+
"""
|
|
173
|
+
env = dict(ENV_FIXED)
|
|
174
|
+
for name in sorted(ENV_PASSTHROUGH):
|
|
175
|
+
if name in host:
|
|
176
|
+
env[name] = host[name]
|
|
177
|
+
for name, value in (extra or {}).items():
|
|
178
|
+
if name in {"HOME", "TMPDIR", "PATH"} and value != env[name]:
|
|
179
|
+
msg = f"environment override of {name} is not allowed"
|
|
180
|
+
raise PolicyError(msg)
|
|
181
|
+
env[name] = value
|
|
182
|
+
return env
|
|
183
|
+
|
|
184
|
+
|
|
185
|
+
@dataclass(frozen=True, slots=True)
|
|
186
|
+
class Availability:
|
|
187
|
+
"""Whether a backend can be used here, and if not, why."""
|
|
188
|
+
|
|
189
|
+
ok: bool
|
|
190
|
+
reason: str = ""
|
|
191
|
+
hint: str = ""
|
|
192
|
+
|
|
193
|
+
|
|
194
|
+
class Backend(Protocol):
|
|
195
|
+
"""One way of building a sandbox."""
|
|
196
|
+
|
|
197
|
+
name: str
|
|
198
|
+
|
|
199
|
+
def available(self) -> Availability:
|
|
200
|
+
"""Cheap check that the backend can work on this host."""
|
|
201
|
+
...
|
|
202
|
+
|
|
203
|
+
def command(self, policy: Policy, argv: Sequence[str]) -> list[str]:
|
|
204
|
+
"""Full host argument list that runs ``argv`` under ``policy``.
|
|
205
|
+
|
|
206
|
+
Pure: no side effects, so tests can inspect it.
|
|
207
|
+
"""
|
|
208
|
+
...
|
|
209
|
+
|
|
210
|
+
def run(self, policy: Policy, argv: Sequence[str]) -> int:
|
|
211
|
+
"""Run ``argv`` under ``policy`` with stdio passed through.
|
|
212
|
+
|
|
213
|
+
Returns:
|
|
214
|
+
The script's exit code.
|
|
215
|
+
|
|
216
|
+
Raises:
|
|
217
|
+
SandboxError: When the sandbox cannot be set up.
|
|
218
|
+
"""
|
|
219
|
+
...
|
coldrun/sandbox/bwrap.py
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
"""Bubblewrap backend: light, no daemon, the default.
|
|
2
|
+
|
|
3
|
+
The sandbox gets new user, PID, mount, IPC, UTS and (unless ``--net full``)
|
|
4
|
+
network namespaces; bubblewrap always sets ``no_new_privs`` and leaves the
|
|
5
|
+
sandbox with no capabilities. The root is a read-only view of ``/usr`` and a
|
|
6
|
+
handful of ``/etc`` files, with private tmpfs for ``/tmp`` and the work
|
|
7
|
+
directory. ``$HOME`` and everything else on the host simply do not exist
|
|
8
|
+
inside.
|
|
9
|
+
"""
|
|
10
|
+
|
|
11
|
+
from __future__ import annotations
|
|
12
|
+
|
|
13
|
+
import os
|
|
14
|
+
import shutil
|
|
15
|
+
import subprocess
|
|
16
|
+
from pathlib import Path
|
|
17
|
+
from typing import TYPE_CHECKING
|
|
18
|
+
|
|
19
|
+
from coldrun.sandbox.base import (
|
|
20
|
+
WORKDIR,
|
|
21
|
+
Availability,
|
|
22
|
+
NetPolicy,
|
|
23
|
+
Policy,
|
|
24
|
+
SandboxError,
|
|
25
|
+
scrub_env,
|
|
26
|
+
)
|
|
27
|
+
|
|
28
|
+
if TYPE_CHECKING:
|
|
29
|
+
from collections.abc import Mapping, Sequence
|
|
30
|
+
|
|
31
|
+
#: Read-only /etc files every script may need. Missing ones are skipped.
|
|
32
|
+
_ETC_RO = ("/etc/ld.so.cache", "/etc/alternatives", "/etc/localtime", "/etc/nsswitch.conf")
|
|
33
|
+
#: Added only when the network policy allows traffic.
|
|
34
|
+
_ETC_NET = ("/etc/resolv.conf", "/etc/hosts", "/etc/ssl", "/etc/ca-certificates", "/etc/pki")
|
|
35
|
+
_USR_SYMLINKS = (
|
|
36
|
+
("usr/bin", "/bin"),
|
|
37
|
+
("usr/sbin", "/sbin"),
|
|
38
|
+
("usr/lib", "/lib"),
|
|
39
|
+
("usr/lib64", "/lib64"),
|
|
40
|
+
)
|
|
41
|
+
_TIOCSTI_SYSCTL = Path("/proc/sys/dev/tty/legacy_tiocsti")
|
|
42
|
+
_USERNS_CLONE = Path("/proc/sys/kernel/unprivileged_userns_clone")
|
|
43
|
+
_APPARMOR_USERNS = Path("/proc/sys/kernel/apparmor_restrict_unprivileged_userns")
|
|
44
|
+
_MAX_USERNS = Path("/proc/sys/user/max_user_namespaces")
|
|
45
|
+
_DOCTOR = "Run `coldrun doctor` for the fix."
|
|
46
|
+
|
|
47
|
+
|
|
48
|
+
def _read_int(path: Path) -> int | None:
|
|
49
|
+
try:
|
|
50
|
+
return int(path.read_text().strip())
|
|
51
|
+
except (OSError, ValueError):
|
|
52
|
+
return None
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def tiocsti_is_blocked() -> bool:
|
|
56
|
+
"""True when the kernel refuses TIOCSTI from unprivileged processes.
|
|
57
|
+
|
|
58
|
+
Kernels from 6.2 expose ``dev.tty.legacy_tiocsti`` and default it to 0.
|
|
59
|
+
Older kernels always allow the ioctl, which would let a sandboxed script
|
|
60
|
+
type into the user's terminal; then the sandbox gets its own session.
|
|
61
|
+
"""
|
|
62
|
+
return _read_int(_TIOCSTI_SYSCTL) == 0
|
|
63
|
+
|
|
64
|
+
|
|
65
|
+
def userns_problem() -> tuple[str, str] | None:
|
|
66
|
+
"""Return (reason, hint) when unprivileged user namespaces look disabled."""
|
|
67
|
+
if _read_int(_USERNS_CLONE) == 0:
|
|
68
|
+
return (
|
|
69
|
+
"unprivileged user namespaces are disabled (kernel.unprivileged_userns_clone=0).",
|
|
70
|
+
"Run `sudo sysctl -w kernel.unprivileged_userns_clone=1` or use --backend podman.",
|
|
71
|
+
)
|
|
72
|
+
if _read_int(_APPARMOR_USERNS) == 1:
|
|
73
|
+
return (
|
|
74
|
+
(
|
|
75
|
+
"AppArmor blocks unprivileged user namespaces "
|
|
76
|
+
"(kernel.apparmor_restrict_unprivileged_userns=1)."
|
|
77
|
+
),
|
|
78
|
+
(
|
|
79
|
+
"Run `sudo sysctl -w kernel.apparmor_restrict_unprivileged_userns=0` "
|
|
80
|
+
"or install the bubblewrap AppArmor profile."
|
|
81
|
+
),
|
|
82
|
+
)
|
|
83
|
+
if _read_int(_MAX_USERNS) == 0:
|
|
84
|
+
return (
|
|
85
|
+
"user namespaces are disabled (user.max_user_namespaces=0).",
|
|
86
|
+
"Run `sudo sysctl -w user.max_user_namespaces=15000`.",
|
|
87
|
+
)
|
|
88
|
+
return None
|
|
89
|
+
|
|
90
|
+
|
|
91
|
+
def _passwd_files(scratch: Path, uid: int, gid: int) -> tuple[Path, Path]:
|
|
92
|
+
"""Write minimal passwd and group files so the host's users stay hidden."""
|
|
93
|
+
meta = scratch / ".coldrun"
|
|
94
|
+
meta.mkdir(mode=0o700, exist_ok=True)
|
|
95
|
+
passwd = meta / "passwd"
|
|
96
|
+
group = meta / "group"
|
|
97
|
+
passwd.write_text(
|
|
98
|
+
f"root:x:0:0:root:/root:/bin/sh\ncoldrun:x:{uid}:{gid}:coldrun:{WORKDIR}:/bin/sh\n"
|
|
99
|
+
)
|
|
100
|
+
group.write_text(f"root:x:0:\ncoldrun:x:{gid}:\n")
|
|
101
|
+
return passwd, group
|
|
102
|
+
|
|
103
|
+
|
|
104
|
+
class BwrapBackend:
|
|
105
|
+
"""Build and run sandboxes with ``bwrap``."""
|
|
106
|
+
|
|
107
|
+
name = "bwrap"
|
|
108
|
+
|
|
109
|
+
def __init__(
|
|
110
|
+
self,
|
|
111
|
+
bwrap: str | None = None,
|
|
112
|
+
environ: Mapping[str, str] | None = None,
|
|
113
|
+
uid: int | None = None,
|
|
114
|
+
gid: int | None = None,
|
|
115
|
+
) -> None:
|
|
116
|
+
"""Create a backend; the arguments exist so tests can pin the host state."""
|
|
117
|
+
self._bwrap = bwrap
|
|
118
|
+
self._environ = environ if environ is not None else os.environ
|
|
119
|
+
self._uid = os.getuid() if uid is None else uid
|
|
120
|
+
self._gid = os.getgid() if gid is None else gid
|
|
121
|
+
|
|
122
|
+
@property
|
|
123
|
+
def executable(self) -> str | None:
|
|
124
|
+
"""Path to ``bwrap`` or ``None`` when it is not installed."""
|
|
125
|
+
return self._bwrap or shutil.which("bwrap")
|
|
126
|
+
|
|
127
|
+
def available(self) -> Availability:
|
|
128
|
+
"""Check for the binary and for user namespace support."""
|
|
129
|
+
if self.executable is None:
|
|
130
|
+
return Availability(
|
|
131
|
+
False,
|
|
132
|
+
"bubblewrap is not installed.",
|
|
133
|
+
"Install it: `sudo pacman -S bubblewrap` or `sudo apt install bubblewrap`.",
|
|
134
|
+
)
|
|
135
|
+
problem = userns_problem()
|
|
136
|
+
if problem is not None:
|
|
137
|
+
return Availability(False, *problem)
|
|
138
|
+
return Availability(True)
|
|
139
|
+
|
|
140
|
+
def command(
|
|
141
|
+
self, policy: Policy, argv: Sequence[str], *, tiocsti_blocked: bool | None = None
|
|
142
|
+
) -> list[str]:
|
|
143
|
+
"""Translate ``policy`` into a ``bwrap`` argument list.
|
|
144
|
+
|
|
145
|
+
Args:
|
|
146
|
+
policy: What the script may access.
|
|
147
|
+
argv: The script command, produced by a runner.
|
|
148
|
+
tiocsti_blocked: Override the kernel probe; tests use it.
|
|
149
|
+
"""
|
|
150
|
+
bwrap = self.executable or "bwrap"
|
|
151
|
+
blocked = tiocsti_is_blocked() if tiocsti_blocked is None else tiocsti_blocked
|
|
152
|
+
cmd: list[str] = [bwrap, "--unshare-all", "--die-with-parent"]
|
|
153
|
+
if policy.net == NetPolicy.FULL:
|
|
154
|
+
cmd.append("--share-net")
|
|
155
|
+
if not (policy.tty and blocked):
|
|
156
|
+
# Without a fresh session a script on an old kernel could inject
|
|
157
|
+
# keystrokes into the user's terminal through TIOCSTI.
|
|
158
|
+
cmd.append("--new-session")
|
|
159
|
+
cmd += ["--hostname", policy.hostname, "--uid", str(self._uid), "--gid", str(self._gid)]
|
|
160
|
+
|
|
161
|
+
# Read-only base system.
|
|
162
|
+
cmd += ["--ro-bind", "/usr", "/usr"]
|
|
163
|
+
for target, link in _USR_SYMLINKS:
|
|
164
|
+
cmd += ["--symlink", target, link]
|
|
165
|
+
for etc in _ETC_RO:
|
|
166
|
+
cmd += ["--ro-bind-try", etc, etc]
|
|
167
|
+
if policy.net != NetPolicy.NONE:
|
|
168
|
+
for etc in _ETC_NET:
|
|
169
|
+
cmd += ["--ro-bind-try", etc, etc]
|
|
170
|
+
passwd, group = _passwd_files(policy.scratch, self._uid, self._gid)
|
|
171
|
+
cmd += ["--ro-bind", str(passwd), "/etc/passwd", "--ro-bind", str(group), "/etc/group"]
|
|
172
|
+
|
|
173
|
+
# Kernel interfaces and private writable space.
|
|
174
|
+
cmd += ["--proc", "/proc", "--dev", "/dev"]
|
|
175
|
+
cmd += ["--tmpfs", "/tmp", "--tmpfs", "/run"] # noqa: S108 - guest paths
|
|
176
|
+
cmd += ["--bind", str(policy.scratch), WORKDIR]
|
|
177
|
+
cmd += ["--ro-bind", str(policy.script), policy.guest_script]
|
|
178
|
+
for p in policy.ro_paths:
|
|
179
|
+
cmd += ["--ro-bind", str(p), str(p)]
|
|
180
|
+
for p in policy.rw_paths:
|
|
181
|
+
cmd += ["--bind", str(p), str(p)]
|
|
182
|
+
# Everything not bound above lives on bwrap's root tmpfs; freeze it.
|
|
183
|
+
cmd += ["--remount-ro", "/", "--chdir", WORKDIR]
|
|
184
|
+
|
|
185
|
+
# Scrubbed environment.
|
|
186
|
+
cmd.append("--clearenv")
|
|
187
|
+
for name, value in scrub_env(self._environ, policy.env).items():
|
|
188
|
+
cmd += ["--setenv", name, value]
|
|
189
|
+
|
|
190
|
+
cmd.append("--")
|
|
191
|
+
cmd.extend(argv)
|
|
192
|
+
return cmd
|
|
193
|
+
|
|
194
|
+
def probe(self) -> None:
|
|
195
|
+
"""Start an empty sandbox once to surface setup errors before the real run.
|
|
196
|
+
|
|
197
|
+
Raises:
|
|
198
|
+
SandboxError: With bubblewrap's own message and a hint.
|
|
199
|
+
"""
|
|
200
|
+
avail = self.available()
|
|
201
|
+
if not avail.ok:
|
|
202
|
+
raise SandboxError(avail.reason, avail.hint)
|
|
203
|
+
bwrap = self.executable
|
|
204
|
+
assert bwrap is not None # noqa: S101 - established by available()
|
|
205
|
+
cmd = [
|
|
206
|
+
bwrap, "--unshare-all", "--die-with-parent", "--new-session",
|
|
207
|
+
"--ro-bind", "/usr", "/usr", "--symlink", "usr/bin", "/bin",
|
|
208
|
+
"--symlink", "usr/lib", "/lib", "--symlink", "usr/lib64", "/lib64",
|
|
209
|
+
"--proc", "/proc", "--dev", "/dev", "--", "/bin/true",
|
|
210
|
+
] # fmt: skip
|
|
211
|
+
try:
|
|
212
|
+
result = subprocess.run(cmd, capture_output=True, text=True, check=False, timeout=30) # noqa: S603 - fixed argv
|
|
213
|
+
except (OSError, subprocess.TimeoutExpired) as exc:
|
|
214
|
+
raise SandboxError(f"bubblewrap could not start: {exc}.", _DOCTOR) from exc
|
|
215
|
+
if result.returncode != 0:
|
|
216
|
+
detail = result.stderr.strip().splitlines()[-1:] or [f"exit {result.returncode}"]
|
|
217
|
+
raise SandboxError(f"bubblewrap failed to create a sandbox: {detail[0]}.", _DOCTOR)
|
|
218
|
+
|
|
219
|
+
def run(self, policy: Policy, argv: Sequence[str]) -> int:
|
|
220
|
+
"""Probe, then run with stdin, stdout and stderr inherited."""
|
|
221
|
+
self.probe()
|
|
222
|
+
cmd = self.command(policy, argv)
|
|
223
|
+
try:
|
|
224
|
+
return subprocess.run(cmd, check=False).returncode # noqa: S603 - argv built by command()
|
|
225
|
+
except OSError as exc:
|
|
226
|
+
raise SandboxError(f"could not start bubblewrap: {exc}.", _DOCTOR) from exc
|
coldrun/vet/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"""Vetting engine: findings, rules and risk scoring."""
|
coldrun/vet/findings.py
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
"""Finding model shared by runners and the vetting engine.
|
|
2
|
+
|
|
3
|
+
Scoring and aggregation arrive with the vetting milestone; this module only
|
|
4
|
+
defines what a single finding looks like so runners can emit them.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from enum import Enum
|
|
11
|
+
from typing import TYPE_CHECKING
|
|
12
|
+
|
|
13
|
+
if TYPE_CHECKING:
|
|
14
|
+
from pathlib import Path
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
class Severity(str, Enum):
|
|
18
|
+
"""How much a finding should worry the user.
|
|
19
|
+
|
|
20
|
+
``INFO`` is shown but never changes the verdict. The other three feed the
|
|
21
|
+
risk score: low runs, medium asks, high refuses.
|
|
22
|
+
"""
|
|
23
|
+
|
|
24
|
+
INFO = "info"
|
|
25
|
+
LOW = "low"
|
|
26
|
+
MEDIUM = "medium"
|
|
27
|
+
HIGH = "high"
|
|
28
|
+
|
|
29
|
+
@property
|
|
30
|
+
def rank(self) -> int:
|
|
31
|
+
"""Numeric order so severities can be compared and maxed."""
|
|
32
|
+
return _RANK[self]
|
|
33
|
+
|
|
34
|
+
|
|
35
|
+
_RANK = {Severity.INFO: 0, Severity.LOW: 1, Severity.MEDIUM: 2, Severity.HIGH: 3}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
@dataclass(frozen=True, slots=True)
|
|
39
|
+
class Finding:
|
|
40
|
+
"""One observation about a script or dependency.
|
|
41
|
+
|
|
42
|
+
Every finding carries a rule ID, a severity, the file it was found in, the
|
|
43
|
+
line when one applies, and a one-line explanation the user can act on.
|
|
44
|
+
"""
|
|
45
|
+
|
|
46
|
+
rule_id: str
|
|
47
|
+
severity: Severity
|
|
48
|
+
file: Path
|
|
49
|
+
message: str
|
|
50
|
+
line: int | None = None
|
|
51
|
+
|
|
52
|
+
def __post_init__(self) -> None:
|
|
53
|
+
"""Reject findings that would be useless to the user."""
|
|
54
|
+
if not self.rule_id:
|
|
55
|
+
msg = "a finding needs a rule_id"
|
|
56
|
+
raise ValueError(msg)
|
|
57
|
+
if not self.message:
|
|
58
|
+
msg = f"{self.rule_id}: a finding needs a one-line message"
|
|
59
|
+
raise ValueError(msg)
|
|
60
|
+
if self.line is not None and self.line < 1:
|
|
61
|
+
msg = f"{self.rule_id}: line numbers start at 1, got {self.line}"
|
|
62
|
+
raise ValueError(msg)
|
|
63
|
+
|
|
64
|
+
def location(self) -> str:
|
|
65
|
+
"""Return ``file:line`` or just ``file`` for display."""
|
|
66
|
+
return f"{self.file}:{self.line}" if self.line is not None else str(self.file)
|