Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Cyber Defense StudioIoT Security and PrivacyExperimentsWorkspaces
ENGINEERING WORKSPACE
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
KALI WSL / OPTIONAL SECURITY EXTENSION
IoT Security and Privacy

K20 · Authenticated IoT gateway and defensive monitoring

Ask Dr. Mohammad · K20 →

Enforce bounded authenticated input, per-device freshness and log security decisions with a threshold alert.

← Security range
Design experiment & verify evidence →
K20 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Kali & IoT securityK20 · Authenticated IoT gateway and defensive monitoring

Before you start

Complete K07, K16, K17. Copy security_extensions.py and ascon_course.py into ~/kali-labs; existing toolkit dependencies are sufficient. Use fictional data, normal user and no external targets.

Learning outcome

Enforce bounded authenticated input, per-device freshness and log security decisions with a threshold alert.

Updated Kali toolkit

Predict: Record the expected outcomes before running the program.

K20 · Academic orientation

Scope and objectives

Scope of the experiment

Enforce bounded authenticated input, per-device freshness and log security decisions with a threshold alert.

The focus of this experiment is to trace authenticated IoT gateway messages and defensive monitoring. Students then compare valid, unauthorized and replayed traffic in the local fixture, and reconcile security decisions with captured evidence and recovery controls. The Concepts view explains the operation before the practical work; the Simulation view is used to examine reference and changed inputs, not to substitute for actual measurements.

Learning objectives

  • Trace authenticated IoT gateway messages and defensive monitoring.
  • Compare valid, unauthorized and replayed traffic in the local fixture.
  • Reconcile security decisions with captured evidence and recovery controls.
  • Identify the configured inputs (Rejections required for alert; Traffic scenario; Maximum accepted temperature; Enforce monotonic sequence) and record the corresponding observed outputs with units where applicable.
  • Compare the reference calculation or decision with an independent implementation or authorized observation; state any discrepancy and the applicable model boundary.

Expected learning outcomes

On completion, students can trace authenticated IoT gateway messages and defensive monitoring, compare valid, unauthorized and replayed traffic in the local fixture, and reconcile security decisions with captured evidence and recovery controls.

Required deliverables

Submit the derivation or state trace for the named operation, the exact reference and changed configurations, the associated simulator or practical evidence, and a short validation statement addressing reconcile security decisions with captured evidence and recovery controls. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to IoT threat modelling & risk register.

Environment and experimental methodology

The specified isolated laboratory environment, with local synthetic inputs and authorized services only. Use the experiment-specific setup and verification instructions.

Begin with a manual prediction, record the baseline, change one independent condition at a time, and compare the resulting trace or measurements with the original prediction. Record observations and uncertainty separately from reference values. Follow the experiment’s specific procedure, safety limits, and acceptance checks.

Understand the experiment

Scientific architecture · Authenticated IoT gateway and monitoring

Authenticated gateway monitoring — Sensor / sequence + tag; Gateway / verify and admit; Broker / authorize topic; Monitor / count rejection; Dashboard / audit freshness
Scientific concept map: Sensor message — Sequence + MAC; Gateway — Authentication / freshness; Broker — Authorized topic; Monitor — Anomaly decision; Dashboard — Accepted records / alerts.

Scientific foundations and analytical reasoning

Gateway acceptance requires authenticated input, schema/range checks and freshness. Rejection counters support monitoring, not automatic attribution.

Before operating the equipment or executing the program, derive the expected outcome using the required theoretical work in Experiment. Use the diagram to identify the variables and system boundaries.

Scientific theory · Gateway acceptance and observability

An authenticated gateway validates device identity, schema, ranges and freshness before forwarding telemetry. Each stage can reject a record for a distinct reason. Monitoring counters expose failure patterns, not necessarily their underlying cause; use a unique record identifier for correlation.

Worked example and engineering interpretation

Suppose ten arrivals include two invalid tags, one schema failure and one replay after authentication. If categories are mutually exclusive, six records pass. Compare accepted count with storage acknowledgments; authentication success alone is not end-to-end delivery.

