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