1 /*
2  * Copyright 2005-2023 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (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 "internal/packet.h"
17 #include "internal/cryptlib.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         ERR_raise(ERR_LIB_SSL, 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 
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 
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         if (rl->s->options & SSL_OP_CLEANSE_PLAINTEXT)
81             OPENSSL_cleanse(rdata->rbuf.buf, rdata->rbuf.len);
82         OPENSSL_free(rdata->rbuf.buf);
83         OPENSSL_free(item->data);
84         pitem_free(item);
85     }
86 
87     while ((item = pqueue_pop(d->buffered_app_data.q)) != NULL) {
88         rdata = (DTLS1_RECORD_DATA *)item->data;
89         if (rl->s->options & SSL_OP_CLEANSE_PLAINTEXT)
90             OPENSSL_cleanse(rdata->rbuf.buf, rdata->rbuf.len);
91         OPENSSL_free(rdata->rbuf.buf);
92         OPENSSL_free(item->data);
93         pitem_free(item);
94     }
95 
96     unprocessed_rcds = d->unprocessed_rcds.q;
97     processed_rcds = d->processed_rcds.q;
98     buffered_app_data = d->buffered_app_data.q;
99     memset(d, 0, sizeof(*d));
100     d->unprocessed_rcds.q = unprocessed_rcds;
101     d->processed_rcds.q = processed_rcds;
102     d->buffered_app_data.q = buffered_app_data;
103 }
104 
105 void DTLS_RECORD_LAYER_set_saved_w_epoch(RECORD_LAYER *rl, unsigned short e)
106 {
107     if (e == rl->d->w_epoch - 1) {
108         memcpy(rl->d->curr_write_sequence,
109                rl->write_sequence, sizeof(rl->write_sequence));
110         memcpy(rl->write_sequence,
111                rl->d->last_write_sequence, sizeof(rl->write_sequence));
112     } else if (e == rl->d->w_epoch + 1) {
113         memcpy(rl->d->last_write_sequence,
114                rl->write_sequence, sizeof(unsigned char[8]));
115         memcpy(rl->write_sequence,
116                rl->d->curr_write_sequence, sizeof(rl->write_sequence));
117     }
118     rl->d->w_epoch = e;
119 }
120 
121 void DTLS_RECORD_LAYER_set_write_sequence(RECORD_LAYER *rl, unsigned char *seq)
122 {
123     memcpy(rl->write_sequence, seq, SEQ_NUM_SIZE);
124 }
125 
126 /* copy buffered record into SSL structure */
127 static int dtls1_copy_record(SSL *s, pitem *item)
128 {
129     DTLS1_RECORD_DATA *rdata;
130 
131     rdata = (DTLS1_RECORD_DATA *)item->data;
132 
133     SSL3_BUFFER_release(&s->rlayer.rbuf);
134 
135     s->rlayer.packet = rdata->packet;
136     s->rlayer.packet_length = rdata->packet_length;
137     memcpy(&s->rlayer.rbuf, &(rdata->rbuf), sizeof(SSL3_BUFFER));
138     memcpy(&s->rlayer.rrec, &(rdata->rrec), sizeof(SSL3_RECORD));
139 
140     /* Set proper sequence number for mac calculation */
141     memcpy(&(s->rlayer.read_sequence[2]), &(rdata->packet[5]), 6);
142 
143     return 1;
144 }
145 
146 int dtls1_buffer_record(SSL *s, record_pqueue *queue, unsigned char *priority)
147 {
148     DTLS1_RECORD_DATA *rdata;
149     pitem *item;
150 
151     /* Limit the size of the queue to prevent DOS attacks */
152     if (pqueue_size(queue->q) >= 100)
153         return 0;
154 
155     rdata = OPENSSL_malloc(sizeof(*rdata));
156     item = pitem_new(priority, rdata);
157     if (rdata == NULL || item == NULL) {
158         OPENSSL_free(rdata);
159         pitem_free(item);
160         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
161         return -1;
162     }
163 
164     rdata->packet = s->rlayer.packet;
165     rdata->packet_length = s->rlayer.packet_length;
166     memcpy(&(rdata->rbuf), &s->rlayer.rbuf, sizeof(SSL3_BUFFER));
167     memcpy(&(rdata->rrec), &s->rlayer.rrec, sizeof(SSL3_RECORD));
168 
169     item->data = rdata;
170 
171 #ifndef OPENSSL_NO_SCTP
172     /* Store bio_dgram_sctp_rcvinfo struct */
173     if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
174         (SSL_get_state(s) == TLS_ST_SR_FINISHED
175          || SSL_get_state(s) == TLS_ST_CR_FINISHED)) {
176         BIO_ctrl(SSL_get_rbio(s), BIO_CTRL_DGRAM_SCTP_GET_RCVINFO,
177                  sizeof(rdata->recordinfo), &rdata->recordinfo);
178     }
179 #endif
180 
181     s->rlayer.packet = NULL;
182     s->rlayer.packet_length = 0;
183     memset(&s->rlayer.rbuf, 0, sizeof(s->rlayer.rbuf));
184     memset(&s->rlayer.rrec, 0, sizeof(s->rlayer.rrec));
185 
186     if (!ssl3_setup_buffers(s)) {
187         /* SSLfatal() already called */
188         OPENSSL_free(rdata->rbuf.buf);
189         OPENSSL_free(rdata);
190         pitem_free(item);
191         return -1;
192     }
193 
194     if (pqueue_insert(queue->q, item) == NULL) {
195         /* Must be a duplicate so ignore it */
196         OPENSSL_free(rdata->rbuf.buf);
197         OPENSSL_free(rdata);
198         pitem_free(item);
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                  SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
269                  return 0;
270             }
271 #ifndef OPENSSL_NO_SCTP
272             /* Only do replay check if no SCTP bio */
273             if (!BIO_dgram_is_sctp(SSL_get_rbio(s)))
274 #endif
275             {
276                 /*
277                  * Check whether this is a repeat, or aged record. We did this
278                  * check once already when we first received the record - but
279                  * we might have updated the window since then due to
280                  * records we subsequently processed.
281                  */
282                 replayok = dtls1_record_replay_check(s, bitmap);
283             }
284 
285             if (!replayok || !dtls1_process_record(s, bitmap)) {
286                 if (ossl_statem_in_error(s)) {
287                     /* dtls1_process_record called SSLfatal() */
288                     return 0;
289                 }
290                 /* dump this record */
291                 rr->length = 0;
292                 RECORD_LAYER_reset_packet_length(&s->rlayer);
293                 continue;
294             }
295 
296             if (dtls1_buffer_record(s, &(s->rlayer.d->processed_rcds),
297                     SSL3_RECORD_get_seq_num(s->rlayer.rrec)) < 0) {
298                 /* SSLfatal() already called */
299                 return 0;
300             }
301         }
302     }
303 
304     /*
305      * sync epoch numbers once all the unprocessed records have been
306      * processed
307      */
308     s->rlayer.d->processed_rcds.epoch = s->rlayer.d->r_epoch;
309     s->rlayer.d->unprocessed_rcds.epoch = s->rlayer.d->r_epoch + 1;
310 
311     return 1;
312 }
313 
314 /*-
315  * Return up to 'len' payload bytes received in 'type' records.
316  * 'type' is one of the following:
317  *
318  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
319  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
320  *   -  0 (during a shutdown, no data has to be returned)
321  *
322  * If we don't have stored data to work from, read a SSL/TLS record first
323  * (possibly multiple records if we still don't have anything to return).
324  *
325  * This function must handle any surprises the peer may have for us, such as
326  * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
327  * messages are treated as if they were handshake messages *if* the |recd_type|
328  * argument is non NULL.
329  * Also if record payloads contain fragments too small to process, we store
330  * them until there is enough for the respective protocol (the record protocol
331  * may use arbitrary fragmentation and even interleaving):
332  *     Change cipher spec protocol
333  *             just 1 byte needed, no need for keeping anything stored
334  *     Alert protocol
335  *             2 bytes needed (AlertLevel, AlertDescription)
336  *     Handshake protocol
337  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
338  *             to detect unexpected Client Hello and Hello Request messages
339  *             here, anything else is handled by higher layers
340  *     Application data protocol
341  *             none of our business
342  */
343 int dtls1_read_bytes(SSL *s, int type, int *recvd_type, unsigned char *buf,
344                      size_t len, int peek, size_t *readbytes)
345 {
346     int i, j, iret;
347     size_t n;
348     SSL3_RECORD *rr;
349     void (*cb) (const SSL *ssl, int type2, int val) = NULL;
350 
351     if (!SSL3_BUFFER_is_initialised(&s->rlayer.rbuf)) {
352         /* Not initialized yet */
353         if (!ssl3_setup_buffers(s)) {
354             /* SSLfatal() already called */
355             return -1;
356         }
357     }
358 
359     if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
360          (type != SSL3_RT_HANDSHAKE)) ||
361         (peek && (type != SSL3_RT_APPLICATION_DATA))) {
362         SSLfatal(s, SSL_AD_INTERNAL_ERROR, 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,
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             if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
521                 OPENSSL_cleanse(&(SSL3_RECORD_get_data(rr)[SSL3_RECORD_get_off(rr)]), n);
522             SSL3_RECORD_sub_length(rr, n);
523             SSL3_RECORD_add_off(rr, n);
524             if (SSL3_RECORD_get_length(rr) == 0) {
525                 s->rlayer.rstate = SSL_ST_READ_HEADER;
526                 SSL3_RECORD_set_off(rr, 0);
527                 SSL3_RECORD_set_read(rr);
528             }
529         }
530 #ifndef OPENSSL_NO_SCTP
531         /*
532          * We might had to delay a close_notify alert because of reordered
533          * app data. If there was an alert and there is no message to read
534          * anymore, finally set shutdown.
535          */
536         if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
537             s->d1->shutdown_received
538             && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s)) <= 0) {
539             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
540             return 0;
541         }
542 #endif
543         *readbytes = n;
544         return 1;
545     }
546 
547     /*
548      * If we get here, then type != rr->type; if we have a handshake message,
549      * then it was unexpected (Hello Request or Client Hello).
550      */
551 
552     if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) {
553         unsigned int alert_level, alert_descr;
554         unsigned char *alert_bytes = SSL3_RECORD_get_data(rr)
555                                      + SSL3_RECORD_get_off(rr);
556         PACKET alert;
557 
558         if (!PACKET_buf_init(&alert, alert_bytes, SSL3_RECORD_get_length(rr))
559                 || !PACKET_get_1(&alert, &alert_level)
560                 || !PACKET_get_1(&alert, &alert_descr)
561                 || PACKET_remaining(&alert) != 0) {
562             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
563             return -1;
564         }
565 
566         if (s->msg_callback)
567             s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, s,
568                             s->msg_callback_arg);
569 
570         if (s->info_callback != NULL)
571             cb = s->info_callback;
572         else if (s->ctx->info_callback != NULL)
573             cb = s->ctx->info_callback;
574 
575         if (cb != NULL) {
576             j = (alert_level << 8) | alert_descr;
577             cb(s, SSL_CB_READ_ALERT, j);
578         }
579 
580         if (alert_level == SSL3_AL_WARNING) {
581             s->s3.warn_alert = alert_descr;
582             SSL3_RECORD_set_read(rr);
583 
584             s->rlayer.alert_count++;
585             if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
586                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
587                          SSL_R_TOO_MANY_WARN_ALERTS);
588                 return -1;
589             }
590 
591             if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
592 #ifndef OPENSSL_NO_SCTP
593                 /*
594                  * With SCTP and streams the socket may deliver app data
595                  * after a close_notify alert. We have to check this first so
596                  * that nothing gets discarded.
597                  */
598                 if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
599                     BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s)) > 0) {
600                     s->d1->shutdown_received = 1;
601                     s->rwstate = SSL_READING;
602                     BIO_clear_retry_flags(SSL_get_rbio(s));
603                     BIO_set_retry_read(SSL_get_rbio(s));
604                     return -1;
605                 }
606 #endif
607                 s->shutdown |= SSL_RECEIVED_SHUTDOWN;
608                 return 0;
609             }
610         } else if (alert_level == SSL3_AL_FATAL) {
611             s->rwstate = SSL_NOTHING;
612             s->s3.fatal_alert = alert_descr;
613             SSLfatal_data(s, SSL_AD_NO_ALERT,
614                           SSL_AD_REASON_OFFSET + alert_descr,
615                           "SSL alert number %d", alert_descr);
616             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
617             SSL3_RECORD_set_read(rr);
618             SSL_CTX_remove_session(s->session_ctx, s->session);
619             return 0;
620         } else {
621             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
622             return -1;
623         }
624 
625         goto start;
626     }
627 
628     if (s->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
629                                             * shutdown */
630         s->rwstate = SSL_NOTHING;
631         SSL3_RECORD_set_length(rr, 0);
632         SSL3_RECORD_set_read(rr);
633         return 0;
634     }
635 
636     if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {
637         /*
638          * We can't process a CCS now, because previous handshake messages
639          * are still missing, so just drop it.
640          */
641         SSL3_RECORD_set_length(rr, 0);
642         SSL3_RECORD_set_read(rr);
643         goto start;
644     }
645 
646     /*
647      * Unexpected handshake message (Client Hello, or protocol violation)
648      */
649     if ((SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) &&
650             !ossl_statem_get_in_handshake(s)) {
651         struct hm_header_st msg_hdr;
652 
653         /*
654          * This may just be a stale retransmit. Also sanity check that we have
655          * at least enough record bytes for a message header
656          */
657         if (SSL3_RECORD_get_epoch(rr) != s->rlayer.d->r_epoch
658                 || SSL3_RECORD_get_length(rr) < DTLS1_HM_HEADER_LENGTH) {
659             SSL3_RECORD_set_length(rr, 0);
660             SSL3_RECORD_set_read(rr);
661             goto start;
662         }
663 
664         dtls1_get_message_header(rr->data, &msg_hdr);
665 
666         /*
667          * If we are server, we may have a repeated FINISHED of the client
668          * here, then retransmit our CCS and FINISHED.
669          */
670         if (msg_hdr.type == SSL3_MT_FINISHED) {
671             if (dtls1_check_timeout_num(s) < 0) {
672                 /* SSLfatal) already called */
673                 return -1;
674             }
675 
676             if (dtls1_retransmit_buffered_messages(s) <= 0) {
677                 /* Fail if we encountered a fatal error */
678                 if (ossl_statem_in_error(s))
679                     return -1;
680             }
681             SSL3_RECORD_set_length(rr, 0);
682             SSL3_RECORD_set_read(rr);
683             if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
684                 if (SSL3_BUFFER_get_left(&s->rlayer.rbuf) == 0) {
685                     /* no read-ahead left? */
686                     BIO *bio;
687 
688                     s->rwstate = SSL_READING;
689                     bio = SSL_get_rbio(s);
690                     BIO_clear_retry_flags(bio);
691                     BIO_set_retry_read(bio);
692                     return -1;
693                 }
694             }
695             goto start;
696         }
697 
698         /*
699          * To get here we must be trying to read app data but found handshake
700          * data. But if we're trying to read app data, and we're not in init
701          * (which is tested for at the top of this function) then init must be
702          * finished
703          */
704         if (!ossl_assert(SSL_is_init_finished(s))) {
705             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
706             return -1;
707         }
708 
709         /* We found handshake data, so we're going back into init */
710         ossl_statem_set_in_init(s, 1);
711 
712         i = s->handshake_func(s);
713         /* SSLfatal() called if appropriate */
714         if (i < 0)
715             return i;
716         if (i == 0)
717             return -1;
718 
719         if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
720             if (SSL3_BUFFER_get_left(&s->rlayer.rbuf) == 0) {
721                 /* no read-ahead left? */
722                 BIO *bio;
723                 /*
724                  * In the case where we try to read application data, but we
725                  * trigger an SSL handshake, we return -1 with the retry
726                  * option set.  Otherwise renegotiation may cause nasty
727                  * problems in the blocking world
728                  */
729                 s->rwstate = SSL_READING;
730                 bio = SSL_get_rbio(s);
731                 BIO_clear_retry_flags(bio);
732                 BIO_set_retry_read(bio);
733                 return -1;
734             }
735         }
736         goto start;
737     }
738 
739     switch (SSL3_RECORD_get_type(rr)) {
740     default:
741         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
742         return -1;
743     case SSL3_RT_CHANGE_CIPHER_SPEC:
744     case SSL3_RT_ALERT:
745     case SSL3_RT_HANDSHAKE:
746         /*
747          * we already handled all of these, with the possible exception of
748          * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
749          * that should not happen when type != rr->type
750          */
751         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
752         return -1;
753     case SSL3_RT_APPLICATION_DATA:
754         /*
755          * At this point, we were expecting handshake data, but have
756          * application data.  If the library was running inside ssl3_read()
757          * (i.e. in_read_app_data is set) and it makes sense to read
758          * application data at this point (session renegotiation not yet
759          * started), we will indulge it.
760          */
761         if (s->s3.in_read_app_data &&
762             (s->s3.total_renegotiations != 0) &&
763             ossl_statem_app_data_allowed(s)) {
764             s->s3.in_read_app_data = 2;
765             return -1;
766         } else {
767             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
768             return -1;
769         }
770     }
771     /* not reached */
772 }
773 
774 /*
775  * Call this to write data in records of type 'type' It will return <= 0 if
776  * not all data has been sent or non-blocking IO.
777  */
778 int dtls1_write_bytes(SSL *s, int type, const void *buf, size_t len,
779                       size_t *written)
780 {
781     int i;
782 
783     if (!ossl_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH)) {
784         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
785         return -1;
786     }
787     s->rwstate = SSL_NOTHING;
788     i = do_dtls1_write(s, type, buf, len, 0, written);
789     return i;
790 }
791 
792 int do_dtls1_write(SSL *s, int type, const unsigned char *buf,
793                    size_t len, int create_empty_fragment, size_t *written)
794 {
795     unsigned char *p, *pseq;
796     int i, mac_size, clear = 0;
797     size_t prefix_len = 0;
798     int eivlen;
799     SSL3_RECORD wr;
800     SSL3_BUFFER *wb;
801     SSL_SESSION *sess;
802 
803     wb = &s->rlayer.wbuf[0];
804 
805     /*
806      * DTLS writes whole datagrams, so there can't be anything left in
807      * the buffer.
808      */
809     if (!ossl_assert(SSL3_BUFFER_get_left(wb) == 0)) {
810         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
811         return 0;
812     }
813 
814     /* If we have an alert to send, lets send it */
815     if (s->s3.alert_dispatch) {
816         i = s->method->ssl_dispatch_alert(s);
817         if (i <= 0)
818             return i;
819         /* if it went, fall through and send more stuff */
820     }
821 
822     if (len == 0 && !create_empty_fragment)
823         return 0;
824 
825     if (len > ssl_get_max_send_fragment(s)) {
826         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_EXCEEDS_MAX_FRAGMENT_SIZE);
827         return 0;
828     }
829 
830     sess = s->session;
831 
832     if ((sess == NULL)
833             || (s->enc_write_ctx == NULL)
834             || (EVP_MD_CTX_get0_md(s->write_hash) == NULL))
835         clear = 1;
836 
837     if (clear)
838         mac_size = 0;
839     else {
840         mac_size = EVP_MD_CTX_get_size(s->write_hash);
841         if (mac_size < 0) {
842             SSLfatal(s, SSL_AD_INTERNAL_ERROR,
843                      SSL_R_EXCEEDS_MAX_FRAGMENT_SIZE);
844             return -1;
845         }
846     }
847 
848     p = SSL3_BUFFER_get_buf(wb) + prefix_len;
849 
850     /* write the header */
851 
852     *(p++) = type & 0xff;
853     SSL3_RECORD_set_type(&wr, type);
854     /*
855      * Special case: for hello verify request, client version 1.0 and we
856      * haven't decided which version to use yet send back using version 1.0
857      * header: otherwise some clients will ignore it.
858      */
859     if (s->method->version == DTLS_ANY_VERSION &&
860         s->max_proto_version != DTLS1_BAD_VER) {
861         *(p++) = DTLS1_VERSION >> 8;
862         *(p++) = DTLS1_VERSION & 0xff;
863     } else {
864         *(p++) = s->version >> 8;
865         *(p++) = s->version & 0xff;
866     }
867 
868     /* field where we are to write out packet epoch, seq num and len */
869     pseq = p;
870     p += 10;
871 
872     /* Explicit IV length, block ciphers appropriate version flag */
873     if (s->enc_write_ctx) {
874         int mode = EVP_CIPHER_CTX_get_mode(s->enc_write_ctx);
875         if (mode == EVP_CIPH_CBC_MODE) {
876             eivlen = EVP_CIPHER_CTX_get_iv_length(s->enc_write_ctx);
877             if (eivlen < 0) {
878                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_LIBRARY_BUG);
879                 return -1;
880             }
881             if (eivlen <= 1)
882                 eivlen = 0;
883         }
884         /* Need explicit part of IV for GCM mode */
885         else if (mode == EVP_CIPH_GCM_MODE)
886             eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
887         else if (mode == EVP_CIPH_CCM_MODE)
888             eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
889         else
890             eivlen = 0;
891     } else
892         eivlen = 0;
893 
894     /* lets setup the record stuff. */
895     SSL3_RECORD_set_data(&wr, p + eivlen); /* make room for IV in case of CBC */
896     SSL3_RECORD_set_length(&wr, len);
897     SSL3_RECORD_set_input(&wr, (unsigned char *)buf);
898 
899     /*
900      * we now 'read' from wr.input, wr.length bytes into wr.data
901      */
902 
903     /* first we compress */
904     if (s->compress != NULL) {
905         if (!ssl3_do_compress(s, &wr)) {
906             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
907             return -1;
908         }
909     } else {
910         memcpy(SSL3_RECORD_get_data(&wr), SSL3_RECORD_get_input(&wr),
911                SSL3_RECORD_get_length(&wr));
912         SSL3_RECORD_reset_input(&wr);
913     }
914 
915     /*
916      * we should still have the output to wr.data and the input from
917      * wr.input.  Length should be wr.length. wr.data still points in the
918      * wb->buf
919      */
920 
921     if (!SSL_WRITE_ETM(s) && mac_size != 0) {
922         if (!s->method->ssl3_enc->mac(s, &wr,
923                                       &(p[SSL3_RECORD_get_length(&wr) + eivlen]),
924                                       1)) {
925             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
926             return -1;
927         }
928         SSL3_RECORD_add_length(&wr, mac_size);
929     }
930 
931     /* this is true regardless of mac size */
932     SSL3_RECORD_set_data(&wr, p);
933     SSL3_RECORD_reset_input(&wr);
934 
935     if (eivlen)
936         SSL3_RECORD_add_length(&wr, eivlen);
937 
938     if (s->method->ssl3_enc->enc(s, &wr, 1, 1, NULL, mac_size) < 1) {
939         if (!ossl_statem_in_error(s)) {
940             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
941         }
942         return -1;
943     }
944 
945     if (SSL_WRITE_ETM(s) && mac_size != 0) {
946         if (!s->method->ssl3_enc->mac(s, &wr,
947                                       &(p[SSL3_RECORD_get_length(&wr)]), 1)) {
948             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
949             return -1;
950         }
951         SSL3_RECORD_add_length(&wr, mac_size);
952     }
953 
954     /* record length after mac and block padding */
955 
956     /* there's only one epoch between handshake and app data */
957 
958     s2n(s->rlayer.d->w_epoch, pseq);
959 
960     memcpy(pseq, &(s->rlayer.write_sequence[2]), 6);
961     pseq += 6;
962     s2n(SSL3_RECORD_get_length(&wr), pseq);
963 
964     if (s->msg_callback)
965         s->msg_callback(1, 0, SSL3_RT_HEADER, pseq - DTLS1_RT_HEADER_LENGTH,
966                         DTLS1_RT_HEADER_LENGTH, s, s->msg_callback_arg);
967 
968     /*
969      * we should now have wr.data pointing to the encrypted data, which is
970      * wr->length long
971      */
972     SSL3_RECORD_set_type(&wr, type); /* not needed but helps for debugging */
973     SSL3_RECORD_add_length(&wr, DTLS1_RT_HEADER_LENGTH);
974 
975     ssl3_record_sequence_update(&(s->rlayer.write_sequence[0]));
976 
977     if (create_empty_fragment) {
978         /*
979          * we are in a recursive call; just return the length, don't write
980          * out anything here
981          */
982         *written = wr.length;
983         return 1;
984     }
985 
986     /* now let's set up wb */
987     SSL3_BUFFER_set_left(wb, prefix_len + SSL3_RECORD_get_length(&wr));
988     SSL3_BUFFER_set_offset(wb, 0);
989 
990     /*
991      * memorize arguments so that ssl3_write_pending can detect bad write
992      * retries later
993      */
994     s->rlayer.wpend_tot = len;
995     s->rlayer.wpend_buf = buf;
996     s->rlayer.wpend_type = type;
997     s->rlayer.wpend_ret = len;
998 
999     /* we now just need to write the buffer. Calls SSLfatal() as required. */
1000     return ssl3_write_pending(s, type, buf, len, written);
1001 }
1002 
1003 DTLS1_BITMAP *dtls1_get_bitmap(SSL *s, SSL3_RECORD *rr,
1004                                unsigned int *is_next_epoch)
1005 {
1006 
1007     *is_next_epoch = 0;
1008 
1009     /* In current epoch, accept HM, CCS, DATA, & ALERT */
1010     if (rr->epoch == s->rlayer.d->r_epoch)
1011         return &s->rlayer.d->bitmap;
1012 
1013     /*
1014      * We can only handle messages from the next epoch if we have already
1015      * processed all of the unprocessed records from the previous epoch
1016      */
1017     else if (rr->epoch == (unsigned long)(s->rlayer.d->r_epoch + 1)
1018              && s->rlayer.d->unprocessed_rcds.epoch != s->rlayer.d->r_epoch) {
1019         *is_next_epoch = 1;
1020         return &s->rlayer.d->next_bitmap;
1021     }
1022 
1023     return NULL;
1024 }
1025 
1026 void dtls1_reset_seq_numbers(SSL *s, int rw)
1027 {
1028     unsigned char *seq;
1029     unsigned int seq_bytes = sizeof(s->rlayer.read_sequence);
1030 
1031     if (rw & SSL3_CC_READ) {
1032         seq = s->rlayer.read_sequence;
1033         s->rlayer.d->r_epoch++;
1034         memcpy(&s->rlayer.d->bitmap, &s->rlayer.d->next_bitmap,
1035                sizeof(s->rlayer.d->bitmap));
1036         memset(&s->rlayer.d->next_bitmap, 0, sizeof(s->rlayer.d->next_bitmap));
1037 
1038         /*
1039          * We must not use any buffered messages received from the previous
1040          * epoch
1041          */
1042         dtls1_clear_received_buffer(s);
1043     } else {
1044         seq = s->rlayer.write_sequence;
1045         memcpy(s->rlayer.d->last_write_sequence, seq,
1046                sizeof(s->rlayer.write_sequence));
1047         s->rlayer.d->w_epoch++;
1048     }
1049 
1050     memset(seq, 0, seq_bytes);
1051 }
1052