[+] lab7
Grade 3 secure application acceptance / secure (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Xabenskie
2026-11-30 09:09:57 +03:00
parent 20afc2c790
commit 4eca49fe3d
149 changed files with 68317 additions and 58 deletions
+123
View File
@@ -0,0 +1,123 @@
"""Real TLS sockets and locally generated certificates, no verification bypass."""
import asyncio
import json
from pathlib import Path
import ssl
import subprocess
import tempfile
import unittest
from messenger import tls_gateway
BASE=Path('/security-tests')
if not BASE.exists(): BASE=Path(__file__).resolve().parents[1]/'secrets'
class GatewayTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
self.methods=[]
async def reply(reader,writer):
try:
while True:
lines=[]
while True:
line=await reader.readline()
if not line: break
lines.append(line)
if not line.strip(): break
if not lines: break
headers=b''.join(lines)
self.methods.append(headers.split(b' ',1)[0].decode())
writer.write(b'HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok');await writer.drain()
if b'connection: close' in headers.lower(): break
finally: writer.close();await writer.wait_closed()
self.backend=await asyncio.start_server(reply,'127.0.0.1',0)
self.tmp=tempfile.TemporaryDirectory()
self.revoked=Path(self.tmp.name)/'revoked.json';self.revoked.write_text('[]')
config={'host':'127.0.0.1','port':0,'upstream_port':self.backend.sockets[0].getsockname()[1],
'ca':str(BASE/'trust/ca.crt'),'cert':str(BASE/'pki/api/tls.crt'),'key':str(BASE/'pki/api/tls.key'),
'alpn':['h2','http/1.1'],'allowed_clients':['lb','grafana'],'read_only_clients':['grafana'],'protocol':'http','revoked':str(self.revoked)}
self.server=await tls_gateway.listen(config)
self.port=self.server.sockets[0].getsockname()[1]
async def asyncTearDown(self):
self.server.close();await self.server.wait_closed();self.backend.close();await self.backend.wait_closed();self.tmp.cleanup()
async def request(self,role=None,foreign=False,hostname='api',method='GET'):
context=ssl.create_default_context(cafile=str(BASE/'trust/ca.crt'))
if role:
root=BASE/'operator/foreign/leaf' if foreign else BASE/'pki'/role
context.load_cert_chain(str(root/'tls.crt'),str(root/'tls.key'))
writer=None
try:
reader,writer=await asyncio.open_connection('127.0.0.1',self.port,ssl=context,server_hostname=hostname)
writer.write((method+' / HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n').encode());await writer.drain()
return await asyncio.wait_for(reader.read(4096),2)
except (ssl.SSLError,ConnectionError,asyncio.TimeoutError) as exc:
self.last_error=repr(exc);return b''
finally:
if writer:
writer.close()
try: await writer.wait_closed()
except (ssl.SSLError,ConnectionError): pass
async def test_correct_identity(self):
self.assertIn(b'200 OK',await self.request('lb'),getattr(self,'last_error',''))
async def test_missing_foreign_and_wrong_identity(self):
for role,foreign in [(None,False),('lb',True),('intruder',False)]:
self.assertNotIn(b'200 OK',await self.request(role,foreign))
async def test_hostname_verification(self):
self.assertNotIn(b'200 OK',await self.request('lb',hostname='wrong.example'))
async def test_serial_revocation_new_connection(self):
self.assertIn(b'200 OK',await self.request('lb'),getattr(self,'last_error',''))
serial=subprocess.check_output(['openssl','x509','-in',str(BASE/'pki/lb/tls.crt'),'-noout','-serial'],text=True).strip().split('=')[1]
self.revoked.write_text(json.dumps([serial]))
self.assertNotIn(b'200 OK',await self.request('lb'))
async def test_query_identity_cannot_write(self):
self.assertIn(b'200 OK',await self.request('grafana'))
self.assertNotIn(b'200 OK',await self.request('grafana',method='POST'))
async def test_readonly_keepalive_cannot_smuggle_second_write(self):
context=ssl.create_default_context(cafile=str(BASE/'trust/ca.crt'))
context.load_cert_chain(str(BASE/'pki/grafana/tls.crt'),str(BASE/'pki/grafana/tls.key'))
reader,writer=await asyncio.open_connection('127.0.0.1',self.port,ssl=context,server_hostname='api')
try:
writer.write(b'GET / HTTP/1.1\r\nHost: api\r\nConnection: keep-alive\r\n\r\nPOST /write HTTP/1.1\r\nHost: api\r\nContent-Length: 0\r\n\r\n')
await writer.drain()
await asyncio.wait_for(reader.read(4096),2)
await asyncio.sleep(.1)
self.assertNotIn('POST',self.methods)
finally:
writer.close()
try: await writer.wait_closed()
except (ssl.SSLError,ConnectionError): pass
async def test_grpc_gateway_negotiates_h2(self):
ctx=ssl.create_default_context(cafile=str(BASE/'trust/ca.crt'))
ctx.load_cert_chain(str(BASE/'pki/lb/tls.crt'),str(BASE/'pki/lb/tls.key'))
ctx.set_alpn_protocols(['h2'])
_,writer=await asyncio.open_connection('127.0.0.1',self.port,ssl=ctx,server_hostname='api')
try: self.assertEqual(writer.get_extra_info('ssl_object').selected_alpn_protocol(),'h2')
finally:
writer.close()
try: await writer.wait_closed()
except (ssl.SSLError,ConnectionError): pass
async def test_readonly_rejects_mixed_lf_request_smuggling(self):
ctx=ssl.create_default_context(cafile=str(BASE/'trust/ca.crt'))
ctx.load_cert_chain(str(BASE/'pki/grafana/tls.crt'),str(BASE/'pki/grafana/tls.key'))
reader,writer=await asyncio.open_connection('127.0.0.1',self.port,ssl=ctx,server_hostname='api')
try:
writer.write(b'GET /ready HTTP/1.1\nHost: api\n\nPOST /write HTTP/1.1\r\nHost: api\r\nContent-Length: 0\r\n\r\n')
await writer.drain()
await asyncio.wait_for(reader.read(4096),2)
await asyncio.sleep(.1)
self.assertNotIn('POST',self.methods)
finally:
writer.close()
try: await writer.wait_closed()
except (ssl.SSLError,ConnectionError): pass