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 #include <string.h>
113 
114 #include <openssl/bytestring.h>
115 #include <openssl/err.h>
116 #include <openssl/mem.h>
117 
118 #include "internal.h"
119 #include "../crypto/internal.h"
120 
121 
122 /* kMaxEmptyRecords is the number of consecutive, empty records that will be
123  * processed. Without this limit an attacker could send empty records at a
124  * faster rate than we can process and cause record processing to loop
125  * forever. */
126 static const uint8_t kMaxEmptyRecords = 32;
127 
128 /* kMaxWarningAlerts is the number of consecutive warning alerts that will be
129  * processed. */
130 static const uint8_t kMaxWarningAlerts = 4;
131 
132 /* ssl_needs_record_splitting returns one if |ssl|'s current outgoing cipher
133  * state needs record-splitting and zero otherwise. */
ssl_needs_record_splitting(const SSL * ssl)134 static int ssl_needs_record_splitting(const SSL *ssl) {
135   return ssl->s3->aead_write_ctx != NULL &&
136          ssl3_protocol_version(ssl) < TLS1_1_VERSION &&
137          (ssl->mode & SSL_MODE_CBC_RECORD_SPLITTING) != 0 &&
138          SSL_CIPHER_is_block_cipher(ssl->s3->aead_write_ctx->cipher);
139 }
140 
ssl_record_sequence_update(uint8_t * seq,size_t seq_len)141 int ssl_record_sequence_update(uint8_t *seq, size_t seq_len) {
142   size_t i;
143   for (i = seq_len - 1; i < seq_len; i--) {
144     ++seq[i];
145     if (seq[i] != 0) {
146       return 1;
147     }
148   }
149   OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
150   return 0;
151 }
152 
ssl_record_prefix_len(const SSL * ssl)153 size_t ssl_record_prefix_len(const SSL *ssl) {
154   if (SSL_IS_DTLS(ssl)) {
155     return DTLS1_RT_HEADER_LENGTH +
156            SSL_AEAD_CTX_explicit_nonce_len(ssl->s3->aead_read_ctx);
157   } else {
158     return SSL3_RT_HEADER_LENGTH +
159            SSL_AEAD_CTX_explicit_nonce_len(ssl->s3->aead_read_ctx);
160   }
161 }
162 
ssl_seal_align_prefix_len(const SSL * ssl)163 size_t ssl_seal_align_prefix_len(const SSL *ssl) {
164   if (SSL_IS_DTLS(ssl)) {
165     return DTLS1_RT_HEADER_LENGTH +
166            SSL_AEAD_CTX_explicit_nonce_len(ssl->s3->aead_write_ctx);
167   } else {
168     size_t ret = SSL3_RT_HEADER_LENGTH +
169                  SSL_AEAD_CTX_explicit_nonce_len(ssl->s3->aead_write_ctx);
170     if (ssl_needs_record_splitting(ssl)) {
171       ret += SSL3_RT_HEADER_LENGTH;
172       ret += ssl_cipher_get_record_split_len(ssl->s3->aead_write_ctx->cipher);
173     }
174     return ret;
175   }
176 }
177 
ssl_max_seal_overhead(const SSL * ssl)178 size_t ssl_max_seal_overhead(const SSL *ssl) {
179   size_t ret = SSL_AEAD_CTX_max_overhead(ssl->s3->aead_write_ctx);
180   if (SSL_IS_DTLS(ssl)) {
181     ret += DTLS1_RT_HEADER_LENGTH;
182   } else {
183     ret += SSL3_RT_HEADER_LENGTH;
184   }
185   /* TLS 1.3 needs an extra byte for the encrypted record type. */
186   if (ssl->s3->have_version &&
187       ssl3_protocol_version(ssl) >= TLS1_3_VERSION) {
188     ret += 1;
189   }
190   if (!SSL_IS_DTLS(ssl) && ssl_needs_record_splitting(ssl)) {
191     ret *= 2;
192   }
193   return ret;
194 }
195 
tls_open_record(SSL * ssl,uint8_t * out_type,CBS * out,size_t * out_consumed,uint8_t * out_alert,uint8_t * in,size_t in_len)196 enum ssl_open_record_t tls_open_record(SSL *ssl, uint8_t *out_type, CBS *out,
197                                        size_t *out_consumed, uint8_t *out_alert,
198                                        uint8_t *in, size_t in_len) {
199   *out_consumed = 0;
200 
201   CBS cbs;
202   CBS_init(&cbs, in, in_len);
203 
204   /* Decode the record header. */
205   uint8_t type;
206   uint16_t version, ciphertext_len;
207   if (!CBS_get_u8(&cbs, &type) ||
208       !CBS_get_u16(&cbs, &version) ||
209       !CBS_get_u16(&cbs, &ciphertext_len)) {
210     *out_consumed = SSL3_RT_HEADER_LENGTH;
211     return ssl_open_record_partial;
212   }
213 
214   /* Check that the major version in the record matches. As of TLS 1.3, the
215    * minor version is no longer checked. */
216   if ((version >> 8) != SSL3_VERSION_MAJOR) {
217     OPENSSL_PUT_ERROR(SSL, SSL_R_WRONG_VERSION_NUMBER);
218     *out_alert = SSL_AD_PROTOCOL_VERSION;
219     return ssl_open_record_error;
220   }
221 
222   /* Check the ciphertext length. */
223   if (ciphertext_len > SSL3_RT_MAX_ENCRYPTED_LENGTH) {
224     OPENSSL_PUT_ERROR(SSL, SSL_R_ENCRYPTED_LENGTH_TOO_LONG);
225     *out_alert = SSL_AD_RECORD_OVERFLOW;
226     return ssl_open_record_error;
227   }
228 
229   /* Extract the body. */
230   CBS body;
231   if (!CBS_get_bytes(&cbs, &body, ciphertext_len)) {
232     *out_consumed = SSL3_RT_HEADER_LENGTH + (size_t)ciphertext_len;
233     return ssl_open_record_partial;
234   }
235 
236   ssl_do_msg_callback(ssl, 0 /* read */, 0, SSL3_RT_HEADER, in,
237                       SSL3_RT_HEADER_LENGTH);
238 
239   /* Decrypt the body in-place. */
240   if (!SSL_AEAD_CTX_open(ssl->s3->aead_read_ctx, out, type, version,
241                          ssl->s3->read_sequence, (uint8_t *)CBS_data(&body),
242                          CBS_len(&body))) {
243     OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
244     *out_alert = SSL_AD_BAD_RECORD_MAC;
245     return ssl_open_record_error;
246   }
247   *out_consumed = in_len - CBS_len(&cbs);
248 
249   if (!ssl_record_sequence_update(ssl->s3->read_sequence, 8)) {
250     *out_alert = SSL_AD_INTERNAL_ERROR;
251     return ssl_open_record_error;
252   }
253 
254   /* TLS 1.3 hides the record type inside the encrypted data. */
255   if (ssl->s3->have_version &&
256       ssl3_protocol_version(ssl) >= TLS1_3_VERSION &&
257       ssl->s3->aead_read_ctx != NULL) {
258     do {
259       if (!CBS_get_last_u8(out, &type)) {
260         OPENSSL_PUT_ERROR(SSL, SSL_R_DECRYPTION_FAILED_OR_BAD_RECORD_MAC);
261         *out_alert = SSL_AD_DECRYPT_ERROR;
262         return ssl_open_record_error;
263       }
264     } while (type == 0);
265   }
266 
267   /* Check the plaintext length. */
268   if (CBS_len(out) > SSL3_RT_MAX_PLAIN_LENGTH) {
269     OPENSSL_PUT_ERROR(SSL, SSL_R_DATA_LENGTH_TOO_LONG);
270     *out_alert = SSL_AD_RECORD_OVERFLOW;
271     return ssl_open_record_error;
272   }
273 
274   /* Limit the number of consecutive empty records. */
275   if (CBS_len(out) == 0) {
276     ssl->s3->empty_record_count++;
277     if (ssl->s3->empty_record_count > kMaxEmptyRecords) {
278       OPENSSL_PUT_ERROR(SSL, SSL_R_TOO_MANY_EMPTY_FRAGMENTS);
279       *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
280       return ssl_open_record_error;
281     }
282     /* Apart from the limit, empty records are returned up to the caller. This
283      * allows the caller to reject records of the wrong type. */
284   } else {
285     ssl->s3->empty_record_count = 0;
286   }
287 
288   if (type == SSL3_RT_ALERT) {
289     return ssl_process_alert(ssl, out_alert, CBS_data(out), CBS_len(out));
290   }
291 
292   ssl->s3->warning_alert_count = 0;
293 
294   *out_type = type;
295   return ssl_open_record_success;
296 }
297 
do_seal_record(SSL * ssl,uint8_t * out,size_t * out_len,size_t max_out,uint8_t type,const uint8_t * in,size_t in_len)298 static int do_seal_record(SSL *ssl, uint8_t *out, size_t *out_len,
299                           size_t max_out, uint8_t type, const uint8_t *in,
300                           size_t in_len) {
301   if (max_out < SSL3_RT_HEADER_LENGTH) {
302     OPENSSL_PUT_ERROR(SSL, SSL_R_BUFFER_TOO_SMALL);
303     return 0;
304   }
305 
306   /* Either |in| and |out| don't alias or |in| aligns with the
307    * ciphertext. |tls_seal_record| forbids aliasing, but TLS 1.3 aliases them
308    * internally. */
309   assert(!buffers_alias(in, in_len, out, max_out) ||
310          in ==
311              out + SSL3_RT_HEADER_LENGTH +
312                  SSL_AEAD_CTX_explicit_nonce_len(ssl->s3->aead_write_ctx));
313 
314   out[0] = type;
315 
316   /* The TLS record-layer version number is meaningless and, starting in
317    * TLS 1.3, is frozen at TLS 1.0. But for historical reasons, SSL 3.0
318    * ClientHellos should use SSL 3.0 and pre-TLS-1.3 expects the version
319    * to change after version negotiation. */
320   uint16_t wire_version = TLS1_VERSION;
321   if (ssl->version == SSL3_VERSION ||
322       (ssl->s3->have_version && ssl3_protocol_version(ssl) < TLS1_3_VERSION)) {
323     wire_version = ssl->version;
324   }
325   out[1] = wire_version >> 8;
326   out[2] = wire_version & 0xff;
327 
328   size_t ciphertext_len;
329   if (!SSL_AEAD_CTX_seal(ssl->s3->aead_write_ctx, out + SSL3_RT_HEADER_LENGTH,
330                          &ciphertext_len, max_out - SSL3_RT_HEADER_LENGTH,
331                          type, wire_version, ssl->s3->write_sequence, in,
332                          in_len) ||
333       !ssl_record_sequence_update(ssl->s3->write_sequence, 8)) {
334     return 0;
335   }
336 
337   if (ciphertext_len >= 1 << 16) {
338     OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
339     return 0;
340   }
341   out[3] = ciphertext_len >> 8;
342   out[4] = ciphertext_len & 0xff;
343 
344   *out_len = SSL3_RT_HEADER_LENGTH + ciphertext_len;
345 
346   ssl_do_msg_callback(ssl, 1 /* write */, 0, SSL3_RT_HEADER, out,
347                       SSL3_RT_HEADER_LENGTH);
348   return 1;
349 }
350 
tls_seal_record(SSL * ssl,uint8_t * out,size_t * out_len,size_t max_out,uint8_t type,const uint8_t * in,size_t in_len)351 int tls_seal_record(SSL *ssl, uint8_t *out, size_t *out_len, size_t max_out,
352                     uint8_t type, const uint8_t *in, size_t in_len) {
353   if (buffers_alias(in, in_len, out, max_out)) {
354     OPENSSL_PUT_ERROR(SSL, SSL_R_OUTPUT_ALIASES_INPUT);
355     return 0;
356   }
357 
358   size_t frag_len = 0;
359 
360   /* TLS 1.3 hides the actual record type inside the encrypted data. */
361   if (ssl->s3->have_version &&
362       ssl3_protocol_version(ssl) >= TLS1_3_VERSION &&
363       ssl->s3->aead_read_ctx != NULL) {
364     size_t padding = SSL3_RT_HEADER_LENGTH + 1;
365 
366     if (in_len > in_len + padding || max_out < in_len + padding) {
367       OPENSSL_PUT_ERROR(SSL, SSL_R_BUFFER_TOO_SMALL);
368       return 0;
369     }
370 
371     memmove(out + SSL3_RT_HEADER_LENGTH, in, in_len);
372     out[SSL3_RT_HEADER_LENGTH + in_len] = type;
373     in = out + SSL3_RT_HEADER_LENGTH;
374     type = SSL3_RT_APPLICATION_DATA;
375     in_len++;
376   }
377 
378   if (type == SSL3_RT_APPLICATION_DATA && in_len > 1 &&
379       ssl_needs_record_splitting(ssl)) {
380     if (!do_seal_record(ssl, out, &frag_len, max_out, type, in, 1)) {
381       return 0;
382     }
383     in++;
384     in_len--;
385     out += frag_len;
386     max_out -= frag_len;
387 
388 #if !defined(BORINGSSL_UNSAFE_FUZZER_MODE)
389     assert(SSL3_RT_HEADER_LENGTH + ssl_cipher_get_record_split_len(
390                                        ssl->s3->aead_write_ctx->cipher) ==
391            frag_len);
392 #endif
393   }
394 
395   if (!do_seal_record(ssl, out, out_len, max_out, type, in, in_len)) {
396     return 0;
397   }
398   *out_len += frag_len;
399   return 1;
400 }
401 
ssl_set_read_state(SSL * ssl,SSL_AEAD_CTX * aead_ctx)402 void ssl_set_read_state(SSL *ssl, SSL_AEAD_CTX *aead_ctx) {
403   if (SSL_IS_DTLS(ssl)) {
404     ssl->d1->r_epoch++;
405     memset(&ssl->d1->bitmap, 0, sizeof(ssl->d1->bitmap));
406   }
407   memset(ssl->s3->read_sequence, 0, sizeof(ssl->s3->read_sequence));
408 
409   SSL_AEAD_CTX_free(ssl->s3->aead_read_ctx);
410   ssl->s3->aead_read_ctx = aead_ctx;
411 }
412 
ssl_set_write_state(SSL * ssl,SSL_AEAD_CTX * aead_ctx)413 void ssl_set_write_state(SSL *ssl, SSL_AEAD_CTX *aead_ctx) {
414   if (SSL_IS_DTLS(ssl)) {
415     ssl->d1->w_epoch++;
416     memcpy(ssl->d1->last_write_sequence, ssl->s3->write_sequence,
417            sizeof(ssl->s3->write_sequence));
418   }
419   memset(ssl->s3->write_sequence, 0, sizeof(ssl->s3->write_sequence));
420 
421   SSL_AEAD_CTX_free(ssl->s3->aead_write_ctx);
422   ssl->s3->aead_write_ctx = aead_ctx;
423 }
424 
ssl_process_alert(SSL * ssl,uint8_t * out_alert,const uint8_t * in,size_t in_len)425 enum ssl_open_record_t ssl_process_alert(SSL *ssl, uint8_t *out_alert,
426                                          const uint8_t *in, size_t in_len) {
427   /* Alerts records may not contain fragmented or multiple alerts. */
428   if (in_len != 2) {
429     *out_alert = SSL_AD_DECODE_ERROR;
430     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_ALERT);
431     return ssl_open_record_error;
432   }
433 
434   ssl_do_msg_callback(ssl, 0 /* read */, ssl->version, SSL3_RT_ALERT, in, in_len);
435 
436   const uint8_t alert_level = in[0];
437   const uint8_t alert_descr = in[1];
438 
439   uint16_t alert = (alert_level << 8) | alert_descr;
440   ssl_do_info_callback(ssl, SSL_CB_READ_ALERT, alert);
441 
442   if (alert_level == SSL3_AL_WARNING) {
443     if (alert_descr == SSL_AD_CLOSE_NOTIFY) {
444       ssl->s3->recv_shutdown = ssl_shutdown_close_notify;
445       return ssl_open_record_close_notify;
446     }
447 
448     ssl->s3->warning_alert_count++;
449     if (ssl->s3->warning_alert_count > kMaxWarningAlerts) {
450       *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
451       OPENSSL_PUT_ERROR(SSL, SSL_R_TOO_MANY_WARNING_ALERTS);
452       return ssl_open_record_error;
453     }
454     return ssl_open_record_discard;
455   }
456 
457   if (alert_level == SSL3_AL_FATAL) {
458     ssl->s3->recv_shutdown = ssl_shutdown_fatal_alert;
459     SSL_CTX_remove_session(ssl->ctx, ssl->session);
460 
461     char tmp[16];
462     OPENSSL_PUT_ERROR(SSL, SSL_AD_REASON_OFFSET + alert_descr);
463     BIO_snprintf(tmp, sizeof(tmp), "%d", alert_descr);
464     ERR_add_error_data(2, "SSL alert number ", tmp);
465     return ssl_open_record_fatal_alert;
466   }
467 
468   *out_alert = SSL_AD_ILLEGAL_PARAMETER;
469   OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_ALERT_TYPE);
470   return ssl_open_record_error;
471 }
472