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,672 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../cipher_suite"
4
+ require_relative "../config"
5
+ require_relative "../crypto"
6
+ require_relative "../event"
7
+ require_relative "../extension"
8
+ require_relative "../iana"
9
+ require_relative "../key_schedule"
10
+ require_relative "../server_name"
11
+ require_relative "../ticket"
12
+ require_relative "../trace"
13
+ require_relative "authentication_messages"
14
+ require_relative "key_update_handling"
15
+
16
+ module Raiha::TLS
17
+ module Handshake
18
+ # The server's states, table of expected messages and handlers, and what
19
+ # it keeps for one connection.
20
+ #
21
+ # From the ClientHello to the first flight there is nothing to wait for
22
+ # (the Verifier and everything else is synchronous), so receiving a
23
+ # ClientHello runs straight through: the checks in the state machine's
24
+ # table, the choice of suite, group and ALPN, a HelloRetryRequest if the
25
+ # client sent no key share for the group, then the certificate and the
26
+ # first flight. A second ClientHello takes the same path, after the
27
+ # checks that it differs from the first only as RFC 9846 allows.
28
+ class ServerSide
29
+ include KeyUpdateHandling
30
+
31
+ STATES = %i[wait_ch2 wait_eoed wait_cert wait_cv wait_finished connected failed].freeze
32
+
33
+ EXPECTED = Ractor.make_shareable({
34
+ wait_ch2: { initial: Set[ClientHello::MSG_TYPE] },
35
+ wait_eoed: { early_data: Set[EndOfEarlyData::MSG_TYPE] },
36
+ wait_cert: { handshake: Set[Certificate::MSG_TYPE] },
37
+ wait_cv: { handshake: Set[CertificateVerify::MSG_TYPE] },
38
+ wait_finished: { handshake: Set[Finished::MSG_TYPE] },
39
+ connected: { application: Set[KeyUpdate::MSG_TYPE] },
40
+ failed: {} # steep:ignore
41
+ }) #: Hash[Symbol, Hash[epoch, Set[Integer]]]
42
+
43
+ NONE = Set.new.freeze #: Set[Integer]
44
+
45
+ # What RFC 9846 "Client Hello" lets the second ClientHello change.
46
+ ALLOWED_TO_CHANGE = [
47
+ Extension::KeyShare::TYPE, Extension::EarlyData::TYPE, Extension::PreSharedKey::TYPE,
48
+ Extension::Cookie::TYPE, ClientHelloBuilder::PADDING
49
+ ].freeze
50
+
51
+ PSK_DHE_KE = 1
52
+
53
+ # The least 0-RTT skipped when it is not taken, in bytes, even by a
54
+ # server that takes none: a client may still hold a ticket from when it
55
+ # did, and then gets a full handshake rather than a failure. OpenSSL
56
+ # skips this much by default, BoringSSL always.
57
+ SKIPPED_EARLY_DATA_FLOOR = 16_384
58
+
59
+ # The ticket a server resumes with, and the index of its identity in
60
+ # the ClientHello.
61
+ class Resumption < Data.define(:index, :ticket); end
62
+
63
+ attr_reader :cipher_suite, :group, :alpn, :peer_certificates, :exporter_values, :peer_record_size_limit
64
+
65
+ def initialize(conductor, extensions:, tracer:, resumption_binding:, early_data_context:, anti_replay:)
66
+ @conductor = conductor
67
+ @config = conductor.config
68
+ @keyring = conductor.keyring
69
+ @extensions = extensions
70
+ @tracer = tracer
71
+ @resumption_binding = resumption_binding
72
+ @early_data_context = early_data_context
73
+ @anti_replay = anti_replay
74
+ # When the full handshake whose key material the connection holds
75
+ # took place (milliseconds), nil until the handshake is over; a
76
+ # resumption takes it from the ticket.
77
+ @authenticated_at = nil #: Integer?
78
+ @resumption = nil #: Resumption?
79
+ # Whether this ClientHello's 0-RTT is taken, and whether it offered
80
+ # 0-RTT that is not, which the record layer then skips.
81
+ @early_data_accepted = false
82
+ @early_data_rejected = false
83
+ @authentication = AuthenticationMessages.new(AuthenticationMessages::Parameters::SERVER, tracer:)
84
+ @client_hello = nil #: ClientHello?
85
+ @hello_retry_request = nil #: ServerHello?
86
+ @server_name = nil #: String?
87
+ @cipher_suite = nil #: CipherSuite?
88
+ @group = nil #: Symbol?
89
+ @alpn = nil #: String?
90
+ @peer_record_size_limit = nil #: Integer?
91
+ # @type var peer_certificates: Array[OpenSSL::X509::Certificate]
92
+ peer_certificates = []
93
+ @peer_certificates = peer_certificates
94
+ # @type var exporter_values: Hash[String, String]
95
+ exporter_values = {}
96
+ @exporter_values = exporter_values
97
+ start_key_updates
98
+ end
99
+
100
+ # The ClientHello comes in as a message; there is nothing to send first.
101
+ def start(now:) = nil
102
+
103
+ def expected_types(state, epoch)
104
+ return NONE if state.nil?
105
+ types = EXPECTED.fetch(state).fetch(epoch, NONE)
106
+ @config.profile.allow_key_update_message ? types : types - [KeyUpdate::MSG_TYPE]
107
+ end
108
+
109
+ def unexpected_reason(state, msg_type) = :unexpected_message
110
+
111
+ def handle(message, raw:, transcript_hash_before:, now:)
112
+ case message
113
+ when ClientHello then client_hello(message, now)
114
+ when EndOfEarlyData then end_of_early_data
115
+ when Certificate then certificate(message, now)
116
+ when CertificateVerify then certificate_verify(message, transcript_hash_before) # steep:ignore
117
+ when Finished then finished(message, transcript_hash_before, now) # steep:ignore
118
+ when KeyUpdate then receive_key_update(message)
119
+ end
120
+ end
121
+
122
+ def forget_secrets!
123
+ @exporter_values.each_value(&:clear).clear
124
+ @resumption&.ticket&.psk&.clear
125
+ nil
126
+ end
127
+
128
+ private def key_schedule = @conductor.key_schedule || raise("the key schedule has not started")
129
+
130
+ private def suite = @cipher_suite || raise("no cipher suite was negotiated")
131
+
132
+ private def own_side = :server
133
+
134
+ private def peer_side = :client
135
+
136
+ private def fail!(alert, reason) = @conductor.fail!(alert, reason)
137
+
138
+ private def client_hello(ch, now)
139
+ first = @client_hello
140
+ if first
141
+ failure = check_second_client_hello(first, ch)
142
+ return fail!(failure.alert, failure.reason) if failure
143
+ end
144
+ profile = @config.profile
145
+ types = ch.extensions.map(&:extension_type)
146
+ # 1, 2: RFC 9001 "QUIC Transport Parameters Extension", both ways.
147
+ return fail!(:missing_extension, :required_extension) unless (profile.required_extensions - types).empty?
148
+ return fail!(:unsupported_extension, :forbidden_extension) unless (types & profile.forbidden_extensions).empty?
149
+ # 3: RFC 9001 "Prohibit TLS Middlebox Compatibility Mode".
150
+ if profile.reject_nonempty_session_id && !ch.legacy_session_id.empty?
151
+ return fail!(:illegal_parameter, :nonempty_legacy_session_id)
152
+ end
153
+ # 4
154
+ @server_name = server_name(ch)
155
+ return fail!(:missing_extension, :server_name) if @config.require_server_name && @server_name.nil?
156
+ # 5: our order; a suite the Profile never selects is passed over, not
157
+ # refused.
158
+ suite = @config.cipher_suite_ids.filter_map { |id| CipherSuite.find(id) }.find do |candidate|
159
+ ch.cipher_suites.include?(candidate.id) && !profile.never_select_cipher_suites.include?(candidate.name)
160
+ end
161
+ return fail!(:handshake_failure, :no_common_cipher_suite) unless suite
162
+ # 6
163
+ groups = case (ext = ch.extension(Extension::SupportedGroups::TYPE))
164
+ when Extension::SupportedGroups then ext.named_group_list
165
+ end
166
+ if ch.extension(Extension::PreSharedKey::TYPE) && !psk_dhe_ke?(ch) && groups.nil?
167
+ return fail!(:insufficient_security, :psk_dhe_ke_not_offered)
168
+ end
169
+ # 7: a mutual group the client sent a share for saves a round trip;
170
+ # otherwise our first mutual group, by HelloRetryRequest.
171
+ # @type var shares: Array[Extension::KeyShare::Entry]
172
+ shares = case (ext = ch.extension(Extension::KeyShare::TYPE))
173
+ when Extension::KeyShare::CH then ext.client_shares
174
+ else []
175
+ end
176
+ mutual = @config.group_ids & (groups || [])
177
+ group = mutual.find { |id| shares.any? { |share| share.group == id } } || mutual.first
178
+ return fail!(:handshake_failure, :no_common_group) unless group
179
+ # 8, 9
180
+ offered_alpn = case (ext = ch.extension(Extension::Alpn::TYPE))
181
+ when Extension::Alpn then ext.protocol_name_list
182
+ end
183
+ alpn = offered_alpn && @config.alpn.find { |protocol| offered_alpn.include?(protocol) }
184
+ if offered_alpn && !@config.alpn.empty? && alpn.nil?
185
+ return fail!(:no_application_protocol, :no_common_application_protocol)
186
+ end
187
+ return fail!(:no_application_protocol, :application_protocol_required) if profile.require_alpn && alpn.nil?
188
+ # 10
189
+ group_name = IANA::NAMED_GROUPS.fetch(group)
190
+ share = shares.find { |entry| entry.group == group }
191
+ unless share
192
+ return fail!(:illegal_parameter, :missing_key_share) if first
193
+ return hello_retry_request(ch, suite, group)
194
+ end
195
+ encapsulated = @keyring.key_exchange.encapsulate(group_name, share.key_exchange)
196
+ return fail!(:illegal_parameter, :invalid_key_share) unless encapsulated
197
+ ciphertext, shared_secret = encapsulated
198
+ # The PSK, then 11; a certificate only without one.
199
+ case (resumption = choose_psk(ch, suite, alpn, now))
200
+ when Violation
201
+ shared_secret.clear
202
+ return fail!(resumption.alert, resumption.reason)
203
+ when Resumption
204
+ selected = nil
205
+ else
206
+ # 12, 13
207
+ algorithms = case (ext = ch.extension(Extension::SignatureAlgorithms::TYPE))
208
+ when Extension::SignatureAlgorithms then ext.supported_signature_algorithms
209
+ end
210
+ unless algorithms
211
+ shared_secret.clear
212
+ return fail!(:missing_extension, :signature_algorithms)
213
+ end
214
+ selected = @keyring.server_credential(server_name: @server_name, signature_algorithms: algorithms,
215
+ signature_algorithms_cert: signature_algorithms_cert(ch), certificate_authorities: certificate_authorities(ch))
216
+ unless selected
217
+ shared_secret.clear
218
+ return fail!(:handshake_failure, :no_usable_certificate)
219
+ end
220
+ end
221
+
222
+ @resumption = resumption
223
+ @client_hello = ch
224
+ @cipher_suite = suite
225
+ @group = group_name
226
+ @alpn = alpn
227
+ if ch.extension(Extension::EarlyData::TYPE)
228
+ reason = resumption ? early_data_refusal(ch, resumption, now) : :psk_not_selected
229
+ reason ? reject_early_data(reason) : (@early_data_accepted = true)
230
+ end
231
+ ch.extensions.each do |ext|
232
+ next if Config::RESERVED_EXTENSIONS.include?(ext.extension_type) || IANA.grease?(ext.extension_type)
233
+ @conductor.event!(Event::PeerExtension.new(type: ext.extension_type, data: ext.encode, message: ClientHello::MSG_TYPE))
234
+ end
235
+ send_first_flight(ch, Extension::KeyShare::Entry.new(group:, key_exchange: ciphertext), shared_secret, selected)
236
+ end
237
+
238
+ # The first identity whose ticket opens and passes the checks against
239
+ # the current Config, its binder verified, or nil for a full
240
+ # handshake, with the reason each identity was passed over traced.
241
+ # Only a binder that does not verify fails the handshake (RFC 9846
242
+ # "Pre-Shared Key Extension").
243
+ private def choose_psk(ch, suite, alpn, now)
244
+ offer = case (ext = ch.extension(Extension::PreSharedKey::TYPE))
245
+ when Extension::PreSharedKey::CH then ext
246
+ end
247
+ keys = @config.ticket_keys
248
+ return nil unless offer && keys
249
+ unless psk_dhe_ke?(ch)
250
+ offer.identities.each_index { |index| reject_psk(index, :psk_mode_unsupported) }
251
+ return nil
252
+ end
253
+ binding = Ticket.binding(@config.ticket_binding, resumption_binding: @resumption_binding, server_name: @server_name || "",
254
+ alpn: alpn || "")
255
+ offer.identities.each_with_index do |identity, index|
256
+ case (opened = Ticket.open(identity.identity, keys:, binding:, now:, max_size: @config.max_ticket_size))
257
+ when Ticket::Plaintext
258
+ reason = ticket_refusal(opened, suite, now)
259
+ return verify_binder(index, opened, offer.binders.fetch(index), suite) unless reason
260
+ opened.psk.clear
261
+ reject_psk(index, reason)
262
+ else reject_psk(index, opened)
263
+ end
264
+ end
265
+ nil
266
+ end
267
+
268
+ # The first check of `ticket` against the current Config at `now` that
269
+ # it fails, nil when it passes them all: the age of the ticket and of
270
+ # the full handshake its key material comes from, the hash of the
271
+ # suite, whether the client is to be authenticated now as it was then,
272
+ # and for a client certificate, the rules it was verified by, the
273
+ # anchor its chain ended at, which must still be trusted (a chain that
274
+ # ended at none never is), and the dates of the whole chain.
275
+ private def ticket_refusal(ticket, suite, now)
276
+ now_ms = (now.to_r * 1000).floor
277
+ lifetime = [ticket.lifetime, @config.ticket_lifetime, Config::MAX_TICKET_LIFETIME].min
278
+ return :ticket_expired if now_ms - ticket.issued_at > lifetime * 1000
279
+ return :authentication_expired if now_ms - ticket.authenticated_at > Config::MAX_TICKET_LIFETIME * 1000
280
+ return :cipher_suite_hash_mismatch unless CipherSuite.find(ticket.cipher_suite)&.hash_algorithm == suite.hash_algorithm
281
+ client = ticket.client
282
+ return :client_certificate_missing if client.nil? && @config.client_auth == :required
283
+ return :client_auth_disabled if client && @config.client_auth == :none
284
+ return nil unless client
285
+ rules_digest = client_rules_digest or return :client_auth_not_resumable
286
+ return :verification_rules_changed unless client.rules_digest == rules_digest
287
+ return :trust_anchor_removed unless @config.trust_anchor_digests.include?(client.anchor_digest)
288
+ return :client_certificate_expired unless now.to_i.between?(client.valid_from, client.valid_until)
289
+ nil
290
+ end
291
+
292
+ # Constant time, a binder of the wrong length not verifying either.
293
+ private def verify_binder(index, ticket, binder, suite)
294
+ schedule = KeySchedule.new(hash: suite.hash_algorithm, psk: ticket.psk)
295
+ verified = schedule.verify_binder(kind: :resumption, transcript_hash: @conductor.binder_transcript_hash(suite.hash_algorithm), binder:)
296
+ schedule.discard!
297
+ unless verified
298
+ ticket.psk.clear
299
+ return Violation.new(alert: :decrypt_error, reason: :psk_binder_mismatch)
300
+ end
301
+ @conductor.trace(Trace::BinderVerified.new(index:)) if @conductor.tracing?
302
+ Resumption.new(index:, ticket:)
303
+ end
304
+
305
+ # The first check that keeps this ClientHello's 0-RTT from being taken
306
+ # on `resumption`, nil when it passes them all and the anti-replay
307
+ # record takes it: the ticket and the Config allow 0-RTT, the first
308
+ # identity, the cipher suite, ALPN protocol and early_data_context of
309
+ # the ticket (which the layer above must give where there is no
310
+ # record layer), the ticket's age as the client counts it (RFC 9846
311
+ # "Early Data Indication", "Freshness Checks"), and last, as only it
312
+ # records, the anti-replay record ("Client Hello Recording").
313
+ private def early_data_refusal(ch, resumption, now)
314
+ ticket = resumption.ticket
315
+ return :ticket_disallows unless ticket.early_data_allowed
316
+ return :config_disallows unless @config.max_early_data_size.positive?
317
+ return :not_first_identity unless resumption.index.zero?
318
+ return :cipher_suite_mismatch unless ticket.cipher_suite == suite.id
319
+ return :alpn_mismatch unless ticket.alpn == (@alpn || "".b)
320
+ context = @early_data_context
321
+ return :early_data_context_mismatch unless ticket.early_data_context == context && (@config.profile.record_layer || !context.empty?)
322
+ offer = case (ext = ch.extension(Extension::PreSharedKey::TYPE))
323
+ when Extension::PreSharedKey::CH then ext
324
+ else raise "a PSK was selected"
325
+ end
326
+ client_age = (offer.identities.fetch(0).obfuscated_ticket_age - ticket.age_add) % (1 << 32)
327
+ # The server's milliseconds not rounded, so that a replay passes this
328
+ # check no later than the record is asked to keep the ClientHello.
329
+ skew = client_age - (now.to_r * 1000 - ticket.issued_at)
330
+ return :ticket_age_skew unless skew.between?(-10_000, 1_000)
331
+ anti_replay = @anti_replay or raise "a Config that takes 0-RTT has an anti-replay record"
332
+ case (result = anti_replay.check(offer.binders.fetch(0), expires_at: now + Rational(skew + 10_000, 1000), now:))
333
+ when :accepted then nil
334
+ when :replayed then :replayed
335
+ when :unavailable then :anti_replay_unavailable
336
+ # A record that breaks its contract can answer anything.
337
+ else raise UsageError, "an anti-replay record answers :accepted, :replayed or :unavailable, not #{result.inspect}" # steep:ignore
338
+ end
339
+ end
340
+
341
+ private def reject_early_data(reason)
342
+ @early_data_rejected = true
343
+ @conductor.event!(Event::EarlyDataRejected.new(reason:))
344
+ @conductor.trace(Trace::EarlyDataRejected.new(reason:)) if @conductor.tracing?
345
+ end
346
+
347
+ private def reject_psk(index, reason)
348
+ @conductor.trace(Trace::PskRejected.new(index:, reason:)) if @conductor.tracing?
349
+ nil
350
+ end
351
+
352
+ # 0a to 0c of the state machine's table for the second ClientHello: the
353
+ # first that fails.
354
+ private def check_second_client_hello(first, second)
355
+ same = %i[legacy_version random legacy_session_id cipher_suites legacy_compression_methods].all? do |field|
356
+ first.public_send(field) == second.public_send(field)
357
+ end
358
+ kept = ->(ch) { ch.extensions.reject { |ext| ALLOWED_TO_CHANGE.include?(ext.extension_type) } }
359
+ hrr = @hello_retry_request or raise "a second ClientHello without a HelloRetryRequest"
360
+ sent_cookie = hrr.extension(Extension::Cookie::TYPE)
361
+ cookie = second.extension(Extension::Cookie::TYPE)
362
+ unless same && kept.call(first) == kept.call(second) && cookie&.encode == sent_cookie&.encode
363
+ return Violation.new(alert: :illegal_parameter, reason: :client_hello_changed)
364
+ end
365
+ if second.extension(Extension::EarlyData::TYPE)
366
+ return Violation.new(alert: :illegal_parameter, reason: :early_data_after_hello_retry_request)
367
+ end
368
+ requested = case (ext = hrr.extension(Extension::KeyShare::TYPE))
369
+ when Extension::KeyShare::HRR then ext.selected_group
370
+ end
371
+ # @type var shares: Array[Integer]
372
+ shares = case (ext = second.extension(Extension::KeyShare::TYPE))
373
+ when Extension::KeyShare::CH then ext.client_shares.map(&:group)
374
+ else []
375
+ end
376
+ return Violation.new(alert: :illegal_parameter, reason: :key_share_not_requested_group) if requested && shares != [requested]
377
+ nil
378
+ end
379
+
380
+ private def hello_retry_request(ch, suite, group)
381
+ hrr = ServerHello.new(
382
+ legacy_version: ClientHelloBuilder::LEGACY_VERSION, random: ServerHello::HELLO_RETRY_REQUEST_RANDOM,
383
+ legacy_session_id_echo: ch.legacy_session_id, cipher_suite: suite.id, legacy_compression_method: 0,
384
+ extensions: [
385
+ Extension::KeyShare::HRR.new(selected_group: group),
386
+ Extension::SupportedVersions::SH.new(selected_version: ClientHelloBuilder::TLS13)
387
+ ]
388
+ )
389
+ @client_hello = ch
390
+ @cipher_suite = suite
391
+ # No 0-RTT after a HelloRetryRequest (RFC 9846 "Early Data
392
+ # Indication").
393
+ reject_early_data(:hello_retry_request) if ch.extension(Extension::EarlyData::TYPE)
394
+ @hello_retry_request = @conductor.emit_hello_retry_request!(hrr, suite.hash_algorithm)
395
+ @conductor.transition!(:wait_ch2)
396
+ end
397
+
398
+ # A server that resumes authenticates by the PSK alone, sending
399
+ # neither a certificate nor a CertificateRequest (RFC 9846
400
+ # "Certificate Request"); otherwise `selected` is the credential and
401
+ # scheme to sign with.
402
+ private def send_first_flight(ch, share, shared_secret, selected)
403
+ suite = self.suite
404
+ resumption = @resumption
405
+ extensions = [
406
+ Extension::KeyShare::SH.new(server_share: share),
407
+ Extension::SupportedVersions::SH.new(selected_version: ClientHelloBuilder::TLS13)
408
+ ] #: Array[Extension::_Extension]
409
+ extensions << Extension::PreSharedKey::SH.new(selected_identity: resumption.index) if resumption
410
+ server_hello = ServerHello.new(
411
+ legacy_version: ClientHelloBuilder::LEGACY_VERSION, random: @keyring.random_bytes(32),
412
+ legacy_session_id_echo: ch.legacy_session_id, cipher_suite: suite.id, legacy_compression_method: 0, extensions:
413
+ )
414
+ # 0-RTT's key is over the ClientHello alone.
415
+ client_hello_hash = @conductor.transcript_hash(suite.hash_algorithm)
416
+ @conductor.emit_server_hello!(server_hello, suite.hash_algorithm)
417
+ if resumption
418
+ @authenticated_at = resumption.ticket.authenticated_at
419
+ # The leaf alone: a ticket keeps no more of the chain.
420
+ client = resumption.ticket.client
421
+ @peer_certificates = [Crypto::Certificate.parse(client.leaf) || raise("a ticket holds a leaf it was sealed with")] if client
422
+ end
423
+ schedule = @conductor.start_key_schedule(hash: suite.hash_algorithm, client_random: ch.random, psk: resumption&.ticket&.psk)
424
+ # The early secret holds it now.
425
+ resumption&.ticket&.psk&.clear
426
+ # @type var secrets: Array[Conductor::secret_entry]
427
+ secrets = []
428
+ secrets << [:early_data, :read, schedule.client_early_traffic_secret(client_hello_hash)] if @early_data_accepted
429
+ schedule.handshake!(shared_secret)
430
+ shared_secret.clear
431
+ transcript_hash = @conductor.transcript_hash
432
+ client_handshake = schedule.client_handshake_traffic_secret(transcript_hash)
433
+ server_handshake = schedule.server_handshake_traffic_secret(transcript_hash)
434
+
435
+ @conductor.emit_message!(:handshake, EncryptedExtensions.new(extensions: encrypted_extensions(ch)))
436
+ if selected
437
+ credential, scheme = selected
438
+ @conductor.emit_message!(:handshake, certificate_request) unless @config.client_auth == :none
439
+ @conductor.emit_message!(:handshake, @authentication.certificate(credential))
440
+ @conductor.emit_message!(:handshake, @authentication.certificate_verify(credential, scheme, @conductor.transcript_hash))
441
+ end
442
+ @conductor.emit_message!(:handshake, @authentication.finished(schedule, @conductor.transcript_hash))
443
+
444
+ schedule.main!
445
+ through_server_finished = @conductor.transcript_hash
446
+ server_application = schedule.server_application_traffic_secret(through_server_finished)
447
+ schedule.client_application_traffic_secret(through_server_finished)
448
+ @exporter_values = schedule.exporter_values(@config.exporter_labels, through_server_finished)
449
+ # Where there is a record layer, the client's 0-RTT comes first, up to
450
+ # its EndOfEarlyData.
451
+ until_end_of_early_data = @early_data_accepted && @config.profile.send_end_of_early_data
452
+ secrets.push([:handshake, :read, client_handshake], [:handshake, :write, server_handshake], [:application, :write, server_application])
453
+ moved = @conductor.change_epochs!(cipher_suite: suite, read: until_end_of_early_data ? :early_data : :handshake, write: :application,
454
+ secrets:)
455
+ return unless moved
456
+ if until_end_of_early_data
457
+ @conductor.transition!(:wait_eoed)
458
+ else
459
+ @conductor.transition!(resumption || @config.client_auth == :none ? :wait_finished : :wait_cert)
460
+ end
461
+ end
462
+
463
+ # The end of the client's 0-RTT; its Finished follows under the
464
+ # handshake key. Only a resumed connection takes 0-RTT, so no
465
+ # certificate comes.
466
+ private def end_of_early_data
467
+ return unless @conductor.change_epochs!(cipher_suite: suite, read: :handshake)
468
+ @conductor.transition!(:wait_finished)
469
+ end
470
+
471
+ def skip_early_data_limit = ([@config.max_early_data_size, SKIPPED_EARLY_DATA_FLOOR].max if @early_data_rejected && @config.profile.record_layer)
472
+
473
+ # The client offered every type we answer with: server_name when its
474
+ # SNI was used, ALPN, record_size_limit, and the extensions given from
475
+ # outside. A given extension of a type the client did not offer is
476
+ # dropped, as a server may not send it, and traced so the mistake shows.
477
+ private def encrypted_extensions(ch)
478
+ offered = ch.extensions.map(&:extension_type)
479
+ # @type var extensions: Array[Extension::_Extension]
480
+ extensions = []
481
+ extensions << Extension::ServerName::EE.new if @server_name
482
+ extensions << Extension::EarlyData::EE.new if @early_data_accepted
483
+ alpn = @alpn
484
+ extensions << Extension::Alpn.new(protocol_name_list: [alpn]) if alpn
485
+ case (ext = ch.extension(Extension::RecordSizeLimit::TYPE))
486
+ when Extension::RecordSizeLimit then @peer_record_size_limit = ext.record_size_limit
487
+ end
488
+ limit = @config.record_size_limit
489
+ if limit && offered.include?(Extension::RecordSizeLimit::TYPE)
490
+ extensions << Extension::RecordSizeLimit.new(record_size_limit: limit)
491
+ end
492
+ (@config.extensions + @extensions).each do |ext|
493
+ if offered.include?(ext.extension_type)
494
+ extensions << ext
495
+ elsif @conductor.tracing?
496
+ @conductor.trace(Trace::ExtensionDropped.new(type: ext.extension_type))
497
+ end
498
+ end
499
+ extensions
500
+ end
501
+
502
+ # RFC 9846 "Certificate Request": an empty context during the
503
+ # handshake, our signature schemes, and the CAs we trust unless the
504
+ # Config says not to name them.
505
+ private def certificate_request
506
+ extensions = [Extension::SignatureAlgorithms.new(supported_signature_algorithms: @config.signature_algorithm_ids)] #: Array[Extension::_Extension]
507
+ unless @config.signature_algorithm_cert_ids == @config.signature_algorithm_ids
508
+ extensions << Extension::SignatureAlgorithmsCert.new(supported_signature_algorithms: @config.signature_algorithm_cert_ids)
509
+ end
510
+ subjects = @keyring.trust_anchor_subjects
511
+ if @config.certificate_authorities && !subjects.empty?
512
+ extensions << Extension::CertificateAuthorities.new(authorities: subjects)
513
+ end
514
+ CertificateRequest.new(certificate_request_context: "".b, extensions:)
515
+ end
516
+
517
+ private def certificate(message, now)
518
+ return fail!(:decode_error, :certificate_request_context) unless message.certificate_request_context.empty?
519
+ if message.certificate_list.empty?
520
+ return fail!(:certificate_required, :certificate_required) if @config.client_auth == :required
521
+ # :optional: on without client authentication.
522
+ return @conductor.transition!(:wait_finished)
523
+ end
524
+ return fail!(:unsupported_extension, :unsolicited_extension) if message.certificate_list.any? { |entry| !entry.extensions.empty? }
525
+ result = @authentication.verify_certificate(message, keyring: @keyring, server_name: nil, now:,
526
+ max_chain_length: @config.max_certificate_chain_length, context: "".b)
527
+ case result
528
+ when AuthenticationMessages::Failure then fail!(result.alert, result.reason)
529
+ else
530
+ @peer_certificates = result
531
+ @conductor.transition!(:wait_cv)
532
+ end
533
+ end
534
+
535
+ private def certificate_verify(message, transcript_hash)
536
+ leaf = @peer_certificates.first or raise "no peer certificate to verify against"
537
+ result = @authentication.verify_certificate_verify(message, leaf, offered: @config.signature_algorithm_ids, transcript_hash:)
538
+ case result
539
+ when AuthenticationMessages::Failure then fail!(result.alert, result.reason)
540
+ else @conductor.transition!(:wait_finished)
541
+ end
542
+ end
543
+
544
+ private def finished(message, transcript_hash, now)
545
+ schedule = key_schedule
546
+ case (result = @authentication.verify_finished(message, schedule, transcript_hash))
547
+ when AuthenticationMessages::Failure then return fail!(result.alert, result.reason)
548
+ end
549
+ # RFC 9001 "Receiving Out-of-Order Protected Packets": no 1-RTT data
550
+ # from the client before its Finished.
551
+ return unless @conductor.change_epochs!(cipher_suite: suite, read: :application,
552
+ secrets: [[:application, :read, schedule.application_traffic_secret(:client)]])
553
+ schedule.resumption!(@conductor.transcript_hash)
554
+ @conductor.transition!(:connected)
555
+ issue_tickets(schedule, now)
556
+ @conductor.event!(Event::HandshakeComplete.new(
557
+ server_name: @server_name, alpn: @alpn, cipher_suite: suite.name, group: @group, resumed: !@resumption.nil?,
558
+ early_data_accepted: @early_data_accepted, peer_certificates: @peer_certificates, peer_verified: peer_verified?
559
+ ))
560
+ end
561
+
562
+ # Issues ticket_count tickets right after the client Finished, sealed
563
+ # under the key of `now`; none, the reason traced, for a client that
564
+ # does not take psk_dhe_ke, without a key that seals now, for a client
565
+ # certificate whose verification a resumption could not repeat, or past
566
+ # 7 days from the full handshake the key material comes from. A ticket
567
+ # past max_ticket_size is not sent.
568
+ private def issue_tickets(schedule, now)
569
+ return unless @config.issues_tickets?
570
+ keys = @config.ticket_keys or return
571
+ ch = @client_hello or raise "no ClientHello to issue tickets for"
572
+ return refuse_ticket(:psk_mode_unsupported) unless psk_dhe_ke?(ch)
573
+ entry = keys.sealing(now) or return refuse_ticket(:ticket_keys_exhausted)
574
+ rules_digest = client_rules_digest
575
+ return refuse_ticket(:client_auth_not_resumable) unless @peer_certificates.empty? || rules_digest
576
+ now_ms = (now.to_r * 1000).floor
577
+ authenticated_at = @authenticated_at ||= now_ms
578
+ return refuse_ticket(:authentication_expired) if now_ms - authenticated_at > Config::MAX_TICKET_LIFETIME * 1000
579
+ client = ticket_client(rules_digest)
580
+ binding = Ticket.binding(@config.ticket_binding, resumption_binding: @resumption_binding, server_name: @server_name || "",
581
+ alpn: @alpn || "")
582
+ early_data = @config.max_early_data_size
583
+ extensions = early_data.positive? ? [Extension::EarlyData::NST.new(max_early_data_size: early_data)] : [] #: Array[Extension::_Extension]
584
+ @config.ticket_count.times do |index|
585
+ nonce = [index].pack("Q>")
586
+ age_add = @keyring.random_bytes(4).unpack1("N") #: Integer
587
+ psk = schedule.ticket_psk(nonce)
588
+ plaintext = Ticket::Plaintext.new(issued_at: now_ms, authenticated_at:, lifetime: @config.ticket_lifetime,
589
+ age_add:, cipher_suite: suite.id, psk:, alpn: @alpn || "".b, early_data_allowed: early_data.positive?, client:,
590
+ early_data_context: @early_data_context)
591
+ ticket = Ticket.seal(plaintext, entry:, binding:, random: @keyring.random_bytes(Ticket::RANDOM_LENGTH))
592
+ psk.clear
593
+ next refuse_ticket(:ticket_too_large) if ticket.bytesize > @config.max_ticket_size
594
+ @conductor.emit_message!(:application, NewSessionTicket.new(ticket_lifetime: @config.ticket_lifetime, ticket_age_add: age_add,
595
+ ticket_nonce: nonce, ticket:, extensions:))
596
+ end
597
+ end
598
+
599
+ # The digest of the rules a client certificate is verified by, nil when
600
+ # a resumption could not verify it the same way: the Verifier cannot
601
+ # say what its rules are, or the Config checks revocation.
602
+ private def client_rules_digest
603
+ policy = @keyring.verifier.resumption_policy
604
+ Ticket.rules_digest(policy) if policy && (@config.verify_flags & Verifier::Default::REVOCATION_FLAGS).zero?
605
+ end
606
+
607
+ # Whether the client's certificate was verified, by this handshake or
608
+ # by the one the ticket resumed comes from.
609
+ private def peer_verified?
610
+ return false if @peer_certificates.empty?
611
+ resumed = @resumption&.ticket&.client
612
+ resumed ? resumed.verified : @keyring.peer_verified?
613
+ end
614
+
615
+ # What a ticket keeps of the client's certificate, nil without one: the
616
+ # leaf, `rules_digest`, the anchor the verified chain ended at, and when
617
+ # every certificate of the chain was valid; a resumed connection's, as
618
+ # the ticket it resumed kept it. A chain nothing verified ended at no
619
+ # anchor, whatever its last certificate: Verifier::None hands back the
620
+ # peer's chain as it came.
621
+ private def ticket_client(rules_digest)
622
+ resumed = @resumption&.ticket&.client
623
+ return resumed if resumed
624
+ leaf = @peer_certificates.first or return nil
625
+ rules_digest or raise "a ticket of a client certificate needs the rules it was verified by"
626
+ anchor = @peer_certificates.fetch(-1).to_der
627
+ anchored = @keyring.peer_verified? && @config.trust_anchors.include?(anchor)
628
+ anchor_digest = anchored ? Ticket.anchor_digest(anchor) : Ticket::NO_ANCHOR
629
+ # Seconds from 1970, as a ticket holds them: a date before is 1970,
630
+ # as much in the past for the checks.
631
+ valid_from = @peer_certificates.map { |cert| cert.not_before.to_i }.max.clamp(0, Ticket::MAX_TIME)
632
+ valid_until = @peer_certificates.map { |cert| cert.not_after.to_i }.min.clamp(0, Ticket::MAX_TIME)
633
+ Ticket::ClientCertificate.new(leaf: leaf.to_der, rules_digest:, anchor_digest:, valid_from:, valid_until:,
634
+ verified: @keyring.peer_verified?)
635
+ end
636
+
637
+ private def refuse_ticket(reason)
638
+ @conductor.trace(Trace::TicketNotIssued.new(reason:)) if @conductor.tracing?
639
+ nil
640
+ end
641
+
642
+ private def server_name(ch)
643
+ case (ext = ch.extension(Extension::ServerName::TYPE))
644
+ when Extension::ServerName::CH
645
+ host_name = ext.host_name or return nil
646
+ name, ignored = ServerName.for_server(host_name)
647
+ @conductor.trace(Trace::ServerNameIgnored.new(reason: ignored)) if ignored && @conductor.tracing?
648
+ name
649
+ end
650
+ end
651
+
652
+ private def psk_dhe_ke?(ch)
653
+ case (ext = ch.extension(Extension::PskKeyExchangeModes::TYPE))
654
+ when Extension::PskKeyExchangeModes then ext.ke_modes.include?(PSK_DHE_KE)
655
+ else false
656
+ end
657
+ end
658
+
659
+ private def signature_algorithms_cert(ch)
660
+ case (ext = ch.extension(Extension::SignatureAlgorithmsCert::TYPE))
661
+ when Extension::SignatureAlgorithmsCert then ext.supported_signature_algorithms
662
+ end
663
+ end
664
+
665
+ private def certificate_authorities(ch)
666
+ case (ext = ch.extension(Extension::CertificateAuthorities::TYPE))
667
+ when Extension::CertificateAuthorities then ext.authorities
668
+ end
669
+ end
670
+ end
671
+ end
672
+ end