Files
mtusi2026lab7/infra/security/tls_proxy.py
2026-11-24 12:20:21 +03:00

84 lines
4.0 KiB
Python

"""Bounded mTLS TCP proxy. The backend shares this network namespace and
binds only loopback. Certificate chain AND DNS SAN role are mandatory.
Each new connection reloads leaf and denylist: no session resumption cache.
"""
import os, socket, ssl, threading, time, json
from pathlib import Path
ROLE=os.environ['PROXY_ROLE']
ALLOWED=set(os.environ['ALLOWED_IDENTITIES'].split(','))
PORTS=[tuple(map(int,p.split(':'))) for p in os.environ['PORT_MAP'].split(',')]
PER_PORT=json.loads(os.environ.get("PORT_IDENTITIES","{}"))
SLOTS=threading.BoundedSemaphore(64)
def serve(conn,upstream,port):
try:
conn.settimeout(5)
ctx=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);ctx.minimum_version=ssl.TLSVersion.TLSv1_2
ctx.load_cert_chain('/run/tls/cert.crt','/run/tls/key.key');ctx.load_verify_locations('/run/ca/ca.crt');ctx.verify_mode=ssl.CERT_REQUIRED
ctx.options |= ssl.OP_NO_TICKET
with ctx.wrap_socket(conn,server_side=True) as client:
cert=client.getpeercert();names={v for k,v in cert.get('subjectAltName',[]) if k=='DNS'}
revoked=Path('/run/ca/revoked-serials').read_text().lower().split()
if not names.intersection(set(PER_PORT.get(str(port),list(ALLOWED)))) or cert.get('serialNumber','').lower().lstrip('0') in [s.lstrip('0') for s in revoked]:return
principal=next(iter(names.intersection(set(PER_PORT.get(str(port),list(ALLOWED))))))
with socket.create_connection(('127.0.0.1',upstream),timeout=3) as backend:
client.settimeout(75);backend.settimeout(75)
# Two blocking directions; finite socket timeouts, bounded connections.
def copy(a,b):
try:
while True:
data=a.recv(32768)
if not data:break
b.sendall(data)
except (OSError,ssl.SSLError):pass
finally:
try:b.shutdown(socket.SHUT_WR)
except OSError:pass
def redis_commands():
try:
stream=client.makefile('rb')
while True:
header=stream.readline(128)
if not header:break
if not header.startswith(b'*'):break
count=int(header[1:]);args=[];wire=bytearray(header)
if not 1<=count<=64:break
for _ in range(count):
size=stream.readline(128)
if not size.startswith(b'$'):raise ValueError('invalid RESP')
n=int(size[1:])
if not 0<=n<=1048576:raise ValueError('oversized command')
value=stream.read(n+2)
if len(value)!=n+2:raise ValueError('truncated RESP')
args.append(value[:-2]);wire.extend(size);wire.extend(value)
op=args[0].lower()
allowed={b'ping',b'hello',b'auth',b'client'}
if principal=='worker':allowed|={b'xgroup',b'xautoclaim',b'xreadgroup',b'xack',b'xdel',b'xadd'}
if principal=='dispatcher':allowed|={b'xadd'}
if principal!='operator':
if op not in allowed:break
if op==b'auth' and (len(args)!=3 or args[1].decode()!=principal):break
if op==b'hello' and b'auth' in [a.lower() for a in args]:
i=[a.lower() for a in args].index(b'auth')
if args[i+1].decode()!=principal:break
if op==b'xadd':
expected=b'attachment.invalid.dlq' if principal=='worker' else b'attachment.jobs.v1'
if len(args)<2 or args[1]!=expected:break
backend.sendall(wire)
except (OSError,ValueError,IndexError,UnicodeError):pass
finally:
try:backend.shutdown(socket.SHUT_WR)
except OSError:pass
t=threading.Thread(target=redis_commands if ROLE=='broker' else copy,args=() if ROLE=='broker' else (client,backend),daemon=True)
t.start();copy(backend,client);t.join(timeout=1)
except (OSError,ssl.SSLError):conn.close()
finally:SLOTS.release()
def listen(port,upstream):
with socket.socket() as s:
s.setsockopt(socket.SOL_SOCKET,socket.SO_REUSEADDR,1);s.bind(('0.0.0.0',port));s.listen(32)
while True:
conn,_=s.accept()
if not SLOTS.acquire(blocking=False):conn.close();continue
threading.Thread(target=serve,args=(conn,upstream,port),daemon=True).start()
for port,upstream in PORTS:threading.Thread(target=listen,args=(port,upstream),daemon=True).start()
while True:time.sleep(3600)