Coverage Report

Created: 2023-04-12 06:22

/src/openssl/ssl/d1_lib.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 * Copyright 2005-2022 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (the "License").  You may not use
5
 * this file except in compliance with the License.  You can obtain a copy
6
 * in the file LICENSE in the source distribution or at
7
 * https://www.openssl.org/source/license.html
8
 */
9
10
#include "internal/e_os.h"
11
#include <stdio.h>
12
#include <openssl/objects.h>
13
#include <openssl/rand.h>
14
#include "ssl_local.h"
15
#include "internal/time.h"
16
17
static int dtls1_handshake_write(SSL_CONNECTION *s);
18
static size_t dtls1_link_min_mtu(void);
19
20
/* XDTLS:  figure out the right values */
21
static const size_t g_probable_mtu[] = { 1500, 512, 256 };
22
23
const SSL3_ENC_METHOD DTLSv1_enc_data = {
24
    tls1_setup_key_block,
25
    tls1_generate_master_secret,
26
    tls1_change_cipher_state,
27
    tls1_final_finish_mac,
28
    TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
29
    TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
30
    tls1_alert_code,
31
    tls1_export_keying_material,
32
    SSL_ENC_FLAG_DTLS | SSL_ENC_FLAG_EXPLICIT_IV,
33
    dtls1_set_handshake_header,
34
    dtls1_close_construct_packet,
35
    dtls1_handshake_write
36
};
37
38
const SSL3_ENC_METHOD DTLSv1_2_enc_data = {
39
    tls1_setup_key_block,
40
    tls1_generate_master_secret,
41
    tls1_change_cipher_state,
42
    tls1_final_finish_mac,
43
    TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
44
    TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
45
    tls1_alert_code,
46
    tls1_export_keying_material,
47
    SSL_ENC_FLAG_DTLS | SSL_ENC_FLAG_EXPLICIT_IV | SSL_ENC_FLAG_SIGALGS
48
        | SSL_ENC_FLAG_SHA256_PRF | SSL_ENC_FLAG_TLS1_2_CIPHERS,
49
    dtls1_set_handshake_header,
50
    dtls1_close_construct_packet,
51
    dtls1_handshake_write
52
};
53
54
OSSL_TIME dtls1_default_timeout(void)
55
0
{
56
    /*
57
     * 2 hours, the 24 hours mentioned in the DTLSv1 spec is way too long for
58
     * http, the cache would over fill
59
     */
60
0
    return ossl_seconds2time(60 * 60 * 2);
61
0
}
62
63
int dtls1_new(SSL *ssl)
64
0
{
65
0
    DTLS1_STATE *d1;
66
0
    SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
67
68
0
    if (s == NULL)
69
0
        return 0;
70
71
0
    if (!DTLS_RECORD_LAYER_new(&s->rlayer)) {
72
0
        return 0;
73
0
    }
74
75
0
    if (!ssl3_new(ssl))
76
0
        return 0;
77
0
    if ((d1 = OPENSSL_zalloc(sizeof(*d1))) == NULL) {
78
0
        ssl3_free(ssl);
79
0
        return 0;
80
0
    }
81
82
0
    d1->buffered_messages = pqueue_new();
83
0
    d1->sent_messages = pqueue_new();
84
85
0
    if (s->server) {
86
0
        d1->cookie_len = sizeof(s->d1->cookie);
87
0
    }
88
89
0
    d1->link_mtu = 0;
90
0
    d1->mtu = 0;
91
92
0
    if (d1->buffered_messages == NULL || d1->sent_messages == NULL) {
93
0
        pqueue_free(d1->buffered_messages);
94
0
        pqueue_free(d1->sent_messages);
95
0
        OPENSSL_free(d1);
96
0
        ssl3_free(ssl);
97
0
        return 0;
98
0
    }
99
100
0
    s->d1 = d1;
101
102
0
    if (!ssl->method->ssl_clear(ssl))
103
0
        return 0;
104
105
0
    return 1;
106
0
}
107
108
static void dtls1_clear_queues(SSL_CONNECTION *s)
109
0
{
110
0
    dtls1_clear_received_buffer(s);
111
0
    dtls1_clear_sent_buffer(s);
112
0
}
113
114
void dtls1_clear_received_buffer(SSL_CONNECTION *s)
115
0
{
116
0
    pitem *item = NULL;
117
0
    hm_fragment *frag = NULL;
118
119
0
    while ((item = pqueue_pop(s->d1->buffered_messages)) != NULL) {
120
0
        frag = (hm_fragment *)item->data;
121
0
        dtls1_hm_fragment_free(frag);
122
0
        pitem_free(item);
123
0
    }
124
0
}
125
126
void dtls1_clear_sent_buffer(SSL_CONNECTION *s)
127
0
{
128
0
    pitem *item = NULL;
129
0
    hm_fragment *frag = NULL;
130
131
0
    while ((item = pqueue_pop(s->d1->sent_messages)) != NULL) {
132
0
        frag = (hm_fragment *)item->data;
133
0
        dtls1_hm_fragment_free(frag);
134
0
        pitem_free(item);
135
0
    }
136
0
}
137
138
139
void dtls1_free(SSL *ssl)
140
0
{
141
0
    SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
142
143
0
    if (s == NULL)
144
0
        return;
145
146
0
    DTLS_RECORD_LAYER_free(&s->rlayer);
147
148
0
    ssl3_free(ssl);
149
150
0
    if (s->d1 != NULL) {
151
0
        dtls1_clear_queues(s);
152
0
        pqueue_free(s->d1->buffered_messages);
153
0
        pqueue_free(s->d1->sent_messages);
154
0
    }
155
156
0
    OPENSSL_free(s->d1);
157
0
    s->d1 = NULL;
158
0
}
159
160
int dtls1_clear(SSL *ssl)
161
0
{
162
0
    pqueue *buffered_messages;
163
0
    pqueue *sent_messages;
164
0
    size_t mtu;
165
0
    size_t link_mtu;
166
167
0
    SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
168
169
0
    if (s == NULL)
170
0
        return 0;
171
172
0
    DTLS_RECORD_LAYER_clear(&s->rlayer);
173
174
0
    if (s->d1) {
175
0
        DTLS_timer_cb timer_cb = s->d1->timer_cb;
176
177
0
        buffered_messages = s->d1->buffered_messages;
178
0
        sent_messages = s->d1->sent_messages;
179
0
        mtu = s->d1->mtu;
180
0
        link_mtu = s->d1->link_mtu;
181
182
0
        dtls1_clear_queues(s);
183
184
0
        memset(s->d1, 0, sizeof(*s->d1));
185
186
        /* Restore the timer callback from previous state */
187
0
        s->d1->timer_cb = timer_cb;
188
189
0
        if (s->server) {
190
0
            s->d1->cookie_len = sizeof(s->d1->cookie);
191
0
        }
192
193
0
        if (SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU) {
194
0
            s->d1->mtu = mtu;
195
0
            s->d1->link_mtu = link_mtu;
196
0
        }
197
198
0
        s->d1->buffered_messages = buffered_messages;
199
0
        s->d1->sent_messages = sent_messages;
200
0
    }
201
202
0
    if (!ssl3_clear(ssl))
203
0
        return 0;
204
205
0
    if (ssl->method->version == DTLS_ANY_VERSION)
206
0
        s->version = DTLS_MAX_VERSION_INTERNAL;
207
0
#ifndef OPENSSL_NO_DTLS1_METHOD
208
0
    else if (s->options & SSL_OP_CISCO_ANYCONNECT)
209
0
        s->client_version = s->version = DTLS1_BAD_VER;
210
0
#endif
211
0
    else
212
0
        s->version = ssl->method->version;
213
214
0
    return 1;
215
0
}
216
217
long dtls1_ctrl(SSL *ssl, int cmd, long larg, void *parg)
218
0
{
219
0
    int ret = 0;
220
0
    OSSL_TIME t;
221
0
    SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
222
223
0
    if (s == NULL)
224
0
        return 0;
225
226
0
    switch (cmd) {
227
0
    case DTLS_CTRL_GET_TIMEOUT:
228
0
        if (dtls1_get_timeout(s, &t) != NULL) {
229
0
            *(struct timeval *)parg = ossl_time_to_timeval(t);
230
0
            ret = 1;
231
0
        }
232
0
        break;
233
0
    case DTLS_CTRL_HANDLE_TIMEOUT:
234
0
        ret = dtls1_handle_timeout(s);
235
0
        break;
236
0
    case DTLS_CTRL_SET_LINK_MTU:
237
0
        if (larg < (long)dtls1_link_min_mtu())
238
0
            return 0;
239
0
        s->d1->link_mtu = larg;
240
0
        return 1;
241
0
    case DTLS_CTRL_GET_LINK_MIN_MTU:
242
0
        return (long)dtls1_link_min_mtu();
243
0
    case SSL_CTRL_SET_MTU:
244
        /*
245
         *  We may not have a BIO set yet so can't call dtls1_min_mtu()
246
         *  We'll have to make do with dtls1_link_min_mtu() and max overhead
247
         */
248
0
        if (larg < (long)dtls1_link_min_mtu() - DTLS1_MAX_MTU_OVERHEAD)
249
0
            return 0;
250
0
        s->d1->mtu = larg;
251
0
        return larg;
252
0
    default:
253
0
        ret = ssl3_ctrl(ssl, cmd, larg, parg);
254
0
        break;
255
0
    }
256
0
    return ret;
257
0
}
258
259
void dtls1_start_timer(SSL_CONNECTION *s)
260
0
{
261
0
    struct timeval tv;
262
0
    OSSL_TIME duration;
263
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
264
265
#ifndef OPENSSL_NO_SCTP
266
    /* Disable timer for SCTP */
267
    if (BIO_dgram_is_sctp(SSL_get_wbio(ssl))) {
268
        s->d1->next_timeout = ossl_time_zero();
269
        return;
270
    }
271
#endif
272
273
    /*
274
     * If timer is not set, initialize duration with 1 second or
275
     * a user-specified value if the timer callback is installed.
276
     */
277
0
    if (ossl_time_is_zero(s->d1->next_timeout)) {
278
0
        if (s->d1->timer_cb != NULL)
279
0
            s->d1->timeout_duration_us = s->d1->timer_cb(ssl, 0);
280
0
        else
281
0
            s->d1->timeout_duration_us = 1000000;
282
0
    }
283
284
    /* Set timeout to current time plus duration */
285
0
    duration = ossl_us2time(s->d1->timeout_duration_us);
286
0
    s->d1->next_timeout = ossl_time_add(ossl_time_now(), duration);
287
288
0
    tv = ossl_time_to_timeval(s->d1->next_timeout);
289
0
    BIO_ctrl(SSL_get_rbio(ssl), BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0, &tv);
290
0
}
291
292
OSSL_TIME *dtls1_get_timeout(SSL_CONNECTION *s, OSSL_TIME *timeleft)
293
0
{
294
0
    OSSL_TIME timenow;
295
296
    /* If no timeout is set, just return NULL */
297
0
    if (ossl_time_is_zero(s->d1->next_timeout))
298
0
        return NULL;
299
300
    /* Get current time */
301
0
    timenow = ossl_time_now();
302
303
    /*
304
     * If timer already expired or if remaining time is less than 15 ms,
305
     * set it to 0 to prevent issues because of small divergences with
306
     * socket timeouts.
307
     */
308
0
    *timeleft = ossl_time_subtract(s->d1->next_timeout, timenow);
309
0
    if (ossl_time_compare(*timeleft, ossl_ms2time(15)) <= 0)
310
0
        *timeleft = ossl_time_zero();
311
0
    return timeleft;
312
0
}
313
314
int dtls1_is_timer_expired(SSL_CONNECTION *s)
315
0
{
316
0
    OSSL_TIME timeleft;
317
318
    /* Get time left until timeout, return false if no timer running */
319
0
    if (dtls1_get_timeout(s, &timeleft) == NULL) {
320
0
        return 0;
321
0
    }
322
323
    /* Return false if timer is not expired yet */
324
0
    if (!ossl_time_is_zero(timeleft)) {
325
0
        return 0;
326
0
    }
327
328
    /* Timer expired, so return true */
329
0
    return 1;
330
0
}
331
332
static void dtls1_double_timeout(SSL_CONNECTION *s)
333
0
{
334
0
    s->d1->timeout_duration_us *= 2;
335
0
    if (s->d1->timeout_duration_us > 60000000)
336
0
        s->d1->timeout_duration_us = 60000000;
337
0
}
338
339
void dtls1_stop_timer(SSL_CONNECTION *s)
340
0
{
341
0
    struct timeval tv;
342
343
    /* Reset everything */
344
0
    s->d1->timeout_num_alerts = 0;
345
0
    s->d1->next_timeout = ossl_time_zero();
346
0
    s->d1->timeout_duration_us = 1000000;
347
0
    tv = ossl_time_to_timeval(s->d1->next_timeout);
348
0
    BIO_ctrl(s->rbio, BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0, &tv);
349
    /* Clear retransmission buffer */
350
0
    dtls1_clear_sent_buffer(s);
351
0
}
352
353
int dtls1_check_timeout_num(SSL_CONNECTION *s)
354
0
{
355
0
    size_t mtu;
356
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
357
358
0
    s->d1->timeout_num_alerts++;
359
360
    /* Reduce MTU after 2 unsuccessful retransmissions */
361
0
    if (s->d1->timeout_num_alerts > 2
362
0
        && !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
363
0
        mtu =
364
0
            BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_GET_FALLBACK_MTU, 0, NULL);
365
0
        if (mtu < s->d1->mtu)
366
0
            s->d1->mtu = mtu;
367
0
    }
