문제: `test:system` 사전 점검은 system manager bus(`systemctl show-environment`)와 실행 파일 셋만 보고 PASS를 냈다. provider 본 단계는 `/usr/bin/prlimit`·`/usr/bin/systemd-run`을 쓰고, user manager 버전(254 이상)을 묻고, `systemd-run --user --scope`로 cgroup 한도를 강제한다. 그래서 user bus가 없거나 버전이 낮거나 controller가 위임되지 않은 호스트는 PASS 뒤 provider 시험마다 `provider cgroup unavailable: ...`로 떨어졌다. 고친 것: 점검이 prlimit·systemd-run 실행 가능 여부를 보고, provider와 같은 인자(`USER_MANAGER_VERSION_ARGUMENTS`)로 user manager 버전을 묻고, provider scope와 같은 속성·같은 cgroup 강제 확인으로 `/bin/true`를 한 번 띄운다. scope 인자와 최소 버전은 `scripts/lib/provider-cgroup.ts` 한 곳에 두고 provider와 점검이 같이 쓴다. system bus 점검은 provider가 쓰지 않아 user manager 점검으로 바꿨다. 위임 controller 값은 scope 안의 강제 확인(memory.max·pids.max·cpu.max)이 실제로 읽어 보므로 UNVERIFIED로 남길 몫이 없다. 위험·한계: 점검이 user scope 하나를 띄웠다 지운다(`--collect`, 5초 상한). 시스템 컨테이너 안(root)에서도 provider와 같은 호출이라 같은 결과를 낸다고 보고, FE-GATE-013으로 확인한다. 검증: desktop `scripts/verify.sh exec`로 `node scripts/run-vitest.ts run tests/unit/system-test-prerequisites.test.ts` 등 7파일 134건 통과. 점검 코드를 기준 커밋으로 되돌리면 새 시험 6건이 실패한다(RED). Refs: 1112/08-03
249 lines
9.0 KiB
TypeScript
249 lines
9.0 KiB
TypeScript
export type ProviderKind = "vulnerability" | "provenance";
|
|
|
|
/** The oldest systemd user manager whose `--scope` properties the provider relies on. */
|
|
export const MINIMUM_PROVIDER_SYSTEMD_VERSION = 254;
|
|
|
|
/** `systemctl` arguments that ask the user manager its version; the provider and the prerequisite check both use them. */
|
|
export const USER_MANAGER_VERSION_ARGUMENTS: readonly string[] = Object.freeze([
|
|
"--user",
|
|
"show",
|
|
"--property=Version",
|
|
"--value",
|
|
]);
|
|
|
|
const MEMORY_MAX = 1_073_741_824;
|
|
const TASKS_MAX = 64;
|
|
const STOP_TIMEOUT_MS = 5_000;
|
|
const RUNTIME_GRACE_MS = 10_000;
|
|
const UNIT_NAME = /^ca-provider-(?:vulnerability|provenance)-[1-9][0-9]*-[0-9a-f]{24}\.scope$/u;
|
|
const PROBE_UNIT_NAME = /^ca-provider-prerequisite-[1-9][0-9]*-[0-9a-f]{24}\.scope$/u;
|
|
/** How long the prerequisite probe's scope may live; it runs /bin/true. */
|
|
const PROBE_RUNTIME_MS = 5_000;
|
|
const UNIT_NONCE = /^[0-9a-f]{24}$/u;
|
|
const ENVIRONMENT_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/u;
|
|
const ENFORCEMENT_GATE = [
|
|
'cgroup_path=""',
|
|
"while IFS=: read -r hierarchy controllers candidate; do",
|
|
' if [ "$hierarchy" = 0 ] && [ -z "$controllers" ]; then cgroup_path=$candidate; fi',
|
|
"done < /proc/self/cgroup",
|
|
'if [ -z "$cgroup_path" ]; then',
|
|
" printf '%s\\n' 'provider cgroup enforcement failed: unified cgroup v2 membership is required' >&2",
|
|
" exit 125",
|
|
"fi",
|
|
'case "$cgroup_path" in',
|
|
' */"$0") ;;',
|
|
" *)",
|
|
" printf '%s\\n' 'provider cgroup enforcement failed: unit membership is invalid' >&2",
|
|
" exit 125",
|
|
" ;;",
|
|
"esac",
|
|
"cgroup_root=/sys/fs/cgroup$cgroup_path",
|
|
"require_cgroup_value() {",
|
|
' actual=$(/bin/cat "$cgroup_root/$1") || {',
|
|
" printf 'provider cgroup enforcement failed: cannot read %s\\n' \"$1\" >&2",
|
|
" exit 125",
|
|
" }",
|
|
' if [ "$actual" != "$2" ]; then',
|
|
" printf 'provider cgroup enforcement failed: %s is %s, expected %s\\n' \"$1\" \"$actual\" \"$2\" >&2",
|
|
" exit 125",
|
|
" fi",
|
|
"}",
|
|
`require_cgroup_value memory.max ${MEMORY_MAX}`,
|
|
"require_cgroup_value memory.swap.max 0",
|
|
`require_cgroup_value pids.max ${TASKS_MAX}`,
|
|
"require_cgroup_value cpu.max '100000 100000'",
|
|
'exec "$@"',
|
|
].join("\n");
|
|
|
|
export function formatProviderCgroupUnitName(
|
|
kind: ProviderKind,
|
|
supervisorPid: number,
|
|
nonce: string,
|
|
): string {
|
|
if (!Number.isSafeInteger(supervisorPid) || supervisorPid <= 0 || !UNIT_NONCE.test(nonce)) {
|
|
throw new TypeError("provider cgroup unit identity is invalid");
|
|
}
|
|
const unit = `ca-provider-${kind}-${supervisorPid}-${nonce}.scope`;
|
|
assertUnit(unit);
|
|
return unit;
|
|
}
|
|
|
|
export function systemdRunProviderArguments(
|
|
unit: string,
|
|
timeoutMs: number,
|
|
cpuSeconds: number,
|
|
nodeExecutable: string,
|
|
wrapperScript: string,
|
|
reportPath: string,
|
|
reportDev: number,
|
|
reportIno: number,
|
|
): string[] {
|
|
assertUnit(unit);
|
|
if (!Number.isSafeInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > Number.MAX_SAFE_INTEGER - RUNTIME_GRACE_MS) {
|
|
throw new TypeError("provider cgroup runtime is invalid");
|
|
}
|
|
if (!Number.isSafeInteger(cpuSeconds) || cpuSeconds <= 0) {
|
|
throw new TypeError("provider cgroup CPU limit is invalid");
|
|
}
|
|
if (
|
|
!nodeExecutable.startsWith("/") || !wrapperScript.startsWith("/") ||
|
|
!reportPath.startsWith("/") || reportPath.includes("\0") ||
|
|
!Number.isSafeInteger(reportDev) || reportDev <= 0 ||
|
|
!Number.isSafeInteger(reportIno) || reportIno <= 0
|
|
) {
|
|
throw new TypeError("provider scope wrapper path is invalid");
|
|
}
|
|
return [
|
|
...scopeArguments(unit, timeoutMs + RUNTIME_GRACE_MS),
|
|
nodeExecutable,
|
|
wrapperScript,
|
|
String(cpuSeconds),
|
|
reportPath,
|
|
String(reportDev),
|
|
String(reportIno),
|
|
];
|
|
}
|
|
|
|
export function formatProviderPrerequisiteUnitName(supervisorPid: number, nonce: string): string {
|
|
if (!Number.isSafeInteger(supervisorPid) || supervisorPid <= 0 || !UNIT_NONCE.test(nonce)) {
|
|
throw new TypeError("provider cgroup unit identity is invalid");
|
|
}
|
|
return `ca-provider-prerequisite-${supervisorPid}-${nonce}.scope`;
|
|
}
|
|
|
|
/**
|
|
* 1112/08-03. The provider's own scope — same properties, same check that the
|
|
* unit's cgroup enforces them — around /bin/true. A host whose user manager
|
|
* cannot start the scope, or does not delegate the memory, pids and cpu
|
|
* controllers, fails here instead of in each provider test.
|
|
*/
|
|
export function systemdRunPrerequisiteProbeArguments(unit: string): string[] {
|
|
if (!PROBE_UNIT_NAME.test(unit)) throw new TypeError("provider cgroup unit is invalid");
|
|
return [...scopeArguments(unit, PROBE_RUNTIME_MS), "/bin/true"];
|
|
}
|
|
|
|
/** `systemd-run` options and the enforcement gate up to its `$0`; the caller appends what the gate execs. */
|
|
function scopeArguments(unit: string, runtimeMaxMs: number): string[] {
|
|
return [
|
|
"--user",
|
|
"--scope",
|
|
"--collect",
|
|
"--quiet",
|
|
"--expand-environment=no",
|
|
`--unit=${unit}`,
|
|
`--property=MemoryMax=${MEMORY_MAX}`,
|
|
"--property=MemorySwapMax=0",
|
|
`--property=TasksMax=${TASKS_MAX}`,
|
|
"--property=CPUQuota=100%",
|
|
"--property=CPUQuotaPeriodSec=100ms",
|
|
"--property=KillMode=control-group",
|
|
"--property=SendSIGKILL=yes",
|
|
`--property=TimeoutStopSec=${STOP_TIMEOUT_MS}ms`,
|
|
`--property=RuntimeMaxSec=${runtimeMaxMs}ms`,
|
|
"--",
|
|
"/bin/sh",
|
|
"-eu",
|
|
"-c",
|
|
ENFORCEMENT_GATE,
|
|
unit,
|
|
];
|
|
}
|
|
|
|
export type ProviderScopeFrame = Readonly<{
|
|
bwrapInput: Buffer;
|
|
/**
|
|
* The sandboxed command, kept out of the args file on purpose.
|
|
*
|
|
* `bwrap --args FD` splices the file's options into the option stream, but
|
|
* bubblewrap stops at the first non-option and never propagates the command
|
|
* back out of the recursive parse. A command written into the args file is
|
|
* therefore silently dropped and bubblewrap exits with its usage text, so
|
|
* the sandbox is never entered and the provider produces no evidence at all.
|
|
* Only the options may be hidden; the command travels on real argv.
|
|
*
|
|
* Nothing secret lives here: credentials and the provider command reach the
|
|
* sandbox through `--setenv` inside the args file, and this vector only ever
|
|
* names `prlimit` and a shell that expands `$PROVIDER_COMMAND`.
|
|
*/
|
|
bwrapCommand: readonly string[];
|
|
reportPath: string;
|
|
reportDev: number;
|
|
reportIno: number;
|
|
}>;
|
|
|
|
export function encodeProviderScopeFrame(input: ProviderScopeFrame): Buffer {
|
|
if (
|
|
!Buffer.isBuffer(input.bwrapInput) || input.bwrapInput.byteLength === 0 ||
|
|
!input.reportPath.startsWith("/") || input.reportPath.includes("\0") ||
|
|
!Number.isSafeInteger(input.reportDev) || input.reportDev <= 0 ||
|
|
!Number.isSafeInteger(input.reportIno) || input.reportIno <= 0
|
|
) {
|
|
throw new TypeError("provider scope frame is invalid");
|
|
}
|
|
assertBwrapCommand(input.bwrapCommand);
|
|
const payload = Buffer.from(JSON.stringify({
|
|
bwrapInputBase64: input.bwrapInput.toString("base64"),
|
|
bwrapCommand: [...input.bwrapCommand],
|
|
reportPath: input.reportPath,
|
|
reportDev: input.reportDev,
|
|
reportIno: input.reportIno,
|
|
}));
|
|
const frame = Buffer.allocUnsafe(4 + payload.byteLength);
|
|
frame.writeUInt32BE(payload.byteLength, 0);
|
|
payload.copy(frame, 4);
|
|
return frame;
|
|
}
|
|
|
|
/**
|
|
* The command vector bubblewrap will exec. It has to be an absolute executable
|
|
* so the sandbox never resolves it through a `PATH` the caller controls.
|
|
*/
|
|
export function assertBwrapCommand(command: readonly string[]): void {
|
|
if (
|
|
!Array.isArray(command) || command.length === 0 ||
|
|
typeof command[0] !== "string" || !command[0].startsWith("/") ||
|
|
command.some((argument) =>
|
|
typeof argument !== "string" || argument.includes("\0"),
|
|
)
|
|
) {
|
|
throw new TypeError("provider bwrap command is invalid");
|
|
}
|
|
}
|
|
|
|
export function encodeProviderBwrapInput(
|
|
optionArguments: readonly string[],
|
|
environment: Readonly<Record<string, string | undefined>>,
|
|
): Buffer {
|
|
if (optionArguments.some((argument) => argument.includes("\0"))) {
|
|
throw new TypeError("provider bwrap argument is invalid");
|
|
}
|
|
// A bare `--` ends bubblewrap's option stream. Inside an args file that also
|
|
// ends the recursive parse, so everything after it is discarded rather than
|
|
// executed. Refusing it here keeps the drop from being reintroduced by a
|
|
// caller that appends a command to the option list.
|
|
if (optionArguments.includes("--")) {
|
|
throw new TypeError("provider bwrap options may not terminate the option stream");
|
|
}
|
|
const entries = Object.entries(environment).sort(([left], [right]) =>
|
|
left < right ? -1 : left > right ? 1 : 0,
|
|
);
|
|
if (entries.some(([name, value]) =>
|
|
!ENVIRONMENT_NAME.test(name) || value === undefined || value.includes("\0")
|
|
)) {
|
|
throw new TypeError("provider bwrap environment is invalid");
|
|
}
|
|
const input = ["--clearenv"];
|
|
for (const [name, value] of entries) input.push("--setenv", name, value ?? "");
|
|
input.push(...optionArguments);
|
|
return Buffer.from(`${input.join("\0")}\0`);
|
|
}
|
|
|
|
export function systemctlKillProviderArguments(unit: string): string[] {
|
|
assertUnit(unit);
|
|
return ["--user", "kill", "--kill-whom=all", "--signal=SIGKILL", unit];
|
|
}
|
|
|
|
function assertUnit(unit: string): void {
|
|
if (!UNIT_NAME.test(unit)) throw new TypeError("provider cgroup unit name is invalid");
|
|
}
|