Coverage Report

Created: 2026-10-31 07:16

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/wolfssl-normal-math/wolfcrypt/src/rsa.c
Line
Count
Source
1
/* rsa.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
/*
23
24
DESCRIPTION
25
This library provides the interface to the RSA.
26
RSA keys can be used to encrypt, decrypt, sign and verify data.
27
28
*/
29
30
#define WC_FIPS_LL_CRYPTO
31
#define _WC_BUILDING_RSA_C
32
33
#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
34
35
#ifndef NO_RSA
36
37
#if FIPS_VERSION3_GE(2,0,0)
38
       #if defined(USE_WINDOWS_API) && defined(_MSC_VER)
39
               #pragma code_seg(".fipsA$j")
40
               #pragma const_seg(".fipsB$j")
41
       #endif
42
#endif
43
44
#include <wolfssl/wolfcrypt/rsa.h>
45
#include <wolfssl/wolfcrypt/logging.h>
46
47
#ifdef WOLFSSL_AFALG_XILINX_RSA
48
#include <wolfssl/wolfcrypt/port/af_alg/wc_afalg.h>
49
#endif
50
#if defined(WOLFSSL_XILINX_CRYPT_VERSAL)
51
#include <xsecure_rsaclient.h>
52
#endif
53
#if defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA)
54
#include <wolfssl/wolfcrypt/port/nxp/se050_port.h>
55
#endif
56
#ifdef WOLFSSL_HAVE_SP_RSA
57
#include <wolfssl/wolfcrypt/sp.h>
58
#endif
59
#if defined(WOLFSSL_NXP_CASPER_RSA_PUB_EXPTMOD)
60
#include <wolfssl/wolfcrypt/port/nxp/casper_port.h>
61
#endif
62
63
/*
64
 * RSA Build Options:
65
 *
66
 * Core:
67
 * NO_RSA:                  Disable RSA support entirely            default: off
68
 * WOLFSSL_RSA_PUBLIC_ONLY: Only include RSA public key operations  default: off
69
 * WOLFSSL_RSA_VERIFY_ONLY: Only include RSA verify operation       default: off
70
 * WOLFSSL_RSA_VERIFY_INLINE: RSA verify inline (no output copy)   default: off
71
 * WC_RSA_DIRECT:           Enable direct RSA encrypt/decrypt API   default: off
72
 * WC_RSA_NO_PADDING:       Enable no-padding RSA mode              default: off
73
 * WOLFSSL_RSA_KEY_CHECK:   Enable RSA key pair consistency check   default: off
74
 * WOLFSSL_RSA_CHECK_D_ON_DECRYPT: Validate private exponent d     default: off
75
 *                           before each decrypt operation
76
 * WOLFSSL_RSA_DECRYPT_TO_0_LEN: Allow RSA decrypt result of 0     default: off
77
 *                           length (empty plaintext)
78
 * NO_RSA_BOUNDS_CHECK:     Disable RSA bounds checking on input    default: off
79
 * SHOW_GEN:                Show key generation progress dots        default: off
80
 *
81
 * Padding:
82
 * WC_RSA_PSS:              Enable RSA-PSS signature support        default: off
83
 * WC_NO_RSA_OAEP:          Disable RSA OAEP padding                default: off
84
 * WOLFSSL_PSS_LONG_SALT:   Allow PSS salt longer than hash length  default: off
85
 * WOLFSSL_PSS_SALT_LEN_DISCOVER: Auto-discover PSS salt length    default: off
86
 *                           during verification
87
 *
88
 * Performance:
89
 * WC_RSA_BLINDING:         Use blinding with private key ops       default: on
90
 *                           Note: ~20% slower, protects against
91
 *                           timing side-channels
92
 * RSA_LOW_MEM:             Non-CRT private ops, less memory        default: off
93
 * WC_RSA_NONBLOCK:         Non-blocking RSA operations             default: off
94
 * WC_RSA_NONBLOCK_TIME:    Time-based non-blocking RSA             default: off
95
 * WOLFSSL_MP_INVMOD_CONSTANT_TIME: Constant-time modular inverse  default: off
96
 * WC_RSA_NO_FERMAT_CHECK:  Skip Fermat factorization check on     default: off
97
 *                           key generation (p and q closeness)
98
 *
99
 * Key Generation:
100
 * WOLFSSL_KEY_GEN:         Enable RSA private key generation       default: off
101
 * FP_MAX_BITS:             Max key bits with USE_FAST_MATH         default: 4096
102
 *                           Value is key size * 2 (e.g. RSA 3072 = 6144)
103
 *
104
 * SP Math:
105
 * WOLFSSL_HAVE_SP_RSA:     Use SP math for RSA operations          default: off
106
 * WOLFSSL_SP_MATH:         Use SP math only (no multi-precision)   default: off
107
 * WOLFSSL_SP_MATH_ALL:     SP math for all key sizes               default: off
108
 * WOLFSSL_SP_NO_2048:      Disable SP RSA 2048-bit support         default: off
109
 * WOLFSSL_SP_NO_3072:      Disable SP RSA 3072-bit support         default: off
110
 * WOLFSSL_SP_4096:         Enable SP RSA 4096-bit support          default: off
111
 * WOLFSSL_SP_ASM:          Use SP assembly optimizations           default: off
112
 *
113
 * Hardware Acceleration (RSA-specific):
114
 * WC_ASYNC_ENABLE_RSA:     Enable async RSA operations             default: off
115
 * WOLFSSL_KCAPI_RSA:       Linux kernel crypto API for RSA         default: off
116
 * WOLFSSL_AFALG_XILINX_RSA: AF_ALG Xilinx RSA acceleration        default: off
117
 * WOLFSSL_SE050_NO_RSA:    Disable SE050 RSA                       default: off
118
 * WOLFSSL_XILINX_CRYPT:    Xilinx crypto RSA acceleration          default: off
119
 * WOLFSSL_NO_RSA_SW:       No software RSA, hardware only          default: off
120
 */
121
122
123
#include <wolfssl/wolfcrypt/random.h>
124
#ifdef WOLF_CRYPTO_CB
125
    #include <wolfssl/wolfcrypt/cryptocb.h>
126
#endif
127
#ifdef NO_INLINE
128
    #include <wolfssl/wolfcrypt/misc.h>
129
#else
130
    #define WOLFSSL_MISC_INCLUDED
131
    #include <wolfcrypt/src/misc.c>
132
#endif
133
134
#if FIPS_VERSION3_GE(6,0,0)
135
    const unsigned int wolfCrypt_FIPS_rsa_ro_sanity[2] =
136
                                                     { 0x1a2b3c4d, 0x00000012 };
137
    int wolfCrypt_FIPS_RSA_sanity(void)
138
    {
139
        return 0;
140
    }
141
#endif
142
143
/* The software padding generation (and with it the OAEP/PSS mask generation
144
 * and un-padding helpers) is only reachable when an RSA operation can fall
145
 * through to the software implementation. WOLFSSL_NO_RSA_SW removes that
146
 * fall-through, so drop the padding layer too - apart from the PKCS#1 v1.5
147
 * un-pad helper, which the SE050 verify path calls to hand the decoded
148
 * DigestInfo back to the caller.
149
 *
150
 * RSA-PSS is the exception: neither backend serves wolfCrypt's PSS interface,
151
 * which hands over a pre-computed digest (the SE050 API hashes the input
152
 * itself), so a build that
153
 * enables RSA-PSS keeps the whole padding layer. */
154
#if defined(WOLFSSL_NO_RSA_SW) && !defined(WC_RSA_PSS)
155
    #define WOLFSSL_NO_RSA_SW_PAD
156
#endif
157
158
enum {
159
    RSA_STATE_NONE = 0,
160
161
    RSA_STATE_ENCRYPT_PAD,
162
    RSA_STATE_ENCRYPT_EXPTMOD,
163
    RSA_STATE_ENCRYPT_RES,
164
165
    RSA_STATE_DECRYPT_EXPTMOD,
166
    RSA_STATE_DECRYPT_UNPAD,
167
    RSA_STATE_DECRYPT_RES
168
};
169
170
static void wc_RsaCleanup(RsaKey* key)
171
28.8k
{
172
28.8k
#if !defined(WOLFSSL_NO_MALLOC) && (defined(WOLFSSL_ASYNC_CRYPT) || \
173
28.8k
    (!defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)))
174
28.8k
    if (key != NULL) {
175
176
28.8k
    #ifndef WOLFSSL_RSA_PUBLIC_ONLY
177
        /* Erase the recovered plaintext on the way out, success or failure.
178
         * SP 800-56B Rev2 sec 7.2.2.4. Erase only a buffer we allocated. */
179
28.8k
        if (key->dataIsAlloc && key->data != NULL && key->dataLen > 0) {
180
709
            ForceZero(key->data, key->dataLen);
181
            #ifdef WOLFSSL_CHECK_MEM_ZERO
182
            wc_MemZero_Check(key->data, key->dataLen);
183
            #endif
184
709
        }
185
28.8k
    #endif /* !WOLFSSL_RSA_PUBLIC_ONLY */
186
        /* make sure any allocated memory is free'd */
187
28.8k
        if (key->dataIsAlloc) {
188
709
            XFREE(key->data, key->heap, DYNAMIC_TYPE_WOLF_BIGINT);
189
709
            key->dataIsAlloc = 0;
190
709
        }
191
192
28.8k
        key->data = NULL;
193
28.8k
        key->dataLen = 0;
194
28.8k
    }
195
#else
196
    (void)key;
197
#endif
198
28.8k
}
199
200
#ifndef WC_NO_CONSTRUCTORS
201
202
0
#define RSA_NEW_INIT_PLAIN  0
203
#ifdef WOLF_PRIVATE_KEY_ID
204
0
#define RSA_NEW_INIT_ID     1
205
0
#define RSA_NEW_INIT_LABEL  2
206
#endif
207
208
static RsaKey* _NewRsaKey_common(void* heap, int devId, int *result_code,
209
                                  int rsaInitType, unsigned char* id,
210
                                  int idLen, const char* label)
211
0
{
212
0
    int ret;
213
0
    RsaKey* key = (RsaKey*)XMALLOC(sizeof(RsaKey), heap, DYNAMIC_TYPE_RSA);
214
0
    if (key == NULL) {
215
0
        ret = MEMORY_E;
216
0
    }
217
0
    else {
218
0
        switch (rsaInitType) {
219
0
#ifdef WOLF_PRIVATE_KEY_ID
220
0
        case RSA_NEW_INIT_ID:
221
0
            if (id == NULL || idLen == 0 || label != NULL) {
222
0
                ret = BAD_FUNC_ARG;
223
0
            }
224
0
            else {
225
0
                ret = wc_InitRsaKey_Id(key, id, idLen, heap, devId);
226
0
            }
227
0
            break;
228
0
        case RSA_NEW_INIT_LABEL:
229
0
            if (label == NULL || id != NULL || idLen != 0) {
230
0
                ret = BAD_FUNC_ARG;
231
0
            }
232
0
            else {
233
0
                ret = wc_InitRsaKey_Label(key, label, heap, devId);
234
0
            }
235
0
            break;
236
0
#endif
237
0
        default:
238
0
            if (id != NULL || idLen != 0 || label != NULL) {
239
0
                ret = BAD_FUNC_ARG;
240
0
            }
241
0
            else {
242
0
                ret = wc_InitRsaKey_ex(key, heap, devId);
243
0
            }
244
0
            break;
245
0
        }
246
0
        if (ret != 0) {
247
0
            XFREE(key, heap, DYNAMIC_TYPE_RSA);
248
0
            key = NULL;
249
0
        }
250
0
    }
251
0
    (void)rsaInitType;
252
0
    (void)id;
253
0
    (void)idLen;
254
0
    (void)label;
255
256
0
    if (result_code != NULL) {
257
0
        *result_code = ret;
258
0
    }
259
260
0
    return key;
261
0
}
262
263
RsaKey* wc_NewRsaKey(void* heap, int devId, int *result_code)
264
0
{
265
0
    return _NewRsaKey_common(heap, devId, result_code,
266
0
                             RSA_NEW_INIT_PLAIN, NULL, 0, NULL);
267
0
}
268
269
#ifdef WOLF_PRIVATE_KEY_ID
270
RsaKey* wc_NewRsaKey_Id(unsigned char* id, int len, void* heap, int devId,
271
                         int *result_code)
272
0
{
273
0
    return _NewRsaKey_common(heap, devId, result_code,
274
0
                             RSA_NEW_INIT_ID, id, len, NULL);
275
0
}
276
277
RsaKey* wc_NewRsaKey_Label(const char* label, void* heap, int devId,
278
                            int *result_code)
279
0
{
280
0
    return _NewRsaKey_common(heap, devId, result_code,
281
0
                             RSA_NEW_INIT_LABEL, NULL, 0, label);
282
0
}
283
#endif /* WOLF_PRIVATE_KEY_ID */
284
285
int wc_DeleteRsaKey(RsaKey* key, RsaKey** key_p)
286
0
{
287
0
    void* heap;
288
0
    if (key == NULL) {
289
0
        return BAD_FUNC_ARG;
290
0
    }
291
0
    heap = key->heap;
292
0
    wc_FreeRsaKey(key);
293
0
    XFREE(key, heap, DYNAMIC_TYPE_RSA);
294
0
    if (key_p != NULL) {
295
0
        *key_p = NULL;
296
0
    }
297
0
    return 0;
298
0
}
299
#endif /* !WC_NO_CONSTRUCTORS */
300
301
int wc_InitRsaKey_ex(RsaKey* key, void* heap, int devId)
302
12.7k
{
303
12.7k
    int ret = 0;
304
305
12.7k
    if (key == NULL) {
306
0
        return BAD_FUNC_ARG;
307
0
    }
308
309
12.7k
    XMEMSET(key, 0, sizeof(RsaKey));
310
311
12.7k
    key->type = RSA_TYPE_UNKNOWN;
312
12.7k
    key->state = RSA_STATE_NONE;
313
12.7k
    key->heap = heap;
314
12.7k
#if !defined(WOLFSSL_NO_MALLOC) && (defined(WOLFSSL_ASYNC_CRYPT) || \
315
12.7k
    (!defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE)))
316
12.7k
    key->dataIsAlloc = 0;
317
12.7k
#endif
318
319
12.7k
#ifdef WOLF_CRYPTO_CB
320
12.7k
    key->devId = devId;
321
#else
322
    (void)devId;
323
#endif
324
325
#ifdef WOLFSSL_ASYNC_CRYPT
326
    #ifdef WOLFSSL_CERT_GEN
327
        XMEMSET(&key->certSignCtx, 0, sizeof(CertSignCtx));
328
    #endif
329
330
    #ifdef WC_ASYNC_ENABLE_RSA
331
        #ifdef WOLF_CRYPTO_CB
332
        /* prefer crypto callback */
333
        if (key->devId != INVALID_DEVID)
334
        #endif
335
        {
336
            /* handle as async */
337
            ret = wolfAsync_DevCtxInit(&key->asyncDev,
338
                    WOLFSSL_ASYNC_MARKER_RSA, key->heap, devId);
339
            if (ret != 0)
340
                return ret;
341
        }
342
    #endif /* WC_ASYNC_ENABLE_RSA */
343
#endif /* WOLFSSL_ASYNC_CRYPT */
344
345
12.7k
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
346
12.7k
    ret = mp_init_multi(&key->n, &key->e, NULL, NULL, NULL, NULL);
347
12.7k
    if (ret != MP_OKAY)
348
0
        return ret;
349
350
#if !defined(WOLFSSL_KEY_GEN) && !defined(OPENSSL_EXTRA) && defined(RSA_LOW_MEM)
351
    ret = mp_init_multi(&key->d, &key->p, &key->q, NULL, NULL, NULL);
352
#else
353
12.7k
    ret = mp_init_multi(&key->d, &key->p, &key->q, &key->dP, &key->dQ, &key->u);
354
12.7k
#endif
355
12.7k
    if (ret != MP_OKAY) {
356
0
        mp_clear(&key->n);
357
0
        mp_clear(&key->e);
358
0
        return ret;
359
0
    }
360
#else
361
    ret = mp_init(&key->n);
362
    if (ret != MP_OKAY)
363
        return ret;
364
    ret = mp_init(&key->e);
365
    if (ret != MP_OKAY) {
366
        mp_clear(&key->n);
367
        return ret;
368
    }
369
#endif
370
371
#ifdef WOLFSSL_XILINX_CRYPT
372
    key->pubExp = 0;
373
    key->mod    = NULL;
374
#endif
375
376
#ifdef WOLFSSL_AFALG_XILINX_RSA
377
    key->alFd = WC_SOCK_NOTSET;
378
    key->rdFd = WC_SOCK_NOTSET;
379
#endif
380
381
#ifdef WOLFSSL_KCAPI_RSA
382
    key->handle = NULL;
383
#endif
384
385
#if defined(WOLFSSL_RENESAS_FSPSM)
386
    key->ctx.wrapped_pri1024_key = NULL;
387
    key->ctx.wrapped_pub1024_key = NULL;
388
    key->ctx.wrapped_pri2048_key = NULL;
389
    key->ctx.wrapped_pub2048_key = NULL;
390
    key->ctx.keySz = 0;
391
#endif
392
393
12.7k
    return ret;
394
12.7k
}
395
396
int wc_InitRsaKey(RsaKey* key, void* heap)
397
5.17k
{
398
5.17k
    return wc_InitRsaKey_ex(key, heap, INVALID_DEVID);
399
5.17k
}
400
401
#ifdef WOLF_PRIVATE_KEY_ID
402
int wc_InitRsaKey_Id(RsaKey* key, unsigned char* id, int len, void* heap,
403
                     int devId)
404
0
{
405
0
    int ret = 0;
406
#if defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA)
407
    /* SE050 TLS users store a word32 at id, need to read it back */
408
    word32 keyId = 0;
409
#endif
410
411
0
    if (key == NULL || (id == NULL && len > 0))
412
0
        ret = BAD_FUNC_ARG;
413
0
    if (ret == 0 && (len < 0 || len > RSA_MAX_ID_LEN))
414
0
        ret = BUFFER_E;
415
0
    if (ret == 0)
416
0
        ret = wc_InitRsaKey_ex(key, heap, devId);
417
0
    if (ret == 0 && id != NULL && len != 0) {
418
0
        XMEMCPY(key->id, id, (size_t)len);
419
0
        key->idLen = len;
420
    #if defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA)
421
        /* Set SE050 ID from word32, populate RsaKey with public from SE050 */
422
        if (len == (int)sizeof(word32)) {
423
            keyId = readUnalignedWord32(key->id);
424
            ret = wc_RsaUseKeyId(key, keyId, 0);
425
        }
426
    #endif
427
0
    }
428
429
0
    return ret;
430
0
}
431
432
int wc_InitRsaKey_Label(RsaKey* key, const char* label, void* heap, int devId)
433
0
{
434
0
    int ret = 0;
435
0
    int labelLen = 0;
436
437
0
    if (key == NULL || label == NULL)
438
0
        ret = BAD_FUNC_ARG;
439
0
    if (ret == 0) {
440
0
        labelLen = (int)XSTRLEN(label);
441
0
        if (labelLen == 0 || labelLen > RSA_MAX_LABEL_LEN)
442
0
            ret = BUFFER_E;
443
0
    }
444
0
    if (ret == 0)
445
0
        ret = wc_InitRsaKey_ex(key, heap, devId);
446
0
    if (ret == 0) {
447
0
        XMEMCPY(key->label, label, (size_t)labelLen);
448
0
        key->labelLen = labelLen;
449
0
    }
450
451
0
    return ret;
452
0
}
453
#endif /* WOLF_PRIVATE_KEY_ID */
454
455
456
#ifdef WOLFSSL_XILINX_CRYPT
457
#define MAX_E_SIZE 4
458
/* Used to setup hardware state
459
 *
460
 * key  the RSA key to setup
461
 *
462
 * returns 0 on success
463
 */
464
int wc_InitRsaHw(RsaKey* key)
465
{
466
    unsigned char* m; /* RSA modulus */
467
    word32 e = 0;     /* RSA public exponent */
468
    int mSz;
469
    int eSz;
470
    int ret;
471
472
    if (key == NULL) {
473
        return BAD_FUNC_ARG;
474
    }
475
476
    mSz = mp_unsigned_bin_size(&(key->n));
477
#if defined(WOLFSSL_XILINX_CRYPT_VERSAL)
478
    if (mSz > WOLFSSL_XSECURE_RSA_KEY_SIZE) {
479
        return BAD_FUNC_ARG;
480
    }
481
    /* Allocate 4 bytes more for the public exponent. */
482
    m = (unsigned char*) XMALLOC(WOLFSSL_XSECURE_RSA_KEY_SIZE + 4, key->heap,
483
                                 DYNAMIC_TYPE_KEY);
484
#else
485
    m = (unsigned char*)XMALLOC(mSz, key->heap, DYNAMIC_TYPE_KEY);
486
#endif
487
    if (m == NULL) {
488
        return MEMORY_E;
489
    }
490
491
    if (mp_to_unsigned_bin(&(key->n), m) != MP_OKAY) {
492
        WOLFSSL_MSG("Unable to get RSA key modulus");
493
        XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
494
        return MP_READ_E;
495
    }
496
#if defined(WOLFSSL_XILINX_CRYPT_VERSAL)
497
    XMEMSET(m + mSz, 0, WOLFSSL_XSECURE_RSA_KEY_SIZE + 4 - mSz);
498
#endif
499
500
    eSz = mp_unsigned_bin_size(&(key->e));
501
    if (eSz > MAX_E_SIZE) {
502
        WOLFSSL_MSG("Exponent of size 4 bytes expected");
503
        XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
504
        return BAD_FUNC_ARG;
505
    }
506
507
    if (mp_to_unsigned_bin(&(key->e), (byte*)&e + (MAX_E_SIZE - eSz))
508
                != MP_OKAY) {
509
        XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
510
        WOLFSSL_MSG("Unable to get RSA key exponent");
511
        return MP_READ_E;
512
    }
513
514
    /* check for existing mod buffer to avoid memory leak */
515
    XFREE(key->mod, key->heap, DYNAMIC_TYPE_KEY);
516
517
    key->pubExp = e;
518
    key->mod    = m;
519
520
#if defined(WOLFSSL_XILINX_CRYPT_VERSAL)
521
    ret = wc_InitXsecure(&(key->xSec));
522
    if (ret != 0) {
523
        WOLFSSL_MSG("Unable to initialize xSecure for RSA");
524
        XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
525
        return ret;
526
    }
527
    XMEMCPY(&m[WOLFSSL_XSECURE_RSA_KEY_SIZE], &e, sizeof(e));
528
    key->mSz = mSz;
529
#else
530
    if (XSecure_RsaInitialize(&(key->xRsa), key->mod, NULL,
531
                (byte*)&(key->pubExp)) != XST_SUCCESS) {
532
        WOLFSSL_MSG("Unable to initialize RSA on hardware");
533
        XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
534
        return BAD_STATE_E;
535
    }
536
537
#ifdef WOLFSSL_XILINX_PATCH
538
   /* currently a patch of xsecure_rsa.c for 2048 bit keys */
539
   if (wc_RsaEncryptSize(key) == 256) {
540
       if (XSecure_RsaSetSize(&(key->xRsa), 2048) != XST_SUCCESS) {
541
           WOLFSSL_MSG("Unable to set RSA key size on hardware");
542
           XFREE(m, key->heap, DYNAMIC_TYPE_KEY);
543
           return BAD_STATE_E;
544
       }
545
   }
546
#endif
547
#endif
548
    return 0;
549
} /* WOLFSSL_XILINX_CRYPT*/
550
551
#endif /* WOLFSSL_XILINX_CRYPT */
552
553
#if defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA)
554
/* Use specified hardware key ID with RsaKey operations. Unlike devId,
555
 * keyId is a word32 so can handle key IDs larger than an int.
556
 *
557
 * key    initialized RsaKey struct
558
 * keyId  hardware key ID which stores RSA key
559
 * flags  optional flags, currently unused
560
 *
561
 * Return 0 on success, negative on error */
562
int wc_RsaUseKeyId(RsaKey* key, word32 keyId, word32 flags)
563
{
564
    (void)flags;
565
566
    if (key == NULL) {
567
        return BAD_FUNC_ARG;
568
    }
569
570
    return se050_rsa_use_key_id(key, keyId);
571
}
572
573
/* Get hardware key ID associated with this RsaKey structure.
574
 *
575
 * key    initialized RsaKey struct
576
 * keyId  [OUT] output for key ID associated with this structure
577
 *
578
 * Returns 0 on success, negative on error.
579
 */
580
int wc_RsaGetKeyId(RsaKey* key, word32* keyId)
581
{
582
    if (key == NULL || keyId == NULL) {
583
        return BAD_FUNC_ARG;
584
    }
585
586
    return se050_rsa_get_key_id(key, keyId);
587
}
588
#endif /* WOLFSSL_SE050 */
589
590
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
591
static void RsaForceZeroPriv(RsaKey* key)
592
12.7k
{
593
12.7k
#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
594
12.7k
    mp_forcezero(&key->u);
595
12.7k
    mp_forcezero(&key->dQ);
596
12.7k
    mp_forcezero(&key->dP);
597
12.7k
#endif
598
12.7k
    mp_forcezero(&key->q);
599
12.7k
    mp_forcezero(&key->p);
600
12.7k
    mp_forcezero(&key->d);
601
12.7k
}
602
#endif
603
604
int wc_FreeRsaKey(RsaKey* key)
605
12.7k
{
606
12.7k
    int ret = 0;
607
608
12.7k
    if (key == NULL) {
609
0
        return BAD_FUNC_ARG;
610
0
    }
611
612
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_FREE)
613
    #ifndef WOLF_CRYPTO_CB_FIND
614
    if (key->devId != INVALID_DEVID)
615
    #endif
616
    {
617
        ret = wc_CryptoCb_Free(key->devId, WC_ALGO_TYPE_PK,
618
                               WC_PK_TYPE_RSA, 0, key);
619
        /* If callback wants standard free, it returns CRYPTOCB_UNAVAILABLE.
620
         * Otherwise assume the callback handled cleanup. */
621
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
622
            return ret;
623
        /* fall-through to software cleanup */
624
        ret = 0;
625
    }
626
#endif /* WOLF_CRYPTO_CB && WOLF_CRYPTO_CB_FREE */
627
628
#if defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA)
629
    se050_rsa_free_key(key);
630
#endif
631
632
12.7k
    wc_RsaCleanup(key);
633
634
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA)
635
    wolfAsync_DevCtxFree(&key->asyncDev, WOLFSSL_ASYNC_MARKER_RSA);
636
#endif
637
638
12.7k
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
639
    /* Private fields may hold residue even when type is not RSA_PRIVATE. */
640
12.7k
    RsaForceZeroPriv(key);
641
12.7k
#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
642
643
    /* public part */
644
12.7k
    mp_clear(&key->e);
645
12.7k
    mp_clear(&key->n);
646
647
#ifdef WOLFSSL_XILINX_CRYPT
648
    XFREE(key->mod, key->heap, DYNAMIC_TYPE_KEY);
649
    key->mod = NULL;
650
#endif
651
652
#ifdef WOLFSSL_AFALG_XILINX_RSA
653
    /* make sure that sockets are closed on cleanup */
654
    if (key->alFd > 0) {
655
        close(key->alFd);
656
        key->alFd = WC_SOCK_NOTSET;
657
    }
658
    if (key->rdFd > 0) {
659
        close(key->rdFd);
660
        key->rdFd = WC_SOCK_NOTSET;
661
    }
662
#endif
663
664
#ifdef WOLFSSL_KCAPI_RSA
665
    KcapiRsa_Free(key);
666
#endif
667
668
#ifdef WOLFSSL_CHECK_MEM_ZERO
669
    wc_MemZero_Check(key, sizeof(RsaKey));
670
#endif
671
672
#if defined(WOLFSSL_RENESAS_FSPSM_CRYPTONLY)
673
    wc_fspsm_RsaKeyFree(key);
674
#endif
675
#ifdef WOLFSSL_MICROCHIP_TA100
676
    wc_Microchip_rsa_free(key);
677
#endif
678
12.7k
    return ret;
679
12.7k
}
680
681
#ifdef WOLFSSL_RSA_KEY_CHECK
682
/* Check the pair-wise consistency of the RSA key. */
683
static int _ifc_pairwise_consistency_test(RsaKey* key, WC_RNG* rng)
684
{
685
    static const char* msg = "Everyone gets Friday off.";
686
#ifndef WOLFSSL_NO_MALLOC
687
    byte* sig = NULL;
688
#else
689
    byte sig[RSA_MAX_SIZE/8];
690
#endif
691
    byte* plain;
692
    int ret = 0;
693
    word32 msgLen, plainLen, sigLen;
694
695
    msgLen = (word32)XSTRLEN(msg);
696
    ret = wc_RsaEncryptSize(key);
697
    if (ret < 0)
698
        return ret;
699
    else if (ret == 0)
700
        return BAD_FUNC_ARG;
701
    sigLen = (word32)ret;
702
703
    WOLFSSL_MSG("Doing RSA consistency test");
704
705
#ifndef WOLFSSL_NO_MALLOC
706
    /* Sign and verify. */
707
    sig = (byte*)XMALLOC(sigLen, key->heap, DYNAMIC_TYPE_RSA);
708
    if (sig == NULL) {
709
        return MEMORY_E;
710
    }
711
#endif
712
    XMEMSET(sig, 0, sigLen);
713
#ifdef WOLFSSL_CHECK_MEM_ZERO
714
    wc_MemZero_Add("Pairwise CT sig", sig, sigLen);
715
#endif
716
    plain = sig;
717
718
#ifdef WOLFSSL_ASYNC_CRYPT
719
    /* Do blocking async calls here, caller does not support WC_PENDING_E */
720
    do {
721
        if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
722
            ret = wc_AsyncWait(ret, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
723
        if (ret >= 0)
724
#endif
725
            ret = wc_RsaSSL_Sign((const byte*)msg, msgLen, sig, sigLen, key, rng);
726
#ifdef WOLFSSL_ASYNC_CRYPT
727
    } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E));
728
#endif
729
730
    if (ret > 0) {
731
        sigLen = (word32)ret;
732
#ifdef WOLFSSL_ASYNC_CRYPT
733
        /* Do blocking async calls here, caller does not support WC_PENDING_E */
734
        do {
735
            if (ret == WC_NO_ERR_TRACE(WC_PENDING_E))
736
                ret = wc_AsyncWait(ret, &key->asyncDev, WC_ASYNC_FLAG_CALL_AGAIN);
737
            if (ret >= 0)
738
#endif
739
                ret = wc_RsaSSL_VerifyInline(sig, sigLen, &plain, key);
740
#ifdef WOLFSSL_ASYNC_CRYPT
741
        } while (ret == WC_NO_ERR_TRACE(WC_PENDING_E));
742
#endif
743
    }
744
745
    if (ret > 0) {
746
        plainLen = (word32)ret;
747
        ret = (msgLen != plainLen) || (XMEMCMP(plain, msg, msgLen) != 0);
748
    }
749
750
    if (ret != 0)
751
        ret = RSA_KEY_PAIR_E;
752
753
    ForceZero(sig, sigLen);
754
#ifndef WOLFSSL_NO_MALLOC
755
    XFREE(sig, key->heap, DYNAMIC_TYPE_RSA);
756
#endif
757
758
    return ret;
759
}
760
761
762
#if FIPS_VERSION3_GE(7,0,0) && defined(WOLFSSL_KEY_GEN) && \
763
    !defined(WOLFSSL_RSA_PUBLIC_ONLY)
764
/* Defined with the key generation code below; reused here so that key pair
765
 * validation checks the primes as strictly as generation does.
766
 * FIPS 186-5 App. A.1.1. */
767
static int _CheckProbablePrime(mp_int* p, mp_int* q, mp_int* e, int nlen,
768
                               int* isPrime, WC_RNG* rng);
769
#endif
770
771
int wc_CheckRsaKey(RsaKey* key)
772
{
773
    WC_RNG *rng = NULL;
774
#if !defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_NO_MALLOC)
775
    WC_RNG rng_buf;
776
#endif
777
    int ret = 0;
778
    DECL_MP_INT_SIZE_DYN(tmp, (key)? mp_bitsused(&key->n) : 0, RSA_MAX_SIZE);
779
780
    if (key == NULL) {
781
        return BAD_FUNC_ARG;
782
    }
783
784
#ifdef WOLFSSL_CAAM
785
    /* can not perform these checks on an encrypted key */
786
    if (key->blackKey != 0) {
787
        return 0;
788
    }
789
#endif
790
791
    if (MP_BITS_OVER_MAX(mp_bitsused(&key->n), RSA_MAX_SIZE)) {
792
        return WC_KEY_SIZE_E;
793
    }
794
795
    NEW_MP_INT_SIZE(tmp, mp_bitsused(&key->n), NULL, DYNAMIC_TYPE_RSA);
796
#ifdef MP_INT_SIZE_CHECK_NULL
797
    if (tmp == NULL) {
798
        return MEMORY_E;
799
    }
800
#endif
801
802
    if (key->rng)
803
        rng = key->rng;
804
    else {
805
#if !defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_NO_MALLOC)
806
        rng = &rng_buf;
807
#else
808
        rng = (WC_RNG *)XMALLOC(sizeof(*rng), NULL, DYNAMIC_TYPE_RNG);
809
        if (rng == NULL) {
810
            FREE_MP_INT_SIZE(tmp, NULL, DYNAMIC_TYPE_RSA);
811
            return MEMORY_E;
812
        }
813
#endif
814
        ret = wc_InitRng(rng);
815
        if (ret != 0) {
816
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
817
            XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
818
            FREE_MP_INT_SIZE(tmp, NULL, DYNAMIC_TYPE_RSA);
819
#endif
820
            return ret;
821
        }
822
    }
823
824
    if (ret == 0) {
825
        if (INIT_MP_INT_SIZE(tmp, mp_bitsused(&key->n)) != MP_OKAY)
826
            ret = MP_INIT_E;
827
    }
828
829
    if (ret == 0)
830
        ret = _ifc_pairwise_consistency_test(key, rng);
831
832
    /* Check d is less than n. */
833
    if (ret == 0 ) {
834
        if (mp_cmp(&key->d, &key->n) != MP_LT) {
835
            ret = MP_EXPTMOD_E;
836
        }
837
    }
838
    /* Check p*q = n. */
839
    if (ret == 0 ) {
840
    #ifdef WOLFSSL_CHECK_MEM_ZERO
841
        mp_memzero_add("RSA CheckKey tmp", tmp);
842
    #endif
843
        if (mp_mul(&key->p, &key->q, tmp) != MP_OKAY) {
844
            ret = MP_EXPTMOD_E;
845
        }
846
    }
847
    if (ret == 0 ) {
848
        if (mp_cmp(&key->n, tmp) != MP_EQ) {
849
            ret = MP_EXPTMOD_E;
850
        }
851
    }
852
853
#if FIPS_VERSION3_GE(7,0,0) && defined(WOLFSSL_KEY_GEN) && \
854
    !defined(WOLFSSL_RSA_PUBLIC_ONLY)
855
    /* Validate the key the way SP 800-56B Rev2 sec 6.4.1.4.3 (crt_pkv) does.
856
     * Step numbers below are that section's. */
857
    if (ret == 0) {
858
        int nBits = mp_count_bits(&key->n);
859
        int isPrime = 0;
860
861
        /* Modulus: even number of bits (item D, step 3c) and at least 2048
862
         * (FIPS 186-5 sec 5.1).  Spelled out rather than using RSA_MIN_SIZE,
863
         * which drops to 1024 under HAVE_WOLFENGINE / HAVE_WOLFPROVIDER. */
864
        if ((nBits < 2048) || ((nBits & 1) != 0)) {
865
            ret = WC_KEY_SIZE_E;
866
        }
867
868
        /* Public exponent: odd, and 65537 <= e < 2^256 (item B).  Bounds are
869
         * bit counts, not mp_cmp_d: a digit can be 8 or 16 bits wide
870
         * (sp_int.h), and 65537 would truncate there.  An odd e of at least
871
         * 17 bits is >= 65537, because 65536 is the only 17-bit value below
872
         * it and that one is even. */
873
        if ((ret == 0) && (mp_iseven(&key->e) ||
874
                (mp_count_bits(&key->e) < 17) ||
875
                (mp_count_bits(&key->e) > 256))) {
876
            ret = MP_EXPTMOD_E;
877
        }
878
879
        /* Primes: right size, coprime to e, far enough apart, and actually
880
         * prime (steps 5a to 5g).  Two calls because steps 5f/5g want a
881
         * primality test on each prime: the first tests p, the second tests
882
         * q and the |p - q| separation. */
883
        if (ret == 0) {
884
            ret = _CheckProbablePrime(&key->p, NULL, &key->e, nBits, &isPrime,
885
                                      rng);
886
            if ((ret == 0) && isPrime) {
887
                ret = _CheckProbablePrime(&key->p, &key->q, &key->e, nBits,
888
                                          &isPrime, rng);
889
            }
890
            if ((ret == 0) && (!isPrime)) {
891
                ret = MP_EXPTMOD_E;
892
            }
893
        }
894
895
        /* Private exponent must exceed 2^(nBits/2) (step 6a).  A d of that
896
         * many bits or fewer cannot, so counting bits settles it. */
897
        if ((ret == 0) && (mp_count_bits(&key->d) <= (nBits / 2))) {
898
            ret = MP_EXPTMOD_E;
899
        }
900
    }
901
#endif
902
903
#ifndef WC_RSA_NO_FERMAT_CHECK
904
    /* Fermat's Factorization works when difference between p and q
905
     * is less than (conservatively):
906
     *     n^(1/4) + 32
907
     *  ~= 2^(bit count of n)^(1/4) + 32) = 2^((bit count of n)/4 + 32)
908
     */
909
    if (ret == 0) {
910
        ret = mp_sub(&key->p, &key->q, tmp);
911
    }
912
    if (ret == 0) {
913
        if (mp_count_bits(tmp) <= (mp_count_bits(&key->n) / 4 + 32)) {
914
            ret = MP_EXPTMOD_E;
915
        }
916
    }
917
#endif
918
919
    /* Check dP, dQ and u if they exist */
920
    if (ret == 0 && !mp_iszero(&key->dP)) {
921
#if FIPS_VERSION3_GE(7,0,0)
922
        /* Each CRT component must be greater than 1; upper bounds are
923
         * checked just below.  SP 800-56B Rev2 sec 6.4.1.4.3 item F, steps
924
         * 7a/7b/7c.  No WOLFSSL_KEY_GEN in the guard: unlike the block
925
         * above this calls no key-generation helper. */
926
        if ((mp_cmp_d(&key->dP, 1) != MP_GT) ||
927
            (mp_cmp_d(&key->dQ, 1) != MP_GT) ||
928
            (mp_cmp_d(&key->u, 1) != MP_GT)) {
929
            ret = MP_EXPTMOD_E;
930
        }
931
#endif
932
        if ((ret == 0) && (mp_sub_d(&key->p, 1, tmp) != MP_OKAY)) {
933
            ret = MP_EXPTMOD_E;
934
        }
935
        /* Check dP <= p-1. */
936
        if (ret == 0) {
937
            if (mp_cmp(&key->dP, tmp) != MP_LT) {
938
                ret = MP_EXPTMOD_E;
939
            }
940
        }
941
        /* Check e*dP mod p-1 = 1. (dP = 1/e mod p-1) */
942
        if (ret == 0) {
943
            if (mp_mulmod(&key->dP, &key->e, tmp, tmp) != MP_OKAY) {
944
                ret = MP_EXPTMOD_E;
945
            }
946
        }
947
        if (ret == 0 ) {
948
            if (!mp_isone(tmp)) {
949
                ret = MP_EXPTMOD_E;
950
            }
951
        }
952
953
        if (ret == 0) {
954
            if (mp_sub_d(&key->q, 1, tmp) != MP_OKAY) {
955
                ret = MP_EXPTMOD_E;
956
            }
957
        }
958
        /* Check dQ <= q-1. */
959
        if (ret == 0) {
960
            if (mp_cmp(&key->dQ, tmp) != MP_LT) {
961
                ret = MP_EXPTMOD_E;
962
            }
963
        }
964
        /* Check e*dP mod p-1 = 1. (dQ = 1/e mod q-1) */
965
        if (ret == 0) {
966
            if (mp_mulmod(&key->dQ, &key->e, tmp, tmp) != MP_OKAY) {
967
                ret = MP_EXPTMOD_E;
968
            }
969
        }
970
        if (ret == 0 ) {
971
            if (!mp_isone(tmp)) {
972
                ret = MP_EXPTMOD_E;
973
            }
974
        }
975
976
        /* Check u <= p. */
977
        if (ret == 0) {
978
            if (mp_cmp(&key->u, &key->p) != MP_LT) {
979
                ret = MP_EXPTMOD_E;
980
            }
981
        }
982
        /* Check u*q mod p = 1. (u = 1/q mod p) */
983
        if (ret == 0) {
984
            if (mp_mulmod(&key->u, &key->q, &key->p, tmp) != MP_OKAY) {
985
                ret = MP_EXPTMOD_E;
986
            }
987
        }
988
        if (ret == 0 ) {
989
            if (!mp_isone(tmp)) {
990
                ret = MP_EXPTMOD_E;
991
            }
992
        }
993
    }
994
995
    mp_forcezero(tmp);
996
997
    if ((rng != NULL) && (rng != key->rng)) {
998
        wc_FreeRng(rng);
999
#ifdef WOLFSSL_SMALL_STACK
1000
        XFREE(rng, NULL, DYNAMIC_TYPE_RNG);
1001
#endif
1002
    }
1003
#ifdef WOLFSSL_CHECK_MEM_ZERO
1004
    mp_memzero_check(tmp);
1005
#endif
1006
    FREE_MP_INT_SIZE(tmp, NULL, DYNAMIC_TYPE_RSA);
1007
1008
    return ret;
1009
}
1010
#endif /* WOLFSSL_RSA_KEY_CHECK */
1011
1012
1013
#if (!defined(WC_NO_RSA_OAEP) || defined(WC_RSA_PSS)) && \
1014
    !defined(WOLFSSL_NO_RSA_SW_PAD)
