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