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