2 * Copyright 2022 The OpenSSL Project Authors. All Rights Reserved.
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
10 #include "internal/quic_record_rx.h"
11 #include "quic_record_shared.h"
12 #include "internal/common.h"
13 #include "../ssl_local.h"
16 * Mark a packet in a bitfield.
18 * pkt_idx: index of packet within datagram.
20 static ossl_inline void pkt_mark(uint64_t *bitf, size_t pkt_idx)
22 assert(pkt_idx < QUIC_MAX_PKT_PER_URXE);
23 *bitf |= ((uint64_t)1) << pkt_idx;
26 /* Returns 1 if a packet is in the bitfield. */
27 static ossl_inline int pkt_is_marked(const uint64_t *bitf, size_t pkt_idx)
29 assert(pkt_idx < QUIC_MAX_PKT_PER_URXE);
30 return (*bitf & (((uint64_t)1) << pkt_idx)) != 0;
37 * RX Entries (RXEs) store processed (i.e., decrypted) data received from the
38 * network. One RXE is used per received QUIC packet.
40 typedef struct rxe_st RXE;
44 size_t data_len, alloc_len;
46 /* Extra fields for per-packet information. */
47 QUIC_PKT_HDR hdr; /* data/len are decrypted payload */
49 /* Decoded packet number. */
52 /* Addresses copied from URXE. */
55 /* Time we received the packet (not when we processed it). */
58 /* Total length of the datagram which contained this packet. */
62 * alloc_len allocated bytes (of which data_len bytes are valid) follow this
67 typedef struct ossl_qrx_rxe_list_st {
71 static ossl_inline unsigned char *rxe_data(const RXE *e)
73 return (unsigned char *)(e + 1);
76 static void rxe_remove(RXE_LIST *l, RXE *e)
79 e->prev->next = e->next;
81 e->next->prev = e->prev;
88 e->next = e->prev = NULL;
91 static void rxe_insert_tail(RXE_LIST *l, RXE *e)
93 if (l->tail == NULL) {
94 l->head = l->tail = e;
95 e->next = e->prev = NULL;
110 OSSL_LIB_CTX *libctx;
113 /* Demux to receive datagrams from. */
116 /* Length of connection IDs used in short-header packets in bytes. */
117 size_t short_conn_id_len;
119 /* Maximum number of deferred datagrams buffered at any one time. */
122 /* Current count of deferred datagrams. */
126 * List of URXEs which are filled with received encrypted data.
127 * These are returned to the DEMUX's free list as they are processed.
129 QUIC_URXE_LIST urx_pending;
132 * List of URXEs which we could not decrypt immediately and which are being
133 * kept in case they can be decrypted later.
135 QUIC_URXE_LIST urx_deferred;
138 * List of RXEs which are not currently in use. These are moved
139 * to the pending list as they are filled.
144 * List of RXEs which are filled with decrypted packets ready to be passed
145 * to the user. A RXE is removed from all lists inside the QRL when passed
146 * to the user, then returned to the free list when the user returns it.
150 /* Largest PN we have received and processed in a given PN space. */
151 QUIC_PN largest_pn[QUIC_PN_SPACE_NUM];
153 /* Per encryption-level state. */
154 OSSL_QRL_ENC_LEVEL_SET el_set;
156 /* Bytes we have received since this counter was last cleared. */
157 uint64_t bytes_received;
160 * Number of forged packets we have received since the QRX was instantiated.
161 * Note that as per RFC 9001, this is connection-level state; it is not per
162 * EL and is not reset by a key update.
164 uint64_t forged_pkt_count;
166 /* Validation callback. */
167 ossl_qrx_early_validation_cb *validation_cb;
168 void *validation_cb_arg;
170 /* Key update callback. */
171 ossl_qrx_key_update_cb *key_update_cb;
172 void *key_update_cb_arg;
174 /* Initial key phase. For debugging use only; always 0 in real use. */
175 unsigned char init_key_phase_bit;
178 static void qrx_on_rx(QUIC_URXE *urxe, void *arg);
180 OSSL_QRX *ossl_qrx_new(const OSSL_QRX_ARGS *args)
185 if (args->demux == NULL || args->max_deferred == 0)
188 qrx = OPENSSL_zalloc(sizeof(OSSL_QRX));
192 for (i = 0; i < OSSL_NELEM(qrx->largest_pn); ++i)
193 qrx->largest_pn[i] = args->init_largest_pn[i];
195 qrx->libctx = args->libctx;
196 qrx->propq = args->propq;
197 qrx->demux = args->demux;
198 qrx->short_conn_id_len = args->short_conn_id_len;
199 qrx->init_key_phase_bit = args->init_key_phase_bit;
200 qrx->max_deferred = args->max_deferred;
204 static void qrx_cleanup_rxl(RXE_LIST *l)
208 for (e = l->head; e != NULL; e = enext) {
213 l->head = l->tail = NULL;
216 static void qrx_cleanup_urxl(OSSL_QRX *qrx, QUIC_URXE_LIST *l)
218 QUIC_URXE *e, *enext;
220 for (e = l->head; e != NULL; e = enext) {
222 ossl_quic_demux_release_urxe(qrx->demux, e);
225 l->head = l->tail = NULL;
228 void ossl_qrx_free(OSSL_QRX *qrx)
232 /* Unregister from the RX DEMUX. */
233 ossl_quic_demux_unregister_by_cb(qrx->demux, qrx_on_rx, qrx);
235 /* Free RXE queue data. */
236 qrx_cleanup_rxl(&qrx->rx_free);
237 qrx_cleanup_rxl(&qrx->rx_pending);
238 qrx_cleanup_urxl(qrx, &qrx->urx_pending);
239 qrx_cleanup_urxl(qrx, &qrx->urx_deferred);
241 /* Drop keying material and crypto resources. */
242 for (i = 0; i < QUIC_ENC_LEVEL_NUM; ++i)
243 ossl_qrl_enc_level_set_discard(&qrx->el_set, i);
248 static void qrx_on_rx(QUIC_URXE *urxe, void *arg)
252 /* Initialize our own fields inside the URXE and add to the pending list. */
254 urxe->hpr_removed = 0;
256 ossl_quic_urxe_insert_tail(&qrx->urx_pending, urxe);
259 int ossl_qrx_add_dst_conn_id(OSSL_QRX *qrx,
260 const QUIC_CONN_ID *dst_conn_id)
262 return ossl_quic_demux_register(qrx->demux,
268 int ossl_qrx_remove_dst_conn_id(OSSL_QRX *qrx,
269 const QUIC_CONN_ID *dst_conn_id)
271 return ossl_quic_demux_unregister(qrx->demux, dst_conn_id);
274 static void qrx_requeue_deferred(OSSL_QRX *qrx)
278 while ((e = qrx->urx_deferred.head) != NULL) {
279 ossl_quic_urxe_remove(&qrx->urx_deferred, e);
280 ossl_quic_urxe_insert_head(&qrx->urx_pending, e);
284 int ossl_qrx_provide_secret(OSSL_QRX *qrx, uint32_t enc_level,
285 uint32_t suite_id, EVP_MD *md,
286 const unsigned char *secret, size_t secret_len)
288 if (enc_level >= QUIC_ENC_LEVEL_NUM)
291 if (!ossl_qrl_enc_level_set_provide_secret(&qrx->el_set,
299 qrx->init_key_phase_bit,
304 * Any packets we previously could not decrypt, we may now be able to
305 * decrypt, so move any datagrams containing deferred packets from the
306 * deferred to the pending queue.
308 qrx_requeue_deferred(qrx);
312 int ossl_qrx_discard_enc_level(OSSL_QRX *qrx, uint32_t enc_level)
314 if (enc_level >= QUIC_ENC_LEVEL_NUM)
317 ossl_qrl_enc_level_set_discard(&qrx->el_set, enc_level);
321 /* Returns 1 if there are one or more pending RXEs. */
322 int ossl_qrx_processed_read_pending(OSSL_QRX *qrx)
324 return qrx->rx_pending.head != NULL;
327 /* Returns 1 if there are yet-unprocessed packets. */
328 int ossl_qrx_unprocessed_read_pending(OSSL_QRX *qrx)
330 return qrx->urx_pending.head != NULL || qrx->urx_deferred.head != NULL;
333 /* Pop the next pending RXE. Returns NULL if no RXE is pending. */
334 static RXE *qrx_pop_pending_rxe(OSSL_QRX *qrx)
336 RXE *rxe = qrx->rx_pending.head;
341 rxe_remove(&qrx->rx_pending, rxe);
345 /* Allocate a new RXE. */
346 static RXE *qrx_alloc_rxe(size_t alloc_len)
350 if (alloc_len >= SIZE_MAX - sizeof(RXE))
353 rxe = OPENSSL_malloc(sizeof(RXE) + alloc_len);
357 rxe->prev = rxe->next = NULL;
358 rxe->alloc_len = alloc_len;
364 * Ensures there is at least one RXE in the RX free list, allocating a new entry
365 * if necessary. The returned RXE is in the RX free list; it is not popped.
367 * alloc_len is a hint which may be used to determine the RXE size if allocation
368 * is necessary. Returns NULL on allocation failure.
370 static RXE *qrx_ensure_free_rxe(OSSL_QRX *qrx, size_t alloc_len)
374 if (qrx->rx_free.head != NULL)
375 return qrx->rx_free.head;
377 rxe = qrx_alloc_rxe(alloc_len);
381 rxe_insert_tail(&qrx->rx_free, rxe);
386 * Resize the data buffer attached to an RXE to be n bytes in size. The address
387 * of the RXE might change; the new address is returned, or NULL on failure, in
388 * which case the original RXE remains valid.
390 static RXE *qrx_resize_rxe(RXE_LIST *rxl, RXE *rxe, size_t n)
394 /* Should never happen. */
398 if (n >= SIZE_MAX - sizeof(RXE))
402 * NOTE: We do not clear old memory, although it does contain decrypted
405 rxe2 = OPENSSL_realloc(rxe, sizeof(RXE) + n);
407 /* original RXE is still intact unchanged */
411 if (rxl->head == rxe)
413 if (rxl->tail == rxe)
415 if (rxe->prev != NULL)
416 rxe->prev->next = rxe2;
417 if (rxe->next != NULL)
418 rxe->next->prev = rxe2;
426 * Ensure the data buffer attached to an RXE is at least n bytes in size.
427 * Returns NULL on failure.
429 static RXE *qrx_reserve_rxe(RXE_LIST *rxl,
432 if (rxe->alloc_len >= n)
435 return qrx_resize_rxe(rxl, rxe, n);
438 /* Return a RXE handed out to the user back to our freelist. */
439 static void qrx_recycle_rxe(OSSL_QRX *qrx, RXE *rxe)
441 /* RXE should not be in any list */
442 assert(rxe->prev == NULL && rxe->next == NULL);
443 rxe_insert_tail(&qrx->rx_free, rxe);
447 * Given a pointer to a pointer pointing to a buffer and the size of that
448 * buffer, copy the buffer into *prxe, expanding the RXE if necessary (its
449 * pointer may change due to realloc). *pi is the offset in bytes to copy the
450 * buffer to, and on success is updated to be the offset pointing after the
451 * copied buffer. *pptr is updated to point to the new location of the buffer.
453 static int qrx_relocate_buffer(OSSL_QRX *qrx, RXE **prxe, size_t *pi,
454 const unsigned char **pptr, size_t buf_len)
462 if ((rxe = qrx_reserve_rxe(&qrx->rx_free, *prxe, *pi + buf_len)) == NULL)
466 dst = (unsigned char *)rxe_data(rxe) + *pi;
468 memcpy(dst, *pptr, buf_len);
474 static uint32_t qrx_determine_enc_level(const QUIC_PKT_HDR *hdr)
477 case QUIC_PKT_TYPE_INITIAL:
478 return QUIC_ENC_LEVEL_INITIAL;
479 case QUIC_PKT_TYPE_HANDSHAKE:
480 return QUIC_ENC_LEVEL_HANDSHAKE;
481 case QUIC_PKT_TYPE_0RTT:
482 return QUIC_ENC_LEVEL_0RTT;
483 case QUIC_PKT_TYPE_1RTT:
484 return QUIC_ENC_LEVEL_1RTT;
488 case QUIC_PKT_TYPE_RETRY:
489 case QUIC_PKT_TYPE_VERSION_NEG:
490 return QUIC_ENC_LEVEL_INITIAL; /* not used */
494 static uint32_t rxe_determine_pn_space(RXE *rxe)
498 enc_level = qrx_determine_enc_level(&rxe->hdr);
499 return ossl_quic_enc_level_to_pn_space(enc_level);
502 static int qrx_validate_hdr_early(OSSL_QRX *qrx, RXE *rxe,
505 /* Ensure version is what we want. */
506 if (rxe->hdr.version != QUIC_VERSION_1
507 && rxe->hdr.version != QUIC_VERSION_NONE)
510 /* Clients should never receive 0-RTT packets. */
511 if (rxe->hdr.type == QUIC_PKT_TYPE_0RTT)
514 /* Version negotiation and retry packets must be the first packet. */
515 if (first_rxe != NULL && !ossl_quic_pkt_type_can_share_dgram(rxe->hdr.type))
519 * If this is not the first packet in a datagram, the destination connection
520 * ID must match the one in that packet.
522 if (first_rxe != NULL &&
523 !ossl_quic_conn_id_eq(&first_rxe->hdr.dst_conn_id,
524 &rxe->hdr.dst_conn_id))
530 /* Validate header and decode PN. */
531 static int qrx_validate_hdr(OSSL_QRX *qrx, RXE *rxe)
533 int pn_space = rxe_determine_pn_space(rxe);
535 if (!ossl_quic_wire_decode_pkt_hdr_pn(rxe->hdr.pn, rxe->hdr.pn_len,
536 qrx->largest_pn[pn_space],
541 * Allow our user to decide whether to discard the packet before we try and
544 if (qrx->validation_cb != NULL
545 && !qrx->validation_cb(rxe->pn, pn_space, qrx->validation_cb_arg))
551 /* Retrieves the correct cipher context for an EL and key phase. */
552 static size_t qrx_get_cipher_ctx_idx(OSSL_QRX *qrx, OSSL_QRL_ENC_LEVEL *el,
554 unsigned char key_phase_bit)
556 if (enc_level != QUIC_ENC_LEVEL_1RTT)
559 if (!ossl_assert(key_phase_bit <= 1))
563 * RFC 9001 requires that we not create timing channels which could reveal
564 * the decrypted value of the Key Phase bit. We usually handle this by
565 * keeping the cipher contexts for both the current and next key epochs
566 * around, so that we just select a cipher context blindly using the key
567 * phase bit, which is time-invariant.
569 * In the COOLDOWN state, we only have one keyslot/cipher context. RFC 9001
570 * suggests an implementation strategy to avoid creating a timing channel in
573 * Endpoints can use randomized packet protection keys in place of
574 * discarded keys when key updates are not yet permitted.
576 * Rather than use a randomised key, we simply use our existing key as it
577 * will fail AEAD verification anyway. This avoids the need to keep around a
578 * dedicated garbage key.
580 * Note: Accessing different cipher contexts is technically not
581 * timing-channel safe due to microarchitectural side channels, but this is
582 * the best we can reasonably do and appears to be directly suggested by the
585 return el->state == QRL_EL_STATE_PROV_COOLDOWN ? el->key_epoch & 1
590 * Tries to decrypt a packet payload.
592 * Returns 1 on success or 0 on failure (which is permanent). The payload is
593 * decrypted from src and written to dst. The buffer dst must be of at least
594 * src_len bytes in length. The actual length of the output in bytes is written
595 * to *dec_len on success, which will always be equal to or less than (usually
596 * less than) src_len.
598 static int qrx_decrypt_pkt_body(OSSL_QRX *qrx, unsigned char *dst,
599 const unsigned char *src,
600 size_t src_len, size_t *dec_len,
601 const unsigned char *aad, size_t aad_len,
602 QUIC_PN pn, uint32_t enc_level,
603 unsigned char key_phase_bit)
606 unsigned char nonce[EVP_MAX_IV_LENGTH];
607 size_t nonce_len, i, cctx_idx;
608 OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(&qrx->el_set,
610 EVP_CIPHER_CTX *cctx;
612 if (src_len > INT_MAX || aad_len > INT_MAX)
615 /* We should not have been called if we do not have key material. */
616 if (!ossl_assert(el != NULL))
619 if (el->tag_len >= src_len)
623 * If we have failed to authenticate a certain number of ciphertexts, refuse
624 * to decrypt any more ciphertexts.
626 if (qrx->forged_pkt_count >= ossl_qrl_get_suite_max_forged_pkt(el->suite_id))
629 cctx_idx = qrx_get_cipher_ctx_idx(qrx, el, enc_level, key_phase_bit);
630 if (!ossl_assert(cctx_idx < OSSL_NELEM(el->cctx)))
633 cctx = el->cctx[cctx_idx];
635 /* Construct nonce (nonce=IV ^ PN). */
636 nonce_len = EVP_CIPHER_CTX_get_iv_length(cctx);
637 if (!ossl_assert(nonce_len >= sizeof(QUIC_PN)))
640 memcpy(nonce, el->iv[cctx_idx], nonce_len);
641 for (i = 0; i < sizeof(QUIC_PN); ++i)
642 nonce[nonce_len - i - 1] ^= (unsigned char)(pn >> (i * 8));
644 /* type and key will already have been setup; feed the IV. */
645 if (EVP_CipherInit_ex(cctx, NULL,
646 NULL, NULL, nonce, /*enc=*/0) != 1)
649 /* Feed the AEAD tag we got so the cipher can validate it. */
650 if (EVP_CIPHER_CTX_ctrl(cctx, EVP_CTRL_AEAD_SET_TAG,
652 (unsigned char *)src + src_len - el->tag_len) != 1)
656 if (EVP_CipherUpdate(cctx, NULL, &l, aad, aad_len) != 1)
659 /* Feed encrypted packet body. */
660 if (EVP_CipherUpdate(cctx, dst, &l, src, src_len - el->tag_len) != 1)
663 /* Ensure authentication succeeded. */
664 if (EVP_CipherFinal_ex(cctx, NULL, &l2) != 1) {
665 /* Authentication failed, increment failed auth counter. */
666 ++qrx->forged_pkt_count;
674 static ossl_inline void ignore_res(int x)
679 static void qrx_key_update_initiated(OSSL_QRX *qrx)
681 if (!ossl_qrl_enc_level_set_key_update(&qrx->el_set, QUIC_ENC_LEVEL_1RTT))
684 if (qrx->key_update_cb != NULL)
685 qrx->key_update_cb(qrx->key_update_cb_arg);
688 /* Process a single packet in a datagram. */
689 static int qrx_process_pkt(OSSL_QRX *qrx, QUIC_URXE *urxe,
690 PACKET *pkt, size_t pkt_idx,
695 const unsigned char *eop = NULL;
696 size_t i, aad_len = 0, dec_len = 0;
697 PACKET orig_pkt = *pkt;
698 const unsigned char *sop = PACKET_data(pkt);
700 char need_second_decode = 0, already_processed = 0;
701 QUIC_PKT_HDR_PTRS ptrs;
702 uint32_t pn_space, enc_level;
703 OSSL_QRL_ENC_LEVEL *el = NULL;
706 * Get a free RXE. If we need to allocate a new one, use the packet length
707 * as a good ballpark figure.
709 rxe = qrx_ensure_free_rxe(qrx, PACKET_remaining(pkt));
713 /* Have we already processed this packet? */
714 if (pkt_is_marked(&urxe->processed, pkt_idx))
715 already_processed = 1;
718 * Decode the header into the RXE structure. We first decrypt and read the
719 * unprotected part of the packet header (unless we already removed header
720 * protection, in which case we decode all of it).
722 need_second_decode = !pkt_is_marked(&urxe->hpr_removed, pkt_idx);
723 if (!ossl_quic_wire_decode_pkt_hdr(pkt,
724 qrx->short_conn_id_len,
725 need_second_decode, &rxe->hdr, &ptrs))
729 * Our successful decode above included an intelligible length and the
730 * PACKET is now pointing to the end of the QUIC packet.
732 eop = PACKET_data(pkt);
735 * Make a note of the first RXE so we can later ensure the destination
736 * connection IDs of all packets in a datagram match.
742 * Early header validation. Since we now know the packet length, we can also
743 * now skip over it if we already processed it.
745 if (already_processed
746 || !qrx_validate_hdr_early(qrx, rxe, pkt_idx == 0 ? NULL : *first_rxe))
748 * Already processed packets are handled identically to malformed
749 * packets; i.e., they are ignored.
753 if (!ossl_quic_pkt_type_is_encrypted(rxe->hdr.type)) {
755 * Version negotiation and retry packets are a special case. They do not
756 * contain a payload which needs decrypting and have no header
760 /* Just copy the payload from the URXE to the RXE. */
761 if ((rxe = qrx_reserve_rxe(&qrx->rx_free, rxe, rxe->hdr.len)) == NULL)
763 * Allocation failure. EOP will be pointing to the end of the
764 * datagram so processing of this datagram will end here.
768 /* We are now committed to returning the packet. */
769 memcpy(rxe_data(rxe), rxe->hdr.data, rxe->hdr.len);
770 pkt_mark(&urxe->processed, pkt_idx);
772 rxe->hdr.data = rxe_data(rxe);
773 rxe->pn = QUIC_PN_INVALID;
775 /* Move RXE to pending. */
776 rxe_remove(&qrx->rx_free, rxe);
777 rxe_insert_tail(&qrx->rx_pending, rxe);
778 return 0; /* success, did not defer */
781 /* Determine encryption level of packet. */
782 enc_level = qrx_determine_enc_level(&rxe->hdr);
784 /* If we do not have keying material for this encryption level yet, defer. */
785 switch (ossl_qrl_enc_level_set_have_el(&qrx->el_set, enc_level)) {
793 /* We already discarded keys for this EL, we will never process this.*/
798 * We will copy any token included in the packet to the start of our RXE
799 * data buffer (so that we don't reference the URXE buffer any more and can
800 * recycle it). Track our position in the RXE buffer by index instead of
801 * pointer as the pointer may change as reallocs occur.
806 * rxe->hdr.data is now pointing at the (encrypted) packet payload. rxe->hdr
807 * also has fields pointing into the PACKET buffer which will be going away
808 * soon (the URXE will be reused for another incoming packet).
810 * Firstly, relocate some of these fields into the RXE as needed.
812 * Relocate token buffer and fix pointer.
814 if (rxe->hdr.type == QUIC_PKT_TYPE_INITIAL
815 && !qrx_relocate_buffer(qrx, &rxe, &i, &rxe->hdr.token,
819 /* Now remove header protection. */
822 el = ossl_qrl_enc_level_set_get(&qrx->el_set, enc_level, 1);
823 assert(el != NULL); /* Already checked above */
825 if (need_second_decode) {
826 if (!ossl_quic_hdr_protector_decrypt(&el->hpr, &ptrs))
830 * We have removed header protection, so don't attempt to do it again if
831 * the packet gets deferred and processed again.
833 pkt_mark(&urxe->hpr_removed, pkt_idx);
835 /* Decode the now unprotected header. */
836 if (ossl_quic_wire_decode_pkt_hdr(pkt, qrx->short_conn_id_len,
837 0, &rxe->hdr, NULL) != 1)
841 /* Validate header and decode PN. */
842 if (!qrx_validate_hdr(qrx, rxe))
846 * The AAD data is the entire (unprotected) packet header including the PN.
847 * The packet header has been unprotected in place, so we can just reuse the
848 * PACKET buffer. The header ends where the payload begins.
850 aad_len = rxe->hdr.data - sop;
852 /* Ensure the RXE buffer size is adequate for our payload. */
853 if ((rxe = qrx_reserve_rxe(&qrx->rx_free, rxe, rxe->hdr.len + i)) == NULL) {
855 * Allocation failure, treat as malformed and do not bother processing
856 * any further packets in the datagram as they are likely to also
857 * encounter allocation failures.
864 * We decrypt the packet body to immediately after the token at the start of
865 * the RXE buffer (where present).
867 * Do the decryption from the PACKET (which points into URXE memory) to our
868 * RXE payload (single-copy decryption), then fixup the pointers in the
869 * header to point to our new buffer.
871 * If decryption fails this is considered a permanent error; we defer
872 * packets we don't yet have decryption keys for above, so if this fails,
873 * something has gone wrong with the handshake process or a packet has been
876 dst = (unsigned char *)rxe_data(rxe) + i;
877 if (!qrx_decrypt_pkt_body(qrx, dst, rxe->hdr.data, rxe->hdr.len,
878 &dec_len, sop, aad_len, rxe->pn, enc_level,
883 * We automatically discard INITIAL keys when successfully decrypting a
886 if (enc_level == QUIC_ENC_LEVEL_HANDSHAKE)
887 ossl_qrl_enc_level_set_discard(&qrx->el_set, QUIC_ENC_LEVEL_INITIAL);
890 * At this point, we have successfully authenticated the AEAD tag and no
891 * longer need to worry about exposing the Key Phase bit in timing channels.
892 * Check for a Key Phase bit differing from our expectation.
894 if (rxe->hdr.type == QUIC_PKT_TYPE_1RTT
895 && rxe->hdr.key_phase != (el->key_epoch & 1))
896 qrx_key_update_initiated(qrx);
899 * We have now successfully decrypted the packet payload. If there are
900 * additional packets in the datagram, it is possible we will fail to
901 * decrypt them and need to defer them until we have some key material we
902 * don't currently possess. If this happens, the URXE will be moved to the
903 * deferred queue. Since a URXE corresponds to one datagram, which may
904 * contain multiple packets, we must ensure any packets we have already
905 * processed in the URXE are not processed again (this is an RFC
906 * requirement). We do this by marking the nth packet in the datagram as
909 * We are now committed to returning this decrypted packet to the user,
910 * meaning we now consider the packet processed and must mark it
913 pkt_mark(&urxe->processed, pkt_idx);
916 * Update header to point to the decrypted buffer, which may be shorter
917 * due to AEAD tags, block padding, etc.
920 rxe->hdr.len = dec_len;
921 rxe->data_len = dec_len;
922 rxe->datagram_len = datagram_len;
924 /* We processed the PN successfully, so update largest processed PN. */
925 pn_space = rxe_determine_pn_space(rxe);
926 if (rxe->pn > qrx->largest_pn[pn_space])
927 qrx->largest_pn[pn_space] = rxe->pn;
929 /* Copy across network addresses and RX time from URXE to RXE. */
930 rxe->peer = urxe->peer;
931 rxe->local = urxe->local;
932 rxe->time = urxe->time;
934 /* Move RXE to pending. */
935 rxe_remove(&qrx->rx_free, rxe);
936 rxe_insert_tail(&qrx->rx_pending, rxe);
937 return 0; /* success, did not defer; not distinguished from failure */
941 * We cannot process this packet right now (but might be able to later). We
942 * MUST attempt to process any other packets in the datagram, so defer it
945 assert(eop != NULL && eop >= PACKET_data(pkt));
947 * We don't care if this fails as it will just result in the packet being at
948 * the end of the datagram buffer.
950 ignore_res(PACKET_forward(pkt, eop - PACKET_data(pkt)));
951 return 1; /* deferred */
956 * This packet cannot be processed and will never be processable. We
957 * were at least able to decode its header and determine its length, so
958 * we can skip over it and try to process any subsequent packets in the
961 * Mark as processed as an optimization.
963 assert(eop >= PACKET_data(pkt));
964 pkt_mark(&urxe->processed, pkt_idx);
965 /* We don't care if this fails (see above) */
966 ignore_res(PACKET_forward(pkt, eop - PACKET_data(pkt)));
969 * This packet cannot be processed and will never be processable.
970 * Because even its header is not intelligible, we cannot examine any
971 * further packets in the datagram because its length cannot be
974 * Advance over the entire remainder of the datagram, and mark it as
975 * processed gap as an optimization.
977 pkt_mark(&urxe->processed, pkt_idx);
978 /* We don't care if this fails (see above) */
979 ignore_res(PACKET_forward(pkt, PACKET_remaining(pkt)));
981 return 0; /* failure, did not defer; not distinguished from success */
984 /* Process a datagram which was received. */
985 static int qrx_process_datagram(OSSL_QRX *qrx, QUIC_URXE *e,
986 const unsigned char *data,
989 int have_deferred = 0;
992 RXE *first_rxe = NULL;
994 qrx->bytes_received += data_len;
996 if (!PACKET_buf_init(&pkt, data, data_len))
999 for (; PACKET_remaining(&pkt) > 0; ++pkt_idx) {
1001 * A packet smallest than the minimum possible QUIC packet size is not
1002 * considered valid. We also ignore more than a certain number of
1003 * packets within the same datagram.
1005 if (PACKET_remaining(&pkt) < QUIC_MIN_VALID_PKT_LEN
1006 || pkt_idx >= QUIC_MAX_PKT_PER_URXE)
1010 * We note whether packet processing resulted in a deferral since
1011 * this means we need to move the URXE to the deferred list rather
1012 * than the free list after we're finished dealing with it for now.
1014 * However, we don't otherwise care here whether processing succeeded or
1015 * failed, as the RFC says even if a packet in a datagram is malformed,
1016 * we should still try to process any packets following it.
1018 * In the case where the packet is so malformed we can't determine its
1019 * length, qrx_process_pkt will take care of advancing to the end of
1020 * the packet, so we will exit the loop automatically in this case.
1022 if (qrx_process_pkt(qrx, e, &pkt, pkt_idx, &first_rxe, data_len))
1026 /* Only report whether there were any deferrals. */
1027 return have_deferred;
1030 /* Process a single pending URXE. */
1031 static int qrx_process_one_urxe(OSSL_QRX *qrx, QUIC_URXE *e)
1035 /* The next URXE we process should be at the head of the pending list. */
1036 if (!ossl_assert(e == qrx->urx_pending.head))
1040 * Attempt to process the datagram. The return value indicates only if
1041 * processing of the datagram was deferred. If we failed to process the
1042 * datagram, we do not attempt to process it again and silently eat the
1045 was_deferred = qrx_process_datagram(qrx, e, ossl_quic_urxe_data(e),
1049 * Remove the URXE from the pending list and return it to
1050 * either the free or deferred list.
1052 ossl_quic_urxe_remove(&qrx->urx_pending, e);
1053 if (was_deferred > 0 &&
1054 (e->deferred || qrx->num_deferred < qrx->max_deferred)) {
1055 ossl_quic_urxe_insert_tail(&qrx->urx_deferred, e);
1058 ++qrx->num_deferred;
1063 --qrx->num_deferred;
1065 ossl_quic_demux_release_urxe(qrx->demux, e);
1071 /* Process any pending URXEs to generate pending RXEs. */
1072 static int qrx_process_pending_urxl(OSSL_QRX *qrx)
1076 while ((e = qrx->urx_pending.head) != NULL)
1077 if (!qrx_process_one_urxe(qrx, e))
1083 int ossl_qrx_read_pkt(OSSL_QRX *qrx, OSSL_QRX_PKT *pkt)
1087 if (!ossl_qrx_processed_read_pending(qrx)) {
1088 if (!qrx_process_pending_urxl(qrx))
1091 if (!ossl_qrx_processed_read_pending(qrx))
1095 rxe = qrx_pop_pending_rxe(qrx);
1096 if (!ossl_assert(rxe != NULL))
1100 pkt->hdr = &rxe->hdr;
1102 pkt->time = rxe->time;
1104 = BIO_ADDR_family(&rxe->peer) != AF_UNSPEC ? &rxe->peer : NULL;
1106 = BIO_ADDR_family(&rxe->local) != AF_UNSPEC ? &rxe->local : NULL;
1110 void ossl_qrx_release_pkt(OSSL_QRX *qrx, void *handle)
1112 if (handle != NULL) {
1115 qrx_recycle_rxe(qrx, rxe);
1119 uint64_t ossl_qrx_get_bytes_received(OSSL_QRX *qrx, int clear)
1121 uint64_t v = qrx->bytes_received;
1124 qrx->bytes_received = 0;
1129 int ossl_qrx_set_early_validation_cb(OSSL_QRX *qrx,
1130 ossl_qrx_early_validation_cb *cb,
1133 qrx->validation_cb = cb;
1134 qrx->validation_cb_arg = cb_arg;
1138 int ossl_qrx_set_key_update_cb(OSSL_QRX *qrx,
1139 ossl_qrx_key_update_cb *cb,
1142 qrx->key_update_cb = cb;
1143 qrx->key_update_cb_arg = cb_arg;
1147 uint64_t ossl_qrx_get_key_epoch(OSSL_QRX *qrx)
1149 OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(&qrx->el_set,
1150 QUIC_ENC_LEVEL_1RTT, 1);
1152 return el == NULL ? UINT64_MAX : el->key_epoch;
1155 int ossl_qrx_key_update_timeout(OSSL_QRX *qrx, int normal)
1157 OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(&qrx->el_set,
1158 QUIC_ENC_LEVEL_1RTT, 1);
1163 if (el->state == QRL_EL_STATE_PROV_UPDATING
1164 && !ossl_qrl_enc_level_set_key_update_done(&qrx->el_set,
1165 QUIC_ENC_LEVEL_1RTT))
1168 if (normal && el->state == QRL_EL_STATE_PROV_COOLDOWN
1169 && !ossl_qrl_enc_level_set_key_cooldown_done(&qrx->el_set,
1170 QUIC_ENC_LEVEL_1RTT))
1176 uint64_t ossl_qrx_get_cur_forged_pkt_count(OSSL_QRX *qrx)
1178 return qrx->forged_pkt_count;
1181 uint64_t ossl_qrx_get_max_forged_pkt_count(OSSL_QRX *qrx,
1184 OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(&qrx->el_set,
1187 return el == NULL ? UINT64_MAX
1188 : ossl_qrl_get_suite_max_forged_pkt(el->suite_id);