Coverage Report

Created: 2023-09-25 06:42

/src/openssl/ssl/quic/quic_tls.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 2022-2023 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
#include "internal/quic_error.h"
14
15
#define QUIC_TLS_FATAL(rl, ad, err) \
16
0
    do { \
17
0
        if ((rl) != NULL) (rl)->alert = (ad); \
18
0
        ERR_raise(ERR_LIB_SSL, (err)); \
19
0
        if ((rl) != NULL) (rl)->qtls->inerror = 1; \
20
0
    } while(0)
21
22
struct quic_tls_st {
23
    QUIC_TLS_ARGS args;
24
25
    /*
26
     * Transport parameters which client should send. Buffer lifetime must
27
     * exceed the lifetime of the QUIC_TLS object.
28
     */
29
    const unsigned char *local_transport_params;
30
    size_t local_transport_params_len;
31
32
    ERR_STATE *error_state;
33
34
    /*
35
     * QUIC error code (usually in the TLS Alert-mapped CRYPTO_ERR range). Valid
36
     * only if inerror is 1.
37
     */
38
    uint64_t error_code;
39
40
    /*
41
     * Error message with static storage duration. Valid only if inerror is 1.
42
     * Should be suitable for encapsulation in a CONNECTION_CLOSE frame.
43
     */
44
    const char *error_msg;
45
46
    /* Whether our SSL object for TLS has been configured for use in QUIC */
47
    unsigned int configured : 1;
48
49
    /* Set if we have hit any error state */
50
    unsigned int inerror : 1;
51
52
    /* Set if the handshake has completed */
53
    unsigned int complete : 1;
54
};
55
56
struct ossl_record_layer_st {
57
    QUIC_TLS *qtls;
58
59
    /* Protection level */
60
    int level;
61
62
    /* Only used for retry flags */
63
    BIO *dummybio;
64
65
    /* Number of bytes written so far if we are part way through a write */
66
    size_t written;
67
68
    /* If we are part way through a write, a copy of the template */
69
    OSSL_RECORD_TEMPLATE template;
70
71
    /*
72
     * If we hit an error, what alert code should be used
73
     */
74
    int alert;
75
76
    /* Amount of crypto stream data we read in the last call to quic_read_record */
77
    size_t recread;
78
79
    /* Amount of crypto stream data read but not yet released */
80
    size_t recunreleased;
81
82
    /* Callbacks */
83
    OSSL_FUNC_rlayer_msg_callback_fn *msg_callback;
84
    void *cbarg;
85
};
86
87
static int quic_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio);
88
89
static int
90
quic_new_record_layer(OSSL_LIB_CTX *libctx, const char *propq, int vers,
91
                      int role, int direction, int level, uint16_t epoch,
92
                      unsigned char *secret, size_t secretlen,
93
                      unsigned char *key, size_t keylen, unsigned char *iv,
94
                      size_t ivlen, unsigned char *mackey, size_t mackeylen,
95
                      const EVP_CIPHER *ciph, size_t taglen,
96
                      int mactype,
97
                      const EVP_MD *md, COMP_METHOD *comp,
98
                      const EVP_MD *kdfdigest, BIO *prev, BIO *transport,
99
                      BIO *next, BIO_ADDR *local, BIO_ADDR *peer,
100
                      const OSSL_PARAM *settings, const OSSL_PARAM *options,
101
                      const OSSL_DISPATCH *fns, void *cbarg, void *rlarg,
102
                      OSSL_RECORD_LAYER **retrl)
