quic_record_rx.h 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  1. /*
  2. * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
  3. *
  4. * Licensed under the Apache License 2.0 (the "License"). You may not use
  5. * this file except in compliance with the License. You can obtain a copy
  6. * in the file LICENSE in the source distribution or at
  7. * https://www.openssl.org/source/license.html
  8. */
  9. #ifndef OSSL_QUIC_RECORD_RX_H
  10. # define OSSL_QUIC_RECORD_RX_H
  11. # include <openssl/ssl.h>
  12. # include "internal/quic_wire_pkt.h"
  13. # include "internal/quic_types.h"
  14. # include "internal/quic_record_util.h"
  15. # include "internal/quic_demux.h"
  16. /*
  17. * QUIC Record Layer - RX
  18. * ======================
  19. */
  20. typedef struct ossl_qrx_st OSSL_QRX;
  21. typedef struct ossl_qrx_args_st {
  22. OSSL_LIB_CTX *libctx;
  23. const char *propq;
  24. /* Demux to receive datagrams from. */
  25. QUIC_DEMUX *demux;
  26. /* Length of connection IDs used in short-header packets in bytes. */
  27. size_t short_conn_id_len;
  28. /*
  29. * Maximum number of deferred datagrams buffered at any one time.
  30. * Suggested value: 32.
  31. */
  32. size_t max_deferred;
  33. /* Initial reference PN used for RX. */
  34. QUIC_PN init_largest_pn[QUIC_PN_SPACE_NUM];
  35. /* Initial key phase. For debugging use only; always 0 in real use. */
  36. unsigned char init_key_phase_bit;
  37. } OSSL_QRX_ARGS;
  38. /* Instantiates a new QRX. */
  39. OSSL_QRX *ossl_qrx_new(const OSSL_QRX_ARGS *args);
  40. /*
  41. * Frees the QRX. All packets obtained using ossl_qrx_read_pkt must already
  42. * have been released by calling ossl_qrx_release_pkt.
  43. *
  44. * You do not need to call ossl_qrx_remove_dst_conn_id first; this function will
  45. * unregister the QRX from the demuxer for all registered destination connection
  46. * IDs (DCIDs) automatically.
  47. */
  48. void ossl_qrx_free(OSSL_QRX *qrx);
  49. /*
  50. * DCID Management
  51. * ===============
  52. */
  53. /*
  54. * Adds a given DCID to the QRX. The QRX will register the DCID with the demuxer
  55. * so that incoming packets with that DCID are passed to the given QRX. Multiple
  56. * DCIDs may be associated with a QRX at any one time. You will need to add at
  57. * least one DCID after instantiating the QRX. A zero-length DCID is a valid
  58. * input to this function. This function fails if the DCID is already
  59. * registered.
  60. *
  61. * Returns 1 on success or 0 on error.
  62. */
  63. int ossl_qrx_add_dst_conn_id(OSSL_QRX *qrx,
  64. const QUIC_CONN_ID *dst_conn_id);
  65. /*
  66. * Remove a DCID previously registered with ossl_qrx_add_dst_conn_id. The DCID
  67. * is unregistered from the demuxer. Fails if the DCID is not registered with
  68. * the demuxer.
  69. *
  70. * Returns 1 on success or 0 on error.
  71. */
  72. int ossl_qrx_remove_dst_conn_id(OSSL_QRX *qrx,
  73. const QUIC_CONN_ID *dst_conn_id);
  74. /*
  75. * Secret Management
  76. * =================
  77. *
  78. * A QRX has several encryption levels (Initial, Handshake, 0-RTT, 1-RTT) and
  79. * two directions (RX, TX). At any given time, key material is managed for each
  80. * (EL, RX/TX) combination.
  81. *
  82. * Broadly, for a given (EL, RX/TX), the following state machine is applicable:
  83. *
  84. * WAITING_FOR_KEYS --[Provide]--> HAVE_KEYS --[Discard]--> | DISCARDED |
  85. * \-------------------------------------[Discard]--> | |
  86. *
  87. * To transition the RX side of an EL from WAITING_FOR_KEYS to HAVE_KEYS, call
  88. * ossl_qrx_provide_secret (for the INITIAL EL, use of
  89. * ossl_quic_provide_initial_secret is recommended).
  90. *
  91. * Once keys have been provisioned for an EL, you call
  92. * ossl_qrx_discard_enc_level to transition the EL to the DISCARDED state. You
  93. * can also call this function to transition directly to the DISCARDED state
  94. * even before any keys have been provisioned for that EL.
  95. *
  96. * The DISCARDED state is terminal for a given EL; you cannot provide a secret
  97. * again for that EL after reaching it.
  98. *
  99. * Incoming packets cannot be processed and decrypted if they target an EL
  100. * not in the HAVE_KEYS state. However, there is a distinction between
  101. * the WAITING_FOR_KEYS and DISCARDED states:
  102. *
  103. * - In the WAITING_FOR_KEYS state, the QRX assumes keys for the given
  104. * EL will eventually arrive. Therefore, if it receives any packet
  105. * for an EL in this state, it buffers it and tries to process it
  106. * again once the EL reaches HAVE_KEYS.
  107. *
  108. * - In the DISCARDED state, the QRX assumes no keys for the given
  109. * EL will ever arrive again. If it receives any packet for an EL
  110. * in this state, it is simply discarded.
  111. *
  112. * If the user wishes to instantiate a new QRX to replace an old one for
  113. * whatever reason, for example to take over for an already established QUIC
  114. * connection, it is important that all ELs no longer being used (i.e., INITIAL,
  115. * 0-RTT, 1-RTT) are transitioned to the DISCARDED state. Otherwise, the QRX
  116. * will assume that keys for these ELs will arrive in future, and will buffer
  117. * any received packets for those ELs perpetually. This can be done by calling
  118. * ossl_qrx_discard_enc_level for all non-1-RTT ELs immediately after
  119. * instantiating the QRX.
  120. *
  121. * The INITIAL EL is not setup automatically when the QRX is instantiated. This
  122. * allows the caller to instead discard it immediately after instantiation of
  123. * the QRX if it is not needed, for example if the QRX is being instantiated to
  124. * take over handling of an existing connection which has already passed the
  125. * INITIAL phase. This avoids the unnecessary derivation of INITIAL keys where
  126. * they are not needed. In the ordinary case, ossl_quic_provide_initial_secret
  127. * should be called immediately after instantiation.
  128. */
  129. /*
  130. * Provides a secret to the QRX, which arises due to an encryption level change.
  131. * enc_level is a QUIC_ENC_LEVEL_* value. To initialise the INITIAL encryption
  132. * level, it is recommended to use ossl_quic_provide_initial_secret instead.
  133. *
  134. * You should seek to call this function for a given EL before packets of that
  135. * EL arrive and are processed by the QRX. However, if packets have already
  136. * arrived for a given EL, the QRX will defer processing of them and perform
  137. * processing of them when this function is eventually called for the EL in
  138. * question.
  139. *
  140. * suite_id is a QRL_SUITE_* value which determines the AEAD function used for
  141. * the QRX.
  142. *
  143. * The secret passed is used directly to derive the "quic key", "quic iv" and
  144. * "quic hp" values.
  145. *
  146. * secret_len is the length of the secret buffer in bytes. The buffer must be
  147. * sized correctly to the chosen suite, else the function fails.
  148. *
  149. * This function can only be called once for a given EL. Subsequent calls fail,
  150. * as do calls made after a corresponding call to ossl_qrx_discard_enc_level for
  151. * that EL. The secret for a EL cannot be changed after it is set because QUIC
  152. * has no facility for introducing additional key material after an EL is setup.
  153. * QUIC key updates are managed semi-automatically by the QRX but do require
  154. * some caller handling (see below).
  155. *
  156. * md is for internal use and should be NULL.
  157. *
  158. * Returns 1 on success or 0 on failure.
  159. */
  160. int ossl_qrx_provide_secret(OSSL_QRX *qrx,
  161. uint32_t enc_level,
  162. uint32_t suite_id,
  163. EVP_MD *md,
  164. const unsigned char *secret,
  165. size_t secret_len);
  166. /*
  167. * Informs the QRX that it can now discard key material for a given EL. The QRX
  168. * will no longer be able to process incoming packets received at that
  169. * encryption level. This function is idempotent and succeeds if the EL has
  170. * already been discarded.
  171. *
  172. * Returns 1 on success and 0 on failure.
  173. */
  174. int ossl_qrx_discard_enc_level(OSSL_QRX *qrx, uint32_t enc_level);
  175. /*
  176. * Packet Reception
  177. * ================
  178. */
  179. /* Information about a received packet. */
  180. typedef struct ossl_qrx_pkt_st {
  181. /* Opaque handle to be passed to ossl_qrx_release_pkt. */
  182. void *handle;
  183. /*
  184. * Points to a logical representation of the decoded QUIC packet header. The
  185. * data and len fields point to the decrypted QUIC payload (i.e., to a
  186. * sequence of zero or more (potentially malformed) frames to be decoded).
  187. */
  188. QUIC_PKT_HDR *hdr;
  189. /*
  190. * Address the packet was received from. If this is not available for this
  191. * packet, this field is NULL (but this can only occur for manually injected
  192. * packets).
  193. */
  194. const BIO_ADDR *peer;
  195. /*
  196. * Local address the packet was sent to. If this is not available for this
  197. * packet, this field is NULL.
  198. */
  199. const BIO_ADDR *local;
  200. /*
  201. * This is the length of the datagram which contained this packet. Note that
  202. * the datagram may have contained other packets than this. The intended use
  203. * for this is so that the user can enforce minimum datagram sizes (e.g. for
  204. * datagrams containing INITIAL packets), as required by RFC 9000.
  205. */
  206. size_t datagram_len;
  207. /* The PN which was decoded for the packet, if the packet has a PN field. */
  208. QUIC_PN pn;
  209. /*
  210. * Time the packet was received, or ossl_time_zero() if the demuxer is not
  211. * using a now() function.
  212. */
  213. OSSL_TIME time;
  214. } OSSL_QRX_PKT;
  215. /*
  216. * Tries to read a new decrypted packet from the QRX.
  217. *
  218. * On success, all fields of *pkt are filled and 1 is returned.
  219. * Else, returns 0.
  220. *
  221. * The resources referenced by pkt->hdr, pkt->hdr->data and pkt->peer will
  222. * remain allocated at least until the user frees them by calling
  223. * ossl_qrx_release_pkt, which must be called once you are done with the packet.
  224. */
  225. int ossl_qrx_read_pkt(OSSL_QRX *qrx, OSSL_QRX_PKT *pkt);
  226. /*
  227. * Release the resources pointed to by an OSSL_QRX_PKT returned by
  228. * ossl_qrx_read_pkt. Pass the opaque value pkt->handle returned in the
  229. * structure.
  230. */
  231. void ossl_qrx_release_pkt(OSSL_QRX *qrx, void *handle);
  232. /*
  233. * Returns 1 if there are any already processed (i.e. decrypted) packets waiting
  234. * to be read from the QRX.
  235. */
  236. int ossl_qrx_processed_read_pending(OSSL_QRX *qrx);
  237. /*
  238. * Returns 1 if there are any unprocessed (i.e. not yet decrypted) packets
  239. * waiting to be processed by the QRX. These may or may not result in
  240. * successfully decrypted packets once processed. This indicates whether
  241. * unprocessed data is buffered by the QRX, not whether any data is available in
  242. * a kernel socket buffer.
  243. */
  244. int ossl_qrx_unprocessed_read_pending(OSSL_QRX *qrx);
  245. /*
  246. * Returns the number of UDP payload bytes received from the network so far
  247. * since the last time this counter was cleared. If clear is 1, clears the
  248. * counter and returns the old value.
  249. *
  250. * The intended use of this is to allow callers to determine how much credit to
  251. * add to their anti-amplification budgets. This is reported separately instead
  252. * of in the OSSL_QRX_PKT structure so that a caller can apply
  253. * anti-amplification credit as soon as a datagram is received, before it has
  254. * necessarily read all processed packets contained within that datagram from
  255. * the QRX.
  256. */
  257. uint64_t ossl_qrx_get_bytes_received(OSSL_QRX *qrx, int clear);
  258. /*
  259. * Sets a callback which is called when a packet is received and being
  260. * validated before being queued in the read queue. This is called before packet
  261. * body decryption. pn_space is a QUIC_PN_SPACE_* value denoting which PN space
  262. * the PN belongs to.
  263. *
  264. * If this callback returns 1, processing continues normally.
  265. * If this callback returns 0, the packet is discarded.
  266. *
  267. * Other packets in the same datagram will still be processed where possible.
  268. *
  269. * The intended use for this function is to allow early validation of whether
  270. * a PN is a potential duplicate before spending CPU time decrypting the
  271. * packet payload.
  272. *
  273. * The callback is optional and can be unset by passing NULL for cb.
  274. * cb_arg is an opaque value passed to cb.
  275. */
  276. typedef int (ossl_qrx_early_validation_cb)(QUIC_PN pn, int pn_space,
  277. void *arg);
  278. int ossl_qrx_set_early_validation_cb(OSSL_QRX *qrx,
  279. ossl_qrx_early_validation_cb *cb,
  280. void *cb_arg);
  281. /*
  282. * Key Update (RX)
  283. * ===============
  284. *
  285. * Key update on the RX side is a largely but not entirely automatic process.
  286. *
  287. * Key update is initially triggered by receiving a 1-RTT packet with a
  288. * different Key Phase value. This could be caused by an attacker in the network
  289. * flipping random bits, therefore such a key update is tentative until the
  290. * packet payload is successfully decrypted and authenticated by the AEAD with
  291. * the 'next' keys. These 'next' keys then become the 'current' keys and the
  292. * 'current' keys then become the 'previous' keys. The 'previous' keys must be
  293. * kept around temporarily as some packets may still be in flight in the network
  294. * encrypted with the old keys. If the old Key Phase value is X and the new Key
  295. * Phase Value is Y (where obviously X != Y), this creates an ambiguity as any
  296. * new packet received with a KP of X could either be an attempt to initiate yet
  297. * another key update right after the last one, or an old packet encrypted
  298. * before the key update.
  299. *
  300. * RFC 9001 provides some guidance on handling this issue:
  301. *
  302. * Strategy 1:
  303. * Three keys, disambiguation using packet numbers
  304. *
  305. * "A recovered PN that is lower than any PN from the current KP uses the
  306. * previous packet protection keys; a recovered PN that is higher than any
  307. * PN from the current KP requires use of the next packet protection
  308. * keys."
  309. *
  310. * Strategy 2:
  311. * Two keys and a timer
  312. *
  313. * "Alternatively, endpoints can retain only two sets of packet protection
  314. * keys, swapping previous keys for next after enough time has passed to
  315. * allow for reordering in the network. In this case, the KP bit alone can
  316. * be used to select keys."
  317. *
  318. * Strategy 2 is more efficient (we can keep fewer cipher contexts around) and
  319. * should cover all actually possible network conditions. It also allows a delay
  320. * after we make the 'next' keys our 'current' keys before we generate new
  321. * 'next' keys, which allows us to mitigate against malicious peers who try to
  322. * initiate an excessive number of key updates.
  323. *
  324. * We therefore model the following state machine:
  325. *
  326. *
  327. * PROVISIONED
  328. * _______________________________
  329. * | |
  330. * UNPROVISIONED --|----> NORMAL <----------\ |------> DISCARDED
  331. * | | | |
  332. * | | | |
  333. * | v | |
  334. * | UPDATING | |
  335. * | | | |
  336. * | | | |
  337. * | v | |
  338. * | COOLDOWN | |
  339. * | | | |
  340. * | | | |
  341. * | \---------------| |
  342. * |_______________________________|
  343. *
  344. *
  345. * The RX starts (once a secret has been provisioned) in the NORMAL state. In
  346. * the NORMAL state, the current expected value of the Key Phase bit is
  347. * recorded. When a flipped Key Phase bit is detected, the RX attempts to
  348. * decrypt and authenticate the received packet with the 'next' keys rather than
  349. * the 'current' keys. If (and only if) this authentication is successful, we
  350. * move to the UPDATING state. (An attacker in the network could flip
  351. * the Key Phase bit randomly, so it is essential we do nothing until AEAD
  352. * authentication is complete.)
  353. *
  354. * In the UPDATING state, we know a key update is occurring and record
  355. * the new Key Phase bit value as the newly current value, but we still keep the
  356. * old keys around so that we can still process any packets which were still in
  357. * flight when the key update was initiated. In the UPDATING state, a
  358. * Key Phase bit value different to the current expected value is treated not as
  359. * the initiation of another key update, but a reference to our old keys.
  360. *
  361. * Eventually we will be reasonably sure we are not going to receive any more
  362. * packets with the old keys. At this point, we can transition to the COOLDOWN
  363. * state. This transition occurs automatically after a certain amount of time;
  364. * RFC 9001 recommends it be the PTO interval, which relates to our RTT to the
  365. * peer. The duration also SHOULD NOT exceed three times the PTO to assist with
  366. * maintaining PFS.
  367. *
  368. * In the COOLDOWN phase, the old keys have been securely erased and only one
  369. * set of keys can be used: the current keys. If a packet is received with a Key
  370. * Phase bit value different to the current Key Phase Bit value, this is treated
  371. * as a request for a Key Update, but this request is ignored and the packet is
  372. * treated as malformed. We do this to allow mitigation against malicious peers
  373. * trying to initiate an excessive number of Key Updates. The timeout for the
  374. * transition from UPDATING to COOLDOWN is recommended as adequate for
  375. * this purpose in itself by the RFC, so the normal additional timeout value for
  376. * the transition from COOLDOWN to normal is zero (immediate transition).
  377. *
  378. * A summary of each state:
  379. *
  380. * Epoch Exp KP Uses Keys KS0 KS1 If Non-Expected KP Bit
  381. * ----- ------ --------- ------ ----- ----------------------
  382. * NORMAL 0 0 Keyset 0 Gen 0 Gen 1 → UPDATING
  383. * UPDATING 1 1 Keyset 1 Gen 0 Gen 1 Use Keyset 0
  384. * COOLDOWN 1 1 Keyset 1 Erased Gen 1 Ignore Packet (*)
  385. *
  386. * NORMAL 1 1 Keyset 1 Gen 2 Gen 1 → UPDATING
  387. * UPDATING 2 0 Keyset 0 Gen 2 Gen 1 Use Keyset 1
  388. * COOLDOWN 2 0 Keyset 0 Gen 2 Erased Ignore Packet (*)
  389. *
  390. * (*) Actually implemented by attempting to decrypt the packet with the
  391. * wrong keys (which ultimately has the same outcome), as recommended
  392. * by RFC 9001 to avoid creating timing channels.
  393. *
  394. * Note that the key material for the next key generation ("key epoch") is
  395. * always kept in the NORMAL state (necessary to avoid side-channel attacks).
  396. * This material is derived during the transition from COOLDOWN to NORMAL.
  397. *
  398. * Note that when a peer initiates a Key Update, we MUST also initiate a Key
  399. * Update as per the RFC. The caller is responsible for detecting this condition
  400. * and making the necessary calls to the TX side by detecting changes to the
  401. * return value of ossl_qrx_get_key_epoch().
  402. *
  403. * The above states (NORMAL, UPDATING, COOLDOWN) can themselves be
  404. * considered substates of the PROVISIONED state. Providing a secret to the QRX
  405. * for an EL transitions from UNPROVISIONED, the initial state, to PROVISIONED
  406. * (NORMAL). Dropping key material for an EL transitions from whatever the
  407. * current substate of the PROVISIONED state is to the DISCARDED state, which is
  408. * the terminal state.
  409. *
  410. * Note that non-1RTT ELs cannot undergo key update, therefore a non-1RTT EL is
  411. * always in the NORMAL substate if it is in the PROVISIONED state.
  412. */
  413. /*
  414. * Return the current RX key epoch for the 1-RTT encryption level. This is
  415. * initially zero and is incremented by one for every Key Update successfully
  416. * signalled by the peer. If the 1-RTT EL has not yet been provisioned or has
  417. * been discarded, returns UINT64_MAX.
  418. *
  419. * A necessary implication of this API is that the least significant bit of the
  420. * returned value corresponds to the currently expected Key Phase bit, though
  421. * callers are not anticipated to have any need of this information.
  422. *
  423. * It is not possible for the returned value to overflow, as a QUIC connection
  424. * cannot support more than 2**62 packet numbers, and a connection must be
  425. * terminated if this limit is reached.
  426. *
  427. * The caller should use this function to detect when the key epoch has changed
  428. * and use it to initiate a key update on the TX side.
  429. *
  430. * The value returned by this function increments specifically at the transition
  431. * from the NORMAL to the UPDATING state discussed above.
  432. */
  433. uint64_t ossl_qrx_get_key_epoch(OSSL_QRX *qrx);
  434. /*
  435. * Sets an optional callback which will be called when the key epoch changes.
  436. *
  437. * The callback is optional and can be unset by passing NULL for cb.
  438. * cb_arg is an opaque value passed to cb.
  439. */
  440. typedef void (ossl_qrx_key_update_cb)(void *arg);
  441. int ossl_qrx_set_key_update_cb(OSSL_QRX *qrx,
  442. ossl_qrx_key_update_cb *cb, void *cb_arg);
  443. /*
  444. * Relates to the 1-RTT encryption level. The caller should call this after the
  445. * UPDATING state is reached, after a timeout to be determined by the caller.
  446. *
  447. * This transitions from the UPDATING state to the COOLDOWN state (if
  448. * still in the UPDATING state). If normal is 1, then transitions from
  449. * the COOLDOWN state to the NORMAL state. Both transitions can be performed at
  450. * once if desired.
  451. *
  452. * If in the normal state, or if in the COOLDOWN state and normal is 0, this is
  453. * a no-op and returns 1. Returns 0 if the 1-RTT EL has not been provisioned or
  454. * has been dropped.
  455. *
  456. * It is essential that the caller call this within a few PTO intervals of a key
  457. * update occurring (as detected by the caller in a call to
  458. * ossl_qrx_key_get_key_epoch()), as otherwise the peer will not be able to
  459. * perform a Key Update ever again.
  460. */
  461. int ossl_qrx_key_update_timeout(OSSL_QRX *qrx, int normal);
  462. /*
  463. * Key Expiration
  464. * ==============
  465. */
  466. /*
  467. * Returns the number of seemingly forged packets which have been received by
  468. * the QRX. If this value reaches the value returned by
  469. * ossl_qrx_get_max_epoch_forged_pkt_count() for a given EL, all further
  470. * received encrypted packets for that EL will be discarded without processing.
  471. *
  472. * Note that the forged packet limit is for the connection lifetime, thus it is
  473. * not reset by a key update. It is suggested that the caller terminate the
  474. * connection a reasonable margin before the limit is reached. However, the
  475. * exact limit imposed does vary by EL due to the possibility that different ELs
  476. * use different AEADs.
  477. */
  478. uint64_t ossl_qrx_get_cur_forged_pkt_count(OSSL_QRX *qrx);
  479. /*
  480. * Returns the maximum number of forged packets which the record layer will
  481. * permit to be verified using this QRX instance.
  482. */
  483. uint64_t ossl_qrx_get_max_forged_pkt_count(OSSL_QRX *qrx,
  484. uint32_t enc_level);
  485. #endif