368
369
0
    if (s->d1->timeout_num_alerts > DTLS1_TMO_ALERT_COUNT) {
370
        /* fail the connection, enough alerts have been sent */
371
0
        SSLfatal(s, SSL_AD_NO_ALERT, SSL_R_READ_TIMEOUT_EXPIRED);
372
0
        return -1;
373
0
    }
374
375
0
    return 0;
376
0
}
377
378
int dtls1_handle_timeout(SSL_CONNECTION *s)
379
0
{
380
    /* if no timer is expired, don't do anything */
381
0
    if (!dtls1_is_timer_expired(s)) {
382
0
        return 0;
383
0
    }
384
385
0
    if (s->d1->timer_cb != NULL)
386
0
        s->d1->timeout_duration_us = s->d1->timer_cb(SSL_CONNECTION_GET_SSL(s),
387
0
                                                     s->d1->timeout_duration_us);
388
0
    else
389
0
        dtls1_double_timeout(s);
390
391
0
    if (dtls1_check_timeout_num(s) < 0) {
392
        /* SSLfatal() already called */
393
0
        return -1;
394
0
    }
395
396
0
    dtls1_start_timer(s);
397
    /* Calls SSLfatal() if required */
398
0
    return dtls1_retransmit_buffered_messages(s);
399
0
}
400
401
0
#define LISTEN_SUCCESS              2
402
0
#define LISTEN_SEND_VERIFY_REQUEST  1
403
404
#ifndef OPENSSL_NO_SOCK
405
int DTLSv1_listen(SSL *ssl, BIO_ADDR *client)
406
0
{
407
0
    int next, n, ret = 0;
408
0
    unsigned char cookie[DTLS1_COOKIE_LENGTH];
409
0
    unsigned char seq[SEQ_NUM_SIZE];
410
0
    const unsigned char *data;
411
0
    unsigned char *buf = NULL, *wbuf;
412
0
    size_t fragoff, fraglen, msglen;
413
0
    unsigned int rectype, versmajor, msgseq, msgtype, clientvers, cookielen;
414
0
    BIO *rbio, *wbio;
415
0
    BIO_ADDR *tmpclient = NULL;
416
0
    PACKET pkt, msgpkt, msgpayload, session, cookiepkt;
417
0
    SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
418
419
0
    if (s == NULL)
420
0
        return -1;
421
422
0
    if (s->handshake_func == NULL) {
423
        /* Not properly initialized yet */
424
0
        SSL_set_accept_state(ssl);
425
0
    }
426
427
    /* Ensure there is no state left over from a previous invocation */
428
0
    if (!SSL_clear(ssl))
429
0
        return -1;
430
431
0
    ERR_clear_error();
432
433
0
    rbio = SSL_get_rbio(ssl);
434
0
    wbio = SSL_get_wbio(ssl);
435
436
0
    if (!rbio || !wbio) {
437
0
        ERR_raise(ERR_LIB_SSL, SSL_R_BIO_NOT_SET);
438
0
        return -1;
439
0
    }
440
441
    /*
442
     * Note: This check deliberately excludes DTLS1_BAD_VER because that version
443
     * requires the MAC to be calculated *including* the first ClientHello
444
     * (without the cookie). Since DTLSv1_listen is stateless that cannot be
445
     * supported. DTLS1_BAD_VER must use cookies in a stateful manner (e.g. via
446
     * SSL_accept)
447
     */
448
0
    if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00)) {
449
0
        ERR_raise(ERR_LIB_SSL, SSL_R_UNSUPPORTED_SSL_VERSION);
450
0
        return -1;
451
0
    }