1015
/* Uses MGF1 standard as a mask generation function
1016
   hType: hash type used
1017
   seed:  seed to use for generating mask
1018
   seedSz: size of seed buffer
1019
   out:   mask output after generation
1020
   outSz: size of output buffer
1021
 */
1022
#if !defined(NO_SHA) || !defined(NO_SHA256) || defined(WOLFSSL_SHA384) || defined(WOLFSSL_SHA512)
1023
static int RsaMGF1(enum wc_HashType hType, byte* seed, word32 seedSz,
1024
                                        byte* out, word32 outSz, void* heap)
1025
1.60k
{
1026
1.60k
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1027
1.60k
    byte* tmp = NULL;
1028
1.60k
    byte   tmpF = 0;     /* 1 if dynamic memory needs freed */
1029
#else
1030
    byte tmp[RSA_MAX_SIZE/8];
1031
#endif
1032
    /* needs to be large enough for seed size plus counter(4) */
1033
1.60k
    byte  tmpA[WC_MAX_DIGEST_SIZE + 4];
1034
1.60k
    word32 tmpSz = 0;
1035
1.60k
    int hLen;
1036
1.60k
    int ret;
1037
1.60k
    word32 counter;
1038
1.60k
    word32 idx;
1039
#ifdef WOLFSSL_SMALL_STACK_CACHE
1040
    wc_HashAlg *hash;
1041
#endif
1042
1.60k
    hLen    = wc_HashGetDigestSize(hType);
1043
1.60k
    counter = 0;
1044
1.60k
    idx     = 0;
1045
1046
1.60k
    (void)heap;
1047
1048
1.60k
    XMEMSET(tmpA, 0, sizeof(tmpA));
1049
    /* check error return of wc_HashGetDigestSize */
1050
1.60k
    if (hLen < 0) {
1051
0
        return hLen;
1052
0
    }
1053
1054
    /* if tmp is not large enough than use some dynamic memory */
1055
1.60k
    if ((seedSz + 4) > sizeof(tmpA) || (word32)hLen > sizeof(tmpA)) {
1056
        /* find largest amount of memory needed which will be the max of
1057
         * hLen and (seedSz + 4) since tmp is used to store the hash digest */
1058
342
        tmpSz = ((seedSz + 4) > (word32)hLen)? seedSz + 4: (word32)hLen;
1059
342
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1060
342
        tmp = (byte*)XMALLOC(tmpSz, heap, DYNAMIC_TYPE_RSA_BUFFER);
1061
342
        if (tmp == NULL) {
1062
0
            return MEMORY_E;
1063
0
        }
1064
342
        tmpF = 1; /* make sure to free memory when done */
1065
#else
1066
        if (tmpSz > RSA_MAX_SIZE/8)
1067
            return BAD_FUNC_ARG;
1068
#endif
1069
342
    }
1070
1.26k
    else {
1071
        /* use array on the stack */
1072
1.26k
    #ifndef WOLFSSL_SMALL_STACK_CACHE
1073
1.26k
        tmpSz = sizeof(tmpA);
1074
1.26k
    #endif
1075
1.26k
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1076
1.26k
        tmp  = tmpA;
1077
1.26k
        tmpF = 0; /* no need to free memory at end */
1078
1.26k
#endif
1079
1.26k
    }
1080
1081
#ifdef WOLFSSL_SMALL_STACK_CACHE
1082
    hash = (wc_HashAlg*)XMALLOC(sizeof(*hash), heap, DYNAMIC_TYPE_DIGEST);
1083
    if (hash == NULL) {
1084
    #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1085
        if (tmpF) {
1086
            XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1087
        }
1088
    #endif
1089
        return MEMORY_E;
1090
    }
1091
    ret = wc_HashInit_ex(hash, hType, heap, INVALID_DEVID);
1092
    if (ret != 0) {
1093
        XFREE(hash, heap, DYNAMIC_TYPE_DIGEST);
1094
    #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1095
        if (tmpF) {
1096
            XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1097
        }
1098
    #endif
1099
        return ret;
1100
    }
1101
#endif
1102
1103
#ifdef WOLFSSL_CHECK_MEM_ZERO
1104
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1105
    if (tmpF) {
1106
        wc_MemZero_Add("RsaMGF1 tmp", tmp, tmpSz);
1107
    }
1108
    else {
1109
        wc_MemZero_Add("RsaMGF1 tmpA", tmpA, sizeof(tmpA));
1110
    }
1111
#else
1112
    wc_MemZero_Add("RsaMGF1 tmp", tmp, sizeof(tmp));
1113
#endif
1114
#endif
1115
1116
8.16k
    do {
1117
8.16k
        int i = 0;
1118
8.16k
        XMEMCPY(tmp, seed, seedSz);
1119
1120
        /* counter to byte array appended to tmp */
1121
8.16k
        tmp[seedSz]     = (byte)((counter >> 24) & 0xFF);
1122
8.16k
        tmp[seedSz + 1] = (byte)((counter >> 16) & 0xFF);
1123
8.16k
        tmp[seedSz + 2] = (byte)((counter >>  8) & 0xFF);
1124
8.16k
        tmp[seedSz + 3] = (byte)((counter)       & 0xFF);
1125
1126
        /* hash and append to existing output */
1127
#ifdef WOLFSSL_SMALL_STACK_CACHE
1128
        ret = wc_HashUpdate(hash, hType, tmp, (seedSz + 4));
1129
        if (ret == 0) {
1130
            ret = wc_HashFinal(hash, hType, tmp);
1131
        }
1132
#else
1133
8.16k
        ret = wc_Hash(hType, tmp, (seedSz + 4), tmp, tmpSz);
1134
8.16k
#endif
1135
8.16k
        if (ret != 0) {
1136
            /* tmp holds the OAEP seed (ISO/IEC 19790:2012 7.9.7). */
1137
0
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1138
0
            if (tmpF) {
1139
0
                ForceZero(tmp, tmpSz);
1140
0
            }
1141
0
            else {
1142
0
                ForceZero(tmpA, sizeof(tmpA));
1143
0
            }
1144
#else
1145
            ForceZero(tmp, sizeof(tmp));
1146
#endif
1147
#ifdef WOLFSSL_CHECK_MEM_ZERO
1148
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1149
            if (!tmpF) {
1150
                wc_MemZero_Check(tmpA, sizeof(tmpA));
1151
            }
1152
#else
1153
            wc_MemZero_Check(tmp, sizeof(tmp));
1154
#endif
1155
#endif
1156
            /* check for if dynamic memory was needed, then free */
1157
#ifdef WOLFSSL_SMALL_STACK_CACHE
1158
            wc_HashFree(hash, hType);
1159
            XFREE(hash, heap, DYNAMIC_TYPE_DIGEST);
1160
#endif
1161
0
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1162
0
            if (tmpF) {
1163
0
                XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1164
0
            }
1165
0
#endif
1166
0
            return ret;
1167
0
        }
1168
1169
278k
        for (i = 0; i < hLen && idx < outSz; i++) {
1170
270k
            out[idx++] = tmp[i];
1171
270k
        }
1172
8.16k
        counter++;
1173
8.16k
    } while (idx < outSz);
1174
    /* tmp holds the OAEP seed (ISO/IEC 19790:2012 7.9.7). */
1175
1.60k
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1176
1.60k
    if (tmpF) {
1177
342
        ForceZero(tmp, tmpSz);
1178
342
    }
1179
1.26k
    else {
1180
1.26k
        ForceZero(tmpA, sizeof(tmpA));
1181
1.26k
    }
1182
#else
1183
    ForceZero(tmp, sizeof(tmp));
1184
#endif
1185
#ifdef WOLFSSL_CHECK_MEM_ZERO
1186
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1187
    if (!tmpF) {
1188
        wc_MemZero_Check(tmpA, sizeof(tmpA));
1189
    }
1190
#else
1191
    wc_MemZero_Check(tmp, sizeof(tmp));
1192
#endif
1193
#endif
1194
1.60k
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1195
    /* check for if dynamic memory was needed, then free */
1196
1.60k
    if (tmpF) {
1197
342
        XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1198
342
    }
1199
1.60k
#endif
1200
#ifdef WOLFSSL_SMALL_STACK_CACHE
1201
    wc_HashFree(hash, hType);
1202
    XFREE(hash, heap, DYNAMIC_TYPE_DIGEST);
1203
#endif
1204
1205
1.60k
    return 0;
1206
1.60k
}
1207
#endif /* SHA2 Hashes */
1208
1209
#if defined(WOLFSSL_SHA3) && \
1210
    (defined(WOLFSSL_SHAKE128) || defined(WOLFSSL_SHAKE256))
1211
/* SHAKE XOF used directly as mask generation function (not MGF1).
1212
 * Per FIPS 186-5, SHAKE can be used as the MGF for RSA-PSS. */
1213
static int RsaMGF_SHAKE(enum wc_HashType shakeType, byte* seed, word32 seedSz,
1214
                         byte* out, word32 outSz, void* heap)
1215
49
{
1216
49
    WC_DECLARE_VAR(shake, wc_Shake, 1, heap);
1217
49
    int ret;
1218
1219
49
    (void)heap;
1220
49
    (void)shakeType;
1221
1222
49
    WC_ALLOC_VAR_EX(shake, wc_Shake, 1, heap, DYNAMIC_TYPE_TMP_BUFFER,
1223
49
        return MEMORY_E);
1224
1225
49
#ifdef WOLFSSL_SHAKE128
1226
49
    if (shakeType == WC_HASH_TYPE_SHAKE128) {
1227
28
        ret = wc_InitShake128(shake, heap, INVALID_DEVID);
1228
28
        if (ret == 0) {
1229
28
            ret = wc_Shake128_Update(shake, seed, seedSz);
1230
28
            if (ret == 0)
1231
28
                ret = wc_Shake128_Final(shake, out, outSz);
1232
28
            wc_Shake128_Free(shake);
1233
28
        }
1234
28
    }
1235
21
    else
1236
21
#endif
1237
21
#ifdef WOLFSSL_SHAKE256
1238
21
    if (shakeType == WC_HASH_TYPE_SHAKE256) {
1239
21
        ret = wc_InitShake256(shake, heap, INVALID_DEVID);
1240
21
        if (ret == 0) {
1241
21
            ret = wc_Shake256_Update(shake, seed, seedSz);
1242
21
            if (ret == 0)
1243
21
                ret = wc_Shake256_Final(shake, out, outSz);
1244
21
            wc_Shake256_Free(shake);
1245
21
        }
1246
21
    }
1247
0
    else
1248
0
#endif
1249
0
    {
1250
0
        ret = BAD_FUNC_ARG;
1251
0
    }
1252
49
    WC_FREE_VAR_EX(shake, heap, DYNAMIC_TYPE_TMP_BUFFER);
1253
49
    return ret;
1254
49
}
1255
#endif /* WOLFSSL_SHA3 && (WOLFSSL_SHAKE128 || WOLFSSL_SHAKE256) */
1256
1257
/* helper function to direct which mask generation function is used
1258
   switched on type input
1259
 */
1260
static int RsaMGF(int type, byte* seed, word32 seedSz, byte* out,
1261
                                                    word32 outSz, void* heap)
1262
1.71k
{
1263
1.71k
    int ret;
1264
1265
1.71k
    switch(type) {
1266
0
    #ifndef NO_SHA
1267
134
        case WC_MGF1SHA1:
1268
134
            ret = RsaMGF1(WC_HASH_TYPE_SHA, seed, seedSz, out, outSz, heap);
1269
134
            break;
1270
0
    #endif
1271
0
    #ifndef NO_SHA256
1272
0
    #ifdef WOLFSSL_SHA224
1273
132
        case WC_MGF1SHA224:
1274
132
            ret = RsaMGF1(WC_HASH_TYPE_SHA224, seed, seedSz, out, outSz, heap);
1275
132
            break;
1276
0
    #endif
1277
511
        case WC_MGF1SHA256:
1278
511
            ret = RsaMGF1(WC_HASH_TYPE_SHA256, seed, seedSz, out, outSz, heap);
1279
511
            break;
1280
0
    #endif
1281
0
    #ifdef WOLFSSL_SHA384
1282
243
        case WC_MGF1SHA384:
1283
243
            ret = RsaMGF1(WC_HASH_TYPE_SHA384, seed, seedSz, out, outSz, heap);
1284
243
            break;
1285
0
    #endif
1286
0
    #ifdef WOLFSSL_SHA512
1287
223
        case WC_MGF1SHA512:
1288
223
            ret = RsaMGF1(WC_HASH_TYPE_SHA512, seed, seedSz, out, outSz, heap);
1289
223
            break;
1290
0
        #ifndef WOLFSSL_NOSHA512_224
1291
102
        case WC_MGF1SHA512_224:
1292
102
            ret = RsaMGF1(WC_HASH_TYPE_SHA512_224, seed, seedSz, out, outSz,
1293
102
                heap);
1294
102
            break;
1295
0
        #endif
1296
0
        #ifndef WOLFSSL_NOSHA512_256
1297
39
        case WC_MGF1SHA512_256:
1298
39
            ret = RsaMGF1(WC_HASH_TYPE_SHA512_256, seed, seedSz, out, outSz,
1299
39
                heap);
1300
39
            break;
1301
0
        #endif
1302
0
    #endif
1303
0
    #ifdef WOLFSSL_SHA3
1304
0
    #ifndef WOLFSSL_NOSHA3_224
1305
70
        case WC_MGF1SHA3_224:
1306
70
            ret = RsaMGF1(WC_HASH_TYPE_SHA3_224, seed, seedSz, out, outSz,
1307
70
                heap);
1308
70
            break;
1309
0
    #endif
1310
0
    #ifndef WOLFSSL_NOSHA3_256
1311
24
        case WC_MGF1SHA3_256:
1312
24
            ret = RsaMGF1(WC_HASH_TYPE_SHA3_256, seed, seedSz, out, outSz,
1313
24
                heap);
1314
24
            break;
1315
0
    #endif
1316
0
    #ifndef WOLFSSL_NOSHA3_384
1317
30
        case WC_MGF1SHA3_384:
1318
30
            ret = RsaMGF1(WC_HASH_TYPE_SHA3_384, seed, seedSz, out, outSz,
1319
30
                heap);
1320
30
            break;
1321
0
    #endif
1322
0
    #ifndef WOLFSSL_NOSHA3_512
1323
45
        case WC_MGF1SHA3_512:
1324
45
            ret = RsaMGF1(WC_HASH_TYPE_SHA3_512, seed, seedSz, out, outSz,
1325
45
                heap);
1326
45
            break;
1327
0
    #endif
1328
0
    #endif /* WOLFSSL_SHA3 */
1329
0
    #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE128)
1330
29
        case WC_MGF1SHAKE128:
1331
29
            ret = RsaMGF1(WC_HASH_TYPE_SHAKE128, seed, seedSz, out, outSz,
1332
29
                heap);
1333
29
            break;
1334
28
        case WC_MGFSHAKE128:
1335
28
            ret = RsaMGF_SHAKE(WC_HASH_TYPE_SHAKE128, seed, seedSz, out, outSz,
1336
28
                heap);
1337
28
            break;
1338
0
    #endif
1339
0
    #if defined(WOLFSSL_SHA3) && defined(WOLFSSL_SHAKE256)
1340
25
        case WC_MGF1SHAKE256:
1341
25
            ret = RsaMGF1(WC_HASH_TYPE_SHAKE256, seed, seedSz, out, outSz,
1342
25
                heap);
1343
25
            break;
1344
21
        case WC_MGFSHAKE256:
1345
21
            ret = RsaMGF_SHAKE(WC_HASH_TYPE_SHAKE256, seed, seedSz, out, outSz,
1346
21
                heap);
1347
21
            break;
1348
0
    #endif
1349
57
        default:
1350
57
            WOLFSSL_MSG("Unknown MGF type: check build options");
1351
57
            ret = BAD_FUNC_ARG;
1352
1.71k
    }
1353
1354
    /* in case of default avoid unused warning */
1355
1.71k
    (void)seed;
1356
1.71k
    (void)seedSz;
1357
1.71k
    (void)out;
1358
1.71k
    (void)outSz;
1359
1.71k
    (void)heap;
1360
1361
1.71k
    return ret;
1362
1.71k
}
1363
#endif /* (!WC_NO_RSA_OAEP || WC_RSA_PSS) && !WOLFSSL_NO_RSA_SW_PAD */
1364
1365
1366
/* Padding */
1367
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_NO_RSA_SW_PAD)
1368
#ifndef WC_NO_RNG
1369
#ifndef WC_NO_RSA_OAEP
1370
static int RsaPad_OAEP(const byte* input, word32 inputLen, byte* pkcsBlock,
1371
        word32 pkcsBlockLen, byte padValue, WC_RNG* rng,
1372
        enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen,
1373
        void* heap)
