Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Connected Networks StudioNetworking and CommunicationExperimentsWorkspaces
ENGINEERING WORKSPACE
Home / Kali security course / K07
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
WSL LABORATORIES / KALI LINUX / SECURITY & PRIVACY
IoT Security and Privacy

K07 · Authenticated freshness & replay protection

Ask Dr. Mohammad · K07 →

Practical IoT Security & Privacy · Kali WSL · 30 min

Design experiment & verify evidence →
K07 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Kali & IoT securityK07 · Authenticated freshness & replay protection
V19.0 · Contextual AI workspace

Ask your engineering assistants

K07 · 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
K07 · Authenticated freshness & replay protection

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.

Readiness checksRevision deckEngineering workspaceRecord evidence
K07 · Academic orientation

Scope and objectives

Scope of the experiment

Verify authenticated anti-replay state across an ordered delivery sequence.

The focus of this experiment is to trace message authentication and replay-cache decisions. Students then evaluate sequence and timestamp boundaries in a controlled fixture, and verify stale or duplicated messages are rejected. 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 message authentication and replay-cache decisions.
  • Evaluate sequence and timestamp boundaries in a controlled fixture.
  • Verify stale or duplicated messages are rejected.
  • Identify the configured inputs (Initial high-water sequence; Incoming sequence; Incoming timestamp (s); Receiver teaching clock (s); Allowed absolute skew (s)) 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 message authentication and replay-cache decisions, evaluate sequence and timestamp boundaries in a controlled fixture, and verify stale or duplicated messages are rejected.

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 verify stale or duplicated messages are rejected. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to K08 · Authenticated encryption & signatures.

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.

CONCEPTS / ACTIVE RECALL

Understand the experiment

Authenticated freshness · state update

Verify integrity before changing replay-protection state
Verify integrity before changing replay-protection state

Scientific architecture · Stateful authenticated freshness receiver

Authenticated freshness decision — Receive message + tag / parse seq; Verify MAC / exact encoded bytes; Sequence greater than accepted? / check stored state; Accept / update highest sequence; Reject / state remains unchanged
Scientific concept map: Sender — Sequence + payload + MAC; Receiver — Verify tag first; Freshness state — High-water mark; Policy — Reject old sequence; Commit — Advance state only on acceptance.

Scientific foundations and analytical reasoning

Authentication protects message integrity; a high-water sequence and bounded timestamp skew enforce freshness separately.

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 · Freshness and authenticated state

A valid authentication tag can be replayed with its original message. A receiver can enforce monotonic sequence numbers and a bounded timestamp policy after authentication, keeping state per device. State must not advance on invalid tags; persistence matters across restarts.

Worked example and engineering interpretation

If the last accepted sequence is 10, a valid sequence 11 can advance the state. A later valid replay of 10 is rejected. An invalid-tag packet with sequence 99 must not advance the receiver's accepted high-water mark. Compare sequence and tag outcomes independently.

Engineering principles · additional worked teaching example

Freshness combines authenticated timestamp and sequence. A high-water mark rejects sequence ≤last accepted; absolute skew checks bounded clock error. Only update stored state after successful authentication. At last=7 and incoming7, valid tag still does not make message fresh.

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 K07 · Authenticated freshness & replay protection

Reject duplicate, stale and altered authenticated messages.

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: Reject duplicate, stale and altered authenticated messages.

  1. Start with high-water 0, sequence 1, timestamp and clock 1000, window 30, duplicate delivery. The first message advances to 1; the duplicate must not advance it.
  2. Choose altered and verify tag rejection before the freshness check.
  3. Choose single and set timestamp 900. The HMAC is valid but timestamp is outside 30 s.
  4. Restore timestamp and choose next; verify sequence 2 is accepted after sequence 1.

Reference check:

Model boundary:

Independent task and submission evidence

2. Choose altered and verify tag rejection before the freshness check. 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: Initial high-water sequence = 0; Incoming sequence = 1; Incoming timestamp (s) = 1000; Receiver teaching clock (s) = 1000; Allowed absolute skew (s) = 30; Delivery sequence = duplicate. In the classroom model, Accepted = 1; Rejected = 1; Final sequence = 1. Invalid tag, stale time and replay are distinct; none of them changes receiver state. Actual HMAC over canonical teaching JSON; clock and receiver state are simulated.

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.

K07 · Authenticated freshness & replay protection: progressive data plot00.250.50.751High-water markIncoming sequenceinitial2initial

Step 1 of 3 · Observation initial

Observation initial

High-water mark
0

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

Recall the concept before revealing its explanation.

0 / 3 revealed
K07 · 01 / 08What is replay protection?Reveal explanation
Engineering explanation

Rejecting a previously accepted message using authenticated freshness state.

K07 · 02 / 08Why authenticate timestamps?Reveal explanation
Engineering explanation

An untrusted timestamp can be changed by a sender without integrity protection.

K07 · 03 / 08What initial authenticated sequence/freshness conditions must be established?Reveal explanation
Engineering explanation

