Coverage Report

Created: 2026-04-08 06:20

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/openssl/ssl/statem/statem_dtls.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 <assert.h>
11
#include <limits.h>
12
#include <string.h>
13
#include <stdio.h>
14
#include "../ssl_local.h"
15
#include "statem_local.h"
16
#include "internal/cryptlib.h"
17
#include "internal/ssl_unwrap.h"
18
#include <openssl/buffer.h>
19
20
#define RSMBLY_BITMASK_SIZE(msg_len) (((msg_len) + 7) / 8)
21
22
#define RSMBLY_BITMASK_MARK(bitmask, start, end)                             \
23
0
    {                                                                        \
24
0
        if ((end) - (start) <= 8) {                                          \
25
0
            long ii;                                                         \
26
0
            for (ii = (start); ii < (end); ii++)                             \
27
0
                bitmask[((ii) >> 3)] |= (1 << ((ii) & 7));                   \
28
0
        } else {                                                             \
29
0
            long ii;                                                         \
30
0
            bitmask[((start) >> 3)] |= bitmask_start_values[((start) & 7)];  \
31
0
            for (ii = (((start) >> 3) + 1); ii < ((((end) - 1)) >> 3); ii++) \
32
0
                bitmask[ii] = 0xff;                                          \
33
0
            bitmask[(((end) - 1) >> 3)] |= bitmask_end_values[((end) & 7)];  \
34
0
        }                                                                    \
35
0
    }
36
37
#define RSMBLY_BITMASK_IS_COMPLETE(bitmask, msg_len, is_complete)                   \
38
0
    {                                                                               \
39
0
        long ii;                                                                    \
40
0
        is_complete = 1;                                                            \
41
0
        if (bitmask[(((msg_len) - 1) >> 3)] != bitmask_end_values[((msg_len) & 7)]) \
42
0
            is_complete = 0;                                                        \
43
0
        if (is_complete)                                                            \
44
0
            for (ii = (((msg_len) - 1) >> 3) - 1; ii >= 0; ii--)                    \
45
0
                if (bitmask[ii] != 0xff) {                                          \
46
0
                    is_complete = 0;                                                \
47
0
                    break;                                                          \
48
0
                }                                                                   \
49
0
    }
50
51
static const unsigned char bitmask_start_values[] = {
52
    0xff, 0xfe, 0xfc, 0xf8, 0xf0, 0xe0, 0xc0, 0x80
53
};
54
static const unsigned char bitmask_end_values[] = {
55
    0xff, 0x01, 0x03, 0x07, 0x0f, 0x1f, 0x3f, 0x7f
56
};
57
58
static void dtls1_fix_message_header(SSL_CONNECTION *s, size_t frag_off,
59
    size_t frag_len);
60
static unsigned char *dtls1_write_message_header(SSL_CONNECTION *s,
61
    unsigned char *p);
62
static void dtls1_set_message_header_int(SSL_CONNECTION *s, unsigned char mt,
63
    size_t len,
64
    unsigned short seq_num,
65
    size_t frag_off,
66
    size_t frag_len);
67
static int dtls_get_reassembled_message(SSL_CONNECTION *s, int *errtype,
68
    size_t *len);
69
70
/*
71
 * Check if CCS is expected in current state.
72
 *
73
 * RFC 6347 Section 4.1 states DTLS must handle message reordering since UDP
74
 * does not guarantee in-order delivery. This function determines when a
75
 * buffered CCS should be delivered to the state machine.
76
 *
77
 * Server states where CCS is expected:
78
 *   - TLS_ST_SR_KEY_EXCH: After key exchange (anonymous or no_cert_verify)
79
 *   - TLS_ST_SR_CERT_VRFY: After certificate verify
80
 *   - TLS_ST_SW_FINISHED: Session resumption (abbreviated handshake)
81
 *
82
 * Client states where CCS is expected:
83
 *   - TLS_ST_CR_SRVR_HELLO: Abbreviated handshake without ticket
84
 *   - TLS_ST_CW_FINISHED: After sending Finished, before server CCS
85
 *   - TLS_ST_CR_SESSION_TICKET: After receiving session ticket
86
 */
87
static int dtls_ccs_expected(SSL_CONNECTION *s)
88
0
{
89
0
    OSSL_HANDSHAKE_STATE st = s->statem.hand_state;
90
91
0
    if (s->server) {
92
0
        switch (st) {
93
0
        case TLS_ST_SR_KEY_EXCH:
94
            /* Anonymous or no client cert: CCS follows KeyExchange */
95
0
            if (s->session->peer == NULL && s->session->peer_rpk == NULL)
96
0
                return 1;
97
            /* Client cert but no verify message required */
98
0
            return s->statem.no_cert_verify;
99
0
        case TLS_ST_SR_CERT_VRFY:
100
0
            return 1;
101
0
        case TLS_ST_SW_FINISHED:
102
            /* Abbreviated handshake: server sends first, then receives CCS */
103
0
            return s->hit;
104
0
        default:
105
0
            return 0;
106
0
        }
107
0
    } else {
108
0
        switch (st) {
109
0
        case TLS_ST_CR_SRVR_HELLO:
110
            /* Abbreviated handshake without session ticket */
111
0
            return (s->hit && !s->ext.ticket_expected);
112
0
        case TLS_ST_CW_FINISHED:
113
            /* Full handshake: waiting for server CCS after sending Finished */
114
0
            return !s->ext.ticket_expected;
115
0
        case TLS_ST_CR_SESSION_TICKET:
116
0
            return 1;
117
0
        default:
118
0
            return 0;
119
0
        }
120
0
    }
121
0
}
122
123
static hm_fragment *dtls1_hm_fragment_new(size_t frag_len, int reassembly)
124
0
{
125
0
    hm_fragment *frag = NULL;
126
0
    unsigned char *buf = NULL;
127
0
    unsigned char *bitmask = NULL;
128
129
0
    if ((frag = OPENSSL_zalloc(sizeof(*frag))) == NULL)
130
0
        return NULL;
131
132
0
    if (frag_len) {
133
0
        if ((buf = OPENSSL_malloc(frag_len)) == NULL) {
134
0
            OPENSSL_free(frag);
135
0
            return NULL;
136
0
        }
137
0
    }
138
139
    /* zero length fragment gets zero frag->fragment */
140
0
    frag->fragment = buf;
141
142
    /* Initialize reassembly bitmask if necessary */
143
0
    if (reassembly) {
144
0
        bitmask = OPENSSL_zalloc(RSMBLY_BITMASK_SIZE(frag_len));
145
0
        if (bitmask == NULL) {
146
0
            OPENSSL_free(buf);
147
0
            OPENSSL_free(frag);
148
0
            return NULL;
149
0
        }
150
0
    }
151
152
0
    frag->reassembly = bitmask;
153
154
0
    return frag;
155
0
}
156
157
void dtls1_hm_fragment_free(hm_fragment *frag)
158
0
{
159
0
    if (!frag)
160
0
        return;
161
162
0
    OPENSSL_free(frag->fragment);
163
0
    OPENSSL_free(frag->reassembly);
164
0
    OPENSSL_free(frag);
165
0
}
166
167
/*
168
 * send s->init_buf in records of type 'type' (SSL3_RT_HANDSHAKE or
169
 * SSL3_RT_CHANGE_CIPHER_SPEC)
170
 */
