HTTPS carries HTTP over TLS; a successful handshake authenticates the configured server identity and establishes protected transport, not application authorization.
The focus of this experiment is to distinguish HTTPS from TLS and broker transport from MQTT authorization. Students then validate a local TLS connection and compare hostname outcomes, and verify secure MQTT frame exchange and separate application freshness checks. 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 HTTPS from TLS and broker transport from MQTT authorization.
Validate a local TLS connection and compare hostname outcomes.
Verify secure MQTT frame exchange and separate application freshness checks.
Record the relevant inputs, intermediate states and final verification result before changing the reference configuration.
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 HTTPS from TLS and broker transport from MQTT authorization, validate a local TLS connection and compare hostname outcomes, and verify secure MQTT frame exchange and separate application freshness checks.
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 secure MQTT frame exchange and separate application freshness checks. Separate predicted values from observations.
Prerequisite knowledge and related learning
Review the following catalogue prerequisites before starting. After completion, continue to Challenge-response and mutual authentication.
A standard browser and the experiment-specific Python implementation or Colab notebook. Where the practical uses a protocol model, model results are distinguished from actual local cryptographic operations.
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.
01 · Experiment overview
CR80 · Verified local TLS 1.2/1.3 and hostname failure
Use Python SSL MemoryBIO to conduct a real TLS handshake in process. Trust only a generated local CA; verify hostname; compare TLS 1.2 and 1.3 with the same data. No listener or public network is used.
Learning objectives
Trace the named operation, reproduce intermediate values, verify the result and explain the consequences of a controlled change.
Use Python SSL MemoryBIO to conduct a real TLS handshake in process. Trust only a generated local CA; verify hostname; compare TLS 1.2 and 1.3 with the same data. No listener or public network is used.
Learning objectives
Trace the named operation, reproduce intermediate values, verify the result and explain the consequences of a controlled change.
Mathematical verification and controlled comparison
Substitute the output into its defining equation or check the protocol invariant. A controlled comparison changes one input while holding others fixed. Cite actual trace values and identify the limitations of the evidence.
Before starting
Environment: standard computer, browser and Python/WSL.
Simulation: Recorded, verified Python scenarios; use Python for arbitrary inputs
Technical scope: Actual OpenSSL-backed in-memory TLS; not packet capture, socket server or MQTT broker.
HTTPS identity and local TLS
1 · Principles and purpose
HTTPS carries HTTP over TLS; a successful handshake authenticates the configured server identity and establishes protected transport, not application authorization.
2 · Mathematical and algorithmic foundations
Use a client trust store with the local CA and check hostname. Negotiated TLS version, cipher and successful authenticated payload recovery are separate evidence fields. Reject validation errors rather than disabling verification.
3 · Worked teaching example
A trusted localhost certificate must fail when verifying unrelated hostname. Compare the two local versions under equivalent trust conditions; bytes and timings vary with library negotiation and randomness.
Captured earlier local execution. Randomized values and timing can differ; compare the invariant.
4 · Verification and experimental interpretation
Step through the following visualization and compare the named operation with the corresponding computed state. Check the mathematical invariant, inverse operation or protocol acceptance condition. Change one input at a time; distinguish a measured output from a prediction.
Actual local HTTPS validation
Browser illustrates expected handshake decisions; it cannot force a browser-native TLS version or expose TLS secrets. Python performs actual TLS in memory without external connections. Certificate trust and hostname verification remain enabled; a wrong hostname must fail. The HTTP payload is synthetic.
Use the operation-by-operation diagram below. The highlighted stage follows the active Simulation trace. Change inputs in Simulation, then return here to inspect the updated sequence.
Concept animation · independent state notebook
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.
Step 1 of 4 · Calculated state 1
Calculated state 1
flight
0
sender
client
wire_bytes
1478
complete
false
Calculated state 2
flight
0
sender
server
wire_bytes
1883
complete
false
Calculated state 3
flight
1
sender
client
wire_bytes
80
complete
true
Calculated state 4
flight
1
sender
server
wire_bytes
510
complete
true
Teaching example only; inspect live calculations or real practical evidence separately.
Secure MQTT telemetry with mutual TLS
MQTT transports publish/subscribe messages using separate connections from each client to the broker. TLS authenticates the broker and protects each connection; mutual TLS adds broker-side verification of client certificates. An authenticated client must still be authorized for a particular topic, and a gateway must validate application freshness. The broker can read plaintext MQTT payloads after TLS termination. QoS 0 provides no delivery acknowledgment. The local Python practical uses real TLS via SSL MemoryBIO and actual MQTT 3.1.1 control packets, with a minimal classroom policy rather than a full broker.
Compare the three linked experiments to distinguish measured performance, application authentication and transport security.
Calculated baseline diagram · enable JavaScript to explore changed inputs.
Edit the parameters, then Calculate / run. The local protocol model recomputes the trace; it does not contact a remote service. For CR80 actual TLS is measured in Python.
Predict localhost and wrong.lab under TLS 1.2 and 1.3 in the browser. Run the identical four configurations in Python, which negotiates TLS using SSL MemoryBIO and a freshly generated classroom CA. Record the actual negotiated version, certificate failure reason, recovered HTTP request and flight byte counts. Repeat twice; do not compare randomized bytes as fixed constants.
Interactive trust-policy model; this browser does not establish MQTT or TLS connections. The local Python practical performs the real cryptographic exchange.
Step 1
Ask Dr. Mohammad · current stage
For line-by-line implementation guidance, use the code mentor in Experiments.
Calculated result
Select Calculate / run.
04 · Experiments and engineering investigations
Analytical preparation — before Python
Use Python SSL MemoryBIO to conduct a real TLS handshake in process. Trust only a generated local CA; verify hostname; compare TLS 1.2 and 1.3 with the same data. No listener or public network is used.
Predict the baseline result before revealing the calculated state. A controlled comparison changes the named input while keeping the other conditions fixed. Record an observed value separately from an expected value.
Part A · Independent theoretical exercises
Complete each question before running the simulator or Python. Show calculations or protocol traces. The teaching example is a method, not a substitute for the assigned values.
01 · Application and derivation
Application and derivation · Independent work
Before running the local TLS program, predict results for localhost and an unrelated hostname under TLS 1.2 and 1.3. Distinguish certificate trust, hostname verification, negotiated version and application payload recovery.
Application and derivation — Use a client trust store with the local CA and check hostname. Negotiated TLS version, cipher and successful authenticated payload recovery are separate evidence fields. Reject validation errors rather than disabling verification. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
02 · Validation design
Validation design · Independent work
A local broker/service certificate is trusted but name does not match. Both TLS1.2 and TLS1.3 supported. Does switching version cure mismatch?
Validation design — Review the defining equations and compare the input restrictions and state transitions in Concepts. Apply this method to the assigned values independently; compare your reasoning with the relevant simulator or practical implementation.
Required evidence: state the expected invariant or acceptance condition; record hand-derived results, compare with the simulator or Python trace, and explain the first discrepancy. Do not report a predicted value as a measurement.
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 · Alternate configuration
Independent theoretical exercise · CR80-01
For the separate teaching-test configuration version: 1.3; hostname: wrong.lab, predict verified using the relevant operation or decision rule. Show intermediate work and state whether this is a deterministic result.
Intermediate · Interpret a computation state
Independent theoretical exercise · CR80-02
A teaching trace for Verified local TLS 1.2/1.3 and hostname failure contains flight: 0; sender: server; wire_bytes: 1883; complete: false. Explain the role of complete (recorded value false) and identify the rule or input that determines it. Distinguish an intermediate state from the final result.
Intermediate · Compare two recorded states
Independent theoretical exercise · CR80-03
The first and final trace records show flight = 0 and 1. Calculate the signed difference and explain whether it is an operation count, a state value or a measurement.
Challenging · Controlled algorithm verification
Independent theoretical exercise · CR80-04
Plan a comparison of version: 1.3; hostname: localhost with version: 1.3; hostname: wrong.lab. Record the dependent value verified, identify the changed factor(s), and describe the verification and failure criterion without claiming a real security measurement.
Part B · Guided simulation and practical procedure
Before starting — tools and setup
Standard computer; extract the WSL toolkit into a new directory. For the browser activity, use the integrated workstation. Verified browser scenarios; arbitrary inputs in Python (protocol simulations are models unless identified as executed local protocol tests).
Install Python dependencies only if required by the selected toolkit README. Use its requirements file and virtual environment instructions.
Use the exact baseline input below and write a prediction.
Select the baseline configuration below. Predict the relevant operation using the theory; execute the workstation and record the first and final state. Reproduce the same input with Python.
Save the trace and compare it with the reference output.
Experimental inputs
Experimental reference · json
{"version":"1.3","hostname":"localhost"}
Verified baseline reference (check after predicting)
Compare your baseline with the verified reference output below; for runtime-dependent results, compare invariants and report actual measurements instead of expecting identical timing or randomly generated values.
Evidence to record
Record the named intermediate values and final outputs from the selected trace.
Predict localhost and wrong.lab under TLS 1.2 and 1.3 in the browser. Run the identical four configurations in Python, which negotiates TLS using SSL MemoryBIO and a freshly generated classroom CA. Record the actual negotiated version, certificate failure reason, recovered HTTP request and flight byte counts. Repeat twice; do not compare randomized bytes as fixed constants.
Record inputs and complete traces for each trial, holding all other parameters constant.
Compare Python results to the corresponding browser model; report any difference in scope or measured behavior.
Trial
Input configuration
Prediction
Observed
Verification
1
{"version":"1.3","hostname":"localhost"}
2
{"version":"1.3","hostname":"wrong.lab"}
3
{"version":"1.2","hostname":"localhost"}
Use the table as a recording template; enter your own measured values in the field below or reproduce it in your report.
Part E/F · Independent Python verification and deliverables
Download the notebook or toolkit and run the default example.
Reproduce at least one changed input; compare the intermediate values with the browser where supported.
Complete the independent assessment below without copying the worked baseline. Explain discrepancies and distinguish mathematical results from security claims.
Additional investigation instructions
Read the theory and prerequisite labs. Run the baseline and record the input and result.
Run TLS 1.3 with localhost and wrong.lab. Then set version=1.2 and repeat. Record negotiated version, certificate failure and application-data recovery.
Locate the first intermediate step where the two cases differ. Verify the defining equation or decision rule.
Submit a two-row comparison table, trace evidence and a conclusion with limitations.
Case
Input
Observed result
Verification
Limitation
Baseline
Record
Record
Derive
Explain
Changed
Record
Record
Derive
Explain
Integrated IoT engineering investigation
Run the local mutual-TLS practical. Record negotiated TLS version, accepted sequence numbers, rejected cases and total encrypted application-record bytes. In the policy workstation toggle broker trust, client certificate, topic authorization and replay separately. Identify the layer at which each rejection occurs. Optionally repeat on a disposable local Mosquitto broker using the supplied commands. Compare results without disabling trust checks.
Predict the baseline before running the program.
Change one named condition at a time and retain the remaining settings.
Record actual output, comparison and interpretation. Identify the boundary where the security service applies.
Trial / change
Prediction
Observed result
Reason / limitation
Trial 1
Trial 2
Trial 3
Trial 4
Trial 5
Copy observations to the Engineering evidence record or export the workstation JSON. Do not enter actual credentials.
Use Ubuntu or Kali WSL, not PowerShell. Download the toolkit above to your computer. If Python, venv or unzip is missing, install these prerequisites once (requires administrator permission and network access).
In WSL, enter the actual downloaded ZIP path when prompted (for example, a file under /mnt/c/Users/…/Downloads). Extract to a new, dedicated directory. If this directory already exists from a previous extraction, use the existing verified toolkit or choose a clean directory rather than overwriting it.
Step 1 · Extract · bash
read -r -p "Full path to PSUT_V22_9_9_Cryptography_WSL.zip: " ZIP
DEST="$HOME/psut-crypto-v22.9.9"
if [ -f "$ZIP" ] && [ ! -e "$DEST" ]; then
mkdir "$DEST" && unzip "$ZIP" -d "$DEST"
else
echo "Check ZIP path and use a fresh destination."
fi
Create the isolated environment in the extracted toolkit root, activate it, then enter this experiment’s actual folder. Install only its declared dependencies. A comment-only requirements file requires no third-party packages.
Step 2 · Activate and install · bash
cd ~/psut-crypto-v22.9.9
python3 -m venv .venv
source .venv/bin/activate
cd CR80
ls
python -m pip install -r requirements.txt
Execute the default run and save the genuine program output. Then run the supplied regression test and the baseline fixture through the explicit input interface.
To change inputs, copy example-input.json, edit the copy in a text editor and run the command below. The original fixture is preserved.
Step 4 · Change an input · bash
cp example-input.json my-input.json
# Edit my-input.json with your preferred editor.
python lab.py --inputs "$(cat my-input.json)"
These scripts terminate normally. Use Ctrl+C to stop a long-running calculation if needed. When finished, leave the isolated virtual environment; no global service cleanup is required for these local examples.
Step 5 · Finish · bash
deactivate
Declared dependencies: cryptography>=42
Expected terminal output — captured local execution
This excerpt contains the actual first trace step and final result from python lab.py, followed by the actual regression test output. Full stdout is in CR80/verified-output.txt inside the toolkit. Timing, random signatures, keys, certificate fields and implementation-dependent sizes can vary; compare the invariant and record your own observations.
Check the output JSON and the test exit status. An assertion error means the expected invariant was not met. If Python reports a missing module, activate the environment and install the experiment’s requirements file; if a file is missing, check pwd and ls.
Download the notebook, open Google Colab and upload it using File → Upload notebook. For local Linux/WSL execution, follow the command blocks below in order.
Inspect Python source
Documented Python implementation · python
# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR80
# Experiment: verified local tls 1 2 1 3 and hostname failure
# Purpose: expose algorithm states and verify the experiment invariant.
# ------------------------------------------------------------
# CR80 | Verified local TLS 1.2/1.3 and hostname failure
# Execute the named operation; expose states and assert the laboratory invariant.
import json
DEFAULT={'version': '1.3', 'hostname': 'localhost'}
ALTERNATE={'hostname': 'wrong.lab'}
def run(overrides=None):
# Merge only explicitly supplied inputs with the lecture baseline.
params={**DEFAULT, **(overrides or {})}
version=params['version']
hostname=params['hostname']
import re
if version not in ('1.2','1.3') or not isinstance(hostname,str) or not re.fullmatch(r'[a-z0-9](?:[a-z0-9.-]{0,61}[a-z0-9])?',hostname):
raise ValueError('Use TLS 1.2/1.3 and a lowercase classroom DNS name')
import ssl,tempfile
from pathlib import Path
from datetime import datetime,timedelta,timezone
from cryptography import x509
from cryptography.x509.oid import NameOID
from cryptography.hazmat.primitives import hashes,serialization
from cryptography.hazmat.primitives.asymmetric import ec
now=datetime.now(timezone.utc);ca=ec.generate_private_key(ec.SECP256R1());leaf=ec.generate_private_key(ec.SECP256R1());N=lambda s:x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,s)]);root=N('PSUT local CA');cert=lambda subject,issuer,key,signer,isca:x509.CertificateBuilder().subject_name(subject).issuer_name(issuer).public_key(key.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now-timedelta(days=1)).not_valid_after(now+timedelta(days=1)).add_extension(x509.BasicConstraints(ca=isca,path_length=0 if isca else None),True).add_extension(x509.SubjectAlternativeName([x509.DNSName('localhost')]),False).add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),False).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(signer.public_key()),False).add_extension(x509.KeyUsage(digital_signature=True,content_commitment=False,key_encipherment=False,data_encipherment=False,key_agreement=False,key_cert_sign=isca,crl_sign=isca,encipher_only=None,decipher_only=None),True).sign(signer,hashes.SHA256())
rootcert=cert(root,root,ca,ca,True);leafcert=cert(N('localhost'),root,leaf,ca,False);ver=ssl.TLSVersion.TLSv1_3 if version=='1.3' else ssl.TLSVersion.TLSv1_2
steps=[]
with tempfile.TemporaryDirectory() as tmp:
p=Path(tmp);(p/'cert.pem').write_bytes(leafcert.public_bytes(serialization.Encoding.PEM));(p/'key.pem').write_bytes(leaf.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption()));server=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);server.load_cert_chain(p/'cert.pem',p/'key.pem');client=ssl.create_default_context(cadata=rootcert.public_bytes(serialization.Encoding.PEM).decode());server.minimum_version=server.maximum_version=client.minimum_version=client.maximum_version=ver
ci,co,si,so=[ssl.MemoryBIO() for i in range(4)];c=client.wrap_bio(ci,co,server_hostname=hostname);s=server.wrap_bio(si,so,server_side=True);done=[False,False];error=None
for i in range(30):
try:
for j,obj in enumerate((c,s)):
if not done[j]:
try:obj.do_handshake();done[j]=True
except ssl.SSLWantReadError:pass
out,inp=(co,si) if j==0 else (so,ci);buf=out.read();inp.write(buf);steps.append({'flight':i,'sender':'client' if j==0 else 'server','wire_bytes':len(buf),'complete':done[j]})
if all(done):break
except ssl.SSLCertVerificationError as e:error=e.verify_message;break
if all(done):
msg=b'GET / HTTP/1.0\r\n\r\n';c.write(msg);wire=co.read();si.write(wire);read=s.read();result={'verified':True,'version':c.version(),'payload_recovered':read==msg,'plaintext_visible_in_wire':msg in wire}
else:result={'verified':False,'error':error}
# Independently check the stated mathematical or protocol invariant.
assert result["verified"]==(hostname=="localhost") and (not result["verified"] or result["payload_recovered"]), "verification failed"
return {"steps":steps,"result":result}
if __name__ == "__main__":
import argparse
parser=argparse.ArgumentParser();parser.add_argument("--inputs",default="{}");parser.add_argument("--test",action="store_true");args=parser.parse_args()
if args.test:
for case in [{},ALTERNATE]:run(case)
print("PASS")
else:print(json.dumps(run(json.loads(args.inputs)),indent=2))
Integrated IoT practical · Secure MQTT telemetry with mutual TLS
Use the downloaded current WSL toolkit. The following commands assume the extraction directory from the workflow above.
Ubuntu/Kali WSL · bash
cd ~/psut-crypto-v22.9.9
source .venv/bin/activate
cd CR80
ls
python -m pip install -r requirements.txt
python mqtt_tls_lab.py | tee integrated-results.json
python test_lab.py
Inspect the integrated practical implementation
mqtt_tls_lab.py · python
# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR80 integrated IoT security
# Purpose: exchange MQTT 3.1.1 frames across real mutual TLS
# using isolated in-memory endpoints, not a production broker.
# ------------------------------------------------------------
import argparse, json, ssl, tempfile, struct
from datetime import datetime, timedelta, timezone
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
TOPIC='psut/device01/telemetry'
def provision(path, hostname='localhost'):
"""Generate a disposable root, broker, device and gateway identities."""
path=Path(path); path.mkdir(mode=0o700,parents=True,exist_ok=True)
if any(path.iterdir()): raise ValueError('Use an empty directory for fresh credentials')
now=datetime.now(timezone.utc)
def issue(name, ca=None, purpose=None):
key=ec.generate_private_key(ec.SECP256R1())
subject=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,name)])
issuer, signer=(subject,key) if ca is None else (ca[0].subject,ca[1])
b=x509.CertificateBuilder().subject_name(subject).issuer_name(issuer).public_key(key.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now-timedelta(minutes=5)).not_valid_after(now+timedelta(days=2)).add_extension(x509.BasicConstraints(ca=ca is None,path_length=0 if ca is None else None),critical=True).add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),False).add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(signer.public_key()),False).add_extension(x509.KeyUsage(digital_signature=True,content_commitment=False,key_encipherment=False,data_encipherment=False,key_agreement=False,key_cert_sign=ca is None,crl_sign=ca is None,encipher_only=None,decipher_only=None),True)
if purpose: b=b.add_extension(x509.ExtendedKeyUsage([purpose]),False)
if purpose==ExtendedKeyUsageOID.SERVER_AUTH: b=b.add_extension(x509.SubjectAlternativeName([x509.DNSName(hostname)]),False)
cert=b.sign(signer,hashes.SHA256()); return cert,key
root=issue('PSUT disposable classroom CA')
for stem,pair in [('ca',root),('broker',issue(hostname,root,ExtendedKeyUsageOID.SERVER_AUTH)),('device01',issue('device01',root,ExtendedKeyUsageOID.CLIENT_AUTH)),('gateway',issue('gateway',root,ExtendedKeyUsageOID.CLIENT_AUTH))]:
cert,key=pair; (path/f'{stem}.crt').write_bytes(cert.public_bytes(serialization.Encoding.PEM))
if stem!='ca':
f=path/f'{stem}.key'; f.write_bytes(key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption())); f.chmod(0o600)
# The CA private key is intentionally never exported. The listener is loopback-only.
(path/'acl').write_text(f'user device01\ntopic write {TOPIC}\nuser gateway\ntopic read {TOPIC}\n')
base=path.resolve()
(path/'mosquitto.conf').write_text(f'listener 8883 127.0.0.1\nallow_anonymous false\ncafile {base}/ca.crt\ncertfile {base}/broker.crt\nkeyfile {base}/broker.key\nrequire_certificate true\nuse_identity_as_username true\nacl_file {base}/acl\n')
def utf(s):
b=s.encode(); return struct.pack('!H',len(b))+b
def frame(header,body):
"""MQTT variable-byte remaining length, up to four bytes."""
n=len(body); out=bytearray([header])
if n>268435455: raise ValueError('packet too long')
while True:
d=n%128; n//=128; out.append(d|(128 if n else 0))
if not n: return bytes(out)+body
def connect(cid): return frame(0x10,utf('MQTT')+b'\x04\x02\x00\x3c'+utf(cid))
def subscribe(topic): return frame(0x82,b'\x00\x01'+utf(topic)+b'\x00')
def publish(topic,payload): return frame(0x30,utf(topic)+payload)
def parse(packet):
n=0
for i in range(1,5):
d=packet[i]; n+=(d&127)*128**(i-1)
if d<128:
assert len(packet)==i+1+n
return packet[0],packet[i+1:]
raise ValueError('bad remaining length')
def read_utf(buf):
n=int.from_bytes(buf[:2],'big'); return buf[2:2+n].decode(),buf[2+n:]
class Link:
"""Real TLS endpoints coupled by MemoryBIO; no network or capture privileges."""
def __init__(self,path,identity,hostname='localhost'):
path=Path(path); server=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);server.minimum_version=ssl.TLSVersion.TLSv1_2
server.load_cert_chain(path/'broker.crt',path/'broker.key');server.load_verify_locations(path/'ca.crt');server.verify_mode=ssl.CERT_REQUIRED
client=ssl.create_default_context(cafile=str(path/'ca.crt'));client.minimum_version=ssl.TLSVersion.TLSv1_2
if identity: client.load_cert_chain(path/f'{identity}.crt',path/f'{identity}.key')
self.ci,self.co,self.si,self.so=[ssl.MemoryBIO() for _ in range(4)]
self.c=client.wrap_bio(self.ci,self.co,server_hostname=hostname);self.s=server.wrap_bio(self.si,self.so,server_side=True)
done=[False,False]
for _ in range(32):
for j,(obj,out,inp) in enumerate([(self.c,self.co,self.si),(self.s,self.so,self.ci)]):
if not done[j]:
try: obj.do_handshake();done[j]=True
except ssl.SSLWantReadError: pass
inp.write(out.read())
if all(done): break
if not all(done): raise RuntimeError('Handshake did not complete')
self.identity=next(v for r in self.s.getpeercert()['subject'] for k,v in r if k=='commonName')
self.wire_bytes=0
def transfer(self,packet,to_server=True):
src,out,inp,dst=(self.c,self.co,self.si,self.s) if to_server else (self.s,self.so,self.ci,self.c)
src.write(packet); wire=out.read(); self.wire_bytes+=len(wire); inp.write(wire)
received=dst.read(len(packet)); assert received==packet
return received, packet in wire
def run():
"""Exercise a minimal broker policy for two local TLS-authenticated clients."""
with tempfile.TemporaryDirectory() as tmp:
provision(tmp); dev=Link(tmp,'device01'); gw=Link(tmp,'gateway')
for link in (dev,gw):
header,body=parse(link.transfer(connect(link.identity))[0]); assert header==0x10 and body.startswith(utf('MQTT'))
assert parse(link.transfer(frame(0x20,b'\x00\x00'),False)[0])==(0x20,b'\x00\x00')
header,body=parse(gw.transfer(subscribe(TOPIC))[0]); topic,tail=read_utf(body[2:]); assert header==0x82 and topic==TOPIC and tail==b'\x00'
assert parse(gw.transfer(frame(0x90,b'\x00\x01\x00'),False)[0])==(0x90,b'\x00\x01\x00')
delivered=[]; visible=False; high=-1; rejected=[]
for topic,seq in [(TOPIC,1),(TOPIC,1),('psut/device02/telemetry',2),(TOPIC,2)]:
payload=json.dumps({'device':'device01','seq':seq,'temperature':25.0},separators=(',',':')).encode()
received,seen=dev.transfer(publish(topic,payload)); visible|=seen
header,body=parse(received); t,data=read_utf(body); assert header==0x30
if dev.identity!='device01' or t!=TOPIC: rejected.append('topic ACL');continue
# Broker forwarding uses a separate TLS session. Freshness is a gateway policy.
received,seen=gw.transfer(publish(t,data),False);visible|=seen
_,b=parse(received);_,message=read_utf(b); m=json.loads(message)
if m['seq']<=high: rejected.append('replay');continue
high=m['seq'];delivered.append(m['seq'])
def fails(identity,hostname):
try: Link(tmp,identity,hostname)
except ssl.SSLError:return True
return False
result={'tls':dev.c.version(),'client_identity':dev.identity,'gateway_identity':gw.identity,'accepted_sequences':delivered,'rejected':rejected,'wrong_hostname_rejected':fails('device01','wrong.lab'),'missing_client_cert_rejected':fails(None,'localhost'),'mqtt_frame_visible_in_tls_records':visible,'tls_wire_bytes':dev.wire_bytes+gw.wire_bytes}
assert delivered==[1,2] and rejected==['replay','topic ACL'] and result['wrong_hostname_rejected'] and result['missing_client_cert_rejected'] and not visible
return result
if __name__=='__main__':
p=argparse.ArgumentParser();p.add_argument('--provision',type=Path);p.add_argument('--hostname',default='localhost');a=p.parse_args()
if a.provision: provision(a.provision,a.hostname);print('Disposable certificates and loopback broker configuration created.')
else: print(json.dumps(run(),indent=2))
Actual captured example output (timings and random fields can vary)
Install Mosquitto in WSL. This actual broker deployment has not been executed in the build environment. The generated configuration binds to localhost, requires client certificates and applies topic ACLs. See INTEGRATED_IOT.md in the toolkit for full instructions.
Terminal A — provision and launch · bash
sudo apt install mosquitto mosquitto-clients
cd ~/psut-crypto-v22.9.9
source .venv/bin/activate
cd CR80
python mqtt_tls_lab.py --provision credentials
mosquitto -c "$PWD/credentials/mosquitto.conf" -v
Optional hardware extensions · instructor-authorized isolated LAN only
The toolkit includes a Raspberry Pi subscriber and an ESP32 sketch using certificate verification. Physical boards, Arduino compilation, Paho and Mosquitto were not tested here. Follow INTEGRATED_IOT.md for approved LAN configuration, DNS, certificate provisioning and device-specific setup. Do not use public brokers, share private keys or disable verification.
Raspberry Pi gateway source
pi_gateway.py · python
# ------------------------------------------------------------
# PSUT IoT Engineering Studio | CR80 optional Raspberry Pi gateway
# Requires paho-mqtt>=2,<3, generated CA and gateway certificate.
# ------------------------------------------------------------
import argparse, json, ssl, sqlite3
from pathlib import Path
import paho.mqtt.client as mqtt
TOPIC='psut/device01/telemetry'
p=argparse.ArgumentParser();p.add_argument('--host',default='localhost');p.add_argument('--credentials',type=Path,required=True);p.add_argument('--db',default='gateway-state.sqlite');a=p.parse_args()
db=sqlite3.connect(a.db);db.execute('CREATE TABLE IF NOT EXISTS freshness (device TEXT PRIMARY KEY, seq INTEGER NOT NULL)')
def on_connect(client,userdata,flags,reason_code,properties):
if reason_code.is_failure:print('CONNECT failed:',reason_code,flush=True);return
client.subscribe(TOPIC,qos=0)
def on_message(client,userdata,msg):
try:
m=json.loads(msg.payload);n=m['seq']
if msg.topic!=TOPIC or m['device']!='device01' or type(n) is not int or not 0<=n<2**63:raise ValueError('invalid device or sequence')
with db:cur=db.execute('INSERT INTO freshness VALUES (?,?) ON CONFLICT(device) DO UPDATE SET seq=excluded.seq WHERE excluded.seq>freshness.seq',('device01',n))
print('ACCEPT' if cur.rowcount else 'REPLAY',m,flush=True)
except (ValueError,TypeError,KeyError):print('REJECT malformed payload',flush=True)
client=mqtt.Client(mqtt.CallbackAPIVersion.VERSION2,client_id='gateway-pi',protocol=mqtt.MQTTv311)
ctx=ssl.create_default_context(cafile=str(a.credentials/'ca.crt'));ctx.minimum_version=ssl.TLSVersion.TLSv1_2;ctx.load_cert_chain(a.credentials/'gateway.crt',a.credentials/'gateway.key');client.tls_set_context(ctx)
client.on_connect=on_connect;client.on_message=on_message;client.connect(a.host,8883,60)
try:client.loop_forever()
except KeyboardInterrupt:pass
finally:client.disconnect();db.close()
ESP32 source (Arduino IDE)
esp32_secure.ino · cpp
// ------------------------------------------------------------
// PSUT IoT Engineering Studio | CR80 optional ESP32 publisher
// Requires Arduino-ESP32, PubSubClient; private classroom LAN only.
// ------------------------------------------------------------
#include <WiFi.h>
#include <WiFiClientSecure.h>
#include <PubSubClient.h>
#include <Preferences.h>
#include <time.h>
#include "local_secrets.h"
WiFiClientSecure transport;
PubSubClient mqtt(transport);
Preferences prefs;
void setup() {
Serial.begin(115200);
WiFi.begin(WIFI_SSID, WIFI_PASSWORD);
unsigned long start = millis();
while (WiFi.status() != WL_CONNECTED && millis()-start < 30000) delay(250);
if (WiFi.status() != WL_CONNECTED) { Serial.println("WiFi failed"); return; }
// TLS certificate dates require a trustworthy clock.
configTime(0, 0, NTP_HOST);
struct tm now;
if (!getLocalTime(&now, 15000)) { Serial.println("Clock sync failed; TLS not attempted"); return; }
transport.setCACert(ROOT_CA);
transport.setCertificate(DEVICE_CERT);
transport.setPrivateKey(DEVICE_KEY);
mqtt.setServer(BROKER_HOST, 8883);
if (!prefs.begin("psut-crypto", false)) { Serial.println("NVS failed"); return; }
if (!mqtt.connect("device01-esp32")) { Serial.printf("MQTT failed: %d\n", mqtt.state()); return; }
// Reserve a sequence value in NVS before transmission to avoid reuse on reboot.
uint64_t seq = prefs.getULong64("seq", 0) + 1;
if (!seq || seq >= (1ULL<<63) || prefs.putULong64("seq",seq) != sizeof(seq)) { Serial.println("Counter write failed"); mqtt.disconnect(); return; }
char message[128];
snprintf(message,sizeof(message),"{\"device\":\"device01\",\"seq\":%llu,\"temperature\":25.0}",(unsigned long long)seq);
// Synthetic reading: no GPIO or sensor hardware needed for this extension.
Serial.println(mqtt.publish("psut/device01/telemetry",message,false)?"PUBLISH queued (QoS 0)":"PUBLISH failed");
mqtt.loop(); mqtt.disconnect();prefs.end();
}
void loop() { delay(1000); }
05 · Interactive flashcards
Recall before revealing. Review and mastery ratings remain on this device.
Browse all explanationsWhat is the defining principle?
Use Python SSL MemoryBIO to conduct a real TLS handshake in process. Trust only a generated local CA; verify hostname; compare TLS 1.2 and 1.3 with the same data. No listener or public network is used.
How do I verify the result?
Run TLS 1.3 with localhost and wrong.lab. Then set version=1.2 and repeat. Record negotiated version, certificate failure and application-data recovery.
What does this experiment not establish?
Actual OpenSSL-backed in-memory TLS; not packet capture, socket server or MQTT broker.
What input settings define the baseline for this experiment?
version = 1.3; hostname = localhost
What is the first intermediate state in the baseline?
Run TLS 1.3 with localhost and wrong.lab. Then set version=1.2 and repeat. Record negotiated version, certificate failure and application-data recovery. Choose one valid input not included in the browser cases, calculate it in Python, and explain the first changed intermediate value. Include a failure or boundary case where applicable. Criteria: mathematical correctness 40%, reproducible evidence 30%, interpretation 20%, scope 10%.
Part F · Engineering evidence record
Record the baseline, prediction, changed input, observed result, discrepancy and limitation. Save locally or export with the displayed result. This is not an official submission.