Files
mtusi2026lab7/checks/hardening.py
T

37 lines
2.3 KiB
Python

import json
from pathlib import Path
import ssl
import subprocess
import urllib.request
ROOT=Path(__file__).resolve().parents[1]
def docker(*args):return subprocess.check_output(['docker',*args],cwd=ROOT,text=True,encoding='utf-8').strip()
rows=[]
ids=docker('compose','ps','-q').splitlines()
for cid in ids:
data=json.loads(docker('inspect',cid))[0]
role=data['Config']['Labels']['com.docker.compose.service']
if role in ('telemetry-init','secret-init'):continue
h=data['HostConfig'];mounts=data['Mounts'];user=data['Config']['User']
assert not h['Privileged'] and h['NetworkMode']!='host'
assert h['ReadonlyRootfs'] and 'ALL' in h['CapDrop'] and 'no-new-privileges:true' in h['SecurityOpt']
assert h['Memory']>0 and h['NanoCpus']>0 and h['PidsLimit']>0
assert not any('docker.sock' in m['Source'] or '/operator' in m['Source'].replace('\\','/') for m in mounts)
published=[]
for port,bindings in (h.get('PortBindings') or {}).items():
for bind in bindings or []:
assert bind['HostIp']=='127.0.0.1'
assert (role,bind['HostPort']) in {('lb','8443'),('openbao','8200'),('grafana','3000')}
published.append(bind['HostPort'])
if role in ('api1','api2','worker','dispatcher','reconciler'):
assert user=='10001:10001'
assert all(not e.startswith(('DATABASE_URL=','S3_SECRET_KEY=','BAO_TOKEN=','POSTGRES_PASSWORD=')) for e in data['Config']['Env'])
assert all(m['Destination'] in ('/identity','/trust','/tmp') for m in mounts)
rows.append({'service':role,'user':user,'read_only':True,'cap_drop':['ALL'],'memory_bytes':h['Memory'],'NanoCpus':h['NanoCpus'],'pids_limit':h['PidsLimit'],'published_loopback_ports':published,'operator_material_absent':True})
ctx=ssl.create_default_context(cafile=str(ROOT/'secrets/trust/ca.crt'))
with urllib.request.urlopen('https://127.0.0.1:3000/login',context=ctx,timeout=10) as r:assert r.status==200
raw=docker('compose','run','--rm','--no-deps','security-check','python','/checks/plaintext_isolation.py')
isolation=json.loads(raw);assert isolation['passed']
(ROOT/'evidence/hardening.json').write_text(json.dumps({'passed':True,'runtime':rows,'grafana_verified_HTTPS':True,'plaintext_isolation':isolation},indent=2)+'\n')
print('PASS: runtime privileges/resource limits/mounts/public ports and loopback-only plaintext')