nish 0.49.1 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. package/README.md +27 -21
  2. package/docs/AI.md +237 -160
  3. package/docs/INSTALL.md +1 -1
  4. package/package.json +12 -12
  5. package/runtime/gfx/nish-gfx.h +373 -61
  6. package/runtime/nish.d.ts +94 -11
  7. package/runtime/nish.h +5 -0
  8. package/runtime/runtime-host.c +21 -5
  9. package/std/README.md +14 -11
  10. package/std/base64.ts +74 -35
  11. package/std/bytes.ts +207 -97
  12. package/std/cli-args.ts +150 -107
  13. package/std/compress/checksum.ts +68 -10
  14. package/std/compress/deflate.ts +213 -115
  15. package/std/compress/gzip.ts +124 -49
  16. package/std/compress/zlib.ts +57 -15
  17. package/std/crypto/aes.ts +51 -9
  18. package/std/crypto/base64url.ts +93 -66
  19. package/std/crypto/bcrypt.ts +25 -21
  20. package/std/crypto/ed25519.ts +12 -10
  21. package/std/crypto/hkdf.ts +405 -283
  22. package/std/crypto/hmac.ts +484 -149
  23. package/std/crypto/jwt.ts +51 -40
  24. package/std/crypto/p256.ts +14 -19
  25. package/std/crypto/pki-roots.ts +35 -12
  26. package/std/crypto/pki.ts +43 -55
  27. package/std/crypto/rsa-sign.ts +1635 -0
  28. package/std/crypto/rsa.ts +26 -4
  29. package/std/crypto/sha256.ts +212 -90
  30. package/std/crypto/sha512.ts +135 -49
  31. package/std/crypto/x25519.ts +12 -11
  32. package/std/crypto/x509.ts +164 -40
  33. package/std/gpu/sys.ts +490 -0
  34. package/std/json-equal.ts +33 -18
  35. package/std/json-format.ts +39 -8
  36. package/std/json-number.ts +15 -3
  37. package/std/json-tokenizer.ts +4 -3
  38. package/std/json-typed.ts +12 -6
  39. package/std/json-value.ts +236 -119
  40. package/std/json.ts +81 -46
  41. package/std/net/buffer-pool.ts +25 -14
  42. package/std/net/dns-config.ts +18 -5
  43. package/std/net/dns-message.ts +60 -27
  44. package/std/net/dns-resolver.ts +35 -16
  45. package/std/net/dns.ts +3 -2
  46. package/std/net/fetch.ts +224 -61
  47. package/std/net/handler.ts +189 -88
  48. package/std/net/hpack.ts +216 -103
  49. package/std/net/http-compress.ts +104 -42
  50. package/std/net/http-fields.ts +327 -31
  51. package/std/net/http-server.ts +326 -24
  52. package/std/net/http1-client-codec.ts +159 -55
  53. package/std/net/http1-codec.ts +427 -237
  54. package/std/net/http1-server.ts +220 -38
  55. package/std/net/http2-cleartext.ts +10 -4
  56. package/std/net/http2-frame.ts +2 -2
  57. package/std/net/http2-tls.ts +3 -3
  58. package/std/net/http2.ts +69 -15
  59. package/std/net/http3-frame.ts +11 -14
  60. package/std/net/http3-server.ts +139 -60
  61. package/std/net/http3.ts +140 -79
  62. package/std/net/multipart.ts +592 -0
  63. package/std/net/outbound.ts +24 -8
  64. package/std/net/postgres-async.ts +97 -64
  65. package/std/net/postgres-carrier.ts +28 -4
  66. package/std/net/postgres.ts +166 -65
  67. package/std/net/prefork.ts +86 -5
  68. package/std/net/protobuf.ts +6 -2
  69. package/std/net/qpack.ts +147 -40
  70. package/std/net/quic-conn-ack.ts +27 -7
  71. package/std/net/quic-conn-cid.ts +13 -7
  72. package/std/net/quic-datagram.ts +6 -5
  73. package/std/net/quic-frame.ts +67 -23
  74. package/std/net/quic-listener.ts +61 -39
  75. package/std/net/quic-packet.ts +91 -50
  76. package/std/net/quic-recovery.ts +11 -9
  77. package/std/net/quic-stream.ts +36 -27
  78. package/std/net/quic.ts +84 -54
  79. package/std/net/router.ts +136 -24
  80. package/std/net/serve.ts +59 -5
  81. package/std/net/static.ts +86 -36
  82. package/std/net/tls/client.ts +81 -34
  83. package/std/net/tls/codec.ts +3 -4
  84. package/std/net/tls/record.ts +80 -35
  85. package/std/net/tls/schedule.ts +339 -149
  86. package/std/net/tls/ticket.ts +6 -5
  87. package/std/net/tls-tcp.ts +69 -30
  88. package/std/net/tls.ts +194 -50
  89. package/std/net/upstream.ts +83 -38
  90. package/std/net/url.ts +170 -94
  91. package/std/net/websocket.ts +19 -20
  92. package/std/net/webtransport.ts +123 -33
  93. package/std/raster.ts +12 -2
  94. package/std/regex.ts +600 -388
  95. package/std/sqlite.ts +37 -19
  96. package/std/sync/ring.ts +232 -115
  97. package/std/sync/shm.ts +11 -4
  98. package/std/temporal.ts +232 -133
  99. package/std/term-io.ts +12 -6
  100. package/std/term-pixels.ts +176 -24
  101. package/std/term-rate.ts +8 -3
  102. package/std/term.ts +4 -4
  103. package/std/text.ts +38 -16
  104. package/std/yaml-json.ts +238 -106
  105. package/std/yaml-lines.ts +47 -27
  106. package/std/yaml-write.ts +58 -24
  107. package/std/yaml.ts +808 -395
@@ -86,6 +86,7 @@ import {
86
86
  } from "nish/crypto/chacha20poly1305"