Engineering principles · additional worked teaching example

An authenticated gateway should validate bounded schema and device identity before state changes; repeated failures may produce alerts. A threshold of three failures in a window triggers on third, not necessarily blocks valid messages unless policy states so.

From theory to experiment

Predict the reference result before operating the workbench; check the actual intermediate state, units and constraints. The existing simulation, implementation and procedure below are distinct sources of evidence.

How to investigate K20 · Authenticated IoT gateway and defensive monitoring

Enforce bounded authenticated input, per-device freshness and log security decisions with a threshold alert.

Analytical investigation means collecting an observation, identifying the mechanism, using a calculation or state trace to explain it, and checking your conclusion against evidence. Controlled comparison means changing one independent variable, holding the remaining relevant conditions constant, and measuring a dependent variable against a baseline. Experimental validation means comparing a predicted result to a reproducible observation or assertion; agreement inside a model does not certify hardware. Evidence-based reasoning connects a specific observation to a theoretical rule and states uncertainty, not merely an opinion. Performance characterization records a named metric and its units across conditions; sensitivity analysis changes one parameter across several values. A threat assessment links an asset, threat, consequence and evidence to a mitigation.

Experiment-specific guided practice

Objective: Enforce bounded authenticated input, per-device freshness and log security decisions with a threshold alert.

  1. Use mixed traffic, temperature limit 80 °C, sequence guard enabled, alert threshold 3. Inspect five arrivals: valid, duplicate, changed bytes, temperature 90, valid recovery.
  2. Verify only accepted records are stored and the high-water counter changes only on accepted records.
  3. Raise alert threshold to 4; all gateway decisions remain unchanged, but the alert is not triggered.
  4. Choose all valid traffic, then replays. Compare rejection counts with stored records.

Reference check:

Model boundary:

Independent task and submission evidence

2. Verify only accepted records are stored and the high-water counter changes only on accepted records. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat.

Before execution write the independent variable and its levels, dependent observation with units where applicable, baseline, controlled variables, measurement method and expected result. For a state machine use state/event/output rather than inventing a numeric metric. Record failures and repeat the baseline. A weak conclusion is “it works”; a supported conclusion names the changed setting, observed value/state, corresponding rule and one limitation.

TrialChanged settingFixed settingsPredicted resultActual observation / unitsEvidence / uncertainty
A: baselineReferenceRecordPredictRecordRecord
B: one changeRecordSame as APredictRecordRecord
A: repeatRestoreSame as APredictRecordRecord

Completion: submit the filled table, relevant simulator screenshot or terminal/notebook output, reasoning with units/assumptions, and one limitation. Preserve the independent assessment questions; this guide does not fill their answers.

Worked engineering reasoning and boundary conditions

Engineering reference configuration: Rejections required for alert = 3; Traffic scenario = mixed; Maximum accepted temperature = 80; Enforce monotonic sequence = true. In the classroom model, Accepted = 2; Rejected = 3; Final sequence = 2; Alert = Yes. Alert and storage are computed independently from the same event decisions. Actual HMAC and in-memory policy over fictional samples; no live network gateway.

Use the diagram to follow the calculation or state progression. Keep the teaching configuration separate from the independent exercise values; compare observations with the actual model and implementation.

Concept animation · progressive data plot

Explore the teaching example independently of the simulator. Each step reveals an operation, data relationship or calculated state. The Simulation view has separate editable inputs.

K20 · Authenticated IoT gateway and defensive monitoring: progressive data plot00.751.52.253Accepted sequenceCumulative reject…Alert threshold151

Step 1 of 5 · Observation 1

Observation 1

Accepted sequence
1
Cumulative rejections
0
Alert threshold
3

Teaching example only; inspect live calculations or real practical evidence separately.

Recall the concept before revealing its explanation.

0 / 3 revealed
K20 · 01 / 08What must happen before parsing?Reveal explanation
Engineering explanation

Verify authenticated integrity and bound the message size.

