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

K19 · Certificate revocation lifecycle

Ask Dr. Mohammad · K19 →

Verify certificate revocation using a signed CRL and independent positive and negative controls.

← Security range
Design experiment & verify evidence →
K19 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Kali & IoT securityK19 · Certificate revocation lifecycle

Before you start

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

Learning outcome

Verify certificate revocation using a signed CRL and independent positive and negative controls.

Updated Kali toolkit

Predict: Record the expected outcomes before running the program.

K19 · Academic orientation

Scope and objectives

Scope of the experiment

Verify certificate revocation using a signed CRL and independent positive and negative controls.

The focus of this experiment is to identify certificate validity and revocation as distinct conditions. Students then trace an authorized local certificate lifecycle and CRL check, and verify rejection of a revoked credential using the configured trust 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

  • Identify certificate validity and revocation as distinct conditions.
  • Trace an authorized local certificate lifecycle and CRL check.
  • Verify rejection of a revoked credential using the configured trust policy.
  • Identify the configured inputs (Client certificate; CRL version; Relying party checks CRL; Verification minute (valid 0–60); Issuer trusted) 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 identify certificate validity and revocation as distinct conditions, trace an authorized local certificate lifecycle and CRL check, and verify rejection of a revoked credential using the configured trust 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 rejection of a revoked credential using the configured trust policy. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to K20 · Authenticated IoT gateway and defensive monitoring.

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 · Certificate revocation lifecycle

Certificate revocation checking — CA; Client; Service; Issue certificate / 0>2; Present certificate / 2>1; Retrieve CRL / 1>0; Signed list / 0>1; Validate freshness & status / 1>1
Scientific concept map: Certificate authority — Issue certificate; Revocation list — Serial numbers / update; Client trust check — Validity and identity; CRL policy — Current or stale list; Decision — Accept or reject.

Scientific foundations and analytical reasoning

A signed CRL records revoked certificate serials and has a validity window. Trust, current time and revocation policy are independent.

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 · Revocation and certificate validity

A certificate can be inside its validity interval but revoked. A CRL is a signed list of revoked serials for an issuing authority and has update times. A relying party needs valid trust, time and revocation policy. An unavailable or stale list must be handled under the declared failure policy.

Worked example and engineering interpretation

Use the local CRL fixture to compare a valid unlisted serial, a revoked serial and an expired list. Do not infer that every unlisted certificate is valid: identity, signature and validity still need checking. Record the exact verification reason.

Engineering principles · additional worked teaching example

A CRL is signed issuer evidence listing revoked certificate serials, with update times; expiration is independent. A path can otherwise validate yet be rejected when valid CRL lists the leaf. CRL absence is not proof of no revocation.

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 K19 · Certificate revocation lifecycle

Verify certificate revocation using a signed CRL and independent positive and negative controls.

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 certificate revocation using a signed CRL and independent positive and negative controls.

  1. Select sensor, initial CRL and minute 10; verify the certificate and empty revocation list.
  2. Choose sensor revoked and inspect the matching serial and the certificate-revoked result.
  3. Keep the updated CRL but switch to viewer. Confirm it is not revoked.
  4. Disable CRL checking in the model only, then compare with the enforced result. Explain the relying-party requirement.

Reference check:

Model boundary:

Independent task and submission evidence

2. Choose sensor revoked and inspect the matching serial and the certificate-revoked result. 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: Client certificate = sensor; CRL version = initial; Relying party checks CRL = true; Verification minute (valid 0–60) = 10; Issuer trusted = true. In the classroom model, Verification = Accepted; Reason = Valid under selected policy; Serial = A101; CRL checking = Yes. A valid status is conditional on the configured trust, validity and revocation checks. Logical certificate/CRL policy fixture; real certificate creation, signature and CRL validation occur in the local Python/OpenSSL lab.

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 · message sequence

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.

K19 · Certificate revocation lifecycle: message sequenceCA / CRLRelying partyClientinitialCertificate A101Valid under selected policy

Step 1 of 3 · initial

initial

1. CA / CRL → Relying party
initial

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

Recall the concept before revealing its explanation.

0 / 3 revealed
K19 · 01 / 08What is a CRL?Reveal explanation
Engineering explanation

A signed certificate revocation list issued by a CA.

K19 · 02 / 08What does revocation check establish?Reveal explanation
Engineering explanation

