2 * Copyright 2022-2024 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 <openssl/ssl.h>
11 #include "internal/quic_record_rx.h"
12 #include "quic_record_shared.h"
13 #include "internal/common.h"
14 #include "internal/list.h"
15 #include "../ssl_local.h"
18 * Mark a packet in a bitfield.
20 * pkt_idx: index of packet within datagram.
22 static ossl_inline
void pkt_mark(uint64_t *bitf
, size_t pkt_idx
)
24 assert(pkt_idx
< QUIC_MAX_PKT_PER_URXE
);
25 *bitf
|= ((uint64_t)1) << pkt_idx
;
28 /* Returns 1 if a packet is in the bitfield. */
29 static ossl_inline
int pkt_is_marked(const uint64_t *bitf
, size_t pkt_idx
)
31 assert(pkt_idx
< QUIC_MAX_PKT_PER_URXE
);
32 return (*bitf
& (((uint64_t)1) << pkt_idx
)) != 0;
39 * RX Entries (RXEs) store processed (i.e., decrypted) data received from the
40 * network. One RXE is used per received QUIC packet.
42 typedef struct rxe_st RXE
;
46 OSSL_LIST_MEMBER(rxe
, RXE
);
47 size_t data_len
, alloc_len
, refcount
;
49 /* Extra fields for per-packet information. */
50 QUIC_PKT_HDR hdr
; /* data/len are decrypted payload */
52 /* Decoded packet number. */
55 /* Addresses copied from URXE. */
58 /* Time we received the packet (not when we processed it). */
61 /* Total length of the datagram which contained this packet. */
65 * The key epoch the packet was received with. Always 0 for non-1-RTT
71 * Monotonically increases with each datagram received.
72 * For diagnostic use only.
77 * alloc_len allocated bytes (of which data_len bytes are valid) follow this
82 DEFINE_LIST_OF(rxe
, RXE
);
83 typedef OSSL_LIST(rxe
) RXE_LIST
;
85 static ossl_inline
unsigned char *rxe_data(const RXE
*e
)
87 return (unsigned char *)(e
+ 1);
98 /* Demux to receive datagrams from. */
101 /* Length of connection IDs used in short-header packets in bytes. */
102 size_t short_conn_id_len
;
104 /* Maximum number of deferred datagrams buffered at any one time. */
107 /* Current count of deferred datagrams. */
111 * List of URXEs which are filled with received encrypted data.
112 * These are returned to the DEMUX's free list as they are processed.
114 QUIC_URXE_LIST urx_pending
;
117 * List of URXEs which we could not decrypt immediately and which are being
118 * kept in case they can be decrypted later.
120 QUIC_URXE_LIST urx_deferred
;
123 * List of RXEs which are not currently in use. These are moved
124 * to the pending list as they are filled.
129 * List of RXEs which are filled with decrypted packets ready to be passed
130 * to the user. A RXE is removed from all lists inside the QRL when passed
131 * to the user, then returned to the free list when the user returns it.
135 /* Largest PN we have received and processed in a given PN space. */
136 QUIC_PN largest_pn
[QUIC_PN_SPACE_NUM
];
138 /* Per encryption-level state. */
139 OSSL_QRL_ENC_LEVEL_SET el_set
;
141 /* Bytes we have received since this counter was last cleared. */
142 uint64_t bytes_received
;
145 * Number of forged packets we have received since the QRX was instantiated.
146 * Note that as per RFC 9001, this is connection-level state; it is not per
147 * EL and is not reset by a key update.
149 uint64_t forged_pkt_count
;
152 * The PN the current key epoch started at, inclusive.
154 uint64_t cur_epoch_start_pn
;
156 /* Validation callback. */
157 ossl_qrx_late_validation_cb
*validation_cb
;
158 void *validation_cb_arg
;
160 /* Key update callback. */
161 ossl_qrx_key_update_cb
*key_update_cb
;
162 void *key_update_cb_arg
;
164 /* Initial key phase. For debugging use only; always 0 in real use. */
165 unsigned char init_key_phase_bit
;
167 /* Are we allowed to process 1-RTT packets yet? */
168 unsigned char allow_1rtt
;
170 /* Message callback related arguments */
171 ossl_msg_cb msg_callback
;
172 void *msg_callback_arg
;
173 SSL
*msg_callback_ssl
;
176 OSSL_QRX
*ossl_qrx_new(const OSSL_QRX_ARGS
*args
)
181 if (args
->demux
== NULL
|| args
->max_deferred
== 0)
184 qrx
= OPENSSL_zalloc(sizeof(OSSL_QRX
));
188 for (i
= 0; i
< OSSL_NELEM(qrx
->largest_pn
); ++i
)
189 qrx
->largest_pn
[i
] = args
->init_largest_pn
[i
];
191 qrx
->libctx
= args
->libctx
;
192 qrx
->propq
= args
->propq
;
193 qrx
->demux
= args
->demux
;
194 qrx
->short_conn_id_len
= args
->short_conn_id_len
;
195 qrx
->init_key_phase_bit
= args
->init_key_phase_bit
;
196 qrx
->max_deferred
= args
->max_deferred
;
200 static void qrx_cleanup_rxl(RXE_LIST
*l
)
204 for (e
= ossl_list_rxe_head(l
); e
!= NULL
; e
= enext
) {
205 enext
= ossl_list_rxe_next(e
);
206 ossl_list_rxe_remove(l
, e
);
211 static void qrx_cleanup_urxl(OSSL_QRX
*qrx
, QUIC_URXE_LIST
*l
)
213 QUIC_URXE
*e
, *enext
;
215 for (e
= ossl_list_urxe_head(l
); e
!= NULL
; e
= enext
) {
216 enext
= ossl_list_urxe_next(e
);
217 ossl_list_urxe_remove(l
, e
);
218 ossl_quic_demux_release_urxe(qrx
->demux
, e
);
222 void ossl_qrx_free(OSSL_QRX
*qrx
)
229 /* Free RXE queue data. */
230 qrx_cleanup_rxl(&qrx
->rx_free
);
231 qrx_cleanup_rxl(&qrx
->rx_pending
);
232 qrx_cleanup_urxl(qrx
, &qrx
->urx_pending
);
233 qrx_cleanup_urxl(qrx
, &qrx
->urx_deferred
);
235 /* Drop keying material and crypto resources. */
236 for (i
= 0; i
< QUIC_ENC_LEVEL_NUM
; ++i
)
237 ossl_qrl_enc_level_set_discard(&qrx
->el_set
, i
);
242 void ossl_qrx_inject_urxe(OSSL_QRX
*qrx
, QUIC_URXE
*urxe
)
244 /* Initialize our own fields inside the URXE and add to the pending list. */
246 urxe
->hpr_removed
= 0;
248 ossl_list_urxe_insert_tail(&qrx
->urx_pending
, urxe
);
250 if (qrx
->msg_callback
!= NULL
)
251 qrx
->msg_callback(0, OSSL_QUIC1_VERSION
, SSL3_RT_QUIC_DATAGRAM
, urxe
+ 1,
252 urxe
->data_len
, qrx
->msg_callback_ssl
,
253 qrx
->msg_callback_arg
);
256 static void qrx_requeue_deferred(OSSL_QRX
*qrx
)
260 while ((e
= ossl_list_urxe_head(&qrx
->urx_deferred
)) != NULL
) {
261 ossl_list_urxe_remove(&qrx
->urx_deferred
, e
);
262 ossl_list_urxe_insert_tail(&qrx
->urx_pending
, e
);
266 int ossl_qrx_provide_secret(OSSL_QRX
*qrx
, uint32_t enc_level
,
267 uint32_t suite_id
, EVP_MD
*md
,
268 const unsigned char *secret
, size_t secret_len
)
270 if (enc_level
>= QUIC_ENC_LEVEL_NUM
)
273 if (!ossl_qrl_enc_level_set_provide_secret(&qrx
->el_set
,
281 qrx
->init_key_phase_bit
,
286 * Any packets we previously could not decrypt, we may now be able to
287 * decrypt, so move any datagrams containing deferred packets from the
288 * deferred to the pending queue.
290 qrx_requeue_deferred(qrx
);
294 int ossl_qrx_discard_enc_level(OSSL_QRX
*qrx
, uint32_t enc_level
)
296 if (enc_level
>= QUIC_ENC_LEVEL_NUM
)
299 ossl_qrl_enc_level_set_discard(&qrx
->el_set
, enc_level
);
303 /* Returns 1 if there are one or more pending RXEs. */
304 int ossl_qrx_processed_read_pending(OSSL_QRX
*qrx
)
306 return !ossl_list_rxe_is_empty(&qrx
->rx_pending
);
309 /* Returns 1 if there are yet-unprocessed packets. */
310 int ossl_qrx_unprocessed_read_pending(OSSL_QRX
*qrx
)
312 return !ossl_list_urxe_is_empty(&qrx
->urx_pending
)
313 || !ossl_list_urxe_is_empty(&qrx
->urx_deferred
);
316 /* Pop the next pending RXE. Returns NULL if no RXE is pending. */
317 static RXE
*qrx_pop_pending_rxe(OSSL_QRX
*qrx
)
319 RXE
*rxe
= ossl_list_rxe_head(&qrx
->rx_pending
);
324 ossl_list_rxe_remove(&qrx
->rx_pending
, rxe
);
328 /* Allocate a new RXE. */
329 static RXE
*qrx_alloc_rxe(size_t alloc_len
)
333 if (alloc_len
>= SIZE_MAX
- sizeof(RXE
))
336 rxe
= OPENSSL_malloc(sizeof(RXE
) + alloc_len
);
340 ossl_list_rxe_init_elem(rxe
);
341 rxe
->alloc_len
= alloc_len
;
348 * Ensures there is at least one RXE in the RX free list, allocating a new entry
349 * if necessary. The returned RXE is in the RX free list; it is not popped.
351 * alloc_len is a hint which may be used to determine the RXE size if allocation
352 * is necessary. Returns NULL on allocation failure.
354 static RXE
*qrx_ensure_free_rxe(OSSL_QRX
*qrx
, size_t alloc_len
)
358 if (ossl_list_rxe_head(&qrx
->rx_free
) != NULL
)
359 return ossl_list_rxe_head(&qrx
->rx_free
);
361 rxe
= qrx_alloc_rxe(alloc_len
);
365 ossl_list_rxe_insert_tail(&qrx
->rx_free
, rxe
);
370 * Resize the data buffer attached to an RXE to be n bytes in size. The address
371 * of the RXE might change; the new address is returned, or NULL on failure, in
372 * which case the original RXE remains valid.
374 static RXE
*qrx_resize_rxe(RXE_LIST
*rxl
, RXE
*rxe
, size_t n
)
378 /* Should never happen. */
382 if (n
>= SIZE_MAX
- sizeof(RXE
))
385 /* Remove the item from the list to avoid accessing freed memory */
386 p
= ossl_list_rxe_prev(rxe
);
387 ossl_list_rxe_remove(rxl
, rxe
);
389 /* Should never resize an RXE which has been handed out. */
390 if (!ossl_assert(rxe
->refcount
== 0))
394 * NOTE: We do not clear old memory, although it does contain decrypted
397 rxe2
= OPENSSL_realloc(rxe
, sizeof(RXE
) + n
);
399 /* Resize failed, restore old allocation. */
401 ossl_list_rxe_insert_head(rxl
, rxe
);
403 ossl_list_rxe_insert_after(rxl
, p
, rxe
);
408 ossl_list_rxe_insert_head(rxl
, rxe2
);
410 ossl_list_rxe_insert_after(rxl
, p
, rxe2
);
417 * Ensure the data buffer attached to an RXE is at least n bytes in size.
418 * Returns NULL on failure.
420 static RXE
*qrx_reserve_rxe(RXE_LIST
*rxl
,
423 if (rxe
->alloc_len
>= n
)
426 return qrx_resize_rxe(rxl
, rxe
, n
);
429 /* Return a RXE handed out to the user back to our freelist. */
430 static void qrx_recycle_rxe(OSSL_QRX
*qrx
, RXE
*rxe
)
432 /* RXE should not be in any list */
433 assert(ossl_list_rxe_prev(rxe
) == NULL
&& ossl_list_rxe_next(rxe
) == NULL
);
435 rxe
->pkt
.peer
= NULL
;
436 rxe
->pkt
.local
= NULL
;
437 ossl_list_rxe_insert_tail(&qrx
->rx_free
, rxe
);
441 * Given a pointer to a pointer pointing to a buffer and the size of that
442 * buffer, copy the buffer into *prxe, expanding the RXE if necessary (its
443 * pointer may change due to realloc). *pi is the offset in bytes to copy the
444 * buffer to, and on success is updated to be the offset pointing after the
445 * copied buffer. *pptr is updated to point to the new location of the buffer.
447 static int qrx_relocate_buffer(OSSL_QRX
*qrx
, RXE
**prxe
, size_t *pi
,
448 const unsigned char **pptr
, size_t buf_len
)
456 if ((rxe
= qrx_reserve_rxe(&qrx
->rx_free
, *prxe
, *pi
+ buf_len
)) == NULL
)
460 dst
= (unsigned char *)rxe_data(rxe
) + *pi
;
462 memcpy(dst
, *pptr
, buf_len
);
468 static uint32_t qrx_determine_enc_level(const QUIC_PKT_HDR
*hdr
)
471 case QUIC_PKT_TYPE_INITIAL
:
472 return QUIC_ENC_LEVEL_INITIAL
;
473 case QUIC_PKT_TYPE_HANDSHAKE
:
474 return QUIC_ENC_LEVEL_HANDSHAKE
;
475 case QUIC_PKT_TYPE_0RTT
:
476 return QUIC_ENC_LEVEL_0RTT
;
477 case QUIC_PKT_TYPE_1RTT
:
478 return QUIC_ENC_LEVEL_1RTT
;
482 case QUIC_PKT_TYPE_RETRY
:
483 case QUIC_PKT_TYPE_VERSION_NEG
:
484 return QUIC_ENC_LEVEL_INITIAL
; /* not used */
488 static uint32_t rxe_determine_pn_space(RXE
*rxe
)
492 enc_level
= qrx_determine_enc_level(&rxe
->hdr
);
493 return ossl_quic_enc_level_to_pn_space(enc_level
);
496 static int qrx_validate_hdr_early(OSSL_QRX
*qrx
, RXE
*rxe
,
497 const QUIC_CONN_ID
*first_dcid
)
499 /* Ensure version is what we want. */
500 if (rxe
->hdr
.version
!= QUIC_VERSION_1
501 && rxe
->hdr
.version
!= QUIC_VERSION_NONE
)
504 /* Clients should never receive 0-RTT packets. */
505 if (rxe
->hdr
.type
== QUIC_PKT_TYPE_0RTT
)
508 /* Version negotiation and retry packets must be the first packet. */
509 if (first_dcid
!= NULL
&& !ossl_quic_pkt_type_can_share_dgram(rxe
->hdr
.type
))
513 * If this is not the first packet in a datagram, the destination connection
514 * ID must match the one in that packet.
516 if (first_dcid
!= NULL
) {
517 if (!ossl_assert(first_dcid
->id_len
< QUIC_MAX_CONN_ID_LEN
)
518 || !ossl_quic_conn_id_eq(first_dcid
,
519 &rxe
->hdr
.dst_conn_id
))
526 /* Validate header and decode PN. */
527 static int qrx_validate_hdr(OSSL_QRX
*qrx
, RXE
*rxe
)
529 int pn_space
= rxe_determine_pn_space(rxe
);
531 if (!ossl_quic_wire_decode_pkt_hdr_pn(rxe
->hdr
.pn
, rxe
->hdr
.pn_len
,
532 qrx
->largest_pn
[pn_space
],
539 /* Late packet header validation. */
540 static int qrx_validate_hdr_late(OSSL_QRX
*qrx
, RXE
*rxe
)
542 int pn_space
= rxe_determine_pn_space(rxe
);
545 * Allow our user to decide whether to discard the packet before we try and
548 if (qrx
->validation_cb
!= NULL
549 && !qrx
->validation_cb(rxe
->pn
, pn_space
, qrx
->validation_cb_arg
))
556 * Retrieves the correct cipher context for an EL and key phase. Writes the key
557 * epoch number actually used for packet decryption to *rx_key_epoch.
559 static size_t qrx_get_cipher_ctx_idx(OSSL_QRX
*qrx
, OSSL_QRL_ENC_LEVEL
*el
,
561 unsigned char key_phase_bit
,
562 uint64_t *rx_key_epoch
,
569 if (enc_level
!= QUIC_ENC_LEVEL_1RTT
) {
574 if (!ossl_assert(key_phase_bit
<= 1))
578 * RFC 9001 requires that we not create timing channels which could reveal
579 * the decrypted value of the Key Phase bit. We usually handle this by
580 * keeping the cipher contexts for both the current and next key epochs
581 * around, so that we just select a cipher context blindly using the key
582 * phase bit, which is time-invariant.
584 * In the COOLDOWN state, we only have one keyslot/cipher context. RFC 9001
585 * suggests an implementation strategy to avoid creating a timing channel in
588 * Endpoints can use randomized packet protection keys in place of
589 * discarded keys when key updates are not yet permitted.
591 * Rather than use a randomised key, we simply use our existing key as it
592 * will fail AEAD verification anyway. This avoids the need to keep around a
593 * dedicated garbage key.
595 * Note: Accessing different cipher contexts is technically not
596 * timing-channel safe due to microarchitectural side channels, but this is
597 * the best we can reasonably do and appears to be directly suggested by the
600 idx
= (el
->state
== QRL_EL_STATE_PROV_COOLDOWN
? el
->key_epoch
& 1
604 * We also need to determine the key epoch number which this index
605 * corresponds to. This is so we can report the key epoch number in the
606 * OSSL_QRX_PKT structure, which callers need to validate whether it was OK
607 * for a packet to be sent using a given key epoch's keys.
610 case QRL_EL_STATE_PROV_NORMAL
:
612 * If we are in the NORMAL state, usually the KP bit will match the LSB
613 * of our key epoch, meaning no new key update is being signalled. If it
614 * does not match, this means the packet (purports to) belong to
615 * the next key epoch.
617 * IMPORTANT: The AEAD tag has not been verified yet when this function
618 * is called, so this code must be timing-channel safe, hence use of
619 * XOR. Moreover, the value output below is not yet authenticated.
622 = el
->key_epoch
+ ((el
->key_epoch
& 1) ^ (uint64_t)key_phase_bit
);
625 case QRL_EL_STATE_PROV_UPDATING
:
627 * If we are in the UPDATING state, usually the KP bit will match the
628 * LSB of our key epoch. If it does not match, this means that the
629 * packet (purports to) belong to the previous key epoch.
631 * As above, must be timing-channel safe.
633 *is_old_key
= (el
->key_epoch
& 1) ^ (uint64_t)key_phase_bit
;
634 *rx_key_epoch
= el
->key_epoch
- (uint64_t)*is_old_key
;
637 case QRL_EL_STATE_PROV_COOLDOWN
:
639 * If we are in COOLDOWN, there is only one key epoch we can possibly
640 * decrypt with, so just try that. If AEAD decryption fails, the
641 * value we output here isn't used anyway.
643 *rx_key_epoch
= el
->key_epoch
;
651 * Tries to decrypt a packet payload.
653 * Returns 1 on success or 0 on failure (which is permanent). The payload is
654 * decrypted from src and written to dst. The buffer dst must be of at least
655 * src_len bytes in length. The actual length of the output in bytes is written
656 * to *dec_len on success, which will always be equal to or less than (usually
657 * less than) src_len.
659 static int qrx_decrypt_pkt_body(OSSL_QRX
*qrx
, unsigned char *dst
,
660 const unsigned char *src
,
661 size_t src_len
, size_t *dec_len
,
662 const unsigned char *aad
, size_t aad_len
,
663 QUIC_PN pn
, uint32_t enc_level
,
664 unsigned char key_phase_bit
,
665 uint64_t *rx_key_epoch
)
667 int l
= 0, l2
= 0, is_old_key
, nonce_len
;
668 unsigned char nonce
[EVP_MAX_IV_LENGTH
];
670 OSSL_QRL_ENC_LEVEL
*el
= ossl_qrl_enc_level_set_get(&qrx
->el_set
,
672 EVP_CIPHER_CTX
*cctx
;
674 if (src_len
> INT_MAX
|| aad_len
> INT_MAX
)
677 /* We should not have been called if we do not have key material. */
678 if (!ossl_assert(el
!= NULL
))
681 if (el
->tag_len
>= src_len
)
685 * If we have failed to authenticate a certain number of ciphertexts, refuse
686 * to decrypt any more ciphertexts.
688 if (qrx
->forged_pkt_count
>= ossl_qrl_get_suite_max_forged_pkt(el
->suite_id
))
691 cctx_idx
= qrx_get_cipher_ctx_idx(qrx
, el
, enc_level
, key_phase_bit
,
692 rx_key_epoch
, &is_old_key
);
693 if (!ossl_assert(cctx_idx
< OSSL_NELEM(el
->cctx
)))
696 if (is_old_key
&& pn
>= qrx
->cur_epoch_start_pn
)
698 * RFC 9001 s. 5.5: Once an endpoint successfully receives a packet with
699 * a given PN, it MUST discard all packets in the same PN space with
700 * higher PNs if they cannot be successfully unprotected with the same
701 * key, or -- if there is a key update -- a subsequent packet protection
704 * In other words, once a PN x triggers a KU, it is invalid for us to
705 * receive a packet with a newer PN y (y > x) using the old keys.
709 cctx
= el
->cctx
[cctx_idx
];
711 /* Construct nonce (nonce=IV ^ PN). */
712 nonce_len
= EVP_CIPHER_CTX_get_iv_length(cctx
);
713 if (!ossl_assert(nonce_len
>= (int)sizeof(QUIC_PN
)))
716 memcpy(nonce
, el
->iv
[cctx_idx
], nonce_len
);
717 for (i
= 0; i
< sizeof(QUIC_PN
); ++i
)
718 nonce
[nonce_len
- i
- 1] ^= (unsigned char)(pn
>> (i
* 8));
720 /* type and key will already have been setup; feed the IV. */
721 if (EVP_CipherInit_ex(cctx
, NULL
,
722 NULL
, NULL
, nonce
, /*enc=*/0) != 1)
725 /* Feed the AEAD tag we got so the cipher can validate it. */
726 if (EVP_CIPHER_CTX_ctrl(cctx
, EVP_CTRL_AEAD_SET_TAG
,
728 (unsigned char *)src
+ src_len
- el
->tag_len
) != 1)
732 if (EVP_CipherUpdate(cctx
, NULL
, &l
, aad
, aad_len
) != 1)
735 /* Feed encrypted packet body. */
736 if (EVP_CipherUpdate(cctx
, dst
, &l
, src
, src_len
- el
->tag_len
) != 1)
739 #ifdef FUZZING_BUILD_MODE_UNSAFE_FOR_PRODUCTION
741 * Throw away what we just decrypted and just use the ciphertext instead
742 * (which should be unencrypted)
746 /* Pretend to authenticate the tag but ignore it */
747 if (EVP_CipherFinal_ex(cctx
, NULL
, &l2
) != 1) {
751 /* Ensure authentication succeeded. */
752 if (EVP_CipherFinal_ex(cctx
, NULL
, &l2
) != 1) {
753 /* Authentication failed, increment failed auth counter. */
754 ++qrx
->forged_pkt_count
;
763 static ossl_inline
void ignore_res(int x
)
768 static void qrx_key_update_initiated(OSSL_QRX
*qrx
, QUIC_PN pn
)
770 if (!ossl_qrl_enc_level_set_key_update(&qrx
->el_set
, QUIC_ENC_LEVEL_1RTT
))
771 /* We are already in RXKU, so we don't call the callback again. */
774 qrx
->cur_epoch_start_pn
= pn
;
776 if (qrx
->key_update_cb
!= NULL
)
777 qrx
->key_update_cb(pn
, qrx
->key_update_cb_arg
);
780 /* Process a single packet in a datagram. */
781 static int qrx_process_pkt(OSSL_QRX
*qrx
, QUIC_URXE
*urxe
,
782 PACKET
*pkt
, size_t pkt_idx
,
783 QUIC_CONN_ID
*first_dcid
,
787 const unsigned char *eop
= NULL
;
788 size_t i
, aad_len
= 0, dec_len
= 0;
789 PACKET orig_pkt
= *pkt
;
790 const unsigned char *sop
= PACKET_data(pkt
);
792 char need_second_decode
= 0, already_processed
= 0;
793 QUIC_PKT_HDR_PTRS ptrs
;
794 uint32_t pn_space
, enc_level
;
795 OSSL_QRL_ENC_LEVEL
*el
= NULL
;
796 uint64_t rx_key_epoch
= UINT64_MAX
;
799 * Get a free RXE. If we need to allocate a new one, use the packet length
800 * as a good ballpark figure.
802 rxe
= qrx_ensure_free_rxe(qrx
, PACKET_remaining(pkt
));
806 /* Have we already processed this packet? */
807 if (pkt_is_marked(&urxe
->processed
, pkt_idx
))
808 already_processed
= 1;
811 * Decode the header into the RXE structure. We first decrypt and read the
812 * unprotected part of the packet header (unless we already removed header
813 * protection, in which case we decode all of it).
815 need_second_decode
= !pkt_is_marked(&urxe
->hpr_removed
, pkt_idx
);
816 if (!ossl_quic_wire_decode_pkt_hdr(pkt
,
817 qrx
->short_conn_id_len
,
818 need_second_decode
, 0, &rxe
->hdr
, &ptrs
))
822 * Our successful decode above included an intelligible length and the
823 * PACKET is now pointing to the end of the QUIC packet.
825 eop
= PACKET_data(pkt
);
828 * Make a note of the first packet's DCID so we can later ensure the
829 * destination connection IDs of all packets in a datagram match.
832 *first_dcid
= rxe
->hdr
.dst_conn_id
;
835 * Early header validation. Since we now know the packet length, we can also
836 * now skip over it if we already processed it.
838 if (already_processed
839 || !qrx_validate_hdr_early(qrx
, rxe
, pkt_idx
== 0 ? NULL
: first_dcid
))
841 * Already processed packets are handled identically to malformed
842 * packets; i.e., they are ignored.
846 if (!ossl_quic_pkt_type_is_encrypted(rxe
->hdr
.type
)) {
848 * Version negotiation and retry packets are a special case. They do not
849 * contain a payload which needs decrypting and have no header
853 /* Just copy the payload from the URXE to the RXE. */
854 if ((rxe
= qrx_reserve_rxe(&qrx
->rx_free
, rxe
, rxe
->hdr
.len
)) == NULL
)
856 * Allocation failure. EOP will be pointing to the end of the
857 * datagram so processing of this datagram will end here.
861 /* We are now committed to returning the packet. */
862 memcpy(rxe_data(rxe
), rxe
->hdr
.data
, rxe
->hdr
.len
);
863 pkt_mark(&urxe
->processed
, pkt_idx
);
865 rxe
->hdr
.data
= rxe_data(rxe
);
866 rxe
->pn
= QUIC_PN_INVALID
;
868 rxe
->data_len
= rxe
->hdr
.len
;
869 rxe
->datagram_len
= datagram_len
;
871 rxe
->peer
= urxe
->peer
;
872 rxe
->local
= urxe
->local
;
873 rxe
->time
= urxe
->time
;
874 rxe
->datagram_id
= urxe
->datagram_id
;
876 /* Move RXE to pending. */
877 ossl_list_rxe_remove(&qrx
->rx_free
, rxe
);
878 ossl_list_rxe_insert_tail(&qrx
->rx_pending
, rxe
);
879 return 0; /* success, did not defer */
882 /* Determine encryption level of packet. */
883 enc_level
= qrx_determine_enc_level(&rxe
->hdr
);
885 /* If we do not have keying material for this encryption level yet, defer. */
886 switch (ossl_qrl_enc_level_set_have_el(&qrx
->el_set
, enc_level
)) {
889 if (enc_level
== QUIC_ENC_LEVEL_1RTT
&& !qrx
->allow_1rtt
)
891 * But we cannot process 1-RTT packets until the handshake is
892 * completed (RFC 9000 s. 5.7).
901 /* We already discarded keys for this EL, we will never process this.*/
906 * We will copy any token included in the packet to the start of our RXE
907 * data buffer (so that we don't reference the URXE buffer any more and can
908 * recycle it). Track our position in the RXE buffer by index instead of
909 * pointer as the pointer may change as reallocs occur.
914 * rxe->hdr.data is now pointing at the (encrypted) packet payload. rxe->hdr
915 * also has fields pointing into the PACKET buffer which will be going away
916 * soon (the URXE will be reused for another incoming packet).
918 * Firstly, relocate some of these fields into the RXE as needed.
920 * Relocate token buffer and fix pointer.
922 if (rxe
->hdr
.type
== QUIC_PKT_TYPE_INITIAL
) {
923 const unsigned char *token
= rxe
->hdr
.token
;
926 * This may change the value of rxe and change the value of the token
927 * pointer as well. So we must make a temporary copy of the pointer to
928 * the token, and then copy it back into the new location of the rxe
930 if (!qrx_relocate_buffer(qrx
, &rxe
, &i
, &token
, rxe
->hdr
.token_len
))
933 rxe
->hdr
.token
= token
;
936 /* Now remove header protection. */
939 el
= ossl_qrl_enc_level_set_get(&qrx
->el_set
, enc_level
, 1);
940 assert(el
!= NULL
); /* Already checked above */
942 if (need_second_decode
) {
943 if (!ossl_quic_hdr_protector_decrypt(&el
->hpr
, &ptrs
))
947 * We have removed header protection, so don't attempt to do it again if
948 * the packet gets deferred and processed again.
950 pkt_mark(&urxe
->hpr_removed
, pkt_idx
);
952 /* Decode the now unprotected header. */
953 if (ossl_quic_wire_decode_pkt_hdr(pkt
, qrx
->short_conn_id_len
,
954 0, 0, &rxe
->hdr
, NULL
) != 1)
958 /* Validate header and decode PN. */
959 if (!qrx_validate_hdr(qrx
, rxe
))
962 if (qrx
->msg_callback
!= NULL
)
963 qrx
->msg_callback(0, OSSL_QUIC1_VERSION
, SSL3_RT_QUIC_PACKET
, sop
,
964 eop
- sop
- rxe
->hdr
.len
, qrx
->msg_callback_ssl
,
965 qrx
->msg_callback_arg
);
968 * The AAD data is the entire (unprotected) packet header including the PN.
969 * The packet header has been unprotected in place, so we can just reuse the
970 * PACKET buffer. The header ends where the payload begins.
972 aad_len
= rxe
->hdr
.data
- sop
;
974 /* Ensure the RXE buffer size is adequate for our payload. */
975 if ((rxe
= qrx_reserve_rxe(&qrx
->rx_free
, rxe
, rxe
->hdr
.len
+ i
)) == NULL
) {
977 * Allocation failure, treat as malformed and do not bother processing
978 * any further packets in the datagram as they are likely to also
979 * encounter allocation failures.
986 * We decrypt the packet body to immediately after the token at the start of
987 * the RXE buffer (where present).
989 * Do the decryption from the PACKET (which points into URXE memory) to our
990 * RXE payload (single-copy decryption), then fixup the pointers in the
991 * header to point to our new buffer.
993 * If decryption fails this is considered a permanent error; we defer
994 * packets we don't yet have decryption keys for above, so if this fails,
995 * something has gone wrong with the handshake process or a packet has been
998 dst
= (unsigned char *)rxe_data(rxe
) + i
;
999 if (!qrx_decrypt_pkt_body(qrx
, dst
, rxe
->hdr
.data
, rxe
->hdr
.len
,
1000 &dec_len
, sop
, aad_len
, rxe
->pn
, enc_level
,
1001 rxe
->hdr
.key_phase
, &rx_key_epoch
))
1005 * -----------------------------------------------------
1006 * IMPORTANT: ANYTHING ABOVE THIS LINE IS UNVERIFIED
1007 * AND MUST BE TIMING-CHANNEL SAFE.
1008 * -----------------------------------------------------
1010 * At this point, we have successfully authenticated the AEAD tag and no
1011 * longer need to worry about exposing the PN, PN length or Key Phase bit in
1012 * timing channels. Invoke any configured validation callback to allow for
1013 * rejection of duplicate PNs.
1015 if (!qrx_validate_hdr_late(qrx
, rxe
))
1018 /* Check for a Key Phase bit differing from our expectation. */
1019 if (rxe
->hdr
.type
== QUIC_PKT_TYPE_1RTT
1020 && rxe
->hdr
.key_phase
!= (el
->key_epoch
& 1))
1021 qrx_key_update_initiated(qrx
, rxe
->pn
);
1024 * We have now successfully decrypted the packet payload. If there are
1025 * additional packets in the datagram, it is possible we will fail to
1026 * decrypt them and need to defer them until we have some key material we
1027 * don't currently possess. If this happens, the URXE will be moved to the
1028 * deferred queue. Since a URXE corresponds to one datagram, which may
1029 * contain multiple packets, we must ensure any packets we have already
1030 * processed in the URXE are not processed again (this is an RFC
1031 * requirement). We do this by marking the nth packet in the datagram as
1034 * We are now committed to returning this decrypted packet to the user,
1035 * meaning we now consider the packet processed and must mark it
1038 pkt_mark(&urxe
->processed
, pkt_idx
);
1041 * Update header to point to the decrypted buffer, which may be shorter
1042 * due to AEAD tags, block padding, etc.
1044 rxe
->hdr
.data
= dst
;
1045 rxe
->hdr
.len
= dec_len
;
1046 rxe
->data_len
= dec_len
;
1047 rxe
->datagram_len
= datagram_len
;
1048 rxe
->key_epoch
= rx_key_epoch
;
1050 /* We processed the PN successfully, so update largest processed PN. */
1051 pn_space
= rxe_determine_pn_space(rxe
);
1052 if (rxe
->pn
> qrx
->largest_pn
[pn_space
])
1053 qrx
->largest_pn
[pn_space
] = rxe
->pn
;
1055 /* Copy across network addresses and RX time from URXE to RXE. */
1056 rxe
->peer
= urxe
->peer
;
1057 rxe
->local
= urxe
->local
;
1058 rxe
->time
= urxe
->time
;
1059 rxe
->datagram_id
= urxe
->datagram_id
;
1061 /* Move RXE to pending. */
1062 ossl_list_rxe_remove(&qrx
->rx_free
, rxe
);
1063 ossl_list_rxe_insert_tail(&qrx
->rx_pending
, rxe
);
1064 return 0; /* success, did not defer; not distinguished from failure */
1068 * We cannot process this packet right now (but might be able to later). We
1069 * MUST attempt to process any other packets in the datagram, so defer it
1072 assert(eop
!= NULL
&& eop
>= PACKET_data(pkt
));
1074 * We don't care if this fails as it will just result in the packet being at
1075 * the end of the datagram buffer.
1077 ignore_res(PACKET_forward(pkt
, eop
- PACKET_data(pkt
)));
1078 return 1; /* deferred */
1083 * This packet cannot be processed and will never be processable. We
1084 * were at least able to decode its header and determine its length, so
1085 * we can skip over it and try to process any subsequent packets in the
1088 * Mark as processed as an optimization.
1090 assert(eop
>= PACKET_data(pkt
));
1091 pkt_mark(&urxe
->processed
, pkt_idx
);
1092 /* We don't care if this fails (see above) */
1093 ignore_res(PACKET_forward(pkt
, eop
- PACKET_data(pkt
)));
1096 * This packet cannot be processed and will never be processable.
1097 * Because even its header is not intelligible, we cannot examine any
1098 * further packets in the datagram because its length cannot be
1101 * Advance over the entire remainder of the datagram, and mark it as
1102 * processed as an optimization.
1104 pkt_mark(&urxe
->processed
, pkt_idx
);
1105 /* We don't care if this fails (see above) */
1106 ignore_res(PACKET_forward(pkt
, PACKET_remaining(pkt
)));
1108 return 0; /* failure, did not defer; not distinguished from success */
1111 /* Process a datagram which was received. */
1112 static int qrx_process_datagram(OSSL_QRX
*qrx
, QUIC_URXE
*e
,
1113 const unsigned char *data
,
1116 int have_deferred
= 0;
1119 QUIC_CONN_ID first_dcid
= { 255 };
1121 qrx
->bytes_received
+= data_len
;
1123 if (!PACKET_buf_init(&pkt
, data
, data_len
))
1126 for (; PACKET_remaining(&pkt
) > 0; ++pkt_idx
) {
1128 * A packet smaller than the minimum possible QUIC packet size is not
1129 * considered valid. We also ignore more than a certain number of
1130 * packets within the same datagram.
1132 if (PACKET_remaining(&pkt
) < QUIC_MIN_VALID_PKT_LEN
1133 || pkt_idx
>= QUIC_MAX_PKT_PER_URXE
)
1137 * We note whether packet processing resulted in a deferral since
1138 * this means we need to move the URXE to the deferred list rather
1139 * than the free list after we're finished dealing with it for now.
1141 * However, we don't otherwise care here whether processing succeeded or
1142 * failed, as the RFC says even if a packet in a datagram is malformed,
1143 * we should still try to process any packets following it.
1145 * In the case where the packet is so malformed we can't determine its
1146 * length, qrx_process_pkt will take care of advancing to the end of
1147 * the packet, so we will exit the loop automatically in this case.
1149 if (qrx_process_pkt(qrx
, e
, &pkt
, pkt_idx
, &first_dcid
, data_len
))
1153 /* Only report whether there were any deferrals. */
1154 return have_deferred
;
1157 /* Process a single pending URXE. */
1158 static int qrx_process_one_urxe(OSSL_QRX
*qrx
, QUIC_URXE
*e
)
1162 /* The next URXE we process should be at the head of the pending list. */
1163 if (!ossl_assert(e
== ossl_list_urxe_head(&qrx
->urx_pending
)))
1167 * Attempt to process the datagram. The return value indicates only if
1168 * processing of the datagram was deferred. If we failed to process the
1169 * datagram, we do not attempt to process it again and silently eat the
1172 was_deferred
= qrx_process_datagram(qrx
, e
, ossl_quic_urxe_data(e
),
1176 * Remove the URXE from the pending list and return it to
1177 * either the free or deferred list.
1179 ossl_list_urxe_remove(&qrx
->urx_pending
, e
);
1180 if (was_deferred
> 0 &&
1181 (e
->deferred
|| qrx
->num_deferred
< qrx
->max_deferred
)) {
1182 ossl_list_urxe_insert_tail(&qrx
->urx_deferred
, e
);
1185 ++qrx
->num_deferred
;
1190 --qrx
->num_deferred
;
1192 ossl_quic_demux_release_urxe(qrx
->demux
, e
);
1198 /* Process any pending URXEs to generate pending RXEs. */
1199 static int qrx_process_pending_urxl(OSSL_QRX
*qrx
)
1203 while ((e
= ossl_list_urxe_head(&qrx
->urx_pending
)) != NULL
)
1204 if (!qrx_process_one_urxe(qrx
, e
))
1210 int ossl_qrx_read_pkt(OSSL_QRX
*qrx
, OSSL_QRX_PKT
**ppkt
)
1214 if (!ossl_qrx_processed_read_pending(qrx
)) {
1215 if (!qrx_process_pending_urxl(qrx
))
1218 if (!ossl_qrx_processed_read_pending(qrx
))
1222 rxe
= qrx_pop_pending_rxe(qrx
);
1223 if (!ossl_assert(rxe
!= NULL
))
1226 assert(rxe
->refcount
== 0);
1229 rxe
->pkt
.hdr
= &rxe
->hdr
;
1230 rxe
->pkt
.pn
= rxe
->pn
;
1231 rxe
->pkt
.time
= rxe
->time
;
1232 rxe
->pkt
.datagram_len
= rxe
->datagram_len
;
1234 = BIO_ADDR_family(&rxe
->peer
) != AF_UNSPEC
? &rxe
->peer
: NULL
;
1236 = BIO_ADDR_family(&rxe
->local
) != AF_UNSPEC
? &rxe
->local
: NULL
;
1237 rxe
->pkt
.key_epoch
= rxe
->key_epoch
;
1238 rxe
->pkt
.datagram_id
= rxe
->datagram_id
;
1245 void ossl_qrx_pkt_release(OSSL_QRX_PKT
*pkt
)
1253 assert(rxe
->refcount
> 0);
1254 if (--rxe
->refcount
== 0)
1255 qrx_recycle_rxe(pkt
->qrx
, rxe
);
1258 void ossl_qrx_pkt_up_ref(OSSL_QRX_PKT
*pkt
)
1260 RXE
*rxe
= (RXE
*)pkt
;
1262 assert(rxe
->refcount
> 0);
1266 uint64_t ossl_qrx_get_bytes_received(OSSL_QRX
*qrx
, int clear
)
1268 uint64_t v
= qrx
->bytes_received
;
1271 qrx
->bytes_received
= 0;
1276 int ossl_qrx_set_late_validation_cb(OSSL_QRX
*qrx
,
1277 ossl_qrx_late_validation_cb
*cb
,
1280 qrx
->validation_cb
= cb
;
1281 qrx
->validation_cb_arg
= cb_arg
;
1285 int ossl_qrx_set_key_update_cb(OSSL_QRX
*qrx
,
1286 ossl_qrx_key_update_cb
*cb
,
1289 qrx
->key_update_cb
= cb
;
1290 qrx
->key_update_cb_arg
= cb_arg
;
1294 uint64_t ossl_qrx_get_key_epoch(OSSL_QRX
*qrx
)
1296 OSSL_QRL_ENC_LEVEL
*el
= ossl_qrl_enc_level_set_get(&qrx
->el_set
,
1297 QUIC_ENC_LEVEL_1RTT
, 1);
1299 return el
== NULL
? UINT64_MAX
: el
->key_epoch
;
1302 int ossl_qrx_key_update_timeout(OSSL_QRX
*qrx
, int normal
)
1304 OSSL_QRL_ENC_LEVEL
*el
= ossl_qrl_enc_level_set_get(&qrx
->el_set
,
1305 QUIC_ENC_LEVEL_1RTT
, 1);
1310 if (el
->state
== QRL_EL_STATE_PROV_UPDATING
1311 && !ossl_qrl_enc_level_set_key_update_done(&qrx
->el_set
,
1312 QUIC_ENC_LEVEL_1RTT
))
1315 if (normal
&& el
->state
== QRL_EL_STATE_PROV_COOLDOWN
1316 && !ossl_qrl_enc_level_set_key_cooldown_done(&qrx
->el_set
,
1317 QUIC_ENC_LEVEL_1RTT
))
1323 uint64_t ossl_qrx_get_cur_forged_pkt_count(OSSL_QRX
*qrx
)
1325 return qrx
->forged_pkt_count
;
1328 uint64_t ossl_qrx_get_max_forged_pkt_count(OSSL_QRX
*qrx
,
1331 OSSL_QRL_ENC_LEVEL
*el
= ossl_qrl_enc_level_set_get(&qrx
->el_set
,
1334 return el
== NULL
? UINT64_MAX
1335 : ossl_qrl_get_suite_max_forged_pkt(el
->suite_id
);
1338 void ossl_qrx_allow_1rtt_processing(OSSL_QRX
*qrx
)
1340 if (qrx
->allow_1rtt
)
1343 qrx
->allow_1rtt
= 1;
1344 qrx_requeue_deferred(qrx
);
1347 void ossl_qrx_set_msg_callback(OSSL_QRX
*qrx
, ossl_msg_cb msg_callback
,
1348 SSL
*msg_callback_ssl
)
1350 qrx
->msg_callback
= msg_callback
;
1351 qrx
->msg_callback_ssl
= msg_callback_ssl
;
1354 void ossl_qrx_set_msg_callback_arg(OSSL_QRX
*qrx
, void *msg_callback_arg
)
1356 qrx
->msg_callback_arg
= msg_callback_arg
;