103
0
{
104
0
    OSSL_RECORD_LAYER *rl = OPENSSL_zalloc(sizeof(*rl));
105
0
    uint32_t enc_level;
106
0
    int qdir;
107
0
    uint32_t suite_id = 0;
108
109
0
    if (rl == NULL) {
110
0
        QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
111
0
        return 0;
112
0
    }
113
114
0
    rl->qtls = (QUIC_TLS *)rlarg;
115
0
    rl->level = level;
116
0
    if (!quic_set1_bio(rl, transport)) {
117
0
        QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
118
0
        goto err;
119
0
    }
120
0
    rl->cbarg = cbarg;
121
0
    *retrl = rl;
122
123
0
    if (fns != NULL) {
124
0
        for (; fns->function_id != 0; fns++) {
125
0
            switch (fns->function_id) {
126
0
                break;
127
0
            case OSSL_FUNC_RLAYER_MSG_CALLBACK:
128
0
                rl->msg_callback = OSSL_FUNC_rlayer_msg_callback(fns);
129
0
                break;
130
0
            default:
131
                /* Just ignore anything we don't understand */
132
0
                break;
133
0
            }
134
0
        }
135
0
    }
136
137
0
    switch (level) {
138
0
    case OSSL_RECORD_PROTECTION_LEVEL_NONE:
139
0
        return 1;
140
141
0
    case OSSL_RECORD_PROTECTION_LEVEL_EARLY:
142
0
        enc_level = QUIC_ENC_LEVEL_0RTT;
143
0
        break;
144
145
0
    case OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE:
146
0
        enc_level = QUIC_ENC_LEVEL_HANDSHAKE;
147
0
        break;
148
149
0
    case OSSL_RECORD_PROTECTION_LEVEL_APPLICATION:
150
0
        enc_level = QUIC_ENC_LEVEL_1RTT;
151
0
        break;
152
153
0
    default:
154
0
        QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
155
0
        goto err;
156
0
    }
157
158
0
    if (direction == OSSL_RECORD_DIRECTION_READ)
159
0
        qdir = 0;
160
0
    else
161
0
        qdir = 1;
162
163
0
    if (EVP_CIPHER_is_a(ciph, "AES-128-GCM")) {
164
0
        suite_id = QRL_SUITE_AES128GCM;
165
0
    } else if (EVP_CIPHER_is_a(ciph, "AES-256-GCM")) {
166
0
        suite_id = QRL_SUITE_AES256GCM;
167
0
    } else if (EVP_CIPHER_is_a(ciph, "CHACHA20-POLY1305")) {
168
0
        suite_id = QRL_SUITE_CHACHA20POLY1305;
169
0
    } else {
170
0
        QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, SSL_R_UNKNOWN_CIPHER_TYPE);
171
0
        goto err;
172
0
    }
173
174
    /* We pass a ref to the md in a successful yield_secret_cb call */
175
    /* TODO(QUIC FUTURE): This cast is horrible. We should try and remove it */
176
0
    if (!EVP_MD_up_ref((EVP_MD *)kdfdigest)) {
177
0
        QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
178
0
        goto err;
179
0
    }
180
181
0
    if (!rl->qtls->args.yield_secret_cb(enc_level, qdir, suite_id,
182
0
                                        (EVP_MD *)kdfdigest, secret, secretlen,
183
0
                                        rl->qtls->args.yield_secret_cb_arg)) {
184
0
        QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
185
0
        EVP_MD_free((EVP_MD *)kdfdigest);
186
0
        goto err;
187
0
    }
188
189
0
    return 1;
190
0
 err:
191
0
    *retrl = NULL;
192
0
    OPENSSL_free(rl);
193
0
    return 0;
194
0
}
195
196
static int quic_free(OSSL_RECORD_LAYER *rl)
197
0
{
198
0
    if (rl == NULL)
199
0
        return 1;
200
201
0
    BIO_free(rl->dummybio);
202
0
    OPENSSL_free(rl);
203
0
    return 1;
204
0
}
205
206
static int quic_unprocessed_read_pending(OSSL_RECORD_LAYER *rl)
207
0
{
208
    /*
209
     * Read ahead isn't really a thing for QUIC so we never have unprocessed
210
     * data pending
211
     */
212
0
    return 0;
213
0
}
214
215
static int quic_processed_read_pending(OSSL_RECORD_LAYER *rl)
216
0
{
217
    /*
218
     * This is currently only ever used by:
219
     * - SSL_has_pending()
220
     * - to check whether we have more records that we want to supply to the
221
     *   upper layers
222
     *
223
     * We only ever supply 1 record at a time to the upper layers, and
224
     * SSL_has_pending() will go via the QUIC method not the TLS method so that
225
     * use case doesn't apply here.
226
     * Therefore we can ignore this for now and always return 0. We might
227
     * eventually want to change this to check in the receive buffers to see if
228
     * we have any more data pending.
229
     */
230
0
    return 0;
231
0
}
232
233
static size_t quic_get_max_records(OSSL_RECORD_LAYER *rl, uint8_t type,
234
                                   size_t len,
235
                                   size_t maxfrag, size_t *preffrag)
236
0
{
237
0
    return 1;
238
0
}
239
240
static int quic_write_records(OSSL_RECORD_LAYER *rl,
241
                              OSSL_RECORD_TEMPLATE *template,
242
                              size_t numtempl)
