1/* Copyright (C) 1995-1998 Eric Young (eay@cryptsoft.com)
2 * All rights reserved.
3 *
4 * This package is an SSL implementation written
5 * by Eric Young (eay@cryptsoft.com).
6 * The implementation was written so as to conform with Netscapes SSL.
7 *
8 * This library is free for commercial and non-commercial use as long as
9 * the following conditions are aheared to.  The following conditions
10 * apply to all code found in this distribution, be it the RC4, RSA,
11 * lhash, DES, etc., code; not just the SSL code.  The SSL documentation
12 * included with this distribution is covered by the same copyright terms
13 * except that the holder is Tim Hudson (tjh@cryptsoft.com).
14 *
15 * Copyright remains Eric Young's, and as such any Copyright notices in
16 * the code are not to be removed.
17 * If this package is used in a product, Eric Young should be given attribution
18 * as the author of the parts of the library used.
19 * This can be in the form of a textual message at program startup or
20 * in documentation (online or textual) provided with the package.
21 *
22 * Redistribution and use in source and binary forms, with or without
23 * modification, are permitted provided that the following conditions
24 * are met:
25 * 1. Redistributions of source code must retain the copyright
26 *    notice, this list of conditions and the following disclaimer.
27 * 2. Redistributions in binary form must reproduce the above copyright
28 *    notice, this list of conditions and the following disclaimer in the
29 *    documentation and/or other materials provided with the distribution.
30 * 3. All advertising materials mentioning features or use of this software
31 *    must display the following acknowledgement:
32 *    "This product includes cryptographic software written by
33 *     Eric Young (eay@cryptsoft.com)"
34 *    The word 'cryptographic' can be left out if the rouines from the library
35 *    being used are not cryptographic related :-).
36 * 4. If you include any Windows specific code (or a derivative thereof) from
37 *    the apps directory (application code) you must include an acknowledgement:
38 *    "This product includes software written by Tim Hudson (tjh@cryptsoft.com)"
39 *
40 * THIS SOFTWARE IS PROVIDED BY ERIC YOUNG ``AS IS'' AND
41 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
42 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
43 * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
44 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
45 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
46 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
47 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
48 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
49 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
50 * SUCH DAMAGE.
51 *
52 * The licence and distribution terms for any publically available version or
53 * derivative of this code cannot be changed.  i.e. this code cannot simply be
54 * copied and put under another distribution licence
55 * [including the GNU Public Licence.]
56 */
57/* ====================================================================
58 * Copyright (c) 1998-2002 The OpenSSL Project.  All rights reserved.
59 *
60 * Redistribution and use in source and binary forms, with or without
61 * modification, are permitted provided that the following conditions
62 * are met:
63 *
64 * 1. Redistributions of source code must retain the above copyright
65 *    notice, this list of conditions and the following disclaimer.
66 *
67 * 2. Redistributions in binary form must reproduce the above copyright
68 *    notice, this list of conditions and the following disclaimer in
69 *    the documentation and/or other materials provided with the
70 *    distribution.
71 *
72 * 3. All advertising materials mentioning features or use of this
73 *    software must display the following acknowledgment:
74 *    "This product includes software developed by the OpenSSL Project
75 *    for use in the OpenSSL Toolkit. (http://www.openssl.org/)"
76 *
77 * 4. The names "OpenSSL Toolkit" and "OpenSSL Project" must not be used to
78 *    endorse or promote products derived from this software without
79 *    prior written permission. For written permission, please contact
80 *    openssl-core@openssl.org.
81 *
82 * 5. Products derived from this software may not be called "OpenSSL"
83 *    nor may "OpenSSL" appear in their names without prior written
84 *    permission of the OpenSSL Project.
85 *
86 * 6. Redistributions of any form whatsoever must retain the following
87 *    acknowledgment:
88 *    "This product includes software developed by the OpenSSL Project
89 *    for use in the OpenSSL Toolkit (http://www.openssl.org/)"
90 *
91 * THIS SOFTWARE IS PROVIDED BY THE OpenSSL PROJECT ``AS IS'' AND ANY
92 * EXPRESSED OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
93 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
94 * PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE OpenSSL PROJECT OR
95 * ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
96 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
97 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
98 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
99 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
100 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
101 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
102 * OF THE POSSIBILITY OF SUCH DAMAGE.
103 * ====================================================================
104 *
105 * This product includes cryptographic software written by Eric Young
106 * (eay@cryptsoft.com).  This product includes software written by Tim
107 * Hudson (tjh@cryptsoft.com). */
108
109#include <openssl/ssl.h>
110
111#include <assert.h>
112
113#include <openssl/bytestring.h>
114#include <openssl/err.h>
115
116#include "internal.h"
117
118
119/* kMaxEmptyRecords is the number of consecutive, empty records that will be
120 * processed. Without this limit an attacker could send empty records at a
121 * faster rate than we can process and cause record processing to loop
122 * forever. */
123static const uint8_t kMaxEmptyRecords = 32;
124
125/* ssl_needs_record_splitting returns one if |ssl|'s current outgoing cipher
126 * state needs record-splitting and zero otherwise. */
127static int ssl_needs_record_splitting(const SSL *ssl) {
128  return !SSL_USE_EXPLICIT_IV(ssl) && ssl->aead_write_ctx != NULL &&
129         (ssl->mode & SSL_MODE_CBC_RECORD_SPLITTING) != 0 &&
130         SSL_CIPHER_is_block_cipher(ssl->aead_write_ctx->cipher);
131}
132
133size_t ssl_record_prefix_len(const SSL *ssl) {
134  if (SSL_IS_DTLS(ssl)) {
135    return DTLS1_RT_HEADER_LENGTH +
136           SSL_AEAD_CTX_explicit_nonce_len(ssl->aead_read_ctx);
137  } else {
138    return SSL3_RT_HEADER_LENGTH +
139           SSL_AEAD_CTX_explicit_nonce_len(ssl->aead_read_ctx);
140  }
141}
142
143size_t ssl_seal_prefix_len(const SSL *ssl) {
144  if (SSL_IS_DTLS(ssl)) {
145    return DTLS1_RT_HEADER_LENGTH +
146           SSL_AEAD_CTX_explicit_nonce_len(ssl->aead_write_ctx);
147  } else {
148    size_t ret = SSL3_RT_HEADER_LENGTH +
149                 SSL_AEAD_CTX_explicit_nonce_len(ssl->aead_write_ctx);
150    if (ssl_needs_record_splitting(ssl)) {
151      ret += SSL3_RT_HEADER_LENGTH;
152      ret += ssl_cipher_get_record_split_len(ssl->aead_write_ctx->cipher);
153    }
154    return ret;
155  }
156}
157
158size_t ssl_max_seal_overhead(const SSL *ssl) {
159  if (SSL_IS_DTLS(ssl)) {
160    return DTLS1_RT_HEADER_LENGTH +
161           SSL_AEAD_CTX_max_overhead(ssl->aead_write_ctx);
162  } else {
163    size_t ret = SSL3_RT_HEADER_LENGTH +
164                 SSL_AEAD_CTX_max_overhead(ssl->aead_write_ctx);
165    if (ssl_needs_record_splitting(ssl)) {
166      ret *= 2;
167    }
168    return ret;
169  }
170}
171
172enum ssl_open_record_t tls_open_record(
173    SSL *ssl, uint8_t *out_type, uint8_t *out, size_t *out_len,
174    size_t *out_consumed, uint8_t *out_alert, size_t max_out, const uint8_t *in,
175    size_t in_len) {
176  CBS cbs;
177  CBS_init(&cbs, in, in_len);
178
179  /* Decode the record header. */
180  uint8_t type;
181  uint16_t version, ciphertext_len;
182  if (!CBS_get_u8(&cbs, &type) ||
183      !CBS_get_u16(&cbs, &version) ||
184      !CBS_get_u16(&cbs, &ciphertext_len)) {
185    *out_consumed = SSL3_RT_HEADER_LENGTH;
186    return ssl_open_record_partial;
187  }
188
189  /* Check the version. */
190  if ((ssl->s3->have_version && version != ssl->version) ||
191      (version >> 8) != SSL3_VERSION_MAJOR) {
192    OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_VERSION_NUMBER);
193    *out_alert = SSL_AD_PROTOCOL_VERSION;
194    return ssl_open_record_error;
195  }
196
197  /* Check the ciphertext length. */
198  if (ciphertext_len > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
199    OPENSSL_PUT_ERROR(SSL, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
200    *out_alert = SSL_AD_RECORD_OVERFLOW;
201    return ssl_open_record_error;
202  }
203
204  /* Extract the body. */
205  CBS body;
206  if (!CBS_get_bytes(&cbs, &body, ciphertext_len)) {
207    *out_consumed = SSL3_RT_HEADER_LENGTH + (size_t)ciphertext_len;
208    return ssl_open_record_partial;
209  }
210
211  if (ssl->msg_callback != NULL) {
212    ssl->msg_callback(0 /* read */, 0, SSL3_RT_HEADER, in,
213                      SSL3_RT_HEADER_LENGTH, ssl, ssl->msg_callback_arg);
214  }
215
216  /* Decrypt the body. */
217  size_t plaintext_len;
218  if (!SSL_AEAD_CTX_open(ssl->aead_read_ctx, out, &plaintext_len, max_out,
219                         type, version, ssl->s3->read_sequence, CBS_data(&body),
220                         CBS_len(&body))) {
221    OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
222    *out_alert = SSL_AD_BAD_RECORD_MAC;
223    return ssl_open_record_error;
224  }
225  if (!ssl3_record_sequence_update(ssl->s3->read_sequence, 8)) {
226    *out_alert = SSL_AD_INTERNAL_ERROR;
227    return ssl_open_record_error;
228  }
229
230  /* Check the plaintext length. */
231  if (plaintext_len > SSL3_RT_MAX_PLAIN_LENGTH) {
232    OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
233    *out_alert = SSL_AD_RECORD_OVERFLOW;
234    return ssl_open_record_error;
235  }
236
237  /* Limit the number of consecutive empty records. */
238  if (plaintext_len == 0) {
239    ssl->s3->empty_record_count++;
240    if (ssl->s3->empty_record_count > kMaxEmptyRecords) {
241      OPENSSL_PUT_ERROR(SSL, SSL_R_TOO_MANY_EMPTY_FRAGMENTS);
242      *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
243      return ssl_open_record_error;
244    }
245    /* Apart from the limit, empty records are returned up to the caller. This
246     * allows the caller to reject records of the wrong type. */
247  } else {
248    ssl->s3->empty_record_count = 0;
249  }
250
251  *out_type = type;
252  *out_len = plaintext_len;
253  *out_consumed = in_len - CBS_len(&cbs);
254  return ssl_open_record_success;
255}
256
257static int do_seal_record(SSL *ssl, uint8_t *out, size_t *out_len,
258                          size_t max_out, uint8_t type, const uint8_t *in,
259                          size_t in_len) {
260  if (max_out < SSL3_RT_HEADER_LENGTH) {
261    OPENSSL_PUT_ERROR(SSL, SSL_R_BUFFER_TOO_SMALL);
262    return 0;
263  }
264  /* Check the record header does not alias any part of the input.
265   * |SSL_AEAD_CTX_seal| will internally enforce other aliasing requirements. */
266  if (in < out + SSL3_RT_HEADER_LENGTH && out < in + in_len) {
267    OPENSSL_PUT_ERROR(SSL, SSL_R_OUTPUT_ALIASES_INPUT);
268    return 0;
269  }
270
271  out[0] = type;
272
273  /* Some servers hang if initial ClientHello is larger than 256 bytes and
274   * record version number > TLS 1.0. */
275  uint16_t wire_version = ssl->version;
276  if (!ssl->s3->have_version && ssl->version > SSL3_VERSION) {
277    wire_version = TLS1_VERSION;
278  }
279  out[1] = wire_version >> 8;
280  out[2] = wire_version & 0xff;
281
282  size_t ciphertext_len;
283  if (!SSL_AEAD_CTX_seal(ssl->aead_write_ctx, out + SSL3_RT_HEADER_LENGTH,
284                         &ciphertext_len, max_out - SSL3_RT_HEADER_LENGTH,
285                         type, wire_version, ssl->s3->write_sequence, in,
286                         in_len) ||
287      !ssl3_record_sequence_update(ssl->s3->write_sequence, 8)) {
288    return 0;
289  }
290
291  if (ciphertext_len >= 1 << 16) {
292    OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
293    return 0;
294  }
295  out[3] = ciphertext_len >> 8;
296  out[4] = ciphertext_len & 0xff;
297
298  *out_len = SSL3_RT_HEADER_LENGTH + ciphertext_len;
299
300  if (ssl->msg_callback) {
301    ssl->msg_callback(1 /* write */, 0, SSL3_RT_HEADER, out,
302                      SSL3_RT_HEADER_LENGTH, ssl, ssl->msg_callback_arg);
303  }
304
305  return 1;
306}
307
308int tls_seal_record(SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
309                    uint8_t type, const uint8_t *in, size_t in_len) {
310  size_t frag_len = 0;
311  if (type == SSL3_RT_APPLICATION_DATA && in_len > 1 &&
312      ssl_needs_record_splitting(ssl)) {
313    /* |do_seal_record| will notice if it clobbers |in[0]|, but not if it
314     * aliases the rest of |in|. */
315    if (in + 1 <= out && out < in + in_len) {
316      OPENSSL_PUT_ERROR(SSL, SSL_R_OUTPUT_ALIASES_INPUT);
317      return 0;
318    }
319    /* Ensure |do_seal_record| does not write beyond |in[0]|. */
320    size_t frag_max_out = max_out;
321    if (out <= in + 1 && in + 1 < out + frag_max_out) {
322      frag_max_out = (size_t)(in + 1 - out);
323    }
324    if (!do_seal_record(ssl, out, &frag_len, frag_max_out, type, in, 1)) {
325      return 0;
326    }
327    in++;
328    in_len--;
329    out += frag_len;
330    max_out -= frag_len;
331
332    assert(SSL3_RT_HEADER_LENGTH +
333               ssl_cipher_get_record_split_len(ssl->aead_write_ctx->cipher) ==
334           frag_len);
335  }
336
337  if (!do_seal_record(ssl, out, out_len, max_out, type, in, in_len)) {
338    return 0;
339  }
340  *out_len += frag_len;
341  return 1;
342}
343