Coverage Report

Created: 2025-11-16 07:15

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