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