171
int dtls1_do_write(SSL_CONNECTION *s, uint8_t type)
172
0
{
173
0
    int ret;
174
0
    size_t written;
175
0
    size_t curr_mtu;
176
0
    int retry = 1;
177
0
    size_t len, frag_off, overhead, used_len;
178
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
179
0
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
180
0
    uint8_t saved_payload[DTLS1_HM_HEADER_LENGTH];
181
182
0
    if (!dtls1_query_mtu(s))
183
0
        return -1;
184
185
0
    if (s->d1->mtu < dtls1_min_mtu(s))
186
        /* should have something reasonable now */
187
0
        return -1;
188
189
0
    if (s->init_off == 0 && type == SSL3_RT_HANDSHAKE) {
190
0
        if (!ossl_assert(s->init_num == s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH))
191
0
            return -1;
192
0
    }
193
194
0
    overhead = s->rlayer.wrlmethod->get_max_record_overhead(s->rlayer.wrl);
195
196
0
    frag_off = 0;
197
0
    s->rwstate = SSL_NOTHING;
198
199
    /* s->init_num shouldn't ever be < 0...but just in case */
200
0
    while (s->init_num > 0) {
201
0
        if (type == SSL3_RT_HANDSHAKE && s->init_off != 0) {
202
            /* We must be writing a fragment other than the first one */
203
204
0
            if (frag_off > 0) {
205
                /* This is the first attempt at writing out this fragment */
206
207
0
                if (s->init_off <= DTLS1_HM_HEADER_LENGTH) {
208
                    /*
209
                     * Each fragment that was already sent must at least have
210
                     * contained the message header plus one other byte.
211
                     * Therefore |init_off| must have progressed by at least
212
                     * |DTLS1_HM_HEADER_LENGTH + 1| bytes. If not something went
213
                     * wrong.
214
                     */
215
0
                    return -1;
216
0
                }
217
218
                /*
219
                 * Adjust |init_off| and |init_num| to allow room for a new
220
                 * message header for this fragment.
221
                 */
222
0
                s->init_off -= DTLS1_HM_HEADER_LENGTH;
223
0
                s->init_num += DTLS1_HM_HEADER_LENGTH;
224
0
            } else {
225
                /*
226
                 * We must have been called again after a retry so use the
227
                 * fragment offset from our last attempt. We do not need
228
                 * to adjust |init_off| and |init_num| as above, because
229
                 * that should already have been done before the retry.
230
                 */
231
0
                frag_off = s->d1->w_msg_hdr.frag_off;
232
0
            }
233
0
        }
234
235
0
        used_len = BIO_wpending(s->wbio) + overhead;
236
0
        if (s->d1->mtu > used_len)
237
0
            curr_mtu = s->d1->mtu - used_len;
238
0
        else
239
0
            curr_mtu = 0;
240
241
0
        if (curr_mtu <= DTLS1_HM_HEADER_LENGTH) {
242
            /*
243
             * grr.. we could get an error if MTU picked was wrong
244
             */
245
0
            ret = BIO_flush(s->wbio);
246
0
            if (ret <= 0) {
247
0
                s->rwstate = SSL_WRITING;
248
0
                return ret;
249
0
            }
250
0
            if (s->d1->mtu > overhead + DTLS1_HM_HEADER_LENGTH) {
251
0
                curr_mtu = s->d1->mtu - overhead;
252
0
            } else {
253
                /* Shouldn't happen */
254
0
                return -1;
255
0
            }
256
0
        }
257
258
        /*
259
         * We just checked that s->init_num > 0 so this cast should be safe
260
         */
261
0
        if (((unsigned int)s->init_num) > curr_mtu)
262
0
            len = curr_mtu;
263
0
        else
264
0
            len = s->init_num;
265
266
0
        if (len > ssl_get_max_send_fragment(s))
267
0
            len = ssl_get_max_send_fragment(s);
268
269
        /*
270
         * XDTLS: this function is too long.  split out the CCS part
271
         */
272
0
        if (type == SSL3_RT_HANDSHAKE) {
273
0
            if (len < DTLS1_HM_HEADER_LENGTH) {
274
                /*
275
                 * len is so small that we really can't do anything sensible
276
                 * so fail
277
                 */
278
0
                return -1;
279
0
            }
280
0
            dtls1_fix_message_header(s, frag_off, len - DTLS1_HM_HEADER_LENGTH);
281
282
            /*
283
             * Save the data that will be overwritten by
284
             * dtls1_write_messsage_header so no corruption occurs when using
285
             * a msg callback.
286
             */
287
0
            if (s->msg_callback && s->init_off != 0)
288
0
                memcpy(saved_payload, &s->init_buf->data[s->init_off],
289
0
                    sizeof(saved_payload));
290
291
0
            dtls1_write_message_header(s,
292
0
                (unsigned char *)&s->init_buf->data[s->init_off]);
293
0
        }
294
295
0
        ret = dtls1_write_bytes(s, type, &s->init_buf->data[s->init_off], len,
296
0
            &written);
297
298
0
        if (type == SSL3_RT_HANDSHAKE && s->msg_callback && s->init_off != 0)
299
0
            memcpy(&s->init_buf->data[s->init_off], saved_payload,
300
0
                sizeof(saved_payload));
301
302
0
        if (ret <= 0) {
303
            /*
304
             * might need to update MTU here, but we don't know which
305
             * previous packet caused the failure -- so can't really
306
             * retransmit anything.  continue as if everything is fine and
307
             * wait for an alert to handle the retransmit
308
             */
309
0
            if (retry && BIO_ctrl(SSL_get_wbio(ssl), BIO_CTRL_DGRAM_MTU_EXCEEDED, 0, NULL) > 0) {
310
0
                if (!(SSL_get_options(ssl) & SSL_OP_NO_QUERY_MTU)) {
311
0
                    if (!dtls1_query_mtu(s))
312
0
                        return -1;
313
                    /* Have one more go */
314
0
                    retry = 0;
315
0
                } else
316
0
                    return -1;
317
0
            } else {
318
0
                return -1;
319
0
            }
320
0
        } else {
321
322
            /*
323
             * bad if this assert fails, only part of the handshake message
324
             * got sent.  but why would this happen?
325
             */
326
0
            if (!ossl_assert(len == written))
327
0
                return -1;
328
329
            /*
330
             * We should not exceed the MTU size. If compression is in use
331
             * then the max record overhead calculation is unreliable so we do
332
             * not check in that case. We use assert rather than ossl_assert
333
             * because in a production build, if this assert were ever to fail,
334
             * then the best thing to do is probably carry on regardless.
335
             */
336
0
            assert(s->s3.tmp.new_compression != NULL
337
0
                || BIO_wpending(s->wbio) <= (int)s->d1->mtu);
338
339
0
            if (type == SSL3_RT_HANDSHAKE && !s->d1->retransmitting) {
340
                /*
341
                 * should not be done for 'Hello Request's, but in that case
342
                 * we'll ignore the result anyway
343
                 */
344
0
                unsigned char *p = (unsigned char *)&s->init_buf->data[s->init_off];
345
0
                const struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
346
0
                size_t xlen;
347
348
0
                if (frag_off == 0 && s->version != DTLS1_BAD_VER) {
349
                    /*
350
                     * reconstruct message header is if it is being sent in
351
                     * single fragment
352
                     */
353
0
                    *p++ = msg_hdr->type;
354
0
                    l2n3(msg_hdr->msg_len, p);
355
0
                    s2n(msg_hdr->seq, p);
356
0
                    l2n3(0, p);
357
0
                    l2n3(msg_hdr->msg_len, p);
358
0
                    p -= DTLS1_HM_HEADER_LENGTH;
359
0
                    xlen = written;
360
0
                } else {
361
0
                    p += DTLS1_HM_HEADER_LENGTH;
362
0
                    xlen = written - DTLS1_HM_HEADER_LENGTH;
363
0
                }
364
365
0
                if (!ssl3_finish_mac(s, p, xlen))
366
0
                    return -1;
367
0
            }
368
369
0
            if (written == s->init_num) {
370
0
                if (s->msg_callback)
371
0
                    s->msg_callback(1, s->version, type, s->init_buf->data,
372
0
                        s->init_off + s->init_num, ussl,
373
0
                        s->msg_callback_arg);
374
375
0
                s->init_off = 0; /* done writing this message */
376
0
                s->init_num = 0;
377
378
0
                return 1;
379
0
            }
380
0
            s->init_off += written;
381
0
            s->init_num -= written;
382
0
            written -= DTLS1_HM_HEADER_LENGTH;
383
0
            frag_off += written;
384
385
            /*
386
             * We save the fragment offset for the next fragment so we have it
387
             * available in case of an IO retry. We don't know the length of the
388
             * next fragment yet so just set that to 0 for now. It will be
389
             * updated again later.
390
             */
391
0
            dtls1_fix_message_header(s, frag_off, 0);
392
0
        }
393
0
    }
394
0
    return 0;
395
0
}
396
397
int dtls_get_message(SSL_CONNECTION *s, int *mt)
398
0
{
399
0
    struct hm_header_st *msg_hdr;
400
0
    unsigned char *p;
401
0
    size_t msg_len;
402
0
    size_t tmplen;
403
0
    int errtype;
404
405
0
    msg_hdr = &s->d1->r_msg_hdr;
406
0
    memset(msg_hdr, 0, sizeof(*msg_hdr));
407
408
0
again:
409
0
    if (!dtls_get_reassembled_message(s, &errtype, &tmplen)) {
410
0
        if (errtype == DTLS1_HM_BAD_FRAGMENT
411
0
            || errtype == DTLS1_HM_FRAGMENT_RETRY) {
412
            /* bad fragment received */
413
0
            goto again;
414
0
        }
415
0
        return 0;
416
0
    }
417
418
0
    *mt = s->s3.tmp.message_type;
419
420
0
    p = (unsigned char *)s->init_buf->data;
421
422
0
    if (*mt == SSL3_MT_CHANGE_CIPHER_SPEC) {
423
0
        if (s->msg_callback) {
424
0
            s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
425
0
                p, 1, SSL_CONNECTION_GET_USER_SSL(s),
426
0
                s->msg_callback_arg);
427
0
        }
428
        /*
429
         * This isn't a real handshake message so skip the processing below.
430
         */
431
0
        return 1;
432
0
    }
