Coverage Report

Created: 2026-10-31 07:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl-heapmath/wolfcrypt/src/kdf.c
Line
Count
Source
1
/* kdf.c
2
 *
3
 * Copyright (C) 2006-2026 wolfSSL Inc.
4
 *
5
 * This file is part of wolfSSL.
6
 *
7
 * wolfSSL is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * wolfSSL is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program; if not, write to the Free Software
19
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
20
 */
21
22
#define WC_FIPS_LL_CRYPTO
23
#define _WC_BUILDING_KDF_C
24
25
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
26
27
#ifndef NO_KDF
28
29
#if FIPS_VERSION3_GE(5,0,0)
30
    #if defined(USE_WINDOWS_API) && defined(_MSC_VER)
31
        #pragma code_seg(".fipsA$h")
32
        #pragma const_seg(".fipsB$h")
33
    #endif
34
#endif
35
36
37
#ifdef NO_INLINE
38
    #include <wolfssl/wolfcrypt/misc.h>
39
#else
40
    #define WOLFSSL_MISC_INCLUDED
41
    #include <wolfcrypt/src/misc.c>
42
#endif
43
44
#include <wolfssl/wolfcrypt/hmac.h>
45
#include <wolfssl/wolfcrypt/kdf.h>
46
#if defined(WC_SRTP_KDF) || defined(HAVE_CMAC_KDF)
47
    #include <wolfssl/wolfcrypt/aes.h>
48
#endif
49
#ifdef WOLF_CRYPTO_CB
50
    #include <wolfssl/wolfcrypt/cryptocb.h>
51
#endif
52
53
#if FIPS_VERSION3_GE(6,0,0)
54
    const unsigned int wolfCrypt_FIPS_kdf_ro_sanity[2] =
55
                                                     { 0x1a2b3c4d, 0x00000009 };
56
    int wolfCrypt_FIPS_KDF_sanity(void)
57
    {
58
        return 0;
59
    }
60
#endif
61
62
#if defined(WOLFSSL_HAVE_PRF) && !defined(NO_HMAC)
63
64
#ifdef WOLFSSL_SHA512
65
0
    #define P_HASH_MAX_SIZE WC_SHA512_DIGEST_SIZE
66
#elif defined(WOLFSSL_SHA384)
67
    #define P_HASH_MAX_SIZE WC_SHA384_DIGEST_SIZE
68
#else
69
    #define P_HASH_MAX_SIZE WC_SHA256_DIGEST_SIZE
70
#endif
71
72
/* Pseudo Random Function for MD5, SHA-1, SHA-256, SHA-384, or SHA-512 */
73
int wc_PRF(byte* result, word32 resLen, const byte* secret,
74
                  word32 secLen, const byte* seed, word32 seedLen,
75
                  int hash_type, void* heap, int devId)
76
0
{
77
0
    word32 len = P_HASH_MAX_SIZE;
78
0
    word32 times;
79
0
    word32 lastLen;
80
0
    word32 lastTime;
81
0
    int    ret = 0;
82
0
#ifdef WOLFSSL_SMALL_STACK
83
0
    byte*  current;
84
0
    Hmac*  hmac;
85
#else
86
    byte   current[P_HASH_MAX_SIZE];   /* max size */
87
    Hmac   hmac[1];
88
#endif
89
90
0
    if ((result == NULL && resLen != 0) || (secret == NULL && secLen != 0) ||
91
0
       (seed == NULL && seedLen != 0))
92
0
        return BAD_FUNC_ARG;
93
94
0
    switch (hash_type) {
95
0
    #ifndef NO_MD5
96
0
        case md5_mac:
97
0
            hash_type = WC_MD5;
98
0
            len  = WC_MD5_DIGEST_SIZE;
99
0
        break;
100
0
    #endif
101
102
0
    #ifndef NO_SHA256
103
0
        case sha256_mac:
104
0
            hash_type = WC_SHA256;
105
0
            len  = WC_SHA256_DIGEST_SIZE;
106
0
        break;
107
0
    #endif
108
109
0
    #ifdef WOLFSSL_SHA384
110
0
        case sha384_mac:
111
0
            hash_type = WC_SHA384;
112
0
            len  = WC_SHA384_DIGEST_SIZE;
113
0
        break;
114
0
    #endif
115
116
0
    #ifdef WOLFSSL_SHA512
117
0
        case sha512_mac:
118
0
            hash_type = WC_SHA512;
119
0
            len  = WC_SHA512_DIGEST_SIZE;
120
0
        break;
121
0
    #endif
122
123
0
    #ifdef WOLFSSL_SM3
124
0
        case sm3_mac:
125
0
            hash_type = WC_SM3;
126
0
            len  = WC_SM3_DIGEST_SIZE;
127
0
        break;
128
0
    #endif
129
130
0
    #ifndef NO_SHA
131
0
        case sha_mac:
132
0
            hash_type = WC_SHA;
133
0
            len  = WC_SHA_DIGEST_SIZE;
134
0
        break;
135
0
    #endif
136
0
        default:
137
0
            return HASH_TYPE_E;
138
0
    }
139
140
0
    times   = resLen / len;
141
0
    lastLen = resLen % len;
142
143
0
    if (lastLen)
144
0
        times += 1;
145
146
    /* times == 0 if resLen == 0, but times == 0 abides clang static analyzer
147
       while resLen == 0 doesn't */
148
0
    if (times == 0)
149
0
        return BAD_FUNC_ARG;
150
151
0
    lastTime = times - 1;
152
153
0
#ifdef WOLFSSL_SMALL_STACK
154
0
    current = (byte*)XMALLOC(P_HASH_MAX_SIZE, heap, DYNAMIC_TYPE_DIGEST);
155
0
    hmac    = (Hmac*)XMALLOC(sizeof(Hmac),    heap, DYNAMIC_TYPE_HMAC);
156
0
    if (current == NULL || hmac == NULL) {
157
0
        XFREE(current, heap, DYNAMIC_TYPE_DIGEST);
158
0
        XFREE(hmac, heap, DYNAMIC_TYPE_HMAC);
159
0
        return MEMORY_E;
160
0
    }
161
0
#endif
162
#ifdef WOLFSSL_CHECK_MEM_ZERO
163
    XMEMSET(current, 0xff, P_HASH_MAX_SIZE);
164
    wc_MemZero_Add("wc_PRF current", current, P_HASH_MAX_SIZE);
165
    wc_MemZero_Add("wc_PRF hmac", hmac, sizeof(Hmac));
166
#endif
167
168
0
    ret = wc_HmacInit(hmac, heap, devId);
169
0
    if (ret == 0) {
170
0
        ret = wc_HmacSetKey(hmac, hash_type, secret, secLen);
171
0
        if (ret == 0)
172
0
            ret = wc_HmacUpdate(hmac, seed, seedLen); /* A0 = seed */
173
0
        if (ret == 0)
174
0
            ret = wc_HmacFinal(hmac, current);        /* A1 */
175
0
        if (ret == 0) {
176
0
            word32 i;
177
0
            word32 idx = 0;
178
179
0
            for (i = 0; i < times; i++) {
180
0
                ret = wc_HmacUpdate(hmac, current, len);
181
0
                if (ret != 0)
182
0
                    break;
183
0
                ret = wc_HmacUpdate(hmac, seed, seedLen);
184
0
                if (ret != 0)
185
0
                    break;
186
0
                if ((i != lastTime) || !lastLen) {
187
0
                    ret = wc_HmacFinal(hmac, &result[idx]);
188
0
                    if (ret != 0)
189
0
                        break;
190
0
                    idx += len;
191
192
0
                    ret = wc_HmacUpdate(hmac, current, len);
193
0
                    if (ret != 0)
194
0
                        break;
195
0
                    ret = wc_HmacFinal(hmac, current);
196
0
                    if (ret != 0)
197
0
                        break;
198
0
                }
199
0
                else {
200
0
                    ret = wc_HmacFinal(hmac, current);
201
0
                    if (ret != 0)
202
0
                        break;
203
0
                    XMEMCPY(&result[idx], current,
204
0
                                             min(lastLen, P_HASH_MAX_SIZE));
205
0
                }
206
0
            }
207
0
        }
208
0
        wc_HmacFree(hmac);
209
0
    }
210
0
    if (ret != 0) {
211
        /* Partial PRF output is not released (ISO/IEC 19790 7.9.7). */
212
0
        ForceZero(result, resLen);
213
0
    }
214
215
0
    ForceZero(current, P_HASH_MAX_SIZE);
216
0
    ForceZero(hmac,    sizeof(Hmac));
217
218
#if defined(WOLFSSL_CHECK_MEM_ZERO)
219
    wc_MemZero_Check(current, P_HASH_MAX_SIZE);
220
    wc_MemZero_Check(hmac,    sizeof(Hmac));
221
#endif
222
223
0
    WC_FREE_VAR_EX(current, heap, DYNAMIC_TYPE_DIGEST);
224
0
    WC_FREE_VAR_EX(hmac, heap, DYNAMIC_TYPE_HMAC);
225
226
0
    return ret;
227
0
}
228
#undef P_HASH_MAX_SIZE
229
230
/* compute PRF (pseudo random function) using SHA1 and MD5 for TLSv1 */
231
int wc_PRF_TLSv1(byte* digest, word32 digLen, const byte* secret,
232
           word32 secLen, const byte* label, word32 labLen,
233
           const byte* seed, word32 seedLen, void* heap, int devId)
