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