forked from mtusi2026/mtusi2026lab7
Лабораторная 7: безопасность, mTLS и OpenBao, оценка 3
This commit is contained in:
@@ -0,0 +1,21 @@
|
||||
"""Public ingress: real login rate limit, body limit and hostname check."""
|
||||
import ssl
|
||||
import json
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
ctx=ssl.create_default_context(cafile='secrets/ca.crt')
|
||||
for i in range(25):
|
||||
req=urllib.request.Request('https://localhost:8443/api/v1/auth/sessions',data=b'',method='POST')
|
||||
try: urllib.request.urlopen(req,context=ctx,timeout=5)
|
||||
except urllib.error.HTTPError as e:
|
||||
if e.code==429:
|
||||
assert int(e.headers['Retry-After'])>0
|
||||
assert json.load(e)['error']['request_id']==e.headers['X-Request-Id']
|
||||
print('PASS login rate limit: 429 with Retry-After');break
|
||||
assert e.code==401
|
||||
else: raise AssertionError('429 not received')
|
||||
req=urllib.request.Request('https://localhost:8443/api/v1/users',data=b'x'*65537,headers={'Content-Type':'application/json'},method='POST')
|
||||
try: urllib.request.urlopen(req,context=ctx,timeout=5)
|
||||
except urllib.error.HTTPError as e: assert e.code==413
|
||||
else: raise AssertionError('body limit absent')
|
||||
print('PASS JSON request size limit: 413')
|
||||
@@ -0,0 +1,40 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Target both concrete replicas in sequence and preserve session/data through each stop."""
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'tests'))
|
||||
from client import Client
|
||||
c=Client('https://localhost:8443',ca_file='secrets/ca.crt')
|
||||
alice,bob,eve,chat=c.bootstrap()
|
||||
ids=subprocess.check_output(['docker','compose','ps','-q','api'],text=True).split()
|
||||
assert len(ids)==2
|
||||
saved=[]
|
||||
for id in ids:
|
||||
alias=subprocess.check_output(['docker','exec',id,'cat','/tmp/instance-alias'],text=True).strip()
|
||||
before=c.message(alice,chat,'confirmed-before-'+alias)['json']; saved.append(before)
|
||||
start=time.monotonic()
|
||||
subprocess.run(['scripts/stop-one.sh'],env=dict(os.environ,TARGET_INSTANCE_ID=alias),check=True,stdout=subprocess.DEVNULL)
|
||||
for attempt in range(30):
|
||||
try:
|
||||
response=c.message(alice,chat,'confirmed-after-'+alias,key='retry-'+alias)
|
||||
break
|
||||
except Exception:
|
||||
time.sleep(.25)
|
||||
else: raise AssertionError('no recovery')
|
||||
assert response['headers']['X-Instance-Id']!=alias
|
||||
saved.append(response['json'])
|
||||
page=c.call('GET','/api/v1/chats/'+chat['id']+'/messages',actor=bob,schema='MessagePage')['json']
|
||||
assert all(x in page['items'] for x in saved)
|
||||
name=subprocess.check_output(['docker','inspect','--format','{{.Name}}',id],text=True).strip()
|
||||
print('PASS stopped',name,'confirmed data/session preserved; recovery_seconds',round(time.monotonic()-start,3),flush=True)
|
||||
subprocess.run(['docker','start',id],check=True,stdout=subprocess.DEVNULL)
|
||||
for attempt in range(100):
|
||||
seen={c.call('GET','/health/ready')['headers']['X-Instance-Id'] for _ in range(4)}
|
||||
if len(seen)>=2: break
|
||||
time.sleep(.2)
|
||||
else: raise AssertionError('replica did not rejoin')
|
||||
print('PASS both distinct API containers stopped in sequence and restored')
|
||||
@@ -0,0 +1,25 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Inspect only safe fields; do not dump environment, mounts contents or tokens."""
|
||||
import json
|
||||
import subprocess
|
||||
ids=subprocess.check_output(['docker','compose','ps','-q'],text=True).split()
|
||||
assert ids
|
||||
for id in ids:
|
||||
c=json.loads(subprocess.check_output(['docker','inspect',id]))[0]
|
||||
role=c['Config']['Labels']['com.docker.compose.service']
|
||||
h=c['HostConfig']
|
||||
assert not h['Privileged'] and h['NetworkMode']!='host'
|
||||
assert all('docker.sock' not in m['Source'] for m in c['Mounts'])
|
||||
assert h['Memory']>0 and h['NanoCpus']>0
|
||||
if role in ('api','worker','dispatcher'):
|
||||
assert c['Config']['User']=='65534:65534'
|
||||
assert 'ALL' in h['CapDrop'] and h['ReadonlyRootfs']
|
||||
assert 'no-new-privileges:true' in h['SecurityOpt']
|
||||
assert not h['PortBindings']
|
||||
assert all('/operator' not in m['Destination'] for m in c['Mounts'])
|
||||
ports=h['PortBindings'] or {}
|
||||
for entries in ports.values():
|
||||
for entry in entries or []:
|
||||
assert entry['HostIp']=='127.0.0.1'
|
||||
assert role in ('lb','grafana','openbao')
|
||||
print('PASS hardening/resource/port checks:',role)
|
||||
@@ -0,0 +1,128 @@
|
||||
"""Run in an ephemeral operator test container, never in production app containers."""
|
||||
import base64
|
||||
import http.client
|
||||
import json
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import ssl
|
||||
import time
|
||||
import uuid
|
||||
import os
|
||||
|
||||
ROOT=Path('/audit')
|
||||
CA=str(ROOT/'secrets/ca.crt')
|
||||
def context(role=None):
|
||||
ctx=ssl.create_default_context(cafile=CA)
|
||||
if role:
|
||||
if role=='foreign':
|
||||
ctx.load_cert_chain(str(ROOT/'operator/foreign-client.crt'),str(ROOT/'operator/foreign-client.key'))
|
||||
else: ctx.load_cert_chain(str(ROOT/f'secrets/{role}/service.crt'),str(ROOT/f'secrets/{role}/service.key'))
|
||||
return ctx
|
||||
|
||||
def request(host, port, path, method='GET', body=None, headers=None, role=None, target=None):
|
||||
c=http.client.HTTPSConnection(host,port,context=context(role),timeout=5)
|
||||
c.sock=context(role).wrap_socket(socket.create_connection((target or host,port),timeout=5),server_hostname=host)
|
||||
try:
|
||||
c.request(method,path,body=body,headers=headers or {})
|
||||
r=c.getresponse(); data=r.read(); return r.status,dict(r.getheaders()),json.loads(data) if data else None
|
||||
finally: c.close()
|
||||
|
||||
addresses=sorted({x[4][0] for x in socket.getaddrinfo('api',8080,type=socket.SOCK_STREAM)})
|
||||
assert len(addresses)>=2
|
||||
for ip in addresses:
|
||||
assert request('api',8080,'/health/ready',role='lb',target=ip)[0]==200
|
||||
for role in (None,'foreign','wrong-role'):
|
||||
try: request('api',8080,'/health/ready',role=role,target=ip)
|
||||
except ssl.SSLError: pass
|
||||
else: raise AssertionError('mTLS allowed forbidden identity')
|
||||
print('PASS API replica: LB accepted; absent cert, foreign CA, same-CA wrong SAN rejected')
|
||||
|
||||
for host,port in [('valkey',6379),('broker',6379),('s3',9443),('otel-collector',4438),('otel-collector',8899),('otel-collector',8898),('loki',3443),('tempo',3443),('tempo',4438),('prometheus',9443),('grafana',3443),('openbao',8200)]:
|
||||
client_role = 'api' if host=='otel-collector' else 'grafana' if host in ('loki','tempo','prometheus') else None
|
||||
with context(client_role).wrap_socket(socket.create_connection((host,port),timeout=5),server_hostname=host): pass
|
||||
try:
|
||||
with context(client_role).wrap_socket(socket.create_connection((host,port),timeout=5),server_hostname='forbidden.example'): pass
|
||||
except ssl.SSLCertVerificationError: pass
|
||||
else: raise AssertionError('hostname unchecked')
|
||||
print(f'PASS verified TLS + hostname rejection: {host}:{port}')
|
||||
for host,port,good in [('otel-collector',4438,'api'),('loki',3443,'otel-collector'),('tempo',4438,'otel-collector'),('prometheus',9443,'grafana')]:
|
||||
def probe(role):
|
||||
with context(role).wrap_socket(socket.create_connection((host,port),timeout=5),server_hostname=host) as conn:
|
||||
conn.sendall(b'GET / HTTP/1.1\r\nHost: test\r\nConnection: close\r\n\r\n')
|
||||
return conn.recv(64)
|
||||
assert probe(good).startswith(b'HTTP/')
|
||||
for bad in (None,'foreign','wrong-role'):
|
||||
try:
|
||||
result=probe(bad)
|
||||
except (ssl.SSLError,ConnectionResetError,BrokenPipeError):
|
||||
pass
|
||||
else:
|
||||
assert not result, 'telemetry wrong identity allowed'
|
||||
print(f'PASS telemetry {host}: authorized HTTP works; no-cert/foreign/wrong-URI rejected')
|
||||
|
||||
for host,ports in [('s3',[9000,9333,8080,8888,19000,19333,18080,18888]),('otel-collector',[4318,8889,8888]),('loki',[3100,9095]),('tempo',[3200,4318,9095]),('prometheus',[9090]),('grafana',[3000])]:
|
||||
for port in ports:
|
||||
try: socket.create_connection((host,port),timeout=1).close()
|
||||
except OSError: pass
|
||||
else: raise AssertionError(f'plaintext bypass {host}:{port}')
|
||||
print('PASS all declared loopback plaintext hops inaccessible from app network')
|
||||
|
||||
for role in ('api','worker','dispatcher'):
|
||||
status,_,auth=request('openbao',8200,'/v1/auth/cert/login','POST',json.dumps({'name':role}),{'Content-Type':'application/json'},role=role)
|
||||
assert status==200 and auth['auth']['lease_duration']<=300
|
||||
headers={'X-Vault-Token':auth['auth']['client_token']}
|
||||
assert request('openbao',8200,'/v1/secret/data/'+role,headers=headers,role=role)[0]==200
|
||||
for path in ('secret/data/'+('worker' if role=='api' else 'api'),'sys/mounts'):
|
||||
assert request('openbao',8200,'/v1/'+path,headers=headers,role=role)[0]==403
|
||||
assert request('openbao',8200,'/v1/auth/token/revoke-self','POST','{}',headers,role=role)[0] in (200,204)
|
||||
assert request('openbao',8200,'/v1/secret/data/'+role,headers=headers,role=role)[0]==403
|
||||
print(f'PASS Bao {role}: cert auth, TTL, own read, cross-role/admin deny, revoked token deny')
|
||||
assert request('openbao',8200,'/v1/auth/cert/login','POST','{"name":"api"}',role='wrong-role')[0] in (400,403)
|
||||
print('PASS Bao wrong identity cannot authenticate as API')
|
||||
|
||||
import psycopg
|
||||
import redis
|
||||
import boto3
|
||||
from botocore.exceptions import ClientError
|
||||
bundles=json.loads((ROOT/'operator/bundles.json').read_text())
|
||||
for role in ('api','worker','dispatcher'):
|
||||
dsn=bundles[role]['database_url'].replace('/tls/ca.crt',CA)
|
||||
with psycopg.connect(dsn,autocommit=True) as db:
|
||||
assert db.execute('SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()').fetchone()[0]
|
||||
try: db.execute('CREATE TABLE forbidden_probe(id int)')
|
||||
except psycopg.errors.InsufficientPrivilege: pass
|
||||
else: raise AssertionError('DB DDL privilege')
|
||||
if role!='api':
|
||||
try: db.execute('SELECT password_hash FROM users LIMIT 1')
|
||||
except psycopg.errors.InsufficientPrivilege: pass
|
||||
else: raise AssertionError('worker read password hashes')
|
||||
print(f'PASS DB {role}: TLS verified and least-privilege DDL/password isolation')
|
||||
try:
|
||||
psycopg.connect(bundles['api']['database_url'].split('?')[0]+'?sslmode=disable',connect_timeout=3)
|
||||
except psycopg.OperationalError: pass
|
||||
else: raise AssertionError('DB plaintext accepted')
|
||||
for role in ('worker','dispatcher'):
|
||||
r=redis.Redis.from_url(bundles[role]['broker_url'],ssl_ca_certs=CA,ssl_check_hostname=True)
|
||||
assert r.ping()
|
||||
try: r.set('forbidden-key','test')
|
||||
except redis.exceptions.NoPermissionError: pass
|
||||
else: raise AssertionError('broker privilege escalation')
|
||||
print(f'PASS broker {role}: TLS auth + unrelated command/key denied')
|
||||
for role in ('api','worker'):
|
||||
b=bundles[role]
|
||||
s3=boto3.client('s3',endpoint_url='https://s3:9443',aws_access_key_id=b['s3_access_key_id'],aws_secret_access_key=b['s3_secret_access_key'],region_name='us-east-1',verify=CA)
|
||||
try: s3.list_objects_v2(Bucket='messenger-attachments')
|
||||
except ClientError as e: assert e.response['ResponseMetadata']['HTTPStatusCode']==403
|
||||
else: raise AssertionError('S3 listing allowed')
|
||||
print(f'PASS S3 {role}: bucket listing denied')
|
||||
if os.getenv('EXPIRY_TARGET'):
|
||||
target=os.environ['EXPIRY_TARGET']
|
||||
user='expiry_'+uuid.uuid4().hex[:16]; password='SyntheticExpiryPassword123'
|
||||
assert request('api',8080,'/api/v1/users','POST',json.dumps({'username':user,'display_name':'Expiry','password':password}),{'Content-Type':'application/json'},role='lb',target=target)[0]==201
|
||||
status,_,session=request('api',8080,'/api/v1/auth/sessions','POST',headers={'Authorization':'Basic '+base64.b64encode((user+':'+password).encode()).decode()},role='lb',target=target)
|
||||
assert status==201
|
||||
headers={'Authorization':'Bearer '+session['token']}
|
||||
assert request('api',8080,'/api/v1/users/me',headers=headers,role='lb',target=target)[0]==200
|
||||
time.sleep(3)
|
||||
assert request('api',8080,'/api/v1/users/me',headers=headers,role='lb',target=target)[0]==401
|
||||
print('PASS real service session expiry: valid token then 401 after TTL=2s')
|
||||
@@ -0,0 +1,88 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Assert actual application signals in each backend; persist no credentials."""
|
||||
import json
|
||||
import ssl
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'tests'))
|
||||
from client import Client, check
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
CA = ROOT / 'secrets/ca.crt'
|
||||
|
||||
def backend_context():
|
||||
ctx = ssl.create_default_context(cafile=str(CA))
|
||||
ctx.load_cert_chain(str(ROOT/'secrets/grafana/service.crt'), str(ROOT/'secrets/grafana/service.key'))
|
||||
return ctx
|
||||
|
||||
def get(base, path, params=None):
|
||||
if params:
|
||||
path += '?' + urllib.parse.urlencode(params)
|
||||
with urllib.request.urlopen(base + path, timeout=15, context=backend_context()) as response:
|
||||
return json.load(response)
|
||||
|
||||
def eventually(fn, seconds=90):
|
||||
deadline = time.monotonic() + seconds
|
||||
last = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
value = fn()
|
||||
if value:
|
||||
return value
|
||||
except Exception as exc:
|
||||
last = type(exc).__name__
|
||||
time.sleep(2)
|
||||
raise AssertionError('signal did not arrive: ' + str(last))
|
||||
|
||||
def logs(service, suffix=''):
|
||||
return get('https://loki:3443', '/loki/api/v1/query_range', {
|
||||
'query': '{service_name="'+service+'"}' + suffix,
|
||||
'start': int((time.time()-600)*1e9), 'end': int(time.time()*1e9), 'limit': 100
|
||||
})['data']['result']
|
||||
|
||||
def trace_exists(tid):
|
||||
data = get('https://tempo:3443', '/api/traces/' + tid)
|
||||
return data if data.get('batches') or data.get('resourceSpans') else None
|
||||
|
||||
def main():
|
||||
c = Client('https://lb:8443', ca_file=str(CA))
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
response = c.message(alice, chat, 'telemetry synthetic check')
|
||||
# Follow a controlled request by server-generated X-Trace-Id and X-Request-Id.
|
||||
response = c.call('GET', '/api/v1/chats/'+chat['id']+'/messages', actor=alice)
|
||||
headers = response['headers']
|
||||
tid = headers.get('X-Trace-Id')
|
||||
rid = headers.get('X-Request-Id')
|
||||
check(bool(tid) and len(tid)==32, 'missing trace ID')
|
||||
job_started = time.time()
|
||||
att, _ = c.attachment(alice, chat)
|
||||
c.wait_ready(alice, att)
|
||||
api_logs = eventually(lambda: logs('messenger-api', ' | trace_id="'+tid+'"'))
|
||||
api_trace = eventually(lambda: trace_exists(tid))
|
||||
worker_logs = eventually(lambda: [row for row in logs('messenger-worker', ' | event="job.success"') if int(row['values'][0][0])/1e9 >= job_started])
|
||||
values = worker_logs[0]['values']
|
||||
# Native OTLP metadata carries trace_id without making it a metric label.
|
||||
worker_tid = values[0][2].get('trace_id') if len(values[0]) > 2 else None
|
||||
if not worker_tid:
|
||||
worker_tid = worker_logs[0]['stream'].get('trace_id')
|
||||
check(bool(worker_tid), 'worker log lacks trace ID')
|
||||
worker_trace = eventually(lambda: trace_exists(worker_tid))
|
||||
metric_names = ['api_requests_total','api_duration_seconds_bucket','worker_jobs_total','worker_duration_seconds_bucket']
|
||||
metric_results = {}
|
||||
for name in metric_names:
|
||||
metric_results[name] = eventually(lambda: get('https://prometheus:9443','/api/v1/query',{'query': name})['data']['result'])
|
||||
for results in metric_results.values():
|
||||
for result in results:
|
||||
check(not (set(result['metric']) & {'user_id','chat_id','message_id','attachment_id','request_id','filename'}), 'high cardinality metric labels')
|
||||
proof = {'api_trace_id':tid,'api_request_id':rid,'worker_trace_id':worker_tid,
|
||||
'api_logs':api_logs,'worker_logs':worker_logs,'api_trace':api_trace,'worker_trace':worker_trace,
|
||||
'metrics':metric_results}
|
||||
(ROOT/'evidence'/'telemetry.json').write_text(json.dumps(proof,ensure_ascii=False,indent=2)+'\n')
|
||||
print('PASS: API trace + matching log, worker consumer trace + matching log, four real SDK metrics; evidence/telemetry.json')
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,24 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Check publishable files against actual local secret values without printing them."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
values=[]
|
||||
def collect(x):
|
||||
if isinstance(x,dict):
|
||||
for v in x.values(): collect(v)
|
||||
elif isinstance(x,list):
|
||||
for v in x: collect(v)
|
||||
elif isinstance(x,str) and len(x)>=20: values.append(x.encode())
|
||||
for p in ('operator/credentials.json','operator/bao-init.json'):
|
||||
collect(json.loads(Path(p).read_text()))
|
||||
files=subprocess.check_output(['git','ls-files','--cached','--others','--exclude-standard'],text=True).splitlines()
|
||||
for file in files:
|
||||
p=Path(file)
|
||||
if not p.is_file(): continue
|
||||
data=p.read_bytes()
|
||||
assert not any(v in data for v in values), 'secret value in '+file
|
||||
# Split literals avoid scanner matching its own source code.
|
||||
for marker in (b'-----BEGIN '+b'PRIVATE KEY-----',b'-----BEGIN RSA '+b'PRIVATE KEY-----'):
|
||||
assert marker not in data,'private key in '+file
|
||||
print('PASS no generated credential/root/unseal values or private keys in publishable files')
|
||||
Reference in New Issue
Block a user