Coverage Report

Created: 2026-11-11 06:47

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