Coverage Report

Created: 2024-08-27 12:20

/src/mbedtls/library/rsa.c
Line
Count
Source (jump to first uncovered line)
1
/*
2
 *  The RSA public-key cryptosystem
3
 *
4
 *  Copyright The Mbed TLS Contributors
5
 *  SPDX-License-Identifier: Apache-2.0
6
 *
7
 *  Licensed under the Apache License, Version 2.0 (the "License"); you may
8
 *  not use this file except in compliance with the License.
9
 *  You may obtain a copy of the License at
10
 *
11
 *  http://www.apache.org/licenses/LICENSE-2.0
12
 *
13
 *  Unless required by applicable law or agreed to in writing, software
14
 *  distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15
 *  WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
 *  See the License for the specific language governing permissions and
17
 *  limitations under the License.
18
 */
19
20
/*
21
 *  The following sources were referenced in the design of this implementation
22
 *  of the RSA algorithm:
23
 *
24
 *  [1] A method for obtaining digital signatures and public-key cryptosystems
25
 *      R Rivest, A Shamir, and L Adleman
26
 *      http://people.csail.mit.edu/rivest/pubs.html#RSA78
27
 *
28
 *  [2] Handbook of Applied Cryptography - 1997, Chapter 8
29
 *      Menezes, van Oorschot and Vanstone
30
 *
31
 *  [3] Malware Guard Extension: Using SGX to Conceal Cache Attacks
32
 *      Michael Schwarz, Samuel Weiser, Daniel Gruss, Clémentine Maurice and
33
 *      Stefan Mangard
34
 *      https://arxiv.org/abs/1702.08719v2
35
 *
36
 */
37
38
#include "common.h"
39
40
#if defined(MBEDTLS_RSA_C)
41
42
#include "mbedtls/rsa.h"
43
#include "rsa_alt_helpers.h"
44
#include "mbedtls/oid.h"
45
#include "mbedtls/platform_util.h"
46
#include "mbedtls/error.h"
47
#include "constant_time_internal.h"
48
#include "mbedtls/constant_time.h"
49
#include "hash_info.h"
50
51
#include <string.h>
52
53
#if defined(MBEDTLS_PKCS1_V15) && !defined(__OpenBSD__) && !defined(__NetBSD__)
54
#include <stdlib.h>
55
#endif
56
57
/* We use MD first if it's available (for compatibility reasons)
58
 * and "fall back" to PSA otherwise (which needs psa_crypto_init()). */
59
#if defined(MBEDTLS_PKCS1_V21)
60
#if !defined(MBEDTLS_MD_C)
61
#include "psa/crypto.h"
62
#include "mbedtls/psa_util.h"
63
#endif /* MBEDTLS_MD_C */
64
#endif /* MBEDTLS_PKCS1_V21 */
65
66
#include "mbedtls/platform.h"
67
68
#if !defined(MBEDTLS_RSA_ALT)
69
70
int mbedtls_rsa_import(mbedtls_rsa_context *ctx,
71
                       const mbedtls_mpi *N,
72
                       const mbedtls_mpi *P, const mbedtls_mpi *Q,
73
                       const mbedtls_mpi *D, const mbedtls_mpi *E)
74
0
{
75
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
76
77
0
    if ((N != NULL && (ret = mbedtls_mpi_copy(&ctx->N, N)) != 0) ||
78
0
        (P != NULL && (ret = mbedtls_mpi_copy(&ctx->P, P)) != 0) ||
79
0
        (Q != NULL && (ret = mbedtls_mpi_copy(&ctx->Q, Q)) != 0) ||
80
0
        (D != NULL && (ret = mbedtls_mpi_copy(&ctx->D, D)) != 0) ||
81
0
        (E != NULL && (ret = mbedtls_mpi_copy(&ctx->E, E)) != 0)) {
82
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
83
0
    }
84
85
0
    if (N != NULL) {
86
0
        ctx->len = mbedtls_mpi_size(&ctx->N);
87
0
    }
88
89
0
    return 0;
90
0
}
91
92
int mbedtls_rsa_import_raw(mbedtls_rsa_context *ctx,
93
                           unsigned char const *N, size_t N_len,
94
                           unsigned char const *P, size_t P_len,
95
                           unsigned char const *Q, size_t Q_len,
96
                           unsigned char const *D, size_t D_len,
97
                           unsigned char const *E, size_t E_len)
98
25.6k
{
99
25.6k
    int ret = 0;
100
101
25.6k
    if (N != NULL) {
102
12.9k
        MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->N, N, N_len));
103
12.9k
        ctx->len = mbedtls_mpi_size(&ctx->N);
104
12.9k
    }
105
106
25.6k
    if (P != NULL) {
107
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->P, P, P_len));
108
0
    }
109
110
25.6k
    if (Q != NULL) {
111
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->Q, Q, Q_len));
112
0
    }
113
114
25.6k
    if (D != NULL) {
115
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->D, D, D_len));
116
0
    }
117
118
25.6k
    if (E != NULL) {
119
12.6k
        MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&ctx->E, E, E_len));
120
12.6k
    }
121
122
25.6k
cleanup:
123
124
25.6k
    if (ret != 0) {
125
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
126
0
    }
127
128
25.6k
    return 0;
129
25.6k
}
130
131
/*
132
 * Checks whether the context fields are set in such a way
133
 * that the RSA primitives will be able to execute without error.
134
 * It does *not* make guarantees for consistency of the parameters.
135
 */
136
static int rsa_check_context(mbedtls_rsa_context const *ctx, int is_priv,
137
                             int blinding_needed)
138
26.2k
{
139
26.2k
#if !defined(MBEDTLS_RSA_NO_CRT)
140
    /* blinding_needed is only used for NO_CRT to decide whether
141
     * P,Q need to be present or not. */
142
26.2k
    ((void) blinding_needed);
143
26.2k
#endif
144
145
26.2k
    if (ctx->len != mbedtls_mpi_size(&ctx->N) ||
146
26.2k
        ctx->len > MBEDTLS_MPI_MAX_SIZE) {
147
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
148
0
    }
149
150
    /*
151
     * 1. Modular exponentiation needs positive, odd moduli.
152
     */
153
154
    /* Modular exponentiation wrt. N is always used for
155
     * RSA public key operations. */
156
26.2k
    if (mbedtls_mpi_cmp_int(&ctx->N, 0) <= 0 ||
157
26.2k
        mbedtls_mpi_get_bit(&ctx->N, 0) == 0) {
158
26
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
159
26
    }
160
161
26.2k
#if !defined(MBEDTLS_RSA_NO_CRT)
162
    /* Modular exponentiation for P and Q is only
163
     * used for private key operations and if CRT
164
     * is used. */
165
26.2k
    if (is_priv &&
166
26.2k
        (mbedtls_mpi_cmp_int(&ctx->P, 0) <= 0 ||
167
0
         mbedtls_mpi_get_bit(&ctx->P, 0) == 0 ||
168
0
         mbedtls_mpi_cmp_int(&ctx->Q, 0) <= 0 ||
169
0
         mbedtls_mpi_get_bit(&ctx->Q, 0) == 0)) {
170
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
171
0
    }
172
26.2k
#endif /* !MBEDTLS_RSA_NO_CRT */
173
174
    /*
175
     * 2. Exponents must be positive
176
     */
177
178
    /* Always need E for public key operations */
179
26.2k
    if (mbedtls_mpi_cmp_int(&ctx->E, 0) <= 0) {
180
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
181
0
    }
182
183
#if defined(MBEDTLS_RSA_NO_CRT)
184
    /* For private key operations, use D or DP & DQ
185
     * as (unblinded) exponents. */
186
    if (is_priv && mbedtls_mpi_cmp_int(&ctx->D, 0) <= 0) {
187
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
188
    }
189
#else
190
26.2k
    if (is_priv &&
191
26.2k
        (mbedtls_mpi_cmp_int(&ctx->DP, 0) <= 0 ||
192
0
         mbedtls_mpi_cmp_int(&ctx->DQ, 0) <= 0)) {
193
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
194
0
    }
195
26.2k
#endif /* MBEDTLS_RSA_NO_CRT */
196
197
    /* Blinding shouldn't make exponents negative either,
198
     * so check that P, Q >= 1 if that hasn't yet been
199
     * done as part of 1. */
200
#if defined(MBEDTLS_RSA_NO_CRT)
201
    if (is_priv && blinding_needed &&
202
        (mbedtls_mpi_cmp_int(&ctx->P, 0) <= 0 ||
203
         mbedtls_mpi_cmp_int(&ctx->Q, 0) <= 0)) {
204
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
205
    }
206
#endif
207
208
    /* It wouldn't lead to an error if it wasn't satisfied,
209
     * but check for QP >= 1 nonetheless. */
210
26.2k
#if !defined(MBEDTLS_RSA_NO_CRT)
211
26.2k
    if (is_priv &&
212
26.2k
        mbedtls_mpi_cmp_int(&ctx->QP, 0) <= 0) {
213
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
214
0
    }
215
26.2k
#endif
216
217
26.2k
    return 0;
218
26.2k
}
219
220
int mbedtls_rsa_complete(mbedtls_rsa_context *ctx)
221
12.6k
{
222
12.6k
    int ret = 0;
223
12.6k
    int have_N, have_P, have_Q, have_D, have_E;
224
12.6k
#if !defined(MBEDTLS_RSA_NO_CRT)
225
12.6k
    int have_DP, have_DQ, have_QP;
226
12.6k
#endif
227
12.6k
    int n_missing, pq_missing, d_missing, is_pub, is_priv;
228
229
12.6k
    have_N = (mbedtls_mpi_cmp_int(&ctx->N, 0) != 0);
230
12.6k
    have_P = (mbedtls_mpi_cmp_int(&ctx->P, 0) != 0);
231
12.6k
    have_Q = (mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0);
232
12.6k
    have_D = (mbedtls_mpi_cmp_int(&ctx->D, 0) != 0);
233
12.6k
    have_E = (mbedtls_mpi_cmp_int(&ctx->E, 0) != 0);
234
235
12.6k
#if !defined(MBEDTLS_RSA_NO_CRT)
236
12.6k
    have_DP = (mbedtls_mpi_cmp_int(&ctx->DP, 0) != 0);
237
12.6k
    have_DQ = (mbedtls_mpi_cmp_int(&ctx->DQ, 0) != 0);
238
12.6k
    have_QP = (mbedtls_mpi_cmp_int(&ctx->QP, 0) != 0);
239
12.6k
#endif
240
241
    /*
242
     * Check whether provided parameters are enough
243
     * to deduce all others. The following incomplete
244
     * parameter sets for private keys are supported:
245
     *
246
     * (1) P, Q missing.
247
     * (2) D and potentially N missing.
248
     *
249
     */
250
251
12.6k
    n_missing  =              have_P &&  have_Q &&  have_D && have_E;
252
12.6k
    pq_missing =   have_N && !have_P && !have_Q &&  have_D && have_E;
253
12.6k
    d_missing  =              have_P &&  have_Q && !have_D && have_E;
254
12.6k
    is_pub     =   have_N && !have_P && !have_Q && !have_D && have_E;
255
256
    /* These three alternatives are mutually exclusive */
257
12.6k
    is_priv = n_missing || pq_missing || d_missing;
258
259
12.6k
    if (!is_priv && !is_pub) {
260
64
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
261
64
    }
262
263
    /*
264
     * Step 1: Deduce N if P, Q are provided.
265
     */
266
267
12.6k
    if (!have_N && have_P && have_Q) {
268
0
        if ((ret = mbedtls_mpi_mul_mpi(&ctx->N, &ctx->P,
269
0
                                       &ctx->Q)) != 0) {
270
0
            return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
271
0
        }
272
273
0
        ctx->len = mbedtls_mpi_size(&ctx->N);
274
0
    }
275
276
    /*
277
     * Step 2: Deduce and verify all remaining core parameters.
278
     */
279
280
12.6k
    if (pq_missing) {
281
0
        ret = mbedtls_rsa_deduce_primes(&ctx->N, &ctx->E, &ctx->D,
282
0
                                        &ctx->P, &ctx->Q);
283
0
        if (ret != 0) {
284
0
            return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
285
0
        }
286
287
12.6k
    } else if (d_missing) {
288
0
        if ((ret = mbedtls_rsa_deduce_private_exponent(&ctx->P,
289
0
                                                       &ctx->Q,
290
0
                                                       &ctx->E,
291
0
                                                       &ctx->D)) != 0) {
292
0
            return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
293
0
        }
294
0
    }
295
296
    /*
297
     * Step 3: Deduce all additional parameters specific
298
     *         to our current RSA implementation.
299
     */
300
301
12.6k
#if !defined(MBEDTLS_RSA_NO_CRT)
302
12.6k
    if (is_priv && !(have_DP && have_DQ && have_QP)) {
303
0
        ret = mbedtls_rsa_deduce_crt(&ctx->P,  &ctx->Q,  &ctx->D,
304
0
                                     &ctx->DP, &ctx->DQ, &ctx->QP);
305
0
        if (ret != 0) {
306
0
            return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
307
0
        }
308
0
    }
309
12.6k
#endif /* MBEDTLS_RSA_NO_CRT */
310
311
    /*
312
     * Step 3: Basic sanity checks
313
     */
314
315
12.6k
    return rsa_check_context(ctx, is_priv, 1);
316
12.6k
}
317
318
int mbedtls_rsa_export_raw(const mbedtls_rsa_context *ctx,
319
                           unsigned char *N, size_t N_len,
320
                           unsigned char *P, size_t P_len,
321
                           unsigned char *Q, size_t Q_len,
322
                           unsigned char *D, size_t D_len,
323
                           unsigned char *E, size_t E_len)
