xref: /aosp_15_r20/external/cronet/third_party/boringssl/src/ssl/s3_pkt.cc (revision 6777b5387eb2ff775bb5750e3f5d96f37fb7352b)
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 // do_tls_write writes an SSL record of the given type. On success, it sets
202 // |*out_bytes_written| to number of bytes successfully written and returns one.
203 // 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)204 static int do_tls_write(SSL *ssl, size_t *out_bytes_written, uint8_t type,
205                         Span<const uint8_t> in) {
206   // If there is a pending write, the retry must be consistent.
207   if (!ssl->s3->pending_write.empty() &&
208       (ssl->s3->pending_write.size() > in.size() ||
209        (!(ssl->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER) &&
210         ssl->s3->pending_write.data() != in.data()) ||
211        ssl->s3->pending_write_type != type)) {
212     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_WRITE_RETRY);
213     return -1;
214   }
215 
216   // Flush any unwritten data to the transport. There may be data to flush even
217   // if |wpend_tot| is zero.
218   int ret = ssl_write_buffer_flush(ssl);
219   if (ret <= 0) {
220     return ret;
221   }
222 
223   // If there is a pending write, we just completed it. Report it to the caller.
224   if (!ssl->s3->pending_write.empty()) {
225     *out_bytes_written = ssl->s3->pending_write.size();
226     ssl->s3->pending_write = {};
227     return 1;
228   }
229 
230   SSLBuffer *buf = &ssl->s3->write_buffer;
231   if (in.size() > SSL3_RT_MAX_PLAIN_LENGTH || buf->size() > 0) {
232     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
233     return -1;
234   }
235 
236   if (!tls_flush_pending_hs_data(ssl)) {
237     return -1;
238   }
239 
240   // We may have unflushed handshake data that must be written before |in|. This
241   // may be a KeyUpdate acknowledgment, 0-RTT key change messages, or a
242   // NewSessionTicket.
243   Span<const uint8_t> pending_flight;
244   if (ssl->s3->pending_flight != nullptr) {
245     pending_flight = MakeConstSpan(
246         reinterpret_cast<const uint8_t *>(ssl->s3->pending_flight->data),
247         ssl->s3->pending_flight->length);
248     pending_flight = pending_flight.subspan(ssl->s3->pending_flight_offset);
249   }
250 
251   size_t max_out = pending_flight.size();
252   if (!in.empty()) {
253     const size_t max_ciphertext_len = in.size() + SSL_max_seal_overhead(ssl);
254     if (max_ciphertext_len < in.size() ||
255         max_out + max_ciphertext_len < max_out) {
256       OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
257       return -1;
258     }
259     max_out += max_ciphertext_len;
260   }
261 
262   if (max_out == 0) {
263     // Nothing to write.
264     *out_bytes_written = 0;
265     return 1;
266   }
267 
268   if (!buf->EnsureCap(pending_flight.size() + ssl_seal_align_prefix_len(ssl),
269                       max_out)) {
270     return -1;
271   }
272 
273   // Copy |pending_flight| to the output.
274   if (!pending_flight.empty()) {
275     OPENSSL_memcpy(buf->remaining().data(), pending_flight.data(),
276                    pending_flight.size());
277     ssl->s3->pending_flight.reset();
278     ssl->s3->pending_flight_offset = 0;
279     buf->DidWrite(pending_flight.size());
280   }
281 
282   if (!in.empty()) {
283     size_t ciphertext_len;
284     if (!tls_seal_record(ssl, buf->remaining().data(), &ciphertext_len,
285                          buf->remaining().size(), type, in.data(), in.size())) {
286       return -1;
287     }
288     buf->DidWrite(ciphertext_len);
289   }
290 
291   // Now that we've made progress on the connection, uncork KeyUpdate
292   // acknowledgments.
293   ssl->s3->key_update_pending = false;
294 
295   // Flush the write buffer.
296   ret = ssl_write_buffer_flush(ssl);
297   if (ret <= 0) {
298     // Track the unfinished write.
299     if (!in.empty()) {
300       ssl->s3->pending_write = in;
301       ssl->s3->pending_write_type = type;
302     }
303     return ret;
304   }
305 
306   *out_bytes_written = in.size();
307   return 1;
308 }
309 
tls_open_app_data(SSL * ssl,Span<uint8_t> * out,size_t * out_consumed,uint8_t * out_alert,Span<uint8_t> in)310 ssl_open_record_t tls_open_app_data(SSL *ssl, Span<uint8_t> *out,
311                                     size_t *out_consumed, uint8_t *out_alert,
312                                     Span<uint8_t> in) {
313   assert(ssl_can_read(ssl));
314   assert(!ssl->s3->aead_read_ctx->is_null_cipher());
315 
316   uint8_t type;
317   Span<uint8_t> body;
318   auto ret = tls_open_record(ssl, &type, &body, out_consumed, out_alert, in);
319   if (ret != ssl_open_record_success) {
320     return ret;
321   }
322 
323   const bool is_early_data_read = ssl->server && SSL_in_early_data(ssl);
324 
325   if (type == SSL3_RT_HANDSHAKE) {
326     // Post-handshake data prior to TLS 1.3 is always renegotiation, which we
327     // never accept as a server. Otherwise |tls_get_message| will send
328     // |SSL_R_EXCESSIVE_MESSAGE_SIZE|.
329     if (ssl->server && ssl_protocol_version(ssl) < TLS1_3_VERSION) {
330       OPENSSL_PUT_ERROR(SSL, SSL_R_NO_RENEGOTIATION);
331       *out_alert = SSL_AD_NO_RENEGOTIATION;
332       return ssl_open_record_error;
333     }
334 
335     if (!tls_append_handshake_data(ssl, body)) {
336       *out_alert = SSL_AD_INTERNAL_ERROR;
337       return ssl_open_record_error;
338     }
339     return ssl_open_record_discard;
340   }
341 
342   if (type != SSL3_RT_APPLICATION_DATA) {
343     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
344     *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
345     return ssl_open_record_error;
346   }
347 
348   if (is_early_data_read) {
349     if (body.size() > kMaxEarlyDataAccepted - ssl->s3->hs->early_data_read) {
350       OPENSSL_PUT_ERROR(SSL, SSL_R_TOO_MUCH_READ_EARLY_DATA);
351       *out_alert = SSL3_AD_UNEXPECTED_MESSAGE;
352       return ssl_open_record_error;
353     }
354 
355     ssl->s3->hs->early_data_read += body.size();
356   }
357 
358   if (body.empty()) {
359     return ssl_open_record_discard;
360   }
361 
362   *out = body;
363   return ssl_open_record_success;
364 }
365 
tls_open_change_cipher_spec(SSL * ssl,size_t * out_consumed,uint8_t * out_alert,Span<uint8_t> in)366 ssl_open_record_t tls_open_change_cipher_spec(SSL *ssl, size_t *out_consumed,
367                                               uint8_t *out_alert,
368                                               Span<uint8_t> in) {
369   uint8_t type;
370   Span<uint8_t> body;
371   auto ret = tls_open_record(ssl, &type, &body, out_consumed, out_alert, in);
372   if (ret != ssl_open_record_success) {
373     return ret;
374   }
375 
376   if (type != SSL3_RT_CHANGE_CIPHER_SPEC) {
377     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
378     *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
379     return ssl_open_record_error;
380   }
381 
382   if (body.size() != 1 || body[0] != SSL3_MT_CCS) {
383     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_CHANGE_CIPHER_SPEC);
384     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
385     return ssl_open_record_error;
386   }
387 
388   ssl_do_msg_callback(ssl, 0 /* read */, SSL3_RT_CHANGE_CIPHER_SPEC, body);
389   return ssl_open_record_success;
390 }
391 
ssl_send_alert(SSL * ssl,int level,int desc)392 void ssl_send_alert(SSL *ssl, int level, int desc) {
393   // This function is called in response to a fatal error from the peer. Ignore
394   // any failures writing the alert and report only the original error. In
395   // particular, if the transport uses |SSL_write|, our existing error will be
396   // clobbered so we must save and restore the error queue. See
397   // https://crbug.com/959305.
398   //
399   // TODO(davidben): Return the alert out of the handshake, rather than calling
400   // this function internally everywhere.
401   //
402   // TODO(davidben): This does not allow retrying if the alert hit EAGAIN. See
403   // https://crbug.com/boringssl/130.
404   UniquePtr<ERR_SAVE_STATE> err_state(ERR_save_state());
405   ssl_send_alert_impl(ssl, level, desc);
406   ERR_restore_state(err_state.get());
407 }
408 
ssl_send_alert_impl(SSL * ssl,int level,int desc)409 int ssl_send_alert_impl(SSL *ssl, int level, int desc) {
410   // It is illegal to send an alert when we've already sent a closing one.
411   if (ssl->s3->write_shutdown != ssl_shutdown_none) {
412     OPENSSL_PUT_ERROR(SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
413     return -1;
414   }
415 
416   if (level == SSL3_AL_WARNING && desc == SSL_AD_CLOSE_NOTIFY) {
417     ssl->s3->write_shutdown = ssl_shutdown_close_notify;
418   } else {
419     assert(level == SSL3_AL_FATAL);
420     assert(desc != SSL_AD_CLOSE_NOTIFY);
421     ssl->s3->write_shutdown = ssl_shutdown_error;
422   }
423 
424   ssl->s3->alert_dispatch = true;
425   ssl->s3->send_alert[0] = level;
426   ssl->s3->send_alert[1] = desc;
427   if (ssl->s3->write_buffer.empty()) {
428     // Nothing is being written out, so the alert may be dispatched
429     // immediately.
430     return ssl->method->dispatch_alert(ssl);
431   }
432 
433   // The alert will be dispatched later.
434   return -1;
435 }
436 
tls_dispatch_alert(SSL * ssl)437 int tls_dispatch_alert(SSL *ssl) {
438   if (ssl->quic_method) {
439     if (!ssl->quic_method->send_alert(ssl, ssl->s3->write_level,
440                                       ssl->s3->send_alert[1])) {
441       OPENSSL_PUT_ERROR(SSL, SSL_R_QUIC_INTERNAL_ERROR);
442       return 0;
443     }
444   } else {
445     size_t bytes_written;
446     int ret =
447         do_tls_write(ssl, &bytes_written, SSL3_RT_ALERT, ssl->s3->send_alert);
448     if (ret <= 0) {
449       return ret;
450     }
451     assert(bytes_written == 2);
452   }
453 
454   ssl->s3->alert_dispatch = false;
455 
456   // If the alert is fatal, flush the BIO now.
457   if (ssl->s3->send_alert[0] == SSL3_AL_FATAL) {
458     BIO_flush(ssl->wbio.get());
459   }
460 
461   ssl_do_msg_callback(ssl, 1 /* write */, SSL3_RT_ALERT, ssl->s3->send_alert);
462 
463   int alert = (ssl->s3->send_alert[0] << 8) | ssl->s3->send_alert[1];
464   ssl_do_info_callback(ssl, SSL_CB_WRITE_ALERT, alert);
465 
466   return 1;
467 }
468 
469 BSSL_NAMESPACE_END
470