234
86
{
235
86
    int         ret  = 0;
236
86
    word32      half = (secLen + 1) / 2;
237
86
    const byte* md5_half;
238
86
    const byte* sha_half;
239
86
    byte*      md5_result;
240
86
    WC_DECLARE_VAR(sha_result, byte, MAX_PRF_DIG, heap); /* digLen is real size */
241
86
    WC_DECLARE_VAR(labelSeed, byte, MAX_PRF_LABSEED, heap);
242
243
86
    if ((digest == NULL && digLen  != 0) ||
244
86
        (secret == NULL && secLen  != 0) ||
245
86
        (label  == NULL && labLen  != 0) ||
246
86
        (seed   == NULL && seedLen != 0)) {
247
0
        return BAD_FUNC_ARG;
248
0
    }
249
250
    /* labLen + seedLen is checked with subtraction to avoid word32 wraparound
251
     * (the labLen bound first ensures MAX_PRF_LABSEED - labLen cannot
252
     * underflow). */
253
86
    if (half > MAX_PRF_HALF ||
254
86
        labLen > MAX_PRF_LABSEED || seedLen > (MAX_PRF_LABSEED - labLen) ||
255
86
        digLen > MAX_PRF_DIG)
256
0
    {
257
0
        return BUFFER_E;
258
0
    }
259
260
86
    WC_ALLOC_VAR_EX(sha_result, byte, MAX_PRF_DIG, heap, DYNAMIC_TYPE_DIGEST,
261
86
                    return MEMORY_E);
262
86
    WC_ALLOC_VAR_EX(labelSeed, byte, MAX_PRF_LABSEED, heap, DYNAMIC_TYPE_DIGEST,
263
86
                    { WC_FREE_VAR_EX(sha_result, heap, DYNAMIC_TYPE_DIGEST);
264
86
                      return MEMORY_E; });
265
266
86
    md5_half = secret;
267
86
    sha_half = secret + half - secLen % 2;
268
86
    md5_result = digest;
269
270
86
    if (labLen != 0)
271
86
        XMEMCPY(labelSeed, label, labLen);
272
86
    if (seedLen != 0)
273
86
        XMEMCPY(labelSeed + labLen, seed, seedLen);
274
275
86
    if ((ret = wc_PRF(md5_result, digLen, md5_half, half, labelSeed,
276
86
                                labLen + seedLen, md5_mac, heap, devId)) == 0) {
277
86
        if ((ret = wc_PRF(sha_result, digLen, sha_half, half, labelSeed,
278
86
                                labLen + seedLen, sha_mac, heap, devId)) == 0) {
279
        #ifdef WOLFSSL_CHECK_MEM_ZERO
280
            wc_MemZero_Add("wc_PRF_TLSv1 sha_result", sha_result, digLen);
281
        #endif
282
            /* calculate XOR for TLSv1 PRF */
283
            /* md5 result is placed directly in digest */
284
86
            xorbuf(digest, sha_result, digLen);
285
86
            ForceZero(sha_result, digLen);
286
86
        }
287
86
    }
288
289
#if defined(WOLFSSL_CHECK_MEM_ZERO)
290
    wc_MemZero_Check(sha_result, MAX_PRF_DIG);
291
#endif
292
293
86
    WC_FREE_VAR_EX(sha_result, heap, DYNAMIC_TYPE_DIGEST);
294
86
    WC_FREE_VAR_EX(labelSeed, heap, DYNAMIC_TYPE_DIGEST);
295
296
86
    return ret;
297
86
}
298
299
/* Wrapper for TLS 1.2 and TLSv1 cases to calculate PRF */
300
/* In TLS 1.2 case call straight thru to wc_PRF */
301
int wc_PRF_TLS(byte* digest, word32 digLen, const byte* secret, word32 secLen,
302
            const byte* label, word32 labLen, const byte* seed, word32 seedLen,
303
            int useAtLeastSha256, int hash_type, void* heap, int devId)
304
1.94k
{
305
1.94k
    int ret = 0;
306
307
1.94k
    if ((digest == NULL && digLen  != 0) ||
308
1.94k
        (secret == NULL && secLen  != 0) ||
309
1.94k
        (label  == NULL && labLen  != 0) ||
310
1.94k
        (seed   == NULL && seedLen != 0)) {
311
0
        return BAD_FUNC_ARG;
312
0
    }
313
314
#ifdef WOLFSSL_DEBUG_TLS
315
    WOLFSSL_MSG("  secret");
316
    WOLFSSL_BUFFER(secret, secLen);
317
    WOLFSSL_MSG("  label");
318
    WOLFSSL_BUFFER(label, labLen);
319
    WOLFSSL_MSG("  seed");
320
    WOLFSSL_BUFFER(seed, seedLen);
321
#endif
322
323
1.94k
    if (useAtLeastSha256) {
324
1.86k
        WC_DECLARE_VAR(labelSeed, byte, MAX_PRF_LABSEED, 0);
325
326
        /* Checked with subtraction to avoid word32 wraparound of
327
         * labLen + seedLen. */
328
1.86k
        if (labLen > MAX_PRF_LABSEED || seedLen > (MAX_PRF_LABSEED - labLen)) {
329
0
            return BUFFER_E;
330
0
        }
331
332
1.86k
        WC_ALLOC_VAR_EX(labelSeed, byte, MAX_PRF_LABSEED, heap,
333
1.86k
            DYNAMIC_TYPE_DIGEST, return MEMORY_E);
334
335
1.86k
        if (labLen != 0)
336
1.86k
            XMEMCPY(labelSeed, label, labLen);
337
1.86k
        if (seedLen != 0)
338
1.86k
            XMEMCPY(labelSeed + labLen, seed, seedLen);
339
340
        /* If a cipher suite wants an algorithm better than sha256, it
341
         * should use better. */
342
1.86k
        if (hash_type < sha256_mac || hash_type == blake2b_mac) {
343
175
            hash_type = sha256_mac;
344
175
        }
345
        /* compute PRF for MD5, SHA-1, SHA-256, or SHA-384 for TLSv1.2 PRF */
346
1.86k
        ret = wc_PRF(digest, digLen, secret, secLen, labelSeed,
347
1.86k
                     labLen + seedLen, hash_type, heap, devId);
348
349
1.86k
        WC_FREE_VAR_EX(labelSeed, heap, DYNAMIC_TYPE_DIGEST);
350
1.86k
    }
351
86
    else {
352
#ifndef NO_OLD_TLS
353
        /* compute TLSv1 PRF (pseudo random function using HMAC) */
354
        ret = wc_PRF_TLSv1(digest, digLen, secret, secLen, label, labLen, seed,
355
                          seedLen, heap, devId);
356
#else
357
86
        ret = BAD_FUNC_ARG;
358
86
#endif
359
86
    }
360
361
#ifdef WOLFSSL_DEBUG_TLS
362
    WOLFSSL_MSG("  digest");
363
    WOLFSSL_BUFFER(digest, digLen);
364
    WOLFSSL_MSG_EX("hash_type %d", hash_type);
365
#endif
366
367
1.94k
    return ret;
368
1.94k
}
369
#endif /* WOLFSSL_HAVE_PRF && !NO_HMAC */
370
371
372
#if defined(HAVE_HKDF) && !defined(NO_HMAC)
373
374
    /* Extract data using HMAC, salt and input.
375
     * RFC 5869 - HMAC-based Extract-and-Expand Key Derivation Function (HKDF)
376
     */
377
    int wc_Tls13_HKDF_Extract_ex(byte* prk, const byte* salt, word32 saltLen,
378
        byte* ikm, word32 ikmLen, int digest, void* heap, int devId)
379
0
    {
380
0
        byte   tmp[WC_MAX_DIGEST_SIZE]; /* localIkm helper */
381
0
        const  byte* localIkm;  /* either points to user input or tmp */
382
0
        int    ret;
383
0
        word32 len = 0;
384
385
0
        if (prk == NULL || (ikm == NULL && ikmLen > 0)) {
386
0
            return BAD_FUNC_ARG;
387
0
        }
388
389
0
        switch (digest) {
390
0
            #ifndef NO_SHA256
391
0
            case WC_SHA256:
392
0
                len = WC_SHA256_DIGEST_SIZE;
393
0
                break;
394
0
            #endif
395
396
0
            #ifdef WOLFSSL_SHA384
397
0
            case WC_SHA384:
398
0
                len = WC_SHA384_DIGEST_SIZE;
399
0
                break;
400
0
            #endif
401
402
            #ifdef WOLFSSL_TLS13_SHA512
403
            case WC_SHA512:
404
                len = WC_SHA512_DIGEST_SIZE;
405
                break;
406
            #endif
407
408
0
            #ifdef WOLFSSL_SM3
409
0
            case WC_SM3:
410
0
                len = WC_SM3_DIGEST_SIZE;
411
0
                break;
412
0
            #endif
413
414
0
            default:
415
0
                return BAD_FUNC_ARG;
416
0
        }
417
418
        /* When length is 0 then use zeroed data of digest length. The caller's
419
         * buffer is not sized for this, so use a local one. */
420
0
        localIkm = ikm;
421
0
        if (ikmLen == 0) {
422
0
            XMEMSET(tmp, 0, len);
423
0
            localIkm = tmp;
424
0
            ikmLen = len;
425
0
        }
426
427
#ifdef WOLFSSL_DEBUG_TLS
428
        WOLFSSL_MSG("  Salt");
429
        WOLFSSL_BUFFER(salt, saltLen);
430
        WOLFSSL_MSG("  IKM");
431
        WOLFSSL_BUFFER(localIkm, ikmLen);
432
#endif
433
434
0
#if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
435
0
    (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
436
0
        ret = wc_HKDF_Extract_ex(digest, salt, saltLen, localIkm, ikmLen, prk,
437
0
            heap, devId);
438
#else
439
        ret = wc_HKDF_Extract(digest, salt, saltLen, localIkm, ikmLen, prk);
440
        (void)heap;
441
        (void)devId;
442
#endif
443
444
#ifdef WOLFSSL_DEBUG_TLS
445
        WOLFSSL_MSG("  PRK");
446
        WOLFSSL_BUFFER(prk, len);
447
#endif
448
449
0
        return ret;
450
0
    }
451
452
    int wc_Tls13_HKDF_Extract(byte* prk, const byte* salt, word32 saltLen,
453
                                 byte* ikm, word32 ikmLen, int digest)
454
0
    {
455
0
        return wc_Tls13_HKDF_Extract_ex(prk, salt, saltLen, ikm, ikmLen, digest,
456
0
            NULL, INVALID_DEVID);
457
0
    }
458
459
    /* Expand data using HMAC, salt and label and info.
460
     * TLS v1.3 defines this function. */
461
    int wc_Tls13_HKDF_Expand_Label_ex(byte* okm, word32 okmLen,
462
                                 const byte* prk, word32 prkLen,
463
                                 const byte* protocol, word32 protocolLen,
464
                                 const byte* label, word32 labelLen,
465
                                 const byte* info, word32 infoLen,
466
                                 int digest, void* heap, int devId)
467
7.74k
    {
468
7.74k
        int    ret = 0;
469
7.74k
        word32 idx = 0;
470
7.74k
        WC_DECLARE_VAR(data, byte, MAX_TLS13_HKDF_LABEL_SZ, 0);
471
472
        /* okmLen (2) + protocol|label len (1) + info len(1) + protocollen +
473
         * labellen + infolen */
474
7.74k
        idx = 4 + protocolLen + labelLen + infoLen;
475
7.74k
        if (idx > MAX_TLS13_HKDF_LABEL_SZ) {
476
0
            return BUFFER_E;
477
0
        }
478
479
7.74k
        WC_ALLOC_VAR_EX(data, byte, idx, NULL, DYNAMIC_TYPE_TMP_BUFFER,
480
7.74k
            return MEMORY_E);
481
7.74k
        idx = 0;
482
483
        /* Output length. */
484
7.74k
        data[idx++] = (byte)(okmLen >> 8);
485
7.74k
        data[idx++] = (byte)okmLen;
486
        /* Length of protocol | label. */
487
7.74k
        data[idx++] = (byte)(protocolLen + labelLen);
488
7.74k
        if (protocolLen > 0) {
489
            /* Protocol */
490
7.74k
            XMEMCPY(&data[idx], protocol, protocolLen);
491
7.74k
            idx += protocolLen;
492
7.74k
        }
493
7.74k
        if (labelLen > 0) {
494
            /* Label */
495
7.74k
            XMEMCPY(&data[idx], label, labelLen);
496
7.74k
            idx += labelLen;
497
7.74k
        }
498
        /* Length of hash of messages */
499
7.74k
        data[idx++] = (byte)infoLen;
500
7.74k
        if (infoLen > 0) {
501
            /* Hash of messages */
502
3.59k
            XMEMCPY(&data[idx], info, infoLen);
503
3.59k
            idx += infoLen;
504
3.59k
        }
505
506
    #ifdef WOLFSSL_CHECK_MEM_ZERO
507
        wc_MemZero_Add("wc_Tls13_HKDF_Expand_Label data", data, idx);
508
    #endif
509
510
#ifdef WOLFSSL_DEBUG_TLS
511
        WOLFSSL_MSG("  PRK");
512
        WOLFSSL_BUFFER(prk, prkLen);
513
        WOLFSSL_MSG("  Info");
514
        WOLFSSL_BUFFER(data, idx);
515
        WOLFSSL_MSG_EX("  Digest %d", digest);
516
#endif
517
518
7.74k
#if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
519
7.74k
    (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
520
7.74k
        ret = wc_HKDF_Expand_ex(digest, prk, prkLen, data, idx, okm, okmLen,
521
7.74k
            heap, devId);
522
#else
523
        ret = wc_HKDF_Expand(digest, prk, prkLen, data, idx, okm, okmLen);
524
        (void)heap;
525
        (void)devId;
526
#endif
527
528
#ifdef WOLFSSL_DEBUG_TLS
529
        WOLFSSL_MSG("  OKM");
530
        WOLFSSL_BUFFER(okm, okmLen);
531
#endif
532
533
7.74k
        ForceZero(data, idx);
534
535
    #ifdef WOLFSSL_CHECK_MEM_ZERO
536
        wc_MemZero_Check(data, idx);
537
    #endif
538
7.74k
        WC_FREE_VAR_EX(data, NULL, DYNAMIC_TYPE_TMP_BUFFER);
539
7.74k
        return ret;
540
7.74k
    }
541
542
    int wc_Tls13_HKDF_Expand_Label(byte* okm, word32 okmLen,
543
                                 const byte* prk, word32 prkLen,
544
                                 const byte* protocol, word32 protocolLen,
545
                                 const byte* label, word32 labelLen,
546
                                 const byte* info, word32 infoLen,
547
                                 int digest)
548
0
    {
549
0
        return wc_Tls13_HKDF_Expand_Label_ex(okm, okmLen, prk, prkLen, protocol,
550
0
            protocolLen, label, labelLen, info, infoLen, digest,
551
0
            NULL, INVALID_DEVID);
552
0
    }
553
554
#if defined(WOLFSSL_TICKET_NONCE_MALLOC) &&                                    \
555
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)))
556
    /* Expand data using HMAC, salt and label and info.
557
     * TLS v1.3 defines this function. */
