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