Secure messenger with TLS identities, scoped OpenBao secrets and worker compromise experiments
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Grade5 track1: copied worker credentials, bounded probes, quarantine/revoke/recover."""
|
||||
import concurrent.futures,importlib.util,json,os,shutil,subprocess,sys,threading,time,urllib.parse,uuid
|
||||
from pathlib import Path
|
||||
ROOT=Path(__file__).resolve().parents[1];sys.path.insert(0,str(ROOT/'tests'));from client import Client,check
|
||||
s=importlib.util.spec_from_file_location('sec',ROOT/'student-tests/security.py');sec=importlib.util.module_from_spec(s);s.loader.exec_module(sec)
|
||||
s=importlib.util.spec_from_file_location('rot',ROOT/'scripts/rotate.py');rot=importlib.util.module_from_spec(s);s.loader.exec_module(rot)
|
||||
op=rot.op;BASE=sec.BASE
|
||||
|
||||
def main():
|
||||
c=Client(BASE,ca_file=sec.CA);a,b,outsider,chat=c.bootstrap();result={'model':'exfiltrated live worker leaf+service credentials, no host/Docker/CA compromise; operator probes use only selected worker identity; baseline is a deliberately overprivileged test fixture, never mounted into runtime worker','images_before':sec.dc('images','-q','worker').splitlines()}
|
||||
raw=sec.dc('exec','-T','worker','cat','/run/runtime/active.json');active=json.loads(raw)
|
||||
db=urllib.parse.urlparse(active['database_url']);broker=urllib.parse.urlparse(active['broker_url'])
|
||||
stolen={'worker':{'db_password':db.password,'broker_password':broker.password,'s3_access_key_id':active['s3_access_key_id'],'s3_secret_access_key':active['s3_secret_access_key']}}
|
||||
(op.OP/'stolen-worker.json').write_text(json.dumps(stolen));os.chmod(op.OP/'stolen-worker.json',0o600)
|
||||
d=ROOT/'certs/private/stolen-worker'
|
||||
if d.exists():shutil.rmtree(d)
|
||||
shutil.copytree(ROOT/'certs/private/worker',d)
|
||||
defaults={'Role':'worker','Cert':'stolen-worker','CredentialsFile':'/operator/stolen-worker.json'}
|
||||
probe=lambda **kw:sec.probe(**dict(defaults,**kw))
|
||||
# A pre-separation model with API SQL credentials/root S3 credentials allows broader access.
|
||||
broad=json.loads((op.OP/'credentials.json').read_text());broad['baseline']={'s3_access_key_id':broad['s3_root_user'],'s3_secret_access_key':broad['s3_root_password']};(op.OP/'baseline-worker.json').write_text(json.dumps({'baseline':broad['baseline']}));os.chmod(op.OP/'baseline-worker.json',0o600)
|
||||
result['before_least_privilege']={'password_table':sec.probe(Kind='postgres',Role='api',Cert='stolen-worker',Query='SELECT password_hash FROM users LIMIT 1'),'bucket_administration':sec.probe(Kind='s3',Role='baseline',Cert='stolen-worker',CredentialsFile='/operator/baseline-worker.json',Method='LIST_BUCKETS')}
|
||||
assert all(x['ok'] for x in result['before_least_privilege'].values())
|
||||
sec.dc('stop','worker') # quarantine before new secrets become visible to replacement
|
||||
att,data=c.attachment(a,chat);accepted=[(att,data)]
|
||||
stage=sec.sql_value("SELECT staging_key FROM attachments WHERE id='"+att['id']+"'")
|
||||
marker='originals/security-probe-'+uuid.uuid4().hex+'/marker'
|
||||
good={'db_pipeline':probe(Kind='postgres',Query='SELECT job_id FROM pipeline_jobs LIMIT 1'),'db_execution_update':probe(Kind='postgres',Query="UPDATE attachments SET status=status WHERE id='"+att['id']+"'"),'s3_staging':probe(Kind='s3',Key=stage),'s3_final_put':probe(Kind='s3',Method='PUT',Key=marker,Body='synthetic allowed scope'),'queue_ping':probe(Kind='redis',Command=['PING'])}
|
||||
assert all(x['ok'] for x in good.values()),good
|
||||
denied={}
|
||||
for name,query in [('password_table','SELECT password_hash FROM users'),('sessions','SELECT token_hash FROM sessions'),('messages','SELECT text FROM messages'),('change_owner',"UPDATE attachments SET owner_id=owner_id WHERE false"),('change_checksum',"UPDATE attachments SET sha256=sha256 WHERE false"),('drop_table','BEGIN; DROP TABLE users; ROLLBACK;')]:
|
||||
denied[name]=probe(Kind='postgres',Query=query);assert not denied[name]['ok'] and denied[name].get('error_category')=='permission_denied',(name,denied[name])
|
||||
for name,args in [('s3_private_prefix',{'Kind':'s3','Method':'PUT','Key':'private/blocked','Body':'synthetic'}),('s3_staging_write',{'Kind':'s3','Method':'PUT','Key':'staging/blocked','Body':'synthetic'}),('s3_final_delete',{'Kind':'s3','Method':'DELETE','Key':marker}),('bucket_administration',{'Kind':'s3','Method':'LIST_BUCKETS'}),('queue_publish',{'Kind':'redis','Command':['XADD','attachment.jobs.v1','*','payload','{}']}),('queue_flush',{'Kind':'redis','Command':['FLUSHALL']}),('queue_other_key',{'Kind':'redis','Command':['XREADGROUP','GROUP','image-workers','probe','STREAMS','other.stream','>']})]:
|
||||
denied[name]=probe(**args);assert not denied[name]['ok'] and denied[name].get('error_category')=='permission_denied',(name,denied[name])
|
||||
login=op.request('POST','auth/cert/login',{'name':'worker'},cert='worker')['auth'];oldtoken=login['client_token'];accessor=login['accessor']
|
||||
try:op.request('GET','kv/data/api',token=oldtoken,cert='worker')
|
||||
except RuntimeError:denied['bao_api_secret']={'ok':False,'error_category':'policy_denied'}
|
||||
else:raise AssertionError('worker read API secret')
|
||||
for _ in range(7):accepted.append(c.attachment(a,chat))
|
||||
result['accepted_while_quarantined']=len(accepted);result['least_privilege']={'allowed':good,'denied':denied}
|
||||
stop=threading.Event();traffic=[]
|
||||
def send():
|
||||
client=Client(BASE,ca_file=sec.CA)
|
||||
while not stop.is_set():
|
||||
try:client.message(a,chat,'Synthetic during worker revocation');traffic.append(True)
|
||||
except Exception:traffic.append(False)
|
||||
time.sleep(.05)
|
||||
pool=concurrent.futures.ThreadPoolExecutor(2);tasks=[pool.submit(send) for _ in range(2)]
|
||||
start=time.monotonic();root=json.loads((op.OP/'init.json').read_text())['root_token']
|
||||
try:
|
||||
rot.revoke('worker');op.request('DELETE','auth/cert/certs/worker',token=root);op.request('POST','auth/token/revoke-accessor',{'accessor':accessor},root)
|
||||
after={}
|
||||
after['old_cert_queue']=probe(Kind='redis',Command=['PING']);after['old_cert_s3']=probe(Kind='s3',Key=stage)
|
||||
assert not after['old_cert_queue']['ok'] and not after['old_cert_s3']['ok']
|
||||
try:op.request('GET','kv/data/worker',token=oldtoken,cert='stolen-worker')
|
||||
except RuntimeError:after['old_bao_token_denied']=True
|
||||
else:raise AssertionError('revoked Bao token accepted')
|
||||
rot.rotate('worker',certificate=True)
|
||||
# Use a NEW accepted TLS identity to prove the old SQL password itself is revoked.
|
||||
after['old_sql_password']=probe(Kind='postgres',Cert='worker',Query='SELECT 1');assert not after['old_sql_password']['ok'] and after['old_sql_password'].get('error_category')=='credential_denied'
|
||||
sec.dc('up','-d','--no-deps','--force-recreate','worker')
|
||||
for attachment,original in accepted:
|
||||
ready=c.wait_ready(a,attachment);download=c.call('GET','/api/v1/attachments/'+attachment['id']+'/content',actor=a);check(download['bytes']==original,'accepted original changed')
|
||||
elapsed=time.monotonic()-start;result['after_revocation']=after
|
||||
finally:stop.set();pool.shutdown(wait=True)
|
||||
result.update(recovery_all_ready_seconds=round(elapsed,3),all_accepted_originals_identical=True,background_messages_success=sum(traffic),background_messages_errors=len(traffic)-sum(traffic),images_after=sec.dc('images','-q','worker').splitlines(),new_worker_connects=sec.probe(Kind='redis',Role='worker',Cert='worker',Command=['PING']))
|
||||
assert result['images_before']==result['images_after'] and result['new_worker_connects']['ok']
|
||||
(ROOT/'evidence/worker-compromise.json').write_text(json.dumps(result,indent=2)+'\n');print('PASS: bounded worker compromise, before/after least privilege, actual identity/SQL revocation, fresh worker restored all accepted bytes; no image rebuild',flush=True)
|
||||
if __name__=='__main__':main()
|
||||
Reference in New Issue
Block a user