Copyright consolidation 01/10
[openssl.git] / ssl / record / rec_layer_d1.c
1 /*
2  * Copyright 2005-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9
10 #include <stdio.h>
11 #include <errno.h>
12 #define USE_SOCKETS
13 #include "../ssl_locl.h"
14 #include <openssl/evp.h>
15 #include <openssl/buffer.h>
16 #include <openssl/rand.h>
17 #include "record_locl.h"
18
19 int DTLS_RECORD_LAYER_new(RECORD_LAYER *rl)
20 {
21     DTLS_RECORD_LAYER *d;
22     
23     if ((d = OPENSSL_malloc(sizeof(*d))) == NULL)
24         return (0);
25
26
27     rl->d = d;
28
29     d->unprocessed_rcds.q = pqueue_new();
30     d->processed_rcds.q = pqueue_new();
31     d->buffered_app_data.q = pqueue_new();
32
33     if (d->unprocessed_rcds.q == NULL || d->processed_rcds.q == NULL
34         || d->buffered_app_data.q == NULL) {
35         pqueue_free(d->unprocessed_rcds.q);
36         pqueue_free(d->processed_rcds.q);
37         pqueue_free(d->buffered_app_data.q);
38         OPENSSL_free(d);
39         rl->d = NULL;
40         return (0);
41     }
42
43     return 1;
44 }
45
46 void DTLS_RECORD_LAYER_free(RECORD_LAYER *rl)
47 {
48     DTLS_RECORD_LAYER_clear(rl);
49     pqueue_free(rl->d->unprocessed_rcds.q);
50     pqueue_free(rl->d->processed_rcds.q);
51     pqueue_free(rl->d->buffered_app_data.q);
52     OPENSSL_free(rl->d);
53     rl->d = NULL;
54 }
55
56 void DTLS_RECORD_LAYER_clear(RECORD_LAYER *rl)
57 {
58     DTLS_RECORD_LAYER *d;
59     pitem *item = NULL;
60     DTLS1_RECORD_DATA *rdata;
61     pqueue *unprocessed_rcds;
62     pqueue *processed_rcds;
63     pqueue *buffered_app_data;
64
65     d = rl->d;
66     
67     while ((item = pqueue_pop(d->unprocessed_rcds.q)) != NULL) {
68         rdata = (DTLS1_RECORD_DATA *)item->data;
69         OPENSSL_free(rdata->rbuf.buf);
70         OPENSSL_free(item->data);
71         pitem_free(item);
72     }
73
74     while ((item = pqueue_pop(d->processed_rcds.q)) != NULL) {
75         rdata = (DTLS1_RECORD_DATA *)item->data;
76         OPENSSL_free(rdata->rbuf.buf);
77         OPENSSL_free(item->data);
78         pitem_free(item);
79     }
80
81     while ((item = pqueue_pop(d->buffered_app_data.q)) != NULL) {
82         rdata = (DTLS1_RECORD_DATA *)item->data;
83         OPENSSL_free(rdata->rbuf.buf);
84         OPENSSL_free(item->data);
85         pitem_free(item);
86     }
87
88     unprocessed_rcds = d->unprocessed_rcds.q;
89     processed_rcds = d->processed_rcds.q;
90     buffered_app_data = d->buffered_app_data.q;
91     memset(d, 0, sizeof(*d));
92     d->unprocessed_rcds.q = unprocessed_rcds;
93     d->processed_rcds.q = processed_rcds;
94     d->buffered_app_data.q = buffered_app_data;
95 }
96
97 void DTLS_RECORD_LAYER_set_saved_w_epoch(RECORD_LAYER *rl, unsigned short e)
98 {
99     if (e == rl->d->w_epoch - 1) {
100         memcpy(rl->d->curr_write_sequence,
101                rl->write_sequence,
102                sizeof(rl->write_sequence));
103         memcpy(rl->write_sequence,
104                rl->d->last_write_sequence,
105                sizeof(rl->write_sequence));
106     } else if (e == rl->d->w_epoch + 1) {
107         memcpy(rl->d->last_write_sequence,
108                rl->write_sequence,
109                sizeof(unsigned char[8]));
110         memcpy(rl->write_sequence,
111                rl->d->curr_write_sequence,
112                sizeof(rl->write_sequence));
113     }
114     rl->d->w_epoch = e;
115 }
116
117 void DTLS_RECORD_LAYER_resync_write(RECORD_LAYER *rl)
118 {
119     memcpy(rl->write_sequence, rl->read_sequence, sizeof(rl->write_sequence));
120 }
121
122
123 void DTLS_RECORD_LAYER_set_write_sequence(RECORD_LAYER *rl, unsigned char *seq)
124 {
125     memcpy(rl->write_sequence, seq, SEQ_NUM_SIZE);
126 }
127
128 static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
129                                    int len);
130
131 /* copy buffered record into SSL structure */
132 static int dtls1_copy_record(SSL *s, pitem *item)
133 {
134     DTLS1_RECORD_DATA *rdata;
135
136     rdata = (DTLS1_RECORD_DATA *)item->data;
137
138     SSL3_BUFFER_release(&s->rlayer.rbuf);
139
140     s->rlayer.packet = rdata->packet;
141     s->rlayer.packet_length = rdata->packet_length;
142     memcpy(&s->rlayer.rbuf, &(rdata->rbuf), sizeof(SSL3_BUFFER));
143     memcpy(&s->rlayer.rrec, &(rdata->rrec), sizeof(SSL3_RECORD));
144
145     /* Set proper sequence number for mac calculation */
146     memcpy(&(s->rlayer.read_sequence[2]), &(rdata->packet[5]), 6);
147
148     return (1);
149 }
150
151 int dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
152 {
153     DTLS1_RECORD_DATA *rdata;
154     pitem *item;
155
156     /* Limit the size of the queue to prevent DOS attacks */
157     if (pqueue_size(queue->q) >= 100)
158         return 0;
159
160     rdata = OPENSSL_malloc(sizeof(*rdata));
161     item = pitem_new(priority, rdata);
162     if (rdata == NULL || item == NULL) {
163         OPENSSL_free(rdata);
164         pitem_free(item);
165         SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
166         return -1;
167     }
168
169     rdata->packet = s->rlayer.packet;
170     rdata->packet_length = s->rlayer.packet_length;
171     memcpy(&(rdata->rbuf), &s->rlayer.rbuf, sizeof(SSL3_BUFFER));
172     memcpy(&(rdata->rrec), &s->rlayer.rrec, sizeof(SSL3_RECORD));
173
174     item->data = rdata;
175
176 #ifndef OPENSSL_NO_SCTP
177     /* Store bio_dgram_sctp_rcvinfo struct */
178     if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
179         (SSL_get_state(s) == TLS_ST_SR_FINISHED
180          || SSL_get_state(s) == TLS_ST_CR_FINISHED)) {
181         BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_GET_RCVINFO,
182                  sizeof(rdata->recordinfo), &rdata->recordinfo);
183     }
184 #endif
185
186     s->rlayer.packet = NULL;
187     s->rlayer.packet_length = 0;
188     memset(&s->rlayer.rbuf, 0, sizeof(s->rlayer.rbuf));
189     memset(&s->rlayer.rrec, 0, sizeof(s->rlayer.rrec));
190
191     if (!ssl3_setup_buffers(s)) {
192         SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
193         OPENSSL_free(rdata->rbuf.buf);
194         OPENSSL_free(rdata);
195         pitem_free(item);
196         return (-1);
197     }
198
199     /* insert should not fail, since duplicates are dropped */
200     if (pqueue_insert(queue->q, item) == NULL) {
201         SSLerr(SSL_F_DTLS1_BUFFER_RECORD, ERR_R_INTERNAL_ERROR);
202         OPENSSL_free(rdata->rbuf.buf);
203         OPENSSL_free(rdata);
204         pitem_free(item);
205         return (-1);
206     }
207
208     return (1);
209 }
210
211 int dtls1_retrieve_buffered_record(SSL *s, record_pqueue *queue)
212 {
213     pitem *item;
214
215     item = pqueue_pop(queue->q);
216     if (item) {
217         dtls1_copy_record(s, item);
218
219         OPENSSL_free(item->data);
220         pitem_free(item);
221
222         return (1);
223     }
224
225     return (0);
226 }
227
228 /*
229  * retrieve a buffered record that belongs to the new epoch, i.e., not
230  * processed yet
231  */
232 #define dtls1_get_unprocessed_record(s) \
233                    dtls1_retrieve_buffered_record((s), \
234                    &((s)->rlayer.d->unprocessed_rcds))
235
236
237 int dtls1_process_buffered_records(SSL *s)
238 {
239     pitem *item;
240
241     item = pqueue_peek(s->rlayer.d->unprocessed_rcds.q);
242     if (item) {
243         /* Check if epoch is current. */
244         if (s->rlayer.d->unprocessed_rcds.epoch != s->rlayer.d->r_epoch)
245             return (1);         /* Nothing to do. */
246
247         /* Process all the records. */
248         while (pqueue_peek(s->rlayer.d->unprocessed_rcds.q)) {
249             dtls1_get_unprocessed_record(s);
250             if (!dtls1_process_record(s))
251                 return (0);
252             if (dtls1_buffer_record(s, &(s->rlayer.d->processed_rcds),
253                 SSL3_RECORD_get_seq_num(s->rlayer.rrec)) < 0)
254                 return -1;
255         }
256     }
257
258     /*
259      * sync epoch numbers once all the unprocessed records have been
260      * processed
261      */
262     s->rlayer.d->processed_rcds.epoch = s->rlayer.d->r_epoch;
263     s->rlayer.d->unprocessed_rcds.epoch = s->rlayer.d->r_epoch + 1;
264
265     return (1);
266 }
267
268
269 /*-
270  * Return up to 'len' payload bytes received in 'type' records.
271  * 'type' is one of the following:
272  *
273  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
274  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
275  *   -  0 (during a shutdown, no data has to be returned)
276  *
277  * If we don't have stored data to work from, read a SSL/TLS record first
278  * (possibly multiple records if we still don't have anything to return).
279  *
280  * This function must handle any surprises the peer may have for us, such as
281  * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
282  * messages are treated as if they were handshake messages *if* the |recd_type|
283  * argument is non NULL.
284  * Also if record payloads contain fragments too small to process, we store
285  * them until there is enough for the respective protocol (the record protocol
286  * may use arbitrary fragmentation and even interleaving):
287  *     Change cipher spec protocol
288  *             just 1 byte needed, no need for keeping anything stored
289  *     Alert protocol
290  *             2 bytes needed (AlertLevel, AlertDescription)
291  *     Handshake protocol
292  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
293  *             to detect unexpected Client Hello and Hello Request messages
294  *             here, anything else is handled by higher layers
295  *     Application data protocol
296  *             none of our business
297  */
298 int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
299                      int len, int peek)
300 {
301     int al, i, j, ret;
302     unsigned int n;
303     SSL3_RECORD *rr;
304     void (*cb) (const SSL *ssl, int type2, int val) = NULL;
305
306     if (!SSL3_BUFFER_is_initialised(&s->rlayer.rbuf)) {
307         /* Not initialized yet */
308         if (!ssl3_setup_buffers(s))
309             return (-1);
310     }
311
312     if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
313          (type != SSL3_RT_HANDSHAKE)) ||
314         (peek && (type != SSL3_RT_APPLICATION_DATA))) {
315         SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
316         return -1;
317     }
318
319     /*
320      * check whether there's a handshake message (client hello?) waiting
321      */
322     if ((ret = have_handshake_fragment(s, type, buf, len)))
323         return ret;
324
325     /*
326      * Now s->rlayer.d->handshake_fragment_len == 0 if
327      * type == SSL3_RT_HANDSHAKE.
328      */
329
330 #ifndef OPENSSL_NO_SCTP
331     /*
332      * Continue handshake if it had to be interrupted to read app data with
333      * SCTP.
334      */
335     if ((!ossl_statem_get_in_handshake(s) && SSL_in_init(s)) ||
336         (BIO_dgram_is_sctp(SSL_get_rbio(s))
337          && ossl_statem_in_sctp_read_sock(s)
338          && s->s3->in_read_app_data != 2))
339 #else
340     if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s))
341 #endif
342     {
343         /* type == SSL3_RT_APPLICATION_DATA */
344         i = s->handshake_func(s);
345         if (i < 0)
346             return (i);
347         if (i == 0) {
348             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
349             return (-1);
350         }
351     }
352
353  start:
354     s->rwstate = SSL_NOTHING;
355
356     /*-
357      * s->s3->rrec.type         - is the type of record
358      * s->s3->rrec.data,    - data
359      * s->s3->rrec.off,     - offset into 'data' for next read
360      * s->s3->rrec.length,  - number of bytes.
361      */
362     rr = s->rlayer.rrec;
363
364     /*
365      * We are not handshaking and have no data yet, so process data buffered
366      * during the last handshake in advance, if any.
367      */
368     if (SSL_is_init_finished(s) && SSL3_RECORD_get_length(rr) == 0) {
369         pitem *item;
370         item = pqueue_pop(s->rlayer.d->buffered_app_data.q);
371         if (item) {
372 #ifndef OPENSSL_NO_SCTP
373             /* Restore bio_dgram_sctp_rcvinfo struct */
374             if (BIO_dgram_is_sctp(SSL_get_rbio(s))) {
375                 DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *)item->data;
376                 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO,
377                          sizeof(rdata->recordinfo), &rdata->recordinfo);
378             }
379 #endif
380
381             dtls1_copy_record(s, item);
382
383             OPENSSL_free(item->data);
384             pitem_free(item);
385         }
386     }
387
388     /* Check for timeout */
389     if (dtls1_handle_timeout(s) > 0)
390         goto start;
391
392     /* get new packet if necessary */
393     if ((SSL3_RECORD_get_length(rr) == 0)
394             || (s->rlayer.rstate == SSL_ST_READ_BODY)) {
395         ret = dtls1_get_record(s);
396         if (ret <= 0) {
397             ret = dtls1_read_failed(s, ret);
398             /* anything other than a timeout is an error */
399             if (ret <= 0)
400                 return (ret);
401             else
402                 goto start;
403         }
404     }
405
406     /* we now have a packet which can be read and processed */
407
408     if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
409                                    * reset by ssl3_get_finished */
410         && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) {
411         /*
412          * We now have application data between CCS and Finished. Most likely
413          * the packets were reordered on their way, so buffer the application
414          * data for later processing rather than dropping the connection.
415          */
416         if (dtls1_buffer_record(s, &(s->rlayer.d->buffered_app_data),
417             SSL3_RECORD_get_seq_num(rr)) < 0) {
418             SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
419             return -1;
420         }
421         SSL3_RECORD_set_length(rr, 0);
422         goto start;
423     }
424
425     /*
426      * If the other end has shut down, throw anything we read away (even in
427      * 'peek' mode)
428      */
429     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
430         SSL3_RECORD_set_length(rr, 0);
431         s->rwstate = SSL_NOTHING;
432         return (0);
433     }
434
435     if (type == SSL3_RECORD_get_type(rr)
436             || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
437                 && type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) {
438         /*
439          * SSL3_RT_APPLICATION_DATA or
440          * SSL3_RT_HANDSHAKE or
441          * SSL3_RT_CHANGE_CIPHER_SPEC
442          */
443         /*
444          * make sure that we are not getting application data when we are
445          * doing a handshake for the first time
446          */
447         if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
448             (s->enc_read_ctx == NULL)) {
449             al = SSL_AD_UNEXPECTED_MESSAGE;
450             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
451             goto f_err;
452         }
453
454         if (recvd_type != NULL)
455             *recvd_type = SSL3_RECORD_get_type(rr);
456
457         if (len <= 0)
458             return (len);
459
460         if ((unsigned int)len > SSL3_RECORD_get_length(rr))
461             n = SSL3_RECORD_get_length(rr);
462         else
463             n = (unsigned int)len;
464
465         memcpy(buf, &(SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)]), n);
466         if (!peek) {
467             SSL3_RECORD_add_length(rr, -n);
468             SSL3_RECORD_add_off(rr, n);
469             if (SSL3_RECORD_get_length(rr) == 0) {
470                 s->rlayer.rstate = SSL_ST_READ_HEADER;
471                 SSL3_RECORD_set_off(rr, 0);
472             }
473         }
474 #ifndef OPENSSL_NO_SCTP
475         /*
476          * We were about to renegotiate but had to read belated application
477          * data first, so retry.
478          */
479         if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
480             SSL3_RECORD_get_type(rr) == SSL3_RT_APPLICATION_DATA &&
481             ossl_statem_in_sctp_read_sock(s)) {
482             s->rwstate = SSL_READING;
483             BIO_clear_retry_flags(SSL_get_rbio(s));
484             BIO_set_retry_read(SSL_get_rbio(s));
485         }
486
487         /*
488          * We might had to delay a close_notify alert because of reordered
489          * app data. If there was an alert and there is no message to read
490          * anymore, finally set shutdown.
491          */
492         if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
493             s->d1->shutdown_received
494             && !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
495             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
496             return (0);
497         }
498 #endif
499         return (n);
500     }
501
502     /*
503      * If we get here, then type != rr->type; if we have a handshake message,
504      * then it was unexpected (Hello Request or Client Hello).
505      */
506
507     /*
508      * In case of record types for which we have 'fragment' storage, fill
509      * that so that we can process the data at a fixed place.
510      */
511     {
512         unsigned int k, dest_maxlen = 0;
513         unsigned char *dest = NULL;
514         unsigned int *dest_len = NULL;
515
516         if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
517             dest_maxlen = sizeof s->rlayer.d->handshake_fragment;
518             dest = s->rlayer.d->handshake_fragment;
519             dest_len = &s->rlayer.d->handshake_fragment_len;
520         } else if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) {
521             dest_maxlen = sizeof(s->rlayer.d->alert_fragment);
522             dest = s->rlayer.d->alert_fragment;
523             dest_len = &s->rlayer.d->alert_fragment_len;
524         }
525 #ifndef OPENSSL_NO_HEARTBEATS
526         else if (SSL3_RECORD_get_type(rr) == DTLS1_RT_HEARTBEAT) {
527             /* We allow a 0 return */
528             if (dtls1_process_heartbeat(s, SSL3_RECORD_get_data(rr),
529                     SSL3_RECORD_get_length(rr)) < 0) {
530                 return -1;
531             }
532             /* Exit and notify application to read again */
533             SSL3_RECORD_set_length(rr, 0);
534             s->rwstate = SSL_READING;
535             BIO_clear_retry_flags(SSL_get_rbio(s));
536             BIO_set_retry_read(SSL_get_rbio(s));
537             return (-1);
538         }
539 #endif
540         /* else it's a CCS message, or application data or wrong */
541         else if (SSL3_RECORD_get_type(rr) != SSL3_RT_CHANGE_CIPHER_SPEC) {
542             /*
543              * Application data while renegotiating is allowed. Try again
544              * reading.
545              */
546             if (SSL3_RECORD_get_type(rr)  == SSL3_RT_APPLICATION_DATA) {
547                 BIO *bio;
548                 s->s3->in_read_app_data = 2;
549                 bio = SSL_get_rbio(s);
550                 s->rwstate = SSL_READING;
551                 BIO_clear_retry_flags(bio);
552                 BIO_set_retry_read(bio);
553                 return (-1);
554             }
555
556             /* Not certain if this is the right error handling */
557             al = SSL_AD_UNEXPECTED_MESSAGE;
558             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
559             goto f_err;
560         }
561
562         if (dest_maxlen > 0) {
563             /*
564              * XDTLS: In a pathological case, the Client Hello may be
565              * fragmented--don't always expect dest_maxlen bytes
566              */
567             if (SSL3_RECORD_get_length(rr)  < dest_maxlen) {
568 #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
569                 /*
570                  * for normal alerts rr->length is 2, while
571                  * dest_maxlen is 7 if we were to handle this
572                  * non-existing alert...
573                  */
574                 FIX ME
575 #endif
576                 s->rlayer.rstate = SSL_ST_READ_HEADER;
577                 SSL3_RECORD_set_length(rr, 0);
578                 goto start;
579             }
580
581             /* now move 'n' bytes: */
582             for (k = 0; k < dest_maxlen; k++) {
583                 dest[k] = SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)];
584                 SSL3_RECORD_add_off(rr, 1);
585                 SSL3_RECORD_add_length(rr, -1);
586             }
587             *dest_len = dest_maxlen;
588         }
589     }
590
591     /*-
592      * s->rlayer.d->handshake_fragment_len == 12  iff  rr->type == SSL3_RT_HANDSHAKE;
593      * s->rlayer.d->alert_fragment_len == 7      iff  rr->type == SSL3_RT_ALERT.
594      * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
595      */
596
597     /* If we are a client, check for an incoming 'Hello Request': */
598     if ((!s->server) &&
599         (s->rlayer.d->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
600         (s->rlayer.d->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
601         (s->session != NULL) && (s->session->cipher != NULL)) {
602         s->rlayer.d->handshake_fragment_len = 0;
603
604         if ((s->rlayer.d->handshake_fragment[1] != 0) ||
605             (s->rlayer.d->handshake_fragment[2] != 0) ||
606             (s->rlayer.d->handshake_fragment[3] != 0)) {
607             al = SSL_AD_DECODE_ERROR;
608             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
609             goto f_err;
610         }
611
612         /*
613          * no need to check sequence number on HELLO REQUEST messages
614          */
615
616         if (s->msg_callback)
617             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
618                             s->rlayer.d->handshake_fragment, 4, s,
619                             s->msg_callback_arg);
620
621         if (SSL_is_init_finished(s) &&
622             !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
623             !s->s3->renegotiate) {
624             s->d1->handshake_read_seq++;
625             s->new_session = 1;
626             ssl3_renegotiate(s);
627             if (ssl3_renegotiate_check(s)) {
628                 i = s->handshake_func(s);
629                 if (i < 0)
630                     return (i);
631                 if (i == 0) {
632                     SSLerr(SSL_F_DTLS1_READ_BYTES,
633                            SSL_R_SSL_HANDSHAKE_FAILURE);
634                     return (-1);
635                 }
636
637                 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
638                     if (SSL3_BUFFER_get_left(&s->rlayer.rbuf) == 0) {
639                         /* no read-ahead left? */
640                         BIO *bio;
641                         /*
642                          * In the case where we try to read application data,
643                          * but we trigger an SSL handshake, we return -1 with
644                          * the retry option set.  Otherwise renegotiation may
645                          * cause nasty problems in the blocking world
646                          */
647                         s->rwstate = SSL_READING;
648                         bio = SSL_get_rbio(s);
649                         BIO_clear_retry_flags(bio);
650                         BIO_set_retry_read(bio);
651                         return (-1);
652                     }
653                 }
654             }
655         }
656         /*
657          * we either finished a handshake or ignored the request, now try
658          * again to obtain the (application) data we were asked for
659          */
660         goto start;
661     }
662
663     if (s->rlayer.d->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) {
664         int alert_level = s->rlayer.d->alert_fragment[0];
665         int alert_descr = s->rlayer.d->alert_fragment[1];
666
667         s->rlayer.d->alert_fragment_len = 0;
668
669         if (s->msg_callback)
670             s->msg_callback(0, s->version, SSL3_RT_ALERT,
671                             s->rlayer.d->alert_fragment, 2, s,
672                             s->msg_callback_arg);
673
674         if (s->info_callback != NULL)
675             cb = s->info_callback;
676         else if (s->ctx->info_callback != NULL)
677             cb = s->ctx->info_callback;
678
679         if (cb != NULL) {
680             j = (alert_level << 8) | alert_descr;
681             cb(s, SSL_CB_READ_ALERT, j);
682         }
683
684         if (alert_level == SSL3_AL_WARNING) {
685             s->s3->warn_alert = alert_descr;
686             if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
687 #ifndef OPENSSL_NO_SCTP
688                 /*
689                  * With SCTP and streams the socket may deliver app data
690                  * after a close_notify alert. We have to check this first so
691                  * that nothing gets discarded.
692                  */
693                 if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
694                     BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
695                     s->d1->shutdown_received = 1;
696                     s->rwstate = SSL_READING;
697                     BIO_clear_retry_flags(SSL_get_rbio(s));
698                     BIO_set_retry_read(SSL_get_rbio(s));
699                     return -1;
700                 }
701 #endif
702                 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
703                 return (0);
704             }
705 #if 0
706             /* XXX: this is a possible improvement in the future */
707             /* now check if it's a missing record */
708             if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) {
709                 unsigned short seq;
710                 unsigned int frag_off;
711                 unsigned char *p = &(s->rlayer.d->alert_fragment[2]);
712
713                 n2s(p, seq);
714                 n2l3(p, frag_off);
715
716                 dtls1_retransmit_message(s,
717                                          dtls1_get_queue_priority
718                                          (frag->msg_header.seq, 0), frag_off,
719                                          &found);
720                 if (!found && SSL_in_init(s)) {
721                     /*
722                      * fprintf( stderr,"in init = %d\n", SSL_in_init(s));
723                      */
724                     /*
725                      * requested a message not yet sent, send an alert
726                      * ourselves
727                      */
728                     ssl3_send_alert(s, SSL3_AL_WARNING,
729                                     DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
730                 }
731             }
732 #endif
733         } else if (alert_level == SSL3_AL_FATAL) {
734             char tmp[16];
735
736             s->rwstate = SSL_NOTHING;
737             s->s3->fatal_alert = alert_descr;
738             SSLerr(SSL_F_DTLS1_READ_BYTES,
739                    SSL_AD_REASON_OFFSET + alert_descr);
740             BIO_snprintf(tmp, sizeof tmp, "%d", alert_descr);
741             ERR_add_error_data(2, "SSL alert number ", tmp);
742             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
743             SSL_CTX_remove_session(s->ctx, s->session);
744             return (0);
745         } else {
746             al = SSL_AD_ILLEGAL_PARAMETER;
747             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
748             goto f_err;
749         }
750
751         goto start;
752     }
753
754     if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
755                                             * shutdown */
756         s->rwstate = SSL_NOTHING;
757         SSL3_RECORD_set_length(rr, 0);
758         return (0);
759     }
760
761     if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {
762         /*
763          * We can't process a CCS now, because previous handshake messages
764          * are still missing, so just drop it.
765          */
766         SSL3_RECORD_set_length(rr, 0);
767         goto start;
768     }
769
770     /*
771      * Unexpected handshake message (Client Hello, or protocol violation)
772      */
773     if ((s->rlayer.d->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
774         !ossl_statem_get_in_handshake(s)) {
775         struct hm_header_st msg_hdr;
776
777         /* this may just be a stale retransmit */
778         dtls1_get_message_header(rr->data, &msg_hdr);
779         if (SSL3_RECORD_get_epoch(rr) != s->rlayer.d->r_epoch) {
780             SSL3_RECORD_set_length(rr, 0);
781             goto start;
782         }
783
784         /*
785          * If we are server, we may have a repeated FINISHED of the client
786          * here, then retransmit our CCS and FINISHED.
787          */
788         if (msg_hdr.type == SSL3_MT_FINISHED) {
789             if (dtls1_check_timeout_num(s) < 0)
790                 return -1;
791
792             dtls1_retransmit_buffered_messages(s);
793             SSL3_RECORD_set_length(rr, 0);
794             goto start;
795         }
796
797         if (SSL_is_init_finished(s) &&
798             !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
799             ossl_statem_set_in_init(s, 1);
800             s->renegotiate = 1;
801             s->new_session = 1;
802         }
803         i = s->handshake_func(s);
804         if (i < 0)
805             return (i);
806         if (i == 0) {
807             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
808             return (-1);
809         }
810
811         if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
812             if (SSL3_BUFFER_get_left(&s->rlayer.rbuf) == 0) {
813                 /* no read-ahead left? */
814                 BIO *bio;
815                 /*
816                  * In the case where we try to read application data, but we
817                  * trigger an SSL handshake, we return -1 with the retry
818                  * option set.  Otherwise renegotiation may cause nasty
819                  * problems in the blocking world
820                  */
821                 s->rwstate = SSL_READING;
822                 bio = SSL_get_rbio(s);
823                 BIO_clear_retry_flags(bio);
824                 BIO_set_retry_read(bio);
825                 return (-1);
826             }
827         }
828         goto start;
829     }
830
831     switch (SSL3_RECORD_get_type(rr)) {
832     default:
833         /* TLS just ignores unknown message types */
834         if (s->version == TLS1_VERSION) {
835             SSL3_RECORD_set_length(rr, 0);
836             goto start;
837         }
838         al = SSL_AD_UNEXPECTED_MESSAGE;
839         SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
840         goto f_err;
841     case SSL3_RT_CHANGE_CIPHER_SPEC:
842     case SSL3_RT_ALERT:
843     case SSL3_RT_HANDSHAKE:
844         /*
845          * we already handled all of these, with the possible exception of
846          * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
847          * that should not happen when type != rr->type
848          */
849         al = SSL_AD_UNEXPECTED_MESSAGE;
850         SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
851         goto f_err;
852     case SSL3_RT_APPLICATION_DATA:
853         /*
854          * At this point, we were expecting handshake data, but have
855          * application data.  If the library was running inside ssl3_read()
856          * (i.e. in_read_app_data is set) and it makes sense to read
857          * application data at this point (session renegotiation not yet
858          * started), we will indulge it.
859          */
860         if (s->s3->in_read_app_data &&
861             (s->s3->total_renegotiations != 0) &&
862             ossl_statem_app_data_allowed(s)) {
863             s->s3->in_read_app_data = 2;
864             return (-1);
865         } else {
866             al = SSL_AD_UNEXPECTED_MESSAGE;
867             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
868             goto f_err;
869         }
870     }
871     /* not reached */
872
873  f_err:
874     ssl3_send_alert(s, SSL3_AL_FATAL, al);
875     return (-1);
876 }
877
878
879         /*
880          * this only happens when a client hello is received and a handshake
881          * is started.
882          */
883 static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
884                                    int len)
885 {
886
887     if ((type == SSL3_RT_HANDSHAKE)
888             && (s->rlayer.d->handshake_fragment_len > 0))
889         /* (partially) satisfy request from storage */
890     {
891         unsigned char *src = s->rlayer.d->handshake_fragment;
892         unsigned char *dst = buf;
893         unsigned int k, n;
894
895         /* peek == 0 */
896         n = 0;
897         while ((len > 0) && (s->rlayer.d->handshake_fragment_len > 0)) {
898             *dst++ = *src++;
899             len--;
900             s->rlayer.d->handshake_fragment_len--;
901             n++;
902         }
903         /* move any remaining fragment bytes: */
904         for (k = 0; k < s->rlayer.d->handshake_fragment_len; k++)
905             s->rlayer.d->handshake_fragment[k] = *src++;
906         return n;
907     }
908
909     return 0;
910 }
911
912 /*
913  * Call this to write data in records of type 'type' It will return <= 0 if
914  * not all data has been sent or non-blocking IO.
915  */
916 int dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
917 {
918     int i;
919
920     OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
921     s->rwstate = SSL_NOTHING;
922     i = do_dtls1_write(s, type, buf, len, 0);
923     return i;
924 }
925
926 int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
927                    unsigned int len, int create_empty_fragment)
928 {
929     unsigned char *p, *pseq;
930     int i, mac_size, clear = 0;
931     int prefix_len = 0;
932     int eivlen;
933     SSL3_RECORD wr;
934     SSL3_BUFFER *wb;
935     SSL_SESSION *sess;
936
937     wb = &s->rlayer.wbuf[0];
938
939     /*
940      * first check if there is a SSL3_BUFFER still being written out.  This
941      * will happen with non blocking IO
942      */
943     if (SSL3_BUFFER_get_left(wb) != 0) {
944         OPENSSL_assert(0);      /* XDTLS: want to see if we ever get here */
945         return (ssl3_write_pending(s, type, buf, len));
946     }
947
948     /* If we have an alert to send, lets send it */
949     if (s->s3->alert_dispatch) {
950         i = s->method->ssl_dispatch_alert(s);
951         if (i <= 0)
952             return (i);
953         /* if it went, fall through and send more stuff */
954     }
955
956     if (len == 0 && !create_empty_fragment)
957         return 0;
958
959     sess = s->session;
960
961     if ((sess == NULL) ||
962         (s->enc_write_ctx == NULL) || (EVP_MD_CTX_md(s->write_hash) == NULL))
963         clear = 1;
964
965     if (clear)
966         mac_size = 0;
967     else {
968         mac_size = EVP_MD_CTX_size(s->write_hash);
969         if (mac_size < 0)
970             goto err;
971     }
972
973     p = SSL3_BUFFER_get_buf(wb) + prefix_len;
974
975     /* write the header */
976
977     *(p++) = type & 0xff;
978     SSL3_RECORD_set_type(&wr, type);
979     /*
980      * Special case: for hello verify request, client version 1.0 and we
981      * haven't decided which version to use yet send back using version 1.0
982      * header: otherwise some clients will ignore it.
983      */
984     if (s->method->version == DTLS_ANY_VERSION) {
985         *(p++) = DTLS1_VERSION >> 8;
986         *(p++) = DTLS1_VERSION & 0xff;
987     } else {
988         *(p++) = s->version >> 8;
989         *(p++) = s->version & 0xff;
990     }
991
992     /* field where we are to write out packet epoch, seq num and len */
993     pseq = p;
994     p += 10;
995
996     /* Explicit IV length, block ciphers appropriate version flag */
997     if (s->enc_write_ctx) {
998         int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
999         if (mode == EVP_CIPH_CBC_MODE) {
1000             eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
1001             if (eivlen <= 1)
1002                 eivlen = 0;
1003         }
1004         /* Need explicit part of IV for GCM mode */
1005         else if (mode == EVP_CIPH_GCM_MODE)
1006             eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
1007         else if (mode == EVP_CIPH_CCM_MODE)
1008             eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
1009         else
1010             eivlen = 0;
1011     } else
1012         eivlen = 0;
1013
1014     /* lets setup the record stuff. */
1015     SSL3_RECORD_set_data(&wr, p + eivlen); /* make room for IV in case of CBC */
1016     SSL3_RECORD_set_length(&wr, (int)len);
1017     SSL3_RECORD_set_input(&wr, (unsigned char *)buf);
1018
1019     /*
1020      * we now 'read' from wr.input, wr.length bytes into wr.data
1021      */
1022
1023     /* first we compress */
1024     if (s->compress != NULL) {
1025         if (!ssl3_do_compress(s, &wr)) {
1026             SSLerr(SSL_F_DO_DTLS1_WRITE, SSL_R_COMPRESSION_FAILURE);
1027             goto err;
1028         }
1029     } else {
1030         memcpy(SSL3_RECORD_get_data(&wr), SSL3_RECORD_get_input(&wr),
1031                SSL3_RECORD_get_length(&wr));
1032         SSL3_RECORD_reset_input(&wr);
1033     }
1034
1035     /*
1036      * we should still have the output to wr.data and the input from
1037      * wr.input.  Length should be wr.length. wr.data still points in the
1038      * wb->buf
1039      */
1040
1041     if (mac_size != 0) {
1042         if (s->method->ssl3_enc->mac(s, &wr,
1043                 &(p[SSL3_RECORD_get_length(&wr) + eivlen]), 1) < 0)
1044             goto err;
1045         SSL3_RECORD_add_length(&wr, mac_size);
1046     }
1047
1048     /* this is true regardless of mac size */
1049     SSL3_RECORD_set_data(&wr, p);
1050     SSL3_RECORD_reset_input(&wr);
1051
1052     if (eivlen)
1053         SSL3_RECORD_add_length(&wr, eivlen);
1054
1055     if (s->method->ssl3_enc->enc(s, &wr, 1, 1) < 1)
1056         goto err;
1057
1058     /* record length after mac and block padding */
1059     /*
1060      * if (type == SSL3_RT_APPLICATION_DATA || (type == SSL3_RT_ALERT && !
1061      * SSL_in_init(s)))
1062      */
1063
1064     /* there's only one epoch between handshake and app data */
1065
1066     s2n(s->rlayer.d->w_epoch, pseq);
1067
1068     /* XDTLS: ?? */
1069     /*
1070      * else s2n(s->d1->handshake_epoch, pseq);
1071      */
1072
1073     memcpy(pseq, &(s->rlayer.write_sequence[2]), 6);
1074     pseq += 6;
1075     s2n(SSL3_RECORD_get_length(&wr), pseq);
1076
1077     if (s->msg_callback)
1078         s->msg_callback(1, 0, SSL3_RT_HEADER, pseq - DTLS1_RT_HEADER_LENGTH,
1079                         DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
1080
1081     /*
1082      * we should now have wr.data pointing to the encrypted data, which is
1083      * wr->length long
1084      */
1085     SSL3_RECORD_set_type(&wr, type); /* not needed but helps for debugging */
1086     SSL3_RECORD_add_length(&wr, DTLS1_RT_HEADER_LENGTH);
1087
1088     ssl3_record_sequence_update(&(s->rlayer.write_sequence[0]));
1089
1090     if (create_empty_fragment) {
1091         /*
1092          * we are in a recursive call; just return the length, don't write
1093          * out anything here
1094          */
1095         return wr.length;
1096     }
1097
1098     /* now let's set up wb */
1099     SSL3_BUFFER_set_left(wb, prefix_len + SSL3_RECORD_get_length(&wr));
1100     SSL3_BUFFER_set_offset(wb, 0);
1101
1102     /*
1103      * memorize arguments so that ssl3_write_pending can detect bad write
1104      * retries later
1105      */
1106     s->rlayer.wpend_tot = len;
1107     s->rlayer.wpend_buf = buf;
1108     s->rlayer.wpend_type = type;
1109     s->rlayer.wpend_ret = len;
1110
1111     /* we now just need to write the buffer */
1112     return ssl3_write_pending(s, type, buf, len);
1113  err:
1114     return -1;
1115 }
1116
1117 DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
1118                                       unsigned int *is_next_epoch)
1119 {
1120
1121     *is_next_epoch = 0;
1122
1123     /* In current epoch, accept HM, CCS, DATA, & ALERT */
1124     if (rr->epoch == s->rlayer.d->r_epoch)
1125         return &s->rlayer.d->bitmap;
1126
1127     /* Only HM and ALERT messages can be from the next epoch */
1128     else if (rr->epoch == (unsigned long)(s->rlayer.d->r_epoch + 1) &&
1129             (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
1130         *is_next_epoch = 1;
1131         return &s->rlayer.d->next_bitmap;
1132     }
1133
1134     return NULL;
1135 }
1136
1137 void dtls1_reset_seq_numbers(SSL *s, int rw)
1138 {
1139     unsigned char *seq;
1140     unsigned int seq_bytes = sizeof(s->rlayer.read_sequence);
1141
1142     if (rw & SSL3_CC_READ) {
1143         seq = s->rlayer.read_sequence;
1144         s->rlayer.d->r_epoch++;
1145         memcpy(&s->rlayer.d->bitmap, &s->rlayer.d->next_bitmap,
1146                sizeof(s->rlayer.d->bitmap));
1147         memset(&s->rlayer.d->next_bitmap, 0,
1148                sizeof(s->rlayer.d->next_bitmap));
1149     } else {
1150         seq = s->rlayer.write_sequence;
1151         memcpy(s->rlayer.d->last_write_sequence, seq,
1152                sizeof(s->rlayer.write_sequence));
1153         s->rlayer.d->w_epoch++;
1154     }
1155
1156     memset(seq, 0, seq_bytes);
1157 }