Coverage Report

Created: 2026-10-31 07:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl-openssl-api/src/ssl_crypto.c
Line
Count
Source
1
/* ssl_crypto.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
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
23
24
#ifndef WOLFSSL_SSL_CRYPTO_INCLUDED
25
    #ifndef WOLFSSL_IGNORE_FILE_WARN
26
        #warning ssl_crypto.c does not need to be compiled separately from ssl.c
27
    #endif
28
#else
29
30
/*******************************************************************************
31
 * START OF Digest APIs
32
 ******************************************************************************/
33
34
#ifdef OPENSSL_EXTRA
35
#ifndef NO_MD4
36
/* Initialize MD4 hash operation.
37
 *
38
 * @param [in, out] md4  MD4 context object.
39
 */
40
void wolfSSL_MD4_Init(WOLFSSL_MD4_CTX* md4)
41
96
{
42
    /* Ensure WOLFSSL_MD4_CTX is big enough for wolfCrypt Md4. */
43
96
    WOLFSSL_ASSERT_SIZEOF_GE(md4->buffer, wc_Md4);
44
45
96
    WOLFSSL_ENTER("MD4_Init");
46
47
    /* Initialize wolfCrypt MD4 object. */
48
96
    wc_InitMd4((wc_Md4*)md4);
49
96
}
50
51
/* Update MD4 hash with data.
52
 *
53
 * @param [in, out] md4   MD4 context object.
54
 * @param [in]      data  Data to be hashed.
55
 * @param [in]      len   Length of data in bytes.
56
 */
57
void wolfSSL_MD4_Update(WOLFSSL_MD4_CTX* md4, const void* data,
58
    unsigned long len)
59
302
{
60
302
    WOLFSSL_ENTER("MD4_Update");
61
62
    /* Update wolfCrypt MD4 object with data. */
63
302
    wc_Md4Update((wc_Md4*)md4, (const byte*)data, (word32)len);
64
302
}
65
66
/* Finalize MD4 hash and return output.
67
 *
68
 * @param [out]     digest  Hash output.
69
 *                          Must be able to hold MD4_DIGEST_SIZE bytes.
70
 * @param [in, out] md4     MD4 context object.
71
 */
72
void wolfSSL_MD4_Final(unsigned char* digest, WOLFSSL_MD4_CTX* md4)
73
96
{
74
96
    WOLFSSL_ENTER("MD4_Final");
75
76
    /* Finalize wolfCrypt MD4 hash into digest. */
77
96
    wc_Md4Final((wc_Md4*)md4, digest);
78
96
}
79
80
#endif /* NO_MD4 */
81
#endif /* OPENSSL_EXTRA */
82
83
#if defined(OPENSSL_EXTRA) || defined(HAVE_CURL)
84
#ifndef NO_MD5
85
/* Initialize MD5 hash operation.
86
 *
87
 * @param [in, out] md5  MD5 context object.
88
 * @return  1 on success.
89
 * @return  0 when md5 is NULL.
90
 */
91
int wolfSSL_MD5_Init(WOLFSSL_MD5_CTX* md5)
92
62
{
93
    /* Ensure WOLFSSL_MD5_CTX is big enough for wolfCrypt wc_Md5. */
94
62
    WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_MD5_CTX, wc_Md5);
95
96
62
    WOLFSSL_ENTER("MD5_Init");
97
98
    /* Initialize wolfCrypt MD5 object. */
99
62
    return wc_InitMd5((wc_Md5*)md5) == 0;
100
62
}
101
102
/* Update MD5 hash with data.
103
 *
104
 * @param [in, out] md5    MD5 context object.
105
 * @param [in]      input  Data to be hashed.
106
 * @param [in]      sz     Length of data in bytes.
107
 * @return  1 on success.
108
 * @return  0 when md5 is NULL.
109
 */
110
int wolfSSL_MD5_Update(WOLFSSL_MD5_CTX* md5, const void* input,
111
    unsigned long sz)
112
272
{
113
272
    WOLFSSL_ENTER("MD5_Update");
114
115
    /* Update wolfCrypt MD5 object with data. */
116
272
    return wc_Md5Update((wc_Md5*)md5, (const byte*)input, (word32)sz) == 0;
117
272
}
118
119
/* Finalize MD5 hash and return output.
120
 *
121
 * @param [out]     digest  Hash output.
122
 *                          Must be able to hold MD5_DIGEST_SIZE bytes.
123
 * @param [in, out] md5     MD5 context object.
124
 * @return  1 on success.
125
 * @return  0 when md5 or output is NULL.
126
 */
127
int wolfSSL_MD5_Final(byte* output, WOLFSSL_MD5_CTX* md5)
128
62
{
129
62
    int ret;
130
131
62
    WOLFSSL_ENTER("MD5_Final");
132
133
    /* Finalize wolfCrypt MD5 hash into output. */
134
62
    ret = (wc_Md5Final((wc_Md5*)md5, output) == 0);
135
    /* Free resources here, as OpenSSL API doesn't include MD5_Free(). */
136
62
    wc_Md5Free((wc_Md5*)md5);
137
138
62
    return ret;
139
62
}
140
141
/* Apply MD5 transformation to the data.
142
 *
143
 * 'data' has words reversed in this function when big endian.
144
 *
145
 * @param [in, out] md5   MD5 context object.
146
 * @param [in, out] data  One block of data to be hashed.
147
 * @return  1 on success.
148
 * @return  0 when md5 or data is NULL.
149
 */
150
int wolfSSL_MD5_Transform(WOLFSSL_MD5_CTX* md5, const unsigned char* data)
151
0
{
152
0
    WOLFSSL_ENTER("MD5_Transform");
153
154
#if defined(BIG_ENDIAN_ORDER)
155
    /* Byte reversal done outside transform. */
156
    if ((md5 != NULL) && (data != NULL)) {
157
        ByteReverseWords((word32*)data, (word32*)data, WC_MD5_BLOCK_SIZE);
158
    }
159
#endif
160
    /* Transform block of data with wolfCrypt MD5 object. */
161
0
    return wc_Md5Transform((wc_Md5*)md5, data) == 0;
162
0
}
163
164
/* One shot MD5 hash of data.
165
 *
166
 * When hash is null, a static buffer of MD5_DIGEST_SIZE is used.
167
 * When the static buffer is used this function is not thread safe.
168
 *
169
 * @param [in]  data  Data to be hashed.
170
 * @param [in]  len   Length of data in bytes.
171
 * @param [out] hash  Buffer to hold digest. May be NULL.
172
 *                    Must be able to hold MD5_DIGEST_SIZE bytes.
173
 * @return  Buffer holding hash on success.
174
 * @return  NULL when hashing fails.
175
 */
176
unsigned char* wolfSSL_MD5(const unsigned char* data, size_t len,
177
    unsigned char* hash)
178
0
{
179
    /* Buffer to use when hash is NULL. */
180
0
    static unsigned char dgst[WC_MD5_DIGEST_SIZE];
181
182
0
    WOLFSSL_ENTER("wolfSSL_MD5");
183
184
    /* Ensure buffer available for digest result. */
185
0
    if (hash == NULL) {
186
0
        hash = dgst;
187
0
    }
188
    /* One shot MD5 hash with wolfCrypt. */
189
0
    if (wc_Md5Hash(data, (word32)len, hash) != 0) {
190
0
        WOLFSSL_MSG("wc_Md5Hash error");
191
0
        hash = NULL;
192
0
    }
193
194
0
    return hash;
195
0
}
196
#endif /* !NO_MD5 */
197
198
#ifndef NO_SHA
199
/* Initialize SHA hash operation.
200
 *
201
 * @param [in, out] sha  SHA context object.
202
 * @return  1 on success.
203
 * @return  0 when sha is NULL.
204
 */
205
int wolfSSL_SHA_Init(WOLFSSL_SHA_CTX* sha)
206
34
{
207
    /* Ensure WOLFSSL_SHA_CTX is big enough for wolfCrypt wc_Sha. */
208
34
    WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_SHA_CTX, wc_Sha);
209
210
34
    WOLFSSL_ENTER("SHA_Init");
211
212
    /* Initialize wolfCrypt SHA object. */
213
34
    return wc_InitSha((wc_Sha*)sha) == 0;
214
34
}
215
216
/* Update SHA hash with data.
217
 *
218
 * @param [in, out] sha    SHA context object.
219
 * @param [in]      input  Data to be hashed.
220
 * @param [in]      sz     Length of data in bytes.
221
 * @return  1 on success.
222
 * @return  0 when md5 is NULL.
223
 */
224
int wolfSSL_SHA_Update(WOLFSSL_SHA_CTX* sha, const void* input,
225
    unsigned long sz)
226
161
{
227
161
    WOLFSSL_ENTER("SHA_Update");
228
229
    /* Update wolfCrypt SHA object with data. */
230
161
    return wc_ShaUpdate((wc_Sha*)sha, (const byte*)input, (word32)sz) == 0;
231
161
}
232
233
/* Finalize SHA hash and return output.
234
 *
235
 * @param [out]     output  Hash output.
236
 *                          Must be able to hold SHA_DIGEST_SIZE bytes.
237
 * @param [in, out] sha     SHA context object.
238
 * @return  1 on success.
239
 * @return  0 when sha or output is NULL.
240
 */
241
int wolfSSL_SHA_Final(byte* output, WOLFSSL_SHA_CTX* sha)
242
34
{
243
34
    int ret;
244
245
34
    WOLFSSL_ENTER("SHA_Final");
246
247
    /* Finalize wolfCrypt SHA hash into output. */
248
34
    ret = (wc_ShaFinal((wc_Sha*)sha, output) == 0);
249
    /* Free resources here, as OpenSSL API doesn't include SHA_Free(). */
250
34
    wc_ShaFree((wc_Sha*)sha);
251
252
34
    return ret;
253
34
}
254
255
#if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
256
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2)))
257
/* Apply SHA transformation to the data.
258
 *
259
 * 'data' has words reversed in this function when little endian.
260
 *
261
 * @param [in, out] sha   SHA context object.
262
 * @param [in, out] data  One block of data to be hashed.
263
 * @return  1 on success.
264
 * @return  0 when sha or data is NULL.
265
 */
266
int wolfSSL_SHA_Transform(WOLFSSL_SHA_CTX* sha, const unsigned char* data)
267
0
{
268
0
    WOLFSSL_ENTER("SHA_Transform");
269
270
0
#if defined(LITTLE_ENDIAN_ORDER)
271
    /* Byte reversal done outside transform. */
272
0
    if ((sha != NULL) && (data != NULL)) {
273
0
        ByteReverseWords((word32*)data, (word32*)data, WC_SHA_BLOCK_SIZE);
274
0
    }
275
0
#endif
276
    /* Transform block of data with wolfCrypt SHA object. */
277
0
    return wc_ShaTransform((wc_Sha*)sha, data) == 0;
278
0
}
279
#endif
280
281
/* Initialize SHA-1 hash operation.
282
 *
283
 * @param [in, out] sha  SHA context object.
284
 * @return  1 on success.
285
 * @return  0 when sha is NULL.
286
 */
287
int wolfSSL_SHA1_Init(WOLFSSL_SHA_CTX* sha)
288
0
{
289
0
    WOLFSSL_ENTER("SHA1_Init");
290
291
0
    return wolfSSL_SHA_Init(sha);
292
0
}
293
294
295
/* Update SHA-1 hash with data.
296
 *
297
 * @param [in, out] sha    SHA context object.
298
 * @param [in]      input  Data to be hashed.
299
 * @param [in]      sz     Length of data in bytes.
300
 * @return  1 on success.
301
 * @return  0 when sha is NULL.
302
 */
303
int wolfSSL_SHA1_Update(WOLFSSL_SHA_CTX* sha, const void* input,
304
    unsigned long sz)
305
0
{
306
0
    WOLFSSL_ENTER("SHA1_Update");
307
308
0
    return wolfSSL_SHA_Update(sha, input, sz);
309
0
}
310
311
/* Finalize SHA-1 hash and return output.
312
 *
313
 * @param [out]     output  Hash output.
314
 *                          Must be able to hold SHA_DIGEST_SIZE bytes.
315
 * @param [in, out] sha     SHA context object.
316
 * @return  1 on success.
317
 * @return  0 when sha or output is NULL.
318
 */
319
int wolfSSL_SHA1_Final(byte* output, WOLFSSL_SHA_CTX* sha)
320
0
{
321
0
    WOLFSSL_ENTER("SHA1_Final");
322
323
0
    return wolfSSL_SHA_Final(output, sha);
324
0
}
325
326
#if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
327
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2)))
328
/* Apply SHA-1 transformation to the data.
329
 *
330
 * 'data' has words reversed in this function when little endian.
331
 *
332
 * @param [in, out] sha   SHA context object.
333
 * @param [in, out] data  One block of data to be hashed.
334
 * @return  1 on success.
335
 * @return  0 when sha or data is NULL.
336
 */
337
int wolfSSL_SHA1_Transform(WOLFSSL_SHA_CTX* sha, const unsigned char* data)
338
0
{
339
0
   WOLFSSL_ENTER("SHA1_Transform");
340
341
0
   return wolfSSL_SHA_Transform(sha, data);
342
0
}
343
#endif
344
#endif /* !NO_SHA */
345
346
#ifndef NO_SHA256
347
#ifdef WOLFSSL_SHA224
348
/* Initialize SHA-224 hash operation.
349
 *
350
 * @param [in, out] sha224  SHA-224 context object.
351
 * @return  1 on success.
352
 * @return  0 when sha224 is NULL.
353
 */
354
int wolfSSL_SHA224_Init(WOLFSSL_SHA224_CTX* sha224)
355
66
{
356
    /* Ensure WOLFSSL_SHA224_CTX is big enough for wolfCrypt wc_Sha224. */
357
66
    WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_SHA224_CTX, wc_Sha224);
358
359
66
    WOLFSSL_ENTER("SHA224_Init");
360
361
    /* Initialize wolfCrypt SHA-224 object. */
362
66
    return wc_InitSha224((wc_Sha224*)sha224) == 0;
363
66
}
364
365
/* Update SHA-224 hash with data.
366
 *
367
 * @param [in, out] sha224  SHA-224 context object.
368
 * @param [in]      input   Data to be hashed.
369
 * @param [in]      sz      Length of data in bytes.
370
 * @return  1 on success.
371
 * @return  0 when sha224 is NULL.
372
 */
373
int wolfSSL_SHA224_Update(WOLFSSL_SHA224_CTX* sha224, const void* input,
374
    unsigned long sz)
375
131
{
376
131
    WOLFSSL_ENTER("SHA224_Update");
377
378
    /* Update wolfCrypt SHA-224 object with data. */
379
131
    return wc_Sha224Update((wc_Sha224*)sha224, (const byte*)input, (word32)sz)
380
131
        == 0;
381
131
}
382
383
/* Finalize SHA-224 hash and return output.
384
 *
385
 * @param [out]     output  Hash output.
386
 *                          Must be able to hold SHA224_DIGEST_SIZE bytes.
387
 * @param [in, out] sha224  SHA-224 context object.
388
 * @return  1 on success.
389
 * @return  0 when sha224 or output is NULL.
390
 */
391
int wolfSSL_SHA224_Final(byte* output, WOLFSSL_SHA224_CTX* sha224)
392
66
{
393
66
    int ret;
394
395
66
    WOLFSSL_ENTER("SHA224_Final");
396
397
    /* Finalize wolfCrypt SHA-224 hash into output. */
398
66
    ret = (wc_Sha224Final((wc_Sha224*)sha224, output) == 0);
399
    /* Free resources here, as OpenSSL API doesn't include SHA224_Free(). */
400
66
    wc_Sha224Free((wc_Sha224*)sha224);
401
402
66
    return ret;
403
66
}
404
405
#endif /* WOLFSSL_SHA224 */
406
407
/* Initialize SHA-256 hash operation.
408
 *
409
 * @param [in, out] sha256  SHA-256 context object.
410
 * @return  1 on success.
411
 * @return  0 when sha256 is NULL.
412
 */
413
int wolfSSL_SHA256_Init(WOLFSSL_SHA256_CTX* sha256)
414
45
{
415
    /* Ensure WOLFSSL_SHA256_CTX is big enough for wolfCrypt wc_Sha256. */
416
45
    WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_SHA256_CTX, wc_Sha256);
417
418
45
    WOLFSSL_ENTER("SHA256_Init");
419
420
    /* Initialize wolfCrypt SHA-256 object. */
421
45
    return wc_InitSha256((wc_Sha256*)sha256) == 0;
422
45
}
423
424
/* Update SHA-256 hash with data.
425
 *
426
 * @param [in, out] sha256  SHA-256 context object.
427
 * @param [in]      input   Data to be hashed.
428
 * @param [in]      sz      Length of data in bytes.
429
 * @return  1 on success.
430
 * @return  0 when sha256 is NULL.
431
 */
432
int wolfSSL_SHA256_Update(WOLFSSL_SHA256_CTX* sha256, const void* input,
433
    unsigned long sz)
434
145
{
435
145
    WOLFSSL_ENTER("SHA256_Update");
436
437
    /* Update wolfCrypt SHA-256 object with data. */
438
145
    return wc_Sha256Update((wc_Sha256*)sha256, (const byte*)input, (word32)sz)
439
145
        == 0;
440
145
}
441
442
/* Finalize SHA-256 hash and return output.
443
 *
444
 * @param [out]     output  Hash output.
445
 *                          Must be able to hold SHA256_DIGEST_SIZE bytes.
446
 * @param [in, out] sha256  SHA-256 context object.
447
 * @return  1 on success.
448
 * @return  0 when sha256 or output is NULL.
449
 */
450
int wolfSSL_SHA256_Final(byte* output, WOLFSSL_SHA256_CTX* sha256)
451
45
{
452
45
    int ret;
453
454
45
    WOLFSSL_ENTER("SHA256_Final");
455
456
    /* Finalize wolfCrypt SHA-256 hash into output. */
457
45
    ret = (wc_Sha256Final((wc_Sha256*)sha256, output) == 0);
458
    /* Free resources here, as OpenSSL API doesn't include SHA256_Free(). */
459
45
    wc_Sha256Free((wc_Sha256*)sha256);
460
461
45
    return ret;
462
45
}
463
464
#if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
465
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))) && \
466
    !defined(WOLFSSL_DEVCRYPTO_HASH) && !defined(WOLFSSL_AFALG_HASH) && \
467
    !defined(WOLFSSL_KCAPI_HASH) /* doesn't support direct transform */
468
/* Apply SHA-256 transformation to the data.
469
 *
470
 * 'data' has words reversed in this function when little endian.
471
 *
472
 * @param [in, out] sha256  SHA256 context object.
473
 * @param [in, out] data    One block of data to be hashed.
474
 * @return  1 on success.
475
 * @return  0 when sha256 or data is NULL.
476
 */
477
int wolfSSL_SHA256_Transform(WOLFSSL_SHA256_CTX* sha256,
478
    const unsigned char* data)
479
0
{
480
0
    WOLFSSL_ENTER("SHA256_Transform");
481
482
0
#if defined(LITTLE_ENDIAN_ORDER)
483
    /* Byte reversal done outside transform. */
484
0
    if ((sha256 != NULL) && (data != NULL)) {
485
0
        ByteReverseWords((word32*)data, (word32*)data, WC_SHA256_BLOCK_SIZE);
486
0
    }
487
0
#endif
488
    /* Transform block of data with wolfCrypt SHA-256 object. */
489
0
    return wc_Sha256Transform((wc_Sha256*)sha256, data) == 0;
490
0
}
491
#endif
492
#endif /* !NO_SHA256 */
493
494
#ifdef WOLFSSL_SHA384
495
496
/* Initialize SHA-384 hash operation.
497
 *
498
 * @param [in, out] sha384  SHA-384 context object.
499
 * @return  1 on success.
500
 * @return  0 when sha384 is NULL.
501
 */
502
int wolfSSL_SHA384_Init(WOLFSSL_SHA384_CTX* sha384)
503
52
{
504
    /* Ensure WOLFSSL_SHA384_CTX is big enough for wolfCrypt wc_Sha384. */
505
52
    WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_SHA384_CTX, wc_Sha384);
506
507
52
    WOLFSSL_ENTER("SHA384_Init");
508
509
    /* Initialize wolfCrypt SHA-384 object. */
510
52
    return wc_InitSha384((wc_Sha384*)sha384) == 0;
511
52
}
512
513
/* Update SHA-384 hash with data.
514
 *
515
 * @param [in, out] sha384  SHA-384 context object.
516
 * @param [in]      input   Data to be hashed.
517
 * @param [in]      sz      Length of data in bytes.
518
 * @return  1 on success.
519
 * @return  0 when sha384 is NULL.
520
 */
521
int wolfSSL_SHA384_Update(WOLFSSL_SHA384_CTX* sha384, const void* input,
522
    unsigned long sz)
523
139
{
524
139
    WOLFSSL_ENTER("SHA384_Update");
525
526
    /* Update wolfCrypt SHA-384 object with data. */
527
139
    return wc_Sha384Update((wc_Sha384*)sha384, (const byte*)input, (word32)sz)
528
139
        == 0;
529
139
}
530
531
/* Finalize SHA-384 hash and return output.
532
 *
533
 * @param [out]     output  Hash output.
534
 *                          Must be able to hold SHA384_DIGEST_SIZE bytes.
535
 * @param [in, out] sha384  SHA-384 context object.
536
 * @return  1 on success.
537
 * @return  0 when sha384 or output is NULL.
538
 */
539
int wolfSSL_SHA384_Final(byte* output, WOLFSSL_SHA384_CTX* sha384)
540
52
{
541
52
    int ret;
542
543
52
    WOLFSSL_ENTER("SHA384_Final");
544
545
    /* Finalize wolfCrypt SHA-384 hash into output. */
546
52
    ret = (wc_Sha384Final((wc_Sha384*)sha384, output) == 0);
547
    /* Free resources here, as OpenSSL API doesn't include SHA384_Free(). */
548
52
    wc_Sha384Free((wc_Sha384*)sha384);
549
550
52
    return ret;
551
52
}
552
#endif /* WOLFSSL_SHA384 */
553
554
#ifdef WOLFSSL_SHA512
555
/* Initialize SHA-512 hash operation.
556
 *
557
 * @param [in, out] sha512  SHA-512 context object.
558
 * @return  1 on success.
559
 * @return  0 when sha512 is NULL.
560
 */
561
int wolfSSL_SHA512_Init(WOLFSSL_SHA512_CTX* sha512)
562
48
{
563
    /* Ensure WOLFSSL_SHA512_CTX is big enough for wolfCrypt wc_Sha512. */
564
48
    WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_SHA512_CTX, wc_Sha512);
565
566
48
    WOLFSSL_ENTER("SHA512_Init");
567
568
    /* Initialize wolfCrypt SHA-512 object. */
569
48
    return wc_InitSha512((wc_Sha512*)sha512) == 0;
570
48
}
571
572
/* Update SHA-512 hash with data.
573
 *
574
 * @param [in, out] sha512  SHA-512 context object.
575
 * @param [in]      input   Data to be hashed.
576
 * @param [in]      sz      Length of data in bytes.
577
 * @return  1 on success.
578
 * @return  0 when sha512 is NULL.
579
 */
580
int wolfSSL_SHA512_Update(WOLFSSL_SHA512_CTX* sha512, const void* input,
581
    unsigned long sz)
582
98
{
583
98
    WOLFSSL_ENTER("SHA512_Update");
584
585
    /* Update wolfCrypt SHA-512 object with data. */
586
98
    return wc_Sha512Update((wc_Sha512*)sha512, (const byte*)input, (word32)sz)
587
98
        == 0;
588
98
}
589
590
/* Finalize SHA-512 hash and return output.
591
 *
592
 * @param [out]     output  Hash output.
593
 *                          Must be able to hold SHA512_DIGEST_SIZE bytes.
594
 * @param [in, out] sha512  SHA-512 context object.
595
 * @return  1 on success.
596
 * @return  0 when sha512 or output is NULL.
597
 */
598
int wolfSSL_SHA512_Final(byte* output, WOLFSSL_SHA512_CTX* sha512)
599
48
{
600
48
    int ret;
601
602
48
    WOLFSSL_ENTER("SHA512_Final");
603
604
    /* Finalize wolfCrypt SHA-512 hash into output. */
605
48
    ret = (wc_Sha512Final((wc_Sha512*)sha512, output) == 0);
606
    /* Free resources here, as OpenSSL API doesn't include SHA512_Free(). */
607
48
    wc_Sha512Free((wc_Sha512*)sha512);
608
609
48
    return ret;
610
48
}
611
612
#if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
613
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))) && \
614
    !defined(WOLFSSL_KCAPI_HASH) /* doesn't support direct transform */ && \
615
    !defined(WOLF_CRYPTO_CB_ONLY_SHA512) /* no wc_Sha512Transform in CB-only */
616
/* Apply SHA-512 transformation to the data.
617
 *
618
 * @param [in, out] sha512  SHA512 context object.
619
 * @param [in]      data    One block of data to be hashed.
620
 * @return  1 on success.
621
 * @return  0 when sha512 or data is NULL.
622
 */
623
int wolfSSL_SHA512_Transform(WOLFSSL_SHA512_CTX* sha512,
624
    const unsigned char* data)
625
0
{
626
0
    WOLFSSL_ENTER("SHA512_Transform");
627
628
    /* Transform block of data with wolfCrypt SHA-512 object. */
629
0
    return wc_Sha512Transform((wc_Sha512*)sha512, data) == 0;
630
0
}
631
#endif /* !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \
632
          (HAVE_FIPS_VERSION > 2)) && !WOLFSSL_KCAPI_HASH */
633
634
#if !defined(WOLFSSL_NOSHA512_224) && \
635
   (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 3)) && !defined(HAVE_SELFTEST)
636
/* Initialize SHA-512-224 hash operation.
637
 *
638
 * @param [in, out] sha512  SHA-512-224 context object.
639
 * @return  1 on success.
640
 * @return  0 when sha512 is NULL.
641
 */
