Coverage Report

Created: 2026-10-28 06:28

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl41/ssl/d1_lib.c
Line
Count
Source
1
/*
2
 * Copyright 2005-2026 The OpenSSL Project Authors. All Rights Reserved.
3
 *
4
 * Licensed under the Apache License 2.0 (the "License").  You may not use
5
 * this file except in compliance with the License.  You can obtain a copy
6
 * in the file LICENSE in the source distribution or at
7
 * https://www.openssl.org/source/license.html
8
 */
9
10
#include "internal/e_os.h"
11
#include "internal/e_winsock.h" /* struct timeval for DTLS_CTRL_GET_TIMEOUT */
12
#include <stdio.h>
13
#include <openssl/objects.h>
14
#include <openssl/rand.h>
15
#include <openssl/evp.h>
16
#include <openssl/core_names.h>
17
#include "ssl_local.h"
18
#include "internal/time.h"
19
#include "internal/ssl_unwrap.h"
20
#include "internal/hashfunc.h"
21
#include "internal/dtls_record_rx.h"
22
#include "internal/dgram_demux.h"
23
#include "internal/dgram_conn_lookup.h"
24
#include "internal/rio_notifier.h"
25
26
static int dtls1_handshake_write(SSL_CONNECTION *s);
27
static const size_t dtls1_link_min_mtu = 256;
28
#ifndef OPENSSL_NO_DTLS
29
static OSSL_TIME dtls_listener_get_time_direct(DTLS_LISTENER *dl);
30
#endif
31
32
const SSL3_ENC_METHOD DTLSv1_enc_data = {
33
    tls1_setup_key_block,
34
    tls1_generate_master_secret,
35
    tls1_change_cipher_state,
36
    tls1_final_finish_mac,
37
    TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
38
    TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
39
    tls1_alert_code,
40
    tls1_export_keying_material,
41
    SSL_ENC_FLAG_DTLS,
42
    dtls1_set_handshake_header,
43
    dtls1_close_construct_packet,
44
    dtls1_handshake_write
45
};
46
47
const SSL3_ENC_METHOD DTLSv1_2_enc_data = {
48
    tls1_setup_key_block,
49
    tls1_generate_master_secret,
50
    tls1_change_cipher_state,
51
    tls1_final_finish_mac,
52
    TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
53
    TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
54
    tls1_alert_code,
55
    tls1_export_keying_material,
56
    SSL_ENC_FLAG_DTLS | SSL_ENC_FLAG_SIGALGS
57
        | SSL_ENC_FLAG_SHA256_PRF | SSL_ENC_FLAG_TLS1_2_CIPHERS,
58
    dtls1_set_handshake_header,
59
    dtls1_close_construct_packet,
60
    dtls1_handshake_write
61
};
62
63
const SSL3_ENC_METHOD DTLSv1_3_enc_data = {
64
    tls13_setup_key_block,
65
    tls13_generate_master_secret,
66
    tls13_change_cipher_state,
67
    tls13_final_finish_mac,
68
    TLS_MD_CLIENT_FINISH_CONST, TLS_MD_CLIENT_FINISH_CONST_SIZE,
69
    TLS_MD_SERVER_FINISH_CONST, TLS_MD_SERVER_FINISH_CONST_SIZE,
70
    tls13_alert_code,
71
    tls13_export_keying_material,
72
    SSL_ENC_FLAG_DTLS | SSL_ENC_FLAG_SIGALGS | SSL_ENC_FLAG_SHA256_PRF,
73
    dtls1_set_handshake_header,
74
    dtls1_close_construct_packet,
75
    dtls1_handshake_write
76
};
77
78
OSSL_TIME dtls1_default_timeout(void)
79
54.7k
{
80
    /*
81
     * 2 hours, the 24 hours mentioned in the DTLSv1 spec is way too long for
82
     * http, the cache would over fill
83
     */
84
54.7k
    return ossl_seconds2time(60 * 60 * 2);
85
54.7k
}
86
87
int dtls1_new(SSL *ssl)
88
21.1k
{
89
21.1k
    DTLS1_STATE *d1;
90
21.1k
    SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
91
92
21.1k
    if (s == NULL)
93
0
        return 0;
94
95
21.1k
    if (!DTLS_RECORD_LAYER_new(&s->rlayer)) {
96
0
        return 0;
97
0
    }
98
99
21.1k
    if (!ssl3_new(ssl))
100
0
        return 0;
101
21.1k
    if ((d1 = OPENSSL_zalloc(sizeof(*d1))) == NULL) {
102
0
        ssl3_free(ssl);
103
0
        return 0;
104
0
    }
105
106
21.1k
    d1->hello_verify_request = SSL_HVR_NONE;
107
108
21.1k
    s->d1 = d1;
109
110
21.1k
    if (!ssl->method->ssl_clear(ssl))
111
0
        return 0;
112
113
21.1k
    return 1;
114
21.1k
}
115
116
static void dtls1_clear_queues(SSL_CONNECTION *s)
117
218k
{
118
218k
    dtls1_clear_received_buffer(s);
119
218k
    dtls1_clear_sent_buffer(s, 0);
120
218k
    ossl_list_record_number_elem_free(&s->d1->ack_rec_num);
121
218k
}
122
123
void dtls1_clear_received_buffer(SSL_CONNECTION *s)
124
231k
{
125
231k
    pitem *item = NULL;
126
231k
    hm_fragment *frag = NULL;
127
231k
    pqueue *rcvd_messages = &s->d1->rcvd_messages;
128
129
239k
    while ((item = pqueue_pop(rcvd_messages)) != NULL) {
130
7.66k
        frag = (hm_fragment *)item->data;
131
7.66k
        dtls1_hm_fragment_free(frag);
132
7.66k
        pitem_free(item);
133
7.66k
    }
134
231k
    s->d1->has_change_cipher_spec = 0;
135
231k
}
136
137
/*
138
 * Called once the DTLS 1.3 hellos are done. Our handshake read keys are only
139
 * installed when the peer's first epoch 2 record arrives (dtls1_read_bytes()),
140
 * so until then nothing but a plaintext alert may be read. Anything already
141
 * reassembled or buffered arrived unprotected, so discard it.
142
 */
143
void dtls13_hellos_done(SSL_CONNECTION *s)
144
306
{
145
306
    s->dtls13_process_hello = 1;
146
306
    dtls1_clear_received_buffer(s);
147
306
    if (s->rlayer.rrlmethod->set_plain_alerts != NULL)
148
306
        s->rlayer.rrlmethod->set_plain_alerts(s->rlayer.rrl, 1);
149
306
}
150
151
void ossl_list_record_number_elem_free(OSSL_LIST(record_number) *p_list)
152
129k
{
153
129k
    DTLS1_RECORD_NUMBER *p_elem;
154
129k
    DTLS1_RECORD_NUMBER *p_elem_next = NULL;
155
156
129k
    if (p_list != NULL)
157
129k
        p_elem_next = ossl_list_record_number_head(p_list);
158
159
129k
    while ((p_elem = p_elem_next) != NULL) {
160
278
        p_elem_next = ossl_list_record_number_next(p_elem_next);
161
278
        ossl_list_record_number_remove(p_list, p_elem);
162
278
        OPENSSL_free(p_elem);
163
278
    }
164
129k
}
165
166
DTLS1_RECORD_NUMBER *dtls1_record_number_new(uint64_t epoch, uint64_t seqnum,
167
    size_t frag_off, size_t frag_len)
168
278
{
169
278
    DTLS1_RECORD_NUMBER *recnum = OPENSSL_zalloc(sizeof(*recnum));
170
171
278
    if (recnum != NULL) {
172
278
        recnum->epoch = epoch;
173
278
        recnum->seqnum = seqnum;
174
278
        recnum->frag_off = frag_off;
175
278
        recnum->frag_len = frag_len;
176
278
    }
177
178
278
    return recnum;
179
278
}
180
181
void dtls1_acknowledge_sent_buffer(SSL_CONNECTION *s, uint64_t before_epoch)
182
0
{
183
0
    pitem *item = NULL;
184
0
    piterator iter = pqueue_iterator(&s->d1->sent_messages);
185
186
0
    while ((item = pqueue_next(&iter)) != NULL) {
187
0
        dtls_sent_msg *sent_msg = (dtls_sent_msg *)item->data;
188
0
        DTLS1_RECORD_NUMBER *recnum;
189
0
        DTLS1_RECORD_NUMBER *recnum_next = ossl_list_record_number_head(&sent_msg->rec_nums);
190
191
0
        while ((recnum = recnum_next) != NULL) {
192
0
            recnum_next = ossl_list_record_number_next(recnum_next);
193
194
0
            if (recnum->epoch < before_epoch) {
195
0
                ossl_list_record_number_remove(&sent_msg->rec_nums, recnum);
196
0
                OPENSSL_free(recnum);
197
0
            }
198
0
        }
199
0
    }
200
0
}
201
202
void dtls1_clear_sent_buffer(SSL_CONNECTION *s, int keep_unacked_msgs)
203
96.7k
{
204
96.7k
    pitem *item = NULL;
205
96.7k
    pqueue *remaining_sent_messages = pqueue_new();
206
96.7k
    pqueue *sent_messages = &s->d1->sent_messages;
207
208
141k
    while ((item = pqueue_pop(sent_messages)) != NULL) {
209
45.0k
        dtls_sent_msg *sent_msg = (dtls_sent_msg *)item->data;
210
45.0k
        unsigned char msg_type = sent_msg->msg_info.msg_type;
211
45.0k
        unsigned char record_type = sent_msg->msg_info.record_type;
212
213
45.0k
        if (SSL_CONNECTION_IS_DTLS13(s)
214
344
            && !ossl_list_record_number_is_empty(&sent_msg->rec_nums)
215
0
            && keep_unacked_msgs) {
216
0
            pqueue_insert(remaining_sent_messages, item);
217
0
            continue;
218
0
        }
219
220
45.0k
        if (((!SSL_CONNECTION_IS_DTLS13(s) && record_type == SSL3_RT_CHANGE_CIPHER_SPEC)
221
41.2k
                || (SSL_CONNECTION_IS_DTLS13(s)
222
344
                    && (msg_type == SSL3_MT_FINISHED
223
344
                        || msg_type == SSL3_MT_SERVER_HELLO
224
344
                        || msg_type == SSL3_MT_KEY_UPDATE)))
225
3.80k
            && sent_msg->saved_retransmit_state.wrlmethod != NULL
226
3.80k
            && s->rlayer.wrl != sent_msg->saved_retransmit_state.wrl) {
227
            /*
228
             * If we're freeing the CCS then we're done with the old wrl and it
229
             * can bee freed
230
             */
231
3.80k
            sent_msg->saved_retransmit_state.wrlmethod->free(sent_msg->saved_retransmit_state.wrl);
232
3.80k
        }
233
234
45.0k
        dtls1_sent_msg_free(sent_msg);
235
45.0k
        pitem_free(item);
236
45.0k
    }
237
238
96.7k
    if (SSL_CONNECTION_IS_DTLS13(s))
239
912
        while ((item = pqueue_pop(remaining_sent_messages)) != NULL)
240
0
            pqueue_insert(&s->d1->sent_messages, item);
241
242
96.7k
    pqueue_free(remaining_sent_messages);
243
96.7k
}
244
245
/*
246
 * Before RECORD_LAYER_clear() frees s->rlayer.wrl, null out any
247
 * saved_retransmit_state.wrl pointers in the sent_messages queue that
248
 * reference it.  This transfers ownership of that free exclusively to
249
 * RECORD_LAYER_clear and prevents dtls1_clear_sent_buffer from freeing
250
 * the same pointer a second time.  Entries with a different (older) wrl
251
 * pointer are left untouched and will be freed correctly later.
252
 */
