Skip to main content
PSUT / IoTEngineering learning studio
WORKSPACE
Offline-first portalDr. Mohammad Alja’afreh
Connected Networks StudioNetworking and CommunicationExperimentsWorkspaces
ENGINEERING WORKSPACE
Home / Kali security course / K04
IoTPSUT IoT Engineering StudioPrincess Sumaya University for Technology · Dr. Mohammad Alja’afreh
WSL LABORATORIES / KALI LINUX / SECURITY & PRIVACY
IoT Security and Privacy

K04 · TLS certificate trust & endpoint identity

Ask Dr. Mohammad · K04 →

Practical IoT Security & Privacy · Kali WSL · 25 min

Design experiment & verify evidence →
K04 · Laboratory mentorAsk about the current experiment, its algorithms or Python notebook.
Ask Dr. MohammadAdaptive practice
Learning workflow · Kali & IoT securityK04 · TLS certificate trust & endpoint identity
V19.0 · Contextual AI workspace

Ask your engineering assistants

K04 · 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
K04 · TLS certificate trust & endpoint 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.

Readiness checksRevision deckEngineering workspaceRecord evidence

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

K04 · Academic orientation

Scope and objectives

Scope of the experiment

Determine why a TLS connection is accepted or rejected without turning off certificate verification.

The focus of this experiment is to identify CA trust, certificate validity and endpoint hostname checks. Students then trace a local TLS connection and its verification outcome, and diagnose trust failure without disabling certificate verification. 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 CA trust, certificate validity and endpoint hostname checks.
  • Trace a local TLS connection and its verification outcome.
  • Diagnose trust failure without disabling certificate verification.
  • 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 identify CA trust, certificate validity and endpoint hostname checks, trace a local TLS connection and its verification outcome, and diagnose trust failure without disabling certificate verification.

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 diagnose trust failure without disabling certificate verification. Separate predicted values from observations.

Prerequisite knowledge and related learning

Review the following catalogue prerequisites before starting. After completion, continue to K05 · Plaintext vs TLS packet observation.

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.

CONCEPTS / ACTIVE RECALL

Understand the experiment

TLS server authentication

Certificate chain, hostname and validity are distinct from transport reachability
Certificate chain, hostname and validity are distinct from transport reachability

Scientific architecture · TLS certificate and handshake analyzer

Scientific concept map: ClientHello — Protocol offer; ServerHello — Version choice; Certificate chain — Trust anchor / validity; Hostname check — SAN matches localhost; Finished — Application data only if verified.
Scientific concept map: ClientHello — Protocol offer; ServerHello — Version choice; Certificate chain — Trust anchor / validity; Hostname check — SAN matches localhost; Finished — Application data only if verified.

Scientific foundations and analytical reasoning

A TLS client verifies trust chain, validity interval and hostname independently of encryption. Version negotiation and transport connectivity are additional prerequisites.

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 · Certificate-based TLS trust

A TLS certificate binds public-key identity to a subject under a trust chain. The client checks certificate signatures, validity dates and the expected service identity, normally against SAN entries. Cryptographic key agreement and certificate trust are distinct. A valid chain for a different hostname is not sufficient.

Worked example and engineering interpretation

For a lab certificate valid for broker.lab.example, connecting under that name can pass identity verification; expecting other.lab.example must fail unless that name is also authorized. Test each validation condition separately and do not disable verification as a permanent repair.

Engineering principles · additional worked teaching example

TLS validates chain, date validity, hostname/SAN and negotiated protocol. A trusted CA signature is necessary but not enough for endpoint identity. If SAN is localhost, connecting with expected host wrong.example should fail even if CA is trusted.

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 K04 · TLS certificate trust & endpoint identity

Verify certificate trust and endpoint identity using correct and incorrect 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 trust and endpoint identity using correct and incorrect controls.

  1. Leave the trust store at lab-ca, SAN and expected hostname at localhost, day 3, TLS 1.3. Confirm Established and inspect the certificate table.
  2. Change only expected hostname to wrong.invalid. Confirm Hostname mismatch and application data not allowed.
  3. Restore localhost; select other-ca, then restore lab-ca and set evaluation day to 8. Distinguish trust and validity errors.
  4. Set client TLS 1.2 against TLS 1.3 only; inspect the protocol rejection. Repeat with client TLS 1.3.

