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

K12 · Mutual TLS and device identity

Ask Dr. Mohammad · K12 →

Verify both peer identities using a temporary TLS training endpoint.

← Security range
Design experiment & verify evidence →
K12 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Kali & IoT securityK12 · Mutual TLS and device identity

Before you start

Complete K01 and K08, install the original Kali toolkit, then copy the updated advanced_security.py file into ~/kali-labs. Run as your normal Kali user. No public broker or external target is required.

Related course access: Networking and Communication — same laboratory, notebook and completion record.

K12 · Academic orientation

Scope and objectives

Scope of the experiment

Isolate client-certificate failures from server trust and hostname failures.

The focus of this experiment is to distinguish server authentication from mutual TLS device identity. Students then trace CA trust and client-certificate requirements, and verify correct and incorrect local identity cases. 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

  • Distinguish server authentication from mutual TLS device identity.
  • Trace CA trust and client-certificate requirements.
  • Verify correct and incorrect local identity cases.
  • Identify the configured inputs (Server listener available; Client trust store; Expected hostname; Server certificate DNS SAN; Evaluation day (cert valid day 0–7)) 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 distinguish server authentication from mutual TLS device identity, trace CA trust and client-certificate requirements, and verify correct and incorrect local identity cases.

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 correct and incorrect local identity cases. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to K13 · Authenticated encryption 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

Mutual TLS · two independent identities

TLS 1.3 conceptual handshake; certificate verification on both endpoints
TLS 1.3 conceptual handshake; certificate verification on both endpoints

Scientific architecture · Mutual TLS client identity exchange

Scientific concept map: Client certificate — Device identity; Server certificate — Endpoint identity; TLS handshake — Mutual certificate checks; Trust policy — Client CA / SAN; Application — Authorized session.
Scientific concept map: Client certificate — Device identity; Server certificate — Endpoint identity; TLS handshake — Mutual certificate checks; Trust policy — Client CA / SAN; Application — Authorized session.

Scientific foundations and analytical reasoning

Mutual TLS authenticates both endpoints: client validates the server identity and server independently validates the client certificate.

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 · Bidirectional certificate identity

Mutual TLS adds client-certificate authentication to server authentication. Each peer verifies a separate chain and identity policy. Server acceptance of a certificate does not by itself authorize every application operation; map certificate identity to the device role.

Worked example and engineering interpretation

A server may pass its certificate checks while rejecting a client certificate issued by an untrusted authority. Test both directions with the authorized local certificate fixtures, then check application permissions separately. A single successful connection cannot establish all negative cases.

Engineering principles · additional worked teaching example

Mutual TLS authenticates both endpoint certificates. Server certificate validates server identity; client certificate is mapped to an application principal, and authorization remains separate. A valid but unauthorized client may pass TLS yet fail application access.

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 K12 · Mutual TLS and device identity

Verify mutual TLS trusted exchange and explicit certificate rejections.

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 mutual TLS trusted exchange and explicit certificate rejections.

  1. Verify localhost and a trusted client certificate. Follow both logical certificate directions.
  2. Remove the client certificate while retaining server trust. Record the specific client certificate failure.
  3. Select untrusted client certificate; compare with missing.
  4. Restore client certificate and use wrong.invalid to cause server identity failure.

Reference check:

Model boundary:

Independent task and submission evidence

2. Remove the client certificate while retaining server trust. Record the specific client certificate failure. 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: Server listener available = true; Client trust store = lab-ca; Expected hostname = localhost; Server certificate DNS SAN = localhost; Evaluation day (cert valid day 0–7) = 3; Client offered version = TLS 1.3; Server policy = TLS 1.2 / 1.3; Client certificate = trusted. In the classroom model, Handshake = Established; First failure = Established; Negotiated version = TLS 1.3; Application data allowed = Yes. This calculates certificate-policy outcomes and the first failed check. TLS 1.3 encrypts later handshake messages; the diagram represents logical messages, not a wire capture. Logical mutual TLS policy model, not an actual TLS socket.

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.

K12 · Mutual TLS and device identity: message sequenceTLS clientLocal serverTCP connectClientHello · TLS 1.3ServerHello / certificateCertificateRequestClient cert: trustedFinished · verified

Step 1 of 6 · TCP connect

TCP connect