The verifier rejects a listed serial under the current CRL.

K19 · 03 / 08Does revocation terminate an existing session?Reveal explanation
Engineering explanation

Not automatically; distribution, verifier policy and session handling are separate.

K19 · 04 / 08Why does certificate expiration differ from revocation?Reveal explanation
Engineering reasoning

Expiration is time-based validity; revocation withdraws trust before expiration according to the configured revocation mechanism.

K19 · 05 / 08Why test a non-revoked certificate as a reference?Reveal explanation
Engineering reasoning

It distinguishes revocation-specific rejection from a broken CA, hostname or listener configuration.

K19 · 06 / 08A signed certificate revocation list is used. Select every technically valid statement. A. Verify the list signature and validity conditions. B. Test a revoked and a non-revoked certificate under the configured policy. C. A certificate is permanently trustworthy until its expiry regardless of revocation. D. An unsigned list is equivalent to a verified CRL.Reveal explanation
Applied scenario

Correct: A. Verify the list signature and validity conditions.; B. Test a revoked and a non-revoked certificate under the configured policy.

K19 · 07 / 08Which engineering mechanism is tested by K19 · Certificate revocation lifecycle, and what state or outcome is evaluated?Reveal explanation
Implementation recall

Verify certificate revocation using a signed CRL and independent positive and negative controls.

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

Run security_extensions.py revocation. Require valid sensor before revocation, certificate revoked for sensor after revocation, valid viewer. Temporary CA/CRL files are deleted. This is explicit offline CRL verification, not automatic broker session termination.

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

K19 · 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
K19 · Certificate revocation lifecycle

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 OpenSSL CRL three controls passed.

Run security_extensions.py revocation. Require valid sensor before revocation, certificate revoked for sensor after revocation, valid viewer. Temporary CA/CRL files are deleted. This is explicit offline CRL verification, not automatic broker session termination.

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

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

Independent theoretical exercises

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

01 · Predict and derive using the given inputs

For valid time 0–60 min, evaluate minute 10 with an initial CRL, minute 10 with a CRL listing sensor, and minute 61 with checking required.

02 · Compare or justify using evidence

Explain why an unchecked revocation list cannot prove a revoked certificate is accepted by policy; distinguish invalid CRL issuer from revoked end certificate.

03 · Trust analysis

Trust analysis · Independent work

Leaf is valid today and signed by trusted CA; its serial is listed in an authenticated current CRL. Explain expected verification and contrast with an expired leaf.

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

Use the reference configuration (Client certificate = sensor; CRL version = initial; Relying party checks CRL = true; Verification minute (valid 0–60) = 10; Issuer trusted = true), but change Client certificate = viewer. The model reports Serial = A102. Explain the governing rule and assumptions that make this output plausible; identify an independent verification method.

Intermediate · Interpret a state transition

Independent theoretical exercise · K19-02

The reference model reports Serial: A101. Under Client certificate = viewer it reports A102. 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 · K19-03

For Relying party checks CRL = false, the model supplies this excerpt from Issued client certificates: Identity · Serial · Validity (minute) · Revocation status sensor · A101 · 0–60 · Not listed viewer · A102 · 0–60 · Not listed Count rows whose Serial value is exactly “A101”, and identify the displayed row numbers. Explain what the count describes.

Advanced · Reverse reasoning

Independent theoretical exercise · K19-04

An observation is CRL checking = No. Candidate A uses Client certificate = sensor; CRL version = initial; Relying party checks CRL = true; Verification minute (valid 0–60) = 10; Issuer trusted = true. Candidate B changes the listed settings (Relying party checks CRL = false) 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 · K19-05

A student configures Verification minute (valid 0–60) = 120 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 · K19-06

Design a controlled comparison for K19 · Certificate revocation lifecycle using reference Client certificate = sensor; CRL version = initial; Relying party checks CRL = true; Verification minute (valid 0–60) = 10; Issuer trusted = true and test Client certificate = viewer. Specify the changed setting(s), measured metric Serial, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Investigate certificate status before and after revocation and distinguish verification from distribution.

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.

Client certificatesensor
CRL versioninitial
Relying party checks CRLYes
Verification minute (valid 0–60)10
Issuer trustedYes

