{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "72b3174e",
   "metadata": {},
   "source": [
    "# CR75 · Certificate trust chain and revocation decisions\n",
    "\n",
    "A valid signature is insufficient: trust anchor, intermediates, validity, hostname and applicable revocation policy all matter. Revocation checking depends on client policy and infrastructure.\n",
    "\n",
    "Foundational concepts; prerequisite: CR74.\n",
    "\n",
    "**Scope:** Explicit path-policy model, not a complete RFC 5280 validator."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept075",
   "source": [
    "## PKI path and revocation\n",
    "\n",
    "A trust anchor is an externally configured root. Intermediate CAs require appropriate constraints and key usage; the leaf must have suitable usage, identity and time validity.\n",
    "\n",
    "**Mathematical / protocol foundations:** Policy combines trust path, signature checks, validity, hostname, purpose and configured revocation checks. A CRL lists revoked serial numbers; OCSP can provide status under its policy.\n",
    "\n",
    "**Worked teaching example and interpretation:** A valid signature alone cannot override expiry or hostname mismatch. Compare local OpenSSL outcomes for a valid chain and one failed condition at a time; do not equate a simplified browser policy with full RFC path validation.\n",
    "\n",
    "Compare corresponding states; for randomized or timed runs compare invariants rather than literal random bytes or timings.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "64c99311",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR75 | Algorithm and verification =====\n",
    "# ===== Algorithm and verification =====\n",
    "# The function returns the exact intermediate states and verifies the invariant.\n",
    "import json\n",
    "\n",
    "\n",
    "\n",
    "DEFAULT={'trusted': True, 'intermediate': True, 'time_valid': True, 'hostname_valid': True, 'revoked': False}\n",
    "ALTERNATE={'hostname_valid': False}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the reference baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    trusted=params['trusted']\n",
    "    intermediate=params['intermediate']\n",
    "    time_valid=params['time_valid']\n",
    "    hostname_valid=params['hostname_valid']\n",
    "    revoked=params['revoked']\n",
    "    checks={'trusted root':trusted,'intermediate supplied':intermediate,'validity period':time_valid,'hostname matches':hostname_valid,'not revoked under configured policy':not revoked};steps=[{'check':k,'pass':v} for k,v in checks.items()];result={'accepted':all(checks.values()),'failed':[k for k,v in checks.items() if not v]}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"accepted\"]== (trusted and intermediate and time_valid and hostname_valid and not revoked), \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "5fa14ab0",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b2d01c1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR75 | 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": "75f9d26f",
   "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": "516c87b1",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR75 | 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": "7763aed7",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Compare valid and wrong-hostname scenarios. Independently toggle expiry, missing intermediate, revocation and trust in Python; record failure reason.\n",
    "\n",
    "Submit a baseline/alternate table, trace evidence and a justification. Identify which checks passed and what they do not prove."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## Extended practical: actual certificate path verification\n",
    "Requires Python cryptography and the OpenSSL executable. All certificates and CRL are generated locally; the script removes its temporary directory. Contrast real path verification with the simplified Boolean model."
   ],
   "id": "4f06cf3cc0f80be6"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# ===== CR75 | Dependency check =====\n",
    "import importlib.util\n",
    "assert importlib.util.find_spec(\"cryptography\"), \"Install cryptography with %pip install cryptography\"\n",
    "import shutil\n",
    "assert shutil.which(\"openssl\"), \"OpenSSL executable is required\"\n"
   ],
   "id": "e6cd9f8ac82653aa"
  },
  {
   "cell_type": "code",
   "metadata": {},
   "execution_count": null,
   "outputs": [],
   "source": [
    "# ===== CR75 | Extended local implementation =====\n",
    "# ------------------------------------------------------------\n",
    "# PSUT IoT Engineering Studio | CR75\n",
    "# Build and verify an isolated root/intermediate/leaf chain.\n",
    "# No keys or certificates are installed in a system trust store.\n",
    "# ------------------------------------------------------------\n",
    "from datetime import datetime, timedelta, timezone\n",
    "from pathlib import Path\n",
    "from tempfile import TemporaryDirectory\n",
    "import json\n",
    "import shutil\n",
    "import subprocess\n",
    "from cryptography import x509\n",
    "from cryptography.hazmat.primitives import hashes, serialization\n",
    "from cryptography.hazmat.primitives.asymmetric import ec\n",
    "from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID\n",
    "\n",
    "\n",
    "def verify():\n",
    "    \"\"\"Compare OpenSSL path verification under controlled failure conditions.\"\"\"\n",
    "    if not shutil.which('openssl'):\n",
    "        raise RuntimeError('Install openssl in the Linux environment first.')\n",
    "    now = datetime.now(timezone.utc)\n",
    "    def name(s):\n",
    "        return x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, s)])\n",
    "    def make(subject, key, issuer, signing, ca, path=None):\n",
    "        # The leaf is restricted to server authentication. CA keys sign certificates/CRLs.\n",
    "        builder = (x509.CertificateBuilder().subject_name(name(subject))\n",
    "                   .issuer_name(name(issuer)).public_key(key.public_key())\n",
    "                   .serial_number(x509.random_serial_number())\n",
    "                   .not_valid_before(now - timedelta(days=1))\n",
    "                   .not_valid_after(now + timedelta(days=2))\n",
    "                   .add_extension(x509.BasicConstraints(ca=ca, path_length=path), True)\n",
    "                   .add_extension(x509.KeyUsage(not ca, False, False, False, False, ca, ca, False, False), True)\n",
    "                   .add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()), False)\n",
    "                   .add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(signing.public_key()), False))\n",
    "        if not ca:\n",
    "            builder = (builder.add_extension(x509.SubjectAlternativeName([x509.DNSName(subject)]), False)\n",
    "                       .add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]), False))\n",
    "        return builder.sign(signing, hashes.SHA256())\n",
    "    root, intermediate, leaf, other = [ec.generate_private_key(ec.SECP256R1()) for _ in range(4)]\n",
    "    r = make('PSUT Lab Root', root, 'PSUT Lab Root', root, True, 1)\n",
    "    i = make('PSUT Lab Intermediate', intermediate, 'PSUT Lab Root', root, True, 0)\n",
    "    c = make('sensor.lab', leaf, 'PSUT Lab Intermediate', intermediate, False)\n",
    "    o = make('Unrelated Root', other, 'Unrelated Root', other, True, 1)\n",
    "    # Local CRL explicitly lists the synthetic leaf serial; no external OCSP/CRL service.\n",
    "    revoked = x509.RevokedCertificateBuilder().serial_number(c.serial_number).revocation_date(now - timedelta(minutes=1)).build()\n",
    "    crl = (x509.CertificateRevocationListBuilder().issuer_name(i.subject)\n",
    "           .last_update(now - timedelta(minutes=2)).next_update(now + timedelta(days=1))\n",
    "           .add_revoked_certificate(revoked)\n",
    "           .add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(intermediate.public_key()), False)\n",
    "           .sign(intermediate, hashes.SHA256()))\n",
    "    with TemporaryDirectory(prefix='psut-cr75-') as tmp:\n",
    "        work = Path(tmp)\n",
    "        for n, cert in [('root',r),('intermediate',i),('leaf',c),('other',o),('revoked',crl)]:\n",
    "            (work / (n + '.pem')).write_bytes(cert.public_bytes(serialization.Encoding.PEM))\n",
    "        common = ['-CAfile','root.pem','-untrusted','intermediate.pem','-verify_hostname','sensor.lab','-purpose','sslserver','-x509_strict']\n",
    "        trials = [('baseline',common,True),('hostname mismatch',common+['-verify_hostname','wrong.lab'],False),\n",
    "                  ('missing intermediate',['-CAfile','root.pem','-verify_hostname','sensor.lab'],False),\n",
    "                  ('untrusted root',['-CAfile','other.pem','-untrusted','intermediate.pem','-verify_hostname','sensor.lab'],False),\n",
    "                  ('expired chain',common+['-attime',str(int((now+timedelta(days=3)).timestamp()))],False),\n",
    "                  ('revoked leaf',common+['-crl_check','-CRLfile','revoked.pem'],False)]\n",
    "        results=[]\n",
    "        for label, args, expected in trials:\n",
    "            p = subprocess.run(['openssl','verify',*args,'leaf.pem'],cwd=work,capture_output=True,text=True,timeout=10)\n",
    "            accepted = p.returncode == 0\n",
    "            assert accepted == expected, (label,p.stdout,p.stderr)\n",
    "            results.append({'trial':label,'accepted':accepted,'expected':expected,'output':(p.stdout+p.stderr).strip()})\n",
    "        return results\n",
    "\n",
    "\n",
    "# Execute the extended practical directly in the notebook.\n",
    "print(json.dumps(verify(), indent=2))\n"
   ],
   "id": "2a6c2c03fdc17a15"
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
