raiha 0.1.0 → 0.2.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 (347) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +33 -0
  3. data/LICENSE +202 -0
  4. data/README.md +94 -22
  5. data/docs/configuration.md +227 -0
  6. data/docs/development.md +99 -0
  7. data/docs/fiber-scheduler.md +591 -0
  8. data/docs/getting-started.md +190 -0
  9. data/docs/http3-client.md +303 -0
  10. data/docs/http3-server.md +301 -0
  11. data/docs/platforms.md +98 -0
  12. data/docs/qlog.md +86 -0
  13. data/docs/quic.md +268 -0
  14. data/docs/threads.md +127 -0
  15. data/examples/_certificate.rb +55 -0
  16. data/examples/high_level_loopback.rb +59 -0
  17. data/examples/http3_get_public.rb +68 -0
  18. data/examples/in_memory_handshake.rb +38 -0
  19. data/examples/qlog_output.rb +58 -0
  20. data/examples/qlog_roundtrips.rb +66 -0
  21. data/examples/quic_gem_loopback.rb +62 -0
  22. data/examples/stream_echo.rb +68 -0
  23. data/examples/udp_handshake.rb +76 -0
  24. data/lib/raiha/http3/action.rb +21 -0
  25. data/lib/raiha/http3/capsule.rb +86 -0
  26. data/lib/raiha/http3/connection.rb +983 -0
  27. data/lib/raiha/http3/error.rb +24 -0
  28. data/lib/raiha/http3/error_code.rb +27 -0
  29. data/lib/raiha/http3/event.rb +63 -0
  30. data/lib/raiha/http3/frame.rb +148 -0
  31. data/lib/raiha/http3/frame_reader.rb +114 -0
  32. data/lib/raiha/http3/message.rb +137 -0
  33. data/lib/raiha/http3/output.rb +61 -0
  34. data/lib/raiha/http3/priority.rb +52 -0
  35. data/lib/raiha/http3/qlog.rb +145 -0
  36. data/lib/raiha/http3/qpack/decoder.rb +302 -0
  37. data/lib/raiha/http3/qpack/dynamic_table.rb +83 -0
  38. data/lib/raiha/http3/qpack/encoder.rb +94 -0
  39. data/lib/raiha/http3/qpack/error.rb +39 -0
  40. data/lib/raiha/http3/qpack/error_code.rb +13 -0
  41. data/lib/raiha/http3/qpack/field.rb +15 -0
  42. data/lib/raiha/http3/qpack/huffman.rb +397 -0
  43. data/lib/raiha/http3/qpack/reader.rb +82 -0
  44. data/lib/raiha/http3/qpack/result.rb +26 -0
  45. data/lib/raiha/http3/qpack/static_table.rb +139 -0
  46. data/lib/raiha/http3/qpack/writer.rb +44 -0
  47. data/lib/raiha/http3/qpack.rb +26 -0
  48. data/lib/raiha/http3/receiving.rb +46 -0
  49. data/lib/raiha/http3/sending.rb +23 -0
  50. data/lib/raiha/http3/session.rb +31 -0
  51. data/lib/raiha/http3/settings.rb +81 -0
  52. data/lib/raiha/http3/structured_field.rb +120 -0
  53. data/lib/raiha/http3/tracer.rb +26 -0
  54. data/lib/raiha/http3/varint.rb +45 -0
  55. data/lib/raiha/http3.rb +19 -0
  56. data/lib/raiha/http3_binding.rb +139 -0
  57. data/lib/raiha/namespace.rb +11 -0
  58. data/lib/raiha/quic/config.rb +229 -0
  59. data/lib/raiha/quic/congestion/algorithms.rb +17 -0
  60. data/lib/raiha/quic/congestion/cubic.rb +258 -0
  61. data/lib/raiha/quic/congestion/new_reno.rb +161 -0
  62. data/lib/raiha/quic/congestion/pacing.rb +21 -0
  63. data/lib/raiha/quic/congestion/startup/rapid_start.rb +249 -0
  64. data/lib/raiha/quic/congestion/startup.rb +13 -0
  65. data/lib/raiha/quic/congestion.rb +15 -0
  66. data/lib/raiha/quic/connection.rb +2022 -0
  67. data/lib/raiha/quic/connection_ids.rb +62 -0
  68. data/lib/raiha/quic/crypto/aead.rb +68 -0
  69. data/lib/raiha/quic/crypto/header_protection.rb +42 -0
  70. data/lib/raiha/quic/crypto/initial.rb +23 -0
  71. data/lib/raiha/quic/crypto/keys.rb +32 -0
  72. data/lib/raiha/quic/crypto/mac.rb +15 -0
  73. data/lib/raiha/quic/crypto/random.rb +13 -0
  74. data/lib/raiha/quic/crypto.rb +18 -0
  75. data/lib/raiha/quic/crypto_stream.rb +161 -0
  76. data/lib/raiha/quic/datagrams.rb +91 -0
  77. data/lib/raiha/quic/endpoint.rb +785 -0
  78. data/lib/raiha/quic/error.rb +61 -0
  79. data/lib/raiha/quic/error_code.rb +34 -0
  80. data/lib/raiha/quic/event.rb +59 -0
  81. data/lib/raiha/quic/issued_connection_ids.rb +137 -0
  82. data/lib/raiha/quic/kept_packets.rb +41 -0
  83. data/lib/raiha/quic/mtu_search.rb +75 -0
  84. data/lib/raiha/quic/negotiation.rb +143 -0
  85. data/lib/raiha/quic/new_token.rb +55 -0
  86. data/lib/raiha/quic/pacer.rb +52 -0
  87. data/lib/raiha/quic/packet_protection.rb +310 -0
  88. data/lib/raiha/quic/path.rb +473 -0
  89. data/lib/raiha/quic/peer_connection_ids.rb +160 -0
  90. data/lib/raiha/quic/qlog.rb +260 -0
  91. data/lib/raiha/quic/ranges.rb +32 -0
  92. data/lib/raiha/quic/recovery/duty.rb +102 -0
  93. data/lib/raiha/quic/recovery/packet_number_space.rb +420 -0
  94. data/lib/raiha/quic/recovery/rate_meter.rb +95 -0
  95. data/lib/raiha/quic/recovery/rtt_estimator.rb +57 -0
  96. data/lib/raiha/quic/recovery/sent_packet.rb +16 -0
  97. data/lib/raiha/quic/recovery.rb +641 -0
  98. data/lib/raiha/quic/remembered_transport_parameters.rb +29 -0
  99. data/lib/raiha/quic/retry_token.rb +54 -0
  100. data/lib/raiha/quic/route.rb +37 -0
  101. data/lib/raiha/quic/scheduler.rb +112 -0
  102. data/lib/raiha/quic/session.rb +47 -0
  103. data/lib/raiha/quic/stateless_reset.rb +38 -0
  104. data/lib/raiha/quic/stats.rb +24 -0
  105. data/lib/raiha/quic/streams/receive_window.rb +119 -0
  106. data/lib/raiha/quic/streams/receiver.rb +217 -0
  107. data/lib/raiha/quic/streams/sender.rb +200 -0
  108. data/lib/raiha/quic/streams.rb +687 -0
  109. data/lib/raiha/quic/test/bottleneck.rb +55 -0
  110. data/lib/raiha/quic/test/congestion_contract.rb +106 -0
  111. data/lib/raiha/quic/test/network.rb +244 -0
  112. data/lib/raiha/quic/test/random_loss.rb +34 -0
  113. data/lib/raiha/quic/test/reorder.rb +51 -0
  114. data/lib/raiha/quic/test/server.rb +54 -0
  115. data/lib/raiha/quic/test/vectors.rb +337 -0
  116. data/lib/raiha/quic/test/virtual_clock.rb +21 -0
  117. data/lib/raiha/quic/test.rb +17 -0
  118. data/lib/raiha/quic/tls_binding.rb +179 -0
  119. data/lib/raiha/quic/token.rb +28 -0
  120. data/lib/raiha/quic/tracer.rb +127 -0
  121. data/lib/raiha/quic/transmit.rb +14 -0
  122. data/lib/raiha/quic/transport_parameters.rb +244 -0
  123. data/lib/raiha/quic/version.rb +63 -0
  124. data/lib/raiha/quic/wire/codec.rb +136 -0
  125. data/lib/raiha/quic/wire/frame.rb +521 -0
  126. data/lib/raiha/quic/wire/header.rb +90 -0
  127. data/lib/raiha/quic/wire/packet.rb +130 -0
  128. data/lib/raiha/quic/wire/packet_number.rb +47 -0
  129. data/lib/raiha/quic/wire/retry.rb +62 -0
  130. data/lib/raiha/quic/wire/version_negotiation.rb +53 -0
  131. data/lib/raiha/quic/wire.rb +9 -0
  132. data/lib/raiha/quic.rb +46 -0
  133. data/lib/raiha/runtime/addresses.rb +35 -0
  134. data/lib/raiha/runtime/admission.rb +37 -0
  135. data/lib/raiha/runtime/client.rb +190 -0
  136. data/lib/raiha/runtime/driver.rb +165 -0
  137. data/lib/raiha/runtime/error.rb +16 -0
  138. data/lib/raiha/runtime/http3.rb +363 -0
  139. data/lib/raiha/runtime/http3_fields.rb +38 -0
  140. data/lib/raiha/runtime/http3_server.rb +416 -0
  141. data/lib/raiha/runtime/kept.rb +36 -0
  142. data/lib/raiha/runtime/qlog.rb +204 -0
  143. data/lib/raiha/runtime/rack.rb +180 -0
  144. data/lib/raiha/runtime/server.rb +334 -0
  145. data/lib/raiha/runtime/session.rb +447 -0
  146. data/lib/raiha/runtime/threaded/client.rb +161 -0
  147. data/lib/raiha/runtime/threaded/driver.rb +230 -0
  148. data/lib/raiha/runtime/threaded/http3.rb +287 -0
  149. data/lib/raiha/runtime/threaded/http3_server.rb +432 -0
  150. data/lib/raiha/runtime/threaded/server.rb +290 -0
  151. data/lib/raiha/runtime/threaded/session.rb +604 -0
  152. data/lib/raiha/runtime/threaded.rb +45 -0
  153. data/lib/raiha/runtime/udp.rb +410 -0
  154. data/lib/raiha/runtime/worker.rb +138 -0
  155. data/lib/raiha/runtime/workers.rb +248 -0
  156. data/lib/raiha/runtime.rb +37 -0
  157. data/lib/raiha/tls/anti_replay.rb +139 -0
  158. data/lib/raiha/tls/cipher_suite.rb +62 -0
  159. data/lib/raiha/tls/codec/error.rb +43 -0
  160. data/lib/raiha/tls/codec/reader.rb +95 -0
  161. data/lib/raiha/tls/codec/writer.rb +81 -0
  162. data/lib/raiha/tls/codec.rb +5 -0
  163. data/lib/raiha/tls/config.rb +318 -0
  164. data/lib/raiha/tls/crypto/aead.rb +64 -0
  165. data/lib/raiha/tls/crypto/certificate.rb +28 -0
  166. data/lib/raiha/tls/crypto/digest.rb +30 -0
  167. data/lib/raiha/tls/crypto/ecdh.rb +74 -0
  168. data/lib/raiha/tls/crypto/hash.rb +22 -0
  169. data/lib/raiha/tls/crypto/hkdf.rb +28 -0
  170. data/lib/raiha/tls/crypto/signature.rb +87 -0
  171. data/lib/raiha/tls/crypto.rb +19 -0
  172. data/lib/raiha/tls/error.rb +36 -0
  173. data/lib/raiha/tls/event.rb +45 -0
  174. data/lib/raiha/tls/extension/alpn.rb +35 -0
  175. data/lib/raiha/tls/extension/certificate_authorities.rb +35 -0
  176. data/lib/raiha/tls/extension/compress_certificate.rb +33 -0
  177. data/lib/raiha/tls/extension/cookie.rb +27 -0
  178. data/lib/raiha/tls/extension/early_data.rb +54 -0
  179. data/lib/raiha/tls/extension/key_share.rb +90 -0
  180. data/lib/raiha/tls/extension/list.rb +49 -0
  181. data/lib/raiha/tls/extension/opaque.rb +21 -0
  182. data/lib/raiha/tls/extension/placement.rb +55 -0
  183. data/lib/raiha/tls/extension/post_handshake_auth.rb +22 -0
  184. data/lib/raiha/tls/extension/pre_shared_key.rb +81 -0
  185. data/lib/raiha/tls/extension/psk_key_exchange_modes.rb +32 -0
  186. data/lib/raiha/tls/extension/record_size_limit.rb +30 -0
  187. data/lib/raiha/tls/extension/registry.rb +50 -0
  188. data/lib/raiha/tls/extension/server_name.rb +63 -0
  189. data/lib/raiha/tls/extension/signature_algorithms.rb +39 -0
  190. data/lib/raiha/tls/extension/signature_algorithms_cert.rb +21 -0
  191. data/lib/raiha/tls/extension/supported_groups.rb +32 -0
  192. data/lib/raiha/tls/extension/supported_versions.rb +53 -0
  193. data/lib/raiha/tls/extension.rb +32 -0
  194. data/lib/raiha/tls/handshake/acceptor.rb +164 -0
  195. data/lib/raiha/tls/handshake/authentication_messages.rb +127 -0
  196. data/lib/raiha/tls/handshake/certificate.rb +56 -0
  197. data/lib/raiha/tls/handshake/certificate_request.rb +39 -0
  198. data/lib/raiha/tls/handshake/certificate_verify.rb +40 -0
  199. data/lib/raiha/tls/handshake/client_hello.rb +208 -0
  200. data/lib/raiha/tls/handshake/client_hello_builder.rb +144 -0
  201. data/lib/raiha/tls/handshake/client_side.rb +578 -0
  202. data/lib/raiha/tls/handshake/conductor.rb +390 -0
  203. data/lib/raiha/tls/handshake/encrypted_extensions.rb +33 -0
  204. data/lib/raiha/tls/handshake/end_of_early_data.rb +28 -0
  205. data/lib/raiha/tls/handshake/finished.rb +36 -0
  206. data/lib/raiha/tls/handshake/key_update.rb +38 -0
  207. data/lib/raiha/tls/handshake/key_update_handling.rb +88 -0
  208. data/lib/raiha/tls/handshake/machine.rb +238 -0
  209. data/lib/raiha/tls/handshake/message.rb +25 -0
  210. data/lib/raiha/tls/handshake/new_session_ticket.rb +48 -0
  211. data/lib/raiha/tls/handshake/reassembler.rb +88 -0
  212. data/lib/raiha/tls/handshake/server_hello.rb +98 -0
  213. data/lib/raiha/tls/handshake/server_side.rb +672 -0
  214. data/lib/raiha/tls/handshake/violation.rb +12 -0
  215. data/lib/raiha/tls/handshake.rb +62 -0
  216. data/lib/raiha/tls/iana.rb +113 -0
  217. data/lib/raiha/tls/key_exchange.rb +58 -0
  218. data/lib/raiha/tls/key_schedule.rb +269 -0
  219. data/lib/raiha/tls/keylog.rb +40 -0
  220. data/lib/raiha/tls/keyring.rb +180 -0
  221. data/lib/raiha/tls/masked_inspect.rb +33 -0
  222. data/lib/raiha/tls/output.rb +32 -0
  223. data/lib/raiha/tls/profile.rb +82 -0
  224. data/lib/raiha/tls/record/layer.rb +228 -0
  225. data/lib/raiha/tls/record/protection.rb +67 -0
  226. data/lib/raiha/tls/record.rb +11 -0
  227. data/lib/raiha/tls/server_name.rb +42 -0
  228. data/lib/raiha/tls/session.rb +106 -0
  229. data/lib/raiha/tls/signature_scheme.rb +35 -0
  230. data/lib/raiha/tls/tcp/acceptor.rb +121 -0
  231. data/lib/raiha/tls/tcp/connection.rb +371 -0
  232. data/lib/raiha/tls/tcp/event.rb +15 -0
  233. data/lib/raiha/tls/tcp/socket.rb +161 -0
  234. data/lib/raiha/tls/tcp.rb +14 -0
  235. data/lib/raiha/tls/test/fixed_kem.rb +30 -0
  236. data/lib/raiha/tls/test/fixed_random.rb +18 -0
  237. data/lib/raiha/tls/test/rfc8448.rb +923 -0
  238. data/lib/raiha/tls/test/rfc8448_handshakes.rb +118 -0
  239. data/lib/raiha/tls/test.rb +13 -0
  240. data/lib/raiha/tls/ticket.rb +184 -0
  241. data/lib/raiha/tls/ticket_keys.rb +206 -0
  242. data/lib/raiha/tls/trace.rb +58 -0
  243. data/lib/raiha/tls/transcript.rb +94 -0
  244. data/lib/raiha/tls/verifier/default.rb +72 -0
  245. data/lib/raiha/tls/verifier/host_name.rb +75 -0
  246. data/lib/raiha/tls/verifier/none.rb +14 -0
  247. data/lib/raiha/tls/verifier.rb +24 -0
  248. data/lib/raiha/tls.rb +34 -0
  249. data/lib/raiha/version.rb +3 -1
  250. data/lib/raiha.rb +8 -5
  251. data/sig/patches/array.rbs +9 -0
  252. data/sig/patches/io_buffer.rbs +13 -0
  253. data/sig/patches/openssl.rbs +25 -0
  254. data/sig/patches/socket.rbs +29 -0
  255. data/sig/patches/string.rbs +26 -0
  256. data/sig/patches/strscan.rbs +12 -0
  257. data/sig/raiha/http3/capsule.rbs +32 -0
  258. data/sig/raiha/http3/connection.rbs +324 -0
  259. data/sig/raiha/http3/frame.rbs +138 -0
  260. data/sig/raiha/http3/frame_reader.rbs +39 -0
  261. data/sig/raiha/http3/message.rbs +23 -0
  262. data/sig/raiha/http3/priority.rbs +40 -0
  263. data/sig/raiha/http3/qlog.rbs +54 -0
  264. data/sig/raiha/http3/qpack.rbs +246 -0
  265. data/sig/raiha/http3/session.rbs +11 -0
  266. data/sig/raiha/http3/settings.rbs +26 -0
  267. data/sig/raiha/http3.rbs +2 -0
  268. data/sig/raiha/http3_binding.rbs +26 -0
  269. data/sig/raiha/namespace.rbs +2 -0
  270. data/sig/raiha/quic/config.rbs +89 -0
  271. data/sig/raiha/quic/congestion.rbs +213 -0
  272. data/sig/raiha/quic/connection.rbs +249 -0
  273. data/sig/raiha/quic/connection_ids.rbs +34 -0
  274. data/sig/raiha/quic/crypto.rbs +78 -0
  275. data/sig/raiha/quic/crypto_stream.rbs +34 -0
  276. data/sig/raiha/quic/datagrams.rbs +32 -0
  277. data/sig/raiha/quic/endpoint.rbs +179 -0
  278. data/sig/raiha/quic/frame.rbs +387 -0
  279. data/sig/raiha/quic/issued_connection_ids.rbs +47 -0
  280. data/sig/raiha/quic/kept_packets.rbs +25 -0
  281. data/sig/raiha/quic/mtu_search.rbs +21 -0
  282. data/sig/raiha/quic/negotiation.rbs +33 -0
  283. data/sig/raiha/quic/new_token.rbs +14 -0
  284. data/sig/raiha/quic/pacer.rbs +16 -0
  285. data/sig/raiha/quic/packet_protection.rbs +63 -0
  286. data/sig/raiha/quic/path.rbs +106 -0
  287. data/sig/raiha/quic/peer_connection_ids.rbs +42 -0
  288. data/sig/raiha/quic/qlog.rbs +74 -0
  289. data/sig/raiha/quic/ranges.rbs +7 -0
  290. data/sig/raiha/quic/recovery.rbs +376 -0
  291. data/sig/raiha/quic/retry_token.rbs +21 -0
  292. data/sig/raiha/quic/route.rbs +51 -0
  293. data/sig/raiha/quic/scheduler.rbs +36 -0
  294. data/sig/raiha/quic/session.rbs +17 -0
  295. data/sig/raiha/quic/stateless_reset.rbs +10 -0
  296. data/sig/raiha/quic/streams.rbs +244 -0
  297. data/sig/raiha/quic/test.rbs +354 -0
  298. data/sig/raiha/quic/tls_binding.rbs +58 -0
  299. data/sig/raiha/quic/token.rbs +11 -0
  300. data/sig/raiha/quic/tracer.rbs +71 -0
  301. data/sig/raiha/quic/transport_parameters.rbs +113 -0
  302. data/sig/raiha/quic/values.rbs +200 -0
  303. data/sig/raiha/quic/version.rbs +30 -0
  304. data/sig/raiha/quic/wire.rbs +199 -0
  305. data/sig/raiha/quic.rbs +2 -0
  306. data/sig/raiha/runtime/threaded.rbs +616 -0
  307. data/sig/raiha/runtime.rbs +982 -0
  308. data/sig/raiha/tls/anti_replay.rbs +41 -0
  309. data/sig/raiha/tls/cipher_suite.rbs +41 -0
  310. data/sig/raiha/tls/codec.rbs +66 -0
  311. data/sig/raiha/tls/config.rbs +122 -0
  312. data/sig/raiha/tls/crypto.rbs +86 -0
  313. data/sig/raiha/tls/error.rbs +21 -0
  314. data/sig/raiha/tls/event.rbs +61 -0
  315. data/sig/raiha/tls/extension.rbs +331 -0
  316. data/sig/raiha/tls/handshake.rbs +311 -0
  317. data/sig/raiha/tls/iana.rbs +13 -0
  318. data/sig/raiha/tls/key_exchange.rbs +33 -0
  319. data/sig/raiha/tls/key_schedule.rbs +58 -0
  320. data/sig/raiha/tls/keylog.rbs +20 -0
  321. data/sig/raiha/tls/keyring.rbs +64 -0
  322. data/sig/raiha/tls/machine.rbs +429 -0
  323. data/sig/raiha/tls/masked_inspect.rbs +12 -0
  324. data/sig/raiha/tls/output.rbs +37 -0
  325. data/sig/raiha/tls/profile.rbs +26 -0
  326. data/sig/raiha/tls/record.rbs +79 -0
  327. data/sig/raiha/tls/server_name.rbs +10 -0
  328. data/sig/raiha/tls/session.rbs +48 -0
  329. data/sig/raiha/tls/signature_scheme.rbs +20 -0
  330. data/sig/raiha/tls/tcp.rbs +134 -0
  331. data/sig/raiha/tls/test.rbs +143 -0
  332. data/sig/raiha/tls/ticket.rbs +68 -0
  333. data/sig/raiha/tls/ticket_keys.rbs +67 -0
  334. data/sig/raiha/tls/trace.rbs +99 -0
  335. data/sig/raiha/tls/transcript.rbs +22 -0
  336. data/sig/raiha/tls/verifier.rbs +54 -0
  337. data/sig/raiha/tls.rbs +5 -0
  338. data/sig/raiha.rbs +3 -0
  339. metadata +355 -57
  340. data/.gitignore +0 -10
  341. data/CODE_OF_CONDUCT.md +0 -74
  342. data/Gemfile +0 -4
  343. data/Gemfile.lock +0 -22
  344. data/Rakefile +0 -10
  345. data/bin/console +0 -14
  346. data/bin/setup +0 -8
  347. data/raiha.gemspec +0 -40
