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