lab7: trust matrix, threat model, security test suite and Track 1 runner
This commit is contained in:
@@ -0,0 +1 @@
|
||||
"""Lab 7 automated security verification, audit, and Track 1 experiment suite."""
|
||||
Executable
+620
@@ -0,0 +1,620 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab 7 Application Security Verification Suite (Grade 3 + Grade 4).
|
||||
|
||||
Verifies:
|
||||
- Argon2id PHC format (m>=19456, t>=2, p>=1) + live stand wall-clock benchmark
|
||||
- Transparent password rehash on login (weak Argon2id + legacy $scrypt$)
|
||||
- Hashed Redis session storage (session:sha256:*, zero raw Bearer tokens)
|
||||
- Negative ACLs (outsider chat/messages/attachment metadata & content/cross-chat attach)
|
||||
- Forged X-User-Id rejection, logout revocation, and session expiry
|
||||
- Request size limits (>64 KiB JSON -> 413; >10 MiB / >40M px image -> 413)
|
||||
- Shared Redis login rate limit across >=2 API replicas (429 + Retry-After)
|
||||
- Bounded Argon2id login DoS concurrency protection (0 OOMKill, bounded latency)
|
||||
- Telemetry & HTTP error redaction audit (Loki/Tempo/error bodies -> 0 leaks)
|
||||
|
||||
Writes sanitized JSON + TXT report to evidence/lab7/app-security.{json,txt}.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import statistics
|
||||
import struct
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import uuid
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import common # noqa: E402
|
||||
from client import Client, Failure # noqa: E402
|
||||
|
||||
ARGON2_PHC_RE = re.compile(
|
||||
r'^\$argon2id\$v=(\d+)\$m=(\d+),t=(\d+),p=(\d+)\$([^$]+)\$([^$]+)$'
|
||||
)
|
||||
|
||||
|
||||
def _basic_hdr(username, password):
|
||||
raw = base64.b64encode(f'{username}:{password}'.encode('utf-8')).decode('ascii')
|
||||
return {'Authorization': 'Basic ' + raw}
|
||||
|
||||
|
||||
def _make_png(width, height):
|
||||
"""Build a valid minimal 1-bit grayscale PNG of (width x height) in stdlib."""
|
||||
def chunk(tag, data):
|
||||
crc = zlib.crc32(tag + data) & 0xFFFFFFFF
|
||||
return struct.pack('>I', len(data)) + tag + data + struct.pack('>I', crc)
|
||||
|
||||
ihdr = struct.pack('>IIBBBBB', width, height, 1, 0, 0, 0, 0)
|
||||
row_bytes = (width + 7) // 8
|
||||
raw_row = b'\x00' + (b'\x00' * row_bytes)
|
||||
comp = zlib.compressobj(level=1)
|
||||
parts = []
|
||||
# Feed in blocks to avoid allocating a huge uncompressed buffer in memory
|
||||
block = raw_row * 64
|
||||
full_blocks, rem = divmod(height, 64)
|
||||
for _ in range(full_blocks):
|
||||
parts.append(comp.compress(block))
|
||||
if rem:
|
||||
parts.append(comp.compress(raw_row * rem))
|
||||
parts.append(comp.flush())
|
||||
idat = b''.join(parts)
|
||||
return b'\x89PNG\r\n\x1a\n' + chunk(b'IHDR', ihdr) + chunk(b'IDAT', idat) + chunk(b'IEND', b'')
|
||||
|
||||
|
||||
def _clear_rate_limit_keys():
|
||||
"""Remove rl:* keys created during rate-limit/DoS tests so subsequent tests stay clean."""
|
||||
try:
|
||||
raw = common.redis_admin_cli('--scan', '--pattern', 'rl:*')
|
||||
keys = [k.strip() for k in raw.splitlines() if k.strip()]
|
||||
if keys:
|
||||
common.redis_admin_cli('DEL', *keys)
|
||||
except Failure:
|
||||
pass
|
||||
|
||||
|
||||
def _argon2_benchmark_in_api():
|
||||
"""Benchmark argon2@0.45.1 inside running API container for empirical parameter justification."""
|
||||
js = """
|
||||
const argon2 = require('argon2');
|
||||
const { performance } = require('perf_hooks');
|
||||
const configs = [
|
||||
{ label: 'floor_19MiB_t2_p1', memoryCost: 19456, timeCost: 2, parallelism: 1 },
|
||||
{ label: 'default_32MiB_t2_p1', memoryCost: 32768, timeCost: 2, parallelism: 1 },
|
||||
{ label: 'heavy_64MiB_t3_p1', memoryCost: 65536, timeCost: 3, parallelism: 1 },
|
||||
];
|
||||
const out = [];
|
||||
for (const cfg of configs) {
|
||||
const times = [];
|
||||
for (let i = 0; i < 4; i++) {
|
||||
const t0 = performance.now();
|
||||
await argon2.hash('Bench-P@ssw0rd-' + i, {
|
||||
type: argon2.argon2id,
|
||||
memoryCost: cfg.memoryCost,
|
||||
timeCost: cfg.timeCost,
|
||||
parallelism: cfg.parallelism,
|
||||
hashLength: 32,
|
||||
});
|
||||
times.push(Number((performance.now() - t0).toFixed(2)));
|
||||
}
|
||||
times.sort((a, b) => a - b);
|
||||
out.push({
|
||||
label: cfg.label,
|
||||
memory_kib: cfg.memoryCost,
|
||||
iterations: cfg.timeCost,
|
||||
parallelism: cfg.parallelism,
|
||||
samples_ms: times,
|
||||
median_ms: times[Math.floor(times.length / 2)],
|
||||
max_ms: times[times.length - 1],
|
||||
});
|
||||
}
|
||||
return { rss_mib: Number((process.memoryUsage().rss / (1024 * 1024)).toFixed(1)), configs: out };
|
||||
"""
|
||||
return common.run_node_probe(js, {}, exec_service='api', timeout=60)
|
||||
|
||||
|
||||
def _generate_legacy_hashes(password):
|
||||
js = """
|
||||
const argon2 = require('argon2');
|
||||
const crypto = require('crypto');
|
||||
const weakArgon = await argon2.hash(payload.password, {
|
||||
type: argon2.argon2id,
|
||||
memoryCost: 4096,
|
||||
timeCost: 1,
|
||||
parallelism: 1,
|
||||
hashLength: 32,
|
||||
});
|
||||
const salt = crypto.randomBytes(16);
|
||||
const dk = await new Promise((resolve, reject) => {
|
||||
crypto.scrypt(payload.password, salt, 32, { N: 16384, r: 8, p: 1 }, (err, key) => {
|
||||
if (err) reject(err); else resolve(key);
|
||||
});
|
||||
});
|
||||
const scryptPhc = `$scrypt$ln=14,r=8,p=1$${salt.toString('base64')}$${dk.toString('base64')}`;
|
||||
return { weakArgon, scryptPhc };
|
||||
"""
|
||||
return common.run_node_probe(js, {'password': password}, exec_service='api', timeout=30)
|
||||
|
||||
|
||||
def test_argon2_and_rehash(client, rc):
|
||||
user = client.user('argon2')
|
||||
rc.register_secret(user['registration']['password'])
|
||||
rc.register_secret(user['token'])
|
||||
|
||||
stored = common.psql_admin(
|
||||
f"SELECT password_hash FROM users WHERE id = '{user['id']}'"
|
||||
)
|
||||
rc.register_secret(stored)
|
||||
m = ARGON2_PHC_RE.match(stored)
|
||||
if m:
|
||||
ver, mem, iters, par = int(m.group(1)), int(m.group(2)), int(m.group(3)), int(m.group(4))
|
||||
prefix = f'$argon2id$v={ver}$m={mem},t={iters},p={par}'
|
||||
valid = ver == 19 and mem >= 19456 and iters >= 2 and par >= 1
|
||||
rc.add('APP-1-ARGON2-PHC', 'password_storage',
|
||||
'Stored password uses Argon2id PHC with m>=19456 KiB, t>=2, p>=1',
|
||||
valid, 'argon2id v=19, m>=19456, t>=2, p>=1', prefix,
|
||||
{'password_hash_prefix': prefix, 'm': mem, 't': iters, 'p': par})
|
||||
else:
|
||||
rc.add('APP-1-ARGON2-PHC', 'password_storage',
|
||||
'Stored password uses Argon2id PHC with m>=19456 KiB, t>=2, p>=1',
|
||||
False, 'argon2id PHC string', 'invalid format')
|
||||
mem, iters, par = 32768, 2, 1
|
||||
|
||||
# Empirical Argon2id benchmark inside running API container + live login latency
|
||||
bench_res = _argon2_benchmark_in_api()
|
||||
login_lat = []
|
||||
hdr = _basic_hdr(user['registration']['username'], user['registration']['password'])
|
||||
for _ in range(3):
|
||||
t0 = time.monotonic()
|
||||
r = client.call('POST', '/api/v1/auth/sessions', 201, headers=hdr, schema='Session')
|
||||
login_lat.append(round((time.monotonic() - t0) * 1000, 1))
|
||||
rc.register_secret(r['json']['token'])
|
||||
client.call('DELETE', '/api/v1/auth/sessions/current', 204,
|
||||
headers={'Authorization': 'Bearer ' + r['json']['token']})
|
||||
bench_data = bench_res.get('result') if bench_res.get('ok') else None
|
||||
rc.add('APP-2-ARGON2-BENCHMARK', 'password_storage',
|
||||
'Empirical Argon2id wall-clock benchmark captured on live stand',
|
||||
bool(bench_data) and len(login_lat) == 3,
|
||||
'benchmark completed',
|
||||
f'live_login_median_ms={statistics.median(login_lat)}',
|
||||
{'in_container_benchmark': bench_data, 'live_https_login_ms': login_lat})
|
||||
|
||||
# Transparent rehash: weak Argon2id (m=4096,t=1) -> upgraded to configured Argon2id
|
||||
gen = _generate_legacy_hashes(user['registration']['password'])
|
||||
if not gen.get('ok'):
|
||||
rc.add('APP-3-REHASH-WEAK-ARGON2', 'password_storage',
|
||||
'Transparent rehash of weak Argon2id hash on successful login',
|
||||
False, 'legacy hashes generated', gen.get('error'))
|
||||
return bench_data
|
||||
|
||||
weak_hash = gen['result']['weakArgon']
|
||||
scrypt_hash = gen['result']['scryptPhc']
|
||||
rc.register_secret(weak_hash)
|
||||
rc.register_secret(scrypt_hash)
|
||||
|
||||
escaped_weak = weak_hash.replace("'", "''")
|
||||
common.psql_admin(f"UPDATE users SET password_hash = '{escaped_weak}' WHERE id = '{user['id']}'")
|
||||
r_weak = client.call('POST', '/api/v1/auth/sessions', 201, headers=hdr, schema='Session')
|
||||
rc.register_secret(r_weak['json']['token'])
|
||||
upgraded_1 = common.psql_admin(f"SELECT password_hash FROM users WHERE id = '{user['id']}'")
|
||||
rc.register_secret(upgraded_1)
|
||||
m1 = ARGON2_PHC_RE.match(upgraded_1)
|
||||
rehashed_weak = bool(m1 and int(m1.group(2)) >= 19456 and int(m1.group(3)) >= 2 and upgraded_1 != weak_hash)
|
||||
# Prove subsequent login works with upgraded hash
|
||||
r_after1 = client.call('POST', '/api/v1/auth/sessions', 201, headers=hdr, schema='Session')
|
||||
rc.register_secret(r_after1['json']['token'])
|
||||
rc.add('APP-3-REHASH-WEAK-ARGON2', 'password_storage',
|
||||
'Login with weak Argon2id (m=4096,t=1) transparently upgrades DB hash to active params',
|
||||
rehashed_weak and r_after1['status'] == 201,
|
||||
f'upgraded to m>={mem}, t>={iters}',
|
||||
f'password_rehashed={rehashed_weak}, after_prefix=' +
|
||||
(f'$argon2id$v={m1.group(1)}$m={m1.group(2)},t={m1.group(3)},p={m1.group(4)}' if m1 else 'invalid'))
|
||||
|
||||
# Transparent rehash: legacy $scrypt$ -> upgraded to Argon2id
|
||||
escaped_scrypt = scrypt_hash.replace("'", "''")
|
||||
common.psql_admin(f"UPDATE users SET password_hash = '{escaped_scrypt}' WHERE id = '{user['id']}'")
|
||||
r_scrypt = client.call('POST', '/api/v1/auth/sessions', 201, headers=hdr, schema='Session')
|
||||
rc.register_secret(r_scrypt['json']['token'])
|
||||
upgraded_2 = common.psql_admin(f"SELECT password_hash FROM users WHERE id = '{user['id']}'")
|
||||
rc.register_secret(upgraded_2)
|
||||
m2 = ARGON2_PHC_RE.match(upgraded_2)
|
||||
rehashed_scrypt = bool(m2 and int(m2.group(2)) >= 19456 and int(m2.group(3)) >= 2)
|
||||
r_after2 = client.call('POST', '/api/v1/auth/sessions', 201, headers=hdr, schema='Session')
|
||||
rc.register_secret(r_after2['json']['token'])
|
||||
rc.add('APP-4-REHASH-LEGACY-SCRYPT', 'password_storage',
|
||||
'Login with legacy $scrypt$ hash transparently upgrades DB hash to Argon2id',
|
||||
rehashed_scrypt and r_after2['status'] == 201,
|
||||
'upgraded from $scrypt$ to $argon2id$',
|
||||
f'password_rehashed={rehashed_scrypt}, after_prefix=' +
|
||||
(f'$argon2id$v={m2.group(1)}$m={m2.group(2)},t={m2.group(3)},p={m2.group(4)}' if m2 else 'invalid'))
|
||||
|
||||
return bench_data
|
||||
|
||||
|
||||
def test_acl_sessions_and_limits(client, rc):
|
||||
alice, bob, eve, chat = client.bootstrap()
|
||||
for a in (alice, bob, eve):
|
||||
rc.register_secret(a['registration']['password'])
|
||||
rc.register_secret(a['token'])
|
||||
|
||||
# Upload attachment in (alice, bob) chat and wait ready
|
||||
att, _ = client.attachment(alice, chat)
|
||||
ready = client.wait_ready(bob, att, wait_seconds=60)
|
||||
eve_chat = client.call(
|
||||
'POST', '/api/v1/chats', 201, actor=eve,
|
||||
body={'title': 'Eve private chat', 'member_ids': [eve['id']]},
|
||||
schema='Chat',
|
||||
)['json']
|
||||
alice_chat2 = client.call(
|
||||
'POST', '/api/v1/chats', 201, actor=alice,
|
||||
body={'title': 'Alice second chat', 'member_ids': [alice['id']]},
|
||||
schema='Chat',
|
||||
)['json']
|
||||
|
||||
# 1. Outsider ACL & cross-chat attachment negative tests
|
||||
acl_checks = [
|
||||
('GET', f"/api/v1/chats/{chat['id']}", eve, None),
|
||||
('GET', f"/api/v1/chats/{chat['id']}/messages", eve, None),
|
||||
('POST', f"/api/v1/chats/{chat['id']}/messages", eve, {'text': 'outsider'}),
|
||||
('GET', f"/api/v1/attachments/{ready['id']}", eve, None),
|
||||
('GET', f"/api/v1/attachments/{ready['id']}/content", eve, None),
|
||||
('GET', f"/api/v1/attachments/{ready['id']}/content?variant=thumbnail", eve, None),
|
||||
('POST', f"/api/v1/chats/{eve_chat['id']}/messages", eve, {'text': '', 'attachment_ids': [ready['id']]}),
|
||||
('POST', f"/api/v1/chats/{alice_chat2['id']}/messages", alice, {'text': '', 'attachment_ids': [ready['id']]}),
|
||||
]
|
||||
acl_results = []
|
||||
all_acl_denied = True
|
||||
for method, path, actor, body in acl_checks:
|
||||
hdrs = {'Idempotency-Key': uuid.uuid4().hex} if method == 'POST' else None
|
||||
r = client.call(method, path, [403, 404], actor=actor, body=body, headers=hdrs)
|
||||
acl_results.append({'method': method, 'path': path.split('?')[0], 'status': r['status']})
|
||||
all_acl_denied &= (r['status'] in (403, 404))
|
||||
rc.add('APP-5-ACL-NEGATIVE', 'acl',
|
||||
'Outsider chat/messages/attachment metadata & content and cross-chat attach return 403/404',
|
||||
all_acl_denied, 'all 8 probes 403/404', json.dumps(acl_results))
|
||||
|
||||
# 2. Forged X-User-Id ignored
|
||||
r_no_auth = client.call('GET', '/api/v1/users/me', 401, headers={'X-User-Id': alice['id']})
|
||||
r_forged = client.call('GET', '/api/v1/users/me', 200, actor=eve,
|
||||
headers={'X-User-Id': alice['id']}, schema='User')
|
||||
rc.add('APP-6-FORGED-X-USER-ID', 'acl',
|
||||
'Forged X-User-Id rejected without Bearer (401) and ignored with Bearer',
|
||||
r_no_auth['status'] == 401 and r_forged['json']['id'] == eve['id'],
|
||||
f"no_auth=401, forged_me={eve['id']}",
|
||||
f"no_auth={r_no_auth['status']}, forged_me={r_forged['json']['id']}")
|
||||
|
||||
# 3. Hashed Redis sessions ONLY (session:sha256:*, zero raw Bearer token!)
|
||||
raw_token = alice['token']
|
||||
token_sha = hashlib.sha256(raw_token.encode('utf-8')).hexdigest()
|
||||
expected_key = 'session:sha256:' + token_sha
|
||||
all_sess_keys = [
|
||||
k.strip() for k in common.redis_admin_cli('--scan', '--pattern', 'session:*').splitlines() if k.strip()
|
||||
]
|
||||
key_exists = expected_key in all_sess_keys
|
||||
raw_in_keys = any(raw_token in k for k in all_sess_keys)
|
||||
all_prefixed_sha256 = bool(all_sess_keys) and all(k.startswith('session:sha256:') for k in all_sess_keys)
|
||||
val = common.redis_admin_cli('GET', expected_key) if key_exists else ''
|
||||
raw_in_val = raw_token in val
|
||||
rc.add('APP-7-HASHED-REDIS-SESSIONS', 'session_security',
|
||||
'Redis stores ONLY session:sha256:* keys with zero raw Bearer tokens in keys or values',
|
||||
key_exists and all_prefixed_sha256 and not raw_in_keys and not raw_in_val,
|
||||
'key_exists=True, all_sha256=True, raw_token_in_redis=False',
|
||||
f'key_exists={key_exists}, all_sha256={all_prefixed_sha256}, raw_token_in_redis={raw_in_keys or raw_in_val}, count={len(all_sess_keys)}')
|
||||
|
||||
# 4. Logout revocation & Session expiry
|
||||
r_out = client.call('DELETE', '/api/v1/auth/sessions/current', 204, actor=bob)
|
||||
r_after_out = client.call('GET', '/api/v1/users/me', 401, actor=bob)
|
||||
exp_user = client.user('expiry')
|
||||
rc.register_secret(exp_user['registration']['password'])
|
||||
rc.register_secret(exp_user['token'])
|
||||
exp_key = 'session:sha256:' + hashlib.sha256(exp_user['token'].encode('utf-8')).hexdigest()
|
||||
common.redis_admin_cli('PEXPIRE', exp_key, '800')
|
||||
time.sleep(1.3)
|
||||
r_expired = client.call('GET', '/api/v1/users/me', 401, actor=exp_user)
|
||||
rc.add('APP-8-LOGOUT-AND-EXPIRY', 'session_security',
|
||||
'Logout immediately revokes session (204->401) and expired session returns 401',
|
||||
r_out['status'] == 204 and r_after_out['status'] == 401 and r_expired['status'] == 401,
|
||||
'logout=204, after_logout=401, expired=401',
|
||||
f"logout={r_out['status']}, after_logout={r_after_out['status']}, expired={r_expired['status']}")
|
||||
|
||||
# 5. Request size limits: >64 KiB JSON -> 413, >10 MiB upload -> 413, >40M px image -> 413
|
||||
big_json = json.dumps({'text': 'A' * 70000}).encode('utf-8')
|
||||
r_json = client.call(
|
||||
'POST', f"/api/v1/chats/{chat['id']}/messages", 413,
|
||||
actor=alice, raw=big_json,
|
||||
headers={'Content-Type': 'application/json', 'Idempotency-Key': uuid.uuid4().hex},
|
||||
)
|
||||
rc.add('APP-9-JSON-BODY-LIMIT', 'request_limits',
|
||||
'Oversized JSON body (>64 KiB) rejected with 413 payload_too_large',
|
||||
r_json['status'] == 413 and r_json['json']['error']['code'] == 'payload_too_large',
|
||||
'HTTP 413 payload_too_large',
|
||||
f"status={r_json['status']} code={r_json['json']['error']['code']}")
|
||||
|
||||
oversize_bytes = (common.ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
oversize_bytes = oversize_bytes + (b'\x00' * (10 * 1024 * 1024 + 4096 - len(oversize_bytes)))
|
||||
r_up_bytes = client.call(
|
||||
'POST', f"/api/v1/chats/{chat['id']}/attachments?filename=huge.png", 413,
|
||||
actor=alice, raw=oversize_bytes, headers={'Content-Type': 'image/png'},
|
||||
)
|
||||
huge_px_png = _make_png(7000, 7000) # 49,000,000 px > 40M px limit
|
||||
r_up_px = client.call(
|
||||
'POST', f"/api/v1/chats/{chat['id']}/attachments?filename=hugepx.png", 413,
|
||||
actor=alice, raw=huge_px_png, headers={'Content-Type': 'image/png'},
|
||||
)
|
||||
rc.add('APP-10-UPLOAD-SIZE-AND-PIXELS', 'request_limits',
|
||||
'Oversized binary (>10 MiB) and pixel bomb (>40M px) rejected with 413',
|
||||
r_up_bytes['status'] == 413 and r_up_px['status'] == 413,
|
||||
'bytes=413, pixels=413',
|
||||
f"bytes={r_up_bytes['status']} ({len(oversize_bytes)}B), pixels={r_up_px['status']} (7000x7000, {len(huge_px_png)}B)")
|
||||
|
||||
return alice, chat
|
||||
|
||||
|
||||
def test_shared_ratelimit_and_dos(args, client, alice, rc):
|
||||
ca_file = args.ca_file
|
||||
base = args.base_url.rstrip('/')
|
||||
ctx = common.make_ssl_context(ca_file=ca_file)
|
||||
|
||||
# 1. Shared login rate limit across >=2 API replicas
|
||||
_clear_rate_limit_keys()
|
||||
rl_user = client.user('ratelimit')
|
||||
rc.register_secret(rl_user['registration']['password'])
|
||||
rc.register_secret(rl_user['token'])
|
||||
bad_hdr = _basic_hdr(rl_user['registration']['username'], 'wrong-password-123')
|
||||
|
||||
instances = set()
|
||||
statuses = []
|
||||
first_429_attempt = None
|
||||
retry_after_val = None
|
||||
error_code_429 = None
|
||||
|
||||
for i in range(1, 16):
|
||||
resp = common.https_request('POST', base + '/api/v1/auth/sessions',
|
||||
headers=bad_hdr, ssl_ctx=ctx)
|
||||
inst = resp['headers'].get('x-instance-id')
|
||||
if inst:
|
||||
instances.add(inst)
|
||||
statuses.append(resp['status'])
|
||||
if resp['status'] == 429 and first_429_attempt is None:
|
||||
first_429_attempt = i
|
||||
retry_after_val = resp['headers'].get('retry-after')
|
||||
try:
|
||||
body_j = json.loads(resp['body'].decode('utf-8'))
|
||||
error_code_429 = body_j.get('error', {}).get('code')
|
||||
except ValueError:
|
||||
error_code_429 = None
|
||||
break
|
||||
|
||||
# Verify opaque X-Instance-Id format (no 12-char container IDs / IP / hostname)
|
||||
api_cids = [c[:12] for c in common.container_ids('api')]
|
||||
opaque_ok = bool(instances) and not any(
|
||||
any(cid in inst for cid in api_cids) or '.' in inst for inst in instances
|
||||
)
|
||||
retry_ok = bool(retry_after_val and retry_after_val.isdigit() and int(retry_after_val) >= 1)
|
||||
shared_ok = (
|
||||
len(instances) >= 2
|
||||
and first_429_attempt is not None
|
||||
and first_429_attempt <= 11
|
||||
and retry_ok
|
||||
and error_code_429 == 'rate_limited'
|
||||
and opaque_ok
|
||||
)
|
||||
rc.add('APP-11-SHARED-RATE-LIMIT', 'rate_limit',
|
||||
'Shared Redis login rate limit triggers 429+Retry-After across >=2 opaque API replicas',
|
||||
shared_ok,
|
||||
'instances>=2, first_429<=11, Retry-After>=1, code=rate_limited, opaque X-Instance-Id',
|
||||
f'instances={sorted(instances)}, first_429={first_429_attempt}, retry_after={retry_after_val}, code={error_code_429}, opaque={opaque_ok}')
|
||||
|
||||
# 2. Login DoS concurrency budget test (parallel invalid logins + concurrent authenticated traffic)
|
||||
_clear_rate_limit_keys()
|
||||
restarts_before = {
|
||||
cid[:12]: common.container_inspect(cid)['RestartCount']
|
||||
for cid in common.container_ids('api')
|
||||
}
|
||||
|
||||
def do_bad_login(idx):
|
||||
h = _basic_hdr(f'dos_nonexistent_{idx}_{uuid.uuid4().hex[:6]}', 'Wrong-DoS-Pass!')
|
||||
t0 = time.monotonic()
|
||||
r = common.https_request('POST', base + '/api/v1/auth/sessions', headers=h, ssl_ctx=ctx, timeout=15)
|
||||
return r['status'], round((time.monotonic() - t0) * 1000, 1), r['headers'].get('retry-after')
|
||||
|
||||
def do_auth_me(_idx):
|
||||
h = {'Authorization': 'Bearer ' + alice['token']}
|
||||
t0 = time.monotonic()
|
||||
r = common.https_request('GET', base + '/api/v1/users/me', headers=h, ssl_ctx=ctx, timeout=10)
|
||||
return r['status'], round((time.monotonic() - t0) * 1000, 1)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=40) as pool:
|
||||
login_futs = [pool.submit(do_bad_login, i) for i in range(36)]
|
||||
time.sleep(0.15)
|
||||
auth_futs = [pool.submit(do_auth_me, i) for i in range(10)]
|
||||
login_results = [f.result() for f in login_futs]
|
||||
auth_results = [f.result() for f in auth_futs]
|
||||
|
||||
login_codes = {}
|
||||
shed_retry_ok = True
|
||||
for st, _ms, ra in login_results:
|
||||
login_codes[st] = login_codes.get(st, 0) + 1
|
||||
if st == 429 and not (ra and ra.isdigit() and int(ra) >= 1):
|
||||
shed_retry_ok = False
|
||||
auth_ok = all(st == 200 for st, _ in auth_results)
|
||||
auth_latencies = sorted(ms for _, ms in auth_results)
|
||||
auth_p95 = auth_latencies[int(0.95 * (len(auth_latencies) - 1))] if auth_latencies else None
|
||||
|
||||
oom_any = False
|
||||
restarts_after = {}
|
||||
for cid in common.container_ids('api'):
|
||||
insp = common.container_inspect(cid)
|
||||
oom_any |= bool((insp.get('State') or {}).get('OOMKilled', False))
|
||||
restarts_after[cid[:12]] = insp['RestartCount']
|
||||
no_restarts = restarts_after == restarts_before
|
||||
|
||||
# Clear rl:* right after DoS test so host IP isn't throttled for subsequent scripts
|
||||
_clear_rate_limit_keys()
|
||||
|
||||
dos_ok = (
|
||||
not oom_any
|
||||
and no_restarts
|
||||
and auth_ok
|
||||
and shed_retry_ok
|
||||
and all(code in (401, 429) for code in login_codes)
|
||||
and (login_codes.get(429, 0) >= 1 or max(ms for _, ms, _ in login_results) < 5000)
|
||||
)
|
||||
rc.add('APP-12-LOGIN-DOS-BUDGET', 'dos_protection',
|
||||
'Parallel login burst stays bounded under Argon2id semaphore with 0 OOMKill and unaffected /users/me',
|
||||
dos_ok,
|
||||
'0 OOMKill, 0 restarts, all auth=200, valid 401/429+Retry-After',
|
||||
f'login_codes={login_codes}, auth_p95_ms={auth_p95}, oom={oom_any}, restarts_unchanged={no_restarts}',
|
||||
{'login_codes': login_codes, 'auth_latencies_ms': auth_latencies, 'shed_retry_ok': shed_retry_ok})
|
||||
|
||||
|
||||
def test_telemetry_redaction(args, client, alice, chat, rc):
|
||||
marker = 'LAB7-SECRET-CANARY-' + uuid.uuid4().hex[:12]
|
||||
fake_bao = 'hvs.FAKECANARYTOKEN' + uuid.uuid4().hex[:12]
|
||||
wrong_pw = 'WrongSecret-' + marker
|
||||
rc.register_secret(fake_bao)
|
||||
rc.register_secret(wrong_pw)
|
||||
|
||||
r_msg = client.call(
|
||||
'POST', f"/api/v1/chats/{chat['id']}/messages", 201,
|
||||
actor=alice, body={'text': 'confidential ' + marker},
|
||||
headers={'Idempotency-Key': uuid.uuid4().hex, 'X-Vault-Token': fake_bao},
|
||||
schema='Message',
|
||||
)
|
||||
r_bad = client.call(
|
||||
'POST', '/api/v1/auth/sessions', 401,
|
||||
headers=_basic_hdr(alice['registration']['username'], wrong_pw),
|
||||
)
|
||||
r_404 = client.call(
|
||||
'GET', f"/api/v1/chats/{uuid.uuid4()}", 404,
|
||||
actor=alice, headers={'X-Vault-Token': fake_bao},
|
||||
)
|
||||
|
||||
needles = {
|
||||
'password': [alice['registration']['password'], wrong_pw],
|
||||
'bearer_token': [alice['token']],
|
||||
'bao_token': [fake_bao],
|
||||
'message_body': [marker],
|
||||
'argon2_hash': ['$argon2id$v='],
|
||||
'private_key': ['-----BEGIN PRIVATE KEY-----', '-----BEGIN EC PRIVATE KEY-----'],
|
||||
}
|
||||
|
||||
# Check HTTP error response bodies directly
|
||||
err_leaks = []
|
||||
for label, resp in (('401_login', r_bad), ('404_chat', r_404)):
|
||||
txt = resp['bytes'].decode('utf-8', errors='replace')
|
||||
for cat, items in needles.items():
|
||||
for n in items:
|
||||
if n and n in txt:
|
||||
err_leaks.append({'source': 'http_error:' + label, 'category': cat})
|
||||
|
||||
# Query Loki & Tempo through Grafana HTTPS proxy
|
||||
graf_pw = common.read_secret_file('grafana_admin_password')
|
||||
if graf_pw:
|
||||
rc.register_secret(graf_pw)
|
||||
telemetry_leaks = []
|
||||
scanned_logs = 0
|
||||
scanned_spans = 0
|
||||
loki_checked = False
|
||||
tempo_checked = False
|
||||
|
||||
if graf_pw:
|
||||
ctx = common.make_ssl_context(ca_file=args.ca_file)
|
||||
ghdr = common.basic_auth_header('admin', graf_pw)
|
||||
rids = [r_msg['headers']['X-Request-Id'], r_bad['headers']['X-Request-Id'], r_404['headers']['X-Request-Id']]
|
||||
trace_ids = set()
|
||||
|
||||
# Wait up to 20s for logs to flush to Loki
|
||||
deadline = time.monotonic() + 20
|
||||
loki_rows = []
|
||||
while time.monotonic() < deadline:
|
||||
now_ns = time.time_ns()
|
||||
params = urllib.parse.urlencode({
|
||||
'query': '{service_name=~"messenger-.*"}',
|
||||
'start': str(now_ns - 120 * 10**9),
|
||||
'end': str(now_ns + 10 * 10**9),
|
||||
'limit': '1000',
|
||||
})
|
||||
resp = common.https_request(
|
||||
'GET',
|
||||
args.grafana_url.rstrip('/') + '/api/datasources/proxy/uid/loki/loki/api/v1/query_range?' + params,
|
||||
headers=ghdr, ssl_ctx=ctx,
|
||||
)
|
||||
if resp['status'] == 200:
|
||||
loki_checked = True
|
||||
body = json.loads(resp['body'].decode('utf-8'))
|
||||
loki_rows = []
|
||||
for stream in body.get('data', {}).get('result', []):
|
||||
labels = stream.get('stream', {})
|
||||
if labels.get('request_id') in rids and labels.get('trace_id'):
|
||||
trace_ids.add(labels['trace_id'])
|
||||
for _ts, line in stream.get('values', []):
|
||||
loki_rows.append(line + ' ' + json.dumps(labels, sort_keys=True))
|
||||
if trace_ids:
|
||||
break
|
||||
time.sleep(2)
|
||||
|
||||
scanned_logs = len(loki_rows)
|
||||
for text in loki_rows:
|
||||
for cat, items in needles.items():
|
||||
for n in items:
|
||||
if n and n in text:
|
||||
telemetry_leaks.append({'source': 'loki', 'category': cat})
|
||||
break
|
||||
|
||||
for tid in trace_ids:
|
||||
resp = common.https_request(
|
||||
'GET',
|
||||
args.grafana_url.rstrip('/') + '/api/datasources/proxy/uid/tempo/api/traces/' + tid,
|
||||
headers={**ghdr, 'Accept': 'application/json'}, ssl_ctx=ctx,
|
||||
)
|
||||
if resp['status'] == 200:
|
||||
tempo_checked = True
|
||||
raw_trace = resp['body'].decode('utf-8', errors='replace')
|
||||
scanned_spans += 1
|
||||
for cat, items in needles.items():
|
||||
for n in items:
|
||||
if n and n in raw_trace:
|
||||
telemetry_leaks.append({'source': 'tempo:' + tid[:8], 'category': cat})
|
||||
break
|
||||
|
||||
total_leaks = len(err_leaks) + len(telemetry_leaks)
|
||||
rc.add('APP-13-TELEMETRY-AND-ERROR-REDACTION', 'redaction',
|
||||
'Zero secret/token/password/Argon2/body leaks in HTTP errors, Loki logs, and Tempo traces',
|
||||
total_leaks == 0 and loki_checked,
|
||||
'0 leaks, loki_checked=True',
|
||||
f'leaks={total_leaks}, loki_checked={loki_checked} ({scanned_logs} logs), tempo_checked={tempo_checked} ({scanned_spans} traces)',
|
||||
{'leaks': err_leaks + telemetry_leaks})
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
common.add_common_args(parser)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
rc = common.ResultCollector('lab7-app-security')
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
try:
|
||||
bench = test_argon2_and_rehash(client, rc)
|
||||
alice, chat = test_acl_sessions_and_limits(client, rc)
|
||||
test_shared_ratelimit_and_dos(args, client, alice, rc)
|
||||
test_telemetry_redaction(args, client, alice, chat, rc)
|
||||
finally:
|
||||
_clear_rate_limit_keys()
|
||||
|
||||
rc.summary = {'base_url': args.base_url, 'argon2_benchmark': bench}
|
||||
(json_path, txt_path), rep = rc.save(args.output_dir, 'app-security')
|
||||
print(f"Report written: {json_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)
|
||||
@@ -0,0 +1,740 @@
|
||||
"""Shared stdlib-only helpers for Lab 7 security audits, lifecycle tests, and Track 1.
|
||||
|
||||
Python 3.9+, standard library only. Never prints or persists raw secrets,
|
||||
tokens, private keys, unseal shares, or password hashes.
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import hashlib
|
||||
import http.client
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[2]
|
||||
if str(ROOT / 'tests') not in sys.path:
|
||||
sys.path.insert(0, str(ROOT / 'tests'))
|
||||
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
|
||||
PROJECT = 'mtusi-lab7'
|
||||
ENV_FILE = '.env'
|
||||
COMPOSE = ['docker', 'compose', '--env-file', ENV_FILE]
|
||||
|
||||
_PEM_KEY_RE = re.compile(
|
||||
r'-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z0-9 ]*PRIVATE KEY-----',
|
||||
re.MULTILINE,
|
||||
)
|
||||
_BAO_TOKEN_RE = re.compile(r'\b(?:hvs|hvb|hvr)\.[A-Za-z0-9._-]{8,}\b|\bs\.[A-Za-z0-9]{16,}\b')
|
||||
_BEARER_RE = re.compile(r'(?i)\bBearer\s+[A-Za-z0-9._~+/=-]{8,}')
|
||||
_BASIC_RE = re.compile(r'(?i)\bBasic\s+[A-Za-z0-9+/=]{8,}')
|
||||
_ARGON2_RE = re.compile(r'(\$argon2(?:id|i|d)\$v=\d+\$m=\d+,t=\d+,p=\d+)\$[^$\s"\']+\$[^$\s"\']+')
|
||||
_SCRYPT_RE = re.compile(r'(\$scrypt\$[^$\s"\']+)\$[^$\s"\']+\$[^$\s"\']+')
|
||||
_URL_CRED_RE = re.compile(r'([a-zA-Z][a-zA-Z0-9+.-]*://[^/\s:@]+:)([^/\s@]+)(@)')
|
||||
|
||||
_SENSITIVE_KEY_RE = re.compile(
|
||||
r'(?:^|_)(?:password|passwd|secret|token|private_key|unseal|access_key_id|'
|
||||
r'secret_access_key|authorization|cookie|passphrase|key_pem|client_key|ca_key)$',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
_SAFE_META_KEYS = {
|
||||
'password_rehashed',
|
||||
'password_hash_params',
|
||||
'password_hash_prefix',
|
||||
'password_hash_valid',
|
||||
'old_password_rejected',
|
||||
'token_revoked',
|
||||
'token_expired',
|
||||
'token_ttl_seconds',
|
||||
'token_renewable',
|
||||
'token_reauth_ok',
|
||||
'raw_token_in_redis',
|
||||
'root_token_revoked',
|
||||
'secret_version',
|
||||
'secret_version_before',
|
||||
'secret_version_after',
|
||||
'secret_rotated',
|
||||
'secret_leaks',
|
||||
'secret_env_violations',
|
||||
'metrics_token_blocked',
|
||||
'authorization_header_redacted',
|
||||
}
|
||||
|
||||
|
||||
def utc_now():
|
||||
return time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime())
|
||||
|
||||
|
||||
def default_operator_dir():
|
||||
env = os.environ.get('LAB7_OPERATOR_DIR')
|
||||
if env:
|
||||
return Path(env)
|
||||
state_home = os.environ.get('XDG_STATE_HOME') or os.path.join(
|
||||
os.path.expanduser('~'), '.local', 'state'
|
||||
)
|
||||
return Path(state_home) / 'mtusi-lab7-operator'
|
||||
|
||||
|
||||
def default_ca_file():
|
||||
return Path(os.environ.get('CA_FILE') or (ROOT / 'secrets/pki/ca.crt'))
|
||||
|
||||
|
||||
def first_existing(candidates):
|
||||
for path in candidates:
|
||||
p = Path(path)
|
||||
if p.exists():
|
||||
return p
|
||||
return Path(candidates[0])
|
||||
|
||||
|
||||
def operator_cert_pair(operator_dir):
|
||||
op = Path(operator_dir)
|
||||
crt = first_existing([
|
||||
op / 'operator/operator.crt',
|
||||
op / 'operator-cert/operator.crt',
|
||||
])
|
||||
key = first_existing([
|
||||
op / 'operator/operator.key',
|
||||
op / 'operator-cert/operator.key',
|
||||
])
|
||||
return crt, key
|
||||
|
||||
|
||||
def rogue_cert_pair(operator_dir):
|
||||
op = Path(operator_dir)
|
||||
return op / 'pki/rogue-client.crt', op / 'pki/rogue-client.key'
|
||||
|
||||
|
||||
def foreign_ca_and_client(operator_dir):
|
||||
op = Path(operator_dir)
|
||||
return (
|
||||
op / 'pki/foreign-ca.crt',
|
||||
op / 'pki/foreign-client.crt',
|
||||
op / 'pki/foreign-client.key',
|
||||
)
|
||||
|
||||
|
||||
def haproxy_client_pair():
|
||||
base = ROOT / 'secrets/pki/haproxy'
|
||||
crt = base / 'client.crt'
|
||||
key = base / 'client.key'
|
||||
if crt.exists() and key.exists():
|
||||
return crt, key
|
||||
pem = first_existing([base / 'client.pem', base / 'client-bundle.pem'])
|
||||
return pem, None
|
||||
|
||||
|
||||
def service_client_pair(service):
|
||||
base = ROOT / 'secrets/pki' / service
|
||||
return base / 'client.crt', base / 'client.key'
|
||||
|
||||
|
||||
def read_secret_file(names):
|
||||
"""Read a trimmed secret from ./secrets/infra/<name> or ./secrets/<name>."""
|
||||
if isinstance(names, (str, Path)):
|
||||
names = [names]
|
||||
candidates = []
|
||||
for name in names:
|
||||
candidates.append(ROOT / 'secrets/infra' / name)
|
||||
candidates.append(ROOT / 'secrets' / name)
|
||||
for path in candidates:
|
||||
if path.is_file():
|
||||
return path.read_text(encoding='utf-8').strip()
|
||||
return None
|
||||
|
||||
|
||||
def add_common_args(parser, default_output='evidence/lab7'):
|
||||
parser.add_argument(
|
||||
'--base-url',
|
||||
default=os.environ.get('BASE_URL', 'https://localhost:8443'),
|
||||
)
|
||||
parser.add_argument('--ca-file', default=str(default_ca_file()))
|
||||
parser.add_argument('--operator-dir', default=str(default_operator_dir()))
|
||||
parser.add_argument(
|
||||
'--openbao-url',
|
||||
default=os.environ.get('BAO_ADDR', 'https://localhost:8200'),
|
||||
)
|
||||
parser.add_argument(
|
||||
'--prometheus-url',
|
||||
default=os.environ.get('PROMETHEUS_URL', 'https://localhost:9090'),
|
||||
)
|
||||
parser.add_argument(
|
||||
'--grafana-url',
|
||||
default=os.environ.get('GRAFANA_URL', 'https://localhost:3000'),
|
||||
)
|
||||
parser.add_argument(
|
||||
'--s3-url',
|
||||
default=os.environ.get('S3_PUBLIC_ENDPOINT', 'https://localhost:9000'),
|
||||
)
|
||||
parser.add_argument('--output-dir', default=default_output)
|
||||
return parser
|
||||
|
||||
|
||||
# ----------------------------------------------------------- secret redaction
|
||||
|
||||
def redact_text(text, extra_secrets=None):
|
||||
if not isinstance(text, str):
|
||||
return text
|
||||
out = _PEM_KEY_RE.sub('[REDACTED_PRIVATE_KEY]', text)
|
||||
out = _BAO_TOKEN_RE.sub('[REDACTED_BAO_TOKEN]', out)
|
||||
out = _BEARER_RE.sub('Bearer [REDACTED]', out)
|
||||
out = _BASIC_RE.sub('Basic [REDACTED]', out)
|
||||
out = _ARGON2_RE.sub(r'\1$[REDACTED_SALT_AND_HASH]', out)
|
||||
out = _SCRYPT_RE.sub(r'\1$[REDACTED_SALT_AND_HASH]', out)
|
||||
out = _URL_CRED_RE.sub(r'\1[REDACTED]\3', out)
|
||||
if extra_secrets:
|
||||
for secret in sorted(set(s for s in extra_secrets if isinstance(s, str) and len(s) >= 6), key=len, reverse=True):
|
||||
if secret in out:
|
||||
out = out.replace(secret, '[REDACTED]')
|
||||
return out
|
||||
|
||||
|
||||
def sanitize_data(obj, extra_secrets=None):
|
||||
if isinstance(obj, dict):
|
||||
cleaned = {}
|
||||
for k, v in obj.items():
|
||||
key_str = str(k)
|
||||
if (
|
||||
key_str not in _SAFE_META_KEYS
|
||||
and _SENSITIVE_KEY_RE.search(key_str)
|
||||
and isinstance(v, str)
|
||||
and v
|
||||
):
|
||||
cleaned[key_str] = '[REDACTED]'
|
||||
else:
|
||||
cleaned[key_str] = sanitize_data(v, extra_secrets)
|
||||
return cleaned
|
||||
if isinstance(obj, list):
|
||||
return [sanitize_data(item, extra_secrets) for item in obj]
|
||||
if isinstance(obj, tuple):
|
||||
return [sanitize_data(item, extra_secrets) for item in obj]
|
||||
if isinstance(obj, str):
|
||||
return redact_text(obj, extra_secrets)
|
||||
return obj
|
||||
|
||||
|
||||
def write_evidence(output_dir, stem, report, extra_secrets=None):
|
||||
out_path = Path(output_dir)
|
||||
if not out_path.is_absolute():
|
||||
out_path = ROOT / out_path
|
||||
out_path.mkdir(parents=True, exist_ok=True)
|
||||
safe = sanitize_data(report, extra_secrets)
|
||||
json_path = out_path / (stem + '.json')
|
||||
txt_path = out_path / (stem + '.txt')
|
||||
json_path.write_text(
|
||||
json.dumps(safe, indent=2, ensure_ascii=False, sort_keys=True) + '\n',
|
||||
encoding='utf-8',
|
||||
)
|
||||
lines = [
|
||||
f"suite={safe.get('suite', stem)} passed={safe.get('passed')} "
|
||||
f"checks={safe.get('passed_count', 0)}/{safe.get('total', 0)} "
|
||||
f"captured_at={safe.get('captured_at', utc_now())}",
|
||||
'',
|
||||
]
|
||||
for item in safe.get('checks', []):
|
||||
mark = 'PASS' if item.get('passed') else 'FAIL'
|
||||
lines.append(
|
||||
f"[{mark}] {item.get('id')} ({item.get('category', 'general')}): "
|
||||
f"{item.get('description', '')} -> {item.get('actual', '')}"
|
||||
)
|
||||
if safe.get('summary'):
|
||||
lines.append('')
|
||||
lines.append('summary=' + json.dumps(safe['summary'], ensure_ascii=False, sort_keys=True))
|
||||
txt_path.write_text('\n'.join(lines) + '\n', encoding='utf-8')
|
||||
return json_path, txt_path
|
||||
|
||||
|
||||
class ResultCollector:
|
||||
"""Collects structured pass/fail security assertions for JSON + TXT evidence."""
|
||||
|
||||
def __init__(self, suite):
|
||||
self.suite = suite
|
||||
self.started_at = utc_now()
|
||||
self.checks = []
|
||||
self.summary = {}
|
||||
self.extra_secrets = set()
|
||||
|
||||
def register_secret(self, value):
|
||||
if isinstance(value, str) and len(value) >= 6:
|
||||
self.extra_secrets.add(value)
|
||||
|
||||
def add(self, check_id, category, description, passed, expected, actual, evidence=None):
|
||||
entry = {
|
||||
'id': check_id,
|
||||
'category': category,
|
||||
'description': description,
|
||||
'passed': bool(passed),
|
||||
'expected': expected,
|
||||
'actual': actual,
|
||||
}
|
||||
if evidence is not None:
|
||||
entry['evidence'] = evidence
|
||||
self.checks.append(entry)
|
||||
mark = 'PASS' if passed else 'FAIL'
|
||||
print(f"[{mark}] {check_id}: {description} ({redact_text(str(actual), self.extra_secrets)})", flush=True)
|
||||
return bool(passed)
|
||||
|
||||
def report(self):
|
||||
passed_count = sum(1 for c in self.checks if c['passed'])
|
||||
failed = [c['id'] for c in self.checks if not c['passed']]
|
||||
return {
|
||||
'suite': self.suite,
|
||||
'started_at': self.started_at,
|
||||
'captured_at': utc_now(),
|
||||
'passed': len(failed) == 0 and len(self.checks) > 0,
|
||||
'total': len(self.checks),
|
||||
'passed_count': passed_count,
|
||||
'failed_count': len(failed),
|
||||
'failed_ids': failed,
|
||||
'summary': self.summary,
|
||||
'checks': self.checks,
|
||||
}
|
||||
|
||||
def save(self, output_dir, stem):
|
||||
rep = self.report()
|
||||
return write_evidence(output_dir, stem, rep, self.extra_secrets), rep
|
||||
|
||||
|
||||
# ------------------------------------------------------ docker & host scripts
|
||||
|
||||
def compose(*args, stdin=None, check_result=True, timeout=180, env_extra=None):
|
||||
env = os.environ.copy()
|
||||
if env_extra:
|
||||
env.update(env_extra)
|
||||
result = subprocess.run(
|
||||
COMPOSE + list(args),
|
||||
cwd=ROOT,
|
||||
input=stdin,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
env=env,
|
||||
)
|
||||
if check_result and result.returncode != 0:
|
||||
detail = redact_text((result.stderr or result.stdout).strip())
|
||||
last = detail.splitlines()[-1] if detail else 'unknown error'
|
||||
raise Failure('compose ' + ' '.join(str(a) for a in args) + ' failed: ' + last)
|
||||
return result
|
||||
|
||||
|
||||
def docker(*args, stdin=None, check_result=True, timeout=180):
|
||||
result = subprocess.run(
|
||||
['docker'] + [str(a) for a in args],
|
||||
cwd=ROOT,
|
||||
input=stdin,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
)
|
||||
if check_result and result.returncode != 0:
|
||||
detail = redact_text((result.stderr or result.stdout).strip())
|
||||
last = detail.splitlines()[-1] if detail else 'unknown error'
|
||||
raise Failure('docker ' + ' '.join(str(a) for a in args) + ' failed: ' + last)
|
||||
return result
|
||||
|
||||
|
||||
def run_host_script(script_rel, *args, operator_dir=None, check_result=True, timeout=180, env_extra=None):
|
||||
script = ROOT / script_rel
|
||||
if not script.is_file():
|
||||
raise Failure(f'required operator script missing: {script_rel}')
|
||||
env = os.environ.copy()
|
||||
if operator_dir:
|
||||
env['LAB7_OPERATOR_DIR'] = str(operator_dir)
|
||||
if env_extra:
|
||||
env.update(env_extra)
|
||||
result = subprocess.run(
|
||||
[str(script)] + [str(a) for a in args],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
env=env,
|
||||
)
|
||||
if check_result and result.returncode != 0:
|
||||
detail = redact_text((result.stderr or result.stdout).strip())
|
||||
last = detail.splitlines()[-1] if detail else f'exit {result.returncode}'
|
||||
raise Failure(f'{script_rel} failed: {last}')
|
||||
return result
|
||||
|
||||
|
||||
def container_ids(service, all_states=False):
|
||||
args = ['ps', '-q']
|
||||
if all_states:
|
||||
args.append('-a')
|
||||
args.append(service)
|
||||
out = compose(*args, check_result=False).stdout.split()
|
||||
return [line.strip() for line in out if line.strip()]
|
||||
|
||||
|
||||
def container_inspect(cid):
|
||||
data = json.loads(docker('inspect', cid).stdout)
|
||||
if not data:
|
||||
raise Failure('docker inspect returned empty for ' + cid)
|
||||
return data[0]
|
||||
|
||||
|
||||
def all_project_containers(all_states=False):
|
||||
args = ['ps', '-q']
|
||||
if all_states:
|
||||
args.append('-a')
|
||||
cids = [c.strip() for c in compose(*args, check_result=False).stdout.split() if c.strip()]
|
||||
if not cids:
|
||||
return []
|
||||
return json.loads(docker('inspect', *cids).stdout)
|
||||
|
||||
|
||||
def app_image_id():
|
||||
for svc in ('api', 'worker'):
|
||||
cids = container_ids(svc, all_states=True)
|
||||
if cids:
|
||||
return container_inspect(cids[0])['Image']
|
||||
out = compose('images', '-q', 'api', check_result=False).stdout.strip().splitlines()
|
||||
if out:
|
||||
return out[0].strip()
|
||||
raise Failure('cannot determine application Docker image ID')
|
||||
|
||||
|
||||
def compose_network(suffix):
|
||||
"""Resolve full Docker network name (e.g. mtusi-lab7_lb_api) for a compose network."""
|
||||
out = docker('network', 'ls', '--format', '{{.Name}}').stdout.splitlines()
|
||||
exact = f'{PROJECT}_{suffix}'
|
||||
if exact in out:
|
||||
return exact
|
||||
for name in out:
|
||||
if name.endswith('_' + suffix) or name == suffix:
|
||||
return name
|
||||
raise Failure(f'docker network ending with _{suffix} not found')
|
||||
|
||||
|
||||
def run_node_probe(js_code, payload, network=None, exec_service=None, timeout=40, image=None):
|
||||
"""Run an isolated Node.js probe passing JSON payload over stdin (zero secrets in argv/env)."""
|
||||
wrapper = (
|
||||
"const fs=require('fs');"
|
||||
"const payload=JSON.parse(fs.readFileSync(0,'utf8'));"
|
||||
"(async()=>{" + js_code + "})()"
|
||||
".then(res=>{process.stdout.write(JSON.stringify({ok:true,result:res})+'\\n');})"
|
||||
".catch(err=>{process.stdout.write(JSON.stringify({ok:false,error:String(err&&err.message||err),code:err&&err.code||null,name:err&&err.name||null})+'\\n');});"
|
||||
)
|
||||
stdin_json = json.dumps(payload)
|
||||
if exec_service:
|
||||
res = compose(
|
||||
'exec', '-T', exec_service, 'node', '-e', wrapper,
|
||||
stdin=stdin_json, check_result=False, timeout=timeout,
|
||||
)
|
||||
else:
|
||||
img = image or app_image_id()
|
||||
net = compose_network(network) if network else compose_network('app_data')
|
||||
res = docker(
|
||||
'run', '--rm', '-i',
|
||||
'--network', net,
|
||||
'--read-only',
|
||||
'--cap-drop=ALL',
|
||||
'--security-opt', 'no-new-privileges:true',
|
||||
'--tmpfs', '/tmp:size=16m,noexec,nosuid,nodev',
|
||||
'--user', '1000:1000',
|
||||
img, 'node', '-e', wrapper,
|
||||
stdin=stdin_json, check_result=False, timeout=timeout,
|
||||
)
|
||||
lines = [line.strip() for line in (res.stdout or '').splitlines() if line.strip()]
|
||||
for line in reversed(lines):
|
||||
if line.startswith('{') and line.endswith('}'):
|
||||
try:
|
||||
return json.loads(line)
|
||||
except ValueError:
|
||||
pass
|
||||
err = redact_text((res.stderr or res.stdout or '').strip())
|
||||
return {'ok': False, 'error': err[-400:] if err else f'probe exited {res.returncode}', 'code': res.returncode}
|
||||
|
||||
|
||||
def psql_admin(sql, timeout=30):
|
||||
"""Execute SQL as local postgres superuser over Unix socket inside postgres container."""
|
||||
script = 'psql -h /var/run/postgresql -U postgres -d messenger -v ON_ERROR_STOP=1 -At -F , -c "$SQL"'
|
||||
res = subprocess.run(
|
||||
COMPOSE + ['exec', '-T', '-e', 'SQL=' + sql, 'postgres', 'sh', '-c', script],
|
||||
cwd=ROOT,
|
||||
text=True,
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
)
|
||||
if res.returncode != 0:
|
||||
err = redact_text((res.stderr or res.stdout).strip())
|
||||
raise Failure('psql_admin failed: ' + (err.splitlines()[-1] if err else 'unknown error'))
|
||||
return res.stdout.strip()
|
||||
|
||||
|
||||
def redis_admin_cli(*args, timeout=15):
|
||||
"""Run redis-cli inside redis container as redis_admin over mTLS (password via stdin)."""
|
||||
pw = read_secret_file('redis_admin_password')
|
||||
if not pw:
|
||||
raise Failure('redis_admin_password not found under secrets/infra/')
|
||||
# Build safe shell command passing redis-cli args via "$@"
|
||||
cmd = [
|
||||
'exec', '-T', 'redis', 'sh', '-c',
|
||||
'IFS= read -r pw; export REDISCLI_AUTH="$pw"; '
|
||||
'exec redis-cli --no-auth-warning --tls '
|
||||
'--cacert /run/certs/ca.crt --cert /run/certs/health.crt --key /run/certs/health.key '
|
||||
'--user redis_admin -h localhost -p 6379 "$@"',
|
||||
'--',
|
||||
] + [str(a) for a in args]
|
||||
res = compose(*cmd, stdin=pw + '\n', check_result=False, timeout=timeout)
|
||||
if res.returncode != 0:
|
||||
err = redact_text((res.stderr or res.stdout).strip())
|
||||
raise Failure('redis_admin_cli failed: ' + (err.splitlines()[-1] if err else f'exit {res.returncode}'))
|
||||
return res.stdout.strip()
|
||||
|
||||
|
||||
def wait_for_ready(base_url, ca_file, timeout=60):
|
||||
client = Client(base_url, str(ca_file))
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
r = client.call('GET', '/health/ready', expected=200, schema='Health')
|
||||
if r['status'] == 200:
|
||||
return True
|
||||
except Failure:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
raise Failure(f'API did not become ready at {base_url} within {timeout}s')
|
||||
|
||||
|
||||
# ----------------------------------------------------------- TLS / HTTPS / X.509
|
||||
|
||||
def _asn1_read_tl(buf, pos):
|
||||
if pos >= len(buf):
|
||||
raise ValueError('truncated ASN.1')
|
||||
tag = buf[pos]
|
||||
pos += 1
|
||||
first = buf[pos]
|
||||
pos += 1
|
||||
if first < 0x80:
|
||||
length = first
|
||||
else:
|
||||
nbytes = first & 0x7F
|
||||
length = int.from_bytes(buf[pos:pos + nbytes], 'big')
|
||||
pos += nbytes
|
||||
return tag, pos, pos + length
|
||||
|
||||
|
||||
def parse_der_serial(der_bytes):
|
||||
"""Extract canonical uppercase hex serial number from DER-encoded X.509 certificate."""
|
||||
tag, inner_start, _ = _asn1_read_tl(der_bytes, 0)
|
||||
if tag != 0x30:
|
||||
raise ValueError('expected outer SEQUENCE')
|
||||
tag, tbs_start, _ = _asn1_read_tl(der_bytes, inner_start)
|
||||
if tag != 0x30:
|
||||
raise ValueError('expected tbsCertificate SEQUENCE')
|
||||
pos = tbs_start
|
||||
if der_bytes[pos] == 0xA0:
|
||||
_, _, pos = _asn1_read_tl(der_bytes, pos)
|
||||
tag, val_start, val_end = _asn1_read_tl(der_bytes, pos)
|
||||
if tag != 0x02:
|
||||
raise ValueError('expected INTEGER serialNumber')
|
||||
raw = der_bytes[val_start:val_end]
|
||||
# Strip ASN.1 sign-extension leading zero byte when present
|
||||
if len(raw) > 1 and raw[0] == 0x00:
|
||||
raw = raw[1:]
|
||||
return raw.hex().upper()
|
||||
|
||||
|
||||
def pem_cert_info(cert_path):
|
||||
"""Read serial and SHA-256 fingerprint from a PEM certificate file using stdlib ssl."""
|
||||
text = Path(cert_path).read_text(encoding='utf-8')
|
||||
m = re.search(r'-----BEGIN CERTIFICATE-----[\s\S]+?-----END CERTIFICATE-----', text)
|
||||
if not m:
|
||||
raise Failure(f'no CERTIFICATE block in {cert_path}')
|
||||
der = ssl.PEM_cert_to_DER_cert(m.group(0))
|
||||
return {
|
||||
'serial': parse_der_serial(der),
|
||||
'sha256': hashlib.sha256(der).hexdigest().upper(),
|
||||
}
|
||||
|
||||
|
||||
def make_ssl_context(ca_file=None, cert_file=None, key_file=None,
|
||||
verify=True, check_hostname=True, empty_trust=False):
|
||||
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
# Disable TLS session tickets on client side so revocation tests always do full handshakes.
|
||||
if hasattr(ssl, 'OP_NO_TICKET'):
|
||||
ctx.options |= ssl.OP_NO_TICKET
|
||||
if not verify:
|
||||
ctx.check_hostname = False
|
||||
ctx.verify_mode = ssl.CERT_NONE
|
||||
else:
|
||||
ctx.verify_mode = ssl.CERT_REQUIRED
|
||||
ctx.check_hostname = bool(check_hostname)
|
||||
if not empty_trust:
|
||||
if ca_file:
|
||||
ctx.load_verify_locations(cafile=str(ca_file))
|
||||
else:
|
||||
ctx.load_default_certs()
|
||||
if cert_file:
|
||||
ctx.load_cert_chain(
|
||||
certfile=str(cert_file),
|
||||
keyfile=str(key_file) if key_file else None,
|
||||
)
|
||||
return ctx
|
||||
|
||||
|
||||
def https_request(method, url, headers=None, body=None, ssl_ctx=None, timeout=10):
|
||||
"""Perform a fresh-connection HTTP/HTTPS request (no connection pooling or TLS resumption).
|
||||
|
||||
Returns dict: {status, headers, body, peer_cert}
|
||||
"""
|
||||
parsed = urllib.parse.urlsplit(url)
|
||||
host = parsed.hostname
|
||||
port = parsed.port or (443 if parsed.scheme == 'https' else 80)
|
||||
path = parsed.path or '/'
|
||||
if parsed.query:
|
||||
path += '?' + parsed.query
|
||||
|
||||
req_headers = {'Connection': 'close'}
|
||||
if headers:
|
||||
req_headers.update(headers)
|
||||
raw_body = body
|
||||
if isinstance(body, (dict, list)):
|
||||
raw_body = json.dumps(body).encode('utf-8')
|
||||
req_headers.setdefault('Content-Type', 'application/json')
|
||||
elif isinstance(body, str):
|
||||
raw_body = body.encode('utf-8')
|
||||
|
||||
if parsed.scheme == 'https':
|
||||
conn = http.client.HTTPSConnection(host, port, timeout=timeout, context=ssl_ctx)
|
||||
else:
|
||||
conn = http.client.HTTPConnection(host, port, timeout=timeout)
|
||||
peer_cert = None
|
||||
try:
|
||||
conn.request(method, path, body=raw_body, headers=req_headers)
|
||||
resp = conn.getresponse()
|
||||
data = resp.read()
|
||||
if parsed.scheme == 'https' and conn.sock is not None:
|
||||
der = conn.sock.getpeercert(binary_form=True)
|
||||
if der:
|
||||
peer_cert = {
|
||||
'serial': parse_der_serial(der),
|
||||
'sha256': hashlib.sha256(der).hexdigest().upper(),
|
||||
'version': conn.sock.version(),
|
||||
}
|
||||
resp_headers = {k.lower(): v for k, v in resp.getheaders()}
|
||||
return {
|
||||
'status': resp.status,
|
||||
'headers': resp_headers,
|
||||
'body': data,
|
||||
'peer_cert': peer_cert,
|
||||
}
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
def get_tls_cert_info(host, port, ca_file=None, cert_file=None, key_file=None,
|
||||
server_hostname=None, timeout=5):
|
||||
ctx = make_ssl_context(ca_file=ca_file, cert_file=cert_file, key_file=key_file)
|
||||
sni = server_hostname or host
|
||||
with socket.create_connection((host, int(port)), timeout=timeout) as raw_sock:
|
||||
with ctx.wrap_socket(raw_sock, server_hostname=sni) as tls_sock:
|
||||
der = tls_sock.getpeercert(binary_form=True)
|
||||
parsed = tls_sock.getpeercert() or {}
|
||||
return {
|
||||
'serial': parse_der_serial(der),
|
||||
'sha256': hashlib.sha256(der).hexdigest().upper(),
|
||||
'version': tls_sock.version(),
|
||||
'subject': parsed.get('subject'),
|
||||
'san': parsed.get('subjectAltName'),
|
||||
}
|
||||
|
||||
|
||||
def tcp_port_closed(host, port, timeout=2.0):
|
||||
"""Return True if TCP port refuses connection."""
|
||||
try:
|
||||
with socket.create_connection((host, int(port)), timeout=timeout):
|
||||
return False
|
||||
except (ConnectionRefusedError, OSError):
|
||||
return True
|
||||
|
||||
|
||||
# ------------------------------------------------------------ OpenBao client
|
||||
|
||||
class OpenBaoClient:
|
||||
"""Minimal stdlib HTTPS OpenBao client (fresh connection per request, zero secret logging)."""
|
||||
|
||||
def __init__(self, addr, ca_file, cert_file=None, key_file=None, token=None, timeout=10):
|
||||
self.addr = addr.rstrip('/')
|
||||
self.ca_file = ca_file
|
||||
self.cert_file = cert_file
|
||||
self.key_file = key_file
|
||||
self.token = token
|
||||
self.timeout = timeout
|
||||
|
||||
def _ctx(self):
|
||||
return make_ssl_context(
|
||||
ca_file=self.ca_file,
|
||||
cert_file=self.cert_file,
|
||||
key_file=self.key_file,
|
||||
)
|
||||
|
||||
def request(self, method, path, body=None, token=None):
|
||||
headers = {'Accept': 'application/json'}
|
||||
use_token = token if token is not None else self.token
|
||||
if use_token:
|
||||
headers['X-Vault-Token'] = use_token
|
||||
resp = https_request(
|
||||
method,
|
||||
self.addr + path,
|
||||
headers=headers,
|
||||
body=body,
|
||||
ssl_ctx=self._ctx(),
|
||||
timeout=self.timeout,
|
||||
)
|
||||
parsed = None
|
||||
if resp['body']:
|
||||
try:
|
||||
parsed = json.loads(resp['body'].decode('utf-8', errors='replace'))
|
||||
except ValueError:
|
||||
parsed = None
|
||||
return resp['status'], parsed
|
||||
|
||||
def health(self):
|
||||
return self.request('GET', '/v1/sys/health')
|
||||
|
||||
def cert_login(self, role_name):
|
||||
status, data = self.request('POST', '/v1/auth/cert/login', body={'name': role_name}, token='')
|
||||
if status == 200 and data and data.get('auth', {}).get('client_token'):
|
||||
self.token = data['auth']['client_token']
|
||||
return status, data
|
||||
|
||||
def kv_read(self, logical_path):
|
||||
path = logical_path.lstrip('/')
|
||||
if not path.startswith('v1/'):
|
||||
path = '/v1/' + path
|
||||
else:
|
||||
path = '/' + path
|
||||
return self.request('GET', path)
|
||||
|
||||
def kv_metadata(self, sub_path):
|
||||
return self.request('GET', '/v1/secret/metadata/' + sub_path.lstrip('/'))
|
||||
|
||||
def lookup_self(self):
|
||||
return self.request('GET', '/v1/auth/token/lookup-self')
|
||||
|
||||
def list_accessors(self):
|
||||
return self.request('LIST', '/v1/auth/token/accessors')
|
||||
|
||||
def lookup_accessor(self, accessor):
|
||||
return self.request('POST', '/v1/auth/token/lookup-accessor', body={'accessor': accessor})
|
||||
|
||||
def revoke_accessor(self, accessor):
|
||||
return self.request('POST', '/v1/auth/token/revoke-accessor', body={'accessor': accessor})
|
||||
|
||||
def seal(self):
|
||||
return self.request('PUT', '/v1/sys/seal')
|
||||
|
||||
|
||||
def basic_auth_header(username, password):
|
||||
raw = base64.b64encode(f'{username}:{password}'.encode('utf-8')).decode('ascii')
|
||||
return {'Authorization': 'Basic ' + raw}
|
||||
Executable
+492
@@ -0,0 +1,492 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab 7 Container Hardening, Secret Hygiene & Vulnerability Scan Audit (Grade 3 + Grade 4).
|
||||
|
||||
Audits all running mtusi-lab7 containers via docker inspect (non-root, no privileged,
|
||||
no host network, no docker.sock, read_only rootfs, cap_drop ALL, no-new-privileges,
|
||||
CPU/RAM limits, strict published port policy, zero secrets in Config.Env), runs
|
||||
npm audit in app/ and containerized aquasec/trivy:0.69.3 image + fs scans into
|
||||
evidence/lab7/scans/, and writes sanitized evidence/lab7/hardening-audit.{json,txt}.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import common # noqa: E402
|
||||
|
||||
TRIVY_IMAGE = 'aquasec/trivy:0.69.3'
|
||||
|
||||
ALLOWED_PORTS_BY_SERVICE = {
|
||||
'haproxy': {'8443/tcp': 'public', '8404/tcp': 'loopback'},
|
||||
'openbao': {'8200/tcp': 'loopback'},
|
||||
's3': {'9000/tcp': 'loopback'},
|
||||
'grafana': {'3000/tcp': 'loopback'},
|
||||
'prometheus': {'9090/tcp': 'loopback'},
|
||||
}
|
||||
|
||||
FORBIDDEN_ENV_NAME_RE = re.compile(
|
||||
r'^(?:POSTGRES_PASSWORD|REDIS_PASSWORD|METRICS_TOKEN|BAO_TOKEN|VAULT_TOKEN|'
|
||||
r'S3_ACCESS_KEY_ID|S3_SECRET_ACCESS_KEY|MINIO_ROOT_PASSWORD|MINIO_ROOT_USER|'
|
||||
r'GF_SECURITY_ADMIN_PASSWORD|RABBITMQ_DEFAULT_PASS|UNSEAL_KEY.*|ROOT_TOKEN|'
|
||||
r'BAO_SECRET_ID|VAULT_SECRET_ID)$',
|
||||
re.IGNORECASE,
|
||||
)
|
||||
SECRET_URL_RE = re.compile(r'^[a-zA-Z][a-zA-Z0-9+.-]*://[^/\s:@]+:[^/\s@]+@')
|
||||
SECRET_VALUE_RE = re.compile(
|
||||
r'-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----|'
|
||||
r'\b(?:hvs|hvb|hvr)\.[A-Za-z0-9._-]{8,}\b|'
|
||||
r'\$argon2(?:id|i|d)\$v=\d+\$'
|
||||
)
|
||||
|
||||
|
||||
def _service_name(inspect_obj):
|
||||
labels = (inspect_obj.get('Config') or {}).get('Labels') or {}
|
||||
return labels.get('com.docker.compose.service') or inspect_obj.get('Name', '').lstrip('/')
|
||||
|
||||
|
||||
def _is_non_root(inspect_obj):
|
||||
user = ((inspect_obj.get('Config') or {}).get('User') or '').strip()
|
||||
if user and user not in ('0', 'root', '0:0', 'root:root'):
|
||||
return True, user
|
||||
cid = inspect_obj.get('Id', '')
|
||||
res = common.docker('exec', cid, 'id', '-u', check_result=False)
|
||||
uid = (res.stdout or '').strip()
|
||||
if res.returncode == 0 and uid.isdigit() and int(uid) != 0:
|
||||
return True, f'uid={uid}'
|
||||
return False, user or uid or 'unknown'
|
||||
|
||||
|
||||
def _check_ports(service, inspect_obj):
|
||||
allowed = ALLOWED_PORTS_BY_SERVICE.get(service, {})
|
||||
ports = (inspect_obj.get('NetworkSettings') or {}).get('Ports') or {}
|
||||
violations = []
|
||||
published = []
|
||||
for port_proto, bindings in ports.items():
|
||||
if not bindings:
|
||||
continue
|
||||
for b in bindings:
|
||||
host_ip = b.get('HostIp') or ''
|
||||
host_port = b.get('HostPort') or ''
|
||||
published.append(f'{host_ip}:{host_port}->{port_proto}')
|
||||
rule = allowed.get(port_proto)
|
||||
if rule is None:
|
||||
violations.append(f'unexpected published port {host_ip}:{host_port}->{port_proto}')
|
||||
elif rule == 'loopback' and host_ip not in ('127.0.0.1', '::1'):
|
||||
violations.append(f'admin port {port_proto} must bind 127.0.0.1, got {host_ip}:{host_port}')
|
||||
return published, violations
|
||||
|
||||
|
||||
def _check_env_secrets(inspect_obj):
|
||||
env_list = (inspect_obj.get('Config') or {}).get('Env') or []
|
||||
violations = []
|
||||
for entry in env_list:
|
||||
if '=' not in entry:
|
||||
continue
|
||||
k, v = entry.split('=', 1)
|
||||
if k.endswith('_FILE') or k.endswith('__FILE'):
|
||||
continue
|
||||
if FORBIDDEN_ENV_NAME_RE.match(k) and v.strip():
|
||||
violations.append(f'forbidden_env_var:{k}')
|
||||
elif k in ('DATABASE_URL', 'REDIS_URL', 'BROKER_URL') and SECRET_URL_RE.match(v.strip()):
|
||||
violations.append(f'credential_in_url_env:{k}')
|
||||
elif SECRET_VALUE_RE.search(v):
|
||||
violations.append(f'secret_pattern_in_env:{k}')
|
||||
return violations
|
||||
|
||||
|
||||
def audit_containers(args, rc):
|
||||
containers = common.all_project_containers(all_states=False)
|
||||
rc.add(
|
||||
'HARD-0-RUNNING-CONTAINERS', 'container_hardening',
|
||||
'Project mtusi-lab7 has running containers to audit',
|
||||
len(containers) >= 10, '>=10 running containers', f'count={len(containers)}',
|
||||
)
|
||||
op_dir_resolved = str(Path(args.operator_dir).resolve())
|
||||
repo_resolved = str(common.ROOT.resolve())
|
||||
op_outside_repo = not op_dir_resolved.startswith(repo_resolved + os.sep) and op_dir_resolved != repo_resolved
|
||||
rc.add(
|
||||
'HARD-1-OPDIR-OUTSIDE-REPO', 'secret_hygiene',
|
||||
'Operator state directory (LAB7_OPERATOR_DIR) is strictly outside Git repository',
|
||||
op_outside_repo, 'outside repo', op_dir_resolved,
|
||||
)
|
||||
|
||||
per_container = []
|
||||
all_non_root = True
|
||||
all_no_priv = True
|
||||
all_no_host_net = True
|
||||
all_no_sock = True
|
||||
all_ro_rootfs = True
|
||||
all_cap_drop = True
|
||||
all_no_new_priv = True
|
||||
all_limits = True
|
||||
all_ports_ok = True
|
||||
all_env_clean = True
|
||||
all_no_op_mount = True
|
||||
all_no_oom = True
|
||||
|
||||
service_counts = {}
|
||||
worker_limits = None
|
||||
|
||||
for obj in containers:
|
||||
svc = _service_name(obj)
|
||||
service_counts[svc] = service_counts.get(svc, 0) + 1
|
||||
hc = obj.get('HostConfig') or {}
|
||||
mounts = obj.get('Mounts') or []
|
||||
state = obj.get('State') or {}
|
||||
|
||||
non_root, user_str = _is_non_root(obj)
|
||||
privileged = bool(hc.get('Privileged', False))
|
||||
net_mode = hc.get('NetworkMode') or ''
|
||||
host_net = net_mode == 'host'
|
||||
has_sock = any('docker.sock' in (m.get('Source') or '') or 'docker.sock' in (m.get('Destination') or '') for m in mounts)
|
||||
has_op_mount = any(
|
||||
str(Path(m.get('Source')).resolve()).startswith(op_dir_resolved)
|
||||
for m in mounts if m.get('Type') == 'bind' and m.get('Source')
|
||||
)
|
||||
ro_rootfs = bool(hc.get('ReadonlyRootfs', False))
|
||||
cap_drop = [c.upper() for c in (hc.get('CapDrop') or [])]
|
||||
cap_add = hc.get('CapAdd') or []
|
||||
cap_ok = ('ALL' in cap_drop) and not cap_add
|
||||
sec_opt = hc.get('SecurityOpt') or []
|
||||
no_new_priv = any('no-new-privileges' in s and 'false' not in s.lower() for s in sec_opt)
|
||||
nano_cpus = int(hc.get('NanoCpus') or 0)
|
||||
cpu_quota = int(hc.get('CpuQuota') or 0)
|
||||
memory = int(hc.get('Memory') or 0)
|
||||
limits_ok = (nano_cpus > 0 or cpu_quota > 0) and memory > 0
|
||||
oom_killed = bool(state.get('OOMKilled', False))
|
||||
published, port_violations = _check_ports(svc, obj)
|
||||
env_violations = _check_env_secrets(obj)
|
||||
|
||||
all_non_root &= non_root
|
||||
all_no_priv &= (not privileged)
|
||||
all_no_host_net &= (not host_net)
|
||||
all_no_sock &= (not has_sock)
|
||||
all_ro_rootfs &= ro_rootfs
|
||||
all_cap_drop &= cap_ok
|
||||
all_no_new_priv &= no_new_priv
|
||||
all_limits &= limits_ok
|
||||
all_ports_ok &= (len(port_violations) == 0)
|
||||
all_env_clean &= (len(env_violations) == 0)
|
||||
all_no_op_mount &= (not has_op_mount)
|
||||
all_no_oom &= (not oom_killed)
|
||||
|
||||
info = {
|
||||
'service': svc,
|
||||
'id': obj.get('Id', '')[:12],
|
||||
'user': user_str,
|
||||
'non_root': non_root,
|
||||
'privileged': privileged,
|
||||
'network_mode': net_mode,
|
||||
'docker_sock_mounted': has_sock,
|
||||
'operator_dir_mounted': has_op_mount,
|
||||
'readonly_rootfs': ro_rootfs,
|
||||
'cap_drop': cap_drop,
|
||||
'cap_add': cap_add,
|
||||
'no_new_privileges': no_new_priv,
|
||||
'cpus': round(nano_cpus / 1e9, 3) if nano_cpus else None,
|
||||
'memory_mib': round(memory / (1024 * 1024), 1) if memory else None,
|
||||
'oom_killed': oom_killed,
|
||||
'published_ports': published,
|
||||
'port_violations': port_violations,
|
||||
'env_violations': env_violations,
|
||||
}
|
||||
per_container.append(info)
|
||||
if svc == 'worker':
|
||||
worker_env = dict(
|
||||
e.split('=', 1) for e in ((obj.get('Config') or {}).get('Env') or []) if '=' in e
|
||||
)
|
||||
worker_limits = {
|
||||
'cpus': info['cpus'],
|
||||
'memory_mib': info['memory_mib'],
|
||||
'job_timeout_seconds': worker_env.get('JOB_TIMEOUT_SECONDS'),
|
||||
'worker_concurrency': worker_env.get('WORKER_CONCURRENCY'),
|
||||
'max_upload_bytes': worker_env.get('MAX_UPLOAD_BYTES'),
|
||||
'max_image_pixels': worker_env.get('MAX_IMAGE_PIXELS'),
|
||||
}
|
||||
|
||||
rc.add('HARD-2-NON-ROOT', 'container_hardening',
|
||||
'All running containers execute as non-root users',
|
||||
all_non_root, 'all non-root',
|
||||
[f"{c['service']}:{c['user']}" for c in per_container if not c['non_root']] or 'all non-root')
|
||||
rc.add('HARD-3-NO-PRIVILEGED', 'container_hardening',
|
||||
'Zero containers use privileged=true',
|
||||
all_no_priv, '0 privileged',
|
||||
[c['service'] for c in per_container if c['privileged']] or '0 privileged')
|
||||
rc.add('HARD-4-NO-HOST-NET', 'container_hardening',
|
||||
'Zero containers use network_mode=host',
|
||||
all_no_host_net, '0 host network',
|
||||
[c['service'] for c in per_container if c['network_mode'] == 'host'] or '0 host network')
|
||||
rc.add('HARD-5-NO-DOCKER-SOCK', 'container_hardening',
|
||||
'Zero containers mount /var/run/docker.sock',
|
||||
all_no_sock, '0 docker.sock mounts',
|
||||
[c['service'] for c in per_container if c['docker_sock_mounted']] or '0 mounts')
|
||||
rc.add('HARD-6-NO-OPDIR-MOUNT', 'secret_hygiene',
|
||||
'Zero containers mount LAB7_OPERATOR_DIR (CA key / unseal shares)',
|
||||
all_no_op_mount, '0 operator dir mounts',
|
||||
[c['service'] for c in per_container if c['operator_dir_mounted']] or '0 mounts')
|
||||
rc.add('HARD-7-READONLY-ROOTFS', 'container_hardening',
|
||||
'All running containers use read_only root filesystem',
|
||||
all_ro_rootfs, 'all ReadonlyRootfs=true',
|
||||
[c['service'] for c in per_container if not c['readonly_rootfs']] or 'all read_only=true')
|
||||
rc.add('HARD-8-CAP-DROP-ALL', 'container_hardening',
|
||||
'All running containers drop ALL capabilities with zero CapAdd',
|
||||
all_cap_drop, 'all CapDrop=[ALL], CapAdd=[]',
|
||||
[c['service'] for c in per_container if 'ALL' not in c['cap_drop'] or c['cap_add']] or 'all CapDrop=ALL')
|
||||
rc.add('HARD-9-NO-NEW-PRIVILEGES', 'container_hardening',
|
||||
'All running containers set security_opt no-new-privileges:true',
|
||||
all_no_new_priv, 'all no-new-privileges',
|
||||
[c['service'] for c in per_container if not c['no_new_privileges']] or 'all set')
|
||||
rc.add('HARD-10-RESOURCE-LIMITS', 'container_hardening',
|
||||
'All running containers define explicit CPU and memory limits',
|
||||
all_limits, 'all cpus>0 & memory>0',
|
||||
[c['service'] for c in per_container if not (c['cpus'] and c['memory_mib'])] or 'all bounded')
|
||||
rc.add('HARD-11-PUBLISHED-PORTS', 'network_surface',
|
||||
'Only HTTPS :8443 and loopback 127.0.0.1 admin ports are published',
|
||||
all_ports_ok, '0 port policy violations',
|
||||
[f"{c['service']}:{c['port_violations']}" for c in per_container if c['port_violations']] or 'compliant')
|
||||
rc.add('HARD-12-ZERO-ENV-SECRETS', 'secret_hygiene',
|
||||
'Zero secret credentials or tokens appear in Config.Env of any container',
|
||||
all_env_clean, '0 env secret violations',
|
||||
[f"{c['service']}:{c['env_violations']}" for c in per_container if c['env_violations']] or '0 violations')
|
||||
rc.add('HARD-13-ZERO-OOM', 'container_hardening',
|
||||
'Zero containers have OOMKilled=true',
|
||||
all_no_oom, '0 OOMKilled',
|
||||
[c['service'] for c in per_container if c['oom_killed']] or '0 OOMKilled')
|
||||
|
||||
# Worker bounds & API replica count
|
||||
rc.add('HARD-14-WORKER-BOUNDS', 'worker_hardening',
|
||||
'Upload worker has explicit CPU, memory, and execution bounds',
|
||||
bool(worker_limits and worker_limits.get('cpus') and worker_limits.get('memory_mib')),
|
||||
'worker cpus & memory bounded', json.dumps(worker_limits))
|
||||
rc.add('HARD-15-TOPOLOGY-COUNTS', 'container_hardening',
|
||||
'At least 2 API replicas running; stateful stores single-node (Row 12 N/A)',
|
||||
service_counts.get('api', 0) >= 2 and service_counts.get('worker', 0) >= 1,
|
||||
'api>=2, worker>=1', json.dumps(service_counts))
|
||||
|
||||
# Gitignore check
|
||||
gi = subprocess.run(
|
||||
['git', 'check-ignore', '-q', 'secrets', '.env'],
|
||||
cwd=common.ROOT, capture_output=True, text=True,
|
||||
)
|
||||
rc.add('HARD-16-GITIGNORE', 'secret_hygiene',
|
||||
'secrets/ and .env are ignored by Git',
|
||||
gi.returncode == 0, 'git check-ignore exits 0', f'rc={gi.returncode}')
|
||||
|
||||
return per_container, worker_limits, service_counts
|
||||
|
||||
|
||||
def run_npm_audit(scans_dir, rc):
|
||||
app_dir = common.ROOT / 'app'
|
||||
pkg = json.loads((app_dir / 'package.json').read_text(encoding='utf-8'))
|
||||
deps = pkg.get('dependencies') or {}
|
||||
has_express = '@nestjs/platform-express' in deps
|
||||
zod_spec = deps.get('zod', '')
|
||||
rc.add(
|
||||
'SCAN-NPM-0-DEPS-REMEDIATED', 'dependency_scan',
|
||||
'Unused @nestjs/platform-express removed and zod pinned >=4.6.6',
|
||||
(not has_express) and bool(zod_spec),
|
||||
'no platform-express, zod present',
|
||||
f'has_platform_express={has_express}, zod={zod_spec}',
|
||||
)
|
||||
|
||||
res = subprocess.run(
|
||||
['npm', 'audit', '--omit=dev', '--json'],
|
||||
cwd=app_dir, capture_output=True, text=True, timeout=120,
|
||||
)
|
||||
raw = (res.stdout or '').strip()
|
||||
parsed = None
|
||||
if raw:
|
||||
try:
|
||||
parsed = json.loads(raw)
|
||||
except ValueError:
|
||||
parsed = {'parse_error': True, 'stderr': (res.stderr or '')[:300]}
|
||||
else:
|
||||
parsed = {'error': (res.stderr or 'empty output')[:300], 'returncode': res.returncode}
|
||||
|
||||
out_file = scans_dir / 'npm-audit.json'
|
||||
out_file.write_text(json.dumps(common.sanitize_data(parsed), indent=2) + '\n', encoding='utf-8')
|
||||
|
||||
vulns = ((parsed or {}).get('metadata') or {}).get('vulnerabilities') or {}
|
||||
high_crit = int(vulns.get('high', 0)) + int(vulns.get('critical', 0))
|
||||
rc.add(
|
||||
'SCAN-NPM-1-PROD-AUDIT', 'dependency_scan',
|
||||
'npm audit --omit=dev succeeds with 0 High/Critical production vulnerabilities',
|
||||
isinstance(vulns, dict) and 'high' in vulns and high_crit == 0,
|
||||
'high=0, critical=0',
|
||||
json.dumps(vulns) if vulns else f'rc={res.returncode}',
|
||||
{'report': str(out_file.relative_to(common.ROOT))},
|
||||
)
|
||||
return vulns
|
||||
|
||||
|
||||
def _summarize_trivy(report):
|
||||
vulns = {'CRITICAL': 0, 'HIGH': 0, 'MEDIUM': 0, 'LOW': 0, 'UNKNOWN': 0}
|
||||
secrets = []
|
||||
misconfigs = {'CRITICAL': 0, 'HIGH': 0, 'MEDIUM': 0, 'LOW': 0}
|
||||
top_cves = []
|
||||
for target in (report or {}).get('Results') or []:
|
||||
tname = target.get('Target', '')
|
||||
for v in target.get('Vulnerabilities') or []:
|
||||
sev = str(v.get('Severity', 'UNKNOWN')).upper()
|
||||
vulns[sev] = vulns.get(sev, 0) + 1
|
||||
if sev in ('CRITICAL', 'HIGH') and len(top_cves) < 20:
|
||||
top_cves.append({
|
||||
'id': v.get('VulnerabilityID'),
|
||||
'severity': sev,
|
||||
'pkg': v.get('PkgName'),
|
||||
'installed': v.get('InstalledVersion'),
|
||||
'fixed': v.get('FixedVersion'),
|
||||
'target': tname,
|
||||
})
|
||||
for s in target.get('Secrets') or []:
|
||||
secrets.append({
|
||||
'rule': s.get('RuleID'),
|
||||
'title': s.get('Title'),
|
||||
'target': tname,
|
||||
'line': s.get('StartLine'),
|
||||
})
|
||||
for m in target.get('Misconfigurations') or []:
|
||||
sev = str(m.get('Severity', 'LOW')).upper()
|
||||
misconfigs[sev] = misconfigs.get(sev, 0) + 1
|
||||
return {
|
||||
'vulnerabilities': vulns,
|
||||
'secret_count': len(secrets),
|
||||
'secrets': secrets,
|
||||
'misconfigurations': misconfigs,
|
||||
'top_high_critical_cves': top_cves,
|
||||
}
|
||||
|
||||
|
||||
def run_trivy_scans(scans_dir, rc, skip_trivy=False):
|
||||
if skip_trivy:
|
||||
rc.add('SCAN-TRIVY-SKIPPED', 'image_scan',
|
||||
'Trivy scans skipped by flag', True, 'skipped', 'skipped')
|
||||
return {}
|
||||
|
||||
cache_dir = Path('/tmp/mtusi-lab7-trivy-cache')
|
||||
cache_dir.mkdir(parents=True, exist_ok=True)
|
||||
results = {}
|
||||
|
||||
# 1. Filesystem scan (vuln, secret, misconfig) on repository
|
||||
fs_out = scans_dir / 'trivy-fs.json'
|
||||
fs_cmd = [
|
||||
'docker', 'run', '--rm',
|
||||
'-v', f'{common.ROOT}:/repo:ro',
|
||||
'-v', f'{cache_dir}:/root/.cache/trivy',
|
||||
TRIVY_IMAGE, 'fs',
|
||||
'--scanners', 'vuln,secret,misconfig',
|
||||
'--skip-dirs', 'node_modules,.git,secrets,evidence,.venv',
|
||||
'--format', 'json',
|
||||
'--quiet',
|
||||
'/repo',
|
||||
]
|
||||
fs_res = subprocess.run(fs_cmd, cwd=common.ROOT, capture_output=True, text=True, timeout=300)
|
||||
if fs_res.returncode == 0 and (fs_res.stdout or '').strip():
|
||||
try:
|
||||
fs_json = json.loads(fs_res.stdout)
|
||||
fs_out.write_text(json.dumps(common.sanitize_data(fs_json), indent=2) + '\n', encoding='utf-8')
|
||||
fs_sum = _summarize_trivy(fs_json)
|
||||
results['fs'] = fs_sum
|
||||
rc.add(
|
||||
'SCAN-TRIVY-FS-SECRETS', 'image_scan',
|
||||
'Trivy repo filesystem scan completed with 0 leaked secrets',
|
||||
fs_sum['secret_count'] == 0,
|
||||
'0 secrets in repo',
|
||||
f"secrets={fs_sum['secret_count']} vulns={fs_sum['vulnerabilities']} misconfig={fs_sum['misconfigurations']}",
|
||||
{'report': str(fs_out.relative_to(common.ROOT)), 'top_cves': fs_sum['top_high_critical_cves'][:10]},
|
||||
)
|
||||
except ValueError:
|
||||
rc.add('SCAN-TRIVY-FS-SECRETS', 'image_scan',
|
||||
'Trivy repo filesystem scan produced valid JSON', False, 'valid JSON',
|
||||
common.redact_text((fs_res.stderr or fs_res.stdout)[:300]))
|
||||
else:
|
||||
rc.add('SCAN-TRIVY-FS-SECRETS', 'image_scan',
|
||||
'Trivy repo filesystem scan executed cleanly', False, 'exit 0',
|
||||
common.redact_text((fs_res.stderr or f'rc={fs_res.returncode}')[:300]))
|
||||
|
||||
# 2. Built app image scan (vuln, secret)
|
||||
img_out = scans_dir / 'trivy-image.json'
|
||||
try:
|
||||
img_id = common.app_image_id()
|
||||
except common.Failure as exc:
|
||||
rc.add('SCAN-TRIVY-IMAGE', 'image_scan',
|
||||
'Trivy built application image scan', False, 'app image exists', str(exc))
|
||||
return results
|
||||
|
||||
img_cmd = [
|
||||
'docker', 'run', '--rm',
|
||||
'-v', '/var/run/docker.sock:/var/run/docker.sock:ro',
|
||||
'-v', f'{cache_dir}:/root/.cache/trivy',
|
||||
TRIVY_IMAGE, 'image',
|
||||
'--scanners', 'vuln,secret',
|
||||
'--format', 'json',
|
||||
'--quiet',
|
||||
img_id,
|
||||
]
|
||||
img_res = subprocess.run(img_cmd, cwd=common.ROOT, capture_output=True, text=True, timeout=300)
|
||||
if img_res.returncode == 0 and (img_res.stdout or '').strip():
|
||||
try:
|
||||
img_json = json.loads(img_res.stdout)
|
||||
img_out.write_text(json.dumps(common.sanitize_data(img_json), indent=2) + '\n', encoding='utf-8')
|
||||
img_sum = _summarize_trivy(img_json)
|
||||
results['image'] = img_sum
|
||||
rc.add(
|
||||
'SCAN-TRIVY-IMAGE-SECRETS', 'image_scan',
|
||||
'Trivy built app image scan completed with 0 embedded secrets',
|
||||
img_sum['secret_count'] == 0,
|
||||
'0 secrets in image',
|
||||
f"image={img_id[:19]} secrets={img_sum['secret_count']} vulns={img_sum['vulnerabilities']}",
|
||||
{'report': str(img_out.relative_to(common.ROOT)), 'top_cves': img_sum['top_high_critical_cves'][:10]},
|
||||
)
|
||||
except ValueError:
|
||||
rc.add('SCAN-TRIVY-IMAGE-SECRETS', 'image_scan',
|
||||
'Trivy app image scan produced valid JSON', False, 'valid JSON',
|
||||
common.redact_text((img_res.stderr or img_res.stdout)[:300]))
|
||||
else:
|
||||
rc.add('SCAN-TRIVY-IMAGE-SECRETS', 'image_scan',
|
||||
'Trivy built app image scan executed cleanly', False, 'exit 0',
|
||||
common.redact_text((img_res.stderr or f'rc={img_res.returncode}')[:300]))
|
||||
|
||||
return results
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
common.add_common_args(parser)
|
||||
parser.add_argument('--skip-trivy', action='store_true',
|
||||
help='Skip containerized Trivy scans (container audit & npm audit still run)')
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
rc = common.ResultCollector('lab7-hardening-audit')
|
||||
out_dir = Path(args.output_dir)
|
||||
if not out_dir.is_absolute():
|
||||
out_dir = common.ROOT / out_dir
|
||||
scans_dir = out_dir / 'scans'
|
||||
scans_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
containers, worker_limits, service_counts = audit_containers(args, rc)
|
||||
npm_vulns = run_npm_audit(scans_dir, rc)
|
||||
trivy_summary = run_trivy_scans(scans_dir, rc, skip_trivy=args.skip_trivy)
|
||||
|
||||
rc.summary = {
|
||||
'service_counts': service_counts,
|
||||
'worker_limits': worker_limits,
|
||||
'npm_audit_prod': npm_vulns,
|
||||
'trivy': trivy_summary,
|
||||
'containers': containers,
|
||||
}
|
||||
(json_path, txt_path), rep = rc.save(args.output_dir, 'hardening-audit')
|
||||
print(f"Report written: {json_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 common.Failure as exc:
|
||||
print('FAIL:', common.redact_text(str(exc)), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
Executable
+507
@@ -0,0 +1,507 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab 7 OpenBao, Secrets Lifecycle & Certificate Rotation/Revocation Suite (Grade 3 + Grade 4).
|
||||
|
||||
Verifies:
|
||||
- Non-dev Raft OpenBao mode, initialized & unsealed, root token revoked, zero root/unseal/secrets in containers
|
||||
- Policy allow/deny matrix for messenger-api and messenger-worker (NC-5)
|
||||
- Live DB secret rotation without image rebuild (scripts/rotate-secret.sh api-db)
|
||||
- Live leaf cert rotation + client cert revocation on NEW connection (scripts/rotate-cert.sh, NC-6)
|
||||
- Token revocation & clean auth/cert re-authentication
|
||||
- Sealed OpenBao bounded behavior + container restart (boots sealed) + manual operator unseal recovery
|
||||
|
||||
Writes sanitized JSON + TXT report to evidence/lab7/openbao-lifecycle.{json,txt}.
|
||||
"""
|
||||
import argparse
|
||||
import shutil
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import common # noqa: E402
|
||||
from client import Client, Failure # noqa: E402
|
||||
|
||||
|
||||
def _probe_api_tls(ca_pem, cert_pem, key_pem):
|
||||
"""Fresh-connection mTLS probe to https://api:8443/health/ready from lb_api; returns peer cert serial."""
|
||||
js = """
|
||||
const https = require('https');
|
||||
const crypto = require('crypto');
|
||||
const p = payload;
|
||||
return await new Promise((resolve) => {
|
||||
const req = https.request({
|
||||
hostname: 'api',
|
||||
port: 8443,
|
||||
path: '/health/ready',
|
||||
method: 'GET',
|
||||
ca: p.ca_pem,
|
||||
cert: p.cert_pem,
|
||||
key: p.key_pem,
|
||||
servername: 'api',
|
||||
rejectUnauthorized: true,
|
||||
minVersion: 'TLSv1.2',
|
||||
secureOptions: crypto.constants.SSL_OP_NO_TICKET,
|
||||
headers: { Connection: 'close' },
|
||||
timeout: 6000,
|
||||
}, (res) => {
|
||||
const peer = res.socket.getPeerX509Certificate();
|
||||
const chunks = [];
|
||||
res.on('data', (c) => chunks.push(c));
|
||||
res.on('end', () => resolve({
|
||||
status: res.statusCode,
|
||||
serial: peer ? peer.serialNumber : null,
|
||||
fingerprint256: peer ? peer.fingerprint256 : null,
|
||||
tlsError: null,
|
||||
}));
|
||||
});
|
||||
req.on('timeout', () => req.destroy(new Error('ETIMEDOUT')));
|
||||
req.on('error', (err) => resolve({
|
||||
status: null, serial: null, fingerprint256: null,
|
||||
tlsError: err.code || err.message || String(err),
|
||||
}));
|
||||
req.end();
|
||||
});
|
||||
"""
|
||||
return common.run_node_probe(
|
||||
js, {'ca_pem': ca_pem, 'cert_pem': cert_pem, 'key_pem': key_pem}, network='lb_api'
|
||||
)
|
||||
|
||||
|
||||
def _probe_pg_password(ca_pem, user, password):
|
||||
js = """
|
||||
const { Client } = require('pg');
|
||||
const c = new Client({
|
||||
host: 'postgres', port: 5432, database: 'messenger',
|
||||
user: payload.user, password: payload.password,
|
||||
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 { ok: true, code: null };
|
||||
} catch (err) {
|
||||
try { await c.end(); } catch (_) {}
|
||||
return { ok: false, code: err.code || null, error: err.message || String(err) };
|
||||
}
|
||||
"""
|
||||
return common.run_node_probe(
|
||||
js, {'ca_pem': ca_pem, 'user': user, 'password': password}, network='app_data'
|
||||
)
|
||||
|
||||
|
||||
def _read_pem(path):
|
||||
return Path(path).read_text(encoding='utf-8')
|
||||
|
||||
|
||||
def check_openbao_posture(args, rc, op_crt, op_key, rogue_crt, rogue_key):
|
||||
bao = common.OpenBaoClient(args.openbao_url, args.ca_file)
|
||||
st, health = bao.health()
|
||||
ok_health = st == 200 and isinstance(health, dict) and health.get('initialized') and not health.get('sealed')
|
||||
rc.add('BAO-1-NONDEV-HEALTH', 'openbao_posture',
|
||||
'OpenBao is initialized, unsealed, and reachable over verified HTTPS',
|
||||
ok_health, 'HTTP 200 initialized=True sealed=False',
|
||||
f'status={st} health={health}')
|
||||
|
||||
# Verify non-dev Raft config & persistent volume
|
||||
bao_cids = common.container_ids('openbao')
|
||||
non_dev_ok = False
|
||||
raft_vol_ok = False
|
||||
if bao_cids:
|
||||
insp = common.container_inspect(bao_cids[0])
|
||||
cmd_all = ' '.join((insp.get('Config') or {}).get('Cmd') or [])
|
||||
entry_all = ' '.join((insp.get('Config') or {}).get('Entrypoint') or [])
|
||||
non_dev_ok = ('-dev' not in cmd_all) and ('-dev' not in entry_all) and ('openbao.hcl' in cmd_all)
|
||||
mounts = insp.get('Mounts') or []
|
||||
raft_vol_ok = any(m.get('Destination') == '/openbao/file' and m.get('Type') == 'volume' for m in mounts)
|
||||
hcl_path = common.ROOT / 'infra/openbao/openbao.hcl'
|
||||
hcl_raft = hcl_path.is_file() and 'storage "raft"' in hcl_path.read_text(encoding='utf-8')
|
||||
rc.add('BAO-2-RAFT-NONDEV', 'openbao_posture',
|
||||
'OpenBao runs non-dev mode with persistent Raft volume (openbao-data:/openbao/file)',
|
||||
non_dev_ok and raft_vol_ok and hcl_raft,
|
||||
'non-dev + Raft volume mounted',
|
||||
f'non_dev={non_dev_ok}, raft_vol={raft_vol_ok}, hcl_raft={hcl_raft}')
|
||||
|
||||
# Verify no root token / unseal shares saved in repo or mounted in api/worker
|
||||
repo_leaks = []
|
||||
for cand in ('root_token', 'root-token', 'unseal-share-1', 'unseal_keys', 'init.json'):
|
||||
for base in (common.ROOT, common.ROOT / 'secrets', common.ROOT / 'secrets/infra'):
|
||||
if (base / cand).exists():
|
||||
repo_leaks.append(str((base / cand).relative_to(common.ROOT)))
|
||||
op_root_file = Path(args.operator_dir) / 'openbao/root-token'
|
||||
if op_root_file.exists():
|
||||
# If any root token file exists, verify it is revoked (403)
|
||||
tok = op_root_file.read_text(encoding='utf-8').strip()
|
||||
rc.register_secret(tok)
|
||||
st_rt, _ = common.OpenBaoClient(args.openbao_url, args.ca_file, token=tok).lookup_self()
|
||||
root_ok = st_rt == 403
|
||||
root_note = f'root-token file present but revoked (lookup status={st_rt})'
|
||||
else:
|
||||
root_ok = True
|
||||
root_note = 'no persisted root token file (revoked at bootstrap)'
|
||||
rc.add('BAO-3-NO-ROOT-PERSISTED', 'openbao_posture',
|
||||
'Initial root token revoked and zero root/unseal files in repo or workload containers',
|
||||
root_ok and not repo_leaks, 'no repo root/unseal files & root revoked',
|
||||
f'{root_note}; repo_leaks={repo_leaks}')
|
||||
|
||||
# Operator cert login works; rogue-client cert rejected
|
||||
op_bao = common.OpenBaoClient(args.openbao_url, args.ca_file, cert_file=op_crt, key_file=op_key)
|
||||
st_op, _ = op_bao.cert_login('messenger-operator')
|
||||
if op_bao.token:
|
||||
rc.register_secret(op_bao.token)
|
||||
rogue_bao = common.OpenBaoClient(args.openbao_url, args.ca_file, cert_file=rogue_crt, key_file=rogue_key)
|
||||
st_rogue, _ = rogue_bao.cert_login('messenger-api')
|
||||
rc.add('BAO-4-OPERATOR-AND-ROGUE-AUTH', 'openbao_auth',
|
||||
'Operator mTLS cert authenticates; trusted-CA rogue-client rejected by auth/cert',
|
||||
st_op == 200 and st_rogue in (400, 403),
|
||||
'operator=200, rogue=400/403', f'operator={st_op}, rogue={st_rogue}')
|
||||
return op_bao
|
||||
|
||||
|
||||
def check_policy_matrix(args, rc):
|
||||
api_crt, api_key = common.service_client_pair('api')
|
||||
wrk_crt, wrk_key = common.service_client_pair('worker')
|
||||
|
||||
api_bao = common.OpenBaoClient(args.openbao_url, args.ca_file, cert_file=api_crt, key_file=api_key)
|
||||
st_a, data_a = api_bao.cert_login('messenger-api')
|
||||
if api_bao.token:
|
||||
rc.register_secret(api_bao.token)
|
||||
api_pols = (data_a or {}).get('auth', {}).get('policies', [])
|
||||
api_ttl = (data_a or {}).get('auth', {}).get('lease_duration')
|
||||
|
||||
a_own, a_kv = api_bao.kv_read('secret/data/messenger/api')
|
||||
a_wrk, _ = api_bao.kv_read('secret/data/messenger/worker')
|
||||
a_mig, _ = api_bao.kv_read('secret/data/messenger/migrator')
|
||||
a_adm, _ = api_bao.kv_read('secret/data/messenger/operator-admin')
|
||||
a_pol, _ = api_bao.request('PUT', '/v1/sys/policies/acl/api-policy', body={'policy': 'path "*" { capabilities = ["sudo"] }'})
|
||||
a_crt, _ = api_bao.request('GET', '/v1/auth/cert/certs/messenger-api')
|
||||
a_cross_login, _ = api_bao.request('POST', '/v1/auth/cert/login', body={'name': 'messenger-worker'}, token='')
|
||||
|
||||
api_sec = ((a_kv or {}).get('data') or {}).get('data') or {}
|
||||
for v in api_sec.values():
|
||||
if isinstance(v, str):
|
||||
rc.register_secret(v)
|
||||
api_ok = (
|
||||
st_a == 200 and a_own == 200
|
||||
and all(code == 403 for code in (a_wrk, a_mig, a_adm, a_pol, a_crt))
|
||||
and a_cross_login in (400, 403)
|
||||
and 'default' not in api_pols
|
||||
)
|
||||
rc.add('BAO-5-API-POLICY-MATRIX', 'openbao_policy',
|
||||
'messenger-api reads ONLY secret/data/messenger/api and is denied worker/migrator/admin/sys/auth',
|
||||
api_ok,
|
||||
'own=200, all foreign/sys/auth=403, cross_role_login=400, no default policy',
|
||||
f'login={st_a} policies={api_pols} ttl={api_ttl}s own={a_own} wrk={a_wrk} mig={a_mig} adm={a_adm} pol={a_pol} cert={a_crt} cross={a_cross_login}')
|
||||
|
||||
wrk_bao = common.OpenBaoClient(args.openbao_url, args.ca_file, cert_file=wrk_crt, key_file=wrk_key)
|
||||
st_w, data_w = wrk_bao.cert_login('messenger-worker')
|
||||
if wrk_bao.token:
|
||||
rc.register_secret(wrk_bao.token)
|
||||
wrk_pols = (data_w or {}).get('auth', {}).get('policies', [])
|
||||
wrk_ttl = (data_w or {}).get('auth', {}).get('lease_duration')
|
||||
|
||||
w_own, w_kv = wrk_bao.kv_read('secret/data/messenger/worker')
|
||||
w_api, _ = wrk_bao.kv_read('secret/data/messenger/api')
|
||||
w_mig, _ = wrk_bao.kv_read('secret/data/messenger/migrator')
|
||||
w_adm, _ = wrk_bao.kv_read('secret/data/messenger/operator-admin')
|
||||
w_pol, _ = wrk_bao.request('PUT', '/v1/sys/policies/acl/worker-policy', body={'policy': 'path "*" { capabilities = ["sudo"] }'})
|
||||
w_seal, _ = wrk_bao.request('PUT', '/v1/sys/seal')
|
||||
w_cross_login, _ = wrk_bao.request('POST', '/v1/auth/cert/login', body={'name': 'messenger-api'}, token='')
|
||||
|
||||
wrk_sec = ((w_kv or {}).get('data') or {}).get('data') or {}
|
||||
for v in wrk_sec.values():
|
||||
if isinstance(v, str):
|
||||
rc.register_secret(v)
|
||||
no_api_keys_in_wrk = not any(k in wrk_sec for k in ('redis_password', 'redis_user', 'metrics_token'))
|
||||
wrk_ok = (
|
||||
st_w == 200 and w_own == 200 and no_api_keys_in_wrk
|
||||
and all(code == 403 for code in (w_api, w_mig, w_adm, w_pol, w_seal))
|
||||
and w_cross_login in (400, 403)
|
||||
and 'default' not in wrk_pols
|
||||
)
|
||||
rc.add('BAO-6-WORKER-POLICY-MATRIX', 'openbao_policy',
|
||||
'messenger-worker reads ONLY secret/data/messenger/worker (no Redis/metrics) and is denied api/migrator/admin/sys',
|
||||
wrk_ok,
|
||||
'own=200, no redis/metrics keys, all foreign/sys=403, no default policy',
|
||||
f'login={st_w} policies={wrk_pols} ttl={wrk_ttl}s own={w_own} api={w_api} mig={w_mig} adm={w_adm} pol={w_pol} seal={w_seal} cross={w_cross_login} no_redis_metrics={no_api_keys_in_wrk}')
|
||||
return api_bao, api_kv
|
||||
|
||||
|
||||
def check_secret_rotation(args, rc, api_bao, api_kv_before, ca_pem):
|
||||
img_before = common.app_image_id()
|
||||
ver_before = (((api_kv_before or {}).get('data') or {}).get('metadata') or {}).get('version')
|
||||
old_sec = (((api_kv_before or {}).get('data') or {}).get('data') or {})
|
||||
old_db_user = old_sec.get('db_user', 'messenger_api')
|
||||
old_db_pass = old_sec.get('db_password', '')
|
||||
rc.register_secret(old_db_pass)
|
||||
|
||||
common.run_host_script('scripts/rotate-secret.sh', 'api-db', operator_dir=args.operator_dir)
|
||||
|
||||
st_after, api_kv_after = api_bao.kv_read('secret/data/messenger/api')
|
||||
ver_after = (((api_kv_after or {}).get('data') or {}).get('metadata') or {}).get('version')
|
||||
new_db_pass = ((((api_kv_after or {}).get('data') or {}).get('data') or {}).get('db_password')) or ''
|
||||
rc.register_secret(new_db_pass)
|
||||
img_after = common.app_image_id()
|
||||
|
||||
# Prove OLD DB password rejected on NEW TLS connection
|
||||
old_pg = (_probe_pg_password(ca_pem, old_db_user, old_db_pass).get('result') or {})
|
||||
old_rejected = old_pg.get('ok') is False and (
|
||||
old_pg.get('code') == '28P01' or 'authentication failed' in str(old_pg.get('error', '')).lower()
|
||||
)
|
||||
|
||||
# Prove API seamlessly serves writes over HTTPS without rebuild
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
api_serving = False
|
||||
deadline = time.monotonic() + 20
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
u = client.user('rotdb')
|
||||
rc.register_secret(u['registration']['password'])
|
||||
rc.register_secret(u['token'])
|
||||
api_serving = True
|
||||
break
|
||||
except Failure:
|
||||
time.sleep(1)
|
||||
|
||||
ok = (
|
||||
st_after == 200
|
||||
and img_before == img_after
|
||||
and isinstance(ver_before, int) and isinstance(ver_after, int) and ver_after > ver_before
|
||||
and new_db_pass != old_db_pass
|
||||
and old_rejected
|
||||
and api_serving
|
||||
)
|
||||
rc.add('BAO-7-SECRET-ROTATION-NO-REBUILD', 'secret_rotation',
|
||||
'Live API DB password rotation increments KV version, rejects old password (28P01), keeps API serving without image rebuild',
|
||||
ok,
|
||||
'same Image SHA, KV version++, old PG password 28P01, API serves 201',
|
||||
f'same_image={img_before == img_after} secret_version_before={ver_before} secret_version_after={ver_after} old_password_rejected={old_rejected} api_serving={api_serving}')
|
||||
|
||||
|
||||
def check_cert_rotation_and_revocation(args, rc, ca_pem):
|
||||
hap_crt, hap_key = common.haproxy_client_pair()
|
||||
hap_crt_pem = _read_pem(hap_crt)
|
||||
hap_key_pem = _read_pem(hap_key) if hap_key else hap_crt_pem
|
||||
|
||||
img_before = common.app_image_id()
|
||||
before = (_probe_api_tls(ca_pem, hap_crt_pem, hap_key_pem).get('result') or {})
|
||||
serial_before = before.get('serial')
|
||||
|
||||
common.run_host_script('scripts/rotate-cert.sh', 'api', '--revoke', operator_dir=args.operator_dir)
|
||||
|
||||
disk_serial = common.pem_cert_info(common.ROOT / 'secrets/pki/api/server.crt')['serial']
|
||||
serial_after = None
|
||||
deadline = time.monotonic() + 15
|
||||
while time.monotonic() < deadline:
|
||||
after = (_probe_api_tls(ca_pem, hap_crt_pem, hap_key_pem).get('result') or {})
|
||||
if after.get('status') == 200 and after.get('serial') and after.get('serial') != serial_before:
|
||||
serial_after = after.get('serial')
|
||||
break
|
||||
time.sleep(1)
|
||||
|
||||
img_after = common.app_image_id()
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
ext_ok = client.call('GET', '/health/ready', 200, schema='Health')['status'] == 200
|
||||
|
||||
rc.add('BAO-8-LEAF-CERT-ROTATION-NO-REBUILD', 'cert_rotation',
|
||||
'Live API leaf cert rotation changes presented TLS serial without image rebuild or downtime',
|
||||
bool(serial_before and serial_after and serial_after != serial_before and serial_after.lstrip('0') == disk_serial.lstrip('0') and img_before == img_after and ext_ok),
|
||||
'serial changed & matches disk cert, same Image SHA, external HTTPS 200',
|
||||
f'serial_before={serial_before} serial_after={serial_after} disk_serial={disk_serial} same_image={img_before == img_after} ext_ok={ext_ok}')
|
||||
|
||||
# Client cert revocation on NEW connection (NC-6): issue temporary haproxy-lb SAN client cert, prove 200, revoke, prove rejected!
|
||||
tmpdir = Path(tempfile.mkdtemp(prefix='mtusi-lab7-revtest-'))
|
||||
try:
|
||||
common.run_host_script(
|
||||
'scripts/rotate-cert.sh',
|
||||
'--issue-test-client', 'revtest', 'haproxy-lb-revtest', 'haproxy-lb', str(tmpdir),
|
||||
operator_dir=args.operator_dir,
|
||||
)
|
||||
t_crt = tmpdir / 'revtest.crt'
|
||||
t_key = tmpdir / 'revtest.key'
|
||||
t_crt_pem = _read_pem(t_crt)
|
||||
t_key_pem = _read_pem(t_key)
|
||||
|
||||
pre = (_probe_api_tls(ca_pem, t_crt_pem, t_key_pem).get('result') or {})
|
||||
common.run_host_script(
|
||||
'scripts/rotate-cert.sh', '--revoke-cert', str(t_crt),
|
||||
operator_dir=args.operator_dir,
|
||||
)
|
||||
# Allow live SIGHUP/5s CRL reload to settle, then open BRAND-NEW TCP+TLS connection
|
||||
post = None
|
||||
deadline = time.monotonic() + 12
|
||||
while time.monotonic() < deadline:
|
||||
post = (_probe_api_tls(ca_pem, t_crt_pem, t_key_pem).get('result') or {})
|
||||
if post.get('status') != 200:
|
||||
break
|
||||
time.sleep(1)
|
||||
|
||||
revoked_ok = pre.get('status') == 200 and post is not None and (
|
||||
post.get('status') == 403 or bool(post.get('tlsError'))
|
||||
)
|
||||
rc.add('BAO-9-CERT-REVOCATION-NEW-CONN', 'cert_revocation',
|
||||
'Revoked client cert rejected on BRAND-NEW TCP+TLS connection (no TLS session resumption)',
|
||||
revoked_ok,
|
||||
'pre_revoke=200, post_revoke=TLS revoked or 403',
|
||||
f"pre={pre.get('status')} post_status={post.get('status') if post else None} post_err={post.get('tlsError') if post else None}")
|
||||
finally:
|
||||
shutil.rmtree(tmpdir, ignore_errors=True)
|
||||
|
||||
|
||||
def check_token_revocation(args, rc, op_bao):
|
||||
api_crt, api_key = common.service_client_pair('api')
|
||||
tmp_bao = common.OpenBaoClient(args.openbao_url, args.ca_file, cert_file=api_crt, key_file=api_key)
|
||||
st_login, _ = tmp_bao.cert_login('messenger-api')
|
||||
if tmp_bao.token:
|
||||
rc.register_secret(tmp_bao.token)
|
||||
st_look, look = tmp_bao.lookup_self()
|
||||
accessor = ((look or {}).get('data') or {}).get('accessor')
|
||||
ttl = ((look or {}).get('data') or {}).get('ttl')
|
||||
st_pre, _ = tmp_bao.kv_read('secret/data/messenger/api')
|
||||
|
||||
st_rev, _ = op_bao.revoke_accessor(accessor) if accessor else (0, None)
|
||||
st_post, _ = tmp_bao.kv_read('secret/data/messenger/api')
|
||||
|
||||
# Prove service cleanly re-authenticates via auth/cert
|
||||
st_reauth, _ = tmp_bao.cert_login('messenger-api')
|
||||
if tmp_bao.token:
|
||||
rc.register_secret(tmp_bao.token)
|
||||
st_after, _ = tmp_bao.kv_read('secret/data/messenger/api')
|
||||
|
||||
ok = (
|
||||
st_login == 200 and st_look == 200 and st_pre == 200
|
||||
and st_rev in (200, 204) and st_post == 403
|
||||
and st_reauth == 200 and st_after == 200
|
||||
)
|
||||
rc.add('BAO-10-TOKEN-REVOKE-AND-REAUTH', 'token_lifecycle',
|
||||
'Revoked OpenBao token fails immediately (403) and service re-authenticates via auth/cert',
|
||||
ok,
|
||||
'pre=200, revoke=204, post_revoke=403, reauth=200',
|
||||
f'ttl={ttl}s pre={st_pre} revoke={st_rev} post={st_post} reauth={st_reauth} after={st_after}')
|
||||
|
||||
|
||||
def check_sealed_openbao_and_recovery(args, rc, op_bao):
|
||||
api_crt, api_key = common.service_client_pair('api')
|
||||
_, pre_kv = op_bao.kv_read('secret/data/messenger/api')
|
||||
ver_before = (((pre_kv or {}).get('data') or {}).get('metadata') or {}).get('version')
|
||||
restarts_before = {
|
||||
cid[:12]: common.container_inspect(cid)['RestartCount']
|
||||
for cid in common.container_ids('api')
|
||||
}
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
sealed_ok = False
|
||||
degraded_api_ok = False
|
||||
cold_fail_closed = False
|
||||
booted_sealed = False
|
||||
unsealed_ok = False
|
||||
raft_persisted = False
|
||||
|
||||
try:
|
||||
# 1. Seal OpenBao
|
||||
st_seal, _ = op_bao.seal()
|
||||
st_h1, h1 = common.OpenBaoClient(args.openbao_url, args.ca_file).health()
|
||||
sealed_ok = st_seal in (200, 204) and st_h1 == 503 and bool((h1 or {}).get('sealed'))
|
||||
|
||||
# 2. Prove running API continues serving cleanly on cached RAM credentials/pools with 0 secret leaks in logs
|
||||
r_ready = client.call('GET', '/health/ready', 200, schema='Health')
|
||||
u = client.user('sealed')
|
||||
rc.register_secret(u['registration']['password'])
|
||||
rc.register_secret(u['token'])
|
||||
restarts_mid = {
|
||||
cid[:12]: common.container_inspect(cid)['RestartCount']
|
||||
for cid in common.container_ids('api')
|
||||
}
|
||||
api_logs = common.compose('logs', '--since', '2m', '--no-color', 'api', check_result=False).stdout or ''
|
||||
log_leaks = (
|
||||
common._PEM_KEY_RE.search(api_logs) is not None
|
||||
or common._BAO_TOKEN_RE.search(api_logs) is not None
|
||||
or common._ARGON2_RE.search(api_logs) is not None
|
||||
)
|
||||
degraded_api_ok = r_ready['status'] == 200 and restarts_mid == restarts_before and not log_leaks
|
||||
|
||||
# 3. Prove cold auth/cert login fails closed (503 Vault is sealed)
|
||||
probe_bao = common.OpenBaoClient(args.openbao_url, args.ca_file, cert_file=api_crt, key_file=api_key)
|
||||
st_cold, _ = probe_bao.cert_login('messenger-api')
|
||||
cold_fail_closed = st_cold == 503
|
||||
|
||||
# 4. Restart OpenBao container -> MUST boot SEALED (proving no unprotected auto-unseal!)
|
||||
common.compose('restart', 'openbao')
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
st_h2, h2 = common.OpenBaoClient(args.openbao_url, args.ca_file).health()
|
||||
if st_h2 == 503 and (h2 or {}).get('sealed') is True:
|
||||
booted_sealed = True
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
finally:
|
||||
# 5. ALWAYS manually unseal OpenBao via operator script so stand recovers cleanly
|
||||
common.run_host_script('scripts/openbao-unseal.sh', operator_dir=args.operator_dir)
|
||||
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
st_h3, h3 = common.OpenBaoClient(args.openbao_url, args.ca_file).health()
|
||||
if st_h3 == 200 and (h3 or {}).get('sealed') is False:
|
||||
unsealed_ok = True
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(0.5)
|
||||
|
||||
# Verify Raft secrets & policies survived restart intact
|
||||
op_bao2 = common.OpenBaoClient(args.openbao_url, args.ca_file,
|
||||
cert_file=op_bao.cert_file, key_file=op_bao.key_file)
|
||||
st_op2, _ = op_bao2.cert_login('messenger-operator')
|
||||
if op_bao2.token:
|
||||
rc.register_secret(op_bao2.token)
|
||||
st_kv2, post_kv = op_bao2.kv_read('secret/data/messenger/api')
|
||||
ver_after = (((post_kv or {}).get('data') or {}).get('metadata') or {}).get('version')
|
||||
raft_persisted = st_op2 == 200 and st_kv2 == 200 and ver_after == ver_before
|
||||
post_ready = client.call('GET', '/health/ready', 200, schema='Health')['status'] == 200
|
||||
|
||||
rc.add('BAO-11-SEALED-BOUNDED-BEHAVIOR', 'sealed_recovery',
|
||||
'When OpenBao is sealed, running API stays bounded (0 restarts) and cold login fails closed (503)',
|
||||
sealed_ok and degraded_api_ok and cold_fail_closed,
|
||||
'sealed=503, api_ok=True, cold_login=503',
|
||||
f'sealed={sealed_ok}, api_ok={degraded_api_ok}, cold_fail_closed={cold_fail_closed}')
|
||||
rc.add('BAO-12-RESTART-SEALED-AND-MANUAL-UNSEAL', 'sealed_recovery',
|
||||
'Restarted OpenBao boots sealed, manual scripts/openbao-unseal.sh restores Raft state & API health',
|
||||
booted_sealed and unsealed_ok and raft_persisted and post_ready,
|
||||
'booted_sealed=True, unsealed=True, raft_kv_intact=True, api=200',
|
||||
f'booted_sealed={booted_sealed}, unsealed={unsealed_ok}, ver_before={ver_before}, ver_after={ver_after}, api_ready={post_ready}')
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
common.add_common_args(parser)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
rc = common.ResultCollector('lab7-openbao-lifecycle')
|
||||
ca_pem = _read_pem(args.ca_file)
|
||||
op_crt, op_key = common.operator_cert_pair(args.operator_dir)
|
||||
rogue_crt, rogue_key = common.rogue_cert_pair(args.operator_dir)
|
||||
|
||||
op_bao = check_openbao_posture(args, rc, op_crt, op_key, rogue_crt, rogue_key)
|
||||
api_bao, api_kv = check_policy_matrix(args, rc)
|
||||
check_secret_rotation(args, rc, api_bao, api_kv, ca_pem)
|
||||
check_cert_rotation_and_revocation(args, rc, ca_pem)
|
||||
check_token_revocation(args, rc, op_bao)
|
||||
check_sealed_openbao_and_recovery(args, rc, op_bao)
|
||||
|
||||
rc.summary = {'openbao_url': args.openbao_url, 'base_url': args.base_url}
|
||||
(json_path, txt_path), rep = rc.save(args.output_dir, 'openbao-lifecycle')
|
||||
print(f"Report written: {json_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)
|
||||
Executable
+907
@@ -0,0 +1,907 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Lab 7 Full Trust-Matrix TLS & mTLS Identity Audit (Grade 3 + Grade 4).
|
||||
|
||||
Verifies NC-1 (external TLS), NC-2 (LB->API mTLS + SAN allowlist),
|
||||
NC-3 (RabbitMQ EXTERNAL mTLS + OTel Gateway mTLS + closed loopback boundary),
|
||||
and TLS/mTLS across PostgreSQL, Redis, MinIO, OpenBao, Prometheus, Loki, Tempo,
|
||||
and Grafana. Writes sanitized JSON + TXT evidence to evidence/lab7/tls-audit.*.
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.parse
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent))
|
||||
import common # noqa: E402
|
||||
|
||||
|
||||
def _read_text(path):
|
||||
p = Path(path)
|
||||
if not p.is_file():
|
||||
return None
|
||||
return p.read_text(encoding='utf-8')
|
||||
|
||||
|
||||
def _load_pem_pair(crt_path, key_path=None):
|
||||
crt = _read_text(crt_path)
|
||||
key = _read_text(key_path) if key_path else crt
|
||||
return crt, key
|
||||
|
||||
|
||||
def _is_tls_rejection(err):
|
||||
if not err:
|
||||
return False
|
||||
up = str(err).upper()
|
||||
return not any(tok in up for tok in ('ETIMEDOUT', 'ENOTFOUND', 'ECONNREFUSED', 'EAI_AGAIN'))
|
||||
|
||||
|
||||
def _node_https_probe(network, host, port, path, ca_pem, method='GET',
|
||||
cert_pem=None, key_pem=None, headers=None, body=None,
|
||||
servername=None, plain_http=False, exec_service=None):
|
||||
js = """
|
||||
const https = require('https');
|
||||
const http = require('http');
|
||||
const crypto = require('crypto');
|
||||
const p = payload;
|
||||
return await new Promise((resolve) => {
|
||||
const mod = p.plain_http ? http : https;
|
||||
const opts = {
|
||||
hostname: p.host,
|
||||
port: p.port,
|
||||
path: p.path,
|
||||
method: p.method || 'GET',
|
||||
headers: Object.assign({ Connection: 'close' }, p.headers || {}),
|
||||
timeout: 6000,
|
||||
};
|
||||
if (!p.plain_http) {
|
||||
opts.ca = p.ca_pem;
|
||||
opts.rejectUnauthorized = true;
|
||||
opts.servername = p.servername || p.host;
|
||||
opts.minVersion = 'TLSv1.2';
|
||||
opts.secureOptions = crypto.constants.SSL_OP_NO_TICKET;
|
||||
if (p.cert_pem) opts.cert = p.cert_pem;
|
||||
if (p.key_pem) opts.key = p.key_pem;
|
||||
}
|
||||
const req = mod.request(opts, (res) => {
|
||||
const chunks = [];
|
||||
res.on('data', (c) => chunks.push(c));
|
||||
res.on('end', () => {
|
||||
const text = Buffer.concat(chunks).toString('utf8').slice(0, 400);
|
||||
resolve({ status: res.statusCode, body: text, tlsError: null });
|
||||
});
|
||||
});
|
||||
req.on('timeout', () => {
|
||||
req.destroy(new Error('ETIMEDOUT'));
|
||||
});
|
||||
req.on('error', (err) => {
|
||||
resolve({ status: null, body: '', tlsError: err.code || err.message || String(err) });
|
||||
});
|
||||
if (p.body) req.write(p.body);
|
||||
req.end();
|
||||
});
|
||||
"""
|
||||
return common.run_node_probe(
|
||||
js,
|
||||
{
|
||||
'host': host,
|
||||
'port': int(port),
|
||||
'path': path,
|
||||
'method': method,
|
||||
'ca_pem': ca_pem,
|
||||
'cert_pem': cert_pem,
|
||||
'key_pem': key_pem,
|
||||
'headers': headers or {},
|
||||
'body': body,
|
||||
'servername': servername,
|
||||
'plain_http': plain_http,
|
||||
},
|
||||
network=network,
|
||||
exec_service=exec_service,
|
||||
)
|
||||
|
||||
|
||||
def _node_tcp_probe(network, host, port):
|
||||
js = """
|
||||
const net = require('net');
|
||||
return await new Promise((resolve) => {
|
||||
const s = net.createConnection({ host: payload.host, port: payload.port, timeout: 3000 });
|
||||
s.on('connect', () => { s.destroy(); resolve({ connected: true, code: null }); });
|
||||
s.on('timeout', () => { s.destroy(); resolve({ connected: false, code: 'ETIMEDOUT' }); });
|
||||
s.on('error', (err) => { resolve({ connected: false, code: err.code || err.message }); });
|
||||
});
|
||||
"""
|
||||
return common.run_node_probe(js, {'host': host, 'port': int(port)}, network=network)
|
||||
|
||||
|
||||
def _node_amqp_probe(ca_pem, cert_pem=None, key_pem=None, action='check_exchange',
|
||||
target='attachments.jobs', vhost='messenger'):
|
||||
js = """
|
||||
const amqp = require('amqplib');
|
||||
const crypto = require('crypto');
|
||||
const p = payload;
|
||||
const sockOpts = {
|
||||
ca: [Buffer.from(p.ca_pem)],
|
||||
servername: 'broker',
|
||||
rejectUnauthorized: true,
|
||||
minVersion: 'TLSv1.2',
|
||||
secureOptions: crypto.constants.SSL_OP_NO_TICKET,
|
||||
};
|
||||
if (p.cert_pem) sockOpts.cert = Buffer.from(p.cert_pem);
|
||||
if (p.key_pem) sockOpts.key = Buffer.from(p.key_pem);
|
||||
let conn = null;
|
||||
try {
|
||||
conn = await amqp.connect({
|
||||
protocol: 'amqps',
|
||||
hostname: 'broker',
|
||||
port: 5671,
|
||||
vhost: p.vhost || 'messenger',
|
||||
credentials: amqp.credentials.external(),
|
||||
}, sockOpts);
|
||||
conn.on('error', () => {});
|
||||
if (p.action === 'check_exchange') {
|
||||
const ch = await conn.createConfirmChannel();
|
||||
ch.on('error', () => {});
|
||||
await ch.checkExchange(p.target);
|
||||
await ch.close();
|
||||
return { allowed: true, stage: 'checkExchange' };
|
||||
}
|
||||
if (p.action === 'check_queue') {
|
||||
const ch = await conn.createChannel();
|
||||
ch.on('error', () => {});
|
||||
const info = await ch.checkQueue(p.target);
|
||||
await ch.close();
|
||||
return { allowed: true, stage: 'checkQueue', messageCount: info.messageCount };
|
||||
}
|
||||
if (p.action === 'publish') {
|
||||
const ch = await conn.createConfirmChannel();
|
||||
let chanErr = null;
|
||||
ch.on('error', (e) => { chanErr = e.message || String(e); });
|
||||
ch.publish(p.target, 'attachment.process.v1', Buffer.from('{}'));
|
||||
await ch.waitForConfirms();
|
||||
if (chanErr) return { allowed: false, stage: 'publish', error: chanErr };
|
||||
await ch.close();
|
||||
return { allowed: true, stage: 'publish' };
|
||||
}
|
||||
return { allowed: true, stage: 'connect' };
|
||||
} catch (err) {
|
||||
return { allowed: false, stage: p.action, error: (err && (err.code || err.message)) || String(err) };
|
||||
} finally {
|
||||
if (conn) { try { await conn.close(); } catch (_) {} }
|
||||
}
|
||||
"""
|
||||
return common.run_node_probe(
|
||||
js,
|
||||
{
|
||||
'ca_pem': ca_pem,
|
||||
'cert_pem': cert_pem,
|
||||
'key_pem': key_pem,
|
||||
'action': action,
|
||||
'target': target,
|
||||
'vhost': vhost,
|
||||
},
|
||||
network='app_data',
|
||||
)
|
||||
|
||||
|
||||
def _node_pg_probe(ca_pem, user, password, ssl_mode='verify-full', servername='postgres'):
|
||||
js = """
|
||||
const { Client } = require('pg');
|
||||
const p = payload;
|
||||
const cfg = {
|
||||
host: 'postgres',
|
||||
port: 5432,
|
||||
database: 'messenger',
|
||||
user: p.user,
|
||||
password: p.password,
|
||||
connectionTimeoutMillis: 5000,
|
||||
};
|
||||
if (p.ssl_mode === 'disable') {
|
||||
cfg.ssl = false;
|
||||
} else {
|
||||
cfg.ssl = {
|
||||
ca: p.ca_pem,
|
||||
rejectUnauthorized: true,
|
||||
servername: p.servername || 'postgres',
|
||||
minVersion: 'TLSv1.2',
|
||||
};
|
||||
}
|
||||
const client = new Client(cfg);
|
||||
try {
|
||||
await client.connect();
|
||||
const res = await client.query(
|
||||
'SELECT ssl, version FROM pg_stat_ssl WHERE pid = pg_backend_pid()'
|
||||
);
|
||||
await client.end();
|
||||
return { connected: true, row: res.rows[0] || null };
|
||||
} catch (err) {
|
||||
try { await client.end(); } catch (_) {}
|
||||
return { connected: false, code: err.code || null, error: err.message || String(err) };
|
||||
}
|
||||
"""
|
||||
return common.run_node_probe(
|
||||
js,
|
||||
{
|
||||
'ca_pem': ca_pem,
|
||||
'user': user,
|
||||
'password': password,
|
||||
'ssl_mode': ssl_mode,
|
||||
'servername': servername,
|
||||
},
|
||||
network='app_data',
|
||||
)
|
||||
|
||||
|
||||
def _node_redis_probe(ca_pem, cert_pem=None, key_pem=None, username=None,
|
||||
password=None, use_tls=True, cmd='ping'):
|
||||
js = """
|
||||
const { createClient } = require('redis');
|
||||
const net = require('net');
|
||||
const p = payload;
|
||||
if (!p.use_tls) {
|
||||
return await new Promise((resolve) => {
|
||||
const s = net.createConnection({ host: 'redis', port: 6379, timeout: 3000 });
|
||||
let data = '';
|
||||
s.on('connect', () => { s.write('*1\\r\\n$4\\r\\nPING\\r\\n'); });
|
||||
s.on('data', (chunk) => { data += chunk.toString('utf8'); s.destroy(); });
|
||||
s.on('close', () => resolve({ ok: data.includes('PONG'), reply: data.slice(0, 80) }));
|
||||
s.on('timeout', () => { s.destroy(); resolve({ ok: false, error: 'ETIMEDOUT' }); });
|
||||
s.on('error', (err) => resolve({ ok: false, error: err.code || err.message }));
|
||||
});
|
||||
}
|
||||
const socketCfg = {
|
||||
host: 'redis',
|
||||
port: 6379,
|
||||
tls: true,
|
||||
ca: p.ca_pem,
|
||||
servername: 'redis',
|
||||
rejectUnauthorized: true,
|
||||
minVersion: 'TLSv1.2',
|
||||
connectTimeout: 4000,
|
||||
reconnectStrategy: false,
|
||||
};
|
||||
if (p.cert_pem) socketCfg.cert = p.cert_pem;
|
||||
if (p.key_pem) socketCfg.key = p.key_pem;
|
||||
const opts = { socket: socketCfg };
|
||||
if (p.username) opts.username = p.username;
|
||||
if (p.password) opts.password = p.password;
|
||||
const client = createClient(opts);
|
||||
client.on('error', () => {});
|
||||
try {
|
||||
await client.connect();
|
||||
if (p.cmd === 'config_get') {
|
||||
const val = await client.sendCommand(['CONFIG', 'GET', 'maxmemory']);
|
||||
await client.quit();
|
||||
return { ok: true, reply: String(val) };
|
||||
}
|
||||
const reply = await client.ping();
|
||||
await client.quit();
|
||||
return { ok: reply === 'PONG', reply };
|
||||
} catch (err) {
|
||||
try { client.destroy(); } catch (_) {}
|
||||
return { ok: false, error: err.code || err.message || String(err) };
|
||||
}
|
||||
"""
|
||||
return common.run_node_probe(
|
||||
js,
|
||||
{
|
||||
'ca_pem': ca_pem,
|
||||
'cert_pem': cert_pem,
|
||||
'key_pem': key_pem,
|
||||
'username': username,
|
||||
'password': password,
|
||||
'use_tls': use_tls,
|
||||
'cmd': cmd,
|
||||
},
|
||||
network='app_data',
|
||||
)
|
||||
|
||||
|
||||
def _fetch_api_secrets(openbao_url, ca_file, api_crt, api_key, rc):
|
||||
bao = common.OpenBaoClient(openbao_url, ca_file, cert_file=api_crt, key_file=api_key)
|
||||
st, data = bao.cert_login('messenger-api')
|
||||
if st != 200 or not bao.token:
|
||||
return None
|
||||
rc.register_secret(bao.token)
|
||||
st, kv = bao.kv_read('secret/data/messenger/api')
|
||||
if st != 200 or not kv:
|
||||
return None
|
||||
sec = kv.get('data', {}).get('data', {})
|
||||
for k in ('db_password', 'redis_password', 's3_secret_access_key', 'metrics_token'):
|
||||
if sec.get(k):
|
||||
rc.register_secret(sec[k])
|
||||
return sec
|
||||
|
||||
|
||||
def audit_external_tls(args, rc, ca_file, foreign_ca):
|
||||
base = args.base_url.rstrip('/')
|
||||
parsed = urllib.parse.urlsplit(base)
|
||||
port = parsed.port or 8443
|
||||
|
||||
# 1. Positive HTTPS with CA + localhost
|
||||
try:
|
||||
ctx = common.make_ssl_context(ca_file=ca_file)
|
||||
resp = common.https_request('GET', base + '/health/ready', ssl_ctx=ctx)
|
||||
ok = resp['status'] == 200 and resp['peer_cert'] is not None
|
||||
rc.add(
|
||||
'EXT-1-HTTPS-OK', 'external_tls',
|
||||
'External HTTPS with valid CA and hostname succeeds',
|
||||
ok, 'HTTP 200 over TLSv1.2+',
|
||||
f"status={resp['status']} tls={resp['peer_cert']['version'] if resp['peer_cert'] else None}",
|
||||
{'peer_cert': resp['peer_cert']},
|
||||
)
|
||||
except Exception as exc:
|
||||
rc.add('EXT-1-HTTPS-OK', 'external_tls',
|
||||
'External HTTPS with valid CA and hostname succeeds',
|
||||
False, 'HTTP 200', f'{type(exc).__name__}: {exc}')
|
||||
|
||||
# 2. Empty trust store rejected with SSLCertVerificationError
|
||||
try:
|
||||
ctx = common.make_ssl_context(empty_trust=True)
|
||||
resp = common.https_request('GET', base + '/health/ready', ssl_ctx=ctx)
|
||||
rc.add('EXT-2-EMPTY-CA', 'external_tls',
|
||||
'External HTTPS rejects empty CA trust store',
|
||||
False, 'SSLCertVerificationError', f"unexpected status={resp['status']}")
|
||||
except ssl.SSLCertVerificationError as exc:
|
||||
rc.add('EXT-2-EMPTY-CA', 'external_tls',
|
||||
'External HTTPS rejects empty CA trust store',
|
||||
True, 'SSLCertVerificationError', f'SSLCertVerificationError ({exc.verify_message})')
|
||||
except Exception as exc:
|
||||
rc.add('EXT-2-EMPTY-CA', 'external_tls',
|
||||
'External HTTPS rejects empty CA trust store',
|
||||
False, 'SSLCertVerificationError', f'{type(exc).__name__}: {exc}')
|
||||
|
||||
# 3. Foreign CA rejected with SSLCertVerificationError
|
||||
if Path(foreign_ca).is_file():
|
||||
try:
|
||||
ctx = common.make_ssl_context(ca_file=foreign_ca)
|
||||
resp = common.https_request('GET', base + '/health/ready', ssl_ctx=ctx)
|
||||
rc.add('EXT-3-FOREIGN-CA', 'external_tls',
|
||||
'External HTTPS rejects foreign untrusted CA',
|
||||
False, 'SSLCertVerificationError', f"unexpected status={resp['status']}")
|
||||
except ssl.SSLCertVerificationError as exc:
|
||||
rc.add('EXT-3-FOREIGN-CA', 'external_tls',
|
||||
'External HTTPS rejects foreign untrusted CA',
|
||||
True, 'SSLCertVerificationError', f'SSLCertVerificationError ({exc.verify_message})')
|
||||
except Exception as exc:
|
||||
rc.add('EXT-3-FOREIGN-CA', 'external_tls',
|
||||
'External HTTPS rejects foreign untrusted CA',
|
||||
False, 'SSLCertVerificationError', f'{type(exc).__name__}: {exc}')
|
||||
else:
|
||||
rc.add('EXT-3-FOREIGN-CA', 'external_tls',
|
||||
'External HTTPS rejects foreign untrusted CA',
|
||||
False, 'foreign-ca.crt exists', f'missing {foreign_ca}')
|
||||
|
||||
# 4. Wrong hostname (https://127.0.0.1:8443) rejected with hostname verification error
|
||||
ip_url = f'https://127.0.0.1:{port}/health/ready'
|
||||
try:
|
||||
ctx = common.make_ssl_context(ca_file=ca_file, check_hostname=True)
|
||||
resp = common.https_request('GET', ip_url, ssl_ctx=ctx)
|
||||
rc.add('EXT-4-HOSTNAME-MISMATCH', 'external_tls',
|
||||
'External HTTPS rejects wrong hostname (127.0.0.1 not in SAN)',
|
||||
False, 'SSLCertVerificationError', f"unexpected status={resp['status']}")
|
||||
except ssl.SSLCertVerificationError as exc:
|
||||
rc.add('EXT-4-HOSTNAME-MISMATCH', 'external_tls',
|
||||
'External HTTPS rejects wrong hostname (127.0.0.1 not in SAN)',
|
||||
True, 'SSLCertVerificationError', f'SSLCertVerificationError ({exc.verify_message})')
|
||||
except Exception as exc:
|
||||
rc.add('EXT-4-HOSTNAME-MISMATCH', 'external_tls',
|
||||
'External HTTPS rejects wrong hostname (127.0.0.1 not in SAN)',
|
||||
False, 'SSLCertVerificationError', f'{type(exc).__name__}: {exc}')
|
||||
|
||||
# 5. /internal/metrics blocked 404 on :8443
|
||||
try:
|
||||
ctx = common.make_ssl_context(ca_file=ca_file)
|
||||
resp = common.https_request('GET', base + '/internal/metrics', ssl_ctx=ctx)
|
||||
rc.add('EXT-5-INTERNAL-BLOCKED', 'external_tls',
|
||||
'/internal/metrics blocked with 404 on external :8443',
|
||||
resp['status'] == 404, 'HTTP 404', f"status={resp['status']}")
|
||||
except Exception as exc:
|
||||
rc.add('EXT-5-INTERNAL-BLOCKED', 'external_tls',
|
||||
'/internal/metrics blocked with 404 on external :8443',
|
||||
False, 'HTTP 404', f'{type(exc).__name__}: {exc}')
|
||||
|
||||
# 6. Plaintext :8080 closed
|
||||
closed = common.tcp_port_closed('127.0.0.1', 8080)
|
||||
rc.add('EXT-6-PLAINTEXT-8080-CLOSED', 'external_tls',
|
||||
'Plaintext HTTP port 8080 is closed on host',
|
||||
closed, 'TCP connection refused', 'closed' if closed else 'OPEN')
|
||||
|
||||
# 7. API loopback health listener isolation (127.0.0.1:8081 serves health ONLY, 404 on /api/*)
|
||||
health_ok = _node_https_probe(
|
||||
None, '127.0.0.1', 8081, '/health/ready', None,
|
||||
plain_http=True, exec_service='api',
|
||||
)
|
||||
api_blocked = _node_https_probe(
|
||||
None, '127.0.0.1', 8081, '/api/v1/users/me', None,
|
||||
plain_http=True, exec_service='api',
|
||||
)
|
||||
metrics_blocked = _node_https_probe(
|
||||
None, '127.0.0.1', 8081, '/internal/metrics', None,
|
||||
plain_http=True, exec_service='api',
|
||||
)
|
||||
h_st = (health_ok.get('result') or {}).get('status')
|
||||
a_st = (api_blocked.get('result') or {}).get('status')
|
||||
m_st = (metrics_blocked.get('result') or {}).get('status')
|
||||
rc.add(
|
||||
'EXT-7-HEALTH-ISOLATION', 'health_isolation',
|
||||
'API loopback 127.0.0.1:8081 serves /health/ready only and returns 404 on /api/* & /internal/*',
|
||||
h_st == 200 and a_st == 404 and m_st == 404,
|
||||
'health=200, api=404, internal=404',
|
||||
f'health={h_st}, api={a_st}, internal={m_st}',
|
||||
)
|
||||
|
||||
|
||||
def audit_lb_to_api_mtls(rc, ca_pem, foreign_pair, rogue_pair, worker_pair, haproxy_pair):
|
||||
# No published ports on api
|
||||
api_cids = common.container_ids('api')
|
||||
pub = []
|
||||
for cid in api_cids:
|
||||
ports = common.container_inspect(cid).get('NetworkSettings', {}).get('Ports') or {}
|
||||
for p, bindings in ports.items():
|
||||
if bindings:
|
||||
pub.append(f'{cid[:12]}:{p}')
|
||||
rc.add('MTLS-API-0-NO-HOST-PORTS', 'lb_to_api_mtls',
|
||||
'API replicas publish zero host ports',
|
||||
len(api_cids) >= 2 and not pub,
|
||||
'>=2 replicas, 0 published ports',
|
||||
f'replicas={len(api_cids)}, published={pub}')
|
||||
|
||||
# 1. No client cert -> TLS reject
|
||||
r = _node_https_probe('lb_api', 'api', 8443, '/health/ready', ca_pem)
|
||||
res = r.get('result') or {}
|
||||
rc.add('MTLS-API-1-NO-CERT', 'lb_to_api_mtls',
|
||||
'LB->API rejects connection without client certificate',
|
||||
res.get('status') is None and _is_tls_rejection(res.get('tlsError')),
|
||||
'TLS handshake error',
|
||||
f"status={res.get('status')} error={res.get('tlsError')}")
|
||||
|
||||
# 2. Foreign CA cert -> TLS reject
|
||||
r = _node_https_probe('lb_api', 'api', 8443, '/health/ready', ca_pem,
|
||||
cert_pem=foreign_pair[0], key_pem=foreign_pair[1])
|
||||
res = r.get('result') or {}
|
||||
rc.add('MTLS-API-2-FOREIGN-CA', 'lb_to_api_mtls',
|
||||
'LB->API rejects client certificate signed by foreign CA',
|
||||
res.get('status') is None and _is_tls_rejection(res.get('tlsError')),
|
||||
'TLS handshake error',
|
||||
f"status={res.get('status')} error={res.get('tlsError')}")
|
||||
|
||||
# 3. Trusted CA rogue-client -> rejected (403)
|
||||
r = _node_https_probe('lb_api', 'api', 8443, '/health/ready', ca_pem,
|
||||
cert_pem=rogue_pair[0], key_pem=rogue_pair[1])
|
||||
res = r.get('result') or {}
|
||||
rc.add('MTLS-API-3-ROGUE-CLIENT', 'lb_to_api_mtls',
|
||||
'LB->API rejects trusted-CA rogue-client identity (not CA-only)',
|
||||
res.get('status') == 403 or _is_tls_rejection(res.get('tlsError')),
|
||||
'HTTP 403 (or TLS reject)',
|
||||
f"status={res.get('status')} error={res.get('tlsError')}")
|
||||
|
||||
# 4. Trusted CA messenger-worker -> rejected (403)
|
||||
r = _node_https_probe('lb_api', 'api', 8443, '/health/ready', ca_pem,
|
||||
cert_pem=worker_pair[0], key_pem=worker_pair[1])
|
||||
res = r.get('result') or {}
|
||||
rc.add('MTLS-API-4-WORKER-DENIED', 'lb_to_api_mtls',
|
||||
'LB->API rejects trusted-CA messenger-worker identity',
|
||||
res.get('status') == 403 or _is_tls_rejection(res.get('tlsError')),
|
||||
'HTTP 403 (or TLS reject)',
|
||||
f"status={res.get('status')} error={res.get('tlsError')}")
|
||||
|
||||
# 5. Valid haproxy-lb cert -> 200
|
||||
r = _node_https_probe('lb_api', 'api', 8443, '/health/ready', ca_pem,
|
||||
cert_pem=haproxy_pair[0], key_pem=haproxy_pair[1])
|
||||
res = r.get('result') or {}
|
||||
rc.add('MTLS-API-5-HAPROXY-OK', 'lb_to_api_mtls',
|
||||
'LB->API accepts valid haproxy-lb client identity',
|
||||
res.get('status') == 200,
|
||||
'HTTP 200',
|
||||
f"status={res.get('status')} error={res.get('tlsError')}")
|
||||
|
||||
|
||||
def audit_broker_mtls(rc, ca_pem, foreign_pair, rogue_pair, haproxy_pair, api_pair, worker_pair):
|
||||
# 0. Plaintext 5672 closed
|
||||
tcp = _node_tcp_probe('app_data', 'broker', 5672).get('result') or {}
|
||||
rc.add('MTLS-BROKER-0-PLAIN-CLOSED', 'broker_mtls',
|
||||
'RabbitMQ plaintext port 5672 is closed',
|
||||
tcp.get('connected') is False,
|
||||
'ECONNREFUSED', f"connected={tcp.get('connected')} code={tcp.get('code')}")
|
||||
|
||||
# 1. No client cert -> rejected
|
||||
r = _node_amqp_probe(ca_pem).get('result') or {}
|
||||
rc.add('MTLS-BROKER-1-NO-CERT', 'broker_mtls',
|
||||
'RabbitMQ AMQPS 5671 rejects connection without client cert',
|
||||
r.get('allowed') is False, 'TLS reject', f"allowed={r.get('allowed')} error={r.get('error')}")
|
||||
|
||||
# 2. Foreign CA cert -> rejected
|
||||
r = _node_amqp_probe(ca_pem, cert_pem=foreign_pair[0], key_pem=foreign_pair[1]).get('result') or {}
|
||||
rc.add('MTLS-BROKER-2-FOREIGN-CA', 'broker_mtls',
|
||||
'RabbitMQ AMQPS 5671 rejects foreign-CA client cert',
|
||||
r.get('allowed') is False, 'TLS reject', f"allowed={r.get('allowed')} error={r.get('error')}")
|
||||
|
||||
# 3. Trusted-CA rogue-client -> rejected (EXTERNAL user absent)
|
||||
r = _node_amqp_probe(ca_pem, cert_pem=rogue_pair[0], key_pem=rogue_pair[1]).get('result') or {}
|
||||
rc.add('MTLS-BROKER-3-ROGUE-CLIENT', 'broker_mtls',
|
||||
'RabbitMQ AMQPS 5671 rejects trusted-CA rogue-client identity',
|
||||
r.get('allowed') is False, 'ACCESS_REFUSED', f"allowed={r.get('allowed')} error={r.get('error')}")
|
||||
|
||||
# 4. Trusted-CA haproxy-lb -> rejected
|
||||
r = _node_amqp_probe(ca_pem, cert_pem=haproxy_pair[0], key_pem=haproxy_pair[1]).get('result') or {}
|
||||
rc.add('MTLS-BROKER-4-LB-DENIED', 'broker_mtls',
|
||||
'RabbitMQ AMQPS 5671 rejects trusted-CA haproxy-lb identity',
|
||||
r.get('allowed') is False, 'ACCESS_REFUSED', f"allowed={r.get('allowed')} error={r.get('error')}")
|
||||
|
||||
# 5. Worker publish to attachments.jobs -> ACCESS_REFUSED
|
||||
r = _node_amqp_probe(ca_pem, cert_pem=worker_pair[0], key_pem=worker_pair[1],
|
||||
action='publish', target='attachments.jobs').get('result') or {}
|
||||
rc.add('MTLS-BROKER-5-WORKER-PUBLISH-DENIED', 'broker_mtls',
|
||||
'RabbitMQ denies messenger-worker publish to attachments.jobs',
|
||||
r.get('allowed') is False, 'ACCESS_REFUSED', f"allowed={r.get('allowed')} error={r.get('error')}")
|
||||
|
||||
# 6. Worker passive checkQueue(attachments.process) -> allowed
|
||||
r = _node_amqp_probe(ca_pem, cert_pem=worker_pair[0], key_pem=worker_pair[1],
|
||||
action='check_queue', target='attachments.process').get('result') or {}
|
||||
rc.add('MTLS-BROKER-6-WORKER-CONSUME-OK', 'broker_mtls',
|
||||
'RabbitMQ allows messenger-worker read on attachments.process',
|
||||
r.get('allowed') is True, 'allowed=True', f"allowed={r.get('allowed')} error={r.get('error')}")
|
||||
|
||||
# 7. API passive checkExchange(attachments.jobs) -> allowed
|
||||
r = _node_amqp_probe(ca_pem, cert_pem=api_pair[0], key_pem=api_pair[1],
|
||||
action='check_exchange', target='attachments.jobs').get('result') or {}
|
||||
rc.add('MTLS-BROKER-7-API-PRODUCER-OK', 'broker_mtls',
|
||||
'RabbitMQ allows messenger-api access to attachments.jobs',
|
||||
r.get('allowed') is True, 'allowed=True', f"allowed={r.get('allowed')} error={r.get('error')}")
|
||||
|
||||
|
||||
def audit_otel_mtls(rc, ca_pem, foreign_pair, rogue_pair, haproxy_pair, api_pair, worker_pair):
|
||||
otlp_headers = {'Content-Type': 'application/json'}
|
||||
otlp_body = '{"resourceSpans":[]}'
|
||||
|
||||
# 0. Closed loopback bypass check: 14318 unreachable from app_data
|
||||
tcp = _node_tcp_probe('app_data', 'otel-collector', 14318).get('result') or {}
|
||||
rc.add('MTLS-OTEL-0-LOOPBACK-CLOSED', 'otel_mtls',
|
||||
'OTel Collector loopback port 14318 unreachable outside shared netns',
|
||||
tcp.get('connected') is False, 'ECONNREFUSED',
|
||||
f"connected={tcp.get('connected')} code={tcp.get('code')}")
|
||||
|
||||
# 1. No client cert -> TLS reject
|
||||
r = _node_https_probe('app_data', 'otel-collector', 4318, '/v1/traces', ca_pem,
|
||||
method='POST', headers=otlp_headers, body=otlp_body).get('result') or {}
|
||||
rc.add('MTLS-OTEL-1-NO-CERT', 'otel_mtls',
|
||||
'OTel Gateway 4318 rejects OTLP push without client cert',
|
||||
r.get('status') is None and bool(r.get('tlsError')),
|
||||
'TLS handshake error', f"status={r.get('status')} error={r.get('tlsError')}")
|
||||
|
||||
# 2. Foreign CA cert -> TLS reject
|
||||
r = _node_https_probe('app_data', 'otel-collector', 4318, '/v1/traces', ca_pem,
|
||||
method='POST', cert_pem=foreign_pair[0], key_pem=foreign_pair[1],
|
||||
headers=otlp_headers, body=otlp_body).get('result') or {}
|
||||
rc.add('MTLS-OTEL-2-FOREIGN-CA', 'otel_mtls',
|
||||
'OTel Gateway 4318 rejects foreign-CA client cert',
|
||||
r.get('status') is None and bool(r.get('tlsError')),
|
||||
'TLS handshake error', f"status={r.get('status')} error={r.get('tlsError')}")
|
||||
|
||||
# 3. Trusted-CA rogue-client -> 403
|
||||
r = _node_https_probe('app_data', 'otel-collector', 4318, '/v1/traces', ca_pem,
|
||||
method='POST', cert_pem=rogue_pair[0], key_pem=rogue_pair[1],
|
||||
headers=otlp_headers, body=otlp_body).get('result') or {}
|
||||
rc.add('MTLS-OTEL-3-ROGUE-CLIENT', 'otel_mtls',
|
||||
'OTel Gateway 4318 rejects trusted-CA rogue-client (SAN/CN allowlist)',
|
||||
r.get('status') == 403 or bool(r.get('tlsError')),
|
||||
'HTTP 403 (or TLS reject)', f"status={r.get('status')} error={r.get('tlsError')}")
|
||||
|
||||
# 4. Trusted-CA haproxy-lb -> 403
|
||||
r = _node_https_probe('app_data', 'otel-collector', 4318, '/v1/traces', ca_pem,
|
||||
method='POST', cert_pem=haproxy_pair[0], key_pem=haproxy_pair[1],
|
||||
headers=otlp_headers, body=otlp_body).get('result') or {}
|
||||
rc.add('MTLS-OTEL-4-LB-DENIED', 'otel_mtls',
|
||||
'OTel Gateway 4318 rejects trusted-CA haproxy-lb identity',
|
||||
r.get('status') == 403 or bool(r.get('tlsError')),
|
||||
'HTTP 403 (or TLS reject)', f"status={r.get('status')} error={r.get('tlsError')}")
|
||||
|
||||
# 5. Valid messenger-api -> 200
|
||||
r = _node_https_probe('app_data', 'otel-collector', 4318, '/v1/traces', ca_pem,
|
||||
method='POST', cert_pem=api_pair[0], key_pem=api_pair[1],
|
||||
headers=otlp_headers, body=otlp_body).get('result') or {}
|
||||
rc.add('MTLS-OTEL-5-API-OK', 'otel_mtls',
|
||||
'OTel Gateway 4318 accepts valid messenger-api identity',
|
||||
r.get('status') == 200, 'HTTP 200', f"status={r.get('status')} error={r.get('tlsError')}")
|
||||
|
||||
# 6. Valid messenger-worker -> 200
|
||||
r = _node_https_probe('app_data', 'otel-collector', 4318, '/v1/traces', ca_pem,
|
||||
method='POST', cert_pem=worker_pair[0], key_pem=worker_pair[1],
|
||||
headers=otlp_headers, body=otlp_body).get('result') or {}
|
||||
rc.add('MTLS-OTEL-6-WORKER-OK', 'otel_mtls',
|
||||
'OTel Gateway 4318 accepts valid messenger-worker identity',
|
||||
r.get('status') == 200, 'HTTP 200', f"status={r.get('status')} error={r.get('tlsError')}")
|
||||
|
||||
|
||||
def audit_datastores_and_observability(args, rc, ca_file, ca_pem, api_secrets,
|
||||
api_pair, rogue_pair, op_pair):
|
||||
# --- PostgreSQL (Link 3) ---
|
||||
pg_host_closed = common.tcp_port_closed('127.0.0.1', 5432)
|
||||
rc.add('TLS-PG-0-HOST-CLOSED', 'postgres_tls',
|
||||
'PostgreSQL port 5432 is not published on host',
|
||||
pg_host_closed, 'TCP refused', 'closed' if pg_host_closed else 'OPEN')
|
||||
|
||||
db_user = (api_secrets or {}).get('db_user', 'messenger_api')
|
||||
db_pass = (api_secrets or {}).get('db_password', '')
|
||||
if db_pass:
|
||||
nossl = _node_pg_probe(ca_pem, db_user, db_pass, ssl_mode='disable').get('result') or {}
|
||||
rc.add('TLS-PG-1-NOSSL-REJECTED', 'postgres_tls',
|
||||
'PostgreSQL rejects plaintext TCP connection (hostnossl reject)',
|
||||
nossl.get('connected') is False, 'connection rejected',
|
||||
f"connected={nossl.get('connected')} error={nossl.get('error')}")
|
||||
|
||||
badhost = _node_pg_probe(ca_pem, db_user, db_pass, ssl_mode='verify-full',
|
||||
servername='wrong-pg.local').get('result') or {}
|
||||
rc.add('TLS-PG-2-WRONG-HOST', 'postgres_tls',
|
||||
'PostgreSQL verify-full rejects hostname mismatch',
|
||||
badhost.get('connected') is False, 'TLS hostname error',
|
||||
f"connected={badhost.get('connected')} error={badhost.get('error')}")
|
||||
|
||||
okpg = _node_pg_probe(ca_pem, db_user, db_pass, ssl_mode='verify-full',
|
||||
servername='postgres').get('result') or {}
|
||||
ssl_active = bool((okpg.get('row') or {}).get('ssl'))
|
||||
rc.add('TLS-PG-3-VERIFY-FULL-OK', 'postgres_tls',
|
||||
'PostgreSQL verify-full TLS connection succeeds with pg_stat_ssl.ssl=true',
|
||||
okpg.get('connected') is True and ssl_active,
|
||||
'connected=True, ssl=True',
|
||||
f"connected={okpg.get('connected')} row={okpg.get('row')} error={okpg.get('error')}")
|
||||
else:
|
||||
rc.add('TLS-PG-3-VERIFY-FULL-OK', 'postgres_tls',
|
||||
'PostgreSQL verify-full TLS check (requires OpenBao api DB creds)',
|
||||
False, 'OpenBao api creds fetched', 'could not fetch secret/data/messenger/api')
|
||||
|
||||
# --- Redis (Link 11) ---
|
||||
redis_host_closed = common.tcp_port_closed('127.0.0.1', 6379)
|
||||
rc.add('TLS-REDIS-0-HOST-CLOSED', 'redis_tls',
|
||||
'Redis port 6379 is not published on host',
|
||||
redis_host_closed, 'TCP refused', 'closed' if redis_host_closed else 'OPEN')
|
||||
|
||||
r_plain = _node_redis_probe(ca_pem, use_tls=False).get('result') or {}
|
||||
rc.add('TLS-REDIS-1-PLAIN-REJECTED', 'redis_tls',
|
||||
'Redis plaintext TCP connection is rejected (--port 0)',
|
||||
r_plain.get('ok') is False, 'rejected', f"ok={r_plain.get('ok')} error={r_plain.get('error')}")
|
||||
|
||||
r_nocert = _node_redis_probe(ca_pem, use_tls=True).get('result') or {}
|
||||
rc.add('TLS-REDIS-2-NOCERT-REJECTED', 'redis_tls',
|
||||
'Redis TLS rejects connection without client certificate (mTLS)',
|
||||
r_nocert.get('ok') is False, 'TLS reject', f"ok={r_nocert.get('ok')} error={r_nocert.get('error')}")
|
||||
|
||||
r_user = (api_secrets or {}).get('redis_user', 'messenger_api')
|
||||
r_pass = (api_secrets or {}).get('redis_password', '')
|
||||
if r_pass:
|
||||
r_ok = _node_redis_probe(ca_pem, cert_pem=api_pair[0], key_pem=api_pair[1],
|
||||
username=r_user, password=r_pass, use_tls=True, cmd='ping').get('result') or {}
|
||||
rc.add('TLS-REDIS-3-MTLS-ACL-OK', 'redis_tls',
|
||||
'Redis mTLS + messenger_api ACL succeeds on PING',
|
||||
r_ok.get('ok') is True, 'PONG', f"ok={r_ok.get('ok')} reply={r_ok.get('reply')} error={r_ok.get('error')}")
|
||||
|
||||
r_cfg = _node_redis_probe(ca_pem, cert_pem=api_pair[0], key_pem=api_pair[1],
|
||||
username=r_user, password=r_pass, use_tls=True, cmd='config_get').get('result') or {}
|
||||
rc.add('TLS-REDIS-4-ACL-CONFIG-DENIED', 'redis_tls',
|
||||
'Redis ACL denies CONFIG GET to messenger_api (NOPERM)',
|
||||
r_cfg.get('ok') is False and 'NOPERM' in str(r_cfg.get('error', '')).upper(),
|
||||
'NOPERM', f"ok={r_cfg.get('ok')} error={r_cfg.get('error')}")
|
||||
else:
|
||||
rc.add('TLS-REDIS-3-MTLS-ACL-OK', 'redis_tls',
|
||||
'Redis mTLS + ACL check (requires OpenBao api Redis creds)',
|
||||
False, 'OpenBao api creds fetched', 'missing redis_password')
|
||||
|
||||
# --- MinIO S3 (Link 4) ---
|
||||
s3_url = args.s3_url.rstrip('/')
|
||||
try:
|
||||
ctx = common.make_ssl_context(ca_file=ca_file)
|
||||
resp = common.https_request('GET', s3_url + '/minio/health/live', ssl_ctx=ctx)
|
||||
rc.add('TLS-S3-1-HTTPS-OK', 's3_tls',
|
||||
'MinIO S3 serves HTTPS verified with local CA',
|
||||
resp['status'] == 200, 'HTTP 200', f"status={resp['status']}")
|
||||
anon = common.https_request('GET', s3_url + '/messenger-attachments/', ssl_ctx=ctx)
|
||||
rc.add('TLS-S3-2-ANON-DENIED', 's3_tls',
|
||||
'MinIO S3 rejects anonymous bucket access',
|
||||
anon['status'] == 403, 'HTTP 403', f"status={anon['status']}")
|
||||
except Exception as exc:
|
||||
rc.add('TLS-S3-1-HTTPS-OK', 's3_tls',
|
||||
'MinIO S3 serves HTTPS verified with local CA',
|
||||
False, 'HTTP 200', f'{type(exc).__name__}: {exc}')
|
||||
|
||||
# Plaintext HTTP to MinIO rejected
|
||||
s3_http = s3_url.replace('https://', 'http://', 1) + '/minio/health/live'
|
||||
try:
|
||||
resp = common.https_request('GET', s3_http)
|
||||
plain_rejected = resp['status'] >= 400
|
||||
rc.add('TLS-S3-3-PLAIN-REJECTED', 's3_tls',
|
||||
'MinIO S3 rejects plaintext HTTP',
|
||||
plain_rejected, 'HTTP 400 / protocol error', f"status={resp['status']}")
|
||||
except Exception as exc:
|
||||
rc.add('TLS-S3-3-PLAIN-REJECTED', 's3_tls',
|
||||
'MinIO S3 rejects plaintext HTTP',
|
||||
True, 'HTTP 400 / protocol error', f'{type(exc).__name__}')
|
||||
|
||||
# --- OpenBao (Link 9) ---
|
||||
bao_url = args.openbao_url.rstrip('/')
|
||||
try:
|
||||
ctx = common.make_ssl_context(ca_file=ca_file)
|
||||
resp = common.https_request('GET', bao_url + '/v1/sys/health', ssl_ctx=ctx)
|
||||
rc.add('TLS-BAO-1-HTTPS-OK', 'openbao_tls',
|
||||
'OpenBao serves HTTPS verified with local CA (initialized & unsealed)',
|
||||
resp['status'] == 200, 'HTTP 200', f"status={resp['status']}")
|
||||
except Exception as exc:
|
||||
rc.add('TLS-BAO-1-HTTPS-OK', 'openbao_tls',
|
||||
'OpenBao serves HTTPS verified with local CA',
|
||||
False, 'HTTP 200', f'{type(exc).__name__}: {exc}')
|
||||
|
||||
# --- Prometheus / Grafana / Loki / Tempo / HAProxy stats (Links 7, 8, 10) ---
|
||||
prom_url = args.prometheus_url.rstrip('/')
|
||||
prom_pw = common.read_secret_file('prometheus_operator_password')
|
||||
if prom_pw:
|
||||
rc.register_secret(prom_pw)
|
||||
# Prometheus without client cert fails TLS
|
||||
try:
|
||||
ctx = common.make_ssl_context(ca_file=ca_file)
|
||||
resp = common.https_request('GET', prom_url + '/-/ready', ssl_ctx=ctx)
|
||||
rc.add('TLS-PROM-1-NOCERT-REJECTED', 'observability_tls',
|
||||
'Prometheus rejects HTTPS client without mTLS certificate',
|
||||
resp['status'] in (401, 403), 'TLS error or 401/403', f"status={resp['status']}")
|
||||
except Exception as exc:
|
||||
rc.add('TLS-PROM-1-NOCERT-REJECTED', 'observability_tls',
|
||||
'Prometheus rejects HTTPS client without mTLS certificate',
|
||||
True, 'TLS handshake error', f'{type(exc).__name__}')
|
||||
|
||||
# Prometheus with operator mTLS cert + Basic Auth succeeds
|
||||
if op_pair[0] and op_pair[1] and prom_pw:
|
||||
try:
|
||||
op_crt_p, op_key_p = common.operator_cert_pair(args.operator_dir)
|
||||
ctx = common.make_ssl_context(ca_file=ca_file, cert_file=op_crt_p, key_file=op_key_p)
|
||||
unauth = common.https_request('GET', prom_url + '/api/v1/query?query=up', ssl_ctx=ctx)
|
||||
rc.add('TLS-PROM-2-NOAUTH-401', 'observability_tls',
|
||||
'Prometheus requires Basic Auth even with valid mTLS cert',
|
||||
unauth['status'] == 401, 'HTTP 401', f"status={unauth['status']}")
|
||||
|
||||
hdr = common.basic_auth_header('operator', prom_pw)
|
||||
okp = common.https_request('GET', prom_url + '/api/v1/query?query=up',
|
||||
headers=hdr, ssl_ctx=ctx)
|
||||
up_jobs = {}
|
||||
if okp['status'] == 200:
|
||||
payload = json.loads(okp['body'].decode('utf-8'))
|
||||
for row in payload.get('data', {}).get('result', []):
|
||||
up_jobs[row['metric'].get('job')] = row['value'][1]
|
||||
expected_jobs = ('prometheus', 'otel-collector', 'haproxy', 'rabbitmq', 'loki', 'tempo')
|
||||
all_up = okp['status'] == 200 and all(up_jobs.get(j) == '1' for j in expected_jobs)
|
||||
rc.add('TLS-PROM-3-MTLS-SCRAPES-UP', 'observability_tls',
|
||||
'Prometheus mTLS + operator auth succeeds and all 6 mTLS scrape targets are up=1',
|
||||
all_up, 'HTTP 200 and all 6 jobs up=1', f'status={okp["status"]} up={up_jobs}')
|
||||
except Exception as exc:
|
||||
rc.add('TLS-PROM-3-MTLS-SCRAPES-UP', 'observability_tls',
|
||||
'Prometheus mTLS + operator auth succeeds',
|
||||
False, 'HTTP 200', f'{type(exc).__name__}: {exc}')
|
||||
|
||||
# Grafana HTTPS + auth + datasource TLS checks
|
||||
graf_url = args.grafana_url.rstrip('/')
|
||||
graf_pw = common.read_secret_file('grafana_admin_password')
|
||||
if graf_pw:
|
||||
rc.register_secret(graf_pw)
|
||||
try:
|
||||
ctx = common.make_ssl_context(ca_file=ca_file)
|
||||
g_unauth = common.https_request('GET', graf_url + '/api/datasources', ssl_ctx=ctx)
|
||||
rc.add('TLS-GRAFANA-1-UNAUTH-401', 'observability_tls',
|
||||
'Grafana HTTPS rejects unauthenticated datasource API access',
|
||||
g_unauth['status'] in (401, 403), 'HTTP 401/403', f"status={g_unauth['status']}")
|
||||
if graf_pw:
|
||||
hdr = common.basic_auth_header('admin', graf_pw)
|
||||
g_ds = common.https_request('GET', graf_url + '/api/datasources', headers=hdr, ssl_ctx=ctx)
|
||||
ds_ok = False
|
||||
ds_tls_flags = {}
|
||||
if g_ds['status'] == 200:
|
||||
items = json.loads(g_ds['body'].decode('utf-8'))
|
||||
for item in items:
|
||||
uid = item.get('uid') or item.get('name')
|
||||
jd = item.get('jsonData') or {}
|
||||
ds_tls_flags[uid] = {
|
||||
'url': item.get('url'),
|
||||
'tlsSkipVerify': jd.get('tlsSkipVerify', False),
|
||||
'tlsAuth': jd.get('tlsAuth'),
|
||||
}
|
||||
ds_ok = bool(ds_tls_flags) and all(
|
||||
str(v.get('url', '')).startswith('https://') and v.get('tlsSkipVerify') is False
|
||||
for v in ds_tls_flags.values()
|
||||
)
|
||||
rc.add('TLS-GRAFANA-2-DS-TLS-VERIFY', 'observability_tls',
|
||||
'Grafana datasources use HTTPS with tlsSkipVerify=false',
|
||||
ds_ok, 'all datasources https:// & tlsSkipVerify=false',
|
||||
json.dumps(ds_tls_flags))
|
||||
except Exception as exc:
|
||||
rc.add('TLS-GRAFANA-1-UNAUTH-401', 'observability_tls',
|
||||
'Grafana HTTPS check', False, 'HTTPS reachable', f'{type(exc).__name__}: {exc}')
|
||||
|
||||
# Internal obs_net mTLS checks on Loki & Tempo
|
||||
prom_crt_p, prom_key_p = common.service_client_pair('prometheus')
|
||||
prom_pair = _load_pem_pair(prom_crt_p, prom_key_p)
|
||||
for svc, port in (('loki', 3100), ('tempo', 3200)):
|
||||
no_cert = _node_https_probe('obs_net', svc, port, '/ready', ca_pem).get('result') or {}
|
||||
rc.add(f'TLS-{svc.upper()}-1-NOCERT-REJECTED', 'observability_tls',
|
||||
f'{svc}:{port} rejects HTTPS without client certificate',
|
||||
no_cert.get('status') is None and bool(no_cert.get('tlsError')),
|
||||
'TLS handshake error',
|
||||
f"status={no_cert.get('status')} error={no_cert.get('tlsError')}")
|
||||
with_cert = _node_https_probe('obs_net', svc, port, '/ready', ca_pem,
|
||||
cert_pem=prom_pair[0], key_pem=prom_pair[1]).get('result') or {}
|
||||
rc.add(f'TLS-{svc.upper()}-2-MTLS-OK', 'observability_tls',
|
||||
f'{svc}:{port} accepts valid mTLS client certificate',
|
||||
with_cert.get('status') == 200, 'HTTP 200',
|
||||
f"status={with_cert.get('status')} error={with_cert.get('tlsError')}")
|
||||
|
||||
# OTel Gateway :8888 metrics mTLS allowlist (rogue denied, prometheus allowed)
|
||||
r_rogue = _node_https_probe('obs_net', 'otel-collector', 8888, '/metrics', ca_pem,
|
||||
cert_pem=rogue_pair[0], key_pem=rogue_pair[1]).get('result') or {}
|
||||
r_prom = _node_https_probe('obs_net', 'otel-collector', 8888, '/metrics', ca_pem,
|
||||
cert_pem=prom_pair[0], key_pem=prom_pair[1]).get('result') or {}
|
||||
rc.add('TLS-OTEL-METRICS-MTLS', 'observability_tls',
|
||||
'OTel Gateway :8888 allows prometheus cert and denies rogue-client',
|
||||
(r_rogue.get('status') == 403 or bool(r_rogue.get('tlsError'))) and r_prom.get('status') == 200,
|
||||
'rogue=403/TLS-err, prometheus=200',
|
||||
f"rogue={r_rogue.get('status') or r_rogue.get('tlsError')}, prometheus={r_prom.get('status')}")
|
||||
|
||||
# HAProxy :8404 /stats unauth rejected
|
||||
try:
|
||||
ctx = common.make_ssl_context(ca_file=ca_file)
|
||||
st_unauth = common.https_request('GET', 'https://localhost:8404/stats', ssl_ctx=ctx)
|
||||
rc.add('TLS-HAPROXY-STATS-AUTH', 'observability_tls',
|
||||
'HAProxy HTTPS :8404/stats rejects unauthenticated request',
|
||||
st_unauth['status'] in (401, 403), 'HTTP 401/403', f"status={st_unauth['status']}")
|
||||
except Exception as exc:
|
||||
rc.add('TLS-HAPROXY-STATS-AUTH', 'observability_tls',
|
||||
'HAProxy HTTPS :8404/stats rejects unauthenticated request',
|
||||
True, 'HTTP 401/403 or mTLS reject', f'{type(exc).__name__}')
|
||||
|
||||
|
||||
def main(argv=None):
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
common.add_common_args(parser)
|
||||
args = parser.parse_args(argv)
|
||||
|
||||
rc = common.ResultCollector('lab7-tls-audit')
|
||||
ca_file = Path(args.ca_file)
|
||||
ca_pem = _read_text(ca_file)
|
||||
if not ca_pem:
|
||||
raise common.Failure(f'CA file not found: {ca_file}')
|
||||
|
||||
foreign_ca, foreign_crt, foreign_key = common.foreign_ca_and_client(args.operator_dir)
|
||||
rogue_crt, rogue_key = common.rogue_cert_pair(args.operator_dir)
|
||||
op_crt, op_key = common.operator_cert_pair(args.operator_dir)
|
||||
hap_crt, hap_key = common.haproxy_client_pair()
|
||||
api_crt, api_key = common.service_client_pair('api')
|
||||
wrk_crt, wrk_key = common.service_client_pair('worker')
|
||||
|
||||
foreign_pair = _load_pem_pair(foreign_crt, foreign_key)
|
||||
rogue_pair = _load_pem_pair(rogue_crt, rogue_key)
|
||||
op_pair = _load_pem_pair(op_crt, op_key)
|
||||
haproxy_pair = _load_pem_pair(hap_crt, hap_key)
|
||||
api_pair = _load_pem_pair(api_crt, api_key)
|
||||
worker_pair = _load_pem_pair(wrk_crt, wrk_key)
|
||||
|
||||
audit_external_tls(args, rc, ca_file, foreign_ca)
|
||||
audit_lb_to_api_mtls(rc, ca_pem, foreign_pair, rogue_pair, worker_pair, haproxy_pair)
|
||||
audit_broker_mtls(rc, ca_pem, foreign_pair, rogue_pair, haproxy_pair, api_pair, worker_pair)
|
||||
audit_otel_mtls(rc, ca_pem, foreign_pair, rogue_pair, haproxy_pair, api_pair, worker_pair)
|
||||
|
||||
api_secrets = _fetch_api_secrets(args.openbao_url, ca_file, api_crt, api_key, rc)
|
||||
audit_datastores_and_observability(
|
||||
args, rc, ca_file, ca_pem, api_secrets, api_pair, rogue_pair, op_pair,
|
||||
)
|
||||
|
||||
rc.summary = {
|
||||
'base_url': args.base_url,
|
||||
'ca_file': str(ca_file),
|
||||
}
|
||||
(json_path, txt_path), rep = rc.save(args.output_dir, 'tls-audit')
|
||||
print(f"Report written: {json_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 common.Failure as exc:
|
||||
print('FAIL:', common.redact_text(str(exc)), file=sys.stderr)
|
||||
sys.exit(1)
|
||||
Executable
+982
@@ -0,0 +1,982 @@
|
||||
#!/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 filename 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,
|
||||
};
|
||||
async function tryOp(vhost, fn) {
|
||||
let conn = null;
|
||||
try {
|
||||
conn = await amqp.connect({
|
||||
protocol: 'amqps', hostname: 'broker', port: 5671, vhost,
|
||||
credentials: amqp.credentials.external(),
|
||||
}, 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',
|
||||
credentials: amqp.credentials.external(),
|
||||
}, {
|
||||
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,
|
||||
});
|
||||
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 name) 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)
|
||||
Reference in New Issue
Block a user