Coverage Report

Created: 2026-09-14 06:13

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libspdm/os_stub/mbedtlslib/mbedtls/library/rsa.c
Line
Count
Source
1
/*
2
 *  The RSA public-key cryptosystem
3
 *
4
 *  Copyright The Mbed TLS Contributors
5
 *  SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
6
 */
7
8
/*
9
 *  The following sources were referenced in the design of this implementation
10
 *  of the RSA algorithm:
11
 *
12
 *  [1] A method for obtaining digital signatures and public-key cryptosystems
13
 *      R Rivest, A Shamir, and L Adleman
14
 *      http://people.csail.mit.edu/rivest/pubs.html#RSA78
15
 *
16
 *  [2] Handbook of Applied Cryptography - 1997, Chapter 8
17
 *      Menezes, van Oorschot and Vanstone
18
 *
19
 *  [3] Malware Guard Extension: Using SGX to Conceal Cache Attacks
20
 *      Michael Schwarz, Samuel Weiser, Daniel Gruss, Clémentine Maurice and
21
 *      Stefan Mangard
22
 *      https://arxiv.org/abs/1702.08719v2
23
 *
24
 */
25
26
#include "common.h"
27
28
#if defined(MBEDTLS_RSA_C)
29
30
#include "mbedtls/rsa.h"
31
#include "bignum_core.h"
32
#include "bignum_internal.h"
33
#include "rsa_alt_helpers.h"
34
#include "rsa_internal.h"
35
#include "mbedtls/oid.h"
36
#include "mbedtls/asn1write.h"
37
#include "mbedtls/platform_util.h"
38
#include "mbedtls/error.h"
39
#include "constant_time_internal.h"
40
#include "mbedtls/constant_time.h"
41
#include "md_psa.h"
42
43
#include <string.h>
44
45
#if defined(MBEDTLS_PKCS1_V15) && !defined(__OpenBSD__) && !defined(__NetBSD__)
46
#include <stdlib.h>
47
#endif
48
49
#include "mbedtls/platform.h"
50
51
/*
52
 * Wrapper around mbedtls_asn1_get_mpi() that rejects zero.
53
 *
54
 * The value zero is:
55
 * - never a valid value for an RSA parameter
56
 * - interpreted as "omitted, please reconstruct" by mbedtls_rsa_complete().
57
 *
58
 * Since values can't be omitted in PKCS#1, passing a zero value to
59
 * rsa_complete() would be incorrect, so reject zero values early.
60
 */
61
static int asn1_get_nonzero_mpi(unsigned char **p,
62
                                const unsigned char *end,
63
                                mbedtls_mpi *X)
64
1.43k
{
65
1.43k
    int ret;
66
67
1.43k
    ret = mbedtls_asn1_get_mpi(p, end, X);
68
1.43k
    if (ret != 0) {
69
0
        return ret;
70
0
    }
71
72
1.43k
    if (mbedtls_mpi_cmp_int(X, 0) == 0) {
73
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
74
0
    }
75
76
1.43k
    return 0;
77
1.43k
}
78
79
int mbedtls_rsa_parse_key(mbedtls_rsa_context *rsa, const unsigned char *key, size_t keylen)
80
179
{
81
179
    int ret, version;
82
179
    size_t len;
83
179
    unsigned char *p, *end;
84
85
179
    mbedtls_mpi T;
86
179
    mbedtls_mpi_init(&T);
87
88
179
    p = (unsigned char *) key;
89
179
    end = p + keylen;
90
91
    /*
92
     * This function parses the RSAPrivateKey (PKCS#1)
93
     *
94
     *  RSAPrivateKey ::= SEQUENCE {
95
     *      version           Version,
96
     *      modulus           INTEGER,  -- n
97
     *      publicExponent    INTEGER,  -- e
98
     *      privateExponent   INTEGER,  -- d
99
     *      prime1            INTEGER,  -- p
100
     *      prime2            INTEGER,  -- q
101
     *      exponent1         INTEGER,  -- d mod (p-1)
102
     *      exponent2         INTEGER,  -- d mod (q-1)
103
     *      coefficient       INTEGER,  -- (inverse of q) mod p
104
     *      otherPrimeInfos   OtherPrimeInfos OPTIONAL
105
     *  }
106
     */
107
179
    if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
108
179
                                    MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
109
0
        return ret;
110
0
    }
111
112
179
    if (end != p + len) {
113
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
114
0
    }
115
116
179
    if ((ret = mbedtls_asn1_get_int(&p, end, &version)) != 0) {
117
0
        return ret;
118
0
    }
119
120
179
    if (version != 0) {
121
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
122
0
    }
123
124
    /* Import N */
125
179
    if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
126
179
        (ret = mbedtls_rsa_import(rsa, &T, NULL, NULL,
127
179
                                  NULL, NULL)) != 0) {
128
0
        goto cleanup;
129
0
    }
130
131
    /* Import E */
132
179
    if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
133
179
        (ret = mbedtls_rsa_import(rsa, NULL, NULL, NULL,
134
179
                                  NULL, &T)) != 0) {
135
0
        goto cleanup;
136
0
    }
137
138
    /* Import D */
139
179
    if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
140
179
        (ret = mbedtls_rsa_import(rsa, NULL, NULL, NULL,
141
179
                                  &T, NULL)) != 0) {
142
0
        goto cleanup;
143
0
    }
144
145
    /* Import P */
146
179
    if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
147
179
        (ret = mbedtls_rsa_import(rsa, NULL, &T, NULL,
148
179
                                  NULL, NULL)) != 0) {
149
0
        goto cleanup;
150
0
    }
151
152
    /* Import Q */
153
179
    if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
154
179
        (ret = mbedtls_rsa_import(rsa, NULL, NULL, &T,
155
179
                                  NULL, NULL)) != 0) {
156
0
        goto cleanup;
157
0
    }
158
159
179
#if !defined(MBEDTLS_RSA_NO_CRT) && !defined(MBEDTLS_RSA_ALT)
160
    /*
161
     * The RSA CRT parameters DP, DQ and QP are nominally redundant, in
162
     * that they can be easily recomputed from D, P and Q. However by
163
     * parsing them from the PKCS1 structure it is possible to avoid
164
     * recalculating them which both reduces the overhead of loading
165
     * RSA private keys into memory and also avoids side channels which
166
     * can arise when computing those values, since all of D, P, and Q
167
     * are secret. See https://eprint.iacr.org/2020/055 for a
168
     * description of one such attack.
169
     */
170
171
    /* Import DP */
172
179
    if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
173
179
        (ret = mbedtls_mpi_copy(&rsa->DP, &T)) != 0) {
174
0
        goto cleanup;
175
0
    }
176
177
    /* Import DQ */
178
179
    if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
179
179
        (ret = mbedtls_mpi_copy(&rsa->DQ, &T)) != 0) {
180
0
        goto cleanup;
181
0
    }
182
183
    /* Import QP */
184
179
    if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
185
179
        (ret = mbedtls_mpi_copy(&rsa->QP, &T)) != 0) {
186
0
        goto cleanup;
187
0
    }
188
189
#else
190
    /* Verify existence of the CRT params */
191
    if ((ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
192
        (ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0 ||
193
        (ret = asn1_get_nonzero_mpi(&p, end, &T)) != 0) {
194
        goto cleanup;
195
    }
196
#endif
197
198
    /* rsa_complete() doesn't complete anything with the default
199
     * implementation but is still called:
200
     * - for the benefit of alternative implementation that may want to
201
     *   pre-compute stuff beyond what's provided (eg Montgomery factors)
202
     * - as is also sanity-checks the key
203
     *
204
     * Furthermore, we also check the public part for consistency with
205
     * mbedtls_pk_parse_pubkey(), as it includes size minima for example.
206
     */
207
179
    if ((ret = mbedtls_rsa_complete(rsa)) != 0 ||
208
179
        (ret = mbedtls_rsa_check_pubkey(rsa)) != 0) {
209
0
        goto cleanup;
210
0
    }
211
212
179
    if (p != end) {
213
0
        ret = MBEDTLS_ERR_ASN1_LENGTH_MISMATCH;
214
0
    }
215
216
179
cleanup:
217
218
179
    mbedtls_mpi_free(&T);
219
220
179
    if (ret != 0) {
221
0
        mbedtls_rsa_free(rsa);
222
0
    }
223
224
179
    return ret;
225
179
}
226
227
int mbedtls_rsa_parse_pubkey(mbedtls_rsa_context *rsa, const unsigned char *key, size_t keylen)
228
11.4k
{
229
11.4k
    unsigned char *p = (unsigned char *) key;
230
11.4k
    unsigned char *end = (unsigned char *) (key + keylen);
231
11.4k
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
232
11.4k
    size_t len;
233
234
    /*
235
     *  RSAPublicKey ::= SEQUENCE {
236
     *      modulus           INTEGER,  -- n
237
     *      publicExponent    INTEGER   -- e
238
     *  }
239
     */
240
241
11.4k
    if ((ret = mbedtls_asn1_get_tag(&p, end, &len,
242
11.4k
                                    MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) != 0) {
243
7
        return ret;
244
7
    }
245
246
11.4k
    if (end != p + len) {
247
4
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
248
4
    }
249
250
    /* Import N */
251
11.4k
    if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_INTEGER)) != 0) {
252
8
        return ret;
253
8
    }
254
255
11.4k
    if ((ret = mbedtls_rsa_import_raw(rsa, p, len, NULL, 0, NULL, 0,
256
11.4k
                                      NULL, 0, NULL, 0)) != 0) {
257
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
258
0
    }
259
260
11.4k
    p += len;
261
262
    /* Import E */
263
11.4k
    if ((ret = mbedtls_asn1_get_tag(&p, end, &len, MBEDTLS_ASN1_INTEGER)) != 0) {
264
14
        return ret;
265
14
    }
266
267
11.4k
    if ((ret = mbedtls_rsa_import_raw(rsa, NULL, 0, NULL, 0, NULL, 0,
268
11.4k
                                      NULL, 0, p, len)) != 0) {
269
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
270
0
    }
271
272
11.4k
    p += len;
273
274
11.4k
    if (mbedtls_rsa_complete(rsa) != 0 ||
275
11.4k
        mbedtls_rsa_check_pubkey(rsa) != 0) {
276
65
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
277
65
    }
278
279
11.3k
    if (p != end) {
280
173
        return MBEDTLS_ERR_ASN1_LENGTH_MISMATCH;
281
173
    }
282
283
11.2k
    return 0;
284
11.3k
}
285
286
int mbedtls_rsa_write_key(const mbedtls_rsa_context *rsa, unsigned char *start,
287
                          unsigned char **p)
