Start using the provider side TLS HMAC implementation
[openssl.git] / ssl / record / ssl3_record.c
1 /*
2  * Copyright 1995-2020 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 "../ssl_local.h"
11 #include <openssl/trace.h>
12 #include <openssl/rand.h>
13 #include <openssl/core_names.h>
14 #include "record_local.h"
15 #include "internal/cryptlib.h"
16
17 static const unsigned char ssl3_pad_1[48] = {
18     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
19     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
20     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
21     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
22     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36,
23     0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36, 0x36
24 };
25
26 static const unsigned char ssl3_pad_2[48] = {
27     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
28     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
29     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
30     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
31     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c,
32     0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c, 0x5c
33 };
34
35 /*
36  * Clear the contents of an SSL3_RECORD but retain any memory allocated
37  */
38 void SSL3_RECORD_clear(SSL3_RECORD *r, size_t num_recs)
39 {
40     unsigned char *comp;
41     size_t i;
42
43     for (i = 0; i < num_recs; i++) {
44         comp = r[i].comp;
45
46         memset(&r[i], 0, sizeof(*r));
47         r[i].comp = comp;
48     }
49 }
50
51 void SSL3_RECORD_release(SSL3_RECORD *r, size_t num_recs)
52 {
53     size_t i;
54
55     for (i = 0; i < num_recs; i++) {
56         OPENSSL_free(r[i].comp);
57         r[i].comp = NULL;
58     }
59 }
60
61 void SSL3_RECORD_set_seq_num(SSL3_RECORD *r, const unsigned char *seq_num)
62 {
63     memcpy(r->seq_num, seq_num, SEQ_NUM_SIZE);
64 }
65
66 /*
67  * Peeks ahead into "read_ahead" data to see if we have a whole record waiting
68  * for us in the buffer.
69  */
70 static int ssl3_record_app_data_waiting(SSL *s)
71 {
72     SSL3_BUFFER *rbuf;
73     size_t left, len;
74     unsigned char *p;
75
76     rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
77
78     p = SSL3_BUFFER_get_buf(rbuf);
79     if (p == NULL)
80         return 0;
81
82     left = SSL3_BUFFER_get_left(rbuf);
83
84     if (left < SSL3_RT_HEADER_LENGTH)
85         return 0;
86
87     p += SSL3_BUFFER_get_offset(rbuf);
88
89     /*
90      * We only check the type and record length, we will sanity check version
91      * etc later
92      */
93     if (*p != SSL3_RT_APPLICATION_DATA)
94         return 0;
95
96     p += 3;
97     n2s(p, len);
98
99     if (left < SSL3_RT_HEADER_LENGTH + len)
100         return 0;
101
102     return 1;
103 }
104
105 int early_data_count_ok(SSL *s, size_t length, size_t overhead, int send)
106 {
107     uint32_t max_early_data;
108     SSL_SESSION *sess = s->session;
109
110     /*
111      * If we are a client then we always use the max_early_data from the
112      * session/psksession. Otherwise we go with the lowest out of the max early
113      * data set in the session and the configured max_early_data.
114      */
115     if (!s->server && sess->ext.max_early_data == 0) {
116         if (!ossl_assert(s->psksession != NULL
117                          && s->psksession->ext.max_early_data > 0)) {
118             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_EARLY_DATA_COUNT_OK,
119                      ERR_R_INTERNAL_ERROR);
120             return 0;
121         }
122         sess = s->psksession;
123     }
124
125     if (!s->server)
126         max_early_data = sess->ext.max_early_data;
127     else if (s->ext.early_data != SSL_EARLY_DATA_ACCEPTED)
128         max_early_data = s->recv_max_early_data;
129     else
130         max_early_data = s->recv_max_early_data < sess->ext.max_early_data
131                          ? s->recv_max_early_data : sess->ext.max_early_data;
132
133     if (max_early_data == 0) {
134         SSLfatal(s, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
135                  SSL_F_EARLY_DATA_COUNT_OK, SSL_R_TOO_MUCH_EARLY_DATA);
136         return 0;
137     }
138
139     /* If we are dealing with ciphertext we need to allow for the overhead */
140     max_early_data += overhead;
141
142     if (s->early_data_count + length > max_early_data) {
143         SSLfatal(s, send ? SSL_AD_INTERNAL_ERROR : SSL_AD_UNEXPECTED_MESSAGE,
144                  SSL_F_EARLY_DATA_COUNT_OK, SSL_R_TOO_MUCH_EARLY_DATA);
145         return 0;
146     }
147     s->early_data_count += length;
148
149     return 1;
150 }
151
152 /*
153  * MAX_EMPTY_RECORDS defines the number of consecutive, empty records that
154  * will be processed per call to ssl3_get_record. Without this limit an
155  * attacker could send empty records at a faster rate than we can process and
156  * cause ssl3_get_record to loop forever.
157  */
158 #define MAX_EMPTY_RECORDS 32
159
160 #define SSL2_RT_HEADER_LENGTH   2
161 /*-
162  * Call this to get new input records.
163  * It will return <= 0 if more data is needed, normally due to an error
164  * or non-blocking IO.
165  * When it finishes, |numrpipes| records have been decoded. For each record 'i':
166  * rr[i].type    - is the type of record
167  * rr[i].data,   - data
168  * rr[i].length, - number of bytes
169  * Multiple records will only be returned if the record types are all
170  * SSL3_RT_APPLICATION_DATA. The number of records returned will always be <=
171  * |max_pipelines|
172  */
173 /* used only by ssl3_read_bytes */
174 int ssl3_get_record(SSL *s)
175 {
176     int enc_err, rret;
177     int i;
178     size_t more, n;
179     SSL3_RECORD *rr, *thisrr;
180     SSL3_BUFFER *rbuf;
181     SSL_SESSION *sess;
182     unsigned char *p;
183     unsigned char md[EVP_MAX_MD_SIZE];
184     unsigned int version;
185     size_t mac_size = 0;
186     int imac_size;
187     size_t num_recs = 0, max_recs, j;
188     PACKET pkt, sslv2pkt;
189     int is_ktls_left;
190     SSL_MAC_BUF *macbufs = NULL;
191     int ret = -1;
192
193     rr = RECORD_LAYER_get_rrec(&s->rlayer);
194     rbuf = RECORD_LAYER_get_rbuf(&s->rlayer);
195     is_ktls_left = (rbuf->left > 0);
196     max_recs = s->max_pipelines;
197     if (max_recs == 0)
198         max_recs = 1;
199     sess = s->session;
200
201     do {
202         thisrr = &rr[num_recs];
203
204         /* check if we have the header */
205         if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
206             (RECORD_LAYER_get_packet_length(&s->rlayer)
207              < SSL3_RT_HEADER_LENGTH)) {
208             size_t sslv2len;
209             unsigned int type;
210
211             rret = ssl3_read_n(s, SSL3_RT_HEADER_LENGTH,
212                                SSL3_BUFFER_get_len(rbuf), 0,
213                                num_recs == 0 ? 1 : 0, &n);
214             if (rret <= 0) {
215 #ifndef OPENSSL_NO_KTLS
216                 if (!BIO_get_ktls_recv(s->rbio) || rret == 0)
217                     return rret;     /* error or non-blocking */
218                 switch (errno) {
219                 case EBADMSG:
220                     SSLfatal(s, SSL_AD_BAD_RECORD_MAC,
221                              SSL_F_SSL3_GET_RECORD,
222                              SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
223                     break;
224                 case EMSGSIZE:
225                     SSLfatal(s, SSL_AD_RECORD_OVERFLOW,
226                              SSL_F_SSL3_GET_RECORD,
227                              SSL_R_PACKET_LENGTH_TOO_LONG);
228                     break;
229                 case EINVAL:
230                     SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
231                              SSL_F_SSL3_GET_RECORD,
232                              SSL_R_WRONG_VERSION_NUMBER);
233                     break;
234                 default:
235                     break;
236                 }
237 #endif
238                 return rret;
239             }
240             RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
241
242             p = RECORD_LAYER_get_packet(&s->rlayer);
243             if (!PACKET_buf_init(&pkt, RECORD_LAYER_get_packet(&s->rlayer),
244                                  RECORD_LAYER_get_packet_length(&s->rlayer))) {
245                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_GET_RECORD,
246                          ERR_R_INTERNAL_ERROR);
247                 return -1;
248             }
249             sslv2pkt = pkt;
250             if (!PACKET_get_net_2_len(&sslv2pkt, &sslv2len)
251                     || !PACKET_get_1(&sslv2pkt, &type)) {
252                 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL3_GET_RECORD,
253                          ERR_R_INTERNAL_ERROR);
254                 return -1;
255             }
256             /*
257              * The first record received by the server may be a V2ClientHello.
258              */
259             if (s->server && RECORD_LAYER_is_first_record(&s->rlayer)
260                     && (sslv2len & 0x8000) != 0
261                     && (type == SSL2_MT_CLIENT_HELLO)) {
262                 /*
263                  *  SSLv2 style record
264                  *
265                  * |num_recs| here will actually always be 0 because
266                  * |num_recs > 0| only ever occurs when we are processing
267                  * multiple app data records - which we know isn't the case here
268                  * because it is an SSLv2ClientHello. We keep it using
269                  * |num_recs| for the sake of consistency
270                  */
271                 thisrr->type = SSL3_RT_HANDSHAKE;
272                 thisrr->rec_version = SSL2_VERSION;
273
274                 thisrr->length = sslv2len & 0x7fff;
275
276                 if (thisrr->length > SSL3_BUFFER_get_len(rbuf)
277                     - SSL2_RT_HEADER_LENGTH) {
278                     SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
279                              SSL_R_PACKET_LENGTH_TOO_LONG);
280                     return -1;
281                 }
282
283                 if (thisrr->length < MIN_SSL2_RECORD_LEN) {
284                     SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL3_GET_RECORD,
285                              SSL_R_LENGTH_TOO_SHORT);
286                     return -1;
287                 }
288             } else {
289                 /* SSLv3+ style record */
290
291                 /* Pull apart the header into the SSL3_RECORD */
292                 if (!PACKET_get_1(&pkt, &type)
293                         || !PACKET_get_net_2(&pkt, &version)
294                         || !PACKET_get_net_2_len(&pkt, &thisrr->length)) {
295                     if (s->msg_callback)
296                         s->msg_callback(0, 0, SSL3_RT_HEADER, p, 5, s,
297                                         s->msg_callback_arg);
298                     SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL3_GET_RECORD,
299                              ERR_R_INTERNAL_ERROR);
300                     return -1;
301                 }
302                 thisrr->type = type;
303                 thisrr->rec_version = version;
304
305                 if (s->msg_callback)
306                     s->msg_callback(0, version, SSL3_RT_HEADER, p, 5, s,
307                                     s->msg_callback_arg);
308
309                 /*
310                  * Lets check version. In TLSv1.3 we only check this field
311                  * when encryption is occurring (see later check). For the
312                  * ServerHello after an HRR we haven't actually selected TLSv1.3
313                  * yet, but we still treat it as TLSv1.3, so we must check for
314                  * that explicitly
315                  */
316                 if (!s->first_packet && !SSL_IS_TLS13(s)
317                         && s->hello_retry_request != SSL_HRR_PENDING
318                         && version != (unsigned int)s->version) {
319                     if ((s->version & 0xFF00) == (version & 0xFF00)
320                         && !s->enc_write_ctx && !s->write_hash) {
321                         if (thisrr->type == SSL3_RT_ALERT) {
322                             /*
323                              * The record is using an incorrect version number,
324                              * but what we've got appears to be an alert. We
325                              * haven't read the body yet to check whether its a
326                              * fatal or not - but chances are it is. We probably
327                              * shouldn't send a fatal alert back. We'll just
328                              * end.
329                              */
330                             SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_SSL3_GET_RECORD,
331                                      SSL_R_WRONG_VERSION_NUMBER);
332                             return -1;
333                         }
334                         /*
335                          * Send back error using their minor version number :-)
336                          */
337                         s->version = (unsigned short)version;
338                     }
339                     SSLfatal(s, SSL_AD_PROTOCOL_VERSION, SSL_F_SSL3_GET_RECORD,
340                              SSL_R_WRONG_VERSION_NUMBER);
341                     return -1;
342                 }
343
344                 if ((version >> 8) != SSL3_VERSION_MAJOR) {
345                     if (RECORD_LAYER_is_first_record(&s->rlayer)) {
346                         /* Go back to start of packet, look at the five bytes
347                          * that we have. */
348                         p = RECORD_LAYER_get_packet(&s->rlayer);
349                         if (strncmp((char *)p, "GET ", 4) == 0 ||
350                             strncmp((char *)p, "POST ", 5) == 0 ||
351                             strncmp((char *)p, "HEAD ", 5) == 0 ||
352                             strncmp((char *)p, "PUT ", 4) == 0) {
353                             SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_SSL3_GET_RECORD,
354                                      SSL_R_HTTP_REQUEST);
355                             return -1;
356                         } else if (strncmp((char *)p, "CONNE", 5) == 0) {
357                             SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_SSL3_GET_RECORD,
358                                      SSL_R_HTTPS_PROXY_REQUEST);
359                             return -1;
360                         }
361
362                         /* Doesn't look like TLS - don't send an alert */
363                         SSLfatal(s, SSL_AD_NO_ALERT, SSL_F_SSL3_GET_RECORD,
364                                  SSL_R_WRONG_VERSION_NUMBER);
365                         return -1;
366                     } else {
367                         SSLfatal(s, SSL_AD_PROTOCOL_VERSION,
368                                  SSL_F_SSL3_GET_RECORD,
369                                  SSL_R_WRONG_VERSION_NUMBER);
370                         return -1;
371                     }
372                 }
373
374                 if (SSL_IS_TLS13(s) && s->enc_read_ctx != NULL) {
375                     if (thisrr->type != SSL3_RT_APPLICATION_DATA
376                             && (thisrr->type != SSL3_RT_CHANGE_CIPHER_SPEC
377                                 || !SSL_IS_FIRST_HANDSHAKE(s))
378                             && (thisrr->type != SSL3_RT_ALERT
379                                 || s->statem.enc_read_state
380                                    != ENC_READ_STATE_ALLOW_PLAIN_ALERTS)) {
381                         SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE,
382                                  SSL_F_SSL3_GET_RECORD, SSL_R_BAD_RECORD_TYPE);
383                         return -1;
384                     }
385                     if (thisrr->rec_version != TLS1_2_VERSION) {
386                         SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL3_GET_RECORD,
387                                  SSL_R_WRONG_VERSION_NUMBER);
388                         return -1;
389                     }
390                 }
391
392                 if (thisrr->length >
393                     SSL3_BUFFER_get_len(rbuf) - SSL3_RT_HEADER_LENGTH) {
394                     SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
395                              SSL_R_PACKET_LENGTH_TOO_LONG);
396                     return -1;
397                 }
398             }
399
400             /* now s->rlayer.rstate == SSL_ST_READ_BODY */
401         }
402
403         if (SSL_IS_TLS13(s)) {
404             if (thisrr->length > SSL3_RT_MAX_TLS13_ENCRYPTED_LENGTH) {
405                 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
406                          SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
407                 return -1;
408             }
409         } else {
410             size_t len = SSL3_RT_MAX_ENCRYPTED_LENGTH;
411
412 #ifndef OPENSSL_NO_COMP
413             /*
414              * If OPENSSL_NO_COMP is defined then SSL3_RT_MAX_ENCRYPTED_LENGTH
415              * does not include the compression overhead anyway.
416              */
417             if (s->expand == NULL)
418                 len -= SSL3_RT_MAX_COMPRESSED_OVERHEAD;
419 #endif
420
421             if (thisrr->length > len && !BIO_get_ktls_recv(s->rbio)) {
422                 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
423                          SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
424                 return -1;
425             }
426         }
427
428         /*
429          * s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data.
430          * Calculate how much more data we need to read for the rest of the
431          * record
432          */
433         if (thisrr->rec_version == SSL2_VERSION) {
434             more = thisrr->length + SSL2_RT_HEADER_LENGTH
435                 - SSL3_RT_HEADER_LENGTH;
436         } else {
437             more = thisrr->length;
438         }
439
440         if (more > 0) {
441             /* now s->packet_length == SSL3_RT_HEADER_LENGTH */
442
443             rret = ssl3_read_n(s, more, more, 1, 0, &n);
444             if (rret <= 0)
445                 return rret;     /* error or non-blocking io */
446         }
447
448         /* set state for later operations */
449         RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
450
451         /*
452          * At this point, s->packet_length == SSL3_RT_HEADER_LENGTH
453          * + thisrr->length, or s->packet_length == SSL2_RT_HEADER_LENGTH
454          * + thisrr->length and we have that many bytes in s->packet
455          */
456         if (thisrr->rec_version == SSL2_VERSION) {
457             thisrr->input =
458                 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL2_RT_HEADER_LENGTH]);
459         } else {
460             thisrr->input =
461                 &(RECORD_LAYER_get_packet(&s->rlayer)[SSL3_RT_HEADER_LENGTH]);
462         }
463
464         /*
465          * ok, we can now read from 's->packet' data into 'thisrr' thisrr->input
466          * points at thisrr->length bytes, which need to be copied into
467          * thisrr->data by either the decryption or by the decompression When
468          * the data is 'copied' into the thisrr->data buffer, thisrr->input will
469          * be pointed at the new buffer
470          */
471
472         /*
473          * We now have - encrypted [ MAC [ compressed [ plain ] ] ]
474          * thisrr->length bytes of encrypted compressed stuff.
475          */
476
477         /* decrypt in place in 'thisrr->input' */
478         thisrr->data = thisrr->input;
479         thisrr->orig_len = thisrr->length;
480
481         /* Mark this record as not read by upper layers yet */
482         thisrr->read = 0;
483
484         num_recs++;
485
486         /* we have pulled in a full packet so zero things */
487         RECORD_LAYER_reset_packet_length(&s->rlayer);
488         RECORD_LAYER_clear_first_record(&s->rlayer);
489     } while (num_recs < max_recs
490              && thisrr->type == SSL3_RT_APPLICATION_DATA
491              && SSL_USE_EXPLICIT_IV(s)
492              && s->enc_read_ctx != NULL
493              && (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx))
494                  & EVP_CIPH_FLAG_PIPELINE)
495              && ssl3_record_app_data_waiting(s));
496
497     if (num_recs == 1
498             && thisrr->type == SSL3_RT_CHANGE_CIPHER_SPEC
499             && (SSL_IS_TLS13(s) || s->hello_retry_request != SSL_HRR_NONE)
500             && SSL_IS_FIRST_HANDSHAKE(s)) {
501         /*
502          * CCS messages must be exactly 1 byte long, containing the value 0x01
503          */
504         if (thisrr->length != 1 || thisrr->data[0] != 0x01) {
505             SSLfatal(s, SSL_AD_ILLEGAL_PARAMETER, SSL_F_SSL3_GET_RECORD,
506                      SSL_R_INVALID_CCS_MESSAGE);
507             return -1;
508         }
509         /*
510          * CCS messages are ignored in TLSv1.3. We treat it like an empty
511          * handshake record
512          */
513         thisrr->type = SSL3_RT_HANDSHAKE;
514         RECORD_LAYER_inc_empty_record_count(&s->rlayer);
515         if (RECORD_LAYER_get_empty_record_count(&s->rlayer)
516             > MAX_EMPTY_RECORDS) {
517             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_GET_RECORD,
518                      SSL_R_UNEXPECTED_CCS_MESSAGE);
519             return -1;
520         }
521         thisrr->read = 1;
522         RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
523
524         return 1;
525     }
526
527     /*
528      * KTLS reads full records. If there is any data left,
529      * then it is from before enabling ktls
530      */
531     if (BIO_get_ktls_recv(s->rbio) && !is_ktls_left)
532         goto skip_decryption;
533
534     /* TODO(size_t): convert this to do size_t properly */
535     if (s->read_hash != NULL) {
536         const EVP_MD *tmpmd = EVP_MD_CTX_md(s->read_hash);
537
538         if (tmpmd != NULL) {
539             imac_size = EVP_MD_size(tmpmd);
540             if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
541                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_GET_RECORD,
542                              ERR_LIB_EVP);
543                     return -1;
544             }
545             mac_size = (size_t)imac_size;
546         }
547     }
548
549     /*
550      * If in encrypt-then-mac mode calculate mac from encrypted record. All
551      * the details below are public so no timing details can leak.
552      */
553     if (SSL_READ_ETM(s) && s->read_hash) {
554         unsigned char *mac;
555
556         for (j = 0; j < num_recs; j++) {
557             thisrr = &rr[j];
558
559             if (thisrr->length < mac_size) {
560                 SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_SSL3_GET_RECORD,
561                          SSL_R_LENGTH_TOO_SHORT);
562                 return -1;
563             }
564             thisrr->length -= mac_size;
565             mac = thisrr->data + thisrr->length;
566             i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
567             if (i == 0 || CRYPTO_memcmp(md, mac, mac_size) != 0) {
568                 SSLfatal(s, SSL_AD_BAD_RECORD_MAC, SSL_F_SSL3_GET_RECORD,
569                        SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
570                 return -1;
571             }
572         }
573         /*
574          * We've handled the mac now - there is no MAC inside the encrypted
575          * record
576          */
577         mac_size = 0;
578     }
579
580     if (mac_size > 0) {
581         macbufs = OPENSSL_zalloc(sizeof(*macbufs) * num_recs);
582         if (macbufs == NULL) {
583             SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_GET_RECORD,
584                      ERR_R_MALLOC_FAILURE);
585             return -1;
586         }
587     }
588
589     enc_err = s->method->ssl3_enc->enc(s, rr, num_recs, 0, macbufs, mac_size);
590
591     /*-
592      * enc_err is:
593      *    0: if the record is publicly invalid, or an internal error, or AEAD
594      *       decryption failed, or ETM decryption failed.
595      *    1: Success or MTE decryption failed (MAC will be randomised)
596      */
597     if (enc_err == 0) {
598         if (ossl_statem_in_error(s)) {
599             /* SSLfatal() already got called */
600             goto end;
601         }
602         if (num_recs == 1 && ossl_statem_skip_early_data(s)) {
603             /*
604              * Valid early_data that we cannot decrypt will fail here. We treat
605              * it like an empty record.
606              */
607
608             thisrr = &rr[0];
609
610             if (!early_data_count_ok(s, thisrr->length,
611                                      EARLY_DATA_CIPHERTEXT_OVERHEAD, 0)) {
612                 /* SSLfatal() already called */
613                 goto end;
614             }
615
616             thisrr->length = 0;
617             thisrr->read = 1;
618             RECORD_LAYER_set_numrpipes(&s->rlayer, 1);
619             RECORD_LAYER_reset_read_sequence(&s->rlayer);
620             ret = 1;
621             goto end;
622         }
623         SSLfatal(s, SSL_AD_BAD_RECORD_MAC, SSL_F_SSL3_GET_RECORD,
624                  SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
625         goto end;
626     }
627     OSSL_TRACE_BEGIN(TLS) {
628         BIO_printf(trc_out, "dec %lu\n", (unsigned long)rr[0].length);
629         BIO_dump_indent(trc_out, rr[0].data, rr[0].length, 4);
630     } OSSL_TRACE_END(TLS);
631
632     /* r->length is now the compressed data plus mac */
633     if ((sess != NULL) &&
634         (s->enc_read_ctx != NULL) &&
635         (!SSL_READ_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)) {
636         /* s->read_hash != NULL => mac_size != -1 */
637
638         for (j = 0; j < num_recs; j++) {
639             SSL_MAC_BUF *thismb = &macbufs[j];
640             thisrr = &rr[j];
641
642             i = s->method->ssl3_enc->mac(s, thisrr, md, 0 /* not send */ );
643             if (i == 0 || thismb == NULL || thismb->mac == NULL
644                 || CRYPTO_memcmp(md, thismb->mac, (size_t)mac_size) != 0)
645                 enc_err = 0;
646             if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
647                 enc_err = 0;
648         }
649     }
650
651     if (enc_err == 0) {
652         if (ossl_statem_in_error(s)) {
653             /* We already called SSLfatal() */
654             goto end;
655         }
656         /*
657          * A separate 'decryption_failed' alert was introduced with TLS 1.0,
658          * SSL 3.0 only has 'bad_record_mac'.  But unless a decryption
659          * failure is directly visible from the ciphertext anyway, we should
660          * not reveal which kind of error occurred -- this might become
661          * visible to an attacker (e.g. via a logfile)
662          */
663         SSLfatal(s, SSL_AD_BAD_RECORD_MAC, SSL_F_SSL3_GET_RECORD,
664                  SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
665         goto end;
666     }
667
668  skip_decryption:
669
670     for (j = 0; j < num_recs; j++) {
671         thisrr = &rr[j];
672
673         /* thisrr->length is now just compressed */
674         if (s->expand != NULL) {
675             if (thisrr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
676                 SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
677                          SSL_R_COMPRESSED_LENGTH_TOO_LONG);
678                 goto end;
679             }
680             if (!ssl3_do_uncompress(s, thisrr)) {
681                 SSLfatal(s, SSL_AD_DECOMPRESSION_FAILURE, SSL_F_SSL3_GET_RECORD,
682                          SSL_R_BAD_DECOMPRESSION);
683                 goto end;
684             }
685         }
686
687         if (SSL_IS_TLS13(s)
688                 && s->enc_read_ctx != NULL
689                 && thisrr->type != SSL3_RT_ALERT) {
690             size_t end;
691
692             if (thisrr->length == 0
693                     || thisrr->type != SSL3_RT_APPLICATION_DATA) {
694                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_GET_RECORD,
695                          SSL_R_BAD_RECORD_TYPE);
696                 goto end;
697             }
698
699             /* Strip trailing padding */
700             for (end = thisrr->length - 1; end > 0 && thisrr->data[end] == 0;
701                  end--)
702                 continue;
703
704             thisrr->length = end;
705             thisrr->type = thisrr->data[end];
706             if (thisrr->type != SSL3_RT_APPLICATION_DATA
707                     && thisrr->type != SSL3_RT_ALERT
708                     && thisrr->type != SSL3_RT_HANDSHAKE) {
709                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_GET_RECORD,
710                          SSL_R_BAD_RECORD_TYPE);
711                 goto end;
712             }
713             if (s->msg_callback)
714                 s->msg_callback(0, s->version, SSL3_RT_INNER_CONTENT_TYPE,
715                                 &thisrr->data[end], 1, s, s->msg_callback_arg);
716         }
717
718         /*
719          * TLSv1.3 alert and handshake records are required to be non-zero in
720          * length.
721          */
722         if (SSL_IS_TLS13(s)
723                 && (thisrr->type == SSL3_RT_HANDSHAKE
724                     || thisrr->type == SSL3_RT_ALERT)
725                 && thisrr->length == 0) {
726             SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_GET_RECORD,
727                      SSL_R_BAD_LENGTH);
728             goto end;
729         }
730
731         if (thisrr->length > SSL3_RT_MAX_PLAIN_LENGTH && !BIO_get_ktls_recv(s->rbio)) {
732             SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
733                      SSL_R_DATA_LENGTH_TOO_LONG);
734             goto end;
735         }
736
737         /* If received packet overflows current Max Fragment Length setting */
738         if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session)
739                 && thisrr->length > GET_MAX_FRAGMENT_LENGTH(s->session)
740                 && !BIO_get_ktls_recv(s->rbio)) {
741             SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_SSL3_GET_RECORD,
742                      SSL_R_DATA_LENGTH_TOO_LONG);
743             goto end;
744         }
745
746         thisrr->off = 0;
747         /*-
748          * So at this point the following is true
749          * thisrr->type   is the type of record
750          * thisrr->length == number of bytes in record
751          * thisrr->off    == offset to first valid byte
752          * thisrr->data   == where to take bytes from, increment after use :-).
753          */
754
755         /* just read a 0 length packet */
756         if (thisrr->length == 0) {
757             RECORD_LAYER_inc_empty_record_count(&s->rlayer);
758             if (RECORD_LAYER_get_empty_record_count(&s->rlayer)
759                 > MAX_EMPTY_RECORDS) {
760                 SSLfatal(s, SSL_AD_UNEXPECTED_MESSAGE, SSL_F_SSL3_GET_RECORD,
761                          SSL_R_RECORD_TOO_SMALL);
762                 goto end;
763             }
764         } else {
765             RECORD_LAYER_reset_empty_record_count(&s->rlayer);
766         }
767     }
768
769     if (s->early_data_state == SSL_EARLY_DATA_READING) {
770         thisrr = &rr[0];
771         if (thisrr->type == SSL3_RT_APPLICATION_DATA
772                 && !early_data_count_ok(s, thisrr->length, 0, 0)) {
773             /* SSLfatal already called */
774             goto end;
775         }
776     }
777
778     RECORD_LAYER_set_numrpipes(&s->rlayer, num_recs);
779     ret = 1;
780  end:
781     if (macbufs != NULL) {
782         for (j = 0; j < num_recs; j++) {
783             if (macbufs[j].alloced)
784                 OPENSSL_free(macbufs[j].mac);
785         }
786         OPENSSL_free(macbufs);
787     }
788     return ret;
789 }
790
791 int ssl3_do_uncompress(SSL *ssl, SSL3_RECORD *rr)
792 {
793 #ifndef OPENSSL_NO_COMP
794     int i;
795
796     if (rr->comp == NULL) {
797         rr->comp = (unsigned char *)
798             OPENSSL_malloc(SSL3_RT_MAX_ENCRYPTED_LENGTH);
799     }
800     if (rr->comp == NULL)
801         return 0;
802
803     /* TODO(size_t): Convert this call */
804     i = COMP_expand_block(ssl->expand, rr->comp,
805                           SSL3_RT_MAX_PLAIN_LENGTH, rr->data, (int)rr->length);
806     if (i < 0)
807         return 0;
808     else
809         rr->length = i;
810     rr->data = rr->comp;
811 #endif
812     return 1;
813 }
814
815 int ssl3_do_compress(SSL *ssl, SSL3_RECORD *wr)
816 {
817 #ifndef OPENSSL_NO_COMP
818     int i;
819
820     /* TODO(size_t): Convert this call */
821     i = COMP_compress_block(ssl->compress, wr->data,
822                             (int)(wr->length + SSL3_RT_MAX_COMPRESSED_OVERHEAD),
823                             wr->input, (int)wr->length);
824     if (i < 0)
825         return 0;
826     else
827         wr->length = i;
828
829     wr->input = wr->data;
830 #endif
831     return 1;
832 }
833
834 /*-
835  * ssl3_enc encrypts/decrypts |n_recs| records in |inrecs|. Calls SSLfatal on
836  * internal error, but not otherwise. It is the responsibility of the caller to
837  * report a bad_record_mac
838  *
839  * Returns:
840  *    0: if the record is publicly invalid, or an internal error
841  *    1: Success or Mac-then-encrypt decryption failed (MAC will be randomised)
842  */
843 int ssl3_enc(SSL *s, SSL3_RECORD *inrecs, size_t n_recs, int sending,
844              SSL_MAC_BUF *mac, size_t macsize)
845 {
846     SSL3_RECORD *rec;
847     EVP_CIPHER_CTX *ds;
848     size_t l, i;
849     size_t bs;
850     const EVP_CIPHER *enc;
851
852     rec = inrecs;
853     /*
854      * We shouldn't ever be called with more than one record in the SSLv3 case
855      */
856     if (n_recs != 1)
857         return 0;
858     if (sending) {
859         ds = s->enc_write_ctx;
860         if (s->enc_write_ctx == NULL)
861             enc = NULL;
862         else
863             enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
864     } else {
865         ds = s->enc_read_ctx;
866         if (s->enc_read_ctx == NULL)
867             enc = NULL;
868         else
869             enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
870     }
871
872     if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
873         memmove(rec->data, rec->input, rec->length);
874         rec->input = rec->data;
875     } else {
876         int provided = (EVP_CIPHER_provider(enc) != NULL);
877
878         l = rec->length;
879         /* TODO(size_t): Convert this call */
880         bs = EVP_CIPHER_CTX_block_size(ds);
881
882         /* COMPRESS */
883
884         if ((bs != 1) && sending && !provided) {
885             /*
886              * We only do this for legacy ciphers. Provided ciphers add the
887              * padding on the provider side.
888              */
889             i = bs - (l % bs);
890
891             /* we need to add 'i-1' padding bytes */
892             l += i;
893             /*
894              * the last of these zero bytes will be overwritten with the
895              * padding length.
896              */
897             memset(&rec->input[rec->length], 0, i);
898             rec->length += i;
899             rec->input[l - 1] = (unsigned char)(i - 1);
900         }
901
902         if (!sending) {
903             if (l == 0 || l % bs != 0) {
904                 /* Publicly invalid */
905                 return 0;
906             }
907             /* otherwise, rec->length >= bs */
908         }
909
910         if (EVP_CIPHER_provider(enc) != NULL) {
911             int outlen;
912
913             if (!EVP_CipherUpdate(ds, rec->data, &outlen, rec->input,
914                                   (unsigned int)l))
915                 return 0;
916             rec->length = outlen;
917
918             if (!sending && mac != NULL) {
919                 /* Now get a pointer to the MAC */
920                 OSSL_PARAM params[2], *p = params;
921
922                 /* Get the MAC */
923                 mac->alloced = 0;
924
925                 *p++ = OSSL_PARAM_construct_octet_ptr(OSSL_CIPHER_PARAM_TLS_MAC,
926                                                       (void **)&mac->mac,
927                                                       macsize);
928                 *p = OSSL_PARAM_construct_end();
929
930                 if (!EVP_CIPHER_CTX_get_params(ds, params)) {
931                     /* Shouldn't normally happen */
932                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, 0,
933                              ERR_R_INTERNAL_ERROR);
934                     return 0;
935                 }
936             }
937         } else {
938             /* TODO(size_t): Convert this call */
939             if (EVP_Cipher(ds, rec->data, rec->input, (unsigned int)l) < 1) {
940                 /* Shouldn't happen */
941                 SSLfatal(s, SSL_AD_BAD_RECORD_MAC, 0, ERR_R_INTERNAL_ERROR);
942                 return 0;
943             }
944
945             if (!sending)
946                 return ssl3_cbc_remove_padding_and_mac(&rec->length,
947                                            rec->orig_len,
948                                            rec->data,
949                                            (mac != NULL) ? &mac->mac : NULL,
950                                            (mac != NULL) ? &mac->alloced : NULL,
951                                            bs,
952                                            macsize,
953                                            s->ctx->libctx);
954         }
955     }
956     return 1;
957 }
958
959 #define MAX_PADDING 256
960 /*-
961  * tls1_enc encrypts/decrypts |n_recs| in |recs|. Calls SSLfatal on internal
962  * error, but not otherwise. It is the responsibility of the caller to report
963  * a bad_record_mac - if appropriate (DTLS just drops the record).
964  *
965  * Returns:
966  *    0: if the record is publicly invalid, or an internal error, or AEAD
967  *       decryption failed, or Encrypt-then-mac decryption failed.
968  *    1: Success or Mac-then-encrypt decryption failed (MAC will be randomised)
969  */
970 int tls1_enc(SSL *s, SSL3_RECORD *recs, size_t n_recs, int sending,
971              SSL_MAC_BUF *macs, size_t macsize)
972 {
973     EVP_CIPHER_CTX *ds;
974     size_t reclen[SSL_MAX_PIPELINES];
975     unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
976     int i, pad = 0, tmpr;
977     size_t bs, ctr, padnum, loop;
978     unsigned char padval;
979     const EVP_CIPHER *enc;
980     int tlstree_enc = sending ? (s->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE)
981                               : (s->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE);
982
983     if (n_recs == 0) {
984         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
985                  ERR_R_INTERNAL_ERROR);
986         return 0;
987     }
988
989     if (sending) {
990         if (EVP_MD_CTX_md(s->write_hash)) {
991             int n = EVP_MD_CTX_size(s->write_hash);
992             if (!ossl_assert(n >= 0)) {
993                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
994                          ERR_R_INTERNAL_ERROR);
995                 return 0;
996             }
997         }
998         ds = s->enc_write_ctx;
999         if (s->enc_write_ctx == NULL)
1000             enc = NULL;
1001         else {
1002             int ivlen;
1003             enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
1004             /* For TLSv1.1 and later explicit IV */
1005             if (SSL_USE_EXPLICIT_IV(s)
1006                 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
1007                 ivlen = EVP_CIPHER_iv_length(enc);
1008             else
1009                 ivlen = 0;
1010             if (ivlen > 1) {
1011                 for (ctr = 0; ctr < n_recs; ctr++) {
1012                     if (recs[ctr].data != recs[ctr].input) {
1013                         /*
1014                          * we can't write into the input stream: Can this ever
1015                          * happen?? (steve)
1016                          */
1017                         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1018                                  ERR_R_INTERNAL_ERROR);
1019                         return 0;
1020                     } else if (RAND_bytes_ex(s->ctx->libctx, recs[ctr].input,
1021                                              ivlen) <= 0) {
1022                         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1023                                  ERR_R_INTERNAL_ERROR);
1024                         return 0;
1025                     }
1026                 }
1027             }
1028         }
1029     } else {
1030         if (EVP_MD_CTX_md(s->read_hash)) {
1031             int n = EVP_MD_CTX_size(s->read_hash);
1032             if (!ossl_assert(n >= 0)) {
1033                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1034                          ERR_R_INTERNAL_ERROR);
1035                 return 0;
1036             }
1037         }
1038         ds = s->enc_read_ctx;
1039         if (s->enc_read_ctx == NULL)
1040             enc = NULL;
1041         else
1042             enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
1043     }
1044
1045     if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
1046         for (ctr = 0; ctr < n_recs; ctr++) {
1047             memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
1048             recs[ctr].input = recs[ctr].data;
1049         }
1050     } else {
1051         int provided = (EVP_CIPHER_provider(enc) != NULL);
1052
1053         bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
1054
1055         if (n_recs > 1) {
1056             if (!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
1057                   & EVP_CIPH_FLAG_PIPELINE)) {
1058                 /*
1059                  * We shouldn't have been called with pipeline data if the
1060                  * cipher doesn't support pipelining
1061                  */
1062                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1063                          SSL_R_PIPELINE_FAILURE);
1064                 return 0;
1065             }
1066         }
1067         for (ctr = 0; ctr < n_recs; ctr++) {
1068             reclen[ctr] = recs[ctr].length;
1069
1070             if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
1071                 & EVP_CIPH_FLAG_AEAD_CIPHER) {
1072                 unsigned char *seq;
1073
1074                 seq = sending ? RECORD_LAYER_get_write_sequence(&s->rlayer)
1075                     : RECORD_LAYER_get_read_sequence(&s->rlayer);
1076
1077                 if (SSL_IS_DTLS(s)) {
1078                     /* DTLS does not support pipelining */
1079                     unsigned char dtlsseq[9], *p = dtlsseq;
1080
1081                     s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
1082                         DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
1083                     memcpy(p, &seq[2], 6);
1084                     memcpy(buf[ctr], dtlsseq, 8);
1085                 } else {
1086                     memcpy(buf[ctr], seq, 8);
1087                     for (i = 7; i >= 0; i--) { /* increment */
1088                         ++seq[i];
1089                         if (seq[i] != 0)
1090                             break;
1091                     }
1092                 }
1093
1094                 buf[ctr][8] = recs[ctr].type;
1095                 buf[ctr][9] = (unsigned char)(s->version >> 8);
1096                 buf[ctr][10] = (unsigned char)(s->version);
1097                 buf[ctr][11] = (unsigned char)(recs[ctr].length >> 8);
1098                 buf[ctr][12] = (unsigned char)(recs[ctr].length & 0xff);
1099                 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
1100                                           EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
1101                 if (pad <= 0) {
1102                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1103                              ERR_R_INTERNAL_ERROR);
1104                     return 0;
1105                 }
1106
1107                 if (sending) {
1108                     reclen[ctr] += pad;
1109                     recs[ctr].length += pad;
1110                 }
1111
1112             } else if ((bs != 1) && sending && !provided) {
1113                 /*
1114                  * We only do this for legacy ciphers. Provided ciphers add the
1115                  * padding on the provider side.
1116                  */
1117                 padnum = bs - (reclen[ctr] % bs);
1118
1119                 /* Add weird padding of up to 256 bytes */
1120
1121                 if (padnum > MAX_PADDING) {
1122                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1123                              ERR_R_INTERNAL_ERROR);
1124                     return 0;
1125                 }
1126                 /* we need to add 'padnum' padding bytes of value padval */
1127                 padval = (unsigned char)(padnum - 1);
1128                 for (loop = reclen[ctr]; loop < reclen[ctr] + padnum; loop++)
1129                     recs[ctr].input[loop] = padval;
1130                 reclen[ctr] += padnum;
1131                 recs[ctr].length += padnum;
1132             }
1133
1134             if (!sending) {
1135                 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0) {
1136                     /* Publicly invalid */
1137                     return 0;
1138                 }
1139             }
1140         }
1141         if (n_recs > 1) {
1142             unsigned char *data[SSL_MAX_PIPELINES];
1143
1144             /* Set the output buffers */
1145             for (ctr = 0; ctr < n_recs; ctr++) {
1146                 data[ctr] = recs[ctr].data;
1147             }
1148             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
1149                                     (int)n_recs, data) <= 0) {
1150                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1151                          SSL_R_PIPELINE_FAILURE);
1152                 return 0;
1153             }
1154             /* Set the input buffers */
1155             for (ctr = 0; ctr < n_recs; ctr++) {
1156                 data[ctr] = recs[ctr].input;
1157             }
1158             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
1159                                     (int)n_recs, data) <= 0
1160                 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
1161                                        (int)n_recs, reclen) <= 0) {
1162                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1163                          SSL_R_PIPELINE_FAILURE);
1164                 return 0;
1165             }
1166         }
1167
1168         if (!SSL_IS_DTLS(s) && tlstree_enc) {
1169             unsigned char *seq;
1170             int decrement_seq = 0;
1171
1172             /*
1173              * When sending, seq is incremented after MAC calculation.
1174              * So if we are in ETM mode, we use seq 'as is' in the ctrl-function.
1175              * Otherwise we have to decrease it in the implementation
1176              */
1177             if (sending && !SSL_WRITE_ETM(s))
1178                 decrement_seq = 1;
1179
1180             seq = sending ? RECORD_LAYER_get_write_sequence(&s->rlayer)
1181                           : RECORD_LAYER_get_read_sequence(&s->rlayer);
1182             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_TLSTREE, decrement_seq, seq) <= 0) {
1183                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1184                          ERR_R_INTERNAL_ERROR);
1185                 return 0;
1186             }
1187         }
1188
1189         if (provided) {
1190             int outlen;
1191
1192             /* Provided cipher - we do not support pipelining on this path */
1193             if (n_recs > 1)  {
1194                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1195                          ERR_R_INTERNAL_ERROR);
1196                 return 0;
1197             }
1198
1199             if (!EVP_CipherUpdate(ds, recs[0].data, &outlen, recs[0].input,
1200                                   (unsigned int)reclen[0]))
1201                 return 0;
1202             recs[0].length = outlen;
1203
1204             /*
1205              * The length returned from EVP_CipherUpdate above is the actual
1206              * payload length. We need to adjust the data/input ptr to skip over
1207              * any explicit IV
1208              */
1209             if (!sending) {
1210                 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
1211                         recs[0].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1212                         recs[0].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1213                 } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
1214                         recs[0].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1215                         recs[0].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1216                 } else if (bs != 1 && SSL_USE_EXPLICIT_IV(s)) {
1217                     recs[0].data += bs;
1218                     recs[0].input += bs;
1219                     recs[0].orig_len -= bs;
1220                 }
1221
1222                 /* Now get a pointer to the MAC (if applicable) */
1223                 if (macs != NULL) {
1224                     OSSL_PARAM params[2], *p = params;
1225
1226                     /* Get the MAC */
1227                     macs[0].alloced = 0;
1228
1229                     *p++ = OSSL_PARAM_construct_octet_ptr(OSSL_CIPHER_PARAM_TLS_MAC,
1230                                                           (void **)&macs[0].mac,
1231                                                           macsize);
1232                     *p = OSSL_PARAM_construct_end();
1233
1234                     if (!EVP_CIPHER_CTX_get_params(ds, params)) {
1235                         /* Shouldn't normally happen */
1236                         SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_TLS1_ENC,
1237                                  ERR_R_INTERNAL_ERROR);
1238                         return 0;
1239                     }
1240                 }
1241             }
1242         } else {
1243             /* Legacy cipher */
1244
1245             /* TODO(size_t): Convert this call */
1246             tmpr = EVP_Cipher(ds, recs[0].data, recs[0].input,
1247                               (unsigned int)reclen[0]);
1248             if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
1249                  & EVP_CIPH_FLAG_CUSTOM_CIPHER)
1250                 ? (tmpr < 0)
1251                 : (tmpr == 0)) {
1252                 /* AEAD can fail to verify MAC */
1253                 return 0;
1254             }
1255
1256             if (!sending) {
1257                 /* Adjust the record to remove the explicit IV/MAC/Tag */
1258                 if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
1259                     for (ctr = 0; ctr < n_recs; ctr++) {
1260                         recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1261                         recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
1262                         recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
1263                     }
1264                 } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
1265                     for (ctr = 0; ctr < n_recs; ctr++) {
1266                         recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1267                         recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
1268                         recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
1269                     }
1270                 }
1271
1272                 for (ctr = 0; ctr < n_recs; ctr++) {
1273                     if (bs != 1 && SSL_USE_EXPLICIT_IV(s)) {
1274                         if (recs[ctr].length < bs)
1275                             return 0;
1276                         recs[ctr].data += bs;
1277                         recs[ctr].input += bs;
1278                         recs[ctr].length -= bs;
1279                         recs[ctr].orig_len -= bs;
1280                     }
1281
1282                     /*
1283                      * If using Mac-then-encrypt, then this will succeed but
1284                      * with a random MAC if padding is invalid
1285                      */
1286                     if (!tls1_cbc_remove_padding_and_mac(&recs[ctr].length,
1287                                          recs[ctr].orig_len,
1288                                          recs[ctr].data,
1289                                          (macs != NULL) ? &macs[ctr].mac : NULL,
1290                                          (macs != NULL) ? &macs[ctr].alloced
1291                                                         : NULL,
1292                                          bs,
1293                                          macsize,
1294                                          (EVP_CIPHER_flags(enc)
1295                                          & EVP_CIPH_FLAG_AEAD_CIPHER) != 0,
1296                                          s->ctx->libctx))
1297                         return 0;
1298                 }
1299                 if (pad) {
1300                     for (ctr = 0; ctr < n_recs; ctr++) {
1301                         recs[ctr].length -= pad;
1302                     }
1303                 }
1304             }
1305         }
1306     }
1307     return 1;
1308 }
1309
1310 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int sending)
1311 {
1312     unsigned char *mac_sec, *seq;
1313     const EVP_MD_CTX *hash;
1314     unsigned char *p, rec_char;
1315     size_t md_size;
1316     size_t npad;
1317     int t;
1318
1319     if (sending) {
1320         mac_sec = &(ssl->s3.write_mac_secret[0]);
1321         seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1322         hash = ssl->write_hash;
1323     } else {
1324         mac_sec = &(ssl->s3.read_mac_secret[0]);
1325         seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1326         hash = ssl->read_hash;
1327     }
1328
1329     t = EVP_MD_CTX_size(hash);
1330     if (t < 0)
1331         return 0;
1332     md_size = t;
1333     npad = (48 / md_size) * md_size;
1334
1335     if (!sending &&
1336         EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1337         ssl3_cbc_record_digest_supported(hash)) {
1338         /*
1339          * This is a CBC-encrypted record. We must avoid leaking any
1340          * timing-side channel information about how many blocks of data we
1341          * are hashing because that gives an attacker a timing-oracle.
1342          */
1343
1344         /*-
1345          * npad is, at most, 48 bytes and that's with MD5:
1346          *   16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
1347          *
1348          * With SHA-1 (the largest hash speced for SSLv3) the hash size
1349          * goes up 4, but npad goes down by 8, resulting in a smaller
1350          * total size.
1351          */
1352         unsigned char header[75];
1353         size_t j = 0;
1354         memcpy(header + j, mac_sec, md_size);
1355         j += md_size;
1356         memcpy(header + j, ssl3_pad_1, npad);
1357         j += npad;
1358         memcpy(header + j, seq, 8);
1359         j += 8;
1360         header[j++] = rec->type;
1361         header[j++] = (unsigned char)(rec->length >> 8);
1362         header[j++] = (unsigned char)(rec->length & 0xff);
1363
1364         /* Final param == is SSLv3 */
1365         if (ssl3_cbc_digest_record(EVP_MD_CTX_md(hash),
1366                                    md, &md_size,
1367                                    header, rec->input,
1368                                    rec->length + md_size, rec->orig_len,
1369                                    mac_sec, md_size, 1) <= 0)
1370             return 0;
1371     } else {
1372         unsigned int md_size_u;
1373         /* Chop the digest off the end :-) */
1374         EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1375
1376         if (md_ctx == NULL)
1377             return 0;
1378
1379         rec_char = rec->type;
1380         p = md;
1381         s2n(rec->length, p);
1382         if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1383             || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1384             || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1385             || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1386             || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1387             || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1388             || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1389             || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1390             || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1391             || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1392             || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
1393             || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1394             || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1395             EVP_MD_CTX_free(md_ctx);
1396             return 0;
1397         }
1398
1399         EVP_MD_CTX_free(md_ctx);
1400     }
1401
1402     ssl3_record_sequence_update(seq);
1403     return 1;
1404 }
1405
1406 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int sending)
1407 {
1408     unsigned char *seq;
1409     EVP_MD_CTX *hash;
1410     size_t md_size;
1411     int i;
1412     EVP_MD_CTX *hmac = NULL, *mac_ctx;
1413     unsigned char header[13];
1414     int stream_mac = sending ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1415                              : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM);
1416     int tlstree_mac = sending ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_TLSTREE)
1417                               : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_TLSTREE);
1418     int t;
1419
1420     if (sending) {
1421         seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1422         hash = ssl->write_hash;
1423     } else {
1424         seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1425         hash = ssl->read_hash;
1426     }
1427
1428     t = EVP_MD_CTX_size(hash);
1429     if (!ossl_assert(t >= 0))
1430         return 0;
1431     md_size = t;
1432
1433     /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1434     if (stream_mac) {
1435         mac_ctx = hash;
1436     } else {
1437         hmac = EVP_MD_CTX_new();
1438         if (hmac == NULL || !EVP_MD_CTX_copy(hmac, hash)) {
1439             EVP_MD_CTX_free(hmac);
1440             return 0;
1441         }
1442         mac_ctx = hmac;
1443     }
1444
1445     if (!SSL_IS_DTLS(ssl) && tlstree_mac && EVP_MD_CTX_ctrl(mac_ctx, EVP_MD_CTRL_TLSTREE, 0, seq) <= 0) {
1446         EVP_MD_CTX_free(hmac);
1447         return 0;
1448     }
1449
1450     if (SSL_IS_DTLS(ssl)) {
1451         unsigned char dtlsseq[8], *p = dtlsseq;
1452
1453         s2n(sending ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1454             DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1455         memcpy(p, &seq[2], 6);
1456
1457         memcpy(header, dtlsseq, 8);
1458     } else
1459         memcpy(header, seq, 8);
1460
1461     header[8] = rec->type;
1462     header[9] = (unsigned char)(ssl->version >> 8);
1463     header[10] = (unsigned char)(ssl->version);
1464     header[11] = (unsigned char)(rec->length >> 8);
1465     header[12] = (unsigned char)(rec->length & 0xff);
1466
1467     if (!sending && !SSL_READ_ETM(ssl) &&
1468             EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1469             ssl3_cbc_record_digest_supported(mac_ctx)) {
1470         OSSL_PARAM tls_hmac_params[2], *p = tls_hmac_params;
1471
1472         *p++ = OSSL_PARAM_construct_size_t(OSSL_MAC_PARAM_TLS_DATA_SIZE,
1473                                            &rec->orig_len);
1474         *p++ = OSSL_PARAM_construct_end();
1475
1476         if (!EVP_PKEY_CTX_set_params(EVP_MD_CTX_pkey_ctx(mac_ctx),
1477                                      tls_hmac_params))
1478             return 0;
1479     }
1480
1481     /* TODO(size_t): Convert these calls */
1482     if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1483         || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1484         || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1485         EVP_MD_CTX_free(hmac);
1486         return 0;
1487     }
1488
1489     EVP_MD_CTX_free(hmac);
1490
1491     OSSL_TRACE_BEGIN(TLS) {
1492         BIO_printf(trc_out, "seq:\n");
1493         BIO_dump_indent(trc_out, seq, 8, 4);
1494         BIO_printf(trc_out, "rec:\n");
1495         BIO_dump_indent(trc_out, rec->data, rec->length, 4);
1496     } OSSL_TRACE_END(TLS);
1497
1498     if (!SSL_IS_DTLS(ssl)) {
1499         for (i = 7; i >= 0; i--) {
1500             ++seq[i];
1501             if (seq[i] != 0)
1502                 break;
1503         }
1504     }
1505     OSSL_TRACE_BEGIN(TLS) {
1506         BIO_printf(trc_out, "md:\n");
1507         BIO_dump_indent(trc_out, md, md_size, 4);
1508     } OSSL_TRACE_END(TLS);
1509     return 1;
1510 }
1511
1512 int dtls1_process_record(SSL *s, DTLS1_BITMAP *bitmap)
1513 {
1514     int i;
1515     int enc_err;
1516     SSL_SESSION *sess;
1517     SSL3_RECORD *rr;
1518     int imac_size;
1519     size_t mac_size = 0;
1520     unsigned char md[EVP_MAX_MD_SIZE];
1521     size_t max_plain_length = SSL3_RT_MAX_PLAIN_LENGTH;
1522     SSL_MAC_BUF macbuf = { NULL, 0 };
1523     int ret = 0;
1524
1525     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1526     sess = s->session;
1527
1528     /*
1529      * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1530      * and we have that many bytes in s->packet
1531      */
1532     rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1533
1534     /*
1535      * ok, we can now read from 's->packet' data into 'rr' rr->input points
1536      * at rr->length bytes, which need to be copied into rr->data by either
1537      * the decryption or by the decompression When the data is 'copied' into
1538      * the rr->data buffer, rr->input will be pointed at the new buffer
1539      */
1540
1541     /*
1542      * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1543      * bytes of encrypted compressed stuff.
1544      */
1545
1546     /* check is not needed I believe */
1547     if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1548         SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_DTLS1_PROCESS_RECORD,
1549                  SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1550         return 0;
1551     }
1552
1553     /* decrypt in place in 'rr->input' */
1554     rr->data = rr->input;
1555     rr->orig_len = rr->length;
1556
1557     /* TODO(size_t): convert this to do size_t properly */
1558     if (s->read_hash != NULL) {
1559         const EVP_MD *tmpmd = EVP_MD_CTX_md(s->read_hash);
1560
1561         if (tmpmd != NULL) {
1562             imac_size = EVP_MD_size(tmpmd);
1563             if (!ossl_assert(imac_size >= 0 && imac_size <= EVP_MAX_MD_SIZE)) {
1564                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_F_SSL3_GET_RECORD,
1565                              ERR_LIB_EVP);
1566                     return -1;
1567             }
1568             mac_size = (size_t)imac_size;
1569         }
1570     }
1571
1572     if (SSL_READ_ETM(s) && s->read_hash) {
1573         unsigned char *mac;
1574
1575         if (rr->orig_len < mac_size) {
1576             SSLfatal(s, SSL_AD_DECODE_ERROR, SSL_F_DTLS1_PROCESS_RECORD,
1577                      SSL_R_LENGTH_TOO_SHORT);
1578             return 0;
1579         }
1580         rr->length -= mac_size;
1581         mac = rr->data + rr->length;
1582         i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1583         if (i == 0 || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0) {
1584             SSLfatal(s, SSL_AD_BAD_RECORD_MAC, SSL_F_DTLS1_PROCESS_RECORD,
1585                    SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
1586             return 0;
1587         }
1588         /*
1589          * We've handled the mac now - there is no MAC inside the encrypted
1590          * record
1591          */
1592         mac_size = 0;
1593     }
1594
1595     enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0, &macbuf, mac_size);
1596
1597     /*-
1598      * enc_err is:
1599      *    0: if the record is publicly invalid, or an internal error, or AEAD
1600      *       decryption failed, or ETM decryption failed.
1601      *    1: Success or MTE decryption failed (MAC will be randomised)
1602      */
1603     if (enc_err == 0) {
1604         if (ossl_statem_in_error(s)) {
1605             /* SSLfatal() got called */
1606             goto end;
1607         }
1608         /* For DTLS we simply ignore bad packets. */
1609         rr->length = 0;
1610         RECORD_LAYER_reset_packet_length(&s->rlayer);
1611         goto end;
1612     }
1613     OSSL_TRACE_BEGIN(TLS) {
1614         BIO_printf(trc_out, "dec %zd\n", rr->length);
1615         BIO_dump_indent(trc_out, rr->data, rr->length, 4);
1616     } OSSL_TRACE_END(TLS);
1617
1618     /* r->length is now the compressed data plus mac */
1619     if ((sess != NULL) && !SSL_READ_ETM(s) &&
1620         (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1621         /* s->read_hash != NULL => mac_size != -1 */
1622
1623         i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1624         if (i == 0 || macbuf.mac == NULL
1625             || CRYPTO_memcmp(md, macbuf.mac, mac_size) != 0)
1626             enc_err = 0;
1627         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1628             enc_err = 0;
1629     }
1630
1631     if (enc_err == 0) {
1632         /* decryption failed, silently discard message */
1633         rr->length = 0;
1634         RECORD_LAYER_reset_packet_length(&s->rlayer);
1635         goto end;
1636     }
1637
1638     /* r->length is now just compressed */
1639     if (s->expand != NULL) {
1640         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1641             SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_DTLS1_PROCESS_RECORD,
1642                      SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1643             goto end;
1644         }
1645         if (!ssl3_do_uncompress(s, rr)) {
1646             SSLfatal(s, SSL_AD_DECOMPRESSION_FAILURE,
1647                      SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1648             goto end;
1649         }
1650     }
1651
1652     /* use current Max Fragment Length setting if applicable */
1653     if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session))
1654         max_plain_length = GET_MAX_FRAGMENT_LENGTH(s->session);
1655
1656     /* send overflow if the plaintext is too long now it has passed MAC */
1657     if (rr->length > max_plain_length) {
1658         SSLfatal(s, SSL_AD_RECORD_OVERFLOW, SSL_F_DTLS1_PROCESS_RECORD,
1659                  SSL_R_DATA_LENGTH_TOO_LONG);
1660         goto end;
1661     }
1662
1663     rr->off = 0;
1664     /*-
1665      * So at this point the following is true
1666      * ssl->s3.rrec.type   is the type of record
1667      * ssl->s3.rrec.length == number of bytes in record
1668      * ssl->s3.rrec.off    == offset to first valid byte
1669      * ssl->s3.rrec.data   == where to take bytes from, increment
1670      *                        after use :-).
1671      */
1672
1673     /* we have pulled in a full packet so zero things */
1674     RECORD_LAYER_reset_packet_length(&s->rlayer);
1675
1676     /* Mark receipt of record. */
1677     dtls1_record_bitmap_update(s, bitmap);
1678
1679     ret = 1;
1680  end:
1681     if (macbuf.alloced)
1682         OPENSSL_free(macbuf.mac);
1683     return ret;
1684 }
1685
1686 /*
1687  * Retrieve a buffered record that belongs to the current epoch, i.e. processed
1688  */
1689 #define dtls1_get_processed_record(s) \
1690                    dtls1_retrieve_buffered_record((s), \
1691                    &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1692
1693 /*-
1694  * Call this to get a new input record.
1695  * It will return <= 0 if more data is needed, normally due to an error
1696  * or non-blocking IO.
1697  * When it finishes, one packet has been decoded and can be found in
1698  * ssl->s3.rrec.type    - is the type of record
1699  * ssl->s3.rrec.data    - data
1700  * ssl->s3.rrec.length  - number of bytes
1701  */
1702 /* used only by dtls1_read_bytes */
1703 int dtls1_get_record(SSL *s)
1704 {
1705     int ssl_major, ssl_minor;
1706     int rret;
1707     size_t more, n;
1708     SSL3_RECORD *rr;
1709     unsigned char *p = NULL;
1710     unsigned short version;
1711     DTLS1_BITMAP *bitmap;
1712     unsigned int is_next_epoch;
1713
1714     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1715
1716  again:
1717     /*
1718      * The epoch may have changed.  If so, process all the pending records.
1719      * This is a non-blocking operation.
1720      */
1721     if (!dtls1_process_buffered_records(s)) {
1722         /* SSLfatal() already called */
1723         return -1;
1724     }
1725
1726     /* if we're renegotiating, then there may be buffered records */
1727     if (dtls1_get_processed_record(s))
1728         return 1;
1729
1730     /* get something from the wire */
1731
1732     /* check if we have the header */
1733     if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1734         (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1735         rret = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1736                            SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1, &n);
1737         /* read timeout is handled by dtls1_read_bytes */
1738         if (rret <= 0) {
1739             /* SSLfatal() already called if appropriate */
1740             return rret;         /* error or non-blocking */
1741         }
1742
1743         /* this packet contained a partial record, dump it */
1744         if (RECORD_LAYER_get_packet_length(&s->rlayer) !=
1745             DTLS1_RT_HEADER_LENGTH) {
1746             RECORD_LAYER_reset_packet_length(&s->rlayer);
1747             goto again;
1748         }
1749
1750         RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1751
1752         p = RECORD_LAYER_get_packet(&s->rlayer);
1753
1754         if (s->msg_callback)
1755             s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1756                             s, s->msg_callback_arg);
1757
1758         /* Pull apart the header into the DTLS1_RECORD */
1759         rr->type = *(p++);
1760         ssl_major = *(p++);
1761         ssl_minor = *(p++);
1762         version = (ssl_major << 8) | ssl_minor;
1763
1764         /* sequence number is 64 bits, with top 2 bytes = epoch */
1765         n2s(p, rr->epoch);
1766
1767         memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1768         p += 6;
1769
1770         n2s(p, rr->length);
1771         rr->read = 0;
1772
1773         /*
1774          * Lets check the version. We tolerate alerts that don't have the exact
1775          * version number (e.g. because of protocol version errors)
1776          */
1777         if (!s->first_packet && rr->type != SSL3_RT_ALERT) {
1778             if (version != s->version) {
1779                 /* unexpected version, silently discard */
1780                 rr->length = 0;
1781                 rr->read = 1;
1782                 RECORD_LAYER_reset_packet_length(&s->rlayer);
1783                 goto again;
1784             }
1785         }
1786
1787         if ((version & 0xff00) != (s->version & 0xff00)) {
1788             /* wrong version, silently discard record */
1789             rr->length = 0;
1790             rr->read = 1;
1791             RECORD_LAYER_reset_packet_length(&s->rlayer);
1792             goto again;
1793         }
1794
1795         if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1796             /* record too long, silently discard it */
1797             rr->length = 0;
1798             rr->read = 1;
1799             RECORD_LAYER_reset_packet_length(&s->rlayer);
1800             goto again;
1801         }
1802
1803         /* If received packet overflows own-client Max Fragment Length setting */
1804         if (s->session != NULL && USE_MAX_FRAGMENT_LENGTH_EXT(s->session)
1805                 && rr->length > GET_MAX_FRAGMENT_LENGTH(s->session) + SSL3_RT_MAX_ENCRYPTED_OVERHEAD) {
1806             /* record too long, silently discard it */
1807             rr->length = 0;
1808             rr->read = 1;
1809             RECORD_LAYER_reset_packet_length(&s->rlayer);
1810             goto again;
1811         }
1812
1813         /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1814     }
1815
1816     /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1817
1818     if (rr->length >
1819         RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1820         /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1821         more = rr->length;
1822         rret = ssl3_read_n(s, more, more, 1, 1, &n);
1823         /* this packet contained a partial record, dump it */
1824         if (rret <= 0 || n != more) {
1825             if (ossl_statem_in_error(s)) {
1826                 /* ssl3_read_n() called SSLfatal() */
1827                 return -1;
1828             }
1829             rr->length = 0;
1830             rr->read = 1;
1831             RECORD_LAYER_reset_packet_length(&s->rlayer);
1832             goto again;
1833         }
1834
1835         /*
1836          * now n == rr->length, and s->packet_length ==
1837          * DTLS1_RT_HEADER_LENGTH + rr->length
1838          */
1839     }
1840     /* set state for later operations */
1841     RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1842
1843     /* match epochs.  NULL means the packet is dropped on the floor */
1844     bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1845     if (bitmap == NULL) {
1846         rr->length = 0;
1847         RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1848         goto again;             /* get another record */
1849     }
1850 #ifndef OPENSSL_NO_SCTP
1851     /* Only do replay check if no SCTP bio */
1852     if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1853 #endif
1854         /* Check whether this is a repeat, or aged record. */
1855         /*
1856          * TODO: Does it make sense to have replay protection in epoch 0 where
1857          * we have no integrity negotiated yet?
1858          */
1859         if (!dtls1_record_replay_check(s, bitmap)) {
1860             rr->length = 0;
1861             rr->read = 1;
1862             RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1863             goto again;         /* get another record */
1864         }
1865 #ifndef OPENSSL_NO_SCTP
1866     }
1867 #endif
1868
1869     /* just read a 0 length packet */
1870     if (rr->length == 0) {
1871         rr->read = 1;
1872         goto again;
1873     }
1874
1875     /*
1876      * If this record is from the next epoch (either HM or ALERT), and a
1877      * handshake is currently in progress, buffer it since it cannot be
1878      * processed at this time.
1879      */
1880     if (is_next_epoch) {
1881         if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1882             if (dtls1_buffer_record (s,
1883                     &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1884                     rr->seq_num) < 0) {
1885                 /* SSLfatal() already called */
1886                 return -1;
1887             }
1888         }
1889         rr->length = 0;
1890         rr->read = 1;
1891         RECORD_LAYER_reset_packet_length(&s->rlayer);
1892         goto again;
1893     }
1894
1895     if (!dtls1_process_record(s, bitmap)) {
1896         if (ossl_statem_in_error(s)) {
1897             /* dtls1_process_record() called SSLfatal */
1898             return -1;
1899         }
1900         rr->length = 0;
1901         rr->read = 1;
1902         RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1903         goto again;             /* get another record */
1904     }
1905
1906     return 1;
1907
1908 }
1909
1910 int dtls_buffer_listen_record(SSL *s, size_t len, unsigned char *seq, size_t off)
1911 {
1912     SSL3_RECORD *rr;
1913
1914     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1915     memset(rr, 0, sizeof(SSL3_RECORD));
1916
1917     rr->length = len;
1918     rr->type = SSL3_RT_HANDSHAKE;
1919     memcpy(rr->seq_num, seq, sizeof(rr->seq_num));
1920     rr->off = off;
1921
1922     s->rlayer.packet = RECORD_LAYER_get_rbuf(&s->rlayer)->buf;
1923     s->rlayer.packet_length = DTLS1_RT_HEADER_LENGTH + len;
1924     rr->data = s->rlayer.packet + DTLS1_RT_HEADER_LENGTH;
1925
1926     if (dtls1_buffer_record(s, &(s->rlayer.d->processed_rcds),
1927                             SSL3_RECORD_get_seq_num(s->rlayer.rrec)) <= 0) {
1928         /* SSLfatal() already called */
1929         return 0;
1930     }
1931
1932     return 1;
1933 }