2 · Perform the investigation in order

  1. Select sensor, initial CRL and minute 10; verify the certificate and empty revocation list.
  2. Choose sensor revoked and inspect the matching serial and the certificate-revoked result.
  3. Keep the updated CRL but switch to viewer. Confirm it is not revoked.
  4. Disable CRL checking in the model only, then compare with the enforced result. Explain the relying-party requirement.
  5. Advance beyond the validity window; distinguish an expired certificate from a revoked one.
  6. Run the preserved security_extensions.py revocation practical to obtain actual OpenSSL CRL verification results.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Sensor initially validUse reference inputs aboveVerification: AcceptedRecord actual result
Sensor revokedCRL version = sensor revokedReason: Certificate revokedRecord actual result
Viewer not revokedCRL version = sensor revoked; Client certificate = viewerVerification: AcceptedRecord actual result
Checking disabledCRL version = sensor revoked; Relying party checks CRL = NoVerification: AcceptedRecord actual result
Expired listVerification minute (valid 0–60) = 70Reason: Certificate expiredRecord actual result

4 · Analyze and report

Describe how an updated list reaches clients and why revocation does not automatically end an established session.

Required evidence: Before/after decisions, serial inventory and actual local verification output.

Model boundary: Logical certificate/CRL policy fixture; real certificate creation, signature and CRL validation occur in the local Python/OpenSSL lab.

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
Sensor initially validUse reference inputs aboveRecord actual outcome and units
Sensor revokedCRL version = sensor revokedRecord actual outcome and units
Viewer not revokedCRL version = sensor revoked; Client certificate = viewerRecord actual outcome and units
Checking disabledCRL version = sensor revoked; Relying party checks CRL = NoRecord actual outcome and units

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

Loading laboratory-specific procedure…

Python / Google Colab notebook

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

Download NotebookOpen Google ColabAll Python notebooks

Independent implementation sequence

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

Complete practical procedure

1. Check updated implementation

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

2. Execute verification

Kali WSL · Bash
cd ~/kali-labs
python3 security_extensions.py revocation
✓ Expected: Three controls pass: valid sensor before revocation, revoked sensor rejected with certificate revoked, unrevoked viewer valid.

3. Record and reflect

Notebook action

Record the actual output and compare with the expected decisions.

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

Experimental notebook

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

Scientific method and source

Three controls pass: valid sensor before revocation, revoked sensor rejected with certificate revoked, unrevoked viewer valid. Record all actual outputs; a missing dependency is not a passed security test.

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

Download source
Read complete source
PYTHON · Source code
#!/usr/bin/env python3
"""Defensive coursework with fictional records, temporary keys and local certificate files only."""
import argparse, csv, datetime, hashlib, hmac, json, math, os, platform, secrets, ssl, statistics, subprocess, tempfile, time
from pathlib import Path
from cryptography import x509
from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID
from cryptography.hazmat.primitives import hashes, serialization
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
import ascon_course as ascon

def benchmark():
    key=secrets.token_bytes(16); aes=AESGCM(key); ad=b'PSUT fictional telemetry'; rows=[]
    # Same payload, AAD and paired trial counts. Unique nonces within each algorithm.
    # Distinct algorithms and implementations, not an isolated algorithm comparison.
    ak=secrets.token_bytes(16)
    for size in (32,128,512,1024):
        msg=b'x'*size
        for trial in range(110):
            order=('AES-GCM','Ascon-AEAD128') if trial%2==0 else ('Ascon-AEAD128','AES-GCM')
            for name in order:
                n=(size*1000+trial).to_bytes(12 if name=='AES-GCM' else 16,'big')
                t=time.perf_counter_ns()
                if name=='AES-GCM': c=aes.encrypt(n,msg,ad);plain=aes.decrypt(n,c,ad)
                else:c=ascon.encrypt(ak,n,ad,msg);plain=ascon.decrypt(ak,n,ad,c)
                elapsed=(time.perf_counter_ns()-t)/1000
                assert plain==msg and len(c)==size+16
                if trial>=10:rows.append([name,size,trial-9,elapsed,len(c),len(n)])
    with open('aead-comparison.csv','x',newline='') as f:
        w=csv.writer(f);w.writerow(['algorithm','payload_bytes','trial','combined_us','ciphertext_tag_bytes','nonce_bytes']);w.writerows(rows)
    summaries=[]
    for name in ('AES-GCM','Ascon-AEAD128'):
        for size in (32,128,512,1024):
            t=sorted(r[3] for r in rows if r[0]==name and r[1]==size);summaries.append({'algorithm':name,'bytes':size,'n':len(t),'median_us':statistics.median(t),'p95_us':t[math.ceil(.95*len(t))-1]})
    return {'provenance':'actual host timing, synthetic payload','pass':True,'trials':len(rows),'python':platform.python_version(),'machine':platform.machine(),'openssl':ssl.OPENSSL_VERSION,'warmups':10,'summary':summaries,'limitations':'Python teaching Ascon versus cryptography native AES-GCM; not an algorithm-only, MCU, energy or memory comparison. No memory measurements collected.'}

