Coverage Report

Created: 2025-12-31 06:58

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