253
void dtls1_clear_current_wrl_from_sent_buffer(SSL_CONNECTION *s)
254
21.1k
{
255
21.1k
    pitem *item;
256
21.1k
    piterator iter = pqueue_iterator(&s->d1->sent_messages);
257
258
59.6k
    while ((item = pqueue_next(&iter)) != NULL) {
259
38.5k
        dtls_sent_msg *sent_msg = (dtls_sent_msg *)item->data;
260
261
38.5k
        if (sent_msg->saved_retransmit_state.wrl == s->rlayer.wrl) {
262
30.9k
            sent_msg->saved_retransmit_state.wrl = NULL;
263
30.9k
            sent_msg->saved_retransmit_state.wrlmethod = NULL;
264
30.9k
        }
265
38.5k
    }
266
21.1k
}
267
268
int dtls_any_sent_messages_are_missing_acknowledge(SSL_CONNECTION *s)
269
0
{
270
0
    pitem *item;
271
0
    piterator iter = pqueue_iterator(&s->d1->sent_messages);
272
273
0
    while ((item = pqueue_next(&iter)) != NULL) {
274
0
        dtls_sent_msg *msg = (dtls_sent_msg *)item->data;
275
276
0
        if (!ossl_list_record_number_is_empty(&msg->rec_nums))
277
0
            return 1;
278
0
    }
279
280
0
    return 0;
281
0
}
282
283
void dtls1_free(SSL *ssl)
284
21.1k
{
285
21.1k
    SSL_CONNECTION *s;
286
287
21.1k
#ifndef OPENSSL_NO_DTLS
288
21.1k
    if (IS_DTLS_LISTENER(ssl)) {
289
0
        ossl_dtls_listener_free(ssl);
290
0
        return;
291
0
    }
292
21.1k
#endif
293
294
21.1k
    s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
295
296
21.1k
    if (s == NULL)
297
0
        return;
298
299
21.1k
#ifndef OPENSSL_NO_DTLS
300
    /*
301
     * If this connection was created by a listener, unregister it from the
302
     * listener's established_conns lookup table to prevent use-after-free.
303
     * The listener routes incoming packets to connections via this table,
304
     * so we must remove ourselves before freeing.
305
     */
306
21.1k
    if (s->d1 != NULL && s->d1->listener != NULL)
307
0
        ossl_dtls_listener_unregister_established_conn(s->d1->listener,
308
0
            &s->d1->peer_addr);
309
21.1k
#endif
310
311
21.1k
    if (s->d1 != NULL)
312
21.1k
        dtls1_clear_queues(s);
313
314
21.1k
#ifndef OPENSSL_NO_DTLS
315
21.1k
    if (s->d1 != NULL) {
316
21.1k
        DTLS_RX *rx = s->d1->rx;
317
318
21.1k
        if (s->listener_rx == rx)
319
21.1k
            s->listener_rx = NULL;
320
21.1k
        ossl_dtls_rx_free(rx);
321
322
21.1k
        if (s->d1->listener != NULL)
323
0
            SSL_free(s->d1->listener);
324
21.1k
    }
325
21.1k
#endif
326
327
21.1k
    DTLS_RECORD_LAYER_free(&s->rlayer);
328
21.1k
    ssl3_free(ssl);
329
21.1k
    OPENSSL_free(s->d1);
330
21.1k
    s->d1 = NULL;
331
21.1k
}
332
333
int dtls1_clear(SSL *ssl)
334
84.4k
{
335
84.4k
    size_t mtu;
336
84.4k
    size_t link_mtu;
337
84.4k
    SSL_CONNECTION *s;
338
339
84.4k
#ifndef OPENSSL_NO_DTLS
340
84.4k
    if (IS_DTLS_LISTENER(ssl))
341
0
        return 1;
342
84.4k
#endif
343
344
84.4k
    s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
345
346
84.4k
    if (s == NULL)
347
0
        return 0;
348
349
84.4k
    DTLS_RECORD_LAYER_clear(&s->rlayer);
350
351
84.4k
    if (s->d1) {
352
63.3k
        DTLS_timer_cb timer_cb = s->d1->timer_cb;
353
63.3k
#ifndef OPENSSL_NO_SOCK
354
63.3k
        BIO_ADDR peer_addr = s->d1->peer_addr;
355
63.3k
#endif
356
63.3k
#ifndef OPENSSL_NO_DTLS
357
63.3k
        DTLS_RX *rx = s->d1->rx;
358
63.3k
        SSL *listener = s->d1->listener;
359
63.3k
        OSSL_TIME created_at = s->d1->created_at;
360
63.3k
        unsigned int req_blocking_mode = s->d1->req_blocking_mode;
361
63.3k
#endif
362
363
63.3k
        mtu = s->d1->mtu;
364
63.3k
        link_mtu = s->d1->link_mtu;
365
366
63.3k
        dtls1_clear_queues(s);
367
368
63.3k
        memset(s->d1, 0, sizeof(*s->d1));
369
370
        /* Restore the timer callback from previous state */
371
63.3k
        s->d1->timer_cb = timer_cb;
372
373
63.3k
#ifndef OPENSSL_NO_SOCK
374
        /*
375
         * Restore peer address, DTLS_RX, listener, and created_at for
376
         * listener-created connections. These are set via
377
         * SSL_set1_initial_peer_addr(), ossl_dtls_rx_new(), and
378
         * dtls_listener_create_conn_ssl() before the handshake starts,
379
         * and must be preserved across SSL_clear().
380
         */
381
63.3k
        s->d1->peer_addr = peer_addr;
382
63.3k
#endif
383
63.3k
#ifndef OPENSSL_NO_DTLS
384
63.3k
        s->d1->rx = rx;
385
63.3k
        s->d1->listener = listener;
386
        /*
387
         * The blocking mode is a property of the connection as the application
388
         * configured it, not of the handshake, so it survives a clear.
389
         */
390
63.3k
        s->d1->req_blocking_mode = req_blocking_mode;
391
63.3k
        s->d1->created_at = created_at;
392
63.3k
#endif
393
394
63.3k
        if (SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU) {
395
0
            s->d1->mtu = mtu;
396
0
            s->d1->link_mtu = link_mtu;
397
0
        }
398
63.3k
    }
399
400
84.4k
    if (!ssl3_clear(ssl))
401
0
        return 0;
402
403
84.4k
    if (ssl->method->version == DTLS_ANY_VERSION)
404
84.4k
        s->version = DTLS_MAX_VERSION_INTERNAL;
405
0
#ifndef OPENSSL_NO_DTLS1_METHOD
406
0
    else if (s->options & SSL_OP_CISCO_ANYCONNECT)
407
0
        s->client_version = s->version = DTLS1_BAD_VER;
408
0
#endif
409
0
    else
410
0
        s->version = ssl->method->version;
411
412
84.4k
    return 1;
413
84.4k
}
414
415
long dtls1_ctrl(SSL *ssl, int cmd, long larg, void *parg)
416
12.6k
{
417
12.6k
    int ret = 0;
418
12.6k
    OSSL_TIME t;
419
12.6k
    SSL_CONNECTION *s;
420
421
12.6k
    if (IS_DTLS_LISTENER(ssl))
422
0
        return 0;
423
424
12.6k
    s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
425
426
12.6k
    if (s == NULL)
427
0
        return 0;
428
429
12.6k
    switch (cmd) {
430
0
    case DTLS_CTRL_GET_TIMEOUT:
431
0
        if (dtls1_get_timeout(s, &t)) {
432
0
            *(struct timeval *)parg = ossl_time_to_timeval(t);
433
0
            ret = 1;
434
0
        }
435
0
        break;
436
0
    case DTLS_CTRL_HANDLE_TIMEOUT:
437
0
        ret = dtls1_handle_timeout(s);
438
0
        break;
439
0
    case DTLS_CTRL_SET_LINK_MTU:
440
0
        if (larg < (long)dtls1_link_min_mtu)
441
0
            return 0;
442
0
        s->d1->link_mtu = larg;
443
0
        return 1;
444
0
    case DTLS_CTRL_GET_LINK_MIN_MTU:
445
0
        return (long)dtls1_link_min_mtu;
446
0
    case SSL_CTRL_SET_MTU:
447
        /*
448
         *  We may not have a BIO set yet so can't call dtls1_min_mtu()
449
         *  We'll have to make do with dtls1_link_min_mtu and max overhead
450
         */
451
0
        if (larg < (long)dtls1_link_min_mtu - DTLS1_MAX_MTU_OVERHEAD)
452
0
            return 0;
453
0
        s->d1->mtu = larg;
454
0
        return larg;
455
12.6k
    default:
456
12.6k
        ret = ssl3_ctrl(ssl, cmd, larg, parg);
457
12.6k
        break;
458
12.6k
    }
459
12.6k
    return ret;
460
12.6k
}
461
462
static void dtls1_bio_set_next_timeout(BIO *bio, const DTLS1_STATE *d1)
463
129k
{
464
129k
    struct timeval tv = ossl_time_to_timeval(d1->next_timeout);
465
466
129k
    BIO_ctrl(bio, BIO_CTRL_DGRAM_SET_NEXT_TIMEOUT, 0, &tv);
467
129k
}
468
469
void dtls1_start_timer(SSL_CONNECTION *s)
470
103k
{
471
103k
    OSSL_TIME duration;
472
103k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
473
474
#ifndef OPENSSL_NO_SCTP
475
    /* Disable timer for SCTP */
476
    if (SSL_get_wbio(ssl) != NULL && BIO_dgram_is_sctp(SSL_get_wbio(ssl))) {
477
        s->d1->next_timeout = ossl_time_zero();
478
        return;
479
    }
480
#endif
481
482
    /*
483
     * If timer is not set, initialize duration with 1 second or
484
     * a user-specified value if the timer callback is installed.
485
     */
486
103k
    if (ossl_time_is_zero(s->d1->next_timeout)) {
487
56.7k
        if (s->d1->timer_cb != NULL)
488
0
            s->d1->timeout_duration_us = s->d1->timer_cb(ssl, 0);
489
56.7k
        else
490
56.7k
            s->d1->timeout_duration_us = 1000000;
491
56.7k
    }
492
493
    /* Set timeout to current time plus duration */
494
103k
    duration = ossl_us2time(s->d1->timeout_duration_us);
495
103k
    s->d1->next_timeout = ossl_time_add(ossl_time_now(), duration);
496
497
    /* set s->d1->next_timeout into ssl->rbio interface */
498
103k
    dtls1_bio_set_next_timeout(SSL_get_rbio(ssl), s->d1);
499
103k
}
500
501
int dtls1_get_timeout(const SSL_CONNECTION *s, OSSL_TIME *timeleft)
502
355k
{
503
355k
    OSSL_TIME timenow;
504
505
    /* If no timeout is set, just return NULL */
506
355k
    if (ossl_time_is_zero(s->d1->next_timeout))
507
66.4k
        return 0;
508
509
    /* Get current time */
510
289k
    timenow = ossl_time_now();
511
512
    /*
513
     * If timer already expired or if remaining time is less than 15 ms,
514
     * set it to 0 to prevent issues because of small divergences with
515
     * socket timeouts.
516
     */
517
289k
    *timeleft = ossl_time_subtract(s->d1->next_timeout, timenow);
518
289k
    if (ossl_time_compare(*timeleft, ossl_ms2time(15)) <= 0)
519
0
        *timeleft = ossl_time_zero();
520
289k
    return 1;
521
355k
}
522
523
int dtls1_is_timer_expired(SSL_CONNECTION *s)
524
355k
{
525
355k
    OSSL_TIME timeleft;
526
527
    /* Get time left until timeout, return false if no timer running */
528
355k
    if (!dtls1_get_timeout(s, &timeleft))
529
66.4k
        return 0;
530
531
    /* Return false if timer is not expired yet */
532
289k
    if (!ossl_time_is_zero(timeleft))
533
289k
        return 0;
534
535
    /* Timer expired, so return true */
536
0
    return 1;
537
289k
}
538
539
static void dtls1_double_timeout(SSL_CONNECTION *s)
540
0
{
541
0
    s->d1->timeout_duration_us *= 2;
542
0
    if (s->d1->timeout_duration_us > 60000000)
543
0
        s->d1->timeout_duration_us = 60000000;
544
0
}
545
546
void dtls1_stop_timer(SSL_CONNECTION *s)
547
25.8k
{
548
    /* Reset everything */
549
25.8k
    s->d1->timeout_num_alerts = 0;
550
25.8k
    s->d1->next_timeout = ossl_time_zero();
551
25.8k
    s->d1->timeout_duration_us = 1000000;
552
25.8k
    dtls1_bio_set_next_timeout(s->rbio, s->d1);
553
    /* Clear retransmission buffer */
554
25.8k
    dtls1_clear_sent_buffer(s, 0);
555
25.8k
}
556
557
int dtls1_check_timeout_num(SSL_CONNECTION *s)
558
0
{
559
0
    size_t mtu;
560
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
561
562
0
    s->d1->timeout_num_alerts++;
563
564
    /* Reduce MTU after 2 unsuccessful retransmissions */
565
0
    if (s->d1->timeout_num_alerts > 2
566
0
        && !(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
567
0
        mtu = BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_GET_FALLBACK_MTU, 0, NULL);
568
0
        if (mtu < s->d1->mtu)
569
0
            s->d1->mtu = mtu;
570
0
    }
571
572
0
    if (s->d1->timeout_num_alerts > DTLS1_TMO_ALERT_COUNT) {
573
        /* fail the connection, enough alerts have been sent */
574
0
        SSLfatal(s, SSL_AD_NO_ALERT, SSL_R_READ_TIMEOUT_EXPIRED);
575
0
        return -1;
576
0
    }
577
578
0
    return 0;
579
0
}
580
581
int dtls1_handle_timeout(SSL_CONNECTION *s)
582
329k
{
583
    /* if no timer is expired, don't do anything */
584
329k
    if (!dtls1_is_timer_expired(s)) {
585
329k
        return 0;
586
329k
    }
587
588
0
    if (s->d1->timer_cb != NULL)
589
0
        s->d1->timeout_duration_us = s->d1->timer_cb(SSL_CONNECTION_GET_USER_SSL(s),
590
0
            s->d1->timeout_duration_us);
591
0
    else
592
0
        dtls1_double_timeout(s);
593
594
0
    if (dtls1_check_timeout_num(s) < 0) {
595
        /*
596
         * SSLfatal() already called, so the connection is finished. Stop the
597
         * timer rather than returning with next_timeout left in the past:
598
         * nothing will re-arm or clear it from here, so DTLSv1_get_timeout()
599
         * would report "due now" for ever and spin any caller which waits on
600
         * it.
601
         */
602
0
        dtls1_stop_timer(s);
603
0
        return -1;
604
0
    }
605
606
0
    dtls1_start_timer(s);
607
608
    /*
609
     * If write_state is anything other than WRITE_STATE_TRANSITION, a write
610
     * is still parked mid-flight (WANT_WRITE) from a previous call into the
611
     * state machine - the current flight hasn't actually finished going out
612
     * yet, so there's nothing valid to retransmit. Retransmitting anyway
613
     * would reconstruct an already-sent message from the retransmit queue
614
     * into s->init_buf/s->init_off/s->init_num/s->d1->w_msg - the same
615
     * fields the parked write is still using - corrupting that write's
616
     * state out from under it. Leave it alone and let the next
617
     * SSL_read()/SSL_write()/SSL_accept()/SSL_connect() call resume the
618
     * parked write normally instead.
619
     */
620
0
    if (s->statem.state == MSG_FLOW_WRITING
621
0
        && s->statem.write_state != WRITE_STATE_TRANSITION)
622
0
        return 0;
623
624
    /* Calls SSLfatal() if required */
625
0
    return dtls1_retransmit_sent_messages(s);
626
0
}
627
628
0
#define LISTEN_SUCCESS 2
629
0
#define LISTEN_SEND_VERIFY_REQUEST 1
630
631
#ifndef OPENSSL_NO_SOCK
632
int DTLSv1_listen(SSL *ssl, BIO_ADDR *client)
633
0
{
634
0
    int next, n, ret = 0;
635
0
    unsigned char cookie[DTLS1_COOKIE_LENGTH];
636
0
    unsigned char seq[SEQ_NUM_SIZE];
637
0
    const unsigned char *data;
638
0
    unsigned char *buf = NULL, *wbuf;
639
0
    size_t fragoff, fraglen, msglen;
640
0
    uint64_t record_sequence = 0;
641
0
    unsigned int rectype, versmajor, versminor, msgseq, msgtype, clientvers, cookielen;
642
0
    BIO *rbio, *wbio;
643
0
    BIO_ADDR *tmpclient = NULL;
644
0
    PACKET pkt, msgpkt, msgpayload, session, cookiepkt;
645
0
    SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
646
647
0
    if (s == NULL)
648
0
        return -1;
649
650
0
    if (s->handshake_func == NULL) {
651
        /* Not properly initialized yet */
652
0
        SSL_set_accept_state(ssl);
653
0
    }
654
655
    /* Ensure there is no state left over from a previous invocation */
656
0
    if (!SSL_clear(ssl))
657
0
        return -1;
658
659
0
    ERR_clear_error();
660
661
0
    rbio = SSL_get_rbio(ssl);
662
0
    wbio = SSL_get_wbio(ssl);
663
664
0
    if (!rbio || !wbio) {
665
0
        ERR_raise(ERR_LIB_SSL, SSL_R_BIO_NOT_SET);
666
0
        return -1;
667
0
    }
668
669
    /*
670
     * Note: This check deliberately excludes DTLS1_BAD_VER because that version
671
     * requires the MAC to be calculated *including* the first ClientHello
672
     * (without the cookie). Since DTLSv1_listen is stateless that cannot be
673
     * supported. DTLS1_BAD_VER must use cookies in a stateful manner (e.g. via
674
     * SSL_accept)
675
     */
676
0
    if ((s->version & 0xff00) != (DTLS1_VERSION & 0xff00)) {
677
0
        ERR_raise(ERR_LIB_SSL, SSL_R_UNSUPPORTED_SSL_VERSION);
678
0
        return -1;
679
0
    }
680
681
    /*
682
     * DTLSv1_listen() only supports the legacy HelloVerifyRequest mechanism
683
     * which is not used in DTLS 1.3. For DTLS 1.3, use the SSL_new_listener()
684
     * API instead which supports HelloRetryRequest with cookies.
685
     *
686
     * If the SSL object is configured for DTLS 1.3 only (both min and max
687
     * are set to DTLS 1.3), we must fail since there's no room to downgrade.
688
     * Otherwise, if max allows DTLS 1.3, we clamp it down to DTLS 1.2 so
689
     * that the handshake will use HelloVerifyRequest.
690
     */
691
0
    if (SSL_CONNECTION_IS_DTLS(s)) {
692
0
        int min_version = s->min_proto_version;
693
0
        int max_version = s->max_proto_version;
694
695
        /*
696
         * Check if configured for DTLS 1.3 only - this is not supported.
697
         * min_proto_version of 0 means "use default" which includes older versions,
698
         * so only fail if min is explicitly set to DTLS 1.3.
699
         */
700
0
        if (min_version == DTLS1_3_VERSION
701
0
            && (max_version == 0 || max_version == DTLS1_3_VERSION)) {
702
0
            ERR_raise(ERR_LIB_SSL, SSL_R_UNSUPPORTED_SSL_VERSION);
703
0
            return -1;
704
0
        }
705
706
        /* max_proto_version of 0 means "use default" which could include 1.3 */
707
0
        if (max_version == 0 || DTLS_VERSION_GE(max_version, DTLS1_3_VERSION)) {
708
0
            if (!SSL_set_max_proto_version(ssl, DTLS1_2_VERSION)) {
709
0
                ERR_raise(ERR_LIB_SSL, SSL_R_UNSUPPORTED_SSL_VERSION);
710
0
                return -1;
711
0
            }
712
0
        }
713
0
    }
714
715
0
    buf = OPENSSL_malloc(DTLS1_RT_HEADER_LENGTH + SSL3_RT_MAX_PLAIN_LENGTH);
716
0
    if (buf == NULL)
717
0
        return -1;
718
0
    wbuf = OPENSSL_malloc(DTLS1_RT_HEADER_LENGTH + SSL3_RT_MAX_PLAIN_LENGTH);
719
0
    if (wbuf == NULL) {
720
0
        OPENSSL_free(buf);
721
0
        return -1;
722
0
    }
723
724
0
    do {
725
        /* Get a packet */
726
727
0
        clear_sys_error();
728
0
        n = BIO_read(rbio, buf, SSL3_RT_MAX_PLAIN_LENGTH + DTLS1_RT_HEADER_LENGTH);
729
0
        if (n <= 0) {
730
0
            if (BIO_should_retry(rbio)) {
731
                /* Non-blocking IO */
732
0
                goto end;
733
0
            }
734
0
            ret = -1;
735
0
            goto end;
736
0
        }
737
738
0
        if (!PACKET_buf_init(&pkt, buf, n)) {
739
0
            ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
740
0
            ret = -1;
741
0
            goto end;
742
0
        }
743
744
        /*
745
         * Parse the received record. If there are any problems with it we just
746
         * dump it - with no alert. RFC6347 says this "Unlike TLS, DTLS is
747
         * resilient in the face of invalid records (e.g., invalid formatting,
748
         * length, MAC, etc.).  In general, invalid records SHOULD be silently
749
         * discarded, thus preserving the association; however, an error MAY be
750
         * logged for diagnostic purposes."
751
         */
752
753
        /* this packet contained a partial record, dump it */
754
0
        if (n < DTLS1_RT_HEADER_LENGTH) {
755
0
            ERR_raise(ERR_LIB_SSL, SSL_R_RECORD_TOO_SMALL);
756
0
            goto end;
757
0
        }
758
759
        /* Get the record header */
760
0
        if (!PACKET_get_1(&pkt, &rectype)
761
0
            || !PACKET_get_1(&pkt, &versmajor)
762
0
            || !PACKET_get_1(&pkt, &versminor)) {
763
0
            ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
764
0
            goto end;
765
0
        }
766
767
0
        if (s->msg_callback)
768
0
            s->msg_callback(0, (versmajor << 8) | versminor, SSL3_RT_HEADER, buf,
769
0
                DTLS1_RT_HEADER_LENGTH, ssl, s->msg_callback_arg);
770
771
0
        if (rectype != SSL3_RT_HANDSHAKE) {
772
0
            ERR_raise(ERR_LIB_SSL, SSL_R_UNEXPECTED_MESSAGE);
773
0
            goto end;
774
0
        }
775
776
        /*
777
         * Check record version number. We only check that the major version is
778
         * the same.
779
         */
780
0
        if (versmajor != DTLS1_VERSION_MAJOR) {
781
0
            ERR_raise(ERR_LIB_SSL, SSL_R_BAD_PROTOCOL_VERSION_NUMBER);
782
0
            goto end;
783
0
        }
784
785
        /* Save the sequence number: 64 bits, with top 2 bytes = epoch */
786
0
        if (!PACKET_copy_bytes(&pkt, seq, SEQ_NUM_SIZE)
787
0
            || !PACKET_get_length_prefixed_2(&pkt, &msgpkt)) {
788
0
            ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
789
0
            goto end;
790
0
        }
791
        /*
792
         * We allow data remaining at the end of the packet because there could
793
         * be a second record (but we ignore it)
794
         */
795
796
        /* This is an initial ClientHello so the epoch has to be 0 */
797
0
        if (seq[0] != 0 || seq[1] != 0) {
798
0
            ERR_raise(ERR_LIB_SSL, SSL_R_UNEXPECTED_MESSAGE);
799
0
            goto end;
800
0
        }
801
0
        record_sequence = ((uint64_t)seq[2]) << 40;
802
0
        record_sequence |= ((uint64_t)seq[3]) << 32;
803
0
        record_sequence |= ((uint64_t)seq[4]) << 24;
804
0
        record_sequence |= ((uint64_t)seq[5]) << 16;
805
0
        record_sequence |= ((uint64_t)seq[6]) << 8;
806
0
        record_sequence |= ((uint64_t)seq[7]);
807
808
        /* Get a pointer to the raw message for the later callback */
809
0
        data = PACKET_data(&msgpkt);
810
811
        /* Finished processing the record header, now process the message */
812
0
        if (!PACKET_get_1(&msgpkt, &msgtype)
813
0
            || !PACKET_get_net_3_len(&msgpkt, &msglen)
814
0
            || !PACKET_get_net_2(&msgpkt, &msgseq)
815
0
            || !PACKET_get_net_3_len(&msgpkt, &fragoff)
816
0
            || !PACKET_get_net_3_len(&msgpkt, &fraglen)
817
0
            || !PACKET_get_sub_packet(&msgpkt, &msgpayload, fraglen)
818
0
            || PACKET_remaining(&msgpkt) != 0) {
819
0
            ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
820
0
            goto end;
821
0
        }
822
823
0
        if (msgtype != SSL3_MT_CLIENT_HELLO) {
824
0
            ERR_raise(ERR_LIB_SSL, SSL_R_UNEXPECTED_MESSAGE);
825
0
            goto end;
826
0
        }
827
828
        /* Message sequence number can only be 0 or 1 */
829
0
        if (msgseq > 1) {
830
0
            ERR_raise(ERR_LIB_SSL, SSL_R_INVALID_SEQUENCE_NUMBER);
831
0
            goto end;
832
0
        }
833
834
        /*
835
         * We don't support fragment reassembly for ClientHellos whilst
836
         * listening because that would require server side state (which is
837
         * against the whole point of the ClientHello/HelloVerifyRequest
838
         * mechanism). Instead we only look at the first ClientHello fragment
839
         * and require that the cookie must be contained within it.
840
         */
841
0
        if (fragoff != 0 || fraglen > msglen) {
842
            /* Non initial ClientHello fragment (or bad fragment) */
843
0
            ERR_raise(ERR_LIB_SSL, SSL_R_FRAGMENTED_CLIENT_HELLO);
844
0
            goto end;
845
0
        }
846
847
0
        if (s->msg_callback)
848
0
            s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, data,
849
0
                fraglen + DTLS1_HM_HEADER_LENGTH, ssl,
850
0
                s->msg_callback_arg);
851
852
0
        if (!PACKET_get_net_2(&msgpayload, &clientvers)) {
853
0
            ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
854
0
            goto end;
855
0
        }
856
857
        /*
858
         * Verify client version is supported
859
         */
860
0
        if (DTLS_VERSION_LT(clientvers, (unsigned int)ssl->method->version) && ssl->method->version != DTLS_ANY_VERSION) {
861
0
            ERR_raise(ERR_LIB_SSL, SSL_R_WRONG_VERSION_NUMBER);
862
0
            goto end;
863
0
        }
864
865
0
        if (!PACKET_forward(&msgpayload, SSL3_RANDOM_SIZE)
866
0
            || !PACKET_get_length_prefixed_1(&msgpayload, &session)
867
0
            || !PACKET_get_length_prefixed_1(&msgpayload, &cookiepkt)) {
868
            /*
869
             * Could be malformed or the cookie does not fit within the initial
870
             * ClientHello fragment. Either way we can't handle it.
871
             */
872
0
            ERR_raise(ERR_LIB_SSL, SSL_R_LENGTH_MISMATCH);
873
0
            goto end;
874
0
        }
875
876
        /*
877
         * Check if we have a cookie or not. If not we need to send a
878
         * HelloVerifyRequest.
879
         */
880
0
        if (PACKET_remaining(&cookiepkt) == 0) {
881
0
            next = LISTEN_SEND_VERIFY_REQUEST;
882
0
        } else {
883
            /*
884
             * We have a cookie, so lets check it.
885
             */
886
0
            if (ssl->ctx->app_verify_cookie_cb == NULL) {
887
0
                ERR_raise(ERR_LIB_SSL, SSL_R_NO_VERIFY_COOKIE_CALLBACK);
888
                /* This is fatal */
889
0
                ret = -1;
890
0
                goto end;
891
0
            }
892
0
            if (ssl->ctx->app_verify_cookie_cb(ssl, PACKET_data(&cookiepkt),
893
0
                    (unsigned int)PACKET_remaining(&cookiepkt))
894
0
                == 0) {
895
                /*
896
                 * We treat invalid cookies in the same was as no cookie as
897
                 * per RFC6347
898
                 */
899
0
                next = LISTEN_SEND_VERIFY_REQUEST;
900
0
            } else {
901
                /* Cookie verification succeeded */
902
0
                next = LISTEN_SUCCESS;
903
0
            }
904
0
        }
905
906
0
        if (next == LISTEN_SEND_VERIFY_REQUEST) {
907
0
            WPACKET wpkt;
908
0
            unsigned int version;
909
0
            size_t wreclen;
910
911
            /*
912
             * There was no cookie in the ClientHello so we need to send a
913
             * HelloVerifyRequest. If this fails we do not worry about trying
914
             * to resend, we just drop it.
915
             */
916
917
            /* Generate the cookie */
918
0
            if (ssl->ctx->app_gen_cookie_cb == NULL || ssl->ctx->app_gen_cookie_cb(ssl, cookie, &cookielen) == 0 || cookielen > 255) {
919
0
                ERR_raise(ERR_LIB_SSL, SSL_R_COOKIE_GEN_CALLBACK_FAILURE);
920
                /* This is fatal */
921
0
                ret = -1;
922
0
                goto end;
923
0
            }
924
925
            /*
926
             * Special case: for hello verify request, client version 1.0 and we
927
             * haven't decided which version to use yet send back using version
928
             * 1.0 header: otherwise some clients will ignore it.
929
             */
930
0
            version = (ssl->method->version == DTLS_ANY_VERSION) ? DTLS1_VERSION
931
0
                                                                 : s->version;
932
933
            /* Construct the record and message headers */
934
0
            if (!WPACKET_init_static_len(&wpkt,
935
0
                    wbuf,
936
0
                    ssl_get_max_send_fragment(s)
937
0
                        + DTLS1_RT_HEADER_LENGTH,
938
0
                    0)
939
0
                || !WPACKET_put_bytes_u8(&wpkt, SSL3_RT_HANDSHAKE)
940
0
                || !WPACKET_put_bytes_u16(&wpkt, version)
941
                /*
942
                 * Record sequence number is always the same as in the
943
                 * received ClientHello
944
                 */
945
0
                || !WPACKET_memcpy(&wpkt, seq, SEQ_NUM_SIZE)
946
                /* End of record, start sub packet for message */
947
0
                || !WPACKET_start_sub_packet_u16(&wpkt)
948
                /* Message type */
949
0
                || !WPACKET_put_bytes_u8(&wpkt,
950
0
                    DTLS1_MT_HELLO_VERIFY_REQUEST)
951
                /*
952
                 * Message length - doesn't follow normal TLS convention:
953
                 * the length isn't the last thing in the message header.
954
                 * We'll need to fill this in later when we know the
955
                 * length. Set it to zero for now
956
                 */
957
0
                || !WPACKET_put_bytes_u24(&wpkt, 0)
958
                /*
959
                 * Message sequence number is always 0 for a
960
                 * HelloVerifyRequest
961
                 */
962
0
                || !WPACKET_put_bytes_u16(&wpkt, 0)
963
                /*
964
                 * We never fragment a HelloVerifyRequest, so fragment
965
                 * offset is 0
966
                 */
967
0
                || !WPACKET_put_bytes_u24(&wpkt, 0)
968
                /*
969
                 * Fragment length is the same as message length, but
970
                 * this *is* the last thing in the message header so we
971
                 * can just start a sub-packet. No need to come back
972
                 * later for this one.
973
                 */
974
0
                || !WPACKET_start_sub_packet_u24(&wpkt)
975
                /* Create the actual HelloVerifyRequest body */
976
0
                || !dtls_raw_hello_verify_request(&wpkt, cookie, cookielen)
977
                /* Close message body */
978
0
                || !WPACKET_close(&wpkt)
979
                /* Close record body */
980
0
                || !WPACKET_close(&wpkt)
981
0
                || !WPACKET_get_total_written(&wpkt, &wreclen)
982
0
                || !WPACKET_finish(&wpkt)) {
983
0
                ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
984
0
                WPACKET_cleanup(&wpkt);
985
                /* This is fatal */
986
0
                ret = -1;
987
0
                goto end;
988
0
            }
989
990
            /*
991
             * Fix up the message len in the message header. Its the same as the
992
             * fragment len which has been filled in by WPACKET, so just copy
993
             * that. Destination for the message len is after the record header
994
             * plus one byte for the message content type. The source is the
995
             * last 3 bytes of the message header
996
             */
997
0
            memcpy(&wbuf[DTLS1_RT_HEADER_LENGTH + 1],
998
0
                &wbuf[DTLS1_RT_HEADER_LENGTH + DTLS1_HM_HEADER_LENGTH - 3],
999
0
                3);
1000
1001
0
            if (s->msg_callback) {
1002
                /* Report the outgoing DTLS record header */
1003
0
                s->msg_callback(1, (int)version, SSL3_RT_HEADER,
1004
0
                    wbuf, DTLS1_RT_HEADER_LENGTH,
1005
0
                    ssl, s->msg_callback_arg);
1006
                /* Report the HelloVerifyRequest handshake message */
1007
0
                s->msg_callback(1, (int)version, SSL3_RT_HANDSHAKE,
1008
0
                    wbuf + DTLS1_RT_HEADER_LENGTH,
1009
0
                    wreclen - DTLS1_RT_HEADER_LENGTH,
1010
0
                    ssl, s->msg_callback_arg);
1011
0
            }
1012
1013
0
            if ((tmpclient = BIO_ADDR_new()) == NULL) {
1014
0
                ERR_raise(ERR_LIB_SSL, ERR_R_BIO_LIB);
1015
0
                goto end;
1016
0
            }
1017
1018
            /*
1019
             * This is unnecessary if rbio and wbio are one and the same - but
1020
             * maybe they're not. We ignore errors here - some BIOs do not
1021
             * support this.
1022
             */
1023
0
            if (BIO_dgram_get_peer(rbio, tmpclient) > 0) {
1024
0
                (void)BIO_dgram_set_peer(wbio, tmpclient);
1025
0
            }
1026
0
            BIO_ADDR_free(tmpclient);
1027
0
            tmpclient = NULL;
1028
1029
0
            if (BIO_write(wbio, wbuf, (int)wreclen) < (int)wreclen) {
1030
0
                if (BIO_should_retry(wbio)) {
1031
                    /*
1032
                     * Non-blocking IO...but we're stateless, so we're just
1033
                     * going to drop this packet.
1034
                     */
1035
0
                    goto end;
1036
0
                }
1037
0
                ret = -1;
1038
0
                goto end;
1039
0
            }
1040
1041
0
            if (BIO_flush(wbio) <= 0) {
1042
0
                if (BIO_should_retry(wbio)) {
1043
                    /*
1044
                     * Non-blocking IO...but we're stateless, so we're just
1045
                     * going to drop this packet.
1046
                     */
1047
0
                    goto end;
1048
0
                }
1049
0
                ret = -1;
1050
0
                goto end;
1051
0
            }
1052
0
        }
1053
0
    } while (next != LISTEN_SUCCESS);
