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