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