1054
1055
    /*
1056
     * Set expected sequence numbers to continue the handshake.
1057
     */
1058
0
    s->d1->handshake_read_seq = 1;
1059
0
    s->d1->handshake_write_seq = 1;
1060
0
    s->d1->next_handshake_write_seq = 1;
1061
0
    if (s->rlayer.wrlmethod->set_sequence == NULL
1062
0
        || !s->rlayer.wrlmethod->set_sequence(s->rlayer.wrl,
1063
0
            record_sequence)) {
1064
0
        ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1065
0
        ret = -1;
1066
0
        goto end;
1067
0
    }
1068
1069
    /*
1070
     * We are doing cookie exchange, so make sure we set that option in the
1071
     * SSL object
1072
     */
1073
0
    SSL_set_options(ssl, SSL_OP_COOKIE_EXCHANGE);
1074
1075
    /*
1076
     * Tell the state machine that we've done the initial hello verify
1077
     * exchange
1078
     */
1079
0
    ossl_statem_set_hello_verify_done(s);
1080
1081
    /*
1082
     * Some BIOs may not support this. If we fail we clear the client address
1083
     */
1084
0
    if (BIO_dgram_get_peer(rbio, client) <= 0)
1085
0
        BIO_ADDR_clear(client);
1086
1087
    /* Buffer the record for use by the record layer */
1088
0
    if (BIO_write(s->rlayer.rrlnext, buf, n) != n) {
1089
0
        ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
1090
0
        ret = -1;
1091
0
        goto end;
1092
0
    }
1093
1094
    /*
1095
     * Reset the record layer - but this time we can use the record we just
1096
     * buffered in s->rlayer.rrlnext
1097
     */
1098
0
    if (!ssl_set_new_record_layer(s, DTLS_ANY_VERSION,
1099
0
            OSSL_RECORD_DIRECTION_READ,
1100
0
            OSSL_RECORD_PROTECTION_LEVEL_NONE, NULL, 0,
1101
0
            NULL, NULL, 0, NULL, 0, NULL, 0, NULL, NULL,
1102
0
            0, NID_undef, NULL, NULL, NULL)) {
1103
        /* SSLfatal already called */
1104
0
        ret = -1;
1105
0
        goto end;
1106
0
    }
1107
1108
0
    ret = 1;
1109
0
end:
1110
0
    BIO_ADDR_free(tmpclient);
1111
0
    OPENSSL_free(buf);
1112
0
    OPENSSL_free(wbuf);
1113
0
    return ret;
1114
0
}
1115
#endif
1116
1117
static int dtls1_handshake_write(SSL_CONNECTION *s)
1118
95.7k
{
1119
95.7k
    return dtls1_do_write(s, SSL3_RT_HANDSHAKE);
1120
95.7k
}
1121
1122
int dtls1_shutdown(SSL *s)
1123
0
{
1124
0
    int ret;
1125
#ifndef OPENSSL_NO_SCTP
1126
    BIO *wbio;
1127
    SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
1128
1129
    if (sc == NULL)
1130
        return -1;
1131
1132
    wbio = SSL_get_wbio(s);
1133
    if (wbio != NULL && BIO_dgram_is_sctp(wbio) && !(sc->shutdown & SSL_SENT_SHUTDOWN)) {
1134
        ret = BIO_dgram_sctp_wait_for_dry(wbio);
1135
        if (ret < 0)
1136
            return -1;
1137
1138
        if (ret == 0)
1139
            BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 1,
1140
                NULL);
1141
    }
1142
#endif
1143
0
    ret = ssl3_shutdown(s);
1144
#ifndef OPENSSL_NO_SCTP
1145
    BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_SAVE_SHUTDOWN, 0, NULL);
1146
#endif
1147
0
    return ret;
1148
0
}
1149
1150
int dtls1_query_mtu(SSL_CONNECTION *s)
1151
103k
{
1152
103k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1153
1154
103k
    if (s->d1->link_mtu) {
1155
0
        s->d1->mtu = s->d1->link_mtu - BIO_dgram_get_mtu_overhead(SSL_get_wbio(ssl));
1156
0
        s->d1->link_mtu = 0;
1157
0
    }
1158
1159
    /* AHA!  Figure out the MTU, and stick to the right size */
1160
103k
    if (s->d1->mtu < dtls1_min_mtu(s)) {
1161
44.8k
        if (!(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
1162
44.8k
            s->d1->mtu = BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_QUERY_MTU, 0, NULL);
1163
1164
            /*
1165
             * I've seen the kernel return bogus numbers when it doesn't know
1166
             * (initial write), so just make sure we have a reasonable number
1167
             */
1168
44.8k
            if (s->d1->mtu < dtls1_min_mtu(s)) {
1169
                /* Set to min mtu */
1170
44.8k
                s->d1->mtu = dtls1_min_mtu(s);
1171
44.8k
                BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_SET_MTU,
1172
44.8k
                    (long)s->d1->mtu, NULL);
1173
44.8k
            }
1174
44.8k
        } else
1175
0
            return 0;
1176
44.8k
    }
1177
103k
    return 1;
1178
103k
}
1179
1180
size_t dtls1_min_mtu(SSL_CONNECTION *s)
1181
296k
{
1182
296k
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1183
1184
296k
    return dtls1_link_min_mtu - BIO_dgram_get_mtu_overhead(SSL_get_wbio(ssl));
1185
296k
}
1186
1187
size_t DTLS_get_data_mtu(const SSL *ssl)
1188
0
{
1189
0
    size_t mac_overhead, int_overhead, blocksize, ext_overhead, rechdrlen = 0;
1190
0
    const SSL_CIPHER *ciph = SSL_get_current_cipher(ssl);
1191
0
    size_t mtu;
1192
0
    const SSL_CONNECTION *s = SSL_CONNECTION_FROM_CONST_SSL_ONLY(ssl);
1193
1194
0
    if (s == NULL)
1195
0
        return 0;
1196
1197
0
    mtu = s->d1->mtu;
1198
1199
0
    if (ciph == NULL)
1200
0
        return 0;
1201
1202
0
    if (!ssl_cipher_get_overhead(ciph, SSL_version(ssl), &mac_overhead,
1203
0
            &int_overhead, &blocksize, &ext_overhead))
1204
0
        return 0;
1205
1206
0
    if (SSL_READ_ETM(s))
1207
0
        ext_overhead += mac_overhead;
1208
0
    else
1209
0
        int_overhead += mac_overhead;
1210
1211
0
    if (SSL_version(ssl) == DTLS1_3_VERSION) {
1212
0
        switch (SSL_get_state(ssl)) {
1213
0
        case TLS_ST_BEFORE:
1214
0
        case DTLS_ST_CR_HELLO_VERIFY_REQUEST:
1215
0
        case TLS_ST_CR_SRVR_HELLO:
1216
0
        case TLS_ST_CW_CLNT_HELLO:
1217
0
        case TLS_ST_CW_COMP_CERT:
1218
0
        case TLS_ST_CW_KEY_EXCH:
1219
0
        case TLS_ST_SW_HELLO_REQ:
1220
0
        case TLS_ST_SR_CLNT_HELLO:
1221
0
        case DTLS_ST_SW_HELLO_VERIFY_REQUEST:
1222
0
        case TLS_ST_SW_SRVR_HELLO:
1223
0
        case TLS_ST_CR_HELLO_REQ:
1224
0
            rechdrlen = DTLS1_RT_HEADER_LENGTH;
1225
0
            break;
1226
0
        default:
1227
0
            rechdrlen = DTLS13_UNI_HDR_FIXED_LENGTH;
1228
0
            break;
1229
0
        }
1230
1231
        /* Added record type at the end of the data */
1232
0
        int_overhead++;
1233
0
    } else {
1234
0
        rechdrlen = DTLS1_RT_HEADER_LENGTH;
1235
0
    }
1236
1237
    /* Subtract external overhead (e.g. IV/nonce, separate MAC) */
1238
0
    if (ext_overhead + rechdrlen >= mtu)
1239
0
        return 0;
1240
0
    mtu -= ext_overhead + rechdrlen;
1241
1242
    /* Round encrypted payload down to cipher block size (for CBC etc.)
1243
     * No check for overflow since 'mtu % blocksize' cannot exceed mtu. */
1244
0
    if (blocksize)
1245
0
        mtu -= (mtu % blocksize);
1246
1247
    /* Subtract internal overhead (e.g. CBC padding len byte) */
1248
0
    if (int_overhead >= mtu)
1249
0
        return 0;
1250
0
    mtu -= int_overhead;
1251
1252
0
    return mtu;
1253
0
}
1254
1255
void DTLS_set_timer_cb(SSL *ssl, DTLS_timer_cb cb)
1256
0
{
1257
0
    SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
1258
1259
0
    if (s == NULL)
1260
0
        return;
1261
1262
0
    s->d1->timer_cb = cb;
1263
0
}
1264
1265
#if !defined(OPENSSL_NO_DTLS) && !defined(OPENSSL_NO_SOCK)
1266
/*
1267
 * dtls_listener_connection_free - free an SSL connection owned by the listener.
1268
 *
1269
 * This function is used to free SSL connections that are in the listener's
1270
 * pending_conns or incoming_connections queues. These connections are owned
1271
 * by the listener, NOT by the application.
1272
 *
1273
 * Connections in pending_conns and incoming_connections do NOT hold a reference
1274
 * to the listener, even though sc->d1->listener points to it. This is intentional:
1275
 * if these connections held a reference to the listener, the listener's reference
1276
 * count would never reach zero, and ossl_dtls_listener_free() would never be
1277
 * called to clean up the pending/incoming connections - creating a circular
1278
 * dependency.
1279
 *
1280
 * Only when a connection is returned to the application via SSL_accept_connection()
1281
 * does it take a reference on the listener. At that point, ownership transfers
1282
 * to the application, and the normal SSL_free() path is used.
1283
 *
1284
 * The assert on ssl->references == 1 ensures that nobody else has taken a
1285
 * reference to this connection while it was in the listener's queues. If
1286
 * this assert fires, something has gone wrong with ownership tracking.
1287
 */
1288
static void dtls_listener_connection_free(SSL *ssl)
1289
0
{
1290
0
    SSL_CONNECTION *sc;
1291
1292
0
    if (ssl == NULL)
1293
0
        return;
1294
1295
0
    sc = SSL_CONNECTION_FROM_SSL(ssl);
1296
1297
0
    if (sc != NULL && sc->d1 != NULL) {
1298
        /*
1299
         * Clear listener reference to prevent dtls1_free() from calling
1300
         * SSL_free() on the listener. The connection does not own the listener
1301
         * and SSL_free must not free the listener
1302
         */
1303
0
        sc->d1->listener = NULL;
1304
0
    }
1305
0
    SSL_free(ssl);
1306
0
}
1307
1308
/*
1309
 * dtls_listener_create_conn_ssl - create an SSL object for a new connection.
1310
 *
1311
 * Creates and initializes an SSL object for handling a new incoming
1312
 * connection. Sets up the DTLS_RX for URXE-based packet injection, with
1313
 * the write BIO connected to the listener's network BIO.
1314
 *
1315
 * Returns: new SSL object on success, NULL on failure
1316
 */
1317
static SSL *dtls_listener_create_conn_ssl(DTLS_LISTENER *dl,
1318
    const BIO_ADDR *peer)
