Change #include filenames from <foo.h> to <openssl.h>.
[openssl.git] / ssl / s2_pkt.c
1 /* ssl/s2_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 "ssl_locl.h"
63
64 /* SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_PEER_ERROR_NO_CIPHER);
65  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_PEER_ERROR_NO_CERTIFICATE);
66  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_PEER_ERROR_CERTIFICATE);
67  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE);
68  * SSLerr(SSL_F_GET_SERVER_HELLO,SSL_R_UNKNOWN_REMOTE_ERROR_TYPE);
69  */
70
71 #ifndef NOPROTO
72 static int read_n(SSL *s,unsigned int n,unsigned int max,unsigned int extend);
73 static int do_ssl_write(SSL *s, const unsigned char *buf, unsigned int len);
74 static int write_pending(SSL *s, const unsigned char *buf, unsigned int len);
75 static int ssl_mt_error(int n);
76 #else
77 static int read_n();
78 static int do_ssl_write();
79 static int write_pending();
80 static int ssl_mt_error();
81 #endif
82
83 int ssl2_peek(SSL *s, char *buf, int len)
84         {
85         int ret;
86
87         ret=ssl2_read(s,buf,len);
88         if (ret > 0)
89                 {
90                 s->s2->ract_data_length+=ret;
91                 s->s2->ract_data-=ret;
92                 }
93         return(ret);
94         }
95
96 /* SSL_read -
97  * This routine will return 0 to len bytes, decrypted etc if required.
98  */
99 int ssl2_read(SSL *s, void *buf, int len)
100         {
101         int n;
102         unsigned char mac[MAX_MAC_SIZE];
103         unsigned char *p;
104         int i;
105         unsigned int mac_size=0;
106
107 ssl2_read_again:
108         if (SSL_in_init(s) && !s->in_handshake)
109                 {
110                 n=s->handshake_func(s);
111                 if (n < 0) return(n);
112                 if (n == 0)
113                         {
114                         SSLerr(SSL_F_SSL2_READ,SSL_R_SSL_HANDSHAKE_FAILURE);
115                         return(-1);
116                         }
117                 }
118
119         clear_sys_error();
120         s->rwstate=SSL_NOTHING;
121         if (len <= 0) return(len);
122
123         if (s->s2->ract_data_length != 0) /* read from buffer */
124                 {
125                 if (len > s->s2->ract_data_length)
126                         n=s->s2->ract_data_length;
127                 else
128                         n=len;
129
130                 memcpy(buf,s->s2->ract_data,(unsigned int)n);
131                 s->s2->ract_data_length-=n;
132                 s->s2->ract_data+=n;
133                 if (s->s2->ract_data_length == 0)
134                         s->rstate=SSL_ST_READ_HEADER;
135                 return(n);
136                 }
137
138         if (s->rstate == SSL_ST_READ_HEADER)
139                 {
140                 if (s->first_packet)
141                         {
142                         n=read_n(s,5,SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER+2,0);
143                         if (n <= 0) return(n); /* error or non-blocking */
144                         s->first_packet=0;
145                         p=s->packet;
146                         if (!((p[0] & 0x80) && (
147                                 (p[2] == SSL2_MT_CLIENT_HELLO) ||
148                                 (p[2] == SSL2_MT_SERVER_HELLO))))
149                                 {
150                                 SSLerr(SSL_F_SSL2_READ,SSL_R_NON_SSLV2_INITIAL_PACKET);
151                                 return(-1);
152                                 }
153                         }
154                 else
155                         {
156                         n=read_n(s,2,SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER+2,0);
157                         if (n <= 0) return(n); /* error or non-blocking */
158                         }
159                 /* part read stuff */
160
161                 s->rstate=SSL_ST_READ_BODY;
162                 p=s->packet;
163                 /* Do header */
164                 /*s->s2->padding=0;*/
165                 s->s2->escape=0;
166                 s->s2->rlength=(((unsigned int)p[0])<<8)|((unsigned int)p[1]);
167                 if ((p[0] & TWO_BYTE_BIT))              /* Two byte header? */
168                         {
169                         s->s2->three_byte_header=0;
170                         s->s2->rlength&=TWO_BYTE_MASK;  
171                         }
172                 else
173                         {
174                         s->s2->three_byte_header=1;
175                         s->s2->rlength&=THREE_BYTE_MASK;
176
177                         /* security >s2->escape */
178                         s->s2->escape=((p[0] & SEC_ESC_BIT))?1:0;
179                         }
180                 }
181
182         if (s->rstate == SSL_ST_READ_BODY)
183                 {
184                 n=s->s2->rlength+2+s->s2->three_byte_header;
185                 if (n > (int)s->packet_length)
186                         {
187                         n-=s->packet_length;
188                         i=read_n(s,(unsigned int)n,(unsigned int)n,1);
189                         if (i <= 0) return(i); /* ERROR */
190                         }
191
192                 p= &(s->packet[2]);
193                 s->rstate=SSL_ST_READ_HEADER;
194                 if (s->s2->three_byte_header)
195                         s->s2->padding= *(p++);
196                 else    s->s2->padding=0;
197
198                 /* Data portion */
199                 if (s->s2->clear_text)
200                         {
201                         s->s2->mac_data=p;
202                         s->s2->ract_data=p;
203                         s->s2->pad_data=NULL;
204                         }
205                 else
206                         {
207                         mac_size=EVP_MD_size(s->read_hash);
208                         s->s2->mac_data=p;
209                         s->s2->ract_data= &p[mac_size];
210                         s->s2->pad_data= &p[mac_size+
211                                 s->s2->rlength-s->s2->padding];
212                         }
213
214                 s->s2->ract_data_length=s->s2->rlength;
215                 /* added a check for length > max_size in case
216                  * encryption was not turned on yet due to an error */
217                 if ((!s->s2->clear_text) &&
218                         (s->s2->rlength >= mac_size))
219                         {
220                         ssl2_enc(s,0);
221                         s->s2->ract_data_length-=mac_size;
222                         ssl2_mac(s,mac,0);
223                         s->s2->ract_data_length-=s->s2->padding;
224                         if (    (memcmp(mac,s->s2->mac_data,
225                                 (unsigned int)mac_size) != 0) ||
226                                 (s->s2->rlength%EVP_CIPHER_CTX_block_size(s->enc_read_ctx) != 0))
227                                 {
228                                 SSLerr(SSL_F_SSL2_READ,SSL_R_BAD_MAC_DECODE);
229                                 return(-1);
230                                 }
231                         }
232                 INC32(s->s2->read_sequence); /* expect next number */
233                 /* s->s2->ract_data is now available for processing */
234
235 #if 1
236                 /* How should we react when a packet containing 0
237                  * bytes is received?  (Note that SSLeay/OpenSSL itself
238                  * never sends such packets; see ssl2_write.)
239                  * Returning 0 would be interpreted by the caller as
240                  * indicating EOF, so it's not a good idea.
241                  * Instead, we just continue reading.  Note that using
242                  * select() for blocking sockets *never* guarantees
243                  * that the next SSL_read will not block -- the available
244                  * data may contain incomplete packets, and except for SSL 2
245                  * renegotiation can confuse things even more. */
246
247                 goto ssl2_read_again; /* This should really be
248                                        * "return ssl2_read(s,buf,len)",
249                                        * but that would allow for
250                                        * denial-of-service attacks if a
251                                        * C compiler is used that does not
252                                        * recognize end-recursion. */
253 #else
254                 /* If a 0 byte packet was sent, return 0, otherwise
255                  * we play havoc with people using select with
256                  * blocking sockets.  Let them handle a packet at a time,
257                  * they should really be using non-blocking sockets. */
258                 if (s->s2->ract_data_length == 0)
259                         return(0);
260                 return(ssl2_read(s,buf,len));
261 #endif
262                 }
263         else
264                 {
265                 SSLerr(SSL_F_SSL2_READ,SSL_R_BAD_STATE);
266                         return(-1);
267                 }
268         }
269
270 static int read_n(SSL *s, unsigned int n, unsigned int max,
271              unsigned int extend)
272         {
273         int i,off,newb;
274
275         /* if there is stuff still in the buffer from a previous read,
276          * and there is more than we want, take some. */
277         if (s->s2->rbuf_left >= (int)n)
278                 {
279                 if (extend)
280                         s->packet_length+=n;
281                 else
282                         {
283                         s->packet= &(s->s2->rbuf[s->s2->rbuf_offs]);
284                         s->packet_length=n;
285                         }
286                 s->s2->rbuf_left-=n;
287                 s->s2->rbuf_offs+=n;
288                 return(n);
289                 }
290
291         if (!s->read_ahead) max=n;
292         if (max > (unsigned int)(SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER+2))
293                 max=SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER+2;
294         
295
296         /* Else we want more than we have.
297          * First, if there is some left or we want to extend */
298         off=0;
299         if ((s->s2->rbuf_left != 0) || ((s->packet_length != 0) && extend))
300                 {
301                 newb=s->s2->rbuf_left;
302                 if (extend)
303                         {
304                         off=s->packet_length;
305                         if (s->packet != s->s2->rbuf)
306                                 memcpy(s->s2->rbuf,s->packet,
307                                         (unsigned int)newb+off);
308                         }
309                 else if (s->s2->rbuf_offs != 0)
310                         {
311                         memcpy(s->s2->rbuf,&(s->s2->rbuf[s->s2->rbuf_offs]),
312                                 (unsigned int)newb);
313                         s->s2->rbuf_offs=0;
314                         }
315                 s->s2->rbuf_left=0;
316                 }
317         else
318                 newb=0;
319
320         /* off is the offset to start writing too.
321          * r->s2->rbuf_offs is the 'unread data', now 0. 
322          * newb is the number of new bytes so far
323          */
324         s->packet=s->s2->rbuf;
325         while (newb < (int)n)
326                 {
327                 clear_sys_error();
328                 if (s->rbio != NULL)
329                         {
330                         s->rwstate=SSL_READING;
331                         i=BIO_read(s->rbio,(char *)&(s->s2->rbuf[off+newb]),
332                                 max-newb);
333                         }
334                 else
335                         {
336                         SSLerr(SSL_F_READ_N,SSL_R_READ_BIO_NOT_SET);
337                         i= -1;
338                         }
339 #ifdef PKT_DEBUG
340                 if (s->debug & 0x01) sleep(1);
341 #endif
342                 if (i <= 0)
343                         {
344                         s->s2->rbuf_left+=newb;
345                         return(i);
346                         }
347                 newb+=i;
348                 }
349
350         /* record unread data */
351         if (newb > (int)n)
352                 {
353                 s->s2->rbuf_offs=n+off;
354                 s->s2->rbuf_left=newb-n;
355                 }
356         else
357                 {
358                 s->s2->rbuf_offs=0;
359                 s->s2->rbuf_left=0;
360                 }
361         if (extend)
362                 s->packet_length+=n;
363         else
364                 s->packet_length=n;
365         s->rwstate=SSL_NOTHING;
366         return(n);
367         }
368
369 int ssl2_write(SSL *s, const void *_buf, int len)
370         {
371         const unsigned char *buf=_buf;
372         unsigned int n,tot;
373         int i;
374
375         if (SSL_in_init(s) && !s->in_handshake)
376                 {
377                 i=s->handshake_func(s);
378                 if (i < 0) return(i);
379                 if (i == 0)
380                         {
381                         SSLerr(SSL_F_SSL2_WRITE,SSL_R_SSL_HANDSHAKE_FAILURE);
382                         return(-1);
383                         }
384                 }
385
386         if (s->error)
387                 {
388                 ssl2_write_error(s);
389                 if (s->error)
390                         return(-1);
391                 }
392
393         clear_sys_error();
394         s->rwstate=SSL_NOTHING;
395         if (len <= 0) return(len);
396
397         tot=s->s2->wnum;
398         s->s2->wnum=0;
399
400         n=(len-tot);
401         for (;;)
402                 {
403                 i=do_ssl_write(s,&(buf[tot]),n);
404                 if (i <= 0)
405                         {
406                         s->s2->wnum=tot;
407                         return(i);
408                         }
409                 if (i == (int)n) return(tot+i);
410
411                 n-=i;
412                 tot+=i;
413                 }
414         }
415
416 static int write_pending(SSL *s, const unsigned char *buf, unsigned int len)
417         {
418         int i;
419
420         /* s->s2->wpend_len != 0 MUST be true. */
421
422         /* check that they have given us the same buffer to
423          * write */
424         if ((s->s2->wpend_tot > (int)len) || (s->s2->wpend_buf != buf))
425                 {
426                 SSLerr(SSL_F_WRITE_PENDING,SSL_R_BAD_WRITE_RETRY);
427                 return(-1);
428                 }
429
430         for (;;)
431                 {
432                 clear_sys_error();
433                 if (s->wbio != NULL)
434                         {
435                         s->rwstate=SSL_WRITING;
436                         i=BIO_write(s->wbio,
437                                 (char *)&(s->s2->write_ptr[s->s2->wpend_off]),
438                                 (unsigned int)s->s2->wpend_len);
439                         }
440                 else
441                         {
442                         SSLerr(SSL_F_WRITE_PENDING,SSL_R_WRITE_BIO_NOT_SET);
443                         i= -1;
444                         }
445 #ifdef PKT_DEBUG
446                 if (s->debug & 0x01) sleep(1);
447 #endif
448                 if (i == s->s2->wpend_len)
449                         {
450                         s->s2->wpend_len=0;
451                         s->rwstate=SSL_NOTHING;
452                         return(s->s2->wpend_ret);
453                         }
454                 else if (i <= 0)
455                         return(i);
456                 s->s2->wpend_off+=i;
457                 s->s2->wpend_len-=i;
458                 }
459         }
460
461 static int do_ssl_write(SSL *s, const unsigned char *buf, unsigned int len)
462         {
463         unsigned int j,k,olen,p,mac_size,bs;
464         register unsigned char *pp;
465
466         olen=len;
467
468         /* first check if there is data from an encryption waiting to
469          * be sent - it must be sent because the other end is waiting.
470          * This will happen with non-blocking IO.  We print it and then
471          * return.
472          */
473         if (s->s2->wpend_len != 0) return(write_pending(s,buf,len));
474
475         /* set mac_size to mac size */
476         if (s->s2->clear_text)
477                 mac_size=0;
478         else
479                 mac_size=EVP_MD_size(s->write_hash);
480
481         /* lets set the pad p */
482         if (s->s2->clear_text)
483                 {
484                 if (len > SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER)
485                         len=SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER;
486                 p=0;
487                 s->s2->three_byte_header=0;
488                 /* len=len; */
489                 }
490         else
491                 {
492                 bs=EVP_CIPHER_CTX_block_size(s->enc_read_ctx);
493                 j=len+mac_size;
494                 if ((j > SSL2_MAX_RECORD_LENGTH_3_BYTE_HEADER) &&
495                         (!s->s2->escape))
496                         {
497                         if (j > SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER)
498                                 j=SSL2_MAX_RECORD_LENGTH_2_BYTE_HEADER;
499                         /* set k to the max number of bytes with 2
500                          * byte header */
501                         k=j-(j%bs);
502                         /* how many data bytes? */
503                         len=k-mac_size; 
504                         s->s2->three_byte_header=0;
505                         p=0;
506                         }
507                 else if ((bs <= 1) && (!s->s2->escape))
508                         {
509                         /* len=len; */
510                         s->s2->three_byte_header=0;
511                         p=0;
512                         }
513                 else /* 3 byte header */
514                         {
515                         /*len=len; */
516                         p=(j%bs);
517                         p=(p == 0)?0:(bs-p);
518                         if (s->s2->escape)
519                                 s->s2->three_byte_header=1;
520                         else
521                                 s->s2->three_byte_header=(p == 0)?0:1;
522                         }
523                 }
524         /* mac_size is the number of MAC bytes
525          * len is the number of data bytes we are going to send
526          * p is the number of padding bytes
527          * if p == 0, it is a 2 byte header */
528
529         s->s2->wlength=len;
530         s->s2->padding=p;
531         s->s2->mac_data= &(s->s2->wbuf[3]);
532         s->s2->wact_data= &(s->s2->wbuf[3+mac_size]);
533         /* we copy the data into s->s2->wbuf */
534         memcpy(s->s2->wact_data,buf,len);
535 #ifdef PURIFY
536         if (p)
537                 memset(&(s->s2->wact_data[len]),0,p);
538 #endif
539
540         if (!s->s2->clear_text)
541                 {
542                 s->s2->wact_data_length=len+p;
543                 ssl2_mac(s,s->s2->mac_data,1);
544                 s->s2->wlength+=p+mac_size;
545                 ssl2_enc(s,1);
546                 }
547
548         /* package up the header */
549         s->s2->wpend_len=s->s2->wlength;
550         if (s->s2->three_byte_header) /* 3 byte header */
551                 {
552                 pp=s->s2->mac_data;
553                 pp-=3;
554                 pp[0]=(s->s2->wlength>>8)&(THREE_BYTE_MASK>>8);
555                 if (s->s2->escape) pp[0]|=SEC_ESC_BIT;
556                 pp[1]=s->s2->wlength&0xff;
557                 pp[2]=s->s2->padding;
558                 s->s2->wpend_len+=3;
559                 }
560         else
561                 {
562                 pp=s->s2->mac_data;
563                 pp-=2;
564                 pp[0]=((s->s2->wlength>>8)&(TWO_BYTE_MASK>>8))|TWO_BYTE_BIT;
565                 pp[1]=s->s2->wlength&0xff;
566                 s->s2->wpend_len+=2;
567                 }
568         s->s2->write_ptr=pp;
569         
570         INC32(s->s2->write_sequence); /* expect next number */
571
572         /* lets try to actually write the data */
573         s->s2->wpend_tot=olen;
574         s->s2->wpend_buf=buf;
575
576         s->s2->wpend_ret=len;
577
578         s->s2->wpend_off=0;
579         return(write_pending(s,buf,olen));
580         }
581
582 int ssl2_part_read(SSL *s, unsigned long f, int i)
583         {
584         unsigned char *p;
585         int j;
586
587         /* check for error */
588         if ((s->init_num == 0) && (i >= 3))
589                 {
590                 p=(unsigned char *)s->init_buf->data;
591                 if (p[0] == SSL2_MT_ERROR)
592                         {
593                         j=(p[1]<<8)|p[2];
594                         SSLerr((int)f,ssl_mt_error(j));
595                         }
596                 }
597
598         if (i < 0)
599                 {
600                 /* ssl2_return_error(s); */
601                 /* for non-blocking io,
602                  * this is not fatal */
603                 return(i);
604                 }
605         else
606                 {
607                 s->init_num+=i;
608                 return(0);
609                 }
610         }
611
612 int ssl2_do_write(SSL *s)
613         {
614         int ret;
615
616         ret=ssl2_write(s,&s->init_buf->data[s->init_off],s->init_num);
617         if (ret == s->init_num)
618                 return(1);
619         if (ret < 0)
620                 return(-1);
621         s->init_off+=ret;
622         s->init_num-=ret;
623         return(0);
624         }
625
626 static int ssl_mt_error(int n)
627         {
628         int ret;
629
630         switch (n)
631                 {
632         case SSL2_PE_NO_CIPHER:
633                 ret=SSL_R_PEER_ERROR_NO_CIPHER;
634                 break;
635         case SSL2_PE_NO_CERTIFICATE:
636                 ret=SSL_R_PEER_ERROR_NO_CERTIFICATE;
637                 break;
638         case SSL2_PE_BAD_CERTIFICATE:
639                 ret=SSL_R_PEER_ERROR_CERTIFICATE;
640                 break;
641         case SSL2_PE_UNSUPPORTED_CERTIFICATE_TYPE:
642                 ret=SSL_R_PEER_ERROR_UNSUPPORTED_CERTIFICATE_TYPE;
643                 break;
644         default:
645                 ret=SSL_R_UNKNOWN_REMOTE_ERROR_TYPE;
646                 break;
647                 }
648         return(ret);
649         }