642
int wolfSSL_SHA512_224_Init(WOLFSSL_SHA512_224_CTX* sha512)
643
0
{
644
0
    WOLFSSL_ENTER("SHA512_224_Init");
645
646
    /* Initialize wolfCrypt SHA-512-224 object. */
647
0
    return wc_InitSha512_224((wc_Sha512*)sha512) == 0;
648
0
}
649
650
/* Update SHA-512-224 hash with data.
651
 *
652
 * @param [in, out] sha512  SHA-512-224 context object.
653
 * @param [in]      input   Data to be hashed.
654
 * @param [in]      sz      Length of data in bytes.
655
 * @return  1 on success.
656
 * @return  0 when sha512 is NULL.
657
 */
658
int wolfSSL_SHA512_224_Update(WOLFSSL_SHA512_224_CTX* sha512, const void* input,
659
    unsigned long sz)
660
0
{
661
0
    WOLFSSL_ENTER("SHA512_224_Update");
662
663
    /* Update wolfCrypt SHA-512-224 object with data. */
664
0
    return wc_Sha512_224Update((wc_Sha512*)sha512, (const byte*)input,
665
0
        (word32)sz) == 0;
666
0
}
667
668
/* Finalize SHA-512-224 hash and return output.
669
 *
670
 * @param [out]     output  Hash output.
671
 *                          Must be able to hold SHA224_DIGEST_SIZE bytes.
672
 * @param [in, out] sha512  SHA-512-224 context object.
673
 * @return  1 on success.
674
 * @return  0 when sha512 or output is NULL.
675
 */
676
int wolfSSL_SHA512_224_Final(byte* output, WOLFSSL_SHA512_224_CTX* sha512)
677
0
{
678
0
    int ret;
679
680
0
    WOLFSSL_ENTER("SHA512_224_Final");
681
682
    /* Finalize wolfCrypt SHA-512-224 hash into output. */
683
0
    ret = (wc_Sha512_224Final((wc_Sha512*)sha512, output) == 0);
684
    /* Free resources here, as OpenSSL API doesn't include SHA512_224_Free(). */
685
0
    wc_Sha512_224Free((wc_Sha512*)sha512);
686
687
0
    return ret;
688
0
}
689
690
#if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
691
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))) && \
692
    !defined(WOLF_CRYPTO_CB_ONLY_SHA512) /* no wc_Sha512_224Transform in CB-only */
693
/* Apply SHA-512-224 transformation to the data.
694
 *
695
 * @param [in, out] sha512  SHA512 context object.
696
 * @param [in]      data    One block of data to be hashed.
697
 * @return  1 on success.
698
 * @return  0 when sha512 or data is NULL.
699
 */
700
int wolfSSL_SHA512_224_Transform(WOLFSSL_SHA512_CTX* sha512,
701
    const unsigned char* data)
702
0
{
703
0
    WOLFSSL_ENTER("SHA512_224_Transform");
704
705
    /* Transform block of data with wolfCrypt SHA-512-224 object. */
706
0
    return wc_Sha512_224Transform((wc_Sha512*)sha512, data) == 0;
707
0
}
708
#endif /* !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \
709
          (HAVE_FIPS_VERSION > 2)) */
710
711
#endif /* !WOLFSSL_NOSHA512_224 && !FIPS ... */
712
713
#if !defined(WOLFSSL_NOSHA512_256) && \
714
   (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 3)) && !defined(HAVE_SELFTEST)
715
/* Initialize SHA-512-256 hash operation.
716
 *
717
 * @param [in, out] sha512  SHA-512-256 context object.
718
 * @return  1 on success.
719
 * @return  0 when sha512 is NULL.
720
 */
721
int wolfSSL_SHA512_256_Init(WOLFSSL_SHA512_256_CTX* sha)
722
0
{
723
0
    WOLFSSL_ENTER("SHA512_256_Init");
724
725
    /* Initialize wolfCrypt SHA-512-256 object. */
726
0
    return wc_InitSha512_256((wc_Sha512*)sha) == 0;
727
0
}
728
729
/* Update SHA-512-256 hash with data.
730
 *
731
 * @param [in, out] sha512  SHA-512-256 context object.
732
 * @param [in]      input   Data to be hashed.
733
 * @param [in]      sz      Length of data in bytes.
734
 * @return  1 on success.
735
 * @return  0 when sha512 is NULL.
736
 */
737
int wolfSSL_SHA512_256_Update(WOLFSSL_SHA512_256_CTX* sha512, const void* input,
738
    unsigned long sz)
739
0
{
740
0
    WOLFSSL_ENTER("SHA512_256_Update");
741
742
    /* Update wolfCrypt SHA-512-256 object with data. */
743
0
    return wc_Sha512_256Update((wc_Sha512*)sha512, (const byte*)input,
744
0
        (word32)sz) == 0;
745
0
}
746
747
/* Finalize SHA-512-256 hash and return output.
748
 *
749
 * @param [out]     output  Hash output.
750
 *                          Must be able to hold SHA256_DIGEST_SIZE bytes.
751
 * @param [in, out] sha512  SHA-512-256 context object.
752
 * @return  1 on success.
753
 * @return  0 when sha512 or output is NULL.
754
 */
755
int wolfSSL_SHA512_256_Final(byte* output, WOLFSSL_SHA512_256_CTX* sha512)
756
0
{
757
0
    int ret;
758
759
0
    WOLFSSL_ENTER("SHA512_256_Final");
760
761
    /* Finalize wolfCrypt SHA-512-256 hash into output. */
762
0
    ret = (wc_Sha512_256Final((wc_Sha512*)sha512, output) == 0);
763
    /* Free resources here, as OpenSSL API doesn't include SHA512_256_Free(). */
764
0
    wc_Sha512_224Free((wc_Sha512*)sha512);
765
766
0
    return ret;
767
0
}
768
769
#if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
770
    (defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION > 2))) && \
771
    !defined(WOLF_CRYPTO_CB_ONLY_SHA512) /* no wc_Sha512_256Transform in CB-only */
772
/* Apply SHA-512-256 transformation to the data.
773
 *
774
 * @param [in, out] sha512  SHA512 context object.
775
 * @param [in]      data    One block of data to be hashed.
776
 * @return  1 on success.
777
 * @return  0 when sha512 or data is NULL.
778
 */
779
int wolfSSL_SHA512_256_Transform(WOLFSSL_SHA512_CTX* sha512,
780
    const unsigned char* data)
781
0
{
782
0
    WOLFSSL_ENTER("SHA512_256_Transform");
783
784
    /* Transform block of data with wolfCrypt SHA-512-256 object. */
785
0
    return wc_Sha512_256Transform((wc_Sha512*)sha512, data) == 0;
786
0
}
787
#endif /* !defined(HAVE_FIPS) || (defined(HAVE_FIPS_VERSION) && \
788
          (HAVE_FIPS_VERSION > 2)) */
789
#endif /* !WOLFSSL_NOSHA512_256 && !FIPS ... */
790
#endif /* WOLFSSL_SHA512 */
791
792
#ifdef WOLFSSL_SHA3
793
#ifndef WOLFSSL_NOSHA3_224
794
/* Initialize SHA3-224 hash operation.
795
 *
796
 * @param [in, out] sha3_224  SHA3-224 context object.
797
 * @return  1 on success.
798
 * @return  0 when sha3_224 is NULL.
799
 */
800
int wolfSSL_SHA3_224_Init(WOLFSSL_SHA3_224_CTX* sha3_224)
801
0
{
802
    /* Ensure WOLFSSL_SHA3_224_CTX is big enough for wolfCrypt wc_Sha3. */
803
0
    WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_SHA3_224_CTX, wc_Sha3);
804
805
0
    WOLFSSL_ENTER("SHA3_224_Init");
806
807
    /* Initialize wolfCrypt SHA3-224 object. */
808
0
    return wc_InitSha3_224((wc_Sha3*)sha3_224, NULL, INVALID_DEVID) == 0;
809
0
}
810
811
/* Update SHA3-224 hash with data.
812
 *
813
 * @param [in, out] sha3   SHA3-224 context object.
814
 * @param [in]      input  Data to be hashed.
815
 * @param [in]      sz     Length of data in bytes.
816
 * @return  1 on success.
817
 * @return  0 when sha3 is NULL.
818
 */
819
int wolfSSL_SHA3_224_Update(WOLFSSL_SHA3_224_CTX* sha3, const void* input,
820
    unsigned long sz)
821
0
{
822
0
    WOLFSSL_ENTER("SHA3_224_Update");
823
824
    /* Update wolfCrypt SHA3-224 object with data. */
825
0
    return wc_Sha3_224_Update((wc_Sha3*)sha3, (const byte*)input, (word32)sz)
826
0
        == 0;
827
0
}
828
829
/* Finalize SHA3-224 hash and return output.
830
 *
831
 * @param [out]     output  Hash output.
832
 *                          Must be able to hold SHA3_224_DIGEST_SIZE bytes.
833
 * @param [in, out] sha3    SHA3-224 context object.
834
 * @return  1 on success.
835
 * @return  0 when sha3 or output is NULL.
836
 */
837
int wolfSSL_SHA3_224_Final(byte* output, WOLFSSL_SHA3_224_CTX* sha3)
838
0
{
839
0
    int ret;
840
841
0
    WOLFSSL_ENTER("SHA3_224_Final");
842
843
    /* Finalize wolfCrypt SHA3-224 hash into output. */
844
0
    ret = (wc_Sha3_224_Final((wc_Sha3*)sha3, output) == 0);
845
    /* Free resources here, as OpenSSL API doesn't include SHA3_224_Free(). */
846
0
    wc_Sha3_224_Free((wc_Sha3*)sha3);
847
848
0
    return ret;
849
0
}
850
#endif /* WOLFSSL_NOSHA3_224 */
851
852
#ifndef WOLFSSL_NOSHA3_256
853
/* Initialize SHA3-256 hash operation.
854
 *
855
 * @param [in, out] sha3_256  SHA3-256 context object.
856
 * @return  1 on success.
857
 * @return  0 when sha3_256 is NULL.
858
 */
859
int wolfSSL_SHA3_256_Init(WOLFSSL_SHA3_256_CTX* sha3_256)
860
0
{
861
    /* Ensure WOLFSSL_SHA3_256_CTX is big enough for wolfCrypt wc_Sha3. */
862
0
    WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_SHA3_256_CTX, wc_Sha3);
863
864
0
    WOLFSSL_ENTER("SHA3_256_Init");
865
866
    /* Initialize wolfCrypt SHA3-256 object. */
867
0
    return wc_InitSha3_256((wc_Sha3*)sha3_256, NULL, INVALID_DEVID) == 0;
868
0
}
869
870
/* Update SHA3-256 hash with data.
871
 *
872
 * @param [in, out] sha3   SHA3-256 context object.
873
 * @param [in]      input  Data to be hashed.
874
 * @param [in]      sz     Length of data in bytes.
875
 * @return  1 on success.
876
 * @return  0 when sha3 is NULL.
877
 */
878
int wolfSSL_SHA3_256_Update(WOLFSSL_SHA3_256_CTX* sha3, const void* input,
879
    unsigned long sz)
880
0
{
881
0
    WOLFSSL_ENTER("SHA3_256_Update");
882
883
    /* Update wolfCrypt SHA3-256 object with data. */
884
0
    return wc_Sha3_256_Update((wc_Sha3*)sha3, (const byte*)input, (word32)sz)
885
0
        == 0;
886
0
}
887
888
/* Finalize SHA3-256 hash and return output.
889
 *
890
 * @param [out]     output  Hash output.
891
 *                          Must be able to hold SHA3_256_DIGEST_SIZE bytes.
892
 * @param [in, out] sha3    SHA3-256 context object.
893
 * @return  1 on success.
894
 * @return  0 when sha3 or output is NULL.
895
 */
896
int wolfSSL_SHA3_256_Final(byte* output, WOLFSSL_SHA3_256_CTX* sha3)
897
0
{
898
0
    int ret;
899
900
0
    WOLFSSL_ENTER("SHA3_256_Final");
901
902
    /* Finalize wolfCrypt SHA3-256 hash into output. */
903
0
    ret = (wc_Sha3_256_Final((wc_Sha3*)sha3, output) == 0);
904
    /* Free resources here, as OpenSSL API doesn't include SHA3_256_Free(). */
905
0
    wc_Sha3_256_Free((wc_Sha3*)sha3);
906
907
0
    return ret;
908
0
}
909
#endif /* WOLFSSL_NOSHA3_256 */
910
911
#ifndef WOLFSSL_NOSHA3_384
912
/* Initialize SHA3-384 hash operation.
913
 *
914
 * @param [in, out] sha3_384  SHA3-384 context object.
915
 * @return  1 on success.
916
 * @return  0 when sha3_384 is NULL.
917
 */
918
int wolfSSL_SHA3_384_Init(WOLFSSL_SHA3_384_CTX* sha3_384)
919
0
{
920
    /* Ensure WOLFSSL_SHA3_384_CTX is big enough for wolfCrypt wc_Sha3. */
921
0
    WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_SHA3_384_CTX, wc_Sha3);
922
923
0
    WOLFSSL_ENTER("SHA3_384_Init");
924
925
    /* Initialize wolfCrypt SHA3-384 object. */
926
0
    return wc_InitSha3_384((wc_Sha3*)sha3_384, NULL, INVALID_DEVID) == 0;
927
0
}
928
929
/* Update SHA3-384 hash with data.
930
 *
931
 * @param [in, out] sha3   SHA3-384 context object.
932
 * @param [in]      input  Data to be hashed.
933
 * @param [in]      sz     Length of data in bytes.
934
 * @return  1 on success.
935
 * @return  0 when sha3 is NULL.
936
 */
937
int wolfSSL_SHA3_384_Update(WOLFSSL_SHA3_384_CTX* sha3, const void* input,
938
    unsigned long sz)
939
0
{
940
0
    WOLFSSL_ENTER("SHA3_384_Update");
941
942
    /* Update wolfCrypt SHA3-384 object with data. */
943
0
    return wc_Sha3_384_Update((wc_Sha3*)sha3, (const byte*)input, (word32)sz)
944
0
        == 0;
945
0
}
946
947
/* Finalize SHA3-384 hash and return output.
948
 *
949
 * @param [out]     output  Hash output.
950
 *                          Must be able to hold SHA3_384_DIGEST_SIZE bytes.
951
 * @param [in, out] sha3    SHA3-384 context object.
952
 * @return  1 on success.
953
 * @return  0 when sha3 or output is NULL.
954
 */
955
int wolfSSL_SHA3_384_Final(byte* output, WOLFSSL_SHA3_384_CTX* sha3)
956
0
{
957
0
    int ret;
958
959
0
    WOLFSSL_ENTER("SHA3_384_Final");
960
961
    /* Finalize wolfCrypt SHA3-384 hash into output. */
962
0
    ret = (wc_Sha3_384_Final((wc_Sha3*)sha3, output) == 0);
963
    /* Free resources here, as OpenSSL API doesn't include SHA3_384_Free(). */
964
0
    wc_Sha3_384_Free((wc_Sha3*)sha3);
965
966
0
    return ret;
967
0
}
968
#endif /* WOLFSSL_NOSHA3_384 */
969
970
#ifndef WOLFSSL_NOSHA3_512
971
/* Initialize SHA3-512 hash operation.
972
 *
973
 * @param [in, out] sha3_512  SHA3-512 context object.
974
 * @return  1 on success.
975
 * @return  0 when sha3_512 is NULL.
976
 */
977
int wolfSSL_SHA3_512_Init(WOLFSSL_SHA3_512_CTX* sha3_512)
978
0
{
979
    /* Ensure WOLFSSL_SHA3_512_CTX is big enough for wolfCrypt wc_Sha3. */
980
0
    WOLFSSL_ASSERT_SIZEOF_GE(WOLFSSL_SHA3_512_CTX, wc_Sha3);
981
982
0
    WOLFSSL_ENTER("SHA3_512_Init");
983
984
    /* Initialize wolfCrypt SHA3-512 object. */
985
0
    return wc_InitSha3_512((wc_Sha3*)sha3_512, NULL, INVALID_DEVID) == 0;
986
0
}
987
988
/* Update SHA3-512 hash with data.
989
 *
990
 * @param [in, out] sha3   SHA3-512 context object.
991
 * @param [in]      input  Data to be hashed.
992
 * @param [in]      sz     Length of data in bytes.
993
 * @return  1 on success.
994
 * @return  0 when sha3 is NULL.
995
 */
996
int wolfSSL_SHA3_512_Update(WOLFSSL_SHA3_512_CTX* sha3, const void* input,
997
    unsigned long sz)
998
0
{
999
0
    WOLFSSL_ENTER("SHA3_512_Update");
1000
1001
    /* Update wolfCrypt SHA3-512 object with data. */
1002
0
    return wc_Sha3_512_Update((wc_Sha3*)sha3, (const byte*)input, (word32)sz)
1003
0
        == 0;
1004
0
}
1005
1006
/* Finalize SHA3-512 hash and return output.
1007
 *
1008
 * @param [out]     output  Hash output.
1009
 *                          Must be able to hold SHA3_512_DIGEST_SIZE bytes.
1010
 * @param [in, out] sha3    SHA3-512 context object.
1011
 * @return  1 on success.
1012
 * @return  0 when sha3 or output is NULL.
1013
 */
1014
int wolfSSL_SHA3_512_Final(byte* output, WOLFSSL_SHA3_512_CTX* sha3)
1015
0
{
1016
0
    int ret;
1017
1018
0
    WOLFSSL_ENTER("SHA3_512_Final");
1019
1020
    /* Finalize wolfCrypt SHA3-512 hash into output. */
1021
0
    ret = (wc_Sha3_512_Final((wc_Sha3*)sha3, output) == 0);
1022
    /* Free resources here, as OpenSSL API doesn't include SHA3_512_Free(). */
1023
0
    wc_Sha3_512_Free((wc_Sha3*)sha3);
1024
1025
0
    return ret;
1026
0
}
1027
#endif /* WOLFSSL_NOSHA3_512 */
1028
#endif /* WOLFSSL_SHA3 */
1029
#endif /* OPENSSL_EXTRA || HAVE_CURL */
1030
1031
#if defined(OPENSSL_EXTRA) || defined(HAVE_LIGHTY) || \
1032
    defined(WOLFSSL_MYSQL_COMPATIBLE) || defined(HAVE_STUNNEL) || \
1033
    defined(WOLFSSL_NGINX) || defined(HAVE_POCO_LIB) || \
1034
    defined(WOLFSSL_HAPROXY)
1035
1036
#ifndef NO_SHA
1037
/* One shot SHA1 hash of data.
1038
 *
1039
 * When hash is null, a static buffer of SHA_DIGEST_SIZE is used.
1040
 * When the static buffer is used this function is not thread safe.
1041
 *
1042
 * @param [in]  data  Data to hash.
1043
 * @param [in]  len   Size of data in bytes.
1044
 * @param [out] hash  Buffer to hold digest. May be NULL.
1045
 *                    Must be able to hold SHA_DIGEST_SIZE bytes.
1046
 * @return  Buffer holding hash on success.
1047
 * @return  NULL when hashing fails.
1048
 */
1049
unsigned char* wolfSSL_SHA1(const unsigned char* data, size_t len,
1050
    unsigned char* hash)
1051
0
{
1052
    /* Buffer to use when hash is NULL. */
1053
0
    static byte dgst[WC_SHA_DIGEST_SIZE];
1054
0
    WC_DECLARE_VAR(sha, wc_Sha, 1, 0);
1055
0
    int ret = 0;
1056
1057
0
    WOLFSSL_ENTER("wolfSSL_SHA1");
1058
1059
    /* Use static buffer if none passed in. */
1060
0
    if (hash == NULL) {
1061
0
        WOLFSSL_MSG("STATIC BUFFER BEING USED. wolfSSL_SHA1 IS NOT "
1062
0
                    "THREAD SAFE WHEN hash == NULL");
1063
0
        hash = dgst;
1064
0
    }
1065
1066
    /* Allocate dynamic memory for a wolfSSL SHA object. */
1067
0
    WC_ALLOC_VAR_EX(sha, wc_Sha, 1, NULL, DYNAMIC_TYPE_DIGEST,
1068
0
        ret=MEMORY_E);
1069
1070
0
    if (ret == 0) {
1071
        /* Initialize wolfCrypt SHA object. */
1072
0
        ret = wc_InitSha_ex(sha, NULL, INVALID_DEVID);
1073
0
        if (ret != 0) {
1074
0
            WOLFSSL_MSG("SHA1 Init failed");
1075
0
            hash = NULL;
1076
0
        }
1077
0
    }
1078
0
    if (ret == 0) {
1079
        /* Update wolfCrypt SHA object with data. */
1080
0
        ret = wc_ShaUpdate(sha, (const byte*)data, (word32)len);
1081
0
        if (ret != 0) {
1082
0
            WOLFSSL_MSG("SHA1 Update failed");
1083
0
            hash = NULL;
1084
0
        }
1085
1086
0
        if (ret == 0) {
1087
            /* Finalize wolfCrypt SHA hash into hash. */
1088
0
            ret = wc_ShaFinal(sha, hash);
1089
0
            if (ret != 0) {
1090
0
                WOLFSSL_MSG("SHA1 Final failed");
1091
0
                hash = NULL;
1092
0
            }
1093
0
        }
1094
        /* Dispose of dynamic memory associated with SHA object. */
1095
0
        wc_ShaFree(sha);
1096
0
    }
1097
1098
0
    WC_FREE_VAR_EX(sha, NULL, DYNAMIC_TYPE_DIGEST);
1099
0
    return hash;
1100
0
}
1101
#endif /* ! NO_SHA */
1102
1103
#ifdef WOLFSSL_SHA224
1104
/* One shot SHA-224 hash of data.
1105
 *
1106
 * When hash is null, a static buffer of SHA224_DIGEST_SIZE is used.
1107
 * When the static buffer is used this function is not thread safe.
1108
 *
1109
 * @param [in]  data  Data to hash.
1110
 * @param [in]  len   Size of data in bytes.
1111
 * @param [out] hash  Buffer to hold digest. May be NULL.
1112
 *                    Must be able to hold SHA224_DIGEST_SIZE bytes.
1113
 * @return  Buffer holding hash on success.
1114
 * @return  NULL when hashing fails.
1115
 */
1116
unsigned char* wolfSSL_SHA224(const unsigned char* data, size_t len,
1117
    unsigned char* hash)
1118
0
{
1119
    /* Buffer to use when hash is NULL. */
1120
0
    static byte dgst[WC_SHA224_DIGEST_SIZE];
1121
0
    WC_DECLARE_VAR(sha224, wc_Sha224, 1, 0);
1122
0
    int ret = 0;
1123
1124
0
    WOLFSSL_ENTER("wolfSSL_SHA224");
1125
1126
    /* Use static buffer if none passed in. */
1127
0
    if (hash == NULL) {
1128
0
        WOLFSSL_MSG("STATIC BUFFER BEING USED. wolfSSL_SHA224 IS NOT "
1129
0
                    "THREAD SAFE WHEN hash == NULL");
1130
0
        hash = dgst;
1131
0
    }
1132
1133
    /* Allocate dynamic memory for a wolfSSL SHA-224 object. */
1134
0
    WC_ALLOC_VAR_EX(sha224, wc_Sha224, 1, NULL, DYNAMIC_TYPE_DIGEST,
1135
0
        ret=MEMORY_E);
1136
1137
0
    if (ret == 0) {
1138
        /* Initialize wolfCrypt SHA224 object. */
1139
0
        ret = wc_InitSha224_ex(sha224, NULL, INVALID_DEVID);
1140
0
        if (ret != 0) {
1141
0
            WOLFSSL_MSG("SHA224 Init failed");
1142
0
            hash = NULL;
1143
0
        }
1144
0
    }
1145
0
    if (ret == 0) {
1146
        /* Update wolfCrypt SHA-224 object with data. */
1147
0
        ret = wc_Sha224Update(sha224, (const byte*)data, (word32)len);
1148
0
        if (ret != 0) {
1149
0
            WOLFSSL_MSG("SHA224 Update failed");
1150
0
            hash = NULL;
1151
0
        }
1152
1153
0
        if (ret == 0) {
1154
            /* Finalize wolfCrypt SHA-224 hash into hash. */
1155
0
            ret = wc_Sha224Final(sha224, hash);
1156
0
            if (ret != 0) {
1157
0
                WOLFSSL_MSG("SHA224 Final failed");
1158
0
                hash = NULL;
1159
0
            }
1160
0
        }
1161
        /* Dispose of dynamic memory associated with SHA-224 object. */
1162
0
        wc_Sha224Free(sha224);
1163
0
    }
1164
1165
0
    WC_FREE_VAR_EX(sha224, NULL, DYNAMIC_TYPE_DIGEST);
1166
0
    return hash;
1167
0
}
1168
#endif
1169
1170
#ifndef NO_SHA256
1171
/* One shot SHA-256 hash of data.
1172
 *
1173
 * When hash is null, a static buffer of SHA256_DIGEST_SIZE is used.
1174
 * When the static buffer is used this function is not thread safe.
1175
 *
1176
 * @param [in]  data  Data to hash.
1177
 * @param [in]  len   Size of data in bytes.
1178
 * @param [out] hash  Buffer to hold digest. May be NULL.
1179
 *                    Must be able to hold SHA256_DIGEST_SIZE bytes.
1180
 * @return  Buffer holding hash on success.
1181
 * @return  NULL when hashing fails.
1182
 */
1183
unsigned char* wolfSSL_SHA256(const unsigned char* data, size_t len,
1184
    unsigned char* hash)
