Update copyright year
[oweals/openssl.git] / ssl / record / rec_layer_d1.c
1 /*
2  * Copyright 2005-2018 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the 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         *recvd_type = SSL3_RT_HANDSHAKE;
364         return ret;
365     }
366
367     /*
368      * Now s->rlayer.d->handshake_fragment_len == 0 if
369      * type == SSL3_RT_HANDSHAKE.
370      */
371
372     if (!ossl_statem_get_in_handshake(s) && SSL_in_init(s))
373     {
374         /* type == SSL3_RT_APPLICATION_DATA */
375         i = s->handshake_func(s);
376         if (i < 0)
377             return (i);
378         if (i == 0) {
379             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
380             return (-1);
381         }
382     }
383
384  start:
385     s->rwstate = SSL_NOTHING;
386
387     /*-
388      * s->s3->rrec.type         - is the type of record
389      * s->s3->rrec.data,    - data
390      * s->s3->rrec.off,     - offset into 'data' for next read
391      * s->s3->rrec.length,  - number of bytes.
392      */
393     rr = s->rlayer.rrec;
394
395     /*
396      * We are not handshaking and have no data yet, so process data buffered
397      * during the last handshake in advance, if any.
398      */
399     if (SSL_is_init_finished(s) && SSL3_RECORD_get_length(rr) == 0) {
400         pitem *item;
401         item = pqueue_pop(s->rlayer.d->buffered_app_data.q);
402         if (item) {
403 #ifndef OPENSSL_NO_SCTP
404             /* Restore bio_dgram_sctp_rcvinfo struct */
405             if (BIO_dgram_is_sctp(SSL_get_rbio(s))) {
406                 DTLS1_RECORD_DATA *rdata = (DTLS1_RECORD_DATA *)item->data;
407                 BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_SET_RCVINFO,
408                          sizeof(rdata->recordinfo), &rdata->recordinfo);
409             }
410 #endif
411
412             dtls1_copy_record(s, item);
413
414             OPENSSL_free(item->data);
415             pitem_free(item);
416         }
417     }
418
419     /* Check for timeout */
420     if (dtls1_handle_timeout(s) > 0)
421         goto start;
422
423     /* get new packet if necessary */
424     if ((SSL3_RECORD_get_length(rr) == 0)
425         || (s->rlayer.rstate == SSL_ST_READ_BODY)) {
426         ret = dtls1_get_record(s);
427         if (ret <= 0) {
428             ret = dtls1_read_failed(s, ret);
429             /* anything other than a timeout is an error */
430             if (ret <= 0)
431                 return (ret);
432             else
433                 goto start;
434         }
435     }
436
437     /*
438      * Reset the count of consecutive warning alerts if we've got a non-empty
439      * record that isn't an alert.
440      */
441     if (SSL3_RECORD_get_type(rr) != SSL3_RT_ALERT
442             && SSL3_RECORD_get_length(rr) != 0)
443         s->rlayer.alert_count = 0;
444
445     /* we now have a packet which can be read and processed */
446
447     if (s->s3->change_cipher_spec /* set when we receive ChangeCipherSpec,
448                                    * reset by ssl3_get_finished */
449         && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) {
450         /*
451          * We now have application data between CCS and Finished. Most likely
452          * the packets were reordered on their way, so buffer the application
453          * data for later processing rather than dropping the connection.
454          */
455         if (dtls1_buffer_record(s, &(s->rlayer.d->buffered_app_data),
456                                 SSL3_RECORD_get_seq_num(rr)) < 0) {
457             SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
458             return -1;
459         }
460         SSL3_RECORD_set_length(rr, 0);
461         goto start;
462     }
463
464     /*
465      * If the other end has shut down, throw anything we read away (even in
466      * 'peek' mode)
467      */
468     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
469         SSL3_RECORD_set_length(rr, 0);
470         s->rwstate = SSL_NOTHING;
471         return (0);
472     }
473
474     if (type == SSL3_RECORD_get_type(rr)
475         || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
476             && type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) {
477         /*
478          * SSL3_RT_APPLICATION_DATA or
479          * SSL3_RT_HANDSHAKE or
480          * SSL3_RT_CHANGE_CIPHER_SPEC
481          */
482         /*
483          * make sure that we are not getting application data when we are
484          * doing a handshake for the first time
485          */
486         if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA) &&
487             (s->enc_read_ctx == NULL)) {
488             al = SSL_AD_UNEXPECTED_MESSAGE;
489             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_APP_DATA_IN_HANDSHAKE);
490             goto f_err;
491         }
492
493         if (recvd_type != NULL)
494             *recvd_type = SSL3_RECORD_get_type(rr);
495
496         if (len <= 0)
497             return (len);
498
499         if ((unsigned int)len > SSL3_RECORD_get_length(rr))
500             n = SSL3_RECORD_get_length(rr);
501         else
502             n = (unsigned int)len;
503
504         memcpy(buf, &(SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)]), n);
505         if (!peek) {
506             SSL3_RECORD_sub_length(rr, n);
507             SSL3_RECORD_add_off(rr, n);
508             if (SSL3_RECORD_get_length(rr) == 0) {
509                 s->rlayer.rstate = SSL_ST_READ_HEADER;
510                 SSL3_RECORD_set_off(rr, 0);
511             }
512         }
513 #ifndef OPENSSL_NO_SCTP
514         /*
515          * We might had to delay a close_notify alert because of reordered
516          * app data. If there was an alert and there is no message to read
517          * anymore, finally set shutdown.
518          */
519         if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
520             s->d1->shutdown_received
521             && !BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
522             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
523             return (0);
524         }
525 #endif
526         return (n);
527     }
528
529     /*
530      * If we get here, then type != rr->type; if we have a handshake message,
531      * then it was unexpected (Hello Request or Client Hello).
532      */
533
534     /*
535      * In case of record types for which we have 'fragment' storage, fill
536      * that so that we can process the data at a fixed place.
537      */
538     {
539         unsigned int k, dest_maxlen = 0;
540         unsigned char *dest = NULL;
541         unsigned int *dest_len = NULL;
542
543         if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
544             dest_maxlen = sizeof(s->rlayer.d->handshake_fragment);
545             dest = s->rlayer.d->handshake_fragment;
546             dest_len = &s->rlayer.d->handshake_fragment_len;
547         } else if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) {
548             dest_maxlen = sizeof(s->rlayer.d->alert_fragment);
549             dest = s->rlayer.d->alert_fragment;
550             dest_len = &s->rlayer.d->alert_fragment_len;
551         }
552 #ifndef OPENSSL_NO_HEARTBEATS
553         else if (SSL3_RECORD_get_type(rr) == DTLS1_RT_HEARTBEAT) {
554             /* We allow a 0 return */
555             if (dtls1_process_heartbeat(s, SSL3_RECORD_get_data(rr),
556                                         SSL3_RECORD_get_length(rr)) < 0) {
557                 return -1;
558             }
559             /* Exit and notify application to read again */
560             SSL3_RECORD_set_length(rr, 0);
561             s->rwstate = SSL_READING;
562             BIO_clear_retry_flags(SSL_get_rbio(s));
563             BIO_set_retry_read(SSL_get_rbio(s));
564             return (-1);
565         }
566 #endif
567         /* else it's a CCS message, or application data or wrong */
568         else if (SSL3_RECORD_get_type(rr) != SSL3_RT_CHANGE_CIPHER_SPEC) {
569             /*
570              * Application data while renegotiating is allowed. Try again
571              * reading.
572              */
573             if (SSL3_RECORD_get_type(rr) == SSL3_RT_APPLICATION_DATA) {
574                 BIO *bio;
575                 s->s3->in_read_app_data = 2;
576                 bio = SSL_get_rbio(s);
577                 s->rwstate = SSL_READING;
578                 BIO_clear_retry_flags(bio);
579                 BIO_set_retry_read(bio);
580                 return (-1);
581             }
582
583             /* Not certain if this is the right error handling */
584             al = SSL_AD_UNEXPECTED_MESSAGE;
585             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
586             goto f_err;
587         }
588
589         if (dest_maxlen > 0) {
590             /*
591              * XDTLS: In a pathological case, the Client Hello may be
592              * fragmented--don't always expect dest_maxlen bytes
593              */
594             if (SSL3_RECORD_get_length(rr) < dest_maxlen) {
595 #ifdef DTLS1_AD_MISSING_HANDSHAKE_MESSAGE
596                 /*
597                  * for normal alerts rr->length is 2, while
598                  * dest_maxlen is 7 if we were to handle this
599                  * non-existing alert...
600                  */
601                 FIX ME;
602 #endif
603                 s->rlayer.rstate = SSL_ST_READ_HEADER;
604                 SSL3_RECORD_set_length(rr, 0);
605                 goto start;
606             }
607
608             /* now move 'n' bytes: */
609             for (k = 0; k < dest_maxlen; k++) {
610                 dest[k] = SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)];
611                 SSL3_RECORD_add_off(rr, 1);
612                 SSL3_RECORD_add_length(rr, -1);
613             }
614             *dest_len = dest_maxlen;
615         }
616     }
617
618     /*-
619      * s->rlayer.d->handshake_fragment_len == 12  iff  rr->type == SSL3_RT_HANDSHAKE;
620      * s->rlayer.d->alert_fragment_len == 7      iff  rr->type == SSL3_RT_ALERT.
621      * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
622      */
623
624     /* If we are a client, check for an incoming 'Hello Request': */
625     if ((!s->server) &&
626         (s->rlayer.d->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
627         (s->rlayer.d->handshake_fragment[0] == SSL3_MT_HELLO_REQUEST) &&
628         (s->session != NULL) && (s->session->cipher != NULL)) {
629         s->rlayer.d->handshake_fragment_len = 0;
630
631         if ((s->rlayer.d->handshake_fragment[1] != 0) ||
632             (s->rlayer.d->handshake_fragment[2] != 0) ||
633             (s->rlayer.d->handshake_fragment[3] != 0)) {
634             al = SSL_AD_DECODE_ERROR;
635             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_BAD_HELLO_REQUEST);
636             goto f_err;
637         }
638
639         /*
640          * no need to check sequence number on HELLO REQUEST messages
641          */
642
643         if (s->msg_callback)
644             s->msg_callback(0, s->version, SSL3_RT_HANDSHAKE,
645                             s->rlayer.d->handshake_fragment, 4, s,
646                             s->msg_callback_arg);
647
648         if (SSL_is_init_finished(s) &&
649             (s->options & SSL_OP_NO_RENEGOTIATION) == 0 &&
650             !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS) &&
651             !s->s3->renegotiate) {
652             s->d1->handshake_read_seq++;
653             s->new_session = 1;
654             ssl3_renegotiate(s);
655             if (ssl3_renegotiate_check(s)) {
656                 i = s->handshake_func(s);
657                 if (i < 0)
658                     return (i);
659                 if (i == 0) {
660                     SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
661                     return (-1);
662                 }
663
664                 if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
665                     if (SSL3_BUFFER_get_left(&s->rlayer.rbuf) == 0) {
666                         /* no read-ahead left? */
667                         BIO *bio;
668                         /*
669                          * In the case where we try to read application data,
670                          * but we trigger an SSL handshake, we return -1 with
671                          * the retry option set.  Otherwise renegotiation may
672                          * cause nasty problems in the blocking world
673                          */
674                         s->rwstate = SSL_READING;
675                         bio = SSL_get_rbio(s);
676                         BIO_clear_retry_flags(bio);
677                         BIO_set_retry_read(bio);
678                         return (-1);
679                     }
680                 }
681             }
682         } else {
683             SSL3_RECORD_set_length(rr, 0);
684             ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
685         }
686         /*
687          * we either finished a handshake or ignored the request, now try
688          * again to obtain the (application) data we were asked for
689          */
690         goto start;
691     }
692
693     /*
694      * If we are a server and get a client hello when renegotiation isn't
695      * allowed send back a no renegotiation alert and carry on.
696      */
697     if (s->server
698             && SSL_is_init_finished(s)
699             && s->rlayer.d->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH
700             && s->rlayer.d->handshake_fragment[0] == SSL3_MT_CLIENT_HELLO
701             && s->s3->previous_client_finished_len != 0
702             && ((!s->s3->send_connection_binding
703                     && (s->options
704                         & SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION) == 0)
705                 || (s->options & SSL_OP_NO_RENEGOTIATION) != 0)) {
706         s->rlayer.d->handshake_fragment_len = 0;
707         SSL3_RECORD_set_length(rr, 0);
708         ssl3_send_alert(s, SSL3_AL_WARNING, SSL_AD_NO_RENEGOTIATION);
709         goto start;
710     }
711
712     if (s->rlayer.d->alert_fragment_len >= DTLS1_AL_HEADER_LENGTH) {
713         int alert_level = s->rlayer.d->alert_fragment[0];
714         int alert_descr = s->rlayer.d->alert_fragment[1];
715
716         s->rlayer.d->alert_fragment_len = 0;
717
718         if (s->msg_callback)
719             s->msg_callback(0, s->version, SSL3_RT_ALERT,
720                             s->rlayer.d->alert_fragment, 2, s,
721                             s->msg_callback_arg);
722
723         if (s->info_callback != NULL)
724             cb = s->info_callback;
725         else if (s->ctx->info_callback != NULL)
726             cb = s->ctx->info_callback;
727
728         if (cb != NULL) {
729             j = (alert_level << 8) | alert_descr;
730             cb(s, SSL_CB_READ_ALERT, j);
731         }
732
733         if (alert_level == SSL3_AL_WARNING) {
734             s->s3->warn_alert = alert_descr;
735
736             s->rlayer.alert_count++;
737             if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
738                 al = SSL_AD_UNEXPECTED_MESSAGE;
739                 SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_TOO_MANY_WARN_ALERTS);
740                 goto f_err;
741             }
742
743             if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
744 #ifndef OPENSSL_NO_SCTP
745                 /*
746                  * With SCTP and streams the socket may deliver app data
747                  * after a close_notify alert. We have to check this first so
748                  * that nothing gets discarded.
749                  */
750                 if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
751                     BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s))) {
752                     s->d1->shutdown_received = 1;
753                     s->rwstate = SSL_READING;
754                     BIO_clear_retry_flags(SSL_get_rbio(s));
755                     BIO_set_retry_read(SSL_get_rbio(s));
756                     return -1;
757                 }
758 #endif
759                 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
760                 return (0);
761             }
762 #if 0
763             /* XXX: this is a possible improvement in the future */
764             /* now check if it's a missing record */
765             if (alert_descr == DTLS1_AD_MISSING_HANDSHAKE_MESSAGE) {
766                 unsigned short seq;
767                 unsigned int frag_off;
768                 unsigned char *p = &(s->rlayer.d->alert_fragment[2]);
769
770                 n2s(p, seq);
771                 n2l3(p, frag_off);
772
773                 dtls1_retransmit_message(s,
774                                          dtls1_get_queue_priority
775                                          (frag->msg_header.seq, 0), frag_off,
776                                          &found);
777                 if (!found && SSL_in_init(s)) {
778                     /*
779                      * fprintf( stderr,"in init = %d\n", SSL_in_init(s));
780                      */
781                     /*
782                      * requested a message not yet sent, send an alert
783                      * ourselves
784                      */
785                     ssl3_send_alert(s, SSL3_AL_WARNING,
786                                     DTLS1_AD_MISSING_HANDSHAKE_MESSAGE);
787                 }
788             }
789 #endif
790         } else if (alert_level == SSL3_AL_FATAL) {
791             char tmp[16];
792
793             s->rwstate = SSL_NOTHING;
794             s->s3->fatal_alert = alert_descr;
795             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_AD_REASON_OFFSET + alert_descr);
796             BIO_snprintf(tmp, sizeof(tmp), "%d", alert_descr);
797             ERR_add_error_data(2, "SSL alert number ", tmp);
798             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
799             SSL_CTX_remove_session(s->session_ctx, s->session);
800             return (0);
801         } else {
802             al = SSL_AD_ILLEGAL_PARAMETER;
803             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNKNOWN_ALERT_TYPE);
804             goto f_err;
805         }
806
807         goto start;
808     }
809
810     if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
811                                             * shutdown */
812         s->rwstate = SSL_NOTHING;
813         SSL3_RECORD_set_length(rr, 0);
814         return (0);
815     }
816
817     if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {
818         /*
819          * We can't process a CCS now, because previous handshake messages
820          * are still missing, so just drop it.
821          */
822         SSL3_RECORD_set_length(rr, 0);
823         goto start;
824     }
825
826     /*
827      * Unexpected handshake message (Client Hello, or protocol violation)
828      */
829     if ((s->rlayer.d->handshake_fragment_len >= DTLS1_HM_HEADER_LENGTH) &&
830         !ossl_statem_get_in_handshake(s)) {
831         struct hm_header_st msg_hdr;
832
833         /* this may just be a stale retransmit */
834         dtls1_get_message_header(rr->data, &msg_hdr);
835         if (SSL3_RECORD_get_epoch(rr) != s->rlayer.d->r_epoch) {
836             SSL3_RECORD_set_length(rr, 0);
837             goto start;
838         }
839
840         /*
841          * If we are server, we may have a repeated FINISHED of the client
842          * here, then retransmit our CCS and FINISHED.
843          */
844         if (msg_hdr.type == SSL3_MT_FINISHED) {
845             if (dtls1_check_timeout_num(s) < 0)
846                 return -1;
847
848             dtls1_retransmit_buffered_messages(s);
849             SSL3_RECORD_set_length(rr, 0);
850             goto start;
851         }
852
853         if (SSL_is_init_finished(s) &&
854             !(s->s3->flags & SSL3_FLAGS_NO_RENEGOTIATE_CIPHERS)) {
855             ossl_statem_set_in_init(s, 1);
856             s->renegotiate = 1;
857             s->new_session = 1;
858         }
859         i = s->handshake_func(s);
860         if (i < 0)
861             return (i);
862         if (i == 0) {
863             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_SSL_HANDSHAKE_FAILURE);
864             return (-1);
865         }
866
867         if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
868             if (SSL3_BUFFER_get_left(&s->rlayer.rbuf) == 0) {
869                 /* no read-ahead left? */
870                 BIO *bio;
871                 /*
872                  * In the case where we try to read application data, but we
873                  * trigger an SSL handshake, we return -1 with the retry
874                  * option set.  Otherwise renegotiation may cause nasty
875                  * problems in the blocking world
876                  */
877                 s->rwstate = SSL_READING;
878                 bio = SSL_get_rbio(s);
879                 BIO_clear_retry_flags(bio);
880                 BIO_set_retry_read(bio);
881                 return (-1);
882             }
883         }
884         goto start;
885     }
886
887     switch (SSL3_RECORD_get_type(rr)) {
888     default:
889         /* TLS just ignores unknown message types */
890         if (s->version == TLS1_VERSION) {
891             SSL3_RECORD_set_length(rr, 0);
892             goto start;
893         }
894         al = SSL_AD_UNEXPECTED_MESSAGE;
895         SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
896         goto f_err;
897     case SSL3_RT_CHANGE_CIPHER_SPEC:
898     case SSL3_RT_ALERT:
899     case SSL3_RT_HANDSHAKE:
900         /*
901          * we already handled all of these, with the possible exception of
902          * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
903          * that should not happen when type != rr->type
904          */
905         al = SSL_AD_UNEXPECTED_MESSAGE;
906         SSLerr(SSL_F_DTLS1_READ_BYTES, ERR_R_INTERNAL_ERROR);
907         goto f_err;
908     case SSL3_RT_APPLICATION_DATA:
909         /*
910          * At this point, we were expecting handshake data, but have
911          * application data.  If the library was running inside ssl3_read()
912          * (i.e. in_read_app_data is set) and it makes sense to read
913          * application data at this point (session renegotiation not yet
914          * started), we will indulge it.
915          */
916         if (s->s3->in_read_app_data &&
917             (s->s3->total_renegotiations != 0) &&
918             ossl_statem_app_data_allowed(s)) {
919             s->s3->in_read_app_data = 2;
920             return (-1);
921         } else {
922             al = SSL_AD_UNEXPECTED_MESSAGE;
923             SSLerr(SSL_F_DTLS1_READ_BYTES, SSL_R_UNEXPECTED_RECORD);
924             goto f_err;
925         }
926     }
927     /* not reached */
928
929  f_err:
930     ssl3_send_alert(s, SSL3_AL_FATAL, al);
931     return (-1);
932 }
933
934         /*
935          * this only happens when a client hello is received and a handshake
936          * is started.
937          */
938 static int have_handshake_fragment(SSL *s, int type, unsigned char *buf,
939                                    int len)
940 {
941
942     if ((type == SSL3_RT_HANDSHAKE)
943         && (s->rlayer.d->handshake_fragment_len > 0))
944         /* (partially) satisfy request from storage */
945     {
946         unsigned char *src = s->rlayer.d->handshake_fragment;
947         unsigned char *dst = buf;
948         unsigned int k, n;
949
950         /* peek == 0 */
951         n = 0;
952         while ((len > 0) && (s->rlayer.d->handshake_fragment_len > 0)) {
953             *dst++ = *src++;
954             len--;
955             s->rlayer.d->handshake_fragment_len--;
956             n++;
957         }
958         /* move any remaining fragment bytes: */
959         for (k = 0; k < s->rlayer.d->handshake_fragment_len; k++)
960             s->rlayer.d->handshake_fragment[k] = *src++;
961         return n;
962     }
963
964     return 0;
965 }
966
967 /*
968  * Call this to write data in records of type 'type' It will return <= 0 if
969  * not all data has been sent or non-blocking IO.
970  */
971 int dtls1_write_bytes(SSL *s, int type, const void *buf, int len)
972 {
973     int i;
974
975     OPENSSL_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH);
976     s->rwstate = SSL_NOTHING;
977     i = do_dtls1_write(s, type, buf, len, 0);
978     return i;
979 }
980
981 int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
982                    unsigned int len, int create_empty_fragment)
983 {
984     unsigned char *p, *pseq;
985     int i, mac_size, clear = 0;
986     int prefix_len = 0;
987     int eivlen;
988     SSL3_RECORD wr;
989     SSL3_BUFFER *wb;
990     SSL_SESSION *sess;
991
992     wb = &s->rlayer.wbuf[0];
993
994     /*
995      * first check if there is a SSL3_BUFFER still being written out.  This
996      * will happen with non blocking IO
997      */
998     if (SSL3_BUFFER_get_left(wb) != 0) {
999         OPENSSL_assert(0);      /* XDTLS: want to see if we ever get here */
1000         return (ssl3_write_pending(s, type, buf, len));
1001     }
1002
1003     /* If we have an alert to send, lets send it */
1004     if (s->s3->alert_dispatch) {
1005         i = s->method->ssl_dispatch_alert(s);
1006         if (i <= 0)
1007             return (i);
1008         /* if it went, fall through and send more stuff */
1009     }
1010
1011     if (len == 0 && !create_empty_fragment)
1012         return 0;
1013
1014     if (len > s->max_send_fragment) {
1015         SSLerr(SSL_F_DO_DTLS1_WRITE, SSL_R_EXCEEDS_MAX_FRAGMENT_SIZE);
1016         return 0;
1017     }
1018
1019     sess = s->session;
1020
1021     if ((sess == NULL) ||
1022         (s->enc_write_ctx == NULL) || (EVP_MD_CTX_md(s->write_hash) == NULL))
1023         clear = 1;
1024
1025     if (clear)
1026         mac_size = 0;
1027     else {
1028         mac_size = EVP_MD_CTX_size(s->write_hash);
1029         if (mac_size < 0)
1030             goto err;
1031     }
1032
1033     p = SSL3_BUFFER_get_buf(wb) + prefix_len;
1034
1035     /* write the header */
1036
1037     *(p++) = type & 0xff;
1038     SSL3_RECORD_set_type(&wr, type);
1039     /*
1040      * Special case: for hello verify request, client version 1.0 and we
1041      * haven't decided which version to use yet send back using version 1.0
1042      * header: otherwise some clients will ignore it.
1043      */
1044     if (s->method->version == DTLS_ANY_VERSION &&
1045         s->max_proto_version != DTLS1_BAD_VER) {
1046         *(p++) = DTLS1_VERSION >> 8;
1047         *(p++) = DTLS1_VERSION & 0xff;
1048     } else {
1049         *(p++) = s->version >> 8;
1050         *(p++) = s->version & 0xff;
1051     }
1052
1053     /* field where we are to write out packet epoch, seq num and len */
1054     pseq = p;
1055     p += 10;
1056
1057     /* Explicit IV length, block ciphers appropriate version flag */
1058     if (s->enc_write_ctx) {
1059         int mode = EVP_CIPHER_CTX_mode(s->enc_write_ctx);
1060         if (mode == EVP_CIPH_CBC_MODE) {
1061             eivlen = EVP_CIPHER_CTX_iv_length(s->enc_write_ctx);
1062             if (eivlen <= 1)
1063                 eivlen = 0;
1064         }
1065         /* Need explicit part of IV for GCM mode */
1066         else if (mode == EVP_CIPH_GCM_MODE)
1067             eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
1068         else if (mode == EVP_CIPH_CCM_MODE)
1069             eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
1070         else
1071             eivlen = 0;
1072     } else
1073         eivlen = 0;
1074
1075     /* lets setup the record stuff. */
1076     SSL3_RECORD_set_data(&wr, p + eivlen); /* make room for IV in case of CBC */
1077     SSL3_RECORD_set_length(&wr, (int)len);
1078     SSL3_RECORD_set_input(&wr, (unsigned char *)buf);
1079
1080     /*
1081      * we now 'read' from wr.input, wr.length bytes into wr.data
1082      */
1083
1084     /* first we compress */
1085     if (s->compress != NULL) {
1086         if (!ssl3_do_compress(s, &wr)) {
1087             SSLerr(SSL_F_DO_DTLS1_WRITE, SSL_R_COMPRESSION_FAILURE);
1088             goto err;
1089         }
1090     } else {
1091         memcpy(SSL3_RECORD_get_data(&wr), SSL3_RECORD_get_input(&wr),
1092                SSL3_RECORD_get_length(&wr));
1093         SSL3_RECORD_reset_input(&wr);
1094     }
1095
1096     /*
1097      * we should still have the output to wr.data and the input from
1098      * wr.input.  Length should be wr.length. wr.data still points in the
1099      * wb->buf
1100      */
1101
1102     if (mac_size != 0) {
1103         if (s->method->ssl3_enc->mac(s, &wr,
1104                                      &(p[SSL3_RECORD_get_length(&wr) + eivlen]),
1105                                      1) < 0)
1106             goto err;
1107         SSL3_RECORD_add_length(&wr, mac_size);
1108     }
1109
1110     /* this is true regardless of mac size */
1111     SSL3_RECORD_set_data(&wr, p);
1112     SSL3_RECORD_reset_input(&wr);
1113
1114     if (eivlen)
1115         SSL3_RECORD_add_length(&wr, eivlen);
1116
1117     if (s->method->ssl3_enc->enc(s, &wr, 1, 1) < 1)
1118         goto err;
1119
1120     /* record length after mac and block padding */
1121     /*
1122      * if (type == SSL3_RT_APPLICATION_DATA || (type == SSL3_RT_ALERT && !
1123      * SSL_in_init(s)))
1124      */
1125
1126     /* there's only one epoch between handshake and app data */
1127
1128     s2n(s->rlayer.d->w_epoch, pseq);
1129
1130     /* XDTLS: ?? */
1131     /*
1132      * else s2n(s->d1->handshake_epoch, pseq);
1133      */
1134
1135     memcpy(pseq, &(s->rlayer.write_sequence[2]), 6);
1136     pseq += 6;
1137     s2n(SSL3_RECORD_get_length(&wr), pseq);
1138
1139     if (s->msg_callback)
1140         s->msg_callback(1, 0, SSL3_RT_HEADER, pseq - DTLS1_RT_HEADER_LENGTH,
1141                         DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
1142
1143     /*
1144      * we should now have wr.data pointing to the encrypted data, which is
1145      * wr->length long
1146      */
1147     SSL3_RECORD_set_type(&wr, type); /* not needed but helps for debugging */
1148     SSL3_RECORD_add_length(&wr, DTLS1_RT_HEADER_LENGTH);
1149
1150     ssl3_record_sequence_update(&(s->rlayer.write_sequence[0]));
1151
1152     if (create_empty_fragment) {
1153         /*
1154          * we are in a recursive call; just return the length, don't write
1155          * out anything here
1156          */
1157         return wr.length;
1158     }
1159
1160     /* now let's set up wb */
1161     SSL3_BUFFER_set_left(wb, prefix_len + SSL3_RECORD_get_length(&wr));
1162     SSL3_BUFFER_set_offset(wb, 0);
1163
1164     /*
1165      * memorize arguments so that ssl3_write_pending can detect bad write
1166      * retries later
1167      */
1168     s->rlayer.wpend_tot = len;
1169     s->rlayer.wpend_buf = buf;
1170     s->rlayer.wpend_type = type;
1171     s->rlayer.wpend_ret = len;
1172
1173     /* we now just need to write the buffer */
1174     return ssl3_write_pending(s, type, buf, len);
1175  err:
1176     return -1;
1177 }
1178
1179 DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
1180                                unsigned int *is_next_epoch)
1181 {
1182
1183     *is_next_epoch = 0;
1184
1185     /* In current epoch, accept HM, CCS, DATA, & ALERT */
1186     if (rr->epoch == s->rlayer.d->r_epoch)
1187         return &s->rlayer.d->bitmap;
1188
1189     /*
1190      * Only HM and ALERT messages can be from the next epoch and only if we
1191      * have already processed all of the unprocessed records from the last
1192      * epoch
1193      */
1194     else if (rr->epoch == (unsigned long)(s->rlayer.d->r_epoch + 1) &&
1195              s->rlayer.d->unprocessed_rcds.epoch != s->rlayer.d->r_epoch &&
1196              (rr->type == SSL3_RT_HANDSHAKE || rr->type == SSL3_RT_ALERT)) {
1197         *is_next_epoch = 1;
1198         return &s->rlayer.d->next_bitmap;
1199     }
1200
1201     return NULL;
1202 }
1203
1204 void dtls1_reset_seq_numbers(SSL *s, int rw)
1205 {
1206     unsigned char *seq;
1207     unsigned int seq_bytes = sizeof(s->rlayer.read_sequence);
1208
1209     if (rw & SSL3_CC_READ) {
1210         seq = s->rlayer.read_sequence;
1211         s->rlayer.d->r_epoch++;
1212         memcpy(&s->rlayer.d->bitmap, &s->rlayer.d->next_bitmap,
1213                sizeof(s->rlayer.d->bitmap));
1214         memset(&s->rlayer.d->next_bitmap, 0, sizeof(s->rlayer.d->next_bitmap));
1215
1216         /*
1217          * We must not use any buffered messages received from the previous
1218          * epoch
1219          */
1220         dtls1_clear_received_buffer(s);
1221     } else {
1222         seq = s->rlayer.write_sequence;
1223         memcpy(s->rlayer.d->last_write_sequence, seq,
1224                sizeof(s->rlayer.write_sequence));
1225         s->rlayer.d->w_epoch++;
1226     }
1227
1228     memset(seq, 0, seq_bytes);
1229 }