1374
440
{
1375
440
    int ret;
1376
440
    word32 hLen;
1377
440
    int psLen;
1378
440
    word32 idx;
1379
1380
440
    #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1381
440
        byte* dbMask = NULL;
1382
440
        byte* lHash = NULL;
1383
440
        byte* seed  = NULL;
1384
    #else
1385
        byte dbMask[RSA_MAX_SIZE/8 + RSA_PSS_PAD_SZ];
1386
        /* must be large enough to contain largest hash */
1387
        byte lHash[WC_MAX_DIGEST_SIZE];
1388
        byte seed[WC_MAX_DIGEST_SIZE];
1389
    #endif
1390
1391
    /* no label is allowed, but catch if no label provided and length > 0 */
1392
440
    if (optLabel == NULL && labelLen > 0) {
1393
0
        return BUFFER_E;
1394
0
    }
1395
1396
    /* limit of label is the same as limit of hash function which is massive */
1397
440
    ret = wc_HashGetDigestSize(hType);
1398
440
    if (ret < 0) {
1399
1
        return ret;
1400
1
    }
1401
439
    hLen = (word32)ret;
1402
1403
439
    #if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1404
439
        lHash = (byte*)XMALLOC(hLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
1405
439
        if (lHash == NULL) {
1406
0
            return MEMORY_E;
1407
0
        }
1408
439
        seed = (byte*)XMALLOC(hLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
1409
439
        if (seed == NULL) {
1410
0
            XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1411
0
            return MEMORY_E;
1412
0
        }
1413
    #else
1414
        /* hLen should never be larger than lHash since size is max digest size,
1415
           but check before blindly calling wc_Hash */
1416
        if (hLen > sizeof(lHash)) {
1417
            WOLFSSL_MSG("OAEP lHash to small for digest!!");
1418
            return MEMORY_E;
1419
        }
1420
    #endif
1421
1422
439
    if ((ret = wc_Hash(hType, optLabel, labelLen, lHash, hLen)) != 0) {
1423
4
        WOLFSSL_MSG("OAEP hash type possibly not supported or lHash to small");
1424
4
            WC_FREE_VAR_EX(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1425
4
            WC_FREE_VAR_EX(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1426
4
        return ret;
1427
4
    }
1428
1429
    /* handles check of location for idx as well as psLen, cast to int to check
1430
       for pkcsBlockLen(k) - 2 * hLen - 2 being negative
1431
       This check is similar to decryption where k > 2 * hLen + 2 as msg
1432
       size approaches 0. In decryption if k is less than or equal -- then there
1433
       is no possible room for msg.
1434
       k = RSA key size
1435
       hLen = hash digest size -- will always be >= 0 at this point
1436
     */
1437
435
    if ((2 * hLen + 2) > pkcsBlockLen) {
1438
7
        WOLFSSL_MSG("OAEP pad error hash to big for RSA key size");
1439
7
            WC_FREE_VAR_EX(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1440
7
            WC_FREE_VAR_EX(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1441
7
        return BAD_FUNC_ARG;
1442
7
    }
1443
1444
428
    if (inputLen > (pkcsBlockLen - 2 * hLen - 2)) {
1445
6
        WOLFSSL_MSG("OAEP pad error message too long");
1446
6
            WC_FREE_VAR_EX(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1447
6
            WC_FREE_VAR_EX(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1448
6
        return BAD_FUNC_ARG;
1449
6
    }
1450
1451
    /* concatenate lHash || PS || 0x01 || msg */
1452
422
    idx = pkcsBlockLen - 1 - inputLen;
1453
422
    psLen = (int)pkcsBlockLen - (int)inputLen - 2 * (int)hLen - 2;
1454
422
    if (pkcsBlockLen < inputLen) { /*make sure not writing over end of buffer */
1455
0
            WC_FREE_VAR_EX(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1456
0
            WC_FREE_VAR_EX(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1457
0
        return BUFFER_E;
1458
0
    }
1459
422
    XMEMCPY(pkcsBlock + (pkcsBlockLen - inputLen), input, inputLen);
1460
422
    pkcsBlock[idx--] = 0x01; /* PS and M separator */
1461
422
    XMEMSET(pkcsBlock + idx - psLen + 1, 0, (size_t)psLen);
1462
422
    idx -= (word32)psLen;
1463
1464
422
    idx = idx - hLen + 1;
1465
422
    XMEMCPY(pkcsBlock + idx, lHash, hLen);
1466
1467
#ifdef WOLFSSL_CHECK_MEM_ZERO
1468
    wc_MemZero_Add("Pad OAEP seed", seed, hLen);
1469
#endif
1470
    /* generate random seed */
1471
422
    if ((ret = wc_RNG_GenerateBlock(rng, seed, hLen)) != 0) {
1472
0
            WC_FREE_VAR_EX(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1473
0
            ForceZero(seed, hLen);
1474
#if defined(WOLFSSL_CHECK_MEM_ZERO) && \
1475
    (!defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_NO_MALLOC))
1476
            wc_MemZero_Check(seed, hLen);
1477
#endif
1478
0
            WC_FREE_VAR_EX(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1479
0
        return ret;
1480
0
    }
1481
1482
422
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1483
    /* create maskedDB from dbMask */
1484
422
    dbMask = (byte*)XMALLOC(pkcsBlockLen - hLen - 1, heap, DYNAMIC_TYPE_RSA);
1485
422
    if (dbMask == NULL) {
1486
1487
0
            XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1488
0
            ForceZero(seed, hLen);
1489
0
            XFREE(seed,  heap, DYNAMIC_TYPE_RSA_BUFFER);
1490
0
        return MEMORY_E;
1491
0
    }
1492
#else
1493
    if (pkcsBlockLen - hLen - 1 > sizeof(dbMask)) {
1494
        ForceZero(seed, hLen);
1495
    #ifdef WOLFSSL_CHECK_MEM_ZERO
1496
        wc_MemZero_Check(seed, hLen);
1497
    #endif
1498
        return MEMORY_E;
1499
    }
1500
#endif
1501
422
    XMEMSET(dbMask, 0, pkcsBlockLen - hLen - 1); /* help static analyzer */
1502
#ifdef WOLFSSL_CHECK_MEM_ZERO
1503
    wc_MemZero_Add("Pad OAEP dbMask", dbMask, pkcsBlockLen - hLen - 1);
1504
#endif
1505
422
    ret = RsaMGF(mgf, seed, hLen, dbMask, pkcsBlockLen - hLen - 1, heap);
1506
422
    if (ret != 0) {
1507
54
            ForceZero(dbMask, pkcsBlockLen - hLen - 1);
1508
#if defined(WOLFSSL_CHECK_MEM_ZERO) && \
1509
    (!defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_NO_MALLOC))
1510
            wc_MemZero_Check(dbMask, pkcsBlockLen - hLen - 1);
1511
#endif
1512
54
            WC_FREE_VAR_EX(dbMask, heap, DYNAMIC_TYPE_RSA);
1513
54
            WC_FREE_VAR_EX(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1514
54
            ForceZero(seed, hLen);
1515
#if defined(WOLFSSL_CHECK_MEM_ZERO) && \
1516
    (!defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_NO_MALLOC))
1517
            wc_MemZero_Check(seed, hLen);
1518
#endif
1519
54
            WC_FREE_VAR_EX(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1520
54
        return ret;
1521
54
    }
1522
1523
368
    xorbuf(pkcsBlock + hLen + 1, dbMask,pkcsBlockLen - hLen - 1);
1524
1525
    /* dbMask is derived from the seed (ISO/IEC 19790:2012 7.9.7). */
1526
368
    ForceZero(dbMask, pkcsBlockLen - hLen - 1);
1527
#if defined(WOLFSSL_CHECK_MEM_ZERO) && \
1528
    (!defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_NO_MALLOC))
1529
    wc_MemZero_Check(dbMask, pkcsBlockLen - hLen - 1);
1530
#endif
1531
368
    WC_FREE_VAR_EX(dbMask, heap, DYNAMIC_TYPE_RSA);
1532
1533
    /* create maskedSeed from seedMask */
1534
368
    pkcsBlock[0] = 0x00;
1535
    /* create seedMask inline */
1536
368
    if ((ret = RsaMGF(mgf, pkcsBlock + hLen + 1, pkcsBlockLen - hLen - 1,
1537
368
                                           pkcsBlock + 1, hLen, heap)) != 0) {
1538
0
            WC_FREE_VAR_EX(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1539
0
            ForceZero(seed, hLen);
1540
#if defined(WOLFSSL_CHECK_MEM_ZERO) && \
1541
    (!defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_NO_MALLOC))
1542
            wc_MemZero_Check(seed, hLen);
1543
#endif
1544
0
            WC_FREE_VAR_EX(seed, heap, DYNAMIC_TYPE_RSA_BUFFER);
1545
0
        return ret;
1546
0
    }
1547
1548
    /* xor created seedMask with seed to make maskedSeed */
1549
368
    xorbuf(pkcsBlock + 1, seed, hLen);
1550
1551
    /* Zeroize masking bytes so that padding can't be unmasked. */
1552
368
    ForceZero(seed, hLen);
1553
368
    #ifdef WOLFSSL_SMALL_STACK
1554
368
        XFREE(lHash, heap, DYNAMIC_TYPE_RSA_BUFFER);
1555
368
        XFREE(seed,  heap, DYNAMIC_TYPE_RSA_BUFFER);
1556
    #elif defined(WOLFSSL_CHECK_MEM_ZERO)
1557
        wc_MemZero_Check(seed, hLen);
1558
    #endif
1559
368
    (void)padValue;
1560
1561
368
    return 0;
1562
368
}
1563
#endif /* !WC_NO_RSA_OAEP */
1564
1565
#ifdef WC_RSA_PSS
1566
1567
/* 0x00 .. 0x00 0x01 | Salt | Gen Hash | 0xbc
1568
 * XOR MGF over all bytes down to end of Salt
1569
 * Gen Hash = HASH(8 * 0x00 | Message Hash | Salt)
1570
 *
1571
 * input         Digest of the message.
1572
 * inputLen      Length of digest.
1573
 * pkcsBlock     Buffer to write to.
1574
 * pkcsBlockLen  Length of buffer to write to.
1575
 * rng           Random number generator (for salt).
1576
 * htype         Hash function to use.
1577
 * mgf           Mask generation function.
1578
 * saltLen       Length of salt to put in padding.
1579
 * bits          Length of key in bits.
1580
 * heap          Used for dynamic memory allocation.
1581
 * returns 0 on success, PSS_SALTLEN_E when the salt length is invalid
1582
 * and other negative values on error.
1583
 */
1584
static int RsaPad_PSS(const byte* input, word32 inputLen, byte* pkcsBlock,
1585
        word32 pkcsBlockLen, WC_RNG* rng, enum wc_HashType hType, int mgf,
1586
        int saltLen, int bits, void* heap)
1587
524
{
1588
524
    int   ret = 0;
1589
524
    int   hLen, o, maskLen, hiBits;
1590
524
    byte* m;
1591
524
    byte* s;
1592
#if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY)
1593
    byte msg[RSA_MAX_SIZE/8 + RSA_PSS_PAD_SZ];
1594
#else
1595
524
    byte* msg = NULL;
1596
524
#endif
1597
524
#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
1598
524
    byte* salt;
1599
#else
1600
    byte salt[WC_MAX_DIGEST_SIZE];
1601
#endif
1602
1603
524
#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
1604
524
    if (pkcsBlockLen > RSA_MAX_SIZE/8) {
1605
0
        return MEMORY_E;
1606
0
    }
1607
524
#endif
1608
1609
524
    hLen = wc_HashGetDigestSize(hType);
1610
524
    if (hLen < 0)
1611
1
        return hLen;
1612
523
    if ((int)inputLen != hLen) {
1613
30
        return BAD_FUNC_ARG;
1614
30
    }
1615
1616
493
    hiBits = (bits - 1) & 0x7;
1617
493
    if (hiBits == 0) {
1618
        /* Per RFC8017, set the leftmost 8emLen - emBits bits of the
1619
           leftmost octet in DB to zero.
1620
        */
1621
7
        *(pkcsBlock++) = 0;
1622
7
        pkcsBlockLen--;
1623
7
    }
1624
1625
493
    if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) {
1626
484
        saltLen = hLen;
1627
484
        #ifdef WOLFSSL_SHA512
1628
            /* See FIPS 186-4 section 5.5 item (e). */
1629
484
            if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE) {
1630
7
                saltLen = RSA_PSS_SALT_MAX_SZ;
1631
7
            }
1632
484
        #endif
1633
484
    }
1634
/* The salt may not be longer than the hash.  FIPS 186-5 sec 5.4(g) states
1635
 * this with no exception, so it holds even where long salts are compiled in. */
1636
#if !defined(WOLFSSL_PSS_LONG_SALT) || FIPS_VERSION3_GE(7,0,0)
1637
    else if (saltLen > hLen) {
1638
        return PSS_SALTLEN_E;
1639
    }
1640
#endif
1641
9
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
1642
9
    else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) {
1643
0
        return PSS_SALTLEN_E;
1644
0
    }
1645
#else
1646
    else if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) {
1647
        saltLen = (int)pkcsBlockLen - hLen - 2;
1648
        if (saltLen < 0) {
1649
            return PSS_SALTLEN_E;
1650
        }
1651
    #if FIPS_VERSION3_GE(7,0,0)
1652
        /* The sentinel is negative, so it slips past the cap above; the
1653
         * length derived from it is subject to the same limit. */
1654
        if (saltLen > hLen) {
1655
            return PSS_SALTLEN_E;
1656
        }
1657
    #endif
1658
    }
1659
    else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) {
1660
        return PSS_SALTLEN_E;
1661
    }
1662
#endif
1663
493
    if ((int)pkcsBlockLen - hLen < saltLen + 2) {
1664
1
        return PSS_SALTLEN_E;
1665
1
    }
1666
492
    maskLen = (int)pkcsBlockLen - 1 - hLen;
1667
1668
492
#if defined(WOLFSSL_PSS_LONG_SALT) || defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
1669
492
    #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
1670
492
        msg = (byte*)XMALLOC(
1671
492
                          (size_t)(RSA_PSS_PAD_SZ + inputLen + (word32)saltLen),
1672
492
                          heap, DYNAMIC_TYPE_RSA_BUFFER);
1673
492
        if (msg == NULL) {
1674
0
            return MEMORY_E;
1675
0
        }
1676
    #ifdef WOLFSSL_CHECK_MEM_ZERO
1677
        wc_MemZero_Add("RsaPad_PSS msg", msg,
1678
            RSA_PSS_PAD_SZ + inputLen + (word32)saltLen);
1679
    #endif
1680
492
    #endif
1681
492
    salt = s = m = msg;
1682
492
    XMEMSET(m, 0, RSA_PSS_PAD_SZ);
1683
492
    m += RSA_PSS_PAD_SZ;
1684
492
    XMEMCPY(m, input, inputLen);
1685
492
    m += inputLen;
1686
492
    o = (int)(m - s);
1687
492
    if (saltLen > 0) {
1688
483
        ret = wc_RNG_GenerateBlock(rng, m, (word32)saltLen);
1689
483
        if (ret == 0) {
1690
483
            m += saltLen;
1691
483
        }
1692
483
    }
1693
#else
1694
    if ((int)pkcsBlockLen < RSA_PSS_PAD_SZ + (int)inputLen + saltLen) {
1695
    #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
1696
        msg = (byte*)XMALLOC(
1697
                          (size_t)(RSA_PSS_PAD_SZ + inputLen + (word32)saltLen),
1698
                          heap, DYNAMIC_TYPE_RSA_BUFFER);
1699
        if (msg == NULL) {
1700
            return MEMORY_E;
1701
        }
1702
    #ifdef WOLFSSL_CHECK_MEM_ZERO
1703
        wc_MemZero_Add("RsaPad_PSS msg", msg,
1704
            RSA_PSS_PAD_SZ + inputLen + (word32)saltLen);
1705
    #endif
1706
    #endif
1707
        m = msg;
1708
    }
1709
    else {
1710
        m = pkcsBlock;
1711
    }
1712
    s = m;
1713
    XMEMSET(m, 0, RSA_PSS_PAD_SZ);
1714
    m += RSA_PSS_PAD_SZ;
1715
    XMEMCPY(m, input, inputLen);
1716
    m += inputLen;
1717
    o = 0;
1718
#ifdef WOLFSSL_CHECK_MEM_ZERO
1719
    wc_MemZero_Add("RsaPad_PSS salt", salt, sizeof(salt));
1720
#endif
1721
    if (saltLen > 0) {
1722
        ret = wc_RNG_GenerateBlock(rng, salt, (word32)saltLen);
1723
        if (ret == 0) {
1724
            XMEMCPY(m, salt, (size_t)saltLen);
1725
            m += saltLen;
1726
        }
1727
    }
1728
#endif
1729
492
    if (ret == 0) {
1730
        /* Put Hash at end of pkcsBlock - 1 */
1731
492
        ret = wc_Hash(hType, s, (word32)(m - s), pkcsBlock + maskLen, (word32)hLen);
1732
492
    }
1733
492
    if (ret == 0) {
1734
       /* Set the last eight bits or trailer field to the octet 0xbc */
1735
489
        pkcsBlock[pkcsBlockLen - 1] = RSA_PSS_PAD_TERM;
1736
1737
489
        ret = RsaMGF(mgf, pkcsBlock + maskLen, (word32)hLen, pkcsBlock, (word32)maskLen, heap);
1738
489
    }
1739
492
    if (ret == 0) {
1740
        /* Clear the first high bit when "8emLen - emBits" is non-zero.
1741
           where emBits = n modBits - 1 */
1742
488
        if (hiBits)
1743
482
            pkcsBlock[0] &= (byte)((1 << hiBits) - 1);
1744
1745
488
        m = pkcsBlock + maskLen - saltLen - 1;
1746
488
        *(m++) ^= 0x01;
1747
488
        xorbuf(m, salt + o, (word32)saltLen);
1748
488
    }
1749
1750
#if !defined(WOLFSSL_PSS_LONG_SALT) && !defined(WOLFSSL_PSS_SALT_LEN_DISCOVER)
1751
    ForceZero(salt, sizeof(salt));
1752
#ifdef WOLFSSL_CHECK_MEM_ZERO
1753
    wc_MemZero_Check(salt, sizeof(salt));
1754
#endif
1755
#endif
1756
492
#if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
1757
492
    if (msg != NULL) {
1758
492
        ForceZero(msg, RSA_PSS_PAD_SZ + inputLen + (word32)saltLen);
1759
492
        XFREE(msg, heap, DYNAMIC_TYPE_RSA_BUFFER);
1760
492
    }
1761
#else
1762
    ForceZero(msg, RSA_PSS_PAD_SZ + inputLen + (word32)saltLen);
1763
#endif
1764
492
    return ret;
1765
492
}
1766
#endif /* WC_RSA_PSS */
1767
#endif /* !WC_NO_RNG */
1768
1769
static int RsaPad(const byte* input, word32 inputLen, byte* pkcsBlock,
1770
                           word32 pkcsBlockLen, byte padValue, WC_RNG* rng)
1771
6.95k
{
1772
6.95k
    if (input == NULL || inputLen == 0 || pkcsBlock == NULL ||
1773
6.95k
                                                        pkcsBlockLen == 0) {
1774
0
        return BAD_FUNC_ARG;
1775
0
    }
1776
1777
6.95k
    if (pkcsBlockLen - RSA_MIN_PAD_SZ < inputLen) {
1778
0
        WOLFSSL_MSG("RsaPad error, invalid length");
1779
0
        return RSA_PAD_E;
1780
0
    }
1781
6.95k
    pkcsBlock[0] = 0x0;       /* set first byte to zero and advance */
1782
6.95k
    pkcsBlock++; pkcsBlockLen--;
1783
6.95k
    pkcsBlock[0] = padValue;  /* insert padValue */
1784
1785
6.95k
    if (padValue == RSA_BLOCK_TYPE_1) {
1786
1787
        /* pad with 0xff bytes */
1788
6.91k
        XMEMSET(&pkcsBlock[1], 0xFF, pkcsBlockLen - inputLen - 2);
1789
6.91k
    }
1790
43
    else {
1791
43
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WC_NO_RNG)
1792
        /* pad with non-zero random bytes */
1793
43
        word32 padLen, i;
1794
43
        int    ret;
1795
43
        padLen = pkcsBlockLen - inputLen - 1;
1796
43
        ret    = wc_RNG_GenerateBlock(rng, &pkcsBlock[1], padLen);
1797
43
        if (ret != 0) {
1798
0
            return ret;
1799
0
        }
1800
1801
        /* remove zeros */
1802
7.80k
        for (i = 1; i < padLen; i++) {
1803
7.76k
            if (pkcsBlock[i] == 0) pkcsBlock[i] = 0x01;
1804
7.76k
        }
1805
#else
1806
        (void)rng;
1807
        return RSA_WRONG_TYPE_E;
1808
#endif
1809
43
    }
1810
1811
6.95k
    pkcsBlock[pkcsBlockLen-inputLen-1] = 0;     /* separator */
1812
6.95k
    XMEMCPY(pkcsBlock+pkcsBlockLen-inputLen, input, inputLen);
1813
1814
6.95k
    return 0;
1815
6.95k
}
1816
1817
/* helper function to direct which padding is used */
1818
int wc_RsaPad_ex(const byte* input, word32 inputLen, byte* pkcsBlock,
1819
    word32 pkcsBlockLen, byte padValue, WC_RNG* rng, int padType,
1820
    enum wc_HashType hType, int mgf, byte* optLabel, word32 labelLen,
1821
    int saltLen, int bits, void* heap)
1822
0
{
1823
0
    int ret;
1824
1825
0
    switch (padType)
1826
0
    {
1827
0
        case WC_RSA_PKCSV15_PAD:
1828
            /*WOLFSSL_MSG("wolfSSL Using RSA PKCSV15 padding");*/
1829
0
            ret = RsaPad(input, inputLen, pkcsBlock, pkcsBlockLen,
1830
0
                                                                 padValue, rng);
1831
0
            break;
1832
1833
0
#ifndef WC_NO_RNG
1834
0
    #ifndef WC_NO_RSA_OAEP
1835
0
        case WC_RSA_OAEP_PAD:
1836
0
            WOLFSSL_MSG("wolfSSL Using RSA OAEP padding");
1837
0
            ret = RsaPad_OAEP(input, inputLen, pkcsBlock, pkcsBlockLen,
1838
0
                           padValue, rng, hType, mgf, optLabel, labelLen, heap);
1839
0
            break;
1840
0
    #endif
1841
1842
0
    #ifdef WC_RSA_PSS
1843
0
        case WC_RSA_PSS_PAD:
1844
0
            WOLFSSL_MSG("wolfSSL Using RSA PSS padding");
1845
0
            ret = RsaPad_PSS(input, inputLen, pkcsBlock, pkcsBlockLen, rng,
1846
0
                                               hType, mgf, saltLen, bits, heap);
1847
0
            break;
1848
0
    #endif
1849
0
#endif /* !WC_NO_RNG */
1850
1851
    #ifdef WC_RSA_NO_PADDING
1852
        case WC_RSA_NO_PAD:
1853
        {
1854
            int bytes = (bits + WOLFSSL_BIT_SIZE - 1) / WOLFSSL_BIT_SIZE;
1855
1856
            WOLFSSL_MSG("wolfSSL Using NO padding");
1857
1858
            /* In the case of no padding being used check that input is exactly
1859
             * the RSA key length */
1860
            if ((bits <= 0) || (inputLen != (word32)bytes)) {
1861
                WOLFSSL_MSG("Bad input size");
1862
                ret = RSA_PAD_E;
1863
            }
1864
            else {
1865
                XMEMCPY(pkcsBlock, input, inputLen);
1866
                ret = 0;
1867
            }
1868
            break;
1869
        }
1870
    #endif
1871
1872
0
        default:
1873
0
            WOLFSSL_MSG("Unknown RSA Pad Type");
1874
0
            ret = RSA_PAD_E;
1875
0
    }
1876
1877
    /* silence warning if not used with padding scheme */
1878
0
    (void)input;
1879
0
    (void)inputLen;
1880
0
    (void)pkcsBlock;
1881
0
    (void)pkcsBlockLen;
1882
0
    (void)padValue;
1883
0
    (void)rng;
1884
0
    (void)padType;
1885
0
    (void)hType;
1886
0
    (void)mgf;
1887
0
    (void)optLabel;
1888
0
    (void)labelLen;
1889
0
    (void)saltLen;
1890
0
    (void)bits;
1891
0
    (void)heap;
1892
1893
0
    return ret;
1894
0
}
1895
#endif /* !WOLFSSL_RSA_VERIFY_ONLY && !WOLFSSL_NO_RSA_SW_PAD */
1896
1897
1898
/* UnPadding */
1899
#if !defined(WC_NO_RSA_OAEP) && !defined(NO_HASH_WRAPPER) && \
1900
    !defined(WOLFSSL_NO_RSA_SW_PAD)
1901
/* UnPad plaintext, set start to *output, return length of plaintext,
1902
 * < 0 on error */
1903
static int RsaUnPad_OAEP(byte *pkcsBlock, unsigned int pkcsBlockLen,
1904
                            byte **output, enum wc_HashType hType, int mgf,
1905
                            byte* optLabel, word32 labelLen, void* heap)
1906
0
{
1907
0
    word32 hLen;
1908
0
    int ret;
1909
0
    byte h[WC_MAX_DIGEST_SIZE]; /* max digest size */
1910
0
    word32 idx;
1911
0
    word32 i;
1912
0
    volatile word32 inc;
1913
1914
0
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1915
0
    byte* tmp  = NULL;
1916
#else
1917
    byte tmp[RSA_MAX_SIZE/8 + RSA_PSS_PAD_SZ];
1918
#endif
1919
1920
    /* no label is allowed, but catch if no label provided and length > 0 */
1921
0
    if (optLabel == NULL && labelLen > 0) {
1922
0
        return BUFFER_E;
1923
0
    }
1924
1925
0
    ret = wc_HashGetDigestSize(hType);
1926
0
    if ((ret < 0) || (pkcsBlockLen < (2 * (word32)ret + 2))) {
1927
0
        return BAD_FUNC_ARG;
1928
0
    }
1929
0
    hLen = (word32)ret;
1930
1931
0
#if defined(WOLFSSL_SMALL_STACK) && !defined(WOLFSSL_NO_MALLOC)
1932
0
    tmp = (byte*)XMALLOC(pkcsBlockLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
1933
0
    if (tmp == NULL) {
1934
0
        return MEMORY_E;
1935
0
    }
1936
0
#endif
1937
0
    XMEMSET(tmp, 0, pkcsBlockLen);
1938
#ifdef WOLFSSL_CHECK_MEM_ZERO
1939
    wc_MemZero_Add("OAEP UnPad temp", tmp, pkcsBlockLen);
1940
#endif
1941
1942
    /* find seedMask value */
1943
0
    ret = RsaMGF(mgf, (byte*)(pkcsBlock + (hLen + 1)),
1944
0
                 pkcsBlockLen - hLen - 1, tmp, hLen, heap);
1945
0
    if (ret != 0) {
1946
0
        ForceZero(tmp, pkcsBlockLen);
1947
#if defined(WOLFSSL_CHECK_MEM_ZERO) && \
1948
    (!defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_NO_MALLOC))
1949
        wc_MemZero_Check(tmp, pkcsBlockLen);
1950
#endif
1951
0
        WC_FREE_VAR_EX(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1952
0
        return ret;
1953
0
    }
1954
1955
    /* xor seedMask value with maskedSeed to get seed value */
1956
0
    xorbuf(tmp, pkcsBlock + 1, hLen);
1957
1958
    /* get dbMask value */
1959
0
    ret = RsaMGF(mgf, tmp, hLen, tmp + hLen, pkcsBlockLen - hLen - 1, heap);
1960
0
    if (ret != 0) {
1961
0
        ForceZero(tmp, pkcsBlockLen);
1962
#if defined(WOLFSSL_CHECK_MEM_ZERO) && \
1963
    (!defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_NO_MALLOC))
1964
        wc_MemZero_Check(tmp, pkcsBlockLen);
1965
#endif
1966
0
        WC_FREE_VAR_EX(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1967
0
        return ret;
1968
0
    }
1969
1970
    /* get DB value by doing maskedDB xor dbMask */
1971
0
    xorbuf(pkcsBlock + hLen + 1, tmp + hLen, pkcsBlockLen - hLen - 1);
1972
1973
0
    ForceZero(tmp, pkcsBlockLen);
1974
#if defined(WOLFSSL_CHECK_MEM_ZERO) && \
1975
    (!defined(WOLFSSL_SMALL_STACK) || defined(WOLFSSL_NO_MALLOC))
1976
    wc_MemZero_Check(tmp, pkcsBlockLen);
1977
#endif
1978
0
    WC_FREE_VAR_EX(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
1979
1980
    /* advance idx to index of PS and msg separator, account for PS size of 0*/
1981
0
    idx = hLen + 1 + hLen;
1982
    /* Don't reveal length of message: look at every byte. */
1983
0
    inc = 1;
1984
0
    for (i = hLen + 1 + hLen; i < pkcsBlockLen - 1; i++) {
1985
        /* Looking for non-zero byte. */
1986
0
        inc &= 1 - (((word32)0 - pkcsBlock[i]) >> 31);
1987
0
        idx += inc;
1988
0
    }
1989
1990
    /* create hash of label for comparison with hash sent */
1991
0
    ret = wc_Hash(hType, optLabel, labelLen, h, hLen);
1992
0
    if (ret != 0) {
1993
0
        return ret;
1994
0
    }
1995
1996
    /* say no to chosen ciphertext attack.
1997
       Comparison of lHash, Y, and separator value needs to all happen in
1998
       constant time.
1999
       Attackers should not be able to get error condition from the timing of
2000
       these checks.
2001
     */
2002
0
    {
2003
0
        volatile int c = ConstantCompare(pkcsBlock + hLen + 1, h, (int)hLen);
2004
0
        c = c + (pkcsBlock[idx++] ^ 0x01); /* separator value is 0x01 */
2005
0
        c = c + (pkcsBlock[0]     ^ 0x00); /* Y, the first value, should be 0 */
2006
2007
        /* Return 0 data length on error. */
2008
0
        idx = ctMaskSelWord32(ctMaskEq(c, 0), idx, pkcsBlockLen);
2009
        /* c mixed in the decrypted Y byte. */
2010
0
        c = 0;
2011
0
    }
2012
2013
    /* adjust pointer to correct location in array and return size of M */
2014
0
    *output = (byte*)(pkcsBlock + idx);
2015
0
    return (int)(pkcsBlockLen - idx);
2016
0
}
2017
#endif /* !WC_NO_RSA_OAEP */
2018
2019
#ifdef WC_RSA_PSS
2020
/* 0x00 .. 0x00 0x01 | Salt | Gen Hash | 0xbc
2021
 * MGF over all bytes down to end of Salt
2022
 *
2023
 * pkcsBlock     Buffer holding decrypted data.
2024
 * pkcsBlockLen  Length of buffer.
2025
 * htype         Hash function to use.
2026
 * mgf           Mask generation function.
2027
 * saltLen       Length of salt to put in padding.
2028
 * bits          Length of key in bits.
2029
 * heap          Used for dynamic memory allocation.
2030
 * returns       the sum of salt length and SHA-256 digest size on success.
2031
 *               Otherwise, PSS_SALTLEN_E for an incorrect salt length,
2032
 *               WC_KEY_SIZE_E for an incorrect encoded message (EM) size
2033
                 and other negative values on error.
2034
 */
2035
static int RsaUnPad_PSS(byte *pkcsBlock, unsigned int pkcsBlockLen,
2036
                        byte **output, enum wc_HashType hType, int mgf,
2037
                        int saltLen, int bits, void* heap)
2038
599
{
2039
599
    int   ret;
2040
599
    byte* tmp;
2041
599
    int   hLen, i, maskLen;
2042
599
#ifdef WOLFSSL_SHA512
2043
599
    int orig_bits = bits;
2044
599
#endif
2045
#if defined(WOLFSSL_NO_MALLOC) && !defined(WOLFSSL_STATIC_MEMORY)
2046
    byte tmp_buf[RSA_MAX_SIZE/8];
2047
    tmp = tmp_buf;
2048
2049
    if (pkcsBlockLen > RSA_MAX_SIZE/8) {
2050
        return MEMORY_E;
2051
    }
2052
#endif
2053
2054
599
    hLen = wc_HashGetDigestSize(hType);
2055
599
    if (hLen < 0)
2056
44
        return hLen;
2057
555
    bits = (bits - 1) & 0x7;
2058
555
    if ((pkcsBlock[0] & (0xff << bits)) != 0) {
2059
28
        return BAD_PADDING_E;
2060
28
    }
2061
527
    if (bits == 0) {
2062
22
        pkcsBlock++;
2063
22
        pkcsBlockLen--;
2064
22
    }
2065
527
    maskLen = (int)pkcsBlockLen - 1 - hLen;
2066
527
    if (maskLen < 0) {
2067
73
        WOLFSSL_MSG("RsaUnPad_PSS: Hash too large");
2068
73
        return WC_KEY_SIZE_E;
2069
73
    }
2070
2071
454
    if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) {
2072
448
        saltLen = hLen;
2073
448
        #ifdef WOLFSSL_SHA512
2074
            /* See FIPS 186-4 section 5.5 item (e). */
2075
448
            if (orig_bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE)
2076
17
                saltLen = RSA_PSS_SALT_MAX_SZ;
2077
448
        #endif
2078
448
    }
2079
/* Same salt limit when verifying: FIPS 186-5 sec 5.4(g) says the check
2080
 * "shall also be checked during the signature verification process". */
2081
#if !defined(WOLFSSL_PSS_LONG_SALT) || FIPS_VERSION3_GE(7,0,0)
2082
    else if (saltLen > hLen)
2083
        return PSS_SALTLEN_E;
2084
#endif
2085
6
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
2086
6
    else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT)
2087
0
        return PSS_SALTLEN_E;
2088
454
    if (maskLen < saltLen + 1) {
2089
4
        return PSS_SALTLEN_E;
2090
4
    }
2091
#else
2092
    else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER)
2093
        return PSS_SALTLEN_E;
2094
    if (saltLen != RSA_PSS_SALT_LEN_DISCOVER && maskLen < saltLen + 1) {
2095
        return WC_KEY_SIZE_E;
2096
    }
2097
#endif
2098
2099
450
    if (pkcsBlock[pkcsBlockLen - 1] != RSA_PSS_PAD_TERM) {
2100
16
        WOLFSSL_MSG("RsaUnPad_PSS: Padding Term Error");
2101
16
        return BAD_PADDING_E;
2102
16
    }
2103
2104
434
#if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
2105
434
    tmp = (byte*)XMALLOC((size_t)maskLen, heap, DYNAMIC_TYPE_RSA_BUFFER);
2106
434
    if (tmp == NULL) {
2107
0
        return MEMORY_E;
2108
0
    }
2109
434
    XMEMSET(tmp, 0, (size_t)maskLen);
2110
434
#endif
2111
2112
434
    if ((ret = RsaMGF(mgf, pkcsBlock + maskLen, (word32)hLen, tmp, (word32)maskLen,
2113
434
                                                                  heap)) != 0) {
2114
2
        #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
2115
2
        XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
2116
2
        #endif
2117
2
        return ret;
2118
2
    }
2119
2120
    /* When bits==0, the modulus bit length is congruent to 1 mod 8, so
2121
     * the encoded block includes a leading 0x00 byte and pkcsBlock was
2122
     * already advanced past it (see above); no masking is needed.
2123
     * (1<<0)-1 == 0 would zero both bytes and corrupt the XOR separator
2124
     * check below.  RsaPad_PSS guards the same step with "if (hiBits)"
2125
     * for the same reason. */
2126
432
    if (bits) {
2127
430
        tmp[0] &= (byte)((1 << bits) - 1);
2128
430
        pkcsBlock[0] &= (byte)((1 << bits) - 1);
2129
430
    }
2130
#ifdef WOLFSSL_PSS_SALT_LEN_DISCOVER
2131
    if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) {
2132
        for (i = 0; i < maskLen - 1; i++) {
2133
            if (tmp[i] != pkcsBlock[i]) {
2134
                break;
2135
            }
2136
        }
2137
        if (tmp[i] != (pkcsBlock[i] ^ 0x01)) {
2138
            #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
2139
            XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
2140
            #endif
2141
            WOLFSSL_MSG("RsaUnPad_PSS: Padding Error Match");
2142
            return PSS_SALTLEN_RECOVER_E;
2143
        }
2144
        saltLen = maskLen - (i + 1);
2145
    #if FIPS_VERSION3_GE(7,0,0)
2146
        /* When the length is discovered rather than supplied, it is this
2147
         * recovered value FIPS 186-5 sec 5.4(g) caps at the hash length. */
2148
        if (saltLen > hLen) {
2149
            #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
2150
            XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
2151
            #endif
2152
            return PSS_SALTLEN_E;
2153
        }
2154
    #endif
2155
    }
2156
    else
2157
#endif
2158
432
    {
2159
67.3k
        for (i = 0; i < maskLen - 1 - saltLen; i++) {
2160
66.9k
            if (tmp[i] != pkcsBlock[i]) {
2161
12
                #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
2162
12
                XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
2163
12
                #endif
2164
12
                WOLFSSL_MSG("RsaUnPad_PSS: Padding Error Match");
2165
12
                return PSS_SALTLEN_E;
2166
12
            }
2167
66.9k
        }
2168
420
        if (tmp[i] != (pkcsBlock[i] ^ 0x01)) {
2169
7
            #if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
2170
7
            XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
2171
7
            #endif
2172
7
            WOLFSSL_MSG("RsaUnPad_PSS: Padding Error End");
2173
7
            return PSS_SALTLEN_E;
2174
7
        }
2175
420
    }
2176
413
    xorbuf(pkcsBlock + i, tmp + i, (word32)(maskLen - i));
2177
2178
413
#if !defined(WOLFSSL_NO_MALLOC) || defined(WOLFSSL_STATIC_MEMORY)
2179
413
    XFREE(tmp, heap, DYNAMIC_TYPE_RSA_BUFFER);
2180
413
#endif
2181
2182
413
    *output = pkcsBlock + maskLen - saltLen;
2183
413
    return saltLen + hLen;
2184
420
}
2185
#endif
2186
2187
/* UnPad plaintext, set start to *output, return length of plaintext,
2188
 * < 0 on error */
2189
static int RsaUnPad(const byte *pkcsBlock, unsigned int pkcsBlockLen,
2190
                    const byte **output, byte padValue)
2191
6.44k
{
2192
6.44k
    int    ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
2193
6.44k
    word16 i;
2194
2195
6.44k
    if (output == NULL || pkcsBlockLen < 2 || pkcsBlockLen > 0xFFFF) {
2196
26
        return BAD_FUNC_ARG;
2197
26
    }
2198
2199
6.41k
    if (padValue == RSA_BLOCK_TYPE_1) {
2200
        /* First byte must be 0x00 and Second byte, block type, 0x01 */
2201
6.41k
        if (pkcsBlock[0] != 0 || pkcsBlock[1] != RSA_BLOCK_TYPE_1) {
2202
602
            WOLFSSL_MSG("RsaUnPad error, invalid formatting");
2203
602
            return RSA_PAD_E;
2204
602
        }
2205
2206
        /* check the padding until we find the separator */
2207
1.19M
        for (i = 2; i < pkcsBlockLen; ) {
2208
1.19M
            if (pkcsBlock[i++] != 0xFF) {
2209
5.81k
                break;
2210
5.81k
            }
2211
1.19M
        }
2212
2213
        /* Minimum of 11 bytes of pre-message data and must have separator. */
2214
5.81k
        if (i < RSA_MIN_PAD_SZ || pkcsBlock[i-1] != 0) {
2215
54
            WOLFSSL_MSG("RsaUnPad error, bad formatting");
2216
54
            return RSA_PAD_E;
2217
54
        }
2218
2219
5.76k
        *output = (const byte *)(pkcsBlock + i);
2220
5.76k
        ret = (int)pkcsBlockLen - i;
2221
5.76k
    }
2222
0
#ifndef WOLFSSL_RSA_VERIFY_ONLY
2223
0
    else {
2224
0
        unsigned int    j;
2225
0
        volatile word16 pastSep = 0;
2226
0
        volatile byte   invalid = 0;
2227
0
        volatile byte   minPad;
2228
0
        volatile int    invalidMask;
2229
0
        byte inv;
2230
0
        word16 sep;
2231
2232
0
        i = 0;
2233
        /* Decrypted with private key - unpad must be constant time. */
2234
0
        for (j = 2; j < pkcsBlockLen; j++) {
2235
           /* Update i if not passed the separator and at separator. */
2236
0
            i |= (word16)(~pastSep) & ctMask16Eq(pkcsBlock[j], 0x00) &
2237
0
                (word16)(j + 1);
2238
0
            pastSep |= ctMask16Eq(pkcsBlock[j], 0x00);
2239
0
        }
2240
2241
        /* Snapshot volatiles to avoid multiple volatile accesses per
2242
         * expression. */
2243
0
        inv = invalid;
2244
0
        sep = pastSep;
2245
2246
        /* Minimum of 11 bytes of pre-message data - including leading 0x00. */
2247
0
        minPad = ctMaskLT(i, RSA_MIN_PAD_SZ);
2248
0
        inv |= minPad;
2249
        /* Must have seen separator. */
2250
0
        inv |= (byte)~sep;
2251
        /* First byte must be 0x00. */
2252
0
        inv |= ctMaskNotEq(pkcsBlock[0], 0x00);
2253
        /* Check against expected block type: padValue */
2254
0
        inv |= ctMaskNotEq(pkcsBlock[1], padValue);
2255
2256
0
        invalid = inv;
2257
0
        *output = (const byte *)(pkcsBlock + i);
2258
0
        invalidMask = (int)-1 + (int)(inv >> 7);
2259
0
        ret = invalidMask & ((int)pkcsBlockLen - i);
2260
        /* Which padding check failed is not left behind. */
2261
0
        pastSep = 0;
2262
0
        invalid = 0;
2263
0
        minPad = 0;
2264
0
        invalidMask = 0;
2265
0
    }
2266
5.76k
#endif
2267
2268
5.76k
    return ret;
2269
6.41k
}
2270
2271
/* helper function to direct unpadding
2272
 *
2273
 * bits is the key modulus size in bits
2274
 */
2275
int wc_RsaUnPad_ex(byte* pkcsBlock, word32 pkcsBlockLen, byte** out,
2276
                   byte padValue, int padType, enum wc_HashType hType,
2277
                   int mgf, byte* optLabel, word32 labelLen, int saltLen,
2278
                   int bits, void* heap)
2279
288
{
2280
288
    int ret;
2281
2282
288
    switch (padType) {
2283
288
        case WC_RSA_PKCSV15_PAD:
2284
            /*WOLFSSL_MSG("wolfSSL Using RSA PKCSV15 un-padding");*/
2285
288
            ret = RsaUnPad(pkcsBlock, pkcsBlockLen, (const byte **)(void *)out,
2286
288
                           padValue);
2287
288
            break;
2288
2289
0
    #if !defined(WC_NO_RSA_OAEP) && !defined(WOLFSSL_NO_RSA_SW_PAD)
2290
0
        case WC_RSA_OAEP_PAD:
2291
0
            WOLFSSL_MSG("wolfSSL Using RSA OAEP un-padding");
2292
0
            ret = RsaUnPad_OAEP((byte*)pkcsBlock, pkcsBlockLen, out,
2293
0
                                        hType, mgf, optLabel, labelLen, heap);
2294
0
            break;
2295
0
    #endif
2296
2297
0
    #ifdef WC_RSA_PSS
2298
0
        case WC_RSA_PSS_PAD:
2299
0
            WOLFSSL_MSG("wolfSSL Using RSA PSS un-padding");
2300
0
            ret = RsaUnPad_PSS((byte*)pkcsBlock, pkcsBlockLen, out, hType, mgf,
2301
0
                                                           saltLen, bits, heap);
2302
0
            break;
2303
0
    #endif
2304
2305
    #ifdef WC_RSA_NO_PADDING
2306
        case WC_RSA_NO_PAD:
2307
            WOLFSSL_MSG("wolfSSL Using NO un-padding");
2308
2309
            /* In the case of no padding being used check that input is exactly
2310
             * the RSA key length */
2311
            if (bits <= 0 || pkcsBlockLen !=
2312
                         ((word32)(bits+WOLFSSL_BIT_SIZE-1)/WOLFSSL_BIT_SIZE)) {
2313
                WOLFSSL_MSG("Bad input size");
2314
                ret = RSA_PAD_E;
2315
            }
2316
            else {
2317
                if (out != NULL) {
2318
                    *out = pkcsBlock;
2319
                }
2320
                ret = (int)pkcsBlockLen;
2321
            }
2322
            break;
2323
    #endif /* WC_RSA_NO_PADDING */
2324
2325
0
        default:
2326
0
            WOLFSSL_MSG("Unknown RSA UnPad Type");
2327
0
            ret = RSA_PAD_E;
2328
288
    }
2329
2330
    /* silence warning if not used with padding scheme */
2331
288
    (void)hType;
2332
288
    (void)mgf;
2333
288
    (void)optLabel;
2334
288
    (void)labelLen;
2335
288
    (void)saltLen;
2336
288
    (void)bits;
2337
288
    (void)heap;
2338
2339
288
    return ret;
2340
288
}
2341
2342
#if defined(HAVE_FIPS) && \
2343
    !defined(WOLFSSL_FIPS_READY) && !defined(WOLFSSL_FIPS_DEV)
2344
PRAGMA_DIAG_PUSH
2345
PRAGMA("GCC diagnostic ignored \"-Wswitch-enum\"")
2346
#endif
2347
2348
int wc_hash2mgf(enum wc_HashType hType)
2349
292
{
2350
292
    switch (hType) {
2351
292
    case WC_HASH_TYPE_NONE:
2352
292
        return WC_MGF1NONE;
2353
0
    case WC_HASH_TYPE_SHA:
2354
0
#ifndef NO_SHA
2355
0
        return WC_MGF1SHA1;
2356
#else
2357
        break;
2358
#endif
2359
0
    case WC_HASH_TYPE_SHA224:
2360
0
#ifdef WOLFSSL_SHA224
2361
0
        return WC_MGF1SHA224;
2362
#else
2363
        break;
2364
#endif
2365
0
    case WC_HASH_TYPE_SHA256:
2366
0
#ifndef NO_SHA256
2367
0
        return WC_MGF1SHA256;
2368
#else
2369
        break;
2370
#endif
2371
0
    case WC_HASH_TYPE_SHA384:
2372
0
#ifdef WOLFSSL_SHA384
2373
0
        return WC_MGF1SHA384;
2374
#else
2375
        break;
2376
#endif
2377
0
    case WC_HASH_TYPE_SHA512:
2378
0
#ifdef WOLFSSL_SHA512
2379
0
        return WC_MGF1SHA512;
2380
#else
2381
        break;
2382
#endif
2383
0
    case WC_HASH_TYPE_SHA512_224:
2384
0
#if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_224)
2385
0
        return WC_MGF1SHA512_224;
2386
#else
2387
        break;
2388
#endif
2389
0
    case WC_HASH_TYPE_SHA512_256:
2390
0
#if defined(WOLFSSL_SHA512) && !defined(WOLFSSL_NOSHA512_256)
2391
0
        return WC_MGF1SHA512_256;
2392
#else
2393
        break;
2394
#endif
2395
0
    case WC_HASH_TYPE_SHA3_224:
2396
0
#if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_224)
2397
0
        return WC_MGF1SHA3_224;
2398
#else
2399
        break;
2400
#endif
2401
0
    case WC_HASH_TYPE_SHA3_256:
2402
0
#if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_256)
2403
0
        return WC_MGF1SHA3_256;
2404
#else
2405
        break;
2406
#endif
2407
0
    case WC_HASH_TYPE_SHA3_384:
2408
0
#if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_384)
2409
0
        return WC_MGF1SHA3_384;
2410
#else
2411
        break;
2412
#endif
2413
0
    case WC_HASH_TYPE_SHA3_512:
2414
0
#if defined(WOLFSSL_SHA3) && !defined(WOLFSSL_NOSHA3_512)
2415
0
        return WC_MGF1SHA3_512;
2416
#else
2417
        break;
2418
#endif
2419
0
    case WC_HASH_TYPE_MD2:
2420
0
    case WC_HASH_TYPE_MD4:
2421
0
    case WC_HASH_TYPE_MD5:
2422
0
    case WC_HASH_TYPE_MD5_SHA:
2423
0
    case WC_HASH_TYPE_BLAKE2B:
2424
0
    case WC_HASH_TYPE_BLAKE2S:
2425
0
    case WC_HASH_TYPE_SM3:
2426
        /* no MGF1 identifier defined for these hashes */
2427
0
        break;
2428
0
#ifdef WOLFSSL_SHAKE128
2429
0
    case WC_HASH_TYPE_SHAKE128:
2430
0
        return WC_MGF1SHAKE128;
2431
#else
2432
    case WC_HASH_TYPE_SHAKE128:
2433
        break;
2434
#endif
2435
0
#ifdef WOLFSSL_SHAKE256
2436
0
    case WC_HASH_TYPE_SHAKE256:
2437
0
        return WC_MGF1SHAKE256;
2438
#else
2439
    case WC_HASH_TYPE_SHAKE256:
2440
        break;
2441
#endif
2442
0
    default:
2443
0
        break;
2444
292
    }
2445
0
    WOLFSSL_MSG("Unrecognized or unsupported hash function");
2446
0
    return WC_MGF1NONE;
2447
292
}
2448
2449
#if defined(HAVE_FIPS) && \
2450
    !defined(WOLFSSL_FIPS_READY) && !defined(WOLFSSL_FIPS_DEV)
2451
PRAGMA_DIAG_POP
2452
#endif
2453
2454
#ifdef WC_RSA_NONBLOCK
2455
static int wc_RsaFunctionNonBlock(const byte* in, word32 inLen, byte* out,
2456
                          word32* outLen, int type, RsaKey* key)
2457
{
2458
    int    ret = 0;
2459
#ifdef USE_FAST_MATH
2460
    word32 keyLen, len;
2461
#endif
2462
    /* SP non-blocking RSA wrappers depend on sp_<N>_mod_exp_<W>_nb,
2463
     * which the SP generator only emits when (!RSA_PUBLIC_ONLY ||
2464
     * HAVE_SP_DH). Match that gate here so the dispatch is omitted when
2465
     * those symbols are not available. */
2466
#if defined(WOLFSSL_HAVE_SP_RSA) && defined(WOLFSSL_SP_NONBLOCK) && \
2467
    defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_FAST_MODEXP) && \
2468
    (!defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_HAVE_SP_DH))
2469
    int bits;
2470
#endif
2471
2472
    if (key == NULL || key->nb == NULL) {
2473
        return BAD_FUNC_ARG;
2474
    }
2475
2476
#if defined(WOLFSSL_HAVE_SP_RSA) && defined(WOLFSSL_SP_NONBLOCK) && \
2477
    defined(WOLFSSL_SP_SMALL) && !defined(WOLFSSL_SP_FAST_MODEXP) && \
2478
    (!defined(WOLFSSL_RSA_PUBLIC_ONLY) || defined(WOLFSSL_HAVE_SP_DH))
2479
    bits = mp_count_bits(&key->n);
2480
#ifndef WOLFSSL_SP_NO_2048
2481
    if (bits == 2048) {
2482
        if (type == RSA_PUBLIC_ENCRYPT || type == RSA_PUBLIC_DECRYPT) {
2483
            return sp_RsaPublic_2048_nb(&key->nb->sp_ctx, in, inLen,
2484
                       &key->e, &key->n, out, outLen);
2485
        }
2486
    #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && \
2487
        (defined(SP_RSA_PRIVATE_EXP_D) || defined(RSA_LOW_MEM))
2488
        return sp_RsaPrivate_2048_nb(&key->nb->sp_ctx, in, inLen,
2489
                   &key->d, &key->n, out, outLen);
2490
    #endif
2491
    }
2492
#endif
2493
#ifndef WOLFSSL_SP_NO_3072
2494
    if (bits == 3072) {
2495
        if (type == RSA_PUBLIC_ENCRYPT || type == RSA_PUBLIC_DECRYPT) {
2496
            return sp_RsaPublic_3072_nb(&key->nb->sp_ctx, in, inLen,
2497
                       &key->e, &key->n, out, outLen);
2498
        }
2499
    #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && \
2500
        (defined(SP_RSA_PRIVATE_EXP_D) || defined(RSA_LOW_MEM))
2501
        return sp_RsaPrivate_3072_nb(&key->nb->sp_ctx, in, inLen,
2502
                   &key->d, &key->n, out, outLen);
2503
    #endif
2504
    }
2505
#endif
2506
#ifdef WOLFSSL_SP_4096
2507
    if (bits == 4096) {
2508
        if (type == RSA_PUBLIC_ENCRYPT || type == RSA_PUBLIC_DECRYPT) {
2509
            return sp_RsaPublic_4096_nb(&key->nb->sp_ctx, in, inLen,
2510
                       &key->e, &key->n, out, outLen);
2511
        }
2512
    #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && \
2513
        (defined(SP_RSA_PRIVATE_EXP_D) || defined(RSA_LOW_MEM))
2514
        return sp_RsaPrivate_4096_nb(&key->nb->sp_ctx, in, inLen,
2515
                   &key->d, &key->n, out, outLen);
2516
    #endif
2517
    }
2518
#endif
2519
#endif /* SP nonblock RSA */
2520
2521
#ifdef USE_FAST_MATH
2522
    if (key->nb->exptmod.state == TFM_EXPTMOD_NB_INIT) {
2523
        if (mp_init(&key->nb->tmp) != MP_OKAY) {
2524
            ret = MP_INIT_E;
2525
        }
2526
2527
        if (ret == 0) {
2528
            if (mp_read_unsigned_bin(&key->nb->tmp, (byte*)in, inLen) != MP_OKAY) {
2529
                ret = MP_READ_E;
2530
            }
2531
        }
2532
    }
2533
2534
    if (ret == 0) {
2535
        switch(type) {
2536
#if !defined(WOLFSSL_RSA_PUBLIC_ONLY)
2537
        case RSA_PRIVATE_DECRYPT:
2538
        case RSA_PRIVATE_ENCRYPT:
2539
            ret = fp_exptmod_nb(&key->nb->exptmod, &key->nb->tmp, &key->d,
2540
                &key->n, &key->nb->tmp);
2541
            if (ret == FP_WOULDBLOCK)
2542
                return ret;
2543
            if (ret != MP_OKAY)
2544
                ret = MP_EXPTMOD_E;
2545
            break;
2546
#endif
2547
        case RSA_PUBLIC_ENCRYPT:
2548
        case RSA_PUBLIC_DECRYPT:
2549
            ret = fp_exptmod_nb(&key->nb->exptmod, &key->nb->tmp, &key->e,
2550
                &key->n, &key->nb->tmp);
2551
            if (ret == FP_WOULDBLOCK)
2552
                return ret;
2553
            if (ret != MP_OKAY)
2554
                ret = MP_EXPTMOD_E;
2555
            break;
2556
        default:
2557
            ret = RSA_WRONG_TYPE_E;
2558
            break;
2559
        }
2560
    }
2561
2562
    if (ret == 0) {
2563
        keyLen = wc_RsaEncryptSize(key);
2564
        if (keyLen > *outLen)
2565
            ret = RSA_BUFFER_E;
2566
    }
2567
    if (ret == 0) {
2568
        len = mp_unsigned_bin_size(&key->nb->tmp);
2569
2570
        /* pad front w/ zeros to match key length */
2571
        while (len < keyLen) {
2572
            *out++ = 0x00;
2573
            len++;
2574
        }
2575
2576
        *outLen = keyLen;
2577
2578
        /* convert */
2579
        if (mp_to_unsigned_bin(&key->nb->tmp, out) != MP_OKAY) {
2580
             ret = MP_TO_E;
2581
        }
2582
    }
2583
2584
    mp_clear(&key->nb->tmp);
2585
#else
2586
    /* No non-blocking backend available for this build. The SP non-block
2587
     * dispatch above only matches enabled key sizes; if we reach this
2588
     * point the key is not 2048/3072/4096 (or SP RSA itself isn't built)
2589
     * and TFM fastmath isn't compiled in either. */
2590
    (void)in;
2591
    (void)inLen;
2592
    (void)out;
2593
    (void)outLen;
2594
    (void)type;
2595
    ret = NOT_COMPILED_IN;
2596
#endif /* USE_FAST_MATH */
2597
2598
    return ret;
2599
}
2600
#endif /* WC_RSA_NONBLOCK */
2601
2602
#ifdef WOLFSSL_XILINX_CRYPT
2603
/*
2604
 * Xilinx hardened crypto acceleration.
2605
 *
2606
 * Returns 0 on success and negative values on error.
2607
 */
