IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
CRYPTOGRAPHY ENGINEERING · CR68 · AUTHENTICATION
IoT Security and Privacy
Authenticated sensor telemetry and replay
Authenticated telemetry and replay policy.
CR68 · Laboratory mentorAsk about the current operation and its intermediate values.
CR68 · Academic orientation
Scope and objectives
Scope of the experiment
A valid tag proves possession of the shared key under the protocol assumptions, but an old valid message still has a valid tag. Bind device identity, payload and freshness data to the MAC.
The focus of this experiment is to construct authenticated telemetry with an unambiguous message representation. Students then evaluate valid tags, modified readings and sequence freshness, and verify persistent replay protection across gateway restart. 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
Construct authenticated telemetry with an unambiguous message representation.
Evaluate valid tags, modified readings and sequence freshness.
Verify persistent replay protection across gateway restart.
Record the relevant inputs, intermediate states and final verification result before changing the reference configuration.
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 construct authenticated telemetry with an unambiguous message representation, evaluate valid tags, modified readings and sequence freshness, and verify persistent replay protection across gateway restart.
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 persistent replay protection across gateway restart. Separate predicted values from observations.
Prerequisite knowledge and related learning
Review the following catalogue prerequisites before starting. After completion, continue to AES-CMAC versus legacy CBC-based MAC.
A standard browser and the experiment-specific Python implementation or Colab notebook. Where the practical uses a protocol model, model results are distinguished from actual local cryptographic operations.
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.
01 · Experiment overview
CR68 · Authenticated sensor telemetry and replay
HMAC binds the reading and sequence number to a shared key. A receiver compares tags and independently checks whether the sequence is greater than its last accepted sequence. Only acceptance advances the stored sequence. Replay prevention depends on trusted persistent freshness state and key/device identity, not HMAC alone.
Learning objectives
Authenticated telemetry and replay policy. Predict a result, inspect intermediate states, verify the invariant and explain the specified boundary case.
HMAC binds the reading and sequence number to a shared key. A receiver compares tags and independently checks whether the sequence is greater than its last accepted sequence. Only acceptance advances the stored sequence. Replay prevention depends on trusted persistent freshness state and key/device identity, not HMAC alone.
Learning objectives
Authenticated telemetry and replay policy. Predict a result, inspect intermediate states, verify the invariant and explain the specified boundary case.
Mathematical verification and controlled comparison
Substitute the output into its defining equation or check the protocol invariant. A controlled comparison changes one input while holding others fixed. Cite actual trace values and identify the limitations of the evidence.
Before starting
Environment: standard computer, browser and Python/WSL.
Simulation: live bounded classroom calculations in the browser and Python.
Technical scope: Small synthetic parameters; educational mathematics, not production cryptography.
Authenticated telemetry and freshness
1 · Principles and purpose
A valid tag proves possession of the shared key under the protocol assumptions, but an old valid message still has a valid tag. Bind device identity, payload and freshness data to the MAC.
2 · Mathematical and algorithmic foundations
Verify tag using constant-time comparison; check monotonic sequence or appropriate nonce policy; update accepted freshness state only after verification. Canonical encoding matters.
3 · Worked teaching example
With last accepted sequence 4, valid tag and sequence 5 may advance state; valid tag with sequence 4 is stale; invalid tag must not advance state even if sequence is high. Define reset/reboot policy for IoT devices.
Captured earlier local execution. Randomized values and timing can differ; compare the invariant.
4 · Verification and experimental interpretation
Step through the following visualization and compare the named operation with the corresponding computed state. Check the mathematical invariant, inverse operation or protocol acceptance condition. Change one input at a time; distinguish a measured output from a prediction.
Mathematical representation and interpretation
HMAC construction
K′ is the normalized hash-block-sized key; ipad and opad are repeated constants. The inner hash binds the message and the outer hash produces the authentication tag. Replay prevention is a separate check.
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.
Step 1 of 2 · Calculated state 1
Calculated state 1
attempt
1
tag_valid
true
fresh
true
accepted
true
Calculated state 2
attempt
2
tag_valid
true
fresh
false
accepted
false
Teaching example only; inspect live calculations or real practical evidence separately.
Device authentication and persistent replay prevention
Device identity requires a key bound to the device. Canonical JSON makes the exact authenticated bytes unambiguous: fields are sorted, ASCII encoded, and temperature is represented as an integer in millidegrees Celsius. HMAC-SHA256 authenticates these bytes, not their semantic interpretation. A receiver validates the tag before atomically updating a per-device high-water mark stored in SQLite. A valid duplicate after restart must be rejected; compromised keys and state rollback require additional lifecycle controls.
Compare the three linked experiments to distinguish measured performance, application authentication and transport security.
Reference SVG (visible without scripts). Use the editable workstation below to calculate or run the experiment.
Select a calculated input fixture. These traces were generated and verified with the lab Python implementation; the browser replays recorded states. For arbitrary new inputs use the notebook or toolkit.
Verified baseline reference
Calculated result or labeled reference
{
"first": true,
"replay": false
}
Complete trace
Guided simulation activity
Use the baseline inputs shown above. Predict a result, advance one operation at a time, inspect the intermediate state, then change only the parameter specified in the Experiments view. Export the trace and compare it with your manual derivation.
Device authentication and persistent replay prevention
Actual HMAC calculation with a public teaching key; browser models the stored sequence. The Python experiment uses fresh random keys and real SQLite persistence.
Step 1
Ask Dr. Mohammad · current stage
For line-by-line implementation guidance, use the code mentor in Experiments.
Calculated result
Select Calculate / run.
04 · Experiments and engineering investigations
Analytical preparation — before Python
With initial last=0, sequence 1 and an unchanged reading, the first message is accepted; its identical replay has a valid tag but fails freshness.
Predict the baseline result before revealing the calculated state. A controlled comparison changes the named input while keeping the other conditions fixed. Record an observed value separately from an expected value.
Part A · Independent theoretical exercises
Complete each question before running the simulator or Python. Show calculations or protocol traces. The teaching example is a method, not a substitute for the assigned values.
01 · Application and derivation
Application and derivation · Independent work
For a sensor with last accepted sequence 10, analyze messages with valid tag and sequence 11, valid tag and sequence 10, and invalid tag and sequence 12. Fill an accept/reject table and explain which check must precede updating freshness state.
Application and derivation — Verify tag using constant-time comparison; check monotonic sequence or appropriate nonce policy; update accepted freshness state only after verification. Canonical encoding matters. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
02 · Replay analysis
Replay analysis · Independent work
Stored last=20. A message seq22 has invalid tag; then seq21 has valid tag. Under strict monotonic acceptance, determine state after each.
Replay analysis — Review the defining equations and compare the input restrictions and state transitions in Concepts. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
Required evidence: state the expected invariant or acceptance condition; record hand-derived results, compare with the simulator or Python trace, and explain the first discrepancy. Do not report a predicted value as a measurement.
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 · Alternate configuration
Independent theoretical exercise · CR68-01
For the separate teaching-test configuration tamper: true; sequence: 1, predict first using the relevant operation or decision rule. Show intermediate work and state whether this is a deterministic result.
Intermediate · Interpret a computation state
Independent theoretical exercise · CR68-02
A teaching trace for Authenticated sensor telemetry and replay contains attempt: 2; tag_valid: true; fresh: false; accepted: false. Explain the role of accepted (recorded value false) and identify the rule or input that determines it. Distinguish an intermediate state from the final result.
Intermediate · Compare two recorded states
Independent theoretical exercise · CR68-03
The first and final trace records show attempt = 1 and 2. Calculate the signed difference and explain whether it is an operation count, a state value or a measurement.
Challenging · Controlled algorithm verification
Independent theoretical exercise · CR68-04
Plan a comparison of tamper: false; sequence: 1 with tamper: true; sequence: 1. Record the dependent value first, identify the changed factor(s), and describe the verification and failure criterion without claiming a real security measurement.
Part B · Guided simulation and practical procedure
Before starting — tools and setup
Standard computer; run the integrated workstation or extracted toolkit. All classroom calculations run locally.
Install Python dependencies only if required by the selected toolkit README. Use its requirements file and virtual environment instructions.
Run tamper=false, sequence=1. Inspect two attempts and compare tag validity with freshness.
Export the trace and compare the result with the reference.
Experimental inputs
Experimental reference · json
{"tamper":false,"sequence":1}
Verified baseline reference (check after predicting)
Experimental reference · json
{"first":true,"replay":false}
Compare your baseline with the verified reference output below; for runtime-dependent results, compare invariants and report actual measurements instead of expecting identical timing or randomly generated values.
Evidence to record
Attempt number, tag validity, freshness and acceptance. Explain why a valid tag is not sufficient.
Part D · Controlled investigation — Authenticated telemetry and replay policy
Toggle tamper=true at sequence 1, then restore false and set sequence=0 or 2. Reset receiver state between trials.
Record fixed settings and complete the comparison table.
Measure Attempt number, tag validity, freshness and acceptance. Explain why a valid tag is not sufficient. Explain the first differing state or invariant.
Trial
Input configuration
Prediction
Observed
Verification
1
{"tamper":false,"sequence":1}
2
{"tamper":true,"sequence":1}
3
{"tamper":false,"sequence":0}
4
{"tamper":false,"sequence":2}
Use the table as a recording template; enter your own measured values in the field below or reproduce it in your report.
Part E/F · Independent Python verification and deliverables
Download the notebook or toolkit and run the default example.
Use python3 lab.py --inputs followed by the JSON from a trial. Compare exact math; for randomized or timed experiments compare invariants and report actual measurements separately.
Complete the independent assessment below without copying the worked baseline. Explain discrepancies and distinguish mathematical results from security claims.
Additional investigation instructions
Read the theory and prerequisite labs. Run the baseline and record the input and result.
Compare intact and modified readings, then repeat the intact message. Record authentication and freshness separately.
Locate the first intermediate step where the two cases differ. Verify the defining equation or decision rule.
Submit a two-row comparison table, trace evidence and a conclusion with limitations.
Case
Input
Observed result
Verification
Limitation
Baseline
Record
Record
Derive
Explain
Changed
Record
Record
Derive
Explain
Integrated IoT engineering investigation
Predict whether each of five trials is accepted: fresh signed message, modified payload, wrong key, duplicate after restart and next valid sequence. Execute the program and record each outcome. In the browser, change the temperature by selecting tamper, then test the wrong key and an old sequence separately. Explain why a failed authentication must not update the freshness state.
Predict the baseline before running the program.
Change one named condition at a time and retain the remaining settings.
Record actual output, comparison and interpretation. Identify the boundary where the security service applies.
Trial / change
Prediction
Observed result
Reason / limitation
Trial 1
Trial 2
Trial 3
Trial 4
Trial 5
Copy observations to the Engineering evidence record or export the workstation JSON. Do not enter actual credentials.
Use Ubuntu or Kali WSL, not PowerShell. Download the toolkit above to your computer. If Python, venv or unzip is missing, install these prerequisites once (requires administrator permission and network access).
In WSL, enter the actual downloaded ZIP path when prompted (for example, a file under /mnt/c/Users/…/Downloads). Extract to a new, dedicated directory. If this directory already exists from a previous extraction, use the existing verified toolkit or choose a clean directory rather than overwriting it.
Step 1 · Extract · bash
read -r -p "Full path to PSUT_V22_9_9_Cryptography_WSL.zip: " ZIP
DEST="$HOME/psut-crypto-v22.9.9"
if [ -f "$ZIP" ] && [ ! -e "$DEST" ]; then
mkdir "$DEST" && unzip "$ZIP" -d "$DEST"
else
echo "Check ZIP path and use a fresh destination."
fi
Create the isolated environment in the extracted toolkit root, activate it, then enter this experiment’s actual folder. Install only its declared dependencies. A comment-only requirements file requires no third-party packages.
Step 2 · Activate and install · bash
cd ~/psut-crypto-v22.9.9
python3 -m venv .venv
source .venv/bin/activate
cd CR68
ls
python -m pip install -r requirements.txt
Execute the default run and save the genuine program output. Then run the supplied regression test and the baseline fixture through the explicit input interface.
To change inputs, copy example-input.json, edit the copy in a text editor and run the command below. The original fixture is preserved.
Step 4 · Change an input · bash
cp example-input.json my-input.json
# Edit my-input.json with your preferred editor.
python lab.py --inputs "$(cat my-input.json)"
These scripts terminate normally. Use Ctrl+C to stop a long-running calculation if needed. When finished, leave the isolated virtual environment; no global service cleanup is required for these local examples.
Step 5 · Finish · bash
deactivate
Declared dependencies: # Python standard library only
Expected terminal output — captured local execution
This excerpt contains the actual first trace step and final result from python lab.py, followed by the actual regression test output. Full stdout is in CR68/verified-output.txt inside the toolkit. Timing, random signatures, keys, certificate fields and implementation-dependent sizes can vary; compare the invariant and record your own observations.
Check the output JSON and the test exit status. An assertion error means the expected invariant was not met. If Python reports a missing module, activate the environment and install the experiment’s requirements file; if a file is missing, check pwd and ls.
Download the notebook, open Google Colab and upload it using File → Upload notebook. For local Linux/WSL execution, follow the command blocks below in order.
Inspect Python source
Documented Python implementation · python
# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR68
# Experiment: authenticated sensor telemetry and replay
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR68 | Authenticated sensor telemetry and replay
# Execute the named operation; expose states and assert the laboratory invariant.
import hashlib
import hmac
import json
DEFAULT={'tamper': False, 'sequence': 1}
ALTERNATE={'tamper': True}
def run(overrides=None):
# Merge only explicitly supplied inputs with the reference baseline.
params={**DEFAULT, **(overrides or {})}
tamper=params['tamper']
sequence=params['sequence']
if type(tamper) is not bool or type(sequence) is not int or not 0<=sequence<=1000000: raise ValueError("Invalid sequence or tamper setting")
key=b'classroom-key';m=f'device=1;temperature=25.0;seq={sequence}'.encode();tag=hmac.new(key,m,hashlib.sha256).digest();received=m.replace(b'25.0',b'26.0') if tamper else m;last=0;steps=[]
for i in range(2):
tag_ok=hmac.compare_digest(tag,hmac.new(key,received,hashlib.sha256).digest());fresh=sequence>last;accepted=tag_ok and fresh
if accepted:last=sequence
steps.append({'attempt':i+1,'tag_valid':tag_ok,'fresh':fresh,'accepted':accepted})
result={'first':steps[0]['accepted'],'replay':steps[1]['accepted']}
# Independently check the stated mathematical or protocol invariant.
assert result["first"]== (not tamper and sequence>0) and not result["replay"], "verification failed"
return {"steps":steps,"result":result}
if __name__ == "__main__":
import argparse
parser=argparse.ArgumentParser();parser.add_argument("--inputs",default="{}");parser.add_argument("--test",action="store_true");args=parser.parse_args()
if args.test:
for case in [{},ALTERNATE]:run(case)
print("PASS")
else:print(json.dumps(run(json.loads(args.inputs)),indent=2))
Baseline reference (randomized fields may vary)
Reference result · json
{
"first": true,
"replay": false
}
Integrated IoT practical · Device authentication and persistent replay prevention
Use the downloaded current WSL toolkit. The following commands assume the extraction directory from the workflow above.
Ubuntu/Kali WSL · bash
cd ~/psut-crypto-v22.9.9
source .venv/bin/activate
cd CR68
ls
python -m pip install -r requirements.txt
python device_telemetry.py | tee integrated-results.json
python test_lab.py
Inspect the integrated practical implementation
device_telemetry.py · python
# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR68 integrated device identity
# Purpose: authenticate a canonical sensor payload and persist freshness.
# ------------------------------------------------------------
import hmac, hashlib, json, sqlite3, secrets, tempfile
from pathlib import Path
def encode(device, sequence, temperature_milli_c):
"""Canonical ASCII JSON; integer temperature avoids float ambiguity."""
if type(sequence) is not int or not 0<=sequence<2**63 or type(temperature_milli_c) is not int: raise ValueError('invalid sensor value')
return json.dumps({'device':device,'seq':sequence,'temp_mC':temperature_milli_c},sort_keys=True,separators=(',',':'),ensure_ascii=True).encode('ascii')
def sign(key, message): return hmac.new(key,message,hashlib.sha256).hexdigest()
class Gateway:
def __init__(self, db, keys):
self.db=sqlite3.connect(db);self.keys=keys
self.db.execute('CREATE TABLE IF NOT EXISTS freshness(device TEXT PRIMARY KEY, seq INTEGER NOT NULL)')
def check(self,message,tag):
try:
m=json.loads(message);device=m['device'];seq=m['seq'];key=self.keys.get(device)
if message!=encode(device,seq,m['temp_mC']):return 'noncanonical'
if key is None or not hmac.compare_digest(sign(key,message),tag):return 'authentication failed'
except (ValueError,TypeError,KeyError,AttributeError,UnicodeError):return 'invalid message'
# Commit only after authentication. A replay must not advance the high-water mark.
with self.db:
cur=self.db.execute('INSERT INTO freshness VALUES (?,?) ON CONFLICT(device) DO UPDATE SET seq=excluded.seq WHERE excluded.seq>freshness.seq',(device,seq))
return 'accepted' if cur.rowcount==1 else 'replay'
def close(self):self.db.close()
def run():
key=secrets.token_bytes(32);msg=encode('device01',1,25000);tag=sign(key,msg)
with tempfile.TemporaryDirectory() as tmp:
db=Path(tmp)/'state.sqlite';g=Gateway(db,{'device01':key});r={}
r['first']=g.check(msg,tag);r['tampered']=g.check(encode('device01',2,26000),tag);r['wrong_key']=g.check(encode('device01',2,25000),sign(secrets.token_bytes(32),encode('device01',2,25000)));g.close()
g=Gateway(db,{'device01':key});r['replay_after_restart']=g.check(msg,tag);m=encode('device01',2,25100);r['next']=g.check(m,sign(key,m));g.close()
assert r=={'first':'accepted','tampered':'authentication failed','wrong_key':'authentication failed','replay_after_restart':'replay','next':'accepted'}
return r
if __name__=='__main__':print(json.dumps(run(),indent=2))
Actual captured example output (timings and random fields can vary)
Recall before revealing. Review and mastery ratings remain on this device.
Browse all explanationsWhen is last sequence advanced?
Only after valid tag and freshness.
Does replay invalidate HMAC?
No.
Why persist freshness state?
Otherwise resets can permit previously accepted packets.
Why is the second identical packet rejected?
Its sequence is no longer fresh
What evidence should be recorded?
Attempt number, tag validity, freshness and acceptance. Explain why a valid tag is not sufficient.
How should the comparison be controlled?
Toggle tamper=true at sequence 1, then restore false and set sequence=0 or 2. Reset receiver state between trials.
06 · Knowledge assessment
Toggle tamper=true at sequence 1, then restore false and set sequence=0 or 2. Reset receiver state between trials. Submit the stated measurements, a reasoned comparison and independent verification. Criteria: mathematical correctness 40%, reproducibility 30%, interpretation 20%, limitations 10%.
Formative knowledge check
Why is the second identical packet rejected?
Responses are for instructor review; no grading key is provided here.
Part F · Engineering evidence record
Record the baseline, prediction, changed input, observed result, discrepancy and limitation. Save locally or export with the displayed result. This is not an official submission.