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

K16 · Authenticated audit log verification

Ask Dr. Mohammad · K16 →

Verify integrity and ordering of fictional audit events and explain why a trusted anchor is necessary.

← Security range
Design experiment & verify evidence →
K16 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Kali & IoT securityK16 · Authenticated audit log verification

Before you start

Complete K01 and K06. 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 integrity and ordering of fictional audit events and explain why a trusted anchor is necessary.

Updated Kali toolkit
K16 · Academic orientation

Scope and objectives

Scope of the experiment

Verify integrity and ordering of fictional audit events and explain why a trusted anchor is necessary.

The focus of this experiment is to trace authenticated audit records and their sequence or linkage. Students then detect modified or reordered entries using the verification rule, and explain trusted anchors and remaining deletion or availability risks. The Concepts view explains the operation before the practical work; the Simulation view is used to examine reference and changed inputs, not to substitute for actual measurements.

Learning objectives

  • Trace authenticated audit records and their sequence or linkage.
  • Detect modified or reordered entries using the verification rule.
  • Explain trusted anchors and remaining deletion or availability risks.
  • Identify the configured inputs (Candidate log change; Verify separate count and final tag; Second original event) and record the corresponding observed outputs with units where applicable.
  • Compare the reference calculation or decision with an independent implementation or authorized observation; state any discrepancy and the applicable model boundary.

Expected learning outcomes

On completion, students can trace authenticated audit records and their sequence or linkage, detect modified or reordered entries using the verification rule, and explain trusted anchors and remaining deletion or availability risks.

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 explain trusted anchors and remaining deletion or availability risks. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to K17 · Credential lifecycle and key rotation.

Environment and experimental methodology

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

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

Understand the experiment

Scientific architecture · Authenticated audit-chain verifier

Authenticated audit-chain records — Record 1 / payload + previous commitment; Tag 1 / HMAC with secret key; Record 2 / includes tag 1; Tag 2 / authenticated linkage; Verify / changed record or missing link fails
Scientific concept map: Audit record — Sequence and event; Previous digest — Link record; HMAC — Authenticate chain entry; Verifier — Order and tag checks; Result — Identify first failure.

Scientific foundations and analytical reasoning

An authenticated log chains event tags, binding order and content. A separately trusted count/final tag is needed to detect truncation.

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 · Chained authentication and truncation

An authenticated audit chain incorporates each event and the preceding authentication tag into the next tag. This binds event order and contents. A verifier must also possess a trusted checkpoint, such as expected count and final tag, to detect removal of a suffix.

Worked example and engineering interpretation

Removing an interior record causes the next verification link to fail. Removing only the last record can leave a valid shorter chain unless the expected length or checkpoint is verified. Test modification, reordering and truncation separately using local fixture logs.

Engineering principles · additional worked teaching example

A chained audit record commits to the previous hash/tag and current bytes; verification recomputes chain. Without a trusted external anchor, deleting a suffix can go undetected. A valid chain alone does not prove event truth.

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 K16 · Authenticated audit log verification

Verify integrity and ordering of fictional audit events and explain why a trusted anchor is necessary.

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 integrity and ordering of fictional audit events and explain why a trusted anchor is necessary.

  1. Build the four-entry log and retain its final tag and count. Inspect each entry sequence, previous tag and HMAC.
  2. Modify the second event and verify that the first failing row is identified.
  3. Choose reorder, then delete interior, and compare sequence/previous-tag failures.
  4. Choose truncate suffix with anchor enabled. Per-record checks can pass, but the separate count/final tag rejects the incomplete log.

Reference check:

Model boundary:

Independent task and submission evidence

2. Modify the second event and verify that the first failing row is identified. 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: Candidate log change = none; Verify separate count and final tag = true; Second original event = publication accepted. In the classroom model, Verification = Accepted; Candidate records = 4; Local links valid = Yes; Anchor matches = Yes. A valid prefix is not necessarily a complete log. The anchor detects truncation even if the retained links verify. Actual HMAC-SHA-256 over fictional records, anchor held within the experiment, not a durable audit 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 · operation pathway

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.

K16 · Authenticated audit log verification: operation pathwaySeq 0connect accepted ·47db488f357…Seq 1publicationaccepted ·a328e4def38…Seq 2publication denied· ece54fd7e24…Seq 3disconnect ·d37ef8c458a…Read the active operation, then inspect the accumulated state.

