Files
mtusi2026lab7/scripts/lab7/tls_audit.py
T

908 lines
42 KiB
Python
Executable File

#!/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)