324
0
{
325
0
    int ret = 0;
326
0
    int is_priv;
327
328
    /* Check if key is private or public */
329
0
    is_priv =
330
0
        mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 &&
331
0
        mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 &&
332
0
        mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 &&
333
0
        mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 &&
334
0
        mbedtls_mpi_cmp_int(&ctx->E, 0) != 0;
335
336
0
    if (!is_priv) {
337
        /* If we're trying to export private parameters for a public key,
338
         * something must be wrong. */
339
0
        if (P != NULL || Q != NULL || D != NULL) {
340
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
341
0
        }
342
343
0
    }
344
345
0
    if (N != NULL) {
346
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->N, N, N_len));
347
0
    }
348
349
0
    if (P != NULL) {
350
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->P, P, P_len));
351
0
    }
352
353
0
    if (Q != NULL) {
354
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->Q, Q, Q_len));
355
0
    }
356
357
0
    if (D != NULL) {
358
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->D, D, D_len));
359
0
    }
360
361
0
    if (E != NULL) {
362
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&ctx->E, E, E_len));
363
0
    }
364
365
0
cleanup:
366
367
0
    return ret;
368
0
}
369
370
int mbedtls_rsa_export(const mbedtls_rsa_context *ctx,
371
                       mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q,
372
                       mbedtls_mpi *D, mbedtls_mpi *E)
373
0
{
374
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
375
0
    int is_priv;
376
377
    /* Check if key is private or public */
378
0
    is_priv =
379
0
        mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 &&
380
0
        mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 &&
381
0
        mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 &&
382
0
        mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 &&
383
0
        mbedtls_mpi_cmp_int(&ctx->E, 0) != 0;
384
385
0
    if (!is_priv) {
386
        /* If we're trying to export private parameters for a public key,
387
         * something must be wrong. */
388
0
        if (P != NULL || Q != NULL || D != NULL) {
389
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
390
0
        }
391
392
0
    }
393
394
    /* Export all requested core parameters. */
395
396
0
    if ((N != NULL && (ret = mbedtls_mpi_copy(N, &ctx->N)) != 0) ||
397
0
        (P != NULL && (ret = mbedtls_mpi_copy(P, &ctx->P)) != 0) ||
398
0
        (Q != NULL && (ret = mbedtls_mpi_copy(Q, &ctx->Q)) != 0) ||
399
0
        (D != NULL && (ret = mbedtls_mpi_copy(D, &ctx->D)) != 0) ||
400
0
        (E != NULL && (ret = mbedtls_mpi_copy(E, &ctx->E)) != 0)) {
401
0
        return ret;
402
0
    }
403
404
0
    return 0;
405
0
}
406
407
/*
408
 * Export CRT parameters
409
 * This must also be implemented if CRT is not used, for being able to
410
 * write DER encoded RSA keys. The helper function mbedtls_rsa_deduce_crt
411
 * can be used in this case.
412
 */
413
int mbedtls_rsa_export_crt(const mbedtls_rsa_context *ctx,
414
                           mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP)
415
0
{
416
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
417
0
    int is_priv;
418
419
    /* Check if key is private or public */
420
0
    is_priv =
421
0
        mbedtls_mpi_cmp_int(&ctx->N, 0) != 0 &&
422
0
        mbedtls_mpi_cmp_int(&ctx->P, 0) != 0 &&
423
0
        mbedtls_mpi_cmp_int(&ctx->Q, 0) != 0 &&
424
0
        mbedtls_mpi_cmp_int(&ctx->D, 0) != 0 &&
425
0
        mbedtls_mpi_cmp_int(&ctx->E, 0) != 0;
426
427
0
    if (!is_priv) {
428
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
429
0
    }
430
431
0
#if !defined(MBEDTLS_RSA_NO_CRT)
432
    /* Export all requested blinding parameters. */
433
0
    if ((DP != NULL && (ret = mbedtls_mpi_copy(DP, &ctx->DP)) != 0) ||
434
0
        (DQ != NULL && (ret = mbedtls_mpi_copy(DQ, &ctx->DQ)) != 0) ||
435
0
        (QP != NULL && (ret = mbedtls_mpi_copy(QP, &ctx->QP)) != 0)) {
436
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
437
0
    }
438
#else
439
    if ((ret = mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D,
440
                                      DP, DQ, QP)) != 0) {
441
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_BAD_INPUT_DATA, ret);
442
    }
443
#endif
444
445
0
    return 0;
446
0
}
447
448
/*
449
 * Initialize an RSA context
450
 */
451
void mbedtls_rsa_init(mbedtls_rsa_context *ctx)
452
13.0k
{
453
13.0k
    memset(ctx, 0, sizeof(mbedtls_rsa_context));
454
455
13.0k
    ctx->padding = MBEDTLS_RSA_PKCS_V15;
456
13.0k
    ctx->hash_id = MBEDTLS_MD_NONE;
457
458
#if defined(MBEDTLS_THREADING_C)
459
    /* Set ctx->ver to nonzero to indicate that the mutex has been
460
     * initialized and will need to be freed. */
461
    ctx->ver = 1;
462
    mbedtls_mutex_init(&ctx->mutex);
463
#endif
464
13.0k
}
465
466
/*
467
 * Set padding for an existing RSA context
468
 */
469
int mbedtls_rsa_set_padding(mbedtls_rsa_context *ctx, int padding,
470
                            mbedtls_md_type_t hash_id)
471
0
{
472
0
    switch (padding) {
473
0
#if defined(MBEDTLS_PKCS1_V15)
474
0
        case MBEDTLS_RSA_PKCS_V15:
475
0
            break;
476
0
#endif
477
478
0
#if defined(MBEDTLS_PKCS1_V21)
479
0
        case MBEDTLS_RSA_PKCS_V21:
480
0
            break;
481
0
#endif
482
0
        default:
483
0
            return MBEDTLS_ERR_RSA_INVALID_PADDING;
484
0
    }
485
486
0
#if defined(MBEDTLS_PKCS1_V21)
487
0
    if ((padding == MBEDTLS_RSA_PKCS_V21) &&
488
0
        (hash_id != MBEDTLS_MD_NONE)) {
489
        /* Just make sure this hash is supported in this build. */
490
0
        if (mbedtls_hash_info_psa_from_md(hash_id) == PSA_ALG_NONE) {
491
0
            return MBEDTLS_ERR_RSA_INVALID_PADDING;
492
0
        }
493
0
    }
494
0
#endif /* MBEDTLS_PKCS1_V21 */
495
496
0
    ctx->padding = padding;
497
0
    ctx->hash_id = hash_id;
498
499
0
    return 0;
500
0
}
501
502
/*
503
 * Get length in bytes of RSA modulus
504
 */
505
506
size_t mbedtls_rsa_get_len(const mbedtls_rsa_context *ctx)
507
1.05k
{
508
1.05k
    return ctx->len;
509
1.05k
}
510
511
512
#if defined(MBEDTLS_GENPRIME)
513
514
/*
515
 * Generate an RSA keypair
516
 *
517
 * This generation method follows the RSA key pair generation procedure of
518
 * FIPS 186-4 if 2^16 < exponent < 2^256 and nbits = 2048 or nbits = 3072.
519
 */
520
int mbedtls_rsa_gen_key(mbedtls_rsa_context *ctx,
521
                        int (*f_rng)(void *, unsigned char *, size_t),
522
                        void *p_rng,
523
                        unsigned int nbits, int exponent)
524
0
{
525
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
526
0
    mbedtls_mpi H, G, L;
527
0
    int prime_quality = 0;
528
529
    /*
530
     * If the modulus is 1024 bit long or shorter, then the security strength of
531
     * the RSA algorithm is less than or equal to 80 bits and therefore an error
532
     * rate of 2^-80 is sufficient.
533
     */
534
0
    if (nbits > 1024) {
535
0
        prime_quality = MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR;
536
0
    }
537
538
0
    mbedtls_mpi_init(&H);
539
0
    mbedtls_mpi_init(&G);
540
0
    mbedtls_mpi_init(&L);
541
542
0
    if (nbits < 128 || exponent < 3 || nbits % 2 != 0) {
543
0
        ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
544
0
        goto cleanup;
545
0
    }
546
547
    /*
548
     * find primes P and Q with Q < P so that:
549
     * 1.  |P-Q| > 2^( nbits / 2 - 100 )
550
     * 2.  GCD( E, (P-1)*(Q-1) ) == 1
551
     * 3.  E^-1 mod LCM(P-1, Q-1) > 2^( nbits / 2 )
552
     */
553
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_lset(&ctx->E, exponent));
554
555
0
    do {
556
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_gen_prime(&ctx->P, nbits >> 1,
557
0
                                              prime_quality, f_rng, p_rng));
558
559
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_gen_prime(&ctx->Q, nbits >> 1,
560
0
                                              prime_quality, f_rng, p_rng));
561
562
        /* make sure the difference between p and q is not too small (FIPS 186-4 §B.3.3 step 5.4) */
563
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&H, &ctx->P, &ctx->Q));
564
0
        if (mbedtls_mpi_bitlen(&H) <= ((nbits >= 200) ? ((nbits >> 1) - 99) : 0)) {
565
0
            continue;
566
0
        }
567
568
        /* not required by any standards, but some users rely on the fact that P > Q */
569
0
        if (H.s < 0) {
570
0
            mbedtls_mpi_swap(&ctx->P, &ctx->Q);
571
0
        }
572
573
        /* Temporarily replace P,Q by P-1, Q-1 */
574
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&ctx->P, &ctx->P, 1));
575
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&ctx->Q, &ctx->Q, 1));
576
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&H, &ctx->P, &ctx->Q));
577
578
        /* check GCD( E, (P-1)*(Q-1) ) == 1 (FIPS 186-4 §B.3.1 criterion 2(a)) */
579
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&G, &ctx->E, &H));
580
0
        if (mbedtls_mpi_cmp_int(&G, 1) != 0) {
581
0
            continue;
582
0
        }
583
584
        /* compute smallest possible D = E^-1 mod LCM(P-1, Q-1) (FIPS 186-4 §B.3.1 criterion 3(b)) */
585
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_gcd(&G, &ctx->P, &ctx->Q));
586
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_div_mpi(&L, NULL, &H, &G));
587
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_inv_mod(&ctx->D, &ctx->E, &L));
588
589
0
        if (mbedtls_mpi_bitlen(&ctx->D) <= ((nbits + 1) / 2)) {      // (FIPS 186-4 §B.3.1 criterion 3(a))
590
0
            continue;
591
0
        }
592
593
0
        break;
594
0
    } while (1);
595
596
    /* Restore P,Q */
597
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&ctx->P,  &ctx->P, 1));
598
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_add_int(&ctx->Q,  &ctx->Q, 1));
599
600
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->N, &ctx->P, &ctx->Q));
601
602
0
    ctx->len = mbedtls_mpi_size(&ctx->N);
603
604
0
#if !defined(MBEDTLS_RSA_NO_CRT)
605
    /*
606
     * DP = D mod (P - 1)
607
     * DQ = D mod (Q - 1)
608
     * QP = Q^-1 mod P
609
     */
610
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_deduce_crt(&ctx->P, &ctx->Q, &ctx->D,
611
0
                                           &ctx->DP, &ctx->DQ, &ctx->QP));
612
0
#endif /* MBEDTLS_RSA_NO_CRT */
613
614
    /* Double-check */
615
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_check_privkey(ctx));
616
617
0
cleanup:
618
619
0
    mbedtls_mpi_free(&H);
620
0
    mbedtls_mpi_free(&G);
621
0
    mbedtls_mpi_free(&L);