1. TLS client → Local server
TCP connect

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

Recall the concept before revealing its explanation.

0 / 3 revealed
K12 · 01 / 08What does mutual TLS add?Reveal explanation
Engineering explanation

Both peers present certificates and verify the intended peer identity; server-only TLS authenticates only the server at the TLS layer.

K12 · 02 / 08Why check the actual TLS reason?Reveal explanation
Engineering explanation

A missing message or timeout could arise from unrelated failures. Require an explicit certificate rejection and a successful positive control.

K12 · 03 / 08Is this MQTT mutual TLS?Reveal explanation
Engineering explanation

No. The script uses a temporary TLS application exchange. An MQTT broker requires separate client-certificate and authorization verification.

K12 · 04 / 08What additional identity check does mutual TLS add?Reveal explanation
Engineering reasoning

The server also validates the client's certificate, in addition to the client's verification of the server.

K12 · 05 / 08Why require explicit certificate rejection rather than a timeout?Reveal explanation
Engineering reasoning

A timeout has several causes; a specific authentication error provides stronger evidence of the intended negative test.

K12 · 06 / 08A broker requires mutual TLS. Select every technically valid statement. A. The client validates the server identity. B. The server validates the client certificate under its trust policy. C. Mutual TLS necessarily authorizes every topic. D. A failed client certificate proves all network traffic is encrypted.Reveal explanation
Applied scenario

Correct: A. The client validates the server identity.; B. The server validates the client certificate under its trust policy.

K12 · 07 / 08Which engineering mechanism is tested by K12 · Mutual TLS and device identity, and what state or outcome is evaluated?Reveal explanation
Implementation recall

Verify mutual TLS trusted exchange and explicit certificate rejections.

K12 · 08 / 08For K12 · Mutual TLS and device identity, which actual output or state confirms the prescribed practical run succeeded, and what does it not establish?Reveal explanation
Evidence & acceptance

Run advanced_security.py mtls from ~/kali-labs. The script creates temporary CA/client/server certificates and chooses a local ephemeral port; no broker needed. Confirm trusted exchange and specific rejection of missing client cert and wrong hostname. Temporary files removed automatically. This is TLS over TCP, not MQTT mTLS.

Interactive networking and security instrument

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

K12 · 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
K12 · Mutual TLS and device identity

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 local mutual TLS three controls passed.

Run advanced_security.py mtls from ~/kali-labs. The script creates temporary CA/client/server certificates and chooses a local ephemeral port; no broker needed. Confirm trusted exchange and specific rejection of missing client cert and wrong hostname. Temporary files removed automatically. This is TLS over TCP, not MQTT mTLS.

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

Build a matrix for trusted/absent/untrusted client certificate with valid server certificate, then reverse server trust. Predict which stage rejects.

02 · Compare or justify using evidence

Explain why a trusted server does not imply a trusted client and why private keys remain local.

03 · Scenario analysis

Scenario analysis · Independent work

A client trusts server, server requires client certificate, but client sends none. Which layer fails and how should it be corrected?

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

Use the reference configuration (Server listener available = true; Client trust store = lab-ca; Expected hostname = localhost; Server certificate DNS SAN = localhost; Evaluation day (cert valid day 0–7) = 3; Client offered version = TLS 1.3; Server policy = TLS 1.2 / 1.3; Client certificate = trusted), but change Server listener available = false. The model reports Handshake = 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 · K12-02

The reference model reports Handshake: Established. Under Server listener available = false 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 · K12-03

For Client trust store = other-ca, the model supplies this excerpt from Verification trace: Verification step · Observed decision TCP connection · Pass Trust anchor · Fail Validity interval · Not reached Endpoint SAN · Not reached Protocol negotiation · Not reached Count rows whose Observed decision value is exactly “Not reached”, and identify the displayed row numbers. Explain what the count describes.

Advanced · Reverse reasoning

Independent theoretical exercise · K12-04

An observation is Handshake = Rejected. Candidate A uses Server listener available = true; Client trust store = lab-ca; Expected hostname = localhost; Server certificate DNS SAN = localhost; Evaluation day (cert valid day 0–7) = 3; Client offered version = TLS 1.3; Server policy = TLS 1.2 / 1.3; Client certificate = trusted. Candidate B changes the listed settings (Client trust store = other-ca) 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 · K12-05

