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