1 // Copyright 2016 The BoringSSL Authors
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 <string.h>
19 
20 #include <algorithm>
21 #include <string_view>
22 #include <utility>
23 
24 #include <openssl/aead.h>
25 #include <openssl/aes.h>
26 #include <openssl/bytestring.h>
27 #include <openssl/chacha.h>
28 #include <openssl/digest.h>
29 #include <openssl/hkdf.h>
30 #include <openssl/hmac.h>
31 #include <openssl/mem.h>
32 
33 #include "../crypto/fipsmodule/tls/internal.h"
34 #include "../crypto/internal.h"
35 #include "internal.h"
36 
37 
38 BSSL_NAMESPACE_BEGIN
39 
init_key_schedule(SSL_HANDSHAKE * hs,SSLTranscript * transcript,uint16_t version,const SSL_CIPHER * cipher)40 static bool init_key_schedule(SSL_HANDSHAKE *hs, SSLTranscript *transcript,
41                               uint16_t version, const SSL_CIPHER *cipher) {
42   if (!transcript->InitHash(version, cipher)) {
43     return false;
44   }
45 
46   // Initialize the secret to the zero key.
47   hs->secret.clear();
48   hs->secret.Resize(transcript->DigestLen());
49   return true;
50 }
51 
hkdf_extract_to_secret(SSL_HANDSHAKE * hs,const SSLTranscript & transcript,Span<const uint8_t> in)52 static bool hkdf_extract_to_secret(SSL_HANDSHAKE *hs,
53                                    const SSLTranscript &transcript,
54                                    Span<const uint8_t> in) {
55   size_t len;
56   if (!HKDF_extract(hs->secret.data(), &len, transcript.Digest(), in.data(),
57                     in.size(), hs->secret.data(), hs->secret.size())) {
58     return false;
59   }
60   assert(len == hs->secret.size());
61   return true;
62 }
63 
tls13_init_key_schedule(SSL_HANDSHAKE * hs,Span<const uint8_t> psk)64 bool tls13_init_key_schedule(SSL_HANDSHAKE *hs, Span<const uint8_t> psk) {
65   if (!init_key_schedule(hs, &hs->transcript, ssl_protocol_version(hs->ssl),
66                          hs->new_cipher)) {
67     return false;
68   }
69 
70   // Handback includes the whole handshake transcript, so we cannot free the
71   // transcript buffer in the handback case.
72   if (!hs->handback) {
73     hs->transcript.FreeBuffer();
74   }
75   return hkdf_extract_to_secret(hs, hs->transcript, psk);
76 }
77 
tls13_init_early_key_schedule(SSL_HANDSHAKE * hs,const SSL_SESSION * session)78 bool tls13_init_early_key_schedule(SSL_HANDSHAKE *hs,
79                                    const SSL_SESSION *session) {
80   assert(!hs->ssl->server);
81   // When offering ECH, early data is associated with ClientHelloInner, not
82   // ClientHelloOuter.
83   SSLTranscript *transcript =
84       hs->selected_ech_config ? &hs->inner_transcript : &hs->transcript;
85   return init_key_schedule(hs, transcript,
86                            ssl_session_protocol_version(session),
87                            session->cipher) &&
88          hkdf_extract_to_secret(hs, *transcript, session->secret);
89 }
90 
hkdf_expand_label_with_prefix(Span<uint8_t> out,const EVP_MD * digest,Span<const uint8_t> secret,std::string_view label_prefix,std::string_view label,Span<const uint8_t> hash)91 static bool hkdf_expand_label_with_prefix(Span<uint8_t> out,
92                                           const EVP_MD *digest,
93                                           Span<const uint8_t> secret,
94                                           std::string_view label_prefix,
95                                           std::string_view label,
96                                           Span<const uint8_t> hash) {
97   // This is a copy of CRYPTO_tls13_hkdf_expand_label, but modified to take an
98   // arbitrary prefix for the label instead of using the hardcoded "tls13 "
99   // prefix.
100   CBB cbb, child;
101   uint8_t *hkdf_label = NULL;
102   size_t hkdf_label_len;
103   CBB_zero(&cbb);
104   if (!CBB_init(&cbb,
105                 2 + 1 + label_prefix.size() + label.size() + 1 + hash.size()) ||
106       !CBB_add_u16(&cbb, out.size()) ||
107       !CBB_add_u8_length_prefixed(&cbb, &child) ||
108       !CBB_add_bytes(&child,
109                      reinterpret_cast<const uint8_t *>(label_prefix.data()),
110                      label_prefix.size()) ||
111       !CBB_add_bytes(&child, reinterpret_cast<const uint8_t *>(label.data()),
112                      label.size()) ||
113       !CBB_add_u8_length_prefixed(&cbb, &child) ||
114       !CBB_add_bytes(&child, hash.data(), hash.size()) ||
115       !CBB_finish(&cbb, &hkdf_label, &hkdf_label_len)) {
116     CBB_cleanup(&cbb);
117     return false;
118   }
119 
120   const int ret = HKDF_expand(out.data(), out.size(), digest, secret.data(),
121                               secret.size(), hkdf_label, hkdf_label_len);
122   OPENSSL_free(hkdf_label);
123   return ret == 1;
124 }
125 
hkdf_expand_label(Span<uint8_t> out,const EVP_MD * digest,Span<const uint8_t> secret,std::string_view label,Span<const uint8_t> hash,bool is_dtls)126 static bool hkdf_expand_label(Span<uint8_t> out, const EVP_MD *digest,
127                               Span<const uint8_t> secret,
128                               std::string_view label, Span<const uint8_t> hash,
129                               bool is_dtls) {
130   if (is_dtls) {
131     return hkdf_expand_label_with_prefix(out, digest, secret, "dtls13", label,
132                                          hash);
133   }
134   return CRYPTO_tls13_hkdf_expand_label(
135              out.data(), out.size(), digest, secret.data(), secret.size(),
136              reinterpret_cast<const uint8_t *>(label.data()), label.size(),
137              hash.data(), hash.size()) == 1;
138 }
139 
140 static const char kTLS13LabelDerived[] = "derived";
141 
tls13_advance_key_schedule(SSL_HANDSHAKE * hs,Span<const uint8_t> in)142 bool tls13_advance_key_schedule(SSL_HANDSHAKE *hs, Span<const uint8_t> in) {
143   uint8_t derive_context[EVP_MAX_MD_SIZE];
144   unsigned derive_context_len;
145   return EVP_Digest(nullptr, 0, derive_context, &derive_context_len,
146                     hs->transcript.Digest(), nullptr) &&
147          hkdf_expand_label(Span(hs->secret), hs->transcript.Digest(),
148                            hs->secret, kTLS13LabelDerived,
149                            Span(derive_context, derive_context_len),
150                            SSL_is_dtls(hs->ssl)) &&
151          hkdf_extract_to_secret(hs, hs->transcript, in);
152 }
153 
154 // derive_secret_with_transcript derives a secret of length
155 // |transcript.DigestLen()| and writes the result in |out| with the given label,
156 // the current base secret, and the state of |transcript|. It returns true on
157 // success and false on error.
derive_secret_with_transcript(const SSL_HANDSHAKE * hs,InplaceVector<uint8_t,SSL_MAX_MD_SIZE> * out,const SSLTranscript & transcript,std::string_view label)158 static bool derive_secret_with_transcript(
159     const SSL_HANDSHAKE *hs, InplaceVector<uint8_t, SSL_MAX_MD_SIZE> *out,
160     const SSLTranscript &transcript, std::string_view label) {
161   uint8_t context_hash[EVP_MAX_MD_SIZE];
162   size_t context_hash_len;
163   if (!transcript.GetHash(context_hash, &context_hash_len)) {
164     return false;
165   }
166 
167   out->ResizeForOverwrite(transcript.DigestLen());
168   return hkdf_expand_label(Span(*out), transcript.Digest(), hs->secret, label,
169                            Span(context_hash, context_hash_len),
170                            SSL_is_dtls(hs->ssl));
171 }
172 
derive_secret(SSL_HANDSHAKE * hs,InplaceVector<uint8_t,SSL_MAX_MD_SIZE> * out,std::string_view label)173 static bool derive_secret(SSL_HANDSHAKE *hs,
174                           InplaceVector<uint8_t, SSL_MAX_MD_SIZE> *out,
175                           std::string_view label) {
176   return derive_secret_with_transcript(hs, out, hs->transcript, label);
177 }
178 
tls13_set_traffic_key(SSL * ssl,enum ssl_encryption_level_t level,enum evp_aead_direction_t direction,const SSL_SESSION * session,Span<const uint8_t> traffic_secret)179 bool tls13_set_traffic_key(SSL *ssl, enum ssl_encryption_level_t level,
180                            enum evp_aead_direction_t direction,
181                            const SSL_SESSION *session,
182                            Span<const uint8_t> traffic_secret) {
183   uint16_t version = ssl_session_protocol_version(session);
184   const EVP_MD *digest = ssl_session_get_digest(session);
185   bool is_dtls = SSL_is_dtls(ssl);
186   UniquePtr<SSLAEADContext> traffic_aead;
187   if (SSL_is_quic(ssl)) {
188     // Install a placeholder SSLAEADContext so that SSL accessors work. The
189     // encryption itself will be handled by the SSL_QUIC_METHOD.
190     traffic_aead = SSLAEADContext::CreatePlaceholderForQUIC(session->cipher);
191   } else {
192     // Look up cipher suite properties.
193     const EVP_AEAD *aead;
194     size_t discard;
195     if (!ssl_cipher_get_evp_aead(&aead, &discard, &discard, session->cipher,
196                                  version)) {
197       return false;
198     }
199 
200     // Derive the key and IV.
201     uint8_t key_buf[EVP_AEAD_MAX_KEY_LENGTH], iv_buf[EVP_AEAD_MAX_NONCE_LENGTH];
202     auto key = Span(key_buf).first(EVP_AEAD_key_length(aead));
203     auto iv = Span(iv_buf).first(EVP_AEAD_nonce_length(aead));
204     if (!hkdf_expand_label(key, digest, traffic_secret, "key", {}, is_dtls) ||
205         !hkdf_expand_label(iv, digest, traffic_secret, "iv", {}, is_dtls)) {
206       return false;
207     }
208 
209     traffic_aead = SSLAEADContext::Create(direction, session->ssl_version,
210                                           session->cipher, key, {}, iv);
211   }
212 
213   if (!traffic_aead) {
214     return false;
215   }
216 
217   if (direction == evp_aead_open) {
218     if (!ssl->method->set_read_state(ssl, level, std::move(traffic_aead),
219                                      traffic_secret)) {
220       return false;
221     }
222     ssl->s3->read_traffic_secret.CopyFrom(traffic_secret);
223   } else {
224     if (!ssl->method->set_write_state(ssl, level, std::move(traffic_aead),
225                                       traffic_secret)) {
226       return false;
227     }
228     ssl->s3->write_traffic_secret.CopyFrom(traffic_secret);
229   }
230 
231   return true;
232 }
233 
234 namespace {
235 
236 class AESRecordNumberEncrypter : public RecordNumberEncrypter {
237  public:
SetKey(Span<const uint8_t> key)238   bool SetKey(Span<const uint8_t> key) override {
239     return AES_set_encrypt_key(key.data(), key.size() * 8, &key_) == 0;
240   }
241 
GenerateMask(Span<uint8_t> out,Span<const uint8_t> sample)242   bool GenerateMask(Span<uint8_t> out, Span<const uint8_t> sample) override {
243     if (sample.size() < AES_BLOCK_SIZE || out.size() > AES_BLOCK_SIZE) {
244       return false;
245     }
246     uint8_t mask[AES_BLOCK_SIZE];
247     AES_encrypt(sample.data(), mask, &key_);
248     OPENSSL_memcpy(out.data(), mask, out.size());
249     return true;
250   }
251 
252  private:
253   AES_KEY key_;
254 };
255 
256 class AES128RecordNumberEncrypter : public AESRecordNumberEncrypter {
257  public:
KeySize()258   size_t KeySize() override { return 16; }
259 };
260 
261 class AES256RecordNumberEncrypter : public AESRecordNumberEncrypter {
262  public:
KeySize()263   size_t KeySize() override { return 32; }
264 };
265 
266 class ChaChaRecordNumberEncrypter : public RecordNumberEncrypter {
267  public:
KeySize()268   size_t KeySize() override { return kKeySize; }
269 
SetKey(Span<const uint8_t> key)270   bool SetKey(Span<const uint8_t> key) override {
271     if (key.size() != kKeySize) {
272       return false;
273     }
274     OPENSSL_memcpy(key_, key.data(), key.size());
275     return true;
276   }
277 
GenerateMask(Span<uint8_t> out,Span<const uint8_t> sample)278   bool GenerateMask(Span<uint8_t> out, Span<const uint8_t> sample) override {
279     // RFC 9147 section 4.2.3 uses the first 4 bytes of the sample as the
280     // counter and the next 12 bytes as the nonce. If we have less than 4+12=16
281     // bytes in the sample, then we'll read past the end of the |sample| buffer.
282     // The counter is interpreted as little-endian per RFC 8439.
283     if (sample.size() < 16) {
284       return false;
285     }
286     uint32_t counter = CRYPTO_load_u32_le(sample.data());
287     Span<const uint8_t> nonce = sample.subspan(4);
288     OPENSSL_memset(out.data(), 0, out.size());
289     CRYPTO_chacha_20(out.data(), out.data(), out.size(), key_, nonce.data(),
290                      counter);
291     return true;
292   }
293 
294  private:
295   static constexpr size_t kKeySize = 32;
296   uint8_t key_[kKeySize];
297 };
298 
299 class NullRecordNumberEncrypter : public RecordNumberEncrypter {
300  public:
KeySize()301   size_t KeySize() override { return 0; }
SetKey(Span<const uint8_t> key)302   bool SetKey(Span<const uint8_t> key) override { return true; }
GenerateMask(Span<uint8_t> out,Span<const uint8_t> sample)303   bool GenerateMask(Span<uint8_t> out, Span<const uint8_t> sample) override {
304     OPENSSL_memset(out.data(), 0, out.size());
305     return true;
306   }
307 };
308 
309 }  // namespace
310 
Create(const SSL_CIPHER * cipher,Span<const uint8_t> traffic_secret)311 UniquePtr<RecordNumberEncrypter> RecordNumberEncrypter::Create(
312     const SSL_CIPHER *cipher, Span<const uint8_t> traffic_secret) {
313   const EVP_MD *digest = ssl_get_handshake_digest(TLS1_3_VERSION, cipher);
314   UniquePtr<RecordNumberEncrypter> ret;
315   if (CRYPTO_fuzzer_mode_enabled()) {
316     ret = MakeUnique<NullRecordNumberEncrypter>();
317   } else if (cipher->algorithm_enc == SSL_AES128GCM) {
318     ret = MakeUnique<AES128RecordNumberEncrypter>();
319   } else if (cipher->algorithm_enc == SSL_AES256GCM) {
320     ret = MakeUnique<AES256RecordNumberEncrypter>();
321   } else if (cipher->algorithm_enc == SSL_CHACHA20POLY1305) {
322     ret = MakeUnique<ChaChaRecordNumberEncrypter>();
323   } else {
324     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
325   }
326   if (ret == nullptr) {
327     return nullptr;
328   }
329 
330   uint8_t rne_key_buf[RecordNumberEncrypter::kMaxKeySize];
331   auto rne_key = Span(rne_key_buf).first(ret->KeySize());
332   if (!hkdf_expand_label(rne_key, digest, traffic_secret, "sn", {},
333                          /*is_dtls=*/true) ||
334       !ret->SetKey(rne_key)) {
335     return nullptr;
336   }
337   return ret;
338 }
339 
340 static const char kTLS13LabelExporter[] = "exp master";
341 
342 static const char kTLS13LabelClientEarlyTraffic[] = "c e traffic";
343 static const char kTLS13LabelClientHandshakeTraffic[] = "c hs traffic";
344 static const char kTLS13LabelServerHandshakeTraffic[] = "s hs traffic";
345 static const char kTLS13LabelClientApplicationTraffic[] = "c ap traffic";
346 static const char kTLS13LabelServerApplicationTraffic[] = "s ap traffic";
347 
tls13_derive_early_secret(SSL_HANDSHAKE * hs)348 bool tls13_derive_early_secret(SSL_HANDSHAKE *hs) {
349   SSL *const ssl = hs->ssl;
350   // When offering ECH on the client, early data is associated with
351   // ClientHelloInner, not ClientHelloOuter.
352   const SSLTranscript &transcript = (!ssl->server && hs->selected_ech_config)
353                                         ? hs->inner_transcript
354                                         : hs->transcript;
355   if (!derive_secret_with_transcript(hs, &hs->early_traffic_secret, transcript,
356                                      kTLS13LabelClientEarlyTraffic) ||
357       !ssl_log_secret(ssl, "CLIENT_EARLY_TRAFFIC_SECRET",
358                       hs->early_traffic_secret)) {
359     return false;
360   }
361   return true;
362 }
363 
tls13_derive_handshake_secrets(SSL_HANDSHAKE * hs)364 bool tls13_derive_handshake_secrets(SSL_HANDSHAKE *hs) {
365   SSL *const ssl = hs->ssl;
366   if (!derive_secret(hs, &hs->client_handshake_secret,
367                      kTLS13LabelClientHandshakeTraffic) ||
368       !ssl_log_secret(ssl, "CLIENT_HANDSHAKE_TRAFFIC_SECRET",
369                       hs->client_handshake_secret) ||
370       !derive_secret(hs, &hs->server_handshake_secret,
371                      kTLS13LabelServerHandshakeTraffic) ||
372       !ssl_log_secret(ssl, "SERVER_HANDSHAKE_TRAFFIC_SECRET",
373                       hs->server_handshake_secret)) {
374     return false;
375   }
376 
377   return true;
378 }
379 
tls13_derive_application_secrets(SSL_HANDSHAKE * hs)380 bool tls13_derive_application_secrets(SSL_HANDSHAKE *hs) {
381   SSL *const ssl = hs->ssl;
382   if (!derive_secret(hs, &hs->client_traffic_secret_0,
383                      kTLS13LabelClientApplicationTraffic) ||
384       !ssl_log_secret(ssl, "CLIENT_TRAFFIC_SECRET_0",
385                       hs->client_traffic_secret_0) ||
386       !derive_secret(hs, &hs->server_traffic_secret_0,
387                      kTLS13LabelServerApplicationTraffic) ||
388       !ssl_log_secret(ssl, "SERVER_TRAFFIC_SECRET_0",
389                       hs->server_traffic_secret_0) ||
390       !derive_secret(hs, &ssl->s3->exporter_secret, kTLS13LabelExporter) ||
391       !ssl_log_secret(ssl, "EXPORTER_SECRET", ssl->s3->exporter_secret)) {
392     return false;
393   }
394 
395   return true;
396 }
397 
398 static const char kTLS13LabelApplicationTraffic[] = "traffic upd";
399 
tls13_rotate_traffic_key(SSL * ssl,enum evp_aead_direction_t direction)400 bool tls13_rotate_traffic_key(SSL *ssl, enum evp_aead_direction_t direction) {
401   Span<uint8_t> secret = direction == evp_aead_open
402                              ? Span(ssl->s3->read_traffic_secret)
403                              : Span(ssl->s3->write_traffic_secret);
404 
405   const SSL_SESSION *session = SSL_get_session(ssl);
406   const EVP_MD *digest = ssl_session_get_digest(session);
407   return hkdf_expand_label(secret, digest, secret,
408                            kTLS13LabelApplicationTraffic, {},
409                            SSL_is_dtls(ssl)) &&
410          tls13_set_traffic_key(ssl, ssl_encryption_application, direction,
411                                session, secret);
412 }
413 
414 static const char kTLS13LabelResumption[] = "res master";
415 
tls13_derive_resumption_secret(SSL_HANDSHAKE * hs)416 bool tls13_derive_resumption_secret(SSL_HANDSHAKE *hs) {
417   return derive_secret(hs, &hs->new_session->secret, kTLS13LabelResumption);
418 }
419 
420 static const char kTLS13LabelFinished[] = "finished";
421 
422 // tls13_verify_data sets |out| to be the HMAC of |context| using a derived
423 // Finished key for both Finished messages and the PSK binder. |out| must have
424 // space available for |EVP_MAX_MD_SIZE| bytes.
tls13_verify_data(uint8_t * out,size_t * out_len,const EVP_MD * digest,uint16_t version,Span<const uint8_t> secret,Span<const uint8_t> context,bool is_dtls)425 static bool tls13_verify_data(uint8_t *out, size_t *out_len,
426                               const EVP_MD *digest, uint16_t version,
427                               Span<const uint8_t> secret,
428                               Span<const uint8_t> context, bool is_dtls) {
429   uint8_t key_buf[EVP_MAX_MD_SIZE];
430   auto key = Span(key_buf, EVP_MD_size(digest));
431   unsigned len;
432   if (!hkdf_expand_label(key, digest, secret, kTLS13LabelFinished, {},
433                          is_dtls) ||
434       HMAC(digest, key.data(), key.size(), context.data(), context.size(), out,
435            &len) == nullptr) {
436     return false;
437   }
438   *out_len = len;
439   return true;
440 }
441 
tls13_finished_mac(SSL_HANDSHAKE * hs,uint8_t * out,size_t * out_len,bool is_server)442 bool tls13_finished_mac(SSL_HANDSHAKE *hs, uint8_t *out, size_t *out_len,
443                         bool is_server) {
444   Span<const uint8_t> traffic_secret =
445       is_server ? hs->server_handshake_secret : hs->client_handshake_secret;
446 
447   uint8_t context_hash[EVP_MAX_MD_SIZE];
448   size_t context_hash_len;
449   if (!hs->transcript.GetHash(context_hash, &context_hash_len) ||
450       !tls13_verify_data(out, out_len, hs->transcript.Digest(),
451                          hs->ssl->s3->version, traffic_secret,
452                          Span(context_hash, context_hash_len),
453                          SSL_is_dtls(hs->ssl))) {
454     return false;
455   }
456   return true;
457 }
458 
459 static const char kTLS13LabelResumptionPSK[] = "resumption";
460 
tls13_derive_session_psk(SSL_SESSION * session,Span<const uint8_t> nonce,bool is_dtls)461 bool tls13_derive_session_psk(SSL_SESSION *session, Span<const uint8_t> nonce,
462                               bool is_dtls) {
463   const EVP_MD *digest = ssl_session_get_digest(session);
464   // The session initially stores the resumption_master_secret, which we
465   // override with the PSK.
466   assert(session->secret.size() == EVP_MD_size(digest));
467   return hkdf_expand_label(Span(session->secret), digest, session->secret,
468                            kTLS13LabelResumptionPSK, nonce, is_dtls);
469 }
470 
471 static const char kTLS13LabelExportKeying[] = "exporter";
472 
tls13_export_keying_material(const SSL * ssl,Span<uint8_t> out,Span<const uint8_t> secret,std::string_view label,Span<const uint8_t> context)473 bool tls13_export_keying_material(const SSL *ssl, Span<uint8_t> out,
474                                   Span<const uint8_t> secret,
475                                   std::string_view label,
476                                   Span<const uint8_t> context) {
477   if (secret.empty()) {
478     assert(0);
479     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
480     return false;
481   }
482 
483   const EVP_MD *digest = ssl_session_get_digest(SSL_get_session(ssl));
484 
485   uint8_t hash_buf[EVP_MAX_MD_SIZE];
486   uint8_t export_context_buf[EVP_MAX_MD_SIZE];
487   unsigned hash_len;
488   unsigned export_context_len;
489   if (!EVP_Digest(context.data(), context.size(), hash_buf, &hash_len, digest,
490                   nullptr) ||
491       !EVP_Digest(nullptr, 0, export_context_buf, &export_context_len, digest,
492                   nullptr)) {
493     return false;
494   }
495 
496   auto hash = Span(hash_buf, hash_len);
497   auto export_context = Span(export_context_buf, export_context_len);
498   uint8_t derived_secret_buf[EVP_MAX_MD_SIZE];
499   auto derived_secret = Span(derived_secret_buf, EVP_MD_size(digest));
500   return hkdf_expand_label(derived_secret, digest, secret, label,
501                            export_context, SSL_is_dtls(ssl)) &&
502          hkdf_expand_label(out, digest, derived_secret, kTLS13LabelExportKeying,
503                            hash, SSL_is_dtls(ssl));
504 }
505 
506 static const char kTLS13LabelPSKBinder[] = "res binder";
507 
tls13_psk_binder(uint8_t * out,size_t * out_len,const SSL_SESSION * session,const SSLTranscript & transcript,Span<const uint8_t> client_hello,size_t binders_len,bool is_dtls)508 static bool tls13_psk_binder(uint8_t *out, size_t *out_len,
509                              const SSL_SESSION *session,
510                              const SSLTranscript &transcript,
511                              Span<const uint8_t> client_hello,
512                              size_t binders_len, bool is_dtls) {
513   const EVP_MD *digest = ssl_session_get_digest(session);
514 
515   // Compute the binder key.
516   //
517   // TODO(davidben): Ideally we wouldn't recompute early secret and the binder
518   // key each time.
519   uint8_t binder_context[EVP_MAX_MD_SIZE];
520   unsigned binder_context_len;
521   uint8_t early_secret[EVP_MAX_MD_SIZE] = {0};
522   size_t early_secret_len;
523   uint8_t binder_key_buf[EVP_MAX_MD_SIZE] = {0};
524   auto binder_key = Span(binder_key_buf, EVP_MD_size(digest));
525   if (!EVP_Digest(nullptr, 0, binder_context, &binder_context_len, digest,
526                   nullptr) ||
527       !HKDF_extract(early_secret, &early_secret_len, digest,
528                     session->secret.data(), session->secret.size(), nullptr,
529                     0) ||
530       !hkdf_expand_label(binder_key, digest,
531                          Span(early_secret, early_secret_len),
532                          kTLS13LabelPSKBinder,
533                          Span(binder_context, binder_context_len), is_dtls)) {
534     return false;
535   }
536 
537   // Hash the transcript and truncated ClientHello.
538   if (client_hello.size() < binders_len) {
539     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
540     return false;
541   }
542   auto truncated = client_hello.subspan(0, client_hello.size() - binders_len);
543   uint8_t context[EVP_MAX_MD_SIZE];
544   unsigned context_len;
545   ScopedEVP_MD_CTX ctx;
546   if (!is_dtls) {
547     if (!transcript.CopyToHashContext(ctx.get(), digest) ||
548         !EVP_DigestUpdate(ctx.get(), truncated.data(), truncated.size()) ||
549         !EVP_DigestFinal_ex(ctx.get(), context, &context_len)) {
550       return false;
551     }
552   } else {
553     // In DTLS 1.3, the transcript hash is computed over only the TLS 1.3
554     // handshake messages (i.e. only type and length in the header), not the
555     // full DTLSHandshake messages that are in |truncated|. This code pulls
556     // the header and body out of the truncated ClientHello and writes those
557     // to the hash context so the correct binder value is computed.
558     if (truncated.size() < DTLS1_HM_HEADER_LENGTH) {
559       return false;
560     }
561     auto header = truncated.subspan(0, 4);
562     auto body = truncated.subspan(12);
563     if (!transcript.CopyToHashContext(ctx.get(), digest) ||
564         !EVP_DigestUpdate(ctx.get(), header.data(), header.size()) ||
565         !EVP_DigestUpdate(ctx.get(), body.data(), body.size()) ||
566         !EVP_DigestFinal_ex(ctx.get(), context, &context_len)) {
567       return false;
568     }
569   }
570 
571   if (!tls13_verify_data(out, out_len, digest, session->ssl_version, binder_key,
572                          Span(context, context_len), is_dtls)) {
573     return false;
574   }
575 
576   assert(*out_len == EVP_MD_size(digest));
577   return true;
578 }
579 
tls13_write_psk_binder(const SSL_HANDSHAKE * hs,const SSLTranscript & transcript,Span<uint8_t> msg,size_t * out_binder_len)580 bool tls13_write_psk_binder(const SSL_HANDSHAKE *hs,
581                             const SSLTranscript &transcript, Span<uint8_t> msg,
582                             size_t *out_binder_len) {
583   const SSL *const ssl = hs->ssl;
584   const EVP_MD *digest = ssl_session_get_digest(ssl->session.get());
585   const size_t hash_len = EVP_MD_size(digest);
586   // We only offer one PSK, so the binders are a u16 and u8 length
587   // prefix, followed by the binder. The caller is assumed to have constructed
588   // |msg| with placeholder binders.
589   const size_t binders_len = 3 + hash_len;
590   uint8_t verify_data[EVP_MAX_MD_SIZE];
591   size_t verify_data_len;
592   if (!tls13_psk_binder(verify_data, &verify_data_len, ssl->session.get(),
593                         transcript, msg, binders_len, SSL_is_dtls(hs->ssl)) ||
594       verify_data_len != hash_len) {
595     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
596     return false;
597   }
598 
599   auto msg_binder = msg.last(verify_data_len);
600   OPENSSL_memcpy(msg_binder.data(), verify_data, verify_data_len);
601   if (out_binder_len != nullptr) {
602     *out_binder_len = verify_data_len;
603   }
604   return true;
605 }
606 
tls13_verify_psk_binder(const SSL_HANDSHAKE * hs,const SSL_SESSION * session,const SSLMessage & msg,CBS * binders)607 bool tls13_verify_psk_binder(const SSL_HANDSHAKE *hs,
608                              const SSL_SESSION *session, const SSLMessage &msg,
609                              CBS *binders) {
610   uint8_t verify_data[EVP_MAX_MD_SIZE];
611   size_t verify_data_len;
612   CBS binder;
613   // The binders are computed over |msg| with |binders| and its u16 length
614   // prefix removed. The caller is assumed to have parsed |msg|, extracted
615   // |binders|, and verified the PSK extension is last.
616   if (!tls13_psk_binder(verify_data, &verify_data_len, session, hs->transcript,
617                         msg.raw, 2 + CBS_len(binders), SSL_is_dtls(hs->ssl)) ||
618       // We only consider the first PSK, so compare against the first binder.
619       !CBS_get_u8_length_prefixed(binders, &binder)) {
620     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
621     return false;
622   }
623 
624   bool binder_ok =
625       CBS_len(&binder) == verify_data_len &&
626       CRYPTO_memcmp(CBS_data(&binder), verify_data, verify_data_len) == 0;
627   if (CRYPTO_fuzzer_mode_enabled()) {
628     binder_ok = true;
629   }
630   if (!binder_ok) {
631     OPENSSL_PUT_ERROR(SSL, SSL_R_DIGEST_CHECK_FAILED);
632     return false;
633   }
634 
635   return true;
636 }
637 
ssl_ech_confirmation_signal_hello_offset(const SSL * ssl)638 size_t ssl_ech_confirmation_signal_hello_offset(const SSL *ssl) {
639   static_assert(ECH_CONFIRMATION_SIGNAL_LEN < SSL3_RANDOM_SIZE,
640                 "the confirmation signal is a suffix of the random");
641   const size_t header_len =
642       SSL_is_dtls(ssl) ? DTLS1_HM_HEADER_LENGTH : SSL3_HM_HEADER_LENGTH;
643   return header_len + 2 /* version */ + SSL3_RANDOM_SIZE -
644          ECH_CONFIRMATION_SIGNAL_LEN;
645 }
646 
ssl_ech_accept_confirmation(const SSL_HANDSHAKE * hs,Span<uint8_t> out,Span<const uint8_t> client_random,const SSLTranscript & transcript,bool is_hrr,Span<const uint8_t> msg,size_t offset)647 bool ssl_ech_accept_confirmation(const SSL_HANDSHAKE *hs, Span<uint8_t> out,
648                                  Span<const uint8_t> client_random,
649                                  const SSLTranscript &transcript, bool is_hrr,
650                                  Span<const uint8_t> msg, size_t offset) {
651   // See draft-ietf-tls-esni-13, sections 7.2 and 7.2.1.
652   static const uint8_t kZeros[EVP_MAX_MD_SIZE] = {0};
653 
654   // We hash |msg|, with bytes from |offset| zeroed.
655   if (msg.size() < offset + ECH_CONFIRMATION_SIGNAL_LEN) {
656     OPENSSL_PUT_ERROR(SSL, ERR_R_INTERNAL_ERROR);
657     return false;
658   }
659 
660   // We represent DTLS messages with the longer DTLS 1.2 header, but DTLS 1.3
661   // removes the extra fields from the transcript.
662   auto header = msg.subspan(0, SSL3_HM_HEADER_LENGTH);
663   size_t full_header_len =
664       SSL_is_dtls(hs->ssl) ? DTLS1_HM_HEADER_LENGTH : SSL3_HM_HEADER_LENGTH;
665   auto before_zeros = msg.subspan(full_header_len, offset - full_header_len);
666   auto after_zeros = msg.subspan(offset + ECH_CONFIRMATION_SIGNAL_LEN);
667 
668   uint8_t context[EVP_MAX_MD_SIZE];
669   unsigned context_len;
670   ScopedEVP_MD_CTX ctx;
671   if (!transcript.CopyToHashContext(ctx.get(), transcript.Digest()) ||
672       !EVP_DigestUpdate(ctx.get(), header.data(), header.size()) ||
673       !EVP_DigestUpdate(ctx.get(), before_zeros.data(), before_zeros.size()) ||
674       !EVP_DigestUpdate(ctx.get(), kZeros, ECH_CONFIRMATION_SIGNAL_LEN) ||
675       !EVP_DigestUpdate(ctx.get(), after_zeros.data(), after_zeros.size()) ||
676       !EVP_DigestFinal_ex(ctx.get(), context, &context_len)) {
677     return false;
678   }
679 
680   uint8_t secret[EVP_MAX_MD_SIZE];
681   size_t secret_len;
682   if (!HKDF_extract(secret, &secret_len, transcript.Digest(),
683                     client_random.data(), client_random.size(), kZeros,
684                     transcript.DigestLen())) {
685     return false;
686   }
687 
688   assert(out.size() == ECH_CONFIRMATION_SIGNAL_LEN);
689   return hkdf_expand_label(
690       out, transcript.Digest(), Span(secret, secret_len),
691       is_hrr ? "hrr ech accept confirmation" : "ech accept confirmation",
692       Span(context, context_len), SSL_is_dtls(hs->ssl));
693 }
694 
695 BSSL_NAMESPACE_END
696