558
    int wc_Tls13_HKDF_Expand_Label_Alloc(byte* okm, word32 okmLen,
559
        const byte* prk, word32 prkLen, const byte* protocol,
560
        word32 protocolLen, const byte* label, word32 labelLen,
561
        const byte* info, word32 infoLen, int digest, void* heap)
562
    {
563
        int    ret = 0;
564
        word32 idx = 0;
565
        size_t len;
566
        byte   *data;
567
568
        (void)heap;
569
        /* okmLen (2) + protocol|label len (1) + info len(1) + protocollen +
570
         * labellen + infolen */
571
        len = 4U + protocolLen + labelLen + infoLen;
572
573
        data = (byte*)XMALLOC(len, heap, DYNAMIC_TYPE_TMP_BUFFER);
574
        if (data == NULL)
575
            return BUFFER_E;
576
577
        /* Output length. */
578
        data[idx++] = (byte)(okmLen >> 8);
579
        data[idx++] = (byte)okmLen;
580
        /* Length of protocol | label. */
581
        data[idx++] = (byte)(protocolLen + labelLen);
582
        /* Protocol */
583
        XMEMCPY(&data[idx], protocol, protocolLen);
584
        idx += protocolLen;
585
        /* Label */
586
        XMEMCPY(&data[idx], label, labelLen);
587
        idx += labelLen;
588
        /* Length of hash of messages */
589
        data[idx++] = (byte)infoLen;
590
        /* Hash of messages */
591
        XMEMCPY(&data[idx], info, infoLen);
592
        idx += infoLen;
593
594
    #ifdef WOLFSSL_CHECK_MEM_ZERO
595
        wc_MemZero_Add("wc_Tls13_HKDF_Expand_Label data", data, idx);
596
    #endif
597
598
#ifdef WOLFSSL_DEBUG_TLS
599
        WOLFSSL_MSG("  PRK");
600
        WOLFSSL_BUFFER(prk, prkLen);
601
        WOLFSSL_MSG("  Info");
602
        WOLFSSL_BUFFER(data, idx);
603
        WOLFSSL_MSG_EX("  Digest %d", digest);
604
#endif
605
606
        ret = wc_HKDF_Expand(digest, prk, prkLen, data, idx, okm, okmLen);
607
608
#ifdef WOLFSSL_DEBUG_TLS
609
        WOLFSSL_MSG("  OKM");
610
        WOLFSSL_BUFFER(okm, okmLen);
611
#endif
612
613
        ForceZero(data, idx);
614
615
    #ifdef WOLFSSL_CHECK_MEM_ZERO
616
        wc_MemZero_Check(data, len);
617
    #endif
618
        XFREE(data, heap, DYNAMIC_TYPE_TMP_BUFFER);
619
        return ret;
620
    }
621
622
#endif
623
/* defined(WOLFSSL_TICKET_NONCE_MALLOC) && (!defined(HAVE_FIPS) ||
624
 *  FIPS_VERSION_GE(5,3)) */
625
626
#endif /* HAVE_HKDF && !NO_HMAC */
627
628
629
#ifdef WOLFSSL_WOLFSSH
630
631
/* hash union */
632
typedef union {
633
#ifndef NO_MD5
634
    wc_Md5 md5;
635
#endif
636
#ifndef NO_SHA
637
    wc_Sha sha;
638
#endif
639
#ifdef WOLFSSL_SHA224
640
    wc_Sha224 sha224;
641
#endif
642
#ifndef NO_SHA256
643
    wc_Sha256 sha256;
644
#endif
645
#ifdef WOLFSSL_SHA384
646
    wc_Sha384 sha384;
647
#endif
648
#ifdef WOLFSSL_SHA512
649
    wc_Sha512 sha512;
650
#endif
651
#ifdef WOLFSSL_SHA3
652
    wc_Sha3 sha3;
653
#endif
654
} _hash;
655
656
static
657
int _HashInit(byte hashId, _hash* hash)
658
{
659
    int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
660
661
    switch (hashId) {
662
    #ifndef NO_SHA
663
        case WC_SHA:
664
            ret = wc_InitSha(&hash->sha);
665
            break;
666
    #endif /* !NO_SHA */
667
668
    #ifndef NO_SHA256
669
        case WC_SHA256:
670
            ret = wc_InitSha256(&hash->sha256);
671
            break;
672
    #endif /* !NO_SHA256 */
673
674
    #ifdef WOLFSSL_SHA384
675
        case WC_SHA384:
676
            ret = wc_InitSha384(&hash->sha384);
677
            break;
678
    #endif /* WOLFSSL_SHA384 */
679
    #ifdef WOLFSSL_SHA512
680
        case WC_SHA512:
681
            ret = wc_InitSha512(&hash->sha512);
682
            break;
683
    #endif /* WOLFSSL_SHA512 */
684
        default:
685
            ret = BAD_FUNC_ARG;
686
            break;
687
    }
688
689
    return ret;
690
}
691
692
static
693
int _HashUpdate(byte hashId, _hash* hash,
694
        const byte* data, word32 dataSz)