243
0
{
244
0
    size_t consumed;
245
0
    unsigned char alert;
246
247
0
    if (!ossl_assert(numtempl == 1)) {
248
        /* How could this be? quic_get_max_records() always returns 1 */
249
0
        QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
250
0
        return OSSL_RECORD_RETURN_FATAL;
251
0
    }
252
253
0
    BIO_clear_retry_flags(rl->dummybio);
254
255
0
    if (rl->msg_callback != NULL) {
256
0
        unsigned char dummyrec[SSL3_RT_HEADER_LENGTH];
257
258
        /*
259
         * For the purposes of the callback we "pretend" to be normal TLS,
260
         * and manufacture a dummy record header
261
         */
262
0
        dummyrec[0] = (rl->level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
263
0
                        ? template->type
264
0
                        : SSL3_RT_APPLICATION_DATA;
265
0
        dummyrec[1] = (unsigned char)((template->version >> 8) & 0xff);
266
0
        dummyrec[2] = (unsigned char)(template->version & 0xff);
267
        /*
268
         * We assume that buflen is always <= UINT16_MAX. Since this is
269
         * generated by libssl itself we actually expect it to never
270
         * exceed SSL3_RT_MAX_PLAIN_LENGTH - so it should be a safe
271
         * assumption
272
         */
273
0
        dummyrec[3] = (unsigned char)((template->buflen >> 8) & 0xff);
274
0
        dummyrec[4] = (unsigned char)(template->buflen & 0xff);
275
276
0
        rl->msg_callback(1, TLS1_3_VERSION, SSL3_RT_HEADER, dummyrec,
277
0
                            SSL3_RT_HEADER_LENGTH, rl->cbarg);
278
279
0
        if (rl->level != OSSL_RECORD_PROTECTION_LEVEL_NONE) {
280
0
            rl->msg_callback(1, TLS1_3_VERSION, SSL3_RT_INNER_CONTENT_TYPE,
281
0
                             &template->type, 1, rl->cbarg);
282
0
        }
283
0
    }
284
285
0
    switch (template->type) {
286
0
    case SSL3_RT_ALERT:
287
0
        if (template->buflen != 2) {
288
            /*
289
             * We assume that libssl always sends both bytes of an alert to
290
             * us in one go, and never fragments it. If we ever get more
291
             * or less bytes than exactly 2 then this is very unexpected.
292
             */
293
0
            QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_VALUE);
294
0
            return OSSL_RECORD_RETURN_FATAL;
295
0
        }
296
        /*
297
         * Byte 0 is the alert level (we ignore it) and byte 1 is the alert
298
         * description that we are actually interested in.
299
         */
300
0
        alert = template->buf[1];
301
302
0
        if (!rl->qtls->args.alert_cb(rl->qtls->args.alert_cb_arg, alert)) {
303
0
            QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
304
0
            return OSSL_RECORD_RETURN_FATAL;
305
0
        }
306
0
        break;
307
308
0
    case SSL3_RT_HANDSHAKE:
309
        /*
310
         * We expect this to only fail on some fatal error (e.g. malloc
311
         * failure)
312
         */
313
0
        if (!rl->qtls->args.crypto_send_cb(template->buf + rl->written,
314
0
                                           template->buflen - rl->written,
315
0
                                           &consumed,
316
0
                                           rl->qtls->args.crypto_send_cb_arg)) {
317
0
            QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
318
0
            return OSSL_RECORD_RETURN_FATAL;
319
0
        }
320
        /*
321
         * We might have written less than we wanted to if we have filled the
322
         * send stream buffer.
323
         */
324
0
        if (consumed + rl->written != template->buflen) {
325
0
            if (!ossl_assert(consumed + rl->written < template->buflen)) {
326
0
                QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
327
0
                return OSSL_RECORD_RETURN_FATAL;
328
0
            }
329
330
            /*
331
             * We've not written everything we wanted to. Take a copy of the
332
             * template, remember how much we wrote so far and signal a retry.
333
             * The buffer supplied in the template is guaranteed to be the same
334
             * on a retry for handshake data
335
             */
336
0
            rl->written += consumed;
337
0
            rl->template = *template;
338
0
            BIO_set_retry_write(rl->dummybio);
339
340
0
            return OSSL_RECORD_RETURN_RETRY;
341
0
        }
342
0
        rl->written = 0;
343
0
        break;
344
345
0
    default:
346
        /* Anything else is unexpected and an error */
347
0
        QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
348
0
        return OSSL_RECORD_RETURN_FATAL;
349
0
    }
350
351
0
    return OSSL_RECORD_RETURN_SUCCESS;
352
0
}
353
354
static int quic_retry_write_records(OSSL_RECORD_LAYER *rl)
355
0
{
356
0
    return quic_write_records(rl, &rl->template, 1);
357
0
}
358
359
static int quic_read_record(OSSL_RECORD_LAYER *rl, void **rechandle,
360
                            int *rversion, uint8_t *type, const unsigned char **data,
361
                            size_t *datalen, uint16_t *epoch,
362
                            unsigned char *seq_num)