288
0
{
289
0
    size_t len = 0;
290
0
    int ret;
291
292
0
    mbedtls_mpi T; /* Temporary holding the exported parameters */
293
294
    /*
295
     * Export the parameters one after another to avoid simultaneous copies.
296
     */
297
298
0
    mbedtls_mpi_init(&T);
299
300
    /* Export QP */
301
0
    if ((ret = mbedtls_rsa_export_crt(rsa, NULL, NULL, &T)) != 0 ||
302
0
        (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
303
0
        goto end_of_export;
304
0
    }
305
0
    len += ret;
306
307
    /* Export DQ */
308
0
    if ((ret = mbedtls_rsa_export_crt(rsa, NULL, &T, NULL)) != 0 ||
309
0
        (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
310
0
        goto end_of_export;
311
0
    }
312
0
    len += ret;
313
314
    /* Export DP */
315
0
    if ((ret = mbedtls_rsa_export_crt(rsa, &T, NULL, NULL)) != 0 ||
316
0
        (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
317
0
        goto end_of_export;
318
0
    }
319
0
    len += ret;
320
321
    /* Export Q */
322
0
    if ((ret = mbedtls_rsa_export(rsa, NULL, NULL, &T, NULL, NULL)) != 0 ||
323
0
        (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
324
0
        goto end_of_export;
325
0
    }
326
0
    len += ret;
327
328
    /* Export P */
329
0
    if ((ret = mbedtls_rsa_export(rsa, NULL, &T, NULL, NULL, NULL)) != 0 ||
330
0
        (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
331
0
        goto end_of_export;
332
0
    }
333
0
    len += ret;
334
335
    /* Export D */
336
0
    if ((ret = mbedtls_rsa_export(rsa, NULL, NULL, NULL, &T, NULL)) != 0 ||
337
0
        (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
338
0
        goto end_of_export;
339
0
    }
340
0
    len += ret;
341
342
    /* Export E */
343
0
    if ((ret = mbedtls_rsa_export(rsa, NULL, NULL, NULL, NULL, &T)) != 0 ||
344
0
        (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
345
0
        goto end_of_export;
346
0
    }
347
0
    len += ret;
348
349
    /* Export N */
350
0
    if ((ret = mbedtls_rsa_export(rsa, &T, NULL, NULL, NULL, NULL)) != 0 ||
351
0
        (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
352
0
        goto end_of_export;
353
0
    }
354
0
    len += ret;
355
356
0
end_of_export:
357
358
0
    mbedtls_mpi_free(&T);
359
0
    if (ret < 0) {
360
0
        return ret;
361
0
    }
362
363
0
    MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_int(p, start, 0));
364
0
    MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, len));
365
0
    MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(p, start,
366
0
                                                     MBEDTLS_ASN1_CONSTRUCTED |
367
0
                                                     MBEDTLS_ASN1_SEQUENCE));
368
369
0
    return (int) len;
370
0
}
371
372
/*
373
 *  RSAPublicKey ::= SEQUENCE {
374
 *      modulus           INTEGER,  -- n
375
 *      publicExponent    INTEGER   -- e
376
 *  }
377
 */
378
int mbedtls_rsa_write_pubkey(const mbedtls_rsa_context *rsa, unsigned char *start,
379
                             unsigned char **p)
380
0
{
381
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
382
0
    size_t len = 0;
383
0
    mbedtls_mpi T;
384
385
0
    mbedtls_mpi_init(&T);
386
387
    /* Export E */
388
0
    if ((ret = mbedtls_rsa_export(rsa, NULL, NULL, NULL, NULL, &T)) != 0 ||
389
0
        (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
390
0
        goto end_of_export;
391
0
    }
392
0
    len += ret;
393
394
    /* Export N */
395
0
    if ((ret = mbedtls_rsa_export(rsa, &T, NULL, NULL, NULL, NULL)) != 0 ||
396
0
        (ret = mbedtls_asn1_write_mpi(p, start, &T)) < 0) {
397
0
        goto end_of_export;
398
0
    }
399
0
    len += ret;
400
401
0
end_of_export:
402
403
0
    mbedtls_mpi_free(&T);
404
0
    if (ret < 0) {
405
0
        return ret;
406
0
    }
407
408
0
    MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_len(p, start, len));
409
0
    MBEDTLS_ASN1_CHK_ADD(len, mbedtls_asn1_write_tag(p, start, MBEDTLS_ASN1_CONSTRUCTED |
410
0
                                                     MBEDTLS_ASN1_SEQUENCE));
411
412
0
    return (int) len;
413
0
}
414
415
#if defined(MBEDTLS_PKCS1_V15) && defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_RSA_ALT)
416
417
/** This function performs the unpadding part of a PKCS#1 v1.5 decryption
418
 *  operation (EME-PKCS1-v1_5 decoding).
419
 *
420
 * \note The return value from this function is a sensitive value
421
 *       (this is unusual). #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE shouldn't happen
422
 *       in a well-written application, but 0 vs #MBEDTLS_ERR_RSA_INVALID_PADDING
423
 *       is often a situation that an attacker can provoke and leaking which
424
 *       one is the result is precisely the information the attacker wants.
425
 *
426
 * \param input          The input buffer which is the payload inside PKCS#1v1.5
427
 *                       encryption padding, called the "encoded message EM"
428
 *                       by the terminology.
429
 * \param ilen           The length of the payload in the \p input buffer.
430
 * \param output         The buffer for the payload, called "message M" by the
431
 *                       PKCS#1 terminology. This must be a writable buffer of
432
 *                       length \p output_max_len bytes.
433
 * \param olen           The address at which to store the length of
434
 *                       the payload. This must not be \c NULL.
435
 * \param output_max_len The length in bytes of the output buffer \p output.
436
 *
437
 * \return      \c 0 on success.
438
 * \return      #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE
439
 *              The output buffer is too small for the unpadded payload.
440
 * \return      #MBEDTLS_ERR_RSA_INVALID_PADDING
441
 *              The input doesn't contain properly formatted padding.
442
 */
443
static int mbedtls_ct_rsaes_pkcs1_v15_unpadding(unsigned char *input,
444
                                                size_t ilen,
445
                                                unsigned char *output,
446
                                                size_t output_max_len,
447
                                                size_t *olen)
448
0
{
449
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
450
0
    size_t i, plaintext_max_size;
451
452
    /* The following variables take sensitive values: their value must
453
     * not leak into the observable behavior of the function other than
454
     * the designated outputs (output, olen, return value). Otherwise
455
     * this would open the execution of the function to
456
     * side-channel-based variants of the Bleichenbacher padding oracle
457
     * attack. Potential side channels include overall timing, memory
458
     * access patterns (especially visible to an adversary who has access
459
     * to a shared memory cache), and branches (especially visible to
460
     * an adversary who has access to a shared code cache or to a shared
461
     * branch predictor). */
462
0
    size_t pad_count = 0;
463
0
    mbedtls_ct_condition_t bad;
464
0
    mbedtls_ct_condition_t pad_done;
465
0
    size_t plaintext_size = 0;
466
0
    mbedtls_ct_condition_t output_too_large;
467
468
0
    plaintext_max_size = (output_max_len > ilen - 11) ? ilen - 11
469
0
                                                        : output_max_len;
470
471
    /* Check and get padding length in constant time and constant
472
     * memory trace. The first byte must be 0. */
473
0
    bad = mbedtls_ct_bool(input[0]);
474
475
476
    /* Decode EME-PKCS1-v1_5 padding: 0x00 || 0x02 || PS || 0x00
477
     * where PS must be at least 8 nonzero bytes. */
478
0
    bad = mbedtls_ct_bool_or(bad, mbedtls_ct_uint_ne(input[1], MBEDTLS_RSA_CRYPT));
479
480
    /* Read the whole buffer. Set pad_done to nonzero if we find
481
     * the 0x00 byte and remember the padding length in pad_count. */
482
0
    pad_done = MBEDTLS_CT_FALSE;
483
0
    for (i = 2; i < ilen; i++) {
484
0
        mbedtls_ct_condition_t found = mbedtls_ct_uint_eq(input[i], 0);
485
0
        pad_done   = mbedtls_ct_bool_or(pad_done, found);
486
0
        pad_count += mbedtls_ct_uint_if_else_0(mbedtls_ct_bool_not(pad_done), 1);
487
0
    }
488
489
    /* If pad_done is still zero, there's no data, only unfinished padding. */
490
0
    bad = mbedtls_ct_bool_or(bad, mbedtls_ct_bool_not(pad_done));
491
492
    /* There must be at least 8 bytes of padding. */
493
0
    bad = mbedtls_ct_bool_or(bad, mbedtls_ct_uint_gt(8, pad_count));
494
495
    /* If the padding is valid, set plaintext_size to the number of
496
     * remaining bytes after stripping the padding. If the padding
497
     * is invalid, avoid leaking this fact through the size of the
498
     * output: use the maximum message size that fits in the output
499
     * buffer. Do it without branches to avoid leaking the padding
500
     * validity through timing. RSA keys are small enough that all the
501
     * size_t values involved fit in unsigned int. */
502
0
    plaintext_size = mbedtls_ct_uint_if(
503
0
        bad, (unsigned) plaintext_max_size,
504
0
        (unsigned) (ilen - pad_count - 3));
505
506
    /* Set output_too_large to 0 if the plaintext fits in the output
507
     * buffer and to 1 otherwise. */
508
0
    output_too_large = mbedtls_ct_uint_gt(plaintext_size,
509
0
                                          plaintext_max_size);
510
511
    /* Set ret without branches to avoid timing attacks. Return:
512
     * - INVALID_PADDING if the padding is bad (bad != 0).
513
     * - OUTPUT_TOO_LARGE if the padding is good but the decrypted
514
     *   plaintext does not fit in the output buffer.
515
     * - 0 if the padding is correct. */
516
0
    ret = mbedtls_ct_error_if(
517
0
        bad,
518
0
        MBEDTLS_ERR_RSA_INVALID_PADDING,
519
0
        mbedtls_ct_error_if_else_0(output_too_large, MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE)
520
0
        );
521
522
    /* If the padding is bad or the plaintext is too large, zero the
523
     * data that we're about to copy to the output buffer.
524
     * We need to copy the same amount of data
525
     * from the same buffer whether the padding is good or not to
526
     * avoid leaking the padding validity through overall timing or
527
     * through memory or cache access patterns. */
528
0
    mbedtls_ct_zeroize_if(mbedtls_ct_bool_or(bad, output_too_large), input + 11, ilen - 11);
529
530
    /* If the plaintext is too large, truncate it to the buffer size.
531
     * Copy anyway to avoid revealing the length through timing, because
532
     * revealing the length is as bad as revealing the padding validity
533
     * for a Bleichenbacher attack. */
534
0
    plaintext_size = mbedtls_ct_uint_if(output_too_large,
535
0
                                        (unsigned) plaintext_max_size,
536
0
                                        (unsigned) plaintext_size);
537
538
    /* Move the plaintext to the leftmost position where it can start in
539
     * the working buffer, i.e. make it start plaintext_max_size from
540
     * the end of the buffer. Do this with a memory access trace that
541
     * does not depend on the plaintext size. After this move, the
542
     * starting location of the plaintext is no longer sensitive
543
     * information. */
544
0
    mbedtls_ct_memmove_left(input + ilen - plaintext_max_size,
545
0
                            plaintext_max_size,
546
0
                            plaintext_max_size - plaintext_size);
547
548
    /* Finally copy the decrypted plaintext plus trailing zeros into the output
549
     * buffer. If output_max_len is 0, then output may be an invalid pointer
550
     * and the result of memcpy() would be undefined; prevent undefined
551
     * behavior making sure to depend only on output_max_len (the size of the
552
     * user-provided output buffer), which is independent from plaintext
553
     * length, validity of padding, success of the decryption, and other
554
     * secrets. */
555
0
    if (output_max_len != 0) {
556
0
        memcpy(output, input + ilen - plaintext_max_size, plaintext_max_size);
557
0
    }
558
559
    /* Report the amount of data we copied to the output buffer. In case
560
     * of errors (bad padding or output too large), the value of *olen
561
     * when this function returns is not specified. Making it equivalent
562
     * to the good case limits the risks of leaking the padding validity. */
563
0
    *olen = plaintext_size;
564
565
0
    return ret;
566
0
}
567
568
#endif /* MBEDTLS_PKCS1_V15 && MBEDTLS_RSA_C && ! MBEDTLS_RSA_ALT */
569
570
#if !defined(MBEDTLS_RSA_ALT)
571
572
int mbedtls_rsa_import(mbedtls_rsa_context *ctx,
573
                       const mbedtls_mpi *N,
574
                       const mbedtls_mpi *P, const mbedtls_mpi *Q,
575
                       const mbedtls_mpi *D, const mbedtls_mpi *E)
576
895
{
577
895
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
578
579
895
    if ((N != NULL && (ret = mbedtls_mpi_copy(&ctx->N, N)) != 0) ||
580
895
        (P != NULL && (ret = mbedtls_mpi_copy(&ctx->P, P)) != 0) ||
581
895
        (Q != NULL && (ret = mbedtls_mpi_copy(&ctx->Q, Q)) != 0) ||
582
895
        (D != NULL && (ret = mbedtls_mpi_copy(&ctx->D, D)) != 0) ||
583
895
        (E != NULL && (ret = mbedtls_mpi_copy(&ctx->E, E)) != 0)) {
584
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
585
0
    }
586
587
895
    if (N != NULL) {
588
179
        ctx->len = mbedtls_mpi_size(&ctx->N);
589
179
    }
590
591
895
    return 0;
592
895
}
593
594
int mbedtls_rsa_import_raw(mbedtls_rsa_context *ctx,
595
                           unsigned char const *N, size_t N_len,
596
                           unsigned char const *P, size_t P_len,
597
                           unsigned char const *Q, size_t Q_len,
598
                           unsigned char const *D, size_t D_len,
599
                           unsigned char const *E, size_t E_len)
600
22.9k
{
601
22.9k
    int ret = 0;
602
603
22.9k
    if (N != NULL) {
604
11.4k
        MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->N, N, N_len));
605
11.4k
        ctx->len = mbedtls_mpi_size(&ctx->N);
606
11.4k
    }
607
608
22.9k
    if (P != NULL) {
609
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->P, P, P_len));
610
0
    }
611
612
22.9k
    if (Q != NULL) {
613
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->Q, Q, Q_len));
614
0
    }
615
616
22.9k
    if (D != NULL) {
617
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->D, D, D_len));
618
0
    }
619
620
22.9k
    if (E != NULL) {
621
11.4k
        MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->E, E, E_len));
622
11.4k
    }
623
624
22.9k
cleanup:
625
626
22.9k
    if (ret != 0) {
627
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
628
0
    }
629
630
22.9k
    return 0;
631
22.9k
}
632
633
/*
634
 * Checks whether the context fields are set in such a way
635
 * that the RSA primitives will be able to execute without error.
636
 * It does *not* make guarantees for consistency of the parameters.
637
 */
638
static int rsa_check_context(mbedtls_rsa_context const *ctx, int is_priv,
639
                             int blinding_needed)
640
24.8k
{
641
24.8k
#if !defined(MBEDTLS_RSA_NO_CRT)
642
    /* blinding_needed is only used for NO_CRT to decide whether
643
     * P,Q need to be present or not. */
644
24.8k
    ((void) blinding_needed);
645
24.8k
#endif
646
647
24.8k
    if (ctx->len != mbedtls_mpi_size(&ctx->N) ||
648
24.8k
        ctx->len > MBEDTLS_MPI_MAX_SIZE) {
649
3
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
650
3
    }
651
652
    /*
653
     * 1. Modular exponentiation needs positive, odd moduli.
654
     */
655
656
    /* Modular exponentiation wrt. N is always used for
657
     * RSA public key operations. */
658
24.8k
    if (mbedtls_mpi_cmp_int(&ctx->N, 0) <= 0 ||
659
24.8k
        mbedtls_mpi_get_bit(&ctx->N, 0) == 0) {
660
9
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
661
9
    }
662
663
24.8k
#if !defined(MBEDTLS_RSA_NO_CRT)
664
    /* Modular exponentiation for P and Q is only
665
     * used for private key operations and if CRT
666
     * is used. */
667
24.8k
    if (is_priv &&
668
537
        (mbedtls_mpi_cmp_int(&ctx->P, 0) <= 0 ||
669
537
         mbedtls_mpi_get_bit(&ctx->P, 0) == 0 ||
670
537
         mbedtls_mpi_cmp_int(&ctx->Q, 0) <= 0 ||
671
537
         mbedtls_mpi_get_bit(&ctx->Q, 0) == 0)) {
672
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
673
0
    }
674
24.8k
#endif /* !MBEDTLS_RSA_NO_CRT */
675
676
    /*
677
     * 2. Exponents must be positive
678
     */
679
680
    /* Always need E for public key operations */
681
24.8k
    if (mbedtls_mpi_cmp_int(&ctx->E, 0) <= 0) {
682
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
683
0
    }
684
685
#if defined(MBEDTLS_RSA_NO_CRT)
686
    /* For private key operations, use D or DP & DQ
687
     * as (unblinded) exponents. */
688
    if (is_priv && mbedtls_mpi_cmp_int(&ctx->D, 0) <= 0) {
689
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
690
    }
691
#else
692
24.8k
    if (is_priv &&
693
537
        (mbedtls_mpi_cmp_int(&ctx->DP, 0) <= 0 ||
694
537
         mbedtls_mpi_cmp_int(&ctx->DQ, 0) <= 0)) {
695
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
696
0
    }
697
24.8k
#endif /* MBEDTLS_RSA_NO_CRT */
698
699
    /* Blinding shouldn't make exponents negative either,
700
     * so check that P, Q >= 1 if that hasn't yet been
701
     * done as part of 1. */
702
#if defined(MBEDTLS_RSA_NO_CRT)
703
    if (is_priv && blinding_needed &&
704
        (mbedtls_mpi_cmp_int(&ctx->P, 0) <= 0 ||
705
         mbedtls_mpi_cmp_int(&ctx->Q, 0) <= 0)) {
706
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
707
    }
708
#endif
709
710
    /* It wouldn't lead to an error if it wasn't satisfied,
711
     * but check for QP >= 1 nonetheless. */
712
24.8k
#if !defined(MBEDTLS_RSA_NO_CRT)
713
24.8k
    if (is_priv &&
714
537
        mbedtls_mpi_cmp_int(&ctx->QP, 0) <= 0) {
715
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
716
0
    }
717
24.8k
#endif
718
719
24.8k
    return 0;
720
24.8k
}
721
722
int mbedtls_rsa_complete(mbedtls_rsa_context *ctx)
723
11.8k
{
724
11.8k
    int ret = 0;
725
11.8k
    int have_N, have_P, have_Q, have_D, have_E;
726
11.8k
#if !defined(MBEDTLS_RSA_NO_CRT)
727
11.8k
    int have_DP, have_DQ, have_QP;
728
11.8k
#endif
729
11.8k
    int n_missing, pq_missing, d_missing, is_pub, is_priv;
730
731
11.8k
    have_N = (mbedtls_mpi_cmp_int(&ctx->N, 0) != 0);
732
11.8k
    have_P = (mbedtls_mpi_cmp_int(&ctx->P, 0) != 0);
733
11.8k
    have_Q = (mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0);
734
11.8k
    have_D = (mbedtls_mpi_cmp_int(&ctx->D, 0) != 0);
735
11.8k
    have_E = (mbedtls_mpi_cmp_int(&ctx->E, 0) != 0);
736
737
11.8k
#if !defined(MBEDTLS_RSA_NO_CRT)
738
11.8k
    have_DP = (mbedtls_mpi_cmp_int(&ctx->DP, 0) != 0);
739
11.8k
    have_DQ = (mbedtls_mpi_cmp_int(&ctx->DQ, 0) != 0);
740
11.8k
    have_QP = (mbedtls_mpi_cmp_int(&ctx->QP, 0) != 0);
741
11.8k
#endif
742
743
    /*
744
     * Check whether provided parameters are enough
745
     * to deduce all others. The following incomplete
746
     * parameter sets for private keys are supported:
747
     *
748
     * (1) P, Q missing.
749
     * (2) D and potentially N missing.
750
     *
751
     */
752
753
11.8k
    n_missing  =              have_P &&  have_Q &&  have_D && have_E;
754
11.8k
    pq_missing =   have_N && !have_P && !have_Q &&  have_D && have_E;
755
11.8k
    d_missing  =              have_P &&  have_Q && !have_D && have_E;
756
11.8k
    is_pub     =   have_N && !have_P && !have_Q && !have_D && have_E;
757
758
    /* These three alternatives are mutually exclusive */
759
11.8k
    is_priv = n_missing || pq_missing || d_missing;
760
761
11.8k
    if (!is_priv && !is_pub) {
762
15
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
763
15
    }
764
765
    /*
766
     * Step 1: Deduce N if P, Q are provided.
767
     */
768
769
11.7k
    if (!have_N && have_P && have_Q) {
770
0
        if ((ret = mbedtls_mpi_mul_mpi(&ctx->N, &ctx->P,
771
0
                                       &ctx->Q)) != 0) {
772
0
            return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
773
0
        }
774
775
0
        ctx->len = mbedtls_mpi_size(&ctx->N);
776
0
    }
777
778
    /*
779
     * Step 2: Deduce and verify all remaining core parameters.
780
     */
781
782
11.7k
    if (pq_missing) {
783
0
        ret = mbedtls_rsa_deduce_primes(&ctx->N, &ctx->E, &ctx->D,
784
0
                                        &ctx->P, &ctx->Q);
785
0
        if (ret != 0) {
786
0
            return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
787
0
        }
788
789
11.7k
    } else if (d_missing) {
790
0
        if ((ret = mbedtls_rsa_deduce_private_exponent(&ctx->P,
791
0
                                                       &ctx->Q,
792
0
                                                       &ctx->E,
793
0
                                                       &ctx->D)) != 0) {
794
0
            return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
795
0
        }
796
0
    }
797
798
    /*
799
     * Step 3: Deduce all additional parameters specific
800
     *         to our current RSA implementation.
801
     */
802
803
11.7k
#if !defined(MBEDTLS_RSA_NO_CRT)
804
11.7k
    if (is_priv && !(have_DP && have_DQ && have_QP)) {
805
0
        ret = mbedtls_rsa_deduce_crt(&ctx->P,  &ctx->Q,  &ctx->D,
806
0
                                     &ctx->DP, &ctx->DQ, &ctx->QP);
807
0
        if (ret != 0) {
808
0
            return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
809
0
        }
810
0
    }
811
11.7k
#endif /* MBEDTLS_RSA_NO_CRT */
812
813
    /*
814
     * Step 3: Basic sanity checks
815
     */
816
817
11.7k
    return rsa_check_context(ctx, is_priv, 1);
818
11.7k
}
819
820
int mbedtls_rsa_export_raw(const mbedtls_rsa_context *ctx,
821
                           unsigned char *N, size_t N_len,
822
                           unsigned char *P, size_t P_len,
823
                           unsigned char *Q, size_t Q_len,
824
                           unsigned char *D, size_t D_len,
825
                           unsigned char *E, size_t E_len)
