From c94c3939f1926bc644f228ee74df6d4bc4ae0ec5 Mon Sep 17 00:00:00 2001 From: Kevin Janssen Date: Tue, 17 Nov 2026 17:40:42 +0100 Subject: [PATCH] Validate the full Windows Update plan through its fixed script revision --- web/src/plan-bytes.ts | 18 +++++++++++++++++ web/src/safety.ts | 35 ++++++++++----------------------- web/src/script-console.test.tsx | 18 +++++++++++++---- web/src/script-console.ts | 7 +++++-- 4 files changed, 47 insertions(+), 31 deletions(-) create mode 100644 web/src/plan-bytes.ts diff --git a/web/src/plan-bytes.ts b/web/src/plan-bytes.ts new file mode 100644 index 0000000..7269a8f --- /dev/null +++ b/web/src/plan-bytes.ts @@ -0,0 +1,18 @@ +export const hashPattern = /^[0-9a-f]{64}$/; +export function parseStrictJson(source: string): unknown { + if (new TextEncoder().encode(source).length > 1048576) throw new Error('JSON über 1 MiB'); + let i = 0; + const space = () => { while (/\s/.test(source[i] ?? '') && i < source.length) i++; }; + const string = (): string => { const start = i++; while (i < source.length) { if (source[i] === '\\') i += 2; else if (source[i++] === '"') return JSON.parse(source.slice(start, i)); } throw new Error('Ungültiger JSON-String'); }; + const value = (depth: number): void => { + if (depth > 64) throw new Error('JSON zu tief verschachtelt'); space(); + if (source[i] === '{') { i++; space(); const keys = new Set(); if (source[i] === '}') { i++; return; } + while (i < source.length) { space(); if (source[i] !== '"') throw new Error('JSON-Objektschlüssel erwartet'); const key = string(); if (keys.has(key)) throw new Error(`Doppeltes JSON-Feld: ${key}`); keys.add(key); space(); if (source[i++] !== ':') throw new Error('JSON-Doppelpunkt erwartet'); value(depth + 1); space(); const end = source[i++]; if (end === '}') return; if (end !== ',') throw new Error('Ungültiges JSON-Objekt'); } throw new Error('Unvollständiges JSON-Objekt'); } + if (source[i] === '[') { i++; space(); if (source[i] === ']') { i++; return; } while (i < source.length) { value(depth + 1); space(); const end = source[i++]; if (end === ']') return; if (end !== ',') throw new Error('Ungültiges JSON-Array'); } throw new Error('Unvollständiges JSON-Array'); } + if (source[i] === '"') { string(); return; } + const token = /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(source.slice(i)); if (!token) throw new Error('Ungültiger JSON-Wert'); i += token[0].length; + }; + value(0); space(); if (i !== source.length) throw new Error('Zusätzliche JSON-Daten'); return JSON.parse(source); +} +export function bytes(value: unknown): Uint8Array { if (!Array.isArray(value) || !value.length || value.length > 1048576 || value.some(n => !Number.isInteger(n) || n < 0 || n > 255)) throw new Error('Exakte Bytefolge fehlt'); return new Uint8Array(value); } +export async function sha256(value: Uint8Array): Promise { return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', value)), n => n.toString(16).padStart(2, '0')).join(''); } diff --git a/web/src/safety.ts b/web/src/safety.ts index 5d04539..29f7a58 100644 --- a/web/src/safety.ts +++ b/web/src/safety.ts @@ -1,32 +1,19 @@ import { Action, PlanInput, RecordValue, Session, planTargetPreviews, record, text, validateSystemService, validateWindowsReboot, windowsScriptProfile, logWindow, validateWindowsLogLimits, windowsEventLogFixtureSource, windowsEventLogFixtureChannel, windowsEventLogFixtureProvider, WindowsMsiManifest, MsiPostcondition, windowsMsi, windowsMsiManifest, windowsMsiAction, validateWindowsMsiInput, validateWindowsMsiLimits, msiUuid, fullMaintenanceScriptProfile, privilegedScriptProfile, validateScriptIdentityProfile } from './api'; import { validateAgentUpdateAction } from './agent-updates'; -export const hashPattern = /^[0-9a-f]{64}$/; +import { bytes, hashPattern, parseStrictJson, sha256 } from './plan-bytes'; +import { verifyScriptPlan } from './script-console'; +export { bytes, hashPattern, parseStrictJson, sha256 } from './plan-bytes'; export const rootWarning = 'HOHES RISIKO: root kann das Zielsystem verändern. Keine automatische Rechteerhöhung; eigener expliziter Plan, Scope, Helper und Genehmigung erforderlich.'; export const systemWarning = 'SYSTEM: ausschließlich fest benannter Windows-Fixturedienst (running/stopped) oder eigenes festes MSI-Rezept. Eigenes system:execute, unabhängiger Helper und konkrete WebUI-Genehmigung erforderlich. Keine SYSTEM-Shell, kein impliziter Reboot oder Retry.'; export const fullMaintenanceWarning = 'VOLLE HOSTWARTUNG · full_maintenance_v1: Das genehmigte Skript läuft als root/SYSTEM mit vollständiger Hostautorität, einschließlich Netzwerk, Dateisystem und Diensten. Es kann auch Agent, PKI und Schutzmechanismen ändern oder einen Neustart auslösen. Keine Sandbox- oder No-Reboot-Zusage. scripts:execute plus root:execute/system:execute, lokaler und zentraler Opt-in, passende Capability, unabhängiger Helper und konkrete WebUI-Genehmigung bleiben erforderlich.'; export function permissions(auth: Session): string[] | null { return auth.permissions ?? null; } export function allowed(auth: Session, permission: string): boolean { return permissions(auth)?.includes(permission) === true; } export function availableActions(auth: Session, base: readonly Action[]): Action[] { return base.filter(a => a !== 'apt_native_acceptance' || auth.principal.simulated === true); } -export function parseStrictJson(source: string): unknown { - if (new TextEncoder().encode(source).length > 1048576) throw new Error('JSON über 1 MiB'); - let i = 0; - const space = () => { while (/\s/.test(source[i] ?? '') && i < source.length) i++; }; - const string = (): string => { const start = i++; while (i < source.length) { if (source[i] === '\\') i += 2; else if (source[i++] === '"') return JSON.parse(source.slice(start, i)); } throw new Error('Ungültiger JSON-String'); }; - const value = (depth: number): void => { - if (depth > 64) throw new Error('JSON zu tief verschachtelt'); space(); - if (source[i] === '{') { i++; space(); const keys = new Set(); if (source[i] === '}') { i++; return; } - while (i < source.length) { space(); if (source[i] !== '"') throw new Error('JSON-Objektschlüssel erwartet'); const key = string(); if (keys.has(key)) throw new Error(`Doppeltes JSON-Feld: ${key}`); keys.add(key); space(); if (source[i++] !== ':') throw new Error('JSON-Doppelpunkt erwartet'); value(depth + 1); space(); const end = source[i++]; if (end === '}') return; if (end !== ',') throw new Error('Ungültiges JSON-Objekt'); } throw new Error('Unvollständiges JSON-Objekt'); } - if (source[i] === '[') { i++; space(); if (source[i] === ']') { i++; return; } while (i < source.length) { value(depth + 1); space(); const end = source[i++]; if (end === ']') return; if (end !== ',') throw new Error('Ungültiges JSON-Array'); } throw new Error('Unvollständiges JSON-Array'); } - if (source[i] === '"') { string(); return; } - const token = /^(?:true|false|null|-?(?:0|[1-9]\d*)(?:\.\d+)?(?:[eE][+-]?\d+)?)/.exec(source.slice(i)); if (!token) throw new Error('Ungültiger JSON-Wert'); i += token[0].length; - }; - value(0); space(); if (i !== source.length) throw new Error('Zusätzliche JSON-Daten'); return JSON.parse(source); -} + function exact(r: RecordValue, fields: string[]) { if (Object.keys(r).some(k => !fields.includes(k)) || fields.some(k => !(k in r))) throw new Error('Schemafelder fehlen oder sind unbekannt'); } function hash(v: unknown) { if (typeof v !== 'string' || !hashPattern.test(v) || /^0{64}$/.test(v)) throw new Error('Exakter SHA-256 fehlt/Platzhalter'); } -export function bytes(value: unknown): Uint8Array { if (!Array.isArray(value) || !value.length || value.length > 1048576 || value.some(n => !Number.isInteger(n) || n < 0 || n > 255)) throw new Error('Exakte Bytefolge fehlt'); return new Uint8Array(value); } -export async function sha256(value: Uint8Array): Promise { return Array.from(new Uint8Array(await crypto.subtle.digest('SHA-256', value)), n => n.toString(16).padStart(2, '0')).join(''); } + function canonical(v: unknown): string { if (Array.isArray(v)) return `[${v.map(canonical).join(',')}]`; if (v !== null && typeof v === 'object') return `{${Object.entries(v).sort(([a], [b]) => a.localeCompare(b)).map(([k, x]) => `${JSON.stringify(k)}:${canonical(x)}`).join(',')}}`; return JSON.stringify(v); } export function validateAptManifest(value: unknown, acceptance: boolean): RecordValue { const m = record(value, 'apt_manifest'); @@ -361,6 +348,10 @@ export async function verifyPlanIntegrity(plan: RecordValue) { validateMsiViews(plan, rawJobs); systemJobs = scriptPayloads(rawJobs).filter(payload => payload.execution_identity === 'system'); } + if (systemJobs.some(payload => record(payload.action).action === 'run_script')) { + // One verifier binds the execution budget to the catalog revision, script bytes and fixed parameters. + await verifyScriptPlan(plan); + } for (const payload of systemJobs) { const action = record(payload.action); if (action.action === 'reboot') { @@ -374,13 +365,7 @@ export async function verifyPlanIntegrity(plan: RecordValue) { continue; } if (isMsi(payload)) continue; // Fully validated, hash-bound package projection above. - if (action.action === 'run_script') { - validateScriptIdentityProfile(action, payload.execution_identity, action.interpreter); - if (privilegedScriptProfile(action, payload.execution_identity) !== fullMaintenanceScriptProfile || action.interpreter !== 'powershell' - || !Number.isInteger(payload.max_runtime_seconds) || Number(payload.max_runtime_seconds) < 1 || Number(payload.max_runtime_seconds) > 120 - || !Number.isInteger(payload.max_output_bytes) || Number(payload.max_output_bytes) < 1 || Number(payload.max_output_bytes) > 65536) throw new Error('SYSTEM-Skript benötigt explizites Vollwartungsprofil und feste Budgets'); - continue; - } + if (action.action === 'run_script') continue; exact(action, ['action', 'unit', 'state']); if (action.action !== 'set_service_state') throw new Error('SYSTEM-Plan enthält keine typisierte Dienstaktion'); validateSystemService(action.unit, action.state, payload.max_runtime_seconds, payload.max_output_bytes); diff --git a/web/src/script-console.test.tsx b/web/src/script-console.test.tsx index 08a0e0d..cfa8dfd 100644 --- a/web/src/script-console.test.tsx +++ b/web/src/script-console.test.tsx @@ -53,22 +53,32 @@ it('shows the immutable library revision and rejects a different catalog script it('accepts one hour only for the exact Windows Update revision', async () => { const source = readFileSync(new URL('../../crates/domain/src/windows_update.ps1', import.meta.url), 'utf8'); - async function windowPlan(script: string, fixed: boolean, seconds: number) { + async function windowPlan(script: string, fixed: boolean, seconds: number, args: string[] = [], expected: string | null = null, claimedHash?: string) { const original = plan('windows_system_full'); const parsed = record(JSON.parse(new TextDecoder().decode(new Uint8Array(original.plan_payload_bytes as number[])))); const job = (parsed.jobs as RecordValue[])[0]!, payload = record(job.payload), action = record(payload.action); - action.script_utf8 = script; action.arguments = []; action.expected_stdout = null; payload.max_runtime_seconds = seconds; + action.script_utf8 = script; action.arguments = args; action.expected_stdout = expected; payload.max_runtime_seconds = seconds; job.script_sha256 = await sha256(new TextEncoder().encode(script)); + if (claimedHash) job.script_sha256 = claimedHash; job.job_payload_hash = await sha256(new TextEncoder().encode(JSON.stringify(payload))); if (fixed) parsed.script_revision = { revision_id: parsed.plan_id, name: 'Windows-Updates installieren', version: 1, script_sha256: job.script_sha256 }; const raw = new TextEncoder().encode(JSON.stringify(parsed)); return { plan_hash: await sha256(raw), plan_payload_bytes: Array.from(raw) }; } const valid = await windowPlan(source, true, 3600); - await verifyScriptPlan(valid); expect(scriptPlanJobs(valid)[0]?.runtimeSeconds).toBe(3600); - for (const bad of [await windowPlan(source+'\n',true,3600), await windowPlan(source,false,3600), await windowPlan(source,true,3601)]) { + await verifyPlanIntegrity(valid); await verifyScriptPlan(valid); + expect(scriptPlanJobs(valid)[0]?.runtimeSeconds).toBe(3600); + const templateHash = await sha256(new TextEncoder().encode(source)); + for (const bad of [ + await windowPlan(source+'\n',true,3600), await windowPlan(source,false,3600), + await windowPlan(source,true,3601), await windowPlan(source,true,3600,['x']), + await windowPlan(source,true,3600,[],'unexpected'), + await windowPlan('Write-Output 1',true,121,[],null,templateHash) + ]) { + await expect(verifyPlanIntegrity(bad)).rejects.toThrow(); await expect(verifyScriptPlan(bad)).rejects.toThrow(); } + await verifyPlanIntegrity(await windowPlan('Write-Output 1',true,120)); }); it('rejects view, byte and fixed identity/budget/profile tampering before and after display', async () => { diff --git a/web/src/script-console.ts b/web/src/script-console.ts index 3174cf1..e10a1a0 100644 --- a/web/src/script-console.ts +++ b/web/src/script-console.ts @@ -1,5 +1,5 @@ import { canonicalJson, record, RecordValue, text, windowsScriptProfile, privilegedScriptProfile, fullMaintenanceScriptProfile, validateScriptIdentityProfile } from './api'; -import { bytes, hashPattern, parseStrictJson, sha256 } from './safety'; +import { bytes, hashPattern, parseStrictJson, sha256 } from './plan-bytes'; export const windowsUpdateScriptHash = '0fa5f513a06b6cf902a3f9ac1989987642c181eedd6c305b3912771bd10f2ebf'; export interface ScriptPlanJob { @@ -56,7 +56,10 @@ function validateViews(plan: RecordValue, parsed: RecordValue, jobs: RecordValue * This is an approval display check, never a grant of execution rights. */ export async function verifyScriptPlan(plan: RecordValue): Promise { const before = snapshot(plan), old = verified.get(plan); - if (old && old.snapshot !== before) throw new Error('Skriptplan wurde nach Anzeige verändert'); + if (old) { + if (old.snapshot !== before) throw new Error('Skriptplan wurde nach Anzeige verändert'); + return; + } const raw = bytes(plan.plan_payload_bytes); if (await sha256(raw) !== digest(plan.plan_hash)) throw new Error('Skript-Planhash widerspricht gespeicherten Bytes'); const parsed = record(parseStrictJson(new TextDecoder('utf-8', { fatal: true }).decode(raw)));