363
0
{
364
0
    if (rl->recread != 0 || rl->recunreleased != 0)
365
0
        return OSSL_RECORD_RETURN_FATAL;
366
367
0
    BIO_clear_retry_flags(rl->dummybio);
368
369
0
    if (!rl->qtls->args.crypto_recv_rcd_cb(data, datalen,
370
0
                                           rl->qtls->args.crypto_recv_rcd_cb_arg)) {
371
0
        QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
372
0
        return OSSL_RECORD_RETURN_FATAL;
373
0
    }
374
375
0
    if (*datalen == 0) {
376
0
        BIO_set_retry_read(rl->dummybio);
377
0
        return OSSL_RECORD_RETURN_RETRY;
378
0
    }
379
380
0
    *rechandle = rl;
381
0
    *rversion = TLS1_3_VERSION;
382
0
    *type = SSL3_RT_HANDSHAKE;
383
0
    rl->recread = rl->recunreleased = *datalen;
384
    /* epoch/seq_num are not relevant for TLS */
385
386
0
    if (rl->msg_callback != NULL) {
387
0
        unsigned char dummyrec[SSL3_RT_HEADER_LENGTH];
388
389
        /*
390
         * For the purposes of the callback we "pretend" to be normal TLS,
391
         * and manufacture a dummy record header
392
         */
393
0
        dummyrec[0] = (rl->level == OSSL_RECORD_PROTECTION_LEVEL_NONE)
394
0
                      ? SSL3_RT_HANDSHAKE
395
0
                      : SSL3_RT_APPLICATION_DATA;
396
0
        dummyrec[1] = (unsigned char)((TLS1_2_VERSION >> 8) & 0xff);
397
0
        dummyrec[2] = (unsigned char)(TLS1_2_VERSION & 0xff);
398
        /*
399
         * *datalen will always fit into 2 bytes because our original buffer
400
         * size is less than that.
401
         */
402
0
        dummyrec[3] = (unsigned char)((*datalen >> 8) & 0xff);
403
0
        dummyrec[4] = (unsigned char)(*datalen & 0xff);
404
405
0
        rl->msg_callback(0, TLS1_3_VERSION, SSL3_RT_HEADER, dummyrec,
406
0
                         SSL3_RT_HEADER_LENGTH, rl->cbarg);
407
0
        rl->msg_callback(0, TLS1_3_VERSION, SSL3_RT_INNER_CONTENT_TYPE, type, 1,
408
0
                         rl->cbarg);
409
0
    }
410
411
0
    return OSSL_RECORD_RETURN_SUCCESS;
412
0
}
413
414
static int quic_release_record(OSSL_RECORD_LAYER *rl, void *rechandle,
415
                               size_t length)
