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