622
623
0
    if (ret != 0) {
624
0
        mbedtls_rsa_free(ctx);
625
626
0
        if ((-ret & ~0x7f) == 0) {
627
0
            ret = MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_KEY_GEN_FAILED, ret);
628
0
        }
629
0
        return ret;
630
0
    }
631
632
0
    return 0;
633
0
}
634
635
#endif /* MBEDTLS_GENPRIME */
636
637
/*
638
 * Check a public RSA key
639
 */
640
int mbedtls_rsa_check_pubkey(const mbedtls_rsa_context *ctx)
641
12.5k
{
642
12.5k
    if (rsa_check_context(ctx, 0 /* public */, 0 /* no blinding */) != 0) {
643
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
644
0
    }
645
646
12.5k
    if (mbedtls_mpi_bitlen(&ctx->N) < 128) {
647
16
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
648
16
    }
649
650
12.5k
    if (mbedtls_mpi_get_bit(&ctx->E, 0) == 0 ||
651
12.5k
        mbedtls_mpi_bitlen(&ctx->E)     < 2  ||
652
12.5k
        mbedtls_mpi_cmp_mpi(&ctx->E, &ctx->N) >= 0) {
653
67
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
654
67
    }
655
656
12.4k
    return 0;
657
12.5k
}
658
659
/*
660
 * Check for the consistency of all fields in an RSA private key context
661
 */
662
int mbedtls_rsa_check_privkey(const mbedtls_rsa_context *ctx)
663
0
{
664
0
    if (mbedtls_rsa_check_pubkey(ctx) != 0 ||
665
0
        rsa_check_context(ctx, 1 /* private */, 1 /* blinding */) != 0) {
666
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
667
0
    }
668
669
0
    if (mbedtls_rsa_validate_params(&ctx->N, &ctx->P, &ctx->Q,
670
0
                                    &ctx->D, &ctx->E, NULL, NULL) != 0) {
671
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
672
0
    }
673
674
0
#if !defined(MBEDTLS_RSA_NO_CRT)
675
0
    else if (mbedtls_rsa_validate_crt(&ctx->P, &ctx->Q, &ctx->D,
676
0
                                      &ctx->DP, &ctx->DQ, &ctx->QP) != 0) {
677
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
678
0
    }
679
0
#endif
680
681
0
    return 0;
682
0
}
683
684
/*
685
 * Check if contexts holding a public and private key match
686
 */
687
int mbedtls_rsa_check_pub_priv(const mbedtls_rsa_context *pub,
688
                               const mbedtls_rsa_context *prv)
689
0
{
690
0
    if (mbedtls_rsa_check_pubkey(pub)  != 0 ||
691
0
        mbedtls_rsa_check_privkey(prv) != 0) {
692
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
693
0
    }
694
695
0
    if (mbedtls_mpi_cmp_mpi(&pub->N, &prv->N) != 0 ||
696
0
        mbedtls_mpi_cmp_mpi(&pub->E, &prv->E) != 0) {
697
0
        return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
698
0
    }
699
700
0
    return 0;
701
0
}
702
703
/*
704
 * Do an RSA public key operation
705
 */
706
int mbedtls_rsa_public(mbedtls_rsa_context *ctx,
707
                       const unsigned char *input,
708
                       unsigned char *output)
709
1.04k
{
710
1.04k
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
711
1.04k
    size_t olen;
712
1.04k
    mbedtls_mpi T;
713
714
1.04k
    if (rsa_check_context(ctx, 0 /* public */, 0 /* no blinding */)) {
715
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
716
0
    }
717
718
1.04k
    mbedtls_mpi_init(&T);
719
720
#if defined(MBEDTLS_THREADING_C)
721
    if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
722
        return ret;
723
    }
724
#endif
725
726
1.04k
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len));
727
728
1.04k
    if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) {
729
29
        ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
730
29
        goto cleanup;
731
29
    }
732
733
1.01k
    olen = ctx->len;
734
1.01k
    MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&T, &T, &ctx->E, &ctx->N, &ctx->RN));
735
1.01k
    MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen));
736
737
1.04k
cleanup:
738
#if defined(MBEDTLS_THREADING_C)
739
    if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
740
        return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
741
    }
742
#endif
743
744
1.04k
    mbedtls_mpi_free(&T);
745
746
1.04k
    if (ret != 0) {
747
29
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_PUBLIC_FAILED, ret);
748
29
    }
749
750
1.01k
    return 0;
751
1.04k
}
752
753
/*
754
 * Generate or update blinding values, see section 10 of:
755
 *  KOCHER, Paul C. Timing attacks on implementations of Diffie-Hellman, RSA,
756
 *  DSS, and other systems. In : Advances in Cryptology-CRYPTO'96. Springer
757
 *  Berlin Heidelberg, 1996. p. 104-113.
758
 */
759
static int rsa_prepare_blinding(mbedtls_rsa_context *ctx,
760
                                int (*f_rng)(void *, unsigned char *, size_t), void *p_rng)
761
0
{
762
0
    int ret, count = 0;
763
0
    mbedtls_mpi R;
764
765
0
    mbedtls_mpi_init(&R);
766
767
0
    if (ctx->Vf.p != NULL) {
768
        /* We already have blinding values, just update them by squaring */
769
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vi, &ctx->Vi));
770
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
771
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vf, &ctx->Vf, &ctx->Vf));
772
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vf, &ctx->Vf, &ctx->N));
773
774
0
        goto cleanup;
775
0
    }
776
777
    /* Unblinding value: Vf = random number, invertible mod N */
778
0
    do {
779
0
        if (count++ > 10) {
780
0
            ret = MBEDTLS_ERR_RSA_RNG_FAILED;
781
0
            goto cleanup;
782
0
        }
783
784
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&ctx->Vf, ctx->len - 1, f_rng, p_rng));
785
786
        /* Compute Vf^-1 as R * (R Vf)^-1 to avoid leaks from inv_mod. */
787
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, ctx->len - 1, f_rng, p_rng));
788
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vf, &R));
789
0
        MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
790
791
        /* At this point, Vi is invertible mod N if and only if both Vf and R
792
         * are invertible mod N. If one of them isn't, we don't need to know
793
         * which one, we just loop and choose new values for both of them.
794
         * (Each iteration succeeds with overwhelming probability.) */
795
0
        ret = mbedtls_mpi_inv_mod(&ctx->Vi, &ctx->Vi, &ctx->N);
796
0
        if (ret != 0 && ret != MBEDTLS_ERR_MPI_NOT_ACCEPTABLE) {
797
0
            goto cleanup;
798
0
        }
799
800
0
    } while (ret == MBEDTLS_ERR_MPI_NOT_ACCEPTABLE);
801
802
    /* Finish the computation of Vf^-1 = R * (R Vf)^-1 */
803
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&ctx->Vi, &ctx->Vi, &R));
804
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&ctx->Vi, &ctx->Vi, &ctx->N));
805
806
    /* Blinding value: Vi = Vf^(-e) mod N
807
     * (Vi already contains Vf^-1 at this point) */
808
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&ctx->Vi, &ctx->Vi, &ctx->E, &ctx->N, &ctx->RN));
809
810
811
0
cleanup:
812
0
    mbedtls_mpi_free(&R);
813
814
0
    return ret;
815
0
}
816
817
/*
818
 * Exponent blinding supposed to prevent side-channel attacks using multiple
819
 * traces of measurements to recover the RSA key. The more collisions are there,
820
 * the more bits of the key can be recovered. See [3].
821
 *
822
 * Collecting n collisions with m bit long blinding value requires 2^(m-m/n)
823
 * observations on average.
824
 *
825
 * For example with 28 byte blinding to achieve 2 collisions the adversary has
826
 * to make 2^112 observations on average.
827
 *
828
 * (With the currently (as of 2017 April) known best algorithms breaking 2048
829
 * bit RSA requires approximately as much time as trying out 2^112 random keys.
830
 * Thus in this sense with 28 byte blinding the security is not reduced by
831
 * side-channel attacks like the one in [3])
832
 *
833
 * This countermeasure does not help if the key recovery is possible with a
834
 * single trace.
835
 */
836
#define RSA_EXPONENT_BLINDING 28
837
838
/*
839
 * Do an RSA private key operation
840
 */
841
int mbedtls_rsa_private(mbedtls_rsa_context *ctx,
842
                        int (*f_rng)(void *, unsigned char *, size_t),
843
                        void *p_rng,
844
                        const unsigned char *input,
845
                        unsigned char *output)
846
0
{
847
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
848
0
    size_t olen;
849
850
    /* Temporary holding the result */
851
0
    mbedtls_mpi T;
852
853
    /* Temporaries holding P-1, Q-1 and the
854
     * exponent blinding factor, respectively. */
855
0
    mbedtls_mpi P1, Q1, R;
856
857
0
#if !defined(MBEDTLS_RSA_NO_CRT)
858
    /* Temporaries holding the results mod p resp. mod q. */
859
0
    mbedtls_mpi TP, TQ;
860
861
    /* Temporaries holding the blinded exponents for
862
     * the mod p resp. mod q computation (if used). */
863
0
    mbedtls_mpi DP_blind, DQ_blind;
864
865
    /* Pointers to actual exponents to be used - either the unblinded
866
     * or the blinded ones, depending on the presence of a PRNG. */
867
0
    mbedtls_mpi *DP = &ctx->DP;
868
0
    mbedtls_mpi *DQ = &ctx->DQ;
869
#else
870
    /* Temporary holding the blinded exponent (if used). */
871
    mbedtls_mpi D_blind;
872
873
    /* Pointer to actual exponent to be used - either the unblinded
874
     * or the blinded one, depending on the presence of a PRNG. */
875
    mbedtls_mpi *D = &ctx->D;
876
#endif /* MBEDTLS_RSA_NO_CRT */
877
878
    /* Temporaries holding the initial input and the double
879
     * checked result; should be the same in the end. */
880
0
    mbedtls_mpi I, C;
881
882
0
    if (f_rng == NULL) {
883
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
884
0
    }
885
886
0
    if (rsa_check_context(ctx, 1 /* private key checks */,
887
0
                          1 /* blinding on        */) != 0) {
888
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
889
0
    }
890
891
#if defined(MBEDTLS_THREADING_C)
892
    if ((ret = mbedtls_mutex_lock(&ctx->mutex)) != 0) {
893
        return ret;
894
    }
895
#endif
896
897
    /* MPI Initialization */
898
0
    mbedtls_mpi_init(&T);
899
900
0
    mbedtls_mpi_init(&P1);
901
0
    mbedtls_mpi_init(&Q1);
902
0
    mbedtls_mpi_init(&R);
903
904
#if defined(MBEDTLS_RSA_NO_CRT)
905
    mbedtls_mpi_init(&D_blind);
906
#else
907
0
    mbedtls_mpi_init(&DP_blind);
908
0
    mbedtls_mpi_init(&DQ_blind);
909
0
#endif
910
911
0
#if !defined(MBEDTLS_RSA_NO_CRT)
912
0
    mbedtls_mpi_init(&TP); mbedtls_mpi_init(&TQ);
913
0
#endif
914
915
0
    mbedtls_mpi_init(&I);
916
0
    mbedtls_mpi_init(&C);
917
918
    /* End of MPI initialization */
919
920
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_binary(&T, input, ctx->len));
921
0
    if (mbedtls_mpi_cmp_mpi(&T, &ctx->N) >= 0) {
922
0
        ret = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
923
0
        goto cleanup;
924
0
    }
925
926
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&I, &T));
927
928
    /*
929
     * Blinding
930
     * T = T * Vi mod N
931
     */
932
0
    MBEDTLS_MPI_CHK(rsa_prepare_blinding(ctx, f_rng, p_rng));
933
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&T, &T, &ctx->Vi));
934
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &T, &ctx->N));
935
936
    /*
937
     * Exponent blinding
938
     */
939
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&P1, &ctx->P, 1));
940
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_sub_int(&Q1, &ctx->Q, 1));
941
942
#if defined(MBEDTLS_RSA_NO_CRT)
943
    /*
944
     * D_blind = ( P - 1 ) * ( Q - 1 ) * R + D
945
     */
946
    MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
947
                                            f_rng, p_rng));
948
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&D_blind, &P1, &Q1));
949
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&D_blind, &D_blind, &R));
950
    MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&D_blind, &D_blind, &ctx->D));
951
952
    D = &D_blind;
953
#else
954
    /*
955
     * DP_blind = ( P - 1 ) * R + DP
956
     */
957
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
958
0
                                            f_rng, p_rng));
959
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&DP_blind, &P1, &R));
960
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&DP_blind, &DP_blind,
961
0
                                        &ctx->DP));
962
963
0
    DP = &DP_blind;
964
965
    /*
966
     * DQ_blind = ( Q - 1 ) * R + DQ
967
     */
