• 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) {
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   if (!ssl_public_key_verify(ssl, signature, signature_algorithm,
374                              hs->peer_pubkey.get(), input)) {
375     OPENSSL_PUT_ERROR(SSL, SSL_R_BAD_SIGNATURE);
376     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
377     return false;
378   }
379 
380   return true;
381 }
382 
tls13_process_finished(SSL_HANDSHAKE * hs,const SSLMessage & msg,bool use_saved_value)383 bool tls13_process_finished(SSL_HANDSHAKE *hs, const SSLMessage &msg,
384                             bool use_saved_value) {
385   SSL *const ssl = hs->ssl;
386   uint8_t verify_data_buf[EVP_MAX_MD_SIZE];
387   Span<const uint8_t> verify_data;
388   if (use_saved_value) {
389     assert(ssl->server);
390     verify_data = hs->expected_client_finished();
391   } else {
392     size_t len;
393     if (!tls13_finished_mac(hs, verify_data_buf, &len, !ssl->server)) {
394       return false;
395     }
396     verify_data = MakeConstSpan(verify_data_buf, len);
397   }
398 
399   bool finished_ok =
400       CBS_mem_equal(&msg.body, verify_data.data(), verify_data.size());
401 #if defined(BORINGSSL_UNSAFE_FUZZER_MODE)
402   finished_ok = true;
403 #endif
404   if (!finished_ok) {
405     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECRYPT_ERROR);
406     OPENSSL_PUT_ERROR(SSL, SSL_R_DIGEST_CHECK_FAILED);
407     return false;
408   }
409 
410   return true;
411 }
412 
tls13_add_certificate(SSL_HANDSHAKE * hs)413 bool tls13_add_certificate(SSL_HANDSHAKE *hs) {
414   SSL *const ssl = hs->ssl;
415   CERT *const cert = hs->config->cert.get();
416   DC *const dc = cert->dc.get();
417 
418   ScopedCBB cbb;
419   CBB *body, body_storage, certificate_list;
420 
421   if (hs->cert_compression_negotiated) {
422     if (!CBB_init(cbb.get(), 1024)) {
423       return false;
424     }
425     body = cbb.get();
426   } else {
427     body = &body_storage;
428     if (!ssl->method->init_message(ssl, cbb.get(), body, SSL3_MT_CERTIFICATE)) {
429       return false;
430     }
431   }
432 
433   if (// The request context is always empty in the handshake.
434       !CBB_add_u8(body, 0) ||
435       !CBB_add_u24_length_prefixed(body, &certificate_list)) {
436     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
437     return false;
438   }
439 
440   if (!ssl_has_certificate(hs)) {
441     return ssl_add_message_cbb(ssl, cbb.get());
442   }
443 
444   CRYPTO_BUFFER *leaf_buf = sk_CRYPTO_BUFFER_value(cert->chain.get(), 0);
445   CBB leaf, extensions;
446   if (!CBB_add_u24_length_prefixed(&certificate_list, &leaf) ||
447       !CBB_add_bytes(&leaf, CRYPTO_BUFFER_data(leaf_buf),
448                      CRYPTO_BUFFER_len(leaf_buf)) ||
449       !CBB_add_u16_length_prefixed(&certificate_list, &extensions)) {
450     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
451     return false;
452   }
453 
454   if (hs->scts_requested && cert->signed_cert_timestamp_list != nullptr) {
455     CBB contents;
456     if (!CBB_add_u16(&extensions, TLSEXT_TYPE_certificate_timestamp) ||
457         !CBB_add_u16_length_prefixed(&extensions, &contents) ||
458         !CBB_add_bytes(
459             &contents,
460             CRYPTO_BUFFER_data(cert->signed_cert_timestamp_list.get()),
461             CRYPTO_BUFFER_len(cert->signed_cert_timestamp_list.get())) ||
462         !CBB_flush(&extensions)) {
463       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
464       return false;
465     }
466   }
467 
468   if (hs->ocsp_stapling_requested && cert->ocsp_response != NULL) {
469     CBB contents, ocsp_response;
470     if (!CBB_add_u16(&extensions, TLSEXT_TYPE_status_request) ||
471         !CBB_add_u16_length_prefixed(&extensions, &contents) ||
472         !CBB_add_u8(&contents, TLSEXT_STATUSTYPE_ocsp) ||
473         !CBB_add_u24_length_prefixed(&contents, &ocsp_response) ||
474         !CBB_add_bytes(&ocsp_response,
475                        CRYPTO_BUFFER_data(cert->ocsp_response.get()),
476                        CRYPTO_BUFFER_len(cert->ocsp_response.get())) ||
477         !CBB_flush(&extensions)) {
478       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
479       return false;
480     }
481   }
482 
483   if (ssl_signing_with_dc(hs)) {
484     const CRYPTO_BUFFER *raw = dc->raw.get();
485     CBB child;
486     if (!CBB_add_u16(&extensions, TLSEXT_TYPE_delegated_credential) ||
487         !CBB_add_u16_length_prefixed(&extensions, &child) ||
488         !CBB_add_bytes(&child, CRYPTO_BUFFER_data(raw),
489                        CRYPTO_BUFFER_len(raw)) ||
490         !CBB_flush(&extensions)) {
491       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
492       return 0;
493     }
494     ssl->s3->delegated_credential_used = true;
495   }
496 
497   for (size_t i = 1; i < sk_CRYPTO_BUFFER_num(cert->chain.get()); i++) {
498     CRYPTO_BUFFER *cert_buf = sk_CRYPTO_BUFFER_value(cert->chain.get(), i);
499     CBB child;
500     if (!CBB_add_u24_length_prefixed(&certificate_list, &child) ||
501         !CBB_add_bytes(&child, CRYPTO_BUFFER_data(cert_buf),
502                        CRYPTO_BUFFER_len(cert_buf)) ||
503         !CBB_add_u16(&certificate_list, 0 /* no extensions */)) {
504       OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
505       return false;
506     }
507   }
508 
509   if (!hs->cert_compression_negotiated) {
510     return ssl_add_message_cbb(ssl, cbb.get());
511   }
512 
513   Array<uint8_t> msg;
514   if (!CBBFinishArray(cbb.get(), &msg)) {
515     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
516     return false;
517   }
518 
519   const CertCompressionAlg *alg = nullptr;
520   for (const auto &candidate : ssl->ctx->cert_compression_algs) {
521     if (candidate.alg_id == hs->cert_compression_alg_id) {
522       alg = &candidate;
523       break;
524     }
525   }
526 
527   if (alg == nullptr || alg->compress == nullptr) {
528     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
529     return false;
530   }
531 
532   CBB compressed;
533   body = &body_storage;
534   if (!ssl->method->init_message(ssl, cbb.get(), body,
535                                  SSL3_MT_COMPRESSED_CERTIFICATE) ||
536       !CBB_add_u16(body, hs->cert_compression_alg_id) ||
537       !CBB_add_u24(body, msg.size()) ||
538       !CBB_add_u24_length_prefixed(body, &compressed) ||
539       !alg->compress(ssl, &compressed, msg.data(), msg.size()) ||
540       !ssl_add_message_cbb(ssl, cbb.get())) {
541     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
542     return false;
543   }
544 
545   return true;
546 }
547 
tls13_add_certificate_verify(SSL_HANDSHAKE * hs)548 enum ssl_private_key_result_t tls13_add_certificate_verify(SSL_HANDSHAKE *hs) {
549   SSL *const ssl = hs->ssl;
550   uint16_t signature_algorithm;
551   if (!tls1_choose_signature_algorithm(hs, &signature_algorithm)) {
552     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_HANDSHAKE_FAILURE);
553     return ssl_private_key_failure;
554   }
555 
556   ScopedCBB cbb;
557   CBB body;
558   if (!ssl->method->init_message(ssl, cbb.get(), &body,
559                                  SSL3_MT_CERTIFICATE_VERIFY) ||
560       !CBB_add_u16(&body, signature_algorithm)) {
561     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
562     return ssl_private_key_failure;
563   }
564 
565   // Sign the digest.
566   CBB child;
567   const size_t max_sig_len = EVP_PKEY_size(hs->local_pubkey.get());
568   uint8_t *sig;
569   size_t sig_len;
570   if (!CBB_add_u16_length_prefixed(&body, &child) ||
571       !CBB_reserve(&child, &sig, max_sig_len)) {
572     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
573     return ssl_private_key_failure;
574   }
575 
576   Array<uint8_t> msg;
577   if (!tls13_get_cert_verify_signature_input(
578           hs, &msg,
579           ssl->server ? ssl_cert_verify_server : ssl_cert_verify_client)) {
580     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
581     return ssl_private_key_failure;
582   }
583 
584   enum ssl_private_key_result_t sign_result = ssl_private_key_sign(
585       hs, sig, &sig_len, max_sig_len, signature_algorithm, msg);
586   if (sign_result != ssl_private_key_success) {
587     return sign_result;
588   }
589 
590   if (!CBB_did_write(&child, sig_len) ||
591       !ssl_add_message_cbb(ssl, cbb.get())) {
592     return ssl_private_key_failure;
593   }
594 
595   return ssl_private_key_success;
596 }
597 
tls13_add_finished(SSL_HANDSHAKE * hs)598 bool tls13_add_finished(SSL_HANDSHAKE *hs) {
599   SSL *const ssl = hs->ssl;
600   size_t verify_data_len;
601   uint8_t verify_data[EVP_MAX_MD_SIZE];
602 
603   if (!tls13_finished_mac(hs, verify_data, &verify_data_len, ssl->server)) {
604     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_INTERNAL_ERROR);
605     OPENSSL_PUT_ERROR(SSL, SSL_R_DIGEST_CHECK_FAILED);
606     return false;
607   }
608 
609   ScopedCBB cbb;
610   CBB body;
611   if (!ssl->method->init_message(ssl, cbb.get(), &body, SSL3_MT_FINISHED) ||
612       !CBB_add_bytes(&body, verify_data, verify_data_len) ||
613       !ssl_add_message_cbb(ssl, cbb.get())) {
614     return false;
615   }
616 
617   return true;
618 }
619 
tls13_add_key_update(SSL * ssl,int update_requested)620 bool tls13_add_key_update(SSL *ssl, int update_requested) {
621   ScopedCBB cbb;
622   CBB body_cbb;
623   if (!ssl->method->init_message(ssl, cbb.get(), &body_cbb,
624                                  SSL3_MT_KEY_UPDATE) ||
625       !CBB_add_u8(&body_cbb, update_requested) ||
626       !ssl_add_message_cbb(ssl, cbb.get()) ||
627       !tls13_rotate_traffic_key(ssl, evp_aead_seal)) {
628     return false;
629   }
630 
631   // Suppress KeyUpdate acknowledgments until this change is written to the
632   // wire. This prevents us from accumulating write obligations when read and
633   // write progress at different rates. See RFC 8446, section 4.6.3.
634   ssl->s3->key_update_pending = true;
635 
636   return true;
637 }
638 
tls13_receive_key_update(SSL * ssl,const SSLMessage & msg)639 static bool tls13_receive_key_update(SSL *ssl, const SSLMessage &msg) {
640   CBS body = msg.body;
641   uint8_t key_update_request;
642   if (!CBS_get_u8(&body, &key_update_request) ||
643       CBS_len(&body) != 0 ||
644       (key_update_request != SSL_KEY_UPDATE_NOT_REQUESTED &&
645        key_update_request != SSL_KEY_UPDATE_REQUESTED)) {
646     OPENSSL_PUT_ERROR(SSL, SSL_R_DECODE_ERROR);
647     ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_DECODE_ERROR);
648     return false;
649   }
650 
651   if (!tls13_rotate_traffic_key(ssl, evp_aead_open)) {
652     return false;
653   }
654 
655   // Acknowledge the KeyUpdate
656   if (key_update_request == SSL_KEY_UPDATE_REQUESTED &&
657       !ssl->s3->key_update_pending &&
658       !tls13_add_key_update(ssl, SSL_KEY_UPDATE_NOT_REQUESTED)) {
659     return false;
660   }
661 
662   return true;
663 }
664 
tls13_post_handshake(SSL * ssl,const SSLMessage & msg)665 bool tls13_post_handshake(SSL *ssl, const SSLMessage &msg) {
666   if (msg.type == SSL3_MT_KEY_UPDATE) {
667     ssl->s3->key_update_count++;
668     if (ssl->quic_method != nullptr ||
669         ssl->s3->key_update_count > kMaxKeyUpdates) {
670       OPENSSL_PUT_ERROR(SSL, SSL_R_TOO_MANY_KEY_UPDATES);
671       ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
672       return false;
673     }
674 
675     return tls13_receive_key_update(ssl, msg);
676   }
677 
678   ssl->s3->key_update_count = 0;
679 
680   if (msg.type == SSL3_MT_NEW_SESSION_TICKET && !ssl->server) {
681     return tls13_process_new_session_ticket(ssl, msg);
682   }
683 
684   ssl_send_alert(ssl, SSL3_AL_FATAL, SSL_AD_UNEXPECTED_MESSAGE);
685   OPENSSL_PUT_ERROR(SSL, SSL_R_UNEXPECTED_MESSAGE);
686   return false;
687 }
688 
689 BSSL_NAMESPACE_END
690