Coverage Report

Created: 2026-04-12 07:08

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