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