Re-align some comments after running the reformat script.
[openssl.git] / ssl / s3_pkt.c
1 /* ssl/s3_pkt.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  *
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  *
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  *
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  *
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  *
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2002 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer.
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111
112 #include <stdio.h>
113 #include <limits.h>
114 #include <errno.h>
115 #define USE_SOCKETS
116 #include "ssl_locl.h"
117 #include <openssl/evp.h>
118 #include <openssl/buffer.h>
119 #include <openssl/rand.h>
120
121 static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
122                          unsigned int len, int create_empty_fragment);
123 static int ssl3_get_record(SSL *s);
124
125 int ssl3_read_n(SSL *s, int n, int max, int extend)
126 {
127     /*
128      * If extend == 0, obtain new n-byte packet; if extend == 1, increase
129      * packet by another n bytes. The packet will be in the sub-array of
130      * s->s3->rbuf.buf specified by s->packet and s->packet_length. (If
131      * s->read_ahead is set, 'max' bytes may be stored in rbuf [plus
132      * s->packet_length bytes if extend == 1].)
133      */
134     int i, len, left;
135     long align = 0;
136     unsigned char *pkt;
137     SSL3_BUFFER *rb;
138
139     if (n <= 0)
140         return n;
141
142     rb = &(s->s3->rbuf);
143     if (rb->buf == NULL)
144         if (!ssl3_setup_read_buffer(s))
145             return -1;
146
147     left = rb->left;
148 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
149     align = (long)rb->buf + SSL3_RT_HEADER_LENGTH;
150     align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
151 #endif
152
153     if (!extend) {
154         /* start with empty packet ... */
155         if (left == 0)
156             rb->offset = align;
157         else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
158             /*
159              * check if next packet length is large enough to justify payload
160              * alignment...
161              */
162             pkt = rb->buf + rb->offset;
163             if (pkt[0] == SSL3_RT_APPLICATION_DATA
164                 && (pkt[3] << 8 | pkt[4]) >= 128) {
165                 /*
166                  * Note that even if packet is corrupted and its length field
167                  * is insane, we can only be led to wrong decision about
168                  * whether memmove will occur or not. Header values has no
169                  * effect on memmove arguments and therefore no buffer
170                  * overrun can be triggered.
171                  */
172                 memmove(rb->buf + align, pkt, left);
173                 rb->offset = align;
174             }
175         }
176         s->packet = rb->buf + rb->offset;
177         s->packet_length = 0;
178         /* ... now we can act as if 'extend' was set */
179     }
180
181     /*
182      * For DTLS/UDP reads should not span multiple packets because the read
183      * operation returns the whole packet at once (as long as it fits into
184      * the buffer).
185      */
186     if (SSL_version(s) == DTLS1_VERSION || SSL_version(s) == DTLS1_BAD_VER) {
187         if (left == 0 && extend)
188             return 0;
189         if (left > 0 && n > left)
190             n = left;
191     }
192
193     /* if there is enough in the buffer from a previous read, take some */
194     if (left >= n) {
195         s->packet_length += n;
196         rb->left = left - n;
197         rb->offset += n;
198         return (n);
199     }
200
201     /* else we need to read more data */
202
203     len = s->packet_length;
204     pkt = rb->buf + align;
205     /*
206      * Move any available bytes to front of buffer: 'len' bytes already
207      * pointed to by 'packet', 'left' extra ones at the end
208      */
209     if (s->packet != pkt) {     /* len > 0 */
210         memmove(pkt, s->packet, len + left);
211         s->packet = pkt;
212         rb->offset = len + align;
213     }
214
215     if (n > (int)(rb->len - rb->offset)) { /* does not happen */
216         SSLerr(SSL_F_SSL3_READ_N, ERR_R_INTERNAL_ERROR);
217         return -1;
218     }
219
220     if (!s->read_ahead)
221         /* ignore max parameter */
222         max = n;
223     else {
224         if (max < n)
225             max = n;
226         if (max > (int)(rb->len - rb->offset))
227             max = rb->len - rb->offset;
228     }
229
230     while (left < n) {
231         /*
232          * Now we have len+left bytes at the front of s->s3->rbuf.buf and
233          * need to read in more until we have len+n (up to len+max if
234          * possible)
235          */
236
237         clear_sys_error();
238         if (s->rbio != NULL) {
239             s->rwstate = SSL_READING;
240             i = BIO_read(s->rbio, pkt + len + left, max - left);
241         } else {
242             SSLerr(SSL_F_SSL3_READ_N, SSL_R_READ_BIO_NOT_SET);
243             i = -1;
244         }
245
246         if (i <= 0) {
247             rb->left = left;
248             if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
249                 SSL_version(s) != DTLS1_VERSION
250                 && SSL_version(s) != DTLS1_BAD_VER)
251                 if (len + left == 0)
252                     ssl3_release_read_buffer(s);
253             return (i);
254         }
255         left += i;
256         /*
257          * reads should *never* span multiple packets for DTLS because the
258          * underlying transport protocol is message oriented as opposed to
259          * byte oriented as in the TLS case.
260          */
261         if (SSL_version(s) == DTLS1_VERSION
262             || SSL_version(s) == DTLS1_BAD_VER) {
263             if (n > left)
264                 n = left;       /* makes the while condition false */
265         }
266     }
267
268     /* done reading, now the book-keeping */
269     rb->offset += n;
270     rb->left = left - n;
271     s->packet_length += n;
272     s->rwstate = SSL_NOTHING;
273     return (n);
274 }
275
276 /*
277  * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
278  * will be processed per call to ssl3_get_record. Without this limit an
279  * attacker could send empty records at a faster rate than we can process and
280  * cause ssl3_get_record to loop forever.
281  */
282 #define MAX_EMPTY_RECORDS 32
283
284 /*-
285  * Call this to get a new input record.
286  * It will return <= 0 if more data is needed, normally due to an error
287  * or non-blocking IO.
288  * When it finishes, one packet has been decoded and can be found in
289  * ssl->s3->rrec.type    - is the type of record
290  * ssl->s3->rrec.data,   - data
291  * ssl->s3->rrec.length, - number of bytes
292  */
293 /* used only by ssl3_read_bytes */
294 static int ssl3_get_record(SSL *s)
295 {
296     int ssl_major, ssl_minor, al;
297     int enc_err, n, i, ret = -1;
298     SSL3_RECORD *rr;
299     SSL_SESSION *sess;
300     unsigned char *p;
301     unsigned char md[EVP_MAX_MD_SIZE];
302     short version;
303     unsigned mac_size, orig_len;
304     size_t extra;
305     unsigned empty_record_count = 0;
306
307     rr = &(s->s3->rrec);
308     sess = s->session;
309
310     if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)
311         extra = SSL3_RT_MAX_EXTRA;
312     else
313         extra = 0;
314     if (extra && !s->s3->init_extra) {
315         /*
316          * An application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER set after
317          * ssl3_setup_buffers() was done
318          */
319         SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
320         return -1;
321     }
322
323  again:
324     /* check if we have the header */
325     if ((s->rstate != SSL_ST_READ_BODY) ||
326         (s->packet_length < SSL3_RT_HEADER_LENGTH)) {
327         n = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
328         if (n <= 0)
329             return (n);         /* error or non-blocking */
330         s->rstate = SSL_ST_READ_BODY;
331
332         p = s->packet;
333
334         /* Pull apart the header into the SSL3_RECORD */
335         rr->type = *(p++);
336         ssl_major = *(p++);
337         ssl_minor = *(p++);
338         version = (ssl_major << 8) | ssl_minor;
339         n2s(p, rr->length);
340 #if 0
341         fprintf(stderr, "Record type=%d, Length=%d\n", rr->type, rr->length);
342 #endif
343
344         /* Lets check version */
345         if (!s->first_packet) {
346             if (version != s->version) {
347                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
348                 if ((s->version & 0xFF00) == (version & 0xFF00)
349                     && !s->enc_write_ctx && !s->write_hash)
350                     /*
351                      * Send back error using their minor version number :-)
352                      */
353                     s->version = (unsigned short)version;
354                 al = SSL_AD_PROTOCOL_VERSION;
355                 goto f_err;
356             }
357         }
358
359         if ((version >> 8) != SSL3_VERSION_MAJOR) {
360             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_WRONG_VERSION_NUMBER);
361             goto err;
362         }
363
364         if (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH) {
365             al = SSL_AD_RECORD_OVERFLOW;
366             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_PACKET_LENGTH_TOO_LONG);
367             goto f_err;
368         }
369
370         /* now s->rstate == SSL_ST_READ_BODY */
371     }
372
373     /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
374
375     if (rr->length > s->packet_length - SSL3_RT_HEADER_LENGTH) {
376         /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
377         i = rr->length;
378         n = ssl3_read_n(s, i, i, 1);
379         if (n <= 0)
380             return (n);         /* error or non-blocking io */
381         /*
382          * now n == rr->length, and s->packet_length == SSL3_RT_HEADER_LENGTH
383          * + rr->length
384          */
385     }
386
387     s->rstate = SSL_ST_READ_HEADER; /* set state for later operations */
388
389     /*
390      * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
391      * and we have that many bytes in s->packet
392      */
393     rr->input = &(s->packet[SSL3_RT_HEADER_LENGTH]);
394
395     /*
396      * ok, we can now read from 's->packet' data into 'rr' rr->input points
397      * at rr->length bytes, which need to be copied into rr->data by either
398      * the decryption or by the decompression When the data is 'copied' into
399      * the rr->data buffer, rr->input will be pointed at the new buffer
400      */
401
402     /*
403      * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
404      * bytes of encrypted compressed stuff.
405      */
406
407     /* check is not needed I believe */
408     if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH + extra) {
409         al = SSL_AD_RECORD_OVERFLOW;
410         SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
411         goto f_err;
412     }
413
414     /* decrypt in place in 'rr->input' */
415     rr->data = rr->input;
416
417     enc_err = s->method->ssl3_enc->enc(s, 0);
418     /*-
419      * enc_err is:
420      *    0: (in non-constant time) if the record is publically invalid.
421      *    1: if the padding is valid
422      *    -1: if the padding is invalid
423      */
424     if (enc_err == 0) {
425         al = SSL_AD_DECRYPTION_FAILED;
426         SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
427         goto f_err;
428     }
429 #ifdef TLS_DEBUG
430     printf("dec %d\n", rr->length);
431     {
432         unsigned int z;
433         for (z = 0; z < rr->length; z++)
434             printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
435     }
436     printf("\n");
437 #endif
438
439     /* r->length is now the compressed data plus mac */
440     if ((sess != NULL) &&
441         (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
442         /* s->read_hash != NULL => mac_size != -1 */
443         unsigned char *mac = NULL;
444         unsigned char mac_tmp[EVP_MAX_MD_SIZE];
445         mac_size = EVP_MD_CTX_size(s->read_hash);
446         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
447
448         /*
449          * kludge: *_cbc_remove_padding passes padding length in rr->type
450          */
451         orig_len = rr->length + ((unsigned int)rr->type >> 8);
452
453         /*
454          * orig_len is the length of the record before any padding was
455          * removed. This is public information, as is the MAC in use,
456          * therefore we can safely process the record in a different amount
457          * of time if it's too short to possibly contain a MAC.
458          */
459         if (orig_len < mac_size ||
460             /* CBC records must have a padding length byte too. */
461             (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
462              orig_len < mac_size + 1)) {
463             al = SSL_AD_DECODE_ERROR;
464             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
465             goto f_err;
466         }
467
468         if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
469             /*
470              * We update the length so that the TLS header bytes can be
471              * constructed correctly but we need to extract the MAC in
472              * constant time from within the record, without leaking the
473              * contents of the padding bytes.
474              */
475             mac = mac_tmp;
476             ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len);
477             rr->length -= mac_size;
478         } else {
479             /*
480              * In this case there's no padding, so |orig_len| equals
481              * |rec->length| and we checked that there's enough bytes for
482              * |mac_size| above.
483              */
484             rr->length -= mac_size;
485             mac = &rr->data[rr->length];
486         }
487
488         i = s->method->ssl3_enc->mac(s, md, 0 /* not send */ );
489         if (i < 0 || mac == NULL
490             || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
491             enc_err = -1;
492         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + extra + mac_size)
493             enc_err = -1;
494     }
495
496     if (enc_err < 0) {
497         /*
498          * A separate 'decryption_failed' alert was introduced with TLS 1.0,
499          * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
500          * failure is directly visible from the ciphertext anyway, we should
501          * not reveal which kind of error occured -- this might become
502          * visible to an attacker (e.g. via a logfile)
503          */
504         al = SSL_AD_BAD_RECORD_MAC;
505         SSLerr(SSL_F_SSL3_GET_RECORD,
506                SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
507         goto f_err;
508     }
509
510     /* r->length is now just compressed */
511     if (s->expand != NULL) {
512         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + extra) {
513             al = SSL_AD_RECORD_OVERFLOW;
514             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_COMPRESSED_LENGTH_TOO_LONG);
515             goto f_err;
516         }
517         if (!ssl3_do_uncompress(s)) {
518             al = SSL_AD_DECOMPRESSION_FAILURE;
519             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BAD_DECOMPRESSION);
520             goto f_err;
521         }
522     }
523
524     if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH + extra) {
525         al = SSL_AD_RECORD_OVERFLOW;
526         SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
527         goto f_err;
528     }
529
530     rr->off = 0;
531     /*-
532      * So at this point the following is true
533      * ssl->s3->rrec.type   is the type of record
534      * ssl->s3->rrec.length == number of bytes in record
535      * ssl->s3->rrec.off    == offset to first valid byte
536      * ssl->s3->rrec.data   == where to take bytes from, increment
537      *                         after use :-).
538      */
539
540     /* we have pulled in a full packet so zero things */
541     s->packet_length = 0;
542
543     /* just read a 0 length packet */
544     if (rr->length == 0) {
545         empty_record_count++;
546         if (empty_record_count > MAX_EMPTY_RECORDS) {
547             al = SSL_AD_UNEXPECTED_MESSAGE;
548             SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_RECORD_TOO_SMALL);
549             goto f_err;
550         }
551         goto again;
552     }
553 #if 0
554     fprintf(stderr, "Ultimate Record type=%d, Length=%d\n", rr->type,
555             rr->length);
556 #endif
557
558     return (1);
559
560  f_err:
561     ssl3_send_alert(s, SSL3_AL_FATAL, al);
562  err:
563     return (ret);
564 }
565
566 int ssl3_do_uncompress(SSL *ssl)
567 {
568 #ifndef OPENSSL_NO_COMP
569     int i;
570     SSL3_RECORD *rr;
571
572     rr = &(ssl->s3->rrec);
573     i = COMP_expand_block(ssl->expand, rr->comp,
574                           SSL3_RT_MAX_PLAIN_LENGTH, rr->data,
575                           (int)rr->length);
576     if (i < 0)
577         return (0);
578     else
579         rr->length = i;
580     rr->data = rr->comp;
581 #endif
582     return (1);
583 }
584
585 int ssl3_do_compress(SSL *ssl)
586 {
587 #ifndef OPENSSL_NO_COMP
588     int i;
589     SSL3_RECORD *wr;
590
591     wr = &(ssl->s3->wrec);
592     i = COMP_compress_block(ssl->compress, wr->data,
593                             SSL3_RT_MAX_COMPRESSED_LENGTH,
594                             wr->input, (int)wr->length);
595     if (i < 0)
596         return (0);
597     else
598         wr->length = i;
599
600     wr->input = wr->data;
601 #endif
602     return (1);
603 }
604
605 /*
606  * Call this to write data in records of type 'type' It will return <= 0 if
607  * not all data has been sent or non-blocking IO.
608  */
609 int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
610 {
611     const unsigned char *buf = buf_;
612     unsigned int n, nw;
613     int i, tot;
614
615     s->rwstate = SSL_NOTHING;
616     OPENSSL_assert(s->s3->wnum <= INT_MAX);
617     tot = s->s3->wnum;
618     s->s3->wnum = 0;
619
620     if (SSL_in_init(s) && !s->in_handshake) {
621         i = s->handshake_func(s);
622         if (i < 0)
623             return (i);
624         if (i == 0) {
625             SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
626             return -1;
627         }
628     }
629
630     /*
631      * ensure that if we end up with a smaller value of data to write out
632      * than the the original len from a write which didn't complete for
633      * non-blocking I/O and also somehow ended up avoiding the check for
634      * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
635      * possible to end up with (len-tot) as a large number that will then
636      * promptly send beyond the end of the users buffer ... so we trap and
637      * report the error in a way the user will notice
638      */
639     if (len < tot) {
640         SSLerr(SSL_F_SSL3_WRITE_BYTES, SSL_R_BAD_LENGTH);
641         return (-1);
642     }
643
644     n = (len - tot);
645     for (;;) {
646         if (n > s->max_send_fragment)
647             nw = s->max_send_fragment;
648         else
649             nw = n;
650
651         i = do_ssl3_write(s, type, &(buf[tot]), nw, 0);
652         if (i <= 0) {
653             s->s3->wnum = tot;
654             return i;
655         }
656
657         if ((i == (int)n) ||
658             (type == SSL3_RT_APPLICATION_DATA &&
659              (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
660             /*
661              * next chunk of data should get another prepended empty fragment
662              * in ciphersuites with known-IV weakness:
663              */
664             s->s3->empty_fragment_done = 0;
665
666             return tot + i;
667         }
668
669         n -= i;
670         tot += i;
671     }
672 }
673
674 static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
675                          unsigned int len, int create_empty_fragment)
676 {
677     unsigned char *p, *plen;
678     int i, mac_size, clear = 0;
679     int prefix_len = 0;
680     int eivlen;
681     long align = 0;
682     SSL3_RECORD *wr;
683     SSL3_BUFFER *wb = &(s->s3->wbuf);
684     SSL_SESSION *sess;
685
686     /*
687      * first check if there is a SSL3_BUFFER still being written out.  This
688      * will happen with non blocking IO
689      */
690     if (wb->left != 0)
691         return (ssl3_write_pending(s, type, buf, len));
692
693     /* If we have an alert to send, lets send it */
694     if (s->s3->alert_dispatch) {
695         i = s->method->ssl_dispatch_alert(s);
696         if (i <= 0)
697             return (i);
698         /* if it went, fall through and send more stuff */
699     }
700
701     if (wb->buf == NULL)
702         if (!ssl3_setup_write_buffer(s))
703             return -1;
704
705     if (len == 0 && !create_empty_fragment)
706         return 0;
707
708     wr = &(s->s3->wrec);
709     sess = s->session;
710
711     if ((sess == NULL) ||
712         (s->enc_write_ctx == NULL) ||
713         (EVP_MD_CTX_md(s->write_hash) == NULL)) {
714 #if 1
715         clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
716 #else
717         clear = 1;
718 #endif
719         mac_size = 0;
720     } else {
721         mac_size = EVP_MD_CTX_size(s->write_hash);
722         if (mac_size < 0)
723             goto err;
724     }
725
726     /*
727      * 'create_empty_fragment' is true only when this function calls itself
728      */
729     if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done) {
730         /*
731          * countermeasure against known-IV weakness in CBC ciphersuites (see
732          * http://www.openssl.org/~bodo/tls-cbc.txt)
733          */
734
735         if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
736             /*
737              * recursive function call with 'create_empty_fragment' set; this
738              * prepares and buffers the data for an empty fragment (these
739              * 'prefix_len' bytes are sent out later together with the actual
740              * payload)
741              */
742             prefix_len = do_ssl3_write(s, type, buf, 0, 1);
743             if (prefix_len <= 0)
744                 goto err;
745
746             if (prefix_len >
747                 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD))
748             {
749                 /* insufficient space */
750                 SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
751                 goto err;
752             }
753         }
754
755         s->s3->empty_fragment_done = 1;
756     }
757
758     if (create_empty_fragment) {
759 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
760         /*
761          * extra fragment would be couple of cipher blocks, which would be
762          * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
763          * payload, then we can just pretent we simply have two headers.
764          */
765         align = (long)wb->buf + 2 * SSL3_RT_HEADER_LENGTH;
766         align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
767 #endif
768         p = wb->buf + align;
769         wb->offset = align;
770     } else if (prefix_len) {
771         p = wb->buf + wb->offset + prefix_len;
772     } else {
773 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
774         align = (long)wb->buf + SSL3_RT_HEADER_LENGTH;
775         align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
776 #endif
777         p = wb->buf + align;
778         wb->offset = align;
779     }
780
781     /* write the header */
782
783     *(p++) = type & 0xff;
784     wr->type = type;
785
786     *(p++) = (s->version >> 8);
787     /*
788      * Some servers hang if iniatial client hello is larger than 256 bytes
789      * and record version number > TLS 1.0
790      */
791     if (s->state == SSL3_ST_CW_CLNT_HELLO_B
792         && !s->renegotiate && TLS1_get_version(s) > TLS1_VERSION)
793         *(p++) = 0x1;
794     else
795         *(p++) = s->version & 0xff;
796
797     /* field where we are to write out packet length */
798     plen = p;
799     p += 2;
800     /* Explicit IV length, block ciphers and TLS version 1.1 or later */
801     if (s->enc_write_ctx && s->version >= TLS1_1_VERSION) {
802         int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
803         if (mode == EVP_CIPH_CBC_MODE) {
804             eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
805             if (eivlen <= 1)
806                 eivlen = 0;
807         }
808         /* Need explicit part of IV for GCM mode */
809         else if (mode == EVP_CIPH_GCM_MODE)
810             eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
811         else
812             eivlen = 0;
813     } else
814         eivlen = 0;
815
816     /* lets setup the record stuff. */
817     wr->data = p + eivlen;
818     wr->length = (int)len;
819     wr->input = (unsigned char *)buf;
820
821     /*
822      * we now 'read' from wr->input, wr->length bytes into wr->data
823      */
824
825     /* first we compress */
826     if (s->compress != NULL) {
827         if (!ssl3_do_compress(s)) {
828             SSLerr(SSL_F_DO_SSL3_WRITE, SSL_R_COMPRESSION_FAILURE);
829             goto err;
830         }
831     } else {
832         memcpy(wr->data, wr->input, wr->length);
833         wr->input = wr->data;
834     }
835
836     /*
837      * we should still have the output to wr->data and the input from
838      * wr->input.  Length should be wr->length. wr->data still points in the
839      * wb->buf
840      */
841
842     if (mac_size != 0) {
843         if (s->method->ssl3_enc->mac(s, &(p[wr->length + eivlen]), 1) < 0)
844             goto err;
845         wr->length += mac_size;
846     }
847
848     wr->input = p;
849     wr->data = p;
850
851     if (eivlen) {
852         /*
853          * if (RAND_pseudo_bytes(p, eivlen) <= 0) goto err;
854          */
855         wr->length += eivlen;
856     }
857
858     if (s->method->ssl3_enc->enc(s, 1) < 1)
859         goto err;
860
861     /* record length after mac and block padding */
862     s2n(wr->length, plen);
863
864     /*
865      * we should now have wr->data pointing to the encrypted data, which is
866      * wr->length long
867      */
868     wr->type = type;            /* not needed but helps for debugging */
869     wr->length += SSL3_RT_HEADER_LENGTH;
870
871     if (create_empty_fragment) {
872         /*
873          * we are in a recursive call; just return the length, don't write
874          * out anything here
875          */
876         return wr->length;
877     }
878
879     /* now let's set up wb */
880     wb->left = prefix_len + wr->length;
881
882     /*
883      * memorize arguments so that ssl3_write_pending can detect bad write
884      * retries later
885      */
886     s->s3->wpend_tot = len;
887     s->s3->wpend_buf = buf;
888     s->s3->wpend_type = type;
889     s->s3->wpend_ret = len;
890
891     /* we now just need to write the buffer */
892     return ssl3_write_pending(s, type, buf, len);
893  err:
894     return -1;
895 }
896
897 /* if s->s3->wbuf.left != 0, we need to call this */
898 int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
899                        unsigned int len)
900 {
901     int i;
902     SSL3_BUFFER *wb = &(s->s3->wbuf);
903
904 /* XXXX */
905     if ((s->s3->wpend_tot > (int)len)
906         || ((s->s3->wpend_buf != buf) &&
907             !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
908         || (s->s3->wpend_type != type)) {
909         SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BAD_WRITE_RETRY);
910         return (-1);
911     }
912
913     for (;;) {
914         clear_sys_error();
915         if (s->wbio != NULL) {
916             s->rwstate = SSL_WRITING;
917             i = BIO_write(s->wbio,
918                           (char *)&(wb->buf[wb->offset]),
919                           (unsigned int)wb->left);
920         } else {
921             SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BIO_NOT_SET);
922             i = -1;
923         }
924         if (i == wb->left) {
925             wb->left = 0;
926             wb->offset += i;
927             if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
928                 SSL_version(s) != DTLS1_VERSION
929                 && SSL_version(s) != DTLS1_BAD_VER)
930                 ssl3_release_write_buffer(s);
931             s->rwstate = SSL_NOTHING;
932             return (s->s3->wpend_ret);
933         } else if (i <= 0) {
934             if (s->version == DTLS1_VERSION || s->version == DTLS1_BAD_VER) {
935                 /*
936                  * For DTLS, just drop it. That's kind of the whole point in
937                  * using a datagram service
938                  */
939                 wb->left = 0;
940             }
941             return (i);
942         }
943         wb->offset += i;
944         wb->left -= i;
945     }
946 }
947
948 /*-
949  * Return up to 'len' payload bytes received in 'type' records.
950  * 'type' is one of the following:
951  *
952  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
953  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
954  *   -  0 (during a shutdown, no data has to be returned)
955  *
956  * If we don't have stored data to work from, read a SSL/TLS record first
957  * (possibly multiple records if we still don't have anything to return).
958  *
959  * This function must handle any surprises the peer may have for us, such as
960  * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
961  * a surprise, but handled as if it were), or renegotiation requests.
962  * Also if record payloads contain fragments too small to process, we store
963  * them until there is enough for the respective protocol (the record protocol
964  * may use arbitrary fragmentation and even interleaving):
965  *     Change cipher spec protocol
966  *             just 1 byte needed, no need for keeping anything stored
967  *     Alert protocol
968  *             2 bytes needed (AlertLevel, AlertDescription)
969  *     Handshake protocol
970  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
971  *             to detect unexpected Client Hello and Hello Request messages
972  *             here, anything else is handled by higher layers
973  *     Application data protocol
974  *             none of our business
975  */
976 int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
977 {
978     int al, i, j, ret;
979     unsigned int n;
980     SSL3_RECORD *rr;
981     void (*cb) (const SSL *ssl, int type2, int val) = NULL;
982
983     if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
984         if (!ssl3_setup_read_buffer(s))
985             return (-1);
986
987     if ((type && (type != SSL3_RT_APPLICATION_DATA)
988          && (type != SSL3_RT_HANDSHAKE)) || (peek
989                                              && (type !=
990                                                  SSL3_RT_APPLICATION_DATA))) {
991         SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
992         return -1;
993     }
994
995     if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0))
996         /* (partially) satisfy request from storage */
997     {
998         unsigned char *src = s->s3->handshake_fragment;
999         unsigned char *dst = buf;
1000         unsigned int k;
1001
1002         /* peek == 0 */
1003         n = 0;
1004         while ((len > 0) && (s->s3->handshake_fragment_len > 0)) {
1005             *dst++ = *src++;
1006             len--;
1007             s->s3->handshake_fragment_len--;
1008             n++;
1009         }
1010         /* move any remaining fragment bytes: */
1011         for (k = 0; k < s->s3->handshake_fragment_len; k++)
1012             s->s3->handshake_fragment[k] = *src++;
1013         return n;
1014     }
1015
1016     /*
1017      * Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1018      */
1019
1020     if (!s->in_handshake && SSL_in_init(s)) {
1021         /* type == SSL3_RT_APPLICATION_DATA */
1022         i = s->handshake_func(s);
1023         if (i < 0)
1024             return (i);
1025         if (i == 0) {
1026             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1027             return (-1);
1028         }
1029     }
1030  start:
1031     s->rwstate = SSL_NOTHING;
1032
1033     /*-
1034      * s->s3->rrec.type         - is the type of record
1035      * s->s3->rrec.data,    - data
1036      * s->s3->rrec.off,     - offset into 'data' for next read
1037      * s->s3->rrec.length,  - number of bytes.
1038      */
1039     rr = &(s->s3->rrec);
1040
1041     /* get new packet if necessary */
1042     if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) {
1043         ret = ssl3_get_record(s);
1044         if (ret <= 0)
1045             return (ret);
1046     }
1047
1048     /* we now have a packet which can be read and processed */
1049
1050     if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
1051                                    * reset by ssl3_get_finished */
1052         && (rr->type != SSL3_RT_HANDSHAKE)) {
1053         al = SSL_AD_UNEXPECTED_MESSAGE;
1054         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1055         goto f_err;
1056     }
1057
1058     /*
1059      * If the other end has shut down, throw anything we read away (even in
1060      * 'peek' mode)
1061      */
1062     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1063         rr->length = 0;
1064         s->rwstate = SSL_NOTHING;
1065         return (0);
1066     }
1067
1068     if (type == rr->type) {     /* SSL3_RT_APPLICATION_DATA or
1069                                  * SSL3_RT_HANDSHAKE */
1070         /*
1071          * make sure that we are not getting application data when we are
1072          * doing a handshake for the first time
1073          */
1074         if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
1075             (s->enc_read_ctx == NULL)) {
1076             al = SSL_AD_UNEXPECTED_MESSAGE;
1077             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
1078             goto f_err;
1079         }
1080
1081         if (len <= 0)
1082             return (len);
1083
1084         if ((unsigned int)len > rr->length)
1085             n = rr->length;
1086         else
1087             n = (unsigned int)len;
1088
1089         memcpy(buf, &(rr->data[rr->off]), n);
1090         if (!peek) {
1091             rr->length -= n;
1092             rr->off += n;
1093             if (rr->length == 0) {
1094                 s->rstate = SSL_ST_READ_HEADER;
1095                 rr->off = 0;
1096                 if (s->mode & SSL_MODE_RELEASE_BUFFERS
1097                     && s->s3->rbuf.left == 0)
1098                     ssl3_release_read_buffer(s);
1099             }
1100         }
1101         return (n);
1102     }
1103
1104     /*
1105      * If we get here, then type != rr->type; if we have a handshake message,
1106      * then it was unexpected (Hello Request or Client Hello).
1107      */
1108
1109     /*
1110      * In case of record types for which we have 'fragment' storage, fill
1111      * that so that we can process the data at a fixed place.
1112      */
1113     {
1114         unsigned int dest_maxlen = 0;
1115         unsigned char *dest = NULL;
1116         unsigned int *dest_len = NULL;
1117
1118         if (rr->type == SSL3_RT_HANDSHAKE) {
1119             dest_maxlen = sizeof s->s3->handshake_fragment;
1120             dest = s->s3->handshake_fragment;
1121             dest_len = &s->s3->handshake_fragment_len;
1122         } else if (rr->type == SSL3_RT_ALERT) {
1123             dest_maxlen = sizeof s->s3->alert_fragment;
1124             dest = s->s3->alert_fragment;
1125             dest_len = &s->s3->alert_fragment_len;
1126         }
1127 #ifndef OPENSSL_NO_HEARTBEATS
1128         else if (rr->type == TLS1_RT_HEARTBEAT) {
1129             tls1_process_heartbeat(s);
1130
1131             /* Exit and notify application to read again */
1132             rr->length = 0;
1133             s->rwstate = SSL_READING;
1134             BIO_clear_retry_flags(SSL_get_rbio(s));
1135             BIO_set_retry_read(SSL_get_rbio(s));
1136             return (-1);
1137         }
1138 #endif
1139
1140         if (dest_maxlen > 0) {
1141             n = dest_maxlen - *dest_len; /* available space in 'dest' */
1142             if (rr->length < n)
1143                 n = rr->length; /* available bytes */
1144
1145             /* now move 'n' bytes: */
1146             while (n-- > 0) {
1147                 dest[(*dest_len)++] = rr->data[rr->off++];
1148                 rr->length--;
1149             }
1150
1151             if (*dest_len < dest_maxlen)
1152                 goto start;     /* fragment was too small */
1153         }
1154     }
1155
1156     /*-
1157      * s->s3->handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
1158      * s->s3->alert_fragment_len == 2      iff  rr->type == SSL3_RT_ALERT.
1159      * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1160      */
1161
1162     /* If we are a client, check for an incoming 'Hello Request': */
1163     if ((!s->server) &&
1164         (s->s3->handshake_fragment_len >= 4) &&
1165         (s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
1166         (s->session != NULL) && (s->session->cipher != NULL)) {
1167         s->s3->handshake_fragment_len = 0;
1168
1169         if ((s->s3->handshake_fragment[1] != 0) ||
1170             (s->s3->handshake_fragment[2] != 0) ||
1171             (s->s3->handshake_fragment[3] != 0)) {
1172             al = SSL_AD_DECODE_ERROR;
1173             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
1174             goto f_err;
1175         }
1176
1177         if (s->msg_callback)
1178             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1179                             s->s3->handshake_fragment, 4, s,
1180                             s->msg_callback_arg);
1181
1182         if (SSL_is_init_finished(s) &&
1183             !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
1184             !s->s3->renegotiate) {
1185             ssl3_renegotiate(s);
1186             if (ssl3_renegotiate_check(s)) {
1187                 i = s->handshake_func(s);
1188                 if (i < 0)
1189                     return (i);
1190                 if (i == 0) {
1191                     SSLerr(SSL_F_SSL3_READ_BYTES,
1192                            SSL_R_SSL_HANDSHAKE_FAILURE);
1193                     return (-1);
1194                 }
1195
1196                 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1197                     if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
1198                         BIO *bio;
1199                         /*
1200                          * In the case where we try to read application data,
1201                          * but we trigger an SSL handshake, we return -1 with
1202                          * the retry option set.  Otherwise renegotiation may
1203                          * cause nasty problems in the blocking world
1204                          */
1205                         s->rwstate = SSL_READING;
1206                         bio = SSL_get_rbio(s);
1207                         BIO_clear_retry_flags(bio);
1208                         BIO_set_retry_read(bio);
1209                         return (-1);
1210                     }
1211                 }
1212             }
1213         }
1214         /*
1215          * we either finished a handshake or ignored the request, now try
1216          * again to obtain the (application) data we were asked for
1217          */
1218         goto start;
1219     }
1220     /*
1221      * If we are a server and get a client hello when renegotiation isn't
1222      * allowed send back a no renegotiation alert and carry on. WARNING:
1223      * experimental code, needs reviewing (steve)
1224      */
1225     if (s->server &&
1226         SSL_is_init_finished(s) &&
1227         !s->s3->send_connection_binding &&
1228         (s->version > SSL3_VERSION) &&
1229         (s->s3->handshake_fragment_len >= 4) &&
1230         (s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
1231         (s->session != NULL) && (s->session->cipher != NULL) &&
1232         !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION)) {
1233         /*
1234          * s->s3->handshake_fragment_len = 0;
1235          */
1236         rr->length = 0;
1237         ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1238         goto start;
1239     }
1240     if (s->s3->alert_fragment_len >= 2) {
1241         int alert_level = s->s3->alert_fragment[0];
1242         int alert_descr = s->s3->alert_fragment[1];
1243
1244         s->s3->alert_fragment_len = 0;
1245
1246         if (s->msg_callback)
1247             s->msg_callback(0, s->version, SSL3_RT_ALERT,
1248                             s->s3->alert_fragment, 2, s, s->msg_callback_arg);
1249
1250         if (s->info_callback != NULL)
1251             cb = s->info_callback;
1252         else if (s->ctx->info_callback != NULL)
1253             cb = s->ctx->info_callback;
1254
1255         if (cb != NULL) {
1256             j = (alert_level << 8) | alert_descr;
1257             cb(s, SSL_CB_READ_ALERT, j);
1258         }
1259
1260         if (alert_level == 1) { /* warning */
1261             s->s3->warn_alert = alert_descr;
1262             if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
1263                 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1264                 return (0);
1265             }
1266             /*
1267              * This is a warning but we receive it if we requested
1268              * renegotiation and the peer denied it. Terminate with a fatal
1269              * alert because if application tried to renegotiatie it
1270              * presumably had a good reason and expects it to succeed. In
1271              * future we might have a renegotiation where we don't care if
1272              * the peer refused it where we carry on.
1273              */
1274             else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1275                 al = SSL_AD_HANDSHAKE_FAILURE;
1276                 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_NO_RENEGOTIATION);
1277                 goto f_err;
1278             }
1279 #ifdef SSL_AD_MISSING_SRP_USERNAME
1280             else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME)
1281                 return (0);
1282 #endif
1283         } else if (alert_level == 2) { /* fatal */
1284             char tmp[16];
1285
1286             s->rwstate = SSL_NOTHING;
1287             s->s3->fatal_alert = alert_descr;
1288             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
1289             BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
1290             ERR_add_error_data(2, "SSL alert number ", tmp);
1291             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1292             SSL_CTX_remove_session(s->ctx, s->session);
1293             return (0);
1294         } else {
1295             al = SSL_AD_ILLEGAL_PARAMETER;
1296             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
1297             goto f_err;
1298         }
1299
1300         goto start;
1301     }
1302
1303     if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
1304                                             * shutdown */
1305         s->rwstate = SSL_NOTHING;
1306         rr->length = 0;
1307         return (0);
1308     }
1309
1310     if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1311         /*
1312          * 'Change Cipher Spec' is just a single byte, so we know exactly
1313          * what the record payload has to look like
1314          */
1315         if ((rr->length != 1) || (rr->off != 0) ||
1316             (rr->data[0] != SSL3_MT_CCS)) {
1317             al = SSL_AD_ILLEGAL_PARAMETER;
1318             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_CHANGE_CIPHER_SPEC);
1319             goto f_err;
1320         }
1321
1322         /* Check we have a cipher to change to */
1323         if (s->s3->tmp.new_cipher == NULL) {
1324             al = SSL_AD_UNEXPECTED_MESSAGE;
1325             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
1326             goto f_err;
1327         }
1328
1329         if (!(s->s3->flags & SSL3_FLAGS_CCS_OK)) {
1330             al = SSL_AD_UNEXPECTED_MESSAGE;
1331             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_CCS_RECEIVED_EARLY);
1332             goto f_err;
1333         }
1334
1335         s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
1336
1337         rr->length = 0;
1338
1339         if (s->msg_callback)
1340             s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC,
1341                             rr->data, 1, s, s->msg_callback_arg);
1342
1343         s->s3->change_cipher_spec = 1;
1344         if (!ssl3_do_change_cipher_spec(s))
1345             goto err;
1346         else
1347             goto start;
1348     }
1349
1350     /*
1351      * Unexpected handshake message (Client Hello, or protocol violation)
1352      */
1353     if ((s->s3->handshake_fragment_len >= 4) && !s->in_handshake) {
1354         if (((s->state & SSL_ST_MASK) == SSL_ST_OK) &&
1355             !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
1356 #if 0                           /* worked only because C operator preferences
1357                                  * are not as expected (and because this is
1358                                  * not really needed for clients except for
1359                                  * detecting protocol violations): */
1360             s->state = SSL_ST_BEFORE | (s->server)
1361                 ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
1362 #else
1363             s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
1364 #endif
1365             s->renegotiate = 1;
1366             s->new_session = 1;
1367         }
1368         i = s->handshake_func(s);
1369         if (i < 0)
1370             return (i);
1371         if (i == 0) {
1372             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
1373             return (-1);
1374         }
1375
1376         if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1377             if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
1378                 BIO *bio;
1379                 /*
1380                  * In the case where we try to read application data, but we
1381                  * trigger an SSL handshake, we return -1 with the retry
1382                  * option set.  Otherwise renegotiation may cause nasty
1383                  * problems in the blocking world
1384                  */
1385                 s->rwstate = SSL_READING;
1386                 bio = SSL_get_rbio(s);
1387                 BIO_clear_retry_flags(bio);
1388                 BIO_set_retry_read(bio);
1389                 return (-1);
1390             }
1391         }
1392         goto start;
1393     }
1394
1395     switch (rr->type) {
1396     default:
1397 #ifndef OPENSSL_NO_TLS
1398         /*
1399          * TLS up to v1.1 just ignores unknown message types: TLS v1.2 give
1400          * an unexpected message alert.
1401          */
1402         if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION) {
1403             rr->length = 0;
1404             goto start;
1405         }
1406 #endif
1407         al = SSL_AD_UNEXPECTED_MESSAGE;
1408         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1409         goto f_err;
1410     case SSL3_RT_CHANGE_CIPHER_SPEC:
1411     case SSL3_RT_ALERT:
1412     case SSL3_RT_HANDSHAKE:
1413         /*
1414          * we already handled all of these, with the possible exception of
1415          * SSL3_RT_HANDSHAKE when s->in_handshake is set, but that should not
1416          * happen when type != rr->type
1417          */
1418         al = SSL_AD_UNEXPECTED_MESSAGE;
1419         SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1420         goto f_err;
1421     case SSL3_RT_APPLICATION_DATA:
1422         /*
1423          * At this point, we were expecting handshake data, but have
1424          * application data.  If the library was running inside ssl3_read()
1425          * (i.e. in_read_app_data is set) and it makes sense to read
1426          * application data at this point (session renegotiation not yet
1427          * started), we will indulge it.
1428          */
1429         if (s->s3->in_read_app_data &&
1430             (s->s3->total_renegotiations != 0) &&
1431             (((s->state & SSL_ST_CONNECT) &&
1432               (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1433               (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
1434              ) || ((s->state & SSL_ST_ACCEPT) &&
1435                    (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
1436                    (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
1437              )
1438             )) {
1439             s->s3->in_read_app_data = 2;
1440             return (-1);
1441         } else {
1442             al = SSL_AD_UNEXPECTED_MESSAGE;
1443             SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1444             goto f_err;
1445         }
1446     }
1447     /* not reached */
1448
1449  f_err:
1450     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1451  err:
1452     return (-1);
1453 }
1454
1455 int ssl3_do_change_cipher_spec(SSL *s)
1456 {
1457     int i;
1458     const char *sender;
1459     int slen;
1460
1461     if (s->state & SSL_ST_ACCEPT)
1462         i = SSL3_CHANGE_CIPHER_SERVER_READ;
1463     else
1464         i = SSL3_CHANGE_CIPHER_CLIENT_READ;
1465
1466     if (s->s3->tmp.key_block == NULL) {
1467         if (s->session == NULL || s->session->master_key_length == 0) {
1468             /* might happen if dtls1_read_bytes() calls this */
1469             SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC,
1470                    SSL_R_CCS_RECEIVED_EARLY);
1471             return (0);
1472         }
1473
1474         s->session->cipher = s->s3->tmp.new_cipher;
1475         if (!s->method->ssl3_enc->setup_key_block(s))
1476             return (0);
1477     }
1478
1479     if (!s->method->ssl3_enc->change_cipher_state(s, i))
1480         return (0);
1481
1482     /*
1483      * we have to record the message digest at this point so we can get it
1484      * before we read the finished message
1485      */
1486     if (s->state & SSL_ST_CONNECT) {
1487         sender = s->method->ssl3_enc->server_finished_label;
1488         slen = s->method->ssl3_enc->server_finished_label_len;
1489     } else {
1490         sender = s->method->ssl3_enc->client_finished_label;
1491         slen = s->method->ssl3_enc->client_finished_label_len;
1492     }
1493
1494     i = s->method->ssl3_enc->final_finish_mac(s,
1495                                               sender, slen,
1496                                               s->s3->tmp.peer_finish_md);
1497     if (i == 0) {
1498         SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
1499         return 0;
1500     }
1501     s->s3->tmp.peer_finish_md_len = i;
1502
1503     return (1);
1504 }
1505
1506 int ssl3_send_alert(SSL *s, int level, int desc)
1507 {
1508     /* Map tls/ssl alert value to correct one */
1509     desc = s->method->ssl3_enc->alert_value(desc);
1510     if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
1511         desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have
1512                                           * protocol_version alerts */
1513     if (desc < 0)
1514         return -1;
1515     /* If a fatal one, remove from cache */
1516     if ((level == 2) && (s->session != NULL))
1517         SSL_CTX_remove_session(s->ctx, s->session);
1518
1519     s->s3->alert_dispatch = 1;
1520     s->s3->send_alert[0] = level;
1521     s->s3->send_alert[1] = desc;
1522     if (s->s3->wbuf.left == 0)  /* data still being written out? */
1523         return s->method->ssl_dispatch_alert(s);
1524     /*
1525      * else data is still being written out, we will get written some time in
1526      * the future
1527      */
1528     return -1;
1529 }
1530
1531 int ssl3_dispatch_alert(SSL *s)
1532 {
1533     int i, j;
1534     void (*cb) (const SSL *ssl, int type, int val) = NULL;
1535
1536     s->s3->alert_dispatch = 0;
1537     i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0);
1538     if (i <= 0) {
1539         s->s3->alert_dispatch = 1;
1540     } else {
1541         /*
1542          * Alert sent to BIO.  If it is important, flush it now. If the
1543          * message does not get sent due to non-blocking IO, we will not
1544          * worry too much.
1545          */
1546         if (s->s3->send_alert[0] == SSL3_AL_FATAL)
1547             (void)BIO_flush(s->wbio);
1548
1549         if (s->msg_callback)
1550             s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert,
1551                             2, s, s->msg_callback_arg);
1552
1553         if (s->info_callback != NULL)
1554             cb = s->info_callback;
1555         else if (s->ctx->info_callback != NULL)
1556             cb = s->ctx->info_callback;
1557
1558         if (cb != NULL) {
1559             j = (s->s3->send_alert[0] << 8) | s->s3->send_alert[1];
1560             cb(s, SSL_CB_WRITE_ALERT, j);
1561         }
1562     }
1563     return (i);
1564 }