Files
mtusi2026lab7/student-tests/internal.py
T

154 lines
7.8 KiB
Python

"""Run in the verifier profile. Real TLS, identity and authorization probes."""
import json
import socket
import ssl
import urllib.request
import urllib.error
import uuid
import time
from urllib.parse import urlparse
import boto3
import pika
import psycopg
from botocore.exceptions import ClientError
def context(identity=None):
ctx=ssl.create_default_context(cafile='/probe/lb/ca.crt')
if identity:
ctx.load_cert_chain('/probe/'+identity+'/cert.crt','/probe/'+identity+'/key.key')
return ctx
def http(host,port,path,identity=None,method='GET',body=None,token=None):
headers={'Content-Type':'application/json'}
if token:headers['X-Vault-Token']=token
req=urllib.request.Request(f'https://{host}:{port}'+path,data=json.dumps(body).encode() if body is not None else None,
headers=headers,method=method)
try:
with urllib.request.urlopen(req,context=context(identity),timeout=5) as response:
return response.status,response.read()
except urllib.error.HTTPError as error:
return error.code,error.read()
def denied_tls(host,port,path,identity):
try:
status,_=http(host,port,path,identity)
except (ssl.SSLError, ConnectionResetError, __import__('http.client',fromlist=['RemoteDisconnected']).RemoteDisconnected):
return
except urllib.error.URLError as error:
assert isinstance(error.reason,(ssl.SSLError,ConnectionResetError)),type(error.reason).__name__
return
raise AssertionError('TLS authorization unexpectedly returned HTTP '+str(status))
def plaintext_closed(host,port):
try:
with socket.create_connection((host,port),timeout=2):pass
except ConnectionRefusedError:return
raise AssertionError('Plaintext bypass reachable '+host)
def wait_http(host,port,path,identity):
deadline=time.monotonic()+60
while True:
status,_=http(host,port,path,identity)
if status==200:return
assert time.monotonic()<deadline,(host,'not ready',status)
time.sleep(1)
def bao(role,identity=None):
status,data=http('openbao',8200,'/v1/auth/cert/login',identity or role,'POST',{'name':role})
assert status==200,('certificate login',role,status)
auth=json.loads(data)['auth']
assert 0<auth['lease_duration']<=300
token=auth['client_token']
own='api' if role=='api2' else role
status,data=http('openbao',8200,'/v1/secret/data/'+own,identity or role,token=token)
assert status==200
for path,method,body in [('/v1/secret/data/'+('worker' if own=='api' else 'api'),'GET',None),
('/v1/sys/policies/acl/escalation','PUT',{'policy':'path "*" { capabilities=["root"] }'}),
('/v1/secret/data/'+own,'POST',{'data':{'overwritten':True}})]:
assert http('openbao',8200,path,identity or role,method,body,token)[0]==403
print('PASS OpenBao',role,'cert auth; TTL<=300; own read=200; foreign read/policy write/KV write=403')
return json.loads(data)['data']['data']
def main():
for host in ('api1','api2'):
for identity in (None,'foreign','probe'):
denied_tls(host,8443,'/health/ready',identity)
assert http(host,8443,'/health/ready','lb')[0]==200
plaintext_closed(host,8080)
print('PASS',host,'no cert / foreign CA / trusted wrong identity rejected; lb=200; port8080 closed')
secrets={role:bao(role, 'api1' if role=='api' else role) for role in ('api','api2','worker','dispatcher','cleaner')}
assert http('openbao',8200,'/v1/auth/cert/login','probe','POST',{'name':'api'})[0] in (400,403)
for role in ('api','worker','dispatcher','cleaner'):
with psycopg.connect(secrets[role]['DATABASE_URL']) as conn:
assert conn.execute('SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()').fetchone()[0]
assert conn.execute('SELECT current_user').fetchone()[0]==role
try:
with psycopg.connect(secrets[role]['DATABASE_URL'].replace('sslmode=verify-full','sslmode=disable')):pass
except psycopg.OperationalError:pass
else:raise AssertionError('DB accepted plaintext')
if role=='worker':
try:
with psycopg.connect(secrets[role]['DATABASE_URL']) as conn:conn.execute('SELECT * FROM users LIMIT 1')
except psycopg.errors.InsufficientPrivilege:pass
else:raise AssertionError('worker can read user credentials')
print('PASS PostgreSQL',role,'verify-full, server TLS observed; plaintext rejected')
for role in ('api','worker','cleaner'):
s3=boto3.client('s3',endpoint_url='https://s3:9000',verify='/probe/s3/ca.crt',region_name='us-east-1',
aws_access_key_id=secrets[role]['S3_ACCESS_KEY'],aws_secret_access_key=secrets[role]['S3_SECRET_KEY'])
try:s3.list_buckets()
except ClientError as error:assert error.response['ResponseMetadata']['HTTPStatusCode']==403
else:raise AssertionError('S3 identity has admin listing')
if role in ('api','cleaner'):s3.list_objects_v2(Bucket='attachments',Prefix='staging/',MaxKeys=1)
if role=='worker':
try:s3.put_object(Bucket='attachments',Key='staging/denied-'+uuid.uuid4().hex,Body=b'denied')
except ClientError as error:assert error.response['ResponseMetadata']['HTTPStatusCode']==403
else:raise AssertionError('worker can write API staging')
print('PASS S3',role,'TLS; administrative bucket listing denied; scoped permissions')
for role in ('worker','dispatcher'):
params=pika.URLParameters(secrets[role]['BROKER_URL'])
params.ssl_options=pika.SSLOptions(context(),'broker')
connection=pika.BlockingConnection(params)
channel=connection.channel();channel.queue_declare('attachment.process.v1',durable=True)
try:
if role=='worker':
channel.confirm_delivery();channel.basic_publish('','attachment.process.v1',b'{}')
else:channel.basic_get('attachment.process.v1')
except pika.exceptions.ChannelClosedByBroker as error:assert error.reply_code==403
else:raise AssertionError('broker ACL did not reject wrong operation')
connection.close()
print('PASS RabbitMQ',role,'TLS; wrong producer/consumer operation=403')
plaintext_closed('broker',5672)
assert http('otel-collector',4318,'/v1/traces','api1','POST',{})[0]==200
denied_tls('otel-collector',4318,'/v1/traces',None)
print('PASS Collector TLS authenticated ingest; no-certificate rejected')
for host,path in [('prometheus','/-/ready'),('loki','/ready'),('tempo','/ready')]:
wait_http(host,9443,path,'grafana')
denied_tls(host,9443,path,'probe')
plaintext_closed(host,{'prometheus':9090,'loki':3100,'tempo':3200}[host])
print('PASS backend',host,'Grafana mTLS; wrong identity rejected; plaintext closed')
assert http('tempo',9444,'/v1/traces','otel-collector','POST',{})[0]==200
payload={'resourceLogs':[{'resource':{'attributes':[{'key':'service.name','value':{'stringValue':'security-probe'}}]},
'scopeLogs':[{'logRecords':[{'timeUnixNano':str(time.time_ns()),'body':{'stringValue':'tls.authorization.probe'},'severityNumber':9}]}]}]}
status,_=http('loki',9443,'/otlp/v1/logs','otel-collector','POST',payload)
assert status in (200,204),('Loki OTLP valid record',status)
assert http('prometheus',9443,'/-/ready','otel-collector')[0]==200
print('PASS Collector -> all backends mTLS')
# Assert hostname rejection, distinct from network timeout/refusal.
with socket.create_connection(('s3',9000),timeout=3) as raw:
try:context().wrap_socket(raw,server_hostname='wrong.invalid')
except ssl.SSLCertVerificationError:pass
else:raise AssertionError('wrong hostname accepted')
print('PASS internal wrong hostname rejected by certificate verifier')
if __name__=='__main__':
main()