{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "8c9d8b97",
   "metadata": {},
   "source": [
    "# CR77 · TCP and TLS 1.2 handshake sequence\n",
    "\n",
    "TCP establishes transport before TLS negotiation. The TLS 1.2 example uses authenticated ephemeral ECDHE; ChangeCipherSpec and Finished precede encrypted application data. Other TLS 1.2 cipher suites differ.\n",
    "\n",
    "Foundational concepts; prerequisite: CR75.\n",
    "\n",
    "**Scope:** TLS 1.2 illustrative ECDHE handshake model, not wire execution."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept077",
   "source": [
    "## TLS 1.2 handshake\n",
    "\n",
    "TCP establishes reliable transport, not cryptographic identity. A certificate-authenticated ECDHE TLS 1.2 exchange negotiates parameters, proves server identity and derives keys.\n",
    "\n",
    "**Mathematical / protocol foundations:** ClientHello and ServerHello negotiate version/randoms/suite; Certificate and ServerKeyExchange convey authenticated server material; ClientKeyExchange carries client share; ChangeCipherSpec and Finished activate/check negotiated protection. Exact messages depend on suite and authentication.\n",
    "\n",
    "**Worked teaching example and interpretation:** For an ephemeral authenticated exchange, private shares remain local. Finished checks the transcript under derived secrets; certificate path and hostname validation still matter. Static RSA key exchange does not provide forward secrecy.\n",
    "\n",
    "Compare corresponding states; for randomized or timed runs compare invariants rather than literal random bytes or timings.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "network77",
   "metadata": {},
   "source": [
    "## TCP versus TLS 1.2 identity\n",
    "\n",
    "Illustrates full server-authenticated TLS 1.2 ECDHE, no client authentication or resumption. The Certificate and signed ephemeral parameters are visible before ChangeCipherSpec. Finished authenticates the transcript under derived secrets. A trusted certificate still requires hostname validation; the switch abstracts those checks."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "89e28f98",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR77 | Live algorithm and verification =====\n",
    "# The function returns actual modeled intermediate states and checks the result.\n",
    "# ------------------------------------------------------------\n",
    "# PSUT IoT Engineering Studio | CR77\n",
    "# Experiment: tcp and tls 1 2 handshake sequence\n",
    "# Purpose: expose algorithm states and verify the experiment invariant.\n",
    "# ------------------------------------------------------------\n",
    "# CR77 | TCP and TLS 1.2 handshake sequence\n",
    "# Execute the named operation; expose states and assert the laboratory invariant.\n",
    "import json\n",
    "\n",
    "\n",
    "\n",
    "DEFAULT={'certificate_valid': True}\n",
    "ALTERNATE={'certificate_valid': False}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the lecture baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    certificate_valid=params['certificate_valid']\n",
    "    if type(certificate_valid) is not bool:\n",
    "        raise ValueError('Invalid classroom input')\n",
    "    steps=[{'from':'Client','to':'Server','message':'TCP SYN'},{'from':'Server','to':'Client','message':'TCP SYN-ACK'},{'from':'Client','to':'Server','message':'TCP ACK'},{'from':'Client','to':'Server','message':'ClientHello'},{'from':'Server','to':'Client','message':'ServerHello, Certificate, ServerKeyExchange, ServerHelloDone'},{'state':'verify server certificate and signed ephemeral parameters','valid':certificate_valid}]\n",
    "    if certificate_valid:steps += [{'from':'Client','to':'Server','message':'ClientKeyExchange, ChangeCipherSpec, Finished'},{'from':'Server','to':'Client','message':'ChangeCipherSpec, Finished'},{'state':'protected application data'}]\n",
    "    else:steps.append({'state':'fatal alert / abort'})\n",
    "    result={'application_allowed':certificate_valid}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"application_allowed\"]==certificate_valid, \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "865f5489",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "cce02814",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR77 | 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": "6fb0cf9a",
   "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": "0f477d8b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR77 | 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": "0656e048",
   "metadata": {},
   "source": [
    "## Controlled investigation\n",
    "\n",
    "Run the valid-certificate baseline; count TCP segments and identify the TLS certificate and Finished stages. Set certificate_valid=false without changing anything else. Record the last completed stage and whether application data is permitted. Compare the resulting flow with CR78.\n",
    "\n",
    "Illustrates full server-authenticated TLS 1.2 ECDHE, no client authentication or resumption. The Certificate and signed ephemeral parameters are visible before ChangeCipherSpec. Finished authenticates the transcript under derived secrets. A trusted certificate still requires hostname validation; the switch abstracts those checks."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}