Merge branch 'vendor/LIBRESSL'
[dragonfly.git] / crypto / libressl / ssl / s3_pkt.c
1 /* $OpenBSD: s3_pkt.c,v 1.58 2016/07/10 23:07:34 tedu Exp $ */
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 <errno.h>
113 #include <stdio.h>
114
115 #include "ssl_locl.h"
116
117 #include <openssl/buffer.h>
118 #include <openssl/evp.h>
119
120 #include "bytestring.h"
121
122 static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
123     unsigned int len, int create_empty_fragment);
124 static int ssl3_get_record(SSL *s);
125
126 /* If extend == 0, obtain new n-byte packet; if extend == 1, increase
127  * packet by another n bytes.
128  * The packet will be in the sub-array of s->s3->rbuf.buf specified
129  * by s->packet and s->packet_length.
130  * (If s->read_ahead is set, 'max' bytes may be stored in rbuf
131  * [plus s->packet_length bytes if extend == 1].)
132  */
133 int
134 ssl3_read_n(SSL *s, int n, int max, int extend)
135 {
136         int i, len, left;
137         size_t align;
138         unsigned char *pkt;
139         SSL3_BUFFER *rb;
140
141         if (n <= 0)
142                 return n;
143
144         rb = &(s->s3->rbuf);
145         if (rb->buf == NULL)
146                 if (!ssl3_setup_read_buffer(s))
147                         return -1;
148
149         left = rb->left;
150         align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
151         align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
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                         /* check if next packet length is large
159                          * enough to justify payload alignment... */
160                         pkt = rb->buf + rb->offset;
161                         if (pkt[0] == SSL3_RT_APPLICATION_DATA &&
162                             (pkt[3]<<8|pkt[4]) >= 128) {
163                                 /* Note that even if packet is corrupted
164                                  * and its length field is insane, we can
165                                  * only be led to wrong decision about
166                                  * whether memmove will occur or not.
167                                  * Header values has no effect on memmove
168                                  * arguments and therefore no buffer
169                                  * overrun can be triggered. */
170                                 memmove(rb->buf + align, pkt, left);
171                                 rb->offset = align;
172                         }
173                 }
174                 s->packet = rb->buf + rb->offset;
175                 s->packet_length = 0;
176                 /* ... now we can act as if 'extend' was set */
177         }
178
179         /* For DTLS/UDP reads should not span multiple packets
180          * because the read operation returns the whole packet
181          * at once (as long as it fits into the buffer). */
182         if (SSL_IS_DTLS(s)) {
183                 if (left > 0 && n > left)
184                         n = left;
185         }
186
187         /* if there is enough in the buffer from a previous read, take some */
188         if (left >= n) {
189                 s->packet_length += n;
190                 rb->left = left - n;
191                 rb->offset += n;
192                 return (n);
193         }
194
195         /* else we need to read more data */
196
197         len = s->packet_length;
198         pkt = rb->buf + align;
199         /* Move any available bytes to front of buffer:
200          * 'len' bytes already pointed to by 'packet',
201          * 'left' extra ones at the end */
202         if (s->packet != pkt)  {
203                 /* len > 0 */
204                 memmove(pkt, s->packet, len + left);
205                 s->packet = pkt;
206                 rb->offset = len + align;
207         }
208
209         if (n > (int)(rb->len - rb->offset)) {
210                 /* does not happen */
211                 SSLerr(SSL_F_SSL3_READ_N, ERR_R_INTERNAL_ERROR);
212                 return -1;
213         }
214
215         if (!s->read_ahead) {
216                 /* ignore max parameter */
217                 max = n;
218         } else {
219                 if (max < n)
220                         max = n;
221                 if (max > (int)(rb->len - rb->offset))
222                         max = rb->len - rb->offset;
223         }
224
225         while (left < n) {
226                 /* Now we have len+left bytes at the front of s->s3->rbuf.buf
227                  * and need to read in more until we have len+n (up to
228                  * len+max if possible) */
229
230                 errno = 0;
231                 if (s->rbio != NULL) {
232                         s->rwstate = SSL_READING;
233                         i = BIO_read(s->rbio, pkt + len + left, max - left);
234                 } else {
235                         SSLerr(SSL_F_SSL3_READ_N, SSL_R_READ_BIO_NOT_SET);
236                         i = -1;
237                 }
238
239                 if (i <= 0) {
240                         rb->left = left;
241                         if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
242                             !SSL_IS_DTLS(s)) {
243                                 if (len + left == 0)
244                                         ssl3_release_read_buffer(s);
245                         }
246                         return (i);
247                 }
248                 left += i;
249
250                 /*
251                  * reads should *never* span multiple packets for DTLS because
252                  * the underlying transport protocol is message oriented as
253                  * opposed to byte oriented as in the TLS case.
254                  */
255                 if (SSL_IS_DTLS(s)) {
256                         if (n > left)
257                                 n = left; /* makes the while condition false */
258                 }
259         }
260
261         /* done reading, now the book-keeping */
262         rb->offset += n;
263         rb->left = left - n;
264         s->packet_length += n;
265         s->rwstate = SSL_NOTHING;
266         return (n);
267 }
268
269 /* Call this to get a new input record.
270  * It will return <= 0 if more data is needed, normally due to an error
271  * or non-blocking IO.
272  * When it finishes, one packet has been decoded and can be found in
273  * ssl->s3->rrec.type    - is the type of record
274  * ssl->s3->rrec.data,   - data
275  * ssl->s3->rrec.length, - number of bytes
276  */
277 /* used only by ssl3_read_bytes */
278 static int
279 ssl3_get_record(SSL *s)
280 {
281         int al;
282         int enc_err, n, i, ret = -1;
283         SSL3_RECORD *rr;
284         SSL_SESSION *sess;
285         unsigned char md[EVP_MAX_MD_SIZE];
286         unsigned mac_size, orig_len;
287
288         rr = &(s->s3->rrec);
289         sess = s->session;
290
291 again:
292         /* check if we have the header */
293         if ((s->rstate != SSL_ST_READ_BODY) ||
294             (s->packet_length < SSL3_RT_HEADER_LENGTH)) {
295                 CBS header;
296                 uint16_t len, ssl_version;
297                 uint8_t type;
298
299                 n = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
300                 if (n <= 0)
301                         return(n); /* error or non-blocking */
302                 s->rstate = SSL_ST_READ_BODY;
303
304                 CBS_init(&header, s->packet, n);
305
306                 /* Pull apart the header into the SSL3_RECORD */
307                 if (!CBS_get_u8(&header, &type) ||
308                     !CBS_get_u16(&header, &ssl_version) ||
309                     !CBS_get_u16(&header, &len)) {
310                         SSLerr(SSL_F_SSL3_GET_RECORD,
311                             SSL_R_BAD_PACKET_LENGTH);
312                         goto err;
313                 }
314
315                 rr->type = type;
316                 rr->length = len;
317
318                 /* Lets check version */
319                 if (!s->first_packet && ssl_version != s->version) {
320                         SSLerr(SSL_F_SSL3_GET_RECORD,
321                             SSL_R_WRONG_VERSION_NUMBER);
322                         if ((s->version & 0xFF00) == (ssl_version & 0xFF00) &&
323                             !s->enc_write_ctx && !s->write_hash)
324                                 /* Send back error using their minor version number :-) */
325                                 s->version = ssl_version;
326                         al = SSL_AD_PROTOCOL_VERSION;
327                         goto f_err;
328                 }
329
330                 if ((ssl_version >> 8) != SSL3_VERSION_MAJOR) {
331                         SSLerr(SSL_F_SSL3_GET_RECORD,
332                             SSL_R_WRONG_VERSION_NUMBER);
333                         goto err;
334                 }
335
336                 if (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH) {
337                         al = SSL_AD_RECORD_OVERFLOW;
338                         SSLerr(SSL_F_SSL3_GET_RECORD,
339                             SSL_R_PACKET_LENGTH_TOO_LONG);
340                         goto f_err;
341                 }
342
343                 /* now s->rstate == SSL_ST_READ_BODY */
344         }
345
346         /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
347
348         if (rr->length > s->packet_length - SSL3_RT_HEADER_LENGTH) {
349                 /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
350                 i = rr->length;
351                 n = ssl3_read_n(s, i, i, 1);
352                 if (n <= 0)
353                         return(n); /* error or non-blocking io */
354                 /* now n == rr->length,
355                  * and s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length */
356         }
357
358         s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
359
360         /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
361          * and we have that many bytes in s->packet
362          */
363         rr->input = &(s->packet[SSL3_RT_HEADER_LENGTH]);
364
365         /* ok, we can now read from 's->packet' data into 'rr'
366          * rr->input points at rr->length bytes, which
367          * need to be copied into rr->data by either
368          * the decryption or by the decompression
369          * When the data is 'copied' into the rr->data buffer,
370          * rr->input will be pointed at the new buffer */
371
372         /* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
373          * rr->length bytes of encrypted compressed stuff. */
374
375         /* check is not needed I believe */
376         if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
377                 al = SSL_AD_RECORD_OVERFLOW;
378                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
379                 goto f_err;
380         }
381
382         /* decrypt in place in 'rr->input' */
383         rr->data = rr->input;
384
385         enc_err = s->method->ssl3_enc->enc(s, 0);
386         /* enc_err is:
387          *    0: (in non-constant time) if the record is publically invalid.
388          *    1: if the padding is valid
389          *    -1: if the padding is invalid */
390         if (enc_err == 0) {
391                 al = SSL_AD_DECRYPTION_FAILED;
392                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
393                 goto f_err;
394         }
395
396
397         /* r->length is now the compressed data plus mac */
398         if ((sess != NULL) && (s->enc_read_ctx != NULL) &&
399             (EVP_MD_CTX_md(s->read_hash) != NULL)) {
400                 /* s->read_hash != NULL => mac_size != -1 */
401                 unsigned char *mac = NULL;
402                 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
403
404                 mac_size = EVP_MD_CTX_size(s->read_hash);
405                 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
406
407                 /* kludge: *_cbc_remove_padding passes padding length in rr->type */
408                 orig_len = rr->length + ((unsigned int)rr->type >> 8);
409
410                 /* orig_len is the length of the record before any padding was
411                  * removed. This is public information, as is the MAC in use,
412                  * therefore we can safely process the record in a different
413                  * amount of time if it's too short to possibly contain a MAC.
414                  */
415                 if (orig_len < mac_size ||
416                         /* CBC records must have a padding length byte too. */
417                     (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
418                     orig_len < mac_size + 1)) {
419                         al = SSL_AD_DECODE_ERROR;
420                         SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_LENGTH_TOO_SHORT);
421                         goto f_err;
422                 }
423
424                 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
425                         /* We update the length so that the TLS header bytes
426                          * can be constructed correctly but we need to extract
427                          * the MAC in constant time from within the record,
428                          * without leaking the contents of the padding bytes.
429                          * */
430                         mac = mac_tmp;
431                         ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len);
432                         rr->length -= mac_size;
433                 } else {
434                         /* In this case there's no padding, so |orig_len|
435                          * equals |rec->length| and we checked that there's
436                          * enough bytes for |mac_size| above. */
437                         rr->length -= mac_size;
438                         mac = &rr->data[rr->length];
439                 }
440
441                 i = s->method->ssl3_enc->mac(s,md,0 /* not send */);
442                 if (i < 0 || mac == NULL ||
443                     timingsafe_memcmp(md, mac, (size_t)mac_size) != 0)
444                         enc_err = -1;
445                 if (rr->length >
446                     SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
447                         enc_err = -1;
448         }
449
450         if (enc_err < 0) {
451                 /*
452                  * A separate 'decryption_failed' alert was introduced with
453                  * TLS 1.0, SSL 3.0 only has 'bad_record_mac'. But unless a
454                  * decryption failure is directly visible from the ciphertext
455                  * anyway, we should not reveal which kind of error
456                  * occurred -- this might become visible to an attacker
457                  * (e.g. via a logfile)
458                  */
459                 al = SSL_AD_BAD_RECORD_MAC;
460                 SSLerr(SSL_F_SSL3_GET_RECORD,
461                     SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
462                 goto f_err;
463         }
464
465         if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
466                 al = SSL_AD_RECORD_OVERFLOW;
467                 SSLerr(SSL_F_SSL3_GET_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
468                 goto f_err;
469         }
470
471         rr->off = 0;
472         /*
473          * So at this point the following is true
474          *
475          * ssl->s3->rrec.type   is the type of record
476          * ssl->s3->rrec.length == number of bytes in record
477          * ssl->s3->rrec.off    == offset to first valid byte
478          * ssl->s3->rrec.data   == where to take bytes from, increment
479          *                         after use :-).
480          */
481
482         /* we have pulled in a full packet so zero things */
483         s->packet_length = 0;
484
485         /* just read a 0 length packet */
486         if (rr->length == 0)
487                 goto again;
488
489         return (1);
490
491 f_err:
492         ssl3_send_alert(s, SSL3_AL_FATAL, al);
493 err:
494         return (ret);
495 }
496
497 /* Call this to write data in records of type 'type'
498  * It will return <= 0 if not all data has been sent or non-blocking IO.
499  */
500 int
501 ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
502 {
503         const unsigned char *buf = buf_;
504         unsigned int tot, n, nw;
505         int i;
506
507         if (len < 0) {
508                 SSLerr(SSL_F_SSL3_WRITE_BYTES, ERR_R_INTERNAL_ERROR);
509                 return -1;
510         }
511
512         s->rwstate = SSL_NOTHING;
513         tot = s->s3->wnum;
514         s->s3->wnum = 0;
515
516         if (SSL_in_init(s) && !s->in_handshake) {
517                 i = s->handshake_func(s);
518                 if (i < 0)
519                         return (i);
520                 if (i == 0) {
521                         SSLerr(SSL_F_SSL3_WRITE_BYTES,
522                             SSL_R_SSL_HANDSHAKE_FAILURE);
523                         return -1;
524                 }
525         }
526
527         if (len < tot)
528                 len = tot;
529         n = (len - tot);
530         for (;;) {
531                 if (n > s->max_send_fragment)
532                         nw = s->max_send_fragment;
533                 else
534                         nw = n;
535
536                 i = do_ssl3_write(s, type, &(buf[tot]), nw, 0);
537                 if (i <= 0) {
538                         s->s3->wnum = tot;
539                         return i;
540                 }
541
542                 if ((i == (int)n) || (type == SSL3_RT_APPLICATION_DATA &&
543                     (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
544                         /*
545                          * Next chunk of data should get another prepended
546                          * empty fragment in ciphersuites with known-IV
547                          * weakness.
548                          */
549                         s->s3->empty_fragment_done = 0;
550
551                         return tot + i;
552                 }
553
554                 n -= i;
555                 tot += i;
556         }
557 }
558
559 static int
560 do_ssl3_write(SSL *s, int type, const unsigned char *buf,
561     unsigned int len, int create_empty_fragment)
562 {
563         unsigned char *p, *plen;
564         int i, mac_size, clear = 0;
565         int prefix_len = 0;
566         int eivlen;
567         size_t align;
568         SSL3_RECORD *wr;
569         SSL3_BUFFER *wb = &(s->s3->wbuf);
570         SSL_SESSION *sess;
571
572         if (wb->buf == NULL)
573                 if (!ssl3_setup_write_buffer(s))
574                         return -1;
575
576         /* first check if there is a SSL3_BUFFER still being written
577          * out.  This will happen with non blocking IO */
578         if (wb->left != 0)
579                 return (ssl3_write_pending(s, type, buf, len));
580
581         /* If we have an alert to send, lets send it */
582         if (s->s3->alert_dispatch) {
583                 i = s->method->ssl_dispatch_alert(s);
584                 if (i <= 0)
585                         return (i);
586                 /* if it went, fall through and send more stuff */
587                 /* we may have released our buffer, so get it again */
588                 if (wb->buf == NULL)
589                         if (!ssl3_setup_write_buffer(s))
590                                 return -1;
591         }
592
593         if (len == 0 && !create_empty_fragment)
594                 return 0;
595
596         wr = &(s->s3->wrec);
597         sess = s->session;
598
599         if ((sess == NULL) || (s->enc_write_ctx == NULL) ||
600             (EVP_MD_CTX_md(s->write_hash) == NULL)) {
601                 clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
602                 mac_size = 0;
603         } else {
604                 mac_size = EVP_MD_CTX_size(s->write_hash);
605                 if (mac_size < 0)
606                         goto err;
607         }
608
609         /*
610          * 'create_empty_fragment' is true only when this function calls
611          * itself.
612          */
613         if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done) {
614                 /*
615                  * Countermeasure against known-IV weakness in CBC ciphersuites
616                  * (see http://www.openssl.org/~bodo/tls-cbc.txt)
617                  */
618                 if (s->s3->need_empty_fragments &&
619                     type == SSL3_RT_APPLICATION_DATA) {
620                         /* recursive function call with 'create_empty_fragment' set;
621                          * this prepares and buffers the data for an empty fragment
622                          * (these 'prefix_len' bytes are sent out later
623                          * together with the actual payload) */
624                         prefix_len = do_ssl3_write(s, type, buf, 0, 1);
625                         if (prefix_len <= 0)
626                                 goto err;
627
628                         if (prefix_len >
629                                 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
630                                 /* insufficient space */
631                                 SSLerr(SSL_F_DO_SSL3_WRITE,
632                                     ERR_R_INTERNAL_ERROR);
633                                 goto err;
634                         }
635                 }
636
637                 s->s3->empty_fragment_done = 1;
638         }
639
640         if (create_empty_fragment) {
641                 /* extra fragment would be couple of cipher blocks,
642                  * which would be multiple of SSL3_ALIGN_PAYLOAD, so
643                  * if we want to align the real payload, then we can
644                  * just pretent we simply have two headers. */
645                 align = (size_t)wb->buf + 2 * SSL3_RT_HEADER_LENGTH;
646                 align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
647
648                 p = wb->buf + align;
649                 wb->offset = align;
650         } else if (prefix_len) {
651                 p = wb->buf + wb->offset + prefix_len;
652         } else {
653                 align = (size_t)wb->buf + SSL3_RT_HEADER_LENGTH;
654                 align = (-align) & (SSL3_ALIGN_PAYLOAD - 1);
655
656                 p = wb->buf + align;
657                 wb->offset = align;
658         }
659
660         /* write the header */
661
662         *(p++) = type&0xff;
663         wr->type = type;
664
665         *(p++) = (s->version >> 8);
666         /* Some servers hang if iniatial client hello is larger than 256
667          * bytes and record version number > TLS 1.0
668          */
669         if (s->state == SSL3_ST_CW_CLNT_HELLO_B && !s->renegotiate &&
670             TLS1_get_version(s) > TLS1_VERSION)
671                 *(p++) = 0x1;
672         else
673                 *(p++) = s->version&0xff;
674
675         /* field where we are to write out packet length */
676         plen = p;
677         p += 2;
678
679         /* Explicit IV length. */
680         if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)) {
681                 int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
682                 if (mode == EVP_CIPH_CBC_MODE) {
683                         eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
684                         if (eivlen <= 1)
685                                 eivlen = 0;
686                 }
687                 /* Need explicit part of IV for GCM mode */
688                 else if (mode == EVP_CIPH_GCM_MODE)
689                         eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
690                 else
691                         eivlen = 0;
692         } else if (s->aead_write_ctx != NULL &&
693             s->aead_write_ctx->variable_nonce_in_record) {
694                 eivlen = s->aead_write_ctx->variable_nonce_len;
695         } else
696                 eivlen = 0;
697
698         /* lets setup the record stuff. */
699         wr->data = p + eivlen;
700         wr->length = (int)len;
701         wr->input = (unsigned char *)buf;
702
703         /* we now 'read' from wr->input, wr->length bytes into wr->data */
704
705         memcpy(wr->data, wr->input, wr->length);
706         wr->input = wr->data;
707
708         /* we should still have the output to wr->data and the input
709          * from wr->input.  Length should be wr->length.
710          * wr->data still points in the wb->buf */
711
712         if (mac_size != 0) {
713                 if (s->method->ssl3_enc->mac(s,
714                     &(p[wr->length + eivlen]), 1) < 0)
715                         goto err;
716                 wr->length += mac_size;
717         }
718
719         wr->input = p;
720         wr->data = p;
721
722         if (eivlen) {
723                 /* if (RAND_pseudo_bytes(p, eivlen) <= 0)
724                         goto err;
725                 */
726                 wr->length += eivlen;
727         }
728
729         /* ssl3_enc can only have an error on read */
730         s->method->ssl3_enc->enc(s, 1);
731
732         /* record length after mac and block padding */
733         s2n(wr->length, plen);
734
735         /* we should now have
736          * wr->data pointing to the encrypted data, which is
737          * wr->length long */
738         wr->type=type; /* not needed but helps for debugging */
739         wr->length += SSL3_RT_HEADER_LENGTH;
740
741         if (create_empty_fragment) {
742                 /* we are in a recursive call;
743                  * just return the length, don't write out anything here
744                  */
745                 return wr->length;
746         }
747
748         /* now let's set up wb */
749         wb->left = prefix_len + wr->length;
750
751         /* memorize arguments so that ssl3_write_pending can detect
752          * bad write retries later */
753         s->s3->wpend_tot = len;
754         s->s3->wpend_buf = buf;
755         s->s3->wpend_type = type;
756         s->s3->wpend_ret = len;
757
758         /* we now just need to write the buffer */
759         return ssl3_write_pending(s, type, buf, len);
760 err:
761         return -1;
762 }
763
764 /* if s->s3->wbuf.left != 0, we need to call this */
765 int
766 ssl3_write_pending(SSL *s, int type, const unsigned char *buf, unsigned int len)
767 {
768         int i;
769         SSL3_BUFFER *wb = &(s->s3->wbuf);
770
771         /* XXXX */
772         if ((s->s3->wpend_tot > (int)len) || ((s->s3->wpend_buf != buf) &&
773             !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)) ||
774             (s->s3->wpend_type != type)) {
775                 SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BAD_WRITE_RETRY);
776                 return (-1);
777         }
778
779         for (;;) {
780                 errno = 0;
781                 if (s->wbio != NULL) {
782                         s->rwstate = SSL_WRITING;
783                         i = BIO_write(s->wbio,
784                         (char *)&(wb->buf[wb->offset]),
785                         (unsigned int)wb->left);
786                 } else {
787                         SSLerr(SSL_F_SSL3_WRITE_PENDING, SSL_R_BIO_NOT_SET);
788                         i = -1;
789                 }
790                 if (i == wb->left) {
791                         wb->left = 0;
792                         wb->offset += i;
793                         if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
794                             !SSL_IS_DTLS(s))
795                                 ssl3_release_write_buffer(s);
796                         s->rwstate = SSL_NOTHING;
797                         return (s->s3->wpend_ret);
798                 } else if (i <= 0) {
799                         /*
800                          * For DTLS, just drop it. That's kind of the
801                          * whole point in using a datagram service.
802                          */
803                         if (SSL_IS_DTLS(s))
804                                 wb->left = 0;
805                         return (i);
806                 }
807                 wb->offset += i;
808                 wb->left -= i;
809         }
810 }
811
812 /* Return up to 'len' payload bytes received in 'type' records.
813  * 'type' is one of the following:
814  *
815  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
816  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
817  *   -  0 (during a shutdown, no data has to be returned)
818  *
819  * If we don't have stored data to work from, read a SSL/TLS record first
820  * (possibly multiple records if we still don't have anything to return).
821  *
822  * This function must handle any surprises the peer may have for us, such as
823  * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
824  * a surprise, but handled as if it were), or renegotiation requests.
825  * Also if record payloads contain fragments too small to process, we store
826  * them until there is enough for the respective protocol (the record protocol
827  * may use arbitrary fragmentation and even interleaving):
828  *     Change cipher spec protocol
829  *             just 1 byte needed, no need for keeping anything stored
830  *     Alert protocol
831  *             2 bytes needed (AlertLevel, AlertDescription)
832  *     Handshake protocol
833  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
834  *             to detect unexpected Client Hello and Hello Request messages
835  *             here, anything else is handled by higher layers
836  *     Application data protocol
837  *             none of our business
838  */
839 int
840 ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
841 {
842         void (*cb)(const SSL *ssl, int type2, int val) = NULL;
843         int al, i, j, ret, rrcount = 0;
844         unsigned int n;
845         SSL3_RECORD *rr;
846         BIO *bio;
847
848         if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
849                 if (!ssl3_setup_read_buffer(s))
850                         return (-1);
851
852         if (len < 0) {
853                 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
854                 return -1;
855         }
856
857         if ((type && type != SSL3_RT_APPLICATION_DATA &&
858             type != SSL3_RT_HANDSHAKE) ||
859             (peek && (type != SSL3_RT_APPLICATION_DATA))) {
860                 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
861                 return -1;
862         }
863
864         if ((type == SSL3_RT_HANDSHAKE) &&
865             (s->s3->handshake_fragment_len > 0)) {
866                 /* (partially) satisfy request from storage */
867                 unsigned char *src = s->s3->handshake_fragment;
868                 unsigned char *dst = buf;
869                 unsigned int k;
870
871                 /* peek == 0 */
872                 n = 0;
873                 while ((len > 0) && (s->s3->handshake_fragment_len > 0)) {
874                         *dst++ = *src++;
875                         len--;
876                         s->s3->handshake_fragment_len--;
877                         n++;
878                 }
879                 /* move any remaining fragment bytes: */
880                 for (k = 0; k < s->s3->handshake_fragment_len; k++)
881                         s->s3->handshake_fragment[k] = *src++;
882                 return n;
883         }
884
885         /*
886          * Now s->s3->handshake_fragment_len == 0 if
887          * type == SSL3_RT_HANDSHAKE.
888          */
889         if (!s->in_handshake && SSL_in_init(s)) {
890                 /* type == SSL3_RT_APPLICATION_DATA */
891                 i = s->handshake_func(s);
892                 if (i < 0)
893                         return (i);
894                 if (i == 0) {
895                         SSLerr(SSL_F_SSL3_READ_BYTES,
896                             SSL_R_SSL_HANDSHAKE_FAILURE);
897                         return (-1);
898                 }
899         }
900
901 start:
902         /*
903          * Do not process more than three consecutive records, otherwise the
904          * peer can cause us to loop indefinitely. Instead, return with an
905          * SSL_ERROR_WANT_READ so the caller can choose when to handle further
906          * processing. In the future, the total number of non-handshake and
907          * non-application data records per connection should probably also be
908          * limited...
909          */
910         if (rrcount++ >= 3) {
911                 if ((bio = SSL_get_rbio(s)) == NULL) {
912                         SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
913                         return -1;
914                 }
915                 BIO_clear_retry_flags(bio);
916                 BIO_set_retry_read(bio);
917                 s->rwstate = SSL_READING;
918                 return -1;
919         }
920
921         s->rwstate = SSL_NOTHING;
922
923         /*
924          * s->s3->rrec.type         - is the type of record
925          * s->s3->rrec.data,    - data
926          * s->s3->rrec.off,     - offset into 'data' for next read
927          * s->s3->rrec.length,  - number of bytes.
928          */
929         rr = &(s->s3->rrec);
930
931         /* get new packet if necessary */
932         if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY)) {
933                 ret = ssl3_get_record(s);
934                 if (ret <= 0)
935                         return (ret);
936         }
937
938         /* we now have a packet which can be read and processed */
939
940         if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
941                                        * reset by ssl3_get_finished */
942             && (rr->type != SSL3_RT_HANDSHAKE)) {
943                 al = SSL_AD_UNEXPECTED_MESSAGE;
944                 SSLerr(SSL_F_SSL3_READ_BYTES,
945                     SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
946                 goto f_err;
947         }
948
949         /* If the other end has shut down, throw anything we read away
950          * (even in 'peek' mode) */
951         if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
952                 rr->length = 0;
953                 s->rwstate = SSL_NOTHING;
954                 return (0);
955         }
956
957
958         /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
959         if (type == rr->type) {
960                 /* make sure that we are not getting application data when we
961                  * are doing a handshake for the first time */
962                 if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
963                         (s->enc_read_ctx == NULL)) {
964                         al = SSL_AD_UNEXPECTED_MESSAGE;
965                         SSLerr(SSL_F_SSL3_READ_BYTES,
966                             SSL_R_APP_DATA_IN_HANDSHAKE);
967                         goto f_err;
968                 }
969
970                 if (len <= 0)
971                         return (len);
972
973                 if ((unsigned int)len > rr->length)
974                         n = rr->length;
975                 else
976                         n = (unsigned int)len;
977
978                 memcpy(buf, &(rr->data[rr->off]), n);
979                 if (!peek) {
980                         memset(&(rr->data[rr->off]), 0, n);
981                         rr->length -= n;
982                         rr->off += n;
983                         if (rr->length == 0) {
984                                 s->rstate = SSL_ST_READ_HEADER;
985                                 rr->off = 0;
986                                 if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
987                                     s->s3->rbuf.left == 0)
988                                         ssl3_release_read_buffer(s);
989                         }
990                 }
991                 return (n);
992         }
993
994
995         /* If we get here, then type != rr->type; if we have a handshake
996          * message, then it was unexpected (Hello Request or Client Hello). */
997
998         {
999                 /*
1000                  * In case of record types for which we have 'fragment'
1001                  * storage, * fill that so that we can process the data
1002                  * at a fixed place.
1003                  */
1004                 unsigned int dest_maxlen = 0;
1005                 unsigned char *dest = NULL;
1006                 unsigned int *dest_len = NULL;
1007
1008                 if (rr->type == SSL3_RT_HANDSHAKE) {
1009                         dest_maxlen = sizeof s->s3->handshake_fragment;
1010                         dest = s->s3->handshake_fragment;
1011                         dest_len = &s->s3->handshake_fragment_len;
1012                 } else if (rr->type == SSL3_RT_ALERT) {
1013                         dest_maxlen = sizeof s->s3->alert_fragment;
1014                         dest = s->s3->alert_fragment;
1015                         dest_len = &s->s3->alert_fragment_len;
1016                 }
1017                 if (dest_maxlen > 0) {
1018                         /* available space in 'dest' */
1019                         n = dest_maxlen - *dest_len;
1020                         if (rr->length < n)
1021                                 n = rr->length; /* available bytes */
1022
1023                         /* now move 'n' bytes: */
1024                         while (n-- > 0) {
1025                                 dest[(*dest_len)++] = rr->data[rr->off++];
1026                                 rr->length--;
1027                         }
1028
1029                         if (*dest_len < dest_maxlen)
1030                                 goto start; /* fragment was too small */
1031                 }
1032         }
1033
1034         /* s->s3->handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
1035          * s->s3->alert_fragment_len == 2      iff  rr->type == SSL3_RT_ALERT.
1036          * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
1037
1038         /* If we are a client, check for an incoming 'Hello Request': */
1039         if ((!s->server) && (s->s3->handshake_fragment_len >= 4) &&
1040             (s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
1041             (s->session != NULL) && (s->session->cipher != NULL)) {
1042                 s->s3->handshake_fragment_len = 0;
1043
1044                 if ((s->s3->handshake_fragment[1] != 0) ||
1045                     (s->s3->handshake_fragment[2] != 0) ||
1046                     (s->s3->handshake_fragment[3] != 0)) {
1047                         al = SSL_AD_DECODE_ERROR;
1048                         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
1049                         goto f_err;
1050                 }
1051
1052                 if (s->msg_callback)
1053                         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
1054                             s->s3->handshake_fragment, 4, s,
1055                             s->msg_callback_arg);
1056
1057                 if (SSL_is_init_finished(s) &&
1058                     !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
1059                     !s->s3->renegotiate) {
1060                         ssl3_renegotiate(s);
1061                         if (ssl3_renegotiate_check(s)) {
1062                                 i = s->handshake_func(s);
1063                                 if (i < 0)
1064                                         return (i);
1065                                 if (i == 0) {
1066                                         SSLerr(SSL_F_SSL3_READ_BYTES,
1067                                             SSL_R_SSL_HANDSHAKE_FAILURE);
1068                                         return (-1);
1069                                 }
1070
1071                                 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1072                                         if (s->s3->rbuf.left == 0) {
1073                                                 /* no read-ahead left? */
1074                         /* In the case where we try to read application data,
1075                          * but we trigger an SSL handshake, we return -1 with
1076                          * the retry option set.  Otherwise renegotiation may
1077                          * cause nasty problems in the blocking world */
1078                                                 s->rwstate = SSL_READING;
1079                                                 bio = SSL_get_rbio(s);
1080                                                 BIO_clear_retry_flags(bio);
1081                                                 BIO_set_retry_read(bio);
1082                                                 return (-1);
1083                                         }
1084                                 }
1085                         }
1086                 }
1087                 /* we either finished a handshake or ignored the request,
1088                  * now try again to obtain the (application) data we were asked for */
1089                 goto start;
1090         }
1091         /* If we are a server and get a client hello when renegotiation isn't
1092          * allowed send back a no renegotiation alert and carry on.
1093          * WARNING: experimental code, needs reviewing (steve)
1094          */
1095         if (s->server &&
1096             SSL_is_init_finished(s) &&
1097             !s->s3->send_connection_binding &&
1098             (s->s3->handshake_fragment_len >= 4) &&
1099             (s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
1100             (s->session != NULL) && (s->session->cipher != NULL)) {
1101                 /*s->s3->handshake_fragment_len = 0;*/
1102                 rr->length = 0;
1103                 ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1104                 goto start;
1105         }
1106         if (s->s3->alert_fragment_len >= 2) {
1107                 int alert_level = s->s3->alert_fragment[0];
1108                 int alert_descr = s->s3->alert_fragment[1];
1109
1110                 s->s3->alert_fragment_len = 0;
1111
1112                 if (s->msg_callback)
1113                         s->msg_callback(0, s->version, SSL3_RT_ALERT,
1114                             s->s3->alert_fragment, 2, s, s->msg_callback_arg);
1115
1116                 if (s->info_callback != NULL)
1117                         cb = s->info_callback;
1118                 else if (s->ctx->info_callback != NULL)
1119                         cb = s->ctx->info_callback;
1120
1121                 if (cb != NULL) {
1122                         j = (alert_level << 8) | alert_descr;
1123                         cb(s, SSL_CB_READ_ALERT, j);
1124                 }
1125
1126                 if (alert_level == 1) {
1127                         /* warning */
1128                         s->s3->warn_alert = alert_descr;
1129                         if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
1130                                 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1131                                 return (0);
1132                         }
1133                         /* This is a warning but we receive it if we requested
1134                          * renegotiation and the peer denied it. Terminate with
1135                          * a fatal alert because if application tried to
1136                          * renegotiatie it presumably had a good reason and
1137                          * expects it to succeed.
1138                          *
1139                          * In future we might have a renegotiation where we
1140                          * don't care if the peer refused it where we carry on.
1141                          */
1142                         else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1143                                 al = SSL_AD_HANDSHAKE_FAILURE;
1144                                 SSLerr(SSL_F_SSL3_READ_BYTES,
1145                                     SSL_R_NO_RENEGOTIATION);
1146                                 goto f_err;
1147                         }
1148                 } else if (alert_level == 2) {
1149                         /* fatal */
1150                         s->rwstate = SSL_NOTHING;
1151                         s->s3->fatal_alert = alert_descr;
1152                         SSLerr(SSL_F_SSL3_READ_BYTES,
1153                             SSL_AD_REASON_OFFSET + alert_descr);
1154                         ERR_asprintf_error_data("SSL alert number %d",
1155                             alert_descr);
1156                         s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1157                         SSL_CTX_remove_session(s->ctx, s->session);
1158                         return (0);
1159                 } else {
1160                         al = SSL_AD_ILLEGAL_PARAMETER;
1161                         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
1162                         goto f_err;
1163                 }
1164
1165                 goto start;
1166         }
1167
1168         if (s->shutdown & SSL_SENT_SHUTDOWN) {
1169                 /* but we have not received a shutdown */
1170                 s->rwstate = SSL_NOTHING;
1171                 rr->length = 0;
1172                 return (0);
1173         }
1174
1175         if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
1176                 /* 'Change Cipher Spec' is just a single byte, so we know
1177                  * exactly what the record payload has to look like */
1178                 if ((rr->length != 1) || (rr->off != 0) ||
1179                         (rr->data[0] != SSL3_MT_CCS)) {
1180                         al = SSL_AD_ILLEGAL_PARAMETER;
1181                         SSLerr(SSL_F_SSL3_READ_BYTES,
1182                             SSL_R_BAD_CHANGE_CIPHER_SPEC);
1183                         goto f_err;
1184                 }
1185
1186                 /* Check we have a cipher to change to */
1187                 if (s->s3->tmp.new_cipher == NULL) {
1188                         al = SSL_AD_UNEXPECTED_MESSAGE;
1189                         SSLerr(SSL_F_SSL3_READ_BYTES,
1190                             SSL_R_CCS_RECEIVED_EARLY);
1191                         goto f_err;
1192                 }
1193
1194                 /* Check that we should be receiving a Change Cipher Spec. */
1195                 if (!(s->s3->flags & SSL3_FLAGS_CCS_OK)) {
1196                         al = SSL_AD_UNEXPECTED_MESSAGE;
1197                         SSLerr(SSL_F_SSL3_READ_BYTES,
1198                             SSL_R_CCS_RECEIVED_EARLY);
1199                         goto f_err;
1200                 }
1201                 s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
1202
1203                 rr->length = 0;
1204
1205                 if (s->msg_callback) {
1206                         s->msg_callback(0, s->version,
1207                             SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s,
1208                             s->msg_callback_arg);
1209                 }
1210
1211                 s->s3->change_cipher_spec = 1;
1212                 if (!ssl3_do_change_cipher_spec(s))
1213                         goto err;
1214                 else
1215                         goto start;
1216         }
1217
1218         /* Unexpected handshake message (Client Hello, or protocol violation) */
1219         if ((s->s3->handshake_fragment_len >= 4) && !s->in_handshake) {
1220                 if (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&
1221                     !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
1222                         s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
1223                         s->renegotiate = 1;
1224                         s->new_session = 1;
1225                 }
1226                 i = s->handshake_func(s);
1227                 if (i < 0)
1228                         return (i);
1229                 if (i == 0) {
1230                         SSLerr(SSL_F_SSL3_READ_BYTES,
1231                             SSL_R_SSL_HANDSHAKE_FAILURE);
1232                         return (-1);
1233                 }
1234
1235                 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1236                         if (s->s3->rbuf.left == 0) { /* no read-ahead left? */
1237                                 BIO *bio;
1238                                 /* In the case where we try to read application data,
1239                                  * but we trigger an SSL handshake, we return -1 with
1240                                  * the retry option set.  Otherwise renegotiation may
1241                                  * cause nasty problems in the blocking world */
1242                                 s->rwstate = SSL_READING;
1243                                 bio = SSL_get_rbio(s);
1244                                 BIO_clear_retry_flags(bio);
1245                                 BIO_set_retry_read(bio);
1246                                 return (-1);
1247                         }
1248                 }
1249                 goto start;
1250         }
1251
1252         switch (rr->type) {
1253         default:
1254                 /*
1255                  * TLS up to v1.1 just ignores unknown message types:
1256                  * TLS v1.2 give an unexpected message alert.
1257                  */
1258                 if (s->version >= TLS1_VERSION &&
1259                     s->version <= TLS1_1_VERSION) {
1260                         rr->length = 0;
1261                         goto start;
1262                 }
1263                 al = SSL_AD_UNEXPECTED_MESSAGE;
1264                 SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1265                 goto f_err;
1266         case SSL3_RT_CHANGE_CIPHER_SPEC:
1267         case SSL3_RT_ALERT:
1268         case SSL3_RT_HANDSHAKE:
1269                 /* we already handled all of these, with the possible exception
1270                  * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that
1271                  * should not happen when type != rr->type */
1272                 al = SSL_AD_UNEXPECTED_MESSAGE;
1273                 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
1274                 goto f_err;
1275         case SSL3_RT_APPLICATION_DATA:
1276                 /* At this point, we were expecting handshake data,
1277                  * but have application data.  If the library was
1278                  * running inside ssl3_read() (i.e. in_read_app_data
1279                  * is set) and it makes sense to read application data
1280                  * at this point (session renegotiation not yet started),
1281                  * we will indulge it.
1282                  */
1283                 if (s->s3->in_read_app_data &&
1284                     (s->s3->total_renegotiations != 0) &&
1285                     (((s->state & SSL_ST_CONNECT) &&
1286                     (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1287                     (s->state <= SSL3_ST_CR_SRVR_HELLO_A)) ||
1288                     ((s->state & SSL_ST_ACCEPT) &&
1289                     (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
1290                     (s->state >= SSL3_ST_SR_CLNT_HELLO_A)))) {
1291                         s->s3->in_read_app_data = 2;
1292                         return (-1);
1293                 } else {
1294                         al = SSL_AD_UNEXPECTED_MESSAGE;
1295                         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
1296                         goto f_err;
1297                 }
1298         }
1299         /* not reached */
1300
1301 f_err:
1302         ssl3_send_alert(s, SSL3_AL_FATAL, al);
1303 err:
1304         return (-1);
1305 }
1306
1307 int
1308 ssl3_do_change_cipher_spec(SSL *s)
1309 {
1310         int i;
1311         const char *sender;
1312         int slen;
1313
1314         if (s->state & SSL_ST_ACCEPT)
1315                 i = SSL3_CHANGE_CIPHER_SERVER_READ;
1316         else
1317                 i = SSL3_CHANGE_CIPHER_CLIENT_READ;
1318
1319         if (s->s3->tmp.key_block == NULL) {
1320                 if (s->session == NULL || s->session->master_key_length == 0) {
1321                         /* might happen if dtls1_read_bytes() calls this */
1322                         SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC,
1323                             SSL_R_CCS_RECEIVED_EARLY);
1324                         return (0);
1325                 }
1326
1327                 s->session->cipher = s->s3->tmp.new_cipher;
1328                 if (!s->method->ssl3_enc->setup_key_block(s))
1329                         return (0);
1330         }
1331
1332         if (!s->method->ssl3_enc->change_cipher_state(s, i))
1333                 return (0);
1334
1335         /* we have to record the message digest at
1336          * this point so we can get it before we read
1337          * the finished message */
1338         if (s->state & SSL_ST_CONNECT) {
1339                 sender = s->method->ssl3_enc->server_finished_label;
1340                 slen = s->method->ssl3_enc->server_finished_label_len;
1341         } else {
1342                 sender = s->method->ssl3_enc->client_finished_label;
1343                 slen = s->method->ssl3_enc->client_finished_label_len;
1344         }
1345
1346         i = s->method->ssl3_enc->final_finish_mac(s, sender, slen,
1347             s->s3->tmp.peer_finish_md);
1348         if (i == 0) {
1349                 SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC, ERR_R_INTERNAL_ERROR);
1350                 return 0;
1351         }
1352         s->s3->tmp.peer_finish_md_len = i;
1353
1354         return (1);
1355 }
1356
1357 int
1358 ssl3_send_alert(SSL *s, int level, int desc)
1359 {
1360         /* Map tls/ssl alert value to correct one */
1361         desc = s->method->ssl3_enc->alert_value(desc);
1362         if (desc < 0)
1363                 return -1;
1364         /* If a fatal one, remove from cache */
1365         if ((level == 2) && (s->session != NULL))
1366                 SSL_CTX_remove_session(s->ctx, s->session);
1367
1368         s->s3->alert_dispatch = 1;
1369         s->s3->send_alert[0] = level;
1370         s->s3->send_alert[1] = desc;
1371         if (s->s3->wbuf.left == 0) /* data still being written out? */
1372                 return s->method->ssl_dispatch_alert(s);
1373
1374         /* else data is still being written out, we will get written
1375          * some time in the future */
1376         return -1;
1377 }
1378
1379 int
1380 ssl3_dispatch_alert(SSL *s)
1381 {
1382         int i, j;
1383         void (*cb)(const SSL *ssl, int type, int val) = NULL;
1384
1385         s->s3->alert_dispatch = 0;
1386         i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0);
1387         if (i <= 0) {
1388                 s->s3->alert_dispatch = 1;
1389         } else {
1390                 /* Alert sent to BIO.  If it is important, flush it now.
1391                  * If the message does not get sent due to non-blocking IO,
1392                  * we will not worry too much. */
1393                 if (s->s3->send_alert[0] == SSL3_AL_FATAL)
1394                         (void)BIO_flush(s->wbio);
1395
1396                 if (s->msg_callback)
1397                         s->msg_callback(1, s->version, SSL3_RT_ALERT,
1398                             s->s3->send_alert, 2, s, s->msg_callback_arg);
1399
1400                 if (s->info_callback != NULL)
1401                         cb = s->info_callback;
1402                 else if (s->ctx->info_callback != NULL)
1403                         cb = s->ctx->info_callback;
1404
1405                 if (cb != NULL) {
1406                         j = (s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
1407                         cb(s, SSL_CB_WRITE_ALERT, j);
1408                 }
1409         }
1410         return (i);
1411 }