{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "94ef411d",
   "metadata": {},
   "source": [
    "# CR79 · TLS record framing and AEAD overhead\n",
    "\n",
    "TLS 1.3 outer record header has 5 bytes; encrypted content contains plaintext, inner content type and optional padding, plus AEAD tag (16 bytes in this example). Outer content type is application_data for encrypted records.\n",
    "\n",
    "Foundational concepts; prerequisite: CR78.\n",
    "\n",
    "**Scope:** Length model only; no ciphertext generated."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept079",
   "source": [
    "## TLS records and AEAD\n",
    "\n",
    "The record layer frames data and protects it with negotiated keys. AEAD combines encryption and authentication and binds associated header/context data.\n",
    "\n",
    "**Mathematical / protocol foundations:** Record header is five bytes in conventional TLS framing. TLS 1.3 inner plaintext includes a content-type byte and optional padding; tag length is suite-specific. Nonces are derived from sequence and static IV, not necessarily sent explicitly.\n",
    "\n",
    "**Worked teaching example and interpretation:** For 20 content bytes, one inner type byte, no padding and a 16-byte tag, TLS 1.3 record total=5+20+1+16=42 bytes. TLS 1.2 overhead depends on selected suite; distinguish record size from IP/TCP overhead.\n",
    "\n",
    "Compare corresponding states; for randomized or timed runs compare invariants rather than literal random bytes or timings.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "network79",
   "metadata": {},
   "source": [
    "## TLS 1.3 record boundary and AEAD\n",
    "\n",
    "TLSInnerPlaintext = content || inner content type || zero padding. The five-byte outer header uses application_data (23), legacy version 0x0303 and ciphertext length. For a 16-byte tag, record length = content + 1 + padding + 16. Model uses no compression and checks the TLSCiphertext length bound of 2^14 + 256 bytes; the encrypted inner plaintext must also respect the applicable inner-size limit. The record AEAD exercise is an isolated record-shaped example, not a TLS connection."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "f0e58429",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR79 | Live algorithm and verification =====\n",
    "# The function returns actual modeled intermediate states and checks the result.\n",
    "# ------------------------------------------------------------\n",
    "# PSUT IoT Engineering Studio | CR79\n",
    "# Experiment: tls record framing and aead overhead\n",
    "# Purpose: expose algorithm states and verify the experiment invariant.\n",
    "# ------------------------------------------------------------\n",
    "# CR79 | TLS record framing and AEAD overhead\n",
    "# Execute the named operation; expose states and assert the laboratory invariant.\n",
    "import json\n",
    "\n",
    "\n",
    "\n",
    "DEFAULT={'payload': 40, 'padding': 0}\n",
    "ALTERNATE={'padding': 16}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the lecture baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    payload=params['payload']\n",
    "    padding=params['padding']\n",
    "    if type(payload) is not int or type(padding) is not int or payload<0 or payload>16384 or padding<0 or payload+padding>16384 or payload+1+padding+16>16640:raise ValueError('record size out of model range')\n",
    "    inner=payload+1+padding;length=inner+16;header=bytes([23,3,3])+length.to_bytes(2,'big');steps=[{'field':'header','hex':header.hex(),'bytes':5},{'field':'application data','bytes':payload},{'field':'inner type','bytes':1},{'field':'zero padding','bytes':padding},{'field':'AEAD tag','bytes':16}];result={'wire_bytes':length+5,'record_length':length,'overhead':length+5-payload}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"wire_bytes\"]==sum(s[\"bytes\"] for s in steps), \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "0d2b04bd",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7cb39bf5",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR79 | 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": "5d8f1a04",
   "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": "98f38305",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR79 | 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": "ca53f9e1",
   "metadata": {},
   "source": [
    "## Controlled investigation\n",
    "\n",
    "For payloads 0, 40 and 128 bytes, choose padding 0 then 16. Record header hexadecimal, outer length and wire length. Verify wire_bytes = 5 + payload + 1 + padding + 16. In Python run record_aead.py and explain why altered associated data, ciphertext and tag fail verification.\n",
    "\n",
    "TLSInnerPlaintext = content || inner content type || zero padding. The five-byte outer header uses application_data (23), legacy version 0x0303 and ciphertext length. For a 16-byte tag, record length = content + 1 + padding + 16. Model uses no compression and checks the TLSCiphertext length bound of 2^14 + 256 bytes; the encrypted inner plaintext must also respect the applicable inner-size limit. The record AEAD exercise is an isolated record-shaped example, not a TLS connection."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "recordaead",
   "metadata": {},
   "source": [
    "## Local authenticated record experiment\n",
    "Run this using the installed cryptography library. The key and nonce are fresh per trial. This is not a TLS handshake.\n"
   ]
  },
  {
   "cell_type": "code",
   "id": "recordcode",
   "execution_count": null,
   "outputs": [],
   "metadata": {},
   "source": [
    "# ------------------------------------------------------------\n",
    "# PSUT IoT Engineering Studio | CR79\n",
    "# Local record-shaped AES-GCM verification, not a TLS session.\n",
    "# Uses a fresh key and IV per run. No traffic is sent.\n",
    "# ------------------------------------------------------------\n",
    "import json\n",
    "from secrets import token_bytes\n",
    "from cryptography.hazmat.primitives.ciphers.aead import AESGCM\n",
    "from cryptography.exceptions import InvalidTag\n",
    "\n",
    "def record_trial(payload=40, padding=16):\n",
    "    \"\"\"Bind a TLS-shaped outer header as associated data; test tampering.\"\"\"\n",
    "    if type(payload) is not int or type(padding) is not int or min(payload,padding)<0 or payload+padding>16384:\n",
    "        raise ValueError('Inner plaintext exceeds the classroom limit')\n",
    "    inner=b'A'*payload+b'\\x17'+bytes(padding)\n",
    "    header=b'\\x17\\x03\\x03'+(len(inner)+16).to_bytes(2,'big')\n",
    "    aes=AESGCM(AESGCM.generate_key(bit_length=128))\n",
    "    iv=token_bytes(12) # Single record; never reuse this key/nonce pair.\n",
    "    ciphertext=aes.encrypt(iv,inner,header)\n",
    "    ok=aes.decrypt(iv,ciphertext,header)==inner\n",
    "    def rejected(body, associated):\n",
    "        try: aes.decrypt(iv,body,associated)\n",
    "        except InvalidTag: return True\n",
    "        return False\n",
    "    return {'header':header.hex(),'wire_bytes':5+len(ciphertext),'recovered':ok,\n",
    "            'header_change_rejected':rejected(ciphertext,bytes([header[0]^1])+header[1:]),\n",
    "            'ciphertext_change_rejected':rejected(bytes([ciphertext[0]^1])+ciphertext[1:],header),\n",
    "            'tag_change_rejected':rejected(ciphertext[:-1]+bytes([ciphertext[-1]^1]),header)}\n",
    "\n",
    "result = record_trial()\n",
    "print(json.dumps(result, indent=2))\n",
    "assert all(result[k] for k in [\"recovered\", \"header_change_rejected\", \"ciphertext_change_rejected\", \"tag_change_rejected\"])\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}