This exercise uses fixed clock and in-memory state. Verify valid, duplicate, stale and tampered cases; do not claim persistent replay protection across restart.

K07 · 04 / 08Why authenticate a sequence number together with telemetry?Reveal explanation
Engineering reasoning

An unauthenticated freshness field can be changed independently; binding it to the tag protects the integrity of the freshness claim.

K07 · 05 / 08Why retain a high-water mark per device?Reveal explanation
Engineering reasoning

It helps detect previously accepted or stale sequence numbers without confusing independent device streams.

K07 · 06 / 08An authenticated record is replayed unchanged. Select every technically valid statement. A. Verify authentication before updating freshness state. B. Reject duplicates using the defined sequence or freshness policy. C. A valid tag guarantees a message has never appeared before. D. An unauthenticated sequence should advance the trusted state.Reveal explanation
Applied scenario

Correct: A. Verify authentication before updating freshness state.; B. Reject duplicates using the defined sequence or freshness policy.

K07 · 07 / 08In K07 · Authenticated freshness & replay protection, which command or code executes the final documented practical action?Reveal explanation
Implementation recall

cat "$HOME/.psut-kali-security-v14/evidence/K07-REPLAY.json"

K07 · 08 / 08For K07 · Authenticated freshness & replay protection, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Run lab.py replay; uses fixed teaching clock and in-memory sequence state. Require all checks pass, including duplicate/stale/altered rejection. Restart resets teaching state; not durable production replay protection.

Interactive networking and security instrument

Loading experiment-specific apparatus…
K07 · 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 →

Experimental protocol

Before you run / verification gate

This exercise uses fixed clock and in-memory state. Verify valid, duplicate, stale and tampered cases; do not claim persistent replay protection across restart.

Experimental protocol

Prerequisites
K06; fixed teaching clock
Procedure
Verify MAC before freshness and sequence. Compare fresh, duplicate, stale, altered and next fresh packet.
Acceptance
Only original and next fresh packet accepted; rejected input cannot update high-water mark.
Evidence
K07-REPLAY.json; describe reboot and persistent-state limitation.
Standards link
Data protection and state awareness
Discussion
Why must replay state survive restart in a real receiver?

Run & verify — acceptance checklist

Build verification: Actual replay controls passed.

Run lab.py replay; uses fixed teaching clock and in-memory sequence state. Require all checks pass, including duplicate/stale/altered rejection. Restart resets teaching state; not durable production replay protection.

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

For high-water 3, receiver time 1000 and allowed skew 30 s, evaluate sequence 4 at times 969,970,1030,1031 assuming valid tags and inclusive bounds. Treat cases independently.

02 · Compare or justify using evidence

Trace valid seq 4 followed by duplicate 4, altered 5 and valid 5. Record high-water after each and justify why rejected messages must not advance it.

03 · Boundary analysis

Boundary analysis · Independent work

Last accepted seq10, clock100 s, skew≤5 s. Independently evaluate (11,95), (11,106), (10,100), (12,100 with invalid tag).

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 · K07-01

Use the reference configuration (Initial high-water sequence = 0; Incoming sequence = 1; Incoming timestamp (s) = 1000; Receiver teaching clock (s) = 1000; Allowed absolute skew (s) = 30; Delivery sequence = duplicate), but change Initial high-water sequence = 10000. The model reports Accepted = 0. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Quantitative comparison

Independent theoretical exercise · K07-02

Two model observations of Accepted are 1 (reference) and 0 (changed condition). Compute signed change and, when the reference is nonzero, percentage change. Explain why units matter.

Intermediate · Interpret a technical trace

Independent theoretical exercise · K07-03

For Incoming sequence = 3, the model supplies this excerpt from Ordered receiver trace: Arrival · Sequence · Timestamp · Tag valid · Before · Decision · After 1 · 3 · 1000 · Yes · 0 · accepted · 3 2 · 3 · 1000 · Yes · 3 · replay · 3 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 · K07-04

An observation is Final sequence = 3. Candidate A uses Initial high-water sequence = 0; Incoming sequence = 1; Incoming timestamp (s) = 1000; Receiver teaching clock (s) = 1000; Allowed absolute skew (s) = 30; Delivery sequence = duplicate. Candidate B changes the listed settings (Incoming sequence = 3) 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 · K07-05

A student configures Incoming timestamp (s) = 0 while preserving all other reference settings, but copies the reference report of Accepted = 1. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · K07-06

Design a controlled comparison for K07 · Authenticated freshness & replay protection using reference Initial high-water sequence = 0; Incoming sequence = 1; Incoming timestamp (s) = 1000; Receiver teaching clock (s) = 1000; Allowed absolute skew (s) = 30; Delivery sequence = duplicate and test Initial high-water sequence = 10000. Specify the changed setting(s), measured metric Accepted, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Verify authenticated anti-replay state across an ordered delivery sequence.

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.