K20 · 02 / 08Why not advance replay state on rejection?Reveal explanation
Engineering explanation

A rejected message must not prevent later valid messages.

K20 · 03 / 08What is the alert limitation?Reveal explanation
Engineering explanation

A synthetic threshold is not a trained IDS or live monitoring service.

K20 · 04 / 08Why verify both authentication and freshness at a gateway?Reveal explanation
Engineering reasoning

Valid tags protect authenticity/integrity, while sequence or time policy helps prevent acceptance of replayed valid messages.

K20 · 05 / 08Why preserve rejection logs without secret data?Reveal explanation
Engineering reasoning

Logs provide evidence for defensive investigation without leaking keys or private credentials.

K20 · 06 / 08A gateway checks authenticated input. Select every technically valid statement. A. Validate bounded input before accepting it. B. Record rejection reasons and apply freshness policy per device. C. Unauthenticated data may advance a trusted sequence safely. D. A threshold alert proves all attacks have been detected.Reveal explanation
Applied scenario

Correct: A. Validate bounded input before accepting it.; B. Record rejection reasons and apply freshness policy per device.

K20 · 07 / 08Which engineering mechanism is tested by K20 · Authenticated IoT gateway and defensive monitoring, and what state or outcome is evaluated?Reveal explanation
Implementation recall

Enforce bounded authenticated input, per-device freshness and log security decisions with a threshold alert.

K20 · 08 / 08For K20 · Authenticated IoT gateway and defensive monitoring, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Run security_extensions.py gateway. Require two accepted records and three rejected decisions with alert true. Input size, HMAC, schema and sequence are checked. This is bounded local policy logic; no live MQTT gateway or IDS deployment.

Loading experiment-specific apparatus…
K20 · Model-linked instrumentation

Visual observation lens

Back to controls ↑

Closed two-condition teaching fixture; actual security validation requires the practical procedure.

Loading instrument…

Awaiting model display.

Experimental instrumentation · A/B

Compare two model conditions

Capture a baseline, change one experimental condition, run the model if required and capture the comparison. Snapshots contain visible controls and display text, not physical sensor readings. Review before exporting.

Open simulation view
Baseline A
Not captured
Comparison B
Not captured

Capture a baseline to begin.

Evidence portfolio →
V19.0 · Contextual AI workspace

Ask your engineering assistants

K20 · current context

Ask Dr. Mohammad locally, or prepare an experiment-aware prompt for ChatGPT, Gemini or Claude. The external providers open in their own tabs; nothing is automatically submitted.

Dr. Mohammad · offline
Dr. Mohammad

Offline curriculum-grounded assistance.

Open local tutor
K20 · Authenticated IoT gateway and defensive monitoring

Public course objective, displayed commands, source excerpts and procedure. Private assessment content is not collected.

Prepare a contextual AI prompt

0 characters

Common secret and email patterns are redacted on preparation; this is not a comprehensive privacy filter. Review the entire editable prompt, including student work and unpublished research, before sharing. The providers apply their own accounts, privacy settings and limits.

Prepare → review → copy & open your selected provider → paste and submit there.

Run & verify — acceptance checklist

Build verification: Actual gateway five controls passed.

Run security_extensions.py gateway. Require two accepted records and three rejected decisions with alert true. Input size, HMAC, schema and sequence are checked. This is bounded local policy logic; no live MQTT gateway or IDS deployment.

Record the actual output, source (mock/model or physical), and any error. A missing tool, timeout or untested external service is not a pass.

Complete lab-by-lab verification report →Open automated verification center → Ask Engineering Copilot →

Independent theoretical exercises

Before the simulation or practical, solve both experiment-specific tasks. List the given inputs, show the intermediate calculation or state trace, identify the expected observation, and state a limitation. Show formulas and intermediate calculations where relevant, or draw the requested state/sequence diagram. These are independent classroom fixtures; where they differ from the reference configuration below, do not treat them as measured values. Compare your predictions with the corresponding experiment afterwards.

01 · Predict and derive using the given inputs

