Avoid resource leaks in do_ssl3_write
[openssl.git] / ssl / record / rec_layer_s3.c
1 /*
2  * Copyright 1995-2022 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 <limits.h>
12 #include <errno.h>
13 #include "../ssl_local.h"
14 #include <openssl/evp.h>
15 #include <openssl/buffer.h>
16 #include <openssl/rand.h>
17 #include "record_local.h"
18 #include "internal/packet.h"
19
20 #if     defined(OPENSSL_SMALL_FOOTPRINT) || \
21         !(      defined(AES_ASM) &&     ( \
22                 defined(__x86_64)       || defined(__x86_64__)  || \
23                 defined(_M_AMD64)       || defined(_M_X64)      ) \
24         )
25 # undef EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
26 # define EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK 0
27 #endif
28
29 void RECORD_LAYER_init(RECORD_LAYER *rl, SSL_CONNECTION *s)
30 {
31     rl->s = s;
32     RECORD_LAYER_set_first_record(&s->rlayer);
33     SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
34 }
35
36 void RECORD_LAYER_clear(RECORD_LAYER *rl)
37 {
38     rl->rstate = SSL_ST_READ_HEADER;
39
40     /*
41      * Do I need to clear read_ahead? As far as I can tell read_ahead did not
42      * previously get reset by SSL_clear...so I'll keep it that way..but is
43      * that right?
44      */
45
46     rl->packet = NULL;
47     rl->packet_length = 0;
48     rl->wnum = 0;
49     memset(rl->handshake_fragment, 0, sizeof(rl->handshake_fragment));
50     rl->handshake_fragment_len = 0;
51     rl->wpend_tot = 0;
52     rl->wpend_type = 0;
53     rl->wpend_ret = 0;
54     rl->wpend_buf = NULL;
55
56     SSL3_BUFFER_clear(&rl->rbuf);
57     ssl3_release_write_buffer(rl->s);
58     rl->numrpipes = 0;
59     SSL3_RECORD_clear(rl->rrec, SSL_MAX_PIPELINES);
60
61     RECORD_LAYER_reset_read_sequence(rl);
62     RECORD_LAYER_reset_write_sequence(rl);
63
64     if (rl->d)
65         DTLS_RECORD_LAYER_clear(rl);
66 }
67
68 void RECORD_LAYER_release(RECORD_LAYER *rl)
69 {
70     if (SSL3_BUFFER_is_initialised(&rl->rbuf))
71         ssl3_release_read_buffer(rl->s);
72     if (rl->numwpipes > 0)
73         ssl3_release_write_buffer(rl->s);
74     SSL3_RECORD_release(rl->rrec, SSL_MAX_PIPELINES);
75 }
76
77 /* Checks if we have unprocessed read ahead data pending */
78 int RECORD_LAYER_read_pending(const RECORD_LAYER *rl)
79 {
80     return SSL3_BUFFER_get_left(&rl->rbuf) != 0;
81 }
82
83 /* Checks if we have decrypted unread record data pending */
84 int RECORD_LAYER_processed_read_pending(const RECORD_LAYER *rl)
85 {
86     size_t curr_rec = 0, num_recs = RECORD_LAYER_get_numrpipes(rl);
87     const SSL3_RECORD *rr = rl->rrec;
88
89     while (curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]))
90         curr_rec++;
91
92     return curr_rec < num_recs;
93 }
94
95 int RECORD_LAYER_write_pending(const RECORD_LAYER *rl)
96 {
97     return (rl->numwpipes > 0)
98         && SSL3_BUFFER_get_left(&rl->wbuf[rl->numwpipes - 1]) != 0;
99 }
100
101 void RECORD_LAYER_reset_read_sequence(RECORD_LAYER *rl)
102 {
103     memset(rl->read_sequence, 0, sizeof(rl->read_sequence));
104 }
105
106 void RECORD_LAYER_reset_write_sequence(RECORD_LAYER *rl)
107 {
108     memset(rl->write_sequence, 0, sizeof(rl->write_sequence));
109 }
110
111 size_t ssl3_pending(const SSL *s)
112 {
113     size_t i, num = 0;
114     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
115
116     if (sc == NULL)
117         return 0;
118
119     if (sc->rlayer.rstate == SSL_ST_READ_BODY)
120         return 0;
121
122     /* Take into account DTLS buffered app data */
123     if (SSL_CONNECTION_IS_DTLS(sc)) {
124         DTLS1_RECORD_DATA *rdata;
125         pitem *item, *iter;
126
127         iter = pqueue_iterator(sc->rlayer.d->buffered_app_data.q);
128         while ((item = pqueue_next(&iter)) != NULL) {
129             rdata = item->data;
130             num += rdata->rrec.length;
131         }
132     }
133
134     for (i = 0; i < RECORD_LAYER_get_numrpipes(&sc->rlayer); i++) {
135         if (SSL3_RECORD_get_type(&sc->rlayer.rrec[i])
136             != SSL3_RT_APPLICATION_DATA)
137             return num;
138         num += SSL3_RECORD_get_length(&sc->rlayer.rrec[i]);
139     }
140
141     return num;
142 }
143
144 void SSL_CTX_set_default_read_buffer_len(SSL_CTX *ctx, size_t len)
145 {
146     ctx->default_read_buf_len = len;
147 }
148
149 void SSL_set_default_read_buffer_len(SSL *s, size_t len)
150 {
151     SSL_CONNECTION *sc = SSL_CONNECTION_FROM_SSL(s);
152
153     if (sc == NULL)
154         return;
155
156     SSL3_BUFFER_set_default_len(RECORD_LAYER_get_rbuf(&sc->rlayer), len);
157 }
158
159 const char *SSL_rstate_string_long(const SSL *s)
160 {
161     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
162
163     if (sc == NULL)
164         return NULL;
165
166     switch (sc->rlayer.rstate) {
167     case SSL_ST_READ_HEADER:
168         return "read header";
169     case SSL_ST_READ_BODY:
170         return "read body";
171     case SSL_ST_READ_DONE:
172         return "read done";
173     default:
174         return "unknown";
175     }
176 }
177
178 const char *SSL_rstate_string(const SSL *s)
179 {
180     const SSL_CONNECTION *sc = SSL_CONNECTION_FROM_CONST_SSL(s);
181
182     if (sc == NULL)
183         return NULL;
184
185     switch (sc->rlayer.rstate) {
186     case SSL_ST_READ_HEADER:
187         return "RH";
188     case SSL_ST_READ_BODY:
189         return "RB";
190     case SSL_ST_READ_DONE:
191         return "RD";
192     default:
193         return "unknown";
194     }
195 }
196
197 /*
198  * Return values are as per SSL_read()
199  */
200 int ssl3_read_n(SSL_CONNECTION *s, size_t n, size_t max, int extend,
201                 int clearold, size_t *readbytes)
202 {
203     /*
204      * If extend == 0, obtain new n-byte packet; if extend == 1, increase
205      * packet by another n bytes. The packet will be in the sub-array of
206      * s->rlayer.rbuf.buf specified by s->rlayer.packet and
207      * s->rlayer.packet_length. (If s->rlayer.read_ahead is set, 'max' bytes may
208      * be stored in rbuf [plus s->rlayer.packet_length bytes if extend == 1].)
209      * if clearold == 1, move the packet to the start of the buffer; if
210      * clearold == 0 then leave any old packets where they were
211      */
212     size_t len, left, align = 0;
213     unsigned char *pkt;
214     SSL3_BUFFER *rb;
215
216     if (n == 0)
217         return 0;
218
219     rb = &s->rlayer.rbuf;
220     if (rb->buf == NULL)
221         if (!ssl3_setup_read_buffer(s)) {
222             /* SSLfatal() already called */
223             return -1;
224         }
225
226     left = rb->left;
227 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
228     align = (size_t)rb->buf + SSL3_RT_HEADER_LENGTH;
229     align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
230 #endif
231
232     if (!extend) {
233         /* start with empty packet ... */
234         if (left == 0)
235             rb->offset = align;
236         else if (align != 0 && left >= SSL3_RT_HEADER_LENGTH) {
237             /*
238              * check if next packet length is large enough to justify payload
239              * alignment...
240              */
241             pkt = rb->buf + rb->offset;
242             if (pkt[0] == SSL3_RT_APPLICATION_DATA
243                 && (pkt[3] << 8 | pkt[4]) >= 128) {
244                 /*
245                  * Note that even if packet is corrupted and its length field
246                  * is insane, we can only be led to wrong decision about
247                  * whether memmove will occur or not. Header values has no
248                  * effect on memmove arguments and therefore no buffer
249                  * overrun can be triggered.
250                  */
251                 memmove(rb->buf + align, pkt, left);
252                 rb->offset = align;
253             }
254         }
255         s->rlayer.packet = rb->buf + rb->offset;
256         s->rlayer.packet_length = 0;
257         /* ... now we can act as if 'extend' was set */
258     }
259
260     len = s->rlayer.packet_length;
261     pkt = rb->buf + align;
262     /*
263      * Move any available bytes to front of buffer: 'len' bytes already
264      * pointed to by 'packet', 'left' extra ones at the end
265      */
266     if (s->rlayer.packet != pkt && clearold == 1) {
267         memmove(pkt, s->rlayer.packet, len + left);
268         s->rlayer.packet = pkt;
269         rb->offset = len + align;
270     }
271
272     /*
273      * For DTLS/UDP reads should not span multiple packets because the read
274      * operation returns the whole packet at once (as long as it fits into
275      * the buffer).
276      */
277     if (SSL_CONNECTION_IS_DTLS(s)) {
278         if (left == 0 && extend)
279             return 0;
280         if (left > 0 && n > left)
281             n = left;
282     }
283
284     /* if there is enough in the buffer from a previous read, take some */
285     if (left >= n) {
286         s->rlayer.packet_length += n;
287         rb->left = left - n;
288         rb->offset += n;
289         *readbytes = n;
290         return 1;
291     }
292
293     /* else we need to read more data */
294
295     if (n > rb->len - rb->offset) {
296         /* does not happen */
297         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
298         return -1;
299     }
300
301     /*
302      * Ktls always reads full records.
303      * Also, we always act like read_ahead is set for DTLS.
304      */
305     if (!BIO_get_ktls_recv(s->rbio) && !s->rlayer.read_ahead
306         && !SSL_CONNECTION_IS_DTLS(s)) {
307         /* ignore max parameter */
308         max = n;
309     } else {
310         if (max < n)
311             max = n;
312         if (max > rb->len - rb->offset)
313             max = rb->len - rb->offset;
314     }
315
316     while (left < n) {
317         size_t bioread = 0;
318         int ret;
319
320         /*
321          * Now we have len+left bytes at the front of s->s3.rbuf.buf and
322          * need to read in more until we have len+n (up to len+max if
323          * possible)
324          */
325
326         clear_sys_error();
327         if (s->rbio != NULL) {
328             s->rwstate = SSL_READING;
329             ret = BIO_read(s->rbio, pkt + len + left, max - left);
330             if (ret >= 0)
331                 bioread = ret;
332             if (ret <= 0
333                     && !BIO_should_retry(s->rbio)
334                     && BIO_eof(s->rbio)) {
335                 if (s->options & SSL_OP_IGNORE_UNEXPECTED_EOF) {
336                     SSL_set_shutdown(SSL_CONNECTION_GET_SSL(s),
337                                      SSL_RECEIVED_SHUTDOWN);
338                     s->s3.warn_alert = SSL_AD_CLOSE_NOTIFY;
339                 } else {
340                     SSLfatal(s, SSL_AD_DECODE_ERROR,
341                              SSL_R_UNEXPECTED_EOF_WHILE_READING);
342                 }
343             }
344         } else {
345             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_READ_BIO_NOT_SET);
346             ret = -1;
347         }
348
349         if (ret <= 0) {
350             rb->left = left;
351             if ((s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
352                 && !SSL_CONNECTION_IS_DTLS(s))
353                 if (len + left == 0)
354                     ssl3_release_read_buffer(s);
355             return ret;
356         }
357         left += bioread;
358         /*
359          * reads should *never* span multiple packets for DTLS because the
360          * underlying transport protocol is message oriented as opposed to
361          * byte oriented as in the TLS case.
362          */
363         if (SSL_CONNECTION_IS_DTLS(s)) {
364             if (n > left)
365                 n = left;       /* makes the while condition false */
366         }
367     }
368
369     /* done reading, now the book-keeping */
370     rb->offset += n;
371     rb->left = left - n;
372     s->rlayer.packet_length += n;
373     s->rwstate = SSL_NOTHING;
374     *readbytes = n;
375     return 1;
376 }
377
378 /*
379  * Call this to write data in records of type 'type' It will return <= 0 if
380  * not all data has been sent or non-blocking IO.
381  */
382 int ssl3_write_bytes(SSL *ssl, int type, const void *buf_, size_t len,
383                      size_t *written)
384 {
385     const unsigned char *buf = buf_;
386     size_t tot;
387     size_t n, max_send_fragment, split_send_fragment, maxpipes;
388 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
389     size_t nw;
390 #endif
391     SSL3_BUFFER *wb;
392     int i;
393     size_t tmpwrit;
394     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
395
396     if (s == NULL)
397         return -1;
398
399     wb = &s->rlayer.wbuf[0];
400     s->rwstate = SSL_NOTHING;
401     tot = s->rlayer.wnum;
402     /*
403      * ensure that if we end up with a smaller value of data to write out
404      * than the original len from a write which didn't complete for
405      * non-blocking I/O and also somehow ended up avoiding the check for
406      * this in ssl3_write_pending/SSL_R_BAD_WRITE_RETRY as it must never be
407      * possible to end up with (len-tot) as a large number that will then
408      * promptly send beyond the end of the users buffer ... so we trap and
409      * report the error in a way the user will notice
410      */
411     if ((len < s->rlayer.wnum)
412         || ((wb->left != 0) && (len < (s->rlayer.wnum + s->rlayer.wpend_tot)))) {
413         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_LENGTH);
414         return -1;
415     }
416
417     if (s->early_data_state == SSL_EARLY_DATA_WRITING
418             && !ossl_early_data_count_ok(s, len, 0, 1)) {
419         /* SSLfatal() already called */
420         return -1;
421     }
422
423     s->rlayer.wnum = 0;
424
425     /*
426      * If we are supposed to be sending a KeyUpdate or NewSessionTicket then go
427      * into init unless we have writes pending - in which case we should finish
428      * doing that first.
429      */
430     if (wb->left == 0 && (s->key_update != SSL_KEY_UPDATE_NONE
431                           || s->ext.extra_tickets_expected > 0))
432         ossl_statem_set_in_init(s, 1);
433
434     /*
435      * When writing early data on the server side we could be "in_init" in
436      * between receiving the EoED and the CF - but we don't want to handle those
437      * messages yet.
438      */
439     if (SSL_in_init(ssl) && !ossl_statem_get_in_handshake(s)
440             && s->early_data_state != SSL_EARLY_DATA_UNAUTH_WRITING) {
441         i = s->handshake_func(ssl);
442         /* SSLfatal() already called */
443         if (i < 0)
444             return i;
445         if (i == 0) {
446             return -1;
447         }
448     }
449
450     /*
451      * first check if there is a SSL3_BUFFER still being written out.  This
452      * will happen with non blocking IO
453      */
454     if (wb->left != 0) {
455         /* SSLfatal() already called if appropriate */
456         i = ssl3_write_pending(s, type, &buf[tot], s->rlayer.wpend_tot,
457                                &tmpwrit);
458         if (i <= 0) {
459             /* XXX should we ssl3_release_write_buffer if i<0? */
460             s->rlayer.wnum = tot;
461             return i;
462         }
463         tot += tmpwrit;               /* this might be last fragment */
464     }
465 #if !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK
466     /*
467      * Depending on platform multi-block can deliver several *times*
468      * better performance. Downside is that it has to allocate
469      * jumbo buffer to accommodate up to 8 records, but the
470      * compromise is considered worthy.
471      */
472     if (type == SSL3_RT_APPLICATION_DATA
473             && len >= 4 * (max_send_fragment = ssl_get_max_send_fragment(s))
474             && s->compress == NULL
475             && s->msg_callback == NULL
476             && !SSL_WRITE_ETM(s)
477             && SSL_USE_EXPLICIT_IV(s)
478             && !BIO_get_ktls_send(s->wbio)
479             && (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
480                 & EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK) != 0) {
481         unsigned char aad[13];
482         EVP_CTRL_TLS1_1_MULTIBLOCK_PARAM mb_param;
483         size_t packlen;
484         int packleni;
485
486         /* minimize address aliasing conflicts */
487         if ((max_send_fragment & 0xfff) == 0)
488             max_send_fragment -= 512;
489
490         if (tot == 0 || wb->buf == NULL) { /* allocate jumbo buffer */
491             ssl3_release_write_buffer(s);
492
493             packlen = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
494                                           EVP_CTRL_TLS1_1_MULTIBLOCK_MAX_BUFSIZE,
495                                           (int)max_send_fragment, NULL);
496
497             if (len >= 8 * max_send_fragment)
498                 packlen *= 8;
499             else
500                 packlen *= 4;
501
502             if (!ssl3_setup_write_buffer(s, 1, packlen)) {
503                 /* SSLfatal() already called */
504                 return -1;
505             }
506         } else if (tot == len) { /* done? */
507             /* free jumbo buffer */
508             ssl3_release_write_buffer(s);
509             *written = tot;
510             return 1;
511         }
512
513         n = (len - tot);
514         for (;;) {
515             if (n < 4 * max_send_fragment) {
516                 /* free jumbo buffer */
517                 ssl3_release_write_buffer(s);
518                 break;
519             }
520
521             if (s->s3.alert_dispatch) {
522                 i = ssl->method->ssl_dispatch_alert(ssl);
523                 if (i <= 0) {
524                     /* SSLfatal() already called if appropriate */
525                     s->rlayer.wnum = tot;
526                     return i;
527                 }
528             }
529
530             if (n >= 8 * max_send_fragment)
531                 nw = max_send_fragment * (mb_param.interleave = 8);
532             else
533                 nw = max_send_fragment * (mb_param.interleave = 4);
534
535             memcpy(aad, s->rlayer.write_sequence, 8);
536             aad[8] = type;
537             aad[9] = (unsigned char)(s->version >> 8);
538             aad[10] = (unsigned char)(s->version);
539             aad[11] = 0;
540             aad[12] = 0;
541             mb_param.out = NULL;
542             mb_param.inp = aad;
543             mb_param.len = nw;
544
545             packleni = EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
546                                           EVP_CTRL_TLS1_1_MULTIBLOCK_AAD,
547                                           sizeof(mb_param), &mb_param);
548             packlen = (size_t)packleni;
549             if (packleni <= 0 || packlen > wb->len) { /* never happens */
550                 /* free jumbo buffer */
551                 ssl3_release_write_buffer(s);
552                 break;
553             }
554
555             mb_param.out = wb->buf;
556             mb_param.inp = &buf[tot];
557             mb_param.len = nw;
558
559             if (EVP_CIPHER_CTX_ctrl(s->enc_write_ctx,
560                                     EVP_CTRL_TLS1_1_MULTIBLOCK_ENCRYPT,
561                                     sizeof(mb_param), &mb_param) <= 0)
562                 return -1;
563
564             s->rlayer.write_sequence[7] += mb_param.interleave;
565             if (s->rlayer.write_sequence[7] < mb_param.interleave) {
566                 int j = 6;
567                 while (j >= 0 && (++s->rlayer.write_sequence[j--]) == 0) ;
568             }
569
570             wb->offset = 0;
571             wb->left = packlen;
572
573             s->rlayer.wpend_tot = nw;
574             s->rlayer.wpend_buf = &buf[tot];
575             s->rlayer.wpend_type = type;
576             s->rlayer.wpend_ret = nw;
577
578             i = ssl3_write_pending(s, type, &buf[tot], nw, &tmpwrit);
579             if (i <= 0) {
580                 /* SSLfatal() already called if appropriate */
581                 if (i < 0 && (!s->wbio || !BIO_should_retry(s->wbio))) {
582                     /* free jumbo buffer */
583                     ssl3_release_write_buffer(s);
584                 }
585                 s->rlayer.wnum = tot;
586                 return i;
587             }
588             if (tmpwrit == n) {
589                 /* free jumbo buffer */
590                 ssl3_release_write_buffer(s);
591                 *written = tot + tmpwrit;
592                 return 1;
593             }
594             n -= tmpwrit;
595             tot += tmpwrit;
596         }
597     } else
598 #endif  /* !defined(OPENSSL_NO_MULTIBLOCK) && EVP_CIPH_FLAG_TLS1_1_MULTIBLOCK */
599     if (tot == len) {           /* done? */
600         if (s->mode & SSL_MODE_RELEASE_BUFFERS && !SSL_CONNECTION_IS_DTLS(s))
601             ssl3_release_write_buffer(s);
602
603         *written = tot;
604         return 1;
605     }
606
607     n = (len - tot);
608
609     max_send_fragment = ssl_get_max_send_fragment(s);
610     split_send_fragment = ssl_get_split_send_fragment(s);
611     /*
612      * If max_pipelines is 0 then this means "undefined" and we default to
613      * 1 pipeline. Similarly if the cipher does not support pipelined
614      * processing then we also only use 1 pipeline, or if we're not using
615      * explicit IVs
616      */
617     maxpipes = s->max_pipelines;
618     if (maxpipes > SSL_MAX_PIPELINES) {
619         /*
620          * We should have prevented this when we set max_pipelines so we
621          * shouldn't get here
622          */
623         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
624         return -1;
625     }
626     if (maxpipes == 0
627         || s->enc_write_ctx == NULL
628         || (EVP_CIPHER_get_flags(EVP_CIPHER_CTX_get0_cipher(s->enc_write_ctx))
629             & EVP_CIPH_FLAG_PIPELINE) == 0
630         || !SSL_USE_EXPLICIT_IV(s))
631         maxpipes = 1;
632     if (max_send_fragment == 0
633             || split_send_fragment == 0
634             || split_send_fragment > max_send_fragment) {
635         /*
636          * We should have prevented this when we set/get the split and max send
637          * fragments so we shouldn't get here
638          */
639         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
640         return -1;
641     }
642
643     for (;;) {
644         size_t pipelens[SSL_MAX_PIPELINES], tmppipelen, remain;
645         size_t numpipes, j;
646
647         if (n == 0)
648             numpipes = 1;
649         else
650             numpipes = ((n - 1) / split_send_fragment) + 1;
651         if (numpipes > maxpipes)
652             numpipes = maxpipes;
653
654         if (n / numpipes >= max_send_fragment) {
655             /*
656              * We have enough data to completely fill all available
657              * pipelines
658              */
659             for (j = 0; j < numpipes; j++) {
660                 pipelens[j] = max_send_fragment;
661             }
662         } else {
663             /* We can partially fill all available pipelines */
664             tmppipelen = n / numpipes;
665             remain = n % numpipes;
666             for (j = 0; j < numpipes; j++) {
667                 pipelens[j] = tmppipelen;
668                 if (j < remain)
669                     pipelens[j]++;
670             }
671         }
672
673         i = do_ssl3_write(s, type, &(buf[tot]), pipelens, numpipes, 0,
674                           &tmpwrit);
675         if (i <= 0) {
676             /* SSLfatal() already called if appropriate */
677             /* XXX should we ssl3_release_write_buffer if i<0? */
678             s->rlayer.wnum = tot;
679             return i;
680         }
681
682         if (tmpwrit == n ||
683             (type == SSL3_RT_APPLICATION_DATA &&
684              (s->mode & SSL_MODE_ENABLE_PARTIAL_WRITE))) {
685             /*
686              * next chunk of data should get another prepended empty fragment
687              * in ciphersuites with known-IV weakness:
688              */
689             s->s3.empty_fragment_done = 0;
690
691             if (tmpwrit == n
692                     && (s->mode & SSL_MODE_RELEASE_BUFFERS) != 0
693                     && !SSL_CONNECTION_IS_DTLS(s))
694                 ssl3_release_write_buffer(s);
695
696             *written = tot + tmpwrit;
697             return 1;
698         }
699
700         n -= tmpwrit;
701         tot += tmpwrit;
702     }
703 }
704
705 int do_ssl3_write(SSL_CONNECTION *s, int type, const unsigned char *buf,
706                   size_t *pipelens, size_t numpipes,
707                   int create_empty_fragment, size_t *written)
708 {
709     WPACKET pkt[SSL_MAX_PIPELINES];
710     SSL3_RECORD wr[SSL_MAX_PIPELINES];
711     WPACKET *thispkt;
712     SSL3_RECORD *thiswr;
713     unsigned char *recordstart;
714     int i, mac_size, clear = 0;
715     size_t prefix_len = 0;
716     int eivlen = 0;
717     size_t align = 0;
718     SSL3_BUFFER *wb;
719     SSL_SESSION *sess;
720     size_t totlen = 0, len, wpinited = 0;
721     size_t j;
722     int using_ktls;
723     SSL *ssl = SSL_CONNECTION_GET_SSL(s);
724
725     for (j = 0; j < numpipes; j++)
726         totlen += pipelens[j];
727     /*
728      * first check if there is a SSL3_BUFFER still being written out.  This
729      * will happen with non blocking IO
730      */
731     if (RECORD_LAYER_write_pending(&s->rlayer)) {
732         /* Calls SSLfatal() as required */
733         return ssl3_write_pending(s, type, buf, totlen, written);
734     }
735
736     /* If we have an alert to send, lets send it */
737     if (s->s3.alert_dispatch) {
738         i = ssl->method->ssl_dispatch_alert(ssl);
739         if (i <= 0) {
740             /* SSLfatal() already called if appropriate */
741             return i;
742         }
743         /* if it went, fall through and send more stuff */
744     }
745
746     if (s->rlayer.numwpipes < numpipes) {
747         if (!ssl3_setup_write_buffer(s, numpipes, 0)) {
748             /* SSLfatal() already called */
749             return -1;
750         }
751     }
752
753     if (totlen == 0 && !create_empty_fragment)
754         return 0;
755
756     sess = s->session;
757
758     if ((sess == NULL)
759             || (s->enc_write_ctx == NULL)
760             || (EVP_MD_CTX_get0_md(s->write_hash) == NULL)) {
761         clear = s->enc_write_ctx ? 0 : 1; /* must be AEAD cipher */
762         mac_size = 0;
763     } else {
764         mac_size = EVP_MD_CTX_get_size(s->write_hash);
765         if (mac_size < 0) {
766             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
767             goto err;
768         }
769     }
770
771     /*
772      * 'create_empty_fragment' is true only when this function calls itself
773      */
774     if (!clear && !create_empty_fragment && !s->s3.empty_fragment_done) {
775         /*
776          * countermeasure against known-IV weakness in CBC ciphersuites (see
777          * http://www.openssl.org/~bodo/tls-cbc.txt)
778          */
779
780         if (s->s3.need_empty_fragments && type == SSL3_RT_APPLICATION_DATA) {
781             /*
782              * recursive function call with 'create_empty_fragment' set; this
783              * prepares and buffers the data for an empty fragment (these
784              * 'prefix_len' bytes are sent out later together with the actual
785              * payload)
786              */
787             size_t tmppipelen = 0;
788             int ret;
789
790             ret = do_ssl3_write(s, type, buf, &tmppipelen, 1, 1, &prefix_len);
791             if (ret <= 0) {
792                 /* SSLfatal() already called if appropriate */
793                 goto err;
794             }
795
796             if (prefix_len >
797                 (SSL3_RT_HEADER_LENGTH + SSL3_RT_SEND_MAX_ENCRYPTED_OVERHEAD)) {
798                 /* insufficient space */
799                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
800                 goto err;
801             }
802         }
803
804         s->s3.empty_fragment_done = 1;
805     }
806
807     using_ktls = BIO_get_ktls_send(s->wbio);
808     if (using_ktls) {
809         /*
810          * ktls doesn't modify the buffer, but to avoid a warning we need to
811          * discard the const qualifier.
812          * This doesn't leak memory because the buffers have been released when
813          * switching to ktls.
814          */
815         SSL3_BUFFER_set_buf(&s->rlayer.wbuf[0], (unsigned char *)buf);
816         SSL3_BUFFER_set_offset(&s->rlayer.wbuf[0], 0);
817         SSL3_BUFFER_set_app_buffer(&s->rlayer.wbuf[0], 1);
818         goto wpacket_init_complete;
819     }
820
821     if (create_empty_fragment) {
822         wb = &s->rlayer.wbuf[0];
823 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD!=0
824         /*
825          * extra fragment would be couple of cipher blocks, which would be
826          * multiple of SSL3_ALIGN_PAYLOAD, so if we want to align the real
827          * payload, then we can just pretend we simply have two headers.
828          */
829         align = (size_t)SSL3_BUFFER_get_buf(wb) + 2 * SSL3_RT_HEADER_LENGTH;
830         align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
831 #endif
832         SSL3_BUFFER_set_offset(wb, align);
833         if (!WPACKET_init_static_len(&pkt[0], SSL3_BUFFER_get_buf(wb),
834                                      SSL3_BUFFER_get_len(wb), 0)
835                 || !WPACKET_allocate_bytes(&pkt[0], align, NULL)) {
836             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
837             goto err;
838         }
839         wpinited = 1;
840     } else if (prefix_len) {
841         wb = &s->rlayer.wbuf[0];
842         if (!WPACKET_init_static_len(&pkt[0],
843                                      SSL3_BUFFER_get_buf(wb),
844                                      SSL3_BUFFER_get_len(wb), 0)
845                 || !WPACKET_allocate_bytes(&pkt[0], SSL3_BUFFER_get_offset(wb)
846                                                     + prefix_len, NULL)) {
847             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
848             goto err;
849         }
850         wpinited = 1;
851     } else {
852         for (j = 0; j < numpipes; j++) {
853             thispkt = &pkt[j];
854
855             wb = &s->rlayer.wbuf[j];
856 #if defined(SSL3_ALIGN_PAYLOAD) && SSL3_ALIGN_PAYLOAD != 0
857             align = (size_t)SSL3_BUFFER_get_buf(wb) + SSL3_RT_HEADER_LENGTH;
858             align = SSL3_ALIGN_PAYLOAD - 1 - ((align - 1) % SSL3_ALIGN_PAYLOAD);
859 #endif
860             SSL3_BUFFER_set_offset(wb, align);
861             if (!WPACKET_init_static_len(thispkt, SSL3_BUFFER_get_buf(wb),
862                                          SSL3_BUFFER_get_len(wb), 0)
863                     || !WPACKET_allocate_bytes(thispkt, align, NULL)) {
864                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
865                 goto err;
866             }
867             wpinited++;
868         }
869     }
870
871     /* Explicit IV length, block ciphers appropriate version flag */
872     if (s->enc_write_ctx && SSL_USE_EXPLICIT_IV(s)
873         && !SSL_CONNECTION_TREAT_AS_TLS13(s)) {
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                 goto err;
880             }
881             if (eivlen <= 1)
882                 eivlen = 0;
883         } else if (mode == EVP_CIPH_GCM_MODE) {
884             /* Need explicit part of IV for GCM mode */
885             eivlen = EVP_GCM_TLS_EXPLICIT_IV_LEN;
886         } else if (mode == EVP_CIPH_CCM_MODE) {
887             eivlen = EVP_CCM_TLS_EXPLICIT_IV_LEN;
888         }
889     }
890
891  wpacket_init_complete:
892
893     totlen = 0;
894     /* Clear our SSL3_RECORD structures */
895     memset(wr, 0, sizeof(wr));
896     for (j = 0; j < numpipes; j++) {
897         unsigned int version = (s->version == TLS1_3_VERSION) ? TLS1_2_VERSION
898                                                               : s->version;
899         unsigned char *compressdata = NULL;
900         size_t maxcomplen;
901         unsigned int rectype;
902
903         thispkt = &pkt[j];
904         thiswr = &wr[j];
905
906         /*
907          * In TLSv1.3, once encrypting, we always use application data for the
908          * record type
909          */
910         if (SSL_CONNECTION_TREAT_AS_TLS13(s)
911                 && s->enc_write_ctx != NULL
912                 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
913                     || type != SSL3_RT_ALERT))
914             rectype = SSL3_RT_APPLICATION_DATA;
915         else
916             rectype = type;
917         SSL3_RECORD_set_type(thiswr, rectype);
918
919         /*
920          * Some servers hang if initial client hello is larger than 256 bytes
921          * and record version number > TLS 1.0
922          */
923         if (SSL_get_state(ssl) == TLS_ST_CW_CLNT_HELLO
924                 && !s->renegotiate
925                 && TLS1_get_version(ssl) > TLS1_VERSION
926                 && s->hello_retry_request == SSL_HRR_NONE)
927             version = TLS1_VERSION;
928         SSL3_RECORD_set_rec_version(thiswr, version);
929
930         maxcomplen = pipelens[j];
931         if (s->compress != NULL)
932             maxcomplen += SSL3_RT_MAX_COMPRESSED_OVERHEAD;
933
934         /*
935          * When using offload kernel will write the header.
936          * Otherwise write the header now
937          */
938         if (!using_ktls
939                 && (!WPACKET_put_bytes_u8(thispkt, rectype)
940                 || !WPACKET_put_bytes_u16(thispkt, version)
941                 || !WPACKET_start_sub_packet_u16(thispkt)
942                 || (eivlen > 0
943                     && !WPACKET_allocate_bytes(thispkt, eivlen, NULL))
944                 || (maxcomplen > 0
945                     && !WPACKET_reserve_bytes(thispkt, maxcomplen,
946                                               &compressdata)))) {
947             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
948             goto err;
949         }
950
951         /* lets setup the record stuff. */
952         SSL3_RECORD_set_data(thiswr, compressdata);
953         SSL3_RECORD_set_length(thiswr, pipelens[j]);
954         SSL3_RECORD_set_input(thiswr, (unsigned char *)&buf[totlen]);
955         totlen += pipelens[j];
956
957         /*
958          * we now 'read' from thiswr->input, thiswr->length bytes into
959          * thiswr->data
960          */
961
962         /* first we compress */
963         if (s->compress != NULL) {
964             if (!ssl3_do_compress(s, thiswr)
965                     || !WPACKET_allocate_bytes(thispkt, thiswr->length, NULL)) {
966                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_COMPRESSION_FAILURE);
967                 goto err;
968             }
969         } else {
970             if (using_ktls) {
971                 SSL3_RECORD_reset_data(&wr[j]);
972             } else {
973                 if (!WPACKET_memcpy(thispkt, thiswr->input, thiswr->length)) {
974                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
975                     goto err;
976                 }
977                 SSL3_RECORD_reset_input(&wr[j]);
978             }
979         }
980
981         if (SSL_CONNECTION_TREAT_AS_TLS13(s)
982                 && !using_ktls
983                 && s->enc_write_ctx != NULL
984                 && (s->statem.enc_write_state != ENC_WRITE_STATE_WRITE_PLAIN_ALERTS
985                     || type != SSL3_RT_ALERT)) {
986             size_t rlen, max_send_fragment;
987
988             if (!WPACKET_put_bytes_u8(thispkt, type)) {
989                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
990                 goto err;
991             }
992             SSL3_RECORD_add_length(thiswr, 1);
993
994             /* Add TLS1.3 padding */
995             max_send_fragment = ssl_get_max_send_fragment(s);
996             rlen = SSL3_RECORD_get_length(thiswr);
997             if (rlen < max_send_fragment) {
998                 size_t padding = 0;
999                 size_t max_padding = max_send_fragment - rlen;
1000                 if (s->record_padding_cb != NULL) {
1001                     padding = s->record_padding_cb(ssl, type, rlen, s->record_padding_arg);
1002                 } else if (s->block_padding > 0) {
1003                     size_t mask = s->block_padding - 1;
1004                     size_t remainder;
1005
1006                     /* optimize for power of 2 */
1007                     if ((s->block_padding & mask) == 0)
1008                         remainder = rlen & mask;
1009                     else
1010                         remainder = rlen % s->block_padding;
1011                     /* don't want to add a block of padding if we don't have to */
1012                     if (remainder == 0)
1013                         padding = 0;
1014                     else
1015                         padding = s->block_padding - remainder;
1016                 }
1017                 if (padding > 0) {
1018                     /* do not allow the record to exceed max plaintext length */
1019                     if (padding > max_padding)
1020                         padding = max_padding;
1021                     if (!WPACKET_memset(thispkt, 0, padding)) {
1022                         SSLfatal(s, SSL_AD_INTERNAL_ERROR,
1023                                  ERR_R_INTERNAL_ERROR);
1024                         goto err;
1025                     }
1026                     SSL3_RECORD_add_length(thiswr, padding);
1027                 }
1028             }
1029         }
1030
1031         /*
1032          * we should still have the output to thiswr->data and the input from
1033          * wr->input. Length should be thiswr->length. thiswr->data still points
1034          * in the wb->buf
1035          */
1036
1037         if (!using_ktls && !SSL_WRITE_ETM(s) && mac_size != 0) {
1038             unsigned char *mac;
1039
1040             if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1041                     || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
1042                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1043                 goto err;
1044             }
1045         }
1046
1047         /*
1048          * Reserve some bytes for any growth that may occur during encryption.
1049          * This will be at most one cipher block or the tag length if using
1050          * AEAD. SSL_RT_MAX_CIPHER_BLOCK_SIZE covers either case.
1051          */
1052         if (!using_ktls) {
1053             if (!WPACKET_reserve_bytes(thispkt,
1054                                         SSL_RT_MAX_CIPHER_BLOCK_SIZE,
1055                                         NULL)
1056                 /*
1057                  * We also need next the amount of bytes written to this
1058                  * sub-packet
1059                  */
1060                 || !WPACKET_get_length(thispkt, &len)) {
1061             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1062             goto err;
1063             }
1064
1065             /* Get a pointer to the start of this record excluding header */
1066             recordstart = WPACKET_get_curr(thispkt) - len;
1067             SSL3_RECORD_set_data(thiswr, recordstart);
1068             SSL3_RECORD_reset_input(thiswr);
1069             SSL3_RECORD_set_length(thiswr, len);
1070         }
1071     }
1072
1073     if (s->statem.enc_write_state == ENC_WRITE_STATE_WRITE_PLAIN_ALERTS) {
1074         /*
1075          * We haven't actually negotiated the version yet, but we're trying to
1076          * send early data - so we need to use the tls13enc function.
1077          */
1078         if (tls13_enc(s, wr, numpipes, 1, NULL, mac_size) < 1) {
1079             if (!ossl_statem_in_error(s)) {
1080                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1081             }
1082             goto err;
1083         }
1084     } else {
1085         if (!using_ktls) {
1086             if (ssl->method->ssl3_enc->enc(s, wr, numpipes, 1, NULL,
1087                                          mac_size) < 1) {
1088                 if (!ossl_statem_in_error(s)) {
1089                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1090                 }
1091                 goto err;
1092             }
1093         }
1094     }
1095
1096     for (j = 0; j < numpipes; j++) {
1097         size_t origlen;
1098
1099         thispkt = &pkt[j];
1100         thiswr = &wr[j];
1101
1102         if (using_ktls)
1103             goto mac_done;
1104
1105         /* Allocate bytes for the encryption overhead */
1106         if (!WPACKET_get_length(thispkt, &origlen)
1107                    /* Encryption should never shrink the data! */
1108                 || origlen > thiswr->length
1109                 || (thiswr->length > origlen
1110                     && !WPACKET_allocate_bytes(thispkt,
1111                                                thiswr->length - origlen,
1112                                                NULL))) {
1113             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1114             goto err;
1115         }
1116         if (SSL_WRITE_ETM(s) && mac_size != 0) {
1117             unsigned char *mac;
1118
1119             if (!WPACKET_allocate_bytes(thispkt, mac_size, &mac)
1120                     || !ssl->method->ssl3_enc->mac(s, thiswr, mac, 1)) {
1121                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1122                 goto err;
1123             }
1124             SSL3_RECORD_add_length(thiswr, mac_size);
1125         }
1126
1127         if (!WPACKET_get_length(thispkt, &len)
1128                 || !WPACKET_close(thispkt)) {
1129             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1130             goto err;
1131         }
1132
1133         if (s->msg_callback) {
1134             recordstart = WPACKET_get_curr(thispkt) - len
1135                           - SSL3_RT_HEADER_LENGTH;
1136             s->msg_callback(1, thiswr->rec_version, SSL3_RT_HEADER, recordstart,
1137                             SSL3_RT_HEADER_LENGTH, ssl,
1138                             s->msg_callback_arg);
1139
1140             if (SSL_CONNECTION_TREAT_AS_TLS13(s) && s->enc_write_ctx != NULL) {
1141                 unsigned char ctype = type;
1142
1143                 s->msg_callback(1, thiswr->rec_version, SSL3_RT_INNER_CONTENT_TYPE,
1144                                 &ctype, 1, ssl, s->msg_callback_arg);
1145             }
1146         }
1147
1148         if (!WPACKET_finish(thispkt)) {
1149             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1150             goto err;
1151         }
1152
1153         /* header is added by the kernel when using offload */
1154         SSL3_RECORD_add_length(thiswr, SSL3_RT_HEADER_LENGTH);
1155
1156         if (create_empty_fragment) {
1157             /*
1158              * we are in a recursive call; just return the length, don't write
1159              * out anything here
1160              */
1161             if (j > 0) {
1162                 /* We should never be pipelining an empty fragment!! */
1163                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1164                 goto err;
1165             }
1166             *written = SSL3_RECORD_get_length(thiswr);
1167             return 1;
1168         }
1169
1170  mac_done:
1171         /*
1172          * we should now have thiswr->data pointing to the encrypted data, which
1173          * is thiswr->length long
1174          */
1175         SSL3_RECORD_set_type(thiswr, type); /* not needed but helps for
1176                                              * debugging */
1177
1178         /* now let's set up wb */
1179         SSL3_BUFFER_set_left(&s->rlayer.wbuf[j],
1180                              prefix_len + SSL3_RECORD_get_length(thiswr));
1181     }
1182
1183     /*
1184      * memorize arguments so that ssl3_write_pending can detect bad write
1185      * retries later
1186      */
1187     s->rlayer.wpend_tot = totlen;
1188     s->rlayer.wpend_buf = buf;
1189     s->rlayer.wpend_type = type;
1190     s->rlayer.wpend_ret = totlen;
1191
1192     /* we now just need to write the buffer */
1193     return ssl3_write_pending(s, type, buf, totlen, written);
1194  err:
1195     for (j = 0; j < wpinited; j++)
1196         WPACKET_cleanup(&pkt[j]);
1197     return -1;
1198 }
1199
1200 /* if SSL3_BUFFER_get_left() != 0, we need to call this
1201  *
1202  * Return values are as per SSL_write()
1203  */
1204 int ssl3_write_pending(SSL_CONNECTION *s, int type, const unsigned char *buf,
1205                        size_t len, size_t *written)
1206 {
1207     int i;
1208     SSL3_BUFFER *wb = s->rlayer.wbuf;
1209     size_t currbuf = 0;
1210     size_t tmpwrit = 0;
1211
1212     if ((s->rlayer.wpend_tot > len)
1213         || (!(s->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER)
1214             && (s->rlayer.wpend_buf != buf))
1215         || (s->rlayer.wpend_type != type)) {
1216         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_WRITE_RETRY);
1217         return -1;
1218     }
1219
1220     for (;;) {
1221         /* Loop until we find a buffer we haven't written out yet */
1222         if (SSL3_BUFFER_get_left(&wb[currbuf]) == 0
1223             && currbuf < s->rlayer.numwpipes - 1) {
1224             currbuf++;
1225             continue;
1226         }
1227         clear_sys_error();
1228         if (s->wbio != NULL) {
1229             s->rwstate = SSL_WRITING;
1230
1231             /*
1232              * To prevent coalescing of control and data messages,
1233              * such as in buffer_write, we flush the BIO
1234              */
1235             if (BIO_get_ktls_send(s->wbio) && type != SSL3_RT_APPLICATION_DATA) {
1236                 i = BIO_flush(s->wbio);
1237                 if (i <= 0)
1238                     return i;
1239                 BIO_set_ktls_ctrl_msg(s->wbio, type);
1240             }
1241             i = BIO_write(s->wbio, (char *)
1242                           &(SSL3_BUFFER_get_buf(&wb[currbuf])
1243                             [SSL3_BUFFER_get_offset(&wb[currbuf])]),
1244                           (unsigned int)SSL3_BUFFER_get_left(&wb[currbuf]));
1245             if (i >= 0)
1246                 tmpwrit = i;
1247         } else {
1248             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BIO_NOT_SET);
1249             i = -1;
1250         }
1251
1252         /*
1253          * When an empty fragment is sent on a connection using KTLS,
1254          * it is sent as a write of zero bytes.  If this zero byte
1255          * write succeeds, i will be 0 rather than a non-zero value.
1256          * Treat i == 0 as success rather than an error for zero byte
1257          * writes to permit this case.
1258          */
1259         if (i >= 0 && tmpwrit == SSL3_BUFFER_get_left(&wb[currbuf])) {
1260             SSL3_BUFFER_set_left(&wb[currbuf], 0);
1261             SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1262             if (currbuf + 1 < s->rlayer.numwpipes)
1263                 continue;
1264             s->rwstate = SSL_NOTHING;
1265             *written = s->rlayer.wpend_ret;
1266             return 1;
1267         } else if (i <= 0) {
1268             if (SSL_CONNECTION_IS_DTLS(s)) {
1269                 /*
1270                  * For DTLS, just drop it. That's kind of the whole point in
1271                  * using a datagram service
1272                  */
1273                 SSL3_BUFFER_set_left(&wb[currbuf], 0);
1274             }
1275             return i;
1276         }
1277         SSL3_BUFFER_add_offset(&wb[currbuf], tmpwrit);
1278         SSL3_BUFFER_sub_left(&wb[currbuf], tmpwrit);
1279     }
1280 }
1281
1282 /*-
1283  * Return up to 'len' payload bytes received in 'type' records.
1284  * 'type' is one of the following:
1285  *
1286  *   -  SSL3_RT_HANDSHAKE (when ssl3_get_message calls us)
1287  *   -  SSL3_RT_APPLICATION_DATA (when ssl3_read calls us)
1288  *   -  0 (during a shutdown, no data has to be returned)
1289  *
1290  * If we don't have stored data to work from, read a SSL/TLS record first
1291  * (possibly multiple records if we still don't have anything to return).
1292  *
1293  * This function must handle any surprises the peer may have for us, such as
1294  * Alert records (e.g. close_notify) or renegotiation requests. ChangeCipherSpec
1295  * messages are treated as if they were handshake messages *if* the |recvd_type|
1296  * argument is non NULL.
1297  * Also if record payloads contain fragments too small to process, we store
1298  * them until there is enough for the respective protocol (the record protocol
1299  * may use arbitrary fragmentation and even interleaving):
1300  *     Change cipher spec protocol
1301  *             just 1 byte needed, no need for keeping anything stored
1302  *     Alert protocol
1303  *             2 bytes needed (AlertLevel, AlertDescription)
1304  *     Handshake protocol
1305  *             4 bytes needed (HandshakeType, uint24 length) -- we just have
1306  *             to detect unexpected Client Hello and Hello Request messages
1307  *             here, anything else is handled by higher layers
1308  *     Application data protocol
1309  *             none of our business
1310  */
1311 int ssl3_read_bytes(SSL *ssl, int type, int *recvd_type, unsigned char *buf,
1312                     size_t len, int peek, size_t *readbytes)
1313 {
1314     int i, j, ret;
1315     size_t n, curr_rec, num_recs, totalbytes;
1316     SSL3_RECORD *rr;
1317     SSL3_BUFFER *rbuf;
1318     void (*cb) (const SSL *ssl, int type2, int val) = NULL;
1319     int is_tls13;
1320     SSL_CONNECTION *s = SSL_CONNECTION_FROM_SSL_ONLY(ssl);
1321
1322     is_tls13 = SSL_CONNECTION_IS_TLS13(s);
1323
1324     rbuf = &s->rlayer.rbuf;
1325
1326     if (!SSL3_BUFFER_is_initialised(rbuf)) {
1327         /* Not initialized yet */
1328         if (!ssl3_setup_read_buffer(s)) {
1329             /* SSLfatal() already called */
1330             return -1;
1331         }
1332     }
1333
1334     if ((type && (type != SSL3_RT_APPLICATION_DATA)
1335          && (type != SSL3_RT_HANDSHAKE)) || (peek
1336                                              && (type !=
1337                                                  SSL3_RT_APPLICATION_DATA))) {
1338         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1339         return -1;
1340     }
1341
1342     if ((type == SSL3_RT_HANDSHAKE) && (s->rlayer.handshake_fragment_len > 0))
1343         /* (partially) satisfy request from storage */
1344     {
1345         unsigned char *src = s->rlayer.handshake_fragment;
1346         unsigned char *dst = buf;
1347         unsigned int k;
1348
1349         /* peek == 0 */
1350         n = 0;
1351         while ((len > 0) && (s->rlayer.handshake_fragment_len > 0)) {
1352             *dst++ = *src++;
1353             len--;
1354             s->rlayer.handshake_fragment_len--;
1355             n++;
1356         }
1357         /* move any remaining fragment bytes: */
1358         for (k = 0; k < s->rlayer.handshake_fragment_len; k++)
1359             s->rlayer.handshake_fragment[k] = *src++;
1360
1361         if (recvd_type != NULL)
1362             *recvd_type = SSL3_RT_HANDSHAKE;
1363
1364         *readbytes = n;
1365         return 1;
1366     }
1367
1368     /*
1369      * Now s->rlayer.handshake_fragment_len == 0 if type == SSL3_RT_HANDSHAKE.
1370      */
1371
1372     if (!ossl_statem_get_in_handshake(s) && SSL_in_init(ssl)) {
1373         /* type == SSL3_RT_APPLICATION_DATA */
1374         i = s->handshake_func(ssl);
1375         /* SSLfatal() already called */
1376         if (i < 0)
1377             return i;
1378         if (i == 0)
1379             return -1;
1380     }
1381  start:
1382     s->rwstate = SSL_NOTHING;
1383
1384     /*-
1385      * For each record 'i' up to |num_recs]
1386      * rr[i].type     - is the type of record
1387      * rr[i].data,    - data
1388      * rr[i].off,     - offset into 'data' for next read
1389      * rr[i].length,  - number of bytes.
1390      */
1391     rr = s->rlayer.rrec;
1392     num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
1393
1394     do {
1395         /* get new records if necessary */
1396         if (num_recs == 0) {
1397             ret = ssl3_get_record(s);
1398             if (ret <= 0) {
1399                 /* SSLfatal() already called if appropriate */
1400                 return ret;
1401             }
1402             num_recs = RECORD_LAYER_get_numrpipes(&s->rlayer);
1403             if (num_recs == 0) {
1404                 /* Shouldn't happen */
1405                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1406                 return -1;
1407             }
1408         }
1409         /* Skip over any records we have already read */
1410         for (curr_rec = 0;
1411              curr_rec < num_recs && SSL3_RECORD_is_read(&rr[curr_rec]);
1412              curr_rec++) ;
1413         if (curr_rec == num_recs) {
1414             RECORD_LAYER_set_numrpipes(&s->rlayer, 0);
1415             num_recs = 0;
1416             curr_rec = 0;
1417         }
1418     } while (num_recs == 0);
1419     rr = &rr[curr_rec];
1420
1421     if (s->rlayer.handshake_fragment_len > 0
1422             && SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE
1423             && SSL_CONNECTION_IS_TLS13(s)) {
1424         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1425                  SSL_R_MIXED_HANDSHAKE_AND_NON_HANDSHAKE_DATA);
1426         return -1;
1427     }
1428
1429     /*
1430      * Reset the count of consecutive warning alerts if we've got a non-empty
1431      * record that isn't an alert.
1432      */
1433     if (SSL3_RECORD_get_type(rr) != SSL3_RT_ALERT
1434             && SSL3_RECORD_get_length(rr) != 0)
1435         s->rlayer.alert_count = 0;
1436
1437     /* we now have a packet which can be read and processed */
1438
1439     if (s->s3.change_cipher_spec /* set when we receive ChangeCipherSpec,
1440                                   * reset by ssl3_get_finished */
1441         && (SSL3_RECORD_get_type(rr) != SSL3_RT_HANDSHAKE)) {
1442         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1443                  SSL_R_DATA_BETWEEN_CCS_AND_FINISHED);
1444         return -1;
1445     }
1446
1447     /*
1448      * If the other end has shut down, throw anything we read away (even in
1449      * 'peek' mode)
1450      */
1451     if (s->shutdown & SSL_RECEIVED_SHUTDOWN) {
1452         SSL3_RECORD_set_length(rr, 0);
1453         s->rwstate = SSL_NOTHING;
1454         return 0;
1455     }
1456
1457     if (type == SSL3_RECORD_get_type(rr)
1458         || (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
1459             && type == SSL3_RT_HANDSHAKE && recvd_type != NULL
1460             && !is_tls13)) {
1461         /*
1462          * SSL3_RT_APPLICATION_DATA or
1463          * SSL3_RT_HANDSHAKE or
1464          * SSL3_RT_CHANGE_CIPHER_SPEC
1465          */
1466         /*
1467          * make sure that we are not getting application data when we are
1468          * doing a handshake for the first time
1469          */
1470         if (SSL_in_init(ssl) && type == SSL3_RT_APPLICATION_DATA
1471             && s->enc_read_ctx == NULL) {
1472             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_APP_DATA_IN_HANDSHAKE);
1473             return -1;
1474         }
1475
1476         if (type == SSL3_RT_HANDSHAKE
1477             && SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC
1478             && s->rlayer.handshake_fragment_len > 0) {
1479             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1480             return -1;
1481         }
1482
1483         if (recvd_type != NULL)
1484             *recvd_type = SSL3_RECORD_get_type(rr);
1485
1486         if (len == 0) {
1487             /*
1488              * Mark a zero length record as read. This ensures multiple calls to
1489              * SSL_read() with a zero length buffer will eventually cause
1490              * SSL_pending() to report data as being available.
1491              */
1492             if (SSL3_RECORD_get_length(rr) == 0)
1493                 SSL3_RECORD_set_read(rr);
1494             return 0;
1495         }
1496
1497         totalbytes = 0;
1498         do {
1499             if (len - totalbytes > SSL3_RECORD_get_length(rr))
1500                 n = SSL3_RECORD_get_length(rr);
1501             else
1502                 n = len - totalbytes;
1503
1504             memcpy(buf, &(rr->data[rr->off]), n);
1505             buf += n;
1506             if (peek) {
1507                 /* Mark any zero length record as consumed CVE-2016-6305 */
1508                 if (SSL3_RECORD_get_length(rr) == 0)
1509                     SSL3_RECORD_set_read(rr);
1510             } else {
1511                 if (s->options & SSL_OP_CLEANSE_PLAINTEXT)
1512                     OPENSSL_cleanse(&(rr->data[rr->off]), n);
1513                 SSL3_RECORD_sub_length(rr, n);
1514                 SSL3_RECORD_add_off(rr, n);
1515                 if (SSL3_RECORD_get_length(rr) == 0) {
1516                     s->rlayer.rstate = SSL_ST_READ_HEADER;
1517                     SSL3_RECORD_set_off(rr, 0);
1518                     SSL3_RECORD_set_read(rr);
1519                 }
1520             }
1521             if (SSL3_RECORD_get_length(rr) == 0
1522                 || (peek && n == SSL3_RECORD_get_length(rr))) {
1523                 curr_rec++;
1524                 rr++;
1525             }
1526             totalbytes += n;
1527         } while (type == SSL3_RT_APPLICATION_DATA && curr_rec < num_recs
1528                  && totalbytes < len);
1529         if (totalbytes == 0) {
1530             /* We must have read empty records. Get more data */
1531             goto start;
1532         }
1533         if (!peek && curr_rec == num_recs
1534             && (s->mode & SSL_MODE_RELEASE_BUFFERS)
1535             && SSL3_BUFFER_get_left(rbuf) == 0)
1536             ssl3_release_read_buffer(s);
1537         *readbytes = totalbytes;
1538         return 1;
1539     }
1540
1541     /*
1542      * If we get here, then type != rr->type; if we have a handshake message,
1543      * then it was unexpected (Hello Request or Client Hello) or invalid (we
1544      * were actually expecting a CCS).
1545      */
1546
1547     /*
1548      * Lets just double check that we've not got an SSLv2 record
1549      */
1550     if (rr->rec_version == SSL2_VERSION) {
1551         /*
1552          * Should never happen. ssl3_get_record() should only give us an SSLv2
1553          * record back if this is the first packet and we are looking for an
1554          * initial ClientHello. Therefore |type| should always be equal to
1555          * |rr->type|. If not then something has gone horribly wrong
1556          */
1557         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
1558         return -1;
1559     }
1560
1561     if (ssl->method->version == TLS_ANY_VERSION
1562         && (s->server || rr->type != SSL3_RT_ALERT)) {
1563         /*
1564          * If we've got this far and still haven't decided on what version
1565          * we're using then this must be a client side alert we're dealing
1566          * with. We shouldn't be receiving anything other than a ClientHello
1567          * if we are a server.
1568          */
1569         s->version = rr->rec_version;
1570         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_MESSAGE);
1571         return -1;
1572     }
1573
1574     /*-
1575      * s->rlayer.handshake_fragment_len == 4  iff  rr->type == SSL3_RT_HANDSHAKE;
1576      * (Possibly rr is 'empty' now, i.e. rr->length may be 0.)
1577      */
1578
1579     if (SSL3_RECORD_get_type(rr) == SSL3_RT_ALERT) {
1580         unsigned int alert_level, alert_descr;
1581         unsigned char *alert_bytes = SSL3_RECORD_get_data(rr)
1582                                      + SSL3_RECORD_get_off(rr);
1583         PACKET alert;
1584
1585         if (!PACKET_buf_init(&alert, alert_bytes, SSL3_RECORD_get_length(rr))
1586                 || !PACKET_get_1(&alert, &alert_level)
1587                 || !PACKET_get_1(&alert, &alert_descr)
1588                 || PACKET_remaining(&alert) != 0) {
1589             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_INVALID_ALERT);
1590             return -1;
1591         }
1592
1593         if (s->msg_callback)
1594             s->msg_callback(0, s->version, SSL3_RT_ALERT, alert_bytes, 2, ssl,
1595                             s->msg_callback_arg);
1596
1597         if (s->info_callback != NULL)
1598             cb = s->info_callback;
1599         else if (ssl->ctx->info_callback != NULL)
1600             cb = ssl->ctx->info_callback;
1601
1602         if (cb != NULL) {
1603             j = (alert_level << 8) | alert_descr;
1604             cb(ssl, SSL_CB_READ_ALERT, j);
1605         }
1606
1607         if (alert_level == SSL3_AL_WARNING
1608                 || (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED)) {
1609             s->s3.warn_alert = alert_descr;
1610             SSL3_RECORD_set_read(rr);
1611
1612             s->rlayer.alert_count++;
1613             if (s->rlayer.alert_count == MAX_WARN_ALERT_COUNT) {
1614                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
1615                          SSL_R_TOO_MANY_WARN_ALERTS);
1616                 return -1;
1617             }
1618         }
1619
1620         /*
1621          * Apart from close_notify the only other warning alert in TLSv1.3
1622          * is user_cancelled - which we just ignore.
1623          */
1624         if (is_tls13 && alert_descr == SSL_AD_USER_CANCELLED) {
1625             goto start;
1626         } else if (alert_descr == SSL_AD_CLOSE_NOTIFY
1627                 && (is_tls13 || alert_level == SSL3_AL_WARNING)) {
1628             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1629             return 0;
1630         } else if (alert_level == SSL3_AL_FATAL || is_tls13) {
1631             s->rwstate = SSL_NOTHING;
1632             s->s3.fatal_alert = alert_descr;
1633             SSLfatal_data(s, SSL_AD_NO_ALERT,
1634                           SSL_AD_REASON_OFFSET + alert_descr,
1635                           "SSL alert number %d", alert_descr);
1636             s->shutdown |= SSL_RECEIVED_SHUTDOWN;
1637             SSL3_RECORD_set_read(rr);
1638             SSL_CTX_remove_session(s->session_ctx, s->session);
1639             return 0;
1640         } else if (alert_descr == SSL_AD_NO_RENEGOTIATION) {
1641             /*
1642              * This is a warning but we receive it if we requested
1643              * renegotiation and the peer denied it. Terminate with a fatal
1644              * alert because if application tried to renegotiate it
1645              * presumably had a good reason and expects it to succeed. In
1646              * future we might have a renegotiation where we don't care if
1647              * the peer refused it where we carry on.
1648              */
1649             SSLfatal(s, SSL_AD_HANDSHAKE_FAILURE, SSL_R_NO_RENEGOTIATION);
1650             return -1;
1651         } else if (alert_level == SSL3_AL_WARNING) {
1652             /* We ignore any other warning alert in TLSv1.2 and below */
1653             goto start;
1654         }
1655
1656         SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_R_UNKNOWN_ALERT_TYPE);
1657         return -1;
1658     }
1659
1660     if ((s->shutdown & SSL_SENT_SHUTDOWN) != 0) {
1661         if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
1662             BIO *rbio;
1663
1664             /*
1665              * We ignore any handshake messages sent to us unless they are
1666              * TLSv1.3 in which case we want to process them. For all other
1667              * handshake messages we can't do anything reasonable with them
1668              * because we are unable to write any response due to having already
1669              * sent close_notify.
1670              */
1671             if (!SSL_CONNECTION_IS_TLS13(s)) {
1672                 SSL3_RECORD_set_length(rr, 0);
1673                 SSL3_RECORD_set_read(rr);
1674
1675                 if ((s->mode & SSL_MODE_AUTO_RETRY) != 0)
1676                     goto start;
1677
1678                 s->rwstate = SSL_READING;
1679                 rbio = SSL_get_rbio(ssl);
1680                 BIO_clear_retry_flags(rbio);
1681                 BIO_set_retry_read(rbio);
1682                 return -1;
1683             }
1684         } else {
1685             /*
1686              * The peer is continuing to send application data, but we have
1687              * already sent close_notify. If this was expected we should have
1688              * been called via SSL_read() and this would have been handled
1689              * above.
1690              * No alert sent because we already sent close_notify
1691              */
1692             SSL3_RECORD_set_length(rr, 0);
1693             SSL3_RECORD_set_read(rr);
1694             SSLfatal(s, SSL_AD_NO_ALERT,
1695                      SSL_R_APPLICATION_DATA_AFTER_CLOSE_NOTIFY);
1696             return -1;
1697         }
1698     }
1699
1700     /*
1701      * For handshake data we have 'fragment' storage, so fill that so that we
1702      * can process the header at a fixed place. This is done after the
1703      * "SHUTDOWN" code above to avoid filling the fragment storage with data
1704      * that we're just going to discard.
1705      */
1706     if (SSL3_RECORD_get_type(rr) == SSL3_RT_HANDSHAKE) {
1707         size_t dest_maxlen = sizeof(s->rlayer.handshake_fragment);
1708         unsigned char *dest = s->rlayer.handshake_fragment;
1709         size_t *dest_len = &s->rlayer.handshake_fragment_len;
1710
1711         n = dest_maxlen - *dest_len; /* available space in 'dest' */
1712         if (SSL3_RECORD_get_length(rr) < n)
1713             n = SSL3_RECORD_get_length(rr); /* available bytes */
1714
1715         /* now move 'n' bytes: */
1716         memcpy(dest + *dest_len,
1717                SSL3_RECORD_get_data(rr) + SSL3_RECORD_get_off(rr), n);
1718         SSL3_RECORD_add_off(rr, n);
1719         SSL3_RECORD_sub_length(rr, n);
1720         *dest_len += n;
1721         if (SSL3_RECORD_get_length(rr) == 0)
1722             SSL3_RECORD_set_read(rr);
1723
1724         if (*dest_len < dest_maxlen)
1725             goto start;     /* fragment was too small */
1726     }
1727
1728     if (SSL3_RECORD_get_type(rr) == SSL3_RT_CHANGE_CIPHER_SPEC) {
1729         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_CCS_RECEIVED_EARLY);
1730         return -1;
1731     }
1732
1733     /*
1734      * Unexpected handshake message (ClientHello, NewSessionTicket (TLS1.3) or
1735      * protocol violation)
1736      */
1737     if ((s->rlayer.handshake_fragment_len >= 4)
1738             && !ossl_statem_get_in_handshake(s)) {
1739         int ined = (s->early_data_state == SSL_EARLY_DATA_READING);
1740
1741         /* We found handshake data, so we're going back into init */
1742         ossl_statem_set_in_init(s, 1);
1743
1744         i = s->handshake_func(ssl);
1745         /* SSLfatal() already called if appropriate */
1746         if (i < 0)
1747             return i;
1748         if (i == 0) {
1749             return -1;
1750         }
1751
1752         /*
1753          * If we were actually trying to read early data and we found a
1754          * handshake message, then we don't want to continue to try and read
1755          * the application data any more. It won't be "early" now.
1756          */
1757         if (ined)
1758             return -1;
1759
1760         if (!(s->mode & SSL_MODE_AUTO_RETRY)) {
1761             if (SSL3_BUFFER_get_left(rbuf) == 0) {
1762                 /* no read-ahead left? */
1763                 BIO *bio;
1764                 /*
1765                  * In the case where we try to read application data, but we
1766                  * trigger an SSL handshake, we return -1 with the retry
1767                  * option set.  Otherwise renegotiation may cause nasty
1768                  * problems in the blocking world
1769                  */
1770                 s->rwstate = SSL_READING;
1771                 bio = SSL_get_rbio(ssl);
1772                 BIO_clear_retry_flags(bio);
1773                 BIO_set_retry_read(bio);
1774                 return -1;
1775             }
1776         }
1777         goto start;
1778     }
1779
1780     switch (SSL3_RECORD_get_type(rr)) {
1781     default:
1782         /*
1783          * TLS 1.0 and 1.1 say you SHOULD ignore unrecognised record types, but
1784          * TLS 1.2 says you MUST send an unexpected message alert. We use the
1785          * TLS 1.2 behaviour for all protocol versions to prevent issues where
1786          * no progress is being made and the peer continually sends unrecognised
1787          * record types, using up resources processing them.
1788          */
1789         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1790         return -1;
1791     case SSL3_RT_CHANGE_CIPHER_SPEC:
1792     case SSL3_RT_ALERT:
1793     case SSL3_RT_HANDSHAKE:
1794         /*
1795          * we already handled all of these, with the possible exception of
1796          * SSL3_RT_HANDSHAKE when ossl_statem_get_in_handshake(s) is true, but
1797          * that should not happen when type != rr->type
1798          */
1799         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, ERR_R_INTERNAL_ERROR);
1800         return -1;
1801     case SSL3_RT_APPLICATION_DATA:
1802         /*
1803          * At this point, we were expecting handshake data, but have
1804          * application data.  If the library was running inside ssl3_read()
1805          * (i.e. in_read_app_data is set) and it makes sense to read
1806          * application data at this point (session renegotiation not yet
1807          * started), we will indulge it.
1808          */
1809         if (ossl_statem_app_data_allowed(s)) {
1810             s->s3.in_read_app_data = 2;
1811             return -1;
1812         } else if (ossl_statem_skip_early_data(s)) {
1813             /*
1814              * This can happen after a client sends a CH followed by early_data,
1815              * but the server responds with a HelloRetryRequest. The server
1816              * reads the next record from the client expecting to find a
1817              * plaintext ClientHello but gets a record which appears to be
1818              * application data. The trial decrypt "works" because null
1819              * decryption was applied. We just skip it and move on to the next
1820              * record.
1821              */
1822             if (!ossl_early_data_count_ok(s, rr->length,
1823                                           EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
1824                 /* SSLfatal() already called */
1825                 return -1;
1826             }
1827             SSL3_RECORD_set_read(rr);
1828             goto start;
1829         } else {
1830             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_R_UNEXPECTED_RECORD);
1831             return -1;
1832         }
1833     }
1834 }
1835
1836 void ssl3_record_sequence_update(unsigned char *seq)
1837 {
1838     int i;
1839
1840     for (i = 7; i >= 0; i--) {
1841         ++seq[i];
1842         if (seq[i] != 0)
1843             break;
1844     }
1845 }
1846
1847 /*
1848  * Returns true if the current rrec was sent in SSLv2 backwards compatible
1849  * format and false otherwise.
1850  */
1851 int RECORD_LAYER_is_sslv2_record(RECORD_LAYER *rl)
1852 {
1853     return SSL3_RECORD_is_sslv2_record(&rl->rrec[0]);
1854 }
1855
1856 /*
1857  * Returns the length in bytes of the current rrec
1858  */
1859 size_t RECORD_LAYER_get_rrec_length(RECORD_LAYER *rl)
1860 {
1861     return SSL3_RECORD_get_length(&rl->rrec[0]);
1862 }