Use return "" not set a var and return.
[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 ssl3_record_app_data_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              && ssl3_record_app_data_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 |n_recs| records in |inrecs|
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 n_recs, 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     /*
668      * We shouldn't ever be called with more than one record in the SSLv3 case
669      */
670     if (n_recs != 1)
671         return 0;
672     if (send) {
673         ds = s->enc_write_ctx;
674         if (s->enc_write_ctx == NULL)
675             enc = NULL;
676         else
677             enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
678     } else {
679         ds = s->enc_read_ctx;
680         if (s->enc_read_ctx == NULL)
681             enc = NULL;
682         else
683             enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
684     }
685
686     if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
687         memmove(rec->data, rec->input, rec->length);
688         rec->input = rec->data;
689     } else {
690         l = rec->length;
691         bs = EVP_CIPHER_CTX_block_size(ds);
692
693         /* COMPRESS */
694
695         if ((bs != 1) && send) {
696             i = bs - ((int)l % bs);
697
698             /* we need to add 'i-1' padding bytes */
699             l += i;
700             /*
701              * the last of these zero bytes will be overwritten with the
702              * padding length.
703              */
704             memset(&rec->input[rec->length], 0, i);
705             rec->length += i;
706             rec->input[l - 1] = (i - 1);
707         }
708
709         if (!send) {
710             if (l == 0 || l % bs != 0)
711                 return 0;
712             /* otherwise, rec->length >= bs */
713         }
714
715         if (EVP_Cipher(ds, rec->data, rec->input, l) < 1)
716             return -1;
717
718         if (EVP_MD_CTX_md(s->read_hash) != NULL)
719             mac_size = EVP_MD_CTX_size(s->read_hash);
720         if ((bs != 1) && !send)
721             return ssl3_cbc_remove_padding(rec, bs, mac_size);
722     }
723     return (1);
724 }
725
726 /*-
727  * tls1_enc encrypts/decrypts |n_recs| in |recs|.
728  *
729  * Returns:
730  *   0: (in non-constant time) if the record is publically invalid (i.e. too
731  *       short etc).
732  *   1: if the record's padding is valid / the encryption was successful.
733  *   -1: if the record's padding/AEAD-authenticator is invalid or, if sending,
734  *       an internal error occurred.
735  */
736 int tls1_enc(SSL *s, SSL3_RECORD *recs, unsigned int n_recs, int send)
737 {
738     EVP_CIPHER_CTX *ds;
739     size_t reclen[SSL_MAX_PIPELINES];
740     unsigned char buf[SSL_MAX_PIPELINES][EVP_AEAD_TLS1_AAD_LEN];
741     int bs, i, j, k, pad = 0, ret, mac_size = 0;
742     const EVP_CIPHER *enc;
743     unsigned int ctr;
744
745     if (send) {
746         if (EVP_MD_CTX_md(s->write_hash)) {
747             int n = EVP_MD_CTX_size(s->write_hash);
748             OPENSSL_assert(n >= 0);
749         }
750         ds = s->enc_write_ctx;
751         if (s->enc_write_ctx == NULL)
752             enc = NULL;
753         else {
754             int ivlen;
755             enc = EVP_CIPHER_CTX_cipher(s->enc_write_ctx);
756             /* For TLSv1.1 and later explicit IV */
757             if (SSL_USE_EXPLICIT_IV(s)
758                 && EVP_CIPHER_mode(enc) == EVP_CIPH_CBC_MODE)
759                 ivlen = EVP_CIPHER_iv_length(enc);
760             else
761                 ivlen = 0;
762             if (ivlen > 1) {
763                 for (ctr = 0; ctr < n_recs; ctr++) {
764                     if (recs[ctr].data != recs[ctr].input) {
765                         /*
766                          * we can't write into the input stream: Can this ever
767                          * happen?? (steve)
768                          */
769                         SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
770                         return -1;
771                     } else if (RAND_bytes(recs[ctr].input, ivlen) <= 0) {
772                         SSLerr(SSL_F_TLS1_ENC, ERR_R_INTERNAL_ERROR);
773                         return -1;
774                     }
775                 }
776             }
777         }
778     } else {
779         if (EVP_MD_CTX_md(s->read_hash)) {
780             int n = EVP_MD_CTX_size(s->read_hash);
781             OPENSSL_assert(n >= 0);
782         }
783         ds = s->enc_read_ctx;
784         if (s->enc_read_ctx == NULL)
785             enc = NULL;
786         else
787             enc = EVP_CIPHER_CTX_cipher(s->enc_read_ctx);
788     }
789
790     if ((s->session == NULL) || (ds == NULL) || (enc == NULL)) {
791         for (ctr = 0; ctr < n_recs; ctr++) {
792             memmove(recs[ctr].data, recs[ctr].input, recs[ctr].length);
793             recs[ctr].input = recs[ctr].data;
794         }
795         ret = 1;
796     } else {
797         bs = EVP_CIPHER_block_size(EVP_CIPHER_CTX_cipher(ds));
798
799         if (n_recs > 1) {
800             if(!(EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
801                                   & EVP_CIPH_FLAG_PIPELINE)) {
802                 /*
803                  * We shouldn't have been called with pipeline data if the
804                  * cipher doesn't support pipelining
805                  */
806                 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
807                 return -1;
808             }
809         }
810         for (ctr = 0; ctr < n_recs; ctr++) {
811             reclen[ctr] = recs[ctr].length;
812
813             if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
814                     & EVP_CIPH_FLAG_AEAD_CIPHER) {
815                 unsigned char *seq;
816
817                 seq = send ? RECORD_LAYER_get_write_sequence(&s->rlayer)
818                     : RECORD_LAYER_get_read_sequence(&s->rlayer);
819
820                 if (SSL_IS_DTLS(s)) {
821                     /* DTLS does not support pipelining */
822                     unsigned char dtlsseq[9], *p = dtlsseq;
823
824                     s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&s->rlayer) :
825                         DTLS_RECORD_LAYER_get_r_epoch(&s->rlayer), p);
826                     memcpy(p, &seq[2], 6);
827                     memcpy(buf[ctr], dtlsseq, 8);
828                 } else {
829                     memcpy(buf[ctr], seq, 8);
830                     for (i = 7; i >= 0; i--) { /* increment */
831                         ++seq[i];
832                         if (seq[i] != 0)
833                             break;
834                     }
835                 }
836
837                 buf[ctr][8] = recs[ctr].type;
838                 buf[ctr][9] = (unsigned char)(s->version >> 8);
839                 buf[ctr][10] = (unsigned char)(s->version);
840                 buf[ctr][11] = recs[ctr].length >> 8;
841                 buf[ctr][12] = recs[ctr].length & 0xff;
842                 pad = EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_AEAD_TLS1_AAD,
843                                           EVP_AEAD_TLS1_AAD_LEN, buf[ctr]);
844                 if (pad <= 0)
845                     return -1;
846
847                 if (send) {
848                     reclen[ctr] += pad;
849                     recs[ctr].length += pad;
850                 }
851
852             } else if ((bs != 1) && send) {
853                 i = bs - ((int)reclen[ctr] % bs);
854
855                 /* Add weird padding of upto 256 bytes */
856
857                 /* we need to add 'i' padding bytes of value j */
858                 j = i - 1;
859                 for (k = (int)reclen[ctr]; k < (int)(reclen[ctr] + i); k++)
860                     recs[ctr].input[k] = j;
861                 reclen[ctr] += i;
862                 recs[ctr].length += i;
863             }
864
865             if (!send) {
866                 if (reclen[ctr] == 0 || reclen[ctr] % bs != 0)
867                     return 0;
868             }
869         }
870         if (n_recs > 1) {
871             unsigned char *data[SSL_MAX_PIPELINES];
872
873             /* Set the output buffers */
874             for(ctr = 0; ctr < n_recs; ctr++) {
875                 data[ctr] = recs[ctr].data;
876             }
877             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_OUTPUT_BUFS,
878                                       n_recs, data) <= 0) {
879                 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
880             }
881             /* Set the input buffers */
882             for(ctr = 0; ctr < n_recs; ctr++) {
883                 data[ctr] = recs[ctr].input;
884             }
885             if (EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_BUFS,
886                                       n_recs, data) <= 0
887                 || EVP_CIPHER_CTX_ctrl(ds, EVP_CTRL_SET_PIPELINE_INPUT_LENS,
888                                       n_recs, reclen) <= 0) {
889                 SSLerr(SSL_F_TLS1_ENC, SSL_R_PIPELINE_FAILURE);
890                 return -1;
891             }
892         }
893
894         i = EVP_Cipher(ds, recs[0].data, recs[0].input, reclen[0]);
895         if ((EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(ds))
896                 & EVP_CIPH_FLAG_CUSTOM_CIPHER)
897             ? (i < 0)
898             : (i == 0))
899             return -1;          /* AEAD can fail to verify MAC */
900         if (send == 0) {
901             if (EVP_CIPHER_mode(enc) == EVP_CIPH_GCM_MODE) {
902                 for (ctr = 0; ctr < n_recs; ctr++) {
903                     recs[ctr].data += EVP_GCM_TLS_EXPLICIT_IV_LEN;
904                     recs[ctr].input += EVP_GCM_TLS_EXPLICIT_IV_LEN;
905                     recs[ctr].length -= EVP_GCM_TLS_EXPLICIT_IV_LEN;
906                 }
907             } else if (EVP_CIPHER_mode(enc) == EVP_CIPH_CCM_MODE) {
908                 for (ctr = 0; ctr < n_recs; ctr++) {
909                     recs[ctr].data += EVP_CCM_TLS_EXPLICIT_IV_LEN;
910                     recs[ctr].input += EVP_CCM_TLS_EXPLICIT_IV_LEN;
911                     recs[ctr].length -= EVP_CCM_TLS_EXPLICIT_IV_LEN;
912                 }
913             }
914         }
915
916         ret = 1;
917         if (!SSL_USE_ETM(s) && EVP_MD_CTX_md(s->read_hash) != NULL)
918             mac_size = EVP_MD_CTX_size(s->read_hash);
919         if ((bs != 1) && !send) {
920             int tmpret;
921             for (ctr = 0; ctr < n_recs; ctr++) {
922                 tmpret = tls1_cbc_remove_padding(s, &recs[ctr], bs, mac_size);
923                 if (tmpret == -1)
924                     return -1;
925                 ret &= tmpret;
926             }
927         }
928         if (pad && !send) {
929             for (ctr = 0; ctr < n_recs; ctr++) {
930                 recs[ctr].length -= pad;
931             }
932         }
933     }
934     return ret;
935 }
936
937 int n_ssl3_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
938 {
939     unsigned char *mac_sec, *seq;
940     const EVP_MD_CTX *hash;
941     unsigned char *p, rec_char;
942     size_t md_size;
943     int npad;
944     int t;
945
946     if (send) {
947         mac_sec = &(ssl->s3->write_mac_secret[0]);
948         seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
949         hash = ssl->write_hash;
950     } else {
951         mac_sec = &(ssl->s3->read_mac_secret[0]);
952         seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
953         hash = ssl->read_hash;
954     }
955
956     t = EVP_MD_CTX_size(hash);
957     if (t < 0)
958         return -1;
959     md_size = t;
960     npad = (48 / md_size) * md_size;
961
962     if (!send &&
963         EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
964         ssl3_cbc_record_digest_supported(hash)) {
965         /*
966          * This is a CBC-encrypted record. We must avoid leaking any
967          * timing-side channel information about how many blocks of data we
968          * are hashing because that gives an attacker a timing-oracle.
969          */
970
971         /*-
972          * npad is, at most, 48 bytes and that's with MD5:
973          *   16 + 48 + 8 (sequence bytes) + 1 + 2 = 75.
974          *
975          * With SHA-1 (the largest hash speced for SSLv3) the hash size
976          * goes up 4, but npad goes down by 8, resulting in a smaller
977          * total size.
978          */
979         unsigned char header[75];
980         unsigned j = 0;
981         memcpy(header + j, mac_sec, md_size);
982         j += md_size;
983         memcpy(header + j, ssl3_pad_1, npad);
984         j += npad;
985         memcpy(header + j, seq, 8);
986         j += 8;
987         header[j++] = rec->type;
988         header[j++] = rec->length >> 8;
989         header[j++] = rec->length & 0xff;
990
991         /* Final param == is SSLv3 */
992         if (ssl3_cbc_digest_record(hash,
993                                    md, &md_size,
994                                    header, rec->input,
995                                    rec->length + md_size, rec->orig_len,
996                                    mac_sec, md_size, 1) <= 0)
997             return -1;
998     } else {
999         unsigned int md_size_u;
1000         /* Chop the digest off the end :-) */
1001         EVP_MD_CTX *md_ctx = EVP_MD_CTX_new();
1002
1003         if (md_ctx == NULL)
1004             return -1;
1005
1006         rec_char = rec->type;
1007         p = md;
1008         s2n(rec->length, p);
1009         if (EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1010                 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1011                 || EVP_DigestUpdate(md_ctx, ssl3_pad_1, npad) <= 0
1012                 || EVP_DigestUpdate(md_ctx, seq, 8) <= 0
1013                 || EVP_DigestUpdate(md_ctx, &rec_char, 1) <= 0
1014                 || EVP_DigestUpdate(md_ctx, md, 2) <= 0
1015                 || EVP_DigestUpdate(md_ctx, rec->input, rec->length) <= 0
1016                 || EVP_DigestFinal_ex(md_ctx, md, NULL) <= 0
1017                 || EVP_MD_CTX_copy_ex(md_ctx, hash) <= 0
1018                 || EVP_DigestUpdate(md_ctx, mac_sec, md_size) <= 0
1019                 || EVP_DigestUpdate(md_ctx, ssl3_pad_2, npad) <= 0
1020                 || EVP_DigestUpdate(md_ctx, md, md_size) <= 0
1021                 || EVP_DigestFinal_ex(md_ctx, md, &md_size_u) <= 0) {
1022             EVP_MD_CTX_reset(md_ctx);
1023             return -1;
1024         }
1025         md_size = md_size_u;
1026
1027         EVP_MD_CTX_free(md_ctx);
1028     }
1029
1030     ssl3_record_sequence_update(seq);
1031     return (md_size);
1032 }
1033
1034 int tls1_mac(SSL *ssl, SSL3_RECORD *rec, unsigned char *md, int send)
1035 {
1036     unsigned char *seq;
1037     EVP_MD_CTX *hash;
1038     size_t md_size;
1039     int i;
1040     EVP_MD_CTX *hmac = NULL, *mac_ctx;
1041     unsigned char header[13];
1042     int stream_mac = (send ? (ssl->mac_flags & SSL_MAC_FLAG_WRITE_MAC_STREAM)
1043                       : (ssl->mac_flags & SSL_MAC_FLAG_READ_MAC_STREAM));
1044     int t;
1045
1046     if (send) {
1047         seq = RECORD_LAYER_get_write_sequence(&ssl->rlayer);
1048         hash = ssl->write_hash;
1049     } else {
1050         seq = RECORD_LAYER_get_read_sequence(&ssl->rlayer);
1051         hash = ssl->read_hash;
1052     }
1053
1054     t = EVP_MD_CTX_size(hash);
1055     OPENSSL_assert(t >= 0);
1056     md_size = t;
1057
1058     /* I should fix this up TLS TLS TLS TLS TLS XXXXXXXX */
1059     if (stream_mac) {
1060         mac_ctx = hash;
1061     } else {
1062         hmac = EVP_MD_CTX_new();
1063         if (hmac == NULL
1064                 || !EVP_MD_CTX_copy(hmac, hash))
1065             return -1;
1066         mac_ctx = hmac;
1067     }
1068
1069     if (SSL_IS_DTLS(ssl)) {
1070         unsigned char dtlsseq[8], *p = dtlsseq;
1071
1072         s2n(send ? DTLS_RECORD_LAYER_get_w_epoch(&ssl->rlayer) :
1073             DTLS_RECORD_LAYER_get_r_epoch(&ssl->rlayer), p);
1074         memcpy(p, &seq[2], 6);
1075
1076         memcpy(header, dtlsseq, 8);
1077     } else
1078         memcpy(header, seq, 8);
1079
1080     header[8] = rec->type;
1081     header[9] = (unsigned char)(ssl->version >> 8);
1082     header[10] = (unsigned char)(ssl->version);
1083     header[11] = (rec->length) >> 8;
1084     header[12] = (rec->length) & 0xff;
1085
1086     if (!send && !SSL_USE_ETM(ssl) &&
1087         EVP_CIPHER_CTX_mode(ssl->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1088         ssl3_cbc_record_digest_supported(mac_ctx)) {
1089         /*
1090          * This is a CBC-encrypted record. We must avoid leaking any
1091          * timing-side channel information about how many blocks of data we
1092          * are hashing because that gives an attacker a timing-oracle.
1093          */
1094         /* Final param == not SSLv3 */
1095         if (ssl3_cbc_digest_record(mac_ctx,
1096                                    md, &md_size,
1097                                    header, rec->input,
1098                                    rec->length + md_size, rec->orig_len,
1099                                    ssl->s3->read_mac_secret,
1100                                    ssl->s3->read_mac_secret_size, 0) <= 0) {
1101             EVP_MD_CTX_free(hmac);
1102             return -1;
1103         }
1104     } else {
1105         if (EVP_DigestSignUpdate(mac_ctx, header, sizeof(header)) <= 0
1106                 || EVP_DigestSignUpdate(mac_ctx, rec->input, rec->length) <= 0
1107                 || EVP_DigestSignFinal(mac_ctx, md, &md_size) <= 0) {
1108             EVP_MD_CTX_free(hmac);
1109             return -1;
1110         }
1111         if (!send && !SSL_USE_ETM(ssl) && FIPS_mode())
1112             tls_fips_digest_extra(ssl->enc_read_ctx,
1113                                   mac_ctx, rec->input,
1114                                   rec->length, rec->orig_len);
1115     }
1116
1117     EVP_MD_CTX_free(hmac);
1118
1119 #ifdef SSL_DEBUG
1120     fprintf(stderr, "seq=");
1121     {
1122         int z;
1123         for (z = 0; z < 8; z++)
1124             fprintf(stderr, "%02X ", seq[z]);
1125         fprintf(stderr, "\n");
1126     }
1127     fprintf(stderr, "rec=");
1128     {
1129         unsigned int z;
1130         for (z = 0; z < rec->length; z++)
1131             fprintf(stderr, "%02X ", rec->data[z]);
1132         fprintf(stderr, "\n");
1133     }
1134 #endif
1135
1136     if (!SSL_IS_DTLS(ssl)) {
1137         for (i = 7; i >= 0; i--) {
1138             ++seq[i];
1139             if (seq[i] != 0)
1140                 break;
1141         }
1142     }
1143 #ifdef SSL_DEBUG
1144     {
1145         unsigned int z;
1146         for (z = 0; z < md_size; z++)
1147             fprintf(stderr, "%02X ", md[z]);
1148         fprintf(stderr, "\n");
1149     }
1150 #endif
1151     return (md_size);
1152 }
1153
1154 /*-
1155  * ssl3_cbc_remove_padding removes padding from the decrypted, SSLv3, CBC
1156  * record in |rec| by updating |rec->length| in constant time.
1157  *
1158  * block_size: the block size of the cipher used to encrypt the record.
1159  * returns:
1160  *   0: (in non-constant time) if the record is publicly invalid.
1161  *   1: if the padding was valid
1162  *  -1: otherwise.
1163  */
1164 int ssl3_cbc_remove_padding(SSL3_RECORD *rec,
1165                             unsigned block_size, unsigned mac_size)
1166 {
1167     unsigned padding_length, good;
1168     const unsigned overhead = 1 /* padding length byte */  + mac_size;
1169
1170     /*
1171      * These lengths are all public so we can test them in non-constant time.
1172      */
1173     if (overhead > rec->length)
1174         return 0;
1175
1176     padding_length = rec->data[rec->length - 1];
1177     good = constant_time_ge(rec->length, padding_length + overhead);
1178     /* SSLv3 requires that the padding is minimal. */
1179     good &= constant_time_ge(block_size, padding_length + 1);
1180     rec->length -= good & (padding_length + 1);
1181     return constant_time_select_int(good, 1, -1);
1182 }
1183
1184 /*-
1185  * tls1_cbc_remove_padding removes the CBC padding from the decrypted, TLS, CBC
1186  * record in |rec| in constant time and returns 1 if the padding is valid and
1187  * -1 otherwise. It also removes any explicit IV from the start of the record
1188  * without leaking any timing about whether there was enough space after the
1189  * padding was removed.
1190  *
1191  * block_size: the block size of the cipher used to encrypt the record.
1192  * returns:
1193  *   0: (in non-constant time) if the record is publicly invalid.
1194  *   1: if the padding was valid
1195  *  -1: otherwise.
1196  */
1197 int tls1_cbc_remove_padding(const SSL *s,
1198                             SSL3_RECORD *rec,
1199                             unsigned block_size, unsigned mac_size)
1200 {
1201     unsigned padding_length, good, to_check, i;
1202     const unsigned overhead = 1 /* padding length byte */  + mac_size;
1203     /* Check if version requires explicit IV */
1204     if (SSL_USE_EXPLICIT_IV(s)) {
1205         /*
1206          * These lengths are all public so we can test them in non-constant
1207          * time.
1208          */
1209         if (overhead + block_size > rec->length)
1210             return 0;
1211         /* We can now safely skip explicit IV */
1212         rec->data += block_size;
1213         rec->input += block_size;
1214         rec->length -= block_size;
1215         rec->orig_len -= block_size;
1216     } else if (overhead > rec->length)
1217         return 0;
1218
1219     padding_length = rec->data[rec->length - 1];
1220
1221     if (EVP_CIPHER_flags(EVP_CIPHER_CTX_cipher(s->enc_read_ctx)) & EVP_CIPH_FLAG_AEAD_CIPHER) {
1222         /* padding is already verified */
1223         rec->length -= padding_length + 1;
1224         return 1;
1225     }
1226
1227     good = constant_time_ge(rec->length, overhead + padding_length);
1228     /*
1229      * The padding consists of a length byte at the end of the record and
1230      * then that many bytes of padding, all with the same value as the length
1231      * byte. Thus, with the length byte included, there are i+1 bytes of
1232      * padding. We can't check just |padding_length+1| bytes because that
1233      * leaks decrypted information. Therefore we always have to check the
1234      * maximum amount of padding possible. (Again, the length of the record
1235      * is public information so we can use it.)
1236      */
1237     to_check = 255;             /* maximum amount of padding. */
1238     if (to_check > rec->length - 1)
1239         to_check = rec->length - 1;
1240
1241     for (i = 0; i < to_check; i++) {
1242         unsigned char mask = constant_time_ge_8(padding_length, i);
1243         unsigned char b = rec->data[rec->length - 1 - i];
1244         /*
1245          * The final |padding_length+1| bytes should all have the value
1246          * |padding_length|. Therefore the XOR should be zero.
1247          */
1248         good &= ~(mask & (padding_length ^ b));
1249     }
1250
1251     /*
1252      * If any of the final |padding_length+1| bytes had the wrong value, one
1253      * or more of the lower eight bits of |good| will be cleared.
1254      */
1255     good = constant_time_eq(0xff, good & 0xff);
1256     rec->length -= good & (padding_length + 1);
1257
1258     return constant_time_select_int(good, 1, -1);
1259 }
1260
1261 /*-
1262  * ssl3_cbc_copy_mac copies |md_size| bytes from the end of |rec| to |out| in
1263  * constant time (independent of the concrete value of rec->length, which may
1264  * vary within a 256-byte window).
1265  *
1266  * ssl3_cbc_remove_padding or tls1_cbc_remove_padding must be called prior to
1267  * this function.
1268  *
1269  * On entry:
1270  *   rec->orig_len >= md_size
1271  *   md_size <= EVP_MAX_MD_SIZE
1272  *
1273  * If CBC_MAC_ROTATE_IN_PLACE is defined then the rotation is performed with
1274  * variable accesses in a 64-byte-aligned buffer. Assuming that this fits into
1275  * a single or pair of cache-lines, then the variable memory accesses don't
1276  * actually affect the timing. CPUs with smaller cache-lines [if any] are
1277  * not multi-core and are not considered vulnerable to cache-timing attacks.
1278  */
1279 #define CBC_MAC_ROTATE_IN_PLACE
1280
1281 void ssl3_cbc_copy_mac(unsigned char *out,
1282                        const SSL3_RECORD *rec, unsigned md_size)
1283 {
1284 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1285     unsigned char rotated_mac_buf[64 + EVP_MAX_MD_SIZE];
1286     unsigned char *rotated_mac;
1287 #else
1288     unsigned char rotated_mac[EVP_MAX_MD_SIZE];
1289 #endif
1290
1291     /*
1292      * mac_end is the index of |rec->data| just after the end of the MAC.
1293      */
1294     unsigned mac_end = rec->length;
1295     unsigned mac_start = mac_end - md_size;
1296     /*
1297      * scan_start contains the number of bytes that we can ignore because the
1298      * MAC's position can only vary by 255 bytes.
1299      */
1300     unsigned scan_start = 0;
1301     unsigned i, j;
1302     unsigned div_spoiler;
1303     unsigned rotate_offset;
1304
1305     OPENSSL_assert(rec->orig_len >= md_size);
1306     OPENSSL_assert(md_size <= EVP_MAX_MD_SIZE);
1307
1308 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1309     rotated_mac = rotated_mac_buf + ((0 - (size_t)rotated_mac_buf) & 63);
1310 #endif
1311
1312     /* This information is public so it's safe to branch based on it. */
1313     if (rec->orig_len > md_size + 255 + 1)
1314         scan_start = rec->orig_len - (md_size + 255 + 1);
1315     /*
1316      * div_spoiler contains a multiple of md_size that is used to cause the
1317      * modulo operation to be constant time. Without this, the time varies
1318      * based on the amount of padding when running on Intel chips at least.
1319      * The aim of right-shifting md_size is so that the compiler doesn't
1320      * figure out that it can remove div_spoiler as that would require it to
1321      * prove that md_size is always even, which I hope is beyond it.
1322      */
1323     div_spoiler = md_size >> 1;
1324     div_spoiler <<= (sizeof(div_spoiler) - 1) * 8;
1325     rotate_offset = (div_spoiler + mac_start - scan_start) % md_size;
1326
1327     memset(rotated_mac, 0, md_size);
1328     for (i = scan_start, j = 0; i < rec->orig_len; i++) {
1329         unsigned char mac_started = constant_time_ge_8(i, mac_start);
1330         unsigned char mac_ended = constant_time_ge_8(i, mac_end);
1331         unsigned char b = rec->data[i];
1332         rotated_mac[j++] |= b & mac_started & ~mac_ended;
1333         j &= constant_time_lt(j, md_size);
1334     }
1335
1336     /* Now rotate the MAC */
1337 #if defined(CBC_MAC_ROTATE_IN_PLACE)
1338     j = 0;
1339     for (i = 0; i < md_size; i++) {
1340         /* in case cache-line is 32 bytes, touch second line */
1341         ((volatile unsigned char *)rotated_mac)[rotate_offset ^ 32];
1342         out[j++] = rotated_mac[rotate_offset++];
1343         rotate_offset &= constant_time_lt(rotate_offset, md_size);
1344     }
1345 #else
1346     memset(out, 0, md_size);
1347     rotate_offset = md_size - rotate_offset;
1348     rotate_offset &= constant_time_lt(rotate_offset, md_size);
1349     for (i = 0; i < md_size; i++) {
1350         for (j = 0; j < md_size; j++)
1351             out[j] |= rotated_mac[i] & constant_time_eq_8(j, rotate_offset);
1352         rotate_offset++;
1353         rotate_offset &= constant_time_lt(rotate_offset, md_size);
1354     }
1355 #endif
1356 }
1357
1358 int dtls1_process_record(SSL *s)
1359 {
1360     int i, al;
1361     int enc_err;
1362     SSL_SESSION *sess;
1363     SSL3_RECORD *rr;
1364     unsigned int mac_size;
1365     unsigned char md[EVP_MAX_MD_SIZE];
1366
1367     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1368     sess = s->session;
1369
1370     /*
1371      * At this point, s->packet_length == SSL3_RT_HEADER_LNGTH + rr->length,
1372      * and we have that many bytes in s->packet
1373      */
1374     rr->input = &(RECORD_LAYER_get_packet(&s->rlayer)[DTLS1_RT_HEADER_LENGTH]);
1375
1376     /*
1377      * ok, we can now read from 's->packet' data into 'rr' rr->input points
1378      * at rr->length bytes, which need to be copied into rr->data by either
1379      * the decryption or by the decompression When the data is 'copied' into
1380      * the rr->data buffer, rr->input will be pointed at the new buffer
1381      */
1382
1383     /*
1384      * We now have - encrypted [ MAC [ compressed [ plain ] ] ] rr->length
1385      * bytes of encrypted compressed stuff.
1386      */
1387
1388     /* check is not needed I believe */
1389     if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1390         al = SSL_AD_RECORD_OVERFLOW;
1391         SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
1392         goto f_err;
1393     }
1394
1395     /* decrypt in place in 'rr->input' */
1396     rr->data = rr->input;
1397     rr->orig_len = rr->length;
1398
1399     enc_err = s->method->ssl3_enc->enc(s, rr, 1, 0);
1400     /*-
1401      * enc_err is:
1402      *    0: (in non-constant time) if the record is publically invalid.
1403      *    1: if the padding is valid
1404      *   -1: if the padding is invalid
1405      */
1406     if (enc_err == 0) {
1407         /* For DTLS we simply ignore bad packets. */
1408         rr->length = 0;
1409         RECORD_LAYER_reset_packet_length(&s->rlayer);
1410         goto err;
1411     }
1412 #ifdef SSL_DEBUG
1413     printf("dec %d\n", rr->length);
1414     {
1415         unsigned int z;
1416         for (z = 0; z < rr->length; z++)
1417             printf("%02X%c", rr->data[z], ((z + 1) % 16) ? ' ' : '\n');
1418     }
1419     printf("\n");
1420 #endif
1421
1422     /* r->length is now the compressed data plus mac */
1423     if ((sess != NULL) &&
1424         (s->enc_read_ctx != NULL) && (EVP_MD_CTX_md(s->read_hash) != NULL)) {
1425         /* s->read_hash != NULL => mac_size != -1 */
1426         unsigned char *mac = NULL;
1427         unsigned char mac_tmp[EVP_MAX_MD_SIZE];
1428         mac_size = EVP_MD_CTX_size(s->read_hash);
1429         OPENSSL_assert(mac_size <= EVP_MAX_MD_SIZE);
1430
1431         /*
1432          * orig_len is the length of the record before any padding was
1433          * removed. This is public information, as is the MAC in use,
1434          * therefore we can safely process the record in a different amount
1435          * of time if it's too short to possibly contain a MAC.
1436          */
1437         if (rr->orig_len < mac_size ||
1438             /* CBC records must have a padding length byte too. */
1439             (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE &&
1440              rr->orig_len < mac_size + 1)) {
1441             al = SSL_AD_DECODE_ERROR;
1442             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_LENGTH_TOO_SHORT);
1443             goto f_err;
1444         }
1445
1446         if (EVP_CIPHER_CTX_mode(s->enc_read_ctx) == EVP_CIPH_CBC_MODE) {
1447             /*
1448              * We update the length so that the TLS header bytes can be
1449              * constructed correctly but we need to extract the MAC in
1450              * constant time from within the record, without leaking the
1451              * contents of the padding bytes.
1452              */
1453             mac = mac_tmp;
1454             ssl3_cbc_copy_mac(mac_tmp, rr, mac_size);
1455             rr->length -= mac_size;
1456         } else {
1457             /*
1458              * In this case there's no padding, so |rec->orig_len| equals
1459              * |rec->length| and we checked that there's enough bytes for
1460              * |mac_size| above.
1461              */
1462             rr->length -= mac_size;
1463             mac = &rr->data[rr->length];
1464         }
1465
1466         i = s->method->ssl3_enc->mac(s, rr, md, 0 /* not send */ );
1467         if (i < 0 || mac == NULL
1468             || CRYPTO_memcmp(md, mac, (size_t)mac_size) != 0)
1469             enc_err = -1;
1470         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH + mac_size)
1471             enc_err = -1;
1472     }
1473
1474     if (enc_err < 0) {
1475         /* decryption failed, silently discard message */
1476         rr->length = 0;
1477         RECORD_LAYER_reset_packet_length(&s->rlayer);
1478         goto err;
1479     }
1480
1481     /* r->length is now just compressed */
1482     if (s->expand != NULL) {
1483         if (rr->length > SSL3_RT_MAX_COMPRESSED_LENGTH) {
1484             al = SSL_AD_RECORD_OVERFLOW;
1485             SSLerr(SSL_F_DTLS1_PROCESS_RECORD,
1486                    SSL_R_COMPRESSED_LENGTH_TOO_LONG);
1487             goto f_err;
1488         }
1489         if (!ssl3_do_uncompress(s, rr)) {
1490             al = SSL_AD_DECOMPRESSION_FAILURE;
1491             SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_BAD_DECOMPRESSION);
1492             goto f_err;
1493         }
1494     }
1495
1496     if (rr->length > SSL3_RT_MAX_PLAIN_LENGTH) {
1497         al = SSL_AD_RECORD_OVERFLOW;
1498         SSLerr(SSL_F_DTLS1_PROCESS_RECORD, SSL_R_DATA_LENGTH_TOO_LONG);
1499         goto f_err;
1500     }
1501
1502     rr->off = 0;
1503     /*-
1504      * So at this point the following is true
1505      * ssl->s3->rrec.type   is the type of record
1506      * ssl->s3->rrec.length == number of bytes in record
1507      * ssl->s3->rrec.off    == offset to first valid byte
1508      * ssl->s3->rrec.data   == where to take bytes from, increment
1509      *                         after use :-).
1510      */
1511
1512     /* we have pulled in a full packet so zero things */
1513     RECORD_LAYER_reset_packet_length(&s->rlayer);
1514     return (1);
1515
1516  f_err:
1517     ssl3_send_alert(s, SSL3_AL_FATAL, al);
1518  err:
1519     return (0);
1520 }
1521
1522
1523 /*
1524  * retrieve a buffered record that belongs to the current epoch, ie,
1525  * processed
1526  */
1527 #define dtls1_get_processed_record(s) \
1528                    dtls1_retrieve_buffered_record((s), \
1529                    &(DTLS_RECORD_LAYER_get_processed_rcds(&s->rlayer)))
1530
1531 /*-
1532  * Call this to get a new input record.
1533  * It will return <= 0 if more data is needed, normally due to an error
1534  * or non-blocking IO.
1535  * When it finishes, one packet has been decoded and can be found in
1536  * ssl->s3->rrec.type    - is the type of record
1537  * ssl->s3->rrec.data,   - data
1538  * ssl->s3->rrec.length, - number of bytes
1539  */
1540 /* used only by dtls1_read_bytes */
1541 int dtls1_get_record(SSL *s)
1542 {
1543     int ssl_major, ssl_minor;
1544     int i, n;
1545     SSL3_RECORD *rr;
1546     unsigned char *p = NULL;
1547     unsigned short version;
1548     DTLS1_BITMAP *bitmap;
1549     unsigned int is_next_epoch;
1550
1551     rr = RECORD_LAYER_get_rrec(&s->rlayer);
1552
1553     /*
1554      * The epoch may have changed.  If so, process all the pending records.
1555      * This is a non-blocking operation.
1556      */
1557     if (dtls1_process_buffered_records(s) < 0)
1558         return -1;
1559
1560     /* if we're renegotiating, then there may be buffered records */
1561     if (dtls1_get_processed_record(s))
1562         return 1;
1563
1564     /* get something from the wire */
1565  again:
1566     /* check if we have the header */
1567     if ((RECORD_LAYER_get_rstate(&s->rlayer) != SSL_ST_READ_BODY) ||
1568         (RECORD_LAYER_get_packet_length(&s->rlayer) < DTLS1_RT_HEADER_LENGTH)) {
1569         n = ssl3_read_n(s, DTLS1_RT_HEADER_LENGTH,
1570             SSL3_BUFFER_get_len(&s->rlayer.rbuf), 0, 1);
1571         /* read timeout is handled by dtls1_read_bytes */
1572         if (n <= 0)
1573             return (n);         /* error or non-blocking */
1574
1575         /* this packet contained a partial record, dump it */
1576         if (RECORD_LAYER_get_packet_length(&s->rlayer) != DTLS1_RT_HEADER_LENGTH) {
1577             RECORD_LAYER_reset_packet_length(&s->rlayer);
1578             goto again;
1579         }
1580
1581         RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_BODY);
1582
1583         p = RECORD_LAYER_get_packet(&s->rlayer);
1584
1585         if (s->msg_callback)
1586             s->msg_callback(0, 0, SSL3_RT_HEADER, p, DTLS1_RT_HEADER_LENGTH,
1587                             s, s->msg_callback_arg);
1588
1589         /* Pull apart the header into the DTLS1_RECORD */
1590         rr->type = *(p++);
1591         ssl_major = *(p++);
1592         ssl_minor = *(p++);
1593         version = (ssl_major << 8) | ssl_minor;
1594
1595         /* sequence number is 64 bits, with top 2 bytes = epoch */
1596         n2s(p, rr->epoch);
1597
1598         memcpy(&(RECORD_LAYER_get_read_sequence(&s->rlayer)[2]), p, 6);
1599         p += 6;
1600
1601         n2s(p, rr->length);
1602
1603         /* Lets check version */
1604         if (!s->first_packet) {
1605             if (version != s->version) {
1606                 /* unexpected version, silently discard */
1607                 rr->length = 0;
1608                 RECORD_LAYER_reset_packet_length(&s->rlayer);
1609                 goto again;
1610             }
1611         }
1612
1613         if ((version & 0xff00) != (s->version & 0xff00)) {
1614             /* wrong version, silently discard record */
1615             rr->length = 0;
1616             RECORD_LAYER_reset_packet_length(&s->rlayer);
1617             goto again;
1618         }
1619
1620         if (rr->length > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
1621             /* record too long, silently discard it */
1622             rr->length = 0;
1623             RECORD_LAYER_reset_packet_length(&s->rlayer);
1624             goto again;
1625         }
1626
1627         /* now s->rlayer.rstate == SSL_ST_READ_BODY */
1628     }
1629
1630     /* s->rlayer.rstate == SSL_ST_READ_BODY, get and decode the data */
1631
1632     if (rr->length >
1633         RECORD_LAYER_get_packet_length(&s->rlayer) - DTLS1_RT_HEADER_LENGTH) {
1634         /* now s->packet_length == DTLS1_RT_HEADER_LENGTH */
1635         i = rr->length;
1636         n = ssl3_read_n(s, i, i, 1, 1);
1637         /* this packet contained a partial record, dump it */
1638         if (n != i) {
1639             rr->length = 0;
1640             RECORD_LAYER_reset_packet_length(&s->rlayer);
1641             goto again;
1642         }
1643
1644         /*
1645          * now n == rr->length, and s->packet_length ==
1646          * DTLS1_RT_HEADER_LENGTH + rr->length
1647          */
1648     }
1649     /* set state for later operations */
1650     RECORD_LAYER_set_rstate(&s->rlayer, SSL_ST_READ_HEADER);
1651
1652     /* match epochs.  NULL means the packet is dropped on the floor */
1653     bitmap = dtls1_get_bitmap(s, rr, &is_next_epoch);
1654     if (bitmap == NULL) {
1655         rr->length = 0;
1656         RECORD_LAYER_reset_packet_length(&s->rlayer);   /* dump this record */
1657         goto again;             /* get another record */
1658     }
1659 #ifndef OPENSSL_NO_SCTP
1660     /* Only do replay check if no SCTP bio */
1661     if (!BIO_dgram_is_sctp(SSL_get_rbio(s))) {
1662 #endif
1663         /* Check whether this is a repeat, or aged record. */
1664         if (!dtls1_record_replay_check(s, bitmap)) {
1665             rr->length = 0;
1666             RECORD_LAYER_reset_packet_length(&s->rlayer); /* dump this record */
1667             goto again;         /* get another record */
1668         }
1669 #ifndef OPENSSL_NO_SCTP
1670     }
1671 #endif
1672
1673     /* just read a 0 length packet */
1674     if (rr->length == 0)
1675         goto again;
1676
1677     /*
1678      * If this record is from the next epoch (either HM or ALERT), and a
1679      * handshake is currently in progress, buffer it since it cannot be
1680      * processed at this time.
1681      */
1682     if (is_next_epoch) {
1683         if ((SSL_in_init(s) || ossl_statem_get_in_handshake(s))) {
1684             if (dtls1_buffer_record
1685                 (s, &(DTLS_RECORD_LAYER_get_unprocessed_rcds(&s->rlayer)),
1686                 rr->seq_num) < 0)
1687                 return -1;
1688             /* Mark receipt of record. */
1689             dtls1_record_bitmap_update(s, bitmap);
1690         }
1691         rr->length = 0;
1692         RECORD_LAYER_reset_packet_length(&s->rlayer);
1693         goto again;
1694     }
1695
1696     if (!dtls1_process_record(s)) {
1697         rr->length = 0;
1698         RECORD_LAYER_reset_packet_length(&s->rlayer);   /* dump this record */
1699         goto again;             /* get another record */
1700     }
1701     dtls1_record_bitmap_update(s, bitmap); /* Mark receipt of record. */
1702
1703     return (1);
1704
1705 }