452
453
0
    buf = OPENSSL_malloc(DTLS1_RT_HEADER_LENGTH + SSL3_RT_MAX_PLAIN_LENGTH);
454
0
    if (buf == NULL)
455
0
        return -1;
456
0
    wbuf = OPENSSL_malloc(DTLS1_RT_HEADER_LENGTH + SSL3_RT_MAX_PLAIN_LENGTH);
457
0
    if (wbuf == NULL) {
458
0
        OPENSSL_free(buf);
459
0
        return -1;
460
0
    }
461
462
0
    do {
463
        /* Get a packet */
464
465
0
        clear_sys_error();
466
0
        n = BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH
467
0
                                + DTLS1_RT_HEADER_LENGTH);
468
0
        if (n <= 0) {
469
0
            if (BIO_should_retry(rbio)) {
470
                /* Non-blocking IO */
471
0
                goto end;
472
0
            }
473
0
            ret = -1;
474
0
            goto end;
475
0
        }
476
477
0
        if (!PACKET_buf_init(&pkt, buf, n)) {
478
0
            ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
479
0
            ret = -1;
480
0
            goto end;
481
0
        }
482
483
        /*
484
         * Parse the received record. If there are any problems with it we just
485
         * dump it - with no alert. RFC6347 says this "Unlike TLS, DTLS is
486
         * resilient in the face of invalid records (e.g., invalid formatting,
487
         * length, MAC, etc.).  In general, invalid records SHOULD be silently
488
         * discarded, thus preserving the association; however, an error MAY be
489
         * logged for diagnostic purposes."
490
         */