1185
52
{
1186
    /* Buffer to use when hash is NULL. */
1187
52
    static byte dgst[WC_SHA256_DIGEST_SIZE];
1188
52
    WC_DECLARE_VAR(sha256, wc_Sha256, 1, 0);
1189
52
    int ret = 0;
1190
1191
52
    WOLFSSL_ENTER("wolfSSL_SHA256");
1192
1193
    /* Use static buffer if none passed in. */
1194
52
    if (hash == NULL) {
1195
0
        WOLFSSL_MSG("STATIC BUFFER BEING USED. wolfSSL_SHA256 IS NOT "
1196
0
                    "THREAD SAFE WHEN hash == NULL");
1197
0
        hash = dgst;
1198
0
    }
1199
1200
    /* Allocate dynamic memory for a wolfSSL SHA-256 object. */
1201
52
    WC_ALLOC_VAR_EX(sha256, wc_Sha256, 1, NULL, DYNAMIC_TYPE_DIGEST,
1202
52
        ret=MEMORY_E);
1203
1204
52
    if (ret == 0) {
1205
        /* Initialize wolfCrypt SHA256 object. */
1206
52
        ret = wc_InitSha256_ex(sha256, NULL, INVALID_DEVID);
1207
52
        if (ret != 0) {
1208
0
            WOLFSSL_MSG("SHA256 Init failed");
1209
0
            hash = NULL;
1210
0
        }
1211
52
    }
1212
52
    if (ret == 0) {
1213
        /* Update wolfCrypt SHA-256 object with data. */
1214
52
        ret = wc_Sha256Update(sha256, (const byte*)data, (word32)len);
1215
52
        if (ret != 0) {
1216
0
            WOLFSSL_MSG("SHA256 Update failed");
1217
0
            hash = NULL;
1218
0
        }
1219
1220
52
        if (ret == 0) {
1221
            /* Finalize wolfCrypt SHA-256 hash into hash. */
1222
52
            ret = wc_Sha256Final(sha256, hash);
1223
52
            if (ret != 0) {
1224
0
                WOLFSSL_MSG("SHA256 Final failed");
1225
0
                hash = NULL;
1226
0
            }
1227
52
        }
1228
        /* Dispose of dynamic memory associated with SHA-256 object. */
1229
52
        wc_Sha256Free(sha256);
1230
52
    }
1231
1232
52
    WC_FREE_VAR_EX(sha256, NULL, DYNAMIC_TYPE_DIGEST);
1233
52
    return hash;
1234
52
}
1235
#endif /* ! NO_SHA256 */
1236
1237
#ifdef WOLFSSL_SHA384
1238
/* One shot SHA-384 hash of data.
1239
 *
1240
 * When hash is null, a static buffer of SHA384_DIGEST_SIZE is used.
1241
 * When the static buffer is used this function is not thread safe.
1242
 *
1243
 * @param [in]  data  Data to hash.
1244
 * @param [in]  len   Size of data in bytes.
1245
 * @param [out] hash  Buffer to hold digest. May be NULL.
1246
 *                    Must be able to hold SHA384_DIGEST_SIZE bytes.
1247
 * @return  Buffer holding hash on success.
1248
 * @return  NULL when hashing fails.
1249
 */
1250
unsigned char* wolfSSL_SHA384(const unsigned char* data, size_t len,
1251
    unsigned char* hash)
1252
0
{
1253
    /* Buffer to use when hash is NULL. */
1254
0
    static byte dgst[WC_SHA384_DIGEST_SIZE];
1255
0
    WC_DECLARE_VAR(sha384, wc_Sha384, 1, 0);
1256
0
    int ret = 0;
1257
1258
0
    WOLFSSL_ENTER("wolfSSL_SHA384");
1259
1260
    /* Use static buffer if none passed in. */
1261
0
    if (hash == NULL) {
1262
0
        WOLFSSL_MSG("STATIC BUFFER BEING USED. wolfSSL_SHA384 IS NOT "
1263
0
                    "THREAD SAFE WHEN hash == NULL");
1264
0
        hash = dgst;
1265
0
    }
1266
1267
    /* Allocate dynamic memory for a wolfSSL SHA-384 object. */
1268
0
    WC_ALLOC_VAR_EX(sha384, wc_Sha384, 1, NULL, DYNAMIC_TYPE_DIGEST,
1269
0
        ret=MEMORY_E);
1270
1271
0
    if (ret == 0) {
1272
        /* Initialize wolfCrypt SHA384 object. */
1273
0
        ret = wc_InitSha384_ex(sha384, NULL, INVALID_DEVID);
1274
0
        if (ret != 0) {
1275
0
            WOLFSSL_MSG("SHA384 Init failed");
1276
0
            hash = NULL;
1277
0
        }
1278
0
    }
1279
0
    if (ret == 0) {
1280
        /* Update wolfCrypt SHA-384 object with data. */
1281
0
        ret = wc_Sha384Update(sha384, (const byte*)data, (word32)len);
1282
0
        if (ret != 0) {
1283
0
            WOLFSSL_MSG("SHA384 Update failed");
1284
0
            hash = NULL;
1285
0
        }
1286
1287
0
        if (ret == 0) {
1288
            /* Finalize wolfCrypt SHA-384 hash into hash. */
1289
0
            ret = wc_Sha384Final(sha384, hash);
1290
0
            if (ret != 0) {
1291
0
                WOLFSSL_MSG("SHA384 Final failed");
1292
0
                hash = NULL;
1293
0
            }
1294
0
        }
1295
        /* Dispose of dynamic memory associated with SHA-384 object. */
1296
0
        wc_Sha384Free(sha384);
1297
0
    }
1298
1299
0
    WC_FREE_VAR_EX(sha384, NULL, DYNAMIC_TYPE_DIGEST);
1300
0
    return hash;
1301
0
}
1302
#endif /* WOLFSSL_SHA384  */
1303
1304
#if defined(WOLFSSL_SHA512)
1305
/* One shot SHA-512 hash of data.
1306
 *
1307
 * When hash is null, a static buffer of SHA512_DIGEST_SIZE is used.
1308
 * When the static buffer is used this function is not thread safe.
1309
 *
1310
 * @param [in]  data  Data to hash.
1311
 * @param [in]  len   Size of data in bytes.
1312
 * @param [out] hash  Buffer to hold digest. May be NULL.
1313
 *                    Must be able to hold SHA512_DIGEST_SIZE bytes.
1314
 * @return  Buffer holding hash on success.
1315
 * @return  NULL when hashing fails.
1316
 */
1317
unsigned char* wolfSSL_SHA512(const unsigned char* data, size_t len,
1318
    unsigned char* hash)
1319
0
{
1320
    /* Buffer to use when hash is NULL. */
1321
0
    static byte dgst[WC_SHA512_DIGEST_SIZE];
1322
0
    WC_DECLARE_VAR(sha512, wc_Sha512, 1, 0);
1323
0
    int ret = 0;
1324
1325
0
    WOLFSSL_ENTER("wolfSSL_SHA512");
1326
1327
    /* Use static buffer if none passed in. */
1328
0
    if (hash == NULL) {
1329
0
        WOLFSSL_MSG("STATIC BUFFER BEING USED. wolfSSL_SHA512 IS NOT "
1330
0
                    "THREAD SAFE WHEN hash == NULL");
1331
0
        hash = dgst;
1332
0
    }
1333
1334
    /* Allocate dynamic memory for a wolfSSL SHA-512 object. */
1335
0
    WC_ALLOC_VAR_EX(sha512, wc_Sha512, 1, NULL, DYNAMIC_TYPE_DIGEST,
1336
0
        ret=MEMORY_E);
1337
1338
0
    if (ret == 0) {
1339
        /* Initialize wolfCrypt SHA512 object. */
1340
0
        ret = wc_InitSha512_ex(sha512, NULL, INVALID_DEVID);
1341
0
        if (ret != 0) {
1342
0
            WOLFSSL_MSG("SHA512 Init failed");
1343
0
            hash = NULL;
1344
0
        }
1345
0
    }
1346
0
    if (ret == 0) {
1347
        /* Update wolfCrypt SHA-512 object with data. */
1348
0
        ret = wc_Sha512Update(sha512, (const byte*)data, (word32)len);
1349
0
        if (ret != 0) {
1350
0
            WOLFSSL_MSG("SHA512 Update failed");
1351
0
            hash = NULL;
1352
0
        }
1353
1354
0
        if (ret == 0) {
1355
            /* Finalize wolfCrypt SHA-512 hash into hash. */
1356
0
            ret = wc_Sha512Final(sha512, hash);
1357
0
            if (ret != 0) {
1358
0
                WOLFSSL_MSG("SHA512 Final failed");
1359
0
                hash = NULL;
1360
0
            }
1361
0
        }
1362
        /* Dispose of dynamic memory associated with SHA-512 object. */
1363
0
        wc_Sha512Free(sha512);
1364
0
    }
1365
1366
0
    WC_FREE_VAR_EX(sha512, NULL, DYNAMIC_TYPE_DIGEST);
1367
0
    return hash;
1368
0
}
1369
#endif /* WOLFSSL_SHA512 */
1370
#endif /* OPENSSL_EXTRA || HAVE_LIGHTY || WOLFSSL_MYSQL_COMPATIBLE ||
1371
        * HAVE_STUNNEL || WOLFSSL_NGINX || HAVE_POCO_LIB || WOLFSSL_HAPROXY */
1372
1373
/*******************************************************************************
1374
 * END OF Digest APIs
1375
 ******************************************************************************/
1376
1377
/*******************************************************************************
1378
 * START OF HMAC API
1379
 ******************************************************************************/
1380
1381
/* _Internal Hmac object initialization. */
1382
0
#define _HMAC_Init _InitHmac
1383
1384
#if defined(OPENSSL_EXTRA) && !defined(WOLFCRYPT_ONLY)
1385
1386
/*
1387
 * Helper Functions
1388
 */
1389
1390
/* Copy a wolfSSL HMAC object.
1391
 *
1392
 * Requires that hash structures have no dynamic parts to them.
1393
 *
1394
 * @param [out] dst  Copy into this object.
1395
 * @param [in]  src  Copy from this object.
1396
 * @return  1 on success.
1397
 * @return  0 on failure.
1398
 */
1399
int wolfSSL_HmacCopy(Hmac* dst, Hmac* src)
1400
227
{
1401
227
    void* heap;
1402
227
    int ret = 1;
1403
1404
227
#ifndef HAVE_FIPS
1405
227
    heap = src->heap;
1406
#else
1407
    heap = NULL;
1408
#endif
1409
1410
    /* Initialize the destination object to reset state. */
1411
227
    if (wc_HmacInit(dst, heap, 0) != 0) {
1412
0
        ret = 0;
1413
0
    }
1414
1415
227
    if (ret == 1) {
1416
227
        int rc;
1417
1418
        /* Copy the digest object based on the MAC type. */
1419
227
        switch (src->macType) {
1420
0
    #ifndef NO_MD5
1421
19
        case WC_MD5:
1422
19
            rc = wc_Md5Copy(&src->hash.md5, &dst->hash.md5);
1423
        #ifdef WOLFSSL_HMAC_COPY_HASH
1424
            if (rc == 0) {
1425
                rc = wc_Md5Copy(&src->i_hash.md5, &dst->i_hash.md5);
1426
            }
1427
            if (rc == 0) {
1428
                rc = wc_Md5Copy(&src->o_hash.md5, &dst->o_hash.md5);
1429
            }
1430
        #endif
1431
19
            break;
1432
0
    #endif /* !NO_MD5 */
1433
1434
0
    #ifndef NO_SHA
1435
27
        case WC_SHA:
1436
27
            rc = wc_ShaCopy(&src->hash.sha, &dst->hash.sha);
1437
        #ifdef WOLFSSL_HMAC_COPY_HASH
1438
            if (rc == 0) {
1439
                rc = wc_ShaCopy(&src->i_hash.sha, &dst->i_hash.sha);
1440
            }
1441
            if (rc == 0) {
1442
                rc = wc_ShaCopy(&src->o_hash.sha, &dst->o_hash.sha);
1443
            }
1444
        #endif
1445
27
            break;
1446
0
    #endif /* !NO_SHA */
1447
1448
0
    #ifdef WOLFSSL_SHA224
1449
46
        case WC_SHA224:
1450
46
            rc = wc_Sha224Copy(&src->hash.sha224, &dst->hash.sha224);
1451
        #ifdef WOLFSSL_HMAC_COPY_HASH
1452
            if (rc == 0) {
1453
                rc = wc_Sha224Copy(&src->i_hash.sha224, &dst->i_hash.sha224);
1454
            }
1455
            if (rc == 0) {
1456
                rc = wc_Sha224Copy(&src->o_hash.sha224, &dst->o_hash.sha224);
1457
            }
1458
        #endif
1459
46
            break;
1460
0
    #endif /* WOLFSSL_SHA224 */
1461
1462
0
    #ifndef NO_SHA256
1463
41
        case WC_SHA256:
1464
41
            rc = wc_Sha256Copy(&src->hash.sha256, &dst->hash.sha256);
1465
        #ifdef WOLFSSL_HMAC_COPY_HASH
1466
            if (rc == 0) {
1467
                rc = wc_Sha256Copy(&src->i_hash.sha256, &dst->i_hash.sha256);
1468
            }
1469
            if (rc == 0) {
1470
                rc = wc_Sha256Copy(&src->o_hash.sha256, &dst->o_hash.sha256);
1471
            }
1472
        #endif
1473
41
            break;
1474
0
    #endif /* !NO_SHA256 */
1475
1476
0
    #ifdef WOLFSSL_SHA384
1477
34
        case WC_SHA384:
1478
34
            rc = wc_Sha384Copy(&src->hash.sha384, &dst->hash.sha384);
1479
        #ifdef WOLFSSL_HMAC_COPY_HASH
1480
            if (rc == 0) {
1481
                rc = wc_Sha384Copy(&src->i_hash.sha384, &dst->i_hash.sha384);
1482
            }
1483
            if (rc == 0) {
1484
                rc = wc_Sha384Copy(&src->o_hash.sha384, &dst->o_hash.sha384);
1485
            }
1486
        #endif
1487
34
            break;
1488
0
    #endif /* WOLFSSL_SHA384 */
1489
0
    #ifdef WOLFSSL_SHA512
1490
60
        case WC_SHA512:
1491
60
            rc = wc_Sha512Copy(&src->hash.sha512, &dst->hash.sha512);
1492
        #ifdef WOLFSSL_HMAC_COPY_HASH
1493
            if (rc == 0) {
1494
                rc = wc_Sha512Copy(&src->i_hash.sha512, &dst->i_hash.sha512);
1495
            }
1496
            if (rc == 0) {
1497
                rc = wc_Sha512Copy(&src->o_hash.sha512, &dst->o_hash.sha512);
1498
            }
1499
        #endif
1500
60
            break;
1501
0
    #endif /* WOLFSSL_SHA512 */
1502
0
#ifdef WOLFSSL_SHA3
1503
0
    #ifndef WOLFSSL_NOSHA3_224
1504
0
        case WC_SHA3_224:
1505
0
            rc = wc_Sha3_224_Copy(&src->hash.sha3, &dst->hash.sha3);
1506
        #ifdef WOLFSSL_HMAC_COPY_HASH
1507
            if (rc == 0) {
1508
                rc = wc_Sha3_224_Copy(&src->i_hash.sha3, &dst->i_hash.sha3);
1509
            }
1510
            if (rc == 0) {
1511
                rc = wc_Sha3_224_Copy(&src->o_hash.sha3, &dst->o_hash.sha3);
1512
            }
1513
        #endif
1514
0
            break;
1515
0
    #endif /* WOLFSSL_NO_SHA3_224 */
1516
0
    #ifndef WOLFSSL_NOSHA3_256
1517
0
        case WC_SHA3_256:
1518
0
            rc = wc_Sha3_256_Copy(&src->hash.sha3, &dst->hash.sha3);
1519
        #ifdef WOLFSSL_HMAC_COPY_HASH
1520
            if (rc == 0) {
1521
                rc = wc_Sha3_256_Copy(&src->i_hash.sha3, &dst->i_hash.sha3);
1522
            }
1523
            if (rc == 0) {
1524
                rc = wc_Sha3_256_Copy(&src->o_hash.sha3, &dst->o_hash.sha3);
1525
            }
1526
        #endif
1527
0
            break;
1528
0
    #endif /* WOLFSSL_NO_SHA3_256 */
1529
0
    #ifndef WOLFSSL_NOSHA3_384
1530
0
        case WC_SHA3_384:
1531
0
            rc = wc_Sha3_384_Copy(&src->hash.sha3, &dst->hash.sha3);
1532
        #ifdef WOLFSSL_HMAC_COPY_HASH
1533
            if (rc == 0) {
1534
                rc = wc_Sha3_384_Copy(&src->i_hash.sha3, &dst->i_hash.sha3);
1535
            }
1536
            if (rc == 0) {
1537
                rc = wc_Sha3_384_Copy(&src->o_hash.sha3, &dst->o_hash.sha3);
1538
            }
1539
        #endif
1540
0
            break;
1541
0
    #endif /* WOLFSSL_NO_SHA3_384 */
1542
0
    #ifndef WOLFSSL_NOSHA3_512
1543
0
        case WC_SHA3_512:
1544
0
            rc = wc_Sha3_512_Copy(&src->hash.sha3, &dst->hash.sha3);
1545
        #ifdef WOLFSSL_HMAC_COPY_HASH
1546
            if (rc == 0) {
1547
                rc = wc_Sha3_512_Copy(&src->i_hash.sha3, &dst->i_hash.sha3);
1548
            }
1549
            if (rc == 0) {
1550
                rc = wc_Sha3_512_Copy(&src->o_hash.sha3, &dst->o_hash.sha3);
1551
            }
1552
        #endif
1553
0
            break;
1554
0
    #endif /* WOLFSSL_NO_SHA3_512 */
1555
0
#endif /* WOLFSSL_SHA3 */
1556
1557
0
    #ifdef WOLFSSL_SM3
1558
0
        case WC_SM3:
1559
0
            rc = wc_Sm3Copy(&src->hash.sm3, &dst->hash.sm3);
1560
        #ifdef WOLFSSL_HMAC_COPY_HASH
1561
            if (rc == 0) {
1562
                rc = wc_Sm3Copy(&src->i_hash.sm3, &dst->i_hash.sm3);
1563
            }
1564
            if (rc == 0) {
1565
                rc = wc_Sm3Copy(&src->o_hash.sm3, &dst->o_hash.sm3);
1566
            }
1567
        #endif
1568
0
            break;
1569
0
    #endif /* WOLFSSL_SM3 */
1570
1571
0
        default:
1572
            /* Digest algorithm not supported. */
1573
0
            rc = BAD_FUNC_ARG;
1574
227
        }
1575
1576
        /* Check result of digest object copy. */
1577
227
        if (rc != 0) {
1578
0
            ret = 0;
1579
0
        }
1580
227
    }
1581
1582
227
    if (ret == 1) {
1583
        /* Copy the pads which are derived from the key. */
1584
227
        XMEMCPY((byte*)dst->ipad, (byte*)src->ipad, WC_HMAC_BLOCK_SIZE);
1585
227
        XMEMCPY((byte*)dst->opad, (byte*)src->opad, WC_HMAC_BLOCK_SIZE);
1586
        /* Copy the inner hash that is the current state. */
1587
227
        XMEMCPY((byte*)dst->innerHash, (byte*)src->innerHash,
1588
227
            WC_MAX_DIGEST_SIZE);
1589
        /* Copy other fields. */
1590
227
    #ifndef HAVE_FIPS
1591
227
        dst->heap    = heap;
1592
227
    #endif
1593
227
        dst->macType = src->macType;
1594
227
        dst->innerHashKeyed = src->innerHashKeyed;
1595
1596
#ifdef WOLFSSL_ASYNC_CRYPT
1597
        XMEMCPY(&dst->asyncDev, &src->asyncDev, sizeof(WC_ASYNC_DEV));
1598
        dst->keyLen = src->keyLen;
1599
    #ifdef HAVE_CAVIUM
1600
        /* Copy the dynamic data. */
1601
        dst->data = (byte*)XMALLOC(src->dataLen, dst->heap, DYNAMIC_TYPE_HMAC);
1602
        if (dst->data == NULL) {
1603
            ret = BUFFER_E;
1604
        }
1605
        else {
1606
            XMEMCPY(dst->data, src->data, src->dataLen);
1607
            dst->dataLen = src->dataLen;
1608
       }
1609
    #endif /* HAVE_CAVIUM */
1610
#endif /* WOLFSSL_ASYNC_CRYPT */
1611
227
    }
1612
1613
227
    return ret;
1614
227
}
1615
1616
1617
/*
1618
 * wolfSSL_HMAC_CTX APIs.
1619
 */
1620
1621
/* Allocate a new HMAC context object and initialize.
1622
 *
1623
 * @return  A cleared HMAC context object on success.
1624
 * @return  NULL on failure.
1625
 */
1626
WOLFSSL_HMAC_CTX* wolfSSL_HMAC_CTX_new(void)
1627
70
{
1628
70
    WOLFSSL_HMAC_CTX* hmac_ctx;
1629
1630
    /* Allocate dynamic memory for HMAC context object. */
1631
70
    hmac_ctx = (WOLFSSL_HMAC_CTX*)XMALLOC(sizeof(WOLFSSL_HMAC_CTX), NULL,
1632
70
        DYNAMIC_TYPE_OPENSSL);
1633
70
    if (hmac_ctx != NULL) {
1634
        /* Initialize HMAC context object. */
1635
70
        wolfSSL_HMAC_CTX_Init(hmac_ctx);
1636
70
    }
1637
1638
70
    return hmac_ctx;
1639
70
}
1640
1641
/* Initialize a HMAC context object.
1642
 *
1643
 * Not an OpenSSL compatibility API.
1644
 *
1645
 * @param [in, out] ctx  HMAC context object.
1646
 * @return  1 indicating success.
1647
 */
1648
int wolfSSL_HMAC_CTX_Init(WOLFSSL_HMAC_CTX* ctx)
1649
70
{
1650
70
    WOLFSSL_MSG("wolfSSL_HMAC_CTX_Init");
1651
1652
70
    if (ctx != NULL) {
1653
        /* Clear all fields. */
1654
70
        XMEMSET(ctx, 0, sizeof(WOLFSSL_HMAC_CTX));
1655
        /* type field is 0 == WC_HASH_TYPE_NONE. */
1656
        /* TODO: for FIPS and selftest 0 == WC_HASH_TYPE_MD5 instead. */
1657
70
    }
1658
1659
70
    return 1;
1660
70
}
1661
1662
/* Deep copy of information from one HMAC context object to another.
1663
 *
1664
 * @param [out] dst  Copy into this object.
1665
 * @param [in]  src  Copy from this object.
1666
 * @return  1 on success.
1667
 * @return  0 on failure.
1668
 */
1669
int wolfSSL_HMAC_CTX_copy(WOLFSSL_HMAC_CTX* dst, WOLFSSL_HMAC_CTX* src)
1670
0
{
1671
0
    int ret = 1;
1672
1673
0
    WOLFSSL_ENTER("wolfSSL_HMAC_CTX_copy");
1674
1675
    /* Validate parameters. */
1676
0
    if ((dst == NULL) || (src == NULL)) {
1677
0
        ret = 0;
1678
0
    }
1679
1680
0
    if (ret == 1) {
1681
        /* Copy hash type. */
1682
0
        dst->type = src->type;
1683
        /* Move pads derived from key into save space. */
1684
0
        XMEMCPY((byte *)&dst->save_ipad, (byte *)&src->hmac.ipad,
1685
0
            WC_HMAC_BLOCK_SIZE);
1686
0
        XMEMCPY((byte *)&dst->save_opad, (byte *)&src->hmac.opad,
1687
0
            WC_HMAC_BLOCK_SIZE);
1688
        /* Copy the wolfSSL Hmac ocbject. */
1689
0
        ret = wolfSSL_HmacCopy(&dst->hmac, &src->hmac);
1690
0
    }
1691
1692
0
    return ret;
1693
0
}
1694
1695
/* Cleanup internal state of HMAC context object.
1696
 *
1697
 * Not an OpenSSL compatibility API.
1698
 *
1699
 * @param [in, out] ctx  HMAC context object.
1700
 */
1701
void wolfSSL_HMAC_CTX_cleanup(WOLFSSL_HMAC_CTX* ctx)
1702
70
{
1703
70
    if (ctx != NULL) {
1704
        /* Cleanup HMAC operation data. */
1705
70
        wolfSSL_HMAC_cleanup(ctx);
1706
70
    }
1707
70
}
1708
1709
/* Free HMAC context object.
1710
 *
1711
 * ctx is deallocated and can no longer be used after this call.
1712
 *
1713
 * @param [in] ctx  HMAC context object.
1714
 */
1715
void wolfSSL_HMAC_CTX_free(WOLFSSL_HMAC_CTX* ctx)
1716
70
{
1717
70
    if (ctx != NULL) {
1718
        /* Cleanup HMAC context object, including freeing dynamic data. */
1719
70
        wolfSSL_HMAC_CTX_cleanup(ctx);
1720
        /* Dispose of the memory for the HMAC context object. */
1721
70
        XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL);
1722
70
    }
1723
70
}
1724
1725
/* Get the EVP digest of the HMAC context.
1726
 *
1727
 * @param [in] ctx  HMAC context object.
1728
 * @return  EVP digest object.
1729
 * @return  NULL when ctx is NULL or EVP digest not set.
1730
 */
1731
const WOLFSSL_EVP_MD* wolfSSL_HMAC_CTX_get_md(const WOLFSSL_HMAC_CTX* ctx)
1732
0
{
1733
0
    const WOLFSSL_EVP_MD* ret = NULL;
1734
1735
0
    if (ctx != NULL) {
1736
        /* Get EVP digest based on digest type. */
1737
0
        ret = wolfSSL_macType2EVP_md((enum wc_HashType)ctx->type);
1738
0
    }
1739
1740
0
    return ret;
1741
0
}
1742
1743
/*
1744
 * wolfSSL_HMAC APIs.
1745
 */
1746
1747
/* Initialize the HMAC operation.
1748
 *
1749
 * @param [in, out] ctx    HMAC context object.
1750
 * @param [in]      key    Array of bytes representing key.
1751
 *                         May be NULL indicating to use the same key as
1752
 *                         previously.
1753
 * @param [in]      keySz  Number of bytes in key.
1754
 *                         0+ in non-FIPS, 14+ in FIPS.
1755
 * @param [in]      type   EVP digest indicate digest type.
1756
 *                         May be NULL if initialized previously.
1757
 * @param [in]      e      wolfSSL engine. Ignored.
1758
 * @return  1 on success.
1759
 * @return  0 on failure.
1760
 */
1761
int wolfSSL_HMAC_Init_ex(WOLFSSL_HMAC_CTX* ctx, const void* key, int keySz,
1762
    const WOLFSSL_EVP_MD* type, WOLFSSL_ENGINE* e)