433
434
0
    msg_len = msg_hdr->msg_len;
435
436
    /* reconstruct message header */
437
0
    *(p++) = msg_hdr->type;
438
0
    l2n3(msg_len, p);
439
0
    s2n(msg_hdr->seq, p);
440
0
    l2n3(0, p);
441
0
    l2n3(msg_len, p);
442
443
0
    memset(msg_hdr, 0, sizeof(*msg_hdr));
444
445
0
    s->d1->handshake_read_seq++;
446
447
0
    s->init_msg = s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
448
449
0
    return 1;
450
0
}
451
452
/*
453
 * Actually we already have the message body - but this is an opportunity for
454
 * DTLS to do any further processing it wants at the same point that TLS would
455
 * be asked for the message body.
456
 */
457
int dtls_get_message_body(SSL_CONNECTION *s, size_t *len)
458
0
{
459
0
    unsigned char *msg = (unsigned char *)s->init_buf->data;
460
0
    size_t msg_len = s->init_num + DTLS1_HM_HEADER_LENGTH;
461
462
0
    if (s->s3.tmp.message_type == SSL3_MT_CHANGE_CIPHER_SPEC) {
463
        /* Nothing to be done */
464
0
        goto end;
465
0
    }
466
    /*
467
     * If receiving Finished, record MAC of prior handshake messages for
468
     * Finished verification.
469
     */
470
0
    if (*(s->init_buf->data) == SSL3_MT_FINISHED && !ssl3_take_mac(s)) {
471
        /* SSLfatal() already called */
472
0
        return 0;
473
0
    }
474
475
0
    if (s->version == DTLS1_BAD_VER) {
476
0
        msg += DTLS1_HM_HEADER_LENGTH;
477
0
        msg_len -= DTLS1_HM_HEADER_LENGTH;
478
0
    }
479
480
0
    if (!ssl3_finish_mac(s, msg, msg_len))
481
0
        return 0;
482
483
0
    if (s->msg_callback)
484
0
        s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
485
0
            s->init_buf->data, s->init_num + DTLS1_HM_HEADER_LENGTH,
486
0
            SSL_CONNECTION_GET_USER_SSL(s), s->msg_callback_arg);
487
488
0
end:
489
0
    *len = s->init_num;
490
0
    return 1;
491
0
}
492
493
/*
494
 * dtls1_max_handshake_message_len returns the maximum number of bytes
495
 * permitted in a DTLS handshake message for |s|. The minimum is 16KB, but
496
 * may be greater if the maximum certificate list size requires it.
497
 */
498
static size_t dtls1_max_handshake_message_len(const SSL_CONNECTION *s)
499
0
{
500
0
    size_t max_len = DTLS1_HM_HEADER_LENGTH + SSL3_RT_MAX_ENCRYPTED_LENGTH;
501
0
    if (max_len < s->max_cert_list)
502
0
        return s->max_cert_list;
503
0
    return max_len;
504
0
}
505
506
static int dtls1_preprocess_fragment(SSL_CONNECTION *s,
507
    struct hm_header_st *msg_hdr)
508
0
{
509
0
    size_t frag_off, frag_len, msg_len;
510
511
0
    msg_len = msg_hdr->msg_len;
512
0
    frag_off = msg_hdr->frag_off;
513
0
    frag_len = msg_hdr->frag_len;
514
515
    /* sanity checking */
516
0
    if ((frag_off + frag_len) > msg_len
517
0
        || msg_len > dtls1_max_handshake_message_len(s)) {
518
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
519
0
        return 0;
520
0
    }
521
522
0
    if (s->d1->r_msg_hdr.frag_off == 0) { /* first fragment */
523
        /*
524
         * msg_len is limited to 2^24, but is effectively checked against
525
         * dtls_max_handshake_message_len(s) above
526
         */
527
0
        if (!BUF_MEM_grow_clean(s->init_buf, msg_len + DTLS1_HM_HEADER_LENGTH)) {
528
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_BUF_LIB);
529
0
            return 0;
530
0
        }
531
532
0
        s->s3.tmp.message_size = msg_len;
533
0
        s->d1->r_msg_hdr.msg_len = msg_len;
534
0
        s->s3.tmp.message_type = msg_hdr->type;
535
0
        s->d1->r_msg_hdr.type = msg_hdr->type;
536
0
        s->d1->r_msg_hdr.seq = msg_hdr->seq;
537
0
    } else if (msg_len != s->d1->r_msg_hdr.msg_len) {
538
        /*
539
         * They must be playing with us! BTW, failure to enforce upper limit
540
         * would open possibility for buffer overrun.
541
         */
542
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_EXCESSIVE_MESSAGE_SIZE);
543
0
        return 0;
544
0
    }
545
546
0
    return 1;