416
0
{
417
0
    if (!ossl_assert(rl->recread > 0)
418
0
            || !ossl_assert(rl->recunreleased <= rl->recread)
419
0
            || !ossl_assert(rl == rechandle)
420
0
            || !ossl_assert(length <= rl->recunreleased)) {
421
0
        QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
422
0
        return OSSL_RECORD_RETURN_FATAL;
423
0
    }
424
425
0
    rl->recunreleased -= length;
426
427
0
    if (rl->recunreleased > 0)
428
0
        return OSSL_RECORD_RETURN_SUCCESS;
429
430
0
    if (!rl->qtls->args.crypto_release_rcd_cb(rl->recread,
431
0
                                              rl->qtls->args.crypto_release_rcd_cb_arg)) {
432
0
        QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
433
0
        return OSSL_RECORD_RETURN_FATAL;
434
0
    }
435
436
0
    rl->recread = 0;
437
0
    return OSSL_RECORD_RETURN_SUCCESS;
438
0
}
439
440
static int quic_get_alert_code(OSSL_RECORD_LAYER *rl)
441
0
{
442
0
    return rl->alert;
443
0
}
444
445
static int quic_set_protocol_version(OSSL_RECORD_LAYER *rl, int version)
446
0
{
447
    /* We only support TLSv1.3, so its bad if we negotiate anything else */
448
0
    if (!ossl_assert(version == TLS1_3_VERSION)) {
449
0
        QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
450
0
        return 0;
451
0
    }
452
453
0
    return 1;
454
0
}
455
456
static void quic_set_plain_alerts(OSSL_RECORD_LAYER *rl, int allow)
457
0
{
458
    /* We don't care */
459
0
}
460
461
static void quic_set_first_handshake(OSSL_RECORD_LAYER *rl, int first)
462
0
{
463
    /* We don't care */
464
0
}
465
466
static void quic_set_max_pipelines(OSSL_RECORD_LAYER *rl, size_t max_pipelines)
467
0
{
468
    /* We don't care */
469
0
}
470
471
static void quic_get_state(OSSL_RECORD_LAYER *rl, const char **shortstr,
472
                    const char **longstr)
473
0
{
474
    /*
475
     * According to the docs, valid read state strings are: "RH"/"read header",
476
     * "RB"/"read body", and "unknown"/"unknown". We don't read records in quite
477
     * that way, so we report every "normal" state as "read header". In the
478
     * event of error then we report "unknown".
479
     */
480
481
0
    if (rl->qtls->inerror) {
482
0
        if (shortstr != NULL)
483
0
            *shortstr = "unknown";
484
0
        if (longstr != NULL)
485
0
            *longstr = "unknown";
486
0
    } else {
487
0
        if (shortstr != NULL)
488
0
            *shortstr = "RH";
489
0
        if (longstr != NULL)
490
0
            *longstr = "read header";
491
0
    }
492
0
}
493
494
static int quic_set_options(OSSL_RECORD_LAYER *rl, const OSSL_PARAM *options)
495
0
{
496
    /*
497
     * We don't support any options yet - but we might do at some point so
498
     * this could be useful.
499
     */
500
0
    return 1;
501
0
}
502
503
static const COMP_METHOD *quic_get_compression(OSSL_RECORD_LAYER *rl)
504
0
{
505
    /* We only support TLSv1.3 which doesn't have compression */
506
0
    return NULL;
507
0
}
508
509
static void quic_set_max_frag_len(OSSL_RECORD_LAYER *rl, size_t max_frag_len)
510
0
{
511
    /* This really doesn't make any sense for QUIC. Ignore it */
512
0
}
513
514
static int quic_alloc_buffers(OSSL_RECORD_LAYER *rl)
515
0
{
516
    /*
517
     * This is a hint only. We don't support it (yet), so just ignore the
518
     * request
519
     */
520
0
    return 1;
521
0
}
522
523
static int quic_free_buffers(OSSL_RECORD_LAYER *rl)
524
0
{
525
    /*
526
     * This is a hint only. We don't support it (yet), so just ignore the
527
     * request
528
     */
529
0
    return 1;
530
0
}
531
532
static int quic_set1_bio(OSSL_RECORD_LAYER *rl, BIO *bio)
533
0
{
534
0
    if (bio != NULL && !BIO_up_ref(bio))
535
0
        return 0;
536
0
    BIO_free(rl->dummybio);
537
0
    rl->dummybio = bio;
538
539
0
    return 1;
540
0
}
541
542
/*
543
 * Never called functions
544
 *
545
 * Due to the way we are configured and used we never expect any of the next set
546
 * of functions to be called. Therefore we set them to always fail.
547
 */
