Fix changing of the cipher state when dealing with early data
[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         EVP_PKEY_CTX_free(pctx);
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 EVP_MD *md, const unsigned char *secret,
82                      unsigned char *key, size_t keylen)
83 {
84     static const unsigned char keylabel[] = "key";
85
86     return tls13_hkdf_expand(s, md, secret, keylabel, sizeof(keylabel) - 1,
87                              NULL, 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 EVP_MD *md, const unsigned char *secret,
95                     unsigned char *iv, size_t ivlen)
96 {
97     static const unsigned char ivlabel[] = "iv";
98
99     return tls13_hkdf_expand(s, md, secret, ivlabel, sizeof(ivlabel) - 1,
100                              NULL, iv, ivlen);
101 }
102
103 int tls13_derive_finishedkey(SSL *s, const EVP_MD *md,
104                              const unsigned char *secret,
105                              unsigned char *fin, size_t finlen)
106 {
107     static const unsigned char finishedlabel[] = "finished";
108
109     return tls13_hkdf_expand(s, md, secret, finishedlabel,
110                              sizeof(finishedlabel) - 1, NULL, fin, finlen);
111 }
112
113 /*
114  * Given the previous secret |prevsecret| and a new input secret |insecret| of
115  * length |insecretlen|, generate a new secret and store it in the location
116  * pointed to by |outsecret|. Returns 1 on success  0 on failure.
117  */
118 int tls13_generate_secret(SSL *s, const EVP_MD *md,
119                           const unsigned char *prevsecret,
120                           const unsigned char *insecret,
121                           size_t insecretlen,
122                           unsigned char *outsecret)
123 {
124     size_t mdlen, prevsecretlen;
125     int ret;
126     EVP_PKEY_CTX *pctx = EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, NULL);
127
128     if (pctx == NULL)
129         return 0;
130
131     mdlen = EVP_MD_size(md);
132
133     if (insecret == NULL) {
134         insecret = default_zeros;
135         insecretlen = mdlen;
136     }
137     if (prevsecret == NULL) {
138         prevsecret = default_zeros;
139         prevsecretlen = 0;
140     } else {
141         prevsecretlen = mdlen;
142     }
143
144     ret = EVP_PKEY_derive_init(pctx) <= 0
145             || EVP_PKEY_CTX_hkdf_mode(pctx, EVP_PKEY_HKDEF_MODE_EXTRACT_ONLY)
146                <= 0
147             || EVP_PKEY_CTX_set_hkdf_md(pctx, md) <= 0
148             || EVP_PKEY_CTX_set1_hkdf_key(pctx, insecret, insecretlen) <= 0
149             || EVP_PKEY_CTX_set1_hkdf_salt(pctx, prevsecret, prevsecretlen)
150                <= 0
151             || EVP_PKEY_derive(pctx, outsecret, &mdlen)
152                <= 0;
153
154     EVP_PKEY_CTX_free(pctx);
155     return ret == 0;
156 }
157
158 /*
159  * Given an input secret |insecret| of length |insecretlen| generate the
160  * handshake secret. This requires the early secret to already have been
161  * generated. Returns 1 on success  0 on failure.
162  */
163 int tls13_generate_handshake_secret(SSL *s, const unsigned char *insecret,
164                                 size_t insecretlen)
165 {
166     return tls13_generate_secret(s, ssl_handshake_md(s), s->early_secret,
167                                  insecret, insecretlen,
168                                  (unsigned char *)&s->handshake_secret);
169 }
170
171 /*
172  * Given the handshake secret |prev| of length |prevlen| generate the master
173  * secret and store its length in |*secret_size|. Returns 1 on success  0 on
174  * failure.
175  */
176 int tls13_generate_master_secret(SSL *s, unsigned char *out,
177                                  unsigned char *prev, size_t prevlen,
178                                  size_t *secret_size)
179 {
180     const EVP_MD *md = ssl_handshake_md(s);
181
182     *secret_size = EVP_MD_size(md);
183     return tls13_generate_secret(s, md, prev, NULL, 0, out);
184 }
185
186 /*
187  * Generates the mac for the Finished message. Returns the length of the MAC or
188  * 0 on error.
189  */
190 size_t tls13_final_finish_mac(SSL *s, const char *str, size_t slen,
191                              unsigned char *out)
192 {
193     const EVP_MD *md = ssl_handshake_md(s);
194     unsigned char hash[EVP_MAX_MD_SIZE];
195     size_t hashlen, ret = 0;
196     EVP_PKEY *key = NULL;
197     EVP_MD_CTX *ctx = EVP_MD_CTX_new();
198
199     if (!ssl_handshake_hash(s, hash, sizeof(hash), &hashlen))
200         goto err;
201
202     if (str == s->method->ssl3_enc->server_finished_label)
203         key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL,
204                                    s->server_finished_secret, hashlen);
205     else
206         key = EVP_PKEY_new_mac_key(EVP_PKEY_HMAC, NULL,
207                                    s->client_finished_secret, hashlen);
208
209     if (key == NULL
210             || ctx == NULL
211             || EVP_DigestSignInit(ctx, NULL, md, NULL, key) <= 0
212             || EVP_DigestSignUpdate(ctx, hash, hashlen) <= 0
213             || EVP_DigestSignFinal(ctx, out, &hashlen) <= 0)
214         goto err;
215
216     ret = hashlen;
217  err:
218     EVP_PKEY_free(key);
219     EVP_MD_CTX_free(ctx);
220     return ret;
221 }
222
223 /*
224  * There isn't really a key block in TLSv1.3, but we still need this function
225  * for initialising the cipher and hash. Returns 1 on success or 0 on failure.
226  */
227 int tls13_setup_key_block(SSL *s)
228 {
229     const EVP_CIPHER *c;
230     const EVP_MD *hash;
231     int mac_type = NID_undef;
232
233     s->session->cipher = s->s3->tmp.new_cipher;
234     if (!ssl_cipher_get_evp
235         (s->session, &c, &hash, &mac_type, NULL, NULL, 0)) {
236         SSLerr(SSL_F_TLS13_SETUP_KEY_BLOCK, SSL_R_CIPHER_OR_HASH_UNAVAILABLE);
237         return 0;
238     }
239
240     s->s3->tmp.new_sym_enc = c;
241     s->s3->tmp.new_hash = hash;
242
243     return 1;
244 }
245
246 static int derive_secret_key_and_iv(SSL *s, int send, const EVP_MD *md,
247                                     const EVP_CIPHER *ciph,
248                                     const unsigned char *insecret,
249                                     const unsigned char *hash,
250                                     const unsigned char *label,
251                                     size_t labellen, unsigned char *secret,
252                                     unsigned char *iv, EVP_CIPHER_CTX *ciph_ctx)
253 {
254     unsigned char key[EVP_MAX_KEY_LENGTH];
255     size_t ivlen, keylen, taglen;
256     size_t hashlen = EVP_MD_size(md);
257
258     if (!tls13_hkdf_expand(s, md, insecret, label, labellen, hash, secret,
259                            hashlen)) {
260         SSLerr(SSL_F_DERIVE_SECRET_KEY_AND_IV, ERR_R_INTERNAL_ERROR);
261         goto err;
262     }
263
264     /* TODO(size_t): convert me */
265     keylen = EVP_CIPHER_key_length(ciph);
266     if (EVP_CIPHER_mode(ciph) == EVP_CIPH_CCM_MODE) {
267         ivlen = EVP_CCM_TLS_IV_LEN;
268         if (s->s3->tmp.new_cipher->algorithm_enc
269                 & (SSL_AES128CCM8 | SSL_AES256CCM8))
270             taglen = EVP_CCM8_TLS_TAG_LEN;
271          else
272             taglen = EVP_CCM_TLS_TAG_LEN;
273     } else {
274         ivlen = EVP_CIPHER_iv_length(ciph);
275         taglen = 0;
276     }
277
278     if (!tls13_derive_key(s, md, secret, key, keylen)
279             || !tls13_derive_iv(s, md, secret, iv, ivlen)) {
280         SSLerr(SSL_F_DERIVE_SECRET_KEY_AND_IV, ERR_R_INTERNAL_ERROR);
281         goto err;
282     }
283
284     if (EVP_CipherInit_ex(ciph_ctx, ciph, NULL, NULL, NULL, send) <= 0
285         || !EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_IVLEN, ivlen, NULL)
286         || (taglen != 0 && !EVP_CIPHER_CTX_ctrl(ciph_ctx, EVP_CTRL_AEAD_SET_TAG,
287                                                 taglen, NULL))
288         || EVP_CipherInit_ex(ciph_ctx, NULL, NULL, key, NULL, -1) <= 0) {
289         SSLerr(SSL_F_DERIVE_SECRET_KEY_AND_IV, ERR_R_EVP_LIB);
290         goto err;
291     }
292
293 #ifdef OPENSSL_SSL_TRACE_CRYPTO
294     if (s->msg_callback) {
295         int wh = send ? TLS1_RT_CRYPTO_WRITE : 0;
296
297         if (ciph->key_len)
298             s->msg_callback(2, s->version, wh | TLS1_RT_CRYPTO_KEY,
299                             key, ciph->key_len, s, s->msg_callback_arg);
300
301         wh |= TLS1_RT_CRYPTO_IV;
302         s->msg_callback(2, s->version, wh, iv, ivlen, s,
303                         s->msg_callback_arg);
304     }
305 #endif
306
307     return 1;
308  err:
309     OPENSSL_cleanse(key, sizeof(key));
310     return 0;
311 }
312
313 int tls13_change_cipher_state(SSL *s, int which)
314 {
315     static const unsigned char client_early_traffic[] =
316         "client early traffic secret";
317     static const unsigned char client_handshake_traffic[] =
318         "client handshake traffic secret";
319     static const unsigned char client_application_traffic[] =
320         "client application traffic secret";
321     static const unsigned char server_handshake_traffic[] =
322         "server handshake traffic secret";
323     static const unsigned char server_application_traffic[] =
324         "server application traffic secret";
325     static const unsigned char resumption_master_secret[] =
326         "resumption master secret";
327     unsigned char *iv;
328     unsigned char secret[EVP_MAX_MD_SIZE];
329     unsigned char hashval[EVP_MAX_MD_SIZE];
330     unsigned char *hash = hashval;
331     unsigned char *insecret;
332     unsigned char *finsecret = NULL;
333     const char *log_label = NULL;
334     EVP_CIPHER_CTX *ciph_ctx;
335     size_t finsecretlen = 0;
336     const unsigned char *label;
337     size_t labellen, hashlen = 0;
338     int ret = 0;
339     const EVP_MD *md;
340     const EVP_CIPHER *cipher;
341
342     if (which & SSL3_CC_READ) {
343         if (s->enc_read_ctx != NULL) {
344             EVP_CIPHER_CTX_reset(s->enc_read_ctx);
345         } else {
346             s->enc_read_ctx = EVP_CIPHER_CTX_new();
347             if (s->enc_read_ctx == NULL) {
348                 SSLerr(SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
349                 goto err;
350             }
351         }
352         ciph_ctx = s->enc_read_ctx;
353         iv = s->read_iv;
354
355         RECORD_LAYER_reset_read_sequence(&s->rlayer);
356     } else {
357         if (s->enc_write_ctx != NULL) {
358             EVP_CIPHER_CTX_reset(s->enc_write_ctx);
359         } else {
360             s->enc_write_ctx = EVP_CIPHER_CTX_new();
361             if (s->enc_write_ctx == NULL) {
362                 SSLerr(SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
363                 goto err;
364             }
365         }
366         ciph_ctx = s->enc_write_ctx;
367         iv = s->write_iv;
368
369         RECORD_LAYER_reset_write_sequence(&s->rlayer);
370     }
371
372     if (((which & SSL3_CC_CLIENT) && (which & SSL3_CC_WRITE))
373             || ((which & SSL3_CC_SERVER) && (which & SSL3_CC_READ))) {
374         if (which & SSL3_CC_EARLY) {
375             EVP_MD_CTX *mdctx = NULL;
376             long handlen;
377             void *hdata;
378             unsigned int hashlenui;
379             const SSL_CIPHER *sslcipher = SSL_SESSION_get0_cipher(s->session);
380
381             insecret = s->early_secret;
382             label = client_early_traffic;
383             labellen = sizeof(client_early_traffic) - 1;
384             log_label = CLIENT_EARLY_LABEL;
385
386             handlen = BIO_get_mem_data(s->s3->handshake_buffer, &hdata);
387             if (handlen <= 0) {
388                 SSLerr(SSL_F_TLS13_CHANGE_CIPHER_STATE,
389                        SSL_R_BAD_HANDSHAKE_LENGTH);
390                 goto err;
391             }
392             if (sslcipher == NULL) {
393                 SSLerr(SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
394                 goto err;
395             }
396
397             /*
398              * We need to calculate the handshake digest using the digest from
399              * the session. We haven't yet selected our ciphersuite so we can't
400              * use ssl_handshake_md().
401              */
402             mdctx = EVP_MD_CTX_new();
403             if (mdctx == NULL) {
404                 SSLerr(SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_MALLOC_FAILURE);
405                 goto err;
406             }
407             cipher = EVP_get_cipherbynid(SSL_CIPHER_get_cipher_nid(sslcipher));
408             md = ssl_md(sslcipher->algorithm2);
409             if (md == NULL || !EVP_DigestInit_ex(mdctx, md, NULL)
410                     || !EVP_DigestUpdate(mdctx, hdata, handlen)
411                     || !EVP_DigestFinal_ex(mdctx, hashval, &hashlenui)) {
412                 SSLerr(SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
413                 EVP_MD_CTX_free(mdctx);
414                 goto err;
415             }
416             hashlen = hashlenui;
417             EVP_MD_CTX_free(mdctx);
418         } else if (which & SSL3_CC_HANDSHAKE) {
419             insecret = s->handshake_secret;
420             finsecret = s->client_finished_secret;
421             finsecretlen = EVP_MD_size(ssl_handshake_md(s));
422             label = client_handshake_traffic;
423             labellen = sizeof(client_handshake_traffic) - 1;
424             log_label = CLIENT_HANDSHAKE_LABEL;
425             /*
426              * The hanshake hash used for the server read handshake traffic
427              * secret is the same as the hash for the server write handshake
428              * traffic secret. However, if we processed early data then we delay
429              * changing the server read cipher state until later, and the
430              * handshake hashes have moved on. Therefore we use the value saved
431              * earlier when we did the server write change cipher state.
432              */
433             if (s->server)
434                 hash = s->handshake_traffic_hash;
435         } else {
436             insecret = s->master_secret;
437             label = client_application_traffic;
438             labellen = sizeof(client_application_traffic) - 1;
439             log_label = CLIENT_APPLICATION_LABEL;
440             /*
441              * For this we only use the handshake hashes up until the server
442              * Finished hash. We do not include the client's Finished, which is
443              * what ssl_handshake_hash() would give us. Instead we use the
444              * previously saved value.
445              */
446             hash = s->server_finished_hash;
447         }
448     } else {
449         /* Early data never applies to client-read/server-write */
450         if (which & SSL3_CC_HANDSHAKE) {
451             insecret = s->handshake_secret;
452             finsecret = s->server_finished_secret;
453             finsecretlen = EVP_MD_size(ssl_handshake_md(s));
454             label = server_handshake_traffic;
455             labellen = sizeof(server_handshake_traffic) - 1;
456             log_label = SERVER_HANDSHAKE_LABEL;
457         } else {
458             insecret = s->master_secret;
459             label = server_application_traffic;
460             labellen = sizeof(server_application_traffic) - 1;
461             log_label = SERVER_APPLICATION_LABEL;
462         }
463     }
464
465     if (!(which & SSL3_CC_EARLY)) {
466         md = ssl_handshake_md(s);
467         cipher = s->s3->tmp.new_sym_enc;
468         if (!ssl3_digest_cached_records(s, 1)
469                 || !ssl_handshake_hash(s, hashval, sizeof(hashval), &hashlen)) {
470             SSLerr(SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
471             goto err;
472         }
473     }
474
475     /*
476      * Save the hash of handshakes up to now for use when we calculate the
477      * client application traffic secret
478      */
479     if (label == server_application_traffic)
480         memcpy(s->server_finished_hash, hashval, hashlen);
481
482     if (s->server && label == server_handshake_traffic)
483         memcpy(s->handshake_traffic_hash, hashval, hashlen);
484
485     if (label == client_application_traffic) {
486         /*
487          * We also create the resumption master secret, but this time use the
488          * hash for the whole handshake including the Client Finished
489          */
490         if (!tls13_hkdf_expand(s, ssl_handshake_md(s), insecret,
491                                resumption_master_secret,
492                                sizeof(resumption_master_secret) - 1,
493                                hashval, s->session->master_key, hashlen)) {
494             SSLerr(SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
495             goto err;
496         }
497         s->session->master_key_length = hashlen;
498     }
499
500     if (!derive_secret_key_and_iv(s, which & SSL3_CC_WRITE, md, cipher,
501                                   insecret, hash, label, labellen, secret, iv,
502                                   ciph_ctx)) {
503         goto err;
504     }
505
506     if (label == server_application_traffic)
507         memcpy(s->server_app_traffic_secret, secret, hashlen);
508     else if (label == client_application_traffic)
509         memcpy(s->client_app_traffic_secret, secret, hashlen);
510
511     if (!ssl_log_secret(s, log_label, secret, hashlen)) {
512         SSLerr(SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
513         goto err;
514     }
515
516     if (finsecret != NULL
517             && !tls13_derive_finishedkey(s, ssl_handshake_md(s), secret,
518                                          finsecret, finsecretlen)) {
519         SSLerr(SSL_F_TLS13_CHANGE_CIPHER_STATE, ERR_R_INTERNAL_ERROR);
520         goto err;
521     }
522
523     ret = 1;
524  err:
525     OPENSSL_cleanse(secret, sizeof(secret));
526     return ret;
527 }
528
529 int tls13_update_key(SSL *s, int send)
530 {
531     static const unsigned char application_traffic[] =
532         "application traffic secret";
533     const EVP_MD *md = ssl_handshake_md(s);
534     size_t hashlen = EVP_MD_size(md);
535     unsigned char *insecret, *iv;
536     unsigned char secret[EVP_MAX_MD_SIZE];
537     EVP_CIPHER_CTX *ciph_ctx;
538     int ret = 0;
539
540     if (s->server == send)
541         insecret = s->server_app_traffic_secret;
542     else
543         insecret = s->client_app_traffic_secret;
544
545     if (send) {
546         iv = s->write_iv;
547         ciph_ctx = s->enc_write_ctx;
548         RECORD_LAYER_reset_write_sequence(&s->rlayer);
549     } else {
550         iv = s->read_iv;
551         ciph_ctx = s->enc_read_ctx;
552         RECORD_LAYER_reset_read_sequence(&s->rlayer);
553     }
554
555     if (!derive_secret_key_and_iv(s, send, ssl_handshake_md(s),
556                                   s->s3->tmp.new_sym_enc, insecret, NULL,
557                                   application_traffic,
558                                   sizeof(application_traffic) - 1, secret, iv,
559                                   ciph_ctx))
560         goto err;
561
562     memcpy(insecret, secret, hashlen);
563
564     ret = 1;
565  err:
566     OPENSSL_cleanse(secret, sizeof(secret));
567     return ret;
568 }
569
570 int tls13_alert_code(int code)
571 {
572     if (code == SSL_AD_MISSING_EXTENSION || code == SSL_AD_END_OF_EARLY_DATA)
573         return code;
574
575     return tls1_alert_code(code);
576 }