prov: add extra params argument to KDF implementations
[openssl.git] / providers / implementations / kdfs / krb5kdf.c
1 /*
2  * Copyright 2018-2021 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 /*
11  * DES low level APIs are deprecated for public use, but still ok for internal
12  * use.  We access the DES_set_odd_parity(3) function here.
13  */
14 #include "internal/deprecated.h"
15
16 #include <stdlib.h>
17 #include <stdarg.h>
18 #include <string.h>
19
20 #include <openssl/core_names.h>
21 #include <openssl/des.h>
22 #include <openssl/evp.h>
23 #include <openssl/kdf.h>
24 #include <openssl/proverr.h>
25
26 #include "internal/cryptlib.h"
27 #include "crypto/evp.h"
28 #include "internal/numbers.h"
29 #include "prov/implementations.h"
30 #include "prov/provider_ctx.h"
31 #include "prov/provider_util.h"
32 #include "prov/providercommon.h"
33
34 /* KRB5 KDF defined in RFC 3961, Section 5.1 */
35
36 static OSSL_FUNC_kdf_newctx_fn krb5kdf_new;
37 static OSSL_FUNC_kdf_freectx_fn krb5kdf_free;
38 static OSSL_FUNC_kdf_reset_fn krb5kdf_reset;
39 static OSSL_FUNC_kdf_derive_fn krb5kdf_derive;
40 static OSSL_FUNC_kdf_settable_ctx_params_fn krb5kdf_settable_ctx_params;
41 static OSSL_FUNC_kdf_set_ctx_params_fn krb5kdf_set_ctx_params;
42 static OSSL_FUNC_kdf_gettable_ctx_params_fn krb5kdf_gettable_ctx_params;
43 static OSSL_FUNC_kdf_get_ctx_params_fn krb5kdf_get_ctx_params;
44
45 static int KRB5KDF(const EVP_CIPHER *cipher, ENGINE *engine,
46                    const unsigned char *key, size_t key_len,
47                    const unsigned char *constant, size_t constant_len,
48                    unsigned char *okey, size_t okey_len);
49
50 typedef struct {
51     void *provctx;
52     PROV_CIPHER cipher;
53     unsigned char *key;
54     size_t key_len;
55     unsigned char *constant;
56     size_t constant_len;
57 } KRB5KDF_CTX;
58
59 static void *krb5kdf_new(void *provctx)
60 {
61     KRB5KDF_CTX *ctx;
62
63     if (!ossl_prov_is_running())
64         return NULL;
65
66     if ((ctx = OPENSSL_zalloc(sizeof(*ctx))) == NULL) {
67         ERR_raise(ERR_LIB_PROV, ERR_R_MALLOC_FAILURE);
68         return NULL;
69     }
70     ctx->provctx = provctx;
71     return ctx;
72 }
73
74 static void krb5kdf_free(void *vctx)
75 {
76     KRB5KDF_CTX *ctx = (KRB5KDF_CTX *)vctx;
77
78     if (ctx != NULL) {
79         krb5kdf_reset(ctx);
80         OPENSSL_free(ctx);
81     }
82 }
83
84 static void krb5kdf_reset(void *vctx)
85 {
86     KRB5KDF_CTX *ctx = (KRB5KDF_CTX *)vctx;
87     void *provctx = ctx->provctx;
88
89     ossl_prov_cipher_reset(&ctx->cipher);
90     OPENSSL_clear_free(ctx->key, ctx->key_len);
91     OPENSSL_clear_free(ctx->constant, ctx->constant_len);
92     memset(ctx, 0, sizeof(*ctx));
93     ctx->provctx = provctx;
94 }
95
96 static int krb5kdf_set_membuf(unsigned char **dst, size_t *dst_len,
97                               const OSSL_PARAM *p)
98 {
99     OPENSSL_clear_free(*dst, *dst_len);
100     *dst = NULL;
101     return OSSL_PARAM_get_octet_string(p, (void **)dst, 0, dst_len);
102 }
103
104 static int krb5kdf_derive(void *vctx, unsigned char *key, size_t keylen,
105                           const OSSL_PARAM params[])
106 {
107     KRB5KDF_CTX *ctx = (KRB5KDF_CTX *)vctx;
108     const EVP_CIPHER *cipher;
109     ENGINE *engine;
110
111     if (!ossl_prov_is_running() || !krb5kdf_set_ctx_params(ctx, params))
112         return 0;
113
114     cipher = ossl_prov_cipher_cipher(&ctx->cipher);
115     if (cipher == NULL) {
116         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_CIPHER);
117         return 0;
118     }
119     if (ctx->key == NULL) {
120         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_KEY);
121         return 0;
122     }
123     if (ctx->constant == NULL) {
124         ERR_raise(ERR_LIB_PROV, PROV_R_MISSING_CONSTANT);
125         return 0;
126     }
127     engine = ossl_prov_cipher_engine(&ctx->cipher);
128     return KRB5KDF(cipher, engine, ctx->key, ctx->key_len,
129                    ctx->constant, ctx->constant_len,
130                    key, keylen);
131 }
132
133 static int krb5kdf_set_ctx_params(void *vctx, const OSSL_PARAM params[])
134 {
135     const OSSL_PARAM *p;
136     KRB5KDF_CTX *ctx = vctx;
137     OSSL_LIB_CTX *provctx = PROV_LIBCTX_OF(ctx->provctx);
138
139     if (!ossl_prov_cipher_load_from_params(&ctx->cipher, params, provctx))
140         return 0;
141
142     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KEY)) != NULL)
143         if (!krb5kdf_set_membuf(&ctx->key, &ctx->key_len, p))
144             return 0;
145
146     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_CONSTANT))
147         != NULL)
148         if (!krb5kdf_set_membuf(&ctx->constant, &ctx->constant_len, p))
149             return 0;
150
151     return 1;
152 }
153
154 static const OSSL_PARAM *krb5kdf_settable_ctx_params(ossl_unused void *ctx,
155                                                      ossl_unused void *provctx)
156 {
157     static const OSSL_PARAM known_settable_ctx_params[] = {
158         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
159         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_CIPHER, NULL, 0),
160         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_KEY, NULL, 0),
161         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_CONSTANT, NULL, 0),
162         OSSL_PARAM_END
163     };
164     return known_settable_ctx_params;
165 }
166
167 static int krb5kdf_get_ctx_params(void *vctx, OSSL_PARAM params[])
168 {
169     KRB5KDF_CTX *ctx = (KRB5KDF_CTX *)vctx;
170     const EVP_CIPHER *cipher;
171     size_t len;
172     OSSL_PARAM *p;
173
174     cipher = ossl_prov_cipher_cipher(&ctx->cipher);
175     if (cipher)
176         len = EVP_CIPHER_key_length(cipher);
177     else
178         len = EVP_MAX_KEY_LENGTH;
179
180     if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL)
181         return OSSL_PARAM_set_size_t(p, len);
182     return -2;
183 }
184
185 static const OSSL_PARAM *krb5kdf_gettable_ctx_params(ossl_unused void *ctx,
186                                                      ossl_unused void *provctx)
187 {
188     static const OSSL_PARAM known_gettable_ctx_params[] = {
189         OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
190         OSSL_PARAM_END
191     };
192     return known_gettable_ctx_params;
193 }
194
195 const OSSL_DISPATCH ossl_kdf_krb5kdf_functions[] = {
196     { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))krb5kdf_new },
197     { OSSL_FUNC_KDF_FREECTX, (void(*)(void))krb5kdf_free },
198     { OSSL_FUNC_KDF_RESET, (void(*)(void))krb5kdf_reset },
199     { OSSL_FUNC_KDF_DERIVE, (void(*)(void))krb5kdf_derive },
200     { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
201       (void(*)(void))krb5kdf_settable_ctx_params },
202     { OSSL_FUNC_KDF_SET_CTX_PARAMS,
203       (void(*)(void))krb5kdf_set_ctx_params },
204     { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
205       (void(*)(void))krb5kdf_gettable_ctx_params },
206     { OSSL_FUNC_KDF_GET_CTX_PARAMS,
207       (void(*)(void))krb5kdf_get_ctx_params },
208     { 0, NULL }
209 };
210
211 #ifndef OPENSSL_NO_DES
212 /*
213  * DES3 is a special case, it requires a random-to-key function and its
214  * input truncated to 21 bytes of the 24 produced by the cipher.
215  * See RFC3961 6.3.1
216  */
217 static int fixup_des3_key(unsigned char *key)
218 {
219     unsigned char *cblock;
220     int i, j;
221
222     for (i = 2; i >= 0; i--) {
223         cblock = &key[i * 8];
224         memmove(cblock, &key[i * 7], 7);
225         cblock[7] = 0;
226         for (j = 0; j < 7; j++)
227             cblock[7] |= (cblock[j] & 1) << (j + 1);
228         DES_set_odd_parity((DES_cblock *)cblock);
229     }
230
231     /* fail if keys are such that triple des degrades to single des */
232     if (CRYPTO_memcmp(&key[0], &key[8], 8) == 0 ||
233         CRYPTO_memcmp(&key[8], &key[16], 8) == 0) {
234         return 0;
235     }
236
237     return 1;
238 }
239 #endif
240
241 /*
242  * N-fold(K) where blocksize is N, and constant_len is K
243  * Note: Here |= denotes concatenation
244  *
245  * L = lcm(N,K)
246  * R = L/K
247  *
248  * for r: 1 -> R
249  *   s |= constant rot 13*(r-1))
250  *
251  * block = 0
252  * for k: 1 -> K
253  *   block += s[N(k-1)..(N-1)k] (one's complement addition)
254  *
255  * Optimizing for space we compute:
256  * for each l in L-1 -> 0:
257  *   s[l] = (constant rot 13*(l/K))[l%k]
258  *   block[l % N] += s[l] (with carry)
259  * finally add carry if any
260  */
261 static void n_fold(unsigned char *block, unsigned int blocksize,
262                    const unsigned char *constant, size_t constant_len)
263 {
264     unsigned int tmp, gcd, remainder, lcm, carry;
265     int b, l;
266
267     if (constant_len == blocksize) {
268         memcpy(block, constant, constant_len);
269         return;
270     }
271
272     /* Least Common Multiple of lengths: LCM(a,b)*/
273     gcd = blocksize;
274     remainder = constant_len;
275     /* Calculate Great Common Divisor first GCD(a,b) */
276     while (remainder != 0) {
277         tmp = gcd % remainder;
278         gcd = remainder;
279         remainder = tmp;
280     }
281     /* resulting a is the GCD, LCM(a,b) = |a*b|/GCD(a,b) */
282     lcm = blocksize * constant_len / gcd;
283
284     /* now spread out the bits */
285     memset(block, 0, blocksize);
286
287     /* last to first to be able to bring carry forward */
288     carry = 0;
289     for (l = lcm - 1; l >= 0; l--) {
290         unsigned int rotbits, rshift, rbyte;
291
292         /* destination byte in block is l % N */
293         b = l % blocksize;
294         /* Our virtual s buffer is R = L/K long (K = constant_len) */
295         /* So we rotate backwards from R-1 to 0 (none) rotations */
296         rotbits = 13 * (l / constant_len);
297         /* find the byte on s where rotbits falls onto */
298         rbyte = l - (rotbits / 8);
299         /* calculate how much shift on that byte */
300         rshift = rotbits & 0x07;
301         /* rbyte % constant_len gives us the unrotated byte in the
302          * constant buffer, get also the previous byte then
303          * appropriately shift them to get the rotated byte we need */
304         tmp = (constant[(rbyte-1) % constant_len] << (8 - rshift)
305                | constant[rbyte % constant_len] >> rshift)
306               & 0xff;
307         /* add with carry to any value placed by previous passes */
308         tmp += carry + block[b];
309         block[b] = tmp & 0xff;
310         /* save any carry that may be left */
311         carry = tmp >> 8;
312     }
313
314     /* if any carry is left at the end, add it through the number */
315     for (b = blocksize - 1; b >= 0 && carry != 0; b--) {
316         carry += block[b];
317         block[b] = carry & 0xff;
318         carry >>= 8;
319     }
320 }
321
322 static int cipher_init(EVP_CIPHER_CTX *ctx,
323                        const EVP_CIPHER *cipher, ENGINE *engine,
324                        const unsigned char *key, size_t key_len)
325 {
326     int klen, ret;
327
328     ret = EVP_EncryptInit_ex(ctx, cipher, engine, key, NULL);
329     if (!ret)
330         goto out;
331     /* set the key len for the odd variable key len cipher */
332     klen = EVP_CIPHER_CTX_key_length(ctx);
333     if (key_len != (size_t)klen) {
334         ret = EVP_CIPHER_CTX_set_key_length(ctx, key_len);
335         if (!ret)
336             goto out;
337     }
338     /* we never want padding, either the length requested is a multiple of
339      * the cipher block size or we are passed a cipher that can cope with
340      * partial blocks via techniques like cipher text stealing */
341     ret = EVP_CIPHER_CTX_set_padding(ctx, 0);
342     if (!ret)
343         goto out;
344
345 out:
346     return ret;
347 }
348
349 static int KRB5KDF(const EVP_CIPHER *cipher, ENGINE *engine,
350                    const unsigned char *key, size_t key_len,
351                    const unsigned char *constant, size_t constant_len,
352                    unsigned char *okey, size_t okey_len)
353 {
354     EVP_CIPHER_CTX *ctx = NULL;
355     unsigned char block[EVP_MAX_BLOCK_LENGTH * 2];
356     unsigned char *plainblock, *cipherblock;
357     size_t blocksize;
358     size_t cipherlen;
359     size_t osize;
360 #ifndef OPENSSL_NO_DES
361     int des3_no_fixup = 0;
362 #endif
363     int ret;
364
365     if (key_len != okey_len) {
366 #ifndef OPENSSL_NO_DES
367         /* special case for 3des, where the caller may be requesting
368          * the random raw key, instead of the fixed up key  */
369         if (EVP_CIPHER_nid(cipher) == NID_des_ede3_cbc &&
370             key_len == 24 && okey_len == 21) {
371                 des3_no_fixup = 1;
372         } else {
373 #endif
374             ERR_raise(ERR_LIB_PROV, PROV_R_WRONG_OUTPUT_BUFFER_SIZE);
375             return 0;
376 #ifndef OPENSSL_NO_DES
377         }
378 #endif
379     }
380
381     ctx = EVP_CIPHER_CTX_new();
382     if (ctx == NULL)
383         return 0;
384
385     ret = cipher_init(ctx, cipher, engine, key, key_len);
386     if (!ret)
387         goto out;
388
389     /* Initialize input block */
390     blocksize = EVP_CIPHER_CTX_block_size(ctx);
391
392     if (constant_len > blocksize) {
393         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CONSTANT_LENGTH);
394         ret = 0;
395         goto out;
396     }
397
398     n_fold(block, blocksize, constant, constant_len);
399     plainblock = block;
400     cipherblock = block + EVP_MAX_BLOCK_LENGTH;
401
402     for (osize = 0; osize < okey_len; osize += cipherlen) {
403         int olen;
404
405         ret = EVP_EncryptUpdate(ctx, cipherblock, &olen,
406                                 plainblock, blocksize);
407         if (!ret)
408             goto out;
409         cipherlen = olen;
410         ret = EVP_EncryptFinal_ex(ctx, cipherblock, &olen);
411         if (!ret)
412             goto out;
413         if (olen != 0) {
414             ERR_raise(ERR_LIB_PROV, PROV_R_WRONG_FINAL_BLOCK_LENGTH);
415             ret = 0;
416             goto out;
417         }
418
419         /* write cipherblock out */
420         if (cipherlen > okey_len - osize)
421             cipherlen = okey_len - osize;
422         memcpy(okey + osize, cipherblock, cipherlen);
423
424         if (okey_len > osize + cipherlen) {
425             /* we need to reinitialize cipher context per spec */
426             ret = EVP_CIPHER_CTX_reset(ctx);
427             if (!ret)
428                 goto out;
429             ret = cipher_init(ctx, cipher, engine, key, key_len);
430             if (!ret)
431                 goto out;
432
433             /* also swap block offsets so last ciphertext becomes new
434              * plaintext */
435             plainblock = cipherblock;
436             if (cipherblock == block) {
437                 cipherblock += EVP_MAX_BLOCK_LENGTH;
438             } else {
439                 cipherblock = block;
440             }
441         }
442     }
443
444 #ifndef OPENSSL_NO_DES
445     if (EVP_CIPHER_nid(cipher) == NID_des_ede3_cbc && !des3_no_fixup) {
446         ret = fixup_des3_key(okey);
447         if (!ret) {
448             ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_GENERATE_KEY);
449             goto out;
450         }
451     }
452 #endif
453
454     ret = 1;
455
456 out:
457     EVP_CIPHER_CTX_free(ctx);
458     OPENSSL_cleanse(block, EVP_MAX_BLOCK_LENGTH * 2);
459     return ret;
460 }
461