2608
static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
2609
                          word32* outLen, int type, RsaKey* key, WC_RNG* rng)
2610
{
2611
    int    ret = 0;
2612
    word32 keyLen;
2613
    (void)rng;
2614
2615
    keyLen = wc_RsaEncryptSize(key);
2616
    if (keyLen > *outLen) {
2617
        WOLFSSL_MSG("Output buffer is not big enough");
2618
        return BAD_FUNC_ARG;
2619
    }
2620
2621
    if (inLen != keyLen) {
2622
        WOLFSSL_MSG("Expected that inLen equals RSA key length");
2623
        return BAD_FUNC_ARG;
2624
    }
2625
2626
    switch(type) {
2627
    case RSA_PRIVATE_DECRYPT:
2628
    case RSA_PRIVATE_ENCRYPT:
2629
    #ifdef WOLFSSL_XILINX_CRYPTO_OLD
2630
        /* Currently public exponent is loaded by default.
2631
         * In SDK 2017.1 RSA exponent values are expected to be of 4 bytes
2632
         * leading to private key operations with Xsecure_RsaDecrypt not being
2633
         * supported */
2634
        ret = RSA_WRONG_TYPE_E;
2635
    #else
2636
        {
2637
            byte *d;
2638
            int dSz;
2639
#if !defined(WOLFSSL_XILINX_CRYPT_VERSAL)
2640
            XSecure_Rsa rsa;
2641
#endif
2642
2643
#if defined(WOLFSSL_XILINX_CRYPT_VERSAL)
2644
            dSz = WOLFSSL_XSECURE_RSA_KEY_SIZE * 2;
2645
#else
2646
            dSz = mp_unsigned_bin_size(&key->d);
2647
#endif
2648
            d = (byte*)XMALLOC(dSz, key->heap, DYNAMIC_TYPE_PRIVATE_KEY);
2649
            if (d == NULL) {
2650
                ret = MEMORY_E;
2651
            } else {
2652
#if defined(WOLFSSL_XILINX_CRYPT_VERSAL)
2653
                XMEMSET(d, 0, dSz);
2654
                XMEMCPY(d, key->mod, key->mSz);
2655
                ret = mp_to_unsigned_bin(&key->d, &d[WOLFSSL_XSECURE_RSA_KEY_SIZE]);
2656
#else
2657
                ret = mp_to_unsigned_bin(&key->d, d);
2658
                XSecure_RsaInitialize(&rsa, key->mod, NULL, d);
2659
#endif
2660
            }
2661
2662
            if (ret == 0) {
2663
#if defined(WOLFSSL_XILINX_CRYPT_VERSAL)
2664
                WOLFSSL_XIL_DCACHE_FLUSH_RANGE((UINTPTR)d, dSz);
2665
                WOLFSSL_XIL_DCACHE_FLUSH_RANGE((UINTPTR)in, inLen);
2666
                if (XSecure_RsaPrivateDecrypt(&(key->xSec.cinst), XIL_CAST_U64(d),
2667
                                              XIL_CAST_U64(in), inLen,
2668
                                              XIL_CAST_U64(out)) != XST_SUCCESS) {
2669
                    ret = BAD_STATE_E;
2670
                }
2671
                WOLFSSL_XIL_DCACHE_FLUSH_RANGE((UINTPTR)out, inLen);
2672
#else
2673
                if (XSecure_RsaPrivateDecrypt(&rsa, (u8*)in, inLen, out) !=
2674
                        XST_SUCCESS) {
2675
                    ret = BAD_STATE_E;
2676
                }
2677
#endif
2678
            }
2679
2680
            if (d != NULL)
2681
                ForceZero(d, dSz);
2682
            XFREE(d, key->heap, DYNAMIC_TYPE_PRIVATE_KEY);
2683
        }
2684
    #endif
2685
        break;
2686
    case RSA_PUBLIC_ENCRYPT:
2687
    case RSA_PUBLIC_DECRYPT:
2688
#if defined(WOLFSSL_XILINX_CRYPT_VERSAL)
2689
        WOLFSSL_XIL_DCACHE_FLUSH_RANGE((UINTPTR)key->mod,
2690
                                       WOLFSSL_XSECURE_RSA_KEY_SIZE + 4);
2691
        WOLFSSL_XIL_DCACHE_FLUSH_RANGE((UINTPTR)in, inLen);
2692
        if (XSecure_RsaPublicEncrypt(&(key->xSec.cinst),
2693
                                     XIL_CAST_U64(key->mod),
2694
                                     XIL_CAST_U64(in), inLen,
2695
                                     XIL_CAST_U64(out))) {
2696
            WOLFSSL_MSG("RSA public operation failed");
2697
            ret = BAD_STATE_E;
2698
        }
2699
        WOLFSSL_XIL_DCACHE_FLUSH_RANGE((UINTPTR)out, inLen);
2700
#elif defined(WOLFSSL_XILINX_CRYPTO_OLD)
2701
        if (XSecure_RsaDecrypt(&(key->xRsa), in, out) != XST_SUCCESS) {
2702
            ret = BAD_STATE_E;
2703
        }
2704
#else
2705
        /* starting at Xilinx release 2019 the function XSecure_RsaDecrypt was removed */
2706
        if (XSecure_RsaPublicEncrypt(&(key->xRsa), (u8*)in, inLen, out) != XST_SUCCESS) {
2707
            WOLFSSL_MSG("Error happened when calling hardware RSA public operation");
2708
            ret = BAD_STATE_E;
2709
        }
2710
#endif
2711
        break;
2712
    default:
2713
        ret = RSA_WRONG_TYPE_E;
2714
    }
2715
2716
    *outLen = keyLen;
2717
2718
    return ret;
2719
}
2720
2721
#elif defined(WOLFSSL_AFALG_XILINX_RSA)
2722
#ifndef ERROR_OUT
2723
#define ERROR_OUT(x) ret = (x); goto done
2724
#endif
2725
2726
static const char WC_TYPE_ASYMKEY[] = "skcipher";
2727
static const char WC_NAME_RSA[] = "xilinx-zynqmp-rsa";
2728
#ifndef MAX_XILINX_RSA_KEY
2729
    /* max key size of 4096 bits / 512 bytes */
2730
    #define MAX_XILINX_RSA_KEY 512
2731
#endif
2732
static const byte XILINX_RSA_FLAG[] = {0x1};
2733
2734
2735
/* AF_ALG implementation of RSA */
2736
static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
2737
                          word32* outLen, int type, RsaKey* key, WC_RNG* rng)
2738
{
2739
    struct msghdr   msg;
2740
    struct cmsghdr* cmsg;
2741
    struct iovec      iov;
2742
    byte*  keyBuf   = NULL;
2743
    word32 keyBufSz = 0;
2744
    char cbuf[CMSG_SPACE(4) + CMSG_SPACE(sizeof(struct af_alg_iv) + 1)] = {0};
2745
    int    ret = 0;
2746
    int    op  = 0;    /* decryption vs encryption flag */
2747
    word32 keyLen;
2748
2749
    /* input and output buffer need to be aligned */
2750
    ALIGN64 byte outBuf[MAX_XILINX_RSA_KEY];
2751
    ALIGN64 byte inBuf[MAX_XILINX_RSA_KEY];
2752
2753
    XMEMSET(&msg, 0, sizeof(struct msghdr));
2754
    (void)rng;
2755
2756
    keyLen = wc_RsaEncryptSize(key);
2757
    if (keyLen > *outLen) {
2758
        ERROR_OUT(RSA_BUFFER_E);
2759
    }
2760
2761
    if (keyLen > MAX_XILINX_RSA_KEY) {
2762
        WOLFSSL_MSG("RSA key size larger than supported");
2763
        ERROR_OUT(BAD_FUNC_ARG);
2764
    }
2765
2766
    if (inLen != keyLen) {
2767
        WOLFSSL_MSG("Expected that inLen equals RSA key length");
2768
        ERROR_OUT(BAD_FUNC_ARG);
2769
    }
2770
2771
    if ((keyBuf = (byte*)XMALLOC(keyLen * 2, key->heap, DYNAMIC_TYPE_KEY))
2772
            == NULL) {
2773
        ERROR_OUT(MEMORY_E);
2774
    }
2775
2776
    if ((ret = mp_to_unsigned_bin(&(key->n), keyBuf)) != MP_OKAY) {
2777
        ERROR_OUT(MP_TO_E);
2778
    }
2779
2780
    switch(type) {
2781
        case RSA_PRIVATE_DECRYPT:
2782
        case RSA_PRIVATE_ENCRYPT:
2783
            op = 1; /* set as decrypt */
2784
            {
2785
                keyBufSz = mp_unsigned_bin_size(&(key->d));
2786
                if ((mp_to_unsigned_bin(&(key->d), keyBuf + keyLen))
2787
                        != MP_OKAY) {
2788
                    ERROR_OUT(MP_TO_E);
2789
                }
2790
            #ifdef WOLFSSL_CHECK_MEM_ZERO
2791
                /* Seed must be zeroized now that it has been used. */
2792
                wc_MemZero_Add("RSA Sync Priv Enc/Dec keyBuf", keyBuf + keyLen,
2793
                    keyBufSz);
2794
            #endif
2795
            }
2796
            break;
2797
2798
        case RSA_PUBLIC_DECRYPT:
2799
        case RSA_PUBLIC_ENCRYPT: {
2800
            word32 exp = 0;
2801
            word32 eSz = mp_unsigned_bin_size(&(key->e));
2802
            if ((mp_to_unsigned_bin(&(key->e), (byte*)&exp +
2803
                            (sizeof(word32) - eSz))) != MP_OKAY) {
2804
                ERROR_OUT(MP_TO_E);
2805
            }
2806
            keyBufSz = sizeof(word32);
2807
            XMEMCPY(keyBuf + keyLen, (byte*)&exp, keyBufSz);
2808
            break;
2809
        }
2810
2811
        default:
2812
            ERROR_OUT(RSA_WRONG_TYPE_E);
2813
    }
2814
    keyBufSz += keyLen; /* add size of modulus */
2815
2816
    /* check for existing sockets before creating new ones */
2817
    if (key->alFd > 0) {
2818
        close(key->alFd);
2819
        key->alFd = WC_SOCK_NOTSET;
2820
    }
2821
    if (key->rdFd > 0) {
2822
        close(key->rdFd);
2823
        key->rdFd = WC_SOCK_NOTSET;
2824
    }
2825
2826
    /* create new sockets and set the key to use */
2827
    if ((key->alFd = wc_Afalg_Socket()) < 0) {
2828
        WOLFSSL_MSG("Unable to create socket");
2829
        ERROR_OUT(key->alFd);
2830
    }
2831
    if ((key->rdFd = wc_Afalg_CreateRead(key->alFd, WC_TYPE_ASYMKEY,
2832
                    WC_NAME_RSA)) < 0) {
2833
        WOLFSSL_MSG("Unable to bind and create read/send socket");
2834
        ERROR_OUT(key->rdFd);
2835
    }
2836
    if ((ret = setsockopt(key->alFd, SOL_ALG, ALG_SET_KEY, keyBuf,
2837
                    keyBufSz)) < 0) {
2838
        WOLFSSL_MSG("Error setting RSA key");
2839
        ERROR_OUT(ret);
2840
    }
2841
2842
    msg.msg_control    = cbuf;
2843
    msg.msg_controllen = sizeof(cbuf);
2844
    cmsg = CMSG_FIRSTHDR(&msg);
2845
    if ((ret = wc_Afalg_SetOp(cmsg, op)) < 0) {
2846
        ERROR_OUT(ret);
2847
    }
2848
2849
    /* set flag in IV spot, needed for Xilinx hardware acceleration use */
2850
    cmsg = CMSG_NXTHDR(&msg, cmsg);
2851
    if ((ret = wc_Afalg_SetIv(cmsg, (byte*)XILINX_RSA_FLAG,
2852
                    sizeof(XILINX_RSA_FLAG))) != 0) {
2853
        ERROR_OUT(ret);
2854
    }
2855
2856
    /* compose and send msg */
2857
    XMEMCPY(inBuf, (byte*)in, inLen); /* for alignment */
2858
    iov.iov_base = inBuf;
2859
    iov.iov_len  = inLen;
2860
    msg.msg_iov  = &iov;
2861
    msg.msg_iovlen = 1;
2862
    if ((ret = sendmsg(key->rdFd, &msg, 0)) <= 0) {
2863
        ERROR_OUT(WC_AFALG_SOCK_E);
2864
    }
2865
2866
    if ((ret = read(key->rdFd, outBuf, inLen)) <= 0) {
2867
        ERROR_OUT(WC_AFALG_SOCK_E);
2868
    }
2869
    XMEMCPY(out, outBuf, ret);
2870
    *outLen = keyLen;
2871
2872
done:
2873
    /* clear key data and free buffer */
2874
    if (keyBuf != NULL) {
2875
        ForceZero(keyBuf, keyBufSz);
2876
    }
2877
    XFREE(keyBuf, key->heap, DYNAMIC_TYPE_KEY);
2878
2879
    if (key->alFd > 0) {
2880
        close(key->alFd);
2881
        key->alFd = WC_SOCK_NOTSET;
2882
    }
2883
    if (key->rdFd > 0) {
2884
        close(key->rdFd);
2885
        key->rdFd = WC_SOCK_NOTSET;
2886
    }
2887
2888
    return ret;
2889
}
2890
2891
#elif defined(WOLFSSL_KCAPI_RSA)
2892
static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
2893
                              word32* outLen, int type, RsaKey* key,
2894
                              WC_RNG* rng)
2895
{
2896
    int ret;
2897
2898
    (void)rng;
2899
2900
    switch(type) {
2901
        case RSA_PRIVATE_DECRYPT:
2902
        case RSA_PRIVATE_ENCRYPT:
2903
            ret = KcapiRsa_Decrypt(key, in, inLen, out, outLen);
2904
            break;
2905
2906
        case RSA_PUBLIC_DECRYPT:
2907
        case RSA_PUBLIC_ENCRYPT:
2908
            ret = KcapiRsa_Encrypt(key, in, inLen, out, outLen);
2909
            break;
2910
2911
        default:
2912
            ret = RSA_WRONG_TYPE_E;
2913
    }
2914
2915
    return ret;
2916
}
2917
2918
#else
2919
#if !defined(WOLF_CRYPTO_CB_ONLY_RSA) && !defined(WOLFSSL_NO_RSA_SW)
2920
#ifdef WOLFSSL_HAVE_SP_RSA
2921
static int RsaFunction_SP(const byte* in, word32 inLen, byte* out,
2922
    word32* outLen, int type, RsaKey* key, WC_RNG* rng)
2923
{
2924
    (void)rng;
2925
2926
#ifndef WOLFSSL_SP_NO_2048
2927
    if (mp_count_bits(&key->n) == 2048) {
2928
        switch(type) {
2929
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
2930
        case RSA_PRIVATE_DECRYPT:
2931
        case RSA_PRIVATE_ENCRYPT:
2932
    #ifdef WC_RSA_BLINDING
2933
            if (rng == NULL)
2934
                return MISSING_RNG_E;
2935
    #endif
2936
    #ifndef RSA_LOW_MEM
2937
            if ((mp_count_bits(&key->p) == 1024) &&
2938
                    (mp_count_bits(&key->q) == 1024) &&
2939
                    (mp_count_bits(&key->dP) > 0) &&
2940
                    (mp_count_bits(&key->dQ) > 0) &&
2941
                    (mp_count_bits(&key->u) > 0)) {
2942
                return sp_RsaPrivate_2048(in, inLen, &key->d, &key->p, &key->q,
2943
                                          &key->dP, &key->dQ, &key->u, &key->n,
2944
                                          out, outLen);
2945
            }
2946
            break;
2947
    #else
2948
            return sp_RsaPrivate_2048(in, inLen, &key->d, NULL, NULL, NULL,
2949
                                      NULL, NULL, &key->n, out, outLen);
2950
    #endif
2951
#endif
2952
        case RSA_PUBLIC_ENCRYPT:
2953
        case RSA_PUBLIC_DECRYPT:
2954
            return sp_RsaPublic_2048(in, inLen, &key->e, &key->n, out, outLen);
2955
        default:
2956
            break;
2957
        }
2958
    }
2959
#endif
2960
#ifndef WOLFSSL_SP_NO_3072
2961
    if (mp_count_bits(&key->n) == 3072) {
2962
        switch(type) {
2963
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
2964
        case RSA_PRIVATE_DECRYPT:
2965
        case RSA_PRIVATE_ENCRYPT:
2966
    #ifdef WC_RSA_BLINDING
2967
            if (rng == NULL)
2968
                return MISSING_RNG_E;
2969
    #endif
2970
    #ifndef RSA_LOW_MEM
2971
            if ((mp_count_bits(&key->p) == 1536) &&
2972
                    (mp_count_bits(&key->q) == 1536) &&
2973
                    (mp_count_bits(&key->dP) > 0) &&
2974
                    (mp_count_bits(&key->dQ) > 0) &&
2975
                    (mp_count_bits(&key->u) > 0)) {
2976
                return sp_RsaPrivate_3072(in, inLen, &key->d, &key->p, &key->q,
2977
                                          &key->dP, &key->dQ, &key->u, &key->n,
2978
                                          out, outLen);
2979
            }
2980
            break;
2981
    #else
2982
            return sp_RsaPrivate_3072(in, inLen, &key->d, NULL, NULL, NULL,
2983
                                      NULL, NULL, &key->n, out, outLen);
2984
    #endif
2985
#endif
2986
        case RSA_PUBLIC_ENCRYPT:
2987
        case RSA_PUBLIC_DECRYPT:
2988
            return sp_RsaPublic_3072(in, inLen, &key->e, &key->n, out, outLen);
2989
        default:
2990
            break;
2991
        }
2992
    }
2993
#endif
2994
#ifdef WOLFSSL_SP_4096
2995
    if (mp_count_bits(&key->n) == 4096) {
2996
        switch(type) {
2997
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
2998
        case RSA_PRIVATE_DECRYPT:
2999
        case RSA_PRIVATE_ENCRYPT:
3000
    #ifdef WC_RSA_BLINDING
3001
            if (rng == NULL)
3002
                return MISSING_RNG_E;
3003
    #endif
3004
    #ifndef RSA_LOW_MEM
3005
            if ((mp_count_bits(&key->p) == 2048) &&
3006
                    (mp_count_bits(&key->q) == 2048) &&
3007
                    (mp_count_bits(&key->dP) > 0) &&
3008
                    (mp_count_bits(&key->dQ) > 0) &&
3009
                    (mp_count_bits(&key->u) > 0)) {
3010
                return sp_RsaPrivate_4096(in, inLen, &key->d, &key->p, &key->q,
3011
                                          &key->dP, &key->dQ, &key->u, &key->n,
3012
                                          out, outLen);
3013
            }
3014
            break;
3015
    #else
3016
            return sp_RsaPrivate_4096(in, inLen, &key->d, NULL, NULL, NULL,
3017
                                      NULL, NULL, &key->n, out, outLen);
3018
    #endif
3019
#endif
3020
        case RSA_PUBLIC_ENCRYPT:
3021
        case RSA_PUBLIC_DECRYPT:
3022
            return sp_RsaPublic_4096(in, inLen, &key->e, &key->n, out, outLen);
3023
        default:
3024
            break;
3025
        }
3026
    }
3027
#endif
3028
3029
    /* SP not able to do operation. */
3030
    return WC_KEY_SIZE_E;
3031
}
3032
#endif
3033
3034
#if !defined(WOLFSSL_SP_MATH)
3035
#if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
3036
static int RsaFunctionPrivate(mp_int* tmp, RsaKey* key, WC_RNG* rng)
3037
7.38k
{
3038
7.38k
    int    ret = 0;
3039
7.38k
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
3040
7.38k
    mp_digit mp = 0;
3041
7.38k
    DECL_MP_INT_SIZE_DYN(rnd, mp_bitsused(&key->n), RSA_MAX_SIZE);
3042
7.38k
    DECL_MP_INT_SIZE_DYN(rndi, mp_bitsused(&key->n), RSA_MAX_SIZE);
3043
7.38k
    DECL_MP_INT_SIZE_DYN(mask, mp_bitsused(&key->n), RSA_MAX_SIZE);
3044
7.38k
#endif /* WC_RSA_BLINDING && !WC_NO_RNG */
3045
3046
7.38k
    if (MP_BITS_OVER_MAX(mp_bitsused(&key->n), RSA_MAX_SIZE)) {
3047
0
        return WC_KEY_SIZE_E;
3048
0
    }
3049
3050
7.38k
    (void)rng;
3051
3052
7.38k
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
3053
7.38k
    NEW_MP_INT_SIZE(rnd, mp_bitsused(&key->n), key->heap, DYNAMIC_TYPE_RSA);
3054
7.38k
    NEW_MP_INT_SIZE(rndi, mp_bitsused(&key->n), key->heap, DYNAMIC_TYPE_RSA);
3055
7.38k
    NEW_MP_INT_SIZE(mask, mp_bitsused(&key->n), key->heap, DYNAMIC_TYPE_RSA);
3056
7.38k
#ifdef MP_INT_SIZE_CHECK_NULL
3057
7.38k
    if ((rnd == NULL) || (rndi == NULL) || (mask == NULL)) {
3058
0
        FREE_MP_INT_SIZE(rnd, key->heap, DYNAMIC_TYPE_RSA);
3059
0
        FREE_MP_INT_SIZE(rndi, key->heap, DYNAMIC_TYPE_RSA);
3060
0
        FREE_MP_INT_SIZE(mask, key->heap, DYNAMIC_TYPE_RSA);
3061
0
        return MEMORY_E;
3062
0
    }
3063
7.38k
#endif
3064
3065
7.38k
    if ((INIT_MP_INT_SIZE(rnd, mp_bitsused(&key->n)) != MP_OKAY) ||
3066
7.38k
            (INIT_MP_INT_SIZE(rndi, mp_bitsused(&key->n)) != MP_OKAY) ||
3067
7.38k
            (INIT_MP_INT_SIZE(mask, mp_bitsused(&key->n)) != MP_OKAY)) {
3068
0
        ret = MP_INIT_E;
3069
0
    }
3070
3071
7.38k
    if (ret == 0) {
3072
        /* blind */
3073
7.38k
        ret = mp_rand(rnd, mp_get_digit_count(&key->n), rng);
3074
7.38k
    }
3075
    /* rndi = 1/rnd mod n
3076
     *
3077
     * mp_invmod() is a binary extended Euclidean variant whose iteration
3078
     * count and branches track its input, and rnd is secret. Invert rnd*mask
3079
     * for a fresh random mask and divide it back out afterwards:
3080
     * (rnd*mask)^-1 * mask == rnd^-1 mod n. The inversion then sees a value
3081
     * independent of rnd. */
3082
7.38k
    if (ret == 0) {
3083
7.38k
        ret = mp_rand(mask, mp_get_digit_count(&key->n), rng);
3084
7.38k
    }
3085
7.38k
    if (ret == 0) {
3086
7.38k
        if (mp_mulmod(rnd, mask, &key->n, rndi) != MP_OKAY) {
3087
0
            ret = MP_MULMOD_E;
3088
0
        }
3089
7.38k
    }
3090
7.38k
    if (ret == 0) {
3091
7.38k
        if (mp_invmod(rndi, &key->n, rndi) != MP_OKAY) {
3092
176
            ret = MP_INVMOD_E;
3093
176
        }
3094
7.38k
    }
3095
7.38k
    if (ret == 0) {
3096
7.21k
        if (mp_mulmod(rndi, mask, &key->n, rndi) != MP_OKAY) {
3097
0
            ret = MP_MULMOD_E;
3098
0
        }
3099
7.21k
    }
3100
7.38k
    if (ret == 0) {
3101
    #ifdef WOLFSSL_CHECK_MEM_ZERO
3102
        mp_memzero_add("RSA Private rnd", rnd);
3103
        mp_memzero_add("RSA Private rndi", rndi);
3104
        mp_memzero_add("RSA Private mask", mask);
3105
    #endif
3106
3107
        /* rnd = rnd^e */
3108
    #ifndef WOLFSSL_SP_MATH_ALL
3109
        if (mp_exptmod(rnd, &key->e, &key->n, rnd) != MP_OKAY) {
3110
            ret = MP_EXPTMOD_E;
3111
        }
3112
    #else
3113
7.21k
        if (mp_exptmod_nct(rnd, &key->e, &key->n, rnd) != MP_OKAY) {
3114
2
            ret = MP_EXPTMOD_E;
3115
2
        }
3116
7.21k
    #endif
3117
7.21k
    }
3118
3119
7.38k
    if (ret == 0) {
3120
        /* tmp = tmp*rnd mod n */
3121
7.20k
        if (mp_mulmod(tmp, rnd, &key->n, tmp) != MP_OKAY) {
3122
0
            ret = MP_MULMOD_E;
3123
0
        }
3124
7.20k
    }
3125
7.38k
#endif /* WC_RSA_BLINDING && !WC_NO_RNG */
3126
3127
#ifdef RSA_LOW_MEM      /* half as much memory but twice as slow */
3128
    if (ret == 0) {
3129
        if (mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY) {
3130
            ret = MP_EXPTMOD_E;
3131
        }
3132
    }
3133
#else
3134
7.38k
    if (ret == 0 && (mp_iszero(&key->p) || mp_iszero(&key->q) ||
3135
7.20k
            mp_iszero(&key->dP) || mp_iszero(&key->dQ) || mp_iszero(&key->u))) {
3136
1.05k
        if (mp_exptmod(tmp, &key->d, &key->n, tmp) != MP_OKAY) {
3137
3
            ret = MP_EXPTMOD_E;
3138
3
        }
3139
1.05k
    }
3140
6.33k
    else if (ret == 0) {
3141
6.15k
        mp_int* tmpa = tmp;
3142
6.15k
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
3143
6.15k
        mp_int* tmpb = rnd;
3144
#else
3145
        DECL_MP_INT_SIZE_DYN(tmpb, mp_bitsused(&key->n), RSA_MAX_SIZE);
3146
#endif
3147
3148
#if !defined(WC_RSA_BLINDING) || defined(WC_NO_RNG)
3149
        NEW_MP_INT_SIZE(tmpb, mp_bitsused(&key->n), key->heap,
3150
            DYNAMIC_TYPE_RSA);
3151
    #ifdef MP_INT_SIZE_CHECK_NULL
3152
        if (tmpb == NULL) {
3153
            ret = MEMORY_E;
3154
        }
3155
    #endif
3156
        if ((ret == 0) && INIT_MP_INT_SIZE(tmpb, mp_bitsused(&key->n)) !=
3157
                MP_OKAY) {
3158
            ret = MP_INIT_E;
3159
        }
3160
#endif
3161
3162
    #ifdef WOLFSSL_CHECK_MEM_ZERO
3163
        if (ret == 0) {
3164
            mp_memzero_add("RSA Sync tmpb", tmpb);
3165
        }
3166
    #endif
3167
3168
        /* tmpb = tmp^dQ mod q */
3169
6.15k
        if (ret == 0 && mp_exptmod(tmp, &key->dQ, &key->q, tmpb) != MP_OKAY)
3170
0
            ret = MP_EXPTMOD_E;
3171
3172
        /* tmpa = tmp^dP mod p */
3173
6.15k
        if (ret == 0 && mp_exptmod(tmp, &key->dP, &key->p, tmpa) != MP_OKAY)
3174
0
            ret = MP_EXPTMOD_E;
3175
3176
        /* tmp = (tmp - tmpb) * qInv (mod p) */
3177
6.15k
    #if (defined(WOLFSSL_SP_MATH) || (defined(WOLFSSL_SP_MATH_ALL)) && \
3178
6.15k
                                              !defined(WOLFSSL_SP_INT_NEGATIVE))
3179
6.15k
        if (ret == 0 && mp_submod(tmpa, tmpb, &key->p, tmp) != MP_OKAY)
3180
0
            ret = MP_SUB_E;
3181
    #else
3182
        if (ret == 0 && mp_sub(tmpa, tmpb, tmp) != MP_OKAY)
3183
            ret = MP_SUB_E;
3184
    #endif
3185
3186
6.15k
        if (ret == 0 && mp_mulmod(tmp, &key->u, &key->p, tmp) != MP_OKAY)
3187
0
            ret = MP_MULMOD_E;
3188
3189
        /* tmp = tmpb + q * tmp */
3190
6.15k
        if (ret == 0 && mp_mul(tmp, &key->q, tmp) != MP_OKAY)
3191
0
            ret = MP_MUL_E;
3192
3193
6.15k
        if (ret == 0 && mp_add(tmp, tmpb, tmp) != MP_OKAY)
3194
0
            ret = MP_ADD_E;
3195
3196
#if !defined(WC_RSA_BLINDING) || defined(WC_NO_RNG)
3197
        mp_forcezero(tmpb);
3198
        FREE_MP_INT_SIZE(tmpb, key->heap, DYNAMIC_TYPE_RSA);
3199
    #if !defined(MP_INT_SIZE_CHECK_NULL) && defined(WOLFSSL_CHECK_MEM_ZERO)
3200
        mp_memzero_check(tmpb);
3201
    #endif
3202
#endif
3203
6.15k
    }
3204
7.38k
#endif   /* RSA_LOW_MEM */
3205
3206
7.38k
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
3207
    /* Multiply result (tmp) by blinding invertor (rndi).
3208
     * Use Montgomery form to make operation more constant time.
3209
     */
3210
7.38k
    if ((ret == 0) && (mp_montgomery_setup(&key->n, &mp) != MP_OKAY)) {
3211
0
        ret = MP_MULMOD_E;
3212
0
    }
3213
7.38k
    if ((ret == 0) && (mp_montgomery_calc_normalization(rnd, &key->n) !=
3214
7.20k
            MP_OKAY)) {
3215
0
        ret = MP_MULMOD_E;
3216
0
    }
3217
    /* Convert blinding invert to Montgomery form. */
3218
7.38k
    if ((ret == 0) && (mp_mul(rndi, rnd, rndi) != MP_OKAY)) {
3219
0
        ret = MP_MULMOD_E;
3220
0
    }
3221
7.38k
    if ((ret == 0) && (mp_mod(rndi, &key->n, rndi) != MP_OKAY)) {
3222
0
        ret = MP_MULMOD_E;
3223
0
    }
3224
    /* Multiply result by blinding invert. */
3225
7.38k
    if ((ret == 0) && (mp_mul(tmp, rndi, tmp) != MP_OKAY)) {
3226
0
        ret = MP_MULMOD_E;
3227
0
    }
3228
    /* Reduce result. */
3229
7.38k
    if ((ret == 0) && (mp_montgomery_reduce_ct(tmp, &key->n, mp) != MP_OKAY)) {
3230
0
        ret = MP_MULMOD_E;
3231
0
    }
3232
3233
7.38k
    mp_forcezero(mask);
3234
7.38k
    mp_forcezero(rndi);
3235
7.38k
    mp_forcezero(rnd);
3236
7.38k
    FREE_MP_INT_SIZE(mask, key->heap, DYNAMIC_TYPE_RSA);
3237
7.38k
    FREE_MP_INT_SIZE(rndi, key->heap, DYNAMIC_TYPE_RSA);
3238
7.38k
    FREE_MP_INT_SIZE(rnd, key->heap, DYNAMIC_TYPE_RSA);
3239
#if !defined(MP_INT_SIZE_CHECK_NULL) && defined(WOLFSSL_CHECK_MEM_ZERO)
3240
    mp_memzero_check(rnd);
3241
    mp_memzero_check(rndi);
3242
    mp_memzero_check(mask);
3243
#endif
3244
7.38k
#endif /* WC_RSA_BLINDING && !WC_NO_RNG */
3245
7.38k
    return ret;
3246
7.38k
}
3247
#endif
3248
3249
static int RsaFunctionSync(const byte* in, word32 inLen, byte* out,
3250
    word32* outLen, int type, RsaKey* key, WC_RNG* rng)