826
0
{
827
0
    int ret = 0;
828
0
    int is_priv;
829
830
    /* Check if key is private or public */
831
0
    is_priv =
832
0
        mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 &&
833
0
        mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 &&
834
0
        mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 &&
835
0
        mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 &&
836
0
        mbedtls_mpi_cmp_int(&ctx->E, 0) != 0;
837
838
0
    if (!is_priv) {
839
        /* If we're trying to export private parameters for a public key,
840
         * something must be wrong. */
841
0
        if (P != NULL || Q != NULL || D != NULL) {
842
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
843
0
        }
844
845
0
    }
846
847
0
    if (N != NULL) {
848
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->N, N, N_len));
849
0
    }
850
851
0
    if (P != NULL) {
852
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->P, P, P_len));
853
0
    }
854
855
0
    if (Q != NULL) {
856
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->Q, Q, Q_len));
857
0
    }
858
859
0
    if (D != NULL) {
860
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->D, D, D_len));
861
0
    }
862
863
0
    if (E != NULL) {
864
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->E, E, E_len));
865
0
    }
866
867
0
cleanup:
868
869
0
    return ret;
870
0
}
871
872
int mbedtls_rsa_export(const mbedtls_rsa_context *ctx,
873
                       mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q,
874
                       mbedtls_mpi *D, mbedtls_mpi *E)
875
0
{
876
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
877
0
    int is_priv;
878
879
    /* Check if key is private or public */
880
0
    is_priv =
881
0
        mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 &&
882
0
        mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 &&
883
0
        mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 &&
884
0
        mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 &&
885
0
        mbedtls_mpi_cmp_int(&ctx->E, 0) != 0;
886
887
0
    if (!is_priv) {
888
        /* If we're trying to export private parameters for a public key,
889
         * something must be wrong. */
890
0
        if (P != NULL || Q != NULL || D != NULL) {
891
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
892
0
        }
893
894
0
    }
895
896
    /* Export all requested core parameters. */
897
898
0
    if ((N != NULL && (ret = mbedtls_mpi_copy(N, &ctx->N)) != 0) ||
899
0
        (P != NULL && (ret = mbedtls_mpi_copy(P, &ctx->P)) != 0) ||
900
0
        (Q != NULL && (ret = mbedtls_mpi_copy(Q, &ctx->Q)) != 0) ||
901
0
        (D != NULL && (ret = mbedtls_mpi_copy(D, &ctx->D)) != 0) ||
902
0
        (E != NULL && (ret = mbedtls_mpi_copy(E, &ctx->E)) != 0)) {
903
0
        return ret;
904
0
    }
905
906
0
    return 0;
907
0
}
908
909
/*
910
 * Export CRT parameters
911
 * This must also be implemented if CRT is not used, for being able to
912
 * write DER encoded RSA keys. The helper function mbedtls_rsa_deduce_crt
913
 * can be used in this case.
914
 */
915
int mbedtls_rsa_export_crt(const mbedtls_rsa_context *ctx,
916
                           mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP)
917
0
{
918
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
919
0
    int is_priv;
920
921
    /* Check if key is private or public */
922
0
    is_priv =
923
0
        mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 &&
924
0
        mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 &&
925
0
        mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 &&
926
0
        mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 &&
927
0
        mbedtls_mpi_cmp_int(&ctx->E, 0) != 0;
928
929
0
    if (!is_priv) {
930
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
931
0
    }
932
933
0
#if !defined(MBEDTLS_RSA_NO_CRT)
934
    /* Export all requested blinding parameters. */
935
0
    if ((DP != NULL && (ret = mbedtls_mpi_copy(DP, &ctx->DP)) != 0) ||
936
0
        (DQ != NULL && (ret = mbedtls_mpi_copy(DQ, &ctx->DQ)) != 0) ||
937
0
        (QP != NULL && (ret = mbedtls_mpi_copy(QP, &ctx->QP)) != 0)) {
938
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
939
0
    }
940
#else
941
    if ((ret = mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D,
942
                                      DP, DQ, QP)) != 0) {
943
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
944
    }
945
#endif
946
947
0
    return 0;
948
0
}
949
950
/*
951
 * Initialize an RSA context
952
 */
953
void mbedtls_rsa_init(mbedtls_rsa_context *ctx)
954
12.7k
{
955
12.7k
    memset(ctx, 0, sizeof(mbedtls_rsa_context));
956
957
12.7k
    ctx->padding = MBEDTLS_RSA_PKCS_V15;
958
12.7k
    ctx->hash_id = MBEDTLS_MD_NONE;
959
960
#if defined(MBEDTLS_THREADING_C)
961
    /* Set ctx->ver to nonzero to indicate that the mutex has been
962
     * initialized and will need to be freed. */
963
    ctx->ver = 1;
964
    mbedtls_mutex_init(&ctx->mutex);
965
#endif
966
12.7k
}
967
968
/*
969
 * Set padding for an existing RSA context
970
 */
971
int mbedtls_rsa_set_padding(mbedtls_rsa_context *ctx, int padding,
972
                            mbedtls_md_type_t hash_id)
973
184
{
974
184
    switch (padding) {
975
0
#if defined(MBEDTLS_PKCS1_V15)
976
184
        case MBEDTLS_RSA_PKCS_V15:
977
184
            break;
978
0
#endif
979
980
0
#if defined(MBEDTLS_PKCS1_V21)
981
0
        case MBEDTLS_RSA_PKCS_V21:
982
0
            break;
983
0
#endif
984
0
        default:
985
0
            return MBEDTLS_ERR_RSA_INVALID_PADDING;
986
184
    }
987
988
184
#if defined(MBEDTLS_PKCS1_V21)
989
184
    if ((padding == MBEDTLS_RSA_PKCS_V21) &&
990
0
        (hash_id != MBEDTLS_MD_NONE)) {
991
        /* Just make sure this hash is supported in this build. */
992
0
        if (mbedtls_md_info_from_type(hash_id) == NULL) {
993
0
            return MBEDTLS_ERR_RSA_INVALID_PADDING;
994
0
        }
995
0
    }
996
184
#endif /* MBEDTLS_PKCS1_V21 */
997
998
184
    ctx->padding = padding;
999
184
    ctx->hash_id = hash_id;
1000
1001
184
    return 0;
1002
184
}
1003
1004
/*
1005
 * Get padding mode of initialized RSA context
1006
 */
1007
int mbedtls_rsa_get_padding_mode(const mbedtls_rsa_context *ctx)
1008
0
{
1009
0
    return ctx->padding;
1010
0
}
1011
1012
/*
1013
 * Get hash identifier of mbedtls_md_type_t type
1014
 */
1015
int mbedtls_rsa_get_md_alg(const mbedtls_rsa_context *ctx)
1016
0
{
1017
0
    return ctx->hash_id;
1018
0
}
1019
1020
/*
1021
 * Get length in bits of RSA modulus
1022
 */
1023
size_t mbedtls_rsa_get_bitlen(const mbedtls_rsa_context *ctx)
1024
2.73k
{
1025
2.73k
    return mbedtls_mpi_bitlen(&ctx->N);
1026
2.73k
}
1027
1028
/*
1029
 * Get length in bytes of RSA modulus
1030
 */
1031
size_t mbedtls_rsa_get_len(const mbedtls_rsa_context *ctx)
1032
1.44k
{
1033
1.44k
    return ctx->len;
1034
1.44k
}
1035
1036
#if defined(MBEDTLS_GENPRIME)
1037
1038
/*
1039
 * Generate an RSA keypair
1040
 *
1041
 * This generation method follows the RSA key pair generation procedure of
1042
 * FIPS 186-4 if 2^16 < exponent < 2^256 and nbits = 2048 or nbits = 3072.
1043
 */
1044
int mbedtls_rsa_gen_key(mbedtls_rsa_context *ctx,
1045
                        int (*f_rng)(void *, unsigned char *, size_t),
1046
                        void *p_rng,
1047
                        unsigned int nbits, int exponent)
1048
0
{
1049
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1050
0
    mbedtls_mpi H;
1051
0
    int prime_quality = 0;
1052
1053
    /*
1054
     * If the modulus is 1024 bit long or shorter, then the security strength of
1055
     * the RSA algorithm is less than or equal to 80 bits and therefore an error
1056
     * rate of 2^-80 is sufficient.
1057
     */
1058
0
    if (nbits > 1024) {
1059
0
        prime_quality = MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR;
1060
0
    }
1061
1062
0
    mbedtls_mpi_init(&H);
1063
1064
0
    if (exponent < 3 || nbits % 2 != 0) {
1065
0
        ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1066
0
        goto cleanup;
1067
0
    }
1068
1069
0
    if (nbits < MBEDTLS_RSA_GEN_KEY_MIN_BITS) {
1070
0
        ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1071
0
        goto cleanup;
1072
0
    }
1073
1074
    /*
1075
     * find primes P and Q with Q < P so that:
1076
     * 1.  |P-Q| > 2^( nbits / 2 - 100 )
1077
     * 2.  GCD( E, (P-1)*(Q-1) ) == 1
1078
     * 3.  E^-1 mod LCM(P-1, Q-1) > 2^( nbits / 2 )
1079
     */
1080
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&ctx->E, exponent));
1081
1082
0
    do {
1083
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_gen_prime(&ctx->P, nbits >> 1,
1084
0
                                              prime_quality, f_rng, p_rng));
1085
1086
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_gen_prime(&ctx->Q, nbits >> 1,
1087
0
                                              prime_quality, f_rng, p_rng));
1088
1089
        /* make sure the difference between p and q is not too small (FIPS 186-4 §B.3.3 step 5.4) */
1090
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&H, &ctx->P, &ctx->Q));
1091
0
        if (mbedtls_mpi_bitlen(&H) <= ((nbits >= 200) ? ((nbits >> 1) - 99) : 0)) {
1092
0
            continue;
1093
0
        }
1094
1095
        /* not required by any standards, but some users rely on the fact that P > Q */
1096
0
        if (H.s < 0) {
1097
0
            mbedtls_mpi_swap(&ctx->P, &ctx->Q);
1098
0
        }
1099
1100
        /* Compute D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b))
1101
         * if it exists (FIPS 186-4 §B.3.1 criterion 2(a)) */
1102
0
        ret = mbedtls_rsa_deduce_private_exponent(&ctx->P, &ctx->Q, &ctx->E, &ctx->D);
1103
0
        if (ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
1104
0
            mbedtls_mpi_lset(&ctx->D, 0); /* needed for the next call */
1105
0
            continue;
1106
0
        }
1107
0
        if (ret != 0) {
1108
0
            goto cleanup;
1109
0
        }
1110
1111
        /* (FIPS 186-4 §B.3.1 criterion 3(a)) */
1112
0
        if (mbedtls_mpi_bitlen(&ctx->D) <= ((nbits + 1) / 2)) {
1113
0
            continue;
1114
0
        }
1115
1116
0
        break;
1117
0
    } while (1);
1118
1119
1120
    /* N = P * Q */
1121
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->N, &ctx->P, &ctx->Q));
1122
0
    ctx->len = mbedtls_mpi_size(&ctx->N);
1123
1124
0
#if !defined(MBEDTLS_RSA_NO_CRT)
1125
    /*
1126
     * DP = D mod (P - 1)
1127
     * DQ = D mod (Q - 1)
1128
     * QP = Q^-1 mod P
1129
     */
