PYTHON · Code cell
# =====================================================================
# K07 | Code cell 02 | K07 · Authenticated freshness & replay protection
# 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 hmac, json, secrets, 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)}
# Define the reusable operation replay; keep its logic separate from the trial.
def replay():
key=secrets.token_bytes(32); highest={}; now=1000 # fixed teaching clock for deterministic test
def sign(seq,stamp):
payload=json.dumps({'device':'demo-01','seq':seq,'timestamp':stamp,'temperature':25},sort_keys=True,separators=(',',':')).encode();return payload,hmac.digest(key,payload,'sha256')
def verify(packet):
payload,tag=packet
if not hmac.compare_digest(tag,hmac.digest(key,payload,'sha256')):return 'invalid tag'
d=json.loads(payload)
if abs(now-d['timestamp'])>30:return 'stale timestamp'
if d['seq']<=highest.get(d['device'],0):return 'replay'
highest[d['device']]=d['seq'];return 'accepted'
a=sign(1,now); cases=[('fresh',a,'accepted'),('duplicate',a,'replay'),('stale',sign(2,900),'stale timestamp'),('altered',(sign(2,now)[0],a[1]),'invalid tag'),('fresh next',sign(2,now),'accepted')]
return save('K07-REPLAY',[check(n,(observed:=verify(p))==expected,observed) for n,p,expected in cases])