quic_record_rx.c 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169
  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. #include "internal/quic_record_rx.h"
  10. #include "quic_record_shared.h"
  11. #include "internal/common.h"
  12. #include "../ssl_local.h"
  13. /*
  14. * Mark a packet in a bitfield.
  15. *
  16. * pkt_idx: index of packet within datagram.
  17. */
  18. static ossl_inline void pkt_mark(uint64_t *bitf, size_t pkt_idx)
  19. {
  20. assert(pkt_idx < QUIC_MAX_PKT_PER_URXE);
  21. *bitf |= ((uint64_t)1) << pkt_idx;
  22. }
  23. /* Returns 1 if a packet is in the bitfield. */
  24. static ossl_inline int pkt_is_marked(const uint64_t *bitf, size_t pkt_idx)
  25. {
  26. assert(pkt_idx < QUIC_MAX_PKT_PER_URXE);
  27. return (*bitf & (((uint64_t)1) << pkt_idx)) != 0;
  28. }
  29. /*
  30. * RXE
  31. * ===
  32. *
  33. * RX Entries (RXEs) store processed (i.e., decrypted) data received from the
  34. * network. One RXE is used per received QUIC packet.
  35. */
  36. typedef struct rxe_st RXE;
  37. struct rxe_st {
  38. RXE *prev, *next;
  39. size_t data_len, alloc_len;
  40. /* Extra fields for per-packet information. */
  41. QUIC_PKT_HDR hdr; /* data/len are decrypted payload */
  42. /* Decoded packet number. */
  43. QUIC_PN pn;
  44. /* Addresses copied from URXE. */
  45. BIO_ADDR peer, local;
  46. /* Time we received the packet (not when we processed it). */
  47. OSSL_TIME time;
  48. /* Total length of the datagram which contained this packet. */
  49. size_t datagram_len;
  50. /*
  51. * alloc_len allocated bytes (of which data_len bytes are valid) follow this
  52. * structure.
  53. */
  54. };
  55. typedef struct ossl_qrx_rxe_list_st {
  56. RXE *head, *tail;
  57. } RXE_LIST;
  58. static ossl_inline unsigned char *rxe_data(const RXE *e)
  59. {
  60. return (unsigned char *)(e + 1);
  61. }
  62. static void rxe_remove(RXE_LIST *l, RXE *e)
  63. {
  64. if (e->prev != NULL)
  65. e->prev->next = e->next;
  66. if (e->next != NULL)
  67. e->next->prev = e->prev;
  68. if (e == l->head)
  69. l->head = e->next;
  70. if (e == l->tail)
  71. l->tail = e->prev;
  72. e->next = e->prev = NULL;
  73. }
  74. static void rxe_insert_tail(RXE_LIST *l, RXE *e)
  75. {
  76. if (l->tail == NULL) {
  77. l->head = l->tail = e;
  78. e->next = e->prev = NULL;
  79. return;
  80. }
  81. l->tail->next = e;
  82. e->prev = l->tail;
  83. e->next = NULL;
  84. l->tail = e;
  85. }
  86. /*
  87. * QRL
  88. * ===
  89. */
  90. struct ossl_qrx_st {
  91. OSSL_LIB_CTX *libctx;
  92. const char *propq;
  93. /* Demux to receive datagrams from. */
  94. QUIC_DEMUX *demux;
  95. /* Length of connection IDs used in short-header packets in bytes. */
  96. size_t short_conn_id_len;
  97. /*
  98. * List of URXEs which are filled with received encrypted data.
  99. * These are returned to the DEMUX's free list as they are processed.
  100. */
  101. QUIC_URXE_LIST urx_pending;
  102. /*
  103. * List of URXEs which we could not decrypt immediately and which are being
  104. * kept in case they can be decrypted later.
  105. */
  106. QUIC_URXE_LIST urx_deferred;
  107. /*
  108. * List of RXEs which are not currently in use. These are moved
  109. * to the pending list as they are filled.
  110. */
  111. RXE_LIST rx_free;
  112. /*
  113. * List of RXEs which are filled with decrypted packets ready to be passed
  114. * to the user. A RXE is removed from all lists inside the QRL when passed
  115. * to the user, then returned to the free list when the user returns it.
  116. */
  117. RXE_LIST rx_pending;
  118. /* Largest PN we have received and processed in a given PN space. */
  119. QUIC_PN largest_pn[QUIC_PN_SPACE_NUM];
  120. /* Per encryption-level state. */
  121. OSSL_QRL_ENC_LEVEL_SET el_set;
  122. /* Bytes we have received since this counter was last cleared. */
  123. uint64_t bytes_received;
  124. /*
  125. * Number of forged packets we have received since the QRX was instantiated.
  126. * Note that as per RFC 9001, this is connection-level state; it is not per
  127. * EL and is not reset by a key update.
  128. */
  129. uint64_t forged_pkt_count;
  130. /* Validation callback. */
  131. ossl_qrx_early_validation_cb *validation_cb;
  132. void *validation_cb_arg;
  133. /* Key update callback. */
  134. ossl_qrx_key_update_cb *key_update_cb;
  135. void *key_update_cb_arg;
  136. /* Initial key phase. For debugging use only; always 0 in real use. */
  137. unsigned char init_key_phase_bit;
  138. };
  139. static void qrx_on_rx(QUIC_URXE *urxe, void *arg);
  140. OSSL_QRX *ossl_qrx_new(const OSSL_QRX_ARGS *args)
  141. {
  142. OSSL_QRX *qrx;
  143. size_t i;
  144. if (args->demux == NULL)
  145. return 0;
  146. qrx = OPENSSL_zalloc(sizeof(OSSL_QRX));
  147. if (qrx == NULL)
  148. return 0;
  149. for (i = 0; i < OSSL_NELEM(qrx->largest_pn); ++i)
  150. qrx->largest_pn[i] = args->init_largest_pn[i];
  151. qrx->libctx = args->libctx;
  152. qrx->propq = args->propq;
  153. qrx->demux = args->demux;
  154. qrx->short_conn_id_len = args->short_conn_id_len;
  155. qrx->init_key_phase_bit = args->init_key_phase_bit;
  156. return qrx;
  157. }
  158. static void qrx_cleanup_rxl(RXE_LIST *l)
  159. {
  160. RXE *e, *enext;
  161. for (e = l->head; e != NULL; e = enext) {
  162. enext = e->next;
  163. OPENSSL_free(e);
  164. }
  165. l->head = l->tail = NULL;
  166. }
  167. static void qrx_cleanup_urxl(OSSL_QRX *qrx, QUIC_URXE_LIST *l)
  168. {
  169. QUIC_URXE *e, *enext;
  170. for (e = l->head; e != NULL; e = enext) {
  171. enext = e->next;
  172. ossl_quic_demux_release_urxe(qrx->demux, e);
  173. }
  174. l->head = l->tail = NULL;
  175. }
  176. void ossl_qrx_free(OSSL_QRX *qrx)
  177. {
  178. uint32_t i;
  179. /* Unregister from the RX DEMUX. */
  180. ossl_quic_demux_unregister_by_cb(qrx->demux, qrx_on_rx, qrx);
  181. /* Free RXE queue data. */
  182. qrx_cleanup_rxl(&qrx->rx_free);
  183. qrx_cleanup_rxl(&qrx->rx_pending);
  184. qrx_cleanup_urxl(qrx, &qrx->urx_pending);
  185. qrx_cleanup_urxl(qrx, &qrx->urx_deferred);
  186. /* Drop keying material and crypto resources. */
  187. for (i = 0; i < QUIC_ENC_LEVEL_NUM; ++i)
  188. ossl_qrl_enc_level_set_discard(&qrx->el_set, i);
  189. OPENSSL_free(qrx);
  190. }
  191. static void qrx_on_rx(QUIC_URXE *urxe, void *arg)
  192. {
  193. OSSL_QRX *qrx = arg;
  194. /* Initialize our own fields inside the URXE and add to the pending list. */
  195. urxe->processed = 0;
  196. urxe->hpr_removed = 0;
  197. ossl_quic_urxe_insert_tail(&qrx->urx_pending, urxe);
  198. }
  199. int ossl_qrx_add_dst_conn_id(OSSL_QRX *qrx,
  200. const QUIC_CONN_ID *dst_conn_id)
  201. {
  202. return ossl_quic_demux_register(qrx->demux,
  203. dst_conn_id,
  204. qrx_on_rx,
  205. qrx);
  206. }
  207. int ossl_qrx_remove_dst_conn_id(OSSL_QRX *qrx,
  208. const QUIC_CONN_ID *dst_conn_id)
  209. {
  210. return ossl_quic_demux_unregister(qrx->demux, dst_conn_id);
  211. }
  212. static void qrx_requeue_deferred(OSSL_QRX *qrx)
  213. {
  214. QUIC_URXE *e;
  215. while ((e = qrx->urx_deferred.head) != NULL) {
  216. ossl_quic_urxe_remove(&qrx->urx_deferred, e);
  217. ossl_quic_urxe_insert_head(&qrx->urx_pending, e);
  218. }
  219. }
  220. int ossl_qrx_provide_secret(OSSL_QRX *qrx, uint32_t enc_level,
  221. uint32_t suite_id, EVP_MD *md,
  222. const unsigned char *secret, size_t secret_len)
  223. {
  224. if (enc_level >= QUIC_ENC_LEVEL_NUM)
  225. return 0;
  226. if (!ossl_qrl_enc_level_set_provide_secret(&qrx->el_set,
  227. qrx->libctx,
  228. qrx->propq,
  229. enc_level,
  230. suite_id,
  231. md,
  232. secret,
  233. secret_len,
  234. qrx->init_key_phase_bit,
  235. /*is_tx=*/0))
  236. return 0;
  237. /*
  238. * Any packets we previously could not decrypt, we may now be able to
  239. * decrypt, so move any datagrams containing deferred packets from the
  240. * deferred to the pending queue.
  241. */
  242. qrx_requeue_deferred(qrx);
  243. return 1;
  244. }
  245. int ossl_qrx_discard_enc_level(OSSL_QRX *qrx, uint32_t enc_level)
  246. {
  247. if (enc_level >= QUIC_ENC_LEVEL_NUM)
  248. return 0;
  249. ossl_qrl_enc_level_set_discard(&qrx->el_set, enc_level);
  250. return 1;
  251. }
  252. /* Returns 1 if there are one or more pending RXEs. */
  253. int ossl_qrx_processed_read_pending(OSSL_QRX *qrx)
  254. {
  255. return qrx->rx_pending.head != NULL;
  256. }
  257. /* Returns 1 if there are yet-unprocessed packets. */
  258. int ossl_qrx_unprocessed_read_pending(OSSL_QRX *qrx)
  259. {
  260. return qrx->urx_pending.head != NULL || qrx->urx_deferred.head != NULL;
  261. }
  262. /* Pop the next pending RXE. Returns NULL if no RXE is pending. */
  263. static RXE *qrx_pop_pending_rxe(OSSL_QRX *qrx)
  264. {
  265. RXE *rxe = qrx->rx_pending.head;
  266. if (rxe == NULL)
  267. return NULL;
  268. rxe_remove(&qrx->rx_pending, rxe);
  269. return rxe;
  270. }
  271. /* Allocate a new RXE. */
  272. static RXE *qrx_alloc_rxe(size_t alloc_len)
  273. {
  274. RXE *rxe;
  275. if (alloc_len >= SIZE_MAX - sizeof(RXE))
  276. return NULL;
  277. rxe = OPENSSL_malloc(sizeof(RXE) + alloc_len);
  278. if (rxe == NULL)
  279. return NULL;
  280. rxe->prev = rxe->next = NULL;
  281. rxe->alloc_len = alloc_len;
  282. rxe->data_len = 0;
  283. return rxe;
  284. }
  285. /*
  286. * Ensures there is at least one RXE in the RX free list, allocating a new entry
  287. * if necessary. The returned RXE is in the RX free list; it is not popped.
  288. *
  289. * alloc_len is a hint which may be used to determine the RXE size if allocation
  290. * is necessary. Returns NULL on allocation failure.
  291. */
  292. static RXE *qrx_ensure_free_rxe(OSSL_QRX *qrx, size_t alloc_len)
  293. {
  294. RXE *rxe;
  295. if (qrx->rx_free.head != NULL)
  296. return qrx->rx_free.head;
  297. rxe = qrx_alloc_rxe(alloc_len);
  298. if (rxe == NULL)
  299. return NULL;
  300. rxe_insert_tail(&qrx->rx_free, rxe);
  301. return rxe;
  302. }
  303. /*
  304. * Resize the data buffer attached to an RXE to be n bytes in size. The address
  305. * of the RXE might change; the new address is returned, or NULL on failure, in
  306. * which case the original RXE remains valid.
  307. */
  308. static RXE *qrx_resize_rxe(RXE_LIST *rxl, RXE *rxe, size_t n)
  309. {
  310. RXE *rxe2;
  311. /* Should never happen. */
  312. if (rxe == NULL)
  313. return NULL;
  314. if (n >= SIZE_MAX - sizeof(RXE))
  315. return NULL;
  316. /*
  317. * NOTE: We do not clear old memory, although it does contain decrypted
  318. * data.
  319. */
  320. rxe2 = OPENSSL_realloc(rxe, sizeof(RXE) + n);
  321. if (rxe2 == NULL)
  322. /* original RXE is still intact unchanged */
  323. return NULL;
  324. if (rxe != rxe2) {
  325. if (rxl->head == rxe)
  326. rxl->head = rxe2;
  327. if (rxl->tail == rxe)
  328. rxl->tail = rxe2;
  329. if (rxe->prev != NULL)
  330. rxe->prev->next = rxe2;
  331. if (rxe->next != NULL)
  332. rxe->next->prev = rxe2;
  333. }
  334. rxe2->alloc_len = n;
  335. return rxe2;
  336. }
  337. /*
  338. * Ensure the data buffer attached to an RXE is at least n bytes in size.
  339. * Returns NULL on failure.
  340. */
  341. static RXE *qrx_reserve_rxe(RXE_LIST *rxl,
  342. RXE *rxe, size_t n)
  343. {
  344. if (rxe->alloc_len >= n)
  345. return rxe;
  346. return qrx_resize_rxe(rxl, rxe, n);
  347. }
  348. /* Return a RXE handed out to the user back to our freelist. */
  349. static void qrx_recycle_rxe(OSSL_QRX *qrx, RXE *rxe)
  350. {
  351. /* RXE should not be in any list */
  352. assert(rxe->prev == NULL && rxe->next == NULL);
  353. rxe_insert_tail(&qrx->rx_free, rxe);
  354. }
  355. /*
  356. * Given a pointer to a pointer pointing to a buffer and the size of that
  357. * buffer, copy the buffer into *prxe, expanding the RXE if necessary (its
  358. * pointer may change due to realloc). *pi is the offset in bytes to copy the
  359. * buffer to, and on success is updated to be the offset pointing after the
  360. * copied buffer. *pptr is updated to point to the new location of the buffer.
  361. */
  362. static int qrx_relocate_buffer(OSSL_QRX *qrx, RXE **prxe, size_t *pi,
  363. const unsigned char **pptr, size_t buf_len)
  364. {
  365. RXE *rxe;
  366. unsigned char *dst;
  367. if (!buf_len)
  368. return 1;
  369. if ((rxe = qrx_reserve_rxe(&qrx->rx_free, *prxe, *pi + buf_len)) == NULL)
  370. return 0;
  371. *prxe = rxe;
  372. dst = (unsigned char *)rxe_data(rxe) + *pi;
  373. memcpy(dst, *pptr, buf_len);
  374. *pi += buf_len;
  375. *pptr = dst;
  376. return 1;
  377. }
  378. static uint32_t qrx_determine_enc_level(const QUIC_PKT_HDR *hdr)
  379. {
  380. switch (hdr->type) {
  381. case QUIC_PKT_TYPE_INITIAL:
  382. return QUIC_ENC_LEVEL_INITIAL;
  383. case QUIC_PKT_TYPE_HANDSHAKE:
  384. return QUIC_ENC_LEVEL_HANDSHAKE;
  385. case QUIC_PKT_TYPE_0RTT:
  386. return QUIC_ENC_LEVEL_0RTT;
  387. case QUIC_PKT_TYPE_1RTT:
  388. return QUIC_ENC_LEVEL_1RTT;
  389. default:
  390. assert(0);
  391. case QUIC_PKT_TYPE_RETRY:
  392. case QUIC_PKT_TYPE_VERSION_NEG:
  393. return QUIC_ENC_LEVEL_INITIAL; /* not used */
  394. }
  395. }
  396. static uint32_t rxe_determine_pn_space(RXE *rxe)
  397. {
  398. uint32_t enc_level;
  399. enc_level = qrx_determine_enc_level(&rxe->hdr);
  400. return ossl_quic_enc_level_to_pn_space(enc_level);
  401. }
  402. static int qrx_validate_hdr_early(OSSL_QRX *qrx, RXE *rxe,
  403. RXE *first_rxe)
  404. {
  405. /* Ensure version is what we want. */
  406. if (rxe->hdr.version != QUIC_VERSION_1
  407. && rxe->hdr.version != QUIC_VERSION_NONE)
  408. return 0;
  409. /* Clients should never receive 0-RTT packets. */
  410. if (rxe->hdr.type == QUIC_PKT_TYPE_0RTT)
  411. return 0;
  412. /* Version negotiation and retry packets must be the first packet. */
  413. if (first_rxe != NULL && !ossl_quic_pkt_type_can_share_dgram(rxe->hdr.type))
  414. return 0;
  415. /*
  416. * If this is not the first packet in a datagram, the destination connection
  417. * ID must match the one in that packet.
  418. */
  419. if (first_rxe != NULL &&
  420. !ossl_quic_conn_id_eq(&first_rxe->hdr.dst_conn_id,
  421. &rxe->hdr.dst_conn_id))
  422. return 0;
  423. return 1;
  424. }
  425. /* Validate header and decode PN. */
  426. static int qrx_validate_hdr(OSSL_QRX *qrx, RXE *rxe)
  427. {
  428. int pn_space = rxe_determine_pn_space(rxe);
  429. if (!ossl_quic_wire_decode_pkt_hdr_pn(rxe->hdr.pn, rxe->hdr.pn_len,
  430. qrx->largest_pn[pn_space],
  431. &rxe->pn))
  432. return 0;
  433. /*
  434. * Allow our user to decide whether to discard the packet before we try and
  435. * decrypt it.
  436. */
  437. if (qrx->validation_cb != NULL
  438. && !qrx->validation_cb(rxe->pn, pn_space, qrx->validation_cb_arg))
  439. return 0;
  440. return 1;
  441. }
  442. /* Retrieves the correct cipher context for an EL and key phase. */
  443. static size_t qrx_get_cipher_ctx_idx(OSSL_QRX *qrx, OSSL_QRL_ENC_LEVEL *el,
  444. uint32_t enc_level,
  445. unsigned char key_phase_bit)
  446. {
  447. if (enc_level != QUIC_ENC_LEVEL_1RTT)
  448. return 0;
  449. if (!ossl_assert(key_phase_bit <= 1))
  450. return SIZE_MAX;
  451. /*
  452. * RFC 9001 requires that we not create timing channels which could reveal
  453. * the decrypted value of the Key Phase bit. We usually handle this by
  454. * keeping the cipher contexts for both the current and next key epochs
  455. * around, so that we just select a cipher context blindly using the key
  456. * phase bit, which is time-invariant.
  457. *
  458. * In the COOLDOWN state, we only have one keyslot/cipher context. RFC 9001
  459. * suggests an implementation strategy to avoid creating a timing channel in
  460. * this case:
  461. *
  462. * Endpoints can use randomized packet protection keys in place of
  463. * discarded keys when key updates are not yet permitted.
  464. *
  465. * Rather than use a randomised key, we simply use our existing key as it
  466. * will fail AEAD verification anyway. This avoids the need to keep around a
  467. * dedicated garbage key.
  468. *
  469. * Note: Accessing different cipher contexts is technically not
  470. * timing-channel safe due to microarchitectural side channels, but this is
  471. * the best we can reasonably do and appears to be directly suggested by the
  472. * RFC.
  473. */
  474. return el->state == QRL_EL_STATE_PROV_COOLDOWN ? el->key_epoch & 1
  475. : key_phase_bit;
  476. }
  477. /*
  478. * Tries to decrypt a packet payload.
  479. *
  480. * Returns 1 on success or 0 on failure (which is permanent). The payload is
  481. * decrypted from src and written to dst. The buffer dst must be of at least
  482. * src_len bytes in length. The actual length of the output in bytes is written
  483. * to *dec_len on success, which will always be equal to or less than (usually
  484. * less than) src_len.
  485. */
  486. static int qrx_decrypt_pkt_body(OSSL_QRX *qrx, unsigned char *dst,
  487. const unsigned char *src,
  488. size_t src_len, size_t *dec_len,
  489. const unsigned char *aad, size_t aad_len,
  490. QUIC_PN pn, uint32_t enc_level,
  491. unsigned char key_phase_bit)
  492. {
  493. int l = 0, l2 = 0;
  494. unsigned char nonce[EVP_MAX_IV_LENGTH];
  495. size_t nonce_len, i, cctx_idx;
  496. OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(&qrx->el_set,
  497. enc_level, 1);
  498. EVP_CIPHER_CTX *cctx;
  499. if (src_len > INT_MAX || aad_len > INT_MAX)
  500. return 0;
  501. /* We should not have been called if we do not have key material. */
  502. if (!ossl_assert(el != NULL))
  503. return 0;
  504. if (el->tag_len >= src_len)
  505. return 0;
  506. /*
  507. * If we have failed to authenticate a certain number of ciphertexts, refuse
  508. * to decrypt any more ciphertexts.
  509. */
  510. if (qrx->forged_pkt_count >= ossl_qrl_get_suite_max_forged_pkt(el->suite_id))
  511. return 0;
  512. cctx_idx = qrx_get_cipher_ctx_idx(qrx, el, enc_level, key_phase_bit);
  513. if (!ossl_assert(cctx_idx < OSSL_NELEM(el->cctx)))
  514. return 0;
  515. cctx = el->cctx[cctx_idx];
  516. /* Construct nonce (nonce=IV ^ PN). */
  517. nonce_len = EVP_CIPHER_CTX_get_iv_length(cctx);
  518. if (!ossl_assert(nonce_len >= sizeof(QUIC_PN)))
  519. return 0;
  520. memcpy(nonce, el->iv[cctx_idx], nonce_len);
  521. for (i = 0; i < sizeof(QUIC_PN); ++i)
  522. nonce[nonce_len - i - 1] ^= (unsigned char)(pn >> (i * 8));
  523. /* type and key will already have been setup; feed the IV. */
  524. if (EVP_CipherInit_ex(cctx, NULL,
  525. NULL, NULL, nonce, /*enc=*/0) != 1)
  526. return 0;
  527. /* Feed the AEAD tag we got so the cipher can validate it. */
  528. if (EVP_CIPHER_CTX_ctrl(cctx, EVP_CTRL_AEAD_SET_TAG,
  529. el->tag_len,
  530. (unsigned char *)src + src_len - el->tag_len) != 1)
  531. return 0;
  532. /* Feed AAD data. */
  533. if (EVP_CipherUpdate(cctx, NULL, &l, aad, aad_len) != 1)
  534. return 0;
  535. /* Feed encrypted packet body. */
  536. if (EVP_CipherUpdate(cctx, dst, &l, src, src_len - el->tag_len) != 1)
  537. return 0;
  538. /* Ensure authentication succeeded. */
  539. if (EVP_CipherFinal_ex(cctx, NULL, &l2) != 1) {
  540. /* Authentication failed, increment failed auth counter. */
  541. ++qrx->forged_pkt_count;
  542. return 0;
  543. }
  544. *dec_len = l;
  545. return 1;
  546. }
  547. static ossl_inline void ignore_res(int x)
  548. {
  549. /* No-op. */
  550. }
  551. static void qrx_key_update_initiated(OSSL_QRX *qrx)
  552. {
  553. if (!ossl_qrl_enc_level_set_key_update(&qrx->el_set, QUIC_ENC_LEVEL_1RTT))
  554. return;
  555. if (qrx->key_update_cb != NULL)
  556. qrx->key_update_cb(qrx->key_update_cb_arg);
  557. }
  558. /* Process a single packet in a datagram. */
  559. static int qrx_process_pkt(OSSL_QRX *qrx, QUIC_URXE *urxe,
  560. PACKET *pkt, size_t pkt_idx,
  561. RXE **first_rxe,
  562. size_t datagram_len)
  563. {
  564. RXE *rxe;
  565. const unsigned char *eop = NULL;
  566. size_t i, aad_len = 0, dec_len = 0;
  567. PACKET orig_pkt = *pkt;
  568. const unsigned char *sop = PACKET_data(pkt);
  569. unsigned char *dst;
  570. char need_second_decode = 0, already_processed = 0;
  571. QUIC_PKT_HDR_PTRS ptrs;
  572. uint32_t pn_space, enc_level;
  573. OSSL_QRL_ENC_LEVEL *el = NULL;
  574. /*
  575. * Get a free RXE. If we need to allocate a new one, use the packet length
  576. * as a good ballpark figure.
  577. */
  578. rxe = qrx_ensure_free_rxe(qrx, PACKET_remaining(pkt));
  579. if (rxe == NULL)
  580. return 0;
  581. /* Have we already processed this packet? */
  582. if (pkt_is_marked(&urxe->processed, pkt_idx))
  583. already_processed = 1;
  584. /*
  585. * Decode the header into the RXE structure. We first decrypt and read the
  586. * unprotected part of the packet header (unless we already removed header
  587. * protection, in which case we decode all of it).
  588. */
  589. need_second_decode = !pkt_is_marked(&urxe->hpr_removed, pkt_idx);
  590. if (!ossl_quic_wire_decode_pkt_hdr(pkt,
  591. qrx->short_conn_id_len,
  592. need_second_decode, &rxe->hdr, &ptrs))
  593. goto malformed;
  594. /*
  595. * Our successful decode above included an intelligible length and the
  596. * PACKET is now pointing to the end of the QUIC packet.
  597. */
  598. eop = PACKET_data(pkt);
  599. /*
  600. * Make a note of the first RXE so we can later ensure the destination
  601. * connection IDs of all packets in a datagram match.
  602. */
  603. if (pkt_idx == 0)
  604. *first_rxe = rxe;
  605. /*
  606. * Early header validation. Since we now know the packet length, we can also
  607. * now skip over it if we already processed it.
  608. */
  609. if (already_processed
  610. || !qrx_validate_hdr_early(qrx, rxe, pkt_idx == 0 ? NULL : *first_rxe))
  611. /*
  612. * Already processed packets are handled identically to malformed
  613. * packets; i.e., they are ignored.
  614. */
  615. goto malformed;
  616. if (!ossl_quic_pkt_type_is_encrypted(rxe->hdr.type)) {
  617. /*
  618. * Version negotiation and retry packets are a special case. They do not
  619. * contain a payload which needs decrypting and have no header
  620. * protection.
  621. */
  622. /* Just copy the payload from the URXE to the RXE. */
  623. if ((rxe = qrx_reserve_rxe(&qrx->rx_free, rxe, rxe->hdr.len)) == NULL)
  624. /*
  625. * Allocation failure. EOP will be pointing to the end of the
  626. * datagram so processing of this datagram will end here.
  627. */
  628. goto malformed;
  629. /* We are now committed to returning the packet. */
  630. memcpy(rxe_data(rxe), rxe->hdr.data, rxe->hdr.len);
  631. pkt_mark(&urxe->processed, pkt_idx);
  632. rxe->hdr.data = rxe_data(rxe);
  633. rxe->pn = QUIC_PN_INVALID;
  634. /* Move RXE to pending. */
  635. rxe_remove(&qrx->rx_free, rxe);
  636. rxe_insert_tail(&qrx->rx_pending, rxe);
  637. return 0; /* success, did not defer */
  638. }
  639. /* Determine encryption level of packet. */
  640. enc_level = qrx_determine_enc_level(&rxe->hdr);
  641. /* If we do not have keying material for this encryption level yet, defer. */
  642. switch (ossl_qrl_enc_level_set_have_el(&qrx->el_set, enc_level)) {
  643. case 1:
  644. /* We have keys. */
  645. break;
  646. case 0:
  647. /* No keys yet. */
  648. goto cannot_decrypt;
  649. default:
  650. /* We already discarded keys for this EL, we will never process this.*/
  651. goto malformed;
  652. }
  653. /*
  654. * We will copy any token included in the packet to the start of our RXE
  655. * data buffer (so that we don't reference the URXE buffer any more and can
  656. * recycle it). Track our position in the RXE buffer by index instead of
  657. * pointer as the pointer may change as reallocs occur.
  658. */
  659. i = 0;
  660. /*
  661. * rxe->hdr.data is now pointing at the (encrypted) packet payload. rxe->hdr
  662. * also has fields pointing into the PACKET buffer which will be going away
  663. * soon (the URXE will be reused for another incoming packet).
  664. *
  665. * Firstly, relocate some of these fields into the RXE as needed.
  666. *
  667. * Relocate token buffer and fix pointer.
  668. */
  669. if (rxe->hdr.type == QUIC_PKT_TYPE_INITIAL
  670. && !qrx_relocate_buffer(qrx, &rxe, &i, &rxe->hdr.token,
  671. rxe->hdr.token_len))
  672. goto malformed;
  673. /* Now remove header protection. */
  674. *pkt = orig_pkt;
  675. el = ossl_qrl_enc_level_set_get(&qrx->el_set, enc_level, 1);
  676. assert(el != NULL); /* Already checked above */
  677. if (need_second_decode) {
  678. if (!ossl_quic_hdr_protector_decrypt(&el->hpr, &ptrs))
  679. goto malformed;
  680. /*
  681. * We have removed header protection, so don't attempt to do it again if
  682. * the packet gets deferred and processed again.
  683. */
  684. pkt_mark(&urxe->hpr_removed, pkt_idx);
  685. /* Decode the now unprotected header. */
  686. if (ossl_quic_wire_decode_pkt_hdr(pkt, qrx->short_conn_id_len,
  687. 0, &rxe->hdr, NULL) != 1)
  688. goto malformed;
  689. }
  690. /* Validate header and decode PN. */
  691. if (!qrx_validate_hdr(qrx, rxe))
  692. goto malformed;
  693. /*
  694. * We automatically discard INITIAL keys when successfully decrypting a
  695. * HANDSHAKE packet.
  696. */
  697. if (enc_level == QUIC_ENC_LEVEL_HANDSHAKE)
  698. ossl_qrl_enc_level_set_discard(&qrx->el_set, QUIC_ENC_LEVEL_INITIAL);
  699. /*
  700. * The AAD data is the entire (unprotected) packet header including the PN.
  701. * The packet header has been unprotected in place, so we can just reuse the
  702. * PACKET buffer. The header ends where the payload begins.
  703. */
  704. aad_len = rxe->hdr.data - sop;
  705. /* Ensure the RXE buffer size is adequate for our payload. */
  706. if ((rxe = qrx_reserve_rxe(&qrx->rx_free, rxe, rxe->hdr.len + i)) == NULL) {
  707. /*
  708. * Allocation failure, treat as malformed and do not bother processing
  709. * any further packets in the datagram as they are likely to also
  710. * encounter allocation failures.
  711. */
  712. eop = NULL;
  713. goto malformed;
  714. }
  715. /*
  716. * We decrypt the packet body to immediately after the token at the start of
  717. * the RXE buffer (where present).
  718. *
  719. * Do the decryption from the PACKET (which points into URXE memory) to our
  720. * RXE payload (single-copy decryption), then fixup the pointers in the
  721. * header to point to our new buffer.
  722. *
  723. * If decryption fails this is considered a permanent error; we defer
  724. * packets we don't yet have decryption keys for above, so if this fails,
  725. * something has gone wrong with the handshake process or a packet has been
  726. * corrupted.
  727. */
  728. dst = (unsigned char *)rxe_data(rxe) + i;
  729. if (!qrx_decrypt_pkt_body(qrx, dst, rxe->hdr.data, rxe->hdr.len,
  730. &dec_len, sop, aad_len, rxe->pn, enc_level,
  731. rxe->hdr.key_phase))
  732. goto malformed;
  733. /*
  734. * At this point, we have successfully authenticated the AEAD tag and no
  735. * longer need to worry about exposing the Key Phase bit in timing channels.
  736. * Check for a Key Phase bit differing from our expectation.
  737. */
  738. if (rxe->hdr.type == QUIC_PKT_TYPE_1RTT
  739. && rxe->hdr.key_phase != (el->key_epoch & 1))
  740. qrx_key_update_initiated(qrx);
  741. /*
  742. * We have now successfully decrypted the packet payload. If there are
  743. * additional packets in the datagram, it is possible we will fail to
  744. * decrypt them and need to defer them until we have some key material we
  745. * don't currently possess. If this happens, the URXE will be moved to the
  746. * deferred queue. Since a URXE corresponds to one datagram, which may
  747. * contain multiple packets, we must ensure any packets we have already
  748. * processed in the URXE are not processed again (this is an RFC
  749. * requirement). We do this by marking the nth packet in the datagram as
  750. * processed.
  751. *
  752. * We are now committed to returning this decrypted packet to the user,
  753. * meaning we now consider the packet processed and must mark it
  754. * accordingly.
  755. */
  756. pkt_mark(&urxe->processed, pkt_idx);
  757. /*
  758. * Update header to point to the decrypted buffer, which may be shorter
  759. * due to AEAD tags, block padding, etc.
  760. */
  761. rxe->hdr.data = dst;
  762. rxe->hdr.len = dec_len;
  763. rxe->data_len = dec_len;
  764. rxe->datagram_len = datagram_len;
  765. /* We processed the PN successfully, so update largest processed PN. */
  766. pn_space = rxe_determine_pn_space(rxe);
  767. if (rxe->pn > qrx->largest_pn[pn_space])
  768. qrx->largest_pn[pn_space] = rxe->pn;
  769. /* Copy across network addresses and RX time from URXE to RXE. */
  770. rxe->peer = urxe->peer;
  771. rxe->local = urxe->local;
  772. rxe->time = urxe->time;
  773. /* Move RXE to pending. */
  774. rxe_remove(&qrx->rx_free, rxe);
  775. rxe_insert_tail(&qrx->rx_pending, rxe);
  776. return 0; /* success, did not defer; not distinguished from failure */
  777. cannot_decrypt:
  778. /*
  779. * We cannot process this packet right now (but might be able to later). We
  780. * MUST attempt to process any other packets in the datagram, so defer it
  781. * and skip over it.
  782. */
  783. assert(eop != NULL && eop >= PACKET_data(pkt));
  784. /*
  785. * We don't care if this fails as it will just result in the packet being at
  786. * the end of the datagram buffer.
  787. */
  788. ignore_res(PACKET_forward(pkt, eop - PACKET_data(pkt)));
  789. return 1; /* deferred */
  790. malformed:
  791. if (eop != NULL) {
  792. /*
  793. * This packet cannot be processed and will never be processable. We
  794. * were at least able to decode its header and determine its length, so
  795. * we can skip over it and try to process any subsequent packets in the
  796. * datagram.
  797. *
  798. * Mark as processed as an optimization.
  799. */
  800. assert(eop >= PACKET_data(pkt));
  801. pkt_mark(&urxe->processed, pkt_idx);
  802. /* We don't care if this fails (see above) */
  803. ignore_res(PACKET_forward(pkt, eop - PACKET_data(pkt)));
  804. } else {
  805. /*
  806. * This packet cannot be processed and will never be processable.
  807. * Because even its header is not intelligible, we cannot examine any
  808. * further packets in the datagram because its length cannot be
  809. * discerned.
  810. *
  811. * Advance over the entire remainder of the datagram, and mark it as
  812. * processed gap as an optimization.
  813. */
  814. pkt_mark(&urxe->processed, pkt_idx);
  815. /* We don't care if this fails (see above) */
  816. ignore_res(PACKET_forward(pkt, PACKET_remaining(pkt)));
  817. }
  818. return 0; /* failure, did not defer; not distinguished from success */
  819. }
  820. /* Process a datagram which was received. */
  821. static int qrx_process_datagram(OSSL_QRX *qrx, QUIC_URXE *e,
  822. const unsigned char *data,
  823. size_t data_len)
  824. {
  825. int have_deferred = 0;
  826. PACKET pkt;
  827. size_t pkt_idx = 0;
  828. RXE *first_rxe = NULL;
  829. qrx->bytes_received += data_len;
  830. if (!PACKET_buf_init(&pkt, data, data_len))
  831. return 0;
  832. for (; PACKET_remaining(&pkt) > 0; ++pkt_idx) {
  833. /*
  834. * A packet smallest than the minimum possible QUIC packet size is not
  835. * considered valid. We also ignore more than a certain number of
  836. * packets within the same datagram.
  837. */
  838. if (PACKET_remaining(&pkt) < QUIC_MIN_VALID_PKT_LEN
  839. || pkt_idx >= QUIC_MAX_PKT_PER_URXE)
  840. break;
  841. /*
  842. * We note whether packet processing resulted in a deferral since
  843. * this means we need to move the URXE to the deferred list rather
  844. * than the free list after we're finished dealing with it for now.
  845. *
  846. * However, we don't otherwise care here whether processing succeeded or
  847. * failed, as the RFC says even if a packet in a datagram is malformed,
  848. * we should still try to process any packets following it.
  849. *
  850. * In the case where the packet is so malformed we can't determine its
  851. * length, qrx_process_pkt will take care of advancing to the end of
  852. * the packet, so we will exit the loop automatically in this case.
  853. */
  854. if (qrx_process_pkt(qrx, e, &pkt, pkt_idx, &first_rxe, data_len))
  855. have_deferred = 1;
  856. }
  857. /* Only report whether there were any deferrals. */
  858. return have_deferred;
  859. }
  860. /* Process a single pending URXE. */
  861. static int qrx_process_one_urxe(OSSL_QRX *qrx, QUIC_URXE *e)
  862. {
  863. int was_deferred;
  864. /* The next URXE we process should be at the head of the pending list. */
  865. if (!ossl_assert(e == qrx->urx_pending.head))
  866. return 0;
  867. /*
  868. * Attempt to process the datagram. The return value indicates only if
  869. * processing of the datagram was deferred. If we failed to process the
  870. * datagram, we do not attempt to process it again and silently eat the
  871. * error.
  872. */
  873. was_deferred = qrx_process_datagram(qrx, e, ossl_quic_urxe_data(e),
  874. e->data_len);
  875. /*
  876. * Remove the URXE from the pending list and return it to
  877. * either the free or deferred list.
  878. */
  879. ossl_quic_urxe_remove(&qrx->urx_pending, e);
  880. if (was_deferred > 0)
  881. ossl_quic_urxe_insert_tail(&qrx->urx_deferred, e);
  882. else
  883. ossl_quic_demux_release_urxe(qrx->demux, e);
  884. return 1;
  885. }
  886. /* Process any pending URXEs to generate pending RXEs. */
  887. static int qrx_process_pending_urxl(OSSL_QRX *qrx)
  888. {
  889. QUIC_URXE *e;
  890. while ((e = qrx->urx_pending.head) != NULL)
  891. if (!qrx_process_one_urxe(qrx, e))
  892. return 0;
  893. return 1;
  894. }
  895. int ossl_qrx_read_pkt(OSSL_QRX *qrx, OSSL_QRX_PKT *pkt)
  896. {
  897. RXE *rxe;
  898. if (!ossl_qrx_processed_read_pending(qrx)) {
  899. if (!qrx_process_pending_urxl(qrx))
  900. return 0;
  901. if (!ossl_qrx_processed_read_pending(qrx))
  902. return 0;
  903. }
  904. rxe = qrx_pop_pending_rxe(qrx);
  905. if (!ossl_assert(rxe != NULL))
  906. return 0;
  907. pkt->handle = rxe;
  908. pkt->hdr = &rxe->hdr;
  909. pkt->pn = rxe->pn;
  910. pkt->time = rxe->time;
  911. pkt->peer
  912. = BIO_ADDR_family(&rxe->peer) != AF_UNSPEC ? &rxe->peer : NULL;
  913. pkt->local
  914. = BIO_ADDR_family(&rxe->local) != AF_UNSPEC ? &rxe->local : NULL;
  915. return 1;
  916. }
  917. void ossl_qrx_release_pkt(OSSL_QRX *qrx, void *handle)
  918. {
  919. RXE *rxe = handle;
  920. qrx_recycle_rxe(qrx, rxe);
  921. }
  922. uint64_t ossl_qrx_get_bytes_received(OSSL_QRX *qrx, int clear)
  923. {
  924. uint64_t v = qrx->bytes_received;
  925. if (clear)
  926. qrx->bytes_received = 0;
  927. return v;
  928. }
  929. int ossl_qrx_set_early_validation_cb(OSSL_QRX *qrx,
  930. ossl_qrx_early_validation_cb *cb,
  931. void *cb_arg)
  932. {
  933. qrx->validation_cb = cb;
  934. qrx->validation_cb_arg = cb_arg;
  935. return 1;
  936. }
  937. int ossl_qrx_set_key_update_cb(OSSL_QRX *qrx,
  938. ossl_qrx_key_update_cb *cb,
  939. void *cb_arg)
  940. {
  941. qrx->key_update_cb = cb;
  942. qrx->key_update_cb_arg = cb_arg;
  943. return 1;
  944. }
  945. uint64_t ossl_qrx_get_key_epoch(OSSL_QRX *qrx)
  946. {
  947. OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(&qrx->el_set,
  948. QUIC_ENC_LEVEL_1RTT, 1);
  949. return el == NULL ? UINT64_MAX : el->key_epoch;
  950. }
  951. int ossl_qrx_key_update_timeout(OSSL_QRX *qrx, int normal)
  952. {
  953. OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(&qrx->el_set,
  954. QUIC_ENC_LEVEL_1RTT, 1);
  955. if (el == NULL)
  956. return 0;
  957. if (el->state == QRL_EL_STATE_PROV_UPDATING
  958. && !ossl_qrl_enc_level_set_key_update_done(&qrx->el_set,
  959. QUIC_ENC_LEVEL_1RTT))
  960. return 0;
  961. if (normal && el->state == QRL_EL_STATE_PROV_COOLDOWN
  962. && !ossl_qrl_enc_level_set_key_cooldown_done(&qrx->el_set,
  963. QUIC_ENC_LEVEL_1RTT))
  964. return 0;
  965. return 1;
  966. }
  967. uint64_t ossl_qrx_get_cur_forged_pkt_count(OSSL_QRX *qrx)
  968. {
  969. return qrx->forged_pkt_count;
  970. }
  971. uint64_t ossl_qrx_get_max_forged_pkt_count(OSSL_QRX *qrx,
  972. uint32_t enc_level)
  973. {
  974. OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(&qrx->el_set,
  975. enc_level, 1);
  976. return el == NULL ? UINT64_MAX
  977. : ossl_qrl_get_suite_max_forged_pkt(el->suite_id);
  978. }