155714Skris/* ssl/s3_pkt.c */
255714Skris/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
355714Skris * All rights reserved.
455714Skris *
555714Skris * This package is an SSL implementation written
655714Skris * by Eric Young (eay@cryptsoft.com).
755714Skris * The implementation was written so as to conform with Netscapes SSL.
8296465Sdelphij *
955714Skris * This library is free for commercial and non-commercial use as long as
1055714Skris * the following conditions are aheared to.  The following conditions
1155714Skris * apply to all code found in this distribution, be it the RC4, RSA,
1255714Skris * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
1355714Skris * included with this distribution is covered by the same copyright terms
1455714Skris * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15296465Sdelphij *
1655714Skris * Copyright remains Eric Young's, and as such any Copyright notices in
1755714Skris * the code are not to be removed.
1855714Skris * If this package is used in a product, Eric Young should be given attribution
1955714Skris * as the author of the parts of the library used.
2055714Skris * This can be in the form of a textual message at program startup or
2155714Skris * in documentation (online or textual) provided with the package.
22296465Sdelphij *
2355714Skris * Redistribution and use in source and binary forms, with or without
2455714Skris * modification, are permitted provided that the following conditions
2555714Skris * are met:
2655714Skris * 1. Redistributions of source code must retain the copyright
2755714Skris *    notice, this list of conditions and the following disclaimer.
2855714Skris * 2. Redistributions in binary form must reproduce the above copyright
2955714Skris *    notice, this list of conditions and the following disclaimer in the
3055714Skris *    documentation and/or other materials provided with the distribution.
3155714Skris * 3. All advertising materials mentioning features or use of this software
3255714Skris *    must display the following acknowledgement:
3355714Skris *    "This product includes cryptographic software written by
3455714Skris *     Eric Young (eay@cryptsoft.com)"
3555714Skris *    The word 'cryptographic' can be left out if the rouines from the library
3655714Skris *    being used are not cryptographic related :-).
37296465Sdelphij * 4. If you include any Windows specific code (or a derivative thereof) from
3855714Skris *    the apps directory (application code) you must include an acknowledgement:
3955714Skris *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40296465Sdelphij *
4155714Skris * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
4255714Skris * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
4355714Skris * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
4455714Skris * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
4555714Skris * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
4655714Skris * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
4755714Skris * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
4855714Skris * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
4955714Skris * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
5055714Skris * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
5155714Skris * SUCH DAMAGE.
52296465Sdelphij *
5355714Skris * The licence and distribution terms for any publically available version or
5455714Skris * derivative of this code cannot be changed.  i.e. this code cannot simply be
5555714Skris * copied and put under another distribution licence
5655714Skris * [including the GNU Public Licence.]
5755714Skris */
5859191Skris/* ====================================================================
59100928Snectar * Copyright (c) 1998-2002 The OpenSSL Project.  All rights reserved.
6059191Skris *
6159191Skris * Redistribution and use in source and binary forms, with or without
6259191Skris * modification, are permitted provided that the following conditions
6359191Skris * are met:
6459191Skris *
6559191Skris * 1. Redistributions of source code must retain the above copyright
66296465Sdelphij *    notice, this list of conditions and the following disclaimer.
6759191Skris *
6859191Skris * 2. Redistributions in binary form must reproduce the above copyright
6959191Skris *    notice, this list of conditions and the following disclaimer in
7059191Skris *    the documentation and/or other materials provided with the
7159191Skris *    distribution.
7259191Skris *
7359191Skris * 3. All advertising materials mentioning features or use of this
7459191Skris *    software must display the following acknowledgment:
7559191Skris *    "This product includes software developed by the OpenSSL Project
7659191Skris *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
7759191Skris *
7859191Skris * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
7959191Skris *    endorse or promote products derived from this software without
8059191Skris *    prior written permission. For written permission, please contact
8159191Skris *    openssl-core@openssl.org.
8259191Skris *
8359191Skris * 5. Products derived from this software may not be called "OpenSSL"
8459191Skris *    nor may "OpenSSL" appear in their names without prior written
8559191Skris *    permission of the OpenSSL Project.
8659191Skris *
8759191Skris * 6. Redistributions of any form whatsoever must retain the following
8859191Skris *    acknowledgment:
8959191Skris *    "This product includes software developed by the OpenSSL Project
9059191Skris *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
9159191Skris *
9259191Skris * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
9359191Skris * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
9459191Skris * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
9559191Skris * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
9659191Skris * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
9759191Skris * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
9859191Skris * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
9959191Skris * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
10059191Skris * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
10159191Skris * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
10259191Skris * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
10359191Skris * OF THE POSSIBILITY OF SUCH DAMAGE.
10459191Skris * ====================================================================
10559191Skris *
10659191Skris * This product includes cryptographic software written by Eric Young
10759191Skris * (eay@cryptsoft.com).  This product includes software written by Tim
10859191Skris * Hudson (tjh@cryptsoft.com).
10959191Skris *
11059191Skris */
11155714Skris
11255714Skris#include <stdio.h>
113279265Sdelphij#include <limits.h>
11455714Skris#include <errno.h>
11555714Skris#define USE_SOCKETS
116109998Smarkm#include "ssl_locl.h"
11755714Skris#include <openssl/evp.h>
11855714Skris#include <openssl/buffer.h>
11955714Skris
12055714Skrisstatic int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
121296465Sdelphij                         unsigned int len, int create_empty_fragment);
12255714Skrisstatic int ssl3_get_record(SSL *s);
12359191Skris
124160814Ssimonint ssl3_read_n(SSL *s, int n, int max, int extend)
125296465Sdelphij{
126296465Sdelphij    /*
127296465Sdelphij     * If extend == 0, obtain new n-byte packet; if extend == 1, increase
128296465Sdelphij     * packet by another n bytes. The packet will be in the sub-array of
129296465Sdelphij     * s->s3->rbuf.buf specified by s->packet and s->packet_length. (If
130296465Sdelphij     * s->read_ahead is set, 'max' bytes may be stored in rbuf [plus
131296465Sdelphij     * s->packet_length bytes if extend == 1].)
132296465Sdelphij     */
133296465Sdelphij    int i, off, newb;
13455714Skris
135296465Sdelphij    if (!extend) {
136296465Sdelphij        /* start with empty packet ... */
137296465Sdelphij        if (s->s3->rbuf.left == 0)
138296465Sdelphij            s->s3->rbuf.offset = 0;
139296465Sdelphij        s->packet = s->s3->rbuf.buf + s->s3->rbuf.offset;
140296465Sdelphij        s->packet_length = 0;
141296465Sdelphij        /* ... now we can act as if 'extend' was set */
142296465Sdelphij    }
14359191Skris
144296465Sdelphij    /*
145296465Sdelphij     * For DTLS/UDP reads should not span multiple packets because the read
146296465Sdelphij     * operation returns the whole packet at once (as long as it fits into
147296465Sdelphij     * the buffer).
148296465Sdelphij     */
149296465Sdelphij    if (SSL_version(s) == DTLS1_VERSION) {
150296465Sdelphij        if (s->s3->rbuf.left == 0 && extend)
151296465Sdelphij            return 0;
152296465Sdelphij        if (s->s3->rbuf.left > 0 && n > s->s3->rbuf.left)
153296465Sdelphij            n = s->s3->rbuf.left;
154296465Sdelphij    }
155160814Ssimon
156296465Sdelphij    /* if there is enough in the buffer from a previous read, take some */
157296465Sdelphij    if (s->s3->rbuf.left >= (int)n) {
158296465Sdelphij        s->packet_length += n;
159296465Sdelphij        s->s3->rbuf.left -= n;
160296465Sdelphij        s->s3->rbuf.offset += n;
161296465Sdelphij        return (n);
162296465Sdelphij    }
16355714Skris
164296465Sdelphij    /* else we need to read more data */
165296465Sdelphij    if (!s->read_ahead)
166296465Sdelphij        max = n;
16755714Skris
168296465Sdelphij    {
169296465Sdelphij        /* avoid buffer overflow */
170296465Sdelphij        int max_max = s->s3->rbuf.len - s->packet_length;
171296465Sdelphij        if (max > max_max)
172296465Sdelphij            max = max_max;
173296465Sdelphij    }
174296465Sdelphij    if (n > max) {              /* does not happen */
175296465Sdelphij        SSLerr(SSL_F_SSL3_READ_N, ERR_R_INTERNAL_ERROR);
176296465Sdelphij        return -1;
177296465Sdelphij    }
17855714Skris
179296465Sdelphij    off = s->packet_length;
180296465Sdelphij    newb = s->s3->rbuf.left;
181296465Sdelphij    /*
182296465Sdelphij     * Move any available bytes to front of buffer: 'off' bytes already
183296465Sdelphij     * pointed to by 'packet', 'newb' extra ones at the end
184296465Sdelphij     */
185296465Sdelphij    if (s->packet != s->s3->rbuf.buf) {
186296465Sdelphij        /*  off > 0 */
187296465Sdelphij        memmove(s->s3->rbuf.buf, s->packet, off + newb);
188296465Sdelphij        s->packet = s->s3->rbuf.buf;
189296465Sdelphij    }
19055714Skris
191296465Sdelphij    while (newb < n) {
192296465Sdelphij        /*
193296465Sdelphij         * Now we have off+newb bytes at the front of s->s3->rbuf.buf and
194296465Sdelphij         * need to read in more until we have off+n (up to off+max if
195296465Sdelphij         * possible)
196296465Sdelphij         */
19759191Skris
198296465Sdelphij        clear_sys_error();
199296465Sdelphij        if (s->rbio != NULL) {
200296465Sdelphij            s->rwstate = SSL_READING;
201296465Sdelphij            i = BIO_read(s->rbio, &(s->s3->rbuf.buf[off + newb]), max - newb);
202296465Sdelphij        } else {
203296465Sdelphij            SSLerr(SSL_F_SSL3_READ_N, SSL_R_READ_BIO_NOT_SET);
204296465Sdelphij            i = -1;
205296465Sdelphij        }
20655714Skris
207296465Sdelphij        if (i <= 0) {
208296465Sdelphij            s->s3->rbuf.left = newb;
209296465Sdelphij            return (i);
210296465Sdelphij        }
211296465Sdelphij        newb += i;
212296465Sdelphij        /*
213296465Sdelphij         * reads should *never* span multiple packets for DTLS because the
214296465Sdelphij         * underlying transport protocol is message oriented as opposed to
215296465Sdelphij         * byte oriented as in the TLS case.
216296465Sdelphij         */
217296465Sdelphij        if (SSL_version(s) == DTLS1_VERSION) {
218296465Sdelphij            if (n > newb)
219296465Sdelphij                n = newb;       /* makes the while condition false */
220296465Sdelphij        }
221296465Sdelphij    }
22255714Skris
223296465Sdelphij    /* done reading, now the book-keeping */
224296465Sdelphij    s->s3->rbuf.offset = off + n;
225296465Sdelphij    s->s3->rbuf.left = newb - n;
226296465Sdelphij    s->packet_length += n;
227296465Sdelphij    s->rwstate = SSL_NOTHING;
228296465Sdelphij    return (n);
229296465Sdelphij}
23055714Skris
231296465Sdelphij/*
232296465Sdelphij * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
233296465Sdelphij * will be processed per call to ssl3_get_record. Without this limit an
234296465Sdelphij * attacker could send empty records at a faster rate than we can process and
235296465Sdelphij * cause ssl3_get_record to loop forever.
236296465Sdelphij */
237279265Sdelphij#define MAX_EMPTY_RECORDS 32
238279265Sdelphij
239296465Sdelphij/*-
240296465Sdelphij * Call this to get a new input record.
24155714Skris * It will return <= 0 if more data is needed, normally due to an error
24255714Skris * or non-blocking IO.
24355714Skris * When it finishes, one packet has been decoded and can be found in
24459191Skris * ssl->s3->rrec.type    - is the type of record
245296465Sdelphij * ssl->s3->rrec.data,   - data
24655714Skris * ssl->s3->rrec.length, - number of bytes
24755714Skris */
24859191Skris/* used only by ssl3_read_bytes */
24955714Skrisstatic int ssl3_get_record(SSL *s)
250296465Sdelphij{
251296465Sdelphij    int ssl_major, ssl_minor, al;
252296465Sdelphij    int enc_err, n, i, ret = -1;
253296465Sdelphij    SSL3_RECORD *rr;
254296465Sdelphij    SSL_SESSION *sess;
255296465Sdelphij    unsigned char *p;
256296465Sdelphij    unsigned char md[EVP_MAX_MD_SIZE];
257296465Sdelphij    short version;
258296465Sdelphij    unsigned mac_size, orig_len;
259296465Sdelphij    size_t extra;
260296465Sdelphij    unsigned empty_record_count = 0;
26155714Skris
262296465Sdelphij    rr = &(s->s3->rrec);
263296465Sdelphij    sess = s->session;
26455714Skris
265296465Sdelphij    if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)
266296465Sdelphij        extra = SSL3_RT_MAX_EXTRA;
267296465Sdelphij    else
268296465Sdelphij        extra = 0;
269296465Sdelphij    if (extra != s->s3->rbuf.len - SSL3_RT_MAX_PACKET_SIZE) {
270296465Sdelphij        /*
271296465Sdelphij         * actually likely an application error:
272296465Sdelphij         * SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER set after ssl3_setup_buffers()
273296465Sdelphij         * was done
274296465Sdelphij         */
275296465Sdelphij        SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
276296465Sdelphij        return -1;
277296465Sdelphij    }
27855714Skris
279296465Sdelphij again:
280296465Sdelphij    /* check if we have the header */
281296465Sdelphij    if ((s->rstate != SSL_ST_READ_BODY) ||
282296465Sdelphij        (s->packet_length < SSL3_RT_HEADER_LENGTH)) {
283296465Sdelphij        n = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
284296465Sdelphij        if (n <= 0)
285296465Sdelphij            return (n);         /* error or non-blocking */
286296465Sdelphij        s->rstate = SSL_ST_READ_BODY;
28755714Skris
288296465Sdelphij        p = s->packet;
28955714Skris
290296465Sdelphij        /* Pull apart the header into the SSL3_RECORD */
291296465Sdelphij        rr->type = *(p++);
292296465Sdelphij        ssl_major = *(p++);
293296465Sdelphij        ssl_minor = *(p++);
294296465Sdelphij        version = (ssl_major << 8) | ssl_minor;
295296465Sdelphij        n2s(p, rr->length);
29655714Skris
297296465Sdelphij        /* Lets check version */
298296465Sdelphij        if (!s->first_packet) {
299296465Sdelphij            if (version != s->version) {
300296465Sdelphij                SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
301296465Sdelphij                if ((s->version & 0xFF00) == (version & 0xFF00))
302296465Sdelphij                    /*
303296465Sdelphij                     * Send back error using their minor version number :-)
304296465Sdelphij                     */
305296465Sdelphij                    s->version = (unsigned short)version;
306296465Sdelphij                al = SSL_AD_PROTOCOL_VERSION;
307296465Sdelphij                goto f_err;
308296465Sdelphij            }
309296465Sdelphij        }
31055714Skris
311296465Sdelphij        if ((version >> 8) != SSL3_VERSION_MAJOR) {
312296465Sdelphij            SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
313296465Sdelphij            goto err;
314296465Sdelphij        }
31555714Skris
316296465Sdelphij        if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH + extra) {
317296465Sdelphij            al = SSL_AD_RECORD_OVERFLOW;
318296465Sdelphij            SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
319296465Sdelphij            goto f_err;
320296465Sdelphij        }
32155714Skris
322296465Sdelphij        /* now s->rstate == SSL_ST_READ_BODY */
323296465Sdelphij    }
32455714Skris
325296465Sdelphij    /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
32659191Skris
327296465Sdelphij    if (rr->length > s->packet_length - SSL3_RT_HEADER_LENGTH) {
328296465Sdelphij        /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
329296465Sdelphij        i = rr->length;
330296465Sdelphij        n = ssl3_read_n(s, i, i, 1);
331296465Sdelphij        if (n <= 0)
332296465Sdelphij            return (n);         /* error or non-blocking io */
333296465Sdelphij        /*
334296465Sdelphij         * now n == rr->length, and s->packet_length == SSL3_RT_HEADER_LENGTH
335296465Sdelphij         * + rr->length
336296465Sdelphij         */
337296465Sdelphij    }
33855714Skris
339296465Sdelphij    s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
34055714Skris
341296465Sdelphij    /*
342296465Sdelphij     * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
343296465Sdelphij     * and we have that many bytes in s->packet
344296465Sdelphij     */
345296465Sdelphij    rr->input = &(s->packet[SSL3_RT_HEADER_LENGTH]);
34655714Skris
347296465Sdelphij    /*
348296465Sdelphij     * ok, we can now read from 's->packet' data into 'rr' rr->input points
349296465Sdelphij     * at rr->length bytes, which need to be copied into rr->data by either
350296465Sdelphij     * the decryption or by the decompression When the data is 'copied' into
351296465Sdelphij     * the rr->data buffer, rr->input will be pointed at the new buffer
352296465Sdelphij     */
35355714Skris
354296465Sdelphij    /*
355296465Sdelphij     * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
356296465Sdelphij     * bytes of encrypted compressed stuff.
357296465Sdelphij     */
35855714Skris
359296465Sdelphij    /* check is not needed I believe */
360296465Sdelphij    if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH + extra) {
361296465Sdelphij        al = SSL_AD_RECORD_OVERFLOW;
362296465Sdelphij        SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
363296465Sdelphij        goto f_err;
364296465Sdelphij    }
36555714Skris
366296465Sdelphij    /* decrypt in place in 'rr->input' */
367296465Sdelphij    rr->data = rr->input;
36855714Skris
369296465Sdelphij    enc_err = s->method->ssl3_enc->enc(s, 0);
370296465Sdelphij    /*-
371296465Sdelphij     * enc_err is:
372296465Sdelphij     *    0: (in non-constant time) if the record is publically invalid.
373296465Sdelphij     *    1: if the padding is valid
374296465Sdelphij     *    -1: if the padding is invalid
375296465Sdelphij     */
376296465Sdelphij    if (enc_err == 0) {
377296465Sdelphij        al = SSL_AD_DECRYPTION_FAILED;
378296465Sdelphij        SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
379296465Sdelphij        goto f_err;
380296465Sdelphij    }
38155714Skris#ifdef TLS_DEBUG
382296465Sdelphij    printf("dec %d\n", rr->length);
383296465Sdelphij    {
384296465Sdelphij        unsigned int z;
385296465Sdelphij        for (z = 0; z < rr->length; z++)
386296465Sdelphij            printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
387296465Sdelphij    }
388296465Sdelphij    printf("\n");
38955714Skris#endif
39089837Skris
391296465Sdelphij    /* r->length is now the compressed data plus mac */
392296465Sdelphij    if ((sess != NULL) && (s->enc_read_ctx != NULL) && (s->read_hash != NULL)) {
393296465Sdelphij        /* s->read_hash != NULL => mac_size != -1 */
394296465Sdelphij        unsigned char *mac = NULL;
395296465Sdelphij        unsigned char mac_tmp[EVP_MAX_MD_SIZE];
396296465Sdelphij        mac_size = EVP_MD_size(s->read_hash);
397296465Sdelphij        OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
39855714Skris
399296465Sdelphij        /*
400296465Sdelphij         * kludge: *_cbc_remove_padding passes padding length in rr->type
401296465Sdelphij         */
402296465Sdelphij        orig_len = rr->length + ((unsigned int)rr->type >> 8);
403267285Sjkim
404296465Sdelphij        /*
405296465Sdelphij         * orig_len is the length of the record before any padding was
406296465Sdelphij         * removed. This is public information, as is the MAC in use,
407296465Sdelphij         * therefore we can safely process the record in a different amount
408296465Sdelphij         * of time if it's too short to possibly contain a MAC.
409296465Sdelphij         */
410296465Sdelphij        if (orig_len < mac_size ||
411296465Sdelphij            /* CBC records must have a padding length byte too. */
412296465Sdelphij            (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
413296465Sdelphij             orig_len < mac_size + 1)) {
414296465Sdelphij            al = SSL_AD_DECODE_ERROR;
415296465Sdelphij            SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
416296465Sdelphij            goto f_err;
417296465Sdelphij        }
418248272Sdelphij
419296465Sdelphij        if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
420296465Sdelphij            /*
421296465Sdelphij             * We update the length so that the TLS header bytes can be
422296465Sdelphij             * constructed correctly but we need to extract the MAC in
423296465Sdelphij             * constant time from within the record, without leaking the
424296465Sdelphij             * contents of the padding bytes.
425296465Sdelphij             */
426296465Sdelphij            mac = mac_tmp;
427296465Sdelphij            ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len);
428296465Sdelphij            rr->length -= mac_size;
429296465Sdelphij        } else {
430296465Sdelphij            /*
431296465Sdelphij             * In this case there's no padding, so |orig_len| equals
432296465Sdelphij             * |rec->length| and we checked that there's enough bytes for
433296465Sdelphij             * |mac_size| above.
434296465Sdelphij             */
435296465Sdelphij            rr->length -= mac_size;
436296465Sdelphij            mac = &rr->data[rr->length];
437296465Sdelphij        }
438248272Sdelphij
439296465Sdelphij        i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
440296465Sdelphij        if (i < 0 || mac == NULL
441296465Sdelphij            || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
442296465Sdelphij            enc_err = -1;
443296465Sdelphij        if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + extra + mac_size)
444296465Sdelphij            enc_err = -1;
445296465Sdelphij    }
44655714Skris
447296465Sdelphij    if (enc_err < 0) {
448296465Sdelphij        /*
449296465Sdelphij         * A separate 'decryption_failed' alert was introduced with TLS 1.0,
450296465Sdelphij         * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
451296465Sdelphij         * failure is directly visible from the ciphertext anyway, we should
452296465Sdelphij         * not reveal which kind of error occured -- this might become
453296465Sdelphij         * visible to an attacker (e.g. via a logfile)
454296465Sdelphij         */
455296465Sdelphij        al = SSL_AD_BAD_RECORD_MAC;
456296465Sdelphij        SSLerr(SSL_F_SSL3_GET_RECORD,
457296465Sdelphij               SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
458296465Sdelphij        goto f_err;
459296465Sdelphij    }
460111147Snectar
461296465Sdelphij    /* r->length is now just compressed */
462296465Sdelphij    if (s->expand != NULL) {
463296465Sdelphij        if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + extra) {
464296465Sdelphij            al = SSL_AD_RECORD_OVERFLOW;
465296465Sdelphij            SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
466296465Sdelphij            goto f_err;
467296465Sdelphij        }
468296465Sdelphij        if (!ssl3_do_uncompress(s)) {
469296465Sdelphij            al = SSL_AD_DECOMPRESSION_FAILURE;
470296465Sdelphij            SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
471296465Sdelphij            goto f_err;
472296465Sdelphij        }
473296465Sdelphij    }
47455714Skris
475296465Sdelphij    if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH + extra) {
476296465Sdelphij        al = SSL_AD_RECORD_OVERFLOW;
477296465Sdelphij        SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
478296465Sdelphij        goto f_err;
479296465Sdelphij    }
48055714Skris
481296465Sdelphij    rr->off = 0;
482296465Sdelphij    /*-
483296465Sdelphij     * So at this point the following is true
484296465Sdelphij     * ssl->s3->rrec.type   is the type of record
485296465Sdelphij     * ssl->s3->rrec.length == number of bytes in record
486296465Sdelphij     * ssl->s3->rrec.off    == offset to first valid byte
487296465Sdelphij     * ssl->s3->rrec.data   == where to take bytes from, increment
488296465Sdelphij     *                         after use :-).
489296465Sdelphij     */
49055714Skris
491296465Sdelphij    /* we have pulled in a full packet so zero things */
492296465Sdelphij    s->packet_length = 0;
49355714Skris
494296465Sdelphij    /* just read a 0 length packet */
495296465Sdelphij    if (rr->length == 0) {
496296465Sdelphij        empty_record_count++;
497296465Sdelphij        if (empty_record_count > MAX_EMPTY_RECORDS) {
498296465Sdelphij            al = SSL_AD_UNEXPECTED_MESSAGE;
499296465Sdelphij            SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
500296465Sdelphij            goto f_err;
501296465Sdelphij        }
502296465Sdelphij        goto again;
503296465Sdelphij    }
50455714Skris
505296465Sdelphij    return (1);
50689837Skris
507296465Sdelphij f_err:
508296465Sdelphij    ssl3_send_alert(s, SSL3_AL_FATAL, al);
509296465Sdelphij err:
510296465Sdelphij    return (ret);
511296465Sdelphij}
51255714Skris
513160814Ssimonint ssl3_do_uncompress(SSL *ssl)
514296465Sdelphij{
515160814Ssimon#ifndef OPENSSL_NO_COMP
516296465Sdelphij    int i;
517296465Sdelphij    SSL3_RECORD *rr;
51855714Skris
519296465Sdelphij    rr = &(ssl->s3->rrec);
520296465Sdelphij    i = COMP_expand_block(ssl->expand, rr->comp,
521296465Sdelphij                          SSL3_RT_MAX_PLAIN_LENGTH, rr->data,
522296465Sdelphij                          (int)rr->length);
523296465Sdelphij    if (i < 0)
524296465Sdelphij        return (0);
525296465Sdelphij    else
526296465Sdelphij        rr->length = i;
527296465Sdelphij    rr->data = rr->comp;
528160814Ssimon#endif
529296465Sdelphij    return (1);
530296465Sdelphij}
53155714Skris
532160814Ssimonint ssl3_do_compress(SSL *ssl)
533296465Sdelphij{
534160814Ssimon#ifndef OPENSSL_NO_COMP
535296465Sdelphij    int i;
536296465Sdelphij    SSL3_RECORD *wr;
53755714Skris
538296465Sdelphij    wr = &(ssl->s3->wrec);
539296465Sdelphij    i = COMP_compress_block(ssl->compress, wr->data,
540296465Sdelphij                            SSL3_RT_MAX_COMPRESSED_LENGTH,
541296465Sdelphij                            wr->input, (int)wr->length);
542296465Sdelphij    if (i < 0)
543296465Sdelphij        return (0);
544296465Sdelphij    else
545296465Sdelphij        wr->length = i;
54655714Skris
547296465Sdelphij    wr->input = wr->data;
548160814Ssimon#endif
549296465Sdelphij    return (1);
550296465Sdelphij}
55155714Skris
552296465Sdelphij/*
553296465Sdelphij * Call this to write data in records of type 'type' It will return <= 0 if
554296465Sdelphij * not all data has been sent or non-blocking IO.
55555714Skris */
55659191Skrisint ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
557296465Sdelphij{
558296465Sdelphij    const unsigned char *buf = buf_;
559296465Sdelphij    unsigned int n, nw;
560296465Sdelphij    int i, tot;
56155714Skris
562296465Sdelphij    s->rwstate = SSL_NOTHING;
563296465Sdelphij    OPENSSL_assert(s->s3->wnum <= INT_MAX);
564296465Sdelphij    tot = s->s3->wnum;
565296465Sdelphij    s->s3->wnum = 0;
56655714Skris
567296465Sdelphij    if (SSL_in_init(s) && !s->in_handshake) {
568296465Sdelphij        i = s->handshake_func(s);
569296465Sdelphij        if (i < 0)
570296465Sdelphij            return (i);
571296465Sdelphij        if (i == 0) {
572296465Sdelphij            SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
573296465Sdelphij            return -1;
574296465Sdelphij        }
575296465Sdelphij    }
57655714Skris
577296465Sdelphij    /*
578296465Sdelphij     * ensure that if we end up with a smaller value of data to write out
579296465Sdelphij     * than the the original len from a write which didn't complete for
580296465Sdelphij     * non-blocking I/O and also somehow ended up avoiding the check for
581296465Sdelphij     * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
582296465Sdelphij     * possible to end up with (len-tot) as a large number that will then
583296465Sdelphij     * promptly send beyond the end of the users buffer ... so we trap and
584296465Sdelphij     * report the error in a way the user will notice
585296465Sdelphij     */
586296465Sdelphij    if (len < tot) {
587296465Sdelphij        SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_BAD_LENGTH);
588296465Sdelphij        return (-1);
589296465Sdelphij    }
590267285Sjkim
591296465Sdelphij    n = (len - tot);
592296465Sdelphij    for (;;) {
593296465Sdelphij        if (n > SSL3_RT_MAX_PLAIN_LENGTH)
594296465Sdelphij            nw = SSL3_RT_MAX_PLAIN_LENGTH;
595296465Sdelphij        else
596296465Sdelphij            nw = n;
597267285Sjkim
598296465Sdelphij        i = do_ssl3_write(s, type, &(buf[tot]), nw, 0);
599296465Sdelphij        if (i <= 0) {
600296465Sdelphij            s->s3->wnum = tot;
601296465Sdelphij            return i;
602296465Sdelphij        }
60359191Skris
604296465Sdelphij        if ((i == (int)n) ||
605296465Sdelphij            (type == SSL3_RT_APPLICATION_DATA &&
606296465Sdelphij             (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
607296465Sdelphij            /*
608296465Sdelphij             * next chunk of data should get another prepended empty fragment
609296465Sdelphij             * in ciphersuites with known-IV weakness:
610296465Sdelphij             */
611296465Sdelphij            s->s3->empty_fragment_done = 0;
61255714Skris
613296465Sdelphij            return tot + i;
614296465Sdelphij        }
61555714Skris
616296465Sdelphij        n -= i;
617296465Sdelphij        tot += i;
618296465Sdelphij    }
619296465Sdelphij}
62055714Skris
62155714Skrisstatic int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
622296465Sdelphij                         unsigned int len, int create_empty_fragment)
623296465Sdelphij{
624296465Sdelphij    unsigned char *p, *plen;
625296465Sdelphij    int i, mac_size, clear = 0;
626296465Sdelphij    int prefix_len = 0;
627296465Sdelphij    SSL3_RECORD *wr;
628296465Sdelphij    SSL3_BUFFER *wb;
629296465Sdelphij    SSL_SESSION *sess;
63055714Skris
631296465Sdelphij    /*
632296465Sdelphij     * first check if there is a SSL3_BUFFER still being written out.  This
633296465Sdelphij     * will happen with non blocking IO
634296465Sdelphij     */
635296465Sdelphij    if (s->s3->wbuf.left != 0)
636296465Sdelphij        return (ssl3_write_pending(s, type, buf, len));
63755714Skris
638296465Sdelphij    /* If we have an alert to send, lets send it */
639296465Sdelphij    if (s->s3->alert_dispatch) {
640296465Sdelphij        i = s->method->ssl_dispatch_alert(s);
641296465Sdelphij        if (i <= 0)
642296465Sdelphij            return (i);
643296465Sdelphij        /* if it went, fall through and send more stuff */
644296465Sdelphij    }
64555714Skris
646296465Sdelphij    if (len == 0 && !create_empty_fragment)
647296465Sdelphij        return 0;
64859191Skris
649296465Sdelphij    wr = &(s->s3->wrec);
650296465Sdelphij    wb = &(s->s3->wbuf);
651296465Sdelphij    sess = s->session;
65255714Skris
653296465Sdelphij    if ((sess == NULL) ||
654296465Sdelphij        (s->enc_write_ctx == NULL) || (s->write_hash == NULL))
655296465Sdelphij        clear = 1;
65655714Skris
657296465Sdelphij    if (clear)
658296465Sdelphij        mac_size = 0;
659296465Sdelphij    else
660296465Sdelphij        mac_size = EVP_MD_size(s->write_hash);
66155714Skris
662296465Sdelphij    /*
663296465Sdelphij     * 'create_empty_fragment' is true only when this function calls itself
664296465Sdelphij     */
665296465Sdelphij    if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done) {
666296465Sdelphij        /*
667296465Sdelphij         * countermeasure against known-IV weakness in CBC ciphersuites (see
668296465Sdelphij         * http://www.openssl.org/~bodo/tls-cbc.txt)
669296465Sdelphij         */
67055714Skris
671296465Sdelphij        if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
672296465Sdelphij            /*
673296465Sdelphij             * recursive function call with 'create_empty_fragment' set; this
674296465Sdelphij             * prepares and buffers the data for an empty fragment (these
675296465Sdelphij             * 'prefix_len' bytes are sent out later together with the actual
676296465Sdelphij             * payload)
677296465Sdelphij             */
678296465Sdelphij            prefix_len = do_ssl3_write(s, type, buf, 0, 1);
679296465Sdelphij            if (prefix_len <= 0)
680296465Sdelphij                goto err;
681100928Snectar
682296465Sdelphij            if (s->s3->wbuf.len <
683296465Sdelphij                (size_t)prefix_len + SSL3_RT_MAX_PACKET_SIZE) {
684296465Sdelphij                /* insufficient space */
685296465Sdelphij                SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
686296465Sdelphij                goto err;
687296465Sdelphij            }
688296465Sdelphij        }
689100928Snectar
690296465Sdelphij        s->s3->empty_fragment_done = 1;
691296465Sdelphij    }
692100928Snectar
693296465Sdelphij    p = wb->buf + prefix_len;
694100928Snectar
695296465Sdelphij    /* write the header */
69655714Skris
697296465Sdelphij    *(p++) = type & 0xff;
698296465Sdelphij    wr->type = type;
69959191Skris
700296465Sdelphij    *(p++) = (s->version >> 8);
701296465Sdelphij    *(p++) = s->version & 0xff;
70259191Skris
703296465Sdelphij    /* field where we are to write out packet length */
704296465Sdelphij    plen = p;
705296465Sdelphij    p += 2;
70655714Skris
707296465Sdelphij    /* lets setup the record stuff. */
708296465Sdelphij    wr->data = p;
709296465Sdelphij    wr->length = (int)len;
710296465Sdelphij    wr->input = (unsigned char *)buf;
71155714Skris
712296465Sdelphij    /*
713296465Sdelphij     * we now 'read' from wr->input, wr->length bytes into wr->data
714296465Sdelphij     */
71555714Skris
716296465Sdelphij    /* first we compress */
717296465Sdelphij    if (s->compress != NULL) {
718296465Sdelphij        if (!ssl3_do_compress(s)) {
719296465Sdelphij            SSLerr(SSL_F_DO_SSL3_WRITE, SSL_R_COMPRESSION_FAILURE);
720296465Sdelphij            goto err;
721296465Sdelphij        }
722296465Sdelphij    } else {
723296465Sdelphij        memcpy(wr->data, wr->input, wr->length);
724296465Sdelphij        wr->input = wr->data;
725296465Sdelphij    }
72655714Skris
727296465Sdelphij    /*
728296465Sdelphij     * we should still have the output to wr->data and the input from
729296465Sdelphij     * wr->input.  Length should be wr->length. wr->data still points in the
730296465Sdelphij     * wb->buf
731296465Sdelphij     */
73255714Skris
733296465Sdelphij    if (mac_size != 0) {
734296465Sdelphij        s->method->ssl3_enc->mac(s, &(p[wr->length]), 1);
735296465Sdelphij        wr->length += mac_size;
736296465Sdelphij        wr->input = p;
737296465Sdelphij        wr->data = p;
738296465Sdelphij    }
73955714Skris
740296465Sdelphij    /* ssl3_enc can only have an error on read */
741296465Sdelphij    s->method->ssl3_enc->enc(s, 1);
74255714Skris
743296465Sdelphij    /* record length after mac and block padding */
744296465Sdelphij    s2n(wr->length, plen);
74555714Skris
746296465Sdelphij    /*
747296465Sdelphij     * we should now have wr->data pointing to the encrypted data, which is
748296465Sdelphij     * wr->length long
749296465Sdelphij     */
750296465Sdelphij    wr->type = type;            /* not needed but helps for debugging */
751296465Sdelphij    wr->length += SSL3_RT_HEADER_LENGTH;
75255714Skris
753296465Sdelphij    if (create_empty_fragment) {
754296465Sdelphij        /*
755296465Sdelphij         * we are in a recursive call; just return the length, don't write
756296465Sdelphij         * out anything here
757296465Sdelphij         */
758296465Sdelphij        return wr->length;
759296465Sdelphij    }
760100928Snectar
761296465Sdelphij    /* now let's set up wb */
762296465Sdelphij    wb->left = prefix_len + wr->length;
763296465Sdelphij    wb->offset = 0;
76455714Skris
765296465Sdelphij    /*
766296465Sdelphij     * memorize arguments so that ssl3_write_pending can detect bad write
767296465Sdelphij     * retries later
768296465Sdelphij     */
769296465Sdelphij    s->s3->wpend_tot = len;
770296465Sdelphij    s->s3->wpend_buf = buf;
771296465Sdelphij    s->s3->wpend_type = type;
772296465Sdelphij    s->s3->wpend_ret = len;
77355714Skris
774296465Sdelphij    /* we now just need to write the buffer */
775296465Sdelphij    return ssl3_write_pending(s, type, buf, len);
776296465Sdelphij err:
777296465Sdelphij    return -1;
778296465Sdelphij}
779296465Sdelphij
78055714Skris/* if s->s3->wbuf.left != 0, we need to call this */
781160814Ssimonint ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
782296465Sdelphij                       unsigned int len)
783296465Sdelphij{
784296465Sdelphij    int i;
78555714Skris
78655714Skris/* XXXX */
787296465Sdelphij    if ((s->s3->wpend_tot > (int)len)
788296465Sdelphij        || ((s->s3->wpend_buf != buf) &&
789296465Sdelphij            !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
790296465Sdelphij        || (s->s3->wpend_type != type)) {
791296465Sdelphij        SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BAD_WRITE_RETRY);
792296465Sdelphij        return (-1);
793296465Sdelphij    }
79455714Skris
795296465Sdelphij    for (;;) {
796296465Sdelphij        clear_sys_error();
797296465Sdelphij        if (s->wbio != NULL) {
798296465Sdelphij            s->rwstate = SSL_WRITING;
799296465Sdelphij            i = BIO_write(s->wbio,
800296465Sdelphij                          (char *)&(s->s3->wbuf.buf[s->s3->wbuf.offset]),
801296465Sdelphij                          (unsigned int)s->s3->wbuf.left);
802296465Sdelphij        } else {
803296465Sdelphij            SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BIO_NOT_SET);
804296465Sdelphij            i = -1;
805296465Sdelphij        }
806296465Sdelphij        if (i == s->s3->wbuf.left) {
807296465Sdelphij            s->s3->wbuf.left = 0;
808296465Sdelphij            s->rwstate = SSL_NOTHING;
809296465Sdelphij            return (s->s3->wpend_ret);
810296465Sdelphij        } else if (i <= 0) {
811296465Sdelphij            if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER) {
812296465Sdelphij                /*
813296465Sdelphij                 * For DTLS, just drop it. That's kind of the whole point in
814296465Sdelphij                 * using a datagram service
815296465Sdelphij                 */
816296465Sdelphij                s->s3->wbuf.left = 0;
817296465Sdelphij            }
818296465Sdelphij            return (i);
819296465Sdelphij        }
820296465Sdelphij        s->s3->wbuf.offset += i;
821296465Sdelphij        s->s3->wbuf.left -= i;
822296465Sdelphij    }
823296465Sdelphij}
82455714Skris
825296465Sdelphij/*-
826296465Sdelphij * Return up to 'len' payload bytes received in 'type' records.
82759191Skris * 'type' is one of the following:
82859191Skris *
82959191Skris *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
83059191Skris *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
83159191Skris *   -  0 (during a shutdown, no data has to be returned)
83259191Skris *
83359191Skris * If we don't have stored data to work from, read a SSL/TLS record first
83459191Skris * (possibly multiple records if we still don't have anything to return).
83559191Skris *
83659191Skris * This function must handle any surprises the peer may have for us, such as
83759191Skris * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
83859191Skris * a surprise, but handled as if it were), or renegotiation requests.
83959191Skris * Also if record payloads contain fragments too small to process, we store
84059191Skris * them until there is enough for the respective protocol (the record protocol
84159191Skris * may use arbitrary fragmentation and even interleaving):
84259191Skris *     Change cipher spec protocol
84359191Skris *             just 1 byte needed, no need for keeping anything stored
84459191Skris *     Alert protocol
84559191Skris *             2 bytes needed (AlertLevel, AlertDescription)
84659191Skris *     Handshake protocol
84759191Skris *             4 bytes needed (HandshakeType, uint24 length) -- we just have
84859191Skris *             to detect unexpected Client Hello and Hello Request messages
84959191Skris *             here, anything else is handled by higher layers
85059191Skris *     Application data protocol
85159191Skris *             none of our business
85259191Skris */
85372613Skrisint ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
854296465Sdelphij{
855296465Sdelphij    int al, i, j, ret;
856296465Sdelphij    unsigned int n;
857296465Sdelphij    SSL3_RECORD *rr;
858296465Sdelphij    void (*cb) (const SSL *ssl, int type2, int val) = NULL;
85955714Skris
860296465Sdelphij    if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
861296465Sdelphij        if (!ssl3_setup_buffers(s))
862296465Sdelphij            return (-1);
86355714Skris
864296465Sdelphij    if ((type && (type != SSL3_RT_APPLICATION_DATA)
865296465Sdelphij         && (type != SSL3_RT_HANDSHAKE)) || (peek
866296465Sdelphij                                             && (type !=
867296465Sdelphij                                                 SSL3_RT_APPLICATION_DATA))) {
868296465Sdelphij        SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
869296465Sdelphij        return -1;
870296465Sdelphij    }
87159191Skris
872296465Sdelphij    if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0))
873296465Sdelphij        /* (partially) satisfy request from storage */
874296465Sdelphij    {
875296465Sdelphij        unsigned char *src = s->s3->handshake_fragment;
876296465Sdelphij        unsigned char *dst = buf;
877296465Sdelphij        unsigned int k;
87859191Skris
879296465Sdelphij        /* peek == 0 */
880296465Sdelphij        n = 0;
881296465Sdelphij        while ((len > 0) && (s->s3->handshake_fragment_len > 0)) {
882296465Sdelphij            *dst++ = *src++;
883296465Sdelphij            len--;
884296465Sdelphij            s->s3->handshake_fragment_len--;
885296465Sdelphij            n++;
886296465Sdelphij        }
887296465Sdelphij        /* move any remaining fragment bytes: */
888296465Sdelphij        for (k = 0; k < s->s3->handshake_fragment_len; k++)
889296465Sdelphij            s->s3->handshake_fragment[k] = *src++;
890296465Sdelphij        return n;
891296465Sdelphij    }
89259191Skris
893296465Sdelphij    /*
894296465Sdelphij     * Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
895296465Sdelphij     */
89659191Skris
897296465Sdelphij    if (!s->in_handshake && SSL_in_init(s)) {
898296465Sdelphij        /* type == SSL3_RT_APPLICATION_DATA */
899296465Sdelphij        i = s->handshake_func(s);
900296465Sdelphij        if (i < 0)
901296465Sdelphij            return (i);
902296465Sdelphij        if (i == 0) {
903296465Sdelphij            SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
904296465Sdelphij            return (-1);
905296465Sdelphij        }
906296465Sdelphij    }
907296465Sdelphij start:
908296465Sdelphij    s->rwstate = SSL_NOTHING;
90955714Skris
910296465Sdelphij    /*-
911296465Sdelphij     * s->s3->rrec.type         - is the type of record
912296465Sdelphij     * s->s3->rrec.data,    - data
913296465Sdelphij     * s->s3->rrec.off,     - offset into 'data' for next read
914296465Sdelphij     * s->s3->rrec.length,  - number of bytes.
915296465Sdelphij     */
916296465Sdelphij    rr = &(s->s3->rrec);
91755714Skris
918296465Sdelphij    /* get new packet if necessary */
919296465Sdelphij    if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) {
920296465Sdelphij        ret = ssl3_get_record(s);
921296465Sdelphij        if (ret <= 0)
922296465Sdelphij            return (ret);
923296465Sdelphij    }
92455714Skris
925308205Sdelphij    /*
926308205Sdelphij     * Reset the count of consecutive warning alerts if we've got a non-empty
927308205Sdelphij     * record that isn't an alert.
928308205Sdelphij     */
929308205Sdelphij    if (rr->type != SSL3_RT_ALERT && rr->length != 0)
930308205Sdelphij        s->s3->alert_count = 0;
931308205Sdelphij
932296465Sdelphij    /* we now have a packet which can be read and processed */
93355714Skris
934296465Sdelphij    if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
935296465Sdelphij                                   * reset by ssl3_get_finished */
936296465Sdelphij        && (rr->type != SSL3_RT_HANDSHAKE)) {
937296465Sdelphij        al = SSL_AD_UNEXPECTED_MESSAGE;
938296465Sdelphij        SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
939296465Sdelphij        goto f_err;
940296465Sdelphij    }
94155714Skris
942296465Sdelphij    /*
943296465Sdelphij     * If the other end has shut down, throw anything we read away (even in
944296465Sdelphij     * 'peek' mode)
945296465Sdelphij     */
946296465Sdelphij    if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
947296465Sdelphij        rr->length = 0;
948296465Sdelphij        s->rwstate = SSL_NOTHING;
949296465Sdelphij        return (0);
950296465Sdelphij    }
95155714Skris
952296465Sdelphij    if (type == rr->type) {     /* SSL3_RT_APPLICATION_DATA or
953296465Sdelphij                                 * SSL3_RT_HANDSHAKE */
954296465Sdelphij        /*
955296465Sdelphij         * make sure that we are not getting application data when we are
956296465Sdelphij         * doing a handshake for the first time
957296465Sdelphij         */
958296465Sdelphij        if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
959296465Sdelphij            (s->enc_read_ctx == NULL)) {
960296465Sdelphij            al = SSL_AD_UNEXPECTED_MESSAGE;
961296465Sdelphij            SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
962296465Sdelphij            goto f_err;
963296465Sdelphij        }
96459191Skris
965296465Sdelphij        if (len <= 0)
966296465Sdelphij            return (len);
96759191Skris
968296465Sdelphij        if ((unsigned int)len > rr->length)
969296465Sdelphij            n = rr->length;
970296465Sdelphij        else
971296465Sdelphij            n = (unsigned int)len;
97259191Skris
973296465Sdelphij        memcpy(buf, &(rr->data[rr->off]), n);
974296465Sdelphij        if (!peek) {
975296465Sdelphij            rr->length -= n;
976296465Sdelphij            rr->off += n;
977296465Sdelphij            if (rr->length == 0) {
978296465Sdelphij                s->rstate = SSL_ST_READ_HEADER;
979296465Sdelphij                rr->off = 0;
980296465Sdelphij            }
981296465Sdelphij        }
982296465Sdelphij        return (n);
983296465Sdelphij    }
98459191Skris
985296465Sdelphij    /*
986296465Sdelphij     * If we get here, then type != rr->type; if we have a handshake message,
987296465Sdelphij     * then it was unexpected (Hello Request or Client Hello).
988296465Sdelphij     */
98959191Skris
990296465Sdelphij    /*
991296465Sdelphij     * In case of record types for which we have 'fragment' storage, fill
992296465Sdelphij     * that so that we can process the data at a fixed place.
993296465Sdelphij     */
994296465Sdelphij    {
995296465Sdelphij        unsigned int dest_maxlen = 0;
996296465Sdelphij        unsigned char *dest = NULL;
997296465Sdelphij        unsigned int *dest_len = NULL;
99859191Skris
999296465Sdelphij        if (rr->type == SSL3_RT_HANDSHAKE) {
1000296465Sdelphij            dest_maxlen = sizeof s->s3->handshake_fragment;
1001296465Sdelphij            dest = s->s3->handshake_fragment;
1002296465Sdelphij            dest_len = &s->s3->handshake_fragment_len;
1003296465Sdelphij        } else if (rr->type == SSL3_RT_ALERT) {
1004296465Sdelphij            dest_maxlen = sizeof s->s3->alert_fragment;
1005296465Sdelphij            dest = s->s3->alert_fragment;
1006296465Sdelphij            dest_len = &s->s3->alert_fragment_len;
1007296465Sdelphij        }
100859191Skris
1009296465Sdelphij        if (dest_maxlen > 0) {
1010296465Sdelphij            n = dest_maxlen - *dest_len; /* available space in 'dest' */
1011296465Sdelphij            if (rr->length < n)
1012296465Sdelphij                n = rr->length; /* available bytes */
101359191Skris
1014296465Sdelphij            /* now move 'n' bytes: */
1015296465Sdelphij            while (n-- > 0) {
1016296465Sdelphij                dest[(*dest_len)++] = rr->data[rr->off++];
1017296465Sdelphij                rr->length--;
1018296465Sdelphij            }
101959191Skris
1020296465Sdelphij            if (*dest_len < dest_maxlen)
1021296465Sdelphij                goto start;     /* fragment was too small */
1022296465Sdelphij        }
1023296465Sdelphij    }
102459191Skris
1025296465Sdelphij    /*-
1026296465Sdelphij     * s->s3->handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
1027296465Sdelphij     * s->s3->alert_fragment_len == 2      iff  rr->type == SSL3_RT_ALERT.
1028296465Sdelphij     * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1029296465Sdelphij     */
103059191Skris
1031296465Sdelphij    /* If we are a client, check for an incoming 'Hello Request': */
1032296465Sdelphij    if ((!s->server) &&
1033296465Sdelphij        (s->s3->handshake_fragment_len >= 4) &&
1034296465Sdelphij        (s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
1035296465Sdelphij        (s->session != NULL) && (s->session->cipher != NULL)) {
1036296465Sdelphij        s->s3->handshake_fragment_len = 0;
103759191Skris
1038296465Sdelphij        if ((s->s3->handshake_fragment[1] != 0) ||
1039296465Sdelphij            (s->s3->handshake_fragment[2] != 0) ||
1040296465Sdelphij            (s->s3->handshake_fragment[3] != 0)) {
1041296465Sdelphij            al = SSL_AD_DECODE_ERROR;
1042296465Sdelphij            SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
1043296465Sdelphij            goto f_err;
1044296465Sdelphij        }
104559191Skris
1046296465Sdelphij        if (s->msg_callback)
1047296465Sdelphij            s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1048296465Sdelphij                            s->s3->handshake_fragment, 4, s,
1049296465Sdelphij                            s->msg_callback_arg);
105059191Skris
1051296465Sdelphij        if (SSL_is_init_finished(s) &&
1052296465Sdelphij            !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
1053296465Sdelphij            !s->s3->renegotiate) {
1054296465Sdelphij            ssl3_renegotiate(s);
1055296465Sdelphij            if (ssl3_renegotiate_check(s)) {
1056296465Sdelphij                i = s->handshake_func(s);
1057296465Sdelphij                if (i < 0)
1058296465Sdelphij                    return (i);
1059296465Sdelphij                if (i == 0) {
1060296465Sdelphij                    SSLerr(SSL_F_SSL3_READ_BYTES,
1061296465Sdelphij                           SSL_R_SSL_HANDSHAKE_FAILURE);
1062296465Sdelphij                    return (-1);
1063296465Sdelphij                }
106455714Skris
1065296465Sdelphij                if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1066296465Sdelphij                    if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
1067296465Sdelphij                        BIO *bio;
1068296465Sdelphij                        /*
1069296465Sdelphij                         * In the case where we try to read application data,
1070296465Sdelphij                         * but we trigger an SSL handshake, we return -1 with
1071296465Sdelphij                         * the retry option set.  Otherwise renegotiation may
1072296465Sdelphij                         * cause nasty problems in the blocking world
1073296465Sdelphij                         */
1074296465Sdelphij                        s->rwstate = SSL_READING;
1075296465Sdelphij                        bio = SSL_get_rbio(s);
1076296465Sdelphij                        BIO_clear_retry_flags(bio);
1077296465Sdelphij                        BIO_set_retry_read(bio);
1078296465Sdelphij                        return (-1);
1079296465Sdelphij                    }
1080296465Sdelphij                }
1081296465Sdelphij            }
1082296465Sdelphij        }
1083296465Sdelphij        /*
1084296465Sdelphij         * we either finished a handshake or ignored the request, now try
1085296465Sdelphij         * again to obtain the (application) data we were asked for
1086296465Sdelphij         */
1087296465Sdelphij        goto start;
1088296465Sdelphij    }
1089296465Sdelphij    /*
1090296465Sdelphij     * If we are a server and get a client hello when renegotiation isn't
1091296465Sdelphij     * allowed send back a no renegotiation alert and carry on. WARNING:
1092296465Sdelphij     * experimental code, needs reviewing (steve)
1093296465Sdelphij     */
1094296465Sdelphij    if (s->server &&
1095296465Sdelphij        SSL_is_init_finished(s) &&
1096296465Sdelphij        !s->s3->send_connection_binding &&
1097296465Sdelphij        (s->version > SSL3_VERSION) &&
1098296465Sdelphij        (s->s3->handshake_fragment_len >= 4) &&
1099296465Sdelphij        (s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
1100296465Sdelphij        (s->session != NULL) && (s->session->cipher != NULL) &&
1101296465Sdelphij        !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
1102296465Sdelphij        /*
1103296465Sdelphij         * s->s3->handshake_fragment_len = 0;
1104296465Sdelphij         */
1105296465Sdelphij        rr->length = 0;
1106296465Sdelphij        ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1107296465Sdelphij        goto start;
1108296465Sdelphij    }
1109296465Sdelphij    if (s->s3->alert_fragment_len >= 2) {
1110296465Sdelphij        int alert_level = s->s3->alert_fragment[0];
1111296465Sdelphij        int alert_descr = s->s3->alert_fragment[1];
1112109998Smarkm
1113296465Sdelphij        s->s3->alert_fragment_len = 0;
111459191Skris
1115296465Sdelphij        if (s->msg_callback)
1116296465Sdelphij            s->msg_callback(0, s->version, SSL3_RT_ALERT,
1117296465Sdelphij                            s->s3->alert_fragment, 2, s, s->msg_callback_arg);
111855714Skris
1119296465Sdelphij        if (s->info_callback != NULL)
1120296465Sdelphij            cb = s->info_callback;
1121296465Sdelphij        else if (s->ctx->info_callback != NULL)
1122296465Sdelphij            cb = s->ctx->info_callback;
112355714Skris
1124296465Sdelphij        if (cb != NULL) {
1125296465Sdelphij            j = (alert_level << 8) | alert_descr;
1126296465Sdelphij            cb(s, SSL_CB_READ_ALERT, j);
1127296465Sdelphij        }
1128109998Smarkm
1129296465Sdelphij        if (alert_level == 1) { /* warning */
1130296465Sdelphij            s->s3->warn_alert = alert_descr;
1131308205Sdelphij
1132308205Sdelphij            s->s3->alert_count++;
1133308205Sdelphij            if (s->s3->alert_count == MAX_WARN_ALERT_COUNT) {
1134308205Sdelphij                al = SSL_AD_UNEXPECTED_MESSAGE;
1135308205Sdelphij                SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_TOO_MANY_WARN_ALERTS);
1136308205Sdelphij                goto f_err;
1137308205Sdelphij            }
1138308205Sdelphij
1139296465Sdelphij            if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
1140296465Sdelphij                s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1141296465Sdelphij                return (0);
1142296465Sdelphij            }
1143296465Sdelphij            /*
1144296465Sdelphij             * This is a warning but we receive it if we requested
1145296465Sdelphij             * renegotiation and the peer denied it. Terminate with a fatal
1146296465Sdelphij             * alert because if application tried to renegotiatie it
1147296465Sdelphij             * presumably had a good reason and expects it to succeed. In
1148296465Sdelphij             * future we might have a renegotiation where we don't care if
1149296465Sdelphij             * the peer refused it where we carry on.
1150296465Sdelphij             */
1151296465Sdelphij            else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1152296465Sdelphij                al = SSL_AD_HANDSHAKE_FAILURE;
1153296465Sdelphij                SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_NO_RENEGOTIATION);
1154296465Sdelphij                goto f_err;
1155296465Sdelphij            }
1156296465Sdelphij        } else if (alert_level == 2) { /* fatal */
1157296465Sdelphij            char tmp[16];
115855714Skris
1159296465Sdelphij            s->rwstate = SSL_NOTHING;
1160296465Sdelphij            s->s3->fatal_alert = alert_descr;
1161296465Sdelphij            SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
1162296465Sdelphij            BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
1163296465Sdelphij            ERR_add_error_data(2, "SSL alert number ", tmp);
1164296465Sdelphij            s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1165296465Sdelphij            SSL_CTX_remove_session(s->ctx, s->session);
1166296465Sdelphij            return (0);
1167296465Sdelphij        } else {
1168296465Sdelphij            al = SSL_AD_ILLEGAL_PARAMETER;
1169296465Sdelphij            SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
1170296465Sdelphij            goto f_err;
1171296465Sdelphij        }
117255714Skris
1173296465Sdelphij        goto start;
1174296465Sdelphij    }
117555714Skris
1176296465Sdelphij    if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
1177296465Sdelphij                                            * shutdown */
1178296465Sdelphij        s->rwstate = SSL_NOTHING;
1179296465Sdelphij        rr->length = 0;
1180296465Sdelphij        return (0);
1181296465Sdelphij    }
118255714Skris
1183296465Sdelphij    if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1184296465Sdelphij        /*
1185296465Sdelphij         * 'Change Cipher Spec' is just a single byte, so we know exactly
1186296465Sdelphij         * what the record payload has to look like
1187296465Sdelphij         */
1188296465Sdelphij        if ((rr->length != 1) || (rr->off != 0) ||
1189296465Sdelphij            (rr->data[0] != SSL3_MT_CCS)) {
1190296465Sdelphij            al = SSL_AD_ILLEGAL_PARAMETER;
1191296465Sdelphij            SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_CHANGE_CIPHER_SPEC);
1192296465Sdelphij            goto f_err;
1193296465Sdelphij        }
119459191Skris
1195296465Sdelphij        /* Check we have a cipher to change to */
1196296465Sdelphij        if (s->s3->tmp.new_cipher == NULL) {
1197296465Sdelphij            al = SSL_AD_UNEXPECTED_MESSAGE;
1198296465Sdelphij            SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
1199296465Sdelphij            goto f_err;
1200296465Sdelphij        }
120159191Skris
1202296465Sdelphij        if (!(s->s3->flags & SSL3_FLAGS_CCS_OK)) {
1203296465Sdelphij            al = SSL_AD_UNEXPECTED_MESSAGE;
1204296465Sdelphij            SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
1205296465Sdelphij            goto f_err;
1206296465Sdelphij        }
120755714Skris
1208296465Sdelphij        s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
1209127114Snectar
1210296465Sdelphij        rr->length = 0;
1211267106Sdelphij
1212296465Sdelphij        if (s->msg_callback)
1213296465Sdelphij            s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
1214296465Sdelphij                            rr->data, 1, s, s->msg_callback_arg);
1215267106Sdelphij
1216296465Sdelphij        s->s3->change_cipher_spec = 1;
1217296465Sdelphij        if (!ssl3_do_change_cipher_spec(s))
1218296465Sdelphij            goto err;
1219296465Sdelphij        else
1220296465Sdelphij            goto start;
1221296465Sdelphij    }
1222109998Smarkm
1223296465Sdelphij    /*
1224296465Sdelphij     * Unexpected handshake message (Client Hello, or protocol violation)
1225296465Sdelphij     */
1226296465Sdelphij    if ((s->s3->handshake_fragment_len >= 4) && !s->in_handshake) {
1227296465Sdelphij        if (((s->state & SSL_ST_MASK) == SSL_ST_OK) &&
1228296465Sdelphij            !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
1229296465Sdelphij#if 0                           /* worked only because C operator preferences
1230296465Sdelphij                                 * are not as expected (and because this is
1231296465Sdelphij                                 * not really needed for clients except for
1232296465Sdelphij                                 * detecting protocol violations): */
1233296465Sdelphij            s->state = SSL_ST_BEFORE | (s->server)
1234296465Sdelphij                ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
123559191Skris#else
1236296465Sdelphij            s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
123759191Skris#endif
1238296465Sdelphij            s->new_session = 1;
1239296465Sdelphij        }
1240296465Sdelphij        i = s->handshake_func(s);
1241296465Sdelphij        if (i < 0)
1242296465Sdelphij            return (i);
1243296465Sdelphij        if (i == 0) {
1244296465Sdelphij            SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1245296465Sdelphij            return (-1);
1246296465Sdelphij        }
124755714Skris
1248296465Sdelphij        if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1249296465Sdelphij            if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
1250296465Sdelphij                BIO *bio;
1251296465Sdelphij                /*
1252296465Sdelphij                 * In the case where we try to read application data, but we
1253296465Sdelphij                 * trigger an SSL handshake, we return -1 with the retry
1254296465Sdelphij                 * option set.  Otherwise renegotiation may cause nasty
1255296465Sdelphij                 * problems in the blocking world
1256296465Sdelphij                 */
1257296465Sdelphij                s->rwstate = SSL_READING;
1258296465Sdelphij                bio = SSL_get_rbio(s);
1259296465Sdelphij                BIO_clear_retry_flags(bio);
1260296465Sdelphij                BIO_set_retry_read(bio);
1261296465Sdelphij                return (-1);
1262296465Sdelphij            }
1263296465Sdelphij        }
1264296465Sdelphij        goto start;
1265296465Sdelphij    }
126655714Skris
1267296465Sdelphij    switch (rr->type) {
1268296465Sdelphij    default:
1269109998Smarkm#ifndef OPENSSL_NO_TLS
1270296465Sdelphij        /* TLS just ignores unknown message types */
1271296465Sdelphij        if (s->version == TLS1_VERSION) {
1272296465Sdelphij            rr->length = 0;
1273296465Sdelphij            goto start;
1274296465Sdelphij        }
127555714Skris#endif
1276296465Sdelphij        al = SSL_AD_UNEXPECTED_MESSAGE;
1277296465Sdelphij        SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1278296465Sdelphij        goto f_err;
1279296465Sdelphij    case SSL3_RT_CHANGE_CIPHER_SPEC:
1280296465Sdelphij    case SSL3_RT_ALERT:
1281296465Sdelphij    case SSL3_RT_HANDSHAKE:
1282296465Sdelphij        /*
1283296465Sdelphij         * we already handled all of these, with the possible exception of
1284296465Sdelphij         * SSL3_RT_HANDSHAKE when s->in_handshake is set, but that should not
1285296465Sdelphij         * happen when type != rr->type
1286296465Sdelphij         */
1287296465Sdelphij        al = SSL_AD_UNEXPECTED_MESSAGE;
1288296465Sdelphij        SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1289296465Sdelphij        goto f_err;
1290296465Sdelphij    case SSL3_RT_APPLICATION_DATA:
1291296465Sdelphij        /*
1292296465Sdelphij         * At this point, we were expecting handshake data, but have
1293296465Sdelphij         * application data.  If the library was running inside ssl3_read()
1294296465Sdelphij         * (i.e. in_read_app_data is set) and it makes sense to read
1295296465Sdelphij         * application data at this point (session renegotiation not yet
1296296465Sdelphij         * started), we will indulge it.
1297296465Sdelphij         */
1298296465Sdelphij        if (s->s3->in_read_app_data &&
1299296465Sdelphij            (s->s3->total_renegotiations != 0) &&
1300296465Sdelphij            (((s->state & SSL_ST_CONNECT) &&
1301296465Sdelphij              (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1302296465Sdelphij              (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
1303296465Sdelphij             ) || ((s->state & SSL_ST_ACCEPT) &&
1304296465Sdelphij                   (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
1305296465Sdelphij                   (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
1306296465Sdelphij             )
1307296465Sdelphij            )) {
1308296465Sdelphij            s->s3->in_read_app_data = 2;
1309296465Sdelphij            return (-1);
1310296465Sdelphij        } else {
1311296465Sdelphij            al = SSL_AD_UNEXPECTED_MESSAGE;
1312296465Sdelphij            SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1313296465Sdelphij            goto f_err;
1314296465Sdelphij        }
1315296465Sdelphij    }
1316296465Sdelphij    /* not reached */
131755714Skris
1318296465Sdelphij f_err:
1319296465Sdelphij    ssl3_send_alert(s, SSL3_AL_FATAL, al);
1320296465Sdelphij err:
1321296465Sdelphij    return (-1);
1322296465Sdelphij}
132355714Skris
1324160814Ssimonint ssl3_do_change_cipher_spec(SSL *s)
1325296465Sdelphij{
1326296465Sdelphij    int i;
1327296465Sdelphij    const char *sender;
1328296465Sdelphij    int slen;
132955714Skris
1330296465Sdelphij    if (s->state & SSL_ST_ACCEPT)
1331296465Sdelphij        i = SSL3_CHANGE_CIPHER_SERVER_READ;
1332296465Sdelphij    else
1333296465Sdelphij        i = SSL3_CHANGE_CIPHER_CLIENT_READ;
133455714Skris
1335296465Sdelphij    if (s->s3->tmp.key_block == NULL) {
1336296465Sdelphij        if (s->session == NULL || s->session->master_key_length == 0) {
1337296465Sdelphij            /* might happen if dtls1_read_bytes() calls this */
1338296465Sdelphij            SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC,
1339296465Sdelphij                   SSL_R_CCS_RECEIVED_EARLY);
1340296465Sdelphij            return (0);
1341296465Sdelphij        }
1342194206Ssimon
1343296465Sdelphij        s->session->cipher = s->s3->tmp.new_cipher;
1344296465Sdelphij        if (!s->method->ssl3_enc->setup_key_block(s))
1345296465Sdelphij            return (0);
1346296465Sdelphij    }
134755714Skris
1348296465Sdelphij    if (!s->method->ssl3_enc->change_cipher_state(s, i))
1349296465Sdelphij        return (0);
135055714Skris
1351296465Sdelphij    /*
1352296465Sdelphij     * we have to record the message digest at this point so we can get it
1353296465Sdelphij     * before we read the finished message
1354296465Sdelphij     */
1355296465Sdelphij    if (s->state & SSL_ST_CONNECT) {
1356296465Sdelphij        sender = s->method->ssl3_enc->server_finished_label;
1357296465Sdelphij        slen = s->method->ssl3_enc->server_finished_label_len;
1358296465Sdelphij    } else {
1359296465Sdelphij        sender = s->method->ssl3_enc->client_finished_label;
1360296465Sdelphij        slen = s->method->ssl3_enc->client_finished_label_len;
1361296465Sdelphij    }
136255714Skris
1363296465Sdelphij    s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
1364296465Sdelphij                                                                          &
1365296465Sdelphij                                                                          (s->s3->finish_dgst1),
1366296465Sdelphij                                                                          &
1367296465Sdelphij                                                                          (s->s3->finish_dgst2),
1368296465Sdelphij                                                                          sender,
1369296465Sdelphij                                                                          slen,
1370296465Sdelphij                                                                          s->s3->tmp.peer_finish_md);
137155714Skris
1372296465Sdelphij    return (1);
1373296465Sdelphij}
137455714Skris
1375205128Ssimonint ssl3_send_alert(SSL *s, int level, int desc)
1376296465Sdelphij{
1377296465Sdelphij    /* Map tls/ssl alert value to correct one */
1378296465Sdelphij    desc = s->method->ssl3_enc->alert_value(desc);
1379296465Sdelphij    if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
1380296465Sdelphij        desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have
1381296465Sdelphij                                          * protocol_version alerts */
1382296465Sdelphij    if (desc < 0)
1383296465Sdelphij        return -1;
1384296465Sdelphij    /* If a fatal one, remove from cache */
1385296465Sdelphij    if ((level == 2) && (s->session != NULL))
1386296465Sdelphij        SSL_CTX_remove_session(s->ctx, s->session);
138755714Skris
1388296465Sdelphij    s->s3->alert_dispatch = 1;
1389296465Sdelphij    s->s3->send_alert[0] = level;
1390296465Sdelphij    s->s3->send_alert[1] = desc;
1391296465Sdelphij    if (s->s3->wbuf.left == 0)  /* data still being written out? */
1392296465Sdelphij        return s->method->ssl_dispatch_alert(s);
1393296465Sdelphij    /*
1394296465Sdelphij     * else data is still being written out, we will get written some time in
1395296465Sdelphij     * the future
1396296465Sdelphij     */
1397296465Sdelphij    return -1;
1398296465Sdelphij}
139955714Skris
140055714Skrisint ssl3_dispatch_alert(SSL *s)
1401296465Sdelphij{
1402296465Sdelphij    int i, j;
1403296465Sdelphij    void (*cb) (const SSL *ssl, int type, int val) = NULL;
140455714Skris
1405296465Sdelphij    s->s3->alert_dispatch = 0;
1406296465Sdelphij    i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0);
1407296465Sdelphij    if (i <= 0) {
1408296465Sdelphij        s->s3->alert_dispatch = 1;
1409296465Sdelphij    } else {
1410296465Sdelphij        /*
1411296465Sdelphij         * Alert sent to BIO.  If it is important, flush it now. If the
1412296465Sdelphij         * message does not get sent due to non-blocking IO, we will not
1413296465Sdelphij         * worry too much.
1414296465Sdelphij         */
1415296465Sdelphij        if (s->s3->send_alert[0] == SSL3_AL_FATAL)
1416296465Sdelphij            (void)BIO_flush(s->wbio);
141755714Skris
1418296465Sdelphij        if (s->msg_callback)
1419296465Sdelphij            s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert,
1420296465Sdelphij                            2, s, s->msg_callback_arg);
1421109998Smarkm
1422296465Sdelphij        if (s->info_callback != NULL)
1423296465Sdelphij            cb = s->info_callback;
1424296465Sdelphij        else if (s->ctx->info_callback != NULL)
1425296465Sdelphij            cb = s->ctx->info_callback;
142659191Skris
1427296465Sdelphij        if (cb != NULL) {
1428296465Sdelphij            j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
1429296465Sdelphij            cb(s, SSL_CB_WRITE_ALERT, j);
1430296465Sdelphij        }
1431296465Sdelphij    }
1432296465Sdelphij    return (i);
1433296465Sdelphij}
1434