Coverage Report

Created: 2024-11-21 07:03

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