Coverage Report

Created: 2026-08-31 06:56

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