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