Reference check:

Model boundary:

Independent task and submission evidence

2. Change only expected hostname to wrong.invalid. Confirm Hostname mismatch and application data not allowed. 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. 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 certificate-policy and handshake model; real TLS validation is performed only by the local OpenSSL procedure.

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.

K04 · TLS certificate trust & endpoint identity: message sequenceTLS clientLocal serverTCP connectClientHello · TLS 1.3ServerHello / certificateFinished · verified

Step 1 of 4 · 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
K04 · 01 / 08What is certificate trust?Reveal explanation
Engineering explanation

Verification of certificate chain, validity and endpoint identity.

K04 · 02 / 08Why check the hostname?Reveal explanation
Engineering explanation

A valid chain alone does not establish the expected server identity.

K04 · 03 / 08Which certificate and local TLS service conditions must be verified?Reveal explanation
Engineering explanation

Keep K02 TLS listener running, use the generated lab CA only, verify dates and SAN. Never disable TLS verification. If expired, stop brokers and follow toolkit renewal instructions.

K04 · 04 / 08Why check the SAN as well as the certificate issuer?Reveal explanation
Engineering reasoning

The issuer establishes a trust path; the subject alternative name must identify the intended endpoint.

K04 · 05 / 08Why must a wrong-hostname test preserve certificate validation?Reveal explanation
Engineering reasoning

Disabling validation would remove the control under investigation, invalidating the negative test.

K04 · 06 / 08A TLS peer presents a trusted certificate for the wrong hostname. Select every technically valid statement. A. Validate endpoint identity as well as certificate chain. B. A mismatched hostname must be rejected. C. A trusted issuer alone authorizes all hostnames. D. Disabling validation is equivalent to verifying identity.Reveal explanation
Applied scenario

Correct: A. Validate endpoint identity as well as certificate chain.; B. A mismatched hostname must be rejected.

K04 · 07 / 08In K04 · TLS certificate trust & endpoint identity, which command or code executes the final documented practical action?Reveal explanation
Implementation recall

cat "$HOME/.psut-kali-security-v14/evidence/K04-TLS.json"

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

K02 TLS broker on 18885 must remain listening and CA/server certificate dates valid. Run lab.py tls. A trusted localhost handshake must succeed and wrong.invalid must fail specifically for hostname mismatch. An expired cert or refused connection is an environment failure. Do not disable hostname verification.

Interactive networking and security instrument

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

Experimental protocol

Before you run / verification gate

Keep K02 TLS listener running, use the generated lab CA only, verify dates and SAN. Never disable TLS verification. If expired, stop brokers and follow toolkit renewal instructions.

Experimental protocol

Prerequisites
K02; CA and certificate generated
Procedure
Compare trusted correct name and deliberately incorrect name; inspect validity and SAN.
Acceptance
Correct name passes; wrong name fails specifically for hostname mismatch. Expired or untrusted cert is not a successful negative control.
Evidence
K04-TLS.json, certificate metadata (not private key).
Standards link
Data protection; secure communication
Discussion
Why is encryption without peer authentication insufficient?
K04 engineering diagram
Engineering diagram · K04. Use the interactive workstation to investigate the calculated state.

Run & verify — acceptance checklist

Build verification: Actual offline OpenSSL positive/negative hostname checks passed; live TLS broker pending.

K02 TLS broker on 18885 must remain listening and CA/server certificate dates valid. Run lab.py tls. A trusted localhost handshake must succeed and wrong.invalid must fail specifically for hostname mismatch. An expired cert or refused connection is an environment failure. Do not disable hostname verification.

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

Using the lab CA, SAN localhost and validity days 0–7, evaluate day 3, wrong hostname, day 8 and untrusted CA. Give the first failed check.

02 · Compare or justify using evidence

