Coverage Report

Created: 2026-11-12 06:59

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