Step 1 of 4 · Seq 0

Seq 0

Seq 0
connect accepted · 47db488f357…

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

Recall the concept before revealing its explanation.

0 / 3 revealed
K16 · 01 / 08What does a chained HMAC protect?Reveal explanation
Engineering explanation

Each record authenticates its content and previous tag, so reorder and modification become detectable.

K16 · 02 / 08Why keep a separate anchor?Reveal explanation
Engineering explanation

A chain alone cannot prove that its final entries were not removed. A separately trusted count and last tag detect truncation.

K16 · 03 / 08Is this a durable production log?Reveal explanation
Engineering explanation

No. The key and anchor live in memory. Production needs protected persistent storage and lifecycle controls.

K16 · 04 / 08Why does an authenticated log chain include previous record information?Reveal explanation
Engineering reasoning

It binds record ordering and helps expose modifications or missing links when checked against a trusted reference.

K16 · 05 / 08Why keep a trusted checkpoint separate?Reveal explanation
Engineering reasoning

An attacker who can replace the entire chain may recompute it; an external trusted commitment limits undetected replacement.

K16 · 06 / 08A hash-linked audit log is modified. Select every technically valid statement. A. Validate ordering and each authenticated record. B. Compare with a separately trusted anchor to detect a rebuilt history. C. Internal hash consistency alone proves historical authenticity. D. A recomputed public hash can never be generated by an attacker.Reveal explanation
Applied scenario

Correct: A. Validate ordering and each authenticated record.; B. Compare with a separately trusted anchor to detect a rebuilt history.

K16 · 07 / 08Which engineering mechanism is tested by K16 · Authenticated audit log verification, and what state or outcome is evaluated?Reveal explanation
Implementation recall

Verify integrity and ordering of fictional audit events and explain why a trusted anchor is necessary.

K16 · 08 / 08For K16 · Authenticated audit log verification, 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 audit. Require five pass flags and explain why independent anchor/count is necessary for truncation detection. Uses ephemeral key and fictional events, not live broker-log monitoring.

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

K16 · 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
K16 · Authenticated audit log verification

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 authenticated audit-chain five controls passed.

Run defensive_range.py audit. Require five pass flags and explain why independent anchor/count is necessary for truncation detection. Uses ephemeral key and fictional events, not live broker-log monitoring.

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

Draw four events E1…E4 with chained tags. Mark which tags must be recomputed after E2 changes, then evaluate deletion of E4 against an anchored count.

02 · Compare or justify using evidence

Explain why a valid prefix may pass without an independent final anchor and why a trusted tag is not equivalent to an unkeyed hash.

03 · Data reasoning

Data reasoning · Independent work

Three records are chained and last trusted digest is held separately. Record 2 is modified. Explain verification consequences and why a new self-consistent chain is insufficient.

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

Use the reference configuration (Candidate log change = none; Verify separate count and final tag = true; Second original event = publication accepted), but change Candidate log change = delete interior. The model reports Verification = Rejected. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Interpret a state transition

Independent theoretical exercise · K16-02

The reference model reports Verification: Accepted. Under Candidate log change = delete interior it reports Rejected. Explain which configured condition changed and what the two outputs establish, and what they do not establish.

Intermediate · Interpret a technical trace

Independent theoretical exercise · K16-03

For Candidate log change = modify event, the model supplies this excerpt from Candidate audit chain: Position · Sequence · Event · Previous tag · Tag · Local check 0 · 0 · connect accepted · 0000000000000000000000000000000000000000000000000000000000000000 · 47db488f357ef094404b647a4b929b999afff2854b1f8ed60d52bbf615fa79c6 · Yes 1 · 1 · publication accepted modified · 47db488f357ef094404b647a4b929b999afff2854b1f8ed60d52bbf615fa79c6 · a328e4def38feabeb7d387402f0f73865bb2d2bf8e9d658d7af6bef6e041756a · No 2 · 2 · publication denied · a328e4def38feabeb7d387402f0f73865bb2d2bf8e9d658d7af6bef6e041756a · ece54fd7e24a60d67d7d116ca6244b7601a20ec5dc7c57a7ae72d7268f4e40e4 · Yes 3 · 3 · disconnect · ece54fd7e24a60d67d7d116ca6244b7601a20ec5dc7c57a7ae72d7268f4e40e4 · d37ef8c458a0af19c3ee446c65a7477103d00d7cc14736ff48864f1caedad744 · Yes 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 · K16-04

