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