forked from mtusi2026/mtusi2026lab7
525 lines
16 KiB
TypeScript
525 lines
16 KiB
TypeScript
import { readFile, copyFile, mkdir, writeFile } from "node:fs/promises";
|
|
import { resolve } from "node:path";
|
|
import {
|
|
root,
|
|
local,
|
|
run,
|
|
compose,
|
|
privateWrite,
|
|
requireThat,
|
|
} from "../scripts/runtime";
|
|
import { unlock, unseal } from "../scripts/openbao-operator";
|
|
import { bao } from "../scripts/bao-client";
|
|
import { parseKV } from "../scripts/kv-secrets";
|
|
import { issue } from "../scripts/pki";
|
|
import { reloadGateway } from "../scripts/reload-gateway";
|
|
import { containerID, containerIP } from "../scripts/runtime-inspect";
|
|
import { tlsProbe, expectDenied } from "./transport";
|
|
import { waitReady } from "./wait";
|
|
import { auditArtifacts } from "./artifacts";
|
|
import { workerCompromise } from "../scripts/rotation";
|
|
import { HTTP } from "./http";
|
|
import { publicLBEndpoint } from "../scripts/public-endpoint";
|
|
import { createSealedShutdown } from "../scripts/sealed-shutdown";
|
|
import { type GitTrackingSource } from "../scripts/git-tracking-proof";
|
|
import {
|
|
createHealthConvergence,
|
|
freshSecretsAfterSeal,
|
|
} from "../scripts/health-convergence";
|
|
const health =
|
|
"GET /health/ready HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n";
|
|
function opensslDate(timestamp: number) {
|
|
return (
|
|
new Date(timestamp).toISOString().replace(/[-:T]/g, "").slice(0, 14) + "Z"
|
|
);
|
|
}
|
|
export async function certificateLifetime(
|
|
password: string,
|
|
scope: "full" | "cached" = "full",
|
|
) {
|
|
const path = resolve(local, "pki/lb/server.pem"),
|
|
original = await readFile(path),
|
|
ca = resolve(local, "operator/ca"),
|
|
outcomes = [];
|
|
const lbID = await containerID("lb"),
|
|
endpoint = publicLBEndpoint(
|
|
JSON.parse((await run(["docker", "inspect", lbID])).out)[0],
|
|
);
|
|
const positive = await tlsProbe(
|
|
endpoint.host,
|
|
endpoint.port,
|
|
endpoint.servername,
|
|
null,
|
|
health,
|
|
);
|
|
requireThat(
|
|
/HTTP\/1\.[01] 200/.test(positive.data),
|
|
"LIFETIME_PUBLIC_TLS_POSITIVE_FAILED",
|
|
);
|
|
try {
|
|
for (const mode of ["expired", "future"]) {
|
|
const destination = resolve(local, "operator", "lifetime-" + mode),
|
|
now = Date.now();
|
|
await issue(ca, destination, "lb", password, {
|
|
start: opensslDate(now + (mode === "expired" ? -2 : 1) * 86400_000),
|
|
end: opensslDate(now + (mode === "expired" ? -1 : 2) * 86400_000),
|
|
});
|
|
await privateWrite(
|
|
path,
|
|
await readFile(resolve(destination, "server.pem")),
|
|
);
|
|
await reloadGateway("lb");
|
|
await Bun.sleep(2500);
|
|
const code = await expectDenied(
|
|
() =>
|
|
tlsProbe(
|
|
endpoint.host,
|
|
endpoint.port,
|
|
endpoint.servername,
|
|
null,
|
|
health,
|
|
),
|
|
"trust",
|
|
);
|
|
requireThat(
|
|
code ===
|
|
(mode === "expired" ? "CERT_HAS_EXPIRED" : "CERT_NOT_YET_VALID"),
|
|
"CERTIFICATE_LIFETIME_WRONG_FAILURE",
|
|
);
|
|
outcomes.push({ mode, code });
|
|
}
|
|
} finally {
|
|
await privateWrite(path, original);
|
|
await reloadGateway("lb");
|
|
await waitReady();
|
|
}
|
|
await writeFile(
|
|
resolve(
|
|
root,
|
|
scope === "full"
|
|
? "evidence/security/certificate-lifetime.json"
|
|
: "evidence/preflight/certificate-lifetime.json",
|
|
),
|
|
JSON.stringify(
|
|
{
|
|
scope,
|
|
actual_listener:
|
|
"verified published loopback LB TLS binding; native HAProxy master-worker reload",
|
|
outcomes,
|
|
restored_verified_https: true,
|
|
image_rebuild: false,
|
|
},
|
|
null,
|
|
2,
|
|
) + "\n",
|
|
);
|
|
}
|
|
export async function sealedLifecycle(password: string, operationId: string) {
|
|
requireThat(/^[a-f0-9-]{36}$/.test(operationId), "SEALED_OPERATION_INVALID");
|
|
const operator = await unlock(password);
|
|
const observe = createSealedShutdown(
|
|
{
|
|
inspect: async (service, expectedId) => {
|
|
const id = expectedId ?? (await containerID(service));
|
|
const state = JSON.parse((await run(["docker", "inspect", id])).out)[0];
|
|
requireThat(
|
|
state.Config.Labels["com.docker.compose.project"] ===
|
|
"mtuci-vp7-security" &&
|
|
state.Config.Labels["com.docker.compose.service"] === service,
|
|
"SEALED_FOREIGN_CONTAINER",
|
|
);
|
|
return {
|
|
id: state.Id,
|
|
running: state.State.Running,
|
|
restarts: state.RestartCount,
|
|
};
|
|
},
|
|
readFreshness: (service) =>
|
|
readFile(resolve(local, "rendered", service, "freshness"), "utf8"),
|
|
readEvents: async (id, since) => {
|
|
const logs = await run([
|
|
"docker",
|
|
"logs",
|
|
"--timestamps",
|
|
"--tail",
|
|
"200",
|
|
"--since",
|
|
new Date(since).toISOString(),
|
|
id,
|
|
]);
|
|
const events = [];
|
|
for (const line of (logs.out + "\n" + logs.err).split("\n")) {
|
|
const split = line.indexOf(" ");
|
|
if (split < 0) continue;
|
|
try {
|
|
const row = JSON.parse(line.slice(split + 1));
|
|
if (row.event === "secret_freshness_failed")
|
|
events.push({
|
|
event: row.event,
|
|
milliseconds: Date.parse(line.slice(0, split)),
|
|
});
|
|
} catch {}
|
|
}
|
|
return events;
|
|
},
|
|
retainBaseline: async (value) => {
|
|
await writeFile(
|
|
resolve(
|
|
root,
|
|
"evidence/security/sealed-baseline-" + operationId + ".json",
|
|
),
|
|
JSON.stringify({ operation_id: operationId, ...value }, null, 2) +
|
|
"\n",
|
|
{ flag: "wx", mode: 0o644 },
|
|
);
|
|
},
|
|
seal: async () => {
|
|
await bao("/sys/seal", { token: operator.root_token, body: {} });
|
|
},
|
|
now: Date.now,
|
|
sleep: (milliseconds) => Bun.sleep(milliseconds),
|
|
},
|
|
{
|
|
maxAgeMilliseconds: 120000,
|
|
deadlineMilliseconds: 190000,
|
|
pollMilliseconds: 2000,
|
|
},
|
|
);
|
|
let proof: Awaited<ReturnType<typeof observe>> | undefined;
|
|
let primary: unknown,
|
|
failed = false,
|
|
recoveryFailure: unknown,
|
|
rejectionAt = 0,
|
|
recoveryStarted = 0;
|
|
try {
|
|
proof = await observe();
|
|
rejectionAt = Date.now();
|
|
await writeFile(
|
|
resolve(root, "evidence/security/sealed-cause-" + operationId + ".json"),
|
|
JSON.stringify(
|
|
{ operation_id: operationId, ...proof, rejection_at: rejectionAt },
|
|
null,
|
|
2,
|
|
) + "\n",
|
|
{ flag: "wx", mode: 0o644 },
|
|
);
|
|
const publicResult = await run([
|
|
"curl",
|
|
"--silent",
|
|
"--show-error",
|
|
"--noproxy",
|
|
"*",
|
|
"--cacert",
|
|
resolve(local, "pki/lb/ca.crt"),
|
|
"--max-time",
|
|
"5",
|
|
"--output",
|
|
"/dev/null",
|
|
"--write-out",
|
|
"%{http_code}",
|
|
"https://localhost:18443/health/ready",
|
|
]);
|
|
requireThat(publicResult.out === "503", "SEALED_BAO_STALE_API_STILL_READY");
|
|
await writeFile(
|
|
resolve(root, "evidence/security/sealed-public-" + operationId + ".json"),
|
|
JSON.stringify({
|
|
operation_id: operationId,
|
|
http_status: 503,
|
|
sealed_at: proof.sealedAt,
|
|
observed_at: Date.now(),
|
|
}) + "\n",
|
|
{ flag: "wx", mode: 0o644 },
|
|
);
|
|
} catch (error) {
|
|
primary = error;
|
|
failed = true;
|
|
} finally {
|
|
recoveryStarted = Date.now();
|
|
try {
|
|
await unseal(password);
|
|
const baoId = await containerID("openbao");
|
|
const health = await createHealthConvergence(
|
|
{
|
|
read: async () => {
|
|
const info = JSON.parse(
|
|
(await run(["docker", "inspect", baoId])).out,
|
|
)[0];
|
|
requireThat(
|
|
info.Id.startsWith(baoId) &&
|
|
info.State.Running &&
|
|
info.Config.Labels["com.docker.compose.project"] ===
|
|
"mtuci-vp7-security" &&
|
|
info.Config.Labels["com.docker.compose.service"] === "openbao",
|
|
"RECOVERY_BAO_OWNER_OR_STATE_CHANGED",
|
|
);
|
|
return info.State.Health?.Status ?? "unknown";
|
|
},
|
|
now: Date.now,
|
|
sleep: (ms) => Bun.sleep(ms),
|
|
},
|
|
10000,
|
|
250,
|
|
)();
|
|
await writeFile(
|
|
resolve(
|
|
root,
|
|
"evidence/security/sealed-recovery-health-" + operationId + ".json",
|
|
),
|
|
JSON.stringify({
|
|
operation_id: operationId,
|
|
container: baoId,
|
|
...health,
|
|
}) + "\n",
|
|
{ flag: "wx", mode: 0o644 },
|
|
);
|
|
await compose(["restart", "api1-agent", "api2-agent", "worker-agent"]);
|
|
const freshness = await createHealthConvergence(
|
|
{
|
|
read: async () =>
|
|
freshSecretsAfterSeal(
|
|
await Promise.all(
|
|
["api1", "api2", "worker"].map((service) =>
|
|
readFile(
|
|
resolve(local, "rendered", service, "freshness"),
|
|
"utf8",
|
|
),
|
|
),
|
|
),
|
|
proof?.sealedAt ?? recoveryStarted,
|
|
Date.now(),
|
|
120000,
|
|
)
|
|
? "healthy"
|
|
: "unhealthy",
|
|
now: Date.now,
|
|
sleep: (ms) => Bun.sleep(ms),
|
|
},
|
|
120000,
|
|
500,
|
|
)().catch((error) => {
|
|
if (
|
|
error instanceof Error &&
|
|
error.message === "BAO_HEALTH_NOT_CONVERGED"
|
|
)
|
|
throw new Error("SEALED_AGENT_FRESHNESS_NOT_CONVERGED", {
|
|
cause: error,
|
|
});
|
|
throw error;
|
|
});
|
|
await writeFile(
|
|
resolve(
|
|
root,
|
|
"evidence/security/sealed-recovery-render-" + operationId + ".json",
|
|
),
|
|
JSON.stringify({
|
|
operation_id: operationId,
|
|
...freshness,
|
|
controlled_agent_restart: true,
|
|
all_three_post_seal: true,
|
|
}) + "\n",
|
|
{ flag: "wx", mode: 0o644 },
|
|
);
|
|
await compose([
|
|
"up",
|
|
"-d",
|
|
"api1-agent",
|
|
"api2-agent",
|
|
"worker-agent",
|
|
"api1",
|
|
"api2",
|
|
"worker",
|
|
]);
|
|
await waitReady(["api1", "api2"], 120_000);
|
|
} catch (error) {
|
|
recoveryFailure = error;
|
|
await Promise.allSettled([
|
|
privateWrite(
|
|
resolve(local, "diagnostics/sealed-recovery-error.json"),
|
|
JSON.stringify({
|
|
message: error instanceof Error ? error.message : "UNKNOWN",
|
|
}),
|
|
),
|
|
]);
|
|
}
|
|
}
|
|
if (failed) throw primary;
|
|
if (recoveryFailure !== undefined) throw recoveryFailure;
|
|
requireThat(proof, "SEALED_CAUSAL_SHUTDOWN_NOT_PROVED");
|
|
const recoveredFreshness: Record<string, number> = {};
|
|
for (const service of ["api1", "api2", "worker"]) {
|
|
const timestamp = Date.parse(
|
|
(
|
|
await readFile(
|
|
resolve(local, "rendered", service, "freshness"),
|
|
"utf8",
|
|
)
|
|
).trim(),
|
|
),
|
|
age = Date.now() - timestamp;
|
|
requireThat(
|
|
Number.isFinite(age) &&
|
|
age >= 0 &&
|
|
age <= 120000 &&
|
|
timestamp > proof.sealedAt,
|
|
"SEALED_RECOVERY_NOT_FRESH",
|
|
);
|
|
recoveredFreshness[service] = timestamp;
|
|
}
|
|
const http = new HTTP(),
|
|
a = await http.user("recovery"),
|
|
b = await http.user("peer");
|
|
const chat = (
|
|
await http.call("POST", "/api/v1/chats", 201, {
|
|
actor: a.token,
|
|
body: { title: "After unseal", member_ids: [a.id, b.id] },
|
|
})
|
|
).json;
|
|
const fixture = new Uint8Array(
|
|
await readFile(resolve(root, "tests/fixtures/sample.png")),
|
|
);
|
|
const att = (
|
|
await http.call(
|
|
"POST",
|
|
`/api/v1/chats/${chat.id}/attachments?filename=recovery.png`,
|
|
202,
|
|
{
|
|
actor: a.token,
|
|
raw: fixture,
|
|
headers: { "Content-Type": "image/png" },
|
|
},
|
|
)
|
|
).json;
|
|
await http.ready(b.token, att.id);
|
|
await writeFile(
|
|
resolve(root, "evidence/security/sealed-lifecycle.json"),
|
|
JSON.stringify(
|
|
{
|
|
operation_id: operationId,
|
|
baseline: proof.baseline,
|
|
baseline_freshness_milliseconds: proof.freshness,
|
|
observed_causal_shutdown: proof.observed,
|
|
recovered_freshness_milliseconds: recoveredFreshness,
|
|
sealed_old_credentials_bounded: true,
|
|
stale_processes_restarted_or_stopped: true,
|
|
public_ready_while_stale: 503,
|
|
seconds_until_checked_rejection: (rejectionAt - proof.started) / 1000,
|
|
recovery_seconds_including_new_upload:
|
|
(Date.now() - recoveryStarted) / 1000,
|
|
unseal_recovery: true,
|
|
real_attachment_processed_after_recovery: true,
|
|
limit:
|
|
"observed local filesystem/scheduling; no universal hung-host wall-clock bound",
|
|
},
|
|
null,
|
|
2,
|
|
) + "\n",
|
|
);
|
|
}
|
|
async function telemetryScope() {
|
|
const service = "openobserve-gateway",
|
|
ip = await containerIP(service);
|
|
const authorization = await readFile(
|
|
resolve(local, "config/openobserve_query_auth"),
|
|
"utf8",
|
|
);
|
|
requireThat(
|
|
authorization.length <= 4096 &&
|
|
/^Basic [A-Za-z0-9+/]+={0,2}$/.test(authorization),
|
|
"INVALID_OPENOBSERVE_AUTH_HEADER_FILE",
|
|
);
|
|
const positive = async () => {
|
|
const response = await tlsProbe(
|
|
ip,
|
|
5082,
|
|
service,
|
|
"grafana",
|
|
`GET /api/default/streams HTTP/1.1\r\nHost: localhost\r\nAuthorization: ${authorization}\r\nConnection: close\r\n\r\n`,
|
|
);
|
|
requireThat(
|
|
response.authorized && /HTTP\/1\.[01] 200/.test(response.data),
|
|
"GRAFANA_NATIVE_QUERY_POSITIVE_FAILED",
|
|
);
|
|
};
|
|
await positive();
|
|
for (const [service, port, path] of [
|
|
["openobserve-gateway", 5082, "/api/default/v1/logs"],
|
|
["openobserve-gateway", 5082, "/api/default/users"],
|
|
["openobserve-gateway", 5082, "/api/foreign/_search"],
|
|
] as const) {
|
|
const ip = await containerIP(service);
|
|
const denied = await tlsProbe(
|
|
ip,
|
|
port,
|
|
service,
|
|
"grafana",
|
|
`POST ${path} HTTP/1.1\r\nHost: localhost\r\nContent-Length: 0\r\nConnection: close\r\n\r\n`,
|
|
);
|
|
requireThat(
|
|
/HTTP\/1\.[01] 403/.test(denied.data),
|
|
"GRAFANA_INGEST_NOT_DENIED",
|
|
);
|
|
}
|
|
await positive();
|
|
console.log("PASS_GRAFANA_QUERY_IDENTITY_CANNOT_INGEST");
|
|
}
|
|
export async function extendedAcceptance(
|
|
password: string,
|
|
operationId: string,
|
|
gitSource: GitTrackingSource,
|
|
) {
|
|
await certificateLifetime(password);
|
|
await telemetryScope();
|
|
await workerCompromise(password);
|
|
await completeSecurityLifecycle(password, operationId, gitSource);
|
|
}
|
|
export async function completeSecurityLifecycle(
|
|
password: string,
|
|
operationId: string,
|
|
gitSource: GitTrackingSource,
|
|
) {
|
|
const expiring = await bao("/auth/cert/login", {
|
|
role: "api",
|
|
body: { name: "api" },
|
|
}),
|
|
ttl = expiring.data.auth.lease_duration,
|
|
token = expiring.data.auth.client_token,
|
|
expiryAt = Date.now() + ttl * 1000 + 1500;
|
|
requireThat(ttl > 0 && ttl <= 60, "EXPIRY_TEST_TOKEN_TTL_UNBOUNDED");
|
|
parseKV(await bao("/kv/data/api", { role: "api", token }), "api");
|
|
await auditArtifacts(password, gitSource);
|
|
while (Date.now() < expiryAt)
|
|
await Bun.sleep(Math.min(1000, expiryAt - Date.now()));
|
|
await bao("/kv/data/api", { role: "api", token, expected: [403] });
|
|
const fresh = await bao("/auth/cert/login", {
|
|
role: "api",
|
|
body: { name: "api" },
|
|
});
|
|
parseKV(
|
|
await bao("/kv/data/api", {
|
|
role: "api",
|
|
token: fresh.data.auth.client_token,
|
|
}),
|
|
"api",
|
|
);
|
|
await bao("/auth/token/revoke-self", {
|
|
role: "api",
|
|
token: fresh.data.auth.client_token,
|
|
body: {},
|
|
});
|
|
await writeFile(
|
|
resolve(root, "evidence/security/token-expiry.json"),
|
|
JSON.stringify(
|
|
{
|
|
token_ttl_seconds: ttl,
|
|
initial_own_read: 200,
|
|
expired_new_request: 403,
|
|
new_auth_same_role_read: 200,
|
|
},
|
|
null,
|
|
2,
|
|
) + "\n",
|
|
);
|
|
await sealedLifecycle(password, operationId);
|
|
console.log("PASS_EXTENDED_LIFECYCLE_AND_WORKER_RESEARCH");
|
|
}
|