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