Files
mtusi2026lab7/scripts/pki.py
T
Xabenskie 4eca49fe3d
Grade 3 secure application acceptance / secure (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
[+] lab7
2026-11-30 09:09:57 +03:00

88 lines
5.1 KiB
Python
Executable File

#!/usr/bin/env python3
"""Local operator-owned PKI; keys never enter the build context or Git."""
import argparse
import json
import os
from pathlib import Path
import secrets
import subprocess
ROOT=Path(__file__).resolve().parents[1]
BASE=ROOT/'secrets'
ROLES=['lb','api','worker','relay','minio','broker','redis','collector','prometheus','loki','tempo','grafana','openbao','postgres','operator','intruder']
def run(*args):
subprocess.run(['openssl',*map(str,args)],check=True,stdout=subprocess.DEVNULL,stderr=subprocess.PIPE)
def issue(role,ca=None,output=None,days=1):
ca=ca or BASE/'operator'
path=output or BASE/'pki'/role
path.mkdir(parents=True,exist_ok=True)
path.chmod(0o755)
for file in path.iterdir():
if file.is_file(): file.chmod(0o600)
aliases=[role]
if role in ('lb','grafana','openbao','loki','tempo','prometheus'): aliases+=['localhost']
extra=path/'extensions.cnf'
extra.write_text('basicConstraints=critical,CA:FALSE\nkeyUsage=critical,digitalSignature,keyEncipherment\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid,issuer\nextendedKeyUsage=serverAuth,clientAuth\nsubjectAltName='+','.join('DNS:'+alias for alias in aliases)+'\n')
run('req','-new','-newkey','rsa:2048','-nodes','-subj','/CN='+role,'-keyout',path/'tls.key','-out',path/'request.csr')
serial=secrets.randbits(120)
run('x509','-req','-in',path/'request.csr','-CA',ca/'ca.crt','-CAkey',ca/'ca.key','-set_serial',str(serial),'-days',str(days),'-sha256','-extfile',extra,'-out',path/'tls.crt')
(path/'request.csr').unlink();extra.unlink()
for file in path.iterdir(): file.chmod(0o444)
return format(serial,'X')
def bootstrap():
os.umask(0o077)
operator=BASE/'operator';operator.mkdir(parents=True,exist_ok=True)
trust=BASE/'trust';trust.mkdir(parents=True,exist_ok=True);trust.chmod(0o755)
existing=(operator/'ca.crt').exists()
text=subprocess.check_output(['openssl','x509','-in',str(operator/'ca.crt'),'-noout','-text']) if existing else b''
new_ca=not existing or b'Key Usage' not in text
if new_ca:
config=operator/'ca.cnf'
config.write_text('[req]\ndistinguished_name=dn\nx509_extensions=ca\n[dn]\n[ca]\nbasicConstraints=critical,CA:TRUE\nkeyUsage=critical,keyCertSign,cRLSign\nsubjectKeyIdentifier=hash\nauthorityKeyIdentifier=keyid:always\n')
if not (operator/'ca.key').exists(): run('genrsa','-out',operator/'ca.key','3072')
run('req','-x509','-key',operator/'ca.key','-days','30','-sha256','-subj','/CN=lab7-local-ca','-config',config,'-out',operator/'ca.crt')
if (trust/'ca.crt').exists(): (trust/'ca.crt').chmod(0o600)
(trust/'ca.crt').write_bytes((operator/'ca.crt').read_bytes());(trust/'ca.crt').chmod(0o444)
if not (trust/'revoked.json').exists():
(trust/'revoked.json').write_text('[]\n');(trust/'revoked.json').chmod(0o444)
for role in ROLES:
leaf=BASE/'pki'/role/'tls.crt'
leaf_text=subprocess.check_output(['openssl','x509','-in',str(leaf),'-noout','-text']) if leaf.exists() else b''
expiring=leaf.exists() and subprocess.run(['openssl','x509','-in',str(leaf),'-noout','-checkend','3600'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL).returncode!=0
if new_ca or b'Authority Key Identifier' not in leaf_text or expiring: issue(role)
# Untrusted CA is used only by negative tests; its keys remain operator-owned.
foreign=operator/'foreign';foreign.mkdir(exist_ok=True)
foreign_cert=foreign/'leaf/tls.crt'
foreign_expiring=not foreign_cert.exists() or subprocess.run(['openssl','x509','-in',str(foreign_cert),'-noout','-checkend','3600'],stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL).returncode!=0
if not (foreign/'ca.key').exists() or foreign_expiring:
for file in [foreign/'ca.key',foreign/'ca.crt']:
if file.exists(): file.chmod(0o600)
run('req','-x509','-newkey','rsa:2048','-nodes','-days','2','-sha256','-subj','/CN=foreign-test-ca','-keyout',foreign/'ca.key','-out',foreign/'ca.crt')
issue('lb',foreign,foreign/'leaf')
operator.chmod(0o700)
print('Local CA/role certificates ready; private values hidden.')
if __name__=='__main__':
parser=argparse.ArgumentParser();parser.add_argument('--rotate',choices=ROLES);args=parser.parse_args()
if args.rotate:
path=BASE/'pki'/args.rotate
old=BASE/'operator'/('old-'+args.rotate);old.mkdir(exist_ok=True)
for name in ('tls.crt','tls.key'):
if (old/name).exists(): (old/name).chmod(0o600)
(old/name).write_bytes((path/name).read_bytes())
raw=subprocess.check_output(['openssl','x509','-in',str(path/'tls.crt'),'-noout','-serial'],text=True)
revoked=BASE/'trust/revoked.json';values=json.loads(revoked.read_text());values.append(raw.strip().split('=')[1].upper().lstrip('0'))
revoked.chmod(0o600);revoked.write_text(json.dumps(values)+'\n');revoked.chmod(0o444)
# Existing mounted directory sees replacements; leaf files need no image rebuild.
for name in ('tls.crt','tls.key'): (path/name).chmod(0o600)
issue(args.rotate)
print('Rotated leaf; previous serial revoked for new gateway connections.')
else: bootstrap()