{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "ee5d2852",
   "metadata": {},
   "source": [
    "# CR74 · X.509 certificate fields and local CA\n",
    "\n",
    "X.509 binds a public key to subject identity via issuer signature; SAN identifies DNS names, validity limits time, key usage constrains purpose. Generate local certificates and verify the issuer signature. Signature verification alone is not full path validation.\n",
    "\n",
    "Foundational concepts; prerequisite: CR70, CR73.\n",
    "\n",
    "**Scope:** Actual local certificate construction/signature check; full chain validation belongs to TLS."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept074",
   "source": [
    "## X.509 identity\n",
    "\n",
    "Certificates bind a public key to identity attributes via an issuer signature. Subject Alternative Name supplies DNS identities for server verification; issuer and subject identify certificate entities.\n",
    "\n",
    "**Mathematical / protocol foundations:** A relying party validates path, constraints, validity, signature and intended usage, then checks the hostname against SAN. A self-signed root is trusted by configuration, not because self-signing proves identity.\n",
    "\n",
    "**Worked teaching example and interpretation:** A locally generated certificate with SAN sensor.lab can pass signature verification but fail identity checking for gateway.lab. Never install the educational CA into a general-purpose trust store.\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": "2cefa6f9",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR74 | 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": "6868e336",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR74 | 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={'hostname': 'localhost'}\n",
    "ALTERNATE={'hostname': 'sensor.lab'}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the reference baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    hostname=params['hostname']\n",
    "    from datetime import datetime,timedelta,timezone\n",
    "    from cryptography import x509\n",
    "    from cryptography.x509.oid import NameOID,ExtendedKeyUsageOID\n",
    "    from cryptography.hazmat.primitives import hashes\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());name=lambda s:x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,s)]);rootname=name('PSUT isolated CA');root=x509.CertificateBuilder().subject_name(rootname).issuer_name(rootname).public_key(ca.public_key()).serial_number(x509.random_serial_number()).not_valid_before(now-timedelta(days=1)).not_valid_after(now+timedelta(days=7)).add_extension(x509.BasicConstraints(ca=True,path_length=0),True).sign(ca,hashes.SHA256());cert=x509.CertificateBuilder().subject_name(name(hostname)).issuer_name(rootname).public_key(leaf.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=False,path_length=None),True).add_extension(x509.SubjectAlternativeName([x509.DNSName(hostname)]),False).add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.SERVER_AUTH]),False).sign(ca,hashes.SHA256());ca.public_key().verify(cert.signature,cert.tbs_certificate_bytes,ec.ECDSA(cert.signature_hash_algorithm))\n",
    "    steps=[{'issuer':cert.issuer.rfc4514_string(),'subject':cert.subject.rfc4514_string(),'version':cert.version.name},{'SAN':cert.extensions.get_extension_for_class(x509.SubjectAlternativeName).value.get_values_for_type(x509.DNSName),'signature_algorithm':cert.signature_algorithm_oid._name},{'root_CA':root.extensions.get_extension_for_class(x509.BasicConstraints).value.ca,'signature_valid':True}];result={'issuer_signature_valid':True,'hostname':hostname}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"issuer_signature_valid\"], \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "7b3c54cb",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4f0ac604",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR74 | 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": "5385b8f5",
   "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": "c2982efc",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR74 | 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": "b85468fa",
   "metadata": {},
   "source": [
    "## Student activity\n",
    "Generate a certificate for localhost then sensor.lab. Identify issuer, subject, SAN and trust anchor. Explain why inspecting fields alone does not establish trust.\n",
    "\n",
    "Submit a baseline/alternate table, trace evidence and a justification. Identify which checks passed and what they do not prove."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}