Files
mtusi2026lab7-fork/student-tests/internal_security.py

134 lines
9.1 KiB
Python

"""Operator-only TLS/ACL audit. Run in an isolated operator container."""
import json,socket,ssl,sys,time
from pathlib import Path
import urllib.request,urllib.error
import grpc,pika,psycopg2,boto3,redis
from botocore.exceptions import ClientError
from opentelemetry.proto.collector.trace.v1.trace_service_pb2_grpc import TraceServiceStub
from opentelemetry.proto.collector.trace.v1.trace_service_pb2 import ExportTraceServiceRequest
R=Path('/workspace');S=R/'secrets';results={}
def ctx(identity=None,foreign=False):
c=ssl.create_default_context(cafile=str(S/('foreign.crt' if foreign else 'ca/bundle.pem')))
if not foreign:c.verify_flags|=ssl.VERIFY_CRL_CHECK_LEAF
if identity=='foreign':c.load_cert_chain('/tmp/foreign.crt','/tmp/foreign.key')
elif identity:c.load_cert_chain(str(S/'tls'/identity/'server.crt'),str(S/'tls'/identity/'server.key'))
return c
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
request=urllib.request.Request('https://'+host+':'+str(port)+path,data=json.dumps(body).encode() if body is not None else None,headers=headers,method=method)
try:
with urllib.request.urlopen(request,context=ctx(identity),timeout=8) as response:return response.status,response.read()
except urllib.error.HTTPError as e:return e.code,e.read()
def expect_failure(label,function):
try:function()
except (FileNotFoundError,TypeError,NameError,AttributeError):raise
except Exception:results[label]=True;return
raise AssertionError(label+' unexpectedly accepted')
def api(identity,host='api-a'):
status,_=http(host,8080,'/health/live',identity)
assert status==200
# Foreign leaf is deliberately self-signed, separate from the trusted lab CA.
from cryptography import x509
from cryptography.hazmat.primitives import serialization,hashes
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.x509.oid import NameOID
import datetime as dt
foreign=rsa.generate_private_key(public_exponent=65537,key_size=2048)
name=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'foreign')]);now=dt.datetime.now(dt.timezone.utc)
cert=x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(foreign.public_key()).serial_number(42).not_valid_before(now-dt.timedelta(minutes=1)).not_valid_after(now+dt.timedelta(days=1)).sign(foreign,hashes.SHA256())
# All test-only writes stay in /tmp, never in the mounted workspace.
Path('/tmp/foreign.crt').write_bytes(cert.public_bytes(serialization.Encoding.PEM))
Path('/tmp/foreign.key').write_bytes(foreign.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()))
def foreign_client(host="api-a"):
c=ctx();c.load_cert_chain('/tmp/foreign.crt','/tmp/foreign.key')
with socket.create_connection((host,8080),timeout=3) as raw:
with c.wrap_socket(raw,server_hostname=host) as sock:
sock.sendall(b'GET /health/live HTTP/1.1\r\nHost: api-a\r\nConnection: close\r\n\r\n')
assert b'200' in sock.recv(1024)
for host in ('api-a','api-b'):
api('nginx',host);results[host+'_correct_lb_identity']=True
for identity in (None,'intruder','expired','worker'):
expect_failure(host+'_reject_'+str(identity),lambda i=identity,h=host:api(i,h))
expect_failure(host+'_foreign_ca',lambda h=host:foreign_client(h))
def wrong_hostname():
with socket.create_connection(('nginx',8443),timeout=3) as raw:
with ctx().wrap_socket(raw,server_hostname='wrong.invalid'):pass
expect_failure('external_wrong_hostname',wrong_hostname)
def collector(identity):
key=cert=None
if identity:
key=Path('/tmp/foreign.key').read_bytes() if identity=='foreign' else (S/'tls'/identity/'server.key').read_bytes()
cert=Path('/tmp/foreign.crt').read_bytes() if identity=='foreign' else (S/'tls'/identity/'server.crt').read_bytes()
creds=grpc.ssl_channel_credentials((S/'ca/ca.crt').read_bytes(),key,cert)
with grpc.secure_channel('otel-collector:4317',creds) as channel:
TraceServiceStub(channel).Export(ExportTraceServiceRequest(),timeout=4)
for identity in ('api-a','api-b','worker','publisher'):collector(identity)
results['collector_distinct_allowed_identities']=True
for identity in (None,'intruder','expired','nginx','foreign'):expect_failure('collector_reject_'+str(identity),lambda i=identity:collector(i))
def broker(identity):
return pika.BlockingConnection(pika.ConnectionParameters(host='rabbitmq',port=5671,credentials=pika.credentials.ExternalCredentials(),ssl_options=pika.SSLOptions(ctx(identity),'rabbitmq'),socket_timeout=3,stack_timeout=5,connection_attempts=1))
for identity in ('publisher','worker'):
connection=broker(identity);ch=connection.channel();ch.queue_declare(queue='attachment.process.v1',durable=True);connection.close()
results['broker_distinct_allowed_identities']=True
for identity in (None,'intruder','api-a','expired','foreign'):expect_failure('broker_reject_'+str(identity),lambda i=identity:broker(i))
connection=broker('worker');ch=connection.channel();ch.confirm_delivery()
expect_failure('worker_cannot_publish',lambda:ch.basic_publish('', 'attachment.process.v1',b'forbidden'))
if connection.is_open:connection.close()
roles=json.loads((S/'operator/roles.json').read_text())
for role in ('api','worker','publisher','cleaner'):
conn=psycopg2.connect(roles[role]['database_url']);cur=conn.cursor();cur.execute('SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()');assert cur.fetchone()[0];conn.close()
results['postgres_all_roles_verified_tls']=True
conn=psycopg2.connect(roles['worker']['database_url']);cur=conn.cursor()
cur.execute("SELECT has_table_privilege('worker','attachments','DELETE'), has_table_privilege('publisher','attachment_variants','SELECT')")
assert cur.fetchone()==(False,False)
conn.close();results['historical_broad_grants_removed']=True
conn=psycopg2.connect(roles['worker']['database_url']);cur=conn.cursor()
expect_failure('worker_cannot_read_users',lambda:cur.execute('SELECT password_hash FROM users'))
conn.rollback();conn.close()
clients={role:boto3.client('s3',endpoint_url='https://s3:9000',verify='/run/ca/ca.crt',aws_access_key_id=roles[role]['s3_access_key_id'],aws_secret_access_key=roles[role]['s3_secret_access_key'],region_name='us-east-1') for role in ('api','worker','cleaner')}
bucket='messenger-attachments';staging='attachments/staging/security-probe';final='attachments/final/security-probe'
clients['api'].put_object(Bucket=bucket,Key=staging,Body=b'probe')
assert clients['worker'].get_object(Bucket=bucket,Key=staging)['Body'].read()==b'probe'
clients['worker'].put_object(Bucket=bucket,Key=final,Body=b'probe')
assert clients['api'].get_object(Bucket=bucket,Key=final)['Body'].read()==b'probe'
expect_failure('api_cannot_write_final',lambda:clients['api'].put_object(Bucket=bucket,Key=final,Body=b'forbidden'))
expect_failure('worker_cannot_write_staging',lambda:clients['worker'].put_object(Bucket=bucket,Key=staging,Body=b'forbidden'))
for key in (staging,final):clients['cleaner'].delete_object(Bucket=bucket,Key=key)
results['s3_prefix_acl']=True
r=redis.Redis.from_url(roles['api']['cache_url'],ssl_ca_certs='/run/ca/ca.crt',ssl_certfile=str(S/'tls/api-a/server.crt'),ssl_keyfile=str(S/'tls/api-a/server.key'))
assert r.ping();expect_failure('redis_config_denied',lambda:r.config_get('*'));results['redis_tls_acl']=True
for role,identity in [('api','api-a'),('worker','worker')]:
status,body=http('openbao',8200,'/v1/auth/cert/login',identity,'POST',{'name':role});assert status==200
token=json.loads(body)['auth']['client_token']
assert http('openbao',8200,'/v1/secret/data/'+role,identity,token=token)[0]==200
assert http('openbao',8200,'/v1/secret/data/'+('worker' if role=='api' else 'api'),identity,token=token)[0]==403
assert http('openbao',8200,'/v1/sys/policies/acl/escalate',identity,'PUT',{'policy':'path "*" { capabilities=["sudo"] }'},token)[0]==403
results['openbao_'+role+'_allow_deny']=True
status,_=http('openbao',8200,'/v1/auth/cert/login','intruder','POST',{'name':'api'});assert status in (400,403)
results['openbao_wrong_identity_denied']=True
for host,port,path,legit in [('prometheus',9090,'/-/ready','grafana'),('loki',3100,'/ready','grafana'),('tempo',3200,'/ready','grafana')]:
for attempt in range(30):
if http(host,port,path,legit)[0]==200:break
time.sleep(1)
else:raise AssertionError(host+' not ready')
expect_failure(host+'_intruder_denied',lambda h=host,p=port,u=path:http(h,p,u,'intruder'))
# An allowed writer cannot use Loki's read API.
assert http('loki',3100,'/loki/api/v1/labels','collector')[0]==403
results['loki_writer_read_denied']=True
assert http('loki',3100,'/loki/api/v1/push','grafana','POST',{'streams':[]})[0]==403
results['grafana_log_ingest_denied']=True
for host,port in [('rabbitmq',5672),('rabbitmq',15692),('rabbitmq',15672),('rabbitmq',25672),('rabbitmq',4369),('otel-collector',43170),('loki',13100),('tempo',13200),('prometheus',19090)]:
expect_failure(host+'_'+str(port)+'_plaintext_loopback_only',lambda h=host,p=port:socket.create_connection((h,p),timeout=2))
print(json.dumps(results,indent=2))