Coverage Report

Created: 2024-07-27 06:36

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