491
492
        /* this packet contained a partial record, dump it */
493
0
        if (n < DTLS1_RT_HEADER_LENGTH) {
494
0
            ERR_raise(ERR_LIB_SSL, SSL_R_RECORD_TOO_SMALL);
495
0
            goto end;
496
0
        }
497
498
0
        if (s->msg_callback)
499
0
            s->msg_callback(0, 0, SSL3_RT_HEADER, buf,
500
0
                            DTLS1_RT_HEADER_LENGTH, ssl, s->msg_callback_arg);
501
502
        /* Get the record header */
503
0
        if (!PACKET_get_1(&pkt, &rectype)
504
0
            || !PACKET_get_1(&pkt, &versmajor)) {
505
0
            ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
506
0
            goto end;
507
0
        }
508
509
0
        if (rectype != SSL3_RT_HANDSHAKE) {
510
0
            ERR_raise(ERR_LIB_SSL, SSL_R_UNEXPECTED_MESSAGE);
511
0
            goto end;
512
0
        }
513
514
        /*
515
         * Check record version number. We only check that the major version is
516
         * the same.
517
         */
518
0
        if (versmajor != DTLS1_VERSION_MAJOR) {
519
0
            ERR_raise(ERR_LIB_SSL, SSL_R_BAD_PROTOCOL_VERSION_NUMBER);
520
0
            goto end;
521
0
        }