1319
0
{
1320
0
    SSL *ssl = NULL;
1321
0
    SSL_CONNECTION *sc = NULL;
1322
0
    BIO *wbio = NULL;
1323
1324
0
    ssl = SSL_new(dl->ssl.ctx);
1325
0
    if (ssl == NULL)
1326
0
        goto err;
1327
1328
0
    sc = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
1329
0
    if (sc == NULL || sc->d1 == NULL)
1330
0
        goto err;
1331
1332
0
    SSL_set_accept_state(ssl);
1333
1334
    /*
1335
     * Create DTLS_RX for this connection. The demux is owned by the listener
1336
     * and will outlive this connection. DTLS_RX manages the URXE queue for
1337
     * incoming packets.
1338
     */
1339
0
    sc->d1->rx = ossl_dtls_rx_new(dl->demux);
1340
0
    if (sc->d1->rx == NULL)
1341
0
        goto err;
1342
0
    sc->listener_rx = sc->d1->rx;
1343
1344
    /*
1345
     * Update the read record layer to use the URXE queue if it already exists.
1346
     * This is needed because the record layer may have been created before
1347
     * sc->d1->rx was set, similar to how SSL_set1_initial_peer_addr() updates
1348
     * the peer address on existing record layers.
1349
     */
1350
0
    if (sc->rlayer.rrlmethod != NULL && sc->rlayer.rrl != NULL
1351
0
        && sc->rlayer.rrlmethod->set_use_urxe != NULL)
1352
0
        sc->rlayer.rrlmethod->set_use_urxe(sc->rlayer.rrl, 1);
1353
1354
    /*
1355
     * Store reference to parent listener. This allows the connection to
1356
     * trigger the listener's demux pump when reading data.
1357
     */
1358
0
    sc->d1->listener = &dl->ssl;
1359
1360
    /*
1361
     * Record when this connection was created. This is used to detect and
1362
     * clean up stale pending connections that haven't completed their
1363
     * handshake within the timeout period.
1364
     */
1365
0
    sc->d1->created_at = dtls_listener_get_time_direct(dl);
1366
1367
    /*
1368
     * For writes, use the shared network wbio. The peer address is NOT set
1369
     * on the BIO itself (which would affect all connections sharing this BIO).
1370
     * Instead, the peer address will be passed to the record layer during
1371
     * SSL_do_handshake(), and the record layer will use BIO_sendmmsg() with
1372
     * the peer address for each write.
1373
     */
1374
0
    wbio = dl->net_wbio;
1375
1376
0
    if (wbio == NULL) {
1377
0
        ERR_raise(ERR_LIB_SSL, SSL_R_BIO_NOT_SET);
1378
0
        goto err;
1379
0
    }
1380
1381
0
    if (!BIO_up_ref(wbio))
1382
0
        goto err;
1383
1384
0
    SSL_set0_rbio(ssl, NULL);
1385
0
    SSL_set0_wbio(ssl, wbio);
1386
0
    wbio = NULL; /* ownership transferred */
1387
1388
    /*
1389
     * Store the peer address in the SSL connection. This will be passed to
1390
     * the record layer when it is created during SSL_do_handshake().
1391
     */
1392
0
    if (!SSL_set1_initial_peer_addr(ssl, peer))
1393
0
        goto err;
1394
1395
    /*
1396
     * Enable cookie exchange if required by listener flags.
1397
     * This tells the state machine to perform HVR (DTLS 1.2) or
1398
     * HRR with cookie (DTLS 1.3) validation.
1399
     */
1400
0
    if (dl->require_hvr_cookie || dl->require_hrr_cookie)
1401
0
        SSL_set_options(ssl, SSL_OP_COOKIE_EXCHANGE);
1402
1403
0
    return ssl;
1404
1405
0
err:
1406
0
    dtls_listener_connection_free(ssl);
1407
0
    return NULL;
1408
0
}
1409
1410
/*
1411
 * dtls_listener_signal_notifier - wake threads blocked on this listener.
1412
 *
1413
 * Readiness may be produced by the thread which pumps the demux while a
1414
 * different thread is blocked in poll() on the network socket. That socket
1415
 * will not necessarily become readable again from the blocked thread's point
1416
 * of view, so the notifier is used to wake it.
1417
 *
1418
 * The caller must hold dl->mutex.
1419
 */
1420
static void dtls_listener_signal_notifier(DTLS_LISTENER *dl)
1421
0
{
1422
0
    if (dl->have_notifier && dl->cur_blocking_waiters > 0
1423
0
        && !dl->signalled_notifier) {
1424
0
        ossl_rio_notifier_signal(&dl->notifier);
1425
0
        dl->signalled_notifier = 1;
1426
0
    }
1427
0
}
1428
1429
/*
1430
 * dtls_listener_packet_handler - callback for handling incoming datagrams.
1431
 *
1432
 * This callback is invoked by the demux for each received datagram. It routes
1433
 * the URXE to the appropriate connection based on peer address, creating a
1434
 * new pending connection if necessary.
1435
 *
1436
 * The URXE ownership is transferred to the connection's DTLS_RX queue.
1437
 * If routing fails, the URXE is released back to the demux.
1438
 */
1439
static void dtls_listener_packet_handler(DGRAM_URXE *urxe, void *arg)
1440
0
{
1441
0
    DTLS_LISTENER *dl = arg;
1442
0
    SSL *conn_ssl = NULL;
1443
0
    SSL_CONNECTION *sc = NULL;
1444
0
    int pending = 0;
1445
1446
0
    ossl_crypto_mutex_lock(dl->mutex);
1447
1448
    /* Check established connections first */
1449
0
    if (dl->established_conns != NULL)
1450
0
        conn_ssl = ossl_dgram_conn_lookup_find(dl->established_conns, urxe);
1451
1452
    /* Check pending connections */
1453
0
    if (conn_ssl == NULL) {
1454
0
        conn_ssl = ossl_dgram_conn_lookup_find(dl->pending_conns, urxe);
1455
0
        pending = 1;
1456
0
    }
1457
1458
    /* Create new pending connection if needed */
1459
0
    if (conn_ssl == NULL) {
1460
        /*
1461
         * Reject before allocating anything if we have reached the pending
1462
         * connection limit. The LHASH item count is O(1), and this check does
1463
         * not need a conn_ssl, so performing it first avoids creating and then
1464
         * immediately freeing a connection when we are at capacity.
1465
         */
1466
0
        if (ossl_dgram_conn_lookup_num_items(dl->pending_conns)
1467
0
                + (size_t)sk_SSL_num(dl->incoming_connections)
1468
0
            >= dl->max_pending_conns)
1469
0
            goto release;
1470
1471
0
        conn_ssl = dtls_listener_create_conn_ssl(dl, &urxe->peer);
1472
0
        if (conn_ssl == NULL)
1473
0
            goto release;
1474
1475
        /*
1476
         * Register the connection in pending_conns before running the
1477
         * application callback. This is to avoid a race condition where
1478
         * another thread grabs the lock and tries to register a connection
1479
         * for this address.
1480
         */
1481
0
        if (!ossl_dgram_conn_lookup_register(dl->pending_conns, urxe, conn_ssl)) {
1482
0
            dtls_listener_connection_free(conn_ssl);
1483
0
            goto release;
1484
0
        }
1485
1486
        /*
1487
         * Give the application a chance to decorate or veto the new
1488
         * pending connection via SSL_CTX_set_new_pending_conn_cb().
1489
         *
1490
         * A return value of 0 from the callback means "discard this
1491
         * connection". On a non-zero return there is nothing more to do here:
1492
         * we already registered the connection above.
1493
         */
1494
0
        if (dl->ssl.ctx->new_pending_conn_cb != NULL) {
1495
0
            int keep;
1496
1497
0
            sc = SSL_CONNECTION_FROM_SSL_ONLY(conn_ssl);
1498
0
            if (sc == NULL || sc->d1 == NULL) {
1499
0
                ossl_dgram_conn_lookup_unregister(dl->pending_conns, &urxe->peer);
1500
0
                dtls_listener_connection_free(conn_ssl);
1501
0
                goto release;
1502
0
            }
1503
1504
            /*
1505
             * Mark the connection being_driven while the mutex is dropped for
1506
             * the callback. This keeps the tick loop away from this connection.
1507
             */
1508
0
            sc->listener_being_driven = 1;
1509
0
            ossl_crypto_mutex_unlock(dl->mutex);
1510
0
            keep = dl->ssl.ctx->new_pending_conn_cb(dl->ssl.ctx, conn_ssl,
1511
0
                dl->ssl.ctx->new_pending_conn_arg);
1512
0
            ossl_crypto_mutex_lock(dl->mutex);
1513
1514
0
            if (!keep) {
1515
                /*
1516
                 * The pending callback doesn't want this connection, so
1517
                 * unregister and free it. While the mutex was dropped a
1518
                 * concurrent handler may have found this same connection and
1519
                 * injected datagrams into its RX queue; freeing releases them
1520
                 * back to the demux via ossl_dtls_rx_free(), so nothing leaks.
1521
                 * being_driven kept the tick away, so the connection still
1522
                 * holds only its single reference and the free is safe.
1523
                 */
1524
0
                ossl_dgram_conn_lookup_unregister(dl->pending_conns, &urxe->peer);
1525
0
                dtls_listener_connection_free(conn_ssl);
1526
0
                goto release;
1527
0
            }
1528
1529
0
            sc->listener_being_driven = 0;
1530
0
        }
1531
0
    }
1532
1533
0
    sc = SSL_CONNECTION_FROM_SSL_ONLY(conn_ssl);
1534
0
    if (sc == NULL || sc->listener_rx == NULL)
1535
0
        goto release;
1536
1537
    /* Inject packet into connection's URXE queue */
1538
0
    ossl_dtls_rx_inject_urxe(sc->listener_rx, urxe);
1539
1540
    /*
1541
     * A connection being driven is rechecked by its driver in phase 3 of
1542
     * dtls_listener_drive_pass(). Anything else needs another pass.
1543
     */
1544
0
    if (pending && !sc->listener_being_driven)
1545
0
        dl->pending_input = 1;
1546
1547
    /* Signal notifier if needed */
1548
0
    dtls_listener_signal_notifier(dl);
1549
1550
0
    ossl_crypto_mutex_unlock(dl->mutex);
1551
0
    return;
1552
1553
0
release:
1554
0
    ossl_crypto_mutex_unlock(dl->mutex);
1555
0
    ossl_dgram_demux_release_urxe(dl->demux, urxe);
1556
0
}
1557
1558
/*
1559
 * DTLS Listener Internal Cookie Callbacks
1560
 *
1561
 * These callbacks are used internally by the DTLS listener to generate and
1562
 * verify cookies for address validation. They use HMAC-SHA256 with the
1563
 * SSL_CTX's cookie_hmac_key to create cookies that bind to the client's
1564
 * address.
1565
 *
1566
 * Cookie format:
1567
 *   - 8 bytes: timestamp (seconds since epoch)
1568
 *   - 32 bytes: HMAC-SHA256(timestamp || peer_address)
1569
 *
1570
 * Total cookie size: 40 bytes
1571
 */
1572
0
#define DTLS_LISTENER_COOKIE_TIMESTAMP_LEN 8
1573
0
#define DTLS_LISTENER_COOKIE_HMAC_LEN 32
1574
0
#define DTLS_LISTENER_COOKIE_LEN (DTLS_LISTENER_COOKIE_TIMESTAMP_LEN + DTLS_LISTENER_COOKIE_HMAC_LEN)
1575
1576
/* Maximum age of a cookie in seconds (default: 60 seconds) */
1577
0
#define DTLS_LISTENER_COOKIE_MAX_AGE 60
1578
1579
/*
1580
 * dtls_listener_get_time - get current time from the listener
1581
 *
1582
 * Returns the current time using the listener's time callback if set,
1583
 * otherwise uses ossl_time_now().
1584
 *
1585
 * If ssl is not associated with a listener, returns ossl_time_now().
1586
 */
1587
static OSSL_TIME dtls_listener_get_time(SSL *ssl)
1588
0
{
1589
0
    SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
1590
0
    DTLS_LISTENER *dl;
1591
1592
0
    if (sc == NULL || sc->d1 == NULL || sc->d1->listener == NULL)
1593
0
        return ossl_time_now();
1594
1595
0
    dl = (DTLS_LISTENER *)sc->d1->listener;
1596
1597
0
    if (dl->now_cb == NULL)
1598
0
        return ossl_time_now();
1599
1600
0
    return dl->now_cb(dl->now_cb_arg);
1601
0
}
1602
1603
/*
1604
 * dtls_listener_get_time_direct - get current time directly from listener
1605
 *
1606
 * Same as dtls_listener_get_time but takes the listener directly.
1607
 * Used during connection creation before listener reference is fully set up.
1608
 */
1609
static OSSL_TIME dtls_listener_get_time_direct(DTLS_LISTENER *dl)
1610
0
{
1611
0
    if (dl == NULL)
1612
0
        return ossl_time_now();
1613
1614
0
    if (dl->now_cb == NULL)
1615
0
        return ossl_time_now();
1616
1617
0
    return dl->now_cb(dl->now_cb_arg);
1618
0
}
1619
1620
/*
1621
 * dtls_listener_cookie_hmac - compute HMAC for cookie validation
1622
 *
1623
 * Computes HMAC-SHA256(timestamp || port || raw_address) using the
1624
 * context's cookie_hmac_key.
1625
 *
1626
 * Returns 1 on success, 0 on failure.
1627
 */
1628
int dtls_listener_cookie_hmac(SSL *ssl, uint64_t timestamp,
1629
    unsigned char *hmac_out)
1630
0
{
1631
0
    SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
1632
0
    SSL_CTX *ctx;
1633
0
    EVP_MAC_CTX *mctx = NULL;
1634
0
    OSSL_PARAM params[2];
1635
    /* 8 (timestamp) + 2 (port) + max address size */
1636
0
    unsigned char data[DTLS_LISTENER_COOKIE_TIMESTAMP_LEN + sizeof(uint16_t) + sizeof(BIO_ADDR)];
1637
0
    unsigned char addr_buf[sizeof(BIO_ADDR)];
1638
0
    size_t data_len = 0;
1639
0
    size_t addr_len = 0;
1640
0
    size_t hmac_len = DTLS_LISTENER_COOKIE_HMAC_LEN;
1641
0
    uint16_t port;
1642
0
    WPACKET pkt;
1643
0
    int ret = 0;
1644
1645
0
    if (sc == NULL || sc->d1 == NULL)
1646
0
        return 0;
1647
1648
0
    ctx = SSL_CONNECTION_GET_CTX(sc);
1649
0
    if (ctx == NULL)
1650
0
        return 0;
1651
1652
    /* Get port and raw address */
1653
0
    port = BIO_ADDR_rawport(&sc->d1->peer_addr);
1654
1655
0
    if (!BIO_ADDR_rawaddress(&sc->d1->peer_addr, addr_buf, &addr_len))
1656
0
        return 0;
1657
1658
    /* Build data to HMAC: timestamp || port || raw_address */
1659
0
    if (!WPACKET_init_static_len(&pkt, data, sizeof(data), 0)
1660
0
        || !WPACKET_put_bytes_u64(&pkt, timestamp)
1661
0
        || !WPACKET_put_bytes_u16(&pkt, port)
1662
0
        || !WPACKET_memcpy(&pkt, addr_buf, addr_len)
1663
0
        || !WPACKET_get_total_written(&pkt, &data_len)
1664
0
        || !WPACKET_finish(&pkt)) {
1665
0
        WPACKET_cleanup(&pkt);
1666
0
        return 0;
1667
0
    }
1668
1669
0
    mctx = EVP_MAC_CTX_new(ctx->hmac);
1670
0
    if (mctx == NULL)
1671
0
        goto err;
1672
1673
0
    params[0] = OSSL_PARAM_construct_utf8_string(OSSL_MAC_PARAM_DIGEST,
1674
0
        "SHA2-256", 0);
1675
0
    params[1] = OSSL_PARAM_construct_end();
1676
1677
0
    if (!EVP_MAC_init(mctx, ctx->ext.cookie_hmac_key,
1678
0
            sizeof(ctx->ext.cookie_hmac_key), params))
1679
0
        goto err;
1680
1681
0
    if (!EVP_MAC_update(mctx, data, data_len))
1682
0
        goto err;
1683
1684
0
    if (!EVP_MAC_final(mctx, hmac_out, &hmac_len, hmac_len))
1685
0
        goto err;
1686
1687
0
    ret = 1;
1688
1689
0
err:
1690
0
    EVP_MAC_CTX_free(mctx);
1691
0
    return ret;
1692
0
}
1693
1694
/*
1695
 * ossl_dtls_listener_gen_cookie_cb - internal HVR cookie generate callback
1696
 *
1697
 * Generates a cookie for HelloVerifyRequest (DTLS 1.2).
1698
 * Cookie format: timestamp (8 bytes) || HMAC (32 bytes)
1699
 */
1700
int ossl_dtls_listener_gen_cookie_cb(SSL *ssl, unsigned char *cookie,
1701
    unsigned int *cookie_len)
1702
0
{
1703
0
    uint64_t now = ossl_time2seconds(dtls_listener_get_time(ssl));
1704
1705
    /* Write timestamp */
1706
0
    cookie[0] = (unsigned char)(now >> 56);
1707
0
    cookie[1] = (unsigned char)(now >> 48);
1708
0
    cookie[2] = (unsigned char)(now >> 40);
1709
0
    cookie[3] = (unsigned char)(now >> 32);
1710
0
    cookie[4] = (unsigned char)(now >> 24);
1711
0
    cookie[5] = (unsigned char)(now >> 16);
1712
0
    cookie[6] = (unsigned char)(now >> 8);
1713
0
    cookie[7] = (unsigned char)(now);
1714
1715
    /* Compute and append HMAC */
1716
0
    if (!dtls_listener_cookie_hmac(ssl, now, cookie + DTLS_LISTENER_COOKIE_TIMESTAMP_LEN))
1717
0
        return 0;
1718
1719
0
    *cookie_len = DTLS_LISTENER_COOKIE_LEN;
1720
0
    return 1;
1721
0
}
1722
1723
/*
1724
 * ossl_dtls_listener_verify_cookie_cb - internal HVR cookie verify callback
1725
 *
1726
 * Verifies a cookie from ClientHello (DTLS 1.2).
1727
 * Checks that:
1728
 *   1. Cookie length is correct
1729
 *   2. Timestamp is not too old
1730
 *   3. HMAC matches
1731
 */
1732
int ossl_dtls_listener_verify_cookie_cb(SSL *ssl, const unsigned char *cookie,
1733
    unsigned int cookie_len)
1734
0
{
1735
0
    uint64_t cookie_time, now;
1736
0
    unsigned char expected_hmac[DTLS_LISTENER_COOKIE_HMAC_LEN];
1737
1738
0
    if (cookie_len != DTLS_LISTENER_COOKIE_LEN)
1739
0
        return 0;
1740
1741
    /* Extract timestamp from cookie */
1742
0
    cookie_time = ((uint64_t)cookie[0] << 56)
1743
0
        | ((uint64_t)cookie[1] << 48)
1744
0
        | ((uint64_t)cookie[2] << 40)
1745
0
        | ((uint64_t)cookie[3] << 32)
1746
0
        | ((uint64_t)cookie[4] << 24)
1747
0
        | ((uint64_t)cookie[5] << 16)
1748
0
        | ((uint64_t)cookie[6] << 8)
1749
0
        | ((uint64_t)cookie[7]);
1750
1751
    /* Check timestamp is not too old */
1752
0
    now = ossl_time2seconds(dtls_listener_get_time(ssl));
1753
0
    if (now > cookie_time && (now - cookie_time) > DTLS_LISTENER_COOKIE_MAX_AGE)
1754
0
        return 0;
1755
1756
    /* Compute expected HMAC and compare */
1757
0
    if (!dtls_listener_cookie_hmac(ssl, cookie_time, expected_hmac))
1758
0
        return 0;
1759
1760
0
    if (CRYPTO_memcmp(cookie + DTLS_LISTENER_COOKIE_TIMESTAMP_LEN,
1761
0
            expected_hmac, DTLS_LISTENER_COOKIE_HMAC_LEN)
1762
0
        != 0)
1763
0
        return 0;
1764
1765
0
    return 1;
1766
0
}
1767
1768
/*
1769
 * ossl_dtls_listener_gen_stateless_cookie_cb - internal HRR cookie generate callback
1770
 *
1771
 * Generates a cookie for HelloRetryRequest (DTLS 1.3).
1772
 * Uses the same format as the HVR cookie.
1773
 */
1774
int ossl_dtls_listener_gen_stateless_cookie_cb(SSL *ssl, unsigned char *cookie,
1775
    size_t *cookie_len)
