Coverage Report

Created: 2026-10-28 06:28

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