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