Initial high-water sequence0
Incoming sequence1
Incoming timestamp (s)1000
Receiver teaching clock (s)1000
Allowed absolute skew (s)30
Delivery sequenceduplicate

2 · Perform the investigation in order

  1. Start with high-water 0, sequence 1, timestamp and clock 1000, window 30, duplicate delivery. The first message advances to 1; the duplicate must not advance it.
  2. Choose altered and verify tag rejection before the freshness check.
  3. Choose single and set timestamp 900. The HMAC is valid but timestamp is outside 30 s.
  4. Restore timestamp and choose next; verify sequence 2 is accepted after sequence 1.
  5. Set initial high-water 2 while sending 1; record both rejection and unchanged state.
  6. Run lab.py replay locally and compare its five named cases.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Duplicate deliveryUse reference inputs aboveAccepted: 1; Rejected: 1; Final sequence: 1Record actual result
StaleIncoming timestamp (s) = 900Accepted: 0; Final sequence: 0Record actual result
Altered tagDelivery sequence = alteredAccepted: 0Record actual result
Next legitimate messageDelivery sequence = nextAccepted: 2; Final sequence: 2Record actual result
Old sequenceInitial high-water sequence = 2Accepted: 0; Final sequence: 2Record actual result

4 · Analyze and report

Identify the order of integrity, time and sequence checks and why rejected packets never update the high-water mark.

Required evidence: Ordered trace with HMAC decisions and before/after sequence.

Model boundary: Actual HMAC over canonical teaching JSON; clock and receiver state are simulated.

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
Duplicate deliveryUse reference inputs aboveRecord actual outcome and units
StaleIncoming timestamp (s) = 900Record actual outcome and units
Altered tagDelivery sequence = alteredRecord actual outcome and units
Next legitimate messageDelivery sequence = nextRecord 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 defensive function; ephemeral evidence directory. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.

Download NotebookOpen Google ColabAll Python notebooks
K07 / Kali · Python HMAC30 min

Authenticated freshness & replay protection

Kali terminal C · working directory
Kali (Bash)
cd ~/kali-labs
bash verify_kali.sh
✓ Expected: Toolkit directory is selected and all dependency checks pass. Do not proceed if any check fails.

Objective: Test accepted, duplicate, stale and altered messages against a local receiver.

Analyze authenticated sequence numbers and a fixed teaching clock.

ACTION 01 / 02
Kali terminal C
python3 lab.py replay
✓ Expected: The JSON report records valid-message acceptance and rejection of duplicate, stale or otherwise invalid authenticated telemetry.
ACTION 02 / 02
Kali terminal C
cat "$HOME/.psut-kali-security-v14/evidence/K07-REPLAY.json"
✓ Expected: The saved JSON report prints individual check outcomes. Review pass/fail rather than assuming all tests succeeded.

Experimental notebook

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

Method and implementation

Review the implementation after attempting the practical steps.

Replay defense · method and source

Verify tag first, then time window, then monotonically increasing sequence. Do not update state after a rejected message. The fixed clock makes the freshness tests reproducible. Production receivers need persistent state, key rotation and an explicit reboot policy.

Inspect the actual implementation below. Full file: lab.py.

PYTHON · Source code
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])

Verification and notebook

Expected observation / verification

Expected fresh and next messages accepted, duplicate/stale/altered rejected. Receiver state is in memory, not production-persistent.

Engineering discussion

How should a real gateway handle reboot, sequence rollback and clock drift?

Python / Google Colab laboratory

K07 · 11 notebook cells · 3 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
# K07 · K07 · Authenticated freshness & replay protection **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Introduction Reject duplicate, stale and altered authenticated messages. ## 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 defensive function; ephemeral evidence directory. 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 Reject duplicate, stale and altered authenticated messages. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Start with high-water 0, sequence 1, timestamp and clock 1000, window 30, duplicate delivery. The first message advances to 1; the duplicate must not advance it. 2. Choose altered and verify tag rejection before the freshness check. 3. Choose single and set timestamp 900. The HMAC is valid but timestamp is outside 30 s. 4. Restore timestamp and choose next; verify sequence 2 is accepted after sequence 1. 5. Set initial high-water 2 while sending 1; record both rejection and unchanged state. **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
# =====================================================================
# K07 | Code cell 01 | K07 · Authenticated freshness & replay protection
# 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
# =====================================================================
# 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])
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
# =====================================================================
# K07 | Code cell 03 | K07 · Authenticated freshness & replay protection
# Purpose: Step 2 · 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
# Limit resource lifetime to this block so files, sockets or temporary state are cleaned up.
with tempfile.TemporaryDirectory() as d:
    HOME=Path(d)
    assert replay()
Ask Dr. Mohammad about this cell
09Instructions · 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 python3 lab.py replay ``` ```python 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]) ```
10Instructions · 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 defensive function; ephemeral evidence directory. Notebook success does not certify external equipment or services.
11Instructions · 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. Choose altered and verify tag rejection before the freshness check. 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