Evaluate fictional values 25,81,−50 and duplicate sequence under max 80 and the lab minimum. Record which checks require additional facts.

02 · Compare or justify using evidence

For rejection threshold 3 and verdicts R,A,R,R,A, calculate cumulative rejection count and first alert position under a cumulative policy. Contrast with consecutive policy.

03 · Engineering reasoning

Engineering reasoning · Independent work

Policy alerts on ≥3 rejected messages in 60 s. Reject events at 0,10,40 s, valid at45 s. When alert first triggers? What must a valid record check?

Work is saved locally when browser storage is available. Export it for submission; no remote upload or automatic grade is assigned.

Expanded independent theoretical exercise bank

Progress from calculation and interpretation to diagnosis and controlled engineering design. Complete the questions without opening the simulation first; show intermediate steps.

Intermediate · Explain a changed-input result

Independent theoretical exercise · K20-01

Use the reference configuration (Rejections required for alert = 3; Traffic scenario = mixed; Maximum accepted temperature = 80; Enforce monotonic sequence = true), but change Rejections required for alert = 5. The model reports Alert = No. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Interpret a state transition

Independent theoretical exercise · K20-02

The reference model reports Alert: Yes. Under Rejections required for alert = 5 it reports No. Explain which configured condition changed and what the two outputs establish, and what they do not establish.

Intermediate · Interpret a technical trace

Independent theoretical exercise · K20-03

For Traffic scenario = replays, the model supplies this excerpt from Gateway event log: Arrival · Sequence · Temperature °C · HMAC valid · Before · Decision · After · Rejections 1 · 1 · 25 · Yes · 0 · accepted · 1 · 0 2 · 1 · 25 · Yes · 1 · replay-rejected · 1 · 1 3 · 1 · 25 · Yes · 1 · replay-rejected · 1 · 2 4 · 1 · 25 · Yes · 1 · replay-rejected · 1 · 3 5 · 1 · 25 · Yes · 1 · replay-rejected · 1 · 4 Compute the range (maximum minus minimum) of the Sequence column in these rows. Identify the maximum observation. Do not extrapolate beyond these rows.

Advanced · Reverse reasoning

Independent theoretical exercise · K20-04

An observation is Accepted = 1. Candidate A uses Rejections required for alert = 3; Traffic scenario = mixed; Maximum accepted temperature = 80; Enforce monotonic sequence = true. Candidate B changes the listed settings (Traffic scenario = replays) and keeps the remaining settings fixed. Which is consistent with the observation? If both can explain it, say what additional evidence is required.

Advanced · Diagnose a reported mismatch

Independent theoretical exercise · K20-05

A student configures Maximum accepted temperature = 25 while preserving all other reference settings, but copies the reference report of Accepted = 2. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · K20-06

Design a controlled comparison for K20 · Authenticated IoT gateway and defensive monitoring using reference Rejections required for alert = 3; Traffic scenario = mixed; Maximum accepted temperature = 80; Enforce monotonic sequence = true and test Rejections required for alert = 5. Specify the changed setting(s), measured metric Alert, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Observe gateway rejection reasons, stored state and the alert threshold on a controlled event stream.

1 · Reference workbench configuration

Use the named reference workbench and its reference inputs. Additional live instruments may have different controls; use the matching instrument. Record virtual and practical results separately.

Rejections required for alert3
Traffic scenariomixed
Maximum accepted temperature80
Enforce monotonic sequenceYes

2 · Perform the investigation in order

  1. Use mixed traffic, temperature limit 80 °C, sequence guard enabled, alert threshold 3. Inspect five arrivals: valid, duplicate, changed bytes, temperature 90, valid recovery.
  2. Verify only accepted records are stored and the high-water counter changes only on accepted records.
  3. Raise alert threshold to 4; all gateway decisions remain unchanged, but the alert is not triggered.
  4. Choose all valid traffic, then replays. Compare rejection counts with stored records.
  5. Disable replay guard in the model only; identify the duplicate acceptance. Restore before concluding.
  6. Run security_extensions.py gateway locally and compare the five actual decisions.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Mixed trafficUse reference inputs aboveAccepted: 2; Rejected: 3; Alert: YesRecord actual result
