0d29dae0428c70d047475565ec7e96f6755f201b
[openssl.git] / ssl / tls13_enc.c
1 /*
2  * Copyright 2016 The OpenSSL Project Authors. All Rights Reserved.
3  *
4  * Licensed under the OpenSSL license (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_locl.h"
12 #include <openssl/evp.h>
13 #include <openssl/kdf.h>
14
15 #define TLS13_MAX_LABEL_LEN     246
16
17 /* Always filled with zeros */
18 static const unsigned char default_zeros[EVP_MAX_MD_SIZE];
19
20 /*
21  * Given a |secret|; a |label| of length |labellen|; and a |hash| of the
22  * handshake messages, derive a new secret |outlen| bytes long and store it in
23  * the location pointed to be |out|. The |hash| value may be NULL. Returns 1 on
24  * success  0 on failure.
25  */
26 int tls13_hkdf_expand(SSL *s, const EVP_MD *md, const unsigned char *secret,
27                              const unsigned char *label, size_t labellen,
28                              const unsigned char *hash,
29                              unsigned char *out, size_t outlen)
30 {
31     const unsigned char label_prefix[] = "TLS 1.3, ";
32     EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL);
33     int ret;
34     size_t hkdflabellen;
35     size_t hashlen;
36     /*
37      * 2 bytes for length of whole HkdfLabel + 1 byte for length of combined
38      * prefix and label + bytes for the label itself + bytes for the hash
39      */
40     unsigned char hkdflabel[sizeof(uint16_t) + sizeof(uint8_t) +
41                             + sizeof(label_prefix) + TLS13_MAX_LABEL_LEN
42                             + EVP_MAX_MD_SIZE];
43     WPACKET pkt;
44
45     if (pctx == NULL)
46         return 0;
47
48     hashlen = EVP_MD_size(md);
49
50     if (!WPACKET_init_static_len(&pkt, hkdflabel, sizeof(hkdflabel), 0)
51             || !WPACKET_put_bytes_u16(&pkt, outlen)
52             || !WPACKET_start_sub_packet_u8(&pkt)
53             || !WPACKET_memcpy(&pkt, label_prefix, sizeof(label_prefix) - 1)
54             || !WPACKET_memcpy(&pkt, label, labellen)
55             || !WPACKET_close(&pkt)
56             || !WPACKET_sub_memcpy_u8(&pkt, hash, (hash == NULL) ? 0 : hashlen)
57             || !WPACKET_get_total_written(&pkt, &hkdflabellen)
58             || !WPACKET_finish(&pkt)) {
59         WPACKET_cleanup(&pkt);
60         return 0;
61     }
62
63     ret = EVP_PKEY_derive_init(pctx) <= 0
64             || EVP_PKEY_CTX_hkdf_mode(pctx, EVP_PKEY_HKDEF_MODE_EXPAND_ONLY)
65                <= 0
66             || EVP_PKEY_CTX_set_hkdf_md(pctx, md) <= 0
67             || EVP_PKEY_CTX_set1_hkdf_key(pctx, secret, hashlen) <= 0
68             || EVP_PKEY_CTX_add1_hkdf_info(pctx, hkdflabel, hkdflabellen) <= 0
69             || EVP_PKEY_derive(pctx, out, &outlen) <= 0;
70
71     EVP_PKEY_CTX_free(pctx);
72
73     return ret == 0;
74 }
75
76 /*
77  * Given a |secret| generate a |key| of length |keylen| bytes. Returns 1 on
78  * success  0 on failure.
79  */
80 int tls13_derive_key(SSL *s, const unsigned char *secret, unsigned char *key,
81                      size_t keylen)
82 {
83     static const unsigned char keylabel[] = "key";
84
85     return tls13_hkdf_expand(s, ssl_handshake_md(s), secret, keylabel,
86                              sizeof(keylabel) - 1, NULL, key, keylen);
87 }
88
89 /*
90  * Given a |secret| generate an |iv| of length |ivlen| bytes. Returns 1 on
91  * success  0 on failure.
92  */
93 int tls13_derive_iv(SSL *s, const unsigned char *secret, unsigned char *iv,
94                     size_t ivlen)
95 {
96     static const unsigned char ivlabel[] = "iv";
97
98     return tls13_hkdf_expand(s, ssl_handshake_md(s), secret, ivlabel,
99                              sizeof(ivlabel) - 1, NULL, iv, ivlen);
100 }
101
102 int tls13_derive_finishedkey(SSL *s, const EVP_MD *md,
103                              const unsigned char *secret,
104                              unsigned char *fin, size_t finlen)
105 {
106     static const unsigned char finishedlabel[] = "finished";
107
108     return tls13_hkdf_expand(s, md, secret, finishedlabel,
109                              sizeof(finishedlabel) - 1, NULL, fin, finlen);
110 }
111
112 /*
113  * Given the previous secret |prevsecret| and a new input secret |insecret| of
114  * length |insecretlen|, generate a new secret and store it in the location
115  * pointed to by |outsecret|. Returns 1 on success  0 on failure.
116  */
117 int tls13_generate_secret(SSL *s, const EVP_MD *md,
118                           const unsigned char *prevsecret,
119                           const unsigned char *insecret,
120                           size_t insecretlen,
121                           unsigned char *outsecret)
122 {
123     size_t mdlen, prevsecretlen;
124     int ret;
125     EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL);
126
127     if (pctx == NULL)
128         return 0;
129
130     mdlen = EVP_MD_size(md);
131
132     if (insecret == NULL) {
133         insecret = default_zeros;
134         insecretlen = mdlen;
135     }
136     if (prevsecret == NULL) {
137         prevsecret = default_zeros;
138         prevsecretlen = 0;
139     } else {
140         prevsecretlen = mdlen;
141     }
142
143     ret = EVP_PKEY_derive_init(pctx) <= 0
144             || EVP_PKEY_CTX_hkdf_mode(pctx, EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY)
145                <= 0
146             || EVP_PKEY_CTX_set_hkdf_md(pctx, md) <= 0
147             || EVP_PKEY_CTX_set1_hkdf_key(pctx, insecret, insecretlen) <= 0
148             || EVP_PKEY_CTX_set1_hkdf_salt(pctx, prevsecret, prevsecretlen)
149                <= 0
150             || EVP_PKEY_derive(pctx, outsecret, &mdlen)
151                <= 0;
152
153     EVP_PKEY_CTX_free(pctx);
154     return ret == 0;
155 }
156
157 /*
158  * Given an input secret |insecret| of length |insecretlen| generate the
159  * handshake secret. This requires the early secret to already have been
160  * generated. Returns 1 on success  0 on failure.
161  */
162 int tls13_generate_handshake_secret(SSL *s, const unsigned char *insecret,
163                                 size_t insecretlen)
164 {
165     return tls13_generate_secret(s, ssl_handshake_md(s), s->early_secret,
166                                  insecret, insecretlen,
167                                  (unsigned char *)&s->handshake_secret);
168 }
169
170 /*
171  * Given the handshake secret |prev| of length |prevlen| generate the master
172  * secret and store its length in |*secret_size|. Returns 1 on success  0 on
173  * failure.
174  */
175 int tls13_generate_master_secret(SSL *s, unsigned char *out,
176                                  unsigned char *prev, size_t prevlen,
177                                  size_t *secret_size)
178 {
179     const EVP_MD *md = ssl_handshake_md(s);
180
181     *secret_size = EVP_MD_size(md);
182     return tls13_generate_secret(s, md, prev, NULL, 0, out);
183 }
184
185 /*
186  * Generates the mac for the Finished message. Returns the length of the MAC or
187  * 0 on error.
188  */
189 size_t tls13_final_finish_mac(SSL *s, const char *str, size_t slen,
190                              unsigned char *out)
191 {
192     const EVP_MD *md = ssl_handshake_md(s);
193     unsigned char hash[EVP_MAX_MD_SIZE];
194     size_t hashlen, ret = 0;
195     EVP_PKEY *key = NULL;
196     EVP_MD_CTX *ctx = EVP_MD_CTX_new();
197
198     if (!ssl_handshake_hash(s, hash, sizeof(hash), &hashlen))
199         goto err;
200
201     if (str == s->method->ssl3_enc->server_finished_label)
202         key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL,
203                                    s->server_finished_secret, hashlen);
204     else
205         key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL,
206                                    s->client_finished_secret, hashlen);
207
208     if (key == NULL
209             || ctx == NULL
210             || EVP_DigestSignInit(ctx, NULL, md, NULL, key) <= 0
211             || EVP_DigestSignUpdate(ctx, hash, hashlen) <= 0
212             || EVP_DigestSignFinal(ctx, out, &hashlen) <= 0)
213         goto err;
214
215     ret = hashlen;
216  err:
217     EVP_PKEY_free(key);
218     EVP_MD_CTX_free(ctx);
219     return ret;
220 }
221
222 /*
223  * There isn't really a key block in TLSv1.3, but we still need this function
224  * for initialising the cipher and hash. Returns 1 on success or 0 on failure.
225  */
226 int tls13_setup_key_block(SSL *s)
227 {
228     const EVP_CIPHER *c;
229     const EVP_MD *hash;
230     int mac_type = NID_undef;
231
232     s->session->cipher = s->s3->tmp.new_cipher;
233     if (!ssl_cipher_get_evp
234         (s->session, &c, &hash, &mac_type, NULL, NULL, 0)) {
235         SSLerr(SSL_F_TLS13_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
236         return 0;
237     }
238
239     s->s3->tmp.new_sym_enc = c;
240     s->s3->tmp.new_hash = hash;
241
242     return 1;
243 }
244
245 int tls13_change_cipher_state(SSL *s, int which)
246 {
247     static const unsigned char client_handshake_traffic[] =
248         "client handshake traffic secret";
249     static const unsigned char client_application_traffic[] =
250         "client application traffic secret";
251     static const unsigned char server_handshake_traffic[] =
252         "server handshake traffic secret";
253     static const unsigned char server_application_traffic[] =
254         "server application traffic secret";
255     static const unsigned char resumption_master_secret[] =
256         "resumption master secret";
257     unsigned char key[EVP_MAX_KEY_LENGTH];
258     unsigned char *iv;
259     unsigned char secret[EVP_MAX_MD_SIZE];
260     unsigned char hashval[EVP_MAX_MD_SIZE];
261     unsigned char *hash = hashval;
262     unsigned char *insecret;
263     unsigned char *finsecret = NULL;
264     const char *log_label = NULL;
265     EVP_CIPHER_CTX *ciph_ctx;
266     const EVP_CIPHER *ciph = s->s3->tmp.new_sym_enc;
267     size_t ivlen, keylen, finsecretlen = 0;
268     const unsigned char *label;
269     size_t labellen, hashlen = 0;
270     int ret = 0;
271
272     if (which & SSL3_CC_READ) {
273         if (s->enc_read_ctx != NULL) {
274             EVP_CIPHER_CTX_reset(s->enc_read_ctx);
275         } else {
276             s->enc_read_ctx = EVP_CIPHER_CTX_new();
277             if (s->enc_read_ctx == NULL) {
278                 SSLerr(SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
279                 goto err;
280             }
281         }
282         ciph_ctx = s->enc_read_ctx;
283         iv = s->read_iv;
284
285         RECORD_LAYER_reset_read_sequence(&s->rlayer);
286     } else {
287         if (s->enc_write_ctx != NULL) {
288             EVP_CIPHER_CTX_reset(s->enc_write_ctx);
289         } else {
290             s->enc_write_ctx = EVP_CIPHER_CTX_new();
291             if (s->enc_write_ctx == NULL) {
292                 SSLerr(SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
293                 goto err;
294             }
295         }
296         ciph_ctx = s->enc_write_ctx;
297         iv = s->write_iv;
298
299         RECORD_LAYER_reset_write_sequence(&s->rlayer);
300     }
301
302     if (((which & SSL3_CC_CLIENT) && (which & SSL3_CC_WRITE))
303             || ((which & SSL3_CC_SERVER) && (which & SSL3_CC_READ))) {
304         if (which & SSL3_CC_HANDSHAKE) {
305             insecret = s->handshake_secret;
306             finsecret = s->client_finished_secret;
307             finsecretlen = EVP_MD_size(ssl_handshake_md(s));
308             label = client_handshake_traffic;
309             labellen = sizeof(client_handshake_traffic) - 1;
310             log_label = CLIENT_HANDSHAKE_LABEL;
311         } else {
312             insecret = s->master_secret;
313             label = client_application_traffic;
314             labellen = sizeof(client_application_traffic) - 1;
315             log_label = CLIENT_APPLICATION_LABEL;
316             /*
317              * For this we only use the handshake hashes up until the server
318              * Finished hash. We do not include the client's Finished, which is
319              * what ssl_handshake_hash() would give us. Instead we use the
320              * previously saved value.
321              */
322             hash = s->server_finished_hash;
323         }
324     } else {
325         if (which & SSL3_CC_HANDSHAKE) {
326             insecret = s->handshake_secret;
327             finsecret = s->server_finished_secret;
328             finsecretlen = EVP_MD_size(ssl_handshake_md(s));
329             label = server_handshake_traffic;
330             labellen = sizeof(server_handshake_traffic) - 1;
331             log_label = SERVER_HANDSHAKE_LABEL;
332         } else {
333             insecret = s->master_secret;
334             label = server_application_traffic;
335             labellen = sizeof(server_application_traffic) - 1;
336             log_label = SERVER_APPLICATION_LABEL;
337         }
338     }
339
340     if (!ssl3_digest_cached_records(s, 1)
341             || !ssl_handshake_hash(s, hashval, sizeof(hashval), &hashlen)) {
342         SSLerr(SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
343         goto err;
344     }
345
346     /*
347      * Save the hash of handshakes up to now for use when we calculate the
348      * client application traffic secret
349      */
350     if (label == server_application_traffic)
351         memcpy(s->server_finished_hash, hashval, hashlen);
352
353     if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret, label, labellen,
354                            hash, secret, hashlen)) {
355         SSLerr(SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
356         goto err;
357     }
358
359     if (label == client_application_traffic) {
360         /*
361          * We also create the resumption master secret, but this time use the
362          * hash for the whole handshake including the Client Finished
363          */
364         if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret,
365                                resumption_master_secret,
366                                sizeof(resumption_master_secret) - 1,
367                                hashval, s->session->master_key, hashlen)) {
368             SSLerr(SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
369             goto err;
370         }
371         s->session->master_key_length = hashlen;
372     }
373
374     /* TODO(size_t): convert me */
375     keylen = EVP_CIPHER_key_length(ciph);
376     ivlen = EVP_CIPHER_iv_length(ciph);
377
378     if (!ssl_log_secret(s, log_label, secret, hashlen)) {
379         SSLerr(SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
380         goto err;
381     }
382
383     if (!tls13_derive_key(s, secret, key, keylen)
384             || !tls13_derive_iv(s, secret, iv, ivlen)
385             || (finsecret != NULL && !tls13_derive_finishedkey(s,
386                                                            ssl_handshake_md(s),
387                                                            secret,
388                                                            finsecret,
389                                                            finsecretlen))) {
390         SSLerr(SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
391         goto err;
392     }
393
394     if (EVP_CipherInit_ex(ciph_ctx, ciph, NULL, key, NULL,
395                           (which & SSL3_CC_WRITE)) <= 0) {
396         SSLerr(SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_EVP_LIB);
397         goto err;
398     }
399
400 #ifdef OPENSSL_SSL_TRACE_CRYPTO
401     if (s->msg_callback) {
402         int wh = which & SSL3_CC_WRITE ? TLS1_RT_CRYPTO_WRITE : 0;
403
404         if (ciph->key_len)
405             s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_KEY,
406                             key, ciph->key_len, s, s->msg_callback_arg);
407
408         wh |= TLS1_RT_CRYPTO_IV;
409         s->msg_callback(2, s->version, wh, iv, ivlen, s,
410                         s->msg_callback_arg);
411     }
412 #endif
413
414     ret = 1;
415  err:
416     OPENSSL_cleanse(secret, sizeof(secret));
417     OPENSSL_cleanse(key, sizeof(key));
418     return ret;
419 }
420
421 int tls13_alert_code(int code)
422 {
423     if (code == SSL_AD_MISSING_EXTENSION)
424         return code;
425
426     return tls1_alert_code(code);
427 }