522
523
0
        if (!PACKET_forward(&pkt, 1)
524
            /* Save the sequence number: 64 bits, with top 2 bytes = epoch */
525
0
            || !PACKET_copy_bytes(&pkt, seq, SEQ_NUM_SIZE)
526
0
            || !PACKET_get_length_prefixed_2(&pkt, &msgpkt)) {
527
0
            ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
528
0
            goto end;
529
0
        }
530
        /*
531
         * We allow data remaining at the end of the packet because there could
532
         * be a second record (but we ignore it)
533
         */
534
535
        /* This is an initial ClientHello so the epoch has to be 0 */
536
0
        if (seq[0] != 0 || seq[1] != 0) {
537
0
            ERR_raise(ERR_LIB_SSL, SSL_R_UNEXPECTED_MESSAGE);
538
0
            goto end;
539
0
        }
540
541
        /* Get a pointer to the raw message for the later callback */
542
0
        data = PACKET_data(&msgpkt);
543
544
        /* Finished processing the record header, now process the message */
545
0
        if (!PACKET_get_1(&msgpkt, &msgtype)
546
0
            || !PACKET_get_net_3_len(&msgpkt, &msglen)
547
0
            || !PACKET_get_net_2(&msgpkt, &msgseq)
548
0
            || !PACKET_get_net_3_len(&msgpkt, &fragoff)
549
0
            || !PACKET_get_net_3_len(&msgpkt, &fraglen)
550
0
            || !PACKET_get_sub_packet(&msgpkt, &msgpayload, fraglen)
551
0
            || PACKET_remaining(&msgpkt) != 0) {
552
0
            ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
553
0
            goto end;
554
0
        }
555
556
0
        if (msgtype != SSL3_MT_CLIENT_HELLO) {
557
0
            ERR_raise(ERR_LIB_SSL, SSL_R_UNEXPECTED_MESSAGE);
558
0
            goto end;
559
0
        }
560
561
        /* Message sequence number can only be 0 or 1 */
562
0
        if (msgseq > 2) {
563
0
            ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_SEQUENCE_NUMBER);
564
0
            goto end;
565
0
        }
566
567
        /*
568
         * We don't support fragment reassembly for ClientHellos whilst
569
         * listening because that would require server side state (which is
570
         * against the whole point of the ClientHello/HelloVerifyRequest
571
         * mechanism). Instead we only look at the first ClientHello fragment
572
         * and require that the cookie must be contained within it.
573
         */
574
0
        if (fragoff != 0 || fraglen > msglen) {
575
            /* Non initial ClientHello fragment (or bad fragment) */
576
0
            ERR_raise(ERR_LIB_SSL, SSL_R_FRAGMENTED_CLIENT_HELLO);
577
0
            goto end;
578
0
        }
579
580
0
        if (s->msg_callback)
581
0
            s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, data,
582
0
                            fraglen + DTLS1_HM_HEADER_LENGTH, ssl,
583
0
                            s->msg_callback_arg);
584
585
0
        if (!PACKET_get_net_2(&msgpayload, &clientvers)) {
586
0
            ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
587
0
            goto end;
588
0
        }
589
590
        /*
591
         * Verify client version is supported
592
         */
593
0
        if (DTLS_VERSION_LT(clientvers, (unsigned int)ssl->method->version) &&
594
0
            ssl->method->version != DTLS_ANY_VERSION) {
595
0
            ERR_raise(ERR_LIB_SSL, SSL_R_WRONG_VERSION_NUMBER);
596
0
            goto end;
597
0
        }
598
599
0
        if (!PACKET_forward(&msgpayload, SSL3_RANDOM_SIZE)
600
0
            || !PACKET_get_length_prefixed_1(&msgpayload, &session)
601
0
            || !PACKET_get_length_prefixed_1(&msgpayload, &cookiepkt)) {
602
            /*
603
             * Could be malformed or the cookie does not fit within the initial
604
             * ClientHello fragment. Either way we can't handle it.
605
             */
606
0
            ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
607
0
            goto end;
608
0
        }