968
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_fill_random(&R, RSA_EXPONENT_BLINDING,
969
0
                                            f_rng, p_rng));
970
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&DQ_blind, &Q1, &R));
971
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&DQ_blind, &DQ_blind,
972
0
                                        &ctx->DQ));
973
974
0
    DQ = &DQ_blind;
975
0
#endif /* MBEDTLS_RSA_NO_CRT */
976
977
#if defined(MBEDTLS_RSA_NO_CRT)
978
    MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&T, &T, D, &ctx->N, &ctx->RN));
979
#else
980
    /*
981
     * Faster decryption using the CRT
982
     *
983
     * TP = input ^ dP mod P
984
     * TQ = input ^ dQ mod Q
985
     */
986
987
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&TP, &T, DP, &ctx->P, &ctx->RP));
988
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&TQ, &T, DQ, &ctx->Q, &ctx->RQ));
989
990
    /*
991
     * T = (TP - TQ) * (Q^-1 mod P) mod P
992
     */
993
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_sub_mpi(&T, &TP, &TQ));
994
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&TP, &T, &ctx->QP));
995
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &TP, &ctx->P));
996
997
    /*
998
     * T = TQ + T * Q
999
     */
1000
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&TP, &T, &ctx->Q));
1001
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(&T, &TQ, &TP));
1002
0
#endif /* MBEDTLS_RSA_NO_CRT */
1003
1004
    /*
1005
     * Unblind
1006
     * T = T * Vf mod N
1007
     */
1008
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mul_mpi(&T, &T, &ctx->Vf));
1009
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_mod_mpi(&T, &T, &ctx->N));
1010
1011
    /* Verify the result to prevent glitching attacks. */
1012
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_exp_mod(&C, &T, &ctx->E,
1013
0
                                        &ctx->N, &ctx->RN));
1014
0
    if (mbedtls_mpi_cmp_mpi(&C, &I) != 0) {
1015
0
        ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
1016
0
        goto cleanup;
1017
0
    }
1018
1019
0
    olen = ctx->len;
1020
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_write_binary(&T, output, olen));
1021
1022
0
cleanup:
1023
#if defined(MBEDTLS_THREADING_C)
1024
    if (mbedtls_mutex_unlock(&ctx->mutex) != 0) {
1025
        return MBEDTLS_ERR_THREADING_MUTEX_ERROR;
1026
    }
1027
#endif
1028
1029
0
    mbedtls_mpi_free(&P1);
1030
0
    mbedtls_mpi_free(&Q1);
1031
0
    mbedtls_mpi_free(&R);
1032
1033
#if defined(MBEDTLS_RSA_NO_CRT)
1034
    mbedtls_mpi_free(&D_blind);
1035
#else
1036
0
    mbedtls_mpi_free(&DP_blind);
1037
0
    mbedtls_mpi_free(&DQ_blind);
1038
0
#endif
1039
1040
0
    mbedtls_mpi_free(&T);
1041
1042
0
#if !defined(MBEDTLS_RSA_NO_CRT)
1043
0
    mbedtls_mpi_free(&TP); mbedtls_mpi_free(&TQ);
1044
0
#endif
1045
1046
0
    mbedtls_mpi_free(&C);
1047
0
    mbedtls_mpi_free(&I);
1048
1049
0
    if (ret != 0 && ret >= -0x007f) {
1050
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_PRIVATE_FAILED, ret);
1051
0
    }
1052
1053
0
    return ret;
1054
0
}
1055
1056
#if defined(MBEDTLS_PKCS1_V21)
1057
/**
1058
 * Generate and apply the MGF1 operation (from PKCS#1 v2.1) to a buffer.
1059
 *
1060
 * \param dst       buffer to mask
1061
 * \param dlen      length of destination buffer
1062
 * \param src       source of the mask generation
1063
 * \param slen      length of the source buffer
1064
 * \param md_alg    message digest to use
1065
 */
1066
static int mgf_mask(unsigned char *dst, size_t dlen, unsigned char *src,
1067
                    size_t slen, mbedtls_md_type_t md_alg)
1068
0
{
1069
0
    unsigned char counter[4];
1070
0
    unsigned char *p;
1071
0
    unsigned int hlen;
1072
0
    size_t i, use_len;
1073
0
    unsigned char mask[MBEDTLS_HASH_MAX_SIZE];
1074
0
#if defined(MBEDTLS_MD_C)
1075
0
    int ret = 0;
1076
0
    const mbedtls_md_info_t *md_info;
1077
0
    mbedtls_md_context_t md_ctx;
1078
1079
0
    mbedtls_md_init(&md_ctx);
1080
0
    md_info = mbedtls_md_info_from_type(md_alg);
1081
0
    if (md_info == NULL) {
1082
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1083
0
    }
1084
1085
0
    mbedtls_md_init(&md_ctx);
1086
0
    if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
1087
0
        goto exit;
1088
0
    }
1089
1090
0
    hlen = mbedtls_md_get_size(md_info);
1091
#else
1092
    psa_hash_operation_t op = PSA_HASH_OPERATION_INIT;
1093
    psa_algorithm_t alg = mbedtls_psa_translate_md(md_alg);
1094
    psa_status_t status = PSA_SUCCESS;
1095
    size_t out_len;
1096
1097
    hlen = PSA_HASH_LENGTH(alg);
1098
#endif
1099
1100
0
    memset(mask, 0, sizeof(mask));
1101
0
    memset(counter, 0, 4);
1102
1103
    /* Generate and apply dbMask */
1104
0
    p = dst;
1105
1106
0
    while (dlen > 0) {
1107
0
        use_len = hlen;
1108
0
        if (dlen < hlen) {
1109
0
            use_len = dlen;
1110
0
        }
1111
1112
0
#if defined(MBEDTLS_MD_C)
1113
0
        if ((ret = mbedtls_md_starts(&md_ctx)) != 0) {
1114
0
            goto exit;
1115
0
        }
1116
0
        if ((ret = mbedtls_md_update(&md_ctx, src, slen)) != 0) {
1117
0
            goto exit;
1118
0
        }
1119
0
        if ((ret = mbedtls_md_update(&md_ctx, counter, 4)) != 0) {
1120
0
            goto exit;
1121
0
        }
1122
0
        if ((ret = mbedtls_md_finish(&md_ctx, mask)) != 0) {
1123
0
            goto exit;
1124
0
        }
1125
#else
1126
        if ((status = psa_hash_setup(&op, alg)) != PSA_SUCCESS) {
1127
            goto exit;
1128
        }
1129
        if ((status = psa_hash_update(&op, src, slen)) != PSA_SUCCESS) {
1130
            goto exit;
1131
        }
1132
        if ((status = psa_hash_update(&op, counter, 4)) != PSA_SUCCESS) {
1133
            goto exit;
1134
        }
1135
        status = psa_hash_finish(&op, mask, sizeof(mask), &out_len);
1136
        if (status != PSA_SUCCESS) {
1137
            goto exit;
1138
        }
1139
#endif
1140
1141
0
        for (i = 0; i < use_len; ++i) {
1142
0
            *p++ ^= mask[i];
1143
0
        }
1144
1145
0
        counter[3]++;
1146
1147
0
        dlen -= use_len;
1148
0
    }
1149
1150
0
exit:
1151
0
    mbedtls_platform_zeroize(mask, sizeof(mask));
1152
0
#if defined(MBEDTLS_MD_C)
1153
0
    mbedtls_md_free(&md_ctx);
1154
1155
0
    return ret;
1156
#else
1157
    psa_hash_abort(&op);
1158
1159
    return mbedtls_md_error_from_psa(status);
1160
#endif
1161
0
}
1162
1163
/**
1164
 * Generate Hash(M') as in RFC 8017 page 43 points 5 and 6.
1165
 *
1166
 * \param hash      the input hash
1167
 * \param hlen      length of the input hash
1168
 * \param salt      the input salt
1169
 * \param slen      length of the input salt
1170
 * \param out       the output buffer - must be large enough for \p md_alg
1171
 * \param md_alg    message digest to use
1172
 */
1173
static int hash_mprime(const unsigned char *hash, size_t hlen,
1174
                       const unsigned char *salt, size_t slen,
1175
                       unsigned char *out, mbedtls_md_type_t md_alg)
1176
0
{
1177
0
    const unsigned char zeros[8] = { 0, 0, 0, 0, 0, 0, 0, 0 };
1178
1179
0
#if defined(MBEDTLS_MD_C)
1180
0
    mbedtls_md_context_t md_ctx;
1181
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1182
1183
0
    const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md_alg);
1184
0
    if (md_info == NULL) {
1185
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1186
0
    }
1187
1188
0
    mbedtls_md_init(&md_ctx);
1189
0
    if ((ret = mbedtls_md_setup(&md_ctx, md_info, 0)) != 0) {
1190
0
        goto exit;
1191
0
    }
1192
0
    if ((ret = mbedtls_md_starts(&md_ctx)) != 0) {
1193
0
        goto exit;
1194
0
    }
1195
0
    if ((ret = mbedtls_md_update(&md_ctx, zeros, sizeof(zeros))) != 0) {
1196
0
        goto exit;
1197
0
    }
1198
0
    if ((ret = mbedtls_md_update(&md_ctx, hash, hlen)) != 0) {
1199
0
        goto exit;
1200
0
    }
1201
0
    if ((ret = mbedtls_md_update(&md_ctx, salt, slen)) != 0) {
1202
0
        goto exit;
1203
0
    }
1204
0
    if ((ret = mbedtls_md_finish(&md_ctx, out)) != 0) {
1205
0
        goto exit;
1206
0
    }
1207
1208
0
exit:
1209
0
    mbedtls_md_free(&md_ctx);
1210
1211
0
    return ret;
1212
#else
1213
    psa_hash_operation_t op = PSA_HASH_OPERATION_INIT;
1214
    psa_algorithm_t alg = mbedtls_psa_translate_md(md_alg);
1215
    psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED;
1216
    size_t out_size = PSA_HASH_LENGTH(alg);
1217
    size_t out_len;
1218
1219
    if ((status = psa_hash_setup(&op, alg)) != PSA_SUCCESS) {
1220
        goto exit;
1221
    }
1222
    if ((status = psa_hash_update(&op, zeros, sizeof(zeros))) != PSA_SUCCESS) {
1223
        goto exit;
1224
    }
1225
    if ((status = psa_hash_update(&op, hash, hlen)) != PSA_SUCCESS) {
1226
        goto exit;
1227
    }
1228
    if ((status = psa_hash_update(&op, salt, slen)) != PSA_SUCCESS) {
1229
        goto exit;
1230
    }
1231
    status = psa_hash_finish(&op, out, out_size, &out_len);
1232
    if (status != PSA_SUCCESS) {
1233
        goto exit;
1234
    }
1235
1236
exit:
1237
    psa_hash_abort(&op);
1238
1239
    return mbedtls_md_error_from_psa(status);
1240
#endif /* !MBEDTLS_MD_C */
1241
0
}
1242
1243
/**
1244
 * Compute a hash.
1245
 *
1246
 * \param md_alg    algorithm to use
1247
 * \param input     input message to hash
1248
 * \param ilen      input length
1249
 * \param output    the output buffer - must be large enough for \p md_alg
1250
 */
1251
static int compute_hash(mbedtls_md_type_t md_alg,
1252
                        const unsigned char *input, size_t ilen,
1253
                        unsigned char *output)
1254
0
{
1255
0
#if defined(MBEDTLS_MD_C)
1256
0
    const mbedtls_md_info_t *md_info;
1257
1258
0
    md_info = mbedtls_md_info_from_type(md_alg);
1259
0
    if (md_info == NULL) {
1260
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1261
0
    }
1262
1263
0
    return mbedtls_md(md_info, input, ilen, output);
1264
#else
1265
    psa_algorithm_t alg = mbedtls_psa_translate_md(md_alg);
1266
    psa_status_t status;
1267
    size_t out_size = PSA_HASH_LENGTH(alg);
1268
    size_t out_len;
1269
1270
    status = psa_hash_compute(alg, input, ilen, output, out_size, &out_len);
1271
1272
    return mbedtls_md_error_from_psa(status);
1273
#endif /* !MBEDTLS_MD_C */
1274
0
}
1275
#endif /* MBEDTLS_PKCS1_V21 */
1276
1277
#if defined(MBEDTLS_PKCS1_V21)
1278
/*
1279
 * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function
1280
 */
1281
int mbedtls_rsa_rsaes_oaep_encrypt(mbedtls_rsa_context *ctx,
1282
                                   int (*f_rng)(void *, unsigned char *, size_t),
1283
                                   void *p_rng,
1284
                                   const unsigned char *label, size_t label_len,
1285
                                   size_t ilen,
1286
                                   const unsigned char *input,
1287
                                   unsigned char *output)
