Coverage Report

Created: 2025-06-13 06:57

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