Coverage Report

Created: 2023-02-22 06:39

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