Coverage Report

Created: 2022-08-24 06:37

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