@@ -0,0 +1,118 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::TLS::Test::RFC8448
4
+ # A Machine playing one side of an RFC 8448 trace: the client or the server
5
+ # of section 3 (:simple_1rtt), 5 (:hello_retry_request) or 6
6
+ # (:client_authentication), or the client of section 4 (:resumed_0rtt),
7
+ # with the trace's randoms and key shares injected.
8
+ #
9
+ # RFC 8448 comes from NSS, and some of what it sends this implementation
10
+ # never builds: TLS 1.2 extensions and groups it does not implement in the
11
+ # ClientHello, a cookie in the HelloRetryRequest, padding in the second
12
+ # ClientHello, NSS's own EncryptedExtensions, RSASSA-PSS signatures with
13
+ # random salts, and certificates whose keys section 6 does not publish.
14
+ # Those messages are replaced by the trace's bytes as they are sent, which
15
+ # only this method can ask for. Everything the Machine derives from the
16
+ # peer's messages, and every message it can build itself (ServerHello,
17
+ # Certificate in sections 3 and 5, Finished), is its own.
18
+ #
19
+ # The peer's certificates are not verified: the trace's are long expired
20
+ # and name no host.
21
+ def self.machine(section, role, now:, keylog: nil)
22
+ return resumed_client(now:, keylog:) if section == :resumed_0rtt && role == :client
23
+ vectors = { simple_1rtt: Simple1RTT, hello_retry_request: HelloRetryRequest, client_authentication: ClientAuthentication }
24
+ trace = vectors.fetch(section)
25
+ tls = Raiha::TLS
26
+ none = tls::Verifier::None.new
27
+ if role == :client
28
+ client_hello = section == :hello_retry_request ? HelloRetryRequest::CLIENT_HELLO_1 : trace.const_get(:CLIENT_HELLO)
29
+ groups = section == :hello_retry_request ? %i[x25519 secp256r1] : %i[x25519]
30
+ keys = { x25519: trace.const_get(:CLIENT_X25519_PRIVATE_KEY) }
31
+ keys[:secp256r1] = HelloRetryRequest::CLIENT_SECP256R1_PRIVATE_KEY if section == :hello_retry_request
32
+ config = tls::Config.deterministic(groups:)
33
+ keyring = tls::Keyring.client(
34
+ config:, identities: section == :client_authentication ? [server_identity] : [], verifier: none,
35
+ key_exchange: Raiha::TLS::Test::FixedKEM.new(keys),
36
+ random: Raiha::TLS::Test::FixedRandom.new(client_hello.byteslice(6, 32).to_s, "\x00".b * 32)
37
+ )
38
+ substitutions = { 1 => [client_hello] }
39
+ substitutions[1] << HelloRetryRequest::CLIENT_HELLO_2 if section == :hello_retry_request
40
+ if section == :client_authentication
41
+ substitutions[11] = [ClientAuthentication::CLIENT_CERTIFICATE]
42
+ substitutions[15] = [ClientAuthentication::CLIENT_CERTIFICATE_VERIFY]
43
+ end
44
+ tls::Handshake::Machine.__send__(:start_client, config:, keyring:, server_name: "server", now:, extensions: [],
45
+ tracer: nil, keylog:, substitutions:)
46
+ else
47
+ server_hello = trace.const_get(:SERVER_HELLO)
48
+ group, key = if section == :hello_retry_request
49
+ [:secp256r1, HelloRetryRequest::SERVER_SECP256R1_PRIVATE_KEY]
50
+ else
51
+ [:x25519, trace.const_get(:SERVER_X25519_PRIVATE_KEY)]
52
+ end
53
+ config = tls::Config.server(groups: [group], client_auth: section == :client_authentication ? :required : :none)
54
+ keyring = tls::Keyring.server(
55
+ config:, identities: [server_identity], verifier: none,
56
+ key_exchange: Raiha::TLS::Test::FixedKEM.new({ group => key }),
57
+ random: Raiha::TLS::Test::FixedRandom.new(server_hello.byteslice(6, 32).to_s)
58
+ )
59
+ substitutions = { 8 => [trace.const_get(:ENCRYPTED_EXTENSIONS)] }
60
+ substitutions[2] = [HelloRetryRequest::HELLO_RETRY_REQUEST] if section == :hello_retry_request
61
+ if section == :client_authentication
62
+ substitutions[13] = [ClientAuthentication::CERTIFICATE_REQUEST]
63
+ substitutions[11] = [ClientAuthentication::SERVER_CERTIFICATE]
64
+ substitutions[15] = [ClientAuthentication::SERVER_CERTIFICATE_VERIFY]
65
+ else
66
+ substitutions[15] = [trace.const_get(:CERTIFICATE_VERIFY)]
67
+ end
68
+ tls::Handshake::Machine.__send__(:start_server, config:, keyring:, client_hello: nil, now:, extensions: [],
69
+ tracer: nil, keylog:, substitutions:)
70
+ end
71
+ end
72
+
73
+ # The client of section 4, resuming the session of section 3's
74
+ # NewSessionTicket with 0-RTT. Its ClientHello is NSS's up to the binders,
75
+ # the binders its own. The session says its server was verified, as the
76
+ # one section 3's client would keep: a client offers no session from a
77
+ # server Verifier::None let in.
78
+ def self.resumed_client(now:, keylog:)
79
+ tls = Raiha::TLS
80
+ config = tls::Config.deterministic(groups: %i[x25519])
81
+ keyring = tls::Keyring.client(
82
+ config:, verifier: tls::Verifier::None.new,
83
+ key_exchange: Raiha::TLS::Test::FixedKEM.new({ x25519: Resumed0RTT::CLIENT_X25519_PRIVATE_KEY }),
84
+ random: Raiha::TLS::Test::FixedRandom.new(Resumed0RTT::CLIENT_HELLO.byteslice(6, 32).to_s, "\x00".b * 32)
85
+ )
86
+ tls::Handshake::Machine.__send__(:start_client, config:, keyring:, server_name: "server", now:, extensions: [],
87
+ tracer: nil, keylog:, substitutions: { 1 => [Resumed0RTT::CLIENT_HELLO] }, session: section3_session(now:), early_data: true)
88
+ end
89
+
90
+ # The session section 3's NewSessionTicket gives, received at `now`.
91
+ def self.section3_session(now:)
92
+ tls = Raiha::TLS
93
+ ticket = case (message = tls::Handshake.parse(Simple1RTT::NEW_SESSION_TICKET, registry: tls::Extension::Registry::BUILTIN))
94
+ when tls::Handshake::NewSessionTicket then message
95
+ else raise "not a NewSessionTicket"
96
+ end
97
+ early_data = case (ext = ticket.extension(tls::Extension::EarlyData::TYPE))
98
+ when tls::Extension::EarlyData::NST then ext
99
+ else raise "no early_data"
100
+ end
101
+ now_ms = (now.to_r * 1000).floor
102
+ tls::Session.new(ticket: ticket.ticket, ticket_nonce: ticket.ticket_nonce, resumption_secret: Simple1RTT::RESUMPTION_SECRET,
103
+ cipher_suite: 0x1301, issued_at: now_ms, lifetime: ticket.ticket_lifetime, age_add: ticket.ticket_age_add,
104
+ max_early_data_size: early_data.max_early_data_size, server_name: "server", alpn: nil,
105
+ peer_certificates: server_identity.cert_der, authenticated_at: now_ms, peer_verified: true)
106
+ end
107
+
108
+ # The certificate of sections 3 to 5 with the key of section 2.
109
+ def self.server_identity
110
+ tls = Raiha::TLS
111
+ certificate = tls::Handshake.parse(Simple1RTT::CERTIFICATE, registry: tls::Extension::Registry::BUILTIN)
112
+ der = case certificate
113
+ when tls::Handshake::Certificate then certificate.certificate_list.fetch(0).cert_data
114
+ else raise "not a Certificate"
115
+ end
116
+ tls::Keyring::Identity.new(cert_der: [der], key_der: SERVER_RSA_PRIVATE_KEY)
117
+ end
118
+ end
@@ -0,0 +1,13 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../tls"
4
+
5
+ # Test support shipped with the gem. `require "raiha/tls"` does not load
6
+ # it; use `require "raiha/tls/test"`.
7
+ module Raiha::TLS::Test
8
+ end
9
+
10
+ require_relative "test/rfc8448"
11
+ require_relative "test/fixed_kem"
12
+ require_relative "test/fixed_random"
13
+ require_relative "test/rfc8448_handshakes"
@@ -0,0 +1,184 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "codec"
4
+ require_relative "crypto"
5
+ require_relative "masked_inspect"
6
+ require_relative "profile"
7
+ require_relative "ticket_keys"
8
+
9
+ module Raiha::TLS
10
+ # A session ticket a server seals for itself, holding what a resumption
11
+ # takes from the connection it was issued on:
12
+ #
13
+ # version (1) || key_id (8) || nonce (12) || AES-256-GCM(padded plaintext) || tag (16)
14
+ # AAD = version || key_id || binding
15
+ #
16
+ # The binding is a SHA-256 of what must be the same for the ticket to
17
+ # open at all: the format, the Profile, the Config's resumption scope,
18
+ # what the layer above binds it to (the QUIC version), the server name
19
+ # and the ALPN protocol; a ticket of any other fails as a forgery would.
20
+ # The nonce is an HMAC of fresh random bytes, the AAD and the plaintext,
21
+ # so a nonce repeats only with the plaintext, and a predictable random
22
+ # source leaks nothing of the key. The plaintext is padded with zeros to a
23
+ # multiple of 64 bytes, which hides small differences of length.
24
+ module Ticket
25
+ VERSION = 1
26
+ NONCE_LENGTH = 12
27
+ RANDOM_LENGTH = 16
28
+ # The version, the key ID, the nonce and the tag.
29
+ OVERHEAD = 1 + TicketKeys::KEY_ID_LENGTH + NONCE_LENGTH + Crypto::AEAD::TAG_LENGTH
30
+ PADDING = 64
31
+ HASH = :sha256
32
+ PROFILE_NAMES = { Profile::TCP => "tcp", Profile::QUIC => "quic" }.freeze #: Hash[Profile, String]
33
+
34
+ # A client certificate as a ticket keeps it: the leaf, the digests of the
35
+ # rules it was verified by and of the anchor its chain ended at (all
36
+ # zeros for a chain that ended at none), when the whole chain was valid
37
+ # (seconds), and whether it was verified.
38
+ class ClientCertificate < Data.define(:leaf, :rules_digest, :anchor_digest, :valid_from, :valid_until, :verified); end
39
+
40
+ NO_ANCHOR = ("\x00".b * 32).freeze
41
+ # The latest time a ticket holds, a 64-bit count.
42
+ MAX_TIME = (1 << 64) - 1
43
+
44
+ # What a ticket holds. `issued_at` and `authenticated_at` are
45
+ # milliseconds of the wall clock; `client` is nil when the client was not
46
+ # authenticated.
47
+ class Plaintext < Data.define(:issued_at, :authenticated_at, :lifetime, :age_add, :cipher_suite, :psk, :alpn,
48
+ :early_data_allowed, :client, :early_data_context)
49
+ include MaskedInspect
50
+
51
+ def masked_members = %i[psk]
52
+
53
+ # The encoding, padded with zeros to a multiple of PADDING.
54
+ def encode
55
+ w = Codec::Writer.new
56
+ Ticket.u64(w, issued_at)
57
+ Ticket.u64(w, authenticated_at)
58
+ w.u32(lifetime)
59
+ w.u32(age_add)
60
+ w.u16(cipher_suite)
61
+ w.vector(1, min: 32, max: 64) { w.bytes(psk) }
62
+ w.vector(1, max: 255) { w.bytes(alpn) }
63
+ w.u8(early_data_allowed ? 1 : 0)
64
+ encode_client(w)
65
+ w.vector(2) { w.bytes(early_data_context) }
66
+ bytes = w.to_s
67
+ bytes + ("\x00".b * (-bytes.bytesize % PADDING))
68
+ end
69
+
70
+ # The Plaintext of `padded`, nil when it does not parse or its padding
71
+ # is not all zeros. Its PSK is a String of its own, which the server
72
+ # clears once it is done with it.
73
+ def self.decode(padded)
74
+ r = Codec::Reader.new(padded)
75
+ plaintext = new(
76
+ issued_at: Ticket.read_u64(r), authenticated_at: Ticket.read_u64(r), lifetime: r.u32, age_add: r.u32,
77
+ cipher_suite: r.u16, psk: r.opaque(1, min: 32, max: 64).dup, alpn: r.opaque(1, max: 255),
78
+ early_data_allowed: Ticket.read_flag(r), client: decode_client(r), early_data_context: r.opaque(2, max: 0xffff)
79
+ )
80
+ rest = padded.byteslice(padded.bytesize - r.remaining, r.remaining).to_s
81
+ plaintext if rest.count("\x00") == rest.bytesize
82
+ rescue Codec::Malformed
83
+ nil
84
+ end
85
+
86
+ def self.decode_client(r)
87
+ return nil unless Ticket.read_flag(r)
88
+ ClientCertificate.new(leaf: r.opaque(3, min: 1, max: 0xffffff), rules_digest: r.bytes(32), anchor_digest: r.bytes(32),
89
+ valid_from: Ticket.read_u64(r), valid_until: Ticket.read_u64(r), verified: Ticket.read_flag(r))
90
+ end
91
+
92
+ private def encode_client(w)
93
+ cert = client
94
+ return w.u8(0) unless cert
95
+ w.u8(1)
96
+ w.vector(3, min: 1) { w.bytes(cert.leaf) }
97
+ w.bytes(cert.rules_digest)
98
+ w.bytes(cert.anchor_digest)
99
+ Ticket.u64(w, cert.valid_from)
100
+ Ticket.u64(w, cert.valid_until)
101
+ w.u8(cert.verified ? 1 : 0)
102
+ end
103
+ end
104
+
105
+ # The part of the binding a Config gives, computed once for it.
106
+ def self.config_binding(profile:, resumption_scope:)
107
+ w = Codec::Writer.new
108
+ w.u8(VERSION)
109
+ w.vector(1) { w.bytes(PROFILE_NAMES.fetch(profile) { raise ArgumentError, "a ticket binds only the built-in Profiles" }) }
110
+ w.vector(2) { w.bytes(resumption_scope) }
111
+ w.to_s.freeze
112
+ end
113
+
114
+ # The binding of a ticket: the Config's part, what the layer above binds
115
+ # it to, the server name ("" for none) and the ALPN protocol ("" for
116
+ # none).
117
+ def self.binding(config_part, resumption_binding:, server_name:, alpn:)
118
+ w = Codec::Writer.new
119
+ w.bytes(config_part)
120
+ w.vector(2) { w.bytes(resumption_binding) }
121
+ w.vector(2) { w.bytes(server_name) }
122
+ w.vector(1) { w.bytes(alpn) }
123
+ Crypto.hash(HASH, w.to_s)
124
+ end
125
+
126
+ # The digest of the rules a client certificate is verified by: what the
127
+ # Verifier says they are, given as its resumption_policy, for the
128
+ # client's purpose.
129
+ def self.rules_digest(resumption_policy)
130
+ w = Codec::Writer.new
131
+ w.vector(2) { w.bytes(resumption_policy) }
132
+ w.vector(1) { w.bytes("client") }
133
+ Crypto.hash(HASH, w.to_s)
134
+ end
135
+
136
+ # The digest a ticket names the trust anchor `der` by.
137
+ def self.anchor_digest(der) = Crypto.hash(HASH, der)
138
+
139
+ # The ticket of `plaintext` under `entry`; `random` is RANDOM_LENGTH fresh
140
+ # bytes.
141
+ def self.seal(plaintext, entry:, binding:, random:)
142
+ padded = plaintext.encode
143
+ header = [VERSION].pack("C") + entry.key_id
144
+ aad = header + binding
145
+ nonce = Crypto.hmac(hash: HASH, key: entry.nonce_key, data: random + aad + padded).byteslice(0, NONCE_LENGTH).to_s
146
+ header + nonce + Crypto::AEAD.new(:aes_256_gcm, entry.aead_key).seal(nonce:, aad:, plaintext: padded)
147
+ end
148
+
149
+ # The Plaintext of `ticket`, or why it gives none, cheapest check first:
150
+ # :malformed (a length out of range, or a plaintext that does not parse),
151
+ # :unknown_version, :unknown_key (no key of `keys` opens it at `now`) or
152
+ # :aead_failure (forged, or bound to something else; the two are not told
153
+ # apart).
154
+ def self.open(ticket, keys:, binding:, now:, max_size:)
155
+ return :malformed unless ticket.bytesize.between?(OVERHEAD, max_size)
156
+ return :unknown_version unless ticket.getbyte(0) == VERSION
157
+ header = ticket.byteslice(0, 1 + TicketKeys::KEY_ID_LENGTH).to_s
158
+ entry = keys.opening(header.byteslice(1, TicketKeys::KEY_ID_LENGTH).to_s, now) or return :unknown_key
159
+ nonce = ticket.byteslice(header.bytesize, NONCE_LENGTH).to_s
160
+ sealed = ticket.byteslice(header.bytesize + NONCE_LENGTH, ticket.bytesize).to_s
161
+ padded = Crypto::AEAD.new(:aes_256_gcm, entry.aead_key).open(nonce:, aad: header + binding, ciphertext: sealed)
162
+ return :aead_failure unless padded
163
+ plaintext = Plaintext.decode(padded)
164
+ padded.clear
165
+ plaintext || :malformed #: Plaintext | reason
166
+ end
167
+
168
+ def self.u64(w, value)
169
+ raise Codec::EncodeError, "#{value} is out of range 0..2^64-1" unless value.between?(0, (1 << 64) - 1)
170
+ w.u32(value >> 32)
171
+ w.u32(value & 0xffff_ffff)
172
+ end
173
+
174
+ def self.read_u64(r) = (r.u32 << 32) | r.u32
175
+
176
+ def self.read_flag(r)
177
+ case r.u8
178
+ when 0 then false
179
+ when 1 then true
180
+ else raise Codec::IllegalValue
181
+ end
182
+ end
183
+ end
184
+ end
@@ -0,0 +1,206 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "key_schedule"
4
+ require_relative "masked_inspect"
5
+ require_relative "error"
6
+
7
+ module Raiha::TLS
8
+ # The keys a server seals its session tickets with. Each comes from a
9
+ # 32-byte seed through HKDF-Expand-Label with a prefix of this
10
+ # implementation's own in place of "tls13 ", so that no label of TLS can
11
+ # give the same key: an AES-256-GCM key, a key for making nonces, and an
12
+ # 8-byte ID that names the key in a ticket. The ID is derived rather than
13
+ # random, so every worker given the same seed names it the same way.
14
+ #
15
+ # TicketKeys.static seals with `current` and opens with it and each of
16
+ # `previous`; the application turns the keys over by building a new
17
+ # Config with new ones. TicketKeys.ratchet gives each epoch of the wall
18
+ # clock keys of its own, every worker computing the same ones without
19
+ # talking to the others (Ratchet).
20
+ class TicketKeys
21
+ # The keys of one seed. `epoch` is nil for keys that are not of a
22
+ # ratchet.
23
+ class Entry < Data.define(:key_id, :aead_key, :nonce_key, :epoch)
24
+ include MaskedInspect
25
+
26
+ def masked_members = %i[aead_key nonce_key]
27
+ end
28
+
29
+ PREFIX = "raiha "
30
+ SEED_LENGTH = 32
31
+ KEY_LENGTH = 32
32
+ KEY_ID_LENGTH = 8
33
+ HASH = :sha256
34
+
35
+ def self.static(current:, previous: [])
36
+ raise ArgumentError, "previous must be an Array of ticket keys" unless previous.is_a?(Array)
37
+ new([current, *previous].map { |seed| derive(seed, nil) })
38
+ end
39
+
40
+ def self.ratchet(base:, base_epoch:, origin:, now:, epoch: 3600, retain: nil, horizon: 24)
41
+ Ratchet.new(base:, base_epoch:, origin:, epoch:, retain:, horizon:, now:)
42
+ end
43
+
44
+ # The Entry of `seed`.
45
+ def self.derive(seed, epoch)
46
+ raise ArgumentError, "a ticket key is #{SEED_LENGTH} bytes" unless seed.is_a?(String) && seed.bytesize == SEED_LENGTH
47
+ Entry.new(key_id: expand(seed, "ticket id", KEY_ID_LENGTH), aead_key: expand(seed, "ticket key", KEY_LENGTH),
48
+ nonce_key: expand(seed, "ticket nonce", KEY_LENGTH), epoch:)
49
+ end
50
+
51
+ def self.expand(seed, label, length)
52
+ KeySchedule.expand_label(secret: seed.b, label:, length:, hash: HASH, prefix: PREFIX)
53
+ end
54
+ private_class_method :expand
55
+
56
+ # `entries`, the first of which seals.
57
+ def initialize(entries)
58
+ ids = entries.map(&:key_id)
59
+ raise ArgumentError, "two ticket keys have the same key ID" unless ids.uniq.size == ids.size
60
+ @entries = entries.dup.freeze
61
+ @by_id = entries.to_h { |entry| [entry.key_id, entry] }.freeze
62
+ Ractor.make_shareable(self)
63
+ end
64
+
65
+ # The Entry to seal a ticket with at `now`, nil when there is none.
66
+ def sealing(now) = @entries.first
67
+
68
+ # The Entry named `key_id` that may open a ticket at `now`, nil when none
69
+ # may.
70
+ def opening(key_id, now) = @by_id[key_id]
71
+
72
+ # The keys as a Config whose tickets live `ticket_lifetime` seconds holds
73
+ # them.
74
+ def for_ticket_lifetime(ticket_lifetime) = self
75
+
76
+ # When these keys stop sealing, nil for never.
77
+ def issuing_until = nil
78
+
79
+ # When to `advance`, nil for never.
80
+ def next_advance_at = nil
81
+
82
+ # The keys to hold from `now` on.
83
+ def advance(now:) = self
84
+
85
+ def inspect = "#<#{self.class.name} key_ids=#{@entries.map { |entry| entry.key_id.unpack1("H*") }.inspect}>"
86
+
87
+ # Keys for each epoch of `epoch` seconds of the wall clock from `origin`,
88
+ # the seed of each epoch derived from the one before:
89
+ #
90
+ # seed(base_epoch) = base
91
+ # seed(e + 1) = HKDF-Expand-Label(seed(e), "ticket ratchet", "", 32)
92
+ #
93
+ # Workers given the same base, base_epoch, origin and epoch compute the
94
+ # same keys at the same time, and keep only the epochs from `retain`
95
+ # before the one they were built in to `horizon` after it. They seal with
96
+ # the key of the current epoch, none once past the horizon, and open a
97
+ # ticket of a key `retain` epochs old to one epoch ahead, for clocks that
98
+ # differ. `advance` builds them again from a later epoch; a seed is never
99
+ # derived backwards, so keys stolen from memory open no ticket sealed
100
+ # before the earliest epoch kept, though they give every later one.
101
+ #
102
+ # Without `retain`, it is the ticket lifetime in epochs plus one, set by
103
+ # the Config the keys are given to (`for_ticket_lifetime`).
104
+ class Ratchet < TicketKeys
105
+ MAX_STEPS = 4096
106
+
107
+ attr_reader :origin, :epoch, :retain, :horizon, :base, :base_epoch
108
+
109
+ def initialize(base:, base_epoch:, origin:, epoch:, retain:, horizon:, now:)
110
+ raise ArgumentError, "a ticket key is #{SEED_LENGTH} bytes" unless base.is_a?(String) && base.bytesize == SEED_LENGTH
111
+ raise ArgumentError, "base_epoch must be an Integer" unless base_epoch.is_a?(Integer)
112
+ raise ArgumentError, "origin and now must be Times" unless origin.is_a?(Time) && now.is_a?(Time)
113
+ raise ArgumentError, "epoch must be a positive Integer of seconds" unless epoch.is_a?(Integer) && epoch.positive?
114
+ raise ArgumentError, "retain must be nil or an Integer of 0 or more" unless retain.nil? || (retain.is_a?(Integer) && !retain.negative?)
115
+ raise ArgumentError, "horizon must be an Integer of 1 or more" unless horizon.is_a?(Integer) && horizon.positive?
116
+ @origin = origin.dup.freeze
117
+ @epoch = epoch
118
+ @retain = retain
119
+ @horizon = horizon
120
+ @built_at = now.dup.freeze
121
+ @built_epoch = epoch_at(now)
122
+ @base = base.b
123
+ @base_epoch = base_epoch
124
+ @by_epoch = {} #: Hash[Integer, Entry]
125
+ return super([]) unless retain
126
+ super(chain(retain))
127
+ end
128
+
129
+ def sealing(now)
130
+ resolved!
131
+ @by_epoch[epoch_at(now)]
132
+ end
133
+
134
+ def opening(key_id, now)
135
+ resolved!
136
+ entry = @by_id[key_id] or return nil
137
+ current = epoch_at(now)
138
+ entry if entry.epoch&.between?(current - retain!, current + 1)
139
+ end
140
+
141
+ def for_ticket_lifetime(ticket_lifetime)
142
+ least = (ticket_lifetime.to_r / epoch).ceil
143
+ return rebuild(retain: least + 1, now: @built_at) unless @retain
144
+ # steep narrows no instance variable by the return above.
145
+ raise ArgumentError, "retain #{@retain} keeps fewer epochs than a ticket lives (#{least})" if @retain < least # steep:ignore
146
+ self
147
+ end
148
+
149
+ def issuing_until = resolved! && (origin + (@built_epoch + horizon + 1) * epoch)
150
+
151
+ def next_advance_at = resolved! && (origin + (@built_epoch + 1) * epoch)
152
+
153
+ # A build walks at most MAX_STEPS seeds from its base, which is
154
+ # `retain` epochs before the epoch it is built in, so keys built
155
+ # further back than that from `now` get there through builds in
156
+ # between: a server that took no connection for months, or whose
157
+ # clock leapt, goes on sealing.
158
+ def advance(now:)
159
+ reach = MAX_STEPS - retain! - horizon
160
+ keys = self
161
+ built = @built_epoch
162
+ while reach.positive? && epoch_at(now) - built > reach
163
+ built += reach
164
+ keys = rebuild(retain: retain!, now: origin + built * epoch, from: keys)
165
+ end
166
+ rebuild(retain: retain!, now:, from: keys)
167
+ end
168
+
169
+ def inspect = "#<#{self.class.name} base_epoch=#{base_epoch} epochs=#{@by_epoch.keys.minmax.inspect}>"
170
+
171
+ private def rebuild(retain:, now:, from: self)
172
+ Ratchet.new(base: from.base, base_epoch: from.base_epoch, origin:, epoch:, retain:, horizon:, now:)
173
+ end
174
+
175
+ # The Entries from `retain` epochs before the current to `horizon`
176
+ # after; `base` becomes the seed of the first.
177
+ private def chain(retain)
178
+ first = @built_epoch - retain
179
+ last = @built_epoch + horizon
180
+ raise ArgumentError, "base_epoch #{base_epoch} is after the first epoch kept, #{first}" if base_epoch > first
181
+ if last - base_epoch > MAX_STEPS
182
+ raise ArgumentError, "the base is #{last - base_epoch} epochs behind; hand out the base of the keys advance(now:) gives instead"
183
+ end
184
+ seed = @base
185
+ (first - base_epoch).times { seed = step(seed) }
186
+ @base = seed
187
+ @base_epoch = first
188
+ (first..last).map do |e|
189
+ entry = TicketKeys.derive(seed, e)
190
+ seed = step(seed)
191
+ @by_epoch[e] = entry
192
+ end
193
+ end
194
+
195
+ private def step(seed)
196
+ KeySchedule.expand_label(secret: seed, label: "ticket ratchet", length: SEED_LENGTH, hash: HASH, prefix: PREFIX)
197
+ end
198
+
199
+ private def epoch_at(time) = ((time.to_r - origin.to_r) / epoch).floor
200
+
201
+ private def retain! = @retain || raise(UsageError, "the ratchet keeps no epochs until a Config gives it its ticket lifetime")
202
+
203
+ private def resolved! = retain! && true
204
+ end
205
+ end
206
+ end
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::TLS
4
+ # Diagnostic values for the `tracer:` of a handshake, one `#tls_trace(value)`
5
+ # call each. None of them carries a secret. A tracer ignores the kinds it
6
+ # does not know, so new kinds do not break it, and with no tracer the
7
+ # values are never built.
8
+ module Trace
9
+ class TranscriptUpdated < Data.define(:msg_type, :length, :digest)
10
+ end
11
+
12
+ class PskRejected < Data.define(:index, :reason)
13
+ end
14
+
15
+ class EarlyDataRejected < Data.define(:reason)
16
+ end
17
+
18
+ class TicketNotIssued < Data.define(:reason)
19
+ end
20
+
21
+ # A client dropped a ticket it had received but nobody had taken yet.
22
+ class TicketIgnored < Data.define(:reason)
23
+ end
24
+
25
+ # A server extension of a type the client did not offer, dropped.
26
+ class ExtensionDropped < Data.define(:type)
27
+ end
28
+
29
+ # An SNI that is not a valid host name, treated as absent.
30
+ class ServerNameIgnored < Data.define(:reason)
31
+ end
32
+
33
+ # The client was asked for 0-RTT but did not attempt it.
34
+ class EarlyDataNotAttempted < Data.define(:reason)
35
+ end
36
+
37
+ # The next four are built only where the check they name has just
38
+ # passed, which a hygiene test enforces, so a test oracle can rely on
39
+ # them: a completed handshake without them skipped a check.
40
+
41
+ # The Verifier accepted the peer's chain; `purpose` is :server or
42
+ # :client.
43
+ class PeerCertificateVerified < Data.define(:purpose)
44
+ end
45
+
46
+ # The signature of the peer's CertificateVerify verified.
47
+ class PeerSignatureVerified < Data.define(:algorithm)
48
+ end
49
+
50
+ # A server verified the binder of the PSK it selected.
51
+ class BinderVerified < Data.define(:index)
52
+ end
53
+
54
+ # The peer's Finished verified over this transcript hash.
55
+ class PeerFinishedVerified < Data.define(:transcript_hash)
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,94 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "crypto"
4
+ require_relative "error"
5
+
6
+ module Raiha::TLS
7
+ # The running transcript hash (RFC 9846 "Transcript Hash").
8
+ #
9
+ # It takes handshake messages as the bytes that went over the wire, header
10
+ # included, and never re-encoded values. A client does not know the cipher
11
+ # suite until the ServerHello, so it runs up to two hashes until `#select!`.
12
+ #
13
+ # There is no snapshot API: the state machine takes the digest right
14
+ # before or after adding a message, and derives the resumption secret at
15
+ # the client Finished instead of keeping a copy. A PSK binder is expressed
16
+ # by order alone: add the ClientHello up to the binders, take the digest,
17
+ # then add the rest.
18
+ class Transcript
19
+ # The handshake messages that enter the transcript: ClientHello,
20
+ # ServerHello (and HelloRetryRequest), EndOfEarlyData, EncryptedExtensions,
21
+ # Certificate, CertificateRequest, CertificateVerify, Finished,
22
+ # CompressedCertificate and the synthetic message_hash. NewSessionTicket
23
+ # and KeyUpdate never do.
24
+ TRANSCRIPT_MESSAGES = Set[1, 2, 5, 8, 11, 13, 15, 20, 25, 254].freeze
25
+
26
+ MESSAGE_HASH = 254
27
+
28
+ def initialize(hashes:)
29
+ if hashes.empty? || hashes.size > 2 || hashes.uniq.size != hashes.size
30
+ raise ArgumentError, "a transcript runs one or two distinct hashes: #{hashes.inspect}"
31
+ end
32
+ @digests = hashes.to_h { |hash| [hash, Crypto::Digest.new(hash)] }
33
+ @selected = nil #: Symbol?
34
+ @header = "".b
35
+ @length = 0
36
+ @restarted = false
37
+ end
38
+
39
+ def selected = @selected
40
+
41
+ def <<(bytes)
42
+ @header << bytes.byteslice(0, 4 - @header.bytesize) if @header.bytesize < 4 # steep:ignore
43
+ @length += bytes.bytesize
44
+ @digests.each_value { |digest| digest << bytes }
45
+ self
46
+ end
47
+
48
+ # The hash of everything added so far, with the selected hash unless one
49
+ # is named.
50
+ def digest(hash = @selected)
51
+ raise UsageError, "no hash is selected yet; name one" if hash.nil?
52
+ running(hash).digest
53
+ end
54
+
55
+ # Keeps only `hash` once the cipher suite is known.
56
+ def select!(hash)
57
+ digest = running(hash)
58
+ raise UsageError, "#{@selected.inspect} is already selected" if @selected && @selected != hash
59
+ @digests = { hash => digest }
60
+ @selected = hash
61
+ self
62
+ end
63
+
64
+ # Replaces ClientHello1 with message_hash(Hash(ClientHello1)) after a
65
+ # HelloRetryRequest. Call it after `#select!` with the hash of the
66
+ # HelloRetryRequest's suite, when the transcript holds exactly
67
+ # ClientHello1, right before adding the HelloRetryRequest. A stateless
68
+ # server passes the ClientHello1 hash it kept in the cookie as `digest:`.
69
+ def restart_with_message_hash!(digest: nil)
70
+ hash = @selected or raise UsageError, "select! the negotiated hash before restarting"
71
+ raise UsageError, "the transcript has already been restarted" if @restarted
72
+ unless only_client_hello?
73
+ raise UsageError, "restart_with_message_hash! needs a transcript of exactly ClientHello1"
74
+ end
75
+ client_hello_hash = digest || self.digest(hash)
76
+ restarted = Crypto::Digest.new(hash)
77
+ restarted << [MESSAGE_HASH, 0, 0, client_hello_hash.bytesize].pack("C4") << client_hello_hash
78
+ @digests = { hash => restarted }
79
+ @restarted = true
80
+ self
81
+ end
82
+
83
+ private def running(hash)
84
+ @digests.fetch(hash) { raise UsageError, "#{hash.inspect} is not running in this transcript" }
85
+ end
86
+
87
+ private def only_client_hello?
88
+ return false unless @header.bytesize == 4 && @header.getbyte(0) == 1
89
+ # The 4-byte header is complete, so every getbyte below is in range.
90
+ length = (@header.getbyte(1) << 16) | (@header.getbyte(2) << 8) | @header.getbyte(3) # steep:ignore
91
+ @length == 4 + length
92
+ end
93
+ end
94
+ end