4a2d5bb043de9fd04a59e633befc4c528b4b6c08
[openssl.git] / ssl / quic / quic_tls.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 #include <openssl/ssl.h>
10 #include "internal/recordmethod.h"
11 #include "internal/quic_tls.h"
12 #include "../ssl_local.h"
13
14 #define QUIC_TLS_FATAL(rl, ad, err) \
15     do { \
16         (rl)->alert = (ad); \
17         ERR_raise(ERR_LIB_SSL, (err)); \
18         (rl)->qtls->inerror = 1; \
19     } while(0)
20
21 struct quic_tls_st {
22     QUIC_TLS_ARGS args;
23
24     /*
25      * Transport parameters which client should send. Buffer lifetime must
26      * exceed the lifetime of the QUIC_TLS object.
27      */
28     const unsigned char *local_transport_params;
29     size_t local_transport_params_len;
30
31     /* Whether our SSL object for TLS has been configured for use in QUIC */
32     unsigned int configured : 1;
33
34     /* Set if we have hit any error state */
35     unsigned int inerror : 1;
36
37     /* Set if the handshake has completed */
38     unsigned int complete : 1;
39 };
40
41 struct ossl_record_layer_st {
42     QUIC_TLS *qtls;
43     /* Only used for retry flags */
44     BIO *dummybio;
45
46     /* Number of bytes written so far if we are part way through a write */
47     size_t written;
48
49     /* If we are part way through a write, a copy of the template */
50     OSSL_RECORD_TEMPLATE template;
51
52     /*
53      * Temp buffer for storing received data (copied from the stream receive
54      * buffer)
55      */
56     unsigned char recbuf[SSL3_RT_MAX_PLAIN_LENGTH];
57
58     /*
59      * If we hit an error, what alert code should be used
60      */
61     int alert;
62
63     /* Set if recbuf is populated with data */
64     unsigned int recread : 1;
65 };
66
67 static int
68 quic_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
69                       int role, int direction, int level, uint16_t epoch,
70                       unsigned char *secret, size_t secretlen,
71                       unsigned char *key, size_t keylen, unsigned char *iv,
72                       size_t ivlen, unsigned char *mackey, size_t mackeylen,
73                       const EVP_CIPHER *ciph, size_t taglen,
74                       int mactype,
75                       const EVP_MD *md, COMP_METHOD *comp,
76                       const EVP_MD *kdfdigest, BIO *prev, BIO *transport,
77                       BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
78                       const OSSL_PARAM *settings, const OSSL_PARAM *options,
79                       const OSSL_DISPATCH *fns, void *cbarg, void *rlarg,
80                       OSSL_RECORD_LAYER **retrl)
81 {
82     OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
83     uint32_t enc_level;
84     int qdir;
85     uint32_t suite_id = 0;
86
87     if (rl == NULL) {
88         QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
89         return 0;
90     }
91
92     rl->qtls = (QUIC_TLS *)rlarg;
93     rl->dummybio = transport;
94     *retrl = rl;
95
96     switch (level) {
97     case OSSL_RECORD_PROTECTION_LEVEL_NONE:
98         return 1;
99
100     case OSSL_RECORD_PROTECTION_LEVEL_EARLY:
101         enc_level = QUIC_ENC_LEVEL_0RTT;
102         break;
103
104     case OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE:
105         enc_level = QUIC_ENC_LEVEL_HANDSHAKE;
106         break;
107
108     case OSSL_RECORD_PROTECTION_LEVEL_APPLICATION:
109         enc_level = QUIC_ENC_LEVEL_1RTT;
110         break;
111
112     default:
113         QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
114         goto err;
115     }
116
117     if (direction == OSSL_RECORD_DIRECTION_READ)
118         qdir = 0;
119     else
120         qdir = 1;
121
122     if (EVP_CIPHER_is_a(ciph, "AES-128-GCM")) {
123         suite_id = QRL_SUITE_AES128GCM;
124     } else if (EVP_CIPHER_is_a(ciph, "AES-256-GCM")) {
125         suite_id = QRL_SUITE_AES256GCM;
126     } else if (EVP_CIPHER_is_a(ciph, "CHACHA20-POLY1305")) {
127         suite_id = QRL_SUITE_CHACHA20POLY1305;
128     } else {
129         QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_CIPHER_TYPE);
130         goto err;
131     }
132
133     /* We pass a ref to the md in a successful yield_secret_cb call */
134     /* TODO(QUIC): This cast is horrible. We should try and remove it */
135     if (!EVP_MD_up_ref((EVP_MD *)kdfdigest)) {
136         QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
137         goto err;
138     }
139
140     if (!rl->qtls->args.yield_secret_cb(enc_level, qdir, suite_id,
141                                         (EVP_MD *)kdfdigest, secret, secretlen,
142                                         rl->qtls->args.yield_secret_cb_arg)) {
143         QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
144         EVP_MD_free((EVP_MD *)kdfdigest);
145         goto err;
146     }
147
148     return 1;
149  err:
150     *retrl = NULL;
151     OPENSSL_free(rl);
152     return 0;
153 }
154
155 static int quic_free(OSSL_RECORD_LAYER *rl)
156 {
157     if (rl == NULL)
158         return 1;
159
160     OPENSSL_free(rl);
161     return 1;
162 }
163
164 static int quic_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
165 {
166     /*
167      * Read ahead isn't really a thing for QUIC so we never have unprocessed
168      * data pending
169      */
170     return 0;
171 }
172
173 static int quic_processed_read_pending(OSSL_RECORD_LAYER *rl)
174 {
175     /*
176      * This is currently only ever used by:
177      * - SSL_has_pending()
178      * - to check whether we have more records that we want to supply to the
179      *   upper layers
180      *
181      * We only ever supply 1 record at a time to the upper layers, and
182      * SSL_has_pending() will go via the QUIC method not the TLS method so that
183      * use case doesn't apply here.
184      * Therefore we can ignore this for now and always return 0. We might
185      * eventually want to change this to check in the receive buffers to see if
186      * we have any more data pending.
187      */
188     return 0;
189 }
190
191 static size_t quic_get_max_records(OSSL_RECORD_LAYER *rl, int type, size_t len,
192                                    size_t maxfrag, size_t *preffrag)
193 {
194     return 1;
195 }
196
197 static int quic_write_records(OSSL_RECORD_LAYER *rl,
198                               OSSL_RECORD_TEMPLATE *template,
199                               size_t numtempl)
200 {
201     size_t consumed;
202     unsigned char alert;
203
204     if (!ossl_assert(numtempl == 1)) {
205         /* How could this be? quic_get_max_records() always returns 1 */
206         QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
207         return OSSL_RECORD_RETURN_FATAL;
208     }
209
210     BIO_clear_retry_flags(rl->dummybio);
211
212     switch (template->type) {
213     case SSL3_RT_ALERT:
214         if (template->buflen != 2) {
215             /*
216              * We assume that libssl always sends both bytes of an alert to
217              * us in one go, and never fragments it. If we ever get more
218              * or less bytes than exactly 2 then this is very unexpected.
219              */
220             QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_VALUE);
221             return OSSL_RECORD_RETURN_FATAL;
222         }
223         /*
224          * Byte 0 is the alert level (we ignore it) and byte 1 is the alert
225          * description that we are actually interested in.
226          */
227         alert = template->buf[1];
228
229         if (!rl->qtls->args.alert_cb(rl->qtls->args.alert_cb_arg, alert)) {
230             QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
231             return OSSL_RECORD_RETURN_FATAL;
232         }
233         break;
234
235     case SSL3_RT_HANDSHAKE:
236         /*
237          * We expect this to only fail on some fatal error (e.g. malloc
238          * failure)
239          */
240         if (!rl->qtls->args.crypto_send_cb(template->buf + rl->written,
241                                            template->buflen - rl->written,
242                                            &consumed,
243                                            rl->qtls->args.crypto_send_cb_arg)) {
244             QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
245             return OSSL_RECORD_RETURN_FATAL;
246         }
247         /*
248          * We might have written less than we wanted to if we have filled the
249          * send stream buffer.
250          */
251         if (consumed + rl->written != template->buflen) {
252             if (!ossl_assert(consumed + rl->written < template->buflen)) {
253                 QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
254                 return OSSL_RECORD_RETURN_FATAL;
255             }
256
257             /*
258              * We've not written everything we wanted to. Take a copy of the
259              * template, remember how much we wrote so far and signal a retry.
260              * The buffer supplied in the template is guaranteed to be the same
261              * on a retry for handshake data
262              */
263             rl->written += consumed;
264             rl->template = *template;
265             BIO_set_retry_write(rl->dummybio);
266
267             return OSSL_RECORD_RETURN_RETRY;
268         }
269         rl->written = 0;
270         break;
271
272     default:
273         /* Anything else is unexpected and an error */
274         QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
275         return OSSL_RECORD_RETURN_FATAL;
276     }
277
278     return OSSL_RECORD_RETURN_SUCCESS;
279 }
280
281 static int quic_retry_write_records(OSSL_RECORD_LAYER *rl)
282 {
283     return quic_write_records(rl, &rl->template, 1);
284 }
285
286 static int quic_read_record(OSSL_RECORD_LAYER *rl, void **rechandle,
287                             int *rversion, int *type, unsigned char **data,
288                             size_t *datalen, uint16_t *epoch,
289                             unsigned char *seq_num)
290 {
291     if (rl->recread != 0)
292         return OSSL_RECORD_RETURN_FATAL;
293
294     BIO_clear_retry_flags(rl->dummybio);
295
296     /*
297      * TODO(QUIC): There seems to be an unnecessary copy here. It would be
298      *             better to send back a ref direct to the underlying buffer
299      */
300     if (!rl->qtls->args.crypto_recv_cb(rl->recbuf, sizeof(rl->recbuf), datalen,
301                                        rl->qtls->args.crypto_recv_cb_arg)) {
302         QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
303         return OSSL_RECORD_RETURN_FATAL;
304     }
305
306     if (*datalen == 0) {
307         BIO_set_retry_read(rl->dummybio);
308         return OSSL_RECORD_RETURN_RETRY;
309     }
310
311     *rechandle = rl;
312     *rversion = TLS1_3_VERSION;
313     *type = SSL3_RT_HANDSHAKE;
314     *data = rl->recbuf;
315     rl->recread = 1;
316     /* epoch/seq_num are not relevant for TLS */
317
318     return OSSL_RECORD_RETURN_SUCCESS;
319 }
320
321 static int quic_release_record(OSSL_RECORD_LAYER *rl, void *rechandle)
322 {
323     if (!ossl_assert(rl->recread == 1) || !ossl_assert(rl == rechandle)) {
324         QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
325         return 0;
326     }
327
328     rl->recread = 0;
329     return 1;
330 }
331
332 static int quic_get_alert_code(OSSL_RECORD_LAYER *rl)
333 {
334     return rl->alert;
335 }
336
337 static int quic_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
338 {
339     /* We only support TLSv1.3, so its bad if we negotiate anything else */
340     if (!ossl_assert(version == TLS1_3_VERSION)) {
341         QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
342         return 0;
343     }
344
345     return 1;
346 }
347
348 static void quic_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
349 {
350     /* We don't care */
351 }
352
353 static void quic_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
354 {
355     /* We don't care */
356 }
357
358 static void quic_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
359 {
360     /* We don't care */
361 }
362
363 static void quic_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
364                     const char **longstr)
365 {
366     /*
367      * According to the docs, valid read state strings are: "RH"/"read header",
368      * "RB"/"read body", "RD"/"read done" and "unknown"/"unknown". We don't
369      * read records in quite that way, so we report every "normal" state as
370      * "read done". In the event of error then we report "unknown".
371      */
372
373     if (rl->qtls->inerror) {
374         if (shortstr != NULL)
375             *shortstr = "unknown";
376         if (longstr != NULL)
377             *longstr = "unknown";
378     } else {
379         if (shortstr != NULL)
380             *shortstr = "RD";
381         if (longstr != NULL)
382             *longstr = "read done";
383     }
384 }
385
386 static int quic_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options)
387 {
388     /*
389      * We don't support any options yet - but we might do at some point so
390      * this could be useful.
391      */
392     return 1;
393 }
394
395 static const COMP_METHOD *quic_get_compression(OSSL_RECORD_LAYER *rl)
396 {
397     /* We only support TLSv1.3 which doesn't have compression */
398     return NULL;
399 }
400
401 static void quic_set_max_frag_len(OSSL_RECORD_LAYER *rl, size_t max_frag_len)
402 {
403     /* This really doesn't make any sense for QUIC. Ignore it */
404 }
405
406 static int quic_alloc_buffers(OSSL_RECORD_LAYER *rl)
407 {
408     /*
409      * This is a hint only. We don't support it (yet), so just ignore the
410      * request
411      */
412     return 1;
413 }
414
415 static int quic_free_buffers(OSSL_RECORD_LAYER *rl)
416 {
417     /*
418      * This is a hint only. We don't support it (yet), so just ignore the
419      * request
420      */
421     return 1;
422 }
423
424 static int quic_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
425 {
426     /*
427      * Can be called to set the buffering BIO - which is then never used by us.
428      * We ignore it
429      */
430     return 1;
431 }
432
433 /*
434  * Never called functions
435  *
436  * Due to the way we are configured and used we never expect any of the next set
437  * of functions to be called. Therefore we set them to always fail.
438  */
439
440 static size_t quic_app_data_pending(OSSL_RECORD_LAYER *rl)
441 {
442     QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
443     return (size_t)ossl_assert(0);
444 }
445
446 static size_t quic_get_max_record_overhead(OSSL_RECORD_LAYER *rl)
447 {
448     QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
449     return (size_t)ossl_assert(0);
450 }
451
452 static int quic_increment_sequence_ctr(OSSL_RECORD_LAYER *rl)
453 {
454     QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
455     return ossl_assert(0);
456 }
457
458 /* End of never called functions */
459
460 static const OSSL_RECORD_METHOD quic_tls_record_method = {
461     quic_new_record_layer,
462     quic_free,
463     quic_unprocessed_read_pending,
464     quic_processed_read_pending,
465     quic_app_data_pending, /* Never called */
466     quic_get_max_records,
467     quic_write_records,
468     quic_retry_write_records,
469     quic_read_record,
470     quic_release_record,
471     quic_get_alert_code,
472     quic_set1_bio,
473     quic_set_protocol_version,
474     quic_set_plain_alerts,
475     quic_set_first_handshake,
476     quic_set_max_pipelines,
477     NULL, /* set_in_init: Optional - we don't need it */
478     quic_get_state,
479     quic_set_options,
480     quic_get_compression,
481     quic_set_max_frag_len,
482     quic_get_max_record_overhead, /* Never called */
483     quic_increment_sequence_ctr, /* Never called */
484     quic_alloc_buffers,
485     quic_free_buffers
486 };
487
488 static int add_transport_params_cb(SSL *s, unsigned int ext_type,
489                                    unsigned int context,
490                                    const unsigned char **out, size_t *outlen,
491                                    X509 *x, size_t chainidx, int *al,
492                                    void *add_arg)
493 {
494     QUIC_TLS *qtls = add_arg;
495
496     *out = qtls->local_transport_params;
497     *outlen = qtls->local_transport_params_len;
498     return 1;
499 }
500
501 static void free_transport_params_cb(SSL *s, unsigned int ext_type,
502                                      unsigned int context,
503                                      const unsigned char *out,
504                                      void *add_arg)
505 {
506 }
507
508 static int parse_transport_params_cb(SSL *s, unsigned int ext_type,
509                                      unsigned int context,
510                                      const unsigned char *in,
511                                      size_t inlen, X509 *x,
512                                      size_t chainidx,
513                                      int *al, void *parse_arg)
514 {
515     QUIC_TLS *qtls = parse_arg;
516
517     return qtls->args.got_transport_params_cb(in, inlen,
518                                               qtls->args.got_transport_params_cb_arg);
519 }
520
521 QUIC_TLS *ossl_quic_tls_new(const QUIC_TLS_ARGS *args)
522 {
523     QUIC_TLS *qtls;
524
525     if (args->crypto_send_cb == NULL
526         || args->crypto_recv_cb == NULL) {
527         ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
528         return NULL;
529     }
530
531     qtls = OPENSSL_zalloc(sizeof(*qtls));
532     if (qtls == NULL)
533         return NULL;
534
535     qtls->args = *args;
536     return qtls;
537 }
538
539 void ossl_quic_tls_free(QUIC_TLS *qtls)
540 {
541     OPENSSL_free(qtls);
542 }
543
544 int ossl_quic_tls_tick(QUIC_TLS *qtls)
545 {
546     int ret;
547     const unsigned char *alpn;
548     unsigned int alpnlen;
549
550     /*
551      * TODO(QUIC): There are various calls here that could fail and ordinarily
552      * would result in an ERR_raise call - but "tick" calls aren't supposed to
553      * fail "loudly" - so its unclear how we will report these errors. The
554      * ERR_raise calls are omitted from this function for now.
555      */
556
557     if (qtls->inerror)
558         return 0;
559
560     if (qtls->complete)
561         return 1;
562
563     if (!qtls->configured) {
564         SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(qtls->args.s);
565         BIO *nullbio;
566
567         /*
568          * No matter how the user has configured us, there are certain
569          * requirements for QUIC-TLS that we enforce
570          */
571
572         /* ALPN is a requirement for QUIC and must be set */
573         if (sc->ext.alpn == NULL || sc->ext.alpn_len == 0) {
574             qtls->inerror = 1;
575             return 0;
576         }
577         if (!SSL_set_min_proto_version(qtls->args.s, TLS1_3_VERSION)) {
578             qtls->inerror = 1;
579             return 0;
580         }
581         SSL_clear_options(qtls->args.s, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
582         ossl_ssl_set_custom_record_layer(sc, &quic_tls_record_method, qtls);
583
584         if (!ossl_tls_add_custom_ext_intern(NULL, &sc->cert->custext,
585                                             ENDPOINT_CLIENT,
586                                             TLSEXT_TYPE_quic_transport_parameters,
587                                             SSL_EXT_TLS1_3_ONLY
588                                             | SSL_EXT_CLIENT_HELLO
589                                             | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
590                                             add_transport_params_cb,
591                                             free_transport_params_cb, qtls,
592                                             parse_transport_params_cb, qtls)) {
593             qtls->inerror = 1;
594             return 0;
595         }
596
597         nullbio = BIO_new(BIO_s_null());
598         if (nullbio == NULL) {
599             qtls->inerror = 1;
600             return 0;
601         }
602
603         /*
604          * Our custom record layer doesn't use the BIO - but libssl generally
605          * expects one to be present.
606          */
607         SSL_set_bio(qtls->args.s, nullbio, nullbio);
608
609         qtls->configured = 1;
610     }
611     ret = SSL_connect(qtls->args.s);
612     if (ret <= 0) {
613         switch (SSL_get_error(qtls->args.s, ret)) {
614         case SSL_ERROR_WANT_READ:
615         case SSL_ERROR_WANT_WRITE:
616             return 1;
617         default:
618             qtls->inerror = 1;
619             return 0;
620         }
621     }
622
623     /* Validate that we have ALPN */
624     SSL_get0_alpn_selected(qtls->args.s, &alpn, &alpnlen);
625     if (alpn == NULL || alpnlen == 0) {
626         qtls->inerror = 1;
627         return 0;
628     }
629     qtls->complete = 1;
630     return qtls->args.handshake_complete_cb(qtls->args.handshake_complete_cb_arg);
631 }
632
633 int ossl_quic_tls_set_transport_params(QUIC_TLS *qtls,
634                                        const unsigned char *transport_params,
635                                        size_t transport_params_len)
636 {
637     if (!ossl_assert(!qtls->args.is_server)) {
638         ERR_raise(ERR_LIB_SSL, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
639         qtls->inerror = 1;
640         return 0;
641     }
642
643     qtls->local_transport_params       = transport_params;
644     qtls->local_transport_params_len   = transport_params_len;
645     return 1;
646 }