An observation is Verification = Rejected. Candidate A uses Candidate log change = none; Verify separate count and final tag = true; Second original event = publication accepted. Candidate B changes the listed settings (Candidate log change = modify event) 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 · K16-05

A student configures Candidate log change = reorder while preserving all other reference settings, but copies the reference report of Verification = Accepted. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · K16-06

Design a controlled comparison for K16 · Authenticated audit log verification using reference Candidate log change = none; Verify separate count and final tag = true; Second original event = publication accepted and test Candidate log change = delete interior. Specify the changed setting(s), measured metric Verification, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Detect log alteration, reordering and truncation using authenticated links and a separate anchor.

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.

Candidate log changenone
Verify separate count and final tagYes
Second original eventpublication accepted

2 · Perform the investigation in order

  1. Build the four-entry log and retain its final tag and count. Inspect each entry sequence, previous tag and HMAC.
  2. Modify the second event and verify that the first failing row is identified.
  3. Choose reorder, then delete interior, and compare sequence/previous-tag failures.
  4. Choose truncate suffix with anchor enabled. Per-record checks can pass, but the separate count/final tag rejects the incomplete log.
  5. Disable the anchor only in the teaching model and repeat truncation. Explain the false completeness conclusion.
  6. Run defensive_range.py audit locally and compare its five controls.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Intact chainUse reference inputs aboveVerification: AcceptedRecord actual result
Modified eventCandidate log change = modify eventVerification: RejectedRecord actual result
ReorderedCandidate log change = reorderVerification: RejectedRecord actual result
Suffix with anchorCandidate log change = truncate suffixVerification: RejectedRecord actual result
Suffix without anchorCandidate log change = truncate suffix; Verify separate count and final tag = NoVerification: AcceptedRecord actual result

4 · Analyze and report

Why does an authenticated chain require an independently trusted completeness anchor?

Required evidence: Authenticated chain and four negative-control traces.

Model boundary: Actual HMAC-SHA-256 over fictional records, anchor held within the experiment, not a durable audit 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
Intact chainUse reference inputs aboveRecord actual outcome and units
Modified eventCandidate log change = modify eventRecord actual outcome and units
ReorderedCandidate log change = reorderRecord actual outcome and units
Suffix with anchorCandidate log change = truncate suffixRecord 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 audit
✓ Expected: Five controls pass: original chain, altered event, reorder, deletion and suffix truncation rejection against a separate anchor.

3. Save actual verification evidence

Kali WSL · Bash
cd ~/kali-labs
mkdir -p ~/psut-security-results
python3 defensive_range.py audit > ~/psut-security-results/K16-evidence.json && cat ~/psut-security-results/K16-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 experiment creates four fictional events, authenticates canonical JSON with an ephemeral HMAC key and checks a separately held count and final tag. This is a local defensive exercise, not a live broker log collector.

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

K16 · 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
# K16 · K16 · Authenticated audit log verification **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Introduction Verify integrity and ordering of fictional audit events and explain why a trusted anchor is necessary. ## 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 integrity and ordering of fictional audit events and explain why a trusted anchor is necessary. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Build the four-entry log and retain its final tag and count. Inspect each entry sequence, previous tag and HMAC. 2. Modify the second event and verify that the first failing row is identified. 3. Choose reorder, then delete interior, and compare sequence/previous-tag failures. 4. Choose truncate suffix with anchor enabled. Per-record checks can pass, but the separate count/final tag rejects the incomplete log. 5. Disable the anchor only in the teaching model and repeat truncation. Explain the false completeness conclusion. **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
# =====================================================================
# K16 | Code cell 01 | K16 · Authenticated audit log verification
# 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
# =====================================================================
# K16 | Code cell 02 | K16 · Authenticated audit log verification
# 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 copy, 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 audit; keep its logic separate from the trial.
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]))])
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
# =====================================================================
# K16 | Code cell 03 | K16 · Authenticated audit log verification
# 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=audit()
    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 audit ``` ```bash cd ~/kali-labs mkdir -p ~/psut-security-results python3 defensive_range.py audit > ~/psut-security-results/K16-evidence.json && cat ~/psut-security-results/K16-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. Modify the second event and verify that the first failing row is identified. 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