xref: /aosp_15_r20/external/boringssl/src/ssl/s3_pkt.cc (revision 8fb009dc861624b67b6cdb62ea21f0f22d0c584b)
1 /* Copyright (C) 1995-1998 Eric Young ([email protected])
2  * All rights reserved.
3  *
4  * This package is an SSL implementation written
5  * by Eric Young ([email protected]).
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 ([email protected]).
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 ([email protected])"
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 ([email protected])"
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  *    [email protected].
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  * ([email protected]).  This product includes software written by Tim
107  * Hudson ([email protected]). */
108 
109 #include <openssl/ssl.h>
110 
111 #include <assert.h>
112 #include <limits.h>
113 #include <string.h>
114 
115 #include <algorithm>
116 
117 #include <openssl/err.h>
118 #include <openssl/evp.h>
119 #include <openssl/mem.h>
120 #include <openssl/rand.h>
121 
122 #include "../crypto/err/internal.h"
123 #include "../crypto/internal.h"
124 #include "internal.h"
125 
126 
127 BSSL_NAMESPACE_BEGIN
128 
129 static int do_tls_write(SSL *ssl, size_t *out_bytes_written, uint8_t type,
130                         Span<const uint8_t> in);
131 
tls_write_app_data(SSL * ssl,bool * out_needs_handshake,size_t * out_bytes_written,Span<const uint8_t> in)132 int tls_write_app_data(SSL *ssl, bool *out_needs_handshake,
133                        size_t *out_bytes_written, Span<const uint8_t> in) {
134   assert(ssl_can_write(ssl));
135   assert(!ssl->s3->aead_write_ctx->is_null_cipher());
136 
137   *out_needs_handshake = false;
138 
139   if (ssl->s3->write_shutdown != ssl_shutdown_none) {
140     OPENSSL_PUT_ERROR(SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
141     return -1;
142   }
143 
144   size_t total_bytes_written = ssl->s3->unreported_bytes_written;
145   if (in.size() < total_bytes_written) {
146     // This can happen if the caller disables |SSL_MODE_ENABLE_PARTIAL_WRITE|,
147     // asks us to write some input of length N, we successfully encrypt M bytes
148     // and write it, but fail to write the rest. We will report
149     // |SSL_ERROR_WANT_WRITE|. If the caller then retries with fewer than M
150     // bytes, we cannot satisfy that request. The caller is required to always
151     // retry with at least as many bytes as the previous attempt.
152     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_LENGTH);
153     return -1;
154   }
155 
156   in = in.subspan(total_bytes_written);
157 
158   const bool is_early_data_write =
159       !ssl->server && SSL_in_early_data(ssl) && ssl->s3->hs->can_early_write;
160   for (;;) {
161     size_t max_send_fragment = ssl->max_send_fragment;
162     if (is_early_data_write) {
163       SSL_HANDSHAKE *hs = ssl->s3->hs.get();
164       if (hs->early_data_written >= hs->early_session->ticket_max_early_data) {
165         ssl->s3->unreported_bytes_written = total_bytes_written;
166         hs->can_early_write = false;
167         *out_needs_handshake = true;
168         return -1;
169       }
170       max_send_fragment = std::min(
171           max_send_fragment, size_t{hs->early_session->ticket_max_early_data -
172                                     hs->early_data_written});
173     }
174 
175     const size_t to_write = std::min(max_send_fragment, in.size());
176     size_t bytes_written;
177     int ret = do_tls_write(ssl, &bytes_written, SSL3_RT_APPLICATION_DATA,
178                            in.subspan(0, to_write));
179     if (ret <= 0) {
180       ssl->s3->unreported_bytes_written = total_bytes_written;
181       return ret;
182     }
183 
184     // Note |bytes_written| may be less than |to_write| if there was a pending
185     // record from a smaller write attempt.
186     assert(bytes_written <= to_write);
187     total_bytes_written += bytes_written;
188     in = in.subspan(bytes_written);
189     if (is_early_data_write) {
190       ssl->s3->hs->early_data_written += bytes_written;
191     }
192 
193     if (in.empty() || (ssl->mode & SSL_MODE_ENABLE_PARTIAL_WRITE)) {
194       ssl->s3->unreported_bytes_written = 0;
195       *out_bytes_written = total_bytes_written;
196       return 1;
197     }
198   }
199 }
200 
201 // tls_seal_align_prefix_len returns the length of the prefix before the start
202 // of the bulk of the ciphertext when sealing a record with |ssl|. Callers may
203 // use this to align buffers.
204 //
205 // Note when TLS 1.0 CBC record-splitting is enabled, this includes the one byte
206 // record and is the offset into second record's ciphertext. Thus sealing a
207 // small record may result in a smaller output than this value.
208 //
209 // TODO(davidben): Is this alignment valuable? Record-splitting makes this a
210 // mess.
tls_seal_align_prefix_len(const SSL * ssl)211 static size_t tls_seal_align_prefix_len(const SSL *ssl) {
212   size_t ret =
213       SSL3_RT_HEADER_LENGTH + ssl->s3->aead_write_ctx->ExplicitNonceLen();
214   if (ssl_needs_record_splitting(ssl)) {
215     ret += SSL3_RT_HEADER_LENGTH;
216     ret += ssl_cipher_get_record_split_len(ssl->s3->aead_write_ctx->cipher());
217   }
218   return ret;
219 }
220 
221 // do_tls_write writes an SSL record of the given type. On success, it sets
222 // |*out_bytes_written| to number of bytes successfully written and returns one.
223 // On error, it returns a value <= 0 from the underlying |BIO|.
do_tls_write(SSL * ssl,size_t * out_bytes_written,uint8_t type,Span<const uint8_t> in)224 static int do_tls_write(SSL *ssl, size_t *out_bytes_written, uint8_t type,
225                         Span<const uint8_t> in) {
226   // If there is a pending write, the retry must be consistent.
227   if (!ssl->s3->pending_write.empty() &&
228       (ssl->s3->pending_write.size() > in.size() ||
229        (!(ssl->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER) &&
230         ssl->s3->pending_write.data() != in.data()) ||
231        ssl->s3->pending_write_type != type)) {
232     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_WRITE_RETRY);
233     return -1;
234   }
235 
236   // Flush any unwritten data to the transport. There may be data to flush even
237   // if |wpend_tot| is zero.
238   int ret = ssl_write_buffer_flush(ssl);
239   if (ret <= 0) {
240     return ret;
241   }
242 
243   // If there is a pending write, we just completed it. Report it to the caller.
244   if (!ssl->s3->pending_write.empty()) {
245     *out_bytes_written = ssl->s3->pending_write.size();
246     ssl->s3->pending_write = {};
247     return 1;
248   }
249 
250   SSLBuffer *buf = &ssl->s3->write_buffer;
251   if (in.size() > SSL3_RT_MAX_PLAIN_LENGTH || buf->size() > 0) {
252     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
253     return -1;
254   }
255 
256   if (!tls_flush_pending_hs_data(ssl)) {
257     return -1;
258   }
259 
260   // We may have unflushed handshake data that must be written before |in|. This
261   // may be a KeyUpdate acknowledgment, 0-RTT key change messages, or a
262   // NewSessionTicket.
263   Span<const uint8_t> pending_flight;
264   if (ssl->s3->pending_flight != nullptr) {
265     pending_flight = MakeConstSpan(
266         reinterpret_cast<const uint8_t *>(ssl->s3->pending_flight->data),
267         ssl->s3->pending_flight->length);
268     pending_flight = pending_flight.subspan(ssl->s3->pending_flight_offset);
269   }
270 
271   size_t max_out = pending_flight.size();
272   if (!in.empty()) {
273     const size_t max_ciphertext_len = in.size() + SSL_max_seal_overhead(ssl);
274     if (max_ciphertext_len < in.size() ||
275         max_out + max_ciphertext_len < max_out) {
276       OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
277       return -1;
278     }
279     max_out += max_ciphertext_len;
280   }
281 
282   if (max_out == 0) {
283     // Nothing to write.
284     *out_bytes_written = 0;
285     return 1;
286   }
287 
288   if (!buf->EnsureCap(pending_flight.size() + tls_seal_align_prefix_len(ssl),
289                       max_out)) {
290     return -1;
291   }
292 
293   // Copy |pending_flight| to the output.
294   if (!pending_flight.empty()) {
295     OPENSSL_memcpy(buf->remaining().data(), pending_flight.data(),
296                    pending_flight.size());
297     ssl->s3->pending_flight.reset();
298     ssl->s3->pending_flight_offset = 0;
299     buf->DidWrite(pending_flight.size());
300   }
301 
302   if (!in.empty()) {
303     size_t ciphertext_len;
304     if (!tls_seal_record(ssl, buf->remaining().data(), &ciphertext_len,
305                          buf->remaining().size(), type, in.data(), in.size())) {
306       return -1;
307     }
308     buf->DidWrite(ciphertext_len);
309   }
310 
311   // Now that we've made progress on the connection, uncork KeyUpdate
312   // acknowledgments.
313   ssl->s3->key_update_pending = false;
314 
315   // Flush the write buffer.
316   ret = ssl_write_buffer_flush(ssl);
317   if (ret <= 0) {
318     // Track the unfinished write.
319     if (!in.empty()) {
320       ssl->s3->pending_write = in;
321       ssl->s3->pending_write_type = type;
322     }
323     return ret;
324   }
325 
326   *out_bytes_written = in.size();
327   return 1;
328 }
329 
tls_open_app_data(SSL * ssl,Span<uint8_t> * out,size_t * out_consumed,uint8_t * out_alert,Span<uint8_t> in)330 ssl_open_record_t tls_open_app_data(SSL *ssl, Span<uint8_t> *out,
331                                     size_t *out_consumed, uint8_t *out_alert,
332                                     Span<uint8_t> in) {
333   assert(ssl_can_read(ssl));
334   assert(!ssl->s3->aead_read_ctx->is_null_cipher());
335 
336   uint8_t type;
337   Span<uint8_t> body;
338   auto ret = tls_open_record(ssl, &type, &body, out_consumed, out_alert, in);
339   if (ret != ssl_open_record_success) {
340     return ret;
341   }
342 
343   const bool is_early_data_read = ssl->server && SSL_in_early_data(ssl);
344 
345   if (type == SSL3_RT_HANDSHAKE) {
346     // Post-handshake data prior to TLS 1.3 is always renegotiation, which we
347     // never accept as a server. Otherwise |tls_get_message| will send
348     // |SSL_R_EXCESSIVE_MESSAGE_SIZE|.
349     if (ssl->server && ssl_protocol_version(ssl) < TLS1_3_VERSION) {
350       OPENSSL_PUT_ERROR(SSL, SSL_R_NO_RENEGOTIATION);
351       *out_alert = SSL_AD_NO_RENEGOTIATION;
352       return ssl_open_record_error;
353     }
354 
355     if (!tls_append_handshake_data(ssl, body)) {
356       *out_alert = SSL_AD_INTERNAL_ERROR;
357       return ssl_open_record_error;
358     }
359     return ssl_open_record_discard;
360   }
361 
362   if (type != SSL3_RT_APPLICATION_DATA) {
363     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
364     *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
365     return ssl_open_record_error;
366   }
367 
368   if (is_early_data_read) {
369     if (body.size() > kMaxEarlyDataAccepted - ssl->s3->hs->early_data_read) {
370       OPENSSL_PUT_ERROR(SSL, SSL_R_TOO_MUCH_READ_EARLY_DATA);
371       *out_alert = SSL3_AD_UNEXPECTED_MESSAGE;
372       return ssl_open_record_error;
373     }
374 
375     ssl->s3->hs->early_data_read += body.size();
376   }
377 
378   if (body.empty()) {
379     return ssl_open_record_discard;
380   }
381 
382   *out = body;
383   return ssl_open_record_success;
384 }
385 
tls_open_change_cipher_spec(SSL * ssl,size_t * out_consumed,uint8_t * out_alert,Span<uint8_t> in)386 ssl_open_record_t tls_open_change_cipher_spec(SSL *ssl, size_t *out_consumed,
387                                               uint8_t *out_alert,
388                                               Span<uint8_t> in) {
389   uint8_t type;
390   Span<uint8_t> body;
391   auto ret = tls_open_record(ssl, &type, &body, out_consumed, out_alert, in);
392   if (ret != ssl_open_record_success) {
393     return ret;
394   }
395 
396   if (type != SSL3_RT_CHANGE_CIPHER_SPEC) {
397     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
398     *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
399     return ssl_open_record_error;
400   }
401 
402   if (body.size() != 1 || body[0] != SSL3_MT_CCS) {
403     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_CHANGE_CIPHER_SPEC);
404     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
405     return ssl_open_record_error;
406   }
407 
408   ssl_do_msg_callback(ssl, 0 /* read */, SSL3_RT_CHANGE_CIPHER_SPEC, body);
409   return ssl_open_record_success;
410 }
411 
ssl_send_alert(SSL * ssl,int level,int desc)412 void ssl_send_alert(SSL *ssl, int level, int desc) {
413   // This function is called in response to a fatal error from the peer. Ignore
414   // any failures writing the alert and report only the original error. In
415   // particular, if the transport uses |SSL_write|, our existing error will be
416   // clobbered so we must save and restore the error queue. See
417   // https://crbug.com/959305.
418   //
419   // TODO(davidben): Return the alert out of the handshake, rather than calling
420   // this function internally everywhere.
421   //
422   // TODO(davidben): This does not allow retrying if the alert hit EAGAIN. See
423   // https://crbug.com/boringssl/130.
424   UniquePtr<ERR_SAVE_STATE> err_state(ERR_save_state());
425   ssl_send_alert_impl(ssl, level, desc);
426   ERR_restore_state(err_state.get());
427 }
428 
ssl_send_alert_impl(SSL * ssl,int level,int desc)429 int ssl_send_alert_impl(SSL *ssl, int level, int desc) {
430   // It is illegal to send an alert when we've already sent a closing one.
431   if (ssl->s3->write_shutdown != ssl_shutdown_none) {
432     OPENSSL_PUT_ERROR(SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
433     return -1;
434   }
435 
436   if (level == SSL3_AL_WARNING && desc == SSL_AD_CLOSE_NOTIFY) {
437     ssl->s3->write_shutdown = ssl_shutdown_close_notify;
438   } else {
439     assert(level == SSL3_AL_FATAL);
440     assert(desc != SSL_AD_CLOSE_NOTIFY);
441     ssl->s3->write_shutdown = ssl_shutdown_error;
442   }
443 
444   ssl->s3->alert_dispatch = true;
445   ssl->s3->send_alert[0] = level;
446   ssl->s3->send_alert[1] = desc;
447   if (ssl->s3->write_buffer.empty()) {
448     // Nothing is being written out, so the alert may be dispatched
449     // immediately.
450     return ssl->method->dispatch_alert(ssl);
451   }
452 
453   // The alert will be dispatched later.
454   return -1;
455 }
456 
tls_dispatch_alert(SSL * ssl)457 int tls_dispatch_alert(SSL *ssl) {
458   if (ssl->quic_method) {
459     if (!ssl->quic_method->send_alert(ssl, ssl->s3->write_level,
460                                       ssl->s3->send_alert[1])) {
461       OPENSSL_PUT_ERROR(SSL, SSL_R_QUIC_INTERNAL_ERROR);
462       return 0;
463     }
464   } else {
465     size_t bytes_written;
466     int ret =
467         do_tls_write(ssl, &bytes_written, SSL3_RT_ALERT, ssl->s3->send_alert);
468     if (ret <= 0) {
469       return ret;
470     }
471     assert(bytes_written == 2);
472   }
473 
474   ssl->s3->alert_dispatch = false;
475 
476   // If the alert is fatal, flush the BIO now.
477   if (ssl->s3->send_alert[0] == SSL3_AL_FATAL) {
478     BIO_flush(ssl->wbio.get());
479   }
480 
481   ssl_do_msg_callback(ssl, 1 /* write */, SSL3_RT_ALERT, ssl->s3->send_alert);
482 
483   int alert = (ssl->s3->send_alert[0] << 8) | ssl->s3->send_alert[1];
484   ssl_do_info_callback(ssl, SSL_CB_WRITE_ALERT, alert);
485 
486   return 1;
487 }
488 
489 BSSL_NAMESPACE_END
490