87
87
  import { tlsSuiteHashLength } from "nish/net/tls/schedule"
88
88
  import { Secret, exposeWith, secret, wipe } from "nish:secret"
89
+ import { wrappingAdd } from "nish:unsafe"
89
90
 
90
91
  /** A ticket key's id, sent in the clear at the head of each ticket it seals. */
91
92
  export const TLS_TICKET_KEY_ID_SIZE: i32 = 16
@@ -134,21 +135,21 @@ const TLS_TICKET_NAME_AT: i32 = 22
134
135
 
135
136
  /**
136
137
  * `a + b`, held at the `i64` range's ends rather than past them. Two values of one
137
- * sign sum within 2^64 of zero, so their sum in `u64` reads across the sign bit only
138
- * when it has left the range.
138
+ * sign sum within 2^64 of zero, so `wrappingAdd` crosses the sign bit only when the
139
+ * true sum has left the range: the wrap is how that is seen, and the sum is held instead.
139
140
  */
140
141
  const tlsTicketAdd = (a: i64, b: i64): i64 => {
141
142
  if (a >= 0) {
142
143
  if (b < 0) {
143
144
  return a + b
144
145
  }
145
- const sum: i64 = toI64(toU64(a) + toU64(b))
146
- return sum >= 0 ? sum : toI64((toU64(0) - toU64(1)) >> toU64(1))
146
+ const sum: i64 = wrappingAdd(a, b)
147
+ return sum >= 0 ? sum : toI64(-1) >>> toI64(1)
147
148
  }
148
149
  if (b >= 0) {
149
150
  return a + b
150
151
  }
151
- const sum: i64 = toI64(toU64(a) + toU64(b))
152
+ const sum: i64 = wrappingAdd(a, b)
152
153
  return sum < 0 ? sum : toI64(toU64(1) << toU64(63))
153
154
  }
154
155
 
@@ -14,7 +14,7 @@
14
14
  * if (slot >= 0) { pollAdd(loop, tls.fd(slot), 1, slot); }
15
15
  * // when a connection's token comes back:
16
16
  * let wants: i32 = (events & 5) !== 0 ? tls.readable(slot) : tls.writable(slot);
17
- * if ((wants & TLS_RECORD_SIGN) !== 0) { wants = tls.signP256(slot, leafKey); }
17
+ * if ((wants & TLS_RECORD_SIGN) !== 0) { wants = tls.signKey(slot, leafKey); }
18
18
  * if ((wants & TLS_RECORD_DATA) !== 0) { tls.read(slot, buf, 0, buf.length); ... }
19
19
  * if ((wants & TLS_RECORD_DONE) !== 0) { tls.close(slot); }
20
20
  * else { pollModify(loop, tls.fd(slot), wants & 3, slot); }
@@ -59,10 +59,14 @@
59
59
  * the slot's copy of the key is wiped once the ServerHello is written, when the
60
60
  * handshake fails, or when the slot is closed.
61
61
  *
62
- * **Signing is the caller's**, as `TlsServer`'s is: `signP256` signs the
63
- * CertificateVerify with a P-256 key the caller holds as a `Secret` and borrows
64
- * for the call, and `signatureInput` / `sign` hand the input out and take any
65
- * signature back.
62
+ * **Signing is the caller's**, as `TlsServer`'s is: `signKey` signs the
63
+ * CertificateVerify with the key the caller holds as a `Secret` and borrows
64
+ * for the call (P-256 or RSA, as the configuration's `signatureScheme`
65
+ * says), and `signatureInput` / `sign` hand the input out and take any
66
+ * signature back. Nothing checks that the key, the leaf certificate and
67
+ * `signatureScheme` agree: the signer refuses only a key not of its
68
+ * scheme's shape, and a key of the right shape that is not the leaf's signs,
69
+ * so the client's check of the CertificateVerify is what fails.
66
70
  *
67
71
  * **Resumption is opt-in, and its keys are the caller's.** After
68
72
  * `enableTickets`, a slot whose interest says `TLS_RECORD_TICKET` waits on
@@ -117,7 +121,7 @@ import {
117
121
  tcpConnect,
118
122
  } from "nish:net"
119
123
  import { monotonicNanos, wallClockNanos } from "nish:process"
120
- import { TlsP256Signer, TlsServer, TlsServerConfig } from "nish/net/tls"
124
+ import { TlsKeySigner, TlsServer, TlsServerConfig } from "nish/net/tls"
121
125
  import { TlsClient, TlsClientConfig } from "nish/net/tls/client"
122
126
  import { TLS_RECORD_AUTH, TlsRecordClient } from "nish/net/tls/record-client"
123
127
  import { TlsClientTrust, tlsClientAuthenticate, tlsClientSystemTrust } from "nish/net/tls/verify"