def certificates(directory):
    p=Path(directory);now=datetime.datetime.now(datetime.timezone.utc);key=ec.generate_private_key(ec.SECP256R1());ca=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'PSUT temporary CA')]);
    def write(label,k,c):
        (p/(label+'.pem')).write_bytes(c.public_bytes(serialization.Encoding.PEM)); f=p/(label+'.key');f.write_bytes(k.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()));f.chmod(0o600)
    def cert(name,k,root=False,server=False):
        b=x509.CertificateBuilder().subject_name(name).issuer_name(ca).public_key(k.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now-datetime.timedelta(minutes=1)).not_valid_after(now+datetime.timedelta(hours=1)).add_extension(x509.BasicConstraints(ca=root,path_length=0 if root else None),critical=True).add_extension(x509.SubjectKeyIdentifier.from_public_key(k.public_key()),False).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False).add_extension(x509.KeyUsage(digital_signature=not root,content_commitment=False,key_encipherment=False,data_encipherment=False,key_agreement=False,key_cert_sign=root,crl_sign=root,encipher_only=None,decipher_only=None),True)
        if not root:
            b=b.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH if server else ExtendedKeyUsageOID.CLIENT_AUTH]),False)
            if server:b=b.add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]),False)
        return b.sign(key,hashes.SHA256())
    root=cert(ca,key,True);write('ca',key,root);issued={}
    for name in ('localhost','sensor','viewer'):
        k=ec.generate_private_key(ec.SECP256R1());c=cert(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,name)]),k,server=name=='localhost');write(name,k,c);issued[name]=c
    def crl(revoke):
        b=x509.CertificateRevocationListBuilder().issuer_name(ca).last_update(now-datetime.timedelta(minutes=1)).next_update(now+datetime.timedelta(hours=1)).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False).add_extension(x509.CRLNumber(2 if revoke else 1),False)
        if revoke:b=b.add_revoked_certificate(x509.RevokedCertificateBuilder().serial_number(issued['sensor'].serial_number).revocation_date(now).build())
        return b.sign(key,hashes.SHA256()).public_bytes(serialization.Encoding.PEM)
    (p/'valid.crl').write_bytes(crl(False));(p/'revoked.crl').write_bytes(crl(True))

def revocation():
    with tempfile.TemporaryDirectory(prefix='psut-crl-') as tmp:
        certificates(tmp);p=Path(tmp);checks=[]
        for label,crl,identity,expected in [('initial client valid','valid','sensor',True),('retired client revoked','revoked','sensor',False),('unrevoked viewer valid','revoked','viewer',True)]:
            r=subprocess.run(['openssl','verify','-CAfile',str(p/'ca.pem'),'-CRLfile',str(p/(crl+'.crl')),'-crl_check','-purpose','sslclient',str(p/(identity+'.pem'))],capture_output=True,text=True,timeout=10)
            msg=(r.stdout+r.stderr).replace(tmp,'<temporary>');passed=r.returncode==0 if expected else r.returncode!=0 and 'certificate revoked' in msg.lower();checks.append({'name':label,'pass':passed,'exit':r.returncode,'observation':msg.strip()})
        return {'source':'actual OpenSSL CRL verification','checks':checks,'pass':all(x['pass'] for x in checks),'limitation':'CRL check must be enabled at relying party. This is not automatic distribution or session termination.'}

