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