QUIC ackm: 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 "../ssl_local.h"
14
15 /*
16  * Mark a packet in a bitfield.
17  *
18  * pkt_idx: index of packet within datagram.
19  */
20 static ossl_inline void pkt_mark(uint64_t *bitf, size_t pkt_idx)
21 {
22     assert(pkt_idx < QUIC_MAX_PKT_PER_URXE);
23     *bitf |= ((uint64_t)1) << pkt_idx;
24 }
25
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)
28 {
29     assert(pkt_idx < QUIC_MAX_PKT_PER_URXE);
30     return (*bitf & (((uint64_t)1) << pkt_idx)) != 0;
31 }
32
33 /*
34  * RXE
35  * ===
36  *
37  * RX Entries (RXEs) store processed (i.e., decrypted) data received from the
38  * network. One RXE is used per received QUIC packet.
39  */
40 typedef struct rxe_st RXE;
41
42 struct rxe_st {
43     RXE                *prev, *next;
44     size_t              data_len, alloc_len;
45
46     /* Extra fields for per-packet information. */
47     QUIC_PKT_HDR        hdr; /* data/len are decrypted payload */
48
49     /* Decoded packet number. */
50     QUIC_PN             pn;
51
52     /* Addresses copied from URXE. */
53     BIO_ADDR            peer, local;
54
55     /* Time we received the packet (not when we processed it). */
56     OSSL_TIME           time;
57
58     /* Total length of the datagram which contained this packet. */
59     size_t              datagram_len;
60
61     /*
62      * alloc_len allocated bytes (of which data_len bytes are valid) follow this
63      * structure.
64      */
65 };
66
67 typedef struct ossl_qrx_rxe_list_st {
68     RXE *head, *tail;
69 } RXE_LIST;
70
71 static ossl_inline unsigned char *rxe_data(const RXE *e)
72 {
73     return (unsigned char *)(e + 1);
74 }
75
76 static void rxe_remove(RXE_LIST *l, RXE *e)
77 {
78     if (e->prev != NULL)
79         e->prev->next = e->next;
80     if (e->next != NULL)
81         e->next->prev = e->prev;
82
83     if (e == l->head)
84         l->head = e->next;
85     if (e == l->tail)
86         l->tail = e->prev;
87
88     e->next = e->prev = NULL;
89 }
90
91 static void rxe_insert_tail(RXE_LIST *l, RXE *e)
92 {
93     if (l->tail == NULL) {
94         l->head = l->tail = e;
95         e->next = e->prev = NULL;
96         return;
97     }
98
99     l->tail->next = e;
100     e->prev = l->tail;
101     e->next = NULL;
102     l->tail = e;
103 }
104
105 /*
106  * QRL
107  * ===
108  */
109 struct ossl_qrx_st {
110     OSSL_LIB_CTX               *libctx;
111     const char                 *propq;
112
113     /* Demux to receive datagrams from. */
114     QUIC_DEMUX                 *demux;
115
116     /* Length of connection IDs used in short-header packets in bytes. */
117     size_t                      short_conn_id_len;
118
119     /* Maximum number of deferred datagrams buffered at any one time. */
120     size_t                      max_deferred;
121
122     /* Current count of deferred datagrams. */
123     size_t                      num_deferred;
124
125     /*
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.
128      */
129     QUIC_URXE_LIST              urx_pending;
130
131     /*
132      * List of URXEs which we could not decrypt immediately and which are being
133      * kept in case they can be decrypted later.
134      */
135     QUIC_URXE_LIST              urx_deferred;
136
137     /*
138      * List of RXEs which are not currently in use. These are moved
139      * to the pending list as they are filled.
140      */
141     RXE_LIST                    rx_free;
142
143     /*
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.
147      */
148     RXE_LIST                    rx_pending;
149
150     /* Largest PN we have received and processed in a given PN space. */
151     QUIC_PN                     largest_pn[QUIC_PN_SPACE_NUM];
152
153     /* Per encryption-level state. */
154     OSSL_QRL_ENC_LEVEL_SET      el_set;
155
156     /* Bytes we have received since this counter was last cleared. */
157     uint64_t                    bytes_received;
158
159     /*
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.
163      */
164     uint64_t                    forged_pkt_count;
165
166     /* Validation callback. */
167     ossl_qrx_early_validation_cb   *validation_cb;
168     void                           *validation_cb_arg;
169
170     /* Key update callback. */
171     ossl_qrx_key_update_cb         *key_update_cb;
172     void                           *key_update_cb_arg;
173
174     /* Initial key phase. For debugging use only; always 0 in real use. */
175     unsigned char                   init_key_phase_bit;
176 };
177
178 static void qrx_on_rx(QUIC_URXE *urxe, void *arg);
179
180 OSSL_QRX *ossl_qrx_new(const OSSL_QRX_ARGS *args)
181 {
182     OSSL_QRX *qrx;
183     size_t i;
184
185     if (args->demux == NULL || args->max_deferred == 0)
186         return 0;
187
188     qrx = OPENSSL_zalloc(sizeof(OSSL_QRX));
189     if (qrx == NULL)
190         return 0;
191
192     for (i = 0; i < OSSL_NELEM(qrx->largest_pn); ++i)
193         qrx->largest_pn[i] = args->init_largest_pn[i];
194
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;
201     return qrx;
202 }
203
204 static void qrx_cleanup_rxl(RXE_LIST *l)
205 {
206     RXE *e, *enext;
207
208     for (e = l->head; e != NULL; e = enext) {
209         enext = e->next;
210         OPENSSL_free(e);
211     }
212
213     l->head = l->tail = NULL;
214 }
215
216 static void qrx_cleanup_urxl(OSSL_QRX *qrx, QUIC_URXE_LIST *l)
217 {
218     QUIC_URXE *e, *enext;
219
220     for (e = l->head; e != NULL; e = enext) {
221         enext = e->next;
222         ossl_quic_demux_release_urxe(qrx->demux, e);
223     }
224
225     l->head = l->tail = NULL;
226 }
227
228 void ossl_qrx_free(OSSL_QRX *qrx)
229 {
230     uint32_t i;
231
232     /* Unregister from the RX DEMUX. */
233     ossl_quic_demux_unregister_by_cb(qrx->demux, qrx_on_rx, qrx);
234
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);
240
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);
244
245     OPENSSL_free(qrx);
246 }
247
248 static void qrx_on_rx(QUIC_URXE *urxe, void *arg)
249 {
250     OSSL_QRX *qrx = arg;
251
252     /* Initialize our own fields inside the URXE and add to the pending list. */
253     urxe->processed     = 0;
254     urxe->hpr_removed   = 0;
255     urxe->deferred      = 0;
256     ossl_quic_urxe_insert_tail(&qrx->urx_pending, urxe);
257 }
258
259 int ossl_qrx_add_dst_conn_id(OSSL_QRX *qrx,
260                              const QUIC_CONN_ID *dst_conn_id)
261 {
262     return ossl_quic_demux_register(qrx->demux,
263                                     dst_conn_id,
264                                     qrx_on_rx,
265                                     qrx);
266 }
267
268 int ossl_qrx_remove_dst_conn_id(OSSL_QRX *qrx,
269                                 const QUIC_CONN_ID *dst_conn_id)
270 {
271     return ossl_quic_demux_unregister(qrx->demux, dst_conn_id);
272 }
273
274 static void qrx_requeue_deferred(OSSL_QRX *qrx)
275 {
276     QUIC_URXE *e;
277
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);
281     }
282 }
283
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)
287 {
288     if (enc_level >= QUIC_ENC_LEVEL_NUM)
289         return 0;
290
291     if (!ossl_qrl_enc_level_set_provide_secret(&qrx->el_set,
292                                                qrx->libctx,
293                                                qrx->propq,
294                                                enc_level,
295                                                suite_id,
296                                                md,
297                                                secret,
298                                                secret_len,
299                                                qrx->init_key_phase_bit,
300                                                /*is_tx=*/0))
301         return 0;
302
303     /*
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.
307      */
308     qrx_requeue_deferred(qrx);
309     return 1;
310 }
311
312 int ossl_qrx_discard_enc_level(OSSL_QRX *qrx, uint32_t enc_level)
313 {
314     if (enc_level >= QUIC_ENC_LEVEL_NUM)
315         return 0;
316
317     ossl_qrl_enc_level_set_discard(&qrx->el_set, enc_level);
318     return 1;
319 }
320
321 /* Returns 1 if there are one or more pending RXEs. */
322 int ossl_qrx_processed_read_pending(OSSL_QRX *qrx)
323 {
324     return qrx->rx_pending.head != NULL;
325 }
326
327 /* Returns 1 if there are yet-unprocessed packets. */
328 int ossl_qrx_unprocessed_read_pending(OSSL_QRX *qrx)
329 {
330     return qrx->urx_pending.head != NULL || qrx->urx_deferred.head != NULL;
331 }
332
333 /* Pop the next pending RXE. Returns NULL if no RXE is pending. */
334 static RXE *qrx_pop_pending_rxe(OSSL_QRX *qrx)
335 {
336     RXE *rxe = qrx->rx_pending.head;
337
338     if (rxe == NULL)
339         return NULL;
340
341     rxe_remove(&qrx->rx_pending, rxe);
342     return rxe;
343 }
344
345 /* Allocate a new RXE. */
346 static RXE *qrx_alloc_rxe(size_t alloc_len)
347 {
348     RXE *rxe;
349
350     if (alloc_len >= SIZE_MAX - sizeof(RXE))
351         return NULL;
352
353     rxe = OPENSSL_malloc(sizeof(RXE) + alloc_len);
354     if (rxe == NULL)
355         return NULL;
356
357     rxe->prev = rxe->next = NULL;
358     rxe->alloc_len = alloc_len;
359     rxe->data_len  = 0;
360     return rxe;
361 }
362
363 /*
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.
366  *
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.
369  */
370 static RXE *qrx_ensure_free_rxe(OSSL_QRX *qrx, size_t alloc_len)
371 {
372     RXE *rxe;
373
374     if (qrx->rx_free.head != NULL)
375         return qrx->rx_free.head;
376
377     rxe = qrx_alloc_rxe(alloc_len);
378     if (rxe == NULL)
379         return NULL;
380
381     rxe_insert_tail(&qrx->rx_free, rxe);
382     return rxe;
383 }
384
385 /*
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.
389  */
390 static RXE *qrx_resize_rxe(RXE_LIST *rxl, RXE *rxe, size_t n)
391 {
392     RXE *rxe2;
393
394     /* Should never happen. */
395     if (rxe == NULL)
396         return NULL;
397
398     if (n >= SIZE_MAX - sizeof(RXE))
399         return NULL;
400
401     /*
402      * NOTE: We do not clear old memory, although it does contain decrypted
403      * data.
404      */
405     rxe2 = OPENSSL_realloc(rxe, sizeof(RXE) + n);
406     if (rxe2 == NULL)
407         /* original RXE is still intact unchanged */
408         return NULL;
409
410     if (rxe != rxe2) {
411         if (rxl->head == rxe)
412             rxl->head = rxe2;
413         if (rxl->tail == rxe)
414             rxl->tail = rxe2;
415         if (rxe->prev != NULL)
416             rxe->prev->next = rxe2;
417         if (rxe->next != NULL)
418             rxe->next->prev = rxe2;
419     }
420
421     rxe2->alloc_len = n;
422     return rxe2;
423 }
424
425 /*
426  * Ensure the data buffer attached to an RXE is at least n bytes in size.
427  * Returns NULL on failure.
428  */
429 static RXE *qrx_reserve_rxe(RXE_LIST *rxl,
430                             RXE *rxe, size_t n)
431 {
432     if (rxe->alloc_len >= n)
433         return rxe;
434
435     return qrx_resize_rxe(rxl, rxe, n);
436 }
437
438 /* Return a RXE handed out to the user back to our freelist. */
439 static void qrx_recycle_rxe(OSSL_QRX *qrx, RXE *rxe)
440 {
441     /* RXE should not be in any list */
442     assert(rxe->prev == NULL && rxe->next == NULL);
443     rxe_insert_tail(&qrx->rx_free, rxe);
444 }
445
446 /*
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.
452  */
453 static int qrx_relocate_buffer(OSSL_QRX *qrx, RXE **prxe, size_t *pi,
454                                const unsigned char **pptr, size_t buf_len)
455 {
456     RXE *rxe;
457     unsigned char *dst;
458
459     if (!buf_len)
460         return 1;
461
462     if ((rxe = qrx_reserve_rxe(&qrx->rx_free, *prxe, *pi + buf_len)) == NULL)
463         return 0;
464
465     *prxe = rxe;
466     dst = (unsigned char *)rxe_data(rxe) + *pi;
467
468     memcpy(dst, *pptr, buf_len);
469     *pi += buf_len;
470     *pptr = dst;
471     return 1;
472 }
473
474 static uint32_t qrx_determine_enc_level(const QUIC_PKT_HDR *hdr)
475 {
476     switch (hdr->type) {
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;
485
486         default:
487             assert(0);
488         case QUIC_PKT_TYPE_RETRY:
489         case QUIC_PKT_TYPE_VERSION_NEG:
490             return QUIC_ENC_LEVEL_INITIAL; /* not used */
491     }
492 }
493
494 static uint32_t rxe_determine_pn_space(RXE *rxe)
495 {
496     uint32_t enc_level;
497
498     enc_level = qrx_determine_enc_level(&rxe->hdr);
499     return ossl_quic_enc_level_to_pn_space(enc_level);
500 }
501
502 static int qrx_validate_hdr_early(OSSL_QRX *qrx, RXE *rxe,
503                                   RXE *first_rxe)
504 {
505     /* Ensure version is what we want. */
506     if (rxe->hdr.version != QUIC_VERSION_1
507         && rxe->hdr.version != QUIC_VERSION_NONE)
508         return 0;
509
510     /* Clients should never receive 0-RTT packets. */
511     if (rxe->hdr.type == QUIC_PKT_TYPE_0RTT)
512         return 0;
513
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))
516         return 0;
517
518     /*
519      * If this is not the first packet in a datagram, the destination connection
520      * ID must match the one in that packet.
521      */
522     if (first_rxe != NULL &&
523         !ossl_quic_conn_id_eq(&first_rxe->hdr.dst_conn_id,
524                               &rxe->hdr.dst_conn_id))
525         return 0;
526
527     return 1;
528 }
529
530 /* Validate header and decode PN. */
531 static int qrx_validate_hdr(OSSL_QRX *qrx, RXE *rxe)
532 {
533     int pn_space = rxe_determine_pn_space(rxe);
534
535     if (!ossl_quic_wire_decode_pkt_hdr_pn(rxe->hdr.pn, rxe->hdr.pn_len,
536                                           qrx->largest_pn[pn_space],
537                                           &rxe->pn))
538         return 0;
539
540     /*
541      * Allow our user to decide whether to discard the packet before we try and
542      * decrypt it.
543      */
544     if (qrx->validation_cb != NULL
545         && !qrx->validation_cb(rxe->pn, pn_space, qrx->validation_cb_arg))
546         return 0;
547
548     return 1;
549 }
550
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,
553                                      uint32_t enc_level,
554                                      unsigned char key_phase_bit)
555 {
556     if (enc_level != QUIC_ENC_LEVEL_1RTT)
557         return 0;
558
559     if (!ossl_assert(key_phase_bit <= 1))
560         return SIZE_MAX;
561
562     /*
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.
568      *
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
571      * this case:
572      *
573      *   Endpoints can use randomized packet protection keys in place of
574      *   discarded keys when key updates are not yet permitted.
575      *
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.
579      *
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
583      * RFC.
584      */
585     return el->state == QRL_EL_STATE_PROV_COOLDOWN ? el->key_epoch & 1
586                                                    : key_phase_bit;
587 }
588
589 /*
590  * Tries to decrypt a packet payload.
591  *
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.
597  */
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)
604 {
605     int l = 0, l2 = 0;
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,
609                                                         enc_level, 1);
610     EVP_CIPHER_CTX *cctx;
611
612     if (src_len > INT_MAX || aad_len > INT_MAX)
613         return 0;
614
615     /* We should not have been called if we do not have key material. */
616     if (!ossl_assert(el != NULL))
617         return 0;
618
619     if (el->tag_len >= src_len)
620         return 0;
621
622     /*
623      * If we have failed to authenticate a certain number of ciphertexts, refuse
624      * to decrypt any more ciphertexts.
625      */
626     if (qrx->forged_pkt_count >= ossl_qrl_get_suite_max_forged_pkt(el->suite_id))
627         return 0;
628
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)))
631         return 0;
632
633     cctx = el->cctx[cctx_idx];
634
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)))
638         return 0;
639
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));
643
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)
647         return 0;
648
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,
651                             el->tag_len,
652                             (unsigned char *)src + src_len - el->tag_len) != 1)
653         return 0;
654
655     /* Feed AAD data. */
656     if (EVP_CipherUpdate(cctx, NULL, &l, aad, aad_len) != 1)
657         return 0;
658
659     /* Feed encrypted packet body. */
660     if (EVP_CipherUpdate(cctx, dst, &l, src, src_len - el->tag_len) != 1)
661         return 0;
662
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;
667         return 0;
668     }
669
670     *dec_len = l;
671     return 1;
672 }
673
674 static ossl_inline void ignore_res(int x)
675 {
676     /* No-op. */
677 }
678
679 static void qrx_key_update_initiated(OSSL_QRX *qrx)
680 {
681     if (!ossl_qrl_enc_level_set_key_update(&qrx->el_set, QUIC_ENC_LEVEL_1RTT))
682         return;
683
684     if (qrx->key_update_cb != NULL)
685         qrx->key_update_cb(qrx->key_update_cb_arg);
686 }
687
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,
691                            RXE **first_rxe,
692                            size_t datagram_len)
693 {
694     RXE *rxe;
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);
699     unsigned char *dst;
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;
704
705     /*
706      * Get a free RXE. If we need to allocate a new one, use the packet length
707      * as a good ballpark figure.
708      */
709     rxe = qrx_ensure_free_rxe(qrx, PACKET_remaining(pkt));
710     if (rxe == NULL)
711         return 0;
712
713     /* Have we already processed this packet? */
714     if (pkt_is_marked(&urxe->processed, pkt_idx))
715         already_processed = 1;
716
717     /*
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).
721      */
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))
726         goto malformed;
727
728     /*
729      * Our successful decode above included an intelligible length and the
730      * PACKET is now pointing to the end of the QUIC packet.
731      */
732     eop = PACKET_data(pkt);
733
734     /*
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.
737      */
738     if (pkt_idx == 0)
739         *first_rxe = rxe;
740
741     /*
742      * Early header validation. Since we now know the packet length, we can also
743      * now skip over it if we already processed it.
744      */
745     if (already_processed
746         || !qrx_validate_hdr_early(qrx, rxe, pkt_idx == 0 ? NULL : *first_rxe))
747         /*
748          * Already processed packets are handled identically to malformed
749          * packets; i.e., they are ignored.
750          */
751         goto malformed;
752
753     if (!ossl_quic_pkt_type_is_encrypted(rxe->hdr.type)) {
754         /*
755          * Version negotiation and retry packets are a special case. They do not
756          * contain a payload which needs decrypting and have no header
757          * protection.
758          */
759
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)
762             /*
763              * Allocation failure. EOP will be pointing to the end of the
764              * datagram so processing of this datagram will end here.
765              */
766             goto malformed;
767
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);
771
772         rxe->hdr.data   = rxe_data(rxe);
773         rxe->pn         = QUIC_PN_INVALID;
774
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 */
779     }
780
781     /* Determine encryption level of packet. */
782     enc_level = qrx_determine_enc_level(&rxe->hdr);
783
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)) {
786         case 1:
787             /* We have keys. */
788             break;
789         case 0:
790             /* No keys yet. */
791             goto cannot_decrypt;
792         default:
793             /* We already discarded keys for this EL, we will never process this.*/
794             goto malformed;
795     }
796
797     /*
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.
802      */
803     i = 0;
804
805     /*
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).
809      *
810      * Firstly, relocate some of these fields into the RXE as needed.
811      *
812      * Relocate token buffer and fix pointer.
813      */
814     if (rxe->hdr.type == QUIC_PKT_TYPE_INITIAL
815         && !qrx_relocate_buffer(qrx, &rxe, &i, &rxe->hdr.token,
816                                 rxe->hdr.token_len))
817         goto malformed;
818
819     /* Now remove header protection. */
820     *pkt = orig_pkt;
821
822     el = ossl_qrl_enc_level_set_get(&qrx->el_set, enc_level, 1);
823     assert(el != NULL); /* Already checked above */
824
825     if (need_second_decode) {
826         if (!ossl_quic_hdr_protector_decrypt(&el->hpr, &ptrs))
827             goto malformed;
828
829         /*
830          * We have removed header protection, so don't attempt to do it again if
831          * the packet gets deferred and processed again.
832          */
833         pkt_mark(&urxe->hpr_removed, pkt_idx);
834
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)
838             goto malformed;
839     }
840
841     /* Validate header and decode PN. */
842     if (!qrx_validate_hdr(qrx, rxe))
843         goto malformed;
844
845     /*
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.
849      */
850     aad_len = rxe->hdr.data - sop;
851
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) {
854         /*
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.
858          */
859         eop = NULL;
860         goto malformed;
861     }
862
863     /*
864      * We decrypt the packet body to immediately after the token at the start of
865      * the RXE buffer (where present).
866      *
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.
870      *
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
874      * corrupted.
875      */
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,
879                               rxe->hdr.key_phase))
880         goto malformed;
881
882     /*
883      * We automatically discard INITIAL keys when successfully decrypting a
884      * HANDSHAKE packet.
885      */
886     if (enc_level == QUIC_ENC_LEVEL_HANDSHAKE)
887         ossl_qrl_enc_level_set_discard(&qrx->el_set, QUIC_ENC_LEVEL_INITIAL);
888
889     /*
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.
893      */
894     if (rxe->hdr.type == QUIC_PKT_TYPE_1RTT
895         && rxe->hdr.key_phase != (el->key_epoch & 1))
896         qrx_key_update_initiated(qrx);
897
898     /*
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
907      * processed.
908      *
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
911      * accordingly.
912      */
913     pkt_mark(&urxe->processed, pkt_idx);
914
915     /*
916      * Update header to point to the decrypted buffer, which may be shorter
917      * due to AEAD tags, block padding, etc.
918      */
919     rxe->hdr.data       = dst;
920     rxe->hdr.len        = dec_len;
921     rxe->data_len       = dec_len;
922     rxe->datagram_len   = datagram_len;
923
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;
928
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;
933
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 */
938
939 cannot_decrypt:
940     /*
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
943      * and skip over it.
944      */
945     assert(eop != NULL && eop >= PACKET_data(pkt));
946     /*
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.
949      */
950     ignore_res(PACKET_forward(pkt, eop - PACKET_data(pkt)));
951     return 1; /* deferred */
952
953 malformed:
954     if (eop != NULL) {
955         /*
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
959          * datagram.
960          *
961          * Mark as processed as an optimization.
962          */
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)));
967     } else {
968         /*
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
972          * discerned.
973          *
974          * Advance over the entire remainder of the datagram, and mark it as
975          * processed gap as an optimization.
976          */
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)));
980     }
981     return 0; /* failure, did not defer; not distinguished from success */
982 }
983
984 /* Process a datagram which was received. */
985 static int qrx_process_datagram(OSSL_QRX *qrx, QUIC_URXE *e,
986                                 const unsigned char *data,
987                                 size_t data_len)
988 {
989     int have_deferred = 0;
990     PACKET pkt;
991     size_t pkt_idx = 0;
992     RXE *first_rxe = NULL;
993
994     qrx->bytes_received += data_len;
995
996     if (!PACKET_buf_init(&pkt, data, data_len))
997         return 0;
998
999     for (; PACKET_remaining(&pkt) > 0; ++pkt_idx) {
1000         /*
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.
1004          */
1005         if (PACKET_remaining(&pkt) < QUIC_MIN_VALID_PKT_LEN
1006             || pkt_idx >= QUIC_MAX_PKT_PER_URXE)
1007             break;
1008
1009         /*
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.
1013          *
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.
1017          *
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.
1021          */
1022         if (qrx_process_pkt(qrx, e, &pkt, pkt_idx, &first_rxe, data_len))
1023             have_deferred = 1;
1024     }
1025
1026     /* Only report whether there were any deferrals. */
1027     return have_deferred;
1028 }
1029
1030 /* Process a single pending URXE. */
1031 static int qrx_process_one_urxe(OSSL_QRX *qrx, QUIC_URXE *e)
1032 {
1033     int was_deferred;
1034
1035     /* The next URXE we process should be at the head of the pending list. */
1036     if (!ossl_assert(e == qrx->urx_pending.head))
1037         return 0;
1038
1039     /*
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
1043      * error.
1044      */
1045     was_deferred = qrx_process_datagram(qrx, e, ossl_quic_urxe_data(e),
1046                                         e->data_len);
1047
1048     /*
1049      * Remove the URXE from the pending list and return it to
1050      * either the free or deferred list.
1051      */
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);
1056         if (!e->deferred) {
1057             e->deferred = 1;
1058             ++qrx->num_deferred;
1059         }
1060     } else {
1061         if (e->deferred) {
1062             e->deferred = 0;
1063             --qrx->num_deferred;
1064         }
1065         ossl_quic_demux_release_urxe(qrx->demux, e);
1066     }
1067
1068     return 1;
1069 }
1070
1071 /* Process any pending URXEs to generate pending RXEs. */
1072 static int qrx_process_pending_urxl(OSSL_QRX *qrx)
1073 {
1074     QUIC_URXE *e;
1075
1076     while ((e = qrx->urx_pending.head) != NULL)
1077         if (!qrx_process_one_urxe(qrx, e))
1078             return 0;
1079
1080     return 1;
1081 }
1082
1083 int ossl_qrx_read_pkt(OSSL_QRX *qrx, OSSL_QRX_PKT *pkt)
1084 {
1085     RXE *rxe;
1086
1087     if (!ossl_qrx_processed_read_pending(qrx)) {
1088         if (!qrx_process_pending_urxl(qrx))
1089             return 0;
1090
1091         if (!ossl_qrx_processed_read_pending(qrx))
1092             return 0;
1093     }
1094
1095     rxe = qrx_pop_pending_rxe(qrx);
1096     if (!ossl_assert(rxe != NULL))
1097         return 0;
1098
1099     pkt->handle     = rxe;
1100     pkt->hdr        = &rxe->hdr;
1101     pkt->pn         = rxe->pn;
1102     pkt->time       = rxe->time;
1103     pkt->peer
1104         = BIO_ADDR_family(&rxe->peer) != AF_UNSPEC ? &rxe->peer : NULL;
1105     pkt->local
1106         = BIO_ADDR_family(&rxe->local) != AF_UNSPEC ? &rxe->local : NULL;
1107     return 1;
1108 }
1109
1110 void ossl_qrx_release_pkt(OSSL_QRX *qrx, void *handle)
1111 {
1112     if (handle != NULL) {
1113         RXE *rxe = handle;
1114
1115         qrx_recycle_rxe(qrx, rxe);
1116     }
1117 }
1118
1119 uint64_t ossl_qrx_get_bytes_received(OSSL_QRX *qrx, int clear)
1120 {
1121     uint64_t v = qrx->bytes_received;
1122
1123     if (clear)
1124         qrx->bytes_received = 0;
1125
1126     return v;
1127 }
1128
1129 int ossl_qrx_set_early_validation_cb(OSSL_QRX *qrx,
1130                                      ossl_qrx_early_validation_cb *cb,
1131                                      void *cb_arg)
1132 {
1133     qrx->validation_cb       = cb;
1134     qrx->validation_cb_arg   = cb_arg;
1135     return 1;
1136 }
1137
1138 int ossl_qrx_set_key_update_cb(OSSL_QRX *qrx,
1139                                ossl_qrx_key_update_cb *cb,
1140                                void *cb_arg)
1141 {
1142     qrx->key_update_cb      = cb;
1143     qrx->key_update_cb_arg  = cb_arg;
1144     return 1;
1145 }
1146
1147 uint64_t ossl_qrx_get_key_epoch(OSSL_QRX *qrx)
1148 {
1149     OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(&qrx->el_set,
1150                                                         QUIC_ENC_LEVEL_1RTT, 1);
1151
1152     return el == NULL ? UINT64_MAX : el->key_epoch;
1153 }
1154
1155 int ossl_qrx_key_update_timeout(OSSL_QRX *qrx, int normal)
1156 {
1157     OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(&qrx->el_set,
1158                                                         QUIC_ENC_LEVEL_1RTT, 1);
1159
1160     if (el == NULL)
1161         return 0;
1162
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))
1166         return 0;
1167
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))
1171         return 0;
1172
1173     return 1;
1174 }
1175
1176 uint64_t ossl_qrx_get_cur_forged_pkt_count(OSSL_QRX *qrx)
1177 {
1178     return qrx->forged_pkt_count;
1179 }
1180
1181 uint64_t ossl_qrx_get_max_forged_pkt_count(OSSL_QRX *qrx,
1182                                            uint32_t enc_level)
1183 {
1184     OSSL_QRL_ENC_LEVEL *el = ossl_qrl_enc_level_set_get(&qrx->el_set,
1185                                                         enc_level, 1);
1186
1187     return el == NULL ? UINT64_MAX
1188         : ossl_qrl_get_suite_max_forged_pkt(el->suite_id);
1189 }