def gateway():
    key=secrets.token_bytes(32);highest=0;logs=[];accepted=[]
    def packet(seq,temp):
        raw=json.dumps({'device':'demo-01','seq':seq,'temperature':temp},separators=(',',':'),allow_nan=False).encode();return raw,hmac.digest(key,raw,'sha256')
    def check(raw,tag):
        nonlocal highest
        if len(raw)>512 or not hmac.compare_digest(hmac.digest(key,raw,'sha256'),tag):return 'integrity-rejected'
        try:d=json.loads(raw);good=type(d)==dict and set(d)=={'device','seq','temperature'} and d['device']=='demo-01' and type(d['seq']) is int and 1<=d['seq']<=2**31-1 and type(d['temperature']) in (int,float) and math.isfinite(d['temperature']) and -40<=d['temperature']<=80
        except (ValueError,TypeError,OverflowError):good=False
        if not good:return 'schema-rejected'
        if d['seq']<=highest:return 'replay-rejected'
        highest=d['seq'];accepted.append(d);return 'accepted'
    good=packet(1,25);bad=packet(2,30);tests=[('positive',*good,'accepted'),('duplicate',*good,'replay-rejected'),('tampered',bad[0]+b' ',bad[1],'integrity-rejected'),('invalid range',*packet(2,90),'schema-rejected'),('recovery',*packet(2,26),'accepted')]
    for label,raw,tag,expected in tests:
        actual=check(raw,tag);logs.append({'case':label,'decision':actual,'expected':expected,'pass':actual==expected})
    counts={x:sum(r['decision']==x for r in logs) for x in set(r['decision'] for r in logs)}
    # Deliberately bounded local rule; no real broker logs are claimed.
    return {'source':'actual local gateway policy evaluation of fictional cases','pass':all(x['pass'] for x in logs),'events':logs,'accepted':accepted,'decision_counts':counts,'alert':sum(v for k,v in counts.items() if k!='accepted')>=3,'limitations':'In-memory state, synthetic event monitor, no production gateway or live broker integration. Range checks do not detect all malicious readings.'}

if __name__=='__main__':
    p=argparse.ArgumentParser();p.add_argument('experiment',choices=['benchmark','revocation','gateway']);args=p.parse_args();r=globals()[args.experiment]();print(json.dumps(r,indent=2));raise SystemExit(0 if r['pass'] else 1)

Verification and discussion

Three controls pass: valid sensor before revocation, revoked sensor rejected with certificate revoked, unrevoked viewer valid.

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

Record evidence → · Ask Dr. Mohammad →

Python / Google Colab laboratory

K19 · 12 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
# K19 · K19 · Certificate revocation lifecycle **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Introduction Verify certificate revocation using a signed CRL and independent positive and negative controls. ## How to run 1. Download this notebook from the laboratory page. Open Google Colab → File → Upload notebook. 2. Select a Python CPU runtime. Run cells from top to bottom using Shift+Enter, or Runtime → Run all. 3. Read the printed observations and assertions. Change one parameter at a time and rerun the relevant cell. 4. Save your own outputs and compare them to the portal Experiment tab. **Execution boundary:** Original local cryptography reference (ephemeral files); not production validation. Do not run the hardware or service commands in Colab. No real credentials are needed. The notebook is self-contained.
02Instructions · Markdown
## Experiment-specific preparation Verify certificate revocation using a signed CRL and independent positive and negative controls. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Select sensor, initial CRL and minute 10; verify the certificate and empty revocation list. 2. Choose sensor revoked and inspect the matching serial and the certificate-revoked result. 3. Keep the updated CRL but switch to viewer. Confirm it is not revoked. 4. Disable CRL checking in the model only, then compare with the enforced result. Explain the relying-party requirement. 5. Advance beyond the validity window; distinguish an expired certificate from a revoked one. **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
# =====================================================================
# K19 | Code cell 01 | K19 · Certificate revocation lifecycle
# 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.
06Instructions · Markdown
### Step 2 · Run the reference calculation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
07Python · executable cell
PYTHON · Code cell
# =====================================================================
# K19 | Code cell 03 | K19 · Certificate revocation lifecycle
# Purpose: revocation
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import datetime, subprocess, tempfile

from pathlib import Path

from cryptography import x509

from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID

from cryptography.hazmat.primitives import hashes, serialization

from cryptography.hazmat.primitives.asymmetric import ec