3251
14.5k
{
3252
14.5k
    DECL_MP_INT_SIZE_DYN(tmp, mp_bitsused(&key->n), RSA_MAX_SIZE);
3253
14.5k
    int    ret = 0;
3254
3255
14.5k
    if (MP_BITS_OVER_MAX(mp_bitsused(&key->n), RSA_MAX_SIZE)) {
3256
0
        return WC_KEY_SIZE_E;
3257
0
    }
3258
3259
14.5k
    (void)rng;
3260
3261
14.5k
    NEW_MP_INT_SIZE(tmp, mp_bitsused(&key->n), key->heap, DYNAMIC_TYPE_RSA);
3262
14.5k
#ifdef MP_INT_SIZE_CHECK_NULL
3263
14.5k
    if (tmp == NULL) {
3264
0
        WOLFSSL_MSG("NEW_MP_INT_SIZE tmp is NULL, return MEMORY_E");
3265
0
        return MEMORY_E;
3266
0
    }
3267
14.5k
#endif
3268
3269
14.5k
    if (INIT_MP_INT_SIZE(tmp, mp_bitsused(&key->n)) != MP_OKAY) {
3270
0
        WOLFSSL_MSG("INIT_MP_INT_SIZE failed.");
3271
0
        ret = MP_INIT_E;
3272
0
    }
3273
3274
14.5k
#ifndef TEST_UNPAD_CONSTANT_TIME
3275
14.5k
    if (ret == 0 && mp_read_unsigned_bin(tmp, in, inLen) != MP_OKAY)
3276
0
        ret = MP_READ_E;
3277
3278
#ifdef WOLFSSL_CHECK_MEM_ZERO
3279
    if (ret == 0) {
3280
        mp_memzero_add("RSA sync tmp", tmp);
3281
    }
3282
#endif
3283
3284
14.5k
    if (ret == 0) {
3285
14.5k
        switch(type) {
3286
0
    #if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
3287
0
        case RSA_PRIVATE_DECRYPT:
3288
7.38k
        case RSA_PRIVATE_ENCRYPT:
3289
7.38k
        {
3290
7.38k
            ret = RsaFunctionPrivate(tmp, key, rng);
3291
7.38k
            break;
3292
0
        }
3293
0
    #endif
3294
388
        case RSA_PUBLIC_ENCRYPT:
3295
7.14k
        case RSA_PUBLIC_DECRYPT:
3296
7.14k
            if (mp_exptmod_nct(tmp, &key->e, &key->n, tmp) != MP_OKAY) {
3297
3
                WOLFSSL_MSG_CERT_LOG("mp_exptmod_nct failed");
3298
3
                ret = MP_EXPTMOD_E;
3299
3
            }
3300
7.14k
            break;
3301
0
        default:
3302
0
            ret = RSA_WRONG_TYPE_E;
3303
0
            break;
3304
14.5k
        }
3305
14.5k
    }
3306
3307
14.5k
    if (ret == 0) {
3308
14.3k
        WOLFSSL_MSG("mp_to_unsigned_bin_len_ct...");
3309
14.3k
        if (mp_to_unsigned_bin_len_ct(tmp, out, (int)*outLen) != MP_OKAY) {
3310
0
            WOLFSSL_MSG("mp_to_unsigned_bin_len_ct failed");
3311
0
            ret = MP_TO_E;
3312
0
        }
3313
14.3k
    }
3314
#ifdef WOLFSSL_RSA_CHECK_D_ON_DECRYPT
3315
    if ((ret == 0) && (type == RSA_PRIVATE_DECRYPT)) {
3316
        mp_sub(&key->n, &key->p, tmp);
3317
        mp_sub(tmp, &key->q, tmp);
3318
        mp_add_d(tmp, 1, tmp);
3319
        mp_mulmod(&key->d, &key->e, tmp, tmp);
3320
        if (!mp_isone(tmp)) {
3321
            ret = MP_EXPTMOD_E;
3322
        }
3323
    }
3324
#endif
3325
#else
3326
    (void)type;
3327
    (void)key;
3328
    XMEMCPY(out, in, inLen);
3329
#endif
3330
3331
14.5k
    mp_forcezero(tmp);
3332
14.5k
    FREE_MP_INT_SIZE(tmp, key->heap, DYNAMIC_TYPE_RSA);
3333
#if !defined(MP_INT_SIZE_CHECK_NULL) && defined(WOLFSSL_CHECK_MEM_ZERO)
3334
    mp_memzero_check(tmp);
3335
#endif
3336
14.5k
    return ret;
3337
14.5k
}
3338
#endif /* !WOLFSSL_SP_MATH */
3339
3340
static int wc_RsaFunctionSync(const byte* in, word32 inLen, byte* out,
3341
                          word32* outLen, int type, RsaKey* key, WC_RNG* rng)
3342
15.1k
{
3343
15.1k
    int ret;
3344
15.1k
    word32 keyLen;
3345
3346
15.1k
    ret = wc_RsaEncryptSize(key);
3347
15.1k
    if (ret < 0) {
3348
#ifdef DEBUG_WOLFSSL
3349
        WOLFSSL_MSG_EX("wc_RsaEncryptSize failed err = %d", ret);
3350
#endif
3351
0
        return ret;
3352
0
    }
3353
15.1k
    keyLen = (word32)ret;
3354
3355
15.1k
    if (inLen > keyLen) {
3356
8
        WOLFSSL_MSG("Expected that inLen be no longer RSA key length");
3357
8
        return BAD_FUNC_ARG;
3358
8
    }
3359
15.1k
    if (keyLen > *outLen) {
3360
293
        WOLFSSL_MSG("Expected that outLen be no shorter RSA key length");
3361
293
        return RSA_BUFFER_E;
3362
293
    }
3363
3364
14.8k
    if (mp_iseven(&key->n)) {
3365
67
        WOLFSSL_MSG("MP_VAL is even");
3366
67
        return MP_VAL;
3367
67
    }
3368
3369
#if defined(WOLFSSL_NXP_CASPER_RSA_PUB_EXPTMOD)
3370
    if (type == RSA_PUBLIC_DECRYPT || type == RSA_PUBLIC_ENCRYPT) {
3371
        ret = casper_rsa_public_exptmod(in, inLen, out, outLen, key);
3372
        if (ret == 0)
3373
            return MP_OKAY;
3374
        /* else fall through for software fallback */
3375
    }
3376
#endif
3377
3378
#ifdef WOLFSSL_HAVE_SP_RSA
3379
    ret = RsaFunction_SP(in, inLen, out, outLen, type, key, rng);
3380
    if (ret != WC_NO_ERR_TRACE(WC_KEY_SIZE_E))
3381
        return ret;
3382
#endif /* WOLFSSL_HAVE_SP_RSA */
3383
3384
#if defined(WOLFSSL_SP_MATH)
3385
    (void)rng;
3386
#ifndef WOLFSSL_HAVE_SP_RSA
3387
    (void)in;
3388
    (void)inLen;
3389
    (void)out;
3390
    (void)outLen;
3391
    (void)type;
3392
    (void)key;
3393
    #error RSA SP option invalid (enable WOLFSSL_HAVE_SP_RSA or disable WOLFSSL_SP_MATH)
3394
    return NOT_COMPILED_IN;
3395
#else
3396
    WOLFSSL_MSG("SP Key Size Error");
3397
    return WC_KEY_SIZE_E;
3398
#endif
3399
#else
3400
14.8k
    *outLen = keyLen;
3401
14.8k
    return RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
3402
14.8k
#endif /* WOLFSSL_SP_MATH */
3403
14.8k
} /* wc_RsaFunctionSync */
3404
#endif /* !WOLF_CRYPTO_CB_ONLY_RSA && !WOLFSSL_NO_RSA_SW */
3405
#endif
3406
3407
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA)
3408
static int wc_RsaFunctionAsync(const byte* in, word32 inLen, byte* out,
3409
                          word32* outLen, int type, RsaKey* key, WC_RNG* rng)
3410
{
3411
    int ret = 0;
3412
3413
    (void)rng;
3414
3415
#ifdef WOLFSSL_ASYNC_CRYPT_SW
3416
    if (wc_AsyncSwInit(&key->asyncDev, ASYNC_SW_RSA_FUNC)) {
3417
        WC_ASYNC_SW* sw = &key->asyncDev.sw;
3418
        sw->rsaFunc.in = in;
3419
        sw->rsaFunc.inSz = inLen;
3420
        sw->rsaFunc.out = out;
3421
        sw->rsaFunc.outSz = outLen;
3422
        sw->rsaFunc.type = type;
3423
        sw->rsaFunc.key = key;
3424
        sw->rsaFunc.rng = rng;
3425
        return WC_PENDING_E;
3426
    }
3427
#endif /* WOLFSSL_ASYNC_CRYPT_SW */
3428
3429
#ifdef WC_RSA_NONBLOCK
3430
    /* When a non-blocking context is attached and the SP nonblock backend
3431
     * is available, drive the chunked state machine here. wolfAsync_DoSw
3432
     * (line "if (ret == FP_WOULDBLOCK) ret = WC_PENDING_E;" at the bottom
3433
     * of the SW switch in wolfcrypt/src/async.c, FP_WOULDBLOCK aliases
3434
     * MP_WOULDBLOCK) translates per-yield MP_WOULDBLOCK into WC_PENDING_E
3435
     * so the TLS / async event loop can drive the operation to completion. */
3436
    if (key->nb != NULL) {
3437
        return wc_RsaFunctionNonBlock(in, inLen, out, outLen, type, key);
3438
    }
3439
#endif
3440
3441
    switch (type) {
3442
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
3443
    case RSA_PRIVATE_DECRYPT:
3444
    case RSA_PRIVATE_ENCRYPT:
3445
    #ifdef HAVE_CAVIUM
3446
        key->dataLen = key->n.raw.len;
3447
        ret = NitroxRsaExptMod(in, inLen,
3448
                               key->d.raw.buf, key->d.raw.len,
3449
                               key->n.raw.buf, key->n.raw.len,
3450
                               out, outLen, key);
3451
    #elif defined(HAVE_INTEL_QA)
3452
        #ifdef RSA_LOW_MEM
3453
            ret = IntelQaRsaPrivate(&key->asyncDev, in, inLen,
3454
                                    &key->d.raw, &key->n.raw,
3455
                                    out, outLen);
3456
        #else
3457
            ret = IntelQaRsaCrtPrivate(&key->asyncDev, in, inLen,
3458
                                &key->p.raw, &key->q.raw,
3459
                                &key->dP.raw, &key->dQ.raw,
3460
                                &key->u.raw,
3461
                                out, outLen);
3462
        #endif
3463
    #else
3464
        ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
3465
    #endif
3466
        break;
3467
#endif
3468
3469
    case RSA_PUBLIC_ENCRYPT:
3470
    case RSA_PUBLIC_DECRYPT:
3471
    #ifdef HAVE_CAVIUM
3472
        key->dataLen = key->n.raw.len;
3473
        ret = NitroxRsaExptMod(in, inLen,
3474
                               key->e.raw.buf, key->e.raw.len,
3475
                               key->n.raw.buf, key->n.raw.len,
3476
                               out, outLen, key);
3477
    #elif defined(HAVE_INTEL_QA)
3478
        ret = IntelQaRsaPublic(&key->asyncDev, in, inLen,
3479
                               &key->e.raw, &key->n.raw,
3480
                               out, outLen);
3481
    #else
3482
        ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
3483
    #endif
3484
        break;
3485
3486
    default:
3487
        ret = RSA_WRONG_TYPE_E;
3488
    }
3489
3490
    return ret;
3491
}
3492
#endif /* WOLFSSL_ASYNC_CRYPT && WC_ASYNC_ENABLE_RSA */
3493
3494
#if defined(WC_RSA_DIRECT) || defined(WC_RSA_NO_PADDING) || \
3495
    defined(OPENSSL_EXTRA) || defined(OPENSSL_EXTRA_X509_SMALL)
3496
/* Performs direct RSA computation without padding. The input and output must
3497
 * match the key size (ex: 2048-bits = 256 bytes). Returns the size of the
3498
 * output on success or negative value on failure. */
3499
int wc_RsaDirect(const byte* in, word32 inLen, byte* out, word32* outSz,
3500
        RsaKey* key, int type, WC_RNG* rng)
3501
{
3502
    int ret;
3503
3504
    if (in == NULL || outSz == NULL || key == NULL) {
3505
        return BAD_FUNC_ARG;
3506
    }
3507
3508
    /* sanity check on type of RSA operation */
3509
    switch (type) {
3510
        case RSA_PUBLIC_ENCRYPT:
3511
        case RSA_PUBLIC_DECRYPT:
3512
        case RSA_PRIVATE_ENCRYPT:
3513
        case RSA_PRIVATE_DECRYPT:
3514
            break;
3515
        default:
3516
            WOLFSSL_MSG("Bad RSA type");
3517
            return BAD_FUNC_ARG;
3518
    }
3519
3520
    if ((ret = wc_RsaEncryptSize(key)) < 0) {
3521
        return ret;
3522
    }
3523
3524
    if (inLen != (word32)ret) {
3525
        WOLFSSL_MSG("Bad input length. Should be RSA key size");
3526
        return BAD_FUNC_ARG;
3527
    }
3528
3529
    if (out == NULL) {
3530
        *outSz = inLen;
3531
        return WC_NO_ERR_TRACE(LENGTH_ONLY_E);
3532
    }
3533
3534
    switch (key->state) {
3535
        case RSA_STATE_NONE:
3536
        case RSA_STATE_ENCRYPT_PAD:
3537
        case RSA_STATE_ENCRYPT_EXPTMOD:
3538
        case RSA_STATE_DECRYPT_EXPTMOD:
3539
        case RSA_STATE_DECRYPT_UNPAD:
3540
            key->state = (type == RSA_PRIVATE_ENCRYPT ||
3541
                    type == RSA_PUBLIC_ENCRYPT) ? RSA_STATE_ENCRYPT_EXPTMOD:
3542
                                                  RSA_STATE_DECRYPT_EXPTMOD;
3543
3544
            key->dataLen = *outSz;
3545
3546
            ret = wc_RsaFunction(in, inLen, out, &key->dataLen, type, key, rng);
3547
            if (ret >= 0 || ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
3548
                key->state = (type == RSA_PRIVATE_ENCRYPT ||
3549
                    type == RSA_PUBLIC_ENCRYPT) ? RSA_STATE_ENCRYPT_RES:
3550
                                                  RSA_STATE_DECRYPT_RES;
3551
            }
3552
            if (ret < 0) {
3553
                break;
3554
            }
3555
3556
            FALL_THROUGH;
3557
3558
        case RSA_STATE_ENCRYPT_RES:
3559
        case RSA_STATE_DECRYPT_RES:
3560
            ret = (int)key->dataLen;
3561
            break;
3562
3563
        default:
3564
            ret = BAD_STATE_E;
3565
    }
3566
3567
    /* if async pending then skip cleanup*/
3568
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)
3569
    #ifdef WC_RSA_NONBLOCK
3570
        || ret == FP_WOULDBLOCK
3571
    #endif
3572
    ) {
3573
        return ret;
3574
    }
3575
3576
    key->state = RSA_STATE_NONE;
3577
    wc_RsaCleanup(key);
3578
3579
    return ret;
3580
}
3581
#endif /* WC_RSA_DIRECT || WC_RSA_NO_PADDING || OPENSSL_EXTRA || \
3582
        * OPENSSL_EXTRA_X509_SMALL */
3583
3584
3585
#if !defined(WOLF_CRYPTO_CB_ONLY_RSA) && !defined(WOLFSSL_NO_RSA_SW)
3586
#if !defined(NO_RSA_BOUNDS_CHECK)
3587
/* Check that 1 < in < n-1. (Requirement of 800-56B.) */
3588
int RsaFunctionCheckIn(const byte* in, word32 inLen, RsaKey* key,
3589
    int checkSmallCt)
3590
7.19k
{
3591
7.19k
    int ret = 0;
3592
3593
7.19k
    DECL_MP_INT_SIZE_DYN(c, mp_bitsused(&key->n), RSA_MAX_SIZE);
3594
3595
7.19k
    if (MP_BITS_OVER_MAX(mp_bitsused(&key->n), RSA_MAX_SIZE)) {
3596
1
        return WC_KEY_SIZE_E;
3597
1
    }
3598
3599
7.18k
    NEW_MP_INT_SIZE(c, mp_bitsused(&key->n), key->heap, DYNAMIC_TYPE_RSA);
3600
7.18k
#ifdef MP_INT_SIZE_CHECK_NULL
3601
7.18k
    if (c == NULL)
3602
0
        ret = MEMORY_E;
3603
7.18k
#endif
3604
3605
7.18k
    if (ret == 0 && INIT_MP_INT_SIZE(c, mp_bitsused(&key->n)) != MP_OKAY) {
3606
0
        ret = MP_INIT_E;
3607
0
    }
3608
7.18k
    if (ret == 0) {
3609
7.18k
        if (mp_read_unsigned_bin(c, in, inLen) != 0)
3610
24
            ret = MP_READ_E;
3611
7.18k
    }
3612
7.18k
    if (ret == 0) {
3613
        /* check c > 1 */
3614
7.16k
        if (checkSmallCt && (mp_cmp_d(c, 1) != MP_GT))
3615
5
            ret = RSA_OUT_OF_RANGE_E;
3616
7.16k
    }
3617
7.18k
    if (ret == 0) {
3618
        /* add c+1 */
3619
7.16k
        if (mp_add_d(c, 1, c) != MP_OKAY)
3620
1
            ret = MP_ADD_E;
3621
7.16k
    }
3622
7.18k
    if (ret == 0) {
3623
        /* check c+1 < n */
3624
7.15k
        if (mp_cmp(c, &key->n) != MP_LT)
3625
114
            ret = RSA_OUT_OF_RANGE_E;
3626
7.15k
    }
3627
7.18k
    mp_clear(c);
3628
3629
7.18k
    FREE_MP_INT_SIZE(c, key->heap, DYNAMIC_TYPE_RSA);
3630
3631
7.18k
    return ret;
3632
7.19k
}
3633
#endif /* !NO_RSA_BOUNDS_CHECK */
3634
#endif /* !WOLF_CRYPTO_CB_ONLY_RSA && !WOLFSSL_NO_RSA_SW */
3635
3636
static int wc_RsaFunction_ex(const byte* in, word32 inLen, byte* out,
3637
                             word32* outLen, int type, RsaKey* key, WC_RNG* rng,
3638
                             int checkSmallCt)
3639
15.0k
{
3640
15.0k
#if !defined(WOLFSSL_NO_RSA_SW) || defined(WOLF_CRYPTO_CB)
3641
15.0k
    int ret = 0;
3642
15.0k
#endif
3643
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD)
3644
    RsaPadding padding;
3645
#endif
3646
3647
15.0k
    (void)rng;
3648
15.0k
    (void)checkSmallCt;
3649
3650
15.0k
    if (key == NULL || in == NULL || inLen == 0 || out == NULL ||
3651
15.0k
            outLen == NULL || *outLen == 0 || type == RSA_TYPE_UNKNOWN) {
3652
0
        return BAD_FUNC_ARG;
3653
0
    }
3654
3655
15.0k
#ifdef WOLF_CRYPTO_CB
3656
15.0k
    #ifndef WOLF_CRYPTO_CB_FIND
3657
15.0k
    if (key->devId != INVALID_DEVID)
3658
0
    #endif
3659
0
    {
3660
    #if defined(WOLF_CRYPTO_CB_RSA_PAD)
3661
        /* If we are here, either the RSA PAD callback was already called
3662
         * and returned that it could not implement for that padding scheme,
3663
         * or this is a public verify operation. Either way indicate to the
3664
         * callback that this should be a raw RSA operation with no padding.*/
3665
        XMEMSET(&padding, 0, sizeof(RsaPadding));
3666
        padding.pad_type = WC_RSA_NO_PAD;
3667
        ret = wc_CryptoCb_RsaPad(in, inLen, out,
3668
                            outLen, type, key, rng, &padding);
3669
    #else
3670
0
        ret = wc_CryptoCb_Rsa(in, inLen, out, outLen, type, key, rng);
3671
0
    #endif
3672
0
        #ifndef WOLF_CRYPTO_CB_ONLY_RSA
3673
0
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE))
3674
0
            return ret;
3675
        /* fall-through when unavailable and try using software */
3676
0
        #endif
3677
        #ifdef WOLF_CRYPTO_CB_ONLY_RSA
3678
        if (ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
3679
            return NO_VALID_DEVID;
3680
        }
3681
        return ret;
3682
        #endif
3683
0
    }
3684
15.0k
#endif
3685
3686
#ifdef WOLFSSL_NO_RSA_SW
3687
    /* No software modular exponentiation is compiled in. The hardware
3688
     * implementation is driven from RsaPublicEncryptEx()/RsaPrivateDecryptEx()
3689
     * with the padding it performs itself, so the raw operation offered by
3690
     * wc_RsaFunction()/wc_RsaDirect() has no provider here. */
3691
    return NOT_COMPILED_IN;
3692
#elif defined(WOLF_CRYPTO_CB_ONLY_RSA)
3693
    return NO_VALID_DEVID;
3694
#else /* !WOLF_CRYPTO_CB_ONLY_RSA */
3695
3696
15.0k
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(TEST_UNPAD_CONSTANT_TIME) && \
3697
15.0k
    !defined(NO_RSA_BOUNDS_CHECK)
3698
15.0k
    if (type == RSA_PRIVATE_DECRYPT &&
3699
0
        key->state == RSA_STATE_DECRYPT_EXPTMOD) {
3700
3701
0
        ret = RsaFunctionCheckIn(in, inLen, key, checkSmallCt);
3702
0
        if (ret != 0) {
3703
0
            return ret;
3704
0
        }
3705
0
    }
3706
15.0k
#endif /* !WOLFSSL_RSA_VERIFY_ONLY && !TEST_UNPAD_CONSTANT_TIME && \
3707
        * !NO_RSA_BOUNDS_CHECK */
3708
15.0k
#if !defined(NO_RSA_BOUNDS_CHECK)
3709
15.0k
    if (type == RSA_PUBLIC_DECRYPT &&
3710
7.19k
        key->state == RSA_STATE_DECRYPT_EXPTMOD) {
3711
3712
7.19k
        ret = RsaFunctionCheckIn(in, inLen, key, checkSmallCt);
3713
7.19k
        if (ret != 0) {
3714
145
            return ret;
3715
145
        }
3716
7.19k
    }
3717
14.8k
#endif
3718
3719
#if !defined(NO_RSA_BOUNDS_CHECK) && FIPS_VERSION3_GE(7,0,0)
3720
    /* Reject a message outside 1 < m < n-1 before exponentiating.
3721
     * SP 800-56B Rev2 sec 7.1.1 (RSAEP) step 1.  Passed 1 rather than the
3722
     * caller's checkSmallCt: the standard gives no opt-out on this path. */
3723
    if ((type == RSA_PUBLIC_ENCRYPT || type == RSA_PRIVATE_ENCRYPT) &&
3724
        key->state == RSA_STATE_ENCRYPT_EXPTMOD) {
3725
3726
        ret = RsaFunctionCheckIn(in, inLen, key, 1);
3727
        if (ret != 0) {
3728
            return ret;
3729
        }
3730
    }
3731
#endif
3732
3733
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA)
3734
    if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
3735
                                                        key->n.raw.len > 0) {
3736
        /* wc_RsaFunctionAsync dispatches to the SP nonblock state machine
3737
         * in its compute path when key->nb is attached - wolfAsync_DoSw
3738
         * (in wolfcrypt/src/async.c) translates per-yield FP_WOULDBLOCK
3739
         * (alias of MP_WOULDBLOCK) into WC_PENDING_E so the TLS / async
3740
         * event loop can drive completion. */
3741
        ret = wc_RsaFunctionAsync(in, inLen, out, outLen, type, key, rng);
3742
    }
3743
    else
3744
#endif
3745
#ifdef WC_RSA_NONBLOCK
3746
    if (key->nb) {
3747
        /* Direct (non-async) nonblock dispatch - the caller (e.g. wolfcrypt
3748
         * test) drives the loop on MP_WOULDBLOCK directly. Reached when no
3749
         * async marker is set on the key. */
3750
        ret = wc_RsaFunctionNonBlock(in, inLen, out, outLen, type, key);
3751
    }
3752
    else
3753
#endif
3754
14.8k
    {
3755
14.8k
        ret = wc_RsaFunctionSync(in, inLen, out, outLen, type, key, rng);
3756
14.8k
    }
3757
3758
    /* handle error */
3759
14.8k
    if (ret < 0 && ret != WC_NO_ERR_TRACE(WC_PENDING_E)
3760
    #ifdef WC_RSA_NONBLOCK
3761
        && ret != FP_WOULDBLOCK
3762
    #endif
3763
14.8k
    ) {
3764
516
        if (ret == WC_NO_ERR_TRACE(MP_EXPTMOD_E)) {
3765
            /* This can happen due to incorrectly set FP_MAX_BITS or missing XREALLOC */
3766
8
            WOLFSSL_MSG("RSA_FUNCTION MP_EXPTMOD_E: memory/config problem");
3767
8
        }
3768
3769
516
        key->state = RSA_STATE_NONE;
3770
516
        wc_RsaCleanup(key);
3771
516
    }
3772
14.8k
    return ret;
3773
15.0k
#endif /* !WOLFSSL_NO_RSA_SW && !WOLF_CRYPTO_CB_ONLY_RSA */
3774
15.0k
}
3775
3776
int wc_RsaFunction(const byte* in, word32 inLen, byte* out,
3777
                          word32* outLen, int type, RsaKey* key, WC_RNG* rng)
3778
7.81k
{
3779
    /* Always check for ciphertext of 0 or 1. (Shouldn't for OAEP decrypt.) */
3780
7.81k
    return wc_RsaFunction_ex(in, inLen, out, outLen, type, key, rng, 1);
3781
7.81k
}
3782
3783
#if !defined(WOLFSSL_NO_RSA_SW_PAD) || defined(WC_RSA_PSS)
3784
/* Modulus bits, from the device's size in bytes for a key it holds. */
3785
static int RsaModulusBits(const RsaKey* key)
3786
15.0k
{
3787
15.0k
    int bits = mp_count_bits(&key->n);
3788
3789
15.0k
    if (bits == 0) {
3790
0
        bits = wc_RsaEncryptSize(key);
3791
0
        bits = (bits > 0) ? bits * WOLFSSL_BIT_SIZE : 0;
3792
0
    }
3793
3794
15.0k
    return bits;
3795
15.0k
}
3796
#endif
3797
3798
#ifndef WOLFSSL_RSA_VERIFY_ONLY
3799
/* Internal Wrappers */
3800
/* Gives the option of choosing padding type
3801
   in : input to be encrypted
3802
   inLen: length of input buffer
3803
   out: encrypted output
3804
   outLen: length of encrypted output buffer
3805
   key   : wolfSSL initialized RSA key struct
3806
   rng   : wolfSSL initialized random number struct
3807
   rsa_type  : type of RSA: RSA_PUBLIC_ENCRYPT, RSA_PUBLIC_DECRYPT,
3808
        RSA_PRIVATE_ENCRYPT or RSA_PRIVATE_DECRYPT
3809
   pad_value: RSA_BLOCK_TYPE_1 or RSA_BLOCK_TYPE_2
3810
   pad_type  : type of padding: WC_RSA_PKCSV15_PAD, WC_RSA_OAEP_PAD,
3811
        WC_RSA_NO_PAD or WC_RSA_PSS_PAD
3812
   hash  : type of hash algorithm to use found in wolfssl/wolfcrypt/hash.h
3813
   mgf   : type of mask generation function to use
3814
   label : optional label
3815
   labelSz : size of optional label buffer
3816
   saltLen : Length of salt used in PSS
3817
   rng : random number generator */
3818
static int RsaPublicEncryptEx(const byte* in, word32 inLen, byte* out,
3819
                            word32 outLen, RsaKey* key, int rsa_type,
3820
                            byte pad_value, int pad_type,
3821
                            enum wc_HashType hash, int mgf,
3822
                            byte* label, word32 labelSz, int saltLen,
3823
                            WC_RNG* rng)
3824
0
{
3825
0
    int ret = 0;
3826
0
    int sz;
3827
0
    int state;
3828
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD)
3829
    RsaPadding padding;
3830
#endif
3831
3832
0
    if (in == NULL || inLen == 0 || out == NULL || key == NULL) {
3833
0
        return BAD_FUNC_ARG;
3834
0
    }
3835
3836
0
    sz = wc_RsaEncryptSize(key);
3837
0
    if (sz > (int)outLen) {
3838
0
        return RSA_BUFFER_E;
3839
0
    }
3840
3841
0
    if (sz < RSA_MIN_PAD_SZ || sz > (int)RSA_MAX_SIZE/8) {
3842
0
        return WC_KEY_SIZE_E;
3843
0
    }
3844
3845
0
    if (inLen > (word32)(sz - RSA_MIN_PAD_SZ)) {
3846
#ifdef WC_RSA_NO_PADDING
3847
        /* In the case that no padding is used the input length can and should
3848
         * be the same size as the RSA key. */
3849
        if (pad_type != WC_RSA_NO_PAD)
3850
#endif
3851
0
        return RSA_BUFFER_E;
3852
0
    }
3853
3854
0
#ifndef WOLFSSL_BIND
3855
0
    state = key->state;
3856
#else
3857
    /* Bind9 shares the EVP_PKEY struct across multiple threads so let's just
3858
     * force a restart on each RsaPublicEncryptEx call for it. */
3859
    state = RSA_STATE_NONE;
3860
#ifdef WOLFSSL_ASYNC_CRYPT
3861
#error wolfSSL does not handle building bind support with async crypto
3862
#endif
3863
#endif
3864
0
    switch (state) {
3865
0
    case RSA_STATE_NONE:
3866
0
    case RSA_STATE_ENCRYPT_PAD:
3867
    #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
3868
            defined(HAVE_CAVIUM)
3869
        if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
3870
                                 pad_type != WC_RSA_PSS_PAD && key->n.raw.buf) {
3871
            /* Async operations that include padding */
3872
            if (rsa_type == RSA_PUBLIC_ENCRYPT &&
3873
                                                pad_value == RSA_BLOCK_TYPE_2) {
3874
                key->state = RSA_STATE_ENCRYPT_RES;
3875
                key->dataLen = key->n.raw.len;
3876
                return NitroxRsaPublicEncrypt(in, inLen, out, outLen, key);
3877
            }
3878
            else if (rsa_type == RSA_PRIVATE_ENCRYPT &&
3879
                                                pad_value == RSA_BLOCK_TYPE_1) {
3880
                key->state = RSA_STATE_ENCRYPT_RES;
3881
                key->dataLen = key->n.raw.len;
3882
                return NitroxRsaSSL_Sign(in, inLen, out, outLen, key);
3883
            }
3884
        }
3885
    #elif defined(WOLFSSL_MICROCHIP_TA100)
3886
        if (rsa_type == RSA_PUBLIC_ENCRYPT &&
3887
                                            pad_value == RSA_BLOCK_TYPE_2) {
3888
            if (key->uKeyH != 0) {
3889
                return wc_Microchip_rsa_encrypt(in, inLen, out, outLen, key);
3890
            }
3891
            return WC_HW_E;
3892
        }
3893
        else if (rsa_type == RSA_PRIVATE_ENCRYPT &&
3894
                                         pad_value == RSA_BLOCK_TYPE_1) {
3895
            if (key->rKeyH != 0) {
3896
                if (pad_type != WC_RSA_PSS_PAD) {
3897
                    return WC_HW_E;
3898
                }
3899
                return wc_Microchip_rsa_sign(in, inLen, out, outLen, key);
3900
            }
3901
            return WC_HW_E;
3902
        }
3903
    #elif defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA)
3904
    #ifdef WOLFSSL_SE050_ONLY_KEY_ID
3905
        /* Only offload to the SE050 when the key is resident in hardware;
3906
         * software keys (keyIdSet == 0) fall through to the software path. */
3907
        if (key->keyIdSet)
3908
    #endif
3909
        {
3910
        if (rsa_type == RSA_PUBLIC_ENCRYPT && pad_value == RSA_BLOCK_TYPE_2) {
3911
            return se050_rsa_public_encrypt(in, inLen, out, outLen, key,
3912
                                            rsa_type, pad_value, pad_type, hash,
3913
                                            mgf, label, labelSz, sz);
3914
        }
3915
        else if (rsa_type == RSA_PRIVATE_ENCRYPT &&
3916
                 pad_value == RSA_BLOCK_TYPE_1 &&
3917
                 pad_type != WC_RSA_PSS_PAD) {
3918
            /* SE050 handles PKCS#1 v1.5 signing directly. PSS signing falls
3919
             * through to software path because the SE050 PSS sign API
3920
             * (Se05x_API_RSASign) is hash-then-sign and does not support
3921
             * signing a pre-computed digest without double-hashing. */
3922
            return se050_rsa_sign(in, inLen, out, outLen, key, rsa_type,
3923
                                  pad_value, pad_type, hash, mgf, label,
3924
                                  labelSz, sz);
3925
        }
3926
        }
3927
    #endif /* RSA CRYPTO HW */
3928
3929
    #ifdef WOLFSSL_NO_RSA_SW_PAD
3930
        /* Hardware only build with no software padding compiled in: whatever
3931
         * the hardware dispatch above did not take has no provider here, the
3932
         * same way wc_RsaFunction() has none. Not every hardware arm consumes
3933
         * the padding arguments, so discard them all here. */
3934
        (void)pad_type;
3935
        (void)hash;
3936
        (void)mgf;
3937
        (void)label;
3938
        (void)labelSz;
3939
        (void)saltLen;
3940
        (void)rng;
3941
        ret = NOT_COMPILED_IN;
3942
        break;
3943
    #else
3944
3945
    #if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD)
3946
        if (key->devId != INVALID_DEVID) {
3947
            XMEMSET(&padding, 0, sizeof(RsaPadding));
3948
            padding.pad_value = pad_value;
3949
            padding.pad_type = pad_type;
3950
            padding.hash = hash;
3951
            padding.mgf = mgf;
3952
            padding.label = label;
3953
            padding.labelSz = labelSz;
3954
            padding.saltLen = saltLen;
3955
            ret = wc_CryptoCb_RsaPad(in, inLen, out, &outLen, rsa_type, key, rng,
3956
                                     &padding);
3957
3958
            if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
3959
                if (ret < 0) {
3960
                    break;
3961
                }
3962
3963
                ret = outLen;
3964
                break;
3965
            }
3966
        }
3967
    #endif
3968
0
        key->state = RSA_STATE_ENCRYPT_PAD;
3969
0
        ret = wc_RsaPad_ex(in, inLen, out, (word32)sz, pad_value, rng, pad_type,
3970
0
                           hash, mgf, label, labelSz, saltLen,
3971
0
                           RsaModulusBits(key), key->heap);
3972
0
        if (ret < 0) {
3973
            /* SP 800-56Br2 7.2.2.3: destroy DB, EM and em on any exit,
3974
             * including an early error exit; the OAEP block is built in
3975
             * out (ISO/IEC 19790:2012 7.9.7). */
3976
0
            if (pad_type == WC_RSA_OAEP_PAD) {
3977
0
                ForceZero(out, (word32)sz);
3978
0
            }
3979
0
            break;
3980
0
        }
3981
3982
0
        key->state = RSA_STATE_ENCRYPT_EXPTMOD;
3983
0
        FALL_THROUGH;
3984
3985
0
    case RSA_STATE_ENCRYPT_EXPTMOD:
3986
3987
0
        key->dataLen = outLen;
3988
0
        ret = wc_RsaFunction(out, (word32)sz, out, &key->dataLen, rsa_type, key,
3989
0
                             rng);
3990
3991
0
        if (ret >= 0 || ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
3992
0
            key->state = RSA_STATE_ENCRYPT_RES;
3993
0
        }
3994
0
        if (ret < 0) {
3995
            /* SP 800-56Br2 7.2.2.3: EM is still in out after a failed RSAEP.
3996
             * A pending or would-block call resumes from it. */
3997
0
            if ((pad_type == WC_RSA_OAEP_PAD) &&
3998
0
                    (ret != WC_NO_ERR_TRACE(WC_PENDING_E))
3999
            #ifdef WC_RSA_NONBLOCK
4000
                    && (ret != FP_WOULDBLOCK)
4001
            #endif
4002
0
                    ) {
4003
0
                ForceZero(out, (word32)sz);
4004
0
            }
4005
0
            break;
4006
0
        }
4007
4008
0
        FALL_THROUGH;
4009
0
    #endif /* !WOLFSSL_NO_RSA_SW_PAD */
4010
4011
0
    case RSA_STATE_ENCRYPT_RES:
4012
0
        ret = (int)key->dataLen;
4013
0
        break;
4014
4015
0
    default:
4016
0
        ret = BAD_STATE_E;
4017
0
        break;
4018
0
    }
4019
4020
    /* if async pending then return and skip done cleanup below */
4021
0
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)
4022
    #ifdef WC_RSA_NONBLOCK
4023
        || ret == FP_WOULDBLOCK
4024
    #endif
4025
0
    ) {
4026
0
        return ret;
4027
0
    }
4028
4029
0
    key->state = RSA_STATE_NONE;
4030
0
    wc_RsaCleanup(key);
4031
4032
0
    return ret;
4033
0
}
4034
4035
#endif
4036
4037
/* Gives the option of choosing padding type
4038
   in : input to be decrypted
4039
   inLen: length of input buffer
4040
   out:  decrypted message
4041
   outLen: length of decrypted message in bytes
4042
   outPtr: optional inline output pointer (if provided doing inline)
4043
   key   : wolfSSL initialized RSA key struct
4044
   rsa_type  : type of RSA: RSA_PUBLIC_ENCRYPT, RSA_PUBLIC_DECRYPT,
4045
        RSA_PRIVATE_ENCRYPT or RSA_PRIVATE_DECRYPT
4046
   pad_value: RSA_BLOCK_TYPE_1 or RSA_BLOCK_TYPE_2
4047
   pad_type  : type of padding: WC_RSA_PKCSV15_PAD, WC_RSA_OAEP_PAD,
4048
        WC_RSA_NO_PAD, WC_RSA_PSS_PAD
4049
   hash  : type of hash algorithm to use found in wolfssl/wolfcrypt/hash.h
4050
   mgf   : type of mask generation function to use
4051
   label : optional label
4052
   labelSz : size of optional label buffer
4053
   saltLen : Length of salt used in PSS
4054
   rng : random number generator */
