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