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.
68 lines
3.4 KiB
Python
68 lines
3.4 KiB
Python
"""Explicit operator init/unseal/configure. Root and shares only on protected host."""
|
|
import json
|
|
import ssl
|
|
from pathlib import Path
|
|
import urllib.request
|
|
import urllib.error
|
|
import os
|
|
from pki import ROOT
|
|
|
|
URL=os.environ.get('BAO_OPERATOR_URL','https://localhost:18207')
|
|
def call(path,data=None,token=None,method=None):
|
|
ctx=ssl.create_default_context(cafile=str(ROOT/'operator/ca.crt'))
|
|
ctx.load_cert_chain(str(ROOT/'pki/operator/tls.crt'),str(ROOT/'pki/operator/tls.key'))
|
|
headers={'Content-Type':'application/json'}
|
|
if token:headers['X-Vault-Token']=token
|
|
req=urllib.request.Request(URL+'/v1/'+path,data=None if data is None else json.dumps(data).encode(),headers=headers,method=method)
|
|
op=urllib.request.build_opener(urllib.request.ProxyHandler({}),urllib.request.HTTPSHandler(context=ctx))
|
|
with op.open(req,timeout=60 if path in ["sys/init","sys/unseal"] else 5) as r:return json.load(r) if r.status!=204 else {}
|
|
|
|
def unseal():
|
|
init=ROOT/'operator/bao-init.json'
|
|
if not call('sys/init')['initialized']:
|
|
if init.exists():
|
|
import shutil
|
|
shutil.copyfile(init,ROOT/'operator/bao-init.previous.json')
|
|
(ROOT/'operator/bao-init.previous.json').chmod(0o600)
|
|
info=call('sys/init',{'secret_shares':3,'secret_threshold':2})
|
|
init.write_text(json.dumps(info));init.chmod(0o600)
|
|
data=json.loads(init.read_text())
|
|
if call('sys/seal-status')['sealed']:
|
|
for key in data['keys'][:2]:call('sys/unseal',{'key':key})
|
|
return data['root_token']
|
|
|
|
def configure():
|
|
root=unseal()
|
|
mounts=call('sys/mounts',token=root)
|
|
if 'secret/' not in mounts:call('sys/mounts/secret',{'type':'kv','options':{'version':'2'}},root)
|
|
auth=call('sys/auth',token=root)
|
|
if 'cert/' not in auth:call('sys/auth/cert',{'type':'cert'},root)
|
|
audits=call('sys/audit',token=root)
|
|
assert 'file/' in audits, 'Declarative audit device must be enabled'
|
|
settings=json.loads((ROOT/'operator/settings.json').read_text())
|
|
for role in ['api','worker','dispatcher']:
|
|
policy=(ROOT/'infra/openbao/policies'/(role+'.hcl')).read_text()
|
|
call('sys/policies/acl/'+role,{'policy':policy},root)
|
|
# Exact leaf pinning: another valid certificate from the same CA cannot impersonate this service.
|
|
call('auth/cert/certs/'+role,{'certificate':(ROOT/'pki'/role/'tls.crt').read_text(),'token_policies':[role],'token_ttl':'20s','token_max_ttl':'20s','token_no_default_policy':True},root)
|
|
db='postgresql://db_'+role+':'+settings[role]+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/tls/ca.crt'
|
|
values={'DATABASE_URL':db}
|
|
if role=='api':
|
|
values['CACHE_URL']='rediss://api:'+settings['cache']+'@redis:8443/0'
|
|
else:
|
|
values['BROKER_URL']='rediss://'+role+':'+settings['broker_'+role]+'@broker:8443/0'
|
|
if role in ['api','worker']:
|
|
values['S3_ACCESS_KEY_ID']=settings['s3_'+role+'_key'];values['S3_SECRET_ACCESS_KEY']=settings['s3_'+role]
|
|
call('secret/data/'+role,{'data':values},root)
|
|
print('OpenBao initialized/unsealed by explicit operator action; scoped service policies and 20s certificate-auth tokens configured.')
|
|
|
|
if __name__=='__main__':
|
|
import sys
|
|
if '--unseal-only' in sys.argv:
|
|
import time
|
|
for _ in range(60):
|
|
try:call('sys/init');break
|
|
except Exception:time.sleep(.3)
|
|
unseal();print('OpenBao unsealed by operator.')
|
|
else:configure()
|