1763
70
{
1764
70
    WOLFSSL_ENTER("wolfSSL_HMAC_Init_ex");
1765
1766
    /* WOLFSSL_ENGINE not used, call wolfSSL_HMAC_Init */
1767
70
    (void)e;
1768
1769
70
    return wolfSSL_HMAC_Init(ctx, key, keySz, type);
1770
70
}
1771
1772
/* Initialize the HMAC operation.
1773
 *
1774
 * @param [in, out] ctx    HMAC context object.
1775
 * @param [in]      key    Array of bytes representing key.
1776
 *                         May be NULL indicating to use the same key as
1777
 *                         previously.
1778
 * @param [in]      keySz  Number of bytes in key.
1779
 *                         0+ in non-FIPS, 14+ in FIPS.
1780
 * @param [in]      type   EVP digest indicate digest type.
1781
 *                         May be NULL if initialized previously.
1782
 * @return  1 on success.
1783
 * @return  0 on failure.
1784
 */
1785
int wolfSSL_HMAC_Init(WOLFSSL_HMAC_CTX* ctx, const void* key, int keylen,
1786
    const WOLFSSL_EVP_MD* type)
1787
70
{
1788
70
    int ret = 1;
1789
70
    void* heap = NULL;
1790
70
    int rc;
1791
1792
70
    WOLFSSL_MSG("wolfSSL_HMAC_Init");
1793
1794
    /* Validate parameters. */
1795
70
    if (ctx == NULL) {
1796
0
        WOLFSSL_MSG("no ctx on init");
1797
0
        ret = 0;
1798
0
    }
1799
    /* Digest type must have been previously set if not specified. */
1800
70
    if ((ret == 1) && (type == NULL) && (ctx->type == (int)WC_HASH_TYPE_NONE)) {
1801
0
        WOLFSSL_MSG("no hash type");
1802
0
        ret = 0;
1803
0
    }
1804
    /* wolfSSL HMAC object must have been setup with a key if not specified. */
1805
70
    if ((ret == 1) && (key == NULL) &&
1806
13
            (ctx->hmac.macType == (int)WC_HASH_TYPE_NONE)) {
1807
13
        WOLFSSL_MSG("wolfCrypt hash not setup");
1808
13
        ret = 0;
1809
13
    }
1810
1811
70
    if (ret == 1) {
1812
57
    #ifndef HAVE_FIPS
1813
57
        heap = ctx->hmac.heap;
1814
57
    #endif
1815
1816
57
        if (type != NULL) {
1817
57
            WOLFSSL_MSG("init has type");
1818
            /* Get the digest type based on EVP digest. */
1819
57
            if (wolfssl_evp_md_to_hash_type(type, &ctx->type) != 0) {
1820
7
                WOLFSSL_MSG("bad init type");
1821
7
                ret = 0;
1822
7
            }
1823
57
        }
1824
57
    }
1825
1826
70
    if (ret == 1) {
1827
        /* Check if init has been called before */
1828
50
        int inited = (ctx->hmac.macType != WC_HASH_TYPE_NONE);
1829
        /* Free if wolfSSL HMAC object when initialized. */
1830
50
        if (inited) {
1831
0
            wc_HmacFree(&ctx->hmac);
1832
0
        }
1833
        /* Initialize wolfSSL HMAC object for new HMAC operation. */
1834
50
        rc = wc_HmacInit(&ctx->hmac, NULL, INVALID_DEVID);
1835
50
        if (rc != 0) {
1836
0
            ret = 0;
1837
0
        }
1838
50
    }
1839
70
    if ((ret == 1) && (key != NULL)) {
1840
        /* Set the key into wolfSSL HMAC object. */
1841
50
        rc = wc_HmacSetKey(&ctx->hmac, ctx->type, (const byte*)key,
1842
50
            (word32)keylen);
1843
50
        if (rc != 0) {
1844
            /* in FIPS mode a key < 14 characters will fail here */
1845
0
            WOLFSSL_MSG("hmac set key error");
1846
0
            WOLFSSL_ERROR(rc);
1847
0
            wc_HmacFree(&ctx->hmac);
1848
            /* Context is no longer keyed, so drop any previous key's pads
1849
             * and mark it unkeyed so a later init with no key is rejected
1850
             * rather than recovering from the pads just wiped. */
1851
0
            ForceZero(ctx->save_ipad, sizeof(ctx->save_ipad));
1852
0
            ForceZero(ctx->save_opad, sizeof(ctx->save_opad));
1853
            /* As in wolfSSL_HMAC_cleanup, the hash type in the wolfSSL HMAC
1854
             * object has to say unkeyed as well. wc_HmacFree only zeroes it,
1855
             * which does not read as none in every hash type enum layout.
1856
             * That alone gates the recover-from-pads path, so ctx->type keeps
1857
             * the digest the caller chose and a retry with a longer key, which
1858
             * is what the FIPS failure above asks for, still works. */
1859
0
            ctx->hmac.macType = WC_HASH_TYPE_NONE;
1860
0
            ret = 0;
1861
0
        }
1862
50
        if (ret == 1) {
1863
            /* Save the pads which are derived from the key. Used to re-init. */
1864
50
            XMEMCPY((byte *)&ctx->save_ipad, (byte *)&ctx->hmac.ipad,
1865
50
                WC_HMAC_BLOCK_SIZE);
1866
50
            XMEMCPY((byte *)&ctx->save_opad, (byte *)&ctx->hmac.opad,
1867
50
                WC_HMAC_BLOCK_SIZE);
1868
50
        }
1869
50
    }
1870
20
    else if (ret == 1) {
1871
0
        WOLFSSL_MSG("recover hmac");
1872
        /* Set state of wolfSSL HMAC object. */
1873
0
        ctx->hmac.macType = (byte)ctx->type;
1874
0
        ctx->hmac.innerHashKeyed = 0;
1875
        /* Restore key by copying in saved pads. */
1876
0
        XMEMCPY((byte *)&ctx->hmac.ipad, (byte *)&ctx->save_ipad,
1877
0
            WC_HMAC_BLOCK_SIZE);
1878
0
        XMEMCPY((byte *)&ctx->hmac.opad, (byte *)&ctx->save_opad,
1879
0
            WC_HMAC_BLOCK_SIZE);
1880
    #ifdef WOLFSSL_HMAC_COPY_HASH
1881
        rc = _HmacInitIOHashes(&ctx->hmac);
1882
        if (rc != 0) {
1883
            WOLFSSL_MSG("hmac init i_hash/o_hash error");
1884
            WOLFSSL_ERROR(rc);
1885
            ret = 0;
1886
        }
1887
        if (ret == 1)
1888
    #endif
1889
0
        {
1890
            /* Initialize the wolfSSL HMAC object. */
1891
0
            rc = _HMAC_Init(&ctx->hmac, ctx->hmac.macType, heap);
1892
0
            if (rc != 0) {
1893
0
                WOLFSSL_MSG("hmac init error");
1894
0
                WOLFSSL_ERROR(rc);
1895
0
                ret = 0;
1896
0
            }
1897
0
        }
1898
0
    }
1899
1900
70
    return ret;
1901
70
}
1902
1903
/* Update the HMAC operation with more data.
1904
 *
1905
 * TODO: 'len' should be a signed type.
1906
 *
1907
 * @param [in, out] ctx   HMAC context object.
1908
 * @param [in]      data  Array of byted to MAC. May be NULL.
1909
 * @param [in]      len   Number of bytes to MAC. May be 0.
1910
 * @return  1 on success.
1911
 * @return  0 when ctx is NULL or HMAC update fails.
1912
 */
1913
int wolfSSL_HMAC_Update(WOLFSSL_HMAC_CTX* ctx, const unsigned char* data,
1914
    int len)
1915
4.26k
{
1916
4.26k
    int ret = 1;
1917
1918
4.26k
    WOLFSSL_MSG("wolfSSL_HMAC_Update");
1919
1920
    /* Validate parameters. */
1921
4.26k
    if (ctx == NULL) {
1922
0
        WOLFSSL_MSG("no ctx");
1923
0
        ret = 0;
1924
0
    }
1925
1926
    /* Update when there is data to add. */
1927
4.26k
    if ((ret == 1) && (data != NULL) && (len > 0)) {
1928
216
        int rc;
1929
1930
216
        WOLFSSL_MSG("updating hmac");
1931
        /* Update wolfSSL HMAC object. */
1932
216
        rc = wc_HmacUpdate(&ctx->hmac, data, (word32)len);
1933
216
        if (rc != 0){
1934
0
            WOLFSSL_MSG("hmac update error");
1935
0
            ret = 0;
1936
0
        }
1937
216
    }
1938
1939
4.26k
    return ret;
1940
4.26k
}
1941
1942
/* Finalize HMAC operation.
1943
 *
1944
 * @param [in, out] ctx   HMAC context object.
1945
 * @param [out]     hash  Buffer to hold HMAC result.
1946
 *                        Must be able to hold bytes equivalent to digest size.
1947
 * @param [out]     len   Length of HMAC result. May be NULL.
1948
 * @return  1 on success.
1949
 * @return  0 when ctx or hash is NULL.
1950
 * @return  0 when HMAC finalization fails.
1951
 */
1952
int wolfSSL_HMAC_Final(WOLFSSL_HMAC_CTX* ctx, unsigned char* hash,
1953
    unsigned int* len)
1954
50
{
1955
50
    int ret = 1;
1956
50
    int rc;
1957
1958
50
    WOLFSSL_MSG("wolfSSL_HMAC_Final");
1959
1960
    /* Validate parameters. */
1961
50
    if ((ctx == NULL) || (hash == NULL)) {
1962
0
        WOLFSSL_MSG("invalid parameter");
1963
0
        ret = 0;
1964
0
    }
1965
1966
50
    if (ret == 1) {
1967
50
        WOLFSSL_MSG("final hmac");
1968
        /* Finalize wolfSSL HMAC object. */
1969
50
        rc = wc_HmacFinal(&ctx->hmac, hash);
1970
50
        if (rc != 0){
1971
0
            WOLFSSL_MSG("final hmac error");
1972
0
            ret = 0;
1973
0
        }
1974
50
    }
1975
50
    if ((ret == 1) && (len != NULL)) {
1976
50
        WOLFSSL_MSG("setting output len");
1977
        /* Get the length of the output based on digest type. */
1978
50
        *len = wolfssl_mac_len((unsigned char)ctx->type);
1979
50
    }
1980
1981
50
    return ret;
1982
50
}
1983
1984
1985
/* Cleanup the HMAC operation.
1986
 *
1987
 * Not an OpenSSL compatibility API.
1988
 *
1989
 * @param [in, out] ctx  HMAC context object.
1990
 * @return  1 indicating success.
1991
 */
1992
int wolfSSL_HMAC_cleanup(WOLFSSL_HMAC_CTX* ctx)
1993
140
{
1994
140
    WOLFSSL_MSG("wolfSSL_HMAC_cleanup");
1995
1996
140
    if (ctx != NULL) {
1997
        /* Free the dynamic data in the wolfSSL HMAC object. */
1998
140
        wc_HmacFree(&ctx->hmac);
1999
        /* The pads saved for re-init are derived from the key and live
2000
         * outside the wolfSSL HMAC object, so wipe them here. */
2001
140
        ForceZero(ctx->save_ipad, sizeof(ctx->save_ipad));
2002
140
        ForceZero(ctx->save_opad, sizeof(ctx->save_opad));
2003
        /* Mark the context unkeyed so a later init with no key is rejected
2004
         * rather than recovering from the pads just wiped. Relying on the
2005
         * hash type in the wolfSSL HMAC object is not enough: a zeroed
2006
         * macType does not read as none in every hash type enum layout. */
2007
140
        ctx->type = WC_HASH_TYPE_NONE;
2008
        /* The wolfCrypt object's type has to say unkeyed as well. wc_HmacFree
2009
         * zeroes it, which only reads as none where that enum value is 0; in
2010
         * the FIPS and selftest layout zero is MD5, so an init that supplies a
2011
         * digest but no key would take the recover path and MAC with the pads
2012
         * just wiped. */
2013
140
        ctx->hmac.macType = WC_HASH_TYPE_NONE;
2014
140
    }
2015
2016
140
    return 1;
2017
140
}
2018
2019
/* HMAC data using the specified EVP digest.
2020
 *
2021
 * @param [in]  evp_md  EVP digest.
2022
 * @param [in]  key     Array of bytes representing key.
2023
 * @param [in]  keySz   Number of bytes in key.
2024
 *                      0+ in non-FIPS, 14+ in FIPS.
2025
 * @param [in]  data    Data to MAC.
2026
 * @param [in]  len     Length in bytes of data to MAC.
2027
 * @param [out] md      HMAC output.
2028
 * @param [out] md_len  Length of HMAC output in bytes. May be NULL.
2029
 * @return  Buffer holding HMAC output.
2030
 * @return  NULL on failure.
2031
 */
2032
unsigned char* wolfSSL_HMAC(const WOLFSSL_EVP_MD* evp_md, const void* key,
2033
    int key_len, const unsigned char* data, size_t len, unsigned char* md,
2034
    unsigned int* md_len)
2035
0
{
2036
0
    unsigned char* ret = NULL;
2037
0
    int rc = 0;
2038
0
    int type = 0;
2039
0
    int hmacLen = 0;
2040
0
    WC_DECLARE_VAR(hmac, Hmac, 1, 0);
2041
0
    void* heap = NULL;
2042
2043
    /* Validate parameters. */
2044
0
    if ((evp_md == NULL) || (key == NULL) || (md == NULL)) {
2045
0
        rc = BAD_FUNC_ARG;
2046
0
    }
2047
2048
0
    if (rc == 0) {
2049
        /* Get the hash type corresponding to the EVP digest. */
2050
0
        rc = wolfssl_evp_md_to_hash_type(evp_md, &type);
2051
0
    }
2052
0
#ifdef WOLFSSL_SMALL_STACK
2053
0
    if (rc == 0) {
2054
        /* Allocate dynamic memory for a wolfSSL HMAC object. */
2055
0
        hmac = (Hmac*)XMALLOC(sizeof(Hmac), heap, DYNAMIC_TYPE_HMAC);
2056
0
        if (hmac == NULL) {
2057
0
            rc = MEMORY_E;
2058
0
        }
2059
0
    }
2060
0
#endif
2061
0
    if (rc == 0)  {
2062
        /* Get the HMAC output length. */
2063
0
        hmacLen = (int)wolfssl_mac_len((unsigned char)type);
2064
        /* 0 indicates the digest is not supported. */
2065
0
        if (hmacLen == 0) {
2066
0
            rc = BAD_FUNC_ARG;
2067
0
        }
2068
0
    }
2069
    /* Initialize the wolfSSL HMAC object. */
2070
0
    if ((rc == 0) && (wc_HmacInit(hmac, heap, INVALID_DEVID) == 0)) {
2071
        /* Set the key into the wolfSSL HMAC object. */
2072
0
        rc = wc_HmacSetKey(hmac, type, (const byte*)key, (word32)key_len);
2073
0
        if (rc == 0) {
2074
           /* Update the wolfSSL HMAC object with data. */
2075
0
            rc = wc_HmacUpdate(hmac, data, (word32)len);
2076
0
        }
2077
        /* Finalize the wolfSSL HMAC object. */
2078
0
        if ((rc == 0) && (wc_HmacFinal(hmac, md) == 0)) {
2079
            /* Return the length of the HMAC output if required. */
2080
0
            if (md_len != NULL) {
2081
0
                *md_len = (unsigned int)hmacLen;
2082
0
            }
2083
            /* Set the buffer to return. */
2084
0
            ret = md;
2085
0
        }
2086
        /* Dispose of dynamic memory associated with the wolfSSL HMAC object. */
2087
0
        wc_HmacFree(hmac);
2088
0
    }
2089
2090
0
    WC_FREE_VAR_EX(hmac, heap, DYNAMIC_TYPE_HMAC);
2091
0
    return ret;
2092
0
}
2093
2094
/* Get the HMAC output size.
2095
 *
2096
 * @param [in] ctx  HMAC context object.
2097
 * @return  Size of HMAC output in bytes.
2098
 * @return  0 when ctx is NULL or no digest algorithm set.
2099
 */
2100
size_t wolfSSL_HMAC_size(const WOLFSSL_HMAC_CTX* ctx)
2101
0
{
2102
0
    size_t ret = 0;
2103
2104
0
    if (ctx != NULL) {
2105
        /* Look up digest size with wolfSSL. */
2106
0
        ret = (size_t)wc_HashGetDigestSize((enum wc_HashType)ctx->hmac.macType);
2107
0
    }
2108
2109
0
    return ret;
2110
0
}
2111
#endif /* OPENSSL_EXTRA */
2112
2113
/*******************************************************************************
2114
 * END OF HMAC API
2115
 ******************************************************************************/
2116
2117
/*******************************************************************************
2118
 * START OF CMAC API
2119
 ******************************************************************************/
2120
2121
#if defined(OPENSSL_EXTRA) && !defined(WOLFCRYPT_ONLY)
2122
#if defined(WOLFSSL_CMAC) && defined(OPENSSL_EXTRA) && \
2123
    defined(WOLFSSL_AES_DIRECT)
2124
/* Allocate a new CMAC context object.
2125
 *
2126
 * TODO: make fields static.
2127
 *
2128
 * @return  A CMAC context object on success.
2129
 * @return  NULL on failure.
2130
 */
2131
WOLFSSL_CMAC_CTX* wolfSSL_CMAC_CTX_new(void)
2132
335
{
2133
335
    WOLFSSL_CMAC_CTX* ctx = NULL;
2134
2135
    /* Allocate memory for CMAC context object. */
2136
335
    ctx = (WOLFSSL_CMAC_CTX*)XMALLOC(sizeof(WOLFSSL_CMAC_CTX), NULL,
2137
335
        DYNAMIC_TYPE_OPENSSL);
2138
335
    if (ctx != NULL) {
2139
        /* Memory for wolfSSL CMAC object is allocated in
2140
         * wolfSSL_CMAC_Init().
2141
         */
2142
335
        ctx->internal = NULL;
2143
        /* Allocate memory for EVP cipher context object. */
2144
335
        ctx->cctx = wolfSSL_EVP_CIPHER_CTX_new();
2145
335
        if (ctx->cctx == NULL) {
2146
0
            XFREE(ctx->internal, NULL, DYNAMIC_TYPE_CMAC);
2147
0
            XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL);
2148
0
            ctx = NULL;
2149
0
        }
2150
335
    }
2151
2152
335
    return ctx;
2153
335
}
2154
2155
/* Free CMAC context object and dynamically allocated fields.
2156
 *
2157
 * ctx is deallocated and can no longer be used after this call.
2158
 *
2159
 * @param [in] ctx  CMAC context object.
2160
 */
2161
void wolfSSL_CMAC_CTX_free(WOLFSSL_CMAC_CTX *ctx)
2162
335
{
2163
335
    if (ctx != NULL) {
2164
        /* Deallocate dynamically allocated fields. */
2165
335
        if (ctx->internal != NULL) {
2166
0
#if (!defined(HAVE_FIPS) || FIPS_VERSION_GE(5, 3)) && !defined(HAVE_SELFTEST)
2167
0
            wc_CmacFree((Cmac*)ctx->internal);
2168
0
#endif
2169
0
            XFREE(ctx->internal, NULL, DYNAMIC_TYPE_CMAC);
2170
0
        }
2171
335
        if (ctx->cctx != NULL) {
2172
335
            wolfSSL_EVP_CIPHER_CTX_cleanup(ctx->cctx);
2173
335
            wolfSSL_EVP_CIPHER_CTX_free(ctx->cctx);
2174
335
        }
2175
        /* Deallocate CMAC context object. */
2176
335
        XFREE(ctx, NULL, DYNAMIC_TYPE_OPENSSL);
2177
335
    }
2178
335
}
2179
2180
/* Return a reference to the EVP cipher context.
2181
 *
2182
 * @param [in] ctx  CMAC context object.
2183
 * @return  EVP cipher context.
2184
 * @return  NULL when ctx is NULL.
2185
 */
2186
WOLFSSL_EVP_CIPHER_CTX* wolfSSL_CMAC_CTX_get0_cipher_ctx(WOLFSSL_CMAC_CTX* ctx)
2187
0
{
2188
0
    WOLFSSL_EVP_CIPHER_CTX* cctx = NULL;
2189
2190
0
    if (ctx != NULL) {
2191
        /* Return EVP cipher context object. */
2192
0
        cctx = ctx->cctx;
2193
0
    }
2194
2195
0
    return cctx;
2196
0
}
2197
2198
/* Initialize the CMAC operation.
2199
 *
2200
 * @param [in, out] cmac    CMAC context object.
2201
 * @param [in]      key     Symmetric key to use.
2202
 * @param [in]      keySz   Length of key in bytes.
2203
 * @param [in]      cipher  EVP cipher object describing encryption algorithm
2204
 *                          to use.
2205
 * @param [in]      engine  wolfSSL Engine. Not used.
2206
 * @return  1 on success.
2207
 * @return  0 when ctx or cipher is NULL.
2208
 * @return  0 when cipher is not an AES-CBC algorithm.
2209
 * @return  0 when key length does not match cipher.
2210
 */
2211
int wolfSSL_CMAC_Init(WOLFSSL_CMAC_CTX* ctx, const void *key, size_t keySz,
2212
    const WOLFSSL_EVP_CIPHER* cipher, WOLFSSL_ENGINE* engine)
2213
237
{
2214
237
    int ret = 1;
2215
2216
237
    (void)engine;
2217
2218
237
    WOLFSSL_ENTER("wolfSSL_CMAC_Init");
2219
2220
    /* Validate parameters. */
2221
237
    if ((ctx == NULL) || (cipher == NULL)) {
2222
0
        ret = 0;
2223
0
    }
2224
    /* Only AES-CBC ciphers are supported. */
2225
237
    if ((ret == 1)
2226
237
    #ifdef WOLFSSL_AES_128
2227
237
        && (cipher != EVP_AES_128_CBC)
2228
166
    #endif
2229
166
    #ifdef WOLFSSL_AES_192
2230
166
        && (cipher != EVP_AES_192_CBC)
2231
71
    #endif
2232
71
    #ifdef WOLFSSL_AES_256
2233
71
        && (cipher != EVP_AES_256_CBC)
2234
237
    #endif
2235
237
    ) {
2236
36
        WOLFSSL_MSG("wolfSSL_CMAC_Init: requested cipher is unsupported");
2237
36
        ret = 0;
2238
36
    }
2239
    /* Key length must match cipher. */
2240
237
    if ((ret == 1) && ((int)keySz != wolfSSL_EVP_Cipher_key_length(cipher))) {
2241
49
        WOLFSSL_MSG("wolfSSL_CMAC_Init: "
2242
49
                    "supplied key size doesn't match requested cipher");
2243
49
        ret = 0;
2244
49
    }
2245
2246
237
    if ((ret == 1) && (ctx->internal == NULL)) {
2247
        /* Allocate memory for wolfSSL CMAC object. */
2248
152
        ctx->internal = (Cmac*)XMALLOC(sizeof(Cmac), NULL, DYNAMIC_TYPE_CMAC);
2249
152
        if (ctx->internal == NULL)
2250
0
            ret = 0;
2251
152
    }
2252
2253
    /* Initialize the wolfCrypt CMAC object. */
2254
237
    if ((ret == 1) && (wc_InitCmac((Cmac*)ctx->internal, (const byte*)key,
2255
152
            (word32)keySz, WC_CMAC_AES, NULL) != 0)) {
2256
0
        WOLFSSL_MSG("wolfSSL_CMAC_Init: wc_InitCmac() failed");
2257
0
        XFREE(ctx->internal, NULL, DYNAMIC_TYPE_CMAC);
2258
0
        ctx->internal = NULL;
2259
0
        ret = 0;
2260
0
    }
2261
237
    if (ret == 1) {
2262
        /* Initialize the EVP cipher context object for encryption. */
2263
152
        ret = wolfSSL_EVP_CipherInit(ctx->cctx, cipher, (const byte*)key, NULL,
2264
152
            1);
2265
152
        if (ret != WOLFSSL_SUCCESS)
2266
0
            WOLFSSL_MSG("wolfSSL_CMAC_Init: wolfSSL_EVP_CipherInit() failed");
2267
152
    }
2268
2269
237
    WOLFSSL_LEAVE("wolfSSL_CMAC_Init", ret);
2270
2271
237
    return ret;
2272
237
}
2273
2274
/* Update the CMAC operation with data.
2275
 *
2276
 * @param [in, out] ctx   CMAC context object.
2277
 * @param [in]      data  Data to MAC as a byte array.
2278
 * @param [in]      len   Length of data in bytes.
2279
 * @return  1 on success.
2280
 * @return  0 when ctx is NULL.
2281
 */
2282
int wolfSSL_CMAC_Update(WOLFSSL_CMAC_CTX* ctx, const void* data, size_t len)
2283
1.24k
{
2284
1.24k
    int ret = 1;
2285
2286
1.24k
    WOLFSSL_ENTER("wolfSSL_CMAC_Update");
2287
2288
    /* Validate parameters. */
2289
1.24k
    if (ctx == NULL) {
2290
0
        ret = 0;
2291
0
    }
2292
2293
    /* Update the wolfCrypto CMAC object with data. */
2294
1.24k
    if ((ret == 1) && (data != NULL) && (wc_CmacUpdate((Cmac*)ctx->internal,
2295
1.19k
            (const byte*)data, (word32)len) != 0)) {
2296
0
        ret = 0;
2297
0
    }
2298
2299
1.24k
    WOLFSSL_LEAVE("wolfSSL_CMAC_Update", ret);
2300
2301
1.24k
    return ret;
2302
1.24k
}
2303
2304
/* Finalize the CMAC operation into output buffer.
2305
 *
2306
 * @param [in, out] ctx  CMAC context object.
2307
 * @param [out]     out  Buffer to place CMAC result into.
2308
 *                       Must be able to hold WC_AES_BLOCK_SIZE bytes.
2309
 * @param [out]     len  Length of CMAC result. May be NULL.
2310
 * @return  1 on success.
2311
 * @return  0 when ctx is NULL.
2312
 */