Threshold fourRejections required for alert = 4Alert: NoRecord actual result
All validTraffic scenario = all validAccepted: 5; Rejected: 0Record actual result
Replay control disabledEnforce monotonic sequence = NoAccepted: 3; Rejected: 2Record actual result

4 · Analyze and report

Explain why valid HMAC does not prove a temperature is truthful and why a rejection alarm is not proof of attack.

Required evidence: Decision log, high-water trace, accepted-record table and alert sensitivity.

Model boundary: Actual HMAC and in-memory policy over fictional samples; no live network gateway.

Controlled investigation · reproducible evidence

Method. Use the existing reference workbench configuration and the named controlled changes below. A controlled variable stays fixed while the independent variable is intentionally changed; the dependent variable is the resulting observed output. First predict each trial from the Concepts page. Run the baseline, then change only the specified setting and record the outcome. For deterministic traces one execution per case and a repeated verification are sufficient; for timing or stochastic measurements repeat at least five times, recording each run, median and range. Reset to the reference state between independent comparisons.

TrialIndependent changeDependent observation
Mixed trafficUse reference inputs aboveRecord actual outcome and units
Threshold fourRejections required for alert = 4Record actual outcome and units
All validTraffic scenario = all validRecord actual outcome and units
Replay control disabledEnforce monotonic sequence = NoRecord actual outcome and units

Evidence: attach the completed comparison table, one trace or screenshot per condition, and actual practical terminal/hardware evidence where applicable. Explain any prediction mismatch and distinguish modeled behavior from measured results.

Loading laboratory-specific procedure…

Python / Google Colab notebook

Original local cryptography reference (ephemeral files); not production validation. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.

Download NotebookOpen Google ColabAll Python notebooks

Independent implementation sequence

  1. 1. Check updated implementation
  2. 2. Execute verification
  3. 3. Record and reflect

Complete practical procedure

1. Check updated implementation

Kali WSL · Bash
cd ~/kali-labs
ls -l security_extensions.py
✓ Expected: security_extensions.py exists; copy the updated file from the toolkit if missing.

2. Execute verification

Kali WSL · Bash
cd ~/kali-labs
python3 security_extensions.py gateway
✓ Expected: Five controls pass: accepted, replay rejected, integrity rejected, schema rejected, accepted recovery. Two valid records remain and the three rejection decisions trigger the teaching alert.

3. Record and reflect

Notebook action

Record the actual output and compare with the expected decisions.

✓ Expected: Notebook contains actual outputs, acquisition method and limitations.

Experimental notebook

Record your own results. Values are not prefilled or independently verified.

Scientific method and source

Five controls pass: accepted, replay rejected, integrity rejected, schema rejected, accepted recovery. Two valid records remain and the three rejection decisions trigger the teaching alert. Record all actual outputs; a missing dependency is not a passed security test.

Temporary cryptographic material is removed automatically for K19; the K18 results directory is retained. K20 is a bounded in-memory defensive policy, not a deployed network service.

Download source
Read complete source
PYTHON · Source code
#!/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)

Verification and discussion

Five controls pass: accepted, replay rejected, integrity rejected, schema rejected, accepted recovery. Two valid records remain and the three rejection decisions trigger the teaching alert.

Explain failed or inconclusive outcomes, save the actual JSON and any CSV, record software versions and reflect on limits. No credentials or real data in evidence.

Record evidence → · Ask Dr. Mohammad →

Python / Google Colab laboratory

K20 · 13 notebook cells · 4 executable Python cells

Complete the theoretical investigation first. Run the cells in order, record actual outputs and compare against your prediction.

How to execute

  1. Download this notebook and open Google Colab. Select File → Upload notebook and choose the downloaded .ipynb.
  2. Read the Markdown instructions before each executable cell. Use a Python runtime, run cells from top to bottom, and resolve imports if necessary.
  3. Perform the baseline and controlled changes. Save the notebook with actual outputs and your written interpretation.

