142 lines
5.5 KiB
Python
142 lines
5.5 KiB
Python
"""Run inside the one-shot TLS audit container. Only checks the local lab."""
|
|
from contextlib import contextmanager
|
|
import http.client
|
|
import socket
|
|
import ssl
|
|
import struct
|
|
import time
|
|
|
|
|
|
def context(identity=None, trusted=True):
|
|
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
|
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
|
if trusted:
|
|
ctx.load_verify_locations('/pki/ca.crt')
|
|
if identity:
|
|
ctx.load_cert_chain(f'/pki/{identity}.crt', f'/pki/{identity}.key')
|
|
return ctx
|
|
|
|
|
|
@contextmanager
|
|
def tls(host, port, identity=None, *, target=None, sni=None, trusted=True, pg=False, alpn=None):
|
|
ctx = context(identity, trusted)
|
|
if alpn:
|
|
ctx.set_alpn_protocols([alpn])
|
|
with socket.create_connection((target or host, port), timeout=5) as raw:
|
|
if pg:
|
|
raw.sendall(struct.pack('!II', 8, 80877103))
|
|
assert raw.recv(1) == b'S', 'PostgreSQL refused TLS negotiation'
|
|
with ctx.wrap_socket(raw, server_hostname=sni or host) as conn:
|
|
assert conn.version() in ('TLSv1.2', 'TLSv1.3')
|
|
if alpn:
|
|
assert conn.selected_alpn_protocol() == alpn
|
|
yield conn
|
|
|
|
|
|
def request(conn, host, path, body=None):
|
|
method = 'POST' if body is not None else 'GET'
|
|
body = body or b''
|
|
conn.sendall(
|
|
f'{method} {path} HTTP/1.1\r\nHost: {host}\r\nConnection: close\r\n'
|
|
f'Content-Type: application/json\r\nContent-Length: {len(body)}\r\n\r\n'.encode() + body
|
|
)
|
|
response = http.client.HTTPResponse(conn)
|
|
response.begin()
|
|
status = response.status
|
|
response.close()
|
|
return status
|
|
|
|
|
|
def tls_refused(probe):
|
|
try:
|
|
probe()
|
|
except ssl.SSLError as error:
|
|
# Distinguish an explicit certificate/TLS rejection from a broken route.
|
|
assert error.reason and ('ALERT' in error.reason or 'CERTIFICATE' in error.reason), error.reason
|
|
else:
|
|
raise AssertionError('TLS peer unexpectedly accepted the connection')
|
|
|
|
|
|
def api(target, identity, **options):
|
|
with tls('api', 8080, identity, target=target, **options) as conn:
|
|
return request(conn, 'api', '/health/live')
|
|
|
|
|
|
def otlp(identity, **options):
|
|
with tls('otel-gateway', 4318, identity, **options) as conn:
|
|
return request(conn, 'otel-gateway', '/v1/traces', b'{}')
|
|
|
|
|
|
def redis_command(host, identity, command, **options):
|
|
with tls(host, 6379, identity, **options) as conn:
|
|
args = [b'*' + str(len(command)).encode()]
|
|
for word in command:
|
|
data = word.encode()
|
|
args.extend((b'$' + str(len(data)).encode(), data))
|
|
conn.sendall(b'\r\n'.join(args) + b'\r\n')
|
|
with conn.makefile('rb') as reply:
|
|
line = reply.readline(1024)
|
|
assert line, 'broker closed without an explicit decision'
|
|
return line
|
|
|
|
|
|
def main():
|
|
replicas = {info[4][0] for info in socket.getaddrinfo('api', 8080, type=socket.SOCK_STREAM)}
|
|
assert len(replicas) >= 2, 'start at least two API replicas'
|
|
for target in sorted(replicas):
|
|
assert api(target, 'lb') == 200
|
|
tls_refused(lambda: api(target, 'worker'))
|
|
tls_refused(lambda: api(target, None))
|
|
tls_refused(lambda: api(target, 'lb', sni='invalid.messenger.local'))
|
|
tls_refused(lambda: api(target, 'lb', trusted=False))
|
|
print('PASS LB/API: both replicas, wrong same-CA identity, missing cert, hostname and CA checks')
|
|
|
|
for identity in ('api', 'worker'):
|
|
assert otlp(identity) == 200
|
|
tls_refused(lambda: otlp('lb'))
|
|
tls_refused(lambda: otlp(None))
|
|
tls_refused(lambda: otlp('api', trusted=False))
|
|
print('PASS Collector: mTLS and same-CA identity rejection')
|
|
|
|
for identity in ('api', 'worker', 'health'):
|
|
assert redis_command('broker', identity, ['PING']).startswith(b'+PONG')
|
|
assert redis_command('broker', 'lb', ['PING']).startswith(b'-NOAUTH')
|
|
assert redis_command('broker', 'lb', ['AUTH', 'api.messenger.local', 'invalid']).startswith(b'-WRONGPASS')
|
|
assert redis_command('broker', 'api', ['XRANGE','attachments:v1','-','+','COUNT','1']).startswith(b'-NOPERM')
|
|
assert redis_command('broker', 'worker', ['XADD','attachments:v1','0-0','probe','denied']).startswith(b'-NOPERM')
|
|
tls_refused(lambda: redis_command('broker', None, ['PING']))
|
|
# With TLS the unknown CN completes the handshake, then Redis denies commands.
|
|
print('PASS broker: missing certificate, wrong same-CA identity and opposite-role ACLs')
|
|
|
|
with tls('postgres', 5432, pg=True):
|
|
pass
|
|
assert redis_command('redis', None, ['PING']).startswith(b'+PONG')
|
|
for host, port in [
|
|
('lb', 8443), ('minio', 9000), ('bao', 8200), ('loki', 3100),
|
|
('tempo', 3200), ('prometheus', 9090), ('grafana', 3000),
|
|
('otel-gateway', 8889),
|
|
]:
|
|
with tls(host, port):
|
|
pass
|
|
with tls('tempo', 4317, alpn='h2'):
|
|
pass
|
|
for port in (14318, 18888, 18889):
|
|
try:
|
|
with socket.create_connection(('otel-gateway', port), timeout=2):
|
|
raise AssertionError('Collector loopback listener was reachable from another container')
|
|
except ConnectionRefusedError:
|
|
pass
|
|
for path in ('/metrics', '/collector-metrics'):
|
|
for attempt in range(10):
|
|
with tls('otel-gateway', 8889) as conn:
|
|
if request(conn, 'otel-gateway', path) == 200:
|
|
break
|
|
time.sleep(1)
|
|
else:
|
|
raise AssertionError('verified metrics scrape endpoint did not return HTTP 200')
|
|
print('PASS TLS matrix: ingress, DB, cache, S3, Bao, OTLP, scrape and telemetry backends')
|
|
|
|
|
|
if __name__ == '__main__':
|
|
main()
|