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/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/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..31120602 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -14,6 +14,8 @@ 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`). - 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..4cc3d516 100644 --- a/docs/PROJECT_STATUS.md +++ b/docs/PROJECT_STATUS.md @@ -159,7 +159,9 @@ 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. 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 new file mode 100644 index 00000000..518a6842 --- /dev/null +++ b/docs/TLS.md @@ -0,0 +1,129 @@ +# 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. + +> 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 + +int main() { + auto credentials = std::make_shared( + "/path/to/fullchain.pem", "/path/to/privkey.pem"); + 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"); }); + 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 +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. 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. +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. +`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` +declaration, typically `httpsByDeployment`. The default `refused` applies to +TLS listeners as well. Client authentication and authorization belong to the +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. 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. + +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). + +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. 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. + +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. 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. + +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 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`. +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 +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.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.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/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..03eb0dbc 100644 --- a/docs/adr/ADR-020-services-systeme.md +++ b/docs/adr/ADR-020-services-systeme.md @@ -281,23 +281,25 @@ 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 : 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 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`) : + 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. 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 @@ -506,9 +508,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 :** WebFront ne chiffre pas et 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 new file mode 100644 index 00000000..e6fc5a2d --- /dev/null +++ b/docs/adr/ADR-024-tls-integre.md @@ -0,0 +1,35 @@ +# ADR-024 — TLS intégré + +## 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. 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é. +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 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/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..600873f4 100644 --- a/include/webfront/ReadBinding.hpp +++ b/include/webfront/ReadBinding.hpp @@ -23,6 +23,7 @@ #include #include #include +#include #include #include #include @@ -206,8 +207,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)) {} + + 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) + "-") {} /// 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`. @@ -486,13 +496,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)); @@ -537,7 +547,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..15dc2a26 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,12 @@ 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); + 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 or cause denial of service. See docs/TLS.md.\n"; + return std::make_shared(ReadBinding::Options{.remote = config.remoteFileTransport, .secure = secure}); } } // namespace detail @@ -705,7 +710,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()), @@ -1137,8 +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); }) - Frontend::open(httpAddress, httpPort, htmlFilename, contentPolicy, windowOptions, ViewLaunch{viewSecret, detail::browserOrigin(httpAddress, httpPort)}); + 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 (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); }) @@ -1216,19 +1226,28 @@ 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 (requires { Frontend::launch(httpAddress, httpPort, page, contentPolicy); }) + if constexpr (secure) + 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..23f3adfe 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,33 @@ 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"); + } + } + + // 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); + else + socket.shutdown(Net::Socket::shutdown_both); + co_return; + } + std::string bind(std::string_view address, std::string_view requestedPort) { try { const auto endpoint = Net::Resolve(address, requestedPort); @@ -1143,7 +1173,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); @@ -1187,10 +1217,37 @@ 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) { + // 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 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) { + 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) { + log::warn("TLS handshake failed: {}", error.what()); + co_return; + } + } Request request; std::optional::Lease> lease; std::unique_ptr streamed; @@ -1275,7 +1332,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/http/WebSocket.hpp b/include/webfront/http/WebSocket.hpp index cc288abb..ceceb291 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 (closing) return; auto group = latestGroups.find(key); if (group == latestGroups.end()) group = latestGroups.emplace(std::string(key), LatestGroup{}).first; @@ -428,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()). @@ -440,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)); @@ -453,8 +461,19 @@ 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()) { + 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); + break; + } } processFrames(std::span(readBuffer.data(), received)); } @@ -500,9 +519,54 @@ 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())); + 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())); + } + + 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. @@ -575,6 +639,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 (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 @@ -589,6 +655,15 @@ 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); + if (writtenHandler) writtenHandler(); + co_await Net::Close(socket); + stopSource->request_stop(); // the reply is out: ends closeDeadline() + co_return; + } + } frame = nextFrame(true); if (writtenHandler) writtenHandler(); } diff --git a/include/webfront/networking/BasicNetworking.hpp b/include/webfront/networking/BasicNetworking.hpp index be026995..00950ce3 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 = []() -> bool { + if constexpr (requires { static_cast(Net::secure); }) + return static_cast(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..538685cd --- /dev/null +++ b/include/webfront/tls/Credentials.hpp @@ -0,0 +1,232 @@ +#pragma once +#include "detail/Wire.hpp" + +#include +#include +#include +#include + +namespace webfront::tls { +namespace detail { +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) { + // 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(); +} + +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 + 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(); + 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 keyVersion = key.der(2); + if (pkcs8) { + 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(); + keyVersion = key.der(2); + } + if (keyVersion.size() != 1 || keyVersion.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; + 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)) { + 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()); + erase.active = false; + 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() { + wipe(key.data(), key.size()); + wipe(der.data(), der.size()); + } + } erase{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); + 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; + 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(certificatePublicKey(leaf)), point)) + throw Error("certificate and private key do not match"); + + 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 + 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) { + auto next = detail::loadIdentity(chain, key); + std::scoped_lock lock(mutex); + identity.swap(next); + } + + [[nodiscard]] auto snapshot() const { + std::scoped_lock lock(mutex); + return identity; + } + +private: + 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 new file mode 100644 index 00000000..1d2a6746 --- /dev/null +++ b/include/webfront/tls/Server.hpp @@ -0,0 +1,459 @@ +#pragma once +#include "../networking/Tasks.hpp" +#include "../networking/TCPNetworkingStdnet.hpp" +#include "Credentials.hpp" +#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 { + 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 earlyBytes = 0; + std::size_t offset = 0; + detail::RecordControl control; + bool writeEncrypted = false; + bool established = false; + }; + +public: + static constexpr bool secure = true; + + 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 { + 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 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) { + 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}; + co_await runHandshake(socket, acceptor); + } + + 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 std::size_t{0}; + Byte failure = 0; + try { + 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())); + state.offset += count; + co_return count; + } + const auto type = co_await readRecord(socket, true); + state.offset = state.input.size(); + if (state.control.receive(type, state.input, state.read, state.readSecret)) + state.offset = 0; + } + } catch (const Error& error) { + failure = error.alert; + } 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; + } + 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 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)); + if (state.control.sending) + throw std::logic_error("TLS: concurrent Send on one socket"); + state.control.sending = true; + struct Sending { + bool& active; + ~Sending() { + active = false; + } + } sending{state.control.sending}; + constexpr std::size_t header = 5; + std::size_t length = 0; + 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()}; + 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); + if (record.size() == maxPlaintext + header) { + co_await writeApplication(socket, record); + record.resize(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()) + co_await finishClose(socket); + } + +private: + static Task runHandshake(Socket& socket, const Acceptor& acceptor) { + std::optional failure; + try { + socket.connection = std::make_unique(); + co_await negotiate(socket, acceptor.credentials->snapshot()); + co_return; + } catch (const detail::Error& error) { + failure.emplace(error); + } + try { + 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), failure->what()); + } + + 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, 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) { + 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 || state.earlyBytes != 0); + if (size > state.input.capacity()) + state.input.reserve(size); + state.input.resize(size); + co_await readExact(socket, state.input); + // 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 { + 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)) { + state.earlyBytes = 0; // rejected early data can only precede a ClientHello + 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.control.closed) + throw std::system_error(std::make_error_code(std::errc::connection_reset)); + 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")}; + state.write.install(state.writeSecret); + if (state.control.closed) + co_return; + } + 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()); + } + } + +#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; + 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(); + 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); + state.earlyBytes = 0; + 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{}; + entropy(random); + entropy(scalar); + 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()) + co_await writeRecord(socket, changeCipherSpec, ccs); + } + + // 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; + Bytes extensions; + if (alpn) { + Bytes protocol; + vector(protocol, bytes("http/1.1"), 1); + Bytes protocols; + vector(protocols, protocol, 2); + extension(extensions, 16, protocols); + } + 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, transcriptHash); + Bytes verify; + put(verify, signatureScheme, 2); + vector(verify, sign(identity.key, hash(input)), 2); + 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) { + 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, finishedMessage(serverFinished, transcript.digest())); + + const Secret<> masterSalt{expandLabel(secret, "derived", empty)}; + const Secret<> master{hmac(masterSalt, {zeros})}; + 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) + 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 (!equalSecret(expected, verification)) + throw Error("invalid client Finished", 51); + state.read.install(state.readSecret); + state.input.clear(); + state.established = true; + } +#ifdef _MSC_VER +#pragma optimize("", on) +#endif +}; +} // namespace webfront::tls + +#ifdef _MSC_VER +#pragma warning(pop) +#endif 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/ChaChaPoly.hpp b/include/webfront/tls/detail/ChaChaPoly.hpp new file mode 100644 index 00000000..f38eed32 --- /dev/null +++ b/include/webfront/tls/detail/ChaChaPoly.hpp @@ -0,0 +1,161 @@ +#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); + } +} + +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 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, + (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 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; + carryPoly(h); + // The first carry leaves only limb 0 potentially wide. + carryPoly(h); + }; + 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()); + reducePoly(h); + + 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)); + return tag; +} +} // namespace webfront::tls::detail diff --git a/include/webfront/tls/detail/Crypto.hpp b/include/webfront/tls/detail/Crypto.hpp new file mode 100644 index 00000000..40d3157b --- /dev/null +++ b/include/webfront/tls/detail/Crypto.hpp @@ -0,0 +1,215 @@ +#pragma once +#include "../../automation/Platform.hpp" +#include "ChaChaPoly.hpp" +#include "Curves.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace webfront::tls::detail { +using Bytes = std::vector; +using View = std::span; + +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() { + 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]; + 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); + wipe(pad.data(), pad.size()); + 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() { + wipe(this->data(), Size); + } +}; + +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)); + } + } erase{scalar}; + if (!F::validScalar(scalar)) + throw std::invalid_argument("TLS: invalid P-256 scalar"); + 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})}; + for (;;) { + v = {hmac(mac, {v})}; + auto k = decode(v); + Erase eraseNonce{k}; + if (F::validScalar(k)) { + const auto x = F::reduce(p256Base(k)[0]); + 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}; + 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/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..39e555f4 --- /dev/null +++ b/include/webfront/tls/detail/Field.hpp @@ -0,0 +1,193 @@ +#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 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) { + 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]) & mask); + 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/Protocol.hpp b/include/webfront/tls/detail/Protocol.hpp new file mode 100644 index 00000000..1a7b4c95 --- /dev/null +++ b/include/webfront/tls/detail/Protocol.hpp @@ -0,0 +1,340 @@ +#pragma once +#include "Wire.hpp" + +#include +#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; + bool earlyData = 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 supportsTls13 = false, signature = false, supportedGroup = 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 (containsExtension(kind)) + throw Error("duplicate ClientHello extension", 47); + if (extensionCount == seen.size()) + throw Error("too many ClientHello extensions"); + seen[extensionCount++] = kind; + switch (kind) { + case 43: + supportsTls13 = 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: + 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); + 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 == 45 || kind == 16) + extension.end(); + if (kind != 51 && kind != 21 && kind != 41 && kind != 42) + invariant.update(encoded.first(encoded.size() - extensions.remaining.size())); + } + if (!supportsTls13) + 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); + 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; + 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 tls13{3, 4}; + Bytes extensions; + extension(extensions, 43, tls13); + 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) { + 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(); + // 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); + if (size == 0 || (encrypted && type == applicationData && size < 17)) + throw Error("invalid record length", 50); + 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")}; + 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; + const auto nonce = recordNonce(iv, sequence); + ++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); + } + + Byte open(View header, Bytes& payload) { + if (payload.size() < 17) + throw Error("short ciphertext"); + 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); + if (!equalSecret(expectedTag, View(payload).subspan(size))) + throw Error("invalid authentication tag", 20); + ++sequence; + chachaXor(key, nonce, ciphertext); + 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(); + // 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; + } + +private: + Secret<> key{}; + 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(Byte failure = 0) { + if (std::exchange(closed, true)) + return false; + pendingAlert = failure; + return !sending; + } + + void transportLost() { + closed = true; + pendingAlert.reset(); + } + + std::optional takeAlert() { + return std::exchange(pendingAlert, std::nullopt); + } + + // 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 (updateSize != 0) + throw Error("alert interrupted a KeyUpdate", 10); + if (++skipped > 32) + throw Error("too many consecutive control or empty records", 10); + return false; + } + if (input[1] != 0) { + 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; + } + 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::optional pendingAlert; + std::array update{}; + std::size_t updateSize = 0; + unsigned skipped = 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..f7e363fd --- /dev/null +++ b/include/webfront/tls/detail/Wire.hpp @@ -0,0 +1,73 @@ +#pragma once +#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; +}; + +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"); + } + if (size > maxCredentialBytes) + throw Error("oversized DER value"); + 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..4a7b7985 100644 --- a/test/driver/WfDriver.hpp +++ b/test/driver/WfDriver.hpp @@ -69,16 +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& window, 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)); + std::filesystem::path(profile), window, false, launch); #else - frontend::CEFFrontend::open(address, port, page, policy); + frontend::CEFFrontend::open(address, port, page, policy, window, launch); #endif } }; @@ -402,7 +406,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 00000000..0e895361 Binary files /dev/null and b/test/fuzz/corpus/tls/client-hello differ diff --git a/test/fuzz/corpus/tls/record-header b/test/fuzz/corpus/tls/record-header new file mode 100644 index 00000000..324c6cfc Binary files /dev/null and b/test/fuzz/corpus/tls/record-header differ diff --git a/test/unit/CMakeLists.txt b/test/unit/CMakeLists.txt index 85e3e6df..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) @@ -40,6 +54,7 @@ add_test(NAME BddDiscovery COMMAND ${CMAKE_COMMAND} -DPROBE=$ #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/unit/ReadBindingTests.cpp b/test/unit/ReadBindingTests.cpp index 456c0d54..ef48d73d 100644 --- a/test/unit/ReadBindingTests.cpp +++ b/test/unit/ReadBindingTests.cpp @@ -16,6 +16,7 @@ #include #include #include +#include #include #include #include @@ -28,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) { @@ -73,8 +76,8 @@ struct Fixture { std::string lastRest; std::any lastContext; - explicit Fixture(RemoteFileTransport transport = RemoteFileTransport::refused) - : binding(transport, [this] { return time; }) { + explicit Fixture(RemoteFileTransport transport = RemoteFileTransport::refused, bool secure = false) + : 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; @@ -364,6 +367,20 @@ 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 the default still refuses reads", [&] { + require(cookies.front().contains("; Secure")); + 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", [&] { Fixture fixture; fixture.bind(1, false); @@ -785,3 +802,23 @@ 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")); + require(output.str().contains("denial of service")); + }); +}}; 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 new file mode 100644 index 00000000..334ab113 --- /dev/null +++ b/test/unit/TlsTests.cpp @@ -0,0 +1,389 @@ +#include "Bdd.hpp" +#include "TemporaryDirectory.hpp" +#include +#include +#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"); + const auto secret = View(scalar).first<32>(); + auto output = tls::x25519(secret, tls::Digest{9}); + require(std::ranges::equal(output, tlsHex("8520f0098930a754748b7ddcb43ef75a0dbf3a0d26381af4eba4a98eaa9b4e6a"))); + 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(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."); + 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" + "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"); + const auto shared = tls::x25519(View(scalar).first<32>(), parsed.share.first<32>()); + 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("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. + const auto modes = tlsHex("002d00020101"); + 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 = [&] { + 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); + }); + 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); + }); + payload.back() ^= 1; + require(receiver.open(View(record).first(5), payload) == tls::applicationData); + }); + 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()); + 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); + 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); + try { + tls::recordNonce({}, UINT64_MAX); + require(false); + } catch (const std::system_error& error) { + require(error.code() == std::errc::value_too_large); + } + }); +}); +} // 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 after any 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()); + // The active writer consumes the alert once it has finished its record. + require(closing.takeAlert() == 0); + 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([&] { + fatal.receive(tls::alert, tlsHex("0214"), traffic, secret); + }); + require(fatal.closed); + require(!fatal.beginClose()); + require(!fatal.takeAlert()); + }); +}); + +const Scenario tlsPolyBoundary("Poly1305 reduction handles a carry around bit 130", [] { + 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; + 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", [] { + 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(); + 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"; + 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); + }); + 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); + + 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..da263132 100644 --- a/test/unit/WebLinkTests.cpp +++ b/test/unit/WebLinkTests.cpp @@ -557,3 +557,93 @@ 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(); +}}; + +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(); +}}; 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/CMakeLists.txt b/test/web/CMakeLists.txt index 8acf91e4..ec6a45cc 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) +# 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_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 60) + 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") @@ -272,6 +287,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 +534,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..e5339667 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::httpsByDeployment; +#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/TlsInterop.cpp b/test/web/TlsInterop.cpp new file mode 100644 index 00000000..034a4bf2 --- /dev/null +++ b/test/web/TlsInterop.cpp @@ -0,0 +1,36 @@ +#include + +#include +#include +#include + +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&) { + std::cout << "post" << std::endl; + reply.wait(); + return webfront::http::RouteReply{}; + }; + 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::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..6cf9a56b --- /dev/null +++ b/test/web/TlsInterop.py @@ -0,0 +1,189 @@ +"""Exercise the TLS provider against an independent OpenSSL client over loopback.""" +import errno +import re +import select +import socket +import ssl +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" + 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}") + + 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") + 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 + + 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) + + 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: + 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": + 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" + "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: + 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"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": + 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, 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}") diff --git a/test/web/fixtures/tls/README.md b/test/web/fixtures/tls/README.md new file mode 100644 index 00000000..e1ba2126 --- /dev/null +++ b/test/web/fixtures/tls/README.md @@ -0,0 +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/cert.pem b/test/web/fixtures/tls/cert.pem new file mode 100644 index 00000000..e9dfab18 --- /dev/null +++ b/test/web/fixtures/tls/cert.pem @@ -0,0 +1,11 @@ +-----BEGIN CERTIFICATE----- +MIIBmjCCAT+gAwIBAgIULKImGco7ulQQEMx3HNc/0CclTGEwCgYIKoZIzj0EAwIw +FDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MDEwMTAwMDAwMFoXDTQ2MDEwMTAw +MDAwMFowFDESMBAGA1UEAwwJbG9jYWxob3N0MFkwEwYHKoZIzj0CAQYIKoZIzj0D +AQcDQgAElFa6/ANSNq7ox/s/b07ONUNHj7nMgkAWwiAmNE2pYjr9/bWPKigrSlpF +LM+/IlxW6EkuR2oTB/5NWSMcLpeJJaNvMG0wHQYDVR0OBBYEFGgYWuDY5EjRdPwy +ypettEScSDpFMB8GA1UdIwQYMBaAFGgYWuDY5EjRdPwyypettEScSDpFMBoGA1Ud +EQQTMBGCCWxvY2FsaG9zdIcEfwAAATAPBgNVHRMBAf8EBTADAQH/MAoGCCqGSM49 +BAMCA0kAMEYCIQDumsgsZNhGAN3MAjDkIiQ+7kydrHzLgH1Ug9g2pXhbogIhAKYC +U7Dd24MwsYlYXWHmVn9U2lv9ivaP1zj7c8ziYq8c +-----END CERTIFICATE----- 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----- 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 () => {