609
610
        /*
611
         * Check if we have a cookie or not. If not we need to send a
612
         * HelloVerifyRequest.
613
         */
614
0
        if (PACKET_remaining(&cookiepkt) == 0) {
615
0
            next = LISTEN_SEND_VERIFY_REQUEST;
616
0
        } else {
617
            /*
618
             * We have a cookie, so lets check it.
619
             */
620
0
            if (ssl->ctx->app_verify_cookie_cb == NULL) {
621
0
                ERR_raise(ERR_LIB_SSL, SSL_R_NO_VERIFY_COOKIE_CALLBACK);
622
                /* This is fatal */
623
0
                ret = -1;
624
0
                goto end;
625
0
            }
626
0
            if (ssl->ctx->app_verify_cookie_cb(ssl, PACKET_data(&cookiepkt),
627
0
                    (unsigned int)PACKET_remaining(&cookiepkt)) == 0) {
628
                /*
629
                 * We treat invalid cookies in the same was as no cookie as
630
                 * per RFC6347
631
                 */
632
0
                next = LISTEN_SEND_VERIFY_REQUEST;
633
0
            } else {
634
                /* Cookie verification succeeded */
635
0
                next = LISTEN_SUCCESS;
636
0
            }
637
0
        }
638
639
0
        if (next == LISTEN_SEND_VERIFY_REQUEST) {
640
0
            WPACKET wpkt;
641
0
            unsigned int version;
642
0
            size_t wreclen;
643
644
            /*
645
             * There was no cookie in the ClientHello so we need to send a
646
             * HelloVerifyRequest. If this fails we do not worry about trying
647
             * to resend, we just drop it.
648
             */
649
650
            /* Generate the cookie */
651
0
            if (ssl->ctx->app_gen_cookie_cb == NULL ||
652
0
                ssl->ctx->app_gen_cookie_cb(ssl, cookie, &cookielen) == 0 ||
653
0
                cookielen > 255) {
654
0
                ERR_raise(ERR_LIB_SSL, SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
655
                /* This is fatal */
656
0
                ret = -1;
657
0
                goto end;
658
0
            }
659
660
            /*
661
             * Special case: for hello verify request, client version 1.0 and we
662
             * haven't decided which version to use yet send back using version
663
             * 1.0 header: otherwise some clients will ignore it.
664
             */
665
0
            version = (ssl->method->version == DTLS_ANY_VERSION) ? DTLS1_VERSION
666
0
                                                                 : s->version;
667
668
            /* Construct the record and message headers */
669
0
            if (!WPACKET_init_static_len(&wpkt,
670
0
                                         wbuf,
671
0
                                         ssl_get_max_send_fragment(s)
672
0
                                         + DTLS1_RT_HEADER_LENGTH,
673
0
                                         0)
674
0
                    || !WPACKET_put_bytes_u8(&wpkt, SSL3_RT_HANDSHAKE)
675
0
                    || !WPACKET_put_bytes_u16(&wpkt, version)
676
                       /*
677
                        * Record sequence number is always the same as in the
678
                        * received ClientHello
679
                        */
680
0
                    || !WPACKET_memcpy(&wpkt, seq, SEQ_NUM_SIZE)
681
                       /* End of record, start sub packet for message */
682
0
                    || !WPACKET_start_sub_packet_u16(&wpkt)
683
                       /* Message type */
684
0
                    || !WPACKET_put_bytes_u8(&wpkt,
685
0
                                             DTLS1_MT_HELLO_VERIFY_REQUEST)
686
                       /*
687
                        * Message length - doesn't follow normal TLS convention:
688
                        * the length isn't the last thing in the message header.
689
                        * We'll need to fill this in later when we know the
690
                        * length. Set it to zero for now
691
                        */
692
0
                    || !WPACKET_put_bytes_u24(&wpkt, 0)
693
                       /*
694
                        * Message sequence number is always 0 for a
695
                        * HelloVerifyRequest
696
                        */
697
0
                    || !WPACKET_put_bytes_u16(&wpkt, 0)
698
                       /*
699
                        * We never fragment a HelloVerifyRequest, so fragment
700
                        * offset is 0
701
                        */
702
0
                    || !WPACKET_put_bytes_u24(&wpkt, 0)
703
                       /*
704
                        * Fragment length is the same as message length, but
705
                        * this *is* the last thing in the message header so we
706
                        * can just start a sub-packet. No need to come back
707
                        * later for this one.
708
                        */
709
0
                    || !WPACKET_start_sub_packet_u24(&wpkt)
710
                       /* Create the actual HelloVerifyRequest body */
711
0
                    || !dtls_raw_hello_verify_request(&wpkt, cookie, cookielen)
712
                       /* Close message body */
713
0
                    || !WPACKET_close(&wpkt)
714
                       /* Close record body */
715
0
                    || !WPACKET_close(&wpkt)
716
0
                    || !WPACKET_get_total_written(&wpkt, &wreclen)
717
0
                    || !WPACKET_finish(&wpkt)) {
718
0
                ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
719
0
                WPACKET_cleanup(&wpkt);
720
                /* This is fatal */
721
0
                ret = -1;
722
0
                goto end;
723
0
            }
724
725
            /*
726
             * Fix up the message len in the message header. Its the same as the
727
             * fragment len which has been filled in by WPACKET, so just copy
728
             * that. Destination for the message len is after the record header
729
             * plus one byte for the message content type. The source is the
730
             * last 3 bytes of the message header
731
             */
732
0
            memcpy(&wbuf[DTLS1_RT_HEADER_LENGTH + 1],
733
0
                   &wbuf[DTLS1_RT_HEADER_LENGTH + DTLS1_HM_HEADER_LENGTH - 3],
734
0
                   3);
735
736
0
            if (s->msg_callback)
737
0
                s->msg_callback(1, 0, SSL3_RT_HEADER, buf,
738
0
                                DTLS1_RT_HEADER_LENGTH, ssl,
739
0
                                s->msg_callback_arg);
740
741
0
            if ((tmpclient = BIO_ADDR_new()) == NULL) {
742
0
                ERR_raise(ERR_LIB_SSL, ERR_R_BIO_LIB);
743
0
                goto end;
744
0
            }
745
746
            /*
747
             * This is unnecessary if rbio and wbio are one and the same - but
748
             * maybe they're not. We ignore errors here - some BIOs do not
749
             * support this.
750
             */
751
0
            if (BIO_dgram_get_peer(rbio, tmpclient) > 0) {
752
0
                (void)BIO_dgram_set_peer(wbio, tmpclient);
753
0
            }
754
0
            BIO_ADDR_free(tmpclient);
755
0
            tmpclient = NULL;
756
757
0
            if (BIO_write(wbio, wbuf, wreclen) < (int)wreclen) {
758
0
                if (BIO_should_retry(wbio)) {
759
                    /*
760
                     * Non-blocking IO...but we're stateless, so we're just
761
                     * going to drop this packet.
762
                     */
763
0
                    goto end;
764
0
                }
765
0
                ret = -1;
766
0
                goto end;
767
0
            }
768
769
0
            if (BIO_flush(wbio) <= 0) {
770
0
                if (BIO_should_retry(wbio)) {
771
                    /*
772
                     * Non-blocking IO...but we're stateless, so we're just
773
                     * going to drop this packet.
774
                     */
775
0
                    goto end;
776
0
                }
777
0
                ret = -1;
778
0
                goto end;
779
0
            }
780
0
        }
781
0
    } while (next != LISTEN_SUCCESS);
