076-paywall-proxy.rst (20372B)
1 DD 76: Paivana - Fighting AI Bots with GNU Taler 2 ################################################ 3 4 Summary 5 ======= 6 7 This design document describes the architecture of an AI Web firewall using GNU 8 Taler, as well as new features that are required for the implementation. 9 10 Motivation 11 ========== 12 13 AI bots are causing enormous amounts of traffic by scraping sites like git 14 forges. They neither respect robots.txt nor 5xx HTTP responses. Solutions like 15 Anubis and IP-based blocking do not work anymore at this point. 16 17 Requirements 18 ============ 19 20 * Must withstand high traffic from bots, requests before a payment happened 21 must be *very* cheap, both in terms of response generation and database 22 interaction. This includes good support for caching. 23 * Should work not just for our paivana-httpd but also for Turnstile-style 24 paywalls that need to work with purely static paywall pages without 25 PHP sessions. 26 27 28 Proposed Solution 29 ================= 30 31 Architecture 32 ------------ 33 34 * paivana-httpd is a reverse proxy that sits between ingress HTTP(S) traffic 35 and the protected upstream service. 36 * paivana-httpd is configured with a particular merchant backend. 37 * A payment template must be set up in the merchant backend (called ``{template_id}`` 38 from here on). 39 40 Steps: 41 42 * Browser visits ``{website}`` 43 (for example, ``https://git.taler.net``) where 44 ``{domain}`` is the domain name of ``{website}``. 45 * paivana-httpd working as a reverse-proxy for 46 ``{website}``. Whenever called for a non-whitelisted 47 URL, it checks for a the presence of a Paivana cookie valid for 48 this client IP address and ``{website}`` at this time. 49 The *Paivana Cookie* is computed as: 50 51 ``expiration || '-' || crock32(HKDF(salt=expiration, ikm=paivana_server_secret, info=website || '\0' || client_ip))``. 52 53 where ``expiration`` in the prefix is the expiration time for the 54 cookie (and thus the access to the article) in seconds 55 (to keep it short) while in the salt it is the binary GNUnet 56 absolute time (microseconds) in network byte order. 57 Note that this value is the *end of the access being sold*, chosen by 58 the client and capped by the contract; it is not a statement about 59 when anything happened, and in particular it is not the client's idea 60 of the current time. (It was called ``cur_time`` in earlier drafts of 61 this document, which invited exactly that misreading.) 62 ``HKDF`` is GNUnet's HKDF (``GNUNET_CRYPTO_hkdf_gnunet()``, which 63 extracts with HMAC-SHA-512 and expands with HMAC-SHA-256), and the 64 output is 512 bits. 65 Using a keyed PRF instead of a plain hash over the concatenation 66 ensures that the cookie cannot be forged without the server secret 67 and that the inputs are unambiguously separated: ``website`` is 68 terminated by a zero byte before ``client_ip`` is appended, so 69 different ``(website, client_ip)`` pairs can never yield the same 70 ``info`` string. 71 ``crock32`` is GNUnet's Crockford-inspired base32 encoding. 72 73 The cookie is computed and verified exclusively by paivana-httpd; 74 the browser only stores and returns it and thus never has to 75 reconstruct this value. 76 77 * If such a cookie is set and valid, the request is 78 reverse-proxied to upstream. *Stop.* 79 * Otherwise, an HTTP 303 See Other to 80 ``/.well-known/paivana/templates/$ID#$WEBSITE`` 81 is returned. Here, ``$ID`` is the template ID and 82 ``$WEBSITE`` is base64url-encoding of the full URL of 83 the website currently being visited. This way, 84 the template page can be fully static and cached, and the 85 JavaScript logic on that page can learn which website 86 to pay for (and after payment redirect the browser there). 87 88 * When the browser requests ``/.well-known/paivana/templates/$ID`` 89 a static **cachable** paywall page is returned, 90 including a machine-readable ``Paivana`` HTTP header with 91 the ``taler://pay-template/`` URL minus the client-computed 92 ``{paivana_id}`` and fullfillment URL (see below). 93 94 * The browser (rendering the paywall page) generates a random 95 *paivana ID* via JS using the end of the access it intends to buy 96 (``expiration``) in seconds since the Epoch and the current URL 97 (``{website}``) plus some freshly generated entropy (``{nonce}``): 98 99 ``paivana_id := expiration || '-' || b64url(SHA256(nonce || website || '\0' || expiration))``. 100 101 The exact byte string that is hashed is the concatenation of: 102 103 * the 16-byte (128-bit) binary ``nonce``; 104 * the UTF-8 encoding of ``website``, including its terminating 105 zero byte (which separates it unambiguously from the timestamp); 106 * ``expiration`` as an 8-byte **big-endian (network byte order) 107 number of microseconds** since the Epoch, that is, the value of 108 the seconds-based ``expiration`` multiplied by 1000000. 109 110 Note that ``expiration`` thus appears twice in two different 111 encodings: the ``paivana_id`` *prefix* is the timestamp in 112 **seconds** (as decimal ASCII, to keep the identifier short), 113 while the hashed value is the same instant in **microseconds** 114 in network byte order. 115 116 The client is free to pick this value — it is asking for access until 117 a particular moment, and it is the contract's ``max_pickup_time`` that 118 decides whether it may have it. Since the same value goes into the 119 session ID the order is created under, it cannot be revised after the 120 fact. 121 122 Here ``b64url`` is the RFC 7515 base64 URL encoder without 123 padding, used to keep the result short (same reason for the use of 124 SHA-256). 125 The same computation could also easily be done by a non-JS client 126 that processes the ``Paivana`` HTTP header (or a GNU Taler wallet 127 running as a Web extension). 128 129 * Based on this paivana ID, a 130 ``taler://pay-template/{merchant_backend}/{template_id}?session_id={paivana_id}&fulfillment_url={website}`` 131 URI is generated and rendered as a QR code and link, prompting 132 the user to pay for access to the ``{website}`` using GNU Taler. 133 134 * The JavaScript in the paywall page running in the browser 135 (or the non-JS client) long-polls 136 on a new ``https://{merchant_backend}/sessions/{paivana_id}`` 137 endpoint that returns when an order with the given session ID has been paid 138 for (regardless of the order ID, which is not known to the browser). 139 * A wallet now needs to instantiate the pay template, passing the 140 ``session_id`` and the ``fulfillment_url`` as an additional inputs 141 to the order creation (the session ID here will work just like 142 existing use of ``session_ids`` in session-bound payments). 143 Similarly, the ``{website}`` works as the fulfillment URL as usual. 144 * The wallet then must pay for the resulting order 145 by talking to the Merchant backend. 146 * When the long-poller returns and the payment has succeeded, the 147 browser (still rendering the paywall page) also learns the order ID. 148 * The JavaScript of the paywall page (or the non-JS client 149 processing the ``Paivana`` HTTP header) then POSTs the order ID, 150 ``nonce``, ``expiration`` 151 and ``website`` to ``{domain}/.well-known/pavivana``. 152 In this JSON request, the ``nonce`` is ``crock32``-encoded and 153 ``expiration`` is a normal GNU Taler timestamp object 154 (``{"t_s": ...}``, in seconds); the server re-derives the binary 155 inputs given above from these values. 156 157 Note that by the time this POST is made, the client already has the 158 merchant backend's word that the order was paid: that is precisely 159 what its long poll on ``/sessions/{paivana_id}`` returned, and it is 160 where the order ID being posted came from. The step below is 161 therefore a *confirmation* of something the client has been told, and 162 not an open-ended wait for a payment that may still be in progress. 163 164 * paivana-httpd re-computes the paivana ID from ``nonce``, ``website`` 165 and ``expiration``, and asks the merchant backend, over its own 166 authenticated connection, whether the posted order ID was paid under 167 exactly that session ID. Recomputing rather than accepting the ID is 168 what binds the answer to this request: a client cannot post an order 169 it paid for one article and be let into another, because a different 170 ``website`` yields a different paivana ID and the order is then not 171 found under it. 172 173 The reply is accepted only if all of the following hold: 174 175 * the order status is *paid*, and the order has neither been refunded 176 nor has a refund pending — otherwise a client could take its money 177 back and keep the cookie; 178 * the contract's ``fulfillment_url``, if it has one, equals the 179 posted ``website``; if it has none, the ``website`` must lie under 180 paivana-httpd's own configured base URL, so that the client cannot 181 choose which site it is admitted to; 182 * ``expiration`` is not later than the contract's ``max_pickup_time``, 183 which is what stops a client from buying five minutes of access and 184 minting itself a cookie valid for a year. 185 186 If so, paivana-httpd issues the Paivana cookie described above, with 187 ``Max-Age`` derived from ``expiration``, and redirects to the 188 ``{website}``. 189 190 This query is made as a **long poll with a short, fixed bound** (5 191 seconds in the current implementation). Both halves matter: 192 193 * *Long poll*, because the client's confirmation and the backend's own 194 view of the order can be a moment apart, and because paivana-httpd 195 and the client may be talking to different backend processes. An 196 honest client that is merely early is waited for rather than turned 197 away, which is the difference between a working paywall and one that 198 intermittently refuses people who have paid. 199 * *Short and bounded*, because this endpoint is unauthenticated and 200 reachable before any payment has been shown to exist. The wait is 201 the interval for which an attacker can pin a connection by posting a 202 random order ID, so it is a cost that is deliberately kept small. 203 The same bound is applied client-side, so a merchant backend that 204 stops answering cannot pin connections either. 205 206 Where the order genuinely was not paid, the client is told so (HTTP 207 409 Conflict) after that bound has elapsed; where the backend did not 208 answer at all, it gets 504 Gateway Timeout, and where the backend 209 answered something unusable, 502 Bad Gateway. Distinguishing these 210 matters operationally: only the first is the client's fault. 211 212 * The browser reloads the page with the correct 213 Paivana cookie (see first step). 214 215 216 Problems: 217 --------- 218 219 * A smart attacker might still create a lot of orders via the pay-template. 220 221 * Solution A: Don't care, unlikely to happen in the first place. 222 * Solution B: Rate-limit template instantiation on a per-IP basis. 223 224 Accepted risks: 225 --------------- 226 227 Four properties of this design were examined and deliberately kept as they 228 are. Each is recorded here together with the assumption that makes it 229 acceptable, because a deployment that does not satisfy the assumption does 230 not get the property. 231 232 Only one price per URL 233 ~~~~~~~~~~~~~~~~~~~~~~ 234 235 paivana-httpd quotes a price by taking the first configured template whose 236 anchored ``website_regex`` matches the requested URL; a template configured 237 without a regex matches every URL. At redemption, the checks listed above 238 are all that can be made: the contract carries a fulfillment URL and a 239 ``max_pickup_time``, and it does not carry the identity of the template it 240 was instantiated from. paivana-httpd therefore cannot tell an order created 241 under one template from an order created under another, and in particular 242 cannot check that the amount paid is the amount its own template search 243 would have quoted for the URL being unlocked. 244 245 Where an instance carries more than one paivana template — or one template 246 without a ``website_regex``, which matches everything — this is exploitable 247 in the obvious way. A client that wants an expensive URL instantiates the 248 cheap template with that URL as its fulfillment URL, pays the cheap price, 249 and posts the result for redemption; both orders name the same fulfillment 250 URL, which is all the redemption check inspects. The exposure is wider than 251 the configured regular expressions suggest, because the merchant backend 252 matches ``website_regex`` unanchored where paivana-httpd anchors it: the set 253 of URLs the backend will sell a template for is a superset of the set 254 paivana-httpd paywalls with it. 255 256 The mitigation is a property of the configuration rather than of the code. 257 A merchant instance used by paivana-httpd carries exactly one paivana 258 template, so that every URL it paywalls has exactly one price and there is 259 nothing to substitute; differentiated pricing across a site is then a matter 260 of separate instances, each with its own template and its own paivana-httpd. 261 **The risk is accepted on the assumption that a deployment presents a single 262 price for every URL it paywalls.** A deployment that puts two paivana 263 templates on one instance is selling its expensive articles at the cheaper 264 price. 265 266 Closing the gap properly requires the merchant backend to record the 267 instantiating ``template_id`` in the contract terms and to report it with 268 the order status; paivana-httpd could then re-run its own template search 269 for the posted ``website`` and require the two to agree. That is a 270 merchant-side change in a separate upstream, and this document does not 271 assume it. 272 273 Payment buys access, not a seat 274 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 275 276 The redemption POST is idempotent and unmetered, and nothing records that an 277 order or a paivana ID has already been redeemed. The cookie it returns is 278 bound to the address of whoever posted the redemption, not to the address 279 that paid. Anyone holding the four posted fields — order ID, ``nonce``, 280 ``expiration`` and ``website`` — can therefore obtain their own cookie, for 281 their own address, at any point until ``expiration``, and a buyer who 282 publishes those four fields has given the article to everyone who reads 283 them. 284 285 This is intended behaviour and not a defect. What is sold is access to one 286 resource until one moment, and the buyer may pass that on, in the same way 287 and for the same reasons that the buyer of a newspaper may hand it to the 288 next reader. The purchase stays bounded by what was bought: sharing extends 289 a payment to more readers, never to more URLs and never past ``expiration``, 290 so a client that wants the whole site still pays for the whole site. That 291 bound is what lets the design's actual goal — making bulk automated 292 retrieval expensive — survive the sharing. **The risk is accepted on the 293 assumption that deployments price access per resource and per unit of time, 294 and that none of them requires per-seat licensing**, which this design 295 cannot provide and must not be configured as though it could. 296 297 One consequence has to be stated plainly, because the construction of the 298 cookie invites the opposite reading: binding the cookie to the client 299 address is a cookie-theft mitigation and nothing else. It ensures that a 300 cookie which leaks — from a log, a shared machine, a proxy — is useless to 301 whoever picks it up. It provides no anti-sharing property whatsoever, since 302 the redemption that mints cookies is open to every address. 303 304 The redemption endpoint is thus unmetered by intent. Metering it would not 305 restore any property this design claims; the rate-limiting question raised 306 above for template instantiation is a question about load, it applies to 307 this endpoint in the same form, and it is open in the same way. 308 309 Entropy of the server secret 310 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 311 312 ``paivana_server_secret`` is derived from the configured secret by a single 313 unsalted SHA-512. There is no stretching and no salt, so the cost of 314 guessing that secret offline from one observed cookie is one hash per 315 candidate: the strength of every cookie the deployment will ever issue is 316 the entropy of the configured string, and nothing more. 317 318 The requirement that follows is placed on the operator. The configured 319 secret must carry at least 128 bits drawn from a cryptographic random 320 source, and must never be a passphrase, a hostname, a token reused from 321 elsewhere, or the placeholder that ships in the sample configuration — which 322 is an example rather than a secret, and leaves a deployment that keeps it 323 with no secret at all. Where no secret is configured, paivana-httpd uses a 324 fresh random value per process, which is safe but invalidates every 325 outstanding cookie whenever the service restarts. 326 327 Absorbing the requirement into the construction was considered and rejected. 328 A memory-hard KDF exists to make human-chosen, low-entropy secrets expensive 329 to guess; it buys a fixed factor, no fixed factor rescues a guessable 330 phrase, and against 128 genuine bits it buys nothing that is needed. 331 ``paivana_server_secret`` is a machine-generated configuration value that 332 nobody has to remember or type, so the situation a KDF defends against is 333 one the deployment can simply not be in. **The risk is accepted on the 334 assumption that the secret is produced by a random generator and never 335 chosen by a person**; where a person chooses it, the cookies are forgeable 336 and the paywall is decorative. How to generate such a secret is operator 337 guidance and belongs with the manual rather than here. 338 339 Truncation is unreportable to an HTTP/1.0 client 340 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ 341 342 paivana-httpd relays bodies as they arrive rather than assembling them 343 first, which is what lets it serve content larger than memory and lets the 344 client start receiving before the upstream has finished. The cost is that 345 the upstream's status line and headers reach the client long before the 346 body is complete, so an upstream that fails mid-body cannot be reported as 347 ``502`` — that status has already been spent. 348 349 What is left is to break the framing, which for almost every client is 350 enough: a declared ``Content-Length`` is left unmet, or a chunked response 351 is closed without its terminating chunk, and RFC 9112 section 8.1.2 352 requires a recipient to treat either as a failed message. The exception is 353 an HTTP/1.0 client receiving a response whose length the upstream never 354 declared. Such a client cannot be sent chunks, so the close of the 355 connection *is* the end-of-body marker, and a truncated body is 356 byte-for-byte indistinguishable from a complete one. 357 358 The alternative would be to buffer each response until it is known to be 359 complete, which is exactly the property being given up, and which bounds 360 every response by memory to buy correct reporting for one obsolete client 361 version. **The risk is accepted on the assumption that clients speak 362 HTTP/1.1**, which every browser and every HTTP library in current use has 363 done since well before this design; where a genuine HTTP/1.0 client is 364 expected, the upstream should be configured to declare a 365 ``Content-Length``, which restores detection for it too. 366 367 Implementation: 368 --------------- 369 370 * Merchant backend needs way to lookup order IDs under a ``session_id`` 371 (DONE: e027e729..b476f8ae) 372 * Merchant backend needs way to instantiate templates with 373 a given ``session_id`` and ``fulfillment_url``. This also 374 requires extending the allowed responses for templates in general. 375 * Paivana component needs to be implemented 376 * Wallet-core needs support for a ``session_id`` and 377 ``fulfillment_url`` in pay templates. 378 379 380 Test Plan 381 ========= 382 383 * Deploy it for git.taler.net 384 385 Definition of Done 386 ================== 387 388 N/A 389 390 Alternatives 391 ============ 392 393 * Do not re-use the session ID mechanism but introduce some new concept. 394 This has the drawback of us needing additional tables and indicies, 395 and also the existing use of the session ID is very parallel to this one. 396 * Instead of doing a 303 See Other, cache control could have been achieved by 397 specifying a "Vary: Cookie" HTTP header. We may combine these and use 398 that to additionally enable caching of the 303 See Other. The 303 solution 399 has the advantage that there is only one page to cache per template, and 400 the disadvantage of an additional redirect. Note that this is purely 401 a frontend design choice, wallets and merchant backends work nicely with 402 either approach. 403 404 Drawbacks 405 ========= 406 407 * This exposes an order ID to anyone who knows the session ID. This is 408 clearly not an issue in this context, and for the existing uses of 409 the session ID it also seems clear that knowledge of the session ID 410 requires an attacker to have access that would easily also already 411 give them any order ID, so this seems harmless. 412 413 414 Discussion / Q&A 415 ================