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