Coverage Report

Created: 2026-04-01 06:05

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