A student configures Expected hostname = sensor.local while preserving all other reference settings, but copies the reference report of Handshake = Established. Evaluate whether the report is justified. Identify the first configuration/output check to perform.

Challenging · Design a controlled verification

Independent theoretical exercise · K12-06

Design a controlled comparison for K12 · Mutual TLS and device identity using reference Server listener available = true; Client trust store = lab-ca; Expected hostname = localhost; Server certificate DNS SAN = localhost; Evaluation day (cert valid day 0–7) = 3; Client offered version = TLS 1.3; Server policy = TLS 1.2 / 1.3; Client certificate = trusted and test Server listener available = false. Specify the changed setting(s), measured metric Handshake, controls, repetitions, an acceptance check and what evidence can distinguish an actual implementation from the model.

Step-by-step experimental procedure

Isolate client-certificate failures from server trust and hostname failures.

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.

Server listener availableYes
Client trust storelab-ca
Expected hostnamelocalhost
Server certificate DNS SANlocalhost
Evaluation day (cert valid day 0–7)3
Client offered versionTLS 1.3
Server policyTLS 1.2 / 1.3
Client certificatetrusted

2 · Perform the investigation in order

  1. Verify localhost and a trusted client certificate. Follow both logical certificate directions.
  2. Remove the client certificate while retaining server trust. Record the specific client certificate failure.
  3. Select untrusted client certificate; compare with missing.
  4. Restore client certificate and use wrong.invalid to cause server identity failure.
  5. Execute advanced_security.py mtls from the isolated toolkit and distinguish explicit rejection from timeout.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Mutually authenticatedUse reference inputs aboveHandshake: EstablishedRecord actual result
Missing client certificateClient certificate = missingHandshake: RejectedRecord actual result
Untrusted client certificateClient certificate = untrustedHandshake: RejectedRecord actual result
Wrong hostnameExpected hostname = wrong.invalidFirst failure: Hostname mismatchRecord actual result

4 · Analyze and report

Explain how mutual TLS authenticates both endpoints and how application roles remain separate.

Required evidence: Positive exchange and two distinct certificate failure traces.

Model boundary: Logical mutual TLS policy model, not an actual TLS socket.

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
Mutually authenticatedUse reference inputs aboveRecord actual outcome and units
Missing client certificateClient certificate = missingRecord actual outcome and units
Untrusted client certificateClient certificate = untrustedRecord actual outcome and units
Wrong hostnameExpected hostname = wrong.invalidRecord 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

Practical procedure

Kali WSL · Bash
cd ~/kali-labs
python3 advanced_security.py mtls
✓ Expected: Three passing checks. Trusted exchange succeeds; missing client certificate yields an explicit server-side certificate rejection; wrong hostname is rejected. A timeout is not evidence of successful access control.

Experimental notebook

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

Scientific method

The program creates ephemeral ECDSA certificates, binds an ephemeral loopback port, requires a client certificate and performs an application exchange. All temporary keys are removed when the program exits.

Download the actual implementation

Evidence and discussion

Record actual per-control pass/fail, TLS reason codes and residual risks. This is TLS, not a deployed MQTT mutual-TLS broker.

Keep actual outputs separate from expected results. Record only non-sensitive evidence and note unresolved controls.

Open engineering notebook (select K08 and name the extension in your observation)

Learning progress

Completion is a local learning mark, not independent validation.

Record evidence in engineering notebook

Python / Google Colab laboratory