# Define the reusable operation certificates; keep its logic separate from the trial.
def certificates(directory):
    p=Path(directory);now=datetime.datetime.now(datetime.timezone.utc);key=ec.generate_private_key(ec.SECP256R1());ca=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'PSUT temporary CA')]);
    def write(label,k,c):
        (p/(label+'.pem')).write_bytes(c.public_bytes(serialization.Encoding.PEM)); f=p/(label+'.key');f.write_bytes(k.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()));f.chmod(0o600)
    def cert(name,k,root=False,server=False):
        b=x509.CertificateBuilder().subject_name(name).issuer_name(ca).public_key(k.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now-datetime.timedelta(minutes=1)).not_valid_after(now+datetime.timedelta(hours=1)).add_extension(x509.BasicConstraints(ca=root,path_length=0 if root else None),critical=True).add_extension(x509.SubjectKeyIdentifier.from_public_key(k.public_key()),False).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False).add_extension(x509.KeyUsage(digital_signature=not root,content_commitment=False,key_encipherment=False,data_encipherment=False,key_agreement=False,key_cert_sign=root,crl_sign=root,encipher_only=None,decipher_only=None),True)
        if not root:
            b=b.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH if server else ExtendedKeyUsageOID.CLIENT_AUTH]),False)
            if server:b=b.add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]),False)
        return b.sign(key,hashes.SHA256())
    root=cert(ca,key,True);write('ca',key,root);issued={}
    for name in ('localhost','sensor','viewer'):
        k=ec.generate_private_key(ec.SECP256R1());c=cert(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,name)]),k,server=name=='localhost');write(name,k,c);issued[name]=c
    def crl(revoke):
        b=x509.CertificateRevocationListBuilder().issuer_name(ca).last_update(now-datetime.timedelta(minutes=1)).next_update(now+datetime.timedelta(hours=1)).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False).add_extension(x509.CRLNumber(2 if revoke else 1),False)
        if revoke:b=b.add_revoked_certificate(x509.RevokedCertificateBuilder().serial_number(issued['sensor'].serial_number).revocation_date(now).build())
        return b.sign(key,hashes.SHA256()).public_bytes(serialization.Encoding.PEM)
    (p/'valid.crl').write_bytes(crl(False));(p/'revoked.crl').write_bytes(crl(True))

# Define the reusable operation revocation; keep its logic separate from the trial.
def revocation():
    with tempfile.TemporaryDirectory(prefix='psut-crl-') as tmp:
        certificates(tmp);p=Path(tmp);checks=[]
        for label,crl,identity,expected in [('initial client valid','valid','sensor',True),('retired client revoked','revoked','sensor',False),('unrevoked viewer valid','revoked','viewer',True)]:
            r=subprocess.run(['openssl','verify','-CAfile',str(p/'ca.pem'),'-CRLfile',str(p/(crl+'.crl')),'-crl_check','-purpose','sslclient',str(p/(identity+'.pem'))],capture_output=True,text=True,timeout=10)
            msg=(r.stdout+r.stderr).replace(tmp,'<temporary>');passed=r.returncode==0 if expected else r.returncode!=0 and 'certificate revoked' in msg.lower();checks.append({'name':label,'pass':passed,'exit':r.returncode,'observation':msg.strip()})
        return {'source':'actual OpenSSL CRL verification','checks':checks,'pass':all(x['pass'] for x in checks),'limitation':'CRL check must be enabled at relying party. This is not automatic distribution or session termination.'}
Ask Dr. Mohammad about this cell
08Instructions · Markdown
### Step 3 · Run the reference calculation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
09Python · executable cell
PYTHON · Code cell
# =====================================================================
# K19 | Code cell 04 | K19 · Certificate revocation lifecycle
# Purpose: Step 3 · Run the reference calculation Read the comments and variable definitions before execution. Assertions must pass; inspect values, not just completion.
# Inputs: the explicit fixture/settings below and any preceding cell state.
# Output: inspect printed values, returned records or assertions; record evidence.
# =====================================================================
import tempfile,os
# Set old for the next computation or reference condition.
old=os.getcwd()
# Limit resource lifetime to this block so files, sockets or temporary state are cleaned up.
with tempfile.TemporaryDirectory() as d:
    os.chdir(d)
    try: result=revocation()
    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