782
783
    /*
784
     * Set expected sequence numbers to continue the handshake.
785
     */
786
0
    s->d1->handshake_read_seq = 1;
787
0
    s->d1->handshake_write_seq = 1;
788
0
    s->d1->next_handshake_write_seq = 1;
789
0
    s->rlayer.wrlmethod->increment_sequence_ctr(s->rlayer.wrl);
790
791
    /*
792
     * We are doing cookie exchange, so make sure we set that option in the
793
     * SSL object
794
     */
795
0
    SSL_set_options(ssl, SSL_OP_COOKIE_EXCHANGE);
796
797
    /*
798
     * Tell the state machine that we've done the initial hello verify
799
     * exchange
800
     */
801
0
    ossl_statem_set_hello_verify_done(s);
802
803
    /*
804
     * Some BIOs may not support this. If we fail we clear the client address
805
     */
806
0
    if (BIO_dgram_get_peer(rbio, client) <= 0)
807
0
        BIO_ADDR_clear(client);
808
809
    /* Buffer the record for use by the record layer */
810
0
    if (BIO_write(s->rlayer.rrlnext, buf, n) != n) {
811
0
        ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
812
0
        ret = -1;
813
0
        goto end;
814
0
    }
815
816
    /*
817
     * Reset the record layer - but this time we can use the record we just
818
     * buffered in s->rlayer.rrlnext
819
     */
820
0
    if (!ssl_set_new_record_layer(s,
821
0
                                  DTLS_ANY_VERSION,
822
0
                                  OSSL_RECORD_DIRECTION_READ,
823
0
                                  OSSL_RECORD_PROTECTION_LEVEL_NONE, NULL, 0,
824
0
                                  NULL, 0, NULL, 0, NULL,  0, NULL, 0,
825
0
                                  NID_undef, NULL, NULL, NULL)) {
826
        /* SSLfatal already called */
827
0
        ret = -1;
828
0
        goto end;
829
0
    }
830
831
0
    ret = 1;
832
0
 end:
833
0
    BIO_ADDR_free(tmpclient);
834
0
    OPENSSL_free(buf);
835
0
    OPENSSL_free(wbuf);
836
0
    return ret;