548
549
static size_t quic_app_data_pending(OSSL_RECORD_LAYER *rl)
550
0
{
551
0
    QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
552
0
    return (size_t)ossl_assert(0);
553
0
}
554
555
static size_t quic_get_max_record_overhead(OSSL_RECORD_LAYER *rl)
556
0
{
557
0
    QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
558
0
    return (size_t)ossl_assert(0);
559
0
}
560
561
static int quic_increment_sequence_ctr(OSSL_RECORD_LAYER *rl)
562
0
{
563
0
    QUIC_TLS_FATAL(rl, SSL_AD_INTERNAL_ERROR, ERR_R_SHOULD_NOT_HAVE_BEEN_CALLED);
564
0
    return ossl_assert(0);
565
0
}
566
567
/* End of never called functions */
568
569
static const OSSL_RECORD_METHOD quic_tls_record_method = {
570
    quic_new_record_layer,
571
    quic_free,
572
    quic_unprocessed_read_pending,
573
    quic_processed_read_pending,
574
    quic_app_data_pending, /* Never called */
575
    quic_get_max_records,
576
    quic_write_records,
577
    quic_retry_write_records,
578
    quic_read_record,
579
    quic_release_record,
580
    quic_get_alert_code,
581
    quic_set1_bio,
582
    quic_set_protocol_version,
583
    quic_set_plain_alerts,
584
    quic_set_first_handshake,
585
    quic_set_max_pipelines,
586
    NULL, /* set_in_init: Optional - we don't need it */
587
    quic_get_state,
588
    quic_set_options,
589
    quic_get_compression,
590
    quic_set_max_frag_len,
591
    quic_get_max_record_overhead, /* Never called */
592
    quic_increment_sequence_ctr, /* Never called */
593
    quic_alloc_buffers,
594
    quic_free_buffers
595
};
596
597
static int add_transport_params_cb(SSL *s, unsigned int ext_type,
598
                                   unsigned int context,
599
                                   const unsigned char **out, size_t *outlen,
600
                                   X509 *x, size_t chainidx, int *al,
601
                                   void *add_arg)
602
0
{
603
0
    QUIC_TLS *qtls = add_arg;
604
605
0
    *out = qtls->local_transport_params;
606
0
    *outlen = qtls->local_transport_params_len;
607
0
    return 1;
608
0
}
609
610
static void free_transport_params_cb(SSL *s, unsigned int ext_type,
611
                                     unsigned int context,
612
                                     const unsigned char *out,
613
                                     void *add_arg)
614
0
{
615
0
}
616
617
static int parse_transport_params_cb(SSL *s, unsigned int ext_type,
618
                                     unsigned int context,
619
                                     const unsigned char *in,
620
                                     size_t inlen, X509 *x,
621
                                     size_t chainidx,
622
                                     int *al, void *parse_arg)
623
0
{
624
0
    QUIC_TLS *qtls = parse_arg;
625
626
0
    return qtls->args.got_transport_params_cb(in, inlen,
627
0
                                              qtls->args.got_transport_params_cb_arg);
628
0
}
629
630
QUIC_TLS *ossl_quic_tls_new(const QUIC_TLS_ARGS *args)
631
0
{
632
0
    QUIC_TLS *qtls;
633
634
0
    if (args->crypto_send_cb == NULL
635
0
        || args->crypto_recv_rcd_cb == NULL
636
0
        || args->crypto_release_rcd_cb == NULL) {
637
0
        ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
638
0
        return NULL;
639
0
    }
640
641
0
    qtls = OPENSSL_zalloc(sizeof(*qtls));
642
0
    if (qtls == NULL)
643
0
        return NULL;
644
645
0
    if ((qtls->error_state = OSSL_ERR_STATE_new()) == NULL) {
646
0
        OPENSSL_free(qtls);
647
0
        return NULL;
648
0
    }
649
650
0
    qtls->args = *args;
651
0
    return qtls;
652
0
}
653
654
void ossl_quic_tls_free(QUIC_TLS *qtls)
655
0
{
656
0
    OSSL_ERR_STATE_free(qtls->error_state);
657
0
    OPENSSL_free(qtls);
658
0
}
659
660
static int raise_error(QUIC_TLS *qtls, uint64_t error_code,
661
                       const char *error_msg,
662
                       const char *src_file,
663
                       int src_line,
664
                       const char *src_func)
665
0
{
666
    /*
667
     * When QTLS fails, add a "cover letter" error with information, potentially
668
     * with any underlying libssl errors underneath it (but our cover error may
669
     * be the only error in some cases). Then capture this into an ERR_STATE so
670
     * we can report it later if need be when the QUIC_CHANNEL asks for it.
671
     */
672
0
    ERR_new();
673
0
    ERR_set_debug(src_file, src_line, src_func);
674
0
    ERR_set_error(ERR_LIB_SSL, SSL_R_QUIC_HANDSHAKE_LAYER_ERROR,
675
0
                  "handshake layer error, error code %llu (0x%llx) (\"%s\")",
676
0
                  error_code, error_code, error_msg);
677
0
    OSSL_ERR_STATE_save_to_mark(qtls->error_state);
678
679
    /*
680
     * We record the error information reported via the QUIC protocol
681
     * separately.
682
     */
683
0
    qtls->error_code        = error_code;
684
0
    qtls->error_msg         = error_msg;
685
0
    qtls->inerror           = 1;
686
687
0
    ERR_pop_to_mark();
688
0
    return 0;
689
0
}
690
691
#define RAISE_ERROR(qtls, error_code, error_msg) \
692
0
    raise_error((qtls), (error_code), (error_msg), \
693
0
                OPENSSL_FILE, OPENSSL_LINE, OPENSSL_FUNC)
