Update error codes.
[openssl.git] / ssl / d1_pkt.c
1 /* ssl/d1_pkt.c */
2 /* 
3  * DTLS implementation written by Nagendra Modadugu
4  * (nagendra@cs.stanford.edu) for the OpenSSL project 2005.  
5  */
6 /* ====================================================================
7  * Copyright (c) 1998-2005 The OpenSSL Project.  All rights reserved.
8  *
9  * Redistribution and use in source and binary forms, with or without
10  * modification, are permitted provided that the following conditions
11  * are met:
12  *
13  * 1. Redistributions of source code must retain the above copyright
14  *    notice, this list of conditions and the following disclaimer. 
15  *
16  * 2. Redistributions in binary form must reproduce the above copyright
17  *    notice, this list of conditions and the following disclaimer in
18  *    the documentation and/or other materials provided with the
19  *    distribution.
20  *
21  * 3. All advertising materials mentioning features or use of this
22  *    software must display the following acknowledgment:
23  *    "This product includes software developed by the OpenSSL Project
24  *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
25  *
26  * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
27  *    endorse or promote products derived from this software without
28  *    prior written permission. For written permission, please contact
29  *    openssl-core@openssl.org.
30  *
31  * 5. Products derived from this software may not be called "OpenSSL"
32  *    nor may "OpenSSL" appear in their names without prior written
33  *    permission of the OpenSSL Project.
34  *
35  * 6. Redistributions of any form whatsoever must retain the following
36  *    acknowledgment:
37  *    "This product includes software developed by the OpenSSL Project
38  *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
39  *
40  * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
41  * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
43  * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
44  * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
45  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
46  * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
47  * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
48  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
49  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
50  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
51  * OF THE POSSIBILITY OF SUCH DAMAGE.
52  * ====================================================================
53  *
54  * This product includes cryptographic software written by Eric Young
55  * (eay@cryptsoft.com).  This product includes software written by Tim
56  * Hudson (tjh@cryptsoft.com).
57  *
58  */
59 /* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
60  * All rights reserved.
61  *
62  * This package is an SSL implementation written
63  * by Eric Young (eay@cryptsoft.com).
64  * The implementation was written so as to conform with Netscapes SSL.
65  * 
66  * This library is free for commercial and non-commercial use as long as
67  * the following conditions are aheared to.  The following conditions
68  * apply to all code found in this distribution, be it the RC4, RSA,
69  * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
70  * included with this distribution is covered by the same copyright terms
71  * except that the holder is Tim Hudson (tjh@cryptsoft.com).
72  * 
73  * Copyright remains Eric Young's, and as such any Copyright notices in
74  * the code are not to be removed.
75  * If this package is used in a product, Eric Young should be given attribution
76  * as the author of the parts of the library used.
77  * This can be in the form of a textual message at program startup or
78  * in documentation (online or textual) provided with the package.
79  * 
80  * Redistribution and use in source and binary forms, with or without
81  * modification, are permitted provided that the following conditions
82  * are met:
83  * 1. Redistributions of source code must retain the copyright
84  *    notice, this list of conditions and the following disclaimer.
85  * 2. Redistributions in binary form must reproduce the above copyright
86  *    notice, this list of conditions and the following disclaimer in the
87  *    documentation and/or other materials provided with the distribution.
88  * 3. All advertising materials mentioning features or use of this software
89  *    must display the following acknowledgement:
90  *    "This product includes cryptographic software written by
91  *     Eric Young (eay@cryptsoft.com)"
92  *    The word 'cryptographic' can be left out if the rouines from the library
93  *    being used are not cryptographic related :-).
94  * 4. If you include any Windows specific code (or a derivative thereof) from 
95  *    the apps directory (application code) you must include an acknowledgement:
96  *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
97  * 
98  * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
99  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
100  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
101  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
102  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
103  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
104  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
105  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
106  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
107  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
108  * SUCH DAMAGE.
109  * 
110  * The licence and distribution terms for any publically available version or
111  * derivative of this code cannot be changed.  i.e. this code cannot simply be
112  * copied and put under another distribution licence
113  * [including the GNU Public Licence.]
114  */
115
116 #include <stdio.h>
117 #include <errno.h>
118 #define USE_SOCKETS
119 #include "ssl_locl.h"
120 #include <openssl/evp.h>
121 #include <openssl/buffer.h>
122 #include <openssl/pqueue.h>
123 #include <openssl/rand.h>
124
125 /* mod 128 saturating subtract of two 64-bit values in big-endian order */
126 static int satsub64be(const unsigned char *v1,const unsigned char *v2)
127 {       int ret,sat,brw,i;
128
129         if (sizeof(long) == 8) do
130         {       const union { long one; char little; } is_endian = {1};
131                 long l;
132
133                 if (is_endian.little)                   break;
134                 /* not reached on little-endians */
135                 /* following test is redundant, because input is
136                  * always aligned, but I take no chances... */
137                 if (((size_t)v1|(size_t)v2)&0x7)        break;
138
139                 l  = *((long *)v1);
140                 l -= *((long *)v2);
141                 if (l>128)              return 128;
142                 else if (l<-128)        return -128;
143                 else                    return (int)l;
144         } while (0);
145
146         ret = (int)v1[7]-(int)v2[7];
147         sat = 0;
148         brw = ret>>8;   /* brw is either 0 or -1 */
149         if (ret & 0x80)
150         {       for (i=6;i>=0;i--)
151                 {       brw += (int)v1[i]-(int)v2[i];
152                         sat |= ~brw;
153                         brw >>= 8;
154                 }
155         }
156         else
157         {       for (i=6;i>=0;i--)
158                 {       brw += (int)v1[i]-(int)v2[i];
159                         sat |= brw;
160                         brw >>= 8;
161                 }
162         }
163         brw <<= 8;      /* brw is either 0 or -256 */
164
165         if (sat&0xff)   return brw | 0x80;
166         else            return brw + (ret&0xFF);
167 }
168
169 static int have_handshake_fragment(SSL *s, int type, unsigned char *buf, 
170         int len, int peek);
171 static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap);
172 static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap);
173 static DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, 
174     unsigned int *is_next_epoch);
175 #if 0
176 static int dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr,
177         unsigned short *priority, unsigned long *offset);
178 #endif
179 static int dtls1_buffer_record(SSL *s, record_pqueue *q,
180         unsigned char *priority);
181 static int dtls1_process_record(SSL *s);
182 static void dtls1_clear_timeouts(SSL *s);
183
184 /* copy buffered record into SSL structure */
185 static int
186 dtls1_copy_record(SSL *s, pitem *item)
187     {
188     DTLS1_RECORD_DATA *rdata;
189
190     rdata = (DTLS1_RECORD_DATA *)item->data;
191     
192     if (s->s3->rbuf.buf != NULL)
193         OPENSSL_free(s->s3->rbuf.buf);
194     
195     s->packet = rdata->packet;
196     s->packet_length = rdata->packet_length;
197     memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
198     memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
199     
200     return(1);
201     }
202
203
204 static int
205 dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
206         {
207         DTLS1_RECORD_DATA *rdata;
208         pitem *item;
209
210         rdata = OPENSSL_malloc(sizeof(DTLS1_RECORD_DATA));
211         item = pitem_new(priority, rdata);
212         if (rdata == NULL || item == NULL)
213                 {
214                 if (rdata != NULL) OPENSSL_free(rdata);
215                 if (item != NULL) pitem_free(item);
216                 
217                 SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
218                 return(0);
219                 }
220         
221         rdata->packet = s->packet;
222         rdata->packet_length = s->packet_length;
223         memcpy(&(rdata->rbuf), &(s->s3->rbuf), sizeof(SSL3_BUFFER));
224         memcpy(&(rdata->rrec), &(s->s3->rrec), sizeof(SSL3_RECORD));
225
226         item->data = rdata;
227
228         /* insert should not fail, since duplicates are dropped */
229         if (pqueue_insert(queue->q, item) == NULL)
230                 {
231                 OPENSSL_free(rdata);
232                 pitem_free(item);
233                 return(0);
234                 }
235
236         s->packet = NULL;
237         s->packet_length = 0;
238         memset(&(s->s3->rbuf), 0, sizeof(SSL3_BUFFER));
239         memset(&(s->s3->rrec), 0, sizeof(SSL3_RECORD));
240         
241         if (!ssl3_setup_buffers(s))
242                 {
243                 SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
244                 OPENSSL_free(rdata);
245                 pitem_free(item);
246                 return(0);
247                 }
248         
249         return(1);
250         }
251
252
253 static int
254 dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue)
255     {
256     pitem *item;
257
258     item = pqueue_pop(queue->q);
259     if (item)
260         {
261         dtls1_copy_record(s, item);
262
263         OPENSSL_free(item->data);
264                 pitem_free(item);
265
266         return(1);
267         }
268
269     return(0);
270     }
271
272
273 /* retrieve a buffered record that belongs to the new epoch, i.e., not processed 
274  * yet */
275 #define dtls1_get_unprocessed_record(s) \
276                    dtls1_retrieve_buffered_record((s), \
277                    &((s)->d1->unprocessed_rcds))
278
279 /* retrieve a buffered record that belongs to the current epoch, ie, processed */
280 #define dtls1_get_processed_record(s) \
281                    dtls1_retrieve_buffered_record((s), \
282                    &((s)->d1->processed_rcds))
283
284 static int
285 dtls1_process_buffered_records(SSL *s)
286     {
287     pitem *item;
288     
289     item = pqueue_peek(s->d1->unprocessed_rcds.q);
290     if (item)
291         {
292         DTLS1_RECORD_DATA *rdata;
293         rdata = (DTLS1_RECORD_DATA *)item->data;
294         
295         /* Check if epoch is current. */
296         if (s->d1->unprocessed_rcds.epoch != s->d1->r_epoch)
297             return(1);  /* Nothing to do. */
298         
299         /* Process all the records. */
300         while (pqueue_peek(s->d1->unprocessed_rcds.q))
301             {
302             dtls1_get_unprocessed_record(s);
303             if ( ! dtls1_process_record(s))
304                 return(0);
305             dtls1_buffer_record(s, &(s->d1->processed_rcds), 
306                 s->s3->rrec.seq_num);
307             }
308         }
309
310     /* sync epoch numbers once all the unprocessed records 
311      * have been processed */
312     s->d1->processed_rcds.epoch = s->d1->r_epoch;
313     s->d1->unprocessed_rcds.epoch = s->d1->r_epoch + 1;
314
315     return(1);
316     }
317
318
319 #if 0
320
321 static int
322 dtls1_get_buffered_record(SSL *s)
323         {
324         pitem *item;
325         PQ_64BIT priority = 
326                 (((PQ_64BIT)s->d1->handshake_read_seq) << 32) | 
327                 ((PQ_64BIT)s->d1->r_msg_hdr.frag_off);
328         
329         if ( ! SSL_in_init(s))  /* if we're not (re)negotiating, 
330                                                            nothing buffered */
331                 return 0;
332
333
334         item = pqueue_peek(s->d1->rcvd_records);
335         if (item && item->priority == priority)
336                 {
337                 /* Check if we've received the record of interest.  It must be
338                  * a handshake record, since data records as passed up without
339                  * buffering */
340                 DTLS1_RECORD_DATA *rdata;
341                 item = pqueue_pop(s->d1->rcvd_records);
342                 rdata = (DTLS1_RECORD_DATA *)item->data;
343                 
344                 if (s->s3->rbuf.buf != NULL)
345                         OPENSSL_free(s->s3->rbuf.buf);
346                 
347                 s->packet = rdata->packet;
348                 s->packet_length = rdata->packet_length;
349                 memcpy(&(s->s3->rbuf), &(rdata->rbuf), sizeof(SSL3_BUFFER));
350                 memcpy(&(s->s3->rrec), &(rdata->rrec), sizeof(SSL3_RECORD));
351                 
352                 OPENSSL_free(item->data);
353                 pitem_free(item);
354                 
355                 /* s->d1->next_expected_seq_num++; */
356                 return(1);
357                 }
358         
359         return 0;
360         }
361
362 #endif
363
364 static int
365 dtls1_process_record(SSL *s)
366 {
367         int i,al;
368         int clear=0;
369         int enc_err;
370         SSL_SESSION *sess;
371         SSL3_RECORD *rr;
372         unsigned int mac_size;
373         unsigned char md[EVP_MAX_MD_SIZE];
374
375
376         rr= &(s->s3->rrec);
377         sess = s->session;
378
379         /* At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
380          * and we have that many bytes in s->packet
381          */
382         rr->input= &(s->packet[DTLS1_RT_HEADER_LENGTH]);
383
384         /* ok, we can now read from 's->packet' data into 'rr'
385          * rr->input points at rr->length bytes, which
386          * need to be copied into rr->data by either
387          * the decryption or by the decompression
388          * When the data is 'copied' into the rr->data buffer,
389          * rr->input will be pointed at the new buffer */ 
390
391         /* We now have - encrypted [ MAC [ compressed [ plain ] ] ]
392          * rr->length bytes of encrypted compressed stuff. */
393
394         /* check is not needed I believe */
395         if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
396                 {
397                 al=SSL_AD_RECORD_OVERFLOW;
398                 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
399                 goto f_err;
400                 }
401
402         /* decrypt in place in 'rr->input' */
403         rr->data=rr->input;
404
405         enc_err = s->method->ssl3_enc->enc(s,0);
406         if (enc_err <= 0)
407                 {
408                 if (enc_err == 0)
409                         /* SSLerr() and ssl3_send_alert() have been called */
410                         goto err;
411
412                 /* otherwise enc_err == -1 */
413                 goto decryption_failed_or_bad_record_mac;
414                 }
415
416 #ifdef TLS_DEBUG
417 printf("dec %d\n",rr->length);
418 { unsigned int z; for (z=0; z<rr->length; z++) printf("%02X%c",rr->data[z],((z+1)%16)?' ':'\n'); }
419 printf("\n");
420 #endif
421
422         /* r->length is now the compressed data plus mac */
423         if (    (sess == NULL) ||
424                 (s->enc_read_ctx == NULL) ||
425                 (s->read_hash == NULL))
426         clear=1;
427
428         if (!clear)
429                 {
430                 mac_size=EVP_MD_CTX_size(s->read_hash);
431
432                 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH+mac_size)
433                         {
434 #if 0 /* OK only for stream ciphers (then rr->length is visible from ciphertext anyway) */
435                         al=SSL_AD_RECORD_OVERFLOW;
436                         SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_PRE_MAC_LENGTH_TOO_LONG);
437                         goto f_err;
438 #else
439                         goto decryption_failed_or_bad_record_mac;
440 #endif                  
441                         }
442                 /* check the MAC for rr->input (it's in mac_size bytes at the tail) */
443                 if (rr->length < mac_size)
444                         {
445 #if 0 /* OK only for stream ciphers */
446                         al=SSL_AD_DECODE_ERROR;
447                         SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_LENGTH_TOO_SHORT);
448                         goto f_err;
449 #else
450                         goto decryption_failed_or_bad_record_mac;
451 #endif
452                         }
453                 rr->length-=mac_size;
454                 i=s->method->ssl3_enc->mac(s,md,0);
455                 if (memcmp(md,&(rr->data[rr->length]),mac_size) != 0)
456                         {
457                         goto decryption_failed_or_bad_record_mac;
458                         }
459                 }
460
461         /* r->length is now just compressed */
462         if (s->expand != NULL)
463                 {
464                 if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH)
465                         {
466                         al=SSL_AD_RECORD_OVERFLOW;
467                         SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_COMPRESSED_LENGTH_TOO_LONG);
468                         goto f_err;
469                         }
470                 if (!ssl3_do_uncompress(s))
471                         {
472                         al=SSL_AD_DECOMPRESSION_FAILURE;
473                         SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_BAD_DECOMPRESSION);
474                         goto f_err;
475                         }
476                 }
477
478         if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH)
479                 {
480                 al=SSL_AD_RECORD_OVERFLOW;
481                 SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DATA_LENGTH_TOO_LONG);
482                 goto f_err;
483                 }
484
485         rr->off=0;
486         /* So at this point the following is true
487          * ssl->s3->rrec.type   is the type of record
488          * ssl->s3->rrec.length == number of bytes in record
489          * ssl->s3->rrec.off    == offset to first valid byte
490          * ssl->s3->rrec.data   == where to take bytes from, increment
491          *                         after use :-).
492          */
493
494         /* we have pulled in a full packet so zero things */
495         s->packet_length=0;
496         dtls1_record_bitmap_update(s, &(s->d1->bitmap));/* Mark receipt of record. */
497         return(1);
498
499 decryption_failed_or_bad_record_mac:
500         /* Separate 'decryption_failed' alert was introduced with TLS 1.0,
501          * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
502          * failure is directly visible from the ciphertext anyway,
503          * we should not reveal which kind of error occured -- this
504          * might become visible to an attacker (e.g. via logfile) */
505         al=SSL_AD_BAD_RECORD_MAC;
506         SSLerr(SSL_F_DTLS1_PROCESS_RECORD,SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
507 f_err:
508         ssl3_send_alert(s,SSL3_AL_FATAL,al);
509 err:
510         return(0);
511 }
512
513
514 /* Call this to get a new input record.
515  * It will return <= 0 if more data is needed, normally due to an error
516  * or non-blocking IO.
517  * When it finishes, one packet has been decoded and can be found in
518  * ssl->s3->rrec.type    - is the type of record
519  * ssl->s3->rrec.data,   - data
520  * ssl->s3->rrec.length, - number of bytes
521  */
522 /* used only by dtls1_read_bytes */
523 int dtls1_get_record(SSL *s)
524         {
525         int ssl_major,ssl_minor,al;
526         int i,n;
527         SSL3_RECORD *rr;
528         SSL_SESSION *sess;
529         unsigned char *p;
530         unsigned short version;
531         DTLS1_BITMAP *bitmap;
532         unsigned int is_next_epoch;
533
534         rr= &(s->s3->rrec);
535         sess=s->session;
536
537         /* The epoch may have changed.  If so, process all the
538          * pending records.  This is a non-blocking operation. */
539         if ( ! dtls1_process_buffered_records(s))
540             return 0;
541
542         /* if we're renegotiating, then there may be buffered records */
543         if (dtls1_get_processed_record(s))
544                 return 1;
545
546         /* get something from the wire */
547 again:
548         /* check if we have the header */
549         if (    (s->rstate != SSL_ST_READ_BODY) ||
550                 (s->packet_length < DTLS1_RT_HEADER_LENGTH)) 
551                 {
552                 n=ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH, s->s3->rbuf.len, 0);
553                 /* read timeout is handled by dtls1_read_bytes */
554                 if (n <= 0) return(n); /* error or non-blocking */
555
556                 OPENSSL_assert(s->packet_length == DTLS1_RT_HEADER_LENGTH);
557
558                 s->rstate=SSL_ST_READ_BODY;
559
560                 p=s->packet;
561
562                 /* Pull apart the header into the DTLS1_RECORD */
563                 rr->type= *(p++);
564                 ssl_major= *(p++);
565                 ssl_minor= *(p++);
566                 version=(ssl_major<<8)|ssl_minor;
567
568                 /* sequence number is 64 bits, with top 2 bytes = epoch */ 
569                 n2s(p,rr->epoch);
570
571                 memcpy(&(s->s3->read_sequence[2]), p, 6);
572                 p+=6;
573
574                 n2s(p,rr->length);
575
576                 /* Lets check version */
577                 if (!s->first_packet)
578                         {
579                         if (version != s->version)
580                                 {
581                                 SSLerr(SSL_F_DTLS1_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);
582                                 /* Send back error using their
583                                  * version number :-) */
584                                 s->version=version;
585                                 al=SSL_AD_PROTOCOL_VERSION;
586                                 goto f_err;
587                                 }
588                         }
589
590                 if ((version & 0xff00) != (DTLS1_VERSION & 0xff00))
591                         {
592                         SSLerr(SSL_F_DTLS1_GET_RECORD,SSL_R_WRONG_VERSION_NUMBER);
593                         goto err;
594                         }
595
596                 if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH)
597                         {
598                         al=SSL_AD_RECORD_OVERFLOW;
599                         SSLerr(SSL_F_DTLS1_GET_RECORD,SSL_R_PACKET_LENGTH_TOO_LONG);
600                         goto f_err;
601                         }
602
603                 /* now s->rstate == SSL_ST_READ_BODY */
604                 }
605
606         /* s->rstate == SSL_ST_READ_BODY, get and decode the data */
607
608         if (rr->length > s->packet_length-DTLS1_RT_HEADER_LENGTH)
609                 {
610                 /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
611                 i=rr->length;
612                 n=ssl3_read_n(s,i,i,1);
613                 if (n <= 0) return(n); /* error or non-blocking io */
614
615                 /* this packet contained a partial record, dump it */
616                 if ( n != i)
617                         {
618                         s->packet_length = 0;
619                         goto again;
620                         }
621
622                 /* now n == rr->length,
623                  * and s->packet_length == DTLS1_RT_HEADER_LENGTH + rr->length */
624                 }
625         s->rstate=SSL_ST_READ_HEADER; /* set state for later operations */
626
627         /* match epochs.  NULL means the packet is dropped on the floor */
628         bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
629         if ( bitmap == NULL)
630                 {
631                 s->packet_length = 0;  /* dump this record */
632                 goto again;   /* get another record */
633                 }
634
635         /* check whether this is a repeat, or aged record */
636         if ( ! dtls1_record_replay_check(s, bitmap))
637                 {
638                 s->packet_length=0; /* dump this record */
639                 goto again;     /* get another record */
640                 }
641
642         /* just read a 0 length packet */
643         if (rr->length == 0) goto again;
644
645         /* If this record is from the next epoch (either HM or ALERT),
646          * buffer it since it cannot be processed at this time. Records
647          * from the next epoch are marked as received even though they
648          * are not processed, so as to prevent any potential resource
649          * DoS attack */
650         if (is_next_epoch)
651                 {
652                 dtls1_record_bitmap_update(s, bitmap);
653                 dtls1_buffer_record(s, &(s->d1->unprocessed_rcds), rr->seq_num);
654                 s->packet_length = 0;
655                 goto again;
656                 }
657
658         if ( ! dtls1_process_record(s))
659                 return(0);
660
661         dtls1_clear_timeouts(s);  /* done waiting */
662         return(1);
663
664 f_err:
665         ssl3_send_alert(s,SSL3_AL_FATAL,al);
666 err:
667         return(0);
668         }
669
670 /* Return up to 'len' payload bytes received in 'type' records.
671  * 'type' is one of the following:
672  *
673  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
674  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
675  *   -  0 (during a shutdown, no data has to be returned)
676  *
677  * If we don't have stored data to work from, read a SSL/TLS record first
678  * (possibly multiple records if we still don't have anything to return).
679  *
680  * This function must handle any surprises the peer may have for us, such as
681  * Alert records (e.g. close_notify), ChangeCipherSpec records (not really
682  * a surprise, but handled as if it were), or renegotiation requests.
683  * Also if record payloads contain fragments too small to process, we store
684  * them until there is enough for the respective protocol (the record protocol
685  * may use arbitrary fragmentation and even interleaving):
686  *     Change cipher spec protocol
687  *             just 1 byte needed, no need for keeping anything stored
688  *     Alert protocol
689  *             2 bytes needed (AlertLevel, AlertDescription)
690  *     Handshake protocol
691  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
692  *             to detect unexpected Client Hello and Hello Request messages
693  *             here, anything else is handled by higher layers
694  *     Application data protocol
695  *             none of our business
696  */
697 int dtls1_read_bytes(SSL *s, int type, unsigned char *buf, int len, int peek)
698         {
699         int al,i,j,ret;
700         unsigned int n;
701         SSL3_RECORD *rr;
702         void (*cb)(const SSL *ssl,int type2,int val)=NULL;
703
704         if (s->s3->rbuf.buf == NULL) /* Not initialized yet */
705                 if (!ssl3_setup_buffers(s))
706                         return(-1);
707
708     /* XXX: check what the second '&& type' is about */
709         if ((type && (type != SSL3_RT_APPLICATION_DATA) && 
710                 (type != SSL3_RT_HANDSHAKE) && type) ||
711             (peek && (type != SSL3_RT_APPLICATION_DATA)))
712                 {
713                 SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
714                 return -1;
715                 }
716
717         /* check whether there's a handshake message (client hello?) waiting */
718         if ( (ret = have_handshake_fragment(s, type, buf, len, peek)))
719                 return ret;
720
721         /* Now s->d1->handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE. */
722
723         if (!s->in_handshake && SSL_in_init(s))
724                 {
725                 /* type == SSL3_RT_APPLICATION_DATA */
726                 i=s->handshake_func(s);
727                 if (i < 0) return(i);
728                 if (i == 0)
729                         {
730                         SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
731                         return(-1);
732                         }
733                 }
734
735 start:
736         s->rwstate=SSL_NOTHING;
737
738         /* s->s3->rrec.type         - is the type of record
739          * s->s3->rrec.data,    - data
740          * s->s3->rrec.off,     - offset into 'data' for next read
741          * s->s3->rrec.length,  - number of bytes. */
742         rr = &(s->s3->rrec);
743
744         /* get new packet if necessary */
745         if ((rr->length == 0) || (s->rstate == SSL_ST_READ_BODY))
746                 {
747                 ret=dtls1_get_record(s);
748                 if (ret <= 0) 
749                         {
750                         ret = dtls1_read_failed(s, ret);
751                         /* anything other than a timeout is an error */
752                         if (ret <= 0)  
753                                 return(ret);
754                         else
755                                 goto start;
756                         }
757                 }
758
759         /* we now have a packet which can be read and processed */
760
761         if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
762                                        * reset by ssl3_get_finished */
763                 && (rr->type != SSL3_RT_HANDSHAKE))
764                 {
765                 al=SSL_AD_UNEXPECTED_MESSAGE;
766                 SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
767                 goto err;
768                 }
769
770         /* If the other end has shut down, throw anything we read away
771          * (even in 'peek' mode) */
772         if (s->shutdown & SSL_RECEIVED_SHUTDOWN)
773                 {
774                 rr->length=0;
775                 s->rwstate=SSL_NOTHING;
776                 return(0);
777                 }
778
779
780         if (type == rr->type) /* SSL3_RT_APPLICATION_DATA or SSL3_RT_HANDSHAKE */
781                 {
782                 /* make sure that we are not getting application data when we
783                  * are doing a handshake for the first time */
784                 if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
785                         (s->enc_read_ctx == NULL))
786                         {
787                         al=SSL_AD_UNEXPECTED_MESSAGE;
788                         SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_APP_DATA_IN_HANDSHAKE);
789                         goto f_err;
790                         }
791
792                 if (len <= 0) return(len);
793
794                 if ((unsigned int)len > rr->length)
795                         n = rr->length;
796                 else
797                         n = (unsigned int)len;
798
799                 memcpy(buf,&(rr->data[rr->off]),n);
800                 if (!peek)
801                         {
802                         rr->length-=n;
803                         rr->off+=n;
804                         if (rr->length == 0)
805                                 {
806                                 s->rstate=SSL_ST_READ_HEADER;
807                                 rr->off=0;
808                                 }
809                         }
810                 return(n);
811                 }
812
813
814         /* If we get here, then type != rr->type; if we have a handshake
815          * message, then it was unexpected (Hello Request or Client Hello). */
816
817         /* In case of record types for which we have 'fragment' storage,
818          * fill that so that we can process the data at a fixed place.
819          */
820                 {
821                 unsigned int k, dest_maxlen = 0;
822                 unsigned char *dest = NULL;
823                 unsigned int *dest_len = NULL;
824
825                 if (rr->type == SSL3_RT_HANDSHAKE)
826                         {
827                         dest_maxlen = sizeof s->d1->handshake_fragment;
828                         dest = s->d1->handshake_fragment;
829                         dest_len = &s->d1->handshake_fragment_len;
830                         }
831                 else if (rr->type == SSL3_RT_ALERT)
832                         {
833                         dest_maxlen = sizeof(s->d1->alert_fragment);
834                         dest = s->d1->alert_fragment;
835                         dest_len = &s->d1->alert_fragment_len;
836                         }
837                 /* else it's a CCS message, or it's wrong */
838                 else if (rr->type != SSL3_RT_CHANGE_CIPHER_SPEC)
839                         {
840                           /* Not certain if this is the right error handling */
841                           al=SSL_AD_UNEXPECTED_MESSAGE;
842                           SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
843                           goto f_err;
844                         }
845
846
847                 if (dest_maxlen > 0)
848                         {
849             /* XDTLS:  In a pathalogical case, the Client Hello
850              *  may be fragmented--don't always expect dest_maxlen bytes */
851                         if ( rr->length < dest_maxlen)
852                                 {
853                                 s->rstate=SSL_ST_READ_HEADER;
854                                 rr->length = 0;
855                                 goto start;
856                                 }
857
858                         /* now move 'n' bytes: */
859                         for ( k = 0; k < dest_maxlen; k++)
860                                 {
861                                 dest[k] = rr->data[rr->off++];
862                                 rr->length--;
863                                 }
864                         *dest_len = dest_maxlen;
865                         }
866                 }
867
868         /* s->d1->handshake_fragment_len == 12  iff  rr->type == SSL3_RT_HANDSHAKE;
869          * s->d1->alert_fragment_len == 7      iff  rr->type == SSL3_RT_ALERT.
870          * (Possibly rr is 'empty' now, i.e. rr->length may be 0.) */
871
872         /* If we are a client, check for an incoming 'Hello Request': */
873         if ((!s->server) &&
874                 (s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
875                 (s->d1->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
876                 (s->session != NULL) && (s->session->cipher != NULL))
877                 {
878                 s->d1->handshake_fragment_len = 0;
879
880                 if ((s->d1->handshake_fragment[1] != 0) ||
881                         (s->d1->handshake_fragment[2] != 0) ||
882                         (s->d1->handshake_fragment[3] != 0))
883                         {
884                         al=SSL_AD_DECODE_ERROR;
885                         SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_BAD_HELLO_REQUEST);
886                         goto err;
887                         }
888
889                 /* no need to check sequence number on HELLO REQUEST messages */
890
891                 if (s->msg_callback)
892                         s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE, 
893                                 s->d1->handshake_fragment, 4, s, s->msg_callback_arg);
894
895                 if (SSL_is_init_finished(s) &&
896                         !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
897                         !s->s3->renegotiate)
898                         {
899                         ssl3_renegotiate(s);
900                         if (ssl3_renegotiate_check(s))
901                                 {
902                                 i=s->handshake_func(s);
903                                 if (i < 0) return(i);
904                                 if (i == 0)
905                                         {
906                                         SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
907                                         return(-1);
908                                         }
909
910                                 if (!(s->mode & SSL_MODE_AUTO_RETRY))
911                                         {
912                                         if (s->s3->rbuf.left == 0) /* no read-ahead left? */
913                                                 {
914                                                 BIO *bio;
915                                                 /* In the case where we try to read application data,
916                                                  * but we trigger an SSL handshake, we return -1 with
917                                                  * the retry option set.  Otherwise renegotiation may
918                                                  * cause nasty problems in the blocking world */
919                                                 s->rwstate=SSL_READING;
920                                                 bio=SSL_get_rbio(s);
921                                                 BIO_clear_retry_flags(bio);
922                                                 BIO_set_retry_read(bio);
923                                                 return(-1);
924                                                 }
925                                         }
926                                 }
927                         }
928                 /* we either finished a handshake or ignored the request,
929                  * now try again to obtain the (application) data we were asked for */
930                 goto start;
931                 }
932
933         if (s->d1->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH)
934                 {
935                 int alert_level = s->d1->alert_fragment[0];
936                 int alert_descr = s->d1->alert_fragment[1];
937
938                 s->d1->alert_fragment_len = 0;
939
940                 if (s->msg_callback)
941                         s->msg_callback(0, s->version, SSL3_RT_ALERT, 
942                                 s->d1->alert_fragment, 2, s, s->msg_callback_arg);
943
944                 if (s->info_callback != NULL)
945                         cb=s->info_callback;
946                 else if (s->ctx->info_callback != NULL)
947                         cb=s->ctx->info_callback;
948
949                 if (cb != NULL)
950                         {
951                         j = (alert_level << 8) | alert_descr;
952                         cb(s, SSL_CB_READ_ALERT, j);
953                         }
954
955                 if (alert_level == 1) /* warning */
956                         {
957                         s->s3->warn_alert = alert_descr;
958                         if (alert_descr == SSL_AD_CLOSE_NOTIFY)
959                                 {
960                                 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
961                                 return(0);
962                                 }
963 #if 0
964             /* XXX: this is a possible improvement in the future */
965                         /* now check if it's a missing record */
966                         if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE)
967                                 {
968                                 unsigned short seq;
969                                 unsigned int frag_off;
970                                 unsigned char *p = &(s->d1->alert_fragment[2]);
971
972                                 n2s(p, seq);
973                                 n2l3(p, frag_off);
974
975                                 dtls1_retransmit_message(s, seq, frag_off, &found);
976                                 if ( ! found  && SSL_in_init(s))
977                                         {
978                                         /* fprintf( stderr,"in init = %d\n", SSL_in_init(s)); */
979                                         /* requested a message not yet sent, 
980                                            send an alert ourselves */
981                                         ssl3_send_alert(s,SSL3_AL_WARNING,
982                                                 DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
983                                         }
984                                 }
985 #endif
986                         }
987                 else if (alert_level == 2) /* fatal */
988                         {
989                         char tmp[16];
990
991                         s->rwstate=SSL_NOTHING;
992                         s->s3->fatal_alert = alert_descr;
993                         SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
994                         BIO_snprintf(tmp,sizeof tmp,"%d",alert_descr);
995                         ERR_add_error_data(2,"SSL alert number ",tmp);
996                         s->shutdown|=SSL_RECEIVED_SHUTDOWN;
997                         SSL_CTX_remove_session(s->ctx,s->session);
998                         return(0);
999                         }
1000                 else
1001                         {
1002                         al=SSL_AD_ILLEGAL_PARAMETER;
1003                         SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNKNOWN_ALERT_TYPE);
1004                         goto f_err;
1005                         }
1006
1007                 goto start;
1008                 }
1009
1010         if (s->shutdown & SSL_SENT_SHUTDOWN) /* but we have not received a shutdown */
1011                 {
1012                 s->rwstate=SSL_NOTHING;
1013                 rr->length=0;
1014                 return(0);
1015                 }
1016
1017         if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
1018                 {
1019                 struct ccs_header_st ccs_hdr;
1020
1021                 dtls1_get_ccs_header(rr->data, &ccs_hdr);
1022
1023                 /* 'Change Cipher Spec' is just a single byte, so we know
1024                  * exactly what the record payload has to look like */
1025                 /* XDTLS: check that epoch is consistent */
1026                 if (    (rr->length != DTLS1_CCS_HEADER_LENGTH) || 
1027                         (rr->off != 0) || (rr->data[0] != SSL3_MT_CCS))
1028                         {
1029                         i=SSL_AD_ILLEGAL_PARAMETER;
1030                         SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_BAD_CHANGE_CIPHER_SPEC);
1031                         goto err;
1032                         }
1033
1034                 rr->length=0;
1035
1036                 if (s->msg_callback)
1037                         s->msg_callback(0, s->version, SSL3_RT_CHANGE_CIPHER_SPEC, 
1038                                 rr->data, 1, s, s->msg_callback_arg);
1039
1040                 s->s3->change_cipher_spec=1;
1041                 if (!ssl3_do_change_cipher_spec(s))
1042                         goto err;
1043
1044                 /* do this whenever CCS is processed */
1045                 dtls1_reset_seq_numbers(s, SSL3_CC_READ);
1046
1047                 goto start;
1048                 }
1049
1050         /* Unexpected handshake message (Client Hello, or protocol violation) */
1051         if ((s->d1->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) && 
1052                 !s->in_handshake)
1053                 {
1054                 struct hm_header_st msg_hdr;
1055                 
1056                 /* this may just be a stale retransmit */
1057                 dtls1_get_message_header(rr->data, &msg_hdr);
1058                 if( rr->epoch != s->d1->r_epoch)
1059                         {
1060                         rr->length = 0;
1061                         goto start;
1062                         }
1063
1064                 if (((s->state&SSL_ST_MASK) == SSL_ST_OK) &&
1065                         !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS))
1066                         {
1067 #if 0 /* worked only because C operator preferences are not as expected (and
1068        * because this is not really needed for clients except for detecting
1069        * protocol violations): */
1070                         s->state=SSL_ST_BEFORE|(s->server)
1071                                 ?SSL_ST_ACCEPT
1072                                 :SSL_ST_CONNECT;
1073 #else
1074                         s->state = s->server ? SSL_ST_ACCEPT : SSL_ST_CONNECT;
1075 #endif
1076                         s->new_session=1;
1077                         }
1078                 i=s->handshake_func(s);
1079                 if (i < 0) return(i);
1080                 if (i == 0)
1081                         {
1082                         SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
1083                         return(-1);
1084                         }
1085
1086                 if (!(s->mode & SSL_MODE_AUTO_RETRY))
1087                         {
1088                         if (s->s3->rbuf.left == 0) /* no read-ahead left? */
1089                                 {
1090                                 BIO *bio;
1091                                 /* In the case where we try to read application data,
1092                                  * but we trigger an SSL handshake, we return -1 with
1093                                  * the retry option set.  Otherwise renegotiation may
1094                                  * cause nasty problems in the blocking world */
1095                                 s->rwstate=SSL_READING;
1096                                 bio=SSL_get_rbio(s);
1097                                 BIO_clear_retry_flags(bio);
1098                                 BIO_set_retry_read(bio);
1099                                 return(-1);
1100                                 }
1101                         }
1102                 goto start;
1103                 }
1104
1105         switch (rr->type)
1106                 {
1107         default:
1108 #ifndef OPENSSL_NO_TLS
1109                 /* TLS just ignores unknown message types */
1110                 if (s->version == TLS1_VERSION)
1111                         {
1112                         rr->length = 0;
1113                         goto start;
1114                         }
1115 #endif
1116                 al=SSL_AD_UNEXPECTED_MESSAGE;
1117                 SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
1118                 goto f_err;
1119         case SSL3_RT_CHANGE_CIPHER_SPEC:
1120         case SSL3_RT_ALERT:
1121         case SSL3_RT_HANDSHAKE:
1122                 /* we already handled all of these, with the possible exception
1123                  * of SSL3_RT_HANDSHAKE when s->in_handshake is set, but that
1124                  * should not happen when type != rr->type */
1125                 al=SSL_AD_UNEXPECTED_MESSAGE;
1126                 SSLerr(SSL_F_DTLS1_READ_BYTES,ERR_R_INTERNAL_ERROR);
1127                 goto f_err;
1128         case SSL3_RT_APPLICATION_DATA:
1129                 /* At this point, we were expecting handshake data,
1130                  * but have application data.  If the library was
1131                  * running inside ssl3_read() (i.e. in_read_app_data
1132                  * is set) and it makes sense to read application data
1133                  * at this point (session renegotiation not yet started),
1134                  * we will indulge it.
1135                  */
1136                 if (s->s3->in_read_app_data &&
1137                         (s->s3->total_renegotiations != 0) &&
1138                         ((
1139                                 (s->state & SSL_ST_CONNECT) &&
1140                                 (s->state >= SSL3_ST_CW_CLNT_HELLO_A) &&
1141                                 (s->state <= SSL3_ST_CR_SRVR_HELLO_A)
1142                                 ) || (
1143                                         (s->state & SSL_ST_ACCEPT) &&
1144                                         (s->state <= SSL3_ST_SW_HELLO_REQ_A) &&
1145                                         (s->state >= SSL3_ST_SR_CLNT_HELLO_A)
1146                                         )
1147                                 ))
1148                         {
1149                         s->s3->in_read_app_data=2;
1150                         return(-1);
1151                         }
1152                 else
1153                         {
1154                         al=SSL_AD_UNEXPECTED_MESSAGE;
1155                         SSLerr(SSL_F_DTLS1_READ_BYTES,SSL_R_UNEXPECTED_RECORD);
1156                         goto f_err;
1157                         }
1158                 }
1159         /* not reached */
1160
1161 f_err:
1162         ssl3_send_alert(s,SSL3_AL_FATAL,al);
1163 err:
1164         return(-1);
1165         }
1166
1167 int
1168 dtls1_write_app_data_bytes(SSL *s, int type, const void *buf_, int len)
1169         {
1170         unsigned int n,tot;
1171         int i;
1172
1173         if (SSL_in_init(s) && !s->in_handshake)
1174                 {
1175                 i=s->handshake_func(s);
1176                 if (i < 0) return(i);
1177                 if (i == 0)
1178                         {
1179                         SSLerr(SSL_F_DTLS1_WRITE_APP_DATA_BYTES,SSL_R_SSL_HANDSHAKE_FAILURE);
1180                         return -1;
1181                         }
1182                 }
1183
1184         tot = s->s3->wnum;
1185         n = len - tot;
1186
1187         while( n)
1188                 {
1189                 /* dtls1_write_bytes sends one record at a time, sized according to 
1190                  * the currently known MTU */
1191                 i = dtls1_write_bytes(s, type, buf_, len);
1192                 if (i <= 0) return i;
1193                 
1194                 if ((i == (int)n) ||
1195                         (type == SSL3_RT_APPLICATION_DATA &&
1196                                 (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE)))
1197                         {
1198                         /* next chunk of data should get another prepended empty fragment
1199                          * in ciphersuites with known-IV weakness: */
1200                         s->s3->empty_fragment_done = 0;
1201                         return tot+i;
1202                         }
1203
1204                 tot += i;
1205                 n-=i;
1206                 }
1207
1208         return tot;
1209         }
1210
1211
1212         /* this only happens when a client hello is received and a handshake 
1213          * is started. */
1214 static int
1215 have_handshake_fragment(SSL *s, int type, unsigned char *buf, 
1216         int len, int peek)
1217         {
1218         
1219         if ((type == SSL3_RT_HANDSHAKE) && (s->d1->handshake_fragment_len > 0))
1220                 /* (partially) satisfy request from storage */
1221                 {
1222                 unsigned char *src = s->d1->handshake_fragment;
1223                 unsigned char *dst = buf;
1224                 unsigned int k,n;
1225                 
1226                 /* peek == 0 */
1227                 n = 0;
1228                 while ((len > 0) && (s->d1->handshake_fragment_len > 0))
1229                         {
1230                         *dst++ = *src++;
1231                         len--; s->d1->handshake_fragment_len--;
1232                         n++;
1233                         }
1234                 /* move any remaining fragment bytes: */
1235                 for (k = 0; k < s->d1->handshake_fragment_len; k++)
1236                         s->d1->handshake_fragment[k] = *src++;
1237                 return n;
1238                 }
1239         
1240         return 0;
1241         }
1242
1243
1244
1245
1246 /* Call this to write data in records of type 'type'
1247  * It will return <= 0 if not all data has been sent or non-blocking IO.
1248  */
1249 int dtls1_write_bytes(SSL *s, int type, const void *buf_, int len)
1250         {
1251         const unsigned char *buf=buf_;
1252         unsigned int tot,n,nw;
1253         int i;
1254         unsigned int mtu;
1255
1256         s->rwstate=SSL_NOTHING;
1257         tot=s->s3->wnum;
1258
1259         n=(len-tot);
1260
1261         /* handshake layer figures out MTU for itself, but data records
1262          * are also sent through this interface, so need to figure out MTU */
1263 #if 0
1264         mtu = BIO_ctrl(SSL_get_wbio(s), BIO_CTRL_DGRAM_GET_MTU, 0, NULL);
1265         mtu += DTLS1_HM_HEADER_LENGTH;  /* HM already inserted */
1266 #endif
1267         mtu = s->d1->mtu;
1268
1269         if (mtu > SSL3_RT_MAX_PLAIN_LENGTH)
1270                 mtu = SSL3_RT_MAX_PLAIN_LENGTH;
1271
1272         if (n > mtu)
1273                 nw=mtu;
1274         else
1275                 nw=n;
1276         
1277         i=do_dtls1_write(s, type, &(buf[tot]), nw, 0);
1278         if (i <= 0)
1279                 {
1280                 s->s3->wnum=tot;
1281                 return i;
1282                 }
1283
1284         if ( (int)s->s3->wnum + i == len)
1285                 s->s3->wnum = 0;
1286         else 
1287                 s->s3->wnum += i;
1288
1289         return tot + i;
1290         }
1291
1292 int do_dtls1_write(SSL *s, int type, const unsigned char *buf, unsigned int len, int create_empty_fragment)
1293         {
1294         unsigned char *p,*pseq;
1295         int i,mac_size,clear=0;
1296         int prefix_len = 0;
1297         SSL3_RECORD *wr;
1298         SSL3_BUFFER *wb;
1299         SSL_SESSION *sess;
1300         int bs;
1301
1302         /* first check if there is a SSL3_BUFFER still being written
1303          * out.  This will happen with non blocking IO */
1304         if (s->s3->wbuf.left != 0)
1305                 {
1306                 OPENSSL_assert(0); /* XDTLS:  want to see if we ever get here */
1307                 return(ssl3_write_pending(s,type,buf,len));
1308                 }
1309
1310         /* If we have an alert to send, lets send it */
1311         if (s->s3->alert_dispatch)
1312                 {
1313                 i=s->method->ssl_dispatch_alert(s);
1314                 if (i <= 0)
1315                         return(i);
1316                 /* if it went, fall through and send more stuff */
1317                 }
1318
1319         if (len == 0 && !create_empty_fragment)
1320                 return 0;
1321
1322         wr= &(s->s3->wrec);
1323         wb= &(s->s3->wbuf);
1324         sess=s->session;
1325
1326         if (    (sess == NULL) ||
1327                 (s->enc_write_ctx == NULL) ||
1328                 (EVP_MD_CTX_md(s->write_hash) == NULL))
1329                 clear=1;
1330
1331         if (clear)
1332                 mac_size=0;
1333         else
1334                 mac_size=EVP_MD_CTX_size(s->write_hash);
1335
1336         /* DTLS implements explicit IV, so no need for empty fragments */
1337 #if 0
1338         /* 'create_empty_fragment' is true only when this function calls itself */
1339         if (!clear && !create_empty_fragment && !s->s3->empty_fragment_done
1340                 && SSL_version(s) != DTLS1_VERSION)
1341                 {
1342                 /* countermeasure against known-IV weakness in CBC ciphersuites
1343                  * (see http://www.openssl.org/~bodo/tls-cbc.txt) 
1344                  */
1345
1346                 if (s->s3->need_empty_fragments && type == SSL3_RT_APPLICATION_DATA)
1347                         {
1348                         /* recursive function call with 'create_empty_fragment' set;
1349                          * this prepares and buffers the data for an empty fragment
1350                          * (these 'prefix_len' bytes are sent out later
1351                          * together with the actual payload) */
1352                         prefix_len = s->method->do_ssl_write(s, type, buf, 0, 1);
1353                         if (prefix_len <= 0)
1354                                 goto err;
1355
1356                         if (s->s3->wbuf.len < (size_t)prefix_len + SSL3_RT_MAX_PACKET_SIZE)
1357                                 {
1358                                 /* insufficient space */
1359                                 SSLerr(SSL_F_DO_DTLS1_WRITE, ERR_R_INTERNAL_ERROR);
1360                                 goto err;
1361                                 }
1362                         }
1363                 
1364                 s->s3->empty_fragment_done = 1;
1365                 }
1366 #endif
1367
1368         p = wb->buf + prefix_len;
1369
1370         /* write the header */
1371
1372         *(p++)=type&0xff;
1373         wr->type=type;
1374
1375         *(p++)=(s->version>>8);
1376         *(p++)=s->version&0xff;
1377
1378         /* field where we are to write out packet epoch, seq num and len */
1379         pseq=p; 
1380         p+=10;
1381
1382         /* lets setup the record stuff. */
1383
1384         /* Make space for the explicit IV in case of CBC.
1385          * (this is a bit of a boundary violation, but what the heck).
1386          */
1387         if ( s->enc_write_ctx && 
1388                 (EVP_CIPHER_mode( s->enc_write_ctx->cipher ) & EVP_CIPH_CBC_MODE))
1389                 bs = EVP_CIPHER_block_size(s->enc_write_ctx->cipher);
1390         else
1391                 bs = 0;
1392
1393         wr->data=p + bs;  /* make room for IV in case of CBC */
1394         wr->length=(int)len;
1395         wr->input=(unsigned char *)buf;
1396
1397         /* we now 'read' from wr->input, wr->length bytes into
1398          * wr->data */
1399
1400         /* first we compress */
1401         if (s->compress != NULL)
1402                 {
1403                 if (!ssl3_do_compress(s))
1404                         {
1405                         SSLerr(SSL_F_DO_DTLS1_WRITE,SSL_R_COMPRESSION_FAILURE);
1406                         goto err;
1407                         }
1408                 }
1409         else
1410                 {
1411                 memcpy(wr->data,wr->input,wr->length);
1412                 wr->input=wr->data;
1413                 }
1414
1415         /* we should still have the output to wr->data and the input
1416          * from wr->input.  Length should be wr->length.
1417          * wr->data still points in the wb->buf */
1418
1419         if (mac_size != 0)
1420                 {
1421                 s->method->ssl3_enc->mac(s,&(p[wr->length + bs]),1);
1422                 wr->length+=mac_size;
1423                 }
1424
1425         /* this is true regardless of mac size */
1426         wr->input=p;
1427         wr->data=p;
1428
1429
1430         /* ssl3_enc can only have an error on read */
1431         if (bs) /* bs != 0 in case of CBC */
1432                 {
1433                 RAND_pseudo_bytes(p,bs);
1434                 /* master IV and last CBC residue stand for
1435                  * the rest of randomness */
1436                 wr->length += bs;
1437                 }
1438
1439         s->method->ssl3_enc->enc(s,1);
1440
1441         /* record length after mac and block padding */
1442 /*      if (type == SSL3_RT_APPLICATION_DATA ||
1443         (type == SSL3_RT_ALERT && ! SSL_in_init(s))) */
1444         
1445         /* there's only one epoch between handshake and app data */
1446         
1447         s2n(s->d1->w_epoch, pseq);
1448
1449         /* XDTLS: ?? */
1450 /*      else
1451         s2n(s->d1->handshake_epoch, pseq); */
1452
1453         memcpy(pseq, &(s->s3->write_sequence[2]), 6);
1454         pseq+=6;
1455         s2n(wr->length,pseq);
1456
1457         /* we should now have
1458          * wr->data pointing to the encrypted data, which is
1459          * wr->length long */
1460         wr->type=type; /* not needed but helps for debugging */
1461         wr->length+=DTLS1_RT_HEADER_LENGTH;
1462
1463 #if 0  /* this is now done at the message layer */
1464         /* buffer the record, making it easy to handle retransmits */
1465         if ( type == SSL3_RT_HANDSHAKE || type == SSL3_RT_CHANGE_CIPHER_SPEC)
1466                 dtls1_buffer_record(s, wr->data, wr->length, 
1467                         *((PQ_64BIT *)&(s->s3->write_sequence[0])));
1468 #endif
1469
1470         ssl3_record_sequence_update(&(s->s3->write_sequence[0]));
1471
1472         if (create_empty_fragment)
1473                 {
1474                 /* we are in a recursive call;
1475                  * just return the length, don't write out anything here
1476                  */
1477                 return wr->length;
1478                 }
1479
1480         /* now let's set up wb */
1481         wb->left = prefix_len + wr->length;
1482         wb->offset = 0;
1483
1484         /* memorize arguments so that ssl3_write_pending can detect bad write retries later */
1485         s->s3->wpend_tot=len;
1486         s->s3->wpend_buf=buf;
1487         s->s3->wpend_type=type;
1488         s->s3->wpend_ret=len;
1489
1490         /* we now just need to write the buffer */
1491         return ssl3_write_pending(s,type,buf,len);
1492 err:
1493         return -1;
1494         }
1495
1496
1497
1498 static int dtls1_record_replay_check(SSL *s, DTLS1_BITMAP *bitmap)
1499         {
1500         int cmp;
1501         unsigned int shift;
1502         const unsigned char *seq = s->s3->read_sequence;
1503
1504         cmp = satsub64be(seq,bitmap->max_seq_num);
1505         if (cmp > 0)
1506                 {
1507                 memcpy (s->s3->rrec.seq_num,seq,8);
1508                 return 1; /* this record in new */
1509                 }
1510         shift = -cmp;
1511         if (shift >= sizeof(bitmap->map)*8)
1512                 return 0; /* stale, outside the window */
1513         else if (bitmap->map & (1UL<<shift))
1514                 return 0; /* record previously received */
1515
1516         memcpy (s->s3->rrec.seq_num,seq,8);
1517         return 1;
1518         }
1519
1520
1521 static void dtls1_record_bitmap_update(SSL *s, DTLS1_BITMAP *bitmap)
1522         {
1523         int cmp;
1524         unsigned int shift;
1525         const unsigned char *seq = s->s3->read_sequence;
1526
1527         cmp = satsub64be(seq,bitmap->max_seq_num);
1528         if (cmp > 0)
1529                 {
1530                 shift = cmp;
1531                 if (shift < sizeof(bitmap->map)*8)
1532                         bitmap->map <<= shift, bitmap->map |= 1UL;
1533                 else
1534                         bitmap->map = 1UL;
1535                 memcpy(bitmap->max_seq_num,seq,8);
1536                 }
1537         else    {
1538                 shift = -cmp;
1539                 if (shift < sizeof(bitmap->map)*8)
1540                         bitmap->map |= 1UL<<shift;
1541                 }
1542         }
1543
1544
1545 int dtls1_dispatch_alert(SSL *s)
1546         {
1547         int i,j;
1548         void (*cb)(const SSL *ssl,int type,int val)=NULL;
1549         unsigned char buf[2 + 2 + 3]; /* alert level + alert desc + message seq +frag_off */
1550         unsigned char *ptr = &buf[0];
1551
1552         s->s3->alert_dispatch=0;
1553
1554         memset(buf, 0x00, sizeof(buf));
1555         *ptr++ = s->s3->send_alert[0];
1556         *ptr++ = s->s3->send_alert[1];
1557
1558 #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
1559         if (s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE)
1560                 {       
1561                 s2n(s->d1->handshake_read_seq, ptr);
1562 #if 0
1563                 if ( s->d1->r_msg_hdr.frag_off == 0)  /* waiting for a new msg */
1564
1565                 else
1566                         s2n(s->d1->r_msg_hdr.seq, ptr); /* partial msg read */
1567 #endif
1568
1569 #if 0
1570                 fprintf(stderr, "s->d1->handshake_read_seq = %d, s->d1->r_msg_hdr.seq = %d\n",s->d1->handshake_read_seq,s->d1->r_msg_hdr.seq);
1571 #endif
1572                 l2n3(s->d1->r_msg_hdr.frag_off, ptr);
1573                 }
1574 #endif
1575
1576         i = do_dtls1_write(s, SSL3_RT_ALERT, &buf[0], sizeof(buf), 0);
1577         if (i <= 0)
1578                 {
1579                 s->s3->alert_dispatch=1;
1580                 /* fprintf( stderr, "not done with alert\n" ); */
1581                 }
1582         else
1583                 {
1584                 if (s->s3->send_alert[0] == SSL3_AL_FATAL
1585 #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
1586                     || s->s3->send_alert[1] == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
1587 #endif
1588                     )
1589                         (void)BIO_flush(s->wbio);
1590
1591                 if (s->msg_callback)
1592                         s->msg_callback(1, s->version, SSL3_RT_ALERT, s->s3->send_alert, 
1593                                 2, s, s->msg_callback_arg);
1594
1595                 if (s->info_callback != NULL)
1596                         cb=s->info_callback;
1597                 else if (s->ctx->info_callback != NULL)
1598                         cb=s->ctx->info_callback;
1599
1600                 if (cb != NULL)
1601                         {
1602                         j=(s->s3->send_alert[0]<<8)|s->s3->send_alert[1];
1603                         cb(s,SSL_CB_WRITE_ALERT,j);
1604                         }
1605                 }
1606         return(i);
1607         }
1608
1609
1610 static DTLS1_BITMAP *
1611 dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr, unsigned int *is_next_epoch)
1612     {
1613     
1614     *is_next_epoch = 0;
1615
1616     /* In current epoch, accept HM, CCS, DATA, & ALERT */
1617     if (rr->epoch == s->d1->r_epoch)
1618         return &s->d1->bitmap;
1619
1620     /* Only HM and ALERT messages can be from the next epoch */
1621     else if (rr->epoch == (unsigned long)(s->d1->r_epoch + 1) &&
1622         (rr->type == SSL3_RT_HANDSHAKE ||
1623             rr->type == SSL3_RT_ALERT))
1624         {
1625         *is_next_epoch = 1;
1626         return &s->d1->next_bitmap;
1627         }
1628
1629     return NULL;
1630     }
1631
1632 #if 0
1633 static int
1634 dtls1_record_needs_buffering(SSL *s, SSL3_RECORD *rr, unsigned short *priority,
1635         unsigned long *offset)
1636         {
1637
1638         /* alerts are passed up immediately */
1639         if ( rr->type == SSL3_RT_APPLICATION_DATA ||
1640                 rr->type == SSL3_RT_ALERT)
1641                 return 0;
1642
1643         /* Only need to buffer if a handshake is underway.
1644          * (this implies that Hello Request and Client Hello are passed up
1645          * immediately) */
1646         if ( SSL_in_init(s))
1647                 {
1648                 unsigned char *data = rr->data;
1649                 /* need to extract the HM/CCS sequence number here */
1650                 if ( rr->type == SSL3_RT_HANDSHAKE ||
1651                         rr->type == SSL3_RT_CHANGE_CIPHER_SPEC)
1652                         {
1653                         unsigned short seq_num;
1654                         struct hm_header_st msg_hdr;
1655                         struct ccs_header_st ccs_hdr;
1656
1657                         if ( rr->type == SSL3_RT_HANDSHAKE)
1658                                 {
1659                                 dtls1_get_message_header(data, &msg_hdr);
1660                                 seq_num = msg_hdr.seq;
1661                                 *offset = msg_hdr.frag_off;
1662                                 }
1663                         else
1664                                 {
1665                                 dtls1_get_ccs_header(data, &ccs_hdr);
1666                                 seq_num = ccs_hdr.seq;
1667                                 *offset = 0;
1668                                 }
1669                                 
1670                         /* this is either a record we're waiting for, or a
1671                          * retransmit of something we happened to previously 
1672                          * receive (higher layers will drop the repeat silently */
1673                         if ( seq_num < s->d1->handshake_read_seq)
1674                                 return 0;
1675                         if (rr->type == SSL3_RT_HANDSHAKE && 
1676                                 seq_num == s->d1->handshake_read_seq &&
1677                                 msg_hdr.frag_off < s->d1->r_msg_hdr.frag_off)
1678                                 return 0;
1679                         else if ( seq_num == s->d1->handshake_read_seq &&
1680                                 (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC ||
1681                                         msg_hdr.frag_off == s->d1->r_msg_hdr.frag_off))
1682                                 return 0;
1683                         else
1684                                 {
1685                                 *priority = seq_num;
1686                                 return 1;
1687                                 }
1688                         }
1689                 else /* unknown record type */
1690                         return 0;
1691                 }
1692
1693         return 0;
1694         }
1695 #endif
1696
1697 void
1698 dtls1_reset_seq_numbers(SSL *s, int rw)
1699         {
1700         unsigned char *seq;
1701         unsigned int seq_bytes = sizeof(s->s3->read_sequence);
1702
1703         if ( rw & SSL3_CC_READ)
1704                 {
1705                 seq = s->s3->read_sequence;
1706                 s->d1->r_epoch++;
1707                 memcpy(&(s->d1->bitmap), &(s->d1->next_bitmap), sizeof(DTLS1_BITMAP));
1708                 memset(&(s->d1->next_bitmap), 0x00, sizeof(DTLS1_BITMAP));
1709                 }
1710         else
1711                 {
1712                 seq = s->s3->write_sequence;
1713                 s->d1->w_epoch++;
1714                 }
1715
1716         memset(seq, 0x00, seq_bytes);
1717         }
1718
1719
1720 static void
1721 dtls1_clear_timeouts(SSL *s)
1722         {
1723         memset(&(s->d1->timeout), 0x00, sizeof(struct dtls1_timeout_st));
1724         }