07Python · executable cell
PYTHON · Code cell
# =====================================================================
# K19 | Code cell 03 | K19 · Certificate revocation lifecycle
# Purpose: revocation
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import datetime, subprocess, tempfile
from pathlib import Path
from cryptography import x509
from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
# Define the reusable operation certificates; keep its logic separate from the trial.
def certificates(directory):
p=Path(directory);now=datetime.datetime.now(datetime.timezone.utc);key=ec.generate_private_key(ec.SECP256R1());ca=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'PSUT temporary CA')]);
def write(label,k,c):
(p/(label+'.pem')).write_bytes(c.public_bytes(serialization.Encoding.PEM)); f=p/(label+'.key');f.write_bytes(k.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()));f.chmod(0o600)
def cert(name,k,root=False,server=False):
b=x509.CertificateBuilder().subject_name(name).issuer_name(ca).public_key(k.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now-datetime.timedelta(minutes=1)).not_valid_after(now+datetime.timedelta(hours=1)).add_extension(x509.BasicConstraints(ca=root,path_length=0 if root else None),critical=True).add_extension(x509.SubjectKeyIdentifier.from_public_key(k.public_key()),False).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False).add_extension(x509.KeyUsage(digital_signature=not root,content_commitment=False,key_encipherment=False,data_encipherment=False,key_agreement=False,key_cert_sign=root,crl_sign=root,encipher_only=None,decipher_only=None),True)
if not root:
b=b.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH if server else ExtendedKeyUsageOID.CLIENT_AUTH]),False)
if server:b=b.add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]),False)
return b.sign(key,hashes.SHA256())
root=cert(ca,key,True);write('ca',key,root);issued={}
for name in ('localhost','sensor','viewer'):
k=ec.generate_private_key(ec.SECP256R1());c=cert(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,name)]),k,server=name=='localhost');write(name,k,c);issued[name]=c
def crl(revoke):
b=x509.CertificateRevocationListBuilder().issuer_name(ca).last_update(now-datetime.timedelta(minutes=1)).next_update(now+datetime.timedelta(hours=1)).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False).add_extension(x509.CRLNumber(2 if revoke else 1),False)
if revoke:b=b.add_revoked_certificate(x509.RevokedCertificateBuilder().serial_number(issued['sensor'].serial_number).revocation_date(now).build())
return b.sign(key,hashes.SHA256()).public_bytes(serialization.Encoding.PEM)
(p/'valid.crl').write_bytes(crl(False));(p/'revoked.crl').write_bytes(crl(True))
# Define the reusable operation revocation; keep its logic separate from the trial.
def revocation():
with tempfile.TemporaryDirectory(prefix='psut-crl-') as tmp:
certificates(tmp);p=Path(tmp);checks=[]
for label,crl,identity,expected in [('initial client valid','valid','sensor',True),('retired client revoked','revoked','sensor',False),('unrevoked viewer valid','revoked','viewer',True)]:
r=subprocess.run(['openssl','verify','-CAfile',str(p/'ca.pem'),'-CRLfile',str(p/(crl+'.crl')),'-crl_check','-purpose','sslclient',str(p/(identity+'.pem'))],capture_output=True,text=True,timeout=10)
msg=(r.stdout+r.stderr).replace(tmp,'<temporary>');passed=r.returncode==0 if expected else r.returncode!=0 and 'certificate revoked' in msg.lower();checks.append({'name':label,'pass':passed,'exit':r.returncode,'observation':msg.strip()})
return {'source':'actual OpenSSL CRL verification','checks':checks,'pass':all(x['pass'] for x in checks),'limitation':'CRL check must be enabled at relying party. This is not automatic distribution or session termination.'}
Ask Dr. Mohammad about this cell10Instructions · Markdown
## Original portal implementation (reference only)
These are the actual laboratory snippets. They are retained for comparison; follow the portal setup for WSL, hardware or services. They are **not** executed by Run all.
```bash
cd ~/kali-labs
python3 security_extensions.py revocation
```
```python
#!/usr/bin/env python3
"""Defensive coursework with fictional records, temporary keys and local certificate files only."""
import argparse, csv, datetime, hashlib, hmac, json, math, os, platform, secrets, ssl, statistics, subprocess, tempfile, time
from pathlib import Path
from cryptography import x509
from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import ascon_course as ascon
def benchmark():
key=secrets.token_bytes(16); aes=AESGCM(key); ad=b'PSUT fictional telemetry'; rows=[]
# Same payload, AAD and paired trial counts. Unique nonces within each algorithm.
# Distinct algorithms and implementations, not an isolated algorithm comparison.
ak=secrets.token_bytes(16)
for size in (32,128,512,1024):
msg=b'x'*size
for trial in range(110):
order=('AES-GCM','Ascon-AEAD128') if trial%2==0 else ('Ascon-AEAD128','AES-GCM')
for name in order:
n=(size*1000+trial).to_bytes(12 if name=='AES-GCM' else 16,'big')
t=time.perf_counter_ns()
if name=='AES-GCM': c=aes.encrypt(n,msg,ad);plain=aes.decrypt(n,c,ad)
else:c=ascon.encrypt(ak,n,ad,msg);plain=ascon.decrypt(ak,n,ad,c)
elapsed=(time.perf_counter_ns()-t)/1000
assert plain==msg and len(c)==size+16
if trial>=10:rows.append([name,size,trial-9,elapsed,len(c),len(n)])
with open('aead-comparison.csv','x',newline='') as f:
w=csv.writer(f);w.writerow(['algorithm','payload_bytes','trial','combined_us','ciphertext_tag_bytes','nonce_bytes']);w.writerows(rows)
summaries=[]
for name in ('AES-GCM','Ascon-AEAD128'):
for size in (32,128,512,1024):
t=sorted(r[3] for r in rows if r[0]==name and r[1]==size);summaries.append({'algorithm':name,'bytes':size,'n':len(t),'median_us':statistics.median(t),'p95_us':t[math.ceil(.95*len(t))-1]})
return {'provenance':'actual host timing, synthetic payload','pass':True,'trials':len(rows),'python':platform.python_version(),'machine':platform.machine(),'openssl':ssl.OPENSSL_VERSION,'warmups':10,'summary':summaries,'limitations':'Python teaching Ascon versus cryptography native AES-GCM; not an algorithm-only, MCU, energy or memory comparison. No memory measurements collected.'}
def certificates(directory):
p=Path(directory);now=datetime.datetime.now(datetime.timezone.utc);key=ec.generate_private_key(ec.SECP256R1());ca=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'PSUT temporary CA')]);
def write(label,k,c):
(p/(label+'.pem')).write_bytes(c.public_bytes(serialization.Encoding.PEM)); f=p/(label+'.key');f.write_bytes(k.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()));f.chmod(0o600)
def cert(name,k,root=False,server=False):
b=x509.CertificateBuilder().subject_name(name).issuer_name(ca).public_key(k.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now-datetime.timedelta(minutes=1)).not_valid_after(now+datetime.timedelta(hours=1)).add_extension(x509.BasicConstraints(ca=root,path_length=0 if root else None),critical=True).add_extension(x509.SubjectKeyIdentifier.from_public_key(k.public_key()),False).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False).add_extension(x509.KeyUsage(digital_signature=not root,content_commitment=False,key_encipherment=False,data_encipherment=False,key_agreement=False,key_cert_sign=root,crl_sign=root,encipher_only=None,decipher_only=None),True)
if not root:
b=b.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH if server else ExtendedKeyUsageOID.CLIENT_AUTH]),False)
if server:b=b.add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]),False)
return b.sign(key,hashes.SHA256())
root=cert(ca,key,True);write('ca',key,root);issued={}
for name in ('localhost','sensor','viewer'):
k=ec.generate_private_key(ec.SECP256R1());c=cert(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,name)]),k,server=name=='localhost');write(name,k,c);issued[name]=c
def crl(revoke):
b=x509.CertificateRevocationListBuilder().issuer_name(ca).last_update(now-datetime.timedelta(minutes=1)).next_update(now+datetime.timedelta(hours=1)).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False).add_extension(x509.CRLNumber(2 if revoke else 1),False)
if revoke:b=b.add_revoked_certificate(x509.RevokedCertificateBuilder().serial_number(issued['sensor'].serial_number).revocation_date(now).build())
return b.sign(key,hashes.SHA256()).public_bytes(serialization.Encoding.PEM)
(p/'valid.crl').write_bytes(crl(False));(p/'revoked.crl').write_bytes(crl(True))
def revocation():
with tempfile.TemporaryDirectory(prefix='psut-crl-') as tmp:
certificates(tmp);p=Path(tmp);checks=[]
for label,crl,identity,expected in [('initial client valid','valid','sensor',True),('retired client revoked','revoked','sensor',False),('unrevoked viewer valid','revoked','viewer',True)]:
r=subprocess.run(['openssl','verify','-CAfile',str(p/'ca.pem'),'-CRLfile',str(p/(crl+'.crl')),'-crl_check','-purpose','sslclient',str(p/(identity+'.pem'))],capture_output=True,text=True,timeout=10)
msg=(r.stdout+r.stderr).replace(tmp,'<temporary>');passed=r.returncode==0 if expected else r.returncode!=0 and 'certificate revoked' in msg.lower();checks.append({'name':label,'pass':passed,'exit':r.returncode,'observation':msg.strip()})
return {'source':'actual OpenSSL CRL verification','checks':checks,'pass':all(x['pass'] for x in checks),'limitation':'CRL check must be enabled at relying party. This is not automatic distribution or session termination.'}
def gateway():
key=secrets.token_bytes(32);highest=0;logs=[];accepted=[]
def packet(seq,temp):
raw=json.dumps({'device':'demo-01','seq':seq,'temperature':temp},separators=(',',':'),allow_nan=False).encode();return raw,hmac.digest(key,raw,'sha256')
def check(raw,tag):
nonlocal highest
if len(raw)>512 or not hmac.compare_digest(hmac.digest(key,raw,'sha256'),tag):return 'integrity-rejected'
try:d=json.loads(raw);good=type(d)==dict and set(d)=={'device','seq','temperature'} and d['device']=='demo-01' and type(d['seq']) is int and 1<=d['seq']<=2**31-1 and type(d['temperature']) in (int,float) and math.isfinite(d['temperature']) and -40<=d['temperature']<=80
except (ValueError,TypeError,OverflowError):good=False
if not good:return 'schema-rejected'
if d['seq']<=highest:return 'replay-rejected'
highest=d['seq'];accepted.append(d);return 'accepted'
good=packet(1,25);bad=packet(2,30);tests=[('positive',*good,'accepted'),('duplicate',*good,'replay-rejected'),('tampered',bad[0]+b' ',bad[1],'integrity-rejected'),('invalid range',*packet(2,90),'schema-rejected'),('recovery',*packet(2,26),'accepted')]
for label,raw,tag,expected in tests:
actual=check(raw,tag);logs.append({'case':label,'decision':actual,'expected':expected,'pass':actual==expected})
counts={x:sum(r['decision']==x for r in logs) for x in set(r['decision'] for r in logs)}
# Deliberately bounded local rule; no real broker logs are claimed.
return {'source':'actual local gateway policy evaluation of fictional cases','pass':all(x['pass'] for x in logs),'events':logs,'accepted':accepted,'decision_counts':counts,'alert':sum(v for k,v in counts.items() if k!='accepted')>=3,'limitations':'In-memory state, synthetic event monitor, no production gateway or live broker integration. Range checks do not detect all malicious readings.'}
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('experiment',choices=['benchmark','revocation','gateway']);args=p.parse_args();r=globals()[args.experiment]();print(json.dumps(r,indent=2));raise SystemExit(0 if r['pass'] else 1)
```