1776
0
{
1777
0
    uint64_t now = ossl_time2seconds(dtls_listener_get_time(ssl));
1778
1779
    /* Write timestamp */
1780
0
    cookie[0] = (unsigned char)(now >> 56);
1781
0
    cookie[1] = (unsigned char)(now >> 48);
1782
0
    cookie[2] = (unsigned char)(now >> 40);
1783
0
    cookie[3] = (unsigned char)(now >> 32);
1784
0
    cookie[4] = (unsigned char)(now >> 24);
1785
0
    cookie[5] = (unsigned char)(now >> 16);
1786
0
    cookie[6] = (unsigned char)(now >> 8);
1787
0
    cookie[7] = (unsigned char)(now);
1788
1789
    /* Compute and append HMAC */
1790
0
    if (!dtls_listener_cookie_hmac(ssl, now, cookie + DTLS_LISTENER_COOKIE_TIMESTAMP_LEN))
1791
0
        return 0;
1792
1793
0
    *cookie_len = DTLS_LISTENER_COOKIE_LEN;
1794
0
    return 1;
1795
0
}
1796
1797
/*
1798
 * ossl_dtls_listener_verify_stateless_cookie_cb - internal HRR cookie verify callback
1799
 *
1800
 * Verifies a cookie from ClientHello (DTLS 1.3).
1801
 * Uses the same verification logic as the HVR cookie.
1802
 */
1803
int ossl_dtls_listener_verify_stateless_cookie_cb(SSL *ssl,
1804
    const unsigned char *cookie,
1805
    size_t cookie_len)
1806
0
{
1807
0
    uint64_t cookie_time, now;
1808
0
    unsigned char expected_hmac[DTLS_LISTENER_COOKIE_HMAC_LEN];
1809
1810
0
    if (cookie_len != DTLS_LISTENER_COOKIE_LEN)
1811
0
        return 0;
1812
1813
    /* Extract timestamp from cookie */
1814
0
    cookie_time = ((uint64_t)cookie[0] << 56)
1815
0
        | ((uint64_t)cookie[1] << 48)
1816
0
        | ((uint64_t)cookie[2] << 40)
1817
0
        | ((uint64_t)cookie[3] << 32)
1818
0
        | ((uint64_t)cookie[4] << 24)
1819
0
        | ((uint64_t)cookie[5] << 16)
1820
0
        | ((uint64_t)cookie[6] << 8)
1821
0
        | ((uint64_t)cookie[7]);
1822
1823
    /* Check timestamp is not too old */
1824
0
    now = ossl_time2seconds(dtls_listener_get_time(ssl));
1825
0
    if (now > cookie_time && (now - cookie_time) > DTLS_LISTENER_COOKIE_MAX_AGE)
1826
0
        return 0;
1827
1828
    /* Compute expected HMAC and compare */
1829
0
    if (!dtls_listener_cookie_hmac(ssl, cookie_time, expected_hmac))
1830
0
        return 0;
1831
1832
0
    if (CRYPTO_memcmp(cookie + DTLS_LISTENER_COOKIE_TIMESTAMP_LEN,
1833
0
            expected_hmac, DTLS_LISTENER_COOKIE_HMAC_LEN)
1834
0
        != 0)
1835
0
        return 0;
1836
1837
0
    return 1;
1838
0
}
1839
1840
SSL *ossl_dtls_new_listener(SSL_CTX *ctx, uint64_t flags)
1841
0
{
1842
0
    DTLS_LISTENER *dl = NULL;
1843
0
    int ssl_init_done = 0;
1844
1845
0
    if (ctx == NULL) {
1846
0
        ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_NULL_PARAMETER);
1847
0
        return NULL;
1848
0
    }
1849
1850
0
    if ((dl = OPENSSL_zalloc(sizeof(*dl))) == NULL) {
1851
0
        ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
1852
0
        goto err;
1853
0
    }
1854
1855
    /*
1856
     * Use ossl_ssl_init to initialize the SSL object header consistently
1857
     * with other SSL object types.
1858
     */
1859
0
    if (!ossl_ssl_init(&dl->ssl, ctx, ctx->method, SSL_TYPE_DTLS_LISTENER)) {
1860
0
        ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
1861
0
        goto err;
1862
0
    }
1863
0
    ssl_init_done = 1;
1864
1865
0
    dl->mutex = ossl_crypto_mutex_new();
1866
0
#ifdef OPENSSL_THREADS
1867
0
    if (dl->mutex == NULL) {
1868
0
        ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
1869
0
        goto err;
1870
0
    }
1871
0
#endif
1872
1873
    /* Create demux with internal locking for thread safety. */
1874
0
    dl->demux = ossl_dgram_demux_new(NULL, 1, NULL, NULL);
1875
0
    if (dl->demux == NULL) {
1876
0
        ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
1877
0
        goto err;
1878
0
    }
1879
1880
0
    ossl_dgram_demux_set_max_free_urxe(dl->demux, DEMUX_MAX_FREE_URXE);
1881
1882
    /* Set up the packet handler callback for routing datagrams to connections */
1883
0
    ossl_dgram_demux_set_default_handler(dl->demux, dtls_listener_packet_handler, dl);
1884
1885
0
    dl->incoming_connections = sk_SSL_new_null();
1886
0
    if (dl->incoming_connections == NULL) {
1887
0
        ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
1888
0
        goto err;
1889
0
    }
1890
1891
0
    dl->pending_conns = ossl_dgram_conn_lookup_new_addr();
1892
0
    if (dl->pending_conns == NULL) {
1893
0
        ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
1894
0
        goto err;
1895
0
    }
1896
1897
0
    dl->established_conns = ossl_dgram_conn_lookup_new_addr();
1898
0
    if (dl->established_conns == NULL) {
1899
0
        ERR_raise(ERR_LIB_SSL, ERR_R_CRYPTO_LIB);
1900
0
        goto err;
1901
0
    }
1902
1903
0
    dl->net_rbio = NULL;
1904
0
    dl->net_wbio = NULL;
1905
0
    tsan_store(&dl->listening, 0);
1906
0
    dl->fatal = 0;
1907
1908
    /* Default timeout for pending connections: 30 seconds */
1909
0
    dl->pending_timeout = ossl_seconds2time(30);
1910
1911
    /* Default maximum pending connections */
1912
0
    dl->max_pending_conns = DTLS_LISTENER_DEFAULT_MAX_PENDING_CONNS;
1913
1914
    /*
1915
     * The listener owns its receive-buffer size independent of any
1916
     * network BIO's send-path MTU.
1917
     */
1918
0
    dl->max_dgram_size = DTLS_LISTENER_DEFAULT_MAX_DGRAM_SIZE;
1919
0
    ossl_dgram_demux_set_mtu(dl->demux, (unsigned int)dl->max_dgram_size);
1920
1921
    /*
1922
     * Address validation is performed by default: HelloVerifyRequest for
1923
     * DTLS 1.0/1.2 and a HelloRetryRequest cookie for DTLS 1.3.  It can be
1924
     * requested explicitly with SSL_LISTENER_FLAG_ADDRESS_VALIDATION, or
1925
     * disabled with SSL_LISTENER_FLAG_NO_VALIDATE.  If both are specified we
1926
     * fail safe and validate: SSL_LISTENER_FLAG_ADDRESS_VALIDATION wins.
1927
     */
1928
0
    if ((flags & SSL_LISTENER_FLAG_NO_VALIDATE) == 0
1929
0
        || (flags & SSL_LISTENER_FLAG_ADDRESS_VALIDATION) != 0) {
1930
0
        dl->require_hvr_cookie = 1;
1931
0
        dl->require_hrr_cookie = 1;
1932
0
    }
1933
1934
0
    dl->have_notifier = 0;
1935
0
    dl->signalled_notifier = 0;
1936
0
    dl->cur_blocking_waiters = 0;
1937
1938
0
    if ((flags & SSL_LISTENER_FLAG_SINGLE_THREAD) == 0) {
1939
0
        if (!ossl_rio_notifier_init(&dl->notifier))
1940
0
            goto err;
1941
1942
0
        dl->notifier_cv = ossl_crypto_condvar_new();
1943
0
        if (dl->notifier_cv == NULL) {
1944
0
            ossl_rio_notifier_cleanup(&dl->notifier);
1945
0
            goto err;
1946
0
        }
1947
1948
0
        dl->have_notifier = 1;
1949
0
    }
1950
1951
0
    return &dl->ssl;
1952
1953
0
err:
1954
0
    if (dl == NULL)
1955
0
        return NULL;
1956
1957
    /*
1958
     * If ossl_ssl_init succeeded, SSL_free handles all cleanup
1959
     * including incoming_connections, notifier_cv, and OPENSSL_free(dl)
1960
     * itself via ossl_dtls_listener_free. Otherwise ossl_ssl_init
1961
     * did not run or partially failed, so we must free the raw
1962
     * allocation directly.
1963
     */
1964
0
    if (ssl_init_done)
1965
0
        SSL_free(&dl->ssl);
1966
0
    else
1967
0
        OPENSSL_free(dl);
1968
0
    return NULL;
1969
0
}
1970
1971
/*
1972
 * Callback to free SSL objects in pending_conns hash table.
1973
 * The pending_conns hash table owns the SSL objects it contains,
1974
 * so we must free them before freeing the hash table itself.
1975
 */
1976
static void dtls_free_pending_ssl_cb(SSL *ssl, const BIO_ADDR *peer, void *arg)
1977
0
{
1978
0
    dtls_listener_connection_free(ssl);
1979
0
}
1980
1981
void ossl_dtls_listener_free(SSL *s)
1982
0
{
1983
0
    DTLS_LISTENER *dl;
1984
1985
0
    if (!IS_DTLS_LISTENER(s))
1986
0
        return;
1987
1988
0
    dl = (DTLS_LISTENER *)s;
1989
1990
    /* Free any pending incoming connections */
1991
0
    if (dl->incoming_connections != NULL) {
1992
0
        while (sk_SSL_num(dl->incoming_connections) > 0) {
1993
0
            SSL *conn = sk_SSL_pop(dl->incoming_connections);
1994
1995
0
            dtls_listener_connection_free(conn);
1996
0
        }
1997
0
        sk_SSL_free(dl->incoming_connections);
1998
0
        dl->incoming_connections = NULL;
1999
0
    }
2000
2001
    /*
2002
     * Free all pending connections in the hash table.
2003
     */
2004
0
    if (dl->pending_conns != NULL) {
2005
0
        ossl_dgram_conn_lookup_foreach(dl->pending_conns, dtls_free_pending_ssl_cb, NULL);
2006
0
        ossl_dgram_conn_lookup_free(dl->pending_conns);
2007
0
        dl->pending_conns = NULL;
2008
0
    }
2009
2010
    /* Free all established connections in the hash table (no SSL ownership) */
2011
0
    if (dl->established_conns != NULL) {
2012
0
        ossl_dgram_conn_lookup_free(dl->established_conns);
2013
0
        dl->established_conns = NULL;
2014
0
    }
2015
2016
0
    ossl_crypto_mutex_free(&dl->mutex);
2017
2018
    /* Free the demux after all connections that reference it are freed */
2019
0
    if (dl->demux != NULL)
2020
0
        ossl_dgram_demux_free(dl->demux);
2021
2022
0
    BIO_free_all(dl->net_wbio);
2023
0
    BIO_free_all(dl->net_rbio);
2024
2025
0
    if (dl->have_notifier) {
2026
0
        ossl_crypto_condvar_free(&dl->notifier_cv);
2027
0
        ossl_rio_notifier_cleanup(&dl->notifier);
2028
0
    }
2029
0
}
2030
2031
SSL *ossl_dtls_get0_listener(const SSL *ssl)
2032
0
{
2033
0
    if (!IS_DTLS_LISTENER(ssl))
2034
0
        return NULL;
2035
2036
0
    return (SSL *)ssl;
2037
0
}
2038
2039
/*
2040
 * ossl_dtls_listen - start a DTLS listener accepting incoming connections.
2041
 */
2042
int ossl_dtls_listen(SSL *ssl)
2043
0
{
2044
0
    DTLS_LISTENER *dl;
2045
2046
0
    if (!IS_DTLS_LISTENER(ssl)) {
2047
0
        ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
2048
0
        return 0;
2049
0
    }
2050
2051
0
    dl = (DTLS_LISTENER *)ssl;
2052
2053
    /* Already listening is not an error. */
2054
0
    if (tsan_load(&dl->listening))
2055
0
        return 1;
2056
2057
0
    tsan_store(&dl->listening, 1);
2058
0
    return 1;
2059
0
}
2060
2061
/*
2062
 * dtls_listener_conn_ready - check if connection is ready for accept queue.
2063
 *
2064
 * Determines whether the SSL object has completed cookie validation (if required)
2065
 * or has received a valid ClientHello (if no validation) and is ready to be
2066
 * moved to the incoming_connections queue.
2067
 *
2068
 * The connection is returned to the application BEFORE the handshake completes,
2069
 * allowing the application to finish the handshake itself. This provides more
2070
 * control over the handshake process.
2071
 *
2072
 * For HRR (DTLS 1.3 with validation): Ready when sc->ext.cookieok is set
2073
 * For HVR (DTLS 1.2 with validation): Ready when sc->d1->cookie_verified is set
2074
 * For no validation: Ready after receiving the first ClientHello
2075
 *
2076
 * Returns: 1 if ready, 0 if still in progress
2077
 */
2078
static int dtls_listener_conn_ready(SSL *ssl, DTLS_LISTENER *dl)
2079
0
{
2080
0
    SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
2081
2082
0
    if (sc == NULL)
2083
0
        return 0;
2084
2085
    /*
2086
     * No validation required (SSL_LISTENER_FLAG_NO_VALIDATE):
2087
     * Ready immediately after receiving the first ClientHello.
2088
     * The connection exists in pending_conns, so it's ready.
2089
     */
2090
0
    if (!dl->require_hrr_cookie && !dl->require_hvr_cookie)
2091
0
        return 1;
2092
2093
    /*
2094
     * For DTLS 1.3 with HRR requirement:
2095
     * Ready when the cookie has been validated (second ClientHello received
2096
     * with valid cookie after HRR was sent). The cookieok flag is set during
2097
     * ClientHello processing when the HRR cookie is successfully verified.
2098
     */
2099
0
    if (dl->require_hrr_cookie && sc->ext.cookieok)
2100
0
        return 1;
2101
2102
    /*
2103
     * For DTLS 1.2 (and earlier) with HVR requirement:
2104
     * Ready when the cookie has been validated (second ClientHello received
2105
     * with valid cookie after HVR was sent). The cookie_verified flag is set
2106
     * during ClientHello processing when the HVR cookie is successfully verified.
2107
     */
2108
0
    if (dl->require_hvr_cookie && sc->d1 != NULL && sc->d1->cookie_verified)
2109
0
        return 1;
2110
2111
    /* Not ready yet - still waiting for cookie validation */
2112
0
    return 0;
2113
0
}
2114
2115
/*
2116
 * dtls_listener_conn_needs_retry - check if connection is waiting for more data.
2117
 *
2118
 * Determines whether the SSL object has sent an HRR/HVR and is waiting
2119
 * for the client's response.
2120
 *
2121
 * Returns: 1 if waiting for retry, 0 otherwise
2122
 */
2123
static int dtls_listener_conn_needs_retry(SSL *ssl)
2124
0
{
2125
0
    SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
2126
2127
0
    if (sc == NULL)
2128
0
        return 0;
2129
2130
    /*
2131
     * For DTLS 1.3: HRR has been sent, waiting for second ClientHello
2132
     */
2133
0
    if (sc->hello_retry_request == SSL_HRR_PENDING
2134
0
        && !ossl_statem_in_error(sc))
2135
0
        return 1;
2136
2137
    /*
2138
     * For DTLS 1.2: Check if we're in a state that indicates HVR was sent.
2139
     * The state machine will be waiting for the next ClientHello.
2140
     */
2141
0
    if (sc->statem.hand_state == DTLS_ST_SW_HELLO_VERIFY_REQUEST
2142
0
        && !ossl_statem_in_error(sc))
2143
0
        return 1;
2144
2145
0
    return 0;
2146
0
}
2147
2148
/*
2149
 * Context for drive_pending iteration.
2150
 */
2151
typedef struct {
2152
    DTLS_LISTENER *dl;
2153
    int ready_count; /* Connections ready to move to established */
2154
    int error_count; /* Connections with fatal errors */
2155
    STACK_OF(SSL) *to_drive; /* Connections to drive (collected in phase 1) */
2156
    STACK_OF(SSL) *ready_conns; /* Connections to move */
2157
    STACK_OF(SSL) *failed_conns; /* Connections to remove */
2158
} DRIVE_PENDING_CTX;
2159
2160
/*
2161
 * Callback for collecting pending connections to drive.
2162
 * Called with dl->mutex held. Marks connections as being_driven and up-refs them.
2163
 * Also checks for timed-out connections and marks them as failed.
2164
 */
2165
static void collect_pending_cb(SSL *ssl, const BIO_ADDR *peer, void *arg)
2166
0
{
2167
0
    DRIVE_PENDING_CTX *ctx = arg;
2168
0
    DTLS_LISTENER *dl = ctx->dl;
2169
0
    SSL_CONNECTION *sc;
2170
2171
0
    sc = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
2172
0
    if (sc == NULL)
2173
0
        return;
2174
2175
    /*
2176
     * Skip if already being driven by another thread.
2177
     */
2178
0
    if (sc->listener_being_driven)
2179
0
        return;
2180
2181
0
    if (sc->listener_rx == NULL || sc->d1 == NULL)
2182
0
        return;
2183
2184
    /*
2185
     * Check if this pending connection has exceeded the timeout.
2186
     * Stale connections that haven't completed their handshake are removed
2187
     * to prevent resource exhaustion from incomplete handshakes.
2188
     */
2189
0
    if (!ossl_time_is_infinite(dl->pending_timeout)) {
2190
0
        OSSL_TIME now = dtls_listener_get_time_direct(dl);
2191
0
        OSSL_TIME age = ossl_time_subtract(now, sc->d1->created_at);
2192
2193
0
        if (ossl_time_compare(age, dl->pending_timeout) > 0) {
2194
            /*
2195
             * Connection has timed out - mark for removal
2196
             *
2197
             * Set being_driven so that a concurrent ossl_dtls_tick() running
2198
             * phase 1 hits the being_driven check above and skips this
2199
             * connection, instead of collecting it and freeing it a second
2200
             * time (double-free).
2201
             *
2202
             * No up-ref is needed: phase 1 runs under dl->mutex, so collection
2203
             * is serialized, and being_driven keeps any other tick away until
2204
             * our phase 3 frees this connection. The single pending-queue
2205
             * reference is released by dtls_listener_connection_free() in the
2206
             * failed_conns loop.
2207
             *
2208
             * We intentionally do not handle a failed push specially: if the
2209
             * push fails (allocation failure) the connection stays registered
2210
             * in pending_conns and is simply retried on the next tick.
2211
             */
2212
0
            if (ctx->failed_conns != NULL && sk_SSL_push(ctx->failed_conns, ssl) > 0) {
2213
0
                sc->listener_being_driven = 1;
2214
0
                ctx->error_count++;
2215
0
            }
2216
0
            return;
2217
0
        }
2218
0
    }
2219
2220
0
    if (sc->listener_idle && !dtls1_is_timer_expired(sc)) {
2221
0
        int empty;
2222
2223
0
        ossl_crypto_mutex_lock(sc->listener_rx->mutex);
2224
0
        empty = ossl_list_urxe_is_empty(&sc->listener_rx->urxe_pending);
2225
0
        ossl_crypto_mutex_unlock(sc->listener_rx->mutex);
2226
0
        if (empty)
2227
0
            return;
2228
0
    }
2229
2230
    /*
2231
     * Up-ref and add to list first, then mark as being driven.
2232
     * The up-ref ensures the connection stays valid while we drive it
2233
     * without holding the mutex.
2234
     */
2235
0
    if (!SSL_up_ref(ssl))
2236
0
        return;
2237
2238
0
    if (sk_SSL_push(ctx->to_drive, ssl) <= 0) {
2239
0
        SSL_free(ssl); /* Release the ref we just took */
2240
0
        return;
2241
0
    }
2242
2243
0
    sc->listener_being_driven = 1;
2244
0
}
2245
2246
/*
2247
 * Drive a single connection's handshake.
2248
 * Called WITHOUT holding dl->mutex so demux_pump can be called safely.
2249
 */
