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