1d34cec324e19e89aa2b23fc21307e4dfefdafbb
[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 <errno.h>
114 #define USE_SOCKETS
115 #include "ssl_locl.h"
116 #include <openssl/evp.h>
117 #include <openssl/buffer.h>
118
119 static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
120                          unsigned int len, int create_empty_fragment);
121 static int ssl3_get_record(SSL *s);
122
123 int ssl3_read_n(SSL *s, int n, int max, int extend)
124         {
125         /* If extend == 0, obtain new n-byte packet; if extend == 1, increase
126          * packet by another n bytes.
127          * The packet will be in the sub-array of s->s3->rbuf.buf specified
128          * by s->packet and s->packet_length.
129          * (If s->read_ahead is set, 'max' bytes may be stored in rbuf
130          * [plus s->packet_length bytes if extend == 1].)
131          */
132         int i,len,left,align=0;
133         unsigned char *pkt;
134         SSL3_BUFFER *rb;
135
136         if (n <= 0) return n;
137
138         rb    = &(s->s3->rbuf);
139         left  = rb->left;
140 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
141         align = (int)rb->buf + SSL3_RT_HEADER_LENGTH;
142         align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
143 #endif
144
145         if (!extend)
146                 {
147                 /* start with empty packet ... */
148                 if (left == 0)
149                         rb->offset = align;
150                 else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH)
151                         {
152                         /* check if next packet length is large
153                          * enough to justify payload alignment... */
154                         pkt = rb->buf + rb->offset;
155                         if (pkt[0] == SSL3_RT_APPLICATION_DATA
156                             && (pkt[3]<<8|pkt[4]) >= 128)
157                                 {
158                                 /* Note that even if packet is corrupted
159                                  * and its length field is insane, we can
160                                  * only be led to wrong decision about
161                                  * whether memmove will occur or not.
162                                  * Header values has no effect on memmove
163                                  * arguments and therefore no buffer
164                                  * overrun can be triggered. */
165                                 memmove (rb->buf+align,pkt,left);
166                                 rb->offset = align;
167                                 }
168                         }
169                 s->packet = rb->buf + rb->offset;
170                 s->packet_length = 0;
171                 /* ... now we can act as if 'extend' was set */
172                 }
173
174         /* extend reads should not span multiple packets for DTLS */
175         if ( SSL_version(s) == DTLS1_VERSION &&
176                 extend)
177                 {
178                 if ( left > 0 && n > left)
179                         n = left;
180                 }
181
182         /* if there is enough in the buffer from a previous read, take some */
183         if (left >= n)
184                 {
185                 s->packet_length+=n;
186                 rb->left=left-n;
187                 rb->offset+=n;
188                 return(n);
189                 }
190
191         /* else we need to read more data */
192
193         len = s->packet_length;
194         pkt = rb->buf+align;
195         /* Move any available bytes to front of buffer:
196          * 'len' bytes already pointed to by 'packet',
197          * 'left' extra ones at the end */
198         if (s->packet != pkt) /* len > 0 */
199                 {
200                 memmove(pkt, s->packet, len+left);
201                 s->packet = pkt;
202                 rb->offset = len + align;
203                 }
204
205         max = rb->len - rb->offset;
206         if (n > max) /* does not happen */
207                 {
208                 SSLerr(SSL_F_SSL3_READ_N,ERR_R_INTERNAL_ERROR);
209                 return -1;
210                 }
211
212         if (!s->read_ahead)
213                 max=n;
214
215         while (left < n)
216                 {
217                 /* Now we have len+left bytes at the front of s->s3->rbuf.buf
218                  * and need to read in more until we have len+n (up to
219                  * len+max if possible) */
220
221                 clear_sys_error();
222                 if (s->rbio != NULL)
223                         {
224                         s->rwstate=SSL_READING;
225                         i=BIO_read(s->rbio,pkt+len+left, max-left);
226                         }
227                 else
228                         {
229                         SSLerr(SSL_F_SSL3_READ_N,SSL_R_READ_BIO_NOT_SET);
230                         i = -1;
231                         }
232
233                 if (i <= 0)
234                         {
235                         rb->left = left;
236                         return(i);
237                         }
238                 left+=i;
239                 }
240
241         /* done reading, now the book-keeping */
242         rb->offset += n;
243         rb->left = left - n;
244         s->packet_length += n;
245         s->rwstate=SSL_NOTHING;
246         return(n);
247         }
248
249 /* Call this to get a new input record.
250  * It will return <= 0 if more data is needed, normally due to an error
251  * or non-blocking IO.
252  * When it finishes, one packet has been decoded and can be found in
253  * ssl->s3->rrec.type    - is the type of record
254  * ssl->s3->rrec.data,   - data
255  * ssl->s3->rrec.length, - number of bytes
256  */
257 /* used only by ssl3_read_bytes */
258 static int ssl3_get_record(SSL *s)
259         {
260         int ssl_major,ssl_minor,al;
261         int enc_err,n,i,ret= -1;
262         SSL3_RECORD *rr;
263         SSL_SESSION *sess;
264         unsigned char *p;
265         unsigned char md[EVP_MAX_MD_SIZE];
266         short version;
267         unsigned int mac_size;
268         int clear=0;
269         size_t extra;
270         int decryption_failed_or_bad_record_mac = 0;
271         unsigned char *mac = NULL;
272
273         rr= &(s->s3->rrec);
274         sess=s->session;
275
276         if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)
277                 extra=SSL3_RT_MAX_EXTRA;
278         else
279                 extra=0;
280         if (extra && !s->s3->init_extra)
281                 {
282                 /* An application error: SLS_OP_MICROSOFT_BIG_SSLV3_BUFFER
283                  * set after ssl3_setup_buffers() was done */
284                 SSLerr(SSL_F_SSL3_GET_RECORD, ERR_R_INTERNAL_ERROR);
285                 return -1;
286                 }
287
288 again:
289         /* check if we have the header */
290         if (    (s->rstate != SSL_ST_READ_BODY) ||
291                 (s->packet_length < SSL3_RT_HEADER_LENGTH)) 
292                 {
293                 n=ssl3_read_n(s, SSL3_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
294                 if (n <= 0) return(n); /* error or non-blocking */
295                 s->rstate=SSL_ST_READ_BODY;
296
297                 p=s->packet;
298
299                 /* Pull apart the header into the SSL3_RECORD */
300                 rr->type= *(p++);
301                 ssl_major= *(p++);
302                 ssl_minor= *(p++);
303                 version=(ssl_major<<8)|ssl_minor;
304                 n2s(p,rr->length);
305 #if 0
306 fprintf(stderr, "Record type=%d, Length=%d\n", rr->type, rr->length);
307 #endif
308
309                 /* Lets check version */
310                 if (s->first_packet)
311                         {
312                         s->first_packet=0;
313                         }
314                 else
315                         {
316                         if (version != s->version)
317                                 {
318                                 SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);
319                                 /* Send back error using their
320                                  * version number :-) */
321                                 s->version=version;
322                                 al=SSL_AD_PROTOCOL_VERSION;
323                                 goto f_err;
324                                 }
325                         }
326
327                 if ((version>>8) != SSL3_VERSION_MAJOR)
328                         {
329                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);
330                         goto err;
331                         }
332
333                 if (rr->length > s->s3->rbuf.len - SSL3_RT_HEADER_LENGTH)
334                         {
335                         al=SSL_AD_RECORD_OVERFLOW;
336                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PACKET_LENGTH_TOO_LONG);
337                         goto f_err;
338                         }
339
340                 /* now s->rstate == SSL_ST_READ_BODY */
341                 }
342
343         /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
344
345         if (rr->length > s->packet_length-SSL3_RT_HEADER_LENGTH)
346                 {
347                 /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
348                 i=rr->length;
349                 n=ssl3_read_n(s,i,i,1);
350                 if (n <= 0) return(n); /* error or non-blocking io */
351                 /* now n == rr->length,
352                  * and s->packet_length == SSL3_RT_HEADER_LENGTH + rr->length */
353                 }
354
355         s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
356
357         /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
358          * and we have that many bytes in s->packet
359          */
360         rr->input= &(s->packet[SSL3_RT_HEADER_LENGTH]);
361
362         /* ok, we can now read from 's->packet' data into 'rr'
363          * rr->input points at rr->length bytes, which
364          * need to be copied into rr->data by either
365          * the decryption or by the decompression
366          * When the data is 'copied' into the rr->data buffer,
367          * rr->input will be pointed at the new buffer */ 
368
369         /* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
370          * rr->length bytes of encrypted compressed stuff. */
371
372         /* check is not needed I believe */
373         if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH+extra)
374                 {
375                 al=SSL_AD_RECORD_OVERFLOW;
376                 SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
377                 goto f_err;
378                 }
379
380         /* decrypt in place in 'rr->input' */
381         rr->data=rr->input;
382
383         enc_err = s->method->ssl3_enc->enc(s,0);
384         if (enc_err <= 0)
385                 {
386                 if (enc_err == 0)
387                         /* SSLerr() and ssl3_send_alert() have been called */
388                         goto err;
389
390                 /* Otherwise enc_err == -1, which indicates bad padding
391                  * (rec->length has not been changed in this case).
392                  * To minimize information leaked via timing, we will perform
393                  * the MAC computation anyway. */
394                 decryption_failed_or_bad_record_mac = 1;
395                 }
396
397 #ifdef TLS_DEBUG
398 printf("dec %d\n",rr->length);
399 { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); }
400 printf("\n");
401 #endif
402
403         /* r->length is now the compressed data plus mac */
404         if (    (sess == NULL) ||
405                 (s->enc_read_ctx == NULL) ||
406                 (s->read_hash == NULL))
407                 clear=1;
408
409         if (!clear)
410                 {
411                 mac_size=EVP_MD_size(s->read_hash);
412
413                 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra+mac_size)
414                         {
415 #if 0 /* OK only for stream ciphers (then rr->length is visible from ciphertext anyway) */
416                         al=SSL_AD_RECORD_OVERFLOW;
417                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PRE_MAC_LENGTH_TOO_LONG);
418                         goto f_err;
419 #else
420                         decryption_failed_or_bad_record_mac = 1;
421 #endif                  
422                         }
423                 /* check the MAC for rr->input (it's in mac_size bytes at the tail) */
424                 if (rr->length >= mac_size)
425                         {
426                         rr->length -= mac_size;
427                         mac = &rr->data[rr->length];
428                         }
429                 else
430                         {
431                         /* record (minus padding) is too short to contain a MAC */
432 #if 0 /* OK only for stream ciphers */
433                         al=SSL_AD_DECODE_ERROR;
434                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_LENGTH_TOO_SHORT);
435                         goto f_err;
436 #else
437                         decryption_failed_or_bad_record_mac = 1;
438                         rr->length = 0;
439 #endif
440                         }
441                 i=s->method->ssl3_enc->mac(s,md,0);
442                 if (mac == NULL || memcmp(md, mac, mac_size) != 0)
443                         {
444                         decryption_failed_or_bad_record_mac = 1;
445                         }
446                 }
447
448         if (decryption_failed_or_bad_record_mac)
449                 {
450                 /* A separate 'decryption_failed' alert was introduced with TLS 1.0,
451                  * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
452                  * failure is directly visible from the ciphertext anyway,
453                  * we should not reveal which kind of error occured -- this
454                  * might become visible to an attacker (e.g. via a logfile) */
455                 al=SSL_AD_BAD_RECORD_MAC;
456                 SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
457                 goto f_err;
458                 }
459
460         /* r->length is now just compressed */
461         if (s->expand != NULL)
462                 {
463                 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra)
464                         {
465                         al=SSL_AD_RECORD_OVERFLOW;
466                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG);
467                         goto f_err;
468                         }
469                 if (!ssl3_do_uncompress(s))
470                         {
471                         al=SSL_AD_DECOMPRESSION_FAILURE;
472                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_BAD_DECOMPRESSION);
473                         goto f_err;
474                         }
475                 }
476
477         if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH+extra)
478                 {
479                 al=SSL_AD_RECORD_OVERFLOW;
480                 SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DATA_LENGTH_TOO_LONG);
481                 goto f_err;
482                 }
483
484         rr->off=0;
485         /* So at this point the following is true
486          * ssl->s3->rrec.type   is the type of record
487          * ssl->s3->rrec.length == number of bytes in record
488          * ssl->s3->rrec.off    == offset to first valid byte
489          * ssl->s3->rrec.data   == where to take bytes from, increment
490          *                         after use :-).
491          */
492
493         /* we have pulled in a full packet so zero things */
494         s->packet_length=0;
495
496         /* just read a 0 length packet */
497         if (rr->length == 0) goto again;
498
499 #if 0
500 fprintf(stderr, "Ultimate Record type=%d, Length=%d\n", rr->type, rr->length);
501 #endif
502
503         return(1);
504
505 f_err:
506         ssl3_send_alert(s,SSL3_AL_FATAL,al);
507 err:
508         return(ret);
509         }
510
511 int ssl3_do_uncompress(SSL *ssl)
512         {
513 #ifndef OPENSSL_NO_COMP
514         int i;
515         SSL3_RECORD *rr;
516
517         rr= &(ssl->s3->rrec);
518         i=COMP_expand_block(ssl->expand,rr->comp,
519                 SSL3_RT_MAX_PLAIN_LENGTH,rr->data,(int)rr->length);
520         if (i < 0)
521                 return(0);
522         else
523                 rr->length=i;
524         rr->data=rr->comp;
525 #endif
526         return(1);
527         }
528
529 int ssl3_do_compress(SSL *ssl)
530         {
531 #ifndef OPENSSL_NO_COMP
532         int i;
533         SSL3_RECORD *wr;
534
535         wr= &(ssl->s3->wrec);
536         i=COMP_compress_block(ssl->compress,wr->data,
537                 SSL3_RT_MAX_COMPRESSED_LENGTH,
538                 wr->input,(int)wr->length);
539         if (i < 0)
540                 return(0);
541         else
542                 wr->length=i;
543
544         wr->input=wr->data;
545 #endif
546         return(1);
547         }
548
549 /* Call this to write data in records of type 'type'
550  * It will return <= 0 if not all data has been sent or non-blocking IO.
551  */
552 int ssl3_write_bytes(SSL *s, int type, const void *buf_, int len)
553         {
554         const unsigned char *buf=buf_;
555         unsigned int tot,n,nw;
556         int i;
557
558         s->rwstate=SSL_NOTHING;
559         tot=s->s3->wnum;
560         s->s3->wnum=0;
561
562         if (SSL_in_init(s) && !s->in_handshake)
563                 {
564                 i=s->handshake_func(s);
565                 if (i < 0) return(i);
566                 if (i == 0)
567                         {
568                         SSLerr(SSL_F_SSL3_WRITE_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
569                         return -1;
570                         }
571                 }
572
573         n=(len-tot);
574         for (;;)
575                 {
576                 if (n > s->max_send_fragment)
577                         nw=s->max_send_fragment;
578                 else
579                         nw=n;
580
581                 i=do_ssl3_write(s, type, &(buf[tot]), nw, 0);
582                 if (i <= 0)
583                         {
584                         s->s3->wnum=tot;
585                         return i;
586                         }
587
588                 if ((i == (int)n) ||
589                         (type == SSL3_RT_APPLICATION_DATA &&
590                          (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE)))
591                         {
592                         /* next chunk of data should get another prepended empty fragment
593                          * in ciphersuites with known-IV weakness: */
594                         s->s3->empty_fragment_done = 0;
595                         
596                         return tot+i;
597                         }
598
599                 n-=i;
600                 tot+=i;
601                 }
602         }
603
604 static int do_ssl3_write(SSL *s, int type, const unsigned char *buf,
605                          unsigned int len, int create_empty_fragment)
606         {
607         unsigned char *p,*plen;
608         int i,mac_size,clear=0;
609         int prefix_len=0,align=0;
610         SSL3_RECORD *wr;
611         SSL3_BUFFER *wb=&(s->s3->wbuf);
612         SSL_SESSION *sess;
613
614         /* first check if there is a SSL3_BUFFER still being written
615          * out.  This will happen with non blocking IO */
616         if (wb->left != 0)
617                 return(ssl3_write_pending(s,type,buf,len));
618
619         /* If we have an alert to send, lets send it */
620         if (s->s3->alert_dispatch)
621                 {
622                 i=s->method->ssl_dispatch_alert(s);
623                 if (i <= 0)
624                         return(i);
625                 /* if it went, fall through and send more stuff */
626                 }
627
628         if (len == 0 && !create_empty_fragment)
629                 return 0;
630
631         wr= &(s->s3->wrec);
632         sess=s->session;
633
634         if (    (sess == NULL) ||
635                 (s->enc_write_ctx == NULL) ||
636                 (s->write_hash == NULL))
637                 clear=1;
638
639         if (clear)
640                 mac_size=0;
641         else
642                 mac_size=EVP_MD_size(s->write_hash);
643
644         /* 'create_empty_fragment' is true only when this function calls itself */
645         if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done)
646                 {
647                 /* countermeasure against known-IV weakness in CBC ciphersuites
648                  * (see http://www.openssl.org/~bodo/tls-cbc.txt) */
649
650                 if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA)
651                         {
652                         /* recursive function call with 'create_empty_fragment' set;
653                          * this prepares and buffers the data for an empty fragment
654                          * (these 'prefix_len' bytes are sent out later
655                          * together with the actual payload) */
656                         prefix_len = do_ssl3_write(s, type, buf, 0, 1);
657                         if (prefix_len <= 0)
658                                 goto err;
659
660                         if (prefix_len >
661                 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD))
662                                 {
663                                 /* insufficient space */
664                                 SSLerr(SSL_F_DO_SSL3_WRITE, ERR_R_INTERNAL_ERROR);
665                                 goto err;
666                                 }
667                         }
668                 
669                 s->s3->empty_fragment_done = 1;
670                 }
671
672         if (create_empty_fragment)
673                 {
674 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
675                 /* extra fragment would be couple of cipher blocks,
676                  * which would be multiple of SSL3_ALIGN_PAYLOAD, so
677                  * if we want to align the real payload, then we can
678                  * just pretent we simply have two headers. */
679                 align = (int)wb->buf + 2*SSL3_RT_HEADER_LENGTH;
680                 align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
681 #endif
682                 p = wb->buf + align;
683                 wb->offset  = align;
684                 }
685         else if (prefix_len)
686                 {
687                 p = wb->buf + wb->offset + prefix_len;
688                 }
689         else
690                 {
691 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
692                 align = (int)wb->buf + SSL3_RT_HEADER_LENGTH;
693                 align = (-align)&(SSL3_ALIGN_PAYLOAD-1);
694 #endif
695                 p = wb->buf + align;
696                 wb->offset  = align;
697                 }
698
699         /* write the header */
700
701         *(p++)=type&0xff;
702         wr->type=type;
703
704         *(p++)=(s->version>>8);
705         *(p++)=s->version&0xff;
706
707         /* field where we are to write out packet length */
708         plen=p; 
709         p+=2;
710
711         /* lets setup the record stuff. */
712         wr->data=p;
713         wr->length=(int)len;
714         wr->input=(unsigned char *)buf;
715
716         /* we now 'read' from wr->input, wr->length bytes into
717          * wr->data */
718
719         /* first we compress */
720         if (s->compress != NULL)
721                 {
722                 if (!ssl3_do_compress(s))
723                         {
724                         SSLerr(SSL_F_DO_SSL3_WRITE,SSL_R_COMPRESSION_FAILURE);
725                         goto err;
726                         }
727                 }
728         else
729                 {
730                 memcpy(wr->data,wr->input,wr->length);
731                 wr->input=wr->data;
732                 }
733
734         /* we should still have the output to wr->data and the input
735          * from wr->input.  Length should be wr->length.
736          * wr->data still points in the wb->buf */
737
738         if (mac_size != 0)
739                 {
740                 s->method->ssl3_enc->mac(s,&(p[wr->length]),1);
741                 wr->length+=mac_size;
742                 wr->input=p;
743                 wr->data=p;
744                 }
745
746         /* ssl3_enc can only have an error on read */
747         s->method->ssl3_enc->enc(s,1);
748
749         /* record length after mac and block padding */
750         s2n(wr->length,plen);
751
752         /* we should now have
753          * wr->data pointing to the encrypted data, which is
754          * wr->length long */
755         wr->type=type; /* not needed but helps for debugging */
756         wr->length+=SSL3_RT_HEADER_LENGTH;
757
758         if (create_empty_fragment)
759                 {
760                 /* we are in a recursive call;
761                  * just return the length, don't write out anything here
762                  */
763                 return wr->length;
764                 }
765
766         /* now let's set up wb */
767         wb->left = prefix_len + wr->length;
768
769         /* memorize arguments so that ssl3_write_pending can detect bad write retries later */
770         s->s3->wpend_tot=len;
771         s->s3->wpend_buf=buf;
772         s->s3->wpend_type=type;
773         s->s3->wpend_ret=len;
774
775         /* we now just need to write the buffer */
776         return ssl3_write_pending(s,type,buf,len);
777 err:
778         return -1;
779         }
780
781 /* if s->s3->wbuf.left != 0, we need to call this */
782 int ssl3_write_pending(SSL *s, int type, const unsigned char *buf,
783         unsigned int len)
784         {
785         int i;
786         SSL3_BUFFER *wb=&(s->s3->wbuf);
787
788 /* XXXX */
789         if ((s->s3->wpend_tot > (int)len)
790                 || ((s->s3->wpend_buf != buf) &&
791                         !(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER))
792                 || (s->s3->wpend_type != type))
793                 {
794                 SSLerr(SSL_F_SSL3_WRITE_PENDING,SSL_R_BAD_WRITE_RETRY);
795                 return(-1);
796                 }
797
798         for (;;)
799                 {
800                 clear_sys_error();
801                 if (s->wbio != NULL)
802                         {
803                         s->rwstate=SSL_WRITING;
804                         i=BIO_write(s->wbio,
805                                 (char *)&(wb->buf[wb->offset]),
806                                 (unsigned int)wb->left);
807                         }
808                 else
809                         {
810                         SSLerr(SSL_F_SSL3_WRITE_PENDING,SSL_R_BIO_NOT_SET);
811                         i= -1;
812                         }
813                 if (i == wb->left)
814                         {
815                         wb->left=0;
816                         wb->offset+=i;
817                         s->rwstate=SSL_NOTHING;
818                         return(s->s3->wpend_ret);
819                         }
820                 else if (i <= 0)
821                         return(i);
822                 wb->offset+=i;
823                 wb->left-=i;
824                 }
825         }
826
827 /* Return up to 'len' payload bytes received in 'type' records.
828  * 'type' is one of the following:
829  *
830  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
831  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
832  *   -  0 (during a shutdown, no data has to be returned)
833  *
834  * If we don't have stored data to work from, read a SSL/TLS record first
835  * (possibly multiple records if we still don't have anything to return).
836  *
837  * This function must handle any surprises the peer may have for us, such as
838  * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
839  * a surprise, but handled as if it were), or renegotiation requests.
840  * Also if record payloads contain fragments too small to process, we store
841  * them until there is enough for the respective protocol (the record protocol
842  * may use arbitrary fragmentation and even interleaving):
843  *     Change cipher spec protocol
844  *             just 1 byte needed, no need for keeping anything stored
845  *     Alert protocol
846  *             2 bytes needed (AlertLevel, AlertDescription)
847  *     Handshake protocol
848  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
849  *             to detect unexpected Client Hello and Hello Request messages
850  *             here, anything else is handled by higher layers
851  *     Application data protocol
852  *             none of our business
853  */
854 int ssl3_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
855         {
856         int al,i,j,ret;
857         unsigned int n;
858         SSL3_RECORD *rr;
859         void (*cb)(const SSL *ssl,int type2,int val)=NULL;
860
861         if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
862                 if (!ssl3_setup_buffers(s))
863                         return(-1);
864
865         if ((type && (type != SSL3_RT_APPLICATION_DATA) && (type != SSL3_RT_HANDSHAKE) && type) ||
866             (peek && (type != SSL3_RT_APPLICATION_DATA)))
867                 {
868                 SSLerr(SSL_F_SSL3_READ_BYTES, ERR_R_INTERNAL_ERROR);
869                 return -1;
870                 }
871
872         if ((type == SSL3_RT_HANDSHAKE) && (s->s3->handshake_fragment_len > 0))
873                 /* (partially) satisfy request from storage */
874                 {
875                 unsigned char *src = s->s3->handshake_fragment;
876                 unsigned char *dst = buf;
877                 unsigned int k;
878
879                 /* peek == 0 */
880                 n = 0;
881                 while ((len > 0) && (s->s3->handshake_fragment_len > 0))
882                         {
883                         *dst++ = *src++;
884                         len--; s->s3->handshake_fragment_len--;
885                         n++;
886                         }
887                 /* move any remaining fragment bytes: */
888                 for (k = 0; k < s->s3->handshake_fragment_len; k++)
889                         s->s3->handshake_fragment[k] = *src++;
890                 return n;
891         }
892
893         /* Now s->s3->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
894
895         if (!s->in_handshake && SSL_in_init(s))
896                 {
897                 /* type == SSL3_RT_APPLICATION_DATA */
898                 i=s->handshake_func(s);
899                 if (i < 0) return(i);
900                 if (i == 0)
901                         {
902                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
903                         return(-1);
904                         }
905                 }
906 start:
907         s->rwstate=SSL_NOTHING;
908
909         /* s->s3->rrec.type         - is the type of record
910          * s->s3->rrec.data,    - data
911          * s->s3->rrec.off,     - offset into 'data' for next read
912          * s->s3->rrec.length,  - number of bytes. */
913         rr = &(s->s3->rrec);
914
915         /* get new packet if necessary */
916         if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))
917                 {
918                 ret=ssl3_get_record(s);
919                 if (ret <= 0) return(ret);
920                 }
921
922         /* we now have a packet which can be read and processed */
923
924         if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
925                                        * reset by ssl3_get_finished */
926                 && (rr->type != SSL3_RT_HANDSHAKE))
927                 {
928                 al=SSL_AD_UNEXPECTED_MESSAGE;
929                 SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
930                 goto f_err;
931                 }
932
933         /* If the other end has shut down, throw anything we read away
934          * (even in 'peek' mode) */
935         if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
936                 {
937                 rr->length=0;
938                 s->rwstate=SSL_NOTHING;
939                 return(0);
940                 }
941
942
943         if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
944                 {
945                 /* make sure that we are not getting application data when we
946                  * are doing a handshake for the first time */
947                 if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
948                         (s->enc_read_ctx == NULL))
949                         {
950                         al=SSL_AD_UNEXPECTED_MESSAGE;
951                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_APP_DATA_IN_HANDSHAKE);
952                         goto f_err;
953                         }
954
955                 if (len <= 0) return(len);
956
957                 if ((unsigned int)len > rr->length)
958                         n = rr->length;
959                 else
960                         n = (unsigned int)len;
961
962                 memcpy(buf,&(rr->data[rr->off]),n);
963                 if (!peek)
964                         {
965                         rr->length-=n;
966                         rr->off+=n;
967                         if (rr->length == 0)
968                                 {
969                                 s->rstate=SSL_ST_READ_HEADER;
970                                 rr->off=0;
971                                 }
972                         }
973                 return(n);
974                 }
975
976
977         /* If we get here, then type != rr->type; if we have a handshake
978          * message, then it was unexpected (Hello Request or Client Hello). */
979
980         /* In case of record types for which we have 'fragment' storage,
981          * fill that so that we can process the data at a fixed place.
982          */
983                 {
984                 unsigned int dest_maxlen = 0;
985                 unsigned char *dest = NULL;
986                 unsigned int *dest_len = NULL;
987
988                 if (rr->type == SSL3_RT_HANDSHAKE)
989                         {
990                         dest_maxlen = sizeof s->s3->handshake_fragment;
991                         dest = s->s3->handshake_fragment;
992                         dest_len = &s->s3->handshake_fragment_len;
993                         }
994                 else if (rr->type == SSL3_RT_ALERT)
995                         {
996                         dest_maxlen = sizeof s->s3->alert_fragment;
997                         dest = s->s3->alert_fragment;
998                         dest_len = &s->s3->alert_fragment_len;
999                         }
1000
1001                 if (dest_maxlen > 0)
1002                         {
1003                         n = dest_maxlen - *dest_len; /* available space in 'dest' */
1004                         if (rr->length < n)
1005                                 n = rr->length; /* available bytes */
1006
1007                         /* now move 'n' bytes: */
1008                         while (n-- > 0)
1009                                 {
1010                                 dest[(*dest_len)++] = rr->data[rr->off++];
1011                                 rr->length--;
1012                                 }
1013
1014                         if (*dest_len < dest_maxlen)
1015                                 goto start; /* fragment was too small */
1016                         }
1017                 }
1018
1019         /* s->s3->handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
1020          * s->s3->alert_fragment_len == 2      iff  rr->type == SSL3_RT_ALERT.
1021          * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
1022
1023         /* If we are a client, check for an incoming 'Hello Request': */
1024         if ((!s->server) &&
1025                 (s->s3->handshake_fragment_len >= 4) &&
1026                 (s->s3->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
1027                 (s->session != NULL) && (s->session->cipher != NULL))
1028                 {
1029                 s->s3->handshake_fragment_len = 0;
1030
1031                 if ((s->s3->handshake_fragment[1] != 0) ||
1032                         (s->s3->handshake_fragment[2] != 0) ||
1033                         (s->s3->handshake_fragment[3] != 0))
1034                         {
1035                         al=SSL_AD_DECODE_ERROR;
1036                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_HELLO_REQUEST);
1037                         goto f_err;
1038                         }
1039
1040                 if (s->msg_callback)
1041                         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, s->s3->handshake_fragment, 4, s, s->msg_callback_arg);
1042
1043                 if (SSL_is_init_finished(s) &&
1044                         !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
1045                         !s->s3->renegotiate)
1046                         {
1047                         ssl3_renegotiate(s);
1048                         if (ssl3_renegotiate_check(s))
1049                                 {
1050                                 i=s->handshake_func(s);
1051                                 if (i < 0) return(i);
1052                                 if (i == 0)
1053                                         {
1054                                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
1055                                         return(-1);
1056                                         }
1057
1058                                 if (!(s->mode & SSL_MODE_AUTO_RETRY))
1059                                         {
1060                                         if (s->s3->rbuf.left == 0) /* no read-ahead left? */
1061                                                 {
1062                                                 BIO *bio;
1063                                                 /* In the case where we try to read application data,
1064                                                  * but we trigger an SSL handshake, we return -1 with
1065                                                  * the retry option set.  Otherwise renegotiation may
1066                                                  * cause nasty problems in the blocking world */
1067                                                 s->rwstate=SSL_READING;
1068                                                 bio=SSL_get_rbio(s);
1069                                                 BIO_clear_retry_flags(bio);
1070                                                 BIO_set_retry_read(bio);
1071                                                 return(-1);
1072                                                 }
1073                                         }
1074                                 }
1075                         }
1076                 /* we either finished a handshake or ignored the request,
1077                  * now try again to obtain the (application) data we were asked for */
1078                 goto start;
1079                 }
1080
1081         if (s->s3->alert_fragment_len >= 2)
1082                 {
1083                 int alert_level = s->s3->alert_fragment[0];
1084                 int alert_descr = s->s3->alert_fragment[1];
1085
1086                 s->s3->alert_fragment_len = 0;
1087
1088                 if (s->msg_callback)
1089                         s->msg_callback(0, s->version, SSL3_RT_ALERT, s->s3->alert_fragment, 2, s, s->msg_callback_arg);
1090
1091                 if (s->info_callback != NULL)
1092                         cb=s->info_callback;
1093                 else if (s->ctx->info_callback != NULL)
1094                         cb=s->ctx->info_callback;
1095
1096                 if (cb != NULL)
1097                         {
1098                         j = (alert_level << 8) | alert_descr;
1099                         cb(s, SSL_CB_READ_ALERT, j);
1100                         }
1101
1102                 if (alert_level == 1) /* warning */
1103                         {
1104                         s->s3->warn_alert = alert_descr;
1105                         if (alert_descr == SSL_AD_CLOSE_NOTIFY)
1106                                 {
1107                                 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1108                                 return(0);
1109                                 }
1110                         }
1111                 else if (alert_level == 2) /* fatal */
1112                         {
1113                         char tmp[16];
1114
1115                         s->rwstate=SSL_NOTHING;
1116                         s->s3->fatal_alert = alert_descr;
1117                         SSLerr(SSL_F_SSL3_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
1118                         BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr);
1119                         ERR_add_error_data(2,"SSL alert number ",tmp);
1120                         s->shutdown|=SSL_RECEIVED_SHUTDOWN;
1121                         SSL_CTX_remove_session(s->ctx,s->session);
1122                         return(0);
1123                         }
1124                 else
1125                         {
1126                         al=SSL_AD_ILLEGAL_PARAMETER;
1127                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNKNOWN_ALERT_TYPE);
1128                         goto f_err;
1129                         }
1130
1131                 goto start;
1132                 }
1133
1134         if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
1135                 {
1136                 s->rwstate=SSL_NOTHING;
1137                 rr->length=0;
1138                 return(0);
1139                 }
1140
1141         if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
1142                 {
1143                 /* 'Change Cipher Spec' is just a single byte, so we know
1144                  * exactly what the record payload has to look like */
1145                 if (    (rr->length != 1) || (rr->off != 0) ||
1146                         (rr->data[0] != SSL3_MT_CCS))
1147                         {
1148                         al=SSL_AD_ILLEGAL_PARAMETER;
1149                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC);
1150                         goto f_err;
1151                         }
1152
1153                 /* Check we have a cipher to change to */
1154                 if (s->s3->tmp.new_cipher == NULL)
1155                         {
1156                         al=SSL_AD_UNEXPECTED_MESSAGE;
1157                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_CCS_RECEIVED_EARLY);
1158                         goto f_err;
1159                         }
1160
1161                 rr->length=0;
1162
1163                 if (s->msg_callback)
1164                         s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, rr->data, 1, s, s->msg_callback_arg);
1165
1166                 s->s3->change_cipher_spec=1;
1167                 if (!ssl3_do_change_cipher_spec(s))
1168                         goto err;
1169                 else
1170                         goto start;
1171                 }
1172
1173         /* Unexpected handshake message (Client Hello, or protocol violation) */
1174         if ((s->s3->handshake_fragment_len >= 4) &&     !s->in_handshake)
1175                 {
1176                 if (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&
1177                         !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS))
1178                         {
1179 #if 0 /* worked only because C operator preferences are not as expected (and
1180        * because this is not really needed for clients except for detecting
1181        * protocol violations): */
1182                         s->state=SSL_ST_BEFORE|(s->server)
1183                                 ?SSL_ST_ACCEPT
1184                                 :SSL_ST_CONNECT;
1185 #else
1186                         s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
1187 #endif
1188                         s->new_session=1;
1189                         }
1190                 i=s->handshake_func(s);
1191                 if (i < 0) return(i);
1192                 if (i == 0)
1193                         {
1194                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
1195                         return(-1);
1196                         }
1197
1198                 if (!(s->mode & SSL_MODE_AUTO_RETRY))
1199                         {
1200                         if (s->s3->rbuf.left == 0) /* no read-ahead left? */
1201                                 {
1202                                 BIO *bio;
1203                                 /* In the case where we try to read application data,
1204                                  * but we trigger an SSL handshake, we return -1 with
1205                                  * the retry option set.  Otherwise renegotiation may
1206                                  * cause nasty problems in the blocking world */
1207                                 s->rwstate=SSL_READING;
1208                                 bio=SSL_get_rbio(s);
1209                                 BIO_clear_retry_flags(bio);
1210                                 BIO_set_retry_read(bio);
1211                                 return(-1);
1212                                 }
1213                         }
1214                 goto start;
1215                 }
1216
1217         switch (rr->type)
1218                 {
1219         default:
1220 #ifndef OPENSSL_NO_TLS
1221                 /* TLS just ignores unknown message types */
1222                 if (s->version == TLS1_VERSION)
1223                         {
1224                         rr->length = 0;
1225                         goto start;
1226                         }
1227 #endif
1228                 al=SSL_AD_UNEXPECTED_MESSAGE;
1229                 SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
1230                 goto f_err;
1231         case SSL3_RT_CHANGE_CIPHER_SPEC:
1232         case SSL3_RT_ALERT:
1233         case SSL3_RT_HANDSHAKE:
1234                 /* we already handled all of these, with the possible exception
1235                  * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that
1236                  * should not happen when type != rr->type */
1237                 al=SSL_AD_UNEXPECTED_MESSAGE;
1238                 SSLerr(SSL_F_SSL3_READ_BYTES,ERR_R_INTERNAL_ERROR);
1239                 goto f_err;
1240         case SSL3_RT_APPLICATION_DATA:
1241                 /* At this point, we were expecting handshake data,
1242                  * but have application data.  If the library was
1243                  * running inside ssl3_read() (i.e. in_read_app_data
1244                  * is set) and it makes sense to read application data
1245                  * at this point (session renegotiation not yet started),
1246                  * we will indulge it.
1247                  */
1248                 if (s->s3->in_read_app_data &&
1249                         (s->s3->total_renegotiations != 0) &&
1250                         ((
1251                                 (s->state & SSL_ST_CONNECT) &&
1252                                 (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1253                                 (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
1254                                 ) || (
1255                                         (s->state & SSL_ST_ACCEPT) &&
1256                                         (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
1257                                         (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
1258                                         )
1259                                 ))
1260                         {
1261                         s->s3->in_read_app_data=2;
1262                         return(-1);
1263                         }
1264                 else
1265                         {
1266                         al=SSL_AD_UNEXPECTED_MESSAGE;
1267                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
1268                         goto f_err;
1269                         }
1270                 }
1271         /* not reached */
1272
1273 f_err:
1274         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1275 err:
1276         return(-1);
1277         }
1278
1279 int ssl3_do_change_cipher_spec(SSL *s)
1280         {
1281         int i;
1282         const char *sender;
1283         int slen;
1284
1285         if (s->state & SSL_ST_ACCEPT)
1286                 i=SSL3_CHANGE_CIPHER_SERVER_READ;
1287         else
1288                 i=SSL3_CHANGE_CIPHER_CLIENT_READ;
1289
1290         if (s->s3->tmp.key_block == NULL)
1291                 {
1292                 s->session->cipher=s->s3->tmp.new_cipher;
1293                 if (!s->method->ssl3_enc->setup_key_block(s)) return(0);
1294                 }
1295
1296         if (!s->method->ssl3_enc->change_cipher_state(s,i))
1297                 return(0);
1298
1299         /* we have to record the message digest at
1300          * this point so we can get it before we read
1301          * the finished message */
1302         if (s->state & SSL_ST_CONNECT)
1303                 {
1304                 sender=s->method->ssl3_enc->server_finished_label;
1305                 slen=s->method->ssl3_enc->server_finished_label_len;
1306                 }
1307         else
1308                 {
1309                 sender=s->method->ssl3_enc->client_finished_label;
1310                 slen=s->method->ssl3_enc->client_finished_label_len;
1311                 }
1312
1313         s->s3->tmp.peer_finish_md_len = s->method->ssl3_enc->final_finish_mac(s,
1314                 &(s->s3->finish_dgst1),
1315                 &(s->s3->finish_dgst2),
1316                 sender,slen,s->s3->tmp.peer_finish_md);
1317
1318         return(1);
1319         }
1320
1321 void ssl3_send_alert(SSL *s, int level, int desc)
1322         {
1323         /* Map tls/ssl alert value to correct one */
1324         desc=s->method->ssl3_enc->alert_value(desc);
1325         if (s->version == SSL3_VERSION && desc == SSL_AD_PROTOCOL_VERSION)
1326                 desc = SSL_AD_HANDSHAKE_FAILURE; /* SSL 3.0 does not have protocol_version alerts */
1327         if (desc < 0) return;
1328         /* If a fatal one, remove from cache */
1329         if ((level == 2) && (s->session != NULL))
1330                 SSL_CTX_remove_session(s->ctx,s->session);
1331
1332         s->s3->alert_dispatch=1;
1333         s->s3->send_alert[0]=level;
1334         s->s3->send_alert[1]=desc;
1335         if (s->s3->wbuf.left == 0) /* data still being written out? */
1336                 s->method->ssl_dispatch_alert(s);
1337         /* else data is still being written out, we will get written
1338          * some time in the future */
1339         }
1340
1341 int ssl3_dispatch_alert(SSL *s)
1342         {
1343         int i,j;
1344         void (*cb)(const SSL *ssl,int type,int val)=NULL;
1345
1346         s->s3->alert_dispatch=0;
1347         i = do_ssl3_write(s, SSL3_RT_ALERT, &s->s3->send_alert[0], 2, 0);
1348         if (i <= 0)
1349                 {
1350                 s->s3->alert_dispatch=1;
1351                 }
1352         else
1353                 {
1354                 /* Alert sent to BIO.  If it is important, flush it now.
1355                  * If the message does not get sent due to non-blocking IO,
1356                  * we will not worry too much. */
1357                 if (s->s3->send_alert[0] == SSL3_AL_FATAL)
1358                         (void)BIO_flush(s->wbio);
1359
1360                 if (s->msg_callback)
1361                         s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 2, s, s->msg_callback_arg);
1362
1363                 if (s->info_callback != NULL)
1364                         cb=s->info_callback;
1365                 else if (s->ctx->info_callback != NULL)
1366                         cb=s->ctx->info_callback;
1367
1368                 if (cb != NULL)
1369                         {
1370                         j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
1371                         cb(s,SSL_CB_WRITE_ALERT,j);
1372                         }
1373                 }
1374         return(i);
1375         }