blob: 3ccb0a0d4f495f34d727eeca53be87fa88f71834 [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>
Adam Langley87750b42014-06-20 12:00:00 -0700111#include <limits.h>
Adam Langley95c29f32014-06-20 12:00:00 -0700112#include <stdio.h>
113
114#include <openssl/buf.h>
115#include <openssl/err.h>
116#include <openssl/evp.h>
117#include <openssl/mem.h>
118#include <openssl/rand.h>
119
120#include "ssl_locl.h"
121
122static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
Adam Langleyd493d522014-06-20 12:00:00 -0700123 unsigned int len, char fragment, char is_fragment);
Adam Langley95c29f32014-06-20 12:00:00 -0700124static int ssl3_get_record(SSL *s);
125
126int ssl3_read_n(SSL *s, int n, int max, int extend)
127 {
128 /* If extend == 0, obtain new n-byte packet; if extend == 1, increase
129 * packet by another n bytes.
130 * The packet will be in the sub-array of s->s3->rbuf.buf specified
131 * by s->packet and s->packet_length.
132 * (If s->read_ahead is set, 'max' bytes may be stored in rbuf
133 * [plus s->packet_length bytes if extend == 1].)
134 */
135 int i,len,left;
136 long align=0;
137 unsigned char *pkt;
138 SSL3_BUFFER *rb;
139
140 if (n <= 0) return n;
141
142 rb = &(s->s3->rbuf);
143 if (rb->buf == NULL)
144 if (!ssl3_setup_read_buffer(s))
145 return -1;
146
147 left = rb->left;
148#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
149 align = (long)rb->buf + SSL3_RT_HEADER_LENGTH;
150 align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
151#endif
152
153 if (!extend)
154 {
155 /* start with empty packet ... */
156 if (left == 0)
157 rb->offset = align;
158 else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH)
159 {
160 /* check if next packet length is large
161 * enough to justify payload alignment... */
162 pkt = rb->buf + rb->offset;
163 if (pkt[0] == SSL3_RT_APPLICATION_DATA
164 && (pkt[3]<<8|pkt[4]) >= 128)
165 {
166 /* Note that even if packet is corrupted
167 * and its length field is insane, we can
168 * only be led to wrong decision about
169 * whether memmove will occur or not.
170 * Header values has no effect on memmove
171 * arguments and therefore no buffer
172 * overrun can be triggered. */
173 memmove (rb->buf+align,pkt,left);
174 rb->offset = align;
175 }
176 }
177 s->packet = rb->buf + rb->offset;
178 s->packet_length = 0;
179 /* ... now we can act as if 'extend' was set */
180 }
181
182 /* For DTLS/UDP reads should not span multiple packets
183 * because the read operation returns the whole packet
184 * at once (as long as it fits into the buffer). */
185 if (SSL_IS_DTLS(s))
186 {
187 if (left > 0 && n > left)
188 n = left;
189 }
190
191 /* if there is enough in the buffer from a previous read, take some */
192 if (left >= n)
193 {
194 s->packet_length+=n;
195 rb->left=left-n;
196 rb->offset+=n;
197 return(n);
198 }
199
200 /* else we need to read more data */
201
202 len = s->packet_length;
203 pkt = rb->buf+align;
204 /* Move any available bytes to front of buffer:
205 * 'len' bytes already pointed to by 'packet',
206 * 'left' extra ones at the end */
207 if (s->packet != pkt) /* len > 0 */
208 {
209 memmove(pkt, s->packet, len+left);
210 s->packet = pkt;
211 rb->offset = len + align;
212 }
213
214 if (n > (int)(rb->len - rb->offset)) /* does not happen */
215 {
216 OPENSSL_PUT_ERROR(SSL, ssl3_read_n, ERR_R_INTERNAL_ERROR);
217 return -1;
218 }
219
220 if (!s->read_ahead)
221 /* ignore max parameter */
222 max = n;
223 else
224 {
225 if (max < n)
226 max = n;
227 if (max > (int)(rb->len - rb->offset))
228 max = rb->len - rb->offset;
229 }
230
231 while (left < n)
232 {
233 /* Now we have len+left bytes at the front of s->s3->rbuf.buf
234 * and need to read in more until we have len+n (up to
235 * len+max if possible) */
236
237 ERR_clear_system_error();
238 if (s->rbio != NULL)
239 {
240 s->rwstate=SSL_READING;
241 i=BIO_read(s->rbio,pkt+len+left, max-left);
242 }
243 else
244 {
245 OPENSSL_PUT_ERROR(SSL, ssl3_read_n, SSL_R_READ_BIO_NOT_SET);
246 i = -1;
247 }
248
249 if (i <= 0)
250 {
251 rb->left = left;
252 if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
253 !SSL_IS_DTLS(s))
254 if (len+left == 0)
255 ssl3_release_read_buffer(s);
256 return(i);
257 }
258 left+=i;
259 /* reads should *never* span multiple packets for DTLS because
260 * the underlying transport protocol is message oriented as opposed
261 * to byte oriented as in the TLS case. */
262 if (SSL_IS_DTLS(s))
263 {
264 if (n > left)
265 n = left; /* makes the while condition false */
266 }
267 }
268
269 /* done reading, now the book-keeping */
270 rb->offset += n;
271 rb->left = left - n;
272 s->packet_length += n;
273 s->rwstate=SSL_NOTHING;
274 return(n);
275 }
276
Adam Langley48105fa2014-06-20 12:00:00 -0700277/* MAX_EMPTY_RECORDS defines the number of consecutive, empty records that will
278 * be processed per call to ssl3_get_record. Without this limit an attacker
279 * could send empty records at a faster rate than we can process and cause
280 * ssl3_get_record to loop forever. */
281#define MAX_EMPTY_RECORDS 32
282
Adam Langley95c29f32014-06-20 12:00:00 -0700283/* Call this to get a new input record.
284 * It will return <= 0 if more data is needed, normally due to an error
285 * or non-blocking IO.
286 * When it finishes, one packet has been decoded and can be found in
287 * ssl->s3->rrec.type - is the type of record
288 * ssl->s3->rrec.data, - data
289 * ssl->s3->rrec.length, - number of bytes
290 */
291/* used only by ssl3_read_bytes */
292static int ssl3_get_record(SSL *s)
293 {
294 int ssl_major,ssl_minor,al;
295 int enc_err,n,i,ret= -1;
296 SSL3_RECORD *rr;
297 SSL_SESSION *sess;
298 unsigned char *p;
299 unsigned char md[EVP_MAX_MD_SIZE];
300 short version;
301 unsigned mac_size, orig_len;
302 size_t extra;
Adam Langley48105fa2014-06-20 12:00:00 -0700303 unsigned empty_record_count = 0;
Adam Langley95c29f32014-06-20 12:00:00 -0700304
305 rr= &(s->s3->rrec);
306 sess=s->session;
307
308 if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)
309 extra=SSL3_RT_MAX_EXTRA;
310 else
311 extra=0;
312 if (extra && !s->s3->init_extra)
313 {
David Benjaminc92c2d72014-08-30 22:14:20 -0400314 /* An application error: SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER
Adam Langley95c29f32014-06-20 12:00:00 -0700315 * set after ssl3_setup_buffers() was done */
316 OPENSSL_PUT_ERROR(SSL, ssl3_get_record, ERR_R_INTERNAL_ERROR);
317 return -1;
318 }
319
320again:
321 /* check if we have the header */
322 if ( (s->rstate != SSL_ST_READ_BODY) ||
323 (s->packet_length < SSL3_RT_HEADER_LENGTH))
324 {
325 n=ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
326 if (n <= 0) return(n); /* error or non-blocking */
327 s->rstate=SSL_ST_READ_BODY;
328
329 p=s->packet;
330 if (s->msg_callback)
331 s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s, s->msg_callback_arg);
332
333 /* Pull apart the header into the SSL3_RECORD */
334 rr->type= *(p++);
335 ssl_major= *(p++);
336 ssl_minor= *(p++);
337 version=(ssl_major<<8)|ssl_minor;
338 n2s(p,rr->length);
339#if 0
340fprintf(stderr, "Record type=%d, Length=%d\n", rr->type, rr->length);
341#endif
342
343 /* Lets check version */
344 if (!s->first_packet)
345 {
346 if (version != s->version)
347 {
348 OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_WRONG_VERSION_NUMBER);
349 if ((s->version & 0xFF00) == (version & 0xFF00) && !s->enc_write_ctx && !s->write_hash)
350 /* Send back error using their minor version number :-) */
351 s->version = (unsigned short)version;
352 al=SSL_AD_PROTOCOL_VERSION;
353 goto f_err;
354 }
355 }
356
357 if ((version>>8) != SSL3_VERSION_MAJOR)
358 {
359 OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_WRONG_VERSION_NUMBER);
360 goto err;
361 }
362
363 if (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH)
364 {
365 al=SSL_AD_RECORD_OVERFLOW;
366 OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_PACKET_LENGTH_TOO_LONG);
367 goto f_err;
368 }
369
370 /* now s->rstate == SSL_ST_READ_BODY */
371 }
372
373 /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
374
375 if (rr->length > s->packet_length-SSL3_RT_HEADER_LENGTH)
376 {
377 /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
378 i=rr->length;
379 n=ssl3_read_n(s,i,i,1);
380 if (n <= 0) return(n); /* error or non-blocking io */
381 /* now n == rr->length,
382 * and s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length */
383 }
384
385 s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
386
387 /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
388 * and we have that many bytes in s->packet
389 */
390 rr->input= &(s->packet[SSL3_RT_HEADER_LENGTH]);
391
392 /* ok, we can now read from 's->packet' data into 'rr'
393 * rr->input points at rr->length bytes, which
394 * need to be copied into rr->data by either
395 * the decryption or by the decompression
396 * When the data is 'copied' into the rr->data buffer,
397 * rr->input will be pointed at the new buffer */
398
399 /* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
400 * rr->length bytes of encrypted compressed stuff. */
401
402 /* check is not needed I believe */
403 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH+extra)
404 {
405 al=SSL_AD_RECORD_OVERFLOW;
406 OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
407 goto f_err;
408 }
409
410 /* decrypt in place in 'rr->input' */
411 rr->data=rr->input;
412
413 enc_err = s->method->ssl3_enc->enc(s,0);
414 /* enc_err is:
415 * 0: (in non-constant time) if the record is publically invalid.
416 * 1: if the padding is valid
417 * -1: if the padding is invalid */
418 if (enc_err == 0)
419 {
420 al=SSL_AD_DECRYPTION_FAILED;
421 OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
422 goto f_err;
423 }
424
425#ifdef TLS_DEBUG
426printf("dec %d\n",rr->length);
427{ unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); }
428printf("\n");
429#endif
430
431 /* r->length is now the compressed data plus mac */
432 if ((sess != NULL) &&
433 (s->enc_read_ctx != NULL) &&
434 (EVP_MD_CTX_md(s->read_hash) != NULL))
435 {
436 /* s->read_hash != NULL => mac_size != -1 */
437 unsigned char *mac = NULL;
438 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
439 mac_size=EVP_MD_CTX_size(s->read_hash);
440 assert(mac_size <= EVP_MAX_MD_SIZE);
441
442 /* kludge: *_cbc_remove_padding passes padding length in rr->type */
443 orig_len = rr->length+((unsigned int)rr->type>>8);
444
445 /* orig_len is the length of the record before any padding was
446 * removed. This is public information, as is the MAC in use,
447 * therefore we can safely process the record in a different
448 * amount of time if it's too short to possibly contain a MAC.
449 */
450 if (orig_len < mac_size ||
451 /* CBC records must have a padding length byte too. */
452 (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
453 orig_len < mac_size+1))
454 {
455 al=SSL_AD_DECODE_ERROR;
456 OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_LENGTH_TOO_SHORT);
457 goto f_err;
458 }
459
460 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE)
461 {
462 /* We update the length so that the TLS header bytes
463 * can be constructed correctly but we need to extract
464 * the MAC in constant time from within the record,
465 * without leaking the contents of the padding bytes.
466 * */
467 mac = mac_tmp;
468 ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len);
469 rr->length -= mac_size;
470 }
471 else
472 {
473 /* In this case there's no padding, so |orig_len|
474 * equals |rec->length| and we checked that there's
475 * enough bytes for |mac_size| above. */
476 rr->length -= mac_size;
477 mac = &rr->data[rr->length];
478 }
479
480 i=s->method->ssl3_enc->mac(s,md,0 /* not send */);
481 if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
482 enc_err = -1;
483 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra+mac_size)
484 enc_err = -1;
485 }
486
487 if (enc_err < 0)
488 {
489 /* A separate 'decryption_failed' alert was introduced with TLS 1.0,
490 * SSL 3.0 only has 'bad_record_mac'. But unless a decryption
491 * failure is directly visible from the ciphertext anyway,
492 * we should not reveal which kind of error occured -- this
493 * might become visible to an attacker (e.g. via a logfile) */
494 al=SSL_AD_BAD_RECORD_MAC;
495 OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
496 goto f_err;
497 }
498
Adam Langley95c29f32014-06-20 12:00:00 -0700499 if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH+extra)
500 {
501 al=SSL_AD_RECORD_OVERFLOW;
502 OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_DATA_LENGTH_TOO_LONG);
503 goto f_err;
504 }
505
506 rr->off=0;
507 /* So at this point the following is true
508 * ssl->s3->rrec.type is the type of record
509 * ssl->s3->rrec.length == number of bytes in record
510 * ssl->s3->rrec.off == offset to first valid byte
511 * ssl->s3->rrec.data == where to take bytes from, increment
512 * after use :-).
513 */
514
515 /* we have pulled in a full packet so zero things */
516 s->packet_length=0;
517
518 /* just read a 0 length packet */
Adam Langley48105fa2014-06-20 12:00:00 -0700519 if (rr->length == 0)
520 {
521 empty_record_count++;
522 if (empty_record_count > MAX_EMPTY_RECORDS)
523 {
524 al=SSL_AD_UNEXPECTED_MESSAGE;
525 OPENSSL_PUT_ERROR(SSL, ssl3_get_record, SSL_R_TOO_MANY_EMPTY_FRAGMENTS);
526 goto f_err;
527 }
528 goto again;
529 }
Adam Langley95c29f32014-06-20 12:00:00 -0700530
531#if 0
532fprintf(stderr, "Ultimate Record type=%d, Length=%d\n", rr->type, rr->length);
533#endif
534
535 return(1);
536
537f_err:
538 ssl3_send_alert(s,SSL3_AL_FATAL,al);
539err:
540 return(ret);
541 }
542
Adam Langley95c29f32014-06-20 12:00:00 -0700543/* Call this to write data in records of type 'type'
544 * It will return <= 0 if not all data has been sent or non-blocking IO.
545 */
546int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
547 {
548 const unsigned char *buf=buf_;
549 unsigned int tot,n,nw;
550 int i;
551
552 s->rwstate=SSL_NOTHING;
Adam Langley87750b42014-06-20 12:00:00 -0700553 assert(s->s3->wnum <= INT_MAX);
Adam Langley95c29f32014-06-20 12:00:00 -0700554 tot=s->s3->wnum;
555 s->s3->wnum=0;
556
557 if (SSL_in_init(s) && !s->in_handshake)
558 {
559 i=s->handshake_func(s);
560 if (i < 0) return(i);
561 if (i == 0)
562 {
563 OPENSSL_PUT_ERROR(SSL, ssl3_write_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
564 return -1;
565 }
566 }
567
Adam Langley9611cfc2014-06-20 12:00:00 -0700568 /* ensure that if we end up with a smaller value of data to write
569 * out than the the original len from a write which didn't complete
570 * for non-blocking I/O and also somehow ended up avoiding
571 * the check for this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as
572 * it must never be possible to end up with (len-tot) as a large
573 * number that will then promptly send beyond the end of the users
574 * buffer ... so we trap and report the error in a way the user
575 * will notice
576 */
David Benjaminfb3ff2c2014-09-30 21:00:38 -0400577 if (len < 0 || (size_t)len < tot)
Adam Langley9611cfc2014-06-20 12:00:00 -0700578 {
579 OPENSSL_PUT_ERROR(SSL, ssl3_write_bytes, SSL_R_BAD_LENGTH);
580 return(-1);
581 }
582
Adam Langley95c29f32014-06-20 12:00:00 -0700583 n=(len-tot);
584 for (;;)
585 {
Adam Langleyd493d522014-06-20 12:00:00 -0700586 /* max contains the maximum number of bytes that we can put
587 * into a record. */
588 unsigned max = s->max_send_fragment;
589 /* fragment is true if do_ssl3_write should send the first byte
590 * in its own record in order to randomise a CBC IV. */
591 int fragment = 0;
592
593 if (n > 1 &&
594 s->s3->need_record_splitting &&
595 type == SSL3_RT_APPLICATION_DATA &&
596 !s->s3->record_split_done)
597 {
598 fragment = 1;
Adam Langleyd493d522014-06-20 12:00:00 -0700599 /* record_split_done records that the splitting has
600 * been done in case we hit an SSL_WANT_WRITE condition.
601 * In that case, we don't need to do the split again. */
602 s->s3->record_split_done = 1;
603 }
604
605 if (n > max)
606 nw=max;
Adam Langley95c29f32014-06-20 12:00:00 -0700607 else
608 nw=n;
609
Adam Langleyd493d522014-06-20 12:00:00 -0700610 i=do_ssl3_write(s, type, &(buf[tot]), nw, fragment, 0);
Adam Langley95c29f32014-06-20 12:00:00 -0700611 if (i <= 0)
612 {
613 s->s3->wnum=tot;
Kenny Root7fdeaf12014-08-05 15:23:37 -0700614 s->s3->record_split_done = 0;
Adam Langley95c29f32014-06-20 12:00:00 -0700615 return i;
616 }
617
618 if ((i == (int)n) ||
619 (type == SSL3_RT_APPLICATION_DATA &&
620 (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE)))
621 {
Adam Langleyd493d522014-06-20 12:00:00 -0700622 /* next chunk of data should get another prepended,
623 * one-byte fragment in ciphersuites with known-IV
624 * weakness. */
625 s->s3->record_split_done = 0;
Adam Langley95c29f32014-06-20 12:00:00 -0700626 return tot+i;
627 }
628
629 n-=i;
630 tot+=i;
631 }
632 }
633
Adam Langleyd493d522014-06-20 12:00:00 -0700634/* do_ssl3_write writes an SSL record of the given type. If |fragment| is 1
635 * then it splits the record into a one byte record and a record with the rest
636 * of the data in order to randomise a CBC IV. If |is_fragment| is true then
637 * this call resulted from do_ssl3_write calling itself in order to create that
638 * one byte fragment. */
Adam Langley95c29f32014-06-20 12:00:00 -0700639static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
Adam Langleyd493d522014-06-20 12:00:00 -0700640 unsigned int len, char fragment, char is_fragment)
Adam Langley95c29f32014-06-20 12:00:00 -0700641 {
642 unsigned char *p,*plen;
Adam Langleyd493d522014-06-20 12:00:00 -0700643 int i,mac_size;
Adam Langley95c29f32014-06-20 12:00:00 -0700644 int prefix_len=0;
645 int eivlen;
646 long align=0;
647 SSL3_RECORD *wr;
648 SSL3_BUFFER *wb=&(s->s3->wbuf);
649 SSL_SESSION *sess;
650
Adam Langley95c29f32014-06-20 12:00:00 -0700651 /* first check if there is a SSL3_BUFFER still being written
652 * out. This will happen with non blocking IO */
653 if (wb->left != 0)
654 return(ssl3_write_pending(s,type,buf,len));
655
656 /* If we have an alert to send, lets send it */
657 if (s->s3->alert_dispatch)
658 {
659 i=s->method->ssl_dispatch_alert(s);
660 if (i <= 0)
661 return(i);
662 /* if it went, fall through and send more stuff */
663 }
664
Adam Langleyc6c8ae82014-06-20 12:00:00 -0700665 if (wb->buf == NULL)
666 if (!ssl3_setup_write_buffer(s))
667 return -1;
668
Adam Langleyd493d522014-06-20 12:00:00 -0700669 if (len == 0)
Adam Langley95c29f32014-06-20 12:00:00 -0700670 return 0;
671
672 wr= &(s->s3->wrec);
673 sess=s->session;
674
675 if ( (sess == NULL) ||
676 (s->enc_write_ctx == NULL) ||
677 (EVP_MD_CTX_md(s->write_hash) == NULL))
678 {
Adam Langley95c29f32014-06-20 12:00:00 -0700679 mac_size=0;
680 }
681 else
682 {
683 mac_size=EVP_MD_CTX_size(s->write_hash);
684 if (mac_size < 0)
685 goto err;
686 }
687
Adam Langleyd493d522014-06-20 12:00:00 -0700688 if (fragment)
Adam Langley95c29f32014-06-20 12:00:00 -0700689 {
690 /* countermeasure against known-IV weakness in CBC ciphersuites
691 * (see http://www.openssl.org/~bodo/tls-cbc.txt) */
Adam Langleyd493d522014-06-20 12:00:00 -0700692 prefix_len = do_ssl3_write(s, type, buf, 1 /* length */,
693 0 /* fragment */,
694 1 /* is_fragment */);
695 if (prefix_len <= 0)
696 goto err;
Adam Langley95c29f32014-06-20 12:00:00 -0700697
Adam Langleyd493d522014-06-20 12:00:00 -0700698 if (prefix_len > (SSL3_RT_HEADER_LENGTH +
699 SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD))
Adam Langley95c29f32014-06-20 12:00:00 -0700700 {
Adam Langleyd493d522014-06-20 12:00:00 -0700701 /* insufficient space */
702 OPENSSL_PUT_ERROR(SSL, do_ssl3_write, ERR_R_INTERNAL_ERROR);
703 goto err;
Adam Langley95c29f32014-06-20 12:00:00 -0700704 }
Adam Langley95c29f32014-06-20 12:00:00 -0700705 }
706
Adam Langleyd493d522014-06-20 12:00:00 -0700707 if (is_fragment)
Adam Langley95c29f32014-06-20 12:00:00 -0700708 {
709#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
Adam Langleyd493d522014-06-20 12:00:00 -0700710 /* The extra fragment would be couple of cipher blocks, and
711 * that will be a multiple of SSL3_ALIGN_PAYLOAD. So, if we
712 * want to align the real payload, we can just pretend that we
713 * have two headers and a byte. */
714 align = (long)wb->buf + 2*SSL3_RT_HEADER_LENGTH + 1;
Adam Langley95c29f32014-06-20 12:00:00 -0700715 align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
716#endif
717 p = wb->buf + align;
718 wb->offset = align;
719 }
720 else if (prefix_len)
721 {
722 p = wb->buf + wb->offset + prefix_len;
723 }
724 else
725 {
726#if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
727 align = (long)wb->buf + SSL3_RT_HEADER_LENGTH;
728 align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
729#endif
730 p = wb->buf + align;
731 wb->offset = align;
732 }
733
734 /* write the header */
735
736 *(p++)=type&0xff;
737 wr->type=type;
738
739 *(p++)=(s->version>>8);
740 /* Some servers hang if iniatial client hello is larger than 256
741 * bytes and record version number > TLS 1.0
742 */
743 if (s->state == SSL3_ST_CW_CLNT_HELLO_B
744 && !s->renegotiate
745 && TLS1_get_version(s) > TLS1_VERSION)
746 *(p++) = 0x1;
747 else
748 *(p++)=s->version&0xff;
749
750 /* field where we are to write out packet length */
Adam Langleyd493d522014-06-20 12:00:00 -0700751 plen=p;
Adam Langley95c29f32014-06-20 12:00:00 -0700752 p+=2;
753 /* Explicit IV length, block ciphers appropriate version flag */
754 if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s))
755 {
756 int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
757 if (mode == EVP_CIPH_CBC_MODE)
758 {
759 eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
760 if (eivlen <= 1)
761 eivlen = 0;
762 }
Adam Langley95c29f32014-06-20 12:00:00 -0700763 else
764 eivlen = 0;
765 }
Adam Langleyde0b2022014-06-20 12:00:00 -0700766 else if (s->aead_write_ctx != NULL &&
767 s->aead_write_ctx->variable_nonce_included_in_record)
768 {
Adam Langleyc9fb3752014-06-20 12:00:00 -0700769 eivlen = s->aead_write_ctx->variable_nonce_len;
Adam Langleyde0b2022014-06-20 12:00:00 -0700770 }
Adam Langleyc9fb3752014-06-20 12:00:00 -0700771 else
Adam Langley95c29f32014-06-20 12:00:00 -0700772 eivlen = 0;
773
774 /* lets setup the record stuff. */
775 wr->data=p + eivlen;
Adam Langleyd493d522014-06-20 12:00:00 -0700776 wr->length=(int)(len - (fragment != 0));
777 wr->input=(unsigned char *)buf + (fragment != 0);
Adam Langley95c29f32014-06-20 12:00:00 -0700778
779 /* we now 'read' from wr->input, wr->length bytes into
780 * wr->data */
781
David Benjamin3f6fa3d2014-06-24 18:43:57 -0400782 memcpy(wr->data,wr->input,wr->length);
783 wr->input=wr->data;
Adam Langley95c29f32014-06-20 12:00:00 -0700784
785 /* we should still have the output to wr->data and the input
786 * from wr->input. Length should be wr->length.
787 * wr->data still points in the wb->buf */
788
789 if (mac_size != 0)
790 {
791 if (s->method->ssl3_enc->mac(s,&(p[wr->length + eivlen]),1) < 0)
792 goto err;
793 wr->length+=mac_size;
794 }
795
796 wr->input=p;
797 wr->data=p;
798
799 if (eivlen)
800 {
801 /* if (RAND_pseudo_bytes(p, eivlen) <= 0)
802 goto err; */
803 wr->length += eivlen;
804 }
805
806 /* ssl3_enc can only have an error on read */
807 s->method->ssl3_enc->enc(s,1);
808
809 /* record length after mac and block padding */
810 s2n(wr->length,plen);
811
812 if (s->msg_callback)
813 s->msg_callback(1, 0, SSL3_RT_HEADER, plen - 5, 5, s, s->msg_callback_arg);
814
815 /* we should now have
816 * wr->data pointing to the encrypted data, which is
817 * wr->length long */
818 wr->type=type; /* not needed but helps for debugging */
819 wr->length+=SSL3_RT_HEADER_LENGTH;
820
Adam Langleyd493d522014-06-20 12:00:00 -0700821 if (is_fragment)
Adam Langley95c29f32014-06-20 12:00:00 -0700822 {
Adam Langleyd493d522014-06-20 12:00:00 -0700823 /* we are in a recursive call; just return the length, don't
824 * write out anything. */
Adam Langley95c29f32014-06-20 12:00:00 -0700825 return wr->length;
826 }
827
828 /* now let's set up wb */
829 wb->left = prefix_len + wr->length;
830
831 /* memorize arguments so that ssl3_write_pending can detect bad write retries later */
832 s->s3->wpend_tot=len;
833 s->s3->wpend_buf=buf;
834 s->s3->wpend_type=type;
835 s->s3->wpend_ret=len;
836
837 /* we now just need to write the buffer */
838 return ssl3_write_pending(s,type,buf,len);
839err:
840 return -1;
841 }
842
843/* if s->s3->wbuf.left != 0, we need to call this */
844int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
845 unsigned int len)
846 {
847 int i;
848 SSL3_BUFFER *wb=&(s->s3->wbuf);
849
850/* XXXX */
851 if ((s->s3->wpend_tot > (int)len)
852 || ((s->s3->wpend_buf != buf) &&
853 !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
854 || (s->s3->wpend_type != type))
855 {
856 OPENSSL_PUT_ERROR(SSL, ssl3_write_pending, SSL_R_BAD_WRITE_RETRY);
857 return(-1);
858 }
859
860 for (;;)
861 {
862 ERR_clear_system_error();
863 if (s->wbio != NULL)
864 {
865 s->rwstate=SSL_WRITING;
866 i=BIO_write(s->wbio,
867 (char *)&(wb->buf[wb->offset]),
868 (unsigned int)wb->left);
869 }
870 else
871 {
872 OPENSSL_PUT_ERROR(SSL, ssl3_write_pending, SSL_R_BIO_NOT_SET);
873 i= -1;
874 }
875 if (i == wb->left)
876 {
877 wb->left=0;
878 wb->offset+=i;
879 if (s->mode & SSL_MODE_RELEASE_BUFFERS &&
880 !SSL_IS_DTLS(s))
881 ssl3_release_write_buffer(s);
882 s->rwstate=SSL_NOTHING;
883 return(s->s3->wpend_ret);
884 }
885 else if (i <= 0) {
David Benjamin09bd58d2014-08-12 21:22:28 -0400886 if (SSL_IS_DTLS(s)) {
Adam Langley95c29f32014-06-20 12:00:00 -0700887 /* For DTLS, just drop it. That's kind of the whole
888 point in using a datagram service */
889 wb->left = 0;
890 }
891 return(i);
892 }
893 wb->offset+=i;
894 wb->left-=i;
895 }
896 }
897
David Benjamin86271ee2014-07-21 16:14:03 -0400898/* ssl3_expect_change_cipher_spec informs the record layer that a
899 * ChangeCipherSpec record is required at this point. If a Handshake record is
900 * received before ChangeCipherSpec, the connection will fail. Moreover, if
901 * there are unprocessed handshake bytes, the handshake will also fail and the
902 * function returns zero. Otherwise, the function returns one. */
903int ssl3_expect_change_cipher_spec(SSL *s)
904 {
905 if (s->s3->handshake_fragment_len > 0 || s->s3->tmp.reuse_message)
906 {
907 OPENSSL_PUT_ERROR(SSL, ssl3_expect_change_cipher_spec, SSL_R_UNPROCESSED_HANDSHAKE_DATA);
908 return 0;
909 }
910 s->s3->flags |= SSL3_FLAGS_EXPECT_CCS;
911 return 1;
912 }
913
Adam Langley95c29f32014-06-20 12:00:00 -0700914/* Return up to 'len' payload bytes received in 'type' records.
915 * 'type' is one of the following:
916 *
917 * - SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
918 * - SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
919 * - 0 (during a shutdown, no data has to be returned)
920 *
921 * If we don't have stored data to work from, read a SSL/TLS record first
922 * (possibly multiple records if we still don't have anything to return).
923 *
924 * This function must handle any surprises the peer may have for us, such as
925 * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
926 * a surprise, but handled as if it were), or renegotiation requests.
927 * Also if record payloads contain fragments too small to process, we store
928 * them until there is enough for the respective protocol (the record protocol
929 * may use arbitrary fragmentation and even interleaving):
930 * Change cipher spec protocol
931 * just 1 byte needed, no need for keeping anything stored
932 * Alert protocol
933 * 2 bytes needed (AlertLevel, AlertDescription)
934 * Handshake protocol
935 * 4 bytes needed (HandshakeType, uint24 length) -- we just have
936 * to detect unexpected Client Hello and Hello Request messages
937 * here, anything else is handled by higher layers
938 * Application data protocol
939 * none of our business
940 */
941int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
942 {
943 int al,i,j,ret;
944 unsigned int n;
945 SSL3_RECORD *rr;
946 void (*cb)(const SSL *ssl,int type2,int val)=NULL;
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -0400947 uint8_t alert_buffer[2];
Adam Langley95c29f32014-06-20 12:00:00 -0700948
949 if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
950 if (!ssl3_setup_read_buffer(s))
951 return(-1);
952
Adam Langley46cfb0e2014-07-24 17:30:28 -0700953 if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE)) ||
Adam Langley95c29f32014-06-20 12:00:00 -0700954 (peek && (type != SSL3_RT_APPLICATION_DATA)))
955 {
956 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, ERR_R_INTERNAL_ERROR);
957 return -1;
958 }
959
960 if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0))
961 /* (partially) satisfy request from storage */
962 {
963 unsigned char *src = s->s3->handshake_fragment;
964 unsigned char *dst = buf;
965 unsigned int k;
966
967 /* peek == 0 */
968 n = 0;
969 while ((len > 0) && (s->s3->handshake_fragment_len > 0))
970 {
971 *dst++ = *src++;
972 len--; s->s3->handshake_fragment_len--;
973 n++;
974 }
975 /* move any remaining fragment bytes: */
976 for (k = 0; k < s->s3->handshake_fragment_len; k++)
977 s->s3->handshake_fragment[k] = *src++;
978 return n;
979 }
980
981 /* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
982
983 if (!s->in_handshake && SSL_in_init(s))
984 {
985 /* type == SSL3_RT_APPLICATION_DATA */
986 i=s->handshake_func(s);
987 if (i < 0) return(i);
988 if (i == 0)
989 {
990 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
991 return(-1);
992 }
993 }
994start:
995 s->rwstate=SSL_NOTHING;
996
997 /* s->s3->rrec.type - is the type of record
998 * s->s3->rrec.data, - data
999 * s->s3->rrec.off, - offset into 'data' for next read
1000 * s->s3->rrec.length, - number of bytes. */
1001 rr = &(s->s3->rrec);
1002
1003 /* get new packet if necessary */
1004 if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))
1005 {
1006 ret=ssl3_get_record(s);
1007 if (ret <= 0) return(ret);
1008 }
1009
1010 /* we now have a packet which can be read and processed */
1011
1012 if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
1013 * reset by ssl3_get_finished */
1014 && (rr->type != SSL3_RT_HANDSHAKE))
1015 {
1016 al=SSL_AD_UNEXPECTED_MESSAGE;
1017 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1018 goto f_err;
1019 }
1020
David Benjamin86271ee2014-07-21 16:14:03 -04001021 /* If we are expecting a ChangeCipherSpec, it is illegal to receive a
1022 * Handshake record. */
1023 if (rr->type == SSL3_RT_HANDSHAKE && (s->s3->flags & SSL3_FLAGS_EXPECT_CCS))
1024 {
1025 al = SSL_AD_UNEXPECTED_MESSAGE;
1026 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_HANDSHAKE_RECORD_BEFORE_CCS);
1027 goto f_err;
1028 }
1029
Adam Langley95c29f32014-06-20 12:00:00 -07001030 /* If the other end has shut down, throw anything we read away
1031 * (even in 'peek' mode) */
1032 if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
1033 {
1034 rr->length=0;
1035 s->rwstate=SSL_NOTHING;
1036 return(0);
1037 }
1038
Adam Langley95c29f32014-06-20 12:00:00 -07001039 if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
1040 {
1041 /* make sure that we are not getting application data when we
1042 * are doing a handshake for the first time */
1043 if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
1044 (s->enc_read_ctx == NULL))
1045 {
1046 al=SSL_AD_UNEXPECTED_MESSAGE;
1047 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_APP_DATA_IN_HANDSHAKE);
1048 goto f_err;
1049 }
1050
1051 if (len <= 0) return(len);
1052
1053 if ((unsigned int)len > rr->length)
1054 n = rr->length;
1055 else
1056 n = (unsigned int)len;
1057
1058 memcpy(buf,&(rr->data[rr->off]),n);
1059 if (!peek)
1060 {
1061 rr->length-=n;
1062 rr->off+=n;
1063 if (rr->length == 0)
1064 {
1065 s->rstate=SSL_ST_READ_HEADER;
1066 rr->off=0;
Adam Langley4a35a932014-06-20 12:00:00 -07001067 if (s->mode & SSL_MODE_RELEASE_BUFFERS && s->s3->rbuf.left == 0)
Adam Langley95c29f32014-06-20 12:00:00 -07001068 ssl3_release_read_buffer(s);
1069 }
1070 }
1071 return(n);
1072 }
1073
1074
1075 /* If we get here, then type != rr->type; if we have a handshake
1076 * message, then it was unexpected (Hello Request or Client Hello). */
1077
1078 /* In case of record types for which we have 'fragment' storage,
1079 * fill that so that we can process the data at a fixed place.
1080 */
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001081
1082 if (rr->type == SSL3_RT_HANDSHAKE)
Adam Langley95c29f32014-06-20 12:00:00 -07001083 {
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001084 const size_t size = sizeof(s->s3->handshake_fragment);
1085 const size_t avail = size - s->s3->handshake_fragment_len;
1086 const size_t len = (rr->length < avail) ? rr->length : avail;
1087 memcpy(s->s3->handshake_fragment + s->s3->handshake_fragment_len,
1088 &rr->data[rr->off], len);
1089 rr->off += len;
1090 rr->length -= len;
1091 s->s3->handshake_fragment_len += len;
1092 if (s->s3->handshake_fragment_len < size)
Adam Langley95c29f32014-06-20 12:00:00 -07001093 {
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001094 goto start; /* fragment was too small */
Adam Langley95c29f32014-06-20 12:00:00 -07001095 }
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001096 }
1097 else if (rr->type == SSL3_RT_ALERT)
1098 {
1099 const size_t len = sizeof(alert_buffer);
1100 /* Note that this will still allow multiple alerts to
1101 * be processed in the same record */
1102 if (rr->length < sizeof(alert_buffer))
Adam Langley95c29f32014-06-20 12:00:00 -07001103 {
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001104 al = SSL_AD_DECODE_ERROR;
1105 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_ALERT);
1106 goto f_err;
Adam Langley95c29f32014-06-20 12:00:00 -07001107 }
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001108 memcpy(alert_buffer, &rr->data[rr->off], len);
1109 rr->off += len;
1110 rr->length -= len;
Adam Langley95c29f32014-06-20 12:00:00 -07001111 }
1112
1113 /* s->s3->handshake_fragment_len == 4 iff rr->type == SSL3_RT_HANDSHAKE;
Adam Langley95c29f32014-06-20 12:00:00 -07001114 * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
1115
1116 /* If we are a client, check for an incoming 'Hello Request': */
1117 if ((!s->server) &&
1118 (s->s3->handshake_fragment_len >= 4) &&
1119 (s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
1120 (s->session != NULL) && (s->session->cipher != NULL))
1121 {
1122 s->s3->handshake_fragment_len = 0;
1123
1124 if ((s->s3->handshake_fragment[1] != 0) ||
1125 (s->s3->handshake_fragment[2] != 0) ||
1126 (s->s3->handshake_fragment[3] != 0))
1127 {
1128 al=SSL_AD_DECODE_ERROR;
1129 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_HELLO_REQUEST);
1130 goto f_err;
1131 }
1132
1133 if (s->msg_callback)
1134 s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->s3->handshake_fragment, 4, s, s->msg_callback_arg);
1135
1136 if (SSL_is_init_finished(s) &&
1137 !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
1138 !s->s3->renegotiate)
1139 {
1140 ssl3_renegotiate(s);
1141 if (ssl3_renegotiate_check(s))
1142 {
1143 i=s->handshake_func(s);
1144 if (i < 0) return(i);
1145 if (i == 0)
1146 {
1147 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
1148 return(-1);
1149 }
Adam Langley95c29f32014-06-20 12:00:00 -07001150 }
1151 }
1152 /* we either finished a handshake or ignored the request,
1153 * now try again to obtain the (application) data we were asked for */
1154 goto start;
1155 }
David Benjaminb4188f02014-11-01 03:43:48 -04001156
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001157 if (rr->type == SSL3_RT_ALERT)
Adam Langley95c29f32014-06-20 12:00:00 -07001158 {
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001159 uint8_t alert_level = alert_buffer[0];
1160 uint8_t alert_descr = alert_buffer[1];
Adam Langley95c29f32014-06-20 12:00:00 -07001161
1162 if (s->msg_callback)
Alex Chernyakhovsky4cd8c432014-11-01 19:39:08 -04001163 s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_buffer, 2, s, s->msg_callback_arg);
Adam Langley95c29f32014-06-20 12:00:00 -07001164
1165 if (s->info_callback != NULL)
1166 cb=s->info_callback;
1167 else if (s->ctx->info_callback != NULL)
1168 cb=s->ctx->info_callback;
1169
1170 if (cb != NULL)
1171 {
1172 j = (alert_level << 8) | alert_descr;
1173 cb(s, SSL_CB_READ_ALERT, j);
1174 }
1175
1176 if (alert_level == 1) /* warning */
1177 {
1178 s->s3->warn_alert = alert_descr;
1179 if (alert_descr == SSL_AD_CLOSE_NOTIFY)
1180 {
1181 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1182 return(0);
1183 }
1184 /* This is a warning but we receive it if we requested
1185 * renegotiation and the peer denied it. Terminate with
1186 * a fatal alert because if application tried to
1187 * renegotiatie it presumably had a good reason and
1188 * expects it to succeed.
1189 *
1190 * In future we might have a renegotiation where we
1191 * don't care if the peer refused it where we carry on.
1192 */
1193 else if (alert_descr == SSL_AD_NO_RENEGOTIATION)
1194 {
1195 al = SSL_AD_HANDSHAKE_FAILURE;
1196 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_NO_RENEGOTIATION);
1197 goto f_err;
1198 }
Adam Langley95c29f32014-06-20 12:00:00 -07001199 }
1200 else if (alert_level == 2) /* fatal */
1201 {
1202 char tmp[16];
1203
1204 s->rwstate=SSL_NOTHING;
1205 s->s3->fatal_alert = alert_descr;
1206 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_AD_REASON_OFFSET + alert_descr);
1207 BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr);
1208 ERR_add_error_data(2,"SSL alert number ",tmp);
1209 s->shutdown|=SSL_RECEIVED_SHUTDOWN;
1210 SSL_CTX_remove_session(s->ctx,s->session);
1211 return(0);
1212 }
1213 else
1214 {
1215 al=SSL_AD_ILLEGAL_PARAMETER;
1216 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNKNOWN_ALERT_TYPE);
1217 goto f_err;
1218 }
1219
1220 goto start;
1221 }
1222
1223 if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
1224 {
1225 s->rwstate=SSL_NOTHING;
1226 rr->length=0;
1227 return(0);
1228 }
1229
1230 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
1231 {
1232 /* 'Change Cipher Spec' is just a single byte, so we know
1233 * exactly what the record payload has to look like */
1234 if ( (rr->length != 1) || (rr->off != 0) ||
1235 (rr->data[0] != SSL3_MT_CCS))
1236 {
1237 al=SSL_AD_ILLEGAL_PARAMETER;
1238 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_BAD_CHANGE_CIPHER_SPEC);
1239 goto f_err;
1240 }
1241
1242 /* Check we have a cipher to change to */
1243 if (s->s3->tmp.new_cipher == NULL)
1244 {
1245 al=SSL_AD_UNEXPECTED_MESSAGE;
1246 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_CCS_RECEIVED_EARLY);
1247 goto f_err;
1248 }
1249
David Benjamin86271ee2014-07-21 16:14:03 -04001250 if (!(s->s3->flags & SSL3_FLAGS_EXPECT_CCS))
Adam Langleyce7f9ca2014-06-20 12:00:00 -07001251 {
1252 al=SSL_AD_UNEXPECTED_MESSAGE;
1253 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_CCS_RECEIVED_EARLY);
1254 goto f_err;
1255 }
1256
David Benjamin86271ee2014-07-21 16:14:03 -04001257 s->s3->flags &= ~SSL3_FLAGS_EXPECT_CCS;
Adam Langleyce7f9ca2014-06-20 12:00:00 -07001258
Adam Langley95c29f32014-06-20 12:00:00 -07001259 rr->length=0;
1260
1261 if (s->msg_callback)
1262 s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg);
1263
1264 s->s3->change_cipher_spec=1;
1265 if (!ssl3_do_change_cipher_spec(s))
1266 goto err;
1267 else
1268 goto start;
1269 }
1270
1271 /* Unexpected handshake message (Client Hello, or protocol violation) */
1272 if ((s->s3->handshake_fragment_len >= 4) && !s->in_handshake)
1273 {
1274 if (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&
1275 !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS))
1276 {
Adam Langley95c29f32014-06-20 12:00:00 -07001277 s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
Adam Langley95c29f32014-06-20 12:00:00 -07001278 s->renegotiate=1;
1279 s->new_session=1;
1280 }
1281 i=s->handshake_func(s);
1282 if (i < 0) return(i);
1283 if (i == 0)
1284 {
1285 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_SSL_HANDSHAKE_FAILURE);
1286 return(-1);
1287 }
1288
Adam Langley95c29f32014-06-20 12:00:00 -07001289 goto start;
1290 }
1291
1292 switch (rr->type)
1293 {
1294 default:
Adam Langley95c29f32014-06-20 12:00:00 -07001295 /* TLS up to v1.1 just ignores unknown message types:
1296 * TLS v1.2 give an unexpected message alert.
1297 */
1298 if (s->version >= TLS1_VERSION && s->version <= TLS1_1_VERSION)
1299 {
1300 rr->length = 0;
1301 goto start;
1302 }
Adam Langley95c29f32014-06-20 12:00:00 -07001303 al=SSL_AD_UNEXPECTED_MESSAGE;
1304 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNEXPECTED_RECORD);
1305 goto f_err;
1306 case SSL3_RT_CHANGE_CIPHER_SPEC:
1307 case SSL3_RT_ALERT:
1308 case SSL3_RT_HANDSHAKE:
1309 /* we already handled all of these, with the possible exception
1310 * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that
1311 * should not happen when type != rr->type */
1312 al=SSL_AD_UNEXPECTED_MESSAGE;
1313 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, ERR_R_INTERNAL_ERROR);
1314 goto f_err;
1315 case SSL3_RT_APPLICATION_DATA:
1316 /* At this point, we were expecting handshake data,
1317 * but have application data. If the library was
1318 * running inside ssl3_read() (i.e. in_read_app_data
1319 * is set) and it makes sense to read application data
1320 * at this point (session renegotiation not yet started),
1321 * we will indulge it.
1322 */
1323 if (s->s3->in_read_app_data &&
1324 (s->s3->total_renegotiations != 0) &&
1325 ((
1326 (s->state & SSL_ST_CONNECT) &&
1327 (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1328 (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
1329 ) || (
1330 (s->state & SSL_ST_ACCEPT) &&
1331 (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
1332 (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
1333 )
1334 ))
1335 {
1336 s->s3->in_read_app_data=2;
1337 return(-1);
1338 }
1339 else
1340 {
1341 al=SSL_AD_UNEXPECTED_MESSAGE;
1342 OPENSSL_PUT_ERROR(SSL, ssl3_read_bytes, SSL_R_UNEXPECTED_RECORD);
1343 goto f_err;
1344 }
1345 }
1346 /* not reached */
1347
1348f_err:
1349 ssl3_send_alert(s,SSL3_AL_FATAL,al);
1350err:
1351 return(-1);
1352 }
1353
1354int ssl3_do_change_cipher_spec(SSL *s)
1355 {
1356 int i;
Adam Langley95c29f32014-06-20 12:00:00 -07001357
1358 if (s->state & SSL_ST_ACCEPT)
1359 i=SSL3_CHANGE_CIPHER_SERVER_READ;
1360 else
1361 i=SSL3_CHANGE_CIPHER_CLIENT_READ;
1362
1363 if (s->s3->tmp.key_block == NULL)
1364 {
Adam Langleyec48ffc2014-06-20 12:00:00 -07001365 if (s->session == NULL || s->session->master_key_length == 0)
Adam Langley95c29f32014-06-20 12:00:00 -07001366 {
1367 /* might happen if dtls1_read_bytes() calls this */
1368 OPENSSL_PUT_ERROR(SSL, ssl3_do_change_cipher_spec, SSL_R_CCS_RECEIVED_EARLY);
1369 return (0);
1370 }
1371
1372 s->session->cipher=s->s3->tmp.new_cipher;
1373 if (!s->method->ssl3_enc->setup_key_block(s)) return(0);
1374 }
1375
1376 if (!s->method->ssl3_enc->change_cipher_state(s,i))
1377 return(0);
1378
Adam Langley95c29f32014-06-20 12:00:00 -07001379 return(1);
1380 }
1381
1382int ssl3_send_alert(SSL *s, int level, int desc)
1383 {
1384 /* Map tls/ssl alert value to correct one */
1385 desc=s->method->ssl3_enc->alert_value(desc);
1386 if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
1387 desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have protocol_version alerts */
1388 if (desc < 0) return -1;
1389 /* If a fatal one, remove from cache */
1390 if ((level == 2) && (s->session != NULL))
1391 SSL_CTX_remove_session(s->ctx,s->session);
1392
1393 s->s3->alert_dispatch=1;
1394 s->s3->send_alert[0]=level;
1395 s->s3->send_alert[1]=desc;
1396 if (s->s3->wbuf.left == 0) /* data still being written out? */
1397 return s->method->ssl_dispatch_alert(s);
1398 /* else data is still being written out, we will get written
1399 * some time in the future */
1400 return -1;
1401 }
1402
1403int ssl3_dispatch_alert(SSL *s)
1404 {
1405 int i,j;
1406 void (*cb)(const SSL *ssl,int type,int val)=NULL;
1407
1408 s->s3->alert_dispatch=0;
Adam Langleyd493d522014-06-20 12:00:00 -07001409 i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0, 0);
Adam Langley95c29f32014-06-20 12:00:00 -07001410 if (i <= 0)
1411 {
1412 s->s3->alert_dispatch=1;
1413 }
1414 else
1415 {
1416 /* Alert sent to BIO. If it is important, flush it now.
1417 * If the message does not get sent due to non-blocking IO,
1418 * we will not worry too much. */
1419 if (s->s3->send_alert[0] == SSL3_AL_FATAL)
1420 (void)BIO_flush(s->wbio);
1421
1422 if (s->msg_callback)
1423 s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s, s->msg_callback_arg);
1424
1425 if (s->info_callback != NULL)
1426 cb=s->info_callback;
1427 else if (s->ctx->info_callback != NULL)
1428 cb=s->ctx->info_callback;
1429
1430 if (cb != NULL)
1431 {
1432 j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
1433 cb(s,SSL_CB_WRITE_ALERT,j);
1434 }
1435 }
1436 return(i);
1437 }