PYTHON · Code cell
# =====================================================================
# K11 | Code cell 02 | K11 · Threat modeling & integrated security review
# Purpose: 3. Implementation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import hashlib, json, time
from pathlib import Path
# Set HOME for the next computation or reference condition.
HOME=Path.home()/'.psut-kali-security-v14'
# Define the reusable operation save; keep its logic separate from the trial.
def save(name, tests):
report={'schema':'psut-kali-v14','experiment':name,'source':'local-execution-self-reported','utc':time.strftime('%Y-%m-%dT%H:%M:%SZ',time.gmtime()),'checks':tests}
out=HOME/'evidence'; out.mkdir(parents=True,exist_ok=True,mode=0o700)
(out/(name+'.json')).write_text(json.dumps(report,indent=2)+'\n')
print(json.dumps(report,indent=2)); return all(x['pass'] for x in tests)
# Define the reusable operation check; keep its logic separate from the trial.
def check(name, ok, observation): return {'name':name,'pass':bool(ok),'observation':str(observation)}
# Bounded defensive integration: signed manifest, rollback and strict schema.
def capstone():
"""Bounded defensive integration: signed manifest, rollback and strict schema."""
import math
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import hashes
from cryptography.exceptions import InvalidSignature
def schema(d):
return (isinstance(d,dict) and set(d)=={'device','temperature','humidity'}
and d['device']=='demo-01' and all(type(d[k]) in (float,int) and math.isfinite(d[k]) for k in ('temperature','humidity'))
and -40<=d['temperature']<=80 and 0<=d['humidity']<=100)
valid={'device':'demo-01','temperature':25,'humidity':60}
tests=[check('Valid telemetry schema',schema(valid),'accepted'),check('Extra field rejected',not schema(dict(valid,token='dummy')),'rejected'),check('Out-of-range humidity rejected',not schema(dict(valid,humidity=110)),'rejected'),check('Boolean temperature rejected',not schema(dict(valid,temperature=True)),'rejected')]
key=ec.generate_private_key(ec.SECP256R1());public=key.public_key();current=2
def manifest(version,content):return json.dumps({'version':version,'sha256':hashlib.sha256(content).hexdigest()},sort_keys=True,separators=(',',':')).encode()
def accept(record,signature,content):
try:public.verify(signature,record,ec.ECDSA(hashes.SHA256()))
except InvalidSignature:return 'invalid signature'
data=json.loads(record)
if data['sha256']!=hashlib.sha256(content).hexdigest():return 'digest mismatch'
if data['version']<=current:return 'rollback rejected'
return 'accepted'
artifact=b'fictional update data; not executable';new=manifest(3,artifact);sig=key.sign(new,ec.ECDSA(hashes.SHA256()));old=manifest(1,artifact);old_sig=key.sign(old,ec.ECDSA(hashes.SHA256()))
for name,record,signature,content,expected in [('Signed newer manifest',new,sig,artifact,'accepted'),('Modified manifest',old,sig,artifact,'invalid signature'),('Modified content',new,sig,artifact+b'x','digest mismatch'),('Signed older version',old,old_sig,artifact,'rollback rejected')]:
outcome=accept(record,signature,content);tests.append(check(name,outcome==expected,outcome))
return save('K11-INTEGRATED',tests)