695
{
696
    int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
697
698
    switch (hashId) {
699
    #ifndef NO_SHA
700
        case WC_SHA:
701
            ret = wc_ShaUpdate(&hash->sha, data, dataSz);
702
            break;
703
    #endif /* !NO_SHA */
704
705
    #ifndef NO_SHA256
706
        case WC_SHA256:
707
            ret = wc_Sha256Update(&hash->sha256, data, dataSz);
708
            break;
709
    #endif /* !NO_SHA256 */
710
711
    #ifdef WOLFSSL_SHA384
712
        case WC_SHA384:
713
            ret = wc_Sha384Update(&hash->sha384, data, dataSz);
714
            break;
715
    #endif /* WOLFSSL_SHA384 */
716
    #ifdef WOLFSSL_SHA512
717
        case WC_SHA512:
718
            ret = wc_Sha512Update(&hash->sha512, data, dataSz);
719
            break;
720
    #endif /* WOLFSSL_SHA512 */
721
        default:
722
            ret = BAD_FUNC_ARG;
723
            break;
724
    }
725
726
    return ret;
727
}
728
729
static
730
int _HashFinal(byte hashId, _hash* hash, byte* digest)
731
{
732
    int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
733
734
    switch (hashId) {
735
    #ifndef NO_SHA
736
        case WC_SHA:
737
            ret = wc_ShaFinal(&hash->sha, digest);
738
            break;
739
    #endif /* !NO_SHA */
740
741
    #ifndef NO_SHA256
742
        case WC_SHA256:
743
            ret = wc_Sha256Final(&hash->sha256, digest);
744
            break;
745
    #endif /* !NO_SHA256 */
746
747
    #ifdef WOLFSSL_SHA384
748
        case WC_SHA384:
749
            ret = wc_Sha384Final(&hash->sha384, digest);
750
            break;
751
    #endif /* WOLFSSL_SHA384 */
752
    #ifdef WOLFSSL_SHA512
753
        case WC_SHA512:
754
            ret = wc_Sha512Final(&hash->sha512, digest);
755
            break;
756
    #endif /* WOLFSSL_SHA512 */
757
        default:
758
            ret = BAD_FUNC_ARG;
759
            break;
760
    }
761
762
    return ret;
763
}
764
765
static
766
void _HashFree(byte hashId, _hash* hash)
767
{
768
    switch (hashId) {
769
    #ifndef NO_SHA
770
        case WC_SHA:
771
            wc_ShaFree(&hash->sha);
772
            break;
773
    #endif /* !NO_SHA */
774
775
    #ifndef NO_SHA256
776
        case WC_SHA256:
777
            wc_Sha256Free(&hash->sha256);
778
            break;
779
    #endif /* !NO_SHA256 */
780
781
    #ifdef WOLFSSL_SHA384
782
        case WC_SHA384:
783
            wc_Sha384Free(&hash->sha384);
784
            break;
785
    #endif /* WOLFSSL_SHA384 */
786
    #ifdef WOLFSSL_SHA512
787
        case WC_SHA512:
788
            wc_Sha512Free(&hash->sha512);
789
            break;
790
    #endif /* WOLFSSL_SHA512 */
791
    }
792
}
793
794
795
#define LENGTH_SZ 4
796
797
int wc_SSH_KDF(byte hashId, byte keyId, byte* key, word32 keySz,
798
        const byte* k, word32 kSz, const byte* h, word32 hSz,
799
        const byte* sessionId, word32 sessionIdSz)
800
{
801
    word32 blocks, remainder;
802
    _hash hash;
803
    enum wc_HashType enmhashId = (enum wc_HashType)hashId;
804
    byte kPad = 0;
805
    byte pad = 0;
806
    byte kSzFlat[LENGTH_SZ];
807
    word32 digestSz;
808
    int ret;
809
810
    if (key == NULL || keySz == 0 ||
811
        k == NULL || kSz == 0 ||
812
        h == NULL || hSz == 0 ||
813
        sessionId == NULL || sessionIdSz == 0) {
814
815
        return BAD_FUNC_ARG;
816
    }
817
818
    ret = wc_HmacSizeByType((int)enmhashId);
819
    if (ret <= 0) {
820
        return BAD_FUNC_ARG;
821
    }
822
    digestSz = (word32)ret;
823
824
    if (k[0] & 0x80) kPad = 1;
825
    c32toa(kSz + kPad, kSzFlat);
826
827
    blocks = keySz / digestSz;
828
    remainder = keySz % digestSz;
829
830
    ret = _HashInit(enmhashId, &hash);
831
    if (ret != 0)
832
        return ret;
833
#ifdef WOLFSSL_CHECK_MEM_ZERO
834
    wc_MemZero_Add("wc_SSH_KDF hash", &hash, sizeof(hash));
835
#endif
836
837
    ret = _HashUpdate(enmhashId, &hash, kSzFlat, LENGTH_SZ);
838
    if (ret == 0 && kPad)
839
        ret = _HashUpdate(enmhashId, &hash, &pad, 1);
840
    if (ret == 0)
841
        ret = _HashUpdate(enmhashId, &hash, k, kSz);
842
    if (ret == 0)
843
        ret = _HashUpdate(enmhashId, &hash, h, hSz);
844
    if (ret == 0)
845
        ret = _HashUpdate(enmhashId, &hash, &keyId, sizeof(keyId));
846
    if (ret == 0)
847
        ret = _HashUpdate(enmhashId, &hash, sessionId, sessionIdSz);
848
849
    if (ret == 0) {
850
        if (blocks == 0) {
851
            if (remainder > 0) {
852
                byte lastBlock[WC_MAX_DIGEST_SIZE];
853
            #ifdef WOLFSSL_CHECK_MEM_ZERO
854
                wc_MemZero_Add("wc_SSH_KDF lastBlock", lastBlock,
855
                    sizeof(lastBlock));
856
            #endif
857
                ret = _HashFinal(enmhashId, &hash, lastBlock);
858
                if (ret == 0)
859
                    XMEMCPY(key, lastBlock, remainder);
860
                /* lastBlock held derived key material (ISO/IEC 19790 7.9). */
861
                ForceZero(lastBlock, sizeof(lastBlock));
862
            #ifdef WOLFSSL_CHECK_MEM_ZERO
863
                wc_MemZero_Check(lastBlock, sizeof(lastBlock));
864
            #endif
865
            }
866
        }
867
        else {
868
            word32 runningKeySz, curBlock;
869
870
            runningKeySz = digestSz;
871
            ret = _HashFinal(enmhashId, &hash, key);
872
873
            for (curBlock = 1; (ret == 0) && (curBlock < blocks); curBlock++) {
874
                /* Final resets the hash for reuse. Reinitializing here would
875
                 * lose owned resources such as the cached SHA-256 schedule. */
876
                ret = _HashUpdate(enmhashId, &hash, kSzFlat, LENGTH_SZ);
877
                if (ret != 0) break;
878
                if (kPad)
879
                    ret = _HashUpdate(enmhashId, &hash, &pad, 1);
880
                if (ret != 0) break;
881
                ret = _HashUpdate(enmhashId, &hash, k, kSz);
882
                if (ret != 0) break;
883
                ret = _HashUpdate(enmhashId, &hash, h, hSz);
884
                if (ret != 0) break;
885
                ret = _HashUpdate(enmhashId, &hash, key, runningKeySz);
886
                if (ret != 0) break;
887
                ret = _HashFinal(enmhashId, &hash, key + runningKeySz);
888
                if (ret != 0) break;
889
                runningKeySz += digestSz;
890
            }
891
892
            if (remainder > 0) {
893
                byte lastBlock[WC_MAX_DIGEST_SIZE];
894
            #ifdef WOLFSSL_CHECK_MEM_ZERO
895
                wc_MemZero_Add("wc_SSH_KDF lastBlock", lastBlock,
896
                    sizeof(lastBlock));
897
            #endif
898
                /* Reuse the reset context from the preceding Final. */
899
                if (ret == 0)
900
                    ret = _HashUpdate(enmhashId, &hash, kSzFlat, LENGTH_SZ);
901
                if (ret == 0 && kPad)
902
                    ret = _HashUpdate(enmhashId, &hash, &pad, 1);
903
                if (ret == 0)
904
                    ret = _HashUpdate(enmhashId, &hash, k, kSz);
905
                if (ret == 0)
906
                    ret = _HashUpdate(enmhashId, &hash, h, hSz);
907
                if (ret == 0)
908
                    ret = _HashUpdate(enmhashId, &hash, key, runningKeySz);
909
                if (ret == 0)
910
                    ret = _HashFinal(enmhashId, &hash, lastBlock);
911
                if (ret == 0)
912
                    XMEMCPY(key + runningKeySz, lastBlock, remainder);
913
                /* lastBlock held derived key material (ISO/IEC 19790 7.9). */
914
                ForceZero(lastBlock, sizeof(lastBlock));
915
            #ifdef WOLFSSL_CHECK_MEM_ZERO
916
                wc_MemZero_Check(lastBlock, sizeof(lastBlock));
917
            #endif
918
            }
919
        }
920
    }
921
922
    _HashFree(enmhashId, &hash);
923
    /* hash absorbed the shared secret K (ISO/IEC 19790:2012 7.9.7). */
924
    ForceZero(&hash, sizeof(hash));
925
#ifdef WOLFSSL_CHECK_MEM_ZERO
926
    wc_MemZero_Check(&hash, sizeof(hash));
927
#endif
928
    if (ret != 0) {
929
        ForceZero(key, keySz);
930
    }
931
932
    return ret;
933
}
934
935
#endif /* WOLFSSL_WOLFSSH */
936
937
#ifdef WC_SRTP_KDF
938
/* Calculate first block to encrypt.
939
 *
940
 * @param [in]  salt     Random value to XOR in.
941
 * @param [in]  saltSz   Size of random value in bytes.
942
 * @param [in]  kdrIdx   Key derivation rate. kdr = 0 when -1, otherwise
943
 *                       kdr = 2^kdrIdx.
944
 * @param [in]  idx      Index value to XOR in.
945
 * @param [in]  idxSz    Size of index value in bytes.
946
 * @param [out] block    First block to encrypt.
947
 */
948
static void wc_srtp_kdf_first_block(const byte* salt, word32 saltSz, int kdrIdx,
949
        const byte* idx, int idxSz, unsigned char* block)
950
{
951
    int i;
952
953
    /* XOR salt into zeroized buffer. */
954
    for (i = 0; i < WC_SRTP_MAX_SALT - (int)saltSz; i++) {
955
        block[i] = 0;
956
    }
957
    XMEMCPY(block + WC_SRTP_MAX_SALT - saltSz, salt, saltSz);
958
    /* block[14-15] are counter. */
959
960
    /* When kdrIdx is -1, don't XOR in index. */
961
    if (kdrIdx >= 0) {
962
        /* Get the number of bits to shift index by. */
963
        word32 bits = kdrIdx & 0x7;
964
        /* Reduce index size by number of bytes to remove. */
965
        idxSz -= kdrIdx >> 3;
966
967
        if ((kdrIdx & 0x7) == 0) {
968
            /* Just XOR in as no bit shifting. */
969
            for (i = 0; i < idxSz; i++) {
970
                block[i + WC_SRTP_MAX_SALT - idxSz] ^= idx[i];
971
            }
972
        }
973
        else {
974
            /* XOR in as bit shifted index. */
975
            block[WC_SRTP_MAX_SALT - idxSz] ^= (byte)(idx[0] >> bits);
976
            for (i = 1; i < idxSz; i++) {
977
                block[i + WC_SRTP_MAX_SALT - idxSz] ^=
978
                    (byte)((idx[i-1] << (8 - bits)) |
979
                           (idx[i+0] >>      bits ));
980
            }
981
        }
982
    }
983
}
984
985
/* Derive a key given the first block.
986
 *
987
 * @param [in, out] block    First block to encrypt. Need label XORed in.
988
 * @param [in]      indexSz  Size of index in bytes to calculate where label is
989
 *                           XORed into.
990
 * @param [in]      label    Label byte that differs for each key.
991
 * @param [out]     key      Derived key.
992
 * @param [in]      keySz    Size of key to derive in bytes.
993
 * @param [in]      aes      AES object to encrypt with.
994
 * @return  0 on success.
995
 */
