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