{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "700eb113",
   "metadata": {},
   "source": [
    "# CR84 · Challenge-response and mutual authentication\n",
    "\n",
    "Challenge-response uses a fresh nonce and proof of key possession. Mutual authentication requires two direction-bound proofs to prevent reflection; this synthetic HMAC model verifies separate labels.\n",
    "\n",
    "Foundational concepts; prerequisite: CR67.\n",
    "\n",
    "**Scope:** Toy protocol; fixed nonces are for reproducibility only, never deploy."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "id": "concept084",
   "source": [
    "## Challenge-response and mutual authentication\n",
    "\n",
    "A challenge is a fresh value used to demonstrate possession of a secret without sending it. Mutual authentication requires verification in both directions.\n",
    "\n",
    "**Mathematical / protocol foundations:** For challenge N, response=MAC_K(context\n",
    "\n",
    "**Worked teaching example and interpretation:** |N||roles). Verify response and freshness; use distinct roles/directions to avoid reflection. Identity binding and authorization remain separate.|If a response is reused with a different challenge, the expected MAC changes and validation must fail. Use local synthetic secrets; do not model a shared MAC key as a public signature key.\n",
    "\n",
    "Compare corresponding states; for randomized or timed runs compare invariants rather than literal random bytes or timings.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "network84",
   "metadata": {},
   "source": [
    "## Challenge-response proof integrity\n",
    "\n",
    "Uses actual HMAC-SHA256 over role labels and two fixed synthetic classroom nonces; client and server labels differ. One-bit tampering changes the received tag. The static nonces make this reproducible, not secure for deployment. Real protocols require fresh unpredictable challenges, canonical framing, context binding and constant-time verification."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a0e9a4e0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR84 | Live algorithm and verification =====\n",
    "# The function returns actual modeled intermediate states and checks the result.\n",
    "# ------------------------------------------------------------\n",
    "# PSUT IoT Engineering Studio | CR84\n",
    "# Experiment: challenge response and mutual authentication\n",
    "# Purpose: expose algorithm states and verify the experiment invariant.\n",
    "# ------------------------------------------------------------\n",
    "# CR84 | Challenge-response and mutual authentication\n",
    "# Execute the named operation; expose states and assert the laboratory invariant.\n",
    "import hashlib\n",
    "import hmac\n",
    "import json\n",
    "\n",
    "\n",
    "\n",
    "DEFAULT={'tamper': False}\n",
    "ALTERNATE={'tamper': True}\n",
    "\n",
    "def run(overrides=None):\n",
    "    # Merge only explicitly supplied inputs with the lecture baseline.\n",
    "    params={**DEFAULT, **(overrides or {})}\n",
    "    tamper=params['tamper']\n",
    "    if type(tamper) is not bool:\n",
    "        raise ValueError('Invalid classroom input')\n",
    "    k=b'synthetic shared key';client_nonce=b'nonce-client';server_nonce=b'nonce-server';mac=lambda label:hmac.new(k,label+b'|'+client_nonce+b'|'+server_nonce,hashlib.sha256).digest();server=mac(b'server');client=mac(b'client');received=client[:-1]+bytes([client[-1]^1]) if tamper else client;steps=[{'message':'client nonce','hex':client_nonce.hex()},{'message':'server proof','tag':server.hex(),'accepted':hmac.compare_digest(server,mac(b'server'))},{'message':'client proof','expected_tag':client.hex(),'received_tag':received.hex(),'accepted':hmac.compare_digest(received,mac(b'client'))}];result={'mutual':steps[1]['accepted'] and steps[2]['accepted']}\n",
    "    # Independently check the stated mathematical or protocol invariant.\n",
    "    assert result[\"mutual\"]== (not tamper), \"verification failed\"\n",
    "    return {\"steps\":steps,\"result\":result}\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "9ac9d065",
   "metadata": {},
   "source": [
    "## Baseline calculation\n",
    "Inspect each trace row. The final result is separate from intermediate states."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "344711a0",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR84 | 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": "bb49be3c",
   "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": "cfd348dd",
   "metadata": {},
   "outputs": [],
   "source": [
    "# ===== CR84 | 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": "00fe82d9",
   "metadata": {},
   "source": [
    "## Controlled investigation\n",
    "\n",
    "Run the valid proof and then toggle tamper. Record the expected and received client tags and verification decisions. Explain how separate role labels prevent reflection in this simplified exchange. In Python confirm the tag using hmac.compare_digest.\n",
    "\n",
    "Uses actual HMAC-SHA256 over role labels and two fixed synthetic classroom nonces; client and server labels differ. One-bit tampering changes the received tag. The static nonces make this reproducible, not secure for deployment. Real protocols require fresh unpredictable challenges, canonical framing, context binding and constant-time verification."
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "name": "python",
   "version": "3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}