4055
static int RsaPrivateDecryptEx(const byte* in, word32 inLen, byte* out,
4056
                            word32 outLen, byte** outPtr, RsaKey* key,
4057
                            int rsa_type, byte pad_value, int pad_type,
4058
                            enum wc_HashType hash, int mgf,
4059
                            byte* label, word32 labelSz, int saltLen,
4060
                            WC_RNG* rng)
4061
7.55k
{
4062
7.55k
    int ret = WC_NO_ERR_TRACE(RSA_WRONG_TYPE_E);
4063
7.55k
#ifndef WOLFSSL_NO_RSA_SW_PAD
4064
7.55k
    byte* pad = NULL;
4065
7.55k
#endif
4066
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD)
4067
    RsaPadding padding;
4068
#endif
4069
4070
7.55k
    if (in == NULL || inLen == 0 || out == NULL || key == NULL) {
4071
19
        return BAD_FUNC_ARG;
4072
19
    }
4073
4074
7.53k
    switch (key->state) {
4075
7.53k
    case RSA_STATE_NONE:
4076
7.53k
        key->dataLen = inLen;
4077
4078
    #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
4079
            defined(HAVE_CAVIUM)
4080
        /* Async operations that include padding */
4081
        if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
4082
                                                   pad_type != WC_RSA_PSS_PAD) {
4083
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
4084
            if (rsa_type == RSA_PRIVATE_DECRYPT &&
4085
                                                pad_value == RSA_BLOCK_TYPE_2) {
4086
                key->state = RSA_STATE_DECRYPT_RES;
4087
                key->data = NULL;
4088
                return NitroxRsaPrivateDecrypt(in, inLen, out, &key->dataLen,
4089
                                               key);
4090
#endif
4091
            }
4092
            else if (rsa_type == RSA_PUBLIC_DECRYPT &&
4093
                                                pad_value == RSA_BLOCK_TYPE_1) {
4094
                key->state = RSA_STATE_DECRYPT_RES;
4095
                key->data = NULL;
4096
                return NitroxRsaSSL_Verify(in, inLen, out, &key->dataLen, key);
4097
            }
4098
        }
4099
    #elif defined(WOLFSSL_MICROCHIP_TA100)
4100
        if (rsa_type == RSA_PRIVATE_DECRYPT &&
4101
                                            pad_value == RSA_BLOCK_TYPE_2) {
4102
            if (key->rKeyH != 0) {
4103
                return wc_Microchip_rsa_decrypt(in, inLen, out, outLen, key);
4104
            }
4105
            return WC_HW_E;
4106
        }
4107
        /* Note: RSA_PUBLIC_DECRYPT (verify) is intentionally not intercepted
4108
         * here. wc_Microchip_rsa_verify takes a digest as input, not a raw
4109
         * signature blob; the proper TA100 short-circuit lives in the
4110
         * wc_RsaPSS_CheckPadding / wc_RsaPSS_VerifyCheck path which has the
4111
         * digest available. */
4112
    #elif defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA)
4113
    #ifdef WOLFSSL_SE050_ONLY_KEY_ID
4114
        /* Only offload to the SE050 when the key is resident in hardware;
4115
         * software keys (keyIdSet == 0) fall through to the software path. */
4116
        if (key->keyIdSet)
4117
    #endif
4118
        {
4119
        if (rsa_type == RSA_PRIVATE_DECRYPT && pad_value == RSA_BLOCK_TYPE_2) {
4120
            ret = se050_rsa_private_decrypt(in, inLen, out, outLen, key,
4121
                                            rsa_type, pad_value, pad_type, hash,
4122
                                            mgf, label, labelSz);
4123
            if (outPtr != NULL) {
4124
                *outPtr = out;
4125
            }
4126
            return ret;
4127
        }
4128
    #if !defined(WOLFSSL_SE050_NO_RSA_VERIFY)
4129
        else if (rsa_type == RSA_PUBLIC_DECRYPT &&
4130
                 pad_value == RSA_BLOCK_TYPE_1 &&
4131
                 pad_type != WC_RSA_PSS_PAD) {
4132
            /* SE050 handles PKCS#1 v1.5 verification directly. PSS
4133
             * verification falls through to software path to match the
4134
             * software PSS signing path (SE050 PSS sign uses hash-then-sign
4135
             * which double-hashes a pre-computed digest). */
4136
            ret = se050_rsa_verify(in, inLen, out, outLen, key, rsa_type,
4137
                                   pad_value, pad_type, hash, mgf, label,
4138
                                   labelSz);
4139
            if (outPtr != NULL) {
4140
                *outPtr = out;
4141
            }
4142
            return ret;
4143
        }
4144
    #endif /* !WOLFSSL_SE050_NO_RSA_VERIFY */
4145
        }
4146
    #endif /* RSA CRYPTO HW */
4147
4148
    #ifdef WOLFSSL_NO_RSA_SW_PAD
4149
        /* Hardware only build with no software padding compiled in: whatever
4150
         * the hardware dispatch above did not take has no provider here, the
4151
         * same way wc_RsaFunction() has none. Not every hardware arm consumes
4152
         * the padding arguments, so discard them all here. */
4153
        (void)pad_type;
4154
        (void)hash;
4155
        (void)mgf;
4156
        (void)label;
4157
        (void)labelSz;
4158
        (void)saltLen;
4159
        (void)rng;
4160
        ret = NOT_COMPILED_IN;
4161
        break;
4162
    #else
4163
4164
7.53k
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) && \
4165
7.53k
    !defined(WOLFSSL_NO_MALLOC)
4166
        /* verify the tmp ptr is NULL, otherwise indicates bad state */
4167
7.53k
        if (key->data != NULL) {
4168
0
            ret = BAD_STATE_E;
4169
0
            break;
4170
0
        }
4171
4172
        /* if not doing this inline then allocate a buffer for it */
4173
7.53k
        if (outPtr == NULL) {
4174
709
            key->data = (byte*)XMALLOC(inLen, key->heap,
4175
709
                                                      DYNAMIC_TYPE_WOLF_BIGINT);
4176
709
            key->dataIsAlloc = 1;
4177
709
            if (key->data == NULL) {
4178
0
                ret = MEMORY_E;
4179
0
                break;
4180
0
            }
4181
709
            XMEMCPY(key->data, in, inLen);
4182
709
            key->dataLen = inLen;
4183
            #ifdef WOLFSSL_CHECK_MEM_ZERO
4184
            wc_MemZero_Add("key data in", key->data, key->dataLen);
4185
            #endif
4186
709
        }
4187
6.82k
        else {
4188
6.82k
            key->dataIsAlloc = 0;
4189
6.82k
            key->data = out;
4190
6.82k
        }
4191
7.53k
#endif
4192
4193
7.53k
        key->state = RSA_STATE_DECRYPT_EXPTMOD;
4194
7.53k
        FALL_THROUGH;
4195
4196
7.53k
    case RSA_STATE_DECRYPT_EXPTMOD:
4197
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD)
4198
    if ((key->devId != INVALID_DEVID)
4199
    #if !defined(WOLFSSL_RENESAS_FSPSM_CRYPTONLY) && \
4200
        !defined(WOLFSSL_RENESAS_TSIP_CRYPTONLY)
4201
    && (rsa_type != RSA_PUBLIC_DECRYPT)
4202
    #endif
4203
    ) {
4204
        /* Everything except verify goes to crypto cb if
4205
         * WOLF_CRYPTO_CB_RSA_PAD defined */
4206
        XMEMSET(&padding, 0, sizeof(RsaPadding));
4207
        padding.pad_value = pad_value;
4208
        padding.pad_type = pad_type;
4209
        padding.hash = hash;
4210
        padding.mgf = mgf;
4211
        padding.label = label;
4212
        padding.labelSz = labelSz;
4213
        padding.saltLen = saltLen;
4214
        ret = wc_CryptoCb_RsaPad(in, inLen, out,
4215
                            &outLen, rsa_type, key, rng, &padding);
4216
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
4217
            if (outPtr != NULL) {
4218
                *outPtr = out;
4219
            }
4220
            if (ret == 0) {
4221
                ret = (int)outLen;
4222
            }
4223
            break;
4224
        }
4225
    }
4226
#endif
4227
7.53k
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) && \
4228
7.53k
    !defined(WOLFSSL_NO_MALLOC)
4229
7.53k
        ret = wc_RsaFunction_ex(key->data, inLen, key->data, &key->dataLen,
4230
7.53k
                                                   rsa_type, key, rng,
4231
7.53k
                                                   pad_type != WC_RSA_OAEP_PAD);
4232
#else
4233
        ret = wc_RsaFunction_ex(in, inLen, out, &key->dataLen, rsa_type, key,
4234
                                              rng, pad_type != WC_RSA_OAEP_PAD);
4235
#endif
4236
4237
7.53k
        if (ret >= 0 || ret == WC_NO_ERR_TRACE(WC_PENDING_E)) {
4238
7.04k
            key->state = RSA_STATE_DECRYPT_UNPAD;
4239
7.04k
        }
4240
7.53k
        if (ret < 0) {
4241
490
            break;
4242
490
        }
4243
4244
7.04k
        FALL_THROUGH;
4245
4246
7.04k
    case RSA_STATE_DECRYPT_UNPAD:
4247
7.04k
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) && \
4248
7.04k
    !defined(WOLFSSL_NO_MALLOC)
4249
7.04k
        ret = wc_RsaUnPad_ex(key->data,
4250
7.04k
            key->dataLen, &pad, pad_value, pad_type, hash, mgf,
4251
7.04k
            label, labelSz, saltLen, RsaModulusBits(key), key->heap);
4252
#else
4253
        ret = wc_RsaUnPad_ex(out,
4254
            key->dataLen, &pad, pad_value, pad_type, hash, mgf, label,
4255
            labelSz, saltLen, RsaModulusBits(key), key->heap);
4256
#endif
4257
7.04k
        if (rsa_type == RSA_PUBLIC_DECRYPT && ret > (int)outLen) {
4258
4
            ret = RSA_BUFFER_E;
4259
4
        }
4260
7.03k
        else if (ret >= 0 && pad != NULL) {
4261
            /* only copy output if not inline */
4262
6.17k
            if (outPtr == NULL) {
4263
10
#if !defined(WOLFSSL_RSA_VERIFY_ONLY) && !defined(WOLFSSL_RSA_VERIFY_INLINE) && \
4264
10
    !defined(WOLFSSL_NO_MALLOC)
4265
10
                if (rsa_type == RSA_PRIVATE_DECRYPT) {
4266
0
                    word32 i = 0;
4267
0
                    word32 j;
4268
0
                    byte last = 0;
4269
0
                    int start = (int)((size_t)pad - (size_t)key->data);
4270
4271
0
                    for (j = 0; j < key->dataLen; j++) {
4272
0
                        signed char incMask;
4273
0
                        signed char maskData;
4274
4275
                        /* When j < start + outLen then out[i] = key->data[j]
4276
                         *                         else out[i] = last
4277
                         */
4278
0
                        maskData = (signed char)ctMaskLT((int)j,
4279
0
                            start + (int)outLen);
4280
0
                        out[i] = (byte)(key->data[j] &   maskData ) |
4281
0
                                 (byte)(last         & (~maskData));
4282
0
                        last = out[i];
4283
4284
                        /* Increment i when j is in range:
4285
                         *   [start..(start + outLen - 1)]. */
4286
0
                        incMask  = (signed char)ctMaskGTE((int)j, start);
4287
0
                        incMask &= (signed char)ctMaskLT((int)j,
4288
0
                            start + (int)outLen - 1);
4289
0
                        i += (word32)((byte)(-incMask));
4290
0
                    }
4291
0
                }
4292
10
                else
4293
10
#endif
4294
10
                {
4295
10
                    XMEMCPY(out, pad, (size_t)ret);
4296
10
                }
4297
10
            }
4298
6.16k
            else {
4299
6.16k
                *outPtr = pad;
4300
6.16k
            }
4301
4302
6.17k
#if !defined(WOLFSSL_RSA_VERIFY_ONLY)
4303
6.17k
            ret = ctMaskSelInt(ctMaskLTE(ret, (int)outLen), ret,
4304
6.17k
                               WC_NO_ERR_TRACE(RSA_BUFFER_E));
4305
6.17k
    #ifndef WOLFSSL_RSA_DECRYPT_TO_0_LEN
4306
6.17k
            ret = ctMaskSelInt(ctMaskNotEq(ret, 0), ret,
4307
6.17k
                               WC_NO_ERR_TRACE(RSA_BUFFER_E));
4308
6.17k
    #endif
4309
#else
4310
            if (outLen < (word32)ret)
4311
                ret = RSA_BUFFER_E;
4312
#endif
4313
6.17k
        }
4314
4315
7.04k
        key->state = RSA_STATE_DECRYPT_RES;
4316
7.04k
        FALL_THROUGH;
4317
7.04k
    #endif /* !WOLFSSL_NO_RSA_SW_PAD */
4318
4319
7.04k
    case RSA_STATE_DECRYPT_RES:
4320
    #if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
4321
            defined(HAVE_CAVIUM)
4322
        if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA &&
4323
                                                   pad_type != WC_RSA_PSS_PAD) {
4324
            ret = key->asyncDev.event.ret;
4325
            if (ret >= 0) {
4326
                /* convert result */
4327
                byte* dataLen = (byte*)&key->dataLen;
4328
                ret = (dataLen[0] << 8) | (dataLen[1]);
4329
4330
                if (outPtr)
4331
                    *outPtr = in;
4332
            }
4333
        }
4334
    #endif
4335
7.04k
        break;
4336
4337
0
    default:
4338
0
        ret = BAD_STATE_E;
4339
0
        break;
4340
7.53k
    }
4341
4342
    /* if async pending then return and skip done cleanup below */
4343
7.53k
    if (ret == WC_NO_ERR_TRACE(WC_PENDING_E)
4344
    #ifdef WC_RSA_NONBLOCK
4345
        || ret == FP_WOULDBLOCK
4346
    #endif
4347
7.53k
    ) {
4348
0
        return ret;
4349
0
    }
4350
4351
7.53k
    key->state = RSA_STATE_NONE;
4352
7.53k
    wc_RsaCleanup(key);
4353
4354
7.53k
    return ret;
4355
7.53k
}
4356
4357
4358
#ifndef WOLFSSL_RSA_VERIFY_ONLY
4359
/* Public RSA Functions */
4360
int wc_RsaPublicEncrypt(const byte* in, word32 inLen, byte* out, word32 outLen,
4361
                                                     RsaKey* key, WC_RNG* rng)
4362
0
{
4363
0
    int ret;
4364
0
    ret = RsaPublicEncryptEx(in, inLen, out, outLen, key,
4365
0
        RSA_PUBLIC_ENCRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD,
4366
0
        WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
4367
0
    return ret;
4368
0
}
4369
4370
4371
#if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_NO_PADDING)
4372
int wc_RsaPublicEncrypt_ex(const byte* in, word32 inLen, byte* out,
4373
                    word32 outLen, RsaKey* key, WC_RNG* rng, int type,
4374
                    enum wc_HashType hash, int mgf, byte* label,
4375
                    word32 labelSz)
4376
538
{
4377
538
    int ret;
4378
538
    ret = RsaPublicEncryptEx(in, inLen, out, outLen, key, RSA_PUBLIC_ENCRYPT,
4379
538
        RSA_BLOCK_TYPE_2, type, hash, mgf, label, labelSz, 0, rng);
4380
538
    return ret;
4381
538
}
4382
#endif /* WC_NO_RSA_OAEP */
4383
#endif
4384
4385
4386
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
4387
int wc_RsaPrivateDecryptInline(byte* in, word32 inLen, byte** out, RsaKey* key)
4388
0
{
4389
0
    WC_RNG* rng;
4390
0
    int ret;
4391
0
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
4392
0
    if (key == NULL) {
4393
0
        return BAD_FUNC_ARG;
4394
0
    }
4395
0
    rng = key->rng;
4396
#else
4397
    rng = NULL;
4398
#endif
4399
0
    ret = RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
4400
0
        RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD,
4401
0
        WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
4402
0
    return ret;
4403
0
}
4404
4405
4406
#ifndef WC_NO_RSA_OAEP
4407
int wc_RsaPrivateDecryptInline_ex(byte* in, word32 inLen, byte** out,
4408
                                  RsaKey* key, int type, enum wc_HashType hash,
4409
                                  int mgf, byte* label, word32 labelSz)
4410
0
{
4411
0
    WC_RNG* rng;
4412
0
    int ret;
4413
0
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
4414
0
    if (key == NULL) {
4415
0
        return BAD_FUNC_ARG;
4416
0
    }
4417
0
    rng = key->rng;
4418
#else
4419
    rng = NULL;
4420
#endif
4421
0
    ret = RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
4422
0
        RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, type, hash,
4423
0
        mgf, label, labelSz, 0, rng);
4424
0
    return ret;
4425
0
}
4426
#endif /* WC_NO_RSA_OAEP */
4427
4428
4429
int wc_RsaPrivateDecrypt(const byte* in, word32 inLen, byte* out,
4430
                                                 word32 outLen, RsaKey* key)
4431
0
{
4432
0
    WC_RNG* rng;
4433
0
    int ret;
4434
0
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
4435
0
    if (key == NULL) {
4436
0
        return BAD_FUNC_ARG;
4437
0
    }
4438
0
    rng = key->rng;
4439
#else
4440
    rng = NULL;
4441
#endif
4442
0
    ret = RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key,
4443
0
        RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, WC_RSA_PKCSV15_PAD,
4444
0
        WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
4445
0
    return ret;
4446
0
}
4447
4448
#if !defined(WC_NO_RSA_OAEP) || defined(WC_RSA_NO_PADDING)
4449
int wc_RsaPrivateDecrypt_ex(const byte* in, word32 inLen, byte* out,
4450
                            word32 outLen, RsaKey* key, int type,
4451
                            enum wc_HashType hash, int mgf, byte* label,
4452
                            word32 labelSz)
4453
0
{
4454
0
    WC_RNG* rng;
4455
0
    int ret;
4456
0
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
4457
0
    if (key == NULL) {
4458
0
        return BAD_FUNC_ARG;
4459
0
    }
4460
0
    rng = key->rng;
4461
#else
4462
    rng = NULL;
4463
#endif
4464
0
    ret = RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key,
4465
0
        RSA_PRIVATE_DECRYPT, RSA_BLOCK_TYPE_2, type, hash, mgf, label,
4466
0
        labelSz, 0, rng);
4467
0
    return ret;
4468
0
}
4469
#endif /* WC_NO_RSA_OAEP || WC_RSA_NO_PADDING */
4470
#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
4471
4472
int wc_RsaSSL_VerifyInline(byte* in, word32 inLen, byte** out, RsaKey* key)
4473
6.42k
{
4474
6.42k
    WC_RNG* rng;
4475
6.42k
    int ret;
4476
6.42k
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
4477
6.42k
    if (key == NULL) {
4478
0
        return BAD_FUNC_ARG;
4479
0
    }
4480
6.42k
    rng = key->rng;
4481
#else
4482
    rng = NULL;
4483
#endif
4484
6.42k
    ret = RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
4485
6.42k
        RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PKCSV15_PAD,
4486
6.42k
        WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
4487
6.42k
    return ret;
4488
6.42k
}
4489
#ifndef WOLFSSL_RSA_VERIFY_INLINE
4490
int wc_RsaSSL_Verify(const byte* in, word32 inLen, byte* out, word32 outLen,
4491
                                                                 RsaKey* key)
4492
292
{
4493
292
    return wc_RsaSSL_Verify_ex(in, inLen, out, outLen, key, WC_RSA_PKCSV15_PAD);
4494
292
}
4495
4496
int  wc_RsaSSL_Verify_ex(const byte* in, word32 inLen, byte* out, word32 outLen,
4497
                         RsaKey* key, int pad_type)
4498
292
{
4499
292
    int ret;
4500
292
    ret = wc_RsaSSL_Verify_ex2(in, inLen, out, outLen, key, pad_type,
4501
292
            WC_HASH_TYPE_NONE);
4502
292
    return ret;
4503
292
}
4504
4505
int  wc_RsaSSL_Verify_ex2(const byte* in, word32 inLen, byte* out, word32 outLen,
4506
                         RsaKey* key, int pad_type, enum wc_HashType hash)
4507
292
{
4508
292
    WC_RNG* rng;
4509
292
    int ret;
4510
4511
292
    if (key == NULL) {
4512
0
        return BAD_FUNC_ARG;
4513
0
    }
4514
4515
292
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
4516
292
    rng = key->rng;
4517
#else
4518
    rng = NULL;
4519
#endif
4520
4521
292
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
4522
292
    ret = RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key,
4523
292
        RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, pad_type,
4524
292
        hash, wc_hash2mgf(hash), NULL, 0, RSA_PSS_SALT_LEN_DEFAULT, rng);
4525
#else
4526
    ret = RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key,
4527
        RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, pad_type,
4528
        hash, wc_hash2mgf(hash), NULL, 0, RSA_PSS_SALT_LEN_DISCOVER, rng);
4529
#endif
4530
292
    return ret;
4531
292
}
4532
#endif
4533
4534
#ifdef WC_RSA_PSS
4535
/* Verify the message signed with RSA-PSS.
4536
 * The input buffer is reused for the output buffer.
4537
 * Salt length is equal to hash length.
4538
 *
4539
 * in     Buffer holding encrypted data.
4540
 * inLen  Length of data in buffer.
4541
 * out    Pointer to address containing the PSS data.
4542
 * hash   Hash algorithm.
4543
 * mgf    Mask generation function.
4544
 * key    Public RSA key.
4545
 * returns the length of the PSS data on success and negative indicates failure.
4546
 */
4547
int wc_RsaPSS_VerifyInline(byte* in, word32 inLen, byte** out,
4548
                           enum wc_HashType hash, int mgf, RsaKey* key)
4549
399
{
4550
399
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
4551
399
    return wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf,
4552
399
                                                 RSA_PSS_SALT_LEN_DEFAULT, key);
4553
#else
4554
    return wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf,
4555
                                                RSA_PSS_SALT_LEN_DISCOVER, key);
4556
#endif
4557
399
}
4558
4559
/* Verify the message signed with RSA-PSS.
4560
 * The input buffer is reused for the output buffer.
4561
 *
4562
 * in       Buffer holding encrypted data.
4563
 * inLen    Length of data in buffer.
4564
 * out      Pointer to address containing the PSS data.
4565
 * hash     Hash algorithm.
4566
 * mgf      Mask generation function.
4567
 * key      Public RSA key.
4568
 * saltLen  Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
4569
 *          length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
4570
 *          indicates salt length is determined from the data.
4571
 * returns the length of the PSS data on success and negative indicates failure.
4572
 */
4573
int wc_RsaPSS_VerifyInline_ex(byte* in, word32 inLen, byte** out,
4574
                              enum wc_HashType hash, int mgf, int saltLen,
4575
                              RsaKey* key)
4576
399
{
4577
399
    WC_RNG* rng;
4578
399
    int ret;
4579
399
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
4580
399
    if (key == NULL) {
4581
0
        return BAD_FUNC_ARG;
4582
0
    }
4583
399
    rng = key->rng;
4584
#else
4585
    rng = NULL;
4586
#endif
4587
399
    ret = RsaPrivateDecryptEx(in, inLen, in, inLen, out, key,
4588
399
        RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD,
4589
399
        hash, mgf, NULL, 0, saltLen, rng);
4590
399
    return ret;
4591
399
}
4592
4593
/* Verify the message signed with RSA-PSS.
4594
 * Salt length is equal to hash length.
4595
 *
4596
 * in     Buffer holding encrypted data.
4597
 * inLen  Length of data in buffer.
4598
 * out    Pointer to address containing the PSS data.
4599
 * hash   Hash algorithm.
4600
 * mgf    Mask generation function.
4601
 * key    Public RSA key.
4602
 * returns the length of the PSS data on success and negative indicates failure.
4603
 */
4604
int wc_RsaPSS_Verify(const byte* in, word32 inLen, byte* out, word32 outLen,
4605
                     enum wc_HashType hash, int mgf, RsaKey* key)
4606
409
{
4607
409
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
4608
409
    return wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf,
4609
409
                                                 RSA_PSS_SALT_LEN_DEFAULT, key);
4610
#else
4611
    return wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash, mgf,
4612
                                                RSA_PSS_SALT_LEN_DISCOVER, key);
4613
#endif
4614
409
}
4615
4616
/* Verify the message signed with RSA-PSS.
4617
 *
4618
 * in       Buffer holding encrypted data.
4619
 * inLen    Length of data in buffer.
4620
 * out      Pointer to address containing the PSS data.
4621
 * hash     Hash algorithm.
4622
 * mgf      Mask generation function.
4623
 * key      Public RSA key.
4624
 * saltLen  Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
4625
 *          length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
4626
 *          indicates salt length is determined from the data.
4627
 * returns the length of the PSS data on success and negative indicates failure.
4628
 */
4629
int wc_RsaPSS_Verify_ex(const byte* in, word32 inLen, byte* out, word32 outLen,
4630
                        enum wc_HashType hash, int mgf, int saltLen,
4631
                        RsaKey* key)
4632
436
{
4633
436
    WC_RNG* rng;
4634
436
    int ret;
4635
436
#if defined(WC_RSA_BLINDING) && !defined(WC_NO_RNG)
4636
436
    if (key == NULL) {
4637
0
        return BAD_FUNC_ARG;
4638
0
    }
4639
436
    rng = key->rng;
4640
#else
4641
    rng = NULL;
4642
#endif
4643
436
    ret = RsaPrivateDecryptEx(in, inLen, out, outLen, NULL, key,
4644
436
        RSA_PUBLIC_DECRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD,
4645
436
        hash, mgf, NULL, 0, saltLen, rng);
4646
436
    return ret;
4647
436
}
4648
4649
4650
/* Checks the PSS data to ensure that the signature matches.
4651
 * Salt length is equal to hash length.
4652
 *
4653
 * in        Hash of the data that is being verified.
4654
 * inSz      Length of hash.
4655
 * sig       Buffer holding PSS data.
4656
 * sigSz     Size of PSS data.
4657
 * hashType  Hash algorithm.
4658
 * returns BAD_PADDING_E when the PSS data is invalid, BAD_FUNC_ARG when
4659
 * NULL is passed in to in or sig or inSz is not the same as the hash
4660
 * algorithm length and 0 on success.
4661
 */
4662
int wc_RsaPSS_CheckPadding(const byte* in, word32 inSz, const byte* sig,
4663
                           word32 sigSz, enum wc_HashType hashType)
4664
175
{
4665
175
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
4666
175
    return wc_RsaPSS_CheckPadding_ex(in, inSz, sig, sigSz, hashType, RSA_PSS_SALT_LEN_DEFAULT, 0);
4667
#else
4668
    return wc_RsaPSS_CheckPadding_ex(in, inSz, sig, sigSz, hashType, RSA_PSS_SALT_LEN_DISCOVER, 0);
4669
#endif
4670
175
}
4671
4672
/* Checks the PSS data to ensure that the signature matches.
4673
 *
4674
 * in        Hash of the data that is being verified.
4675
 * inSz      Length of hash.
4676
 * sig       Buffer holding PSS data.
4677
 * sigSz     Size of PSS data.
4678
 * hashType  Hash algorithm.
4679
 * saltLen   Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
4680
 *           length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
4681
 *           indicates salt length is determined from the data.
4682
 * bits      Can be used to calculate salt size in FIPS case
4683
 * returns BAD_PADDING_E when the PSS data is invalid, BAD_FUNC_ARG when
4684
 * NULL is passed in to in or sig or inSz is not the same as the hash
4685
 * algorithm length and 0 on success.
4686
 */
4687
int wc_RsaPSS_CheckPadding_ex2(const byte* in, word32 inSz, const byte* sig,
4688
                               word32 sigSz, enum wc_HashType hashType,
4689
                               int saltLen, int bits, void* heap)
4690
576
{
4691
576
    int ret = 0;
4692
576
    byte sigCheckBuf[WC_MAX_DIGEST_SIZE*2 + RSA_PSS_PAD_SZ];
4693
576
    byte *sigCheck = sigCheckBuf;
4694
576
    int digSz;
4695
576
    (void)bits;
4696
4697
576
    digSz = wc_HashGetDigestSize(hashType);
4698
4699
576
    if (in == NULL || sig == NULL || digSz < 0 || inSz != (word32)digSz) {
4700
25
        ret = BAD_FUNC_ARG;
4701
25
    }
4702
4703
576
    if (ret == 0) {
4704
551
        if (saltLen == RSA_PSS_SALT_LEN_DEFAULT) {
4705
549
            saltLen = (int)inSz;
4706
549
            #ifdef WOLFSSL_SHA512
4707
                /* See FIPS 186-4 section 5.5 item (e). */
4708
549
                if (bits == 1024 && inSz == WC_SHA512_DIGEST_SIZE) {
4709
0
                    saltLen = RSA_PSS_SALT_MAX_SZ;
4710
0
                }
4711
549
            #endif
4712
549
        }
4713
/* Same salt limit; here inSz is the hash length.  FIPS 186-5 sec 5.4(g). */
4714
#if !defined(WOLFSSL_PSS_LONG_SALT) || FIPS_VERSION3_GE(7,0,0)
4715
        else if (saltLen > (int)inSz) {
4716
            ret = PSS_SALTLEN_E;
4717
        }
4718
#endif
4719
2
#ifndef WOLFSSL_PSS_SALT_LEN_DISCOVER
4720
2
        else if (saltLen < RSA_PSS_SALT_LEN_DEFAULT) {
4721
0
            ret = PSS_SALTLEN_E;
4722
0
        }
4723
#else
4724
        else if (saltLen == RSA_PSS_SALT_LEN_DISCOVER) {
4725
            saltLen = sigSz - inSz;
4726
            /* Same cap on the discovered length; inSz is the hash length. */
4727
            if ((saltLen < 0)
4728
        #if FIPS_VERSION3_GE(7,0,0)
4729
                    || (saltLen > (int)inSz)
4730
        #endif
4731
                    ) {
4732
                ret = PSS_SALTLEN_E;
4733
            }
4734
        }
4735
        else if (saltLen < RSA_PSS_SALT_LEN_DISCOVER) {
4736
            ret = PSS_SALTLEN_E;
4737
        }
4738
#endif
4739
551
    }
4740
4741
    /* Sig = Salt | Exp Hash */
4742
576
    if (ret == 0) {
4743
551
        word32 totalSz = 0;
4744
551
        if ((WC_SAFE_SUM_WORD32(inSz, (word32)saltLen, totalSz) == 0) ||
4745
551
            (sigSz != totalSz))
4746
34
        {
4747
34
            ret = PSS_SALTLEN_E;
4748
34
        }
4749
551
    }
4750
4751
576
#ifdef WOLFSSL_PSS_LONG_SALT
4752
    /* if long salt is larger then default maximum buffer then allocate a buffer */
4753
576
    if ((ret == 0) &&
4754
517
            (sizeof(sigCheckBuf) < (RSA_PSS_PAD_SZ + inSz + (word32)saltLen))) {
4755
0
        sigCheck = (byte*)XMALLOC(
4756
0
                              (size_t)(RSA_PSS_PAD_SZ + inSz + (word32)saltLen),
4757
0
                              heap, DYNAMIC_TYPE_RSA_BUFFER);
4758
0
        if (sigCheck == NULL) {
4759
0
            ret = MEMORY_E;
4760
0
        }
4761
0
    }
4762
#else
4763
    if (ret == 0 && sizeof(sigCheckBuf) < (RSA_PSS_PAD_SZ + inSz + (word32)saltLen)) {
4764
        ret = BUFFER_E;
4765
    }
4766
#endif
4767
4768
    /* Exp Hash = HASH(8 * 0x00 | Message Hash | Salt) */
4769
576
    if (ret == 0) {
4770
517
        XMEMSET(sigCheck, 0, RSA_PSS_PAD_SZ);
4771
517
        XMEMCPY(sigCheck + RSA_PSS_PAD_SZ, in, inSz);
4772
517
        XMEMCPY(sigCheck + RSA_PSS_PAD_SZ + inSz, sig, (size_t)saltLen);
4773
517
        ret = wc_Hash(hashType, sigCheck, RSA_PSS_PAD_SZ + inSz + (word32)saltLen,
4774
517
                      sigCheck, inSz);
4775
517
    }
4776
576
    if (ret == 0) {
4777
516
        if (XMEMCMP(sigCheck, sig + saltLen, inSz) != 0) {
4778
116
            WOLFSSL_MSG("RsaPSS_CheckPadding: Padding Error");
4779
116
            ret = BAD_PADDING_E;
4780
116
        }
4781
516
    }
4782
4783
576
#ifdef WOLFSSL_PSS_LONG_SALT
4784
576
    if (sigCheck != NULL && sigCheck != sigCheckBuf) {
4785
0
        XFREE(sigCheck, heap, DYNAMIC_TYPE_RSA_BUFFER);
4786
0
    }
4787
576
#endif
4788
4789
576
    (void)heap; /* unused if memory is disabled */
4790
576
    return ret;
4791
576
}
4792
int wc_RsaPSS_CheckPadding_ex(const byte* in, word32 inSz, const byte* sig,
4793
                               word32 sigSz, enum wc_HashType hashType,
4794
                               int saltLen, int bits)
4795
576
{
4796
576
    return wc_RsaPSS_CheckPadding_ex2(in, inSz, sig, sigSz, hashType, saltLen,
4797
576
        bits, NULL);
4798
576
}
4799
4800
4801
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD)
4802
/* Let a device verify an RSA-PSS signature and its padding in one shot (it gets
4803
 * the digest, which the RsaPad path does not). Shared by the two verify and
4804
 * check entry points below.
4805
 *
4806
 * out       Buffer the device may write the recovered PSS block into.
4807
 * outSz     Size of that buffer.
4808
 * recovered Set to the number of bytes the device wrote, 0 for a verdict only.
4809
 * returns the length the caller should report, a negative error, or
4810
 * CRYPTOCB_UNAVAILABLE when no device handled it.
4811
 */
4812
static int RsaPssVerifyDevice(const byte* in, word32 inLen, const byte* digest,
4813
    word32 digestLen, enum wc_HashType hash, int mgf, int saltLen, int hLen,
4814
    RsaKey* key, byte* out, word32 outSz, word32* recovered)
4815
{
4816
    int    ret;
4817
    int    res = 0;
4818
    word32 recSz = 0;
4819
4820
    *recovered = 0;
4821
4822
#ifndef WOLF_CRYPTO_CB_FIND
4823
    if (key == NULL || key->devId == INVALID_DEVID)
4824
#else
4825
    if (key == NULL)
4826
#endif
4827
    {
4828
        return WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE);
4829
    }
4830
4831
    ret = wc_CryptoCb_RsaPssVerify(in, inLen, digest, digestLen, hash, mgf,
4832
                                   saltLen, key, &res, out, outSz, &recSz);
4833
    if (ret == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
4834
        return ret;
4835
    }
4836
    if (ret > 0) {
4837
        /* A handler returns 0 with res set, or a negative error. */
4838
        return SIG_VERIFY_E;
4839
    }
4840
    if (ret != 0) {
4841
        return ret;
4842
    }
4843
    if (recSz > outSz) {
4844
        recSz = 0;
4845
    }
4846
    if (res == 0) {
4847
        return SIG_VERIFY_E;
4848
    }
4849
    if (recSz > 0) {
4850
        *recovered = recSz;
4851
        return (int)recSz;
4852
    }
4853
    if (outSz < (word32)(saltLen + hLen)) {
4854
        return RSA_BUFFER_E;
4855
    }
4856
    return saltLen + hLen;
4857
}
4858
#endif
4859
4860
4861
/* Verify the message signed with RSA-PSS.
4862
 * The input buffer is reused for the output buffer.
4863
 * Salt length is equal to hash length.
4864
 *
4865
 * in     Buffer holding encrypted data.
4866
 * inLen  Length of data in buffer.
4867
 * out    Pointer to address containing the PSS data.
4868
 * digest Hash of the data that is being verified.
4869
 * digestLen Length of hash.
4870
 * hash   Hash algorithm.
4871
 * mgf    Mask generation function.
4872
 * key    Public RSA key.
4873
 * returns the length of the PSS data on success and negative indicates failure.
4874
 *
4875
 * Note: a device that recovers nothing sets *out to NULL, so check *out first.
4876
 */
4877
int wc_RsaPSS_VerifyCheckInline(byte* in, word32 inLen, byte** out,
4878
                           const byte* digest, word32 digestLen,
4879
                           enum wc_HashType hash, int mgf, RsaKey* key)