2250
static void drive_single_connection(SSL *ssl, DTLS_LISTENER *dl,
2251
    DRIVE_PENDING_CTX *ctx)
2252
0
{
2253
0
    SSL_CONNECTION *sc;
2254
0
    int ret, ssl_err;
2255
2256
0
    sc = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
2257
0
    if (sc == NULL)
2258
0
        return;
2259
2260
    /*
2261
     * Drive the state machine with SSL_accept().
2262
     *
2263
     * We MUST set TLS1_FLAGS_STATELESS to prevent the state machine from
2264
     * calling SSL_clear() when entering the handshake.
2265
     *
2266
     * Without the flag, the state machine in state_machine() calls SSL_clear()
2267
     * when SSL_in_before() is true, which wipes out our restored state.
2268
     */
2269
0
    if (dl->require_hrr_cookie || dl->require_hvr_cookie)
2270
0
        sc->s3.flags |= TLS1_FLAGS_STATELESS;
2271
2272
    /*
2273
     * We are inside the listener's own tick, so this must not block: nothing
2274
     * else can make progress while it does, including whatever it would be
2275
     * waiting for.
2276
     */
2277
0
    sc->listener_force_nonblocking = 1;
2278
0
    ret = SSL_accept(ssl);
2279
0
    sc->listener_force_nonblocking = 0;
2280
0
    ssl_err = SSL_get_error(ssl, ret);
2281
0
    sc->listener_idle = ssl_err == SSL_ERROR_WANT_READ;
2282
2283
    /*
2284
     * Always clear the stateless flag after SSL_accept() completes.
2285
     */
2286
0
    if (dl->require_hrr_cookie || dl->require_hvr_cookie)
2287
0
        sc->s3.flags &= ~TLS1_FLAGS_STATELESS;
2288
2289
    /* Check if connection is ready to move to established */
2290
0
    if (dtls_listener_conn_ready(ssl, dl)) {
2291
0
        if (ctx->ready_conns != NULL && sk_SSL_push(ctx->ready_conns, ssl) > 0)
2292
0
            ctx->ready_count++;
2293
0
        return;
2294
0
    }
2295
2296
    /* Check if connection needs retry (HRR/HVR sent) */
2297
0
    if (dtls_listener_conn_needs_retry(ssl))
2298
0
        return;
2299
2300
0
    if (ssl_err == SSL_ERROR_WANT_READ || ssl_err == SSL_ERROR_WANT_WRITE) {
2301
        /* Handshake in progress, needs more data - keep pending */
2302
0
        return;
2303
0
    }
2304
2305
    /* Fatal error on this connection - mark for removal */
2306
0
    if (ssl_err == SSL_ERROR_SYSCALL || ssl_err == SSL_ERROR_SSL) {
2307
0
        if (ctx->failed_conns != NULL && sk_SSL_push(ctx->failed_conns, ssl) > 0)
2308
0
            ctx->error_count++;
2309
0
    }
2310
0
}
2311
2312
/*
2313
 * dtls_listener_drive_pass - drive handshakes for all pending connections.
2314
 *
2315
 * Uses a three-phase approach to minimize lock contention:
2316
 *   Phase 1: LOCK - collect connections to drive, mark as being_driven, up-ref
2317
 *   Phase 2: UNLOCK - drive each connection (can safely call demux_pump)
2318
 *   Phase 3: LOCK - update data structures, clear being_driven, release refs
2319
 *
2320
 * This approach allows SSL_accept() to call demux_pump() without deadlock,
2321
 * since the mutex is not held during phase 2.
2322
 *
2323
 * *again is set if a pending connection may have input left undriven.
2324
 *
2325
 * Returns:
2326
 *   1   At least one connection was moved to incoming_connections
2327
 *   0   No connections completed (all still pending or failed)
2328
 *  -1   Fatal error
2329
 */
2330
static int dtls_listener_drive_pass(DTLS_LISTENER *dl, int last_pass,
2331
    int *again)
2332
0
{
2333
0
    DRIVE_PENDING_CTX ctx;
2334
0
    SSL *ssl;
2335
0
    SSL_CONNECTION *sc;
2336
0
    int i, result = 0;
2337
2338
0
    memset(&ctx, 0, sizeof(ctx));
2339
0
    ctx.dl = dl;
2340
0
    ctx.to_drive = sk_SSL_new_null();
2341
0
    ctx.ready_conns = sk_SSL_new_null();
2342
0
    ctx.failed_conns = sk_SSL_new_null();
2343
2344
0
    if (ctx.to_drive == NULL || ctx.ready_conns == NULL
2345
0
        || ctx.failed_conns == NULL) {
2346
0
        sk_SSL_free(ctx.to_drive);
2347
0
        sk_SSL_free(ctx.ready_conns);
2348
0
        sk_SSL_free(ctx.failed_conns);
2349
0
        return -1;
2350
0
    }
2351
2352
    /*
2353
     * Phase 1: Collect connections to drive.
2354
     * Hold mutex while iterating pending_conns, mark connections as being_driven,
2355
     * and up-ref them so they stay valid after we release the mutex.
2356
     */
2357
0
    ossl_crypto_mutex_lock(dl->mutex);
2358
0
    dl->pending_input = 0;
2359
0
    ossl_dgram_conn_lookup_foreach(dl->pending_conns, collect_pending_cb, &ctx);
2360
0
    ossl_crypto_mutex_unlock(dl->mutex);
2361
2362
    /*
2363
     * Phase 2: Drive connections WITHOUT holding mutex.
2364
     * This allows SSL_accept() to call demux_pump() which may invoke
2365
     * packet_handler(), which needs to acquire the mutex.
2366
     */
2367
0
    for (i = 0; i < sk_SSL_num(ctx.to_drive); i++) {
2368
0
        ssl = sk_SSL_value(ctx.to_drive, i);
2369
0
        drive_single_connection(ssl, dl, &ctx);
2370
0
    }
2371
2372
    /*
2373
     * Phase 3: Update data structures.
2374
     * Re-acquire mutex to move ready connections to established,
2375
     * remove failed connections, clear being_driven flags, and release refs.
2376
     */
2377
0
    ossl_crypto_mutex_lock(dl->mutex);
2378
2379
    /*
2380
     * Since we have the mutex, clear the driven flag and release the
2381
     * up-ref for each connection.
2382
     */
2383
0
    for (i = 0; i < sk_SSL_num(ctx.to_drive); i++) {
2384
0
        ssl = sk_SSL_value(ctx.to_drive, i);
2385
0
        sc = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
2386
2387
0
        if (sc != NULL) {
2388
0
            sc->listener_being_driven = 0;
2389
0
            if (sc->listener_idle && sc->listener_rx != NULL) {
2390
0
                ossl_crypto_mutex_lock(sc->listener_rx->mutex);
2391
0
                if (!ossl_list_urxe_is_empty(&sc->listener_rx->urxe_pending))
2392
0
                    dl->pending_input = 1;
2393
0
                ossl_crypto_mutex_unlock(sc->listener_rx->mutex);
2394
0
            }
2395
0
        }
2396
2397
0
        SSL_free(ssl); /* Release reference from phase 1 */
2398
0
    }
2399
2400
    /* Move ready connections to established and incoming queue */
2401
0
    for (i = 0; i < sk_SSL_num(ctx.ready_conns); i++) {
2402
0
        ssl = sk_SSL_value(ctx.ready_conns, i);
2403
0
        sc = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
2404
2405
0
        if (sc == NULL || sc->d1 == NULL)
2406
0
            continue;
2407
2408
        /* Get peer address from the connection */
2409
0
        if (BIO_ADDR_family(&sc->d1->peer_addr) != AF_UNSPEC) {
2410
2411
            /* Remove from pending */
2412
0
            ossl_dgram_conn_lookup_unregister(dl->pending_conns, &sc->d1->peer_addr);
2413
2414
            /* Add to established connections (inline, we already hold mutex) */
2415
0
            if (dl->established_conns == NULL || !ossl_dgram_conn_lookup_register_addr(dl->established_conns, &sc->d1->peer_addr, ssl)) {
2416
0
                dtls_listener_connection_free(ssl);
2417
0
                continue;
2418
0
            }
2419
2420
            /* Add to incoming queue */
2421
0
            if (sk_SSL_push(dl->incoming_connections, ssl) > 0) {
2422
0
                result = 1;
2423
0
            } else {
2424
                /* Failed to add to queue, unregister and free */
2425
0
                ossl_dgram_conn_lookup_unregister(dl->established_conns,
2426
0
                    &sc->d1->peer_addr);
2427
0
                dtls_listener_connection_free(ssl);
2428
0
            }
2429
0
        }
2430
0
    }
2431
2432
    /*
2433
     * A connection became acceptable. Any thread blocked waiting for one is
2434
     * polling the network socket, which will not necessarily become readable
2435
     * again on its behalf, so wake it explicitly.
2436
     */
2437
0
    if (result)
2438
0
        dtls_listener_signal_notifier(dl);
2439
2440
    /* Remove failed connections (after releasing refs so ref count is 1) */
2441
0
    for (i = 0; i < sk_SSL_num(ctx.failed_conns); i++) {
2442
0
        ssl = sk_SSL_value(ctx.failed_conns, i);
2443
0
        sc = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
2444
2445
0
        if (sc != NULL && sc->d1 != NULL)
2446
0
            ossl_dgram_conn_lookup_unregister(dl->pending_conns, &sc->d1->peer_addr);
2447
2448
0
        dtls_listener_connection_free(ssl);
2449
0
    }
2450
2451
0
    *again = dl->pending_input;
2452
    /* Out of passes: make sure a blocked waiter ticks again. */
2453
0
    if (*again && last_pass)
2454
0
        dtls_listener_signal_notifier(dl);
2455
2456
0
    ossl_crypto_mutex_unlock(dl->mutex);
2457
2458
0
    sk_SSL_free(ctx.to_drive);
2459
0
    sk_SSL_free(ctx.ready_conns);
2460
0
    sk_SSL_free(ctx.failed_conns);
2461
2462
0
    return result;
2463
0
}
2464
2465
/*
2466
 * Driving a connection pumps the demux, which can queue input for a pending
2467
 * connection that the pass did not collect or has already driven. Pass again
2468
 * while that happens, up to a bound.
2469
 */
2470
static int dtls_listener_drive_pending(DTLS_LISTENER *dl)
2471
0
{
2472
0
    int pass, ret, again = 0, result = 0;
2473
2474
0
    for (pass = 0; pass < DTLS_LISTENER_MAX_DRIVE_PASSES; pass++) {
2475
0
        ret = dtls_listener_drive_pass(dl,
2476
0
            pass == DTLS_LISTENER_MAX_DRIVE_PASSES - 1, &again);
2477
0
        if (ret < 0)
2478
0
            return -1;
2479
0
        if (ret > 0)
2480
0
            result = 1;
2481
0
        if (!again)
2482
0
            break;
2483
0
    }
2484
0
    return result;
2485
0
}
2486
2487
/*
2488
 * ossl_dtls_tick - drive one iteration of the DTLS listener I/O loop.
2489
 *
2490
 * Uses the demux pump/callback architecture for efficient packet handling:
2491
 *   1. Call ossl_dgram_demux_pump() to read datagrams from the network
2492
 *   2. The demux invokes dtls_listener_packet_handler() for each datagram
2493
 *   3. The handler routes URXEs to connections (established or pending)
2494
 *   4. Drive handshakes for pending connections
2495
 *   5. Move completed connections to established_conns and incoming queue
2496
 *
2497
 * Return values:
2498
 *   1   A verified connection was pushed onto dl->incoming_connections.
2499
 *   0   Exchange incomplete (HRR/HVR sent, or no data yet); call again.
2500
 *  -1   Fatal error; dl->fatal is set.
2501
 */
2502
int ossl_dtls_tick(DTLS_LISTENER *dl)
2503
0
{
2504
0
    int pump_ret;
2505
2506
0
    if (dl == NULL || dl->net_rbio == NULL)
2507
0
        return 0;
2508
2509
    /*
2510
     * Get datagrams from the network and route them to connections.
2511
     */
2512
0
    pump_ret = ossl_dgram_demux_pump(dl->demux);
2513
2514
0
    if (pump_ret == DGRAM_DEMUX_PUMP_RES_PERMANENT_FAIL) {
2515
        /* Fatal BIO or allocation error */
2516
0
        ossl_crypto_mutex_lock(dl->mutex);
2517
0
        dl->fatal = 1;
2518
0
        ossl_crypto_mutex_unlock(dl->mutex);
2519
0
        return -1;
2520
0
    }
2521
2522
    /*
2523
     * Drive Handshakes for pending connections.
2524
     * call even if pump_ret indicates no data or temporary failure,
2525
     * to allow handshakes to progress even when no new data is arriving
2526
     */
2527
0
    return dtls_listener_drive_pending(dl);
2528
0
}
2529
2530
/*
2531
 * Does a pending connection have input which the last tick left undriven?
2532
 * A waiter must then tick again rather than sleep. Not on a fatal listener:
2533
 * its ticks fail before driving, so pending_input may never be cleared.
2534
 */
2535
int ossl_dtls_listener_has_pending_input(SSL *s)
2536
0
{
2537
0
    DTLS_LISTENER *dl;
2538
0
    int ret;
2539
2540
0
    if (!IS_DTLS_LISTENER(s))
2541
0
        return 0;
2542
2543
0
    dl = (DTLS_LISTENER *)s;
2544
0
    ossl_crypto_mutex_lock(dl->mutex);
2545
0
    ret = dl->pending_input && !dl->fatal;
2546
0
    ossl_crypto_mutex_unlock(dl->mutex);
2547
0
    return ret;
2548
0
}
2549
2550
SSL *ossl_dtls_accept_connection(SSL *ssl, uint64_t flags)
2551
0
{
2552
0
    DTLS_LISTENER *dl;
2553
0
    SSL *conn = NULL;
2554
0
    SSL_CONNECTION *sc = NULL;
2555
0
    int no_block = ((flags & SSL_ACCEPT_CONNECTION_NO_BLOCK) != 0);
2556
2557
0
    if (!IS_DTLS_LISTENER(ssl)) {
2558
0
        ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
2559
0
        return NULL;
2560
0
    }
2561
2562
0
    dl = (DTLS_LISTENER *)ssl;
2563
2564
0
    if (!ossl_dtls_listen(ssl))
2565
0
        return NULL;
2566
2567
    /* If a previous tick produced a fatal BIO error, do not try again. */
2568
0
    ossl_crypto_mutex_lock(dl->mutex);
2569
0
    if (dl->fatal) {
2570
0
        ossl_crypto_mutex_unlock(dl->mutex);
2571
0
        return NULL;
2572
0
    }
2573
2574
    /* Fast path: return any already-queued connection immediately. */
2575
0
    conn = sk_SSL_shift(dl->incoming_connections);
2576
0
    ossl_crypto_mutex_unlock(dl->mutex);
2577
0
    if (conn != NULL)
2578
0
        goto end;
2579
2580
    /*
2581
     * Wait only if the caller has not asked us not to and the listener is in
2582
     * blocking mode. Note that the check for a network BIO below is deliberately
2583
     * left ahead of this, so that asking to wait on a listener which has none
2584
     * remains an error rather than silently returning nothing.
2585
     */
2586
0
    if (!no_block && !ossl_dtls_blocking(ssl) && dl->net_rbio != NULL)
2587
0
        no_block = 1;
2588
2589
0
    if (no_block) {
2590
        /*
2591
         * Non-blocking: run one tick to drain any pending datagram, then
2592
         * return whatever is in the queue
2593
         */
2594
0
        if (dl->net_rbio != NULL) {
2595
0
            if (ossl_dtls_tick(dl) < 0) {
2596
0
                ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
2597
0
                return NULL;
2598
0
            }
2599
0
        }
2600
0
        ossl_crypto_mutex_lock(dl->mutex);
2601
0
        conn = sk_SSL_shift(dl->incoming_connections);
2602
0
        ossl_crypto_mutex_unlock(dl->mutex);
2603
0
        goto end;
2604
0
    }
2605
2606
    /* Blocking path: we need a BIO to make any progress. */
2607
0
    if (dl->net_rbio == NULL) {
2608
0
        ERR_raise(ERR_LIB_SSL, SSL_R_BIO_NOT_SET);
2609
0
        return NULL;
2610
0
    }
2611
2612
    /*
2613
     * Blocking path: tick to make whatever progress is possible now, and if
2614
     * that did not produce a connection, wait for readiness before ticking
2615
     * again.
2616
     *
2617
     * The wait is what stops this from being a busy loop. The network BIO is
2618
     * non-blocking, so a tick which finds no datagram returns immediately;
2619
     * without waiting in between, this loop would spin.
2620
     */
2621
0
    for (;;) {
2622
0
        if (ossl_dtls_tick(dl) < 0) {
2623
            /* fatal BIO error */
2624
0
            ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
2625
0
            break;
2626
0
        }
2627
2628
0
        ossl_crypto_mutex_lock(dl->mutex);
2629
0
        conn = sk_SSL_shift(dl->incoming_connections);
2630
0
        ossl_crypto_mutex_unlock(dl->mutex);
2631
0
        if (conn != NULL)
2632
0
            break;
2633
2634
        /*
2635
         * Nothing yet, so wait for the listener to become ready before ticking
2636
         * again. What that amounts to is decided by the poll translation for a
2637
         * listener: the network socket becoming readable, or another thread
2638
         * signalling the notifier because it produced readiness on our behalf.
2639
         */
2640
0
        if (!ossl_dtls_block_until_ready(ssl, SSL_POLL_EVENT_IC,
2641
0
                ossl_time_infinite(), /*bound_by_event_timeout=*/1))
2642
0
            break;
2643
0
    }
2644
2645
0
end:
2646
0
    if (conn != NULL) {
2647
0
        sc = SSL_CONNECTION_FROM_SSL(conn);
2648
        /*
2649
         * Take a reference on the listener now that ownership of the connection
2650
         * is transferring to the application. While in incoming_connections,
2651
         * the connection did not hold a reference to avoid circular dependencies.
2652
         * Now that the application owns the connection, it must hold a reference
2653
         * to ensure the listener stays alive - the connection needs the listener
2654
         * for packet routing
2655
         */
2656
0
        if (sc == NULL || sc->d1 == NULL || sc->d1->listener == NULL
2657
0
            || !SSL_up_ref(sc->d1->listener)) {
2658
            /*
2659
             * Ownership did not transfer to the application. A connection taken
2660
             * from incoming_connections is still registered in established_conns;
2661
             */
2662
0
            if (sc != NULL && sc->d1 != NULL)
2663
0
                ossl_dtls_listener_unregister_established_conn(ssl, &sc->d1->peer_addr);
2664
0
            dtls_listener_connection_free(conn);
2665
0
            ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
2666
0
            return NULL;
2667
0
        }
2668
0
    }
2669
0
    return conn;
2670
0
}
2671
2672
/*
2673
 * ossl_dtls_listener_set0_net_rbio - set the network read BIO for a listener.
2674
 *
2675
 * Thread safety: The caller must ensure that this function is not called
2676
 * concurrently with any other operations on the listener or its connections.
2677
 * This includes SSL_accept_connection(), SSL_poll(), SSL_tick(), and any
2678
 * I/O operations on connections created from this listener.
2679
 *
2680
 * The BIO must not be changed while other threads are actively using the
2681
 * listener. Typically, the BIO should be set once before calling SSL_listen()
2682
 * and not modified afterward.
2683
 */