K12 · 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
# K12 · K12 · Mutual TLS and device identity **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Introduction Verify mutual TLS trusted exchange and explicit certificate rejections. ## 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 mutual TLS trusted exchange and explicit certificate rejections. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Verify localhost and a trusted client certificate. Follow both logical certificate directions. 2. Remove the client certificate while retaining server trust. Record the specific client certificate failure. 3. Select untrusted client certificate; compare with missing. 4. Restore client certificate and use wrong.invalid to cause server identity failure. 5. Execute advanced_security.py mtls from the isolated toolkit and distinguish explicit rejection from timeout. **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
# =====================================================================
# K12 | Code cell 01 | K12 · Mutual TLS and device identity
# 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
# =====================================================================
# K12 | Code cell 02 | K12 · Mutual TLS and device identity
# 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 datetime, socket, ssl, tempfile, threading

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 mtls; keep its logic separate from the trial.
def mtls():
    # Ephemeral teaching trust root, server and client. No persistent keys or external endpoints.
    with tempfile.TemporaryDirectory(prefix='psut-mtls-') as tmp:
        p=Path(tmp); now=datetime.datetime.now(datetime.timezone.utc); ca_key=ec.generate_private_key(ec.SECP256R1()); ca_name=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'PSUT ephemeral training CA')]);
        def cert(name,key,issuer,signer,ca=False,server=False):
            b=x509.CertificateBuilder().subject_name(name).issuer_name(issuer).public_key(key.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=ca,path_length=0 if ca else None),critical=True)
            b=b.add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),critical=False).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(signer.public_key()),critical=False).add_extension(x509.KeyUsage(digital_signature=not ca,content_commitment=False,key_encipherment=False,data_encipherment=False,key_agreement=False,key_cert_sign=ca,crl_sign=ca,encipher_only=None,decipher_only=None),critical=True)
            if not ca:
                b=b.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH if server else ExtendedKeyUsageOID.CLIENT_AUTH]),critical=False)
                if server:b=b.add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]),critical=False)
            return b.sign(signer,hashes.SHA256())
        root=cert(ca_name,ca_key,ca_name,ca_key,ca=True);(p/'ca.pem').write_bytes(root.public_bytes(serialization.Encoding.PEM))
        for label in ['server','client']:
            k=ec.generate_private_key(ec.SECP256R1()); c=cert(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'localhost' if label=='server' else 'training sensor')]),k,ca_name,ca_key,server=label=='server');(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)
        out=[]
        for label,client_cert,host,expected in [('trusted mutual TLS',True,'localhost',True),('missing client certificate',False,'localhost',False),('wrong server hostname',True,'invalid.local',False)]:
            server=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);server.minimum_version=ssl.TLSVersion.TLSv1_2;server.load_cert_chain(str(p/'server.pem'),str(p/'server.key'));server.load_verify_locations(str(p/'ca.pem'));server.verify_mode=ssl.CERT_REQUIRED
            cli=ssl.create_default_context(cafile=str(p/'ca.pem'));cli.minimum_version=ssl.TLSVersion.TLSv1_2
            if client_cert:cli.load_cert_chain(str(p/'client.pem'),str(p/'client.key'))
            state={}; listener=socket.socket();listener.bind(('127.0.0.1',0));listener.listen(1);listener.settimeout(3);port=listener.getsockname()[1]
            def worker():
                try:
                    conn,_=listener.accept()
                    with conn:
                        conn.settimeout(3)
                        with server.wrap_socket(conn,server_side=True) as s:
                            if s.recv(16)==b'PSUT':s.sendall(b'OK');state['server_ok']=True
                except ssl.SSLError as e:state['server_error']=e.reason
                except OSError as e:state['other_error']=type(e).__name__
            t=threading.Thread(target=worker);t.start();ok=False;client_error=None
            try:
                with socket.create_connection(('127.0.0.1',port),timeout=3) as conn:
                    with cli.wrap_socket(conn,server_hostname=host) as s:s.sendall(b'PSUT');ok=s.recv(16)==b'OK'
            except ssl.SSLError as e:
                client_error=e.reason
                if isinstance(e,ssl.SSLCertVerificationError):state['verify_code']=e.verify_code
            except OSError as e:state['client_other_error']=type(e).__name__
            finally:t.join(4);listener.close()
            negative_specific=(label=='missing client certificate' and state.get('server_error')=='PEER_DID_NOT_RETURN_A_CERTIFICATE') or (label=='wrong server hostname' and client_error=='CERTIFICATE_VERIFY_FAILED' and state.get('verify_code')==62)
            passed=(ok and state.get('server_ok') is True) if expected else (not ok and negative_specific)
            out.append({'control':label,'expected_accept':expected,'actual_exchange':ok,'pass':bool(passed),'client_tls_error':client_error,**state})
        return {'source':'actual-local-TLS','checks':out,'pass':all(x['pass'] for x in out)}
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
# =====================================================================
# K12 | Code cell 03 | K12 · Mutual TLS and device identity
# 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=mtls()
    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 advanced_security.py mtls ```
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. Remove the client certificate while retaining server trust. Record the specific client certificate failure. 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