1130
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D,
1131
0
                                           &ctx->DP, &ctx->DQ, &ctx->QP));
1132
0
#endif /* MBEDTLS_RSA_NO_CRT */
1133
1134
    /* Double-check */
1135
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_check_privkey(ctx));
1136
1137
0
cleanup:
1138
1139
0
    mbedtls_mpi_free(&H);
1140
1141
0
    if (ret != 0) {
1142
0
        mbedtls_rsa_free(ctx);
1143
1144
0
        if ((-ret & ~0x7f) == 0) {
1145
0
            ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_KEY_GEN_FAILED, ret);
1146
0
        }
1147
0
        return ret;
1148
0
    }
1149
1150
0
    return 0;
1151
0
}
1152
1153
#endif /* MBEDTLS_GENPRIME */
1154
1155
/*
1156
 * Check a public RSA key
1157
 */
1158
int mbedtls_rsa_check_pubkey(const mbedtls_rsa_context *ctx)
1159
11.6k
{
1160
11.6k
    if (rsa_check_context(ctx, 0 /* public */, 0 /* no blinding */) != 0) {
1161
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1162
0
    }
1163
1164
11.6k
    if (mbedtls_mpi_bitlen(&ctx->N) < 128) {
1165
20
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1166
20
    }
1167
1168
11.5k
    if (mbedtls_mpi_get_bit(&ctx->E, 0) == 0 ||
1169
11.5k
        mbedtls_mpi_bitlen(&ctx->E)     < 2  ||
1170
11.5k
        mbedtls_mpi_cmp_mpi(&ctx->E, &ctx->N) >= 0) {
1171
18
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1172
18
    }
1173
1174
11.5k
    return 0;
1175
11.5k
}
1176
1177
/*
1178
 * Check for the consistency of all fields in an RSA private key context
1179
 */
1180
int mbedtls_rsa_check_privkey(const mbedtls_rsa_context *ctx)
1181
0
{
1182
0
    if (mbedtls_rsa_check_pubkey(ctx) != 0 ||
1183
0
        rsa_check_context(ctx, 1 /* private */, 1 /* blinding */) != 0) {
1184
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1185
0
    }
1186
1187
0
    if (mbedtls_rsa_validate_params(&ctx->N, &ctx->P, &ctx->Q,
1188
0
                                    &ctx->D, &ctx->E, NULL, NULL) != 0) {
1189
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1190
0
    }
1191
1192
0
#if !defined(MBEDTLS_RSA_NO_CRT)
1193
0
    else if (mbedtls_rsa_validate_crt(&ctx->P, &ctx->Q, &ctx->D,
1194
0
                                      &ctx->DP, &ctx->DQ, &ctx->QP) != 0) {
1195
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1196
0
    }
1197
0
#endif
1198
1199
0
    return 0;
1200
0
}
1201
1202
/*
1203
 * Check if contexts holding a public and private key match
1204
 */
1205
int mbedtls_rsa_check_pub_priv(const mbedtls_rsa_context *pub,
1206
                               const mbedtls_rsa_context *prv)
1207
0
{
1208
0
    if (mbedtls_rsa_check_pubkey(pub)  != 0 ||
1209
0
        mbedtls_rsa_check_privkey(prv) != 0) {
1210
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1211
0
    }
1212
1213
0
    if (mbedtls_mpi_cmp_mpi(&pub->N, &prv->N) != 0 ||
1214
0
        mbedtls_mpi_cmp_mpi(&pub->E, &prv->E) != 0) {
1215
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
1216
0
    }
1217
1218
0
    return 0;
1219
0
}
1220
1221
/*
1222
 * Do an RSA public key operation
1223
 */
1224
int mbedtls_rsa_public(mbedtls_rsa_context *ctx,
1225
                       const unsigned char *input,
1226
                       unsigned char *output)
1227
1.27k
{
1228
1.27k
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1229
1.27k
    size_t olen;
1230
1.27k
    mbedtls_mpi T;
1231
1232
1.27k
    if (rsa_check_context(ctx, 0 /* public */, 0 /* no blinding */)) {
1233
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1234
0
    }
1235
1236
1.27k
    mbedtls_mpi_init(&T);
1237
1238
#if defined(MBEDTLS_THREADING_C)
1239
    if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
1240
        return ret;
1241
    }
1242
#endif
1243
1244
1.27k
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len));
1245
1246
1.27k
    if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) {
1247
0
        ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
1248
0
        goto cleanup;
1249
0
    }
1250
1251
1.27k
    olen = ctx->len;
1252
1.27k
    MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod_unsafe(&T, &T, &ctx->E, &ctx->N, &ctx->RN));
1253
1.27k
    MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen));
1254
1255
1.27k
cleanup:
1256
#if defined(MBEDTLS_THREADING_C)
1257
    if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
1258
        return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
1259
    }
1260
#endif
1261
1262
1.27k
    mbedtls_mpi_free(&T);
1263
1264
1.27k
    if (ret != 0) {
1265
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_PUBLIC_FAILED, ret);
1266
0
    }
1267
1268
1.27k
    return 0;
1269
1.27k
}
1270
1271
/*
1272
 * Generate or update blinding values, see section 10 of:
1273
 *  KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA,
1274
 *  DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer
1275
 *  Berlin Heidelberg, 1996. p. 104-113.
1276
 */
1277
static int rsa_prepare_blinding(mbedtls_rsa_context *ctx,
1278
                                int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
1279
179
{
1280
179
    int ret, count = 0;
1281
179
    mbedtls_mpi R;
1282
1283
179
    mbedtls_mpi_init(&R);
1284
1285
179
    if (ctx->Vf.p != NULL) {
1286
        /* We already have blinding values, just update them by squaring */
1287
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vi, &ctx->Vi));
1288
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
1289
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vf, &ctx->Vf, &ctx->Vf));
1290
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vf, &ctx->Vf, &ctx->N));
1291
1292
0
        goto cleanup;
1293
0
    }
1294
1295
    /* Unblinding value: Vf = random number, invertible mod N */
1296
179
    mbedtls_mpi_lset(&R, 0);
1297
179
    do {
1298
179
        if (count++ > 10) {
1299
0
            ret = MBEDTLS_ERR_RSA_RNG_FAILED;
1300
0
            goto cleanup;
1301
0
        }
1302
1303
179
        MBEDTLS_MPI_CHK(mbedtls_mpi_random(&ctx->Vf, 1, &ctx->N, f_rng, p_rng));
1304
179
        MBEDTLS_MPI_CHK(mbedtls_mpi_gcd_modinv_odd(&R, &ctx->Vi, &ctx->Vf, &ctx->N));
1305
179
    } while (mbedtls_mpi_cmp_int(&R, 1) != 0);
1306
1307
    /* Blinding value: Vi = Vf^(-e) mod N
1308
     * (Vi already contains Vf^-1 at this point) */
1309
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN));
1310
1311
1312
179
cleanup:
1313
179
    mbedtls_mpi_free(&R);
1314
1315
179
    return ret;
1316
179
}
1317
1318
/*
1319
 * Unblind
1320
 * T = T * Vf mod N
1321
 */
1322
static int rsa_unblind(mbedtls_mpi *T, mbedtls_mpi *Vf, const mbedtls_mpi *N)
1323
179
{
1324
179
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1325
179
    const mbedtls_mpi_uint mm = mbedtls_mpi_core_montmul_init(N->p);
1326
179
    const size_t nlimbs = N->n;
1327
179
    const size_t tlimbs = mbedtls_mpi_core_montmul_working_limbs(nlimbs);
1328
179
    mbedtls_mpi RR, M_T;
1329
1330
179
    mbedtls_mpi_init(&RR);
1331
179
    mbedtls_mpi_init(&M_T);
1332
1333
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_core_get_mont_r2_unsafe(&RR, N));
1334
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_grow(&M_T, tlimbs));
1335
1336
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_grow(T, nlimbs));
1337
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_grow(Vf, nlimbs));
1338
1339
    /* T = T * Vf mod N
1340
     * Reminder: montmul(A, B, N) = A * B * R^-1 mod N
1341
     * Usually both operands are multiplied by R mod N beforehand (by calling
1342
     * `to_mont_rep()` on them), yielding a result that's also * R mod N (aka
1343
     * "in the Montgomery domain"). Here we only multiply one operand by R mod
1344
     * N, so the result is directly what we want - no need to call
1345
     * `from_mont_rep()` on it. */
1346
179
    mbedtls_mpi_core_to_mont_rep(T->p, T->p, N->p, nlimbs, mm, RR.p, M_T.p);
1347
179
    mbedtls_mpi_core_montmul(T->p, T->p, Vf->p, nlimbs, N->p, nlimbs, mm, M_T.p);
1348
1349
179
cleanup:
1350
1351
179
    mbedtls_mpi_free(&RR);
1352
179
    mbedtls_mpi_free(&M_T);
1353
1354
179
    return ret;
1355
179
}
1356
1357
/*
1358
 * Exponent blinding supposed to prevent side-channel attacks using multiple
1359
 * traces of measurements to recover the RSA key. The more collisions are there,
1360
 * the more bits of the key can be recovered. See [3].
1361
 *
1362
 * Collecting n collisions with m bit long blinding value requires 2^(m-m/n)
1363
 * observations on average.
1364
 *
1365
 * For example with 28 byte blinding to achieve 2 collisions the adversary has
1366
 * to make 2^112 observations on average.
1367
 *
1368
 * (With the currently (as of 2017 April) known best algorithms breaking 2048
1369
 * bit RSA requires approximately as much time as trying out 2^112 random keys.
1370
 * Thus in this sense with 28 byte blinding the security is not reduced by
1371
 * side-channel attacks like the one in [3])
1372
 *
1373
 * This countermeasure does not help if the key recovery is possible with a
1374
 * single trace.
1375
 */
1376
#define RSA_EXPONENT_BLINDING 28
1377
1378
/*
1379
 * Do an RSA private key operation
1380
 */
1381
int mbedtls_rsa_private(mbedtls_rsa_context *ctx,
1382
                        int (*f_rng)(void *, unsigned char *, size_t),
1383
                        void *p_rng,
1384
                        const unsigned char *input,
1385
                        unsigned char *output)
1386
179
{
1387
179
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1388
179
    size_t olen;
1389
1390
    /* Temporary holding the result */
1391
179
    mbedtls_mpi T;
1392
1393
    /* Temporaries holding P-1, Q-1 and the
1394
     * exponent blinding factor, respectively. */
1395
179
    mbedtls_mpi P1, Q1, R;
1396
1397
179
#if !defined(MBEDTLS_RSA_NO_CRT)
1398
    /* Temporaries holding the results mod p resp. mod q. */
1399
179
    mbedtls_mpi TP, TQ;
1400
1401
    /* Temporaries holding the blinded exponents for
1402
     * the mod p resp. mod q computation (if used). */
1403
179
    mbedtls_mpi DP_blind, DQ_blind;
1404
#else
1405
    /* Temporary holding the blinded exponent (if used). */
1406
    mbedtls_mpi D_blind;
1407
#endif /* MBEDTLS_RSA_NO_CRT */
1408
1409
    /* Temporaries holding the initial input and the double
1410
     * checked result; should be the same in the end. */
1411
179
    mbedtls_mpi input_blinded, check_result_blinded;
1412
1413
179
    if (f_rng == NULL) {
1414
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1415
0
    }
1416
1417
179
    if (rsa_check_context(ctx, 1 /* private key checks */,
1418
179
                          1 /* blinding on        */) != 0) {
1419
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1420
0
    }
1421
1422
#if defined(MBEDTLS_THREADING_C)
1423
    if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
1424
        return ret;
1425
    }
1426
#endif
1427
1428
    /* MPI Initialization */
1429
179
    mbedtls_mpi_init(&T);
1430
1431
179
    mbedtls_mpi_init(&P1);
1432
179
    mbedtls_mpi_init(&Q1);
1433
179
    mbedtls_mpi_init(&R);
1434
1435
#if defined(MBEDTLS_RSA_NO_CRT)
1436
    mbedtls_mpi_init(&D_blind);
1437
#else
1438
179
    mbedtls_mpi_init(&DP_blind);
1439
179
    mbedtls_mpi_init(&DQ_blind);
1440
179
#endif
1441
1442
179
#if !defined(MBEDTLS_RSA_NO_CRT)
1443
179
    mbedtls_mpi_init(&TP); mbedtls_mpi_init(&TQ);
1444
179
#endif
1445
1446
179
    mbedtls_mpi_init(&input_blinded);
1447
179
    mbedtls_mpi_init(&check_result_blinded);
1448
1449
    /* End of MPI initialization */
1450
1451
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len));
1452
179
    if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) {
1453
0
        ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
1454
0
        goto cleanup;
1455
0
    }
1456
1457
    /*
1458
     * Blinding
1459
     * T = T * Vi mod N
1460
     */
1461
179
    MBEDTLS_MPI_CHK(rsa_prepare_blinding(ctx, f_rng, p_rng));
1462
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&T, &T, &ctx->Vi));
1463
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &T, &ctx->N));
1464
1465
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&input_blinded, &T));
1466
1467
    /*
1468
     * Exponent blinding
1469
     */
1470
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&P1, &ctx->P, 1));
1471
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&Q1, &ctx->Q, 1));
1472
1473
#if defined(MBEDTLS_RSA_NO_CRT)
1474
    /*
1475
     * D_blind = ( P - 1 ) * ( Q - 1 ) * R + D
1476
     */
1477
    MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
1478
                                            f_rng, p_rng));
1479
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&D_blind, &P1, &Q1));
1480
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&D_blind, &D_blind, &R));
1481
    MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&D_blind, &D_blind, &ctx->D));
1482
#else
1483
    /*
1484
     * DP_blind = ( P - 1 ) * R + DP
1485
     */
1486
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
1487
179
                                            f_rng, p_rng));
1488
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&DP_blind, &P1, &R));
1489
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&DP_blind, &DP_blind,
1490
179
                                        &ctx->DP));
1491
1492
    /*
1493
     * DQ_blind = ( Q - 1 ) * R + DQ
1494
     */
1495
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
1496
179
                                            f_rng, p_rng));
1497
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&DQ_blind, &Q1, &R));
1498
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&DQ_blind, &DQ_blind,
1499
179
                                        &ctx->DQ));
1500
179
#endif /* MBEDTLS_RSA_NO_CRT */
1501
1502
#if defined(MBEDTLS_RSA_NO_CRT)
1503
    MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&T, &T, &D_blind, &ctx->N, &ctx->RN));
1504
#else
1505
    /*
1506
     * Faster decryption using the CRT
1507
     *
1508
     * TP = input ^ dP mod P
1509
     * TQ = input ^ dQ mod Q
1510
     */
1511
1512
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&TP, &T, &DP_blind, &ctx->P, &ctx->RP));
1513
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&TQ, &T, &DQ_blind, &ctx->Q, &ctx->RQ));
1514
1515
    /*
1516
     * T = (TP - TQ) * (Q^-1 mod P) mod P
1517
     */