547
0
}
548
549
/*
550
 * Returns 1 if there is a buffered fragment available, 0 if not, or -1 on a
551
 * fatal error.
552
 */
553
static int dtls1_retrieve_buffered_fragment(SSL_CONNECTION *s, size_t *len)
554
0
{
555
    /*-
556
     * (0) check whether the desired fragment is available
557
     * if so:
558
     * (1) copy over the fragment to s->init_buf->data[]
559
     * (2) update s->init_num
560
     */
561
0
    pitem *item;
562
0
    piterator iter;
563
0
    hm_fragment *frag;
564
0
    int ret;
565
0
    int chretran = 0;
566
567
0
    iter = pqueue_iterator(s->d1->buffered_messages);
568
0
    do {
569
0
        item = pqueue_next(&iter);
570
0
        if (item == NULL)
571
0
            return 0;
572
573
0
        frag = (hm_fragment *)item->data;
574
575
0
        if (frag->msg_header.seq < s->d1->handshake_read_seq) {
576
0
            pitem *next;
577
0
            hm_fragment *nextfrag;
578
579
0
            if (!s->server
580
0
                || frag->msg_header.seq != 0
581
0
                || s->d1->handshake_read_seq != 1
582
0
                || s->statem.hand_state != DTLS_ST_SW_HELLO_VERIFY_REQUEST) {
583
                /*
584
                 * This is a stale message that has been buffered so clear it.
585
                 * It is safe to pop this message from the queue even though
586
                 * we have an active iterator
587
                 */
588
0
                pqueue_pop(s->d1->buffered_messages);
589
0
                dtls1_hm_fragment_free(frag);
590
0
                pitem_free(item);
591
0
                item = NULL;
592
0
                frag = NULL;
593
0
            } else {
594
                /*
595
                 * We have fragments for a ClientHello without a cookie,
596
                 * even though we have sent a HelloVerifyRequest. It is possible
597
                 * that the HelloVerifyRequest got lost and this is a
598
                 * retransmission of the original ClientHello
599
                 */
600
0
                next = pqueue_next(&iter);
601
0
                if (next != NULL) {
602
0
                    nextfrag = (hm_fragment *)next->data;
603
0
                    if (nextfrag->msg_header.seq == s->d1->handshake_read_seq) {
604
                        /*
605
                         * We have fragments for both a ClientHello without
606
                         * cookie and one with. Ditch the one without.
607
                         */
608
0
                        pqueue_pop(s->d1->buffered_messages);
609
0
                        dtls1_hm_fragment_free(frag);
610
0
                        pitem_free(item);
611
0
                        item = next;
612
0
                        frag = nextfrag;
613
0
                    } else {
614
0
                        chretran = 1;
615
0
                    }
616
0
                } else {
617
0
                    chretran = 1;
618
0
                }
619
0
            }
620
0
        }
621
0
    } while (item == NULL);
622
623
    /* Don't return if reassembly still in progress */
624
0
    if (frag->reassembly != NULL)
625
0
        return 0;
626
627
0
    if (s->d1->handshake_read_seq == frag->msg_header.seq || chretran) {
628
0
        size_t frag_len = frag->msg_header.frag_len;
629
0
        pqueue_pop(s->d1->buffered_messages);
630
631
        /* Calls SSLfatal() as required */
632
0
        ret = dtls1_preprocess_fragment(s, &frag->msg_header);
633
634
0
        if (ret && frag->msg_header.frag_len > 0) {
635
0
            unsigned char *p = (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
636
0
            memcpy(&p[frag->msg_header.frag_off], frag->fragment,
637
0
                frag->msg_header.frag_len);
638
0
        }
639
640
0
        dtls1_hm_fragment_free(frag);
641
0
        pitem_free(item);
642
643
0
        if (ret) {
644
0
            if (chretran) {
645
                /*
646
                 * We got a new ClientHello with a message sequence of 0.
647
                 * Reset the read/write sequences back to the beginning.
648
                 * We process it like this is the first time we've seen a
649
                 * ClientHello from the client.
650
                 */
651
0
                s->d1->handshake_read_seq = 0;
652
0
                s->d1->next_handshake_write_seq = 0;
653
0
            }
654
0
            *len = frag_len;
655
0
            return 1;
656
0
        }
657
658
        /* Fatal error */
659
0
        s->init_num = 0;
660
0
        return -1;
661
0
    } else {
662
0
        return 0;
663
0
    }
664
0
}
665
666
static int dtls1_reassemble_fragment(SSL_CONNECTION *s,
667
    const struct hm_header_st *msg_hdr)
668
0
{
669
0
    hm_fragment *frag = NULL;
670
0
    pitem *item = NULL;
671
0
    int i = -1, is_complete;
672
0
    unsigned char seq64be[8];
673
0
    size_t frag_len = msg_hdr->frag_len;
674
0
    size_t readbytes;
675
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
676
677
0
    if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len || msg_hdr->msg_len > dtls1_max_handshake_message_len(s))
678
0
        goto err;
679
680
0
    if (frag_len == 0) {
681
0
        return DTLS1_HM_FRAGMENT_RETRY;
682
0
    }
683
684
    /* Try to find item in queue */
685
0
    memset(seq64be, 0, sizeof(seq64be));
686
0
    seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
687
0
    seq64be[7] = (unsigned char)msg_hdr->seq;
688
0
    item = pqueue_find(s->d1->buffered_messages, seq64be);
689
690
0
    if (item == NULL) {
691
0
        frag = dtls1_hm_fragment_new(msg_hdr->msg_len, 1);
692
0
        if (frag == NULL)
693
0
            goto err;
694
0
        memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
695
0
        frag->msg_header.frag_len = frag->msg_header.msg_len;
696
0
        frag->msg_header.frag_off = 0;
697
0
    } else {
698
0
        frag = (hm_fragment *)item->data;
699
0
        if (frag->msg_header.msg_len != msg_hdr->msg_len) {
700
0
            item = NULL;
701
0
            frag = NULL;
702
0
            goto err;
703
0
        }
704
0
    }
705
706
    /*
707
     * If message is already reassembled, this must be a retransmit and can
708
     * be dropped. In this case item != NULL and so frag does not need to be
709
     * freed.
710
     */
711
0
    if (frag->reassembly == NULL) {
712
0
        unsigned char devnull[256];
713
714
0
        while (frag_len) {
715
0
            i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
716
0
                devnull,
717
0
                frag_len > sizeof(devnull) ? sizeof(devnull) : frag_len, 0, &readbytes);
718
0
            if (i <= 0)
719
0
                goto err;
720
0
            frag_len -= readbytes;
721
0
        }
722
0
        return DTLS1_HM_FRAGMENT_RETRY;
723
0
    }
724
725
    /* read the body of the fragment (header has already been read */
726
0
    i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
727
0
        frag->fragment + msg_hdr->frag_off,
728
0
        frag_len, 0, &readbytes);
729
0
    if (i <= 0 || readbytes != frag_len)
730
0
        i = -1;
731
0
    if (i <= 0)
732
0
        goto err;
733
734
0
    RSMBLY_BITMASK_MARK(frag->reassembly, (long)msg_hdr->frag_off,
735
0
        (long)(msg_hdr->frag_off + frag_len));
736
737
0
    if (!ossl_assert(msg_hdr->msg_len > 0))
738
0
        goto err;
739
0
    RSMBLY_BITMASK_IS_COMPLETE(frag->reassembly, (long)msg_hdr->msg_len,
740
0
        is_complete);
741
742
0
    if (is_complete) {
743
0
        OPENSSL_free(frag->reassembly);
744
0
        frag->reassembly = NULL;
745
0
    }