694
695
#define RAISE_INTERNAL_ERROR(qtls) \
696
0
    RAISE_ERROR((qtls), QUIC_ERR_INTERNAL_ERROR, "internal error")
697
698
int ossl_quic_tls_tick(QUIC_TLS *qtls)
699
0
{
700
0
    int ret, err;
701
0
    const unsigned char *alpn;
702
0
    unsigned int alpnlen;
703
704
0
    if (qtls->inerror)
705
0
        return 0;
706
707
    /*
708
     * SSL_get_error does not truly know what the cause of an SSL_read failure
709
     * is and to some extent guesses based on contextual information. In
710
     * particular, if there is _any_ ERR on the error stack, SSL_ERROR_SSL or
711
     * SSL_ERROR_SYSCALL will be returned no matter what and there is no
712
     * possibility of SSL_ERROR_WANT_READ/WRITE being returned, even if that was
713
     * the actual cause of the SSL_read() failure.
714
     *
715
     * This means that ordinarily, the below code might not work right if the
716
     * application has any ERR on the error stack. In order to make this code
717
     * perform correctly regardless of prior ERR state, we use a variant of
718
     * SSL_get_error() which ignores the error stack. However, some ERRs are
719
     * raised by SSL_read() and actually indicate that something has gone wrong
720
     * during the call to SSL_read(). We therefore adopt a strategy of marking
721
     * the ERR stack and seeing if any errors get appended during the call to
722
     * SSL_read(). If they are, we assume SSL_read() has raised an error and
723
     * that we should use normal SSL_get_error() handling.
724
     *
725
     * NOTE: Ensure all escape paths from this function call
726
     * ERR_clear_to_mark(). The RAISE macros handle this in failure cases.
727
     */
728
0
    ERR_set_mark();
729
730
0
    if (!qtls->configured) {
731
0
        SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(qtls->args.s);
732
0
        SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(sc);
733
0
        BIO *nullbio;
734
735
        /*
736
         * No matter how the user has configured us, there are certain
737
         * requirements for QUIC-TLS that we enforce
738
         */
739
740
        /* ALPN is a requirement for QUIC and must be set */
741
0
        if (qtls->args.is_server) {
742
0
            if (sctx->ext.alpn_select_cb == NULL)
743
0
                return RAISE_INTERNAL_ERROR(qtls);
744
0
        } else {
745
0
            if (sc->ext.alpn == NULL || sc->ext.alpn_len == 0)
746
0
                return RAISE_ERROR(qtls, QUIC_ERR_CRYPTO_NO_APP_PROTO,
747
0
                                   "ALPN must be configured when using QUIC");
748
0
        }
749
0
        if (!SSL_set_min_proto_version(qtls->args.s, TLS1_3_VERSION))
750
0
            return RAISE_INTERNAL_ERROR(qtls);
751
752
0
        SSL_clear_options(qtls->args.s, SSL_OP_ENABLE_MIDDLEBOX_COMPAT);
753
0
        ossl_ssl_set_custom_record_layer(sc, &quic_tls_record_method, qtls);
754
755
0
        if (!ossl_tls_add_custom_ext_intern(NULL, &sc->cert->custext,
756
0
                                            qtls->args.is_server ? ENDPOINT_SERVER
757
0
                                                                 : ENDPOINT_CLIENT,
758
0
                                            TLSEXT_TYPE_quic_transport_parameters,
759
0
                                            SSL_EXT_TLS1_3_ONLY
760
0
                                            | SSL_EXT_CLIENT_HELLO
761
0
                                            | SSL_EXT_TLS1_3_ENCRYPTED_EXTENSIONS,
762
0
                                            add_transport_params_cb,
763
0
                                            free_transport_params_cb, qtls,
764
0
                                            parse_transport_params_cb, qtls))
765
0
            return RAISE_INTERNAL_ERROR(qtls);
766
767
0
        nullbio = BIO_new(BIO_s_null());
768
0
        if (nullbio == NULL)
769
0
            return RAISE_INTERNAL_ERROR(qtls);
770
771
        /*
772
         * Our custom record layer doesn't use the BIO - but libssl generally
773
         * expects one to be present.
774
         */
775
0
        SSL_set_bio(qtls->args.s, nullbio, nullbio);
776
777
0
        if (qtls->args.is_server)
778
0
            SSL_set_accept_state(qtls->args.s);
779
0
        else
780
0
            SSL_set_connect_state(qtls->args.s);
781
782
0
        qtls->configured = 1;
783
0
    }
784
785
0
    if (qtls->complete)
786
        /*
787
         * There should never be app data to read, but calling SSL_read() will
788
         * ensure any post-handshake messages are processed.
789
         */
790
0
        ret = SSL_read(qtls->args.s, NULL, 0);
791
0
    else
792
0
        ret = SSL_do_handshake(qtls->args.s);
793
794
0
    if (ret <= 0) {
795
0
        err = ossl_ssl_get_error(qtls->args.s, ret,
796
0
                                 /*check_err=*/ERR_count_to_mark() > 0);
797
798
0
        switch (err) {
799
0
        case SSL_ERROR_WANT_READ:
800
0
        case SSL_ERROR_WANT_WRITE:
801
0
        case SSL_ERROR_WANT_CLIENT_HELLO_CB:
802
0
        case SSL_ERROR_WANT_X509_LOOKUP:
803
0
        case SSL_ERROR_WANT_RETRY_VERIFY:
804
0
            ERR_pop_to_mark();
805
0
            return 1;
806
807
0
        default:
808
0
            return RAISE_INTERNAL_ERROR(qtls);
809
0
        }
810
0
    }
811
812
0
    if (!qtls->complete) {
813
        /* Validate that we have ALPN */
814
0
        SSL_get0_alpn_selected(qtls->args.s, &alpn, &alpnlen);
815
0
        if (alpn == NULL || alpnlen == 0)
816
0
            return RAISE_ERROR(qtls, QUIC_ERR_CRYPTO_NO_APP_PROTO,
817
0
                               "no application protocol negotiated");
818
819
0
        qtls->complete = 1;
820
0
        ERR_pop_to_mark();
821
0
        return qtls->args.handshake_complete_cb(qtls->args.handshake_complete_cb_arg);
822
0
    }
823
824
0
    ERR_pop_to_mark();
825
0
    return 1;
826
0
}
827
828
int ossl_quic_tls_set_transport_params(QUIC_TLS *qtls,
829
                                       const unsigned char *transport_params,
830
                                       size_t transport_params_len)