1518
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&T, &TP, &TQ));
1519
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&TP, &T, &ctx->QP));
1520
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &TP, &ctx->P));
1521
1522
    /*
1523
     * T = TQ + T * Q
1524
     */
1525
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&TP, &T, &ctx->Q));
1526
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&T, &TQ, &TP));
1527
179
#endif /* MBEDTLS_RSA_NO_CRT */
1528
1529
    /* Verify the result to prevent glitching attacks. */
1530
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&check_result_blinded, &T, &ctx->E,
1531
179
                                        &ctx->N, &ctx->RN));
1532
179
    if (mbedtls_mpi_cmp_mpi(&check_result_blinded, &input_blinded) != 0) {
1533
0
        ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
1534
0
        goto cleanup;
1535
0
    }
1536
1537
    /*
1538
     * Unblind
1539
     * T = T * Vf mod N
1540
     */
1541
179
    MBEDTLS_MPI_CHK(rsa_unblind(&T, &ctx->Vf, &ctx->N));
1542
1543
179
    olen = ctx->len;
1544
179
    MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen));
1545
1546
179
cleanup:
1547
#if defined(MBEDTLS_THREADING_C)
1548
    if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
1549
        return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
1550
    }
1551
#endif
1552
1553
179
    mbedtls_mpi_free(&P1);
1554
179
    mbedtls_mpi_free(&Q1);
1555
179
    mbedtls_mpi_free(&R);
1556
1557
#if defined(MBEDTLS_RSA_NO_CRT)
1558
    mbedtls_mpi_free(&D_blind);
1559
#else
1560
179
    mbedtls_mpi_free(&DP_blind);
1561
179
    mbedtls_mpi_free(&DQ_blind);
1562
179
#endif
1563
1564
179
    mbedtls_mpi_free(&T);
1565
1566
179
#if !defined(MBEDTLS_RSA_NO_CRT)
1567
179
    mbedtls_mpi_free(&TP); mbedtls_mpi_free(&TQ);
1568
179
#endif
1569
1570
179
    mbedtls_mpi_free(&check_result_blinded);
1571
179
    mbedtls_mpi_free(&input_blinded);
1572
1573
179
    if (ret != 0 && ret >= -0x007f) {
1574
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_PRIVATE_FAILED, ret);
1575
0
    }
1576
1577
179
    return ret;
1578
179
}
1579
1580
#if defined(MBEDTLS_PKCS1_V21)
1581
/**
1582
 * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer.
1583
 *
1584
 * \param dst       buffer to mask
1585
 * \param dlen      length of destination buffer
1586
 * \param src       source of the mask generation
1587
 * \param slen      length of the source buffer
1588
 * \param md_alg    message digest to use
1589
 */
1590
static int mgf_mask(unsigned char *dst, size_t dlen, unsigned char *src,
1591
                    size_t slen, mbedtls_md_type_t md_alg)
1592
0
{
1593
0
    unsigned char counter[4];
1594
0
    unsigned char *p;
1595
0
    unsigned int hlen;
1596
0
    size_t i, use_len;
1597
0
    unsigned char mask[MBEDTLS_MD_MAX_SIZE];
1598
0
    int ret = 0;
1599
0
    const mbedtls_md_info_t *md_info;
1600
0
    mbedtls_md_context_t md_ctx;
1601
1602
0
    mbedtls_md_init(&md_ctx);
1603
0
    md_info = mbedtls_md_info_from_type(md_alg);
1604
0
    if (md_info == NULL) {
1605
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1606
0
    }
1607
1608
0
    mbedtls_md_init(&md_ctx);
1609
0
    if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
1610
0
        goto exit;
1611
0
    }
1612
1613
0
    hlen = mbedtls_md_get_size(md_info);
1614
1615
0
    memset(mask, 0, sizeof(mask));
1616
0
    memset(counter, 0, 4);
1617
1618
    /* Generate and apply dbMask */
1619
0
    p = dst;
1620
1621
0
    while (dlen > 0) {
1622
0
        use_len = hlen;
1623
0
        if (dlen < hlen) {
1624
0
            use_len = dlen;
1625
0
        }
1626
1627
0
        if ((ret = mbedtls_md_starts(&md_ctx)) != 0) {
1628
0
            goto exit;
1629
0
        }
1630
0
        if ((ret = mbedtls_md_update(&md_ctx, src, slen)) != 0) {
1631
0
            goto exit;
1632
0
        }
1633
0
        if ((ret = mbedtls_md_update(&md_ctx, counter, 4)) != 0) {
1634
0
            goto exit;
1635
0
        }
1636
0
        if ((ret = mbedtls_md_finish(&md_ctx, mask)) != 0) {
1637
0
            goto exit;
1638
0
        }
1639
1640
0
        for (i = 0; i < use_len; ++i) {
1641
0
            *p++ ^= mask[i];
1642
0
        }
1643
1644
0
        counter[3]++;
1645
1646
0
        dlen -= use_len;
1647
0
    }
1648
1649
0
exit:
1650
0
    mbedtls_platform_zeroize(mask, sizeof(mask));
1651
0
    mbedtls_md_free(&md_ctx);
1652
1653
0
    return ret;
1654
0
}
1655
1656
/**
1657
 * Generate Hash(M') as in RFC 8017 page 43 points 5 and 6.
1658
 *
1659
 * \param hash      the input hash
1660
 * \param hlen      length of the input hash
1661
 * \param salt      the input salt
1662
 * \param slen      length of the input salt
1663
 * \param out       the output buffer - must be large enough for \p md_alg
1664
 * \param md_alg    message digest to use
1665
 */
1666
static int hash_mprime(const unsigned char *hash, size_t hlen,
1667
                       const unsigned char *salt, size_t slen,
1668
                       unsigned char *out, mbedtls_md_type_t md_alg)
1669
0
{
1670
0
    const unsigned char zeros[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
1671
1672
0
    mbedtls_md_context_t md_ctx;
1673
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1674
1675
0
    const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_alg);
1676
0
    if (md_info == NULL) {
1677
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1678
0
    }
1679
1680
0
    mbedtls_md_init(&md_ctx);
1681
0
    if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
1682
0
        goto exit;
1683
0
    }
1684
0
    if ((ret = mbedtls_md_starts(&md_ctx)) != 0) {
1685
0
        goto exit;
1686
0
    }
1687
0
    if ((ret = mbedtls_md_update(&md_ctx, zeros, sizeof(zeros))) != 0) {
1688
0
        goto exit;
1689
0
    }
1690
0
    if ((ret = mbedtls_md_update(&md_ctx, hash, hlen)) != 0) {
1691
0
        goto exit;
1692
0
    }
1693
0
    if ((ret = mbedtls_md_update(&md_ctx, salt, slen)) != 0) {
1694
0
        goto exit;
1695
0
    }
1696
0
    if ((ret = mbedtls_md_finish(&md_ctx, out)) != 0) {
1697
0
        goto exit;
1698
0
    }
1699
1700
0
exit:
1701
0
    mbedtls_md_free(&md_ctx);
1702
1703
0
    return ret;
1704
0
}
1705
1706
/**
1707
 * Compute a hash.
1708
 *
1709
 * \param md_alg    algorithm to use
1710
 * \param input     input message to hash
1711
 * \param ilen      input length
1712
 * \param output    the output buffer - must be large enough for \p md_alg
1713
 */
1714
static int compute_hash(mbedtls_md_type_t md_alg,
1715
                        const unsigned char *input, size_t ilen,
1716
                        unsigned char *output)
1717
0
{
1718
0
    const mbedtls_md_info_t *md_info;
1719
1720
0
    md_info = mbedtls_md_info_from_type(md_alg);
1721
0
    if (md_info == NULL) {
1722
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1723
0
    }
1724
1725
0
    return mbedtls_md(md_info, input, ilen, output);
1726
0
}
1727
#endif /* MBEDTLS_PKCS1_V21 */
1728
1729
#if defined(MBEDTLS_PKCS1_V21)
1730
/*
1731
 * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function
1732
 */
1733
int mbedtls_rsa_rsaes_oaep_encrypt(mbedtls_rsa_context *ctx,
1734
                                   int (*f_rng)(void *, unsigned char *, size_t),
1735
                                   void *p_rng,
1736
                                   const unsigned char *label, size_t label_len,
1737
                                   size_t ilen,
1738
                                   const unsigned char *input,
1739
                                   unsigned char *output)
1740
0
{
1741
0
    size_t olen;
1742
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1743
0
    unsigned char *p = output;
1744
0
    unsigned int hlen;
1745
1746
0
    if (f_rng == NULL) {
1747
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1748
0
    }
1749
1750
0
    hlen = mbedtls_md_get_size_from_type((mbedtls_md_type_t) ctx->hash_id);
1751
0
    if (hlen == 0) {
1752
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1753
0
    }
1754
1755
0
    olen = ctx->len;
1756
1757
    /* first comparison checks for overflow */
1758
0
    if (ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2) {
1759
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1760
0
    }
1761
1762
0
    memset(output, 0, olen);
1763
1764
0
    *p++ = 0;
1765
1766
    /* Generate a random octet string seed */
1767
0
    if ((ret = f_rng(p_rng, p, hlen)) != 0) {
1768
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
1769
0
    }
1770
1771
0
    p += hlen;
1772
1773
    /* Construct DB */
1774
0
    ret = compute_hash((mbedtls_md_type_t) ctx->hash_id, label, label_len, p);
1775
0
    if (ret != 0) {
1776
0
        return ret;
1777
0
    }
1778
0
    p += hlen;
1779
0
    p += olen - 2 * hlen - 2 - ilen;
1780
0
    *p++ = 1;
1781
0
    if (ilen != 0) {
1782
0
        memcpy(p, input, ilen);
1783
0
    }
1784
1785
    /* maskedDB: Apply dbMask to DB */
1786
0
    if ((ret = mgf_mask(output + hlen + 1, olen - hlen - 1, output + 1, hlen,
1787
0
                        (mbedtls_md_type_t) ctx->hash_id)) != 0) {
1788
0
        return ret;
1789
0
    }
1790
1791
    /* maskedSeed: Apply seedMask to seed */
1792
0
    if ((ret = mgf_mask(output + 1, hlen, output + hlen + 1, olen - hlen - 1,
1793
0
                        (mbedtls_md_type_t) ctx->hash_id)) != 0) {
1794
0
        return ret;
1795
0
    }
1796
1797
0
    return mbedtls_rsa_public(ctx, output, output);
1798
0
}
1799
#endif /* MBEDTLS_PKCS1_V21 */
1800
1801
#if defined(MBEDTLS_PKCS1_V15)
1802
/*
1803
 * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function
1804
 */
1805
int mbedtls_rsa_rsaes_pkcs1_v15_encrypt(mbedtls_rsa_context *ctx,
1806
                                        int (*f_rng)(void *, unsigned char *, size_t),
1807
                                        void *p_rng, size_t ilen,
1808
                                        const unsigned char *input,
1809
                                        unsigned char *output)
1810
0
{
1811
0
    size_t nb_pad, olen;
1812
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1813
0
    unsigned char *p = output;
1814
1815
0
    olen = ctx->len;
1816
1817
    /* first comparison checks for overflow */
1818
0
    if (ilen + 11 < ilen || olen < ilen + 11) {
1819
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1820
0
    }
1821
1822
0
    nb_pad = olen - 3 - ilen;
1823
1824
0
    *p++ = 0;
1825
1826
0
    if (f_rng == NULL) {
1827
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1828
0
    }
1829
1830
0
    *p++ = MBEDTLS_RSA_CRYPT;
1831
1832
0
    while (nb_pad-- > 0) {
1833
0
        int rng_dl = 100;
1834
1835
0
        do {
1836
0
            ret = f_rng(p_rng, p, 1);
1837
0
        } while (*p == 0 && --rng_dl && ret == 0);
1838
1839
        /* Check if RNG failed to generate data */
1840
0
        if (rng_dl == 0 || ret != 0) {
1841
0
            return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
1842
0
        }
1843
1844
0
        p++;
1845
0
    }
1846
1847
0
    *p++ = 0;
1848
0
    if (ilen != 0) {
1849
0
        memcpy(p, input, ilen);
1850
0
    }
1851
1852
0
    return mbedtls_rsa_public(ctx, output, output);
1853
0
}
1854
#endif /* MBEDTLS_PKCS1_V15 */
1855
1856
/*
1857
 * Add the message padding, then do an RSA operation
1858
 */
1859
int mbedtls_rsa_pkcs1_encrypt(mbedtls_rsa_context *ctx,
1860
                              int (*f_rng)(void *, unsigned char *, size_t),
1861
                              void *p_rng,
1862
                              size_t ilen,
1863
                              const unsigned char *input,
1864
                              unsigned char *output)
1865
0
{
1866
0
    switch (ctx->padding) {
1867
0
#if defined(MBEDTLS_PKCS1_V15)
1868
0
        case MBEDTLS_RSA_PKCS_V15:
1869
0
            return mbedtls_rsa_rsaes_pkcs1_v15_encrypt(ctx, f_rng, p_rng,
1870
0
                                                       ilen, input, output);
1871
0
#endif
1872
1873
0
#if defined(MBEDTLS_PKCS1_V21)
1874
0
        case MBEDTLS_RSA_PKCS_V21:
1875
0
            return mbedtls_rsa_rsaes_oaep_encrypt(ctx, f_rng, p_rng, NULL, 0,
1876
0
                                                  ilen, input, output);
1877
0
#endif
1878
1879
0
        default:
1880
0
            return MBEDTLS_ERR_RSA_INVALID_PADDING;
1881
0
    }
1882
0
}
1883
1884
#if defined(MBEDTLS_PKCS1_V21)
1885
/*
1886
 * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function
1887
 */
1888
int mbedtls_rsa_rsaes_oaep_decrypt(mbedtls_rsa_context *ctx,
1889
                                   int (*f_rng)(void *, unsigned char *, size_t),
1890
                                   void *p_rng,
1891
                                   const unsigned char *label, size_t label_len,
1892
                                   size_t *olen,
1893
                                   const unsigned char *input,
1894
                                   unsigned char *output,
1895
                                   size_t output_max_len)