1288
0
{
1289
0
    size_t olen;
1290
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1291
0
    unsigned char *p = output;
1292
0
    unsigned int hlen;
1293
1294
0
    if (f_rng == NULL) {
1295
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1296
0
    }
1297
1298
0
    hlen = mbedtls_hash_info_get_size((mbedtls_md_type_t) ctx->hash_id);
1299
0
    if (hlen == 0) {
1300
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1301
0
    }
1302
1303
0
    olen = ctx->len;
1304
1305
    /* first comparison checks for overflow */
1306
0
    if (ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2) {
1307
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1308
0
    }
1309
1310
0
    memset(output, 0, olen);
1311
1312
0
    *p++ = 0;
1313
1314
    /* Generate a random octet string seed */
1315
0
    if ((ret = f_rng(p_rng, p, hlen)) != 0) {
1316
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
1317
0
    }
1318
1319
0
    p += hlen;
1320
1321
    /* Construct DB */
1322
0
    ret = compute_hash((mbedtls_md_type_t) ctx->hash_id, label, label_len, p);
1323
0
    if (ret != 0) {
1324
0
        return ret;
1325
0
    }
1326
0
    p += hlen;
1327
0
    p += olen - 2 * hlen - 2 - ilen;
1328
0
    *p++ = 1;
1329
0
    if (ilen != 0) {
1330
0
        memcpy(p, input, ilen);
1331
0
    }
1332
1333
    /* maskedDB: Apply dbMask to DB */
1334
0
    if ((ret = mgf_mask(output + hlen + 1, olen - hlen - 1, output + 1, hlen,
1335
0
                        ctx->hash_id)) != 0) {
1336
0
        return ret;
1337
0
    }
1338
1339
    /* maskedSeed: Apply seedMask to seed */
1340
0
    if ((ret = mgf_mask(output + 1, hlen, output + hlen + 1, olen - hlen - 1,
1341
0
                        ctx->hash_id)) != 0) {
1342
0
        return ret;
1343
0
    }
1344
1345
0
    return mbedtls_rsa_public(ctx, output, output);
1346
0
}
1347
#endif /* MBEDTLS_PKCS1_V21 */
1348
1349
#if defined(MBEDTLS_PKCS1_V15)
1350
/*
1351
 * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function
1352
 */
1353
int mbedtls_rsa_rsaes_pkcs1_v15_encrypt(mbedtls_rsa_context *ctx,
1354
                                        int (*f_rng)(void *, unsigned char *, size_t),
1355
                                        void *p_rng, size_t ilen,
1356
                                        const unsigned char *input,
1357
                                        unsigned char *output)
1358
0
{
1359
0
    size_t nb_pad, olen;
1360
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1361
0
    unsigned char *p = output;
1362
1363
0
    olen = ctx->len;
1364
1365
    /* first comparison checks for overflow */
1366
0
    if (ilen + 11 < ilen || olen < ilen + 11) {
1367
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1368
0
    }
1369
1370
0
    nb_pad = olen - 3 - ilen;
1371
1372
0
    *p++ = 0;
1373
1374
0
    if (f_rng == NULL) {
1375
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1376
0
    }
1377
1378
0
    *p++ = MBEDTLS_RSA_CRYPT;
1379
1380
0
    while (nb_pad-- > 0) {
1381
0
        int rng_dl = 100;
1382
1383
0
        do {
1384
0
            ret = f_rng(p_rng, p, 1);
1385
0
        } while (*p == 0 && --rng_dl && ret == 0);
1386
1387
        /* Check if RNG failed to generate data */
1388
0
        if (rng_dl == 0 || ret != 0) {
1389
0
            return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
1390
0
        }
1391
1392
0
        p++;
1393
0
    }
1394
1395
0
    *p++ = 0;
1396
0
    if (ilen != 0) {
1397
0
        memcpy(p, input, ilen);
1398
0
    }
1399
1400
0
    return mbedtls_rsa_public(ctx, output, output);
1401
0
}
1402
#endif /* MBEDTLS_PKCS1_V15 */
1403
1404
/*
1405
 * Add the message padding, then do an RSA operation
1406
 */
1407
int mbedtls_rsa_pkcs1_encrypt(mbedtls_rsa_context *ctx,
1408
                              int (*f_rng)(void *, unsigned char *, size_t),
1409
                              void *p_rng,
1410
                              size_t ilen,
1411
                              const unsigned char *input,
1412
                              unsigned char *output)
1413
0
{
1414
0
    switch (ctx->padding) {
1415
0
#if defined(MBEDTLS_PKCS1_V15)
1416
0
        case MBEDTLS_RSA_PKCS_V15:
1417
0
            return mbedtls_rsa_rsaes_pkcs1_v15_encrypt(ctx, f_rng, p_rng,
1418
0
                                                       ilen, input, output);
1419
0
#endif
1420
1421
0
#if defined(MBEDTLS_PKCS1_V21)
1422
0
        case MBEDTLS_RSA_PKCS_V21:
1423
0
            return mbedtls_rsa_rsaes_oaep_encrypt(ctx, f_rng, p_rng, NULL, 0,
1424
0
                                                  ilen, input, output);
1425
0
#endif
1426
1427
0
        default:
1428
0
            return MBEDTLS_ERR_RSA_INVALID_PADDING;
1429
0
    }
1430
0
}
1431
1432
#if defined(MBEDTLS_PKCS1_V21)
1433
/*
1434
 * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function
1435
 */
1436
int mbedtls_rsa_rsaes_oaep_decrypt(mbedtls_rsa_context *ctx,
1437
                                   int (*f_rng)(void *, unsigned char *, size_t),
1438
                                   void *p_rng,
1439
                                   const unsigned char *label, size_t label_len,
1440
                                   size_t *olen,
1441
                                   const unsigned char *input,
1442
                                   unsigned char *output,
1443
                                   size_t output_max_len)
1444
0
{
1445
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1446
0
    size_t ilen, i, pad_len;
1447
0
    unsigned char *p, bad, pad_done;
1448
0
    unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
1449
0
    unsigned char lhash[MBEDTLS_HASH_MAX_SIZE];
1450
0
    unsigned int hlen;
1451
1452
    /*
1453
     * Parameters sanity checks
1454
     */
1455
0
    if (ctx->padding != MBEDTLS_RSA_PKCS_V21) {
1456
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1457
0
    }
1458
1459
0
    ilen = ctx->len;
1460
1461
0
    if (ilen < 16 || ilen > sizeof(buf)) {
1462
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1463
0
    }
1464
1465
0
    hlen = mbedtls_hash_info_get_size((mbedtls_md_type_t) ctx->hash_id);
1466
0
    if (hlen == 0) {
1467
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1468
0
    }
1469
1470
    // checking for integer underflow
1471
0
    if (2 * hlen + 2 > ilen) {
1472
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1473
0
    }
1474
1475
    /*
1476
     * RSA operation
1477
     */
1478
0
    ret = mbedtls_rsa_private(ctx, f_rng, p_rng, input, buf);
1479
1480
0
    if (ret != 0) {
1481
0
        goto cleanup;
1482
0
    }
1483
1484
    /*
1485
     * Unmask data and generate lHash
1486
     */
1487
    /* seed: Apply seedMask to maskedSeed */
1488
0
    if ((ret = mgf_mask(buf + 1, hlen, buf + hlen + 1, ilen - hlen - 1,
1489
0
                        ctx->hash_id)) != 0 ||
1490
        /* DB: Apply dbMask to maskedDB */
1491
0
        (ret = mgf_mask(buf + hlen + 1, ilen - hlen - 1, buf + 1, hlen,
1492
0
                        ctx->hash_id)) != 0) {
1493
0
        goto cleanup;
1494
0
    }
1495
1496
    /* Generate lHash */
1497
0
    ret = compute_hash((mbedtls_md_type_t) ctx->hash_id,
1498
0
                       label, label_len, lhash);
1499
0
    if (ret != 0) {
1500
0
        goto cleanup;
1501
0
    }
1502
1503
    /*
1504
     * Check contents, in "constant-time"
1505
     */
1506
0
    p = buf;
1507
0
    bad = 0;
1508
1509
0
    bad |= *p++; /* First byte must be 0 */
1510
1511
0
    p += hlen; /* Skip seed */
1512
1513
    /* Check lHash */
1514
0
    for (i = 0; i < hlen; i++) {
1515
0
        bad |= lhash[i] ^ *p++;
1516
0
    }
1517
1518
    /* Get zero-padding len, but always read till end of buffer
1519
     * (minus one, for the 01 byte) */
1520
0
    pad_len = 0;
1521
0
    pad_done = 0;
1522
0
    for (i = 0; i < ilen - 2 * hlen - 2; i++) {
1523
0
        pad_done |= p[i];
1524
0
        pad_len += ((pad_done | (unsigned char) -pad_done) >> 7) ^ 1;
1525
0
    }
1526
1527
0
    p += pad_len;
1528
0
    bad |= *p++ ^ 0x01;
1529
1530
    /*
1531
     * The only information "leaked" is whether the padding was correct or not
1532
     * (eg, no data is copied if it was not correct). This meets the
1533
     * recommendations in PKCS#1 v2.2: an opponent cannot distinguish between
1534
     * the different error conditions.
1535
     */
1536
0
    if (bad != 0) {
1537
0
        ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
1538
0
        goto cleanup;
1539
0
    }
1540
1541
0
    if (ilen - (p - buf) > output_max_len) {
1542
0
        ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;
1543
0
        goto cleanup;
1544
0
    }
1545
1546
0
    *olen = ilen - (p - buf);
1547
0
    if (*olen != 0) {
1548
0
        memcpy(output, p, *olen);
1549
0
    }
1550
0
    ret = 0;
1551
1552
0
cleanup:
1553
0
    mbedtls_platform_zeroize(buf, sizeof(buf));
1554
0
    mbedtls_platform_zeroize(lhash, sizeof(lhash));
1555
1556
0
    return ret;
1557
0
}
1558
#endif /* MBEDTLS_PKCS1_V21 */
1559
1560
#if defined(MBEDTLS_PKCS1_V15)
1561
/*
1562
 * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function
1563
 */
1564
int mbedtls_rsa_rsaes_pkcs1_v15_decrypt(mbedtls_rsa_context *ctx,
1565
                                        int (*f_rng)(void *, unsigned char *, size_t),
1566
                                        void *p_rng,
1567
                                        size_t *olen,
1568
                                        const unsigned char *input,
1569
                                        unsigned char *output,
1570
                                        size_t output_max_len)
1571
0
{
1572
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1573
0
    size_t ilen;
1574
0
    unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
1575
1576
0
    ilen = ctx->len;
1577
1578
0
    if (ctx->padding != MBEDTLS_RSA_PKCS_V15) {
1579
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1580
0
    }
1581
1582
0
    if (ilen < 16 || ilen > sizeof(buf)) {
1583
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1584
0
    }
1585
1586
0
    ret = mbedtls_rsa_private(ctx, f_rng, p_rng, input, buf);
1587
1588
0
    if (ret != 0) {
1589
0
        goto cleanup;
1590
0
    }
1591
1592
0
    ret = mbedtls_ct_rsaes_pkcs1_v15_unpadding(buf, ilen,
1593
0
                                               output, output_max_len, olen);
1594
1595
0
cleanup:
1596
0
    mbedtls_platform_zeroize(buf, sizeof(buf));
1597
1598
0
    return ret;
1599
0
}
1600
#endif /* MBEDTLS_PKCS1_V15 */
1601
1602
/*
1603
 * Do an RSA operation, then remove the message padding
1604
 */
1605
int mbedtls_rsa_pkcs1_decrypt(mbedtls_rsa_context *ctx,
1606
                              int (*f_rng)(void *, unsigned char *, size_t),
1607
                              void *p_rng,
1608
                              size_t *olen,
1609
                              const unsigned char *input,
1610
                              unsigned char *output,
1611
                              size_t output_max_len)
1612
0
{
1613
0
    switch (ctx->padding) {
1614
0
#if defined(MBEDTLS_PKCS1_V15)
1615
0
        case MBEDTLS_RSA_PKCS_V15:
1616
0
            return mbedtls_rsa_rsaes_pkcs1_v15_decrypt(ctx, f_rng, p_rng, olen,
1617
0
                                                       input, output, output_max_len);
1618
0
#endif
1619
1620
0
#if defined(MBEDTLS_PKCS1_V21)
1621
0
        case MBEDTLS_RSA_PKCS_V21:
1622
0
            return mbedtls_rsa_rsaes_oaep_decrypt(ctx, f_rng, p_rng, NULL, 0,
1623
0
                                                  olen, input, output,
1624
0
                                                  output_max_len);
1625
0
#endif
1626
1627
0
        default:
1628
0
            return MBEDTLS_ERR_RSA_INVALID_PADDING;
1629
0
    }
1630
0
}
1631
1632
#if defined(MBEDTLS_PKCS1_V21)
1633
static int rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx,
1634
                               int (*f_rng)(void *, unsigned char *, size_t),