2313
int wolfSSL_CMAC_Final(WOLFSSL_CMAC_CTX* ctx, unsigned char* out, size_t* len)
2314
152
{
2315
152
    int ret = 1;
2316
152
    int blockSize;
2317
152
    word32 len32;
2318
2319
152
    WOLFSSL_ENTER("wolfSSL_CMAC_Final");
2320
2321
    /* Validate parameters. */
2322
152
    if (ctx == NULL) {
2323
0
        ret = 0;
2324
0
    }
2325
2326
152
    if (ret == 1) {
2327
        /* Get the expected output size. */
2328
152
        blockSize = wolfSSL_EVP_CIPHER_CTX_block_size(ctx->cctx);
2329
        /* Check value is valid. */
2330
152
        if (blockSize <= 0) {
2331
0
            ret = 0;
2332
0
        }
2333
152
        else {
2334
            /* wolfCrypt CMAC expects buffer size. */
2335
152
            len32 = (word32)blockSize;
2336
            /* Return size if required. */
2337
152
            if (len != NULL) {
2338
152
                *len = (size_t)blockSize;
2339
152
            }
2340
152
        }
2341
152
    }
2342
152
    if ((ret == 1) && (out != NULL)) {
2343
        /* Calculate MAC result with wolfCrypt CMAC object. */
2344
152
        if (wc_CmacFinal((Cmac*)ctx->internal, out, &len32) != 0) {
2345
0
            ret = 0;
2346
0
        }
2347
        /* TODO: Is this necessary? Length should not change. */
2348
        /* Return actual size if required. */
2349
152
        else if (len != NULL) {
2350
152
            *len = (size_t)len32;
2351
152
        }
2352
2353
152
        XFREE(ctx->internal, NULL, DYNAMIC_TYPE_CMAC);
2354
152
        ctx->internal = NULL;
2355
152
    }
2356
2357
152
    WOLFSSL_LEAVE("wolfSSL_CMAC_Final", ret);
2358
2359
152
    return ret;
2360
152
}
2361
#endif /* WOLFSSL_CMAC && OPENSSL_EXTRA && WOLFSSL_AES_DIRECT */
2362
#endif /* OPENSSL_EXTRA && !WOLFCRYPT_ONLY */
2363
2364
/*******************************************************************************
2365
 * END OF CMAC API
2366
 ******************************************************************************/
2367
2368
/*******************************************************************************
2369
 * START OF DES API
2370
 ******************************************************************************/
2371
2372
#ifdef OPENSSL_EXTRA
2373
#ifndef NO_DES3
2374
/* Set parity of the DES key.
2375
 *
2376
 * @param [in, out] key  DES key.
2377
 */
2378
void wolfSSL_DES_set_odd_parity(WOLFSSL_DES_cblock* key)
2379
0
{
2380
0
    int i;
2381
2382
0
    WOLFSSL_ENTER("wolfSSL_DES_set_odd_parity");
2383
2384
0
    for (i = 0; i < DES_KEY_SIZE; i++) {
2385
0
        unsigned char c = (*key)[i];
2386
        /* Set bottom bit to odd parity - XOR of each bit is to be 1.
2387
         * XOR 1 to XOR of each bit.
2388
         * When even parity, the value will be 1 and the bottom bit will be
2389
         * flipped.
2390
         * When odd parity, the value will be 0 and the bottom bit will be
2391
         * unchanged.
2392
         */
2393
0
        c ^= ((c >> 0) ^ (c >> 1) ^ (c >> 2) ^ (c >> 3) ^ (c >> 4) ^ (c >> 5) ^
2394
0
              (c >> 6) ^ (c >> 7) ^ 0x01) & 0x01;
2395
0
        (*key)[i] = c;
2396
0
    }
2397
0
}
2398
2399
/* Check parity of the DES key.
2400
 *
2401
 * @param [in] key  DES key.
2402
 * @return  1 when odd parity on all bytes.
2403
 * @return  0 when even parity on any byte.
2404
 */
2405
int wolfSSL_DES_check_key_parity(WOLFSSL_DES_cblock *key)
2406
0
{
2407
0
    int i;
2408
    /* Assume odd parity. */
2409
0
    unsigned char p = 1;
2410
2411
0
    WOLFSSL_ENTER("wolfSSL_DES_check_key_parity");
2412
2413
0
    for (i = 0; i < DES_KEY_SIZE; i++) {
2414
0
        unsigned char c = (*key)[i];
2415
        /* p will be 0 when parity is even (XOR of bits is 0). */
2416
0
        p &= (c >> 0) ^ (c >> 1) ^ (c >> 2) ^ (c >> 3) ^ (c >> 4) ^ (c >> 5) ^
2417
0
             (c >> 6) ^ (c >> 7);
2418
0
    }
2419
2420
    /* Only care about bottom bit. */
2421
0
    return p & 1;
2422
0
}
2423
2424
/* Check whether key data is the two 32-bit words.
2425
 *
2426
 * return true in fail case (1)
2427
 *
2428
 * @param [in] k1   First part of key.
2429
 * @param [in] k2   Second part of key.
2430
 * @param [in] key  DES key as an array of bytes.
2431
 **/
2432
static int wolfssl_des_check(word32 k1, word32 k2, unsigned char* key)
2433
0
{
2434
    /* Compare the two 32-bit words. */
2435
0
    return (((word32*)key)[0] == k1) && (((word32*)key)[1] == k2);
2436
0
}
2437
2438
/* Check key is not weak.
2439
 *
2440
 * Weak key list from Nist "Recommendation for the Triple Data Encryption
2441
 * Algorithm (TDEA) Block Cipher"
2442
 *
2443
 * @param [in] key  DES key.
2444
 * @return  0 when #key is not a weak key.
2445
 * @return  1 when #key is a weak key.
2446
 */
2447
int wolfSSL_DES_is_weak_key(WOLFSSL_const_DES_cblock* key)
2448
0
{
2449
0
    int ret = 0;
2450
2451
0
    WOLFSSL_ENTER("wolfSSL_DES_is_weak_key");
2452
2453
    /* Validate parameter. */
2454
0
    if (key == NULL) {
2455
0
        WOLFSSL_MSG("NULL key passed in");
2456
0
        ret = 1;
2457
0
    }
2458
2459
    /* Check weak keys - endian doesn't matter. */
2460
0
    if ((ret == 0) && (wolfssl_des_check(0x01010101, 0x01010101, *key) ||
2461
0
                       wolfssl_des_check(0xFEFEFEFE, 0xFEFEFEFE, *key) ||
2462
0
                       wolfssl_des_check(0xE0E0E0E0, 0xF1F1F1F1, *key) ||
2463
0
                       wolfssl_des_check(0x1F1F1F1F, 0x0E0E0E0E, *key))) {
2464
0
        WOLFSSL_MSG("Weak key found");
2465
0
        ret = 1;
2466
0
    }
2467
2468
    /* Check semi-weak keys - endian doesn't matter. */
2469
0
    if ((ret == 0) && (wolfssl_des_check(0x011F011F, 0x010E010E, *key) ||
2470
0
                       wolfssl_des_check(0x1F011F01, 0x0E010E01, *key) ||
2471
0
                       wolfssl_des_check(0x01E001E0, 0x01F101F1, *key) ||
2472
0
                       wolfssl_des_check(0xE001E001, 0xF101F101, *key) ||
2473
0
                       wolfssl_des_check(0x01FE01FE, 0x01FE01FE, *key) ||
2474
0
                       wolfssl_des_check(0xFE01FE01, 0xFE01FE01, *key) ||
2475
0
                       wolfssl_des_check(0x1FE01FE0, 0x0EF10EF1, *key) ||
2476
0
                       wolfssl_des_check(0xE01FE01F, 0xF10EF10E, *key) ||
2477
0
                       wolfssl_des_check(0x1FFE1FFE, 0x0EFE0EFE, *key) ||
2478
0
                       wolfssl_des_check(0xFE1FFE1F, 0xFE0EFE0E, *key) ||
2479
0
                       wolfssl_des_check(0xE0FEE0FE, 0xF1FEF1FE, *key) ||
2480
0
                       wolfssl_des_check(0xFEE0FEE0, 0xFEF1FEF1, *key))) {
2481
0
        WOLFSSL_MSG("Semi-weak key found");
2482
0
        ret = 1;
2483
0
    }
2484
2485
0
    return ret;
2486
0
}
2487
2488
/* Set key into schedule if key parity is odd and key is not weak.
2489
 *
2490
 * @param [in]  key       DES key data.
2491
 * @param [out] schedule  DES key schedule.
2492
 * @return  0 on success.
2493
 * @return  -1 when parity is not odd.
2494
 * @return  -2 when key or schedule is NULL.
2495
 * @return  -2 when key is weak or semi-weak.
2496
 */
2497
int wolfSSL_DES_set_key_checked(WOLFSSL_const_DES_cblock* key,
2498
    WOLFSSL_DES_key_schedule* schedule)
2499
0
{
2500
0
    int ret = 0;
2501
2502
    /* Validate parameters. */
2503
0
    if ((key == NULL) || (schedule == NULL)) {
2504
0
        WOLFSSL_MSG("Bad argument passed to wolfSSL_DES_set_key_checked");
2505
0
        ret = -2;
2506
0
    }
2507
2508
    /* Check key parity is odd. */
2509
0
    if ((ret == 0) && (!wolfSSL_DES_check_key_parity(key))) {
2510
0
        WOLFSSL_MSG("Odd parity test fail");
2511
0
        ret = WOLFSSL_FATAL_ERROR;
2512
0
    }
2513
    /* Check whether key is weak. */
2514
0
    if ((ret == 0) && wolfSSL_DES_is_weak_key(key)) {
2515
0
        WOLFSSL_MSG("Weak key found");
2516
0
        ret = -2;
2517
0
    }
2518
0
    if (ret == 0) {
2519
        /* Key data passed checks, now copy key into schedule. */
2520
0
        XMEMCPY(schedule, key, DES_KEY_SIZE);
2521
0
    }
2522
2523
0
    return ret;
2524
0
}
2525
2526
/* Set key into schedule - no checks on key data performed.
2527
 *
2528
 * @param [in]  key       DES key data.
2529
 * @param [out] schedule  DES key schedule.
2530
 */
2531
void wolfSSL_DES_set_key_unchecked(WOLFSSL_const_DES_cblock* key,
2532
    WOLFSSL_DES_key_schedule* schedule)
2533
0
{
2534
    /* Validate parameters. */
2535
0
    if ((key != NULL) && (schedule != NULL)) {
2536
        /* Copy the key data into the schedule. */
2537
0
        XMEMCPY(schedule, key, DES_KEY_SIZE);
2538
0
    }
2539
0
}
2540
2541
/* Set key into schedule.
2542
 *
2543
 * @param [in]  key       DES key data.
2544
 * @param [out] schedule  DES key schedule.
2545
 * @return  0 on success.
2546
 * @return  -1 when parity is not odd.
2547
 * @return  -2 when key or schedule is NULL.
2548
 * @return  -2 when key is weak or semi-weak.
2549
 */
2550
int wolfSSL_DES_set_key(WOLFSSL_const_DES_cblock* key,
2551
    WOLFSSL_DES_key_schedule* schedule)
2552
0
{
2553
#ifdef WOLFSSL_CHECK_DESKEY
2554
    return wolfSSL_DES_set_key_checked(key, schedule);
2555
#else
2556
0
    wolfSSL_DES_set_key_unchecked(key, schedule);
2557
0
    return 0;
2558
0
#endif
2559
0
}
2560
2561
/* Set the key schedule from the DES key.
2562
 *
2563
 * TODO: OpenSSL checks parity and weak keys.
2564
 *
2565
 * @param [in]  key       DES key data.
2566
 * @param [out] schedule  DES key schedule.
2567
 * @return  0 on success.
2568
 */
2569
int wolfSSL_DES_key_sched(WOLFSSL_const_DES_cblock* key,
2570
    WOLFSSL_DES_key_schedule* schedule)
2571
0
{
2572
0
    WOLFSSL_ENTER("wolfSSL_DES_key_sched");
2573
2574
    /* Check parameters are usable. */
2575
0
    if ((key == NULL) || (schedule == NULL)) {
2576
0
        WOLFSSL_MSG("Null argument passed in");
2577
0
    }
2578
0
    else {
2579
        /* Copy the key data into the schedule. */
2580
0
        XMEMCPY(schedule, key, sizeof(WOLFSSL_const_DES_cblock));
2581
0
    }
2582
2583
0
    return 0;
2584
0
}
2585
2586
/* Encrypt with DES-CBC to create a checksum.
2587
 *
2588
 * Intended to behave similar to Kerberos mit_des_cbc_cksum.
2589
 * Returns the last 4 bytes of cipher text.
2590
 *
2591
 * TODO: Encrypt one block at a time instead of allocating a large amount.
2592
 *
2593
 * @param [in]  in      Data to encrypt.
2594
 * @param [out] out     Last encrypted block.
2595
 * @param [in]  length  Length of data to encrypt.
2596
 * @param [in]  sc      Key schedule for encryption.
2597
 * @param [in]  iv      Initialization vector for CBC.
2598
 * @return  Checksum of encryption.
2599
 * @return  0 on error.
2600
 */
2601
WOLFSSL_DES_LONG wolfSSL_DES_cbc_cksum(const unsigned char* in,
2602
    WOLFSSL_DES_cblock* out, long length, WOLFSSL_DES_key_schedule* sc,
2603
    WOLFSSL_const_DES_cblock* iv)
2604
0
{
2605
0
    WOLFSSL_DES_LONG ret = 0;
2606
0
    int err = 0;
2607
0
    unsigned char* data = (unsigned char*)in;
2608
0
    unsigned char* tmp = NULL;
2609
0
    long dataSz = length;
2610
2611
0
    WOLFSSL_ENTER("wolfSSL_DES_cbc_cksum");
2612
2613
    /* Validate parameters. */
2614
0
    if ((in == NULL) || (out == NULL) || (sc == NULL) || (iv == NULL)
2615
0
        || length <= 0) {
2616
0
        WOLFSSL_MSG("Bad argument passed in");
2617
0
        err = 1;
2618
0
    }
2619
2620
    /* When input length is not a multiple of DES_BLOCK_SIZE pad with 0s. */
2621
0
    if ((!err) && (dataSz % DES_BLOCK_SIZE)) {
2622
        /* Allocate a buffer big enough to hold padded input. */
2623
0
        dataSz += DES_BLOCK_SIZE - (dataSz % DES_BLOCK_SIZE);
2624
0
        data = (unsigned char*)XMALLOC((size_t)dataSz, NULL,
2625
0
        DYNAMIC_TYPE_TMP_BUFFER);
2626
0
        if (data == NULL) {
2627
0
            WOLFSSL_MSG("Issue creating temporary buffer");
2628
0
            err = 1;
2629
0
        }
2630
0
        else {
2631
            /* Copy input and pad with 0s. */
2632
0
            XMEMCPY(data, in, (size_t)length);
2633
0
            XMEMSET(data + length, 0, (size_t)(dataSz - length));
2634
0
        }
2635
0
    }
2636
2637
0
    if (!err) {
2638
        /* Allocate buffer to hold encrypted data. */
2639
0
        tmp = (unsigned char*)XMALLOC((size_t)dataSz, NULL,
2640
0
        DYNAMIC_TYPE_TMP_BUFFER);
2641
0
        if (tmp == NULL) {
2642
0
            WOLFSSL_MSG("Issue creating temporary buffer");
2643
0
            err = 1;
2644
0
        }
2645
0
    }
2646
2647
0
    if (!err) {
2648
        /* Encrypt data into temporary. */
2649
0
        wolfSSL_DES_cbc_encrypt(data, tmp, dataSz, sc, (WOLFSSL_DES_cblock*)iv,
2650
0
            WC_DES_ENCRYPT);
2651
        /* Copy out last block. */
2652
0
        XMEMCPY((unsigned char*)out, tmp + (dataSz - DES_BLOCK_SIZE),
2653
0
            DES_BLOCK_SIZE);
2654
2655
        /* Use the last half of the encrypted block as the checksum. */
2656
0
        ret = (((*((unsigned char*)out + 4) & 0xFF) << 24) |
2657
0
               ((*((unsigned char*)out + 5) & 0xFF) << 16) |
2658
0
               ((*((unsigned char*)out + 6) & 0xFF) <<  8) |
2659
0
                (*((unsigned char*)out + 7) & 0xFF)      );
2660
0
    }
2661
2662
    /* Dispose of allocated memory. */
2663
0
    XFREE(tmp, NULL, DYNAMIC_TYPE_TMP_BUFFER);
2664
0
    if (data != in) {
2665
0
        XFREE(data, NULL, DYNAMIC_TYPE_TMP_BUFFER);
2666
0
    }
2667
0
    return ret;
2668
0
}
2669
2670
/* Encrypt/decrypt data with DES-CBC.
2671
 *
2672
 * TODO: OpenSSL expects a length that is a multiple of the block size but
2673
 *       we are padding the last block. This is not a padding API.
2674
 * TODO: Validate parameters?
2675
 *
2676
 * A length that is not a multiple of DES_BLOCK_SIZE is rounded up to a whole
2677
 * block: on encrypt the trailing partial block is 0 padded and a full block is
2678
 * written to output, and on decrypt a full block is read from input. Both
2679
 * buffers must therefore hold length rounded up to DES_BLOCK_SIZE, not just
2680
 * length bytes.
2681
 *
2682
 * @param [in]  input     Data to encipher.
2683
 * @param [out] output    Enciphered data.
2684
 * @param [in]  length    Length of data to encipher.
2685
 * @param [in]  schedule  Key schedule.
2686
 * @param [in]  ivec      IV for CBC operation.
2687
 * @param [in]  enc       Whether to encrypt.
2688
 */
2689
void wolfSSL_DES_cbc_encrypt(const unsigned char* input, unsigned char* output,
2690
    long length, WOLFSSL_DES_key_schedule* schedule, WOLFSSL_DES_cblock* ivec,
2691
    int enc)
2692
0
{
2693
0
    WC_DECLARE_VAR(des, Des, 1, 0);
2694
0
    byte lastBlock[DES_BLOCK_SIZE];
2695
2696
0
    WOLFSSL_ENTER("wolfSSL_DES_cbc_encrypt");
2697
2698
0
#ifdef WOLFSSL_SMALL_STACK
2699
0
    des = (Des*)XMALLOC(sizeof(Des), NULL, DYNAMIC_TYPE_CIPHER);
2700
0
    if (des == NULL) {
2701
0
        WOLFSSL_MSG("Failed to allocate memory for Des object");
2702
0
    }
2703
0
    else
2704
0
#endif
2705
    /* OpenSSL compat, no ret */
2706
0
    if (wc_Des_SetKey(des, (const byte*)schedule, (const byte*)ivec,
2707
0
            !enc) != 0) {
2708
0
        WOLFSSL_MSG("wc_Des_SetKey return error.");
2709
0
    }
2710
0
    else {
2711
        /* Last incomplete block size. 0 means none over. */
2712
0
        int    lb_sz = length % DES_BLOCK_SIZE;
2713
        /* Length of data that is a multiple of a block. */
2714
0
        word32 len   = (word32)(length - lb_sz);
2715
2716
0
        if (enc == WC_DES_ENCRYPT) {
2717
            /* Encrypt full blocks into output. */
2718
0
            wc_Des_CbcEncrypt(des, output, input, len);
2719
0
            if (lb_sz != 0) {
2720
                /* Create a 0 padded block from remaining bytes. */
2721
0
                XMEMSET(lastBlock, 0, DES_BLOCK_SIZE);
2722
0
                XMEMCPY(lastBlock, input + len, (size_t)lb_sz);
2723
                /* Encrypt last block into output. */
2724
0
                wc_Des_CbcEncrypt(des, output + len, lastBlock,
2725
0
                    (word32)DES_BLOCK_SIZE);
2726
0
            }
2727
0
        }
2728
0
        else {
2729
            /* Decrypt full blocks into output. */
2730
0
            wc_Des_CbcDecrypt(des, output, input, len);
2731
0
            if (lb_sz != 0) {
2732
                /* Decrypt the last block that is not going to be full size. */
2733
0
                wc_Des_CbcDecrypt(des, lastBlock, input + len,
2734
0
                    (word32)DES_BLOCK_SIZE);
2735
                /* Copy out the required amount of the decrypted block. */
2736
0
                XMEMCPY(output + len, lastBlock, (size_t)lb_sz);
2737
0
            }
2738
0
        }
2739
0
    }
2740
2741
0
    WC_FREE_VAR_EX(des, NULL, DYNAMIC_TYPE_CIPHER);
2742
0
}
2743
2744
/* Encrypt/decrypt data with DES-CBC. Sets the IV for following operation.
2745
 *
2746
 * TODO: OpenSSL expects a length that is a multiple of the block size but
2747
 *       we are padding the last block. This is not a padding API.
2748
 * TODO: Validate parameters?
2749
 *
2750
 * A length that is not a multiple of DES_BLOCK_SIZE is rounded up to a whole
2751
 * block, and the new IV is taken from that last whole block. Both buffers must
2752
 * therefore hold length rounded up to DES_BLOCK_SIZE, not just length bytes.
2753
 *
2754
 * @param [in]      input     Data to encipher.
2755
 * @param [out]     output    Enciphered data.
2756
 * @param [in]      length    Length of data to encipher.
2757
 * @param [in]      schedule  Key schedule.
2758
 * @param [in, out] ivec      IV for CBC operation.
2759
 * @param [in]      enc       Whether to encrypt.
2760
 */
2761
void wolfSSL_DES_ncbc_encrypt(const unsigned char* input, unsigned char* output,
2762
    long length, WOLFSSL_DES_key_schedule* schedule, WOLFSSL_DES_cblock* ivec,
2763
    int enc)
2764
0
{
2765
0
    unsigned char tmp[DES_IV_SIZE];
2766
0
    size_t offset;
2767
2768
0
    WOLFSSL_ENTER("wolfSSL_DES_ncbc_encrypt");
2769
2770
    /* Zero/negative length: no block to derive an IV from. The offset math
2771
     * below would underflow for length == 0, yielding a wild-pointer read. */
2772
0
    if (length <= 0) {
2773
0
        WOLFSSL_LEAVE("wolfSSL_DES_ncbc_encrypt", 0);
2774
0
        return;
2775
0
    }
2776
2777
    /* Calculate length to a multiple of block size. */
2778
0
    offset = (size_t)length;
2779
0
    offset = (offset + DES_BLOCK_SIZE - 1) / DES_BLOCK_SIZE;
2780
0
    offset *= DES_BLOCK_SIZE;
2781
0
    offset -= DES_BLOCK_SIZE;
2782
0
    if (enc == WC_DES_ENCRYPT) {
2783
        /* Encrypt data. */
2784
0
        wolfSSL_DES_cbc_encrypt(input, output, length, schedule, ivec, enc);
2785
        /* Use last encrypted block as new IV. */
2786
0
        XMEMCPY(ivec, output + offset, DES_IV_SIZE);
2787
0
    }
2788
0
    else {
2789
        /* Get last encrypted block for new IV. */
2790
0
        XMEMCPY(tmp, input + offset, DES_IV_SIZE);
2791
        /* Decrypt data. */
2792
0
        wolfSSL_DES_cbc_encrypt(input, output, length, schedule, ivec, enc);
2793
        /* Use last encrypted block as new IV. */
2794
0
        XMEMCPY(ivec, tmp, DES_IV_SIZE);
2795
0
    }
2796
0
}
2797
2798
/* Encrypt/decrypt data with DES-CBC.
2799
 *
2800
 * WOLFSSL_DES_key_schedule is an unsigned char array of size 8.
2801
 *
2802
 * TODO: OpenSSL expects a length that is a multiple of the block size but
2803
 *       we are padding the last block. This is not a padding API.
2804
 * TODO: Validate parameters?
2805
 *
2806
 * A size that is not a multiple of DES_BLOCK_SIZE is rounded up to a whole
2807
 * block: on encrypt the trailing partial block is 0 padded and a full block is
2808
 * written to output, and on decrypt a full block is read from input. Both
2809
 * buffers must therefore hold sz rounded up to DES_BLOCK_SIZE, not just sz
2810
 * bytes.
2811
 *
2812
 * @param [in]      input     Data to encipher.
2813
 * @param [out]     output    Enciphered data.
2814
 * @param [in]      sz        Length of data to encipher.
2815
 * @param [in]      ks1       First key schedule.
2816
 * @param [in]      ks2       Second key schedule.
2817
 * @param [in]      ks3       Third key schedule.
2818
 * @param [in, out] ivec      IV for CBC operation.
2819
 * @param [in]      enc       Whether to encrypt.
2820
 */
2821
void wolfSSL_DES_ede3_cbc_encrypt(const unsigned char* input,
2822
    unsigned char* output, long sz, WOLFSSL_DES_key_schedule* ks1,
2823
    WOLFSSL_DES_key_schedule* ks2, WOLFSSL_DES_key_schedule* ks3,
2824
    WOLFSSL_DES_cblock* ivec, int enc)