996
static int wc_srtp_kdf_derive_key(byte* block, int idxSz, byte label,
997
        byte* key, word32 keySz, Aes* aes)
998
{
999
    int i;
1000
    int ret = 0;
1001
    /* Calculate the number of full blocks needed for derived key. */
1002
    int blocks = (int)(keySz / WC_AES_BLOCK_SIZE);
1003
1004
    /* XOR in label. */
1005
    block[WC_SRTP_MAX_SALT - idxSz - 1] ^= label;
1006
    for (i = 0; (ret == 0) && (i < blocks); i++) {
1007
        /* Set counter. */
1008
        block[14] = (byte)(i >> 8);
1009
        block[15] = (byte)i;
1010
        /* Encrypt block into key buffer. */
1011
        ret = wc_AesEcbEncrypt(aes, key, block, WC_AES_BLOCK_SIZE);
1012
        /* Reposition for more derived key. */
1013
        key += WC_AES_BLOCK_SIZE;
1014
        /* Reduce the count of key bytes required. */
1015
        keySz -= WC_AES_BLOCK_SIZE;
1016
    }
1017
    /* Do any partial blocks. */
1018
    if ((ret == 0) && (keySz > 0)) {
1019
        byte enc[WC_AES_BLOCK_SIZE];
1020
        /* Set counter. */
1021
        block[14] = (byte)(i >> 8);
1022
        block[15] = (byte)i;
1023
        /* Encrypt block into temporary. */
1024
        ret = wc_AesEcbEncrypt(aes, enc, block, WC_AES_BLOCK_SIZE);
1025
        if (ret == 0) {
1026
            /* Copy into key required amount. */
1027
            XMEMCPY(key, enc, keySz);
1028
        }
1029
        ForceZero(enc, sizeof(enc));
1030
    }
1031
    /* XOR out label. */
1032
    block[WC_SRTP_MAX_SALT - idxSz - 1] ^= label;
1033
1034
    return ret;
1035
}
1036
1037
/* Derive keys using SRTP KDF algorithm.
1038
 *
1039
 * SP 800-135 (RFC 3711).
1040
 *
1041
 * @param [in]  key      Key to use with encryption.
1042
 * @param [in]  keySz    Size of key in bytes.
1043
 * @param [in]  salt     Random non-secret value.
1044
 * @param [in]  saltSz   Size of random in bytes.
1045
 * @param [in]  kdrIdx   Key derivation rate. kdr = 0 when -1, otherwise
1046
 *                       kdr = 2^kdrIdx.
1047
 * @param [in]  idx      Index value to XOR in.
1048
 * @param [out] key1     First key. Label value of 0x00.
1049
 * @param [in]  key1Sz   Size of first key in bytes.
1050
 * @param [out] key2     Second key. Label value of 0x01.
1051
 * @param [in]  key2Sz   Size of second key in bytes.
1052
 * @param [out] key3     Third key. Label value of 0x02.
1053
 * @param [in]  key3Sz   Size of third key in bytes.
1054
 * @return  BAD_FUNC_ARG when key or salt is NULL.
1055
 * @return  BAD_FUNC_ARG when key length is not 16, 24 or 32.
1056
 * @return  BAD_FUNC_ARG when saltSz is larger than 14.
1057
 * @return  BAD_FUNC_ARG when kdrIdx is less than -1 or larger than 24.
1058
 * @return  MEMORY_E on dynamic memory allocation failure.
1059
 * @return  0 on success.
1060
 */
1061
int wc_SRTP_KDF(const byte* key, word32 keySz, const byte* salt, word32 saltSz,
1062
        int kdrIdx, const byte* idx, byte* key1, word32 key1Sz, byte* key2,
1063
        word32 key2Sz, byte* key3, word32 key3Sz)
1064
{
1065
    int ret = 0;
1066
    byte block[WC_AES_BLOCK_SIZE];
1067
    WC_DECLARE_VAR(aes, Aes, 1, 0);
1068
    int aes_inited = 0;
1069
1070
    /* Validate parameters. */
1071
    if ((key == NULL) || (keySz > AES_256_KEY_SIZE) || (salt == NULL) ||
1072
            (saltSz > WC_SRTP_MAX_SALT) || (kdrIdx < -1) || (kdrIdx > 24) ||
1073
            ((kdrIdx >= 0) && (idx == NULL))) {
1074
        ret = BAD_FUNC_ARG;
1075
    }
1076
1077
#ifdef WOLFSSL_SMALL_STACK
1078
    if (ret == 0) {
1079
        aes = (Aes*)XMALLOC(sizeof(Aes), NULL, DYNAMIC_TYPE_CIPHER);
1080
        if (aes == NULL) {
1081
            ret = MEMORY_E;
1082
        }
1083
    }
1084
#endif
1085
1086
    /* Setup AES object. */
1087
    if (ret == 0) {
1088
        ret = wc_AesInit(aes, NULL, INVALID_DEVID);
1089
    }
1090
    if (ret == 0) {
1091
        aes_inited = 1;
1092
        ret = wc_AesSetKey(aes, key, keySz, NULL, AES_ENCRYPTION);
1093
    }
1094
1095
    /* Calculate first block that can be used in each derivation. */
1096
    if (ret == 0) {
1097
        wc_srtp_kdf_first_block(salt, saltSz, kdrIdx, idx, WC_SRTP_INDEX_LEN,
1098
            block);
1099
    }
1100
1101
    /* Calculate first key if required. */
1102
    if ((ret == 0) && (key1 != NULL)) {
1103
        ret = wc_srtp_kdf_derive_key(block, WC_SRTP_INDEX_LEN,
1104
            WC_SRTP_LABEL_ENCRYPTION, key1, key1Sz, aes);
1105
    }
1106
    /* Calculate second key if required. */
1107
    if ((ret == 0) && (key2 != NULL)) {
1108
        ret = wc_srtp_kdf_derive_key(block, WC_SRTP_INDEX_LEN,
1109
            WC_SRTP_LABEL_MSG_AUTH, key2, key2Sz, aes);
1110
    }
1111
    /* Calculate third key if required. */
1112
    if ((ret == 0) && (key3 != NULL)) {
1113
        ret = wc_srtp_kdf_derive_key(block, WC_SRTP_INDEX_LEN,
1114
            WC_SRTP_LABEL_SALT, key3, key3Sz, aes);
1115
    }
1116
    if ((ret != 0) && aes_inited) {
1117
        /* Derived keys are not released (ISO/IEC 19790 7.9.7). */
1118
        if (key1 != NULL)
1119
            ForceZero(key1, key1Sz);
1120
        if (key2 != NULL)
1121
            ForceZero(key2, key2Sz);
1122
        if (key3 != NULL)
1123
            ForceZero(key3, key3Sz);
1124
    }
1125
1126
    if (aes_inited)
1127
        wc_AesFree(aes);
1128
    WC_FREE_VAR_EX(aes, NULL, DYNAMIC_TYPE_CIPHER);
1129
    return ret;
1130
}
1131
1132
/* Derive keys using SRTCP KDF algorithm.
1133
 *
1134
 * SP 800-135 (RFC 3711).
1135
 *
1136
 * @param [in]  key      Key to use with encryption.
1137
 * @param [in]  keySz    Size of key in bytes.
1138
 * @param [in]  salt     Random non-secret value.
1139
 * @param [in]  saltSz   Size of random in bytes.
1140
 * @param [in]  kdrIdx   Key derivation rate index. kdr = 0 when -1, otherwise
1141
 *                       kdr = 2^kdrIdx. See wc_SRTP_KDF_kdr_to_idx()
1142
 * @param [in]  idx      Index value to XOR in.
1143
 * @param [out] key1     First key. Label value of 0x03.
1144
 * @param [in]  key1Sz   Size of first key in bytes.
1145
 * @param [out] key2     Second key. Label value of 0x04.
1146
 * @param [in]  key2Sz   Size of second key in bytes.
1147
 * @param [out] key3     Third key. Label value of 0x05.
1148
 * @param [in]  key3Sz   Size of third key in bytes.
1149
 * @return  BAD_FUNC_ARG when key or salt is NULL.
1150
 * @return  BAD_FUNC_ARG when key length is not 16, 24 or 32.
1151
 * @return  BAD_FUNC_ARG when saltSz is larger than 14.
1152
 * @return  BAD_FUNC_ARG when kdrIdx is less than -1 or larger than 24.
1153
 * @return  MEMORY_E on dynamic memory allocation failure.
1154
 * @return  0 on success.
1155
 */
1156
int wc_SRTCP_KDF_ex(const byte* key, word32 keySz, const byte* salt, word32 saltSz,
1157
        int kdrIdx, const byte* idx, byte* key1, word32 key1Sz, byte* key2,
1158
        word32 key2Sz, byte* key3, word32 key3Sz, int idxLenIndicator)