Execution scope: Default computational cells passed isolated local Python execution; physical equipment and live services require separate verification.

01Instructions · Markdown
# K20 · K20 · Authenticated IoT gateway and defensive monitoring **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Introduction Enforce bounded authenticated input, per-device freshness and log security decisions with a threshold alert. ## How to run 1. Download this notebook from the laboratory page. Open Google Colab → File → Upload notebook. 2. Select a Python CPU runtime. Run cells from top to bottom using Shift+Enter, or Runtime → Run all. 3. Read the printed observations and assertions. Change one parameter at a time and rerun the relevant cell. 4. Save your own outputs and compare them to the portal Experiment tab. **Execution boundary:** Original local cryptography reference (ephemeral files); not production validation. Do not run the hardware or service commands in Colab. No real credentials are needed. The notebook is self-contained.
02Instructions · Markdown
## Experiment-specific preparation Enforce bounded authenticated input, per-device freshness and log security decisions with a threshold alert. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Use mixed traffic, temperature limit 80 °C, sequence guard enabled, alert threshold 3. Inspect five arrivals: valid, duplicate, changed bytes, temperature 90, valid recovery. 2. Verify only accepted records are stored and the high-water counter changes only on accepted records. 3. Raise alert threshold to 4; all gateway decisions remain unchanged, but the alert is not triggered. 4. Choose all valid traffic, then replays. Compare rejection counts with stored records. 5. Disable replay guard in the model only; identify the duplicate acceptance. Restore before concluding. **Evidence:** **Boundary:**
03Instructions · Markdown
## 1. Objectives and reference condition - Reproduce the specific computational mechanism in this laboratory. - Inspect the output, compare the reference condition with a changed or rejected condition where implemented, and explain any discrepancy. - Distinguish actual local Python execution from mock, physical and external-service observations. ## 2. Environment check
04Python · executable cell
PYTHON · Code cell
# =====================================================================
# K20 | Code cell 01 | K20 · Authenticated IoT gateway and defensive monitoring
# Purpose: 1. Objectives and reference condition - Reproduce the specific computational mechanism in this laboratory. - Inspect the output, compare the reference condition with a changed or rejected condition where implem
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import sys
print("Python",sys.version.split()[0])
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert sys.version_info >= (3,10)
Ask Dr. Mohammad about this cell
05Instructions · Markdown
## 3. Implementation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
06Python · executable cell
PYTHON · Code cell
# =====================================================================
# K20 | Code cell 02 | K20 · Authenticated IoT gateway and defensive monitoring
# 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 types, sys
# Set ascon for the next computation or reference condition.
ascon = types.ModuleType("ascon_course")
exec('#!/usr/bin/env python3\n"""Byte-oriented educational Ascon-AEAD128, NIST SP 800-232 (2025).\nNot hardened or validated for production. No secret inputs or external services.\n"""\nimport hmac, json, os\nMASK=(1<<64)-1\nIV=0x00001000808c0001\nRC=(0xf0,0xe1,0xd2,0xc3,0xb4,0xa5,0x96,0x87,0x78,0x69,0x5a,0x4b)\ndef rot(x,n): return ((x>>n)|(x<<(64-n)))&MASK\ndef perm(s,rounds):\n    for c in RC[-rounds:]:\n        a,b,d,e,f=s; d^=c\n        a^=f; f^=e; d^=b\n        t=[a,b,d,e,f]; u=[t[i]^((~t[(i+1)%5])&t[(i+2)%5]) for i in range(5)]\n        u[1]^=u[0]; u[0]^=u[4]; u[3]^=u[2]; u[2]=(~u[2])&MASK\n        s[:]=[x^rot(x,i)^rot(x,j) for x,(i,j) in zip(u,[(19,28),(61,39),(1,6),(10,17),(7,41)])]\ndef word(b): return int.from_bytes(b,\'little\')\ndef rate(s): return s[0].to_bytes(8,\'little\')+s[1].to_bytes(8,\'little\')\ndef setrate(s,b): s[0],s[1]=word(b[:8]),word(b[8:])\ndef xor(a,b):return bytes(x^y for x,y in zip(a,b))\ndef init(key,nonce,ad):\n    if len(key)!=16 or len(nonce)!=16:raise ValueError(\'128-bit key and nonce required\')\n    k0,k1=word(key[:8]),word(key[8:]);s=[IV,k0,k1,word(nonce[:8]),word(nonce[8:])];perm(s,12);s[3]^=k0;s[4]^=k1\n    if ad:\n        padded=ad+b\'\\x01\'+b\'\\0\'*((15-len(ad))%16)\n        for i in range(0,len(padded),16):setrate(s,xor(rate(s),padded[i:i+16]));perm(s,8)\n    s[4]^=1<<63\n    return s,k0,k1\ndef finish(s,k0,k1):\n    s[2]^=k0;s[3]^=k1;perm(s,12);s[3]^=k0;s[4]^=k1\n    return s[3].to_bytes(8,\'little\')+s[4].to_bytes(8,\'little\')\ndef encrypt(key,nonce,ad,plain):\n    s,k0,k1=init(key,nonce,ad);out=bytearray()\n    for i in range(0,len(plain)//16*16,16):\n        setrate(s,xor(rate(s),plain[i:i+16]));out.extend(rate(s));perm(s,8)\n    tail=plain[len(plain)//16*16:];setrate(s,xor(rate(s),tail+b\'\\x01\'+b\'\\0\'*(15-len(tail))));out.extend(rate(s)[:len(tail)])\n    return bytes(out)+finish(s,k0,k1)\ndef decrypt(key,nonce,ad,combined):\n    if len(combined)<16:raise ValueError(\'Missing tag\')\n    c,tag=combined[:-16],combined[-16:];s,k0,k1=init(key,nonce,ad);out=bytearray()\n    for i in range(0,len(c)//16*16,16):\n        block=c[i:i+16];out.extend(xor(rate(s),block));setrate(s,block);perm(s,8)\n    tail=c[len(c)//16*16:];r=rate(s);out.extend(xor(r,tail));new=bytearray(tail+r[len(tail):]);new[len(tail)]^=1;setrate(s,new)\n    if not hmac.compare_digest(tag,finish(s,k0,k1)):raise ValueError(\'Authentication failed\')\n    return bytes(out)\ndef checks():\n    # Independent RustCrypto ascon-aead 0.6.0 test vector Count=1 (SP 800-232).\n    # https://docs.rs/crate/ascon-aead/0.6.0/source/tests/data/ascon128.txt\n    k=bytes(range(16));n=k;expected=bytes.fromhex(\'4427D64B8E1E1451FC445960F0839BB0\');actual=encrypt(k,n,b\'\',b\'\')\n    results=[{\'control\':\'independent empty-message KAT\',\'pass\':actual==expected,\'actual\':actual.hex(),\'expected\':expected.hex()}]\n    for count,ml,al,hexout in [(2,0,1,\'103AB79D913A0321287715A979BB8585\'),(33,0,32,\'22133A313FBF0B38029A45870AADC542\'),(34,1,0,\'E79F58F1F541FC51B5D438F8E1DD03F147\'),(35,1,1,\'25EB4B700ED4AC8517DCBA20F673292230\'),(53,1,19,\'64E8A535661ECD9BD9986CEA0A46A8556B\')]:\n        expected=bytes.fromhex(hexout);pt=bytes(range(ml));ad=bytes(range(al));actual=encrypt(k,n,ad,pt)\n        results.append({\'control\':f\'independent KAT {count}\',\'pass\':actual==expected and decrypt(k,n,ad,expected)==pt,\'actual\':actual.hex(),\'expected\':expected.hex()})\n    # Fresh key per run, unique nonce for every encryption. Vectors use fixed public inputs only.\n    k=os.urandom(16)\n    for size in [0,1,15,16,17,31,32,33,128]:\n        for alen in [0,1,16,17]:\n            nonce=(size*100+alen).to_bytes(16,\'little\');msg=bytes(range(size));ad=b\'A\'*alen;ct=encrypt(k,nonce,ad,msg)\n            results.append({\'control\':f\'roundtrip-{size}-{alen}\',\'pass\':decrypt(k,nonce,ad,ct)==msg})\n            for label,nn,aa,cc in [(\'tag\',nonce,ad,ct[:-1]+bytes([ct[-1]^1])),(\'associated-data\',nonce,ad+b\'!\',ct),(\'nonce\',bytes([nonce[0]^1])+nonce[1:],ad,ct)]+([(\'ciphertext\',nonce,ad,bytes([ct[0]^1])+ct[1:])] if size else []):\n                try:decrypt(k,nn,aa,cc);ok=False\n                except ValueError:ok=True\n                results.append({\'control\':f\'reject-{label}-{size}-{alen}\',\'pass\':ok})\n    return {\'schema\':\'psut-security-evidence-157\',\'experiment\':\'K15\',\'source\':\'actual-local-educational-crypto\',\'implementation\':\'byte-oriented teaching implementation; not production hardened\',\'checks\':results,\'pass\':all(x[\'pass\'] for x in results)}\n', ascon.__dict__)
# Set sys.modules['ascon_course'] for the next computation or reference condition.
sys.modules["ascon_course"]=ascon
Ask Dr. Mohammad about this cell
07Instructions · Markdown
### Step 2 · Run the reference calculation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
08Python · executable cell
PYTHON · Code cell
# =====================================================================
# K20 | Code cell 03 | K20 · Authenticated IoT gateway and defensive monitoring
# Purpose: gateway
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import hmac, json, math, secrets

