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