xref: /src/crypto/openssl/ssl/tls13_enc.c (revision f25b8c9fb4f58cf61adb47d7570abe7caa6d385d)
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 == s->psksession->ext.max_early_data)) {
544                     SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
545                     goto err;
546                 }
547                 sslcipher = SSL_SESSION_get0_cipher(s->psksession);
548             }
549             if (sslcipher == NULL) {
550                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, SSL_R_BAD_PSK);
551                 goto err;
552             }
553 
554             /*
555              * This ups the ref count on cipher so we better make sure we free
556              * it again
557              */
558             if (!ssl_cipher_get_evp_cipher(sctx, sslcipher, &cipher)) {
559                 /* Error is already recorded */
560                 SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
561                 goto err;
562             }
563 
564             if (((EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0)
565                 && (!ssl_cipher_get_evp_md_mac(sctx, sslcipher, &mac_md,
566                     &mac_pkey_type, NULL))) {
567                 SSLfatal_alert(s, SSL_AD_INTERNAL_ERROR);
568                 goto err;
569             }
570 
571             /*
572              * We need to calculate the handshake digest using the digest from
573              * the session. We haven't yet selected our ciphersuite so we can't
574              * use ssl_handshake_md().
575              */
576             mdctx = EVP_MD_CTX_new();
577             if (mdctx == NULL) {
578                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_EVP_LIB);
579                 goto err;
580             }
581 
582             md = ssl_md(sctx, sslcipher->algorithm2);
583             if (md == NULL || !EVP_DigestInit_ex(mdctx, md, NULL)
584                 || !EVP_DigestUpdate(mdctx, hdata, handlen)
585                 || !EVP_DigestFinal_ex(mdctx, hashval, &hashlenui)) {
586                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
587                 EVP_MD_CTX_free(mdctx);
588                 goto err;
589             }
590             hashlen = hashlenui;
591             EVP_MD_CTX_free(mdctx);
592 
593             if (!tls13_hkdf_expand(s, md, insecret,
594                     early_exporter_master_secret,
595                     sizeof(early_exporter_master_secret) - 1,
596                     hashval, hashlen,
597                     s->early_exporter_master_secret, hashlen,
598                     1)) {
599                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
600                 goto err;
601             }
602 
603             if (!ssl_log_secret(s, EARLY_EXPORTER_SECRET_LABEL,
604                     s->early_exporter_master_secret, hashlen)) {
605                 /* SSLfatal() already called */
606                 goto err;
607             }
608         } else if (which & SSL3_CC_HANDSHAKE) {
609             insecret = s->handshake_secret;
610             finsecret = s->client_finished_secret;
611             finsecretlen = EVP_MD_get_size(ssl_handshake_md(s));
612             if (finsecretlen <= 0) {
613                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
614                 goto err;
615             }
616             label = client_handshake_traffic;
617             labellen = sizeof(client_handshake_traffic) - 1;
618             log_label = CLIENT_HANDSHAKE_LABEL;
619             /*
620              * The handshake hash used for the server read/client write handshake
621              * traffic secret is the same as the hash for the server
622              * write/client read handshake traffic secret. However, if we
623              * processed early data then we delay changing the server
624              * read/client write cipher state until later, and the handshake
625              * hashes have moved on. Therefore we use the value saved earlier
626              * when we did the server write/client read change cipher state.
627              */
628             hash = s->handshake_traffic_hash;
629         } else {
630             insecret = s->master_secret;
631             label = client_application_traffic;
632             labellen = sizeof(client_application_traffic) - 1;
633             log_label = CLIENT_APPLICATION_LABEL;
634             /*
635              * For this we only use the handshake hashes up until the server
636              * Finished hash. We do not include the client's Finished, which is
637              * what ssl_handshake_hash() would give us. Instead we use the
638              * previously saved value.
639              */
640             hash = s->server_finished_hash;
641         }
642     } else {
643         /* Early data never applies to client-read/server-write */
644         if (which & SSL3_CC_HANDSHAKE) {
645             insecret = s->handshake_secret;
646             finsecret = s->server_finished_secret;
647             finsecretlen = EVP_MD_get_size(ssl_handshake_md(s));
648             if (finsecretlen <= 0) {
649                 SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
650                 goto err;
651             }
652             label = server_handshake_traffic;
653             labellen = sizeof(server_handshake_traffic) - 1;
654             log_label = SERVER_HANDSHAKE_LABEL;
655         } else {
656             insecret = s->master_secret;
657             label = server_application_traffic;
658             labellen = sizeof(server_application_traffic) - 1;
659             log_label = SERVER_APPLICATION_LABEL;
660             hash = s->server_finished_hash;
661         }
662     }
663 
664     if ((which & SSL3_CC_EARLY) == 0) {
665         md = ssl_handshake_md(s);
666         cipher = s->s3.tmp.new_sym_enc;
667         mac_md = s->s3.tmp.new_hash;
668         mac_pkey_type = s->s3.tmp.new_mac_pkey_type;
669         if (!ssl3_digest_cached_records(s, 1)
670             || !ssl_handshake_hash(s, hashval, sizeof(hashval), &hashlen)) {
671             /* SSLfatal() already called */;
672             goto err;
673         }
674     }
675 
676     if (label == client_application_traffic) {
677         /*
678          * We also create the resumption master secret, but this time use the
679          * hash for the whole handshake including the Client Finished
680          */
681         if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret,
682                 resumption_master_secret,
683                 sizeof(resumption_master_secret) - 1,
684                 hashval, hashlen, s->resumption_master_secret,
685                 hashlen, 1)) {
686             /* SSLfatal() already called */
687             goto err;
688         }
689     }
690 
691     /* check whether cipher is known */
692     if (!ossl_assert(cipher != NULL))
693         goto err;
694 
695     if (!derive_secret_key_and_iv(s, md, cipher, mac_pkey_type, mac_md,
696             insecret, hash, label, labellen, secret, key,
697             &keylen, &iv, &ivlen, &taglen)) {
698         /* SSLfatal() already called */
699         goto err;
700     }
701 
702     if (label == server_application_traffic) {
703         memcpy(s->server_app_traffic_secret, secret, hashlen);
704         /* Now we create the exporter master secret */
705         if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret,
706                 exporter_master_secret,
707                 sizeof(exporter_master_secret) - 1,
708                 hash, hashlen, s->exporter_master_secret,
709                 hashlen, 1)) {
710             /* SSLfatal() already called */
711             goto err;
712         }
713 
714         if (!ssl_log_secret(s, EXPORTER_SECRET_LABEL, s->exporter_master_secret,
715                 hashlen)) {
716             /* SSLfatal() already called */
717             goto err;
718         }
719     } else if (label == client_application_traffic)
720         memcpy(s->client_app_traffic_secret, secret, hashlen);
721 
722     if (!ssl_log_secret(s, log_label, secret, hashlen)) {
723         /* SSLfatal() already called */
724         goto err;
725     }
726 
727     if (finsecret != NULL
728         && !tls13_derive_finishedkey(s, ssl_handshake_md(s), secret,
729             finsecret, (size_t)finsecretlen)) {
730         /* SSLfatal() already called */
731         goto err;
732     }
733 
734     if ((which & SSL3_CC_WRITE) != 0) {
735         if (!s->server && label == client_early_traffic)
736             s->rlayer.wrlmethod->set_plain_alerts(s->rlayer.wrl, 1);
737         else
738             s->rlayer.wrlmethod->set_plain_alerts(s->rlayer.wrl, 0);
739     }
740 
741     level = (which & SSL3_CC_EARLY) != 0
742         ? OSSL_RECORD_PROTECTION_LEVEL_EARLY
743         : ((which & SSL3_CC_HANDSHAKE) != 0
744                   ? OSSL_RECORD_PROTECTION_LEVEL_HANDSHAKE
745                   : OSSL_RECORD_PROTECTION_LEVEL_APPLICATION);
746 
747     if (!ssl_set_new_record_layer(s, s->version,
748             direction,
749             level, secret, hashlen, key, keylen, iv,
750             ivlen, NULL, 0, cipher, taglen,
751             mac_pkey_type, mac_md, NULL, md)) {
752         /* SSLfatal already called */
753         goto err;
754     }
755 
756     ret = 1;
757 err:
758     if ((which & SSL3_CC_EARLY) != 0) {
759         /* We up-refed this so now we need to down ref */
760         if ((EVP_CIPHER_flags(cipher) & EVP_CIPH_FLAG_AEAD_CIPHER) == 0)
761             ssl_evp_md_free(mac_md);
762         ssl_evp_cipher_free(cipher);
763     }
764     OPENSSL_cleanse(key, sizeof(key));
765     OPENSSL_cleanse(secret, sizeof(secret));
766     if (iv != iv_intern)
767         OPENSSL_free(iv);
768     return ret;
769 }
770 
tls13_update_key(SSL_CONNECTION * s,int sending)771 int tls13_update_key(SSL_CONNECTION *s, int sending)
772 {
773     /* ASCII: "traffic upd", in hex for EBCDIC compatibility */
774     static const unsigned char application_traffic[] = "\x74\x72\x61\x66\x66\x69\x63\x20\x75\x70\x64";
775     const EVP_MD *md = ssl_handshake_md(s);
776     size_t hashlen;
777     unsigned char key[EVP_MAX_KEY_LENGTH];
778     unsigned char *insecret;
779     unsigned char secret[EVP_MAX_MD_SIZE];
780     char *log_label;
781     size_t keylen, ivlen, taglen;
782     int ret = 0, l;
783     int direction = sending ? OSSL_RECORD_DIRECTION_WRITE
784                             : OSSL_RECORD_DIRECTION_READ;
785     unsigned char iv_intern[EVP_MAX_IV_LENGTH];
786     unsigned char *iv = iv_intern;
787 
788     if ((l = EVP_MD_get_size(md)) <= 0) {
789         SSLfatal(s, SSL_AD_INTERNAL_ERROR, ERR_R_INTERNAL_ERROR);
790         return 0;
791     }
792     hashlen = (size_t)l;
793 
794     if (s->server == sending)
795         insecret = s->server_app_traffic_secret;
796     else
797         insecret = s->client_app_traffic_secret;
798 
799     if (!derive_secret_key_and_iv(s, md,
800             s->s3.tmp.new_sym_enc,
801             s->s3.tmp.new_mac_pkey_type, s->s3.tmp.new_hash,
802             insecret, NULL,
803             application_traffic,
804             sizeof(application_traffic) - 1, secret, key,
805             &keylen, &iv, &ivlen, &taglen)) {
806         /* SSLfatal() already called */
807         goto err;
808     }
809 
810     memcpy(insecret, secret, hashlen);
811 
812     if (!ssl_set_new_record_layer(s, s->version,
813             direction,
814             OSSL_RECORD_PROTECTION_LEVEL_APPLICATION,
815             insecret, hashlen, key, keylen, iv, ivlen, NULL, 0,
816             s->s3.tmp.new_sym_enc, taglen, NID_undef, NULL,
817             NULL, md)) {
818         /* SSLfatal already called */
819         goto err;
820     }
821 
822     /* Call Key log on successful traffic secret update */
823     log_label = s->server == sending ? SERVER_APPLICATION_N_LABEL : CLIENT_APPLICATION_N_LABEL;
824     if (!ssl_log_secret(s, log_label, secret, hashlen)) {
825         /* SSLfatal() already called */
826         goto err;
827     }
828     ret = 1;
829 err:
830     OPENSSL_cleanse(key, sizeof(key));
831     OPENSSL_cleanse(secret, sizeof(secret));
832     if (iv != iv_intern)
833         OPENSSL_free(iv);
834     return ret;
835 }
836 
tls13_alert_code(int code)837 int tls13_alert_code(int code)
838 {
839     /* There are 2 additional alerts in TLSv1.3 compared to TLSv1.2 */
840     if (code == SSL_AD_MISSING_EXTENSION || code == SSL_AD_CERTIFICATE_REQUIRED)
841         return code;
842 
843     return tls1_alert_code(code);
844 }
845 
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)846 int tls13_export_keying_material(SSL_CONNECTION *s,
847     unsigned char *out, size_t olen,
848     const char *label, size_t llen,
849     const unsigned char *context,
850     size_t contextlen, int use_context)
851 {
852     unsigned char exportsecret[EVP_MAX_MD_SIZE];
853     /* ASCII: "exporter", in hex for EBCDIC compatibility */
854     static const unsigned char exporterlabel[] = "\x65\x78\x70\x6F\x72\x74\x65\x72";
855     unsigned char hash[EVP_MAX_MD_SIZE], data[EVP_MAX_MD_SIZE];
856     const EVP_MD *md = ssl_handshake_md(s);
857     EVP_MD_CTX *ctx = EVP_MD_CTX_new();
858     unsigned int hashsize, datalen;
859     int ret = 0;
860 
861     if (ctx == NULL || md == NULL || !ossl_statem_export_allowed(s))
862         goto err;
863 
864     if (!use_context)
865         contextlen = 0;
866 
867     if (EVP_DigestInit_ex(ctx, md, NULL) <= 0
868         || EVP_DigestUpdate(ctx, context, contextlen) <= 0
869         || EVP_DigestFinal_ex(ctx, hash, &hashsize) <= 0
870         || EVP_DigestInit_ex(ctx, md, NULL) <= 0
871         || EVP_DigestFinal_ex(ctx, data, &datalen) <= 0
872         || !tls13_hkdf_expand(s, md, s->exporter_master_secret,
873             (const unsigned char *)label, llen,
874             data, datalen, exportsecret, hashsize, 0)
875         || !tls13_hkdf_expand(s, md, exportsecret, exporterlabel,
876             sizeof(exporterlabel) - 1, hash, hashsize,
877             out, olen, 0))
878         goto err;
879 
880     ret = 1;
881 err:
882     EVP_MD_CTX_free(ctx);
883     return ret;
884 }
885 
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)886 int tls13_export_keying_material_early(SSL_CONNECTION *s,
887     unsigned char *out, size_t olen,
888     const char *label, size_t llen,
889     const unsigned char *context,
890     size_t contextlen)
891 {
892     /* ASCII: "exporter", in hex for EBCDIC compatibility */
893     static const unsigned char exporterlabel[] = "\x65\x78\x70\x6F\x72\x74\x65\x72";
894     unsigned char exportsecret[EVP_MAX_MD_SIZE];
895     unsigned char hash[EVP_MAX_MD_SIZE], data[EVP_MAX_MD_SIZE];
896     const EVP_MD *md;
897     EVP_MD_CTX *ctx = EVP_MD_CTX_new();
898     unsigned int hashsize, datalen;
899     int ret = 0;
900     const SSL_CIPHER *sslcipher;
901 
902     if (ctx == NULL || !ossl_statem_export_early_allowed(s))
903         goto err;
904 
905     if (!s->server && s->max_early_data > 0
906         && s->session->ext.max_early_data == 0)
907         sslcipher = SSL_SESSION_get0_cipher(s->psksession);
908     else
909         sslcipher = SSL_SESSION_get0_cipher(s->session);
910 
911     md = ssl_md(SSL_CONNECTION_GET_CTX(s), sslcipher->algorithm2);
912 
913     /*
914      * Calculate the hash value and store it in |data|. The reason why
915      * the empty string is used is that the definition of TLS-Exporter
916      * is like so:
917      *
918      * TLS-Exporter(label, context_value, key_length) =
919      *     HKDF-Expand-Label(Derive-Secret(Secret, label, ""),
920      *                       "exporter", Hash(context_value), key_length)
921      *
922      * Derive-Secret(Secret, Label, Messages) =
923      *       HKDF-Expand-Label(Secret, Label,
924      *                         Transcript-Hash(Messages), Hash.length)
925      *
926      * Here Transcript-Hash is the cipher suite hash algorithm.
927      */
928     if (md == NULL
929         || EVP_DigestInit_ex(ctx, md, NULL) <= 0
930         || EVP_DigestUpdate(ctx, context, contextlen) <= 0
931         || EVP_DigestFinal_ex(ctx, hash, &hashsize) <= 0
932         || EVP_DigestInit_ex(ctx, md, NULL) <= 0
933         || EVP_DigestFinal_ex(ctx, data, &datalen) <= 0
934         || !tls13_hkdf_expand(s, md, s->early_exporter_master_secret,
935             (const unsigned char *)label, llen,
936             data, datalen, exportsecret, hashsize, 0)
937         || !tls13_hkdf_expand(s, md, exportsecret, exporterlabel,
938             sizeof(exporterlabel) - 1, hash, hashsize,
939             out, olen, 0))
940         goto err;
941 
942     ret = 1;
943 err:
944     EVP_MD_CTX_free(ctx);
945     return ret;
946 }
947