forked from mtusi2026/mtusi2026lab7
106 lines
4.5 KiB
Python
106 lines
4.5 KiB
Python
"""Bounded TLS transport boundary. Plaintext listeners/targets are loopback only.
|
|
|
|
Trust/leaf contexts are cached for at most one second. Connections live at most
|
|
60 seconds, bounding revocation and certificate rollover propagation to 61 seconds.
|
|
"""
|
|
import asyncio
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import signal
|
|
import ssl
|
|
import time
|
|
|
|
IDENTITY = Path(os.environ.get('IDENTITY_DIR', '/identity'))
|
|
TRUST = Path(os.environ.get('TRUST_DIR', '/trust'))
|
|
_contexts = {}
|
|
|
|
|
|
def context(server=False):
|
|
cached = _contexts.get(server)
|
|
if cached and time.monotonic() < cached[0]:
|
|
return cached[1]
|
|
ctx = ssl.create_default_context(ssl.Purpose.CLIENT_AUTH if server else ssl.Purpose.SERVER_AUTH,
|
|
cafile=str(TRUST/'bundle.pem'))
|
|
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
|
ctx.load_cert_chain(IDENTITY/'cert.pem', IDENTITY/'key.pem')
|
|
ctx.verify_mode = ssl.CERT_REQUIRED
|
|
ctx.verify_flags |= ssl.VERIFY_CRL_CHECK_LEAF
|
|
if server:
|
|
ctx.options |= ssl.OP_NO_TICKET
|
|
_contexts[server] = (time.monotonic() + 1, ctx)
|
|
return ctx
|
|
|
|
|
|
async def pump(reader, writer):
|
|
while chunk := await reader.read(16384):
|
|
writer.write(chunk)
|
|
await writer.drain()
|
|
|
|
|
|
async def serve(routes):
|
|
slots = asyncio.Semaphore(64)
|
|
tasks = set()
|
|
|
|
async def handle(reader, writer, route):
|
|
peer = None
|
|
try:
|
|
async with asyncio.timeout(60):
|
|
if slots.locked(): return
|
|
async with slots:
|
|
if route['mode'] == 'server':
|
|
# Do not yield before start_tls: a raw StreamReader may
|
|
# consume ClientHello bytes while awaiting other work.
|
|
tls_context = context(True)
|
|
await writer.start_tls(tls_context, ssl_handshake_timeout=3)
|
|
cert = writer.get_extra_info('ssl_object').getpeercert()
|
|
names = {value for kind, value in cert.get('subjectAltName', ()) if kind == 'DNS'}
|
|
if not names.intersection(route['allow']):
|
|
return
|
|
target, peer = await asyncio.wait_for(asyncio.open_connection('127.0.0.1', route['target']), 3)
|
|
else:
|
|
tls_context = context()
|
|
target, peer = await asyncio.wait_for(asyncio.open_connection(
|
|
route['host'], route['target'], ssl=tls_context, server_hostname=route['host'],
|
|
ssl_handshake_timeout=3), 5)
|
|
transfers = [asyncio.create_task(pump(reader, peer)), asyncio.create_task(pump(target, writer))]
|
|
try:
|
|
await asyncio.wait(transfers, return_when=asyncio.FIRST_COMPLETED)
|
|
finally:
|
|
for task in transfers: task.cancel()
|
|
await asyncio.gather(*transfers, return_exceptions=True)
|
|
except (OSError, ssl.SSLError, TimeoutError, ConnectionError):
|
|
# No credentials, payloads or untrusted exception text in logs.
|
|
pass
|
|
finally:
|
|
writer.close()
|
|
if peer: peer.close()
|
|
|
|
def accept(reader, writer, route):
|
|
# connection_made calls this synchronously. Pause before scheduling the
|
|
# coroutine: otherwise StreamReader can consume ClientHello while that
|
|
# coroutine waits in the event-loop queue. start_tls resumes the transport
|
|
# after installing SSLProtocol. Outgoing local plaintext is unaffected.
|
|
if route['mode'] == 'server':
|
|
writer.transport.pause_reading()
|
|
if len(tasks) >= 96:
|
|
writer.close(); return
|
|
task = asyncio.create_task(handle(reader, writer, route))
|
|
tasks.add(task); task.add_done_callback(tasks.discard)
|
|
|
|
servers = []
|
|
for route in routes:
|
|
host = '0.0.0.0' if route['mode'] == 'server' else '127.0.0.1'
|
|
servers.append(await asyncio.start_server(lambda r,w,v=route: accept(r,w,v),host,route['listen'],backlog=64))
|
|
stop = asyncio.Event()
|
|
loop = asyncio.get_running_loop()
|
|
for sig in (signal.SIGTERM, signal.SIGINT): loop.add_signal_handler(sig, stop.set)
|
|
await stop.wait()
|
|
for server in servers: server.close()
|
|
for task in tasks: task.cancel()
|
|
await asyncio.gather(*tasks, return_exceptions=True)
|
|
|
|
|
|
if __name__ == '__main__':
|
|
asyncio.run(serve(json.loads(Path(os.environ.get('PROXY_CONFIG','/proxy.json')).read_text())))
|