Выполнение лабораторной работы номер 7
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,54 @@
|
||||
"""TLS termination restricted by verified client identity; private loopback upstream."""
|
||||
import asyncio
|
||||
import os
|
||||
import ssl
|
||||
import hashlib
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
async def pipe(source,destination):
|
||||
try:
|
||||
while data:=await source.read(65536):
|
||||
destination.write(data)
|
||||
await destination.drain()
|
||||
finally:
|
||||
destination.close()
|
||||
|
||||
|
||||
async def main():
|
||||
allowed=set(filter(None,os.getenv('TLS_ALLOWED_IDENTITIES','').split(',')))
|
||||
context=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER)
|
||||
context.minimum_version=ssl.TLSVersion.TLSv1_2
|
||||
context.load_cert_chain('/tls/tls.crt','/tls/tls.key')
|
||||
if allowed:
|
||||
context.load_verify_locations('/ca/ca.crt')
|
||||
context.verify_mode=ssl.CERT_REQUIRED
|
||||
|
||||
async def handle(reader,writer):
|
||||
try:
|
||||
if allowed:
|
||||
cert=writer.get_extra_info('peercert') or {}
|
||||
identities={value for kind,value in cert.get('subjectAltName',()) if kind=='DNS'}
|
||||
if not identities.intersection(allowed):
|
||||
return
|
||||
pins=Path('/pins')
|
||||
if pins.is_dir():
|
||||
fingerprint=hashlib.sha256(writer.get_extra_info('ssl_object').getpeercert(binary_form=True)).digest()
|
||||
trusted={hashlib.sha256(ssl.PEM_cert_to_DER_cert((pins/f'{identity}.crt').read_text())).digest()
|
||||
for identity in identities.intersection(allowed) if (pins/f'{identity}.crt').is_file()}
|
||||
if fingerprint not in trusted:
|
||||
return
|
||||
upstream,output=await asyncio.open_connection('127.0.0.1',int(os.environ['TLS_BACKEND_PORT']))
|
||||
await asyncio.gather(pipe(reader,output),pipe(upstream,writer),return_exceptions=True)
|
||||
except (OSError,ssl.SSLError):
|
||||
pass
|
||||
finally:
|
||||
writer.close()
|
||||
|
||||
server=await asyncio.start_server(handle,'0.0.0.0',int(os.environ['TLS_LISTEN_PORT']),ssl=context,ssl_handshake_timeout=5)
|
||||
async with server:
|
||||
await server.serve_forever()
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
asyncio.run(main())
|
||||
Reference in New Issue
Block a user