Coverage Report

Created: 2025-06-13 06:58

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