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