Evaluate a TLS 1.2-only client against a 1.3-only server and compare with a stopped listener. Draw an abbreviated certificate-authenticated handshake.

03 · Failure diagnosis

Failure diagnosis · Independent work

A local certificate is trusted and valid on day 2, but its SAN is demo.local and the client expects localhost. Is encryption sufficient? Give a secure correction.

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 · K04-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), but change Expected hostname = sensor.local. 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 · K04-02

The reference model reports Handshake: Established. Under Expected hostname = sensor.local 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 · K04-03

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

Advanced · Reverse reasoning

Independent theoretical exercise · K04-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. Candidate B changes the listed settings (Server certificate DNS SAN = sensor.local) 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 · K04-05

A student configures Evaluation day (cert valid day 0–7) = -5 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 · K04-06

Design a controlled comparison for K04 · TLS certificate trust & endpoint 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 and test Expected hostname = sensor.local. 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

Determine why a TLS connection is accepted or rejected without turning off certificate verification.

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

2 · Perform the investigation in order

  1. Leave the trust store at lab-ca, SAN and expected hostname at localhost, day 3, TLS 1.3. Confirm Established and inspect the certificate table.
  2. Change only expected hostname to wrong.invalid. Confirm Hostname mismatch and application data not allowed.
  3. Restore localhost; select other-ca, then restore lab-ca and set evaluation day to 8. Distinguish trust and validity errors.
  4. Set client TLS 1.2 against TLS 1.3 only; inspect the protocol rejection. Repeat with client TLS 1.3.
  5. Disable the listener. Explain why a connection refusal cannot be counted as proof of certificate rejection.
  6. Run python3 lab.py tls, then inspect subject, issuer, SAN and dates using the provided OpenSSL command. Compare the actual localhost and wrong.invalid checks.

3 · Compare controlled trials

TrialIndependent changeExpected checkObservation
Verified localhostUse reference inputs aboveHandshake: EstablishedRecord actual result
Wrong hostExpected hostname = wrong.invalidFirst failure: Hostname mismatchRecord actual result
Unknown CAClient trust store = other-caFirst failure: Unknown CARecord actual result
ExpiredEvaluation day (cert valid day 0–7) = 8First failure: Certificate expired or not yet validRecord actual result
Version conflictClient offered version = TLS 1.2; Server policy = TLS 1.3 onlyFirst failure: Protocol version unsupportedRecord actual result
No serverServer listener available = NoFirst failure: No listener / connection refusedRecord actual result

4 · Analyze and report

Explain why encryption alone does not establish endpoint identity and why a positive exchange is required.

Required evidence: Certificate table, handshake trace and local K04-TLS.json.

Model boundary: Logical certificate-policy and handshake model; real TLS validation is performed only by the local OpenSSL procedure.

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
Verified localhostUse reference inputs aboveRecord actual outcome and units
Wrong hostExpected hostname = wrong.invalidRecord actual outcome and units
Unknown CAClient trust store = other-caRecord actual outcome and units
ExpiredEvaluation day (cert valid day 0–7) = 8Record 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
K04 / Kali · OpenSSL25 min

TLS certificate trust & endpoint identity

Kali terminal C · working directory
Kali (Bash)
cd ~/kali-labs
bash verify_kali.sh
✓ Expected: Toolkit directory is selected and all dependency checks pass. Do not proceed if any check fails.

Objective: Verify a trusted certificate for localhost; then verify rejection for the wrong name.

Inspect certificate validity, SAN and negotiated TLS version.

ACTION 01 / 03
Kali terminal C
python3 lab.py tls
✓ Expected: The correct-hostname and deliberately incorrect-hostname checks produce a JSON evidence report. Review each result.
ACTION 02 / 03
Kali terminal C
openssl x509 -in "$HOME/.psut-kali-security-v14/server.crt" -noout -subject -issuer -dates -ext subjectAltName
✓ Expected: Certificate subject, issuer, validity dates and SAN are printed; verify the intended local endpoint identity.
ACTION 03 / 03
Kali terminal C — inspect actual evidence
cat "$HOME/.psut-kali-security-v14/evidence/K04-TLS.json"
✓ Expected: The saved JSON shows individual outcomes. Missing reports or failed controls require investigation, not a pass.

