Coverage Report

Created: 2026-10-16 06:40

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