{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "76261052",
   "metadata": {},
   "source": [
    "# CR76 · IPsec AH/ESP transport and tunnel packet layout\n",
    "\n",
    "AH provides integrity/authentication but no confidentiality. ESP can provide confidentiality and integrity; transport protects the upper-layer payload while tunnel carries an inner IP packet. This model omits algorithm-dependent padding and outer options except specified assumptions.\n",
    "\n",
    "Foundational concepts; prerequisite: CR19, CR67.\n",
    "\n",
    "**Scope:** Packet-structure arithmetic only; no kernel IPsec or VPN deployment."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept076",
   "source": [
    "## IPsec packet protection\n",
    "\n",
    "IPsec secures network-layer traffic using security associations (SA), policies and sequence numbers. AH authenticates selected fields and payload but does not encrypt; ESP can provide confidentiality and integrity/AEAD.\n",
    "\n",
    "**Mathematical / protocol foundations:** Transport mode retains the original outer IP header and protects upper-layer payload according to AH/ESP semantics. Tunnel mode encapsulates the original IP packet under a new outer header. SPI identifies an SA; sequence number supports anti-replay.\n",
    "\n",
    "**Worked teaching example and interpretation:** For ESP tunnel mode, distinguish the visible outer header from protected inner packet and trailer; overhead depends on suite, padding, IV and tag. The diagram is a packet-layout model, not a configured VPN.\n",
    "\n",
    "Compare corresponding states; for randomized or timed runs compare invariants rather than literal random bytes or timings.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "network76",
   "metadata": {},
   "source": [
    "## Packet layout and byte accounting\n",
    "\n",
    "Assume IPv4 without options (20 B), ESP AES-GCM example with 8 B explicit IV, 16 B tag and alignment to 4 B. AH uses an illustrative 24 B header. Actual sizes depend on transform, IP options and encapsulation; AH excludes or normalizes mutable IP fields. This is byte accounting, not an IPsec implementation."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4c0de81b",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR76 | Live algorithm and verification =====\n",
    "# The function returns actual modeled intermediate states and checks the result.\n",
    "# ------------------------------------------------------------\n",
    "# PSUT IoT Engineering Studio | CR76\n",
    "# Experiment: ipsec ah esp transport and tunnel packet layout\n",
    "# Purpose: expose algorithm states and verify the experiment invariant.\n",
    "# ------------------------------------------------------------\n",
    "# CR76 | IPsec AH/ESP transport and tunnel packet layout\n",
    "# Execute the named operation; expose states and assert the laboratory invariant.\n",
    "import json\n",
    "\n",
    "\n",
    "\n",
    "DEFAULT={'mode': 'transport', 'protocol': 'ESP', 'payload': 48}\n",
    "ALTERNATE={'mode': 'tunnel'}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the lecture baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    mode=params['mode']\n",
    "    protocol=params['protocol']\n",
    "    payload=params['payload']\n",
    "    if type(payload) is not int or not 0 <= payload <= 65000 or mode not in ('transport','tunnel') or protocol not in ('ESP','AH'):raise ValueError('invalid mode/protocol')\n",
    "    inner=20+payload;protected=payload if mode=='transport' else inner;parts=[{'field':'outer IP header','bytes':20,'encrypted':False}]\n",
    "    if protocol=='ESP':parts += [{'field':'ESP SPI + sequence','bytes':8,'encrypted':False},{'field':'explicit IV (example AES-GCM)','bytes':8,'encrypted':False},{'field':'payload or inner packet','bytes':protected,'encrypted':True},{'field':'padding + trailer','bytes':(-(protected+2))%4+2,'encrypted':True},{'field':'ICV/tag','bytes':16,'encrypted':False}]\n",
    "    else:parts += [{'field':'AH (illustrative 96-bit ICV)','bytes':24,'encrypted':False},{'field':'payload or inner packet','bytes':protected,'encrypted':False}]\n",
    "    steps=parts;result={'packet_bytes':sum(x['bytes'] for x in parts),'overhead_vs_original':sum(x['bytes'] for x in parts)-inner,'confidentiality':protocol=='ESP'}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"packet_bytes\"]>20+payload, \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "2a1301ed",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f0239d09",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR76 | 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": "164eb98b",
   "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": "8994ebec",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR76 | 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": "af9c56cd",
   "metadata": {},
   "source": [
    "## Controlled investigation\n",
    "\n",
    "Use ESP transport with 48 bytes, then 49 and 50 bytes. Record alignment padding, tag length and wire bytes. Switch to tunnel without changing the original payload. Repeat with AH. Identify visible fields; distinguish integrity coverage from confidentiality.\n",
    "\n",
    "Assume IPv4 without options (20 B), ESP AES-GCM example with 8 B explicit IV, 16 B tag and alignment to 4 B. AH uses an illustrative 24 B header. Actual sizes depend on transform, IP options and encapsulation; AH excludes or normalizes mutable IP fields. This is byte accounting, not an IPsec implementation."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}