1159
{
1160
    int ret = 0;
1161
    byte block[WC_AES_BLOCK_SIZE];
1162
    WC_DECLARE_VAR(aes, Aes, 1, 0);
1163
    int aes_inited = 0;
1164
    int idxLen;
1165
1166
    if (idxLenIndicator == WC_SRTCP_32BIT_IDX) {
1167
        idxLen = WC_SRTCP_INDEX_LEN;
1168
    } else if (idxLenIndicator == WC_SRTCP_48BIT_IDX) {
1169
        idxLen = WC_SRTP_INDEX_LEN;
1170
    } else {
1171
        return BAD_FUNC_ARG; /* bad or invalid idxLenIndicator */
1172
    }
1173
1174
    /* Validate parameters. */
1175
    if ((key == NULL) || (keySz > AES_256_KEY_SIZE) || (salt == NULL) ||
1176
            (saltSz > WC_SRTP_MAX_SALT) || (kdrIdx < -1) || (kdrIdx > 24) ||
1177
            ((kdrIdx >= 0) && (idx == NULL))) {
1178
        ret = BAD_FUNC_ARG;
1179
    }
1180
1181
#ifdef WOLFSSL_SMALL_STACK
1182
    if (ret == 0) {
1183
        aes = (Aes*)XMALLOC(sizeof(Aes), NULL, DYNAMIC_TYPE_CIPHER);
1184
        if (aes == NULL) {
1185
            ret = MEMORY_E;
1186
        }
1187
    }
1188
#endif
1189
1190
    /* Setup AES object. */
1191
    if (ret == 0) {
1192
        ret = wc_AesInit(aes, NULL, INVALID_DEVID);
1193
    }
1194
    if (ret == 0) {
1195
        aes_inited = 1;
1196
        ret = wc_AesSetKey(aes, key, keySz, NULL, AES_ENCRYPTION);
1197
    }
1198
1199
    /* Calculate first block that can be used in each derivation. */
1200
    if (ret == 0) {
1201
        wc_srtp_kdf_first_block(salt, saltSz, kdrIdx, idx, idxLen, block);
1202
    }
1203
1204
    /* Calculate first key if required. */
1205
    if ((ret == 0) && (key1 != NULL)) {
1206
        ret = wc_srtp_kdf_derive_key(block, idxLen,
1207
            WC_SRTCP_LABEL_ENCRYPTION, key1, key1Sz, aes);
1208
    }
1209
    /* Calculate second key if required. */
1210
    if ((ret == 0) && (key2 != NULL)) {
1211
        ret = wc_srtp_kdf_derive_key(block, idxLen,
1212
            WC_SRTCP_LABEL_MSG_AUTH, key2, key2Sz, aes);
1213
    }
1214
    /* Calculate third key if required. */
1215
    if ((ret == 0) && (key3 != NULL)) {
1216
        ret = wc_srtp_kdf_derive_key(block, idxLen,
1217
            WC_SRTCP_LABEL_SALT, key3, key3Sz, aes);
1218
    }
1219
    if ((ret != 0) && aes_inited) {
1220
        /* Derived keys are not released (ISO/IEC 19790 7.9.7). */
1221
        if (key1 != NULL)
1222
            ForceZero(key1, key1Sz);
1223
        if (key2 != NULL)
1224
            ForceZero(key2, key2Sz);
1225
        if (key3 != NULL)
1226
            ForceZero(key3, key3Sz);
1227
    }
1228
1229
    if (aes_inited)
1230
        wc_AesFree(aes);
1231
    WC_FREE_VAR_EX(aes, NULL, DYNAMIC_TYPE_CIPHER);
1232
    return ret;
1233
}
1234
1235
int wc_SRTCP_KDF(const byte* key, word32 keySz, const byte* salt, word32 saltSz,
1236
        int kdrIdx, const byte* idx, byte* key1, word32 key1Sz, byte* key2,
1237
        word32 key2Sz, byte* key3, word32 key3Sz)
1238
{
1239
    /* The default 32-bit IDX expected by many implementations */
1240
    return wc_SRTCP_KDF_ex(key, keySz, salt, saltSz, kdrIdx, idx,
1241
                           key1, key1Sz, key2, key2Sz, key3, key3Sz,
1242
                           WC_SRTCP_32BIT_IDX);
1243
}
1244
/* Derive key with label using SRTP KDF algorithm.
1245
 *
1246
 * SP 800-135 (RFC 3711).
1247
 *
1248
 * @param [in]  key       Key to use with encryption.
1249
 * @param [in]  keySz     Size of key in bytes.
1250
 * @param [in]  salt      Random non-secret value.
1251
 * @param [in]  saltSz    Size of random in bytes.
1252
 * @param [in]  kdrIdx    Key derivation rate index. kdr = 0 when -1, otherwise
1253
 *                        kdr = 2^kdrIdx. See wc_SRTP_KDF_kdr_to_idx()
1254
 * @param [in]  idx       Index value to XOR in.
1255
 * @param [in]  label     Label to use when deriving key.
1256
 * @param [out] outKey    Derived key.
1257
 * @param [in]  outKeySz  Size of derived key in bytes.
1258
 * @return  BAD_FUNC_ARG when key, salt or outKey is NULL.
1259
 * @return  BAD_FUNC_ARG when key length is not 16, 24 or 32.
1260
 * @return  BAD_FUNC_ARG when saltSz is larger than 14.
1261
 * @return  BAD_FUNC_ARG when kdrIdx is less than -1 or larger than 24.
1262
 * @return  MEMORY_E on dynamic memory allocation failure.
1263
 * @return  0 on success.
1264
 */
1265
int wc_SRTP_KDF_label(const byte* key, word32 keySz, const byte* salt,
1266
        word32 saltSz, int kdrIdx, const byte* idx, byte label, byte* outKey,
1267
        word32 outKeySz)
1268
{
1269
    int ret = 0;
1270
    byte block[WC_AES_BLOCK_SIZE];
1271
    WC_DECLARE_VAR(aes, Aes, 1, 0);
1272
    int aes_inited = 0;
1273
1274
    /* Validate parameters. */
1275
    if ((key == NULL) || (keySz > AES_256_KEY_SIZE) || (salt == NULL) ||
1276
            (saltSz > WC_SRTP_MAX_SALT) || (kdrIdx < -1) || (kdrIdx > 24) ||
1277
            (outKey == NULL) || ((kdrIdx >= 0) && (idx == NULL))) {
1278
        ret = BAD_FUNC_ARG;
1279
    }
1280
1281
#ifdef WOLFSSL_SMALL_STACK
1282
    if (ret == 0) {
1283
        aes = (Aes*)XMALLOC(sizeof(Aes), NULL, DYNAMIC_TYPE_CIPHER);
1284
        if (aes == NULL) {
1285
            ret = MEMORY_E;
1286
        }
1287
    }
1288
#endif
1289
1290
    /* Setup AES object. */
1291
    if (ret == 0) {
1292
        ret = wc_AesInit(aes, NULL, INVALID_DEVID);
1293
    }
1294
    if (ret == 0) {
1295
        aes_inited = 1;
1296
        ret = wc_AesSetKey(aes, key, keySz, NULL, AES_ENCRYPTION);
1297
    }
1298
1299
    /* Calculate first block that can be used in each derivation. */
1300
    if (ret == 0) {
1301
        wc_srtp_kdf_first_block(salt, saltSz, kdrIdx, idx, WC_SRTP_INDEX_LEN,
1302
            block);
1303
    }
1304
    if (ret == 0) {
1305
        /* Calculate key. */
1306
        ret = wc_srtp_kdf_derive_key(block, WC_SRTP_INDEX_LEN, label, outKey,
1307
            outKeySz, aes);
1308
    }
1309
    if ((ret != 0) && aes_inited) {
1310
        ForceZero(outKey, outKeySz);
1311
    }
1312
1313
    if (aes_inited)
1314
        wc_AesFree(aes);
1315
    WC_FREE_VAR_EX(aes, NULL, DYNAMIC_TYPE_CIPHER);
1316
    return ret;
1317
1318
}
1319
1320
/* Derive key with label using SRTCP KDF algorithm.
1321
 *
1322
 * SP 800-135 (RFC 3711).
1323
 *
1324
 * @param [in]  key       Key to use with encryption.
1325
 * @param [in]  keySz     Size of key in bytes.
1326
 * @param [in]  salt      Random non-secret value.
1327
 * @param [in]  saltSz    Size of random in bytes.
1328
 * @param [in]  kdrIdx    Key derivation rate index. kdr = 0 when -1, otherwise
1329
 *                        kdr = 2^kdrIdx. See wc_SRTP_KDF_kdr_to_idx()
1330
 * @param [in]  idx       Index value to XOR in.
1331
 * @param [in]  label     Label to use when deriving key.
1332
 * @param [out] outKey    Derived key.
1333
 * @param [in]  outKeySz  Size of derived key in bytes.
1334
 * @return  BAD_FUNC_ARG when key, salt or outKey is NULL.
1335
 * @return  BAD_FUNC_ARG when key length is not 16, 24 or 32.
1336
 * @return  BAD_FUNC_ARG when saltSz is larger than 14.
1337
 * @return  BAD_FUNC_ARG when kdrIdx is less than -1 or larger than 24.
1338
 * @return  MEMORY_E on dynamic memory allocation failure.
1339
 * @return  0 on success.
1340
 */
1341
int wc_SRTCP_KDF_label(const byte* key, word32 keySz, const byte* salt,
1342
        word32 saltSz, int kdrIdx, const byte* idx, byte label, byte* outKey,
1343
        word32 outKeySz)
1344
{
1345
    int ret = 0;
1346
    byte block[WC_AES_BLOCK_SIZE];
1347
    WC_DECLARE_VAR(aes, Aes, 1, 0);
1348
    int aes_inited = 0;
1349
1350
    /* Validate parameters. */
1351
    if ((key == NULL) || (keySz > AES_256_KEY_SIZE) || (salt == NULL) ||
1352
            (saltSz > WC_SRTP_MAX_SALT) || (kdrIdx < -1) || (kdrIdx > 24) ||
1353
            (outKey == NULL) || ((kdrIdx >= 0) && (idx == NULL))) {
1354
        ret = BAD_FUNC_ARG;
1355
    }
1356
1357
#ifdef WOLFSSL_SMALL_STACK
1358
    if (ret == 0) {
1359
        aes = (Aes*)XMALLOC(sizeof(Aes), NULL, DYNAMIC_TYPE_CIPHER);
1360
        if (aes == NULL) {
1361
            ret = MEMORY_E;
1362
        }
1363
    }
1364
#endif
1365
1366
    /* Setup AES object. */
1367
    if (ret == 0) {
1368
        ret = wc_AesInit(aes, NULL, INVALID_DEVID);
1369
    }
1370
    if (ret == 0) {
1371
        aes_inited = 1;
1372
        ret = wc_AesSetKey(aes, key, keySz, NULL, AES_ENCRYPTION);
1373
    }
1374
1375
    /* Calculate first block that can be used in each derivation. */
1376
    if (ret == 0) {
1377
        wc_srtp_kdf_first_block(salt, saltSz, kdrIdx, idx, WC_SRTCP_INDEX_LEN,
1378
            block);
1379
    }
1380
    if (ret == 0) {
1381
        /* Calculate key. */
1382
        ret = wc_srtp_kdf_derive_key(block, WC_SRTCP_INDEX_LEN, label, outKey,
1383
            outKeySz, aes);
1384
    }
1385
    if ((ret != 0) && aes_inited) {
1386
        ForceZero(outKey, outKeySz);
1387
    }
1388
1389
    if (aes_inited)
1390
        wc_AesFree(aes);
1391
    WC_FREE_VAR_EX(aes, NULL, DYNAMIC_TYPE_CIPHER);
1392
    return ret;
1393
1394
}
1395
1396
/* Converts a kdr value to an index to use in SRTP/SRTCP KDF API.
1397
 *
1398
 * @param [in] kdr  Key derivation rate to convert.
1399
 * @return  Key derivation rate as an index.
1400
 */
