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