Coverage Report

Created: 2026-10-28 06:28

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