Experimental notebook

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

Method and implementation

Review the implementation after attempting the practical steps.

Trust versus encryption · method and source

A valid signature chain and correct hostname are separate requirements. The CA is a disposable lab CA, not a globally trusted identity. Repeat the negative check only after the positive check succeeds.

Inspect the actual implementation below. Full file: lab.py.

PYTHON · Source code
def tls():
    tests=[]
    for hostname,expect in [('localhost',True),('wrong.invalid',False)]:
        r=run(['openssl','s_client','-connect','127.0.0.1:18885','-CAfile',str(HOME/'ca.crt'),'-verify_hostname',hostname,'-verify_return_error','-brief'],input='')
        detail='\n'.join(line.strip() for line in (r.stdout+'\n'+r.stderr).splitlines() if any(term in line.lower() for term in ('protocol version','ciphersuite','verification','verify error','hostname mismatch')))
        ok=r.returncode==0 if expect else r.returncode!=0 and 'hostname mismatch' in (r.stdout+r.stderr).lower()
        tests.append(check('TLS hostname '+hostname,ok,f'exit={r.returncode}; '+detail[:500]))
    # Avoid accepting an unrelated failed connection as a negative verification.
    tests[1]['pass']=tests[1]['pass'] and tests[0]['pass'];return save('K04-TLS',tests)

Verification and notebook

Expected observation / verification

Expected trusted endpoint succeeds; wrong hostname fails. Record the two outcomes. Never use --insecure.

Engineering discussion

Why is encryption without endpoint authentication insufficient?

Python / Google Colab laboratory

K04 · 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
# K04 · K04 · TLS certificate trust & endpoint identity **PSUT IoT Engineering Studio — Dr. Mohammad Alja’afreh** ## Introduction Verify certificate trust and endpoint identity using correct and incorrect 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 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 certificate trust and endpoint identity using correct and incorrect controls. **Reference procedure (use the matching simulator/WSL tool where named, not an unrelated service):** 1. Leave the trust store at lab-ca, SAN and expected hostname at localhost, day 3, TLS 1.3. Confirm Established and inspect the certificate table. 2. Change only expected hostname to wrong.invalid. Confirm Hostname mismatch and application data not allowed. 3. Restore localhost; select other-ca, then restore lab-ca and set evaluation day to 8. Distinguish trust and validity errors. 4. Set client TLS 1.2 against TLS 1.3 only; inspect the protocol rejection. Repeat with client TLS 1.3. 5. Disable the listener. Explain why a connection refusal cannot be counted as proof of certificate rejection. **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
# =====================================================================
# K04 | Code cell 01 | K04 · TLS certificate trust & endpoint 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
# =====================================================================
# K04 | Code cell 02 | K04 · TLS certificate trust & endpoint 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
# =====================================================================
# K04 | Code cell 03 | K04 · TLS certificate trust & endpoint 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 python3 lab.py tls ``` ```python def tls(): tests=[] for hostname,expect in [('localhost',True),('wrong.invalid',False)]: r=run(['openssl','s_client','-connect','127.0.0.1:18885','-CAfile',str(HOME/'ca.crt'),'-verify_hostname',hostname,'-verify_return_error','-brief'],input='') detail='\n'.join(line.strip() for line in (r.stdout+'\n'+r.stderr).splitlines() if any(term in line.lower() for term in ('protocol version','ciphersuite','verification','verify error','hostname mismatch'))) ok=r.returncode==0 if expect else r.returncode!=0 and 'hostname mismatch' in (r.stdout+r.stderr).lower() tests.append(check('TLS hostname '+hostname,ok,f'exit={r.returncode}; '+detail[:500])) # Avoid accepting an unrelated failed connection as a negative verification. tests[1]['pass']=tests[1]['pass'] and tests[0]['pass'];return save('K04-TLS',tests) ```
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. Change only expected hostname to wrong.invalid. Confirm Hostname mismatch and application data not allowed. 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