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