Coverage Report

Created: 2025-12-14 06:48

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