Coverage Report

Created: 2026-10-28 06:28

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