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