Fix propq in x942kdf
[openssl.git] / providers / implementations / kdfs / x942kdf.c
1 /*
2  * Copyright 2019-2020 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright (c) 2019, Oracle and/or its affiliates.  All rights reserved.
4  *
5  * Licensed under the Apache License 2.0 (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  */
10
11 #include "e_os.h"
12 #include <openssl/core_names.h>
13 #include <openssl/core_dispatch.h>
14 #include <openssl/err.h>
15 #include <openssl/evp.h>
16 #include <openssl/params.h>
17 #include "internal/packet.h"
18 #include "internal/der.h"
19 #include "prov/provider_ctx.h"
20 #include "prov/providercommon.h"
21 #include "prov/providercommonerr.h"
22 #include "prov/implementations.h"
23 #include "prov/provider_util.h"
24 #include "prov/der_wrap.h"
25
26 #define X942KDF_MAX_INLEN (1 << 30)
27
28 static OSSL_FUNC_kdf_newctx_fn x942kdf_new;
29 static OSSL_FUNC_kdf_freectx_fn x942kdf_free;
30 static OSSL_FUNC_kdf_reset_fn x942kdf_reset;
31 static OSSL_FUNC_kdf_derive_fn x942kdf_derive;
32 static OSSL_FUNC_kdf_settable_ctx_params_fn x942kdf_settable_ctx_params;
33 static OSSL_FUNC_kdf_set_ctx_params_fn x942kdf_set_ctx_params;
34 static OSSL_FUNC_kdf_gettable_ctx_params_fn x942kdf_gettable_ctx_params;
35 static OSSL_FUNC_kdf_get_ctx_params_fn x942kdf_get_ctx_params;
36
37 typedef struct {
38     void *provctx;
39     PROV_DIGEST digest;
40     unsigned char *secret;
41     size_t secret_len;
42     unsigned char *ukm;
43     size_t ukm_len;
44     size_t dkm_len;
45     const unsigned char *cek_oid;
46     size_t cek_oid_len;
47 } KDF_X942;
48
49 /*
50  * A table of allowed wrapping algorithms, oids and the associated output
51  * lengths.
52  * NOTE: RC2wrap and camellia128_wrap have been removed as there are no
53  * corresponding ciphers for these operations.
54  */
55 static const struct {
56     const char *name;
57     const unsigned char *oid;
58     size_t oid_len;
59     size_t keklen; /* size in bytes */
60 } kek_algs[] = {
61     { "AES-128-WRAP", der_oid_id_aes128_wrap, DER_OID_SZ_id_aes128_wrap, 16 },
62     { "AES-192-WRAP", der_oid_id_aes192_wrap, DER_OID_SZ_id_aes192_wrap, 24 },
63     { "AES-256-WRAP", der_oid_id_aes256_wrap, DER_OID_SZ_id_aes256_wrap, 32 },
64 #ifndef FIPS_MODULE
65     { "DES3-WRAP", der_oid_id_alg_CMS3DESwrap, DER_OID_SZ_id_alg_CMS3DESwrap,
66       24 },
67 #endif
68 };
69
70 static int find_alg_id(OPENSSL_CTX *libctx, const char *algname,
71                        const char *propq, size_t *id)
72 {
73     int ret = 1;
74     size_t i;
75     EVP_CIPHER *cipher;
76
77     cipher = EVP_CIPHER_fetch(libctx, algname, propq);
78     if (cipher != NULL) {
79         for (i = 0; i < OSSL_NELEM(kek_algs); i++) {
80             if (EVP_CIPHER_is_a(cipher, kek_algs[i].name)) {
81                 *id = i;
82                 goto end;
83             }
84         }
85     }
86     ret = 0;
87     ERR_raise(ERR_LIB_PROV, PROV_R_UNSUPPORTED_CEK_ALG);
88 end:
89     EVP_CIPHER_free(cipher);
90     return ret;
91 }
92
93 static int DER_w_keyinfo(WPACKET *pkt,
94                          const unsigned char *der_oid, size_t der_oidlen,
95                          unsigned char **pcounter)
96 {
97     return DER_w_begin_sequence(pkt, -1)
98            /* Store the initial value of 1 into the counter */
99            && DER_w_octet_string_uint32(pkt, -1, 1)
100            /* Remember where we stored the counter in the buffer */
101            && (pcounter == NULL
102                || (*pcounter = WPACKET_get_curr(pkt)) != NULL)
103            && DER_w_precompiled(pkt, -1, der_oid, der_oidlen)
104            && DER_w_end_sequence(pkt, -1);
105 }
106
107 static int der_encode_sharedinfo(WPACKET *pkt, unsigned char *buf, size_t buflen,
108                                  const unsigned char *der_oid, size_t der_oidlen,
109                                  const unsigned char *ukm, size_t ukmlen,
110                                  uint32_t keylen_bits, unsigned char **pcounter)
111 {
112     return (buf != NULL ? WPACKET_init_der(pkt, buf, buflen) :
113                           WPACKET_init_null_der(pkt))
114            && DER_w_begin_sequence(pkt, -1)
115            && DER_w_octet_string_uint32(pkt, 2, keylen_bits)
116            && (ukm == NULL || DER_w_octet_string(pkt, 0, ukm, ukmlen))
117            && DER_w_keyinfo(pkt, der_oid, der_oidlen, pcounter)
118            && DER_w_end_sequence(pkt, -1)
119            && WPACKET_finish(pkt);
120 }
121
122 /*
123  * Encode the other info structure.
124  *
125  *  RFC2631 Section 2.1.2 Contains the following definition for otherinfo
126  *
127  *  OtherInfo ::= SEQUENCE {
128  *      keyInfo KeySpecificInfo,
129  *      partyAInfo [0] OCTET STRING OPTIONAL,
130  *      suppPubInfo [2] OCTET STRING
131  *  }
132  *  Note suppPubInfo is the key length (in bits) (stored into 4 bytes)
133  *
134  *
135  *  KeySpecificInfo ::= SEQUENCE {
136  *      algorithm OBJECT IDENTIFIER,
137  *      counter OCTET STRING SIZE (4..4)
138  *  }
139  *
140  * |keylen| is the length (in bytes) of the generated KEK. It is stored into
141  * suppPubInfo (in bits).
142  * |cek_oid| The oid of the key wrapping algorithm.
143  * |cek_oidlen| The length (in bytes) of the key wrapping algorithm oid,
144  * |ukm| is the optional user keying material that is stored into partyAInfo. It
145  * can be NULL.
146  * |ukmlen| is the user keying material length (in bytes).
147  * |der| is the returned encoded data. It must be freed by the caller.
148  * |der_len| is the returned size of the encoded data.
149  * |out_ctr| returns a pointer to the counter data which is embedded inside the
150  * encoded data. This allows the counter bytes to be updated without re-encoding.
151  *
152  * Returns: 1 if successfully encoded, or 0 otherwise.
153  * Assumptions: |der|, |der_len| & |out_ctr| are not NULL.
154  */
155 static int x942_encode_otherinfo(size_t keylen,
156                                  const unsigned char *cek_oid, size_t cek_oidlen,
157                                  const unsigned char *ukm, size_t ukmlen,
158                                  unsigned char **der, size_t *der_len,
159                                  unsigned char **out_ctr)
160 {
161     int ret = 0;
162     unsigned char *pcounter = NULL, *der_buf = NULL;
163     size_t der_buflen = 0;
164     WPACKET pkt;
165     uint32_t keylen_bits;
166
167     /* keylenbits must fit into 4 bytes */
168     if (keylen > 0xFFFFFF)
169         return 0;
170     keylen_bits = 8 * keylen;
171
172     /* Calculate the size of the buffer */
173     if (!der_encode_sharedinfo(&pkt, NULL, 0, cek_oid, cek_oidlen, ukm, ukmlen,
174                                keylen_bits, NULL)
175         || !WPACKET_get_total_written(&pkt, &der_buflen))
176         goto err;
177     WPACKET_cleanup(&pkt);
178     /* Alloc the buffer */
179     der_buf = OPENSSL_zalloc(der_buflen);
180     if (der_buf == NULL)
181         goto err;
182     /* Encode into the buffer */
183     if (!der_encode_sharedinfo(&pkt, der_buf, der_buflen, cek_oid, cek_oidlen,
184                                ukm, ukmlen, keylen_bits, &pcounter))
185         goto err;
186     /*
187      * Since we allocated the exact size required, the buffer should point to the
188      * start of the alllocated buffer at this point.
189      */
190     if (WPACKET_get_curr(&pkt) != der_buf)
191         goto err;
192
193     /*
194      * The data for the DER encoded octet string of a 32 bit counter = 1
195      * should be 04 04 00 00 00 01
196      * So just check the header is correct and skip over it.
197      * This counter will be incremented in the kdf update loop.
198      */
199     if (pcounter == NULL
200         || pcounter[0] != 0x04
201         || pcounter[1] != 0x04)
202         goto err;
203     *out_ctr = (pcounter + 2);
204     *der = der_buf;
205     *der_len = der_buflen;
206     ret = 1;
207 err:
208     WPACKET_cleanup(&pkt);
209     return ret;
210 }
211
212 static int x942kdf_hash_kdm(const EVP_MD *kdf_md,
213                             const unsigned char *z, size_t z_len,
214                             const unsigned char *other, size_t other_len,
215                             unsigned char *ctr,
216                             unsigned char *derived_key, size_t derived_key_len)
217 {
218     int ret = 0, hlen;
219     size_t counter, out_len, len = derived_key_len;
220     unsigned char mac[EVP_MAX_MD_SIZE];
221     unsigned char *out = derived_key;
222     EVP_MD_CTX *ctx = NULL, *ctx_init = NULL;
223
224     if (z_len > X942KDF_MAX_INLEN || other_len > X942KDF_MAX_INLEN
225             || derived_key_len > X942KDF_MAX_INLEN
226             || derived_key_len == 0) {
227         ERR_raise(ERR_LIB_PROV, PROV_R_BAD_LENGTH);
228         return 0;
229     }
230
231     hlen = EVP_MD_size(kdf_md);
232     if (hlen <= 0)
233         return 0;
234     out_len = (size_t)hlen;
235
236     ctx = EVP_MD_CTX_create();
237     ctx_init = EVP_MD_CTX_create();
238     if (ctx == NULL || ctx_init == NULL)
239         goto end;
240
241     if (!EVP_DigestInit(ctx_init, kdf_md))
242         goto end;
243
244     for (counter = 1;; counter++) {
245         /* updating the ctr modifies 4 bytes in the 'other' buffer */
246         ctr[0] = (unsigned char)((counter >> 24) & 0xff);
247         ctr[1] = (unsigned char)((counter >> 16) & 0xff);
248         ctr[2] = (unsigned char)((counter >> 8) & 0xff);
249         ctr[3] = (unsigned char)(counter & 0xff);
250
251         if (!EVP_MD_CTX_copy_ex(ctx, ctx_init)
252             || !EVP_DigestUpdate(ctx, z, z_len)
253             || !EVP_DigestUpdate(ctx, other, other_len))
254             goto end;
255         if (len >= out_len) {
256             if (!EVP_DigestFinal_ex(ctx, out, NULL))
257                 goto end;
258             out += out_len;
259             len -= out_len;
260             if (len == 0)
261                 break;
262         } else {
263             if (!EVP_DigestFinal_ex(ctx, mac, NULL))
264                 goto end;
265             memcpy(out, mac, len);
266             break;
267         }
268     }
269     ret = 1;
270 end:
271     EVP_MD_CTX_free(ctx);
272     EVP_MD_CTX_free(ctx_init);
273     OPENSSL_cleanse(mac, sizeof(mac));
274     return ret;
275 }
276
277 static void *x942kdf_new(void *provctx)
278 {
279     KDF_X942 *ctx;
280
281     if (!ossl_prov_is_running())
282         return 0;
283
284     if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL)
285         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
286     ctx->provctx = provctx;
287     return ctx;
288 }
289
290 static void x942kdf_reset(void *vctx)
291 {
292     KDF_X942 *ctx = (KDF_X942 *)vctx;
293     void *provctx = ctx->provctx;
294
295     ossl_prov_digest_reset(&ctx->digest);
296     OPENSSL_clear_free(ctx->secret, ctx->secret_len);
297     OPENSSL_clear_free(ctx->ukm, ctx->ukm_len);
298     memset(ctx, 0, sizeof(*ctx));
299     ctx->provctx = provctx;
300 }
301
302 static void x942kdf_free(void *vctx)
303 {
304     KDF_X942 *ctx = (KDF_X942 *)vctx;
305
306     if (ctx != NULL) {
307         x942kdf_reset(ctx);
308         OPENSSL_free(ctx);
309     }
310 }
311
312 static int x942kdf_set_buffer(unsigned char **out, size_t *out_len,
313                               const OSSL_PARAM *p)
314 {
315     if (p->data_size == 0 || p->data == NULL)
316         return 1;
317
318     OPENSSL_free(*out);
319     *out = NULL;
320     return OSSL_PARAM_get_octet_string(p, (void **)out, 0, out_len);
321 }
322
323 static size_t x942kdf_size(KDF_X942 *ctx)
324 {
325     int len;
326     const EVP_MD *md = ossl_prov_digest_md(&ctx->digest);
327
328     if (md == NULL) {
329         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
330         return 0;
331     }
332     len = EVP_MD_size(md);
333     return (len <= 0) ? 0 : (size_t)len;
334 }
335
336 static int x942kdf_derive(void *vctx, unsigned char *key, size_t keylen)
337 {
338     KDF_X942 *ctx = (KDF_X942 *)vctx;
339     const EVP_MD *md;
340     int ret = 0;
341     unsigned char *ctr;
342     unsigned char *der = NULL;
343     size_t der_len = 0;
344
345     if (!ossl_prov_is_running())
346         return 0;
347
348     if (ctx->secret == NULL) {
349         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_SECRET);
350         return 0;
351     }
352     md = ossl_prov_digest_md(&ctx->digest);
353     if (md == NULL) {
354         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_MESSAGE_DIGEST);
355         return 0;
356     }
357     if (ctx->cek_oid == NULL || ctx->cek_oid_len == 0) {
358         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_CEK_ALG);
359         return 0;
360     }
361     if (ctx->ukm != NULL && ctx->ukm_len >= X942KDF_MAX_INLEN) {
362         /*
363          * Note the ukm length MUST be 512 bits.
364          * For backwards compatibility the old check is being done.
365          */
366         ERR_raise(ERR_LIB_PROV, PROV_R_INAVLID_UKM_LENGTH);
367         return 0;
368     }
369     /* generate the otherinfo der */
370     if (!x942_encode_otherinfo(ctx->dkm_len,
371                                ctx->cek_oid, ctx->cek_oid_len,
372                                ctx->ukm, ctx->ukm_len,
373                                &der, &der_len, &ctr)) {
374         ERR_raise(ERR_LIB_PROV, PROV_R_BAD_ENCODING);
375         return 0;
376     }
377     ret = x942kdf_hash_kdm(md, ctx->secret, ctx->secret_len,
378                            der, der_len, ctr, key, keylen);
379     OPENSSL_free(der);
380     return ret;
381 }
382
383 static int x942kdf_set_ctx_params(void *vctx, const OSSL_PARAM params[])
384 {
385     const OSSL_PARAM *p, *pq;
386     KDF_X942 *ctx = vctx;
387     OPENSSL_CTX *provctx = PROV_LIBRARY_CONTEXT_OF(ctx->provctx);
388     const char *propq = NULL;
389     size_t id;
390
391     if (!ossl_prov_digest_load_from_params(&ctx->digest, params, provctx))
392         return 0;
393
394     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_SECRET)) != NULL
395         || (p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KEY)) != NULL)
396         if (!x942kdf_set_buffer(&ctx->secret, &ctx->secret_len, p))
397             return 0;
398
399     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_UKM)) != NULL)
400         if (!x942kdf_set_buffer(&ctx->ukm, &ctx->ukm_len, p))
401             return 0;
402
403     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_CEK_ALG)) != NULL) {
404         if (p->data_type != OSSL_PARAM_UTF8_STRING)
405             return 0;
406         pq = OSSL_PARAM_locate_const(params, OSSL_ALG_PARAM_PROPERTIES);
407         /*
408          * We already grab the properties during ossl_prov_digest_load_from_params()
409          * so there is no need to check the validity again..
410          */
411         if (pq != NULL)
412             propq = p->data;
413         if (find_alg_id(provctx, p->data, propq, &id) == 0)
414             return 0;
415         ctx->cek_oid = kek_algs[id].oid;
416         ctx->cek_oid_len = kek_algs[id].oid_len;
417         ctx->dkm_len = kek_algs[id].keklen;
418     }
419     return 1;
420 }
421
422 static const OSSL_PARAM *x942kdf_settable_ctx_params(ossl_unused void *provctx)
423 {
424     static const OSSL_PARAM known_settable_ctx_params[] = {
425         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
426         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_DIGEST, NULL, 0),
427         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_SECRET, NULL, 0),
428         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_KEY, NULL, 0),
429         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_UKM, NULL, 0),
430         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_CEK_ALG, NULL, 0),
431         OSSL_PARAM_END
432     };
433     return known_settable_ctx_params;
434 }
435
436 static int x942kdf_get_ctx_params(void *vctx, OSSL_PARAM params[])
437 {
438     KDF_X942 *ctx = (KDF_X942 *)vctx;
439     OSSL_PARAM *p;
440
441     if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL)
442         return OSSL_PARAM_set_size_t(p, x942kdf_size(ctx));
443     return -2;
444 }
445
446 static const OSSL_PARAM *x942kdf_gettable_ctx_params(ossl_unused void *provctx)
447 {
448     static const OSSL_PARAM known_gettable_ctx_params[] = {
449         OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
450         OSSL_PARAM_END
451     };
452     return known_gettable_ctx_params;
453 }
454
455 const OSSL_DISPATCH kdf_x942_kdf_functions[] = {
456     { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))x942kdf_new },
457     { OSSL_FUNC_KDF_FREECTX, (void(*)(void))x942kdf_free },
458     { OSSL_FUNC_KDF_RESET, (void(*)(void))x942kdf_reset },
459     { OSSL_FUNC_KDF_DERIVE, (void(*)(void))x942kdf_derive },
460     { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
461       (void(*)(void))x942kdf_settable_ctx_params },
462     { OSSL_FUNC_KDF_SET_CTX_PARAMS, (void(*)(void))x942kdf_set_ctx_params },
463     { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
464       (void(*)(void))x942kdf_gettable_ctx_params },
465     { OSSL_FUNC_KDF_GET_CTX_PARAMS, (void(*)(void))x942kdf_get_ctx_params },
466     { 0, NULL }
467 };