1635
                               void *p_rng,
1636
                               mbedtls_md_type_t md_alg,
1637
                               unsigned int hashlen,
1638
                               const unsigned char *hash,
1639
                               int saltlen,
1640
                               unsigned char *sig)
1641
0
{
1642
0
    size_t olen;
1643
0
    unsigned char *p = sig;
1644
0
    unsigned char *salt = NULL;
1645
0
    size_t slen, min_slen, hlen, offset = 0;
1646
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1647
0
    size_t msb;
1648
1649
0
    if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
1650
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1651
0
    }
1652
1653
0
    if (ctx->padding != MBEDTLS_RSA_PKCS_V21) {
1654
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1655
0
    }
1656
1657
0
    if (f_rng == NULL) {
1658
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1659
0
    }
1660
1661
0
    olen = ctx->len;
1662
1663
0
    if (md_alg != MBEDTLS_MD_NONE) {
1664
        /* Gather length of hash to sign */
1665
0
        size_t exp_hashlen = mbedtls_hash_info_get_size(md_alg);
1666
0
        if (exp_hashlen == 0) {
1667
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1668
0
        }
1669
1670
0
        if (hashlen != exp_hashlen) {
1671
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1672
0
        }
1673
0
    }
1674
1675
0
    hlen = mbedtls_hash_info_get_size((mbedtls_md_type_t) ctx->hash_id);
1676
0
    if (hlen == 0) {
1677
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1678
0
    }
1679
1680
0
    if (saltlen == MBEDTLS_RSA_SALT_LEN_ANY) {
1681
        /* Calculate the largest possible salt length, up to the hash size.
1682
         * Normally this is the hash length, which is the maximum salt length
1683
         * according to FIPS 185-4 §5.5 (e) and common practice. If there is not
1684
         * enough room, use the maximum salt length that fits. The constraint is
1685
         * that the hash length plus the salt length plus 2 bytes must be at most
1686
         * the key length. This complies with FIPS 186-4 §5.5 (e) and RFC 8017
1687
         * (PKCS#1 v2.2) §9.1.1 step 3. */
1688
0
        min_slen = hlen - 2;
1689
0
        if (olen < hlen + min_slen + 2) {
1690
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1691
0
        } else if (olen >= hlen + hlen + 2) {
1692
0
            slen = hlen;
1693
0
        } else {
1694
0
            slen = olen - hlen - 2;
1695
0
        }
1696
0
    } else if ((saltlen < 0) || (saltlen + hlen + 2 > olen)) {
1697
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1698
0
    } else {
1699
0
        slen = (size_t) saltlen;
1700
0
    }
1701
1702
0
    memset(sig, 0, olen);
1703
1704
    /* Note: EMSA-PSS encoding is over the length of N - 1 bits */
1705
0
    msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
1706
0
    p += olen - hlen - slen - 2;
1707
0
    *p++ = 0x01;
1708
1709
    /* Generate salt of length slen in place in the encoded message */
1710
0
    salt = p;
1711
0
    if ((ret = f_rng(p_rng, salt, slen)) != 0) {
1712
0
        return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_RSA_RNG_FAILED, ret);
1713
0
    }
1714
1715
0
    p += slen;
1716
1717
    /* Generate H = Hash( M' ) */
1718
0
    ret = hash_mprime(hash, hashlen, salt, slen, p, ctx->hash_id);
1719
0
    if (ret != 0) {
1720
0
        return ret;
1721
0
    }
1722
1723
    /* Compensate for boundary condition when applying mask */
1724
0
    if (msb % 8 == 0) {
1725
0
        offset = 1;
1726
0
    }
1727
1728
    /* maskedDB: Apply dbMask to DB */
1729
0
    ret = mgf_mask(sig + offset, olen - hlen - 1 - offset, p, hlen,
1730
0
                   ctx->hash_id);
1731
0
    if (ret != 0) {
1732
0
        return ret;
1733
0
    }
1734
1735
0
    msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
1736
0
    sig[0] &= 0xFF >> (olen * 8 - msb);
1737
1738
0
    p += hlen;
1739
0
    *p++ = 0xBC;
1740
1741
0
    return mbedtls_rsa_private(ctx, f_rng, p_rng, sig, sig);
1742
0
}
1743
1744
/*
1745
 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function with
1746
 * the option to pass in the salt length.
1747
 */
1748
int mbedtls_rsa_rsassa_pss_sign_ext(mbedtls_rsa_context *ctx,
1749
                                    int (*f_rng)(void *, unsigned char *, size_t),
1750
                                    void *p_rng,
1751
                                    mbedtls_md_type_t md_alg,
1752
                                    unsigned int hashlen,
1753
                                    const unsigned char *hash,
1754
                                    int saltlen,
1755
                                    unsigned char *sig)
1756
0
{
1757
0
    return rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
1758
0
                               hashlen, hash, saltlen, sig);
1759
0
}
1760
1761
1762
/*
1763
 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function
1764
 */
1765
int mbedtls_rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx,
1766
                                int (*f_rng)(void *, unsigned char *, size_t),
1767
                                void *p_rng,
1768
                                mbedtls_md_type_t md_alg,
1769
                                unsigned int hashlen,
1770
                                const unsigned char *hash,
1771
                                unsigned char *sig)
1772
0
{
1773
0
    return rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
1774
0
                               hashlen, hash, MBEDTLS_RSA_SALT_LEN_ANY, sig);
1775
0
}
1776
#endif /* MBEDTLS_PKCS1_V21 */
1777
1778
#if defined(MBEDTLS_PKCS1_V15)
1779
/*
1780
 * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function
1781
 */
1782
1783
/* Construct a PKCS v1.5 encoding of a hashed message
1784
 *
1785
 * This is used both for signature generation and verification.
1786
 *
1787
 * Parameters:
1788
 * - md_alg:  Identifies the hash algorithm used to generate the given hash;
1789
 *            MBEDTLS_MD_NONE if raw data is signed.
1790
 * - hashlen: Length of hash. Must match md_alg if that's not NONE.
1791
 * - hash:    Buffer containing the hashed message or the raw data.
1792
 * - dst_len: Length of the encoded message.
1793
 * - dst:     Buffer to hold the encoded message.
1794
 *
1795
 * Assumptions:
1796
 * - hash has size hashlen.
1797
 * - dst points to a buffer of size at least dst_len.
1798
 *
1799
 */
1800
static int rsa_rsassa_pkcs1_v15_encode(mbedtls_md_type_t md_alg,
1801
                                       unsigned int hashlen,
1802
                                       const unsigned char *hash,
1803
                                       size_t dst_len,
1804
                                       unsigned char *dst)
1805
1.04k
{
1806
1.04k
    size_t oid_size  = 0;
1807
1.04k
    size_t nb_pad    = dst_len;
1808
1.04k
    unsigned char *p = dst;
1809
1.04k
    const char *oid  = NULL;
1810
1811
    /* Are we signing hashed or raw data? */
1812
1.04k
    if (md_alg != MBEDTLS_MD_NONE) {
1813
1.04k
        unsigned char md_size = mbedtls_hash_info_get_size(md_alg);
1814
1.04k
        if (md_size == 0) {
1815
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1816
0
        }
1817
1818
1.04k
        if (mbedtls_oid_get_oid_by_md(md_alg, &oid, &oid_size) != 0) {
1819
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1820
0
        }
1821
1822
1.04k
        if (hashlen != md_size) {
1823
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1824
0
        }
1825
1826
        /* Double-check that 8 + hashlen + oid_size can be used as a
1827
         * 1-byte ASN.1 length encoding and that there's no overflow. */
1828
1.04k
        if (8 + hashlen + oid_size  >= 0x80         ||
1829
1.04k
            10 + hashlen            <  hashlen      ||
1830
1.04k
            10 + hashlen + oid_size <  10 + hashlen) {
1831
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1832
0
        }
1833
1834
        /*
1835
         * Static bounds check:
1836
         * - Need 10 bytes for five tag-length pairs.
1837
         *   (Insist on 1-byte length encodings to protect against variants of
1838
         *    Bleichenbacher's forgery attack against lax PKCS#1v1.5 verification)
1839
         * - Need hashlen bytes for hash
1840
         * - Need oid_size bytes for hash alg OID.
1841
         */
1842
1.04k
        if (nb_pad < 10 + hashlen + oid_size) {
1843
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1844
0
        }
1845
1.04k
        nb_pad -= 10 + hashlen + oid_size;
1846
1.04k
    } else {
1847
0
        if (nb_pad < hashlen) {
1848
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1849
0
        }
1850
1851
0
        nb_pad -= hashlen;
1852
0
    }
1853
1854
    /* Need space for signature header and padding delimiter (3 bytes),
1855
     * and 8 bytes for the minimal padding */
1856
1.04k
    if (nb_pad < 3 + 8) {
1857
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1858
0
    }
1859
1.04k
    nb_pad -= 3;
1860
1861
    /* Now nb_pad is the amount of memory to be filled
1862
     * with padding, and at least 8 bytes long. */
1863
1864
    /* Write signature header and padding */
1865
1.04k
    *p++ = 0;
1866
1.04k
    *p++ = MBEDTLS_RSA_SIGN;
1867
1.04k
    memset(p, 0xFF, nb_pad);
1868
1.04k
    p += nb_pad;
1869
1.04k
    *p++ = 0;
1870
1871
    /* Are we signing raw data? */
1872
1.04k
    if (md_alg == MBEDTLS_MD_NONE) {
1873
0
        memcpy(p, hash, hashlen);
1874
0
        return 0;
1875
0
    }
1876
1877
    /* Signing hashed data, add corresponding ASN.1 structure
1878
     *
1879
     * DigestInfo ::= SEQUENCE {
1880
     *   digestAlgorithm DigestAlgorithmIdentifier,
1881
     *   digest Digest }
1882
     * DigestAlgorithmIdentifier ::= AlgorithmIdentifier
1883
     * Digest ::= OCTET STRING
1884
     *
1885
     * Schematic:
1886
     * TAG-SEQ + LEN [ TAG-SEQ + LEN [ TAG-OID  + LEN [ OID  ]
1887
     *                                 TAG-NULL + LEN [ NULL ] ]
1888
     *                 TAG-OCTET + LEN [ HASH ] ]
1889
     */
1890
1.04k
    *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
1891
1.04k
    *p++ = (unsigned char) (0x08 + oid_size + hashlen);
1892
1.04k
    *p++ = MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED;
1893
1.04k
    *p++ = (unsigned char) (0x04 + oid_size);
1894
1.04k
    *p++ = MBEDTLS_ASN1_OID;
1895
1.04k
    *p++ = (unsigned char) oid_size;
1896
1.04k
    memcpy(p, oid, oid_size);
1897
1.04k
    p += oid_size;
1898
1.04k
    *p++ = MBEDTLS_ASN1_NULL;
1899
1.04k
    *p++ = 0x00;
1900
1.04k
    *p++ = MBEDTLS_ASN1_OCTET_STRING;
1901
1.04k
    *p++ = (unsigned char) hashlen;
1902
1.04k
    memcpy(p, hash, hashlen);
1903
1.04k
    p += hashlen;
1904
1905
    /* Just a sanity-check, should be automatic
1906
     * after the initial bounds check. */
1907
1.04k
    if (p != dst + dst_len) {
1908
0
        mbedtls_platform_zeroize(dst, dst_len);
1909
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1910
0
    }
1911
1912
1.04k
    return 0;
1913
1.04k
}
1914
1915
/*
1916
 * Do an RSA operation to sign the message digest
1917
 */
1918
int mbedtls_rsa_rsassa_pkcs1_v15_sign(mbedtls_rsa_context *ctx,
1919
                                      int (*f_rng)(void *, unsigned char *, size_t),
1920
                                      void *p_rng,
1921
                                      mbedtls_md_type_t md_alg,
1922
                                      unsigned int hashlen,
1923
                                      const unsigned char *hash,
1924
                                      unsigned char *sig)
1925
0
{
1926
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
1927
0
    unsigned char *sig_try = NULL, *verif = NULL;
1928
1929
0
    if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
1930
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1931
0
    }
1932
1933
0
    if (ctx->padding != MBEDTLS_RSA_PKCS_V15) {
1934
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1935
0
    }
