• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /* Copyright (c) 2016, Google Inc.
2  *
3  * Permission to use, copy, modify, and/or distribute this software for any
4  * purpose with or without fee is hereby granted, provided that the above
5  * copyright notice and this permission notice appear in all copies.
6  *
7  * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
8  * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
9  * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
10  * SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
11  * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION
12  * OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
13  * CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. */
14 
15 #include <openssl/ssl.h>
16 
17 #include <assert.h>
18 #include <string.h>
19 
20 #include <utility>
21 
22 #include <openssl/bytestring.h>
23 #include <openssl/err.h>
24 #include <openssl/hkdf.h>
25 #include <openssl/mem.h>
26 #include <openssl/stack.h>
27 #include <openssl/x509.h>
28 
29 #include "../crypto/internal.h"
30 #include "internal.h"
31 
32 
33 BSSL_NAMESPACE_BEGIN
34 
35 // kMaxKeyUpdates is the number of consecutive KeyUpdates that will be
36 // processed. Without this limit an attacker could force unbounded processing
37 // without being able to return application data.
38 static const uint8_t kMaxKeyUpdates = 32;
39 
40 const uint8_t kHelloRetryRequest[SSL3_RANDOM_SIZE] = {
41     0xcf, 0x21, 0xad, 0x74, 0xe5, 0x9a, 0x61, 0x11, 0xbe, 0x1d, 0x8c,
42     0x02, 0x1e, 0x65, 0xb8, 0x91, 0xc2, 0xa2, 0x11, 0x16, 0x7a, 0xbb,
43     0x8c, 0x5e, 0x07, 0x9e, 0x09, 0xe2, 0xc8, 0xa8, 0x33, 0x9c,
44 };
45 
46 // See RFC 8446, section 4.1.3.
47 const uint8_t kTLS12DowngradeRandom[8] = {0x44, 0x4f, 0x57, 0x4e,
48                                           0x47, 0x52, 0x44, 0x00};
49 const uint8_t kTLS13DowngradeRandom[8] = {0x44, 0x4f, 0x57, 0x4e,
50                                           0x47, 0x52, 0x44, 0x01};
51 
52 // This is a non-standard randomly-generated value.
53 const uint8_t kJDK11DowngradeRandom[8] = {0xed, 0xbf, 0xb4, 0xa8,
54                                           0xc2, 0x47, 0x10, 0xff};
55 
tls13_get_cert_verify_signature_input(SSL_HANDSHAKE * hs,Array<uint8_t> * out,enum ssl_cert_verify_context_t cert_verify_context)56 bool tls13_get_cert_verify_signature_input(
57     SSL_HANDSHAKE *hs, Array<uint8_t> *out,
58     enum ssl_cert_verify_context_t cert_verify_context) {
59   ScopedCBB cbb;
60   if (!CBB_init(cbb.get(), 64 + 33 + 1 + 2 * EVP_MAX_MD_SIZE)) {
61     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
62     return false;
63   }
64 
65   for (size_t i = 0; i < 64; i++) {
66     if (!CBB_add_u8(cbb.get(), 0x20)) {
67       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
68       return false;
69     }
70   }
71 
72   Span<const char> context;
73   if (cert_verify_context == ssl_cert_verify_server) {
74     static const char kContext[] = "TLS 1.3, server CertificateVerify";
75     context = kContext;
76   } else if (cert_verify_context == ssl_cert_verify_client) {
77     static const char kContext[] = "TLS 1.3, client CertificateVerify";
78     context = kContext;
79   } else if (cert_verify_context == ssl_cert_verify_channel_id) {
80     static const char kContext[] = "TLS 1.3, Channel ID";
81     context = kContext;
82   } else {
83     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
84     return false;
85   }
86 
87   // Note |context| includes the NUL byte separator.
88   if (!CBB_add_bytes(cbb.get(),
89                      reinterpret_cast<const uint8_t *>(context.data()),
90                      context.size())) {
91     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
92     return false;
93   }
94 
95   uint8_t context_hash[EVP_MAX_MD_SIZE];
96   size_t context_hash_len;
97   if (!hs->transcript.GetHash(context_hash, &context_hash_len) ||
98       !CBB_add_bytes(cbb.get(), context_hash, context_hash_len) ||
99       !CBBFinishArray(cbb.get(), out)) {
100     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
101     return false;
102   }
103 
104   return true;
105 }
106 
tls13_process_certificate(SSL_HANDSHAKE * hs,const SSLMessage & msg,bool allow_anonymous)107 bool tls13_process_certificate(SSL_HANDSHAKE *hs, const SSLMessage &msg,
108                                bool allow_anonymous) {
109   SSL *const ssl = hs->ssl;
110   CBS body = msg.body;
111   bssl::UniquePtr<CRYPTO_BUFFER> decompressed;
112 
113   if (msg.type == SSL3_MT_COMPRESSED_CERTIFICATE) {
114     CBS compressed;
115     uint16_t alg_id;
116     uint32_t uncompressed_len;
117 
118     if (!CBS_get_u16(&body, &alg_id) ||
119         !CBS_get_u24(&body, &uncompressed_len) ||
120         !CBS_get_u24_length_prefixed(&body, &compressed) ||
121         CBS_len(&body) != 0) {
122       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
123       OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
124       return false;
125     }
126 
127     if (uncompressed_len > ssl->max_cert_list) {
128       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
129       OPENSSL_PUT_ERROR(SSL, SSL_R_UNCOMPRESSED_CERT_TOO_LARGE);
130       ERR_add_error_dataf("requested=%u",
131                           static_cast<unsigned>(uncompressed_len));
132       return false;
133     }
134 
135     ssl_cert_decompression_func_t decompress = nullptr;
136     for (const auto* alg : ssl->ctx->cert_compression_algs.get()) {
137       if (alg->alg_id == alg_id) {
138         decompress = alg->decompress;
139         break;
140       }
141     }
142 
143     if (decompress == nullptr) {
144       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
145       OPENSSL_PUT_ERROR(SSL, SSL_R_UNKNOWN_CERT_COMPRESSION_ALG);
146       ERR_add_error_dataf("alg=%d", static_cast<int>(alg_id));
147       return false;
148     }
149 
150     CRYPTO_BUFFER *decompressed_ptr = nullptr;
151     if (!decompress(ssl, &decompressed_ptr, uncompressed_len,
152                     CBS_data(&compressed), CBS_len(&compressed))) {
153       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
154       OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_DECOMPRESSION_FAILED);
155       ERR_add_error_dataf("alg=%d", static_cast<int>(alg_id));
156       return false;
157     }
158     decompressed.reset(decompressed_ptr);
159 
160     if (CRYPTO_BUFFER_len(decompressed_ptr) != uncompressed_len) {
161       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
162       OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_DECOMPRESSION_FAILED);
163       ERR_add_error_dataf(
164           "alg=%d got=%u expected=%u", static_cast<int>(alg_id),
165           static_cast<unsigned>(CRYPTO_BUFFER_len(decompressed_ptr)),
166           static_cast<unsigned>(uncompressed_len));
167       return false;
168     }
169 
170     CBS_init(&body, CRYPTO_BUFFER_data(decompressed_ptr),
171              CRYPTO_BUFFER_len(decompressed_ptr));
172   } else {
173     assert(msg.type == SSL3_MT_CERTIFICATE);
174   }
175 
176   CBS context, certificate_list;
177   if (!CBS_get_u8_length_prefixed(&body, &context) ||
178       CBS_len(&context) != 0 ||
179       !CBS_get_u24_length_prefixed(&body, &certificate_list) ||
180       CBS_len(&body) != 0) {
181     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
182     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
183     return false;
184   }
185 
186   UniquePtr<STACK_OF(CRYPTO_BUFFER)> certs(sk_CRYPTO_BUFFER_new_null());
187   if (!certs) {
188     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
189     OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
190     return false;
191   }
192 
193   const bool retain_sha256 =
194       ssl->server && hs->config->retain_only_sha256_of_client_certs;
195   UniquePtr<EVP_PKEY> pkey;
196   while (CBS_len(&certificate_list) > 0) {
197     CBS certificate, extensions;
198     if (!CBS_get_u24_length_prefixed(&certificate_list, &certificate) ||
199         !CBS_get_u16_length_prefixed(&certificate_list, &extensions) ||
200         CBS_len(&certificate) == 0) {
201       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
202       OPENSSL_PUT_ERROR(SSL, SSL_R_CERT_LENGTH_MISMATCH);
203       return false;
204     }
205 
206     if (sk_CRYPTO_BUFFER_num(certs.get()) == 0) {
207       pkey = ssl_cert_parse_pubkey(&certificate);
208       if (!pkey) {
209         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
210         OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
211         return false;
212       }
213       // TLS 1.3 always uses certificate keys for signing thus the correct
214       // keyUsage is enforced.
215       if (!ssl_cert_check_key_usage(&certificate,
216                                     key_usage_digital_signature)) {
217         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_ILLEGAL_PARAMETER);
218         return false;
219       }
220 
221       if (retain_sha256) {
222         // Retain the hash of the leaf certificate if requested.
223         SHA256(CBS_data(&certificate), CBS_len(&certificate),
224                hs->new_session->peer_sha256);
225       }
226     }
227 
228     UniquePtr<CRYPTO_BUFFER> buf(
229         CRYPTO_BUFFER_new_from_CBS(&certificate, ssl->ctx->pool));
230     if (!buf ||
231         !PushToStack(certs.get(), std::move(buf))) {
232       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
233       OPENSSL_PUT_ERROR(SSL, ERR_R_MALLOC_FAILURE);
234       return false;
235     }
236 
237     // Parse out the extensions.
238     bool have_status_request = false, have_sct = false;
239     CBS status_request, sct;
240     const SSL_EXTENSION_TYPE ext_types[] = {
241         {TLSEXT_TYPE_status_request, &have_status_request, &status_request},
242         {TLSEXT_TYPE_certificate_timestamp, &have_sct, &sct},
243     };
244 
245     uint8_t alert = SSL_AD_DECODE_ERROR;
246     if (!ssl_parse_extensions(&extensions, &alert, ext_types,
247                               OPENSSL_ARRAY_SIZE(ext_types),
248                               0 /* reject unknown */)) {
249       ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
250       return false;
251     }
252 
253     // All Certificate extensions are parsed, but only the leaf extensions are
254     // stored.
255     if (have_status_request) {
256       if (ssl->server || !hs->config->ocsp_stapling_enabled) {
257         OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
258         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_EXTENSION);
259         return false;
260       }
261 
262       uint8_t status_type;
263       CBS ocsp_response;
264       if (!CBS_get_u8(&status_request, &status_type) ||
265           status_type != TLSEXT_STATUSTYPE_ocsp ||
266           !CBS_get_u24_length_prefixed(&status_request, &ocsp_response) ||
267           CBS_len(&ocsp_response) == 0 ||
268           CBS_len(&status_request) != 0) {
269         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
270         return false;
271       }
272 
273       if (sk_CRYPTO_BUFFER_num(certs.get()) == 1) {
274         hs->new_session->ocsp_response.reset(
275             CRYPTO_BUFFER_new_from_CBS(&ocsp_response, ssl->ctx->pool));
276         if (hs->new_session->ocsp_response == nullptr) {
277           ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
278           return false;
279         }
280       }
281     }
282 
283     if (have_sct) {
284       if (ssl->server || !hs->config->signed_cert_timestamps_enabled) {
285         OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_EXTENSION);
286         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNSUPPORTED_EXTENSION);
287         return false;
288       }
289 
290       if (!ssl_is_sct_list_valid(&sct)) {
291         OPENSSL_PUT_ERROR(SSL, SSL_R_ERROR_PARSING_EXTENSION);
292         ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
293         return false;
294       }
295 
296       if (sk_CRYPTO_BUFFER_num(certs.get()) == 1) {
297         hs->new_session->signed_cert_timestamp_list.reset(
298             CRYPTO_BUFFER_new_from_CBS(&sct, ssl->ctx->pool));
299         if (hs->new_session->signed_cert_timestamp_list == nullptr) {
300           ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
301           return false;
302         }
303       }
304     }
305   }
306 
307   // Store a null certificate list rather than an empty one if the peer didn't
308   // send certificates.
309   if (sk_CRYPTO_BUFFER_num(certs.get()) == 0) {
310     certs.reset();
311   }
312 
313   hs->peer_pubkey = std::move(pkey);
314   hs->new_session->certs = std::move(certs);
315 
316   if (!ssl->ctx->x509_method->session_cache_objects(hs->new_session.get())) {
317     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
318     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
319     return false;
320   }
321 
322   if (sk_CRYPTO_BUFFER_num(hs->new_session->certs.get()) == 0) {
323     if (!allow_anonymous) {
324       OPENSSL_PUT_ERROR(SSL, SSL_R_PEER_DID_NOT_RETURN_A_CERTIFICATE);
325       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_CERTIFICATE_REQUIRED);
326       return false;
327     }
328 
329     // OpenSSL returns X509_V_OK when no certificates are requested. This is
330     // classed by them as a bug, but it's assumed by at least NGINX.
331     hs->new_session->verify_result = X509_V_OK;
332 
333     // No certificate, so nothing more to do.
334     return true;
335   }
336 
337   hs->new_session->peer_sha256_valid = retain_sha256;
338   return true;
339 }
340 
tls13_process_certificate_verify(SSL_HANDSHAKE * hs,const SSLMessage & msg)341 bool tls13_process_certificate_verify(SSL_HANDSHAKE *hs, const SSLMessage &msg) {
342   SSL *const ssl = hs->ssl;
343   if (hs->peer_pubkey == NULL) {
344     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
345     return false;
346   }
347 
348   CBS body = msg.body, signature;
349   uint16_t signature_algorithm;
350   if (!CBS_get_u16(&body, &signature_algorithm) ||
351       !CBS_get_u16_length_prefixed(&body, &signature) ||
352       CBS_len(&body) != 0) {
353     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
354     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
355     return false;
356   }
357 
358   uint8_t alert = SSL_AD_DECODE_ERROR;
359   if (!tls12_check_peer_sigalg(ssl, &alert, signature_algorithm)) {
360     ssl_send_alert(ssl, SSL3_AL_FATAL, alert);
361     return false;
362   }
363   hs->new_session->peer_signature_algorithm = signature_algorithm;
364 
365   Array<uint8_t> input;
366   if (!tls13_get_cert_verify_signature_input(
367           hs, &input,
368           ssl->server ? ssl_cert_verify_client : ssl_cert_verify_server)) {
369     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
370     return false;
371   }
372 
373   bool sig_ok = ssl_public_key_verify(ssl, signature, signature_algorithm,
374                                       hs->peer_pubkey.get(), input);
375 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
376   sig_ok = true;
377   ERR_clear_error();
378 #endif
379   if (!sig_ok) {
380     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
381     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
382     return false;
383   }
384 
385   return true;
386 }
387 
tls13_process_finished(SSL_HANDSHAKE * hs,const SSLMessage & msg,bool use_saved_value)388 bool tls13_process_finished(SSL_HANDSHAKE *hs, const SSLMessage &msg,
389                             bool use_saved_value) {
390   SSL *const ssl = hs->ssl;
391   uint8_t verify_data_buf[EVP_MAX_MD_SIZE];
392   const uint8_t *verify_data;
393   size_t verify_data_len;
394   if (use_saved_value) {
395     assert(ssl->server);
396     verify_data = hs->expected_client_finished;
397     verify_data_len = hs->hash_len;
398   } else {
399     if (!tls13_finished_mac(hs, verify_data_buf, &verify_data_len,
400                             !ssl->server)) {
401       return false;
402     }
403     verify_data = verify_data_buf;
404   }
405 
406   bool finished_ok = CBS_mem_equal(&msg.body, verify_data, verify_data_len);
407 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
408   finished_ok = true;
409 #endif
410   if (!finished_ok) {
411     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
412     OPENSSL_PUT_ERROR(SSL, SSL_R_DIGEST_CHECK_FAILED);
413     return false;
414   }
415 
416   return true;
417 }
418 
tls13_add_certificate(SSL_HANDSHAKE * hs)419 bool tls13_add_certificate(SSL_HANDSHAKE *hs) {
420   SSL *const ssl = hs->ssl;
421   CERT *const cert = hs->config->cert.get();
422   DC *const dc = cert->dc.get();
423 
424   ScopedCBB cbb;
425   CBB *body, body_storage, certificate_list;
426 
427   if (hs->cert_compression_negotiated) {
428     if (!CBB_init(cbb.get(), 1024)) {
429       return false;
430     }
431     body = cbb.get();
432   } else {
433     body = &body_storage;
434     if (!ssl->method->init_message(ssl, cbb.get(), body, SSL3_MT_CERTIFICATE)) {
435       return false;
436     }
437   }
438 
439   if (// The request context is always empty in the handshake.
440       !CBB_add_u8(body, 0) ||
441       !CBB_add_u24_length_prefixed(body, &certificate_list)) {
442     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
443     return false;
444   }
445 
446   if (!ssl_has_certificate(hs)) {
447     return ssl_add_message_cbb(ssl, cbb.get());
448   }
449 
450   CRYPTO_BUFFER *leaf_buf = sk_CRYPTO_BUFFER_value(cert->chain.get(), 0);
451   CBB leaf, extensions;
452   if (!CBB_add_u24_length_prefixed(&certificate_list, &leaf) ||
453       !CBB_add_bytes(&leaf, CRYPTO_BUFFER_data(leaf_buf),
454                      CRYPTO_BUFFER_len(leaf_buf)) ||
455       !CBB_add_u16_length_prefixed(&certificate_list, &extensions)) {
456     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
457     return false;
458   }
459 
460   if (hs->scts_requested && cert->signed_cert_timestamp_list != nullptr) {
461     CBB contents;
462     if (!CBB_add_u16(&extensions, TLSEXT_TYPE_certificate_timestamp) ||
463         !CBB_add_u16_length_prefixed(&extensions, &contents) ||
464         !CBB_add_bytes(
465             &contents,
466             CRYPTO_BUFFER_data(cert->signed_cert_timestamp_list.get()),
467             CRYPTO_BUFFER_len(cert->signed_cert_timestamp_list.get())) ||
468         !CBB_flush(&extensions)) {
469       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
470       return false;
471     }
472   }
473 
474   if (hs->ocsp_stapling_requested && cert->ocsp_response != NULL) {
475     CBB contents, ocsp_response;
476     if (!CBB_add_u16(&extensions, TLSEXT_TYPE_status_request) ||
477         !CBB_add_u16_length_prefixed(&extensions, &contents) ||
478         !CBB_add_u8(&contents, TLSEXT_STATUSTYPE_ocsp) ||
479         !CBB_add_u24_length_prefixed(&contents, &ocsp_response) ||
480         !CBB_add_bytes(&ocsp_response,
481                        CRYPTO_BUFFER_data(cert->ocsp_response.get()),
482                        CRYPTO_BUFFER_len(cert->ocsp_response.get())) ||
483         !CBB_flush(&extensions)) {
484       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
485       return false;
486     }
487   }
488 
489   if (ssl_signing_with_dc(hs)) {
490     const CRYPTO_BUFFER *raw = dc->raw.get();
491     if (!CBB_add_u16(&extensions, TLSEXT_TYPE_delegated_credential) ||
492         !CBB_add_u16(&extensions, CRYPTO_BUFFER_len(raw)) ||
493         !CBB_add_bytes(&extensions,
494                        CRYPTO_BUFFER_data(raw),
495                        CRYPTO_BUFFER_len(raw)) ||
496         !CBB_flush(&extensions)) {
497       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
498       return 0;
499     }
500   }
501 
502   for (size_t i = 1; i < sk_CRYPTO_BUFFER_num(cert->chain.get()); i++) {
503     CRYPTO_BUFFER *cert_buf = sk_CRYPTO_BUFFER_value(cert->chain.get(), i);
504     CBB child;
505     if (!CBB_add_u24_length_prefixed(&certificate_list, &child) ||
506         !CBB_add_bytes(&child, CRYPTO_BUFFER_data(cert_buf),
507                        CRYPTO_BUFFER_len(cert_buf)) ||
508         !CBB_add_u16(&certificate_list, 0 /* no extensions */)) {
509       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
510       return false;
511     }
512   }
513 
514   if (!hs->cert_compression_negotiated) {
515     return ssl_add_message_cbb(ssl, cbb.get());
516   }
517 
518   Array<uint8_t> msg;
519   if (!CBBFinishArray(cbb.get(), &msg)) {
520     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
521     return false;
522   }
523 
524   const CertCompressionAlg *alg = nullptr;
525   for (const auto *candidate : ssl->ctx->cert_compression_algs.get()) {
526     if (candidate->alg_id == hs->cert_compression_alg_id) {
527       alg = candidate;
528       break;
529     }
530   }
531 
532   if (alg == nullptr || alg->compress == nullptr) {
533     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
534     return false;
535   }
536 
537   CBB compressed;
538   body = &body_storage;
539   if (!ssl->method->init_message(ssl, cbb.get(), body,
540                                  SSL3_MT_COMPRESSED_CERTIFICATE) ||
541       !CBB_add_u16(body, hs->cert_compression_alg_id) ||
542       !CBB_add_u24(body, msg.size()) ||
543       !CBB_add_u24_length_prefixed(body, &compressed) ||
544       !alg->compress(ssl, &compressed, msg.data(), msg.size()) ||
545       !ssl_add_message_cbb(ssl, cbb.get())) {
546     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
547     return false;
548   }
549 
550   return true;
551 }
552 
tls13_add_certificate_verify(SSL_HANDSHAKE * hs)553 enum ssl_private_key_result_t tls13_add_certificate_verify(SSL_HANDSHAKE *hs) {
554   SSL *const ssl = hs->ssl;
555   uint16_t signature_algorithm;
556   if (!tls1_choose_signature_algorithm(hs, &signature_algorithm)) {
557     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
558     return ssl_private_key_failure;
559   }
560 
561   ScopedCBB cbb;
562   CBB body;
563   if (!ssl->method->init_message(ssl, cbb.get(), &body,
564                                  SSL3_MT_CERTIFICATE_VERIFY) ||
565       !CBB_add_u16(&body, signature_algorithm)) {
566     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
567     return ssl_private_key_failure;
568   }
569 
570   // Sign the digest.
571   CBB child;
572   const size_t max_sig_len = EVP_PKEY_size(hs->local_pubkey.get());
573   uint8_t *sig;
574   size_t sig_len;
575   if (!CBB_add_u16_length_prefixed(&body, &child) ||
576       !CBB_reserve(&child, &sig, max_sig_len)) {
577     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
578     return ssl_private_key_failure;
579   }
580 
581   Array<uint8_t> msg;
582   if (!tls13_get_cert_verify_signature_input(
583           hs, &msg,
584           ssl->server ? ssl_cert_verify_server : ssl_cert_verify_client)) {
585     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
586     return ssl_private_key_failure;
587   }
588 
589   enum ssl_private_key_result_t sign_result = ssl_private_key_sign(
590       hs, sig, &sig_len, max_sig_len, signature_algorithm, msg);
591   if (sign_result != ssl_private_key_success) {
592     return sign_result;
593   }
594 
595   if (!CBB_did_write(&child, sig_len) ||
596       !ssl_add_message_cbb(ssl, cbb.get())) {
597     return ssl_private_key_failure;
598   }
599 
600   return ssl_private_key_success;
601 }
602 
tls13_add_finished(SSL_HANDSHAKE * hs)603 bool tls13_add_finished(SSL_HANDSHAKE *hs) {
604   SSL *const ssl = hs->ssl;
605   size_t verify_data_len;
606   uint8_t verify_data[EVP_MAX_MD_SIZE];
607 
608   if (!tls13_finished_mac(hs, verify_data, &verify_data_len, ssl->server)) {
609     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
610     OPENSSL_PUT_ERROR(SSL, SSL_R_DIGEST_CHECK_FAILED);
611     return false;
612   }
613 
614   ScopedCBB cbb;
615   CBB body;
616   if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_FINISHED) ||
617       !CBB_add_bytes(&body, verify_data, verify_data_len) ||
618       !ssl_add_message_cbb(ssl, cbb.get())) {
619     return false;
620   }
621 
622   return true;
623 }
624 
tls13_add_key_update(SSL * ssl,int update_requested)625 bool tls13_add_key_update(SSL *ssl, int update_requested) {
626   ScopedCBB cbb;
627   CBB body_cbb;
628   if (!ssl->method->init_message(ssl, cbb.get(), &body_cbb,
629                                  SSL3_MT_KEY_UPDATE) ||
630       !CBB_add_u8(&body_cbb, update_requested) ||
631       !ssl_add_message_cbb(ssl, cbb.get()) ||
632       !tls13_rotate_traffic_key(ssl, evp_aead_seal)) {
633     return false;
634   }
635 
636   // Suppress KeyUpdate acknowledgments until this change is written to the
637   // wire. This prevents us from accumulating write obligations when read and
638   // write progress at different rates. See RFC 8446, section 4.6.3.
639   ssl->s3->key_update_pending = true;
640 
641   return true;
642 }
643 
tls13_receive_key_update(SSL * ssl,const SSLMessage & msg)644 static bool tls13_receive_key_update(SSL *ssl, const SSLMessage &msg) {
645   CBS body = msg.body;
646   uint8_t key_update_request;
647   if (!CBS_get_u8(&body, &key_update_request) ||
648       CBS_len(&body) != 0 ||
649       (key_update_request != SSL_KEY_UPDATE_NOT_REQUESTED &&
650        key_update_request != SSL_KEY_UPDATE_REQUESTED)) {
651     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
652     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
653     return false;
654   }
655 
656   if (!tls13_rotate_traffic_key(ssl, evp_aead_open)) {
657     return false;
658   }
659 
660   // Acknowledge the KeyUpdate
661   if (key_update_request == SSL_KEY_UPDATE_REQUESTED &&
662       !ssl->s3->key_update_pending &&
663       !tls13_add_key_update(ssl, SSL_KEY_UPDATE_NOT_REQUESTED)) {
664     return false;
665   }
666 
667   return true;
668 }
669 
tls13_post_handshake(SSL * ssl,const SSLMessage & msg)670 bool tls13_post_handshake(SSL *ssl, const SSLMessage &msg) {
671   if (msg.type == SSL3_MT_KEY_UPDATE) {
672     ssl->s3->key_update_count++;
673     if (ssl->quic_method != nullptr ||
674         ssl->s3->key_update_count > kMaxKeyUpdates) {
675       OPENSSL_PUT_ERROR(SSL, SSL_R_TOO_MANY_KEY_UPDATES);
676       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
677       return false;
678     }
679 
680     return tls13_receive_key_update(ssl, msg);
681   }
682 
683   ssl->s3->key_update_count = 0;
684 
685   if (msg.type == SSL3_MT_NEW_SESSION_TICKET && !ssl->server) {
686     return tls13_process_new_session_ticket(ssl, msg);
687   }
688 
689   ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
690   OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
691   return false;
692 }
693 
694 BSSL_NAMESPACE_END
695