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