@amritk/nish-x86_64-linux 0.44.0 → 0.46.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 (119) hide show
  1. package/INSTALL.md +3 -1
  2. package/bin/nish +0 -0
  3. package/docs/AI.md +18 -16
  4. package/package.json +1 -1
  5. package/runtime/core/numbers.mjs +3 -1
  6. package/runtime/core/strings.mjs +90 -38
  7. package/runtime/core.d.ts +8 -0
  8. package/runtime/core.mjs +16 -0
  9. package/runtime/nish.d.ts +88 -5
  10. package/runtime/nish.h +10 -0
  11. package/runtime/nish.mjs +5 -0
  12. package/runtime/runtime-host.c +15 -0
  13. package/runtime/runtime-net.c +223 -4
  14. package/runtime/runtime-os.c +15 -1
  15. package/runtime/runtime-uring.c +291 -31
  16. package/runtime/sqlite/nish-sqlite.c +301 -128
  17. package/std/README.md +15 -15
  18. package/std/array.ts +10 -2
  19. package/std/bytes.ts +239 -26
  20. package/std/cli-args.ts +1072 -606
  21. package/std/cli-flags.ts +180 -98
  22. package/std/cli.ts +21 -13
  23. package/std/collections.ts +245 -127
  24. package/std/compress/checksum.ts +32 -37
  25. package/std/compress/deflate.ts +1102 -542
  26. package/std/compress/gzip.ts +290 -145
  27. package/std/compress/zlib.ts +57 -21
  28. package/std/crypto/aes.ts +153 -75
  29. package/std/crypto/base64url.ts +84 -61
  30. package/std/crypto/bcrypt-batch.ts +164 -90
  31. package/std/crypto/bcrypt.ts +185 -107
  32. package/std/crypto/chacha20poly1305.ts +84 -68
  33. package/std/crypto/ct.ts +9 -7
  34. package/std/crypto/ed25519.ts +64 -27
  35. package/std/crypto/hkdf.ts +105 -63
  36. package/std/crypto/hmac.ts +95 -89
  37. package/std/crypto/jwt.ts +248 -126
  38. package/std/crypto/p256.ts +758 -444
  39. package/std/crypto/p384.ts +20 -13
  40. package/std/crypto/pki-roots.ts +95 -38
  41. package/std/crypto/pki.ts +164 -60
  42. package/std/crypto/rsa.ts +266 -223
  43. package/std/crypto/scram.ts +3 -4
  44. package/std/crypto/sha1.ts +107 -65
  45. package/std/crypto/sha256.ts +502 -422
  46. package/std/crypto/sha512.ts +204 -135
  47. package/std/crypto/x509-random.ts +9 -3
  48. package/std/crypto/x509.ts +331 -171
  49. package/std/json-equal.ts +35 -19
  50. package/std/json-format.ts +215 -108
  51. package/std/json-number.ts +126 -72
  52. package/std/json-pointer.ts +42 -13
  53. package/std/json-tokenizer.ts +498 -307
  54. package/std/json-typed.ts +115 -36
  55. package/std/json-value.ts +341 -152
  56. package/std/json.ts +300 -158
  57. package/std/net/buffer-pool.ts +17 -7
  58. package/std/net/dns-config.ts +427 -236
  59. package/std/net/dns-message.ts +114 -47
  60. package/std/net/dns-resolver.ts +736 -237
  61. package/std/net/dns.ts +205 -52
  62. package/std/net/fetch.ts +320 -184
  63. package/std/net/grpc.ts +948 -0
  64. package/std/net/handler.ts +1315 -222
  65. package/std/net/hpack.ts +395 -180
  66. package/std/net/http-compress.ts +502 -65
  67. package/std/net/http-fields.ts +85 -49
  68. package/std/net/http-server.ts +1764 -602
  69. package/std/net/http1-client-codec.ts +372 -161
  70. package/std/net/http1-codec.ts +665 -331
  71. package/std/net/http1-server.ts +660 -278
  72. package/std/net/http2-cleartext.ts +165 -95
  73. package/std/net/http2-frame.ts +232 -89
  74. package/std/net/http2-tls.ts +42 -12
  75. package/std/net/http2.ts +327 -101
  76. package/std/net/http3-frame.ts +68 -33
  77. package/std/net/http3-server.ts +647 -192
  78. package/std/net/http3.ts +667 -189
  79. package/std/net/oidc.ts +63 -24
  80. package/std/net/outbound.ts +207 -142
  81. package/std/net/postgres-async.ts +1165 -443
  82. package/std/net/postgres-carrier.ts +575 -372
  83. package/std/net/postgres.ts +1459 -559
  84. package/std/net/prefork.ts +254 -98
  85. package/std/net/protobuf.ts +1017 -0
  86. package/std/net/qpack.ts +143 -92
  87. package/std/net/quic-conn-ack.ts +50 -18
  88. package/std/net/quic-conn-cid.ts +66 -26
  89. package/std/net/quic-conn-params.ts +13 -7
  90. package/std/net/quic-datagram.ts +90 -27
  91. package/std/net/quic-frame.ts +225 -124
  92. package/std/net/quic-listener.ts +197 -89
  93. package/std/net/quic-packet.ts +289 -163
  94. package/std/net/quic-recovery.ts +279 -128
  95. package/std/net/quic-stream.ts +466 -167
  96. package/std/net/quic.ts +568 -257
  97. package/std/net/router.ts +450 -99
  98. package/std/net/serve.ts +651 -232
  99. package/std/net/static.ts +1458 -0
  100. package/std/net/tls/client.ts +140 -45
  101. package/std/net/tls/codec.ts +510 -260
  102. package/std/net/tls/record-client.ts +268 -76
  103. package/std/net/tls/record-server.ts +236 -79
  104. package/std/net/tls/record.ts +173 -47
  105. package/std/net/tls/schedule.ts +58 -39
  106. package/std/net/tls/ticket.ts +295 -103
  107. package/std/net/tls/verify.ts +1 -1
  108. package/std/net/tls-tcp.ts +218 -75
  109. package/std/net/tls.ts +260 -152
  110. package/std/net/upstream.ts +283 -86
  111. package/std/net/url.ts +277 -102
  112. package/std/net/websocket.ts +370 -186
  113. package/std/net/webtransport.ts +755 -436
  114. package/std/regex.ts +1659 -829
  115. package/std/sqlite.ts +171 -0
  116. package/std/sync/ring.ts +320 -156
  117. package/std/sync/shm.ts +53 -6
  118. package/std/text.ts +205 -124
  119. package/std/threads.ts +22 -2
