Teach TLSProxy how to parse CertificateRequest messages
[openssl.git] / crypto / kdf / hkdf.c
1 /*
2  * Copyright 2016-2018 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 <stdarg.h>
12 #include <string.h>
13 #include <openssl/hmac.h>
14 #include <openssl/evp.h>
15 #include <openssl/kdf.h>
16 #include "internal/cryptlib.h"
17 #include "internal/numbers.h"
18 #include "internal/evp_int.h"
19 #include "kdf_local.h"
20
21 #define HKDF_MAXBUF 1024
22
23 static void kdf_hkdf_reset(EVP_KDF_IMPL *impl);
24 static int HKDF(const EVP_MD *evp_md,
25                 const unsigned char *salt, size_t salt_len,
26                 const unsigned char *key, size_t key_len,
27                 const unsigned char *info, size_t info_len,
28                 unsigned char *okm, size_t okm_len);
29 static int HKDF_Extract(const EVP_MD *evp_md,
30                         const unsigned char *salt, size_t salt_len,
31                         const unsigned char *ikm, size_t ikm_len,
32                         unsigned char *prk, size_t prk_len);
33 static int HKDF_Expand(const EVP_MD *evp_md,
34                        const unsigned char *prk, size_t prk_len,
35                        const unsigned char *info, size_t info_len,
36                        unsigned char *okm, size_t okm_len);
37
38 struct evp_kdf_impl_st {
39     int mode;
40     const EVP_MD *md;
41     unsigned char *salt;
42     size_t salt_len;
43     unsigned char *key;
44     size_t key_len;
45     unsigned char info[HKDF_MAXBUF];
46     size_t info_len;
47 };
48
49 static EVP_KDF_IMPL *kdf_hkdf_new(void)
50 {
51     EVP_KDF_IMPL *impl;
52
53     if ((impl = OPENSSL_zalloc(sizeof(*impl))) == NULL)
54         KDFerr(KDF_F_KDF_HKDF_NEW, ERR_R_MALLOC_FAILURE);
55     return impl;
56 }
57
58 static void kdf_hkdf_free(EVP_KDF_IMPL *impl)
59 {
60     kdf_hkdf_reset(impl);
61     OPENSSL_free(impl);
62 }
63
64 static void kdf_hkdf_reset(EVP_KDF_IMPL *impl)
65 {
66     OPENSSL_free(impl->salt);
67     OPENSSL_clear_free(impl->key, impl->key_len);
68     OPENSSL_cleanse(impl->info, impl->info_len);
69     memset(impl, 0, sizeof(*impl));
70 }
71
72 static int kdf_hkdf_ctrl(EVP_KDF_IMPL *impl, int cmd, va_list args)
73 {
74     const unsigned char *p;
75     size_t len;
76     const EVP_MD *md;
77
78     switch (cmd) {
79     case EVP_KDF_CTRL_SET_MD:
80         md = va_arg(args, const EVP_MD *);
81         if (md == NULL)
82             return 0;
83
84         impl->md = md;
85         return 1;
86
87     case EVP_KDF_CTRL_SET_HKDF_MODE:
88         impl->mode = va_arg(args, int);
89         return 1;
90
91     case EVP_KDF_CTRL_SET_SALT:
92         p = va_arg(args, const unsigned char *);
93         len = va_arg(args, size_t);
94         if (len == 0 || p == NULL)
95             return 1;
96
97         OPENSSL_free(impl->salt);
98         impl->salt = OPENSSL_memdup(p, len);
99         if (impl->salt == NULL)
100             return 0;
101
102         impl->salt_len = len;
103         return 1;
104
105     case EVP_KDF_CTRL_SET_KEY:
106         p = va_arg(args, const unsigned char *);
107         len = va_arg(args, size_t);
108         OPENSSL_clear_free(impl->key, impl->key_len);
109         impl->key = OPENSSL_memdup(p, len);
110         if (impl->key == NULL)
111             return 0;
112
113         impl->key_len  = len;
114         return 1;
115
116     case EVP_KDF_CTRL_RESET_HKDF_INFO:
117         OPENSSL_cleanse(impl->info, impl->info_len);
118         impl->info_len = 0;
119         return 1;
120
121     case EVP_KDF_CTRL_ADD_HKDF_INFO:
122         p = va_arg(args, const unsigned char *);
123         len = va_arg(args, size_t);
124         if (len == 0 || p == NULL)
125             return 1;
126
127         if (len > (HKDF_MAXBUF - impl->info_len))
128             return 0;
129
130         memcpy(impl->info + impl->info_len, p, len);
131         impl->info_len += len;
132         return 1;
133
134     default:
135         return -2;
136     }
137 }
138
139 static int kdf_hkdf_ctrl_str(EVP_KDF_IMPL *impl, const char *type,
140                              const char *value)
141 {
142     if (strcmp(type, "mode") == 0) {
143         int mode;
144
145         if (strcmp(value, "EXTRACT_AND_EXPAND") == 0)
146             mode = EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND;
147         else if (strcmp(value, "EXTRACT_ONLY") == 0)
148             mode = EVP_KDF_HKDF_MODE_EXTRACT_ONLY;
149         else if (strcmp(value, "EXPAND_ONLY") == 0)
150             mode = EVP_KDF_HKDF_MODE_EXPAND_ONLY;
151         else
152             return 0;
153
154         return call_ctrl(kdf_hkdf_ctrl, impl, EVP_KDF_CTRL_SET_HKDF_MODE, mode);
155     }
156
157     if (strcmp(type, "digest") == 0)
158         return kdf_md2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_SET_MD, value);
159
160     if (strcmp(type, "salt") == 0)
161         return kdf_str2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_SET_SALT, value);
162
163     if (strcmp(type, "hexsalt") == 0)
164         return kdf_hex2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_SET_SALT, value);
165
166     if (strcmp(type, "key") == 0)
167         return kdf_str2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_SET_KEY, value);
168
169     if (strcmp(type, "hexkey") == 0)
170         return kdf_hex2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_SET_KEY, value);
171
172     if (strcmp(type, "info") == 0)
173         return kdf_str2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_ADD_HKDF_INFO,
174                             value);
175
176     if (strcmp(type, "hexinfo") == 0)
177         return kdf_hex2ctrl(impl, kdf_hkdf_ctrl, EVP_KDF_CTRL_ADD_HKDF_INFO,
178                             value);
179
180     return -2;
181 }
182
183 static size_t kdf_hkdf_size(EVP_KDF_IMPL *impl)
184 {
185     int sz;
186
187     if (impl->mode != EVP_KDF_HKDF_MODE_EXTRACT_ONLY)
188         return SIZE_MAX;
189
190     if (impl->md == NULL) {
191         KDFerr(KDF_F_KDF_HKDF_SIZE, KDF_R_MISSING_MESSAGE_DIGEST);
192         return 0;
193     }
194     sz = EVP_MD_size(impl->md);
195     if (sz < 0)
196         return 0;
197
198     return sz;
199 }
200
201 static int kdf_hkdf_derive(EVP_KDF_IMPL *impl, unsigned char *key,
202                            size_t keylen)
203 {
204     if (impl->md == NULL) {
205         KDFerr(KDF_F_KDF_HKDF_DERIVE, KDF_R_MISSING_MESSAGE_DIGEST);
206         return 0;
207     }
208     if (impl->key == NULL) {
209         KDFerr(KDF_F_KDF_HKDF_DERIVE, KDF_R_MISSING_KEY);
210         return 0;
211     }
212
213     switch (impl->mode) {
214     case EVP_KDF_HKDF_MODE_EXTRACT_AND_EXPAND:
215         return HKDF(impl->md, impl->salt, impl->salt_len, impl->key,
216                     impl->key_len, impl->info, impl->info_len, key,
217                     keylen);
218
219     case EVP_KDF_HKDF_MODE_EXTRACT_ONLY:
220         return HKDF_Extract(impl->md, impl->salt, impl->salt_len, impl->key,
221                             impl->key_len, key, keylen);
222
223     case EVP_KDF_HKDF_MODE_EXPAND_ONLY:
224         return HKDF_Expand(impl->md, impl->key, impl->key_len, impl->info,
225                            impl->info_len, key, keylen);
226
227     default:
228         return 0;
229     }
230 }
231
232 const EVP_KDF hkdf_kdf_meth = {
233     EVP_KDF_HKDF,
234     kdf_hkdf_new,
235     kdf_hkdf_free,
236     kdf_hkdf_reset,
237     kdf_hkdf_ctrl,
238     kdf_hkdf_ctrl_str,
239     kdf_hkdf_size,
240     kdf_hkdf_derive
241 };
242
243 /*
244  * Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
245  * Section 2 (https://tools.ietf.org/html/rfc5869#section-2) and
246  * "Cryptographic Extraction and Key Derivation: The HKDF Scheme"
247  * Section 4.2 (https://eprint.iacr.org/2010/264.pdf).
248  *
249  * From the paper:
250  *   The scheme HKDF is specified as:
251  *     HKDF(XTS, SKM, CTXinfo, L) = K(1) | K(2) | ... | K(t)
252  *
253  *     where:
254  *       SKM is source key material
255  *       XTS is extractor salt (which may be null or constant)
256  *       CTXinfo is context information (may be null)
257  *       L is the number of key bits to be produced by KDF
258  *       k is the output length in bits of the hash function used with HMAC
259  *       t = ceil(L/k)
260  *       the value K(t) is truncated to its first d = L mod k bits.
261  *
262  * From RFC 5869:
263  *   2.2.  Step 1: Extract
264  *     HKDF-Extract(salt, IKM) -> PRK
265  *   2.3.  Step 2: Expand
266  *     HKDF-Expand(PRK, info, L) -> OKM
267  */
268 static int HKDF(const EVP_MD *evp_md,
269                 const unsigned char *salt, size_t salt_len,
270                 const unsigned char *ikm, size_t ikm_len,
271                 const unsigned char *info, size_t info_len,
272                 unsigned char *okm, size_t okm_len)
273 {
274     unsigned char prk[EVP_MAX_MD_SIZE];
275     int ret, sz;
276     size_t prk_len;
277
278     sz = EVP_MD_size(evp_md);
279     if (sz < 0)
280         return 0;
281     prk_len = (size_t)sz;
282
283     /* Step 1: HKDF-Extract(salt, IKM) -> PRK */
284     if (!HKDF_Extract(evp_md, salt, salt_len, ikm, ikm_len, prk, prk_len))
285         return 0;
286
287     /* Step 2: HKDF-Expand(PRK, info, L) -> OKM */
288     ret = HKDF_Expand(evp_md, prk, prk_len, info, info_len, okm, okm_len);
289     OPENSSL_cleanse(prk, sizeof(prk));
290
291     return ret;
292 }
293
294 /*
295  * Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
296  * Section 2.2 (https://tools.ietf.org/html/rfc5869#section-2.2).
297  *
298  * 2.2.  Step 1: Extract
299  *
300  *   HKDF-Extract(salt, IKM) -> PRK
301  *
302  *   Options:
303  *      Hash     a hash function; HashLen denotes the length of the
304  *               hash function output in octets
305  *
306  *   Inputs:
307  *      salt     optional salt value (a non-secret random value);
308  *               if not provided, it is set to a string of HashLen zeros.
309  *      IKM      input keying material
310  *
311  *   Output:
312  *      PRK      a pseudorandom key (of HashLen octets)
313  *
314  *   The output PRK is calculated as follows:
315  *
316  *   PRK = HMAC-Hash(salt, IKM)
317  */
318 static int HKDF_Extract(const EVP_MD *evp_md,
319                         const unsigned char *salt, size_t salt_len,
320                         const unsigned char *ikm, size_t ikm_len,
321                         unsigned char *prk, size_t prk_len)
322 {
323     int sz = EVP_MD_size(evp_md);
324
325     if (sz < 0)
326         return 0;
327     if (prk_len != (size_t)sz) {
328         KDFerr(KDF_F_HKDF_EXTRACT, KDF_R_WRONG_OUTPUT_BUFFER_SIZE);
329         return 0;
330     }
331     /* calc: PRK = HMAC-Hash(salt, IKM) */
332     return HMAC(evp_md, salt, salt_len, ikm, ikm_len, prk, NULL) != NULL;
333 }
334
335 /*
336  * Refer to "HMAC-based Extract-and-Expand Key Derivation Function (HKDF)"
337  * Section 2.3 (https://tools.ietf.org/html/rfc5869#section-2.3).
338  *
339  * 2.3.  Step 2: Expand
340  *
341  *   HKDF-Expand(PRK, info, L) -> OKM
342  *
343  *   Options:
344  *      Hash     a hash function; HashLen denotes the length of the
345  *               hash function output in octets
346  *
347  *   Inputs:
348  *      PRK      a pseudorandom key of at least HashLen octets
349  *               (usually, the output from the extract step)
350  *      info     optional context and application specific information
351  *               (can be a zero-length string)
352  *      L        length of output keying material in octets
353  *               (<= 255*HashLen)
354  *
355  *   Output:
356  *      OKM      output keying material (of L octets)
357  *
358  *   The output OKM is calculated as follows:
359  *
360  *   N = ceil(L/HashLen)
361  *   T = T(1) | T(2) | T(3) | ... | T(N)
362  *   OKM = first L octets of T
363  *
364  *   where:
365  *   T(0) = empty string (zero length)
366  *   T(1) = HMAC-Hash(PRK, T(0) | info | 0x01)
367  *   T(2) = HMAC-Hash(PRK, T(1) | info | 0x02)
368  *   T(3) = HMAC-Hash(PRK, T(2) | info | 0x03)
369  *   ...
370  *
371  *   (where the constant concatenated to the end of each T(n) is a
372  *   single octet.)
373  */
374 static int HKDF_Expand(const EVP_MD *evp_md,
375                        const unsigned char *prk, size_t prk_len,
376                        const unsigned char *info, size_t info_len,
377                        unsigned char *okm, size_t okm_len)
378 {
379     HMAC_CTX *hmac;
380     int ret = 0, sz;
381     unsigned int i;
382     unsigned char prev[EVP_MAX_MD_SIZE];
383     size_t done_len = 0, dig_len, n;
384
385     sz = EVP_MD_size(evp_md);
386     if (sz <= 0)
387         return 0;
388     dig_len = (size_t)sz;
389
390     /* calc: N = ceil(L/HashLen) */
391     n = okm_len / dig_len;
392     if (okm_len % dig_len)
393         n++;
394
395     if (n > 255 || okm == NULL)
396         return 0;
397
398     if ((hmac = HMAC_CTX_new()) == NULL)
399         return 0;
400
401     if (!HMAC_Init_ex(hmac, prk, prk_len, evp_md, NULL))
402         goto err;
403
404     for (i = 1; i <= n; i++) {
405         size_t copy_len;
406         const unsigned char ctr = i;
407
408         /* calc: T(i) = HMAC-Hash(PRK, T(i - 1) | info | i) */
409         if (i > 1) {
410             if (!HMAC_Init_ex(hmac, NULL, 0, NULL, NULL))
411                 goto err;
412
413             if (!HMAC_Update(hmac, prev, dig_len))
414                 goto err;
415         }
416
417         if (!HMAC_Update(hmac, info, info_len))
418             goto err;
419
420         if (!HMAC_Update(hmac, &ctr, 1))
421             goto err;
422
423         if (!HMAC_Final(hmac, prev, NULL))
424             goto err;
425
426         copy_len = (done_len + dig_len > okm_len) ?
427                        okm_len - done_len :
428                        dig_len;
429
430         memcpy(okm + done_len, prev, copy_len);
431
432         done_len += copy_len;
433     }
434     ret = 1;
435
436  err:
437     OPENSSL_cleanse(prev, sizeof(prev));
438     HMAC_CTX_free(hmac);
439     return ret;
440 }