Keep old method in case of an unsupported protocol
[openssl.git] / ssl / s3_pkt.c
1 /* ssl/s3_pkt.c */
2 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
3  * All rights reserved.
4  *
5  * This package is an SSL implementation written
6  * by Eric Young (eay@cryptsoft.com).
7  * The implementation was written so as to conform with Netscapes SSL.
8  * 
9  * This library is free for commercial and non-commercial use as long as
10  * the following conditions are aheared to.  The following conditions
11  * apply to all code found in this distribution, be it the RC4, RSA,
12  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
13  * included with this distribution is covered by the same copyright terms
14  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
15  * 
16  * Copyright remains Eric Young's, and as such any Copyright notices in
17  * the code are not to be removed.
18  * If this package is used in a product, Eric Young should be given attribution
19  * as the author of the parts of the library used.
20  * This can be in the form of a textual message at program startup or
21  * in documentation (online or textual) provided with the package.
22  * 
23  * Redistribution and use in source and binary forms, with or without
24  * modification, are permitted provided that the following conditions
25  * are met:
26  * 1. Redistributions of source code must retain the copyright
27  *    notice, this list of conditions and the following disclaimer.
28  * 2. Redistributions in binary form must reproduce the above copyright
29  *    notice, this list of conditions and the following disclaimer in the
30  *    documentation and/or other materials provided with the distribution.
31  * 3. All advertising materials mentioning features or use of this software
32  *    must display the following acknowledgement:
33  *    "This product includes cryptographic software written by
34  *     Eric Young (eay@cryptsoft.com)"
35  *    The word 'cryptographic' can be left out if the rouines from the library
36  *    being used are not cryptographic related :-).
37  * 4. If you include any Windows specific code (or a derivative thereof) from 
38  *    the apps directory (application code) you must include an acknowledgement:
39  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
40  * 
41  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
42  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
43  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
44  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
45  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
46  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
47  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
49  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
50  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
51  * SUCH DAMAGE.
52  * 
53  * The licence and distribution terms for any publically available version or
54  * derivative of this code cannot be changed.  i.e. this code cannot simply be
55  * copied and put under another distribution licence
56  * [including the GNU Public Licence.]
57  */
58 /* ====================================================================
59  * Copyright (c) 1998-2002 The OpenSSL Project.  All rights reserved.
60  *
61  * Redistribution and use in source and binary forms, with or without
62  * modification, are permitted provided that the following conditions
63  * are met:
64  *
65  * 1. Redistributions of source code must retain the above copyright
66  *    notice, this list of conditions and the following disclaimer. 
67  *
68  * 2. Redistributions in binary form must reproduce the above copyright
69  *    notice, this list of conditions and the following disclaimer in
70  *    the documentation and/or other materials provided with the
71  *    distribution.
72  *
73  * 3. All advertising materials mentioning features or use of this
74  *    software must display the following acknowledgment:
75  *    "This product includes software developed by the OpenSSL Project
76  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
77  *
78  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
79  *    endorse or promote products derived from this software without
80  *    prior written permission. For written permission, please contact
81  *    openssl-core@openssl.org.
82  *
83  * 5. Products derived from this software may not be called "OpenSSL"
84  *    nor may "OpenSSL" appear in their names without prior written
85  *    permission of the OpenSSL Project.
86  *
87  * 6. Redistributions of any form whatsoever must retain the following
88  *    acknowledgment:
89  *    "This product includes software developed by the OpenSSL Project
90  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
91  *
92  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
93  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
94  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
95  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
96  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
97  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
98  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
99  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
100  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
101  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
102  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
103  * OF THE POSSIBILITY OF SUCH DAMAGE.
104  * ====================================================================
105  *
106  * This product includes cryptographic software written by Eric Young
107  * (eay@cryptsoft.com).  This product includes software written by Tim
108  * Hudson (tjh@cryptsoft.com).
109  *
110  */
111
112 #include <stdio.h>
113 #include <limits.h>
114 #include <errno.h>
115 #define USE_SOCKETS
116 #include "ssl_locl.h"
117 #include <openssl/evp.h>
118 #include <openssl/buffer.h>
119
120 static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
121                          unsigned int len, int create_empty_fragment);
122 static int ssl3_get_record(SSL *s);
123
124 int ssl3_read_n(SSL *s, int n, int max, int extend)
125         {
126         /* If extend == 0, obtain new n-byte packet; if extend == 1, increase
127          * packet by another n bytes.
128          * The packet will be in the sub-array of s->s3->rbuf.buf specified
129          * by s->packet and s->packet_length.
130          * (If s->read_ahead is set, 'max' bytes may be stored in rbuf
131          * [plus s->packet_length bytes if extend == 1].)
132          */
133         int i,off,newb;
134
135         if (!extend)
136                 {
137                 /* start with empty packet ... */
138                 if (s->s3->rbuf.left == 0)
139                         s->s3->rbuf.offset = 0;
140                 s->packet = s->s3->rbuf.buf + s->s3->rbuf.offset;
141                 s->packet_length = 0;
142                 /* ... now we can act as if 'extend' was set */
143                 }
144
145         /* For DTLS/UDP reads should not span multiple packets
146          * because the read operation returns the whole packet
147          * at once (as long as it fits into the buffer). */
148         if (SSL_version(s) == DTLS1_VERSION)
149                 {
150                 if ( s->s3->rbuf.left > 0 && n > s->s3->rbuf.left)
151                         n = s->s3->rbuf.left;
152                 }
153
154         /* if there is enough in the buffer from a previous read, take some */
155         if (s->s3->rbuf.left >= (int)n)
156                 {
157                 s->packet_length+=n;
158                 s->s3->rbuf.left-=n;
159                 s->s3->rbuf.offset+=n;
160                 return(n);
161                 }
162
163         /* else we need to read more data */
164         if (!s->read_ahead)
165                 max=n;
166
167         {
168                 /* avoid buffer overflow */
169                 int max_max = s->s3->rbuf.len - s->packet_length;
170                 if (max > max_max)
171                         max = max_max;
172         }
173         if (n > max) /* does not happen */
174                 {
175                 SSLerr(SSL_F_SSL3_READ_N,ERR_R_INTERNAL_ERROR);
176                 return -1;
177                 }
178
179         off = s->packet_length;
180         newb = s->s3->rbuf.left;
181         /* Move any available bytes to front of buffer:
182          * 'off' bytes already pointed to by 'packet',
183          * 'newb' extra ones at the end */
184         if (s->packet != s->s3->rbuf.buf)
185                 {
186                 /*  off > 0 */
187                 memmove(s->s3->rbuf.buf, s->packet, off+newb);
188                 s->packet = s->s3->rbuf.buf;
189                 }
190
191         while (newb < n)
192                 {
193                 /* Now we have off+newb bytes at the front of s->s3->rbuf.buf and need
194                  * to read in more until we have off+n (up to off+max if possible) */
195
196                 clear_sys_error();
197                 if (s->rbio != NULL)
198                         {
199                         s->rwstate=SSL_READING;
200                         i=BIO_read(s->rbio,     &(s->s3->rbuf.buf[off+newb]), max-newb);
201                         }
202                 else
203                         {
204                         SSLerr(SSL_F_SSL3_READ_N,SSL_R_READ_BIO_NOT_SET);
205                         i = -1;
206                         }
207
208                 if (i <= 0)
209                         {
210                         s->s3->rbuf.left = newb;
211                         return(i);
212                         }
213                 newb+=i;
214                 /* reads should *never* span multiple packets for DTLS because
215                  * the underlying transport protocol is message oriented as opposed
216                  * to byte oriented as in the TLS case. */
217                 if (SSL_version(s) == DTLS1_VERSION)
218                         {
219                         if (n > newb)
220                                 n = newb; /* makes the while condition false */
221                         }
222                 }
223
224         /* done reading, now the book-keeping */
225         s->s3->rbuf.offset = off + n;
226         s->s3->rbuf.left = newb - n;
227         s->packet_length += n;
228         s->rwstate=SSL_NOTHING;
229         return(n);
230         }
231
232 /* MAX_EMPTY_RECORDS defines the number of consecutive, empty records that will
233  * be processed per call to ssl3_get_record. Without this limit an attacker
234  * could send empty records at a faster rate than we can process and cause
235  * ssl3_get_record to loop forever. */
236 #define MAX_EMPTY_RECORDS 32
237
238 /* Call this to get a new input record.
239  * It will return <= 0 if more data is needed, normally due to an error
240  * or non-blocking IO.
241  * When it finishes, one packet has been decoded and can be found in
242  * ssl->s3->rrec.type    - is the type of record
243  * ssl->s3->rrec.data,   - data
244  * ssl->s3->rrec.length, - number of bytes
245  */
246 /* used only by ssl3_read_bytes */
247 static int ssl3_get_record(SSL *s)
248         {
249         int ssl_major,ssl_minor,al;
250         int enc_err,n,i,ret= -1;
251         SSL3_RECORD *rr;
252         SSL_SESSION *sess;
253         unsigned char *p;
254         unsigned char md[EVP_MAX_MD_SIZE];
255         short version;
256         unsigned mac_size, orig_len;
257         size_t extra;
258         unsigned empty_record_count = 0;
259
260         rr= &(s->s3->rrec);
261         sess=s->session;
262
263         if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)
264                 extra=SSL3_RT_MAX_EXTRA;
265         else
266                 extra=0;
267         if (extra != s->s3->rbuf.len - SSL3_RT_MAX_PACKET_SIZE)
268                 {
269                 /* actually likely an application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER
270                  * set after ssl3_setup_buffers() was done */
271                 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
272                 return -1;
273                 }
274
275 again:
276         /* check if we have the header */
277         if (    (s->rstate != SSL_ST_READ_BODY) ||
278                 (s->packet_length < SSL3_RT_HEADER_LENGTH)) 
279                 {
280                 n=ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
281                 if (n <= 0) return(n); /* error or non-blocking */
282                 s->rstate=SSL_ST_READ_BODY;
283
284                 p=s->packet;
285
286                 /* Pull apart the header into the SSL3_RECORD */
287                 rr->type= *(p++);
288                 ssl_major= *(p++);
289                 ssl_minor= *(p++);
290                 version=(ssl_major<<8)|ssl_minor;
291                 n2s(p,rr->length);
292
293                 /* Lets check version */
294                 if (!s->first_packet)
295                         {
296                         if (version != s->version)
297                                 {
298                                 SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);
299                                 if ((s->version & 0xFF00) == (version & 0xFF00))
300                                         /* Send back error using their minor version number :-) */
301                                         s->version = (unsigned short)version;
302                                 al=SSL_AD_PROTOCOL_VERSION;
303                                 goto f_err;
304                                 }
305                         }
306
307                 if ((version>>8) != SSL3_VERSION_MAJOR)
308                         {
309                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);
310                         goto err;
311                         }
312
313                 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH+extra)
314                         {
315                         al=SSL_AD_RECORD_OVERFLOW;
316                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PACKET_LENGTH_TOO_LONG);
317                         goto f_err;
318                         }
319
320                 /* now s->rstate == SSL_ST_READ_BODY */
321                 }
322
323         /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
324
325         if (rr->length > s->packet_length-SSL3_RT_HEADER_LENGTH)
326                 {
327                 /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
328                 i=rr->length;
329                 n=ssl3_read_n(s,i,i,1);
330                 if (n <= 0) return(n); /* error or non-blocking io */
331                 /* now n == rr->length,
332                  * and s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length */
333                 }
334
335         s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
336
337         /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
338          * and we have that many bytes in s->packet
339          */
340         rr->input= &(s->packet[SSL3_RT_HEADER_LENGTH]);
341
342         /* ok, we can now read from 's->packet' data into 'rr'
343          * rr->input points at rr->length bytes, which
344          * need to be copied into rr->data by either
345          * the decryption or by the decompression
346          * When the data is 'copied' into the rr->data buffer,
347          * rr->input will be pointed at the new buffer */ 
348
349         /* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
350          * rr->length bytes of encrypted compressed stuff. */
351
352         /* check is not needed I believe */
353         if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH+extra)
354                 {
355                 al=SSL_AD_RECORD_OVERFLOW;
356                 SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
357                 goto f_err;
358                 }
359
360         /* decrypt in place in 'rr->input' */
361         rr->data=rr->input;
362
363         enc_err = s->method->ssl3_enc->enc(s,0);
364         /* enc_err is:
365          *    0: (in non-constant time) if the record is publically invalid.
366          *    1: if the padding is valid
367          *    -1: if the padding is invalid */
368         if (enc_err == 0)
369                 {
370                 al=SSL_AD_DECRYPTION_FAILED;
371                 SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_BLOCK_CIPHER_PAD_IS_WRONG);
372                 goto f_err;
373                 }
374
375 #ifdef TLS_DEBUG
376 printf("dec %d\n",rr->length);
377 { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); }
378 printf("\n");
379 #endif
380
381         /* r->length is now the compressed data plus mac */
382         if ((sess != NULL) &&
383             (s->enc_read_ctx != NULL) &&
384             (s->read_hash != NULL))
385                 {
386                 /* s->read_hash != NULL => mac_size != -1 */
387                 unsigned char *mac = NULL;
388                 unsigned char mac_tmp[EVP_MAX_MD_SIZE];
389                 mac_size=EVP_MD_size(s->read_hash);
390                 OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
391
392                 /* kludge: *_cbc_remove_padding passes padding length in rr->type */
393                 orig_len = rr->length+((unsigned int)rr->type>>8);
394
395                 /* orig_len is the length of the record before any padding was
396                  * removed. This is public information, as is the MAC in use,
397                  * therefore we can safely process the record in a different
398                  * amount of time if it's too short to possibly contain a MAC.
399                  */
400                 if (orig_len < mac_size ||
401                     /* CBC records must have a padding length byte too. */
402                     (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
403                      orig_len < mac_size+1))
404                         {
405                         al=SSL_AD_DECODE_ERROR;
406                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_LENGTH_TOO_SHORT);
407                         goto f_err;
408                         }
409
410                 if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE)
411                         {
412                         /* We update the length so that the TLS header bytes
413                          * can be constructed correctly but we need to extract
414                          * the MAC in constant time from within the record,
415                          * without leaking the contents of the padding bytes.
416                          * */
417                         mac = mac_tmp;
418                         ssl3_cbc_copy_mac(mac_tmp, rr, mac_size, orig_len);
419                         rr->length -= mac_size;
420                         }
421                 else
422                         {
423                         /* In this case there's no padding, so |orig_len|
424                          * equals |rec->length| and we checked that there's
425                          * enough bytes for |mac_size| above. */
426                         rr->length -= mac_size;
427                         mac = &rr->data[rr->length];
428                         }
429
430                 i=s->method->ssl3_enc->mac(s,md,0 /* not send */);
431                 if (i < 0 || mac == NULL || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
432                         enc_err = -1;
433                 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra+mac_size)
434                         enc_err = -1;
435                 }
436
437         if (enc_err < 0)
438                 {
439                 /* A separate 'decryption_failed' alert was introduced with TLS 1.0,
440                  * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
441                  * failure is directly visible from the ciphertext anyway,
442                  * we should not reveal which kind of error occured -- this
443                  * might become visible to an attacker (e.g. via a logfile) */
444                 al=SSL_AD_BAD_RECORD_MAC;
445                 SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
446                 goto f_err;
447                 }
448
449         /* r->length is now just compressed */
450         if (s->expand != NULL)
451                 {
452                 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra)
453                         {
454                         al=SSL_AD_RECORD_OVERFLOW;
455                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG);
456                         goto f_err;
457                         }
458                 if (!ssl3_do_uncompress(s))
459                         {
460                         al=SSL_AD_DECOMPRESSION_FAILURE;
461                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_BAD_DECOMPRESSION);
462                         goto f_err;
463                         }
464                 }
465
466         if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH+extra)
467                 {
468                 al=SSL_AD_RECORD_OVERFLOW;
469                 SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DATA_LENGTH_TOO_LONG);
470                 goto f_err;
471                 }
472
473         rr->off=0;
474         /* So at this point the following is true
475          * ssl->s3->rrec.type   is the type of record
476          * ssl->s3->rrec.length == number of bytes in record
477          * ssl->s3->rrec.off    == offset to first valid byte
478          * ssl->s3->rrec.data   == where to take bytes from, increment
479          *                         after use :-).
480          */
481
482         /* we have pulled in a full packet so zero things */
483         s->packet_length=0;
484
485         /* just read a 0 length packet */
486         if (rr->length == 0)
487                 {
488                 empty_record_count++;
489                 if (empty_record_count > MAX_EMPTY_RECORDS)
490                         {
491                         al=SSL_AD_UNEXPECTED_MESSAGE;
492                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_RECORD_TOO_SMALL);
493                         goto f_err;
494                         }
495                 goto again;
496                 }
497
498         return(1);
499
500 f_err:
501         ssl3_send_alert(s,SSL3_AL_FATAL,al);
502 err:
503         return(ret);
504         }
505
506 int ssl3_do_uncompress(SSL *ssl)
507         {
508 #ifndef OPENSSL_NO_COMP
509         int i;
510         SSL3_RECORD *rr;
511
512         rr= &(ssl->s3->rrec);
513         i=COMP_expand_block(ssl->expand,rr->comp,
514                 SSL3_RT_MAX_PLAIN_LENGTH,rr->data,(int)rr->length);
515         if (i < 0)
516                 return(0);
517         else
518                 rr->length=i;
519         rr->data=rr->comp;
520 #endif
521         return(1);
522         }
523
524 int ssl3_do_compress(SSL *ssl)
525         {
526 #ifndef OPENSSL_NO_COMP
527         int i;
528         SSL3_RECORD *wr;
529
530         wr= &(ssl->s3->wrec);
531         i=COMP_compress_block(ssl->compress,wr->data,
532                 SSL3_RT_MAX_COMPRESSED_LENGTH,
533                 wr->input,(int)wr->length);
534         if (i < 0)
535                 return(0);
536         else
537                 wr->length=i;
538
539         wr->input=wr->data;
540 #endif
541         return(1);
542         }
543
544 /* Call this to write data in records of type 'type'
545  * It will return <= 0 if not all data has been sent or non-blocking IO.
546  */
547 int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
548         {
549         const unsigned char *buf=buf_;
550         unsigned int n,nw;
551         int i,tot;
552
553         s->rwstate=SSL_NOTHING;
554         OPENSSL_assert(s->s3->wnum <= INT_MAX);
555         tot=s->s3->wnum;
556         s->s3->wnum=0;
557
558         if (SSL_in_init(s) && !s->in_handshake)
559                 {
560                 i=s->handshake_func(s);
561                 if (i < 0) return(i);
562                 if (i == 0)
563                         {
564                         SSLerr(SSL_F_SSL3_WRITE_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
565                         return -1;
566                         }
567                 }
568
569         /* ensure that if we end up with a smaller value of data to write 
570          * out than the the original len from a write which didn't complete 
571          * for non-blocking I/O and also somehow ended up avoiding 
572          * the check for this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as
573          * it must never be possible to end up with (len-tot) as a large
574          * number that will then promptly send beyond the end of the users
575          * buffer ... so we trap and report the error in a way the user
576          * will notice
577          */
578         if (len < tot)
579                 {
580                 SSLerr(SSL_F_SSL3_WRITE_BYTES,SSL_R_BAD_LENGTH);
581                 return(-1);
582                 }
583
584
585         n=(len-tot);
586         for (;;)
587                 {
588                 if (n > SSL3_RT_MAX_PLAIN_LENGTH)
589                         nw=SSL3_RT_MAX_PLAIN_LENGTH;
590                 else
591                         nw=n;
592
593                 i=do_ssl3_write(s, type, &(buf[tot]), nw, 0);
594                 if (i <= 0)
595                         {
596                         s->s3->wnum=tot;
597                         return i;
598                         }
599
600                 if ((i == (int)n) ||
601                         (type == SSL3_RT_APPLICATION_DATA &&
602                          (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE)))
603                         {
604                         /* next chunk of data should get another prepended empty fragment
605                          * in ciphersuites with known-IV weakness: */
606                         s->s3->empty_fragment_done = 0;
607                         
608                         return tot+i;
609                         }
610
611                 n-=i;
612                 tot+=i;
613                 }
614         }
615
616 static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
617                          unsigned int len, int create_empty_fragment)
618         {
619         unsigned char *p,*plen;
620         int i,mac_size,clear=0;
621         int prefix_len = 0;
622         SSL3_RECORD *wr;
623         SSL3_BUFFER *wb;
624         SSL_SESSION *sess;
625
626         /* first check if there is a SSL3_BUFFER still being written
627          * out.  This will happen with non blocking IO */
628         if (s->s3->wbuf.left != 0)
629                 return(ssl3_write_pending(s,type,buf,len));
630
631         /* If we have an alert to send, lets send it */
632         if (s->s3->alert_dispatch)
633                 {
634                 i=s->method->ssl_dispatch_alert(s);
635                 if (i <= 0)
636                         return(i);
637                 /* if it went, fall through and send more stuff */
638                 }
639
640         if (len == 0 && !create_empty_fragment)
641                 return 0;
642
643         wr= &(s->s3->wrec);
644         wb= &(s->s3->wbuf);
645         sess=s->session;
646
647         if (    (sess == NULL) ||
648                 (s->enc_write_ctx == NULL) ||
649                 (s->write_hash == NULL))
650                 clear=1;
651
652         if (clear)
653                 mac_size=0;
654         else
655                 mac_size=EVP_MD_size(s->write_hash);
656
657         /* 'create_empty_fragment' is true only when this function calls itself */
658         if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done)
659                 {
660                 /* countermeasure against known-IV weakness in CBC ciphersuites
661                  * (see http://www.openssl.org/~bodo/tls-cbc.txt) */
662
663                 if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA)
664                         {
665                         /* recursive function call with 'create_empty_fragment' set;
666                          * this prepares and buffers the data for an empty fragment
667                          * (these 'prefix_len' bytes are sent out later
668                          * together with the actual payload) */
669                         prefix_len = do_ssl3_write(s, type, buf, 0, 1);
670                         if (prefix_len <= 0)
671                                 goto err;
672
673                         if (s->s3->wbuf.len < (size_t)prefix_len + SSL3_RT_MAX_PACKET_SIZE)
674                                 {
675                                 /* insufficient space */
676                                 SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
677                                 goto err;
678                                 }
679                         }
680                 
681                 s->s3->empty_fragment_done = 1;
682                 }
683
684         p = wb->buf + prefix_len;
685
686         /* write the header */
687
688         *(p++)=type&0xff;
689         wr->type=type;
690
691         *(p++)=(s->version>>8);
692         *(p++)=s->version&0xff;
693
694         /* field where we are to write out packet length */
695         plen=p; 
696         p+=2;
697
698         /* lets setup the record stuff. */
699         wr->data=p;
700         wr->length=(int)len;
701         wr->input=(unsigned char *)buf;
702
703         /* we now 'read' from wr->input, wr->length bytes into
704          * wr->data */
705
706         /* first we compress */
707         if (s->compress != NULL)
708                 {
709                 if (!ssl3_do_compress(s))
710                         {
711                         SSLerr(SSL_F_DO_SSL3_WRITE,SSL_R_COMPRESSION_FAILURE);
712                         goto err;
713                         }
714                 }
715         else
716                 {
717                 memcpy(wr->data,wr->input,wr->length);
718                 wr->input=wr->data;
719                 }
720
721         /* we should still have the output to wr->data and the input
722          * from wr->input.  Length should be wr->length.
723          * wr->data still points in the wb->buf */
724
725         if (mac_size != 0)
726                 {
727                 s->method->ssl3_enc->mac(s,&(p[wr->length]),1);
728                 wr->length+=mac_size;
729                 wr->input=p;
730                 wr->data=p;
731                 }
732
733         /* ssl3_enc can only have an error on read */
734         s->method->ssl3_enc->enc(s,1);
735
736         /* record length after mac and block padding */
737         s2n(wr->length,plen);
738
739         /* we should now have
740          * wr->data pointing to the encrypted data, which is
741          * wr->length long */
742         wr->type=type; /* not needed but helps for debugging */
743         wr->length+=SSL3_RT_HEADER_LENGTH;
744
745         if (create_empty_fragment)
746                 {
747                 /* we are in a recursive call;
748                  * just return the length, don't write out anything here
749                  */
750                 return wr->length;
751                 }
752
753         /* now let's set up wb */
754         wb->left = prefix_len + wr->length;
755         wb->offset = 0;
756
757         /* memorize arguments so that ssl3_write_pending can detect bad write retries later */
758         s->s3->wpend_tot=len;
759         s->s3->wpend_buf=buf;
760         s->s3->wpend_type=type;
761         s->s3->wpend_ret=len;
762
763         /* we now just need to write the buffer */
764         return ssl3_write_pending(s,type,buf,len);
765 err:
766         return -1;
767         }
768
769 /* if s->s3->wbuf.left != 0, we need to call this */
770 int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
771         unsigned int len)
772         {
773         int i;
774
775 /* XXXX */
776         if ((s->s3->wpend_tot > (int)len)
777                 || ((s->s3->wpend_buf != buf) &&
778                         !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
779                 || (s->s3->wpend_type != type))
780                 {
781                 SSLerr(SSL_F_SSL3_WRITE_PENDING,SSL_R_BAD_WRITE_RETRY);
782                 return(-1);
783                 }
784
785         for (;;)
786                 {
787                 clear_sys_error();
788                 if (s->wbio != NULL)
789                         {
790                         s->rwstate=SSL_WRITING;
791                         i=BIO_write(s->wbio,
792                                 (char *)&(s->s3->wbuf.buf[s->s3->wbuf.offset]),
793                                 (unsigned int)s->s3->wbuf.left);
794                         }
795                 else
796                         {
797                         SSLerr(SSL_F_SSL3_WRITE_PENDING,SSL_R_BIO_NOT_SET);
798                         i= -1;
799                         }
800                 if (i == s->s3->wbuf.left)
801                         {
802                         s->s3->wbuf.left=0;
803                         s->rwstate=SSL_NOTHING;
804                         return(s->s3->wpend_ret);
805                         }
806                 else if (i <= 0) {
807                         if (s->version == DTLS1_VERSION ||
808                             s->version == DTLS1_BAD_VER) {
809                                 /* For DTLS, just drop it. That's kind of the whole
810                                    point in using a datagram service */
811                                 s->s3->wbuf.left = 0;
812                         }
813                         return(i);
814                 }
815                 s->s3->wbuf.offset+=i;
816                 s->s3->wbuf.left-=i;
817                 }
818         }
819
820 /* Return up to 'len' payload bytes received in 'type' records.
821  * 'type' is one of the following:
822  *
823  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
824  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
825  *   -  0 (during a shutdown, no data has to be returned)
826  *
827  * If we don't have stored data to work from, read a SSL/TLS record first
828  * (possibly multiple records if we still don't have anything to return).
829  *
830  * This function must handle any surprises the peer may have for us, such as
831  * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
832  * a surprise, but handled as if it were), or renegotiation requests.
833  * Also if record payloads contain fragments too small to process, we store
834  * them until there is enough for the respective protocol (the record protocol
835  * may use arbitrary fragmentation and even interleaving):
836  *     Change cipher spec protocol
837  *             just 1 byte needed, no need for keeping anything stored
838  *     Alert protocol
839  *             2 bytes needed (AlertLevel, AlertDescription)
840  *     Handshake protocol
841  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
842  *             to detect unexpected Client Hello and Hello Request messages
843  *             here, anything else is handled by higher layers
844  *     Application data protocol
845  *             none of our business
846  */
847 int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
848         {
849         int al,i,j,ret;
850         unsigned int n;
851         SSL3_RECORD *rr;
852         void (*cb)(const SSL *ssl,int type2,int val)=NULL;
853
854         if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
855                 if (!ssl3_setup_buffers(s))
856                         return(-1);
857
858         if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE)) ||
859             (peek && (type != SSL3_RT_APPLICATION_DATA)))
860                 {
861                 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
862                 return -1;
863                 }
864
865         if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0))
866                 /* (partially) satisfy request from storage */
867                 {
868                 unsigned char *src = s->s3->handshake_fragment;
869                 unsigned char *dst = buf;
870                 unsigned int k;
871
872                 /* peek == 0 */
873                 n = 0;
874                 while ((len > 0) && (s->s3->handshake_fragment_len > 0))
875                         {
876                         *dst++ = *src++;
877                         len--; s->s3->handshake_fragment_len--;
878                         n++;
879                         }
880                 /* move any remaining fragment bytes: */
881                 for (k = 0; k < s->s3->handshake_fragment_len; k++)
882                         s->s3->handshake_fragment[k] = *src++;
883                 return n;
884         }
885
886         /* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
887
888         if (!s->in_handshake && SSL_in_init(s))
889                 {
890                 /* type == SSL3_RT_APPLICATION_DATA */
891                 i=s->handshake_func(s);
892                 if (i < 0) return(i);
893                 if (i == 0)
894                         {
895                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
896                         return(-1);
897                         }
898                 }
899 start:
900         s->rwstate=SSL_NOTHING;
901
902         /* s->s3->rrec.type         - is the type of record
903          * s->s3->rrec.data,    - data
904          * s->s3->rrec.off,     - offset into 'data' for next read
905          * s->s3->rrec.length,  - number of bytes. */
906         rr = &(s->s3->rrec);
907
908         /* get new packet if necessary */
909         if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))
910                 {
911                 ret=ssl3_get_record(s);
912                 if (ret <= 0) return(ret);
913                 }
914
915         /* we now have a packet which can be read and processed */
916
917         if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
918                                        * reset by ssl3_get_finished */
919                 && (rr->type != SSL3_RT_HANDSHAKE))
920                 {
921                 al=SSL_AD_UNEXPECTED_MESSAGE;
922                 SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
923                 goto f_err;
924                 }
925
926         /* If the other end has shut down, throw anything we read away
927          * (even in 'peek' mode) */
928         if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
929                 {
930                 rr->length=0;
931                 s->rwstate=SSL_NOTHING;
932                 return(0);
933                 }
934
935
936         if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
937                 {
938                 /* make sure that we are not getting application data when we
939                  * are doing a handshake for the first time */
940                 if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
941                         (s->enc_read_ctx == NULL))
942                         {
943                         al=SSL_AD_UNEXPECTED_MESSAGE;
944                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_APP_DATA_IN_HANDSHAKE);
945                         goto f_err;
946                         }
947
948                 if (len <= 0) return(len);
949
950                 if ((unsigned int)len > rr->length)
951                         n = rr->length;
952                 else
953                         n = (unsigned int)len;
954
955                 memcpy(buf,&(rr->data[rr->off]),n);
956                 if (!peek)
957                         {
958                         rr->length-=n;
959                         rr->off+=n;
960                         if (rr->length == 0)
961                                 {
962                                 s->rstate=SSL_ST_READ_HEADER;
963                                 rr->off=0;
964                                 }
965                         }
966                 return(n);
967                 }
968
969
970         /* If we get here, then type != rr->type; if we have a handshake
971          * message, then it was unexpected (Hello Request or Client Hello). */
972
973         /* In case of record types for which we have 'fragment' storage,
974          * fill that so that we can process the data at a fixed place.
975          */
976                 {
977                 unsigned int dest_maxlen = 0;
978                 unsigned char *dest = NULL;
979                 unsigned int *dest_len = NULL;
980
981                 if (rr->type == SSL3_RT_HANDSHAKE)
982                         {
983                         dest_maxlen = sizeof s->s3->handshake_fragment;
984                         dest = s->s3->handshake_fragment;
985                         dest_len = &s->s3->handshake_fragment_len;
986                         }
987                 else if (rr->type == SSL3_RT_ALERT)
988                         {
989                         dest_maxlen = sizeof s->s3->alert_fragment;
990                         dest = s->s3->alert_fragment;
991                         dest_len = &s->s3->alert_fragment_len;
992                         }
993
994                 if (dest_maxlen > 0)
995                         {
996                         n = dest_maxlen - *dest_len; /* available space in 'dest' */
997                         if (rr->length < n)
998                                 n = rr->length; /* available bytes */
999
1000                         /* now move 'n' bytes: */
1001                         while (n-- > 0)
1002                                 {
1003                                 dest[(*dest_len)++] = rr->data[rr->off++];
1004                                 rr->length--;
1005                                 }
1006
1007                         if (*dest_len < dest_maxlen)
1008                                 goto start; /* fragment was too small */
1009                         }
1010                 }
1011
1012         /* s->s3->handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
1013          * s->s3->alert_fragment_len == 2      iff  rr->type == SSL3_RT_ALERT.
1014          * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
1015
1016         /* If we are a client, check for an incoming 'Hello Request': */
1017         if ((!s->server) &&
1018                 (s->s3->handshake_fragment_len >= 4) &&
1019                 (s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
1020                 (s->session != NULL) && (s->session->cipher != NULL))
1021                 {
1022                 s->s3->handshake_fragment_len = 0;
1023
1024                 if ((s->s3->handshake_fragment[1] != 0) ||
1025                         (s->s3->handshake_fragment[2] != 0) ||
1026                         (s->s3->handshake_fragment[3] != 0))
1027                         {
1028                         al=SSL_AD_DECODE_ERROR;
1029                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_HELLO_REQUEST);
1030                         goto f_err;
1031                         }
1032
1033                 if (s->msg_callback)
1034                         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->s3->handshake_fragment, 4, s, s->msg_callback_arg);
1035
1036                 if (SSL_is_init_finished(s) &&
1037                         !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
1038                         !s->s3->renegotiate)
1039                         {
1040                         ssl3_renegotiate(s);
1041                         if (ssl3_renegotiate_check(s))
1042                                 {
1043                                 i=s->handshake_func(s);
1044                                 if (i < 0) return(i);
1045                                 if (i == 0)
1046                                         {
1047                                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
1048                                         return(-1);
1049                                         }
1050
1051                                 if (!(s->mode & SSL_MODE_AUTO_RETRY))
1052                                         {
1053                                         if (s->s3->rbuf.left == 0) /* no read-ahead left? */
1054                                                 {
1055                                                 BIO *bio;
1056                                                 /* In the case where we try to read application data,
1057                                                  * but we trigger an SSL handshake, we return -1 with
1058                                                  * the retry option set.  Otherwise renegotiation may
1059                                                  * cause nasty problems in the blocking world */
1060                                                 s->rwstate=SSL_READING;
1061                                                 bio=SSL_get_rbio(s);
1062                                                 BIO_clear_retry_flags(bio);
1063                                                 BIO_set_retry_read(bio);
1064                                                 return(-1);
1065                                                 }
1066                                         }
1067                                 }
1068                         }
1069                 /* we either finished a handshake or ignored the request,
1070                  * now try again to obtain the (application) data we were asked for */
1071                 goto start;
1072                 }
1073         /* If we are a server and get a client hello when renegotiation isn't
1074          * allowed send back a no renegotiation alert and carry on.
1075          * WARNING: experimental code, needs reviewing (steve)
1076          */
1077         if (s->server &&
1078                 SSL_is_init_finished(s) &&
1079                 !s->s3->send_connection_binding &&
1080                 (s->version > SSL3_VERSION) &&
1081                 (s->s3->handshake_fragment_len >= 4) &&
1082                 (s->s3->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO) &&
1083                 (s->session != NULL) && (s->session->cipher != NULL) &&
1084                 !(s->ctx->options & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION))
1085                 
1086                 {
1087                 /*s->s3->handshake_fragment_len = 0;*/
1088                 rr->length = 0;
1089                 ssl3_send_alert(s,SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
1090                 goto start;
1091                 }
1092         if (s->s3->alert_fragment_len >= 2)
1093                 {
1094                 int alert_level = s->s3->alert_fragment[0];
1095                 int alert_descr = s->s3->alert_fragment[1];
1096
1097                 s->s3->alert_fragment_len = 0;
1098
1099                 if (s->msg_callback)
1100                         s->msg_callback(0, s->version, SSL3_RT_ALERT, s->s3->alert_fragment, 2, s, s->msg_callback_arg);
1101
1102                 if (s->info_callback != NULL)
1103                         cb=s->info_callback;
1104                 else if (s->ctx->info_callback != NULL)
1105                         cb=s->ctx->info_callback;
1106
1107                 if (cb != NULL)
1108                         {
1109                         j = (alert_level << 8) | alert_descr;
1110                         cb(s, SSL_CB_READ_ALERT, j);
1111                         }
1112
1113                 if (alert_level == 1) /* warning */
1114                         {
1115                         s->s3->warn_alert = alert_descr;
1116                         if (alert_descr == SSL_AD_CLOSE_NOTIFY)
1117                                 {
1118                                 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1119                                 return(0);
1120                                 }
1121                         /* This is a warning but we receive it if we requested
1122                          * renegotiation and the peer denied it. Terminate with
1123                          * a fatal alert because if application tried to
1124                          * renegotiatie it presumably had a good reason and
1125                          * expects it to succeed.
1126                          *
1127                          * In future we might have a renegotiation where we
1128                          * don't care if the peer refused it where we carry on.
1129                          */
1130                         else if (alert_descr == SSL_AD_NO_RENEGOTIATION)
1131                                 {
1132                                 al = SSL_AD_HANDSHAKE_FAILURE;
1133                                 SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_NO_RENEGOTIATION);
1134                                 goto f_err;
1135                                 }
1136                         }
1137                 else if (alert_level == 2) /* fatal */
1138                         {
1139                         char tmp[16];
1140
1141                         s->rwstate=SSL_NOTHING;
1142                         s->s3->fatal_alert = alert_descr;
1143                         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
1144                         BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr);
1145                         ERR_add_error_data(2,"SSL alert number ",tmp);
1146                         s->shutdown|=SSL_RECEIVED_SHUTDOWN;
1147                         SSL_CTX_remove_session(s->ctx,s->session);
1148                         return(0);
1149                         }
1150                 else
1151                         {
1152                         al=SSL_AD_ILLEGAL_PARAMETER;
1153                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNKNOWN_ALERT_TYPE);
1154                         goto f_err;
1155                         }
1156
1157                 goto start;
1158                 }
1159
1160         if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
1161                 {
1162                 s->rwstate=SSL_NOTHING;
1163                 rr->length=0;
1164                 return(0);
1165                 }
1166
1167         if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
1168                 {
1169                 /* 'Change Cipher Spec' is just a single byte, so we know
1170                  * exactly what the record payload has to look like */
1171                 if (    (rr->length != 1) || (rr->off != 0) ||
1172                         (rr->data[0] != SSL3_MT_CCS))
1173                         {
1174                         al=SSL_AD_ILLEGAL_PARAMETER;
1175                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC);
1176                         goto f_err;
1177                         }
1178
1179                 /* Check we have a cipher to change to */
1180                 if (s->s3->tmp.new_cipher == NULL)
1181                         {
1182                         al=SSL_AD_UNEXPECTED_MESSAGE;
1183                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_CCS_RECEIVED_EARLY);
1184                         goto f_err;
1185                         }
1186
1187                 if (!(s->s3->flags & SSL3_FLAGS_CCS_OK))
1188                         {
1189                         al=SSL_AD_UNEXPECTED_MESSAGE;
1190                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_CCS_RECEIVED_EARLY);
1191                         goto f_err;
1192                         }
1193
1194                 s->s3->flags &= ~SSL3_FLAGS_CCS_OK;
1195
1196                 rr->length=0;
1197
1198                 if (s->msg_callback)
1199                         s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg);
1200
1201                 s->s3->change_cipher_spec=1;
1202                 if (!ssl3_do_change_cipher_spec(s))
1203                         goto err;
1204                 else
1205                         goto start;
1206                 }
1207
1208         /* Unexpected handshake message (Client Hello, or protocol violation) */
1209         if ((s->s3->handshake_fragment_len >= 4) &&     !s->in_handshake)
1210                 {
1211                 if (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&
1212                         !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS))
1213                         {
1214 #if 0 /* worked only because C operator preferences are not as expected (and
1215        * because this is not really needed for clients except for detecting
1216        * protocol violations): */
1217                         s->state=SSL_ST_BEFORE|(s->server)
1218                                 ?SSL_ST_ACCEPT
1219                                 :SSL_ST_CONNECT;
1220 #else
1221                         s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
1222 #endif
1223                         s->new_session=1;
1224                         }
1225                 i=s->handshake_func(s);
1226                 if (i < 0) return(i);
1227                 if (i == 0)
1228                         {
1229                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
1230                         return(-1);
1231                         }
1232
1233                 if (!(s->mode & SSL_MODE_AUTO_RETRY))
1234                         {
1235                         if (s->s3->rbuf.left == 0) /* no read-ahead left? */
1236                                 {
1237                                 BIO *bio;
1238                                 /* In the case where we try to read application data,
1239                                  * but we trigger an SSL handshake, we return -1 with
1240                                  * the retry option set.  Otherwise renegotiation may
1241                                  * cause nasty problems in the blocking world */
1242                                 s->rwstate=SSL_READING;
1243                                 bio=SSL_get_rbio(s);
1244                                 BIO_clear_retry_flags(bio);
1245                                 BIO_set_retry_read(bio);
1246                                 return(-1);
1247                                 }
1248                         }
1249                 goto start;
1250                 }
1251
1252         switch (rr->type)
1253                 {
1254         default:
1255 #ifndef OPENSSL_NO_TLS
1256                 /* TLS just ignores unknown message types */
1257                 if (s->version == TLS1_VERSION)
1258                         {
1259                         rr->length = 0;
1260                         goto start;
1261                         }
1262 #endif
1263                 al=SSL_AD_UNEXPECTED_MESSAGE;
1264                 SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
1265                 goto f_err;
1266         case SSL3_RT_CHANGE_CIPHER_SPEC:
1267         case SSL3_RT_ALERT:
1268         case SSL3_RT_HANDSHAKE:
1269                 /* we already handled all of these, with the possible exception
1270                  * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that
1271                  * should not happen when type != rr->type */
1272                 al=SSL_AD_UNEXPECTED_MESSAGE;
1273                 SSLerr(SSL_F_SSL3_READ_BYTES,ERR_R_INTERNAL_ERROR);
1274                 goto f_err;
1275         case SSL3_RT_APPLICATION_DATA:
1276                 /* At this point, we were expecting handshake data,
1277                  * but have application data.  If the library was
1278                  * running inside ssl3_read() (i.e. in_read_app_data
1279                  * is set) and it makes sense to read application data
1280                  * at this point (session renegotiation not yet started),
1281                  * we will indulge it.
1282                  */
1283                 if (s->s3->in_read_app_data &&
1284                         (s->s3->total_renegotiations != 0) &&
1285                         ((
1286                                 (s->state & SSL_ST_CONNECT) &&
1287                                 (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1288                                 (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
1289                                 ) || (
1290                                         (s->state & SSL_ST_ACCEPT) &&
1291                                         (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
1292                                         (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
1293                                         )
1294                                 ))
1295                         {
1296                         s->s3->in_read_app_data=2;
1297                         return(-1);
1298                         }
1299                 else
1300                         {
1301                         al=SSL_AD_UNEXPECTED_MESSAGE;
1302                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
1303                         goto f_err;
1304                         }
1305                 }
1306         /* not reached */
1307
1308 f_err:
1309         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1310 err:
1311         return(-1);
1312         }
1313
1314 int ssl3_do_change_cipher_spec(SSL *s)
1315         {
1316         int i;
1317         const char *sender;
1318         int slen;
1319
1320         if (s->state & SSL_ST_ACCEPT)
1321                 i=SSL3_CHANGE_CIPHER_SERVER_READ;
1322         else
1323                 i=SSL3_CHANGE_CIPHER_CLIENT_READ;
1324
1325         if (s->s3->tmp.key_block == NULL)
1326                 {
1327                 if (s->session == NULL || s->session->master_key_length == 0)
1328                         {
1329                         /* might happen if dtls1_read_bytes() calls this */
1330                         SSLerr(SSL_F_SSL3_DO_CHANGE_CIPHER_SPEC,SSL_R_CCS_RECEIVED_EARLY);
1331                         return (0);
1332                         }
1333
1334                 s->session->cipher=s->s3->tmp.new_cipher;
1335                 if (!s->method->ssl3_enc->setup_key_block(s)) return(0);
1336                 }
1337
1338         if (!s->method->ssl3_enc->change_cipher_state(s,i))
1339                 return(0);
1340
1341         /* we have to record the message digest at
1342          * this point so we can get it before we read
1343          * the finished message */
1344         if (s->state & SSL_ST_CONNECT)
1345                 {
1346                 sender=s->method->ssl3_enc->server_finished_label;
1347                 slen=s->method->ssl3_enc->server_finished_label_len;
1348                 }
1349         else
1350                 {
1351                 sender=s->method->ssl3_enc->client_finished_label;
1352                 slen=s->method->ssl3_enc->client_finished_label_len;
1353                 }
1354
1355         s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
1356                 &(s->s3->finish_dgst1),
1357                 &(s->s3->finish_dgst2),
1358                 sender,slen,s->s3->tmp.peer_finish_md);
1359
1360         return(1);
1361         }
1362
1363 int ssl3_send_alert(SSL *s, int level, int desc)
1364         {
1365         /* Map tls/ssl alert value to correct one */
1366         desc=s->method->ssl3_enc->alert_value(desc);
1367         if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
1368                 desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have protocol_version alerts */
1369         if (desc < 0) return -1;
1370         /* If a fatal one, remove from cache */
1371         if ((level == 2) && (s->session != NULL))
1372                 SSL_CTX_remove_session(s->ctx,s->session);
1373
1374         s->s3->alert_dispatch=1;
1375         s->s3->send_alert[0]=level;
1376         s->s3->send_alert[1]=desc;
1377         if (s->s3->wbuf.left == 0) /* data still being written out? */
1378                 return s->method->ssl_dispatch_alert(s);
1379         /* else data is still being written out, we will get written
1380          * some time in the future */
1381         return -1;
1382         }
1383
1384 int ssl3_dispatch_alert(SSL *s)
1385         {
1386         int i,j;
1387         void (*cb)(const SSL *ssl,int type,int val)=NULL;
1388
1389         s->s3->alert_dispatch=0;
1390         i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0);
1391         if (i <= 0)
1392                 {
1393                 s->s3->alert_dispatch=1;
1394                 }
1395         else
1396                 {
1397                 /* Alert sent to BIO.  If it is important, flush it now.
1398                  * If the message does not get sent due to non-blocking IO,
1399                  * we will not worry too much. */
1400                 if (s->s3->send_alert[0] == SSL3_AL_FATAL)
1401                         (void)BIO_flush(s->wbio);
1402
1403                 if (s->msg_callback)
1404                         s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s, s->msg_callback_arg);
1405
1406                 if (s->info_callback != NULL)
1407                         cb=s->info_callback;
1408                 else if (s->ctx->info_callback != NULL)
1409                         cb=s->ctx->info_callback;
1410
1411                 if (cb != NULL)
1412                         {
1413                         j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
1414                         cb(s,SSL_CB_WRITE_ALERT,j);
1415                         }
1416                 }
1417         return(i);
1418         }