2825
0
{
2826
0
    WC_DECLARE_VAR(des3, Des3, 1, 0);
2827
2828
0
    WOLFSSL_ENTER("wolfSSL_DES_ede3_cbc_encrypt");
2829
2830
0
#ifdef WOLFSSL_SMALL_STACK
2831
0
    des3 = (Des3*)XMALLOC(sizeof(Des3), NULL, DYNAMIC_TYPE_CIPHER);
2832
0
    if (des3 == NULL) {
2833
0
        WOLFSSL_MSG("Failed to allocate memory for Des3 object");
2834
0
        sz = 0;
2835
0
    }
2836
0
#endif
2837
2838
0
    if (sz > 0) {
2839
0
        int    ret;
2840
0
        byte   key[DES3_KEY_SIZE];
2841
0
        byte   lastBlock[DES_BLOCK_SIZE];
2842
0
        int    lb_sz;
2843
0
        word32 len;
2844
2845
        /* Copy the three keys into the buffer for wolfCrypt DES. */
2846
0
        XMEMCPY(key + 0 * DES_BLOCK_SIZE, *ks1, DES_BLOCK_SIZE);
2847
0
        XMEMCPY(key + 1 * DES_BLOCK_SIZE, *ks2, DES_BLOCK_SIZE);
2848
0
        XMEMCPY(key + 2 * DES_BLOCK_SIZE, *ks3, DES_BLOCK_SIZE);
2849
2850
        /* Last incomplete block size. 0 means none over. */
2851
0
        lb_sz = sz % DES_BLOCK_SIZE;
2852
        /* Length of data that is a multiple of a block. */
2853
0
        len   = (word32)(sz - lb_sz);
2854
2855
        /* Initialize wolfCrypt DES3 object. */
2856
0
        XMEMSET(des3, 0, sizeof(Des3));
2857
0
        ret = wc_Des3Init(des3, NULL, INVALID_DEVID);
2858
0
        (void)ret;
2859
2860
0
        if (enc == WC_DES_ENCRYPT) {
2861
            /* Initialize wolfCrypt DES3 object. */
2862
0
            if (wc_Des3_SetKey(des3, key, (const byte*)ivec, DES_ENCRYPTION)
2863
0
                    == 0) {
2864
                /* Encrypt full blocks into output. */
2865
0
                ret = wc_Des3_CbcEncrypt(des3, output, input, len);
2866
0
                (void)ret;
2867
            #if defined(WOLFSSL_ASYNC_CRYPT)
2868
                ret = wc_AsyncWait(ret, &des3->asyncDev, WC_ASYNC_FLAG_NONE);
2869
                (void)ret;
2870
            #endif
2871
0
                if (lb_sz != 0) {
2872
                    /* Create a 0 padded block from remaining bytes. */
2873
0
                    XMEMSET(lastBlock, 0, DES_BLOCK_SIZE);
2874
0
                    XMEMCPY(lastBlock, input + len, (size_t)lb_sz);
2875
                    /* Encrypt last block into output. */
2876
0
                    ret = wc_Des3_CbcEncrypt(des3, output + len, lastBlock,
2877
0
                        (word32)DES_BLOCK_SIZE);
2878
0
                    (void)ret;
2879
                #if defined(WOLFSSL_ASYNC_CRYPT)
2880
                    ret = wc_AsyncWait(ret, &des3->asyncDev,
2881
                        WC_ASYNC_FLAG_NONE);
2882
                    (void)ret;
2883
                #endif
2884
                    /* Copy the last encrypted block as IV for next decrypt. */
2885
0
                    XMEMCPY(ivec, output + len, DES_BLOCK_SIZE);
2886
0
                }
2887
0
                else {
2888
                    /* Copy the last encrypted block as IV for next decrypt. */
2889
0
                    XMEMCPY(ivec, output + len - DES_BLOCK_SIZE,
2890
0
                        DES_BLOCK_SIZE);
2891
0
                }
2892
0
            }
2893
0
        }
2894
0
        else {
2895
            /* Initialize wolfCrypt DES3 object. */
2896
0
            if (wc_Des3_SetKey(des3, key, (const byte*)ivec, DES_DECRYPTION)
2897
0
                    == 0) {
2898
                /* Copy the last encrypted block as IV for next decrypt. */
2899
0
                if (lb_sz != 0) {
2900
0
                    XMEMCPY(ivec, input + len, DES_BLOCK_SIZE);
2901
0
                }
2902
0
                else {
2903
0
                    XMEMCPY(ivec, input + len - DES_BLOCK_SIZE, DES_BLOCK_SIZE);
2904
0
                }
2905
                /* Decrypt full blocks into output. */
2906
0
                ret = wc_Des3_CbcDecrypt(des3, output, input, len);
2907
0
                (void)ret;
2908
            #if defined(WOLFSSL_ASYNC_CRYPT)
2909
                ret = wc_AsyncWait(ret, &des3->asyncDev, WC_ASYNC_FLAG_NONE);
2910
                (void)ret;
2911
            #endif
2912
0
                if (lb_sz != 0) {
2913
                   /* Decrypt the last block that is not going to be full size.
2914
                    */
2915
0
                    ret = wc_Des3_CbcDecrypt(des3, lastBlock, input + len,
2916
0
                        (word32)DES_BLOCK_SIZE);
2917
0
                    (void)ret;
2918
                #if defined(WOLFSSL_ASYNC_CRYPT)
2919
                    ret = wc_AsyncWait(ret, &des3->asyncDev,
2920
                        WC_ASYNC_FLAG_NONE);
2921
                    (void)ret;
2922
                #endif
2923
                    /* Copy out the required amount of the decrypted block. */
2924
0
                    XMEMCPY(output + len, lastBlock, (size_t)lb_sz);
2925
0
                }
2926
0
            }
2927
0
        }
2928
0
        wc_Des3Free(des3);
2929
2930
0
        ForceZero(key, DES3_KEY_SIZE);
2931
0
    }
2932
2933
0
    WC_FREE_VAR_EX(des3, NULL, DYNAMIC_TYPE_CIPHER);
2934
0
}
2935
2936
#ifdef WOLFSSL_DES_ECB
2937
/* Encrypt or decrypt input message desa with key and get output in desb.
2938
 *
2939
 * @param [in]  in   Block to encipher with DES-ECB.
2940
 * @param [out] out  Enciphered block.
2941
 * @param [in]  key  DES key schedule.
2942
 * @param [in]  enc  Whether to encrypt.
2943
 */
2944
void wolfSSL_DES_ecb_encrypt(WOLFSSL_DES_cblock* in, WOLFSSL_DES_cblock* out,
2945
    WOLFSSL_DES_key_schedule* key, int enc)
2946
0
{
2947
0
    WC_DECLARE_VAR(des, Des, 1, 0);
2948
2949
0
    WOLFSSL_ENTER("wolfSSL_DES_ecb_encrypt");
2950
2951
    /* Validate parameters. */
2952
0
    if ((in == NULL) || (out == NULL) || (key == NULL) ||
2953
0
           ((enc != WC_DES_ENCRYPT) && (enc != WC_DES_DECRYPT))) {
2954
0
        WOLFSSL_MSG("Bad argument passed to wolfSSL_DES_ecb_encrypt");
2955
0
    }
2956
0
#ifdef WOLFSSL_SMALL_STACK
2957
0
    else if ((des = (Des*)XMALLOC(sizeof(Des), NULL, DYNAMIC_TYPE_CIPHER))
2958
0
             == NULL)
2959
0
    {
2960
0
        WOLFSSL_MSG("Failed to allocate memory for Des object");
2961
0
    }
2962
0
#endif
2963
    /* Set key in wolfCrypt DES object for encryption or decryption.
2964
     * WC_DES_ENCRYPT = 1, wolfSSL DES_ENCRYPTION = 0.
2965
     * WC_DES_DECRYPT = 0, wolfSSL DES_DECRYPTION = 1.
2966
     */
2967
0
    else if (wc_Des_SetKey(des, (const byte*)key, NULL, !enc) != 0) {
2968
0
        WOLFSSL_MSG("wc_Des_SetKey return error.");
2969
0
    }
2970
0
    else if (enc == WC_DES_ENCRYPT) {
2971
        /* Encrypt a block with wolfCrypt DES object. */
2972
0
        if (wc_Des_EcbEncrypt(des, (byte*)out, (const byte*)in, DES_KEY_SIZE)
2973
0
                != 0) {
2974
0
            WOLFSSL_MSG("wc_Des_EcbEncrypt return error.");
2975
0
        }
2976
0
    }
2977
0
    else {
2978
        /* Decrypt a block with wolfCrypt DES object. */
2979
0
        if (wc_Des_EcbDecrypt(des, (byte*)out, (const byte*)in, DES_KEY_SIZE)
2980
0
                != 0) {
2981
0
            WOLFSSL_MSG("wc_Des_EcbDecrpyt return error.");
2982
0
        }
2983
0
    }
2984
2985
0
    WC_FREE_VAR_EX(des, NULL, DYNAMIC_TYPE_CIPHER);
2986
0
}
2987
#endif
2988
#endif /* NO_DES3 */
2989
#endif /* OPENSSL_EXTRA */
2990
2991
/*******************************************************************************
2992
 * END OF DES API
2993
 ******************************************************************************/
2994
2995
/*******************************************************************************
2996
 * START OF AES API
2997
 ******************************************************************************/
2998
2999
#ifdef OPENSSL_EXTRA
3000
3001
#if !defined(NO_AES) && !defined(WOLFSSL_NO_OPENSSL_AES_LOW_LEVEL_API)
3002
3003
/* Sets the key into the AES key object for encryption or decryption.
3004
 *
3005
 * TODO: check bits value?
3006
 *
3007
 * @param [in]  key   Key data.
3008
 * @param [in]  bits  Number of bits in key.
3009
 * @param [out] aes   AES key object.
3010
 * @param [in]  enc   Whether to encrypt. AES_ENCRYPTION or AES_DECRYPTION.
3011
 * @return  0 on success.
3012
 * @return  -1 when key or aes is NULL.
3013
 * @return  -1 when setting key with wolfCrypt fails.
3014
 */
3015
static int wolfssl_aes_set_key(const unsigned char *key, const int bits,
3016
    WOLFSSL_AES_KEY *aes, int enc)
3017
{
3018
    wc_static_assert(sizeof(WOLFSSL_AES_KEY) >= sizeof(Aes));
3019
3020
    /* Validate parameters. */
3021
    if ((key == NULL) || (aes == NULL)) {
3022
        WOLFSSL_MSG("Null argument passed in");
3023
        return WOLFSSL_FATAL_ERROR;
3024
    }
3025
3026
    XMEMSET(aes, 0, sizeof(WOLFSSL_AES_KEY));
3027
3028
    if (wc_AesInit((Aes*)aes, NULL, INVALID_DEVID) != 0) {
3029
        WOLFSSL_MSG("Error in initting AES key");
3030
        return WOLFSSL_FATAL_ERROR;
3031
    }
3032
3033
    if (wc_AesSetKey((Aes*)aes, key, (word32)((bits)/8), NULL, enc) != 0) {
3034
        WOLFSSL_MSG("Error in setting AES key");
3035
        return WOLFSSL_FATAL_ERROR;
3036
    }
3037
    return 0;
3038
}
3039
3040
/* Sets the key into the AES key object for encryption.
3041
 *
3042
 * @param [in]  key   Key data.
3043
 * @param [in]  bits  Number of bits in key.
3044
 * @param [out] aes   AES key object.
3045
 * @return  0 on success.
3046
 * @return  -1 when key or aes is NULL.
3047
 * @return  -1 when setting key with wolfCrypt fails.
3048
 */
3049
int wolfSSL_AES_set_encrypt_key(const unsigned char *key, const int bits,
3050
    WOLFSSL_AES_KEY *aes)
3051
{
3052
    WOLFSSL_ENTER("wolfSSL_AES_set_encrypt_key");
3053
3054
    return wolfssl_aes_set_key(key, bits, aes, AES_ENCRYPTION);
3055
}
3056
3057
/* Sets the key into the AES key object for decryption.
3058
 *
3059
 * @param [in]  key   Key data.
3060
 * @param [in]  bits  Number of bits in key.
3061
 * @param [out] aes   AES key object.
3062
 * @return  0 on success.
3063
 * @return  -1 when key or aes is NULL.
3064
 * @return  -1 when setting key with wolfCrypt fails.
3065
 */
3066
int wolfSSL_AES_set_decrypt_key(const unsigned char *key, const int bits,
3067
    WOLFSSL_AES_KEY *aes)
3068
{
3069
    WOLFSSL_ENTER("wolfSSL_AES_set_decrypt_key");
3070
3071
    return wolfssl_aes_set_key(key, bits, aes, AES_DECRYPTION);
3072
}
3073
3074
#ifdef WOLFSSL_AES_DIRECT
3075
/* Encrypt a 16-byte block of data using AES-ECB.
3076
 *
3077
 * wolfSSL_AES_set_encrypt_key() must have been called.
3078
 *
3079
 * #input must contain WC_AES_BLOCK_SIZE bytes of data.
3080
 * #output must be a buffer at least WC_AES_BLOCK_SIZE bytes in length.
3081
 *
3082
 * @param [in]  input   Data to encrypt.
3083
 * @param [out] output  Encrypted data.
3084
 * @param [in]  key     AES key to use for encryption.
3085
 */
3086
void wolfSSL_AES_encrypt(const unsigned char* input, unsigned char* output,
3087
    WOLFSSL_AES_KEY *key)
3088
{
3089
    WOLFSSL_ENTER("wolfSSL_AES_encrypt");
3090
3091
    /* Validate parameters. */
3092
    if ((input == NULL) || (output == NULL) || (key == NULL)) {
3093
        WOLFSSL_MSG("Null argument passed in");
3094
    }
3095
    else
3096
#if !defined(HAVE_SELFTEST) && \
3097
    (!defined(HAVE_FIPS) || (defined(FIPS_VERSION_GE) && FIPS_VERSION_GE(5,3)) \
3098
    || defined(WOLFSSL_KERNEL_MODE))
3099
    /* Encrypt a block with wolfCrypt AES. */
3100
    if (wc_AesEncryptDirect((Aes*)key, output, input) != 0) {
3101
        WOLFSSL_MSG("wc_AesEncryptDirect failed");
3102
    }
3103
#else
3104
    {
3105
        /* Encrypt a block with wolfCrypt AES. */
3106
        wc_AesEncryptDirect((Aes*)key, output, input);
3107
    }
3108
#endif
3109
}
3110
3111
3112
/* Decrypt a 16-byte block of data using AES-ECB.
3113
 *
3114
 * wolfSSL_AES_set_decrypt_key() must have been called.
3115
 *
3116
 * #input must contain WC_AES_BLOCK_SIZE bytes of data.
3117
 * #output must be a buffer at least WC_AES_BLOCK_SIZE bytes in length.
3118
 *
3119
 * @param [in]  input   Data to decrypt.
3120
 * @param [out] output  Decrypted data.
3121
 * @param [in]  key     AES key to use for encryption.
3122
 */
3123
void wolfSSL_AES_decrypt(const unsigned char* input, unsigned char* output,
3124
    WOLFSSL_AES_KEY *key)
3125
{
3126
    WOLFSSL_ENTER("wolfSSL_AES_decrypt");
3127
3128
    /* Validate parameters. */
3129
    if ((input == NULL) || (output == NULL) || (key == NULL)) {
3130
        WOLFSSL_MSG("Null argument passed in");
3131
    }
3132
    else
3133
#if !defined(HAVE_SELFTEST) && (!defined(HAVE_FIPS) || \
3134
    (defined(FIPS_VERSION_GE) && FIPS_VERSION3_GE(5,3,0)))
3135
    /* Decrypt a block with wolfCrypt AES. */
3136
    if (wc_AesDecryptDirect((Aes*)key, output, input) != 0) {
3137
        WOLFSSL_MSG("wc_AesDecryptDirect failed");
3138
    }
3139
#else
3140
    {
3141
        /* Decrypt a block with wolfCrypt AES. */
3142
        wc_AesDecryptDirect((Aes*)key, output, input);
3143
    }
3144
#endif
3145
}
3146
#endif /* WOLFSSL_AES_DIRECT */
3147
3148
3149
3150
#ifdef HAVE_AES_ECB
3151
/* Encrypt/decrypt a 16-byte block of data using AES-ECB.
3152
 *
3153
 * wolfSSL_AES_set_encrypt_key() or wolfSSL_AES_set_decrypt_key ()must have been
3154
 * called.
3155
 *
3156
 * #input must contain WC_AES_BLOCK_SIZE bytes of data.
3157
 * #output must be a buffer at least WC_AES_BLOCK_SIZE bytes in length.
3158
 *
3159
 * @param [in]  in   Data to encipher.
3160
 * @param [out] out  Enciphered data.
3161
 * @param [in]  key  AES key to use for encryption/decryption.
3162
 * @param [in]  enc  Whether to encrypt.
3163
 *                   AES_ENCRPT for encryption, AES_DECRYPTION for decryption.
3164
 */
3165
void wolfSSL_AES_ecb_encrypt(const unsigned char *in, unsigned char* out,
3166
    WOLFSSL_AES_KEY *key, const int enc)
3167
{
3168
    WOLFSSL_ENTER("wolfSSL_AES_ecb_encrypt");
3169
3170
    /* Validate parameters. */
3171
    if ((key == NULL) || (in == NULL) || (out == NULL)) {
3172
        WOLFSSL_MSG("Error, Null argument passed in");
3173
    }
3174
    else if (enc == AES_ENCRYPTION) {
3175
        /* Encrypt block. */
3176
        if (wc_AesEcbEncrypt((Aes*)key, out, in, WC_AES_BLOCK_SIZE) != 0) {
3177
            WOLFSSL_MSG("Error with AES CBC encrypt");
3178
        }
3179
    }
3180
    else {
3181
    #ifdef HAVE_AES_DECRYPT
3182
        /* Decrypt block. */
3183
        if (wc_AesEcbDecrypt((Aes*)key, out, in, WC_AES_BLOCK_SIZE) != 0) {
3184
            WOLFSSL_MSG("Error with AES CBC decrypt");
3185
        }
3186
    #else
3187
        WOLFSSL_MSG("AES decryption not compiled in");
3188
    #endif
3189
    }
3190
}
3191
#endif /* HAVE_AES_ECB */
3192
3193
#ifdef HAVE_AES_CBC
3194
/* Encrypt/decrypt data with IV using AES-CBC.
3195
 *
3196
 * wolfSSL_AES_set_encrypt_key() or wolfSSL_AES_set_decrypt_key() must have been
3197
 * called.
3198
 *
3199
 * @param [in]       in   Data to encipher.
3200
 * @param [out]      out  Enciphered data.
3201
 * @param [in]       len  Length of data to encipher.
3202
 * @param [in]       key  AES key to use for encryption/decryption.
3203
 * @param [in, out]  iv   Initialization Vector (IV) of CBC mode.
3204
 *                        On in, used with first block.
3205
 *                        On out, IV for further operations.
3206
 * @param [in]       enc  Whether to encrypt.
3207
 *                   AES_ENCRPT for encryption, AES_DECRYPTION for decryption.
3208
 */
3209
void wolfSSL_AES_cbc_encrypt(const unsigned char *in, unsigned char* out,
3210
    size_t len, WOLFSSL_AES_KEY *key, unsigned char* iv, const int enc)
3211
{
3212
    WOLFSSL_ENTER("wolfSSL_AES_cbc_encrypt");
3213
3214
    /* Validate parameters. */
3215
    if ((key == NULL) || (in == NULL) || (out == NULL) || (iv == NULL) ||
3216
            (len == 0)) {
3217
        WOLFSSL_MSG("Error, Null argument passed in");
3218
    }
3219
    /* Set IV for operation. */
3220
    else {
3221
        int ret;
3222
        Aes* aes = (Aes*)key;
3223
3224
        if ((ret = wc_AesSetIV(aes, (const byte*)iv)) != 0) {
3225
            WOLFSSL_MSG("Error with setting iv");
3226
        }
3227
        else if (enc == AES_ENCRYPTION) {
3228
            /* Encrypt with wolfCrypt AES object. */
3229
            if ((ret = wc_AesCbcEncrypt(aes, out, in, (word32)len)) != 0) {
3230
                WOLFSSL_MSG("Error with AES CBC encrypt");
3231
            }
3232
        }
3233
        else {
3234
            /* Decrypt with wolfCrypt AES object. */
3235
            if ((ret = wc_AesCbcDecrypt(aes, out, in, (word32)len)) != 0) {
3236
                WOLFSSL_MSG("Error with AES CBC decrypt");
3237
            }
3238
        }
3239
3240
        if (ret == 0) {
3241
            /* Get IV for next operation. */
3242
            XMEMCPY(iv, (byte*)(aes->reg), WC_AES_BLOCK_SIZE);
3243
        }
3244
    }
3245
}
3246
#endif /* HAVE_AES_CBC */
3247
3248
3249
/* Encrypt/decrypt data with IV using AES-CFB.
3250
 *
3251
 * wolfSSL_AES_set_encrypt_key() must have been called.
3252
 *
3253
 * @param [in]       in   Data to encipher.
3254
 * @param [out]      out  Enciphered data.
3255
 * @param [in]       len  Length of data to encipher.
3256
 * @param [in]       key  AES key to use for encryption/decryption.
3257
 * @param [in, out]  iv   Initialization Vector (IV) of CFB mode.
3258
 *                        On in, used with first block.
3259
 *                        On out, IV for further operations.
3260
 * @param [out]      num  Number of bytes used from last incomplete block.
3261
 * @param [in]       enc  Whether to encrypt.
3262
 *                   AES_ENCRPT for encryption, AES_DECRYPTION for decryption.
3263
 */
3264
void wolfSSL_AES_cfb128_encrypt(const unsigned char *in, unsigned char* out,
3265
    size_t len, WOLFSSL_AES_KEY *key, unsigned char* iv, int* num,
3266
    const int enc)
3267
{
3268
#ifndef WOLFSSL_AES_CFB
3269
    WOLFSSL_MSG("CFB mode not enabled please use macro WOLFSSL_AES_CFB");
3270
3271
    (void)in;
3272
    (void)out;
3273
    (void)len;
3274
    (void)key;
3275
    (void)iv;
3276
    (void)num;
3277
    (void)enc;
3278
#else
3279
    WOLFSSL_ENTER("wolfSSL_AES_cfb_encrypt");
3280
3281
    /* Validate parameters. */
3282
    if ((key == NULL) || (in == NULL) || (out == NULL) || (iv == NULL)) {
3283
        WOLFSSL_MSG("Error, Null argument passed in");
3284
    }
3285
    else {
3286
        int ret;
3287
        Aes* aes = (Aes*)key;
3288
3289
        /* Copy the IV directly into reg here because wc_AesSetIV clears
3290
         * leftover bytes field "left", and this function relies on the leftover
3291
         * bytes being preserved between calls.
3292
         */
3293
        XMEMCPY(aes->reg, iv, WC_AES_BLOCK_SIZE);
3294
3295
        if (enc == AES_ENCRYPTION) {
3296
            /* Encrypt data with AES-CFB. */
3297
            if ((ret = wc_AesCfbEncrypt(aes, out, in, (word32)len)) != 0) {
3298
                WOLFSSL_MSG("Error with AES CBC encrypt");
3299
            }
3300
        }
3301
        else {
3302
            /* Decrypt data with AES-CFB. */
3303
            if ((ret = wc_AesCfbDecrypt(aes, out, in, (word32)len)) != 0) {
3304
                WOLFSSL_MSG("Error with AES CBC decrypt");
3305
            }
3306
        }
3307
3308
        if (ret == 0) {
3309
            /* Copy IV out after operation. */
3310
            XMEMCPY(iv, (byte*)(aes->reg), WC_AES_BLOCK_SIZE);
3311
3312
            /* Store number of left over bytes to num. */
3313
            if (num != NULL) {
3314
                *num = (WC_AES_BLOCK_SIZE - aes->left) % WC_AES_BLOCK_SIZE;
3315
            }
3316
        }
3317
    }
3318
#endif /* WOLFSSL_AES_CFB */
3319
}
3320
3321
/* wc_AesKey*Wrap_ex API not available in FIPS and SELFTEST */
3322
#if defined(HAVE_AES_KEYWRAP) && !defined(HAVE_FIPS) && !defined(HAVE_SELFTEST)
3323
/* Wrap (encrypt) a key using RFC3394 AES key wrap.
3324
 *
3325
 * @param [in, out] key   AES key.
3326
 * @param [in]      iv    Initialization vector used by encryption mode.
3327
 * @param [out]     out   Wrapped key.
3328
 * @param [in]      in    Key data to wrap.
3329
 * @param [in]      inSz  Length of key to wrap in bytes.
3330
 * @return  Length of encrypted key in bytes.
3331
 * @return  0 when key, iv, out or in is NULL.
3332
 * @return  0 when key length is not valid.
3333
 */
3334
int wolfSSL_AES_wrap_key(WOLFSSL_AES_KEY *key, const unsigned char *iv,
3335
    unsigned char *out, const unsigned char *in, unsigned int inSz)
3336
{
3337
    int ret = 0;
3338
    int len = 0;
3339
3340
    WOLFSSL_ENTER("wolfSSL_AES_wrap_key");
3341
3342
    /* Validate parameters. */
3343
    if ((out == NULL) || (in == NULL)) {
3344
        WOLFSSL_MSG("Error, Null argument passed in");
3345
        ret = BAD_FUNC_ARG;
3346
    }
3347
3348
    /* Wrap key. */
3349
    if ((ret == 0) && ((ret = wc_AesKeyWrap_ex((Aes*)key, in, inSz, out,
3350
            inSz + KEYWRAP_BLOCK_SIZE, iv)) > 0)) {
3351
        /* Get the length of the wrapped key. */
3352
        len = ret;
3353
    }
3354
3355
    return len;
3356
}
3357
3358
/* Unwrap (decrypt) a key using RFC3394 AES key wrap.
3359
 *
3360
 * @param [in, out] key   AES key.
3361
 * @param [in]      iv    Initialization vector used by decryption mode.
3362
 * @param [out]     out   Unwrapped key.
3363
 * @param [in]      in    Wrapped key data.
3364
 * @param [in]      inSz  Length of wrapped key data in bytes.
3365
 * @return  Length of decrypted key in bytes.
3366
 * @return  0 when key, iv, out or in is NULL.
3367
 * @return  0 when wrapped key data length is not valid.
3368
 */
3369
int wolfSSL_AES_unwrap_key(WOLFSSL_AES_KEY *key, const unsigned char *iv,
3370
    unsigned char *out, const unsigned char *in, unsigned int inSz)
3371
{
3372
    int ret = 0;
3373
    int len = 0;
3374
3375
    WOLFSSL_ENTER("wolfSSL_AES_wrap_key");
3376
3377
    /* Validate parameters. */
3378
    if ((out == NULL) || (in == NULL)) {
3379
        WOLFSSL_MSG("Error, Null argument passed in");
3380
        ret = BAD_FUNC_ARG;
3381
    }
3382
3383
    /* Unwrap key. */
3384
    if ((ret == 0) && ((ret = wc_AesKeyUnWrap_ex((Aes*)key, in, inSz, out,
3385
            inSz + KEYWRAP_BLOCK_SIZE, iv)) > 0)) {
3386
        /* Get the length of the unwrapped key. */
3387
        len = ret;
3388
    }
3389
3390
    return len;
3391
}
3392
#endif /* HAVE_AES_KEYWRAP && !HAVE_FIPS && !HAVE_SELFTEST */
3393
3394
#ifdef HAVE_CTS
3395
/* Ciphertext stealing encryption compatible with RFC2040 and RFC3962.
3396
 *
3397
 * @param [in]  in   Data to encrypt.
3398
 * @param [out] out  Encrypted data.
3399
 * @param [in]  len  Length of data to encrypt.
3400
 * @param [in]  key  Symmetric key.
3401
 * @param [in]  iv   Initialization Vector for encryption mode.
3402
 * @param [in]  cbc  CBC mode encryption function.
3403
 * @return  Length of encrypted data in bytes on success.
3404
 * @return  0 when in, out, cbc, key or iv are NULL.
3405
 * @return  0 when len is less than or equal to 16 bytes.
3406
 */