1896
0
{
1897
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1898
0
    size_t ilen, i, pad_len;
1899
0
    unsigned char *p;
1900
0
    mbedtls_ct_condition_t bad, in_padding;
1901
0
    unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
1902
0
    unsigned char lhash[MBEDTLS_MD_MAX_SIZE];
1903
0
    unsigned int hlen;
1904
1905
    /*
1906
     * Parameters sanity checks
1907
     */
1908
0
    if (ctx->padding != MBEDTLS_RSA_PKCS_V21) {
1909
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1910
0
    }
1911
1912
0
    ilen = ctx->len;
1913
1914
0
    if (ilen < 16 || ilen > sizeof(buf)) {
1915
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1916
0
    }
1917
1918
0
    hlen = mbedtls_md_get_size_from_type((mbedtls_md_type_t) ctx->hash_id);
1919
0
    if (hlen == 0) {
1920
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1921
0
    }
1922
1923
    // checking for integer underflow
1924
0
    if (2 * hlen + 2 > ilen) {
1925
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1926
0
    }
1927
1928
    /*
1929
     * RSA operation
1930
     */
1931
0
    ret = mbedtls_rsa_private(ctx, f_rng, p_rng, input, buf);
1932
1933
0
    if (ret != 0) {
1934
0
        goto cleanup;
1935
0
    }
1936
1937
    /*
1938
     * Unmask data and generate lHash
1939
     */
1940
    /* seed: Apply seedMask to maskedSeed */
1941
0
    if ((ret = mgf_mask(buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1,
1942
0
                        (mbedtls_md_type_t) ctx->hash_id)) != 0 ||
1943
        /* DB: Apply dbMask to maskedDB */
1944
0
        (ret = mgf_mask(buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen,
1945
0
                        (mbedtls_md_type_t) ctx->hash_id)) != 0) {
1946
0
        goto cleanup;
1947
0
    }
1948
1949
    /* Generate lHash */
1950
0
    ret = compute_hash((mbedtls_md_type_t) ctx->hash_id,
1951
0
                       label, label_len, lhash);
1952
0
    if (ret != 0) {
1953
0
        goto cleanup;
1954
0
    }
1955
1956
    /*
1957
     * Check contents, in "constant-time"
1958
     */
1959
0
    p = buf;
1960
1961
0
    bad = mbedtls_ct_bool(*p++); /* First byte must be 0 */
1962
1963
0
    p += hlen; /* Skip seed */
1964
1965
    /* Check lHash */
1966
0
    bad = mbedtls_ct_bool_or(bad, mbedtls_ct_bool(mbedtls_ct_memcmp(lhash, p, hlen)));
1967
0
    p += hlen;
1968
1969
    /* Get zero-padding len, but always read till end of buffer
1970
     * (minus one, for the 01 byte) */
1971
0
    pad_len = 0;
1972
0
    in_padding = MBEDTLS_CT_TRUE;
1973
0
    for (i = 0; i < ilen - 2 * hlen - 2; i++) {
1974
0
        in_padding = mbedtls_ct_bool_and(in_padding, mbedtls_ct_uint_eq(p[i], 0));
1975
0
        pad_len += mbedtls_ct_uint_if_else_0(in_padding, 1);
1976
0
    }
1977
1978
0
    p += pad_len;
1979
0
    bad = mbedtls_ct_bool_or(bad, mbedtls_ct_uint_ne(*p++, 0x01));
1980
1981
    /*
1982
     * The only information "leaked" is whether the padding was correct or not
1983
     * (eg, no data is copied if it was not correct). This meets the
1984
     * recommendations in PKCS#1 v2.2: an opponent cannot distinguish between
1985
     * the different error conditions.
1986
     */
1987
0
    if (bad != MBEDTLS_CT_FALSE) {
1988
0
        ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
1989
0
        goto cleanup;
1990
0
    }
1991
1992
0
    if (ilen - ((size_t) (p - buf)) > output_max_len) {
1993
0
        ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;
1994
0
        goto cleanup;
1995
0
    }
1996
1997
0
    *olen = ilen - ((size_t) (p - buf));
1998
0
    if (*olen != 0) {
1999
0
        memcpy(output, p, *olen);
2000
0
    }
2001
0
    ret = 0;
2002
2003
0
cleanup:
2004
0
    mbedtls_platform_zeroize(buf, sizeof(buf));
2005
0
    mbedtls_platform_zeroize(lhash, sizeof(lhash));
2006
2007
0
    return ret;
2008
0
}
2009
#endif /* MBEDTLS_PKCS1_V21 */
2010
2011
#if defined(MBEDTLS_PKCS1_V15)
2012
/*
2013
 * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function
2014
 */
2015
int mbedtls_rsa_rsaes_pkcs1_v15_decrypt(mbedtls_rsa_context *ctx,
2016
                                        int (*f_rng)(void *, unsigned char *, size_t),
2017
                                        void *p_rng,
2018
                                        size_t *olen,
2019
                                        const unsigned char *input,
2020
                                        unsigned char *output,
2021
                                        size_t output_max_len)
2022
0
{
2023
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2024
0
    size_t ilen;
2025
0
    unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
2026
2027
0
    ilen = ctx->len;
2028
2029
0
    if (ctx->padding != MBEDTLS_RSA_PKCS_V15) {
2030
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2031
0
    }
2032
2033
0
    if (ilen < 16 || ilen > sizeof(buf)) {
2034
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2035
0
    }
2036
2037
0
    ret = mbedtls_rsa_private(ctx, f_rng, p_rng, input, buf);
2038
2039
0
    if (ret != 0) {
2040
0
        goto cleanup;
2041
0
    }
2042
2043
0
    ret = mbedtls_ct_rsaes_pkcs1_v15_unpadding(buf, ilen,
2044
0
                                               output, output_max_len, olen);
2045
2046
0
cleanup:
2047
0
    mbedtls_platform_zeroize(buf, sizeof(buf));
2048
2049
0
    return ret;
2050
0
}
2051
#endif /* MBEDTLS_PKCS1_V15 */
2052
2053
/*
2054
 * Do an RSA operation, then remove the message padding
2055
 */
2056
int mbedtls_rsa_pkcs1_decrypt(mbedtls_rsa_context *ctx,
2057
                              int (*f_rng)(void *, unsigned char *, size_t),
2058
                              void *p_rng,
2059
                              size_t *olen,
2060
                              const unsigned char *input,
2061
                              unsigned char *output,
2062
                              size_t output_max_len)
2063
0
{
2064
0
    switch (ctx->padding) {
2065
0
#if defined(MBEDTLS_PKCS1_V15)
2066
0
        case MBEDTLS_RSA_PKCS_V15:
2067
0
            return mbedtls_rsa_rsaes_pkcs1_v15_decrypt(ctx, f_rng, p_rng, olen,
2068
0
                                                       input, output, output_max_len);
2069
0
#endif
2070
2071
0
#if defined(MBEDTLS_PKCS1_V21)
2072
0
        case MBEDTLS_RSA_PKCS_V21:
2073
0
            return mbedtls_rsa_rsaes_oaep_decrypt(ctx, f_rng, p_rng, NULL, 0,
2074
0
                                                  olen, input, output,
2075
0
                                                  output_max_len);
2076
0
#endif
2077
2078
0
        default:
2079
0
            return MBEDTLS_ERR_RSA_INVALID_PADDING;
2080
0
    }
2081
0
}
2082
2083
#if defined(MBEDTLS_PKCS1_V21)
2084
static int rsa_rsassa_pss_sign_no_mode_check(mbedtls_rsa_context *ctx,
2085
                                             int (*f_rng)(void *, unsigned char *, size_t),
2086
                                             void *p_rng,
2087
                                             mbedtls_md_type_t md_alg,
2088
                                             unsigned int hashlen,
2089
                                             const unsigned char *hash,
2090
                                             int saltlen,
2091
                                             unsigned char *sig)
2092
0
{
2093
0
    size_t olen;
2094
0
    unsigned char *p = sig;
2095
0
    unsigned char *salt = NULL;
2096
0
    size_t slen, min_slen, hlen, offset = 0;
2097
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2098
0
    size_t msb;
2099
0
    mbedtls_md_type_t hash_id;
2100
2101
0
    if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2102
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2103
0
    }
2104
2105
0
    if (f_rng == NULL) {
2106
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2107
0
    }
2108
2109
0
    olen = ctx->len;
2110
2111
0
    if (md_alg != MBEDTLS_MD_NONE) {
2112
        /* Gather length of hash to sign */
2113
0
        size_t exp_hashlen = mbedtls_md_get_size_from_type(md_alg);
2114
0
        if (exp_hashlen == 0) {
2115
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2116
0
        }
2117
2118
0
        if (hashlen != exp_hashlen) {
2119
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2120
0
        }
2121
0
    }
2122
2123
0
    hash_id = (mbedtls_md_type_t) ctx->hash_id;
2124
0
    if (hash_id == MBEDTLS_MD_NONE) {
2125
0
        hash_id = md_alg;
2126
0
    }
2127
0
    hlen = mbedtls_md_get_size_from_type(hash_id);
2128
0
    if (hlen == 0) {
2129
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2130
0
    }
2131
2132
0
    if (saltlen == MBEDTLS_RSA_SALT_LEN_ANY) {
2133
        /* Calculate the largest possible salt length, up to the hash size.
2134
         * Normally this is the hash length, which is the maximum salt length
2135
         * according to FIPS 185-4 §5.5 (e) and common practice. If there is not
2136
         * enough room, use the maximum salt length that fits. The constraint is
2137
         * that the hash length plus the salt length plus 2 bytes must be at most
2138
         * the key length. This complies with FIPS 186-4 §5.5 (e) and RFC 8017
2139
         * (PKCS#1 v2.2) §9.1.1 step 3. */
2140
0
        min_slen = hlen - 2;
2141
0
        if (olen < hlen + min_slen + 2) {
2142
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2143
0
        } else if (olen >= hlen + hlen + 2) {
2144
0
            slen = hlen;
2145
0
        } else {
2146
0
            slen = olen - hlen - 2;
2147
0
        }
2148
0
    } else if ((saltlen < 0) || (saltlen + hlen + 2 > olen)) {
2149
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2150
0
    } else {
2151
0
        slen = (size_t) saltlen;
2152
0
    }
2153
2154
0
    memset(sig, 0, olen);
2155
2156
    /* Note: EMSA-PSS encoding is over the length of N - 1 bits */
2157
0
    msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
2158
0
    p += olen - hlen - slen - 2;
2159
0
    *p++ = 0x01;
2160
2161
    /* Generate salt of length slen in place in the encoded message */
2162
0
    salt = p;
2163
0
    if ((ret = f_rng(p_rng, salt, slen)) != 0) {
2164
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
2165
0
    }
2166
2167
0
    p += slen;
2168
2169
    /* Generate H = Hash( M' ) */
2170
0
    ret = hash_mprime(hash, hashlen, salt, slen, p, hash_id);
2171
0
    if (ret != 0) {
2172
0
        return ret;
2173
0
    }
2174
2175
    /* Compensate for boundary condition when applying mask */
2176
0
    if (msb % 8 == 0) {
2177
0
        offset = 1;
2178
0
    }
2179
2180
    /* maskedDB: Apply dbMask to DB */
2181
0
    ret = mgf_mask(sig + offset, olen - hlen - 1 - offset, p, hlen, hash_id);
2182
0
    if (ret != 0) {
2183
0
        return ret;
2184
0
    }
2185
2186
0
    msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
2187
0
    sig[0] &= 0xFF >> (olen * 8 - msb);
2188
2189
0
    p += hlen;
2190
0
    *p++ = 0xBC;
2191
2192
0
    return mbedtls_rsa_private(ctx, f_rng, p_rng, sig, sig);
2193
0
}
2194
2195
static int rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx,
2196
                               int (*f_rng)(void *, unsigned char *, size_t),
2197
                               void *p_rng,
2198
                               mbedtls_md_type_t md_alg,
2199
                               unsigned int hashlen,
2200
                               const unsigned char *hash,
2201
                               int saltlen,
2202
                               unsigned char *sig)
2203
0
{
2204
0
    if (ctx->padding != MBEDTLS_RSA_PKCS_V21) {
2205
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2206
0
    }
2207
0
    if ((ctx->hash_id == MBEDTLS_MD_NONE) && (md_alg == MBEDTLS_MD_NONE)) {
2208
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2209
0
    }
2210
0
    return rsa_rsassa_pss_sign_no_mode_check(ctx, f_rng, p_rng, md_alg, hashlen, hash, saltlen,
2211
0
                                             sig);
2212
0
}
2213
2214
int mbedtls_rsa_rsassa_pss_sign_no_mode_check(mbedtls_rsa_context *ctx,
2215
                                              int (*f_rng)(void *, unsigned char *, size_t),
2216
                                              void *p_rng,
2217
                                              mbedtls_md_type_t md_alg,
2218
                                              unsigned int hashlen,
2219
                                              const unsigned char *hash,
2220
                                              unsigned char *sig)
2221
0
{
2222
0
    return rsa_rsassa_pss_sign_no_mode_check(ctx, f_rng, p_rng, md_alg,
2223
0
                                             hashlen, hash, MBEDTLS_RSA_SALT_LEN_ANY, sig);
2224
0
}
2225
2226
/*
2227
 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function with
2228
 * the option to pass in the salt length.
2229
 */
2230
int mbedtls_rsa_rsassa_pss_sign_ext(mbedtls_rsa_context *ctx,
2231
                                    int (*f_rng)(void *, unsigned char *, size_t),
2232
                                    void *p_rng,
2233
                                    mbedtls_md_type_t md_alg,
2234
                                    unsigned int hashlen,
2235
                                    const unsigned char *hash,
2236
                                    int saltlen,
2237
                                    unsigned char *sig)
2238
0
{
2239
0
    return rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
2240
0
                               hashlen, hash, saltlen, sig);
2241
0
}
2242
2243
/*
2244
 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function
2245
 */
2246
int mbedtls_rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx,
2247
                                int (*f_rng)(void *, unsigned char *, size_t),
2248
                                void *p_rng,
2249
                                mbedtls_md_type_t md_alg,
2250
                                unsigned int hashlen,
2251
                                const unsigned char *hash,
2252
                                unsigned char *sig)
2253
0
{
2254
0
    return rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
2255
0
                               hashlen, hash, MBEDTLS_RSA_SALT_LEN_ANY, sig);
2256
0
}
2257
#endif /* MBEDTLS_PKCS1_V21 */
2258
2259
#if defined(MBEDTLS_PKCS1_V15)
2260
/*
2261
 * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function
2262
 */
2263
2264
/* Construct a PKCS v1.5 encoding of a hashed message
2265
 *
2266
 * This is used both for signature generation and verification.
2267
 *
2268
 * Parameters:
2269
 * - md_alg:  Identifies the hash algorithm used to generate the given hash;
2270
 *            MBEDTLS_MD_NONE if raw data is signed.
2271
 * - hashlen: Length of hash. Must match md_alg if that's not NONE.
2272
 * - hash:    Buffer containing the hashed message or the raw data.
2273
 * - dst_len: Length of the encoded message.
2274
 * - dst:     Buffer to hold the encoded message.
2275
 *
2276
 * Assumptions:
2277
 * - hash has size hashlen.
2278
 * - dst points to a buffer of size at least dst_len.
2279
 *
2280
 */
2281
static int rsa_rsassa_pkcs1_v15_encode(mbedtls_md_type_t md_alg,
2282
                                       unsigned int hashlen,
2283
                                       const unsigned char *hash,
2284
                                       size_t dst_len,
2285
                                       unsigned char *dst)