746
747
0
    if (item == NULL) {
748
0
        item = pitem_new(seq64be, frag);
749
0
        if (item == NULL) {
750
0
            i = -1;
751
0
            goto err;
752
0
        }
753
754
0
        item = pqueue_insert(s->d1->buffered_messages, item);
755
        /*
756
         * pqueue_insert fails iff a duplicate item is inserted. However,
757
         * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
758
         * would have returned it and control would never have reached this
759
         * branch.
760
         */
761
0
        if (!ossl_assert(item != NULL))
762
0
            goto err;
763
0
    }
764
765
0
    return DTLS1_HM_FRAGMENT_RETRY;
766
767
0
err:
768
0
    if (item == NULL)
769
0
        dtls1_hm_fragment_free(frag);
770
0
    return -1;
771
0
}
772
773
static int dtls1_process_out_of_seq_message(SSL_CONNECTION *s,
774
    const struct hm_header_st *msg_hdr)
775
0
{
776
0
    int i = -1;
777
0
    hm_fragment *frag = NULL;
778
0
    pitem *item = NULL;
779
0
    unsigned char seq64be[8];
780
0
    size_t frag_len = msg_hdr->frag_len;
781
0
    size_t readbytes;
782
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
783
784
0
    if ((msg_hdr->frag_off + frag_len) > msg_hdr->msg_len)
785
0
        goto err;
786
787
    /* Try to find item in queue, to prevent duplicate entries */
788
0
    memset(seq64be, 0, sizeof(seq64be));
789
0
    seq64be[6] = (unsigned char)(msg_hdr->seq >> 8);
790
0
    seq64be[7] = (unsigned char)msg_hdr->seq;
791
0
    item = pqueue_find(s->d1->buffered_messages, seq64be);
792
793
    /*
794
     * If we already have an entry and this one is a fragment, don't discard
795
     * it and rather try to reassemble it.
796
     */
797
0
    if (item != NULL && frag_len != msg_hdr->msg_len)
798
0
        item = NULL;
799
800
    /*
801
     * Discard the message if sequence number was already there, is too far
802
     * in the future, already in the queue or if we received a FINISHED
803
     * before the SERVER_HELLO, which then must be a stale retransmit.
804
     */
805
0
    if (msg_hdr->seq <= s->d1->handshake_read_seq || msg_hdr->seq > s->d1->handshake_read_seq + 10 || item != NULL || (s->d1->handshake_read_seq == 0 && msg_hdr->type == SSL3_MT_FINISHED)) {
806
0
        unsigned char devnull[256];
807
808
0
        while (frag_len) {
809
0
            i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
810
0
                devnull,
811
0
                frag_len > sizeof(devnull) ? sizeof(devnull) : frag_len, 0, &readbytes);
812
0
            if (i <= 0)
813
0
                goto err;
814
0
            frag_len -= readbytes;
815
0
        }
816
0
    } else {
817
0
        if (frag_len != msg_hdr->msg_len) {
818
0
            return dtls1_reassemble_fragment(s, msg_hdr);
819
0
        }
820
821
0
        if (frag_len > dtls1_max_handshake_message_len(s))
822
0
            goto err;
823
824
0
        frag = dtls1_hm_fragment_new(frag_len, 0);
825
0
        if (frag == NULL)
826
0
            goto err;
827
828
0
        memcpy(&(frag->msg_header), msg_hdr, sizeof(*msg_hdr));
829
830
0
        if (frag_len) {
831
            /*
832
             * read the body of the fragment (header has already been read
833
             */
834
0
            i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
835
0
                frag->fragment, frag_len, 0,
836
0
                &readbytes);
837
0
            if (i <= 0 || readbytes != frag_len)
838
0
                i = -1;
839
0
            if (i <= 0)
840
0
                goto err;
841
0
        }
842
843
0
        item = pitem_new(seq64be, frag);
844
0
        if (item == NULL)
845
0
            goto err;
846
847
0
        item = pqueue_insert(s->d1->buffered_messages, item);
848
        /*
849
         * pqueue_insert fails iff a duplicate item is inserted. However,
850
         * |item| cannot be a duplicate. If it were, |pqueue_find|, above,
851
         * would have returned it. Then, either |frag_len| !=
852
         * |msg_hdr->msg_len| in which case |item| is set to NULL and it will
853
         * have been processed with |dtls1_reassemble_fragment|, above, or
854
         * the record will have been discarded.
855
         */
856
0
        if (!ossl_assert(item != NULL))
857
0
            goto err;
858
0
    }
859
860
0
    return DTLS1_HM_FRAGMENT_RETRY;
861
862
0
err:
863
0
    if (item == NULL)
864
0
        dtls1_hm_fragment_free(frag);
865
0
    return 0;
866
0
}
867
868
static int dtls_get_reassembled_message(SSL_CONNECTION *s, int *errtype,
869
    size_t *len)
870
0
{
871
0
    size_t mlen, frag_off, frag_len;
872
0
    int i, ret;
873
0
    uint8_t recvd_type;
874
0
    struct hm_header_st msg_hdr;
875
0
    size_t readbytes;
876
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
877
0
    SSL *ussl = SSL_CONNECTION_GET_USER_SSL(s);
878
0
    int chretran = 0;
879
0
    unsigned char *p;
880
881
0
    *errtype = 0;
882
883
0
    p = (unsigned char *)s->init_buf->data;
884
885
0
redo:
886
    /* Check for buffered CCS */
887
0
    if ((s->version == DTLS1_VERSION || s->version == DTLS1_2_VERSION
888
0
            || s->version == DTLS1_BAD_VER)
889
0
        && s->d1->has_change_cipher_spec && dtls_ccs_expected(s)) {
890
0
        size_t extra = (s->version == DTLS1_BAD_VER) ? 2 : 0;
891
892
0
        s->d1->has_change_cipher_spec = 0;
893
0
        p[0] = SSL3_MT_CCS;
894
        /*
895
         * The extra 2 bytes are never consumed, only checked for
896
         * length -- zero-fill to avoid old init_buf content.
897
         */
898
0
        if (extra > 0)
899
0
            memset(p + 1, 0, extra);
900
0
        s->init_num = extra;
901
0
        s->init_msg = p + 1;
902
0
        s->s3.tmp.message_type = SSL3_MT_CHANGE_CIPHER_SPEC;
903
0
        s->s3.tmp.message_size = extra;
904
0
        *len = extra;
905
0
        return 1;
906
0
    }
907
908
    /* see if we have the required fragment already */
909
0
    ret = dtls1_retrieve_buffered_fragment(s, &frag_len);
910
0
    if (ret < 0) {
911
        /* SSLfatal() already called */
912
0
        return 0;
913
0
    }
914
0
    if (ret > 0) {
915
0
        s->init_num = frag_len;
916
0
        *len = frag_len;
917
0
        return 1;
918
0
    }
919
920
    /* read handshake message header */
921
0
    i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, &recvd_type, p,
922
0
        DTLS1_HM_HEADER_LENGTH, 0, &readbytes);
923
0
    if (i <= 0) { /* nbio, or an error */
924
0
        s->rwstate = SSL_READING;
925
0
        *len = 0;
926
0
        return 0;
927
0
    }
928
0
    if (recvd_type == SSL3_RT_CHANGE_CIPHER_SPEC) {
929
0
        if (p[0] != SSL3_MT_CCS) {
930
0
            SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
931
0
                SSL_R_BAD_CHANGE_CIPHER_SPEC);
932
0
            goto f_err;
933
0
        }
