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