2286
1.27k
{
2287
1.27k
    size_t oid_size  = 0;
2288
1.27k
    size_t nb_pad    = dst_len;
2289
1.27k
    unsigned char *p = dst;
2290
1.27k
    const char *oid  = NULL;
2291
2292
    /* Are we signing hashed or raw data? */
2293
1.27k
    if (md_alg != MBEDTLS_MD_NONE) {
2294
1.27k
        unsigned char md_size = mbedtls_md_get_size_from_type(md_alg);
2295
1.27k
        if (md_size == 0) {
2296
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2297
0
        }
2298
2299
1.27k
        if (mbedtls_oid_get_oid_by_md(md_alg, &oid, &oid_size) != 0) {
2300
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2301
0
        }
2302
2303
1.27k
        if (hashlen != md_size) {
2304
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2305
0
        }
2306
2307
        /* Double-check that 8 + hashlen + oid_size can be used as a
2308
         * 1-byte ASN.1 length encoding and that there's no overflow. */
2309
1.27k
        if (8 + hashlen + oid_size  >= 0x80         ||
2310
1.27k
            10 + hashlen            <  hashlen      ||
2311
1.27k
            10 + hashlen + oid_size <  10 + hashlen) {
2312
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2313
0
        }
2314
2315
        /*
2316
         * Static bounds check:
2317
         * - Need 10 bytes for five tag-length pairs.
2318
         *   (Insist on 1-byte length encodings to protect against variants of
2319
         *    Bleichenbacher's forgery attack against lax PKCS#1v1.5 verification)
2320
         * - Need hashlen bytes for hash
2321
         * - Need oid_size bytes for hash alg OID.
2322
         */
2323
1.27k
        if (nb_pad < 10 + hashlen + oid_size) {
2324
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2325
0
        }
2326
1.27k
        nb_pad -= 10 + hashlen + oid_size;
2327
1.27k
    } else {
2328
0
        if (nb_pad < hashlen) {
2329
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2330
0
        }
2331
2332
0
        nb_pad -= hashlen;
2333
0
    }
2334
2335
    /* Need space for signature header and padding delimiter (3 bytes),
2336
     * and 8 bytes for the minimal padding */
2337
1.27k
    if (nb_pad < 3 + 8) {
2338
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2339
0
    }
2340
1.27k
    nb_pad -= 3;
2341
2342
    /* Now nb_pad is the amount of memory to be filled
2343
     * with padding, and at least 8 bytes long. */
2344
2345
    /* Write signature header and padding */
2346
1.27k
    *p++ = 0;
2347
1.27k
    *p++ = MBEDTLS_RSA_SIGN;
2348
1.27k
    memset(p, 0xFF, nb_pad);
2349
1.27k
    p += nb_pad;
2350
1.27k
    *p++ = 0;
2351
2352
    /* Are we signing raw data? */
2353
1.27k
    if (md_alg == MBEDTLS_MD_NONE) {
2354
0
        memcpy(p, hash, hashlen);
2355
0
        return 0;
2356
0
    }
2357
2358
    /* Signing hashed data, add corresponding ASN.1 structure
2359
     *
2360
     * DigestInfo ::= SEQUENCE {
2361
     *   digestAlgorithm DigestAlgorithmIdentifier,
2362
     *   digest Digest }
2363
     * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
2364
     * Digest ::= OCTET STRING
2365
     *
2366
     * Schematic:
2367
     * TAG-SEQ + LEN [ TAG-SEQ + LEN [ TAG-OID  + LEN [ OID  ]
2368
     *                                 TAG-NULL + LEN [ NULL ] ]
2369
     *                 TAG-OCTET + LEN [ HASH ] ]
2370
     */
2371
1.27k
    *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
2372
1.27k
    *p++ = (unsigned char) (0x08 + oid_size + hashlen);
2373
1.27k
    *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
2374
1.27k
    *p++ = (unsigned char) (0x04 + oid_size);
2375
1.27k
    *p++ = MBEDTLS_ASN1_OID;
2376
1.27k
    *p++ = (unsigned char) oid_size;
2377
1.27k
    memcpy(p, oid, oid_size);
2378
1.27k
    p += oid_size;
2379
1.27k
    *p++ = MBEDTLS_ASN1_NULL;
2380
1.27k
    *p++ = 0x00;
2381
1.27k
    *p++ = MBEDTLS_ASN1_OCTET_STRING;
2382
1.27k
    *p++ = (unsigned char) hashlen;
2383
1.27k
    memcpy(p, hash, hashlen);
2384
1.27k
    p += hashlen;
2385
2386
    /* Just a sanity-check, should be automatic
2387
     * after the initial bounds check. */
2388
1.27k
    if (p != dst + dst_len) {
2389
0
        mbedtls_platform_zeroize(dst, dst_len);
2390
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2391
0
    }
2392
2393
1.27k
    return 0;
2394
1.27k
}
2395
2396
/*
2397
 * Do an RSA operation to sign the message digest
2398
 */
2399
int mbedtls_rsa_rsassa_pkcs1_v15_sign(mbedtls_rsa_context *ctx,
2400
                                      int (*f_rng)(void *, unsigned char *, size_t),
2401
                                      void *p_rng,
2402
                                      mbedtls_md_type_t md_alg,
2403
                                      unsigned int hashlen,
2404
                                      const unsigned char *hash,
2405
                                      unsigned char *sig)
2406
179
{
2407
179
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2408
179
    unsigned char *sig_try = NULL, *verif = NULL;
2409
2410
179
    if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2411
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2412
0
    }
2413
2414
179
    if (ctx->padding != MBEDTLS_RSA_PKCS_V15) {
2415
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2416
0
    }
2417
2418
    /*
2419
     * Prepare PKCS1-v1.5 encoding (padding and hash identifier)
2420
     */
2421
2422
179
    if ((ret = rsa_rsassa_pkcs1_v15_encode(md_alg, hashlen, hash,
2423
179
                                           ctx->len, sig)) != 0) {
2424
0
        return ret;
2425
0
    }
2426
2427
    /* Private key operation
2428
     *
2429
     * In order to prevent Lenstra's attack, make the signature in a
2430
     * temporary buffer and check it before returning it.
2431
     */
2432
2433
179
    sig_try = mbedtls_calloc(1, ctx->len);
2434
179
    if (sig_try == NULL) {
2435
0
        return MBEDTLS_ERR_MPI_ALLOC_FAILED;
2436
0
    }
2437
2438
179
    verif = mbedtls_calloc(1, ctx->len);
2439
179
    if (verif == NULL) {
2440
0
        mbedtls_free(sig_try);
2441
0
        return MBEDTLS_ERR_MPI_ALLOC_FAILED;
2442
0
    }
2443
2444
179
    MBEDTLS_MPI_CHK(mbedtls_rsa_private(ctx, f_rng, p_rng, sig, sig_try));
2445
179
    MBEDTLS_MPI_CHK(mbedtls_rsa_public(ctx, sig_try, verif));
2446
2447
179
    if (mbedtls_ct_memcmp(verif, sig, ctx->len) != 0) {
2448
0
        ret = MBEDTLS_ERR_RSA_PRIVATE_FAILED;
2449
0
        goto cleanup;
2450
0
    }
2451
2452
179
    memcpy(sig, sig_try, ctx->len);
2453
2454
179
cleanup:
2455
179
    mbedtls_zeroize_and_free(sig_try, ctx->len);
2456
179
    mbedtls_zeroize_and_free(verif, ctx->len);
2457
2458
179
    if (ret != 0) {
2459
0
        memset(sig, '!', ctx->len);
2460
0
    }
2461
179
    return ret;
2462
179
}
2463
#endif /* MBEDTLS_PKCS1_V15 */
2464
2465
/*
2466
 * Do an RSA operation to sign the message digest
2467
 */
2468
int mbedtls_rsa_pkcs1_sign(mbedtls_rsa_context *ctx,
2469
                           int (*f_rng)(void *, unsigned char *, size_t),
2470
                           void *p_rng,
2471
                           mbedtls_md_type_t md_alg,
2472
                           unsigned int hashlen,
2473
                           const unsigned char *hash,
2474
                           unsigned char *sig)
2475
179
{
2476
179
    if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2477
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2478
0
    }
2479
2480
179
    switch (ctx->padding) {
2481
0
#if defined(MBEDTLS_PKCS1_V15)
2482
179
        case MBEDTLS_RSA_PKCS_V15:
2483
179
            return mbedtls_rsa_rsassa_pkcs1_v15_sign(ctx, f_rng, p_rng,
2484
179
                                                     md_alg, hashlen, hash, sig);
2485
0
#endif
2486
2487
0
#if defined(MBEDTLS_PKCS1_V21)
2488
0
        case MBEDTLS_RSA_PKCS_V21:
2489
0
            return mbedtls_rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
2490
0
                                               hashlen, hash, sig);
2491
0
#endif
2492
2493
0
        default:
2494
0
            return MBEDTLS_ERR_RSA_INVALID_PADDING;
2495
179
    }
2496
179
}
2497
2498
#if defined(MBEDTLS_PKCS1_V21)
2499
/*
2500
 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function
2501
 */
2502
int mbedtls_rsa_rsassa_pss_verify_ext(mbedtls_rsa_context *ctx,
2503
                                      mbedtls_md_type_t md_alg,
2504
                                      unsigned int hashlen,
2505
                                      const unsigned char *hash,
2506
                                      mbedtls_md_type_t mgf1_hash_id,
2507
                                      int expected_salt_len,
2508
                                      const unsigned char *sig)
2509
0
{
2510
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2511
0
    size_t siglen;
2512
0
    unsigned char *p;
2513
0
    unsigned char *hash_start;
2514
0
    unsigned char result[MBEDTLS_MD_MAX_SIZE];
2515
0
    unsigned int hlen;
2516
0
    size_t observed_salt_len, msb;
2517
0
    unsigned char buf[MBEDTLS_MPI_MAX_SIZE] = { 0 };
2518
2519
0
    if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2520
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2521
0
    }
2522
2523
0
    siglen = ctx->len;
2524
2525
0
    if (siglen < 16 || siglen > sizeof(buf)) {
2526
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2527
0
    }
2528
2529
0
    ret = mbedtls_rsa_public(ctx, sig, buf);
2530
2531
0
    if (ret != 0) {
2532
0
        return ret;
2533
0
    }
2534
2535
0
    p = buf;
2536
2537
0
    if (buf[siglen - 1] != 0xBC) {
2538
0
        return MBEDTLS_ERR_RSA_INVALID_PADDING;
2539
0
    }
2540
2541
0
    if (md_alg != MBEDTLS_MD_NONE) {
2542
        /* Gather length of hash to sign */
2543
0
        size_t exp_hashlen = mbedtls_md_get_size_from_type(md_alg);
2544
0
        if (exp_hashlen == 0) {
2545
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2546
0
        }
2547
2548
0
        if (hashlen != exp_hashlen) {
2549
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2550
0
        }
2551
0
    }
2552
2553
0
    hlen = mbedtls_md_get_size_from_type(mgf1_hash_id);
2554
0
    if (hlen == 0) {
2555
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2556
0
    }
2557
2558
    /*
2559
     * Note: EMSA-PSS verification is over the length of N - 1 bits
2560
     */
2561
0
    msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
2562
2563
0
    if (buf[0] >> (8 - siglen * 8 + msb)) {
2564
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2565
0
    }
2566
2567
    /* Compensate for boundary condition when applying mask */
2568
0
    if (msb % 8 == 0) {
2569
0
        p++;
2570
0
        siglen -= 1;
2571
0
    }
2572
2573
0
    if (siglen < hlen + 2) {
2574
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2575
0
    }
2576
0
    hash_start = p + siglen - hlen - 1;
2577
2578
0
    ret = mgf_mask(p, siglen - hlen - 1, hash_start, hlen, mgf1_hash_id);
2579
0
    if (ret != 0) {
2580
0
        return ret;
2581
0
    }
2582
2583
0
    buf[0] &= 0xFF >> (siglen * 8 - msb);
2584
2585
0
    while (p < hash_start - 1 && *p == 0) {
2586
0
        p++;
2587
0
    }
2588
2589
0
    if (*p++ != 0x01) {
2590
0
        return MBEDTLS_ERR_RSA_INVALID_PADDING;
2591
0
    }
2592
2593
0
    observed_salt_len = (size_t) (hash_start - p);
2594
2595
0
    if (expected_salt_len != MBEDTLS_RSA_SALT_LEN_ANY &&
2596
0
        observed_salt_len != (size_t) expected_salt_len) {
2597
0
        return MBEDTLS_ERR_RSA_INVALID_PADDING;
2598
0
    }
2599
2600
    /*
2601
     * Generate H = Hash( M' )
2602
     */
2603
0
    ret = hash_mprime(hash, hashlen, p, observed_salt_len,
2604
0
                      result, mgf1_hash_id);
2605
0
    if (ret != 0) {
2606
0
        return ret;
2607
0
    }
2608
2609
0
    if (memcmp(hash_start, result, hlen) != 0) {
2610
0
        return MBEDTLS_ERR_RSA_VERIFY_FAILED;
2611
0
    }
2612
2613
0
    return 0;
2614
0
}
2615
2616
/*
2617
 * Simplified PKCS#1 v2.1 RSASSA-PSS-VERIFY function
2618
 */
2619
int mbedtls_rsa_rsassa_pss_verify(mbedtls_rsa_context *ctx,
2620
                                  mbedtls_md_type_t md_alg,
2621
                                  unsigned int hashlen,
2622
                                  const unsigned char *hash,
2623
                                  const unsigned char *sig)
2624
0
{
2625
0
    mbedtls_md_type_t mgf1_hash_id;
2626
0
    if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2627
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2628
0
    }
2629
2630
0
    mgf1_hash_id = (ctx->hash_id != MBEDTLS_MD_NONE)
2631
0
                             ? (mbedtls_md_type_t) ctx->hash_id
2632
0
                             : md_alg;
2633
2634
0
    return mbedtls_rsa_rsassa_pss_verify_ext(ctx,
2635
0
                                             md_alg, hashlen, hash,
2636
0
                                             mgf1_hash_id,
2637
0
                                             MBEDTLS_RSA_SALT_LEN_ANY,
2638
0
                                             sig);
2639
2640
0
}
2641
#endif /* MBEDTLS_PKCS1_V21 */
2642
2643
#if defined(MBEDTLS_PKCS1_V15)
2644
/*
2645
 * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-v1_5-VERIFY function
2646
 */
2647
int mbedtls_rsa_rsassa_pkcs1_v15_verify(mbedtls_rsa_context *ctx,
2648
                                        mbedtls_md_type_t md_alg,
2649
                                        unsigned int hashlen,
2650
                                        const unsigned char *hash,
2651
                                        const unsigned char *sig)
2652
1.09k
{
2653
1.09k
    int ret = 0;
2654
1.09k
    size_t sig_len;
2655
1.09k
    unsigned char *encoded = NULL, *encoded_expected = NULL;
2656
2657
1.09k
    if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2658
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2659
0
    }
2660
2661
1.09k
    sig_len = ctx->len;
2662
2663
    /*
2664
     * Prepare expected PKCS1 v1.5 encoding of hash.
2665
     */
2666
2667
1.09k
    if ((encoded          = mbedtls_calloc(1, sig_len)) == NULL ||
2668
1.09k
        (encoded_expected = mbedtls_calloc(1, sig_len)) == NULL) {
2669
0
        ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
2670
0
        goto cleanup;
2671
0
    }
