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

K17 · Credential lifecycle and key rotation

Ask Dr. Mohammad · K17 →

Verify key retirement and continued replay protection across a controlled rotation.

← Security range
Design experiment & verify evidence →
K17 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Kali & IoT securityK17 · Credential lifecycle and key rotation

Before you start

Complete K01 and K07. Copy the updated Kali toolkit file into ~/kali-labs. Run as a normal Kali user; no additional packages or public services are needed.

Learning outcome

Verify key retirement and continued replay protection across a controlled rotation.

Updated Kali toolkit
K17 · Academic orientation

Scope and objectives

Scope of the experiment

Verify that key rotation and per-device replay protection remain independent controls.

The focus of this experiment is to trace credential issuance, rotation, overlap and revocation. Students then compare acceptance at lifecycle boundaries, and verify old and new credentials under the stated policy. 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 credential issuance, rotation, overlap and revocation.
  • Compare acceptance at lifecycle boundaries.
  • Verify old and new credentials under the stated policy.
  • Identify the configured inputs (Old-key policy after rotation; Preserve replay counter on rotation; Initial 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 credential issuance, rotation, overlap and revocation, compare acceptance at lifecycle boundaries, and verify old and new credentials under the stated policy.

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 old and new credentials under the stated policy. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to K18 · Comparative AES-GCM and Ascon benchmarking.

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 · Credential rotation and persistent replay state

Credential rotation and replay state — Active key A / sequence state; Provision key B / authenticated update; Transition / bounded overlap; Retire A / reject old key; Persist sequence / reboot must not reset policy
Scientific concept map: Current key — Key ID + policy; Rotation — Activate new key; Receiver — Verify allowed key ID; Freshness store — Persistent counter; Retirement — Reject old key.

Scientific foundations and analytical reasoning

Key rotation changes which keys are accepted; freshness state belongs to the device identity and must survive rotation.

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 · Key rotation and identity continuity

Key rotation changes which key versions are active or accepted during a defined overlap. The stable device identity, authorization and replay state must not be reset simply because its key changes. Revocation and expiry limit acceptance but require reliable time and policy.

Worked example and engineering interpretation

If device A has accepted sequence 50 under key version 1, version 2 must not make sequence 20 fresh again. Verify the new key's acceptance, old-key expiry and persisted sequence state independently. Distinguish an operational grace period from indefinite trust.

Engineering principles · additional worked teaching example

Rotation introduces new key identifiers and retires old keys under policy. Replay state must remain bound to device and sequence across key changes. If last sequence=20, accepting seq1 only because key ID changes can permit replay unless explicitly defined new epoch.

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 K17 · Credential lifecycle and key rotation

Verify key retirement and continued replay protection across a controlled rotation.

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: Verify key retirement and continued replay protection across a controlled rotation.

  1. Start with retire and preserve counter. Inspect the initial old-key acceptance, duplicate, rotation, retired-key attempt, valid new-key update and rollback.
  2. Select grace and inspect which old-key message is accepted after rotation; compare the corresponding new-key sequence collision.
  3. Restore retire and disable counter preservation. Inspect the rollback test before the new legitimate message.
  4. Explain why replay state must survive restart and rotation; design a durable key-ID and sequence update.

Reference check:

Model boundary:

Independent task and submission evidence

2. Select grace and inspect which old-key message is accepted after rotation; compare the corresponding new-key sequence collision. 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: Old-key policy after rotation = retire; Preserve replay counter on rotation = true; Initial sequence = 1. In the classroom model, Accepted messages = 2; Final sequence = 2; Retired-key acceptance = No; Rollback accepted = No. Old-key acceptance and replay state are independently evaluated. Actual HMAC and in-memory state machine; not a production credential service.

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.

K17 · Credential lifecycle and key rotation: progressive data plot00.511.52High-water sequen…initialvalid new messageinitial

Step 1 of 7 · Observation initial

Observation initial

High-water sequence
0

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

Recall the concept before revealing its explanation.

0 / 3 revealed
K17 · 01 / 08What is key retirement?Reveal explanation
Engineering explanation

The receiver stops accepting messages authenticated by a retired key.

K17 · 02 / 08Why keep the sequence state across rotation?Reveal explanation
Engineering explanation

Resetting the replay counter can allow an old sequence to be accepted again.

K17 · 03 / 08Does key rotation fix compromised devices?Reveal explanation
Engineering explanation

No. Device identity, protected provisioning, recovery, monitoring and durable state must also be addressed.

K17 · 04 / 08Why distinguish rotation from revocation?Reveal explanation
Engineering reasoning

Rotation replaces credentials; revocation invalidates a credential that should no longer be accepted.

K17 · 05 / 08Why test the old credential after rotation?Reveal explanation
Engineering reasoning

The new credential succeeding does not prove the old one has been disabled; test both expected outcomes.

K17 · 06 / 08A key rotation is performed. Select every technically valid statement. A. Reject retired credentials according to policy. B. Preserve replay protection across the rotation. C. A new key automatically makes every old record fresh. D. All retired keys must remain accepted indefinitely.Reveal explanation
Applied scenario

Correct: A. Reject retired credentials according to policy.; B. Preserve replay protection across the rotation.

K17 · 07 / 08Which engineering mechanism is tested by K17 · Credential lifecycle and key rotation, and what state or outcome is evaluated?Reveal explanation
Implementation recall

Verify key retirement and continued replay protection across a controlled rotation.

K17 · 08 / 08For K17 · Credential lifecycle and key rotation, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Run defensive_range.py rotation; require six pass flags. Fresh key succeeds; retired key and replay rejected; sequence state preserved within one run. This is in-memory lifecycle logic, not certificate enrollment or hardware key storage.

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

K17 · 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
K17 · Credential lifecycle and key rotation

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 key-rotation six controls passed.

Run defensive_range.py rotation; require six pass flags. Fresh key succeeds; retired key and replay rejected; sequence state preserved within one run. This is in-memory lifecycle logic, not certificate enrollment or hardware key storage.

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

Trace accepted old-key seq 1, new-key seq 2, old-key seq 3 after retirement and duplicate new-key seq 2. Record high-water and verdicts.

02 · Compare or justify using evidence

Compare resetting and preserving counters on rotation. Explain why the overlap policy requires an explicit end time.

03 · State analysis

State analysis · Independent work

Old key retired, new key active; high-water=50. Independently assess valid old-key seq51, valid new-key seq50, valid new-key seq51.

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

Use the reference configuration (Old-key policy after rotation = retire; Preserve replay counter on rotation = true; Initial sequence = 1), but change Initial sequence = 3. The model reports Final sequence = 4. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Quantitative comparison

Independent theoretical exercise · K17-02

Two model observations of Final sequence are 2 (reference) and 4 (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 · K17-03

For Old-key policy after rotation = grace, the model supplies this excerpt from Rotation sequence: Message · Key ID · Seq · Before · Decision · After old first · old · 1 · 0 · Accepted · 1 duplicate · old · 1 · 1 · Replay · 1 retired-key attempt · old · 2 · 1 · Accepted · 2 rollback with new key · new · 1 · 2 · Replay · 2 modified new message · new · 2 · 2 · Bad HMAC · 2 Count rows whose Key ID value is exactly “old”, and identify the displayed row numbers. Explain what the count describes.

Advanced · Reverse reasoning

Independent theoretical exercise · K17-04

An observation is Retired-key acceptance = Yes. Candidate A uses Old-key policy after rotation = retire; Preserve replay counter on rotation = true; Initial sequence = 1. Candidate B changes the listed settings (Old-key policy after rotation = grace) 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 · K17-05

A student configures Preserve replay counter on rotation = false while preserving all other reference settings, but copies the reference report of Accepted messages = 2. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · K17-06

Design a controlled comparison for K17 · Credential lifecycle and key rotation using reference Old-key policy after rotation = retire; Preserve replay counter on rotation = true; Initial sequence = 1 and test Initial sequence = 3. Specify the changed setting(s), measured metric Final sequence, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Verify that key rotation and per-device replay protection remain independent controls.

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.

Old-key policy after rotationretire
Preserve replay counter on rotationYes
Initial sequence1

2 · Perform the investigation in order

  1. Start with retire and preserve counter. Inspect the initial old-key acceptance, duplicate, rotation, retired-key attempt, valid new-key update and rollback.
  2. Select grace and inspect which old-key message is accepted after rotation; compare the corresponding new-key sequence collision.
  3. Restore retire and disable counter preservation. Inspect the rollback test before the new legitimate message.
  4. Explain why replay state must survive restart and rotation; design a durable key-ID and sequence update.
  5. Execute defensive_range.py rotation in Kali and compare its six controls.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Retire and persistUse reference inputs aboveAccepted messages: 2; Final sequence: 2Record actual result
Grace periodOld-key policy after rotation = graceAccepted messages: 2; Retired-key acceptance: YesRecord actual result
Reset replay statePreserve replay counter on rotation = NoRollback accepted: YesRecord actual result

4 · Analyze and report

What risks arise when grace periods and counter resets are used without a transition policy?

Required evidence: Per-message key ID, counter, decision and recovery trace.

Model boundary: Actual HMAC and in-memory state machine; not a production credential service.

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
Retire and persistUse reference inputs aboveRecord actual outcome and units
Grace periodOld-key policy after rotation = graceRecord actual outcome and units
Reset replay statePreserve replay counter on rotation = 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 defensive reference; ephemeral keys/files. Validated locally in a fresh Jupyter kernel. Download, then upload to Google Colab.

Download NotebookOpen Google ColabAll Python notebooks

Independent implementation sequence

  1. 1. Verify updated toolkit file
  2. 2. Run the local defensive controls
  3. 3. Save actual verification evidence

Practical procedure

1. Verify updated toolkit file

Kali WSL · Bash
cd ~/kali-labs
ls -l defensive_range.py
✓ Expected: The named Python file exists. If missing, copy it from the updated Kali toolkit; do not reinstall Kali.

2. Run the local defensive controls

Kali WSL · Bash
cd ~/kali-labs
python3 defensive_range.py rotation
✓ Expected: Six controls pass, including acceptance before and after rotation, duplicate rejection, retired-key rejection, tampering and sequence rollback rejection.

3. Save actual verification evidence

Kali WSL · Bash
cd ~/kali-labs
mkdir -p ~/psut-security-results
python3 defensive_range.py rotation > ~/psut-security-results/K17-evidence.json && cat ~/psut-security-results/K17-evidence.json
✓ Expected: The JSON records the actual controls and overall pass value. This repeat replaces the named evidence file; rename it first to preserve previous runs.

Experimental notebook

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

Scientific method

The script uses fictional sensor data, ephemeral HMAC keys and a receiver allowlist. It deliberately preserves per-device sequence state when rotating the active key. This is not a production provisioning or revocation service.

Read the complete source code
PYTHON · Source code
#!/usr/bin/env python3
"""Controlled local defensive exercises. Fictional data, ephemeral keys; no network targets."""
import argparse, copy, hashlib, hmac, json, secrets

def canonical(x):return json.dumps(x,sort_keys=True,separators=(',',':'),allow_nan=False).encode()
def mac(key,obj):return hmac.new(key,canonical(obj),hashlib.sha256).hexdigest()
def evidence(lab,checks):return {'schema':'psut-security-evidence-157','experiment':lab,'source':'actual-local-defensive-teaching-test','checks':[{'control':n,'pass':bool(p)} for n,p in checks],'pass':all(p for _,p in checks)}
def audit():
    key=secrets.token_bytes(32);log=[];previous='0'*64
    for i,event in enumerate(['connect accepted','publication accepted','publication denied','disconnect']):
        entry={'seq':i,'event':event,'prev':previous};previous=mac(key,entry);log.append({**entry,'tag':previous})
    anchor=(len(log),previous) # Held separately in this exercise, not durable production storage.
    def valid(rows):
        prev='0'*64
        for i,r in enumerate(rows):
            item={k:v for k,v in r.items() if k!='tag'}
            if r['seq']!=i or r['prev']!=prev or not hmac.compare_digest(mac(key,item),r['tag']):return False
            prev=r['tag']
        return (len(rows),prev)==anchor
    changed=copy.deepcopy(log);changed[1]['event']='changed';swapped=copy.deepcopy(log);swapped[1],swapped[2]=swapped[2],swapped[1]
    return evidence('K16',[('original authenticated chain',valid(log)),('modified event rejected',not valid(changed)),('reordered entries rejected',not valid(swapped)),('interior deletion rejected',not valid(log[:1]+log[2:])),('truncated suffix rejected against separate anchor',not valid(log[:-1]))])
def rotation():
    keys={'old':secrets.token_bytes(32),'new':secrets.token_bytes(32)};active={'old'};seen={}
    def packet(kid,seq):
        obj={'device':'fictional-sensor','kid':kid,'seq':seq,'temperature':25};return {**obj,'tag':mac(keys[kid],obj)}
    def accept(p):
        obj={k:v for k,v in p.items() if k!='tag'};kid=p['kid'];seq=p['seq']
        if kid not in active or not hmac.compare_digest(mac(keys[kid],obj),p['tag']):return False
        if type(seq) is not int or seq<=seen.get(p['device'],-1):return False
        seen[p['device']]=seq;return True
    p=packet('old',1);checks=[('old key initially accepted',accept(p)),('duplicate rejected',not accept(p))]
    active={'new'};checks.append(('retired key rejected even with new sequence',not accept(packet('old',2))))
    q=packet('new',2);tamper={**q,'temperature':40};checks.extend([('altered message rejected',not accept(tamper)),('valid rotated key accepted',accept(q)),('sequence rollback rejected across rotation',not accept(packet('new',1)))])
    return evidence('K17',checks)
if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('experiment',choices=['audit','rotation']);a=p.parse_args();r=globals()[a.experiment]();print(json.dumps(r,indent=2));raise SystemExit(0 if r['pass'] else 1)
Download source file

Verification and discussion

Record the actual JSON output, Python environment, expected versus observed decisions, and any failed or inconclusive controls. Explain what is not established by these tests. Keep fictional inputs and actual local execution distinct.

Record evidence in engineering notebook →

Ask Dr. Mohammad →

Completion is not independent verification.

Python / Google Colab laboratory

K17 · 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
# K17 · K17 · Credential lifecycle and key rotation **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Introduction Verify key retirement and continued replay protection across a controlled rotation. ## 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 defensive reference; ephemeral keys/files. 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 Verify key retirement and continued replay protection across a controlled rotation. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Start with retire and preserve counter. Inspect the initial old-key acceptance, duplicate, rotation, retired-key attempt, valid new-key update and rollback. 2. Select grace and inspect which old-key message is accepted after rotation; compare the corresponding new-key sequence collision. 3. Restore retire and disable counter preservation. Inspect the rollback test before the new legitimate message. 4. Explain why replay state must survive restart and rotation; design a durable key-ID and sequence update. 5. Execute defensive_range.py rotation in Kali and compare its six controls. **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
# =====================================================================
# K17 | Code cell 01 | K17 · Credential lifecycle and key rotation
# 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
# =====================================================================
# K17 | Code cell 02 | K17 · Credential lifecycle and key rotation
# Purpose: 3. Implementation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import hashlib, hmac, json, secrets

# Define the reusable operation canonical; keep its logic separate from the trial.
def canonical(x):return json.dumps(x,sort_keys=True,separators=(',',':'),allow_nan=False).encode()

# Define the reusable operation mac; keep its logic separate from the trial.
def mac(key,obj):return hmac.new(key,canonical(obj),hashlib.sha256).hexdigest()

# Define the reusable operation evidence; keep its logic separate from the trial.
def evidence(lab,checks):return {'schema':'psut-security-evidence-157','experiment':lab,'source':'actual-local-defensive-teaching-test','checks':[{'control':n,'pass':bool(p)} for n,p in checks],'pass':all(p for _,p in checks)}

# Define the reusable operation rotation; keep its logic separate from the trial.
def rotation():
    keys={'old':secrets.token_bytes(32),'new':secrets.token_bytes(32)};active={'old'};seen={}
    def packet(kid,seq):
        obj={'device':'fictional-sensor','kid':kid,'seq':seq,'temperature':25};return {**obj,'tag':mac(keys[kid],obj)}
    def accept(p):
        obj={k:v for k,v in p.items() if k!='tag'};kid=p['kid'];seq=p['seq']
        if kid not in active or not hmac.compare_digest(mac(keys[kid],obj),p['tag']):return False
        if type(seq) is not int or seq<=seen.get(p['device'],-1):return False
        seen[p['device']]=seq;return True
    p=packet('old',1);checks=[('old key initially accepted',accept(p)),('duplicate rejected',not accept(p))]
    active={'new'};checks.append(('retired key rejected even with new sequence',not accept(packet('old',2))))
    q=packet('new',2);tamper={**q,'temperature':40};checks.extend([('altered message rejected',not accept(tamper)),('valid rotated key accepted',accept(q)),('sequence rollback rejected across rotation',not accept(packet('new',1)))])
    return evidence('K17',checks)
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
# =====================================================================
# K17 | Code cell 03 | K17 · Credential lifecycle and key rotation
# 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,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=rotation()
    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
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 cd ~/kali-labs python3 defensive_range.py rotation ``` ```bash cd ~/kali-labs mkdir -p ~/psut-security-results python3 defensive_range.py rotation > ~/psut-security-results/K17-evidence.json && cat ~/psut-security-results/K17-evidence.json ``` ```python #!/usr/bin/env python3 """Controlled local defensive exercises. Fictional data, ephemeral keys; no network targets.""" import argparse, copy, hashlib, hmac, json, secrets def canonical(x):return json.dumps(x,sort_keys=True,separators=(',',':'),allow_nan=False).encode() def mac(key,obj):return hmac.new(key,canonical(obj),hashlib.sha256).hexdigest() def evidence(lab,checks):return {'schema':'psut-security-evidence-157','experiment':lab,'source':'actual-local-defensive-teaching-test','checks':[{'control':n,'pass':bool(p)} for n,p in checks],'pass':all(p for _,p in checks)} def audit(): key=secrets.token_bytes(32);log=[];previous='0'*64 for i,event in enumerate(['connect accepted','publication accepted','publication denied','disconnect']): entry={'seq':i,'event':event,'prev':previous};previous=mac(key,entry);log.append({**entry,'tag':previous}) anchor=(len(log),previous) # Held separately in this exercise, not durable production storage. def valid(rows): prev='0'*64 for i,r in enumerate(rows): item={k:v for k,v in r.items() if k!='tag'} if r['seq']!=i or r['prev']!=prev or not hmac.compare_digest(mac(key,item),r['tag']):return False prev=r['tag'] return (len(rows),prev)==anchor changed=copy.deepcopy(log);changed[1]['event']='changed';swapped=copy.deepcopy(log);swapped[1],swapped[2]=swapped[2],swapped[1] return evidence('K16',[('original authenticated chain',valid(log)),('modified event rejected',not valid(changed)),('reordered entries rejected',not valid(swapped)),('interior deletion rejected',not valid(log[:1]+log[2:])),('truncated suffix rejected against separate anchor',not valid(log[:-1]))]) def rotation(): keys={'old':secrets.token_bytes(32),'new':secrets.token_bytes(32)};active={'old'};seen={} def packet(kid,seq): obj={'device':'fictional-sensor','kid':kid,'seq':seq,'temperature':25};return {**obj,'tag':mac(keys[kid],obj)} def accept(p): obj={k:v for k,v in p.items() if k!='tag'};kid=p['kid'];seq=p['seq'] if kid not in active or not hmac.compare_digest(mac(keys[kid],obj),p['tag']):return False if type(seq) is not int or seq<=seen.get(p['device'],-1):return False seen[p['device']]=seq;return True p=packet('old',1);checks=[('old key initially accepted',accept(p)),('duplicate rejected',not accept(p))] active={'new'};checks.append(('retired key rejected even with new sequence',not accept(packet('old',2)))) q=packet('new',2);tamper={**q,'temperature':40};checks.extend([('altered message rejected',not accept(tamper)),('valid rotated key accepted',accept(q)),('sequence rollback rejected across rotation',not accept(packet('new',1)))]) return evidence('K17',checks) if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('experiment',choices=['audit','rotation']);a=p.parse_args();r=globals()[a.experiment]();print(json.dumps(r,indent=2));raise SystemExit(0 if r['pass'] else 1) ```
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 local defensive reference; ephemeral keys/files. 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. Select grace and inspect which old-key message is accepted after rotation; compare the corresponding new-key sequence collision. 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