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