10Instructions · Markdown
## Original portal implementation (reference only) These are the actual laboratory snippets. They are retained for comparison; follow the portal setup for WSL, hardware or services. They are **not** executed by Run all. ```bash cd ~/kali-labs python3 security_extensions.py revocation ``` ```python #!/usr/bin/env python3 """Defensive coursework with fictional records, temporary keys and local certificate files only.""" import argparse, csv, datetime, hashlib, hmac, json, math, os, platform, secrets, ssl, statistics, subprocess, tempfile, time from pathlib import Path from cryptography import x509 from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID from cryptography.hazmat.primitives import hashes, serialization from cryptography.hazmat.primitives.asymmetric import ec from cryptography.hazmat.primitives.ciphers.aead import AESGCM import ascon_course as ascon def benchmark(): key=secrets.token_bytes(16); aes=AESGCM(key); ad=b'PSUT fictional telemetry'; rows=[] # Same payload, AAD and paired trial counts. Unique nonces within each algorithm. # Distinct algorithms and implementations, not an isolated algorithm comparison. ak=secrets.token_bytes(16) for size in (32,128,512,1024): msg=b'x'*size for trial in range(110): order=('AES-GCM','Ascon-AEAD128') if trial%2==0 else ('Ascon-AEAD128','AES-GCM') for name in order: n=(size*1000+trial).to_bytes(12 if name=='AES-GCM' else 16,'big') t=time.perf_counter_ns() if name=='AES-GCM': c=aes.encrypt(n,msg,ad);plain=aes.decrypt(n,c,ad) else:c=ascon.encrypt(ak,n,ad,msg);plain=ascon.decrypt(ak,n,ad,c) elapsed=(time.perf_counter_ns()-t)/1000 assert plain==msg and len(c)==size+16 if trial>=10:rows.append([name,size,trial-9,elapsed,len(c),len(n)]) with open('aead-comparison.csv','x',newline='') as f: w=csv.writer(f);w.writerow(['algorithm','payload_bytes','trial','combined_us','ciphertext_tag_bytes','nonce_bytes']);w.writerows(rows) summaries=[] for name in ('AES-GCM','Ascon-AEAD128'): for size in (32,128,512,1024): t=sorted(r[3] for r in rows if r[0]==name and r[1]==size);summaries.append({'algorithm':name,'bytes':size,'n':len(t),'median_us':statistics.median(t),'p95_us':t[math.ceil(.95*len(t))-1]}) return {'provenance':'actual host timing, synthetic payload','pass':True,'trials':len(rows),'python':platform.python_version(),'machine':platform.machine(),'openssl':ssl.OPENSSL_VERSION,'warmups':10,'summary':summaries,'limitations':'Python teaching Ascon versus cryptography native AES-GCM; not an algorithm-only, MCU, energy or memory comparison. No memory measurements collected.'} def certificates(directory): p=Path(directory);now=datetime.datetime.now(datetime.timezone.utc);key=ec.generate_private_key(ec.SECP256R1());ca=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'PSUT temporary CA')]); def write(label,k,c): (p/(label+'.pem')).write_bytes(c.public_bytes(serialization.Encoding.PEM)); f=p/(label+'.key');f.write_bytes(k.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()));f.chmod(0o600) def cert(name,k,root=False,server=False): b=x509.CertificateBuilder().subject_name(name).issuer_name(ca).public_key(k.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now-datetime.timedelta(minutes=1)).not_valid_after(now+datetime.timedelta(hours=1)).add_extension(x509.BasicConstraints(ca=root,path_length=0 if root else None),critical=True).add_extension(x509.SubjectKeyIdentifier.from_public_key(k.public_key()),False).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False).add_extension(x509.KeyUsage(digital_signature=not root,content_commitment=False,key_encipherment=False,data_encipherment=False,key_agreement=False,key_cert_sign=root,crl_sign=root,encipher_only=None,decipher_only=None),True) if not root: b=b.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH if server else ExtendedKeyUsageOID.CLIENT_AUTH]),False) if server:b=b.add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]),False) return b.sign(key,hashes.SHA256()) root=cert(ca,key,True);write('ca',key,root);issued={} for name in ('localhost','sensor','viewer'): k=ec.generate_private_key(ec.SECP256R1());c=cert(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,name)]),k,server=name=='localhost');write(name,k,c);issued[name]=c def crl(revoke): b=x509.CertificateRevocationListBuilder().issuer_name(ca).last_update(now-datetime.timedelta(minutes=1)).next_update(now+datetime.timedelta(hours=1)).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False).add_extension(x509.CRLNumber(2 if revoke else 1),False) if revoke:b=b.add_revoked_certificate(x509.RevokedCertificateBuilder().serial_number(issued['sensor'].serial_number).revocation_date(now).build()) return b.sign(key,hashes.SHA256()).public_bytes(serialization.Encoding.PEM) (p/'valid.crl').write_bytes(crl(False));(p/'revoked.crl').write_bytes(crl(True)) def revocation(): with tempfile.TemporaryDirectory(prefix='psut-crl-') as tmp: certificates(tmp);p=Path(tmp);checks=[] for label,crl,identity,expected in [('initial client valid','valid','sensor',True),('retired client revoked','revoked','sensor',False),('unrevoked viewer valid','revoked','viewer',True)]: r=subprocess.run(['openssl','verify','-CAfile',str(p/'ca.pem'),'-CRLfile',str(p/(crl+'.crl')),'-crl_check','-purpose','sslclient',str(p/(identity+'.pem'))],capture_output=True,text=True,timeout=10) msg=(r.stdout+r.stderr).replace(tmp,'<temporary>');passed=r.returncode==0 if expected else r.returncode!=0 and 'certificate revoked' in msg.lower();checks.append({'name':label,'pass':passed,'exit':r.returncode,'observation':msg.strip()}) return {'source':'actual OpenSSL CRL verification','checks':checks,'pass':all(x['pass'] for x in checks),'limitation':'CRL check must be enabled at relying party. This is not automatic distribution or session termination.'} def gateway(): key=secrets.token_bytes(32);highest=0;logs=[];accepted=[] def packet(seq,temp): raw=json.dumps({'device':'demo-01','seq':seq,'temperature':temp},separators=(',',':'),allow_nan=False).encode();return raw,hmac.digest(key,raw,'sha256') def check(raw,tag): nonlocal highest if len(raw)>512 or not hmac.compare_digest(hmac.digest(key,raw,'sha256'),tag):return 'integrity-rejected' try:d=json.loads(raw);good=type(d)==dict and set(d)=={'device','seq','temperature'} and d['device']=='demo-01' and type(d['seq']) is int and 1<=d['seq']<=2**31-1 and type(d['temperature']) in (int,float) and math.isfinite(d['temperature']) and -40<=d['temperature']<=80 except (ValueError,TypeError,OverflowError):good=False if not good:return 'schema-rejected' if d['seq']<=highest:return 'replay-rejected' highest=d['seq'];accepted.append(d);return 'accepted' good=packet(1,25);bad=packet(2,30);tests=[('positive',*good,'accepted'),('duplicate',*good,'replay-rejected'),('tampered',bad[0]+b' ',bad[1],'integrity-rejected'),('invalid range',*packet(2,90),'schema-rejected'),('recovery',*packet(2,26),'accepted')] for label,raw,tag,expected in tests: actual=check(raw,tag);logs.append({'case':label,'decision':actual,'expected':expected,'pass':actual==expected}) counts={x:sum(r['decision']==x for r in logs) for x in set(r['decision'] for r in logs)} # Deliberately bounded local rule; no real broker logs are claimed. return {'source':'actual local gateway policy evaluation of fictional cases','pass':all(x['pass'] for x in logs),'events':logs,'accepted':accepted,'decision_counts':counts,'alert':sum(v for k,v in counts.items() if k!='accepted')>=3,'limitations':'In-memory state, synthetic event monitor, no production gateway or live broker integration. Range checks do not detect all malicious readings.'} if __name__=='__main__': p=argparse.ArgumentParser();p.add_argument('experiment',choices=['benchmark','revocation','gateway']);args=p.parse_args();r=globals()[args.experiment]();print(json.dumps(r,indent=2));raise SystemExit(0 if r['pass'] else 1) ```
11Instructions · Markdown
## 4. Results and analysis Record the actual output and whether the assertions pass. Identify a parameter to vary, state your prediction, repeat the reference calculation, then explain the changed result. | Trial | Configuration | Observation | Interpretation | |---|---|---|---| | A | Reference | | | | B | One controlled change | | | | C | Reference repeat | | | **Limitations:** Original local cryptography reference (ephemeral files); not production validation. Notebook success does not certify external equipment or services.
12Instructions · Markdown
## Guided reasoning and evidence A controlled comparison changes one independent input while keeping the other relevant inputs fixed; the dependent variable is the recorded output. Use this lab’s reference condition above. **Independent task:** 2. Choose sensor revoked and inspect the matching serial and the certificate-revoked result. 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