2684
void ossl_dtls_listener_set0_net_rbio(SSL *s, BIO *bio)
2685
0
{
2686
0
    DTLS_LISTENER *dl;
2687
0
    BIO *old_rbio;
2688
2689
0
    if (!IS_DTLS_LISTENER(s))
2690
0
        return;
2691
2692
0
    dl = (DTLS_LISTENER *)s;
2693
2694
    /*
2695
     * The listener demultiplexes one socket to many connections, so it can
2696
     * never afford to block inside a read: a read for one connection would
2697
     * stall every other, and the demux lock is held across it. Blocking
2698
     * behaviour is provided by waiting for readiness instead, so configure the
2699
     * BIO for non-blocking operation on the application's behalf, as QUIC does.
2700
     */
2701
0
    if (bio != NULL)
2702
0
        BIO_set_nbio(bio, 1); /* best effort autoconfig */
2703
2704
0
    ossl_crypto_mutex_lock(dl->mutex);
2705
2706
    /*
2707
     * The demux receive-buffer size is the listener's configured maximum
2708
     * datagram size, independent of the network BIO's path MTU. Size the demux
2709
     * to that value for whatever BIO is attached.
2710
     */
2711
0
    ossl_dgram_demux_set_bio(dl->demux, bio);
2712
0
    ossl_dgram_demux_set_mtu(dl->demux, (unsigned int)dl->max_dgram_size);
2713
2714
0
    old_rbio = dl->net_rbio;
2715
2716
    /* No change - nothing to do */
2717
0
    if (old_rbio == bio) {
2718
0
        ossl_crypto_mutex_unlock(dl->mutex);
2719
0
        return;
2720
0
    }
2721
2722
0
    dl->net_rbio = bio;
2723
2724
0
    ossl_crypto_mutex_unlock(dl->mutex);
2725
2726
    /* Free the old BIO now that we've taken ownership of the new one */
2727
0
    BIO_free_all(old_rbio);
2728
0
}
2729
2730
/*
2731
 * update_conn_wbio - callback to update the wbio on a single connection.
2732
 *
2733
 * Used by ossl_dtls_listener_set0_net_wbio() to propagate wbio changes
2734
 * to all pending and established connections
2735
 */
2736
static void update_conn_wbio(SSL *ssl, const BIO_ADDR *peer, void *arg)
2737
0
{
2738
0
    BIO *new_wbio = arg;
2739
2740
0
    if (SSL_get_wbio(ssl) == new_wbio)
2741
0
        return;
2742
2743
0
    if (new_wbio != NULL && !BIO_up_ref(new_wbio))
2744
0
        return;
2745
2746
0
    SSL_set0_wbio(ssl, new_wbio);
2747
0
}
2748
2749
/*
2750
 * ossl_dtls_listener_set0_net_wbio - set the network write BIO for a listener.
2751
 *
2752
 * Thread safety: The caller must ensure that this function is not called
2753
 * concurrently with any other operations on the listener or its connections.
2754
 * This includes SSL_accept_connection(), SSL_poll(), SSL_tick(), and any
2755
 * I/O operations on connections created from this listener.
2756
 *
2757
 * The BIO must not be changed while other threads are actively using the
2758
 * listener. Typically, the BIO should be set once before calling SSL_listen()
2759
 * and not modified afterward.
2760
 */
2761
void ossl_dtls_listener_set0_net_wbio(SSL *s, BIO *bio)
2762
0
{
2763
0
    DTLS_LISTENER *dl;
2764
0
    BIO *old_wbio;
2765
2766
0
    if (!IS_DTLS_LISTENER(s))
2767
0
        return;
2768
2769
0
    dl = (DTLS_LISTENER *)s;
2770
2771
    /* See ossl_dtls_listener_set0_net_rbio() as to why. */
2772
0
    if (bio != NULL)
2773
0
        BIO_set_nbio(bio, 1); /* best effort autoconfig */
2774
2775
0
    old_wbio = dl->net_wbio;
2776
2777
    /* No change - nothing to do */
2778
0
    if (old_wbio == bio) {
2779
0
        return;
2780
0
    }
2781
2782
    /* Update wbio in all pending connections */
2783
0
    if (dl->pending_conns != NULL)
2784
0
        ossl_dgram_conn_lookup_foreach(dl->pending_conns, update_conn_wbio, bio);
2785
2786
    /* Update wbio in all established connections */
2787
0
    if (dl->established_conns != NULL)
2788
0
        ossl_dgram_conn_lookup_foreach(dl->established_conns, update_conn_wbio, bio);
2789
2790
0
    dl->net_wbio = bio;
2791
2792
    /* Free the old BIO now that we've taken ownership of the new one */
2793
0
    BIO_free_all(old_wbio);
2794
0
}
2795
2796
/*
2797
 * ossl_dtls_listener_get_net_rbio - get the network read BIO for a listener.
2798
 *
2799
 * Thread safety: The caller must ensure that the BIO is not being changed
2800
 * concurrently via SSL_set0_rbio(). The returned BIO pointer is only valid
2801
 * as long as no other thread modifies it.
2802
 */
2803
BIO *ossl_dtls_listener_get_net_rbio(const SSL *s)
2804
0
{
2805
0
    const DTLS_LISTENER *dl;
2806
2807
0
    if (!IS_DTLS_LISTENER(s))
2808
0
        return NULL;
2809
2810
0
    dl = (const DTLS_LISTENER *)s;
2811
2812
0
    return dl->net_rbio;
2813
0
}
2814
2815
/*
2816
 * ossl_dtls_listener_get_net_wbio - get the network write BIO for a listener.
2817
 *
2818
 * Thread safety: The caller must ensure that the BIO is not being changed
2819
 * concurrently via SSL_set0_wbio(). The returned BIO pointer is only valid
2820
 * as long as no other thread modifies it.
2821
 */
2822
BIO *ossl_dtls_listener_get_net_wbio(const SSL *s)
2823
0
{
2824
0
    const DTLS_LISTENER *dl;
2825
2826
0
    if (!IS_DTLS_LISTENER(s))
2827
0
        return NULL;
2828
2829
0
    dl = (const DTLS_LISTENER *)s;
2830
2831
0
    return dl->net_wbio;
2832
0
}
2833
2834
/*
2835
 * Established connections API - these handle their own locking.
2836
 *
2837
 * The established_conns lookup table is accessed from multiple threads:
2838
 * - Listener thread: looking up and registering connections
2839
 * - Connection thread: unregistering via SSL_free -> dtls1_free
2840
 */
2841
2842
/*
2843
 * ossl_dtls_listener_find_established_conn - find an established connection.
2844
 *
2845
 * Looks up a connection in the established_conns table by peer address.
2846
 * Returns the SSL connection if found, NULL otherwise.
2847
 */
2848
SSL *ossl_dtls_listener_find_established_conn(DTLS_LISTENER *dl,
2849
    const DGRAM_URXE *urxe)
2850
0
{
2851
0
    SSL *result = NULL;
2852
2853
0
    if (dl == NULL || urxe == NULL)
2854
0
        return NULL;
2855
2856
0
    ossl_crypto_mutex_lock(dl->mutex);
2857
2858
0
    if (dl->established_conns != NULL)
2859
0
        result = ossl_dgram_conn_lookup_find(dl->established_conns, urxe);
2860
2861
0
    ossl_crypto_mutex_unlock(dl->mutex);
2862
0
    return result;
2863
0
}
2864
2865
/*
2866
 * ossl_dtls_listener_unregister_established_conn - unregister an established
2867
 * connection from the listener.
2868
 *
2869
 * Called when a DTLS connection created by this listener is being freed.
2870
 */
2871
void ossl_dtls_listener_unregister_established_conn(SSL *s, const BIO_ADDR *peer_addr)
2872
0
{
2873
0
    DTLS_LISTENER *dl;
2874
2875
0
    if (!IS_DTLS_LISTENER(s))
2876
0
        return;
2877
2878
0
    if (peer_addr == NULL || BIO_ADDR_family(peer_addr) == AF_UNSPEC)
2879
0
        return;
2880
2881
0
    dl = (DTLS_LISTENER *)s;
2882
2883
0
    ossl_crypto_mutex_lock(dl->mutex);
2884
2885
0
    if (dl->established_conns != NULL)
2886
0
        ossl_dgram_conn_lookup_unregister(dl->established_conns, peer_addr);
2887
2888
0
    ossl_crypto_mutex_unlock(dl->mutex);
2889
0
}
2890
2891
/*
2892
 * ossl_dtls_listener_clear_established_conns - clear and recreate the
2893
 * established_conns table.
2894
 */
2895
void ossl_dtls_listener_clear_established_conns(DTLS_LISTENER *dl)
2896
0
{
2897
0
    if (dl == NULL)
2898
0
        return;
2899
2900
0
    ossl_crypto_mutex_lock(dl->mutex);
2901
2902
0
    if (dl->established_conns != NULL)
2903
0
        ossl_dgram_conn_lookup_free(dl->established_conns);
2904
0
    dl->established_conns = ossl_dgram_conn_lookup_new_addr();
2905
2906
0
    ossl_crypto_mutex_unlock(dl->mutex);
2907
0
}
2908
2909
size_t ossl_dtls_get_accept_connection_queue_len(SSL *ssl)
2910
0
{
2911
0
    DTLS_LISTENER *dl;
2912
0
    size_t len;
2913
2914
0
    if (!IS_DTLS_LISTENER(ssl))
2915
0
        return 0;
2916
2917
0
    dl = (DTLS_LISTENER *)ssl;
2918
2919
0
    ossl_crypto_mutex_lock(dl->mutex);
2920
0
    len = (size_t)sk_SSL_num(dl->incoming_connections);
2921
0
    ossl_crypto_mutex_unlock(dl->mutex);
2922
2923
0
    return len;
2924
0
}
2925
2926
/*
2927
 * Set an override time callback for the DTLS listener.
2928
 * This is primarily for testing purposes to allow time injection.
2929
 * If now_cb is NULL, the listener will use ossl_time_now().
2930
 */
2931
int ossl_dtls_listener_set_override_now_cb(SSL *s,
2932
    OSSL_TIME (*now_cb)(void *arg),
2933
    void *now_cb_arg)
2934
0
{
2935
0
    DTLS_LISTENER *dl;
2936
2937
0
    if (!IS_DTLS_LISTENER(s))
2938
0
        return 0;
2939
2940
0
    dl = (DTLS_LISTENER *)s;
2941
0
    dl->now_cb = now_cb;
2942
0
    dl->now_cb_arg = now_cb_arg;
2943
2944
0
    return 1;
2945
0
}
2946
2947
/*
2948
 * ossl_dtls_get_value_uint - read a tunable value from a DTLS listener.
2949
 *
2950
 * DTLS-side implementation backing SSL_get_value_uint(3) when the target
2951
 * SSL object is a DTLS listener created by SSL_new_listener().
2952
 *
2953
 * Supported (id) values:
2954
 *   SSL_VALUE_DTLS_LISTENER_MAX_PENDING_CONNS
2955
 *       Admission budget: the total connections the listener owns,
2956
 *       counting both the pending (handshake-in-progress) table and the
2957
 *       accept queue (validated connections awaiting
2958
 *       SSL_accept_connection). Accepted connections are not counted.
2959
 *   SSL_VALUE_DTLS_LISTENER_PENDING_TIMEOUT
2960
 *       Current reap timeout for pending connections, in milliseconds.
2961
 *       UINT64_MAX means "infinite / disabled". Accept-queue entries do
2962
 *       not expire.
2963
 *   SSL_VALUE_DTLS_LISTENER_MAX_DGRAM_SIZE
2964
 *       Maximum size in bytes of a datagram the listener will receive.
2965
 *
2966
 * Only SSL_VALUE_CLASS_GENERIC is accepted for class_; other
2967
 * classes are rejected with a return of 0
2968
 *
2969
 * Parameters:
2970
 *   s      - listener SSL. Must satisfy IS_DTLS_LISTENER(s).
2971
 *   class_ - value class; must be SSL_VALUE_CLASS_GENERIC.
2972
 *   id     - one of the SSL_VALUE_DTLS_LISTENER_* ids listed above.
2973
 *   value  - out-parameter receiving the current value. Must be non-NULL.
2974
 *
2975
 * Returns:
2976
 *   1 on success (*value populated).
2977
 *   0 on failure (unsupported id, wrong class, NULL value, or not a
2978
 *     DTLS listener).
2979
 */
2980
int ossl_dtls_get_value_uint(SSL *s, uint32_t class_, uint32_t id, uint64_t *value)
2981
0
{
2982
0
    DTLS_LISTENER *dl;
2983
0
    int ret = 1;
2984
2985
0
    if (!IS_DTLS_LISTENER(s)) {
2986
0
        ERR_raise(ERR_LIB_SSL, SSL_R_LISTENER_USE_ONLY);
2987
0
        return 0;
2988
0
    }
2989
0
    if (class_ != SSL_VALUE_CLASS_GENERIC) {
2990
0
        ERR_raise(ERR_LIB_SSL, SSL_R_UNSUPPORTED_CONFIG_VALUE_CLASS);
2991
0
        return 0;
2992
0
    }
2993
0
    if (value == NULL) {
2994
0
        ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
2995
0
        return 0;
2996
0
    }
2997
2998
0
    dl = (DTLS_LISTENER *)s;
2999
3000
0
    ossl_crypto_mutex_lock(dl->mutex);
3001
3002
0
    switch (id) {
3003
0
    case SSL_VALUE_DTLS_LISTENER_MAX_PENDING_CONNS:
3004
0
        *value = (uint64_t)dl->max_pending_conns;
3005
0
        break;
3006
0
    case SSL_VALUE_DTLS_LISTENER_PENDING_TIMEOUT:
3007
0
        if (ossl_time_is_infinite(dl->pending_timeout))
3008
0
            *value = UINT64_MAX;
3009
0
        else
3010
0
            *value = ossl_time2ms(dl->pending_timeout);
3011
0
        break;
3012
0
    case SSL_VALUE_DTLS_LISTENER_MAX_DGRAM_SIZE:
3013
0
        *value = (uint64_t)dl->max_dgram_size;
3014
0
        break;
3015
0
    default:
3016
0
        ERR_raise(ERR_LIB_SSL, SSL_R_UNSUPPORTED_CONFIG_VALUE);
3017
0
        ret = 0;
3018
0
        break;
3019
0
    }
3020
3021
0
    ossl_crypto_mutex_unlock(dl->mutex);
3022
0
    return ret;
3023
0
}
3024
3025
/*
3026
 * ossl_dtls_set_value_uint - write a tunable value on a DTLS listener.
3027
 *
3028
 * DTLS-side implementation backing SSL_set_value_uint(3) when the target
3029
 * SSL object is a DTLS listener created by SSL_new_listener().
3030
 *
3031
 * Supported (id) values -- see ossl_dtls_get_value_uint() above.
3032
 *
3033
 * Per-id policy:
3034
 *   SSL_VALUE_DTLS_LISTENER_MAX_PENDING_CONNS
3035
 *       value == 0 is rejected (a zero cap would reject every incoming
3036
 *       connection). Values larger than SIZE_MAX are clamped to SIZE_MAX
3037
 *       to avoid silent truncation on 32-bit builds. Lowering the value
3038
 *       below the current number of listener-owned connections does not
3039
 *       evict any of them; it only affects later admission.
3040
 *   SSL_VALUE_DTLS_LISTENER_PENDING_TIMEOUT
3041
 *       Interpreted as milliseconds. value == 0 is rejected. UINT64_MAX is
3042
 *       treated as "infinite / disabled".
3043
 *   SSL_VALUE_DTLS_LISTENER_MAX_DGRAM_SIZE
3044
 *       Clamped to the maximum UDP payload (DTLS_LISTENER_MAX_DGRAM_SIZE);
3045
 *       values below the demux minimum receive size are rejected.
3046
 *
3047
 * Only SSL_VALUE_CLASS_GENERIC is accepted for class_.
3048
 *
3049
 * Parameters:
3050
 *   s      - listener SSL. Must satisfy IS_DTLS_LISTENER(s).
3051
 *   class_ - value class; must be SSL_VALUE_CLASS_GENERIC.
3052
 *   id     - one of the SSL_VALUE_DTLS_LISTENER_* ids.
3053
 *   value  - new value to store, in the units documented per id.
3054
 *
3055
 * Returns:
3056
 *   1 on success.
3057
 *   0 on failure (unsupported id, wrong class, not a DTLS listener,
3058
 *     or policy rejection such as 0 on the cap).
3059
 */
3060
int ossl_dtls_set_value_uint(SSL *s, uint32_t class_, uint32_t id, uint64_t value)
3061
0
{
3062
0
    DTLS_LISTENER *dl;
3063
0
    int ret = 1;
3064
3065
0
    if (!IS_DTLS_LISTENER(s)) {
3066
0
        ERR_raise(ERR_LIB_SSL, SSL_R_LISTENER_USE_ONLY);
3067
0
        return 0;
3068
0
    }
3069
0
    if (class_ != SSL_VALUE_CLASS_GENERIC) {
3070
0
        ERR_raise(ERR_LIB_SSL, SSL_R_UNSUPPORTED_CONFIG_VALUE_CLASS);
3071
0
        return 0;
3072
0
    }
3073
3074
0
    dl = (DTLS_LISTENER *)s;
3075
3076
0
    ossl_crypto_mutex_lock(dl->mutex);
3077
3078
0
    switch (id) {
3079
0
    case SSL_VALUE_DTLS_LISTENER_MAX_PENDING_CONNS:
3080
0
        if (value == 0) {
3081
            /* A zero cap would reject every connection (num_items >= 0). */
3082
0
            ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
3083
0
            ret = 0;
3084
0
            break;
3085
0
        }
3086
        /* Clamp to SIZE_MAX to prevent silent truncation on 32-bit. */
3087
0
        dl->max_pending_conns = (value > SIZE_MAX) ? SIZE_MAX : (size_t)value;
3088
0
        break;
3089
0
    case SSL_VALUE_DTLS_LISTENER_PENDING_TIMEOUT:
3090
0
        if (value == 0) {
3091
            /*
3092
             * A zero timeout will remove all pending connections on the next
3093
             * tick, before the handshake could complete.
3094
             */
3095
0
            ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
3096
0
            ret = 0;
3097
0
            break;
3098
0
        }
3099
        /*
3100
         * ossl_ms2time() scales by OSSL_TIME_MS (10^6 ns/ms), so any value
3101
         * above UINT64_MAX / OSSL_TIME_MS would overflow the product and
3102
         * silently wrap to a tiny timeout. Treat those (which includes the
3103
         * UINT64_MAX "infinite" sentinel) as an infinite timeout.
3104
         */
3105
0
        if (value > UINT64_MAX / OSSL_TIME_MS)
3106
0
            dl->pending_timeout = ossl_time_infinite();
3107
0
        else
3108
0
            dl->pending_timeout = ossl_ms2time(value);
3109
0
        break;
3110
0
    case SSL_VALUE_DTLS_LISTENER_MAX_DGRAM_SIZE:
3111
        /* Nothing larger than the maximum UDP payload can ever arrive. */
3112
0
        if (value > DTLS_LISTENER_MAX_DGRAM_SIZE)
3113
0
            value = DTLS_LISTENER_MAX_DGRAM_SIZE;
3114
        /* set_mtu returns 0 (rejecting) for values below the demux minimum. */
3115
0
        if (!ossl_dgram_demux_set_mtu(dl->demux, (unsigned int)value)) {
3116
0
            ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
3117
0
            ret = 0;
3118
0
        } else {
3119
0
            dl->max_dgram_size = (size_t)value;
3120
0
        }
3121
0
        break;
3122
0
    default:
3123
0
        ERR_raise(ERR_LIB_SSL, SSL_R_UNSUPPORTED_CONFIG_VALUE);
3124
0
        ret = 0;
3125
0
        break;
3126
0
    }
3127
3128
0
    ossl_crypto_mutex_unlock(dl->mutex);
3129
0
    return ret;
3130
0
}
3131
3132
/*
3133
 * Resolve the requested blocking mode of a DTLS listener, or of a connection
3134
 * created from one, following the inheritance chain.
3135
 *
3136
 * A connection set to INHERIT follows its listener; a listener set to INHERIT
3137
 * is blocking, there being nothing further to inherit from. Blocking is
3138
 * therefore the default unless the application asks otherwise.
3139
 *
3140
 * Returns 1 if blocking is wanted, which says nothing about whether it can be
3141
 * provided - see ossl_dtls_can_support_blocking().
3142
 */
