xref: /freebsd/crypto/openssl/ssl/tls13_enc.c (revision e7be843b4a162e68651d3911f0357ed464915629)
1 /*
2  * Copyright 2016-2025 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the Apache License 2.0 (the "License").  You may not use
5  * this file except in compliance with the License.  You can obtain a copy
6  * in the file LICENSE in the source distribution or at
7  * https://www.openssl.org/source/license.html
8  */
9 
10 #include <stdlib.h>
11 #include "ssl_local.h"
12 #include "internal/ktls.h"
13 #include "record/record_local.h"
14 #include "internal/cryptlib.h"
15 #include "internal/ssl_unwrap.h"
16 #include <openssl/evp.h>
17 #include <openssl/kdf.h>
18 #include <openssl/core_names.h>
19 
20 #define TLS13_MAX_LABEL_LEN     249
21 
22 /* ASCII: "tls13 ", in hex for EBCDIC compatibility */
23 static const unsigned char label_prefix[] = "\x74\x6C\x73\x31\x33\x20";
24 
25 /*
26  * Given a |secret|; a |label| of length |labellen|; and |data| of length
27  * |datalen| (e.g. typically a hash of the handshake messages), derive a new
28  * secret |outlen| bytes long and store it in the location pointed to be |out|.
29  * The |data| value may be zero length. Any errors will be treated as fatal if
30  * |fatal| is set. Returns 1 on success  0 on failure.
31  * If |raise_error| is set, ERR_raise is called on failure.
32  */
tls13_hkdf_expand_ex(OSSL_LIB_CTX * libctx,const char * propq,const EVP_MD * md,const unsigned char * secret,const unsigned char * label,size_t labellen,const unsigned char * data,size_t datalen,unsigned char * out,size_t outlen,int raise_error)33 int tls13_hkdf_expand_ex(OSSL_LIB_CTX *libctx, const char *propq,
34                          const EVP_MD *md,
35                          const unsigned char *secret,
36                          const unsigned char *label, size_t labellen,
37                          const unsigned char *data, size_t datalen,
38                          unsigned char *out, size_t outlen, int raise_error)
39 {
40     EVP_KDF *kdf = EVP_KDF_fetch(libctx, OSSL_KDF_NAME_TLS1_3_KDF, propq);
41     EVP_KDF_CTX *kctx;
42     OSSL_PARAM params[7], *p = params;
43     int mode = EVP_PKEY_HKDEF_MODE_EXPAND_ONLY;
44     const char *mdname = EVP_MD_get0_name(md);
45     int ret;
46     size_t hashlen;
47 
48     kctx = EVP_KDF_CTX_new(kdf);
49     EVP_KDF_free(kdf);
50     if (kctx == NULL)
51         return 0;
52 
53     if (labellen > TLS13_MAX_LABEL_LEN) {
54         if (raise_error)
55             /*
56              * Probably we have been called from SSL_export_keying_material(),
57              * or SSL_export_keying_material_early().
58              */
59             ERR_raise(ERR_LIB_SSL, SSL_R_TLS_ILLEGAL_EXPORTER_LABEL);
60 
61         EVP_KDF_CTX_free(kctx);
62         return 0;
63     }
64 
65     if ((ret = EVP_MD_get_size(md)) <= 0) {
66         EVP_KDF_CTX_free(kctx);
67         if (raise_error)
68             ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
69         return 0;
70     }
71     hashlen = (size_t)ret;
72 
73     *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_MODE, &mode);
74     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
75                                             (char *)mdname, 0);
76     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
77                                              (unsigned char *)secret, hashlen);
78     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PREFIX,
79                                              (unsigned char *)label_prefix,
80                                              sizeof(label_prefix) - 1);
81     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_LABEL,
82                                              (unsigned char *)label, labellen);
83     if (data != NULL)
84         *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_DATA,
85                                                  (unsigned char *)data,
86                                                  datalen);
87     *p++ = OSSL_PARAM_construct_end();
88 
89     ret = EVP_KDF_derive(kctx, out, outlen, params) <= 0;
90     EVP_KDF_CTX_free(kctx);
91 
92     if (ret != 0) {
93         if (raise_error)
94             ERR_raise(ERR_LIB_SSL, ERR_R_INTERNAL_ERROR);
95     }
96 
97     return ret == 0;
98 }
99 
tls13_hkdf_expand(SSL_CONNECTION * s,const EVP_MD * md,const unsigned char * secret,const unsigned char * label,size_t labellen,const unsigned char * data,size_t datalen,unsigned char * out,size_t outlen,int fatal)100 int tls13_hkdf_expand(SSL_CONNECTION *s, const EVP_MD *md,
101                       const unsigned char *secret,
102                       const unsigned char *label, size_t labellen,
103                       const unsigned char *data, size_t datalen,
104                       unsigned char *out, size_t outlen, int fatal)
105 {
106     int ret;
107     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
108 
109     ret = tls13_hkdf_expand_ex(sctx->libctx, sctx->propq, md,
110                                secret, label, labellen, data, datalen,
111                                out, outlen, !fatal);
112     if (ret == 0 && fatal)
113         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
114 
115     return ret;
116 }
117 
118 /*
119  * Given a |secret| generate a |key| of length |keylen| bytes. Returns 1 on
120  * success  0 on failure.
121  */
tls13_derive_key(SSL_CONNECTION * s,const EVP_MD * md,const unsigned char * secret,unsigned char * key,size_t keylen)122 int tls13_derive_key(SSL_CONNECTION *s, const EVP_MD *md,
123                      const unsigned char *secret,
124                      unsigned char *key, size_t keylen)
125 {
126     /* ASCII: "key", in hex for EBCDIC compatibility */
127     static const unsigned char keylabel[] = "\x6B\x65\x79";
128 
129     return tls13_hkdf_expand(s, md, secret, keylabel, sizeof(keylabel) - 1,
130                              NULL, 0, key, keylen, 1);
131 }
132 
133 /*
134  * Given a |secret| generate an |iv| of length |ivlen| bytes. Returns 1 on
135  * success  0 on failure.
136  */
tls13_derive_iv(SSL_CONNECTION * s,const EVP_MD * md,const unsigned char * secret,unsigned char * iv,size_t ivlen)137 int tls13_derive_iv(SSL_CONNECTION *s, const EVP_MD *md,
138                     const unsigned char *secret,
139                     unsigned char *iv, size_t ivlen)
140 {
141     /* ASCII: "iv", in hex for EBCDIC compatibility */
142     static const unsigned char ivlabel[] = "\x69\x76";
143 
144     return tls13_hkdf_expand(s, md, secret, ivlabel, sizeof(ivlabel) - 1,
145                              NULL, 0, iv, ivlen, 1);
146 }
147 
tls13_derive_finishedkey(SSL_CONNECTION * s,const EVP_MD * md,const unsigned char * secret,unsigned char * fin,size_t finlen)148 int tls13_derive_finishedkey(SSL_CONNECTION *s, const EVP_MD *md,
149                              const unsigned char *secret,
150                              unsigned char *fin, size_t finlen)
151 {
152     /* ASCII: "finished", in hex for EBCDIC compatibility */
153     static const unsigned char finishedlabel[] = "\x66\x69\x6E\x69\x73\x68\x65\x64";
154 
155     return tls13_hkdf_expand(s, md, secret, finishedlabel,
156                              sizeof(finishedlabel) - 1, NULL, 0, fin, finlen, 1);
157 }
158 
159 /*
160  * Given the previous secret |prevsecret| and a new input secret |insecret| of
161  * length |insecretlen|, generate a new secret and store it in the location
162  * pointed to by |outsecret|. Returns 1 on success  0 on failure.
163  */
tls13_generate_secret(SSL_CONNECTION * s,const EVP_MD * md,const unsigned char * prevsecret,const unsigned char * insecret,size_t insecretlen,unsigned char * outsecret)164 int tls13_generate_secret(SSL_CONNECTION *s, const EVP_MD *md,
165                           const unsigned char *prevsecret,
166                           const unsigned char *insecret,
167                           size_t insecretlen,
168                           unsigned char *outsecret)
169 {
170     size_t mdlen;
171     int mdleni;
172     int ret;
173     EVP_KDF *kdf;
174     EVP_KDF_CTX *kctx;
175     OSSL_PARAM params[7], *p = params;
176     int mode = EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY;
177     const char *mdname = EVP_MD_get0_name(md);
178     /* ASCII: "derived", in hex for EBCDIC compatibility */
179     static const char derived_secret_label[] = "\x64\x65\x72\x69\x76\x65\x64";
180     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
181 
182     kdf = EVP_KDF_fetch(sctx->libctx, OSSL_KDF_NAME_TLS1_3_KDF, sctx->propq);
183     kctx = EVP_KDF_CTX_new(kdf);
184     EVP_KDF_free(kdf);
185     if (kctx == NULL) {
186         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
187         return 0;
188     }
189 
190     mdleni = EVP_MD_get_size(md);
191     /* Ensure cast to size_t is safe */
192     if (!ossl_assert(mdleni > 0)) {
193         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
194         EVP_KDF_CTX_free(kctx);
195         return 0;
196     }
197     mdlen = (size_t)mdleni;
198 
199     *p++ = OSSL_PARAM_construct_int(OSSL_KDF_PARAM_MODE, &mode);
200     *p++ = OSSL_PARAM_construct_utf8_string(OSSL_KDF_PARAM_DIGEST,
201                                             (char *)mdname, 0);
202     if (insecret != NULL)
203         *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_KEY,
204                                                  (unsigned char *)insecret,
205                                                  insecretlen);
206     if (prevsecret != NULL)
207         *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_SALT,
208                                                  (unsigned char *)prevsecret, mdlen);
209     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_PREFIX,
210                                              (unsigned char *)label_prefix,
211                                              sizeof(label_prefix) - 1);
212     *p++ = OSSL_PARAM_construct_octet_string(OSSL_KDF_PARAM_LABEL,
213                                              (unsigned char *)derived_secret_label,
214                                              sizeof(derived_secret_label) - 1);
215     *p++ = OSSL_PARAM_construct_end();
216 
217     ret = EVP_KDF_derive(kctx, outsecret, mdlen, params) <= 0;
218 
219     if (ret != 0)
220         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
221 
222     EVP_KDF_CTX_free(kctx);
223     return ret == 0;
224 }
225 
226 /*
227  * Given an input secret |insecret| of length |insecretlen| generate the
228  * handshake secret. This requires the early secret to already have been
229  * generated. Returns 1 on success  0 on failure.
230  */
tls13_generate_handshake_secret(SSL_CONNECTION * s,const unsigned char * insecret,size_t insecretlen)231 int tls13_generate_handshake_secret(SSL_CONNECTION *s,
232                                     const unsigned char *insecret,
233                                     size_t insecretlen)
234 {
235     /* Calls SSLfatal() if required */
236     return tls13_generate_secret(s, ssl_handshake_md(s), s->early_secret,
237                                  insecret, insecretlen,
238                                  (unsigned char *)&s->handshake_secret);
239 }
240 
241 /*
242  * Given the handshake secret |prev| of length |prevlen| generate the master
243  * secret and store its length in |*secret_size|. Returns 1 on success  0 on
244  * failure.
245  */
tls13_generate_master_secret(SSL_CONNECTION * s,unsigned char * out,unsigned char * prev,size_t prevlen,size_t * secret_size)246 int tls13_generate_master_secret(SSL_CONNECTION *s, unsigned char *out,
247                                  unsigned char *prev, size_t prevlen,
248                                  size_t *secret_size)
249 {
250     const EVP_MD *md = ssl_handshake_md(s);
251     int md_size;
252 
253     md_size = EVP_MD_get_size(md);
254     if (md_size <= 0) {
255         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
256         return 0;
257     }
258     *secret_size = (size_t)md_size;
259     /* Calls SSLfatal() if required */
260     return tls13_generate_secret(s, md, prev, NULL, 0, out);
261 }
262 
263 /*
264  * Generates the mac for the Finished message. Returns the length of the MAC or
265  * 0 on error.
266  */
tls13_final_finish_mac(SSL_CONNECTION * s,const char * str,size_t slen,unsigned char * out)267 size_t tls13_final_finish_mac(SSL_CONNECTION *s, const char *str, size_t slen,
268                              unsigned char *out)
269 {
270     const EVP_MD *md = ssl_handshake_md(s);
271     const char *mdname = EVP_MD_get0_name(md);
272     unsigned char hash[EVP_MAX_MD_SIZE];
273     unsigned char finsecret[EVP_MAX_MD_SIZE];
274     unsigned char *key = NULL;
275     size_t len = 0, hashlen;
276     OSSL_PARAM params[2], *p = params;
277     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
278 
279     if (md == NULL)
280         return 0;
281 
282     /* Safe to cast away const here since we're not "getting" any data */
283     if (sctx->propq != NULL)
284         *p++ = OSSL_PARAM_construct_utf8_string(OSSL_ALG_PARAM_PROPERTIES,
285                                                 (char *)sctx->propq,
286                                                 0);
287     *p = OSSL_PARAM_construct_end();
288 
289     if (!ssl_handshake_hash(s, hash, sizeof(hash), &hashlen)) {
290         /* SSLfatal() already called */
291         goto err;
292     }
293 
294     if (str == SSL_CONNECTION_GET_SSL(s)->method->ssl3_enc->server_finished_label) {
295         key = s->server_finished_secret;
296     } else if (SSL_IS_FIRST_HANDSHAKE(s)) {
297         key = s->client_finished_secret;
298     } else {
299         if (!tls13_derive_finishedkey(s, md,
300                                       s->client_app_traffic_secret,
301                                       finsecret, hashlen))
302             goto err;
303         key = finsecret;
304     }
305 
306     if (!EVP_Q_mac(sctx->libctx, "HMAC", sctx->propq, mdname,
307                    params, key, hashlen, hash, hashlen,
308                    /* outsize as per sizeof(peer_finish_md) */
309                    out, EVP_MAX_MD_SIZE * 2, &len)) {
310         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
311         goto err;
312     }
313 
314  err:
315     OPENSSL_cleanse(finsecret, sizeof(finsecret));
316     return len;
317 }
318 
319 /*
320  * There isn't really a key block in TLSv1.3, but we still need this function
321  * for initialising the cipher and hash. Returns 1 on success or 0 on failure.
322  */
tls13_setup_key_block(SSL_CONNECTION * s)323 int tls13_setup_key_block(SSL_CONNECTION *s)
324 {
325     const EVP_CIPHER *c;
326     const EVP_MD *hash;
327     int mac_type = NID_undef;
328     size_t mac_secret_size = 0;
329 
330     s->session->cipher = s->s3.tmp.new_cipher;
331     if (!ssl_cipher_get_evp(SSL_CONNECTION_GET_CTX(s), s->session, &c, &hash,
332                             &mac_type, &mac_secret_size, NULL, 0)) {
333         /* Error is already recorded */
334         SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
335         return 0;
336     }
337 
338     ssl_evp_cipher_free(s->s3.tmp.new_sym_enc);
339     s->s3.tmp.new_sym_enc = c;
340     ssl_evp_md_free(s->s3.tmp.new_hash);
341     s->s3.tmp.new_hash = hash;
342     s->s3.tmp.new_mac_pkey_type = mac_type;
343     s->s3.tmp.new_mac_secret_size = mac_secret_size;
344 
345     return 1;
346 }
347 
derive_secret_key_and_iv(SSL_CONNECTION * s,const EVP_MD * md,const EVP_CIPHER * ciph,int mac_type,const EVP_MD * mac_md,const unsigned char * insecret,const unsigned char * hash,const unsigned char * label,size_t labellen,unsigned char * secret,unsigned char * key,size_t * keylen,unsigned char ** iv,size_t * ivlen,size_t * taglen)348 static int derive_secret_key_and_iv(SSL_CONNECTION *s, const EVP_MD *md,
349                                     const EVP_CIPHER *ciph,
350                                     int mac_type,
351                                     const EVP_MD *mac_md,
352                                     const unsigned char *insecret,
353                                     const unsigned char *hash,
354                                     const unsigned char *label,
355                                     size_t labellen, unsigned char *secret,
356                                     unsigned char *key, size_t *keylen,
357                                     unsigned char **iv, size_t *ivlen,
358                                     size_t *taglen)
359 {
360     int hashleni = EVP_MD_get_size(md);
361     size_t hashlen;
362     int mode, mac_mdleni;
363 
364     /* Ensure cast to size_t is safe */
365     if (!ossl_assert(hashleni > 0)) {
366         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
367         return 0;
368     }
369     hashlen = (size_t)hashleni;
370 
371     if (!tls13_hkdf_expand(s, md, insecret, label, labellen, hash, hashlen,
372                            secret, hashlen, 1)) {
373         /* SSLfatal() already called */
374         return 0;
375     }
376 
377     /* if ciph is NULL cipher, then use new_hash to calculate keylen */
378     if (EVP_CIPHER_is_a(ciph, "NULL")
379         && mac_md != NULL
380         && mac_type == NID_hmac) {
381         mac_mdleni = EVP_MD_get_size(mac_md);
382 
383         if (mac_mdleni <= 0) {
384             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
385             return 0;
386         }
387         *ivlen = *taglen = (size_t)mac_mdleni;
388         *keylen = s->s3.tmp.new_mac_secret_size;
389     } else {
390 
391         *keylen = EVP_CIPHER_get_key_length(ciph);
392 
393         mode = EVP_CIPHER_get_mode(ciph);
394         if (mode == EVP_CIPH_CCM_MODE) {
395             uint32_t algenc;
396 
397             *ivlen = EVP_CCM_TLS_IV_LEN;
398             if (s->s3.tmp.new_cipher != NULL) {
399                 algenc = s->s3.tmp.new_cipher->algorithm_enc;
400             } else if (s->session->cipher != NULL) {
401                 /* We've not selected a cipher yet - we must be doing early data */
402                 algenc = s->session->cipher->algorithm_enc;
403             } else if (s->psksession != NULL && s->psksession->cipher != NULL) {
404                 /* We must be doing early data with out-of-band PSK */
405                 algenc = s->psksession->cipher->algorithm_enc;
406             } else {
407                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
408                 return 0;
409             }
410             if (algenc & (SSL_AES128CCM8 | SSL_AES256CCM8))
411                 *taglen = EVP_CCM8_TLS_TAG_LEN;
412             else
413                 *taglen = EVP_CCM_TLS_TAG_LEN;
414         } else {
415             int iivlen;
416 
417             if (mode == EVP_CIPH_GCM_MODE) {
418                 *taglen = EVP_GCM_TLS_TAG_LEN;
419             } else {
420                 /* CHACHA20P-POLY1305 */
421                 *taglen = EVP_CHACHAPOLY_TLS_TAG_LEN;
422             }
423             iivlen = EVP_CIPHER_get_iv_length(ciph);
424             if (iivlen < 0) {
425                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
426                 return 0;
427             }
428             *ivlen = iivlen;
429         }
430     }
431 
432     if (*ivlen > EVP_MAX_IV_LENGTH) {
433         *iv = OPENSSL_malloc(*ivlen);
434         if (*iv == NULL) {
435             SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_MALLOC_FAILURE);
436             return 0;
437         }
438     }
439 
440     if (!tls13_derive_key(s, md, secret, key, *keylen)
441             || !tls13_derive_iv(s, md, secret, *iv, *ivlen)) {
442         /* SSLfatal() already called */
443         return 0;
444     }
445 
446     return 1;
447 }
448 
tls13_store_hash(SSL_CONNECTION * s,unsigned char * hash,size_t len)449 static int tls13_store_hash(SSL_CONNECTION *s, unsigned char *hash, size_t len)
450 {
451     size_t hashlen;
452 
453     if (!ssl3_digest_cached_records(s, 1)
454             || !ssl_handshake_hash(s, hash, len, &hashlen)) {
455         /* SSLfatal() already called */;
456         return 0;
457     }
458 
459     return 1;
460 }
461 
tls13_store_handshake_traffic_hash(SSL_CONNECTION * s)462 int tls13_store_handshake_traffic_hash(SSL_CONNECTION *s)
463 {
464     return tls13_store_hash(s, s->handshake_traffic_hash,
465                             sizeof(s->handshake_traffic_hash));
466 }
467 
tls13_store_server_finished_hash(SSL_CONNECTION * s)468 int tls13_store_server_finished_hash(SSL_CONNECTION *s)
469 {
470     return tls13_store_hash(s, s->server_finished_hash,
471                             sizeof(s->server_finished_hash));
472 }
473 
tls13_change_cipher_state(SSL_CONNECTION * s,int which)474 int tls13_change_cipher_state(SSL_CONNECTION *s, int which)
475 {
476     /* ASCII: "c e traffic", in hex for EBCDIC compatibility */
477     static const unsigned char client_early_traffic[] = "\x63\x20\x65\x20\x74\x72\x61\x66\x66\x69\x63";
478     /* ASCII: "c hs traffic", in hex for EBCDIC compatibility */
479     static const unsigned char client_handshake_traffic[] = "\x63\x20\x68\x73\x20\x74\x72\x61\x66\x66\x69\x63";
480     /* ASCII: "c ap traffic", in hex for EBCDIC compatibility */
481     static const unsigned char client_application_traffic[] = "\x63\x20\x61\x70\x20\x74\x72\x61\x66\x66\x69\x63";
482     /* ASCII: "s hs traffic", in hex for EBCDIC compatibility */
483     static const unsigned char server_handshake_traffic[] = "\x73\x20\x68\x73\x20\x74\x72\x61\x66\x66\x69\x63";
484     /* ASCII: "s ap traffic", in hex for EBCDIC compatibility */
485     static const unsigned char server_application_traffic[] = "\x73\x20\x61\x70\x20\x74\x72\x61\x66\x66\x69\x63";
486     /* ASCII: "exp master", in hex for EBCDIC compatibility */
487     static const unsigned char exporter_master_secret[] = "\x65\x78\x70\x20\x6D\x61\x73\x74\x65\x72";
488     /* ASCII: "res master", in hex for EBCDIC compatibility */
489     static const unsigned char resumption_master_secret[] = "\x72\x65\x73\x20\x6D\x61\x73\x74\x65\x72";
490     /* ASCII: "e exp master", in hex for EBCDIC compatibility */
491     static const unsigned char early_exporter_master_secret[] = "\x65\x20\x65\x78\x70\x20\x6D\x61\x73\x74\x65\x72";
492     unsigned char iv_intern[EVP_MAX_IV_LENGTH];
493     unsigned char *iv = iv_intern;
494     unsigned char key[EVP_MAX_KEY_LENGTH];
495     unsigned char secret[EVP_MAX_MD_SIZE];
496     unsigned char hashval[EVP_MAX_MD_SIZE];
497     unsigned char *hash = hashval;
498     unsigned char *insecret;
499     unsigned char *finsecret = NULL;
500     const char *log_label = NULL;
501     int finsecretlen = 0;
502     const unsigned char *label;
503     size_t labellen, hashlen = 0;
504     int ret = 0;
505     const EVP_MD *md = NULL, *mac_md = NULL;
506     const EVP_CIPHER *cipher = NULL;
507     int mac_pkey_type = NID_undef;
508     SSL_CTX *sctx = SSL_CONNECTION_GET_CTX(s);
509     size_t keylen, ivlen = EVP_MAX_IV_LENGTH, taglen;
510     int level;
511     int direction = (which & SSL3_CC_READ) != 0 ? OSSL_RECORD_DIRECTION_READ
512                                                 : OSSL_RECORD_DIRECTION_WRITE;
513 
514     if (((which & SSL3_CC_CLIENT) && (which & SSL3_CC_WRITE))
515             || ((which & SSL3_CC_SERVER) && (which & SSL3_CC_READ))) {
516         if ((which & SSL3_CC_EARLY) != 0) {
517             EVP_MD_CTX *mdctx = NULL;
518             long handlen;
519             void *hdata;
520             unsigned int hashlenui;
521             const SSL_CIPHER *sslcipher = SSL_SESSION_get0_cipher(s->session);
522 
523             insecret = s->early_secret;
524             label = client_early_traffic;
525             labellen = sizeof(client_early_traffic) - 1;
526             log_label = CLIENT_EARLY_LABEL;
527 
528             handlen = BIO_get_mem_data(s->s3.handshake_buffer, &hdata);
529             if (handlen <= 0) {
530                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_HANDSHAKE_LENGTH);
531                 goto err;
532             }
533 
534             if (s->early_data_state == SSL_EARLY_DATA_CONNECTING
535                     && s->max_early_data > 0
536                     && s->session->ext.max_early_data == 0) {
537                 /*
538                  * If we are attempting to send early data, and we've decided to
539                  * actually do it but max_early_data in s->session is 0 then we
540                  * must be using an external PSK.
541                  */
542                 if (!ossl_assert(s->psksession != NULL
543                         && s->max_early_data ==
544                            s->psksession->ext.max_early_data)) {
545                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
546                     goto err;
547                 }
548                 sslcipher = SSL_SESSION_get0_cipher(s->psksession);
549             }
550             if (sslcipher == NULL) {
551                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_PSK);
552                 goto err;
553             }
554 
555             /*
556              * This ups the ref count on cipher so we better make sure we free
557              * it again
558              */
559             if (!ssl_cipher_get_evp_cipher(sctx, sslcipher, &cipher)) {
560                 /* Error is already recorded */
561                 SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
562                 goto err;
563             }
564 
565             if (((EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0)
566                 && (!ssl_cipher_get_evp_md_mac(sctx, sslcipher, &mac_md,
567                                                &mac_pkey_type, NULL))) {
568                 SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
569                 goto err;
570             }
571 
572             /*
573              * We need to calculate the handshake digest using the digest from
574              * the session. We haven't yet selected our ciphersuite so we can't
575              * use ssl_handshake_md().
576              */
577             mdctx = EVP_MD_CTX_new();
578             if (mdctx == NULL) {
579                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
580                 goto err;
581             }
582 
583             md = ssl_md(sctx, sslcipher->algorithm2);
584             if (md == NULL || !EVP_DigestInit_ex(mdctx, md, NULL)
585                     || !EVP_DigestUpdate(mdctx, hdata, handlen)
586                     || !EVP_DigestFinal_ex(mdctx, hashval, &hashlenui)) {
587                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
588                 EVP_MD_CTX_free(mdctx);
589                 goto err;
590             }
591             hashlen = hashlenui;
592             EVP_MD_CTX_free(mdctx);
593 
594             if (!tls13_hkdf_expand(s, md, insecret,
595                                    early_exporter_master_secret,
596                                    sizeof(early_exporter_master_secret) - 1,
597                                    hashval, hashlen,
598                                    s->early_exporter_master_secret, hashlen,
599                                    1)) {
600                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
601                 goto err;
602             }
603 
604             if (!ssl_log_secret(s, EARLY_EXPORTER_SECRET_LABEL,
605                                 s->early_exporter_master_secret, hashlen)) {
606                 /* SSLfatal() already called */
607                 goto err;
608             }
609         } else if (which & SSL3_CC_HANDSHAKE) {
610             insecret = s->handshake_secret;
611             finsecret = s->client_finished_secret;
612             finsecretlen = EVP_MD_get_size(ssl_handshake_md(s));
613             if (finsecretlen <= 0) {
614                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
615                 goto err;
616             }
617             label = client_handshake_traffic;
618             labellen = sizeof(client_handshake_traffic) - 1;
619             log_label = CLIENT_HANDSHAKE_LABEL;
620             /*
621              * The handshake hash used for the server read/client write handshake
622              * traffic secret is the same as the hash for the server
623              * write/client read handshake traffic secret. However, if we
624              * processed early data then we delay changing the server
625              * read/client write cipher state until later, and the handshake
626              * hashes have moved on. Therefore we use the value saved earlier
627              * when we did the server write/client read change cipher state.
628              */
629             hash = s->handshake_traffic_hash;
630         } else {
631             insecret = s->master_secret;
632             label = client_application_traffic;
633             labellen = sizeof(client_application_traffic) - 1;
634             log_label = CLIENT_APPLICATION_LABEL;
635             /*
636              * For this we only use the handshake hashes up until the server
637              * Finished hash. We do not include the client's Finished, which is
638              * what ssl_handshake_hash() would give us. Instead we use the
639              * previously saved value.
640              */
641             hash = s->server_finished_hash;
642         }
643     } else {
644         /* Early data never applies to client-read/server-write */
645         if (which & SSL3_CC_HANDSHAKE) {
646             insecret = s->handshake_secret;
647             finsecret = s->server_finished_secret;
648             finsecretlen = EVP_MD_get_size(ssl_handshake_md(s));
649             if (finsecretlen <= 0) {
650                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
651                 goto err;
652             }
653             label = server_handshake_traffic;
654             labellen = sizeof(server_handshake_traffic) - 1;
655             log_label = SERVER_HANDSHAKE_LABEL;
656         } else {
657             insecret = s->master_secret;
658             label = server_application_traffic;
659             labellen = sizeof(server_application_traffic) - 1;
660             log_label = SERVER_APPLICATION_LABEL;
661             hash = s->server_finished_hash;
662         }
663     }
664 
665     if ((which & SSL3_CC_EARLY) == 0) {
666         md = ssl_handshake_md(s);
667         cipher = s->s3.tmp.new_sym_enc;
668         mac_md = s->s3.tmp.new_hash;
669         mac_pkey_type = s->s3.tmp.new_mac_pkey_type;
670         if (!ssl3_digest_cached_records(s, 1)
671                 || !ssl_handshake_hash(s, hashval, sizeof(hashval), &hashlen)) {
672             /* SSLfatal() already called */;
673             goto err;
674         }
675     }
676 
677     if (label == client_application_traffic) {
678         /*
679          * We also create the resumption master secret, but this time use the
680          * hash for the whole handshake including the Client Finished
681          */
682         if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret,
683                                resumption_master_secret,
684                                sizeof(resumption_master_secret) - 1,
685                                hashval, hashlen, s->resumption_master_secret,
686                                hashlen, 1)) {
687             /* SSLfatal() already called */
688             goto err;
689         }
690     }
691 
692     /* check whether cipher is known */
693     if (!ossl_assert(cipher != NULL))
694         goto err;
695 
696     if (!derive_secret_key_and_iv(s, md, cipher, mac_pkey_type, mac_md,
697                                   insecret, hash, label, labellen, secret, key,
698                                   &keylen, &iv, &ivlen, &taglen)) {
699         /* SSLfatal() already called */
700         goto err;
701     }
702 
703     if (label == server_application_traffic) {
704         memcpy(s->server_app_traffic_secret, secret, hashlen);
705         /* Now we create the exporter master secret */
706         if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret,
707                                exporter_master_secret,
708                                sizeof(exporter_master_secret) - 1,
709                                hash, hashlen, s->exporter_master_secret,
710                                hashlen, 1)) {
711             /* SSLfatal() already called */
712             goto err;
713         }
714 
715         if (!ssl_log_secret(s, EXPORTER_SECRET_LABEL, s->exporter_master_secret,
716                             hashlen)) {
717             /* SSLfatal() already called */
718             goto err;
719         }
720     } else if (label == client_application_traffic)
721         memcpy(s->client_app_traffic_secret, secret, hashlen);
722 
723     if (!ssl_log_secret(s, log_label, secret, hashlen)) {
724         /* SSLfatal() already called */
725         goto err;
726     }
727 
728     if (finsecret != NULL
729             && !tls13_derive_finishedkey(s, ssl_handshake_md(s), secret,
730                                          finsecret, (size_t)finsecretlen)) {
731         /* SSLfatal() already called */
732         goto err;
733     }
734 
735     if ((which & SSL3_CC_WRITE) != 0) {
736         if (!s->server && label == client_early_traffic)
737             s->rlayer.wrlmethod->set_plain_alerts(s->rlayer.wrl, 1);
738         else
739             s->rlayer.wrlmethod->set_plain_alerts(s->rlayer.wrl, 0);
740     }
741 
742     level = (which & SSL3_CC_EARLY) != 0
743             ? OSSL_RECORD_PROTECTION_LEVEL_EARLY
744             : ((which &SSL3_CC_HANDSHAKE) != 0
745                ? OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE
746                : OSSL_RECORD_PROTECTION_LEVEL_APPLICATION);
747 
748     if (!ssl_set_new_record_layer(s, s->version,
749                                   direction,
750                                   level, secret, hashlen, key, keylen, iv,
751                                   ivlen, NULL, 0, cipher, taglen,
752                                   mac_pkey_type, mac_md, NULL, md)) {
753         /* SSLfatal already called */
754         goto err;
755     }
756 
757     ret = 1;
758  err:
759     if ((which & SSL3_CC_EARLY) != 0) {
760         /* We up-refed this so now we need to down ref */
761         if ((EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0)
762             ssl_evp_md_free(mac_md);
763         ssl_evp_cipher_free(cipher);
764     }
765     OPENSSL_cleanse(key, sizeof(key));
766     OPENSSL_cleanse(secret, sizeof(secret));
767     if (iv != iv_intern)
768         OPENSSL_free(iv);
769     return ret;
770 }
771 
tls13_update_key(SSL_CONNECTION * s,int sending)772 int tls13_update_key(SSL_CONNECTION *s, int sending)
773 {
774     /* ASCII: "traffic upd", in hex for EBCDIC compatibility */
775     static const unsigned char application_traffic[] = "\x74\x72\x61\x66\x66\x69\x63\x20\x75\x70\x64";
776     const EVP_MD *md = ssl_handshake_md(s);
777     size_t hashlen;
778     unsigned char key[EVP_MAX_KEY_LENGTH];
779     unsigned char *insecret;
780     unsigned char secret[EVP_MAX_MD_SIZE];
781     char *log_label;
782     size_t keylen, ivlen, taglen;
783     int ret = 0, l;
784     int direction = sending ? OSSL_RECORD_DIRECTION_WRITE
785                             : OSSL_RECORD_DIRECTION_READ;
786     unsigned char iv_intern[EVP_MAX_IV_LENGTH];
787     unsigned char *iv = iv_intern;
788 
789     if ((l = EVP_MD_get_size(md)) <= 0) {
790         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
791         return 0;
792     }
793     hashlen = (size_t)l;
794 
795     if (s->server == sending)
796         insecret = s->server_app_traffic_secret;
797     else
798         insecret = s->client_app_traffic_secret;
799 
800     if (!derive_secret_key_and_iv(s, md,
801                                   s->s3.tmp.new_sym_enc,
802                                   s->s3.tmp.new_mac_pkey_type, s->s3.tmp.new_hash,
803                                   insecret, NULL,
804                                   application_traffic,
805                                   sizeof(application_traffic) - 1, secret, key,
806                                   &keylen, &iv, &ivlen, &taglen)) {
807         /* SSLfatal() already called */
808         goto err;
809     }
810 
811     memcpy(insecret, secret, hashlen);
812 
813     if (!ssl_set_new_record_layer(s, s->version,
814                             direction,
815                             OSSL_RECORD_PROTECTION_LEVEL_APPLICATION,
816                             insecret, hashlen, key, keylen, iv, ivlen, NULL, 0,
817                             s->s3.tmp.new_sym_enc, taglen, NID_undef, NULL,
818                             NULL, md)) {
819         /* SSLfatal already called */
820         goto err;
821     }
822 
823     /* Call Key log on successful traffic secret update */
824     log_label = s->server == sending ? SERVER_APPLICATION_N_LABEL : CLIENT_APPLICATION_N_LABEL;
825     if (!ssl_log_secret(s, log_label, secret, hashlen)) {
826         /* SSLfatal() already called */
827         goto err;
828     }
829     ret = 1;
830  err:
831     OPENSSL_cleanse(key, sizeof(key));
832     OPENSSL_cleanse(secret, sizeof(secret));
833     if (iv != iv_intern)
834         OPENSSL_free(iv);
835     return ret;
836 }
837 
tls13_alert_code(int code)838 int tls13_alert_code(int code)
839 {
840     /* There are 2 additional alerts in TLSv1.3 compared to TLSv1.2 */
841     if (code == SSL_AD_MISSING_EXTENSION || code == SSL_AD_CERTIFICATE_REQUIRED)
842         return code;
843 
844     return tls1_alert_code(code);
845 }
846 
tls13_export_keying_material(SSL_CONNECTION * s,unsigned char * out,size_t olen,const char * label,size_t llen,const unsigned char * context,size_t contextlen,int use_context)847 int tls13_export_keying_material(SSL_CONNECTION *s,
848                                  unsigned char *out, size_t olen,
849                                  const char *label, size_t llen,
850                                  const unsigned char *context,
851                                  size_t contextlen, int use_context)
852 {
853     unsigned char exportsecret[EVP_MAX_MD_SIZE];
854     /* ASCII: "exporter", in hex for EBCDIC compatibility */
855     static const unsigned char exporterlabel[] = "\x65\x78\x70\x6F\x72\x74\x65\x72";
856     unsigned char hash[EVP_MAX_MD_SIZE], data[EVP_MAX_MD_SIZE];
857     const EVP_MD *md = ssl_handshake_md(s);
858     EVP_MD_CTX *ctx = EVP_MD_CTX_new();
859     unsigned int hashsize, datalen;
860     int ret = 0;
861 
862     if (ctx == NULL || md == NULL || !ossl_statem_export_allowed(s))
863         goto err;
864 
865     if (!use_context)
866         contextlen = 0;
867 
868     if (EVP_DigestInit_ex(ctx, md, NULL) <= 0
869             || EVP_DigestUpdate(ctx, context, contextlen) <= 0
870             || EVP_DigestFinal_ex(ctx, hash, &hashsize) <= 0
871             || EVP_DigestInit_ex(ctx, md, NULL) <= 0
872             || EVP_DigestFinal_ex(ctx, data, &datalen) <= 0
873             || !tls13_hkdf_expand(s, md, s->exporter_master_secret,
874                                   (const unsigned char *)label, llen,
875                                   data, datalen, exportsecret, hashsize, 0)
876             || !tls13_hkdf_expand(s, md, exportsecret, exporterlabel,
877                                   sizeof(exporterlabel) - 1, hash, hashsize,
878                                   out, olen, 0))
879         goto err;
880 
881     ret = 1;
882  err:
883     EVP_MD_CTX_free(ctx);
884     return ret;
885 }
886 
tls13_export_keying_material_early(SSL_CONNECTION * s,unsigned char * out,size_t olen,const char * label,size_t llen,const unsigned char * context,size_t contextlen)887 int tls13_export_keying_material_early(SSL_CONNECTION *s,
888                                        unsigned char *out, size_t olen,
889                                        const char *label, size_t llen,
890                                        const unsigned char *context,
891                                        size_t contextlen)
892 {
893     /* ASCII: "exporter", in hex for EBCDIC compatibility */
894     static const unsigned char exporterlabel[] = "\x65\x78\x70\x6F\x72\x74\x65\x72";
895     unsigned char exportsecret[EVP_MAX_MD_SIZE];
896     unsigned char hash[EVP_MAX_MD_SIZE], data[EVP_MAX_MD_SIZE];
897     const EVP_MD *md;
898     EVP_MD_CTX *ctx = EVP_MD_CTX_new();
899     unsigned int hashsize, datalen;
900     int ret = 0;
901     const SSL_CIPHER *sslcipher;
902 
903     if (ctx == NULL || !ossl_statem_export_early_allowed(s))
904         goto err;
905 
906     if (!s->server && s->max_early_data > 0
907             && s->session->ext.max_early_data == 0)
908         sslcipher = SSL_SESSION_get0_cipher(s->psksession);
909     else
910         sslcipher = SSL_SESSION_get0_cipher(s->session);
911 
912     md = ssl_md(SSL_CONNECTION_GET_CTX(s), sslcipher->algorithm2);
913 
914     /*
915      * Calculate the hash value and store it in |data|. The reason why
916      * the empty string is used is that the definition of TLS-Exporter
917      * is like so:
918      *
919      * TLS-Exporter(label, context_value, key_length) =
920      *     HKDF-Expand-Label(Derive-Secret(Secret, label, ""),
921      *                       "exporter", Hash(context_value), key_length)
922      *
923      * Derive-Secret(Secret, Label, Messages) =
924      *       HKDF-Expand-Label(Secret, Label,
925      *                         Transcript-Hash(Messages), Hash.length)
926      *
927      * Here Transcript-Hash is the cipher suite hash algorithm.
928      */
929     if (md == NULL
930             || EVP_DigestInit_ex(ctx, md, NULL) <= 0
931             || EVP_DigestUpdate(ctx, context, contextlen) <= 0
932             || EVP_DigestFinal_ex(ctx, hash, &hashsize) <= 0
933             || EVP_DigestInit_ex(ctx, md, NULL) <= 0
934             || EVP_DigestFinal_ex(ctx, data, &datalen) <= 0
935             || !tls13_hkdf_expand(s, md, s->early_exporter_master_secret,
936                                   (const unsigned char *)label, llen,
937                                   data, datalen, exportsecret, hashsize, 0)
938             || !tls13_hkdf_expand(s, md, exportsecret, exporterlabel,
939                                   sizeof(exporterlabel) - 1, hash, hashsize,
940                                   out, olen, 0))
941         goto err;
942 
943     ret = 1;
944  err:
945     EVP_MD_CTX_free(ctx);
946     return ret;
947 }
948