831
0
{
832
0
    qtls->local_transport_params       = transport_params;
833
0
    qtls->local_transport_params_len   = transport_params_len;
834
0
    return 1;
835
0
}
836
837
int ossl_quic_tls_get_error(QUIC_TLS *qtls,
838
                            uint64_t *error_code,
839
                            const char **error_msg,
840
                            ERR_STATE **error_state)
841
0
{
842
0
    if (qtls->inerror) {
843
0
        *error_code     = qtls->error_code;
844
0
        *error_msg      = qtls->error_msg;
845
0
        *error_state    = qtls->error_state;
846
0
    }
847
848
0
    return qtls->inerror;
849
0
}
850
851
/*
852
 * Returns true if the last handshake record message we processed was a
853
 * CertificateRequest
854
 */
855
int ossl_quic_tls_is_cert_request(QUIC_TLS *qtls)
856
0
{
857
0
    SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(qtls->args.s);
858
859
0
    return sc->s3.tmp.message_type == SSL3_MT_CERTIFICATE_REQUEST;
860
0
}
861
862
/*
863
 * Returns true if the last session associated with the connection has an
864
 * invalid max_early_data value for QUIC.
865
 */
866
int ossl_quic_tls_has_bad_max_early_data(QUIC_TLS *qtls)
867
0
{
868
0
    uint32_t max_early_data = SSL_get0_session(qtls->args.s)->ext.max_early_data;
869
870
    /*
871
     * If max_early_data was present we always ensure a non-zero value is
872
     * stored in the session for QUIC. Therefore if max_early_data == 0 here
873
     * we can be confident that it was not present in the NewSessionTicket
874
     */
875
0
    return max_early_data != 0xffffffff && max_early_data != 0;
876
0
}