837
0
}
838
#endif
839
840
static int dtls1_handshake_write(SSL_CONNECTION *s)
841
0
{
842
0
    return dtls1_do_write(s, SSL3_RT_HANDSHAKE);
843
0
}
844
845
int dtls1_shutdown(SSL *s)
846
0
{
847
0
    int ret;
848
#ifndef OPENSSL_NO_SCTP
849
    BIO *wbio;
850
    SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
851
852
    if (s == NULL)
853
        return -1;
854
855
    wbio = SSL_get_wbio(s);
856
    if (wbio != NULL && BIO_dgram_is_sctp(wbio) &&
857
        !(sc->shutdown & SSL_SENT_SHUTDOWN)) {
858
        ret = BIO_dgram_sctp_wait_for_dry(wbio);
859
        if (ret < 0)
860
            return -1;
861
862
        if (ret == 0)
863
            BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 1,
864
                     NULL);
865
    }
866
#endif
867
0
    ret = ssl3_shutdown(s);
868
#ifndef OPENSSL_NO_SCTP
869
    BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 0, NULL);
870
#endif
871
0
    return ret;
872
0
}
873
874
int dtls1_query_mtu(SSL_CONNECTION *s)
875
0
{
876
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
877
878
0
    if (s->d1->link_mtu) {
879
0
        s->d1->mtu =
880
0
            s->d1->link_mtu - BIO_dgram_get_mtu_overhead(SSL_get_wbio(ssl));
881
0
        s->d1->link_mtu = 0;
882
0
    }
883
884
    /* AHA!  Figure out the MTU, and stick to the right size */
885
0
    if (s->d1->mtu < dtls1_min_mtu(s)) {
886
0
        if (!(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
887
0
            s->d1->mtu =
888
0
                BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
889
890
            /*
891
             * I've seen the kernel return bogus numbers when it doesn't know
892
             * (initial write), so just make sure we have a reasonable number
893
             */
894
0
            if (s->d1->mtu < dtls1_min_mtu(s)) {
895
                /* Set to min mtu */
896
0
                s->d1->mtu = dtls1_min_mtu(s);
897
0
                BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SET_MTU,
898
0
                         (long)s->d1->mtu, NULL);
899
0
            }
900
0
        } else
901
0
            return 0;
902
0
    }
903
0
    return 1;
904
0
}
905
906
static size_t dtls1_link_min_mtu(void)
907
0
{
908
0
    return (g_probable_mtu[(sizeof(g_probable_mtu) /
909
0
                            sizeof(g_probable_mtu[0])) - 1]);
910
0
}
911
912
size_t dtls1_min_mtu(SSL_CONNECTION *s)
913
0
{
914
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
915
916
0
    return dtls1_link_min_mtu() - BIO_dgram_get_mtu_overhead(SSL_get_wbio(ssl));
917
0
}
918
919
size_t DTLS_get_data_mtu(const SSL *ssl)
920
0
{
921
0
    size_t mac_overhead, int_overhead, blocksize, ext_overhead;
922
0
    const SSL_CIPHER *ciph = SSL_get_current_cipher(ssl);
923
0
    size_t mtu;
924
0
    const SSL_CONNECTION *s = SSL_CONNECTION_FROM_CONST_SSL_ONLY(ssl);
925
926
0
    if (s == NULL)
927
0
        return 0;
928
929
0
    mtu = s->d1->mtu;
930
931
0
    if (ciph == NULL)
932
0
        return 0;
933
934
0
    if (!ssl_cipher_get_overhead(ciph, &mac_overhead, &int_overhead,
935
0
                                 &blocksize, &ext_overhead))
936
0
        return 0;
937
938
0
    if (SSL_READ_ETM(s))
939
0
        ext_overhead += mac_overhead;
940
0
    else
941
0
        int_overhead += mac_overhead;
942
943
    /* Subtract external overhead (e.g. IV/nonce, separate MAC) */
944
0
    if (ext_overhead + DTLS1_RT_HEADER_LENGTH >= mtu)
945
0
        return 0;
946
0
    mtu -= ext_overhead + DTLS1_RT_HEADER_LENGTH;
947
948
    /* Round encrypted payload down to cipher block size (for CBC etc.)
949
     * No check for overflow since 'mtu % blocksize' cannot exceed mtu. */
950
0
    if (blocksize)
951
0
        mtu -= (mtu % blocksize);
952
953
    /* Subtract internal overhead (e.g. CBC padding len byte) */
954
0
    if (int_overhead >= mtu)
955
0
        return 0;
956
0
    mtu -= int_overhead;
957
958
0
    return mtu;
959
0
}
960
961
void DTLS_set_timer_cb(SSL *ssl, DTLS_timer_cb cb)
962
0
{
963
0
    SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
964
965
0
    if (s == NULL)
966
0
        return;
967
968
0
    s->d1->timer_cb = cb;
969
0
}