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