Coverage Report

Created: 2026-10-16 07:31

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