Coverage Report

Created: 2026-11-16 07:12

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