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