Coverage Report

Created: 2025-12-31 06:58

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