forked from mtusi2026/mtusi2026lab7
Добавить стенд лабораторной 7 с mTLS, OpenBao и least privilege worker.
Закрывает обязательный минимум и трек 1: ротация leaf и секрета, sealed OpenBao и сохранность queued-задачи.
This commit is contained in:
@@ -0,0 +1,109 @@
|
||||
"""Terminate TLS in the API process and allow only the LB leaf serials."""
|
||||
import asyncio
|
||||
import ssl
|
||||
|
||||
from app.settings import require
|
||||
|
||||
|
||||
def _serials():
|
||||
settings = require()
|
||||
try:
|
||||
raw = open(settings.allowed_serials_file, "r", encoding="utf-8").read()
|
||||
except OSError:
|
||||
return set()
|
||||
found = set()
|
||||
for line in raw.splitlines():
|
||||
item = line.strip().replace(":", "")
|
||||
if not item or item.startswith("#"):
|
||||
continue
|
||||
try:
|
||||
found.add(format(int(item, 16), "X"))
|
||||
except ValueError:
|
||||
continue
|
||||
return found
|
||||
|
||||
|
||||
def _allowed(sslobj):
|
||||
settings = require()
|
||||
cert = sslobj.getpeercert()
|
||||
if not cert:
|
||||
return False
|
||||
names = [value for kind, value in cert.get("subjectAltName", ()) if kind == "DNS"]
|
||||
if settings.allowed_client_san not in names:
|
||||
return False
|
||||
serial = str(cert.get("serialNumber") or "")
|
||||
try:
|
||||
normalized = format(int(serial.replace(":", ""), 16), "X")
|
||||
except ValueError:
|
||||
return False
|
||||
return normalized in _serials()
|
||||
|
||||
|
||||
async def _pipe(reader, writer):
|
||||
try:
|
||||
while True:
|
||||
data = await reader.read(65536)
|
||||
if not data:
|
||||
break
|
||||
writer.write(data)
|
||||
await writer.drain()
|
||||
except Exception:
|
||||
pass
|
||||
finally:
|
||||
try:
|
||||
writer.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
async def _reject(writer):
|
||||
body = b'{"error":"client_identity_rejected"}'
|
||||
head = (
|
||||
b"HTTP/1.1 403 Forbidden\r\n"
|
||||
b"Content-Type: application/json\r\n"
|
||||
b"Content-Length: " + str(len(body)).encode("ascii") + b"\r\n"
|
||||
b"Connection: close\r\n\r\n"
|
||||
)
|
||||
writer.write(head + body)
|
||||
try:
|
||||
await writer.drain()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
writer.close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
async def _handle(reader, writer):
|
||||
sslobj = writer.get_extra_info("ssl_object")
|
||||
if sslobj is None or not _allowed(sslobj):
|
||||
await _reject(writer)
|
||||
return
|
||||
try:
|
||||
local_reader, local_writer = await asyncio.open_connection("127.0.0.1", require().local_port)
|
||||
except Exception:
|
||||
writer.close()
|
||||
return
|
||||
await asyncio.gather(_pipe(reader, local_writer), _pipe(local_reader, writer))
|
||||
|
||||
|
||||
def _context():
|
||||
settings = require()
|
||||
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
ctx.load_cert_chain(settings.tls_cert, settings.tls_key)
|
||||
ctx.load_verify_locations(settings.tls_ca)
|
||||
ctx.verify_mode = ssl.CERT_REQUIRED
|
||||
ctx.check_hostname = False
|
||||
return ctx
|
||||
|
||||
|
||||
async def _serve():
|
||||
server = await asyncio.start_server(_handle, "0.0.0.0", require().mtls_port, ssl=_context())
|
||||
async with server:
|
||||
await server.serve_forever()
|
||||
|
||||
|
||||
def serve_forever():
|
||||
asyncio.run(_serve())
|
||||
Reference in New Issue
Block a user