Coverage Report

Created: 2026-08-15 06:21

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