3407
size_t wolfSSL_CRYPTO_cts128_encrypt(const unsigned char *in,
3408
    unsigned char *out, size_t len, const void *key, unsigned char *iv,
3409
    WOLFSSL_CBC128_CB cbc)
3410
{
3411
    byte lastBlk[WOLFSSL_CTS128_BLOCK_SZ];
3412
    int lastBlkLen = len % WOLFSSL_CTS128_BLOCK_SZ;
3413
3414
    WOLFSSL_ENTER("wolfSSL_CRYPTO_cts128_encrypt");
3415
3416
    /* Validate parameters. */
3417
    if ((in == NULL) || (out == NULL) || (len <= WOLFSSL_CTS128_BLOCK_SZ) ||
3418
            (cbc == NULL) || (key == NULL) || (iv == NULL)) {
3419
        WOLFSSL_MSG("Bad parameter");
3420
        len = 0;
3421
    }
3422
3423
    if (len > 0) {
3424
        /* Must have a last block. */
3425
        if (lastBlkLen == 0) {
3426
            lastBlkLen = WOLFSSL_CTS128_BLOCK_SZ;
3427
        }
3428
3429
        /* Encrypt data up to last block */
3430
        (*cbc)(in, out, len - lastBlkLen, key, iv, AES_ENCRYPTION);
3431
3432
        /* Move to last block */
3433
        in += len - lastBlkLen;
3434
        out += len - lastBlkLen;
3435
3436
        /* RFC2040: Pad Pn with zeros at the end to create P of length BB. */
3437
        XMEMCPY(lastBlk, in, lastBlkLen);
3438
        XMEMSET(lastBlk + lastBlkLen, 0, WOLFSSL_CTS128_BLOCK_SZ - lastBlkLen);
3439
        /* RFC2040: Select the first Ln bytes of En-1 to create Cn */
3440
        XMEMCPY(out, out - WOLFSSL_CTS128_BLOCK_SZ, lastBlkLen);
3441
        /* Encrypt last block. */
3442
        (*cbc)(lastBlk, out - WOLFSSL_CTS128_BLOCK_SZ, WOLFSSL_CTS128_BLOCK_SZ,
3443
                key, iv, AES_ENCRYPTION);
3444
    }
3445
3446
    return len;
3447
}
3448
3449
/* Ciphertext stealing decryption compatible with RFC2040 and RFC3962.
3450
 *
3451
 * @param [in]  in   Data to decrypt.
3452
 * @param [out] out  Decrypted data.
3453
 * @param [in]  len  Length of data to decrypt.
3454
 * @param [in]  key  Symmetric key.
3455
 * @param [in]  iv   Initialization Vector for decryption mode.
3456
 * @param [in]  cbc  CBC mode encryption function.
3457
 * @return  Length of decrypted data in bytes on success.
3458
 * @return  0 when in, out, cbc, key or iv are NULL.
3459
 * @return  0 when len is less than or equal to 16 bytes.
3460
 */
3461
size_t wolfSSL_CRYPTO_cts128_decrypt(const unsigned char *in,
3462
    unsigned char *out, size_t len, const void *key, unsigned char *iv,
3463
    WOLFSSL_CBC128_CB cbc)
3464
{
3465
    byte lastBlk[WOLFSSL_CTS128_BLOCK_SZ];
3466
    byte prevBlk[WOLFSSL_CTS128_BLOCK_SZ];
3467
    int lastBlkLen = len % WOLFSSL_CTS128_BLOCK_SZ;
3468
3469
    WOLFSSL_ENTER("wolfSSL_CRYPTO_cts128_decrypt");
3470
3471
    /* Validate parameters. */
3472
    if ((in == NULL) || (out == NULL) || (len <= WOLFSSL_CTS128_BLOCK_SZ) ||
3473
            (cbc == NULL) || (key == NULL) || (iv == NULL)) {
3474
        WOLFSSL_MSG("Bad parameter");
3475
        len = 0;
3476
    }
3477
3478
    if (len > 0) {
3479
        /* Must have a last block. */
3480
        if (lastBlkLen == 0) {
3481
            lastBlkLen = WOLFSSL_CTS128_BLOCK_SZ;
3482
        }
3483
3484
        if (len - lastBlkLen - WOLFSSL_CTS128_BLOCK_SZ != 0) {
3485
            /* Decrypt up to last two blocks */
3486
            (*cbc)(in, out, len - lastBlkLen - WOLFSSL_CTS128_BLOCK_SZ, key, iv,
3487
                    AES_DECRYPTION);
3488
3489
            /* Move to last two blocks */
3490
            in += len - lastBlkLen - WOLFSSL_CTS128_BLOCK_SZ;
3491
            out += len - lastBlkLen - WOLFSSL_CTS128_BLOCK_SZ;
3492
        }
3493
3494
        /* RFC2040: Decrypt Cn-1 to create Dn.
3495
         * Use 0 buffer as IV to do straight decryption.
3496
         * This places the Cn-1 block at lastBlk */
3497
        XMEMSET(lastBlk, 0, WOLFSSL_CTS128_BLOCK_SZ);
3498
        (*cbc)(in, prevBlk, WOLFSSL_CTS128_BLOCK_SZ, key, lastBlk,
3499
            AES_DECRYPTION);
3500
        /* RFC2040: Append the tail (BB minus Ln) bytes of Xn to Cn
3501
         *          to create En. */
3502
        XMEMCPY(prevBlk, in + WOLFSSL_CTS128_BLOCK_SZ, lastBlkLen);
3503
        /* Cn and Cn-1 can now be decrypted */
3504
        (*cbc)(prevBlk, out, WOLFSSL_CTS128_BLOCK_SZ, key, iv, AES_DECRYPTION);
3505
        (*cbc)(lastBlk, lastBlk, WOLFSSL_CTS128_BLOCK_SZ, key, iv,
3506
            AES_DECRYPTION);
3507
        XMEMCPY(out + WOLFSSL_CTS128_BLOCK_SZ, lastBlk, lastBlkLen);
3508
    }
3509
3510
    return len;
3511
}
3512
#endif /* HAVE_CTS */
3513
#endif /* !NO_AES && !WOLFSSL_NO_OPENSSL_AES_LOW_LEVEL_API */
3514
#endif /* OPENSSL_EXTRA */
3515
3516
/*******************************************************************************
3517
 * END OF AES API
3518
 ******************************************************************************/
3519
3520
/*******************************************************************************
3521
 * START OF RC4 API
3522
 ******************************************************************************/
3523
3524
#ifdef OPENSSL_EXTRA
3525
3526
#ifndef NO_RC4
3527
/* Set the key state for Arc4 key.
3528
 *
3529
 * @param [out] key   Arc4 key.
3530
 * @param [in]  len   Length of key in buffer.
3531
 * @param [in]  data  Key data buffer.
3532
 */
3533
void wolfSSL_RC4_set_key(WOLFSSL_RC4_KEY* key, int len,
3534
    const unsigned char* data)
3535
0
{
3536
0
    wc_static_assert(sizeof(WOLFSSL_RC4_KEY) >= sizeof(Arc4));
3537
3538
0
    WOLFSSL_ENTER("wolfSSL_RC4_set_key");
3539
3540
    /* Validate parameters. */
3541
0
    if ((key == NULL) || (len < 0) || (data == NULL)) {
3542
0
        WOLFSSL_MSG("bad argument passed in");
3543
0
    }
3544
0
    else {
3545
        /* Reset wolfCrypt Arc4 object. */
3546
0
        XMEMSET(key, 0, sizeof(WOLFSSL_RC4_KEY));
3547
        /* Set key into wolfCrypt Arc4 object. */
3548
0
        wc_Arc4SetKey((Arc4*)key, data, (word32)len);
3549
0
    }
3550
0
}
3551
3552
3553
/* Encrypt/decrypt with Arc4 key.
3554
 *
3555
 * @param [in]  len  Length of data to encrypt/decrypt.
3556
 * @param [in]  in   Data to encrypt/decrypt.
3557
 * @param [out] out  Enciphered data.
3558
 */
3559
void wolfSSL_RC4(WOLFSSL_RC4_KEY* key, size_t len, const unsigned char* in,
3560
    unsigned char* out)
3561
0
{
3562
0
    WOLFSSL_ENTER("wolfSSL_RC4");
3563
3564
    /* Validate parameters. */
3565
0
    if ((key == NULL) || (in == NULL) || (out == NULL)) {
3566
0
        WOLFSSL_MSG("Bad argument passed in");
3567
0
    }
3568
0
    else {
3569
        /* Encrypt/decrypt data. */
3570
0
        wc_Arc4Process((Arc4*)key, out, in, (word32)len);
3571
0
    }
3572
0
}
3573
#endif /* NO_RC4 */
3574
3575
#endif /* OPENSSL_EXTRA */
3576
3577
/*******************************************************************************
3578
 * END OF RC4 API
3579
 ******************************************************************************/
3580
3581
#ifndef WOLFCRYPT_ONLY
3582
3583
/*******************************************************************************
3584
 * START OF RAND API
3585
 ******************************************************************************/
3586
3587
#if defined(OPENSSL_EXTRA) && !defined(WOLFSSL_NO_OPENSSL_RAND_CB)
3588
/* Initialize the mutex protecting the RAND method.
3589
 *
3590
 * Does nothing when the mutex is statically initialized.
3591
 *
3592
 * @return  0 on success.
3593
 * @return  BAD_MUTEX_E when initializing the mutex fails.
3594
 */
3595
static int wolfSSL_RAND_InitMutex(void)
3596
48
{
3597
#ifndef WOLFSSL_MUTEX_INITIALIZER
3598
    if (gRandMethodsInit == 0) {
3599
        if (wc_InitMutex(&gRandMethodMutex) != 0) {
3600
            WOLFSSL_MSG("Bad Init Mutex rand methods");
3601
            return BAD_MUTEX_E;
3602
        }
3603
        gRandMethodsInit = 1;
3604
    }
3605
#endif
3606
48
    return 0;
3607
48
}
3608
#endif
3609
3610
#ifdef OPENSSL_EXTRA
3611
3612
#if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \
3613
    ((defined(HAVE_FIPS) && FIPS_VERSION3_LE(6,0,0)) || defined(HAVE_SELFTEST))
3614
/* In older FIPS bundles add check for reseed here since it does not exist in
3615
 * the older random.c certified files. */
3616
static pid_t currentRandPid = 0;
3617
#endif
3618
3619
/* Checks if the global RNG has been created. If not then one is created.
3620
 *
3621
 * Returns WOLFSSL_SUCCESS when no error is encountered.
3622
 */
3623
int wolfSSL_RAND_Init(void)
3624
16
{
3625
16
    int ret = WC_NO_ERR_TRACE(WOLFSSL_FAILURE);
3626
16
#ifdef HAVE_GLOBAL_RNG
3627
16
    if (wc_LockMutex(&globalRNGMutex) == 0) {
3628
16
        if (initGlobalRNG == 0) {
3629
16
            ret = wc_InitRng(&globalRNG);
3630
16
            if (ret == 0) {
3631
            #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \
3632
                ((defined(HAVE_FIPS) && FIPS_VERSION3_LE(6,0,0)) || \
3633
                 defined(HAVE_SELFTEST))
3634
3635
                currentRandPid = getpid();
3636
            #endif
3637
16
                initGlobalRNG = 1;
3638
16
                ret = WOLFSSL_SUCCESS;
3639
16
            }
3640
16
        }
3641
0
        else {
3642
            /* GlobalRNG is already initialized */
3643
0
            ret = WOLFSSL_SUCCESS;
3644
0
        }
3645
3646
16
        wc_UnLockMutex(&globalRNGMutex);
3647
16
    }
3648
16
#endif
3649
16
    return ret;
3650
16
}
3651
3652
3653
/* WOLFSSL_SUCCESS on ok */
3654
int wolfSSL_RAND_seed(const void* seed, int len)
3655
16
{
3656
16
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
3657
16
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
3658
16
        if (gRandMethods && gRandMethods->seed) {
3659
0
            int ret = gRandMethods->seed(seed, len);
3660
0
            wc_UnLockMutex(&gRandMethodMutex);
3661
0
            return ret;
3662
0
        }
3663
16
        wc_UnLockMutex(&gRandMethodMutex);
3664
16
    }
3665
#else
3666
    (void)seed;
3667
    (void)len;
3668
#endif
3669
3670
    /* Make sure global shared RNG (globalRNG) is initialized */
3671
16
    return wolfSSL_RAND_Init();
3672
16
}
3673
3674
3675
/* Returns the path for reading seed data from.
3676
 * Uses the env variable $RANDFILE first if set, if not then used $HOME/.rnd
3677
 *
3678
 * Note uses stdlib by default unless XGETENV macro is overwritten
3679
 *
3680
 * fname buffer to hold path
3681
 * len   length of fname buffer
3682
 *
3683
 * Returns a pointer to fname on success and NULL on failure
3684
 */
3685
const char* wolfSSL_RAND_file_name(char* fname, unsigned long len)
3686
0
{
3687
0
#if !defined(NO_FILESYSTEM) && defined(XGETENV) && !defined(NO_GETENV)
3688
0
    char* rt;
3689
3690
0
    WOLFSSL_ENTER("wolfSSL_RAND_file_name");
3691
3692
0
    if (fname == NULL) {
3693
0
        return NULL;
3694
0
    }
3695
3696
0
    XMEMSET(fname, 0, len);
3697
3698
/* // NOLINTBEGIN(concurrency-mt-unsafe) */
3699
0
    if ((rt = XGETENV("RANDFILE")) != NULL) {
3700
0
        if (len > XSTRLEN(rt)) {
3701
0
            XMEMCPY(fname, rt, XSTRLEN(rt));
3702
0
        }
3703
0
        else {
3704
0
            WOLFSSL_MSG("RANDFILE too large for buffer");
3705
0
            rt = NULL;
3706
0
        }
3707
0
    }
3708
/* // NOLINTEND(concurrency-mt-unsafe) */
3709
3710
    /* $RANDFILE was not set or is too large, check $HOME */
3711
0
    if (rt == NULL) {
3712
0
        const char ap[] = "/.rnd";
3713
3714
0
        WOLFSSL_MSG("Environment variable RANDFILE not set");
3715
3716
/* // NOLINTBEGIN(concurrency-mt-unsafe) */
3717
0
        if ((rt = XGETENV("HOME")) == NULL) {
3718
            #ifdef XALTHOMEVARNAME
3719
            if ((rt = XGETENV(XALTHOMEVARNAME)) == NULL) {
3720
                WOLFSSL_MSG("Environment variable HOME and " XALTHOMEVARNAME
3721
                            " not set");
3722
                return NULL;
3723
            }
3724
            #else
3725
0
            WOLFSSL_MSG("Environment variable HOME not set");
3726
0
            return NULL;
3727
0
            #endif
3728
0
        }
3729
/* // NOLINTEND(concurrency-mt-unsafe) */
3730
3731
0
        if (len > XSTRLEN(rt) + XSTRLEN(ap)) {
3732
0
            fname[0] = '\0';
3733
0
            XSTRNCAT(fname, rt, len);
3734
0
            XSTRNCAT(fname, ap, len - XSTRLEN(rt));
3735
0
            return fname;
3736
0
        }
3737
0
        else {
3738
0
            WOLFSSL_MSG("Path too large for buffer");
3739
0
            return NULL;
3740
0
        }
3741
0
    }
3742
3743
0
    return fname;
3744
#else
3745
    WOLFSSL_ENTER("wolfSSL_RAND_file_name");
3746
    WOLFSSL_MSG("RAND_file_name requires filesystem and getenv support, "
3747
                "not compiled in");
3748
    (void)fname;
3749
    (void)len;
3750
    return NULL;
3751
#endif
3752
0
}
3753
3754
3755
#ifndef WOLFSSL_RAND_WRITE_FILE_BUF_SZ
3756
0
#define WOLFSSL_RAND_WRITE_FILE_BUF_SZ 1024
3757
#endif
3758
/* Writes WOLFSSL_RAND_WRITE_FILE_BUF_SZ bytes (1024 by default) from the RNG
3759
 * to the given file name.
3760
 *
3761
 * fname name of file to write to
3762
 *
3763
 * Returns the number of bytes written
3764
 */