2672
2673
1.09k
    if ((ret = rsa_rsassa_pkcs1_v15_encode(md_alg, hashlen, hash, sig_len,
2674
1.09k
                                           encoded_expected)) != 0) {
2675
0
        goto cleanup;
2676
0
    }
2677
2678
    /*
2679
     * Apply RSA primitive to get what should be PKCS1 encoded hash.
2680
     */
2681
2682
1.09k
    ret = mbedtls_rsa_public(ctx, sig, encoded);
2683
1.09k
    if (ret != 0) {
2684
0
        goto cleanup;
2685
0
    }
2686
2687
    /*
2688
     * Compare
2689
     */
2690
2691
1.09k
    if ((ret = mbedtls_ct_memcmp(encoded, encoded_expected,
2692
1.09k
                                 sig_len)) != 0) {
2693
5
        ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
2694
5
        goto cleanup;
2695
5
    }
2696
2697
1.09k
cleanup:
2698
2699
1.09k
    if (encoded != NULL) {
2700
1.09k
        mbedtls_zeroize_and_free(encoded, sig_len);
2701
1.09k
    }
2702
2703
1.09k
    if (encoded_expected != NULL) {
2704
1.09k
        mbedtls_zeroize_and_free(encoded_expected, sig_len);
2705
1.09k
    }
2706
2707
1.09k
    return ret;
2708
1.09k
}
2709
#endif /* MBEDTLS_PKCS1_V15 */
2710
2711
/*
2712
 * Do an RSA operation and check the message digest
2713
 */
2714
int mbedtls_rsa_pkcs1_verify(mbedtls_rsa_context *ctx,
2715
                             mbedtls_md_type_t md_alg,
2716
                             unsigned int hashlen,
2717
                             const unsigned char *hash,
2718
                             const unsigned char *sig)
2719
1.09k
{
2720
1.09k
    if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2721
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2722
0
    }
2723
2724
1.09k
    switch (ctx->padding) {
2725
0
#if defined(MBEDTLS_PKCS1_V15)
2726
1.09k
        case MBEDTLS_RSA_PKCS_V15:
2727
1.09k
            return mbedtls_rsa_rsassa_pkcs1_v15_verify(ctx, md_alg,
2728
1.09k
                                                       hashlen, hash, sig);
2729
0
#endif
2730
2731
0
#if defined(MBEDTLS_PKCS1_V21)
2732
0
        case MBEDTLS_RSA_PKCS_V21:
2733
0
            return mbedtls_rsa_rsassa_pss_verify(ctx, md_alg,
2734
0
                                                 hashlen, hash, sig);
2735
0
#endif
2736
2737
0
        default:
2738
0
            return MBEDTLS_ERR_RSA_INVALID_PADDING;
2739
1.09k
    }
2740
1.09k
}
2741
2742
/*
2743
 * Copy the components of an RSA key
2744
 */
2745
int mbedtls_rsa_copy(mbedtls_rsa_context *dst, const mbedtls_rsa_context *src)
2746
1.05k
{
2747
1.05k
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2748
2749
1.05k
    dst->len = src->len;
2750
2751
1.05k
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->N, &src->N));
2752
1.05k
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->E, &src->E));
2753
2754
1.05k
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->D, &src->D));
2755
1.05k
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->P, &src->P));
2756
1.05k
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Q, &src->Q));
2757
2758
1.05k
#if !defined(MBEDTLS_RSA_NO_CRT)
2759
1.05k
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->DP, &src->DP));
2760
1.05k
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->DQ, &src->DQ));
2761
1.05k
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->QP, &src->QP));
2762
1.05k
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RP, &src->RP));
2763
1.05k
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RQ, &src->RQ));
2764
1.05k
#endif
2765
2766
1.05k
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RN, &src->RN));
2767
2768
1.05k
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Vi, &src->Vi));
2769
1.05k
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Vf, &src->Vf));
2770
2771
1.05k
    dst->padding = src->padding;
2772
1.05k
    dst->hash_id = src->hash_id;
2773
2774
1.05k
cleanup:
2775
1.05k
    if (ret != 0) {
2776
0
        mbedtls_rsa_free(dst);
2777
0
    }
2778
2779
1.05k
    return ret;
2780
1.05k
}
2781
2782
/*
2783
 * Free the components of an RSA key
2784
 */
2785
void mbedtls_rsa_free(mbedtls_rsa_context *ctx)
2786
12.7k
{
2787
12.7k
    if (ctx == NULL) {
2788
0
        return;
2789
0
    }
2790
2791
12.7k
    mbedtls_mpi_free(&ctx->Vi);
2792
12.7k
    mbedtls_mpi_free(&ctx->Vf);
2793
12.7k
    mbedtls_mpi_free(&ctx->RN);
2794
12.7k
    mbedtls_mpi_free(&ctx->D);
2795
12.7k
    mbedtls_mpi_free(&ctx->Q);
2796
12.7k
    mbedtls_mpi_free(&ctx->P);
2797
12.7k
    mbedtls_mpi_free(&ctx->E);
2798
12.7k
    mbedtls_mpi_free(&ctx->N);
2799
2800
12.7k
#if !defined(MBEDTLS_RSA_NO_CRT)
2801
12.7k
    mbedtls_mpi_free(&ctx->RQ);
2802
12.7k
    mbedtls_mpi_free(&ctx->RP);
2803
12.7k
    mbedtls_mpi_free(&ctx->QP);
2804
12.7k
    mbedtls_mpi_free(&ctx->DQ);
2805
12.7k
    mbedtls_mpi_free(&ctx->DP);
2806
12.7k
#endif /* MBEDTLS_RSA_NO_CRT */
2807
2808
#if defined(MBEDTLS_THREADING_C)
2809
    /* Free the mutex, but only if it hasn't been freed already. */
2810
    if (ctx->ver != 0) {
2811
        mbedtls_mutex_free(&ctx->mutex);
2812
        ctx->ver = 0;
2813
    }
2814
#endif
2815
12.7k
}
2816
2817
#endif /* !MBEDTLS_RSA_ALT */
2818
2819
#if defined(MBEDTLS_SELF_TEST)
2820
2821
2822
/*
2823
 * Example RSA-1024 keypair, for test purposes
2824
 */
2825
#define KEY_LEN 128
2826
2827
#define RSA_N   "9292758453063D803DD603D5E777D788" \
2828
                "8ED1D5BF35786190FA2F23EBC0848AEA" \
2829
                "DDA92CA6C3D80B32C4D109BE0F36D6AE" \
2830
                "7130B9CED7ACDF54CFC7555AC14EEBAB" \
2831
                "93A89813FBF3C4F8066D2D800F7C38A8" \
2832
                "1AE31942917403FF4946B0A83D3D3E05" \
2833
                "EE57C6F5F5606FB5D4BC6CD34EE0801A" \
2834
                "5E94BB77B07507233A0BC7BAC8F90F79"
2835
2836
#define RSA_E   "10001"
2837
2838
#define RSA_D   "24BF6185468786FDD303083D25E64EFC" \
2839
                "66CA472BC44D253102F8B4A9D3BFA750" \
2840
                "91386C0077937FE33FA3252D28855837" \
2841
                "AE1B484A8A9A45F7EE8C0C634F99E8CD" \
2842
                "DF79C5CE07EE72C7F123142198164234" \
2843
                "CABB724CF78B8173B9F880FC86322407" \
2844
                "AF1FEDFDDE2BEB674CA15F3E81A1521E" \
2845
                "071513A1E85B5DFA031F21ECAE91A34D"
2846
2847
#define RSA_P   "C36D0EB7FCD285223CFB5AABA5BDA3D8" \
2848
                "2C01CAD19EA484A87EA4377637E75500" \
2849
                "FCB2005C5C7DD6EC4AC023CDA285D796" \
2850
                "C3D9E75E1EFC42488BB4F1D13AC30A57"
2851
2852
#define RSA_Q   "C000DF51A7C77AE8D7C7370C1FF55B69" \
2853
                "E211C2B9E5DB1ED0BF61D0D9899620F4" \
2854
                "910E4168387E3C30AA1E00C339A79508" \
2855
                "8452DD96A9A5EA5D9DCA68DA636032AF"
2856
2857
0
#define PT_LEN  24
2858
0
#define RSA_PT  "\xAA\xBB\xCC\x03\x02\x01\x00\xFF\xFF\xFF\xFF\xFF" \
2859
0
                "\x11\x22\x33\x0A\x0B\x0C\xCC\xDD\xDD\xDD\xDD\xDD"
2860
2861
#if defined(MBEDTLS_PKCS1_V15)
2862
static int myrand(void *rng_state, unsigned char *output, size_t len)
2863
0
{
2864
0
#if !defined(__OpenBSD__) && !defined(__NetBSD__)
2865
0
    size_t i;
2866
2867
0
    if (rng_state != NULL) {
2868
0
        rng_state  = NULL;
2869
0
    }
2870
2871
0
    for (i = 0; i < len; ++i) {
2872
0
        output[i] = rand();
2873
0
    }
2874
#else
2875
    if (rng_state != NULL) {
2876
        rng_state = NULL;
2877
    }
2878
2879
    arc4random_buf(output, len);
2880
#endif /* !OpenBSD && !NetBSD */
2881
2882
0
    return 0;
2883
0
}
2884
#endif /* MBEDTLS_PKCS1_V15 */
2885
2886
/*
2887
 * Checkup routine
2888
 */
2889
int mbedtls_rsa_self_test(int verbose)
2890
0
{
2891
0
    int ret = 0;
2892
0
#if defined(MBEDTLS_PKCS1_V15)
2893
0
    size_t len;
2894
0
    mbedtls_rsa_context rsa;
2895
0
    unsigned char rsa_plaintext[PT_LEN];
2896
0
    unsigned char rsa_decrypted[PT_LEN];
2897
0
    unsigned char rsa_ciphertext[KEY_LEN];
2898
#if defined(MBEDTLS_MD_CAN_SHA1)
2899
    unsigned char sha1sum[20];
2900
#endif
2901
2902
0
    mbedtls_mpi K;
2903
2904
0
    mbedtls_mpi_init(&K);
2905
0
    mbedtls_rsa_init(&rsa);
2906
2907
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_N));
2908
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, &K, NULL, NULL, NULL, NULL));
2909
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_P));
2910
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, &K, NULL, NULL, NULL));
2911
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_Q));
2912
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, &K, NULL, NULL));
2913
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_D));
2914
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, NULL, &K, NULL));
2915
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_E));
2916
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, NULL, NULL, &K));
2917
2918
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_complete(&rsa));
2919
2920
0
    if (verbose != 0) {
2921
0
        mbedtls_printf("  RSA key validation: ");
2922
0
    }
2923
2924
0
    if (mbedtls_rsa_check_pubkey(&rsa) != 0 ||
2925
0
        mbedtls_rsa_check_privkey(&rsa) != 0) {
2926
0
        if (verbose != 0) {
2927
0
            mbedtls_printf("failed\n");
2928
0
        }
2929
2930
0
        ret = 1;
2931
0
        goto cleanup;
2932
0
    }
2933
2934
0
    if (verbose != 0) {
2935
0
        mbedtls_printf("passed\n  PKCS#1 encryption : ");
2936
0
    }
2937
2938
0
    memcpy(rsa_plaintext, RSA_PT, PT_LEN);
2939
2940
0
    if (mbedtls_rsa_pkcs1_encrypt(&rsa, myrand, NULL,
2941
0
                                  PT_LEN, rsa_plaintext,
2942
0
                                  rsa_ciphertext) != 0) {
2943
0
        if (verbose != 0) {
2944
0
            mbedtls_printf("failed\n");
2945
0
        }
2946
2947
0
        ret = 1;
2948
0
        goto cleanup;
2949
0
    }
2950
2951
0
    if (verbose != 0) {
2952
0
        mbedtls_printf("passed\n  PKCS#1 decryption : ");
2953
0
    }
2954
2955
0
    if (mbedtls_rsa_pkcs1_decrypt(&rsa, myrand, NULL,
2956
0
                                  &len, rsa_ciphertext, rsa_decrypted,
2957
0
                                  sizeof(rsa_decrypted)) != 0) {
2958
0
        if (verbose != 0) {
2959
0
            mbedtls_printf("failed\n");
2960
0
        }
2961
2962
0
        ret = 1;
2963
0
        goto cleanup;
2964
0
    }
2965
2966
0
    if (memcmp(rsa_decrypted, rsa_plaintext, len) != 0) {
2967
0
        if (verbose != 0) {
2968
0
            mbedtls_printf("failed\n");
2969
0
        }
2970
2971
0
        ret = 1;
2972
0
        goto cleanup;
2973
0
    }
2974
2975
0
    if (verbose != 0) {
2976
0
        mbedtls_printf("passed\n");
2977
0
    }
2978
2979
#if defined(MBEDTLS_MD_CAN_SHA1)
2980
    if (verbose != 0) {
2981
        mbedtls_printf("  PKCS#1 data sign  : ");
2982
    }
2983
2984
    if (mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1),
2985
                   rsa_plaintext, PT_LEN, sha1sum) != 0) {
2986
        if (verbose != 0) {
2987
            mbedtls_printf("failed\n");
2988
        }
2989
2990
        return 1;
2991
    }
2992
2993
    if (mbedtls_rsa_pkcs1_sign(&rsa, myrand, NULL,
2994
                               MBEDTLS_MD_SHA1, 20,
2995
                               sha1sum, rsa_ciphertext) != 0) {
2996
        if (verbose != 0) {
2997
            mbedtls_printf("failed\n");
2998
        }
2999
3000
        ret = 1;
3001
        goto cleanup;
3002
    }
3003
3004
    if (verbose != 0) {
3005
        mbedtls_printf("passed\n  PKCS#1 sig. verify: ");
3006
    }
3007
3008
    if (mbedtls_rsa_pkcs1_verify(&rsa, MBEDTLS_MD_SHA1, 20,
3009
                                 sha1sum, rsa_ciphertext) != 0) {
3010
        if (verbose != 0) {
3011
            mbedtls_printf("failed\n");
3012
        }
3013
3014
        ret = 1;
3015
        goto cleanup;
3016
    }
3017
3018
    if (verbose != 0) {
3019
        mbedtls_printf("passed\n");
3020
    }
3021
#endif /* MBEDTLS_MD_CAN_SHA1 */
3022
3023
0
    if (verbose != 0) {
3024
0
        mbedtls_printf("\n");
3025
0
    }
3026
3027
0
cleanup:
3028
0
    mbedtls_mpi_free(&K);
3029
0
    mbedtls_rsa_free(&rsa);
3030
#else /* MBEDTLS_PKCS1_V15 */
3031
    ((void) verbose);
3032
#endif /* MBEDTLS_PKCS1_V15 */
3033
0
    return ret;
3034
0
}
3035
3036
#endif /* MBEDTLS_SELF_TEST */
3037
3038
#endif /* MBEDTLS_RSA_C */