@@ -224,8 +228,11 @@ export class TlsTcpServer {
224
228
  private scratch: u8[]
225
229
  /** The last accepted peer's address, in `nish:net`'s 18-byte form. */
226
230
  peer: u8[]
227
- /** Signs every slot's CertificateVerify in `signP256`, one for the pool, keeping nothing per signature. */
228
- private signer: TlsP256Signer
231
+ /**
232
+ * Signs every slot's CertificateVerify in `signKey`, in the configuration's
233
+ * scheme: one for the pool, keeping nothing per signature.
234
+ */
235
+ private signer: TlsKeySigner
229
236
  /**
230
237
  * Each slot's own copy of its connection's server random: `TlsServer`
231
238
  * keeps the array it is given and writes it into the ServerHello only once
@@ -290,7 +297,7 @@ export class TlsTcpServer {
290
297
  this.pools = new TlsRecordPools(this.slots)
291
298
  this.scratch = new Array<u8>(TLS_MAX_RECORD)
292
299
  this.peer = new Array<u8>(TLS_TCP_ADDRESS_SIZE)
293
- this.signer = new TlsP256Signer()
300
+ this.signer = new TlsKeySigner(config.signatureScheme)
294
301
  }
295
302
 
296
303
  /**
@@ -754,17 +761,18 @@ export class TlsTcpServer {
754
761
  }
755
762
 
756
763
  /**
757
- * Signs `slot`'s CertificateVerify with the P-256 private key `key` and
758
- * hands it over, as `sign` does, through the pool's `TlsP256Signer`, so a
759
- * handshake's signature keeps nothing. The key is borrowed: the caller made
760
- * the `Secret`, and wipes it. A malformed key fails the connection with
761
- * `internal_error`.
764
+ * Signs `slot`'s CertificateVerify with `key` in the configuration's
765
+ * `signatureScheme` — a P-256 key for `ecdsa_secp256r1_sha256`, an RSA key
766
+ * for `rsa_pss_rsae_sha256` — and hands it over, as `sign` does, through
767
+ * the pool's `TlsKeySigner`, so a handshake's signature keeps nothing. The
768
+ * key is borrowed: the caller made the `Secret`, and wipes it. A key of the
769
+ * wrong kind or a malformed one fails the connection with `internal_error`.
762
770
  *
763
771
  * @param slot The slot whose interest says `TLS_RECORD_SIGN`.
764
- * @param key The certificate's P-256 private key; borrowed, still the caller's to wipe.
772
+ * @param key The certificate's private key; borrowed, still the caller's to wipe.
765
773
  * @returns The slot's interest after sending; the current interest when the slot wants no signature.
766
774
  */
767
- signP256(slot: i32, key: Secret<u8[]>): i32 {
775
+ signKey(slot: i32, key: Secret<u8[]>): i32 {
768
776
  const input: u8[] | null = this.signatureInput(slot)
769
777
  if (input === null) {
770
778
  return this.interest(slot)
@@ -781,6 +789,18 @@ export class TlsTcpServer {
781
789
  return this.sign(slot, signature)
782
790
  }
783
791
 
792
+ /**
793
+ * `signKey`, under the name it had when P-256 was the only scheme: it signs
794
+ * in whatever scheme the configuration names.
795
+ *
796
+ * @param slot The slot whose interest says `TLS_RECORD_SIGN`.
797
+ * @param key The certificate's private key; borrowed, still the caller's to wipe.
798
+ * @returns The slot's interest after sending.
799
+ */
800
+ signP256(slot: i32, key: Secret<u8[]>): i32 {
801
+ return this.signKey(slot, key)
802
+ }
803
+
784
804
  /**
785
805
  * Turns session resumption on for every slot (`TlsServer.enableTickets`):
786
806
  * from the next `accept`, a connection offering a ticket, or one that may
@@ -1337,13 +1357,16 @@ export class TlsTcpClient {
1337
1357
  let loop: i32 = -1
1338
1358
  let result: i32 = 0
1339
1359
  while (true) {
1340
- if (done < len) {
1341
- // Wrapping sums, exact while they fit: `done` runs from 0 up to `len`,
1342
- // so the rest is exact, and an `off + done` past `i32` comes out
1343
- // negative, a window `write` refuses with -22 rather than a panic.
1344
- const n: i32 = this.write(data, toI32(toU32(off) + toU32(done)), toI32(toU32(len) - toU32(done)))
1360
+ if (len > 0 && done >= 0 && done < len) {
1361
+ // `done` runs from 0 up to `len`, so the rest is exact; an
1362
+ // `off + done` past `i32` is -1, a window `write` refuses with -22.
1363
+ const rest: i32 = len - done
1364
+ const from: i64 = toI64(off) + toI64(done)
1365
+ const n: i32 = this.write(data, from > toI64(2147483647) ? toI32(-1) : toI32(from), rest)
1345
1366
  if (n >= 0) {
1346
- done = toI32(toU32(done) + toU32(n))
1367
+ // `write` takes at most `rest`; counted down from `len`.
1368
+ const left: i32 = rest >= 0 ? rest - n : 0
1369
+ done = left > 0 ? len - left : len
1347
1370
  } else if (n !== TLS_RECORD_AGAIN) {
1348
1371
  result = n
1349
1372
  break
@@ -1504,20 +1527,36 @@ export class TlsTcpClient {
1504
1527
  }
1505
1528
  }
1506
1529
 
1530
+ /** 2^62 - 1, where a deadline stops: centuries past any clock reading. */
1531
+ const TLS_TCP_CLOCK_MAX: i64 = 1073741824 * 4294967296 - 1
1532
+
1507
1533
  /**
1508
- * The monotonic clock `timeoutMs` milliseconds from now. Added wrapping:
1509
- * the clock counts up from boot, far below 2^62, and an `i32` of
1510
- * milliseconds is below 2^52 nanoseconds either way, so the sum is exact.
1534
+ * The monotonic clock `timeoutMs` milliseconds from now. The clock counts up
1535
+ * from boot, far below 2^62, and an `i32` of milliseconds is below 2^52
1536
+ * nanoseconds, so the sum is exact; it is taken below `TLS_TCP_CLOCK_MAX`,
1537
+ * which it would stop at. A negative timeout is a deadline already passed: now.
1511
1538
  */
1512
- const tlsTcpDeadline = (timeoutMs: i32): i64 =>
1513
- toI64(toU64(monotonicNanos()) + toU64(toI64(timeoutMs) * TLS_TCP_NANOS_PER_MS))
1539
+ const tlsTcpDeadline = (timeoutMs: i32): i64 => {
1540
+ const now: i64 = monotonicNanos()
1541
+ const span: i64 = toI64(timeoutMs) * TLS_TCP_NANOS_PER_MS
1542
+ if (now < 0 || span < 0) {
1543
+ return now
1544
+ }
1545
+ const room: i64 = TLS_TCP_CLOCK_MAX - now
1546
+ if (room < 0) {
1547
+ return TLS_TCP_CLOCK_MAX
1548
+ }
1549
+ const left: i64 = room - span
1550
+ return left > 0 ? TLS_TCP_CLOCK_MAX - left : TLS_TCP_CLOCK_MAX
1551
+ }
1514
1552
 
1515
1553
  /**
1516
1554
  * How many output bytes wait between `start` and `end`, for a loop that runs
1517
- * while `end > start`. Taken unsigned: a record layer's output start is never
1518
- * negative, so the gap is exact and cannot overflow.
1555
+ * while `end > start`. A record layer's output start is never negative; a
1556
+ * pair out of that order has none waiting.
1519
1557
  */
1520
- const tlsTcpPending = (start: i32, end: i32): i32 => toI32(toU32(end) - toU32(start))
1558
+ const tlsTcpPending = (start: i32, end: i32): i32 =>
1559
+ start >= 0 && end >= 0 && end >= start ? end - start : 0
1521
1560
 
1522
1561
  /**
1523
1562
  * Opens a TLS 1.3 connection to the server at `addr` (`nish:net`'s 18-byte
package/std/net/tls.ts CHANGED
@@ -102,6 +102,7 @@ import {
102
102
  p256SignSha256,
103
103
  p256SignSha256Into,
104
104
  } from "nish/crypto/p256"
105
+ import { RsaSignScratch, rsaPrivateKeyBits, rsaSignPssSha256Into } from "nish/crypto/rsa-sign"
105
106
  import { timingSafeEqual, timingSafeEqualAt } from "nish/crypto/ct"
106
107
  import { X25519_SIZE, x25519, x25519Base } from "nish/crypto/x25519"
107
108
  import {
@@ -121,6 +122,8 @@ import {
121
122
  TLS_EXT_RECORD_SIZE_LIMIT,
122
123
  TLS_RANDOM_SIZE,
123
124
  TLS_RECORD_SIZE_LIMIT_MAX,
125
+ TLS_SIGNATURE_ECDSA_SECP256R1_SHA256,
126
+ TLS_SIGNATURE_RSA_PSS_RSAE_SHA256,
124
127
  TLS_VERSION_13,
125
128
  TLS_P256_SHARE_SIZE,
126
129
  TLS_X25519_SHARE_SIZE,
@@ -229,7 +232,9 @@ export interface TlsServerConfig {
229
232
  /**
230
233
  * The signature scheme the caller's key signs with, sent in
231
234
  * CertificateVerify: `TLS_SIGNATURE_ECDSA_SECP256R1_SHA256` for a P-256
232
- * key. A client that does not list it is refused with `handshake_failure`.
235
+ * key, `TLS_SIGNATURE_RSA_PSS_RSAE_SHA256` for an RSA key of 2048 to 4096
236
+ * bits (`TlsKeySigner` signs either). A client that does not list it is
237
+ * refused with `handshake_failure`.
233
238
  */
234
239
  signatureScheme: i32
235
240
  /** Whether the carrier is QUIC, which turns `quic_transport_parameters` on both ways. */
@@ -296,8 +301,8 @@ const tlsExtensionsHave = (extensions: u8[], type: i32): boolean => {
296
301
  if (length > end - at - 4) {
297
302
  return false
298
303
  }
299
- // At most `end`, an array length, so the unsigned sum cannot wrap.
300
- at = toI32(toU32(at) + toU32(4) + toU32(length))
304
+ // At most `end` by the check above; -1 past 2^31 ends the walk.
305
+ at = tlsSum(tlsSum(at, 4), length)
301
306
  }
302
307
  return false
303
308
  }
@@ -378,8 +383,8 @@ const tlsDerIntegerInto = (out: u8[], to: i32, rs: u8[], at: i32, length: i32):
378
383
  j++
379
384
  from++
380
385
  }
381
- // Inside `out` by the check above, so the unsigned sum cannot wrap.
382
- return toI32(toU32(to) + toU32(2) + toU32(length))
386
+ // Inside `out` by the check above; -1 past 2^31.
387
+ return tlsSum(tlsSum(to, 2), length)
383
388
  }
384
389
 
385
390
  /**
@@ -502,6 +507,103 @@ export class TlsP256Signer {
502
507
  }
503
508
  }
504
509
 
510
+ /**
511
+ * Signs CertificateVerify inputs for `rsa_pss_rsae_sha256` (RFC 8446
512
+ * §4.2.3) with nothing kept per signature: `rsaSignPssSha256Into` hashes in
513
+ * this signer's scratch, releases what it allocates, and writes the
514
+ * signature into this signer's own array of the key's length, which
515
+ * `TlsServer.sign` stores as it stores a P-256 one. The array is made by the
516
+ * first signature with a key of a new length and kept, so a server with one
517
+ * key allocates it once. A carrier keeps one signer, not one per slot.
518
+ */
519
+ export class TlsRsaSigner {
520
+ /** The hashers every signature hashes in. */
521
+ private scratch: RsaSignScratch
522
+ /** The last signature, as long as the key's modulus; empty before the first. */
523
+ private out: u8[]
524
+
525
+ /** Makes the hashers; the signature array waits for the first key. */
526
+ constructor() {
527
+ this.scratch = new RsaSignScratch()
528
+ this.out = []
529
+ }
530
+
531
+ /**
532
+ * The `rsa_pss_rsae_sha256` signature of `content` under `priv`, in this
533
+ * signer's own array; `null` for a `Secret` that is not an RSA key from
534
+ * `rsaParsePrivateKey` or `x509ParseRsaPrivateKey`, and for a signature
535
+ * that fails the check against the public exponent. The key is borrowed.
536
+ *
537
+ * @param priv The server's RSA private key, borrowed.
538
+ * @param content The CertificateVerify input, as `TlsServer.signatureInput` answers it.
539
+ * @returns This signer's own array, which the next `sign` overwrites, or `null`.
540
+ */
541
+ sign(priv: Secret<u8[]>, content: u8[]): u8[] | null {
542
+ const bits: i32 = rsaPrivateKeyBits(priv)
543
+ if (bits < 2048 || bits > 4096) {
544
+ return null
545
+ }
546
+ const k: i32 = (bits + 7) >> 3
547
+ if (k < 256 || k > 512) {
548
+ return null
549
+ }
550
+ if (toI32(this.out.length) !== k) {
551
+ this.out = new Array<u8>(k)
552
+ }
553
+ if (
554
+ !rsaSignPssSha256Into(this.scratch, priv, content, TLS_FROM, toI32(content.length), this.out, TLS_FROM)
555
+ ) {
556
+ return null
557
+ }
558
+ return this.out
559
+ }
560
+ }
561
+
562
+ /**
563
+ * The CertificateVerify signer for a configuration's `signatureScheme`: a
564
+ * `TlsP256Signer` for `TLS_SIGNATURE_ECDSA_SECP256R1_SHA256`, a
565
+ * `TlsRsaSigner` for `TLS_SIGNATURE_RSA_PSS_RSAE_SHA256`, and for any other
566
+ * scheme none, so every signature answers `null` and the connection fails
567
+ * with `internal_error`. Only the one the scheme names is made.
568
+ */
569
+ export class TlsKeySigner {
570
+ /** The P-256 signer, with that scheme. */
571
+ private p256: TlsP256Signer | null
572
+ /** The RSA-PSS signer, with that scheme. */
573
+ private rsa: TlsRsaSigner | null
574
+
575
+ /**
576
+ * Makes the signer `scheme` names.
577
+ *
578
+ * @param scheme The configuration's `signatureScheme`.
579
+ */
580
+ constructor(scheme: i32) {
581
+ this.p256 = scheme === TLS_SIGNATURE_ECDSA_SECP256R1_SHA256 ? new TlsP256Signer() : null
582
+ this.rsa = scheme === TLS_SIGNATURE_RSA_PSS_RSAE_SHA256 ? new TlsRsaSigner() : null
583
+ }
584
+
585
+ /**
586
+ * `content` signed under `priv` in the scheme this signer was made for,
587
+ * in the inner signer's own array; `null` for a key that is not of that
588
+ * kind, a signature that fails, or a scheme with no signer.
589
+ *
590
+ * @param priv The server's private key, borrowed.
591
+ * @param content The CertificateVerify input, as `TlsServer.signatureInput` answers it.
592
+ * @returns The inner signer's own array, or `null`.
593
+ */
594
+ sign(priv: Secret<u8[]>, content: u8[]): u8[] | null {
595
+ const p256: TlsP256Signer | null = this.p256
596
+ if (p256 !== null) {
597
+ return p256.sign(priv, content)
598
+ }
599
+ const rsa: TlsRsaSigner | null = this.rsa
600
+ if (rsa !== null) {
601
+ return rsa.sign(priv, content)
602
+ }
603
+ return null
604
+ }
605
+ }
606
+
505
607
  /**
506
608
  * Whether an x25519 shared secret is all zeros, reading every byte (run inside `expose`).
507
609
  *
@@ -669,6 +771,19 @@ class TlsExchangeWords {
669
771
  hashLength: i32 = 0
670
772
  }
671
773
 
774
+ /**
775
+ * `a + b` for two offsets or sizes, or -1 when either is negative or the sum
776
+ * passes 2^31 - 1. The sum is taken in i64, where it cannot overflow; -1 is
777
+ * an offset outside every array and a size no buffer grows to.
778
+ */
779
+ const tlsSum = (a: i32, b: i32): i32 => {
780
+ if (a < 0 || b < 0) {
781
+ return -1
782
+ }
783
+ const sum: i64 = toI64(a) + toI64(b)
784
+ return sum > toI64(2147483647) ? -1 : toI32(sum)
785
+ }
786
+
672
787
  /**
673
788
  * `n` zero bytes; none for a negative `n`. A length a `u16` holds is one
674
789
  * allocation; a longer one is pushed a byte at a time.
@@ -699,11 +814,10 @@ const tlsWordAt = (b: u8[], at: i32): u64 => {
699
814
  }
700
815
 
701
816
  /**
702
- * `tlsWordAt(b, at + skip)` for a share's later words. The offset is summed
703
- * in u32, which is the i32 sum wherever that does not wrap; where it would,
704
- * the offset lands below zero and the word reads as zero, outside `b`.
817
+ * `tlsWordAt(b, at + skip)` for a share's later words. Where the sum would
818
+ * pass 2^31 the offset is -1, and the word reads as zero, outside `b`.
705
819
  */
706
- const tlsWordAfter = (b: u8[], at: i32, skip: i32): u64 => tlsWordAt(b, toI32(toU32(at) + toU32(skip)))
820
+ const tlsWordAfter = (b: u8[], at: i32, skip: i32): u64 => tlsWordAt(b, tlsSum(at, skip))
707
821
 
708
822
  /** `v` big-endian into `b[at .. at + 8)`; a byte outside `b` is dropped. */
709
823
  const tlsWordInto = (b: u8[], at: i32, v: u64): void => {
@@ -1002,8 +1116,8 @@ const tlsFlightCapacity = (config: TlsServerConfig): i32 => {
1002
1116
  config.quic ? 0 : TLS_RECORD_SIZE_LIMIT_MAX
1003
1117
  )
1004
1118
  const certificate: i32 = tlsWriteCertificate(none, TLS_FROM, config.certificateChain)
1005
- // Two non-negative i32s and a constant: the u32 sum cannot wrap, and `tlsConfigFits` keeps it far below 2^31.
1006
- return toI32(toU32(extensions) + toU32(certificate) + toU32(8 + TLS_ECDSA_SIGNATURE_MAX + 4 + SHA384_SIZE))
1119
+ // `tlsConfigFits` keeps the sum far below 2^31; past it, -1 sizes nothing.
1120
+ return tlsSum(tlsSum(extensions, certificate), 8 + TLS_ECDSA_SIGNATURE_MAX + 4 + SHA384_SIZE)
1007
1121
  }
1008
1122
 
1009
1123
  // ---- Resumption ------------------------------------------------------------------
@@ -1289,10 +1403,8 @@ export class TlsServer {
1289
1403
  this.opened = new TlsTicketState()
1290
1404
  this.issuing = new TlsTicketState()
1291
1405
  this.ticketScratch = tlsZeros(tlsServerTicketCapacity(this.issuing))
1292
- // A few hundred bytes and a constant: the u32 sum cannot wrap.
1293
- this.outputApplication = tlsZeros(
1294
- toI32(toU32(toI32(this.ticketScratch.length)) + toU32(TLS_SERVER_TICKET_OVERHEAD))
1295
- )
1406
+ // A few hundred bytes and a constant.
1407
+ this.outputApplication = tlsZeros(tlsSum(toI32(this.ticketScratch.length), TLS_SERVER_TICKET_OVERHEAD))
1296
1408
  this.ticketNonce = new Array<u8>(1)
1297
1409
  this.ageAddBytes = new Array<u8>(4)
1298
1410
  this.restart(serverRandom, ephemeralPrivate)
@@ -1470,9 +1582,9 @@ export class TlsServer {
1470
1582
  }
1471
1583
  const most: i32 = TLS_MAX_HANDSHAKE_MESSAGE + 4
1472
1584
  let size: i32 = capacity
1473
- // Stopping at `most` gives the same clamped size; below it the u32 doubling cannot wrap.
1585
+ // Stopping at `most` gives the same clamped size; an empty buffer starts there.
1474
1586
  while (size < need && size < most) {
1475
- size = toI32(toU32(size) * toU32(2))
1587
+ size = size > 0 ? tlsSum(size, size) : most
1476
1588
  }
1477
1589
  const grown: u8[] = tlsZeros(size > most ? most : size)
1478
1590
  for (
@@ -1573,12 +1685,13 @@ export class TlsServer {
1573
1685
  return 0
1574
1686
  }
1575
1687
  const type: i32 = toI32(this.input[0])
1576
- const length: i32 = (toI32(this.input[1]) << 16) | (toI32(this.input[2]) << 8) | toI32(this.input[3])
1688
+ // Three bytes, 0 to 2^24 - 1; the mask is the bound the proof reads.
1689
+ const length: i32 =
1690
+ ((toI32(this.input[1]) << 16) | (toI32(this.input[2]) << 8) | toI32(this.input[3])) & 0xffffff
1577
1691
  if (length > TLS_MAX_HANDSHAKE_MESSAGE) {
1578
1692
  return this.fail(TLS_ALERT_DECODE_ERROR)
1579
1693
  }
1580
- // Three bytes, so 0 to 2^24 - 1: the u32 sum cannot wrap.
1581
- const whole: i32 = toI32(toU32(4) + toU32(length))
1694
+ const whole: i32 = 4 + length
1582
1695
  if (this.inputLength < whole) {
1583
1696
  return 0
1584
1697
  }
@@ -1623,8 +1736,8 @@ export class TlsServer {
1623
1736
  if (tlsSuiteHashLength(suite) > 0) {
1624
1737
  return suite
1625
1738
  }
1626
- // Both below 2^31, so the u32 sum cannot wrap; past i32 it ends the loop.
1627
- k = toI32(toU32(k) + toU32(2))
1739
+ // `k` is below the data's length less one, so the sum is in range.
1740
+ k = k + 2
1628
1741
  }
1629
1742
  return 0
1630
1743
  }
@@ -1653,12 +1766,12 @@ export class TlsServer {
1653
1766
  let at: i32 = hello.alpnAt
1654
1767
  while (toI64(at) < end && at >= 0 && at < toI32(data.length)) {
1655
1768
  const n: i32 = toI32(data[at])
1656
- // `at` is inside `data` and `n` a byte, so the u32 sums cannot wrap.
1657
- if (tlsBytesSpell(data, toI32(toU32(at) + toU32(1)), n, protocol)) {
1769
+ // `at` is inside `data` and `n` a byte.
1770
+ if (tlsBytesSpell(data, at + 1, n, protocol)) {
1658
1771
  this.alpn = protocol
1659
1772
  return 0
1660
1773
  }
1661
- at = toI32(toU32(at) + toU32(1) + toU32(n))
1774
+ at = tlsSum(tlsSum(at, 1), n)
1662
1775
  }
1663
1776
  }
1664
1777
  return TLS_ALERT_NO_APPLICATION_PROTOCOL
@@ -1768,8 +1881,8 @@ export class TlsServer {
1768
1881
  // difference is the i32 it always was.
1769
1882
  this.transcript.update(data, prefix, toI32(toI64(4) + toI64(length) - toI64(prefix)))
1770
1883
  } else {
1771
- // Three bytes, so the u32 sum cannot wrap.
1772
- this.transcript.update(data, TLS_FROM, toI32(toU32(4) + toU32(length)))
1884
+ // `length` is three bytes and inside the message.
1885
+ this.transcript.update(data, TLS_FROM, tlsSum(4, length))
1773
1886
  }
1774
1887
  // The group is the server's choice, not the client's: x25519 whenever the
1775
1888
  // client lists it, secp256r1 only for a client that does not. A hello
@@ -1996,11 +2109,12 @@ export class TlsServer {
1996
2109
  using _scope = arena()
1997
2110
  const psk: u8[] = expose(pool.psk, tlsHeldClone)
1998
2111
  const early: u8[] = tlsZeros(h)
1999
- tlsPskEarlySecretInto(this.kdf, h, psk, early)
2112
+ const extracted: boolean = tlsPskEarlySecretInto(this.kdf, h, psk, early)
2000
2113
  secureZero(psk)
2001
2114
  exposeWith(pool.early, early, tlsHeldCopyIn)
2002
2115
  const binderKey: u8[] = tlsZeros(h)
2003
- tlsBinderKeyInto(this.kdf, h, early, binderKey)
2116
+ // A derivation that answers `false` fails the binder, so the hello is `decrypt_error` (row 9).
2117
+ const keyed: boolean = extracted && tlsBinderKeyInto(this.kdf, h, early, binderKey)
2004
2118
  secureZero(early)
2005
2119
  exposeWith(pool.binderKey, binderKey, tlsHeldCopyIn)
2006
2120
  const verified: boolean = tlsBinderVerify(
@@ -2016,7 +2130,7 @@ export class TlsServer {
2016
2130
  secureZero(binderKey)
2017
2131
  pool.zero(TLS_SECRET_PSK)
2018
2132
  pool.zero(TLS_SECRET_BINDER_KEY)
2019
- return verified
2133
+ return keyed && verified
2020
2134
  }
2021
2135
 
2022
2136
  /** The salt a resumed handshake secret is extracted under, `Derive-Secret(early, "derived", "")`, into `salt`. */
@@ -2024,7 +2138,9 @@ export class TlsServer {
2024
2138
  const pool: TlsSecretPool = this.secrets()
2025
2139
  using _scope = arena()
2026
2140
  const early: u8[] = expose(pool.early, tlsHeldClone)
2027
- tlsHandshakeSaltInto(this.kdf, this.hashLength, early, this.salt)
2141
+ if (!tlsHandshakeSaltInto(this.kdf, this.hashLength, early, this.salt)) {
2142
+ this.transcript.refuse()
2143
+ }
2028
2144
  secureZero(early)
2029
2145
  }
2030
2146
 
@@ -2113,8 +2229,8 @@ export class TlsServer {
2113
2229
  this.config.quic ? this.config.quicTransportParameters : null,
2114
2230
  this.ownRecordSizeLimit()
2115
2231
  )
2116
- // A message's end inside the output and a hash length: the u32 sum cannot wrap.
2117
- this.reserveOutput(TLS_LEVEL_HANDSHAKE, toI32(toU32(extensionsEnd) + toU32(4) + toU32(this.hashLength)))
2232
+ // A message's end inside the output and a hash length.
2233
+ this.reserveOutput(TLS_LEVEL_HANDSHAKE, tlsSum(tlsSum(extensionsEnd, 4), this.hashLength))
2118
2234
  // The secrets' pool is the slot's, chosen before the blocks open.
2119
2235
  const pool: TlsSecretPool = this.secrets()
2120
2236
  this.writeResumedHello(pool, index)
@@ -2312,7 +2428,9 @@ export class TlsServer {
2312
2428
  */
2313
2429
  private deriveInto(prk: u8[], label: string, dst: Secret<u8[]>): void {
2314
2430
  const out: u8[] = tlsZeros(this.hashLength)
2315
- tlsDeriveSecretInto(this.kdf, this.hashLength, prk, label, this.hashes, TLS_FROM, out)
2431
+ if (!tlsDeriveSecretInto(this.kdf, this.hashLength, prk, label, this.hashes, TLS_FROM, out)) {
2432
+ this.transcript.refuse()
2433
+ }
2316
2434
  exposeWith(dst, out, tlsHeldCopyIn)
2317
2435
  secureZero(out)
2318
2436
  }
@@ -2351,10 +2469,11 @@ export class TlsServer {
2351
2469
  return this.fail(TLS_ALERT_INTERNAL_ERROR)
2352
2470
  }
2353
2471
  const h: i32 = this.hashLength
2354
- // A length inside the output, at most 65535 and a hash length: the u32 sum cannot wrap.
2472
+ // A length inside the output, the two headers (8 and 4 bytes), at most
2473
+ // 65535 and a hash length.
2355
2474
  this.reserveOutput(
2356
2475
  TLS_LEVEL_HANDSHAKE,
2357
- toI32(toU32(this.outputHandshakeLength) + toU32(8) + toU32(signatureLength) + toU32(4) + toU32(h))
2476
+ tlsSum(tlsSum(this.outputHandshakeLength, 12), tlsSum(signatureLength, h))
2358
2477
  )
2359
2478
  // The secrets' pool is the slot's, chosen before the blocks open.
2360
2479
  const pool: TlsSecretPool = this.secrets()
@@ -2387,11 +2506,23 @@ export class TlsServer {
2387
2506
  const h: i32 = this.hashLength
2388
2507
  using _scope = arena()
2389
2508
  const at: i32 = this.outputHandshakeLength
2390
- // Where the body starts: `at` is inside the output, so the u32 sum cannot wrap.
2391
- const body: i32 = toI32(toU32(at) + toU32(4))
2509
+ // Where the body starts: `at` is inside the output.
2510
+ const body: i32 = tlsSum(at, 4)
2392
2511
  this.transcript.hashInto(this.hashes, TLS_FROM)
2393
2512
  const serverHandshake: u8[] = expose(pool.serverHandshake, tlsHeldClone)
2394
- tlsFinishedVerifyDataInto(this.kdf, h, serverHandshake, this.hashes, TLS_FROM, this.outputHandshake, body)
2513
+ if (
2514
+ !tlsFinishedVerifyDataInto(
2515
+ this.kdf,
2516
+ h,
2517
+ serverHandshake,
2518
+ this.hashes,
2519
+ TLS_FROM,
2520
+ this.outputHandshake,
2521
+ body
2522
+ )
2523
+ ) {
2524
+ this.transcript.refuse()
2525
+ }
2395
2526
  secureZero(serverHandshake)
2396
2527
  const finishedEnd: i32 = tlsWriteFinished(this.outputHandshake, at, this.outputHandshake, body, h)
2397
2528
  this.sent(TLS_LEVEL_HANDSHAKE, at, finishedEnd)
@@ -2409,20 +2540,24 @@ export class TlsServer {
2409
2540
  this.transcript.hashInto(this.hashes, TLS_FROM)
2410
2541
  const handshake: u8[] = expose(pool.handshake, tlsHeldClone)
2411
2542
  const master: u8[] = tlsZeros(h)
2412
- tlsMasterSecretInto(this.kdf, h, handshake, master)
2543
+ if (!tlsMasterSecretInto(this.kdf, h, handshake, master)) {
2544
+ this.transcript.refuse()
2545
+ }
2413
2546
  secureZero(handshake)
2414
2547
  this.deriveInto(master, "c ap traffic", pool.clientApplication)
2415
2548
  this.deriveInto(master, "s ap traffic", pool.serverApplication)
2416
2549
  this.deriveInto(master, "exp master", pool.exporter)
2417
2550
  const clientHandshake: u8[] = expose(pool.clientHandshake, tlsHeldClone)
2418
2551
  const finished: u8[] = pool.clientFinished
2419
- tlsFinishedVerifyDataInto(this.kdf, h, clientHandshake, this.hashes, TLS_FROM, finished, TLS_FROM)
2552
+ if (!tlsFinishedVerifyDataInto(this.kdf, h, clientHandshake, this.hashes, TLS_FROM, finished, TLS_FROM)) {
2553
+ this.transcript.refuse()
2554
+ }
2420
2555
  secureZero(clientHandshake)
2421
2556
  // The only client Finished `handleFinished` accepts is the one just
2422
2557
  // computed, so the transcript through it is known now (RFC 8446 §4.6.1),
2423
2558
  // and the resumption master secret is derived while the master secret is.
2424
- // A hash length and its header: the u32 sum cannot wrap.
2425
- const clientFinished: u8[] = tlsZeros(toI32(toU32(4) + toU32(h)))
2559
+ // A hash length and its header.
2560
+ const clientFinished: u8[] = tlsZeros(tlsSum(4, h))
2426
2561
  tlsWriteFinished(clientFinished, TLS_FROM, finished, TLS_FROM, h)
2427
2562
  this.transcript.update(clientFinished, TLS_FROM, toI32(clientFinished.length))
2428
2563
  this.transcript.hashInto(this.hashes, TLS_FROM)
@@ -2466,12 +2601,12 @@ export class TlsServer {
2466
2601
  return written
2467
2602
  }
2468
2603
 
2469
- /** The resumption PSK for nonce `ticketNonce`, into `issuing.psk` (§4.6.1). */
2470
- private resumptionPsk(): void {
2604
+ /** The resumption PSK for nonce `ticketNonce`, into `issuing.psk` (§4.6.1), and whether it was derived. */
2605
+ private resumptionPsk(): boolean {
2471
2606
  const pool: TlsSecretPool = this.secrets()
2472
2607
  using _scope = arena()
2473
2608
  const resumption: u8[] = expose(pool.resumption, tlsHeldClone)
2474
- tlsResumptionPskInto(
2609
+ const derived: boolean = tlsResumptionPskInto(
2475
2610
  this.kdf,
2476
2611
  this.hashLength,
2477
2612
  resumption,
@@ -2481,6 +2616,7 @@ export class TlsServer {
2481
2616
  this.issuing.psk
2482
2617
  )
2483
2618
  secureZero(resumption)
2619
+ return derived
2484
2620
  }
2485
2621
 
2486
2622
  /** `issue`'s ticket: sealed into `ticketScratch`, its PSK zeroed, and the NewSessionTicket written. */
@@ -2492,7 +2628,10 @@ export class TlsServer {
2492
2628
  if (!this.resumed) {
2493
2629
  issuing.chainStart = now
2494
2630
  }
2495
- this.resumptionPsk()
2631
+ if (!this.resumptionPsk()) {
2632
+ secureZero(issuing.psk)
2633
+ return false
2634
+ }
2496
2635
  const length: i32 = tlsTicketSeal(key, info, issuing, now, this.ticketScratch)
2497
2636
  secureZero(issuing.psk)
2498
2637
  if (length === 0) {
@@ -2535,6 +2674,11 @@ export class TlsServer {
2535
2674
  if (length !== this.hashLength) {
2536
2675
  return TLS_ALERT_DECODE_ERROR
2537
2676
  }
2677
+ // A transcript window refused on the way here left a hash that covers
2678
+ // less than the handshake: no connection is made on it.
2679
+ if (this.transcript.refused()) {
2680
+ return TLS_ALERT_INTERNAL_ERROR
2681
+ }
2538
2682
  const pool: TlsSecretPool = this.secrets()
2539
2683
  if (!timingSafeEqualAt(this.input, 4, pool.clientFinished, TLS_FROM, this.hashLength)) {
2540
2684
  return TLS_ALERT_DECRYPT_ERROR
@@ -2551,9 +2695,9 @@ export class TlsServer {
2551
2695
  * level's buffer, goes into the transcript and stays on the output.
2552
2696
  */
2553
2697
  private sent(level: i32, at: i32, end: i32): void {
2554
- // Both are offsets inside the buffer, `end` past `at`: the u32 difference
2555
- // is the i32 one, and cannot wrap.
2556
- const length: i32 = toI32(toU32(end) - toU32(at))
2698
+ // Both are offsets inside the buffer, `end` past `at`; anything else
2699
+ // records nothing.
2700
+ const length: i32 = at >= 0 && end >= 0 && end >= at ? end - at : 0
2557
2701
  if (level === TLS_LEVEL_INITIAL) {
2558
2702
  this.transcript.update(this.outputInitial, at, length)
2559
2703
  this.outputInitialLength = end