983 lines
51 KiB
Python
Executable File
983 lines
51 KiB
Python
Executable File
#!/usr/bin/env python3
|
||
"""Lab 7 Grade 5, Track 1 («Компрометация worker») Repeatable Experiment Suite.
|
||
|
||
Simulates compromise of the running `worker` container using ONLY the certs and
|
||
credentials accessible inside `worker`:
|
||
1. Baseline health, worker env/mount hygiene audit, canary message + pre-compromise upload
|
||
2. Capture stolen worker runtime context (client cert/key -> OpenBao auth/cert -> PG/S3 creds)
|
||
3. Execute 26+ automated blast-radius probes across OpenBao, PostgreSQL, MinIO S3,
|
||
RabbitMQ, Redis, and API mTLS
|
||
4. Quarantine worker; enqueue pre- & during-containment uploads (API keeps returning 202)
|
||
5. Execute scripts/revoke-worker.sh --no-start (zero image rebuild)
|
||
6. Prove EVERY stolen credential/cert fails on BRAND-NEW connections (NC-6)
|
||
7. Recover worker without image rebuild; prove 100% job durability, exact SHA-256,
|
||
256x160 JPEG thumbnails, 0 lost jobs, 0 duplicate variants
|
||
8. Emit structured Before (Lab 6) vs After (Lab 7) comparison & residual risks to
|
||
evidence/lab7/track1/summary.{json,md,txt}
|
||
"""
|
||
import argparse
|
||
import hashlib
|
||
import json
|
||
import re
|
||
import sys
|
||
import tempfile
|
||
import time
|
||
import uuid
|
||
from pathlib import Path
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||
import common # noqa: E402
|
||
from client import Client, Failure # noqa: E402
|
||
from image_probe import jpeg_size # noqa: E402
|
||
|
||
HYPOTHESIS = (
|
||
'Under Lab 7 least-privilege boundaries (OpenBao auth/cert + worker-policy, '
|
||
'PostgreSQL messenger_worker table/column grants, tightened MinIO prefix policy, '
|
||
'RabbitMQ EXTERNAL consumer-only ACL, zero Redis access in worker, and API mTLS '
|
||
'LB-SAN allowlist), full compromise of the worker container yields zero access to '
|
||
'user credentials, sessions, private messages, chats, or API/admin secrets, and '
|
||
'cannot forge jobs, delete committed originals, or alter attachment integrity metadata; '
|
||
'revoking the compromised worker identity and rotating all related credentials without '
|
||
'rebuilding images immediately blocks all stolen access on new connections while '
|
||
'preserving 100% of queued and in-flight jobs with zero duplicates.'
|
||
)
|
||
|
||
BEFORE_AFTER_MATRIX = [
|
||
{
|
||
'domain': 'PostgreSQL',
|
||
'before_lab6': 'Shared messenger superuser/table-owner via .env DATABASE_URL over plaintext TCP; compromised worker could read users.password_hash, all messages/chats, or DROP tables.',
|
||
'after_lab7': 'Dedicated messenger_worker role over TLS verify-full with strictly 5 pipeline tables + column-level UPDATE; users, chats, chat_members, messages, message_attachments, idempotency_keys, schema_migrations, DELETE attachments/jobs, UPDATE sha256, and DDL all fail with 42501.',
|
||
'delta': '100% elimination of user credential, message, chat, and schema exposure from worker.',
|
||
},
|
||
{
|
||
'domain': 'MinIO S3',
|
||
'before_lab6': 'Plaintext HTTP; static keys in ./secrets/; broad s3:PutObject across attachments/*.',
|
||
'after_lab7': 'HTTPS + CA verify; rotatable IAM user in OpenBao; staging/* Get/Delete only (no Put); attachments/*/original Get/Put only (no Delete); attachments/*/v*/* Put/Delete; backups/*, admin/*, bucket root list, CreateBucket, and MinIO Admin API all fail with 403 AccessDenied.',
|
||
'delta': 'Eliminates staging poisoning, committed original deletion, and cross-prefix/admin pivoting.',
|
||
},
|
||
{
|
||
'domain': 'RabbitMQ',
|
||
'before_lab6': 'Plaintext AMQP 5672; static password file; configure/write/read across topology (worker could forge jobs and tamper with queues).',
|
||
'after_lab7': 'AMQPS 5671 + mTLS SASL EXTERNAL (generation-suffixed CN); configure=^$, write=^$, read=^attachments\\.process$; OutboxRelay removed from worker. Publish to attachments.jobs, declare/delete queue, DLQ consume, and vhost / all fail with 403 ACCESS_REFUSED.',
|
||
'delta': 'Eliminates job forgery, topology tampering, DLQ reading, and vhost pivoting.',
|
||
},
|
||
{
|
||
'domain': 'Redis',
|
||
'before_lab6': 'Plaintext TCP, unauthenticated REDIS_URL in worker .env; raw Bearer tokens stored in session:<token>.',
|
||
'after_lab7': 'TLS + mTLS + user default off + ACLs; RedisModule removed from WorkerModule (zero Redis credentials in worker); API stores only session:sha256:<hex>.',
|
||
'delta': '100% elimination of user session hijacking and rate-limit tampering from worker.',
|
||
},
|
||
{
|
||
'domain': 'Secrets / OpenBao',
|
||
'before_lab6': 'No KMS; all secrets in .env / ./secrets/ including POSTGRES_PASSWORD and METRICS_TOKEN.',
|
||
'after_lab7': 'Non-dev Raft OpenBao over TLS; mTLS auth/cert + worker-policy (token_no_default_policy=true) + CRL; zero API/migrator/operator/root secrets reachable; sub-second accessor + CRL revocation.',
|
||
'delta': 'Eliminates static secret sprawl and enables live zero-rebuild revocation/rotation.',
|
||
},
|
||
{
|
||
'domain': 'API Internal Surface',
|
||
'before_lab6': 'Plaintext http://api:8080 reachable directly from worker container.',
|
||
'after_lab7': 'Mandatory mTLS + LB SAN allowlist (haproxy-lb) + CRL on api:8443; valid CA-signed worker cert rejected with 403.',
|
||
'delta': 'Eliminates direct LB bypass and API impersonation from worker.',
|
||
},
|
||
]
|
||
|
||
RESIDUAL_RISKS = [
|
||
'In-scope functional abuse before detection: until revoked, a compromised worker legitimately needs read access to staging/* and write access to attachments/*/v*/* and attachments/*/original for claimed jobs, so it could delay or corrupt rendered variants of active jobs (mitigated by immutable attachments.sha256, job timeouts, and queue lag alerts).',
|
||
'Single-host lab boundary: host OS root or Docker daemon compromise is outside container isolation; production deployments isolate nodes, run multi-node OpenBao Raft HA with KMS auto-unseal, and issue short-lived workload certs via SPIRE/OpenBao PKI.',
|
||
'Active connection drain window: credential revocation immediately blocks all new connections (TLS session resumption disabled); active sockets are terminated explicitly during scripts/revoke-worker.sh via pg_terminate_backend, rabbitmqctl delete_user, MinIO user deletion, and OpenBao accessor revocation.',
|
||
]
|
||
|
||
|
||
def _worker_exec_read(path):
|
||
res = common.compose('exec', '-T', 'worker', 'cat', path)
|
||
return res.stdout
|
||
|
||
|
||
def _cert_cn_and_serial(pem_text):
|
||
import ssl
|
||
m = re.search(r'-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----', pem_text)
|
||
if not m:
|
||
raise Failure('invalid PEM certificate')
|
||
der = ssl.PEM_cert_to_DER_cert(m.group(0))
|
||
serial = common.parse_der_serial(der)
|
||
# Extract CN via openssl or Node X509Certificate fallback
|
||
js = """
|
||
const { X509Certificate } = require('crypto');
|
||
const c = new X509Certificate(payload.pem);
|
||
const m = (c.subject || '').match(/CN=([^\\n,]+)/);
|
||
return { subject: c.subject, cn: m ? m[1].trim() : null, serial: c.serialNumber, san: c.subjectAltName };
|
||
"""
|
||
info = common.run_node_probe(js, {'pem': m.group(0)}, exec_service='api').get('result') or {}
|
||
return info.get('cn'), info.get('serial') or serial, info.get('san')
|
||
|
||
|
||
def _s3_admin_canary(ca_pem, action, key='backups/canary.txt', body='TRACK1-S3-CANARY'):
|
||
"""Use MinIO root creds from host ./secrets/infra/ to seed or remove out-of-prefix canary."""
|
||
root_user = common.read_secret_file('minio_root_user')
|
||
root_pass = common.read_secret_file('minio_root_password')
|
||
if not (root_user and root_pass):
|
||
raise Failure('minio_root_user / minio_root_password not found in secrets/infra/')
|
||
js = """
|
||
const https = require('https');
|
||
const { S3Client, PutObjectCommand, DeleteObjectCommand } = require('@aws-sdk/client-s3');
|
||
const { NodeHttpHandler } = require('@smithy/node-http-handler');
|
||
const agent = new https.Agent({ ca: payload.ca_pem, rejectUnauthorized: true, minVersion: 'TLSv1.2' });
|
||
const s3 = new S3Client({
|
||
endpoint: 'https://s3:9000',
|
||
region: 'us-east-1',
|
||
forcePathStyle: true,
|
||
credentials: { accessKeyId: payload.user, secretAccessKey: payload.pass },
|
||
requestHandler: new NodeHttpHandler({ httpsAgent: agent }),
|
||
maxAttempts: 1,
|
||
});
|
||
if (payload.action === 'put') {
|
||
await s3.send(new PutObjectCommand({ Bucket: 'messenger-attachments', Key: payload.key, Body: payload.body }));
|
||
} else {
|
||
await s3.send(new DeleteObjectCommand({ Bucket: 'messenger-attachments', Key: payload.key }));
|
||
}
|
||
agent.destroy();
|
||
return { ok: true };
|
||
"""
|
||
return common.run_node_probe(
|
||
js,
|
||
{'ca_pem': ca_pem, 'user': root_user, 'pass': root_pass, 'action': action, 'key': key, 'body': body},
|
||
network='app_data',
|
||
)
|
||
|
||
|
||
def _probe_pg_blast_radius(ca_pem, db_user, db_pass, att_id):
|
||
js = """
|
||
const { Client } = require('pg');
|
||
const c = new Client({
|
||
host: 'postgres', port: 5432, database: 'messenger',
|
||
user: payload.user, password: payload.pass,
|
||
connectionTimeoutMillis: 5000,
|
||
ssl: { ca: payload.ca_pem, rejectUnauthorized: true, servername: 'postgres', minVersion: 'TLSv1.2' },
|
||
});
|
||
await c.connect();
|
||
async function run(sql, params) {
|
||
try {
|
||
const r = await c.query(sql, params || []);
|
||
return { allowed: true, code: null, rows: r.rowCount };
|
||
} catch (e) {
|
||
return { allowed: false, code: e.code || null, error: (e.message || String(e)).slice(0, 140) };
|
||
}
|
||
}
|
||
const out = {
|
||
allow_select_jobs: await run('SELECT count(*) FROM attachment_jobs'),
|
||
allow_select_attachments: await run('SELECT id, status FROM attachments WHERE id = $1', [payload.att_id]),
|
||
allow_select_variants: await run('SELECT count(*) FROM attachment_variants WHERE attachment_id = $1', [payload.att_id]),
|
||
allow_update_att_status_noop: await run('UPDATE attachments SET updated_at = updated_at WHERE id = $1', [payload.att_id]),
|
||
deny_select_users: await run('SELECT id, username, password_hash FROM users LIMIT 1'),
|
||
deny_select_messages: await run('SELECT id, text FROM messages LIMIT 1'),
|
||
deny_select_chats: await run('SELECT id, title FROM chats LIMIT 1'),
|
||
deny_select_chat_members: await run('SELECT chat_id, user_id FROM chat_members LIMIT 1'),
|
||
deny_select_message_attachments: await run('SELECT message_id, attachment_id FROM message_attachments LIMIT 1'),
|
||
deny_select_idempotency: await run('SELECT key FROM idempotency_keys LIMIT 1'),
|
||
deny_select_migrations: await run('SELECT version FROM schema_migrations LIMIT 1'),
|
||
deny_delete_attachments: await run('DELETE FROM attachments WHERE id = $1', [payload.att_id]),
|
||
deny_delete_jobs: await run('DELETE FROM attachment_jobs WHERE attachment_id = $1', [payload.att_id]),
|
||
deny_update_sha256: await run("UPDATE attachments SET sha256 = '0000000000000000000000000000000000000000000000000000000000000000' WHERE id = $1", [payload.att_id]),
|
||
deny_delete_variants: await run('DELETE FROM attachment_variants WHERE attachment_id = $1', [payload.att_id]),
|
||
deny_ddl_create: await run('CREATE TABLE public.track1_pwned (x int)'),
|
||
};
|
||
await c.end();
|
||
return out;
|
||
"""
|
||
return common.run_node_probe(
|
||
js,
|
||
{'ca_pem': ca_pem, 'user': db_user, 'pass': db_pass, 'att_id': att_id},
|
||
network='app_data',
|
||
timeout=45,
|
||
)
|
||
|
||
|
||
def _probe_s3_blast_radius(ca_pem, access_key, secret_key, att_id):
|
||
js = """
|
||
const https = require('https');
|
||
const crypto = require('crypto');
|
||
const {
|
||
S3Client, GetObjectCommand, PutObjectCommand, DeleteObjectCommand,
|
||
ListObjectsV2Command, CreateBucketCommand,
|
||
} = require('@aws-sdk/client-s3');
|
||
const { NodeHttpHandler } = require('@smithy/node-http-handler');
|
||
const agent = new https.Agent({ ca: payload.ca_pem, rejectUnauthorized: true, minVersion: 'TLSv1.2' });
|
||
const s3 = new S3Client({
|
||
endpoint: 'https://s3:9000',
|
||
region: 'us-east-1',
|
||
forcePathStyle: true,
|
||
credentials: { accessKeyId: payload.ak, secretAccessKey: payload.sk },
|
||
requestHandler: new NodeHttpHandler({ httpsAgent: agent }),
|
||
maxAttempts: 1,
|
||
});
|
||
async function run(cmd) {
|
||
try {
|
||
const res = await s3.send(cmd);
|
||
if (res.Body && typeof res.Body.transformToByteArray === 'function') {
|
||
await res.Body.transformToByteArray();
|
||
}
|
||
return { allowed: true, status: res.$metadata && res.$metadata.httpStatusCode || 200, code: null };
|
||
} catch (e) {
|
||
return {
|
||
allowed: false,
|
||
status: e.$metadata && e.$metadata.httpStatusCode || null,
|
||
code: e.Code || e.name || null,
|
||
};
|
||
}
|
||
}
|
||
const bucket = 'messenger-attachments';
|
||
const probeKey = `attachments/${payload.att_id}/v99/track1-probe.jpg`;
|
||
const out = {
|
||
allow_get_staging: await run(new GetObjectCommand({ Bucket: bucket, Key: 'staging/track1-probe/original' })),
|
||
allow_del_staging: await run(new DeleteObjectCommand({ Bucket: bucket, Key: 'staging/track1-probe/original' })),
|
||
allow_get_original: await run(new GetObjectCommand({ Bucket: bucket, Key: `attachments/${payload.att_id}/original` })),
|
||
allow_put_variant: await run(new PutObjectCommand({ Bucket: bucket, Key: probeKey, Body: Buffer.from('probe') })),
|
||
allow_del_variant: await run(new DeleteObjectCommand({ Bucket: bucket, Key: probeKey })),
|
||
deny_get_backups: await run(new GetObjectCommand({ Bucket: bucket, Key: 'backups/canary.txt' })),
|
||
deny_put_backups: await run(new PutObjectCommand({ Bucket: bucket, Key: 'backups/pwned.txt', Body: Buffer.from('x') })),
|
||
deny_put_admin: await run(new PutObjectCommand({ Bucket: bucket, Key: 'admin/pwned.txt', Body: Buffer.from('x') })),
|
||
deny_put_staging: await run(new PutObjectCommand({ Bucket: bucket, Key: 'staging/forged/original', Body: Buffer.from('x') })),
|
||
deny_del_original: await run(new DeleteObjectCommand({ Bucket: bucket, Key: `attachments/${payload.att_id}/original` })),
|
||
deny_list_root: await run(new ListObjectsV2Command({ Bucket: bucket })),
|
||
deny_list_backups: await run(new ListObjectsV2Command({ Bucket: bucket, Prefix: 'backups/' })),
|
||
deny_create_bucket: await run(new CreateBucketCommand({ Bucket: 'track1-pwned-bucket' })),
|
||
};
|
||
|
||
// Signed SigV4 probe against MinIO Admin API (/minio/admin/v3/info)
|
||
function hmac(key, msg) { return crypto.createHmac('sha256', key).update(msg).digest(); }
|
||
function sha256Hex(msg) { return crypto.createHash('sha256').update(msg).digest('hex'); }
|
||
const now = new Date();
|
||
const amzDate = now.toISOString().replace(/[-:]/g, '').replace(/\\.\\d+Z$/, 'Z');
|
||
const dateStamp = amzDate.slice(0, 8);
|
||
const payloadHash = sha256Hex('');
|
||
const canonHeaders = `host:s3:9000\\nx-amz-content-sha256:${payloadHash}\\nx-amz-date:${amzDate}\\n`;
|
||
const signedHeaders = 'host;x-amz-content-sha256;x-amz-date';
|
||
const canonReq = `GET\\n/minio/admin/v3/info\\n\\n${canonHeaders}\\n${signedHeaders}\\n${payloadHash}`;
|
||
const scope = `${dateStamp}/us-east-1/s3/aws4_request`;
|
||
const strToSign = `AWS4-HMAC-SHA256\\n${amzDate}\\n${scope}\\n${sha256Hex(canonReq)}`;
|
||
const kSigning = hmac(hmac(hmac(hmac('AWS4' + payload.sk, dateStamp), 'us-east-1'), 's3'), 'aws4_request');
|
||
const sig = crypto.createHmac('sha256', kSigning).update(strToSign).digest('hex');
|
||
const authHdr = `AWS4-HMAC-SHA256 Credential=${payload.ak}/${scope}, SignedHeaders=${signedHeaders}, Signature=${sig}`;
|
||
|
||
out.deny_minio_admin = await new Promise((resolve) => {
|
||
const req = https.request({
|
||
hostname: 's3', port: 9000, path: '/minio/admin/v3/info', method: 'GET',
|
||
ca: payload.ca_pem, rejectUnauthorized: true, servername: 's3', minVersion: 'TLSv1.2',
|
||
headers: {
|
||
Host: 's3:9000',
|
||
'x-amz-date': amzDate,
|
||
'x-amz-content-sha256': payloadHash,
|
||
Authorization: authHdr,
|
||
Connection: 'close',
|
||
},
|
||
timeout: 5000,
|
||
}, (res) => {
|
||
const chunks = [];
|
||
res.on('data', (c) => chunks.push(c));
|
||
res.on('end', () => {
|
||
const text = Buffer.concat(chunks).toString('utf8');
|
||
resolve({
|
||
allowed: res.statusCode === 200,
|
||
status: res.statusCode,
|
||
code: text.includes('AccessDenied') ? 'AccessDenied' : text.slice(0, 80),
|
||
});
|
||
});
|
||
});
|
||
req.on('error', (err) => resolve({ allowed: false, status: null, code: err.code || err.message }));
|
||
req.end();
|
||
});
|
||
|
||
agent.destroy();
|
||
return out;
|
||
"""
|
||
return common.run_node_probe(
|
||
js,
|
||
{'ca_pem': ca_pem, 'ak': access_key, 'sk': secret_key, 'att_id': att_id},
|
||
network='app_data',
|
||
timeout=45,
|
||
)
|
||
|
||
|
||
def _probe_rabbitmq_blast_radius(ca_pem, cert_pem, key_pem):
|
||
js = """
|
||
const amqp = require('amqplib');
|
||
const crypto = require('crypto');
|
||
const sockOpts = {
|
||
ca: [Buffer.from(payload.ca_pem)],
|
||
cert: Buffer.from(payload.cert_pem),
|
||
key: Buffer.from(payload.key_pem),
|
||
servername: 'broker',
|
||
rejectUnauthorized: true,
|
||
minVersion: 'TLSv1.2',
|
||
secureOptions: crypto.constants.SSL_OP_NO_TICKET,
|
||
credentials: amqp.credentials.external(),
|
||
};
|
||
async function tryOp(vhost, fn) {
|
||
let conn = null;
|
||
try {
|
||
conn = await amqp.connect({
|
||
protocol: 'amqps', hostname: 'broker', port: 5671, vhost,
|
||
}, sockOpts);
|
||
conn.on('error', () => {});
|
||
const val = await fn(conn);
|
||
return { allowed: true, detail: val || 'ok' };
|
||
} catch (e) {
|
||
return { allowed: false, error: (e && (e.message || e.code)) || String(e) };
|
||
} finally {
|
||
if (conn) { try { await conn.close(); } catch (_) {} }
|
||
}
|
||
}
|
||
const out = {};
|
||
out.allow_consume_process = await tryOp('messenger', async (conn) => {
|
||
const ch = await conn.createChannel();
|
||
ch.on('error', () => {});
|
||
await ch.checkQueue('attachments.process');
|
||
const sub = await ch.consume('attachments.process', (msg) => {
|
||
if (msg) ch.nack(msg, false, true);
|
||
}, { noAck: false });
|
||
await ch.cancel(sub.consumerTag);
|
||
await ch.close();
|
||
return 'consumed_ok';
|
||
});
|
||
out.deny_publish_jobs = await tryOp('messenger', async (conn) => {
|
||
const ch = await conn.createConfirmChannel();
|
||
let errMsg = null;
|
||
ch.on('error', (e) => { errMsg = e.message || String(e); });
|
||
ch.publish('attachments.jobs', 'attachment.process.v1', Buffer.from('{"forged":true}'));
|
||
await ch.waitForConfirms();
|
||
if (errMsg) throw new Error(errMsg);
|
||
await ch.close();
|
||
return 'published';
|
||
});
|
||
out.deny_declare_queue = await tryOp('messenger', async (conn) => {
|
||
const ch = await conn.createChannel();
|
||
ch.on('error', () => {});
|
||
await ch.assertQueue('track1.pwned.queue', { durable: false });
|
||
await ch.close();
|
||
return 'declared';
|
||
});
|
||
out.deny_delete_queue = await tryOp('messenger', async (conn) => {
|
||
const ch = await conn.createChannel();
|
||
ch.on('error', () => {});
|
||
await ch.deleteQueue('attachments.process');
|
||
await ch.close();
|
||
return 'deleted';
|
||
});
|
||
out.deny_consume_dlq = await tryOp('messenger', async (conn) => {
|
||
const ch = await conn.createChannel();
|
||
ch.on('error', () => {});
|
||
await ch.consume('attachments.process.dlq', () => {});
|
||
await ch.close();
|
||
return 'consumed_dlq';
|
||
});
|
||
out.deny_root_vhost = await tryOp('/', async () => 'connected_root');
|
||
return out;
|
||
"""
|
||
return common.run_node_probe(
|
||
js, {'ca_pem': ca_pem, 'cert_pem': cert_pem, 'key_pem': key_pem},
|
||
network='app_data', timeout=45,
|
||
)
|
||
|
||
|
||
def _probe_redis_and_api_lateral(ca_pem, cert_pem, key_pem):
|
||
js = """
|
||
const https = require('https');
|
||
const crypto = require('crypto');
|
||
const { createClient } = require('redis');
|
||
|
||
// 1. Redis probe with worker cert & no credentials (worker holds 0 Redis creds)
|
||
let redisRes;
|
||
const rClient = createClient({
|
||
socket: {
|
||
host: 'redis', port: 6379, tls: true,
|
||
ca: payload.ca_pem, cert: payload.cert_pem, key: payload.key_pem,
|
||
servername: 'redis', rejectUnauthorized: true, minVersion: 'TLSv1.2',
|
||
connectTimeout: 4000, reconnectStrategy: false,
|
||
},
|
||
});
|
||
rClient.on('error', () => {});
|
||
try {
|
||
await rClient.connect();
|
||
await rClient.ping();
|
||
await rClient.quit();
|
||
redisRes = { allowed: true, error: null };
|
||
} catch (e) {
|
||
try { rClient.destroy(); } catch (_) {}
|
||
redisRes = { allowed: false, error: (e && (e.message || e.code)) || String(e) };
|
||
}
|
||
|
||
// 2. API mTLS lateral movement from app_data using trusted-CA worker cert
|
||
const apiRes = await new Promise((resolve) => {
|
||
const req = https.request({
|
||
hostname: 'api', port: 8443, path: '/health/ready', method: 'GET',
|
||
ca: payload.ca_pem, cert: payload.cert_pem, key: payload.key_pem,
|
||
servername: 'api', rejectUnauthorized: true, minVersion: 'TLSv1.2',
|
||
secureOptions: crypto.constants.SSL_OP_NO_TICKET,
|
||
headers: { Connection: 'close' }, timeout: 5000,
|
||
}, (res) => {
|
||
res.resume();
|
||
res.on('end', () => resolve({ allowed: res.statusCode === 200, status: res.statusCode, error: null }));
|
||
});
|
||
req.on('error', (e) => resolve({ allowed: false, status: null, error: e.code || e.message }));
|
||
req.end();
|
||
});
|
||
|
||
// 3. OTel Gateway probe using worker cert (used both before & after revocation)
|
||
const otelRes = await new Promise((resolve) => {
|
||
const req = https.request({
|
||
hostname: 'otel-collector', port: 4318, path: '/v1/traces', method: 'POST',
|
||
ca: payload.ca_pem, cert: payload.cert_pem, key: payload.key_pem,
|
||
servername: 'otel-collector', rejectUnauthorized: true, minVersion: 'TLSv1.2',
|
||
secureOptions: crypto.constants.SSL_OP_NO_TICKET,
|
||
headers: { 'Content-Type': 'application/json', Connection: 'close' },
|
||
timeout: 5000,
|
||
}, (res) => {
|
||
res.resume();
|
||
res.on('end', () => resolve({ allowed: res.statusCode === 200, status: res.statusCode, error: null }));
|
||
});
|
||
req.on('error', (e) => resolve({ allowed: false, status: null, error: e.code || e.message }));
|
||
req.write('{"resourceSpans":[]}');
|
||
req.end();
|
||
});
|
||
|
||
return { redis: redisRes, api: apiRes, otel: otelRes };
|
||
"""
|
||
return common.run_node_probe(
|
||
js, {'ca_pem': ca_pem, 'cert_pem': cert_pem, 'key_pem': key_pem},
|
||
network='app_data', timeout=30,
|
||
)
|
||
|
||
|
||
def _probe_revoked_g1(ca_pem, bao_url, ca_file, stolen_token, stolen_crt_pem, stolen_key_pem,
|
||
db_user, db_pass, s3_ak, s3_sk, att_id):
|
||
results = {}
|
||
|
||
# 1. Stolen OpenBao token -> 403
|
||
st_tok, _ = common.OpenBaoClient(bao_url, ca_file, token=stolen_token).kv_read('secret/data/messenger/worker')
|
||
results['openbao_token'] = {'rejected': st_tok == 403, 'status': st_tok}
|
||
|
||
# 2. Stolen g1 cert -> OpenBao auth/cert/login -> 400/403 (CRL revoked)
|
||
with tempfile.TemporaryDirectory(prefix='mtusi-t1-g1-') as td:
|
||
crt_p = Path(td) / 'g1.crt'
|
||
key_p = Path(td) / 'g1.key'
|
||
crt_p.write_text(stolen_crt_pem, encoding='utf-8')
|
||
key_p.write_text(stolen_key_pem, encoding='utf-8')
|
||
try:
|
||
st_cert, _ = common.OpenBaoClient(bao_url, ca_file, cert_file=crt_p, key_file=key_p).cert_login('messenger-worker')
|
||
results['openbao_cert'] = {'rejected': st_cert in (400, 403), 'status': st_cert}
|
||
except Exception as exc:
|
||
results['openbao_cert'] = {'rejected': True, 'error': type(exc).__name__}
|
||
|
||
# 3. Stolen PG password -> 28P01 on new TLS connection
|
||
pg_js = """
|
||
const { Client } = require('pg');
|
||
const c = new Client({
|
||
host: 'postgres', port: 5432, database: 'messenger',
|
||
user: payload.user, password: payload.pass, connectionTimeoutMillis: 5000,
|
||
ssl: { ca: payload.ca_pem, rejectUnauthorized: true, servername: 'postgres', minVersion: 'TLSv1.2' },
|
||
});
|
||
try { await c.connect(); await c.query('SELECT 1'); await c.end(); return { rejected: false }; }
|
||
catch (e) { try { await c.end(); } catch (_) {} return { rejected: true, code: e.code || null, error: (e.message || '').slice(0, 120) }; }
|
||
"""
|
||
pg_r = (common.run_node_probe(pg_js, {'ca_pem': ca_pem, 'user': db_user, 'pass': db_pass}, network='app_data').get('result') or {})
|
||
results['postgres'] = pg_r
|
||
|
||
# 4. Stolen S3 key -> 403 on new HTTPS connection
|
||
s3_js = """
|
||
const https = require('https');
|
||
const { S3Client, GetObjectCommand } = require('@aws-sdk/client-s3');
|
||
const { NodeHttpHandler } = require('@smithy/node-http-handler');
|
||
const agent = new https.Agent({ ca: payload.ca_pem, rejectUnauthorized: true, minVersion: 'TLSv1.2' });
|
||
const s3 = new S3Client({
|
||
endpoint: 'https://s3:9000', region: 'us-east-1', forcePathStyle: true,
|
||
credentials: { accessKeyId: payload.ak, secretAccessKey: payload.sk },
|
||
requestHandler: new NodeHttpHandler({ httpsAgent: agent }), maxAttempts: 1,
|
||
});
|
||
try {
|
||
await s3.send(new GetObjectCommand({ Bucket: 'messenger-attachments', Key: `attachments/${payload.att_id}/original` }));
|
||
agent.destroy();
|
||
return { rejected: false, status: 200 };
|
||
} catch (e) {
|
||
agent.destroy();
|
||
return { rejected: true, status: e.$metadata && e.$metadata.httpStatusCode || null, code: e.Code || e.name || null };
|
||
}
|
||
"""
|
||
s3_r = (common.run_node_probe(s3_js, {'ca_pem': ca_pem, 'ak': s3_ak, 'sk': s3_sk, 'att_id': att_id}, network='app_data').get('result') or {})
|
||
results['minio_s3'] = s3_r
|
||
|
||
# 5. Stolen g1 cert -> RabbitMQ AMQPS EXTERNAL -> rejected
|
||
rmq_js = """
|
||
const amqp = require('amqplib');
|
||
const crypto = require('crypto');
|
||
let conn = null;
|
||
try {
|
||
conn = await amqp.connect({
|
||
protocol: 'amqps', hostname: 'broker', port: 5671, vhost: 'messenger',
|
||
}, {
|
||
ca: [Buffer.from(payload.ca_pem)], cert: Buffer.from(payload.cert_pem), key: Buffer.from(payload.key_pem),
|
||
servername: 'broker', rejectUnauthorized: true, minVersion: 'TLSv1.2',
|
||
secureOptions: crypto.constants.SSL_OP_NO_TICKET,
|
||
credentials: amqp.credentials.external(),
|
||
});
|
||
await conn.close();
|
||
return { rejected: false };
|
||
} catch (e) {
|
||
return { rejected: true, error: (e && (e.message || e.code)) || String(e) };
|
||
}
|
||
"""
|
||
rmq_r = (common.run_node_probe(rmq_js, {'ca_pem': ca_pem, 'cert_pem': stolen_crt_pem, 'key_pem': stolen_key_pem}, network='app_data').get('result') or {})
|
||
results['rabbitmq'] = rmq_r
|
||
|
||
# 6. Stolen g1 cert -> OTel Gateway :4318 -> TLS revoked / 403
|
||
lat_r = (_probe_redis_and_api_lateral(ca_pem, stolen_crt_pem, stolen_key_pem).get('result') or {})
|
||
otel_r = lat_r.get('otel') or {}
|
||
results['otel_gateway'] = {
|
||
'rejected': otel_r.get('allowed') is False,
|
||
'status': otel_r.get('status'),
|
||
'error': otel_r.get('error'),
|
||
}
|
||
|
||
return results
|
||
|
||
|
||
def _verify_attachment_durability(client, actor, att_id, expected_bytes):
|
||
ready = client.wait_ready(actor, {'id': att_id}, wait_seconds=90)
|
||
dl = client.call('GET', f'/api/v1/attachments/{att_id}/content', 200, actor=actor)
|
||
orig_sha_expected = hashlib.sha256(expected_bytes).hexdigest()
|
||
orig_sha_actual = hashlib.sha256(dl['bytes']).hexdigest()
|
||
orig_match = (dl['bytes'] == expected_bytes and orig_sha_actual == orig_sha_expected == ready['sha256'])
|
||
|
||
variants = ready.get('variants') or []
|
||
var_names = sorted(v['name'] for v in variants)
|
||
thumbs = [v for v in variants if v['name'] == 'thumbnail']
|
||
thumb_ok = False
|
||
thumb_dims = None
|
||
if len(thumbs) == 1:
|
||
t = thumbs[0]
|
||
tdl = client.call('GET', f'/api/v1/attachments/{att_id}/content?variant=thumbnail', 200, actor=actor)
|
||
thumb_dims = jpeg_size(tdl['bytes'])
|
||
thumb_ok = (
|
||
tdl['headers'].get_content_type() == 'image/jpeg'
|
||
and thumb_dims == (256, 160)
|
||
and hashlib.sha256(tdl['bytes']).hexdigest() == t['sha256']
|
||
and len(tdl['bytes']) == t['size_bytes']
|
||
)
|
||
|
||
db_counts = common.psql_admin(
|
||
f"SELECT count(*), count(DISTINCT variant) FROM attachment_variants WHERE attachment_id = '{att_id}'"
|
||
)
|
||
total_v, distinct_v = (int(x) for x in db_counts.split(','))
|
||
no_dups = (total_v == distinct_v and total_v == 3)
|
||
|
||
return {
|
||
'attachment_id': att_id,
|
||
'status': ready['status'],
|
||
'original_sha256_match': orig_match,
|
||
'variant_names': var_names,
|
||
'db_variant_rows': total_v,
|
||
'db_distinct_variants': distinct_v,
|
||
'zero_duplicates': no_dups,
|
||
'thumbnail_256x160_ok': thumb_ok,
|
||
'thumbnail_dims': list(thumb_dims) if thumb_dims else None,
|
||
'passed': ready['status'] == 'ready' and orig_match and no_dups and thumb_ok,
|
||
}
|
||
|
||
|
||
def _render_markdown_summary(summary_data):
|
||
lines = [
|
||
'# Lab 7 — Grade 5, Track 1 («Компрометация worker») — Сводка эксперимента',
|
||
'',
|
||
f"- **Дата прогона (UTC):** `{summary_data['captured_at']}`",
|
||
f"- **Общий результат:** `{'PASS' if summary_data['passed'] else 'FAIL'}` ({summary_data['passed_count']}/{summary_data['total']} проверок)",
|
||
f"- **Zero Image Rebuild:** `api` `{summary_data['images']['api_before'][:19]}` == `{summary_data['images']['api_after'][:19]}`, `worker` `{summary_data['images']['worker_before'][:19]}` == `{summary_data['images']['worker_after'][:19]}`",
|
||
f"- **Ротация идентичности worker:** `{summary_data['worker_identity']['stolen_cn']}` (serial `{summary_data['worker_identity']['stolen_serial']}`) → `{summary_data['worker_identity']['recovered_cn']}` (serial `{summary_data['worker_identity']['recovered_serial']}`)",
|
||
'',
|
||
'## 1. Гипотеза',
|
||
'',
|
||
HYPOTHESIS,
|
||
'',
|
||
'## 2. Сравнение последствий: До (Lab 6) vs После (Lab 7 Least Privilege)',
|
||
'',
|
||
'| Контур | До (Lab 6 baseline) | После (Lab 7 hardened) | Снижение blast radius |',
|
||
'| --- | --- | --- | --- |',
|
||
]
|
||
for row in BEFORE_AFTER_MATRIX:
|
||
lines.append(
|
||
f"| **{row['domain']}** | {row['before_lab6']} | {row['after_lab7']} | {row['delta']} |"
|
||
)
|
||
lines.extend([
|
||
'',
|
||
'## 3. Проверка отзыва украденных credentials (`g1`) на новых соединениях (NC-6)',
|
||
'',
|
||
'| Граница | Результат после `scripts/revoke-worker.sh` | Деталь |',
|
||
'| --- | --- | --- |',
|
||
])
|
||
for boundary, info in (summary_data.get('revocation_new_connections') or {}).items():
|
||
status_str = 'REJECTED (PASS)' if info.get('rejected') else 'STILL ALLOWED (FAIL)'
|
||
detail = info.get('code') or info.get('status') or info.get('error') or ''
|
||
lines.append(f'| `{boundary}` | **{status_str}** | `{detail}` |')
|
||
|
||
lines.extend([
|
||
'',
|
||
'## 4. Сохранность и обработка заданий (Pre / During / Post Containment)',
|
||
'',
|
||
'| Этап | Attachment ID | Status | Original SHA-256 | Variants (0 dups) | Thumbnail 256×160 |',
|
||
'| --- | --- | --- | --- | --- | --- |',
|
||
])
|
||
for label, d in (summary_data.get('durability') or {}).items():
|
||
lines.append(
|
||
f"| `{label}` | `{d['attachment_id']}` | `{d['status']}` | "
|
||
f"`{d['original_sha256_match']}` | `{d['db_variant_rows']}/{d['db_distinct_variants']}` (`{d['zero_duplicates']}`) | "
|
||
f"`{d['thumbnail_256x160_ok']}` (`{d['thumbnail_dims']}`) |"
|
||
)
|
||
|
||
lines.extend([
|
||
'',
|
||
'## 5. Детальные результаты всех проверок',
|
||
'',
|
||
'| ID | Категория | Статус | Фактический результат |',
|
||
'| --- | --- | --- | --- |',
|
||
])
|
||
for chk in summary_data.get('checks', []):
|
||
lines.append(
|
||
f"| `{chk['id']}` | `{chk['category']}` | **{'PASS' if chk['passed'] else 'FAIL'}** | `{chk['actual']}` |"
|
||
)
|
||
|
||
lines.extend(['', '## 6. Остаточные риски и ограничения', ''])
|
||
for idx, risk in enumerate(RESIDUAL_RISKS, 1):
|
||
lines.append(f'{idx}. {risk}')
|
||
lines.append('')
|
||
return '\n'.join(lines)
|
||
|
||
|
||
def main(argv=None):
|
||
parser = argparse.ArgumentParser(description=__doc__)
|
||
common.add_common_args(parser, default_output='evidence/lab7/track1')
|
||
args = parser.parse_args(argv)
|
||
|
||
rc = common.ResultCollector('lab7-track1-worker-compromise')
|
||
ca_file = Path(args.ca_file)
|
||
ca_pem = ca_file.read_text(encoding='utf-8')
|
||
client = Client(args.base_url, str(ca_file))
|
||
sample = (common.ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||
|
||
# Step 0: Baseline, Image SHAs, Worker Env/Mount Hygiene, Canary Setup
|
||
api_cids = common.container_ids('api')
|
||
wrk_cids = common.container_ids('worker')
|
||
if not api_cids or not wrk_cids:
|
||
raise Failure('both api and worker containers must be running before Track 1')
|
||
img_api_before = common.container_inspect(api_cids[0])['Image']
|
||
wrk_insp = common.container_inspect(wrk_cids[0])
|
||
img_wrk_before = wrk_insp['Image']
|
||
|
||
wrk_env = (wrk_insp.get('Config') or {}).get('Env') or []
|
||
forbidden_wrk_keys = (
|
||
'POSTGRES_PASSWORD=', 'DATABASE_URL=', 'REDIS_URL=', 'REDIS_PASSWORD=',
|
||
'METRICS_TOKEN=', 'BAO_TOKEN=', 'VAULT_TOKEN=', 'MINIO_ROOT_PASSWORD=',
|
||
'S3_SECRET_ACCESS_KEY=',
|
||
)
|
||
wrk_env_leaks = [e.split('=', 1)[0] for e in wrk_env if any(e.startswith(f) for f in forbidden_wrk_keys)]
|
||
rc.add('T1-00-WORKER-ENV-CLEAN', 'baseline',
|
||
'Worker container env has zero static DB/Redis/S3/metrics/OpenBao secrets',
|
||
len(wrk_env_leaks) == 0, '0 secret env vars', f'leaked_vars={wrk_env_leaks}')
|
||
|
||
alice, bob, eve, chat = client.bootstrap()
|
||
for a in (alice, bob, eve):
|
||
rc.register_secret(a['registration']['password'])
|
||
rc.register_secret(a['token'])
|
||
canary_text = 'CONFIDENTIAL-TRACK1-' + uuid.uuid4().hex
|
||
canary_msg = client.message(alice, chat, canary_text)['json']
|
||
att_pre, _ = client.attachment(alice, chat)
|
||
att_pre_ready = client.wait_ready(bob, att_pre, wait_seconds=60)
|
||
rc.add('T1-01-BASELINE-UPLOAD-READY', 'baseline',
|
||
'Pre-compromise upload completes cleanly to status=ready',
|
||
att_pre_ready['status'] == 'ready', 'ready', f"att_pre={att_pre['id']} status={att_pre_ready['status']}")
|
||
|
||
# Seed S3 out-of-prefix canary backups/canary.txt and disposable staging/track1-probe/original
|
||
canary_seeded = False
|
||
staging_seeded = False
|
||
revocation_results = {}
|
||
durability_results = {}
|
||
stolen_cn = stolen_serial = recovered_cn = recovered_serial = None
|
||
|
||
try:
|
||
seed_res = _s3_admin_canary(ca_pem, 'put', key='backups/canary.txt', body='TRACK1-S3-CANARY')
|
||
canary_seeded = bool(seed_res.get('ok'))
|
||
st_res = _s3_admin_canary(ca_pem, 'put', key='staging/track1-probe/original', body='TRACK1-STAGING-PROBE')
|
||
staging_seeded = bool(st_res.get('ok'))
|
||
|
||
# Step 1: Capture stolen worker runtime context strictly from running worker container
|
||
stolen_crt_pem = _worker_exec_read('/run/certs/client.crt')
|
||
stolen_key_pem = _worker_exec_read('/run/certs/client.key')
|
||
rc.register_secret(stolen_key_pem)
|
||
stolen_cn, stolen_serial, stolen_san = _cert_cn_and_serial(stolen_crt_pem)
|
||
|
||
with tempfile.TemporaryDirectory(prefix='mtusi-t1-stolen-') as td:
|
||
crt_p = Path(td) / 'worker.crt'
|
||
key_p = Path(td) / 'worker.key'
|
||
crt_p.write_text(stolen_crt_pem, encoding='utf-8')
|
||
key_p.write_text(stolen_key_pem, encoding='utf-8')
|
||
wrk_bao = common.OpenBaoClient(args.openbao_url, str(ca_file), cert_file=crt_p, key_file=key_p)
|
||
st_login, _ = wrk_bao.cert_login('messenger-worker')
|
||
stolen_token = wrk_bao.token
|
||
rc.register_secret(stolen_token)
|
||
st_own, kv_own = wrk_bao.kv_read('secret/data/messenger/worker')
|
||
st_api, _ = wrk_bao.kv_read('secret/data/messenger/api')
|
||
st_mig, _ = wrk_bao.kv_read('secret/data/messenger/migrator')
|
||
st_adm, _ = wrk_bao.kv_read('secret/data/messenger/operator-admin')
|
||
st_pol, _ = wrk_bao.request('PUT', '/v1/sys/policies/acl/worker-policy', body={'policy': 'path "*" { capabilities = ["sudo"] }'})
|
||
st_cross, _ = wrk_bao.request('POST', '/v1/auth/cert/login', body={'name': 'messenger-api'}, token='')
|
||
|
||
wrk_sec = ((kv_own or {}).get('data') or {}).get('data') or {}
|
||
db_user = wrk_sec.get('db_user', 'messenger_worker')
|
||
db_pass = wrk_sec.get('db_password', '')
|
||
s3_ak = wrk_sec.get('s3_access_key_id', '')
|
||
s3_sk = wrk_sec.get('s3_secret_access_key', '')
|
||
for s in (db_pass, s3_ak, s3_sk):
|
||
rc.register_secret(s)
|
||
|
||
# Step 2: 26+ Blast-Radius Probes across all 6 boundaries
|
||
# --- OpenBao (6 probes) ---
|
||
rc.add('T1-BAO-01-ALLOW-OWN', 'blast_openbao',
|
||
'Compromised worker reads own secret/data/messenger/worker',
|
||
st_login == 200 and st_own == 200 and bool(db_pass) and bool(s3_sk),
|
||
'200 with DB+S3 creds', f'login={st_login} own={st_own} cn={stolen_cn} san={stolen_san}')
|
||
rc.add('T1-BAO-02-DENY-API', 'blast_openbao',
|
||
'Compromised worker DENIED secret/data/messenger/api',
|
||
st_api == 403, '403', f'status={st_api}')
|
||
rc.add('T1-BAO-03-DENY-MIGRATOR', 'blast_openbao',
|
||
'Compromised worker DENIED secret/data/messenger/migrator',
|
||
st_mig == 403, '403', f'status={st_mig}')
|
||
rc.add('T1-BAO-04-DENY-OPERATOR', 'blast_openbao',
|
||
'Compromised worker DENIED secret/data/messenger/operator-admin',
|
||
st_adm == 403, '403', f'status={st_adm}')
|
||
rc.add('T1-BAO-05-DENY-POLICY-WRITE', 'blast_openbao',
|
||
'Compromised worker DENIED sys/policies/acl write',
|
||
st_pol == 403, '403', f'status={st_pol}')
|
||
rc.add('T1-BAO-06-DENY-API-ROLE-LOGIN', 'blast_openbao',
|
||
'Worker cert DENIED auth/cert/login as messenger-api',
|
||
st_cross in (400, 403), '400/403', f'status={st_cross}')
|
||
|
||
# --- PostgreSQL (11+ probes) ---
|
||
pg = (_probe_pg_blast_radius(ca_pem, db_user, db_pass, att_pre['id']).get('result') or {})
|
||
pg_allow_ok = all(
|
||
(pg.get(k) or {}).get('allowed') is True
|
||
for k in ('allow_select_jobs', 'allow_select_attachments', 'allow_select_variants', 'allow_update_att_status_noop')
|
||
)
|
||
rc.add('T1-PG-07-ALLOW-PIPELINE', 'blast_postgres',
|
||
'messenger_worker allowed SELECT/scoped UPDATE on job pipeline tables',
|
||
pg_allow_ok, 'all 4 pipeline ops allowed',
|
||
{k: (pg.get(k) or {}).get('allowed') for k in ('allow_select_jobs', 'allow_select_attachments', 'allow_select_variants', 'allow_update_att_status_noop')})
|
||
|
||
pg_deny_specs = [
|
||
('T1-PG-08-DENY-USERS', 'deny_select_users', 'SELECT users (password_hash)'),
|
||
('T1-PG-09-DENY-MESSAGES', 'deny_select_messages', 'SELECT messages'),
|
||
('T1-PG-10-DENY-CHATS', 'deny_select_chats', 'SELECT chats'),
|
||
('T1-PG-11-DENY-CHAT-MEMBERS', 'deny_select_chat_members', 'SELECT chat_members'),
|
||
('T1-PG-12-DENY-MSG-ATT', 'deny_select_message_attachments', 'SELECT message_attachments'),
|
||
('T1-PG-13-DENY-IDEMPOTENCY', 'deny_select_idempotency', 'SELECT idempotency_keys'),
|
||
('T1-PG-14-DENY-MIGRATIONS', 'deny_select_migrations', 'SELECT schema_migrations'),
|
||
('T1-PG-15-DENY-DELETE-ATT', 'deny_delete_attachments', 'DELETE attachments'),
|
||
('T1-PG-16-DENY-DELETE-JOBS', 'deny_delete_jobs', 'DELETE attachment_jobs'),
|
||
('T1-PG-17-DENY-UPDATE-SHA256', 'deny_update_sha256', 'UPDATE attachments.sha256 (column-level integrity)'),
|
||
('T1-PG-18-DENY-DDL-CREATE', 'deny_ddl_create', 'DDL CREATE TABLE in public'),
|
||
]
|
||
for cid, key, desc in pg_deny_specs:
|
||
item = pg.get(key) or {}
|
||
rc.add(cid, 'blast_postgres', f'messenger_worker DENIED {desc} (42501)',
|
||
item.get('allowed') is False and item.get('code') == '42501',
|
||
'SQLSTATE 42501', f"allowed={item.get('allowed')} code={item.get('code')}")
|
||
|
||
# --- MinIO S3 (9+ probes) ---
|
||
s3 = (_probe_s3_blast_radius(ca_pem, s3_ak, s3_sk, att_pre['id']).get('result') or {})
|
||
s3_allow_keys = ('allow_get_staging', 'allow_del_staging', 'allow_get_original', 'allow_put_variant', 'allow_del_variant')
|
||
s3_allow_ok = all((s3.get(k) or {}).get('allowed') is True for k in s3_allow_keys)
|
||
rc.add('T1-S3-19-ALLOW-OWN-PREFIX', 'blast_s3',
|
||
'Worker S3 allowed staging/* Get/Delete, attachments/*/original Get, and attachments/*/v*/* Put/Delete',
|
||
s3_allow_ok, 'all 5 allowed (200/204)',
|
||
{k: (s3.get(k) or {}).get('status') for k in s3_allow_keys})
|
||
|
||
s3_deny_specs = [
|
||
('T1-S3-20-DENY-GET-BACKUPS', 'deny_get_backups', 'GetObject backups/canary.txt'),
|
||
('T1-S3-21-DENY-PUT-BACKUPS', 'deny_put_backups', 'PutObject backups/pwned.txt'),
|
||
('T1-S3-22-DENY-PUT-ADMIN', 'deny_put_admin', 'PutObject admin/pwned.txt'),
|
||
('T1-S3-23-DENY-PUT-STAGING', 'deny_put_staging', 'PutObject staging/forged/original'),
|
||
('T1-S3-24-DENY-DEL-ORIGINAL', 'deny_del_original', 'DeleteObject attachments/*/original'),
|
||
('T1-S3-25-DENY-LIST-ROOT', 'deny_list_root', 'ListBucket root & backups/'),
|
||
('T1-S3-26-DENY-CREATE-BUCKET', 'deny_create_bucket', 'CreateBucket'),
|
||
('T1-S3-27-DENY-MINIO-ADMIN', 'deny_minio_admin', 'MinIO Admin API /minio/admin/v3/info'),
|
||
]
|
||
for cid, key, desc in s3_deny_specs:
|
||
item = s3.get(key) or {}
|
||
extra_ok = True
|
||
if key == 'deny_list_root':
|
||
lb = s3.get('deny_list_backups') or {}
|
||
extra_ok = (lb.get('allowed') is False and lb.get('status') == 403)
|
||
rc.add(cid, 'blast_s3', f'Worker S3 DENIED {desc} (403)',
|
||
item.get('allowed') is False and item.get('status') == 403 and extra_ok,
|
||
'HTTP 403 AccessDenied',
|
||
f"allowed={item.get('allowed')} status={item.get('status')} code={item.get('code')}")
|
||
|
||
# --- RabbitMQ (6 probes) ---
|
||
rmq = (_probe_rabbitmq_blast_radius(ca_pem, stolen_crt_pem, stolen_key_pem).get('result') or {})
|
||
rc.add('T1-RMQ-28-ALLOW-CONSUME', 'blast_rabbitmq',
|
||
'Worker mTLS EXTERNAL allowed consume on attachments.process',
|
||
(rmq.get('allow_consume_process') or {}).get('allowed') is True,
|
||
'allowed=True', str(rmq.get('allow_consume_process')))
|
||
rmq_deny_specs = [
|
||
('T1-RMQ-29-DENY-PUBLISH-JOBS', 'deny_publish_jobs', 'publish to attachments.jobs'),
|
||
('T1-RMQ-30-DENY-DECLARE-QUEUE', 'deny_declare_queue', 'declare arbitrary queue'),
|
||
('T1-RMQ-31-DENY-DELETE-QUEUE', 'deny_delete_queue', 'delete attachments.process'),
|
||
('T1-RMQ-32-DENY-CONSUME-DLQ', 'deny_consume_dlq', 'consume attachments.process.dlq'),
|
||
('T1-RMQ-33-DENY-ROOT-VHOST', 'deny_root_vhost', 'connect to vhost /'),
|
||
]
|
||
for cid, key, desc in rmq_deny_specs:
|
||
item = rmq.get(key) or {}
|
||
rc.add(cid, 'blast_rabbitmq', f'Worker mTLS EXTERNAL DENIED {desc}',
|
||
item.get('allowed') is False, 'ACCESS_REFUSED',
|
||
f"allowed={item.get('allowed')} error={item.get('error')}")
|
||
|
||
# --- Redis & API mTLS Lateral Movement (2 probes) ---
|
||
lat = (_probe_redis_and_api_lateral(ca_pem, stolen_crt_pem, stolen_key_pem).get('result') or {})
|
||
r_lat = lat.get('redis') or {}
|
||
a_lat = lat.get('api') or {}
|
||
rc.add('T1-LAT-34-DENY-REDIS', 'blast_lateral',
|
||
'Compromised worker has zero Redis credentials and is rejected by Redis',
|
||
r_lat.get('allowed') is False and 'redis_password' not in wrk_sec,
|
||
'rejected & no redis creds', f"allowed={r_lat.get('allowed')} error={r_lat.get('error')}")
|
||
rc.add('T1-LAT-35-DENY-API-MTLS', 'blast_lateral',
|
||
'Compromised worker trusted-CA cert is rejected by API mTLS LB allowlist (403)',
|
||
a_lat.get('allowed') is False and (a_lat.get('status') == 403 or bool(a_lat.get('error'))),
|
||
'HTTP 403 or TLS reject', f"status={a_lat.get('status')} error={a_lat.get('error')}")
|
||
|
||
# Step 3: Quarantine compromised worker & enqueue pre- and during-containment uploads
|
||
common.compose('stop', 'worker')
|
||
att_before, _ = client.attachment(alice, chat)
|
||
att_during_1, _ = client.attachment(bob, chat)
|
||
att_during_2, _ = client.attachment(alice, chat)
|
||
rc.add('T1-CONTAIN-36-API-202-WHILE-WORKER-STOPPED', 'containment',
|
||
'While compromised worker is quarantined, API keeps accepting uploads (202 queued)',
|
||
all(a['status'] == 'queued' for a in (att_before, att_during_1, att_during_2)),
|
||
'3 queued 202 uploads',
|
||
f"ids={[att_before['id'], att_during_1['id'], att_during_2['id']]}")
|
||
|
||
# Step 4: Revoke compromised worker identity & rotate all related secrets (zero image rebuild)
|
||
common.run_host_script('scripts/revoke-worker.sh', '--no-start', operator_dir=args.operator_dir)
|
||
new_crt_pem = (common.ROOT / 'secrets/pki/worker/client.crt').read_text(encoding='utf-8')
|
||
recovered_cn, recovered_serial, _ = _cert_cn_and_serial(new_crt_pem)
|
||
rc.add('T1-REVOKE-37-IDENTITY-ROTATED', 'revocation',
|
||
'scripts/revoke-worker.sh issued new worker generation cert/serial without image rebuild',
|
||
bool(recovered_serial and recovered_serial != stolen_serial and recovered_cn != stolen_cn),
|
||
'new CN & new serial',
|
||
f'{stolen_cn}({stolen_serial}) -> {recovered_cn}({recovered_serial})')
|
||
|
||
# Step 5: Prove EVERY stolen g1 credential/cert fails on BRAND-NEW connections (NC-6)
|
||
revocation_results = _probe_revoked_g1(
|
||
ca_pem, args.openbao_url, str(ca_file),
|
||
stolen_token, stolen_crt_pem, stolen_key_pem,
|
||
db_user, db_pass, s3_ak, s3_sk, att_pre['id'],
|
||
)
|
||
for idx, (boundary, label) in enumerate((
|
||
('openbao_token', 'Stolen g1 OpenBao token rejected (403)'),
|
||
('openbao_cert', 'Stolen g1 cert rejected at OpenBao auth/cert/login CRL (400)'),
|
||
('postgres', 'Stolen g1 PostgreSQL password rejected on new TLS conn (28P01)'),
|
||
('minio_s3', 'Stolen g1 MinIO S3 key rejected on new HTTPS conn (403)'),
|
||
('rabbitmq', 'Stolen g1 cert rejected at RabbitMQ AMQPS EXTERNAL'),
|
||
('otel_gateway', 'Stolen g1 cert rejected at OTel Gateway mTLS CRL/allowlist'),
|
||
), 38):
|
||
info = revocation_results.get(boundary) or {}
|
||
rc.add(f'T1-REVOKED-{idx}-{boundary.upper()}', 'revocation_nc6', label,
|
||
info.get('rejected') is True, 'rejected=True on NEW connection', json.dumps(info))
|
||
|
||
# Step 6: Start clean recovered worker (g2) WITHOUT image rebuild & prove 100% job durability
|
||
common.compose('up', '-d', '--no-build', '--no-deps', '--wait', 'worker')
|
||
att_after, _ = client.attachment(alice, chat)
|
||
|
||
img_api_after = common.container_inspect(common.container_ids('api')[0])['Image']
|
||
img_wrk_after = common.container_inspect(common.container_ids('worker')[0])['Image']
|
||
rc.add('T1-RECOVER-44-ZERO-IMAGE-REBUILD', 'recovery',
|
||
'Recovered worker and API run identical Docker Image SHAs (zero rebuild)',
|
||
img_api_before == img_api_after and img_wrk_before == img_wrk_after,
|
||
'api & worker Image SHAs unchanged',
|
||
f'api_same={img_api_before == img_api_after}, worker_same={img_wrk_before == img_wrk_after}')
|
||
|
||
for label, actor, att in (
|
||
('pre_compromise', bob, att_pre),
|
||
('pre_revocation', alice, att_before),
|
||
('during_containment_1', bob, att_during_1),
|
||
('during_containment_2', alice, att_during_2),
|
||
('post_recovery', bob, att_after),
|
||
):
|
||
durability_results[label] = _verify_attachment_durability(client, actor, att['id'], sample)
|
||
|
||
all_durable = all(v['passed'] for v in durability_results.values())
|
||
rc.add('T1-RECOVER-45-ALL-JOBS-DURABLE', 'durability',
|
||
'All 5 pre/during/post-containment jobs reach ready with exact SHA-256, 256x160 JPEG thumbnail, and 0 duplicate variants',
|
||
all_durable, '5/5 durable, 0 lost, 0 duplicates',
|
||
{k: {'status': v['status'], 'sha_ok': v['original_sha256_match'], 'no_dups': v['zero_duplicates'], 'thumb_ok': v['thumbnail_256x160_ok']} for k, v in durability_results.items()})
|
||
|
||
# Verify confidential canary message survived intact and remains invisible to eve
|
||
msgs = client.call('GET', f"/api/v1/chats/{chat['id']}/messages?limit=50", 200, actor=bob, schema='MessagePage')['json']['items']
|
||
canary_intact = any(m['id'] == canary_msg['id'] and m['text'] == canary_text for m in msgs)
|
||
eve_blocked = client.call('GET', f"/api/v1/chats/{chat['id']}/messages", 404, actor=eve)['status'] == 404
|
||
rc.add('T1-RECOVER-46-CANARY-INTACT', 'durability',
|
||
'Confidential canary message survived containment intact and remains 404 to outsider',
|
||
canary_intact and eve_blocked, 'canary_intact=True, eve=404',
|
||
f'canary_intact={canary_intact}, eve_blocked={eve_blocked}')
|
||
|
||
finally:
|
||
# Ensure worker is running and temporary S3 canary object is cleaned up
|
||
try:
|
||
common.compose('up', '-d', '--no-build', '--no-deps', '--wait', 'worker', check_result=False)
|
||
except Exception:
|
||
pass
|
||
if canary_seeded:
|
||
try:
|
||
_s3_admin_canary(ca_pem, 'delete', key='backups/canary.txt')
|
||
except Exception:
|
||
pass
|
||
if staging_seeded:
|
||
try:
|
||
_s3_admin_canary(ca_pem, 'delete', key='staging/track1-probe/original')
|
||
except Exception:
|
||
pass
|
||
|
||
img_api_final = common.container_inspect(common.container_ids('api')[0])['Image']
|
||
img_wrk_final = common.container_inspect(common.container_ids('worker')[0])['Image']
|
||
rc.summary = {
|
||
'hypothesis': HYPOTHESIS,
|
||
'images': {
|
||
'api_before': img_api_before,
|
||
'api_after': img_api_final,
|
||
'worker_before': img_wrk_before,
|
||
'worker_after': img_wrk_final,
|
||
},
|
||
'worker_identity': {
|
||
'stolen_cn': stolen_cn,
|
||
'stolen_serial': stolen_serial,
|
||
'recovered_cn': recovered_cn,
|
||
'recovered_serial': recovered_serial,
|
||
},
|
||
'revocation_new_connections': revocation_results,
|
||
'durability': durability_results,
|
||
'before_vs_after': BEFORE_AFTER_MATRIX,
|
||
'residual_risks': RESIDUAL_RISKS,
|
||
}
|
||
(json_path, txt_path), rep = rc.save(args.output_dir, 'summary')
|
||
md_path = json_path.with_suffix('.md')
|
||
md_payload = dict(rep)
|
||
md_payload.update(rc.summary)
|
||
md_text = common.redact_text(_render_markdown_summary(md_payload), rc.extra_secrets)
|
||
md_path.write_text(md_text, encoding='utf-8')
|
||
|
||
print(f"Track 1 reports written: {json_path}, {md_path}, {txt_path} (passed={rep['passed']} {rep['passed_count']}/{rep['total']})")
|
||
return 0 if rep['passed'] else 1
|
||
|
||
|
||
if __name__ == '__main__':
|
||
try:
|
||
sys.exit(main())
|
||
except Failure as exc:
|
||
print('FAIL:', common.redact_text(str(exc)), file=sys.stderr)
|
||
sys.exit(1)
|