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