934
935
        /* Buffer CCS for reorder tolerance */
936
0
        if (s->version == DTLS1_VERSION || s->version == DTLS1_2_VERSION
937
0
            || s->version == DTLS1_BAD_VER) {
938
0
            size_t expected = (s->version == DTLS1_BAD_VER) ? 3 : 1;
939
940
0
            if (readbytes != expected) {
941
0
                SSLfatal(s, SSL_AD_DECODE_ERROR,
942
0
                    SSL_R_BAD_CHANGE_CIPHER_SPEC);
943
0
                goto f_err;
944
0
            }
945
0
            s->d1->has_change_cipher_spec = 1;
946
0
            goto redo;
947
0
        }
948
0
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
949
0
            SSL_R_BAD_CHANGE_CIPHER_SPEC);
950
0
        goto f_err;
951
0
    }
952
953
    /* Handshake fails if message header is incomplete */
954
0
    if (readbytes != DTLS1_HM_HEADER_LENGTH) {
955
0
        SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
956
0
        goto f_err;
957
0
    }
958
959
    /* parse the message fragment header */
960
0
    dtls1_get_message_header(p, &msg_hdr);
961
962
0
    mlen = msg_hdr.msg_len;
963
0
    frag_off = msg_hdr.frag_off;
964
0
    frag_len = msg_hdr.frag_len;
965
966
    /*
967
     * We must have at least frag_len bytes left in the record to be read.
968
     * Fragments must not span records.
969
     */
970
0
    if (frag_len > s->rlayer.tlsrecs[s->rlayer.curr_rec].length) {
971
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_LENGTH);
972
0
        goto f_err;
973
0
    }
974
975
    /*
976
     * if this is a future (or stale) message it gets buffered
977
     * (or dropped)--no further processing at this time
978
     * While listening, we accept seq 1 (ClientHello with cookie)
979
     * although we're still expecting seq 0 (ClientHello)
980
     */
981
0
    if (msg_hdr.seq != s->d1->handshake_read_seq) {
982
0
        if (!s->server
983
0
            || msg_hdr.seq != 0
984
0
            || s->d1->handshake_read_seq != 1
985
0
            || p[0] != SSL3_MT_CLIENT_HELLO
986
0
            || s->statem.hand_state != DTLS_ST_SW_HELLO_VERIFY_REQUEST) {
987
0
            *errtype = dtls1_process_out_of_seq_message(s, &msg_hdr);
988
0
            return 0;
989
0
        }
990
        /*
991
         * We received a ClientHello and sent back a HelloVerifyRequest. We
992
         * now seem to have received a retransmitted initial ClientHello. That
993
         * is allowed (possibly our HelloVerifyRequest got lost).
994
         */
995
0
        chretran = 1;
996
0
    }
997
998
0
    if (frag_len && frag_len < mlen) {
999
0
        *errtype = dtls1_reassemble_fragment(s, &msg_hdr);
1000
0
        return 0;
1001
0
    }
1002
1003
0
    if (!s->server
1004
0
        && s->d1->r_msg_hdr.frag_off == 0
1005
0
        && s->statem.hand_state != TLS_ST_OK
1006
0
        && p[0] == SSL3_MT_HELLO_REQUEST) {
1007
        /*
1008
         * The server may always send 'Hello Request' messages -- we are
1009
         * doing a handshake anyway now, so ignore them if their format is
1010
         * correct. Does not count for 'Finished' MAC.
1011
         */
1012
0
        if (p[1] == 0 && p[2] == 0 && p[3] == 0) {
1013
0
            if (s->msg_callback)
1014
0
                s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1015
0
                    p, DTLS1_HM_HEADER_LENGTH, ussl,
1016
0
                    s->msg_callback_arg);
1017
1018
0
            s->init_num = 0;
1019
0
            goto redo;
1020
0
        } else { /* Incorrectly formatted Hello request */
1021
1022
0
            SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1023
0
            goto f_err;
1024
0
        }
1025
0
    }
1026
1027
0
    if (!dtls1_preprocess_fragment(s, &msg_hdr)) {
1028
        /* SSLfatal() already called */
1029
0
        goto f_err;
1030
0
    }
1031
1032
0
    if (frag_len > 0) {
1033
        /* dtls1_preprocess_fragment() above could reallocate init_buf */
1034
0
        p = (unsigned char *)s->init_buf->data + DTLS1_HM_HEADER_LENGTH;
1035
1036
0
        i = ssl->method->ssl_read_bytes(ssl, SSL3_RT_HANDSHAKE, NULL,
1037
0
            &p[frag_off], frag_len, 0, &readbytes);
1038
1039
        /*
1040
         * This shouldn't ever fail due to NBIO because we already checked
1041
         * that we have enough data in the record
1042
         */
1043
0
        if (i <= 0) {
1044
0
            s->rwstate = SSL_READING;
1045
0
            *len = 0;
1046
0
            return 0;
1047
0
        }
1048
0
    } else {
1049
0
        readbytes = 0;
1050
0
    }
1051
1052
    /*
1053
     * XDTLS: an incorrectly formatted fragment should cause the handshake
1054
     * to fail
1055
     */
1056
0
    if (readbytes != frag_len) {
1057
0
        SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_BAD_LENGTH);
1058
0
        goto f_err;
1059
0
    }
1060
1061
0
    if (chretran) {
1062
        /*
1063
         * We got a new ClientHello with a message sequence of 0.
1064
         * Reset the read/write sequences back to the beginning.
1065
         * We process it like this is the first time we've seen a ClientHello
1066
         * from the client.
1067
         */
1068
0
        s->d1->handshake_read_seq = 0;
1069
0
        s->d1->next_handshake_write_seq = 0;
1070
0
    }
1071
1072
    /*
1073
     * Note that s->init_num is *not* used as current offset in
1074
     * s->init_buf->data, but as a counter summing up fragments' lengths: as
1075
     * soon as they sum up to handshake packet length, we assume we have got
1076
     * all the fragments.
1077
     */
1078
0
    *len = s->init_num = frag_len;
1079
0
    return 1;
1080
1081
0
f_err:
1082
0
    s->init_num = 0;
1083
0
    *len = 0;
1084
0
    return 0;
1085
0
}
1086
1087
/*-
1088
 * for these 2 messages, we need to
1089
 * ssl->session->read_sym_enc           assign
1090
 * ssl->session->read_compression       assign
1091
 * ssl->session->read_hash              assign
1092
 */
1093
CON_FUNC_RETURN dtls_construct_change_cipher_spec(SSL_CONNECTION *s,
1094
    WPACKET *pkt)
1095
0
{
1096
0
    if (s->version == DTLS1_BAD_VER) {
1097
0
        s->d1->next_handshake_write_seq++;
1098
1099
0
        if (!WPACKET_put_bytes_u16(pkt, s->d1->handshake_write_seq)) {
1100
0
            SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1101
0
            return CON_FUNC_ERROR;
1102
0
        }
1103
0
    }
1104
1105
0
    return CON_FUNC_SUCCESS;
1106
0
}
1107
1108
#ifndef OPENSSL_NO_SCTP
1109
/*
1110
 * Wait for a dry event. Should only be called at a point in the handshake
1111
 * where we are not expecting any data from the peer except an alert.
1112
 */
