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