4880
0
{
4881
0
    int ret = 0, verify, saltLen, hLen, bits = 0;
4882
#ifdef WOLFSSL_MICROCHIP_TA100
4883
    if (key != NULL && key->uKeyH != 0) {
4884
        int verified = 0;
4885
        ret = wc_Microchip_rsa_verify(digest, digestLen, in, inLen, key,
4886
                                      &verified);
4887
        if (ret != 0) {
4888
            return ret;
4889
        }
4890
        return verified ? (int)inLen : SIG_VERIFY_E;
4891
    }
4892
#endif
4893
4894
0
    hLen = wc_HashGetDigestSize(hash);
4895
0
    if (hLen < 0)
4896
0
        return BAD_FUNC_ARG;
4897
0
    if ((word32)hLen != digestLen)
4898
0
        return BAD_FUNC_ARG;
4899
4900
0
    saltLen = hLen;
4901
0
    #ifdef WOLFSSL_SHA512
4902
0
        if (key == NULL) {
4903
0
            return BAD_FUNC_ARG;
4904
0
        }
4905
        /* See FIPS 186-4 section 5.5 item (e). */
4906
0
        bits = RsaModulusBits(key);
4907
0
        if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE)
4908
0
            saltLen = RSA_PSS_SALT_MAX_SZ;
4909
0
    #endif
4910
4911
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD)
4912
    {
4913
        word32 recovered = 0;
4914
4915
        ret = RsaPssVerifyDevice(in, inLen, digest, digestLen, hash, mgf,
4916
                                 saltLen, hLen, key, in, inLen, &recovered);
4917
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
4918
            if ((ret > 0) && (out != NULL)) {
4919
                if (recovered > 0) {
4920
                    *out = in;
4921
                }
4922
                else {
4923
                    /* Device reported a verdict only; nothing to expose. */
4924
                    *out = NULL;
4925
                }
4926
            }
4927
            return ret;
4928
        }
4929
        ret = 0;
4930
    }
4931
#endif
4932
4933
0
    verify = wc_RsaPSS_VerifyInline_ex(in, inLen, out, hash, mgf, saltLen, key);
4934
0
    if (verify > 0)
4935
0
        ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, *out, (word32)verify,
4936
0
                                        hash, saltLen, bits);
4937
0
    if (ret == 0)
4938
0
        ret = verify;
4939
4940
0
    return ret;
4941
0
}
4942
4943
4944
/* Verify the message signed with RSA-PSS.
4945
 * Salt length is equal to hash length.
4946
 *
4947
 * in     Buffer holding encrypted data.
4948
 * inLen  Length of data in buffer.
4949
 * out    Pointer to address containing the PSS data.
4950
 * outLen Length of the output.
4951
 * digest Hash of the data that is being verified.
4952
 * digestLen Length of hash.
4953
 * hash   Hash algorithm.
4954
 * mgf    Mask generation function.
4955
 * key    Public RSA key.
4956
 * returns the length of the PSS data on success and negative indicates failure.
4957
 */
4958
int wc_RsaPSS_VerifyCheck(const byte* in, word32 inLen, byte* out, word32 outLen,
4959
                          const byte* digest, word32 digestLen,
4960
                          enum wc_HashType hash, int mgf,
4961
                          RsaKey* key)
4962
36
{
4963
36
    int ret = 0, verify, saltLen, hLen, bits = 0;
4964
#ifdef WOLFSSL_MICROCHIP_TA100
4965
    if (key != NULL && key->uKeyH != 0) {
4966
        int verified = 0;
4967
        ret = wc_Microchip_rsa_verify(digest, digestLen, (byte*)in, inLen,
4968
                                      key, &verified);
4969
        if (ret != 0) {
4970
            return ret;
4971
        }
4972
        return verified ? (int)inLen : SIG_VERIFY_E;
4973
    }
4974
#endif
4975
4976
36
    hLen = wc_HashGetDigestSize(hash);
4977
36
    if (hLen < 0)
4978
1
        return hLen;
4979
35
    if ((word32)hLen != digestLen)
4980
8
        return BAD_FUNC_ARG;
4981
4982
27
    saltLen = hLen;
4983
27
    #ifdef WOLFSSL_SHA512
4984
27
        if (key == NULL) {
4985
0
            return BAD_FUNC_ARG;
4986
0
        }
4987
        /* See FIPS 186-4 section 5.5 item (e). */
4988
27
        bits = RsaModulusBits(key);
4989
27
        if (bits == 1024 && hLen == WC_SHA512_DIGEST_SIZE)
4990
4
            saltLen = RSA_PSS_SALT_MAX_SZ;
4991
27
    #endif
4992
4993
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_RSA_PAD)
4994
    {
4995
        word32 recovered = 0;
4996
4997
        ret = RsaPssVerifyDevice(in, inLen, digest, digestLen, hash, mgf,
4998
                                 saltLen, hLen, key, out, outLen, &recovered);
4999
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
5000
            if ((ret > 0) && (recovered == 0) && (out != NULL)) {
5001
                /* Device gave a verdict only; leave no stale data behind. */
5002
                XMEMSET(out, 0, (word32)ret);
5003
            }
5004
            return ret;
5005
        }
5006
        ret = 0;
5007
    }
5008
#endif
5009
5010
27
    verify = wc_RsaPSS_Verify_ex(in, inLen, out, outLen, hash,
5011
27
                                 mgf, saltLen, key);
5012
27
    if (verify > 0)
5013
2
        ret = wc_RsaPSS_CheckPadding_ex(digest, digestLen, out, (word32)verify,
5014
2
                                        hash, saltLen, bits);
5015
27
    if (ret == 0)
5016
25
        ret = verify;
5017
5018
27
    return ret;
5019
27
}
5020
5021
#endif
5022
5023
#if !defined(WOLFSSL_RSA_PUBLIC_ONLY) && !defined(WOLFSSL_RSA_VERIFY_ONLY)
5024
int wc_RsaSSL_Sign(const byte* in, word32 inLen, byte* out, word32 outLen,
5025
                                                   RsaKey* key, WC_RNG* rng)
5026
6.94k
{
5027
6.94k
    int ret;
5028
6.94k
    ret = RsaPublicEncryptEx(in, inLen, out, outLen, key,
5029
6.94k
        RSA_PRIVATE_ENCRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PKCSV15_PAD,
5030
6.94k
        WC_HASH_TYPE_NONE, WC_MGF1NONE, NULL, 0, 0, rng);
5031
6.94k
    return ret;
5032
6.94k
}
5033
5034
#ifdef WC_RSA_PSS
5035
/* Sign the hash of a message using RSA-PSS.
5036
 * Salt length is equal to hash length.
5037
 *
5038
 * in      Buffer holding hash of message.
5039
 * inLen   Length of data in buffer (hash length).
5040
 * out     Buffer to write encrypted signature into.
5041
 * outLen  Size of buffer to write to.
5042
 * hash    Hash algorithm.
5043
 * mgf     Mask generation function.
5044
 * key     Public RSA key.
5045
 * rng     Random number generator.
5046
 * returns the length of the encrypted signature on success, a negative value
5047
 * indicates failure.
5048
 */
5049
int wc_RsaPSS_Sign(const byte* in, word32 inLen, byte* out, word32 outLen,
5050
                       enum wc_HashType hash, int mgf, RsaKey* key, WC_RNG* rng)
5051
520
{
5052
520
    return wc_RsaPSS_Sign_ex(in, inLen, out, outLen, hash, mgf,
5053
520
                                            RSA_PSS_SALT_LEN_DEFAULT, key, rng);
5054
520
}
5055
5056
/* Sign the hash of a message using RSA-PSS.
5057
 *
5058
 * in       Buffer holding hash of message.
5059
 * inLen    Length of data in buffer (hash length).
5060
 * out      Buffer to write encrypted signature into.
5061
 * outLen   Size of buffer to write to.
5062
 * hash     Hash algorithm.
5063
 * mgf      Mask generation function.
5064
 * saltLen  Length of salt used. RSA_PSS_SALT_LEN_DEFAULT (-1) indicates salt
5065
 *          length is the same as the hash length. RSA_PSS_SALT_LEN_DISCOVER
5066
 *          indicates salt length is determined from the data.
5067
 * key      Public RSA key.
5068
 * rng      Random number generator.
5069
 * returns the length of the encrypted signature on success, a negative value
5070
 * indicates failure.
5071
 */
5072
int wc_RsaPSS_Sign_ex(const byte* in, word32 inLen, byte* out, word32 outLen,
5073
                      enum wc_HashType hash, int mgf, int saltLen, RsaKey* key,
5074
                      WC_RNG* rng)
5075
520
{
5076
520
    int ret;
5077
520
    ret = RsaPublicEncryptEx(in, inLen, out, outLen, key,
5078
520
        RSA_PRIVATE_ENCRYPT, RSA_BLOCK_TYPE_1, WC_RSA_PSS_PAD,
5079
520
        hash, mgf, NULL, 0, saltLen, rng);
5080
520
    return ret;
5081
520
}
5082
#endif
5083
#endif
5084
5085
int wc_RsaEncryptSize(const RsaKey* key)
5086
29.0k
{
5087
29.0k
    int ret;
5088
5089
29.0k
    if (key == NULL) {
5090
0
        return BAD_FUNC_ARG;
5091
0
    }
5092
5093
29.0k
    ret = mp_unsigned_bin_size(&key->n);
5094
5095
#if defined(WOLFSSL_MICROCHIP_TA100)
5096
    if (ret == 0 && (key->rKeyH != 0 || key->uKeyH != 0)) {
5097
        ret = 2048 / 8;
5098
    }
5099
#endif
5100
5101
29.0k
#ifdef WOLF_CRYPTO_CB
5102
29.0k
    if (ret == 0 && key->devId != INVALID_DEVID) {
5103
0
        if (wc_CryptoCb_RsaGetSize(key, &ret) == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
5104
0
            ret = 2048/8; /* hardware handles, use 2048-bit as default */
5105
0
        }
5106
0
    }
5107
29.0k
#endif
5108
5109
29.0k
    return ret;
5110
29.0k
}
5111
5112
#ifndef WOLFSSL_RSA_VERIFY_ONLY
5113
/* Software-only export of RSA public key elements from RsaKey.
5114
 * This internal helper avoids recursion when called from the EXPORT_KEY path. */
5115
static int _RsaFlattenPublicKey(const RsaKey* key, byte* e, word32* eSz,
5116
                                byte* n, word32* nSz)
5117
0
{
5118
0
    int sz, ret;
5119
5120
0
    if (key == NULL || e == NULL || eSz == NULL || n == NULL || nSz == NULL) {
5121
0
        return BAD_FUNC_ARG;
5122
0
    }
5123
5124
0
    sz = mp_unsigned_bin_size(&key->e);
5125
0
    if ((word32)sz > *eSz) {
5126
0
        return RSA_BUFFER_E;
5127
0
    }
5128
0
    ret = mp_to_unsigned_bin(&key->e, e);
5129
0
    if (ret != MP_OKAY) {
5130
0
        return ret;
5131
0
    }
5132
0
    *eSz = (word32)sz;
5133
5134
0
    sz = wc_RsaEncryptSize(key);
5135
0
    if ((word32)sz > *nSz) {
5136
0
        return RSA_BUFFER_E;
5137
0
    }
5138
0
    ret = mp_to_unsigned_bin(&key->n, n);
5139
0
    if (ret != MP_OKAY) {
5140
0
        return ret;
5141
0
    }
5142
0
    *nSz = (word32)sz;
5143
5144
0
    return 0;
5145
0
}
5146
5147
/* flatten RsaKey structure into individual elements (e, n) */
5148
int wc_RsaFlattenPublicKey(const RsaKey* key, byte* e, word32* eSz, byte* n,
5149
                                                                   word32* nSz)
5150
0
{
5151
0
    if (key == NULL || e == NULL || eSz == NULL || n == NULL || nSz == NULL) {
5152
0
        return BAD_FUNC_ARG;
5153
0
    }
5154
5155
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_EXPORT_KEY)
5156
#ifndef WOLF_CRYPTO_CB_FIND
5157
    if (key->devId != INVALID_DEVID)
5158
#endif
5159
    {
5160
        int ret;
5161
        WC_DECLARE_VAR(tmpKey, RsaKey, 1, NULL);
5162
5163
        WC_ALLOC_VAR(tmpKey, RsaKey, 1, key->heap);
5164
        if (!WC_VAR_OK(tmpKey)) {
5165
            return MEMORY_E;
5166
        }
5167
        XMEMSET(tmpKey, 0, sizeof(RsaKey));
5168
5169
        ret = wc_InitRsaKey_ex(tmpKey, key->heap, INVALID_DEVID);
5170
        if (ret != 0) {
5171
            WC_FREE_VAR(tmpKey, key->heap);
5172
            return ret;
5173
        }
5174
5175
        ret = wc_CryptoCb_ExportKey(key->devId, WC_PK_TYPE_RSA,
5176
                                     key, tmpKey);
5177
        if (ret == 0) {
5178
            /* Call software helper (no callback recursion) */
5179
            ret = _RsaFlattenPublicKey(tmpKey, e, eSz, n, nSz);
5180
        }
5181
        /* wc_FreeRsaKey calls mp_forcezero on all private key components,
5182
         * so no separate ForceZero of the struct is needed here. Calling
5183
         * ForceZero before wc_FreeRsaKey would zero the mp_int metadata
5184
         * and cause a crash. */
5185
        wc_FreeRsaKey(tmpKey);
5186
        WC_FREE_VAR(tmpKey, key->heap);
5187
        if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
5188
            return ret;
5189
        }
5190
        /* fall through to software */
5191
    }
5192
#endif /* WOLF_CRYPTO_CB && WOLF_CRYPTO_CB_EXPORT_KEY */
5193
5194
0
    return _RsaFlattenPublicKey(key, e, eSz, n, nSz);
5195
0
}
5196
#endif
5197
5198
#ifndef WOLFSSL_RSA_VERIFY_ONLY
5199
static int RsaGetValue(const mp_int* in, byte* out, word32* outSz)
5200
0
{
5201
0
    word32 sz;
5202
0
    int ret = 0;
5203
5204
    /* Parameters ensured by calling function. */
5205
5206
0
    sz = (word32)mp_unsigned_bin_size(in);
5207
0
    if (sz > *outSz)
5208
0
        ret = RSA_BUFFER_E;
5209
5210
0
    if (ret == 0)
5211
0
        ret = mp_to_unsigned_bin(in, out);
5212
5213
0
    if (ret == MP_OKAY)
5214
0
        *outSz = sz;
5215
5216
0
    return ret;
5217
0
}
5218
5219
5220
/* Software-only export of RSA key elements from RsaKey.
5221
 * This internal helper avoids recursion when called from the EXPORT_KEY path. */
5222
static int _RsaExportKey(const RsaKey* key,
5223
                         byte* e, word32* eSz, byte* n, word32* nSz,
5224
                         byte* d, word32* dSz, byte* p, word32* pSz,
5225
                         byte* q, word32* qSz)
5226
0
{
5227
0
    int ret = 0;
5228
5229
0
    if (key == NULL || e == NULL || eSz == NULL || n == NULL || nSz == NULL
5230
0
            || d == NULL || dSz == NULL || p == NULL || pSz == NULL
5231
0
            || q == NULL || qSz == NULL) {
5232
0
        return BAD_FUNC_ARG;
5233
0
    }
5234
5235
0
    if (ret == 0) {
5236
0
        ret = RsaGetValue(&key->e, e, eSz);
5237
0
    }
5238
0
    if (ret == 0) {
5239
0
        ret = RsaGetValue(&key->n, n, nSz);
5240
0
    }
5241
0
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
5242
0
    if (ret == 0) {
5243
0
        ret = RsaGetValue(&key->d, d, dSz);
5244
0
    }
5245
0
    if (ret == 0) {
5246
0
        ret = RsaGetValue(&key->p, p, pSz);
5247
0
    }
5248
0
    if (ret == 0) {
5249
0
        ret = RsaGetValue(&key->q, q, qSz);
5250
0
    }
5251
#else
5252
    /* no private parts to key */
5253
    if (d == NULL || p == NULL || q == NULL || dSz == NULL || pSz == NULL
5254
            || qSz == NULL) {
5255
        ret = BAD_FUNC_ARG;
5256
    }
5257
    else {
5258
        *dSz = 0;
5259
        *pSz = 0;
5260
        *qSz = 0;
5261
    }
5262
#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
5263
5264
0
    return ret;
5265
0
}
5266
5267
int wc_RsaExportKey(const RsaKey* key,
5268
                    byte* e, word32* eSz, byte* n, word32* nSz,
5269
                    byte* d, word32* dSz, byte* p, word32* pSz,
5270
                    byte* q, word32* qSz)
5271
0
{
5272
0
    int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
5273
5274
0
    if (key && e && eSz && n && nSz && d && dSz && p && pSz && q && qSz) {
5275
0
        ret = 0;
5276
0
    }
5277
5278
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_EXPORT_KEY)
5279
    if (ret == 0) {
5280
    #ifndef WOLF_CRYPTO_CB_FIND
5281
        if (key->devId != INVALID_DEVID)
5282
    #endif
5283
        {
5284
            WC_DECLARE_VAR(tmpKey, RsaKey, 1, NULL);
5285
5286
            WC_ALLOC_VAR(tmpKey, RsaKey, 1, key->heap);
5287
            if (!WC_VAR_OK(tmpKey)) {
5288
                return MEMORY_E;
5289
            }
5290
            XMEMSET(tmpKey, 0, sizeof(RsaKey));
5291
5292
            ret = wc_InitRsaKey_ex(tmpKey, key->heap, INVALID_DEVID);
5293
            if (ret != 0) {
5294
                WC_FREE_VAR(tmpKey, key->heap);
5295
                return ret;
5296
            }
5297
5298
            ret = wc_CryptoCb_ExportKey(key->devId, WC_PK_TYPE_RSA,
5299
                                         key, tmpKey);
5300
            if (ret == 0) {
5301
                /* Call software helper (no callback recursion) */
5302
                ret = _RsaExportKey(tmpKey, e, eSz, n, nSz,
5303
                                    d, dSz, p, pSz, q, qSz);
5304
            }
5305
            /* wc_FreeRsaKey calls mp_forcezero on all private key components,
5306
             * so no separate ForceZero of the struct is needed here. */
5307
            wc_FreeRsaKey(tmpKey);
5308
            WC_FREE_VAR(tmpKey, key->heap);
5309
            if (ret != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
5310
                return ret;
5311
            }
5312
            ret = 0; /* fall through to software */
5313
        }
5314
    }
5315
#endif /* WOLF_CRYPTO_CB && WOLF_CRYPTO_CB_EXPORT_KEY */
5316
5317
0
    if (ret == 0) {
5318
0
        ret = _RsaExportKey(key, e, eSz, n, nSz, d, dSz, p, pSz, q, qSz);
5319
0
    }
5320
5321
0
    return ret;
5322
0
}
5323
#endif
5324
5325
5326
#if defined(WOLFSSL_KEY_GEN) && !defined(WOLFSSL_RSA_PUBLIC_ONLY)
5327
5328
#ifndef WOLFSSL_NO_RSA_SW
5329
/* Check that |p-q| > 2^((size/2)-100) */
5330
static int wc_CompareDiffPQ(mp_int* p, mp_int* q, int size, int* valid)
5331
0
{
5332
0
#ifdef WOLFSSL_SMALL_STACK
5333
0
    mp_int *c = NULL, *d = NULL;
5334
#else
5335
    mp_int c[1], d[1];
5336
#endif
5337
0
    int ret;
5338
5339
0
    if (p == NULL || q == NULL)
5340
0
        return BAD_FUNC_ARG;
5341
5342
0
#ifdef WOLFSSL_SMALL_STACK
5343
0
    if (((c = (mp_int *)XMALLOC(sizeof(*c), NULL, DYNAMIC_TYPE_WOLF_BIGINT)) == NULL) ||
5344
0
        ((d = (mp_int *)XMALLOC(sizeof(*d), NULL, DYNAMIC_TYPE_WOLF_BIGINT)) == NULL)) {
5345
        /* mp_init_multi() below is skipped, so nothing was initialized: free
5346
         * what was allocated here and NULL the pointers. The cleanup at the
5347
         * end must not see an allocated-but-uninitialized mp_int - clearing
5348
         * one reads a garbage used/size and corrupts the heap. */
5349
0
        XFREE(c, NULL, DYNAMIC_TYPE_WOLF_BIGINT);
5350
0
        XFREE(d, NULL, DYNAMIC_TYPE_WOLF_BIGINT);
5351
0
        c = NULL;
5352
0
        d = NULL;
5353
0
        ret = MEMORY_E;
5354
0
    }
5355
0
    else
5356
0
        ret = 0;
5357
5358
0
    if (ret == 0)
5359
0
#endif
5360
0
        ret = mp_init_multi(c, d, NULL, NULL, NULL, NULL);
5361
5362
    /* c = 2^((size/2)-100) */
5363
0
    if (ret == 0)
5364
0
        ret = mp_2expt(c, (size/2)-100);
5365
5366
    /* d = |p-q| */
5367
0
    if (ret == 0)
5368
0
        ret = mp_sub(p, q, d);
5369
5370
#ifdef WOLFSSL_CHECK_MEM_ZERO
5371
    if (ret == 0)
5372
        mp_memzero_add("Compare PQ d", d);
5373
#endif
5374
5375
#if !defined(WOLFSSL_SP_MATH) && (!defined(WOLFSSL_SP_MATH_ALL) || \
5376
                                               defined(WOLFSSL_SP_INT_NEGATIVE))
5377
    if (ret == 0)
5378
        ret = mp_abs(d, d);
5379
#endif
5380
5381
    /* compare */
5382
0
    if (ret == 0)
5383
0
        *valid = (mp_cmp(d, c) == MP_GT);
5384
5385
0
#ifdef WOLFSSL_SMALL_STACK
5386
0
    if (d != NULL) {
5387
0
        mp_forcezero(d);
5388
0
        XFREE(d, NULL, DYNAMIC_TYPE_WOLF_BIGINT);
5389
0
    }
5390
0
    if (c != NULL) {
5391
0
        mp_clear(c);
5392
0
        XFREE(c, NULL, DYNAMIC_TYPE_WOLF_BIGINT);
5393
0
    }
5394
#else
5395
    mp_forcezero(d);
5396
    mp_clear(c);
5397
#ifdef WOLFSSL_CHECK_MEM_ZERO
5398
    mp_memzero_check(d);
5399
#endif
5400
#endif
5401
5402
0
    return ret;
5403
0
}
5404
5405
5406
/* The lower_bound value is floor(2^(0.5) * 2^((nlen/2)-1)) where nlen is 4096.
5407
 * This number was calculated using a small test tool written with a common
5408
 * large number math library. Other values of nlen may be checked with a subset
5409
 * of lower_bound. */
5410
static const byte lower_bound[] = {
5411
    0xB5, 0x04, 0xF3, 0x33, 0xF9, 0xDE, 0x64, 0x84,
5412
    0x59, 0x7D, 0x89, 0xB3, 0x75, 0x4A, 0xBE, 0x9F,
5413
    0x1D, 0x6F, 0x60, 0xBA, 0x89, 0x3B, 0xA8, 0x4C,
5414
    0xED, 0x17, 0xAC, 0x85, 0x83, 0x33, 0x99, 0x15,
5415
/* 512 */
5416
    0x4A, 0xFC, 0x83, 0x04, 0x3A, 0xB8, 0xA2, 0xC3,
5417
    0xA8, 0xB1, 0xFE, 0x6F, 0xDC, 0x83, 0xDB, 0x39,
5418
    0x0F, 0x74, 0xA8, 0x5E, 0x43, 0x9C, 0x7B, 0x4A,
5419
    0x78, 0x04, 0x87, 0x36, 0x3D, 0xFA, 0x27, 0x68,
5420
/* 1024 */
5421
    0xD2, 0x20, 0x2E, 0x87, 0x42, 0xAF, 0x1F, 0x4E,
5422
    0x53, 0x05, 0x9C, 0x60, 0x11, 0xBC, 0x33, 0x7B,
5423
    0xCA, 0xB1, 0xBC, 0x91, 0x16, 0x88, 0x45, 0x8A,
5424
    0x46, 0x0A, 0xBC, 0x72, 0x2F, 0x7C, 0x4E, 0x33,
5425
    0xC6, 0xD5, 0xA8, 0xA3, 0x8B, 0xB7, 0xE9, 0xDC,
5426
    0xCB, 0x2A, 0x63, 0x43, 0x31, 0xF3, 0xC8, 0x4D,
5427
    0xF5, 0x2F, 0x12, 0x0F, 0x83, 0x6E, 0x58, 0x2E,
5428
    0xEA, 0xA4, 0xA0, 0x89, 0x90, 0x40, 0xCA, 0x4A,
5429
/* 2048 */
5430
    0x81, 0x39, 0x4A, 0xB6, 0xD8, 0xFD, 0x0E, 0xFD,
5431
    0xF4, 0xD3, 0xA0, 0x2C, 0xEB, 0xC9, 0x3E, 0x0C,
5432
    0x42, 0x64, 0xDA, 0xBC, 0xD5, 0x28, 0xB6, 0x51,
5433
    0xB8, 0xCF, 0x34, 0x1B, 0x6F, 0x82, 0x36, 0xC7,
5434
    0x01, 0x04, 0xDC, 0x01, 0xFE, 0x32, 0x35, 0x2F,
5435
    0x33, 0x2A, 0x5E, 0x9F, 0x7B, 0xDA, 0x1E, 0xBF,
5436
    0xF6, 0xA1, 0xBE, 0x3F, 0xCA, 0x22, 0x13, 0x07,
5437
    0xDE, 0xA0, 0x62, 0x41, 0xF7, 0xAA, 0x81, 0xC2,
5438
/* 3072 */
5439
    0xC1, 0xFC, 0xBD, 0xDE, 0xA2, 0xF7, 0xDC, 0x33,
5440
    0x18, 0x83, 0x8A, 0x2E, 0xAF, 0xF5, 0xF3, 0xB2,
5441
    0xD2, 0x4F, 0x4A, 0x76, 0x3F, 0xAC, 0xB8, 0x82,
5442
    0xFD, 0xFE, 0x17, 0x0F, 0xD3, 0xB1, 0xF7, 0x80,
5443
    0xF9, 0xAC, 0xCE, 0x41, 0x79, 0x7F, 0x28, 0x05,
5444
    0xC2, 0x46, 0x78, 0x5E, 0x92, 0x95, 0x70, 0x23,
5445
    0x5F, 0xCF, 0x8F, 0x7B, 0xCA, 0x3E, 0xA3, 0x3B,
5446
    0x4D, 0x7C, 0x60, 0xA5, 0xE6, 0x33, 0xE3, 0xE1
5447
/* 4096 */
5448
};
5449
#endif /* !WOLFSSL_NO_RSA_SW */
5450
5451
5452
/* returns 1 on key size ok and 0 if not ok */
5453
static WC_INLINE int RsaSizeCheck(int size)
5454
0
{
5455
0
    if (size < RSA_MIN_SIZE || size > RSA_MAX_SIZE) {
5456
0
        return 0;
5457
0
    }
5458
5459
#if FIPS_VERSION3_GE(7,0,0)
5460
    /* Only the sizes this module is validated for.  The standards set a
5461
     * floor, not a list: at least 2048 bits and even (FIPS 186-5 sec 5.1),
5462
     * with less disallowed for signing (SP 800-131Ar2 Table 2).  These three
5463
     * are what wolfSSL holds CAVP certificates for, so this is stricter. */
5464
    switch (size) {
5465
        case 2048:
5466
        case 3072:
5467
        case 4096:
5468
            return 1;
5469
    }
5470
5471
    return 0;
5472
#elif defined(HAVE_FIPS)
5473
    /* Key size requirements for CAVP */
5474
    switch (size) {
5475
        case 1024:
5476
        case 2048:
5477
        case 3072:
5478
        case 4096:
5479
            return 1;
5480
    }
5481
5482
    return 0;
5483
#else
5484
0
    return 1; /* allow unusual key sizes in non FIPS mode */
5485
0
#endif /* FIPS_VERSION3_GE(7,0,0) */
5486
0
}
5487
5488
5489
#ifndef WOLFSSL_NO_RSA_SW
5490
static int _CheckProbablePrime(mp_int* p, mp_int* q, mp_int* e, int nlen,
5491
                                    int* isPrime, WC_RNG* rng)
5492
0
{
5493
0
    int ret;
5494
0
#ifdef WOLFSSL_SMALL_STACK
5495
0
    mp_int *tmp1 = NULL, *tmp2 = NULL;
5496
#else
5497
    mp_int tmp1[1], tmp2[2];
5498
#endif
5499
0
    mp_int* prime;
5500
5501
0
    if (p == NULL || e == NULL || isPrime == NULL)
5502
0
        return BAD_FUNC_ARG;
5503
5504
0
    if (!RsaSizeCheck(nlen))
5505
0
        return BAD_FUNC_ARG;
5506
5507
0
    *isPrime = MP_NO;
5508
5509
0
#ifdef WOLFSSL_SMALL_STACK
5510
0
    if (((tmp1 = (mp_int *)XMALLOC(sizeof(*tmp1), NULL, DYNAMIC_TYPE_WOLF_BIGINT)) == NULL) ||
5511
0
        ((tmp2 = (mp_int *)XMALLOC(sizeof(*tmp2), NULL, DYNAMIC_TYPE_WOLF_BIGINT)) == NULL)) {
5512
        /* mp_init_multi() below is skipped, so nothing was initialized: free
5513
         * what was allocated here and NULL the pointers. The notOkay cleanup
5514
         * must not see an allocated-but-uninitialized mp_int - clearing one
5515
         * reads a garbage used/size and corrupts the heap. */
5516
0
        XFREE(tmp1, NULL, DYNAMIC_TYPE_WOLF_BIGINT);
5517
0
        XFREE(tmp2, NULL, DYNAMIC_TYPE_WOLF_BIGINT);
5518
0
        tmp1 = NULL;
5519
0
        tmp2 = NULL;
5520
0
        ret = MEMORY_E;
5521
0
        goto notOkay;
5522
0
    }
5523
0
#endif
5524
5525
0
    ret = mp_init_multi(tmp1, tmp2, NULL, NULL, NULL, NULL);
5526
0
    if (ret != MP_OKAY) goto notOkay;
5527
5528
0
    if (q != NULL) {
5529
0
        int valid = 0;
5530
        /* 5.4 (186-4) 5.5 (186-5) -
5531
         * check that |p-q| <= (2^(1/2))(2^((nlen/2)-1)) */
5532
0
        ret = wc_CompareDiffPQ(p, q, nlen, &valid);
5533
0
        if ((ret != MP_OKAY) || (!valid)) goto notOkay;
5534
0
        prime = q;
5535
0
    }
5536
0
    else
5537
0
        prime = p;
5538
5539
    /* 4.4,5.5 (186-4) 4.4,5.4 (186-5) -
5540
     * Check that prime >= (2^(1/2))(2^((nlen/2)-1))
5541
     *           This is a comparison against lowerBound */
5542
0
    ret = mp_read_unsigned_bin(tmp1, lower_bound, (word32)nlen/16);
5543
0
    if (ret != MP_OKAY) goto notOkay;
5544
0
    ret = mp_cmp(prime, tmp1);
5545
0
    if (ret == MP_LT) goto exit;
5546
5547
    /* 4.5,5.6 (186-4 & 186-5) - Check that GCD(p-1, e) == 1 */
5548
0
    ret = mp_sub_d(prime, 1, tmp1);  /* tmp1 = prime-1 */
5549
0
    if (ret != MP_OKAY) goto notOkay;
5550
#ifdef WOLFSSL_CHECK_MEM_ZERO
5551
    mp_memzero_add("Check Probable Prime tmp1", tmp1);
5552
#endif
5553
0
    ret = mp_gcd(tmp1, e, tmp2);  /* tmp2 = gcd(prime-1, e) */
5554
0
    if (ret != MP_OKAY) goto notOkay;
5555
0
    ret = mp_cmp_d(tmp2, 1);
5556
0
    if (ret != MP_EQ) goto exit; /* e divides p-1 */
5557
5558
    /* 4.5.1,5.6.1 - Check primality of p with 8 rounds of M-R.
5559
     * mp_prime_is_prime_ex() performs test divisions against the first 256
5560
     * prime numbers. After that it performs 8 rounds of M-R using random
5561
     * bases between 2 and n-2.
5562
     * mp_prime_is_prime() performs the same test divisions and then does
5563
     * M-R with the first 8 primes. Both functions set isPrime as a
5564
     * side-effect. */
5565
0
    if (rng != NULL)
5566
0
        ret = mp_prime_is_prime_ex(prime, 8, isPrime, rng);
5567
0
    else
5568
0
        ret = mp_prime_is_prime(prime, 8, isPrime);
5569
0
    if (ret != MP_OKAY) goto notOkay;
5570
5571
0
exit:
5572
0
    ret = MP_OKAY;
5573
5574
0
notOkay:
5575
5576
0
#ifdef WOLFSSL_SMALL_STACK
5577
0
    if (tmp1 != NULL) {
5578
0
        mp_forcezero(tmp1);
5579
0
        XFREE(tmp1, NULL, DYNAMIC_TYPE_WOLF_BIGINT);
5580
0
    }
5581
0
    if (tmp2 != NULL) {
5582
0
        mp_clear(tmp2);
5583
0
        XFREE(tmp2, NULL, DYNAMIC_TYPE_WOLF_BIGINT);
5584
0
    }
5585
#else
5586
    mp_forcezero(tmp1);
5587
    mp_clear(tmp2);
5588
#ifdef WOLFSSL_CHECK_MEM_ZERO
5589
    mp_memzero_check(tmp1);
5590
#endif
5591
#endif
5592
5593
0
    return ret;
5594
0
}
5595
5596
5597
int wc_CheckProbablePrime_ex(const byte* pRaw, word32 pRawSz,
5598
                          const byte* qRaw, word32 qRawSz,
5599
                          const byte* eRaw, word32 eRawSz,
5600
                          int nlen, int* isPrime, WC_RNG* rng)
5601
0
{
5602
0
#ifdef WOLFSSL_SMALL_STACK
5603
0
    mp_int *p = NULL, *q = NULL, *e = NULL;
5604
#else
5605
    mp_int p[1], q[1], e[1];
5606
#endif
5607
0
    mp_int* Q = NULL;
5608
0
    int ret;
5609
5610
0
    if (pRaw == NULL || pRawSz == 0 ||
5611
0
        eRaw == NULL || eRawSz == 0 ||
5612
0
        isPrime == NULL) {
5613
5614
0
        return BAD_FUNC_ARG;
5615
0
    }
5616
5617
0
    if ((qRaw != NULL && qRawSz == 0) || (qRaw == NULL && qRawSz != 0))
5618
0
        return BAD_FUNC_ARG;
5619
5620
0
#ifdef WOLFSSL_SMALL_STACK
5621
5622
0
    if (((p = (mp_int *)XMALLOC(sizeof(*p), NULL, DYNAMIC_TYPE_RSA_BUFFER)) == NULL) ||
5623
0
        ((q = (mp_int *)XMALLOC(sizeof(*q), NULL, DYNAMIC_TYPE_RSA_BUFFER)) == NULL) ||
5624
0
        ((e = (mp_int *)XMALLOC(sizeof(*e), NULL, DYNAMIC_TYPE_RSA_BUFFER)) == NULL)) {
5625
        /* mp_init_multi() below is skipped, so nothing was initialized: free
5626
         * what was allocated here and NULL the pointers. The cleanup at the
5627
         * end must not see an allocated-but-uninitialized mp_int - clearing
5628
         * one reads a garbage used/size and corrupts the heap. */
5629
0
        XFREE(p, NULL, DYNAMIC_TYPE_RSA_BUFFER);
5630
0
        XFREE(q, NULL, DYNAMIC_TYPE_RSA_BUFFER);
5631
0
        XFREE(e, NULL, DYNAMIC_TYPE_RSA_BUFFER);
5632
0
        p = NULL;
5633
0
        q = NULL;
5634
0
        e = NULL;
5635
0
        ret = MEMORY_E;
5636
0
    }
5637
0
    else
5638
0
        ret = 0;
5639
5640
0
    if (ret == 0)
5641
0
#endif
5642
0
        ret = mp_init_multi(p, q, e, NULL, NULL, NULL);
5643
5644
0
    if (ret == MP_OKAY)
5645
0
        ret = mp_read_unsigned_bin(p, pRaw, pRawSz);
5646
5647
0
    if (ret == MP_OKAY) {
5648
    #ifdef WOLFSSL_CHECK_MEM_ZERO
5649
        mp_memzero_add("wc_CheckProbablePrime_ex p", p);
5650
    #endif
5651
0
        if (qRaw != NULL) {
5652
0
            ret = mp_read_unsigned_bin(q, qRaw, qRawSz);
5653
0
            if (ret == MP_OKAY) {
5654
            #ifdef WOLFSSL_CHECK_MEM_ZERO
5655
                mp_memzero_add("wc_CheckProbablePrime_ex q", q);
5656
            #endif
5657
0
                Q = q;
5658
0
            }
5659
0
        }
5660
0
    }
5661
5662
0
    if (ret == MP_OKAY)
5663
0
        ret = mp_read_unsigned_bin(e, eRaw, eRawSz);
5664
5665
0
    if (ret == 0) {
5666
0
        ret = _CheckProbablePrime(p, Q, e, nlen, isPrime, rng);
5667
0
    }
5668
5669
0
    ret = (ret == MP_OKAY) ? 0 : PRIME_GEN_E;
5670
5671
0
#ifdef WOLFSSL_SMALL_STACK
5672
0
    if (p != NULL) {
5673
0
        mp_forcezero(p);
5674
0
        XFREE(p, NULL, DYNAMIC_TYPE_RSA_BUFFER);
5675
0
    }
5676
0
    if (q != NULL) {
5677
0
        mp_forcezero(q);
5678
0
        XFREE(q, NULL, DYNAMIC_TYPE_RSA_BUFFER);
5679
0
    }
5680
0
    if (e != NULL) {
5681
0
        mp_clear(e);
5682
0
        XFREE(e, NULL, DYNAMIC_TYPE_RSA_BUFFER);
5683
0
    }
5684
#else
5685
    mp_forcezero(p);
5686
    mp_forcezero(q);
5687
    mp_clear(e);
5688
#ifdef WOLFSSL_CHECK_MEM_ZERO
5689
    mp_memzero_check(p);
5690
    mp_memzero_check(q);
5691
#endif
5692
#endif
5693
5694
0
    return ret;
5695
0
}
5696
5697
5698
int wc_CheckProbablePrime(const byte* pRaw, word32 pRawSz,
5699
                          const byte* qRaw, word32 qRawSz,
5700
                          const byte* eRaw, word32 eRawSz,
5701
                          int nlen, int* isPrime)
