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