1401
int wc_SRTP_KDF_kdr_to_idx(word32 kdr)
1402
{
1403
    int idx = -1;
1404
1405
    /* Keep shifting value down and incrementing index until top bit is gone. */
1406
    while (kdr != 0) {
1407
        kdr >>= 1;
1408
        idx++;
1409
    }
1410
1411
    /* Index of top bit set. */
1412
    return idx;
1413
}
1414
#endif /* WC_SRTP_KDF */
1415
1416
#ifdef WC_KDF_NIST_SP_800_56C
1417
static int wc_KDA_KDF_iteration(const byte* z, word32 zSz, word32 counter,
1418
    const byte* fixedInfo, word32 fixedInfoSz, enum wc_HashType hashType,
1419
    byte* output)
1420
{
1421
    byte counterBuf[4];
1422
    WC_DECLARE_VAR(hash, wc_HashAlg, 1, NULL);
1423
    int ret;
1424
1425
    WC_ALLOC_VAR_EX(hash, wc_HashAlg, 1, NULL, DYNAMIC_TYPE_HASHES,
1426
                    return MEMORY_E);
1427
1428
    ret = wc_HashInit(hash, hashType);
1429
    if (ret != 0) {
1430
        WC_FREE_VAR_EX(hash, NULL, DYNAMIC_TYPE_HASHES);
1431
        return ret;
1432
    }
1433
    c32toa(counter, counterBuf);
1434
    ret = wc_HashUpdate(hash, hashType, counterBuf, 4);
1435
    if (ret == 0) {
1436
        ret = wc_HashUpdate(hash, hashType, z, zSz);
1437
    }
1438
    if (ret == 0 && fixedInfoSz > 0) {
1439
        ret = wc_HashUpdate(hash, hashType, fixedInfo, fixedInfoSz);
1440
    }
1441
    if (ret == 0) {
1442
        ret = wc_HashFinal(hash, hashType, output);
1443
    }
1444
    wc_HashFree(hash, hashType);
1445
    WC_FREE_VAR_EX(hash, NULL, DYNAMIC_TYPE_HASHES);
1446
    return ret;
1447
}
1448
1449
/**
1450
 * \brief Performs the single-step key derivation function (KDF) as specified in
1451
 * SP800-56C option 1. This implementation uses a 32 bit counter.
1452
 *
1453
 * \param [in] z The input keying material.
1454
 * \param [in] zSz The size of the input keying material.
1455
 * \param [in] fixedInfo The fixed information to be included in the KDF.
1456
 * \param [in] fixedInfoSz The size of the fixed information.
1457
 * \param [in] derivedSecretSz The desired size of the derived secret.
1458
 * \param [in] hashType The hash algorithm to be used in the KDF.
1459
 * \param [out] output The buffer to store the derived secret.
1460
 * \param [in] outputSz The size of the output buffer.
1461
 *
1462
 * \return 0 if the KDF operation is successful.
1463
 * \return BAD_FUNC_ARG if the input parameters are invalid.
1464
 * \return negative error code if the KDF operation fails.
1465
 */
1466
int wc_KDA_KDF_onestep(const byte* z, word32 zSz, const byte* fixedInfo,
1467
    word32 fixedInfoSz, word32 derivedSecretSz, enum wc_HashType hashType,
1468
    byte* output, word32 outputSz)
1469
{
1470
    byte hashTempBuf[WC_MAX_DIGEST_SIZE];
1471
    word32 counter, outIdx;
1472
    int hashOutSz;
1473
    int ret;
1474
1475
    if (output == NULL || outputSz < derivedSecretSz)
1476
        return BAD_FUNC_ARG;
1477
    if (z == NULL || zSz == 0 || (fixedInfoSz > 0 && fixedInfo == NULL))
1478
        return BAD_FUNC_ARG;
1479
    if (derivedSecretSz == 0)
1480
        return BAD_FUNC_ARG;
1481
1482
    hashOutSz = wc_HashGetDigestSize(hashType);
1483
    if (hashOutSz <= 0)
1484
        return BAD_FUNC_ARG;
1485
1486
    /* According to SP800_56C, table 1, the max input size (max_H_inputBits)
1487
     * depends on the HASH algo. The smaller value in the table is (2**64-1)/8.
1488
     * This is larger than the possible length using word32 integers. */
1489
1490
    counter = 1; /* init counter to 1, from SP800-56C section 4.1 */
1491
    outIdx = 0;
1492
    ret = 0;
1493
1494
    /* According to SP800_56C the number of iterations shall not be greater than
1495
     * 2**32-1. This is not possible using word32 integers.*/
1496
    while (outIdx + (word32) hashOutSz <= derivedSecretSz) {
1497
        ret = wc_KDA_KDF_iteration(z, zSz, counter, fixedInfo, fixedInfoSz,
1498
            hashType, output + outIdx);
1499
        if (ret != 0)
1500
            break;
1501
        counter++;
1502
        outIdx += (word32) hashOutSz;
1503
    }
1504
1505
    if (ret == 0 && outIdx < derivedSecretSz) {
1506
    #ifdef WOLFSSL_CHECK_MEM_ZERO
1507
        /* poison so a missed ForceZero on any path is caught by the check */
1508
        XMEMSET(hashTempBuf, 0xff, (word32) hashOutSz);
1509
        wc_MemZero_Add("wc_KDA_KDF_onestep hashTempBuf", hashTempBuf,
1510
            (word32) hashOutSz);
1511
    #endif
1512
        ret = wc_KDA_KDF_iteration(z, zSz, counter, fixedInfo, fixedInfoSz,
1513
            hashType, hashTempBuf);
1514
        if (ret == 0) {
1515
            XMEMCPY(output + outIdx, hashTempBuf, derivedSecretSz - outIdx);
1516
        }
1517
        ForceZero(hashTempBuf, (word32) hashOutSz);
1518
    #ifdef WOLFSSL_CHECK_MEM_ZERO
1519
        wc_MemZero_Check(hashTempBuf, (word32) hashOutSz);
1520
    #endif
1521
    }
1522
1523
    if (ret != 0) {
1524
        ForceZero(output, derivedSecretSz);
1525
    }
1526
1527
    return ret;
1528
}
1529
#endif /* WC_KDF_NIST_SP_800_56C */
1530
1531
#ifdef HAVE_CMAC_KDF
1532
/**
1533
 * \brief Performs the two-step cmac key derivation function (KDF) as
1534
 * specified in SP800-56C, section 5.1, in counter mode.
1535
 *
1536
 *            Z                               fixedInfo
1537
 *        ____|_________________________________|___________
1538
 *       |    |                                 |           |
1539
 *       |    ________________                ___________   |
1540
 * salt--|-> | Randomness     |              | Key       |  |
1541
 *       |   | Extract        | --Key_kdk--> | Expansion | -|-output-->
1542
 *       |    ----------------                -----------   |
1543
 *        --------------------------------------------------
1544
 *
1545
 * \param [in]  salt         The input keying material for cmac.
1546
 * \param [in]  salt_len     The size of the input keying material.
1547
 * \param [in]  z            The input shared secret (message to cmac).
1548
 * \param [in]  zSz          The size of the input shared secret.
1549
 * \param [in]  fixedInfo    The fixed information in the KDF.
1550
 * \param [in]  fixedInfoSz  The size of the fixed information.
1551
 * \param [out] output       The buffer to store the derived secret.
1552
 * \param [in]  outputSz     The desired size of the output secret.
1553
 * \param [in]  heap         The heap hint.
1554
 * \param [in]  devId        The device id.
1555
 *
1556
 * \return 0 if the KDF operation is successful.
1557
 * \return BAD_FUNC_ARG if the input parameters are invalid.
1558
 * \return negative error code if the KDF operation fails.
1559
 */
1560
int wc_KDA_KDF_twostep_cmac(const byte * salt, word32 salt_len,
1561
                            const byte* z, word32 zSz,
1562
                            const byte* fixedInfo, word32 fixedInfoSz,
1563
                            byte* output, word32 outputSz,
1564
                            void * heap, int devId)
1565
{
1566
    byte   Key_kdk[WC_AES_BLOCK_SIZE]; /* key derivation key*/
1567
    word32 kdk_len = sizeof(Key_kdk);
1568
    word32 tag_len = WC_AES_BLOCK_SIZE;
1569
    #ifdef WOLFSSL_SMALL_STACK
1570
    Cmac * cmac = NULL;
1571
    #else
1572
    Cmac   cmac[1];
1573
    #endif /* WOLFSSL_SMALL_STACK */
1574
    int    ret = 0;
1575
1576
    /* screen out bad args. */
1577
    switch (salt_len) {
1578
    case AES_128_KEY_SIZE:
1579
    case AES_192_KEY_SIZE:
1580
    case AES_256_KEY_SIZE:
1581
        break; /* salt ok */
1582
    default:
1583
        WOLFSSL_MSG_EX("KDF twostep cmac: bad salt len: %d", salt_len);
1584
        return BAD_FUNC_ARG;
1585
    }
1586
1587
    if (zSz == 0 || outputSz == 0) {
1588
        return BAD_FUNC_ARG;
1589
    }
1590
1591
    if (fixedInfoSz > 0 && fixedInfo == NULL) {
1592
        return BAD_FUNC_ARG;
1593
    }
1594
1595
    if (salt == NULL || z == NULL || output == NULL) {
1596
        return BAD_FUNC_ARG;
1597
    }
1598
1599
    #ifdef WOLF_CRYPTO_CB
1600
    /* Try crypto callback first for complete operation */
1601
    if (devId != INVALID_DEVID) {
1602
         ret = wc_CryptoCb_Kdf_TwostepCmac(salt, salt_len, z, zSz,
1603
                                           fixedInfo, fixedInfoSz,
1604
                                           output, outputSz, devId);
1605
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
1606
            return ret;
1607
        }
1608
        /* fall-through when unavailable */
1609
    }
1610
    #endif
1611
1612
    XMEMSET(Key_kdk, 0, kdk_len);
1613
#ifdef WOLFSSL_CHECK_MEM_ZERO
1614
    /* register at the 0 baseline; every exit below checks it */
1615
    wc_MemZero_Add("wc_KDA_KDF_twostep_cmac Key_kdk", Key_kdk,
1616
        sizeof(Key_kdk));
1617
#endif
1618
1619
    #ifdef WOLFSSL_SMALL_STACK
