{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "324e99d6",
   "metadata": {},
   "source": [
    "# CR80 · Verified local TLS 1.2/1.3 and hostname failure\n",
    "\n",
    "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.\n",
    "\n",
    "Foundational concepts; prerequisite: CR74, CR78.\n",
    "\n",
    "**Scope:** Actual OpenSSL-backed in-memory TLS; not packet capture, socket server or MQTT broker."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept080",
   "source": [
    "## HTTPS identity and local TLS\n",
    "\n",
    "HTTPS carries HTTP over TLS; a successful handshake authenticates the configured server identity and establishes protected transport, not application authorization.\n",
    "\n",
    "**Mathematical / protocol 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.\n",
    "\n",
    "**Worked teaching example and interpretation:** 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.\n",
    "\n",
    "Compare corresponding states; for randomized or timed runs compare invariants rather than literal random bytes or timings.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "network80",
   "metadata": {},
   "source": [
    "## Actual local HTTPS validation\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2810b973",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR80 | Dependency check =====\n",
    "# ===== Dependency check =====\n",
    "# Colab normally includes cryptography; install a compatible version if absent.\n",
    "import importlib.util\n",
    "if importlib.util.find_spec(\"cryptography\") is None:\n",
    "    import subprocess,sys\n",
    "    subprocess.check_call([sys.executable,\"-m\",\"pip\",\"install\",\"cryptography>=42\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "94dc9f8f",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR80 | Live algorithm and verification =====\n",
    "# The function returns actual modeled intermediate states and checks the result.\n",
    "# ------------------------------------------------------------\n",
    "# PSUT IoT Engineering Studio | CR80\n",
    "# Experiment: verified local tls 1 2 1 3 and hostname failure\n",
    "# Purpose: expose algorithm states and verify the experiment invariant.\n",
    "# ------------------------------------------------------------\n",
    "# CR80 | Verified local TLS 1.2/1.3 and hostname failure\n",
    "# Execute the named operation; expose states and assert the laboratory invariant.\n",
    "import json\n",
    "\n",
    "\n",
    "\n",
    "DEFAULT={'version': '1.3', 'hostname': 'localhost'}\n",
    "ALTERNATE={'hostname': 'wrong.lab'}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the lecture baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    version=params['version']\n",
    "    hostname=params['hostname']\n",
    "    import re\n",
    "    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):\n",
    "        raise ValueError('Use TLS 1.2/1.3 and a lowercase classroom DNS name')\n",
    "    import ssl,tempfile\n",
    "    from pathlib import Path\n",
    "    from datetime import datetime,timedelta,timezone\n",
    "    from cryptography import x509\n",
    "    from cryptography.x509.oid import NameOID\n",
    "    from cryptography.hazmat.primitives import hashes,serialization\n",
    "    from cryptography.hazmat.primitives.asymmetric import ec\n",
    "    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())\n",
    "    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\n",
    "    steps=[]\n",
    "    with tempfile.TemporaryDirectory() as tmp:\n",
    "        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\n",
    "        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\n",
    "        for i in range(30):\n",
    "            try:\n",
    "                for j,obj in enumerate((c,s)):\n",
    "                    if not done[j]:\n",
    "                        try:obj.do_handshake();done[j]=True\n",
    "                        except ssl.SSLWantReadError:pass\n",
    "                    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]})\n",
    "                if all(done):break\n",
    "            except ssl.SSLCertVerificationError as e:error=e.verify_message;break\n",
    "        if all(done):\n",
    "            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}\n",
    "        else:result={'verified':False,'error':error}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"verified\"]==(hostname==\"localhost\") and (not result[\"verified\"] or result[\"payload_recovered\"]), \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "74fe78d5",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "c0bf07df",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR80 | Execute the baseline =====\n",
    "# ===== Execute the baseline =====\n",
    "# Run the default worked example; inspect the intermediate states in order.\n",
    "baseline=run()\n",
    "for step in baseline[\"steps\"]: print(step)\n",
    "print(\"Result:\",baseline[\"result\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "ce1a7b5a",
   "metadata": {},
   "source": [
    "## Controlled comparison\n",
    "Change the indicated input; leave other inputs unchanged. A baseline is the reference run. A mathematical verification substitutes the result back into its defining equation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "0c5627f0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR80 | Compare the specified alternative =====\n",
    "# ===== Compare the specified alternative =====\n",
    "# Override only the chosen input(s), leaving remaining parameters at baseline.\n",
    "comparison=run(ALTERNATE)\n",
    "for step in comparison[\"steps\"]: print(step)\n",
    "print(\"Result:\",comparison[\"result\"])"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "c2096189",
   "metadata": {},
   "source": [
    "## Controlled investigation\n",
    "\n",
    "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.\n",
    "\n",
    "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."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Integrated practical — Mutual TLS and MQTT telemetry\n",
    "\n",
    "Establish two authenticated TLS sessions: publisher to broker, subscriber to broker. Send MQTT 3.1.1 frames, enforce topic authorization and check sequence freshness. The Python MemoryBIO exercise uses real TLS and actual MQTT packet bytes with a minimal policy model, not a production broker. Compare hostname failure, missing client certificate, topic denial and replay.\n",
    "\n",
    "Run the following independent teaching example, then repeat with one controlled change. Record the actual outputs. Hardware and live broker extensions are in the WSL toolkit."
   ],
   "id": "76cf0a4d5e63fba5"
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR80 | Mutual TLS and MQTT telemetry =====\n",
    "# ------------------------------------------------------------\n",
    "# PSUT IoT Engineering Studio | CR80 integrated IoT security\n",
    "# Purpose: exchange MQTT 3.1.1 frames across real mutual TLS\n",
    "# using isolated in-memory endpoints, not a production broker.\n",
    "# ------------------------------------------------------------\n",
    "import argparse, json, ssl, tempfile, struct\n",
    "from datetime import datetime, timedelta, timezone\n",
    "from pathlib import Path\n",
    "from cryptography import x509\n",
    "from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID\n",
    "from cryptography.hazmat.primitives import hashes, serialization\n",
    "from cryptography.hazmat.primitives.asymmetric import ec\n",
    "TOPIC='psut/device01/telemetry'\n",
    "\n",
    "def provision(path, hostname='localhost'):\n",
    "    \"\"\"Generate a disposable root, broker, device and gateway identities.\"\"\"\n",
    "    path=Path(path); path.mkdir(mode=0o700,parents=True,exist_ok=True)\n",
    "    if any(path.iterdir()): raise ValueError('Use an empty directory for fresh credentials')\n",
    "    now=datetime.now(timezone.utc)\n",
    "    def issue(name, ca=None, purpose=None):\n",
    "        key=ec.generate_private_key(ec.SECP256R1())\n",
    "        subject=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,name)])\n",
    "        issuer, signer=(subject,key) if ca is None else (ca[0].subject,ca[1])\n",
    "        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)\n",
    "        if purpose: b=b.add_extension(x509.ExtendedKeyUsage([purpose]),False)\n",
    "        if purpose==ExtendedKeyUsageOID.SERVER_AUTH: b=b.add_extension(x509.SubjectAlternativeName([x509.DNSName(hostname)]),False)\n",
    "        cert=b.sign(signer,hashes.SHA256()); return cert,key\n",
    "    root=issue('PSUT disposable classroom CA')\n",
    "    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))]:\n",
    "        cert,key=pair; (path/f'{stem}.crt').write_bytes(cert.public_bytes(serialization.Encoding.PEM))\n",
    "        if stem!='ca':\n",
    "            f=path/f'{stem}.key'; f.write_bytes(key.private_bytes(serialization.Encoding.PEM,serialization.PrivateFormat.PKCS8,serialization.NoEncryption())); f.chmod(0o600)\n",
    "    # The CA private key is intentionally never exported. The listener is loopback-only.\n",
    "    (path/'acl').write_text(f'user device01\\ntopic write {TOPIC}\\nuser gateway\\ntopic read {TOPIC}\\n')\n",
    "    base=path.resolve()\n",
    "    (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')\n",
    "\n",
    "def utf(s):\n",
    "    b=s.encode(); return struct.pack('!H',len(b))+b\n",
    "\n",
    "def frame(header,body):\n",
    "    \"\"\"MQTT variable-byte remaining length, up to four bytes.\"\"\"\n",
    "    n=len(body); out=bytearray([header])\n",
    "    if n>268435455: raise ValueError('packet too long')\n",
    "    while True:\n",
    "        d=n%128; n//=128; out.append(d|(128 if n else 0))\n",
    "        if not n: return bytes(out)+body\n",
    "\n",
    "def connect(cid): return frame(0x10,utf('MQTT')+b'\\x04\\x02\\x00\\x3c'+utf(cid))\n",
    "def subscribe(topic): return frame(0x82,b'\\x00\\x01'+utf(topic)+b'\\x00')\n",
    "def publish(topic,payload): return frame(0x30,utf(topic)+payload)\n",
    "def parse(packet):\n",
    "    n=0\n",
    "    for i in range(1,5):\n",
    "        d=packet[i]; n+=(d&127)*128**(i-1)\n",
    "        if d<128:\n",
    "            assert len(packet)==i+1+n\n",
    "            return packet[0],packet[i+1:]\n",
    "    raise ValueError('bad remaining length')\n",
    "def read_utf(buf):\n",
    "    n=int.from_bytes(buf[:2],'big'); return buf[2:2+n].decode(),buf[2+n:]\n",
    "\n",
    "class Link:\n",
    "    \"\"\"Real TLS endpoints coupled by MemoryBIO; no network or capture privileges.\"\"\"\n",
    "    def __init__(self,path,identity,hostname='localhost'):\n",
    "        path=Path(path); server=ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER);server.minimum_version=ssl.TLSVersion.TLSv1_2\n",
    "        server.load_cert_chain(path/'broker.crt',path/'broker.key');server.load_verify_locations(path/'ca.crt');server.verify_mode=ssl.CERT_REQUIRED\n",
    "        client=ssl.create_default_context(cafile=str(path/'ca.crt'));client.minimum_version=ssl.TLSVersion.TLSv1_2\n",
    "        if identity: client.load_cert_chain(path/f'{identity}.crt',path/f'{identity}.key')\n",
    "        self.ci,self.co,self.si,self.so=[ssl.MemoryBIO() for _ in range(4)]\n",
    "        self.c=client.wrap_bio(self.ci,self.co,server_hostname=hostname);self.s=server.wrap_bio(self.si,self.so,server_side=True)\n",
    "        done=[False,False]\n",
    "        for _ in range(32):\n",
    "            for j,(obj,out,inp) in enumerate([(self.c,self.co,self.si),(self.s,self.so,self.ci)]):\n",
    "                if not done[j]:\n",
    "                    try: obj.do_handshake();done[j]=True\n",
    "                    except ssl.SSLWantReadError: pass\n",
    "                inp.write(out.read())\n",
    "            if all(done): break\n",
    "        if not all(done): raise RuntimeError('Handshake did not complete')\n",
    "        self.identity=next(v for r in self.s.getpeercert()['subject'] for k,v in r if k=='commonName')\n",
    "        self.wire_bytes=0\n",
    "    def transfer(self,packet,to_server=True):\n",
    "        src,out,inp,dst=(self.c,self.co,self.si,self.s) if to_server else (self.s,self.so,self.ci,self.c)\n",
    "        src.write(packet); wire=out.read(); self.wire_bytes+=len(wire); inp.write(wire)\n",
    "        received=dst.read(len(packet)); assert received==packet\n",
    "        return received, packet in wire\n",
    "\n",
    "def run():\n",
    "    \"\"\"Exercise a minimal broker policy for two local TLS-authenticated clients.\"\"\"\n",
    "    with tempfile.TemporaryDirectory() as tmp:\n",
    "        provision(tmp); dev=Link(tmp,'device01'); gw=Link(tmp,'gateway')\n",
    "        for link in (dev,gw):\n",
    "            header,body=parse(link.transfer(connect(link.identity))[0]); assert header==0x10 and body.startswith(utf('MQTT'))\n",
    "            assert parse(link.transfer(frame(0x20,b'\\x00\\x00'),False)[0])==(0x20,b'\\x00\\x00')\n",
    "        header,body=parse(gw.transfer(subscribe(TOPIC))[0]); topic,tail=read_utf(body[2:]); assert header==0x82 and topic==TOPIC and tail==b'\\x00'\n",
    "        assert parse(gw.transfer(frame(0x90,b'\\x00\\x01\\x00'),False)[0])==(0x90,b'\\x00\\x01\\x00')\n",
    "        delivered=[]; visible=False; high=-1; rejected=[]\n",
    "        for topic,seq in [(TOPIC,1),(TOPIC,1),('psut/device02/telemetry',2),(TOPIC,2)]:\n",
    "            payload=json.dumps({'device':'device01','seq':seq,'temperature':25.0},separators=(',',':')).encode()\n",
    "            received,seen=dev.transfer(publish(topic,payload)); visible|=seen\n",
    "            header,body=parse(received); t,data=read_utf(body); assert header==0x30\n",
    "            if dev.identity!='device01' or t!=TOPIC: rejected.append('topic ACL');continue\n",
    "            # Broker forwarding uses a separate TLS session. Freshness is a gateway policy.\n",
    "            received,seen=gw.transfer(publish(t,data),False);visible|=seen\n",
    "            _,b=parse(received);_,message=read_utf(b); m=json.loads(message)\n",
    "            if m['seq']<=high: rejected.append('replay');continue\n",
    "            high=m['seq'];delivered.append(m['seq'])\n",
    "        def fails(identity,hostname):\n",
    "            try: Link(tmp,identity,hostname)\n",
    "            except ssl.SSLError:return True\n",
    "            return False\n",
    "        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}\n",
    "        assert delivered==[1,2] and rejected==['replay','topic ACL'] and result['wrong_hostname_rejected'] and result['missing_client_cert_rejected'] and not visible\n",
    "        return result\n",
    "\n",
    "# Execute the independent classroom verification.\n",
    "print(json.dumps(run(),indent=2))\n"
   ],
   "id": "dbea253cd36aedaa"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
