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,180 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "securerandom"
4
+ require_relative "config"
5
+ require_relative "crypto"
6
+ require_relative "key_exchange"
7
+ require_relative "masked_inspect"
8
+ require_relative "verifier"
9
+
10
+ module Raiha::TLS
11
+ # What a handshake needs besides its Config and cannot share between
12
+ # Ractors: certificates and private keys, the trust store, the random
13
+ # source and the key exchange provider. Build one per Ractor or process,
14
+ # not per connection; parsing happens here, once.
15
+ #
16
+ # A Keyring is frozen but not shareable, so sending one to another Ractor
17
+ # raises instead of sharing key material by accident.
18
+ class Keyring
19
+ # A certificate chain, leaf first, and the leaf's private key, as given:
20
+ # DER, or PEM, which is parsed the same way.
21
+ class Identity < Data.define(:cert_der, :key_der)
22
+ include MaskedInspect
23
+
24
+ def masked_members = %i[key_der]
25
+ end
26
+
27
+ # An Identity once parsed: the chain as certificates and as DER for the
28
+ # Certificate message, and the private key.
29
+ class Credential < Data.define(:chain, :chain_der, :key)
30
+ def leaf = chain.fetch(0)
31
+ end
32
+
33
+ def self.client(config:, identities: [], random: SecureRandom, key_exchange: KeyExchange::OpenSSL.new, verifier: nil)
34
+ raise ArgumentError, "Keyring.client takes a client Config" unless config.client?
35
+ new(config:, identities:, random:, key_exchange:, verifier:)
36
+ end
37
+
38
+ def self.server(config:, identities:, random: SecureRandom, key_exchange: KeyExchange::OpenSSL.new, verifier: nil)
39
+ raise ArgumentError, "Keyring.server takes a server Config" unless config.server?
40
+ new(config:, identities:, random:, key_exchange:, verifier:)
41
+ end
42
+
43
+ private_class_method :new
44
+
45
+ attr_reader :config, :credentials, :key_exchange, :verifier
46
+
47
+ # The subjects of the Config's trust anchors, as DER, for the
48
+ # certificate_authorities extension of a CertificateRequest.
49
+ attr_reader :trust_anchor_subjects
50
+
51
+ def initialize(config:, identities:, random:, key_exchange:, verifier:)
52
+ @config = config
53
+ @credentials = identities.map { |identity| parse(identity) }.freeze
54
+ if config.server? && @credentials.empty?
55
+ raise ArgumentError, "a server needs at least one identity to authenticate with"
56
+ end
57
+ @random = random
58
+ unsupported = config.groups - key_exchange.supported_groups
59
+ unless unsupported.empty?
60
+ raise ArgumentError, "the key exchange provider does not support #{unsupported.inspect}"
61
+ end
62
+ @key_exchange = key_exchange
63
+ @verifier = verifier || default_verifier(config)
64
+ @trust_anchor_subjects = config.trust_anchors.map do |der|
65
+ anchor = Crypto::Certificate.parse(der) or raise ArgumentError, "a trust anchor is not a DER certificate"
66
+ anchor.subject.to_der.freeze
67
+ end.freeze
68
+ freeze
69
+ end
70
+
71
+ # Where the connection's random bytes come from, for a QUIC connection
72
+ # as well as for TLS, so that a seeded one makes a test repeatable.
73
+ attr_reader :random
74
+
75
+ # A Keyring of this one's Config with `ticket_keys` in place of its
76
+ # own: the certificates, keys, verifier and random source are this
77
+ # one's, not parsed again. A server that turns a TicketKeys.ratchet
78
+ # over builds a Config for each epoch, and a handshake takes only the
79
+ # Keyring of its own Config.
80
+ def with_ticket_keys(ticket_keys) = dup.bind(@config.with(ticket_keys:))
81
+
82
+ # A copy made by `with_ticket_keys` takes its Config.
83
+ protected def bind(config)
84
+ @config = config
85
+ freeze
86
+ end
87
+
88
+ def random_bytes(length) = @random.bytes(length)
89
+
90
+ # False for Verifier::None, so the application can tell that the peer
91
+ # was not authenticated.
92
+ def peer_verified?
93
+ case @verifier
94
+ when Verifier::None then false
95
+ else true
96
+ end
97
+ end
98
+
99
+ # The client's answer to a CertificateRequest (RFC 9846 "Certificate
100
+ # Selection"): the first identity whose key signs with a scheme the
101
+ # server lists, and, when the server names CAs, whose chain has an issuer
102
+ # among them; with the scheme, in our order of preference. nil when none
103
+ # fits, and the client then sends an empty Certificate.
104
+ def client_credential(signature_algorithms:, certificate_authorities:)
105
+ @credentials.each do |credential|
106
+ scheme = scheme_for(credential, signature_algorithms) or next
107
+ if certificate_authorities && credential.chain.none? { |cert| certificate_authorities.include?(cert.issuer.to_der) }
108
+ next
109
+ end
110
+ return [credential, scheme]
111
+ end
112
+ nil
113
+ end
114
+
115
+ # The server's certificate when no PSK was selected. Candidates are the
116
+ # identities whose key signs with a scheme the client lists; among them
117
+ # the best by, in order: valid for `server_name` (RFC 9525), every
118
+ # signature in the chain acceptable to the client, an issuer among the
119
+ # client's certificate_authorities. Ties go to the order of the
120
+ # identities, and with no candidate at all the result is nil.
121
+ def server_credential(server_name:, signature_algorithms:, signature_algorithms_cert:, certificate_authorities:)
122
+ chain_schemes = signature_algorithms_cert || signature_algorithms
123
+ candidates = @credentials.filter_map.with_index do |credential, index|
124
+ scheme = scheme_for(credential, signature_algorithms) or next
125
+ rank = [
126
+ server_name && Verifier::HostName.match?(credential.leaf, server_name) ? 0 : 1,
127
+ chain_signatures_acceptable?(credential, chain_schemes) ? 0 : 1,
128
+ certificate_authorities && credential.chain.any? { |cert| certificate_authorities.include?(cert.issuer.to_der) } ? 0 : 1,
129
+ index
130
+ ]
131
+ [rank, credential, scheme]
132
+ end
133
+ best = candidates.min_by(&:first) or return nil
134
+ [best[1], best[2]]
135
+ end
136
+
137
+ # Our preferred scheme the credential's key signs with, among `offered`.
138
+ private def scheme_for(credential, offered)
139
+ @config.signature_algorithms.each do |name|
140
+ scheme = Config::SCHEMES_BY_NAME.fetch(name)
141
+ return scheme if offered.include?(scheme.id) && Crypto::Signature.key_matches?(scheme, credential.key)
142
+ end
143
+ nil
144
+ end
145
+
146
+ # Every signature in the chain but a self-signed one's is one of
147
+ # `schemes`.
148
+ private def chain_signatures_acceptable?(credential, schemes)
149
+ credential.chain.all? do |cert|
150
+ cert.subject.to_der == cert.issuer.to_der || schemes.include?(Crypto::Certificate.signature_scheme_id(cert))
151
+ end
152
+ end
153
+
154
+ private def instance_variables_to_inspect = %i[@config @verifier]
155
+
156
+ private def parse(identity)
157
+ raise ArgumentError, "identities must be Keyring::Identity values" unless identity.is_a?(Identity)
158
+ unless identity.cert_der.is_a?(Array) && !identity.cert_der.empty?
159
+ raise ArgumentError, "an identity needs a certificate chain, leaf first"
160
+ end
161
+ chain = identity.cert_der.map do |der|
162
+ Crypto::Certificate.parse(der) || raise(ArgumentError, "an identity's certificate does not parse")
163
+ end
164
+ key = Crypto::Signature.private_key(identity.key_der) or raise ArgumentError, "an identity's private key does not parse"
165
+ leaf = chain.fetch(0)
166
+ raise ArgumentError, "an identity's private key does not match its certificate" unless leaf.check_private_key(key)
167
+ Credential.new(chain: chain.freeze, chain_der: chain.map { |cert| cert.to_der.freeze }.freeze, key:)
168
+ end
169
+
170
+ # A Verifier::Default over the Config's trust anchors. With none, it
171
+ # could accept nobody, which is a mistake to report now.
172
+ private def default_verifier(config)
173
+ authenticates_peer = config.client? || config.client_auth != :none
174
+ if authenticates_peer && config.trust_anchors.empty?
175
+ raise ArgumentError, "the default verifier needs trust_anchors in the Config (or pass verifier:)"
176
+ end
177
+ Verifier::Default.new(store: Verifier::Default.store(config.trust_anchors), verify_flags: config.verify_flags)
178
+ end
179
+ end
180
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::TLS
4
+ # Shows the members named by `#masked_members` only by size in `inspect`,
5
+ # `to_s` and `pp`, so secrets stay out of logs. `==` and `to_h` still see
6
+ # every member.
7
+ #
8
+ # `Data#inspect` does not consult `instance_variables_to_inspect`, so this
9
+ # replaces it.
10
+ module MaskedInspect
11
+ def inspect
12
+ fields = to_h.map do |name, value|
13
+ shown = masked_members.include?(name) ? MaskedInspect.mask(value) : value.inspect
14
+ "#{name}=#{shown}"
15
+ end
16
+ "#<data #{self.class.name} #{fields.join(", ")}>"
17
+ end
18
+
19
+ def to_s = inspect
20
+
21
+ def pretty_print(q) = q.text(inspect)
22
+
23
+ def self.mask(value)
24
+ if value.is_a?(String)
25
+ "[#{value.bytesize} bytes]"
26
+ elsif value.is_a?(Array)
27
+ "[#{value.map { |v| mask(v) }.join(", ")}]"
28
+ else
29
+ "[masked]"
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,32 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "masked_inspect"
4
+
5
+ module Raiha::TLS
6
+ # What the handshake core hands to its transport, in one ordered queue.
7
+ #
8
+ # A Secret comes out when its key may be used, and every Message and Alert
9
+ # carries the epoch whose key sends it, so the consumer only has to handle
10
+ # the queue in order. Within one trigger the Secrets that became usable
11
+ # come before the Messages. The one exception is a TCP KeyUpdate, sent
12
+ # under the old key and followed by the new write Secret.
13
+ module Output
14
+ # One handshake message, header included.
15
+ class Message < Data.define(:epoch, :bytes)
16
+ end
17
+
18
+ # A traffic secret, not a key: QUIC derives its own keys from it with
19
+ # labels of its own. `direction` is :read or :write; `cipher_suite` is the
20
+ # CipherSuite descriptor.
21
+ class Secret < Data.define(:epoch, :direction, :secret, :cipher_suite)
22
+ include MaskedInspect
23
+
24
+ def masked_members = %i[secret]
25
+ end
26
+
27
+ # `epoch` is the write epoch when the alert was raised, the one the peer
28
+ # is reading.
29
+ class Alert < Data.define(:level, :description, :epoch)
30
+ end
31
+ end
32
+ end
@@ -0,0 +1,82 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::TLS
4
+ # What differs between TLS over TCP and TLS inside QUIC, as one set of
5
+ # flags. RFC 9001 puts a number of "must not"s on the TLS side; gathering
6
+ # them here keeps them out of the state machine's branches, and reading
7
+ # `TCP` next to `QUIC` shows everything QUIC changes.
8
+ class Profile < Data.define(
9
+ :record_layer,
10
+ :compatibility_mode,
11
+ :reject_nonempty_session_id,
12
+ :send_end_of_early_data,
13
+ :allow_key_update_message,
14
+ :required_extensions,
15
+ :forbidden_extensions,
16
+ :max_early_data_size_policy,
17
+ :never_select_cipher_suites,
18
+ :all_alerts_fatal,
19
+ :require_alpn,
20
+ :protocol_violation_reasons
21
+ )
22
+ QUIC_TRANSPORT_PARAMETERS = 0x39
23
+
24
+ TCP = Ractor.make_shareable(new(
25
+ record_layer: true,
26
+ compatibility_mode: true,
27
+ reject_nonempty_session_id: false,
28
+ send_end_of_early_data: true,
29
+ allow_key_update_message: true,
30
+ required_extensions: [],
31
+ # RFC 9001 "QUIC Transport Parameters Extension": an endpoint that
32
+ # receives quic_transport_parameters over a TLS connection that is not
33
+ # QUIC must abort with unsupported_extension.
34
+ forbidden_extensions: [QUIC_TRANSPORT_PARAMETERS],
35
+ max_early_data_size_policy: :free,
36
+ never_select_cipher_suites: [],
37
+ all_alerts_fatal: false,
38
+ require_alpn: false,
39
+ protocol_violation_reasons: []
40
+ ))
41
+
42
+ QUIC = Ractor.make_shareable(new(
43
+ # RFC 9001 "Carrying TLS Messages": handshake messages go in CRYPTO
44
+ # frames, not records.
45
+ record_layer: false,
46
+ # RFC 9001 "Prohibit TLS Middlebox Compatibility Mode": a client must
47
+ # not request it, and a server should treat a nonempty
48
+ # legacy_session_id as a PROTOCOL_VIOLATION.
49
+ compatibility_mode: false,
50
+ reject_nonempty_session_id: true,
51
+ # RFC 9001 "Removing the EndOfEarlyData Message".
52
+ send_end_of_early_data: false,
53
+ # RFC 9001 "Key Update": a KeyUpdate message is a connection error.
54
+ allow_key_update_message: false,
55
+ # RFC 9001 "QUIC Transport Parameters Extension": missing_extension
56
+ # without it.
57
+ required_extensions: [QUIC_TRANSPORT_PARAMETERS],
58
+ forbidden_extensions: [],
59
+ # RFC 9001 "Enabling 0-RTT": max_early_data_size must be 0xffffffff.
60
+ max_early_data_size_policy: :sentinel,
61
+ # RFC 9001 "Header Protection" defines none for this suite. It is never
62
+ # selected, but an offer of it is not rejected either.
63
+ never_select_cipher_suites: %i[TLS_AES_128_CCM_8_SHA256],
64
+ # QUIC carries only fatal errors, as CONNECTION_CLOSE.
65
+ all_alerts_fatal: true,
66
+ # RFC 9001 "Application-Layer Protocol Negotiation": QUIC endpoints must
67
+ # agree on a protocol with ALPN, failing with no_application_protocol.
68
+ require_alpn: true,
69
+ # Failures the TLS core detects for which RFC 9001 asks for
70
+ # PROTOCOL_VIOLATION rather than CRYPTO_ERROR. The QUIC binding looks up
71
+ # Event::Failed#reason here.
72
+ protocol_violation_reasons: %i[
73
+ handshake_data_spans_key_change
74
+ data_after_client_hello
75
+ wrong_epoch
76
+ post_handshake_certificate_request
77
+ max_early_data_size_not_sentinel
78
+ nonempty_legacy_session_id
79
+ ]
80
+ ))
81
+ end
82
+ end
@@ -0,0 +1,228 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../error"
4
+ require_relative "protection"
5
+
6
+ module Raiha::TLS
7
+ module Record
8
+ CONTENT_TYPES = { change_cipher_spec: 20, alert: 21, handshake: 22, application_data: 23 }.freeze #: Hash[Symbol, Integer]
9
+ CONTENT_TYPE_NAMES = CONTENT_TYPES.invert.freeze #: Hash[Integer, Symbol]
10
+
11
+ HEADER_LENGTH = 5
12
+ MAX_PLAINTEXT = 1 << 14
13
+ # TLSCiphertext.length may exceed the plaintext by up to 256 bytes.
14
+ MAX_EXPANSION = 256
15
+ # RFC 8449 counts the content type byte, so the default limit is one more
16
+ # than MAX_PLAINTEXT.
17
+ DEFAULT_SIZE_LIMIT = MAX_PLAINTEXT + 1
18
+
19
+ # One record's content, opened. `content_type` is a Symbol of
20
+ # CONTENT_TYPES. A change_cipher_spec record is only ever unprotected.
21
+ class Plaintext < Data.define(:content_type, :payload)
22
+ end
23
+
24
+ # Why the record layer gave up on the peer's bytes, as the alert to send
25
+ # and a reason for Event::Failed. A value, not an exception: over TCP a
26
+ # record that does not open ends the connection (bad_record_mac), which
27
+ # the caller decides, unlike QUIC, which drops such packets.
28
+ class Failure < Data.define(:alert, :reason)
29
+ end
30
+
31
+ BAD_RECORD_MAC = Failure.new(alert: :bad_record_mac, reason: :bad_record_mac)
32
+
33
+ # The TLS record layer for Profile::TCP (RFC 9846 "Record Protocol").
34
+ # Independent of the handshake: it holds a key table per epoch and
35
+ # direction, filled from Output::Secret in queue order, and frames,
36
+ # protects, opens and fragments records. Each record is read under the
37
+ # epoch the caller names, so the caller can move the read epoch between
38
+ # two records of one segment.
39
+ class Layer
40
+ def initialize(profile:)
41
+ raise ArgumentError, "a record layer needs a profile with one, as Profile::TCP" unless profile.record_layer
42
+ @buffer = "".b
43
+ @read = {} #: Hash[epoch, Protection]
44
+ @write = {} #: Hash[epoch, Protection]
45
+ @send_size_limit = DEFAULT_SIZE_LIMIT
46
+ @receive_size_limit = DEFAULT_SIZE_LIMIT
47
+ # The client's 0-RTT skipped so far, and whether skipping has ended.
48
+ @early_data_skipped = 0
49
+ @skipping_ended = false
50
+ end
51
+
52
+ # Puts a key in the table, replacing the one of the same epoch and
53
+ # direction: a KeyUpdate's next generation goes in the same way.
54
+ def install(direction:, epoch:, secret:, cipher_suite:)
55
+ raise UsageError, ":initial records are not protected" if epoch == :initial
56
+ table = direction == :read ? @read : @write
57
+ table[epoch]&.discard!
58
+ table[epoch] = Protection.new(secret:, cipher_suite:)
59
+ nil
60
+ end
61
+
62
+ # The record_size_limit values in force (RFC 8449): `send` is the
63
+ # peer's, `receive` our own once the peer has agreed to it. Both count
64
+ # the content type byte of a protected record.
65
+ def limit_sizes(send: DEFAULT_SIZE_LIMIT, receive: DEFAULT_SIZE_LIMIT)
66
+ @send_size_limit = send.clamp(..DEFAULT_SIZE_LIMIT)
67
+ @receive_size_limit = receive.clamp(..DEFAULT_SIZE_LIMIT)
68
+ nil
69
+ end
70
+
71
+ def <<(bytes)
72
+ @buffer << bytes
73
+ self
74
+ end
75
+
76
+ def pending_bytes = @buffer.bytesize
77
+
78
+ # The next whole record, opened with `epoch`'s key: a Plaintext, a
79
+ # Failure, or nil until a whole record is buffered. A server that did
80
+ # not take the client's 0-RTT gives `skip_early_data`, the most of it
81
+ # to skip in bytes (Machine#skip_early_data_limit).
82
+ def read(epoch:, skip_early_data: nil)
83
+ loop do
84
+ return nil if @buffer.bytesize < HEADER_LENGTH
85
+ # The version field is ignored, as RFC 9846 asks. Only a record of
86
+ # application_data is ever protected, so any other is held to the
87
+ # plaintext limit as soon as its header is in.
88
+ type, length = @buffer.unpack("Cx2n").map(&:to_i)
89
+ # A type no record has is unexpected_message as soon as the header
90
+ # is in, so that what is no TLS record, an SSL 2.0 ClientHello say,
91
+ # is not waited on for a length it does not have.
92
+ return Failure.new(alert: :unexpected_message, reason: :unexpected_record) unless CONTENT_TYPE_NAMES.key?(type)
93
+ limit = type == CONTENT_TYPES.fetch(:application_data) ? MAX_PLAINTEXT + MAX_EXPANSION : MAX_PLAINTEXT
94
+ return Failure.new(alert: :record_overflow, reason: :record_too_large) if length > limit # steep:ignore
95
+ return nil if @buffer.bytesize < HEADER_LENGTH + length # steep:ignore
96
+ header = @buffer.byteslice(0, HEADER_LENGTH).to_s
97
+ fragment = @buffer.byteslice(HEADER_LENGTH, length).to_s # steep:ignore
98
+ @buffer = @buffer.byteslice((HEADER_LENGTH + length)..).to_s # steep:ignore
99
+ result = epoch == :initial ? unprotected(type, fragment) : protected(epoch, type, header, fragment) # steep:ignore
100
+ return result unless skip_early_data && skipped?(epoch, type, result) # steep:ignore
101
+ # Too short for a tag and a content type, it was never 0-RTT.
102
+ return BAD_RECORD_MAC if fragment.bytesize <= Crypto::AEAD::TAG_LENGTH
103
+ # The plaintext the record carried, at most, as its tag and content
104
+ # type are not 0-RTT; an empty one counts once, so that the records
105
+ # tried under the handshake key are bounded too.
106
+ @early_data_skipped += (fragment.bytesize - Crypto::AEAD::TAG_LENGTH - 1).clamp(1, MAX_PLAINTEXT)
107
+ return Failure.new(alert: :unexpected_message, reason: :too_much_early_data) if @early_data_skipped > skip_early_data
108
+ end
109
+ end
110
+
111
+ # The records carrying `payload`, split to fit the peer's limit and
112
+ # protected with `epoch`'s key unless it is :initial.
113
+ def write(content_type:, payload:, epoch:)
114
+ type = CONTENT_TYPES.fetch(content_type) { raise ArgumentError, "unknown content type #{content_type.inspect}" }
115
+ if epoch == :initial
116
+ fragments(payload, fragment_size(epoch)).map { |fragment| [type, Protection::LEGACY_RECORD_VERSION, fragment.bytesize].pack("Cnn") + fragment }.join
117
+ else
118
+ protection = @write.fetch(epoch) { raise UsageError, "no write key for #{epoch.inspect}" }
119
+ fragments(payload, fragment_size(epoch)).map { |fragment| protection.seal(fragment + type.chr) }.join
120
+ end
121
+ end
122
+
123
+ # The most content one record of `epoch` carries: a protected record
124
+ # keeps to the peer's limit, less its content type byte.
125
+ def fragment_size(epoch) = epoch == :initial ? MAX_PLAINTEXT : @send_size_limit - 1
126
+
127
+ # Records written under `epoch`'s current key.
128
+ def records_written(epoch) = @write[epoch]&.sequence_number || 0
129
+
130
+ # Whether `epoch`'s write key has room for only one more record within
131
+ # its cipher suite's confidentiality limit over TCP: the KeyUpdate that
132
+ # replaces it must go out now (RFC 9846 "Limits on Key Usage").
133
+ def key_update_due?(epoch)
134
+ protection = @write[epoch] or return false
135
+ limit = protection.cipher_suite.confidentiality_limit(:tcp) or return false
136
+ protection.sequence_number + 1 >= limit
137
+ end
138
+
139
+ def discard!
140
+ (@read.values + @write.values).each(&:discard!)
141
+ @read.clear
142
+ @write.clear
143
+ @buffer.clear
144
+ nil
145
+ end
146
+
147
+ # RFC 9846 "Early Data Indication": the client's 0-RTT that was not
148
+ # taken comes until its next flight, and is skipped. While the server
149
+ # reads in the clear, after a HelloRetryRequest, that is each record of
150
+ # application_data; under the handshake key, each record that does not
151
+ # open. Any other record ends the skipping for good, but for the
152
+ # change_cipher_spec of middlebox compatibility, which a client sends
153
+ # before its 0-RTT.
154
+ private def skipped?(epoch, type, result)
155
+ return false if @skipping_ended
156
+ rejected = case epoch
157
+ when :initial then type == CONTENT_TYPES.fetch(:application_data)
158
+ when :handshake then result == BAD_RECORD_MAC
159
+ else false
160
+ end
161
+ @skipping_ended = true unless rejected || type == CONTENT_TYPES.fetch(:change_cipher_spec)
162
+ rejected
163
+ end
164
+
165
+ # An empty payload is one empty record: zero-length application data is
166
+ # allowed, and the caller never writes an empty handshake message.
167
+ private def fragments(payload, size)
168
+ return ["".b] if payload.empty?
169
+ (0...payload.bytesize).step(size).map { |offset| payload.byteslice(offset, size).to_s }
170
+ end
171
+
172
+ # Before any key: handshake, alert and change_cipher_spec records in
173
+ # the clear. Application data cannot come yet.
174
+ private def unprotected(type, fragment)
175
+ name = CONTENT_TYPE_NAMES[type]
176
+ return Failure.new(alert: :unexpected_message, reason: :unexpected_record) if name.nil? || name == :application_data
177
+ return Failure.new(alert: :record_overflow, reason: :record_too_large) if fragment.bytesize > MAX_PLAINTEXT
178
+ return Failure.new(alert: :unexpected_message, reason: :empty_handshake_record) if name == :handshake && fragment.empty?
179
+ return Failure.new(alert: :unexpected_message, reason: :empty_alert_record) if name == :alert && fragment.empty?
180
+ return change_cipher_spec(:initial, fragment) if name == :change_cipher_spec
181
+ Plaintext.new(content_type: name, payload: fragment)
182
+ end
183
+
184
+ # Once keys are in place every record is protected, but for the
185
+ # change_cipher_spec of middlebox compatibility and an alert from a
186
+ # peer that failed before it had the handshake keys.
187
+ private def protected(epoch, type, header, fragment)
188
+ case CONTENT_TYPE_NAMES[type]
189
+ when :application_data then open(epoch, header, fragment)
190
+ when :change_cipher_spec then change_cipher_spec(epoch, fragment)
191
+ when :alert then epoch == :handshake ? unprotected(type, fragment) : Failure.new(alert: :unexpected_message, reason: :unprotected_record)
192
+ else Failure.new(alert: :unexpected_message, reason: :unprotected_record)
193
+ end
194
+ end
195
+
196
+ # The single byte 0x01 a middlebox-compatible peer sends, which only
197
+ # comes before the peer's Finished, that is, before the :application
198
+ # read keys (RFC 9846 "Record Protocol"). Anything else is an
199
+ # unexpected record. Whether one may come before the first ClientHello
200
+ # is the caller's to judge.
201
+ private def change_cipher_spec(epoch, fragment)
202
+ return Failure.new(alert: :unexpected_message, reason: :unexpected_change_cipher_spec) if epoch == :application || fragment != "\x01".b
203
+ Plaintext.new(content_type: :change_cipher_spec, payload: fragment)
204
+ end
205
+
206
+ private def open(epoch, header, fragment)
207
+ protection = @read.fetch(epoch) { raise UsageError, "no read key for #{epoch.inspect}" }
208
+ if fragment.bytesize > @receive_size_limit + MAX_EXPANSION - 1
209
+ return Failure.new(alert: :record_overflow, reason: :record_too_large)
210
+ end
211
+ inner = protection.open(header, fragment) or return BAD_RECORD_MAC
212
+ return Failure.new(alert: :record_overflow, reason: :record_too_large) if inner.bytesize > @receive_size_limit
213
+ # TLSInnerPlaintext: the content, its type, then zeros.
214
+ last = inner.bytesize - 1
215
+ last -= 1 while last >= 0 && inner.getbyte(last) == 0
216
+ return Failure.new(alert: :unexpected_message, reason: :no_content_type) if last < 0
217
+ name = CONTENT_TYPE_NAMES[inner.getbyte(last).to_i]
218
+ return Failure.new(alert: :unexpected_message, reason: :unexpected_record) if name.nil? || name == :change_cipher_spec
219
+ content = inner.byteslice(0, last).to_s
220
+ # RFC 8446 "Record Layer": a Handshake or Alert record of no content
221
+ # is unexpected_message.
222
+ return Failure.new(alert: :unexpected_message, reason: :empty_handshake_record) if name == :handshake && content.empty?
223
+ return Failure.new(alert: :unexpected_message, reason: :empty_alert_record) if name == :alert && content.empty?
224
+ Plaintext.new(content_type: name, payload: content)
225
+ end
226
+ end
227
+ end
228
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../crypto"
4
+ require_relative "../key_schedule"
5
+
6
+ module Raiha::TLS
7
+ module Record
8
+ # One direction's protection under one traffic secret (RFC 9846 "Record
9
+ # Payload Protection" and "Per-Record Nonce"): the AEAD keyed from the
10
+ # secret, the nonce from the IV and the record sequence number, and the
11
+ # count of records it has protected or opened.
12
+ class Protection
13
+ CONTENT_TYPE_APPLICATION_DATA = 23
14
+ LEGACY_RECORD_VERSION = 0x0303
15
+
16
+ attr_reader :cipher_suite, :sequence_number
17
+
18
+ def initialize(secret:, cipher_suite:)
19
+ @cipher_suite = cipher_suite
20
+ hash = cipher_suite.hash_algorithm
21
+ key = KeySchedule.expand_label(secret:, label: KeySchedule::LABELS.fetch(:key), length: cipher_suite.key_length, hash:)
22
+ @iv = KeySchedule.expand_label(secret:, label: KeySchedule::LABELS.fetch(:iv), length: cipher_suite.iv_length, hash:)
23
+ @aead = Crypto::AEAD.new(cipher_suite.aead, key)
24
+ key.clear
25
+ @sequence_number = 0
26
+ end
27
+
28
+ # The whole record that protects `inner_plaintext` (TLSInnerPlaintext:
29
+ # content, its type, and any zero padding).
30
+ def seal(inner_plaintext)
31
+ header = [CONTENT_TYPE_APPLICATION_DATA, LEGACY_RECORD_VERSION, inner_plaintext.bytesize + Crypto::AEAD::TAG_LENGTH].pack("Cnn")
32
+ header + @aead.seal(nonce: next_nonce, aad: header, plaintext: inner_plaintext)
33
+ end
34
+
35
+ # The TLSInnerPlaintext of the record with `header` and
36
+ # `encrypted_record`, or nil when it does not authenticate. Only a
37
+ # record that opens is counted: a server that did not take the
38
+ # client's 0-RTT tries its records under the handshake key and skips
39
+ # those that do not open (Layer#read).
40
+ def open(header, encrypted_record)
41
+ inner = @aead.open(nonce: nonce(@sequence_number), aad: header, ciphertext: encrypted_record)
42
+ @sequence_number += 1 if inner
43
+ inner
44
+ end
45
+
46
+ def discard!
47
+ @iv.clear
48
+ @aead.discard!
49
+ end
50
+
51
+ private def instance_variables_to_inspect = %i[@cipher_suite @sequence_number]
52
+
53
+ private def next_nonce
54
+ sequence = @sequence_number
55
+ @sequence_number += 1
56
+ nonce(sequence)
57
+ end
58
+
59
+ # The IV XORed with `sequence`, the number of records protected or
60
+ # opened under this key before. Every suite here has a 12-byte IV.
61
+ private def nonce(sequence)
62
+ high, middle, low = @iv.unpack("N3")
63
+ [high.to_i, middle.to_i ^ (sequence >> 32), low.to_i ^ (sequence & 0xffff_ffff)].pack("N3")
64
+ end
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,11 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::TLS
4
+ # The TLS record layer, used over TCP only (Profile::TCP). QUIC carries
5
+ # handshake messages in CRYPTO frames and protects packets itself.
6
+ module Record
7
+ end
8
+ end
9
+
10
+ require_relative "record/protection"
11
+ require_relative "record/layer"
@@ -0,0 +1,42 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "verifier"
4
+
5
+ module Raiha::TLS
6
+ # The normal form of server_name at the edges of a handshake: ASCII
7
+ # lowercase without a trailing dot. ClientHelloInfo, HandshakeComplete,
8
+ # certificate selection and RFC 9525 matching all see this form.
9
+ module ServerName
10
+ MAX_LENGTH = 253
11
+ LABEL = /\A[a-z0-9-]{1,63}\z/
12
+
13
+ # The SNI to send and the name to match the certificate against, from
14
+ # what the application asked for. An IP address literal is matched but
15
+ # never sent as SNI (RFC 6066 "Server Name Indication"). A name that is not
16
+ # an ASCII host name (U-labels included: pass A-labels) is an
17
+ # ArgumentError.
18
+ def self.for_client(name)
19
+ return [nil, name] if Verifier::HostName.ip_address(name)
20
+ normal = normalize(name) or raise ArgumentError, "#{name.inspect} is not an ASCII host name"
21
+ [normal, normal]
22
+ end
23
+
24
+ # The peer's host_name in normal form, or nil and why it was ignored:
25
+ # :ip_literal or :invalid_syntax. RFC 6066 lets a server go on without a
26
+ # name it does not recognize, which is kinder to clients that send an
27
+ # address or a trailing dot than failing.
28
+ def self.for_server(host_name)
29
+ return [nil, :ip_literal] if Verifier::HostName.ip_address(host_name)
30
+ normal = normalize(host_name)
31
+ normal ? [normal, nil] : [nil, :invalid_syntax]
32
+ end
33
+
34
+ # One trailing dot is dropped: RFC 9525 treats the two as the same name.
35
+ def self.normalize(name)
36
+ return nil unless name.ascii_only?
37
+ normal = name.downcase.delete_suffix(".")
38
+ return nil if normal.empty? || normal.bytesize > MAX_LENGTH
39
+ normal.split(".", -1).all? { |label| label.match?(LABEL) } ? normal : nil
40
+ end
41
+ end
42
+ end