1160814Ssimon/* ssl/d1_pkt.c */
2296341Sdelphij/*
3160814Ssimon * DTLS implementation written by Nagendra Modadugu
4296341Sdelphij * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.
5160814Ssimon */
6160814Ssimon/* ====================================================================
7160814Ssimon * Copyright (c) 1998-2005 The OpenSSL Project.  All rights reserved.
8160814Ssimon *
9160814Ssimon * Redistribution and use in source and binary forms, with or without
10160814Ssimon * modification, are permitted provided that the following conditions
11160814Ssimon * are met:
12160814Ssimon *
13160814Ssimon * 1. Redistributions of source code must retain the above copyright
14296341Sdelphij *    notice, this list of conditions and the following disclaimer.
15160814Ssimon *
16160814Ssimon * 2. Redistributions in binary form must reproduce the above copyright
17160814Ssimon *    notice, this list of conditions and the following disclaimer in
18160814Ssimon *    the documentation and/or other materials provided with the
19160814Ssimon *    distribution.
20160814Ssimon *
21160814Ssimon * 3. All advertising materials mentioning features or use of this
22160814Ssimon *    software must display the following acknowledgment:
23160814Ssimon *    "This product includes software developed by the OpenSSL Project
24160814Ssimon *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
25160814Ssimon *
26160814Ssimon * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27160814Ssimon *    endorse or promote products derived from this software without
28160814Ssimon *    prior written permission. For written permission, please contact
29160814Ssimon *    openssl-core@openssl.org.
30160814Ssimon *
31160814Ssimon * 5. Products derived from this software may not be called "OpenSSL"
32160814Ssimon *    nor may "OpenSSL" appear in their names without prior written
33160814Ssimon *    permission of the OpenSSL Project.
34160814Ssimon *
35160814Ssimon * 6. Redistributions of any form whatsoever must retain the following
36160814Ssimon *    acknowledgment:
37160814Ssimon *    "This product includes software developed by the OpenSSL Project
38160814Ssimon *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
39160814Ssimon *
40160814Ssimon * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41160814Ssimon * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42160814Ssimon * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43160814Ssimon * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44160814Ssimon * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45160814Ssimon * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46160814Ssimon * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47160814Ssimon * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48160814Ssimon * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49160814Ssimon * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50160814Ssimon * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51160814Ssimon * OF THE POSSIBILITY OF SUCH DAMAGE.
52160814Ssimon * ====================================================================
53160814Ssimon *
54160814Ssimon * This product includes cryptographic software written by Eric Young
55160814Ssimon * (eay@cryptsoft.com).  This product includes software written by Tim
56160814Ssimon * Hudson (tjh@cryptsoft.com).
57160814Ssimon *
58160814Ssimon */
59160814Ssimon/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
60160814Ssimon * All rights reserved.
61160814Ssimon *
62160814Ssimon * This package is an SSL implementation written
63160814Ssimon * by Eric Young (eay@cryptsoft.com).
64160814Ssimon * The implementation was written so as to conform with Netscapes SSL.
65296341Sdelphij *
66160814Ssimon * This library is free for commercial and non-commercial use as long as
67160814Ssimon * the following conditions are aheared to.  The following conditions
68160814Ssimon * apply to all code found in this distribution, be it the RC4, RSA,
69160814Ssimon * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
70160814Ssimon * included with this distribution is covered by the same copyright terms
71160814Ssimon * except that the holder is Tim Hudson (tjh@cryptsoft.com).
72296341Sdelphij *
73160814Ssimon * Copyright remains Eric Young's, and as such any Copyright notices in
74160814Ssimon * the code are not to be removed.
75160814Ssimon * If this package is used in a product, Eric Young should be given attribution
76160814Ssimon * as the author of the parts of the library used.
77160814Ssimon * This can be in the form of a textual message at program startup or
78160814Ssimon * in documentation (online or textual) provided with the package.
79296341Sdelphij *
80160814Ssimon * Redistribution and use in source and binary forms, with or without
81160814Ssimon * modification, are permitted provided that the following conditions
82160814Ssimon * are met:
83160814Ssimon * 1. Redistributions of source code must retain the copyright
84160814Ssimon *    notice, this list of conditions and the following disclaimer.
85160814Ssimon * 2. Redistributions in binary form must reproduce the above copyright
86160814Ssimon *    notice, this list of conditions and the following disclaimer in the
87160814Ssimon *    documentation and/or other materials provided with the distribution.
88160814Ssimon * 3. All advertising materials mentioning features or use of this software
89160814Ssimon *    must display the following acknowledgement:
90160814Ssimon *    "This product includes cryptographic software written by
91160814Ssimon *     Eric Young (eay@cryptsoft.com)"
92160814Ssimon *    The word 'cryptographic' can be left out if the rouines from the library
93160814Ssimon *    being used are not cryptographic related :-).
94296341Sdelphij * 4. If you include any Windows specific code (or a derivative thereof) from
95160814Ssimon *    the apps directory (application code) you must include an acknowledgement:
96160814Ssimon *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
97296341Sdelphij *
98160814Ssimon * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
99160814Ssimon * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
100160814Ssimon * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
101160814Ssimon * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
102160814Ssimon * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
103160814Ssimon * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
104160814Ssimon * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
105160814Ssimon * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
106160814Ssimon * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
107160814Ssimon * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
108160814Ssimon * SUCH DAMAGE.
109296341Sdelphij *
110160814Ssimon * The licence and distribution terms for any publically available version or
111160814Ssimon * derivative of this code cannot be changed.  i.e. this code cannot simply be
112160814Ssimon * copied and put under another distribution licence
113160814Ssimon * [including the GNU Public Licence.]
114160814Ssimon */
115160814Ssimon
116160814Ssimon#include <stdio.h>
117160814Ssimon#include <errno.h>
118160814Ssimon#define USE_SOCKETS
119160814Ssimon#include "ssl_locl.h"
120160814Ssimon#include <openssl/evp.h>
121160814Ssimon#include <openssl/buffer.h>
122160814Ssimon#include <openssl/pqueue.h>
123194206Ssimon#include <openssl/rand.h>
124160814Ssimon
125238405Sjkim/* mod 128 saturating subtract of two 64-bit values in big-endian order */
126296341Sdelphijstatic int satsub64be(const unsigned char *v1, const unsigned char *v2)
127296341Sdelphij{
128296341Sdelphij    int ret, sat, brw, i;
129238405Sjkim
130296341Sdelphij    if (sizeof(long) == 8)
131296341Sdelphij        do {
132296341Sdelphij            const union {
133296341Sdelphij                long one;
134296341Sdelphij                char little;
135296341Sdelphij            } is_endian = {
136296341Sdelphij                1
137296341Sdelphij            };
138296341Sdelphij            long l;
139238405Sjkim
140296341Sdelphij            if (is_endian.little)
141296341Sdelphij                break;
142296341Sdelphij            /* not reached on little-endians */
143296341Sdelphij            /*
144296341Sdelphij             * following test is redundant, because input is always aligned,
145296341Sdelphij             * but I take no chances...
146296341Sdelphij             */
147296341Sdelphij            if (((size_t)v1 | (size_t)v2) & 0x7)
148296341Sdelphij                break;
149238405Sjkim
150296341Sdelphij            l = *((long *)v1);
151296341Sdelphij            l -= *((long *)v2);
152296341Sdelphij            if (l > 128)
153296341Sdelphij                return 128;
154296341Sdelphij            else if (l < -128)
155296341Sdelphij                return -128;
156296341Sdelphij            else
157296341Sdelphij                return (int)l;
158296341Sdelphij        } while (0);
159238405Sjkim
160296341Sdelphij    ret = (int)v1[7] - (int)v2[7];
161296341Sdelphij    sat = 0;
162296341Sdelphij    brw = ret >> 8;             /* brw is either 0 or -1 */
163296341Sdelphij    if (ret & 0x80) {
164296341Sdelphij        for (i = 6; i >= 0; i--) {
165296341Sdelphij            brw += (int)v1[i] - (int)v2[i];
166296341Sdelphij            sat |= ~brw;
167296341Sdelphij            brw >>= 8;
168296341Sdelphij        }
169296341Sdelphij    } else {
170296341Sdelphij        for (i = 6; i >= 0; i--) {
171296341Sdelphij            brw += (int)v1[i] - (int)v2[i];
172296341Sdelphij            sat |= brw;
173296341Sdelphij            brw >>= 8;
174296341Sdelphij        }
175296341Sdelphij    }
176296341Sdelphij    brw <<= 8;                  /* brw is either 0 or -256 */
177238405Sjkim
178296341Sdelphij    if (sat & 0xff)
179296341Sdelphij        return brw | 0x80;
180296341Sdelphij    else
181296341Sdelphij        return brw + (ret & 0xFF);
182238405Sjkim}
183238405Sjkim
184296341Sdelphijstatic int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
185296341Sdelphij                                   int len, int peek);
186238405Sjkimstatic int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap);
187160814Ssimonstatic void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap);
188296341Sdelphijstatic DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
189296341Sdelphij                                      unsigned int *is_next_epoch);
190160814Ssimon#if 0
191160814Ssimonstatic int dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr,
192296341Sdelphij                                        unsigned short *priority,
193296341Sdelphij                                        unsigned long *offset);
194160814Ssimon#endif
195160814Ssimonstatic int dtls1_buffer_record(SSL *s, record_pqueue *q,
196296341Sdelphij                               unsigned char *priority);
197306230Sdelphijstatic int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap);
198160814Ssimon
199160814Ssimon/* copy buffered record into SSL structure */
200296341Sdelphijstatic int dtls1_copy_record(SSL *s, pitem *item)
201296341Sdelphij{
202160814Ssimon    DTLS1_RECORD_DATA *rdata;
203160814Ssimon
204160814Ssimon    rdata = (DTLS1_RECORD_DATA *)item->data;
205296341Sdelphij
206160814Ssimon    if (s->s3->rbuf.buf != NULL)
207160814Ssimon        OPENSSL_free(s->s3->rbuf.buf);
208296341Sdelphij
209160814Ssimon    s->packet = rdata->packet;
210160814Ssimon    s->packet_length = rdata->packet_length;
211160814Ssimon    memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
212160814Ssimon    memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
213160814Ssimon
214296341Sdelphij    /* Set proper sequence number for mac calculation */
215296341Sdelphij    memcpy(&(s->s3->read_sequence[2]), &(rdata->packet[5]), 6);
216160814Ssimon
217296341Sdelphij    return (1);
218296341Sdelphij}
219296341Sdelphij
220160814Ssimonstatic int
221238405Sjkimdtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
222296341Sdelphij{
223296341Sdelphij    DTLS1_RECORD_DATA *rdata;
224296341Sdelphij    pitem *item;
225160814Ssimon
226296341Sdelphij    /* Limit the size of the queue to prevent DOS attacks */
227296341Sdelphij    if (pqueue_size(queue->q) >= 100)
228296341Sdelphij        return 0;
229277195Sdelphij
230296341Sdelphij    rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA));
231296341Sdelphij    item = pitem_new(priority, rdata);
232296341Sdelphij    if (rdata == NULL || item == NULL) {
233296341Sdelphij        if (rdata != NULL)
234296341Sdelphij            OPENSSL_free(rdata);
235296341Sdelphij        if (item != NULL)
236296341Sdelphij            pitem_free(item);
237160814Ssimon
238296341Sdelphij        SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
239296341Sdelphij        return -1;
240296341Sdelphij    }
241160814Ssimon
242296341Sdelphij    rdata->packet = s->packet;
243296341Sdelphij    rdata->packet_length = s->packet_length;
244296341Sdelphij    memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER));
245296341Sdelphij    memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD));
246296341Sdelphij
247296341Sdelphij    item->data = rdata;
248296341Sdelphij
249238405Sjkim#ifndef OPENSSL_NO_SCTP
250296341Sdelphij    /* Store bio_dgram_sctp_rcvinfo struct */
251296341Sdelphij    if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
252296341Sdelphij        (s->state == SSL3_ST_SR_FINISHED_A
253296341Sdelphij         || s->state == SSL3_ST_CR_FINISHED_A)) {
254296341Sdelphij        BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_GET_RCVINFO,
255296341Sdelphij                 sizeof(rdata->recordinfo), &rdata->recordinfo);
256296341Sdelphij    }
257238405Sjkim#endif
258238405Sjkim
259296341Sdelphij    s->packet = NULL;
260296341Sdelphij    s->packet_length = 0;
261296341Sdelphij    memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER));
262296341Sdelphij    memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD));
263267258Sjkim
264296341Sdelphij    if (!ssl3_setup_buffers(s)) {
265296341Sdelphij        SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
266296341Sdelphij        if (rdata->rbuf.buf != NULL)
267296341Sdelphij            OPENSSL_free(rdata->rbuf.buf);
268296341Sdelphij        OPENSSL_free(rdata);
269296341Sdelphij        pitem_free(item);
270296341Sdelphij        return (-1);
271296341Sdelphij    }
272267258Sjkim
273296341Sdelphij    /* insert should not fail, since duplicates are dropped */
274296341Sdelphij    if (pqueue_insert(queue->q, item) == NULL) {
275296341Sdelphij        SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
276296341Sdelphij        if (rdata->rbuf.buf != NULL)
277296341Sdelphij            OPENSSL_free(rdata->rbuf.buf);
278296341Sdelphij        OPENSSL_free(rdata);
279296341Sdelphij        pitem_free(item);
280296341Sdelphij        return (-1);
281296341Sdelphij    }
282160814Ssimon
283296341Sdelphij    return (1);
284296341Sdelphij}
285160814Ssimon
286296341Sdelphijstatic int dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue)
287296341Sdelphij{
288160814Ssimon    pitem *item;
289160814Ssimon
290160814Ssimon    item = pqueue_pop(queue->q);
291296341Sdelphij    if (item) {
292160814Ssimon        dtls1_copy_record(s, item);
293160814Ssimon
294160814Ssimon        OPENSSL_free(item->data);
295296341Sdelphij        pitem_free(item);
296160814Ssimon
297296341Sdelphij        return (1);
298160814Ssimon    }
299160814Ssimon
300296341Sdelphij    return (0);
301296341Sdelphij}
302160814Ssimon
303296341Sdelphij/*
304296341Sdelphij * retrieve a buffered record that belongs to the new epoch, i.e., not
305296341Sdelphij * processed yet
306296341Sdelphij */
307160814Ssimon#define dtls1_get_unprocessed_record(s) \
308160814Ssimon                   dtls1_retrieve_buffered_record((s), \
309160814Ssimon                   &((s)->d1->unprocessed_rcds))
310160814Ssimon
311296341Sdelphij/*
312296341Sdelphij * retrieve a buffered record that belongs to the current epoch, ie,
313296341Sdelphij * processed
314296341Sdelphij */
315160814Ssimon#define dtls1_get_processed_record(s) \
316160814Ssimon                   dtls1_retrieve_buffered_record((s), \
317160814Ssimon                   &((s)->d1->processed_rcds))
318160814Ssimon
319296341Sdelphijstatic int dtls1_process_buffered_records(SSL *s)
320296341Sdelphij{
321160814Ssimon    pitem *item;
322306230Sdelphij    SSL3_BUFFER *rb;
323306230Sdelphij    SSL3_RECORD *rr;
324306230Sdelphij    DTLS1_BITMAP *bitmap;
325306230Sdelphij    unsigned int is_next_epoch;
326306230Sdelphij    int replayok = 1;
327296341Sdelphij
328160814Ssimon    item = pqueue_peek(s->d1->unprocessed_rcds.q);
329296341Sdelphij    if (item) {
330160814Ssimon        /* Check if epoch is current. */
331160814Ssimon        if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch)
332306230Sdelphij            return 1;         /* Nothing to do. */
333296341Sdelphij
334306230Sdelphij        rr = &s->s3->rrec;
335306230Sdelphij        rb = &s->s3->rbuf;
336306230Sdelphij
337306230Sdelphij        if (rb->left > 0) {
338306230Sdelphij            /*
339306230Sdelphij             * We've still got data from the current packet to read. There could
340306230Sdelphij             * be a record from the new epoch in it - so don't overwrite it
341306230Sdelphij             * with the unprocessed records yet (we'll do it when we've
342306230Sdelphij             * finished reading the current packet).
343306230Sdelphij             */
344306230Sdelphij            return 1;
345306230Sdelphij        }
346306230Sdelphij
347306230Sdelphij
348160814Ssimon        /* Process all the records. */
349296341Sdelphij        while (pqueue_peek(s->d1->unprocessed_rcds.q)) {
350160814Ssimon            dtls1_get_unprocessed_record(s);
351306230Sdelphij            bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
352306230Sdelphij            if (bitmap == NULL) {
353306230Sdelphij                /*
354306230Sdelphij                 * Should not happen. This will only ever be NULL when the
355306230Sdelphij                 * current record is from a different epoch. But that cannot
356306230Sdelphij                 * be the case because we already checked the epoch above
357306230Sdelphij                 */
358306230Sdelphij                 SSLerr(SSL_F_DTLS1_PROCESS_BUFFERED_RECORDS,
359306230Sdelphij                        ERR_R_INTERNAL_ERROR);
360306230Sdelphij                 return 0;
361306230Sdelphij            }
362306230Sdelphij#ifndef OPENSSL_NO_SCTP
363306230Sdelphij            /* Only do replay check if no SCTP bio */
364306230Sdelphij            if (!BIO_dgram_is_sctp(SSL_get_rbio(s)))
365306230Sdelphij#endif
366306230Sdelphij            {
367306230Sdelphij                /*
368306230Sdelphij                 * Check whether this is a repeat, or aged record. We did this
369306230Sdelphij                 * check once already when we first received the record - but
370306230Sdelphij                 * we might have updated the window since then due to
371306230Sdelphij                 * records we subsequently processed.
372306230Sdelphij                 */
373306230Sdelphij                replayok = dtls1_record_replay_check(s, bitmap);
374306230Sdelphij            }
375306230Sdelphij
376306230Sdelphij            if (!replayok || !dtls1_process_record(s, bitmap)) {
377306230Sdelphij                /* dump this record */
378306230Sdelphij                rr->length = 0;
379306230Sdelphij                s->packet_length = 0;
380306230Sdelphij                continue;
381306230Sdelphij            }
382306230Sdelphij
383296341Sdelphij            if (dtls1_buffer_record(s, &(s->d1->processed_rcds),
384296341Sdelphij                                    s->s3->rrec.seq_num) < 0)
385306230Sdelphij                return 0;
386160814Ssimon        }
387296341Sdelphij    }
388160814Ssimon
389296341Sdelphij    /*
390296341Sdelphij     * sync epoch numbers once all the unprocessed records have been
391296341Sdelphij     * processed
392296341Sdelphij     */
393160814Ssimon    s->d1->processed_rcds.epoch = s->d1->r_epoch;
394160814Ssimon    s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1;
395160814Ssimon
396306230Sdelphij    return 1;
397296341Sdelphij}
398160814Ssimon
399160814Ssimon#if 0
400160814Ssimon
401296341Sdelphijstatic int dtls1_get_buffered_record(SSL *s)
402296341Sdelphij{
403296341Sdelphij    pitem *item;
404296341Sdelphij    PQ_64BIT priority =
405296341Sdelphij        (((PQ_64BIT) s->d1->handshake_read_seq) << 32) |
406296341Sdelphij        ((PQ_64BIT) s->d1->r_msg_hdr.frag_off);
407160814Ssimon
408296341Sdelphij    /* if we're not (re)negotiating, nothing buffered */
409296341Sdelphij    if (!SSL_in_init(s))
410296341Sdelphij        return 0;
411160814Ssimon
412296341Sdelphij    item = pqueue_peek(s->d1->rcvd_records);
413296341Sdelphij    if (item && item->priority == priority) {
414296341Sdelphij        /*
415296341Sdelphij         * Check if we've received the record of interest.  It must be a
416296341Sdelphij         * handshake record, since data records as passed up without
417296341Sdelphij         * buffering
418296341Sdelphij         */
419296341Sdelphij        DTLS1_RECORD_DATA *rdata;
420296341Sdelphij        item = pqueue_pop(s->d1->rcvd_records);
421296341Sdelphij        rdata = (DTLS1_RECORD_DATA *)item->data;
422160814Ssimon
423296341Sdelphij        if (s->s3->rbuf.buf != NULL)
424296341Sdelphij            OPENSSL_free(s->s3->rbuf.buf);
425296341Sdelphij
426296341Sdelphij        s->packet = rdata->packet;
427296341Sdelphij        s->packet_length = rdata->packet_length;
428296341Sdelphij        memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
429296341Sdelphij        memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
430296341Sdelphij
431296341Sdelphij        OPENSSL_free(item->data);
432296341Sdelphij        pitem_free(item);
433296341Sdelphij
434296341Sdelphij        /* s->d1->next_expected_seq_num++; */
435296341Sdelphij        return (1);
436296341Sdelphij    }
437296341Sdelphij
438296341Sdelphij    return 0;
439296341Sdelphij}
440296341Sdelphij
441160814Ssimon#endif
442160814Ssimon
443306230Sdelphijstatic int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
444160814Ssimon{
445296341Sdelphij    int i, al;
446296341Sdelphij    int enc_err;
447296341Sdelphij    SSL_SESSION *sess;
448296341Sdelphij    SSL3_RECORD *rr;
449296341Sdelphij    unsigned int mac_size, orig_len;
450296341Sdelphij    unsigned char md[EVP_MAX_MD_SIZE];
451160814Ssimon
452296341Sdelphij    rr = &(s->s3->rrec);
453296341Sdelphij    sess = s->session;
454160814Ssimon
455296341Sdelphij    /*
456296341Sdelphij     * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
457296341Sdelphij     * and we have that many bytes in s->packet
458296341Sdelphij     */
459296341Sdelphij    rr->input = &(s->packet[DTLS1_RT_HEADER_LENGTH]);
460160814Ssimon
461296341Sdelphij    /*
462296341Sdelphij     * ok, we can now read from 's->packet' data into 'rr' rr->input points
463296341Sdelphij     * at rr->length bytes, which need to be copied into rr->data by either
464296341Sdelphij     * the decryption or by the decompression When the data is 'copied' into
465296341Sdelphij     * the rr->data buffer, rr->input will be pointed at the new buffer
466296341Sdelphij     */
467160814Ssimon
468296341Sdelphij    /*
469296341Sdelphij     * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
470296341Sdelphij     * bytes of encrypted compressed stuff.
471296341Sdelphij     */
472160814Ssimon
473296341Sdelphij    /* check is not needed I believe */
474296341Sdelphij    if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
475296341Sdelphij        al = SSL_AD_RECORD_OVERFLOW;
476296341Sdelphij        SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
477296341Sdelphij        goto f_err;
478296341Sdelphij    }
479160814Ssimon
480296341Sdelphij    /* decrypt in place in 'rr->input' */
481296341Sdelphij    rr->data = rr->input;
482160814Ssimon
483296341Sdelphij    enc_err = s->method->ssl3_enc->enc(s, 0);
484296341Sdelphij    /*-
485296341Sdelphij     * enc_err is:
486296341Sdelphij     *    0: (in non-constant time) if the record is publically invalid.
487296341Sdelphij     *    1: if the padding is valid
488296341Sdelphij     *   -1: if the padding is invalid
489296341Sdelphij     */
490296341Sdelphij    if (enc_err == 0) {
491296341Sdelphij        /* For DTLS we simply ignore bad packets. */
492296341Sdelphij        rr->length = 0;
493296341Sdelphij        s->packet_length = 0;
494296341Sdelphij        goto err;
495296341Sdelphij    }
496160814Ssimon#ifdef TLS_DEBUG
497296341Sdelphij    printf("dec %d\n", rr->length);
498296341Sdelphij    {
499296341Sdelphij        unsigned int z;
500296341Sdelphij        for (z = 0; z < rr->length; z++)
501296341Sdelphij            printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
502296341Sdelphij    }
503296341Sdelphij    printf("\n");
504160814Ssimon#endif
505160814Ssimon
506296341Sdelphij    /* r->length is now the compressed data plus mac */
507296341Sdelphij    if ((sess != NULL) &&
508296341Sdelphij        (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
509296341Sdelphij        /* s->read_hash != NULL => mac_size != -1 */
510296341Sdelphij        unsigned char *mac = NULL;
511296341Sdelphij        unsigned char mac_tmp[EVP_MAX_MD_SIZE];
512296341Sdelphij        mac_size = EVP_MD_CTX_size(s->read_hash);
513296341Sdelphij        OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
514160814Ssimon
515296341Sdelphij        /*
516296341Sdelphij         * kludge: *_cbc_remove_padding passes padding length in rr->type
517296341Sdelphij         */
518296341Sdelphij        orig_len = rr->length + ((unsigned int)rr->type >> 8);
519246772Sjkim
520296341Sdelphij        /*
521296341Sdelphij         * orig_len is the length of the record before any padding was
522296341Sdelphij         * removed. This is public information, as is the MAC in use,
523296341Sdelphij         * therefore we can safely process the record in a different amount
524296341Sdelphij         * of time if it's too short to possibly contain a MAC.
525296341Sdelphij         */
526296341Sdelphij        if (orig_len < mac_size ||
527296341Sdelphij            /* CBC records must have a padding length byte too. */
528296341Sdelphij            (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
529296341Sdelphij             orig_len < mac_size + 1)) {
530296341Sdelphij            al = SSL_AD_DECODE_ERROR;
531296341Sdelphij            SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
532296341Sdelphij            goto f_err;
533296341Sdelphij        }
534246772Sjkim
535296341Sdelphij        if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
536296341Sdelphij            /*
537296341Sdelphij             * We update the length so that the TLS header bytes can be
538296341Sdelphij             * constructed correctly but we need to extract the MAC in
539296341Sdelphij             * constant time from within the record, without leaking the
540296341Sdelphij             * contents of the padding bytes.
541296341Sdelphij             */
542296341Sdelphij            mac = mac_tmp;
543296341Sdelphij            ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len);
544296341Sdelphij            rr->length -= mac_size;
545296341Sdelphij        } else {
546296341Sdelphij            /*
547296341Sdelphij             * In this case there's no padding, so |orig_len| equals
548296341Sdelphij             * |rec->length| and we checked that there's enough bytes for
549296341Sdelphij             * |mac_size| above.
550296341Sdelphij             */
551296341Sdelphij            rr->length -= mac_size;
552296341Sdelphij            mac = &rr->data[rr->length];
553296341Sdelphij        }
554246772Sjkim
555296341Sdelphij        i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
556296341Sdelphij        if (i < 0 || mac == NULL
557296341Sdelphij            || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
558296341Sdelphij            enc_err = -1;
559296341Sdelphij        if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
560296341Sdelphij            enc_err = -1;
561296341Sdelphij    }
562160814Ssimon
563296341Sdelphij    if (enc_err < 0) {
564296341Sdelphij        /* decryption failed, silently discard message */
565296341Sdelphij        rr->length = 0;
566296341Sdelphij        s->packet_length = 0;
567296341Sdelphij        goto err;
568296341Sdelphij    }
569237657Sjkim
570296341Sdelphij    /* r->length is now just compressed */
571296341Sdelphij    if (s->expand != NULL) {
572296341Sdelphij        if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
573296341Sdelphij            al = SSL_AD_RECORD_OVERFLOW;
574296341Sdelphij            SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
575296341Sdelphij                   SSL_R_COMPRESSED_LENGTH_TOO_LONG);
576296341Sdelphij            goto f_err;
577296341Sdelphij        }
578296341Sdelphij        if (!ssl3_do_uncompress(s)) {
579296341Sdelphij            al = SSL_AD_DECOMPRESSION_FAILURE;
580296341Sdelphij            SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
581296341Sdelphij            goto f_err;
582296341Sdelphij        }
583296341Sdelphij    }
584160814Ssimon
585296341Sdelphij    if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
586296341Sdelphij        al = SSL_AD_RECORD_OVERFLOW;
587296341Sdelphij        SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
588296341Sdelphij        goto f_err;
589296341Sdelphij    }
590160814Ssimon
591296341Sdelphij    rr->off = 0;
592296341Sdelphij    /*-
593296341Sdelphij     * So at this point the following is true
594296341Sdelphij     * ssl->s3->rrec.type   is the type of record
595296341Sdelphij     * ssl->s3->rrec.length == number of bytes in record
596296341Sdelphij     * ssl->s3->rrec.off    == offset to first valid byte
597296341Sdelphij     * ssl->s3->rrec.data   == where to take bytes from, increment
598296341Sdelphij     *                         after use :-).
599296341Sdelphij     */
600160814Ssimon
601296341Sdelphij    /* we have pulled in a full packet so zero things */
602296341Sdelphij    s->packet_length = 0;
603306230Sdelphij
604306230Sdelphij    /* Mark receipt of record. */
605306230Sdelphij    dtls1_record_bitmap_update(s, bitmap);
606306230Sdelphij
607296341Sdelphij    return (1);
608160814Ssimon
609296341Sdelphij f_err:
610296341Sdelphij    ssl3_send_alert(s, SSL3_AL_FATAL, al);
611296341Sdelphij err:
612296341Sdelphij    return (0);
613160814Ssimon}
614160814Ssimon
615296341Sdelphij/*-
616296341Sdelphij * Call this to get a new input record.
617160814Ssimon * It will return <= 0 if more data is needed, normally due to an error
618160814Ssimon * or non-blocking IO.
619160814Ssimon * When it finishes, one packet has been decoded and can be found in
620160814Ssimon * ssl->s3->rrec.type    - is the type of record
621296341Sdelphij * ssl->s3->rrec.data,   - data
622160814Ssimon * ssl->s3->rrec.length, - number of bytes
623160814Ssimon */
624160814Ssimon/* used only by dtls1_read_bytes */
625160814Ssimonint dtls1_get_record(SSL *s)
626296341Sdelphij{
627296341Sdelphij    int ssl_major, ssl_minor;
628296341Sdelphij    int i, n;
629296341Sdelphij    SSL3_RECORD *rr;
630296341Sdelphij    unsigned char *p = NULL;
631296341Sdelphij    unsigned short version;
632296341Sdelphij    DTLS1_BITMAP *bitmap;
633296341Sdelphij    unsigned int is_next_epoch;
634160814Ssimon
635296341Sdelphij    rr = &(s->s3->rrec);
636160814Ssimon
637306230Sdelphij again:
638296341Sdelphij    /*
639296341Sdelphij     * The epoch may have changed.  If so, process all the pending records.
640296341Sdelphij     * This is a non-blocking operation.
641296341Sdelphij     */
642306230Sdelphij    if (!dtls1_process_buffered_records(s))
643296341Sdelphij        return -1;
644160814Ssimon
645296341Sdelphij    /* if we're renegotiating, then there may be buffered records */
646296341Sdelphij    if (dtls1_get_processed_record(s))
647296341Sdelphij        return 1;
648160814Ssimon
649296341Sdelphij    /* get something from the wire */
650296341Sdelphij    /* check if we have the header */
651296341Sdelphij    if ((s->rstate != SSL_ST_READ_BODY) ||
652296341Sdelphij        (s->packet_length < DTLS1_RT_HEADER_LENGTH)) {
653296341Sdelphij        n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
654296341Sdelphij        /* read timeout is handled by dtls1_read_bytes */
655296341Sdelphij        if (n <= 0)
656296341Sdelphij            return (n);         /* error or non-blocking */
657160814Ssimon
658296341Sdelphij        /* this packet contained a partial record, dump it */
659296341Sdelphij        if (s->packet_length != DTLS1_RT_HEADER_LENGTH) {
660296341Sdelphij            s->packet_length = 0;
661296341Sdelphij            goto again;
662296341Sdelphij        }
663160814Ssimon
664296341Sdelphij        s->rstate = SSL_ST_READ_BODY;
665160814Ssimon
666296341Sdelphij        p = s->packet;
667160814Ssimon
668296341Sdelphij        /* Pull apart the header into the DTLS1_RECORD */
669296341Sdelphij        rr->type = *(p++);
670296341Sdelphij        ssl_major = *(p++);
671296341Sdelphij        ssl_minor = *(p++);
672296341Sdelphij        version = (ssl_major << 8) | ssl_minor;
673160814Ssimon
674296341Sdelphij        /* sequence number is 64 bits, with top 2 bytes = epoch */
675296341Sdelphij        n2s(p, rr->epoch);
676160814Ssimon
677296341Sdelphij        memcpy(&(s->s3->read_sequence[2]), p, 6);
678296341Sdelphij        p += 6;
679160814Ssimon
680296341Sdelphij        n2s(p, rr->length);
681160814Ssimon
682296341Sdelphij        /* Lets check version */
683296341Sdelphij        if (!s->first_packet) {
684296341Sdelphij            if (version != s->version) {
685296341Sdelphij                /* unexpected version, silently discard */
686296341Sdelphij                rr->length = 0;
687296341Sdelphij                s->packet_length = 0;
688296341Sdelphij                goto again;
689296341Sdelphij            }
690296341Sdelphij        }
691160814Ssimon
692296341Sdelphij        if ((version & 0xff00) != (s->version & 0xff00)) {
693296341Sdelphij            /* wrong version, silently discard record */
694296341Sdelphij            rr->length = 0;
695296341Sdelphij            s->packet_length = 0;
696296341Sdelphij            goto again;
697296341Sdelphij        }
698160814Ssimon
699296341Sdelphij        if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
700296341Sdelphij            /* record too long, silently discard it */
701296341Sdelphij            rr->length = 0;
702296341Sdelphij            s->packet_length = 0;
703296341Sdelphij            goto again;
704296341Sdelphij        }
705160814Ssimon
706296341Sdelphij        /* now s->rstate == SSL_ST_READ_BODY */
707296341Sdelphij    }
708160814Ssimon
709296341Sdelphij    /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
710160814Ssimon
711296341Sdelphij    if (rr->length > s->packet_length - DTLS1_RT_HEADER_LENGTH) {
712296341Sdelphij        /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
713296341Sdelphij        i = rr->length;
714296341Sdelphij        n = ssl3_read_n(s, i, i, 1);
715296341Sdelphij        /* this packet contained a partial record, dump it */
716296341Sdelphij        if (n != i) {
717296341Sdelphij            rr->length = 0;
718296341Sdelphij            s->packet_length = 0;
719296341Sdelphij            goto again;
720296341Sdelphij        }
721160814Ssimon
722296341Sdelphij        /*
723296341Sdelphij         * now n == rr->length, and s->packet_length ==
724296341Sdelphij         * DTLS1_RT_HEADER_LENGTH + rr->length
725296341Sdelphij         */
726296341Sdelphij    }
727296341Sdelphij    s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
728160814Ssimon
729296341Sdelphij    /* match epochs.  NULL means the packet is dropped on the floor */
730296341Sdelphij    bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
731296341Sdelphij    if (bitmap == NULL) {
732296341Sdelphij        rr->length = 0;
733296341Sdelphij        s->packet_length = 0;   /* dump this record */
734296341Sdelphij        goto again;             /* get another record */
735296341Sdelphij    }
736238405Sjkim#ifndef OPENSSL_NO_SCTP
737296341Sdelphij    /* Only do replay check if no SCTP bio */
738296341Sdelphij    if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
739238405Sjkim#endif
740296341Sdelphij        /*
741296341Sdelphij         * Check whether this is a repeat, or aged record. Don't check if
742296341Sdelphij         * we're listening and this message is a ClientHello. They can look
743296341Sdelphij         * as if they're replayed, since they arrive from different
744296341Sdelphij         * connections and would be dropped unnecessarily.
745296341Sdelphij         */
746296341Sdelphij        if (!(s->d1->listen && rr->type == SSL3_RT_HANDSHAKE &&
747296341Sdelphij              s->packet_length > DTLS1_RT_HEADER_LENGTH &&
748296341Sdelphij              s->packet[DTLS1_RT_HEADER_LENGTH] == SSL3_MT_CLIENT_HELLO) &&
749296341Sdelphij            !dtls1_record_replay_check(s, bitmap)) {
750296341Sdelphij            rr->length = 0;
751296341Sdelphij            s->packet_length = 0; /* dump this record */
752296341Sdelphij            goto again;         /* get another record */
753296341Sdelphij        }
754238405Sjkim#ifndef OPENSSL_NO_SCTP
755296341Sdelphij    }
756238405Sjkim#endif
757238405Sjkim
758296341Sdelphij    /* just read a 0 length packet */
759296341Sdelphij    if (rr->length == 0)
760296341Sdelphij        goto again;
761160814Ssimon
762296341Sdelphij    /*
763296341Sdelphij     * If this record is from the next epoch (either HM or ALERT), and a
764296341Sdelphij     * handshake is currently in progress, buffer it since it cannot be
765296341Sdelphij     * processed at this time. However, do not buffer anything while
766296341Sdelphij     * listening.
767296341Sdelphij     */
768296341Sdelphij    if (is_next_epoch) {
769296341Sdelphij        if ((SSL_in_init(s) || s->in_handshake) && !s->d1->listen) {
770296341Sdelphij            if (dtls1_buffer_record
771296341Sdelphij                (s, &(s->d1->unprocessed_rcds), rr->seq_num) < 0)
772296341Sdelphij                return -1;
773296341Sdelphij        }
774296341Sdelphij        rr->length = 0;
775296341Sdelphij        s->packet_length = 0;
776296341Sdelphij        goto again;
777296341Sdelphij    }
778160814Ssimon
779306230Sdelphij    if (!dtls1_process_record(s, bitmap)) {
780296341Sdelphij        rr->length = 0;
781296341Sdelphij        s->packet_length = 0;   /* dump this record */
782296341Sdelphij        goto again;             /* get another record */
783296341Sdelphij    }
784160814Ssimon
785296341Sdelphij    return (1);
786160814Ssimon
787296341Sdelphij}
788160814Ssimon
789296341Sdelphij/*-
790296341Sdelphij * Return up to 'len' payload bytes received in 'type' records.
791160814Ssimon * 'type' is one of the following:
792160814Ssimon *
793160814Ssimon *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
794160814Ssimon *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
795160814Ssimon *   -  0 (during a shutdown, no data has to be returned)
796160814Ssimon *
797160814Ssimon * If we don't have stored data to work from, read a SSL/TLS record first
798160814Ssimon * (possibly multiple records if we still don't have anything to return).
799160814Ssimon *
800160814Ssimon * This function must handle any surprises the peer may have for us, such as
801160814Ssimon * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
802160814Ssimon * a surprise, but handled as if it were), or renegotiation requests.
803160814Ssimon * Also if record payloads contain fragments too small to process, we store
804160814Ssimon * them until there is enough for the respective protocol (the record protocol
805160814Ssimon * may use arbitrary fragmentation and even interleaving):
806160814Ssimon *     Change cipher spec protocol
807160814Ssimon *             just 1 byte needed, no need for keeping anything stored
808160814Ssimon *     Alert protocol
809160814Ssimon *             2 bytes needed (AlertLevel, AlertDescription)
810160814Ssimon *     Handshake protocol
811160814Ssimon *             4 bytes needed (HandshakeType, uint24 length) -- we just have
812160814Ssimon *             to detect unexpected Client Hello and Hello Request messages
813160814Ssimon *             here, anything else is handled by higher layers
814160814Ssimon *     Application data protocol
815160814Ssimon *             none of our business
816160814Ssimon */
817160814Ssimonint dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
818296341Sdelphij{
819296341Sdelphij    int al, i, j, ret;
820296341Sdelphij    unsigned int n;
821296341Sdelphij    SSL3_RECORD *rr;
822296341Sdelphij    void (*cb) (const SSL *ssl, int type2, int val) = NULL;
823160814Ssimon
824296341Sdelphij    if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
825296341Sdelphij        if (!ssl3_setup_buffers(s))
826296341Sdelphij            return (-1);
827160814Ssimon
828160814Ssimon    /* XXX: check what the second '&& type' is about */
829296341Sdelphij    if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
830296341Sdelphij         (type != SSL3_RT_HANDSHAKE) && type) ||
831296341Sdelphij        (peek && (type != SSL3_RT_APPLICATION_DATA))) {
832296341Sdelphij        SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
833296341Sdelphij        return -1;
834296341Sdelphij    }
835160814Ssimon
836296341Sdelphij    /*
837296341Sdelphij     * check whether there's a handshake message (client hello?) waiting
838296341Sdelphij     */
839296341Sdelphij    if ((ret = have_handshake_fragment(s, type, buf, len, peek)))
840296341Sdelphij        return ret;
841160814Ssimon
842296341Sdelphij    /*
843296341Sdelphij     * Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
844296341Sdelphij     */
845160814Ssimon
846238405Sjkim#ifndef OPENSSL_NO_SCTP
847296341Sdelphij    /*
848296341Sdelphij     * Continue handshake if it had to be interrupted to read app data with
849296341Sdelphij     * SCTP.
850296341Sdelphij     */
851296341Sdelphij    if ((!s->in_handshake && SSL_in_init(s)) ||
852296341Sdelphij        (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
853296341Sdelphij         (s->state == DTLS1_SCTP_ST_SR_READ_SOCK
854296341Sdelphij          || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)
855296341Sdelphij         && s->s3->in_read_app_data != 2))
856238405Sjkim#else
857296341Sdelphij    if (!s->in_handshake && SSL_in_init(s))
858238405Sjkim#endif
859296341Sdelphij    {
860296341Sdelphij        /* type == SSL3_RT_APPLICATION_DATA */
861296341Sdelphij        i = s->handshake_func(s);
862296341Sdelphij        if (i < 0)
863296341Sdelphij            return (i);
864296341Sdelphij        if (i == 0) {
865296341Sdelphij            SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
866296341Sdelphij            return (-1);
867296341Sdelphij        }
868296341Sdelphij    }
869160814Ssimon
870296341Sdelphij start:
871296341Sdelphij    s->rwstate = SSL_NOTHING;
872160814Ssimon
873296341Sdelphij    /*-
874296341Sdelphij     * s->s3->rrec.type         - is the type of record
875296341Sdelphij     * s->s3->rrec.data,    - data
876296341Sdelphij     * s->s3->rrec.off,     - offset into 'data' for next read
877296341Sdelphij     * s->s3->rrec.length,  - number of bytes.
878296341Sdelphij     */
879296341Sdelphij    rr = &(s->s3->rrec);
880160814Ssimon
881296341Sdelphij    /*
882296341Sdelphij     * We are not handshaking and have no data yet, so process data buffered
883296341Sdelphij     * during the last handshake in advance, if any.
884296341Sdelphij     */
885296341Sdelphij    if (s->state == SSL_ST_OK && rr->length == 0) {
886296341Sdelphij        pitem *item;
887296341Sdelphij        item = pqueue_pop(s->d1->buffered_app_data.q);
888296341Sdelphij        if (item) {
889238405Sjkim#ifndef OPENSSL_NO_SCTP
890296341Sdelphij            /* Restore bio_dgram_sctp_rcvinfo struct */
891296341Sdelphij            if (BIO_dgram_is_sctp(SSL_get_rbio(s))) {
892296341Sdelphij                DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *)item->data;
893296341Sdelphij                BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO,
894296341Sdelphij                         sizeof(rdata->recordinfo), &rdata->recordinfo);
895296341Sdelphij            }
896238405Sjkim#endif
897238405Sjkim
898296341Sdelphij            dtls1_copy_record(s, item);
899205128Ssimon
900296341Sdelphij            OPENSSL_free(item->data);
901296341Sdelphij            pitem_free(item);
902296341Sdelphij        }
903296341Sdelphij    }
904205128Ssimon
905296341Sdelphij    /* Check for timeout */
906296341Sdelphij    if (dtls1_handle_timeout(s) > 0)
907296341Sdelphij        goto start;
908205128Ssimon
909296341Sdelphij    /* get new packet if necessary */
910296341Sdelphij    if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) {
911296341Sdelphij        ret = dtls1_get_record(s);
912296341Sdelphij        if (ret <= 0) {
913296341Sdelphij            ret = dtls1_read_failed(s, ret);
914296341Sdelphij            /* anything other than a timeout is an error */
915296341Sdelphij            if (ret <= 0)
916296341Sdelphij                return (ret);
917296341Sdelphij            else
918296341Sdelphij                goto start;
919296341Sdelphij        }
920296341Sdelphij    }
921160814Ssimon
922296341Sdelphij    if (s->d1->listen && rr->type != SSL3_RT_HANDSHAKE) {
923296341Sdelphij        rr->length = 0;
924296341Sdelphij        goto start;
925296341Sdelphij    }
926264331Sjkim
927308204Sdelphij    /*
928308204Sdelphij     * Reset the count of consecutive warning alerts if we've got a non-empty
929308204Sdelphij     * record that isn't an alert.
930308204Sdelphij     */
931308204Sdelphij    if (rr->type != SSL3_RT_ALERT && rr->length != 0)
932308204Sdelphij        s->s3->alert_count = 0;
933308204Sdelphij
934296341Sdelphij    /* we now have a packet which can be read and processed */
935160814Ssimon
936296341Sdelphij    if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
937296341Sdelphij                                   * reset by ssl3_get_finished */
938296341Sdelphij        && (rr->type != SSL3_RT_HANDSHAKE)) {
939296341Sdelphij        /*
940296341Sdelphij         * We now have application data between CCS and Finished. Most likely
941296341Sdelphij         * the packets were reordered on their way, so buffer the application
942296341Sdelphij         * data for later processing rather than dropping the connection.
943296341Sdelphij         */
944296341Sdelphij        if (dtls1_buffer_record(s, &(s->d1->buffered_app_data), rr->seq_num) <
945296341Sdelphij            0) {
946296341Sdelphij            SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
947296341Sdelphij            return -1;
948296341Sdelphij        }
949296341Sdelphij        rr->length = 0;
950296341Sdelphij        goto start;
951296341Sdelphij    }
952160814Ssimon
953296341Sdelphij    /*
954296341Sdelphij     * If the other end has shut down, throw anything we read away (even in
955296341Sdelphij     * 'peek' mode)
956296341Sdelphij     */
957296341Sdelphij    if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
958296341Sdelphij        rr->length = 0;
959296341Sdelphij        s->rwstate = SSL_NOTHING;
960296341Sdelphij        return (0);
961296341Sdelphij    }
962160814Ssimon
963296341Sdelphij    if (type == rr->type) {     /* SSL3_RT_APPLICATION_DATA or
964296341Sdelphij                                 * SSL3_RT_HANDSHAKE */
965296341Sdelphij        /*
966296341Sdelphij         * make sure that we are not getting application data when we are
967296341Sdelphij         * doing a handshake for the first time
968296341Sdelphij         */
969296341Sdelphij        if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
970296341Sdelphij            (s->enc_read_ctx == NULL)) {
971296341Sdelphij            al = SSL_AD_UNEXPECTED_MESSAGE;
972296341Sdelphij            SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
973296341Sdelphij            goto f_err;
974296341Sdelphij        }
975160814Ssimon
976296341Sdelphij        if (len <= 0)
977296341Sdelphij            return (len);
978160814Ssimon
979296341Sdelphij        if ((unsigned int)len > rr->length)
980296341Sdelphij            n = rr->length;
981296341Sdelphij        else
982296341Sdelphij            n = (unsigned int)len;
983160814Ssimon
984296341Sdelphij        memcpy(buf, &(rr->data[rr->off]), n);
985296341Sdelphij        if (!peek) {
986296341Sdelphij            rr->length -= n;
987296341Sdelphij            rr->off += n;
988296341Sdelphij            if (rr->length == 0) {
989296341Sdelphij                s->rstate = SSL_ST_READ_HEADER;
990296341Sdelphij                rr->off = 0;
991296341Sdelphij            }
992296341Sdelphij        }
993238405Sjkim#ifndef OPENSSL_NO_SCTP
994296341Sdelphij        /*
995296341Sdelphij         * We were about to renegotiate but had to read belated application
996296341Sdelphij         * data first, so retry.
997296341Sdelphij         */
998296341Sdelphij        if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
999296341Sdelphij            rr->type == SSL3_RT_APPLICATION_DATA &&
1000296341Sdelphij            (s->state == DTLS1_SCTP_ST_SR_READ_SOCK
1001296341Sdelphij             || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)) {
1002296341Sdelphij            s->rwstate = SSL_READING;
1003296341Sdelphij            BIO_clear_retry_flags(SSL_get_rbio(s));
1004296341Sdelphij            BIO_set_retry_read(SSL_get_rbio(s));
1005296341Sdelphij        }
1006238405Sjkim
1007296341Sdelphij        /*
1008296341Sdelphij         * We might had to delay a close_notify alert because of reordered
1009296341Sdelphij         * app data. If there was an alert and there is no message to read
1010296341Sdelphij         * anymore, finally set shutdown.
1011296341Sdelphij         */
1012296341Sdelphij        if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
1013296341Sdelphij            s->d1->shutdown_received
1014296341Sdelphij            && !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
1015296341Sdelphij            s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1016296341Sdelphij            return (0);
1017296341Sdelphij        }
1018296341Sdelphij#endif
1019296341Sdelphij        return (n);
1020296341Sdelphij    }
1021160814Ssimon
1022296341Sdelphij    /*
1023296341Sdelphij     * If we get here, then type != rr->type; if we have a handshake message,
1024296341Sdelphij     * then it was unexpected (Hello Request or Client Hello).
1025296341Sdelphij     */
1026160814Ssimon
1027296341Sdelphij    /*
1028296341Sdelphij     * In case of record types for which we have 'fragment' storage, fill
1029296341Sdelphij     * that so that we can process the data at a fixed place.
1030296341Sdelphij     */
1031296341Sdelphij    {
1032296341Sdelphij        unsigned int k, dest_maxlen = 0;
1033296341Sdelphij        unsigned char *dest = NULL;
1034296341Sdelphij        unsigned int *dest_len = NULL;
1035160814Ssimon
1036296341Sdelphij        if (rr->type == SSL3_RT_HANDSHAKE) {
1037296341Sdelphij            dest_maxlen = sizeof s->d1->handshake_fragment;
1038296341Sdelphij            dest = s->d1->handshake_fragment;
1039296341Sdelphij            dest_len = &s->d1->handshake_fragment_len;
1040296341Sdelphij        } else if (rr->type == SSL3_RT_ALERT) {
1041296341Sdelphij            dest_maxlen = sizeof(s->d1->alert_fragment);
1042296341Sdelphij            dest = s->d1->alert_fragment;
1043296341Sdelphij            dest_len = &s->d1->alert_fragment_len;
1044296341Sdelphij        }
1045238405Sjkim#ifndef OPENSSL_NO_HEARTBEATS
1046296341Sdelphij        else if (rr->type == TLS1_RT_HEARTBEAT) {
1047296341Sdelphij            dtls1_process_heartbeat(s);
1048238405Sjkim
1049296341Sdelphij            /* Exit and notify application to read again */
1050296341Sdelphij            rr->length = 0;
1051296341Sdelphij            s->rwstate = SSL_READING;
1052296341Sdelphij            BIO_clear_retry_flags(SSL_get_rbio(s));
1053296341Sdelphij            BIO_set_retry_read(SSL_get_rbio(s));
1054296341Sdelphij            return (-1);
1055296341Sdelphij        }
1056238405Sjkim#endif
1057296341Sdelphij        /* else it's a CCS message, or application data or wrong */
1058296341Sdelphij        else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC) {
1059296341Sdelphij            /*
1060296341Sdelphij             * Application data while renegotiating is allowed. Try again
1061296341Sdelphij             * reading.
1062296341Sdelphij             */
1063296341Sdelphij            if (rr->type == SSL3_RT_APPLICATION_DATA) {
1064296341Sdelphij                BIO *bio;
1065296341Sdelphij                s->s3->in_read_app_data = 2;
1066296341Sdelphij                bio = SSL_get_rbio(s);
1067296341Sdelphij                s->rwstate = SSL_READING;
1068296341Sdelphij                BIO_clear_retry_flags(bio);
1069296341Sdelphij                BIO_set_retry_read(bio);
1070296341Sdelphij                return (-1);
1071296341Sdelphij            }
1072160814Ssimon
1073296341Sdelphij            /* Not certain if this is the right error handling */
1074296341Sdelphij            al = SSL_AD_UNEXPECTED_MESSAGE;
1075296341Sdelphij            SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1076296341Sdelphij            goto f_err;
1077296341Sdelphij        }
1078160814Ssimon
1079296341Sdelphij        if (dest_maxlen > 0) {
1080296341Sdelphij            /*
1081296341Sdelphij             * XDTLS: In a pathalogical case, the Client Hello may be
1082296341Sdelphij             * fragmented--don't always expect dest_maxlen bytes
1083296341Sdelphij             */
1084296341Sdelphij            if (rr->length < dest_maxlen) {
1085194206Ssimon#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
1086296341Sdelphij                /*
1087296341Sdelphij                 * for normal alerts rr->length is 2, while
1088296341Sdelphij                 * dest_maxlen is 7 if we were to handle this
1089296341Sdelphij                 * non-existing alert...
1090296341Sdelphij                 */
1091296341Sdelphij                FIX ME
1092194206Ssimon#endif
1093296341Sdelphij                 s->rstate = SSL_ST_READ_HEADER;
1094296341Sdelphij                rr->length = 0;
1095296341Sdelphij                goto start;
1096296341Sdelphij            }
1097160814Ssimon
1098296341Sdelphij            /* now move 'n' bytes: */
1099296341Sdelphij            for (k = 0; k < dest_maxlen; k++) {
1100296341Sdelphij                dest[k] = rr->data[rr->off++];
1101296341Sdelphij                rr->length--;
1102296341Sdelphij            }
1103296341Sdelphij            *dest_len = dest_maxlen;
1104296341Sdelphij        }
1105296341Sdelphij    }
1106160814Ssimon
1107296341Sdelphij    /*-
1108296341Sdelphij     * s->d1->handshake_fragment_len == 12  iff  rr->type == SSL3_RT_HANDSHAKE;
1109296341Sdelphij     * s->d1->alert_fragment_len == 7      iff  rr->type == SSL3_RT_ALERT.
1110296341Sdelphij     * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1111296341Sdelphij     */
1112160814Ssimon
1113296341Sdelphij    /* If we are a client, check for an incoming 'Hello Request': */
1114296341Sdelphij    if ((!s->server) &&
1115296341Sdelphij        (s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
1116296341Sdelphij        (s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
1117296341Sdelphij        (s->session != NULL) && (s->session->cipher != NULL)) {
1118296341Sdelphij        s->d1->handshake_fragment_len = 0;
1119160814Ssimon
1120296341Sdelphij        if ((s->d1->handshake_fragment[1] != 0) ||
1121296341Sdelphij            (s->d1->handshake_fragment[2] != 0) ||
1122296341Sdelphij            (s->d1->handshake_fragment[3] != 0)) {
1123296341Sdelphij            al = SSL_AD_DECODE_ERROR;
1124296341Sdelphij            SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
1125296341Sdelphij            goto f_err;
1126296341Sdelphij        }
1127160814Ssimon
1128296341Sdelphij        /*
1129296341Sdelphij         * no need to check sequence number on HELLO REQUEST messages
1130296341Sdelphij         */
1131160814Ssimon
1132296341Sdelphij        if (s->msg_callback)
1133296341Sdelphij            s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1134296341Sdelphij                            s->d1->handshake_fragment, 4, s,
1135296341Sdelphij                            s->msg_callback_arg);
1136160814Ssimon
1137296341Sdelphij        if (SSL_is_init_finished(s) &&
1138296341Sdelphij            !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
1139296341Sdelphij            !s->s3->renegotiate) {
1140296341Sdelphij            s->d1->handshake_read_seq++;
1141296341Sdelphij            s->new_session = 1;
1142296341Sdelphij            ssl3_renegotiate(s);
1143296341Sdelphij            if (ssl3_renegotiate_check(s)) {
1144296341Sdelphij                i = s->handshake_func(s);
1145296341Sdelphij                if (i < 0)
1146296341Sdelphij                    return (i);
1147296341Sdelphij                if (i == 0) {
1148296341Sdelphij                    SSLerr(SSL_F_DTLS1_READ_BYTES,
1149296341Sdelphij                           SSL_R_SSL_HANDSHAKE_FAILURE);
1150296341Sdelphij                    return (-1);
1151296341Sdelphij                }
1152160814Ssimon
1153296341Sdelphij                if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1154296341Sdelphij                    if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
1155296341Sdelphij                        BIO *bio;
1156296341Sdelphij                        /*
1157296341Sdelphij                         * In the case where we try to read application data,
1158296341Sdelphij                         * but we trigger an SSL handshake, we return -1 with
1159296341Sdelphij                         * the retry option set.  Otherwise renegotiation may
1160296341Sdelphij                         * cause nasty problems in the blocking world
1161296341Sdelphij                         */
1162296341Sdelphij                        s->rwstate = SSL_READING;
1163296341Sdelphij                        bio = SSL_get_rbio(s);
1164296341Sdelphij                        BIO_clear_retry_flags(bio);
1165296341Sdelphij                        BIO_set_retry_read(bio);
1166296341Sdelphij                        return (-1);
1167296341Sdelphij                    }
1168296341Sdelphij                }
1169296341Sdelphij            }
1170296341Sdelphij        }
1171296341Sdelphij        /*
1172296341Sdelphij         * we either finished a handshake or ignored the request, now try
1173296341Sdelphij         * again to obtain the (application) data we were asked for
1174296341Sdelphij         */
1175296341Sdelphij        goto start;
1176296341Sdelphij    }
1177160814Ssimon
1178296341Sdelphij    if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) {
1179296341Sdelphij        int alert_level = s->d1->alert_fragment[0];
1180296341Sdelphij        int alert_descr = s->d1->alert_fragment[1];
1181160814Ssimon
1182296341Sdelphij        s->d1->alert_fragment_len = 0;
1183160814Ssimon
1184296341Sdelphij        if (s->msg_callback)
1185296341Sdelphij            s->msg_callback(0, s->version, SSL3_RT_ALERT,
1186296341Sdelphij                            s->d1->alert_fragment, 2, s, s->msg_callback_arg);
1187160814Ssimon
1188296341Sdelphij        if (s->info_callback != NULL)
1189296341Sdelphij            cb = s->info_callback;
1190296341Sdelphij        else if (s->ctx->info_callback != NULL)
1191296341Sdelphij            cb = s->ctx->info_callback;
1192160814Ssimon
1193296341Sdelphij        if (cb != NULL) {
1194296341Sdelphij            j = (alert_level << 8) | alert_descr;
1195296341Sdelphij            cb(s, SSL_CB_READ_ALERT, j);
1196296341Sdelphij        }
1197160814Ssimon
1198296341Sdelphij        if (alert_level == SSL3_AL_WARNING) {
1199296341Sdelphij            s->s3->warn_alert = alert_descr;
1200308204Sdelphij
1201308204Sdelphij            s->s3->alert_count++;
1202308204Sdelphij            if (s->s3->alert_count == MAX_WARN_ALERT_COUNT) {
1203308204Sdelphij                al = SSL_AD_UNEXPECTED_MESSAGE;
1204308204Sdelphij                SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_TOO_MANY_WARN_ALERTS);
1205308204Sdelphij                goto f_err;
1206308204Sdelphij            }
1207308204Sdelphij
1208296341Sdelphij            if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
1209238405Sjkim#ifndef OPENSSL_NO_SCTP
1210296341Sdelphij                /*
1211296341Sdelphij                 * With SCTP and streams the socket may deliver app data
1212296341Sdelphij                 * after a close_notify alert. We have to check this first so
1213296341Sdelphij                 * that nothing gets discarded.
1214296341Sdelphij                 */
1215296341Sdelphij                if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
1216296341Sdelphij                    BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
1217296341Sdelphij                    s->d1->shutdown_received = 1;
1218296341Sdelphij                    s->rwstate = SSL_READING;
1219296341Sdelphij                    BIO_clear_retry_flags(SSL_get_rbio(s));
1220296341Sdelphij                    BIO_set_retry_read(SSL_get_rbio(s));
1221296341Sdelphij                    return -1;
1222296341Sdelphij                }
1223238405Sjkim#endif
1224296341Sdelphij                s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1225296341Sdelphij                return (0);
1226296341Sdelphij            }
1227160814Ssimon#if 0
1228160814Ssimon            /* XXX: this is a possible improvement in the future */
1229296341Sdelphij            /* now check if it's a missing record */
1230296341Sdelphij            if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) {
1231296341Sdelphij                unsigned short seq;
1232296341Sdelphij                unsigned int frag_off;
1233296341Sdelphij                unsigned char *p = &(s->d1->alert_fragment[2]);
1234160814Ssimon
1235296341Sdelphij                n2s(p, seq);
1236296341Sdelphij                n2l3(p, frag_off);
1237160814Ssimon
1238296341Sdelphij                dtls1_retransmit_message(s,
1239296341Sdelphij                                         dtls1_get_queue_priority
1240296341Sdelphij                                         (frag->msg_header.seq, 0), frag_off,
1241296341Sdelphij                                         &found);
1242296341Sdelphij                if (!found && SSL_in_init(s)) {
1243296341Sdelphij                    /*
1244296341Sdelphij                     * fprintf( stderr,"in init = %d\n", SSL_in_init(s));
1245296341Sdelphij                     */
1246296341Sdelphij                    /*
1247296341Sdelphij                     * requested a message not yet sent, send an alert
1248296341Sdelphij                     * ourselves
1249296341Sdelphij                     */
1250296341Sdelphij                    ssl3_send_alert(s, SSL3_AL_WARNING,
1251296341Sdelphij                                    DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
1252296341Sdelphij                }
1253296341Sdelphij            }
1254160814Ssimon#endif
1255296341Sdelphij        } else if (alert_level == SSL3_AL_FATAL) {
1256296341Sdelphij            char tmp[16];
1257160814Ssimon
1258296341Sdelphij            s->rwstate = SSL_NOTHING;
1259296341Sdelphij            s->s3->fatal_alert = alert_descr;
1260296341Sdelphij            SSLerr(SSL_F_DTLS1_READ_BYTES,
1261296341Sdelphij                   SSL_AD_REASON_OFFSET + alert_descr);
1262296341Sdelphij            BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
1263296341Sdelphij            ERR_add_error_data(2, "SSL alert number ", tmp);
1264296341Sdelphij            s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1265296341Sdelphij            SSL_CTX_remove_session(s->ctx, s->session);
1266296341Sdelphij            return (0);
1267296341Sdelphij        } else {
1268296341Sdelphij            al = SSL_AD_ILLEGAL_PARAMETER;
1269296341Sdelphij            SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
1270296341Sdelphij            goto f_err;
1271296341Sdelphij        }
1272160814Ssimon
1273296341Sdelphij        goto start;
1274296341Sdelphij    }
1275160814Ssimon
1276296341Sdelphij    if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
1277296341Sdelphij                                            * shutdown */
1278296341Sdelphij        s->rwstate = SSL_NOTHING;
1279296341Sdelphij        rr->length = 0;
1280296341Sdelphij        return (0);
1281296341Sdelphij    }
1282160814Ssimon
1283296341Sdelphij    if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1284296341Sdelphij        struct ccs_header_st ccs_hdr;
1285296341Sdelphij        unsigned int ccs_hdr_len = DTLS1_CCS_HEADER_LENGTH;
1286160814Ssimon
1287296341Sdelphij        dtls1_get_ccs_header(rr->data, &ccs_hdr);
1288160814Ssimon
1289296341Sdelphij        if (s->version == DTLS1_BAD_VER)
1290296341Sdelphij            ccs_hdr_len = 3;
1291238405Sjkim
1292296341Sdelphij        /*
1293296341Sdelphij         * 'Change Cipher Spec' is just a single byte, so we know exactly
1294296341Sdelphij         * what the record payload has to look like
1295296341Sdelphij         */
1296296341Sdelphij        /* XDTLS: check that epoch is consistent */
1297296341Sdelphij        if ((rr->length != ccs_hdr_len) ||
1298296341Sdelphij            (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS)) {
1299296341Sdelphij            i = SSL_AD_ILLEGAL_PARAMETER;
1300296341Sdelphij            SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_CHANGE_CIPHER_SPEC);
1301296341Sdelphij            goto err;
1302296341Sdelphij        }
1303194206Ssimon
1304296341Sdelphij        rr->length = 0;
1305194206Ssimon
1306296341Sdelphij        if (s->msg_callback)
1307296341Sdelphij            s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
1308296341Sdelphij                            rr->data, 1, s, s->msg_callback_arg);
1309194206Ssimon
1310296341Sdelphij        /*
1311296341Sdelphij         * We can't process a CCS now, because previous handshake messages
1312296341Sdelphij         * are still missing, so just drop it.
1313296341Sdelphij         */
1314296341Sdelphij        if (!s->d1->change_cipher_spec_ok) {
1315296341Sdelphij            goto start;
1316296341Sdelphij        }
1317205128Ssimon
1318296341Sdelphij        s->d1->change_cipher_spec_ok = 0;
1319205128Ssimon
1320296341Sdelphij        s->s3->change_cipher_spec = 1;
1321296341Sdelphij        if (!ssl3_do_change_cipher_spec(s))
1322296341Sdelphij            goto err;
1323194206Ssimon
1324296341Sdelphij        /* do this whenever CCS is processed */
1325296341Sdelphij        dtls1_reset_seq_numbers(s, SSL3_CC_READ);
1326194206Ssimon
1327296341Sdelphij        if (s->version == DTLS1_BAD_VER)
1328296341Sdelphij            s->d1->handshake_read_seq++;
1329194206Ssimon
1330238405Sjkim#ifndef OPENSSL_NO_SCTP
1331296341Sdelphij        /*
1332296341Sdelphij         * Remember that a CCS has been received, so that an old key of
1333296341Sdelphij         * SCTP-Auth can be deleted when a CCS is sent. Will be ignored if no
1334296341Sdelphij         * SCTP is used
1335296341Sdelphij         */
1336296341Sdelphij        BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_SCTP_AUTH_CCS_RCVD, 1, NULL);
1337238405Sjkim#endif
1338238405Sjkim
1339296341Sdelphij        goto start;
1340296341Sdelphij    }
1341160814Ssimon
1342296341Sdelphij    /*
1343296341Sdelphij     * Unexpected handshake message (Client Hello, or protocol violation)
1344296341Sdelphij     */
1345296341Sdelphij    if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
1346296341Sdelphij        !s->in_handshake) {
1347296341Sdelphij        struct hm_header_st msg_hdr;
1348160814Ssimon
1349296341Sdelphij        /* this may just be a stale retransmit */
1350296341Sdelphij        dtls1_get_message_header(rr->data, &msg_hdr);
1351296341Sdelphij        if (rr->epoch != s->d1->r_epoch) {
1352296341Sdelphij            rr->length = 0;
1353296341Sdelphij            goto start;
1354296341Sdelphij        }
1355237657Sjkim
1356296341Sdelphij        /*
1357296341Sdelphij         * If we are server, we may have a repeated FINISHED of the client
1358296341Sdelphij         * here, then retransmit our CCS and FINISHED.
1359296341Sdelphij         */
1360296341Sdelphij        if (msg_hdr.type == SSL3_MT_FINISHED) {
1361296341Sdelphij            if (dtls1_check_timeout_num(s) < 0)
1362296341Sdelphij                return -1;
1363205128Ssimon
1364296341Sdelphij            dtls1_retransmit_buffered_messages(s);
1365296341Sdelphij            rr->length = 0;
1366296341Sdelphij            goto start;
1367296341Sdelphij        }
1368296341Sdelphij
1369296341Sdelphij        if (((s->state & SSL_ST_MASK) == SSL_ST_OK) &&
1370296341Sdelphij            !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
1371296341Sdelphij#if 0                           /* worked only because C operator preferences
1372296341Sdelphij                                 * are not as expected (and because this is
1373296341Sdelphij                                 * not really needed for clients except for
1374296341Sdelphij                                 * detecting protocol violations): */
1375296341Sdelphij            s->state = SSL_ST_BEFORE | (s->server)
1376296341Sdelphij                ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
1377160814Ssimon#else
1378296341Sdelphij            s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
1379160814Ssimon#endif
1380296341Sdelphij            s->renegotiate = 1;
1381296341Sdelphij            s->new_session = 1;
1382296341Sdelphij        }
1383296341Sdelphij        i = s->handshake_func(s);
1384296341Sdelphij        if (i < 0)
1385296341Sdelphij            return (i);
1386296341Sdelphij        if (i == 0) {
1387296341Sdelphij            SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1388296341Sdelphij            return (-1);
1389296341Sdelphij        }
1390160814Ssimon
1391296341Sdelphij        if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1392296341Sdelphij            if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
1393296341Sdelphij                BIO *bio;
1394296341Sdelphij                /*
1395296341Sdelphij                 * In the case where we try to read application data, but we
1396296341Sdelphij                 * trigger an SSL handshake, we return -1 with the retry
1397296341Sdelphij                 * option set.  Otherwise renegotiation may cause nasty
1398296341Sdelphij                 * problems in the blocking world
1399296341Sdelphij                 */
1400296341Sdelphij                s->rwstate = SSL_READING;
1401296341Sdelphij                bio = SSL_get_rbio(s);
1402296341Sdelphij                BIO_clear_retry_flags(bio);
1403296341Sdelphij                BIO_set_retry_read(bio);
1404296341Sdelphij                return (-1);
1405296341Sdelphij            }
1406296341Sdelphij        }
1407296341Sdelphij        goto start;
1408296341Sdelphij    }
1409160814Ssimon
1410296341Sdelphij    switch (rr->type) {
1411296341Sdelphij    default:
1412160814Ssimon#ifndef OPENSSL_NO_TLS
1413296341Sdelphij        /* TLS just ignores unknown message types */
1414296341Sdelphij        if (s->version == TLS1_VERSION) {
1415296341Sdelphij            rr->length = 0;
1416296341Sdelphij            goto start;
1417296341Sdelphij        }
1418160814Ssimon#endif
1419296341Sdelphij        al = SSL_AD_UNEXPECTED_MESSAGE;
1420296341Sdelphij        SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1421296341Sdelphij        goto f_err;
1422296341Sdelphij    case SSL3_RT_CHANGE_CIPHER_SPEC:
1423296341Sdelphij    case SSL3_RT_ALERT:
1424296341Sdelphij    case SSL3_RT_HANDSHAKE:
1425296341Sdelphij        /*
1426296341Sdelphij         * we already handled all of these, with the possible exception of
1427296341Sdelphij         * SSL3_RT_HANDSHAKE when s->in_handshake is set, but that should not
1428296341Sdelphij         * happen when type != rr->type
1429296341Sdelphij         */
1430296341Sdelphij        al = SSL_AD_UNEXPECTED_MESSAGE;
1431296341Sdelphij        SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
1432296341Sdelphij        goto f_err;
1433296341Sdelphij    case SSL3_RT_APPLICATION_DATA:
1434296341Sdelphij        /*
1435296341Sdelphij         * At this point, we were expecting handshake data, but have
1436296341Sdelphij         * application data.  If the library was running inside ssl3_read()
1437296341Sdelphij         * (i.e. in_read_app_data is set) and it makes sense to read
1438296341Sdelphij         * application data at this point (session renegotiation not yet
1439296341Sdelphij         * started), we will indulge it.
1440296341Sdelphij         */
1441296341Sdelphij        if (s->s3->in_read_app_data &&
1442296341Sdelphij            (s->s3->total_renegotiations != 0) &&
1443296341Sdelphij            (((s->state & SSL_ST_CONNECT) &&
1444296341Sdelphij              (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1445296341Sdelphij              (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
1446296341Sdelphij             ) || ((s->state & SSL_ST_ACCEPT) &&
1447296341Sdelphij                   (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
1448296341Sdelphij                   (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
1449296341Sdelphij             )
1450296341Sdelphij            )) {
1451296341Sdelphij            s->s3->in_read_app_data = 2;
1452296341Sdelphij            return (-1);
1453296341Sdelphij        } else {
1454296341Sdelphij            al = SSL_AD_UNEXPECTED_MESSAGE;
1455296341Sdelphij            SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1456296341Sdelphij            goto f_err;
1457296341Sdelphij        }
1458296341Sdelphij    }
1459296341Sdelphij    /* not reached */
1460160814Ssimon
1461296341Sdelphij f_err:
1462296341Sdelphij    ssl3_send_alert(s, SSL3_AL_FATAL, al);
1463296341Sdelphij err:
1464296341Sdelphij    return (-1);
1465296341Sdelphij}
1466160814Ssimon
1467296341Sdelphijint dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
1468296341Sdelphij{
1469296341Sdelphij    int i;
1470160814Ssimon
1471238405Sjkim#ifndef OPENSSL_NO_SCTP
1472296341Sdelphij    /*
1473296341Sdelphij     * Check if we have to continue an interrupted handshake for reading
1474296341Sdelphij     * belated app data with SCTP.
1475296341Sdelphij     */
1476296341Sdelphij    if ((SSL_in_init(s) && !s->in_handshake) ||
1477296341Sdelphij        (BIO_dgram_is_sctp(SSL_get_wbio(s)) &&
1478296341Sdelphij         (s->state == DTLS1_SCTP_ST_SR_READ_SOCK
1479296341Sdelphij          || s->state == DTLS1_SCTP_ST_CR_READ_SOCK)))
1480238405Sjkim#else
1481296341Sdelphij    if (SSL_in_init(s) && !s->in_handshake)
1482238405Sjkim#endif
1483296341Sdelphij    {
1484296341Sdelphij        i = s->handshake_func(s);
1485296341Sdelphij        if (i < 0)
1486296341Sdelphij            return (i);
1487296341Sdelphij        if (i == 0) {
1488296341Sdelphij            SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES,
1489296341Sdelphij                   SSL_R_SSL_HANDSHAKE_FAILURE);
1490296341Sdelphij            return -1;
1491296341Sdelphij        }
1492296341Sdelphij    }
1493160814Ssimon
1494296341Sdelphij    if (len > SSL3_RT_MAX_PLAIN_LENGTH) {
1495296341Sdelphij        SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES, SSL_R_DTLS_MESSAGE_TOO_BIG);
1496296341Sdelphij        return -1;
1497296341Sdelphij    }
1498160814Ssimon
1499296341Sdelphij    i = dtls1_write_bytes(s, type, buf_, len);
1500296341Sdelphij    return i;
1501296341Sdelphij}
1502160814Ssimon
1503296341Sdelphij        /*
1504296341Sdelphij         * this only happens when a client hello is received and a handshake
1505296341Sdelphij         * is started.
1506296341Sdelphij         */
1507160814Ssimonstatic int
1508296341Sdelphijhave_handshake_fragment(SSL *s, int type, unsigned char *buf,
1509296341Sdelphij                        int len, int peek)
1510296341Sdelphij{
1511160814Ssimon
1512296341Sdelphij    if ((type == SSL3_RT_HANDSHAKE) && (s->d1->handshake_fragment_len > 0))
1513296341Sdelphij        /* (partially) satisfy request from storage */
1514296341Sdelphij    {
1515296341Sdelphij        unsigned char *src = s->d1->handshake_fragment;
1516296341Sdelphij        unsigned char *dst = buf;
1517296341Sdelphij        unsigned int k, n;
1518160814Ssimon
1519296341Sdelphij        /* peek == 0 */
1520296341Sdelphij        n = 0;
1521296341Sdelphij        while ((len > 0) && (s->d1->handshake_fragment_len > 0)) {
1522296341Sdelphij            *dst++ = *src++;
1523296341Sdelphij            len--;
1524296341Sdelphij            s->d1->handshake_fragment_len--;
1525296341Sdelphij            n++;
1526296341Sdelphij        }
1527296341Sdelphij        /* move any remaining fragment bytes: */
1528296341Sdelphij        for (k = 0; k < s->d1->handshake_fragment_len; k++)
1529296341Sdelphij            s->d1->handshake_fragment[k] = *src++;
1530296341Sdelphij        return n;
1531296341Sdelphij    }
1532160814Ssimon
1533296341Sdelphij    return 0;
1534296341Sdelphij}
1535160814Ssimon
1536296341Sdelphij/*
1537296341Sdelphij * Call this to write data in records of type 'type' It will return <= 0 if
1538296341Sdelphij * not all data has been sent or non-blocking IO.
1539160814Ssimon */
1540205128Ssimonint dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
1541296341Sdelphij{
1542296341Sdelphij    int i;
1543160814Ssimon
1544296341Sdelphij    OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
1545296341Sdelphij    s->rwstate = SSL_NOTHING;
1546296341Sdelphij    i = do_dtls1_write(s, type, buf, len, 0);
1547296341Sdelphij    return i;
1548296341Sdelphij}
1549160814Ssimon
1550296341Sdelphijint do_dtls1_write(SSL *s, int type, const unsigned char *buf,
1551296341Sdelphij                   unsigned int len, int create_empty_fragment)
1552296341Sdelphij{
1553296341Sdelphij    unsigned char *p, *pseq;
1554296341Sdelphij    int i, mac_size, clear = 0;
1555296341Sdelphij    int prefix_len = 0;
1556296341Sdelphij    SSL3_RECORD *wr;
1557296341Sdelphij    SSL3_BUFFER *wb;
1558296341Sdelphij    SSL_SESSION *sess;
1559296341Sdelphij    int bs;
1560160814Ssimon
1561296341Sdelphij    /*
1562296341Sdelphij     * first check if there is a SSL3_BUFFER still being written out.  This
1563296341Sdelphij     * will happen with non blocking IO
1564296341Sdelphij     */
1565296341Sdelphij    if (s->s3->wbuf.left != 0) {
1566296341Sdelphij        OPENSSL_assert(0);      /* XDTLS: want to see if we ever get here */
1567296341Sdelphij        return (ssl3_write_pending(s, type, buf, len));
1568296341Sdelphij    }
1569160814Ssimon
1570296341Sdelphij    /* If we have an alert to send, lets send it */
1571296341Sdelphij    if (s->s3->alert_dispatch) {
1572296341Sdelphij        i = s->method->ssl_dispatch_alert(s);
1573296341Sdelphij        if (i <= 0)
1574296341Sdelphij            return (i);
1575296341Sdelphij        /* if it went, fall through and send more stuff */
1576296341Sdelphij    }
1577160814Ssimon
1578296341Sdelphij    if (len == 0 && !create_empty_fragment)
1579296341Sdelphij        return 0;
1580160814Ssimon
1581296341Sdelphij    wr = &(s->s3->wrec);
1582296341Sdelphij    wb = &(s->s3->wbuf);
1583296341Sdelphij    sess = s->session;
1584160814Ssimon
1585296341Sdelphij    if ((sess == NULL) ||
1586296341Sdelphij        (s->enc_write_ctx == NULL) || (EVP_MD_CTX_md(s->write_hash) == NULL))
1587296341Sdelphij        clear = 1;
1588160814Ssimon
1589296341Sdelphij    if (clear)
1590296341Sdelphij        mac_size = 0;
1591296341Sdelphij    else {
1592296341Sdelphij        mac_size = EVP_MD_CTX_size(s->write_hash);
1593296341Sdelphij        if (mac_size < 0)
1594296341Sdelphij            goto err;
1595296341Sdelphij    }
1596160814Ssimon
1597296341Sdelphij    /* DTLS implements explicit IV, so no need for empty fragments */
1598160814Ssimon#if 0
1599296341Sdelphij    /*
1600296341Sdelphij     * 'create_empty_fragment' is true only when this function calls itself
1601296341Sdelphij     */
1602296341Sdelphij    if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done
1603296341Sdelphij        && SSL_version(s) != DTLS1_VERSION && SSL_version(s) != DTLS1_BAD_VER)
1604296341Sdelphij    {
1605296341Sdelphij        /*
1606296341Sdelphij         * countermeasure against known-IV weakness in CBC ciphersuites (see
1607296341Sdelphij         * http://www.openssl.org/~bodo/tls-cbc.txt)
1608296341Sdelphij         */
1609160814Ssimon
1610296341Sdelphij        if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
1611296341Sdelphij            /*
1612296341Sdelphij             * recursive function call with 'create_empty_fragment' set; this
1613296341Sdelphij             * prepares and buffers the data for an empty fragment (these
1614296341Sdelphij             * 'prefix_len' bytes are sent out later together with the actual
1615296341Sdelphij             * payload)
1616296341Sdelphij             */
1617296341Sdelphij            prefix_len = s->method->do_ssl_write(s, type, buf, 0, 1);
1618296341Sdelphij            if (prefix_len <= 0)
1619296341Sdelphij                goto err;
1620160814Ssimon
1621296341Sdelphij            if (s->s3->wbuf.len <
1622296341Sdelphij                (size_t)prefix_len + SSL3_RT_MAX_PACKET_SIZE) {
1623296341Sdelphij                /* insufficient space */
1624296341Sdelphij                SSLerr(SSL_F_DO_DTLS1_WRITE, ERR_R_INTERNAL_ERROR);
1625296341Sdelphij                goto err;
1626296341Sdelphij            }
1627296341Sdelphij        }
1628296341Sdelphij
1629296341Sdelphij        s->s3->empty_fragment_done = 1;
1630296341Sdelphij    }
1631160814Ssimon#endif
1632296341Sdelphij    p = wb->buf + prefix_len;
1633160814Ssimon
1634296341Sdelphij    /* write the header */
1635160814Ssimon
1636296341Sdelphij    *(p++) = type & 0xff;
1637296341Sdelphij    wr->type = type;
1638160814Ssimon
1639296341Sdelphij    *(p++) = (s->version >> 8);
1640296341Sdelphij    *(p++) = s->version & 0xff;
1641160814Ssimon
1642296341Sdelphij    /* field where we are to write out packet epoch, seq num and len */
1643296341Sdelphij    pseq = p;
1644296341Sdelphij    p += 10;
1645160814Ssimon
1646296341Sdelphij    /* lets setup the record stuff. */
1647160814Ssimon
1648296341Sdelphij    /*
1649296341Sdelphij     * Make space for the explicit IV in case of CBC. (this is a bit of a
1650296341Sdelphij     * boundary violation, but what the heck).
1651296341Sdelphij     */
1652296341Sdelphij    if (s->enc_write_ctx &&
1653296341Sdelphij        (EVP_CIPHER_mode(s->enc_write_ctx->cipher) & EVP_CIPH_CBC_MODE))
1654296341Sdelphij        bs = EVP_CIPHER_block_size(s->enc_write_ctx->cipher);
1655296341Sdelphij    else
1656296341Sdelphij        bs = 0;
1657160814Ssimon
1658296341Sdelphij    wr->data = p + bs;          /* make room for IV in case of CBC */
1659296341Sdelphij    wr->length = (int)len;
1660296341Sdelphij    wr->input = (unsigned char *)buf;
1661160814Ssimon
1662296341Sdelphij    /*
1663296341Sdelphij     * we now 'read' from wr->input, wr->length bytes into wr->data
1664296341Sdelphij     */
1665160814Ssimon
1666296341Sdelphij    /* first we compress */
1667296341Sdelphij    if (s->compress != NULL) {
1668296341Sdelphij        if (!ssl3_do_compress(s)) {
1669296341Sdelphij            SSLerr(SSL_F_DO_DTLS1_WRITE, SSL_R_COMPRESSION_FAILURE);
1670296341Sdelphij            goto err;
1671296341Sdelphij        }
1672296341Sdelphij    } else {
1673296341Sdelphij        memcpy(wr->data, wr->input, wr->length);
1674296341Sdelphij        wr->input = wr->data;
1675296341Sdelphij    }
1676160814Ssimon
1677296341Sdelphij    /*
1678296341Sdelphij     * we should still have the output to wr->data and the input from
1679296341Sdelphij     * wr->input.  Length should be wr->length. wr->data still points in the
1680296341Sdelphij     * wb->buf
1681296341Sdelphij     */
1682160814Ssimon
1683296341Sdelphij    if (mac_size != 0) {
1684296341Sdelphij        if (s->method->ssl3_enc->mac(s, &(p[wr->length + bs]), 1) < 0)
1685296341Sdelphij            goto err;
1686296341Sdelphij        wr->length += mac_size;
1687296341Sdelphij    }
1688160814Ssimon
1689296341Sdelphij    /* this is true regardless of mac size */
1690296341Sdelphij    wr->input = p;
1691296341Sdelphij    wr->data = p;
1692160814Ssimon
1693296341Sdelphij    /* ssl3_enc can only have an error on read */
1694296341Sdelphij    if (bs) {                   /* bs != 0 in case of CBC */
1695296341Sdelphij        RAND_pseudo_bytes(p, bs);
1696296341Sdelphij        /*
1697296341Sdelphij         * master IV and last CBC residue stand for the rest of randomness
1698296341Sdelphij         */
1699296341Sdelphij        wr->length += bs;
1700296341Sdelphij    }
1701160814Ssimon
1702296341Sdelphij    if (s->method->ssl3_enc->enc(s, 1) < 1)
1703296341Sdelphij        goto err;
1704194206Ssimon
1705296341Sdelphij    /* record length after mac and block padding */
1706296341Sdelphij    /*
1707296341Sdelphij     * if (type == SSL3_RT_APPLICATION_DATA || (type == SSL3_RT_ALERT && !
1708296341Sdelphij     * SSL_in_init(s)))
1709296341Sdelphij     */
1710160814Ssimon
1711296341Sdelphij    /* there's only one epoch between handshake and app data */
1712160814Ssimon
1713296341Sdelphij    s2n(s->d1->w_epoch, pseq);
1714160814Ssimon
1715296341Sdelphij    /* XDTLS: ?? */
1716296341Sdelphij    /*
1717296341Sdelphij     * else s2n(s->d1->handshake_epoch, pseq);
1718296341Sdelphij     */
1719160814Ssimon
1720296341Sdelphij    memcpy(pseq, &(s->s3->write_sequence[2]), 6);
1721296341Sdelphij    pseq += 6;
1722296341Sdelphij    s2n(wr->length, pseq);
1723160814Ssimon
1724296341Sdelphij    /*
1725296341Sdelphij     * we should now have wr->data pointing to the encrypted data, which is
1726296341Sdelphij     * wr->length long
1727296341Sdelphij     */
1728296341Sdelphij    wr->type = type;            /* not needed but helps for debugging */
1729296341Sdelphij    wr->length += DTLS1_RT_HEADER_LENGTH;
1730296341Sdelphij
1731296341Sdelphij#if 0                           /* this is now done at the message layer */
1732296341Sdelphij    /* buffer the record, making it easy to handle retransmits */
1733296341Sdelphij    if (type == SSL3_RT_HANDSHAKE || type == SSL3_RT_CHANGE_CIPHER_SPEC)
1734296341Sdelphij        dtls1_buffer_record(s, wr->data, wr->length,
1735296341Sdelphij                            *((PQ_64BIT *) & (s->s3->write_sequence[0])));
1736160814Ssimon#endif
1737160814Ssimon
1738296341Sdelphij    ssl3_record_sequence_update(&(s->s3->write_sequence[0]));
1739160814Ssimon
1740296341Sdelphij    if (create_empty_fragment) {
1741296341Sdelphij        /*
1742296341Sdelphij         * we are in a recursive call; just return the length, don't write
1743296341Sdelphij         * out anything here
1744296341Sdelphij         */
1745296341Sdelphij        return wr->length;
1746296341Sdelphij    }
1747160814Ssimon
1748296341Sdelphij    /* now let's set up wb */
1749296341Sdelphij    wb->left = prefix_len + wr->length;
1750296341Sdelphij    wb->offset = 0;
1751160814Ssimon
1752296341Sdelphij    /*
1753296341Sdelphij     * memorize arguments so that ssl3_write_pending can detect bad write
1754296341Sdelphij     * retries later
1755296341Sdelphij     */
1756296341Sdelphij    s->s3->wpend_tot = len;
1757296341Sdelphij    s->s3->wpend_buf = buf;
1758296341Sdelphij    s->s3->wpend_type = type;
1759296341Sdelphij    s->s3->wpend_ret = len;
1760160814Ssimon
1761296341Sdelphij    /* we now just need to write the buffer */
1762296341Sdelphij    return ssl3_write_pending(s, type, buf, len);
1763296341Sdelphij err:
1764296341Sdelphij    return -1;
1765296341Sdelphij}
1766160814Ssimon
1767238405Sjkimstatic int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap)
1768296341Sdelphij{
1769296341Sdelphij    int cmp;
1770296341Sdelphij    unsigned int shift;
1771296341Sdelphij    const unsigned char *seq = s->s3->read_sequence;
1772160814Ssimon
1773296341Sdelphij    cmp = satsub64be(seq, bitmap->max_seq_num);
1774296341Sdelphij    if (cmp > 0) {
1775296341Sdelphij        memcpy(s->s3->rrec.seq_num, seq, 8);
1776296341Sdelphij        return 1;               /* this record in new */
1777296341Sdelphij    }
1778296341Sdelphij    shift = -cmp;
1779296341Sdelphij    if (shift >= sizeof(bitmap->map) * 8)
1780296341Sdelphij        return 0;               /* stale, outside the window */
1781296341Sdelphij    else if (bitmap->map & (1UL << shift))
1782296341Sdelphij        return 0;               /* record previously received */
1783160814Ssimon
1784296341Sdelphij    memcpy(s->s3->rrec.seq_num, seq, 8);
1785296341Sdelphij    return 1;
1786296341Sdelphij}
1787160814Ssimon
1788160814Ssimonstatic void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap)
1789296341Sdelphij{
1790296341Sdelphij    int cmp;
1791296341Sdelphij    unsigned int shift;
1792296341Sdelphij    const unsigned char *seq = s->s3->read_sequence;
1793160814Ssimon
1794296341Sdelphij    cmp = satsub64be(seq, bitmap->max_seq_num);
1795296341Sdelphij    if (cmp > 0) {
1796296341Sdelphij        shift = cmp;
1797296341Sdelphij        if (shift < sizeof(bitmap->map) * 8)
1798296341Sdelphij            bitmap->map <<= shift, bitmap->map |= 1UL;
1799296341Sdelphij        else
1800296341Sdelphij            bitmap->map = 1UL;
1801296341Sdelphij        memcpy(bitmap->max_seq_num, seq, 8);
1802296341Sdelphij    } else {
1803296341Sdelphij        shift = -cmp;
1804296341Sdelphij        if (shift < sizeof(bitmap->map) * 8)
1805296341Sdelphij            bitmap->map |= 1UL << shift;
1806296341Sdelphij    }
1807296341Sdelphij}
1808160814Ssimon
1809160814Ssimonint dtls1_dispatch_alert(SSL *s)
1810296341Sdelphij{
1811296341Sdelphij    int i, j;
1812296341Sdelphij    void (*cb) (const SSL *ssl, int type, int val) = NULL;
1813296341Sdelphij    unsigned char buf[DTLS1_AL_HEADER_LENGTH];
1814296341Sdelphij    unsigned char *ptr = &buf[0];
1815160814Ssimon
1816296341Sdelphij    s->s3->alert_dispatch = 0;
1817160814Ssimon
1818296341Sdelphij    memset(buf, 0x00, sizeof(buf));
1819296341Sdelphij    *ptr++ = s->s3->send_alert[0];
1820296341Sdelphij    *ptr++ = s->s3->send_alert[1];
1821160814Ssimon
1822194206Ssimon#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
1823296341Sdelphij    if (s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) {
1824296341Sdelphij        s2n(s->d1->handshake_read_seq, ptr);
1825296341Sdelphij# if 0
1826296341Sdelphij        if (s->d1->r_msg_hdr.frag_off == 0)
1827296341Sdelphij            /*
1828296341Sdelphij             * waiting for a new msg
1829296341Sdelphij             */
1830296341Sdelphij            else
1831296341Sdelphij            s2n(s->d1->r_msg_hdr.seq, ptr); /* partial msg read */
1832296341Sdelphij# endif
1833160814Ssimon
1834296341Sdelphij# if 0
1835296341Sdelphij        fprintf(stderr,
1836296341Sdelphij                "s->d1->handshake_read_seq = %d, s->d1->r_msg_hdr.seq = %d\n",
1837296341Sdelphij                s->d1->handshake_read_seq, s->d1->r_msg_hdr.seq);
1838296341Sdelphij# endif
1839296341Sdelphij        l2n3(s->d1->r_msg_hdr.frag_off, ptr);
1840296341Sdelphij    }
1841160814Ssimon#endif
1842160814Ssimon
1843296341Sdelphij    i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf), 0);
1844296341Sdelphij    if (i <= 0) {
1845296341Sdelphij        s->s3->alert_dispatch = 1;
1846296341Sdelphij        /* fprintf( stderr, "not done with alert\n" ); */
1847296341Sdelphij    } else {
1848296341Sdelphij        if (s->s3->send_alert[0] == SSL3_AL_FATAL
1849194206Ssimon#ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
1850296341Sdelphij            || s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
1851194206Ssimon#endif
1852296341Sdelphij            )
1853296341Sdelphij            (void)BIO_flush(s->wbio);
1854160814Ssimon
1855296341Sdelphij        if (s->msg_callback)
1856296341Sdelphij            s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert,
1857296341Sdelphij                            2, s, s->msg_callback_arg);
1858160814Ssimon
1859296341Sdelphij        if (s->info_callback != NULL)
1860296341Sdelphij            cb = s->info_callback;
1861296341Sdelphij        else if (s->ctx->info_callback != NULL)
1862296341Sdelphij            cb = s->ctx->info_callback;
1863160814Ssimon
1864296341Sdelphij        if (cb != NULL) {
1865296341Sdelphij            j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
1866296341Sdelphij            cb(s, SSL_CB_WRITE_ALERT, j);
1867296341Sdelphij        }
1868296341Sdelphij    }
1869296341Sdelphij    return (i);
1870296341Sdelphij}
1871160814Ssimon
1872296341Sdelphijstatic DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
1873296341Sdelphij                                      unsigned int *is_next_epoch)
1874296341Sdelphij{
1875160814Ssimon
1876160814Ssimon    *is_next_epoch = 0;
1877160814Ssimon
1878160814Ssimon    /* In current epoch, accept HM, CCS, DATA, & ALERT */
1879160814Ssimon    if (rr->epoch == s->d1->r_epoch)
1880160814Ssimon        return &s->d1->bitmap;
1881160814Ssimon
1882306230Sdelphij    /*
1883306230Sdelphij     * Only HM and ALERT messages can be from the next epoch and only if we
1884306230Sdelphij     * have already processed all of the unprocessed records from the last
1885306230Sdelphij     * epoch
1886306230Sdelphij     */
1887160814Ssimon    else if (rr->epoch == (unsigned long)(s->d1->r_epoch + 1) &&
1888306230Sdelphij             s->d1->unprocessed_rcds.epoch != s->d1->r_epoch &&
1889296341Sdelphij             (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
1890160814Ssimon        *is_next_epoch = 1;
1891160814Ssimon        return &s->d1->next_bitmap;
1892296341Sdelphij    }
1893160814Ssimon
1894160814Ssimon    return NULL;
1895296341Sdelphij}
1896160814Ssimon
1897160814Ssimon#if 0
1898160814Ssimonstatic int
1899296341Sdelphijdtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr,
1900296341Sdelphij                             unsigned short *priority, unsigned long *offset)
1901296341Sdelphij{
1902160814Ssimon
1903296341Sdelphij    /* alerts are passed up immediately */
1904296341Sdelphij    if (rr->type == SSL3_RT_APPLICATION_DATA || rr->type == SSL3_RT_ALERT)
1905296341Sdelphij        return 0;
1906160814Ssimon
1907296341Sdelphij    /*
1908296341Sdelphij     * Only need to buffer if a handshake is underway. (this implies that
1909296341Sdelphij     * Hello Request and Client Hello are passed up immediately)
1910296341Sdelphij     */
1911296341Sdelphij    if (SSL_in_init(s)) {
1912296341Sdelphij        unsigned char *data = rr->data;
1913296341Sdelphij        /* need to extract the HM/CCS sequence number here */
1914296341Sdelphij        if (rr->type == SSL3_RT_HANDSHAKE ||
1915296341Sdelphij            rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1916296341Sdelphij            unsigned short seq_num;
1917296341Sdelphij            struct hm_header_st msg_hdr;
1918296341Sdelphij            struct ccs_header_st ccs_hdr;
1919160814Ssimon
1920296341Sdelphij            if (rr->type == SSL3_RT_HANDSHAKE) {
1921296341Sdelphij                dtls1_get_message_header(data, &msg_hdr);
1922296341Sdelphij                seq_num = msg_hdr.seq;
1923296341Sdelphij                *offset = msg_hdr.frag_off;
1924296341Sdelphij            } else {
1925296341Sdelphij                dtls1_get_ccs_header(data, &ccs_hdr);
1926296341Sdelphij                seq_num = ccs_hdr.seq;
1927296341Sdelphij                *offset = 0;
1928296341Sdelphij            }
1929160814Ssimon
1930296341Sdelphij            /*
1931296341Sdelphij             * this is either a record we're waiting for, or a retransmit of
1932296341Sdelphij             * something we happened to previously receive (higher layers
1933296341Sdelphij             * will drop the repeat silently
1934296341Sdelphij             */
1935296341Sdelphij            if (seq_num < s->d1->handshake_read_seq)
1936296341Sdelphij                return 0;
1937296341Sdelphij            if (rr->type == SSL3_RT_HANDSHAKE &&
1938296341Sdelphij                seq_num == s->d1->handshake_read_seq &&
1939296341Sdelphij                msg_hdr.frag_off < s->d1->r_msg_hdr.frag_off)
1940296341Sdelphij                return 0;
1941296341Sdelphij            else if (seq_num == s->d1->handshake_read_seq &&
1942296341Sdelphij                     (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC ||
1943296341Sdelphij                      msg_hdr.frag_off == s->d1->r_msg_hdr.frag_off))
1944296341Sdelphij                return 0;
1945296341Sdelphij            else {
1946296341Sdelphij                *priority = seq_num;
1947296341Sdelphij                return 1;
1948296341Sdelphij            }
1949296341Sdelphij        } else                  /* unknown record type */
1950296341Sdelphij            return 0;
1951296341Sdelphij    }
1952296341Sdelphij
1953296341Sdelphij    return 0;
1954296341Sdelphij}
1955160814Ssimon#endif
1956160814Ssimon
1957296341Sdelphijvoid dtls1_reset_seq_numbers(SSL *s, int rw)
1958296341Sdelphij{
1959296341Sdelphij    unsigned char *seq;
1960296341Sdelphij    unsigned int seq_bytes = sizeof(s->s3->read_sequence);
1961160814Ssimon
1962296341Sdelphij    if (rw & SSL3_CC_READ) {
1963296341Sdelphij        seq = s->s3->read_sequence;
1964296341Sdelphij        s->d1->r_epoch++;
1965296341Sdelphij        memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
1966296341Sdelphij        memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
1967306230Sdelphij
1968306230Sdelphij        /*
1969306230Sdelphij         * We must not use any buffered messages received from the previous
1970306230Sdelphij         * epoch
1971306230Sdelphij         */
1972306230Sdelphij        dtls1_clear_received_buffer(s);
1973296341Sdelphij    } else {
1974296341Sdelphij        seq = s->s3->write_sequence;
1975296341Sdelphij        memcpy(s->d1->last_write_sequence, seq,
1976296341Sdelphij               sizeof(s->s3->write_sequence));
1977296341Sdelphij        s->d1->w_epoch++;
1978296341Sdelphij    }
1979160814Ssimon
1980296341Sdelphij    memset(seq, 0x00, seq_bytes);
1981296341Sdelphij}
1982