forked from mtusi2026/mtusi2026lab7
Майорова Софья, БВТ2301, на 5. Трек1. HTTPS/TLS/ACL,18 API tests,13 pipeline groups,3 compromise runs,clean clone,persistence. Original tests/API contract preserved; residual CVE triage in REPORT/security.
53 lines
3.5 KiB
Python
53 lines
3.5 KiB
Python
"""Inspect effective container hardening and the actual network namespace listeners."""
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import socket
|
|
import ssl
|
|
import subprocess
|
|
ROOT=Path(__file__).resolve().parents[1]
|
|
def output(*args):return subprocess.check_output(['docker','compose',*args],cwd=ROOT,text=True)
|
|
def inspect(container):return json.loads(subprocess.check_output(['docker','inspect',container],text=True))[0]
|
|
ids=output('ps','-aq').split()
|
|
rows=[];listeners={}
|
|
for identifier in ids:
|
|
data=inspect(identifier);role=data['Config']['Labels']['com.docker.compose.service'];host=data['HostConfig']
|
|
assert not host['Privileged'] and host['NetworkMode']!='host'
|
|
assert not any('docker.sock' in m['Destination'] for m in data['Mounts'])
|
|
assert host['Memory']>0 and host['NanoCpus']>0
|
|
assert 'ALL' in host['CapDrop']
|
|
assert any(x.startswith('no-new-privileges') for x in host['SecurityOpt'])
|
|
if role in ['api','worker','dispatcher']:
|
|
assert data['Config']['User']=='10001:10001' and host['ReadonlyRootfs'] and not host.get('CapAdd')
|
|
assert not any(m['Destination'].startswith('/operator') for m in data['Mounts'])
|
|
for port,bindings in (host['PortBindings'] or {}).items():
|
|
assert role in ['lb','bao','grafana']
|
|
assert all(b['HostIp']=='127.0.0.1' for b in bindings)
|
|
rows.append({'service':role,'user':data['Config']['User'],'read_only':host['ReadonlyRootfs'],
|
|
'cap_drop':host['CapDrop'],'cap_add':host.get('CapAdd') or [],'no_new_privileges':True,
|
|
'memory_bytes':host['Memory'],'nano_cpus':host['NanoCpus'],'host_ports':host['PortBindings'] or {}})
|
|
if role in ['s3','broker','redis','otel-collector','loki','tempo','prometheus','api','lb','bao','grafana'] and data['State']['Running']:
|
|
text=subprocess.check_output(['docker','exec',identifier,'cat','/proc/net/tcp'],text=True)
|
|
endpoints=[]
|
|
for line in text.splitlines()[1:]:
|
|
parts=line.split()
|
|
if parts[3]!='0A':continue
|
|
address,port=parts[1].split(':')
|
|
ip=socket.inet_ntoa(bytes.fromhex(address)[::-1]);port=int(port,16)
|
|
endpoints.append({'address':ip,'port':port})
|
|
key=role+('-'+str(len([r for r in rows if r['service']==role])) if role=='api' else '')
|
|
listeners[key]=endpoints
|
|
allowed={'api':{8080},'lb':{8443},'s3':{8443},'broker':{8443},'redis':{8443},'otel-collector':{8443,8444,8445},'loki':{8443},'tempo':{8443,8444},'prometheus':{8443},'bao':{8200,8201},'grafana':{3000}}[role]
|
|
for e in endpoints:
|
|
if e['address']=='0.0.0.0':assert e['port'] in allowed,(role,e)
|
|
# Explicit external wrong hostname, over a successful local TCP connection.
|
|
ctx=ssl.create_default_context(cafile=str(ROOT/'pki/lb/ca.crt'))
|
|
try:
|
|
with socket.create_connection(('127.0.0.1',int(os.environ.get('APP_PORT','18443'))),timeout=3) as raw:
|
|
ctx.wrap_socket(raw,server_hostname='wrong-hostname.invalid')
|
|
except ssl.SSLCertVerificationError:wrong_hostname=True
|
|
else:raise AssertionError('Hostname validation off')
|
|
(ROOT/'evidence/hardening.json').write_text(json.dumps({'containers':rows,'ipv4_listeners':listeners,
|
|
'wrong_external_hostname_rejected':wrong_hostname,'note':'Raw local hops share only their proxy namespace; PostgreSQL is native TLS. DNS on127.0.0.11 is platform-local, not a business listener.'},indent=2)+'\n')
|
|
print('PASS effective limits, non-root apps, drop ALL/no-new-privileges/read-only; published loopback TLS only, local raw listeners, wrong hostname rejected.')
|