xref: /freebsd/crypto/openssl/ssl/record/rec_layer_d1.c (revision e7be843b4a162e68651d3911f0357ed464915629)
1 /*
2  * Copyright 2005-2025 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 #include "internal/ssl_unwrap.h"
19 
DTLS_RECORD_LAYER_new(RECORD_LAYER * rl)20 int DTLS_RECORD_LAYER_new(RECORD_LAYER *rl)
21 {
22     DTLS_RECORD_LAYER *d;
23 
24     if ((d = OPENSSL_malloc(sizeof(*d))) == NULL)
25         return 0;
26 
27     rl->d = d;
28 
29     d->buffered_app_data = pqueue_new();
30 
31     if (d->buffered_app_data == NULL) {
32         OPENSSL_free(d);
33         rl->d = NULL;
34         return 0;
35     }
36 
37     return 1;
38 }
39 
DTLS_RECORD_LAYER_free(RECORD_LAYER * rl)40 void DTLS_RECORD_LAYER_free(RECORD_LAYER *rl)
41 {
42     if (rl->d == NULL)
43         return;
44 
45     DTLS_RECORD_LAYER_clear(rl);
46     pqueue_free(rl->d->buffered_app_data);
47     OPENSSL_free(rl->d);
48     rl->d = NULL;
49 }
50 
DTLS_RECORD_LAYER_clear(RECORD_LAYER * rl)51 void DTLS_RECORD_LAYER_clear(RECORD_LAYER *rl)
52 {
53     DTLS_RECORD_LAYER *d;
54     pitem *item = NULL;
55     TLS_RECORD *rec;
56     pqueue *buffered_app_data;
57 
58     d = rl->d;
59 
60     while ((item = pqueue_pop(d->buffered_app_data)) != NULL) {
61         rec = (TLS_RECORD *)item->data;
62 
63         if (rl->s->options & SSL_OP_CLEANSE_PLAINTEXT)
64             OPENSSL_cleanse(rec->allocdata, rec->length);
65         OPENSSL_free(rec->allocdata);
66         OPENSSL_free(item->data);
67         pitem_free(item);
68     }
69 
70     buffered_app_data = d->buffered_app_data;
71     memset(d, 0, sizeof(*d));
72     d->buffered_app_data = buffered_app_data;
73 }
74 
dtls_buffer_record(SSL_CONNECTION * s,TLS_RECORD * rec)75 static int dtls_buffer_record(SSL_CONNECTION *s, TLS_RECORD *rec)
76 {
77     TLS_RECORD *rdata;
78     pitem *item;
79     struct pqueue_st *queue = s->rlayer.d->buffered_app_data;
80 
81     /* Limit the size of the queue to prevent DOS attacks */
82     if (pqueue_size(queue) >= 100)
83         return 0;
84 
85     /* We don't buffer partially read records */
86     if (!ossl_assert(rec->off == 0))
87         return -1;
88 
89     rdata = OPENSSL_malloc(sizeof(*rdata));
90     item = pitem_new(rec->seq_num, rdata);
91     if (rdata == NULL || item == NULL) {
92         OPENSSL_free(rdata);
93         pitem_free(item);
94         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
95         return -1;
96     }
97 
98     *rdata = *rec;
99     /*
100      * We will release the record from the record layer soon, so we take a copy
101      * now. Copying data isn't good - but this should be infrequent so we
102      * accept it here.
103      */
104     rdata->data = rdata->allocdata = OPENSSL_memdup(rec->data, rec->length);
105     if (rdata->data == NULL) {
106         OPENSSL_free(rdata);
107         pitem_free(item);
108         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_CRYPTO_LIB);
109         return -1;
110     }
111     /*
112      * We use a NULL rechandle to indicate that the data field has been
113      * allocated by us.
114      */
115     rdata->rechandle = NULL;
116 
117     item->data = rdata;
118 
119 #ifndef OPENSSL_NO_SCTP
120     /* Store bio_dgram_sctp_rcvinfo struct */
121     if (BIO_dgram_is_sctp(s->rbio) &&
122         (ossl_statem_get_state(s) == TLS_ST_SR_FINISHED
123          || ossl_statem_get_state(s) == TLS_ST_CR_FINISHED)) {
124         BIO_ctrl(s->rbio, BIO_CTRL_DGRAM_SCTP_GET_RCVINFO,
125                  sizeof(rdata->recordinfo), &rdata->recordinfo);
126     }
127 #endif
128 
129     if (pqueue_insert(queue, item) == NULL) {
130         /* Must be a duplicate so ignore it */
131         OPENSSL_free(rdata->allocdata);
132         OPENSSL_free(rdata);
133         pitem_free(item);
134     }
135 
136     return 1;
137 }
138 
139 /* Unbuffer a previously buffered TLS_RECORD structure if any */
dtls_unbuffer_record(SSL_CONNECTION * s)140 static void dtls_unbuffer_record(SSL_CONNECTION *s)
141 {
142     TLS_RECORD *rdata;
143     pitem *item;
144 
145     /* If we already have records to handle then do nothing */
146     if (s->rlayer.curr_rec < s->rlayer.num_recs)
147         return;
148 
149     item = pqueue_pop(s->rlayer.d->buffered_app_data);
150     if (item != NULL) {
151         rdata = (TLS_RECORD *)item->data;
152 
153         s->rlayer.tlsrecs[0] = *rdata;
154         s->rlayer.num_recs = 1;
155         s->rlayer.curr_rec = 0;
156 
157 #ifndef OPENSSL_NO_SCTP
158         /* Restore bio_dgram_sctp_rcvinfo struct */
159         if (BIO_dgram_is_sctp(s->rbio)) {
160             BIO_ctrl(s->rbio, BIO_CTRL_DGRAM_SCTP_SET_RCVINFO,
161                      sizeof(rdata->recordinfo), &rdata->recordinfo);
162         }
163 #endif
164 
165         OPENSSL_free(item->data);
166         pitem_free(item);
167     }
168 }
169 
170 /*-
171  * Return up to 'len' payload bytes received in 'type' records.
172  * 'type' is one of the following:
173  *
174  *   -  SSL3_RT_HANDSHAKE
175  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
176  *   -  0 (during a shutdown, no data has to be returned)
177  *
178  * If we don't have stored data to work from, read an SSL/TLS record first
179  * (possibly multiple records if we still don't have anything to return).
180  *
181  * This function must handle any surprises the peer may have for us, such as
182  * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
183  * messages are treated as if they were handshake messages *if* the |recd_type|
184  * argument is non NULL.
185  * Also if record payloads contain fragments too small to process, we store
186  * them until there is enough for the respective protocol (the record protocol
187  * may use arbitrary fragmentation and even interleaving):
188  *     Change cipher spec protocol
189  *             just 1 byte needed, no need for keeping anything stored
190  *     Alert protocol
191  *             2 bytes needed (AlertLevel, AlertDescription)
192  *     Handshake protocol
193  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
194  *             to detect unexpected Client Hello and Hello Request messages
195  *             here, anything else is handled by higher layers
196  *     Application data protocol
197  *             none of our business
198  */
dtls1_read_bytes(SSL * s,uint8_t type,uint8_t * recvd_type,unsigned char * buf,size_t len,int peek,size_t * readbytes)199 int dtls1_read_bytes(SSL *s, uint8_t type, uint8_t *recvd_type,
200                      unsigned char *buf, size_t len,
201                      int peek, size_t *readbytes)
202 {
203     int i, j, ret;
204     size_t n;
205     TLS_RECORD *rr;
206     void (*cb) (const SSL *ssl, int type2, int val) = NULL;
207     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
208 
209     if (sc == NULL)
210         return -1;
211 
212     if ((type && (type != SSL3_RT_APPLICATION_DATA) &&
213          (type != SSL3_RT_HANDSHAKE)) ||
214         (peek && (type != SSL3_RT_APPLICATION_DATA))) {
215         SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
216         return -1;
217     }
218 
219     if (!ossl_statem_get_in_handshake(sc) && SSL_in_init(s)) {
220         /* type == SSL3_RT_APPLICATION_DATA */
221         i = sc->handshake_func(s);
222         /* SSLfatal() already called if appropriate */
223         if (i < 0)
224             return i;
225         if (i == 0)
226             return -1;
227     }
228 
229  start:
230     sc->rwstate = SSL_NOTHING;
231 
232     /*
233      * We are not handshaking and have no data yet, so process data buffered
234      * during the last handshake in advance, if any.
235      */
236     if (SSL_is_init_finished(s))
237         dtls_unbuffer_record(sc);
238 
239     /* Check for timeout */
240     if (dtls1_handle_timeout(sc) > 0) {
241         goto start;
242     } else if (ossl_statem_in_error(sc)) {
243         /* dtls1_handle_timeout() has failed with a fatal error */
244         return -1;
245     }
246 
247     /* get new packet if necessary */
248     if (sc->rlayer.curr_rec >= sc->rlayer.num_recs) {
249         sc->rlayer.curr_rec = sc->rlayer.num_recs = 0;
250         do {
251             rr = &sc->rlayer.tlsrecs[sc->rlayer.num_recs];
252 
253             ret = HANDLE_RLAYER_READ_RETURN(sc,
254                     sc->rlayer.rrlmethod->read_record(sc->rlayer.rrl,
255                                                       &rr->rechandle,
256                                                       &rr->version, &rr->type,
257                                                       &rr->data, &rr->length,
258                                                       &rr->epoch, rr->seq_num));
259             if (ret <= 0) {
260                 ret = dtls1_read_failed(sc, ret);
261                 /*
262                 * Anything other than a timeout is an error. SSLfatal() already
263                 * called if appropriate.
264                 */
265                 if (ret <= 0)
266                     return ret;
267                 else
268                     goto start;
269             }
270             rr->off = 0;
271             sc->rlayer.num_recs++;
272         } while (sc->rlayer.rrlmethod->processed_read_pending(sc->rlayer.rrl)
273                  && sc->rlayer.num_recs < SSL_MAX_PIPELINES);
274     }
275     rr = &sc->rlayer.tlsrecs[sc->rlayer.curr_rec];
276 
277     /*
278      * Reset the count of consecutive warning alerts if we've got a non-empty
279      * record that isn't an alert.
280      */
281     if (rr->type != SSL3_RT_ALERT && rr->length != 0)
282         sc->rlayer.alert_count = 0;
283 
284     /* we now have a packet which can be read and processed */
285 
286     if (sc->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
287                                   * reset by ssl3_get_finished */
288         && (rr->type != SSL3_RT_HANDSHAKE)) {
289         /*
290          * We now have application data between CCS and Finished. Most likely
291          * the packets were reordered on their way, so buffer the application
292          * data for later processing rather than dropping the connection.
293          */
294         if (dtls_buffer_record(sc, rr) < 0) {
295             /* SSLfatal() already called */
296             return -1;
297         }
298         if (!ssl_release_record(sc, rr, 0))
299             return -1;
300         goto start;
301     }
302 
303     /*
304      * If the other end has shut down, throw anything we read away (even in
305      * 'peek' mode)
306      */
307     if (sc->shutdown & SSL_RECEIVED_SHUTDOWN) {
308         if (!ssl_release_record(sc, rr, 0))
309             return -1;
310         sc->rwstate = SSL_NOTHING;
311         return 0;
312     }
313 
314     if (type == rr->type
315         || (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC
316             && type == SSL3_RT_HANDSHAKE && recvd_type != NULL)) {
317         /*
318          * SSL3_RT_APPLICATION_DATA or
319          * SSL3_RT_HANDSHAKE or
320          * SSL3_RT_CHANGE_CIPHER_SPEC
321          */
322         /*
323          * make sure that we are not getting application data when we are
324          * doing a handshake for the first time
325          */
326         if (SSL_in_init(s) && (type == SSL3_RT_APPLICATION_DATA)
327                 && (SSL_IS_FIRST_HANDSHAKE(sc))) {
328             SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE,
329                      SSL_R_APP_DATA_IN_HANDSHAKE);
330             return -1;
331         }
332 
333         if (recvd_type != NULL)
334             *recvd_type = rr->type;
335 
336         if (len == 0) {
337             /*
338              * Release a zero length record. This ensures multiple calls to
339              * SSL_read() with a zero length buffer will eventually cause
340              * SSL_pending() to report data as being available.
341              */
342             if (rr->length == 0 && !ssl_release_record(sc, rr, 0))
343                 return -1;
344             return 0;
345         }
346 
347         if (len > rr->length)
348             n = rr->length;
349         else
350             n = len;
351 
352         memcpy(buf, &(rr->data[rr->off]), n);
353         if (peek) {
354             if (rr->length == 0 && !ssl_release_record(sc, rr, 0))
355                 return -1;
356         } else {
357             if (!ssl_release_record(sc, rr, n))
358                 return -1;
359         }
360 #ifndef OPENSSL_NO_SCTP
361         /*
362          * We might had to delay a close_notify alert because of reordered
363          * app data. If there was an alert and there is no message to read
364          * anymore, finally set shutdown.
365          */
366         if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
367             sc->d1->shutdown_received
368             && BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s)) <= 0) {
369             sc->shutdown |= SSL_RECEIVED_SHUTDOWN;
370             return 0;
371         }
372 #endif
373         *readbytes = n;
374         return 1;
375     }
376 
377     /*
378      * If we get here, then type != rr->type; if we have a handshake message,
379      * then it was unexpected (Hello Request or Client Hello).
380      */
381 
382     if (rr->type == SSL3_RT_ALERT) {
383         unsigned int alert_level, alert_descr;
384         const unsigned char *alert_bytes = rr->data + rr->off;
385         PACKET alert;
386 
387         if (!PACKET_buf_init(&alert, alert_bytes, rr->length)
388                 || !PACKET_get_1(&alert, &alert_level)
389                 || !PACKET_get_1(&alert, &alert_descr)
390                 || PACKET_remaining(&alert) != 0) {
391             SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
392             return -1;
393         }
394 
395         if (sc->msg_callback)
396             sc->msg_callback(0, sc->version, SSL3_RT_ALERT, alert_bytes, 2, s,
397                              sc->msg_callback_arg);
398 
399         if (sc->info_callback != NULL)
400             cb = sc->info_callback;
401         else if (s->ctx->info_callback != NULL)
402             cb = s->ctx->info_callback;
403 
404         if (cb != NULL) {
405             j = (alert_level << 8) | alert_descr;
406             cb(s, SSL_CB_READ_ALERT, j);
407         }
408 
409         if (alert_level == SSL3_AL_WARNING) {
410             sc->s3.warn_alert = alert_descr;
411             if (!ssl_release_record(sc, rr, 0))
412                 return -1;
413 
414             sc->rlayer.alert_count++;
415             if (sc->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
416                 SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE,
417                          SSL_R_TOO_MANY_WARN_ALERTS);
418                 return -1;
419             }
420 
421             if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
422 #ifndef OPENSSL_NO_SCTP
423                 /*
424                  * With SCTP and streams the socket may deliver app data
425                  * after a close_notify alert. We have to check this first so
426                  * that nothing gets discarded.
427                  */
428                 if (BIO_dgram_is_sctp(SSL_get_rbio(s)) &&
429                     BIO_dgram_sctp_msg_waiting(SSL_get_rbio(s)) > 0) {
430                     sc->d1->shutdown_received = 1;
431                     sc->rwstate = SSL_READING;
432                     BIO_clear_retry_flags(SSL_get_rbio(s));
433                     BIO_set_retry_read(SSL_get_rbio(s));
434                     return -1;
435                 }
436 #endif
437                 sc->shutdown |= SSL_RECEIVED_SHUTDOWN;
438                 return 0;
439             } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
440                 /*
441                  * This is a warning but we receive it if we requested
442                  * renegotiation and the peer denied it. Terminate with a fatal
443                  * alert because if the application tried to renegotiate it
444                  * presumably had a good reason and expects it to succeed. In
445                  * the future we might have a renegotiation where we don't care
446                  * if the peer refused it where we carry on.
447                  */
448                 SSLfatal(sc, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
449                 return -1;
450             }
451         } else if (alert_level == SSL3_AL_FATAL) {
452             sc->rwstate = SSL_NOTHING;
453             sc->s3.fatal_alert = alert_descr;
454             SSLfatal_data(sc, SSL_AD_NO_ALERT,
455                           SSL_AD_REASON_OFFSET + alert_descr,
456                           "SSL alert number %d", alert_descr);
457             sc->shutdown |= SSL_RECEIVED_SHUTDOWN;
458             if (!ssl_release_record(sc, rr, 0))
459                 return -1;
460             SSL_CTX_remove_session(sc->session_ctx, sc->session);
461             return 0;
462         } else {
463             SSLfatal(sc, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
464             return -1;
465         }
466 
467         goto start;
468     }
469 
470     if (sc->shutdown & SSL_SENT_SHUTDOWN) { /* but we have not received a
471                                             * shutdown */
472         sc->rwstate = SSL_NOTHING;
473         if (!ssl_release_record(sc, rr, 0))
474             return -1;
475         return 0;
476     }
477 
478     if (rr->type == SSL3_RT_CHANGE_CIPHER_SPEC) {
479         /*
480          * We can't process a CCS now, because previous handshake messages
481          * are still missing, so just drop it.
482          */
483         if (!ssl_release_record(sc, rr, 0))
484             return -1;
485         goto start;
486     }
487 
488     /*
489      * Unexpected handshake message (Client Hello, or protocol violation)
490      */
491     if (rr->type == SSL3_RT_HANDSHAKE && !ossl_statem_get_in_handshake(sc)) {
492         struct hm_header_st msg_hdr;
493 
494         /*
495          * This may just be a stale retransmit. Also sanity check that we have
496          * at least enough record bytes for a message header
497          */
498         if (rr->epoch != sc->rlayer.d->r_epoch
499                 || rr->length < DTLS1_HM_HEADER_LENGTH) {
500             if (!ssl_release_record(sc, rr, 0))
501                 return -1;
502             goto start;
503         }
504 
505         dtls1_get_message_header(rr->data, &msg_hdr);
506 
507         /*
508          * If we are server, we may have a repeated FINISHED of the client
509          * here, then retransmit our CCS and FINISHED.
510          */
511         if (msg_hdr.type == SSL3_MT_FINISHED) {
512             if (dtls1_check_timeout_num(sc) < 0) {
513                 /* SSLfatal) already called */
514                 return -1;
515             }
516 
517             if (dtls1_retransmit_buffered_messages(sc) <= 0) {
518                 /* Fail if we encountered a fatal error */
519                 if (ossl_statem_in_error(sc))
520                     return -1;
521             }
522             if (!ssl_release_record(sc, rr, 0))
523                 return -1;
524             if (!(sc->mode & SSL_MODE_AUTO_RETRY)) {
525                 if (!sc->rlayer.rrlmethod->unprocessed_read_pending(sc->rlayer.rrl)) {
526                     /* no read-ahead left? */
527                     BIO *bio;
528 
529                     sc->rwstate = SSL_READING;
530                     bio = SSL_get_rbio(s);
531                     BIO_clear_retry_flags(bio);
532                     BIO_set_retry_read(bio);
533                     return -1;
534                 }
535             }
536             goto start;
537         }
538 
539         /*
540          * To get here we must be trying to read app data but found handshake
541          * data. But if we're trying to read app data, and we're not in init
542          * (which is tested for at the top of this function) then init must be
543          * finished
544          */
545         if (!ossl_assert(SSL_is_init_finished(s))) {
546             SSLfatal(sc, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
547             return -1;
548         }
549 
550         /* We found handshake data, so we're going back into init */
551         ossl_statem_set_in_init(sc, 1);
552 
553         i = sc->handshake_func(s);
554         /* SSLfatal() called if appropriate */
555         if (i < 0)
556             return i;
557         if (i == 0)
558             return -1;
559 
560         if (!(sc->mode & SSL_MODE_AUTO_RETRY)) {
561             if (!sc->rlayer.rrlmethod->unprocessed_read_pending(sc->rlayer.rrl)) {
562                 /* no read-ahead left? */
563                 BIO *bio;
564                 /*
565                  * In the case where we try to read application data, but we
566                  * trigger an SSL handshake, we return -1 with the retry
567                  * option set.  Otherwise renegotiation may cause nasty
568                  * problems in the blocking world
569                  */
570                 sc->rwstate = SSL_READING;
571                 bio = SSL_get_rbio(s);
572                 BIO_clear_retry_flags(bio);
573                 BIO_set_retry_read(bio);
574                 return -1;
575             }
576         }
577         goto start;
578     }
579 
580     switch (rr->type) {
581     default:
582         SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
583         return -1;
584     case SSL3_RT_CHANGE_CIPHER_SPEC:
585     case SSL3_RT_ALERT:
586     case SSL3_RT_HANDSHAKE:
587         /*
588          * we already handled all of these, with the possible exception of
589          * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
590          * that should not happen when type != rr->type
591          */
592         SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
593         return -1;
594     case SSL3_RT_APPLICATION_DATA:
595         /*
596          * At this point, we were expecting handshake data, but have
597          * application data.  If the library was running inside ssl3_read()
598          * (i.e. in_read_app_data is set) and it makes sense to read
599          * application data at this point (session renegotiation not yet
600          * started), we will indulge it.
601          */
602         if (sc->s3.in_read_app_data &&
603             (sc->s3.total_renegotiations != 0) &&
604             ossl_statem_app_data_allowed(sc)) {
605             sc->s3.in_read_app_data = 2;
606             return -1;
607         } else {
608             SSLfatal(sc, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
609             return -1;
610         }
611     }
612     /* not reached */
613 }
614 
615 /*
616  * Call this to write data in records of type 'type' It will return <= 0 if
617  * not all data has been sent or non-blocking IO.
618  */
dtls1_write_bytes(SSL_CONNECTION * s,uint8_t type,const void * buf,size_t len,size_t * written)619 int dtls1_write_bytes(SSL_CONNECTION *s, uint8_t type, const void *buf,
620                       size_t len, size_t *written)
621 {
622     int i;
623 
624     if (!ossl_assert(len <= SSL3_RT_MAX_PLAIN_LENGTH)) {
625         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
626         return -1;
627     }
628     s->rwstate = SSL_NOTHING;
629     i = do_dtls1_write(s, type, buf, len, written);
630     return i;
631 }
632 
do_dtls1_write(SSL_CONNECTION * sc,uint8_t type,const unsigned char * buf,size_t len,size_t * written)633 int do_dtls1_write(SSL_CONNECTION *sc, uint8_t type, const unsigned char *buf,
634                    size_t len, size_t *written)
635 {
636     int i;
637     OSSL_RECORD_TEMPLATE tmpl;
638     SSL *s = SSL_CONNECTION_GET_SSL(sc);
639     int ret;
640 
641     /* If we have an alert to send, lets send it */
642     if (sc->s3.alert_dispatch > 0) {
643         i = s->method->ssl_dispatch_alert(s);
644         if (i <= 0)
645             return i;
646         /* if it went, fall through and send more stuff */
647     }
648 
649     if (len == 0)
650         return 0;
651 
652     if (len > ssl_get_max_send_fragment(sc)) {
653         SSLfatal(sc, SSL_AD_INTERNAL_ERROR, SSL_R_EXCEEDS_MAX_FRAGMENT_SIZE);
654         return 0;
655     }
656 
657     tmpl.type = type;
658     /*
659      * Special case: for hello verify request, client version 1.0 and we
660      * haven't decided which version to use yet send back using version 1.0
661      * header: otherwise some clients will ignore it.
662      */
663     if (s->method->version == DTLS_ANY_VERSION
664             && sc->max_proto_version != DTLS1_BAD_VER)
665         tmpl.version = DTLS1_VERSION;
666     else
667         tmpl.version = sc->version;
668     tmpl.buf = buf;
669     tmpl.buflen = len;
670 
671     ret = HANDLE_RLAYER_WRITE_RETURN(sc,
672               sc->rlayer.wrlmethod->write_records(sc->rlayer.wrl, &tmpl, 1));
673 
674     if (ret > 0)
675         *written = (int)len;
676 
677     return ret;
678 }
679 
dtls1_increment_epoch(SSL_CONNECTION * s,int rw)680 void dtls1_increment_epoch(SSL_CONNECTION *s, int rw)
681 {
682     if (rw & SSL3_CC_READ) {
683         s->rlayer.d->r_epoch++;
684 
685         /*
686          * We must not use any buffered messages received from the previous
687          * epoch
688          */
689         dtls1_clear_received_buffer(s);
690     } else {
691         s->rlayer.d->w_epoch++;
692     }
693 }
694 
dtls1_get_epoch(SSL_CONNECTION * s,int rw)695 uint16_t dtls1_get_epoch(SSL_CONNECTION *s, int rw) {
696     uint16_t epoch;
697 
698     if (rw & SSL3_CC_READ)
699         epoch = s->rlayer.d->r_epoch;
700     else
701         epoch = s->rlayer.d->w_epoch;
702 
703     return epoch;
704 }
705