@@ -243,11 +243,26 @@ const tlsReadVector = (r: TlsReader, width: i32, min: i32, max: i32): i32 => {
243
243
  for (let k: i32 = 0; k < width; k++) {
244
244
  n = (n << 8) | tlsReadU8(r)
245
245
  }
246
- if (r.failed || n < min || n > max || n > r.end - r.at) {
246
+ const at: i32 = r.at
247
+ const end: i32 = r.end
248
+ // A width of at most 3 bytes reads at most 2^24 - 1, and a position is
249
+ // never past `data.length`: the bounds refuse only a reader no caller opens.
250
+ if (
251
+ r.failed ||
252
+ n < min ||
253
+ n > max ||
254
+ n < 0 ||
255
+ n > 16777215 ||
256
+ at < 0 ||
257
+ at > 1073741823 ||
258
+ end < 0 ||
259
+ end < at ||
260
+ n > end - at
261
+ ) {
247
262
  r.failed = true
248
- return r.at
263
+ return at
249
264
  }
250
- return r.at + n
265
+ return at + n
251
266
  }
252
267
 
253
268
  /**
@@ -263,6 +278,42 @@ const tlsReadList = (r: TlsReader, listEnd: i32): i32 => {
263
278
  return outer
264
279
  }
265
280
 
281
+ /**
282
+ * How many bytes lie from the reader's position to `to`, an end a vector
283
+ * read of this reader answered. A `to` before the position, which no such
284
+ * end is, fails the reader and answers 0.
285
+ */
286
+ const tlsReadSpan = (r: TlsReader, to: i32): i32 => {
287
+ const at: i32 = r.at
288
+ if (at < 0 || to < 0 || to < at) {
289
+ r.failed = true
290
+ return 0
291
+ }
292
+ return to - at
293
+ }
294
+
295
+ /**
296
+ * The reader's position plus `n`, unchecked against the window, which
297
+ * `tlsReadSkipTo` and the vector reads check. A position past 2^30 - 1,
298
+ * which no buffer this module reads reaches, fails the reader and answers
299
+ * the position.
300
+ */
301
+ const tlsReadAhead = (r: TlsReader, n: i32): i32 => {
302
+ const at: i32 = r.at
303
+ if (at < 0 || at > 1073741823 || n < 0 || n > 1073741823) {
304
+ r.failed = true
305
+ return at
306
+ }
307
+ return at + n
308
+ }
309
+
310
+ /**
311
+ * The length of the window `from .. to` a 16-bit vector read opened at
312
+ * `from` and answered `to` for: 0 when the read failed and left `to` before
313
+ * `from`, which the failed reader reports.
314
+ */
315
+ const tlsWindowLength = (from: i32, to: i32): i32 => (from < 0 || to < 0 || to < from ? 0 : to - from)
316
+
266
317
  /** Moves to `to`, the end of a vector this reader opened. */
267
318
  const tlsReadSkipTo = (r: TlsReader, to: i32): void => {
268
319
  if (to < r.at || to > r.end) {
@@ -542,7 +593,7 @@ const tlsHelloRefuse = (hello: TlsClientHelloView, alert: i32): void => {
542
593
  */
543
594
  const tlsReadU16Vector = (r: TlsReader, width: i32, min: i32, max: i32): i32 => {
544
595
  const end: i32 = tlsReadVector(r, width, min, max)
545
- if ((end - r.at) % 2 !== 0) {
596
+ if (tlsReadSpan(r, end) % 2 !== 0) {
546
597
  r.failed = true
547
598
  return r.at
548
599
  }
@@ -572,11 +623,8 @@ export const tlsListHas = (list: i32[], value: i32): boolean => list.indexOf(val
572
623
  * @returns true when one of the window's values is `value`.
573
624
  */
574
625
  export const tlsWindowHasU16 = (data: u8[], at: i32, length: i32, value: i32): boolean => {
575
- for (
576
- let k: i32 = at;
577
- k + 1 < at + length && k >= 0 && k < toI32(data.length) && k + 1 < toI32(data.length);
578
- k += 2
579
- ) {
626
+ const end: i64 = toI64(at) + toI64(length)
627
+ for (let k: i32 = at; k >= 0 && k < toI32(data.length) - 1 && toI64(k) + 1 < end; k += 2) {
580
628
  if (((toI32(data[k]) << 8) | toI32(data[k + 1])) === value) {
581
629
  return true
582
630
  }
@@ -604,7 +652,7 @@ const tlsReadServerName = (r: TlsReader, hello: TlsClientHelloView): void => {
604
652
  }
605
653
  hello.hasServerName = true
606
654
  hello.serverNameAt = r.at
607
- hello.serverNameLength = nameEnd - r.at
655
+ hello.serverNameLength = tlsReadSpan(r, nameEnd)
608
656
  while (!r.failed && r.at < nameEnd) {
609
657
  const c: i32 = tlsReadU8(r)
610
658
  if (c < 0x21 || c > 0x7e) {
@@ -627,7 +675,7 @@ const tlsReadKeyShare = (r: TlsReader, hello: TlsClientHelloView): void => {
627
675
  hello.hasKeyShare = true
628
676
  const listEnd: i32 = tlsReadVector(r, 2, 0, 65535)
629
677
  hello.sharesAt = r.at
630
- hello.sharesLength = listEnd - r.at
678
+ hello.sharesLength = tlsReadSpan(r, listEnd)
631
679
  // The list's own end bounds every entry in it (see `tlsReadList`).
632
680
  const outerEnd: i32 = tlsReadList(r, listEnd)
633
681
  while (!r.failed && r.at < listEnd) {
@@ -639,12 +687,12 @@ const tlsReadKeyShare = (r: TlsReader, hello: TlsClientHelloView): void => {
639
687
  if (group === TLS_GROUP_X25519 && !r.failed) {
640
688
  hello.hasX25519Share = true
641
689
  hello.x25519ShareAt = r.at
642
- hello.x25519ShareLength = shareEnd - r.at
690
+ hello.x25519ShareLength = tlsReadSpan(r, shareEnd)
643
691
  }
644
692
  if (group === TLS_GROUP_SECP256R1 && !r.failed) {
645
693
  hello.hasP256Share = true
646
694
  hello.p256ShareAt = r.at
647
- hello.p256ShareLength = shareEnd - r.at
695
+ hello.p256ShareLength = tlsReadSpan(r, shareEnd)
648
696
  }
649
697
  tlsReadSkipTo(r, shareEnd)
650
698
  }
@@ -656,7 +704,7 @@ const tlsReadAlpn = (r: TlsReader, hello: TlsClientHelloView): void => {
656
704
  hello.hasAlpn = true
657
705
  const listEnd: i32 = tlsReadVector(r, 2, 2, 65535)
658
706
  hello.alpnAt = r.at
659
- hello.alpnLength = listEnd - r.at
707
+ hello.alpnLength = tlsReadSpan(r, listEnd)
660
708
  // The list's own end bounds every entry in it (see `tlsReadList`).
661
709
  const outerEnd: i32 = tlsReadList(r, listEnd)
662
710
  while (!r.failed && r.at < listEnd) {
@@ -678,31 +726,37 @@ const tlsReadPreSharedKey = (r: TlsReader, hello: TlsClientHelloView): void => {
678
726
  hello.hasPreSharedKey = true
679
727
  const identitiesEnd: i32 = tlsReadVector(r, 2, 7, 65535)
680
728
  hello.pskIdentitiesAt = r.at
681
- hello.pskIdentitiesLength = identitiesEnd - r.at
729
+ hello.pskIdentitiesLength = tlsReadSpan(r, identitiesEnd)
682
730
  // The list's own end bounds every entry in it (see `tlsReadList`).
683
731
  let outerEnd: i32 = tlsReadList(r, identitiesEnd)
684
- while (!r.failed && r.at < identitiesEnd) {
732
+ // Each entry is at least 7 bytes of a list of at most 65535, so the count
733
+ // bound never ends the walk early.
734
+ let identities: i32 = 0
735
+ while (!r.failed && r.at < identitiesEnd && identities < 65535) {
685
736
  const identityEnd: i32 = tlsReadVector(r, 2, 1, 65535)
686
737
  tlsReadSkipTo(r, identityEnd)
687
738
  // obfuscated_ticket_age, which the server reads only for the identity it selects.
688
- tlsReadSkipTo(r, r.at + 4)
739
+ tlsReadSkipTo(r, tlsReadAhead(r, 4))
689
740
  if (!r.failed) {
690
- hello.pskIdentityCount = hello.pskIdentityCount + 1
741
+ identities++
691
742
  }
692
743
  }
744
+ hello.pskIdentityCount = identities
693
745
  r.end = outerEnd
694
746
  hello.pskBindersPrefixAt = r.at
695
747
  const bindersEnd: i32 = tlsReadVector(r, 2, 33, 65535)
696
748
  hello.pskBindersAt = r.at
697
- hello.pskBindersLength = bindersEnd - r.at
749
+ hello.pskBindersLength = tlsReadSpan(r, bindersEnd)
698
750
  outerEnd = tlsReadList(r, bindersEnd)
699
- while (!r.failed && r.at < bindersEnd) {
751
+ let binders: i32 = 0
752
+ while (!r.failed && r.at < bindersEnd && binders < 65535) {
700
753
  const binderEnd: i32 = tlsReadVector(r, 1, 32, 255)
701
754
  tlsReadSkipTo(r, binderEnd)
702
755
  if (!r.failed) {
703
- hello.pskBinderCount = hello.pskBinderCount + 1
756
+ binders++
704
757
  }
705
758
  }
759
+ hello.pskBinderCount = binders
706
760
  r.end = outerEnd
707
761
  }
708
762
 
@@ -715,7 +769,7 @@ const tlsReadPskModes = (r: TlsReader, hello: TlsClientHelloView): void => {
715
769
  hello.hasPskModes = true
716
770
  const modesEnd: i32 = tlsReadVector(r, 1, 1, 255)
717
771
  hello.pskModesAt = r.at
718
- hello.pskModesLength = modesEnd - r.at
772
+ hello.pskModesLength = tlsReadSpan(r, modesEnd)
719
773
  while (!r.failed && r.at < modesEnd) {
720
774
  if (tlsReadU8(r) === TLS_PSK_DHE_KE) {
721
775
  hello.pskDheKe = true
@@ -731,7 +785,7 @@ const tlsReadPskModes = (r: TlsReader, hello: TlsClientHelloView): void => {
731
785
  * `illegal_parameter`; one above the TLS 1.3 maximum is read as that maximum.
732
786
  */
733
787
  const tlsReadRecordSizeLimit = (r: TlsReader, end: i32, hello: TlsClientHelloView): void => {
734
- if (end - r.at !== 2) {
788
+ if (tlsReadSpan(r, end) !== 2) {
735
789
  r.failed = true
736
790
  return
737
791
  }
@@ -751,21 +805,21 @@ const tlsReadExtension = (r: TlsReader, type: i32, end: i32, hello: TlsClientHel
751
805
  break
752
806
  case TLS_EXT_SUPPORTED_GROUPS:
753
807
  hello.hasSupportedGroups = true
754
- hello.groupsAt = r.at + 2
755
- hello.groupsLength = tlsReadU16Vector(r, 2, 2, 65535) - hello.groupsAt
808
+ hello.groupsAt = tlsReadAhead(r, 2)
809
+ hello.groupsLength = tlsWindowLength(hello.groupsAt, tlsReadU16Vector(r, 2, 2, 65535))
756
810
  break
757
811
  case TLS_EXT_SIGNATURE_ALGORITHMS:
758
812
  hello.hasSignatureAlgorithms = true
759
- hello.schemesAt = r.at + 2
760
- hello.schemesLength = tlsReadU16Vector(r, 2, 2, 65534) - hello.schemesAt
813
+ hello.schemesAt = tlsReadAhead(r, 2)
814
+ hello.schemesLength = tlsWindowLength(hello.schemesAt, tlsReadU16Vector(r, 2, 2, 65534))
761
815
  break
762
816
  case TLS_EXT_ALPN:
763
817
  tlsReadAlpn(r, hello)
764
818
  break
765
819
  case TLS_EXT_SUPPORTED_VERSIONS:
766
820
  hello.hasSupportedVersions = true
767
- hello.versionsAt = r.at + 1
768
- hello.versionsLength = tlsReadU16Vector(r, 1, 2, 254) - hello.versionsAt
821
+ hello.versionsAt = tlsReadAhead(r, 1)
822
+ hello.versionsLength = tlsWindowLength(hello.versionsAt, tlsReadU16Vector(r, 1, 2, 254))
769
823
  break
770
824
  case TLS_EXT_KEY_SHARE:
771
825
  tlsReadKeyShare(r, hello)
@@ -779,7 +833,7 @@ const tlsReadExtension = (r: TlsReader, type: i32, end: i32, hello: TlsClientHel
779
833
  case TLS_EXT_QUIC_TRANSPORT_PARAMETERS:
780
834
  hello.hasQuicTransportParameters = true
781
835
  hello.quicAt = r.at
782
- hello.quicLength = end - r.at
836
+ hello.quicLength = tlsReadSpan(r, end)
783
837
  tlsReadSkipTo(r, end)
784
838
  break
785
839
  case TLS_EXT_RECORD_SIZE_LIMIT:
@@ -827,7 +881,8 @@ export const tlsReadClientHello = (hello: TlsClientHelloView, data: u8[], off: i
827
881
  hello.alert = TLS_ALERT_DECODE_ERROR
828
882
  return
829
883
  }
830
- const end: i32 = off + len
884
+ // The guard above keeps the sum inside `data.length`.
885
+ const end: i32 = toI32(toI64(off) + toI64(len))
831
886
  const r: TlsReader = hello.reader
832
887
  r.data = data
833
888
  r.at = off
@@ -835,22 +890,22 @@ export const tlsReadClientHello = (hello: TlsClientHelloView, data: u8[], off: i
835
890
  r.failed = false
836
891
  hello.legacyVersion = tlsReadU16(r)
837
892
  hello.randomAt = r.at
838
- tlsReadSkipTo(r, r.at + TLS_RANDOM_SIZE)
893
+ tlsReadSkipTo(r, tlsReadAhead(r, TLS_RANDOM_SIZE))
839
894
  const sessionEnd: i32 = tlsReadVector(r, 1, 0, 32)
840
895
  hello.sessionIdAt = r.at
841
- hello.sessionIdLength = sessionEnd - r.at
896
+ hello.sessionIdLength = tlsReadSpan(r, sessionEnd)
842
897
  tlsReadSkipTo(r, sessionEnd)
843
- hello.suitesAt = r.at + 2
844
- hello.suitesLength = tlsReadU16Vector(r, 2, 2, 65534) - hello.suitesAt
898
+ hello.suitesAt = tlsReadAhead(r, 2)
899
+ hello.suitesLength = tlsWindowLength(hello.suitesAt, tlsReadU16Vector(r, 2, 2, 65534))
845
900
  const compressionEnd: i32 = tlsReadVector(r, 1, 1, 255)
846
- hello.nullCompressionOnly = compressionEnd - r.at === 1 && tlsReadU8(r) === 0
901
+ hello.nullCompressionOnly = tlsReadSpan(r, compressionEnd) === 1 && tlsReadU8(r) === 0
847
902
  tlsReadSkipTo(r, compressionEnd)
848
903
  // A hello with no extensions block is well formed (§4.1.2 keeps it for
849
904
  // TLS 1.2 and earlier); it offers no TLS 1.3, which the server refuses.
850
905
  if (!r.failed && r.at < end) {
851
906
  const extensionsEnd: i32 = tlsReadVector(r, 2, 0, 65535)
852
907
  hello.extensionsAt = r.at
853
- hello.extensionsLength = extensionsEnd - r.at
908
+ hello.extensionsLength = tlsReadSpan(r, extensionsEnd)
854
909
  // The extensions vector's own end bounds every extension in it: one whose
855
910
  // length runs past it is malformed even when the message's length still
856
911
  // balances.
@@ -912,21 +967,31 @@ export const tlsSelectPskIdentity = (hello: TlsClientHelloView, index: i32): boo
912
967
  return false
913
968
  }
914
969
  const data: u8[] = hello.data
970
+ // A list of at most 65535 bytes holds fewer entries than that.
971
+ if (index > 65535) {
972
+ return false
973
+ }
915
974
  let at: i32 = hello.pskIdentitiesAt
916
- for (let k: i32 = 0; at >= 0 && at + 1 < toI32(data.length); k++) {
917
- const length: i32 = (toI32(data[at]) << 8) | toI32(data[at + 1])
918
- const age: i32 = at + 2 + length
919
- if (age < 0 || age + 3 >= toI32(data.length)) {
975
+ for (let k: i32 = 0; k <= index && at >= 0 && at < toI32(data.length) - 1; k++) {
976
+ const length: i32 = tlsWindowU16(data, at)
977
+ if (length < 0) {
978
+ return false
979
+ }
980
+ // Past 2^31 - 1 the sum wraps negative, which is refused with the rest.
981
+ const age: i32 = toI32(toI64(at) + 2 + toI64(length))
982
+ if (age < 0 || age > toI32(data.length) - 4) {
920
983
  return false
921
984
  }
922
985
  if (k === index) {
923
986
  hello.pskIdentityAt = at + 2
924
987
  hello.pskIdentityLength = length
925
- hello.pskTicketAge =
926
- (toU32(data[age]) << 24) |
927
- (toU32(data[age + 1]) << 16) |
928
- (toU32(data[age + 2]) << 8) |
929
- toU32(data[age + 3])
988
+ const ticketAge: i64 = tlsWindowU32(data, age)
989
+ if (ticketAge < 0 || ticketAge > 4294967295) {
990
+ hello.pskIdentityAt = 0
991
+ hello.pskIdentityLength = 0
992
+ return false
993
+ }
994
+ hello.pskTicketAge = toU32(ticketAge)
930
995
  break
931
996
  }
932
997
  at = age + 4
@@ -937,14 +1002,14 @@ export const tlsSelectPskIdentity = (hello: TlsClientHelloView, index: i32): boo
937
1002
  return false
938
1003
  }
939
1004
  at = hello.pskBindersAt
940
- for (let k: i32 = 0; at >= 0 && at < toI32(data.length); k++) {
1005
+ for (let k: i32 = 0; k <= index && at >= 0 && at < toI32(data.length); k++) {
941
1006
  const length: i32 = toI32(data[at])
942
1007
  if (k === index) {
943
1008
  hello.pskBinderAt = at + 1
944
1009
  hello.pskBinderLength = length
945
1010
  return true
946
1011
  }
947
- at = at + 1 + length
1012
+ at = toI32(toI64(at) + 1 + toI64(length))
948
1013
  }
949
1014
  return false
950
1015
  }
@@ -1049,6 +1114,31 @@ export class TlsClientHello {
1049
1114
  }
1050
1115
  }
1051
1116
 
1117
+ /**
1118
+ * The big-endian 16-bit value at `data[at]`, `data[at + 1]`, or -1 when
1119
+ * those bytes do not both lie inside `data`.
1120
+ */
1121
+ const tlsWindowU16 = (data: u8[], at: i32): i32 => toI32(tlsWindowUint(data, at, 2))
1122
+
1123
+ /** The big-endian 32-bit value at `data[at .. at + 4)`, or -1 when those bytes do not all lie inside `data`. */
1124
+ const tlsWindowU32 = (data: u8[], at: i32): i64 => tlsWindowUint(data, at, 4)
1125
+
1126
+ /**
1127
+ * The big-endian value of the `width` bytes (1 to 4) from `data[at]`, or -1
1128
+ * when they do not all lie inside `data`: every caller has checked the window,
1129
+ * and the -1 refuses rather than read a shorter value.
1130
+ */
1131
+ const tlsWindowUint = (data: u8[], at: i32, width: i32): i64 => {
1132
+ if (at < 0 || width < 1 || width > 4 || at > toI32(data.length) - width) {
1133
+ return -1
1134
+ }
1135
+ let v: i64 = 0
1136
+ for (let j: i32 = at; j < toI32(data.length) && j - at < width; j++) {
1137
+ v = (v << 8) | toI64(data[j])
1138
+ }
1139
+ return v
1140
+ }
1141
+
1052
1142
  /**
1053
1143
  * A copy of `data[at .. at + length)`, which is how a window of a view becomes
1054
1144
  * an array of its own that outlives the buffer it was read from.
@@ -1056,24 +1146,34 @@ export class TlsClientHello {
1056
1146
  * @param data The buffer the window points into.
1057
1147
  * @param at Where the window starts in `data`, in bytes.
1058
1148
  * @param length How many bytes to copy; a negative one copies none.
1059
- * @returns A fresh array of `length` bytes; nothing from outside `data` is copied into it.
1149
+ * @returns A fresh array of the window's bytes; it stops where `data` ends, so it is
1150
+ * shorter than `length` when the window runs past the buffer. Callers in
1151
+ * `std/net/tls` pass a window a parsed view validated, or check the copy's length
1152
+ * (`tlsHeldWindow` in `schedule.ts`).
1060
1153
  */
1061
1154
  export const tlsCopyWindow = (data: u8[], at: i32, length: i32): u8[] => {
1062
- const out: u8[] = new Array<u8>(length < 0 ? TLS_CODEC_FROM : length)
1063
- for (let k: i32 = 0; k < toI32(out.length) && at + k >= 0 && at + k < toI32(data.length); k++) {
1064
- out[k] = data[at + k]
1155
+ const out: u8[] = []
1156
+ for (let k: i32 = 0; k < length; k++) {
1157
+ // Past 2^31 - 1 the sum wraps negative, which ends the copy as the buffer's end does.
1158
+ const j: i32 = toI32(toI64(at) + toI64(k))
1159
+ if (j < 0 || j >= toI32(data.length)) {
1160
+ break
1161
+ }
1162
+ out.push(data[j])
1065
1163
  }
1066
1164
  return out
1067
1165
  }
1068
1166
 
1069
- /** The 16-bit values of `data[at .. at + length)`, in a fresh list. */
1167
+ /**
1168
+ * The 16-bit values of `data[at .. at + length)`, in a fresh list. Every caller
1169
+ * validates the window first; the walk's own stop is a backstop.
1170
+ */
1070
1171
  const tlsCopyU16Window = (data: u8[], at: i32, length: i32): i32[] => {
1071
1172
  const out: i32[] = []
1072
- for (
1073
- let k: i32 = at;
1074
- k + 1 < at + length && k >= 0 && k < toI32(data.length) && k + 1 < toI32(data.length);
1075
- k += 2
1076
- ) {
1173
+ const end: i64 = toI64(at) + toI64(length)
1174
+ // The step is widened because the `push` forgets the bound on `k`; a sum
1175
+ // past 2^31 - 1 wraps negative and ends the walk.
1176
+ for (let k: i32 = at; k >= 0 && k < toI32(data.length) - 1 && toI64(k) + 1 < end; k = toI32(toI64(k) + 2)) {
1077
1177
  out.push((toI32(data[k]) << 8) | toI32(data[k + 1]))
1078
1178
  }
1079
1179
  return out
@@ -1086,11 +1186,13 @@ const tlsCopyU16Window = (data: u8[], at: i32, length: i32): i32[] => {
1086
1186
  * @param data The buffer the window points into.
1087
1187
  * @param at Where the window starts in `data`, in bytes.
1088
1188
  * @param length How many bytes the window holds; any part outside `data` is left out.
1089
- * @returns A fresh string, one character for each byte read.
1189
+ * @returns A fresh string, one character for each byte read. Every caller in
1190
+ * `std/net/tls` validates the window first, so no byte is left out there.
1090
1191
  */
1091
1192
  export const tlsWindowString = (data: u8[], at: i32, length: i32): string => {
1092
1193
  const parts: string[] = []
1093
- for (let k: i32 = at; k < at + length && k >= 0 && k < toI32(data.length); k++) {
1194
+ const end: i64 = toI64(at) + toI64(length)
1195
+ for (let k: i32 = at; toI64(k) < end && k >= 0 && k < toI32(data.length); k++) {
1094
1196
  parts.push(String.fromCharCode(toI32(data[k])))
1095
1197
  }
1096
1198
  return parts.join("")
@@ -1125,39 +1227,42 @@ export const tlsParseClientHello = (data: u8[], off: i32, len: i32): TlsClientHe
1125
1227
  hello.serverName = tlsWindowString(data, view.serverNameAt, view.serverNameLength)
1126
1228
  hello.quicTransportParameters = tlsCopyWindow(data, view.quicAt, view.quicLength)
1127
1229
  // The key shares, ALPN names and extension types, walked again; the read
1128
- // above has checked every length these loops follow.
1230
+ // above has checked every length these loops follow. Positions are summed
1231
+ // in 64 bits, and one that wraps past 2^31 - 1 ends its walk.
1129
1232
  let at: i32 = view.sharesAt
1130
- while (
1131
- at + 4 <= view.sharesAt + view.sharesLength &&
1132
- at >= 0 &&
1133
- at < toI32(data.length) &&
1134
- at + 3 < toI32(data.length)
1135
- ) {
1136
- // All four bytes are read before the `push`, which is a call and so
1137
- // forgets what the guard said about `data.length`.
1138
- const group: i32 = (toI32(data[at]) << 8) | toI32(data[at + 1])
1139
- const skip: i32 = (toI32(data[at + 2]) << 8) | toI32(data[at + 3])
1140
- hello.shareGroups.push(group)
1141
- at = at + 4 + skip
1233
+ const sharesEnd: i64 = toI64(view.sharesAt) + toI64(view.sharesLength)
1234
+ while (at >= 0 && at < toI32(data.length) - 3 && toI64(at) + 4 <= sharesEnd) {
1235
+ const skip: i32 = tlsWindowU16(data, toI32(toI64(at) + 2))
1236
+ const entry: i32 = tlsWindowU16(data, at)
1237
+ // The loop's test keeps both inside `data`; were it not to, the copy is
1238
+ // refused rather than left short.
1239
+ if (skip < 0 || entry < 0) {
1240
+ hello.alert = TLS_ALERT_INTERNAL_ERROR
1241
+ return hello
1242
+ }
1243
+ hello.shareGroups.push(entry)
1244
+ at = toI32(toI64(at) + 4 + toI64(skip))
1142
1245
  }
1143
1246
  at = view.alpnAt
1144
- while (at < view.alpnAt + view.alpnLength && at >= 0 && at < toI32(data.length)) {
1247
+ const alpnEnd: i64 = toI64(view.alpnAt) + toI64(view.alpnLength)
1248
+ while (at >= 0 && at < toI32(data.length) && toI64(at) < alpnEnd) {
1145
1249
  const n: i32 = toI32(data[at])
1146
1250
  hello.alpn.push(tlsCopyWindow(data, at + 1, n))
1147
- at = at + 1 + n
1251
+ at = toI32(toI64(at) + 1 + toI64(n))
1148
1252
  }
1149
1253
  at = view.extensionsAt
1150
- while (
1151
- at + 4 <= view.extensionsAt + view.extensionsLength &&
1152
- at >= 0 &&
1153
- at < toI32(data.length) &&
1154
- at + 3 < toI32(data.length)
1155
- ) {
1156
- // Read before the `push`, as in the key-share walk above.
1157
- const kind: i32 = (toI32(data[at]) << 8) | toI32(data[at + 1])
1158
- const skip: i32 = (toI32(data[at + 2]) << 8) | toI32(data[at + 3])
1159
- hello.extensionTypes.push(kind)
1160
- at = at + 4 + skip
1254
+ const extensionsEnd: i64 = toI64(view.extensionsAt) + toI64(view.extensionsLength)
1255
+ while (at >= 0 && at < toI32(data.length) - 3 && toI64(at) + 4 <= extensionsEnd) {
1256
+ const skip: i32 = tlsWindowU16(data, toI32(toI64(at) + 2))
1257
+ const entry: i32 = tlsWindowU16(data, at)
1258
+ // The loop's test keeps both inside `data`; were it not to, the copy is
1259
+ // refused rather than left short.
1260
+ if (skip < 0 || entry < 0) {
1261
+ hello.alert = TLS_ALERT_INTERNAL_ERROR
1262
+ return hello
1263
+ }
1264
+ hello.extensionTypes.push(entry)
1265
+ at = toI32(toI64(at) + 4 + toI64(skip))
1161
1266
  }
1162
1267
  hello.nullCompressionOnly = view.nullCompressionOnly
1163
1268
  hello.hasSupportedVersions = view.hasSupportedVersions
@@ -1174,7 +1279,8 @@ export const tlsParseClientHello = (data: u8[], off: i32, len: i32): TlsClientHe
1174
1279
  hello.pskDheKe = view.pskDheKe
1175
1280
  hello.pskModes = tlsCopyWindow(data, view.pskModesAt, view.pskModesLength)
1176
1281
  if (view.hasPreSharedKey) {
1177
- hello.pskBindersPrefix = view.pskBindersPrefixAt - off
1282
+ // Both are in `[0, data.length]`, the prefix's end past `off`.
1283
+ hello.pskBindersPrefix = toI32(toI64(view.pskBindersPrefixAt) - toI64(off))
1178
1284
  }
1179
1285
  for (let k: i32 = 0; k < view.pskIdentityCount && tlsSelectPskIdentity(view, k); k++) {
1180
1286
  hello.pskIdentities.push(tlsCopyWindow(data, view.pskIdentityAt, view.pskIdentityLength))
@@ -1193,12 +1299,29 @@ export const tlsParseClientHello = (data: u8[], off: i32, len: i32): TlsClientHe
1193
1299
  * write it again, and a server that keeps its output in a buffer of its own
1194
1300
  * makes room first and writes in place. The `tlsPut*` helpers are the same
1195
1301
  * shape: they take the position and answer the next.
1302
+ *
1303
+ * A position is never past 2^30 - 1, far past any TLS message (§4 allows
1304
+ * 2^24 - 1 a body). A step that would pass it, or
1305
+ * that starts from a negative position, answers -1, and every later step
1306
+ * from -1 answers -1 again: so a writer handed a field too long for any
1307
+ * message, or an offset no array reaches, answers -1 and writes nothing past
1308
+ * the failure, and its caller tests the end once.
1196
1309
  */
1310
+ const tlsAdvance = (at: i32, n: i32): i32 => {
1311
+ // 2^30 - 1 each, so the sum stays inside an `i32`.
1312
+ if (at < 0 || at > 1073741823 || n < 0 || n > 1073741823) {
1313
+ return -1
1314
+ }
1315
+ const next: i32 = at + n
1316
+ return next > 1073741823 ? -1 : next
1317
+ }
1318
+
1197
1319
  const tlsPutU8 = (out: u8[], at: i32, v: i32): i32 => {
1198
- if (at >= 0 && at < toI32(out.length)) {
1320
+ const next: i32 = tlsAdvance(at, 1)
1321
+ if (next >= 0 && at >= 0 && at < toI32(out.length)) {
1199
1322
  out[at] = toU8(v & 255)
1200
1323
  }
1201
- return at + 1
1324
+ return next
1202
1325
  }
1203
1326
 
1204
1327
  const tlsPutU16 = (out: u8[], at: i32, v: i32): i32 => tlsPutU8(out, tlsPutU8(out, at, v >> 8), v)
@@ -1208,16 +1331,21 @@ const tlsPutU32 = (out: u8[], at: i32, v: u32): i32 => {
1208
1331
  return tlsPutU16(out, p, toI32(v & 0xffff))
1209
1332
  }
1210
1333
 
1211
- /** `bytes[off .. off + len)`, at `out[at]`. */
1334
+ /** `bytes[off .. off + len)`, at `out[at]`; -1 when `off .. off + len` is not inside `bytes`. */
1212
1335
  const tlsPutWindow = (out: u8[], at: i32, bytes: u8[], off: i32, len: i32): i32 => {
1336
+ const size: i32 = toI32(bytes.length)
1337
+ if (off < 0 || off > size || len < 0 || len > size - off) {
1338
+ return -1
1339
+ }
1340
+ const next: i32 = tlsAdvance(at, len)
1213
1341
  // Measuring over an empty array: nothing would land, so nothing is copied.
1214
- if (toI32(out.length) === 0) {
1215
- return at + len
1342
+ if (next < 0 || toI32(out.length) === 0) {
1343
+ return next
1216
1344
  }
1217
- for (let k: i32 = 0; k < len && off + k >= 0 && off + k < toI32(bytes.length); k++) {
1218
- tlsPutU8(out, at + k, toI32(bytes[off + k]))
1345
+ for (let j: i32 = off; j < size && j - off < len; j++) {
1346
+ tlsPutU8(out, toI32(toI64(at) + toI64(j - off)), toI32(bytes[j]))
1219
1347
  }
1220
- return at + len
1348
+ return next
1221
1349
  }
1222
1350
 
1223
1351
  const tlsPutBytes = (out: u8[], at: i32, b: u8[]): i32 =>
@@ -1226,36 +1354,63 @@ const tlsPutBytes = (out: u8[], at: i32, b: u8[]): i32 =>
1226
1354
  /** The bytes of `text`, one a character: ASCII here, an ALPN protocol id. */
1227
1355
  const tlsPutAscii = (out: u8[], at: i32, text: string): i32 => {
1228
1356
  const length: i32 = toI32(text.length)
1357
+ const next: i32 = tlsAdvance(at, length)
1358
+ if (next < 0) {
1359
+ return next
1360
+ }
1229
1361
  for (let k: i32 = 0; k < length; k++) {
1230
- tlsPutU8(out, at + k, toI32(text.charCodeAt(k)))
1362
+ tlsPutU8(out, toI32(toI64(at) + toI64(k)), toI32(text.charCodeAt(k)))
1231
1363
  }
1232
- return at + length
1364
+ return next
1233
1365
  }
1234
1366
 
1235
1367
  /**
1236
1368
  * Writes the `width`-byte length of the vector whose contents run from
1237
1369
  * `start` to `end`, into the `width` bytes before `start` that the caller
1238
- * left for it.
1370
+ * left for it. A failed writer (`end` -1) or a vector longer than `width`
1371
+ * bytes can say answers -1; otherwise `end`.
1239
1372
  */
1240
- const tlsPutLength = (out: u8[], start: i32, end: i32, width: i32): void => {
1373
+ const tlsPutLength = (out: u8[], start: i32, end: i32, width: i32): i32 => {
1374
+ if (
1375
+ start < 3 ||
1376
+ start > 1073741823 ||
1377
+ end < 0 ||
1378
+ end < start ||
1379
+ end > 1073741823 ||
1380
+ width < 1 ||
1381
+ width > 3
1382
+ ) {
1383
+ return -1
1384
+ }
1241
1385
  let n: i32 = end - start
1242
- for (let at: i32 = start - 1; at >= start - width; at--) {
1243
- tlsPutU8(out, at, n)
1386
+ if (n > 16777215 || (width === 1 && n > 255) || (width === 2 && n > 65535)) {
1387
+ return -1
1388
+ }
1389
+ for (let k: i32 = 1; k <= width; k++) {
1390
+ tlsPutU8(out, start - k, n)
1244
1391
  n = n >> 8
1245
1392
  }
1393
+ return end
1246
1394
  }
1247
1395
 
1248
- /** The handshake header (§4): `type`, then a 24-bit length of the body that follows it to `end`. */
1249
- const tlsPutHeader = (out: u8[], at: i32, type: i32, end: i32): void => {
1396
+ /**
1397
+ * The handshake header (§4): `type`, then a 24-bit length of the body that
1398
+ * follows it to `end`. Answers `end`, or -1 for a failed writer or a body
1399
+ * past 2^24 - 1 bytes.
1400
+ */
1401
+ const tlsPutHeader = (out: u8[], at: i32, type: i32, end: i32): i32 => {
1250
1402
  tlsPutU8(out, at, type)
1251
- tlsPutLength(out, at + 4, end, 3)
1403
+ return tlsPutLength(out, tlsAdvance(at, 4), end, 3)
1252
1404
  }
1253
1405
 
1254
1406
  /** The fixed `random` that marks a ServerHello as a HelloRetryRequest: SHA-256 of "HelloRetryRequest" (§4.1.3). */
1255
1407
  const TLS_HELLO_RETRY_RANDOM: string = "cf21ad74e59a6111be1d8c021e65b891c2a211167abb8c5e079e09e2c8a8339c"
1256
1408
 
1257
1409
  /** The value of one lowercase hex digit. */
1258
- const tlsHexNibble = (c: i32): i32 => (c <= 57 ? c - 48 : c - 87)
1410
+ const tlsHexNibble = (c: u8): i32 => {
1411
+ const v: i32 = toI32(c)
1412
+ return v <= 57 ? v - 48 : v - 87
1413
+ }
1259
1414
 
1260
1415
  /**
1261
1416
  * Writes the bytes the lowercase hex constant `text` spells at `out[at]` and
@@ -1265,16 +1420,24 @@ const tlsHexNibble = (c: i32): i32 => (c <= 57 ? c - 48 : c - 87)
1265
1420
  * @param text Lowercase hex digits, two a byte; a last odd digit is ignored, and nothing else is checked.
1266
1421
  * @param out The array to write into; a byte that would land outside it is dropped.
1267
1422
  * @param at Where the first byte goes in `out`.
1268
- * @returns `at` plus the number of bytes `text` spells, written or not.
1423
+ * @returns `at` plus the number of bytes `text` spells, written or not; -1 when `at` is
1424
+ * negative or the end would pass 2^30 - 1.
1269
1425
  */
1270
1426
  export const tlsHexInto = (text: string, out: u8[], at: i32): i32 => {
1271
- const length: i32 = toI32(text.length) >> 1
1272
- for (let k: i32 = 0; k < length; k++) {
1273
- const hi: i32 = tlsHexNibble(toI32(text.charCodeAt(2 * k)))
1274
- const lo: i32 = tlsHexNibble(toI32(text.charCodeAt(2 * k + 1)))
1275
- tlsPutU8(out, at + k, (hi << 4) | lo)
1427
+ const digits: i32 = toI32(text.length)
1428
+ const next: i32 = tlsAdvance(at, digits >> 1)
1429
+ if (next < 0) {
1430
+ return next
1431
+ }
1432
+ // Every odd index closes a byte: the digit before it is the high nibble.
1433
+ for (let i: i32 = 1; i < digits; i++) {
1434
+ if ((i & 1) === 1) {
1435
+ const hi: i32 = tlsHexNibble(toU8(text.charCodeAt(i - 1)))
1436
+ const lo: i32 = tlsHexNibble(toU8(text.charCodeAt(i)))
1437
+ tlsPutU8(out, toI32(toI64(at) + toI64(i >> 1)), (hi << 4) | lo)
1438
+ }
1276
1439
  }
1277
- return at + length
1440
+ return next
1278
1441
  }
1279
1442
 
1280
1443
  /** The `supported_versions` a server hello carries: TLS 1.3 alone (§4.2.1). */
@@ -1298,8 +1461,9 @@ const tlsPutHelloHead = (
1298
1461
  ): i32 => {
1299
1462
  let p: i32 = tlsPutU16(out, at, TLS_LEGACY_VERSION)
1300
1463
  p = retry ? tlsHexInto(TLS_HELLO_RETRY_RANDOM, out, p) : tlsPutBytes(out, p, random)
1301
- p = tlsPutU8(out, p, sessionIdLength)
1302
- p = tlsPutWindow(out, p, sessionId, sessionIdOff, sessionIdLength)
1464
+ const id: i32 = tlsAdvance(p, 1)
1465
+ p = tlsPutWindow(out, id, sessionId, sessionIdOff, sessionIdLength)
1466
+ p = tlsPutLength(out, id, p, 1)
1303
1467
  p = tlsPutU16(out, p, suite)
1304
1468
  return tlsPutU8(out, p, 0)
1305
1469
  }
@@ -1323,24 +1487,32 @@ const tlsPutServerHello = (
1323
1487
  publicKey: u8[],
1324
1488
  selectedIdentity: i32
1325
1489
  ): i32 => {
1326
- let p: i32 = tlsPutHelloHead(out, at + 4, random, false, sessionId, sessionIdOff, sessionIdLength, suite)
1327
- const extensions: i32 = p + 2
1490
+ let p: i32 = tlsPutHelloHead(
1491
+ out,
1492
+ tlsAdvance(at, 4),
1493
+ random,
1494
+ false,
1495
+ sessionId,
1496
+ sessionIdOff,
1497
+ sessionIdLength,
1498
+ suite
1499
+ )
1500
+ const extensions: i32 = tlsAdvance(p, 2)
1328
1501
  p = extensions
1329
1502
  if (selectedIdentity >= 0) {
1330
1503
  p = tlsPutU16(out, tlsPutU16(out, tlsPutU16(out, p, TLS_EXT_PRE_SHARED_KEY), 2), selectedIdentity)
1331
1504
  }
1332
1505
  p = tlsPutU16(out, p, TLS_EXT_KEY_SHARE)
1333
- const share: i32 = p + 2
1506
+ const share: i32 = tlsAdvance(p, 2)
1334
1507
  const group: i32 = toI32(publicKey.length) === TLS_P256_SHARE_SIZE ? TLS_GROUP_SECP256R1 : TLS_GROUP_X25519
1335
1508
  p = tlsPutU16(out, share, group)
1336
- const key: i32 = p + 2
1509
+ const key: i32 = tlsAdvance(p, 2)
1337
1510
  p = tlsPutBytes(out, key, publicKey)
1338
- tlsPutLength(out, key, p, 2)
1339
- tlsPutLength(out, share, p, 2)
1511
+ p = tlsPutLength(out, key, p, 2)
1512
+ p = tlsPutLength(out, share, p, 2)
1340
1513
  p = tlsPutSelectedVersion(out, p)
1341
- tlsPutLength(out, extensions, p, 2)
1342
- tlsPutHeader(out, at, TLS_HANDSHAKE_SERVER_HELLO, p)
1343
- return p
1514
+ p = tlsPutLength(out, extensions, p, 2)
1515
+ return tlsPutHeader(out, at, TLS_HANDSHAKE_SERVER_HELLO, p)
1344
1516
  }
1345
1517
 
1346
1518
  /**
@@ -1360,7 +1532,10 @@ const tlsPutServerHello = (
1360
1532
  * @param suite The cipher suite the server chose, such as `nish/net/tls/schedule`'s `TLS_AES_128_GCM_SHA256`.
1361
1533
  * @param serverShare The server's key share, its `key_exchange`: 32 bytes of x25519, or a
1362
1534
  * 65-byte uncompressed secp256r1 point.
1363
- * @returns Where the message ends in `out`: `at` plus its length, written or not.
1535
+ * @returns Where the message ends in `out`: `at` plus its length, written or not; -1 when `at` is
1536
+ * negative, a window is outside its buffer, the end would pass 2^30 - 1, or a vector is longer
1537
+ * than its length field holds (`tlsPutLength`): the session id past 255 bytes, or the key share
1538
+ * or the extensions past 65,535.
1364
1539
  */
1365
1540
  export const tlsWriteServerHello = (
1366
1541
  out: u8[],
@@ -1391,7 +1566,10 @@ export const tlsWriteServerHello = (
1391
1566
  * 65-byte uncompressed secp256r1 point.
1392
1567
  * @param selectedIdentity The index, from 0, of the client's PSK identity the server accepts; only its low
1393
1568
  * 16 bits are written.
1394
- * @returns Where the message ends in `out`: `at` plus its length, written or not.
1569
+ * @returns Where the message ends in `out`: `at` plus its length, written or not; -1 when `at` is
1570
+ * negative, a window is outside its buffer, the end would pass 2^30 - 1, or a vector is longer
1571
+ * than its length field holds (`tlsPutLength`): the session id past 255 bytes, or the key share
1572
+ * or the extensions past 65,535.
1395
1573
  */
1396
1574
  export const tlsWriteServerHelloPsk = (
1397
1575
  out: u8[],
@@ -1429,7 +1607,9 @@ export const tlsWriteServerHelloPsk = (
1429
1607
  * @param sessionIdLength How many bytes the session id is, 0 to 32.
1430
1608
  * @param suite The cipher suite the server chose, which the second ServerHello must choose again.
1431
1609
  * @param group The group the client is asked to send a share for, such as `TLS_GROUP_X25519`.
1432
- * @returns Where the message ends in `out`: `at` plus its length, written or not.
1610
+ * @returns Where the message ends in `out`: `at` plus its length, written or not; -1 when `at` is
1611
+ * negative, a window is outside its buffer, the end would pass 2^30 - 1, or a vector is longer
1612
+ * than its length field holds (`tlsPutLength`): the session id past 255 bytes.
1433
1613
  */
1434
1614
  export const tlsWriteHelloRetryRequest = (
1435
1615
  out: u8[],
@@ -1441,15 +1621,23 @@ export const tlsWriteHelloRetryRequest = (
1441
1621
  group: i32
1442
1622
  ): i32 => {
1443
1623
  const none: u8[] = []
1444
- let p: i32 = tlsPutHelloHead(out, at + 4, none, true, sessionId, sessionIdOff, sessionIdLength, suite)
1445
- const extensions: i32 = p + 2
1624
+ let p: i32 = tlsPutHelloHead(
1625
+ out,
1626
+ tlsAdvance(at, 4),
1627
+ none,
1628
+ true,
1629
+ sessionId,
1630
+ sessionIdOff,
1631
+ sessionIdLength,
1632
+ suite
1633
+ )
1634
+ const extensions: i32 = tlsAdvance(p, 2)
1446
1635
  p = tlsPutU16(out, extensions, TLS_EXT_KEY_SHARE)
1447
1636
  p = tlsPutU16(out, p, 2)
1448
1637
  p = tlsPutU16(out, p, group)
1449
1638
  p = tlsPutSelectedVersion(out, p)
1450
- tlsPutLength(out, extensions, p, 2)
1451
- tlsPutHeader(out, at, TLS_HANDSHAKE_SERVER_HELLO, p)
1452
- return p
1639
+ p = tlsPutLength(out, extensions, p, 2)
1640
+ return tlsPutHeader(out, at, TLS_HANDSHAKE_SERVER_HELLO, p)
1453
1641
  }
1454
1642
 
1455
1643
  /**
@@ -1469,7 +1657,10 @@ export const tlsWriteHelloRetryRequest = (
1469
1657
  * @param acknowledgeServerName Whether to send the empty `server_name` that says the server used the name.
1470
1658
  * @param quicTransportParameters The server's QUIC transport parameters, opaque; `null` to send none.
1471
1659
  * @param recordSizeLimit The largest record plaintext the server takes, content type included, written as a `uint16`; 0 to send none.
1472
- * @returns Where the message ends in `out`: `at` plus its length, written or not.
1660
+ * @returns Where the message ends in `out`: `at` plus its length, written or not; -1 when `at` is
1661
+ * negative, a window is outside its buffer, the end would pass 2^30 - 1, or a vector is longer
1662
+ * than its length field holds (`tlsPutLength`): the ALPN protocol past 255 bytes, or
1663
+ * `quicTransportParameters` or the extensions past 65,535.
1473
1664
  */
1474
1665
  export const tlsWriteEncryptedExtensions = (
1475
1666
  out: u8[],
@@ -1480,33 +1671,32 @@ export const tlsWriteEncryptedExtensions = (
1480
1671
  quicTransportParameters: u8[] | null,
1481
1672
  recordSizeLimit: i32
1482
1673
  ): i32 => {
1483
- const extensions: i32 = at + 6
1674
+ const extensions: i32 = tlsAdvance(at, 6)
1484
1675
  let p: i32 = tlsPutBytes(out, extensions, extra)
1485
1676
  if (toI32(alpn.length) > 0) {
1486
1677
  p = tlsPutU16(out, p, TLS_EXT_ALPN)
1487
- const body: i32 = p + 2
1488
- const list: i32 = body + 2
1489
- const name: i32 = list + 1
1678
+ const body: i32 = tlsAdvance(p, 2)
1679
+ const list: i32 = tlsAdvance(body, 2)
1680
+ const name: i32 = tlsAdvance(list, 1)
1490
1681
  p = tlsPutAscii(out, name, alpn)
1491
- tlsPutLength(out, name, p, 1)
1492
- tlsPutLength(out, list, p, 2)
1493
- tlsPutLength(out, body, p, 2)
1682
+ p = tlsPutLength(out, name, p, 1)
1683
+ p = tlsPutLength(out, list, p, 2)
1684
+ p = tlsPutLength(out, body, p, 2)
1494
1685
  }
1495
1686
  if (acknowledgeServerName) {
1496
1687
  p = tlsPutU16(out, tlsPutU16(out, p, TLS_EXT_SERVER_NAME), 0)
1497
1688
  }
1498
1689
  if (quicTransportParameters !== null) {
1499
1690
  p = tlsPutU16(out, p, TLS_EXT_QUIC_TRANSPORT_PARAMETERS)
1500
- const body: i32 = p + 2
1691
+ const body: i32 = tlsAdvance(p, 2)
1501
1692
  p = tlsPutBytes(out, body, quicTransportParameters)
1502
- tlsPutLength(out, body, p, 2)
1693
+ p = tlsPutLength(out, body, p, 2)
1503
1694
  }
1504
1695
  if (recordSizeLimit !== 0) {
1505
1696
  p = tlsPutU16(out, tlsPutU16(out, tlsPutU16(out, p, TLS_EXT_RECORD_SIZE_LIMIT), 2), recordSizeLimit)
1506
1697
  }
1507
- tlsPutLength(out, extensions, p, 2)
1508
- tlsPutHeader(out, at, TLS_HANDSHAKE_ENCRYPTED_EXTENSIONS, p)
1509
- return p
1698
+ p = tlsPutLength(out, extensions, p, 2)
1699
+ return tlsPutHeader(out, at, TLS_HANDSHAKE_ENCRYPTED_EXTENSIONS, p)
1510
1700
  }
1511
1701
 
1512
1702
  /**
@@ -1517,20 +1707,22 @@ export const tlsWriteEncryptedExtensions = (
1517
1707
  * @param out The array to write into; a byte that would land outside it is dropped, so an empty one measures.
1518
1708
  * @param at Where the message, handshake header first, starts in `out`.
1519
1709
  * @param chain The DER certificates, leaf first, each written as it is.
1520
- * @returns Where the message ends in `out`: `at` plus its length, written or not.
1710
+ * @returns Where the message ends in `out`: `at` plus its length, written or not; -1 when `at` is
1711
+ * negative, a window is outside its buffer, the end would pass 2^30 - 1, or a vector is longer
1712
+ * than its length field holds (`tlsPutLength`): a certificate or the whole list past 2^24 - 1
1713
+ * bytes.
1521
1714
  */
1522
1715
  export const tlsWriteCertificate = (out: u8[], at: i32, chain: u8[][]): i32 => {
1523
- const list: i32 = tlsPutU8(out, at + 4, 0) + 3
1716
+ const list: i32 = tlsAdvance(tlsPutU8(out, tlsAdvance(at, 4), 0), 3)
1524
1717
  let p: i32 = list
1525
1718
  for (const certificate of chain) {
1526
- const entry: i32 = p + 3
1719
+ const entry: i32 = tlsAdvance(p, 3)
1527
1720
  p = tlsPutBytes(out, entry, certificate)
1528
- tlsPutLength(out, entry, p, 3)
1721
+ p = tlsPutLength(out, entry, p, 3)
1529
1722
  p = tlsPutU16(out, p, 0)
1530
1723
  }
1531
- tlsPutLength(out, list, p, 3)
1532
- tlsPutHeader(out, at, TLS_HANDSHAKE_CERTIFICATE, p)
1533
- return p
1724
+ p = tlsPutLength(out, list, p, 3)
1725
+ return tlsPutHeader(out, at, TLS_HANDSHAKE_CERTIFICATE, p)
1534
1726
  }
1535
1727
 
1536
1728
  /**
@@ -1541,14 +1733,15 @@ export const tlsWriteCertificate = (out: u8[], at: i32, chain: u8[][]): i32 => {
1541
1733
  * @param at Where the message, handshake header first, starts in `out`.
1542
1734
  * @param scheme The signature scheme, such as `TLS_SIGNATURE_ECDSA_SECP256R1_SHA256`.
1543
1735
  * @param signature The signature over `tlsCertificateVerifyContent`, in the scheme's wire encoding.
1544
- * @returns Where the message ends in `out`: `at` plus its length, written or not.
1736
+ * @returns Where the message ends in `out`: `at` plus its length, written or not; -1 when `at` is
1737
+ * negative, a window is outside its buffer, the end would pass 2^30 - 1, or a vector is longer
1738
+ * than its length field holds (`tlsPutLength`): the signature past 65,535 bytes.
1545
1739
  */
1546
1740
  export const tlsWriteCertificateVerify = (out: u8[], at: i32, scheme: i32, signature: u8[]): i32 => {
1547
- const body: i32 = tlsPutU16(out, at + 4, scheme) + 2
1548
- const p: i32 = tlsPutBytes(out, body, signature)
1549
- tlsPutLength(out, body, p, 2)
1550
- tlsPutHeader(out, at, TLS_HANDSHAKE_CERTIFICATE_VERIFY, p)
1551
- return p
1741
+ const body: i32 = tlsAdvance(tlsPutU16(out, tlsAdvance(at, 4), scheme), 2)
1742
+ let p: i32 = tlsPutBytes(out, body, signature)
1743
+ p = tlsPutLength(out, body, p, 2)
1744
+ return tlsPutHeader(out, at, TLS_HANDSHAKE_CERTIFICATE_VERIFY, p)
1552
1745
  }
1553
1746
 
1554
1747
  /**
@@ -1559,12 +1752,13 @@ export const tlsWriteCertificateVerify = (out: u8[], at: i32, scheme: i32, signa
1559
1752
  * @param verifyData The buffer that holds the `verify_data`, the HMAC the key schedule computed.
1560
1753
  * @param off Where the `verify_data` starts in `verifyData`.
1561
1754
  * @param len How many bytes it is: the suite's hash length, 32 or 48.
1562
- * @returns Where the message ends in `out`: `at` plus its length, written or not.
1755
+ * @returns Where the message ends in `out`: `at` plus its length, written or not; -1 when `at` is
1756
+ * negative, the window is outside `verifyData`, `len` is past 2^24 - 1 (the handshake header's
1757
+ * length field), or the end would pass 2^30 - 1.
1563
1758
  */
1564
1759
  export const tlsWriteFinished = (out: u8[], at: i32, verifyData: u8[], off: i32, len: i32): i32 => {
1565
- const p: i32 = tlsPutWindow(out, at + 4, verifyData, off, len)
1566
- tlsPutHeader(out, at, TLS_HANDSHAKE_FINISHED, p)
1567
- return p
1760
+ const p: i32 = tlsPutWindow(out, tlsAdvance(at, 4), verifyData, off, len)
1761
+ return tlsPutHeader(out, at, TLS_HANDSHAKE_FINISHED, p)
1568
1762
  }
1569
1763
 
1570
1764
  /**
@@ -1584,9 +1778,12 @@ export const tlsWriteFinished = (out: u8[], at: i32, verifyData: u8[], off: i32,
1584
1778
  * @param nonceLength How many bytes the nonce is, 0 to 255.
1585
1779
  * @param ticket The buffer that holds the ticket the client will send back.
1586
1780
  * @param ticketOff Where the ticket starts in `ticket`.
1587
- * @param ticketLength How many bytes the ticket is: §4.6.1 allows 1 to 65535, not checked here.
1781
+ * @param ticketLength How many bytes the ticket is: §4.6.1 allows 1 to 65535; past 65535 answers -1, and 0 is not checked.
1588
1782
  * @param extra Whole extensions, type and length included, written unchecked; empty for none.
1589
- * @returns Where the message ends in `out`: `at` plus its length, written or not.
1783
+ * @returns Where the message ends in `out`: `at` plus its length, written or not; -1 when `at` is
1784
+ * negative, a window is outside its buffer, the end would pass 2^30 - 1, or a vector is longer
1785
+ * than its length field holds (`tlsPutLength`): the nonce past 255 bytes, or the ticket or the
1786
+ * extensions past 65,535.
1590
1787
  */
1591
1788
  export const tlsWriteNewSessionTicket = (
1592
1789
  out: u8[],
@@ -1601,16 +1798,17 @@ export const tlsWriteNewSessionTicket = (
1601
1798
  ticketLength: i32,
1602
1799
  extra: u8[]
1603
1800
  ): i32 => {
1604
- let p: i32 = tlsPutU32(out, tlsPutU32(out, at + 4, lifetime), ageAdd)
1605
- p = tlsPutU8(out, p, nonceLength)
1606
- p = tlsPutWindow(out, p, nonce, nonceOff, nonceLength)
1607
- p = tlsPutU16(out, p, ticketLength)
1608
- p = tlsPutWindow(out, p, ticket, ticketOff, ticketLength)
1609
- const extensions: i32 = p + 2
1801
+ let p: i32 = tlsPutU32(out, tlsPutU32(out, tlsAdvance(at, 4), lifetime), ageAdd)
1802
+ const nonceAt: i32 = tlsAdvance(p, 1)
1803
+ p = tlsPutWindow(out, nonceAt, nonce, nonceOff, nonceLength)
1804
+ p = tlsPutLength(out, nonceAt, p, 1)
1805
+ const ticketAt: i32 = tlsAdvance(p, 2)
1806
+ p = tlsPutWindow(out, ticketAt, ticket, ticketOff, ticketLength)
1807
+ p = tlsPutLength(out, ticketAt, p, 2)
1808
+ const extensions: i32 = tlsAdvance(p, 2)
1610
1809
  p = tlsPutBytes(out, extensions, extra)
1611
- tlsPutLength(out, extensions, p, 2)
1612
- tlsPutHeader(out, at, TLS_HANDSHAKE_NEW_SESSION_TICKET, p)
1613
- return p
1810
+ p = tlsPutLength(out, extensions, p, 2)
1811
+ return tlsPutHeader(out, at, TLS_HANDSHAKE_NEW_SESSION_TICKET, p)
1614
1812
  }
1615
1813
 
1616
1814
  /**
@@ -1624,7 +1822,8 @@ export const tlsWriteNewSessionTicket = (
1624
1822
  * @param transcriptHash The buffer that holds the transcript hash through the server's Certificate.
1625
1823
  * @param off Where the hash starts in `transcriptHash`.
1626
1824
  * @param len How many bytes the hash is: the suite's hash length.
1627
- * @returns Where the content ends in `out`: `at` plus 98 plus `len`, written or not.
1825
+ * @returns Where the content ends in `out`: `at` plus 98 plus `len`, written or not; -1
1826
+ * when `at` is negative, the window is outside `transcriptHash`, or the end would pass 2^30 - 1.
1628
1827
  */
1629
1828
  export const tlsWriteCertificateVerifyContent = (
1630
1829
  out: u8[],
@@ -1642,6 +1841,19 @@ export const tlsWriteCertificateVerifyContent = (
1642
1841
  return tlsPutWindow(out, p, transcriptHash, off, len)
1643
1842
  }
1644
1843
 
1844
+ /**
1845
+ * `n` zero bytes in a fresh array, the buffer a `tlsEncode*` fills after its
1846
+ * writer measured it; a negative `n`, the measure of a message past 2^30 - 1
1847
+ * bytes or with a vector its length field cannot hold, gives an empty one, which the writer then leaves empty.
1848
+ */
1849
+ const tlsZeros = (n: i32): u8[] => {
1850
+ const out: u8[] = []
1851
+ for (let k: i32 = 0; k < n; k++) {
1852
+ out.push(0)
1853
+ }
1854
+ return out
1855
+ }
1856
+
1645
1857
  /** The bytes of `name` as a string of one character a byte, which `tlsWriteEncryptedExtensions` writes back as they were. */
1646
1858
  const tlsBytesString = (name: u8[]): string => tlsWindowString(name, TLS_CODEC_FROM, toI32(name.length))
1647
1859
 
@@ -1655,12 +1867,14 @@ const tlsBytesString = (name: u8[]): string => tlsWindowString(name, TLS_CODEC_F
1655
1867
  * @param suite The cipher suite the server chose.
1656
1868
  * @param serverShare The server's key share, its `key_exchange`: 32 bytes of x25519, or a
1657
1869
  * 65-byte uncompressed secp256r1 point.
1658
- * @returns The whole message, handshake header included.
1870
+ * @returns The whole message, handshake header included; empty for one past 2^30 - 1 bytes, or for
1871
+ * a vector longer than its length field holds (`tlsPutLength`): the session id past 255 bytes, or
1872
+ * the key share or the extensions past 65,535.
1659
1873
  */
1660
1874
  export const tlsEncodeServerHello = (random: u8[], sessionId: u8[], suite: i32, serverShare: u8[]): u8[] => {
1661
1875
  const none: u8[] = []
1662
1876
  const sessionIdLength: i32 = toI32(sessionId.length)
1663
- const out: u8[] = new Array<u8>(
1877
+ const out: u8[] = tlsZeros(
1664
1878
  tlsWriteServerHello(
1665
1879
  none,
1666
1880
  TLS_CODEC_FROM,
@@ -1696,7 +1910,9 @@ export const tlsEncodeServerHello = (random: u8[], sessionId: u8[], suite: i32,
1696
1910
  * 65-byte uncompressed secp256r1 point.
1697
1911
  * @param selectedIdentity The index, from 0, of the client's PSK identity the server accepts; only its low
1698
1912
  * 16 bits are written.
1699
- * @returns The whole message, handshake header included.
1913
+ * @returns The whole message, handshake header included; empty for one past 2^30 - 1 bytes, or for
1914
+ * a vector longer than its length field holds (`tlsPutLength`): the session id past 255 bytes, or
1915
+ * the key share or the extensions past 65,535.
1700
1916
  */
1701
1917
  export const tlsEncodeServerHelloPsk = (
1702
1918
  random: u8[],
@@ -1707,7 +1923,7 @@ export const tlsEncodeServerHelloPsk = (
1707
1923
  ): u8[] => {
1708
1924
  const none: u8[] = []
1709
1925
  const sessionIdLength: i32 = toI32(sessionId.length)
1710
- const out: u8[] = new Array<u8>(
1926
+ const out: u8[] = tlsZeros(
1711
1927
  tlsWriteServerHelloPsk(
1712
1928
  none,
1713
1929
  TLS_CODEC_FROM,
@@ -1741,12 +1957,13 @@ export const tlsEncodeServerHelloPsk = (
1741
1957
  * @param sessionId The client's whole `legacy_session_id`, 0 to 32 bytes, echoed.
1742
1958
  * @param suite The cipher suite the server chose, which the second ServerHello must choose again.
1743
1959
  * @param group The group the client is asked to send a share for, such as `TLS_GROUP_X25519`.
1744
- * @returns The whole message, handshake header included.
1960
+ * @returns The whole message, handshake header included; empty for one past 2^30 - 1 bytes, or for
1961
+ * a vector longer than its length field holds (`tlsPutLength`): the session id past 255 bytes.
1745
1962
  */
1746
1963
  export const tlsEncodeHelloRetryRequest = (sessionId: u8[], suite: i32, group: i32): u8[] => {
1747
1964
  const none: u8[] = []
1748
1965
  const sessionIdLength: i32 = toI32(sessionId.length)
1749
- const out: u8[] = new Array<u8>(
1966
+ const out: u8[] = tlsZeros(
1750
1967
  tlsWriteHelloRetryRequest(none, TLS_CODEC_FROM, sessionId, TLS_CODEC_FROM, sessionIdLength, suite, group)
1751
1968
  )
1752
1969
  tlsWriteHelloRetryRequest(out, TLS_CODEC_FROM, sessionId, TLS_CODEC_FROM, sessionIdLength, suite, group)
@@ -1762,7 +1979,9 @@ export const tlsEncodeHelloRetryRequest = (sessionId: u8[], suite: i32, group: i
1762
1979
  * @param acknowledgeServerName Whether to send the empty `server_name` that says the server used the name.
1763
1980
  * @param quicTransportParameters The server's QUIC transport parameters, opaque; `null` to send none.
1764
1981
  * @param recordSizeLimit The server's own `record_size_limit` (RFC 8449 §4); 0 to send none.
1765
- * @returns The whole message, handshake header included.
1982
+ * @returns The whole message, handshake header included; empty for one past 2^30 - 1 bytes, or for
1983
+ * a vector longer than its length field holds (`tlsPutLength`): the ALPN protocol past 255 bytes,
1984
+ * or `quicTransportParameters` or the extensions past 65,535.
1766
1985
  */
1767
1986
  export const tlsEncodeEncryptedExtensions = (
1768
1987
  extra: u8[],
@@ -1773,7 +1992,7 @@ export const tlsEncodeEncryptedExtensions = (
1773
1992
  ): u8[] => {
1774
1993
  const none: u8[] = []
1775
1994
  const protocol: string = tlsBytesString(alpn)
1776
- const out: u8[] = new Array<u8>(
1995
+ const out: u8[] = tlsZeros(
1777
1996
  tlsWriteEncryptedExtensions(
1778
1997
  none,
1779
1998
  TLS_CODEC_FROM,
@@ -1800,11 +2019,13 @@ export const tlsEncodeEncryptedExtensions = (
1800
2019
  * A server's Certificate (§4.4.2) in a fresh array (`tlsWriteCertificate`).
1801
2020
  *
1802
2021
  * @param chain The DER certificates, leaf first, each written as it is.
1803
- * @returns The whole message, handshake header included.
2022
+ * @returns The whole message, handshake header included; empty for one past 2^30 - 1 bytes, or for
2023
+ * a vector longer than its length field holds (`tlsPutLength`): a certificate or the whole list
2024
+ * past 2^24 - 1 bytes.
1804
2025
  */
1805
2026
  export const tlsEncodeCertificate = (chain: u8[][]): u8[] => {
1806
2027
  const none: u8[] = []
1807
- const out: u8[] = new Array<u8>(tlsWriteCertificate(none, TLS_CODEC_FROM, chain))
2028
+ const out: u8[] = tlsZeros(tlsWriteCertificate(none, TLS_CODEC_FROM, chain))
1808
2029
  tlsWriteCertificate(out, TLS_CODEC_FROM, chain)
1809
2030
  return out
1810
2031
  }
@@ -1814,11 +2035,12 @@ export const tlsEncodeCertificate = (chain: u8[][]): u8[] => {
1814
2035
  *
1815
2036
  * @param scheme The signature scheme, such as `TLS_SIGNATURE_ECDSA_SECP256R1_SHA256`.
1816
2037
  * @param signature The signature over `tlsCertificateVerifyContent`, in the scheme's wire encoding.
1817
- * @returns The whole message, handshake header included.
2038
+ * @returns The whole message, handshake header included; empty for one past 2^30 - 1 bytes, or for
2039
+ * a vector longer than its length field holds (`tlsPutLength`): the signature past 65,535 bytes.
1818
2040
  */
1819
2041
  export const tlsEncodeCertificateVerify = (scheme: i32, signature: u8[]): u8[] => {
1820
2042
  const none: u8[] = []
1821
- const out: u8[] = new Array<u8>(tlsWriteCertificateVerify(none, TLS_CODEC_FROM, scheme, signature))
2043
+ const out: u8[] = tlsZeros(tlsWriteCertificateVerify(none, TLS_CODEC_FROM, scheme, signature))
1822
2044
  tlsWriteCertificateVerify(out, TLS_CODEC_FROM, scheme, signature)
1823
2045
  return out
1824
2046
  }
@@ -1827,12 +2049,13 @@ export const tlsEncodeCertificateVerify = (scheme: i32, signature: u8[]): u8[] =
1827
2049
  * A Finished (§4.4.4) carrying `verifyData`, in a fresh array (`tlsWriteFinished`).
1828
2050
  *
1829
2051
  * @param verifyData The whole `verify_data`, the HMAC the key schedule computed: 32 or 48 bytes.
1830
- * @returns The whole message, handshake header included.
2052
+ * @returns The whole message, handshake header included; empty for `verifyData` past 2^24 - 1
2053
+ * bytes.
1831
2054
  */
1832
2055
  export const tlsEncodeFinished = (verifyData: u8[]): u8[] => {
1833
2056
  const none: u8[] = []
1834
2057
  const length: i32 = toI32(verifyData.length)
1835
- const out: u8[] = new Array<u8>(tlsWriteFinished(none, TLS_CODEC_FROM, verifyData, TLS_CODEC_FROM, length))
2058
+ const out: u8[] = tlsZeros(tlsWriteFinished(none, TLS_CODEC_FROM, verifyData, TLS_CODEC_FROM, length))
1836
2059
  tlsWriteFinished(out, TLS_CODEC_FROM, verifyData, TLS_CODEC_FROM, length)
1837
2060
  return out
1838
2061
  }
@@ -1843,9 +2066,11 @@ export const tlsEncodeFinished = (verifyData: u8[]): u8[] => {
1843
2066
  * @param lifetime How long the ticket may be used, in seconds; RFC 8446 §4.6.1 caps it at seven days.
1844
2067
  * @param ageAdd The `ticket_age_add` that obfuscates the ticket age, which §4.6.1 wants fresh and random.
1845
2068
  * @param nonce The whole `ticket_nonce`, 0 to 255 bytes.
1846
- * @param ticket The whole ticket the client will send back: §4.6.1 allows 1 to 65535 bytes, not checked here.
2069
+ * @param ticket The whole ticket the client will send back: §4.6.1 allows 1 to 65535 bytes; past 65535 answers empty, and 0 is not checked.
1847
2070
  * @param extra Whole extensions, type and length included, written unchecked; empty for none.
1848
- * @returns The whole message, handshake header included.
2071
+ * @returns The whole message, handshake header included; empty for one past 2^30 - 1 bytes, or for
2072
+ * a vector longer than its length field holds (`tlsPutLength`): the nonce past 255 bytes, or the
2073
+ * ticket or the extensions past 65,535.
1849
2074
  */
1850
2075
  export const tlsEncodeNewSessionTicket = (
1851
2076
  lifetime: u32,
@@ -1857,7 +2082,7 @@ export const tlsEncodeNewSessionTicket = (
1857
2082
  const none: u8[] = []
1858
2083
  const nonceLength: i32 = toI32(nonce.length)
1859
2084
  const ticketLength: i32 = toI32(ticket.length)
1860
- const out: u8[] = new Array<u8>(
2085
+ const out: u8[] = tlsZeros(
1861
2086
  tlsWriteNewSessionTicket(
1862
2087
  none,
1863
2088
  TLS_CODEC_FROM,
@@ -1898,7 +2123,7 @@ export const tlsEncodeNewSessionTicket = (
1898
2123
  export const tlsCertificateVerifyContent = (transcriptHash: u8[]): u8[] => {
1899
2124
  const none: u8[] = []
1900
2125
  const length: i32 = toI32(transcriptHash.length)
1901
- const out: u8[] = new Array<u8>(
2126
+ const out: u8[] = tlsZeros(
1902
2127
  tlsWriteCertificateVerifyContent(none, TLS_CODEC_FROM, transcriptHash, TLS_CODEC_FROM, length)
1903
2128
  )
1904
2129
  tlsWriteCertificateVerifyContent(out, TLS_CODEC_FROM, transcriptHash, TLS_CODEC_FROM, length)
@@ -1953,7 +2178,11 @@ export const tlsClientOffersScheme = (scheme: i32): boolean =>
1953
2178
  * @param serverName The host name for `server_name`, ASCII; empty to leave the extension out.
1954
2179
  * @param alpn The ALPN protocols offered, one character a byte, in order; empty to leave ALPN out.
1955
2180
  * @param cookie A HelloRetryRequest's `cookie` to echo; empty to send none.
1956
- * @returns Where the message ends in `out`: `at` plus its length, written or not.
2181
+ * @returns Where the message ends in `out`: `at` plus its length, written or not; -1 when `at` is
2182
+ * negative, a window is outside its buffer, the end would pass 2^30 - 1, or a vector is longer
2183
+ * than its length field holds (`tlsPutLength`): the session id or an ALPN protocol past 255
2184
+ * bytes, or the server name, a list (suites, groups, schemes, ALPN, key shares), the key share,
2185
+ * the cookie or the extensions past 65,535.
1957
2186
  */
1958
2187
  export const tlsWriteClientHello = (
1959
2188
  out: u8[],
@@ -1968,78 +2197,78 @@ export const tlsWriteClientHello = (
1968
2197
  alpn: string[],
1969
2198
  cookie: u8[]
1970
2199
  ): i32 => {
1971
- let p: i32 = tlsPutU16(out, at + 4, TLS_LEGACY_VERSION)
2200
+ let p: i32 = tlsPutU16(out, tlsAdvance(at, 4), TLS_LEGACY_VERSION)
1972
2201
  p = tlsPutBytes(out, p, random)
1973
- p = tlsPutU8(out, p, toI32(sessionId.length))
1974
- p = tlsPutBytes(out, p, sessionId)
1975
- const suiteList: i32 = p + 2
2202
+ const id: i32 = tlsAdvance(p, 1)
2203
+ p = tlsPutBytes(out, id, sessionId)
2204
+ p = tlsPutLength(out, id, p, 1)
2205
+ const suiteList: i32 = tlsAdvance(p, 2)
1976
2206
  p = suiteList
1977
2207
  for (const suite of suites) {
1978
2208
  p = tlsPutU16(out, p, suite)
1979
2209
  }
1980
- tlsPutLength(out, suiteList, p, 2)
2210
+ p = tlsPutLength(out, suiteList, p, 2)
1981
2211
  p = tlsPutU8(out, tlsPutU8(out, p, 1), 0)
1982
- const extensions: i32 = p + 2
2212
+ const extensions: i32 = tlsAdvance(p, 2)
1983
2213
  p = extensions
1984
2214
  if (toI32(serverName.length) > 0) {
1985
2215
  p = tlsPutU16(out, p, TLS_EXT_SERVER_NAME)
1986
- const body: i32 = p + 2
1987
- const list: i32 = body + 2
1988
- const name: i32 = tlsPutU8(out, list, 0) + 2
2216
+ const body: i32 = tlsAdvance(p, 2)
2217
+ const list: i32 = tlsAdvance(body, 2)
2218
+ const name: i32 = tlsAdvance(tlsPutU8(out, list, 0), 2)
1989
2219
  p = tlsPutAscii(out, name, serverName)
1990
- tlsPutLength(out, name, p, 2)
1991
- tlsPutLength(out, list, p, 2)
1992
- tlsPutLength(out, body, p, 2)
2220
+ p = tlsPutLength(out, name, p, 2)
2221
+ p = tlsPutLength(out, list, p, 2)
2222
+ p = tlsPutLength(out, body, p, 2)
1993
2223
  }
1994
2224
  p = tlsPutU16(out, p, TLS_EXT_SUPPORTED_GROUPS)
1995
- const groupsBody: i32 = p + 2
1996
- const groupList: i32 = groupsBody + 2
2225
+ const groupsBody: i32 = tlsAdvance(p, 2)
2226
+ const groupList: i32 = tlsAdvance(groupsBody, 2)
1997
2227
  p = groupList
1998
2228
  for (const group of groups) {
1999
2229
  p = tlsPutU16(out, p, group)
2000
2230
  }
2001
- tlsPutLength(out, groupList, p, 2)
2002
- tlsPutLength(out, groupsBody, p, 2)
2231
+ p = tlsPutLength(out, groupList, p, 2)
2232
+ p = tlsPutLength(out, groupsBody, p, 2)
2003
2233
  p = tlsPutU16(out, p, TLS_EXT_SIGNATURE_ALGORITHMS)
2004
- const schemesBody: i32 = p + 2
2005
- const schemeList: i32 = schemesBody + 2
2234
+ const schemesBody: i32 = tlsAdvance(p, 2)
2235
+ const schemeList: i32 = tlsAdvance(schemesBody, 2)
2006
2236
  p = tlsPutClientSchemes(out, schemeList)
2007
- tlsPutLength(out, schemeList, p, 2)
2008
- tlsPutLength(out, schemesBody, p, 2)
2237
+ p = tlsPutLength(out, schemeList, p, 2)
2238
+ p = tlsPutLength(out, schemesBody, p, 2)
2009
2239
  if (toI32(alpn.length) > 0) {
2010
2240
  p = tlsPutU16(out, p, TLS_EXT_ALPN)
2011
- const body: i32 = p + 2
2012
- const list: i32 = body + 2
2241
+ const body: i32 = tlsAdvance(p, 2)
2242
+ const list: i32 = tlsAdvance(body, 2)
2013
2243
  p = list
2014
2244
  for (const protocol of alpn) {
2015
- const name: i32 = p + 1
2245
+ const name: i32 = tlsAdvance(p, 1)
2016
2246
  p = tlsPutAscii(out, name, protocol)
2017
- tlsPutLength(out, name, p, 1)
2247
+ p = tlsPutLength(out, name, p, 1)
2018
2248
  }
2019
- tlsPutLength(out, list, p, 2)
2020
- tlsPutLength(out, body, p, 2)
2249
+ p = tlsPutLength(out, list, p, 2)
2250
+ p = tlsPutLength(out, body, p, 2)
2021
2251
  }
2022
2252
  p = tlsPutU16(out, tlsPutU16(out, p, TLS_EXT_SUPPORTED_VERSIONS), 3)
2023
2253
  p = tlsPutU16(out, tlsPutU8(out, p, 2), TLS_VERSION_13)
2024
2254
  p = tlsPutU16(out, p, TLS_EXT_KEY_SHARE)
2025
- const shareBody: i32 = p + 2
2026
- const shareList: i32 = shareBody + 2
2027
- const key: i32 = tlsPutU16(out, shareList, shareGroup) + 2
2255
+ const shareBody: i32 = tlsAdvance(p, 2)
2256
+ const shareList: i32 = tlsAdvance(shareBody, 2)
2257
+ const key: i32 = tlsAdvance(tlsPutU16(out, shareList, shareGroup), 2)
2028
2258
  p = tlsPutBytes(out, key, sharePublic)
2029
- tlsPutLength(out, key, p, 2)
2030
- tlsPutLength(out, shareList, p, 2)
2031
- tlsPutLength(out, shareBody, p, 2)
2259
+ p = tlsPutLength(out, key, p, 2)
2260
+ p = tlsPutLength(out, shareList, p, 2)
2261
+ p = tlsPutLength(out, shareBody, p, 2)
2032
2262
  if (toI32(cookie.length) > 0) {
2033
2263
  p = tlsPutU16(out, p, TLS_EXT_COOKIE)
2034
- const body: i32 = p + 2
2035
- const value: i32 = body + 2
2264
+ const body: i32 = tlsAdvance(p, 2)
2265
+ const value: i32 = tlsAdvance(body, 2)
2036
2266
  p = tlsPutBytes(out, value, cookie)
2037
- tlsPutLength(out, value, p, 2)
2038
- tlsPutLength(out, body, p, 2)
2267
+ p = tlsPutLength(out, value, p, 2)
2268
+ p = tlsPutLength(out, body, p, 2)
2039
2269
  }
2040
- tlsPutLength(out, extensions, p, 2)
2041
- tlsPutHeader(out, at, TLS_HANDSHAKE_CLIENT_HELLO, p)
2042
- return p
2270
+ p = tlsPutLength(out, extensions, p, 2)
2271
+ return tlsPutHeader(out, at, TLS_HANDSHAKE_CLIENT_HELLO, p)
2043
2272
  }
2044
2273
 
2045
2274
  /**
@@ -2054,7 +2283,10 @@ export const tlsWriteClientHello = (
2054
2283
  * @param serverName The host name for `server_name`, ASCII; empty to leave the extension out.
2055
2284
  * @param alpn The ALPN protocols offered, one character a byte, in order; empty to leave ALPN out.
2056
2285
  * @param cookie A HelloRetryRequest's `cookie` to echo; empty to send none.
2057
- * @returns The whole message, handshake header included.
2286
+ * @returns The whole message, handshake header included; empty for one past 2^30 - 1 bytes, or for
2287
+ * a vector longer than its length field holds (`tlsPutLength`): the session id or an ALPN
2288
+ * protocol past 255 bytes, or the server name, a list (suites, groups, schemes, ALPN, key
2289
+ * shares), the key share, the cookie or the extensions past 65,535.
2058
2290
  */
2059
2291
  export const tlsEncodeClientHello = (
2060
2292
  random: u8[],
@@ -2068,7 +2300,7 @@ export const tlsEncodeClientHello = (
2068
2300
  cookie: u8[]
2069
2301
  ): u8[] => {
2070
2302
  const none: u8[] = []
2071
- const out: u8[] = new Array<u8>(
2303
+ const out: u8[] = tlsZeros(
2072
2304
  tlsWriteClientHello(
2073
2305
  none,
2074
2306
  TLS_CODEC_FROM,
@@ -2262,6 +2494,14 @@ const tlsClientOffersExtension = (type: i32): boolean =>
2262
2494
  type === TLS_EXT_KEY_SHARE ||
2263
2495
  type === TLS_EXT_COOKIE
2264
2496
 
2497
+ /**
2498
+ * `off + len`, the end of a window whose start and length are each in
2499
+ * `[0, 2^31 - 1]`; a sum past that wraps negative, which every reader refuses
2500
+ * as a position. The readers below call it only on a window `tlsFlightOpen`
2501
+ * has checked lies inside its buffer.
2502
+ */
2503
+ const tlsWindowEnd = (off: i32, len: i32): i32 => toI32(toI64(off) + toI64(len))
2504
+
2265
2505
  /** Opens `view` on `data[off .. off + len)` and answers its reader, or `null` for a window outside `data` (`decode_error`). */
2266
2506
  const tlsFlightOpen = (view: TlsServerFlightView, data: u8[], off: i32, len: i32): TlsReader | null => {
2267
2507
  view.clear()
@@ -2273,7 +2513,7 @@ const tlsFlightOpen = (view: TlsServerFlightView, data: u8[], off: i32, len: i32
2273
2513
  const r: TlsReader = view.reader
2274
2514
  r.data = data
2275
2515
  r.at = off
2276
- r.end = off + len
2516
+ r.end = tlsWindowEnd(off, len)
2277
2517
  r.failed = false
2278
2518
  return r
2279
2519
  }
@@ -2301,14 +2541,14 @@ const tlsReadServerHelloExtension = (r: TlsReader, type: i32, end: i32, view: Tl
2301
2541
  if (!view.isRetry) {
2302
2542
  const keyEnd: i32 = tlsReadVector(r, 2, 1, 65535)
2303
2543
  view.shareAt = r.at
2304
- view.shareLength = keyEnd - r.at
2544
+ view.shareLength = tlsReadSpan(r, keyEnd)
2305
2545
  tlsReadSkipTo(r, keyEnd)
2306
2546
  }
2307
2547
  } else if (type === TLS_EXT_COOKIE && view.isRetry) {
2308
2548
  const cookieEnd: i32 = tlsReadVector(r, 2, 1, 65535)
2309
2549
  view.hasCookie = true
2310
2550
  view.cookieAt = r.at
2311
- view.cookieLength = cookieEnd - r.at
2551
+ view.cookieLength = tlsReadSpan(r, cookieEnd)
2312
2552
  tlsReadSkipTo(r, cookieEnd)
2313
2553
  } else {
2314
2554
  tlsFlightRefuseExtension(
@@ -2330,7 +2570,7 @@ const tlsReadEncryptedExtension = (r: TlsReader, type: i32, end: i32, view: TlsS
2330
2570
  const nameEnd: i32 = tlsReadVector(r, 1, 1, 255)
2331
2571
  view.hasAlpn = true
2332
2572
  view.alpnAt = r.at
2333
- view.alpnLength = nameEnd - r.at
2573
+ view.alpnLength = tlsReadSpan(r, nameEnd)
2334
2574
  tlsReadSkipTo(r, nameEnd)
2335
2575
  if (!r.failed && nameEnd !== listEnd) {
2336
2576
  tlsFlightRefuseExtension(view, TLS_ALERT_ILLEGAL_PARAMETER)
@@ -2386,11 +2626,15 @@ const tlsWindowIsHex = (data: u8[], at: i32, text: string): boolean => {
2386
2626
  if (at < 0 || at > toI32(data.length) - length) {
2387
2627
  return false
2388
2628
  }
2389
- for (let k: i32 = 0; k < length; k++) {
2390
- const hi: i32 = tlsHexNibble(toI32(text.charCodeAt(2 * k)))
2391
- const lo: i32 = tlsHexNibble(toI32(text.charCodeAt(2 * k + 1)))
2392
- if (toI32(data[at + k]) !== ((hi << 4) | lo)) {
2393
- return false
2629
+ const digits: i32 = toI32(text.length)
2630
+ for (let i: i32 = 1; i < digits; i++) {
2631
+ const k: i32 = toI32(toI64(at) + toI64(i >> 1))
2632
+ if ((i & 1) === 1 && k >= 0 && k < toI32(data.length)) {
2633
+ const hi: i32 = tlsHexNibble(toU8(text.charCodeAt(i - 1)))
2634
+ const lo: i32 = tlsHexNibble(toU8(text.charCodeAt(i)))
2635
+ if (toI32(data[k]) !== ((hi << 4) | lo)) {
2636
+ return false
2637
+ }
2394
2638
  }
2395
2639
  }
2396
2640
  return true
@@ -2414,18 +2658,19 @@ export const tlsReadServerHello = (view: TlsServerFlightView, data: u8[], off: i
2414
2658
  }
2415
2659
  view.legacyVersion = tlsReadU16(r)
2416
2660
  view.randomAt = r.at
2417
- view.isRetry = tlsWindowIsHex(data, r.at, TLS_HELLO_RETRY_RANDOM) && r.end - r.at >= TLS_RANDOM_SIZE
2418
- tlsReadSkipTo(r, r.at + TLS_RANDOM_SIZE)
2661
+ view.isRetry =
2662
+ tlsWindowIsHex(data, r.at, TLS_HELLO_RETRY_RANDOM) && tlsWindowLength(r.at, r.end) >= TLS_RANDOM_SIZE
2663
+ tlsReadSkipTo(r, tlsReadAhead(r, TLS_RANDOM_SIZE))
2419
2664
  const sessionEnd: i32 = tlsReadVector(r, 1, 0, 32)
2420
2665
  view.sessionIdAt = r.at
2421
- view.sessionIdLength = sessionEnd - r.at
2666
+ view.sessionIdLength = tlsReadSpan(r, sessionEnd)
2422
2667
  tlsReadSkipTo(r, sessionEnd)
2423
2668
  view.suite = tlsReadU16(r)
2424
2669
  view.compression = tlsReadU8(r)
2425
- if (!r.failed && r.at < off + len) {
2670
+ if (!r.failed && r.at < tlsWindowEnd(off, len)) {
2426
2671
  tlsReadServerExtensions(r, view, true)
2427
2672
  }
2428
- tlsFlightClose(view, r, off + len)
2673
+ tlsFlightClose(view, r, tlsWindowEnd(off, len))
2429
2674
  }
2430
2675
 
2431
2676
  /** The 8 bytes RFC 8446 §4.1.3 has a TLS 1.3 server put at the end of its random when it negotiates TLS 1.2 or below. */
@@ -2441,7 +2686,8 @@ const TLS_DOWNGRADE_11: string = "444f574e47524400"
2441
2686
  * @returns true when the random ends in the TLS 1.2 or the TLS 1.1 sentinel.
2442
2687
  */
2443
2688
  export const tlsServerHelloDowngrade = (view: TlsServerFlightView): boolean => {
2444
- const at: i32 = view.randomAt + TLS_RANDOM_SIZE - 8
2689
+ // A wrapped sum is negative, which `tlsWindowIsHex` answers false for.
2690
+ const at: i32 = toI32(toI64(view.randomAt) + toI64(TLS_RANDOM_SIZE - 8))
2445
2691
  return tlsWindowIsHex(view.data, at, TLS_DOWNGRADE_12) || tlsWindowIsHex(view.data, at, TLS_DOWNGRADE_11)
2446
2692
  }
2447
2693
 
@@ -2466,7 +2712,7 @@ export const tlsReadEncryptedExtensions = (
2466
2712
  return
2467
2713
  }
2468
2714
  tlsReadServerExtensions(r, view, false)
2469
- tlsFlightClose(view, r, off + len)
2715
+ tlsFlightClose(view, r, tlsWindowEnd(off, len))
2470
2716
  }
2471
2717
 
2472
2718
  /**
@@ -2487,23 +2733,27 @@ export const tlsReadCertificate = (view: TlsServerFlightView, data: u8[], off: i
2487
2733
  return
2488
2734
  }
2489
2735
  const contextEnd: i32 = tlsReadVector(r, 1, 0, 255)
2490
- view.contextLength = contextEnd - r.at
2736
+ view.contextLength = tlsReadSpan(r, contextEnd)
2491
2737
  tlsReadSkipTo(r, contextEnd)
2492
2738
  const listEnd: i32 = tlsReadVector(r, 3, 1, 16777215)
2493
2739
  view.certificatesAt = r.at
2494
- view.certificatesLength = listEnd - r.at
2740
+ view.certificatesLength = tlsReadSpan(r, listEnd)
2495
2741
  const messageEnd: i32 = tlsReadList(r, listEnd)
2496
- while (!r.failed && r.at < listEnd) {
2742
+ // Each entry is at least 6 bytes of a list of at most 2^24 - 1, so the
2743
+ // count's bound never ends the walk.
2744
+ let count: i32 = 0
2745
+ while (!r.failed && r.at < listEnd && count < 16777215) {
2497
2746
  tlsReadSkipTo(r, tlsReadVector(r, 3, 1, 16777215))
2498
2747
  const extensionsEnd: i32 = tlsReadVector(r, 2, 0, 65535)
2499
2748
  if (extensionsEnd !== r.at) {
2500
2749
  tlsFlightRefuseExtension(view, TLS_ALERT_UNSUPPORTED_EXTENSION)
2501
2750
  }
2502
2751
  tlsReadSkipTo(r, extensionsEnd)
2503
- view.certificateCount = view.certificateCount + 1
2752
+ count++
2504
2753
  }
2754
+ view.certificateCount = count
2505
2755
  r.end = messageEnd
2506
- tlsFlightClose(view, r, off + len)
2756
+ tlsFlightClose(view, r, tlsWindowEnd(off, len))
2507
2757
  }
2508
2758
 
2509
2759
  /**
@@ -2523,9 +2773,9 @@ export const tlsReadCertificateVerify = (view: TlsServerFlightView, data: u8[],
2523
2773
  view.scheme = tlsReadU16(r)
2524
2774
  const signatureEnd: i32 = tlsReadVector(r, 2, 1, 65535)
2525
2775
  view.signatureAt = r.at
2526
- view.signatureLength = signatureEnd - r.at
2776
+ view.signatureLength = tlsReadSpan(r, signatureEnd)
2527
2777
  tlsReadSkipTo(r, signatureEnd)
2528
- tlsFlightClose(view, r, off + len)
2778
+ tlsFlightClose(view, r, tlsWindowEnd(off, len))
2529
2779
  }
2530
2780
 
2531
2781
  /**
@@ -2543,11 +2793,11 @@ export const tlsReadNewSessionTicket = (view: TlsServerFlightView, data: u8[], o
2543
2793
  if (r === null) {
2544
2794
  return
2545
2795
  }
2546
- tlsReadSkipTo(r, r.at + 8)
2796
+ tlsReadSkipTo(r, tlsReadAhead(r, 8))
2547
2797
  tlsReadSkipTo(r, tlsReadVector(r, 1, 0, 255))
2548
2798
  tlsReadSkipTo(r, tlsReadVector(r, 2, 1, 65535))
2549
2799
  tlsReadSkipTo(r, tlsReadVector(r, 2, 0, 65534))
2550
- tlsFlightClose(view, r, off + len)
2800
+ tlsFlightClose(view, r, tlsWindowEnd(off, len))
2551
2801
  }
2552
2802
 
2553
2803
  /**
@@ -2562,11 +2812,11 @@ export const tlsCopyCertificates = (view: TlsServerFlightView): u8[][] => {
2562
2812
  const r: TlsReader = new TlsReader(
2563
2813
  view.data,
2564
2814
  view.certificatesAt,
2565
- view.certificatesAt + view.certificatesLength
2815
+ tlsWindowEnd(view.certificatesAt, view.certificatesLength)
2566
2816
  )
2567
2817
  while (view.alert === 0 && !r.failed && r.at < r.end) {
2568
2818
  const certificateEnd: i32 = tlsReadVector(r, 3, 1, 16777215)
2569
- chain.push(tlsCopyWindow(view.data, r.at, certificateEnd - r.at))
2819
+ chain.push(tlsCopyWindow(view.data, r.at, tlsReadSpan(r, certificateEnd)))
2570
2820
  tlsReadSkipTo(r, certificateEnd)
2571
2821
  tlsReadSkipTo(r, tlsReadVector(r, 2, 0, 65535))
2572
2822
  }