1113
WORK_STATE dtls_wait_for_dry(SSL_CONNECTION *s)
1114
{
1115
    int ret, errtype;
1116
    size_t len;
1117
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1118
1119
    /* read app data until dry event */
1120
    ret = BIO_dgram_sctp_wait_for_dry(SSL_get_wbio(ssl));
1121
    if (ret < 0) {
1122
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1123
        return WORK_ERROR;
1124
    }
1125
1126
    if (ret == 0) {
1127
        /*
1128
         * We're not expecting any more messages from the peer at this point -
1129
         * but we could get an alert. If an alert is waiting then we will never
1130
         * return successfully. Therefore we attempt to read a message. This
1131
         * should never succeed but will process any waiting alerts.
1132
         */
1133
        if (dtls_get_reassembled_message(s, &errtype, &len)) {
1134
            /* The call succeeded! This should never happen */
1135
            SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1136
            return WORK_ERROR;
1137
        }
1138
1139
        s->s3.in_read_app_data = 2;
1140
        s->rwstate = SSL_READING;
1141
        BIO_clear_retry_flags(SSL_get_rbio(ssl));
1142
        BIO_set_retry_read(SSL_get_rbio(ssl));
1143
        return WORK_MORE_A;
1144
    }
1145
    return WORK_FINISHED_CONTINUE;
1146
}
1147
#endif
1148
1149
int dtls1_read_failed(SSL_CONNECTION *s, int code)
1150
0
{
1151
0
    SSL *ssl = SSL_CONNECTION_GET_SSL(s);
1152
1153
0
    if (code > 0) {
1154
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1155
0
        return 0;
1156
0
    }
1157
1158
0
    if (!dtls1_is_timer_expired(s) || ossl_statem_in_error(s)) {
1159
        /*
1160
         * not a timeout, none of our business, let higher layers handle
1161
         * this.  in fact it's probably an error
1162
         */
1163
0
        return code;
1164
0
    }
1165
    /* done, no need to send a retransmit */
1166
0
    if (!SSL_in_init(ssl)) {
1167
0
        BIO_set_flags(SSL_get_rbio(ssl), BIO_FLAGS_READ);
1168
0
        return code;
1169
0
    }
1170
1171
0
    return dtls1_handle_timeout(s);
1172
0
}
1173
1174
int dtls1_get_queue_priority(unsigned short seq, int is_ccs)
1175
0
{
1176
    /*
1177
     * The index of the retransmission queue actually is the message sequence
1178
     * number, since the queue only contains messages of a single handshake.
1179
     * However, the ChangeCipherSpec has no message sequence number and so
1180
     * using only the sequence will result in the CCS and Finished having the
1181
     * same index. To prevent this, the sequence number is multiplied by 2.
1182
     * In case of a CCS 1 is subtracted. This does not only differ CSS and
1183
     * Finished, it also maintains the order of the index (important for
1184
     * priority queues) and fits in the unsigned short variable.
1185
     */
1186
0
    return seq * 2 - is_ccs;
1187
0
}
1188
1189
int dtls1_retransmit_buffered_messages(SSL_CONNECTION *s)
1190
0
{
1191
0
    pqueue *sent = s->d1->sent_messages;
1192
0
    piterator iter;
1193
0
    pitem *item;
1194
0
    hm_fragment *frag;
1195
0
    int found = 0;
1196
1197
0
    iter = pqueue_iterator(sent);
1198
1199
0
    for (item = pqueue_next(&iter); item != NULL; item = pqueue_next(&iter)) {
1200
0
        frag = (hm_fragment *)item->data;
1201
0
        if (dtls1_retransmit_message(s, (unsigned short)dtls1_get_queue_priority(frag->msg_header.seq, frag->msg_header.is_ccs), &found) <= 0)
1202
0
            return -1;
1203
0
    }
1204
1205
0
    return 1;
1206
0
}
1207
1208
int dtls1_buffer_message(SSL_CONNECTION *s, int is_ccs)
1209
0
{
1210
0
    pitem *item;
1211
0
    hm_fragment *frag;
1212
0
    unsigned char seq64be[8];
1213
1214
    /*
1215
     * this function is called immediately after a message has been
1216
     * serialized
1217
     */
1218
0
    if (!ossl_assert(s->init_off == 0))
1219
0
        return 0;
1220
1221
0
    frag = dtls1_hm_fragment_new(s->init_num, 0);
1222
0
    if (frag == NULL)
1223
0
        return 0;
1224
1225
0
    memcpy(frag->fragment, s->init_buf->data, s->init_num);
1226
1227
0
    if (is_ccs) {
1228
        /* For DTLS1_BAD_VER the header length is non-standard */
1229
0
        if (!ossl_assert(s->d1->w_msg_hdr.msg_len + ((s->version == DTLS1_BAD_VER) ? 3 : DTLS1_CCS_HEADER_LENGTH)
1230
0
                == (unsigned int)s->init_num)) {
1231
0
            dtls1_hm_fragment_free(frag);
1232
0
            return 0;
1233
0
        }
1234
0
    } else {
1235
0
        if (!ossl_assert(s->d1->w_msg_hdr.msg_len + DTLS1_HM_HEADER_LENGTH == (unsigned int)s->init_num)) {
1236
0
            dtls1_hm_fragment_free(frag);
1237
0
            return 0;
1238
0
        }
1239
0
    }
1240
1241
0
    frag->msg_header.msg_len = s->d1->w_msg_hdr.msg_len;
1242
0
    frag->msg_header.seq = s->d1->w_msg_hdr.seq;
1243
0
    frag->msg_header.type = s->d1->w_msg_hdr.type;
1244
0
    frag->msg_header.frag_off = 0;
1245
0
    frag->msg_header.frag_len = s->d1->w_msg_hdr.msg_len;
1246
0
    frag->msg_header.is_ccs = is_ccs;
1247
1248
    /* save current state */
1249
0
    frag->msg_header.saved_retransmit_state.wrlmethod = s->rlayer.wrlmethod;
1250
0
    frag->msg_header.saved_retransmit_state.wrl = s->rlayer.wrl;
1251
1252
0
    memset(seq64be, 0, sizeof(seq64be));
1253
0
    seq64be[6] = (unsigned char)(dtls1_get_queue_priority(frag->msg_header.seq,
1254
0
                                     frag->msg_header.is_ccs)
1255
0
        >> 8);
1256
0
    seq64be[7] = (unsigned char)(dtls1_get_queue_priority(frag->msg_header.seq,
1257
0
        frag->msg_header.is_ccs));
1258
1259
0
    item = pitem_new(seq64be, frag);
1260
0
    if (item == NULL) {
1261
0
        dtls1_hm_fragment_free(frag);
1262
0
        return 0;
1263
0
    }
1264
1265
0
    if (pqueue_insert(s->d1->sent_messages, item) == NULL) {
1266
0
        dtls1_hm_fragment_free(frag);
1267
0
        pitem_free(item);
1268
0
        return 0;
1269
0
    }
1270
0
    return 1;
1271
0
}
1272
1273
int dtls1_retransmit_message(SSL_CONNECTION *s, unsigned short seq, int *found)
1274
0
{
1275
0
    int ret;
1276
    /* XDTLS: for now assuming that read/writes are blocking */
1277
0
    pitem *item;
1278
0
    hm_fragment *frag;
1279
0
    unsigned long header_length;
1280
0
    unsigned char seq64be[8];
1281
0
    struct dtls1_retransmit_state saved_state;
1282
1283
    /* XDTLS:  the requested message ought to be found, otherwise error */
1284
0
    memset(seq64be, 0, sizeof(seq64be));
1285
0
    seq64be[6] = (unsigned char)(seq >> 8);
1286
0
    seq64be[7] = (unsigned char)seq;
1287
1288
0
    item = pqueue_find(s->d1->sent_messages, seq64be);
1289
0
    if (item == NULL) {
1290
0
        SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1291
0
        *found = 0;
1292
0
        return 0;
1293
0
    }
1294
1295
0
    *found = 1;
1296
0
    frag = (hm_fragment *)item->data;
1297
1298
0
    if (frag->msg_header.is_ccs)
1299
0
        header_length = DTLS1_CCS_HEADER_LENGTH;
1300
0
    else
1301
0
        header_length = DTLS1_HM_HEADER_LENGTH;
1302
1303
0
    memcpy(s->init_buf->data, frag->fragment,
1304
0
        frag->msg_header.msg_len + header_length);
1305
0
    s->init_num = frag->msg_header.msg_len + header_length;
1306
1307
0
    dtls1_set_message_header_int(s, frag->msg_header.type,
1308
0
        frag->msg_header.msg_len,
1309
0
        frag->msg_header.seq, 0,
1310
0
        frag->msg_header.frag_len);
1311
1312
    /* save current state */
1313
0
    saved_state.wrlmethod = s->rlayer.wrlmethod;
1314
0
    saved_state.wrl = s->rlayer.wrl;
1315
1316
0
    s->d1->retransmitting = 1;
1317
1318
    /* restore state in which the message was originally sent */
1319
0
    s->rlayer.wrlmethod = frag->msg_header.saved_retransmit_state.wrlmethod;
1320
0
    s->rlayer.wrl = frag->msg_header.saved_retransmit_state.wrl;
1321
1322
    /*
1323
     * The old wrl may be still pointing at an old BIO. Update it to what we're
1324
     * using now.
1325
     */
1326
0
    s->rlayer.wrlmethod->set1_bio(s->rlayer.wrl, s->wbio);
1327
1328
0
    ret = dtls1_do_write(s, frag->msg_header.is_ccs ? SSL3_RT_CHANGE_CIPHER_SPEC : SSL3_RT_HANDSHAKE);
1329
1330
    /* restore current state */
1331
0
    s->rlayer.wrlmethod = saved_state.wrlmethod;
1332
0
    s->rlayer.wrl = saved_state.wrl;
1333
1334
0
    s->d1->retransmitting = 0;
1335
1336
0
    (void)BIO_flush(s->wbio);
1337
0
    return ret;
1338
0
}
1339
1340
void dtls1_set_message_header(SSL_CONNECTION *s,
1341
    unsigned char mt, size_t len,
1342
    size_t frag_off, size_t frag_len)