3143
static int ossl_dtls_desires_blocking(const SSL *s)
3144
0
{
3145
0
    const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL_ONLY(s);
3146
0
    const DTLS_LISTENER *dl = NULL;
3147
3148
0
    if (sc != NULL && sc->d1 != NULL) {
3149
        /* The listener is driving this connection; it must not block. */
3150
0
        if (sc->listener_force_nonblocking)
3151
0
            return 0;
3152
3153
0
        if (sc->d1->req_blocking_mode != DTLS_BLOCKING_MODE_INHERIT)
3154
0
            return sc->d1->req_blocking_mode == DTLS_BLOCKING_MODE_BLOCKING;
3155
3156
0
        dl = (const DTLS_LISTENER *)sc->d1->listener;
3157
0
    } else if (IS_DTLS_LISTENER(s)) {
3158
0
        dl = (const DTLS_LISTENER *)s;
3159
0
    }
3160
3161
0
    if (dl == NULL)
3162
0
        return 0;
3163
3164
0
    return dl->req_blocking_mode != DTLS_BLOCKING_MODE_NONBLOCKING;
3165
0
}
3166
3167
/*
3168
 * Report whether blocking mode can be provided for a DTLS listener or a
3169
 * connection created from one.
3170
 *
3171
 * Blocking is emulated by waiting for readiness of the listener's network
3172
 * socket, so it requires a BIO which can supply a poll descriptor to wait on.
3173
 * A memory BIO cannot, and such a listener is therefore non-blocking whatever
3174
 * was requested, as is the case for QUIC.
3175
 */
3176
static int ossl_dtls_can_support_blocking(const SSL *s)
3177
0
{
3178
0
    const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL_ONLY(s);
3179
0
    const SSL *listener = NULL;
3180
0
    BIO_POLL_DESCRIPTOR desc;
3181
0
    BIO *rbio;
3182
3183
0
    if (sc != NULL && sc->d1 != NULL)
3184
0
        listener = sc->d1->listener;
3185
0
    else if (IS_DTLS_LISTENER(s))
3186
0
        listener = s;
3187
3188
0
    if (listener == NULL)
3189
0
        return 0;
3190
3191
0
    rbio = SSL_get_rbio(listener);
3192
0
    if (rbio == NULL)
3193
0
        return 0;
3194
3195
0
    return BIO_get_rpoll_descriptor(rbio, &desc) != 0
3196
0
        && desc.type == BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD;
3197
0
}
3198
3199
/*
3200
 * Report whether a call on this object should block, which is the case when
3201
 * blocking is both wanted and possible.
3202
 */
3203
int ossl_dtls_blocking(const SSL *s)
3204
0
{
3205
0
    return ossl_dtls_desires_blocking(s) && ossl_dtls_can_support_blocking(s);
3206
0
}
3207
3208
int ossl_dtls_set_blocking_mode(SSL *s, int blocking)
3209
0
{
3210
0
    SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
3211
0
    unsigned int mode = (blocking != 0)
3212
0
        ? DTLS_BLOCKING_MODE_BLOCKING
3213
0
        : DTLS_BLOCKING_MODE_NONBLOCKING;
3214
3215
    /*
3216
     * Only a listener, or a connection created from one, has a blocking mode.
3217
     * Any other DTLS object takes its behaviour from its own BIO in the
3218
     * traditional way, so there is nothing here to configure.
3219
     */
3220
0
    if (!IS_DTLS_LISTENER(s)
3221
0
        && (sc == NULL || sc->d1 == NULL || sc->d1->listener == NULL)) {
3222
0
        ERR_raise(ERR_LIB_SSL, ERR_R_PASSED_INVALID_ARGUMENT);
3223
0
        return 0;
3224
0
    }
3225
3226
    /*
3227
     * Refuse to claim blocking we cannot deliver, as QUIC does. Checked before
3228
     * anything is written, so that a call which fails leaves the mode alone
3229
     * rather than reporting failure having already changed it.
3230
     */
3231
0
    if (blocking && !ossl_dtls_can_support_blocking(s)) {
3232
0
        ERR_raise(ERR_LIB_SSL, ERR_R_UNSUPPORTED);
3233
0
        return 0;
3234
0
    }
3235
3236
0
    if (IS_DTLS_LISTENER(s))
3237
0
        ((DTLS_LISTENER *)s)->req_blocking_mode = mode;
3238
0
    else
3239
0
        sc->d1->req_blocking_mode = mode;
3240
3241
0
    return 1;
3242
0
}
3243
3244
int ossl_dtls_get_blocking_mode(const SSL *s)
3245
0
{
3246
0
    const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL_ONLY(s);
3247
3248
0
    if (!IS_DTLS_LISTENER(s)
3249
0
        && (sc == NULL || sc->d1 == NULL || sc->d1->listener == NULL))
3250
0
        return -1;
3251
3252
0
    return ossl_dtls_blocking(s);
3253
0
}
3254
3255
/*
3256
 * Wait until a datagram has been demultiplexed to this connection's receive
3257
 * queue, for a connection which is in blocking mode.
3258
 *
3259
 * This is what makes a blocking read on a listener based connection block. Such
3260
 * a connection has no BIO of its own to block in: it reads from a queue which
3261
 * the listener fills, so the wait has to happen here instead.
3262
 *
3263
 * A wakeup does not mean the datagram was ours - the listener's socket is
3264
 * shared, and another connection may be the one with data - so this loops until
3265
 * something actually lands in our queue. Events are handled after each wait
3266
 * because nothing else will do it while we are in here, and the retransmission
3267
 * timer needs servicing if it is what woke us.
3268
 *
3269
 * A datagram which is already waiting costs nothing: the wait pumps the
3270
 * listener's demux while translating the poll, and returns without sleeping if
3271
 * anything has been queued for us by then.
3272
 *
3273
 * Returns 1 if a datagram is now queued for this connection, or 0 if the wait
3274
 * could not be performed or the listener has failed.
3275
 */
3276
int ossl_dtls_conn_wait_for_datagram(SSL *s)
3277
0
{
3278
0
    SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
3279
0
    DTLS_LISTENER *dl;
3280
0
    int empty;
3281
3282
0
    if (sc == NULL || sc->d1 == NULL || sc->d1->rx == NULL
3283
0
        || sc->d1->listener == NULL)
3284
0
        return 0;
3285
3286
0
    dl = (DTLS_LISTENER *)sc->d1->listener;
3287
3288
0
    for (;;) {
3289
0
        ossl_crypto_mutex_lock(dl->mutex);
3290
0
        if (dl->fatal) {
3291
0
            ossl_crypto_mutex_unlock(dl->mutex);
3292
0
            return 0;
3293
0
        }
3294
0
        ossl_crypto_mutex_unlock(dl->mutex);
3295
3296
        /*
3297
         * An infinite deadline here is bounded by the connection's own event
3298
         * timeout, which the poll translation folds in, so this still wakes in
3299
         * time to retransmit.
3300
         */
3301
0
        if (!ossl_dtls_block_until_ready(s, SSL_POLL_EVENT_R,
3302
0
                ossl_time_infinite(), /*bound_by_event_timeout=*/1))
3303
0
            return 0;
3304
3305
0
        if (!SSL_handle_events(s))
3306
0
            return 0;
3307
3308
0
        ossl_dgram_demux_pump(sc->d1->rx->demux);
3309
3310
0
        ossl_crypto_mutex_lock(sc->d1->rx->mutex);
3311
0
        empty = ossl_list_urxe_is_empty(&sc->d1->rx->urxe_pending);
3312
0
        ossl_crypto_mutex_unlock(sc->d1->rx->mutex);
3313
3314
0
        if (!empty)
3315
0
            return 1;
3316
0
    }
3317
0
}
3318
3319
/*
3320
 * Wait until the listener's socket can accept another datagram, for a
3321
 * connection which is in blocking mode.
3322
 *
3323
 * The socket is shared with every other connection and is always
3324
 * non-blocking, so a send which cannot be completed has nowhere to wait. For
3325
 * DTLS the record layer would otherwise discard the datagram - a reasonable
3326
 * default for an unreliable transport, but not what an application which asked
3327
 * for blocking writes expects.
3328
 *
3329
 * Only one wait is performed. The caller retries the send, and comes back here
3330
 * if it still cannot proceed, so a wakeup which turns out not to leave room in
3331
 * the socket buffer costs an extra attempt rather than a lost datagram.
3332
 *
3333
 * The retransmission timer deliberately does not shorten this wait, unlike the
3334
 * one for a datagram above. There the wakeup is useful, because the wait can
3335
 * service the timer itself; here it cannot. Servicing it would mean
3336
 * retransmitting a flight from inside tls_retry_write_records(), which is
3337
 * part-way through sending one and holds write buffer state that a
3338
 * re-entrant do_dtls1_write() would clobber. Waking for a timer nothing then
3339
 * services would be worse than not waking: the timeout stays expired, and an
3340
 * expired timeout reads as a zero deadline, so every later wait would return
3341
 * at once and the caller's retry loop would spin without sleeping. Waiting for
3342
 * the socket alone is also what the send actually needs. Retransmission is not
3343
 * the right response to a flight which has not finished going out, and once it
3344
 * has, the state machine handles the timer as usual.
3345
 *
3346
 * Returns 1 if the send should be retried, or 0 if the wait could not be
3347
 * performed or the listener has failed.
3348
 */
3349
int ossl_dtls_conn_wait_for_write(SSL *s)
3350
0
{
3351
0
    SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL_ONLY(s);
3352
0
    DTLS_LISTENER *dl;
3353
0
    int fatal;
3354
3355
0
    if (sc == NULL || sc->d1 == NULL || sc->d1->listener == NULL)
3356
0
        return 0;
3357
3358
0
    dl = (DTLS_LISTENER *)sc->d1->listener;
3359
3360
0
    ossl_crypto_mutex_lock(dl->mutex);
3361
0
    fatal = dl->fatal;
3362
0
    ossl_crypto_mutex_unlock(dl->mutex);
3363
0
    if (fatal)
3364
0
        return 0;
3365
3366
0
    return ossl_dtls_block_until_ready(s, SSL_POLL_EVENT_W,
3367
0
        ossl_time_infinite(), /*bound_by_event_timeout=*/0);
3368
0
}
3369
3370
void ossl_dtls_listener_enter_blocking_section(SSL *s)
3371
0
{
3372
0
    DTLS_LISTENER *dl;
3373
3374
0
    if (!IS_DTLS_LISTENER(s))
3375
0
        return;
3376
3377
0
    dl = (DTLS_LISTENER *)s;
3378
3379
0
    if (dl->have_notifier) {
3380
0
        ossl_crypto_mutex_lock(dl->mutex);
3381
0
        dl->cur_blocking_waiters++;
3382
0
        ossl_crypto_mutex_unlock(dl->mutex);
3383
0
    }
3384
0
}
3385
3386
int ossl_dtls_listener_deregister_blocking_section(SSL *s, uint64_t *generation)
3387
0
{
3388
0
    DTLS_LISTENER *dl;
3389
0
    int need_wait = 0;
3390
3391
0
    if (!IS_DTLS_LISTENER(s))
3392
0
        return 0;
3393
3394
0
    dl = (DTLS_LISTENER *)s;
3395
3396
0
    if (dl->have_notifier) {
3397
0
        ossl_crypto_mutex_lock(dl->mutex);
3398
3399
0
        assert(dl->cur_blocking_waiters > 0);
3400
0
        --dl->cur_blocking_waiters;
3401
3402
0
        if (dl->signalled_notifier) {
3403
0
            if (dl->cur_blocking_waiters == 0) {
3404
0
                ossl_rio_notifier_unsignal(&dl->notifier);
3405
0
                dl->signalled_notifier = 0;
3406
0
                ++dl->notify_generation;
3407
3408
                /*
3409
                 * Release the other threads which have woken up
3410
                 */
3411
0
                ossl_crypto_condvar_broadcast(dl->notifier_cv);
3412
0
            } else {
3413
0
                *generation = dl->notify_generation;
3414
0
                need_wait = 1;
3415
0
            }
3416
0
        }
3417
3418
0
        ossl_crypto_mutex_unlock(dl->mutex);
3419
0
    }
3420
3421
0
    return need_wait;
3422
0
}
3423
3424
void ossl_dtls_listener_wait_for_notifier_clear(SSL *s, uint64_t generation)
3425
0
{
3426
0
    DTLS_LISTENER *dl;
3427
3428
0
    if (!IS_DTLS_LISTENER(s))
3429
0
        return;
3430
3431
0
    dl = (DTLS_LISTENER *)s;
3432
0
    if (dl->have_notifier) {
3433
0
        ossl_crypto_mutex_lock(dl->mutex);
3434
0
        while (dl->signalled_notifier && dl->notify_generation == generation)
3435
0
            ossl_crypto_condvar_wait(dl->notifier_cv, dl->mutex);
3436
0
        ossl_crypto_mutex_unlock(dl->mutex);
3437
0
    }
3438
0
}
3439
3440
/* Combined leave for single-listener tests; poll cleanup uses both phases. */
3441
void ossl_dtls_listener_leave_blocking_section(SSL *s)
3442
0
{
3443
0
    uint64_t generation;
3444
3445
0
    if (ossl_dtls_listener_deregister_blocking_section(s, &generation))
3446
0
        ossl_dtls_listener_wait_for_notifier_clear(s, generation);
3447
0
}
3448
3449
int ossl_dtls_listener_poll_events(SSL *s, uint64_t events, int do_tick,
3450
    uint64_t *revents)
3451
0
{
3452
0
    DTLS_LISTENER *dl;
3453
0
    uint64_t result = 0;
3454
3455
0
    if (!ossl_assert(IS_DTLS_LISTENER(s)))
3456
0
        return 0;
3457
3458
0
    dl = (DTLS_LISTENER *)s;
3459
3460
0
    if (do_tick)
3461
0
        ossl_dtls_tick(dl);
3462
3463
0
    if ((events & SSL_POLL_EVENT_IC) != 0) {
3464
0
        if (SSL_get_accept_connection_queue_len(s) > 0)
3465
0
            result |= SSL_POLL_EVENT_IC;
3466
0
    }
3467
3468
0
    if ((events & SSL_POLL_EVENT_R) != 0) {
3469
0
        BIO *rbio = SSL_get_rbio(s);
3470
0
        if (rbio != NULL && BIO_pending(rbio) > 0)
3471
0
            result |= SSL_POLL_EVENT_R;
3472
0
    }
3473
3474
0
    *revents = result;
3475
0
    return 1;
3476
0
}
3477
3478
int ossl_dtls_conn_poll_events(SSL *s, uint64_t events, int do_tick,
3479
    uint64_t *revents)
3480
0
{
3481
0
    SSL_CONNECTION *sc;
3482
0
    uint64_t result = 0;
3483
0
    BIO_POLL_DESCRIPTOR desc;
3484
0
    int has_pending;
3485
3486
0
    sc = SSL_CONNECTION_FROM_SSL(s);
3487
0
    if (sc == NULL || sc->d1 == NULL)
3488
0
        return 0;
3489
3490
    /*
3491
     * For DTLS connections that came from a listener, data arrives via
3492
     * URXEs injected by the listener's demux. When do_tick is set and
3493
     * we have a listener reference, pump the demux to get new data.
3494
     */
3495
0
    if (do_tick && sc->d1->listener != NULL) {
3496
0
        DTLS_LISTENER *dl = (DTLS_LISTENER *)sc->d1->listener;
3497
0
        ossl_dtls_tick(dl);
3498
0
    }
3499
3500
    /*
3501
     * Handle events for the connection itself, which for DTLS means servicing
3502
     * the retransmission timer. The caller may have blocked until that timer
3503
     * expired, so if nothing retransmits here then nothing will, and the
3504
     * deadline would be recomputed as "now" on every subsequent wait.
3505
     *
3506
     * A failure here leaves the connection in a fatal error state, which the
3507
     * SSL_POLL_EVENT_EC check below reports.
3508
     */
3509
0
    if (do_tick)
3510
0
        SSL_handle_events(s);
3511
3512
0
    if ((events & SSL_POLL_EVENT_R) != 0) {
3513
        /*
3514
         * Application data buffered during a handshake cannot be read until
3515
         * the handshake finishes. Until then, reporting it would make
3516
         * SSL_poll() return immediately while SSL_read() keeps failing with
3517
         * SSL_ERROR_WANT_READ, so wait for the datagrams that complete the
3518
         * handshake instead.
3519
         */
3520
0
        if (RECORD_LAYER_processed_read_pending(&sc->rlayer)
3521
0
            || RECORD_LAYER_read_pending(&sc->rlayer)
3522
0
            || (SSL_is_init_finished(s)
3523
0
                && DTLS_RECORD_LAYER_buffered_app_data_pending(&sc->rlayer))) {
3524
0
            result |= SSL_POLL_EVENT_R;
3525
0
        } else if (sc->d1->rx != NULL) {
3526
            /* Listener-based connection: check URXE queue */
3527
0
            ossl_crypto_mutex_lock(sc->d1->rx->mutex);
3528
0
            has_pending = !ossl_list_urxe_is_empty(&sc->d1->rx->urxe_pending);
3529
0
            ossl_crypto_mutex_unlock(sc->d1->rx->mutex);
3530
0
            if (has_pending)
3531
0
                result |= SSL_POLL_EVENT_R;
3532
0
        } else {
3533
            /*
3534
             * Standalone DTLS SSL object (not from a listener).
3535
             * Check the underlying socket for readability.
3536
             */
3537
0
            BIO *rbio = SSL_get_rbio(s);
3538
3539
0
            if (rbio != NULL) {
3540
0
                if (BIO_get_rpoll_descriptor(rbio, &desc)
3541
0
                    && desc.type == BIO_POLL_DESCRIPTOR_TYPE_SOCK_FD
3542
0
                    && desc.value.fd >= 0) {
3543
0
                    if (BIO_socket_ready(desc.value.fd, 1) > 0)
3544
0
                        result |= SSL_POLL_EVENT_R;
3545
0
                } else {
3546
                    /* Checking non-socket BIO */
3547
0
                    if (BIO_pending(rbio) > 0)
3548
0
                        result |= SSL_POLL_EVENT_R;
3549
0
                }
3550
0
            }
3551
0
        }
3552
0
    }
3553
3554
0
    if ((events & SSL_POLL_EVENT_W) != 0) {
3555
0
        result |= SSL_POLL_EVENT_W;
3556
0
    }
3557
3558
0
    if ((events & (SSL_POLL_EVENT_EC | SSL_POLL_EVENT_F)) != 0) {
3559
0
        if (SSL_get_error(s, 0) == SSL_ERROR_SSL || SSL_get_shutdown(s) != 0)
3560
0
            result |= SSL_POLL_EVENT_EC;
3561
0
    }
3562
3563
0
    *revents = result;
3564
0
    return 1;
3565
0
}
3566
3567
#endif /* !OPENSSL_NO_DTLS && !OPENSSL_NO_SOCK */