ЛР 7 — БВТ2303 — Брезгунова — на 5
Skeleton contracts / contracts (pull_request) Blocked by required conditions
Lab7 solution / integration (pull_request) Blocked by required conditions

This commit is contained in:
2026-12-04 17:07:57 +03:00
parent 20afc2c790
commit ee9d70af85
129 changed files with 81564 additions and 90 deletions
+106
View File
@@ -0,0 +1,106 @@
"""Operator actions for bounded seal and compromised worker campaign."""
import json
from pathlib import Path
import secrets
import shutil
import sys
import time
import urllib.error
from cryptography import x509
ROOT=Path(__file__).resolve().parents[1]
sys.path.insert(0,str(ROOT/'scripts'))
sys.path.insert(0,str(ROOT/'student-tests'))
from bootstrap import bao,root_token,value,configure,database
from security import scoped,request,broker,storage,database as connect,context,tls_probe
from pki import issue
def revoke():
auth,values=scoped('worker')
old=ROOT/'secrets/tls/retired-worker'
old.mkdir(exist_ok=True)
for name in ('cert.crt','key.key'):
shutil.copyfile(ROOT/'secrets/tls/worker'/name,old/name)
cert=x509.load_pem_x509_certificate((old/'cert.crt').read_bytes())
path=ROOT/'pki/revoked.json'
revoked=json.loads(path.read_text());revoked.append(str(cert.serial_number));path.write_text(json.dumps(revoked))
bao('auth/cert/certs/worker',token=root_token(),method='DELETE')
bao('auth/token/revoke',{'token':auth['client_token']},root_token())
# Operator retains old synthetic credentials only for explicit fresh-connection tests.
(ROOT/'secrets/operator/retired-worker.json').write_text(json.dumps({'token':auth['client_token'],'values':values}))
print('Worker identity revoked at gateway and Bao; old secret retained privately for negative tests.')
def rotate():
for kind in ('db_password','s3_secret','broker_password'):
(ROOT/'secrets'/('worker_'+kind)).write_text(secrets.token_hex(24))
issue('worker',force=True)
# Persist broker password rotation and apply using a different operator identity.
old=json.loads((ROOT/'secrets/operator/retired-worker.json').read_text())['values']
import redis
r=redis.Redis(host='broker',port=6380,username='operator',password=value('operator_broker_password'),ssl=True,
ssl_ca_certs=str(ROOT/'pki/ca.crt'),ssl_certfile=str(ROOT/'secrets/tls/operator/cert.crt'),ssl_keyfile=str(ROOT/'secrets/tls/operator/key.key'),ssl_check_hostname=True)
acl=ROOT/'secrets/broker.acl'
import re
s=acl.read_text();s=re.sub(r'(user worker on >)\S+',lambda m:m[1]+value('worker_broker_password'),s);acl.write_text(s)
r.execute_command('ACL','LOAD')
configure()
database()
print('New worker leaf and scoped DB/broker/S3 secrets issued without image rebuild.')
def old_denied():
from client import check
old=json.loads((ROOT/'secrets/operator/retired-worker.json').read_text())
denied=[]
try:
request('retired-worker','auth/cert/login',{'name':'worker'})
raise AssertionError('old cert reauthenticated')
except urllib.error.HTTPError as error:
check(error.code in (400,403),'unexpected Bao denial');denied.append('old cert auth denied')
try:
request('retired-worker','secret/data/worker',token=old['token'])
raise AssertionError('old token still authorized')
except urllib.error.HTTPError as error:
check(error.code==403,'unexpected old token denial');denied.append('old token denied')
accepted,_=tls_probe('broker',6380,'retired-worker',b'*1\r\n$4\r\nPING\r\n')
check(not accepted,'old certificate accepted by broker gateway');denied.append('old serial denied by gateway')
try:
with connect(old['values']['DATABASE_URL']):pass
raise AssertionError('old DB secret accepted')
except Exception as error:
check(type(error).__name__=='OperationalError','unexpected DB failure');denied.append('old DB password denied')
try:
storage(old['values']).list_objects_v2(Bucket='messenger-attachments',Prefix='results/')
raise AssertionError('old S3 secret accepted')
except Exception as error:
check(type(error).__name__=='ClientError','unexpected S3 failure');denied.append('old S3 secret denied')
_,new=scoped('worker');check(broker('worker',new).ping(),'new worker broker credentials fail')
try:
broker('worker',old['values']).ping()
raise AssertionError('old broker password accepted with new valid certificate')
except Exception as error:
check(type(error).__name__=='AuthenticationError','unexpected broker failure');denied.append('old broker password denied')
(ROOT/'evidence/rotation.json').write_text(json.dumps({'result':'PASS','denied':denied,'new_worker_cert_auth':True,'new_broker_credentials':True,'images_rebuilt':False},indent=2))
print('PASS: retired leaf/token/DB/S3 denied; new identity authorized.')
if __name__=='__main__':
action=sys.argv[1]
if action=='seal':bao('sys/seal',{},root_token())
elif action=='revoke':revoke()
elif action=='rotate':rotate()
elif action=='old-denied':old_denied()
elif action=='probe-sealed':
import urllib.request
from client import check
req=urllib.request.Request('https://api1:8443/health/ready')
try:
urllib.request.urlopen(req,context=context('lb'),timeout=10)
raise AssertionError('API ready while scoped secrets unavailable')
except urllib.error.HTTPError as error:
check(error.code==503,'unexpected sealed API status')
data=json.load(error)
check(data['error']['request_id']==error.headers['X-Request-Id'],'error correlation absent')
(ROOT/'evidence/bao-sealed-api.json').write_text(json.dumps({'result':'PASS','status':503,'mTLS_identity':'lb','request_id':data['error']['request_id'],'backend':'api1'},indent=2))
print('PASS: sealed Bao causes API 503 on verified mTLS connection.')