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,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "error"
4
+
5
+ module Raiha::TLS::Codec
6
+ # An append-only BINARY buffer. `#vector` writes a zero length prefix,
7
+ # yields, and then fills the prefix in with `setbyte`, so nested vectors are
8
+ # written in one pass without allocating a String per length.
9
+ #
10
+ # The buffer is always BINARY: `String#<<` with an Integer appends a code
11
+ # point, which is one byte only in a BINARY string.
12
+ class Writer
13
+ PAD = Ractor.make_shareable(["".b, "\0".b, "\0\0".b, "\0\0\0".b]) #: Array[String]
14
+
15
+ def initialize
16
+ @buf = String.new(encoding: Encoding::BINARY)
17
+ end
18
+
19
+ def u8(v)
20
+ check_range(v, 0xff)
21
+ @buf << v
22
+ nil
23
+ end
24
+
25
+ def u16(v)
26
+ check_range(v, 0xffff)
27
+ @buf << (v >> 8) << (v & 0xff)
28
+ nil
29
+ end
30
+
31
+ def u24(v)
32
+ check_range(v, 0xffffff)
33
+ @buf << (v >> 16) << ((v >> 8) & 0xff) << (v & 0xff)
34
+ nil
35
+ end
36
+
37
+ def u32(v)
38
+ check_range(v, 0xffffffff)
39
+ @buf << (v >> 24) << ((v >> 16) & 0xff) << ((v >> 8) & 0xff) << (v & 0xff)
40
+ nil
41
+ end
42
+
43
+ def bytes(s)
44
+ @buf << (s.encoding == Encoding::BINARY ? s : s.b)
45
+ nil
46
+ end
47
+
48
+ # Writes a `len_bytes`-byte length prefix followed by whatever the block
49
+ # writes. The length is filled in after the block returns. `min:` and
50
+ # `max:` are the bounds from the vector's definition, the same ones
51
+ # `Reader#vector` checks, so nothing written here fails to parse for its
52
+ # length.
53
+ def vector(len_bytes, min: 0, max: nil)
54
+ pad = PAD[len_bytes] or raise ArgumentError, "length prefix must be 1 to 3 bytes: #{len_bytes}"
55
+ pos = @buf.bytesize
56
+ @buf << pad
57
+ yield
58
+ len = @buf.bytesize - pos - len_bytes
59
+ raise EncodeError, "vector too long: #{len} bytes" if len >= (1 << (8 * len_bytes))
60
+ raise EncodeError, "vector length #{len} is out of range #{min}..#{max}" if len < min || (max && len > max)
61
+ case len_bytes
62
+ when 1
63
+ @buf.setbyte(pos, len)
64
+ when 2
65
+ @buf.setbyte(pos, len >> 8)
66
+ @buf.setbyte(pos + 1, len & 0xff)
67
+ else
68
+ @buf.setbyte(pos, len >> 16)
69
+ @buf.setbyte(pos + 1, (len >> 8) & 0xff)
70
+ @buf.setbyte(pos + 2, len & 0xff)
71
+ end
72
+ nil
73
+ end
74
+
75
+ def to_s = @buf
76
+
77
+ private def check_range(v, max)
78
+ raise EncodeError, "#{v} is out of range 0..#{max}" unless 0 <= v && v <= max
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "codec/error"
4
+ require_relative "codec/reader"
5
+ require_relative "codec/writer"
@@ -0,0 +1,318 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "iana"
4
+ require_relative "cipher_suite"
5
+ require_relative "signature_scheme"
6
+ require_relative "profile"
7
+ require_relative "extension"
8
+ require_relative "ticket_keys"
9
+ require_relative "ticket"
10
+
11
+ module Raiha::TLS
12
+ # The settings a handshake runs with, shared by every connection and every
13
+ # Ractor: a Config is deeply frozen and Ractor-shareable from the moment it
14
+ # is built. Key material, the random source and anything else that cannot
15
+ # be shared lives in a Keyring instead.
16
+ #
17
+ # Enumerated settings are given as Symbols and checked against what this
18
+ # implementation knows. A setting that cannot work raises ArgumentError
19
+ # here rather than failing a handshake later.
20
+ class Config
21
+ DEFAULT_CIPHER_SUITES = %i[TLS_AES_128_GCM_SHA256 TLS_AES_256_GCM_SHA384 TLS_CHACHA20_POLY1305_SHA256].freeze
22
+
23
+ DEFAULT_GROUPS = %i[x25519 secp256r1 secp384r1].freeze
24
+
25
+ # Schemes for a CertificateVerify, in our order of preference.
26
+ DEFAULT_SIGNATURE_ALGORITHMS = %i[
27
+ ecdsa_secp256r1_sha256 rsa_pss_rsae_sha256 ed25519
28
+ ecdsa_secp384r1_sha384 rsa_pss_rsae_sha384 rsa_pss_rsae_sha512
29
+ ].freeze
30
+
31
+ # Schemes accepted in certificate chains, sent as signature_algorithms_cert.
32
+ # RSASSA-PKCS1-v1_5 still signs most of the Web PKI.
33
+ DEFAULT_SIGNATURE_ALGORITHMS_CERT = (DEFAULT_SIGNATURE_ALGORITHMS + %i[
34
+ ecdsa_secp521r1_sha512 rsa_pkcs1_sha256 rsa_pkcs1_sha384 rsa_pkcs1_sha512
35
+ ]).freeze
36
+
37
+ # Extensions the state machine builds, or builds from a typed setting
38
+ # here. Each extension has exactly one way to be set, so these cannot be
39
+ # given in `extensions:`.
40
+ RESERVED_EXTENSIONS = [
41
+ Extension::SupportedVersions::TYPE, Extension::KeyShare::TYPE, Extension::SupportedGroups::TYPE,
42
+ Extension::SignatureAlgorithms::TYPE, Extension::SignatureAlgorithmsCert::TYPE,
43
+ Extension::PskKeyExchangeModes::TYPE, Extension::PreSharedKey::TYPE, Extension::EarlyData::TYPE,
44
+ Extension::Cookie::TYPE,
45
+ Extension::ServerName::TYPE, Extension::Alpn::TYPE, Extension::RecordSizeLimit::TYPE,
46
+ Extension::CompressCertificate::TYPE, Extension::PostHandshakeAuth::TYPE
47
+ ].freeze
48
+
49
+ # HKDF-Expand-Label takes a label of 7 to 255 bytes, "tls13 " included.
50
+ EXPORTER_LABEL_LENGTH = 1..249
51
+
52
+ # RFC 9846 "New Session Ticket Message": a ticket lives 7 days at most.
53
+ MAX_TICKET_LIFETIME = 604_800
54
+ DEFAULT_TICKET_LIFETIME = 7200
55
+ DEFAULT_TICKET_COUNT = 2
56
+ # A ticket fits a leaf of ML-DSA-87 for client authentication.
57
+ DEFAULT_MAX_TICKET_SIZE = 8192
58
+ # A ticket rides in a ClientHello, which an Acceptor takes up to 16 KiB;
59
+ # the rest of a ClientHello with a post-quantum key share needs about
60
+ # 2.3 KB, and 4 KiB is left for it, so no Config issues a ticket its own
61
+ # server would refuse.
62
+ MAX_TICKET_SIZE = 12_288
63
+ # max_early_data_size is a uint32.
64
+ MAX_EARLY_DATA_SIZE = 0xffff_ffff
65
+
66
+ CIPHER_SUITES_BY_NAME = CipherSuite::SUITES.values.to_h { |suite| [suite.name, suite] }.freeze
67
+ GROUPS_BY_NAME = IANA::NAMED_GROUPS.invert.freeze
68
+ SCHEMES_BY_NAME = SignatureScheme::SCHEMES.values.to_h { |scheme| [scheme.name, scheme] }.freeze
69
+
70
+ def self.client(**options) = new(role: :client, **options)
71
+
72
+ def self.server(**options) = new(role: :server, **options)
73
+
74
+ # A client Config whose ClientHello depends only on the random and the
75
+ # key shares: no extension permutation and no GREASE. For test vectors
76
+ # and byte-for-byte comparisons.
77
+ def self.deterministic(**options) = client(permute_extensions: false, grease: false, **options)
78
+
79
+ attr_reader :role, :profile, :cipher_suites, :groups, :signature_algorithms, :signature_algorithms_cert,
80
+ :alpn, :registry, :extensions, :max_handshake_message_size, :max_certificate_message_size,
81
+ :max_certificate_chain_length, :permute_extensions, :grease, :exporter_labels, :record_size_limit,
82
+ :trust_anchors, :verify_flags, :client_auth, :certificate_authorities, :require_server_name,
83
+ :resumption, :ticket_keys, :ticket_lifetime, :ticket_count, :max_ticket_size, :resumption_scope, :max_early_data_size,
84
+ :ticket_binding, :trust_anchor_digests
85
+
86
+ # The wire values of the Symbol settings above, in the same order.
87
+ attr_reader :cipher_suite_ids, :group_ids, :signature_algorithm_ids, :signature_algorithm_cert_ids
88
+
89
+ def initialize(
90
+ role:,
91
+ profile: Profile::TCP,
92
+ cipher_suites: DEFAULT_CIPHER_SUITES,
93
+ groups: DEFAULT_GROUPS,
94
+ signature_algorithms: DEFAULT_SIGNATURE_ALGORITHMS,
95
+ signature_algorithms_cert: DEFAULT_SIGNATURE_ALGORITHMS_CERT,
96
+ alpn: [],
97
+ registry: Extension::Registry::BUILTIN,
98
+ extensions: [],
99
+ max_handshake_message_size: 16 * 1024,
100
+ max_certificate_message_size: 256 * 1024,
101
+ max_certificate_chain_length: 10,
102
+ permute_extensions: true,
103
+ grease: true,
104
+ exporter_labels: [],
105
+ record_size_limit: nil,
106
+ trust_anchors: [],
107
+ verify_flags: 0,
108
+ client_auth: :none,
109
+ certificate_authorities: true,
110
+ require_server_name: false,
111
+ resumption: true,
112
+ ticket_keys: nil,
113
+ ticket_key: nil,
114
+ ticket_lifetime: DEFAULT_TICKET_LIFETIME,
115
+ ticket_count: nil,
116
+ max_ticket_size: DEFAULT_MAX_TICKET_SIZE,
117
+ resumption_scope: "",
118
+ max_early_data_size: 0
119
+ )
120
+ raise ArgumentError, "role must be :client or :server, not #{role.inspect}" unless %i[client server].include?(role)
121
+ raise ArgumentError, "profile must be a Profile" unless profile.is_a?(Profile)
122
+ @role = role
123
+ @profile = profile
124
+
125
+ @cipher_suites = names(:cipher_suites, cipher_suites, CIPHER_SUITES_BY_NAME)
126
+ @cipher_suite_ids = @cipher_suites.map { |name| CIPHER_SUITES_BY_NAME.fetch(name).id }
127
+ @groups = names(:groups, groups, GROUPS_BY_NAME)
128
+ @group_ids = @groups.map { |name| GROUPS_BY_NAME.fetch(name) }
129
+ @signature_algorithms = names(:signature_algorithms, signature_algorithms, SCHEMES_BY_NAME)
130
+ unusable = @signature_algorithms.reject { |name| SCHEMES_BY_NAME.fetch(name).usable_in_certificate_verify? }
131
+ unless unusable.empty?
132
+ raise ArgumentError, "#{unusable.inspect} cannot sign a CertificateVerify; list them in signature_algorithms_cert"
133
+ end
134
+ @signature_algorithm_ids = @signature_algorithms.map { |name| SCHEMES_BY_NAME.fetch(name).id }
135
+ @signature_algorithms_cert = names(:signature_algorithms_cert, signature_algorithms_cert, SCHEMES_BY_NAME)
136
+ @signature_algorithm_cert_ids = @signature_algorithms_cert.map { |name| SCHEMES_BY_NAME.fetch(name).id }
137
+
138
+ @alpn = check_alpn(alpn)
139
+ raise ArgumentError, "registry must be an Extension::Registry" unless registry.is_a?(Extension::Registry)
140
+ @registry = registry
141
+ @extensions = check_extensions(extensions, registry)
142
+
143
+ @max_handshake_message_size = positive(:max_handshake_message_size, max_handshake_message_size)
144
+ @max_certificate_message_size = positive(:max_certificate_message_size, max_certificate_message_size)
145
+ @max_certificate_chain_length = positive(:max_certificate_chain_length, max_certificate_chain_length)
146
+ @permute_extensions = permute_extensions ? true : false
147
+ @grease = grease ? true : false
148
+ @exporter_labels = check_exporter_labels(exporter_labels)
149
+ # RFC 8449: a value under 64 is an error, and TLS 1.3 allows a plaintext
150
+ # of at most 2^14 bytes plus the content type.
151
+ unless record_size_limit.nil? || (record_size_limit.is_a?(Integer) && record_size_limit.between?(64, (1 << 14) + 1))
152
+ raise ArgumentError, "record_size_limit must be nil or in 64..16385"
153
+ end
154
+ @record_size_limit = record_size_limit
155
+
156
+ unless trust_anchors.is_a?(Array) && trust_anchors.all? { |der| der.is_a?(String) }
157
+ raise ArgumentError, "trust_anchors must be an Array of DER Strings"
158
+ end
159
+ @trust_anchors = trust_anchors.map(&:b)
160
+ # How a ticket of a client certificate names the anchor its chain
161
+ # ended at.
162
+ @trust_anchor_digests = @trust_anchors.map { |der| Ticket.anchor_digest(der) }
163
+ raise ArgumentError, "verify_flags must be an Integer" unless verify_flags.is_a?(Integer)
164
+ @verify_flags = verify_flags
165
+
166
+ unless %i[none optional required].include?(client_auth)
167
+ raise ArgumentError, "client_auth must be :none, :optional or :required, not #{client_auth.inspect}"
168
+ end
169
+ raise ArgumentError, "client_auth is a server setting" if role == :client && client_auth != :none
170
+ raise ArgumentError, "require_server_name is a server setting" if role == :client && require_server_name
171
+ @client_auth = client_auth
172
+ @certificate_authorities = certificate_authorities ? true : false
173
+ @require_server_name = require_server_name ? true : false
174
+ resumption_settings(resumption:, ticket_keys:, ticket_key:, ticket_lifetime:, ticket_count:, max_ticket_size:,
175
+ resumption_scope:, max_early_data_size:)
176
+
177
+ # Every setting above is a copy of what was given, so this freezes
178
+ # nothing of the caller's.
179
+ Ractor.make_shareable(self)
180
+ end
181
+
182
+ def client? = role == :client
183
+
184
+ def server? = role == :server
185
+
186
+ # A Config with some settings changed, checked and frozen like a new one.
187
+ def with(
188
+ profile: self.profile, cipher_suites: self.cipher_suites, groups: self.groups,
189
+ signature_algorithms: self.signature_algorithms, signature_algorithms_cert: self.signature_algorithms_cert,
190
+ alpn: self.alpn, registry: self.registry, extensions: self.extensions,
191
+ max_handshake_message_size: self.max_handshake_message_size,
192
+ max_certificate_message_size: self.max_certificate_message_size,
193
+ max_certificate_chain_length: self.max_certificate_chain_length,
194
+ permute_extensions: self.permute_extensions, grease: self.grease, exporter_labels: self.exporter_labels,
195
+ record_size_limit: self.record_size_limit, trust_anchors: self.trust_anchors, verify_flags: self.verify_flags,
196
+ client_auth: self.client_auth, certificate_authorities: self.certificate_authorities,
197
+ require_server_name: self.require_server_name, resumption: self.resumption, ticket_keys: self.ticket_keys,
198
+ ticket_lifetime: self.ticket_lifetime, ticket_count: @ticket_count_given, max_ticket_size: self.max_ticket_size,
199
+ resumption_scope: self.resumption_scope, max_early_data_size: self.max_early_data_size
200
+ )
201
+ Config.new(
202
+ role:, profile:, cipher_suites:, groups:, signature_algorithms:, signature_algorithms_cert:, alpn:, registry:,
203
+ extensions:, max_handshake_message_size:, max_certificate_message_size:, max_certificate_chain_length:,
204
+ permute_extensions:, grease:, exporter_labels:, record_size_limit:, trust_anchors:, verify_flags:,
205
+ client_auth:, certificate_authorities:, require_server_name:, resumption:, ticket_keys:, ticket_lifetime:,
206
+ ticket_count:, max_ticket_size:, resumption_scope:, max_early_data_size:
207
+ )
208
+ end
209
+
210
+ # Whether a server issues tickets: only when given keys to seal them.
211
+ def issues_tickets? = !ticket_keys.nil? && ticket_count.positive?
212
+
213
+ private def names(setting, given, table)
214
+ raise ArgumentError, "#{setting} must be a non-empty Array of Symbols" unless given.is_a?(Array) && !given.empty?
215
+ unknown = given.reject { |name| table.key?(name) }
216
+ raise ArgumentError, "#{setting} has unknown or unsupported names: #{unknown.inspect}" unless unknown.empty?
217
+ raise ArgumentError, "#{setting} lists a name twice" unless given.uniq.size == given.size
218
+ given.dup
219
+ end
220
+
221
+ # RFC 7301: ProtocolName<1..2^8-1>.
222
+ private def check_alpn(alpn)
223
+ raise ArgumentError, "alpn must be an Array of Strings" unless alpn.is_a?(Array) && alpn.all? { |p| p.is_a?(String) }
224
+ protocols = alpn.map(&:b)
225
+ raise ArgumentError, "an ALPN protocol name is 1 to 255 bytes" unless protocols.all? { |p| p.bytesize.between?(1, 255) }
226
+ raise ArgumentError, "alpn lists a protocol twice" unless protocols.uniq.size == protocols.size
227
+ protocols
228
+ end
229
+
230
+ private def check_extensions(extensions, registry)
231
+ raise ArgumentError, "extensions must be an Array" unless extensions.is_a?(Array)
232
+ Config.check_extensions(extensions, registry)
233
+ Ractor.make_shareable(extensions, copy: true)
234
+ # A Proc cannot be copied (TypeError) and some objects cannot be made
235
+ # shareable at all (Ractor::Error).
236
+ rescue Ractor::Error, TypeError => e
237
+ raise ArgumentError, "a Config is shared between Ractors, so its extensions cannot hold a Proc or an I/O: #{e.message}"
238
+ end
239
+
240
+ # The checks on extensions given from outside, shared with the ones a
241
+ # Machine is given for one connection.
242
+ def self.check_extensions(extensions, registry)
243
+ types = extensions.map do |ext|
244
+ type = ext.extension_type
245
+ raise ArgumentError, "extension #{type} is set by the handshake itself" if RESERVED_EXTENSIONS.include?(type)
246
+ raise ArgumentError, "extension #{type} is a GREASE value" if IANA.grease?(type)
247
+ case ext
248
+ when Extension::Opaque
249
+ # Raw bytes need no codec.
250
+ else
251
+ # A typed value must be registered, so that the same type coming
252
+ # back from the peer parses into the same class, not into Opaque.
253
+ raise ArgumentError, "extension #{type} is not registered in the Config's registry" unless registry.registered?(type)
254
+ end
255
+ type
256
+ end
257
+ raise ArgumentError, "an extension type appears twice" unless types.uniq.size == types.size
258
+ end
259
+
260
+ private def check_exporter_labels(labels)
261
+ unless labels.is_a?(Array) && labels.all? { |label| label.is_a?(String) }
262
+ raise ArgumentError, "exporter_labels must be an Array of Strings"
263
+ end
264
+ labels = labels.map(&:b)
265
+ unless labels.all? { |label| EXPORTER_LABEL_LENGTH.cover?(label.bytesize) }
266
+ raise ArgumentError, "an exporter label is 1 to 249 bytes"
267
+ end
268
+ raise ArgumentError, "exporter_labels lists a label twice" unless labels.uniq.size == labels.size
269
+ labels
270
+ end
271
+
272
+ # The settings of session resumption. A client resumes unless `resumption`
273
+ # is false. A server issues tickets only when given `ticket_keys:` (or a
274
+ # `ticket_key:` String, a static key), and takes 0-RTT only then; a
275
+ # setting that would do nothing without them is refused. With QUIC,
276
+ # max_early_data_size is the sentinel RFC 9001 "Enabling 0-RTT" asks for
277
+ # whenever 0-RTT is allowed at all.
278
+ private def resumption_settings(resumption:, ticket_keys:, ticket_key:, ticket_lifetime:, ticket_count:,
279
+ max_ticket_size:, resumption_scope:, max_early_data_size:)
280
+ @resumption = resumption ? true : false
281
+ raise ArgumentError, "a server resumes when given ticket_keys; resumption is a client setting" if role == :server && !@resumption
282
+ if role == :client && (ticket_keys || ticket_key || ticket_count || max_early_data_size != 0 || resumption_scope != "")
283
+ raise ArgumentError, "ticket_keys, ticket_count, max_early_data_size and resumption_scope are server settings"
284
+ end
285
+ raise ArgumentError, "give ticket_keys or ticket_key, not both" if ticket_keys && ticket_key
286
+ unless ticket_lifetime.is_a?(Integer) && ticket_lifetime.between?(1, MAX_TICKET_LIFETIME)
287
+ raise ArgumentError, "ticket_lifetime is 1 to #{MAX_TICKET_LIFETIME} seconds"
288
+ end
289
+ keys = ticket_key ? TicketKeys.static(current: ticket_key) : ticket_keys
290
+ raise ArgumentError, "ticket_keys must be TicketKeys" unless keys.nil? || keys.is_a?(TicketKeys)
291
+ raise ArgumentError, "ticket_count must be an Integer of 0 or more" unless ticket_count.nil? || (ticket_count.is_a?(Integer) && !ticket_count.negative?)
292
+ raise ArgumentError, "ticket_count without ticket_keys issues nothing" if keys.nil? && ticket_count&.positive?
293
+ unless max_ticket_size.is_a?(Integer) && max_ticket_size.between?(1, MAX_TICKET_SIZE)
294
+ raise ArgumentError, "max_ticket_size is 1 to #{MAX_TICKET_SIZE} bytes"
295
+ end
296
+ raise ArgumentError, "resumption_scope must be a String" unless resumption_scope.is_a?(String)
297
+ unless max_early_data_size.is_a?(Integer) && max_early_data_size.between?(0, MAX_EARLY_DATA_SIZE)
298
+ raise ArgumentError, "max_early_data_size is 0 to #{MAX_EARLY_DATA_SIZE}"
299
+ end
300
+ raise ArgumentError, "max_early_data_size without ticket_keys takes no 0-RTT" if keys.nil? && max_early_data_size.positive?
301
+ @ticket_keys = keys&.for_ticket_lifetime(ticket_lifetime)
302
+ @ticket_lifetime = ticket_lifetime
303
+ @ticket_count_given = ticket_count
304
+ @ticket_count = ticket_count || (keys ? DEFAULT_TICKET_COUNT : 0)
305
+ @max_ticket_size = max_ticket_size
306
+ @resumption_scope = resumption_scope.b
307
+ sentinel = profile.max_early_data_size_policy == :sentinel && max_early_data_size.positive?
308
+ @max_early_data_size = sentinel ? MAX_EARLY_DATA_SIZE : max_early_data_size
309
+ # The part of a ticket's binding this Config gives, computed once.
310
+ @ticket_binding = Ticket.config_binding(profile:, resumption_scope: @resumption_scope)
311
+ end
312
+
313
+ private def positive(setting, value)
314
+ raise ArgumentError, "#{setting} must be a positive Integer" unless value.is_a?(Integer) && value.positive?
315
+ value
316
+ end
317
+ end
318
+ end
@@ -0,0 +1,64 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::TLS
4
+ module Crypto
5
+ # One key of an AEAD algorithm of the TLS 1.3 cipher suites (RFC 5116),
6
+ # named by Symbol. Each direction keeps its own OpenSSL context, keyed
7
+ # once and given a fresh nonce for every call.
8
+ #
9
+ # A failed authentication is nil, not an exception: the bytes come from
10
+ # the peer, and the record layer turns nil into bad_record_mac.
11
+ class AEAD
12
+ CIPHERS = { aes_128_gcm: "aes-128-gcm", aes_256_gcm: "aes-256-gcm", chacha20_poly1305: "chacha20-poly1305" }.freeze #: Hash[Symbol, String]
13
+ TAG_LENGTH = 16
14
+
15
+ def initialize(algorithm, key)
16
+ @name = CIPHERS.fetch(algorithm) { raise ArgumentError, "unknown AEAD: #{algorithm.inspect}" }
17
+ @key = key.b
18
+ @sealer = nil #: OpenSSL::Cipher?
19
+ @opener = nil #: OpenSSL::Cipher?
20
+ end
21
+
22
+ # The ciphertext followed by the tag.
23
+ def seal(nonce:, aad:, plaintext:)
24
+ cipher = @sealer ||= context(:encrypt)
25
+ cipher.iv = nonce
26
+ cipher.auth_data = aad
27
+ sealed = plaintext.empty? ? "".b : cipher.update(plaintext)
28
+ sealed << cipher.final << cipher.auth_tag(TAG_LENGTH)
29
+ end
30
+
31
+ # The plaintext, or nil when `ciphertext` (with its tag) does not
32
+ # authenticate under `nonce` and `aad`.
33
+ def open(nonce:, aad:, ciphertext:)
34
+ return nil if ciphertext.bytesize < TAG_LENGTH
35
+ cipher = @opener ||= context(:decrypt)
36
+ body_length = ciphertext.bytesize - TAG_LENGTH
37
+ cipher.iv = nonce
38
+ cipher.auth_tag = ciphertext.byteslice(body_length, TAG_LENGTH).to_s
39
+ cipher.auth_data = aad
40
+ opened = body_length.zero? ? "".b : cipher.update(ciphertext.byteslice(0, body_length).to_s)
41
+ opened << cipher.final
42
+ rescue OpenSSL::Cipher::CipherError
43
+ nil
44
+ end
45
+
46
+ # Forgets the key, a best effort: OpenSSL's contexts keep their own
47
+ # copies until collected.
48
+ def discard!
49
+ @key.clear
50
+ @sealer = nil
51
+ @opener = nil
52
+ end
53
+
54
+ private def instance_variables_to_inspect = %i[@name]
55
+
56
+ private def context(direction)
57
+ cipher = OpenSSL::Cipher.new(@name)
58
+ direction == :encrypt ? cipher.encrypt : cipher.decrypt
59
+ cipher.key = @key
60
+ cipher
61
+ end
62
+ end
63
+ end
64
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::TLS
4
+ module Crypto
5
+ # X.509 certificates from DER.
6
+ module Certificate
7
+ # The SignatureScheme code point of a certificate's own signature, by
8
+ # the name of its algorithm in lower case; nil for one without a
9
+ # matching scheme (RSASSA-PSS parameters, for one, are not looked
10
+ # into). Lower case, since the libraries differ in case: OpenSSL says
11
+ # "ED25519" where LibreSSL says "Ed25519".
12
+ SIGNATURE_SCHEMES = {
13
+ "sha256WithRSAEncryption" => 0x0401, "sha384WithRSAEncryption" => 0x0501, "sha512WithRSAEncryption" => 0x0601,
14
+ "ecdsa-with-SHA256" => 0x0403, "ecdsa-with-SHA384" => 0x0503, "ecdsa-with-SHA512" => 0x0603,
15
+ "ED25519" => 0x0807, "ED448" => 0x0808, "sha1WithRSAEncryption" => 0x0201, "ecdsa-with-SHA1" => 0x0203
16
+ }.transform_keys(&:downcase).freeze #: Hash[String, Integer]
17
+
18
+ def self.signature_scheme_id(certificate) = SIGNATURE_SCHEMES[certificate.signature_algorithm.downcase]
19
+
20
+ # nil for bytes that are not one DER certificate.
21
+ def self.parse(der)
22
+ OpenSSL::X509::Certificate.new(der)
23
+ rescue OpenSSL::X509::CertificateError
24
+ nil
25
+ end
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "hash"
4
+
5
+ module Raiha::TLS
6
+ module Crypto
7
+ # A running hash. `#digest` returns the hash of everything added so far
8
+ # and keeps accumulating.
9
+ class Digest
10
+ attr_reader :hash_name
11
+
12
+ def initialize(hash_name)
13
+ @hash_name = hash_name
14
+ @digest = OpenSSL::Digest.new(Crypto.digest_name(hash_name))
15
+ end
16
+
17
+ def <<(bytes)
18
+ @digest << bytes
19
+ self
20
+ end
21
+
22
+ def digest = @digest.digest
23
+
24
+ def initialize_copy(other)
25
+ super
26
+ @digest = @digest.dup
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,74 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::TLS
4
+ module Crypto
5
+ # Elliptic-curve Diffie-Hellman over the groups TLS 1.3 uses, with public
6
+ # keys as they appear in key_share: the 32-byte u-coordinate for X25519
7
+ # and the uncompressed point for the NIST curves.
8
+ module ECDH
9
+ CURVES = { secp256r1: "prime256v1", secp384r1: "secp384r1" }.freeze #: Hash[Symbol, String]
10
+ POINT_LENGTHS = { secp256r1: 65, secp384r1: 97 }.freeze #: Hash[Symbol, Integer]
11
+ X25519_LENGTH = 32
12
+
13
+ def self.groups = [:x25519, *CURVES.keys]
14
+
15
+ def self.generate(group)
16
+ if group == :x25519
17
+ OpenSSL::PKey.generate_key("X25519")
18
+ else
19
+ OpenSSL::PKey::EC.generate(curve_name(group))
20
+ end
21
+ end
22
+
23
+ # A private key from its raw bytes: the scalar for the NIST curves.
24
+ # Only fixed test keys need this. The ECPrivateKey carries the public
25
+ # key too, the scalar times the generator: OpenSSL works it out where
26
+ # it is missing, but LibreSSL refuses such a key.
27
+ def self.private_key(group, bytes)
28
+ return OpenSSL::PKey.new_raw_private_key("X25519", bytes) if group == :x25519
29
+ name = curve_name(group)
30
+ point = OpenSSL::PKey::EC::Group.new(name).generator.mul(OpenSSL::BN.new(bytes, 2)) # steep:ignore
31
+ der = OpenSSL::ASN1::Sequence([OpenSSL::ASN1::Integer(1), OpenSSL::ASN1::OctetString(bytes),
32
+ explicit(OpenSSL::ASN1::ObjectId(name), 0), explicit(OpenSSL::ASN1::BitString(point.to_octet_string(:uncompressed)), 1)]).to_der
33
+ OpenSSL::PKey::EC.new(der)
34
+ end
35
+
36
+ # `value` under the context-specific tag `tag`, EXPLICIT.
37
+ private_class_method def self.explicit(value, tag)
38
+ value.tag = tag
39
+ value.tagging = :EXPLICIT
40
+ value.tag_class = :CONTEXT_SPECIFIC
41
+ value
42
+ end
43
+
44
+ def self.public_bytes(group, key)
45
+ if group == :x25519
46
+ key.raw_public_key
47
+ else
48
+ key.public_key.to_octet_string(:uncompressed) # steep:ignore
49
+ end
50
+ end
51
+
52
+ # The shared secret, or nil when the peer's public key is not a valid
53
+ # key of the group: a wrong length, a compressed or off-curve point, or
54
+ # an X25519 key that yields the all-zero secret, which OpenSSL refuses.
55
+ def self.derive(group, key, peer_public_bytes)
56
+ if group == :x25519
57
+ return nil unless peer_public_bytes.bytesize == X25519_LENGTH
58
+ key.derive(OpenSSL::PKey.new_raw_public_key("X25519", peer_public_bytes))
59
+ else
60
+ return nil unless peer_public_bytes.bytesize == POINT_LENGTHS.fetch(group) && peer_public_bytes.getbyte(0) == 4
61
+ ec_group = OpenSSL::PKey::EC::Group.new(curve_name(group))
62
+ point = OpenSSL::PKey::EC::Point.new(ec_group, OpenSSL::BN.new(peer_public_bytes, 2))
63
+ key.dh_compute_key(point) # steep:ignore
64
+ end
65
+ rescue OpenSSL::PKey::PKeyError, OpenSSL::PKey::EC::Point::Error
66
+ nil
67
+ end
68
+
69
+ private_class_method def self.curve_name(group)
70
+ CURVES.fetch(group) { raise ArgumentError, "unsupported group: #{group.inspect}" }
71
+ end
72
+ end
73
+ end
74
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Raiha::TLS
4
+ module Crypto
5
+ # The hash functions of TLS 1.3 cipher suites, named by Symbol.
6
+ HASHES = { sha256: "SHA256", sha384: "SHA384" }.freeze #: Hash[Symbol, String]
7
+ HASH_LENGTHS = { sha256: 32, sha384: 48 }.freeze #: Hash[Symbol, Integer]
8
+
9
+ def self.hash_length(hash) = HASH_LENGTHS.fetch(hash) { raise ArgumentError, "unknown hash: #{hash.inspect}" }
10
+
11
+ def self.digest_name(hash) = HASHES.fetch(hash) { raise ArgumentError, "unknown hash: #{hash.inspect}" }
12
+
13
+ def self.hash(hash, data) = OpenSSL::Digest.digest(digest_name(hash), data)
14
+
15
+ def self.hmac(hash:, key:, data:) = OpenSSL::HMAC.digest(digest_name(hash), key, data)
16
+
17
+ # Compares two secrets of the same, public length in constant time.
18
+ # Different lengths raise ArgumentError: the caller must have checked the
19
+ # length already, and answering false would hide a missing length check.
20
+ def self.fixed_length_secure_compare(a, b) = OpenSSL.fixed_length_secure_compare(a, b)
21
+ end
22
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "hash"
4
+
5
+ module Raiha::TLS
6
+ module Crypto
7
+ # HKDF (RFC 5869), split into its two steps as TLS 1.3 uses them.
8
+ module HKDF
9
+ def self.extract(hash:, salt:, ikm:)
10
+ Crypto.hmac(hash:, key: salt, data: ikm)
11
+ end
12
+
13
+ def self.expand(hash:, prk:, info:, length:)
14
+ hash_length = Crypto.hash_length(hash)
15
+ raise ArgumentError, "HKDF-Expand length #{length} is out of range" unless length.between?(0, 255 * hash_length)
16
+ output = String.new(encoding: Encoding::BINARY)
17
+ block = "".b
18
+ counter = 1
19
+ while output.bytesize < length
20
+ block = Crypto.hmac(hash:, key: prk, data: block + info + counter.chr)
21
+ output << block
22
+ counter += 1
23
+ end
24
+ output.byteslice(0, length) #: String
25
+ end
26
+ end
27
+ end
28
+ end