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