• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 1995-2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
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
8  */
9 
10 #include <openssl/ssl.h>
11 
12 #include <assert.h>
13 #include <limits.h>
14 #include <string.h>
15 
16 #include <algorithm>
17 
18 #include <openssl/err.h>
19 #include <openssl/evp.h>
20 #include <openssl/mem.h>
21 #include <openssl/rand.h>
22 
23 #include "../crypto/err/internal.h"
24 #include "../crypto/internal.h"
25 #include "internal.h"
26 
27 
28 BSSL_NAMESPACE_BEGIN
29 
30 static int do_tls_write(SSL *ssl, size_t *out_bytes_written, uint8_t type,
31                         Span<const uint8_t> in);
32 
tls_write_app_data(SSL * ssl,bool * out_needs_handshake,size_t * out_bytes_written,Span<const uint8_t> in)33 int tls_write_app_data(SSL *ssl, bool *out_needs_handshake,
34                        size_t *out_bytes_written, Span<const uint8_t> in) {
35   assert(ssl_can_write(ssl));
36   assert(!ssl->s3->aead_write_ctx->is_null_cipher());
37 
38   *out_needs_handshake = false;
39 
40   if (ssl->s3->write_shutdown != ssl_shutdown_none) {
41     OPENSSL_PUT_ERROR(SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
42     return -1;
43   }
44 
45   size_t total_bytes_written = ssl->s3->unreported_bytes_written;
46   if (in.size() < total_bytes_written) {
47     // This can happen if the caller disables |SSL_MODE_ENABLE_PARTIAL_WRITE|,
48     // asks us to write some input of length N, we successfully encrypt M bytes
49     // and write it, but fail to write the rest. We will report
50     // |SSL_ERROR_WANT_WRITE|. If the caller then retries with fewer than M
51     // bytes, we cannot satisfy that request. The caller is required to always
52     // retry with at least as many bytes as the previous attempt.
53     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_LENGTH);
54     return -1;
55   }
56 
57   in = in.subspan(total_bytes_written);
58 
59   const bool is_early_data_write =
60       !ssl->server && SSL_in_early_data(ssl) && ssl->s3->hs->can_early_write;
61   for (;;) {
62     size_t max_send_fragment = ssl->max_send_fragment;
63     if (is_early_data_write) {
64       SSL_HANDSHAKE *hs = ssl->s3->hs.get();
65       if (hs->early_data_written >= hs->early_session->ticket_max_early_data) {
66         ssl->s3->unreported_bytes_written = total_bytes_written;
67         hs->can_early_write = false;
68         *out_needs_handshake = true;
69         return -1;
70       }
71       max_send_fragment = std::min(
72           max_send_fragment, size_t{hs->early_session->ticket_max_early_data -
73                                     hs->early_data_written});
74     }
75 
76     const size_t to_write = std::min(max_send_fragment, in.size());
77     size_t bytes_written;
78     int ret = do_tls_write(ssl, &bytes_written, SSL3_RT_APPLICATION_DATA,
79                            in.subspan(0, to_write));
80     if (ret <= 0) {
81       ssl->s3->unreported_bytes_written = total_bytes_written;
82       return ret;
83     }
84 
85     // Note |bytes_written| may be less than |to_write| if there was a pending
86     // record from a smaller write attempt.
87     assert(bytes_written <= to_write);
88     total_bytes_written += bytes_written;
89     in = in.subspan(bytes_written);
90     if (is_early_data_write) {
91       ssl->s3->hs->early_data_written += bytes_written;
92     }
93 
94     if (in.empty() || (ssl->mode & SSL_MODE_ENABLE_PARTIAL_WRITE)) {
95       ssl->s3->unreported_bytes_written = 0;
96       *out_bytes_written = total_bytes_written;
97       return 1;
98     }
99   }
100 }
101 
102 // tls_seal_align_prefix_len returns the length of the prefix before the start
103 // of the bulk of the ciphertext when sealing a record with |ssl|. Callers may
104 // use this to align buffers.
105 //
106 // Note when TLS 1.0 CBC record-splitting is enabled, this includes the one byte
107 // record and is the offset into second record's ciphertext. Thus sealing a
108 // small record may result in a smaller output than this value.
109 //
110 // TODO(davidben): Is this alignment valuable? Record-splitting makes this a
111 // mess.
tls_seal_align_prefix_len(const SSL * ssl)112 static size_t tls_seal_align_prefix_len(const SSL *ssl) {
113   size_t ret =
114       SSL3_RT_HEADER_LENGTH + ssl->s3->aead_write_ctx->ExplicitNonceLen();
115   if (ssl_needs_record_splitting(ssl)) {
116     ret += SSL3_RT_HEADER_LENGTH;
117     ret += ssl_cipher_get_record_split_len(ssl->s3->aead_write_ctx->cipher());
118   }
119   return ret;
120 }
121 
122 // do_tls_write writes an SSL record of the given type. On success, it sets
123 // |*out_bytes_written| to number of bytes successfully written and returns one.
124 // 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)125 static int do_tls_write(SSL *ssl, size_t *out_bytes_written, uint8_t type,
126                         Span<const uint8_t> in) {
127   // If there is a pending write, the retry must be consistent.
128   if (!ssl->s3->pending_write.empty() &&
129       (ssl->s3->pending_write.size() > in.size() ||
130        (!(ssl->mode & SSL_MODE_ACCEPT_MOVING_WRITE_BUFFER) &&
131         ssl->s3->pending_write.data() != in.data()) ||
132        ssl->s3->pending_write_type != type)) {
133     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_WRITE_RETRY);
134     return -1;
135   }
136 
137   // Flush any unwritten data to the transport. There may be data to flush even
138   // if |wpend_tot| is zero.
139   int ret = ssl_write_buffer_flush(ssl);
140   if (ret <= 0) {
141     return ret;
142   }
143 
144   // If there is a pending write, we just completed it. Report it to the caller.
145   if (!ssl->s3->pending_write.empty()) {
146     *out_bytes_written = ssl->s3->pending_write.size();
147     ssl->s3->pending_write = {};
148     return 1;
149   }
150 
151   SSLBuffer *buf = &ssl->s3->write_buffer;
152   if (in.size() > SSL3_RT_MAX_PLAIN_LENGTH || buf->size() > 0) {
153     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
154     return -1;
155   }
156 
157   if (!tls_flush_pending_hs_data(ssl)) {
158     return -1;
159   }
160 
161   // We may have unflushed handshake data that must be written before |in|. This
162   // may be a KeyUpdate acknowledgment, 0-RTT key change messages, or a
163   // NewSessionTicket.
164   Span<const uint8_t> pending_flight;
165   if (ssl->s3->pending_flight != nullptr) {
166     pending_flight =
167         Span(reinterpret_cast<const uint8_t *>(ssl->s3->pending_flight->data),
168              ssl->s3->pending_flight->length);
169     pending_flight = pending_flight.subspan(ssl->s3->pending_flight_offset);
170   }
171 
172   size_t max_out = pending_flight.size();
173   if (!in.empty()) {
174     const size_t max_ciphertext_len = in.size() + SSL_max_seal_overhead(ssl);
175     if (max_ciphertext_len < in.size() ||
176         max_out + max_ciphertext_len < max_out) {
177       OPENSSL_PUT_ERROR(SSL, ERR_R_OVERFLOW);
178       return -1;
179     }
180     max_out += max_ciphertext_len;
181   }
182 
183   if (max_out == 0) {
184     // Nothing to write.
185     *out_bytes_written = 0;
186     return 1;
187   }
188 
189   if (!buf->EnsureCap(pending_flight.size() + tls_seal_align_prefix_len(ssl),
190                       max_out)) {
191     return -1;
192   }
193 
194   // Copy |pending_flight| to the output.
195   if (!pending_flight.empty()) {
196     OPENSSL_memcpy(buf->remaining().data(), pending_flight.data(),
197                    pending_flight.size());
198     ssl->s3->pending_flight.reset();
199     ssl->s3->pending_flight_offset = 0;
200     buf->DidWrite(pending_flight.size());
201   }
202 
203   if (!in.empty()) {
204     size_t ciphertext_len;
205     if (!tls_seal_record(ssl, buf->remaining().data(), &ciphertext_len,
206                          buf->remaining().size(), type, in.data(), in.size())) {
207       return -1;
208     }
209     buf->DidWrite(ciphertext_len);
210   }
211 
212   // Now that we've made progress on the connection, uncork KeyUpdate
213   // acknowledgments.
214   ssl->s3->key_update_pending = false;
215 
216   // Flush the write buffer.
217   ret = ssl_write_buffer_flush(ssl);
218   if (ret <= 0) {
219     // Track the unfinished write.
220     if (!in.empty()) {
221       ssl->s3->pending_write = in;
222       ssl->s3->pending_write_type = type;
223     }
224     return ret;
225   }
226 
227   *out_bytes_written = in.size();
228   return 1;
229 }
230 
tls_open_app_data(SSL * ssl,Span<uint8_t> * out,size_t * out_consumed,uint8_t * out_alert,Span<uint8_t> in)231 ssl_open_record_t tls_open_app_data(SSL *ssl, Span<uint8_t> *out,
232                                     size_t *out_consumed, uint8_t *out_alert,
233                                     Span<uint8_t> in) {
234   assert(ssl_can_read(ssl));
235   assert(!ssl->s3->aead_read_ctx->is_null_cipher());
236 
237   uint8_t type;
238   Span<uint8_t> body;
239   auto ret = tls_open_record(ssl, &type, &body, out_consumed, out_alert, in);
240   if (ret != ssl_open_record_success) {
241     return ret;
242   }
243 
244   const bool is_early_data_read = ssl->server && SSL_in_early_data(ssl);
245 
246   if (type == SSL3_RT_HANDSHAKE) {
247     // Post-handshake data prior to TLS 1.3 is always renegotiation, which we
248     // never accept as a server. Otherwise |tls_get_message| will send
249     // |SSL_R_EXCESSIVE_MESSAGE_SIZE|.
250     if (ssl->server && ssl_protocol_version(ssl) < TLS1_3_VERSION) {
251       OPENSSL_PUT_ERROR(SSL, SSL_R_NO_RENEGOTIATION);
252       *out_alert = SSL_AD_NO_RENEGOTIATION;
253       return ssl_open_record_error;
254     }
255 
256     if (!tls_append_handshake_data(ssl, body)) {
257       *out_alert = SSL_AD_INTERNAL_ERROR;
258       return ssl_open_record_error;
259     }
260     return ssl_open_record_discard;
261   }
262 
263   if (type != SSL3_RT_APPLICATION_DATA) {
264     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
265     *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
266     return ssl_open_record_error;
267   }
268 
269   if (is_early_data_read) {
270     if (body.size() > kMaxEarlyDataAccepted - ssl->s3->hs->early_data_read) {
271       OPENSSL_PUT_ERROR(SSL, SSL_R_TOO_MUCH_READ_EARLY_DATA);
272       *out_alert = SSL3_AD_UNEXPECTED_MESSAGE;
273       return ssl_open_record_error;
274     }
275 
276     ssl->s3->hs->early_data_read += body.size();
277   }
278 
279   if (body.empty()) {
280     return ssl_open_record_discard;
281   }
282 
283   *out = body;
284   return ssl_open_record_success;
285 }
286 
tls_open_change_cipher_spec(SSL * ssl,size_t * out_consumed,uint8_t * out_alert,Span<uint8_t> in)287 ssl_open_record_t tls_open_change_cipher_spec(SSL *ssl, size_t *out_consumed,
288                                               uint8_t *out_alert,
289                                               Span<uint8_t> in) {
290   uint8_t type;
291   Span<uint8_t> body;
292   auto ret = tls_open_record(ssl, &type, &body, out_consumed, out_alert, in);
293   if (ret != ssl_open_record_success) {
294     return ret;
295   }
296 
297   if (type != SSL3_RT_CHANGE_CIPHER_SPEC) {
298     OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_RECORD);
299     *out_alert = SSL_AD_UNEXPECTED_MESSAGE;
300     return ssl_open_record_error;
301   }
302 
303   if (body.size() != 1 || body[0] != SSL3_MT_CCS) {
304     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_CHANGE_CIPHER_SPEC);
305     *out_alert = SSL_AD_ILLEGAL_PARAMETER;
306     return ssl_open_record_error;
307   }
308 
309   ssl_do_msg_callback(ssl, 0 /* read */, SSL3_RT_CHANGE_CIPHER_SPEC, body);
310   return ssl_open_record_success;
311 }
312 
ssl_send_alert(SSL * ssl,int level,int desc)313 void ssl_send_alert(SSL *ssl, int level, int desc) {
314   // This function is called in response to a fatal error from the peer. Ignore
315   // any failures writing the alert and report only the original error. In
316   // particular, if the transport uses |SSL_write|, our existing error will be
317   // clobbered so we must save and restore the error queue. See
318   // https://crbug.com/959305.
319   //
320   // TODO(davidben): Return the alert out of the handshake, rather than calling
321   // this function internally everywhere.
322   //
323   // TODO(davidben): This does not allow retrying if the alert hit EAGAIN. See
324   // https://crbug.com/boringssl/130.
325   UniquePtr<ERR_SAVE_STATE> err_state(ERR_save_state());
326   ssl_send_alert_impl(ssl, level, desc);
327   ERR_restore_state(err_state.get());
328 }
329 
ssl_send_alert_impl(SSL * ssl,int level,int desc)330 int ssl_send_alert_impl(SSL *ssl, int level, int desc) {
331   // It is illegal to send an alert when we've already sent a closing one.
332   if (ssl->s3->write_shutdown != ssl_shutdown_none) {
333     OPENSSL_PUT_ERROR(SSL, SSL_R_PROTOCOL_IS_SHUTDOWN);
334     return -1;
335   }
336 
337   if (level == SSL3_AL_WARNING && desc == SSL_AD_CLOSE_NOTIFY) {
338     ssl->s3->write_shutdown = ssl_shutdown_close_notify;
339   } else {
340     assert(level == SSL3_AL_FATAL);
341     assert(desc != SSL_AD_CLOSE_NOTIFY);
342     ssl->s3->write_shutdown = ssl_shutdown_error;
343   }
344 
345   ssl->s3->alert_dispatch = true;
346   ssl->s3->send_alert[0] = level;
347   ssl->s3->send_alert[1] = desc;
348   if (ssl->s3->write_buffer.empty()) {
349     // Nothing is being written out, so the alert may be dispatched
350     // immediately.
351     return ssl->method->dispatch_alert(ssl);
352   }
353 
354   // The alert will be dispatched later.
355   return -1;
356 }
357 
tls_dispatch_alert(SSL * ssl)358 int tls_dispatch_alert(SSL *ssl) {
359   if (SSL_is_quic(ssl)) {
360     if (!ssl->quic_method->send_alert(ssl, ssl->s3->quic_write_level,
361                                       ssl->s3->send_alert[1])) {
362       OPENSSL_PUT_ERROR(SSL, SSL_R_QUIC_INTERNAL_ERROR);
363       return 0;
364     }
365   } else {
366     size_t bytes_written;
367     int ret =
368         do_tls_write(ssl, &bytes_written, SSL3_RT_ALERT, ssl->s3->send_alert);
369     if (ret <= 0) {
370       return ret;
371     }
372     assert(bytes_written == 2);
373   }
374 
375   ssl->s3->alert_dispatch = false;
376 
377   // If the alert is fatal, flush the BIO now.
378   if (ssl->s3->send_alert[0] == SSL3_AL_FATAL) {
379     BIO_flush(ssl->wbio.get());
380   }
381 
382   ssl_do_msg_callback(ssl, 1 /* write */, SSL3_RT_ALERT, ssl->s3->send_alert);
383 
384   int alert = (ssl->s3->send_alert[0] << 8) | ssl->s3->send_alert[1];
385   ssl_do_info_callback(ssl, SSL_CB_WRITE_ALERT, alert);
386 
387   return 1;
388 }
389 
390 BSSL_NAMESPACE_END
391