1620
    cmac = (Cmac*)XMALLOC(sizeof(Cmac), heap, DYNAMIC_TYPE_CMAC);
1621
    if (cmac == NULL) {
1622
    #ifdef WOLFSSL_CHECK_MEM_ZERO
1623
        wc_MemZero_Check(Key_kdk, sizeof(Key_kdk));
1624
    #endif
1625
        return MEMORY_E;
1626
    }
1627
    #ifdef WOLFSSL_CHECK_MEM_ZERO
1628
    /* Aes part is checked by wc_AesFree. */
1629
    wc_MemZero_Add("wc_KDA_KDF_twostep_cmac cmac",
1630
        ((unsigned char *)cmac) + sizeof(Aes), sizeof(Cmac) - sizeof(Aes));
1631
    #endif
1632
    #endif
1633
1634
    /* step 1: cmac extract */
1635
    ret = wc_AesCmacGenerate_ex(cmac, Key_kdk, &tag_len, z, zSz, salt, salt_len,
1636
                                heap, devId);
1637
1638
    if (ret == 0) {
1639
        if (tag_len != WC_AES_BLOCK_SIZE) {
1640
            WOLFSSL_MSG_EX("KDF twostep cmac: got %d, expected %d\n",
1641
                           tag_len, WC_AES_BLOCK_SIZE);
1642
            ret = BUFFER_E;
1643
        }
1644
    }
1645
1646
    #ifdef WOLFSSL_SMALL_STACK
1647
    if (cmac) {
1648
        ForceZero(cmac, sizeof(Cmac));
1649
        XFREE(cmac, heap, DYNAMIC_TYPE_CMAC);
1650
        cmac = NULL;
1651
    }
1652
    #endif /* WOLFSSL_SMALL_STACK */
1653
1654
    /* step 2: cmac expand with SP 800-108 PRF.
1655
     * If AES-128-CMAC, AES-192-CMAC, or AES-256-CMAC is used in the
1656
     * randomness extraction step, then only AES-128-CMAC is used in the
1657
     * key-expansion step.*/
1658
    if (ret == 0) {
1659
        ret = wc_KDA_KDF_PRF_cmac(Key_kdk, kdk_len, fixedInfo, fixedInfoSz,
1660
                                  output, outputSz, WC_CMAC_AES,
1661
                                  heap, devId);
1662
    }
1663
1664
    /* always force zero the intermediate key derivation key. */
1665
    ForceZero(Key_kdk, sizeof(Key_kdk));
1666
#ifdef WOLFSSL_CHECK_MEM_ZERO
1667
    wc_MemZero_Check(Key_kdk, sizeof(Key_kdk));
1668
#endif
1669
1670
    return ret;
1671
}
1672
1673
/**
1674
 * \brief Performs the KDF PRF as specified in SP800-108r1.
1675
 * At the moment, only AES-CMAC counter mode (section 4.1) is
1676
 * implemented. This implementation uses a 32 bit counter.
1677
 *
1678
 * \param [in]  Kin       The input keying material.
1679
 * \param [in]  KinSz     The size of the input keying material.
1680
 * \param [in]  fixedInfo The fixed information to be included in the KDF.
1681
 * \param [in]  fixedInfo Sz The size of the fixed information.
1682
 * \param [out] Kout      The output keying material.
1683
 * \param [in]  KoutSz    The desired size of the output key.
1684
 * \param [in]  type      The type of cmac.
1685
 * \param [in]  heap      The heap hint.
1686
 * \param [in]  devId     The device id.
1687
 *
1688
 * \return 0 if the KDF operation is successful.
1689
 * \return BAD_FUNC_ARG if the input parameters are invalid.
1690
 * \return negative error code if the KDF operation fails.
1691
 */
1692
int wc_KDA_KDF_PRF_cmac(const byte* Kin, word32 KinSz,
1693
                        const byte* fixedInfo, word32 fixedInfoSz,
1694
                        byte* Kout, word32 KoutSz, CmacType type,
1695
                        void * heap, int devId)
1696
{
1697
    word32 len_rem = KoutSz;
1698
    word32 tag_len = WC_AES_BLOCK_SIZE;
1699
    word32 counter = 1; /* init counter to 1, from SP800-108r1 section 4.1 */
1700
    #ifdef WOLFSSL_SMALL_STACK
1701
    Cmac * cmac = NULL;
1702
    #else
1703
    Cmac   cmac[1];
1704
    #endif /* WOLFSSL_SMALL_STACK */
1705
    byte   counterBuf[4];
1706
    int    ret = 0;
1707
1708
    /* screen out bad args. */
1709
    if (Kin == NULL || Kout == NULL) {
1710
        return BAD_FUNC_ARG;
1711
    }
1712
1713
    if (fixedInfoSz > 0 && fixedInfo == NULL) {
1714
        return BAD_FUNC_ARG;
1715
    }
1716
1717
    if (KoutSz == 0) {
1718
        return BAD_FUNC_ARG;
1719
    }
1720
1721
    /* Only AES-CMAC PRF supported at this time. */
1722
    if (type != WC_CMAC_AES) {
1723
        return BAD_FUNC_ARG;
1724
    }
1725
1726
    #ifdef WOLFSSL_SMALL_STACK
1727
    cmac = (Cmac*)XMALLOC(sizeof(Cmac), heap, DYNAMIC_TYPE_CMAC);
1728
    if (cmac == NULL) {
1729
        return MEMORY_E;
1730
    }
1731
    #ifdef WOLFSSL_CHECK_MEM_ZERO
1732
    /* Aes part is checked by wc_AesFree. */
1733
    wc_MemZero_Add("wc_KDA_KDF_PRF_cmac cmac",
1734
        ((unsigned char *)cmac) + sizeof(Aes), sizeof(Cmac) - sizeof(Aes));
1735
    #endif
1736
    #endif
1737
1738
    while (len_rem >= WC_AES_BLOCK_SIZE) {
1739
        int cmac_inited = 0;
1740
        /* cmac in place in block size increments */
1741
        c32toa(counter, counterBuf);
1742
        #ifdef WOLFSSL_DEBUG_KDF
1743
        WOLFSSL_MSG_EX("wc_KDA_KDF_PRF_cmac: in place: "
1744
                       "len_rem = %d, i = %d", len_rem, counter);
1745
        #endif /* WOLFSSL_DEBUG_KDF */
1746
1747
        ret = wc_InitCmac_ex(cmac, Kin, KinSz, WC_CMAC_AES, NULL, heap, devId);
1748
1749
        if (ret == 0) {
1750
            cmac_inited = 1;
1751
            ret = wc_CmacUpdate(cmac, counterBuf, sizeof(counterBuf));
1752
        }
1753
1754
        if (ret == 0 && fixedInfoSz > 0) {
1755
            ret = wc_CmacUpdate(cmac, fixedInfo, fixedInfoSz);
1756
        }
1757
1758
        if (ret == 0) {
1759
            ret = wc_CmacFinalNoFree(cmac, &Kout[KoutSz - len_rem], &tag_len);
1760
1761
            if (tag_len != WC_AES_BLOCK_SIZE) {
1762
                WOLFSSL_MSG_EX("wc_KDA_KDF_PRF_cmac: got %d, expected %d\n",
1763
                               tag_len, WC_AES_BLOCK_SIZE);
1764
                ret = BUFFER_E;
1765
            }
1766
        }
1767
1768
        if (cmac_inited)
1769
            (void)wc_CmacFree(cmac);
1770
1771
        if (ret != 0) { break; }
1772
1773
        len_rem -= WC_AES_BLOCK_SIZE;
1774
        ++counter;
1775
    }
1776
1777
    if (ret == 0 && len_rem) {
1778
        /* cmac the last little bit that wouldn't fit in a block size. */
1779
        byte rem[WC_AES_BLOCK_SIZE];
1780
        int cmac_inited = 0;
1781
        XMEMSET(rem, 0, sizeof(rem));
1782
    #ifdef WOLFSSL_CHECK_MEM_ZERO
1783
        wc_MemZero_Add("wc_KDA_KDF_PRF_cmac rem", rem, sizeof(rem));
1784
    #endif
1785
        c32toa(counter, counterBuf);
1786
1787
        #ifdef WOLFSSL_DEBUG_KDF
1788
        WOLFSSL_MSG_EX("wc_KDA_KDF_PRF_cmac: last little bit: "
1789
                       "len_rem = %d, i = %d", len_rem, counter);
1790
        #endif /* WOLFSSL_DEBUG_KDF */
1791
1792
        ret = wc_InitCmac_ex(cmac, Kin, KinSz, WC_CMAC_AES, NULL, heap, devId);
1793
1794
        if (ret == 0) {
1795
            cmac_inited = 1;
1796
            ret = wc_CmacUpdate(cmac, counterBuf, sizeof(counterBuf));
1797
        }
1798
1799
        if (ret == 0 && fixedInfoSz > 0) {
1800
            ret = wc_CmacUpdate(cmac, fixedInfo, fixedInfoSz);
1801
        }
1802
1803
        if (ret == 0) {
1804
            ret = wc_CmacFinalNoFree(cmac, rem, &tag_len);
1805
1806
            if (tag_len != WC_AES_BLOCK_SIZE) {
1807
                WOLFSSL_MSG_EX("wc_KDA_KDF_PRF_cmac: got %d, expected %d\n",
1808
                               tag_len, WC_AES_BLOCK_SIZE);
1809
                ret = BUFFER_E;
1810
            }
1811
        }
1812
1813
        if (ret == 0) {
1814
            XMEMCPY(&Kout[KoutSz - len_rem], rem, len_rem);
1815
        }
1816
1817
        ForceZero(rem, sizeof(rem));
1818
    #ifdef WOLFSSL_CHECK_MEM_ZERO
1819
        wc_MemZero_Check(rem, sizeof(rem));
1820
    #endif
1821
        if (cmac_inited)
1822
            (void)wc_CmacFree(cmac);
1823
    }
1824
1825
    #ifdef WOLFSSL_SMALL_STACK
1826
    if (cmac) {
1827
        ForceZero(cmac, sizeof(Cmac));
1828
        XFREE(cmac, heap, DYNAMIC_TYPE_CMAC);
1829
        cmac = NULL;
1830
    }
1831
    #endif /* WOLFSSL_SMALL_STACK */
1832
1833
    if (ret != 0) {
1834
        ForceZero(Kout, KoutSz);
1835
    }
1836
1837
    return ret;
1838
}
1839
#endif /* HAVE_CMAC_KDF */
1840
1841
#endif /* NO_KDF */