Generate errors when public/private key check is done.
[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 #include <stdio.h>
60 #include <errno.h>
61 #define USE_SOCKETS
62 #include "evp.h"
63 #include "buffer.h"
64 #include "ssl_locl.h"
65
66 /* SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_SSLV3_ALERT_PEER_ERROR_NO_CIPHER);
67  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_SSLV3_ALERT_PEER_ERROR_NO_CERTIFICATE);
68  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_SSLV3_ALERT_PEER_ERROR_CERTIFICATE);
69  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_SSLV3_ALERT_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
70  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_SSLV3_ALERT_UNKNOWN_REMOTE_ERROR_TYPE);
71  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_SSLV3_ALERT_UNEXPECTED_MESSAGE);
72  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_SSLV3_ALERT_BAD_RECORD_MAC);
73  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_SSLV3_ALERT_DECOMPRESSION_FAILURE);
74  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_SSLV3_ALERT_HANDSHAKE_FAILURE);
75  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_SSLV3_ALERT_NO_CERTIFICATE);
76  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_SSLV3_ALERT_BAD_CERTIFICATE);
77  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_SSLV3_ALERT_UNSUPPORTED_CERTIFICATE);
78  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_SSLV3_ALERT_CERTIFICATE_REVOKED);
79  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_SSLV3_ALERT_CERTIFICATE_EXPIRED);
80  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_SSLV3_ALERT_CERTIFICATE_UNKNOWN);
81  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_SSLV3_ALERT_ILLEGAL_PARAMETER);
82  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_TLSV1_ALERT_DECRYPTION_FAILED);
83  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_TLSV1_ALERT_RECORD_OVERFLOW);
84  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_TLSV1_ALERT_UNKNOWN_CA);
85  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_TLSV1_ALERT_ACCESS_DENIED);
86  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_TLSV1_ALERT_DECODE_ERROR);
87  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_TLSV1_ALERT_DECRYPT_ERROR);
88  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_TLSV1_ALERT_EXPORT_RESTRICION);
89  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_TLSV1_ALERT_PROTOCOL_VERSION);
90  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_TLSV1_ALERT_INSUFFICIENT_SECURITY);
91  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_TLSV1_ALERT_INTERNAL_ERROR);
92  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_TLSV1_ALERT_USER_CANCLED);
93  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_TLSV1_ALERT_NO_RENEGOTIATION);
94  */
95
96 #ifndef NOPROTO
97 static int do_ssl3_write(SSL *s, int type, char *buf, unsigned int len);
98 static int ssl3_write_pending(SSL *s, int type, char *buf, unsigned int len);
99 static int ssl3_get_record(SSL *s);
100 static int do_compress(SSL *ssl);
101 static int do_uncompress(SSL *ssl);
102 static int do_change_cipher_spec(SSL *ssl);
103 #else
104 static int do_ssl3_write();
105 static int ssl3_write_pending();
106 static int ssl3_get_record();
107 static int do_compress();
108 static int do_uncompress();
109 static int do_change_cipher_spec();
110 #endif
111
112 static int ssl3_read_n(s,n,max,extend)
113 SSL *s;
114 int n;
115 int max;
116 int extend;
117         {
118         int i,off,newb;
119
120         /* if there is stuff still in the buffer from a previous read,
121          * and there is more than we want, take some. */
122         if (s->s3->rbuf.left >= (int)n)
123                 {
124                 if (extend)
125                         s->packet_length+=n;
126                 else
127                         {
128                         s->packet= &(s->s3->rbuf.buf[s->s3->rbuf.offset]);
129                         s->packet_length=n;
130                         }
131                 s->s3->rbuf.left-=n;
132                 s->s3->rbuf.offset+=n;
133                 return(n);
134                 }
135
136         /* else we need to read more data */
137         if (!s->read_ahead) max=n;
138         if (max > SSL3_RT_MAX_PACKET_SIZE)
139                 max=SSL3_RT_MAX_PACKET_SIZE;
140
141         /* First check if there is some left or we want to extend */
142         off=0;
143         if (    (s->s3->rbuf.left != 0) ||
144                 ((s->packet_length != 0) && extend))
145                 {
146                 newb=s->s3->rbuf.left;
147                 if (extend)
148                         {
149                         /* Copy bytes back to the front of the buffer 
150                          * Take the bytes already pointed to by 'packet'
151                          * and take the extra ones on the end. */
152                         off=s->packet_length;
153                         if (s->packet != s->s3->rbuf.buf)
154                                 memcpy(s->s3->rbuf.buf,s->packet,newb+off);
155                         }
156                 else if (s->s3->rbuf.offset != 0)
157                         { /* so the data is not at the start of the buffer */
158                         memcpy(s->s3->rbuf.buf,
159                                 &(s->s3->rbuf.buf[s->s3->rbuf.offset]),newb);
160                         s->s3->rbuf.offset=0;
161                         }
162
163                 s->s3->rbuf.left=0;
164                 }
165         else
166                 newb=0;
167
168         /* So we now have 'newb' bytes at the front of 
169          * s->s3->rbuf.buf and need to read some more in on the end
170          * We start reading into the buffer at 's->s3->rbuf.offset'
171          */
172         s->packet=s->s3->rbuf.buf;
173
174         while (newb < n)
175                 {
176                 clear_sys_error();
177                 if (s->rbio != NULL)
178                         {
179                         s->rwstate=SSL_READING;
180                         i=BIO_read(s->rbio,
181                                 (char *)&(s->s3->rbuf.buf[off+newb]),
182                                 max-newb);
183                         }
184                 else
185                         {
186                         SSLerr(SSL_F_SSL3_READ_N,SSL_R_READ_BIO_NOT_SET);
187                         i= -1;
188                         }
189
190                 if (i <= 0)
191                         {
192                         s->s3->rbuf.left+=newb;
193                         return(i);
194                         }
195                 newb+=i;
196                 }
197
198         /* record used data read */
199         if (newb > n)
200                 {
201                 s->s3->rbuf.offset=n+off;
202                 s->s3->rbuf.left=newb-n;
203                 }
204         else
205                 {
206                 s->s3->rbuf.offset=0;
207                 s->s3->rbuf.left=0;
208                 }
209
210         if (extend)
211                 s->packet_length+=n;
212         else
213                 s->packet_length+=n;
214         return(n);
215         }
216
217 /* Call this to get a new input record.
218  * It will return <= 0 if more data is needed, normally due to an error
219  * or non-blocking IO.
220  * When it finishes, one packet has been decoded and can be found in
221  * ssl->s3->rrec.type   - is the type of record
222  * ssl->s3->rrec.data,  - data
223  * ssl->s3->rrec.length, - number of bytes
224  */
225 static int ssl3_get_record(s)
226 SSL *s;
227         {
228         int ssl_major,ssl_minor,al;
229         int n,i,ret= -1;
230         SSL3_BUFFER *rb;
231         SSL3_RECORD *rr;
232         SSL_SESSION *sess;
233         unsigned char *p;
234         unsigned char md[EVP_MAX_MD_SIZE];
235         short version;
236         unsigned int mac_size;
237         int clear=0,extra;
238
239         rr= &(s->s3->rrec);
240         rb= &(s->s3->rbuf);
241         sess=s->session;
242
243         if (s->options & SSL_OP_MICROSOFT_BIG_SSLV3_BUFFER)
244                 extra=SSL3_RT_MAX_EXTRA;
245         else
246                 extra=0;
247
248 again:
249         /* check if we have the header */
250         if (    (s->rstate != SSL_ST_READ_BODY) ||
251                 (s->packet_length < SSL3_RT_HEADER_LENGTH)) 
252                 {
253                 n=ssl3_read_n(s,SSL3_RT_HEADER_LENGTH,
254                         SSL3_RT_MAX_PACKET_SIZE,0);
255                 if (n <= 0) return(n); /* error or non-blocking */
256                 s->rstate=SSL_ST_READ_BODY;
257
258                 p=s->packet;
259
260                 /* Pull apart the header into the SSL3_RECORD */
261                 rr->type= *(p++);
262                 ssl_major= *(p++);
263                 ssl_minor= *(p++);
264                 version=(ssl_major<<8)|ssl_minor;
265                 n2s(p,rr->length);
266
267                 /* Lets check version */
268                 if (s->first_packet)
269                         {
270                         s->first_packet=0;
271                         }
272                 else
273                         {
274                         if (version != s->version)
275                                 {
276                                 SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);
277                                 /* Send back error using their
278                                  * version number :-) */
279                                 s->version=version;
280                                 al=SSL_AD_PROTOCOL_VERSION;
281                                 goto f_err;
282                                 }
283                         }
284
285                 if ((version>>8) != SSL3_VERSION_MAJOR)
286                         {
287                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);
288                         goto err;
289                         }
290
291                 if (rr->length > 
292                         (unsigned int)SSL3_RT_MAX_ENCRYPTED_LENGTH+extra)
293                         {
294                         al=SSL_AD_RECORD_OVERFLOW;
295                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PACKET_LENGTH_TOO_LONG);
296                         goto f_err;
297                         }
298
299                 s->rstate=SSL_ST_READ_BODY;
300                 }
301
302         /* get and decode the data */
303         if (s->rstate == SSL_ST_READ_BODY)
304                 {
305                 if (rr->length > (s->packet_length-SSL3_RT_HEADER_LENGTH))
306                         {
307                         i=rr->length;
308                         /*-(s->packet_length-SSL3_RT_HEADER_LENGTH); */
309                         n=ssl3_read_n(s,i,i,1);
310                         if (n <= 0) return(n); /* error or non-blocking io */
311                         }
312                 s->rstate=SSL_ST_READ_HEADER;
313                 }
314
315         /* At this point, we have the data in s->packet and there should be
316          * s->packet_length bytes, we must not 'overrun' this buffer :-)
317          * One of the following functions will copy the data from the
318          * s->packet buffer */
319
320         rr->input= &(s->packet[SSL3_RT_HEADER_LENGTH]);
321
322         /* ok, we can now read from 's->packet' data into 'rr'
323          * rr->input points at rr->length bytes, which
324          * need to be copied into rr->data by either
325          * the decryption or by the decompression
326          * When the data is 'copied' into the rr->data buffer,
327          * rr->input will be pointed at the new buffer */ 
328
329         /* Set the state for the following operations */
330         s->rstate=SSL_ST_READ_HEADER;
331
332         /* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
333          * rr->length bytes of encrypted compressed stuff. */
334
335         /* check is not needed I belive */
336         if (rr->length > (unsigned int)SSL3_RT_MAX_ENCRYPTED_LENGTH+extra)
337                 {
338                 al=SSL_AD_RECORD_OVERFLOW;
339                 SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
340                 goto f_err;
341                 }
342
343         /* decrypt in place in 'rr->input' */
344         rr->data=rr->input;
345
346         if (!s->method->ssl3_enc->enc(s,0))
347                 {
348                 al=SSL_AD_DECRYPT_ERROR;
349                 goto f_err;
350                 }
351 #ifdef TLS_DEBUG
352 printf("dec %d\n",rr->length);
353 { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); }
354 printf("\n");
355 #endif
356         /* r->length is now the compressed data plus mac */
357         if (    (sess == NULL) ||
358                 (s->enc_read_ctx == NULL) ||
359                 (s->read_hash == NULL))
360                 clear=1;
361
362         if (!clear)
363                 {
364                 mac_size=EVP_MD_size(s->read_hash);
365
366                 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+extra+mac_size)
367                         {
368                         al=SSL_AD_RECORD_OVERFLOW;
369                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_PRE_MAC_LENGTH_TOO_LONG);
370                         goto f_err;
371                         }
372                 /* check MAC for rr->input' */
373                 if (rr->length < mac_size)
374                         {
375                         al=SSL_AD_DECODE_ERROR;
376                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_LENGTH_TOO_SHORT);
377                         goto f_err;
378                         }
379                 rr->length-=mac_size;
380                 i=s->method->ssl3_enc->mac(s,md,0);
381                 if (memcmp(md,&(rr->data[rr->length]),mac_size) != 0)
382                         {
383                         al=SSL_AD_BAD_RECORD_MAC;
384                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_BAD_MAC_DECODE);
385                         ret= -1;
386                         goto f_err;
387                         }
388                 }
389
390         /* r->length is now just compressed */
391         if (s->expand != NULL)
392                 {
393                 if (rr->length > 
394                         (unsigned int)SSL3_RT_MAX_COMPRESSED_LENGTH+extra)
395                         {
396                         al=SSL_AD_RECORD_OVERFLOW;
397                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG);
398                         goto f_err;
399                         }
400                 if (!do_uncompress(s))
401                         {
402                         al=SSL_AD_DECOMPRESSION_FAILURE;
403                         SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_BAD_DECOMPRESSION);
404                         goto f_err;
405                         }
406                 }
407
408         if (rr->length > (unsigned int)SSL3_RT_MAX_PLAIN_LENGTH+extra)
409                 {
410                 al=SSL_AD_RECORD_OVERFLOW;
411                 SSLerr(SSL_F_SSL3_GET_RECORD,SSL_R_DATA_LENGTH_TOO_LONG);
412                 goto f_err;
413                 }
414
415         rr->off=0;
416         /* So at this point the following is true
417          * ssl->s3->rrec.type   is the type of record
418          * ssl->s3->rrec.length == number of bytes in record
419          * ssl->s3->rrec.off    == offset to first valid byte
420          * ssl->s3->rrec.data   == where to take bytes from, increment
421          *                         after use :-).
422          */
423
424         /* we have pulled in a full packet so zero things */
425         s->packet_length=0;
426
427         /* just read a 0 length packet */
428         if (rr->length == 0) goto again;
429
430         return(1);
431 f_err:
432         ssl3_send_alert(s,SSL3_AL_FATAL,al);
433 err:
434         return(ret);
435         }
436
437 static int do_uncompress(ssl)
438 SSL *ssl;
439         {
440         int i;
441         SSL3_RECORD *rr;
442
443         rr= &(ssl->s3->rrec);
444         i=COMP_expand_block(ssl->expand,rr->comp,
445                 SSL3_RT_MAX_PLAIN_LENGTH,rr->data,(int)rr->length);
446         if (i < 0)
447                 return(0);
448         else
449                 rr->length=i;
450         rr->data=rr->comp;
451
452         return(1);
453         }
454
455 static int do_compress(ssl)
456 SSL *ssl;
457         {
458         int i;
459         SSL3_RECORD *wr;
460
461         wr= &(ssl->s3->wrec);
462         i=COMP_compress_block(ssl->compress,wr->data,
463                 SSL3_RT_MAX_COMPRESSED_LENGTH,
464                 wr->input,(int)wr->length);
465         if (i < 0)
466                 return(0);
467         else
468                 wr->length=i;
469
470         wr->input=wr->data;
471         return(1);
472         }
473
474 /* Call this to write data
475  * It will return <= 0 if not all data has been sent or non-blocking IO.
476  */
477 int ssl3_write_bytes(s,type,buf,len)
478 SSL *s;
479 int type;
480 char *buf;
481 int len;
482         {
483         unsigned int tot,n,nw;
484         int i;
485
486         s->rwstate=SSL_NOTHING;
487         tot=s->s3->wnum;
488         s->s3->wnum=0;
489
490         if (SSL_in_init(s) && !s->in_handshake)
491                 {
492                 i=s->handshake_func(s);
493                 if (i < 0) return(i);
494                 if (i == 0)
495                         {
496                         SSLerr(SSL_F_SSL3_WRITE_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
497                         return(-1);
498                         }
499                 }
500
501         n=(len-tot);
502         for (;;)
503                 {
504                 if (n > SSL3_RT_MAX_PLAIN_LENGTH)
505                         nw=SSL3_RT_MAX_PLAIN_LENGTH;
506                 else
507                         nw=n;
508                         
509                 i=do_ssl3_write(s,type,&(buf[tot]),nw);
510                 if (i <= 0)
511                         {
512                         s->s3->wnum=tot;
513                         return(i);
514                         }
515
516                 if (type == SSL3_RT_HANDSHAKE)
517                         ssl3_finish_mac(s,(unsigned char *)&(buf[tot]),i);
518
519                 if (i == (int)n) return(tot+i);
520
521                 n-=i;
522                 tot+=i;
523                 }
524         }
525
526 static int do_ssl3_write(s,type,buf,len)
527 SSL *s;
528 int type;
529 char *buf;
530 unsigned int len;
531         {
532         unsigned char *p,*plen;
533         int i,mac_size,clear=0;
534         SSL3_RECORD *wr;
535         SSL3_BUFFER *wb;
536         SSL_SESSION *sess;
537
538         /* first check is there is a SSL3_RECORD still being written
539          * out.  This will happen with non blocking IO */
540         if (s->s3->wbuf.left != 0)
541                 return(ssl3_write_pending(s,type,buf,len));
542
543         /* If we have an alert to send, lets send it */
544         if (s->s3->alert_dispatch)
545                 {
546                 i=ssl3_dispatch_alert(s);
547                 if (i <= 0)
548                         return(i);
549                 /* if it went, fall through and send more stuff */
550                 }
551
552         if (len <= 0) return(len);
553         
554         wr= &(s->s3->wrec);
555         wb= &(s->s3->wbuf);
556         sess=s->session;
557
558         if (    (sess == NULL) ||
559                 (s->enc_write_ctx == NULL) ||
560                 (s->write_hash == NULL))
561                 clear=1;
562
563         if (clear)
564                 mac_size=0;
565         else
566                 mac_size=EVP_MD_size(s->write_hash);
567
568         p=wb->buf;
569
570         /* write the header */
571         *(p++)=type&0xff;
572         wr->type=type;
573
574         *(p++)=(s->version>>8);
575         *(p++)=s->version&0xff;
576         
577         /* record where we are to write out packet length */
578         plen=p; 
579         p+=2;
580         
581         /* lets setup the record stuff. */
582         wr->data=p;
583         wr->length=(int)len;
584         wr->input=(unsigned char *)buf;
585
586         /* we now 'read' from wr->input, wr->length bytes into
587          * wr->data */
588
589         /* first we compress */
590         if (s->compress != NULL)
591                 {
592                 if (!do_compress(s))
593                         {
594                         SSLerr(SSL_F_DO_SSL3_WRITE,SSL_R_COMPRESSION_FAILURE);
595                         goto err;
596                         }
597                 }
598         else
599                 {
600                 memcpy(wr->data,wr->input,wr->length);
601                 wr->input=wr->data;
602                 }
603
604         /* we should still have the output to wr->data and the input
605          * from wr->input.  Length should be wr->length.
606          * wr->data still points in the wb->buf */
607
608         if (mac_size != 0)
609                 {
610                 s->method->ssl3_enc->mac(s,&(p[wr->length]),1);
611                 wr->length+=mac_size;
612                 wr->input=p;
613                 wr->data=p;
614                 }
615
616         /* ssl3_enc can only have an error on read */
617         s->method->ssl3_enc->enc(s,1);
618
619         /* record length after mac and block padding */
620         s2n(wr->length,plen);
621
622         /* we should now have
623          * wr->data pointing to the encrypted data, which is
624          * wr->length long */
625         wr->type=type; /* not needed but helps for debugging */
626         wr->length+=SSL3_RT_HEADER_LENGTH;
627
628         /* Now lets setup wb */
629         wb->left=wr->length;
630         wb->offset=0;
631
632         s->s3->wpend_tot=len;
633         s->s3->wpend_buf=buf;
634         s->s3->wpend_type=type;
635         s->s3->wpend_ret=len;
636
637         /* we now just need to write the buffer */
638         return(ssl3_write_pending(s,type,buf,len));
639 err:
640         return(-1);
641         }
642
643 /* if s->s3->wbuf.left != 0, we need to call this */
644 static int ssl3_write_pending(s,type,buf,len)
645 SSL *s;
646 int type;
647 char *buf;
648 unsigned int len;
649         {
650         int i;
651
652 /* XXXX */
653         if ((s->s3->wpend_tot > (int)len) || (s->s3->wpend_buf != buf)
654                 || (s->s3->wpend_type != type))
655                 {
656                 SSLerr(SSL_F_SSL3_WRITE_PENDING,SSL_R_BAD_WRITE_RETRY);
657                 return(-1);
658                 }
659
660         for (;;)
661                 {
662                 clear_sys_error();
663                 if (s->wbio != NULL)
664                         {
665                         s->rwstate=SSL_WRITING;
666                         i=BIO_write(s->wbio,
667                                 (char *)&(s->s3->wbuf.buf[s->s3->wbuf.offset]),
668                                 (unsigned int)s->s3->wbuf.left);
669                         }
670                 else
671                         {
672                         SSLerr(SSL_F_SSL3_WRITE_PENDING,SSL_R_BIO_NOT_SET);
673                         i= -1;
674                         }
675                 if (i == s->s3->wbuf.left)
676                         {
677                         s->s3->wbuf.left=0;
678                         s->rwstate=SSL_NOTHING;
679                         return(s->s3->wpend_ret);
680                         }
681                 else if (i <= 0)
682                         return(i);
683                 s->s3->wbuf.offset+=i;
684                 s->s3->wbuf.left-=i;
685                 }
686         }
687
688 int ssl3_read_bytes(s,type,buf,len)
689 SSL *s;
690 int type;
691 char *buf;
692 int len;
693         {
694         int al,i,j,n,ret;
695         SSL3_RECORD *rr;
696         void (*cb)()=NULL;
697         BIO *bio;
698
699         if (s->s3->rbuf.buf == NULL) /* Not initialize yet */
700                 if (!ssl3_setup_buffers(s))
701                         return(-1);
702
703         if (!s->in_handshake && SSL_in_init(s))
704                 {
705                 i=s->handshake_func(s);
706                 if (i < 0) return(i);
707                 if (i == 0)
708                         {
709                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
710                         return(-1);
711                         }
712                 }
713 start:
714         s->rwstate=SSL_NOTHING;
715
716         /* s->s3->rrec.type     - is the type of record
717          * s->s3->rrec.data,    - data
718          * s->s3->rrec.off,     - ofset into 'data' for next read
719          * s->s3->rrec.length,  - number of bytes. */
720         rr= &(s->s3->rrec);
721
722         /* get new packet */
723         if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))
724                 {
725                 ret=ssl3_get_record(s);
726                 if (ret <= 0) return(ret);
727                 }
728
729         /* we now have a packet which can be read and processed */
730
731         if (s->s3->change_cipher_spec && (rr->type != SSL3_RT_HANDSHAKE))
732                 {
733                 al=SSL_AD_UNEXPECTED_MESSAGE;
734                 SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
735                 goto err;
736                 }
737
738         /* If the other end has shutdown, throw anything we read away */
739         if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
740                 {
741                 rr->length=0;
742                 s->rwstate=SSL_NOTHING;
743                 return(0);
744                 }
745
746         /* Check for an incoming 'Client Request' message */
747         if ((rr->type == SSL3_RT_HANDSHAKE) && (rr->length == 4) &&
748                 (rr->data[0] == SSL3_MT_CLIENT_REQUEST) &&
749                 (s->session != NULL) && (s->session->cipher != NULL))
750                 {
751                 if ((rr->data[1] != 0) || (rr->data[2] != 0) ||
752                         (rr->data[3] != 0))
753                         {
754                         al=SSL_AD_DECODE_ERROR;
755                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_CLIENT_REQUEST);
756                         goto err;
757                         }
758
759                 if (SSL_is_init_finished(s) &&
760                         !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
761                         !s->s3->renegotiate)
762                         {
763                         ssl3_renegotiate(s);
764                         if (ssl3_renegotiate_check(s))
765                                 {
766                                 n=s->handshake_func(s);
767                                 if (n < 0) return(n);
768                                 if (n == 0)
769                                         {
770                                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
771                                         return(-1);
772                                         }
773                                 }
774                         }
775                 rr->length=0;
776 /* ZZZ */       goto start;
777                 }
778
779         /* if it is not the type we want, or we have shutdown and want
780          * the peer shutdown */
781         if ((rr->type != type) || (s->shutdown & SSL_SENT_SHUTDOWN))
782                 {
783                 if (rr->type == SSL3_RT_ALERT)
784                         {
785                         if ((rr->length != 2) || (rr->off != 0))
786                                 {
787                                 al=SSL_AD_DECODE_ERROR;
788                                 SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_ALERT_RECORD);
789                                 goto f_err;
790                                 }
791
792                         i=rr->data[0];
793                         n=rr->data[1];
794
795                         /* clear from buffer */
796                         rr->length=0;
797
798                         if (s->info_callback != NULL)
799                                 cb=s->info_callback;
800                         else if (s->ctx->info_callback != NULL)
801                                 cb=s->ctx->info_callback;
802
803                         if (cb != NULL)
804                                 {
805                                 j=(i<<8)|n;
806                                 cb(s,SSL_CB_READ_ALERT,j);
807                                 }
808
809                         if (i == 1)
810                                 {
811                                 s->s3->warn_alert=n;
812                                 if (n == SSL_AD_CLOSE_NOTIFY)
813                                         {
814                                         s->shutdown|=SSL_RECEIVED_SHUTDOWN;
815                                         return(0);
816                                         }
817                                 }
818                         else if (i == 2)
819                                 {
820                                 char tmp[16];
821
822                                 s->rwstate=SSL_NOTHING;
823                                 s->s3->fatal_alert=n;
824                                 SSLerr(SSL_F_SSL3_READ_BYTES,
825                                         SSL_AD_REASON_OFFSET+n);
826                                 sprintf(tmp,"%d",n);
827                                 ERR_add_error_data(2,"SSL alert number ",tmp);
828                                 s->shutdown|=SSL_RECEIVED_SHUTDOWN;
829                                 SSL_CTX_remove_session(s->ctx,s->session);
830                                 return(0);
831                                 }
832                         else
833                                 {
834                                 al=SSL_AD_ILLEGAL_PARAMETER;
835                                 SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNKNOWN_ALERT_TYPE);
836                                 goto f_err;
837                                 }
838
839                         rr->length=0;
840                         goto start;
841                         }
842
843                 if (s->shutdown & SSL_SENT_SHUTDOWN)
844                         {
845                         s->rwstate=SSL_NOTHING;
846                         rr->length=0;
847                         return(0);
848                         }
849
850                 if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
851                         {
852                         if (    (rr->length != 1) || (rr->off != 0) ||
853                                 (rr->data[0] != SSL3_MT_CCS))
854                                 {
855                                 i=SSL_AD_ILLEGAL_PARAMETER;
856                                 SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC);
857                                 goto err;
858                                 }
859
860                         rr->length=0;
861                         s->s3->change_cipher_spec=1;
862                         if (!do_change_cipher_spec(s))
863                                 goto err;
864                         else
865                                 goto start;
866                         }
867
868                 /* else we have a handshake */
869                 if ((rr->type == SSL3_RT_HANDSHAKE) &&
870                         !s->in_handshake)
871                         {
872                         if (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&
873                                 !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS))
874                                 {
875                                 s->state=SSL_ST_BEFORE|(s->server)
876                                                 ?SSL_ST_ACCEPT
877                                                 :SSL_ST_CONNECT;
878                                 s->new_session=1;
879                                 }
880                         n=s->handshake_func(s);
881                         if (n < 0) return(n);
882                         if (n == 0)
883                                 {
884                                 SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
885                                 return(-1);
886                                 }
887
888                         /* In the case where we try to read application data
889                          * the first time, but we trigger an SSL handshake, we
890                          * return -1 with the retry option set.  I do this
891                          * otherwise renegotiation can cause nasty problems 
892                          * in the non-blocking world */
893
894                         s->rwstate=SSL_READING;
895                         bio=SSL_get_rbio(s);
896                         BIO_clear_retry_flags(bio);
897                         BIO_set_retry_read(bio);
898                         return(-1);
899                         }
900
901                 switch (rr->type)
902                         {
903                 default:
904 #ifndef NO_TLS
905                         /* TLS just ignores unknown message types */
906                         if (s->version == TLS1_VERSION)
907                                 {
908                                 goto start;
909                                 }
910 #endif
911                 case SSL3_RT_CHANGE_CIPHER_SPEC:
912                 case SSL3_RT_ALERT:
913                 case SSL3_RT_HANDSHAKE:
914                         al=SSL_AD_UNEXPECTED_MESSAGE;
915                         SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
916                         goto f_err;
917                 case SSL3_RT_APPLICATION_DATA:
918                         /* At this point, we were expecting something else,
919                          * but have application data.  What we do is set the
920                          * error, and return -1.  On the way out, if the
921                          * library was running inside ssl3_read() and it makes
922                          * sense to read application data at this point, we
923                          * will indulge it.  This will mostly happen during
924                          * session renegotiation.
925                          */
926                         if (s->s3->in_read_app_data &&
927                                 (s->s3->total_renegotiations != 0) &&
928                                 ((
929                                   (s->state & SSL_ST_CONNECT) &&
930                                   (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
931                                   (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
932                                  ) || (
933                                   (s->state & SSL_ST_ACCEPT) &&
934                                   (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
935                                   (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
936                                  )
937                                 ))
938                                 {
939                                 s->s3->in_read_app_data=0;
940                                 return(-1);
941                                 }
942                         else
943                                 {
944                                 al=SSL_AD_UNEXPECTED_MESSAGE;
945                                 SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
946                                 goto f_err;
947                                 }
948                         }
949                 }
950
951         /* make sure that we are not getting application data when we
952          * are doing a handshake for the first time */
953         if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
954                 (s->enc_read_ctx == NULL))
955                 {
956                 al=SSL_AD_UNEXPECTED_MESSAGE;
957                 SSLerr(SSL_F_SSL3_READ_BYTES,SSL_R_APP_DATA_IN_HANDSHAKE);
958                 goto f_err;
959                 }
960
961         if (len <= 0) return(len);
962
963         if ((unsigned int)len > rr->length)
964                 n=rr->length;
965         else
966                 n=len;
967
968         memcpy(buf,&(rr->data[rr->off]),(unsigned int)n);
969         rr->length-=n;
970         rr->off+=n;
971         if (rr->length <= 0)
972                 {
973                 s->rstate=SSL_ST_READ_HEADER;
974                 rr->off=0;
975                 }
976
977         if (type == SSL3_RT_HANDSHAKE)
978                 ssl3_finish_mac(s,(unsigned char *)buf,n);
979         return(n);
980 f_err:
981         ssl3_send_alert(s,SSL3_AL_FATAL,al);
982 err:
983         return(-1);
984         }
985
986 static int do_change_cipher_spec(s)
987 SSL *s;
988         {
989         int i;
990         unsigned char *sender;
991         int slen;
992
993         if (s->state & SSL_ST_ACCEPT)
994                 i=SSL3_CHANGE_CIPHER_SERVER_READ;
995         else
996                 i=SSL3_CHANGE_CIPHER_CLIENT_READ;
997
998         if (s->s3->tmp.key_block == NULL)
999                 {
1000                 s->session->cipher=s->s3->tmp.new_cipher;
1001                 if (!s->method->ssl3_enc->setup_key_block(s)) return(0);
1002                 }
1003
1004         if (!s->method->ssl3_enc->change_cipher_state(s,i))
1005                 return(0);
1006
1007         /* we have to record the message digest at
1008          * this point so we can get it before we read
1009          * the finished message */
1010         if (s->state & SSL_ST_CONNECT)
1011                 {
1012                 sender=s->method->ssl3_enc->server_finished;
1013                 slen=s->method->ssl3_enc->server_finished_len;
1014                 }
1015         else
1016                 {
1017                 sender=s->method->ssl3_enc->client_finished;
1018                 slen=s->method->ssl3_enc->client_finished_len;
1019                 }
1020
1021         s->method->ssl3_enc->final_finish_mac(s,
1022                 &(s->s3->finish_dgst1),
1023                 &(s->s3->finish_dgst2),
1024                 sender,slen,&(s->s3->tmp.finish_md[0]));
1025
1026         return(1);
1027         }
1028
1029 int ssl3_do_write(s,type)
1030 SSL *s;
1031 int type;
1032         {
1033         int ret;
1034
1035         ret=ssl3_write_bytes(s,type,(char *)
1036                 &(s->init_buf->data[s->init_off]),s->init_num);
1037         if (ret == s->init_num)
1038                 return(1);
1039         if (ret < 0) return(-1);
1040         s->init_off+=ret;
1041         s->init_num-=ret;
1042         return(0);
1043         }
1044
1045 void ssl3_send_alert(s,level,desc)
1046 SSL *s;
1047 int level;
1048 int desc;
1049         {
1050         /* Map tls/ssl alert value to correct one */
1051         desc=s->method->ssl3_enc->alert_value(desc);
1052         if (desc < 0) return;
1053         /* If a fatal one, remove from cache */
1054         if ((level == 2) && (s->session != NULL))
1055                 SSL_CTX_remove_session(s->ctx,s->session);
1056
1057         s->s3->alert_dispatch=1;
1058         s->s3->send_alert[0]=level;
1059         s->s3->send_alert[1]=desc;
1060         if (s->s3->wbuf.left == 0) /* data still being written out */
1061                 ssl3_dispatch_alert(s);
1062         /* else data is still being written out, we will get written
1063          * some time in the future */
1064         }
1065
1066 int ssl3_dispatch_alert(s)
1067 SSL *s;
1068         {
1069         int i,j;
1070         void (*cb)()=NULL;
1071
1072         s->s3->alert_dispatch=0;
1073         i=do_ssl3_write(s,SSL3_RT_ALERT,&(s->s3->send_alert[0]),2);
1074         if (i <= 0)
1075                 {
1076                 s->s3->alert_dispatch=1;
1077                 }
1078         else
1079                 {
1080                 /* If it is important, send it now.  If the message
1081                  * does not get sent due to non-blocking IO, we will
1082                  * not worry too much. */
1083                 if (s->s3->send_alert[0] == SSL3_AL_FATAL)
1084                         BIO_flush(s->wbio);
1085
1086                 if (s->info_callback != NULL)
1087                         cb=s->info_callback;
1088                 else if (s->ctx->info_callback != NULL)
1089                         cb=s->ctx->info_callback;
1090                 
1091                 if (cb != NULL)
1092                         {
1093                         j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
1094                         cb(s,SSL_CB_WRITE_ALERT,j);
1095                         }
1096                 }
1097         return(i);
1098         }
1099