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