5702
0
{
5703
0
    return wc_CheckProbablePrime_ex(pRaw, pRawSz, qRaw, qRawSz,
5704
0
                          eRaw, eRawSz, nlen, isPrime, NULL);
5705
0
}
5706
#endif /* !WOLFSSL_NO_RSA_SW */
5707
5708
#if !defined(HAVE_FIPS) || (defined(HAVE_FIPS) && \
5709
        defined(HAVE_FIPS_VERSION) && (HAVE_FIPS_VERSION >= 2))
5710
/* Make an RSA key for size bits, with e specified, 65537 is a good e */
5711
int wc_MakeRsaKey(RsaKey* key, int size, long e, WC_RNG* rng)
5712
0
{
5713
0
#ifndef WC_NO_RNG
5714
0
#if (!defined(WOLFSSL_SE050) || defined(WOLFSSL_SE050_NO_RSA) || \
5715
0
     defined(WOLFSSL_SE050_ONLY_KEY_ID)) && \
5716
0
    !defined(WOLF_CRYPTO_CB_ONLY_RSA) && \
5717
0
    !defined(WOLFSSL_MICROCHIP_TA100)
5718
0
#ifdef WOLFSSL_SMALL_STACK
5719
0
    mp_int *p = NULL;
5720
0
    mp_int *q = NULL;
5721
0
    mp_int *tmp1 = NULL;
5722
0
    mp_int *tmp2 = NULL;
5723
0
    mp_int *tmp3 = NULL;
5724
#else
5725
    mp_int p_buf, *p = &p_buf;
5726
    mp_int q_buf, *q = &q_buf;
5727
    mp_int tmp1_buf, *tmp1 = &tmp1_buf;
5728
    mp_int tmp2_buf, *tmp2 = &tmp2_buf;
5729
    mp_int tmp3_buf, *tmp3 = &tmp3_buf;
5730
#endif /* WOLFSSL_SMALL_STACK */
5731
0
    int i, failCount, isPrime = 0;
5732
0
    word32 primeSz;
5733
0
#ifndef WOLFSSL_NO_MALLOC
5734
0
    byte* buf = NULL;
5735
#else
5736
    /* RSA_MAX_SIZE is the size of n in bits. */
5737
    byte buf[RSA_MAX_SIZE/16];
5738
#endif
5739
0
#ifdef WC_CRYPTOCB_KEYGEN_ID_CHECK
5740
0
    int idKey = 0;
5741
0
    int idDevId = INVALID_DEVID;
5742
0
#endif
5743
0
#endif /* !WOLFSSL_SE050 */
5744
0
    int err;
5745
5746
#if (!defined(WOLFSSL_SE050) || defined(WOLFSSL_SE050_NO_RSA) || \
5747
     defined(WOLFSSL_SE050_ONLY_KEY_ID)) && \
5748
    !defined(WOLF_CRYPTO_CB_ONLY_RSA) && \
5749
    !defined(WOLFSSL_MICROCHIP_TA100) && \
5750
    !defined(WOLFSSL_SMALL_STACK) && defined(WOLFSSL_CHECK_MEM_ZERO)
5751
    /* Zero the stack temporaries so the mp_memzero_check() in the 'out'
5752
     * cleanup is safe even when an early argument/size check leaves via
5753
     * 'goto out' before these are mp_init'd - an uninitialized mp_int's size
5754
     * field would otherwise make the check scan an arbitrary stack range.
5755
     * Done here, after all declarations, to satisfy C89. */
5756
    XMEMSET(&p_buf, 0, sizeof(p_buf));
5757
    XMEMSET(&q_buf, 0, sizeof(q_buf));
5758
    XMEMSET(&tmp1_buf, 0, sizeof(tmp1_buf));
5759
    XMEMSET(&tmp2_buf, 0, sizeof(tmp2_buf));
5760
    XMEMSET(&tmp3_buf, 0, sizeof(tmp3_buf));
5761
#endif
5762
5763
0
    if (key == NULL || rng == NULL) {
5764
0
        err = BAD_FUNC_ARG;
5765
0
        goto out;
5766
0
    }
5767
5768
0
    if (!RsaSizeCheck(size)) {
5769
0
        err = BAD_FUNC_ARG;
5770
0
        goto out;
5771
0
    }
5772
5773
#if defined(HAVE_FIPS)
5774
    /* WC_RSA_EXPONENT is 65537, which is what FIPS 186-5 sec 5.4(e) requires
5775
     * as the lower bound.  e is a long, so it cannot reach the 2^256 upper
5776
     * bound the same clause sets. */
5777
    if (e < WC_RSA_EXPONENT || (e & 1) == 0) {
5778
#else
5779
0
    if (e < 3 || (e & 1) == 0) {
5780
0
#endif
5781
0
        err = BAD_FUNC_ARG;
5782
0
        goto out;
5783
0
    }
5784
5785
#if defined(WOLFSSL_MICROCHIP_TA100)
5786
    err = wc_Microchip_rsa_create_key(key, size, e);
5787
    goto out;
5788
#elif defined(WOLFSSL_SE050) && !defined(WOLFSSL_SE050_NO_RSA) && \
5789
      !defined(WOLFSSL_SE050_ONLY_KEY_ID)
5790
    err = se050_rsa_create_key(key, size, e);
5791
    goto out;
5792
#else
5793
    /* software crypto */
5794
5795
0
#ifdef WOLFSSL_SMALL_STACK
5796
0
    p = (mp_int *)XMALLOC(sizeof *p, key->heap, DYNAMIC_TYPE_RSA);
5797
0
    q = (mp_int *)XMALLOC(sizeof *q, key->heap, DYNAMIC_TYPE_RSA);
5798
0
    tmp1 = (mp_int *)XMALLOC(sizeof *tmp1, key->heap, DYNAMIC_TYPE_RSA);
5799
0
    tmp2 = (mp_int *)XMALLOC(sizeof *tmp2, key->heap, DYNAMIC_TYPE_RSA);
5800
0
    tmp3 = (mp_int *)XMALLOC(sizeof *tmp3, key->heap, DYNAMIC_TYPE_RSA);
5801
5802
0
    if ((p == NULL) ||
5803
0
        (q == NULL) ||
5804
0
        (tmp1 == NULL) ||
5805
0
        (tmp2 == NULL) ||
5806
0
        (tmp3 == NULL)) {
5807
0
      err = MEMORY_E;
5808
0
      goto out;
5809
0
    }
5810
0
#endif
5811
#ifdef WOLFSSL_CHECK_MEM_ZERO
5812
    XMEMSET(p, 0, sizeof(*p));
5813
    XMEMSET(q, 0, sizeof(*q));
5814
    XMEMSET(tmp1, 0, sizeof(*tmp1));
5815
    XMEMSET(tmp2, 0, sizeof(*tmp2));
5816
    XMEMSET(tmp3, 0, sizeof(*tmp3));
5817
#endif
5818
5819
0
#if defined(WC_CRYPTOCB_KEYGEN_ID_CHECK) && !defined(WOLF_CRYPTO_CB_ONLY_RSA)
5820
0
    idKey = WC_CRYPTOCB_HAS_ID(key);
5821
0
    idDevId = key->devId;
5822
0
#endif
5823
0
#ifdef WOLF_CRYPTO_CB
5824
0
    #ifndef WOLF_CRYPTO_CB_FIND
5825
0
    if (key->devId != INVALID_DEVID)
5826
0
    #endif
5827
0
    {
5828
0
        err = wc_CryptoCb_MakeRsaKey(key, size, e, rng);
5829
    #ifdef WOLF_CRYPTO_CB_ONLY_RSA
5830
        if (err == WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
5831
            err = NO_VALID_DEVID;
5832
            goto out;
5833
        }
5834
    #else
5835
0
        if (err != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
5836
0
            goto out;
5837
0
        }
5838
        /* fall-through when unavailable */
5839
0
    #endif
5840
0
    }
5841
    #if !defined(WOLF_CRYPTO_CB_FIND) && defined(WOLF_CRYPTO_CB_ONLY_RSA)
5842
    else {
5843
        err = NO_VALID_DEVID;
5844
    }
5845
    #endif
5846
0
    #if defined(WC_CRYPTOCB_KEYGEN_ID_CHECK) && \
5847
0
        !defined(WOLF_CRYPTO_CB_ONLY_RSA)
5848
0
    if (idKey && wc_CryptoCb_HasPkDevice(idDevId)) {
5849
0
        err = NO_VALID_DEVID;
5850
0
        goto out;
5851
0
    }
5852
0
    #endif
5853
0
#endif
5854
5855
0
#ifndef WOLF_CRYPTO_CB_ONLY_RSA
5856
#if defined(WOLFSSL_ASYNC_CRYPT) && defined(WC_ASYNC_ENABLE_RSA) && \
5857
    defined(WC_ASYNC_ENABLE_RSA_KEYGEN)
5858
    if (key->asyncDev.marker == WOLFSSL_ASYNC_MARKER_RSA) {
5859
    #ifdef HAVE_CAVIUM
5860
        /* TODO: Not implemented */
5861
    #elif defined(HAVE_INTEL_QA)
5862
        err = IntelQaRsaKeyGen(&key->asyncDev, key, size, e, rng);
5863
        goto out;
5864
    #elif defined(WOLFSSL_ASYNC_CRYPT_SW)
5865
        if (wc_AsyncSwInit(&key->asyncDev, ASYNC_SW_RSA_MAKE)) {
5866
            WC_ASYNC_SW* sw = &key->asyncDev.sw;
5867
            sw->rsaMake.rng = rng;
5868
            sw->rsaMake.key = key;
5869
            sw->rsaMake.size = size;
5870
            sw->rsaMake.e = e;
5871
            err = WC_PENDING_E;
5872
            goto out;
5873
        }
5874
    #endif
5875
    }
5876
#endif
5877
5878
0
    err = mp_init_multi(p, q, tmp1, tmp2, tmp3, NULL);
5879
5880
0
    if (err == MP_OKAY)
5881
0
        err = mp_set_int(tmp3, (unsigned long)e);
5882
5883
    /* The failCount value comes from NIST FIPS 186-4, section B.3.3,
5884
     * process steps 4.7 and 5.8. */
5885
0
    failCount = 5 * (size / 2);
5886
0
    primeSz = (word32)size / 16; /* size is the size of n in bits.
5887
                            primeSz is in bytes. */
5888
5889
0
#ifndef WOLFSSL_NO_MALLOC
5890
    /* allocate buffer to work with */
5891
0
    if (err == MP_OKAY) {
5892
0
        buf = (byte*)XMALLOC(primeSz, key->heap, DYNAMIC_TYPE_RSA);
5893
0
        if (buf == NULL)
5894
0
            err = MEMORY_E;
5895
0
    }
5896
0
#endif
5897
5898
    /* make p */
5899
0
    if (err == MP_OKAY) {
5900
    #ifdef WOLFSSL_CHECK_MEM_ZERO
5901
        wc_MemZero_Add("RSA gen buf", buf, primeSz);
5902
        mp_memzero_add("RSA gen p", p);
5903
        mp_memzero_add("RSA gen q", q);
5904
        mp_memzero_add("RSA gen tmp1", tmp1);
5905
        mp_memzero_add("RSA gen tmp2", tmp2);
5906
        mp_memzero_add("RSA gen tmp3", tmp3);
5907
    #endif
5908
0
        isPrime = 0;
5909
0
        i = 0;
5910
0
        for (;;) {
5911
#ifdef SHOW_GEN
5912
            printf(".");
5913
            fflush(stdout);
5914
#endif
5915
            /* generate value */
5916
0
            err = wc_RNG_GenerateBlock(rng, buf, primeSz);
5917
0
            if (err == 0) {
5918
                /* prime lower bound has the MSB set, set it in candidate */
5919
0
                buf[0] |= 0x80;
5920
                /* make candidate odd */
5921
0
                buf[primeSz-1] |= 0x01;
5922
                /* load value */
5923
0
                err = mp_read_unsigned_bin(p, buf, primeSz);
5924
0
            }
5925
5926
0
            if (err == MP_OKAY)
5927
0
                err = _CheckProbablePrime(p, NULL, tmp3, size, &isPrime, rng);
5928
5929
#ifdef HAVE_FIPS
5930
            i++;
5931
#else
5932
            /* Keep the old retry behavior in non-FIPS build. */
5933
0
#endif
5934
5935
0
            if (err != MP_OKAY || isPrime || i >= failCount)
5936
0
                break;
5937
5938
0
            err = WC_CHECK_FOR_INTR_SIGNALS();
5939
0
            if (err != 0)
5940
0
                break;
5941
0
            WC_RELAX_LONG_LOOP();
5942
0
        };
5943
0
    }
5944
5945
0
    if (err == MP_OKAY && !isPrime)
5946
0
        err = PRIME_GEN_E;
5947
5948
    /* make q */
5949
0
    if (err == MP_OKAY) {
5950
0
        isPrime = 0;
5951
0
        i = 0;
5952
0
        do {
5953
#ifdef SHOW_GEN
5954
            printf(".");
5955
            fflush(stdout);
5956
#endif
5957
            /* generate value */
5958
0
            err = wc_RNG_GenerateBlock(rng, buf, primeSz);
5959
0
            if (err == 0) {
5960
                /* prime lower bound has the MSB set, set it in candidate */
5961
0
                buf[0] |= 0x80;
5962
                /* make candidate odd */
5963
0
                buf[primeSz-1] |= 0x01;
5964
                /* load value */
5965
0
                err = mp_read_unsigned_bin(q, buf, primeSz);
5966
0
            }
5967
5968
0
            if (err == MP_OKAY)
5969
0
                err = _CheckProbablePrime(p, q, tmp3, size, &isPrime, rng);
5970
5971
0
#ifndef WC_RSA_NO_FERMAT_CHECK
5972
0
            if (err == MP_OKAY && isPrime) {
5973
                /* Fermat's Factorization works when difference between p and q
5974
                 * is less than (conservatively):
5975
                 *     n^(1/4) + 32
5976
                 *  ~= 2^(bit count of n)^(1/4) + 32)
5977
                 *   = 2^((bit count of n)/4 + 32)
5978
                 */
5979
0
                err = mp_sub(p, q, tmp1);
5980
0
                if (err == MP_OKAY && mp_count_bits(tmp1) <= (size / 4) + 32) {
5981
0
                    isPrime = 0;
5982
0
                }
5983
0
            }
5984
0
#endif
5985
5986
#ifdef HAVE_FIPS
5987
            i++;
5988
#else
5989
            /* Keep the old retry behavior in non-FIPS build. */
5990
0
            (void)i;
5991
0
#endif
5992
5993
            /* Check err before WC_CHECK_FOR_INTR_SIGNALS() overwrites it, as
5994
             * the p loop does; a lost error retries forever without failCount.
5995
             * SP 800-90A Rev1 sec 11.4.2: DRBG errors must reach the caller. */
5996
0
            if (err != MP_OKAY || isPrime || i >= failCount)
5997
0
                break;
5998
5999
0
            err = WC_CHECK_FOR_INTR_SIGNALS();
6000
0
            if (err != 0)
6001
0
                break;
6002
0
            WC_RELAX_LONG_LOOP();
6003
6004
0
        } while (err == MP_OKAY && !isPrime && i < failCount);
6005
0
    }
6006
6007
0
    if (err == MP_OKAY && !isPrime)
6008
0
        err = PRIME_GEN_E;
6009
6010
0
#ifndef WOLFSSL_NO_MALLOC
6011
0
    if (buf) {
6012
0
        ForceZero(buf, primeSz);
6013
0
        XFREE(buf, key->heap, DYNAMIC_TYPE_RSA);
6014
0
    }
6015
#else
6016
    ForceZero(buf, primeSz);
6017
#endif
6018
6019
0
    if (err == MP_OKAY && mp_cmp(p, q) < 0) {
6020
0
        err = mp_copy(p, tmp1);
6021
0
        if (err == MP_OKAY)
6022
0
            err = mp_copy(q, p);
6023
0
        if (err == MP_OKAY)
6024
0
            mp_copy(tmp1, q);
6025
0
    }
6026
6027
    /* Setup RsaKey buffers */
6028
0
    if (err == MP_OKAY)
6029
0
        err = mp_init_multi(&key->n, &key->e, &key->d, &key->p, &key->q, NULL);
6030
0
    if (err == MP_OKAY)
6031
0
        err = mp_init_multi(&key->dP, &key->dQ, &key->u, NULL, NULL, NULL);
6032
6033
    /* Software Key Calculation */
6034
0
    if (err == MP_OKAY)                /* tmp1 = p-1 */
6035
0
        err = mp_sub_d(p, 1, tmp1);
6036
0
    if (err == MP_OKAY)                /* tmp2 = q-1 */
6037
0
        err = mp_sub_d(q, 1, tmp2);
6038
0
#ifdef WC_RSA_BLINDING
6039
0
    if (err == MP_OKAY)                /* tmp3 = order of n */
6040
0
        err = mp_mul(tmp1, tmp2, tmp3);
6041
#else
6042
    if (err == MP_OKAY)                /* tmp3 = lcm(p-1, q-1), last loop */
6043
        err = mp_lcm(tmp1, tmp2, tmp3);
6044
#endif
6045
    /* make key */
6046
0
    if (err == MP_OKAY)                /* key->e = e */
6047
0
        err = mp_set_int(&key->e, (unsigned long)e);
6048
0
#ifdef WC_RSA_BLINDING
6049
    /* Blind the inverse operation with a value that is invertable */
6050
0
    if (err == MP_OKAY) {
6051
0
        do {
6052
0
            err = mp_rand(&key->p, mp_get_digit_count(tmp3), rng);
6053
0
            if (err == MP_OKAY)
6054
0
                err = mp_set_bit(&key->p, 0);
6055
0
            if (err == MP_OKAY)
6056
0
                err = mp_set_bit(&key->p, size - 1);
6057
0
            if (err == MP_OKAY)
6058
0
                err = mp_gcd(&key->p, tmp3, &key->q);
6059
0
        }
6060
0
        while ((err == MP_OKAY) && !mp_isone(&key->q));
6061
0
    }
6062
    /* 8/16-bit word size requires a full multiply when e=0x10001 */
6063
0
    if (err == MP_OKAY)
6064
0
        err = mp_mul(&key->p, &key->e, &key->e);
6065
0
#endif
6066
0
    if (err == MP_OKAY)                /* key->d = 1/e mod lcm(p-1, q-1) */
6067
0
        err = mp_invmod(&key->e, tmp3, &key->d);
6068
0
#ifdef WC_RSA_BLINDING
6069
    /* Take off blinding from d and reset e */
6070
0
    if (err == MP_OKAY)
6071
0
        err = mp_mulmod(&key->d, &key->p, tmp3, &key->d);
6072
    /* The blind, its gcd and the blinded e were staged in p, q and e. */
6073
0
    mp_forcezero(&key->p);
6074
0
    mp_forcezero(&key->q);
6075
0
    mp_forcezero(&key->e);
6076
0
    if (err == MP_OKAY)
6077
0
        err = mp_set_int(&key->e, (unsigned long)e);
6078
0
#endif
6079
0
    if (err == MP_OKAY)                /* key->n = pq */
6080
0
        err = mp_mul(p, q, &key->n);
6081
0
    if (err == MP_OKAY)                /* key->dP = d mod(p-1) */
6082
0
        err = mp_mod(&key->d, tmp1, &key->dP);
6083
0
    if (err == MP_OKAY)                /* key->dQ = d mod(q-1) */
6084
0
        err = mp_mod(&key->d, tmp2, &key->dQ);
6085
#ifdef WOLFSSL_MP_INVMOD_CONSTANT_TIME
6086
    if (err == MP_OKAY)                /* key->u = 1/q mod p */
6087
        err = mp_invmod(q, p, &key->u);
6088
#else
6089
0
    if (err == MP_OKAY)
6090
0
        err = mp_sub_d(p, 2, tmp3);
6091
0
    if (err == MP_OKAY)                /* key->u = 1/q mod p = q^p-2 mod p */
6092
0
        err = mp_exptmod(q, tmp3, p, &key->u);
6093
0
#endif
6094
0
    if (err == MP_OKAY)
6095
0
        err = mp_copy(p, &key->p);
6096
0
    if (err == MP_OKAY)
6097
0
        err = mp_copy(q, &key->q);
6098
6099
#ifdef HAVE_WOLF_BIGINT
6100
    /* make sure raw unsigned bin version is available */
6101
    if (err == MP_OKAY)
6102
         err = wc_mp_to_bigint(&key->n, &key->n.raw);
6103
    if (err == MP_OKAY)
6104
         err = wc_mp_to_bigint(&key->e, &key->e.raw);
6105
    if (err == MP_OKAY)
6106
         err = wc_mp_to_bigint(&key->d, &key->d.raw);
6107
    if (err == MP_OKAY)
6108
         err = wc_mp_to_bigint(&key->p, &key->p.raw);
6109
    if (err == MP_OKAY)
6110
         err = wc_mp_to_bigint(&key->q, &key->q.raw);
6111
    if (err == MP_OKAY)
6112
         err = wc_mp_to_bigint(&key->dP, &key->dP.raw);
6113
    if (err == MP_OKAY)
6114
         err = wc_mp_to_bigint(&key->dQ, &key->dQ.raw);
6115
    if (err == MP_OKAY)
6116
         err = wc_mp_to_bigint(&key->u, &key->u.raw);
6117
#endif
6118
6119
0
    if (err == MP_OKAY)
6120
0
        key->type = RSA_PRIVATE;
6121
6122
#ifdef WOLFSSL_CHECK_MEM_ZERO
6123
    if (err == MP_OKAY) {
6124
        mp_memzero_add("Make RSA key d", &key->d);
6125
        mp_memzero_add("Make RSA key p", &key->p);
6126
        mp_memzero_add("Make RSA key q", &key->q);
6127
        mp_memzero_add("Make RSA key dP", &key->dP);
6128
        mp_memzero_add("Make RSA key dQ", &key->dQ);
6129
        mp_memzero_add("Make RSA key u", &key->u);
6130
    }
6131
#endif
6132
6133
    /* Last value p - 1. */
6134
0
    mp_forcezero(tmp1);
6135
    /* Last value q - 1. */
6136
0
    mp_forcezero(tmp2);
6137
    /* Last value p - 2. */
6138
0
    mp_forcezero(tmp3);
6139
0
    mp_forcezero(p);
6140
0
    mp_forcezero(q);
6141
6142
#ifdef WOLFSSL_RSA_KEY_CHECK
6143
    /* Perform the pair-wise consistency test on the new key. */
6144
    if (err == 0)
6145
        err = _ifc_pairwise_consistency_test(key, rng);
6146
#endif
6147
6148
0
    if (err != 0) {
6149
0
        wc_FreeRsaKey(key);
6150
0
        goto out;
6151
0
    }
6152
6153
#if defined(WOLFSSL_XILINX_CRYPT)
6154
    if (wc_InitRsaHw(key) != 0) {
6155
        return BAD_STATE_E;
6156
    }
6157
#endif
6158
6159
0
    err = 0;
6160
0
#endif /* WOLF_CRYPTO_CB_ONLY_RSA */
6161
0
#endif /* hardware / software selection */
6162
0
  out:
6163
6164
0
#if !defined(WOLFSSL_SE050) || defined(WOLFSSL_SE050_ONLY_KEY_ID)
6165
0
#ifdef WOLFSSL_SMALL_STACK
6166
0
    if (key != NULL) {
6167
0
        XFREE(p, key->heap, DYNAMIC_TYPE_RSA);
6168
0
        XFREE(q, key->heap, DYNAMIC_TYPE_RSA);
6169
0
        XFREE(tmp1, key->heap, DYNAMIC_TYPE_RSA);
6170
0
        XFREE(tmp2, key->heap, DYNAMIC_TYPE_RSA);
6171
0
        XFREE(tmp3, key->heap, DYNAMIC_TYPE_RSA);
6172
0
    }
6173
#elif defined(WOLFSSL_CHECK_MEM_ZERO)
6174
    mp_memzero_check(p);
6175
    mp_memzero_check(q);
6176
    mp_memzero_check(tmp1);
6177
    mp_memzero_check(tmp2);
6178
    mp_memzero_check(tmp3);
6179
#endif /* WOLFSSL_SMALL_STACK */
6180
0
#endif /* !WOLFSSL_SE050 */
6181
6182
0
    return err;
6183
6184
#else
6185
    return NOT_COMPILED_IN;
6186
#endif
6187
0
}
6188
#endif /* !FIPS || FIPS_VER >= 2 */
6189
#endif /* WOLFSSL_KEY_GEN */
6190
6191
#ifndef WC_NO_RNG
6192
int wc_RsaSetRNG(RsaKey* key, WC_RNG* rng)
6193
376
{
6194
376
    if (key == NULL || rng == NULL)
6195
0
        return BAD_FUNC_ARG;
6196
6197
376
    key->rng = rng;
6198
6199
376
    return 0;
6200
376
}
6201
6202
/* Companion to wc_RsaSetRNG(): detach the key's RNG association.
6203
 * Subsequent operations that require the key's RNG (blinding, pairwise
6204
 * consistency) then either fail with MISSING_RNG_E or fall back to a
6205
 * locally instantiated RNG, per operation, until a new RNG is set. */
6206
int wc_RsaClearRNG(RsaKey* key)
6207
0
{
6208
0
    if (key == NULL)
6209
0
        return BAD_FUNC_ARG;
6210
6211
0
    key->rng = NULL;
6212
6213
0
    return 0;
6214
0
}
6215
#endif /* !WC_NO_RNG */
6216
6217
#ifdef WC_RSA_NONBLOCK
6218
int wc_RsaSetNonBlock(RsaKey* key, RsaNb* nb)
6219
{
6220
    if (key == NULL)
6221
        return BAD_FUNC_ARG;
6222
6223
    if (nb) {
6224
        XMEMSET(nb, 0, sizeof(RsaNb));
6225
    }
6226
6227
    /* Allow nb == NULL to clear non-block mode */
6228
    key->nb = nb;
6229
6230
    return 0;
6231
}
6232
#if defined(WC_RSA_NONBLOCK_TIME) && defined(USE_FAST_MATH)
6233
int wc_RsaSetNonBlockTime(RsaKey* key, word32 maxBlockUs, word32 cpuMHz)
6234
{
6235
    if (key == NULL || key->nb == NULL) {
6236
        return BAD_FUNC_ARG;
6237
    }
6238
6239
    /* calculate maximum number of instructions to block */
6240
    key->nb->exptmod.maxBlockInst = cpuMHz * maxBlockUs;
6241
6242
    return 0;
6243
}
6244
#endif /* WC_RSA_NONBLOCK_TIME && USE_FAST_MATH */
6245
#endif /* WC_RSA_NONBLOCK */
6246
6247
#ifndef WOLFSSL_RSA_PUBLIC_ONLY
6248
6249
#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
6250
/*
6251
 * Calculate  y = d mod(x-1)
6252
 */
6253
static int CalcDX(mp_int* y, mp_int* x, mp_int* d)
6254
0
{
6255
0
    int err;
6256
#ifndef WOLFSSL_SMALL_STACK
6257
    mp_int  m[1];
6258
#else
6259
0
    mp_int* m = (mp_int*)XMALLOC(sizeof(mp_int), NULL, DYNAMIC_TYPE_WOLF_BIGINT);
6260
0
    if (m == NULL)
6261
0
        return MEMORY_E;
6262
0
#endif
6263
6264
0
    err = mp_init(m);
6265
0
    if (err == MP_OKAY) {
6266
0
        err = mp_sub_d(x, 1, m);
6267
0
        if (err == MP_OKAY)
6268
0
            err = mp_mod(d, m, y);
6269
0
        mp_forcezero(m);
6270
0
    }
6271
6272
0
    WC_FREE_VAR_EX(m, NULL, DYNAMIC_TYPE_WOLF_BIGINT);
6273
6274
0
    return err;
6275
0
}
6276
#endif
6277
6278
/* Software-only import of RSA private key elements into RsaKey.
6279
 * This internal helper avoids recursion when called from the SETKEY path. */
6280
static int _RsaPrivateKeyDecodeRaw(const byte* n, word32 nSz,
6281
        const byte* e, word32 eSz, const byte* d, word32 dSz,
6282
        const byte* u, word32 uSz, const byte* p, word32 pSz,
6283
        const byte* q, word32 qSz, const byte* dP, word32 dPSz,
6284
        const byte* dQ, word32 dQSz, RsaKey* key)
6285
0
{
6286
0
    int err = MP_OKAY;
6287
6288
0
    if (n == NULL || nSz == 0 || e == NULL || eSz == 0
6289
0
            || d == NULL || dSz == 0 || p == NULL || pSz == 0
6290
0
            || q == NULL || qSz == 0 || key == NULL) {
6291
0
        return BAD_FUNC_ARG;
6292
0
    }
6293
6294
0
#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
6295
0
    if ((u == NULL || uSz == 0)
6296
0
            || (dP != NULL && dPSz == 0)
6297
0
            || (dQ != NULL && dQSz == 0)) {
6298
0
        return BAD_FUNC_ARG;
6299
0
    }
6300
#else
6301
    (void)u;
6302
    (void)uSz;
6303
    (void)dP;
6304
    (void)dPSz;
6305
    (void)dQ;
6306
    (void)dQSz;
6307
#endif
6308
6309
0
    if (err == MP_OKAY) {
6310
0
        err = mp_read_unsigned_bin(&key->n, n, nSz);
6311
0
    }
6312
0
    if (err == MP_OKAY) {
6313
0
        err = mp_read_unsigned_bin(&key->e, e, eSz);
6314
0
    }
6315
0
    if (err == MP_OKAY) {
6316
0
        err = mp_read_unsigned_bin(&key->d, d, dSz);
6317
0
    }
6318
0
    if (err == MP_OKAY) {
6319
0
        err = mp_read_unsigned_bin(&key->p, p, pSz);
6320
0
    }
6321
0
    if (err == MP_OKAY) {
6322
0
        err = mp_read_unsigned_bin(&key->q, q, qSz);
6323
0
    }
6324
0
#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
6325
0
    if (err == MP_OKAY) {
6326
0
        err = mp_read_unsigned_bin(&key->u, u, uSz);
6327
0
    }
6328
0
    if (err == MP_OKAY) {
6329
0
        if (dP != NULL) {
6330
0
            err = mp_read_unsigned_bin(&key->dP, dP, dPSz);
6331
0
        }
6332
0
        else {
6333
0
            err = CalcDX(&key->dP, &key->p, &key->d);
6334
0
        }
6335
0
    }
6336
0
    if (err == MP_OKAY) {
6337
0
        if (dQ != NULL) {
6338
0
            err = mp_read_unsigned_bin(&key->dQ, dQ, dQSz);
6339
0
        }
6340
0
        else {
6341
0
            err = CalcDX(&key->dQ, &key->q, &key->d);
6342
0
        }
6343
0
    }
6344
0
#endif
6345
6346
0
    if (err == MP_OKAY) {
6347
0
        key->type = RSA_PRIVATE;
6348
0
    }
6349
0
    else {
6350
0
        mp_clear(&key->n);
6351
0
        mp_clear(&key->e);
6352
0
        mp_forcezero(&key->d);
6353
0
        mp_forcezero(&key->p);
6354
0
        mp_forcezero(&key->q);
6355
0
#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
6356
0
        mp_forcezero(&key->u);
6357
0
        mp_forcezero(&key->dP);
6358
0
        mp_forcezero(&key->dQ);
6359
0
#endif
6360
0
    }
6361
6362
0
    return err;
6363
0
}
6364
6365
int wc_RsaPrivateKeyDecodeRaw(const byte* n, word32 nSz,
6366
        const byte* e, word32 eSz, const byte* d, word32 dSz,
6367
        const byte* u, word32 uSz, const byte* p, word32 pSz,
6368
        const byte* q, word32 qSz, const byte* dP, word32 dPSz,
6369
        const byte* dQ, word32 dQSz, RsaKey* key)
6370
0
{
6371
0
    int err = MP_OKAY;
6372
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_SETKEY)
6373
    int cbRet = WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE);
6374
    WC_DECLARE_VAR(tmpKey, RsaKey, 1, NULL);
6375
#endif
6376
6377
0
    if (n == NULL || nSz == 0 || e == NULL || eSz == 0
6378
0
            || d == NULL || dSz == 0 || p == NULL || pSz == 0
6379
0
            || q == NULL || qSz == 0 || key == NULL) {
6380
0
        err = BAD_FUNC_ARG;
6381
0
    }
6382
6383
0
#if defined(WOLFSSL_KEY_GEN) || defined(OPENSSL_EXTRA) || !defined(RSA_LOW_MEM)
6384
0
    if (err == MP_OKAY) {
6385
0
        if ((u == NULL || uSz == 0)
6386
0
                || (dP != NULL && dPSz == 0)
6387
0
                || (dQ != NULL && dQSz == 0)) {
6388
0
            err = BAD_FUNC_ARG;
6389
0
        }
6390
0
    }
6391
#else
6392
    (void)u;
6393
    (void)uSz;
6394
    (void)dP;
6395
    (void)dPSz;
6396
    (void)dQ;
6397
    (void)dQSz;
6398
#endif
6399
6400
#if defined(WOLF_CRYPTO_CB) && defined(WOLF_CRYPTO_CB_SETKEY)
6401
    #ifndef WOLF_CRYPTO_CB_FIND
6402
    if (err == MP_OKAY && key->devId != INVALID_DEVID)
6403
    #else
6404
    if (err == MP_OKAY)
6405
    #endif
6406
    {
6407
        /* Allocate temp key for callback to export from */
6408
        WC_ALLOC_VAR(tmpKey, RsaKey, 1, key->heap);
6409
        if (!WC_VAR_OK(tmpKey)) {
6410
            return MEMORY_E;
6411
        }
6412
        XMEMSET(tmpKey, 0, sizeof(RsaKey));
6413
6414
        /* Init temp with INVALID_DEVID to prevent callback recursion */
6415
        err = wc_InitRsaKey_ex(tmpKey, key->heap, INVALID_DEVID);
6416
        if (err != MP_OKAY) {
6417
            WC_FREE_VAR(tmpKey, key->heap);
6418
            return err;
6419
        }
6420
6421
        /* Import into temp via software helper (no callback recursion) */
6422
        err = _RsaPrivateKeyDecodeRaw(n, nSz, e, eSz, d, dSz,
6423
            u, uSz, p, pSz, q, qSz, dP, dPSz, dQ, dQSz, tmpKey);
6424
        if (err == MP_OKAY) {
6425
            cbRet = wc_CryptoCb_SetKey(key->devId,
6426
                WC_SETKEY_RSA_PRIV, key, tmpKey,
6427
                wc_RsaEncryptSize(tmpKey), NULL, 0, 0);
6428
        }
6429
6430
        /* wc_FreeRsaKey calls mp_forcezero on all private key components,
6431
         * so no separate ForceZero of the struct is needed here. */
6432
        wc_FreeRsaKey(tmpKey);
6433
        WC_FREE_VAR(tmpKey, key->heap);
6434
6435
        if (err != MP_OKAY) {
6436
            return err;
6437
        }
6438
        if (cbRet != WC_NO_ERR_TRACE(CRYPTOCB_UNAVAILABLE)) {
6439
            return cbRet;
6440
        }
6441
        /* CRYPTOCB_UNAVAILABLE: fall through to software import */
6442
        err = MP_OKAY;
6443
    }
6444
#endif /* WOLF_CRYPTO_CB && WOLF_CRYPTO_CB_SETKEY */
6445
6446
0
    if (err == MP_OKAY) {
6447
0
        err = _RsaPrivateKeyDecodeRaw(n, nSz, e, eSz, d, dSz,
6448
0
            u, uSz, p, pSz, q, qSz, dP, dPSz, dQ, dQSz, key);
6449
0
    }
6450
6451
0
    return err;
6452
0
}
6453
#endif /* WOLFSSL_RSA_PUBLIC_ONLY */
6454
6455
#endif /* NO_RSA */