# Define the reusable operation gateway; keep its logic separate from the trial.
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.'}
Ask Dr. Mohammad about this cell
09Instructions · Markdown
### Step 3 · Run the reference calculation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
10Python · executable cell
PYTHON · Code cell
# =====================================================================
# K20 | Code cell 04 | K20 · Authenticated IoT gateway and defensive monitoring
# Purpose: Step 3 · Run the reference calculation 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 tempfile,os
# Set old for the next computation or reference condition.
old=os.getcwd()
# Limit resource lifetime to this block so files, sockets or temporary state are cleaned up.
with tempfile.TemporaryDirectory() as d:
    os.chdir(d)
    try: result=gateway()
    finally: os.chdir(old)
print(result)
# Check the expected invariant so a mismatch fails visibly instead of appearing successful.
assert result is not None and (not isinstance(result,dict) or result.get("pass",result.get("passed",True)))
Ask Dr. Mohammad about this cell
11Instructions · 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 gateway ``` ```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) ```
12Instructions · Markdown
## 4. Results and analysis Record the actual output and whether the assertions pass. Identify a parameter to vary, state your prediction, repeat the reference calculation, then explain the changed result. | Trial | Configuration | Observation | Interpretation | |---|---|---|---| | A | Reference | | | | B | One controlled change | | | | C | Reference repeat | | | **Limitations:** Original local cryptography reference (ephemeral files); not production validation. Notebook success does not certify external equipment or services.
13Instructions · Markdown
## Guided reasoning and evidence A controlled comparison changes one independent input while keeping the other relevant inputs fixed; the dependent variable is the recorded output. Use this lab’s reference condition above. **Independent task:** 2. Verify only accepted records are stored and the high-water counter changes only on accepted records. Record the named input, prediction, actual output and one limitation; restore the original condition and repeat. | Trial | Input/configuration | Prediction | Observation | Evidence / limitation | |---|---|---|---|---| | A | Reference | | | | | B | Changed input | | | | | A repeat | Reference | | | | A conclusion is supported only when it cites the recorded values or observed states and explains them with the experiment theory.
Shared research workbenches · network designer & advanced studies
Concurrent-device simulation & Monte Carlo research
Distributed digital twin · topology, protocol & battery research