blob: c159e62d1204ee2e285015e6679ea3f89ba68f1d [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
678 if (wb->buf == NULL)
679 if (!ssl3_setup_write_buffer(s))
680 return -1;
681
682 /* first check if there is a SSL3_BUFFER still being written
683 * out. This will happen with non blocking IO */
684 if (wb->left != 0)
685 return(ssl3_write_pending(s,type,buf,len));
686
687 /* If we have an alert to send, lets send it */
688 if (s->s3->alert_dispatch)
689 {
690 i=s->method->ssl_dispatch_alert(s);
691 if (i <= 0)
692 return(i);
693 /* if it went, fall through and send more stuff */
694 }
695
Adam Langleyc6c8ae82014-06-20 12:00:00 -0700696 /* Dispatching the alert may have released the write buffer. */
697 if (wb->buf == NULL)
698 if (!ssl3_setup_write_buffer(s))
699 return -1;
700
Adam Langleyd493d522014-06-20 12:00:00 -0700701 if (len == 0)
Adam Langley95c29f32014-06-20 12:00:00 -0700702 return 0;
703
704 wr= &(s->s3->wrec);
705 sess=s->session;
706
707 if ( (sess == NULL) ||
708 (s->enc_write_ctx == NULL) ||
709 (EVP_MD_CTX_md(s->write_hash) == NULL))
710 {
Adam Langley95c29f32014-06-20 12:00:00 -0700711 mac_size=0;
712 }
713 else
714 {
715 mac_size=EVP_MD_CTX_size(s->write_hash);
716 if (mac_size < 0)
717 goto err;
718 }
719
Adam Langleyd493d522014-06-20 12:00:00 -0700720 if (fragment)
Adam Langley95c29f32014-06-20 12:00:00 -0700721 {
722 /* countermeasure against known-IV weakness in CBC ciphersuites
723 * (see http://www.openssl.org/~bodo/tls-cbc.txt) */
Adam Langleyd493d522014-06-20 12:00:00 -0700724 prefix_len = do_ssl3_write(s, type, buf, 1 /* length */,
725 0 /* fragment */,
726 1 /* is_fragment */);
727 if (prefix_len <= 0)
728 goto err;
Adam Langley95c29f32014-06-20 12:00:00 -0700729
Adam Langleyd493d522014-06-20 12:00:00 -0700730 if (prefix_len > (SSL3_RT_HEADER_LENGTH +
731 SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD))
Adam Langley95c29f32014-06-20 12:00:00 -0700732 {
Adam Langleyd493d522014-06-20 12:00:00 -0700733 /* insufficient space */
734 OPENSSL_PUT_ERROR(SSL, do_ssl3_write, ERR_R_INTERNAL_ERROR);
735 goto err;
Adam Langley95c29f32014-06-20 12:00:00 -0700736 }
Adam Langley95c29f32014-06-20 12:00:00 -0700737 }
738
Adam Langleyd493d522014-06-20 12:00:00 -0700739 if (is_fragment)
Adam Langley95c29f32014-06-20 12:00:00 -0700740 {
741#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
Adam Langleyd493d522014-06-20 12:00:00 -0700742 /* The extra fragment would be couple of cipher blocks, and
743 * that will be a multiple of SSL3_ALIGN_PAYLOAD. So, if we
744 * want to align the real payload, we can just pretend that we
745 * have two headers and a byte. */
746 align = (long)wb->buf + 2*SSL3_RT_HEADER_LENGTH + 1;
Adam Langley95c29f32014-06-20 12:00:00 -0700747 align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
748#endif
749 p = wb->buf + align;
750 wb->offset = align;
751 }
752 else if (prefix_len)
753 {
754 p = wb->buf + wb->offset + prefix_len;
755 }
756 else
757 {
758#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
759 align = (long)wb->buf + SSL3_RT_HEADER_LENGTH;
760 align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
761#endif
762 p = wb->buf + align;
763 wb->offset = align;
764 }
765
766 /* write the header */
767
768 *(p++)=type&0xff;
769 wr->type=type;
770
771 *(p++)=(s->version>>8);
772 /* Some servers hang if iniatial client hello is larger than 256
773 * bytes and record version number > TLS 1.0
774 */
775 if (s->state == SSL3_ST_CW_CLNT_HELLO_B
776 && !s->renegotiate
777 && TLS1_get_version(s) > TLS1_VERSION)
778 *(p++) = 0x1;
779 else
780 *(p++)=s->version&0xff;
781
782 /* field where we are to write out packet length */
Adam Langleyd493d522014-06-20 12:00:00 -0700783 plen=p;
Adam Langley95c29f32014-06-20 12:00:00 -0700784 p+=2;
785 /* Explicit IV length, block ciphers appropriate version flag */
786 if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s))
787 {
788 int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
789 if (mode == EVP_CIPH_CBC_MODE)
790 {
791 eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
792 if (eivlen <= 1)
793 eivlen = 0;
794 }
795 /* Need explicit part of IV for GCM mode */
796 else if (mode == EVP_CIPH_GCM_MODE)
797 eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
798 else
799 eivlen = 0;
800 }
Adam Langleyde0b2022014-06-20 12:00:00 -0700801 else if (s->aead_write_ctx != NULL &&
802 s->aead_write_ctx->variable_nonce_included_in_record)
803 {
Adam Langleyc9fb3752014-06-20 12:00:00 -0700804 eivlen = s->aead_write_ctx->variable_nonce_len;
Adam Langleyde0b2022014-06-20 12:00:00 -0700805 }
Adam Langleyc9fb3752014-06-20 12:00:00 -0700806 else
Adam Langley95c29f32014-06-20 12:00:00 -0700807 eivlen = 0;
808
809 /* lets setup the record stuff. */
810 wr->data=p + eivlen;
Adam Langleyd493d522014-06-20 12:00:00 -0700811 wr->length=(int)(len - (fragment != 0));
812 wr->input=(unsigned char *)buf + (fragment != 0);
Adam Langley95c29f32014-06-20 12:00:00 -0700813
814 /* we now 'read' from wr->input, wr->length bytes into
815 * wr->data */
816
817 /* first we compress */
818 if (s->compress != NULL)
819 {
820 if (!ssl3_do_compress(s))
821 {
822 OPENSSL_PUT_ERROR(SSL, do_ssl3_write, SSL_R_COMPRESSION_FAILURE);
823 goto err;
824 }
825 }
826 else
827 {
828 memcpy(wr->data,wr->input,wr->length);
829 wr->input=wr->data;
830 }
831
832 /* we should still have the output to wr->data and the input
833 * from wr->input. Length should be wr->length.
834 * wr->data still points in the wb->buf */
835
836 if (mac_size != 0)
837 {
838 if (s->method->ssl3_enc->mac(s,&(p[wr->length + eivlen]),1) < 0)
839 goto err;
840 wr->length+=mac_size;
841 }
842
843 wr->input=p;
844 wr->data=p;
845
846 if (eivlen)
847 {
848 /* if (RAND_pseudo_bytes(p, eivlen) <= 0)
849 goto err; */
850 wr->length += eivlen;
851 }
852
853 /* ssl3_enc can only have an error on read */
854 s->method->ssl3_enc->enc(s,1);
855
856 /* record length after mac and block padding */
857 s2n(wr->length,plen);
858
859 if (s->msg_callback)
860 s->msg_callback(1, 0, SSL3_RT_HEADER, plen - 5, 5, s, s->msg_callback_arg);
861
862 /* we should now have
863 * wr->data pointing to the encrypted data, which is
864 * wr->length long */
865 wr->type=type; /* not needed but helps for debugging */
866 wr->length+=SSL3_RT_HEADER_LENGTH;
867
Adam Langleyd493d522014-06-20 12:00:00 -0700868 if (is_fragment)
Adam Langley95c29f32014-06-20 12:00:00 -0700869 {
Adam Langleyd493d522014-06-20 12:00:00 -0700870 /* we are in a recursive call; just return the length, don't
871 * write out anything. */
Adam Langley95c29f32014-06-20 12:00:00 -0700872 return wr->length;
873 }
874
875 /* now let's set up wb */
876 wb->left = prefix_len + wr->length;
877
878 /* memorize arguments so that ssl3_write_pending can detect bad write retries later */
879 s->s3->wpend_tot=len;
880 s->s3->wpend_buf=buf;
881 s->s3->wpend_type=type;
882 s->s3->wpend_ret=len;
883
884 /* we now just need to write the buffer */
885 return ssl3_write_pending(s,type,buf,len);
886err:
887 return -1;
888 }
889
890/* if s->s3->wbuf.left != 0, we need to call this */
891int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
892 unsigned int len)
893 {
894 int i;
895 SSL3_BUFFER *wb=&(s->s3->wbuf);
896
897/* XXXX */
898 if ((s->s3->wpend_tot > (int)len)
899 || ((s->s3->wpend_buf != buf) &&
900 !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
901 || (s->s3->wpend_type != type))
902 {
903 OPENSSL_PUT_ERROR(SSL, ssl3_write_pending, SSL_R_BAD_WRITE_RETRY);
904 return(-1);
905 }
906
907 for (;;)
908 {
909 ERR_clear_system_error();
910 if (s->wbio != NULL)
911 {
912 s->rwstate=SSL_WRITING;
913 i=BIO_write(s->wbio,
914 (char *)&(wb->buf[wb->offset]),
915 (unsigned int)wb->left);
916 }
917 else
918 {
919 OPENSSL_PUT_ERROR(SSL, ssl3_write_pending, SSL_R_BIO_NOT_SET);
920 i= -1;
921 }
922 if (i == wb->left)
923 {
924 wb->left=0;
925 wb->offset+=i;
926 if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
927 !SSL_IS_DTLS(s))
928 ssl3_release_write_buffer(s);
929 s->rwstate=SSL_NOTHING;
930 return(s->s3->wpend_ret);
931 }
932 else if (i <= 0) {
933 if (s->version == DTLS1_VERSION ||
934 s->version == DTLS1_BAD_VER) {
935 /* For DTLS, just drop it. That's kind of the whole
936 point in using a datagram service */
937 wb->left = 0;
938 }
939 return(i);
940 }
941 wb->offset+=i;
942 wb->left-=i;
943 }
944 }
945
946/* Return up to 'len' payload bytes received in 'type' records.
947 * 'type' is one of the following:
948 *
949 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
950 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
951 * - 0 (during a shutdown, no data has to be returned)
952 *
953 * If we don't have stored data to work from, read a SSL/TLS record first
954 * (possibly multiple records if we still don't have anything to return).
955 *
956 * This function must handle any surprises the peer may have for us, such as
957 * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
958 * a surprise, but handled as if it were), or renegotiation requests.
959 * Also if record payloads contain fragments too small to process, we store
960 * them until there is enough for the respective protocol (the record protocol
961 * may use arbitrary fragmentation and even interleaving):
962 * Change cipher spec protocol
963 * just 1 byte needed, no need for keeping anything stored
964 * Alert protocol
965 * 2 bytes needed (AlertLevel, AlertDescription)
966 * Handshake protocol
967 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
968 * to detect unexpected Client Hello and Hello Request messages
969 * here, anything else is handled by higher layers
970 * Application data protocol
971 * none of our business
972 */
973int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
974 {
975 int al,i,j,ret;
976 unsigned int n;
977 SSL3_RECORD *rr;
978 void (*cb)(const SSL *ssl,int type2,int val)=NULL;
979
980 if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
981 if (!ssl3_setup_read_buffer(s))
982 return(-1);
983
984 if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE) && type) ||
985 (peek && (type != SSL3_RT_APPLICATION_DATA)))
986 {
987 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, ERR_R_INTERNAL_ERROR);
988 return -1;
989 }
990
991 if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0))
992 /* (partially) satisfy request from storage */
993 {
994 unsigned char *src = s->s3->handshake_fragment;
995 unsigned char *dst = buf;
996 unsigned int k;
997
998 /* peek == 0 */
999 n = 0;
1000 while ((len > 0) && (s->s3->handshake_fragment_len > 0))
1001 {
1002 *dst++ = *src++;
1003 len--; s->s3->handshake_fragment_len--;
1004 n++;
1005 }
1006 /* move any remaining fragment bytes: */
1007 for (k = 0; k < s->s3->handshake_fragment_len; k++)
1008 s->s3->handshake_fragment[k] = *src++;
1009 return n;
1010 }
1011
1012 /* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
1013
1014 if (!s->in_handshake && SSL_in_init(s))
1015 {
1016 /* type == SSL3_RT_APPLICATION_DATA */
1017 i=s->handshake_func(s);
1018 if (i < 0) return(i);
1019 if (i == 0)
1020 {
1021 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
1022 return(-1);
1023 }
1024 }
1025start:
1026 s->rwstate=SSL_NOTHING;
1027
1028 /* s->s3->rrec.type - is the type of record
1029 * s->s3->rrec.data, - data
1030 * s->s3->rrec.off, - offset into 'data' for next read
1031 * s->s3->rrec.length, - number of bytes. */
1032 rr = &(s->s3->rrec);
1033
1034 /* get new packet if necessary */
1035 if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))
1036 {
1037 ret=ssl3_get_record(s);
1038 if (ret <= 0) return(ret);
1039 }
1040
1041 /* we now have a packet which can be read and processed */
1042
1043 if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
1044 * reset by ssl3_get_finished */
1045 && (rr->type != SSL3_RT_HANDSHAKE))
1046 {
1047 al=SSL_AD_UNEXPECTED_MESSAGE;
1048 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1049 goto f_err;
1050 }
1051
1052 /* If the other end has shut down, throw anything we read away
1053 * (even in 'peek' mode) */
1054 if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
1055 {
1056 rr->length=0;
1057 s->rwstate=SSL_NOTHING;
1058 return(0);
1059 }
1060
1061
1062 if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
1063 {
1064 /* make sure that we are not getting application data when we
1065 * are doing a handshake for the first time */
1066 if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
1067 (s->enc_read_ctx == NULL))
1068 {
1069 al=SSL_AD_UNEXPECTED_MESSAGE;
1070 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_APP_DATA_IN_HANDSHAKE);
1071 goto f_err;
1072 }
1073
1074 if (len <= 0) return(len);
1075
1076 if ((unsigned int)len > rr->length)
1077 n = rr->length;
1078 else
1079 n = (unsigned int)len;
1080
1081 memcpy(buf,&(rr->data[rr->off]),n);
1082 if (!peek)
1083 {
1084 rr->length-=n;
1085 rr->off+=n;
1086 if (rr->length == 0)
1087 {
1088 s->rstate=SSL_ST_READ_HEADER;
1089 rr->off=0;
Adam Langley4a35a932014-06-20 12:00:00 -07001090 if (s->mode & SSL_MODE_RELEASE_BUFFERS && s->s3->rbuf.left == 0)
Adam Langley95c29f32014-06-20 12:00:00 -07001091 ssl3_release_read_buffer(s);
1092 }
1093 }
1094 return(n);
1095 }
1096
1097
1098 /* If we get here, then type != rr->type; if we have a handshake
1099 * message, then it was unexpected (Hello Request or Client Hello). */
1100
1101 /* In case of record types for which we have 'fragment' storage,
1102 * fill that so that we can process the data at a fixed place.
1103 */
1104 {
1105 unsigned int dest_maxlen = 0;
1106 unsigned char *dest = NULL;
1107 unsigned int *dest_len = NULL;
1108
1109 if (rr->type == SSL3_RT_HANDSHAKE)
1110 {
1111 dest_maxlen = sizeof s->s3->handshake_fragment;
1112 dest = s->s3->handshake_fragment;
1113 dest_len = &s->s3->handshake_fragment_len;
1114 }
1115 else if (rr->type == SSL3_RT_ALERT)
1116 {
1117 dest_maxlen = sizeof s->s3->alert_fragment;
1118 dest = s->s3->alert_fragment;
1119 dest_len = &s->s3->alert_fragment_len;
1120 }
1121#ifndef OPENSSL_NO_HEARTBEATS
1122 else if (rr->type == TLS1_RT_HEARTBEAT)
1123 {
1124 tls1_process_heartbeat(s);
1125
1126 /* Exit and notify application to read again */
1127 rr->length = 0;
1128 s->rwstate=SSL_READING;
1129 BIO_clear_retry_flags(SSL_get_rbio(s));
1130 BIO_set_retry_read(SSL_get_rbio(s));
1131 return(-1);
1132 }
1133#endif
1134
1135 if (dest_maxlen > 0)
1136 {
1137 n = dest_maxlen - *dest_len; /* available space in 'dest' */
1138 if (rr->length < n)
1139 n = rr->length; /* available bytes */
1140
1141 /* now move 'n' bytes: */
1142 while (n-- > 0)
1143 {
1144 dest[(*dest_len)++] = rr->data[rr->off++];
1145 rr->length--;
1146 }
1147
1148 if (*dest_len < dest_maxlen)
1149 goto start; /* fragment was too small */
1150 }
1151 }
1152
1153 /* s->s3->handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
1154 * s->s3->alert_fragment_len == 2 iff rr->type == SSL3_RT_ALERT.
1155 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
1156
1157 /* If we are a client, check for an incoming 'Hello Request': */
1158 if ((!s->server) &&
1159 (s->s3->handshake_fragment_len >= 4) &&
1160 (s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
1161 (s->session != NULL) && (s->session->cipher != NULL))
1162 {
1163 s->s3->handshake_fragment_len = 0;
1164
1165 if ((s->s3->handshake_fragment[1] != 0) ||
1166 (s->s3->handshake_fragment[2] != 0) ||
1167 (s->s3->handshake_fragment[3] != 0))
1168 {
1169 al=SSL_AD_DECODE_ERROR;
1170 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_HELLO_REQUEST);
1171 goto f_err;
1172 }
1173
1174 if (s->msg_callback)
1175 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->s3->handshake_fragment, 4, s, s->msg_callback_arg);
1176
1177 if (SSL_is_init_finished(s) &&
1178 !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
1179 !s->s3->renegotiate)
1180 {
1181 ssl3_renegotiate(s);
1182 if (ssl3_renegotiate_check(s))
1183 {
1184 i=s->handshake_func(s);
1185 if (i < 0) return(i);
1186 if (i == 0)
1187 {
1188 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
1189 return(-1);
1190 }
1191
1192 if (!(s->mode & SSL_MODE_AUTO_RETRY))
1193 {
1194 if (s->s3->rbuf.left == 0) /* no read-ahead left? */
1195 {
1196 BIO *bio;
1197 /* In the case where we try to read application data,
1198 * but we trigger an SSL handshake, we return -1 with
1199 * the retry option set. Otherwise renegotiation may
1200 * cause nasty problems in the blocking world */
1201 s->rwstate=SSL_READING;
1202 bio=SSL_get_rbio(s);
1203 BIO_clear_retry_flags(bio);
1204 BIO_set_retry_read(bio);
1205 return(-1);
1206 }
1207 }
1208 }
1209 }
1210 /* we either finished a handshake or ignored the request,
1211 * now try again to obtain the (application) data we were asked for */
1212 goto start;
1213 }
1214 /* If we are a server and get a client hello when renegotiation isn't
1215 * allowed send back a no renegotiation alert and carry on.
1216 * WARNING: experimental code, needs reviewing (steve)
1217 */
1218 if (s->server &&
1219 SSL_is_init_finished(s) &&
1220 !s->s3->send_connection_binding &&
1221 (s->version > SSL3_VERSION) &&
1222 (s->s3->handshake_fragment_len >= 4) &&
1223 (s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
1224 (s->session != NULL) && (s->session->cipher != NULL) &&
1225 !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
1226
1227 {
1228 /*s->s3->handshake_fragment_len = 0;*/
1229 rr->length = 0;
1230 ssl3_send_alert(s,SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1231 goto start;
1232 }
1233 if (s->s3->alert_fragment_len >= 2)
1234 {
1235 int alert_level = s->s3->alert_fragment[0];
1236 int alert_descr = s->s3->alert_fragment[1];
1237
1238 s->s3->alert_fragment_len = 0;
1239
1240 if (s->msg_callback)
1241 s->msg_callback(0, s->version, SSL3_RT_ALERT, s->s3->alert_fragment, 2, s, s->msg_callback_arg);
1242
1243 if (s->info_callback != NULL)
1244 cb=s->info_callback;
1245 else if (s->ctx->info_callback != NULL)
1246 cb=s->ctx->info_callback;
1247
1248 if (cb != NULL)
1249 {
1250 j = (alert_level << 8) | alert_descr;
1251 cb(s, SSL_CB_READ_ALERT, j);
1252 }
1253
1254 if (alert_level == 1) /* warning */
1255 {
1256 s->s3->warn_alert = alert_descr;
1257 if (alert_descr == SSL_AD_CLOSE_NOTIFY)
1258 {
1259 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1260 return(0);
1261 }
1262 /* This is a warning but we receive it if we requested
1263 * renegotiation and the peer denied it. Terminate with
1264 * a fatal alert because if application tried to
1265 * renegotiatie it presumably had a good reason and
1266 * expects it to succeed.
1267 *
1268 * In future we might have a renegotiation where we
1269 * don't care if the peer refused it where we carry on.
1270 */
1271 else if (alert_descr == SSL_AD_NO_RENEGOTIATION)
1272 {
1273 al = SSL_AD_HANDSHAKE_FAILURE;
1274 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_NO_RENEGOTIATION);
1275 goto f_err;
1276 }
1277#ifdef SSL_AD_MISSING_SRP_USERNAME
1278 else if (alert_descr == SSL_AD_MISSING_SRP_USERNAME)
1279 return(0);
1280#endif
1281 }
1282 else if (alert_level == 2) /* fatal */
1283 {
1284 char tmp[16];
1285
1286 s->rwstate=SSL_NOTHING;
1287 s->s3->fatal_alert = alert_descr;
1288 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_AD_REASON_OFFSET + alert_descr);
1289 BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr);
1290 ERR_add_error_data(2,"SSL alert number ",tmp);
1291 s->shutdown|=SSL_RECEIVED_SHUTDOWN;
1292 SSL_CTX_remove_session(s->ctx,s->session);
1293 return(0);
1294 }
1295 else
1296 {
1297 al=SSL_AD_ILLEGAL_PARAMETER;
1298 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNKNOWN_ALERT_TYPE);
1299 goto f_err;
1300 }
1301
1302 goto start;
1303 }
1304
1305 if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
1306 {
1307 s->rwstate=SSL_NOTHING;
1308 rr->length=0;
1309 return(0);
1310 }
1311
1312 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
1313 {
1314 /* 'Change Cipher Spec' is just a single byte, so we know
1315 * exactly what the record payload has to look like */
1316 if ( (rr->length != 1) || (rr->off != 0) ||
1317 (rr->data[0] != SSL3_MT_CCS))
1318 {
1319 al=SSL_AD_ILLEGAL_PARAMETER;
1320 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_CHANGE_CIPHER_SPEC);
1321 goto f_err;
1322 }
1323
1324 /* Check we have a cipher to change to */
1325 if (s->s3->tmp.new_cipher == NULL)
1326 {
1327 al=SSL_AD_UNEXPECTED_MESSAGE;
1328 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_CCS_RECEIVED_EARLY);
1329 goto f_err;
1330 }
1331
1332 rr->length=0;
1333
1334 if (s->msg_callback)
1335 s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg);
1336
1337 s->s3->change_cipher_spec=1;
1338 if (!ssl3_do_change_cipher_spec(s))
1339 goto err;
1340 else
1341 goto start;
1342 }
1343
1344 /* Unexpected handshake message (Client Hello, or protocol violation) */
1345 if ((s->s3->handshake_fragment_len >= 4) && !s->in_handshake)
1346 {
1347 if (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&
1348 !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS))
1349 {
1350#if 0 /* worked only because C operator preferences are not as expected (and
1351 * because this is not really needed for clients except for detecting
1352 * protocol violations): */
1353 s->state=SSL_ST_BEFORE|(s->server)
1354 ?SSL_ST_ACCEPT
1355 :SSL_ST_CONNECT;
1356#else
1357 s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
1358#endif
1359 s->renegotiate=1;
1360 s->new_session=1;
1361 }
1362 i=s->handshake_func(s);
1363 if (i < 0) return(i);
1364 if (i == 0)
1365 {
1366 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
1367 return(-1);
1368 }
1369
1370 if (!(s->mode & SSL_MODE_AUTO_RETRY))
1371 {
1372 if (s->s3->rbuf.left == 0) /* no read-ahead left? */
1373 {
1374 BIO *bio;
1375 /* In the case where we try to read application data,
1376 * but we trigger an SSL handshake, we return -1 with
1377 * the retry option set. Otherwise renegotiation may
1378 * cause nasty problems in the blocking world */
1379 s->rwstate=SSL_READING;
1380 bio=SSL_get_rbio(s);
1381 BIO_clear_retry_flags(bio);
1382 BIO_set_retry_read(bio);
1383 return(-1);
1384 }
1385 }
1386 goto start;
1387 }
1388
1389 switch (rr->type)
1390 {
1391 default:
1392#ifndef OPENSSL_NO_TLS
1393 /* TLS up to v1.1 just ignores unknown message types:
1394 * TLS v1.2 give an unexpected message alert.
1395 */
1396 if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION)
1397 {
1398 rr->length = 0;
1399 goto start;
1400 }
1401#endif
1402 al=SSL_AD_UNEXPECTED_MESSAGE;
1403 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNEXPECTED_RECORD);
1404 goto f_err;
1405 case SSL3_RT_CHANGE_CIPHER_SPEC:
1406 case SSL3_RT_ALERT:
1407 case SSL3_RT_HANDSHAKE:
1408 /* we already handled all of these, with the possible exception
1409 * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that
1410 * should not happen when type != rr->type */
1411 al=SSL_AD_UNEXPECTED_MESSAGE;
1412 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, ERR_R_INTERNAL_ERROR);
1413 goto f_err;
1414 case SSL3_RT_APPLICATION_DATA:
1415 /* At this point, we were expecting handshake data,
1416 * but have application data. If the library was
1417 * running inside ssl3_read() (i.e. in_read_app_data
1418 * is set) and it makes sense to read application data
1419 * at this point (session renegotiation not yet started),
1420 * we will indulge it.
1421 */
1422 if (s->s3->in_read_app_data &&
1423 (s->s3->total_renegotiations != 0) &&
1424 ((
1425 (s->state & SSL_ST_CONNECT) &&
1426 (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1427 (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
1428 ) || (
1429 (s->state & SSL_ST_ACCEPT) &&
1430 (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
1431 (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
1432 )
1433 ))
1434 {
1435 s->s3->in_read_app_data=2;
1436 return(-1);
1437 }
1438 else
1439 {
1440 al=SSL_AD_UNEXPECTED_MESSAGE;
1441 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNEXPECTED_RECORD);
1442 goto f_err;
1443 }
1444 }
1445 /* not reached */
1446
1447f_err:
1448 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1449err:
1450 return(-1);
1451 }
1452
1453int ssl3_do_change_cipher_spec(SSL *s)
1454 {
1455 int i;
1456 const char *sender;
1457 int slen;
1458
1459 if (s->state & SSL_ST_ACCEPT)
1460 i=SSL3_CHANGE_CIPHER_SERVER_READ;
1461 else
1462 i=SSL3_CHANGE_CIPHER_CLIENT_READ;
1463
1464 if (s->s3->tmp.key_block == NULL)
1465 {
1466 if (s->session == NULL)
1467 {
1468 /* might happen if dtls1_read_bytes() calls this */
1469 OPENSSL_PUT_ERROR(SSL, ssl3_do_change_cipher_spec, SSL_R_CCS_RECEIVED_EARLY);
1470 return (0);
1471 }
1472
1473 s->session->cipher=s->s3->tmp.new_cipher;
1474 if (!s->method->ssl3_enc->setup_key_block(s)) return(0);
1475 }
1476
1477 if (!s->method->ssl3_enc->change_cipher_state(s,i))
1478 return(0);
1479
1480 /* we have to record the message digest at
1481 * this point so we can get it before we read
1482 * the finished message */
1483 if (s->state & SSL_ST_CONNECT)
1484 {
1485 sender=s->method->ssl3_enc->server_finished_label;
1486 slen=s->method->ssl3_enc->server_finished_label_len;
1487 }
1488 else
1489 {
1490 sender=s->method->ssl3_enc->client_finished_label;
1491 slen=s->method->ssl3_enc->client_finished_label_len;
1492 }
1493
1494 i = s->method->ssl3_enc->final_finish_mac(s,
1495 sender,slen,s->s3->tmp.peer_finish_md);
1496 if (i == 0)
1497 {
1498 OPENSSL_PUT_ERROR(SSL, ssl3_do_change_cipher_spec, ERR_R_INTERNAL_ERROR);
1499 return 0;
1500 }
1501 s->s3->tmp.peer_finish_md_len = i;
1502
1503 return(1);
1504 }
1505
1506int ssl3_send_alert(SSL *s, int level, int desc)
1507 {
1508 /* Map tls/ssl alert value to correct one */
1509 desc=s->method->ssl3_enc->alert_value(desc);
1510 if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
1511 desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have protocol_version alerts */
1512 if (desc < 0) return -1;
1513 /* If a fatal one, remove from cache */
1514 if ((level == 2) && (s->session != NULL))
1515 SSL_CTX_remove_session(s->ctx,s->session);
1516
1517 s->s3->alert_dispatch=1;
1518 s->s3->send_alert[0]=level;
1519 s->s3->send_alert[1]=desc;
1520 if (s->s3->wbuf.left == 0) /* data still being written out? */
1521 return s->method->ssl_dispatch_alert(s);
1522 /* else data is still being written out, we will get written
1523 * some time in the future */
1524 return -1;
1525 }
1526
1527int ssl3_dispatch_alert(SSL *s)
1528 {
1529 int i,j;
1530 void (*cb)(const SSL *ssl,int type,int val)=NULL;
1531
1532 s->s3->alert_dispatch=0;
Adam Langleyd493d522014-06-20 12:00:00 -07001533 i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0, 0);
Adam Langley95c29f32014-06-20 12:00:00 -07001534 if (i <= 0)
1535 {
1536 s->s3->alert_dispatch=1;
1537 }
1538 else
1539 {
1540 /* Alert sent to BIO. If it is important, flush it now.
1541 * If the message does not get sent due to non-blocking IO,
1542 * we will not worry too much. */
1543 if (s->s3->send_alert[0] == SSL3_AL_FATAL)
1544 (void)BIO_flush(s->wbio);
1545
1546 if (s->msg_callback)
1547 s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s, s->msg_callback_arg);
1548
1549 if (s->info_callback != NULL)
1550 cb=s->info_callback;
1551 else if (s->ctx->info_callback != NULL)
1552 cb=s->ctx->info_callback;
1553
1554 if (cb != NULL)
1555 {
1556 j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
1557 cb(s,SSL_CB_WRITE_ALERT,j);
1558 }
1559 }
1560 return(i);
1561 }