[+] lab7
This commit is contained in:
@@ -0,0 +1,182 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Real local lifecycle/ACL/admission checks; secrets stay in memory or ignored files."""
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import urllib.error
|
||||
|
||||
ROOT=Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0,str(ROOT/'tests'))
|
||||
sys.path.insert(0,str(ROOT/'scripts'))
|
||||
from client import Client,check
|
||||
from bao_operator import request as bao_request,bootstrap as bao_unseal
|
||||
|
||||
CA=ROOT/'secrets/trust/ca.crt'
|
||||
BASE='https://localhost:8443'
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run(['docker','compose',*args],cwd=ROOT,check=True,capture_output=True,text=True,timeout=180).stdout
|
||||
|
||||
|
||||
def wait_for(function,seconds=40):
|
||||
end=time.monotonic()+seconds
|
||||
while time.monotonic()<end:
|
||||
try:
|
||||
value=function()
|
||||
if value:return value
|
||||
except Exception:pass
|
||||
time.sleep(.5)
|
||||
raise AssertionError('Condition did not recover in bounded time')
|
||||
|
||||
|
||||
def inside(body,**values):
|
||||
script="import json,hashlib,time,ssl,socket\nfrom pathlib import Path\nfrom urllib.parse import urlsplit\nfrom psycopg import sql\nimport psycopg\nimport sys;sys.path.insert(0,'/audit-scripts')\nfrom matrix_audit import VALUES,context,http\nv="+repr(values)+'\n'+body+'\nprint(json.dumps(result,default=str))'
|
||||
result=subprocess.run(['docker','compose','run','--rm','--no-deps','-T','security-audit','python','-'],cwd=ROOT,
|
||||
input=script,capture_output=True,text=True,timeout=120)
|
||||
if result.returncode:raise RuntimeError(result.stderr)
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def status(path='/api/v1/users/me',actor=None):
|
||||
headers={} if actor is None else {'Authorization':'Bearer '+actor['token']}
|
||||
req=urllib.request.Request(BASE+path,headers=headers)
|
||||
try:r=urllib.request.urlopen(req,context=ssl.create_default_context(cafile=str(CA)),timeout=8)
|
||||
except urllib.error.HTTPError as exc:r=exc
|
||||
with r:return r.status
|
||||
|
||||
|
||||
def backend_get(port,path):
|
||||
ctx=ssl.create_default_context(cafile=str(CA));ctx.load_cert_chain(str(ROOT/'secrets/pki/operator/tls.crt'),str(ROOT/'secrets/pki/operator/tls.key'))
|
||||
with urllib.request.urlopen(urllib.request.Request('https://localhost:'+str(port)+path,headers={'Accept':'application/json'}),context=ctx,timeout=8) as r:return json.load(r)
|
||||
|
||||
|
||||
def save(name,data):
|
||||
(ROOT/'evidence'/name).write_text(json.dumps(data,indent=2)+'\n')
|
||||
|
||||
|
||||
def main():
|
||||
c=Client(BASE,str(CA));alice,bob,eve,chat=c.bootstrap()
|
||||
result={'result':'INCOMPLETE'};sealed=False;worker_stopped=False
|
||||
try:
|
||||
# Rehash before applying deliberate login admission pressure.
|
||||
inside("from argon2 import PasswordHasher\nold=PasswordHasher(time_cost=1,memory_cost=8192,parallelism=1).hash(v['password'])\nwith psycopg.connect(VALUES['api']['DATABASE_URL']) as db:\n db.execute('UPDATE users SET password_hash=%s WHERE id=%s',(old,v['id']))\nresult=True",password=alice['registration']['password'],id=alice['id'])
|
||||
login=c.call('POST','/api/v1/auth/sessions',201,headers={'Authorization':'Basic '+base64.b64encode((alice['registration']['username']+':'+alice['registration']['password']).encode()).decode()},schema='Session')
|
||||
result['rehash']=inside("from messenger.security import HASHER\nwith psycopg.connect(VALUES['api']['DATABASE_URL']) as db:\n encoded=db.execute('SELECT password_hash FROM users WHERE id=%s',(v['id'],)).fetchone()[0]\nresult={'argon2id':encoded.startswith('$argon2id$'),'current_parameters':not HASHER.check_needs_rehash(encoded)}",id=alice['id'])
|
||||
check(all(result['rehash'].values()),'Rehash failed')
|
||||
c.call('GET','/api/v1/chats/'+chat['id'],404,actor=eve)
|
||||
att,raw=c.attachment(alice,chat);c.wait_ready(bob,att)
|
||||
for suffix in ('','/content'):c.call('GET','/api/v1/attachments/'+att['id']+suffix,404,actor=eve)
|
||||
c.call('POST','/api/v1/chats/'+chat['id']+'/messages',404,actor=eve,body={'text':'','attachment_ids':[att['id']]},headers={'Idempotency-Key':secrets.token_hex(8)})
|
||||
me=c.call('GET','/api/v1/users/me',actor=alice,headers={'X-User-Id':eve['id']},schema='User')['json'];check(me['id']==alice['id'],'Forged identity')
|
||||
result['session_hash']=inside("with psycopg.connect(VALUES['api']['DATABASE_URL']) as db:\n found=db.execute('SELECT count(*) FROM sessions WHERE token_hash=%s',(hashlib.sha256(v['token'].encode()).hexdigest(),)).fetchone()[0]\nresult={'sha256_server_session':found==1}",token=alice['token'])
|
||||
# Shared account budget is checked across both API aliases.
|
||||
if time.time()%10>7:time.sleep(10-time.time()%10+.1)
|
||||
basic=base64.b64encode((alice['registration']['username']+':wrong-password-123').encode()).decode()
|
||||
def attempt(_):
|
||||
response=c.call('POST','/api/v1/auth/sessions',[401,429],headers={'Authorization':'Basic '+basic})
|
||||
return {'status':response['status'],'instance':response['headers'].get('X-Instance-Id'),'retry_after':response['headers'].get('Retry-After')}
|
||||
with ThreadPoolExecutor(max_workers=16) as pool:attempts=list(pool.map(attempt,range(16)))
|
||||
check(any(a['status']==429 and a['retry_after'] for a in attempts),'No shared rate limit')
|
||||
check(len({a['instance'] for a in attempts})==2,'Rate test did not hit both replicas')
|
||||
result['shared_login_limit']={'attempts':attempts,'replicas':2,'per_account':10,'window_seconds':10,'global_kdf':120}
|
||||
# Operator benchmark runs inside the actual 1 CPU API cgroup.
|
||||
bench="import json,time,resource;from messenger.security import HASHER\np='synthetic-benchmark-password';h=HASHER.hash(p);values=[]\nfor _ in range(10):\n t=time.perf_counter();HASHER.verify(h,p);values.append(1000*(time.perf_counter()-t))\nprint(json.dumps({'m_kib':19456,'t':2,'p':1,'verify_ms':values,'max_verify_ms':max(values),'peak_kib':resource.getrusage(resource.RUSAGE_SELF).ru_maxrss,'local_slots_per_api':2,'replicas':2}))"
|
||||
result['argon_budget']=json.loads(compose('exec','-T','api','python','-c',bench))
|
||||
# Exact hostname validation, not a connection failure.
|
||||
rejected=False
|
||||
try:
|
||||
rawsock=socket.create_connection(('localhost',8443),timeout=3)
|
||||
ssl.create_default_context(cafile=str(CA)).wrap_socket(rawsock,server_hostname='wrong.example')
|
||||
except ssl.SSLCertVerificationError:rejected=True
|
||||
check(rejected,'Wrong ingress hostname accepted');result['wrong_hostname_rejected']=True
|
||||
# Leaf rotation and application-level serial revocation on fresh connections.
|
||||
before=compose('images','-q','api','lb').split()
|
||||
subprocess.run(['python3','scripts/pki.py','--rotate','lb'],cwd=ROOT,check=True,capture_output=True,text=True)
|
||||
old=ROOT/'secrets/operator/old-lb';old.chmod(0o755)
|
||||
for file in old.iterdir():file.chmod(0o444)
|
||||
compose('exec','-T','lb','nginx','-s','reload')
|
||||
wait_for(lambda:status('/health/ready')==200)
|
||||
code="import json,ssl,socket\nctx=ssl.create_default_context(cafile='/trust/ca.crt');ctx.load_cert_chain('/old-lb/tls.crt','/old-lb/tls.key')\naccepted=False\ntry:\n s=ctx.wrap_socket(socket.create_connection(('api',9443),timeout=3),server_hostname='api');s.sendall(b'GET /health/ready HTTP/1.1\\r\\nHost: api\\r\\nConnection: close\\r\\n\\r\\n');accepted=b'200 OK' in s.recv(4096);s.close()\nexcept (OSError,ssl.SSLError):pass\nprint(json.dumps({'revoked_old_leaf_rejected':not accepted}))"
|
||||
old_test=subprocess.run(['docker','compose','run','--rm','--no-deps','-T','-v',str(old)+':/old-lb:ro','security-audit','python','-c',code],cwd=ROOT,capture_output=True,text=True,check=True)
|
||||
leaf=json.loads(old_test.stdout);check(leaf['revoked_old_leaf_rejected'],'Old leaf still authorized')
|
||||
result['leaf_rotation']={**leaf,'new_leaf_works':True,'image_ids_unchanged':compose('images','-q','api','lb').split()==before}
|
||||
# Rotate only API DB password; deny old on a NEW connection and recreate consumers of it.
|
||||
workload=ROOT/'secrets/operator/workloads.json';workload.chmod(0o600);values=json.loads(workload.read_text())
|
||||
old_url=values['api']['DATABASE_URL'];old_password=urllib.parse.urlsplit(old_url).password
|
||||
new_password=secrets.token_hex(24);new_url=old_url.replace(':'+old_password+'@',':'+new_password+'@')
|
||||
rotation=inside("with psycopg.connect(v['old']) as db:\n db.execute(sql.SQL('ALTER ROLE db_api PASSWORD {}').format(sql.Literal(v['new_password'])))\nold_allowed=True\ntry:\n c=psycopg.connect(v['old'],connect_timeout=3);c.close()\nexcept psycopg.Error:old_allowed=False\nwith psycopg.connect(v['new'],connect_timeout=3) as db:\n ok=db.execute('SELECT current_user').fetchone()[0]=='db_api'\nresult={'old_new_connection_denied':not old_allowed,'new_connection_allowed':ok}",old=old_url,new=new_url,new_password=new_password)
|
||||
values['api']['DATABASE_URL']=new_url;workload.write_text(json.dumps(values));workload.chmod(0o444)
|
||||
password_file=ROOT/'secrets/db_api_password';password_file.chmod(0o600);password_file.write_text(new_password);password_file.chmod(0o444)
|
||||
db_roles=ROOT/'secrets/operator/db-roles.json';db_roles.chmod(0o600);roles=json.loads(db_roles.read_text());roles['db_api']=new_password;db_roles.write_text(json.dumps(roles));db_roles.chmod(0o444)
|
||||
bao_unseal()
|
||||
compose('up','-d','--no-deps','--force-recreate','--wait','--wait-timeout','90','api')
|
||||
wait_for(lambda:status(actor=alice)==200)
|
||||
check(c.call('GET','/api/v1/attachments/'+att['id']+'/content',actor=bob)['bytes']==raw,'Rotation lost original')
|
||||
check(all(rotation.values()),'DB credential rotation failed');result['secret_rotation']={**rotation,'same_session_original_preserved':True,'no_image_rebuild':True}
|
||||
# Accepted work and session remain durable while OpenBao is sealed.
|
||||
compose('stop','worker');worker_stopped=True
|
||||
pending,pending_raw=c.attachment(alice,chat)
|
||||
c.message(alice,chat,'',attachments=[pending['id']])
|
||||
bao_request('PUT','sys/seal',{});sealed=True;started=time.monotonic();observed=[]
|
||||
while time.monotonic()-started<75:
|
||||
code=status(actor=alice);observed.append({'seconds':round(time.monotonic()-started,2),'status':code})
|
||||
if code in (502,503,504):break
|
||||
time.sleep(2)
|
||||
check(observed[-1]['status'] in (502,503,504),'Sealed Bao did not fail closed')
|
||||
live=json.loads(compose('exec','-T','api','python','-c',"import urllib.request,json;r=urllib.request.urlopen('http://127.0.0.1:8080/health/live');print(json.dumps({'status':r.status}))"))
|
||||
check(live['status']==200,'Secret outage broke liveness')
|
||||
bao_unseal();sealed=False
|
||||
wait_for(lambda:status(actor=alice)==200)
|
||||
compose('up','-d','--no-deps','worker');worker_stopped=False
|
||||
c.wait_ready(bob,pending)
|
||||
check(c.call('GET','/api/v1/attachments/'+pending['id']+'/content',actor=bob)['bytes']==pending_raw,'Accepted work lost across seal')
|
||||
result['bao_sealed']={'polls':observed,'cache_budget_seconds_max':60,'liveness':200,'same_accepted_job_session_recovered':True}
|
||||
# Positive-control telemetry and absence of a secret/body canary.
|
||||
canary='private-body-canary-'+secrets.token_hex(12)
|
||||
c.message(alice,chat,canary)
|
||||
raw=(ROOT/'tests/fixtures/sample.png').read_bytes()
|
||||
response=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=private.png',202,actor=alice,raw=raw,headers={'Content-Type':'image/png'},schema='Attachment')
|
||||
traced=response['json'];trace_id=response['headers']['X-Trace-Id'];c.wait_ready(bob,traced)
|
||||
def find_trace():
|
||||
value=backend_get(3200,'/api/traces/'+trace_id)
|
||||
names=[]
|
||||
def walk(item):
|
||||
if isinstance(item,dict):
|
||||
if 'spanId' in item:names.append(item.get('name'))
|
||||
for v in item.values():walk(v)
|
||||
elif isinstance(item,list):
|
||||
for v in item:walk(v)
|
||||
walk(value)
|
||||
return value if {'attachments.publish','attachments.consume','s3.put','postgres.query'}<=set(names) else None
|
||||
trace=wait_for(find_trace,60);save('secure-upload-trace.json',trace)
|
||||
def logs(query):
|
||||
args=urllib.parse.urlencode({'query':query,'limit':100,'start':str(time.time_ns()-900_000_000_000)})
|
||||
return backend_get(3100,'/loki/api/v1/query_range?'+args)
|
||||
positive=wait_for(lambda: (lambda x:x if {'messenger-api','messenger-worker'}<={s['stream'].get('service_name') for s in x['data']['result']} else None)(logs('{service_name=~"messenger-.*"} |= "'+trace_id+'"')),60)
|
||||
save('secure-upload-logs.json',positive)
|
||||
negative=logs('{service_name=~"messenger-.*"} |= "'+canary+'"')
|
||||
check(not negative['data']['result'],'Message body leaked into telemetry')
|
||||
result['telemetry_privacy']={'trace_id':trace_id,'api_worker_positive_control':True,'body_canary_matches':0}
|
||||
# Actual logout invalidates the current server-side session.
|
||||
c.call('DELETE','/api/v1/auth/sessions/current',204,actor=eve)
|
||||
c.call('GET','/api/v1/users/me',401,actor=eve)
|
||||
result['acl_logout']={'outsider_metadata_content_binding':404,'forged_header_ignored':True,'logout':401}
|
||||
result['result']='PASS';save('security-lifecycle.json',result)
|
||||
print('PASS: security-lifecycle.json and secure trace/log proof',flush=True)
|
||||
finally:
|
||||
if sealed:bao_unseal()
|
||||
if worker_stopped:compose('up','-d','--no-deps','worker')
|
||||
|
||||
|
||||
if __name__=='__main__':main()
|
||||
Reference in New Issue
Block a user