From db1afe569ced49085c65df3a3d20d0ee1731b3f4 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:08:16 +0100 Subject: [PATCH 01/24] Add an optional integrated TLS 1.3 server (#631) --- README.md | 2 +- docs/AUTOMATION.md | 2 +- docs/CHANGELOG.md | 1 + docs/CONTENT_POLICY.md | 5 +- docs/PROJECT_STATUS.md | 3 +- docs/TLS.md | 64 ++ ...DR-008-contenu-de-confiance-et-origines.md | 4 +- ...ADR-010-composants-et-outils-optionnels.md | 4 +- docs/adr/ADR-020-services-systeme.md | 11 +- docs/adr/ADR-024-tls-integre.md | 24 + docs/adr/README.md | 1 + include/webfront/ApplicationOrigin.hpp | 4 +- include/webfront/DeveloperApp.hpp | 11 +- include/webfront/ReadBinding.hpp | 14 +- include/webfront/ViewAssociation.hpp | 10 +- include/webfront/WebFront.hpp | 24 +- include/webfront/frontend/CEF.hpp | 8 +- include/webfront/frontend/DefaultBrowser.hpp | 8 +- include/webfront/frontend/Frontend.hpp | 19 +- include/webfront/frontend/Url.hpp | 4 + include/webfront/frontend/WKWebView.hpp | 2 +- include/webfront/frontend/WebKitGTK.hpp | 4 +- include/webfront/frontend/WebView2.hpp | 4 +- include/webfront/http/HTTPServer.hpp | 37 +- .../webfront/networking/BasicNetworking.hpp | 7 + include/webfront/tls/Credentials.hpp | 192 ++++ include/webfront/tls/Server.hpp | 366 ++++++ include/webfront/tls/WebFront.hpp | 8 + include/webfront/tls/detail/Crypto.hpp | 227 ++++ include/webfront/tls/detail/Monocypher.hpp | 1000 +++++++++++++++++ include/webfront/tls/detail/P256.hpp | 803 +++++++++++++ include/webfront/tls/detail/Protocol.hpp | 239 ++++ include/webfront/tls/detail/Wire.hpp | 70 ++ test/driver/WfDriver.hpp | 17 +- test/fuzz/CMakeLists.txt | 2 +- test/fuzz/README.md | 2 +- test/fuzz/RunFuzzers.py | 2 +- test/fuzz/TLSFuzz.cpp | 22 + test/fuzz/corpus/tls/client-hello | Bin 0 -> 196 bytes test/fuzz/corpus/tls/record-header | Bin 0 -> 22 bytes test/unit/CMakeLists.txt | 1 + test/unit/ReadBindingTests.cpp | 12 +- test/unit/TlsTests.cpp | 136 +++ test/web/CMakeLists.txt | 23 +- test/web/JasmineTest.cpp | 37 +- test/web/fixtures/tls/README.md | 3 + test/web/fixtures/tls/cert.pem | 11 + test/web/fixtures/tls/key.pem | 5 + test/web/fixtures/tls/spki.txt | 1 + test/web/suite/specs/webfront-specs.mjs | 1 + 50 files changed, 3390 insertions(+), 67 deletions(-) create mode 100644 docs/TLS.md create mode 100644 docs/adr/ADR-024-tls-integre.md create mode 100644 include/webfront/tls/Credentials.hpp create mode 100644 include/webfront/tls/Server.hpp create mode 100644 include/webfront/tls/WebFront.hpp create mode 100644 include/webfront/tls/detail/Crypto.hpp create mode 100644 include/webfront/tls/detail/Monocypher.hpp create mode 100644 include/webfront/tls/detail/P256.hpp create mode 100644 include/webfront/tls/detail/Protocol.hpp create mode 100644 include/webfront/tls/detail/Wire.hpp create mode 100644 test/fuzz/TLSFuzz.cpp create mode 100644 test/fuzz/corpus/tls/client-hello create mode 100644 test/fuzz/corpus/tls/record-header create mode 100644 test/unit/TlsTests.cpp create mode 100644 test/web/fixtures/tls/README.md create mode 100644 test/web/fixtures/tls/cert.pem create mode 100644 test/web/fixtures/tls/key.pem create mode 100644 test/web/fixtures/tls/spki.txt diff --git a/README.md b/README.md index 33bbc334..cd04ef8f 100644 --- a/README.md +++ b/README.md @@ -526,7 +526,7 @@ CI exercises C++ and native-browser paths on Windows, macOS and Linux. Extended - Development project access is explicit and intended for trusted local code. Downloaded tools run with the application's bridge authority, and script permissions frame only the `context` API: neither is a sandbox. Only packages that run in a browser are supported; installation scripts and native add-ons are not executed. Builds transform TypeScript without type checking; `wf check` type-checks with the compiler the project locks. - An opt-in [native pseudoterminal](docs/PTY.md) connects an application-selected program to xterm.js on Linux, macOS and Windows. - The optional [`@webfront/react` adapter](docs/REACT.md) supplies coalesced C++ stores and empty React islands. `WebFrontLifeReact` demonstrates a C++ panel within the Game of Life React UI; its package archive is prepared locally for registry publication. -- Embedded Linux has ARM64 CI coverage and specific Orin Nano board evidence; other boards, bare-metal targets and microcontrollers are not generally qualified. Check C++23, memory, networking and browser requirements for your target. The default local transport supplies neither TLS nor client authentication; remote deployment needs an application-specific security design. +- Embedded Linux has ARM64 CI coverage and specific Orin Nano board evidence; other boards, bare-metal targets and microcontrollers are not generally qualified. Check C++23, memory, networking and browser requirements for your target. For HTTPS and WSS, see the [optional TLS listener and remote deployment recipe](docs/TLS.md). Client authentication is an application responsibility. - Packaging, accessibility and native-engine deployment still need application-specific work. The optional [`ui.document()` API](docs/DOM.md) provides DOM islands, automatically batched writes, event callbacks and grouped sender reads. See [project status](docs/PROJECT_STATUS.md) for known limitations. ## License diff --git a/docs/AUTOMATION.md b/docs/AUTOMATION.md index 82f1893d..eddb2382 100644 --- a/docs/AUTOMATION.md +++ b/docs/AUTOMATION.md @@ -147,7 +147,7 @@ two-second handshake deadline); they do not consume the 32 authenticated request This prevents silent connections from exhausting that worker pool. A sustained local flood can still deny service through OS or CPU resource exhaustion. Attached clients wait up to 30 seconds for each response; `--request-timeout 1..3600` changes this independently of the operation and -startup deadlines. CLI result polling backs off from 50 ms to one second. There is no TLS or remote/multi-user authentication promise. +startup deadlines. CLI result polling backs off from 50 ms to one second. The automation channel remains local. The optional [TLS listener](TLS.md) serves the application UI and bridge. Listening, accepted and client sockets are non-inheritable; POSIX closes them on exec. The page capability uses the same OS cryptographic generator and comparison as the attachment channel. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 50548de0..0df1f995 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -14,6 +14,7 @@ these entries stays in the GitHub releases and the Git history. - The CEF profile is now `cef_cache/`, not `cef_cache`: an application starts with an empty profile (localStorage, cookies); to keep the data, move the old contents of `cef_cache` into `cef_cache/` once (#617, `docs/HOST_INTEGRATION.md`). ### Added +- Serve HTTPS and WSS with the optional header-only TLS 1.3 listener and reload its PEM identity after renewal (#631, `docs/TLS.md`). - Start an application with no port setting when `9002` is taken: an empty `WebFrontConfig::port` falls back to a free port, a chosen port is never replaced, and CEF and WebKitGTK give each live instance its own profile directory (#617, `docs/HOST_INTEGRATION.md`). - Start several applications side by side: the default port follows `WEBFRONT_PORT` (a number from 0 to 65535, `0` asks for a free port, `9002` remains the default), the examples take `--port`, the server announces the port really bound, and a failed bind names the address, the port and the cause (#617, `docs/HOST_INTEGRATION.md`). - Run the MSVC code analysis in a pull request into `develop` that changes Windows code, and list the reruns each job needed before going green with `FlakeReport.py --days` (#628, `docs/TEST_TIERS.md`, `docs/TEST_PERFORMANCE.md`). diff --git a/docs/CONTENT_POLICY.md b/docs/CONTENT_POLICY.md index d09b85be..d49442b1 100644 --- a/docs/CONTENT_POLICY.md +++ b/docs/CONTENT_POLICY.md @@ -76,8 +76,9 @@ WebView2 still reports failures to read popup event data or mark it handled as s This is a top-level navigation policy, not a subresource/iframe/network sandbox. Frames, fetches, third-party scripts, downloads, OS protocol handlers and browser extensions need separate host -controls. A same-origin script already has the application's bridge authority. The server exposes -no TLS or user authentication. Keep the default loopback bind unless remote access is deliberate. +controls. A same-origin script already has the application's bridge authority. The optional [TLS listener](TLS.md) +protects the transport and authenticates the server. The application owns client authentication. +Keep the default loopback bind unless remote access is deliberate. DevTools settings control the adapter's engine UI, not inspection by native host code or an external debugger. Custom frontends can opt into `open(address, port, page, const ContentPolicy&)`; `BasicWF` prefers diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index 53821250..cb67ceed 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -159,7 +159,8 @@ are retained for investigation; diagnostics alone do not establish a correction. - The developer environment and `NativeDebugFS` are trusted development facilities, not sandboxes. Manifest permissions bound only the scripts' `context` API. Only browser packages install; installation scripts and native add-ons do not run. The [content policy](CONTENT_POLICY.md) - restricts browser origins and navigation but provides neither TLS nor client authentication. + restricts browser origins and navigation. The optional [TLS listener](TLS.md) adds HTTPS and WSS + with TLS 1.3 and ChaCha20-Poly1305. Client authentication remains an application responsibility. - `fs::NativeStorage` confines writable storage to a declared root while resolving each path, but on POSIX it cannot prevent the effective user or the superuser from moving a directory out of the root during an operation: it detects such a move before a commit and after each operation, at diff --git a/docs/TLS.md b/docs/TLS.md new file mode 100644 index 00000000..06b08bb9 --- /dev/null +++ b/docs/TLS.md @@ -0,0 +1,64 @@ +# Serving HTTPS directly + +Include `` and use `webfront::tls::WebFront<>` for a +TLS-only listener. It serves HTTP/1.1 and the WebFront bridge over WSS on the same port. +The component is header-only and links without a TLS library. + +```cpp +#include + +int main() { + auto credentials = std::make_shared( + "/path/to/fullchain.pem", "/path/to/privkey.pem"); + webfront::tls::WebFront app({ + .address = "0.0.0.0", + .port = "8443", + .contentPolicy = {.bridgeAllowedOrigins = {"https://app.example.com:8443"}}, + .tlsCredentials = credentials, + }); + app.cppFunction("greeting", [] { return std::string("Hello over HTTPS"); }); + app.run(); +} +``` + +Use an ECDSA P-256 leaf certificate whose SAN covers the DNS name users visit. +Supply the PEM chain in leaf-first order and an unencrypted PEM private key +in PKCS#8 or SEC1 form. Give the application account read access to the key. +After the certificate manager has written both renewed files, call +`credentials->reload(fullchain, privkey)` from the application's renewal hook. +It checks that the leaf and key match before publishing them to new handshakes. +A failed reload throws and preserves the active identity. Existing connections +continue with their negotiated keys. + +Open the deployment URL in the browser. When using `show()` on a local bind, +the certificate must cover the configured address used in the window URL. +The browser verifies the certificate chain and server name. WebFront applies +the usual bridge origin policy, and the file-service binding cookie has the +`Secure` attribute on the TLS listener. Client authentication and authorization +belong to the application. + +The initial profile negotiates TLS 1.3, X25519, ECDSA P-256 with SHA-256 and +`TLS_CHACHA20_POLY1305_SHA256`. Clients must offer this suite. The profile +uses full handshakes and HTTP/1.1. Where clients require AES-GCM, HTTP/2, +or another certificate type, terminate TLS at the deployment proxy and +configure `httpsByDeployment` if file-service reads are enabled. + +The handshake parser limits ClientHello to 64 KiB and the receive buffer to +16,640 bytes of ciphertext. Connection admission and idle timeouts are +deployment concerns. The [decision record](adr/ADR-024-tls-integre.md) describes +the component's scope and qualification. + +## Size and memory + +On Linux x86-64 with GCC 16.1, a minimal app with one bridge callback built at +`-Os -DNDEBUG -ffunction-sections -fdata-sections -Wl,--gc-sections` gained +47.8 KiB of `.text` and 5.3 KiB of `.rodata` when the TCP provider was +replaced by the TLS provider. The TLS headers total about 2,900 lines, +including source notices and comments in the two vendored primitive subsets. + +In the same binaries, 200 open loopback WebSockets increased Linux +`smaps_rollup` private dirty memory by about 3.6 KiB more per idle connection +for WSS than for WS. Giving each socket 16,384 bytes of an incomplete frame +increased the WSS overhead to about 18.8 KiB per connection. These are process +measurements after a warm-up connection and include allocator overhead. +Thumb-2 size and peak memory during the handshake remain unmeasured. diff --git a/docs/adr/ADR-008-contenu-de-confiance-et-origines.md b/docs/adr/ADR-008-contenu-de-confiance-et-origines.md index 2c493d50..df17f311 100644 --- a/docs/adr/ADR-008-contenu-de-confiance-et-origines.md +++ b/docs/adr/ADR-008-contenu-de-confiance-et-origines.md @@ -37,7 +37,9 @@ peut forger cet en-tête. `Host` ne donne pas une permission de bridge. Que les dérogations de développement demeurent explicites. DevTools et menus restent activés par défaut. Le navigateur système contrôle sa propre navigation ; le serveur y applique néanmoins le contrôle du bridge. Les capacités des moteurs diffèrent, notamment les popups WKWebView. -WebFront cible du contenu de confiance, sans TLS ni authentification intégrés. +WebFront cible du contenu de confiance. Le TLS optionnel ([ADR-024](ADR-024-tls-integre.md)) protège la confidentialité +et l'intégrité du transport. Il authentifie le serveur auprès du navigateur. Le contrôle d'origine reste seul juge +de l'accès au pont et WebFront ne fournit pas d'authentification des clients. Que le secret de lancement d'une vue intégrée (#453) ne s'ajoute pas au contrôle d'origine : il ne donne aucun accès au pont, que le contrôle d'`Origin` règle seul. Il ne sert qu'à savoir si la connexion vient de la vue de diff --git a/docs/adr/ADR-010-composants-et-outils-optionnels.md b/docs/adr/ADR-010-composants-et-outils-optionnels.md index 796e2ad8..96efb47b 100644 --- a/docs/adr/ADR-010-composants-et-outils-optionnels.md +++ b/docs/adr/ADR-010-composants-et-outils-optionnels.md @@ -45,6 +45,8 @@ Le terminal édite les lignes dans le navigateur et appelle les commandes C++. L navigateur peuvent traiter une commande ou la laisser continuer côté C++. Leurs interruptions ne promettent pas d’arrêter une commande C++. +Le TLS serveur est un composant hors du cœur ([ADR-024](ADR-024-tls-integre.md)). + Pour `wf`, HTTPS et vérification SHA-512 se font dans le navigateur. C++ valide les chemins, reçoit les chunks séquentiels et installe via staging puis commit. `ToolStore` conserve `webfront-tools.lock.json` et les fichiers sous `.webfront/tools/`. `PackageFS` utilise le même @@ -56,7 +58,7 @@ l’autorité du bridge de l’application ; c’est une fonction de développem - Étendre le protocole pour chaque composant : évité, réutiliser les types du bridge. - Écraser le handler UI global : remplacé par des abonnements à durée de vie explicite. -- Implémenter TLS ou un registre de paquets C++ dans le cœur : le navigateur fournit HTTPS +- Implémenter un registre de paquets C++ dans le cœur : le navigateur fournit HTTPS et npm fournit métadonnées et distribution. - Installer directement dans le répertoire final : rejeté au profit de transactions pour préserver la version installée en cas d’échec. diff --git a/docs/adr/ADR-020-services-systeme.md b/docs/adr/ADR-020-services-systeme.md index 67ff1643..bc27181b 100644 --- a/docs/adr/ADR-020-services-systeme.md +++ b/docs/adr/ADR-020-services-systeme.md @@ -281,15 +281,14 @@ lève). - **Exposition du jeton.** Chaque réponse de lecture porte `Cache-Control: no-store` et `Referrer-Policy: no-referrer` ; le jeton n'apparaît dans aucun journal HTTP ni diagnostic (chemin masqué). Le cookie de liaison porte `Secure` lorsque la page est servie en HTTPS. -- **Transport : déclaré, jamais déduit.** WebFront ne fournit pas TLS (ADR-008) et ne peut pas savoir comment un client - l'atteint : un mandataire ou un tunnel présente une connexion de boucle locale pour un client distant, et des en-têtes - `Forwarded`/`X-Forwarded-*` peuvent être forgés. WebFront ne lit donc **ni l'adresse ni ces en-têtes** pour décider. +- **Transport** : lorsque WebFront termine TLS ([ADR-024](ADR-024-tls-integre.md)), le transport est connu + et le cookie de liaison est `Secure`. Pour le fournisseur TCP, le transport distant reste déclaré par le déploiement. Une connexion est de transport local seulement si elle est **associée à la vue d'un frontend intégré** : son secret est remis à la vue par l'adaptateur, dans le processus, sans transiter par une ligne de commande, une URL ou un historique. Aucun secret transmis au navigateur système (fragment de l'URL ouverte) n'atteste le transport : la ligne de commande et l'historique peuvent le divulguer, et un acteur qui le présente le premier depuis un navigateur distant serait accepté ; l'échec ultérieur de l'association légitime ne protège pas cette première connexion. Pour - toute connexion non associée, dont celles du navigateur système, le transport est inconnu, quelle que soit son + toute connexion non associée sur le fournisseur TCP, dont celles du navigateur système, le transport est inconnu, quelle que soit son adresse : lectures et écritures de fichiers y sont refusées, sauf déclaration explicite de l'application sur son déploiement (`remoteFileTransport`) : - `refused` (défaut) ; @@ -377,7 +376,7 @@ limites par moteur. #452 est livré dans la version 1.2 (`beforeunload` n'est pa #455 est livré dans la version 1.4 : un fichier non encodé de taille connue est servi par plages (`Range: bytes=a-b`, `a-`, `-n` sur une seule plage : `206` avec `Content-Range`, `416` pour une plage qui commence après la fin, `Accept-Ranges: bytes`), en ne lisant que la plage demandée. Les plages multiples sont servies en entier (`200`) ; il n'y a pas de réponse `multipart/byteranges`. Les réponses encodées ou décodées par le repli annoncent `Accept-Ranges: none`. `If-Range` n'accepte qu'un `ETag` fort fourni par le fournisseur (`fs::File::setEntityTag`) ; WebFront n'en déduit aucun d'un chemin, d'une taille ou d'une date, qui peuvent désigner une autre version que le flux ouvert. Sans validateur (fichiers natifs, données embarquées), la plage conditionnée est servie en entier. Une route dynamique sert un fichier par plages avec `http::fileReply`. Le jeton de lecture reste donc réutilisable pour plusieurs requêtes `Range` ; leur liaison à la connexion propriétaire vient de #469. -#469 est livré dans la version 1.5 : `app.addReadRoute(préfixe, gestionnaire)` (sous `/webfront/services/`, hors `bind/`) et `ui.grantRead(route, chemin, ReadOptions)` appliquent les règles ci-dessus. Le jeton est `.` placé après le préfixe ; la requête est acceptée si le jeton est connu, non expiré, si la connexion propriétaire est ouverte et si l'un des cookies présentés désigne son client (sauf mode transférable : durée obligatoire de 15 minutes au plus). Un jeton est refusé de la même façon dans tous les cas (`403`, mêmes en-têtes). `WebFront.js` échange le secret reçu par `wfBind.exchange` contre le cookie (`GET /webfront/services/bind/`, puis `check`) et `webFront.bound` rejette avec une erreur explicite si le navigateur refuse le cookie. Le cookie est `Secure` si l'application déclare `httpsByDeployment` (le navigateur utilise `https://`) ; un tunnel chiffré sous `http://` (`encryptedByDeployment`) n'en reçoit pas, car le navigateur refuserait un cookie `Secure` reçu en HTTP. Un transport non local sans déclaration est refusé à l'émission du jeton et à chaque requête. +#469 est livré dans la version 1.5 : `app.addReadRoute(préfixe, gestionnaire)` (sous `/webfront/services/`, hors `bind/`) et `ui.grantRead(route, chemin, ReadOptions)` appliquent les règles ci-dessus. Le jeton est `.` placé après le préfixe ; la requête est acceptée si le jeton est connu, non expiré, si la connexion propriétaire est ouverte et si l'un des cookies présentés désigne son client (sauf mode transférable : durée obligatoire de 15 minutes au plus). Un jeton est refusé de la même façon dans tous les cas (`403`, mêmes en-têtes). `WebFront.js` échange le secret reçu par `wfBind.exchange` contre le cookie (`GET /webfront/services/bind/`, puis `check`) et `webFront.bound` rejette avec une erreur explicite si le navigateur refuse le cookie. Le cookie est `Secure` si l'application déclare `httpsByDeployment` (le navigateur utilise `https://`) ; un tunnel chiffré sous `http://` (`encryptedByDeployment`) n'en reçoit pas, car le navigateur refuserait un cookie `Secure` reçu en HTTP. Sur le fournisseur TCP, un transport non local sans déclaration est refusé à l'émission du jeton et à chaque requête. #460 est livré dans la version 1.7 (révision 3.0 de l'ADR-002, qui en donne le détail) : `fs::NativeStorage` applique les mesures de la section « Prescriptions » à toute opération (listage paginé, métadonnées, lecture, écriture par temporaire et renommage, création, suppression, renommage), avec les erreurs typées `storage.rootMoved`, `storage.confinementViolated`, `storage.unsafeDirectory`, `storage.linkRefused`… (`fs::StorageError`, une `BridgeError`). Quatre écarts aux prescriptions, sans affaiblir la garantie : sous Linux, la descente composant par composant est toujours employée plutôt qu'`openat2`, puisque chaque répertoire traversé doit être ouvert pour contrôler son propriétaire ; sous Windows, un point de réanalyse n'est jamais suivi (`LinkPolicy::followInside` ne vaut que sous POSIX) : une opération qui le traverserait ou le lirait échoue avec `linkRefused`, tandis que `status` le signale comme lien et que `remove` supprime le point lui-même, sans atteindre sa cible ; sous Windows, l'appartenance du répertoire à la racine se vérifie par le chemin final de son handle, les handles tenus empêchant déjà le déplacement ; sous Windows encore, le renommage passe par `NtSetInformationFile`, car `SetFileInformationByHandle` convertit un nom relatif en chemin absolu, que refuse un renommage relatif au handle d'un dossier (`STATUS_INVALID_PARAMETER`). Les tests Catch2 couvrent le stockage simulé, les sorties par liens (jonctions sous Windows), le remplacement concurrent d'un composant ou du fichier final par des points d'injection, une course répétée (POSIX), les déplacements d'un répertoire ou de la racine pendant la résolution, l'écriture du temporaire et avant la validation, et les propriétaires refusés ou admis (simulés, et `/tmp` réel). Les droits refusés par le système réel ne sont simulés que par `fs::MemoryStorage` : un test qui retire des droits sur disque échoue sous le superutilisateur. Le paquet `@webfront/services` (#461) est livré dans la version 1.8 : sources dans `js/services/` (`services`, objet gelé vide, et `selfTest()`), archive produite par `wf run services-package` avec le packager partagé de `@webfront/react`, servie par le registre de test, installée par la suite Jasmine qui l'importe ; `wf check` vérifie ses déclarations et `ServicesPackageContents` compare l'archive aux sources, à la licence et au SHA-512. Aucune ressource n'est ajoutée au cœur. L'étape 4 est achevée ; la façade du premier service s'ajoutera à ce paquet avec son épique. @@ -506,7 +505,7 @@ autorisations explicites, backend par connexion). peuvent lire les URL les unes des autres. - **Coût accepté :** un cookie de liaison par client, à qualifier dans chaque moteur ; les téléchargements gérés par l'adaptateur doivent le présenter. -- **Risque :** WebFront ne chiffre pas et ne peut pas attester le transport ; `remoteFileTransport` repose sur la +- **Risque :** Avec le fournisseur TCP, WebFront ne peut pas attester le transport ; `remoteFileTransport` repose sur la déclaration de l'intégrateur. Une déclaration fausse expose jeton et contenu. Par défaut, toute connexion non associée est refusée, y compris celle du navigateur système. - **Coût accepté :** une application qui utilise le navigateur système doit déclarer `loopbackAttested` pour accéder aux diff --git a/docs/adr/ADR-024-tls-integre.md b/docs/adr/ADR-024-tls-integre.md new file mode 100644 index 00000000..3a05b777 --- /dev/null +++ b/docs/adr/ADR-024-tls-integre.md @@ -0,0 +1,24 @@ +# ADR-024 — TLS intégré + +**Statut** : proposé ([#631](https://github.com/ambroise-leclerc/WebFront/issues/631)). + +Un fournisseur réseau optionnel termine TLS 1.3 avant de livrer le flux au serveur HTTP et au pont WebSocket. +Le cœur HTTP garde son fournisseur TCP. Un port TLS sert exclusivement HTTPS et WSS avec HTTP/1.1. +Le profil initial utilise X25519 (avec HelloRetryRequest), ChaCha20-Poly1305, SHA-256 et ECDSA P-256 +avec nonce RFC 6979. AES-GCM reste conditionné à une implémentation à temps constant raisonnable. +La reprise par tickets ajouterait une politique de rotation, une durée de vie et un second chemin de handshake. +Le premier profil fait un handshake complet à chaque connexion. + +L'application fournit une chaîne PEM et une clé P-256 via la configuration. Le rechargement explicite +publie une paire complète après validation. Les handshakes en cours conservent leur instantané. +Le navigateur valide la chaîne et le nom du serveur. TLS protège le transport, tandis que la politique +d'origine continue de décider de l'accès au pont. Le profil ne demande aucun certificat au client. +Le serveur sait que le transport est chiffré lorsqu'il termine TLS et marque alors le cookie de liaison `Secure`. + +Le composant demeure header-only, sous `include/webfront/tls/`. Il réutilise des primitives compactes +avec provenance et licences conservées. La génération de secrets utilise l'aléa de l'OS. Les opérations +sur des secrets exigent des accès mémoire et un contrôle de flux indépendants de ces secrets, avec +vérification sur les compilateurs et architectures supportés. Les vecteurs des RFC, les refus de protocole, +le fuzzing et un test navigateur HTTPS/WSS font partie de la qualification. Les régressions de sécurité +peuvent être signalées en privé aux mainteneurs. La maintenance du composant inclut le suivi des correctifs +amont des primitives et des mesures reproductibles de taille et de mémoire. diff --git a/docs/adr/README.md b/docs/adr/README.md index 8c14f725..2a93dfe9 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -66,6 +66,7 @@ verification evidence remain in [PROJECT_STATUS](../PROJECT_STATUS.md). | [ADR-021](ADR-021-publication-de-l-environnement-developpeur.md) | Simplifying the publication of the developer environment: automate the release, keep pinned hashes, no dedicated server | Accepted (domain delivered; phase 1 to implement) | 2026-11-02 | 1.0 — 2026-11-02 | | [ADR-022](ADR-022-profils-et-niveaux-de-support.md) | Compiler profiles, GCC 13 S2 minimum, exit clause and LTS build tools | Accepted | 2026-11-11 | 1.1 — 2026-11-11 | | [ADR-023](ADR-023-espace-de-noms-des-commandes-du-terminal.md) | Terminal command names: `wf` stays the prefix of project commands, read-only file commands (`ls`, `cat`, `tree`, `mounts`), file command names reserved ahead, dependency graph with `wf list --tree`, `wf why`, `wf info` | Accepted | 2026-11-14 | 1.0 — 2026-11-14 | +| [ADR-024](ADR-024-tls-integre.md) | Optional integrated TLS 1.3 server | Proposed | 2026-11-21 | 1.0 | Numbering follows the reading topics; milestones and individual file histories provide the chronology, which does not follow the numerical order. diff --git a/include/webfront/ApplicationOrigin.hpp b/include/webfront/ApplicationOrigin.hpp index e64c6eea..92e02914 100644 --- a/include/webfront/ApplicationOrigin.hpp +++ b/include/webfront/ApplicationOrigin.hpp @@ -25,12 +25,12 @@ inline std::string applicationHost(std::string_view address) { } /** @brief Canonical application authority shared by the HTTP server and frontend URL builders. */ -inline std::string applicationOrigin(std::string_view address, std::string_view port) { +inline std::string applicationOrigin(std::string_view address, std::string_view port, bool secure = false) { if (port.empty()) throw std::invalid_argument("WebFront: empty frontend port"); if (port.find_first_not_of("0123456789") != std::string_view::npos) throw std::invalid_argument("WebFront: invalid frontend port"); - return "http://" + applicationHost(address) + ":" + std::string(port); + return (secure ? "https://" : "http://") + applicationHost(address) + ":" + std::string(port); } } // namespace webfront::detail diff --git a/include/webfront/DeveloperApp.hpp b/include/webfront/DeveloperApp.hpp index 0c4b58de..f2ce65fa 100644 --- a/include/webfront/DeveloperApp.hpp +++ b/include/webfront/DeveloperApp.hpp @@ -74,13 +74,13 @@ inline std::string bootstrapConfig(const DeveloperBootstrapOptions& options) { } } // namespace developer -template -class BasicDeveloperApp : public BasicWF, http::DefaultBuffersPolicy, Frontend> { - using Base = BasicWF, http::DefaultBuffersPolicy, Frontend>; +template +class DeveloperAppWithNetwork : public BasicWF, http::DefaultBuffersPolicy, Frontend> { + using Base = BasicWF, http::DefaultBuffersPolicy, Frontend>; public: /// An explicit project is required before enabling development file operations. - explicit BasicDeveloperApp(std::filesystem::path projectDirectory = {}, WebFrontConfig config = {}) + explicit DeveloperAppWithNetwork(std::filesystem::path projectDirectory = {}, WebFrontConfig config = {}) : Base(developer::projectConfig(std::move(config), projectDirectory)), project(projectDirectory.empty() ? std::filesystem::path{} : developer::canonicalDirectory(projectDirectory)) { } @@ -138,6 +138,9 @@ class BasicDeveloperApp : public BasicWF store; }; +template +using BasicDeveloperApp = DeveloperAppWithNetwork; + #if defined(_WIN32) || defined(__APPLE__) || defined(__linux__) using NativeApp = BasicDeveloperApp; diff --git a/include/webfront/ReadBinding.hpp b/include/webfront/ReadBinding.hpp index ff5e713e..f97ca706 100644 --- a/include/webfront/ReadBinding.hpp +++ b/include/webfront/ReadBinding.hpp @@ -209,6 +209,9 @@ class ReadBinding { explicit ReadBinding(RemoteFileTransport declared = RemoteFileTransport::refused, Clock clock = [] { return std::chrono::steady_clock::now(); }) : transport(declared), now(std::move(clock)), ownPrefix(std::string(cookiePrefix) + automation::channel::nonce().substr(0, 8) + "-") {} + ReadBinding(bool secure, RemoteFileTransport declared, Clock clock = [] { return std::chrono::steady_clock::now(); }) + : ReadBinding(declared, std::move(clock)) { secureTransport = secure; } + /// Names the cookies after `name` (the port the server listens on) instead of a random word, so that a restart on the /// same port erases the cookies of its previous run. Call before the first `open`. void useNamespace(std::string_view name) { @@ -280,7 +283,7 @@ class ReadBinding { const auto connection = connections.find(key); if (stopped || connection == connections.end()) throw ReadRefused("The connection is closed"); - if (!connection->second.local && transport == RemoteFileTransport::refused) + if (!connection->second.local && !secureTransport && transport == RemoteFileTransport::refused) throw ReadRefused("This connection is not the view of an embedded frontend: declare WebFrontConfig::remoteFileTransport to read files"); Grant record{.owner = key, .route = std::string(routeId), .secret = secret, .path = std::string(rest), .transferable = options.transferable, .expiry = {}, .context = std::make_shared(std::move(options.context))}; if (options.lifetime.count() > 0) { @@ -486,13 +489,13 @@ class ReadBinding { // Cookies named after a client the server forgot are erased; the ones of a known client are left alone. for (const auto& [name, value] : cookies) if (name.starts_with(ownPrefix) && !clients.contains(name.substr(ownPrefix.size()))) - reply.headers.emplace_back("Set-Cookie", name + "=; Max-Age=0; Path=" + std::string(servicesPath) + "; HttpOnly; SameSite=Strict"); + reply.headers.emplace_back("Set-Cookie", name + "=; Max-Age=0; Path=" + std::string(servicesPath) + "; HttpOnly; SameSite=Strict" + (secureCookies() ? "; Secure" : "")); auto id = cookieClient(cookies); if (id.empty()) { id = automation::channel::nonce().substr(0, 16); Client created{.secret = automation::channel::nonce(), .connections = {}}; std::string cookie = ownPrefix + id + "=" + created.secret + "; Path=" + std::string(servicesPath) + "; HttpOnly; SameSite=Strict"; - if (transport == RemoteFileTransport::httpsByDeployment) + if (secureCookies()) cookie += "; Secure"; reply.headers.emplace_back("Set-Cookie", std::move(cookie)); clients.emplace(id, std::move(created)); @@ -527,7 +530,7 @@ class ReadBinding { const auto connection = connections.find(grant.owner); if (connection == connections.end()) return std::nullopt; - if (!connection->second.local && transport == RemoteFileTransport::refused) + if (!connection->second.local && !secureTransport && transport == RemoteFileTransport::refused) return std::nullopt; if (!grant.transferable) { // Any one of the presented cookies may designate the owner's client (concurrent exchanges leave several). @@ -537,7 +540,10 @@ class ReadBinding { return grant.context; } + bool secureCookies() const { return secureTransport || transport == RemoteFileTransport::httpsByDeployment; } + RemoteFileTransport transport; + bool secureTransport = false; Clock now; std::string ownPrefix; std::mutex mutex; diff --git a/include/webfront/ViewAssociation.hpp b/include/webfront/ViewAssociation.hpp index cdd4e8ae..4261ffcd 100644 --- a/include/webfront/ViewAssociation.hpp +++ b/include/webfront/ViewAssociation.hpp @@ -49,13 +49,13 @@ inline std::string newViewSecret() { return mismatch == 0; } -/// The application origin prepared for injection: lowercase, without the default port 80. The script below lets the +/// The application origin prepared for injection: lowercase, without the default port. The script below lets the /// browser's URL parser finish serialization, including compression of IPv6 and its embedded IPv4 notation. -[[nodiscard]] inline std::string browserOrigin(std::string_view address, std::string_view port) { - auto origin = applicationOrigin(address, port); +[[nodiscard]] inline std::string browserOrigin(std::string_view address, std::string_view port, bool secure = false) { + auto origin = applicationOrigin(address, port, secure); std::ranges::transform(origin, origin.begin(), [](unsigned char c) { return static_cast(std::tolower(c)); }); - if (origin.ends_with(":80")) - origin.resize(origin.size() - 3); + if (port == (secure ? "443" : "80")) + origin.resize(origin.size() - port.size() - 1); return origin; } diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 77685568..3130e0d9 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -559,6 +559,8 @@ struct WebFrontConfig { RemoteFileTransport remoteFileTransport = RemoteFileTransport::refused; /// Allows the optional PtyPage component. Requires a literal loopback bind and a bridge policy limited to the application's Origin. bool allowPtyPages = false; + /// PEM identity for the optional HTTPS provider (webfront/tls/WebFront.hpp). + std::shared_ptr tlsCredentials{}; }; namespace detail { @@ -567,17 +569,17 @@ namespace detail { template ServerType makeHttpServer(const WebFrontConfig& config, std::string_view preferred = "9002") { if (!config.port.empty()) - return ServerType(config.address, config.port, config.documentRoot, config.contentPolicy); + return ServerType(config.address, config.port, config.documentRoot, config.contentPolicy, {}, config.tlsCredentials); const auto chosen = environmentPort(); if (chosen) - return ServerType(config.address, *chosen, config.documentRoot, config.contentPolicy); + return ServerType(config.address, *chosen, config.documentRoot, config.contentPolicy, {}, config.tlsCredentials); try { - return ServerType(config.address, std::string(preferred), config.documentRoot, config.contentPolicy); + return ServerType(config.address, std::string(preferred), config.documentRoot, config.contentPolicy, {}, config.tlsCredentials); } catch (const std::system_error& error) { if (error.code() != std::errc::address_in_use) throw; } - return ServerType(config.address, "0", config.documentRoot, config.contentPolicy); + return ServerType(config.address, "0", config.documentRoot, config.contentPolicy, {}, config.tlsCredentials); } } // namespace detail @@ -682,9 +684,9 @@ inline WebFrontConfig checkedPtyPageConfig(WebFrontConfig config) { } /// The read binding of a configuration, which is refused here, before anything is bound, if its declaration is false. -inline std::shared_ptr makeReadBinding(const WebFrontConfig& config) { +inline std::shared_ptr makeReadBinding(const WebFrontConfig& config, bool secure = false) { checkedAddress(config); - return std::make_shared(config.remoteFileTransport); + return std::make_shared(secure, config.remoteFileTransport); } } // namespace detail @@ -705,7 +707,7 @@ class BasicWF { private: struct CheckedConfig {}; BasicWF(WebFrontConfig config, CheckedConfig) - : readBinding(detail::makeReadBinding(config)), + : readBinding(detail::makeReadBinding(config, networking::secureTransport)), httpServer((detail::ensureFrontendInitialized(), detail::makeHttpServer>(config))), httpAddress(config.address), httpPort(httpServer.port()), @@ -1138,7 +1140,9 @@ class BasicWF { throw std::logic_error("webfront::BasicWF::show(): another application is already showing a window through this frontend"); } if constexpr (requires(const ViewLaunch& launch) { Frontend::open(httpAddress, httpPort, htmlFilename, contentPolicy, windowOptions, launch); }) - Frontend::open(httpAddress, httpPort, htmlFilename, contentPolicy, windowOptions, ViewLaunch{viewSecret, detail::browserOrigin(httpAddress, httpPort)}); + Frontend::open(httpAddress, httpPort, htmlFilename, contentPolicy, windowOptions, ViewLaunch{viewSecret, detail::browserOrigin(httpAddress, httpPort, networking::secureTransport)}); + else if constexpr (networking::secureTransport) + static_assert(!networking::secureTransport, "An HTTPS frontend must accept ViewLaunch in open()"); else if constexpr (requires { Frontend::open(httpAddress, httpPort, htmlFilename, contentPolicy, windowOptions); }) Frontend::open(httpAddress, httpPort, htmlFilename, contentPolicy, windowOptions); else if constexpr (requires { Frontend::open(httpAddress, httpPort, htmlFilename, contentPolicy); }) @@ -1228,7 +1232,9 @@ class BasicWF { detail::noteDevelopmentPath(); startServerThread(); try { - if constexpr (requires { Frontend::launch(httpAddress, httpPort, page, contentPolicy); }) + if constexpr (networking::secureTransport) + Frontend::launchHttps(httpAddress, httpPort, page); + else if constexpr (requires { Frontend::launch(httpAddress, httpPort, page, contentPolicy); }) Frontend::launch(httpAddress, httpPort, page, contentPolicy); else Frontend::launch(httpAddress, httpPort, page); diff --git a/include/webfront/frontend/CEF.hpp b/include/webfront/frontend/CEF.hpp index e94a0aa5..03635c06 100644 --- a/include/webfront/frontend/CEF.hpp +++ b/include/webfront/frontend/CEF.hpp @@ -1006,13 +1006,13 @@ inline void openWindow(std::string url, webfront::detail::BoundContentPolicy con CefString(&settings.log_file).FromString((absoluteProfile / "cef_debug.log").string()); } log::info("Attempting CEF initialization..."); - CefRefPtr app(new SimpleCEFApp); + CefRefPtr app(new SimpleCEFApp); #ifndef _WIN32 struct sigaction previousInt{}, previousTerm{}; if (preserveSignalHandlers && (::sigaction(SIGINT, nullptr, &previousInt) || ::sigaction(SIGTERM, nullptr, &previousTerm))) throw std::runtime_error("Cannot preserve native signal handlers"); #endif - const bool initialized = CefInitialize(main_args, settings, app.get(), nullptr); + const bool initialized = CefInitialize(main_args, settings, std::move(app), nullptr); #ifndef _WIN32 // Chrome's browser startup can install handlers independently of ContentMain's setting. // Restore the embedder's exact actions once all browser initialization has finished. @@ -1085,8 +1085,8 @@ inline void closeBrowser(void* browser) { inline void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy& policy = {}, const WindowOptions& window = {}, const ViewLaunch& launch = {}) { - detail::openWindow(frontend::detail::applicationUrl(address, port, file), - webfront::detail::BoundContentPolicy{webfront::detail::applicationOrigin(address, port), policy}, + detail::openWindow(frontend::detail::applicationUrl(address, port, file, launch.origin), + webfront::detail::BoundContentPolicy{frontend::detail::applicationUrl(address, port, "", launch.origin), policy}, nullptr, {}, window, diff --git a/include/webfront/frontend/DefaultBrowser.hpp b/include/webfront/frontend/DefaultBrowser.hpp index cc641a38..358c168f 100644 --- a/include/webfront/frontend/DefaultBrowser.hpp +++ b/include/webfront/frontend/DefaultBrowser.hpp @@ -170,12 +170,16 @@ struct LaunchContext { }; /// Launch the page, then wait for Enter before returning control to the caller. -inline void open(std::string_view address, std::string_view port, std::string_view file, const LaunchContext& context = {}) { - context.launcher(frontend::detail::applicationUrl(address, port, file)); +inline void openUrl(const std::string& url, const LaunchContext& context = {}) { + context.launcher(url); context.output << "Browser opened. Press Enter to close and stop the server..." << std::endl; context.input.get(); } +inline void open(std::string_view address, std::string_view port, std::string_view file, const LaunchContext& context = {}) { + openUrl(frontend::detail::applicationUrl(address, port, file), context); +} + inline void open(std::string_view port, std::string_view file, const LaunchContext& context = {}) { open("127.0.0.1", port, file, context); } diff --git a/include/webfront/frontend/Frontend.hpp b/include/webfront/frontend/Frontend.hpp index ef9c49d7..8cedf28c 100644 --- a/include/webfront/frontend/Frontend.hpp +++ b/include/webfront/frontend/Frontend.hpp @@ -86,6 +86,15 @@ struct DefaultBrowserFrontend { browser::launchWithoutWaiting(detail::applicationUrl(address, port, file)); } + static void launchHttps(std::string_view address, std::string_view port, std::string_view file) { + browser::launchWithoutWaiting(detail::applicationUrl(address, port, file, webfront::detail::applicationOrigin(address, port, true))); + } + + static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy&, const WindowOptions&, + const ViewLaunch& launch) { + browser::openUrl(detail::applicationUrl(address, port, file, launch.origin)); + } + static void open(std::string_view port, std::string_view file) { browser::open(port, file); } @@ -159,13 +168,17 @@ struct BrowserWithUILoopFrontend { static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy&, const WindowOptions&) { open(address, port, file); } + static void open(std::string_view address, std::string_view port, std::string_view file, const ContentPolicy&, const WindowOptions&, + const ViewLaunch& launch) { + loop(address, port, file, browser::launchWithoutWaiting, launch.origin); + } /// The loop with another launcher: the unit tests start no browser. - static void loop(std::string_view address, std::string_view port, std::string_view file, browser::Launcher launcher) { + static void loop(std::string_view address, std::string_view port, std::string_view file, browser::Launcher launcher, std::string_view origin = {}) { // The page opens from inside the loop, once it can run (the platform's loop acquired, nothing left to fail): a loop // that refuses to run never opens a page that nobody serves. A launcher that fails throws before the executor is // attached, so none is left attached. detail::uiloop::run(uiExecutorHostOf(), loopStop(), [&] { - launcher(detail::applicationUrl(address, port, file)); + launcher(detail::applicationUrl(address, port, file, origin)); }); } @@ -377,7 +390,7 @@ struct NativeOrBrowserFrontendFor { if (usesNativeWindow()) detail::openWith(address, port, file, policy, window, launch); else - detail::openWith(address, port, file, policy, window); + detail::openWith(address, port, file, policy, window, ViewLaunch{"", launch.origin}); } private: diff --git a/include/webfront/frontend/Url.hpp b/include/webfront/frontend/Url.hpp index 4edf4d19..c253ed08 100644 --- a/include/webfront/frontend/Url.hpp +++ b/include/webfront/frontend/Url.hpp @@ -45,6 +45,10 @@ inline std::string applicationUrl(std::string_view address, std::string_view por return webfront::detail::applicationOrigin(address, port) + "/" + encodePageReference(page); } +inline std::string applicationUrl(std::string_view address, std::string_view port, std::string_view page, std::string_view origin) { + return origin.starts_with("https://") ? std::string(origin) + "/" + encodePageReference(page) : applicationUrl(address, port, page); +} + inline std::string applicationUrl(std::string_view port, std::string_view page) { return applicationUrl("127.0.0.1", port, page); } diff --git a/include/webfront/frontend/WKWebView.hpp b/include/webfront/frontend/WKWebView.hpp index a697b6b7..e22c5d17 100644 --- a/include/webfront/frontend/WKWebView.hpp +++ b/include/webfront/frontend/WKWebView.hpp @@ -1190,7 +1190,7 @@ inline void open(std::string_view address, std::string_view port, std::string_vi } } openingScope; Object pool(send(type("NSAutoreleasePool"), "new")); - Session window(applicationUrl(address, port, file), options); + Session window(applicationUrl(address, port, file, options.launch.origin), options); window.create(); window.start(); // The AppKit loop drains the main queue: a wake is a block on it. Closing completes pending operations stopped, diff --git a/include/webfront/frontend/WebKitGTK.hpp b/include/webfront/frontend/WebKitGTK.hpp index c1648968..21374555 100644 --- a/include/webfront/frontend/WebKitGTK.hpp +++ b/include/webfront/frontend/WebKitGTK.hpp @@ -955,7 +955,7 @@ inline void open(std::string_view address, std::string_view port, std::string_vi // One window per process: a second open() on the main thread is refused before it creates a window. if (uiExecutorHostOf().executor().available()) throw std::logic_error("WebKitGTKFrontend: open() is already running; a process opens one window at a time"); - Session session(webfront::detail::BoundContentPolicy{webfront::detail::applicationOrigin(address, port), options.contentPolicy}, options.window); + Session session(webfront::detail::BoundContentPolicy{applicationUrl(address, port, "", options.launch.origin), options.contentPolicy}, options.window); session.launch = options.launch; session.create(mode); if (options.configure) @@ -984,7 +984,7 @@ inline void open(std::string_view address, std::string_view port, std::string_vi host.close(); } } closing{host, windowHost}; - session.run(applicationUrl(address, port, file)); + session.run(applicationUrl(address, port, file, options.launch.origin)); } } // namespace webfront::frontend::detail::webkitgtk diff --git a/include/webfront/frontend/WebView2.hpp b/include/webfront/frontend/WebView2.hpp index bca5abc3..57bd84a8 100644 --- a/include/webfront/frontend/WebView2.hpp +++ b/include/webfront/frontend/WebView2.hpp @@ -973,7 +973,7 @@ inline void open(std::string_view address, std::string_view file, const WebView2Options& options, const std::function& prepare = {}) { - auto contentPolicy = webfront::detail::BoundContentPolicy{frontend::detail::applicationUrl(address, port, ""), options.contentPolicy}; + auto contentPolicy = webfront::detail::BoundContentPolicy{frontend::detail::applicationUrl(address, port, "", options.launch.origin), options.contentPolicy}; // One window per process: a second open() on the interface thread is refused before it creates anything. if (uiExecutorHostOf().executor().available()) throw std::logic_error("WebView2Frontend: open() is already running; a process opens one window at a time"); @@ -987,7 +987,7 @@ inline void open(std::string_view address, auto session = std::make_shared(options.startupTimeout); session->contentPolicy = std::move(contentPolicy); session->viewLaunch = options.launch; - session->url = applicationUrl(address, port, file); + session->url = utf16(frontend::detail::applicationUrl(address, port, file, options.launch.origin)); if (prepare) prepare(*session); const auto profile = options.userDataFolder.empty() ? userDataFolder() : std::filesystem::absolute(options.userDataFolder); diff --git a/include/webfront/http/HTTPServer.hpp b/include/webfront/http/HTTPServer.hpp index 6fc19652..d1100aad 100644 --- a/include/webfront/http/HTTPServer.hpp +++ b/include/webfront/http/HTTPServer.hpp @@ -44,6 +44,8 @@ #include #include +namespace webfront::tls { class Credentials; } + namespace webfront::http { class Headers { @@ -875,10 +877,11 @@ class RequestHandler { template class Server { public: - Server(std::string_view address, std::string_view port, std::filesystem::path docRoot = ".", ContentPolicy policy = {}, Decode decode = {}) + Server(std::string_view address, std::string_view port, std::filesystem::path docRoot = ".", ContentPolicy policy = {}, Decode decode = {}, + std::shared_ptr credentials = {}) : acceptor(ioContext), - listeningPort(bind(address, port)), - requestHandler(docRoot, detail::BoundContentPolicy{detail::applicationOrigin(address, listeningPort), std::move(policy)}), + listeningPort((configureTransport(std::move(credentials)), bind(address, port))), + requestHandler(docRoot, detail::BoundContentPolicy{detail::applicationOrigin(address, listeningPort, networking::secureTransport), std::move(policy)}), decodeExecutor(gzip::decodeLimits(), std::move(decode)) { spawn(acceptConnections()); } @@ -1003,6 +1006,23 @@ class Server { BlockingWorker fileWorker{2}; std::function upgradeHandler; + void configureTransport(std::shared_ptr credentials) { + if constexpr (networking::secureTransport) { + if (!credentials) + throw std::invalid_argument("WebFront: missing TLS credentials"); + acceptor.credentials = std::move(credentials); + } else if (credentials) { + throw std::invalid_argument("WebFront: TLS credentials require the HTTPS provider"); + } + } + + networking::Task closeResponse(typename Net::Socket& socket) { + if constexpr (networking::secureTransport) + co_await Net::Close(socket); + else + socket.shutdown(Net::Socket::shutdown_both); + } + std::string bind(std::string_view address, std::string_view requestedPort) { try { const auto endpoint = Net::Resolve(address, requestedPort); @@ -1187,10 +1207,17 @@ class Server { if (head) response.content.clear(); // an error page keeps its Content-Length; HEAD never has a body co_await Net::Send(socket, response.toBuffers()); if (streaming) co_await streamBody(routeWorker, socket, std::move(reply.body), reply.contentLength, match.route->prefix, match.route->secretPath); - socket.shutdown(Net::Socket::shutdown_both); + co_await closeResponse(socket); } networking::Task serve(typename Net::Socket socket) { + if constexpr (networking::secureTransport) { + try { + co_await Net::Handshake(socket, acceptor); + } catch (const std::system_error&) { + co_return; + } + } Request request; std::optional::Lease> lease; std::unique_ptr streamed; @@ -1275,7 +1302,7 @@ class Server { return read; }, streamLength, "File response"); if (response.statusCode != Response::switchingProtocols || tasks.stopRequested()) - socket.shutdown(Net::Socket::shutdown_both); // a stopped server hands nothing over: its drain would never end + co_await closeResponse(socket); // a stopped server hands nothing over: its drain would never end else if (upgradeHandler) upgradeHandler(std::move(socket)); } diff --git a/include/webfront/networking/BasicNetworking.hpp b/include/webfront/networking/BasicNetworking.hpp index be026995..1dcbaa68 100644 --- a/include/webfront/networking/BasicNetworking.hpp +++ b/include/webfront/networking/BasicNetworking.hpp @@ -25,6 +25,13 @@ concept Features = requires { typename T::MutableBuffer; }; +template +inline constexpr bool secureTransport = [] { + if constexpr (requires { Net::secure; }) + return Net::secure; + return false; +}(); + namespace buffers { class MutableBuffer { public: diff --git a/include/webfront/tls/Credentials.hpp b/include/webfront/tls/Credentials.hpp new file mode 100644 index 00000000..0cb58a04 --- /dev/null +++ b/include/webfront/tls/Credentials.hpp @@ -0,0 +1,192 @@ +#pragma once +#include "detail/Wire.hpp" + +#include +#include +#include +#include + +namespace webfront::tls { +namespace detail { +inline constexpr std::size_t maxCredentialBytes = 256 * 1024; +inline constexpr std::array ecPublicKey{0x2a, 0x86, 0x48, 0xce, 0x3d, 2, 1}; +inline constexpr std::array prime256v1{0x2a, 0x86, 0x48, 0xce, 0x3d, 3, 1, 7}; + +inline void ecAlgorithm(Reader oid) { + if (!std::ranges::equal(oid.der(6), ecPublicKey) || !std::ranges::equal(oid.der(6), prime256v1)) + throw Error("expected P-256 algorithm"); + oid.end(); +} + +inline View certificateKey(View certificate) { + Reader input{certificate}; + Reader outer{input.der(0x30)}; + input.end(); + Reader body{outer.der(0x30)}; + if (!body.empty() && body.remaining.front() == 0xa0) + body.der(0xa0); + for (const Byte type : std::array{2, 0x30, 0x30, 0x30, 0x30}) + body.der(type); // serial, signature, issuer, validity, subject + Reader publicKey{body.der(0x30)}; + ecAlgorithm({publicKey.der(0x30)}); + const auto point = publicKey.der(3); + publicKey.end(); + if (point.size() != 66 || point[0] != 0 || point[1] != 4) + throw Error("expected uncompressed certificate key"); + return point.subspan(2); +} + +inline Secret<> privateKey(View input, bool pkcs8) { + Reader source{input}; + Reader key{source.der(0x30)}; + source.end(); + auto version = key.der(2); + if (pkcs8) { + if (version.size() != 1 || version.front() != 0) + throw Error("expected PKCS#8 private key"); + ecAlgorithm({key.der(0x30)}); + Reader wrapped{key.der(4)}; + key = {wrapped.der(0x30)}; + wrapped.end(); + version = key.der(2); + } + if (version.size() != 1 || version.front() != 1) + throw Error("expected EC private key"); + const auto scalar = key.der(4); + if (scalar.size() != 32) + throw Error("invalid EC private key size"); + if (!key.empty() && key.remaining.front() == 0xa0) { + Reader parameters{key.der(0xa0)}; + if (!std::ranges::equal(parameters.der(6), prime256v1)) + throw Error("expected P-256 private key"); + parameters.end(); + } else if (!pkcs8) { + throw Error("EC private key must name its curve"); + } + if (!key.empty()) + key.der(0xa1); + key.end(); + Secret<> result; + std::ranges::copy(scalar, result.begin()); + return result; +} + +inline Bytes pem(std::string_view& source, std::string_view label) { + constexpr std::string_view whitespace = " \r\n\t"; + const auto first = source.find_first_not_of(whitespace); + if (first == source.npos) + return {}; + source.remove_prefix(first); + const auto begin = "-----BEGIN " + std::string(label) + "-----"; + const auto end = "-----END " + std::string(label) + "-----"; + if (!source.starts_with(begin)) + throw Error("unexpected PEM block"); + source.remove_prefix(begin.size()); + const auto stop = source.find(end); + if (stop == source.npos) + throw Error("unterminated PEM block"); + constexpr std::string_view alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; + Bytes decoded; + decoded.reserve(stop / 4 * 3 + 3); + unsigned bits = 0, count = 0, padding = 0; + for (const auto character : source.substr(0, stop)) { + if (whitespace.find(character) != whitespace.npos) + continue; + if (character == '=') { + ++padding; + continue; + } + const auto digit = alphabet.find(character); + if (digit == alphabet.npos || padding) + throw Error("invalid PEM base64"); + bits = (bits << 6) | static_cast(digit); + count += 6; + if (count >= 8) { + count -= 8; + decoded.push_back(static_cast(bits >> count)); + } + } + if (decoded.empty() || count != 2 * padding || padding > 2 || (bits & ((1u << count) - 1)) != 0) + throw Error("invalid PEM padding"); + source.remove_prefix(stop + end.size()); + return decoded; +} + +inline void readPemFile(const std::filesystem::path& path, std::string& contents) { + std::ifstream file(path, std::ios::binary); + contents.resize(maxCredentialBytes + 1); + file.read(contents.data(), static_cast(contents.size())); + if (!file.eof() || file.bad()) + throw Error("cannot read bounded PEM file"); + contents.resize(static_cast(file.gcount())); +} + +struct Identity { + Bytes certificateMessage; + Secret<> key; +}; + +inline std::shared_ptr loadIdentity(const std::filesystem::path& chainPath, const std::filesystem::path& keyPath) { + std::string chain, key; + Bytes der; + struct Wipe { + std::string& key; + Bytes& der; + ~Wipe() { + mono::crypto_wipe(key.data(), key.size()); + mono::crypto_wipe(der.data(), der.size()); + } + } wipe{key, der}; + readPemFile(chainPath, chain); + readPemFile(keyPath, key); + std::string_view chainPem = chain, keyPem = key; + const auto keyStart = keyPem.find_first_not_of(" \r\n\t"); + const bool pkcs8 = keyStart != keyPem.npos && keyPem.substr(keyStart).starts_with("-----BEGIN PRIVATE KEY-----"); + der = pem(keyPem, pkcs8 ? "PRIVATE KEY" : "EC PRIVATE KEY"); + if (keyPem.find_first_not_of(" \r\n\t") != keyPem.npos) + throw Error("extra PEM key material"); + auto identity = std::make_shared(); + identity->key = privateKey(der, pkcs8); + std::uint32_t scalar[8]{}, x[8]{}, y[8]{}; + const auto valid = p256::scalar_from_bytes(scalar, identity->key.data()); + if (!valid) + p256::scalar_mult(x, y, p256::p256_gx, p256::p256_gy, scalar); + p256::zeroize(scalar, sizeof(scalar)); + if (valid) + throw Error("invalid private key scalar"); + std::array point; + p256::m256_to_bytes(point.data(), x, &p256::p256_p); + p256::m256_to_bytes(point.data() + 32, y, &p256::p256_p); + auto leaf = pem(chainPem, "CERTIFICATE"); + if (!std::ranges::equal(certificateKey(leaf), point)) + throw Error("certificate and private key do not match"); + + Bytes entries; + for (auto certificate = std::move(leaf); !certificate.empty(); certificate = pem(chainPem, "CERTIFICATE")) { + vector(entries, certificate, 3); + put(entries, 0, 2); // CertificateEntry extensions + } + Bytes body{0}; // empty certificate_request_context + vector(body, entries, 3); + identity->certificateMessage = handshake(11, body); + return identity; +} +} // namespace detail + +/// The PEM chain starts with the P-256 leaf. Reload publishes both files atomically or throws. +class Credentials { +public: + Credentials(const std::filesystem::path& chain, const std::filesystem::path& key) : identity(detail::loadIdentity(chain, key)) {} + + void reload(const std::filesystem::path& chain, const std::filesystem::path& key) { + identity.store(detail::loadIdentity(chain, key)); + } + + [[nodiscard]] auto snapshot() const { + return identity.load(); + } + +private: + std::atomic> identity; +}; +} // namespace webfront::tls diff --git a/include/webfront/tls/Server.hpp b/include/webfront/tls/Server.hpp new file mode 100644 index 00000000..a35304ad --- /dev/null +++ b/include/webfront/tls/Server.hpp @@ -0,0 +1,366 @@ +#pragma once +#include "../networking/Tasks.hpp" +#include "../networking/TCPNetworkingStdnet.hpp" +#include "Credentials.hpp" +#include "detail/Protocol.hpp" + +namespace webfront::tls { +/// TCP-style stream provider. Handshake, reads and writes run on the same server I/O context. +class Server : public networking::TCPStdnet { + using TCP = networking::TCPStdnet; + using Task = networking::Task; + template + using Result = networking::ex::task; + + using Byte = detail::Byte; + using Bytes = detail::Bytes; + using View = detail::View; + + struct Connection { + detail::Traffic read, write; + detail::Secret<> readSecret{}, writeSecret{}; + Bytes input; + std::size_t offset = 0; + std::array update{}; + std::size_t updateSize = 0; + unsigned skipped = 0; + bool sending = false; + bool compat = false; + bool writeEncrypted = false; + bool established = false; + bool closed = false; + bool updateRequested = false; + }; + +public: + static constexpr bool secure = true; + + struct Acceptor : TCP::Acceptor { + using TCP::Acceptor::Acceptor; + std::shared_ptr credentials; + }; + + struct Socket : TCP::Socket { + explicit Socket(TCP::Socket&& accepted) : TCP::Socket(std::move(accepted)) {} + + private: + friend class Server; + std::unique_ptr connection; + }; + + static auto Accept(Acceptor& acceptor) { + return networking::ex::then(TCP::Accept(acceptor), [](TCP::Socket socket) { + return Socket(std::move(socket)); + }); + } + + // The HTTP server invokes this in its per-connection task, so an incomplete handshake never holds up accept(). + static Task Handshake(Socket& socket, const Acceptor& acceptor) { + Byte failure = 0; + try { + socket.connection = std::make_unique(); + co_await negotiate(socket, acceptor.credentials->snapshot()); + co_return; + } catch (const detail::Error& error) { + failure = error.alert; + } + try { + const std::array alert{2, failure}; + co_await writeRecord(socket, detail::alert, alert); + } catch (const std::system_error&) {} + throw std::system_error(std::make_error_code(std::errc::protocol_error)); + } + + static Result Receive(Socket& socket, MutableBuffer target) { + using namespace detail; + auto& state = *socket.connection; + if (state.closed) + co_return 0; + Byte failure = 0; + try { + while (!state.closed) { + if (state.offset != state.input.size()) { + const auto count = std::min(target.size(), state.input.size() - state.offset); + std::copy_n(state.input.data() + state.offset, count, static_cast(target.data())); + state.offset += count; + co_return count; + } + const auto type = co_await readRecord(socket, true); + state.offset = state.input.size(); + if (type == alert && state.input.size() == 2) { + state.closed = true; + if (state.input[1] != 0) + throw std::system_error(std::make_error_code(std::errc::connection_aborted)); + } else if (type == handshakeRecord) { + receiveKeyUpdate(state); + } else if (type == applicationData && state.updateSize == 0) { + if (!state.input.empty()) { + state.skipped = 0; + state.offset = 0; + continue; + } + } else { + throw Error("unexpected application record", 10); + } + if (++state.skipped > 32) + throw Error("too many consecutive control or empty records", 10); + } + } catch (const Error& error) { + failure = error.alert; + } + state.closed = true; + // An alert cannot overtake a record already being written by the WebSocket task. + if (!state.sending) { + const std::array response{static_cast(failure ? 2 : 1), failure}; + co_await writeRecord(socket, alert, response); + } + if (failure) + throw std::system_error(std::make_error_code(std::errc::protocol_error)); + co_return 0; + } + + static Task Send(Socket& socket, auto buffers) { + using namespace detail; + auto& state = *socket.connection; + if (state.closed) + throw std::system_error(std::make_error_code(std::errc::connection_reset)); + state.sending = true; + struct Sending { + bool& active; + ~Sending() { + active = false; + } + } sending{state.sending}; + constexpr std::size_t header = 5; + std::size_t length = 0; + for (const auto buffer : buffers) + length += std::min(buffer.size(), maxPlaintext - length); + Bytes record(header); + record.reserve(header + length + 17); + for (auto buffer : buffers) { + View data{static_cast(buffer.data()), buffer.size()}; + while (!data.empty()) { + const auto count = std::min(data.size(), maxPlaintext + header - record.size()); + append(record, data.first(count)); + data = data.subspan(count); + if (record.size() == maxPlaintext + header) { + co_await writeApplication(socket, record); + record.resize(header); + } + } + } + if (record.size() != header) + co_await writeApplication(socket, record); + } + + static Task Close(Socket& socket) { + if (!socket.connection->closed) { + constexpr std::array notify{1, 0}; + co_await writeRecord(socket, detail::alert, notify); + } + socket.shutdown(Socket::shutdown_both); + } + +private: + static void receiveKeyUpdate(Connection& state) { + using namespace detail; + if (state.input.empty() || state.input.size() > state.update.size() - state.updateSize) + throw Error("invalid KeyUpdate size", 10); + std::ranges::copy(state.input, state.update.begin() + static_cast(state.updateSize)); + state.updateSize += state.input.size(); + if (state.updateSize != state.update.size()) + return; + if (!std::ranges::equal(View(state.update).first(4), std::array{24, 0, 0, 1}) || state.update.back() > 1) + throw Error("invalid KeyUpdate", 47); + state.readSecret = {expandLabel(state.readSecret, "traffic upd")}; + state.read.install(state.readSecret); + state.updateRequested |= state.update.back() == 1; + state.updateSize = 0; + } + + static Task readExact(Socket& socket, std::span target) { + while (!target.empty()) { + const auto count = co_await TCP::Receive(socket, Buffer(target.data(), target.size())); + if (count == 0) + throw std::system_error(std::make_error_code(std::errc::connection_reset)); + target = target.subspan(count); + } + } + + static Result readRecord(Socket& socket, bool encrypted, bool initial = false) { + using namespace detail; + auto& state = *socket.connection; + for (;;) { + std::array header; + co_await readExact(socket, header); + const auto [type, size] = parseRecord(header, encrypted, initial); + if (size > state.input.capacity()) + state.input.reserve(size); + state.input.resize(size); + co_await readExact(socket, state.input); + if (type == changeCipherSpec && !state.established && !initial && !state.compat && state.input == Bytes{1}) { + state.compat = true; + continue; + } + if (encrypted && type == applicationData) + co_return state.read.open(header, state.input); + if (!encrypted && (type == handshakeRecord || type == alert)) + co_return type; + throw Error("unexpected record type", 10); + } + } + + static Task writeRecord(Socket& socket, Byte type, View body) { + using namespace detail; + auto& state = *socket.connection; + Bytes record{type, 3, 3}; + record.reserve(5 + body.size() + (state.writeEncrypted ? 17 : 0)); + put(record, body.size(), 2); + append(record, body); + if (state.writeEncrypted) + state.write.seal(type, record); + co_await sendRecord(socket, record); + } + + static Task sendRecord(Socket& socket, const Bytes& record) { + const std::array buffers{Buffer(record)}; + co_await TCP::Send(socket, buffers); + } + + static Task writeApplication(Socket& socket, Bytes& record) { + using namespace detail; + auto& state = *socket.connection; + if (state.closed) + throw std::system_error(std::make_error_code(std::errc::connection_reset)); + if (std::exchange(state.updateRequested, false)) { + constexpr std::array update{24, 0, 0, 1, 0}; + co_await writeRecord(socket, handshakeRecord, update); + state.writeSecret = {expandLabel(state.writeSecret, "traffic upd")}; + state.write.install(state.writeSecret); + } + state.write.seal(applicationData, record); + co_await sendRecord(socket, record); + } + + static Result readHandshake(Socket& socket, unsigned limit, bool encrypted, bool initial = false) { + using namespace detail; + Bytes message; + std::size_t expected = 4; + do { + const auto type = co_await readRecord(socket, encrypted, initial); + const auto& input = socket.connection->input; + if (type == alert && input.size() == 2) + throw std::system_error(std::make_error_code(std::errc::connection_aborted)); + if (type != handshakeRecord) + throw Error("expected handshake record", 10); + if (input.empty() || input.size() > limit - message.size()) + throw Error("invalid handshake fragment"); + append(message, input); + if (message.size() >= 4) { + expected = 4 + Reader{View(message).subspan(1)}.number(3); + if (expected > limit || message.size() > expected) + throw Error("invalid handshake size"); + } + } while (message.size() < expected); + co_return message; + } + + static Task writeHandshake(Socket& socket, detail::Sha256& transcript, View message) { + transcript.update(message); + while (!message.empty()) { + const auto fragment = message.first(std::min(message.size(), detail::maxPlaintext)); + co_await writeRecord(socket, detail::handshakeRecord, fragment); + message = message.subspan(fragment.size()); + } + } + + static Task negotiate(Socket& socket, std::shared_ptr identity) { + using namespace detail; + auto& state = *socket.connection; + Sha256 transcript; + auto message = co_await readHandshake(socket, 65536, false, true); + auto hello = parseHello(message, false); + bool retry = hello.share.empty(); + constexpr std::array ccs{1}; + if (retry) { + const auto first = hello.invariant; + const bool compat = !hello.session.empty(); + transcript.update(handshake(254, hash(message))); + co_await writeHandshake(socket, transcript, serverHello(hello.session, retryRandom, {})); + if (compat) + co_await writeRecord(socket, changeCipherSpec, ccs); + message = co_await readHandshake(socket, 65536, false); + hello = parseHello(message, true); + if (hello.invariant != first || hello.share.empty() || hello.shareCount != 1) + throw Error("invalid second ClientHello", 47); + } + transcript.update(message); + Digest random{}, publicKey{}; + Secret<> scalar{}, shared{}; + entropy(random); + entropy(scalar); + mono::crypto_x25519_public_key(publicKey.data(), scalar.data()); + mono::crypto_x25519(shared.data(), scalar.data(), hello.share.data()); + if (!mono::crypto_verify32(shared.data(), zeros.data())) + throw Error("invalid X25519 shared secret", 47); + co_await writeHandshake(socket, transcript, serverHello(hello.session, random, publicKey)); + if (!retry && !hello.session.empty()) + co_await writeRecord(socket, changeCipherSpec, ccs); + + const auto empty = hash(); + const Secret<> early{hmac(zeros, {zeros})}; + const Secret<> derived{expandLabel(early, "derived", empty)}; + const Secret<> secret{hmac(derived, {shared})}; + const auto afterHello = transcript.digest(); + const Secret<> client{expandLabel(secret, "c hs traffic", afterHello)}; + const Secret<> server{expandLabel(secret, "s hs traffic", afterHello)}; + state.read.install(client); + state.write.install(server); + state.writeEncrypted = true; + Bytes extensions; + if (hello.alpn) { + Bytes protocol; + vector(protocol, bytes("http/1.1"), 1); + Bytes protocols; + vector(protocols, protocol, 2); + extension(extensions, 16, protocols); + } + Bytes encryptedExtensions; + vector(encryptedExtensions, extensions, 2); + co_await writeHandshake(socket, transcript, handshake(8, encryptedExtensions)); + co_await writeHandshake(socket, transcript, identity->certificateMessage); + + Bytes input(64, 0x20); + append(input, bytes("TLS 1.3, server CertificateVerify")); + input.push_back(0); + append(input, transcript.digest()); + Bytes verify; + put(verify, signatureScheme, 2); + vector(verify, sign(identity->key, hash(input)), 2); + co_await writeHandshake(socket, transcript, handshake(15, verify)); + const Secret<> serverFinished{expandLabel(server, "finished")}; + co_await writeHandshake(socket, transcript, handshake(20, hmac(serverFinished, {transcript.digest()}))); + + const Secret<> masterSalt{expandLabel(secret, "derived", empty)}; + const Secret<> master{hmac(masterSalt, {zeros})}; + const auto afterFinished = transcript.digest(); + state.readSecret = {expandLabel(master, "c ap traffic", afterFinished)}; + state.writeSecret = {expandLabel(master, "s ap traffic", afterFinished)}; + state.write.install(state.writeSecret); + + const auto finished = co_await readHandshake(socket, 36, true); + Reader reader{finished}; + if (reader.number(1) != 20) + throw Error("expected client Finished", 10); + const auto verification = reader.vector(3); + reader.end(); + const Secret<> clientFinished{expandLabel(client, "finished")}; + const auto expected = hmac(clientFinished, {afterFinished}); + if (verification.size() != 32 || mono::crypto_verify32(expected.data(), verification.data())) + throw Error("invalid client Finished", 51); + state.read.install(state.readSecret); + state.input.clear(); + state.established = true; + } +}; +} // namespace webfront::tls diff --git a/include/webfront/tls/WebFront.hpp b/include/webfront/tls/WebFront.hpp new file mode 100644 index 00000000..63171c8e --- /dev/null +++ b/include/webfront/tls/WebFront.hpp @@ -0,0 +1,8 @@ +#pragma once +#include "../WebFront.hpp" +#include "Server.hpp" + +namespace webfront::tls { +template +using WebFront = BasicWF; +} // namespace webfront::tls diff --git a/include/webfront/tls/detail/Crypto.hpp b/include/webfront/tls/detail/Crypto.hpp new file mode 100644 index 00000000..12125b33 --- /dev/null +++ b/include/webfront/tls/detail/Crypto.hpp @@ -0,0 +1,227 @@ +#pragma once +#include "../../automation/Platform.hpp" +#include "Monocypher.hpp" +#include "P256.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::tls::detail { +using Byte = std::uint8_t; +using Bytes = std::vector; +using View = std::span; +using Digest = std::array; + +inline View bytes(std::string_view string) { + return {reinterpret_cast(string.data()), string.size()}; +} + +inline void append(Bytes& out, View data) { + out.insert(out.end(), data.begin(), data.end()); +} +inline void put(Bytes& out, std::size_t value, unsigned count) { + while (count) + out.push_back(static_cast(value >> (8 * --count))); +} + +struct Sha256 { + void update(View data) { + length += data.size(); + while (!data.empty()) { + const auto count = std::min(data.size(), block.size() - used); + std::copy_n(data.begin(), count, block.begin() + used); + used += count; + data = data.subspan(count); + if (used == block.size()) { + compress(); + used = 0; + } + } + } + + Digest digest() const { + auto copy = *this; + std::array tail{0x80}; + const auto count = (used < 56 ? 64u : 128u) - used; + for (unsigned i = 0; i != 8; ++i) + tail[count - 1 - i] = static_cast((length * 8) >> (8 * i)); + copy.update(View(tail).first(count)); + Digest result; + for (unsigned i = 0; i != result.size(); ++i) + result[i] = static_cast(copy.state[i / 4] >> (24 - 8 * (i % 4))); + return result; + } + + ~Sha256() { + mono::crypto_wipe(this, sizeof(*this)); + } + +private: + void compress() { + static constexpr std::uint32_t constants[]{ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, 0xd807aa98, 0x12835b01, 0x243185be, + 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, + 0x5cb0a9dc, 0x76f988da, 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, 0x27b70a85, + 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, + 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, + 0x682e6ff3, 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2}; + auto [a, b, c, d, e, f, g, h] = state; + std::array words; + for (unsigned i = 0; i != 64; ++i) { + auto& word = words[i % 16]; + if (i < 16) { + word = 0; + for (unsigned j = 0; j != 4; ++j) + word = (word << 8) | block[4 * i + j]; + } else { + const auto x = words[(i - 15) % 16], y = words[(i - 2) % 16]; + word += words[(i - 7) % 16] + (std::rotr(x, 7) ^ std::rotr(x, 18) ^ (x >> 3)) + (std::rotr(y, 17) ^ std::rotr(y, 19) ^ (y >> 10)); + } + const auto t1 = h + (std::rotr(e, 6) ^ std::rotr(e, 11) ^ std::rotr(e, 25)) + ((e & f) ^ (~e & g)) + constants[i] + word; + const auto t2 = (std::rotr(a, 2) ^ std::rotr(a, 13) ^ std::rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c)); + h = g; + g = f; + f = e; + e = d + t1; + d = c; + c = b; + b = a; + a = t1 + t2; + } + const std::array final{a, b, c, d, e, f, g, h}; + for (unsigned i = 0; i != state.size(); ++i) + state[i] += final[i]; + mono::crypto_wipe(words.data(), sizeof(words)); + } + + std::array state{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; + std::array block{}; + std::uint64_t length = 0; + std::size_t used = 0; +}; + +inline Digest hash(View data = {}) { + Sha256 sha; + sha.update(data); + return sha.digest(); +} + +// All HMAC keys used by the TLS suite and RFC 6979 fit in a single SHA-256 block. +inline Digest hmac(View key, std::initializer_list chunks) { + if (key.size() > 64) + throw std::invalid_argument("HMAC key exceeds one SHA-256 block"); + std::array pad; + pad.fill(0x36); + for (std::size_t i = 0; i != key.size(); ++i) + pad[i] ^= key[i]; + Sha256 inner, outer; + inner.update(pad); + for (const auto chunk : chunks) + inner.update(chunk); + for (auto& byte : pad) + byte ^= 0x36 ^ 0x5c; + outer.update(pad); + auto digest = inner.digest(); + outer.update(digest); + mono::crypto_wipe(pad.data(), pad.size()); + mono::crypto_wipe(digest.data(), digest.size()); + return outer.digest(); +} + +inline Digest expandLabel(View key, std::string_view label, View context = {}, unsigned size = 32) { + Bytes info; + put(info, size, 2); + put(info, 6 + label.size(), 1); + append(info, bytes("tls13 ")); + append(info, bytes(label)); + put(info, context.size(), 1); + append(info, context); + info.push_back(1); // HKDF block number. TLS here needs at most one block. + return hmac(key, {info}); +} + +inline void entropy(std::span out) { +#ifdef _WIN32 + if (BCryptGenRandom(nullptr, out.data(), static_cast(out.size()), BCRYPT_USE_SYSTEM_PREFERRED_RNG) != 0) +#else + if (getentropy(out.data(), out.size()) != 0) +#endif + throw std::runtime_error("TLS: operating system entropy unavailable"); +} + +template +struct Secret : std::array { + ~Secret() { + mono::crypto_wipe(this->data(), Size); + } +}; + +inline Bytes sign(View key, View messageHash) { + using namespace p256; + std::uint32_t d[8]{}, k[8]{}, x[8]{}, y[8]{}, z[8]{}; + struct Wipe { + std::initializer_list buffers; + ~Wipe() { + for (auto buffer : buffers) + zeroize(buffer, 32); + } + } wipe{ + {d, k, x, y, z} + }; + if (scalar_from_bytes(d, key.data()) != 0) + throw std::invalid_argument("TLS: invalid P-256 scalar"); + u256_from_bytes(z, messageHash.data()); + ecdsa_m256_mod_n(z); + Digest reduced; + u256_to_bytes(reduced.data(), z); + Secret<> v, mac{}; + v.fill(1); + const std::array zero{0}, one{1}; + mac = {hmac(mac, {v, zero, key, reduced})}; + v = {hmac(mac, {v})}; + mac = {hmac(mac, {v, one, key, reduced})}; + v = {hmac(mac, {v})}; + m256_prep(d, &p256_n); + m256_prep(z, &p256_n); + for (;;) { + v = {hmac(mac, {v})}; + if (scalar_from_bytes(k, v.data()) == 0) { + scalar_mult(x, y, p256_gx, p256_gy, k); + m256_done(x, &p256_p); + ecdsa_m256_mod_n(x); + Digest r, s; + u256_to_bytes(r.data(), x); + m256_prep(x, &p256_n); + m256_prep(k, &p256_n); + m256_inv(k, k, &p256_n); + m256_mul(y, x, d, &p256_n); + m256_add(y, y, z, &p256_n); + m256_mul(y, y, k, &p256_n); + m256_to_bytes(s.data(), y, &p256_n); + if (u256_diff0(x) && u256_diff0(y)) { + Bytes signature{0x30, 0}; + for (View value : {View(r), View(s)}) { + while (value.size() > 1 && value.front() == 0) + value = value.subspan(1); + const bool prefix = value.front() >= 128; + put(signature, 2, 1); + put(signature, value.size() + prefix, 1); + if (prefix) + signature.push_back(0); + append(signature, value); + } + signature[1] = static_cast(signature.size() - 2); + return signature; + } + } + mac = {hmac(mac, {v, zero})}; + v = {hmac(mac, {v})}; + } +} +} // namespace webfront::tls::detail diff --git a/include/webfront/tls/detail/Monocypher.hpp b/include/webfront/tls/detail/Monocypher.hpp new file mode 100644 index 00000000..dc7754e5 --- /dev/null +++ b/include/webfront/tls/detail/Monocypher.hpp @@ -0,0 +1,1000 @@ +// Monocypher version 4.0.2 +// +// This file is dual-licensed. Choose whichever licence you want from +// the two licences listed below. +// +// The first licence is a regular 2-clause BSD licence. The second licence +// is the CC-0 from Creative Commons. It is intended to release Monocypher +// to the public domain. The BSD licence serves as a fallback option. +// +// SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0 +// +// ------------------------------------------------------------------------ +// +// Copyright (c) 2017-2020, Loup Vaillant +// All rights reserved. +// +// +// Redistribution and use in source and binary forms, with or without +// modification, are permitted provided that the following conditions are +// met: +// +// 1. Redistributions of source code must retain the above copyright +// notice, this list of conditions and the following disclaimer. +// +// 2. Redistributions in binary form must reproduce the above copyright +// notice, this list of conditions and the following disclaimer in the +// documentation and/or other materials provided with the +// distribution. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +// +// ------------------------------------------------------------------------ +// +// Written in 2017-2020 by Loup Vaillant +// +// To the extent possible under law, the author(s) have dedicated all copyright +// and related neighboring rights to this software to the public domain +// worldwide. This software is distributed without any warranty. +// +// You should have received a copy of the CC0 Public Domain Dedication along +// with this software. If not, see +// + +// Subset of Monocypher 4.0.2 (0d85f98c9d9b0227e42cf795cb527dff372b40a4). +#pragma once +#if defined(__GNUC__) +#pragma GCC system_header +#elif defined(_MSC_VER) +#pragma warning(push, 0) +#endif +#include +#include +namespace webfront::tls::detail::mono { +using std::size_t; +using std::int32_t; +using std::int64_t; +using std::uint8_t; +using std::uint32_t; +using std::uint64_t; +#define WEBFRONT_TLS_MONO_FOR_T(type, i, start, end) for (type i = (start); i < (end); i++) +#define WEBFRONT_TLS_MONO_FOR(i, start, end) WEBFRONT_TLS_MONO_FOR_T(size_t, i, start, end) +#define WEBFRONT_TLS_MONO_COPY(dst, src, size) WEBFRONT_TLS_MONO_FOR(_i_, 0, size) (dst)[_i_] = (src)[_i_] +#define WEBFRONT_TLS_MONO_ZERO(buf, size) WEBFRONT_TLS_MONO_FOR(_i_, 0, size) (buf)[_i_] = 0 +#define WEBFRONT_TLS_MONO_WIPE_CTX(ctx) crypto_wipe(ctx , sizeof(*(ctx))) +#define WEBFRONT_TLS_MONO_WIPE_BUFFER(buffer) crypto_wipe(buffer, sizeof(buffer)) +#define WEBFRONT_TLS_MONO_MIN(a, b) ((a) <= (b) ? (a) : (b)) +#define WEBFRONT_TLS_MONO_MAX(a, b) ((a) >= (b) ? (a) : (b)) + +typedef int8_t i8; +typedef uint8_t u8; +typedef int16_t i16; +typedef uint32_t u32; +typedef int32_t i32; +typedef int64_t i64; +typedef uint64_t u64; + +inline constexpr u8 zero[128] = {0}; + +// returns the smallest positive integer y such that +// (x + y) % pow_2 == 0 +// Basically, y is the "gap" missing to align x. +// Only works when pow_2 is a power of 2. +// Note: we use ~x+1 instead of -x to avoid compiler warnings +inline size_t gap(size_t x, size_t pow_2) +{ + return (~x + 1) & (pow_2 - 1); +} + +inline u32 load24_le(const u8 s[3]) +{ + return + ((u32)s[0] << 0) | + ((u32)s[1] << 8) | + ((u32)s[2] << 16); +} + +inline u32 load32_le(const u8 s[4]) +{ + return + ((u32)s[0] << 0) | + ((u32)s[1] << 8) | + ((u32)s[2] << 16) | + ((u32)s[3] << 24); +} + +inline u64 load64_le(const u8 s[8]) +{ + return load32_le(s) | ((u64)load32_le(s+4) << 32); +} + +inline void store32_le(u8 out[4], u32 in) +{ + out[0] = in & 0xff; + out[1] = (in >> 8) & 0xff; + out[2] = (in >> 16) & 0xff; + out[3] = (in >> 24) & 0xff; +} + +inline void store64_le(u8 out[8], u64 in) +{ + store32_le(out , (u32)in ); + store32_le(out + 4, in >> 32); +} + +inline void load32_le_buf (u32 *dst, const u8 *src, size_t size) { + WEBFRONT_TLS_MONO_FOR(i, 0, size) { dst[i] = load32_le(src + i*4); } +} +inline u32 rotl32(u32 x, u32 n) { return (x << n) ^ (x >> (32 - n)); } + +inline int neq0(u64 diff) +{ + // constant time comparison to zero + // return diff != 0 ? -1 : 0 + u64 half = (diff >> 32) | ((u32)diff); + return (1 & ((half - 1) >> 32)) - 1; +} + +inline u64 x16(const u8 a[16], const u8 b[16]) +{ + return (load64_le(a + 0) ^ load64_le(b + 0)) + | (load64_le(a + 8) ^ load64_le(b + 8)); +} +inline u64 x32(const u8 a[32],const u8 b[32]){return x16(a,b)| x16(a+16, b+16);} +inline int crypto_verify16(const u8 a[16], const u8 b[16]){ return neq0(x16(a, b)); } +inline int crypto_verify32(const u8 a[32], const u8 b[32]){ return neq0(x32(a, b)); } +inline void crypto_wipe(void *secret, size_t size) +{ + volatile u8 *v_secret = (u8*)secret; + WEBFRONT_TLS_MONO_ZERO(v_secret, size); +} + +#define WEBFRONT_TLS_MONO_QUARTERROUND(a, b, c, d) \ + a += b; d = rotl32(d ^ a, 16); \ + c += d; b = rotl32(b ^ c, 12); \ + a += b; d = rotl32(d ^ a, 8); \ + c += d; b = rotl32(b ^ c, 7) + +inline void chacha20_rounds(u32 out[16], const u32 in[16]) +{ + // The temporary variables make Chacha20 10% faster. + u32 t0 = in[ 0]; u32 t1 = in[ 1]; u32 t2 = in[ 2]; u32 t3 = in[ 3]; + u32 t4 = in[ 4]; u32 t5 = in[ 5]; u32 t6 = in[ 6]; u32 t7 = in[ 7]; + u32 t8 = in[ 8]; u32 t9 = in[ 9]; u32 t10 = in[10]; u32 t11 = in[11]; + u32 t12 = in[12]; u32 t13 = in[13]; u32 t14 = in[14]; u32 t15 = in[15]; + + WEBFRONT_TLS_MONO_FOR (i, 0, 10) { // 20 rounds, 2 rounds per loop. + WEBFRONT_TLS_MONO_QUARTERROUND(t0, t4, t8 , t12); // column 0 + WEBFRONT_TLS_MONO_QUARTERROUND(t1, t5, t9 , t13); // column 1 + WEBFRONT_TLS_MONO_QUARTERROUND(t2, t6, t10, t14); // column 2 + WEBFRONT_TLS_MONO_QUARTERROUND(t3, t7, t11, t15); // column 3 + WEBFRONT_TLS_MONO_QUARTERROUND(t0, t5, t10, t15); // diagonal 0 + WEBFRONT_TLS_MONO_QUARTERROUND(t1, t6, t11, t12); // diagonal 1 + WEBFRONT_TLS_MONO_QUARTERROUND(t2, t7, t8 , t13); // diagonal 2 + WEBFRONT_TLS_MONO_QUARTERROUND(t3, t4, t9 , t14); // diagonal 3 + } + out[ 0] = t0; out[ 1] = t1; out[ 2] = t2; out[ 3] = t3; + out[ 4] = t4; out[ 5] = t5; out[ 6] = t6; out[ 7] = t7; + out[ 8] = t8; out[ 9] = t9; out[10] = t10; out[11] = t11; + out[12] = t12; out[13] = t13; out[14] = t14; out[15] = t15; +} + +inline const u8 * const chacha20_constant = (const u8*)"expand 32-byte k"; // 16 bytes +inline u64 crypto_chacha20_djb(u8 *cipher_text, const u8 *plain_text, + size_t text_size, const u8 key[32], const u8 nonce[8], + u64 ctr) +{ + u32 input[16]; + load32_le_buf(input , chacha20_constant, 4); + load32_le_buf(input + 4, key , 8); + load32_le_buf(input + 14, nonce , 2); + input[12] = (u32) ctr; + input[13] = (u32)(ctr >> 32); + + // Whole blocks + u32 pool[16]; + size_t nb_blocks = text_size >> 6; + WEBFRONT_TLS_MONO_FOR (i, 0, nb_blocks) { + chacha20_rounds(pool, input); + if (plain_text != 0) { + WEBFRONT_TLS_MONO_FOR (j, 0, 16) { + u32 p = pool[j] + input[j]; + store32_le(cipher_text, p ^ load32_le(plain_text)); + cipher_text += 4; + plain_text += 4; + } + } else { + WEBFRONT_TLS_MONO_FOR (j, 0, 16) { + u32 p = pool[j] + input[j]; + store32_le(cipher_text, p); + cipher_text += 4; + } + } + input[12]++; + if (input[12] == 0) { + input[13]++; + } + } + text_size &= 63; + + // Last (incomplete) block + if (text_size > 0) { + if (plain_text == 0) { + plain_text = zero; + } + chacha20_rounds(pool, input); + u8 tmp[64]; + WEBFRONT_TLS_MONO_FOR (i, 0, 16) { + store32_le(tmp + i*4, pool[i] + input[i]); + } + WEBFRONT_TLS_MONO_FOR (i, 0, text_size) { + cipher_text[i] = tmp[i] ^ plain_text[i]; + } + WEBFRONT_TLS_MONO_WIPE_BUFFER(tmp); + } + ctr = input[12] + ((u64)input[13] << 32) + (text_size > 0); + + WEBFRONT_TLS_MONO_WIPE_BUFFER(pool); + WEBFRONT_TLS_MONO_WIPE_BUFFER(input); + return ctr; +} + +typedef struct { + // Do not rely on the size or contents of this type, + // for they may change without notice. + uint8_t c[16]; // chunk of the message + size_t c_idx; // How many bytes are there in the chunk. + uint32_t r [4]; // constant multiplier (from the secret key) + uint32_t pad[4]; // random number added at the end (from the secret key) + uint32_t h [5]; // accumulated hash +} crypto_poly1305_ctx; +///////////////// +/// Poly 1305 /// +///////////////// + +// h = (h + c) * r +// preconditions: +// ctx->h <= 4_ffffffff_ffffffff_ffffffff_ffffffff +// ctx->r <= 0ffffffc_0ffffffc_0ffffffc_0fffffff +// end <= 1 +// Postcondition: +// ctx->h <= 4_ffffffff_ffffffff_ffffffff_ffffffff +inline void poly_blocks(crypto_poly1305_ctx *ctx, const u8 *in, + size_t nb_blocks, unsigned end) +{ + // Local all the things! + const u32 r0 = ctx->r[0]; + const u32 r1 = ctx->r[1]; + const u32 r2 = ctx->r[2]; + const u32 r3 = ctx->r[3]; + const u32 rr0 = (r0 >> 2) * 5; // lose 2 bits... + const u32 rr1 = (r1 >> 2) + r1; // rr1 == (r1 >> 2) * 5 + const u32 rr2 = (r2 >> 2) + r2; // rr1 == (r2 >> 2) * 5 + const u32 rr3 = (r3 >> 2) + r3; // rr1 == (r3 >> 2) * 5 + const u32 rr4 = r0 & 3; // ...recover 2 bits + u32 h0 = ctx->h[0]; + u32 h1 = ctx->h[1]; + u32 h2 = ctx->h[2]; + u32 h3 = ctx->h[3]; + u32 h4 = ctx->h[4]; + + WEBFRONT_TLS_MONO_FOR (i, 0, nb_blocks) { + // h + c, without carry propagation + const u64 s0 = (u64)h0 + load32_le(in); in += 4; + const u64 s1 = (u64)h1 + load32_le(in); in += 4; + const u64 s2 = (u64)h2 + load32_le(in); in += 4; + const u64 s3 = (u64)h3 + load32_le(in); in += 4; + const u32 s4 = h4 + end; + + // (h + c) * r, without carry propagation + const u64 x0 = s0*r0+ s1*rr3+ s2*rr2+ s3*rr1+ s4*rr0; + const u64 x1 = s0*r1+ s1*r0 + s2*rr3+ s3*rr2+ s4*rr1; + const u64 x2 = s0*r2+ s1*r1 + s2*r0 + s3*rr3+ s4*rr2; + const u64 x3 = s0*r3+ s1*r2 + s2*r1 + s3*r0 + s4*rr3; + const u32 x4 = s4*rr4; + + // partial reduction modulo 2^130 - 5 + const u32 u5 = x4 + (x3 >> 32); // u5 <= 7ffffff5 + const u64 u0 = (u5 >> 2) * 5 + (x0 & 0xffffffff); + const u64 u1 = (u0 >> 32) + (x1 & 0xffffffff) + (x0 >> 32); + const u64 u2 = (u1 >> 32) + (x2 & 0xffffffff) + (x1 >> 32); + const u64 u3 = (u2 >> 32) + (x3 & 0xffffffff) + (x2 >> 32); + const u32 u4 = (u3 >> 32) + (u5 & 3); // u4 <= 4 + + // Update the hash + h0 = u0 & 0xffffffff; + h1 = u1 & 0xffffffff; + h2 = u2 & 0xffffffff; + h3 = u3 & 0xffffffff; + h4 = u4; + } + ctx->h[0] = h0; + ctx->h[1] = h1; + ctx->h[2] = h2; + ctx->h[3] = h3; + ctx->h[4] = h4; +} + +inline void crypto_poly1305_init(crypto_poly1305_ctx *ctx, const u8 key[32]) +{ + WEBFRONT_TLS_MONO_ZERO(ctx->h, 5); // Initial hash is zero + ctx->c_idx = 0; + // load r and pad (r has some of its bits cleared) + load32_le_buf(ctx->r , key , 4); + load32_le_buf(ctx->pad, key+16, 4); + WEBFRONT_TLS_MONO_FOR (i, 0, 1) { ctx->r[i] &= 0x0fffffff; } + WEBFRONT_TLS_MONO_FOR (i, 1, 4) { ctx->r[i] &= 0x0ffffffc; } +} + +inline void crypto_poly1305_update(crypto_poly1305_ctx *ctx, + const u8 *message, size_t message_size) +{ + // Avoid undefined NULL pointer increments with empty messages + if (message_size == 0) { + return; + } + + // Align ourselves with block boundaries + size_t aligned = WEBFRONT_TLS_MONO_MIN(gap(ctx->c_idx, 16), message_size); + WEBFRONT_TLS_MONO_FOR (i, 0, aligned) { + ctx->c[ctx->c_idx] = *message; + ctx->c_idx++; + message++; + message_size--; + } + + // If block is complete, process it + if (ctx->c_idx == 16) { + poly_blocks(ctx, ctx->c, 1, 1); + ctx->c_idx = 0; + } + + // Process the message block by block + size_t nb_blocks = message_size >> 4; + poly_blocks(ctx, message, nb_blocks, 1); + message += nb_blocks << 4; + message_size &= 15; + + // remaining bytes (we never complete a block here) + WEBFRONT_TLS_MONO_FOR (i, 0, message_size) { + ctx->c[ctx->c_idx] = message[i]; + ctx->c_idx++; + } +} + +inline void crypto_poly1305_final(crypto_poly1305_ctx *ctx, u8 mac[16]) +{ + // Process the last block (if any) + // We move the final 1 according to remaining input length + // (this will add less than 2^130 to the last input block) + if (ctx->c_idx != 0) { + WEBFRONT_TLS_MONO_ZERO(ctx->c + ctx->c_idx, 16 - ctx->c_idx); + ctx->c[ctx->c_idx] = 1; + poly_blocks(ctx, ctx->c, 1, 0); + } + + // check if we should subtract 2^130-5 by performing the + // corresponding carry propagation. + u64 c = 5; + WEBFRONT_TLS_MONO_FOR (i, 0, 4) { + c += ctx->h[i]; + c >>= 32; + } + c += ctx->h[4]; + c = (c >> 2) * 5; // shift the carry back to the beginning + // c now indicates how many times we should subtract 2^130-5 (0 or 1) + WEBFRONT_TLS_MONO_FOR (i, 0, 4) { + c += (u64)ctx->h[i] + ctx->pad[i]; + store32_le(mac + i*4, (u32)c); + c = c >> 32; + } + WEBFRONT_TLS_MONO_WIPE_CTX(ctx); +} + +//////////////////////////////////// +/// Arithmetic modulo 2^255 - 19 /// +//////////////////////////////////// +// Originally taken from SUPERCOP's ref10 implementation. +// A bit bigger than TweetNaCl, over 4 times faster. + +// field element +typedef i32 fe[10]; + +// field constants +// +// fe_one : 1 +// sqrtm1 : sqrt(-1) +// d : -121665 / 121666 +// D2 : 2 * -121665 / 121666 +// lop_x, lop_y: low order point in Edwards coordinates +// ufactor : -sqrt(-1) * 2 +// A2 : 486662^2 (A squared) +inline constexpr fe fe_one = {1}; +inline constexpr fe sqrtm1 = { + -32595792, -7943725, 9377950, 3500415, 12389472, + -272473, -25146209, -2005654, 326686, 11406482, +}; +inline void fe_0(fe h) { WEBFRONT_TLS_MONO_ZERO(h , 10); } +inline void fe_1(fe h) { h[0] = 1; WEBFRONT_TLS_MONO_ZERO(h+1, 9); } + +inline void fe_copy(fe h,const fe f ){WEBFRONT_TLS_MONO_FOR(i,0,10) h[i] = f[i]; } +inline void fe_neg (fe h,const fe f ){WEBFRONT_TLS_MONO_FOR(i,0,10) h[i] = -f[i]; } +inline void fe_add (fe h,const fe f,const fe g){WEBFRONT_TLS_MONO_FOR(i,0,10) h[i] = f[i] + g[i];} +inline void fe_sub (fe h,const fe f,const fe g){WEBFRONT_TLS_MONO_FOR(i,0,10) h[i] = f[i] - g[i];} + +inline void fe_cswap(fe f, fe g, int b) +{ + i32 mask = -b; // -1 = 0xffffffff + WEBFRONT_TLS_MONO_FOR (i, 0, 10) { + i32 x = (f[i] ^ g[i]) & mask; + f[i] = f[i] ^ x; + g[i] = g[i] ^ x; + } +} + +inline void fe_ccopy(fe f, const fe g, int b) +{ + i32 mask = -b; // -1 = 0xffffffff + WEBFRONT_TLS_MONO_FOR (i, 0, 10) { + i32 x = (f[i] ^ g[i]) & mask; + f[i] = f[i] ^ x; + } +} + +// Let t be a number. It can be uniquely decomposed thus: +// +// t = h*2^26 + l +// such that -2^25 <= l < 2^25 +// +// Let c = (t + 2^25) / 2^26 (rounded down) +// c = (h*2^26 + l + 2^25) / 2^26 (rounded down) +// c = h + (l + 2^25) / 2^26 (rounded down) +// c = h (exactly) +// Because 0 <= l + 2^25 < 2^26 +// +// Let u = t - c*2^26 +// u = h*2^26 + l - h*2^26 +// u = l +// Therefore, -2^25 <= u < 2^25 +// +// Additionally, if |t| < x, then |h| < x/2^26 (rounded down) +// +// Notations: +// - In C, 1<<25 means 2^25. +// - In C, x>>25 means floor(x / (2^25)). +// - All of the above applies with 25 & 24 as well as 26 & 25. +// +// +// Note on negative right shifts +// ----------------------------- +// +// In C, x >> n, where x is a negative integer, is implementation +// defined. In practice, all platforms do arithmetic shift, which is +// equivalent to division by 2^26, rounded down. Some compilers, like +// GCC, even guarantee it. +// +// If we ever stumble upon a platform that does not propagate the sign +// bit (we won't), visible failures will show at the slightest test, and +// the signed shifts can be replaced by the following: +// +// typedef struct { i64 x:39; } s25; +// typedef struct { i64 x:38; } s26; +// i64 shift25(i64 x) { s25 s; s.x = ((u64)x)>>25; return s.x; } +// i64 shift26(i64 x) { s26 s; s.x = ((u64)x)>>26; return s.x; } +// +// Current compilers cannot optimise this, causing a 30% drop in +// performance. Fairly expensive for something that never happens. +// +// +// Precondition +// ------------ +// +// |t0| < 2^63 +// |t1|..|t9| < 2^62 +// +// Algorithm +// --------- +// c = t0 + 2^25 / 2^26 -- |c| <= 2^36 +// t0 -= c * 2^26 -- |t0| <= 2^25 +// t1 += c -- |t1| <= 2^63 +// +// c = t4 + 2^25 / 2^26 -- |c| <= 2^36 +// t4 -= c * 2^26 -- |t4| <= 2^25 +// t5 += c -- |t5| <= 2^63 +// +// c = t1 + 2^24 / 2^25 -- |c| <= 2^38 +// t1 -= c * 2^25 -- |t1| <= 2^24 +// t2 += c -- |t2| <= 2^63 +// +// c = t5 + 2^24 / 2^25 -- |c| <= 2^38 +// t5 -= c * 2^25 -- |t5| <= 2^24 +// t6 += c -- |t6| <= 2^63 +// +// c = t2 + 2^25 / 2^26 -- |c| <= 2^37 +// t2 -= c * 2^26 -- |t2| <= 2^25 < 1.1 * 2^25 (final t2) +// t3 += c -- |t3| <= 2^63 +// +// c = t6 + 2^25 / 2^26 -- |c| <= 2^37 +// t6 -= c * 2^26 -- |t6| <= 2^25 < 1.1 * 2^25 (final t6) +// t7 += c -- |t7| <= 2^63 +// +// c = t3 + 2^24 / 2^25 -- |c| <= 2^38 +// t3 -= c * 2^25 -- |t3| <= 2^24 < 1.1 * 2^24 (final t3) +// t4 += c -- |t4| <= 2^25 + 2^38 < 2^39 +// +// c = t7 + 2^24 / 2^25 -- |c| <= 2^38 +// t7 -= c * 2^25 -- |t7| <= 2^24 < 1.1 * 2^24 (final t7) +// t8 += c -- |t8| <= 2^63 +// +// c = t4 + 2^25 / 2^26 -- |c| <= 2^13 +// t4 -= c * 2^26 -- |t4| <= 2^25 < 1.1 * 2^25 (final t4) +// t5 += c -- |t5| <= 2^24 + 2^13 < 1.1 * 2^24 (final t5) +// +// c = t8 + 2^25 / 2^26 -- |c| <= 2^37 +// t8 -= c * 2^26 -- |t8| <= 2^25 < 1.1 * 2^25 (final t8) +// t9 += c -- |t9| <= 2^63 +// +// c = t9 + 2^24 / 2^25 -- |c| <= 2^38 +// t9 -= c * 2^25 -- |t9| <= 2^24 < 1.1 * 2^24 (final t9) +// t0 += c * 19 -- |t0| <= 2^25 + 2^38*19 < 2^44 +// +// c = t0 + 2^25 / 2^26 -- |c| <= 2^18 +// t0 -= c * 2^26 -- |t0| <= 2^25 < 1.1 * 2^25 (final t0) +// t1 += c -- |t1| <= 2^24 + 2^18 < 1.1 * 2^24 (final t1) +// +// Postcondition +// ------------- +// |t0|, |t2|, |t4|, |t6|, |t8| < 1.1 * 2^25 +// |t1|, |t3|, |t5|, |t7|, |t9| < 1.1 * 2^24 +#define WEBFRONT_TLS_MONO_FE_CARRY \ + i64 c; \ + c = (t0 + ((i64)1<<25)) >> 26; t0 -= c * ((i64)1 << 26); t1 += c; \ + c = (t4 + ((i64)1<<25)) >> 26; t4 -= c * ((i64)1 << 26); t5 += c; \ + c = (t1 + ((i64)1<<24)) >> 25; t1 -= c * ((i64)1 << 25); t2 += c; \ + c = (t5 + ((i64)1<<24)) >> 25; t5 -= c * ((i64)1 << 25); t6 += c; \ + c = (t2 + ((i64)1<<25)) >> 26; t2 -= c * ((i64)1 << 26); t3 += c; \ + c = (t6 + ((i64)1<<25)) >> 26; t6 -= c * ((i64)1 << 26); t7 += c; \ + c = (t3 + ((i64)1<<24)) >> 25; t3 -= c * ((i64)1 << 25); t4 += c; \ + c = (t7 + ((i64)1<<24)) >> 25; t7 -= c * ((i64)1 << 25); t8 += c; \ + c = (t4 + ((i64)1<<25)) >> 26; t4 -= c * ((i64)1 << 26); t5 += c; \ + c = (t8 + ((i64)1<<25)) >> 26; t8 -= c * ((i64)1 << 26); t9 += c; \ + c = (t9 + ((i64)1<<24)) >> 25; t9 -= c * ((i64)1 << 25); t0 += c * 19; \ + c = (t0 + ((i64)1<<25)) >> 26; t0 -= c * ((i64)1 << 26); t1 += c; \ + h[0]=(i32)t0; h[1]=(i32)t1; h[2]=(i32)t2; h[3]=(i32)t3; h[4]=(i32)t4; \ + h[5]=(i32)t5; h[6]=(i32)t6; h[7]=(i32)t7; h[8]=(i32)t8; h[9]=(i32)t9 + +// Decodes a field element from a byte buffer. +// mask specifies how many bits we ignore. +// Traditionally we ignore 1. It's useful for EdDSA, +// which uses that bit to denote the sign of x. +// Elligator however uses positive representatives, +// which means ignoring 2 bits instead. +inline void fe_frombytes_mask(fe h, const u8 s[32], unsigned nb_mask) +{ + u32 mask = 0xffffff >> nb_mask; + i64 t0 = load32_le(s); // t0 < 2^32 + i64 t1 = load24_le(s + 4) << 6; // t1 < 2^30 + i64 t2 = load24_le(s + 7) << 5; // t2 < 2^29 + i64 t3 = load24_le(s + 10) << 3; // t3 < 2^27 + i64 t4 = load24_le(s + 13) << 2; // t4 < 2^26 + i64 t5 = load32_le(s + 16); // t5 < 2^32 + i64 t6 = load24_le(s + 20) << 7; // t6 < 2^31 + i64 t7 = load24_le(s + 23) << 5; // t7 < 2^29 + i64 t8 = load24_le(s + 26) << 4; // t8 < 2^28 + i64 t9 = (load24_le(s + 29) & mask) << 2; // t9 < 2^25 + WEBFRONT_TLS_MONO_FE_CARRY; // Carry precondition OK +} + +inline void fe_frombytes(fe h, const u8 s[32]) +{ + fe_frombytes_mask(h, s, 1); +} + + +// Precondition +// |h[0]|, |h[2]|, |h[4]|, |h[6]|, |h[8]| < 1.1 * 2^25 +// |h[1]|, |h[3]|, |h[5]|, |h[7]|, |h[9]| < 1.1 * 2^24 +// +// Therefore, |h| < 2^255-19 +// There are two possibilities: +// +// - If h is positive, all we need to do is reduce its individual +// limbs down to their tight positive range. +// - If h is negative, we also need to add 2^255-19 to it. +// Or just remove 19 and chop off any excess bit. +inline void fe_tobytes(u8 s[32], const fe h) +{ + i32 t[10]; + WEBFRONT_TLS_MONO_COPY(t, h, 10); + i32 q = (19 * t[9] + (((i32) 1) << 24)) >> 25; + // |t9| < 1.1 * 2^24 + // -1.1 * 2^24 < t9 < 1.1 * 2^24 + // -21 * 2^24 < 19 * t9 < 21 * 2^24 + // -2^29 < 19 * t9 + 2^24 < 2^29 + // -2^29 / 2^25 < (19 * t9 + 2^24) / 2^25 < 2^29 / 2^25 + // -16 < (19 * t9 + 2^24) / 2^25 < 16 + WEBFRONT_TLS_MONO_FOR (i, 0, 5) { + q += t[2*i ]; q >>= 26; // q = 0 or -1 + q += t[2*i+1]; q >>= 25; // q = 0 or -1 + } + // q = 0 iff h >= 0 + // q = -1 iff h < 0 + // Adding q * 19 to h reduces h to its proper range. + q *= 19; // Shift carry back to the beginning + WEBFRONT_TLS_MONO_FOR (i, 0, 5) { + t[i*2 ] += q; q = t[i*2 ] >> 26; t[i*2 ] -= q * ((i32)1 << 26); + t[i*2+1] += q; q = t[i*2+1] >> 25; t[i*2+1] -= q * ((i32)1 << 25); + } + // h is now fully reduced, and q represents the excess bit. + + store32_le(s + 0, ((u32)t[0] >> 0) | ((u32)t[1] << 26)); + store32_le(s + 4, ((u32)t[1] >> 6) | ((u32)t[2] << 19)); + store32_le(s + 8, ((u32)t[2] >> 13) | ((u32)t[3] << 13)); + store32_le(s + 12, ((u32)t[3] >> 19) | ((u32)t[4] << 6)); + store32_le(s + 16, ((u32)t[5] >> 0) | ((u32)t[6] << 25)); + store32_le(s + 20, ((u32)t[6] >> 7) | ((u32)t[7] << 19)); + store32_le(s + 24, ((u32)t[7] >> 13) | ((u32)t[8] << 12)); + store32_le(s + 28, ((u32)t[8] >> 20) | ((u32)t[9] << 6)); + + WEBFRONT_TLS_MONO_WIPE_BUFFER(t); +} + +// Precondition +// ------------- +// |f0|, |f2|, |f4|, |f6|, |f8| < 1.65 * 2^26 +// |f1|, |f3|, |f5|, |f7|, |f9| < 1.65 * 2^25 +// +// |g0|, |g2|, |g4|, |g6|, |g8| < 1.65 * 2^26 +// |g1|, |g3|, |g5|, |g7|, |g9| < 1.65 * 2^25 +inline void fe_mul_small(fe h, const fe f, i32 g) +{ + i64 t0 = f[0] * (i64) g; i64 t1 = f[1] * (i64) g; + i64 t2 = f[2] * (i64) g; i64 t3 = f[3] * (i64) g; + i64 t4 = f[4] * (i64) g; i64 t5 = f[5] * (i64) g; + i64 t6 = f[6] * (i64) g; i64 t7 = f[7] * (i64) g; + i64 t8 = f[8] * (i64) g; i64 t9 = f[9] * (i64) g; + // |t0|, |t2|, |t4|, |t6|, |t8| < 1.65 * 2^26 * 2^31 < 2^58 + // |t1|, |t3|, |t5|, |t7|, |t9| < 1.65 * 2^25 * 2^31 < 2^57 + + WEBFRONT_TLS_MONO_FE_CARRY; // Carry precondition OK +} + +inline void fe_mul(fe h, const fe f, const fe g) +{ + // Everything is unrolled and put in temporary variables. + // We could roll the loop, but that would make curve25519 twice as slow. + i32 f0 = f[0]; i32 f1 = f[1]; i32 f2 = f[2]; i32 f3 = f[3]; i32 f4 = f[4]; + i32 f5 = f[5]; i32 f6 = f[6]; i32 f7 = f[7]; i32 f8 = f[8]; i32 f9 = f[9]; + i32 g0 = g[0]; i32 g1 = g[1]; i32 g2 = g[2]; i32 g3 = g[3]; i32 g4 = g[4]; + i32 g5 = g[5]; i32 g6 = g[6]; i32 g7 = g[7]; i32 g8 = g[8]; i32 g9 = g[9]; + i32 F1 = f1*2; i32 F3 = f3*2; i32 F5 = f5*2; i32 F7 = f7*2; i32 F9 = f9*2; + i32 G1 = g1*19; i32 G2 = g2*19; i32 G3 = g3*19; + i32 G4 = g4*19; i32 G5 = g5*19; i32 G6 = g6*19; + i32 G7 = g7*19; i32 G8 = g8*19; i32 G9 = g9*19; + // |F1|, |F3|, |F5|, |F7|, |F9| < 1.65 * 2^26 + // |G0|, |G2|, |G4|, |G6|, |G8| < 2^31 + // |G1|, |G3|, |G5|, |G7|, |G9| < 2^30 + + i64 t0 = f0*(i64)g0 + F1*(i64)G9 + f2*(i64)G8 + F3*(i64)G7 + f4*(i64)G6 + + F5*(i64)G5 + f6*(i64)G4 + F7*(i64)G3 + f8*(i64)G2 + F9*(i64)G1; + i64 t1 = f0*(i64)g1 + f1*(i64)g0 + f2*(i64)G9 + f3*(i64)G8 + f4*(i64)G7 + + f5*(i64)G6 + f6*(i64)G5 + f7*(i64)G4 + f8*(i64)G3 + f9*(i64)G2; + i64 t2 = f0*(i64)g2 + F1*(i64)g1 + f2*(i64)g0 + F3*(i64)G9 + f4*(i64)G8 + + F5*(i64)G7 + f6*(i64)G6 + F7*(i64)G5 + f8*(i64)G4 + F9*(i64)G3; + i64 t3 = f0*(i64)g3 + f1*(i64)g2 + f2*(i64)g1 + f3*(i64)g0 + f4*(i64)G9 + + f5*(i64)G8 + f6*(i64)G7 + f7*(i64)G6 + f8*(i64)G5 + f9*(i64)G4; + i64 t4 = f0*(i64)g4 + F1*(i64)g3 + f2*(i64)g2 + F3*(i64)g1 + f4*(i64)g0 + + F5*(i64)G9 + f6*(i64)G8 + F7*(i64)G7 + f8*(i64)G6 + F9*(i64)G5; + i64 t5 = f0*(i64)g5 + f1*(i64)g4 + f2*(i64)g3 + f3*(i64)g2 + f4*(i64)g1 + + f5*(i64)g0 + f6*(i64)G9 + f7*(i64)G8 + f8*(i64)G7 + f9*(i64)G6; + i64 t6 = f0*(i64)g6 + F1*(i64)g5 + f2*(i64)g4 + F3*(i64)g3 + f4*(i64)g2 + + F5*(i64)g1 + f6*(i64)g0 + F7*(i64)G9 + f8*(i64)G8 + F9*(i64)G7; + i64 t7 = f0*(i64)g7 + f1*(i64)g6 + f2*(i64)g5 + f3*(i64)g4 + f4*(i64)g3 + + f5*(i64)g2 + f6*(i64)g1 + f7*(i64)g0 + f8*(i64)G9 + f9*(i64)G8; + i64 t8 = f0*(i64)g8 + F1*(i64)g7 + f2*(i64)g6 + F3*(i64)g5 + f4*(i64)g4 + + F5*(i64)g3 + f6*(i64)g2 + F7*(i64)g1 + f8*(i64)g0 + F9*(i64)G9; + i64 t9 = f0*(i64)g9 + f1*(i64)g8 + f2*(i64)g7 + f3*(i64)g6 + f4*(i64)g5 + + f5*(i64)g4 + f6*(i64)g3 + f7*(i64)g2 + f8*(i64)g1 + f9*(i64)g0; + // t0 < 0.67 * 2^61 + // t1 < 0.41 * 2^61 + // t2 < 0.52 * 2^61 + // t3 < 0.32 * 2^61 + // t4 < 0.38 * 2^61 + // t5 < 0.22 * 2^61 + // t6 < 0.23 * 2^61 + // t7 < 0.13 * 2^61 + // t8 < 0.09 * 2^61 + // t9 < 0.03 * 2^61 + + WEBFRONT_TLS_MONO_FE_CARRY; // Everything below 2^62, Carry precondition OK +} + +inline void fe_sq(fe h, const fe f) +{ + i32 f0 = f[0]; i32 f1 = f[1]; i32 f2 = f[2]; i32 f3 = f[3]; i32 f4 = f[4]; + i32 f5 = f[5]; i32 f6 = f[6]; i32 f7 = f[7]; i32 f8 = f[8]; i32 f9 = f[9]; + i32 f0_2 = f0*2; i32 f1_2 = f1*2; i32 f2_2 = f2*2; i32 f3_2 = f3*2; + i32 f4_2 = f4*2; i32 f5_2 = f5*2; i32 f6_2 = f6*2; i32 f7_2 = f7*2; + i32 f5_38 = f5*38; i32 f6_19 = f6*19; i32 f7_38 = f7*38; + i32 f8_19 = f8*19; i32 f9_38 = f9*38; + // |f0_2| , |f2_2| , |f4_2| , |f6_2| , |f8_2| < 1.65 * 2^27 + // |f1_2| , |f3_2| , |f5_2| , |f7_2| , |f9_2| < 1.65 * 2^26 + // |f5_38|, |f6_19|, |f7_38|, |f8_19|, |f9_38| < 2^31 + + i64 t0 = f0 *(i64)f0 + f1_2*(i64)f9_38 + f2_2*(i64)f8_19 + + f3_2*(i64)f7_38 + f4_2*(i64)f6_19 + f5 *(i64)f5_38; + i64 t1 = f0_2*(i64)f1 + f2 *(i64)f9_38 + f3_2*(i64)f8_19 + + f4 *(i64)f7_38 + f5_2*(i64)f6_19; + i64 t2 = f0_2*(i64)f2 + f1_2*(i64)f1 + f3_2*(i64)f9_38 + + f4_2*(i64)f8_19 + f5_2*(i64)f7_38 + f6 *(i64)f6_19; + i64 t3 = f0_2*(i64)f3 + f1_2*(i64)f2 + f4 *(i64)f9_38 + + f5_2*(i64)f8_19 + f6 *(i64)f7_38; + i64 t4 = f0_2*(i64)f4 + f1_2*(i64)f3_2 + f2 *(i64)f2 + + f5_2*(i64)f9_38 + f6_2*(i64)f8_19 + f7 *(i64)f7_38; + i64 t5 = f0_2*(i64)f5 + f1_2*(i64)f4 + f2_2*(i64)f3 + + f6 *(i64)f9_38 + f7_2*(i64)f8_19; + i64 t6 = f0_2*(i64)f6 + f1_2*(i64)f5_2 + f2_2*(i64)f4 + + f3_2*(i64)f3 + f7_2*(i64)f9_38 + f8 *(i64)f8_19; + i64 t7 = f0_2*(i64)f7 + f1_2*(i64)f6 + f2_2*(i64)f5 + + f3_2*(i64)f4 + f8 *(i64)f9_38; + i64 t8 = f0_2*(i64)f8 + f1_2*(i64)f7_2 + f2_2*(i64)f6 + + f3_2*(i64)f5_2 + f4 *(i64)f4 + f9 *(i64)f9_38; + i64 t9 = f0_2*(i64)f9 + f1_2*(i64)f8 + f2_2*(i64)f7 + + f3_2*(i64)f6 + f4 *(i64)f5_2; + // t0 < 0.67 * 2^61 + // t1 < 0.41 * 2^61 + // t2 < 0.52 * 2^61 + // t3 < 0.32 * 2^61 + // t4 < 0.38 * 2^61 + // t5 < 0.22 * 2^61 + // t6 < 0.23 * 2^61 + // t7 < 0.13 * 2^61 + // t8 < 0.09 * 2^61 + // t9 < 0.03 * 2^61 + + WEBFRONT_TLS_MONO_FE_CARRY; +} + +inline int fe_isequal(const fe f, const fe g) +{ + u8 fs[32]; + u8 gs[32]; + fe_tobytes(fs, f); + fe_tobytes(gs, g); + int isdifferent = crypto_verify32(fs, gs); + WEBFRONT_TLS_MONO_WIPE_BUFFER(fs); + WEBFRONT_TLS_MONO_WIPE_BUFFER(gs); + return 1 + isdifferent; +} + +inline int invsqrt(fe isr, const fe x) +{ + fe t0, t1, t2; + + // t0 = x^((p-5)/8) + // Can be achieved with a simple double & add ladder, + // but it would be slower. + fe_sq(t0, x); + fe_sq(t1,t0); fe_sq(t1, t1); fe_mul(t1, x, t1); + fe_mul(t0, t0, t1); + fe_sq(t0, t0); fe_mul(t0, t1, t0); + fe_sq(t1, t0); WEBFRONT_TLS_MONO_FOR (i, 1, 5) { fe_sq(t1, t1); } fe_mul(t0, t1, t0); + fe_sq(t1, t0); WEBFRONT_TLS_MONO_FOR (i, 1, 10) { fe_sq(t1, t1); } fe_mul(t1, t1, t0); + fe_sq(t2, t1); WEBFRONT_TLS_MONO_FOR (i, 1, 20) { fe_sq(t2, t2); } fe_mul(t1, t2, t1); + fe_sq(t1, t1); WEBFRONT_TLS_MONO_FOR (i, 1, 10) { fe_sq(t1, t1); } fe_mul(t0, t1, t0); + fe_sq(t1, t0); WEBFRONT_TLS_MONO_FOR (i, 1, 50) { fe_sq(t1, t1); } fe_mul(t1, t1, t0); + fe_sq(t2, t1); WEBFRONT_TLS_MONO_FOR (i, 1, 100) { fe_sq(t2, t2); } fe_mul(t1, t2, t1); + fe_sq(t1, t1); WEBFRONT_TLS_MONO_FOR (i, 1, 50) { fe_sq(t1, t1); } fe_mul(t0, t1, t0); + fe_sq(t0, t0); WEBFRONT_TLS_MONO_FOR (i, 1, 2) { fe_sq(t0, t0); } fe_mul(t0, t0, x); + + // quartic = x^((p-1)/4) + i32 *quartic = t1; + fe_sq (quartic, t0); + fe_mul(quartic, quartic, x); + + i32 *check = t2; + fe_0 (check); int z0 = fe_isequal(x , check); + fe_1 (check); int p1 = fe_isequal(quartic, check); + fe_neg(check, check ); int m1 = fe_isequal(quartic, check); + fe_neg(check, sqrtm1); int ms = fe_isequal(quartic, check); + + // if quartic == -1 or sqrt(-1) + // then isr = x^((p-1)/4) * sqrt(-1) + // else isr = x^((p-1)/4) + fe_mul(isr, t0, sqrtm1); + fe_ccopy(isr, t0, 1 - (m1 | ms)); + + WEBFRONT_TLS_MONO_WIPE_BUFFER(t0); + WEBFRONT_TLS_MONO_WIPE_BUFFER(t1); + WEBFRONT_TLS_MONO_WIPE_BUFFER(t2); + return p1 | m1 | z0; +} + +inline void fe_invert(fe out, const fe x) +{ + fe tmp; + fe_sq(tmp, x); + invsqrt(tmp, tmp); + fe_sq(tmp, tmp); + fe_mul(out, tmp, x); + WEBFRONT_TLS_MONO_WIPE_BUFFER(tmp); +} + +inline void crypto_eddsa_trim_scalar(u8 out[32], const u8 in[32]) +{ + WEBFRONT_TLS_MONO_COPY(out, in, 32); + out[ 0] &= 248; + out[31] &= 127; + out[31] |= 64; +} + +inline int scalar_bit(const u8 s[32], int i) +{ + if (i < 0) { return 0; } // handle -1 for sliding windows + return (s[i>>3] >> (i&7)) & 1; +} + +inline void scalarmult(u8 q[32], const u8 scalar[32], const u8 p[32], + int nb_bits) +{ + // computes the scalar product + fe x1; + fe_frombytes(x1, p); + + // computes the actual scalar product (the result is in x2 and z2) + fe x2, z2, x3, z3, t0, t1; + // Montgomery ladder + // In projective coordinates, to avoid divisions: x = X / Z + // We don't care about the y coordinate, it's only 1 bit of information + fe_1(x2); fe_0(z2); // "zero" point + fe_copy(x3, x1); fe_1(z3); // "one" point + int swap = 0; + for (int pos = nb_bits-1; pos >= 0; --pos) { + // constant time conditional swap before ladder step + int b = scalar_bit(scalar, pos); + swap ^= b; // xor trick avoids swapping at the end of the loop + fe_cswap(x2, x3, swap); + fe_cswap(z2, z3, swap); + swap = b; // anticipates one last swap after the loop + + // Montgomery ladder step: replaces (P2, P3) by (P2*2, P2+P3) + // with differential addition + fe_sub(t0, x3, z3); + fe_sub(t1, x2, z2); + fe_add(x2, x2, z2); + fe_add(z2, x3, z3); + fe_mul(z3, t0, x2); + fe_mul(z2, z2, t1); + fe_sq (t0, t1 ); + fe_sq (t1, x2 ); + fe_add(x3, z3, z2); + fe_sub(z2, z3, z2); + fe_mul(x2, t1, t0); + fe_sub(t1, t1, t0); + fe_sq (z2, z2 ); + fe_mul_small(z3, t1, 121666); + fe_sq (x3, x3 ); + fe_add(t0, t0, z3); + fe_mul(z3, x1, z2); + fe_mul(z2, t1, t0); + } + // last swap is necessary to compensate for the xor trick + // Note: after this swap, P3 == P2 + P1. + fe_cswap(x2, x3, swap); + fe_cswap(z2, z3, swap); + + // normalises the coordinates: x == X / Z + fe_invert(z2, z2); + fe_mul(x2, x2, z2); + fe_tobytes(q, x2); + + WEBFRONT_TLS_MONO_WIPE_BUFFER(x1); + WEBFRONT_TLS_MONO_WIPE_BUFFER(x2); WEBFRONT_TLS_MONO_WIPE_BUFFER(z2); WEBFRONT_TLS_MONO_WIPE_BUFFER(t0); + WEBFRONT_TLS_MONO_WIPE_BUFFER(x3); WEBFRONT_TLS_MONO_WIPE_BUFFER(z3); WEBFRONT_TLS_MONO_WIPE_BUFFER(t1); +} + +inline void crypto_x25519(u8 raw_shared_secret[32], + const u8 your_secret_key [32], + const u8 their_public_key [32]) +{ + // restrict the possible scalar values + u8 e[32]; + crypto_eddsa_trim_scalar(e, your_secret_key); + scalarmult(raw_shared_secret, e, their_public_key, 255); + WEBFRONT_TLS_MONO_WIPE_BUFFER(e); +} + +inline void crypto_x25519_public_key(u8 public_key[32], + const u8 secret_key[32]) +{ + static const u8 base_point[32] = {9}; + crypto_x25519(public_key, secret_key, base_point); +} + +typedef struct { + uint64_t counter; + uint8_t key[32]; + uint8_t nonce[8]; +} crypto_aead_ctx; +inline void lock_auth(u8 mac[16], const u8 auth_key[32], + const u8 *ad , size_t ad_size, + const u8 *cipher_text, size_t text_size) +{ + u8 sizes[16]; // Not secret, not wiped + store64_le(sizes + 0, ad_size); + store64_le(sizes + 8, text_size); + crypto_poly1305_ctx poly_ctx; // auto wiped... + crypto_poly1305_init (&poly_ctx, auth_key); + crypto_poly1305_update(&poly_ctx, ad , ad_size); + crypto_poly1305_update(&poly_ctx, zero , gap(ad_size, 16)); + crypto_poly1305_update(&poly_ctx, cipher_text, text_size); + crypto_poly1305_update(&poly_ctx, zero , gap(text_size, 16)); + crypto_poly1305_update(&poly_ctx, sizes , 16); + crypto_poly1305_final (&poly_ctx, mac); // ...here +} + +inline void crypto_aead_init_ietf(crypto_aead_ctx *ctx, + const u8 key[32], const u8 nonce[12]) +{ + WEBFRONT_TLS_MONO_COPY(ctx->key , key , 32); + WEBFRONT_TLS_MONO_COPY(ctx->nonce, nonce + 4, 8); + ctx->counter = (u64)load32_le(nonce) << 32; +} + +inline void crypto_aead_write(crypto_aead_ctx *ctx, u8 *cipher_text, u8 mac[16], + const u8 *ad, size_t ad_size, + const u8 *plain_text, size_t text_size) +{ + u8 auth_key[64]; // the last 32 bytes are used for rekeying. + crypto_chacha20_djb(auth_key, 0, 64, ctx->key, ctx->nonce, ctx->counter); + crypto_chacha20_djb(cipher_text, plain_text, text_size, + ctx->key, ctx->nonce, ctx->counter + 1); + lock_auth(mac, auth_key, ad, ad_size, cipher_text, text_size); + WEBFRONT_TLS_MONO_COPY(ctx->key, auth_key + 32, 32); + WEBFRONT_TLS_MONO_WIPE_BUFFER(auth_key); +} + +inline int crypto_aead_read(crypto_aead_ctx *ctx, u8 *plain_text, const u8 mac[16], + const u8 *ad, size_t ad_size, + const u8 *cipher_text, size_t text_size) +{ + u8 auth_key[64]; // the last 32 bytes are used for rekeying. + u8 real_mac[16]; + crypto_chacha20_djb(auth_key, 0, 64, ctx->key, ctx->nonce, ctx->counter); + lock_auth(real_mac, auth_key, ad, ad_size, cipher_text, text_size); + int mismatch = crypto_verify16(mac, real_mac); + if (!mismatch) { + crypto_chacha20_djb(plain_text, cipher_text, text_size, + ctx->key, ctx->nonce, ctx->counter + 1); + WEBFRONT_TLS_MONO_COPY(ctx->key, auth_key + 32, 32); + } + WEBFRONT_TLS_MONO_WIPE_BUFFER(auth_key); + WEBFRONT_TLS_MONO_WIPE_BUFFER(real_mac); + return mismatch; +} + + +#undef WEBFRONT_TLS_MONO_FOR_T +#undef WEBFRONT_TLS_MONO_FOR +#undef WEBFRONT_TLS_MONO_COPY +#undef WEBFRONT_TLS_MONO_ZERO +#undef WEBFRONT_TLS_MONO_WIPE_CTX +#undef WEBFRONT_TLS_MONO_WIPE_BUFFER +#undef WEBFRONT_TLS_MONO_MIN +#undef WEBFRONT_TLS_MONO_MAX +#undef WEBFRONT_TLS_MONO_QUARTERROUND +#undef WEBFRONT_TLS_MONO_FE_CARRY +} +#if defined(_MSC_VER) && !defined(__GNUC__) +#pragma warning(pop) +#endif diff --git a/include/webfront/tls/detail/P256.hpp b/include/webfront/tls/detail/P256.hpp new file mode 100644 index 00000000..68f1aaef --- /dev/null +++ b/include/webfront/tls/detail/P256.hpp @@ -0,0 +1,803 @@ +/* + * Implementation of curve P-256 (ECDH and ECDSA) + * + * Author: Manuel Pégourié-Gonnard. + * SPDX-License-Identifier: Apache-2.0 + * License text is in the repository LICENSE. + */ +// Subset of p256-m (44af59e0cff5d3b1d653bc333814077ef830e1bd). +#pragma once +#if defined(__GNUC__) +#pragma GCC system_header +#elif defined(_MSC_VER) +#pragma warning(push, 0) +#endif +#include +#include +namespace webfront::tls::detail::p256 { +using std::size_t; +using std::uint8_t; +using std::uint16_t; +using std::uint32_t; +using std::uint64_t; +inline void zeroize(void *d, size_t n) +{ + volatile char *p = static_cast(d); + while( n-- ) + *p++ = 0; +} + + +/********************************************************************** + * + * Operations on fixed-width unsigned integers + * + * Represented using 32-bit limbs, least significant limb first. + * That is: x = x[0] + 2^32 x[1] + ... + 2^224 x[7] for 256-bit. + * + **********************************************************************/ + +/* + * 256-bit set to 32-bit value + * + * in: x in [0, 2^32) + * out: z = x + */ +inline void u256_set32(uint32_t z[8], uint32_t x) +{ + z[0] = x; + for (unsigned i = 1; i < 8; i++) { + z[i] = 0; + } +} + +/* + * 256-bit addition + * + * in: x, y in [0, 2^256) + * out: z = (x + y) mod 2^256 + * c = (x + y) div 2^256 + * That is, z + c * 2^256 = x + y + * + * Note: as a memory area, z must be either equal to x or y, or not overlap. + */ +inline uint32_t u256_add(uint32_t z[8], + const uint32_t x[8], const uint32_t y[8]) +{ + uint32_t carry = 0; + + for (unsigned i = 0; i < 8; i++) { + uint64_t sum = (uint64_t) carry + x[i] + y[i]; + z[i] = (uint32_t) sum; + carry = (uint32_t) (sum >> 32); + } + + return carry; +} + +/* + * 256-bit subtraction + * + * in: x, y in [0, 2^256) + * out: z = (x - y) mod 2^256 + * c = 0 if x >=y, 1 otherwise + * That is, z = c * 2^256 + x - y + * + * Note: as a memory area, z must be either equal to x or y, or not overlap. + */ +inline uint32_t u256_sub(uint32_t z[8], + const uint32_t x[8], const uint32_t y[8]) +{ + uint32_t carry = 0; + + for (unsigned i = 0; i < 8; i++) { + uint64_t diff = (uint64_t) x[i] - y[i] - carry; + z[i] = (uint32_t) diff; + carry = -(uint32_t) (diff >> 32); + } + + return carry; +} + +/* + * 256-bit conditional assignment + * + * in: x in [0, 2^256) + * c in [0, 1] + * out: z = x if c == 1, z unchanged otherwise + * + * Note: as a memory area, z must be either equal to x, or not overlap. + */ +inline void u256_cmov(uint32_t z[8], const uint32_t x[8], uint32_t c) +{ + const uint32_t x_mask = -c; + for (unsigned i = 0; i < 8; i++) { + z[i] = (z[i] & ~x_mask) | (x[i] & x_mask); + } +} + +/* + * 256-bit compare for equality + * + * in: x in [0, 2^256) + * y in [0, 2^256) + * out: 0 if x == y, unspecified non-zero otherwise + */ +inline uint32_t u256_diff0(const uint32_t x[8]) +{ + uint32_t diff = 0; + for (unsigned i = 0; i < 8; i++) { + diff |= x[i]; + } + return diff; +} + +inline uint64_t u32_muladd64(uint32_t x, uint32_t y, uint32_t z, uint32_t t) +{ + /* x = xl + 2**16 xh, y = yl + 2**16 yh */ + const uint16_t xl = (uint16_t) x; + const uint16_t yl = (uint16_t) y; + const uint16_t xh = x >> 16; + const uint16_t yh = y >> 16; + + /* x*y = xl*yl + 2**16 (xh*yl + yl*yh) + 2**32 xh*yh + * = lo + 2**16 (m1 + m2 ) + 2**32 hi */ + const uint32_t lo = (uint32_t) xl * yl; + const uint32_t m1 = (uint32_t) xh * yl; + const uint32_t m2 = (uint32_t) xl * yh; + const uint32_t hi = (uint32_t) xh * yh; + + uint64_t acc = lo + ((uint64_t) (hi + (m1 >> 16) + (m2 >> 16)) << 32); + acc += m1 << 16; + acc += m2 << 16; + acc += z; + acc += t; + + return acc; +} +inline uint32_t u288_muladd(uint32_t z[9], uint32_t x, const uint32_t y[8]) +{ + uint32_t carry = 0; + + for (unsigned i = 0; i < 8; i++) { + const uint64_t prod = u32_muladd64(x, y[i], z[i], carry); + z[i] = static_cast(prod); + carry = static_cast(prod >> 32); + } + + uint64_t sum = (uint64_t) z[8] + carry; + z[8] = (uint32_t) sum; + carry = (uint32_t) (sum >> 32); + + return carry; +} + +/* + * 288-bit in-place right shift by 32 bits + * + * in: z in [0, 2^288) + * c in [0, 2^32) + * out: z_out = z_in div 2^32 + c * 2^256 + * = (z_in + c * 2^288) div 2^32 + * + * This is a helper for Montgomery multiplication. + */ +inline void u288_rshift32(uint32_t z[9], uint32_t c) +{ + for (unsigned i = 0; i < 8; i++) { + z[i] = z[i + 1]; + } + z[8] = c; +} + +/* + * 256-bit import from big-endian bytes + * + * in: p = p0, ..., p31 + * out: z = p0 * 2^248 + p1 * 2^240 + ... + p30 * 2^8 + p31 + */ +inline void u256_from_bytes(uint32_t z[8], const uint8_t p[32]) +{ + for (unsigned i = 0; i < 8; i++) { + unsigned j = 4 * (7 - i); + z[i] = ((uint32_t) p[j + 0] << 24) | + ((uint32_t) p[j + 1] << 16) | + ((uint32_t) p[j + 2] << 8) | + ((uint32_t) p[j + 3] << 0); + } +} + +/* + * 256-bit export to big-endian bytes + * + * in: z in [0, 2^256) + * out: p = p0, ..., p31 such that + * z = p0 * 2^248 + p1 * 2^240 + ... + p30 * 2^8 + p31 + */ +inline void u256_to_bytes(uint8_t p[32], const uint32_t z[8]) +{ + for (unsigned i = 0; i < 8; i++) { + unsigned j = 4 * (7 - i); + p[j + 0] = (uint8_t) (z[i] >> 24); + p[j + 1] = (uint8_t) (z[i] >> 16); + p[j + 2] = (uint8_t) (z[i] >> 8); + p[j + 3] = (uint8_t) (z[i] >> 0); + } +} + +/********************************************************************** + * + * Operations modulo a 256-bit prime m + * + * These are done in the Montgomery domain, that is x is represented by + * x * 2^256 mod m + * Numbers need to be converted to that domain before computations, + * and back from it afterwards. + * + * Inversion is computed using Fermat's little theorem. + * + * Assumptions on m: + * - Montgomery operations require that m is odd. + * - Fermat's little theorem require it to be a prime. + * - m256_inv() further requires that m % 2^32 >= 2. + * - m256_inv() also assumes that the value of m is not a secret. + * + * In practice operations are done modulo the curve's p and n, + * both of which satisfy those assumptions. + * + **********************************************************************/ + +/* + * Data associated to a modulus for Montgomery operations. + * + * m in [0, 2^256) - the modulus itself, must be odd + * R2 = 2^512 mod m + * ni = -m^-1 mod 2^32 + */ +typedef struct { + uint32_t m[8]; + uint32_t R2[8]; + uint32_t ni; +} +m256_mod; + +/* + * Data for Montgomery operations modulo the curve's p + */ +inline constexpr m256_mod p256_p = { + { /* the curve's p */ + 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, + 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF, + }, + { /* 2^512 mod p */ + 0x00000003, 0x00000000, 0xffffffff, 0xfffffffb, + 0xfffffffe, 0xffffffff, 0xfffffffd, 0x00000004, + }, + 0x00000001, /* -p^-1 mod 2^32 */ +}; + +/* + * Data for Montgomery operations modulo the curve's n + */ +inline constexpr m256_mod p256_n = { + { /* the curve's n */ + 0xFC632551, 0xF3B9CAC2, 0xA7179E84, 0xBCE6FAAD, + 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, + }, + { /* 2^512 mod n */ + 0xbe79eea2, 0x83244c95, 0x49bd6fa6, 0x4699799c, + 0x2b6bec59, 0x2845b239, 0xf3d95620, 0x66e12d94, + }, + 0xee00bc4f, /* -n^-1 mod 2^32 */ +}; + +/* + * Modular addition + * + * in: x, y in [0, m) + * mod must point to a valid m256_mod structure + * out: z = (x + y) mod m, in [0, m) + * + * Note: as a memory area, z must be either equal to x or y, or not overlap. + */ +inline void m256_add(uint32_t z[8], + const uint32_t x[8], const uint32_t y[8], + const m256_mod *mod) +{ + uint32_t r[8]; + uint32_t carry_add = u256_add(z, x, y); + uint32_t carry_sub = u256_sub(r, z, mod->m); + /* Need to subract m if: + * x+y >= 2^256 > m (that is, carry_add == 1) + * OR z >= m (that is, carry_sub == 0) */ + uint32_t use_sub = carry_add | (1 - carry_sub); + u256_cmov(z, r, use_sub); +} + +/* + * Modular addition mod p + * + * in: x, y in [0, p) + * out: z = (x + y) mod p, in [0, p) + * + * Note: as a memory area, z must be either equal to x or y, or not overlap. + */ +inline void m256_add_p(uint32_t z[8], + const uint32_t x[8], const uint32_t y[8]) +{ + m256_add(z, x, y, &p256_p); +} + +/* + * Modular subtraction + * + * in: x, y in [0, m) + * mod must point to a valid m256_mod structure + * out: z = (x - y) mod m, in [0, m) + * + * Note: as a memory area, z must be either equal to x or y, or not overlap. + */ +inline void m256_sub(uint32_t z[8], + const uint32_t x[8], const uint32_t y[8], + const m256_mod *mod) +{ + uint32_t r[8]; + uint32_t carry = u256_sub(z, x, y); + (void) u256_add(r, z, mod->m); + /* Need to add m if and only if x < y, that is carry == 1. + * In that case z is in [2^256 - m + 1, 2^256 - 1], so the + * addition will have a carry as well, which cancels out. */ + u256_cmov(z, r, carry); +} + +/* + * Modular subtraction mod p + * + * in: x, y in [0, p) + * out: z = (x + y) mod p, in [0, p) + * + * Note: as a memory area, z must be either equal to x or y, or not overlap. + */ +inline void m256_sub_p(uint32_t z[8], + const uint32_t x[8], const uint32_t y[8]) +{ + m256_sub(z, x, y, &p256_p); +} + +/* + * Montgomery modular multiplication + * + * in: x, y in [0, m) + * mod must point to a valid m256_mod structure + * out: z = (x * y) / 2^256 mod m, in [0, m) + * + * Note: as a memory area, z may overlap with x or y. + */ +inline void m256_mul(uint32_t z[8], + const uint32_t x[8], const uint32_t y[8], + const m256_mod *mod) +{ + /* + * Algorithm 14.36 in Handbook of Applied Cryptography with: + * b = 2^32, n = 8, R = 2^256 + */ + uint32_t m_prime = mod->ni; + uint32_t a[9]; + + for (unsigned i = 0; i < 9; i++) { + a[i] = 0; + } + + for (unsigned i = 0; i < 8; i++) { + /* the "mod 2^32" is implicit from the type */ + uint32_t u = (a[0] + x[i] * y[0]) * m_prime; + + /* a = (a + x[i] * y + u * m) div b */ + uint32_t c = u288_muladd(a, x[i], y); + c += u288_muladd(a, u, mod->m); + u288_rshift32(a, c); + } + + /* a = a > m ? a - m : a */ + uint32_t carry_add = a[8]; // 0 or 1 since a < 2m, see HAC Note 14.37 + uint32_t carry_sub = u256_sub(z, a, mod->m); + uint32_t use_sub = carry_add | (1 - carry_sub); // see m256_add() + u256_cmov(z, a, 1 - use_sub); +} + +/* + * Montgomery modular multiplication modulo p. + * + * in: x, y in [0, p) + * out: z = (x * y) / 2^256 mod p, in [0, p) + * + * Note: as a memory area, z may overlap with x or y. + */ +inline void m256_mul_p(uint32_t z[8], + const uint32_t x[8], const uint32_t y[8]) +{ + m256_mul(z, x, y, &p256_p); +} + +/* + * In-place conversion to Montgomery form + * + * in: z in [0, m) + * mod must point to a valid m256_mod structure + * out: z_out = z_in * 2^256 mod m, in [0, m) + */ +inline void m256_prep(uint32_t z[8], const m256_mod *mod) +{ + m256_mul(z, z, mod->R2, mod); +} + +/* + * In-place conversion from Montgomery form + * + * in: z in [0, m) + * mod must point to a valid m256_mod structure + * out: z_out = z_in / 2^256 mod m, in [0, m) + * That is, z_in was z_actual * 2^256 mod m, and z_out is z_actual + */ +inline void m256_done(uint32_t z[8], const m256_mod *mod) +{ + uint32_t one[8]; + u256_set32(one, 1); + m256_mul(z, z, one, mod); +} + +/* + * Set to 32-bit value + * + * in: x in [0, 2^32) + * mod must point to a valid m256_mod structure + * out: z = x * 2^256 mod m, in [0, m) + * That is, z is set to the image of x in the Montgomery domain. + */ +inline void m256_set32(uint32_t z[8], uint32_t x, const m256_mod *mod) +{ + u256_set32(z, x); + m256_prep(z, mod); +} + +/* + * Modular inversion in Montgomery form + * + * in: x in [0, m) + * mod must point to a valid m256_mod structure + * such that mod->m % 2^32 >= 2, assumed to be public. + * out: z = x^-1 * 2^512 mod m if x != 0, + * z = 0 if x == 0 + * That is, if x = x_actual * 2^256 mod m, then + * z = x_actual^-1 * 2^256 mod m + * + * Note: as a memory area, z may overlap with x. + */ +inline void m256_inv(uint32_t z[8], const uint32_t x[8], + const m256_mod *mod) +{ + /* + * Use Fermat's little theorem to compute x^-1 as x^(m-2). + * + * Take advantage of the fact that both p's and n's least significant limb + * is at least 2 to perform the subtraction on the flight (no carry). + * + * Use plain right-to-left binary exponentiation; + * branches are OK as the exponent is not a secret. + */ + uint32_t bitval[8]; + u256_cmov(bitval, x, 1); /* copy x before writing to z */ + + m256_set32(z, 1, mod); + + unsigned i = 0; + uint32_t limb = mod->m[i] - 2; + while (1) { + for (unsigned j = 0; j < 32; j++) { + if ((limb & 1) != 0) { + m256_mul(z, z, bitval, mod); + } + m256_mul(bitval, bitval, bitval, mod); + limb >>= 1; + } + + if (i == 7) + break; + + i++; + limb = mod->m[i]; + } +} + +/* + * Import modular integer from bytes to Montgomery domain + * + * in: p = p0, ..., p32 + * mod must point to a valid m256_mod structure + * out: z = (p0 * 2^248 + ... + p31) * 2^256 mod m, in [0, m) + * return 0 if the number was already in [0, m), or -1. + * z may be incorrect and must be discared when -1 is returned. + */ +inline int m256_from_bytes(uint32_t z[8], + const uint8_t p[32], const m256_mod *mod) +{ + u256_from_bytes(z, p); + + uint32_t t[8]; + uint32_t lt_m = u256_sub(t, z, mod->m); + if (lt_m != 1) + return -1; + + m256_prep(z, mod); + return 0; +} + +/* + * Export modular integer from Montgomery domain to bytes + * + * in: z in [0, 2^256) + * mod must point to a valid m256_mod structure + * out: p = p0, ..., p31 such that + * z = (p0 * 2^248 + ... + p31) * 2^256 mod m + */ +inline void m256_to_bytes(uint8_t p[32], + const uint32_t z[8], const m256_mod *mod) +{ + uint32_t zi[8]; + u256_cmov(zi, z, 1); + m256_done(zi, mod); + + u256_to_bytes(p, zi); +} + +/********************************************************************** + * + * Operations on curve points + * + * Points are represented in two coordinates system: + * - affine (x, y) - extended to represent 0 (see below) + * - jacobian (x:y:z) + * In either case, coordinates are integers modulo p256_p and + * are always represented in the Montgomery domain. + * + * For background on jacobian coordinates, see for example [GECC] 3.2.2: + * - conversions go (x, y) -> (x:y:1) and (x:y:z) -> (x/z^2, y/z^3) + * - the curve equation becomes y^2 = x^3 - 3 x z^4 + b z^6 + * - 0 (aka the origin aka point at infinity) is (x:y:0) with y^2 = x^3. + * - point negation goes -(x:y:z) = (x:-y:z) + * + * Normally 0 (the point at infinity) can't be represented in affine + * coordinates. However we extend affine coordinates with the convention that + * (0, 0) (which is normally not a point on the curve) is interpreted as 0. + * + * References: + * - [GECC]: Guide to Elliptic Curve Cryptography; Hankerson, Menezes, + * Vanstone; Springer, 2004. + * - [CMO98]: Efficient Elliptic Curve Exponentiation Using Mixed Coordinates; + * Cohen, Miyaji, Ono; Springer, ASIACRYPT 1998. + * https://link.springer.com/content/pdf/10.1007/3-540-49649-1_6.pdf + * - [RCB15]: Complete addition formulas for prime order elliptic curves; + * Renes, Costello, Batina; IACR e-print 2015-1060. + * https://eprint.iacr.org/2015/1060.pdf + * + **********************************************************************/ + +/* + * The curve's b parameter in the Short Weierstrass equation + * y^2 = x^3 - 3*x + b + * Compared to the standard, this is converted to the Montgomery domain. + */ +inline constexpr uint32_t p256_gx[8] = { /* G_x * 2^256 mod p */ + 0x18a9143c, 0x79e730d4, 0x5fedb601, 0x75ba95fc, + 0x77622510, 0x79fb732b, 0xa53755c6, 0x18905f76, +}; +inline constexpr uint32_t p256_gy[8] = { /* G_y * 2^256 mod p */ + 0xce95560a, 0xddf25357, 0xba19e45c, 0x8b4ab8e4, + 0xdd21f325, 0xd2e88688, 0x25885d85, 0x8571ff18, +}; + +inline void point_to_affine(uint32_t x[8], uint32_t y[8], uint32_t z[8]) +{ + uint32_t t[8]; + + m256_inv(z, z, &p256_p); /* z = z^-1 */ + + m256_mul_p(t, z, z); /* t = z^-2 */ + m256_mul_p(x, x, t); /* x = x * z^-2 */ + + m256_mul_p(t, t, z); /* t = z^-3 */ + m256_mul_p(y, y, t); /* y = y * z^-3 */ +} + +inline void point_double(uint32_t x[8], uint32_t y[8], uint32_t z[8]) +{ + /* + * This is formula 6 from [CMO98], cited as complete in [RCB15] (table 1). + * Notations as in the paper, except u added and t ommited (it's x3). + */ + uint32_t m[8], s[8], u[8]; + + /* m = 3 * x^2 + a * z^4 = 3 * (x + z^2) * (x - z^2) */ + m256_mul_p(s, z, z); + m256_add_p(m, x, s); + m256_sub_p(u, x, s); + m256_mul_p(s, m, u); + m256_add_p(m, s, s); + m256_add_p(m, m, s); + + /* s = 4 * x * y^2 */ + m256_mul_p(u, y, y); + m256_add_p(u, u, u); /* u = 2 * y^2 (used below) */ + m256_mul_p(s, x, u); + m256_add_p(s, s, s); + + /* u = 8 * y^4 (not named in the paper, first term of y3) */ + m256_mul_p(u, u, u); + m256_add_p(u, u, u); + + /* x3 = t = m^2 - 2 * s */ + m256_mul_p(x, m, m); + m256_sub_p(x, x, s); + m256_sub_p(x, x, s); + + /* z3 = 2 * y * z */ + m256_mul_p(z, y, z); + m256_add_p(z, z, z); + + /* y3 = -u + m * (s - t) */ + m256_sub_p(y, s, x); + m256_mul_p(y, y, m); + m256_sub_p(y, y, u); +} + +inline void point_add(uint32_t x1[8], uint32_t y1[8], uint32_t z1[8], + const uint32_t x2[8], const uint32_t y2[8]) +{ + /* + * This is formula 5 from [CMO98], with z2 == 1 substituted. We use + * intermediates with neutral names, and names from the paper in comments. + */ + uint32_t t1[8], t2[8], t3[8]; + + /* u1 = x1 and s1 = y1 (no computations) */ + + /* t1 = u2 = x2 z1^2 */ + m256_mul_p(t1, z1, z1); + m256_mul_p(t2, t1, z1); + m256_mul_p(t1, t1, x2); + + /* t2 = s2 = y2 z1^3 */ + m256_mul_p(t2, t2, y2); + + /* t1 = h = u2 - u1 */ + m256_sub_p(t1, t1, x1); /* t1 = x2 * z1^2 - x1 */ + + /* t2 = r = s2 - s1 */ + m256_sub_p(t2, t2, y1); + + /* z3 = z1 * h */ + m256_mul_p(z1, z1, t1); + + /* t1 = h^3 */ + m256_mul_p(t3, t1, t1); + m256_mul_p(t1, t3, t1); + + /* t3 = x1 * h^2 */ + m256_mul_p(t3, t3, x1); + + /* x3 = r^2 - 2 * x1 * h^2 - h^3 */ + m256_mul_p(x1, t2, t2); + m256_sub_p(x1, x1, t3); + m256_sub_p(x1, x1, t3); + m256_sub_p(x1, x1, t1); + + /* y3 = r * (x1 * h^2 - x3) - y1 h^3 */ + m256_sub_p(t3, t3, x1); + m256_mul_p(t3, t3, t2); + m256_mul_p(t1, t1, y1); + m256_sub_p(y1, t3, t1); +} + +inline void scalar_mult(uint32_t rx[8], uint32_t ry[8], + const uint32_t px[8], const uint32_t py[8], + const uint32_t s[8]) +{ + /* + * We use a signed binary ladder, see for example slides 10-14 of + * http://ecc2015.math.u-bordeaux1.fr/documents/hamburg.pdf but with + * implicit recoding, and a different loop initialisation to avoid feeding + * 0 to our addition formulas, as they don't support it. + */ + uint32_t s_odd[8], py_neg[8], py_use[8], rz[8]; + + /* + * Make s odd by replacing it with n - s if necessary. + * + * If s was odd, we'll have s_odd = s, and define P' = P. + * Otherwise, we'll have s_odd = n - s and define P' = -P. + * + * Either way, we can compute s * P as s_odd * P'. + */ + u256_sub(s_odd, p256_n.m, s); /* no carry, result still in [1, n-1] */ + uint32_t negate = ~s[0] & 1; + u256_cmov(s_odd, s, 1 - negate); + + /* Compute py_neg = - py mod p (that's the y coordinate of -P) */ + u256_set32(py_use, 0); + m256_sub_p(py_neg, py_use, py); + + /* Initialize R = P' = (x:(-1)^negate * y:1) */ + u256_cmov(rx, px, 1); + u256_cmov(ry, py, 1); + m256_set32(rz, 1, &p256_p); + u256_cmov(ry, py_neg, negate); + + /* + * For any odd number s_odd = b255 ... b1 1, we have + * s_odd = 2^255 + 2^254 sbit(b255) + ... + 2 sbit(b2) + sbit(b1) + * writing + * sbit(b) = 2 * b - 1 = b ? 1 : -1 + * + * Use that to compute s_odd * P' by repeating R = 2 * R +- P': + * s_odd * P' = 2 * ( ... (2 * P' + sbit(b255) P') ... ) + sbit(b1) P' + * + * The loop invariant is that when beginning an iteration we have + * R = s_i P' + * with + * s_i = 2^(255-i) + 2^(254-i) sbit(b_255) + ... + * where the sum has 256 - i terms. + * + * When updating R we need to make sure the input to point_add() is + * neither 0 not +-P'. Since that input is 2 s_i P', it is sufficient to + * see that 1 < 2 s_i < n-1. The lower bound is obvious since s_i is a + * positive integer, and for the upper bound we distinguish three cases. + * + * If i > 1, then s_i < 2^254, so 2 s_i < 2^255 < n-1. + * Otherwise, i == 1 and we have 2 s_i = s_odd - sbit(b1). + * If s_odd <= n-4, then 2 s_1 <= n-3. + * Otherwise, s_odd = n-2, and for this curve's value of n, + * we have b1 == 1, so sbit(b1) = 1 and 2 s_1 <= n-3. + */ + for (unsigned i = 255; i > 0; i--) { + uint32_t bit = (s_odd[i / 32] >> i % 32) & 1; + + /* set (px, py_use) = sbit(bit) P' = sbit(bit) * (-1)^negate P */ + u256_cmov(py_use, py, bit ^ negate); + u256_cmov(py_use, py_neg, (1 - bit) ^ negate); + + /* Update R = 2 * R +- P' */ + point_double(rx, ry, rz); + point_add(rx, ry, rz, px, py_use); + } + + point_to_affine(rx, ry, rz); +} + +inline int scalar_from_bytes(uint32_t s[8], const uint8_t p[32]) +{ + u256_from_bytes(s, p); + + uint32_t r[8]; + uint32_t lt_n = u256_sub(r, s, p256_n.m); + + u256_set32(r, 1); + uint32_t lt_1 = u256_sub(r, s, r); + + if (lt_n && !lt_1) + return 0; + + return -1; +} + +inline void ecdsa_m256_mod_n(uint32_t x[8]) +{ + uint32_t t[8]; + uint32_t c = u256_sub(t, x, p256_n.m); + u256_cmov(x, t, 1 - c); +} + + +} +#if defined(_MSC_VER) && !defined(__GNUC__) +#pragma warning(pop) +#endif diff --git a/include/webfront/tls/detail/Protocol.hpp b/include/webfront/tls/detail/Protocol.hpp new file mode 100644 index 00000000..f6b2f2ea --- /dev/null +++ b/include/webfront/tls/detail/Protocol.hpp @@ -0,0 +1,239 @@ +#pragma once +#include "Wire.hpp" + +#include +#include + +namespace webfront::tls::detail { +inline constexpr unsigned suite = 0x1303, group = 29, signatureScheme = 0x0403; +inline constexpr unsigned maxPlaintext = 16384, maxCiphertext = maxPlaintext + 256; +inline constexpr Digest zeros{}; +inline constexpr Digest retryRandom{0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c, 0x02, 0x1e, 0x65, 0xb8, 0x91, + 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb, 0x8c, 0x5e, 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c}; + +enum Record : Byte { changeCipherSpec = 20, alert = 21, handshakeRecord = 22, applicationData = 23 }; + +inline bool contains(View list, unsigned width, unsigned value) { + Reader elements{list}; + if (list.empty() || list.size() % width != 0) + throw Error("invalid negotiation list"); + while (!elements.empty()) + if (elements.number(width) == value) + return true; + return false; +} + +struct ClientHello { + View session; + View share; + Digest invariant; + unsigned shareCount = 0; + bool alpn = false; +}; + +inline ClientHello parseHello(View message, bool retry) { + Reader header{message}; + if (header.number(1) != 1) + throw Error("expected ClientHello", 10); + Reader hello{header.vector(3)}; + header.end(); + const auto original = hello.remaining; + if (hello.number(2) != 0x0303) + throw Error("invalid ClientHello legacy version", 70); + hello.take(32); + ClientHello result; + result.session = hello.vector(1); + if (result.session.size() > 32) + throw Error("oversized session ID"); + const bool offeredSuite = contains(hello.vector(2), 2, suite); + const auto compression = hello.vector(1); + if (compression.size() != 1 || compression.front() != 0) + throw Error("invalid compression methods", 47); + Sha256 invariant; + invariant.update(original.first(original.size() - hello.remaining.size())); + Reader extensions{hello.vector(2)}; + hello.end(); + bool version = false, signature = false, supportedGroup = false, earlyData = false; + std::bitset<65536> seen; + View shares, groups; + while (!extensions.empty()) { + const auto encoded = extensions.remaining; + const auto kind = extensions.number(2); + Reader extension{extensions.vector(2)}; + if (seen.test(kind)) + throw Error("duplicate ClientHello extension", 47); + seen.set(kind); + switch (kind) { + case 43: + version = contains(extension.vector(1), 2, 0x0304); + break; + case 13: + signature = contains(extension.vector(2), 2, signatureScheme); + break; + case 10: + groups = extension.vector(2); + supportedGroup = contains(groups, 2, group); + break; + case 51: + shares = extension.vector(2); + break; + case 42: + earlyData = true; + break; + case 44: + throw Error("unexpected ClientHello cookie", 47); + case 41: + if (!extensions.empty()) + throw Error("pre_shared_key is not last", 47); + break; // This server always negotiates a full handshake. + case 16: { + Reader protocols{extension.vector(2)}; + if (protocols.empty()) + throw Error("empty ALPN list"); + while (!protocols.empty()) { + const auto protocol = protocols.vector(1); + if (protocol.empty()) + throw Error("empty ALPN name"); + result.alpn |= std::ranges::equal(protocol, bytes("http/1.1")); + } + if (!result.alpn) + throw Error("HTTP/1.1 not offered", 120); + break; + } + default: + break; + } + if (kind == 43 || kind == 13 || kind == 10 || kind == 51 || kind == 42 || kind == 16) + extension.end(); + if (kind != 51 && kind != 21 && kind != 41 && kind != 42) + invariant.update(encoded.first(encoded.size() - extensions.remaining.size())); + } + if (!version) + throw Error("TLS 1.3 required", 70); + if (!offeredSuite || !signature || !supportedGroup) + throw Error("no common cipher suite, signature or group", 40); + if (earlyData && (retry || !seen.test(41))) + throw Error("unexpected early_data", 47); + Reader keys{shares}; + std::size_t groupOffset = 0; + while (!keys.empty()) { + const auto kind = keys.number(2); + const auto key = keys.vector(2); + // Key shares are an ordered subsequence of supported_groups. + while (groupOffset < groups.size() && Reader{groups.subspan(groupOffset)}.number(2) != kind) + groupOffset += 2; + if (groupOffset == groups.size() || key.empty()) + throw Error("invalid key share", 47); + groupOffset += 2; + ++result.shareCount; + if (kind == group) { + if (key.size() != 32 || !result.share.empty()) + throw Error("invalid X25519 key share", 47); + result.share = key; + } + } + result.invariant = invariant.digest(); + return result; +} + +inline Bytes serverHello(View session, View random, View publicKey) { + constexpr std::array version{3, 4}; + Bytes extensions; + extension(extensions, 43, version); + Bytes keyShare; + put(keyShare, group, 2); + if (!publicKey.empty()) + vector(keyShare, publicKey, 2); + extension(extensions, 51, keyShare); + + Bytes body{3, 3}; + append(body, random); + vector(body, session, 1); + put(body, suite, 2); + put(body, 0, 1); + vector(body, extensions, 2); + return handshake(2, body); +} + +struct RecordHeader { + Byte type; + unsigned size; +}; + +inline RecordHeader parseRecord(View header, bool encrypted, bool initial = false) { + Reader input{header}; + const auto type = static_cast(input.number(1)); + const auto version = input.number(2); + const auto size = input.number(2); + input.end(); + if (version != 0x0303 && !(initial && version == 0x0301 && type == handshakeRecord)) + throw Error("invalid record version", 70); + if (size > (encrypted && type == applicationData ? maxCiphertext : maxPlaintext)) + throw Error("oversized record", 22); + if (size == 0 || (encrypted && type == applicationData && size < 17)) + throw Error("invalid record length", 50); + return {type, size}; +} + +struct Traffic { + void install(View secret) { + key = {expandLabel(secret, "key")}; + const Secret<> expanded{expandLabel(secret, "iv", {}, 12)}; + std::ranges::copy(View(expanded).first(12), iv.begin()); + sequence = 0; + } + + void seal(Byte type, Bytes& record) { + const auto size = record.size() - 5; + if (size > maxPlaintext) + throw Error("oversized plaintext", 22); + record.resize(record.size() + 17); + record[0] = applicationData; + record[1] = record[2] = 3; + record[3] = static_cast((size + 17) >> 8); + record[4] = static_cast(size + 17); + record[5 + size] = type; + auto ctx = context(); + auto payload = record.data() + 5; + mono::crypto_aead_write(&ctx, payload, payload + size + 1, record.data(), 5, payload, size + 1); + mono::crypto_wipe(&ctx, sizeof(ctx)); + } + + Byte open(View header, Bytes& payload) { + if (payload.size() < 17) + throw Error("short ciphertext"); + auto ctx = context(); + const auto size = payload.size() - 16; + const auto mismatch = mono::crypto_aead_read(&ctx, payload.data(), payload.data() + size, header.data(), header.size(), payload.data(), size); + mono::crypto_wipe(&ctx, sizeof(ctx)); + if (mismatch) + throw Error("invalid authentication tag", 20); + payload.resize(size); + while (!payload.empty() && payload.back() == 0) + payload.pop_back(); + if (payload.empty()) + throw Error("missing inner record type", 10); + const auto type = payload.back(); + payload.pop_back(); + if (payload.size() > maxPlaintext) + throw Error("oversized inner plaintext", 22); + return type; + } + +private: + mono::crypto_aead_ctx context() { + if (sequence == UINT64_MAX) + throw Error("record sequence exhausted", 80); + auto nonce = iv; + for (unsigned i = 0; i != 8; ++i) + nonce[11 - i] ^= static_cast(sequence >> (8 * i)); + ++sequence; + mono::crypto_aead_ctx ctx; + mono::crypto_aead_init_ietf(&ctx, key.data(), nonce.data()); + return ctx; + } + Secret<> key{}; + std::array iv{}; + std::uint64_t sequence = 0; +}; +} // namespace webfront::tls::detail diff --git a/include/webfront/tls/detail/Wire.hpp b/include/webfront/tls/detail/Wire.hpp new file mode 100644 index 00000000..4f25544b --- /dev/null +++ b/include/webfront/tls/detail/Wire.hpp @@ -0,0 +1,70 @@ +#pragma once +#include "Crypto.hpp" + +namespace webfront::tls::detail { +struct Error : std::runtime_error { + Error(std::string_view message, Byte code = 50) : std::runtime_error("TLS: " + std::string(message)), alert(code) {} + Byte alert; +}; + +struct Reader { + View remaining; + + View take(std::size_t length) { + if (length > remaining.size()) + throw Error("truncated message"); + const auto value = remaining.first(length); + remaining = remaining.subspan(length); + return value; + } + + unsigned number(unsigned width) { + unsigned value = 0; + for (auto byte : take(width)) + value = (value << 8) | byte; + return value; + } + + View vector(unsigned width) { + return take(number(width)); + } + bool empty() const { + return remaining.empty(); + } + void end() const { + if (!empty()) + throw Error("trailing bytes"); + } + + View der(Byte type) { + if (number(1) != type) + throw Error("unexpected DER tag"); + auto size = number(1); + if (size & 128) { + const auto width = size & 127; + if (width == 0 || width > 3) + throw Error("invalid DER length"); + size = number(width); + if (size < (width == 1 ? 128u : 1u << (8 * (width - 1)))) + throw Error("noncanonical DER length"); + } + return take(size); + } +}; + +inline void vector(Bytes& out, View data, unsigned width) { + put(out, data.size(), width); + append(out, data); +} + +inline Bytes handshake(Byte type, View body) { + Bytes message{type}; + vector(message, body, 3); + return message; +} + +inline void extension(Bytes& out, unsigned type, View body) { + put(out, type, 2); + vector(out, body, 2); +} +} // namespace webfront::tls::detail diff --git a/test/driver/WfDriver.hpp b/test/driver/WfDriver.hpp index 4f4700e8..4c107829 100644 --- a/test/driver/WfDriver.hpp +++ b/test/driver/WfDriver.hpp @@ -69,15 +69,20 @@ struct DriverCEFFrontend : frontend::CEFFrontend { open("127.0.0.1", port, page, {}); } static void open(std::string_view address, std::string_view port, std::string_view page, const ContentPolicy& policy = {}) { + open(address, port, page, policy, {}, {}); + } + static void open(std::string_view address, std::string_view port, std::string_view page, const ContentPolicy& policy, + const WindowOptions&, const ViewLaunch& launch) { #if defined(WEBFRONT_EMBED_CEF) && defined(__linux__) const auto* profile = std::getenv("WEBFRONT_TEST_CEF_PROFILE"); if (!profile || !*profile) throw std::runtime_error("CEF test driver requires an isolated WEBFRONT_TEST_CEF_PROFILE"); - cef::detail::openWindow(frontend::detail::applicationUrl(address, port, page), - webfront::detail::BoundContentPolicy{webfront::detail::applicationOrigin(address, port), policy}, + const auto url = frontend::detail::applicationUrl(address, port, page, launch.origin); + cef::detail::openWindow(url, webfront::detail::BoundContentPolicy{url, policy}, nullptr, std::filesystem::path(profile)); #else + (void)launch; frontend::CEFFrontend::open(address, port, page, policy); #endif } @@ -402,7 +407,13 @@ struct PlainSetup { /// what C++ observed). template int run(const Options& options, Setup&& setup = {}) { - using App = webfront::BasicDeveloperApp, DriverFS, typename std::remove_reference_t::Pages>; + using Configuration = std::remove_reference_t; + using App = typename decltype([] { + if constexpr (requires { typename Configuration::Application; }) + return std::type_identity{}; + else + return std::type_identity, DriverFS, typename Configuration::Pages>>{}; + }())::type; static_assert(frontend::CanRequestClose>, "The driver closes its window with requestClose()"); if (!std::filesystem::is_regular_file(*options.environment)) { std::cerr << "Bootstrap environment archive not found: " << *options.environment << '\n'; diff --git a/test/fuzz/CMakeLists.txt b/test/fuzz/CMakeLists.txt index c87793e5..6d0ea7c1 100644 --- a/test/fuzz/CMakeLists.txt +++ b/test/fuzz/CMakeLists.txt @@ -18,7 +18,7 @@ if(NOT WEBFRONT_HAS_LIBFUZZER) message(FATAL_ERROR "WEBFRONT_ENABLE_FUZZING requires the compiler-rt libFuzzer, ASan and UBSan runtimes") endif() -foreach(_decoder IN ITEMS Messages HTTP WebSocket Gzip) +foreach(_decoder IN ITEMS Messages HTTP WebSocket Gzip TLS) string(TOLOWER "${_decoder}" _corpus) add_executable(fuzz_${_corpus} ${_decoder}Fuzz.cpp) target_link_libraries(fuzz_${_corpus} PRIVATE WebFront WebFront_test_hardening) diff --git a/test/fuzz/README.md b/test/fuzz/README.md index a7987f83..e9f79cf0 100644 --- a/test/fuzz/README.md +++ b/test/fuzz/README.md @@ -1,6 +1,6 @@ # Decoder fuzzing -`WEBFRONT_ENABLE_FUZZING=ON` builds `fuzz_messages`, `fuzz_http`, `fuzz_websocket`, and `fuzz_gzip` with +`WEBFRONT_ENABLE_FUZZING=ON` builds `fuzz_messages`, `fuzz_http`, `fuzz_websocket`, `fuzz_gzip`, and `fuzz_tls` with Clang/libFuzzer, ASan, UBSan, standard library hardening and pattern initialization. Linux with Clang/compiler-rt is validated in CI. Apple Clang does not include libFuzzer; on macOS install it externally (for example as part of LLVM/compiler-rt) and use compatible diff --git a/test/fuzz/RunFuzzers.py b/test/fuzz/RunFuzzers.py index 3cdb0c46..9b62d6b8 100644 --- a/test/fuzz/RunFuzzers.py +++ b/test/fuzz/RunFuzzers.py @@ -6,7 +6,7 @@ import shutil import subprocess -DECODERS = ('messages', 'http', 'websocket', 'gzip', 'gzip_differential') +DECODERS = ('messages', 'http', 'websocket', 'gzip', 'tls', 'gzip_differential') def run_all(root, jobs, seconds, run=subprocess.call): diff --git a/test/fuzz/TLSFuzz.cpp b/test/fuzz/TLSFuzz.cpp new file mode 100644 index 00000000..f5ac1165 --- /dev/null +++ b/test/fuzz/TLSFuzz.cpp @@ -0,0 +1,22 @@ +#include + +extern "C" int LLVMFuzzerTestOneInput(const std::uint8_t* data, std::size_t size) { + namespace tls = webfront::tls::detail; + const tls::View input(data, size); + try { + tls::parseHello(input, false); + } catch (const tls::Error&) {} + if (size < 5) + return 0; + try { + const auto header = input.first(5); + const auto record = tls::parseRecord(header, true); + if (record.type == tls::applicationData && record.size == size - 5) { + tls::Traffic traffic; + traffic.install(tls::zeros); + tls::Bytes payload(input.begin() + 5, input.end()); + traffic.open(header, payload); + } + } catch (const tls::Error&) {} + return 0; +} diff --git a/test/fuzz/corpus/tls/client-hello b/test/fuzz/corpus/tls/client-hello new file mode 100644 index 0000000000000000000000000000000000000000..0e8953619f39d77edb80a5459b6c9a6d1914e63c GIT binary patch literal 196 zcmWN}KMO%&7zOb2JnwtoF0#1FpO7L8CI$ng%my-M z+#OB2qaQ)58-Dl@MF2sBv=A`~l1S)v4k;vc7he~muh#QixtEre=JfPEUWT=6aaV0v qy;yy-&maxKLc)tUVp14F>1ayRFqI^Ol>U@#uwrIp!9<9F%k&5Q!zmg7 literal 0 HcmV?d00001 diff --git a/test/fuzz/corpus/tls/record-header b/test/fuzz/corpus/tls/record-header new file mode 100644 index 0000000000000000000000000000000000000000..324c6cfcb36f0805e14def1b19bc23e4c1a35222 GIT binary patch literal 22 ecmWeByYK!p2m$~=<_I_d literal 0 HcmV?d00001 diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 85e3e6df..b5a8862e 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -40,6 +40,7 @@ add_test(NAME BddDiscovery COMMAND ${CMAKE_COMMAND} -DPROBE=$ +#include + +using namespace webfront::bdd; + +namespace { +namespace tls = webfront::tls::detail; +using tls::Bytes; +using tls::View; + +Bytes tlsHex(std::string_view text) { + constexpr std::string_view digits = "0123456789abcdef"; + Bytes result; + for (std::size_t i = 0; i < text.size(); i += 2) + result.push_back(static_cast(digits.find(text[i]) * 16 + digits.find(text[i + 1]))); + return result; +} + +Bytes traceHello() { + return tlsHex("010000c00303cb34ecb1e78163ba1c38c6dacb196a6dffa21a8d9912ec18a2ef6283024dece70000061301130313020100" + "00910000000b0009000006736572766572ff01000100000a00140012001d0017001800190100010101020103010400230000" + "003300260024001d002099381de560e4bd43d23d8e435a7dbafeb3c06e51c13cae4d5413691e529aaf2c002b0003020304" + "000d0020001e040305030603020308040805080604010501060102010402050206020202002d00020101001c00024001"); +} + +const Scenario tlsPrimitives("TLS cryptographic vectors", {"fast"}, [] { + then("SHA-256 matches the standard message digest", [] { + require(std::ranges::equal(tls::hash(tls::bytes("abc")), tlsHex("ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad"))); + }); + then("HKDF extract and expand match RFC 5869 A.1", [] { + const auto salt = tlsHex("000102030405060708090a0b0c"); + const auto info = tlsHex("f0f1f2f3f4f5f6f7f8f9"); + const Bytes input(22, 0x0b); + const auto key = tls::hmac(salt, {input}); + require(std::ranges::equal(key, tlsHex("077709362c2e32df0ddc3f0dc47bba6390b6c73bb50f9c3122ec844ad7c2b3e5"))); + const auto first = tls::hmac(key, {info, std::array{1}}); + const auto second = tls::hmac(key, {first, info, std::array{2}}); + const auto expected = tlsHex("3cb25f25faacd57a90434f64d0362f2a2d2d0a90cf1a5a4c5db02d56ecc4c5bf34007208d5b887185865"); + require(std::ranges::equal(first, View(expected).first(32))); + require(std::ranges::equal(View(second).first(10), View(expected).subspan(32))); + }); + then("X25519 matches RFC 7748 section 6.1", [] { + const auto scalar = tlsHex("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"); + const auto peer = tlsHex("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"); + tls::Digest output; + tls::mono::crypto_x25519_public_key(output.data(), scalar.data()); + require(std::ranges::equal(output, tlsHex("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"))); + tls::mono::crypto_x25519(output.data(), scalar.data(), peer.data()); + require(std::ranges::equal(output, tlsHex("4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"))); + }); + then("the P-256 signature matches RFC 6979 A.2.5", [] { + const auto scalar = tlsHex("c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721"); + require(tls::sign(scalar, tls::hash(tls::bytes("sample"))) + == tlsHex("3046022100efd48b2aacb6a8fd1140dd9cd45e81d69d2c877b56aaf991c34d0ea84eaf3716" + "022100f7cb1c942d657c41d436c7a1b6e29f65f3e900dbb9aff4064dc4ab2f843acda8")); + }); + then("ChaCha20-Poly1305 matches RFC 8439 section 2.8.2", [] { + const auto key = tlsHex("808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f"); + const auto nonce = tlsHex("070000004041424344454647"); + const auto aad = tlsHex("50515253c0c1c2c3c4c5c6c7"); + const auto message = tls::bytes("Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it."); + Bytes ciphertext(message.size()); + std::array tag; + tls::mono::crypto_aead_ctx context; + tls::mono::crypto_aead_init_ietf(&context, key.data(), nonce.data()); + tls::mono::crypto_aead_write(&context, ciphertext.data(), tag.data(), aad.data(), aad.size(), message.data(), message.size()); + require(ciphertext + == tlsHex("d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63dbea45e8ca9671282fafb69da92728b" + "1a71de0a9e060b2905d6a5b67ecd3b3692ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc" + "3ff4def08e4b7a9de576d26586cec64b6116")); + require(std::ranges::equal(tag, tlsHex("1ae10b594f09e26a7e902ecbd0600691"))); + }); +}); + +const Scenario tlsHandshakeTrace("TLS 1.3 handshake against RFC 8448", {"fast"}, [] { + const auto hello = traceHello(); + const auto server = tlsHex("020000560303a6af06a4121860dc5e6e60249cd34c95930c8ac5cb1434dac155772ed3e2692800130100002e" + "00330024001d0020c9828876112095fe66762bdbf7c672e156d6cc253b833df1dd69b1b04e751f0f002b00020304"); + given("the client and server hellos from section 3", [&] { + const auto parsed = tls::parseHello(hello, false); + const auto scalar = tlsHex("b1580eeadf6dd589b8ef4f2d5652578cc810e9980191ec8d058308cea216a21e"); + tls::Digest shared; + tls::mono::crypto_x25519(shared.data(), scalar.data(), parsed.share.data()); + tls::Sha256 transcript; + transcript.update(hello); + transcript.update(server); + then("the handshake traffic secrets match the published trace", [&] { + const auto early = tls::hmac(tls::zeros, {tls::zeros}); + const auto salt = tls::expandLabel(early, "derived", tls::hash()); + const auto secret = tls::hmac(salt, {shared}); + require(std::ranges::equal(tls::expandLabel(secret, "c hs traffic", transcript.digest()), + tlsHex("b3eddb126e067f35a780b3abf45e2d8f3b1a950738f52e9600746a0e27a55a21"))); + require(std::ranges::equal(tls::expandLabel(secret, "s hs traffic", transcript.digest()), + tlsHex("b67b7d690cc16c4e75e54213cb2d37b4e9c912bcded9105d42befd59d391ad38"))); + }); + }); +}); + +const Scenario tlsRefusals("TLS rejects invalid framing and negotiation", {"fast"}, [] { + then("every truncated ClientHello is refused", [] { + const auto hello = traceHello(); + for (std::size_t size = 0; size < hello.size(); ++size) + requireThrows([&] { + tls::parseHello(View(hello).first(size), false); + }); + }); + then("unsupported versions and cipher suites are refused", [] { + auto hello = traceHello(); + hello[5] = 2; + requireThrows([&] { + tls::parseHello(hello, false); + }); + hello[5] = 3; + hello[44] = 2; // TLS_AES_256_GCM_SHA384 instead of ChaCha20-Poly1305. + requireThrows([&] { + tls::parseHello(hello, false); + }); + }); + then("oversized records and corrupted authentication tags are refused", [] { + requireThrows([] { + tls::parseRecord(tlsHex("1703034101"), true); + }); + tls::Traffic sender, receiver; + sender.install(tls::zeros); + receiver.install(tls::zeros); + Bytes record{0, 0, 0, 0, 0, 0x70}; + sender.seal(tls::applicationData, record); + Bytes payload(record.begin() + 5, record.end()); + payload.back() ^= 1; + requireThrows([&] { + receiver.open(View(record).first(5), payload); + }); + }); +}); +} // namespace diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index 8acf91e4..f504a550 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -272,6 +272,14 @@ if(_browser_tests_available) ARGUMENTS --project "${_suite_project}" --registry-dir "${_registry}" --timeout ${_suite_timeout} -- test --timeout ${_suite_timeout}) webfront_use_own_profile(${WEBFRONT_FRONTEND_${WEBFRONT_WEBTEST_FRONTEND}_TEST_NAME} jasmine) + if(WEBFRONT_WEBTEST_FRONTEND STREQUAL "CEF" AND CMAKE_SYSTEM_NAME STREQUAL "Linux") + webfront_find_xvfb(_tls_xvfb) + set(_tls_fixture "${CMAKE_CURRENT_SOURCE_DIR}/fixtures/tls") + file(STRINGS "${_tls_fixture}/spki.txt" _tls_spki LIMIT_COUNT 1) + webfront_add_test_program(webtest_tls JasmineTest.cpp WITH_WEBTEST + DEFINITIONS WEBFRONT_TEST_TLS_FIXTURE="${_tls_fixture}" WEBFRONT_TEST_MEDIA_FILE="${CMAKE_CURRENT_SOURCE_DIR}/fixtures/media/seek.webm") + target_link_libraries(webtest_tls PRIVATE WebFront_boing) + endif() else() webfront_add_browser_tests(webtest "${WEBFRONT_WEBTEST_FRONTEND}" "${CMAKE_CURRENT_SOURCE_DIR}" frontend_lifecycle SKIP_JASMINE) endif() @@ -511,7 +519,20 @@ if(_browser_tests_available) webfront_add_web_step(ReactAdapterPages REQUIRES ReactAdapterBuilt PROVIDES ReactAdapterPages LOCK "${_suite_project}" COMMAND ${CMAKE_COMMAND} -DBUILD=${_suite_project}/.webfront/developer/build -DOUTPUT=${_suite_project}/pages/react-example -P ${PROJECT_SOURCE_DIR}/test/cmake/PrepareReactExample.cmake) - set_tests_properties(${WEBFRONT_FRONTEND_${WEBFRONT_WEBTEST_FRONTEND}_TEST_NAME} PROPERTIES FIXTURES_REQUIRED "WebSuiteInstalled;ReactAdapterPages") + set_property(TEST ${WEBFRONT_FRONTEND_${WEBFRONT_WEBTEST_FRONTEND}_TEST_NAME} APPEND PROPERTY FIXTURES_REQUIRED WebSuiteInstalled ReactAdapterPages) + if(TARGET webtest_tls) + # Use synthetic begin frames so the canvas specs advance under Xvfb. + add_test(NAME WebFrontCEFHTTPSIntegration COMMAND "${_tls_xvfb}" -a $ + --disable-frame-rate-limit + "--user-data-dir=${CMAKE_CURRENT_BINARY_DIR}/webkitgtk-profiles/jasmine-tls/cef" + "--ignore-certificate-errors-spki-list=${_tls_spki}" + --environment "${WEBFRONT_BOOTSTRAP_ARCHIVE}" --integrity "${WEBFRONT_BOOTSTRAP_INTEGRITY}" + --project "${_suite_project}" --registry-dir "${_registry}" --timeout ${_suite_timeout} + -- test --timeout ${_suite_timeout}) + webfront_set_browser_test_properties(WebFrontCEFHTTPSIntegration "${CMAKE_CURRENT_SOURCE_DIR}" "${WEBFRONT_FRONTEND_CEF_TEST_TIMEOUT}") + webfront_use_own_profile(WebFrontCEFHTTPSIntegration jasmine-tls) + set_property(TEST WebFrontCEFHTTPSIntegration APPEND PROPERTY FIXTURES_REQUIRED WebSuiteInstalled ReactAdapterPages) + endif() endif() # The environment builds itself (#315): the pinned bootstrap environment runs js/developer/scripts on a copy of the diff --git a/test/web/JasmineTest.cpp b/test/web/JasmineTest.cpp index 25bfec52..c3bca0cf 100644 --- a/test/web/JasmineTest.cpp +++ b/test/web/JasmineTest.cpp @@ -8,6 +8,10 @@ #include #include +#ifdef WEBFRONT_TEST_TLS_FIXTURE +#include +#endif + #include "../driver/WfDriver.hpp" #include "../../examples/host-loop/HostLoopUI.hpp" #include "../../examples/life/react/LifeReact.hpp" @@ -101,11 +105,17 @@ class TestPages { #ifndef WEBFRONT_TEST_FRONTEND #define WEBFRONT_TEST_FRONTEND webfront::frontend::CEFFrontend #endif -using TestWF = BasicDeveloperApp, testdriver::DriverFS, TestPages>; +#ifdef WEBFRONT_TEST_TLS_FIXTURE +using TestNet = webfront::tls::Server; +#else +using TestNet = NetProvider; +#endif +using TestWF = DeveloperAppWithNetwork, testdriver::DriverFS, TestPages>; class BrowserIntegrationTest { public: using Pages = TestPages; + using Application = TestWF; ~BrowserIntegrationTest() { joinHostLoop(); @@ -117,6 +127,11 @@ class BrowserIntegrationTest { void configureApplication(WebFrontConfig& config) { config.contentPolicy.allowMissingOrigin = false; config.allowPtyPages = true; +#ifdef WEBFRONT_TEST_TLS_FIXTURE + const filesystem::path fixture(WEBFRONT_TEST_TLS_FIXTURE); + config.tlsCredentials = make_shared(fixture / "cert.pem", fixture / "key.pem"); + config.remoteFileTransport = RemoteFileTransport::refused; +#endif } /// Registers the callbacks of the specs before the page opens; the rejecting WebSocket server starts after the CEF @@ -124,6 +139,9 @@ class BrowserIntegrationTest { void configure(TestWF& app) { log::info("Starting automated Jasmine browser integration test"); webFront = &app; + app.cppFunction("expectedProtocol", [] { + return networking::secureTransport ? "https:"s : "http:"s; + }); rejectedWebSocket.emplace(); registerCallbacks(); registerPtyPage(app, { @@ -743,7 +761,10 @@ class BrowserIntegrationTest { webFront->cppFunction("senderCancellationObserved", [this] { return state.senderCancellationObserved.load(); }); - webFront->cppFunction("plusPageUrl", [this] { return frontend::detail::applicationUrl(webFront->port(), "a+b.html"); }); + webFront->cppFunction("plusPageUrl", [this] { + const auto origin = webfront::detail::applicationOrigin("127.0.0.1", webFront->port(), networking::secureTransport); + return frontend::detail::applicationUrl("127.0.0.1", webFront->port(), "a+b.html", origin); + }); webFront->cppFunction("rejectedWebSocketUrl", [this] { return rejectedWebSocket->url(); }); uiSubscription = webFront->subscribeUIStarted([this](TestWF::UI) { state.subscriberNotified = true; @@ -892,6 +913,18 @@ int main(int argc, char** argv) { log::setLogLevel(log::Warn); const auto consoleSink = log::addSinks(log::clogSink); +#ifdef WEBFRONT_TEST_TLS_FIXTURE + // CEF reads its switches from the process command line. Pass only wf options to the driver. + vector driverArgs{argv[0]}; + for (int i = 1; i < argc; ++i) { + const string_view option(argv[i]); + if (!option.starts_with("--ignore-certificate-errors-spki-list=") && !option.starts_with("--user-data-dir=") + && option != "--disable-frame-rate-limit") + driverArgs.push_back(argv[i]); + } + argc = static_cast(driverArgs.size()); + argv = driverArgs.data(); +#endif BrowserIntegrationTest test; const int result = webfront::testdriver::main(argc, argv, "webtest", test); log::removeSinks(consoleSink); diff --git a/test/web/fixtures/tls/README.md b/test/web/fixtures/tls/README.md new file mode 100644 index 00000000..50030a5c --- /dev/null +++ b/test/web/fixtures/tls/README.md @@ -0,0 +1,3 @@ +This public test identity serves localhost and 127.0.0.1 in the CEF HTTPS Jasmine +test. Its unencrypted key is committed for repeatable tests. CEF is configured +to accept this SPKI fingerprint in an isolated test profile. diff --git a/test/web/fixtures/tls/cert.pem b/test/web/fixtures/tls/cert.pem new file mode 100644 index 00000000..d348b94a --- /dev/null +++ b/test/web/fixtures/tls/cert.pem @@ -0,0 +1,11 @@ +-----BEGIN CERTIFICATE----- +MIIBmTCCAT+gAwIBAgIUPkN6UuZYhLvKC9xWwvCpPlplp0kwCgYIKoZIzj0EAwIw +FDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MTEyMTA5NDcxMloXDTQ2MTExNjA5 +NDcxMlowFDESMBAGA1UEAwwJbG9jYWxob3N0MFkwEwYHKoZIzj0CAQYIKoZIzj0D +AQcDQgAElFa6/ANSNq7ox/s/b07ONUNHj7nMgkAWwiAmNE2pYjr9/bWPKigrSlpF +LM+/IlxW6EkuR2oTB/5NWSMcLpeJJaNvMG0wHQYDVR0OBBYEFGgYWuDY5EjRdPwy +ypettEScSDpFMB8GA1UdIwQYMBaAFGgYWuDY5EjRdPwyypettEScSDpFMA8GA1Ud +EwEB/wQFMAMBAf8wGgYDVR0RBBMwEYIJbG9jYWxob3N0hwR/AAABMAoGCCqGSM49 +BAMCA0gAMEUCIQDeVHey7VGq8znid4nt1gaCKKAGFljB7cPxxOMzcPakaQIgN/RV +boJcR3WlYmgwcB32CIoMfW3y9QwN5QtOygUi4MQ= +-----END CERTIFICATE----- diff --git a/test/web/fixtures/tls/key.pem b/test/web/fixtures/tls/key.pem new file mode 100644 index 00000000..1bdc21fd --- /dev/null +++ b/test/web/fixtures/tls/key.pem @@ -0,0 +1,5 @@ +-----BEGIN PRIVATE KEY----- +MIGHAgEAMBMGByqGSM49AgEGCCqGSM49AwEHBG0wawIBAQQgIPiFhdvvm0nb9rAi +p9rALkPJxwChwFk0UfDRfktEUryhRANCAASUVrr8A1I2rujH+z9vTs41Q0ePucyC +QBbCICY0TaliOv39tY8qKCtKWkUsz78iXFboSS5HahMH/k1ZIxwul4kl +-----END PRIVATE KEY----- diff --git a/test/web/fixtures/tls/spki.txt b/test/web/fixtures/tls/spki.txt new file mode 100644 index 00000000..b0961ae1 --- /dev/null +++ b/test/web/fixtures/tls/spki.txt @@ -0,0 +1 @@ +6mi+lqJgETmBbYRMBlL+jQJyD9gFLyms2p3F27SHvNo= diff --git a/test/web/suite/specs/webfront-specs.mjs b/test/web/suite/specs/webfront-specs.mjs index ad64786e..6fbf258b 100644 --- a/test/web/suite/specs/webfront-specs.mjs +++ b/test/web/suite/specs/webfront-specs.mjs @@ -499,6 +499,7 @@ describe('WebFront browser integration', () => { it('resolves webFront.ready once the bridge has linked', async () => { await expectAsync(webFront.ready).toBeResolved(); + expect(window.location.protocol).toBe(await webFront.cppFunction('expectedProtocol')()); }); it('rejects a bridge whose initial connection fails', async () => { From 38b26b31a06f2afdaada25c30807b6f150f60f21 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 11:19:16 +0100 Subject: [PATCH 02/24] Implement TLS primitives directly from the specifications (#631) --- docs/TLS.md | 5 +- docs/adr/ADR-024-tls-integre.md | 10 +- include/webfront/tls/Credentials.hpp | 22 +- include/webfront/tls/Server.hpp | 8 +- include/webfront/tls/detail/ChaChaPoly.hpp | 151 +++ include/webfront/tls/detail/Crypto.hpp | 78 +- include/webfront/tls/detail/Curves.hpp | 91 ++ include/webfront/tls/detail/Field.hpp | 181 ++++ include/webfront/tls/detail/Monocypher.hpp | 1000 -------------------- include/webfront/tls/detail/P256.hpp | 803 ---------------- include/webfront/tls/detail/Protocol.hpp | 25 +- test/unit/TlsTests.cpp | 35 +- 12 files changed, 508 insertions(+), 1901 deletions(-) create mode 100644 include/webfront/tls/detail/ChaChaPoly.hpp create mode 100644 include/webfront/tls/detail/Curves.hpp create mode 100644 include/webfront/tls/detail/Field.hpp delete mode 100644 include/webfront/tls/detail/Monocypher.hpp delete mode 100644 include/webfront/tls/detail/P256.hpp diff --git a/docs/TLS.md b/docs/TLS.md index 06b08bb9..dc5ffc4f 100644 --- a/docs/TLS.md +++ b/docs/TLS.md @@ -52,9 +52,8 @@ the component's scope and qualification. On Linux x86-64 with GCC 16.1, a minimal app with one bridge callback built at `-Os -DNDEBUG -ffunction-sections -fdata-sections -Wl,--gc-sections` gained -47.8 KiB of `.text` and 5.3 KiB of `.rodata` when the TCP provider was -replaced by the TLS provider. The TLS headers total about 2,900 lines, -including source notices and comments in the two vendored primitive subsets. +43.6 KiB of `.text` and 5.0 KiB of `.rodata` when the TCP provider was +replaced by the TLS provider. The TLS headers total about 1,500 lines, including the in-tree primitives and comments. In the same binaries, 200 open loopback WebSockets increased Linux `smaps_rollup` private dirty memory by about 3.6 KiB more per idle connection diff --git a/docs/adr/ADR-024-tls-integre.md b/docs/adr/ADR-024-tls-integre.md index 3a05b777..e45738f6 100644 --- a/docs/adr/ADR-024-tls-integre.md +++ b/docs/adr/ADR-024-tls-integre.md @@ -15,10 +15,12 @@ Le navigateur valide la chaîne et le nom du serveur. TLS protège le transport, d'origine continue de décider de l'accès au pont. Le profil ne demande aucun certificat au client. Le serveur sait que le transport est chiffré lorsqu'il termine TLS et marque alors le cookie de liaison `Secure`. -Le composant demeure header-only, sous `include/webfront/tls/`. Il réutilise des primitives compactes -avec provenance et licences conservées. La génération de secrets utilise l'aléa de l'OS. Les opérations +Le composant demeure header-only, sous `include/webfront/tls/`. Ses primitives sont implémentées dans WebFront à partir des spécifications +[RFC 7748](https://www.rfc-editor.org/rfc/rfc7748), [RFC 8439](https://www.rfc-editor.org/rfc/rfc8439), +[SEC 1](https://www.secg.org/sec1-v2.pdf), [SEC 2](https://www.secg.org/sec2-v2.pdf) et +[RFC 6979](https://www.rfc-editor.org/rfc/rfc6979). La génération de secrets utilise l'aléa de l'OS. Les opérations sur des secrets exigent des accès mémoire et un contrôle de flux indépendants de ces secrets, avec vérification sur les compilateurs et architectures supportés. Les vecteurs des RFC, les refus de protocole, le fuzzing et un test navigateur HTTPS/WSS font partie de la qualification. Les régressions de sécurité -peuvent être signalées en privé aux mainteneurs. La maintenance du composant inclut le suivi des correctifs -amont des primitives et des mesures reproductibles de taille et de mémoire. +peuvent être signalées en privé aux mainteneurs. La maintenance du composant inclut la revue des primitives, +le suivi des errata des spécifications et des mesures reproductibles de taille et de mémoire. diff --git a/include/webfront/tls/Credentials.hpp b/include/webfront/tls/Credentials.hpp index 0cb58a04..67f11f35 100644 --- a/include/webfront/tls/Credentials.hpp +++ b/include/webfront/tls/Credentials.hpp @@ -133,10 +133,10 @@ inline std::shared_ptr loadIdentity(const std::filesystem::path& std::string& key; Bytes& der; ~Wipe() { - mono::crypto_wipe(key.data(), key.size()); - mono::crypto_wipe(der.data(), der.size()); + wipe(key.data(), key.size()); + wipe(der.data(), der.size()); } - } wipe{key, der}; + } erase{key, der}; readPemFile(chainPath, chain); readPemFile(keyPath, key); std::string_view chainPem = chain, keyPem = key; @@ -147,16 +147,16 @@ inline std::shared_ptr loadIdentity(const std::filesystem::path& throw Error("extra PEM key material"); auto identity = std::make_shared(); identity->key = privateKey(der, pkcs8); - std::uint32_t scalar[8]{}, x[8]{}, y[8]{}; - const auto valid = p256::scalar_from_bytes(scalar, identity->key.data()); - if (!valid) - p256::scalar_mult(x, y, p256::p256_gx, p256::p256_gy, scalar); - p256::zeroize(scalar, sizeof(scalar)); - if (valid) + auto scalar = decode(identity->key); + if (!P256Order::validScalar(scalar)) { + wipe(scalar.data(), sizeof(scalar)); throw Error("invalid private key scalar"); + } + const auto [x, y] = p256Base(scalar); + wipe(scalar.data(), sizeof(scalar)); std::array point; - p256::m256_to_bytes(point.data(), x, &p256::p256_p); - p256::m256_to_bytes(point.data() + 32, y, &p256::p256_p); + std::ranges::copy(encode(x), point.begin()); + std::ranges::copy(encode(y), point.begin() + 32); auto leaf = pem(chainPem, "CERTIFICATE"); if (!std::ranges::equal(certificateKey(leaf), point)) throw Error("certificate and private key do not match"); diff --git a/include/webfront/tls/Server.hpp b/include/webfront/tls/Server.hpp index a35304ad..17b90dd5 100644 --- a/include/webfront/tls/Server.hpp +++ b/include/webfront/tls/Server.hpp @@ -299,9 +299,9 @@ class Server : public networking::TCPStdnet { Secret<> scalar{}, shared{}; entropy(random); entropy(scalar); - mono::crypto_x25519_public_key(publicKey.data(), scalar.data()); - mono::crypto_x25519(shared.data(), scalar.data(), hello.share.data()); - if (!mono::crypto_verify32(shared.data(), zeros.data())) + publicKey = x25519(scalar, Digest{9}); + shared = {x25519(scalar, hello.share.first<32>())}; + if (equalSecret(shared, zeros)) throw Error("invalid X25519 shared secret", 47); co_await writeHandshake(socket, transcript, serverHello(hello.session, random, publicKey)); if (!retry && !hello.session.empty()) @@ -356,7 +356,7 @@ class Server : public networking::TCPStdnet { reader.end(); const Secret<> clientFinished{expandLabel(client, "finished")}; const auto expected = hmac(clientFinished, {afterFinished}); - if (verification.size() != 32 || mono::crypto_verify32(expected.data(), verification.data())) + if (!equalSecret(expected, verification)) throw Error("invalid client Finished", 51); state.read.install(state.readSecret); state.input.clear(); diff --git a/include/webfront/tls/detail/ChaChaPoly.hpp b/include/webfront/tls/detail/ChaChaPoly.hpp new file mode 100644 index 00000000..d555e752 --- /dev/null +++ b/include/webfront/tls/detail/ChaChaPoly.hpp @@ -0,0 +1,151 @@ +#pragma once +#include "Field.hpp" + +#include +#include + +namespace webfront::tls::detail { +inline std::uint32_t loadLittle(const Byte* data) { + std::uint32_t word = 0; + for (unsigned i = 0; i != 4; ++i) + word |= std::uint32_t{data[i]} << (8 * i); + return word; +} + +using Nonce = std::array; +using Tag = std::array; + +inline std::array chachaBlock(const Digest& key, const Nonce& nonce, std::uint32_t counter) { + // RFC 8439 section 2.3. The first four words encode the fixed ChaCha constant. + std::array input{0x61707865, 0x3320646e, 0x79622d32, 0x6b206574}; + for (std::size_t i = 0; i != 8; ++i) + input[4 + i] = loadLittle(key.data() + 4 * i); + input[12] = counter; + for (std::size_t i = 0; i != 3; ++i) + input[13 + i] = loadLittle(nonce.data() + 4 * i); + auto state = input; + const auto mix = [&state](unsigned w, unsigned x, unsigned y, unsigned z) { + state[w] += state[x]; + state[z] = std::rotl(state[z] ^ state[w], 16); + state[y] += state[z]; + state[x] = std::rotl(state[x] ^ state[y], 12); + state[w] += state[x]; + state[z] = std::rotl(state[z] ^ state[w], 8); + state[y] += state[z]; + state[x] = std::rotl(state[x] ^ state[y], 7); + }; + for (unsigned round = 0; round != 10; ++round) { + for (unsigned i = 0; i != 4; ++i) + mix(i, 4 + i, 8 + i, 12 + i); + for (unsigned i = 0; i != 4; ++i) + mix(i, 4 + (i + 1) % 4, 8 + (i + 2) % 4, 12 + (i + 3) % 4); + } + std::array stream; + for (std::size_t i = 0; i != state.size(); ++i) { + const auto word = state[i] + input[i]; + for (unsigned j = 0; j != 4; ++j) + stream[4 * i + j] = static_cast(word >> (8 * j)); + } + wipe(input.data(), sizeof(input)); + wipe(state.data(), sizeof(state)); + return stream; +} + +inline void chachaXor(const Digest& key, const Nonce& nonce, std::span payload) { + for (std::uint32_t counter = 1; !payload.empty(); ++counter) { + auto stream = chachaBlock(key, nonce, counter); + const auto count = std::min(payload.size(), stream.size()); + for (std::size_t i = 0; i != count; ++i) + payload[i] ^= stream[i]; + wipe(stream.data(), stream.size()); + payload = payload.subspan(count); + } +} + +// RFC 8439 sections 2.5 and 2.8.1. The radix makes the carry from limb 4 +// worth five in limb 0, since 2^130 is congruent to five modulo the prime. +inline Tag polyTag(const Digest& key, const Nonce& nonce, std::span aad, std::span ciphertext) { + constexpr std::uint64_t low = (1u << 26) - 1; + using Limbs = std::array; + const auto unpack = [](const Byte* data) -> Limbs { + return {loadLittle(data) & low, + (loadLittle(data + 3) >> 2) & low, + (loadLittle(data + 6) >> 4) & low, + (loadLittle(data + 9) >> 6) & low, + loadLittle(data + 12) >> 8}; + }; + auto oneTimeKey = chachaBlock(key, nonce, 0); + for (const auto i : {3u, 7u, 11u, 15u}) + oneTimeKey[i] &= 15; + for (const auto i : {4u, 8u, 12u}) + oneTimeKey[i] &= 252; + auto r = unpack(oneTimeKey.data()); + Limbs h{}; + const auto carry = [&h] { + for (std::size_t i = 0; i != 4; ++i) { + h[i + 1] += h[i] >> 26; + h[i] &= low; + } + h[0] += 5 * (h[4] >> 26); + h[4] &= low; + }; + const auto absorb = [&](const Byte* data) { + const auto m = unpack(data); + for (std::size_t i = 0; i != 5; ++i) + h[i] += m[i]; + h[4] += 1u << 24; + Limbs product{}; + for (std::size_t i = 0; i != 5; ++i) + for (std::size_t j = 0; j != 5; ++j) + product[(i + j) % 5] += h[i] * r[j] * (i + j < 5 ? 1u : 5u); + h = product; + carry(); + // The first carry leaves only limb 0 potentially wide. + carry(); + }; + for (auto data : {aad, ciphertext}) { + while (data.size() >= 16) { + absorb(data.data()); + data = data.subspan(16); + } + if (!data.empty()) { + Tag padded{}; + std::ranges::copy(data, padded.begin()); + absorb(padded.data()); + } + } + Tag lengths; + for (unsigned i = 0; i != 8; ++i) { + lengths[i] = static_cast(std::uint64_t{aad.size()} >> (8 * i)); + lengths[i + 8] = static_cast(std::uint64_t{ciphertext.size()} >> (8 * i)); + } + absorb(lengths.data()); + carry(); + + // h + 5 crosses bit 130 precisely when h is at least the modulus. + auto reduced = h; + reduced[0] += 5; + for (std::size_t i = 0; i != 4; ++i) { + reduced[i + 1] += reduced[i] >> 26; + reduced[i] &= low; + } + const auto mask = std::uint64_t{0} - (reduced[4] >> 26); + for (std::size_t i = 0; i != 5; ++i) + h[i] ^= (h[i] ^ reduced[i]) & mask; + + Tag tag; + unsigned padCarry = 0; + for (unsigned i = 0; i != tag.size(); ++i) { + const auto index = 8 * i / 26, offset = 8 * i % 26; + const auto pair = h[index] | (index < 4 ? h[index + 1] << 26 : 0); + padCarry += static_cast(pair >> offset) + unsigned{oneTimeKey[16 + i]}; + tag[i] = static_cast(padCarry); + padCarry >>= 8; + } + wipe(oneTimeKey.data(), oneTimeKey.size()); + wipe(r.data(), sizeof(r)); + wipe(h.data(), sizeof(h)); + wipe(reduced.data(), sizeof(reduced)); + return tag; +} +} // namespace webfront::tls::detail diff --git a/include/webfront/tls/detail/Crypto.hpp b/include/webfront/tls/detail/Crypto.hpp index 12125b33..84be4f75 100644 --- a/include/webfront/tls/detail/Crypto.hpp +++ b/include/webfront/tls/detail/Crypto.hpp @@ -1,7 +1,7 @@ #pragma once #include "../../automation/Platform.hpp" -#include "Monocypher.hpp" -#include "P256.hpp" +#include "ChaChaPoly.hpp" +#include "Curves.hpp" #include #include @@ -13,10 +13,8 @@ #include namespace webfront::tls::detail { -using Byte = std::uint8_t; -using Bytes = std::vector; -using View = std::span; -using Digest = std::array; +using Bytes = std::vector; +using View = std::span; inline View bytes(std::string_view string) { return {reinterpret_cast(string.data()), string.size()}; @@ -59,7 +57,7 @@ struct Sha256 { } ~Sha256() { - mono::crypto_wipe(this, sizeof(*this)); + wipe(this, sizeof(*this)); } private: @@ -97,7 +95,7 @@ struct Sha256 { const std::array final{a, b, c, d, e, f, g, h}; for (unsigned i = 0; i != state.size(); ++i) state[i] += final[i]; - mono::crypto_wipe(words.data(), sizeof(words)); + wipe(words.data(), sizeof(words)); } std::array state{0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19}; @@ -129,8 +127,8 @@ inline Digest hmac(View key, std::initializer_list chunks) { outer.update(pad); auto digest = inner.digest(); outer.update(digest); - mono::crypto_wipe(pad.data(), pad.size()); - mono::crypto_wipe(digest.data(), digest.size()); + wipe(pad.data(), pad.size()); + wipe(digest.data(), digest.size()); return outer.digest(); } @@ -158,54 +156,42 @@ inline void entropy(std::span out) { template struct Secret : std::array { ~Secret() { - mono::crypto_wipe(this->data(), Size); + wipe(this->data(), Size); } }; -inline Bytes sign(View key, View messageHash) { - using namespace p256; - std::uint32_t d[8]{}, k[8]{}, x[8]{}, y[8]{}, z[8]{}; - struct Wipe { - std::initializer_list buffers; - ~Wipe() { - for (auto buffer : buffers) - zeroize(buffer, 32); +inline Bytes sign(std::span key, const Digest& messageHash) { + using F = P256Order; + auto scalar = decode(key); + struct Erase { + Integer& value; + ~Erase() { + wipe(value.data(), sizeof(value)); } - } wipe{ - {d, k, x, y, z} - }; - if (scalar_from_bytes(d, key.data()) != 0) + } erase{scalar}; + if (!F::validScalar(scalar)) throw std::invalid_argument("TLS: invalid P-256 scalar"); - u256_from_bytes(z, messageHash.data()); - ecdsa_m256_mod_n(z); - Digest reduced; - u256_to_bytes(reduced.data(), z); - Secret<> v, mac{}; + scalar = F::enter(scalar); + const auto reduced = encode(F::reduce(decode(messageHash))); + const auto z = F::enter(decode(reduced)); + Secret<> v, mac{}; v.fill(1); const std::array zero{0}, one{1}; mac = {hmac(mac, {v, zero, key, reduced})}; v = {hmac(mac, {v})}; mac = {hmac(mac, {v, one, key, reduced})}; v = {hmac(mac, {v})}; - m256_prep(d, &p256_n); - m256_prep(z, &p256_n); for (;;) { - v = {hmac(mac, {v})}; - if (scalar_from_bytes(k, v.data()) == 0) { - scalar_mult(x, y, p256_gx, p256_gy, k); - m256_done(x, &p256_p); - ecdsa_m256_mod_n(x); - Digest r, s; - u256_to_bytes(r.data(), x); - m256_prep(x, &p256_n); - m256_prep(k, &p256_n); - m256_inv(k, k, &p256_n); - m256_mul(y, x, d, &p256_n); - m256_add(y, y, z, &p256_n); - m256_mul(y, y, k, &p256_n); - m256_to_bytes(s.data(), y, &p256_n); - if (u256_diff0(x) && u256_diff0(y)) { - Bytes signature{0x30, 0}; + v = {hmac(mac, {v})}; + auto k = decode(v); + Erase eraseNonce{k}; + if (F::validScalar(k)) { + const auto x = F::reduce(p256Base(k)[0]); + const auto sum = F::add(z, F::multiply(F::enter(x), scalar)); + const auto y = F::leave(F::multiply(F::invert(F::enter(k)), sum)); + if (nonzero(x) && nonzero(y)) { + const auto r = encode(x), s = encode(y); + Bytes signature{0x30, 0}; for (View value : {View(r), View(s)}) { while (value.size() > 1 && value.front() == 0) value = value.subspan(1); diff --git a/include/webfront/tls/detail/Curves.hpp b/include/webfront/tls/detail/Curves.hpp new file mode 100644 index 00000000..e343bcfc --- /dev/null +++ b/include/webfront/tls/detail/Curves.hpp @@ -0,0 +1,91 @@ +#pragma once +#include "Field.hpp" + +namespace webfront::tls::detail { +// RFC 7748 section 5. The affine input is little endian and its top bit is ignored. +inline Digest x25519(std::span scalar, std::span peer) { + using F = Field; + auto k = decode(scalar, true); + k[0] &= ~7u; + k[7] = (k[7] & 0x3fffffffu) | 0x40000000u; + auto coordinate = decode(peer, true); + coordinate[7] &= 0x7fffffffu; + const auto u = F::enter(F::reduce(coordinate)); + const auto a24 = F::enter({121665}); + auto x = F::enter({1}), z = Integer{}, nextX = u, nextZ = x; + const auto swap = [](Integer& a, Integer& b, std::uint32_t choice) { + const auto old = a; + a = select(a, b, choice); + b = select(b, old, choice); + }; + std::uint32_t previous = 0; + for (unsigned i = 255; i-- != 0;) { + const auto current = bit(k, i); + swap(x, nextX, previous ^ current); + swap(z, nextZ, previous ^ current); + previous = current; + const auto sum = F::add(x, z), difference = F::sub(x, z); + const auto sumSquared = F::square(sum), differenceSquared = F::square(difference); + const auto delta = F::sub(sumSquared, differenceSquared); + const auto left = F::multiply(F::sub(nextX, nextZ), sum); + const auto right = F::multiply(F::add(nextX, nextZ), difference); + nextX = F::square(F::add(left, right)); + nextZ = F::multiply(u, F::square(F::sub(left, right))); + x = F::multiply(sumSquared, differenceSquared); + z = F::multiply(delta, F::add(sumSquared, F::multiply(a24, delta))); + } + wipe(k.data(), sizeof(k)); + const auto affine = F::multiply(select(x, nextX, previous), F::invert(select(z, nextZ, previous))); + return encode(F::leave(affine), true); +} + +using P256Field = Field; +using P256Order = Field; + +struct P256Point { + Integer x{}, y{}, z{}; // Jacobian coordinates. z == 0 represents infinity. +}; + +// SEC 2 section 2.4.2. Compute kG with a fixed schedule, selecting the next +// Jacobian point with masks. The addend G is always affine. +inline std::array p256Base(const Integer& k) { + using F = P256Field; + const P256Point base{F::enter({0xd898c296, 0xf4a13945, 0x2deb33a0, 0x77037d81, 0x63a440f2, 0xf8bce6e5, 0xe12c4247, 0x6b17d1f2}), + F::enter({0x37bf51f5, 0xcbb64068, 0x6b315ece, 0x2bce3357, 0x7c0f9e16, 0x8ee7eb4a, 0xfe1a7f9b, 0x4fe342e2}), + F::enter({1})}; + const auto choose = [](const P256Point& a, const P256Point& b, std::uint32_t choice) { + return P256Point{select(a.x, b.x, choice), select(a.y, b.y, choice), select(a.z, b.z, choice)}; + }; + const auto twice = [](const P256Point& point) { + const auto y2 = F::square(point.y), z2 = F::square(point.z); + const auto xy2 = F::multiply(point.x, y2); + auto s = F::add(xy2, xy2); + s = F::add(s, s); + const auto slope = F::multiply(F::sub(point.x, z2), F::add(point.x, z2)); + const auto m = F::add(F::add(slope, slope), slope); // a = -3 + const auto x = F::sub(F::square(m), F::add(s, s)); + auto y4 = F::square(y2); + for (unsigned i = 0; i != 3; ++i) + y4 = F::add(y4, y4); + const auto yz = F::multiply(point.y, point.z); + return P256Point{x, F::sub(F::multiply(m, F::sub(s, x)), y4), F::add(yz, yz)}; + }; + const auto doubleBase = twice(base); + P256Point acc; + for (unsigned i = 256; i-- != 0;) { + const auto doubled = twice(acc); + const auto z2 = F::square(doubled.z); + const auto h = F::sub(F::multiply(base.x, z2), doubled.x); + const auto r = F::sub(F::multiply(base.y, F::multiply(z2, doubled.z)), doubled.y); + const auto h2 = F::square(h), h3 = F::multiply(h2, h); + const auto v = F::multiply(doubled.x, h2); + const auto x = F::sub(F::sub(F::square(r), h3), F::add(v, v)); + const P256Point sum{x, F::sub(F::multiply(r, F::sub(v, x)), F::multiply(doubled.y, h3)), F::multiply(doubled.z, h)}; + const auto same = (1u ^ nonzero(h)) & (1u ^ nonzero(r)); + const auto candidate = choose(choose(sum, doubleBase, same), base, 1u ^ nonzero(doubled.z)); + acc = choose(doubled, candidate, bit(k, i)); + } + const auto inverse = F::invert(acc.z), inverseSquared = F::square(inverse); + return {F::leave(F::multiply(acc.x, inverseSquared)), F::leave(F::multiply(acc.y, F::multiply(inverseSquared, inverse)))}; +} +} // namespace webfront::tls::detail diff --git a/include/webfront/tls/detail/Field.hpp b/include/webfront/tls/detail/Field.hpp new file mode 100644 index 00000000..687b79b5 --- /dev/null +++ b/include/webfront/tls/detail/Field.hpp @@ -0,0 +1,181 @@ +#pragma once + +#include +#include +#include +#include + +namespace webfront::tls::detail { +using Byte = std::uint8_t; +using Digest = std::array; + +inline void wipe(void* data, std::size_t size) { + auto* out = static_cast(data); + while (size--) + *out++ = 0; +} + +inline bool equalSecret(std::span a, std::span b) { + if (a.size() != b.size()) + return false; + unsigned difference = 0; + for (std::size_t i = 0; i != a.size(); ++i) + difference |= unsigned{a[i]} ^ b[i]; + return difference == 0; +} + +using Integer = std::array; + +inline Integer decode(std::span bytes, bool littleEndian = false) { + Integer result{}; + for (std::size_t i = 0; i != bytes.size(); ++i) + result[i / 4] |= std::uint32_t{bytes[littleEndian ? i : 31 - i]} << (8 * (i % 4)); + return result; +} + +inline Digest encode(const Integer& value, bool littleEndian = false) { + Digest result; + for (std::size_t i = 0; i != result.size(); ++i) + result[littleEndian ? i : 31 - i] = static_cast(value[i / 4] >> (8 * (i % 4))); + return result; +} + +inline std::uint32_t bit(const Integer& value, unsigned index) { + return (value[index / 32] >> (index % 32)) & 1u; +} + +inline std::uint32_t nonzero(const Integer& value) { + std::uint32_t combined = 0; + for (auto word : value) + combined |= word; + return (combined | (0u - combined)) >> 31; +} + +constexpr Integer select(const Integer& first, const Integer& second, std::uint32_t choice) { + Integer result; + for (std::size_t i = 0; i != result.size(); ++i) + result[i] = first[i] ^ ((first[i] ^ second[i]) & (0u - choice)); + return result; +} + +// Eight little-endian limbs. Field values are in Montgomery form between import and export. +template +struct Field { + static constexpr std::uint32_t subtract(Integer& out, const Integer& a, const Integer& b) { + std::uint64_t borrow = 0; + for (std::size_t i = 0; i != out.size(); ++i) { + const auto difference = std::uint64_t{a[i]} - b[i] - borrow; + out[i] = static_cast(difference); + borrow = difference >> 63; + } + return static_cast(borrow); + } + + static constexpr Integer reduce(const Integer& a, std::uint32_t high = 0) { + Integer reduced; + const auto borrow = subtract(reduced, a, Modulus); + return select(reduced, a, borrow & (1u ^ high)); + } + + static constexpr Integer add(const Integer& a, const Integer& b) { + Integer sum; + std::uint64_t carry = 0; + for (std::size_t i = 0; i != sum.size(); ++i) { + carry += std::uint64_t{a[i]} + b[i]; + sum[i] = static_cast(carry); + carry >>= 32; + } + return reduce(sum, static_cast(carry)); + } + + static Integer sub(const Integer& a, const Integer& b) { + Integer difference; + const auto mask = 0u - subtract(difference, a, b); + std::uint64_t carry = 0; + for (std::size_t i = 0; i != difference.size(); ++i) { + carry += std::uint64_t{difference[i]} + (Modulus[i] & mask); + difference[i] = static_cast(carry); + carry >>= 32; + } + return difference; + } + + static Integer multiply(const Integer& a, const Integer& b) { + constexpr std::size_t limbs = Modulus.size(); + std::array work{}; + for (const auto digit : a) { + std::uint64_t carry = 0; + for (std::size_t j = 0; j != limbs; ++j) { + carry += std::uint64_t{digit} * b[j] + work[j]; + work[j] = static_cast(carry); + carry >>= 32; + } + carry += work[limbs]; + work[limbs] = static_cast(carry); + work[limbs + 1] = static_cast(carry >> 32); + + // Cancel the low limb by adding a multiple of the modulus, then divide by 2^32. + const auto multiple = work[0] * negativeInverse; + carry = (std::uint64_t{multiple} * Modulus[0] + work[0]) >> 32; + for (std::size_t j = 1; j != limbs; ++j) { + carry += std::uint64_t{multiple} * Modulus[j] + work[j]; + work[j - 1] = static_cast(carry); + carry >>= 32; + } + carry += work[limbs]; + work[limbs - 1] = static_cast(carry); + work[limbs] = work[limbs + 1] + static_cast(carry >> 32); + } + Integer result; + for (std::size_t i = 0; i != limbs; ++i) + result[i] = work[i]; + return reduce(result, work[limbs]); + } + + static Integer square(const Integer& a) { + return multiply(a, a); + } + static Integer enter(const Integer& a) { + return multiply(a, radixSquared); + } + static Integer leave(const Integer& a) { + return multiply(a, {1}); + } + + static Integer invert(const Integer& a) { + // Fermat's little theorem. The exponent depends only on the public modulus. + constexpr auto exponent = [] { + auto value = Modulus; + value[0] -= 2; + return value; + }(); + auto power = enter({1}); + for (unsigned i = 256; i-- != 0;) { + power = square(power); + if (bit(exponent, i)) + power = multiply(power, a); + } + return power; + } + + static bool validScalar(const Integer& value) { + Integer ignored; + return (subtract(ignored, value, Modulus) & nonzero(value)) != 0; + } + +private: + static constexpr auto negativeInverse = [] { + std::uint32_t inverse = 1; + for (unsigned i = 0; i != 5; ++i) + inverse *= 2u - Modulus[0] * inverse; + return 0u - inverse; + }(); + + static constexpr auto radixSquared = [] { + Integer n{1}; + for (unsigned i = 0; i != 512; ++i) + n = add(n, n); + return n; + }(); +}; +} // namespace webfront::tls::detail diff --git a/include/webfront/tls/detail/Monocypher.hpp b/include/webfront/tls/detail/Monocypher.hpp deleted file mode 100644 index dc7754e5..00000000 --- a/include/webfront/tls/detail/Monocypher.hpp +++ /dev/null @@ -1,1000 +0,0 @@ -// Monocypher version 4.0.2 -// -// This file is dual-licensed. Choose whichever licence you want from -// the two licences listed below. -// -// The first licence is a regular 2-clause BSD licence. The second licence -// is the CC-0 from Creative Commons. It is intended to release Monocypher -// to the public domain. The BSD licence serves as a fallback option. -// -// SPDX-License-Identifier: BSD-2-Clause OR CC0-1.0 -// -// ------------------------------------------------------------------------ -// -// Copyright (c) 2017-2020, Loup Vaillant -// All rights reserved. -// -// -// Redistribution and use in source and binary forms, with or without -// modification, are permitted provided that the following conditions are -// met: -// -// 1. Redistributions of source code must retain the above copyright -// notice, this list of conditions and the following disclaimer. -// -// 2. Redistributions in binary form must reproduce the above copyright -// notice, this list of conditions and the following disclaimer in the -// documentation and/or other materials provided with the -// distribution. -// -// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS -// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT -// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR -// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT -// HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, -// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT -// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, -// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY -// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE -// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -// -// ------------------------------------------------------------------------ -// -// Written in 2017-2020 by Loup Vaillant -// -// To the extent possible under law, the author(s) have dedicated all copyright -// and related neighboring rights to this software to the public domain -// worldwide. This software is distributed without any warranty. -// -// You should have received a copy of the CC0 Public Domain Dedication along -// with this software. If not, see -// - -// Subset of Monocypher 4.0.2 (0d85f98c9d9b0227e42cf795cb527dff372b40a4). -#pragma once -#if defined(__GNUC__) -#pragma GCC system_header -#elif defined(_MSC_VER) -#pragma warning(push, 0) -#endif -#include -#include -namespace webfront::tls::detail::mono { -using std::size_t; -using std::int32_t; -using std::int64_t; -using std::uint8_t; -using std::uint32_t; -using std::uint64_t; -#define WEBFRONT_TLS_MONO_FOR_T(type, i, start, end) for (type i = (start); i < (end); i++) -#define WEBFRONT_TLS_MONO_FOR(i, start, end) WEBFRONT_TLS_MONO_FOR_T(size_t, i, start, end) -#define WEBFRONT_TLS_MONO_COPY(dst, src, size) WEBFRONT_TLS_MONO_FOR(_i_, 0, size) (dst)[_i_] = (src)[_i_] -#define WEBFRONT_TLS_MONO_ZERO(buf, size) WEBFRONT_TLS_MONO_FOR(_i_, 0, size) (buf)[_i_] = 0 -#define WEBFRONT_TLS_MONO_WIPE_CTX(ctx) crypto_wipe(ctx , sizeof(*(ctx))) -#define WEBFRONT_TLS_MONO_WIPE_BUFFER(buffer) crypto_wipe(buffer, sizeof(buffer)) -#define WEBFRONT_TLS_MONO_MIN(a, b) ((a) <= (b) ? (a) : (b)) -#define WEBFRONT_TLS_MONO_MAX(a, b) ((a) >= (b) ? (a) : (b)) - -typedef int8_t i8; -typedef uint8_t u8; -typedef int16_t i16; -typedef uint32_t u32; -typedef int32_t i32; -typedef int64_t i64; -typedef uint64_t u64; - -inline constexpr u8 zero[128] = {0}; - -// returns the smallest positive integer y such that -// (x + y) % pow_2 == 0 -// Basically, y is the "gap" missing to align x. -// Only works when pow_2 is a power of 2. -// Note: we use ~x+1 instead of -x to avoid compiler warnings -inline size_t gap(size_t x, size_t pow_2) -{ - return (~x + 1) & (pow_2 - 1); -} - -inline u32 load24_le(const u8 s[3]) -{ - return - ((u32)s[0] << 0) | - ((u32)s[1] << 8) | - ((u32)s[2] << 16); -} - -inline u32 load32_le(const u8 s[4]) -{ - return - ((u32)s[0] << 0) | - ((u32)s[1] << 8) | - ((u32)s[2] << 16) | - ((u32)s[3] << 24); -} - -inline u64 load64_le(const u8 s[8]) -{ - return load32_le(s) | ((u64)load32_le(s+4) << 32); -} - -inline void store32_le(u8 out[4], u32 in) -{ - out[0] = in & 0xff; - out[1] = (in >> 8) & 0xff; - out[2] = (in >> 16) & 0xff; - out[3] = (in >> 24) & 0xff; -} - -inline void store64_le(u8 out[8], u64 in) -{ - store32_le(out , (u32)in ); - store32_le(out + 4, in >> 32); -} - -inline void load32_le_buf (u32 *dst, const u8 *src, size_t size) { - WEBFRONT_TLS_MONO_FOR(i, 0, size) { dst[i] = load32_le(src + i*4); } -} -inline u32 rotl32(u32 x, u32 n) { return (x << n) ^ (x >> (32 - n)); } - -inline int neq0(u64 diff) -{ - // constant time comparison to zero - // return diff != 0 ? -1 : 0 - u64 half = (diff >> 32) | ((u32)diff); - return (1 & ((half - 1) >> 32)) - 1; -} - -inline u64 x16(const u8 a[16], const u8 b[16]) -{ - return (load64_le(a + 0) ^ load64_le(b + 0)) - | (load64_le(a + 8) ^ load64_le(b + 8)); -} -inline u64 x32(const u8 a[32],const u8 b[32]){return x16(a,b)| x16(a+16, b+16);} -inline int crypto_verify16(const u8 a[16], const u8 b[16]){ return neq0(x16(a, b)); } -inline int crypto_verify32(const u8 a[32], const u8 b[32]){ return neq0(x32(a, b)); } -inline void crypto_wipe(void *secret, size_t size) -{ - volatile u8 *v_secret = (u8*)secret; - WEBFRONT_TLS_MONO_ZERO(v_secret, size); -} - -#define WEBFRONT_TLS_MONO_QUARTERROUND(a, b, c, d) \ - a += b; d = rotl32(d ^ a, 16); \ - c += d; b = rotl32(b ^ c, 12); \ - a += b; d = rotl32(d ^ a, 8); \ - c += d; b = rotl32(b ^ c, 7) - -inline void chacha20_rounds(u32 out[16], const u32 in[16]) -{ - // The temporary variables make Chacha20 10% faster. - u32 t0 = in[ 0]; u32 t1 = in[ 1]; u32 t2 = in[ 2]; u32 t3 = in[ 3]; - u32 t4 = in[ 4]; u32 t5 = in[ 5]; u32 t6 = in[ 6]; u32 t7 = in[ 7]; - u32 t8 = in[ 8]; u32 t9 = in[ 9]; u32 t10 = in[10]; u32 t11 = in[11]; - u32 t12 = in[12]; u32 t13 = in[13]; u32 t14 = in[14]; u32 t15 = in[15]; - - WEBFRONT_TLS_MONO_FOR (i, 0, 10) { // 20 rounds, 2 rounds per loop. - WEBFRONT_TLS_MONO_QUARTERROUND(t0, t4, t8 , t12); // column 0 - WEBFRONT_TLS_MONO_QUARTERROUND(t1, t5, t9 , t13); // column 1 - WEBFRONT_TLS_MONO_QUARTERROUND(t2, t6, t10, t14); // column 2 - WEBFRONT_TLS_MONO_QUARTERROUND(t3, t7, t11, t15); // column 3 - WEBFRONT_TLS_MONO_QUARTERROUND(t0, t5, t10, t15); // diagonal 0 - WEBFRONT_TLS_MONO_QUARTERROUND(t1, t6, t11, t12); // diagonal 1 - WEBFRONT_TLS_MONO_QUARTERROUND(t2, t7, t8 , t13); // diagonal 2 - WEBFRONT_TLS_MONO_QUARTERROUND(t3, t4, t9 , t14); // diagonal 3 - } - out[ 0] = t0; out[ 1] = t1; out[ 2] = t2; out[ 3] = t3; - out[ 4] = t4; out[ 5] = t5; out[ 6] = t6; out[ 7] = t7; - out[ 8] = t8; out[ 9] = t9; out[10] = t10; out[11] = t11; - out[12] = t12; out[13] = t13; out[14] = t14; out[15] = t15; -} - -inline const u8 * const chacha20_constant = (const u8*)"expand 32-byte k"; // 16 bytes -inline u64 crypto_chacha20_djb(u8 *cipher_text, const u8 *plain_text, - size_t text_size, const u8 key[32], const u8 nonce[8], - u64 ctr) -{ - u32 input[16]; - load32_le_buf(input , chacha20_constant, 4); - load32_le_buf(input + 4, key , 8); - load32_le_buf(input + 14, nonce , 2); - input[12] = (u32) ctr; - input[13] = (u32)(ctr >> 32); - - // Whole blocks - u32 pool[16]; - size_t nb_blocks = text_size >> 6; - WEBFRONT_TLS_MONO_FOR (i, 0, nb_blocks) { - chacha20_rounds(pool, input); - if (plain_text != 0) { - WEBFRONT_TLS_MONO_FOR (j, 0, 16) { - u32 p = pool[j] + input[j]; - store32_le(cipher_text, p ^ load32_le(plain_text)); - cipher_text += 4; - plain_text += 4; - } - } else { - WEBFRONT_TLS_MONO_FOR (j, 0, 16) { - u32 p = pool[j] + input[j]; - store32_le(cipher_text, p); - cipher_text += 4; - } - } - input[12]++; - if (input[12] == 0) { - input[13]++; - } - } - text_size &= 63; - - // Last (incomplete) block - if (text_size > 0) { - if (plain_text == 0) { - plain_text = zero; - } - chacha20_rounds(pool, input); - u8 tmp[64]; - WEBFRONT_TLS_MONO_FOR (i, 0, 16) { - store32_le(tmp + i*4, pool[i] + input[i]); - } - WEBFRONT_TLS_MONO_FOR (i, 0, text_size) { - cipher_text[i] = tmp[i] ^ plain_text[i]; - } - WEBFRONT_TLS_MONO_WIPE_BUFFER(tmp); - } - ctr = input[12] + ((u64)input[13] << 32) + (text_size > 0); - - WEBFRONT_TLS_MONO_WIPE_BUFFER(pool); - WEBFRONT_TLS_MONO_WIPE_BUFFER(input); - return ctr; -} - -typedef struct { - // Do not rely on the size or contents of this type, - // for they may change without notice. - uint8_t c[16]; // chunk of the message - size_t c_idx; // How many bytes are there in the chunk. - uint32_t r [4]; // constant multiplier (from the secret key) - uint32_t pad[4]; // random number added at the end (from the secret key) - uint32_t h [5]; // accumulated hash -} crypto_poly1305_ctx; -///////////////// -/// Poly 1305 /// -///////////////// - -// h = (h + c) * r -// preconditions: -// ctx->h <= 4_ffffffff_ffffffff_ffffffff_ffffffff -// ctx->r <= 0ffffffc_0ffffffc_0ffffffc_0fffffff -// end <= 1 -// Postcondition: -// ctx->h <= 4_ffffffff_ffffffff_ffffffff_ffffffff -inline void poly_blocks(crypto_poly1305_ctx *ctx, const u8 *in, - size_t nb_blocks, unsigned end) -{ - // Local all the things! - const u32 r0 = ctx->r[0]; - const u32 r1 = ctx->r[1]; - const u32 r2 = ctx->r[2]; - const u32 r3 = ctx->r[3]; - const u32 rr0 = (r0 >> 2) * 5; // lose 2 bits... - const u32 rr1 = (r1 >> 2) + r1; // rr1 == (r1 >> 2) * 5 - const u32 rr2 = (r2 >> 2) + r2; // rr1 == (r2 >> 2) * 5 - const u32 rr3 = (r3 >> 2) + r3; // rr1 == (r3 >> 2) * 5 - const u32 rr4 = r0 & 3; // ...recover 2 bits - u32 h0 = ctx->h[0]; - u32 h1 = ctx->h[1]; - u32 h2 = ctx->h[2]; - u32 h3 = ctx->h[3]; - u32 h4 = ctx->h[4]; - - WEBFRONT_TLS_MONO_FOR (i, 0, nb_blocks) { - // h + c, without carry propagation - const u64 s0 = (u64)h0 + load32_le(in); in += 4; - const u64 s1 = (u64)h1 + load32_le(in); in += 4; - const u64 s2 = (u64)h2 + load32_le(in); in += 4; - const u64 s3 = (u64)h3 + load32_le(in); in += 4; - const u32 s4 = h4 + end; - - // (h + c) * r, without carry propagation - const u64 x0 = s0*r0+ s1*rr3+ s2*rr2+ s3*rr1+ s4*rr0; - const u64 x1 = s0*r1+ s1*r0 + s2*rr3+ s3*rr2+ s4*rr1; - const u64 x2 = s0*r2+ s1*r1 + s2*r0 + s3*rr3+ s4*rr2; - const u64 x3 = s0*r3+ s1*r2 + s2*r1 + s3*r0 + s4*rr3; - const u32 x4 = s4*rr4; - - // partial reduction modulo 2^130 - 5 - const u32 u5 = x4 + (x3 >> 32); // u5 <= 7ffffff5 - const u64 u0 = (u5 >> 2) * 5 + (x0 & 0xffffffff); - const u64 u1 = (u0 >> 32) + (x1 & 0xffffffff) + (x0 >> 32); - const u64 u2 = (u1 >> 32) + (x2 & 0xffffffff) + (x1 >> 32); - const u64 u3 = (u2 >> 32) + (x3 & 0xffffffff) + (x2 >> 32); - const u32 u4 = (u3 >> 32) + (u5 & 3); // u4 <= 4 - - // Update the hash - h0 = u0 & 0xffffffff; - h1 = u1 & 0xffffffff; - h2 = u2 & 0xffffffff; - h3 = u3 & 0xffffffff; - h4 = u4; - } - ctx->h[0] = h0; - ctx->h[1] = h1; - ctx->h[2] = h2; - ctx->h[3] = h3; - ctx->h[4] = h4; -} - -inline void crypto_poly1305_init(crypto_poly1305_ctx *ctx, const u8 key[32]) -{ - WEBFRONT_TLS_MONO_ZERO(ctx->h, 5); // Initial hash is zero - ctx->c_idx = 0; - // load r and pad (r has some of its bits cleared) - load32_le_buf(ctx->r , key , 4); - load32_le_buf(ctx->pad, key+16, 4); - WEBFRONT_TLS_MONO_FOR (i, 0, 1) { ctx->r[i] &= 0x0fffffff; } - WEBFRONT_TLS_MONO_FOR (i, 1, 4) { ctx->r[i] &= 0x0ffffffc; } -} - -inline void crypto_poly1305_update(crypto_poly1305_ctx *ctx, - const u8 *message, size_t message_size) -{ - // Avoid undefined NULL pointer increments with empty messages - if (message_size == 0) { - return; - } - - // Align ourselves with block boundaries - size_t aligned = WEBFRONT_TLS_MONO_MIN(gap(ctx->c_idx, 16), message_size); - WEBFRONT_TLS_MONO_FOR (i, 0, aligned) { - ctx->c[ctx->c_idx] = *message; - ctx->c_idx++; - message++; - message_size--; - } - - // If block is complete, process it - if (ctx->c_idx == 16) { - poly_blocks(ctx, ctx->c, 1, 1); - ctx->c_idx = 0; - } - - // Process the message block by block - size_t nb_blocks = message_size >> 4; - poly_blocks(ctx, message, nb_blocks, 1); - message += nb_blocks << 4; - message_size &= 15; - - // remaining bytes (we never complete a block here) - WEBFRONT_TLS_MONO_FOR (i, 0, message_size) { - ctx->c[ctx->c_idx] = message[i]; - ctx->c_idx++; - } -} - -inline void crypto_poly1305_final(crypto_poly1305_ctx *ctx, u8 mac[16]) -{ - // Process the last block (if any) - // We move the final 1 according to remaining input length - // (this will add less than 2^130 to the last input block) - if (ctx->c_idx != 0) { - WEBFRONT_TLS_MONO_ZERO(ctx->c + ctx->c_idx, 16 - ctx->c_idx); - ctx->c[ctx->c_idx] = 1; - poly_blocks(ctx, ctx->c, 1, 0); - } - - // check if we should subtract 2^130-5 by performing the - // corresponding carry propagation. - u64 c = 5; - WEBFRONT_TLS_MONO_FOR (i, 0, 4) { - c += ctx->h[i]; - c >>= 32; - } - c += ctx->h[4]; - c = (c >> 2) * 5; // shift the carry back to the beginning - // c now indicates how many times we should subtract 2^130-5 (0 or 1) - WEBFRONT_TLS_MONO_FOR (i, 0, 4) { - c += (u64)ctx->h[i] + ctx->pad[i]; - store32_le(mac + i*4, (u32)c); - c = c >> 32; - } - WEBFRONT_TLS_MONO_WIPE_CTX(ctx); -} - -//////////////////////////////////// -/// Arithmetic modulo 2^255 - 19 /// -//////////////////////////////////// -// Originally taken from SUPERCOP's ref10 implementation. -// A bit bigger than TweetNaCl, over 4 times faster. - -// field element -typedef i32 fe[10]; - -// field constants -// -// fe_one : 1 -// sqrtm1 : sqrt(-1) -// d : -121665 / 121666 -// D2 : 2 * -121665 / 121666 -// lop_x, lop_y: low order point in Edwards coordinates -// ufactor : -sqrt(-1) * 2 -// A2 : 486662^2 (A squared) -inline constexpr fe fe_one = {1}; -inline constexpr fe sqrtm1 = { - -32595792, -7943725, 9377950, 3500415, 12389472, - -272473, -25146209, -2005654, 326686, 11406482, -}; -inline void fe_0(fe h) { WEBFRONT_TLS_MONO_ZERO(h , 10); } -inline void fe_1(fe h) { h[0] = 1; WEBFRONT_TLS_MONO_ZERO(h+1, 9); } - -inline void fe_copy(fe h,const fe f ){WEBFRONT_TLS_MONO_FOR(i,0,10) h[i] = f[i]; } -inline void fe_neg (fe h,const fe f ){WEBFRONT_TLS_MONO_FOR(i,0,10) h[i] = -f[i]; } -inline void fe_add (fe h,const fe f,const fe g){WEBFRONT_TLS_MONO_FOR(i,0,10) h[i] = f[i] + g[i];} -inline void fe_sub (fe h,const fe f,const fe g){WEBFRONT_TLS_MONO_FOR(i,0,10) h[i] = f[i] - g[i];} - -inline void fe_cswap(fe f, fe g, int b) -{ - i32 mask = -b; // -1 = 0xffffffff - WEBFRONT_TLS_MONO_FOR (i, 0, 10) { - i32 x = (f[i] ^ g[i]) & mask; - f[i] = f[i] ^ x; - g[i] = g[i] ^ x; - } -} - -inline void fe_ccopy(fe f, const fe g, int b) -{ - i32 mask = -b; // -1 = 0xffffffff - WEBFRONT_TLS_MONO_FOR (i, 0, 10) { - i32 x = (f[i] ^ g[i]) & mask; - f[i] = f[i] ^ x; - } -} - -// Let t be a number. It can be uniquely decomposed thus: -// -// t = h*2^26 + l -// such that -2^25 <= l < 2^25 -// -// Let c = (t + 2^25) / 2^26 (rounded down) -// c = (h*2^26 + l + 2^25) / 2^26 (rounded down) -// c = h + (l + 2^25) / 2^26 (rounded down) -// c = h (exactly) -// Because 0 <= l + 2^25 < 2^26 -// -// Let u = t - c*2^26 -// u = h*2^26 + l - h*2^26 -// u = l -// Therefore, -2^25 <= u < 2^25 -// -// Additionally, if |t| < x, then |h| < x/2^26 (rounded down) -// -// Notations: -// - In C, 1<<25 means 2^25. -// - In C, x>>25 means floor(x / (2^25)). -// - All of the above applies with 25 & 24 as well as 26 & 25. -// -// -// Note on negative right shifts -// ----------------------------- -// -// In C, x >> n, where x is a negative integer, is implementation -// defined. In practice, all platforms do arithmetic shift, which is -// equivalent to division by 2^26, rounded down. Some compilers, like -// GCC, even guarantee it. -// -// If we ever stumble upon a platform that does not propagate the sign -// bit (we won't), visible failures will show at the slightest test, and -// the signed shifts can be replaced by the following: -// -// typedef struct { i64 x:39; } s25; -// typedef struct { i64 x:38; } s26; -// i64 shift25(i64 x) { s25 s; s.x = ((u64)x)>>25; return s.x; } -// i64 shift26(i64 x) { s26 s; s.x = ((u64)x)>>26; return s.x; } -// -// Current compilers cannot optimise this, causing a 30% drop in -// performance. Fairly expensive for something that never happens. -// -// -// Precondition -// ------------ -// -// |t0| < 2^63 -// |t1|..|t9| < 2^62 -// -// Algorithm -// --------- -// c = t0 + 2^25 / 2^26 -- |c| <= 2^36 -// t0 -= c * 2^26 -- |t0| <= 2^25 -// t1 += c -- |t1| <= 2^63 -// -// c = t4 + 2^25 / 2^26 -- |c| <= 2^36 -// t4 -= c * 2^26 -- |t4| <= 2^25 -// t5 += c -- |t5| <= 2^63 -// -// c = t1 + 2^24 / 2^25 -- |c| <= 2^38 -// t1 -= c * 2^25 -- |t1| <= 2^24 -// t2 += c -- |t2| <= 2^63 -// -// c = t5 + 2^24 / 2^25 -- |c| <= 2^38 -// t5 -= c * 2^25 -- |t5| <= 2^24 -// t6 += c -- |t6| <= 2^63 -// -// c = t2 + 2^25 / 2^26 -- |c| <= 2^37 -// t2 -= c * 2^26 -- |t2| <= 2^25 < 1.1 * 2^25 (final t2) -// t3 += c -- |t3| <= 2^63 -// -// c = t6 + 2^25 / 2^26 -- |c| <= 2^37 -// t6 -= c * 2^26 -- |t6| <= 2^25 < 1.1 * 2^25 (final t6) -// t7 += c -- |t7| <= 2^63 -// -// c = t3 + 2^24 / 2^25 -- |c| <= 2^38 -// t3 -= c * 2^25 -- |t3| <= 2^24 < 1.1 * 2^24 (final t3) -// t4 += c -- |t4| <= 2^25 + 2^38 < 2^39 -// -// c = t7 + 2^24 / 2^25 -- |c| <= 2^38 -// t7 -= c * 2^25 -- |t7| <= 2^24 < 1.1 * 2^24 (final t7) -// t8 += c -- |t8| <= 2^63 -// -// c = t4 + 2^25 / 2^26 -- |c| <= 2^13 -// t4 -= c * 2^26 -- |t4| <= 2^25 < 1.1 * 2^25 (final t4) -// t5 += c -- |t5| <= 2^24 + 2^13 < 1.1 * 2^24 (final t5) -// -// c = t8 + 2^25 / 2^26 -- |c| <= 2^37 -// t8 -= c * 2^26 -- |t8| <= 2^25 < 1.1 * 2^25 (final t8) -// t9 += c -- |t9| <= 2^63 -// -// c = t9 + 2^24 / 2^25 -- |c| <= 2^38 -// t9 -= c * 2^25 -- |t9| <= 2^24 < 1.1 * 2^24 (final t9) -// t0 += c * 19 -- |t0| <= 2^25 + 2^38*19 < 2^44 -// -// c = t0 + 2^25 / 2^26 -- |c| <= 2^18 -// t0 -= c * 2^26 -- |t0| <= 2^25 < 1.1 * 2^25 (final t0) -// t1 += c -- |t1| <= 2^24 + 2^18 < 1.1 * 2^24 (final t1) -// -// Postcondition -// ------------- -// |t0|, |t2|, |t4|, |t6|, |t8| < 1.1 * 2^25 -// |t1|, |t3|, |t5|, |t7|, |t9| < 1.1 * 2^24 -#define WEBFRONT_TLS_MONO_FE_CARRY \ - i64 c; \ - c = (t0 + ((i64)1<<25)) >> 26; t0 -= c * ((i64)1 << 26); t1 += c; \ - c = (t4 + ((i64)1<<25)) >> 26; t4 -= c * ((i64)1 << 26); t5 += c; \ - c = (t1 + ((i64)1<<24)) >> 25; t1 -= c * ((i64)1 << 25); t2 += c; \ - c = (t5 + ((i64)1<<24)) >> 25; t5 -= c * ((i64)1 << 25); t6 += c; \ - c = (t2 + ((i64)1<<25)) >> 26; t2 -= c * ((i64)1 << 26); t3 += c; \ - c = (t6 + ((i64)1<<25)) >> 26; t6 -= c * ((i64)1 << 26); t7 += c; \ - c = (t3 + ((i64)1<<24)) >> 25; t3 -= c * ((i64)1 << 25); t4 += c; \ - c = (t7 + ((i64)1<<24)) >> 25; t7 -= c * ((i64)1 << 25); t8 += c; \ - c = (t4 + ((i64)1<<25)) >> 26; t4 -= c * ((i64)1 << 26); t5 += c; \ - c = (t8 + ((i64)1<<25)) >> 26; t8 -= c * ((i64)1 << 26); t9 += c; \ - c = (t9 + ((i64)1<<24)) >> 25; t9 -= c * ((i64)1 << 25); t0 += c * 19; \ - c = (t0 + ((i64)1<<25)) >> 26; t0 -= c * ((i64)1 << 26); t1 += c; \ - h[0]=(i32)t0; h[1]=(i32)t1; h[2]=(i32)t2; h[3]=(i32)t3; h[4]=(i32)t4; \ - h[5]=(i32)t5; h[6]=(i32)t6; h[7]=(i32)t7; h[8]=(i32)t8; h[9]=(i32)t9 - -// Decodes a field element from a byte buffer. -// mask specifies how many bits we ignore. -// Traditionally we ignore 1. It's useful for EdDSA, -// which uses that bit to denote the sign of x. -// Elligator however uses positive representatives, -// which means ignoring 2 bits instead. -inline void fe_frombytes_mask(fe h, const u8 s[32], unsigned nb_mask) -{ - u32 mask = 0xffffff >> nb_mask; - i64 t0 = load32_le(s); // t0 < 2^32 - i64 t1 = load24_le(s + 4) << 6; // t1 < 2^30 - i64 t2 = load24_le(s + 7) << 5; // t2 < 2^29 - i64 t3 = load24_le(s + 10) << 3; // t3 < 2^27 - i64 t4 = load24_le(s + 13) << 2; // t4 < 2^26 - i64 t5 = load32_le(s + 16); // t5 < 2^32 - i64 t6 = load24_le(s + 20) << 7; // t6 < 2^31 - i64 t7 = load24_le(s + 23) << 5; // t7 < 2^29 - i64 t8 = load24_le(s + 26) << 4; // t8 < 2^28 - i64 t9 = (load24_le(s + 29) & mask) << 2; // t9 < 2^25 - WEBFRONT_TLS_MONO_FE_CARRY; // Carry precondition OK -} - -inline void fe_frombytes(fe h, const u8 s[32]) -{ - fe_frombytes_mask(h, s, 1); -} - - -// Precondition -// |h[0]|, |h[2]|, |h[4]|, |h[6]|, |h[8]| < 1.1 * 2^25 -// |h[1]|, |h[3]|, |h[5]|, |h[7]|, |h[9]| < 1.1 * 2^24 -// -// Therefore, |h| < 2^255-19 -// There are two possibilities: -// -// - If h is positive, all we need to do is reduce its individual -// limbs down to their tight positive range. -// - If h is negative, we also need to add 2^255-19 to it. -// Or just remove 19 and chop off any excess bit. -inline void fe_tobytes(u8 s[32], const fe h) -{ - i32 t[10]; - WEBFRONT_TLS_MONO_COPY(t, h, 10); - i32 q = (19 * t[9] + (((i32) 1) << 24)) >> 25; - // |t9| < 1.1 * 2^24 - // -1.1 * 2^24 < t9 < 1.1 * 2^24 - // -21 * 2^24 < 19 * t9 < 21 * 2^24 - // -2^29 < 19 * t9 + 2^24 < 2^29 - // -2^29 / 2^25 < (19 * t9 + 2^24) / 2^25 < 2^29 / 2^25 - // -16 < (19 * t9 + 2^24) / 2^25 < 16 - WEBFRONT_TLS_MONO_FOR (i, 0, 5) { - q += t[2*i ]; q >>= 26; // q = 0 or -1 - q += t[2*i+1]; q >>= 25; // q = 0 or -1 - } - // q = 0 iff h >= 0 - // q = -1 iff h < 0 - // Adding q * 19 to h reduces h to its proper range. - q *= 19; // Shift carry back to the beginning - WEBFRONT_TLS_MONO_FOR (i, 0, 5) { - t[i*2 ] += q; q = t[i*2 ] >> 26; t[i*2 ] -= q * ((i32)1 << 26); - t[i*2+1] += q; q = t[i*2+1] >> 25; t[i*2+1] -= q * ((i32)1 << 25); - } - // h is now fully reduced, and q represents the excess bit. - - store32_le(s + 0, ((u32)t[0] >> 0) | ((u32)t[1] << 26)); - store32_le(s + 4, ((u32)t[1] >> 6) | ((u32)t[2] << 19)); - store32_le(s + 8, ((u32)t[2] >> 13) | ((u32)t[3] << 13)); - store32_le(s + 12, ((u32)t[3] >> 19) | ((u32)t[4] << 6)); - store32_le(s + 16, ((u32)t[5] >> 0) | ((u32)t[6] << 25)); - store32_le(s + 20, ((u32)t[6] >> 7) | ((u32)t[7] << 19)); - store32_le(s + 24, ((u32)t[7] >> 13) | ((u32)t[8] << 12)); - store32_le(s + 28, ((u32)t[8] >> 20) | ((u32)t[9] << 6)); - - WEBFRONT_TLS_MONO_WIPE_BUFFER(t); -} - -// Precondition -// ------------- -// |f0|, |f2|, |f4|, |f6|, |f8| < 1.65 * 2^26 -// |f1|, |f3|, |f5|, |f7|, |f9| < 1.65 * 2^25 -// -// |g0|, |g2|, |g4|, |g6|, |g8| < 1.65 * 2^26 -// |g1|, |g3|, |g5|, |g7|, |g9| < 1.65 * 2^25 -inline void fe_mul_small(fe h, const fe f, i32 g) -{ - i64 t0 = f[0] * (i64) g; i64 t1 = f[1] * (i64) g; - i64 t2 = f[2] * (i64) g; i64 t3 = f[3] * (i64) g; - i64 t4 = f[4] * (i64) g; i64 t5 = f[5] * (i64) g; - i64 t6 = f[6] * (i64) g; i64 t7 = f[7] * (i64) g; - i64 t8 = f[8] * (i64) g; i64 t9 = f[9] * (i64) g; - // |t0|, |t2|, |t4|, |t6|, |t8| < 1.65 * 2^26 * 2^31 < 2^58 - // |t1|, |t3|, |t5|, |t7|, |t9| < 1.65 * 2^25 * 2^31 < 2^57 - - WEBFRONT_TLS_MONO_FE_CARRY; // Carry precondition OK -} - -inline void fe_mul(fe h, const fe f, const fe g) -{ - // Everything is unrolled and put in temporary variables. - // We could roll the loop, but that would make curve25519 twice as slow. - i32 f0 = f[0]; i32 f1 = f[1]; i32 f2 = f[2]; i32 f3 = f[3]; i32 f4 = f[4]; - i32 f5 = f[5]; i32 f6 = f[6]; i32 f7 = f[7]; i32 f8 = f[8]; i32 f9 = f[9]; - i32 g0 = g[0]; i32 g1 = g[1]; i32 g2 = g[2]; i32 g3 = g[3]; i32 g4 = g[4]; - i32 g5 = g[5]; i32 g6 = g[6]; i32 g7 = g[7]; i32 g8 = g[8]; i32 g9 = g[9]; - i32 F1 = f1*2; i32 F3 = f3*2; i32 F5 = f5*2; i32 F7 = f7*2; i32 F9 = f9*2; - i32 G1 = g1*19; i32 G2 = g2*19; i32 G3 = g3*19; - i32 G4 = g4*19; i32 G5 = g5*19; i32 G6 = g6*19; - i32 G7 = g7*19; i32 G8 = g8*19; i32 G9 = g9*19; - // |F1|, |F3|, |F5|, |F7|, |F9| < 1.65 * 2^26 - // |G0|, |G2|, |G4|, |G6|, |G8| < 2^31 - // |G1|, |G3|, |G5|, |G7|, |G9| < 2^30 - - i64 t0 = f0*(i64)g0 + F1*(i64)G9 + f2*(i64)G8 + F3*(i64)G7 + f4*(i64)G6 - + F5*(i64)G5 + f6*(i64)G4 + F7*(i64)G3 + f8*(i64)G2 + F9*(i64)G1; - i64 t1 = f0*(i64)g1 + f1*(i64)g0 + f2*(i64)G9 + f3*(i64)G8 + f4*(i64)G7 - + f5*(i64)G6 + f6*(i64)G5 + f7*(i64)G4 + f8*(i64)G3 + f9*(i64)G2; - i64 t2 = f0*(i64)g2 + F1*(i64)g1 + f2*(i64)g0 + F3*(i64)G9 + f4*(i64)G8 - + F5*(i64)G7 + f6*(i64)G6 + F7*(i64)G5 + f8*(i64)G4 + F9*(i64)G3; - i64 t3 = f0*(i64)g3 + f1*(i64)g2 + f2*(i64)g1 + f3*(i64)g0 + f4*(i64)G9 - + f5*(i64)G8 + f6*(i64)G7 + f7*(i64)G6 + f8*(i64)G5 + f9*(i64)G4; - i64 t4 = f0*(i64)g4 + F1*(i64)g3 + f2*(i64)g2 + F3*(i64)g1 + f4*(i64)g0 - + F5*(i64)G9 + f6*(i64)G8 + F7*(i64)G7 + f8*(i64)G6 + F9*(i64)G5; - i64 t5 = f0*(i64)g5 + f1*(i64)g4 + f2*(i64)g3 + f3*(i64)g2 + f4*(i64)g1 - + f5*(i64)g0 + f6*(i64)G9 + f7*(i64)G8 + f8*(i64)G7 + f9*(i64)G6; - i64 t6 = f0*(i64)g6 + F1*(i64)g5 + f2*(i64)g4 + F3*(i64)g3 + f4*(i64)g2 - + F5*(i64)g1 + f6*(i64)g0 + F7*(i64)G9 + f8*(i64)G8 + F9*(i64)G7; - i64 t7 = f0*(i64)g7 + f1*(i64)g6 + f2*(i64)g5 + f3*(i64)g4 + f4*(i64)g3 - + f5*(i64)g2 + f6*(i64)g1 + f7*(i64)g0 + f8*(i64)G9 + f9*(i64)G8; - i64 t8 = f0*(i64)g8 + F1*(i64)g7 + f2*(i64)g6 + F3*(i64)g5 + f4*(i64)g4 - + F5*(i64)g3 + f6*(i64)g2 + F7*(i64)g1 + f8*(i64)g0 + F9*(i64)G9; - i64 t9 = f0*(i64)g9 + f1*(i64)g8 + f2*(i64)g7 + f3*(i64)g6 + f4*(i64)g5 - + f5*(i64)g4 + f6*(i64)g3 + f7*(i64)g2 + f8*(i64)g1 + f9*(i64)g0; - // t0 < 0.67 * 2^61 - // t1 < 0.41 * 2^61 - // t2 < 0.52 * 2^61 - // t3 < 0.32 * 2^61 - // t4 < 0.38 * 2^61 - // t5 < 0.22 * 2^61 - // t6 < 0.23 * 2^61 - // t7 < 0.13 * 2^61 - // t8 < 0.09 * 2^61 - // t9 < 0.03 * 2^61 - - WEBFRONT_TLS_MONO_FE_CARRY; // Everything below 2^62, Carry precondition OK -} - -inline void fe_sq(fe h, const fe f) -{ - i32 f0 = f[0]; i32 f1 = f[1]; i32 f2 = f[2]; i32 f3 = f[3]; i32 f4 = f[4]; - i32 f5 = f[5]; i32 f6 = f[6]; i32 f7 = f[7]; i32 f8 = f[8]; i32 f9 = f[9]; - i32 f0_2 = f0*2; i32 f1_2 = f1*2; i32 f2_2 = f2*2; i32 f3_2 = f3*2; - i32 f4_2 = f4*2; i32 f5_2 = f5*2; i32 f6_2 = f6*2; i32 f7_2 = f7*2; - i32 f5_38 = f5*38; i32 f6_19 = f6*19; i32 f7_38 = f7*38; - i32 f8_19 = f8*19; i32 f9_38 = f9*38; - // |f0_2| , |f2_2| , |f4_2| , |f6_2| , |f8_2| < 1.65 * 2^27 - // |f1_2| , |f3_2| , |f5_2| , |f7_2| , |f9_2| < 1.65 * 2^26 - // |f5_38|, |f6_19|, |f7_38|, |f8_19|, |f9_38| < 2^31 - - i64 t0 = f0 *(i64)f0 + f1_2*(i64)f9_38 + f2_2*(i64)f8_19 - + f3_2*(i64)f7_38 + f4_2*(i64)f6_19 + f5 *(i64)f5_38; - i64 t1 = f0_2*(i64)f1 + f2 *(i64)f9_38 + f3_2*(i64)f8_19 - + f4 *(i64)f7_38 + f5_2*(i64)f6_19; - i64 t2 = f0_2*(i64)f2 + f1_2*(i64)f1 + f3_2*(i64)f9_38 - + f4_2*(i64)f8_19 + f5_2*(i64)f7_38 + f6 *(i64)f6_19; - i64 t3 = f0_2*(i64)f3 + f1_2*(i64)f2 + f4 *(i64)f9_38 - + f5_2*(i64)f8_19 + f6 *(i64)f7_38; - i64 t4 = f0_2*(i64)f4 + f1_2*(i64)f3_2 + f2 *(i64)f2 - + f5_2*(i64)f9_38 + f6_2*(i64)f8_19 + f7 *(i64)f7_38; - i64 t5 = f0_2*(i64)f5 + f1_2*(i64)f4 + f2_2*(i64)f3 - + f6 *(i64)f9_38 + f7_2*(i64)f8_19; - i64 t6 = f0_2*(i64)f6 + f1_2*(i64)f5_2 + f2_2*(i64)f4 - + f3_2*(i64)f3 + f7_2*(i64)f9_38 + f8 *(i64)f8_19; - i64 t7 = f0_2*(i64)f7 + f1_2*(i64)f6 + f2_2*(i64)f5 - + f3_2*(i64)f4 + f8 *(i64)f9_38; - i64 t8 = f0_2*(i64)f8 + f1_2*(i64)f7_2 + f2_2*(i64)f6 - + f3_2*(i64)f5_2 + f4 *(i64)f4 + f9 *(i64)f9_38; - i64 t9 = f0_2*(i64)f9 + f1_2*(i64)f8 + f2_2*(i64)f7 - + f3_2*(i64)f6 + f4 *(i64)f5_2; - // t0 < 0.67 * 2^61 - // t1 < 0.41 * 2^61 - // t2 < 0.52 * 2^61 - // t3 < 0.32 * 2^61 - // t4 < 0.38 * 2^61 - // t5 < 0.22 * 2^61 - // t6 < 0.23 * 2^61 - // t7 < 0.13 * 2^61 - // t8 < 0.09 * 2^61 - // t9 < 0.03 * 2^61 - - WEBFRONT_TLS_MONO_FE_CARRY; -} - -inline int fe_isequal(const fe f, const fe g) -{ - u8 fs[32]; - u8 gs[32]; - fe_tobytes(fs, f); - fe_tobytes(gs, g); - int isdifferent = crypto_verify32(fs, gs); - WEBFRONT_TLS_MONO_WIPE_BUFFER(fs); - WEBFRONT_TLS_MONO_WIPE_BUFFER(gs); - return 1 + isdifferent; -} - -inline int invsqrt(fe isr, const fe x) -{ - fe t0, t1, t2; - - // t0 = x^((p-5)/8) - // Can be achieved with a simple double & add ladder, - // but it would be slower. - fe_sq(t0, x); - fe_sq(t1,t0); fe_sq(t1, t1); fe_mul(t1, x, t1); - fe_mul(t0, t0, t1); - fe_sq(t0, t0); fe_mul(t0, t1, t0); - fe_sq(t1, t0); WEBFRONT_TLS_MONO_FOR (i, 1, 5) { fe_sq(t1, t1); } fe_mul(t0, t1, t0); - fe_sq(t1, t0); WEBFRONT_TLS_MONO_FOR (i, 1, 10) { fe_sq(t1, t1); } fe_mul(t1, t1, t0); - fe_sq(t2, t1); WEBFRONT_TLS_MONO_FOR (i, 1, 20) { fe_sq(t2, t2); } fe_mul(t1, t2, t1); - fe_sq(t1, t1); WEBFRONT_TLS_MONO_FOR (i, 1, 10) { fe_sq(t1, t1); } fe_mul(t0, t1, t0); - fe_sq(t1, t0); WEBFRONT_TLS_MONO_FOR (i, 1, 50) { fe_sq(t1, t1); } fe_mul(t1, t1, t0); - fe_sq(t2, t1); WEBFRONT_TLS_MONO_FOR (i, 1, 100) { fe_sq(t2, t2); } fe_mul(t1, t2, t1); - fe_sq(t1, t1); WEBFRONT_TLS_MONO_FOR (i, 1, 50) { fe_sq(t1, t1); } fe_mul(t0, t1, t0); - fe_sq(t0, t0); WEBFRONT_TLS_MONO_FOR (i, 1, 2) { fe_sq(t0, t0); } fe_mul(t0, t0, x); - - // quartic = x^((p-1)/4) - i32 *quartic = t1; - fe_sq (quartic, t0); - fe_mul(quartic, quartic, x); - - i32 *check = t2; - fe_0 (check); int z0 = fe_isequal(x , check); - fe_1 (check); int p1 = fe_isequal(quartic, check); - fe_neg(check, check ); int m1 = fe_isequal(quartic, check); - fe_neg(check, sqrtm1); int ms = fe_isequal(quartic, check); - - // if quartic == -1 or sqrt(-1) - // then isr = x^((p-1)/4) * sqrt(-1) - // else isr = x^((p-1)/4) - fe_mul(isr, t0, sqrtm1); - fe_ccopy(isr, t0, 1 - (m1 | ms)); - - WEBFRONT_TLS_MONO_WIPE_BUFFER(t0); - WEBFRONT_TLS_MONO_WIPE_BUFFER(t1); - WEBFRONT_TLS_MONO_WIPE_BUFFER(t2); - return p1 | m1 | z0; -} - -inline void fe_invert(fe out, const fe x) -{ - fe tmp; - fe_sq(tmp, x); - invsqrt(tmp, tmp); - fe_sq(tmp, tmp); - fe_mul(out, tmp, x); - WEBFRONT_TLS_MONO_WIPE_BUFFER(tmp); -} - -inline void crypto_eddsa_trim_scalar(u8 out[32], const u8 in[32]) -{ - WEBFRONT_TLS_MONO_COPY(out, in, 32); - out[ 0] &= 248; - out[31] &= 127; - out[31] |= 64; -} - -inline int scalar_bit(const u8 s[32], int i) -{ - if (i < 0) { return 0; } // handle -1 for sliding windows - return (s[i>>3] >> (i&7)) & 1; -} - -inline void scalarmult(u8 q[32], const u8 scalar[32], const u8 p[32], - int nb_bits) -{ - // computes the scalar product - fe x1; - fe_frombytes(x1, p); - - // computes the actual scalar product (the result is in x2 and z2) - fe x2, z2, x3, z3, t0, t1; - // Montgomery ladder - // In projective coordinates, to avoid divisions: x = X / Z - // We don't care about the y coordinate, it's only 1 bit of information - fe_1(x2); fe_0(z2); // "zero" point - fe_copy(x3, x1); fe_1(z3); // "one" point - int swap = 0; - for (int pos = nb_bits-1; pos >= 0; --pos) { - // constant time conditional swap before ladder step - int b = scalar_bit(scalar, pos); - swap ^= b; // xor trick avoids swapping at the end of the loop - fe_cswap(x2, x3, swap); - fe_cswap(z2, z3, swap); - swap = b; // anticipates one last swap after the loop - - // Montgomery ladder step: replaces (P2, P3) by (P2*2, P2+P3) - // with differential addition - fe_sub(t0, x3, z3); - fe_sub(t1, x2, z2); - fe_add(x2, x2, z2); - fe_add(z2, x3, z3); - fe_mul(z3, t0, x2); - fe_mul(z2, z2, t1); - fe_sq (t0, t1 ); - fe_sq (t1, x2 ); - fe_add(x3, z3, z2); - fe_sub(z2, z3, z2); - fe_mul(x2, t1, t0); - fe_sub(t1, t1, t0); - fe_sq (z2, z2 ); - fe_mul_small(z3, t1, 121666); - fe_sq (x3, x3 ); - fe_add(t0, t0, z3); - fe_mul(z3, x1, z2); - fe_mul(z2, t1, t0); - } - // last swap is necessary to compensate for the xor trick - // Note: after this swap, P3 == P2 + P1. - fe_cswap(x2, x3, swap); - fe_cswap(z2, z3, swap); - - // normalises the coordinates: x == X / Z - fe_invert(z2, z2); - fe_mul(x2, x2, z2); - fe_tobytes(q, x2); - - WEBFRONT_TLS_MONO_WIPE_BUFFER(x1); - WEBFRONT_TLS_MONO_WIPE_BUFFER(x2); WEBFRONT_TLS_MONO_WIPE_BUFFER(z2); WEBFRONT_TLS_MONO_WIPE_BUFFER(t0); - WEBFRONT_TLS_MONO_WIPE_BUFFER(x3); WEBFRONT_TLS_MONO_WIPE_BUFFER(z3); WEBFRONT_TLS_MONO_WIPE_BUFFER(t1); -} - -inline void crypto_x25519(u8 raw_shared_secret[32], - const u8 your_secret_key [32], - const u8 their_public_key [32]) -{ - // restrict the possible scalar values - u8 e[32]; - crypto_eddsa_trim_scalar(e, your_secret_key); - scalarmult(raw_shared_secret, e, their_public_key, 255); - WEBFRONT_TLS_MONO_WIPE_BUFFER(e); -} - -inline void crypto_x25519_public_key(u8 public_key[32], - const u8 secret_key[32]) -{ - static const u8 base_point[32] = {9}; - crypto_x25519(public_key, secret_key, base_point); -} - -typedef struct { - uint64_t counter; - uint8_t key[32]; - uint8_t nonce[8]; -} crypto_aead_ctx; -inline void lock_auth(u8 mac[16], const u8 auth_key[32], - const u8 *ad , size_t ad_size, - const u8 *cipher_text, size_t text_size) -{ - u8 sizes[16]; // Not secret, not wiped - store64_le(sizes + 0, ad_size); - store64_le(sizes + 8, text_size); - crypto_poly1305_ctx poly_ctx; // auto wiped... - crypto_poly1305_init (&poly_ctx, auth_key); - crypto_poly1305_update(&poly_ctx, ad , ad_size); - crypto_poly1305_update(&poly_ctx, zero , gap(ad_size, 16)); - crypto_poly1305_update(&poly_ctx, cipher_text, text_size); - crypto_poly1305_update(&poly_ctx, zero , gap(text_size, 16)); - crypto_poly1305_update(&poly_ctx, sizes , 16); - crypto_poly1305_final (&poly_ctx, mac); // ...here -} - -inline void crypto_aead_init_ietf(crypto_aead_ctx *ctx, - const u8 key[32], const u8 nonce[12]) -{ - WEBFRONT_TLS_MONO_COPY(ctx->key , key , 32); - WEBFRONT_TLS_MONO_COPY(ctx->nonce, nonce + 4, 8); - ctx->counter = (u64)load32_le(nonce) << 32; -} - -inline void crypto_aead_write(crypto_aead_ctx *ctx, u8 *cipher_text, u8 mac[16], - const u8 *ad, size_t ad_size, - const u8 *plain_text, size_t text_size) -{ - u8 auth_key[64]; // the last 32 bytes are used for rekeying. - crypto_chacha20_djb(auth_key, 0, 64, ctx->key, ctx->nonce, ctx->counter); - crypto_chacha20_djb(cipher_text, plain_text, text_size, - ctx->key, ctx->nonce, ctx->counter + 1); - lock_auth(mac, auth_key, ad, ad_size, cipher_text, text_size); - WEBFRONT_TLS_MONO_COPY(ctx->key, auth_key + 32, 32); - WEBFRONT_TLS_MONO_WIPE_BUFFER(auth_key); -} - -inline int crypto_aead_read(crypto_aead_ctx *ctx, u8 *plain_text, const u8 mac[16], - const u8 *ad, size_t ad_size, - const u8 *cipher_text, size_t text_size) -{ - u8 auth_key[64]; // the last 32 bytes are used for rekeying. - u8 real_mac[16]; - crypto_chacha20_djb(auth_key, 0, 64, ctx->key, ctx->nonce, ctx->counter); - lock_auth(real_mac, auth_key, ad, ad_size, cipher_text, text_size); - int mismatch = crypto_verify16(mac, real_mac); - if (!mismatch) { - crypto_chacha20_djb(plain_text, cipher_text, text_size, - ctx->key, ctx->nonce, ctx->counter + 1); - WEBFRONT_TLS_MONO_COPY(ctx->key, auth_key + 32, 32); - } - WEBFRONT_TLS_MONO_WIPE_BUFFER(auth_key); - WEBFRONT_TLS_MONO_WIPE_BUFFER(real_mac); - return mismatch; -} - - -#undef WEBFRONT_TLS_MONO_FOR_T -#undef WEBFRONT_TLS_MONO_FOR -#undef WEBFRONT_TLS_MONO_COPY -#undef WEBFRONT_TLS_MONO_ZERO -#undef WEBFRONT_TLS_MONO_WIPE_CTX -#undef WEBFRONT_TLS_MONO_WIPE_BUFFER -#undef WEBFRONT_TLS_MONO_MIN -#undef WEBFRONT_TLS_MONO_MAX -#undef WEBFRONT_TLS_MONO_QUARTERROUND -#undef WEBFRONT_TLS_MONO_FE_CARRY -} -#if defined(_MSC_VER) && !defined(__GNUC__) -#pragma warning(pop) -#endif diff --git a/include/webfront/tls/detail/P256.hpp b/include/webfront/tls/detail/P256.hpp deleted file mode 100644 index 68f1aaef..00000000 --- a/include/webfront/tls/detail/P256.hpp +++ /dev/null @@ -1,803 +0,0 @@ -/* - * Implementation of curve P-256 (ECDH and ECDSA) - * - * Author: Manuel Pégourié-Gonnard. - * SPDX-License-Identifier: Apache-2.0 - * License text is in the repository LICENSE. - */ -// Subset of p256-m (44af59e0cff5d3b1d653bc333814077ef830e1bd). -#pragma once -#if defined(__GNUC__) -#pragma GCC system_header -#elif defined(_MSC_VER) -#pragma warning(push, 0) -#endif -#include -#include -namespace webfront::tls::detail::p256 { -using std::size_t; -using std::uint8_t; -using std::uint16_t; -using std::uint32_t; -using std::uint64_t; -inline void zeroize(void *d, size_t n) -{ - volatile char *p = static_cast(d); - while( n-- ) - *p++ = 0; -} - - -/********************************************************************** - * - * Operations on fixed-width unsigned integers - * - * Represented using 32-bit limbs, least significant limb first. - * That is: x = x[0] + 2^32 x[1] + ... + 2^224 x[7] for 256-bit. - * - **********************************************************************/ - -/* - * 256-bit set to 32-bit value - * - * in: x in [0, 2^32) - * out: z = x - */ -inline void u256_set32(uint32_t z[8], uint32_t x) -{ - z[0] = x; - for (unsigned i = 1; i < 8; i++) { - z[i] = 0; - } -} - -/* - * 256-bit addition - * - * in: x, y in [0, 2^256) - * out: z = (x + y) mod 2^256 - * c = (x + y) div 2^256 - * That is, z + c * 2^256 = x + y - * - * Note: as a memory area, z must be either equal to x or y, or not overlap. - */ -inline uint32_t u256_add(uint32_t z[8], - const uint32_t x[8], const uint32_t y[8]) -{ - uint32_t carry = 0; - - for (unsigned i = 0; i < 8; i++) { - uint64_t sum = (uint64_t) carry + x[i] + y[i]; - z[i] = (uint32_t) sum; - carry = (uint32_t) (sum >> 32); - } - - return carry; -} - -/* - * 256-bit subtraction - * - * in: x, y in [0, 2^256) - * out: z = (x - y) mod 2^256 - * c = 0 if x >=y, 1 otherwise - * That is, z = c * 2^256 + x - y - * - * Note: as a memory area, z must be either equal to x or y, or not overlap. - */ -inline uint32_t u256_sub(uint32_t z[8], - const uint32_t x[8], const uint32_t y[8]) -{ - uint32_t carry = 0; - - for (unsigned i = 0; i < 8; i++) { - uint64_t diff = (uint64_t) x[i] - y[i] - carry; - z[i] = (uint32_t) diff; - carry = -(uint32_t) (diff >> 32); - } - - return carry; -} - -/* - * 256-bit conditional assignment - * - * in: x in [0, 2^256) - * c in [0, 1] - * out: z = x if c == 1, z unchanged otherwise - * - * Note: as a memory area, z must be either equal to x, or not overlap. - */ -inline void u256_cmov(uint32_t z[8], const uint32_t x[8], uint32_t c) -{ - const uint32_t x_mask = -c; - for (unsigned i = 0; i < 8; i++) { - z[i] = (z[i] & ~x_mask) | (x[i] & x_mask); - } -} - -/* - * 256-bit compare for equality - * - * in: x in [0, 2^256) - * y in [0, 2^256) - * out: 0 if x == y, unspecified non-zero otherwise - */ -inline uint32_t u256_diff0(const uint32_t x[8]) -{ - uint32_t diff = 0; - for (unsigned i = 0; i < 8; i++) { - diff |= x[i]; - } - return diff; -} - -inline uint64_t u32_muladd64(uint32_t x, uint32_t y, uint32_t z, uint32_t t) -{ - /* x = xl + 2**16 xh, y = yl + 2**16 yh */ - const uint16_t xl = (uint16_t) x; - const uint16_t yl = (uint16_t) y; - const uint16_t xh = x >> 16; - const uint16_t yh = y >> 16; - - /* x*y = xl*yl + 2**16 (xh*yl + yl*yh) + 2**32 xh*yh - * = lo + 2**16 (m1 + m2 ) + 2**32 hi */ - const uint32_t lo = (uint32_t) xl * yl; - const uint32_t m1 = (uint32_t) xh * yl; - const uint32_t m2 = (uint32_t) xl * yh; - const uint32_t hi = (uint32_t) xh * yh; - - uint64_t acc = lo + ((uint64_t) (hi + (m1 >> 16) + (m2 >> 16)) << 32); - acc += m1 << 16; - acc += m2 << 16; - acc += z; - acc += t; - - return acc; -} -inline uint32_t u288_muladd(uint32_t z[9], uint32_t x, const uint32_t y[8]) -{ - uint32_t carry = 0; - - for (unsigned i = 0; i < 8; i++) { - const uint64_t prod = u32_muladd64(x, y[i], z[i], carry); - z[i] = static_cast(prod); - carry = static_cast(prod >> 32); - } - - uint64_t sum = (uint64_t) z[8] + carry; - z[8] = (uint32_t) sum; - carry = (uint32_t) (sum >> 32); - - return carry; -} - -/* - * 288-bit in-place right shift by 32 bits - * - * in: z in [0, 2^288) - * c in [0, 2^32) - * out: z_out = z_in div 2^32 + c * 2^256 - * = (z_in + c * 2^288) div 2^32 - * - * This is a helper for Montgomery multiplication. - */ -inline void u288_rshift32(uint32_t z[9], uint32_t c) -{ - for (unsigned i = 0; i < 8; i++) { - z[i] = z[i + 1]; - } - z[8] = c; -} - -/* - * 256-bit import from big-endian bytes - * - * in: p = p0, ..., p31 - * out: z = p0 * 2^248 + p1 * 2^240 + ... + p30 * 2^8 + p31 - */ -inline void u256_from_bytes(uint32_t z[8], const uint8_t p[32]) -{ - for (unsigned i = 0; i < 8; i++) { - unsigned j = 4 * (7 - i); - z[i] = ((uint32_t) p[j + 0] << 24) | - ((uint32_t) p[j + 1] << 16) | - ((uint32_t) p[j + 2] << 8) | - ((uint32_t) p[j + 3] << 0); - } -} - -/* - * 256-bit export to big-endian bytes - * - * in: z in [0, 2^256) - * out: p = p0, ..., p31 such that - * z = p0 * 2^248 + p1 * 2^240 + ... + p30 * 2^8 + p31 - */ -inline void u256_to_bytes(uint8_t p[32], const uint32_t z[8]) -{ - for (unsigned i = 0; i < 8; i++) { - unsigned j = 4 * (7 - i); - p[j + 0] = (uint8_t) (z[i] >> 24); - p[j + 1] = (uint8_t) (z[i] >> 16); - p[j + 2] = (uint8_t) (z[i] >> 8); - p[j + 3] = (uint8_t) (z[i] >> 0); - } -} - -/********************************************************************** - * - * Operations modulo a 256-bit prime m - * - * These are done in the Montgomery domain, that is x is represented by - * x * 2^256 mod m - * Numbers need to be converted to that domain before computations, - * and back from it afterwards. - * - * Inversion is computed using Fermat's little theorem. - * - * Assumptions on m: - * - Montgomery operations require that m is odd. - * - Fermat's little theorem require it to be a prime. - * - m256_inv() further requires that m % 2^32 >= 2. - * - m256_inv() also assumes that the value of m is not a secret. - * - * In practice operations are done modulo the curve's p and n, - * both of which satisfy those assumptions. - * - **********************************************************************/ - -/* - * Data associated to a modulus for Montgomery operations. - * - * m in [0, 2^256) - the modulus itself, must be odd - * R2 = 2^512 mod m - * ni = -m^-1 mod 2^32 - */ -typedef struct { - uint32_t m[8]; - uint32_t R2[8]; - uint32_t ni; -} -m256_mod; - -/* - * Data for Montgomery operations modulo the curve's p - */ -inline constexpr m256_mod p256_p = { - { /* the curve's p */ - 0xFFFFFFFF, 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, - 0x00000000, 0x00000000, 0x00000001, 0xFFFFFFFF, - }, - { /* 2^512 mod p */ - 0x00000003, 0x00000000, 0xffffffff, 0xfffffffb, - 0xfffffffe, 0xffffffff, 0xfffffffd, 0x00000004, - }, - 0x00000001, /* -p^-1 mod 2^32 */ -}; - -/* - * Data for Montgomery operations modulo the curve's n - */ -inline constexpr m256_mod p256_n = { - { /* the curve's n */ - 0xFC632551, 0xF3B9CAC2, 0xA7179E84, 0xBCE6FAAD, - 0xFFFFFFFF, 0xFFFFFFFF, 0x00000000, 0xFFFFFFFF, - }, - { /* 2^512 mod n */ - 0xbe79eea2, 0x83244c95, 0x49bd6fa6, 0x4699799c, - 0x2b6bec59, 0x2845b239, 0xf3d95620, 0x66e12d94, - }, - 0xee00bc4f, /* -n^-1 mod 2^32 */ -}; - -/* - * Modular addition - * - * in: x, y in [0, m) - * mod must point to a valid m256_mod structure - * out: z = (x + y) mod m, in [0, m) - * - * Note: as a memory area, z must be either equal to x or y, or not overlap. - */ -inline void m256_add(uint32_t z[8], - const uint32_t x[8], const uint32_t y[8], - const m256_mod *mod) -{ - uint32_t r[8]; - uint32_t carry_add = u256_add(z, x, y); - uint32_t carry_sub = u256_sub(r, z, mod->m); - /* Need to subract m if: - * x+y >= 2^256 > m (that is, carry_add == 1) - * OR z >= m (that is, carry_sub == 0) */ - uint32_t use_sub = carry_add | (1 - carry_sub); - u256_cmov(z, r, use_sub); -} - -/* - * Modular addition mod p - * - * in: x, y in [0, p) - * out: z = (x + y) mod p, in [0, p) - * - * Note: as a memory area, z must be either equal to x or y, or not overlap. - */ -inline void m256_add_p(uint32_t z[8], - const uint32_t x[8], const uint32_t y[8]) -{ - m256_add(z, x, y, &p256_p); -} - -/* - * Modular subtraction - * - * in: x, y in [0, m) - * mod must point to a valid m256_mod structure - * out: z = (x - y) mod m, in [0, m) - * - * Note: as a memory area, z must be either equal to x or y, or not overlap. - */ -inline void m256_sub(uint32_t z[8], - const uint32_t x[8], const uint32_t y[8], - const m256_mod *mod) -{ - uint32_t r[8]; - uint32_t carry = u256_sub(z, x, y); - (void) u256_add(r, z, mod->m); - /* Need to add m if and only if x < y, that is carry == 1. - * In that case z is in [2^256 - m + 1, 2^256 - 1], so the - * addition will have a carry as well, which cancels out. */ - u256_cmov(z, r, carry); -} - -/* - * Modular subtraction mod p - * - * in: x, y in [0, p) - * out: z = (x + y) mod p, in [0, p) - * - * Note: as a memory area, z must be either equal to x or y, or not overlap. - */ -inline void m256_sub_p(uint32_t z[8], - const uint32_t x[8], const uint32_t y[8]) -{ - m256_sub(z, x, y, &p256_p); -} - -/* - * Montgomery modular multiplication - * - * in: x, y in [0, m) - * mod must point to a valid m256_mod structure - * out: z = (x * y) / 2^256 mod m, in [0, m) - * - * Note: as a memory area, z may overlap with x or y. - */ -inline void m256_mul(uint32_t z[8], - const uint32_t x[8], const uint32_t y[8], - const m256_mod *mod) -{ - /* - * Algorithm 14.36 in Handbook of Applied Cryptography with: - * b = 2^32, n = 8, R = 2^256 - */ - uint32_t m_prime = mod->ni; - uint32_t a[9]; - - for (unsigned i = 0; i < 9; i++) { - a[i] = 0; - } - - for (unsigned i = 0; i < 8; i++) { - /* the "mod 2^32" is implicit from the type */ - uint32_t u = (a[0] + x[i] * y[0]) * m_prime; - - /* a = (a + x[i] * y + u * m) div b */ - uint32_t c = u288_muladd(a, x[i], y); - c += u288_muladd(a, u, mod->m); - u288_rshift32(a, c); - } - - /* a = a > m ? a - m : a */ - uint32_t carry_add = a[8]; // 0 or 1 since a < 2m, see HAC Note 14.37 - uint32_t carry_sub = u256_sub(z, a, mod->m); - uint32_t use_sub = carry_add | (1 - carry_sub); // see m256_add() - u256_cmov(z, a, 1 - use_sub); -} - -/* - * Montgomery modular multiplication modulo p. - * - * in: x, y in [0, p) - * out: z = (x * y) / 2^256 mod p, in [0, p) - * - * Note: as a memory area, z may overlap with x or y. - */ -inline void m256_mul_p(uint32_t z[8], - const uint32_t x[8], const uint32_t y[8]) -{ - m256_mul(z, x, y, &p256_p); -} - -/* - * In-place conversion to Montgomery form - * - * in: z in [0, m) - * mod must point to a valid m256_mod structure - * out: z_out = z_in * 2^256 mod m, in [0, m) - */ -inline void m256_prep(uint32_t z[8], const m256_mod *mod) -{ - m256_mul(z, z, mod->R2, mod); -} - -/* - * In-place conversion from Montgomery form - * - * in: z in [0, m) - * mod must point to a valid m256_mod structure - * out: z_out = z_in / 2^256 mod m, in [0, m) - * That is, z_in was z_actual * 2^256 mod m, and z_out is z_actual - */ -inline void m256_done(uint32_t z[8], const m256_mod *mod) -{ - uint32_t one[8]; - u256_set32(one, 1); - m256_mul(z, z, one, mod); -} - -/* - * Set to 32-bit value - * - * in: x in [0, 2^32) - * mod must point to a valid m256_mod structure - * out: z = x * 2^256 mod m, in [0, m) - * That is, z is set to the image of x in the Montgomery domain. - */ -inline void m256_set32(uint32_t z[8], uint32_t x, const m256_mod *mod) -{ - u256_set32(z, x); - m256_prep(z, mod); -} - -/* - * Modular inversion in Montgomery form - * - * in: x in [0, m) - * mod must point to a valid m256_mod structure - * such that mod->m % 2^32 >= 2, assumed to be public. - * out: z = x^-1 * 2^512 mod m if x != 0, - * z = 0 if x == 0 - * That is, if x = x_actual * 2^256 mod m, then - * z = x_actual^-1 * 2^256 mod m - * - * Note: as a memory area, z may overlap with x. - */ -inline void m256_inv(uint32_t z[8], const uint32_t x[8], - const m256_mod *mod) -{ - /* - * Use Fermat's little theorem to compute x^-1 as x^(m-2). - * - * Take advantage of the fact that both p's and n's least significant limb - * is at least 2 to perform the subtraction on the flight (no carry). - * - * Use plain right-to-left binary exponentiation; - * branches are OK as the exponent is not a secret. - */ - uint32_t bitval[8]; - u256_cmov(bitval, x, 1); /* copy x before writing to z */ - - m256_set32(z, 1, mod); - - unsigned i = 0; - uint32_t limb = mod->m[i] - 2; - while (1) { - for (unsigned j = 0; j < 32; j++) { - if ((limb & 1) != 0) { - m256_mul(z, z, bitval, mod); - } - m256_mul(bitval, bitval, bitval, mod); - limb >>= 1; - } - - if (i == 7) - break; - - i++; - limb = mod->m[i]; - } -} - -/* - * Import modular integer from bytes to Montgomery domain - * - * in: p = p0, ..., p32 - * mod must point to a valid m256_mod structure - * out: z = (p0 * 2^248 + ... + p31) * 2^256 mod m, in [0, m) - * return 0 if the number was already in [0, m), or -1. - * z may be incorrect and must be discared when -1 is returned. - */ -inline int m256_from_bytes(uint32_t z[8], - const uint8_t p[32], const m256_mod *mod) -{ - u256_from_bytes(z, p); - - uint32_t t[8]; - uint32_t lt_m = u256_sub(t, z, mod->m); - if (lt_m != 1) - return -1; - - m256_prep(z, mod); - return 0; -} - -/* - * Export modular integer from Montgomery domain to bytes - * - * in: z in [0, 2^256) - * mod must point to a valid m256_mod structure - * out: p = p0, ..., p31 such that - * z = (p0 * 2^248 + ... + p31) * 2^256 mod m - */ -inline void m256_to_bytes(uint8_t p[32], - const uint32_t z[8], const m256_mod *mod) -{ - uint32_t zi[8]; - u256_cmov(zi, z, 1); - m256_done(zi, mod); - - u256_to_bytes(p, zi); -} - -/********************************************************************** - * - * Operations on curve points - * - * Points are represented in two coordinates system: - * - affine (x, y) - extended to represent 0 (see below) - * - jacobian (x:y:z) - * In either case, coordinates are integers modulo p256_p and - * are always represented in the Montgomery domain. - * - * For background on jacobian coordinates, see for example [GECC] 3.2.2: - * - conversions go (x, y) -> (x:y:1) and (x:y:z) -> (x/z^2, y/z^3) - * - the curve equation becomes y^2 = x^3 - 3 x z^4 + b z^6 - * - 0 (aka the origin aka point at infinity) is (x:y:0) with y^2 = x^3. - * - point negation goes -(x:y:z) = (x:-y:z) - * - * Normally 0 (the point at infinity) can't be represented in affine - * coordinates. However we extend affine coordinates with the convention that - * (0, 0) (which is normally not a point on the curve) is interpreted as 0. - * - * References: - * - [GECC]: Guide to Elliptic Curve Cryptography; Hankerson, Menezes, - * Vanstone; Springer, 2004. - * - [CMO98]: Efficient Elliptic Curve Exponentiation Using Mixed Coordinates; - * Cohen, Miyaji, Ono; Springer, ASIACRYPT 1998. - * https://link.springer.com/content/pdf/10.1007/3-540-49649-1_6.pdf - * - [RCB15]: Complete addition formulas for prime order elliptic curves; - * Renes, Costello, Batina; IACR e-print 2015-1060. - * https://eprint.iacr.org/2015/1060.pdf - * - **********************************************************************/ - -/* - * The curve's b parameter in the Short Weierstrass equation - * y^2 = x^3 - 3*x + b - * Compared to the standard, this is converted to the Montgomery domain. - */ -inline constexpr uint32_t p256_gx[8] = { /* G_x * 2^256 mod p */ - 0x18a9143c, 0x79e730d4, 0x5fedb601, 0x75ba95fc, - 0x77622510, 0x79fb732b, 0xa53755c6, 0x18905f76, -}; -inline constexpr uint32_t p256_gy[8] = { /* G_y * 2^256 mod p */ - 0xce95560a, 0xddf25357, 0xba19e45c, 0x8b4ab8e4, - 0xdd21f325, 0xd2e88688, 0x25885d85, 0x8571ff18, -}; - -inline void point_to_affine(uint32_t x[8], uint32_t y[8], uint32_t z[8]) -{ - uint32_t t[8]; - - m256_inv(z, z, &p256_p); /* z = z^-1 */ - - m256_mul_p(t, z, z); /* t = z^-2 */ - m256_mul_p(x, x, t); /* x = x * z^-2 */ - - m256_mul_p(t, t, z); /* t = z^-3 */ - m256_mul_p(y, y, t); /* y = y * z^-3 */ -} - -inline void point_double(uint32_t x[8], uint32_t y[8], uint32_t z[8]) -{ - /* - * This is formula 6 from [CMO98], cited as complete in [RCB15] (table 1). - * Notations as in the paper, except u added and t ommited (it's x3). - */ - uint32_t m[8], s[8], u[8]; - - /* m = 3 * x^2 + a * z^4 = 3 * (x + z^2) * (x - z^2) */ - m256_mul_p(s, z, z); - m256_add_p(m, x, s); - m256_sub_p(u, x, s); - m256_mul_p(s, m, u); - m256_add_p(m, s, s); - m256_add_p(m, m, s); - - /* s = 4 * x * y^2 */ - m256_mul_p(u, y, y); - m256_add_p(u, u, u); /* u = 2 * y^2 (used below) */ - m256_mul_p(s, x, u); - m256_add_p(s, s, s); - - /* u = 8 * y^4 (not named in the paper, first term of y3) */ - m256_mul_p(u, u, u); - m256_add_p(u, u, u); - - /* x3 = t = m^2 - 2 * s */ - m256_mul_p(x, m, m); - m256_sub_p(x, x, s); - m256_sub_p(x, x, s); - - /* z3 = 2 * y * z */ - m256_mul_p(z, y, z); - m256_add_p(z, z, z); - - /* y3 = -u + m * (s - t) */ - m256_sub_p(y, s, x); - m256_mul_p(y, y, m); - m256_sub_p(y, y, u); -} - -inline void point_add(uint32_t x1[8], uint32_t y1[8], uint32_t z1[8], - const uint32_t x2[8], const uint32_t y2[8]) -{ - /* - * This is formula 5 from [CMO98], with z2 == 1 substituted. We use - * intermediates with neutral names, and names from the paper in comments. - */ - uint32_t t1[8], t2[8], t3[8]; - - /* u1 = x1 and s1 = y1 (no computations) */ - - /* t1 = u2 = x2 z1^2 */ - m256_mul_p(t1, z1, z1); - m256_mul_p(t2, t1, z1); - m256_mul_p(t1, t1, x2); - - /* t2 = s2 = y2 z1^3 */ - m256_mul_p(t2, t2, y2); - - /* t1 = h = u2 - u1 */ - m256_sub_p(t1, t1, x1); /* t1 = x2 * z1^2 - x1 */ - - /* t2 = r = s2 - s1 */ - m256_sub_p(t2, t2, y1); - - /* z3 = z1 * h */ - m256_mul_p(z1, z1, t1); - - /* t1 = h^3 */ - m256_mul_p(t3, t1, t1); - m256_mul_p(t1, t3, t1); - - /* t3 = x1 * h^2 */ - m256_mul_p(t3, t3, x1); - - /* x3 = r^2 - 2 * x1 * h^2 - h^3 */ - m256_mul_p(x1, t2, t2); - m256_sub_p(x1, x1, t3); - m256_sub_p(x1, x1, t3); - m256_sub_p(x1, x1, t1); - - /* y3 = r * (x1 * h^2 - x3) - y1 h^3 */ - m256_sub_p(t3, t3, x1); - m256_mul_p(t3, t3, t2); - m256_mul_p(t1, t1, y1); - m256_sub_p(y1, t3, t1); -} - -inline void scalar_mult(uint32_t rx[8], uint32_t ry[8], - const uint32_t px[8], const uint32_t py[8], - const uint32_t s[8]) -{ - /* - * We use a signed binary ladder, see for example slides 10-14 of - * http://ecc2015.math.u-bordeaux1.fr/documents/hamburg.pdf but with - * implicit recoding, and a different loop initialisation to avoid feeding - * 0 to our addition formulas, as they don't support it. - */ - uint32_t s_odd[8], py_neg[8], py_use[8], rz[8]; - - /* - * Make s odd by replacing it with n - s if necessary. - * - * If s was odd, we'll have s_odd = s, and define P' = P. - * Otherwise, we'll have s_odd = n - s and define P' = -P. - * - * Either way, we can compute s * P as s_odd * P'. - */ - u256_sub(s_odd, p256_n.m, s); /* no carry, result still in [1, n-1] */ - uint32_t negate = ~s[0] & 1; - u256_cmov(s_odd, s, 1 - negate); - - /* Compute py_neg = - py mod p (that's the y coordinate of -P) */ - u256_set32(py_use, 0); - m256_sub_p(py_neg, py_use, py); - - /* Initialize R = P' = (x:(-1)^negate * y:1) */ - u256_cmov(rx, px, 1); - u256_cmov(ry, py, 1); - m256_set32(rz, 1, &p256_p); - u256_cmov(ry, py_neg, negate); - - /* - * For any odd number s_odd = b255 ... b1 1, we have - * s_odd = 2^255 + 2^254 sbit(b255) + ... + 2 sbit(b2) + sbit(b1) - * writing - * sbit(b) = 2 * b - 1 = b ? 1 : -1 - * - * Use that to compute s_odd * P' by repeating R = 2 * R +- P': - * s_odd * P' = 2 * ( ... (2 * P' + sbit(b255) P') ... ) + sbit(b1) P' - * - * The loop invariant is that when beginning an iteration we have - * R = s_i P' - * with - * s_i = 2^(255-i) + 2^(254-i) sbit(b_255) + ... - * where the sum has 256 - i terms. - * - * When updating R we need to make sure the input to point_add() is - * neither 0 not +-P'. Since that input is 2 s_i P', it is sufficient to - * see that 1 < 2 s_i < n-1. The lower bound is obvious since s_i is a - * positive integer, and for the upper bound we distinguish three cases. - * - * If i > 1, then s_i < 2^254, so 2 s_i < 2^255 < n-1. - * Otherwise, i == 1 and we have 2 s_i = s_odd - sbit(b1). - * If s_odd <= n-4, then 2 s_1 <= n-3. - * Otherwise, s_odd = n-2, and for this curve's value of n, - * we have b1 == 1, so sbit(b1) = 1 and 2 s_1 <= n-3. - */ - for (unsigned i = 255; i > 0; i--) { - uint32_t bit = (s_odd[i / 32] >> i % 32) & 1; - - /* set (px, py_use) = sbit(bit) P' = sbit(bit) * (-1)^negate P */ - u256_cmov(py_use, py, bit ^ negate); - u256_cmov(py_use, py_neg, (1 - bit) ^ negate); - - /* Update R = 2 * R +- P' */ - point_double(rx, ry, rz); - point_add(rx, ry, rz, px, py_use); - } - - point_to_affine(rx, ry, rz); -} - -inline int scalar_from_bytes(uint32_t s[8], const uint8_t p[32]) -{ - u256_from_bytes(s, p); - - uint32_t r[8]; - uint32_t lt_n = u256_sub(r, s, p256_n.m); - - u256_set32(r, 1); - uint32_t lt_1 = u256_sub(r, s, r); - - if (lt_n && !lt_1) - return 0; - - return -1; -} - -inline void ecdsa_m256_mod_n(uint32_t x[8]) -{ - uint32_t t[8]; - uint32_t c = u256_sub(t, x, p256_n.m); - u256_cmov(x, t, 1 - c); -} - - -} -#if defined(_MSC_VER) && !defined(__GNUC__) -#pragma warning(pop) -#endif diff --git a/include/webfront/tls/detail/Protocol.hpp b/include/webfront/tls/detail/Protocol.hpp index f6b2f2ea..a02d9e95 100644 --- a/include/webfront/tls/detail/Protocol.hpp +++ b/include/webfront/tls/detail/Protocol.hpp @@ -193,21 +193,22 @@ struct Traffic { record[3] = static_cast((size + 17) >> 8); record[4] = static_cast(size + 17); record[5 + size] = type; - auto ctx = context(); - auto payload = record.data() + 5; - mono::crypto_aead_write(&ctx, payload, payload + size + 1, record.data(), 5, payload, size + 1); - mono::crypto_wipe(&ctx, sizeof(ctx)); + const auto nonce = nextNonce(); + auto payload = std::span(record).subspan(5, size + 1); + chachaXor(key, nonce, payload); + std::ranges::copy(polyTag(key, nonce, View(record).first(5), payload), record.data() + 6 + size); } Byte open(View header, Bytes& payload) { if (payload.size() < 17) throw Error("short ciphertext"); - auto ctx = context(); - const auto size = payload.size() - 16; - const auto mismatch = mono::crypto_aead_read(&ctx, payload.data(), payload.data() + size, header.data(), header.size(), payload.data(), size); - mono::crypto_wipe(&ctx, sizeof(ctx)); - if (mismatch) + const auto nonce = nextNonce(); + const auto size = payload.size() - 16; + const auto ciphertext = std::span(payload).first(size); + const auto expectedTag = polyTag(key, nonce, header, ciphertext); + if (!equalSecret(expectedTag, View(payload).subspan(size))) throw Error("invalid authentication tag", 20); + chachaXor(key, nonce, ciphertext); payload.resize(size); while (!payload.empty() && payload.back() == 0) payload.pop_back(); @@ -221,16 +222,14 @@ struct Traffic { } private: - mono::crypto_aead_ctx context() { + Nonce nextNonce() { if (sequence == UINT64_MAX) throw Error("record sequence exhausted", 80); auto nonce = iv; for (unsigned i = 0; i != 8; ++i) nonce[11 - i] ^= static_cast(sequence >> (8 * i)); ++sequence; - mono::crypto_aead_ctx ctx; - mono::crypto_aead_init_ietf(&ctx, key.data(), nonce.data()); - return ctx; + return nonce; } Secret<> key{}; std::array iv{}; diff --git a/test/unit/TlsTests.cpp b/test/unit/TlsTests.cpp index 2703d090..86fd6612 100644 --- a/test/unit/TlsTests.cpp +++ b/test/unit/TlsTests.cpp @@ -41,30 +41,32 @@ const Scenario tlsPrimitives("TLS cryptographic vectors", {"fast"}, [] { require(std::ranges::equal(View(second).first(10), View(expected).subspan(32))); }); then("X25519 matches RFC 7748 section 6.1", [] { - const auto scalar = tlsHex("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"); - const auto peer = tlsHex("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"); - tls::Digest output; - tls::mono::crypto_x25519_public_key(output.data(), scalar.data()); + const auto scalar = tlsHex("77076d0a7318a57d3c16c17251b26645df4c2f87ebc0992ab177fba51db92c2a"); + const auto peer = tlsHex("de9edb7d7b7dc1b4d35b61c2ece435373f8343c85b78674dadfc7e146f882b4f"); + const auto secret = View(scalar).first<32>(); + auto output = tls::x25519(secret, tls::Digest{9}); require(std::ranges::equal(output, tlsHex("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"))); - tls::mono::crypto_x25519(output.data(), scalar.data(), peer.data()); + output = tls::x25519(secret, View(peer).first<32>()); require(std::ranges::equal(output, tlsHex("4a5d9d5ba4ce2de1728e3bf480350f25e07e21c947d19e3376f09b3c1e161742"))); }); then("the P-256 signature matches RFC 6979 A.2.5", [] { const auto scalar = tlsHex("c9afa9d845ba75166b5c215767b1d6934e50c3db36e89b127b8a622b120f6721"); - require(tls::sign(scalar, tls::hash(tls::bytes("sample"))) + require(tls::sign(View(scalar).first<32>(), tls::hash(tls::bytes("sample"))) == tlsHex("3046022100efd48b2aacb6a8fd1140dd9cd45e81d69d2c877b56aaf991c34d0ea84eaf3716" "022100f7cb1c942d657c41d436c7a1b6e29f65f3e900dbb9aff4064dc4ab2f843acda8")); }); then("ChaCha20-Poly1305 matches RFC 8439 section 2.8.2", [] { - const auto key = tlsHex("808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f"); - const auto nonce = tlsHex("070000004041424344454647"); - const auto aad = tlsHex("50515253c0c1c2c3c4c5c6c7"); - const auto message = tls::bytes("Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it."); - Bytes ciphertext(message.size()); - std::array tag; - tls::mono::crypto_aead_ctx context; - tls::mono::crypto_aead_init_ietf(&context, key.data(), nonce.data()); - tls::mono::crypto_aead_write(&context, ciphertext.data(), tag.data(), aad.data(), aad.size(), message.data(), message.size()); + const auto key = tlsHex("808182838485868788898a8b8c8d8e8f909192939495969798999a9b9c9d9e9f"); + const auto nonce = tlsHex("070000004041424344454647"); + const auto aad = tlsHex("50515253c0c1c2c3c4c5c6c7"); + const auto message = tls::bytes("Ladies and Gentlemen of the class of '99: If I could offer you only one tip for the future, sunscreen would be it."); + tls::Digest secret; + tls::Nonce iv; + std::ranges::copy(key, secret.begin()); + std::ranges::copy(nonce, iv.begin()); + Bytes ciphertext(message.begin(), message.end()); + tls::chachaXor(secret, iv, ciphertext); + const auto tag = tls::polyTag(secret, iv, aad, ciphertext); require(ciphertext == tlsHex("d31a8d34648e60db7b86afbc53ef7ec2a4aded51296e08fea9e2b5a736ee62d63dbea45e8ca9671282fafb69da92728b" "1a71de0a9e060b2905d6a5b67ecd3b3692ddbd7f2d778b8c9803aee328091b58fab324e4fad675945585808b4831d7bc" @@ -80,8 +82,7 @@ const Scenario tlsHandshakeTrace("TLS 1.3 handshake against RFC 8448", {"fast"}, given("the client and server hellos from section 3", [&] { const auto parsed = tls::parseHello(hello, false); const auto scalar = tlsHex("b1580eeadf6dd589b8ef4f2d5652578cc810e9980191ec8d058308cea216a21e"); - tls::Digest shared; - tls::mono::crypto_x25519(shared.data(), scalar.data(), parsed.share.data()); + const auto shared = tls::x25519(View(scalar).first<32>(), parsed.share.first<32>()); tls::Sha256 transcript; transcript.update(hello); transcript.update(server); From 3e421b7679099a21988a2e42efeee186abb6594b Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:16:30 +0100 Subject: [PATCH 03/24] Preserve explicit remote reads and harden TLS lifecycle (#631) --- docs/CHANGELOG.md | 1 + docs/TLS.md | 43 ++++++-- docs/adr/ADR-020-services-systeme.md | 20 ++-- docs/adr/ADR-024-tls-integre.md | 5 +- include/webfront/ReadBinding.hpp | 4 +- include/webfront/WebFront.hpp | 21 ++-- include/webfront/http/HTTPServer.hpp | 3 +- include/webfront/tls/Credentials.hpp | 12 ++- include/webfront/tls/Server.hpp | 89 ++++++---------- include/webfront/tls/detail/ChaChaPoly.hpp | 62 ++++++----- include/webfront/tls/detail/Protocol.hpp | 77 ++++++++++++-- test/unit/ReadBindingTests.cpp | 10 +- test/unit/TlsTests.cpp | 117 +++++++++++++++++++++ test/web/CMakeLists.txt | 15 +++ test/web/JasmineTest.cpp | 2 +- test/web/TlsInterop.cpp | 27 +++++ test/web/TlsInterop.py | 61 +++++++++++ test/web/fixtures/tls/README.md | 3 + test/web/fixtures/tls/key-sec1.pem | 5 + 19 files changed, 446 insertions(+), 131 deletions(-) create mode 100644 test/web/TlsInterop.cpp create mode 100644 test/web/TlsInterop.py create mode 100644 test/web/fixtures/tls/key-sec1.pem diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 0df1f995..31120602 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -14,6 +14,7 @@ these entries stays in the GitHub releases and the Git history. - The CEF profile is now `cef_cache/`, not `cef_cache`: an application starts with an empty profile (localStorage, cookies); to keep the data, move the old contents of `cef_cache` into `cef_cache/` once (#617, `docs/HOST_INTEGRATION.md`). ### Added +- Use a custom network provider with `DeveloperAppWithNetwork`. The `BasicDeveloperApp` alias selects the existing TCP provider (#631). - Serve HTTPS and WSS with the optional header-only TLS 1.3 listener and reload its PEM identity after renewal (#631, `docs/TLS.md`). - Start an application with no port setting when `9002` is taken: an empty `WebFrontConfig::port` falls back to a free port, a chosen port is never replaced, and CEF and WebKitGTK give each live instance its own profile directory (#617, `docs/HOST_INTEGRATION.md`). - Start several applications side by side: the default port follows `WEBFRONT_PORT` (a number from 0 to 65535, `0` asks for a free port, `9002` remains the default), the examples take `--port`, the server announces the port really bound, and a failed bind names the address, the port and the cause (#617, `docs/HOST_INTEGRATION.md`). diff --git a/docs/TLS.md b/docs/TLS.md index dc5ffc4f..c2a8f07f 100644 --- a/docs/TLS.md +++ b/docs/TLS.md @@ -4,6 +4,11 @@ Include `` and use `webfront::tls::WebFront<>` for a TLS-only listener. It serves HTTP/1.1 and the WebFront bridge over WSS on the same port. The component is header-only and links without a TLS library. +> The TLS profile is proposed and its constant-time behavior has not been audited. +> Limit access to controlled networks while it is being qualified. For an +> Internet-facing listener, use a deployment proxy with connection admission +> controls and handshake deadlines. + ```cpp #include @@ -11,9 +16,8 @@ int main() { auto credentials = std::make_shared( "/path/to/fullchain.pem", "/path/to/privkey.pem"); webfront::tls::WebFront app({ - .address = "0.0.0.0", + .address = "127.0.0.1", .port = "8443", - .contentPolicy = {.bridgeAllowedOrigins = {"https://app.example.com:8443"}}, .tlsCredentials = credentials, }); app.cppFunction("greeting", [] { return std::string("Hello over HTTPS"); }); @@ -23,7 +27,10 @@ int main() { Use an ECDSA P-256 leaf certificate whose SAN covers the DNS name users visit. Supply the PEM chain in leaf-first order and an unencrypted PEM private key -in PKCS#8 or SEC1 form. Give the application account read access to the key. +as a single `PRIVATE KEY` (PKCS#8) or `EC PRIVATE KEY` (SEC1) block. The files +accept whitespace around the PEM blocks. Extra text such as `Bag Attributes` +and separate `EC PARAMETERS` blocks are refused. Give the application account +read access to the key. After the certificate manager has written both renewed files, call `credentials->reload(fullchain, privkey)` from the application's renewal hook. It checks that the leaf and key match before publishing them to new handshakes. @@ -33,9 +40,11 @@ continue with their negotiated keys. Open the deployment URL in the browser. When using `show()` on a local bind, the certificate must cover the configured address used in the window URL. The browser verifies the certificate chain and server name. WebFront applies -the usual bridge origin policy, and the file-service binding cookie has the -`Secure` attribute on the TLS listener. Client authentication and authorization -belong to the application. +the usual bridge origin policy. The file-service binding cookie carries `Secure`. +File reads for non-associated clients require an explicit `remoteFileTransport` +declaration, typically `httpsByDeployment`. The default `refused` applies to +TLS listeners as well. Client authentication and authorization belong to the +application. The initial profile negotiates TLS 1.3, X25519, ECDSA P-256 with SHA-256 and `TLS_CHACHA20_POLY1305_SHA256`. Clients must offer this suite. The profile @@ -43,12 +52,18 @@ uses full handshakes and HTTP/1.1. Where clients require AES-GCM, HTTP/2, or another certificate type, terminate TLS at the deployment proxy and configure `httpsByDeployment` if file-service reads are enabled. -The handshake parser limits ClientHello to 64 KiB and the receive buffer to -16,640 bytes of ciphertext. Connection admission and idle timeouts are -deployment concerns. The [decision record](adr/ADR-024-tls-integre.md) describes -the component's scope and qualification. +The handshake parser limits ClientHello to 64 KiB and 128 extensions, and the +receive buffer to 16,640 bytes of ciphertext. Incoming handshake messages may +span records, with one message at a time. The server supports the ClientHello, +optional second ClientHello and Finished sequence described in the +[decision record](adr/ADR-024-tls-integre.md). + +The two X25519 operations and the CertificateVerify signature run on the I/O +thread. Other connections wait while this work runs. An incomplete handshake +has no built-in deadline. Bursts of handshakes can delay established HTTP/WSS +connections, and idle handshakes can hold sockets and memory. -## Size and memory +## Size, memory and handshake time On Linux x86-64 with GCC 16.1, a minimal app with one bridge callback built at `-Os -DNDEBUG -ffunction-sections -fdata-sections -Wl,--gc-sections` gained @@ -61,3 +76,9 @@ for WSS than for WS. Giving each socket 16,384 bytes of an incomplete frame increased the WSS overhead to about 18.8 KiB per connection. These are process measurements after a warm-up connection and include allocator overhead. Thumb-2 size and peak memory during the handshake remain unmeasured. + +On an AMD Ryzen 9 3900X, an OpenSSL-backed Python client completed 200 +sequential loopback handshakes in 2.7 ms at the median and 3.8 ms at the 95th +percentile. The measurement starts after TCP connect and ends after TLS +negotiation, following ten warm-up connections. It includes both endpoints +and excludes HTTP traffic. diff --git a/docs/adr/ADR-020-services-systeme.md b/docs/adr/ADR-020-services-systeme.md index bc27181b..02697712 100644 --- a/docs/adr/ADR-020-services-systeme.md +++ b/docs/adr/ADR-020-services-systeme.md @@ -281,22 +281,21 @@ lève). - **Exposition du jeton.** Chaque réponse de lecture porte `Cache-Control: no-store` et `Referrer-Policy: no-referrer` ; le jeton n'apparaît dans aucun journal HTTP ni diagnostic (chemin masqué). Le cookie de liaison porte `Secure` lorsque la page est servie en HTTPS. -- **Transport** : lorsque WebFront termine TLS ([ADR-024](ADR-024-tls-integre.md)), le transport est connu - et le cookie de liaison est `Secure`. Pour le fournisseur TCP, le transport distant reste déclaré par le déploiement. +- **Transport.** Lorsque WebFront termine TLS ([ADR-024](ADR-024-tls-integre.md)), le cookie de liaison + porte `Secure`. Le transport est authentifié côté serveur et l'autorisation de lecture distante reste déclarative. Une connexion est de transport local seulement si elle est **associée à la vue d'un frontend intégré** : son secret est remis à la vue par l'adaptateur, dans le processus, sans transiter par une ligne de commande, une URL ou un historique. Aucun secret transmis au navigateur système (fragment de l'URL ouverte) n'atteste le transport : la ligne de commande et l'historique peuvent le divulguer, et un acteur qui le présente le premier depuis un navigateur distant serait accepté ; l'échec ultérieur de l'association légitime ne protège pas cette première connexion. Pour - toute connexion non associée sur le fournisseur TCP, dont celles du navigateur système, le transport est inconnu, quelle que soit son - adresse : lectures et écritures de fichiers y sont refusées, sauf déclaration explicite de l'application sur son - déploiement (`remoteFileTransport`) : + toute connexion non associée, dont celle du navigateur système, les lectures de fichiers sont refusées par défaut, + quel que soit le fournisseur. Une déclaration explicite de l'application (`remoteFileTransport`) est requise : - `refused` (défaut) ; - `loopbackAttested` : WebFront vérifie que le serveur n'écoute que sur la boucle locale ; l'intégrateur atteste qu'aucun mandataire ni tunnel ne l'expose et que la machine n'est pas partagée avec des utilisateurs non fiables. C'est la déclaration attendue d'une application de bureau qui utilise le navigateur système ; - `encryptedByDeployment` : le déploiement chiffre sous HTTP (VPN, tunnel) alors que le navigateur utilise `http://` : le cookie n'est pas `Secure`, qu'un navigateur refuserait ; - - `httpsByDeployment` : le navigateur atteint l'application en `https://` (mandataire inverse TLS) : le cookie est `Secure` ; + - `httpsByDeployment` : le navigateur atteint l'application en `https://` (TLS intégré ou mandataire inverse TLS) : le cookie est `Secure` ; - `plaintextAccepted` : réseau isolé de confiance. Hors la part vérifiée de `loopbackAttested`, ces déclarations sont des attestations de l'intégrateur, que WebFront ne @@ -376,7 +375,7 @@ limites par moteur. #452 est livré dans la version 1.2 (`beforeunload` n'est pa #455 est livré dans la version 1.4 : un fichier non encodé de taille connue est servi par plages (`Range: bytes=a-b`, `a-`, `-n` sur une seule plage : `206` avec `Content-Range`, `416` pour une plage qui commence après la fin, `Accept-Ranges: bytes`), en ne lisant que la plage demandée. Les plages multiples sont servies en entier (`200`) ; il n'y a pas de réponse `multipart/byteranges`. Les réponses encodées ou décodées par le repli annoncent `Accept-Ranges: none`. `If-Range` n'accepte qu'un `ETag` fort fourni par le fournisseur (`fs::File::setEntityTag`) ; WebFront n'en déduit aucun d'un chemin, d'une taille ou d'une date, qui peuvent désigner une autre version que le flux ouvert. Sans validateur (fichiers natifs, données embarquées), la plage conditionnée est servie en entier. Une route dynamique sert un fichier par plages avec `http::fileReply`. Le jeton de lecture reste donc réutilisable pour plusieurs requêtes `Range` ; leur liaison à la connexion propriétaire vient de #469. -#469 est livré dans la version 1.5 : `app.addReadRoute(préfixe, gestionnaire)` (sous `/webfront/services/`, hors `bind/`) et `ui.grantRead(route, chemin, ReadOptions)` appliquent les règles ci-dessus. Le jeton est `.` placé après le préfixe ; la requête est acceptée si le jeton est connu, non expiré, si la connexion propriétaire est ouverte et si l'un des cookies présentés désigne son client (sauf mode transférable : durée obligatoire de 15 minutes au plus). Un jeton est refusé de la même façon dans tous les cas (`403`, mêmes en-têtes). `WebFront.js` échange le secret reçu par `wfBind.exchange` contre le cookie (`GET /webfront/services/bind/`, puis `check`) et `webFront.bound` rejette avec une erreur explicite si le navigateur refuse le cookie. Le cookie est `Secure` si l'application déclare `httpsByDeployment` (le navigateur utilise `https://`) ; un tunnel chiffré sous `http://` (`encryptedByDeployment`) n'en reçoit pas, car le navigateur refuserait un cookie `Secure` reçu en HTTP. Sur le fournisseur TCP, un transport non local sans déclaration est refusé à l'émission du jeton et à chaque requête. +#469 est livré dans la version 1.5 : `app.addReadRoute(préfixe, gestionnaire)` (sous `/webfront/services/`, hors `bind/`) et `ui.grantRead(route, chemin, ReadOptions)` appliquent les règles ci-dessus. Le jeton est `.` placé après le préfixe ; la requête est acceptée si le jeton est connu, non expiré, si la connexion propriétaire est ouverte et si l'un des cookies présentés désigne son client (sauf mode transférable : durée obligatoire de 15 minutes au plus). Un jeton est refusé de la même façon dans tous les cas (`403`, mêmes en-têtes). `WebFront.js` échange le secret reçu par `wfBind.exchange` contre le cookie (`GET /webfront/services/bind/`, puis `check`) et `webFront.bound` rejette avec une erreur explicite si le navigateur refuse le cookie. Le cookie est `Secure` si l'application déclare `httpsByDeployment` (le navigateur utilise `https://`) ; un tunnel chiffré sous `http://` (`encryptedByDeployment`) n'en reçoit pas, car le navigateur refuserait un cookie `Secure` reçu en HTTP. Un transport non local sans déclaration est refusé à l'émission du jeton et à chaque requête. #460 est livré dans la version 1.7 (révision 3.0 de l'ADR-002, qui en donne le détail) : `fs::NativeStorage` applique les mesures de la section « Prescriptions » à toute opération (listage paginé, métadonnées, lecture, écriture par temporaire et renommage, création, suppression, renommage), avec les erreurs typées `storage.rootMoved`, `storage.confinementViolated`, `storage.unsafeDirectory`, `storage.linkRefused`… (`fs::StorageError`, une `BridgeError`). Quatre écarts aux prescriptions, sans affaiblir la garantie : sous Linux, la descente composant par composant est toujours employée plutôt qu'`openat2`, puisque chaque répertoire traversé doit être ouvert pour contrôler son propriétaire ; sous Windows, un point de réanalyse n'est jamais suivi (`LinkPolicy::followInside` ne vaut que sous POSIX) : une opération qui le traverserait ou le lirait échoue avec `linkRefused`, tandis que `status` le signale comme lien et que `remove` supprime le point lui-même, sans atteindre sa cible ; sous Windows, l'appartenance du répertoire à la racine se vérifie par le chemin final de son handle, les handles tenus empêchant déjà le déplacement ; sous Windows encore, le renommage passe par `NtSetInformationFile`, car `SetFileInformationByHandle` convertit un nom relatif en chemin absolu, que refuse un renommage relatif au handle d'un dossier (`STATUS_INVALID_PARAMETER`). Les tests Catch2 couvrent le stockage simulé, les sorties par liens (jonctions sous Windows), le remplacement concurrent d'un composant ou du fichier final par des points d'injection, une course répétée (POSIX), les déplacements d'un répertoire ou de la racine pendant la résolution, l'écriture du temporaire et avant la validation, et les propriétaires refusés ou admis (simulés, et `/tmp` réel). Les droits refusés par le système réel ne sont simulés que par `fs::MemoryStorage` : un test qui retire des droits sur disque échoue sous le superutilisateur. Le paquet `@webfront/services` (#461) est livré dans la version 1.8 : sources dans `js/services/` (`services`, objet gelé vide, et `selfTest()`), archive produite par `wf run services-package` avec le packager partagé de `@webfront/react`, servie par le registre de test, installée par la suite Jasmine qui l'importe ; `wf check` vérifie ses déclarations et `ServicesPackageContents` compare l'archive aux sources, à la licence et au SHA-512. Aucune ressource n'est ajoutée au cœur. L'étape 4 est achevée ; la façade du premier service s'ajoutera à ce paquet avec son épique. @@ -505,9 +504,10 @@ autorisations explicites, backend par connexion). peuvent lire les URL les unes des autres. - **Coût accepté :** un cookie de liaison par client, à qualifier dans chaque moteur ; les téléchargements gérés par l'adaptateur doivent le présenter. -- **Risque :** Avec le fournisseur TCP, WebFront ne peut pas attester le transport ; `remoteFileTransport` repose sur la - déclaration de l'intégrateur. Une déclaration fausse expose jeton et contenu. Par défaut, toute connexion non - associée est refusée, y compris celle du navigateur système. +- **Risque :** avec le fournisseur TCP, une attestation de transport fausse peut exposer le jeton et le contenu. + Avec le TLS intégré, le chiffrement du transport et le cookie `Secure` protègent l'échange. Le cookie lie un profil + de navigateur et l'application reste responsable de l'authentification du client. La valeur `refused` refuse par défaut + les lectures via toute connexion non associée. - **Coût accepté :** une application qui utilise le navigateur système doit déclarer `loopbackAttested` pour accéder aux fichiers de l'hôte ; sans cette déclaration, seuls les fichiers du client sont disponibles. - **Coût accepté :** les fichiers actifs ne s'affichent pas en ligne ; un aperçu HTML ou un SVG interactif exige une diff --git a/docs/adr/ADR-024-tls-integre.md b/docs/adr/ADR-024-tls-integre.md index e45738f6..b87e8e32 100644 --- a/docs/adr/ADR-024-tls-integre.md +++ b/docs/adr/ADR-024-tls-integre.md @@ -14,13 +14,14 @@ publie une paire complète après validation. Les handshakes en cours conservent Le navigateur valide la chaîne et le nom du serveur. TLS protège le transport, tandis que la politique d'origine continue de décider de l'accès au pont. Le profil ne demande aucun certificat au client. Le serveur sait que le transport est chiffré lorsqu'il termine TLS et marque alors le cookie de liaison `Secure`. +Les lectures de fichiers pour un client non associé restent soumises à une déclaration explicite (ADR-020). Le composant demeure header-only, sous `include/webfront/tls/`. Ses primitives sont implémentées dans WebFront à partir des spécifications [RFC 7748](https://www.rfc-editor.org/rfc/rfc7748), [RFC 8439](https://www.rfc-editor.org/rfc/rfc8439), [SEC 1](https://www.secg.org/sec1-v2.pdf), [SEC 2](https://www.secg.org/sec2-v2.pdf) et [RFC 6979](https://www.rfc-editor.org/rfc/rfc6979). La génération de secrets utilise l'aléa de l'OS. Les opérations -sur des secrets exigent des accès mémoire et un contrôle de flux indépendants de ces secrets, avec -vérification sur les compilateurs et architectures supportés. Les vecteurs des RFC, les refus de protocole, +sur des secrets visent des accès mémoire et un contrôle de flux indépendants de ces secrets. La qualification +exige une vérification du code produit par les compilateurs et architectures supportés. Cet audit reste à faire. Les vecteurs des RFC, les refus de protocole, le fuzzing et un test navigateur HTTPS/WSS font partie de la qualification. Les régressions de sécurité peuvent être signalées en privé aux mainteneurs. La maintenance du composant inclut la revue des primitives, le suivi des errata des spécifications et des mesures reproductibles de taille et de mémoire. diff --git a/include/webfront/ReadBinding.hpp b/include/webfront/ReadBinding.hpp index f97ca706..2db92873 100644 --- a/include/webfront/ReadBinding.hpp +++ b/include/webfront/ReadBinding.hpp @@ -283,7 +283,7 @@ class ReadBinding { const auto connection = connections.find(key); if (stopped || connection == connections.end()) throw ReadRefused("The connection is closed"); - if (!connection->second.local && !secureTransport && transport == RemoteFileTransport::refused) + if (!connection->second.local && transport == RemoteFileTransport::refused) throw ReadRefused("This connection is not the view of an embedded frontend: declare WebFrontConfig::remoteFileTransport to read files"); Grant record{.owner = key, .route = std::string(routeId), .secret = secret, .path = std::string(rest), .transferable = options.transferable, .expiry = {}, .context = std::make_shared(std::move(options.context))}; if (options.lifetime.count() > 0) { @@ -530,7 +530,7 @@ class ReadBinding { const auto connection = connections.find(grant.owner); if (connection == connections.end()) return std::nullopt; - if (!connection->second.local && !secureTransport && transport == RemoteFileTransport::refused) + if (!connection->second.local && transport == RemoteFileTransport::refused) return std::nullopt; if (!grant.transferable) { // Any one of the presented cookies may designate the owner's client (concurrent exchanges leave several). diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 3130e0d9..33ecf1cf 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -1220,19 +1220,26 @@ class BasicWF { * which show() does not give them either (ADR-020). */ void start(std::string_view page = "index.html") { - static_assert(requires { Frontend::launch(std::string_view{}, std::string_view{}, std::string_view{}); }, - "webfront::BasicWF::start(): this frontend opens its window inside the loop of show(), which keeps the " - "calling thread. Call show() on the interface thread and end it with requestClose(), or run the " - "application in a webfront::UIThread when the frontend allows a secondary thread " - "(docs/HOST_INTEGRATION.md)."); - if constexpr (requires { Frontend::launch(std::string_view{}, std::string_view{}, std::string_view{}); }) { + constexpr bool secure = networking::secureTransport; + constexpr bool canLaunch = secure + ? requires { Frontend::launchHttps(std::string_view{}, std::string_view{}, std::string_view{}); } + : requires { Frontend::launch(std::string_view{}, std::string_view{}, std::string_view{}); }; + if constexpr (secure) + static_assert(canLaunch, "webfront::BasicWF::start(): an HTTPS frontend must provide launchHttps(address, port, page)"); + else + static_assert(canLaunch, + "webfront::BasicWF::start(): this frontend opens its window inside the loop of show(), which keeps the " + "calling thread. Call show() on the interface thread and end it with requestClose(), or run the " + "application in a webfront::UIThread when the frontend allows a secondary thread " + "(docs/HOST_INTEGRATION.md)."); + if constexpr (canLaunch) { if (shown || serverThread.joinable() || launched.exchange(true)) throw std::logic_error("webfront::BasicWF::start(): the application is already started; call start() once, instead of show()"); if (!httpDocRoot.empty() && !developerEnvironment) detail::noteDevelopmentPath(); startServerThread(); try { - if constexpr (networking::secureTransport) + if constexpr (secure) Frontend::launchHttps(httpAddress, httpPort, page); else if constexpr (requires { Frontend::launch(httpAddress, httpPort, page, contentPolicy); }) Frontend::launch(httpAddress, httpPort, page, contentPolicy); diff --git a/include/webfront/http/HTTPServer.hpp b/include/webfront/http/HTTPServer.hpp index d1100aad..0fc79721 100644 --- a/include/webfront/http/HTTPServer.hpp +++ b/include/webfront/http/HTTPServer.hpp @@ -1021,6 +1021,7 @@ class Server { co_await Net::Close(socket); else socket.shutdown(Net::Socket::shutdown_both); + co_return; } std::string bind(std::string_view address, std::string_view requestedPort) { @@ -1163,7 +1164,7 @@ class Server { const auto wanted = std::min(*length - body.size(), buffer.size()); const auto count = co_await Net::Receive(socket, Net::Buffer(buffer.data(), wanted)); if (count == 0) { // the client ended the connection before the announced length - socket.shutdown(Net::Socket::shutdown_both); + co_await closeResponse(socket); co_return; } body.append(buffer.data(), count); diff --git a/include/webfront/tls/Credentials.hpp b/include/webfront/tls/Credentials.hpp index 67f11f35..95516a12 100644 --- a/include/webfront/tls/Credentials.hpp +++ b/include/webfront/tls/Credentials.hpp @@ -1,10 +1,10 @@ #pragma once #include "detail/Wire.hpp" -#include #include #include #include +#include namespace webfront::tls { namespace detail { @@ -179,14 +179,18 @@ class Credentials { Credentials(const std::filesystem::path& chain, const std::filesystem::path& key) : identity(detail::loadIdentity(chain, key)) {} void reload(const std::filesystem::path& chain, const std::filesystem::path& key) { - identity.store(detail::loadIdentity(chain, key)); + auto next = detail::loadIdentity(chain, key); + std::scoped_lock lock(mutex); + identity.swap(next); } [[nodiscard]] auto snapshot() const { - return identity.load(); + std::scoped_lock lock(mutex); + return identity; } private: - std::atomic> identity; + mutable std::mutex mutex; + std::shared_ptr identity; }; } // namespace webfront::tls diff --git a/include/webfront/tls/Server.hpp b/include/webfront/tls/Server.hpp index 17b90dd5..c1bccb37 100644 --- a/include/webfront/tls/Server.hpp +++ b/include/webfront/tls/Server.hpp @@ -17,19 +17,14 @@ class Server : public networking::TCPStdnet { using View = detail::View; struct Connection { - detail::Traffic read, write; - detail::Secret<> readSecret{}, writeSecret{}; - Bytes input; - std::size_t offset = 0; - std::array update{}; - std::size_t updateSize = 0; - unsigned skipped = 0; - bool sending = false; - bool compat = false; - bool writeEncrypted = false; - bool established = false; - bool closed = false; - bool updateRequested = false; + detail::Traffic read, write; + detail::Secret<> readSecret{}, writeSecret{}; + Bytes input; + std::size_t offset = 0; + detail::RecordControl control; + bool compat = false; + bool writeEncrypted = false; + bool established = false; }; public: @@ -74,11 +69,11 @@ class Server : public networking::TCPStdnet { static Result Receive(Socket& socket, MutableBuffer target) { using namespace detail; auto& state = *socket.connection; - if (state.closed) + if (state.control.closed) co_return 0; Byte failure = 0; try { - while (!state.closed) { + while (!state.control.closed && !state.control.peerNotified) { if (state.offset != state.input.size()) { const auto count = std::min(target.size(), state.input.size() - state.offset); std::copy_n(state.input.data() + state.offset, count, static_cast(target.data())); @@ -87,32 +82,15 @@ class Server : public networking::TCPStdnet { } const auto type = co_await readRecord(socket, true); state.offset = state.input.size(); - if (type == alert && state.input.size() == 2) { - state.closed = true; - if (state.input[1] != 0) - throw std::system_error(std::make_error_code(std::errc::connection_aborted)); - } else if (type == handshakeRecord) { - receiveKeyUpdate(state); - } else if (type == applicationData && state.updateSize == 0) { - if (!state.input.empty()) { - state.skipped = 0; - state.offset = 0; - continue; - } - } else { - throw Error("unexpected application record", 10); - } - if (++state.skipped > 32) - throw Error("too many consecutive control or empty records", 10); + if (state.control.receive(type, state.input, state.read, state.readSecret)) + state.offset = 0; } } catch (const Error& error) { failure = error.alert; } - state.closed = true; - // An alert cannot overtake a record already being written by the WebSocket task. - if (!state.sending) { + if (state.control.beginClose()) { const std::array response{static_cast(failure ? 2 : 1), failure}; - co_await writeRecord(socket, alert, response); + co_await tryAlert(socket, response); } if (failure) throw std::system_error(std::make_error_code(std::errc::protocol_error)); @@ -122,15 +100,15 @@ class Server : public networking::TCPStdnet { static Task Send(Socket& socket, auto buffers) { using namespace detail; auto& state = *socket.connection; - if (state.closed) + if (state.control.closed) throw std::system_error(std::make_error_code(std::errc::connection_reset)); - state.sending = true; + state.control.sending = true; struct Sending { bool& active; ~Sending() { active = false; } - } sending{state.sending}; + } sending{state.control.sending}; constexpr std::size_t header = 5; std::size_t length = 0; for (const auto buffer : buffers) @@ -154,28 +132,21 @@ class Server : public networking::TCPStdnet { } static Task Close(Socket& socket) { - if (!socket.connection->closed) { + if (socket.connection->control.beginClose()) { constexpr std::array notify{1, 0}; - co_await writeRecord(socket, detail::alert, notify); + co_await tryAlert(socket, notify); } - socket.shutdown(Socket::shutdown_both); + std::error_code ignored; + socket.shutdown(Socket::shutdown_both, ignored); } private: - static void receiveKeyUpdate(Connection& state) { - using namespace detail; - if (state.input.empty() || state.input.size() > state.update.size() - state.updateSize) - throw Error("invalid KeyUpdate size", 10); - std::ranges::copy(state.input, state.update.begin() + static_cast(state.updateSize)); - state.updateSize += state.input.size(); - if (state.updateSize != state.update.size()) - return; - if (!std::ranges::equal(View(state.update).first(4), std::array{24, 0, 0, 1}) || state.update.back() > 1) - throw Error("invalid KeyUpdate", 47); - state.readSecret = {expandLabel(state.readSecret, "traffic upd")}; - state.read.install(state.readSecret); - state.updateRequested |= state.update.back() == 1; - state.updateSize = 0; + static Task tryAlert(Socket& socket, const std::array& alert) { + try { + co_await writeRecord(socket, detail::alert, alert); + } catch (const std::system_error&) { + // An alert is best effort once the peer has closed the transport. + } } static Task readExact(Socket& socket, std::span target) { @@ -230,13 +201,15 @@ class Server : public networking::TCPStdnet { static Task writeApplication(Socket& socket, Bytes& record) { using namespace detail; auto& state = *socket.connection; - if (state.closed) + if (state.control.closed) throw std::system_error(std::make_error_code(std::errc::connection_reset)); - if (std::exchange(state.updateRequested, false)) { + if (std::exchange(state.control.updateRequested, false)) { constexpr std::array update{24, 0, 0, 1, 0}; co_await writeRecord(socket, handshakeRecord, update); state.writeSecret = {expandLabel(state.writeSecret, "traffic upd")}; state.write.install(state.writeSecret); + if (state.control.closed) + throw std::system_error(std::make_error_code(std::errc::connection_reset)); } state.write.seal(applicationData, record); co_await sendRecord(socket, record); diff --git a/include/webfront/tls/detail/ChaChaPoly.hpp b/include/webfront/tls/detail/ChaChaPoly.hpp index d555e752..f38eed32 100644 --- a/include/webfront/tls/detail/ChaChaPoly.hpp +++ b/include/webfront/tls/detail/ChaChaPoly.hpp @@ -62,12 +62,42 @@ inline void chachaXor(const Digest& key, const Nonce& nonce, std::span pay } } +using PolyLimbs = std::array; +inline constexpr std::uint64_t polyMask = (1u << 26) - 1; + +inline void carryPoly(PolyLimbs& value) { + for (std::size_t i = 0; i != 4; ++i) { + value[i + 1] += value[i] >> 26; + value[i] &= polyMask; + } + value[0] += 5 * (value[4] >> 26); + value[4] &= polyMask; +} + +inline void reducePoly(PolyLimbs& value) { + // The multiplication carried twice. Limb 0 can still have at most one carry. + // If it propagates all the way around, the final fold leaves limb 0 at most nine. + carryPoly(value); + carryPoly(value); + auto reduced = value; + reduced[0] += 5; + for (std::size_t i = 0; i != 4; ++i) { + reduced[i + 1] += reduced[i] >> 26; + reduced[i] &= polyMask; + } + const auto mask = std::uint64_t{0} - (reduced[4] >> 26); + reduced[4] &= polyMask; + for (std::size_t i = 0; i != value.size(); ++i) + value[i] ^= (value[i] ^ reduced[i]) & mask; + wipe(reduced.data(), sizeof(reduced)); +} + // RFC 8439 sections 2.5 and 2.8.1. The radix makes the carry from limb 4 // worth five in limb 0, since 2^130 is congruent to five modulo the prime. inline Tag polyTag(const Digest& key, const Nonce& nonce, std::span aad, std::span ciphertext) { - constexpr std::uint64_t low = (1u << 26) - 1; - using Limbs = std::array; - const auto unpack = [](const Byte* data) -> Limbs { + constexpr auto low = polyMask; + using Limbs = PolyLimbs; + const auto unpack = [](const Byte* data) -> Limbs { return {loadLittle(data) & low, (loadLittle(data + 3) >> 2) & low, (loadLittle(data + 6) >> 4) & low, @@ -81,14 +111,6 @@ inline Tag polyTag(const Digest& key, const Nonce& nonce, std::span oneTimeKey[i] &= 252; auto r = unpack(oneTimeKey.data()); Limbs h{}; - const auto carry = [&h] { - for (std::size_t i = 0; i != 4; ++i) { - h[i + 1] += h[i] >> 26; - h[i] &= low; - } - h[0] += 5 * (h[4] >> 26); - h[4] &= low; - }; const auto absorb = [&](const Byte* data) { const auto m = unpack(data); for (std::size_t i = 0; i != 5; ++i) @@ -99,9 +121,9 @@ inline Tag polyTag(const Digest& key, const Nonce& nonce, std::span for (std::size_t j = 0; j != 5; ++j) product[(i + j) % 5] += h[i] * r[j] * (i + j < 5 ? 1u : 5u); h = product; - carry(); + carryPoly(h); // The first carry leaves only limb 0 potentially wide. - carry(); + carryPoly(h); }; for (auto data : {aad, ciphertext}) { while (data.size() >= 16) { @@ -120,18 +142,7 @@ inline Tag polyTag(const Digest& key, const Nonce& nonce, std::span lengths[i + 8] = static_cast(std::uint64_t{ciphertext.size()} >> (8 * i)); } absorb(lengths.data()); - carry(); - - // h + 5 crosses bit 130 precisely when h is at least the modulus. - auto reduced = h; - reduced[0] += 5; - for (std::size_t i = 0; i != 4; ++i) { - reduced[i + 1] += reduced[i] >> 26; - reduced[i] &= low; - } - const auto mask = std::uint64_t{0} - (reduced[4] >> 26); - for (std::size_t i = 0; i != 5; ++i) - h[i] ^= (h[i] ^ reduced[i]) & mask; + reducePoly(h); Tag tag; unsigned padCarry = 0; @@ -145,7 +156,6 @@ inline Tag polyTag(const Digest& key, const Nonce& nonce, std::span wipe(oneTimeKey.data(), oneTimeKey.size()); wipe(r.data(), sizeof(r)); wipe(h.data(), sizeof(h)); - wipe(reduced.data(), sizeof(reduced)); return tag; } } // namespace webfront::tls::detail diff --git a/include/webfront/tls/detail/Protocol.hpp b/include/webfront/tls/detail/Protocol.hpp index a02d9e95..6b0c4d66 100644 --- a/include/webfront/tls/detail/Protocol.hpp +++ b/include/webfront/tls/detail/Protocol.hpp @@ -1,8 +1,9 @@ #pragma once #include "Wire.hpp" -#include #include +#include +#include namespace webfront::tls::detail { inline constexpr unsigned suite = 0x1303, group = 29, signatureScheme = 0x0403; @@ -53,16 +54,23 @@ inline ClientHello parseHello(View message, bool retry) { invariant.update(original.first(original.size() - hello.remaining.size())); Reader extensions{hello.vector(2)}; hello.end(); - bool version = false, signature = false, supportedGroup = false, earlyData = false; - std::bitset<65536> seen; - View shares, groups; + bool version = false, signature = false, supportedGroup = false, earlyData = false; + std::array seen; + std::size_t extensionCount = 0; + const auto containsExtension = [&](unsigned kind) { + const auto prior = std::span(seen).first(extensionCount); + return std::ranges::find(prior, kind) != prior.end(); + }; + View shares, groups; while (!extensions.empty()) { const auto encoded = extensions.remaining; const auto kind = extensions.number(2); Reader extension{extensions.vector(2)}; - if (seen.test(kind)) + if (containsExtension(kind)) throw Error("duplicate ClientHello extension", 47); - seen.set(kind); + if (extensionCount == seen.size()) + throw Error("too many ClientHello extensions"); + seen[extensionCount++] = kind; switch (kind) { case 43: version = contains(extension.vector(1), 2, 0x0304); @@ -112,7 +120,7 @@ inline ClientHello parseHello(View message, bool retry) { throw Error("TLS 1.3 required", 70); if (!offeredSuite || !signature || !supportedGroup) throw Error("no common cipher suite, signature or group", 40); - if (earlyData && (retry || !seen.test(41))) + if (earlyData && (retry || !containsExtension(41))) throw Error("unexpected early_data", 47); Reader keys{shares}; std::size_t groupOffset = 0; @@ -235,4 +243,59 @@ struct Traffic { std::array iv{}; std::uint64_t sequence = 0; }; +// Serialized by the socket's context. A close cannot overtake an in-flight write. +struct RecordControl { + bool sending = false; + bool closed = false; + bool updateRequested = false; + bool peerNotified = false; + + bool beginClose() { + return !std::exchange(closed, true) && !sending; + } + + // Returns true for a nonempty application record ready to deliver. + bool receive(Byte type, View input, Traffic& traffic, Secret<>& secret) { + if (type == alert && input.size() == 2) { + if (input[1] != 0) { + closed = true; + throw std::system_error(std::make_error_code(std::errc::connection_aborted)); + } + peerNotified = true; + return false; + } + if (type == handshakeRecord) { + constexpr std::array header{24, 0, 0, 1}; + if (input.empty() || input.size() > update.size() - updateSize) + throw Error("invalid KeyUpdate size", 10); + std::ranges::copy(input, update.data() + updateSize); + updateSize += input.size(); + if (!std::ranges::equal(View(update).first(std::min(updateSize, header.size())), View(header).first(std::min(updateSize, header.size())))) + throw Error("unexpected post-handshake message", 10); + if (updateSize == update.size()) { + if (update.back() > 1) + throw Error("invalid KeyUpdate request", 47); + secret = {expandLabel(secret, "traffic upd")}; + traffic.install(secret); + updateRequested |= update.back() == 1; + updateSize = 0; + } + } else if (type == applicationData && updateSize == 0) { + if (!input.empty()) { + skipped = 0; + return true; + } + } else { + throw Error("unexpected application record", 10); + } + if (++skipped > 32) + throw Error("too many consecutive control or empty records", 10); + return false; + } + +private: + std::array update{}; + std::size_t updateSize = 0; + unsigned skipped = 0; +}; } // namespace webfront::tls::detail diff --git a/test/unit/ReadBindingTests.cpp b/test/unit/ReadBindingTests.cpp index f12473ae..0a2f26e9 100644 --- a/test/unit/ReadBindingTests.cpp +++ b/test/unit/ReadBindingTests.cpp @@ -367,9 +367,15 @@ const Scenario connectionNot{"A connection that is not the view of an embedded f given("a connection to the integrated TLS listener", [&] { Fixture fixture{RemoteFileTransport::refused, true}; const auto cookies = headers(fixture.bind(1, false), "Set-Cookie"); - then("its binding uses a Secure cookie and authorizes reads", [&] { + then("its binding uses a Secure cookie and the default still refuses reads", [&] { require(cookies.front().contains("; Secure")); - require(call(fixture.read, fixture.url(1), cookiePair(cookies.front())).status == http::Response::ok); + requireThrows([&] { fixture.url(1); }); + }); + then("an explicit HTTPS declaration authorizes reads with the binding cookie", [&] { + Fixture authorized{RemoteFileTransport::httpsByDeployment, true}; + const auto bound = headers(authorized.bind(2, false), "Set-Cookie").front(); + require(bound.contains("; Secure")); + require(call(authorized.read, authorized.url(2), cookiePair(bound)).status == http::Response::ok); }); }); given("a request through a local proxy that forges the forwarding headers, with the default declaration", [&] { diff --git a/test/unit/TlsTests.cpp b/test/unit/TlsTests.cpp index 86fd6612..2b9f060d 100644 --- a/test/unit/TlsTests.cpp +++ b/test/unit/TlsTests.cpp @@ -1,4 +1,6 @@ #include "Bdd.hpp" +#include "TemporaryDirectory.hpp" +#include #include #include @@ -135,3 +137,118 @@ const Scenario tlsRefusals("TLS rejects invalid framing and negotiation", {"fast }); }); } // namespace + +namespace { +const Scenario tlsRecordControl("TLS application records coordinate updates and closure", [] { + tls::RecordControl control; + tls::Traffic traffic; + tls::Secret<> secret{}; + traffic.install(secret); + given("a KeyUpdate split across authenticated handshake records", [&] { + require(!control.receive(tls::handshakeRecord, tlsHex("180000"), traffic, secret)); + require(!control.updateRequested); + const auto next = tls::expandLabel(secret, "traffic upd"); + require(!control.receive(tls::handshakeRecord, tlsHex("0101"), traffic, secret)); + require(control.updateRequested); + require(std::ranges::equal(secret, next)); + tls::Traffic sender; + sender.install(next); + Bytes record{0, 0, 0, 0, 0, 42}; + sender.seal(tls::applicationData, record); + Bytes ciphertext(record.begin() + 5, record.end()); + require(traffic.open(View(record).first(5), ciphertext) == tls::applicationData); + require(control.receive(tls::applicationData, ciphertext, traffic, secret)); + }); + then("an unexpected handshake type elicits unexpected_message", [&] { + try { + control.receive(tls::handshakeRecord, tlsHex("14000000"), traffic, secret); + require(false); + } catch (const tls::Error& error) { + require(error.alert == 10); + } + }); + then("32 empty records are tolerated and application data resets the count", [&] { + tls::RecordControl limit; + for (unsigned batch = 0; batch != 2; ++batch) { + for (unsigned i = 0; i != 32; ++i) + require(!limit.receive(tls::applicationData, {}, traffic, secret)); + if (batch == 0) + require(limit.receive(tls::applicationData, tlsHex("42"), traffic, secret)); + } + requireThrows([&] { + limit.receive(tls::applicationData, {}, traffic, secret); + }); + }); + then("the orderly response is sent once, except during an in-flight write", [&] { + for (const bool sending : {false, true}) { + tls::RecordControl closing; + closing.sending = sending; + require(!closing.receive(tls::alert, tlsHex("0100"), traffic, secret)); + require(closing.peerNotified); + require(closing.beginClose() == !sending); + require(closing.closed); + require(!closing.beginClose()); + } + }); + then("a fatal peer alert closes without a reply", [&] { + tls::RecordControl fatal; + requireThrows([&] { + fatal.receive(tls::alert, tlsHex("0214"), traffic, secret); + }); + require(fatal.closed); + require(!fatal.beginClose()); + }); +}); + +const Scenario tlsPolyBoundary("Poly1305 reduction handles a carry around bit 130", [] { + constexpr auto max = tls::polyMask; + tls::PolyLimbs primeMinusOne{max - 5, max, max, max, max}; + const auto unchanged = primeMinusOne; + tls::reducePoly(primeMinusOne); + require(primeMinusOne == unchanged); + tls::PolyLimbs prime{max - 4, max, max, max, max}; + tls::reducePoly(prime); + require(prime == tls::PolyLimbs{}); + tls::PolyLimbs wide{max + 1, max, max, max, max}; + tls::reducePoly(wide); + require(wide == (tls::PolyLimbs{5, 0, 0, 0, 0})); +}); + +const Scenario tlsCredentials("TLS loads matching PEM formats and preserves the published identity on reload failure", [] { + const auto fixtures = std::filesystem::path(WEBFRONT_SOURCE_DIR) / "test/web/fixtures/tls"; + const auto certificate = fixtures / "cert.pem"; + const auto sec1 = fixtures / "key-sec1.pem"; + webfront::tls::Credentials credentials(certificate, fixtures / "key.pem"); + const auto pkcs8 = credentials.snapshot(); + credentials.reload(certificate, sec1); + const auto expected = credentials.snapshot(); + require(expected != pkcs8); + require(tls::equalSecret(expected->key, pkcs8->key)); + + webfront::test::TemporaryDirectory temporary; + const auto invalid = temporary.path() / "invalid.pem"; + std::ofstream(invalid) << "-----BEGIN EC PRIVATE KEY-----\n????\n-----END EC PRIVATE KEY-----\n"; + requireThrows([&] { + credentials.reload(certificate, invalid); + }); + require(credentials.snapshot() == expected); + + std::string source; + tls::readPemFile(sec1, source); + std::string_view pem = source; + auto der = tls::pem(pem, "EC PRIVATE KEY"); + tls::Reader outer{der}; + const auto keySequence = outer.der(0x30); + tls::Reader key{keySequence}; + key.der(2); + const auto scalar = key.der(4); + der[static_cast(scalar.data() - der.data())] ^= 1; + std::ofstream(invalid) << "-----BEGIN EC PRIVATE KEY-----\n" << webfront::base64::encode(der) << "\n-----END EC PRIVATE KEY-----\n"; + requireThrows( + [&] { + credentials.reload(certificate, invalid); + }, + contains("certificate and private key do not match")); + require(credentials.snapshot() == expected); +}); +} // namespace diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index f504a550..a63f068a 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -70,6 +70,7 @@ endif() add_executable(multi_instance MultiInstance.cpp) target_link_libraries(multi_instance PRIVATE WebFront WebFront_warnings WebFront_options) webfront_setup_frontends_for_target(multi_instance) +add_dependencies(webtest multi_instance) foreach(_count 2 48) add_test(NAME MultiInstance-${_count} COMMAND multi_instance ${_count}) set_tests_properties(MultiInstance-${_count} PROPERTIES LABELS "web-integration" TIMEOUT 60 RESOURCE_LOCK webfront_port_9002) @@ -79,6 +80,20 @@ endforeach() add_test(NAME FrontendLifecycleStageValues COMMAND "${CMAKE_COMMAND}" "-DSOURCE_DIR=${PROJECT_SOURCE_DIR}" -P "${PROJECT_SOURCE_DIR}/test/cmake/CheckLifecycleStageValues.cmake") set_tests_properties(FrontendLifecycleStageValues PROPERTIES TIMEOUT 10 LABELS fast) +# OpenSSL is a test peer only. The server target links the header-only provider. +if(CMAKE_SYSTEM_NAME STREQUAL "Linux") + find_package(Python3 QUIET COMPONENTS Interpreter) + find_program(WEBFRONT_TEST_OPENSSL openssl) + if(Python3_Interpreter_FOUND AND WEBFRONT_TEST_OPENSSL) + add_executable(tls_interop TlsInterop.cpp) + target_link_libraries(tls_interop PRIVATE WebFront WebFront_test_hardening WebFront_warnings WebFront_options) + add_dependencies(webtest tls_interop) + add_test(NAME TLSOpenSSLInterop COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/TlsInterop.py" + $ "${WEBFRONT_TEST_OPENSSL}" "${CMAKE_CURRENT_SOURCE_DIR}/fixtures/tls") + set_tests_properties(TLSOpenSSLInterop PROPERTIES LABELS "web-integration" TIMEOUT 30) + endif() +endif() + # The reproducibility proof compares every file it lists, and refuses a list split by its caller. add_test(NAME CompareFilesWholeList COMMAND "${CMAKE_COMMAND}" "-DSOURCE_DIR=${PROJECT_SOURCE_DIR}" "-DWORK=${CMAKE_CURRENT_BINARY_DIR}/compare-files-check" -P "${PROJECT_SOURCE_DIR}/test/cmake/CheckCompareFiles.cmake") diff --git a/test/web/JasmineTest.cpp b/test/web/JasmineTest.cpp index c3bca0cf..e5339667 100644 --- a/test/web/JasmineTest.cpp +++ b/test/web/JasmineTest.cpp @@ -130,7 +130,7 @@ class BrowserIntegrationTest { #ifdef WEBFRONT_TEST_TLS_FIXTURE const filesystem::path fixture(WEBFRONT_TEST_TLS_FIXTURE); config.tlsCredentials = make_shared(fixture / "cert.pem", fixture / "key.pem"); - config.remoteFileTransport = RemoteFileTransport::refused; + config.remoteFileTransport = RemoteFileTransport::httpsByDeployment; #endif } diff --git a/test/web/TlsInterop.cpp b/test/web/TlsInterop.cpp new file mode 100644 index 00000000..d403be30 --- /dev/null +++ b/test/web/TlsInterop.cpp @@ -0,0 +1,27 @@ +#include + +#include +#include + +int main(int argc, char** argv) { + if (argc != 3) + return 1; + webfront::tls::WebFront<> app({.port = "0", .tlsCredentials = std::make_shared(argv[1], argv[2])}); + std::latch reply{1}; + const auto post = [&](const webfront::http::RouteRequest&) { + std::cout << "post" << std::endl; + reply.wait(); + return webfront::http::RouteReply{}; + }; + const auto route = app.addRoute("/post/", post, {.postBodyLimit = 64}); + std::jthread server([&] { + app.run(); + }); + std::cout << app.port() << std::endl; + std::cin.get(); + reply.count_down(); + std::cin.get(); + app.stop(); + server.join(); + app.shutdown(); +} diff --git a/test/web/TlsInterop.py b/test/web/TlsInterop.py new file mode 100644 index 00000000..fa00a3cb --- /dev/null +++ b/test/web/TlsInterop.py @@ -0,0 +1,61 @@ +"""Exercise the TLS provider against an independent OpenSSL client over loopback.""" +import select +import socket +import ssl +import struct +import subprocess +import sys +from pathlib import Path + + +def exercise(server, openssl, certificate): + port = int(server.stdout.readline()) + request = b"GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n" + retry = subprocess.run( + [openssl, "s_client", "-connect", f"127.0.0.1:{port}", "-tls1_3", + "-groups", "P-256:X25519", "-CAfile", str(certificate), "-verify_return_error", + "-verify_ip", "127.0.0.1", "-quiet", "-msg"], + input=request, capture_output=True, check=True, timeout=10, + ) + if retry.stdout.count(b", ServerHello") != 2 or b"HTTP/1.1 200 OK" not in retry.stdout: + raise RuntimeError(f"HelloRetryRequest or HTTP response missing: {retry.stdout!r} {retry.stderr!r}") + + context = ssl.create_default_context(cafile=certificate) + context.minimum_version = ssl.TLSVersion.TLSv1_3 + + def connect(): + return context.wrap_socket(socket.create_connection(("127.0.0.1", port), timeout=5), + server_hostname="127.0.0.1") + + post = b"POST /post/ HTTP/1.1\r\nHost: localhost\r\nContent-Length: 2\r\n\r\n" + with connect() as peer: + peer.sendall(post + b"x") + with peer.unwrap(): + pass # close_notify is acknowledged even though the HTTP body is incomplete + + with connect() as peer: + peer.sendall(post + b"ok") + if not select.select([server.stdout], [], [], 5)[0] or server.stdout.readline().strip() != "post": + raise RuntimeError("The server did not enter the POST handler") + peer.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0)) + # Release the handler only once the client has reset its socket. + server.stdin.write("\n") + server.stdin.flush() + with connect() as peer: + peer.sendall(request) + with peer.makefile("rb") as response: + if response.readline().rstrip() != b"HTTP/1.1 200 OK": + raise RuntimeError("The listener did not serve the next connection") + + +if __name__ == "__main__": + program, openssl, fixtures = sys.argv[1:] + certificate = Path(fixtures) / "cert.pem" + with subprocess.Popen([program, certificate, Path(fixtures) / "key.pem"], + stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) as server: + try: + exercise(server, openssl, certificate) + finally: + server.stdin.close() + if server.wait(timeout=5) != 0: + raise RuntimeError("TLS interop server exited unsuccessfully") diff --git a/test/web/fixtures/tls/README.md b/test/web/fixtures/tls/README.md index 50030a5c..e1ba2126 100644 --- a/test/web/fixtures/tls/README.md +++ b/test/web/fixtures/tls/README.md @@ -1,3 +1,6 @@ This public test identity serves localhost and 127.0.0.1 in the CEF HTTPS Jasmine test. Its unencrypted key is committed for repeatable tests. CEF is configured to accept this SPKI fingerprint in an isolated test profile. + +The two key files encode the same test key as PKCS#8 and SEC1 so credential +loading and reload can be checked on every platform. diff --git a/test/web/fixtures/tls/key-sec1.pem b/test/web/fixtures/tls/key-sec1.pem new file mode 100644 index 00000000..92912a9d --- /dev/null +++ b/test/web/fixtures/tls/key-sec1.pem @@ -0,0 +1,5 @@ +-----BEGIN EC PRIVATE KEY----- +MHcCAQEEICD4hYXb75tJ2/awIqfawC5DyccAocBZNFHw0X5LRFK8oAoGCCqGSM49 +AwEHoUQDQgAElFa6/ANSNq7ox/s/b07ONUNHj7nMgkAWwiAmNE2pYjr9/bWPKigr +SlpFLM+/IlxW6EkuR2oTB/5NWSMcLpeJJQ== +-----END EC PRIVATE KEY----- From 807db48cde0e86f06c95f30cadf41ba51c2a59b5 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:18:10 +0100 Subject: [PATCH 04/24] Compile the optional TLS provider on every desktop (#631) --- test/web/CMakeLists.txt | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index a63f068a..0e828dfe 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -80,14 +80,14 @@ endforeach() add_test(NAME FrontendLifecycleStageValues COMMAND "${CMAKE_COMMAND}" "-DSOURCE_DIR=${PROJECT_SOURCE_DIR}" -P "${PROJECT_SOURCE_DIR}/test/cmake/CheckLifecycleStageValues.cmake") set_tests_properties(FrontendLifecycleStageValues PROPERTIES TIMEOUT 10 LABELS fast) -# OpenSSL is a test peer only. The server target links the header-only provider. +# Build the optional provider on every desktop. The independent OpenSSL peer runs on Linux. +add_executable(tls_interop TlsInterop.cpp) +target_link_libraries(tls_interop PRIVATE WebFront WebFront_test_hardening WebFront_warnings WebFront_options) +add_dependencies(webtest tls_interop) if(CMAKE_SYSTEM_NAME STREQUAL "Linux") find_package(Python3 QUIET COMPONENTS Interpreter) find_program(WEBFRONT_TEST_OPENSSL openssl) if(Python3_Interpreter_FOUND AND WEBFRONT_TEST_OPENSSL) - add_executable(tls_interop TlsInterop.cpp) - target_link_libraries(tls_interop PRIVATE WebFront WebFront_test_hardening WebFront_warnings WebFront_options) - add_dependencies(webtest tls_interop) add_test(NAME TLSOpenSSLInterop COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/TlsInterop.py" $ "${WEBFRONT_TEST_OPENSSL}" "${CMAKE_CURRENT_SOURCE_DIR}/fixtures/tls") set_tests_properties(TLSOpenSSLInterop PROPERTIES LABELS "web-integration" TIMEOUT 30) From e1157f2c63f3f8d17be30afef85f3e567b0c595e Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:39:56 +0100 Subject: [PATCH 05/24] Finish orderly WSS closure and preserve masked curve selection (#631) --- docs/TLS.md | 24 ++++++++-- include/webfront/WebFront.hpp | 2 + include/webfront/http/HTTPServer.hpp | 3 ++ include/webfront/http/WebSocket.hpp | 59 ++++++++++++++++++++++-- include/webfront/tls/Credentials.hpp | 9 ++-- include/webfront/tls/Server.hpp | 48 +++++++++++-------- include/webfront/tls/detail/Crypto.hpp | 6 ++- include/webfront/tls/detail/Field.hpp | 16 ++++++- include/webfront/tls/detail/Protocol.hpp | 30 +++++++----- test/unit/CMakeLists.txt | 14 ++++++ test/unit/TlsConstantTime.cpp | 35 ++++++++++++++ test/unit/TlsTests.cpp | 6 ++- test/web/TlsInterop.cpp | 8 +++- test/web/TlsInterop.py | 19 +++++++- 14 files changed, 229 insertions(+), 50 deletions(-) create mode 100644 test/unit/TlsConstantTime.cpp diff --git a/docs/TLS.md b/docs/TLS.md index c2a8f07f..a81169b0 100644 --- a/docs/TLS.md +++ b/docs/TLS.md @@ -61,24 +61,40 @@ optional second ClientHello and Finished sequence described in the The two X25519 operations and the CertificateVerify signature run on the I/O thread. Other connections wait while this work runs. An incomplete handshake has no built-in deadline. Bursts of handshakes can delay established HTTP/WSS -connections, and idle handshakes can hold sockets and memory. +connections, and idle handshakes can hold sockets and memory. WebFront logs +a warning when the integrated listener is configured outside loopback. + +On orderly WSS closure initiated by the peer, WebFront answers the WebSocket +Close frame and then sends TLS `close_notify`. If TLS closure is requested +during a send, the alert follows the current complete TLS record. A reset, +failed write or cancellation during server shutdown can end the connection +before the alert can be sent. + +## Constant-time regression + +On Linux with Valgrind and its development headers installed, the optional +`TLSConstantTime` CTest case marks the private inputs to `p256Base` and `x25519` +undefined and checks compiler-generated branches and addresses with Memcheck. +The probe passed locally on x86-64 with GCC 16.1 and Clang 21 at `-Os` and `-O3`. +The probe covers those scalar operations and compiler configurations. It leaves +an audit of the rest of TLS and other targets, including Thumb-2, outstanding. ## Size, memory and handshake time On Linux x86-64 with GCC 16.1, a minimal app with one bridge callback built at `-Os -DNDEBUG -ffunction-sections -fdata-sections -Wl,--gc-sections` gained -43.6 KiB of `.text` and 5.0 KiB of `.rodata` when the TCP provider was +47.3 KiB of `.text` and 5.5 KiB of `.rodata` when the TCP provider was replaced by the TLS provider. The TLS headers total about 1,500 lines, including the in-tree primitives and comments. In the same binaries, 200 open loopback WebSockets increased Linux -`smaps_rollup` private dirty memory by about 3.6 KiB more per idle connection +`smaps_rollup` private dirty memory by about 3.5 KiB more per idle connection for WSS than for WS. Giving each socket 16,384 bytes of an incomplete frame increased the WSS overhead to about 18.8 KiB per connection. These are process measurements after a warm-up connection and include allocator overhead. Thumb-2 size and peak memory during the handshake remain unmeasured. On an AMD Ryzen 9 3900X, an OpenSSL-backed Python client completed 200 -sequential loopback handshakes in 2.7 ms at the median and 3.8 ms at the 95th +sequential loopback handshakes in 2.0 ms at the median and 2.2 ms at the 95th percentile. The measurement starts after TCP connect and ends after TLS negotiation, following ten warm-up connections. It includes both endpoints and excludes HTTP traffic. diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 33ecf1cf..73802014 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -686,6 +686,8 @@ inline WebFrontConfig checkedPtyPageConfig(WebFrontConfig config) { /// The read binding of a configuration, which is refused here, before anything is bound, if its declaration is false. inline std::shared_ptr makeReadBinding(const WebFrontConfig& config, bool secure = false) { checkedAddress(config); + if (secure && !isLoopbackName(config.address)) + log::warn("TLS listener outside loopback on {}: handshake cryptography runs on the I/O thread and incomplete handshakes have no deadline", config.address); return std::make_shared(secure, config.remoteFileTransport); } } // namespace detail diff --git a/include/webfront/http/HTTPServer.hpp b/include/webfront/http/HTTPServer.hpp index 0fc79721..185263b7 100644 --- a/include/webfront/http/HTTPServer.hpp +++ b/include/webfront/http/HTTPServer.hpp @@ -1217,6 +1217,9 @@ class Server { co_await Net::Handshake(socket, acceptor); } catch (const std::system_error&) { co_return; + } catch (const std::exception& error) { + log::warn("TLS handshake failed: {}", error.what()); + co_return; } } Request request; diff --git a/include/webfront/http/WebSocket.hpp b/include/webfront/http/WebSocket.hpp index cc288abb..8bc979e1 100644 --- a/include/webfront/http/WebSocket.hpp +++ b/include/webfront/http/WebSocket.hpp @@ -6,6 +6,7 @@ #include "Encodings.hpp" #include "../tooling/HexDump.hpp" #include "../networking/Tasks.hpp" +#include "../networking/BasicNetworking.hpp" #include "../tooling/Logger.hpp" #include @@ -13,6 +14,7 @@ #include #include #include +#include #include #include #include @@ -365,6 +367,8 @@ class WebSocket : public std::enable_shared_from_this> { void writeLatest(std::shared_ptr> frame, std::string_view key, std::size_t maxPending) { { std::lock_guard lock(writeMutex); + if constexpr (networking::secureTransport) + if (!started) return; auto group = latestGroups.find(key); if (group == latestGroups.end()) group = latestGroups.emplace(std::string(key), LatestGroup{}).first; @@ -453,8 +457,15 @@ class WebSocket : public std::enable_shared_from_this> { while (started) { const auto received = co_await Net::Receive(socket, Net::Buffer(readBuffer)); if (received == 0) { - failure = std::make_error_code(std::errc::connection_reset); // the browser closed the connection - break; + if constexpr (networking::secureTransport) { + // TLS reports an authenticated EOF. Let the current writer flush any pending close_notify. + if (claimClose() && closeHandler) + closeHandler(CloseEvent{}); + co_return; + } else { + failure = std::make_error_code(std::errc::connection_reset); + break; + } } processFrames(std::span(readBuffer.data(), received)); } @@ -500,9 +511,38 @@ class WebSocket : public std::enable_shared_from_this> { log::debug("Unhandled frameType"); return; } - if (closeHandler) - closeHandler(CloseEvent{}); - stop(); + if constexpr (networking::secureTransport) { + if (!claimClose()) + return; + queueSecureClose(decoder.payload()); + if (closeHandler) + closeHandler(CloseEvent{}); + } else { + if (closeHandler) + closeHandler(CloseEvent{}); + stop(); + } + } + + // Keep the first frame (which the writer may already be sending), then answer the peer. + // This keeps the close frame and the TLS alert behind the in-flight data on the same writer. + void queueSecureClose(std::span payload) { + Frame reply(payload); + reply.setOpcode(Header::Opcode::connectionClose); + auto frame = std::move(reply).share(); + bool writerNeeded; + { + std::lock_guard lock(writeMutex); + writerNeeded = writeQueue.empty(); + if (!writerNeeded) { + writeQueue.erase(std::next(writeQueue.begin()), writeQueue.end()); + writeQueue.front().group.reset(); + } + latestGroups.clear(); + writeQueue.push_back({std::move(frame)}); + } + if (writerNeeded) + spawn(writeFrames(this->shared_from_this())); } // Control frames (close, ping, pong) carry at most 125 bytes (RFC 6455, 5.5), whatever maxMessageSize. @@ -575,6 +615,8 @@ class WebSocket : public std::enable_shared_from_this> { bool enqueue(std::shared_ptr> frame, std::size_t maxPending) { { std::lock_guard lock(writeMutex); + if constexpr (networking::secureTransport) + if (!started) return false; if (writeQueue.size() >= maxPending) return false; writeQueue.push_back({std::move(frame)}); if (writeQueue.size() > 1) return true; // the running writeFrames() task will get to it @@ -589,6 +631,13 @@ class WebSocket : public std::enable_shared_from_this> { for (auto frame = nextFrame(false); frame;) { // A stopped WebSocket cancels the write: it fails like a write on a closed connection. co_await networking::ex::stopped_as_error(Net::Send(socket, frame->toBuffers()), std::make_error_code(std::errc::operation_canceled)); + if constexpr (networking::secureTransport) { + if (frame->opcode() == Header::Opcode::connectionClose) { + nextFrame(true); + co_await Net::Close(socket); + co_return; + } + } frame = nextFrame(true); if (writtenHandler) writtenHandler(); } diff --git a/include/webfront/tls/Credentials.hpp b/include/webfront/tls/Credentials.hpp index 95516a12..82566899 100644 --- a/include/webfront/tls/Credentials.hpp +++ b/include/webfront/tls/Credentials.hpp @@ -13,6 +13,7 @@ inline constexpr std::array ecPublicKey{0x2a, 0x86, 0x48, 0xce, 0x3d, 2 inline constexpr std::array prime256v1{0x2a, 0x86, 0x48, 0xce, 0x3d, 3, 1, 7}; inline void ecAlgorithm(Reader oid) { + // AlgorithmIdentifier carries the algorithm OID followed by the named-curve OID. if (!std::ranges::equal(oid.der(6), ecPublicKey) || !std::ranges::equal(oid.der(6), prime256v1)) throw Error("expected P-256 algorithm"); oid.end(); @@ -40,17 +41,17 @@ inline Secret<> privateKey(View input, bool pkcs8) { Reader source{input}; Reader key{source.der(0x30)}; source.end(); - auto version = key.der(2); + auto keyVersion = key.der(2); if (pkcs8) { - if (version.size() != 1 || version.front() != 0) + if (keyVersion.size() != 1 || keyVersion.front() != 0) throw Error("expected PKCS#8 private key"); ecAlgorithm({key.der(0x30)}); Reader wrapped{key.der(4)}; key = {wrapped.der(0x30)}; wrapped.end(); - version = key.der(2); + keyVersion = key.der(2); } - if (version.size() != 1 || version.front() != 1) + if (keyVersion.size() != 1 || keyVersion.front() != 1) throw Error("expected EC private key"); const auto scalar = key.der(4); if (scalar.size() != 32) diff --git a/include/webfront/tls/Server.hpp b/include/webfront/tls/Server.hpp index c1bccb37..27f0f194 100644 --- a/include/webfront/tls/Server.hpp +++ b/include/webfront/tls/Server.hpp @@ -68,9 +68,11 @@ class Server : public networking::TCPStdnet { static Result Receive(Socket& socket, MutableBuffer target) { using namespace detail; + if (target.size() == 0) + throw std::invalid_argument("TLS: Receive requires a nonempty buffer"); auto& state = *socket.connection; if (state.control.closed) - co_return 0; + co_return std::size_t{0}; Byte failure = 0; try { while (!state.control.closed && !state.control.peerNotified) { @@ -88,13 +90,11 @@ class Server : public networking::TCPStdnet { } catch (const Error& error) { failure = error.alert; } - if (state.control.beginClose()) { - const std::array response{static_cast(failure ? 2 : 1), failure}; - co_await tryAlert(socket, response); - } + if (state.control.beginClose(failure)) + co_await finishClose(socket); if (failure) throw std::system_error(std::make_error_code(std::errc::protocol_error)); - co_return 0; + co_return std::size_t{0}; } static Task Send(Socket& socket, auto buffers) { @@ -111,13 +111,18 @@ class Server : public networking::TCPStdnet { } sending{state.control.sending}; constexpr std::size_t header = 5; std::size_t length = 0; - for (const auto buffer : buffers) + for (const auto buffer : buffers) { length += std::min(buffer.size(), maxPlaintext - length); + if (length == maxPlaintext) + break; + } Bytes record(header); record.reserve(header + length + 17); for (auto buffer : buffers) { View data{static_cast(buffer.data()), buffer.size()}; - while (!data.empty()) { + if (state.control.closed) + break; + while (!data.empty() && !state.control.closed) { const auto count = std::min(data.size(), maxPlaintext + header - record.size()); append(record, data.first(count)); data = data.subspan(count); @@ -127,26 +132,33 @@ class Server : public networking::TCPStdnet { } } } - if (record.size() != header) + if (!state.control.closed && record.size() != header) co_await writeApplication(socket, record); + if (state.control.closed) { + co_await finishClose(socket); + throw std::system_error(std::make_error_code(std::errc::connection_aborted)); + } } + // If a send is in progress, that writer owns the final alert and shutdown. static Task Close(Socket& socket) { - if (socket.connection->control.beginClose()) { - constexpr std::array notify{1, 0}; - co_await tryAlert(socket, notify); - } - std::error_code ignored; - socket.shutdown(Socket::shutdown_both, ignored); + if (socket.connection->control.beginClose()) + co_await finishClose(socket); } private: - static Task tryAlert(Socket& socket, const std::array& alert) { + static Task finishClose(Socket& socket) { + const auto failure = socket.connection->control.takeAlert(); + if (!failure) + co_return; + const std::array response{static_cast(*failure ? 2 : 1), *failure}; try { - co_await writeRecord(socket, detail::alert, alert); + co_await writeRecord(socket, detail::alert, response); } catch (const std::system_error&) { // An alert is best effort once the peer has closed the transport. } + std::error_code ignored; + socket.shutdown(Socket::shutdown_both, ignored); } static Task readExact(Socket& socket, std::span target) { @@ -209,7 +221,7 @@ class Server : public networking::TCPStdnet { state.writeSecret = {expandLabel(state.writeSecret, "traffic upd")}; state.write.install(state.writeSecret); if (state.control.closed) - throw std::system_error(std::make_error_code(std::errc::connection_reset)); + co_return; } state.write.seal(applicationData, record); co_await sendRecord(socket, record); diff --git a/include/webfront/tls/detail/Crypto.hpp b/include/webfront/tls/detail/Crypto.hpp index 84be4f75..40d3157b 100644 --- a/include/webfront/tls/detail/Crypto.hpp +++ b/include/webfront/tls/detail/Crypto.hpp @@ -187,8 +187,10 @@ inline Bytes sign(std::span key, const Digest& messageHash) { Erase eraseNonce{k}; if (F::validScalar(k)) { const auto x = F::reduce(p256Base(k)[0]); - const auto sum = F::add(z, F::multiply(F::enter(x), scalar)); - const auto y = F::leave(F::multiply(F::invert(F::enter(k)), sum)); + auto sum = F::add(z, F::multiply(F::enter(x), scalar)); + Erase eraseSum{sum}; + auto y = F::leave(F::multiply(F::invert(F::enter(k)), sum)); + Erase eraseResult{y}; if (nonzero(x) && nonzero(y)) { const auto r = encode(x), s = encode(y); Bytes signature{0x30, 0}; diff --git a/include/webfront/tls/detail/Field.hpp b/include/webfront/tls/detail/Field.hpp index 687b79b5..39e555f4 100644 --- a/include/webfront/tls/detail/Field.hpp +++ b/include/webfront/tls/detail/Field.hpp @@ -51,10 +51,22 @@ inline std::uint32_t nonzero(const Integer& value) { return (combined | (0u - combined)) >> 31; } +constexpr std::uint32_t selectionMask(std::uint32_t choice) { + if consteval { + return 0u - choice; + } else { + // Keep the mask opaque: Clang can otherwise select an input pointer and + // read through it, making the memory address depend on the secret bit. + const volatile std::uint32_t mask = 0u - choice; + return mask; + } +} + constexpr Integer select(const Integer& first, const Integer& second, std::uint32_t choice) { - Integer result; + const auto mask = selectionMask(choice); + Integer result; for (std::size_t i = 0; i != result.size(); ++i) - result[i] = first[i] ^ ((first[i] ^ second[i]) & (0u - choice)); + result[i] = first[i] ^ ((first[i] ^ second[i]) & mask); return result; } diff --git a/include/webfront/tls/detail/Protocol.hpp b/include/webfront/tls/detail/Protocol.hpp index 6b0c4d66..32f0e04b 100644 --- a/include/webfront/tls/detail/Protocol.hpp +++ b/include/webfront/tls/detail/Protocol.hpp @@ -54,7 +54,7 @@ inline ClientHello parseHello(View message, bool retry) { invariant.update(original.first(original.size() - hello.remaining.size())); Reader extensions{hello.vector(2)}; hello.end(); - bool version = false, signature = false, supportedGroup = false, earlyData = false; + bool supportsTls13 = false, signature = false, supportedGroup = false, earlyData = false; std::array seen; std::size_t extensionCount = 0; const auto containsExtension = [&](unsigned kind) { @@ -73,7 +73,7 @@ inline ClientHello parseHello(View message, bool retry) { seen[extensionCount++] = kind; switch (kind) { case 43: - version = contains(extension.vector(1), 2, 0x0304); + supportsTls13 = contains(extension.vector(1), 2, 0x0304); break; case 13: signature = contains(extension.vector(2), 2, signatureScheme); @@ -116,7 +116,7 @@ inline ClientHello parseHello(View message, bool retry) { if (kind != 51 && kind != 21 && kind != 41 && kind != 42) invariant.update(encoded.first(encoded.size() - extensions.remaining.size())); } - if (!version) + if (!supportsTls13) throw Error("TLS 1.3 required", 70); if (!offeredSuite || !signature || !supportedGroup) throw Error("no common cipher suite, signature or group", 40); @@ -145,9 +145,9 @@ inline ClientHello parseHello(View message, bool retry) { } inline Bytes serverHello(View session, View random, View publicKey) { - constexpr std::array version{3, 4}; + constexpr std::array tls13{3, 4}; Bytes extensions; - extension(extensions, 43, version); + extension(extensions, 43, tls13); Bytes keyShare; put(keyShare, group, 2); if (!publicKey.empty()) @@ -170,11 +170,11 @@ struct RecordHeader { inline RecordHeader parseRecord(View header, bool encrypted, bool initial = false) { Reader input{header}; - const auto type = static_cast(input.number(1)); - const auto version = input.number(2); - const auto size = input.number(2); + const auto type = static_cast(input.number(1)); + const auto recordVersion = input.number(2); + const auto size = input.number(2); input.end(); - if (version != 0x0303 && !(initial && version == 0x0301 && type == handshakeRecord)) + if (recordVersion != 0x0303 && !(initial && recordVersion == 0x0301 && type == handshakeRecord)) throw Error("invalid record version", 70); if (size > (encrypted && type == applicationData ? maxCiphertext : maxPlaintext)) throw Error("oversized record", 22); @@ -250,8 +250,15 @@ struct RecordControl { bool updateRequested = false; bool peerNotified = false; - bool beginClose() { - return !std::exchange(closed, true) && !sending; + bool beginClose(Byte failure = 0) { + if (std::exchange(closed, true)) + return false; + pendingAlert = failure; + return !sending; + } + + std::optional takeAlert() { + return std::exchange(pendingAlert, std::nullopt); } // Returns true for a nonempty application record ready to deliver. @@ -294,6 +301,7 @@ struct RecordControl { } private: + std::optional pendingAlert; std::array update{}; std::size_t updateSize = 0; unsigned skipped = 0; diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index b5a8862e..3226ec68 100644 --- a/test/unit/CMakeLists.txt +++ b/test/unit/CMakeLists.txt @@ -24,6 +24,20 @@ if(WEBFRONT_TEST_DOXYGEN) set_tests_properties(DoxygenDocumentation PROPERTIES TIMEOUT 60) endif() +# Optional Memcheck regression for compiler-introduced secret-dependent curve operations. +if(CMAKE_SYSTEM_NAME STREQUAL "Linux" AND CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang") + find_program(WEBFRONT_TEST_VALGRIND valgrind) + find_path(WEBFRONT_TEST_VALGRIND_INCLUDE valgrind/memcheck.h) + if(WEBFRONT_TEST_VALGRIND AND WEBFRONT_TEST_VALGRIND_INCLUDE) + add_executable(tls_constant_time TlsConstantTime.cpp) + target_link_libraries(tls_constant_time PRIVATE WebFront WebFront_warnings) + target_include_directories(tls_constant_time SYSTEM PRIVATE "${WEBFRONT_TEST_VALGRIND_INCLUDE}") + target_compile_options(tls_constant_time PRIVATE -Os) + add_test(NAME TLSConstantTime COMMAND "${WEBFRONT_TEST_VALGRIND}" --tool=memcheck --error-exitcode=1 $) + set_tests_properties(TLSConstantTime PROPERTIES TIMEOUT 30) + endif() +endif() + # The framework's own test: the order of the sections, the failures, the filters and the exit codes. add_executable(bdd_self_test BddSelfTest.cpp) target_link_libraries(bdd_self_test PRIVATE WebFront_test_hardening WebFront_warnings WebFront_options) diff --git a/test/unit/TlsConstantTime.cpp b/test/unit/TlsConstantTime.cpp new file mode 100644 index 00000000..e1061d3d --- /dev/null +++ b/test/unit/TlsConstantTime.cpp @@ -0,0 +1,35 @@ +// Mark only the private inputs undefined so Memcheck detects dependent branches or addresses. +#include + +#include +namespace { +using namespace webfront::tls::detail; + +[[gnu::noinline]] auto runP256(const Integer& k) { + return p256Base(k); +} +[[gnu::noinline]] auto runX25519(const Digest& k) { + return x25519(k, Digest{9}); +} + +} // namespace + +int main(int argc, char**) { + using namespace webfront::tls::detail; + Integer scalar{static_cast(argc), 0xbce6faad, 0x01010101}; + Digest key{static_cast(argc), 0xab, 0x1e, 0xff, 0xc2}; + for (unsigned i = 0; i != 10; ++i) { + scalar[2] ^= 1u << i; + key[i] ^= static_cast(1 + i); + VALGRIND_MAKE_MEM_UNDEFINED(scalar.data(), sizeof(scalar)); + VALGRIND_MAKE_MEM_UNDEFINED(key.data(), sizeof(key)); + auto point = runP256(scalar); + auto publicKey = runX25519(key); + VALGRIND_MAKE_MEM_DEFINED(scalar.data(), sizeof(scalar)); + VALGRIND_MAKE_MEM_DEFINED(key.data(), sizeof(key)); + VALGRIND_MAKE_MEM_DEFINED(point.data(), sizeof(point)); + VALGRIND_MAKE_MEM_DEFINED(publicKey.data(), sizeof(publicKey)); + if (!nonzero(point[0]) || equalSecret(publicKey, Digest{})) + return 1; + } +} diff --git a/test/unit/TlsTests.cpp b/test/unit/TlsTests.cpp index 2b9f060d..2200f29e 100644 --- a/test/unit/TlsTests.cpp +++ b/test/unit/TlsTests.cpp @@ -179,7 +179,7 @@ const Scenario tlsRecordControl("TLS application records coordinate updates and limit.receive(tls::applicationData, {}, traffic, secret); }); }); - then("the orderly response is sent once, except during an in-flight write", [&] { + then("the orderly response is sent once after any in-flight write", [&] { for (const bool sending : {false, true}) { tls::RecordControl closing; closing.sending = sending; @@ -188,6 +188,9 @@ const Scenario tlsRecordControl("TLS application records coordinate updates and require(closing.beginClose() == !sending); require(closing.closed); require(!closing.beginClose()); + // The active writer consumes the alert once it has finished its record. + require(closing.takeAlert() == 0); + require(!closing.takeAlert()); } }); then("a fatal peer alert closes without a reply", [&] { @@ -197,6 +200,7 @@ const Scenario tlsRecordControl("TLS application records coordinate updates and }); require(fatal.closed); require(!fatal.beginClose()); + require(!fatal.takeAlert()); }); }); diff --git a/test/web/TlsInterop.cpp b/test/web/TlsInterop.cpp index d403be30..c0a53657 100644 --- a/test/web/TlsInterop.cpp +++ b/test/web/TlsInterop.cpp @@ -2,6 +2,7 @@ #include #include +#include int main(int argc, char** argv) { if (argc != 3) @@ -13,11 +14,14 @@ int main(int argc, char** argv) { reply.wait(); return webfront::http::RouteReply{}; }; - const auto route = app.addRoute("/post/", post, {.postBodyLimit = 64}); + const auto route = app.addRoute("/post/", post, {.postBodyLimit = 64}); + // Publish the port before starting the worker, and keep stdin from flushing cout + // while the POST handler is writing its marker. + std::cout << app.port() << std::endl; + std::cin.tie(nullptr); std::jthread server([&] { app.run(); }); - std::cout << app.port() << std::endl; std::cin.get(); reply.count_down(); std::cin.get(); diff --git a/test/web/TlsInterop.py b/test/web/TlsInterop.py index fa00a3cb..f4cb981c 100644 --- a/test/web/TlsInterop.py +++ b/test/web/TlsInterop.py @@ -25,7 +25,24 @@ def exercise(server, openssl, certificate): def connect(): return context.wrap_socket(socket.create_connection(("127.0.0.1", port), timeout=5), - server_hostname="127.0.0.1") + server_hostname="127.0.0.1", suppress_ragged_eofs=False) + + # A WebSocket Close must be answered before the authenticated TLS EOF. + with connect() as peer: + peer.sendall( + f"GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n" + f"Origin: https://127.0.0.1:{port}\r\n" + "Connection: Upgrade\r\nUpgrade: websocket\r\nSec-WebSocket-Version: 13\r\n" + "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\nSec-WebSocket-Protocol: WebFront_0.1\r\n\r\n".encode() + ) + with peer.makefile("rb") as response: + if response.readline().rstrip() != b"HTTP/1.1 101 Switching Protocols": + raise RuntimeError("WebSocket upgrade failed") + while response.readline() not in (b"\r\n", b""): + pass + peer.sendall(bytes.fromhex("88820102030402ea")) # masked status 1000 + if response.read(4) != bytes.fromhex("880203e8") or response.read(1): + raise RuntimeError("Missing WebSocket Close reply or TLS close_notify") post = b"POST /post/ HTTP/1.1\r\nHost: localhost\r\nContent-Length: 2\r\n\r\n" with connect() as peer: From 9bec337759d109ca29459e91a8b51227d6f6f11e Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 13:42:54 +0100 Subject: [PATCH 06/24] Show the off-loopback TLS warning with default logging (#631) --- docs/TLS.md | 4 ++-- include/webfront/WebFront.hpp | 3 ++- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/docs/TLS.md b/docs/TLS.md index a81169b0..c81b7adb 100644 --- a/docs/TLS.md +++ b/docs/TLS.md @@ -61,8 +61,8 @@ optional second ClientHello and Finished sequence described in the The two X25519 operations and the CertificateVerify signature run on the I/O thread. Other connections wait while this work runs. An incomplete handshake has no built-in deadline. Bursts of handshakes can delay established HTTP/WSS -connections, and idle handshakes can hold sockets and memory. WebFront logs -a warning when the integrated listener is configured outside loopback. +connections, and idle handshakes can hold sockets and memory. WebFront writes +a warning to standard error when the integrated listener is configured outside loopback. On orderly WSS closure initiated by the peer, WebFront answers the WebSocket Close frame and then sends TLS `close_notify`. If TLS closure is requested diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 73802014..8135755b 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -687,7 +687,8 @@ inline WebFrontConfig checkedPtyPageConfig(WebFrontConfig config) { inline std::shared_ptr makeReadBinding(const WebFrontConfig& config, bool secure = false) { checkedAddress(config); if (secure && !isLoopbackName(config.address)) - log::warn("TLS listener outside loopback on {}: handshake cryptography runs on the I/O thread and incomplete handshakes have no deadline", config.address); + std::cerr << "WebFront: TLS listener outside loopback. Handshake cryptography runs on the I/O thread, " + "and incomplete handshakes have no deadline. See docs/TLS.md.\n"; return std::make_shared(secure, config.remoteFileTransport); } } // namespace detail From c3f387504ca5a115e1a203aa3febc12e0454a29c Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:03:43 +0100 Subject: [PATCH 07/24] Bound TLS negotiation and drain secure WebSocket closure (#631) --- docs/TLS.md | 23 ++- docs/adr/ADR-024-tls-integre.md | 9 +- include/webfront/ReadBinding.hpp | 12 +- include/webfront/WebFront.hpp | 13 +- include/webfront/http/WebSocket.hpp | 1 + .../webfront/networking/BasicNetworking.hpp | 6 +- include/webfront/tls/Credentials.hpp | 49 ++++- include/webfront/tls/Server.hpp | 85 ++++++--- include/webfront/tls/detail/Protocol.hpp | 46 +++-- include/webfront/tls/detail/Wire.hpp | 3 + test/driver/WfDriver.hpp | 7 +- test/unit/ReadBindingTests.cpp | 22 ++- test/unit/TlsTests.cpp | 174 ++++++++++++++---- test/unit/WebLinkTests.cpp | 48 +++++ test/web/TlsInterop.py | 9 + 15 files changed, 401 insertions(+), 106 deletions(-) diff --git a/docs/TLS.md b/docs/TLS.md index c81b7adb..79b52914 100644 --- a/docs/TLS.md +++ b/docs/TLS.md @@ -18,6 +18,7 @@ int main() { webfront::tls::WebFront app({ .address = "127.0.0.1", .port = "8443", + .contentPolicy = {.allowMissingOrigin = false}, .tlsCredentials = credentials, }); app.cppFunction("greeting", [] { return std::string("Hello over HTTPS"); }); @@ -44,13 +45,15 @@ the usual bridge origin policy. The file-service binding cookie carries `Secure` File reads for non-associated clients require an explicit `remoteFileTransport` declaration, typically `httpsByDeployment`. The default `refused` applies to TLS listeners as well. Client authentication and authorization belong to the -application. +application. A non-browser client can supply its own `Origin` header. The +example requires the header so requests without one are refused. The initial profile negotiates TLS 1.3, X25519, ECDSA P-256 with SHA-256 and `TLS_CHACHA20_POLY1305_SHA256`. Clients must offer this suite. The profile uses full handshakes and HTTP/1.1. Where clients require AES-GCM, HTTP/2, or another certificate type, terminate TLS at the deployment proxy and configure `httpsByDeployment` if file-service reads are enabled. +Client 0-RTT ciphertext offered with a PSK is discarded, up to 64 KiB. The handshake parser limits ClientHello to 64 KiB and 128 extensions, and the receive buffer to 16,640 bytes of ciphertext. Incoming handshake messages may @@ -58,17 +61,19 @@ span records, with one message at a time. The server supports the ClientHello, optional second ClientHello and Finished sequence described in the [decision record](adr/ADR-024-tls-integre.md). +The TLS handshake has a ten-second deadline from accept through Finished. The two X25519 operations and the CertificateVerify signature run on the I/O -thread. Other connections wait while this work runs. An incomplete handshake -has no built-in deadline. Bursts of handshakes can delay established HTTP/WSS -connections, and idle handshakes can hold sockets and memory. WebFront writes -a warning to standard error when the integrated listener is configured outside loopback. +thread. Other connections wait during that work, so bursts of handshakes can +delay established HTTP/WSS connections. WebFront writes a warning to standard +error when the integrated listener is configured outside loopback. On orderly WSS closure initiated by the peer, WebFront answers the WebSocket -Close frame and then sends TLS `close_notify`. If TLS closure is requested -during a send, the alert follows the current complete TLS record. A reset, -failed write or cancellation during server shutdown can end the connection -before the alert can be sent. +Close frame and then sends TLS `close_notify`. The secure queue retains the +active frame and discards other queued frames and subsequent writes once the +peer's Close is accepted. The TCP queue follows its existing stop behavior. +If TLS closure is requested during a send, the alert follows the current +complete TLS record. A reset, failed write or cancellation during server +shutdown can end the connection before the alert can be sent. ## Constant-time regression diff --git a/docs/adr/ADR-024-tls-integre.md b/docs/adr/ADR-024-tls-integre.md index b87e8e32..3649d1e9 100644 --- a/docs/adr/ADR-024-tls-integre.md +++ b/docs/adr/ADR-024-tls-integre.md @@ -1,13 +1,18 @@ # ADR-024 — TLS intégré -**Statut** : proposé ([#631](https://github.com/ambroise-leclerc/WebFront/issues/631)). +## Versions + +| Version | Date | Statut | Auteur | Changement | Référence | +| --- | --- | --- | --- | --- | --- | +| 1.0 | 2026-11-21 | Proposée | Ambroise Leclerc | Fournisseur TLS 1.3 optionnel et règles de qualification. | [PR #635](https://github.com/ambroise-leclerc/WebFront/pull/635) | Un fournisseur réseau optionnel termine TLS 1.3 avant de livrer le flux au serveur HTTP et au pont WebSocket. Le cœur HTTP garde son fournisseur TCP. Un port TLS sert exclusivement HTTPS et WSS avec HTTP/1.1. Le profil initial utilise X25519 (avec HelloRetryRequest), ChaCha20-Poly1305, SHA-256 et ECDSA P-256 avec nonce RFC 6979. AES-GCM reste conditionné à une implémentation à temps constant raisonnable. La reprise par tickets ajouterait une politique de rotation, une durée de vie et un second chemin de handshake. -Le premier profil fait un handshake complet à chaque connexion. +Le premier profil fait un handshake complet à chaque connexion. Le délai est de dix secondes. Le serveur +écarte jusqu'à 64 Kio de données anticipées refusées pendant la négociation. L'application fournit une chaîne PEM et une clé P-256 via la configuration. Le rechargement explicite publie une paire complète après validation. Les handshakes en cours conservent leur instantané. diff --git a/include/webfront/ReadBinding.hpp b/include/webfront/ReadBinding.hpp index 2db92873..ef459647 100644 --- a/include/webfront/ReadBinding.hpp +++ b/include/webfront/ReadBinding.hpp @@ -206,11 +206,17 @@ class ReadBinding { /// The longest lifetime of a transferable grant, which is a bearer capability. static constexpr std::chrono::seconds maxTransferableLifetime{15 * 60}; + struct Options { + RemoteFileTransport remote = RemoteFileTransport::refused; + bool secure = false; + }; + explicit ReadBinding(RemoteFileTransport declared = RemoteFileTransport::refused, Clock clock = [] { return std::chrono::steady_clock::now(); }) - : transport(declared), now(std::move(clock)), ownPrefix(std::string(cookiePrefix) + automation::channel::nonce().substr(0, 8) + "-") {} + : ReadBinding(Options{.remote = declared}, std::move(clock)) {} - ReadBinding(bool secure, RemoteFileTransport declared, Clock clock = [] { return std::chrono::steady_clock::now(); }) - : ReadBinding(declared, std::move(clock)) { secureTransport = secure; } + explicit ReadBinding(Options options, Clock clock = [] { return std::chrono::steady_clock::now(); }) + : transport(options.remote), secureTransport(options.secure), now(std::move(clock)), + ownPrefix(std::string(cookiePrefix) + automation::channel::nonce().substr(0, 8) + "-") {} /// Names the cookies after `name` (the port the server listens on) instead of a random word, so that a restart on the /// same port erases the cookies of its previous run. Call before the first `open`. diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index 8135755b..a2465a06 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -688,8 +688,8 @@ inline std::shared_ptr makeReadBinding(const WebFrontConfig& config checkedAddress(config); if (secure && !isLoopbackName(config.address)) std::cerr << "WebFront: TLS listener outside loopback. Handshake cryptography runs on the I/O thread, " - "and incomplete handshakes have no deadline. See docs/TLS.md.\n"; - return std::make_shared(secure, config.remoteFileTransport); + "and bursts can delay established connections. See docs/TLS.md.\n"; + return std::make_shared(ReadBinding::Options{.remote = config.remoteFileTransport, .secure = secure}); } } // namespace detail @@ -1142,10 +1142,13 @@ class BasicWF { if (!showing.owns) throw std::logic_error("webfront::BasicWF::show(): another application is already showing a window through this frontend"); } - if constexpr (requires(const ViewLaunch& launch) { Frontend::open(httpAddress, httpPort, htmlFilename, contentPolicy, windowOptions, launch); }) + constexpr bool acceptsViewLaunch = requires(const ViewLaunch& launch) { + Frontend::open(httpAddress, httpPort, htmlFilename, contentPolicy, windowOptions, launch); + }; + if constexpr (networking::secureTransport) + static_assert(acceptsViewLaunch, "An HTTPS frontend must accept ViewLaunch in open()"); + if constexpr (acceptsViewLaunch) Frontend::open(httpAddress, httpPort, htmlFilename, contentPolicy, windowOptions, ViewLaunch{viewSecret, detail::browserOrigin(httpAddress, httpPort, networking::secureTransport)}); - else if constexpr (networking::secureTransport) - static_assert(!networking::secureTransport, "An HTTPS frontend must accept ViewLaunch in open()"); else if constexpr (requires { Frontend::open(httpAddress, httpPort, htmlFilename, contentPolicy, windowOptions); }) Frontend::open(httpAddress, httpPort, htmlFilename, contentPolicy, windowOptions); else if constexpr (requires { Frontend::open(httpAddress, httpPort, htmlFilename, contentPolicy); }) diff --git a/include/webfront/http/WebSocket.hpp b/include/webfront/http/WebSocket.hpp index 8bc979e1..5d927a1f 100644 --- a/include/webfront/http/WebSocket.hpp +++ b/include/webfront/http/WebSocket.hpp @@ -634,6 +634,7 @@ class WebSocket : public std::enable_shared_from_this> { if constexpr (networking::secureTransport) { if (frame->opcode() == Header::Opcode::connectionClose) { nextFrame(true); + if (writtenHandler) writtenHandler(); co_await Net::Close(socket); co_return; } diff --git a/include/webfront/networking/BasicNetworking.hpp b/include/webfront/networking/BasicNetworking.hpp index 1dcbaa68..00950ce3 100644 --- a/include/webfront/networking/BasicNetworking.hpp +++ b/include/webfront/networking/BasicNetworking.hpp @@ -26,9 +26,9 @@ concept Features = requires { }; template -inline constexpr bool secureTransport = [] { - if constexpr (requires { Net::secure; }) - return Net::secure; +inline constexpr bool secureTransport = []() -> bool { + if constexpr (requires { static_cast(Net::secure); }) + return static_cast(Net::secure); return false; }(); diff --git a/include/webfront/tls/Credentials.hpp b/include/webfront/tls/Credentials.hpp index 82566899..538685cd 100644 --- a/include/webfront/tls/Credentials.hpp +++ b/include/webfront/tls/Credentials.hpp @@ -8,7 +8,6 @@ namespace webfront::tls { namespace detail { -inline constexpr std::size_t maxCredentialBytes = 256 * 1024; inline constexpr std::array ecPublicKey{0x2a, 0x86, 0x48, 0xce, 0x3d, 2, 1}; inline constexpr std::array prime256v1{0x2a, 0x86, 0x48, 0xce, 0x3d, 3, 1, 7}; @@ -19,16 +18,38 @@ inline void ecAlgorithm(Reader oid) { oid.end(); } -inline View certificateKey(View certificate) { +inline View certificatePublicKey(View certificate) { Reader input{certificate}; Reader outer{input.der(0x30)}; input.end(); Reader body{outer.der(0x30)}; + Reader signatureAlgorithm{outer.der(0x30)}; + if (signatureAlgorithm.der(6).empty()) + throw Error("empty certificate signature algorithm"); + const auto signature = outer.der(3); + if (signature.size() < 2 || signature.front() != 0) + throw Error("invalid certificate signature"); + outer.end(); if (!body.empty() && body.remaining.front() == 0xa0) body.der(0xa0); for (const Byte type : std::array{2, 0x30, 0x30, 0x30, 0x30}) body.der(type); // serial, signature, issuer, validity, subject - Reader publicKey{body.der(0x30)}; + const auto publicKey = body.der(0x30); + Reader components{publicKey}; + Reader algorithm{components.der(0x30)}; + const auto point = components.der(3); + components.end(); + if (algorithm.der(6).empty() || point.size() < 2 || point.front() != 0) + throw Error("invalid certificate public key"); + for (const Byte tag : std::array{0x81, 0x82, 0xa3}) + if (!body.empty() && body.remaining.front() == tag) + body.der(tag); + body.end(); + return publicKey; +} + +inline View certificateKey(View publicKeyInfo) { + Reader publicKey{publicKeyInfo}; ecAlgorithm({publicKey.der(0x30)}); const auto point = publicKey.der(3); publicKey.end(); @@ -88,6 +109,14 @@ inline Bytes pem(std::string_view& source, std::string_view label) { throw Error("unterminated PEM block"); constexpr std::string_view alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; Bytes decoded; + struct WipeOnFailure { + Bytes& bytes; + bool active = true; + ~WipeOnFailure() { + if (active) + wipe(bytes.data(), bytes.size()); + } + } erase{decoded}; decoded.reserve(stop / 4 * 3 + 3); unsigned bits = 0, count = 0, padding = 0; for (const auto character : source.substr(0, stop)) { @@ -110,6 +139,7 @@ inline Bytes pem(std::string_view& source, std::string_view label) { if (decoded.empty() || count != 2 * padding || padding > 2 || (bits & ((1u << count) - 1)) != 0) throw Error("invalid PEM padding"); source.remove_prefix(stop + end.size()); + erase.active = false; return decoded; } @@ -159,15 +189,20 @@ inline std::shared_ptr loadIdentity(const std::filesystem::path& std::ranges::copy(encode(x), point.begin()); std::ranges::copy(encode(y), point.begin() + 32); auto leaf = pem(chainPem, "CERTIFICATE"); - if (!std::ranges::equal(certificateKey(leaf), point)) + if (!std::ranges::equal(certificateKey(certificatePublicKey(leaf)), point)) throw Error("certificate and private key do not match"); - Bytes entries; - for (auto certificate = std::move(leaf); !certificate.empty(); certificate = pem(chainPem, "CERTIFICATE")) { + Bytes entries; + const auto add = [&](View certificate) { vector(entries, certificate, 3); put(entries, 0, 2); // CertificateEntry extensions + }; + add(leaf); + for (auto certificate = pem(chainPem, "CERTIFICATE"); !certificate.empty(); certificate = pem(chainPem, "CERTIFICATE")) { + certificatePublicKey(certificate); + add(certificate); } - Bytes body{0}; // empty certificate_request_context + Bytes body{0}; // empty certificate_request_context vector(body, entries, 3); identity->certificateMessage = handshake(11, body); return identity; diff --git a/include/webfront/tls/Server.hpp b/include/webfront/tls/Server.hpp index 27f0f194..4faeea21 100644 --- a/include/webfront/tls/Server.hpp +++ b/include/webfront/tls/Server.hpp @@ -3,6 +3,7 @@ #include "../networking/TCPNetworkingStdnet.hpp" #include "Credentials.hpp" #include "detail/Protocol.hpp" +#include namespace webfront::tls { /// TCP-style stream provider. Handshake, reads and writes run on the same server I/O context. @@ -20,7 +21,8 @@ class Server : public networking::TCPStdnet { detail::Traffic read, write; detail::Secret<> readSecret{}, writeSecret{}; Bytes input; - std::size_t offset = 0; + std::size_t earlyBytes = 0; + std::size_t offset = 0; detail::RecordControl control; bool compat = false; bool writeEncrypted = false; @@ -49,21 +51,13 @@ class Server : public networking::TCPStdnet { }); } - // The HTTP server invokes this in its per-connection task, so an incomplete handshake never holds up accept(). + // Both senders complete on the I/O context. The winner cancels and joins the other. static Task Handshake(Socket& socket, const Acceptor& acceptor) { - Byte failure = 0; - try { - socket.connection = std::make_unique(); - co_await negotiate(socket, acceptor.credentials->snapshot()); - co_return; - } catch (const detail::Error& error) { - failure = error.alert; - } - try { - const std::array alert{2, failure}; - co_await writeRecord(socket, detail::alert, alert); - } catch (const std::system_error&) {} - throw std::system_error(std::make_error_code(std::errc::protocol_error)); + using namespace std::chrono_literals; + auto deadline = networking::ex::then(TCP::ResumeAfter(socket, 10s), [] { + throw std::system_error(std::make_error_code(std::errc::timed_out)); + }); + co_await exec::when_any(runHandshake(socket, acceptor), std::move(deadline)); } static Result Receive(Socket& socket, MutableBuffer target) { @@ -89,6 +83,9 @@ class Server : public networking::TCPStdnet { } } catch (const Error& error) { failure = error.alert; + } catch (const std::system_error&) { + state.control.transportLost(); + throw; } if (state.control.beginClose(failure)) co_await finishClose(socket); @@ -147,6 +144,22 @@ class Server : public networking::TCPStdnet { } private: + static Task runHandshake(Socket& socket, const Acceptor& acceptor) { + Byte failure = 0; + try { + socket.connection = std::make_unique(); + co_await negotiate(socket, acceptor.credentials->snapshot()); + co_return; + } catch (const detail::Error& error) { + failure = error.alert; + } + try { + const std::array alert{2, failure}; + co_await writeRecord(socket, detail::alert, alert); + } catch (const std::system_error&) {} + throw std::system_error(std::make_error_code(std::errc::protocol_error)); + } + static Task finishClose(Socket& socket) { const auto failure = socket.connection->control.takeAlert(); if (!failure) @@ -176,7 +189,7 @@ class Server : public networking::TCPStdnet { for (;;) { std::array header; co_await readExact(socket, header); - const auto [type, size] = parseRecord(header, encrypted, initial); + const auto [type, size] = parseRecord(header, encrypted || state.earlyBytes != 0, initial); if (size > state.input.capacity()) state.input.reserve(size); state.input.resize(size); @@ -185,8 +198,25 @@ class Server : public networking::TCPStdnet { state.compat = true; continue; } - if (encrypted && type == applicationData) - co_return state.read.open(header, state.input); + if (type == applicationData) { + if (encrypted) { + try { + const auto inner = state.read.open(header, state.input); + state.earlyBytes = 0; + co_return inner; + } catch (const Error& error) { + if (error.alert != 20 || state.earlyBytes == 0) + throw; + } + } + if (state.earlyBytes != 0) { + const auto wireSize = size + header.size(); + if (wireSize > state.earlyBytes) + throw Error("too much rejected early data", 10); + state.earlyBytes -= wireSize; + continue; + } + } if (!encrypted && (type == handshakeRecord || type == alert)) co_return type; throw Error("unexpected record type", 10); @@ -215,7 +245,7 @@ class Server : public networking::TCPStdnet { auto& state = *socket.connection; if (state.control.closed) throw std::system_error(std::make_error_code(std::errc::connection_reset)); - if (std::exchange(state.control.updateRequested, false)) { + while (std::exchange(state.control.updateRequested, false)) { constexpr std::array update{24, 0, 0, 1, 0}; co_await writeRecord(socket, handshakeRecord, update); state.writeSecret = {expandLabel(state.writeSecret, "traffic upd")}; @@ -261,11 +291,13 @@ class Server : public networking::TCPStdnet { static Task negotiate(Socket& socket, std::shared_ptr identity) { using namespace detail; - auto& state = *socket.connection; - Sha256 transcript; - auto message = co_await readHandshake(socket, 65536, false, true); - auto hello = parseHello(message, false); - bool retry = hello.share.empty(); + auto& state = *socket.connection; + Sha256 transcript; + auto message = co_await readHandshake(socket, 65536, false, true); + auto hello = parseHello(message, false); + if (hello.earlyData) + state.earlyBytes = 64 * 1024; + bool retry = hello.share.empty(); constexpr std::array ccs{1}; if (retry) { const auto first = hello.invariant; @@ -274,8 +306,9 @@ class Server : public networking::TCPStdnet { co_await writeHandshake(socket, transcript, serverHello(hello.session, retryRandom, {})); if (compat) co_await writeRecord(socket, changeCipherSpec, ccs); - message = co_await readHandshake(socket, 65536, false); - hello = parseHello(message, true); + message = co_await readHandshake(socket, 65536, false); + state.earlyBytes = 0; + hello = parseHello(message, true); if (hello.invariant != first || hello.share.empty() || hello.shareCount != 1) throw Error("invalid second ClientHello", 47); } diff --git a/include/webfront/tls/detail/Protocol.hpp b/include/webfront/tls/detail/Protocol.hpp index 32f0e04b..05b8fcb5 100644 --- a/include/webfront/tls/detail/Protocol.hpp +++ b/include/webfront/tls/detail/Protocol.hpp @@ -30,6 +30,7 @@ struct ClientHello { Digest invariant; unsigned shareCount = 0; bool alpn = false; + bool earlyData = false; }; inline ClientHello parseHello(View message, bool retry) { @@ -54,7 +55,7 @@ inline ClientHello parseHello(View message, bool retry) { invariant.update(original.first(original.size() - hello.remaining.size())); Reader extensions{hello.vector(2)}; hello.end(); - bool supportsTls13 = false, signature = false, supportedGroup = false, earlyData = false; + bool supportsTls13 = false, signature = false, supportedGroup = false; std::array seen; std::size_t extensionCount = 0; const auto containsExtension = [&](unsigned kind) { @@ -86,7 +87,11 @@ inline ClientHello parseHello(View message, bool retry) { shares = extension.vector(2); break; case 42: - earlyData = true; + result.earlyData = true; + break; + case 45: + if (extension.vector(1).empty()) + throw Error("empty psk_key_exchange_modes", 50); break; case 44: throw Error("unexpected ClientHello cookie", 47); @@ -111,7 +116,7 @@ inline ClientHello parseHello(View message, bool retry) { default: break; } - if (kind == 43 || kind == 13 || kind == 10 || kind == 51 || kind == 42 || kind == 16) + if (kind == 43 || kind == 13 || kind == 10 || kind == 51 || kind == 42 || kind == 45 || kind == 16) extension.end(); if (kind != 51 && kind != 21 && kind != 41 && kind != 42) invariant.update(encoded.first(encoded.size() - extensions.remaining.size())); @@ -120,7 +125,10 @@ inline ClientHello parseHello(View message, bool retry) { throw Error("TLS 1.3 required", 70); if (!offeredSuite || !signature || !supportedGroup) throw Error("no common cipher suite, signature or group", 40); - if (earlyData && (retry || !containsExtension(41))) + const bool hasPsk = containsExtension(41); + if (hasPsk && !containsExtension(45)) + throw Error("PSK offer missing psk_key_exchange_modes", 109); + if (result.earlyData && (retry || !hasPsk)) throw Error("unexpected early_data", 47); Reader keys{shares}; std::size_t groupOffset = 0; @@ -201,8 +209,9 @@ struct Traffic { record[3] = static_cast((size + 17) >> 8); record[4] = static_cast(size + 17); record[5 + size] = type; - const auto nonce = nextNonce(); - auto payload = std::span(record).subspan(5, size + 1); + const auto nonce = recordNonce(); + ++sequence; + auto payload = std::span(record).subspan(5, size + 1); chachaXor(key, nonce, payload); std::ranges::copy(polyTag(key, nonce, View(record).first(5), payload), record.data() + 6 + size); } @@ -210,12 +219,15 @@ struct Traffic { Byte open(View header, Bytes& payload) { if (payload.size() < 17) throw Error("short ciphertext"); - const auto nonce = nextNonce(); + const auto nonce = recordNonce(); const auto size = payload.size() - 16; const auto ciphertext = std::span(payload).first(size); const auto expectedTag = polyTag(key, nonce, header, ciphertext); if (!equalSecret(expectedTag, View(payload).subspan(size))) throw Error("invalid authentication tag", 20); + ++sequence; + if (size > maxPlaintext + 1) + throw Error("oversized inner plaintext", 22); chachaXor(key, nonce, ciphertext); payload.resize(size); while (!payload.empty() && payload.back() == 0) @@ -224,19 +236,16 @@ struct Traffic { throw Error("missing inner record type", 10); const auto type = payload.back(); payload.pop_back(); - if (payload.size() > maxPlaintext) - throw Error("oversized inner plaintext", 22); return type; } private: - Nonce nextNonce() { + Nonce recordNonce() const { if (sequence == UINT64_MAX) throw Error("record sequence exhausted", 80); auto nonce = iv; for (unsigned i = 0; i != 8; ++i) nonce[11 - i] ^= static_cast(sequence >> (8 * i)); - ++sequence; return nonce; } Secret<> key{}; @@ -257,6 +266,11 @@ struct RecordControl { return !sending; } + void transportLost() { + closed = true; + pendingAlert.reset(); + } + std::optional takeAlert() { return std::exchange(pendingAlert, std::nullopt); } @@ -264,10 +278,18 @@ struct RecordControl { // Returns true for a nonempty application record ready to deliver. bool receive(Byte type, View input, Traffic& traffic, Secret<>& secret) { if (type == alert && input.size() == 2) { + // TLS 1.3 uses the description; user_canceled (90) can precede close_notify. + if (input[1] == 90) { + if (++skipped > 32) + throw Error("too many consecutive control or empty records", 10); + return false; + } if (input[1] != 0) { - closed = true; + transportLost(); throw std::system_error(std::make_error_code(std::errc::connection_aborted)); } + if (updateSize != 0) + throw Error("close_notify interrupted a KeyUpdate", 10); peerNotified = true; return false; } diff --git a/include/webfront/tls/detail/Wire.hpp b/include/webfront/tls/detail/Wire.hpp index 4f25544b..f7e363fd 100644 --- a/include/webfront/tls/detail/Wire.hpp +++ b/include/webfront/tls/detail/Wire.hpp @@ -2,6 +2,7 @@ #include "Crypto.hpp" namespace webfront::tls::detail { +inline constexpr std::size_t maxCredentialBytes = 256 * 1024; struct Error : std::runtime_error { Error(std::string_view message, Byte code = 50) : std::runtime_error("TLS: " + std::string(message)), alert(code) {} Byte alert; @@ -48,6 +49,8 @@ struct Reader { if (size < (width == 1 ? 128u : 1u << (8 * (width - 1)))) throw Error("noncanonical DER length"); } + if (size > maxCredentialBytes) + throw Error("oversized DER value"); return take(size); } }; diff --git a/test/driver/WfDriver.hpp b/test/driver/WfDriver.hpp index 4c107829..4a7b7985 100644 --- a/test/driver/WfDriver.hpp +++ b/test/driver/WfDriver.hpp @@ -72,7 +72,7 @@ struct DriverCEFFrontend : frontend::CEFFrontend { open(address, port, page, policy, {}, {}); } static void open(std::string_view address, std::string_view port, std::string_view page, const ContentPolicy& policy, - const WindowOptions&, const ViewLaunch& launch) { + const WindowOptions& window, const ViewLaunch& launch) { #if defined(WEBFRONT_EMBED_CEF) && defined(__linux__) const auto* profile = std::getenv("WEBFRONT_TEST_CEF_PROFILE"); if (!profile || !*profile) @@ -80,10 +80,9 @@ struct DriverCEFFrontend : frontend::CEFFrontend { const auto url = frontend::detail::applicationUrl(address, port, page, launch.origin); cef::detail::openWindow(url, webfront::detail::BoundContentPolicy{url, policy}, nullptr, - std::filesystem::path(profile)); + std::filesystem::path(profile), window, false, launch); #else - (void)launch; - frontend::CEFFrontend::open(address, port, page, policy); + frontend::CEFFrontend::open(address, port, page, policy, window, launch); #endif } }; diff --git a/test/unit/ReadBindingTests.cpp b/test/unit/ReadBindingTests.cpp index 0a2f26e9..033fa711 100644 --- a/test/unit/ReadBindingTests.cpp +++ b/test/unit/ReadBindingTests.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -74,7 +75,7 @@ struct Fixture { std::any lastContext; explicit Fixture(RemoteFileTransport transport = RemoteFileTransport::refused, bool secure = false) - : binding(secure, transport, [this] { return time; }) { + : binding(ReadBinding::Options{.remote = transport, .secure = secure}, [this] { return time; }) { read = binding.readHandler("route-a", std::string(readPrefix), [this](const http::RouteRequest&, const ReadGrant& grant) { lastRest = std::string(grant.rest); lastContext = grant.context; @@ -799,3 +800,22 @@ const Scenario droppingGrant{"Dropping a grant never runs its context's destruct fixture.binding.shutdown(); }); }}; + + +const Scenario secureListenerWarning{"An integrated TLS listener outside loopback warns without a log sink", [] { + std::ostringstream output; + struct Restore { + std::streambuf* previous; + ~Restore() { std::cerr.rdbuf(previous); } + } restore{std::cerr.rdbuf(output.rdbuf())}; + then("loopback and the TCP provider stay quiet", [&] { + detail::makeReadBinding(WebFrontConfig{}, true); + detail::makeReadBinding(WebFrontConfig{.address = "0.0.0.0"}, false); + require(output.str().empty()); + }); + then("wildcard TLS reports the synchronous work on standard error", [&] { + detail::makeReadBinding(WebFrontConfig{.address = "0.0.0.0"}, true); + require(output.str().contains("TLS listener outside loopback")); + require(output.str().contains("bursts can delay established connections")); + }); +}}; diff --git a/test/unit/TlsTests.cpp b/test/unit/TlsTests.cpp index 2200f29e..90d8dd04 100644 --- a/test/unit/TlsTests.cpp +++ b/test/unit/TlsTests.cpp @@ -120,6 +120,26 @@ const Scenario tlsRefusals("TLS rejects invalid framing and negotiation", {"fast tls::parseHello(hello, false); }); }); + then("a PSK offer requires key-exchange modes, and early data is forbidden on retry", [] { + auto hello = traceHello(); + // Remove the modes extension from the trace and append an early-data PSK offer. + const auto modes = tlsHex("002d00020101"); + const auto pos = std::ranges::search(hello, modes).begin(); + require(pos != hello.end()); + hello.erase(pos, pos + modes.size()); + tls::append(hello, tlsHex("002a00000029002c000700010100000000002120")); + hello.resize(hello.size() + 32); + const auto lengths = [&] { + hello[3] = static_cast(hello.size() - 4); + hello[50] = static_cast(hello.size() - 51); + }; + lengths(); + requireThrows([&] { tls::parseHello(hello, false); }, contains("missing psk_key_exchange_modes")); + hello.insert(hello.begin() + 51, modes.begin(), modes.end()); + lengths(); + require(tls::parseHello(hello, false).earlyData); + requireThrows([&] { tls::parseHello(hello, true); }, contains("unexpected early_data")); + }); then("oversized records and corrupted authentication tags are refused", [] { requireThrows([] { tls::parseRecord(tlsHex("1703034101"), true); @@ -134,6 +154,29 @@ const Scenario tlsRefusals("TLS rejects invalid framing and negotiation", {"fast requireThrows([&] { receiver.open(View(record).first(5), payload); }); + payload.back() ^= 1; + require(receiver.open(View(record).first(5), payload) == tls::applicationData); + }); + then("the authenticated size limit includes the type and padding", [] { + const auto key = tls::expandLabel(tls::zeros, "key"); + tls::Nonce nonce; + std::ranges::copy_n(tls::expandLabel(tls::zeros, "iv", {}, 12).begin(), nonce.size(), nonce.begin()); + for (const bool padded : {false, true}) { + Bytes payload(tls::maxPlaintext + 1 + padded, 0); + payload[tls::maxPlaintext] = tls::applicationData; + Bytes header{tls::applicationData, 3, 3}; + tls::put(header, payload.size() + 16, 2); + tls::chachaXor(key, nonce, payload); + tls::append(payload, tls::polyTag(key, nonce, header, payload)); + tls::Traffic receiver; + receiver.install(tls::zeros); + if (padded) + requireThrows([&] { receiver.open(header, payload); }, contains("oversized inner plaintext")); + else { + require(receiver.open(header, payload) == tls::applicationData); + require(payload.size() == tls::maxPlaintext); + } + } }); }); } // namespace @@ -193,6 +236,29 @@ const Scenario tlsRecordControl("TLS application records coordinate updates and require(!closing.takeAlert()); } }); + then("a transport reset discards a pending alert and prohibits new writes", [&] { + tls::RecordControl reset; + reset.sending = true; + require(!reset.beginClose()); + reset.transportLost(); + require(reset.closed); + require(!reset.takeAlert()); + }); + then("user_canceled allows the peer to follow with close_notify", [&] { + tls::RecordControl warning; + require(!warning.receive(tls::alert, tlsHex("015a"), traffic, secret)); + require(!warning.closed); + require(!warning.receive(tls::alert, tlsHex("0100"), traffic, secret)); + require(warning.peerNotified); + }); + then("close_notify cannot interrupt a fragmented KeyUpdate", [&] { + tls::RecordControl fragmented; + require(!fragmented.receive(tls::handshakeRecord, tlsHex("18"), traffic, secret)); + requireThrows([&] { + fragmented.receive(tls::alert, tlsHex("0100"), traffic, secret); + }); + require(!fragmented.peerNotified); + }); then("a fatal peer alert closes without a reply", [&] { tls::RecordControl fatal; requireThrows([&] { @@ -206,16 +272,20 @@ const Scenario tlsRecordControl("TLS application records coordinate updates and const Scenario tlsPolyBoundary("Poly1305 reduction handles a carry around bit 130", [] { constexpr auto max = tls::polyMask; - tls::PolyLimbs primeMinusOne{max - 5, max, max, max, max}; - const auto unchanged = primeMinusOne; - tls::reducePoly(primeMinusOne); - require(primeMinusOne == unchanged); - tls::PolyLimbs prime{max - 4, max, max, max, max}; - tls::reducePoly(prime); - require(prime == tls::PolyLimbs{}); - tls::PolyLimbs wide{max + 1, max, max, max, max}; - tls::reducePoly(wide); - require(wide == (tls::PolyLimbs{5, 0, 0, 0, 0})); + then("the modulus is reduced to zero and its predecessor stays canonical", [&] { + tls::PolyLimbs predecessor{max - 5, max, max, max, max}; + const auto unchanged = predecessor; + tls::reducePoly(predecessor); + require(predecessor == unchanged); + tls::PolyLimbs prime{max - 4, max, max, max, max}; + tls::reducePoly(prime); + require(prime == tls::PolyLimbs{}); + }); + then("a carry crosses the five limbs and folds back as five", [&] { + tls::PolyLimbs wide{max + 1, max, max, max, max}; + tls::reducePoly(wide); + require(wide == (tls::PolyLimbs{5, 0, 0, 0, 0})); + }); }); const Scenario tlsCredentials("TLS loads matching PEM formats and preserves the published identity on reload failure", [] { @@ -226,33 +296,69 @@ const Scenario tlsCredentials("TLS loads matching PEM formats and preserves the const auto pkcs8 = credentials.snapshot(); credentials.reload(certificate, sec1); const auto expected = credentials.snapshot(); - require(expected != pkcs8); - require(tls::equalSecret(expected->key, pkcs8->key)); + then("the two key encodings produce the same key", [&] { + require(expected != pkcs8); + require(tls::equalSecret(expected->key, pkcs8->key)); + }); webfront::test::TemporaryDirectory temporary; - const auto invalid = temporary.path() / "invalid.pem"; - std::ofstream(invalid) << "-----BEGIN EC PRIVATE KEY-----\n????\n-----END EC PRIVATE KEY-----\n"; - requireThrows([&] { - credentials.reload(certificate, invalid); + const auto invalid = temporary.path() / "invalid.pem"; + const auto writePem = [](const auto& path, std::string_view label, Bytes der) { + std::ofstream(path, std::ios::app) << "-----BEGIN " << label << "-----\n" << webfront::base64::encode(der) << "\n-----END " << label << "-----\n"; + }; + then("an invalid private key PEM preserves the identity", [&] { + std::ofstream(invalid) << "-----BEGIN EC PRIVATE KEY-----\nAAAA????\n-----END EC PRIVATE KEY-----\n"; + requireThrows([&] { + credentials.reload(certificate, invalid); + }); + require(credentials.snapshot() == expected); + }); + then("a nonmatching private key preserves the identity", [&] { + std::string source; + tls::readPemFile(sec1, source); + std::string_view pem = source; + auto der = tls::pem(pem, "EC PRIVATE KEY"); + tls::Reader outer{der}; + tls::Reader key{outer.der(0x30)}; + key.der(2); + const auto scalar = key.der(4); + der[static_cast(scalar.data() - der.data())] ^= 1; + const auto keyPath = temporary.path() / "other-key.pem"; + writePem(keyPath, "EC PRIVATE KEY", std::move(der)); + requireThrows( + [&] { + credentials.reload(certificate, keyPath); + }, + contains("certificate and private key do not match")); + require(credentials.snapshot() == expected); }); - require(credentials.snapshot() == expected); + then("an unsigned leaf or malformed intermediate preserves the identity", [&] { + std::string source; + tls::readPemFile(certificate, source); + std::string_view pem = source; + auto leaf = tls::pem(pem, "CERTIFICATE"); + const auto chain = temporary.path() / "chain.pem"; + writePem(chain, "CERTIFICATE", leaf); + writePem(chain, "CERTIFICATE", Bytes{0}); + requireThrows([&] { + credentials.reload(chain, sec1); + }); + require(credentials.snapshot() == expected); - std::string source; - tls::readPemFile(sec1, source); - std::string_view pem = source; - auto der = tls::pem(pem, "EC PRIVATE KEY"); - tls::Reader outer{der}; - const auto keySequence = outer.der(0x30); - tls::Reader key{keySequence}; - key.der(2); - const auto scalar = key.der(4); - der[static_cast(scalar.data() - der.data())] ^= 1; - std::ofstream(invalid) << "-----BEGIN EC PRIVATE KEY-----\n" << webfront::base64::encode(der) << "\n-----END EC PRIVATE KEY-----\n"; - requireThrows( - [&] { - credentials.reload(certificate, invalid); - }, - contains("certificate and private key do not match")); - require(credentials.snapshot() == expected); + require(leaf[1] == 0x82); // The fixture uses a two-byte DER length. + tls::Reader input{leaf}; + tls::Reader outer{input.der(0x30)}; + outer.der(0x30); + const auto size = leaf.size() - outer.remaining.size(); + leaf.resize(size); + leaf[2] = static_cast((size - 4) >> 8); + leaf[3] = static_cast(size - 4); + const auto unsignedLeaf = temporary.path() / "unsigned.pem"; + writePem(unsignedLeaf, "CERTIFICATE", std::move(leaf)); + requireThrows([&] { + credentials.reload(unsignedLeaf, sec1); + }); + require(credentials.snapshot() == expected); + }); }); } // namespace diff --git a/test/unit/WebLinkTests.cpp b/test/unit/WebLinkTests.cpp index e9ee1d8e..6f66c877 100644 --- a/test/unit/WebLinkTests.cpp +++ b/test/unit/WebLinkTests.cpp @@ -557,3 +557,51 @@ const Scenario webLinkNever{"WebLink never logs the payload of an incoming messa require(logged.find("QQQQ") == string::npos); require(logged.find("51 51") == string::npos); }}; + +namespace { +struct SecureCloseTestNetwork : InjectableNetworking { + static constexpr bool secure = true; + static inline unsigned alerts = 0; + + static networking::Task Close(Socket&) { + ++alerts; + co_return; + } +}; +} + +const Scenario securePeerCloseResumesWriters{"A secure peer Close releases writers during backpressure", [] { + InjectableSocket::reset(); + SecureCloseTestNetwork::alerts = 0; + InlineTaskScope scope; + using Link = WebLink; + vector events; + auto link = make_shared(InjectableSocket{}, WebLinkId{54}, [&](WebLinkEvent event) { events.push_back(event.code); }, scope); + InjectableSocket::deferWrites(); + link->sendError(1, "in flight"); + link->sendError(2, "queued before Close"); + bool waiting = false; + networking::Spawn(scope, networking::ex::inline_scheduler{}, waitWrites(webfront::detail::WritesAtMost{link, 0}, waiting)); + given("a blocked writer and a peer Close frame", [&] { + require(!waiting); + InjectableSocket::receive(std::array{byte{0x88}, byte{0x80}, byte{1}, byte{2}, byte{3}, byte{4}}); + require(waiting); + require(events == vector{WebLinkEvent::Code::closed}); + link->sendError(3, "queued after Close"); + bool last = false; + networking::Spawn(scope, networking::ex::inline_scheduler{}, waitWrites(webfront::detail::WritesAtMost{link, 0}, last)); + then("the terminal frame drains the queue and wakes a late waiter", [&] { + require(!last); + require(SecureCloseTestNetwork::alerts == 0); + while (InjectableSocket::completeDeferredWrites() != 0) {} + require(last); + require(link->pendingWrites() == 0); + require(SecureCloseTestNetwork::alerts == 1); + require(InjectableSocket::wrote("in flight")); + require(!InjectableSocket::wrote("queued before Close")); + require(!InjectableSocket::wrote("queued after Close")); + }); + }); + InjectableSocket::deferWrites(false); + InjectableSocket::reset(); +}}; diff --git a/test/web/TlsInterop.py b/test/web/TlsInterop.py index f4cb981c..a5402101 100644 --- a/test/web/TlsInterop.py +++ b/test/web/TlsInterop.py @@ -20,6 +20,11 @@ def exercise(server, openssl, certificate): if retry.stdout.count(b", ServerHello") != 2 or b"HTTP/1.1 200 OK" not in retry.stdout: raise RuntimeError(f"HelloRetryRequest or HTTP response missing: {retry.stdout!r} {retry.stderr!r}") + with socket.create_connection(("127.0.0.1", port), timeout=13) as stalled: + stalled.sendall(b"\x16\x03") + if stalled.recv(1) != b"": + raise RuntimeError("Incomplete TLS record should be closed at the handshake deadline") + context = ssl.create_default_context(cafile=certificate) context.minimum_version = ssl.TLSVersion.TLSv1_3 @@ -50,6 +55,10 @@ def connect(): with peer.unwrap(): pass # close_notify is acknowledged even though the HTTP body is incomplete + with connect() as peer: + peer.sendall(post + b"x") + peer.setsockopt(socket.SOL_SOCKET, socket.SO_LINGER, struct.pack("ii", 1, 0)) + with connect() as peer: peer.sendall(post + b"ok") if not select.select([server.stdout], [], [], 5)[0] or server.stdout.readline().strip() != "post": From c9f0e30058a1c66f423975b914d7c211930ed32c Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:03:55 +0100 Subject: [PATCH 08/24] Keep PSK fixture iterator arithmetic signedness-safe (#631) --- test/unit/TlsTests.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/test/unit/TlsTests.cpp b/test/unit/TlsTests.cpp index 90d8dd04..05866656 100644 --- a/test/unit/TlsTests.cpp +++ b/test/unit/TlsTests.cpp @@ -124,9 +124,9 @@ const Scenario tlsRefusals("TLS rejects invalid framing and negotiation", {"fast auto hello = traceHello(); // Remove the modes extension from the trace and append an early-data PSK offer. const auto modes = tlsHex("002d00020101"); - const auto pos = std::ranges::search(hello, modes).begin(); - require(pos != hello.end()); - hello.erase(pos, pos + modes.size()); + const auto match = std::ranges::search(hello, modes); + require(!match.empty()); + hello.erase(match.begin(), match.end()); tls::append(hello, tlsHex("002a00000029002c000700010100000000002120")); hello.resize(hello.size() + 32); const auto lengths = [&] { From 9cf9c4a93cb0be3022f62b663daa679e3f39f62d Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:06:05 +0100 Subject: [PATCH 09/24] Preserve braced ReadBinding construction with typed options (#631) --- include/webfront/ReadBinding.hpp | 3 ++- test/unit/ReadBindingTests.cpp | 2 ++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/include/webfront/ReadBinding.hpp b/include/webfront/ReadBinding.hpp index ef459647..600873f4 100644 --- a/include/webfront/ReadBinding.hpp +++ b/include/webfront/ReadBinding.hpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -214,7 +215,7 @@ class ReadBinding { explicit ReadBinding(RemoteFileTransport declared = RemoteFileTransport::refused, Clock clock = [] { return std::chrono::steady_clock::now(); }) : ReadBinding(Options{.remote = declared}, std::move(clock)) {} - explicit ReadBinding(Options options, Clock clock = [] { return std::chrono::steady_clock::now(); }) + explicit ReadBinding(std::same_as auto options, Clock clock = [] { return std::chrono::steady_clock::now(); }) : transport(options.remote), secureTransport(options.secure), now(std::move(clock)), ownPrefix(std::string(cookiePrefix) + automation::channel::nonce().substr(0, 8) + "-") {} diff --git a/test/unit/ReadBindingTests.cpp b/test/unit/ReadBindingTests.cpp index 033fa711..b291f1c7 100644 --- a/test/unit/ReadBindingTests.cpp +++ b/test/unit/ReadBindingTests.cpp @@ -29,6 +29,8 @@ using namespace std::chrono_literals; namespace { +static_assert(requires { ReadBinding({}); }); + constexpr std::string_view readPrefix = "/webfront/services/files/"; std::optional header(const http::RouteReply& reply, std::string_view name) { From 1b0608db0438ae2e77c75d127fd93d70464dc91a Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:22:52 +0100 Subject: [PATCH 10/24] Report TLS handshake failures and document closure semantics (#631) --- docs/TLS.md | 15 +++++++++++---- include/webfront/http/HTTPServer.hpp | 3 ++- include/webfront/tls/Server.hpp | 11 +++++++---- include/webfront/tls/detail/Protocol.hpp | 2 ++ test/unit/TlsTests.cpp | 12 ++++++++++++ test/web/TlsInterop.cpp | 5 +++++ test/web/TlsInterop.py | 20 +++++++++++++++++++- 7 files changed, 58 insertions(+), 10 deletions(-) diff --git a/docs/TLS.md b/docs/TLS.md index 79b52914..39e53d8e 100644 --- a/docs/TLS.md +++ b/docs/TLS.md @@ -50,7 +50,9 @@ example requires the header so requests without one are refused. The initial profile negotiates TLS 1.3, X25519, ECDSA P-256 with SHA-256 and `TLS_CHACHA20_POLY1305_SHA256`. Clients must offer this suite. The profile -uses full handshakes and HTTP/1.1. Where clients require AES-GCM, HTTP/2, +uses full handshakes and HTTP/1.1. If a client sends ALPN, it must offer +`http/1.1`. An ALPN offer without it is rejected with `no_application_protocol` +(alert 120). Where clients require AES-GCM, HTTP/2, or another certificate type, terminate TLS at the deployment proxy and configure `httpsByDeployment` if file-service reads are enabled. Client 0-RTT ciphertext offered with a PSK is discarded, up to 64 KiB. @@ -65,15 +67,20 @@ The TLS handshake has a ten-second deadline from accept through Finished. The two X25519 operations and the CertificateVerify signature run on the I/O thread. Other connections wait during that work, so bursts of handshakes can delay established HTTP/WSS connections. WebFront writes a warning to standard -error when the integrated listener is configured outside loopback. +error when the integrated listener is configured outside loopback. Enable +`log::Debug` with a log sink to see handshake failure reasons and error codes. On orderly WSS closure initiated by the peer, WebFront answers the WebSocket Close frame and then sends TLS `close_notify`. The secure queue retains the active frame and discards other queued frames and subsequent writes once the peer's Close is accepted. The TCP queue follows its existing stop behavior. If TLS closure is requested during a send, the alert follows the current -complete TLS record. A reset, failed write or cancellation during server -shutdown can end the connection before the alert can be sent. +complete TLS record. Local `stop()` during a write can cancel that record, +so the peer sees a truncated TLS stream without `close_notify`. A reset or +failed write can also prevent the alert from being sent. + +A peer's `KeyUpdate(update_requested)` is answered before the next +application data record. The response stays pending while the server is idle. ## Constant-time regression diff --git a/include/webfront/http/HTTPServer.hpp b/include/webfront/http/HTTPServer.hpp index 185263b7..c36c90af 100644 --- a/include/webfront/http/HTTPServer.hpp +++ b/include/webfront/http/HTTPServer.hpp @@ -1215,7 +1215,8 @@ class Server { if constexpr (networking::secureTransport) { try { co_await Net::Handshake(socket, acceptor); - } catch (const std::system_error&) { + } catch (const std::system_error& error) { + log::debug("TLS handshake failed ({}:{}): {}", error.code().category().name(), error.code().value(), error.what()); co_return; } catch (const std::exception& error) { log::warn("TLS handshake failed: {}", error.what()); diff --git a/include/webfront/tls/Server.hpp b/include/webfront/tls/Server.hpp index 4faeea21..5073754b 100644 --- a/include/webfront/tls/Server.hpp +++ b/include/webfront/tls/Server.hpp @@ -4,6 +4,7 @@ #include "Credentials.hpp" #include "detail/Protocol.hpp" #include +#include namespace webfront::tls { /// TCP-style stream provider. Handshake, reads and writes run on the same server I/O context. @@ -94,11 +95,13 @@ class Server : public networking::TCPStdnet { co_return std::size_t{0}; } + // HTTP and WebSocket serialize Send calls on each socket. The active writer owns any pending close alert. static Task Send(Socket& socket, auto buffers) { using namespace detail; auto& state = *socket.connection; if (state.control.closed) throw std::system_error(std::make_error_code(std::errc::connection_reset)); + assert(!state.control.sending); state.control.sending = true; struct Sending { bool& active; @@ -145,19 +148,19 @@ class Server : public networking::TCPStdnet { private: static Task runHandshake(Socket& socket, const Acceptor& acceptor) { - Byte failure = 0; + std::optional failure; try { socket.connection = std::make_unique(); co_await negotiate(socket, acceptor.credentials->snapshot()); co_return; } catch (const detail::Error& error) { - failure = error.alert; + failure.emplace(error); } try { - const std::array alert{2, failure}; + const std::array alert{2, failure->alert}; co_await writeRecord(socket, detail::alert, alert); } catch (const std::system_error&) {} - throw std::system_error(std::make_error_code(std::errc::protocol_error)); + throw std::system_error(std::make_error_code(std::errc::protocol_error), failure->what()); } static Task finishClose(Socket& socket) { diff --git a/include/webfront/tls/detail/Protocol.hpp b/include/webfront/tls/detail/Protocol.hpp index 05b8fcb5..fc5ac591 100644 --- a/include/webfront/tls/detail/Protocol.hpp +++ b/include/webfront/tls/detail/Protocol.hpp @@ -123,6 +123,8 @@ inline ClientHello parseHello(View message, bool retry) { } if (!supportsTls13) throw Error("TLS 1.3 required", 70); + if (!containsExtension(13)) + throw Error("missing signature_algorithms", 109); if (!offeredSuite || !signature || !supportedGroup) throw Error("no common cipher suite, signature or group", 40); const bool hasPsk = containsExtension(41); diff --git a/test/unit/TlsTests.cpp b/test/unit/TlsTests.cpp index 05866656..f11e292b 100644 --- a/test/unit/TlsTests.cpp +++ b/test/unit/TlsTests.cpp @@ -120,6 +120,18 @@ const Scenario tlsRefusals("TLS rejects invalid framing and negotiation", {"fast tls::parseHello(hello, false); }); }); + then("a missing signature_algorithms extension elicits missing_extension", [] { + auto hello = traceHello(); + const auto extension = std::ranges::search(hello, tlsHex("000d0020001e")); + require(!extension.empty()); + *extension.begin() = 0xfe; // Unknown extension of the same length. + try { + tls::parseHello(hello, false); + require(false); + } catch (const tls::Error& error) { + require(error.alert == 109); + } + }); then("a PSK offer requires key-exchange modes, and early data is forbidden on retry", [] { auto hello = traceHello(); // Remove the modes extension from the trace and append an early-data PSK offer. diff --git a/test/web/TlsInterop.cpp b/test/web/TlsInterop.cpp index c0a53657..034a4bf2 100644 --- a/test/web/TlsInterop.cpp +++ b/test/web/TlsInterop.cpp @@ -7,6 +7,11 @@ int main(int argc, char** argv) { if (argc != 3) return 1; + webfront::log::setLogLevel(webfront::log::Debug); + webfront::log::addSinks([](std::string_view line) { + if (line.contains("TLS handshake failed (")) + std::clog << line << '\n'; + }); webfront::tls::WebFront<> app({.port = "0", .tlsCredentials = std::make_shared(argv[1], argv[2])}); std::latch reply{1}; const auto post = [&](const webfront::http::RouteRequest&) { diff --git a/test/web/TlsInterop.py b/test/web/TlsInterop.py index a5402101..4087ad11 100644 --- a/test/web/TlsInterop.py +++ b/test/web/TlsInterop.py @@ -1,4 +1,6 @@ """Exercise the TLS provider against an independent OpenSSL client over loopback.""" +import errno +import re import select import socket import ssl @@ -32,8 +34,19 @@ def connect(): return context.wrap_socket(socket.create_connection(("127.0.0.1", port), timeout=5), server_hostname="127.0.0.1", suppress_ragged_eofs=False) + context.set_alpn_protocols(["h2"]) + try: + with connect(): + raise RuntimeError("A client offering only h2 in ALPN should be refused") + except ssl.SSLError as error: + if error.reason != "TLSV1_ALERT_NO_APPLICATION_PROTOCOL": + raise + context.set_alpn_protocols(["http/1.1"]) + # A WebSocket Close must be answered before the authenticated TLS EOF. with connect() as peer: + if peer.selected_alpn_protocol() != "http/1.1": + raise RuntimeError("The server did not negotiate HTTP/1.1 in ALPN") peer.sendall( f"GET / HTTP/1.1\r\nHost: 127.0.0.1:{port}\r\n" f"Origin: https://127.0.0.1:{port}\r\n" @@ -78,10 +91,15 @@ def connect(): program, openssl, fixtures = sys.argv[1:] certificate = Path(fixtures) / "cert.pem" with subprocess.Popen([program, certificate, Path(fixtures) / "key.pem"], - stdin=subprocess.PIPE, stdout=subprocess.PIPE, text=True) as server: + stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True) as server: try: exercise(server, openssl, certificate) finally: server.stdin.close() if server.wait(timeout=5) != 0: raise RuntimeError("TLS interop server exited unsuccessfully") + diagnostics = server.stderr.read() + if not re.search(r"TLS handshake failed \([^:\n]+:\d+\): TLS: HTTP/1\.1 not offered", diagnostics): + raise RuntimeError(f"Missing ALPN handshake diagnostic: {diagnostics!r}") + if not re.search(rf"TLS handshake failed \([^:\n]+:{errno.ETIMEDOUT}\): ", diagnostics): + raise RuntimeError(f"Missing handshake timeout diagnostic: {diagnostics!r}") From 83c50690a442aa0879f7f89cef269f75844b3ce3 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 14:33:16 +0100 Subject: [PATCH 11/24] Cap concurrent TLS handshakes per listener (#631) --- docs/PROJECT_STATUS.md | 3 ++- docs/TLS.md | 22 +++++++++++++++------- docs/adr/ADR-024-tls-integre.md | 7 +++++-- include/webfront/WebFront.hpp | 2 +- include/webfront/tls/Server.hpp | 12 ++++++++++++ include/webfront/tls/detail/Protocol.hpp | 20 ++++++++++---------- test/unit/ReadBindingTests.cpp | 1 + test/unit/TlsTests.cpp | 9 +++++++++ test/web/TlsInterop.py | 19 +++++++++++++++++++ 9 files changed, 74 insertions(+), 21 deletions(-) diff --git a/docs/PROJECT_STATUS.md b/docs/PROJECT_STATUS.md index cb67ceed..4cc3d516 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -160,7 +160,8 @@ are retained for investigation; diagnostics alone do not establish a correction. Manifest permissions bound only the scripts' `context` API. Only browser packages install; installation scripts and native add-ons do not run. The [content policy](CONTENT_POLICY.md) restricts browser origins and navigation. The optional [TLS listener](TLS.md) adds HTTPS and WSS - with TLS 1.3 and ChaCha20-Poly1305. Client authentication remains an application responsibility. + with TLS 1.3 and ChaCha20-Poly1305. Each listener admits 16 concurrent handshakes on the I/O thread. + Client authentication remains an application responsibility. - `fs::NativeStorage` confines writable storage to a declared root while resolving each path, but on POSIX it cannot prevent the effective user or the superuser from moving a directory out of the root during an operation: it detects such a move before a commit and after each operation, at diff --git a/docs/TLS.md b/docs/TLS.md index 39e53d8e..1cc47528 100644 --- a/docs/TLS.md +++ b/docs/TLS.md @@ -30,8 +30,9 @@ Use an ECDSA P-256 leaf certificate whose SAN covers the DNS name users visit. Supply the PEM chain in leaf-first order and an unencrypted PEM private key as a single `PRIVATE KEY` (PKCS#8) or `EC PRIVATE KEY` (SEC1) block. The files accept whitespace around the PEM blocks. Extra text such as `Bag Attributes` -and separate `EC PARAMETERS` blocks are refused. Give the application account -read access to the key. +and separate `EC PARAMETERS` blocks are refused. To generate a single SEC1 +block, use `openssl ecparam -name prime256v1 -genkey -noout -out privkey.pem`. +Give the application account read access to the key. After the certificate manager has written both renewed files, call `credentials->reload(fullchain, privkey)` from the application's renewal hook. It checks that the leaf and key match before publishing them to new handshakes. @@ -63,11 +64,14 @@ span records, with one message at a time. The server supports the ClientHello, optional second ClientHello and Finished sequence described in the [decision record](adr/ADR-024-tls-integre.md). -The TLS handshake has a ten-second deadline from accept through Finished. -The two X25519 operations and the CertificateVerify signature run on the I/O -thread. Other connections wait during that work, so bursts of handshakes can -delay established HTTP/WSS connections. WebFront writes a warning to standard -error when the integrated listener is configured outside loopback. Enable +Each listener admits up to 16 concurrent TLS handshakes, with a ten-second +deadline from accept through Finished. When all slots are occupied, a newly +accepted socket is closed immediately. Established connections release their +slot. The two X25519 operations and the CertificateVerify signature run on +the I/O thread. A sustained rate of incoming handshakes can saturate that +thread and cause denial of service, including for established HTTP/WSS +connections. WebFront writes a warning to standard error when the integrated +listener is configured outside loopback. Enable `log::Debug` with a log sink to see handshake failure reasons and error codes. On orderly WSS closure initiated by the peer, WebFront answers the WebSocket @@ -82,6 +86,10 @@ failed write can also prevent the alert from being sent. A peer's `KeyUpdate(update_requested)` is answered before the next application data record. The response stays pending while the server is idle. +When using `tls::Server` directly, run handshakes for each acceptor on its I/O +thread and serialize `Send` calls on each socket. HTTP and WebSocket enforce +this contract when using `tls::WebFront`. + ## Constant-time regression On Linux with Valgrind and its development headers installed, the optional diff --git a/docs/adr/ADR-024-tls-integre.md b/docs/adr/ADR-024-tls-integre.md index 3649d1e9..e6fc5a2d 100644 --- a/docs/adr/ADR-024-tls-integre.md +++ b/docs/adr/ADR-024-tls-integre.md @@ -11,8 +11,11 @@ Le cœur HTTP garde son fournisseur TCP. Un port TLS sert exclusivement HTTPS et Le profil initial utilise X25519 (avec HelloRetryRequest), ChaCha20-Poly1305, SHA-256 et ECDSA P-256 avec nonce RFC 6979. AES-GCM reste conditionné à une implémentation à temps constant raisonnable. La reprise par tickets ajouterait une politique de rotation, une durée de vie et un second chemin de handshake. -Le premier profil fait un handshake complet à chaque connexion. Le délai est de dix secondes. Le serveur -écarte jusqu'à 64 Kio de données anticipées refusées pendant la négociation. +Le premier profil fait un handshake complet à chaque connexion. Chaque écoute admet jusqu'à 16 négociations +simultanées et ferme immédiatement les connexions excédentaires. Chaque négociation a un délai de dix secondes. +Le serveur écarte jusqu'à 64 Kio de données anticipées refusées pendant la négociation. La cryptographie s'exécute +sur le thread d'E/S. Un débit soutenu de nouvelles négociations peut saturer ce thread et causer un déni de service +pour les connexions établies. Un déploiement exposé à Internet s'appuie sur un proxy avec contrôle d'admission. L'application fournit une chaîne PEM et une clé P-256 via la configuration. Le rechargement explicite publie une paire complète après validation. Les handshakes en cours conservent leur instantané. diff --git a/include/webfront/WebFront.hpp b/include/webfront/WebFront.hpp index a2465a06..15dc2a26 100644 --- a/include/webfront/WebFront.hpp +++ b/include/webfront/WebFront.hpp @@ -688,7 +688,7 @@ inline std::shared_ptr makeReadBinding(const WebFrontConfig& config checkedAddress(config); if (secure && !isLoopbackName(config.address)) std::cerr << "WebFront: TLS listener outside loopback. Handshake cryptography runs on the I/O thread, " - "and bursts can delay established connections. See docs/TLS.md.\n"; + "and bursts can delay established connections or cause denial of service. See docs/TLS.md.\n"; return std::make_shared(ReadBinding::Options{.remote = config.remoteFileTransport, .secure = secure}); } } // namespace detail diff --git a/include/webfront/tls/Server.hpp b/include/webfront/tls/Server.hpp index 5073754b..55d1b40a 100644 --- a/include/webfront/tls/Server.hpp +++ b/include/webfront/tls/Server.hpp @@ -36,6 +36,10 @@ class Server : public networking::TCPStdnet { struct Acceptor : TCP::Acceptor { using TCP::Acceptor::Acceptor; std::shared_ptr credentials; + + private: + friend class Server; + mutable std::size_t pendingHandshakes = 0; // Accessed on the acceptor's I/O thread. }; struct Socket : TCP::Socket { @@ -55,6 +59,14 @@ class Server : public networking::TCPStdnet { // Both senders complete on the I/O context. The winner cancels and joins the other. static Task Handshake(Socket& socket, const Acceptor& acceptor) { using namespace std::chrono_literals; + constexpr std::size_t maxPendingHandshakes = 16; + if (acceptor.pendingHandshakes >= maxPendingHandshakes) + throw std::system_error(std::make_error_code(std::errc::resource_unavailable_try_again), "TLS handshake limit reached"); + ++acceptor.pendingHandshakes; + struct Slot { + std::size_t& pending; + ~Slot() { --pending; } + } slot{acceptor.pendingHandshakes}; auto deadline = networking::ex::then(TCP::ResumeAfter(socket, 10s), [] { throw std::system_error(std::make_error_code(std::errc::timed_out)); }); diff --git a/include/webfront/tls/detail/Protocol.hpp b/include/webfront/tls/detail/Protocol.hpp index fc5ac591..bc4b471f 100644 --- a/include/webfront/tls/detail/Protocol.hpp +++ b/include/webfront/tls/detail/Protocol.hpp @@ -193,6 +193,14 @@ inline RecordHeader parseRecord(View header, bool encrypted, bool initial = fals return {type, size}; } +inline Nonce recordNonce(Nonce nonce, std::uint64_t sequence) { + if (sequence == UINT64_MAX) + throw std::system_error(std::make_error_code(std::errc::value_too_large), "TLS record sequence exhausted"); + for (unsigned i = 0; i != 8; ++i) + nonce[11 - i] ^= static_cast(sequence >> (8 * i)); + return nonce; +} + struct Traffic { void install(View secret) { key = {expandLabel(secret, "key")}; @@ -211,7 +219,7 @@ struct Traffic { record[3] = static_cast((size + 17) >> 8); record[4] = static_cast(size + 17); record[5 + size] = type; - const auto nonce = recordNonce(); + const auto nonce = recordNonce(iv, sequence); ++sequence; auto payload = std::span(record).subspan(5, size + 1); chachaXor(key, nonce, payload); @@ -221,7 +229,7 @@ struct Traffic { Byte open(View header, Bytes& payload) { if (payload.size() < 17) throw Error("short ciphertext"); - const auto nonce = recordNonce(); + const auto nonce = recordNonce(iv, sequence); const auto size = payload.size() - 16; const auto ciphertext = std::span(payload).first(size); const auto expectedTag = polyTag(key, nonce, header, ciphertext); @@ -242,14 +250,6 @@ struct Traffic { } private: - Nonce recordNonce() const { - if (sequence == UINT64_MAX) - throw Error("record sequence exhausted", 80); - auto nonce = iv; - for (unsigned i = 0; i != 8; ++i) - nonce[11 - i] ^= static_cast(sequence >> (8 * i)); - return nonce; - } Secret<> key{}; std::array iv{}; std::uint64_t sequence = 0; diff --git a/test/unit/ReadBindingTests.cpp b/test/unit/ReadBindingTests.cpp index b291f1c7..ef48d73d 100644 --- a/test/unit/ReadBindingTests.cpp +++ b/test/unit/ReadBindingTests.cpp @@ -819,5 +819,6 @@ const Scenario secureListenerWarning{"An integrated TLS listener outside loopbac detail::makeReadBinding(WebFrontConfig{.address = "0.0.0.0"}, true); require(output.str().contains("TLS listener outside loopback")); require(output.str().contains("bursts can delay established connections")); + require(output.str().contains("denial of service")); }); }}; diff --git a/test/unit/TlsTests.cpp b/test/unit/TlsTests.cpp index f11e292b..dbd19c30 100644 --- a/test/unit/TlsTests.cpp +++ b/test/unit/TlsTests.cpp @@ -190,6 +190,15 @@ const Scenario tlsRefusals("TLS rejects invalid framing and negotiation", {"fast } } }); + then("an exhausted record sequence fails as a transport error before wrapping", [] { + require(tls::recordNonce({}, UINT64_MAX - 1).back() == 0xfe); + try { + tls::recordNonce({}, UINT64_MAX); + require(false); + } catch (const std::system_error& error) { + require(error.code() == std::errc::value_too_large); + } + }); }); } // namespace diff --git a/test/web/TlsInterop.py b/test/web/TlsInterop.py index 4087ad11..a0273afe 100644 --- a/test/web/TlsInterop.py +++ b/test/web/TlsInterop.py @@ -7,6 +7,7 @@ import struct import subprocess import sys +from contextlib import ExitStack from pathlib import Path @@ -43,6 +44,24 @@ def connect(): raise context.set_alpn_protocols(["http/1.1"]) + with ExitStack() as pending: + waiting = [pending.enter_context(socket.create_connection(("127.0.0.1", port), timeout=3)) + for _ in range(16)] + with socket.create_connection(("127.0.0.1", port), timeout=3) as excess: + if excess.recv(1) != b"": + raise RuntimeError("A connection beyond the handshake limit should close immediately") + if select.select(waiting, [], [], 0)[0]: + raise RuntimeError("All 16 handshake slots should be available after the earlier timeout") + waiting[0].shutdown(socket.SHUT_WR) + if waiting[0].recv(1) != b"": + raise RuntimeError("The disconnected peer should release its handshake slot") + for _ in range(2): + with connect() as peer: + peer.sendall(request) + with peer.makefile("rb") as response: + if response.readline().rstrip() != b"HTTP/1.1 200 OK": + raise RuntimeError("An admitted handshake should release its slot and serve HTTP") + # A WebSocket Close must be answered before the authenticated TLS EOF. with connect() as peer: if peer.selected_alpn_protocol() != "http/1.1": From 3e1043c70880ab7d4a6ca3aff14a7401335afff0 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:51:46 +0100 Subject: [PATCH 12/24] Verify the default HTTP browser URL and relax TLS test guards (#631) --- test/unit/FrontendContractTests.cpp | 43 +++++++++++++++++++++++++++++ test/web/CMakeLists.txt | 2 +- test/web/TlsInterop.py | 3 +- 3 files changed, 46 insertions(+), 2 deletions(-) diff --git a/test/unit/FrontendContractTests.cpp b/test/unit/FrontendContractTests.cpp index ee725aee..985ed527 100644 --- a/test/unit/FrontendContractTests.cpp +++ b/test/unit/FrontendContractTests.cpp @@ -1,5 +1,6 @@ #include "Mocks.hpp" #include "Bdd.hpp" +#include "TemporaryDirectory.hpp" #include #include #include @@ -14,6 +15,7 @@ #include #include #include +#include #include #include @@ -1290,6 +1292,47 @@ const Scenario systemBrowserLoop{"The system browser's loop ignores a close requ }}; #if !defined(_WIN32) +#if defined(__linux__) || defined(__APPLE__) +const Scenario systemBrowserShowsHttp{"The default browser's show() opens the original HTTP page URL", {"fast"}, [] { + if (browser::isWSL()) { + succeed("WSL uses a PowerShell opener outside PATH"); + return; + } + namespace fs = std::filesystem; + const webfront::test::TemporaryDirectory directory; +#if defined(__APPLE__) + const auto opener = directory.path() / "open"; +#else + const auto opener = directory.path() / "xdg-open"; +#endif + std::ofstream(opener) << "#!/bin/sh\nprintf '%s\\n' \"$1\" > \"$0.url\"\n"; + fs::permissions(opener, fs::perms::owner_all); + + const auto* currentPath = std::getenv("PATH"); + std::istringstream enter{"\n"}; + struct Restore { + std::optional path; + std::streambuf* input; + ~Restore() { + std::cin.rdbuf(input); + if (path) ::setenv("PATH", path->c_str(), 1); + else ::unsetenv("PATH"); + } + } restore{currentPath ? std::optional{currentPath} : std::nullopt, std::cin.rdbuf(enter.rdbuf())}; + require(::setenv("PATH", directory.path().c_str(), 1) == 0); + + WebFront app({.port = "0"}); + app.show("folder/a b.html?x=1#result"); + app.shutdown(); + then("the opener receives the legacy URL with the bound port, query and fragment", [&] { + std::ifstream capture(opener.string() + ".url"); + std::string url; + require(static_cast(std::getline(capture, url))); + require(url == "http://127.0.0.1:" + std::string(app.port()) + "/folder/a%20b.html?x=1#result"); + }); +}}; +#endif + const Scenario systemBrowserLoopUp{"The system browser's loop is up while its opener is still running", [] { given("an opener that lives longer than the close request", [&] { namespace fs = std::filesystem; diff --git a/test/web/CMakeLists.txt b/test/web/CMakeLists.txt index 0e828dfe..ec6a45cc 100644 --- a/test/web/CMakeLists.txt +++ b/test/web/CMakeLists.txt @@ -90,7 +90,7 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Linux") if(Python3_Interpreter_FOUND AND WEBFRONT_TEST_OPENSSL) add_test(NAME TLSOpenSSLInterop COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/TlsInterop.py" $ "${WEBFRONT_TEST_OPENSSL}" "${CMAKE_CURRENT_SOURCE_DIR}/fixtures/tls") - set_tests_properties(TLSOpenSSLInterop PROPERTIES LABELS "web-integration" TIMEOUT 30) + set_tests_properties(TLSOpenSSLInterop PROPERTIES LABELS "web-integration" TIMEOUT 60) endif() endif() diff --git a/test/web/TlsInterop.py b/test/web/TlsInterop.py index a0273afe..a3a74066 100644 --- a/test/web/TlsInterop.py +++ b/test/web/TlsInterop.py @@ -23,7 +23,8 @@ def exercise(server, openssl, certificate): if retry.stdout.count(b", ServerHello") != 2 or b"HTTP/1.1 200 OK" not in retry.stdout: raise RuntimeError(f"HelloRetryRequest or HTTP response missing: {retry.stdout!r} {retry.stderr!r}") - with socket.create_connection(("127.0.0.1", port), timeout=13) as stalled: + # The server owns the ten-second deadline. The client only bounds the wait for a stuck test. + with socket.create_connection(("127.0.0.1", port), timeout=30) as stalled: stalled.sendall(b"\x16\x03") if stalled.recv(1) != b"": raise RuntimeError("Incomplete TLS record should be closed at the handshake deadline") From e882687727dc5c2b5089fc9f80fcb5e657e47c43 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 15:52:41 +0100 Subject: [PATCH 13/24] Check the ALPN alert in the OpenSSL record trace (#631) --- test/web/TlsInterop.py | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/test/web/TlsInterop.py b/test/web/TlsInterop.py index a3a74066..f2960b9a 100644 --- a/test/web/TlsInterop.py +++ b/test/web/TlsInterop.py @@ -36,13 +36,13 @@ def connect(): return context.wrap_socket(socket.create_connection(("127.0.0.1", port), timeout=5), server_hostname="127.0.0.1", suppress_ragged_eofs=False) - context.set_alpn_protocols(["h2"]) - try: - with connect(): - raise RuntimeError("A client offering only h2 in ALPN should be refused") - except ssl.SSLError as error: - if error.reason != "TLSV1_ALERT_NO_APPLICATION_PROTOCOL": - raise + refused = subprocess.run( + [openssl, "s_client", "-connect", f"127.0.0.1:{port}", "-tls1_3", "-alpn", "h2", "-msg"], + input=b"", capture_output=True, timeout=10, + ) + # Check the alert on the wire. Some Python/OpenSSL builds report its reason as unknown. + if not refused.returncode or not re.search(rb"<<< [^\n]*Alert[^\n]*\n[ \t]+02 78\b", refused.stdout): + raise RuntimeError(f"Expected fatal no_application_protocol (120): {refused.stdout!r} {refused.stderr!r}") context.set_alpn_protocols(["http/1.1"]) with ExitStack() as pending: From 1795691af7d7ebcf6b3a3acfd32002e541109deb Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 17:56:53 +0100 Subject: [PATCH 14/24] Split the TLS handshake coroutine for MSVC and harden Receive (#631) negotiate() becomes receiveHello, sendFlight and receiveFinished so MSVC no longer reports C4737. Receive marks the transport lost on any exception. TLS.md states what the handshake cap and the chain checks do not cover. --- docs/TLS.md | 7 ++++- include/webfront/tls/Server.hpp | 51 ++++++++++++++++++++++++--------- 2 files changed, 44 insertions(+), 14 deletions(-) diff --git a/docs/TLS.md b/docs/TLS.md index 1cc47528..420d24da 100644 --- a/docs/TLS.md +++ b/docs/TLS.md @@ -33,6 +33,8 @@ accept whitespace around the PEM blocks. Extra text such as `Bag Attributes` and separate `EC PARAMETERS` blocks are refused. To generate a single SEC1 block, use `openssl ecparam -name prime256v1 -genkey -noout -out privkey.pem`. Give the application account read access to the key. +WebFront checks the structure of each certificate and that the leaf matches the +private key, but not validity dates or the chain's trust: the browser does. After the certificate manager has written both renewed files, call `credentials->reload(fullchain, privkey)` from the application's renewal hook. It checks that the leaf and key match before publishing them to new handshakes. @@ -70,7 +72,10 @@ accepted socket is closed immediately. Established connections release their slot. The two X25519 operations and the CertificateVerify signature run on the I/O thread. A sustained rate of incoming handshakes can saturate that thread and cause denial of service, including for established HTTP/WSS -connections. WebFront writes a warning to standard error when the integrated +connections. The limit of 16 bounds the work in progress, not an attacker's +reach: sixteen idle connections keep every slot for up to ten seconds and can be +renewed, so it is not a defence against denial of service. Put a rate limiter or +a firewall in front of an exposed listener. WebFront writes a warning to standard error when the integrated listener is configured outside loopback. Enable `log::Debug` with a log sink to see handshake failure reasons and error codes. diff --git a/include/webfront/tls/Server.hpp b/include/webfront/tls/Server.hpp index 55d1b40a..b629d31d 100644 --- a/include/webfront/tls/Server.hpp +++ b/include/webfront/tls/Server.hpp @@ -96,7 +96,8 @@ class Server : public networking::TCPStdnet { } } catch (const Error& error) { failure = error.alert; - } catch (const std::system_error&) { + } catch (...) { + // A transport error, or an exception such as bad_alloc: the stream state is unknown, so no alert is attempted. state.control.transportLost(); throw; } @@ -304,12 +305,26 @@ class Server : public networking::TCPStdnet { } } + // MSVC refuses (C4737) one coroutine holding the whole flight, so the handshake runs in three stages. static Task negotiate(Socket& socket, std::shared_ptr identity) { using namespace detail; - auto& state = *socket.connection; - Sha256 transcript; - auto message = co_await readHandshake(socket, 65536, false, true); - auto hello = parseHello(message, false); + Sha256 transcript; + Bytes message; + ClientHello hello; + Secret<> shared{}, clientHandshake{}; + Digest afterFinished{}; + co_await receiveHello(socket, transcript, message, hello, shared); + co_await sendFlight(socket, transcript, *identity, hello.alpn, shared, clientHandshake, afterFinished); + co_await receiveFinished(socket, clientHandshake, afterFinished); + } + + // From the first ClientHello to the ServerHello, including a HelloRetryRequest. Fills the X25519 shared secret. + static Task receiveHello(Socket& socket, detail::Sha256& transcript, detail::Bytes& message, detail::ClientHello& hello, + detail::Secret<>& shared) { + using namespace detail; + auto& state = *socket.connection; + message = co_await readHandshake(socket, 65536, false, true); + hello = parseHello(message, false); if (hello.earlyData) state.earlyBytes = 64 * 1024; bool retry = hello.share.empty(); @@ -329,7 +344,7 @@ class Server : public networking::TCPStdnet { } transcript.update(message); Digest random{}, publicKey{}; - Secret<> scalar{}, shared{}; + Secret<> scalar{}; entropy(random); entropy(scalar); publicKey = x25519(scalar, Digest{9}); @@ -339,19 +354,25 @@ class Server : public networking::TCPStdnet { co_await writeHandshake(socket, transcript, serverHello(hello.session, random, publicKey)); if (!retry && !hello.session.empty()) co_await writeRecord(socket, changeCipherSpec, ccs); + } + // EncryptedExtensions to server Finished, then the application keys. + static Task sendFlight(Socket& socket, detail::Sha256& transcript, const detail::Identity& identity, bool alpn, const detail::Secret<>& shared, + detail::Secret<>& client, detail::Digest& afterFinished) { + using namespace detail; + auto& state = *socket.connection; const auto empty = hash(); const Secret<> early{hmac(zeros, {zeros})}; const Secret<> derived{expandLabel(early, "derived", empty)}; const Secret<> secret{hmac(derived, {shared})}; const auto afterHello = transcript.digest(); - const Secret<> client{expandLabel(secret, "c hs traffic", afterHello)}; + client = {expandLabel(secret, "c hs traffic", afterHello)}; const Secret<> server{expandLabel(secret, "s hs traffic", afterHello)}; state.read.install(client); state.write.install(server); state.writeEncrypted = true; Bytes extensions; - if (hello.alpn) { + if (alpn) { Bytes protocol; vector(protocol, bytes("http/1.1"), 1); Bytes protocols; @@ -361,7 +382,7 @@ class Server : public networking::TCPStdnet { Bytes encryptedExtensions; vector(encryptedExtensions, extensions, 2); co_await writeHandshake(socket, transcript, handshake(8, encryptedExtensions)); - co_await writeHandshake(socket, transcript, identity->certificateMessage); + co_await writeHandshake(socket, transcript, identity.certificateMessage); Bytes input(64, 0x20); append(input, bytes("TLS 1.3, server CertificateVerify")); @@ -369,18 +390,22 @@ class Server : public networking::TCPStdnet { append(input, transcript.digest()); Bytes verify; put(verify, signatureScheme, 2); - vector(verify, sign(identity->key, hash(input)), 2); + vector(verify, sign(identity.key, hash(input)), 2); co_await writeHandshake(socket, transcript, handshake(15, verify)); const Secret<> serverFinished{expandLabel(server, "finished")}; co_await writeHandshake(socket, transcript, handshake(20, hmac(serverFinished, {transcript.digest()}))); const Secret<> masterSalt{expandLabel(secret, "derived", empty)}; const Secret<> master{hmac(masterSalt, {zeros})}; - const auto afterFinished = transcript.digest(); - state.readSecret = {expandLabel(master, "c ap traffic", afterFinished)}; - state.writeSecret = {expandLabel(master, "s ap traffic", afterFinished)}; + afterFinished = transcript.digest(); + state.readSecret = {expandLabel(master, "c ap traffic", afterFinished)}; + state.writeSecret = {expandLabel(master, "s ap traffic", afterFinished)}; state.write.install(state.writeSecret); + } + static Task receiveFinished(Socket& socket, const detail::Secret<>& client, const detail::Digest& afterFinished) { + using namespace detail; + auto& state = *socket.connection; const auto finished = co_await readHandshake(socket, 36, true); Reader reader{finished}; if (reader.number(1) != 20) From 9294355fb5015fb205b1ebc50868b03aae4bba18 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:04:05 +0100 Subject: [PATCH 15/24] Follow RFC 8446 on key_share, plaintext record version, KeyUpdate and rejected early data (#631) A ClientHello without key_share is refused with missing_extension. The legacy_record_version of plaintext records is ignored. An alert cannot interrupt a fragmented KeyUpdate. The rejected early data window closes at the first plaintext handshake record. TLS.md names the compilers of the constant-time test. --- docs/TLS.md | 2 +- include/webfront/tls/Server.hpp | 6 ++++-- include/webfront/tls/detail/Protocol.hpp | 9 +++++++-- 3 files changed, 12 insertions(+), 5 deletions(-) diff --git a/docs/TLS.md b/docs/TLS.md index 420d24da..0e4c0de3 100644 --- a/docs/TLS.md +++ b/docs/TLS.md @@ -97,7 +97,7 @@ this contract when using `tls::WebFront`. ## Constant-time regression -On Linux with Valgrind and its development headers installed, the optional +On Linux with GCC or Clang, Valgrind and its development headers installed, the optional `TLSConstantTime` CTest case marks the private inputs to `p256Base` and `x25519` undefined and checks compiler-generated branches and addresses with Memcheck. The probe passed locally on x86-64 with GCC 16.1 and Clang 21 at `-Os` and `-O3`. diff --git a/include/webfront/tls/Server.hpp b/include/webfront/tls/Server.hpp index b629d31d..f15d55db 100644 --- a/include/webfront/tls/Server.hpp +++ b/include/webfront/tls/Server.hpp @@ -205,7 +205,7 @@ class Server : public networking::TCPStdnet { for (;;) { std::array header; co_await readExact(socket, header); - const auto [type, size] = parseRecord(header, encrypted || state.earlyBytes != 0, initial); + const auto [type, size] = parseRecord(header, encrypted || state.earlyBytes != 0); if (size > state.input.capacity()) state.input.reserve(size); state.input.resize(size); @@ -233,8 +233,10 @@ class Server : public networking::TCPStdnet { continue; } } - if (!encrypted && (type == handshakeRecord || type == alert)) + if (!encrypted && (type == handshakeRecord || type == alert)) { + state.earlyBytes = 0; // rejected early data can only precede a ClientHello co_return type; + } throw Error("unexpected record type", 10); } } diff --git a/include/webfront/tls/detail/Protocol.hpp b/include/webfront/tls/detail/Protocol.hpp index bc4b471f..5fd363a1 100644 --- a/include/webfront/tls/detail/Protocol.hpp +++ b/include/webfront/tls/detail/Protocol.hpp @@ -125,6 +125,8 @@ inline ClientHello parseHello(View message, bool retry) { throw Error("TLS 1.3 required", 70); if (!containsExtension(13)) throw Error("missing signature_algorithms", 109); + if (!containsExtension(51)) + throw Error("missing key_share", 109); if (!offeredSuite || !signature || !supportedGroup) throw Error("no common cipher suite, signature or group", 40); const bool hasPsk = containsExtension(41); @@ -178,13 +180,14 @@ struct RecordHeader { unsigned size; }; -inline RecordHeader parseRecord(View header, bool encrypted, bool initial = false) { +inline RecordHeader parseRecord(View header, bool encrypted) { Reader input{header}; const auto type = static_cast(input.number(1)); const auto recordVersion = input.number(2); const auto size = input.number(2); input.end(); - if (recordVersion != 0x0303 && !(initial && recordVersion == 0x0301 && type == handshakeRecord)) + // TLSPlaintext's legacy_record_version is ignored (RFC 8446, section 5.1); only protected records carry the fixed value. + if (type == applicationData && recordVersion != 0x0303) throw Error("invalid record version", 70); if (size > (encrypted && type == applicationData ? maxCiphertext : maxPlaintext)) throw Error("oversized record", 22); @@ -282,6 +285,8 @@ struct RecordControl { if (type == alert && input.size() == 2) { // TLS 1.3 uses the description; user_canceled (90) can precede close_notify. if (input[1] == 90) { + if (updateSize != 0) + throw Error("alert interrupted a KeyUpdate", 10); if (++skipped > 32) throw Error("too many consecutive control or empty records", 10); return false; From eeced78a9a5f3b8645ef7f794829753b4350074a Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:22:42 +0100 Subject: [PATCH 16/24] Bound the WSS close drain and drop the stdexec-only handshake race (#631) The handshake deadline is enforced by http::Server with a stop source and a timer task instead of exec::when_any, so the provider no longer needs the NVIDIA headers when the standard library supplies senders. A peer's Close reply that waits behind a blocked write is cancelled after ten seconds. --- include/webfront/http/HTTPServer.hpp | 26 +++++++++++++++++++++++++- include/webfront/http/WebSocket.hpp | 13 +++++++++++++ include/webfront/tls/Server.hpp | 12 +++++------- 3 files changed, 43 insertions(+), 8 deletions(-) diff --git a/include/webfront/http/HTTPServer.hpp b/include/webfront/http/HTTPServer.hpp index c36c90af..4eb8916b 100644 --- a/include/webfront/http/HTTPServer.hpp +++ b/include/webfront/http/HTTPServer.hpp @@ -1016,6 +1016,15 @@ class Server { } } + // Cancels a handshake that outlives Net::handshakeTimeout, unless `settled` ends the wait first. + networking::Task handshakeDeadline(std::shared_ptr expired, + std::shared_ptr settled) { + if constexpr (networking::secureTransport) + co_await networking::ex::write_env(Net::ResumeAfter(acceptor, Net::handshakeTimeout), + networking::ex::prop{networking::ex::get_stop_token, settled->get_token()}); + expired->request_stop(); + } + networking::Task closeResponse(typename Net::Socket& socket) { if constexpr (networking::secureTransport) co_await Net::Close(socket); @@ -1213,8 +1222,23 @@ class Server { networking::Task serve(typename Net::Socket socket) { if constexpr (networking::secureTransport) { + // The deadline and the server's shutdown cancel the handshake through this source. + struct Forward { + networking::ex::inplace_stop_source& source; + void operator()() noexcept { source.request_stop(); } + }; + const auto expired = std::make_shared(); + const auto settled = std::make_shared(); + networking::ex::stop_callback_for_t shutdown(tasks.stopToken(), Forward{*expired}); + spawn(handshakeDeadline(expired, settled)); + struct Settle { + networking::ex::inplace_stop_source& source; + ~Settle() { source.request_stop(); } + } settle{*settled}; try { - co_await Net::Handshake(socket, acceptor); + co_await networking::ex::stopped_as_error( + networking::ex::write_env(Net::Handshake(socket, acceptor), networking::ex::prop{networking::ex::get_stop_token, expired->get_token()}), + std::make_error_code(std::errc::timed_out)); } catch (const std::system_error& error) { log::debug("TLS handshake failed ({}:{}): {}", error.code().category().name(), error.code().value(), error.what()); co_return; diff --git a/include/webfront/http/WebSocket.hpp b/include/webfront/http/WebSocket.hpp index 5d927a1f..fb33a0ea 100644 --- a/include/webfront/http/WebSocket.hpp +++ b/include/webfront/http/WebSocket.hpp @@ -543,6 +543,18 @@ class WebSocket : public std::enable_shared_from_this> { } if (writerNeeded) spawn(writeFrames(this->shared_from_this())); + // The reply waits behind any write in flight, and stop() no longer reaches it (the closure is claimed): + // bound that wait, so that a blocked write cannot keep the connection alive for ever. + if constexpr (requires { Net::ResumeAfter(socket, std::chrono::seconds{10}); }) + spawn(closeDeadline(this->shared_from_this())); + } + + networking::Task closeDeadline(std::shared_ptr) { + if constexpr (requires { Net::ResumeAfter(socket, std::chrono::seconds{10}); }) { + co_await Net::ResumeAfter(socket, std::chrono::seconds{10}); + stopSource->request_stop(); + } + co_return; } // Control frames (close, ping, pong) carry at most 125 bytes (RFC 6455, 5.5), whatever maxMessageSize. @@ -636,6 +648,7 @@ class WebSocket : public std::enable_shared_from_this> { nextFrame(true); if (writtenHandler) writtenHandler(); co_await Net::Close(socket); + stopSource->request_stop(); // the reply is out: ends closeDeadline() co_return; } } diff --git a/include/webfront/tls/Server.hpp b/include/webfront/tls/Server.hpp index f15d55db..97edc019 100644 --- a/include/webfront/tls/Server.hpp +++ b/include/webfront/tls/Server.hpp @@ -3,7 +3,6 @@ #include "../networking/TCPNetworkingStdnet.hpp" #include "Credentials.hpp" #include "detail/Protocol.hpp" -#include #include namespace webfront::tls { @@ -56,9 +55,11 @@ class Server : public networking::TCPStdnet { }); } - // Both senders complete on the I/O context. The winner cancels and joins the other. + /// The time a connection has to complete its handshake. The caller enforces it (http::Server does). + static constexpr std::chrono::seconds handshakeTimeout{10}; + + // Completes on the I/O context. Its stop token cancels the pending reads and writes. static Task Handshake(Socket& socket, const Acceptor& acceptor) { - using namespace std::chrono_literals; constexpr std::size_t maxPendingHandshakes = 16; if (acceptor.pendingHandshakes >= maxPendingHandshakes) throw std::system_error(std::make_error_code(std::errc::resource_unavailable_try_again), "TLS handshake limit reached"); @@ -67,10 +68,7 @@ class Server : public networking::TCPStdnet { std::size_t& pending; ~Slot() { --pending; } } slot{acceptor.pendingHandshakes}; - auto deadline = networking::ex::then(TCP::ResumeAfter(socket, 10s), [] { - throw std::system_error(std::make_error_code(std::errc::timed_out)); - }); - co_await exec::when_any(runHandshake(socket, acceptor), std::move(deadline)); + co_await runHandshake(socket, acceptor); } static Result Receive(Socket& socket, MutableBuffer target) { From 66bf5b7279cf320da1ea5f29a2de0a3f2c9b26b8 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 18:46:20 +0100 Subject: [PATCH 17/24] Silence MSVC C4737 for the TLS handshake coroutines (#631) Splitting the coroutine did not remove the diagnostic. It only reports a missed tail call, so it is disabled for the project and, by pragma, for consumers of the header. --- cmake/CompilerWarnings.cmake | 1 + include/webfront/tls/Server.hpp | 11 +++++++++++ 2 files changed, 12 insertions(+) diff --git a/cmake/CompilerWarnings.cmake b/cmake/CompilerWarnings.cmake index dee493ad..b7b86734 100644 --- a/cmake/CompilerWarnings.cmake +++ b/cmake/CompilerWarnings.cmake @@ -31,6 +31,7 @@ function(set_project_warnings project_name) /w14906 # string literal cast to 'LPWSTR' /w14928 # illegal copy-initialization; more than one user-defined conversion has been implicitly applied /wd4714 # '__forceinline' function not inlined: stdexec's coroutine helpers, which are not ours to change + /wd4737 # 'Unable to perform required tail call': MSVC cannot chain the long awaits of the TLS handshake coroutines; a performance note only /analyze # Enable Code Analysis /analyze:external- # Disable Code Analysis for external headers /analyze:stacksize65536 # Raise C6262 stack warning threshold to 64KB (policy buffers can reach 32KB); one argument, as sccache reads a separate "65536" as a second source file and refuses to cache the compilation diff --git a/include/webfront/tls/Server.hpp b/include/webfront/tls/Server.hpp index 97edc019..6caf48c6 100644 --- a/include/webfront/tls/Server.hpp +++ b/include/webfront/tls/Server.hpp @@ -5,6 +5,13 @@ #include "detail/Protocol.hpp" #include +#ifdef _MSC_VER +// C4737: MSVC cannot always turn the awaits of the handshake coroutines into tail calls. It costs stack depth, not correctness, +// and /WX would otherwise break every consumer of this header. +#pragma warning(push) +#pragma warning(disable : 4737) +#endif + namespace webfront::tls { /// TCP-style stream provider. Handshake, reads and writes run on the same server I/O context. class Server : public networking::TCPStdnet { @@ -422,3 +429,7 @@ class Server : public networking::TCPStdnet { } }; } // namespace webfront::tls + +#ifdef _MSC_VER +#pragma warning(pop) +#endif From e61bcb067e628fd407438117ccb0449591a8eecd Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:42:23 +0100 Subject: [PATCH 18/24] Build the TLS handshake stages unoptimized on MSVC (#631) C4737 is an optimizer error that the warning options cannot silence. The handshake stages run once per connection, so they lose nothing that matters; Receive and Send stay optimized. Plain helpers build the EncryptedExtensions and CertificateVerify messages. --- include/webfront/tls/Server.hpp | 58 +++++++++++++++++++++------------ 1 file changed, 38 insertions(+), 20 deletions(-) diff --git a/include/webfront/tls/Server.hpp b/include/webfront/tls/Server.hpp index 6caf48c6..885f4743 100644 --- a/include/webfront/tls/Server.hpp +++ b/include/webfront/tls/Server.hpp @@ -312,6 +312,11 @@ class Server : public networking::TCPStdnet { } } +#ifdef _MSC_VER +// MSVC reports C4737 as an error from its optimizer. The handshake stages run once per connection: build them unoptimized, +// and keep the data path (Receive, Send) optimized. +#pragma optimize("", off) +#endif // MSVC refuses (C4737) one coroutine holding the whole flight, so the handshake runs in three stages. static Task negotiate(Socket& socket, std::shared_ptr identity) { using namespace detail; @@ -363,21 +368,9 @@ class Server : public networking::TCPStdnet { co_await writeRecord(socket, changeCipherSpec, ccs); } - // EncryptedExtensions to server Finished, then the application keys. - static Task sendFlight(Socket& socket, detail::Sha256& transcript, const detail::Identity& identity, bool alpn, const detail::Secret<>& shared, - detail::Secret<>& client, detail::Digest& afterFinished) { + // Plain functions: fewer locals live across the awaits of sendFlight, which MSVC compiles with a missed tail call. + static detail::Bytes encryptedExtensionsMessage(bool alpn) { using namespace detail; - auto& state = *socket.connection; - const auto empty = hash(); - const Secret<> early{hmac(zeros, {zeros})}; - const Secret<> derived{expandLabel(early, "derived", empty)}; - const Secret<> secret{hmac(derived, {shared})}; - const auto afterHello = transcript.digest(); - client = {expandLabel(secret, "c hs traffic", afterHello)}; - const Secret<> server{expandLabel(secret, "s hs traffic", afterHello)}; - state.read.install(client); - state.write.install(server); - state.writeEncrypted = true; Bytes extensions; if (alpn) { Bytes protocol; @@ -386,19 +379,41 @@ class Server : public networking::TCPStdnet { vector(protocols, protocol, 2); extension(extensions, 16, protocols); } - Bytes encryptedExtensions; - vector(encryptedExtensions, extensions, 2); - co_await writeHandshake(socket, transcript, handshake(8, encryptedExtensions)); - co_await writeHandshake(socket, transcript, identity.certificateMessage); + Bytes body; + vector(body, extensions, 2); + return handshake(8, body); + } + static detail::Bytes certificateVerifyMessage(const detail::Identity& identity, const detail::Digest& transcriptHash) { + using namespace detail; Bytes input(64, 0x20); append(input, bytes("TLS 1.3, server CertificateVerify")); input.push_back(0); - append(input, transcript.digest()); + append(input, transcriptHash); Bytes verify; put(verify, signatureScheme, 2); vector(verify, sign(identity.key, hash(input)), 2); - co_await writeHandshake(socket, transcript, handshake(15, verify)); + return handshake(15, verify); + } + + // EncryptedExtensions to server Finished, then the application keys. + static Task sendFlight(Socket& socket, detail::Sha256& transcript, const detail::Identity& identity, bool alpn, const detail::Secret<>& shared, + detail::Secret<>& client, detail::Digest& afterFinished) { + using namespace detail; + auto& state = *socket.connection; + const auto empty = hash(); + const Secret<> early{hmac(zeros, {zeros})}; + const Secret<> derived{expandLabel(early, "derived", empty)}; + const Secret<> secret{hmac(derived, {shared})}; + const auto afterHello = transcript.digest(); + client = {expandLabel(secret, "c hs traffic", afterHello)}; + const Secret<> server{expandLabel(secret, "s hs traffic", afterHello)}; + state.read.install(client); + state.write.install(server); + state.writeEncrypted = true; + co_await writeHandshake(socket, transcript, encryptedExtensionsMessage(alpn)); + co_await writeHandshake(socket, transcript, identity.certificateMessage); + co_await writeHandshake(socket, transcript, certificateVerifyMessage(identity, transcript.digest())); const Secret<> serverFinished{expandLabel(server, "finished")}; co_await writeHandshake(socket, transcript, handshake(20, hmac(serverFinished, {transcript.digest()}))); @@ -427,6 +442,9 @@ class Server : public networking::TCPStdnet { state.input.clear(); state.established = true; } +#ifdef _MSC_VER +#pragma optimize("", on) +#endif }; } // namespace webfront::tls From 3d318640c750829bec1f64b35e6f05812d67103d Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:46:09 +0100 Subject: [PATCH 19/24] Keep the server Finished expression out of the co_await (#631) The braced HMAC chunk list inside the co_await expression of sendFlight is the construct MSVC reports as C4737. --- include/webfront/tls/Server.hpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/include/webfront/tls/Server.hpp b/include/webfront/tls/Server.hpp index 885f4743..c1c7934b 100644 --- a/include/webfront/tls/Server.hpp +++ b/include/webfront/tls/Server.hpp @@ -396,6 +396,11 @@ class Server : public networking::TCPStdnet { return handshake(15, verify); } + // A braced list inside a co_await expression is the construct MSVC cannot compile here (C4737): keep it out of the coroutine. + static detail::Bytes finishedMessage(const detail::Secret<>& finishedKey, const detail::Digest& transcriptHash) { + return detail::handshake(20, detail::hmac(finishedKey, {transcriptHash})); + } + // EncryptedExtensions to server Finished, then the application keys. static Task sendFlight(Socket& socket, detail::Sha256& transcript, const detail::Identity& identity, bool alpn, const detail::Secret<>& shared, detail::Secret<>& client, detail::Digest& afterFinished) { @@ -415,7 +420,7 @@ class Server : public networking::TCPStdnet { co_await writeHandshake(socket, transcript, identity.certificateMessage); co_await writeHandshake(socket, transcript, certificateVerifyMessage(identity, transcript.digest())); const Secret<> serverFinished{expandLabel(server, "finished")}; - co_await writeHandshake(socket, transcript, handshake(20, hmac(serverFinished, {transcript.digest()}))); + co_await writeHandshake(socket, transcript, finishedMessage(serverFinished, transcript.digest())); const Secret<> masterSalt{expandLabel(secret, "derived", empty)}; const Secret<> master{hmac(masterSalt, {zeros})}; From fe5e4979ca7bebd8e269dfa03171117f2e893e9d Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 19:50:43 +0100 Subject: [PATCH 20/24] Reject a concurrent TLS Send in release builds and keep the Poly1305 test constant static (#631) --- include/webfront/tls/Server.hpp | 3 ++- test/unit/TlsTests.cpp | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/include/webfront/tls/Server.hpp b/include/webfront/tls/Server.hpp index c1c7934b..0ca9e0fe 100644 --- a/include/webfront/tls/Server.hpp +++ b/include/webfront/tls/Server.hpp @@ -119,7 +119,8 @@ class Server : public networking::TCPStdnet { auto& state = *socket.connection; if (state.control.closed) throw std::system_error(std::make_error_code(std::errc::connection_reset)); - assert(!state.control.sending); + if (state.control.sending) + throw std::logic_error("TLS: concurrent Send on one socket"); state.control.sending = true; struct Sending { bool& active; diff --git a/test/unit/TlsTests.cpp b/test/unit/TlsTests.cpp index dbd19c30..b0d11d54 100644 --- a/test/unit/TlsTests.cpp +++ b/test/unit/TlsTests.cpp @@ -292,7 +292,7 @@ const Scenario tlsRecordControl("TLS application records coordinate updates and }); const Scenario tlsPolyBoundary("Poly1305 reduction handles a carry around bit 130", [] { - constexpr auto max = tls::polyMask; + static constexpr auto max = tls::polyMask; then("the modulus is reduced to zero and its predecessor stays canonical", [&] { tls::PolyLimbs predecessor{max - 5, max, max, max, max}; const auto unchanged = predecessor; From 88a26e73049f603ba29d4651c6128f585060e1ad Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 20:43:12 +0100 Subject: [PATCH 21/24] Bound the wait of a write blocked when a TLS peer sends close_notify (#631) --- include/webfront/http/WebSocket.hpp | 16 ++++++++--- test/unit/WebLinkTests.cpp | 42 +++++++++++++++++++++++++++++ 2 files changed, 54 insertions(+), 4 deletions(-) diff --git a/include/webfront/http/WebSocket.hpp b/include/webfront/http/WebSocket.hpp index fb33a0ea..1667dd12 100644 --- a/include/webfront/http/WebSocket.hpp +++ b/include/webfront/http/WebSocket.hpp @@ -459,8 +459,12 @@ class WebSocket : public std::enable_shared_from_this> { if (received == 0) { if constexpr (networking::secureTransport) { // TLS reports an authenticated EOF. Let the current writer flush any pending close_notify. - if (claimClose() && closeHandler) - closeHandler(CloseEvent{}); + if (claimClose()) { + if (closeHandler) + closeHandler(CloseEvent{}); + if (pendingWrites() != 0) + boundCloseWait(); // the writer owns the alert: a peer that stopped reading must not hold it + } co_return; } else { failure = std::make_error_code(std::errc::connection_reset); @@ -543,8 +547,12 @@ class WebSocket : public std::enable_shared_from_this> { } if (writerNeeded) spawn(writeFrames(this->shared_from_this())); - // The reply waits behind any write in flight, and stop() no longer reaches it (the closure is claimed): - // bound that wait, so that a blocked write cannot keep the connection alive for ever. + boundCloseWait(); + } + + // The closure is claimed, so stop() no longer reaches a write in flight, and the TLS alert waits behind it: + // bound that wait, so that a blocked write cannot keep the connection alive for ever. + void boundCloseWait() { if constexpr (requires { Net::ResumeAfter(socket, std::chrono::seconds{10}); }) spawn(closeDeadline(this->shared_from_this())); } diff --git a/test/unit/WebLinkTests.cpp b/test/unit/WebLinkTests.cpp index 6f66c877..da263132 100644 --- a/test/unit/WebLinkTests.cpp +++ b/test/unit/WebLinkTests.cpp @@ -605,3 +605,45 @@ const Scenario securePeerCloseResumesWriters{"A secure peer Close releases write InjectableSocket::deferWrites(false); InjectableSocket::reset(); }}; + +namespace { +struct SecureDeadlineNetwork : SecureCloseTestNetwork { + static inline ManualSender::Completion timer; + static inline unsigned timers = 0; + + static ManualSender ResumeAfter(Socket&, std::chrono::seconds) { + return ManualSender([](ManualSender::Completion completion) { + ++timers; + timer = std::move(completion); + }); + } +}; +} + +const Scenario securePeerEofBoundsBlockedWrite{"A secure peer EOF cannot hold a blocked write for ever", [] { + InjectableSocket::reset(); + SecureDeadlineNetwork::alerts = 0; + SecureDeadlineNetwork::timers = 0; + SecureDeadlineNetwork::timer = {}; + InlineTaskScope scope; + using Link = WebLink; + vector events; + auto link = make_shared(InjectableSocket{}, WebLinkId{55}, [&](WebLinkEvent event) { events.push_back(event.code); }, scope); + InjectableSocket::deferWrites(); + link->sendError(1, "in flight"); + given("a write blocked by backpressure and a peer close_notify", [&] { + require(link->pendingWrites() == 1); + InjectableSocket::fail({}); + require(events == vector{WebLinkEvent::Code::closed}); + then("the wait for the writer is bounded by the close deadline", [&] { + require(SecureDeadlineNetwork::timers == 1); + require(link->pendingWrites() == 1); + require(SecureDeadlineNetwork::alerts == 0); + require(SecureDeadlineNetwork::timer.complete); + SecureDeadlineNetwork::timer.complete({}, 0); + require(link->pendingWrites() == 0); + }); + }); + InjectableSocket::deferWrites(false); + InjectableSocket::reset(); +}}; From 37ec84f536f94c101aeb11f494b7049b9c2afddb Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 22:41:05 +0100 Subject: [PATCH 22/24] Address review of the integrated TLS server (#631) Do not log a shutdown-interrupted TLS handshake as a failure, queue secure WebSocket frames written before start(), restore the ADR-020 transport invariants, backdate the test certificate and document start() support. --- docs/TLS.md | 4 ++++ docs/adr/ADR-020-services-systeme.md | 12 ++++++++---- include/webfront/http/HTTPServer.hpp | 1 + include/webfront/http/WebSocket.hpp | 10 +++++++--- test/unit/WebSocketTests.cpp | 29 ++++++++++++++++++++++++++++ test/web/fixtures/tls/cert.pem | 14 +++++++------- 6 files changed, 56 insertions(+), 14 deletions(-) diff --git a/docs/TLS.md b/docs/TLS.md index 0e4c0de3..518a6842 100644 --- a/docs/TLS.md +++ b/docs/TLS.md @@ -43,6 +43,10 @@ continue with their negotiated keys. Open the deployment URL in the browser. When using `show()` on a local bind, the certificate must cover the configured address used in the window URL. +`start()` (return at once, system browser) needs a frontend that provides +`launchHttps(address, port, page)`; today only `DefaultBrowserFrontend`, the +default, does. With another frontend, `start()` fails to compile; use `show()` +or open the URL yourself. The browser verifies the certificate chain and server name. WebFront applies the usual bridge origin policy. The file-service binding cookie carries `Secure`. File reads for non-associated clients require an explicit `remoteFileTransport` diff --git a/docs/adr/ADR-020-services-systeme.md b/docs/adr/ADR-020-services-systeme.md index 02697712..03eb0dbc 100644 --- a/docs/adr/ADR-020-services-systeme.md +++ b/docs/adr/ADR-020-services-systeme.md @@ -281,15 +281,19 @@ lève). - **Exposition du jeton.** Chaque réponse de lecture porte `Cache-Control: no-store` et `Referrer-Policy: no-referrer` ; le jeton n'apparaît dans aucun journal HTTP ni diagnostic (chemin masqué). Le cookie de liaison porte `Secure` lorsque la page est servie en HTTPS. -- **Transport.** Lorsque WebFront termine TLS ([ADR-024](ADR-024-tls-integre.md)), le cookie de liaison - porte `Secure`. Le transport est authentifié côté serveur et l'autorisation de lecture distante reste déclarative. +- **Transport : déclaré, jamais déduit.** Par défaut, WebFront ne fournit pas TLS (ADR-008) et ne peut pas savoir comment + un client l'atteint : un mandataire ou un tunnel présente une connexion de boucle locale pour un client distant, et des + en-têtes `Forwarded`/`X-Forwarded-*` peuvent être forgés. WebFront ne lit donc **ni l'adresse ni ces en-têtes** pour + décider. Le fournisseur de TLS intégré ([ADR-024](ADR-024-tls-integre.md)) n'y change rien : il ajoute seulement que + le cookie de liaison porte `Secure` lorsque WebFront termine TLS, sans que le transport devienne local pour autant. Une connexion est de transport local seulement si elle est **associée à la vue d'un frontend intégré** : son secret est remis à la vue par l'adaptateur, dans le processus, sans transiter par une ligne de commande, une URL ou un historique. Aucun secret transmis au navigateur système (fragment de l'URL ouverte) n'atteste le transport : la ligne de commande et l'historique peuvent le divulguer, et un acteur qui le présente le premier depuis un navigateur distant serait accepté ; l'échec ultérieur de l'association légitime ne protège pas cette première connexion. Pour - toute connexion non associée, dont celle du navigateur système, les lectures de fichiers sont refusées par défaut, - quel que soit le fournisseur. Une déclaration explicite de l'application (`remoteFileTransport`) est requise : + toute connexion non associée, dont celles du navigateur système, le transport est inconnu, quelle que soit son + adresse et quel que soit le fournisseur : lectures et écritures de fichiers y sont refusées, sauf déclaration + explicite de l'application sur son déploiement (`remoteFileTransport`) : - `refused` (défaut) ; - `loopbackAttested` : WebFront vérifie que le serveur n'écoute que sur la boucle locale ; l'intégrateur atteste qu'aucun mandataire ni tunnel ne l'expose et que la machine n'est pas partagée avec des utilisateurs non fiables. diff --git a/include/webfront/http/HTTPServer.hpp b/include/webfront/http/HTTPServer.hpp index 4eb8916b..23f3adfe 100644 --- a/include/webfront/http/HTTPServer.hpp +++ b/include/webfront/http/HTTPServer.hpp @@ -1240,6 +1240,7 @@ class Server { networking::ex::write_env(Net::Handshake(socket, acceptor), networking::ex::prop{networking::ex::get_stop_token, expired->get_token()}), std::make_error_code(std::errc::timed_out)); } catch (const std::system_error& error) { + if (tasks.stopRequested()) co_return; // interrupted by the server's shutdown, not a failed or expired handshake log::debug("TLS handshake failed ({}:{}): {}", error.code().category().name(), error.code().value(), error.what()); co_return; } catch (const std::exception& error) { diff --git a/include/webfront/http/WebSocket.hpp b/include/webfront/http/WebSocket.hpp index 1667dd12..ceceb291 100644 --- a/include/webfront/http/WebSocket.hpp +++ b/include/webfront/http/WebSocket.hpp @@ -368,7 +368,7 @@ class WebSocket : public std::enable_shared_from_this> { { std::lock_guard lock(writeMutex); if constexpr (networking::secureTransport) - if (!started) return; + if (closing) return; auto group = latestGroups.find(key); if (group == latestGroups.end()) group = latestGroups.emplace(std::string(key), LatestGroup{}).first; @@ -432,6 +432,7 @@ class WebSocket : public std::enable_shared_from_this> { }; networking::ex::stop_callback_for_t parentStop; std::atomic_bool started; + std::atomic_bool closing{false}; // set once the close is claimed: no frame is queued after it, whether or not start() ran // A message sent in several frames (RFC 6455, 5.4), as browsers do with large messages: its // type and the payloads received so far, at most http::maxMessageSize() bytes // (payloadBudget()). @@ -444,7 +445,10 @@ class WebSocket : public std::enable_shared_from_this> { log::debug("WebSocket constructor"); } - bool claimClose() { return started.exchange(false); } + bool claimClose() { + closing = true; + return started.exchange(false); + } void spawn(networking::Task task) { networking::Spawn(taskScope, Net::Scheduler(socket), stopSource->get_token(), std::move(task)); @@ -636,7 +640,7 @@ class WebSocket : public std::enable_shared_from_this> { { std::lock_guard lock(writeMutex); if constexpr (networking::secureTransport) - if (!started) return false; + if (closing) return false; if (writeQueue.size() >= maxPending) return false; writeQueue.push_back({std::move(frame)}); if (writeQueue.size() > 1) return true; // the running writeFrames() task will get to it diff --git a/test/unit/WebSocketTests.cpp b/test/unit/WebSocketTests.cpp index cd018d14..a7e8ba6f 100644 --- a/test/unit/WebSocketTests.cpp +++ b/test/unit/WebSocketTests.cpp @@ -42,6 +42,35 @@ const Scenario stoppedWebSocket{"A stopped WebSocket does not read again", [] { }); }}; +namespace { +struct SecureTestNetwork : InjectableNetworking { + static constexpr bool secure = true; + + static networking::Task Close(Socket&) { co_return; } +}; +} + +const Scenario secureWriteBeforeStart{"A secure WebSocket queues a frame written before start() and drops one written after stop()", [] { + InjectableSocket::reset(); + webfront::testing::InlineTaskScope scope; + auto ws = websocket::WebSocket::create(InjectableSocket{}, scope); + + given("a frame written before start(), as with the TCP provider", [&] { + ws->write("before start"); + ws->start(); + + then("it reaches the network", [&] { require(InjectableSocket::wrote("before start")); }); + + when("the WebSocket is stopped", [&] { + ws->stop(); + ws->write("after stop"); + + then("a later frame is dropped", [&] { require(!InjectableSocket::wrote("after stop")); }); + }); + }); + InjectableSocket::reset(); +}}; + const Scenario failedWrite{"A failed write closes the WebSocket", [] { InjectableSocket::reset(); int closeHandlerCalls = 0; diff --git a/test/web/fixtures/tls/cert.pem b/test/web/fixtures/tls/cert.pem index d348b94a..e9dfab18 100644 --- a/test/web/fixtures/tls/cert.pem +++ b/test/web/fixtures/tls/cert.pem @@ -1,11 +1,11 @@ -----BEGIN CERTIFICATE----- -MIIBmTCCAT+gAwIBAgIUPkN6UuZYhLvKC9xWwvCpPlplp0kwCgYIKoZIzj0EAwIw -FDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MTEyMTA5NDcxMloXDTQ2MTExNjA5 -NDcxMlowFDESMBAGA1UEAwwJbG9jYWxob3N0MFkwEwYHKoZIzj0CAQYIKoZIzj0D +MIIBmjCCAT+gAwIBAgIULKImGco7ulQQEMx3HNc/0CclTGEwCgYIKoZIzj0EAwIw +FDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MDEwMTAwMDAwMFoXDTQ2MDEwMTAw +MDAwMFowFDESMBAGA1UEAwwJbG9jYWxob3N0MFkwEwYHKoZIzj0CAQYIKoZIzj0D AQcDQgAElFa6/ANSNq7ox/s/b07ONUNHj7nMgkAWwiAmNE2pYjr9/bWPKigrSlpF LM+/IlxW6EkuR2oTB/5NWSMcLpeJJaNvMG0wHQYDVR0OBBYEFGgYWuDY5EjRdPwy -ypettEScSDpFMB8GA1UdIwQYMBaAFGgYWuDY5EjRdPwyypettEScSDpFMA8GA1Ud -EwEB/wQFMAMBAf8wGgYDVR0RBBMwEYIJbG9jYWxob3N0hwR/AAABMAoGCCqGSM49 -BAMCA0gAMEUCIQDeVHey7VGq8znid4nt1gaCKKAGFljB7cPxxOMzcPakaQIgN/RV -boJcR3WlYmgwcB32CIoMfW3y9QwN5QtOygUi4MQ= +ypettEScSDpFMB8GA1UdIwQYMBaAFGgYWuDY5EjRdPwyypettEScSDpFMBoGA1Ud +EQQTMBGCCWxvY2FsaG9zdIcEfwAAATAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49 +BAMCA0kAMEYCIQDumsgsZNhGAN3MAjDkIiQ+7kydrHzLgH1Ug9g2pXhbogIhAKYC +U7Dd24MwsYlYXWHmVn9U2lv9ivaP1zj7c8ziYq8c -----END CERTIFICATE----- From 516e3af56efa6e14864a173bf1d61a4d4744f8b1 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:24:21 +0100 Subject: [PATCH 23/24] Accept TLS 1.3 record padding before bounding the content (#631) Traffic::open compared the decrypted size, which includes the inner type and any padding, with maxPlaintext + 1 before stripping the padding, so a conforming peer sending a full record with padding got record_overflow. The ciphertext bound is already checked by parseRecord (RFC 8446, section 5.4): strip the padding, then bound the content to 16384 bytes. --- include/webfront/tls/detail/Protocol.hpp | 6 ++++-- test/unit/TlsTests.cpp | 26 ++++++++++++++---------- 2 files changed, 19 insertions(+), 13 deletions(-) diff --git a/include/webfront/tls/detail/Protocol.hpp b/include/webfront/tls/detail/Protocol.hpp index 5fd363a1..1a7b4c95 100644 --- a/include/webfront/tls/detail/Protocol.hpp +++ b/include/webfront/tls/detail/Protocol.hpp @@ -239,8 +239,6 @@ struct Traffic { if (!equalSecret(expectedTag, View(payload).subspan(size))) throw Error("invalid authentication tag", 20); ++sequence; - if (size > maxPlaintext + 1) - throw Error("oversized inner plaintext", 22); chachaXor(key, nonce, ciphertext); payload.resize(size); while (!payload.empty() && payload.back() == 0) @@ -249,6 +247,10 @@ struct Traffic { throw Error("missing inner record type", 10); const auto type = payload.back(); payload.pop_back(); + // RFC 8446, section 5.4: padding follows the type, so the content limit applies once it is removed. The ciphertext + // bound (maxCiphertext) was checked by parseRecord. + if (payload.size() > maxPlaintext) + throw Error("oversized inner plaintext", 22); return type; } diff --git a/test/unit/TlsTests.cpp b/test/unit/TlsTests.cpp index b0d11d54..334ab113 100644 --- a/test/unit/TlsTests.cpp +++ b/test/unit/TlsTests.cpp @@ -169,26 +169,30 @@ const Scenario tlsRefusals("TLS rejects invalid framing and negotiation", {"fast payload.back() ^= 1; require(receiver.open(View(record).first(5), payload) == tls::applicationData); }); - then("the authenticated size limit includes the type and padding", [] { + then("padding after the inner type is accepted, and the content limit applies once it is removed", [] { const auto key = tls::expandLabel(tls::zeros, "key"); tls::Nonce nonce; std::ranges::copy_n(tls::expandLabel(tls::zeros, "iv", {}, 12).begin(), nonce.size(), nonce.begin()); - for (const bool padded : {false, true}) { - Bytes payload(tls::maxPlaintext + 1 + padded, 0); - payload[tls::maxPlaintext] = tls::applicationData; + const auto open = [&](std::size_t content, std::size_t padding, Bytes& payload) { + payload.assign(content + 1 + padding, 0); + payload[content] = tls::applicationData; Bytes header{tls::applicationData, 3, 3}; tls::put(header, payload.size() + 16, 2); tls::chachaXor(key, nonce, payload); tls::append(payload, tls::polyTag(key, nonce, header, payload)); tls::Traffic receiver; receiver.install(tls::zeros); - if (padded) - requireThrows([&] { receiver.open(header, payload); }, contains("oversized inner plaintext")); - else { - require(receiver.open(header, payload) == tls::applicationData); - require(payload.size() == tls::maxPlaintext); - } - } + return receiver.open(header, payload); + }; + Bytes payload; + require(open(tls::maxPlaintext, 0, payload) == tls::applicationData); + require(payload.size() == tls::maxPlaintext); + require(open(tls::maxPlaintext, 1, payload) == tls::applicationData); // a full record with one byte of padding + require(payload.size() == tls::maxPlaintext); + require(open(10, 200, payload) == tls::applicationData); + require(payload.size() == 10); + requireThrows([&] { open(tls::maxPlaintext + 1, 0, payload); }, contains("oversized inner plaintext")); + requireThrows([&] { open(tls::maxPlaintext + 1, 1, payload); }, contains("oversized inner plaintext")); }); then("an exhausted record sequence fails as a transport error before wrapping", [] { require(tls::recordNonce({}, UINT64_MAX - 1).back() == 0xfe); From a2f15ca1b43a2ad5eb01c2ef9c603d9de033d228 Mon Sep 17 00:00:00 2001 From: Ambroise Leclerc <6860842+ambroise-leclerc@users.noreply.github.com> Date: Sat, 21 Nov 2026 23:36:58 +0100 Subject: [PATCH 24/24] Drop every TLS 1.3 compatibility ChangeCipherSpec of the handshake window (#631) The server accepted one change_cipher_spec record and refused the next, but RFC 8446, appendix D.4 lets a client send it at any time between its first ClientHello and its Finished, around a HelloRetryRequest included. Drop each valid record in that window. The interop test relays a client through a repeater that adds several of them after every plaintext record. --- include/webfront/tls/Server.hpp | 8 ++--- test/web/TlsInterop.py | 64 +++++++++++++++++++++++++++++++++ 2 files changed, 68 insertions(+), 4 deletions(-) diff --git a/include/webfront/tls/Server.hpp b/include/webfront/tls/Server.hpp index 0ca9e0fe..1d2a6746 100644 --- a/include/webfront/tls/Server.hpp +++ b/include/webfront/tls/Server.hpp @@ -31,7 +31,6 @@ class Server : public networking::TCPStdnet { std::size_t earlyBytes = 0; std::size_t offset = 0; detail::RecordControl control; - bool compat = false; bool writeEncrypted = false; bool established = false; }; @@ -216,10 +215,11 @@ class Server : public networking::TCPStdnet { state.input.reserve(size); state.input.resize(size); co_await readExact(socket, state.input); - if (type == changeCipherSpec && !state.established && !initial && !state.compat && state.input == Bytes{1}) { - state.compat = true; + // RFC 8446, appendix D.4: a client may send this compatibility record at any time after its first ClientHello and + // before its Finished (around a HelloRetryRequest too), and the server drops each one. The handshake deadline and + // the record limits bound them. + if (type == changeCipherSpec && !state.established && !initial && state.input == Bytes{1}) continue; - } if (type == applicationData) { if (encrypted) { try { diff --git a/test/web/TlsInterop.py b/test/web/TlsInterop.py index f2960b9a..6cf9a56b 100644 --- a/test/web/TlsInterop.py +++ b/test/web/TlsInterop.py @@ -7,10 +7,64 @@ import struct import subprocess import sys +import threading from contextlib import ExitStack from pathlib import Path +COMPATIBILITY_RECORD = bytes.fromhex("140303000101") # change_cipher_spec, RFC 8446 appendix D.4 + + +def read_exactly(source, count): + data = b"" + while len(data) < count: + chunk = source.recv(count - len(data)) + if not chunk: + break + data += chunk + return data + + +def repeat_compatibility_records(port, copies): + """Listen on a port and relay to the server, repeating each plaintext client record's compatibility record. + + A conforming client may send change_cipher_spec at any time between its first ClientHello and its Finished, + around a HelloRetryRequest included. The relay adds `copies` after every plaintext record, until the first + protected record.""" + listener = socket.socket() + listener.bind(("127.0.0.1", 0)) + listener.listen(1) + + def serve(): + with listener, listener.accept()[0] as client, socket.create_connection(("127.0.0.1", port), timeout=10) as server: + def backward(): + try: + while chunk := server.recv(4096): + client.sendall(chunk) + client.shutdown(socket.SHUT_WR) + except OSError: + pass + threading.Thread(target=backward, daemon=True).start() + injecting = True + try: + while header := read_exactly(client, 5): + if len(header) < 5: + break + record = header + read_exactly(client, struct.unpack(">H", header[3:])[0]) + server.sendall(record) + if header[0] == 0x17: + injecting = False + elif injecting: + server.sendall(COMPATIBILITY_RECORD * copies) + server.shutdown(socket.SHUT_WR) + except OSError: + pass + + thread = threading.Thread(target=serve, daemon=True) + thread.start() + return listener.getsockname()[1], thread + + def exercise(server, openssl, certificate): port = int(server.stdout.readline()) request = b"GET / HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n" @@ -23,6 +77,16 @@ def exercise(server, openssl, certificate): if retry.stdout.count(b", ServerHello") != 2 or b"HTTP/1.1 200 OK" not in retry.stdout: raise RuntimeError(f"HelloRetryRequest or HTTP response missing: {retry.stdout!r} {retry.stderr!r}") + relay, relayed = repeat_compatibility_records(port, 3) + repeated = subprocess.run( + [openssl, "s_client", "-connect", f"127.0.0.1:{relay}", "-tls1_3", "-groups", "P-256:X25519", + "-CAfile", str(certificate), "-verify_return_error", "-verify_ip", "127.0.0.1", "-quiet", "-msg"], + input=request, capture_output=True, check=True, timeout=10, + ) + relayed.join(timeout=5) + if repeated.stdout.count(b", ServerHello") != 2 or b"HTTP/1.1 200 OK" not in repeated.stdout: + raise RuntimeError(f"Repeated compatibility records were not dropped: {repeated.stdout!r} {repeated.stderr!r}") + # The server owns the ten-second deadline. The client only bounds the wait for a stuck test. with socket.create_connection(("127.0.0.1", port), timeout=30) as stalled: stalled.sendall(b"\x16\x03")