1343
0
{
1344
0
    if (frag_off == 0) {
1345
0
        s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1346
0
        s->d1->next_handshake_write_seq++;
1347
0
    }
1348
1349
0
    dtls1_set_message_header_int(s, mt, len, s->d1->handshake_write_seq,
1350
0
        frag_off, frag_len);
1351
0
}
1352
1353
/* don't actually do the writing, wait till the MTU has been retrieved */
1354
static void
1355
dtls1_set_message_header_int(SSL_CONNECTION *s, unsigned char mt,
1356
    size_t len, unsigned short seq_num,
1357
    size_t frag_off, size_t frag_len)
1358
0
{
1359
0
    struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1360
1361
0
    msg_hdr->type = mt;
1362
0
    msg_hdr->msg_len = len;
1363
0
    msg_hdr->seq = seq_num;
1364
0
    msg_hdr->frag_off = frag_off;
1365
0
    msg_hdr->frag_len = frag_len;
1366
0
}
1367
1368
static void
1369
dtls1_fix_message_header(SSL_CONNECTION *s, size_t frag_off, size_t frag_len)
1370
0
{
1371
0
    struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1372
1373
0
    msg_hdr->frag_off = frag_off;
1374
0
    msg_hdr->frag_len = frag_len;
1375
0
}
1376
1377
static unsigned char *dtls1_write_message_header(SSL_CONNECTION *s,
1378
    unsigned char *p)
1379
0
{
1380
0
    struct hm_header_st *msg_hdr = &s->d1->w_msg_hdr;
1381
1382
0
    *p++ = msg_hdr->type;
1383
0
    l2n3(msg_hdr->msg_len, p);
1384
1385
0
    s2n(msg_hdr->seq, p);
1386
0
    l2n3(msg_hdr->frag_off, p);
1387
0
    l2n3(msg_hdr->frag_len, p);
1388
1389
0
    return p;
1390
0
}
1391
1392
void dtls1_get_message_header(const unsigned char *data, struct hm_header_st *msg_hdr)
1393
0
{
1394
0
    memset(msg_hdr, 0, sizeof(*msg_hdr));
1395
0
    msg_hdr->type = *(data++);
1396
0
    n2l3(data, msg_hdr->msg_len);
1397
1398
0
    n2s(data, msg_hdr->seq);
1399
0
    n2l3(data, msg_hdr->frag_off);
1400
0
    n2l3(data, msg_hdr->frag_len);
1401
0
}
1402
1403
int dtls1_set_handshake_header(SSL_CONNECTION *s, WPACKET *pkt, int htype)
1404
0
{
1405
0
    unsigned char *header;
1406
1407
0
    if (htype == SSL3_MT_CHANGE_CIPHER_SPEC) {
1408
0
        s->d1->handshake_write_seq = s->d1->next_handshake_write_seq;
1409
0
        dtls1_set_message_header_int(s, SSL3_MT_CCS, 0,
1410
0
            s->d1->handshake_write_seq, 0, 0);
1411
0
        if (!WPACKET_put_bytes_u8(pkt, SSL3_MT_CCS))
1412
0
            return 0;
1413
0
    } else {
1414
0
        dtls1_set_message_header(s, htype, 0, 0, 0);
1415
        /*
1416
         * We allocate space at the start for the message header. This gets
1417
         * filled in later
1418
         */
1419
0
        if (!WPACKET_allocate_bytes(pkt, DTLS1_HM_HEADER_LENGTH, &header)
1420
0
            || !WPACKET_start_sub_packet(pkt))
1421
0
            return 0;
1422
0
    }
1423
1424
0
    return 1;
1425
0
}
1426
1427
int dtls1_close_construct_packet(SSL_CONNECTION *s, WPACKET *pkt, int htype)
1428
0
{
1429
0
    size_t msglen;
1430
1431
0
    if ((htype != SSL3_MT_CHANGE_CIPHER_SPEC && !WPACKET_close(pkt))
1432
0
        || !WPACKET_get_length(pkt, &msglen)
1433
0
        || msglen > INT_MAX)
1434
0
        return 0;
1435
1436
0
    if (htype != SSL3_MT_CHANGE_CIPHER_SPEC) {
1437
0
        s->d1->w_msg_hdr.msg_len = msglen - DTLS1_HM_HEADER_LENGTH;
1438
0
        s->d1->w_msg_hdr.frag_len = msglen - DTLS1_HM_HEADER_LENGTH;
1439
0
    }
1440
0
    s->init_num = (int)msglen;
1441
0
    s->init_off = 0;
1442
1443
0
    if (htype != DTLS1_MT_HELLO_VERIFY_REQUEST) {
1444
        /* Buffer the message to handle re-xmits */
1445
0
        if (!dtls1_buffer_message(s, htype == SSL3_MT_CHANGE_CIPHER_SPEC ? 1 : 0))
1446
0
            return 0;
1447
0
    }
1448
1449
0
    return 1;
1450
0
}