1936
1937
    /*
1938
     * Prepare PKCS1-v1.5 encoding (padding and hash identifier)
1939
     */
1940
1941
0
    if ((ret = rsa_rsassa_pkcs1_v15_encode(md_alg, hashlen, hash,
1942
0
                                           ctx->len, sig)) != 0) {
1943
0
        return ret;
1944
0
    }
1945
1946
    /* Private key operation
1947
     *
1948
     * In order to prevent Lenstra's attack, make the signature in a
1949
     * temporary buffer and check it before returning it.
1950
     */
1951
1952
0
    sig_try = mbedtls_calloc(1, ctx->len);
1953
0
    if (sig_try == NULL) {
1954
0
        return MBEDTLS_ERR_MPI_ALLOC_FAILED;
1955
0
    }
1956
1957
0
    verif = mbedtls_calloc(1, ctx->len);
1958
0
    if (verif == NULL) {
1959
0
        mbedtls_free(sig_try);
1960
0
        return MBEDTLS_ERR_MPI_ALLOC_FAILED;
1961
0
    }
1962
1963
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_private(ctx, f_rng, p_rng, sig, sig_try));
1964
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_public(ctx, sig_try, verif));
1965
1966
0
    if (mbedtls_ct_memcmp(verif, sig, ctx->len) != 0) {
1967
0
        ret = MBEDTLS_ERR_RSA_PRIVATE_FAILED;
1968
0
        goto cleanup;
1969
0
    }
1970
1971
0
    memcpy(sig, sig_try, ctx->len);
1972
1973
0
cleanup:
1974
0
    mbedtls_platform_zeroize(sig_try, ctx->len);
1975
0
    mbedtls_platform_zeroize(verif, ctx->len);
1976
0
    mbedtls_free(sig_try);
1977
0
    mbedtls_free(verif);
1978
1979
0
    if (ret != 0) {
1980
0
        memset(sig, '!', ctx->len);
1981
0
    }
1982
0
    return ret;
1983
0
}
1984
#endif /* MBEDTLS_PKCS1_V15 */
1985
1986
/*
1987
 * Do an RSA operation to sign the message digest
1988
 */
1989
int mbedtls_rsa_pkcs1_sign(mbedtls_rsa_context *ctx,
1990
                           int (*f_rng)(void *, unsigned char *, size_t),
1991
                           void *p_rng,
1992
                           mbedtls_md_type_t md_alg,
1993
                           unsigned int hashlen,
1994
                           const unsigned char *hash,
1995
                           unsigned char *sig)
1996
0
{
1997
0
    if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
1998
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
1999
0
    }
2000
2001
0
    switch (ctx->padding) {
2002
0
#if defined(MBEDTLS_PKCS1_V15)
2003
0
        case MBEDTLS_RSA_PKCS_V15:
2004
0
            return mbedtls_rsa_rsassa_pkcs1_v15_sign(ctx, f_rng, p_rng,
2005
0
                                                     md_alg, hashlen, hash, sig);
2006
0
#endif
2007
2008
0
#if defined(MBEDTLS_PKCS1_V21)
2009
0
        case MBEDTLS_RSA_PKCS_V21:
2010
0
            return mbedtls_rsa_rsassa_pss_sign(ctx, f_rng, p_rng, md_alg,
2011
0
                                               hashlen, hash, sig);
2012
0
#endif
2013
2014
0
        default:
2015
0
            return MBEDTLS_ERR_RSA_INVALID_PADDING;
2016
0
    }
2017
0
}
2018
2019
#if defined(MBEDTLS_PKCS1_V21)
2020
/*
2021
 * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function
2022
 */
2023
int mbedtls_rsa_rsassa_pss_verify_ext(mbedtls_rsa_context *ctx,
2024
                                      mbedtls_md_type_t md_alg,
2025
                                      unsigned int hashlen,
2026
                                      const unsigned char *hash,
2027
                                      mbedtls_md_type_t mgf1_hash_id,
2028
                                      int expected_salt_len,
2029
                                      const unsigned char *sig)
2030
0
{
2031
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2032
0
    size_t siglen;
2033
0
    unsigned char *p;
2034
0
    unsigned char *hash_start;
2035
0
    unsigned char result[MBEDTLS_HASH_MAX_SIZE];
2036
0
    unsigned int hlen;
2037
0
    size_t observed_salt_len, msb;
2038
0
    unsigned char buf[MBEDTLS_MPI_MAX_SIZE] = { 0 };
2039
2040
0
    if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2041
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2042
0
    }
2043
2044
0
    siglen = ctx->len;
2045
2046
0
    if (siglen < 16 || siglen > sizeof(buf)) {
2047
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2048
0
    }
2049
2050
0
    ret = mbedtls_rsa_public(ctx, sig, buf);
2051
2052
0
    if (ret != 0) {
2053
0
        return ret;
2054
0
    }
2055
2056
0
    p = buf;
2057
2058
0
    if (buf[siglen - 1] != 0xBC) {
2059
0
        return MBEDTLS_ERR_RSA_INVALID_PADDING;
2060
0
    }
2061
2062
0
    if (md_alg != MBEDTLS_MD_NONE) {
2063
        /* Gather length of hash to sign */
2064
0
        size_t exp_hashlen = mbedtls_hash_info_get_size(md_alg);
2065
0
        if (exp_hashlen == 0) {
2066
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2067
0
        }
2068
2069
0
        if (hashlen != exp_hashlen) {
2070
0
            return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2071
0
        }
2072
0
    }
2073
2074
0
    hlen = mbedtls_hash_info_get_size(mgf1_hash_id);
2075
0
    if (hlen == 0) {
2076
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2077
0
    }
2078
2079
    /*
2080
     * Note: EMSA-PSS verification is over the length of N - 1 bits
2081
     */
2082
0
    msb = mbedtls_mpi_bitlen(&ctx->N) - 1;
2083
2084
0
    if (buf[0] >> (8 - siglen * 8 + msb)) {
2085
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2086
0
    }
2087
2088
    /* Compensate for boundary condition when applying mask */
2089
0
    if (msb % 8 == 0) {
2090
0
        p++;
2091
0
        siglen -= 1;
2092
0
    }
2093
2094
0
    if (siglen < hlen + 2) {
2095
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2096
0
    }
2097
0
    hash_start = p + siglen - hlen - 1;
2098
2099
0
    ret = mgf_mask(p, siglen - hlen - 1, hash_start, hlen, mgf1_hash_id);
2100
0
    if (ret != 0) {
2101
0
        return ret;
2102
0
    }
2103
2104
0
    buf[0] &= 0xFF >> (siglen * 8 - msb);
2105
2106
0
    while (p < hash_start - 1 && *p == 0) {
2107
0
        p++;
2108
0
    }
2109
2110
0
    if (*p++ != 0x01) {
2111
0
        return MBEDTLS_ERR_RSA_INVALID_PADDING;
2112
0
    }
2113
2114
0
    observed_salt_len = hash_start - p;
2115
2116
0
    if (expected_salt_len != MBEDTLS_RSA_SALT_LEN_ANY &&
2117
0
        observed_salt_len != (size_t) expected_salt_len) {
2118
0
        return MBEDTLS_ERR_RSA_INVALID_PADDING;
2119
0
    }
2120
2121
    /*
2122
     * Generate H = Hash( M' )
2123
     */
2124
0
    ret = hash_mprime(hash, hashlen, p, observed_salt_len,
2125
0
                      result, mgf1_hash_id);
2126
0
    if (ret != 0) {
2127
0
        return ret;
2128
0
    }
2129
2130
0
    if (memcmp(hash_start, result, hlen) != 0) {
2131
0
        return MBEDTLS_ERR_RSA_VERIFY_FAILED;
2132
0
    }
2133
2134
0
    return 0;
2135
0
}
2136
2137
/*
2138
 * Simplified PKCS#1 v2.1 RSASSA-PSS-VERIFY function
2139
 */
2140
int mbedtls_rsa_rsassa_pss_verify(mbedtls_rsa_context *ctx,
2141
                                  mbedtls_md_type_t md_alg,
2142
                                  unsigned int hashlen,
2143
                                  const unsigned char *hash,
2144
                                  const unsigned char *sig)
2145
0
{
2146
0
    mbedtls_md_type_t mgf1_hash_id;
2147
0
    if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2148
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2149
0
    }
2150
2151
0
    mgf1_hash_id = (ctx->hash_id != MBEDTLS_MD_NONE)
2152
0
                             ? (mbedtls_md_type_t) ctx->hash_id
2153
0
                             : md_alg;
2154
2155
0
    return mbedtls_rsa_rsassa_pss_verify_ext(ctx,
2156
0
                                             md_alg, hashlen, hash,
2157
0
                                             mgf1_hash_id,
2158
0
                                             MBEDTLS_RSA_SALT_LEN_ANY,
2159
0
                                             sig);
2160
2161
0
}
2162
#endif /* MBEDTLS_PKCS1_V21 */
2163
2164
#if defined(MBEDTLS_PKCS1_V15)
2165
/*
2166
 * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-v1_5-VERIFY function
2167
 */
2168
int mbedtls_rsa_rsassa_pkcs1_v15_verify(mbedtls_rsa_context *ctx,
2169
                                        mbedtls_md_type_t md_alg,
2170
                                        unsigned int hashlen,
2171
                                        const unsigned char *hash,
2172
                                        const unsigned char *sig)
2173
1.04k
{
2174
1.04k
    int ret = 0;
2175
1.04k
    size_t sig_len;
2176
1.04k
    unsigned char *encoded = NULL, *encoded_expected = NULL;
2177
2178
1.04k
    if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2179
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2180
0
    }
2181
2182
1.04k
    sig_len = ctx->len;
2183
2184
    /*
2185
     * Prepare expected PKCS1 v1.5 encoding of hash.
2186
     */
2187
2188
1.04k
    if ((encoded          = mbedtls_calloc(1, sig_len)) == NULL ||
2189
1.04k
        (encoded_expected = mbedtls_calloc(1, sig_len)) == NULL) {
2190
0
        ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
2191
0
        goto cleanup;
2192
0
    }
2193
2194
1.04k
    if ((ret = rsa_rsassa_pkcs1_v15_encode(md_alg, hashlen, hash, sig_len,
2195
1.04k
                                           encoded_expected)) != 0) {
2196
0
        goto cleanup;
2197
0
    }
2198
2199
    /*
2200
     * Apply RSA primitive to get what should be PKCS1 encoded hash.
2201
     */
2202
2203
1.04k
    ret = mbedtls_rsa_public(ctx, sig, encoded);
2204
1.04k
    if (ret != 0) {
2205
29
        goto cleanup;
2206
29
    }
2207
2208
    /*
2209
     * Compare
2210
     */
2211
2212
1.01k
    if ((ret = mbedtls_ct_memcmp(encoded, encoded_expected,
2213
1.01k
                                 sig_len)) != 0) {
2214
1.01k
        ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
2215
1.01k
        goto cleanup;
2216
1.01k
    }
2217
2218
1.04k
cleanup:
2219
2220
1.04k
    if (encoded != NULL) {
2221
1.04k
        mbedtls_platform_zeroize(encoded, sig_len);
2222
1.04k
        mbedtls_free(encoded);
2223
1.04k
    }
2224
2225
1.04k
    if (encoded_expected != NULL) {
2226
1.04k
        mbedtls_platform_zeroize(encoded_expected, sig_len);
2227
1.04k
        mbedtls_free(encoded_expected);
2228
1.04k
    }
2229
2230
1.04k
    return ret;
2231
1.01k
}
2232
#endif /* MBEDTLS_PKCS1_V15 */
2233
2234
/*
2235
 * Do an RSA operation and check the message digest
2236
 */
2237
int mbedtls_rsa_pkcs1_verify(mbedtls_rsa_context *ctx,
2238
                             mbedtls_md_type_t md_alg,
2239
                             unsigned int hashlen,
2240
                             const unsigned char *hash,
2241
                             const unsigned char *sig)
2242
1.04k
{
2243
1.04k
    if ((md_alg != MBEDTLS_MD_NONE || hashlen != 0) && hash == NULL) {
2244
0
        return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2245
0
    }
2246
2247
1.04k
    switch (ctx->padding) {
2248
0
#if defined(MBEDTLS_PKCS1_V15)
2249
1.04k
        case MBEDTLS_RSA_PKCS_V15:
2250
1.04k
            return mbedtls_rsa_rsassa_pkcs1_v15_verify(ctx, md_alg,
2251
1.04k
                                                       hashlen, hash, sig);
2252
0
#endif
2253
2254
0
#if defined(MBEDTLS_PKCS1_V21)
2255
0
        case MBEDTLS_RSA_PKCS_V21:
2256
0
            return mbedtls_rsa_rsassa_pss_verify(ctx, md_alg,
2257
0
                                                 hashlen, hash, sig);
2258
0
#endif
2259
2260
0
        default:
2261
0
            return MBEDTLS_ERR_RSA_INVALID_PADDING;
2262
1.04k
    }
2263
1.04k
}
2264
2265
/*
2266
 * Copy the components of an RSA key
2267
 */