3765
int wolfSSL_RAND_write_file(const char* fname)
3766
0
{
3767
0
    int bytes = 0;
3768
3769
0
    WOLFSSL_ENTER("wolfSSL_RAND_write_file");
3770
3771
0
    if (fname == NULL) {
3772
0
        return WOLFSSL_FAILURE;
3773
0
    }
3774
3775
0
#ifndef NO_FILESYSTEM
3776
0
    {
3777
    #ifndef WOLFSSL_SMALL_STACK
3778
        unsigned char buf[WOLFSSL_RAND_WRITE_FILE_BUF_SZ];
3779
    #else
3780
0
        unsigned char* buf = (unsigned char *)XMALLOC(
3781
0
            WOLFSSL_RAND_WRITE_FILE_BUF_SZ, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3782
0
        if (buf == NULL) {
3783
0
            WOLFSSL_MSG("malloc failed");
3784
0
            return WOLFSSL_FAILURE;
3785
0
        }
3786
0
    #endif
3787
0
        bytes = WOLFSSL_RAND_WRITE_FILE_BUF_SZ;
3788
3789
0
        if (initGlobalRNG == 0 && wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
3790
0
            WOLFSSL_MSG("No RNG to use");
3791
0
            WC_FREE_VAR_EX(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3792
0
            return 0;
3793
0
        }
3794
3795
0
        if (wc_LockMutex(&globalRNGMutex) != 0) {
3796
0
            WOLFSSL_MSG("Bad Lock Mutex rng");
3797
0
            WC_FREE_VAR_EX(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3798
0
            return 0;
3799
0
        }
3800
3801
0
        if (wc_RNG_GenerateBlock(&globalRNG, buf, (word32)bytes) != 0) {
3802
0
            wc_UnLockMutex(&globalRNGMutex);
3803
0
            WOLFSSL_MSG("Error generating random buffer");
3804
0
            bytes = 0;
3805
0
        }
3806
0
        else {
3807
0
            XFILE f;
3808
3809
0
            wc_UnLockMutex(&globalRNGMutex);
3810
3811
        #ifdef WOLFSSL_CHECK_MEM_ZERO
3812
            wc_MemZero_Add("wolfSSL_RAND_write_file buf", buf, bytes);
3813
        #endif
3814
3815
0
            f = XFOPEN(fname, "wb");
3816
0
            if (f == XBADFILE) {
3817
0
                WOLFSSL_MSG("Error opening the file");
3818
0
                bytes = 0;
3819
0
            }
3820
0
            else {
3821
0
                size_t bytes_written = XFWRITE(buf, 1, (size_t)bytes, f);
3822
0
                bytes = (int)bytes_written;
3823
0
                XFCLOSE(f);
3824
0
            }
3825
0
        }
3826
        /* wipe the whole buffer, not just (word32)bytes: error paths set
3827
         * bytes = 0 but the buffer may still hold generated random data */
3828
0
        ForceZero(buf, WOLFSSL_RAND_WRITE_FILE_BUF_SZ);
3829
0
    #ifdef WOLFSSL_SMALL_STACK
3830
0
        XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3831
    #elif defined(WOLFSSL_CHECK_MEM_ZERO)
3832
        wc_MemZero_Check(buf, sizeof(buf));
3833
    #endif
3834
0
    }
3835
0
#endif
3836
3837
0
    return bytes;
3838
0
}
3839
3840
#ifndef FREERTOS_TCP
3841
3842
/* These constant values are protocol values made by egd */
3843
#if defined(USE_WOLFSSL_IO) && !defined(USE_WINDOWS_API) && \
3844
    !defined(HAVE_FIPS) && defined(HAVE_HASHDRBG) && !defined(NETOS) && \
3845
    defined(HAVE_SYS_UN_H)
3846
0
    #define WOLFSSL_EGD_NBLOCK 0x01
3847
    #include <sys/un.h>
3848
#endif
3849
3850
/* This collects entropy from the path nm and seeds the global PRNG with it.
3851
 *
3852
 * nm is the file path to the egd server
3853
 *
3854
 * Returns the number of bytes read.
3855
 */
3856
int wolfSSL_RAND_egd(const char* nm)
3857
0
{
3858
0
#ifdef WOLFSSL_EGD_NBLOCK
3859
0
    struct sockaddr_un rem;
3860
0
    int fd;
3861
0
    int ret = WOLFSSL_SUCCESS;
3862
0
    word32 bytes = 0;
3863
0
    word32 idx   = 0;
3864
#ifndef WOLFSSL_SMALL_STACK
3865
    unsigned char buf[256];
3866
#else
3867
0
    unsigned char* buf;
3868
0
    buf = (unsigned char*)XMALLOC(256, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3869
0
    if (buf == NULL) {
3870
0
        WOLFSSL_MSG("Not enough memory");
3871
0
        return WOLFSSL_FATAL_ERROR;
3872
0
    }
3873
0
#endif
3874
3875
0
    XMEMSET(&rem, 0, sizeof(struct sockaddr_un));
3876
0
    if (nm == NULL) {
3877
0
        WC_FREE_VAR_EX(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3878
0
        return WOLFSSL_FATAL_ERROR;
3879
0
    }
3880
3881
0
    fd = wc_socket_cloexec(AF_UNIX, SOCK_STREAM, 0);
3882
0
    if (fd < 0) {
3883
0
        WOLFSSL_MSG("Error creating socket");
3884
0
        WC_FREE_VAR_EX(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
3885
0
        return WOLFSSL_FATAL_ERROR;
3886
0
    }
3887
0
    rem.sun_family = AF_UNIX;
3888
0
    XSTRNCPY(rem.sun_path, nm, sizeof(rem.sun_path) - 1);
3889
0
    rem.sun_path[sizeof(rem.sun_path)-1] = '\0';
3890
3891
    /* connect to egd server */
3892
0
    if (connect(fd, (struct sockaddr*)&rem, sizeof(struct sockaddr_un)) == -1) {
3893
0
        WOLFSSL_MSG("error connecting to egd server");
3894
0
        ret = WOLFSSL_FATAL_ERROR;
3895
0
    }
3896
3897
#ifdef WOLFSSL_CHECK_MEM_ZERO
3898
    if (ret == WOLFSSL_SUCCESS) {
3899
        wc_MemZero_Add("wolfSSL_RAND_egd buf", buf, 256);
3900
    }
3901
#endif
3902
0
    while (ret == WOLFSSL_SUCCESS && bytes < 255 && idx + 2 < 256) {
3903
0
        buf[idx]     = WOLFSSL_EGD_NBLOCK;
3904
0
        buf[idx + 1] = 255 - bytes; /* request 255 bytes from server */
3905
0
        ret = (int)write(fd, buf + idx, 2);
3906
0
        if (ret != 2) {
3907
0
            if (errno == EAGAIN) {
3908
0
                ret = WOLFSSL_SUCCESS;
3909
0
                continue;
3910
0
            }
3911
0
            WOLFSSL_MSG("error requesting entropy from egd server");
3912
0
            ret = WOLFSSL_FATAL_ERROR;
3913
0
            break;
3914
0
        }
3915
3916
        /* attempting to read */
3917
0
        buf[idx] = 0;
3918
0
        ret = (int)read(fd, buf + idx, 256 - bytes);
3919
0
        if (ret == 0) {
3920
0
            WOLFSSL_MSG("error reading entropy from egd server");
3921
0
            ret = WOLFSSL_FATAL_ERROR;
3922
0
            break;
3923
0
        }
3924
0
        if (ret > 0 && buf[idx] > 0) {
3925
0
            bytes += buf[idx]; /* egd stores amount sent in first byte */
3926
0
            if (bytes + idx > 255 || buf[idx] > ret) {
3927
0
                WOLFSSL_MSG("Buffer error");
3928
0
                ret = WOLFSSL_FATAL_ERROR;
3929
0
                break;
3930
0
            }
3931
0
            XMEMMOVE(buf + idx, buf + idx + 1, buf[idx]);
3932
0
            idx = bytes;
3933
0
            ret = WOLFSSL_SUCCESS;
3934
0
            if (bytes >= 255) {
3935
0
                break;
3936
0
            }
3937
0
        }
3938
0
        else {
3939
0
            if (errno == EAGAIN || errno == EINTR) {
3940
0
                WOLFSSL_MSG("EGD would read");
3941
0
                ret = WOLFSSL_SUCCESS; /* try again */
3942
0
            }
3943
0
            else if (buf[idx] == 0) {
3944
                /* if egd returned 0 then there is no more entropy to be had.
3945
                   Do not try more reads. */
3946
0
                ret = WOLFSSL_SUCCESS;
3947
0
                break;
3948
0
            }
3949
0
            else {
3950
0
                WOLFSSL_MSG("Error with read");
3951
0
                ret = WOLFSSL_FATAL_ERROR;
3952
0
            }
3953
0
        }
3954
0
    }
3955
3956
0
    if (bytes > 0 && ret == WOLFSSL_SUCCESS) {
3957
        /* call to check global RNG is created */
3958
0
        if (wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
3959
0
            WOLFSSL_MSG("Error with initializing global RNG structure");
3960
0
            ret = WOLFSSL_FATAL_ERROR;
3961
0
        }
3962
0
        else if (wc_LockMutex(&globalRNGMutex) != 0) {
3963
0
            WOLFSSL_MSG("Bad Lock Mutex rng");
3964
0
            ret = WOLFSSL_FATAL_ERROR;
3965
0
        }
3966
0
        else {
3967
0
#ifdef WC_RNG_HAVE_STIR
3968
            /* Caller material carries no entropy credit; mix it as an
3969
             * uncredited stir -- credited user-class reseeds of conformant
3970
             * instances are refused with WC_RNG_RBGC_STRATUM_IMMUTABLE.
3971
             * A standing reseed or recovery obligation (NEEDS_RECOVERY_E:
3972
             * credited reseed due, invalidation latched, or epoch stale;
3973
             * NOT_READY_E: the reseed interval tripped within the call)
3974
             * outranks advisory material and is not a failure: the next
3975
             * generate performs the credited reseed. */
3976
0
            {
3977
0
                int stir_ret = wc_RNG_DRBG_Stir(&globalRNG,
3978
0
                                                (const byte*) buf, bytes);
3979
0
                if ((stir_ret != 0) &&
3980
0
                    (stir_ret != WC_NO_ERR_TRACE(NOT_READY_E)) &&
3981
0
                    (stir_ret != WC_NO_ERR_TRACE(NEEDS_RECOVERY_E)))
3982
0
                {
3983
0
                    WOLFSSL_MSG("Error with stirring DRBG structure");
3984
0
                    ret = WOLFSSL_FATAL_ERROR;
3985
0
                }
3986
0
            }
3987
#else
3988
            if (wc_RNG_DRBG_Reseed(&globalRNG, (const byte*) buf, bytes)
3989
                    != 0) {
3990
                WOLFSSL_MSG("Error with reseeding DRBG structure");
3991
                ret = WOLFSSL_FATAL_ERROR;
3992
            }
3993
#endif
3994
0
            wc_UnLockMutex(&globalRNGMutex);
3995
3996
            #ifdef SHOW_SECRETS
3997
            /* print out entropy found only when no error occurred */
3998
            if (ret == WOLFSSL_SUCCESS) {
3999
                word32 i;
4000
                printf("EGD Entropy = ");
4001
                for (i = 0; i < bytes; i++) {
4002
                    printf("%02X", buf[i]);
4003
                }
4004
                printf("\n");
4005
            }
4006
            #endif
4007
0
        }
4008
0
    }
4009
4010
0
    ForceZero(buf, bytes);
4011
0
#ifdef WOLFSSL_SMALL_STACK
4012
0
    XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4013
#elif defined(WOLFSSL_CHECK_MEM_ZERO)
4014
    wc_MemZero_Check(buf, 256);
4015
#endif
4016
0
    close(fd);
4017
4018
0
    if (ret == WOLFSSL_SUCCESS) {
4019
0
        return (int)bytes;
4020
0
    }
4021
0
    else {
4022
0
        return ret;
4023
0
    }
4024
#else
4025
    WOLFSSL_MSG("Type of socket needed is not available");
4026
    WOLFSSL_MSG("\tor using mode where DRBG API is not available");
4027
    (void)nm;
4028
4029
    return WOLFSSL_FATAL_ERROR;
4030
#endif /* WOLFSSL_EGD_NBLOCK */
4031
0
}
4032
4033
#endif /* !FREERTOS_TCP */
4034
4035
void wolfSSL_RAND_Cleanup(void)
4036
16
{
4037
16
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
4038
16
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
4039
16
        if (gRandMethods && gRandMethods->cleanup)
4040
0
            gRandMethods->cleanup();
4041
16
        wc_UnLockMutex(&gRandMethodMutex);
4042
16
    }
4043
4044
    #ifndef WOLFSSL_MUTEX_INITIALIZER
4045
    if (wc_FreeMutex(&gRandMethodMutex) == 0)
4046
        gRandMethodsInit = 0;
4047
    #endif
4048
16
#endif
4049
16
#ifdef HAVE_GLOBAL_RNG
4050
16
    if (wc_LockMutex(&globalRNGMutex) == 0) {
4051
16
        if (initGlobalRNG) {
4052
16
            wc_FreeRng(&globalRNG);
4053
16
            initGlobalRNG = 0;
4054
16
        }
4055
16
        wc_UnLockMutex(&globalRNGMutex);
4056
16
    }
4057
16
#endif
4058
16
}
4059
4060
/* returns WOLFSSL_SUCCESS if the bytes generated are valid otherwise
4061
 * WOLFSSL_FAILURE */
4062
int wolfSSL_RAND_pseudo_bytes(unsigned char* buf, int num)
4063
0
{
4064
0
    int ret;
4065
0
    int hash;
4066
0
    byte secret[DRBG_SEED_LEN]; /* secret length arbitrarily chosen */
4067
4068
0
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
4069
0
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
4070
0
        if (gRandMethods && gRandMethods->pseudorand) {
4071
0
            ret = gRandMethods->pseudorand(buf, num);
4072
0
            wc_UnLockMutex(&gRandMethodMutex);
4073
0
            return ret;
4074
0
        }
4075
0
        wc_UnLockMutex(&gRandMethodMutex);
4076
0
    }
4077
0
#endif
4078
4079
0
#ifdef WOLFSSL_HAVE_PRF
4080
0
    #ifndef NO_SHA256
4081
0
    hash = WC_SHA256;
4082
    #elif defined(WOLFSSL_SHA384)
4083
    hash = WC_SHA384;
4084
    #elif !defined(NO_SHA)
4085
    hash = WC_SHA;
4086
    #elif !defined(NO_MD5)
4087
    hash = WC_MD5;
4088
    #else
4089
    #error "No PRF hash function available"
4090
    #endif
4091
4092
    /* get secret value from source of entropy */
4093
0
    ret = wolfSSL_RAND_bytes(secret, DRBG_SEED_LEN);
4094
4095
    /* uses input buffer to seed for pseudo random number generation, each
4096
     * thread will potentially have different results this way */
4097
0
    if (ret == WOLFSSL_SUCCESS) {
4098
0
        PRIVATE_KEY_UNLOCK();
4099
0
        ret = wc_PRF(buf, num, secret, DRBG_SEED_LEN, (const byte*)buf, num,
4100
0
                hash, NULL, INVALID_DEVID);
4101
0
        PRIVATE_KEY_LOCK();
4102
0
        ret = (ret == 0) ? WOLFSSL_SUCCESS: WOLFSSL_FAILURE;
4103
0
    }
4104
0
    ForceZero(secret, sizeof(secret));
4105
#else
4106
    /* fall back to just doing wolfSSL_RAND_bytes if PRF not avialbale */
4107
    ret = wolfSSL_RAND_bytes(buf, num);
4108
    (void)hash;
4109
    (void)secret;
4110
#endif
4111
0
    return ret;
4112
0
}
4113
4114
/* returns WOLFSSL_SUCCESS (1) if the bytes generated are valid otherwise 0
4115
 * on failure */
4116
int wolfSSL_RAND_bytes(unsigned char* buf, int num)
4117
0
{
4118
0
    int     ret = 0;
4119
0
    WC_RNG* rng = NULL;
4120
0
    WC_DECLARE_VAR(tmpRNG, WC_RNG, 1, 0);
4121
0
    int initTmpRng = 0;
4122
0
#ifdef HAVE_GLOBAL_RNG
4123
0
    int used_global = 0;
4124
0
#endif
4125
4126
0
    WOLFSSL_ENTER("wolfSSL_RAND_bytes");
4127
    /* sanity check */
4128
0
    if (buf == NULL || num < 0)
4129
        /* return code compliant with OpenSSL */
4130
0
        return 0;
4131
4132
    /* if a RAND callback has been set try and use it */
4133
0
#ifndef WOLFSSL_NO_OPENSSL_RAND_CB
4134
0
    if (wolfSSL_RAND_InitMutex() == 0 && wc_LockMutex(&gRandMethodMutex) == 0) {
4135
0
        if (gRandMethods && gRandMethods->bytes) {
4136
0
            ret = gRandMethods->bytes(buf, num);
4137
0
            wc_UnLockMutex(&gRandMethodMutex);
4138
0
            return ret;
4139
0
        }
4140
0
        wc_UnLockMutex(&gRandMethodMutex);
4141
0
    }
4142
0
#endif
4143
0
#ifdef HAVE_GLOBAL_RNG
4144
0
    if (initGlobalRNG) {
4145
0
        if (wc_LockMutex(&globalRNGMutex) != 0) {
4146
0
            WOLFSSL_MSG("Bad Lock Mutex rng");
4147
0
            return ret;
4148
0
        }
4149
        /* the above access to initGlobalRNG is racey -- recheck it now that we
4150
         * have the lock.
4151
         */
4152
0
        if (initGlobalRNG) {
4153
        #if defined(HAVE_GETPID) && !defined(WOLFSSL_NO_GETPID) && \
4154
                ((defined(HAVE_FIPS) && FIPS_VERSION3_LE(6,0,0)) || \
4155
                 defined(HAVE_SELFTEST))
4156
            pid_t p;
4157
4158
            p = getpid();
4159
            if (p != currentRandPid) {
4160
                wc_UnLockMutex(&globalRNGMutex);
4161
                if (wolfSSL_RAND_poll() != WOLFSSL_SUCCESS) {
4162
                    WOLFSSL_MSG("Issue with check pid and reseed");
4163
                    ret = WOLFSSL_FAILURE;
4164
                }
4165
4166
                /* reclaim lock after wolfSSL_RAND_poll */
4167
                if (wc_LockMutex(&globalRNGMutex) != 0) {
4168
                    WOLFSSL_MSG("Bad Lock Mutex rng");
4169
                    return ret;
4170
                }
4171
                currentRandPid = p;
4172
            }
4173
        #endif
4174
0
            rng = &globalRNG;
4175
0
            used_global = 1;
4176
0
        }
4177
0
        else {
4178
0
            wc_UnLockMutex(&globalRNGMutex);
4179
0
        }
4180
0
    }
4181
4182
0
    if (used_global == 0)
4183
0
#endif
4184
0
    {
4185
0
        WC_ALLOC_VAR_EX(tmpRNG, WC_RNG, 1, NULL, DYNAMIC_TYPE_RNG,
4186
0
            return ret);
4187
0
        if (wc_InitRng(tmpRNG) == 0) {
4188
0
            rng = tmpRNG;
4189
0
            initTmpRng = 1;
4190
0
        }
4191
0
    }
4192
0
    if (rng) {
4193
        /* handles size greater than RNG_MAX_BLOCK_LEN */
4194
0
        int blockCount = num / RNG_MAX_BLOCK_LEN;
4195
4196
0
        while (blockCount--) {
4197
0
            ret = wc_RNG_GenerateBlock(rng, buf, RNG_MAX_BLOCK_LEN);
4198
0
            if (ret != 0) {
4199
0
                WOLFSSL_MSG("Bad wc_RNG_GenerateBlock");
4200
0
                break;
4201
0
            }
4202
0
            num -= RNG_MAX_BLOCK_LEN;
4203
0
            buf += RNG_MAX_BLOCK_LEN;
4204
0
        }
4205
4206
0
        if (ret == 0 && num)
4207
0
            ret = wc_RNG_GenerateBlock(rng, buf, (word32)num);
4208
4209
0
        if (ret != 0)
4210
0
            WOLFSSL_MSG("Bad wc_RNG_GenerateBlock");
4211
0
        else
4212
0
            ret = WOLFSSL_SUCCESS;
4213
0
    }
4214
4215
0
#ifdef HAVE_GLOBAL_RNG
4216
0
    if (used_global == 1)
4217
0
        wc_UnLockMutex(&globalRNGMutex);
4218
0
#endif
4219
0
    if (initTmpRng)
4220
0
        wc_FreeRng(tmpRNG);
4221
0
    WC_FREE_VAR_EX(tmpRNG, NULL, DYNAMIC_TYPE_RNG);
4222
4223
0
    return ret;
4224
0
}
4225
4226
4227
/* Reseed the global random number generator with entropy from the system.
4228
 *
4229
 * @return  WOLFSSL_SUCCESS on success.
4230
 * @return  WOLFSSL_FAILURE when the global RNG is not initialized, getting the
4231
 *          seed fails, reseeding fails or there is no DRBG to reseed.
4232
 */
4233
int wolfSSL_RAND_poll(void)
4234
0
{
4235
0
    int  ret = 0;
4236
4237
0
    WOLFSSL_ENTER("wolfSSL_RAND_poll");
4238
0
    if (initGlobalRNG == 0){
4239
0
        WOLFSSL_MSG("Global RNG no Init");
4240
0
        return  WOLFSSL_FAILURE;
4241
0
    }
4242
4243
    /* lock intentionally covers wc_GenerateSeed as well, since it writes
4244
     * globalRNG.seed; do not narrow this scope or the seed write races */
4245
0
    if (wc_LockMutex(&globalRNGMutex) != 0) {
4246
0
        WOLFSSL_MSG("Bad Lock Mutex rng");
4247
0
        return WOLFSSL_FAILURE;
4248
0
    }
4249
4250
0
#ifdef HAVE_HASHDRBG
4251
4252
0
  #ifdef WC_RNG_HAVE_RESEED_NOW
4253
4254
0
    ret = wc_RNG_DRBG_Reseed_Now(&globalRNG, NULL, 0);
4255
0
    if (ret == 0) {
4256
0
        ret = WOLFSSL_SUCCESS;
4257
0
    }
4258
0
    else {
4259
0
        WOLFSSL_MSG("Bad wc_RNG_DRBG_Reseed_Now");
4260
0
        ret = WOLFSSL_FAILURE;
4261
0
    }
4262
4263
  #else /* !WC_RNG_HAVE_RESEED_NOW: random.h predates wc_RNG_DRBG_Reseed_Now() */
4264
4265
    {
4266
        byte  entropy[16];
4267
        word32 entropy_sz = 16;
4268
4269
        ret = wc_GenerateSeed(&globalRNG.seed, entropy, entropy_sz);
4270
        if (ret != 0) {
4271
            WOLFSSL_MSG("Bad wc_GenerateSeed");
4272
            ret = WOLFSSL_FAILURE;
4273
        }
4274
        else {
4275
            ret = wc_RNG_DRBG_Reseed(&globalRNG, entropy, entropy_sz);
4276
            if (ret != 0) {
4277
                WOLFSSL_MSG("Error reseeding DRBG");
4278
                ret = WOLFSSL_FAILURE;
4279
            }
4280
            else {
4281
                ret = WOLFSSL_SUCCESS;
4282
            }
4283
        }
4284
4285
        ForceZero(entropy, sizeof(entropy));
4286
    }
4287
4288
  #endif /* WC_RNG_HAVE_RESEED_NOW */
4289
4290
#elif defined(HAVE_INTEL_RDRAND)
4291
    WOLFSSL_MSG("Not polling with RAND_poll, RDRAND used without "
4292
                "HAVE_HASHDRBG");
4293
    ret = WOLFSSL_SUCCESS;
4294
#else /* !HAVE_HASHDRBG && !HAVE_INTEL_RDRAND */
4295
    WOLFSSL_MSG("RAND_poll called with HAVE_HASHDRBG not set");
4296
    ret = WOLFSSL_FAILURE;
4297
#endif
4298
4299
0
    wc_UnLockMutex(&globalRNGMutex);
4300
4301
0
    return ret;
4302
0
}
4303
4304
    /* If a valid struct is provided with function pointers, will override
4305
       RAND_seed, bytes, cleanup, add, pseudo_bytes and status.  If a NULL
4306
       pointer is passed in, it will cancel any previous function overrides.
4307
4308
       Returns WOLFSSL_SUCCESS on success, WOLFSSL_FAILURE on failure. */
4309
    int wolfSSL_RAND_set_rand_method(const WOLFSSL_RAND_METHOD *methods)
4310
0
    {
4311
0
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
4312
0
        if (wolfSSL_RAND_InitMutex() == 0 &&
4313
0
                wc_LockMutex(&gRandMethodMutex) == 0) {
4314
0
            gRandMethods = methods;
4315
0
            wc_UnLockMutex(&gRandMethodMutex);
4316
0
            return WOLFSSL_SUCCESS;
4317
0
        }
4318
    #else
4319
        (void)methods;
4320
    #endif
4321
0
        return WOLFSSL_FAILURE;
4322
0
    }
4323
4324
    /* Returns WOLFSSL_SUCCESS if the RNG has been seeded with enough data */
4325
    int wolfSSL_RAND_status(void)
4326
0
    {
4327
0
        int ret = WOLFSSL_SUCCESS;
4328
0
        int useGlobalRng = 1;
4329
0
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
4330
0
        if (wolfSSL_RAND_InitMutex() == 0 &&
4331
0
                wc_LockMutex(&gRandMethodMutex) == 0) {
4332
0
            if (gRandMethods && gRandMethods->status) {
4333
0
                ret = gRandMethods->status();
4334
0
                useGlobalRng = 0;
4335
0
            }
4336
0
            wc_UnLockMutex(&gRandMethodMutex);
4337
0
        }
4338
0
        else {
4339
0
            ret = WOLFSSL_FAILURE;
4340
0
            useGlobalRng = 0;
4341
0
        }
4342
0
    #endif
4343
4344
        /* Drive the global RNG so init / DRBG state failures (mutex
4345
         * acquisition, reseed required, corrupted state) surface to the
4346
         * caller. DRBG output is deterministic between reseeds, so this
4347
         * does not directly probe the entropy source. */
4348
0
    #ifdef HAVE_GLOBAL_RNG
4349
0
        if (useGlobalRng) {
4350
0
            if (wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
4351
0
                ret = WOLFSSL_FAILURE;
4352
0
            }
4353
0
            else if (wc_LockMutex(&globalRNGMutex) != 0) {
4354
0
                ret = WOLFSSL_FAILURE;
4355
0
            }
4356
0
            else {
4357
0
                byte b = 0;
4358
0
                int genRet = wc_RNG_GenerateBlock(&globalRNG, &b, 1);
4359
0
                wc_UnLockMutex(&globalRNGMutex);
4360
0
                ForceZero(&b, 1);
4361
0
                if (genRet != 0)
4362
0
                    ret = WOLFSSL_FAILURE;
4363
0
            }
4364
0
        }
4365
0
    #endif
4366
0
        (void)useGlobalRng;
4367
0
        return ret;
4368
0
    }
4369
4370
    /* Add seed data to the random number generator.
4371
     *
4372
     * Calls the add method of the RAND method when set. Otherwise the data is
4373
     * used to reseed the global DRBG.
4374
     *
4375
     * @param [in] add      Seed data.
4376
     * @param [in] len      Length of seed data in bytes.
4377
     * @param [in] entropy  Estimate of entropy in the data. Not used.
4378
     */
4379
    void wolfSSL_RAND_add(const void* add, int len, double entropy)
4380
0
    {
4381
0
    #ifndef WOLFSSL_NO_OPENSSL_RAND_CB
4382
0
        if (wolfSSL_RAND_InitMutex() == 0 &&
4383
0
                wc_LockMutex(&gRandMethodMutex) == 0) {
4384
0
            if (gRandMethods && gRandMethods->add) {
4385
                /* callback has return code, but RAND_add does not */
4386
0
                (void)gRandMethods->add(add, len, entropy);
4387
0
            }
4388
0
            wc_UnLockMutex(&gRandMethodMutex);
4389
0
        }
4390
    #else
4391
        /* wolfSSL seeds/adds internally, use explicit RNG if you want
4392
           to take control */
4393
        (void)add;
4394
        (void)len;
4395
        (void)entropy;
4396
    #endif
4397
0
    }
4398
4399
4400
#ifndef NO_WOLFSSL_STUB
4401
/* Add screen contents to the random number generator.
4402
 *
4403
 * Not implemented. For OpenSSL compatibility only.
4404
 */
4405
void wolfSSL_RAND_screen(void)
4406
0
{
4407
0
    WOLFSSL_STUB("RAND_screen");
4408
0
}
4409
#endif
4410
4411
#ifndef WOLFSSL_RAND_LOAD_FILE_BUF_SZ
4412
0
#define WOLFSSL_RAND_LOAD_FILE_BUF_SZ 256
4413
#endif
4414
#ifndef WOLFSSL_RAND_LOAD_FILE_MAX_BYTES
4415
0
#define WOLFSSL_RAND_LOAD_FILE_MAX_BYTES (1L << 20)
4416
#endif
4417
4418
/* Seed the random number generator with the contents of a file.
4419
 *
4420
 * Data read is used to reseed the global DRBG.
4421
 *
4422
 * @param [in] fname  Name of file to read seed data from.
4423
 * @param [in] len    Maximum number of bytes to read. -1 to read up to
4424
 *                    WOLFSSL_RAND_LOAD_FILE_MAX_BYTES.
4425
 * @return  Number of bytes read on success.
4426
 * @return  0 when len is 0.
4427
 * @return  WOLFSSL_FATAL_ERROR when fname is NULL, the file cannot be opened,
4428
 *          the global RNG is not available, reseeding fails or dynamic memory
4429
 *          allocation fails.
4430
 */
4431
int wolfSSL_RAND_load_file(const char* fname, long len)
4432
0
{
4433
0
#if !defined(NO_FILESYSTEM) && defined(HAVE_HASHDRBG)
4434
0
    XFILE  f;
4435
0
    long   maxBytes;
4436
0
    long   readSoFar = 0;
4437
0
    int    ret = 0;
4438
#ifndef WOLFSSL_SMALL_STACK
4439
    unsigned char buf[WOLFSSL_RAND_LOAD_FILE_BUF_SZ];
4440
#else
4441
0
    unsigned char* buf;
4442
0
#endif
4443
4444
0
    WOLFSSL_ENTER("wolfSSL_RAND_load_file");
4445
4446
0
    if (fname == NULL)
4447
0
        return WOLFSSL_FATAL_ERROR;
4448
4449
    /* OpenSSL semantics: RAND_load_file(file, -1) reads up to an
4450
     * implementation-defined maximum. WOLFSSL_RAND_LOAD_FILE_MAX_BYTES
4451
     * caps the read so callers passing -1 to ingest a seed file aren't
4452
     * silently truncated at a small default. */
4453
0
    maxBytes = (len < 0) ? WOLFSSL_RAND_LOAD_FILE_MAX_BYTES : len;
4454
0
    if (maxBytes == 0)
4455
0
        return 0;
4456
4457
0
    f = XFOPEN(fname, "rb");
4458
0
    if (f == XBADFILE) {
4459
0
        WOLFSSL_MSG("RAND_load_file: cannot open file");
4460
0
        return WOLFSSL_FATAL_ERROR;
4461
0
    }
4462
4463
0
#ifdef WOLFSSL_SMALL_STACK
4464
0
    buf = (unsigned char*)XMALLOC(WOLFSSL_RAND_LOAD_FILE_BUF_SZ, NULL,
4465
0
        DYNAMIC_TYPE_TMP_BUFFER);
4466
0
    if (buf == NULL) {
4467
0
        XFCLOSE(f);
4468
0
        return WOLFSSL_FATAL_ERROR;
4469
0
    }
4470
0
#endif
4471
#ifdef WOLFSSL_CHECK_MEM_ZERO
4472
    wc_MemZero_Add("wolfSSL_RAND_load_file buf", buf,
4473
        WOLFSSL_RAND_LOAD_FILE_BUF_SZ);
4474
#endif
4475
4476
0
    if (initGlobalRNG == 0 && wolfSSL_RAND_Init() != WOLFSSL_SUCCESS) {
4477
0
        WOLFSSL_MSG("RAND_load_file: global RNG not available");
4478
0
        ret = WOLFSSL_FATAL_ERROR;
4479
0
        goto cleanup;
4480
0
    }
4481
4482
0
    while (readSoFar < maxBytes) {
4483
0
        size_t toRead = (size_t)((maxBytes - readSoFar) <
4484
0
                WOLFSSL_RAND_LOAD_FILE_BUF_SZ
4485
0
            ? (maxBytes - readSoFar) : WOLFSSL_RAND_LOAD_FILE_BUF_SZ);
4486
0
        size_t n = XFREAD(buf, 1, toRead, f);
4487
0
        if (n == 0)
4488
0
            break;
4489
0
        if (wc_LockMutex(&globalRNGMutex) != 0) {
4490
0
            ret = WOLFSSL_FATAL_ERROR;
4491
0
            break;
4492
0
        }
4493
0
  #ifdef WC_RNG_HAVE_STIR
4494
        /* File material carries no entropy credit; mix it as an uncredited
4495
         * stir.  A standing reseed or recovery obligation (NEEDS_RECOVERY_E,
4496
         * NOT_READY_E -- see wolfSSL_RAND_egd()) is not a failure. */
4497
0
        {
4498
0
            int stir_ret = wc_RNG_DRBG_Stir(&globalRNG, buf, (word32)n);
4499
0
            if ((stir_ret != 0) &&
4500
0
                (stir_ret != WC_NO_ERR_TRACE(NOT_READY_E)) &&
4501
0
                (stir_ret != WC_NO_ERR_TRACE(NEEDS_RECOVERY_E)))
4502
0
            {
4503
0
                wc_UnLockMutex(&globalRNGMutex);
4504
0
                WOLFSSL_MSG("RAND_load_file: DRBG stir failed");
4505
0
                ret = WOLFSSL_FATAL_ERROR;
4506
0
                break;
4507
0
            }
4508
0
        }
4509
#else
4510
        if (wc_RNG_DRBG_Reseed(&globalRNG, buf, (word32)n) != 0) {
4511
            wc_UnLockMutex(&globalRNGMutex);
4512
            WOLFSSL_MSG("RAND_load_file: DRBG reseed failed");
4513
            ret = WOLFSSL_FATAL_ERROR;
4514
            break;
4515
        }
4516
#endif
4517
0
        wc_UnLockMutex(&globalRNGMutex);
4518
0
        readSoFar += (long)n;
4519
0
    }
4520
4521
0
cleanup:
4522
0
    XFCLOSE(f);
4523
0
    ForceZero(buf, WOLFSSL_RAND_LOAD_FILE_BUF_SZ);
4524
0
#ifdef WOLFSSL_SMALL_STACK
4525
0
    XFREE(buf, NULL, DYNAMIC_TYPE_TMP_BUFFER);
4526
#elif defined(WOLFSSL_CHECK_MEM_ZERO)
4527
    wc_MemZero_Check(buf, WOLFSSL_RAND_LOAD_FILE_BUF_SZ);
4528
#endif
4529
4530
0
    if (ret < 0)
4531
0
        return WOLFSSL_FATAL_ERROR;
4532
0
    return (int)readSoFar;
4533
#else
4534
    /* Without HAVE_HASHDRBG / filesystem support there is no way to feed
4535
     * external entropy to the wolfCrypt RNG; return success so callers
4536
     * in those configurations are not broken. */
4537
    (void)fname;
4538
    if (len == -1)
4539
        return 1024;
4540
    return (int)len;
4541
#endif
4542
0
}
4543
4544
#endif /* OPENSSL_EXTRA */
4545
4546
/*******************************************************************************
4547
 * END OF RAND API
4548
 ******************************************************************************/
4549
4550
#endif /* !WOLFCRYPT_ONLY */
4551
4552
#endif /* WOLFSSL_SSL_CRYPTO_INCLUDED */
4553