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