2268
int mbedtls_rsa_copy(mbedtls_rsa_context *dst, const mbedtls_rsa_context *src)
2269
0
{
2270
0
    int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
2271
2272
0
    dst->len = src->len;
2273
2274
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->N, &src->N));
2275
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->E, &src->E));
2276
2277
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->D, &src->D));
2278
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->P, &src->P));
2279
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Q, &src->Q));
2280
2281
0
#if !defined(MBEDTLS_RSA_NO_CRT)
2282
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->DP, &src->DP));
2283
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->DQ, &src->DQ));
2284
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->QP, &src->QP));
2285
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RP, &src->RP));
2286
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RQ, &src->RQ));
2287
0
#endif
2288
2289
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->RN, &src->RN));
2290
2291
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Vi, &src->Vi));
2292
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_copy(&dst->Vf, &src->Vf));
2293
2294
0
    dst->padding = src->padding;
2295
0
    dst->hash_id = src->hash_id;
2296
2297
0
cleanup:
2298
0
    if (ret != 0) {
2299
0
        mbedtls_rsa_free(dst);
2300
0
    }
2301
2302
0
    return ret;
2303
0
}
2304
2305
/*
2306
 * Free the components of an RSA key
2307
 */
2308
void mbedtls_rsa_free(mbedtls_rsa_context *ctx)
2309
12.0k
{
2310
12.0k
    if (ctx == NULL) {
2311
0
        return;
2312
0
    }
2313
2314
12.0k
    mbedtls_mpi_free(&ctx->Vi);
2315
12.0k
    mbedtls_mpi_free(&ctx->Vf);
2316
12.0k
    mbedtls_mpi_free(&ctx->RN);
2317
12.0k
    mbedtls_mpi_free(&ctx->D);
2318
12.0k
    mbedtls_mpi_free(&ctx->Q);
2319
12.0k
    mbedtls_mpi_free(&ctx->P);
2320
12.0k
    mbedtls_mpi_free(&ctx->E);
2321
12.0k
    mbedtls_mpi_free(&ctx->N);
2322
2323
12.0k
#if !defined(MBEDTLS_RSA_NO_CRT)
2324
12.0k
    mbedtls_mpi_free(&ctx->RQ);
2325
12.0k
    mbedtls_mpi_free(&ctx->RP);
2326
12.0k
    mbedtls_mpi_free(&ctx->QP);
2327
12.0k
    mbedtls_mpi_free(&ctx->DQ);
2328
12.0k
    mbedtls_mpi_free(&ctx->DP);
2329
12.0k
#endif /* MBEDTLS_RSA_NO_CRT */
2330
2331
#if defined(MBEDTLS_THREADING_C)
2332
    /* Free the mutex, but only if it hasn't been freed already. */
2333
    if (ctx->ver != 0) {
2334
        mbedtls_mutex_free(&ctx->mutex);
2335
        ctx->ver = 0;
2336
    }
2337
#endif
2338
12.0k
}
2339
2340
#endif /* !MBEDTLS_RSA_ALT */
2341
2342
#if defined(MBEDTLS_SELF_TEST)
2343
2344
#include "mbedtls/sha1.h"
2345
2346
/*
2347
 * Example RSA-1024 keypair, for test purposes
2348
 */
2349
#define KEY_LEN 128
2350
2351
#define RSA_N   "9292758453063D803DD603D5E777D788" \
2352
                "8ED1D5BF35786190FA2F23EBC0848AEA" \
2353
                "DDA92CA6C3D80B32C4D109BE0F36D6AE" \
2354
                "7130B9CED7ACDF54CFC7555AC14EEBAB" \
2355
                "93A89813FBF3C4F8066D2D800F7C38A8" \
2356
                "1AE31942917403FF4946B0A83D3D3E05" \
2357
                "EE57C6F5F5606FB5D4BC6CD34EE0801A" \
2358
                "5E94BB77B07507233A0BC7BAC8F90F79"
2359
2360
#define RSA_E   "10001"
2361
2362
#define RSA_D   "24BF6185468786FDD303083D25E64EFC" \
2363
                "66CA472BC44D253102F8B4A9D3BFA750" \
2364
                "91386C0077937FE33FA3252D28855837" \
2365
                "AE1B484A8A9A45F7EE8C0C634F99E8CD" \
2366
                "DF79C5CE07EE72C7F123142198164234" \
2367
                "CABB724CF78B8173B9F880FC86322407" \
2368
                "AF1FEDFDDE2BEB674CA15F3E81A1521E" \
2369
                "071513A1E85B5DFA031F21ECAE91A34D"
2370
2371
#define RSA_P   "C36D0EB7FCD285223CFB5AABA5BDA3D8" \
2372
                "2C01CAD19EA484A87EA4377637E75500" \
2373
                "FCB2005C5C7DD6EC4AC023CDA285D796" \
2374
                "C3D9E75E1EFC42488BB4F1D13AC30A57"
2375
2376
#define RSA_Q   "C000DF51A7C77AE8D7C7370C1FF55B69" \
2377
                "E211C2B9E5DB1ED0BF61D0D9899620F4" \
2378
                "910E4168387E3C30AA1E00C339A79508" \
2379
                "8452DD96A9A5EA5D9DCA68DA636032AF"
2380
2381
0
#define PT_LEN  24
2382
0
#define RSA_PT  "\xAA\xBB\xCC\x03\x02\x01\x00\xFF\xFF\xFF\xFF\xFF" \
2383
0
                "\x11\x22\x33\x0A\x0B\x0C\xCC\xDD\xDD\xDD\xDD\xDD"
2384
2385
#if defined(MBEDTLS_PKCS1_V15)
2386
static int myrand(void *rng_state, unsigned char *output, size_t len)
2387
0
{
2388
0
#if !defined(__OpenBSD__) && !defined(__NetBSD__)
2389
0
    size_t i;
2390
2391
0
    if (rng_state != NULL) {
2392
0
        rng_state  = NULL;
2393
0
    }
2394
2395
0
    for (i = 0; i < len; ++i) {
2396
0
        output[i] = rand();
2397
0
    }
2398
#else
2399
    if (rng_state != NULL) {
2400
        rng_state = NULL;
2401
    }
2402
2403
    arc4random_buf(output, len);
2404
#endif /* !OpenBSD && !NetBSD */
2405
2406
0
    return 0;
2407
0
}
2408
#endif /* MBEDTLS_PKCS1_V15 */
2409
2410
/*
2411
 * Checkup routine
2412
 */
2413
int mbedtls_rsa_self_test(int verbose)
2414
0
{
2415
0
    int ret = 0;
2416
0
#if defined(MBEDTLS_PKCS1_V15)
2417
0
    size_t len;
2418
0
    mbedtls_rsa_context rsa;
2419
0
    unsigned char rsa_plaintext[PT_LEN];
2420
0
    unsigned char rsa_decrypted[PT_LEN];
2421
0
    unsigned char rsa_ciphertext[KEY_LEN];
2422
0
#if defined(MBEDTLS_SHA1_C)
2423
0
    unsigned char sha1sum[20];
2424
0
#endif
2425
2426
0
    mbedtls_mpi K;
2427
2428
0
    mbedtls_mpi_init(&K);
2429
0
    mbedtls_rsa_init(&rsa);
2430
2431
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_N));
2432
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, &K, NULL, NULL, NULL, NULL));
2433
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_P));
2434
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, &K, NULL, NULL, NULL));
2435
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_Q));
2436
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, &K, NULL, NULL));
2437
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_D));
2438
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, NULL, &K, NULL));
2439
0
    MBEDTLS_MPI_CHK(mbedtls_mpi_read_string(&K, 16, RSA_E));
2440
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_import(&rsa, NULL, NULL, NULL, NULL, &K));
2441
2442
0
    MBEDTLS_MPI_CHK(mbedtls_rsa_complete(&rsa));
2443
2444
0
    if (verbose != 0) {
2445
0
        mbedtls_printf("  RSA key validation: ");
2446
0
    }
2447
2448
0
    if (mbedtls_rsa_check_pubkey(&rsa) != 0 ||
2449
0
        mbedtls_rsa_check_privkey(&rsa) != 0) {
2450
0
        if (verbose != 0) {
2451
0
            mbedtls_printf("failed\n");
2452
0
        }
2453
2454
0
        ret = 1;
2455
0
        goto cleanup;
2456
0
    }
2457
2458
0
    if (verbose != 0) {
2459
0
        mbedtls_printf("passed\n  PKCS#1 encryption : ");
2460
0
    }
2461
2462
0
    memcpy(rsa_plaintext, RSA_PT, PT_LEN);
2463
2464
0
    if (mbedtls_rsa_pkcs1_encrypt(&rsa, myrand, NULL,
2465
0
                                  PT_LEN, rsa_plaintext,
2466
0
                                  rsa_ciphertext) != 0) {
2467
0
        if (verbose != 0) {
2468
0
            mbedtls_printf("failed\n");
2469
0
        }
2470
2471
0
        ret = 1;
2472
0
        goto cleanup;
2473
0
    }
2474
2475
0
    if (verbose != 0) {
2476
0
        mbedtls_printf("passed\n  PKCS#1 decryption : ");
2477
0
    }
2478
2479
0
    if (mbedtls_rsa_pkcs1_decrypt(&rsa, myrand, NULL,
2480
0
                                  &len, rsa_ciphertext, rsa_decrypted,
2481
0
                                  sizeof(rsa_decrypted)) != 0) {
2482
0
        if (verbose != 0) {
2483
0
            mbedtls_printf("failed\n");
2484
0
        }
2485
2486
0
        ret = 1;
2487
0
        goto cleanup;
2488
0
    }
2489
2490
0
    if (memcmp(rsa_decrypted, rsa_plaintext, len) != 0) {
2491
0
        if (verbose != 0) {
2492
0
            mbedtls_printf("failed\n");
2493
0
        }
2494
2495
0
        ret = 1;
2496
0
        goto cleanup;
2497
0
    }
2498
2499
0
    if (verbose != 0) {
2500
0
        mbedtls_printf("passed\n");
2501
0
    }
2502
2503
0
#if defined(MBEDTLS_SHA1_C)
2504
0
    if (verbose != 0) {
2505
0
        mbedtls_printf("  PKCS#1 data sign  : ");
2506
0
    }
2507
2508
0
    if (mbedtls_sha1(rsa_plaintext, PT_LEN, sha1sum) != 0) {
2509
0
        if (verbose != 0) {
2510
0
            mbedtls_printf("failed\n");
2511
0
        }
2512
2513
0
        return 1;
2514
0
    }
2515
2516
0
    if (mbedtls_rsa_pkcs1_sign(&rsa, myrand, NULL,
2517
0
                               MBEDTLS_MD_SHA1, 20,
2518
0
                               sha1sum, rsa_ciphertext) != 0) {
2519
0
        if (verbose != 0) {
2520
0
            mbedtls_printf("failed\n");
2521
0
        }
2522
2523
0
        ret = 1;
2524
0
        goto cleanup;
2525
0
    }
2526
2527
0
    if (verbose != 0) {
2528
0
        mbedtls_printf("passed\n  PKCS#1 sig. verify: ");
2529
0
    }
2530
2531
0
    if (mbedtls_rsa_pkcs1_verify(&rsa, MBEDTLS_MD_SHA1, 20,
2532
0
                                 sha1sum, rsa_ciphertext) != 0) {
2533
0
        if (verbose != 0) {
2534
0
            mbedtls_printf("failed\n");
2535
0
        }
2536
2537
0
        ret = 1;
2538
0
        goto cleanup;
2539
0
    }
2540
2541
0
    if (verbose != 0) {
2542
0
        mbedtls_printf("passed\n");
2543
0
    }
2544
0
#endif /* MBEDTLS_SHA1_C */
2545
2546
0
    if (verbose != 0) {
2547
0
        mbedtls_printf("\n");
2548
0
    }
2549
2550
0
cleanup:
2551
0
    mbedtls_mpi_free(&K);
2552
0
    mbedtls_rsa_free(&rsa);
2553
#else /* MBEDTLS_PKCS1_V15 */
2554
    ((void) verbose);
2555
#endif /* MBEDTLS_PKCS1_V15 */
2556
0
    return ret;
2557
0
}
2558
2559
#endif /* MBEDTLS_SELF_TEST */
2560
2561
#endif /* MBEDTLS_RSA_C */