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