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 
krb5kdf_new(void * provctx)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 
krb5kdf_free(void * vctx)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 
krb5kdf_reset(void * vctx)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 
krb5kdf_set_membuf(unsigned char ** dst,size_t * dst_len,const OSSL_PARAM * p)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 
krb5kdf_derive(void * vctx,unsigned char * key,size_t keylen,const OSSL_PARAM params[])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 
krb5kdf_set_ctx_params(void * vctx,const OSSL_PARAM params[])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 (params == NULL)
140         return 1;
141 
142     if (!ossl_prov_cipher_load_from_params(&ctx->cipher, params, provctx))
143         return 0;
144 
145     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_KEY)) != NULL)
146         if (!krb5kdf_set_membuf(&ctx->key, &ctx->key_len, p))
147             return 0;
148 
149     if ((p = OSSL_PARAM_locate_const(params, OSSL_KDF_PARAM_CONSTANT))
150         != NULL)
151         if (!krb5kdf_set_membuf(&ctx->constant, &ctx->constant_len, p))
152             return 0;
153 
154     return 1;
155 }
156 
krb5kdf_settable_ctx_params(ossl_unused void * ctx,ossl_unused void * provctx)157 static const OSSL_PARAM *krb5kdf_settable_ctx_params(ossl_unused void *ctx,
158                                                      ossl_unused void *provctx)
159 {
160     static const OSSL_PARAM known_settable_ctx_params[] = {
161         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_PROPERTIES, NULL, 0),
162         OSSL_PARAM_utf8_string(OSSL_KDF_PARAM_CIPHER, NULL, 0),
163         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_KEY, NULL, 0),
164         OSSL_PARAM_octet_string(OSSL_KDF_PARAM_CONSTANT, NULL, 0),
165         OSSL_PARAM_END
166     };
167     return known_settable_ctx_params;
168 }
169 
krb5kdf_get_ctx_params(void * vctx,OSSL_PARAM params[])170 static int krb5kdf_get_ctx_params(void *vctx, OSSL_PARAM params[])
171 {
172     KRB5KDF_CTX *ctx = (KRB5KDF_CTX *)vctx;
173     const EVP_CIPHER *cipher;
174     size_t len;
175     OSSL_PARAM *p;
176 
177     cipher = ossl_prov_cipher_cipher(&ctx->cipher);
178     if (cipher)
179         len = EVP_CIPHER_get_key_length(cipher);
180     else
181         len = EVP_MAX_KEY_LENGTH;
182 
183     if ((p = OSSL_PARAM_locate(params, OSSL_KDF_PARAM_SIZE)) != NULL)
184         return OSSL_PARAM_set_size_t(p, len);
185     return -2;
186 }
187 
krb5kdf_gettable_ctx_params(ossl_unused void * ctx,ossl_unused void * provctx)188 static const OSSL_PARAM *krb5kdf_gettable_ctx_params(ossl_unused void *ctx,
189                                                      ossl_unused void *provctx)
190 {
191     static const OSSL_PARAM known_gettable_ctx_params[] = {
192         OSSL_PARAM_size_t(OSSL_KDF_PARAM_SIZE, NULL),
193         OSSL_PARAM_END
194     };
195     return known_gettable_ctx_params;
196 }
197 
198 const OSSL_DISPATCH ossl_kdf_krb5kdf_functions[] = {
199     { OSSL_FUNC_KDF_NEWCTX, (void(*)(void))krb5kdf_new },
200     { OSSL_FUNC_KDF_FREECTX, (void(*)(void))krb5kdf_free },
201     { OSSL_FUNC_KDF_RESET, (void(*)(void))krb5kdf_reset },
202     { OSSL_FUNC_KDF_DERIVE, (void(*)(void))krb5kdf_derive },
203     { OSSL_FUNC_KDF_SETTABLE_CTX_PARAMS,
204       (void(*)(void))krb5kdf_settable_ctx_params },
205     { OSSL_FUNC_KDF_SET_CTX_PARAMS,
206       (void(*)(void))krb5kdf_set_ctx_params },
207     { OSSL_FUNC_KDF_GETTABLE_CTX_PARAMS,
208       (void(*)(void))krb5kdf_gettable_ctx_params },
209     { OSSL_FUNC_KDF_GET_CTX_PARAMS,
210       (void(*)(void))krb5kdf_get_ctx_params },
211     { 0, NULL }
212 };
213 
214 #ifndef OPENSSL_NO_DES
215 /*
216  * DES3 is a special case, it requires a random-to-key function and its
217  * input truncated to 21 bytes of the 24 produced by the cipher.
218  * See RFC3961 6.3.1
219  */
fixup_des3_key(unsigned char * key)220 static int fixup_des3_key(unsigned char *key)
221 {
222     unsigned char *cblock;
223     int i, j;
224 
225     for (i = 2; i >= 0; i--) {
226         cblock = &key[i * 8];
227         memmove(cblock, &key[i * 7], 7);
228         cblock[7] = 0;
229         for (j = 0; j < 7; j++)
230             cblock[7] |= (cblock[j] & 1) << (j + 1);
231         DES_set_odd_parity((DES_cblock *)cblock);
232     }
233 
234     /* fail if keys are such that triple des degrades to single des */
235     if (CRYPTO_memcmp(&key[0], &key[8], 8) == 0 ||
236         CRYPTO_memcmp(&key[8], &key[16], 8) == 0) {
237         return 0;
238     }
239 
240     return 1;
241 }
242 #endif
243 
244 /*
245  * N-fold(K) where blocksize is N, and constant_len is K
246  * Note: Here |= denotes concatenation
247  *
248  * L = lcm(N,K)
249  * R = L/K
250  *
251  * for r: 1 -> R
252  *   s |= constant rot 13*(r-1))
253  *
254  * block = 0
255  * for k: 1 -> K
256  *   block += s[N(k-1)..(N-1)k] (one's complement addition)
257  *
258  * Optimizing for space we compute:
259  * for each l in L-1 -> 0:
260  *   s[l] = (constant rot 13*(l/K))[l%k]
261  *   block[l % N] += s[l] (with carry)
262  * finally add carry if any
263  */
n_fold(unsigned char * block,unsigned int blocksize,const unsigned char * constant,size_t constant_len)264 static void n_fold(unsigned char *block, unsigned int blocksize,
265                    const unsigned char *constant, size_t constant_len)
266 {
267     unsigned int tmp, gcd, remainder, lcm, carry;
268     int b, l;
269 
270     if (constant_len == blocksize) {
271         memcpy(block, constant, constant_len);
272         return;
273     }
274 
275     /* Least Common Multiple of lengths: LCM(a,b)*/
276     gcd = blocksize;
277     remainder = constant_len;
278     /* Calculate Great Common Divisor first GCD(a,b) */
279     while (remainder != 0) {
280         tmp = gcd % remainder;
281         gcd = remainder;
282         remainder = tmp;
283     }
284     /* resulting a is the GCD, LCM(a,b) = |a*b|/GCD(a,b) */
285     lcm = blocksize * constant_len / gcd;
286 
287     /* now spread out the bits */
288     memset(block, 0, blocksize);
289 
290     /* last to first to be able to bring carry forward */
291     carry = 0;
292     for (l = lcm - 1; l >= 0; l--) {
293         unsigned int rotbits, rshift, rbyte;
294 
295         /* destination byte in block is l % N */
296         b = l % blocksize;
297         /* Our virtual s buffer is R = L/K long (K = constant_len) */
298         /* So we rotate backwards from R-1 to 0 (none) rotations */
299         rotbits = 13 * (l / constant_len);
300         /* find the byte on s where rotbits falls onto */
301         rbyte = l - (rotbits / 8);
302         /* calculate how much shift on that byte */
303         rshift = rotbits & 0x07;
304         /* rbyte % constant_len gives us the unrotated byte in the
305          * constant buffer, get also the previous byte then
306          * appropriately shift them to get the rotated byte we need */
307         tmp = (constant[(rbyte-1) % constant_len] << (8 - rshift)
308                | constant[rbyte % constant_len] >> rshift)
309               & 0xff;
310         /* add with carry to any value placed by previous passes */
311         tmp += carry + block[b];
312         block[b] = tmp & 0xff;
313         /* save any carry that may be left */
314         carry = tmp >> 8;
315     }
316 
317     /* if any carry is left at the end, add it through the number */
318     for (b = blocksize - 1; b >= 0 && carry != 0; b--) {
319         carry += block[b];
320         block[b] = carry & 0xff;
321         carry >>= 8;
322     }
323 }
324 
cipher_init(EVP_CIPHER_CTX * ctx,const EVP_CIPHER * cipher,ENGINE * engine,const unsigned char * key,size_t key_len)325 static int cipher_init(EVP_CIPHER_CTX *ctx,
326                        const EVP_CIPHER *cipher, ENGINE *engine,
327                        const unsigned char *key, size_t key_len)
328 {
329     int klen, ret;
330 
331     ret = EVP_EncryptInit_ex(ctx, cipher, engine, key, NULL);
332     if (!ret)
333         goto out;
334     /* set the key len for the odd variable key len cipher */
335     klen = EVP_CIPHER_CTX_get_key_length(ctx);
336     if (key_len != (size_t)klen) {
337         ret = EVP_CIPHER_CTX_set_key_length(ctx, key_len);
338         if (!ret)
339             goto out;
340     }
341     /* we never want padding, either the length requested is a multiple of
342      * the cipher block size or we are passed a cipher that can cope with
343      * partial blocks via techniques like cipher text stealing */
344     ret = EVP_CIPHER_CTX_set_padding(ctx, 0);
345     if (!ret)
346         goto out;
347 
348 out:
349     return ret;
350 }
351 
KRB5KDF(const EVP_CIPHER * cipher,ENGINE * engine,const unsigned char * key,size_t key_len,const unsigned char * constant,size_t constant_len,unsigned char * okey,size_t okey_len)352 static int KRB5KDF(const EVP_CIPHER *cipher, ENGINE *engine,
353                    const unsigned char *key, size_t key_len,
354                    const unsigned char *constant, size_t constant_len,
355                    unsigned char *okey, size_t okey_len)
356 {
357     EVP_CIPHER_CTX *ctx = NULL;
358     unsigned char block[EVP_MAX_BLOCK_LENGTH * 2];
359     unsigned char *plainblock, *cipherblock;
360     size_t blocksize;
361     size_t cipherlen;
362     size_t osize;
363 #ifndef OPENSSL_NO_DES
364     int des3_no_fixup = 0;
365 #endif
366     int ret;
367 
368     if (key_len != okey_len) {
369 #ifndef OPENSSL_NO_DES
370         /* special case for 3des, where the caller may be requesting
371          * the random raw key, instead of the fixed up key  */
372         if (EVP_CIPHER_get_nid(cipher) == NID_des_ede3_cbc &&
373             key_len == 24 && okey_len == 21) {
374                 des3_no_fixup = 1;
375         } else {
376 #endif
377             ERR_raise(ERR_LIB_PROV, PROV_R_WRONG_OUTPUT_BUFFER_SIZE);
378             return 0;
379 #ifndef OPENSSL_NO_DES
380         }
381 #endif
382     }
383 
384     ctx = EVP_CIPHER_CTX_new();
385     if (ctx == NULL)
386         return 0;
387 
388     ret = cipher_init(ctx, cipher, engine, key, key_len);
389     if (!ret)
390         goto out;
391 
392     /* Initialize input block */
393     blocksize = EVP_CIPHER_CTX_get_block_size(ctx);
394 
395     if (constant_len > blocksize) {
396         ERR_raise(ERR_LIB_PROV, PROV_R_INVALID_CONSTANT_LENGTH);
397         ret = 0;
398         goto out;
399     }
400 
401     n_fold(block, blocksize, constant, constant_len);
402     plainblock = block;
403     cipherblock = block + EVP_MAX_BLOCK_LENGTH;
404 
405     for (osize = 0; osize < okey_len; osize += cipherlen) {
406         int olen;
407 
408         ret = EVP_EncryptUpdate(ctx, cipherblock, &olen,
409                                 plainblock, blocksize);
410         if (!ret)
411             goto out;
412         cipherlen = olen;
413         ret = EVP_EncryptFinal_ex(ctx, cipherblock, &olen);
414         if (!ret)
415             goto out;
416         if (olen != 0) {
417             ERR_raise(ERR_LIB_PROV, PROV_R_WRONG_FINAL_BLOCK_LENGTH);
418             ret = 0;
419             goto out;
420         }
421 
422         /* write cipherblock out */
423         if (cipherlen > okey_len - osize)
424             cipherlen = okey_len - osize;
425         memcpy(okey + osize, cipherblock, cipherlen);
426 
427         if (okey_len > osize + cipherlen) {
428             /* we need to reinitialize cipher context per spec */
429             ret = EVP_CIPHER_CTX_reset(ctx);
430             if (!ret)
431                 goto out;
432             ret = cipher_init(ctx, cipher, engine, key, key_len);
433             if (!ret)
434                 goto out;
435 
436             /* also swap block offsets so last ciphertext becomes new
437              * plaintext */
438             plainblock = cipherblock;
439             if (cipherblock == block) {
440                 cipherblock += EVP_MAX_BLOCK_LENGTH;
441             } else {
442                 cipherblock = block;
443             }
444         }
445     }
446 
447 #ifndef OPENSSL_NO_DES
448     if (EVP_CIPHER_get_nid(cipher) == NID_des_ede3_cbc && !des3_no_fixup) {
449         ret = fixup_des3_key(okey);
450         if (!ret) {
451             ERR_raise(ERR_LIB_PROV, PROV_R_FAILED_TO_GENERATE_KEY);
452             goto out;
453         }
454     }
455 #endif
456 
457     ret = 1;
458 
459 out:
460     EVP_CIPHER_CTX_free(ctx);
461     OPENSSL_cleanse(block, EVP_MAX_BLOCK_LENGTH * 2);
462     return ret;
463 }
464 
465