1 /*
2  * Copyright (c) 2001-2022, Arm Limited and Contributors. All rights reserved.
3  *
4  * SPDX-License-Identifier: BSD-3-Clause
5  */
6 
7 #include "mbedtls/build_info.h"
8 
9 #if defined(MBEDTLS_RSA_C)
10 
11 #include "mbedtls/rsa.h"
12 #include "mbedtls/oid.h"
13 #include "mbedtls_common.h"
14 #include "mbedtls/bignum.h"
15 
16 #include <string.h>
17 
18 #if defined(MBEDTLS_PKCS1_V21)
19 #include "mbedtls/md.h"
20 #endif
21 
22 #if defined(MBEDTLS_PKCS1_V15) && !defined(__OpenBSD__)
23 #include <stdlib.h>
24 #endif
25 
26 #if defined(MBEDTLS_PLATFORM_C)
27 #include "mbedtls/platform.h"
28 #else
29 #define mbedtls_printf printf
30 #define mbedtls_calloc calloc
31 #define mbedtls_free   free
32 #endif
33 
34 
35 #if defined (MBEDTLS_RSA_ALT)
36 #include "cc_bitops.h"
37 #include "rsa_public.h"
38 #include "rsa_private.h"
39 #include "cc_pal_mem.h"
40 #include "cc_rsa_error.h"
41 #include "cc_rsa_local.h"
42 #include "cc_common_math.h"
43 #include "cc_fips_defs.h"
44 #include "cc_pal_types_plat.h"
45 #include "cc_pal_log.h"
46 #include "cc_rsa_schemes.h"
47 #include "cc_rnd_common.h"
48 #include "cc_rnd_error.h"
49 
50 #define IN
51 #define OUT
52 
53 #include "cc_rsa_kg.h"
54 #include "cc_rsa_prim.h"
55 #include "cc_common.h"
56 #include "pki.h"
57 #include "rsa.h"
58 
59 #include "mbedtls/ctr_drbg.h"
60 #include "pka.h"
61 #include "cc_pal_abort.h"
62 
63 #define GOTO_END(ERR) \
64     do { \
65         Error = ERR; \
66         goto End; \
67     } while (0)
68 
69 #define GOTO_CLEANUP(ERR) \
70     do { \
71         Error = ERR; \
72         goto Cleanup; \
73     } while (0)
74 
75 
76 /* Minimal and maximal size of RSA modulus in bits
77  * According to FIPS 186-4 size in bits should be in range [1024...3072] */
78 #define MBEDTLS_RSA_MIN_VALID_KEY_SIZE_VALUE_IN_BITS  1024
79 #define MBEDTLS_RSA_MAX_VALID_KEY_SIZE_VALUE_IN_BITS  4096
80 
81 #define MBEDTLS_RSA_MIN_VALID_KEYGEN_SIZE_VALUE_IN_BITS  1024
82 #define MBEDTLS_RSA_MAX_VALID_KEYGEN_SIZE_VALUE_IN_BITS  3072
83 
84 #define MBEDTLS_RSA_CHK(f) do { if( ( err = f ) != 0 ) goto End; } while( 0 )
85 
86 #define  MOD_LEN_ID 0
87 #define  REG_LEN_ID 1
88 #define  PLEN_ID    2
89 
90 typedef enum {
91     CC_RSA_OP_DEFAULT,
92     CC_RSA_OP_PUBLIC,
93     CC_RSA_OP_PRIVATE,
94 } CC_RSA_OP;
95 
96 static int mbedtls_alt_rsa_deduce_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q,
97                             const mbedtls_mpi *D, mbedtls_mpi *DP,
98                             mbedtls_mpi *DQ, mbedtls_mpi *QP );
99 
100 /* Implementation that should never be optimized out by the compiler */
mbedtls_rsa_zeroize(void * v,size_t n)101 static void mbedtls_rsa_zeroize( void *v, size_t n ) {
102     volatile uint8_t *p = v; while( n-- ) *p++ = 0;
103 }
104 
105 /* The function zeroizes size_bytes part on allocated buffer and
106  * then releases the memory given by the pointer X
107  */
mbedtls_buff_free(void * X,size_t size_bytes)108 static void mbedtls_buff_free( void *X, size_t size_bytes )
109 {
110     if( X == NULL )
111         return;
112     if(size_bytes != 0)
113         mbedtls_rsa_zeroize( X, size_bytes );
114 
115     mbedtls_free( X );
116 }
117 
118 #define WORD_SIZE_IN_BYTES       sizeof(mbedtls_mpi_uint)
119 
mbedtls_mpi_size_in_words(const mbedtls_mpi * X)120 static size_t mbedtls_mpi_size_in_words( const mbedtls_mpi *X )
121 {
122     return ((mbedtls_mpi_size(X) + WORD_SIZE_IN_BYTES - 1) / WORD_SIZE_IN_BYTES);
123 }
124 /*
125 * The function allocates mpi inner buffer X->p of required length sizeInWords, copies given data into it.
126 * Assumed that the data is positive, therefore the function sets X->s = 1.
127 */
mbedtls_rsa_uint32_buf_to_mpi(mbedtls_mpi * X,const uint32_t * buf,size_t sizeInWords)128 static int32_t mbedtls_rsa_uint32_buf_to_mpi(mbedtls_mpi *X, const uint32_t *buf, size_t sizeInWords)
129 {
130      int32_t err = 0;
131 
132      if(X == NULL || X->MBEDTLS_PRIVATE(p) != NULL || X->MBEDTLS_PRIVATE(n) != 0 || sizeInWords == 0) {
133         err = MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
134         goto End;
135      }
136 
137     if( ( X->MBEDTLS_PRIVATE(p) = (uint32_t*)mbedtls_calloc( sizeInWords, sizeof(uint32_t) ) ) == NULL ) {
138         err = MBEDTLS_ERR_MPI_ALLOC_FAILED;
139         goto End;
140     }
141 
142     CC_PalMemCopy(X->MBEDTLS_PRIVATE(p), buf, sizeInWords*CC_32BIT_WORD_SIZE);
143     X->MBEDTLS_PRIVATE(s) = 1;
144     X->MBEDTLS_PRIVATE(n) = sizeInWords;
145 
146     End:
147     return err;
148 }
149 
150 
151 /*
152  * The function converts CC errors codes to appropriate mbedtls defined code
153  *
154  * */
error_mapping_cc_to_mbedtls_rsa(CCError_t cc_error,CC_RSA_OP op)155 static int error_mapping_cc_to_mbedtls_rsa (CCError_t cc_error, CC_RSA_OP op)
156 {
157     int ret=-1;
158     int base = 0;
159 
160     switch (op)
161     {
162         case CC_RSA_OP_PUBLIC:
163             base = MBEDTLS_ERR_RSA_PUBLIC_FAILED;
164             break;
165 
166         case CC_RSA_OP_PRIVATE:
167             base = MBEDTLS_ERR_RSA_PRIVATE_FAILED;
168             break;
169 
170         default:
171             base = 0;
172             break;
173     }
174 
175     switch (cc_error)
176     {
177         case CC_OK:
178             return 0;
179             break;
180 
181         case CC_RSA_BASE_MGF_MASK_TOO_LONG:
182         case CC_RSA_BASE_OAEP_DECODE_MESSAGE_TOO_LONG:
183         case CC_RSA_BASE_OAEP_DECODE_PARAMETER_STRING_TOO_LONG:
184         case CC_RSA_BASE_OAEP_ENCODE_MESSAGE_TOO_LONG:
185         case CC_RSA_BASE_OAEP_ENCODE_PARAMETER_STRING_TOO_LONG:
186         case CC_RSA_CONV_TO_CRT_INVALID_TEMP_BUFF_POINTER_ERROR:
187         case CC_RSA_DATA_POINTER_INVALID_ERROR:
188         case CC_RSA_DECRYPT_INVALID_OUTPUT_SIZE:
189         case CC_RSA_DECRYPT_OUTPUT_SIZE_POINTER_ERROR:
190         case CC_RSA_ENCODE_15_MSG_OUT_OF_RANGE:
191         case CC_RSA_GET_DER_HASH_MODE_ILLEGAL:
192         case CC_RSA_HASH_ILLEGAL_OPERATION_MODE_ERROR:
193         case CC_RSA_ILLEGAL_PARAMS_ACCORDING_TO_PRIV_ERROR:
194         case CC_RSA_INVALID_CRT_COEFFICIENT_PTR_ERROR:
195         case CC_RSA_INVALID_CRT_COEFFICIENT_SIZE_ERROR:
196         case CC_RSA_INVALID_CRT_COEFFICIENT_SIZE_PTR_ERROR:
197         case CC_RSA_INVALID_CRT_COEFF_VAL:
198         case CC_RSA_INVALID_CRT_FIRST_AND_SECOND_FACTOR_SIZE:
199         case CC_RSA_INVALID_CRT_FIRST_FACTOR_EXPONENT_VAL:
200         case CC_RSA_INVALID_CRT_FIRST_FACTOR_EXP_PTR_ERROR:
201         case CC_RSA_INVALID_CRT_FIRST_FACTOR_EXP_SIZE_ERROR:
202         case CC_RSA_INVALID_CRT_FIRST_FACTOR_EXP_SIZE_PTR_ERROR:
203         case CC_RSA_INVALID_CRT_FIRST_FACTOR_POINTER_ERROR:
204         case CC_RSA_INVALID_CRT_FIRST_FACTOR_SIZE:
205         case CC_RSA_INVALID_CRT_FIRST_FACTOR_SIZE_ERROR:
206         case CC_RSA_INVALID_CRT_FIRST_FACTOR_SIZE_POINTER_ERROR:
207         case CC_RSA_INVALID_CRT_PARAMETR_SIZE_ERROR:
208         case CC_RSA_INVALID_CRT_SECOND_FACTOR_EXPONENT_VAL:
209         case CC_RSA_INVALID_CRT_SECOND_FACTOR_EXP_PTR_ERROR:
210         case CC_RSA_INVALID_CRT_SECOND_FACTOR_EXP_SIZE_ERROR:
211         case CC_RSA_INVALID_CRT_SECOND_FACTOR_EXP_SIZE_PTR_ERROR:
212         case CC_RSA_INVALID_CRT_SECOND_FACTOR_POINTER_ERROR:
213         case CC_RSA_INVALID_CRT_SECOND_FACTOR_SIZE:
214         case CC_RSA_INVALID_CRT_SECOND_FACTOR_SIZE_ERROR:
215         case CC_RSA_INVALID_CRT_SECOND_FACTOR_SIZE_POINTER_ERROR:
216         case CC_RSA_INVALID_DECRYPRION_MODE_ERROR:
217         case CC_RSA_INVALID_EXPONENT_POINTER_ERROR:
218         case CC_RSA_INVALID_EXPONENT_SIZE:
219         case CC_RSA_INVALID_EXPONENT_VAL:
220         case CC_RSA_INVALID_EXP_BUFFER_SIZE_POINTER:
221         case CC_RSA_INVALID_MESSAGE_BUFFER_SIZE:
222         case CC_RSA_INVALID_MESSAGE_DATA_SIZE:
223         case CC_RSA_INVALID_MODULUS_ERROR:
224         case CC_RSA_INVALID_MODULUS_POINTER_ERROR:
225         case CC_RSA_INVALID_MODULUS_SIZE:
226         case CC_RSA_INVALID_MOD_BUFFER_SIZE_POINTER:
227         case CC_RSA_INVALID_OUTPUT_POINTER_ERROR:
228         case CC_RSA_INVALID_OUTPUT_SIZE_POINTER_ERROR:
229         case CC_RSA_INVALID_PRIV_KEY_STRUCT_POINTER_ERROR:
230         case CC_RSA_INVALID_PTR_ERROR:
231         case CC_RSA_INVALID_PUB_KEY_STRUCT_POINTER_ERROR:
232         case CC_RSA_INVALID_SIGNATURE_BUFFER_POINTER:
233         case CC_RSA_INVALID_SIGNATURE_BUFFER_SIZE:
234         case CC_RSA_INVALID_USER_CONTEXT_POINTER_ERROR:
235         case CC_RSA_KEY_GEN_DATA_STRUCT_POINTER_INVALID:
236         case CC_RSA_MGF_ILLEGAL_ARG_ERROR:
237         case CC_RSA_MODULUS_EVEN_ERROR:
238         case CC_RSA_PKCS1_VER_ARG_ERROR:
239         case CC_RSA_PRIM_DATA_STRUCT_POINTER_INVALID:
240         case CC_RSA_PRIV_KEY_VALIDATION_TAG_ERROR:
241         case CC_RSA_PSS_ENCODING_MODULUS_HASH_SALT_LENGTHS_ERROR:
242         case CC_RSA_PUB_KEY_VALIDATION_TAG_ERROR:
243         case CC_RSA_USER_CONTEXT_VALIDATION_TAG_ERROR:
244         case CC_RSA_WRONG_PRIVATE_KEY_TYPE:
245             ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
246             break;
247 
248         case CC_RSA_INVALID_MESSAGE_VAL:
249             ret = base + MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
250             break;
251 
252         case CC_RSA_INVALID_MESSAGE_DATA_SIZE_IN_SSL_CASE:
253         case CC_RSA_ERROR_IN_DECRYPTED_BLOCK_PARSING:
254         case CC_RSA_OAEP_DECODE_ERROR:
255             ret = MBEDTLS_ERR_RSA_INVALID_PADDING;
256             break;
257 
258         case CC_RSA_15_ERROR_IN_DECRYPTED_DATA_SIZE:
259             ret = MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE;
260             break;
261 
262         case CC_RSA_KEY_GEN_CONDITIONAL_TEST_FAIL_ERROR:
263         case CC_RSA_GENERATED_PRIV_KEY_IS_TOO_LOW:
264         case CC_RSA_KEY_GENERATION_FAILURE_ERROR:
265             ret = MBEDTLS_ERR_RSA_KEY_GEN_FAILED;
266             break;
267 
268         case CC_RSA_CAN_NOT_GENERATE_RAND_IN_RANGE:
269         case CC_RSA_ERROR_IN_RANDOM_OPERATION_FOR_ENCODE:
270         case CC_RND_STATE_PTR_INVALID_ERROR:
271         case CC_RND_GEN_VECTOR_FUNC_ERROR:
272             ret = MBEDTLS_ERR_RSA_RNG_FAILED;
273             break;
274 
275         case CC_RSA_ERROR_VER15_INCONSISTENT_VERIFY:
276         case CC_RSA_ERROR_PSS_INCONSISTENT_VERIFY:
277             ret = MBEDTLS_ERR_RSA_VERIFY_FAILED;
278             break;
279 
280         // For now, there is no better error code for malloc failure, both in CC and mbedtls
281         case CC_OUT_OF_RESOURCE_ERROR:
282             ret = -1;
283             break;
284 
285         default:
286             ret = -1;
287             CC_PAL_LOG_ERR("Unknown CC_ERROR %d (0x%08x)\r\n", cc_error, cc_error);
288             break;
289     }
290 
291 
292     CC_PAL_LOG_DEBUG("Converted CC_ERROR %d (0x%08x) to MBEDTLS_ERR %d\r\n",
293                      cc_error, cc_error, ret);
294     return ret;
295 }
296 
mbedtls_rsa_init(mbedtls_rsa_context * ctx)297 void mbedtls_rsa_init( mbedtls_rsa_context *ctx)
298 {
299     /* check input parameters and functions */
300     if (ctx == NULL){
301             CC_PalAbort("Ctx is NULL\n");
302     }
303     CC_PalMemSetZero(ctx, sizeof( mbedtls_rsa_context));
304 
305 #if defined(MBEDTLS_THREADING_C)
306     mbedtls_mutex_init( &ctx->MBEDTLS_PRIVATE(mutex) );
307 #endif
308 }
309 
310 /*
311  * Set padding for an existing RSA context
312  */
mbedtls_rsa_set_padding(mbedtls_rsa_context * ctx,int padding,mbedtls_md_type_t hash_id)313 int mbedtls_rsa_set_padding( mbedtls_rsa_context *ctx, int padding, mbedtls_md_type_t hash_id )
314 {
315     /* check input parameters and functions */
316     if (ctx == NULL){
317             CC_PalAbort("Ctx is NULL\n");
318     }
319     if ((hash_id != MBEDTLS_MD_NONE) && ((hash_id < MBEDTLS_MD_SHA1) || (hash_id > MBEDTLS_MD_SHA512))){
320             CC_PalAbort("Not valid hash id\n");
321     }
322     ctx->MBEDTLS_PRIVATE(padding) = padding;
323     ctx->MBEDTLS_PRIVATE(hash_id) = hash_id;
324 
325     return (0);
326 }
327 
328 #if defined(MBEDTLS_GENPRIME)
329 
330 /*
331  * Generate the RSA key pair (CRT and non CRT parameters) .
332  */
mbedtls_rsa_gen_key(mbedtls_rsa_context * pCtx,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng,unsigned int nbits,int pubExp)333 int mbedtls_rsa_gen_key( mbedtls_rsa_context *pCtx,    /*!< pointer to context structure, containing RSA parameters */
334         int (*f_rng)(void *, unsigned char *, size_t), /*<! random vector generation function prototype */
335         void *p_rng,                                   /*<! pointer to PRNG buffer (state) */
336         unsigned int nbits,                            /*<! RSA modulus size in bits */
337         int pubExp )                                   /*<! public exponent value */
338 {
339 
340 
341     CCRndContext_t rndContext;
342     CCRndContext_t *pRndContext = &rndContext;
343 
344     /* the Error return code identifier */
345     CCError_t err = CC_OK;
346     uint32_t pubExpSizeBits, mask;
347     uint32_t keySizeWords; /* size of RSA modulus */
348     CCRsaPubKey_t  *pCcPubKey = NULL;
349     CCRsaPrivKey_t *pCcPrivKey = NULL;
350     CCRsaKgData_t  *pKeyGenData = NULL;
351 
352     uint32_t keySizeBytes = CALC_FULL_BYTES(nbits);
353 #define PUB_EXP_SIZE_IN_WORDS 1
354 
355 #ifdef FIPS_CERTIFICATION
356     CCRsaKgFipsContext_t  FipsCtx;
357 #endif
358 
359 
360     /* check input parameters and functions */
361     if ( pCtx == NULL || f_rng == NULL || p_rng == NULL ){
362             return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
363     }
364 
365     /* verifying the exponent has legal value (currently only 0x3,0x11 and 0x10001) */
366     if (pubExp != CC_RSA_KG_PUB_EXP_ALLOW_VAL_1  &&
367         pubExp != CC_RSA_KG_PUB_EXP_ALLOW_VAL_2  &&
368         pubExp != CC_RSA_KG_PUB_EXP_ALLOW_VAL_3) {
369             return  MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
370     }
371 
372     /*  check that the key size allowed by CRYS requirements  */
373     if (( nbits < MBEDTLS_RSA_MIN_VALID_KEYGEN_SIZE_VALUE_IN_BITS ) ||
374         ( nbits > MBEDTLS_RSA_MAX_VALID_KEYGEN_SIZE_VALUE_IN_BITS ) ||
375         ( nbits % CC_RSA_VALID_KEY_SIZE_MULTIPLE_VALUE_IN_BITS )) {
376             return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
377     }
378 
379     /* set random generation function and context */
380     pRndContext->rndState = p_rng;
381 
382     err = CC_RndSetGenerateVectorFunc(pRndContext, f_rng);
383     if ( err != CC_OK ){
384             return MBEDTLS_ERR_RSA_RNG_FAILED;
385     }
386 
387     /* RSA modulus size in bytes and words */
388     keySizeWords = CALC_FULL_32BIT_WORDS(nbits);
389 
390     /* allocate temp buffers */
391     pCcPubKey = (CCRsaPubKey_t *)mbedtls_calloc(CALC_32BIT_WORDS_FROM_BYTES(sizeof(CCRsaPubKey_t)), sizeof(uint32_t));
392     if (pCcPubKey == NULL) {
393         err = CC_OUT_OF_RESOURCE_ERROR;
394         goto End;
395     }
396     pCcPrivKey = (CCRsaPrivKey_t *)mbedtls_calloc(CALC_32BIT_WORDS_FROM_BYTES(sizeof(CCRsaPrivKey_t)), sizeof(uint32_t));
397     if (pCcPrivKey == NULL) {
398         err = CC_OUT_OF_RESOURCE_ERROR;
399         goto End;
400     }
401     pKeyGenData = (CCRsaKgData_t *)mbedtls_calloc(CALC_32BIT_WORDS_FROM_BYTES(sizeof(CCRsaKgData_t)), sizeof(uint32_t));
402     if (pKeyGenData == NULL) {
403         err = CC_OUT_OF_RESOURCE_ERROR;
404         goto End;
405     }
406 
407     /* get pub.exp size in bits */
408     pubExpSizeBits = 32;
409     mask = 1UL << 31;
410     while((pubExp & mask) == 0) {
411         pubExpSizeBits--;
412         mask >>= 1;
413     }
414 
415     /* init sizes */
416     pCcPubKey->nSizeInBits  = nbits;
417     pCcPubKey->eSizeInBits  = pubExpSizeBits;
418     pCcPrivKey->nSizeInBits = nbits;
419     pCcPubKey->e[0] = pubExp;
420 
421     /* set params for non CRT */
422     pCcPrivKey->OperationMode = CC_RSA_NoCrt; /* default mode */
423     pCcPrivKey->PriveKeyDb.NonCrt.eSizeInBits = pCcPubKey->eSizeInBits;
424     pCcPrivKey->PriveKeyDb.NonCrt.e[0] = pubExp;
425 
426 
427     /* .....   calculate primes (P, Q) and nonCRT key (N, D) ..... */
428     do{
429          err = RsaGenPandQ(
430                         pRndContext,
431                         nbits,
432                         pubExpSizeBits,
433                         (uint32_t*)&pubExp,
434                         pKeyGenData );
435         if (err != CC_OK) {
436            goto End;
437         }
438 
439         /* calculate modulus n and private nonCRT exponent d */
440         err = RsaCalculateNandD(
441                         pCcPubKey,
442                         pCcPrivKey,
443                         pKeyGenData,
444                         nbits/2 );
445 
446         if (err != CC_OK) {
447             goto End;
448         }
449 
450         /* repeat the loop if D is too low */
451     } while( err == CC_RSA_GENERATED_PRIV_KEY_IS_TOO_LOW );
452 
453      /* calculate Barr. tag for modulus N */
454     err = PkiCalcNp(((RsaPubKeyDb_t*)(pCcPubKey->ccRSAIntBuff))->NP, /*out*/
455             pCcPubKey->n, nbits);   /*in*/
456 
457     if (err != CC_OK) {
458         goto End;
459     }
460 
461 
462     /* allocate mbedtls context internal buffers and copy data to them  */
463     pCtx->MBEDTLS_PRIVATE(len) = keySizeBytes; /* full size of modulus in bytes, including leading zeros*/
464     MBEDTLS_RSA_CHK( mbedtls_rsa_uint32_buf_to_mpi( &pCtx->MBEDTLS_PRIVATE(N), pCcPubKey->n, keySizeWords ) );
465     MBEDTLS_RSA_CHK( mbedtls_rsa_uint32_buf_to_mpi( &pCtx->MBEDTLS_PRIVATE(E), pCcPubKey->e, PUB_EXP_SIZE_IN_WORDS ) );
466     MBEDTLS_RSA_CHK( mbedtls_rsa_uint32_buf_to_mpi( &pCtx->MBEDTLS_PRIVATE(D), pCcPrivKey->PriveKeyDb.NonCrt.d, keySizeWords ) );
467     MBEDTLS_RSA_CHK( mbedtls_rsa_uint32_buf_to_mpi( &pCtx->MBEDTLS_PRIVATE(NP), ((RsaPubKeyDb_t*)(pCcPubKey->ccRSAIntBuff))->NP,
468                            CC_PKA_BARRETT_MOD_TAG_SIZE_IN_WORDS ) );
469 
470     /*  P,Q saved in the context as it is done in mbedtls independent on
471      * CRT compilation flag  */
472     MBEDTLS_RSA_CHK( mbedtls_rsa_uint32_buf_to_mpi( &pCtx->MBEDTLS_PRIVATE(P), pKeyGenData->KGData.p, keySizeWords/2 ) );
473     MBEDTLS_RSA_CHK( mbedtls_rsa_uint32_buf_to_mpi( &pCtx->MBEDTLS_PRIVATE(Q), pKeyGenData->KGData.q, keySizeWords/2 ) );
474 
475     /* calculate Barrett tags for P,Q and set into context */
476     err = PkiCalcNp(((RsaPrivKeyDb_t *)(pCcPrivKey->ccRSAPrivKeyIntBuff))->Crt.PP,/*out*/
477             pKeyGenData->KGData.p, nbits/2);   /*in*/
478     if (err != CC_OK) {
479         goto End;
480     }
481     err = PkiCalcNp(((RsaPrivKeyDb_t *)(pCcPrivKey->ccRSAPrivKeyIntBuff))->Crt.QP,/*out*/
482             pKeyGenData->KGData.q, nbits/2);   /*in*/
483     if (err != CC_OK) {
484         goto End;
485     }
486     MBEDTLS_RSA_CHK( mbedtls_rsa_uint32_buf_to_mpi( &pCtx->MBEDTLS_PRIVATE(BPP), ((RsaPrivKeyDb_t*)(pCcPrivKey->ccRSAPrivKeyIntBuff))->Crt.PP, CC_PKA_BARRETT_MOD_TAG_SIZE_IN_WORDS ) );
487     MBEDTLS_RSA_CHK( mbedtls_rsa_uint32_buf_to_mpi( &pCtx->MBEDTLS_PRIVATE(BQP), ((RsaPrivKeyDb_t*)(pCcPrivKey->ccRSAPrivKeyIntBuff))->Crt.QP, CC_PKA_BARRETT_MOD_TAG_SIZE_IN_WORDS ) );
488 
489     /* calculate CRT parameters */
490 #if !defined(MBEDTLS_RSA_NO_CRT)
491     pCcPrivKey->OperationMode = CC_RSA_Crt;
492     err = RsaCalculateCrtParams(
493                         (uint32_t*)&pubExp, pubExpSizeBits,
494                         nbits,
495                         pKeyGenData->KGData.p, pKeyGenData->KGData.q,
496                         pCcPrivKey->PriveKeyDb.Crt.dP,
497                         pCcPrivKey->PriveKeyDb.Crt.dQ,
498                         pCcPrivKey->PriveKeyDb.Crt.qInv );
499 
500     if (err !=CC_OK) {
501        goto End;
502     }
503 
504     /* allocate mbedtls context internal buffers and copy data to them  */
505     MBEDTLS_RSA_CHK( mbedtls_rsa_uint32_buf_to_mpi( &pCtx->MBEDTLS_PRIVATE(DP), pCcPrivKey->PriveKeyDb.Crt.dP, keySizeWords/2 ) );
506     MBEDTLS_RSA_CHK( mbedtls_rsa_uint32_buf_to_mpi( &pCtx->MBEDTLS_PRIVATE(DQ), pCcPrivKey->PriveKeyDb.Crt.dQ, keySizeWords/2 ) );
507     MBEDTLS_RSA_CHK( mbedtls_rsa_uint32_buf_to_mpi( &pCtx->MBEDTLS_PRIVATE(QP), pCcPrivKey->PriveKeyDb.Crt.qInv, keySizeWords/2 ) );
508 #endif /* MBEDTLS_RSA_NO_CRT */
509 
510 #ifdef FIPS_CERTIFICATION
511         CC_CommonReverseMemcpy( rsaKgOutParams.nModulus, (uint8_t*)pCcPubKey->n, keySizeBytes );
512         CC_CommonReverseMemcpy( rsaKgOutParams.pPrim, (uint8_t*)pKeyGenData->KGData.p, keySizeBytes/2 );
513         CC_CommonReverseMemcpy( rsaKgOutParams.qPrim, (uint8_t*)pKeyGenData->KGData.q, keySizeBytes/2 );
514         CC_CommonReverseMemcpy( rsaKgOutParams.dPrivExponent, (uint8_t*)pCcPrivKey->PriveKeyDb.NonCrt.d, keySizeBytes );
515 #endif
516 
517     End:
518     /* zeroing temp buffers  */
519     mbedtls_buff_free( pKeyGenData, sizeof( CCRsaKgData_t ) );
520     mbedtls_buff_free( pCcPrivKey,  sizeof( CCRsaPrivKey_t ) );
521     mbedtls_buff_free( pCcPubKey,   sizeof( CCRsaPubKey_t ) );
522 
523     if( err != 0 ) {
524         mbedtls_rsa_free( pCtx );
525 
526     }
527 
528     return error_mapping_cc_to_mbedtls_rsa( err, CC_RSA_OP_PUBLIC );
529 
530 }
531 
532 #endif /* MBEDTLS_GENPRIME */
533 
534 
535 /*
536  * Checks whether the context fields are set in such a way
537  * that the RSA primitives will be able to execute without error.
538  * It does *not* make guarantees for consistency of the parameters.
539  */
rsa_check_context_alt(mbedtls_rsa_context const * ctx,int is_priv,int blinding_needed)540 static int rsa_check_context_alt( mbedtls_rsa_context const *ctx, int is_priv,
541                               int blinding_needed )
542 {
543     /* blinding_needed is only used for NO_CRT to decide whether
544      * P,Q need to be present or not. In this function this variable is not used */
545     ((void) blinding_needed);
546 
547     if( ctx->MBEDTLS_PRIVATE(len) != mbedtls_mpi_size( &ctx->MBEDTLS_PRIVATE(N) ) ||
548         ctx->MBEDTLS_PRIVATE(len) > MBEDTLS_MPI_MAX_SIZE )
549     {
550         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
551     }
552 
553     /*
554      * 1. Modular exponentiation needs positive, odd moduli.
555      */
556 
557     /* Modular exponentiation wrt. N is always used for
558      * RSA public key operations. */
559     if( mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(N), 0 ) <= 0 ||
560         mbedtls_mpi_get_bit( &ctx->MBEDTLS_PRIVATE(N), 0 ) == 0  )
561     {
562         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
563     }
564 
565 #if !defined(MBEDTLS_RSA_NO_CRT)
566     /* Modular exponentiation for P and Q is only
567      * used for private key operations and if CRT
568      * is used. */
569     if( is_priv &&
570         ( mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(P), 0 ) <= 0 ||
571           mbedtls_mpi_get_bit( &ctx->MBEDTLS_PRIVATE(P), 0 ) == 0 ||
572           mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(Q), 0 ) <= 0 ||
573           mbedtls_mpi_get_bit( &ctx->MBEDTLS_PRIVATE(Q), 0 ) == 0  ) )
574     {
575         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
576     }
577 #endif /* !MBEDTLS_RSA_NO_CRT */
578 
579     /*
580      * 2. Exponents must be positive
581      */
582 
583     /* Always need E for public key operations */
584     if( mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(E), 0 ) <= 0 )
585         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
586 
587 #if defined(MBEDTLS_RSA_NO_CRT)
588     /* For private key operations, use D or DP & DQ
589      * as (unblinded) exponents. */
590     if( is_priv && mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(D), 0 ) <= 0 )
591         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
592 #else
593     if( is_priv &&
594         ( mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(DP), 0 ) <= 0 ||
595           mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(DQ), 0 ) <= 0  ) )
596     {
597         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
598     }
599 #endif /* MBEDTLS_RSA_NO_CRT */
600 
601     /* It wouldn't lead to an error if it wasn't satisfied,
602      * but check for QP >= 1 nonetheless. */
603 #if !defined(MBEDTLS_RSA_NO_CRT)
604     if( is_priv &&
605         mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(QP), 0 ) <= 0 )
606     {
607         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
608     }
609 #endif
610 
611     return( 0 );
612 }
613 
614 
615 /*
616  * Check that core RSA parameters are sane.
617  * Note: this function checks only that given combination of parameters is
618  * mathematically correct and not checks consistency and security of public/private key-pair.
619  *
620  */
mbedtls_rsa_validate_params_alt(const mbedtls_mpi * N,const mbedtls_mpi * P,const mbedtls_mpi * Q,const mbedtls_mpi * D,const mbedtls_mpi * E,int (* f_rng)(void *,unsigned char *,size_t),void * p_rng)621 int mbedtls_rsa_validate_params_alt( const mbedtls_mpi *N, const mbedtls_mpi *P,
622                                  const mbedtls_mpi *Q, const mbedtls_mpi *D,
623                                  const mbedtls_mpi *E,
624                                  int (*f_rng)(void *, unsigned char *, size_t),
625                                  void *p_rng )
626 {
627     int ret = 0;
628     mbedtls_mpi K, L;
629 
630 #if defined( MBEDTLS_GENPRIME )
631     uint32_t keySizeWords;
632     uint32_t *pTempBuff; /* temp buffer of size 3*key size in words */
633 #endif
634 
635     /* check that at least one checking operation is avaliable */
636     if( !( ( P != NULL )                           ||
637            ( Q != NULL )                           ||
638            ( N != NULL && D != NULL && E != NULL ))) {
639         ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
640     }
641 
642     /*
643      * Step 1: If PRNG provided, check that P and Q are prime
644      */
645 
646     /* get key size from existed data */
647     if ( N != NULL ) {
648         keySizeWords = mbedtls_mpi_size_in_words(N);
649     } else if ( P != NULL ) {
650         keySizeWords = 2 * mbedtls_mpi_size_in_words(P);
651     } else if ( Q != NULL ) {
652         keySizeWords = 2 * mbedtls_mpi_size_in_words(Q);
653     } else {
654         return MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
655     }
656 
657     /* allocate temp buffer */
658     if( ( pTempBuff = (uint32_t*)mbedtls_calloc( 3*keySizeWords/2, CC_32BIT_WORD_SIZE ) ) == NULL ) {
659         return  MBEDTLS_ERR_MPI_ALLOC_FAILED;
660     }
661 
662     mbedtls_mpi_init( &K );
663     mbedtls_mpi_init( &L );
664 
665 #if defined( MBEDTLS_GENPRIME )
666 
667     if( f_rng != NULL && p_rng != NULL ) {
668 
669         CCRndContext_t ccRndCtx;
670         int8_t isPrime = 0;
671         uint32_t rabinTestsCount;
672 
673         ccRndCtx.rndState = p_rng;
674         ccRndCtx.rndGenerateVectFunc = f_rng;
675         ccRndCtx.entropyCtx = NULL;
676 
677         /* Set count of R-M tests */
678         if ( keySizeWords * CC_BITS_IN_32BIT_WORD <= 1024 ) {
679             rabinTestsCount = PKA_RSA_KEY_1024_PQ_PRIME_RM_TST_COUNT;  /* 7 */
680         } else if ( keySizeWords * CC_BITS_IN_32BIT_WORD <= 2048 ) {
681             rabinTestsCount = PKA_RSA_KEY_2048_PQ_PRIME_RM_TST_COUNT;  /* 4 */;
682         } else {/* if key size > 2048 */
683             rabinTestsCount = PKA_RSA_KEY_3072_PQ_PRIME_RM_TST_COUNT;  /* 3 */;
684         }
685 
686         if( P != NULL ) {
687             ret = RsaPrimeTestCall( &ccRndCtx, &P->MBEDTLS_PRIVATE(p)[0], mbedtls_mpi_size_in_words(P),
688                                     rabinTestsCount,
689                                     &isPrime, pTempBuff/*3*modSizeWords*/,
690                                     CC_RSA_PRIME_TEST_MODE );
691             if ( ret != 0  && isPrime != 1 ) {
692                 ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
693                goto cleanup;
694             }
695         }
696         if( Q != NULL ) {
697             ret = RsaPrimeTestCall( &ccRndCtx, &Q->MBEDTLS_PRIVATE(p)[0], mbedtls_mpi_size_in_words(Q),
698                                     rabinTestsCount,
699                                     &isPrime, pTempBuff/*3*modSizeWords*/,
700                                     CC_RSA_PRIME_TEST_MODE );
701             if ( ret != 0 && isPrime != 1 ) {
702                 ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
703                 goto cleanup;
704             }
705         }
706     }
707 
708 #else
709     ((void) f_rng);
710     ((void) p_rng);
711 #endif /* MBEDTLS_GENPRIME */
712 
713     /*
714      * Step 2: Check that 1 < N = P * Q
715      */
716 
717     if( P != NULL && Q != NULL && N != NULL )
718     {
719         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, P, Q ) );
720         if( mbedtls_mpi_cmp_int( N, 1 )  <= 0 ||
721             mbedtls_mpi_cmp_mpi( &K, N ) != 0 )
722         {
723             ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
724             goto cleanup;
725         }
726     }
727 
728     /*
729      * Step 3: Check and 1 < D, E < N if present.
730      */
731 
732     if( N != NULL && D != NULL && E != NULL )
733     {
734         if ( mbedtls_mpi_cmp_int( D, 1 ) <= 0 ||
735              mbedtls_mpi_cmp_int( E, 1 ) <= 0 ||
736              mbedtls_mpi_cmp_mpi( D, N ) >= 0 ||
737              mbedtls_mpi_cmp_mpi( E, N ) >= 0 )
738         {
739             ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
740             goto cleanup;
741         }
742     }
743 
744     /*
745      * Step 4: Check that D, E are inverse modulo P-1 and Q-1
746      */
747 
748     if( P != NULL && Q != NULL && D != NULL && E != NULL )
749     {
750         if( mbedtls_mpi_cmp_int( P, 1 ) <= 0 ||
751             mbedtls_mpi_cmp_int( Q, 1 ) <= 0 )
752         {
753             ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
754             goto cleanup;
755         }
756 
757         /* Compute DE-1 mod P-1 */
758         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, D, E ) );
759         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );
760         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, P, 1 ) );
761         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, &L ) );
762         if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 )
763         {
764             ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
765             goto cleanup;
766         }
767 
768         /* Compute DE-1 mod Q-1 */
769         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, D, E ) );
770         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );
771         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &L, Q, 1 ) );
772         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, &L ) );
773         if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 )
774         {
775             ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
776             goto cleanup;
777         }
778     }
779 
780 cleanup:
781 
782 #if defined( MBEDTLS_GENPRIME )
783     mbedtls_rsa_zeroize( pTempBuff, 3*keySizeWords*CC_32BIT_WORD_SIZE/2 );
784     mbedtls_free( pTempBuff );
785 #endif
786     mbedtls_mpi_free( &K );
787     mbedtls_mpi_free( &L );
788 
789     /* Wrap MPI error codes by RSA check failure error code */
790     if( ret != 0 && ret != MBEDTLS_ERR_RSA_KEY_CHECK_FAILED )
791     {
792         ret += MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
793     }
794 
795     return( ret );
796 }
797 
798 #if !defined MBEDTLS_RSA_NO_CRT
799 /*
800  * Check that RSA CRT parameters are in accordance with core parameters.
801  */
mbedtls_rsa_validate_crt_alt(const mbedtls_mpi * P,const mbedtls_mpi * Q,const mbedtls_mpi * D,const mbedtls_mpi * DP,const mbedtls_mpi * DQ,const mbedtls_mpi * QP)802 static int mbedtls_rsa_validate_crt_alt( const mbedtls_mpi *P,  const mbedtls_mpi *Q,
803                               const mbedtls_mpi *D,  const mbedtls_mpi *DP,
804                               const mbedtls_mpi *DQ, const mbedtls_mpi *QP )
805 {
806     int ret = 0;
807 
808     mbedtls_mpi K, L;
809     mbedtls_mpi_init( &K );
810     mbedtls_mpi_init( &L );
811 
812     /* Check that DP - D == 0 mod P - 1 */
813     if( DP != NULL )
814     {
815         if( P == NULL )
816         {
817             ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
818             goto cleanup;
819         }
820 
821         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, P, 1 ) );
822         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &L, DP, D ) );
823         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &L, &L, &K ) );
824 
825         if( mbedtls_mpi_cmp_int( &L, 0 ) != 0 )
826         {
827             ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
828             goto cleanup;
829         }
830     }
831 
832     /* Check that DQ - D == 0 mod Q - 1 */
833     if( DQ != NULL )
834     {
835         if( Q == NULL )
836         {
837             ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
838             goto cleanup;
839         }
840 
841         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, Q, 1 ) );
842         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_mpi( &L, DQ, D ) );
843         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &L, &L, &K ) );
844 
845         if( mbedtls_mpi_cmp_int( &L, 0 ) != 0 )
846         {
847             ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
848             goto cleanup;
849         }
850     }
851 
852     /* Check that QP * Q - 1 == 0 mod P */
853     if( QP != NULL )
854     {
855         if( P == NULL || Q == NULL )
856         {
857             ret = MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
858             goto cleanup;
859         }
860 
861         MBEDTLS_MPI_CHK( mbedtls_mpi_mul_mpi( &K, QP, Q ) );
862         MBEDTLS_MPI_CHK( mbedtls_mpi_sub_int( &K, &K, 1 ) );
863         MBEDTLS_MPI_CHK( mbedtls_mpi_mod_mpi( &K, &K, P ) );
864         if( mbedtls_mpi_cmp_int( &K, 0 ) != 0 )
865         {
866             ret = MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
867             goto cleanup;
868         }
869     }
870 
871 cleanup:
872 
873     /* Wrap MPI error codes by RSA check failure error code */
874     if( ret != 0 &&
875         ret != MBEDTLS_ERR_RSA_KEY_CHECK_FAILED &&
876         ret != MBEDTLS_ERR_RSA_BAD_INPUT_DATA )
877     {
878         ret += MBEDTLS_ERR_RSA_KEY_CHECK_FAILED;
879     }
880 
881     mbedtls_mpi_free( &K );
882     mbedtls_mpi_free( &L );
883 
884     return( ret );
885 }
886 #endif
887 
888 /*
889  * Check a public RSA key
890  */
mbedtls_rsa_check_pubkey(const mbedtls_rsa_context * ctx)891 int mbedtls_rsa_check_pubkey( const mbedtls_rsa_context *ctx )
892 {
893     if( ctx == NULL || !ctx->MBEDTLS_PRIVATE(N).MBEDTLS_PRIVATE(p) || ( ctx->MBEDTLS_PRIVATE(N).MBEDTLS_PRIVATE(s) != 1 ) || !ctx->MBEDTLS_PRIVATE(E).MBEDTLS_PRIVATE(p) || ( ctx->MBEDTLS_PRIVATE(E).MBEDTLS_PRIVATE(s) != 1 ) )
894         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
895 
896     /* check oddness */
897     if( ( ctx->MBEDTLS_PRIVATE(N).MBEDTLS_PRIVATE(p)[0] & 1 ) == 0 ||
898         ( ctx->MBEDTLS_PRIVATE(E).MBEDTLS_PRIVATE(p)[0] & 1 ) == 0 )
899           return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED);
900 
901     if( mbedtls_mpi_bitlen( &ctx->MBEDTLS_PRIVATE(N) ) < MBEDTLS_RSA_MIN_VALID_KEY_SIZE_VALUE_IN_BITS ||
902         mbedtls_mpi_bitlen( &ctx->MBEDTLS_PRIVATE(N) ) > MBEDTLS_RSA_MAX_VALID_KEY_SIZE_VALUE_IN_BITS )
903         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
904 
905 
906     if( mbedtls_mpi_bitlen( &ctx->MBEDTLS_PRIVATE(E) ) < 2 ||
907         mbedtls_mpi_cmp_mpi( &ctx->MBEDTLS_PRIVATE(E), &ctx->MBEDTLS_PRIVATE(N) ) >= 0 )
908         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
909 
910     return( 0 );
911 }
912 
913 
914 /*
915  * Check for the consistency of all fields in an RSA private key context
916  */
mbedtls_rsa_check_privkey(const mbedtls_rsa_context * ctx)917 int mbedtls_rsa_check_privkey( const mbedtls_rsa_context *ctx )
918 {
919     if( ctx == NULL )
920         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
921 
922     if( mbedtls_rsa_check_pubkey( ctx ) != 0 )
923     {
924         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
925     }
926 
927     if( rsa_check_context_alt( ctx, 1 /* private */, 1 /* blinding */ ) != 0 )
928     {
929         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
930     }
931 
932     if( mbedtls_rsa_validate_params_alt( &ctx->MBEDTLS_PRIVATE(N), &ctx->MBEDTLS_PRIVATE(P), &ctx->MBEDTLS_PRIVATE(Q),
933                                          &ctx->MBEDTLS_PRIVATE(D), &ctx->MBEDTLS_PRIVATE(E), NULL, NULL ) != 0 )
934     {
935         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
936     }
937 
938 #if !defined(MBEDTLS_RSA_NO_CRT)
939     if( mbedtls_rsa_validate_crt_alt( &ctx->MBEDTLS_PRIVATE(P), &ctx->MBEDTLS_PRIVATE(Q), &ctx->MBEDTLS_PRIVATE(D),
940                                       &ctx->MBEDTLS_PRIVATE(DP), &ctx->MBEDTLS_PRIVATE(DQ), &ctx->MBEDTLS_PRIVATE(QP) ) != 0 )
941     {
942         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
943     }
944 #endif
945 
946     return( 0 );
947 }
948 
949 /*
950  * Check if contexts holding a public and private key match
951  */
mbedtls_rsa_check_pub_priv(const mbedtls_rsa_context * pub,const mbedtls_rsa_context * prv)952 int mbedtls_rsa_check_pub_priv( const mbedtls_rsa_context *pub, const mbedtls_rsa_context *prv )
953 {
954     if( mbedtls_rsa_check_pubkey( pub ) != 0 ||
955         mbedtls_rsa_check_privkey( prv ) != 0 )
956     {
957         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
958     }
959 
960     if( mbedtls_mpi_cmp_mpi( &pub->MBEDTLS_PRIVATE(N), &prv->MBEDTLS_PRIVATE(N) ) != 0 ||
961         mbedtls_mpi_cmp_mpi( &pub->MBEDTLS_PRIVATE(E), &prv->MBEDTLS_PRIVATE(E) ) != 0 )
962     {
963         return( MBEDTLS_ERR_RSA_KEY_CHECK_FAILED );
964     }
965 
966     return( 0 );
967 }
968 
969 
convert_mbedtls_md_type_to_cc_rsa_hash_opmode(IN mbedtls_md_type_t mdType,IN int isRsaHashModeAfter,OUT CCRsaHashOpMode_t * hashOpMode,OUT size_t * hashOutputSizeBytes)970 static CCError_t convert_mbedtls_md_type_to_cc_rsa_hash_opmode(IN mbedtls_md_type_t mdType,
971                                                     IN  int isRsaHashModeAfter,
972                                                     OUT CCRsaHashOpMode_t * hashOpMode,
973                                                     OUT size_t * hashOutputSizeBytes)
974 {
975     switch (mdType)
976     {
977         case MBEDTLS_MD_MD5 :
978             /*MD5 is not recommended in PKCS1 ver 2.1 standard, hence it is not supported*/
979             return CC_RSA_HASH_ILLEGAL_OPERATION_MODE_ERROR;
980         case MBEDTLS_MD_SHA1:
981             *hashOpMode = CC_RSA_HASH_SHA1_mode;/*changing the hash mode to CC definition*/
982             *hashOutputSizeBytes = CC_HASH_SHA1_DIGEST_SIZE_IN_BYTES;
983             break;
984         case MBEDTLS_MD_SHA224:
985             *hashOpMode = CC_RSA_HASH_SHA224_mode;
986             *hashOutputSizeBytes = CC_HASH_SHA224_DIGEST_SIZE_IN_BYTES;
987             break;
988         case MBEDTLS_MD_SHA256:
989             *hashOpMode = CC_RSA_HASH_SHA256_mode;
990             *hashOutputSizeBytes = CC_HASH_SHA256_DIGEST_SIZE_IN_BYTES;
991             break;
992         case MBEDTLS_MD_SHA384:
993             *hashOpMode = CC_RSA_HASH_SHA384_mode;
994             *hashOutputSizeBytes = CC_HASH_SHA384_DIGEST_SIZE_IN_BYTES;
995             break;
996         case MBEDTLS_MD_SHA512:
997             *hashOpMode = CC_RSA_HASH_SHA512_mode;
998             *hashOutputSizeBytes = CC_HASH_SHA512_DIGEST_SIZE_IN_BYTES;
999             break;
1000         default:
1001             return CC_RSA_HASH_ILLEGAL_OPERATION_MODE_ERROR;
1002     }
1003     if (isRsaHashModeAfter)
1004     {
1005         *hashOpMode += CC_RSA_After_MD5_mode;
1006 
1007     }
1008     return CC_OK;
1009 }
1010 
validate_mbedtls_rsa_context_private_key(mbedtls_rsa_context * ctx)1011 static CCError_t validate_mbedtls_rsa_context_private_key(mbedtls_rsa_context * ctx)
1012 {
1013     CCError_t Error = CC_OK;
1014 
1015     if (ctx == NULL)
1016     {
1017         GOTO_END( CC_RSA_INVALID_PRIV_KEY_STRUCT_POINTER_ERROR );
1018     }
1019 
1020     if (ctx->MBEDTLS_PRIVATE(N).MBEDTLS_PRIVATE(p) == NULL)
1021     {
1022         GOTO_END( CC_RSA_INVALID_MODULUS_POINTER_ERROR );
1023     }
1024 
1025     if (ctx->MBEDTLS_PRIVATE(len) == 0)
1026     {
1027         GOTO_END( CC_RSA_INVALID_MODULUS_SIZE );
1028     }
1029 
1030 #if defined(MBEDTLS_RSA_NO_CRT)
1031     if (ctx->MBEDTLS_PRIVATE(D).MBEDTLS_PRIVATE(p) == NULL)
1032     {
1033         GOTO_END( CC_RSA_INVALID_EXPONENT_POINTER_ERROR );
1034     }
1035 #else
1036     if (ctx->MBEDTLS_PRIVATE(P).MBEDTLS_PRIVATE(p) == NULL)
1037         GOTO_END( CC_RSA_INVALID_CRT_FIRST_FACTOR_POINTER_ERROR );
1038 
1039     if (ctx->MBEDTLS_PRIVATE(Q).MBEDTLS_PRIVATE(p) == NULL)
1040         GOTO_END( CC_RSA_INVALID_CRT_SECOND_FACTOR_POINTER_ERROR );
1041 
1042     if (ctx->MBEDTLS_PRIVATE(DP).MBEDTLS_PRIVATE(p) == NULL)
1043         GOTO_END( CC_RSA_INVALID_CRT_FIRST_FACTOR_EXP_PTR_ERROR );
1044 
1045     if (ctx->MBEDTLS_PRIVATE(DQ).MBEDTLS_PRIVATE(p) == NULL)
1046         GOTO_END( CC_RSA_INVALID_CRT_SECOND_FACTOR_EXP_PTR_ERROR );
1047 
1048     if (ctx->MBEDTLS_PRIVATE(QP).MBEDTLS_PRIVATE(p) == NULL)
1049         GOTO_END( CC_RSA_INVALID_CRT_COEFFICIENT_PTR_ERROR );
1050 
1051 #endif
1052 
1053 End:
1054     return Error;
1055 }
1056 
validate_mbedtls_rsa_context_public_key(mbedtls_rsa_context * ctx)1057 static CCError_t validate_mbedtls_rsa_context_public_key(mbedtls_rsa_context * ctx)
1058 {
1059     CCError_t Error = CC_OK;
1060 
1061     if (ctx == NULL)
1062     {
1063         GOTO_END( CC_RSA_INVALID_PRIV_KEY_STRUCT_POINTER_ERROR );
1064     }
1065 
1066     /* ...... checking the validity of the exponent pointer ............... */
1067     if (ctx->MBEDTLS_PRIVATE(E).MBEDTLS_PRIVATE(p) == NULL)
1068         GOTO_END( CC_RSA_INVALID_EXPONENT_POINTER_ERROR );
1069 
1070     /* ...... checking the validity of the modulus pointer .............. */
1071     if (ctx->MBEDTLS_PRIVATE(N).MBEDTLS_PRIVATE(p) == NULL)
1072         GOTO_END( CC_RSA_INVALID_MODULUS_POINTER_ERROR );
1073 
1074     if (ctx->MBEDTLS_PRIVATE(len) == 0)
1075     {
1076         GOTO_END( CC_RSA_INVALID_MODULUS_SIZE );
1077     }
1078 
1079 End:
1080     return Error;
1081 }
1082 
1083 #if defined(MBEDTLS_RSA_NO_CRT)
build_cc_priv_non_crt_key(IN mbedtls_rsa_context * ctx,OUT CCRsaUserPrivKey_t * UserPrivKey_ptr)1084 static CCError_t build_cc_priv_non_crt_key(
1085         IN mbedtls_rsa_context *ctx,
1086         OUT CCRsaUserPrivKey_t *UserPrivKey_ptr
1087         )
1088 {
1089     /* FUNCTION DECLARATIONS */
1090 
1091     /* the counter compare result */
1092     CCCommonCmpCounter_t CounterCmpResult;
1093 
1094     /* the size in bytes of the modulus buffer from mbedtls_rsa_ctx*/
1095     size_t ModulusSize;
1096 
1097     /* the effective size in bits of the modulus buffer */
1098     uint32_t ModulusEffectiveSizeInBits;
1099 
1100     /* the size in bytes of the exponent buffers (private and public) from mbedtls_rsa_ctx*/
1101     size_t PrivExponentSize, PubExponentSize;
1102 
1103     /* the effective sizes in bits of the private and public exponents */
1104     uint32_t PrivExponentEffectiveSizeInBits, PubExponentEffectiveSizeInBits;
1105 
1106     /* the private key database pointer */
1107     CCRsaPrivKey_t *PrivKey_ptr;
1108 
1109     /* the Error return code identifier */
1110     CCError_t Error = CC_OK;
1111 
1112     /* FUNCTION LOGIC */
1113 
1114     /* ................. checking the validity of the pointer arguments ....... */
1115     /* ------------------------------------------------------------------------ */
1116     CHECK_AND_RETURN_ERR_UPON_FIPS_ERROR();
1117     ModulusSize = mbedtls_mpi_size(&ctx->MBEDTLS_PRIVATE(N));
1118     PubExponentSize = mbedtls_mpi_size(&ctx->MBEDTLS_PRIVATE(E));
1119     PrivExponentSize = mbedtls_mpi_size(&ctx->MBEDTLS_PRIVATE(D));
1120 
1121     /* ...... checking the validity of the modulus size, private exponent can not be more than 256 bytes .............. */
1122     if (ModulusSize > CC_RSA_MAX_VALID_KEY_SIZE_VALUE_IN_BYTES)
1123         GOTO_END(CC_RSA_INVALID_MODULUS_SIZE);
1124 
1125     if (PrivExponentSize > CC_RSA_MAX_VALID_KEY_SIZE_VALUE_IN_BYTES)
1126         GOTO_END(CC_RSA_INVALID_EXPONENT_SIZE);
1127 
1128     if (PubExponentSize > CC_RSA_MAX_VALID_KEY_SIZE_VALUE_IN_BYTES)
1129         GOTO_END(CC_RSA_INVALID_EXPONENT_SIZE);
1130 
1131     /* .................. copy the buffers to the key handle structure .... */
1132     /* -------------------------------------------------------------------- */
1133 
1134     /* setting the pointer to the key database */
1135     PrivKey_ptr = (CCRsaPrivKey_t *)UserPrivKey_ptr->PrivateKeyDbBuff;
1136 
1137 
1138     /* clear the private key db */
1139     CC_PalMemSetZero(PrivKey_ptr, sizeof(CCRsaPrivKey_t));
1140 
1141     CC_PalMemCopy(PrivKey_ptr->n, ctx->MBEDTLS_PRIVATE(N).MBEDTLS_PRIVATE(p), ModulusSize);
1142     CC_PalMemCopy(PrivKey_ptr->PriveKeyDb.NonCrt.d, ctx->MBEDTLS_PRIVATE(D).MBEDTLS_PRIVATE(p), PrivExponentSize);
1143 
1144     /* .................. initializing local variables ................... */
1145     /* ------------------------------------------------------------------- */
1146 
1147     /* .......... initializing the effective counters size in bits .......... */
1148     ModulusEffectiveSizeInBits =
1149         CC_CommonGetWordsCounterEffectiveSizeInBits(PrivKey_ptr->n, (ModulusSize + 3)/4);
1150     PrivExponentEffectiveSizeInBits =
1151         CC_CommonGetWordsCounterEffectiveSizeInBits(PrivKey_ptr->PriveKeyDb.NonCrt.d, (PrivExponentSize + 3) / 4);
1152 
1153     /*  checking the size of the modulus  */
1154     if ( ( ModulusEffectiveSizeInBits < CC_RSA_MIN_VALID_KEY_SIZE_VALUE_IN_BITS ) ||
1155             ( ModulusEffectiveSizeInBits > CC_RSA_MAX_VALID_KEY_SIZE_VALUE_IN_BITS ) ||
1156             ( ModulusEffectiveSizeInBits % CC_RSA_VALID_KEY_SIZE_MULTIPLE_VALUE_IN_BITS ) ) {
1157         GOTO_CLEANUP(CC_RSA_INVALID_MODULUS_SIZE);
1158     }
1159 
1160     /*  verifying the modulus is odd  */
1161     if ( (PrivKey_ptr->n[0] & 1UL) == 0 ) {
1162         GOTO_CLEANUP(CC_RSA_MODULUS_EVEN_ERROR);
1163     }
1164 
1165     /*  checking the priv. exponent size is not 0 in bytes */
1166     if ( PrivExponentEffectiveSizeInBits == 0 ) {
1167         GOTO_CLEANUP(CC_RSA_INVALID_EXPONENT_SIZE);
1168     }
1169 
1170     /* verifying the priv. exponent is less then the modulus */
1171     CounterCmpResult =
1172         CC_CommonCmpLsWordsUnsignedCounters(PrivKey_ptr->PriveKeyDb.NonCrt.d, (PrivExponentSize+3)/4,
1173                 PrivKey_ptr->n, (ModulusSize+3)/4);
1174 
1175     if ( CounterCmpResult != CC_COMMON_CmpCounter2GreaterThenCounter1 ) {
1176         GOTO_CLEANUP(CC_RSA_INVALID_EXPONENT_VAL);
1177     }
1178 
1179     /* verifying the priv. exponent is not less then 1 */
1180     if ( PrivExponentEffectiveSizeInBits < 32 &&
1181             PrivKey_ptr->PriveKeyDb.NonCrt.d[0] < CC_RSA_MIN_PRIV_EXP_VALUE ) {
1182         GOTO_CLEANUP(CC_RSA_INVALID_EXPONENT_VAL);
1183     }
1184 
1185     /*  checking that the public exponent is an integer between 3 and modulus - 1 */
1186     if ( ctx->MBEDTLS_PRIVATE(E).MBEDTLS_PRIVATE(p) != NULL ) {
1187         CC_PalMemCopy(PrivKey_ptr->PriveKeyDb.NonCrt.e, ctx->MBEDTLS_PRIVATE(E).MBEDTLS_PRIVATE(p), PubExponentSize);
1188         PubExponentEffectiveSizeInBits =
1189             CC_CommonGetWordsCounterEffectiveSizeInBits(PrivKey_ptr->PriveKeyDb.NonCrt.e, (PubExponentSize+3)/4);
1190 
1191         /* verifying that the exponent is not less than 3 */
1192         if (PubExponentEffectiveSizeInBits < 32 &&
1193                 PrivKey_ptr->PriveKeyDb.NonCrt.e[0] < CC_RSA_MIN_PUB_EXP_VALUE) {
1194             GOTO_CLEANUP(CC_RSA_INVALID_EXPONENT_VAL);
1195         }
1196 
1197         /* verifying that the public exponent is less than the modulus */
1198         CounterCmpResult =
1199             CC_CommonCmpLsWordsUnsignedCounters(PrivKey_ptr->PriveKeyDb.NonCrt.e, (PubExponentSize+3)/4,
1200                     PrivKey_ptr->n, (ModulusSize+3)/4);
1201 
1202         if (CounterCmpResult != CC_COMMON_CmpCounter2GreaterThenCounter1) {
1203             GOTO_CLEANUP(CC_RSA_INVALID_EXPONENT_VAL);
1204         }
1205     } else {
1206         PubExponentEffectiveSizeInBits = 0;
1207     }
1208 
1209 
1210     /* ................. building the structure ............................. */
1211     /* ---------------------------------------------------------------------- */
1212 
1213     /* set the mode to non CRT mode */
1214     PrivKey_ptr->OperationMode = CC_RSA_NoCrt;
1215 
1216     /* set the key source as external */
1217     PrivKey_ptr->KeySource = CC_RSA_ExternalKey;
1218 
1219     /* setting the modulus and exponent size in bits */
1220     PrivKey_ptr->nSizeInBits                   = ModulusEffectiveSizeInBits;
1221     PrivKey_ptr->PriveKeyDb.NonCrt.dSizeInBits = PrivExponentEffectiveSizeInBits;
1222     PrivKey_ptr->PriveKeyDb.NonCrt.eSizeInBits = PubExponentEffectiveSizeInBits;
1223 
1224     /* ................ calculate the Barret tag .............. */
1225     Error = RsaInitPrivKeyDb(PrivKey_ptr);
1226 
1227     if ( Error != CC_OK ) {
1228         GOTO_CLEANUP(CC_RSA_INTERNAL_ERROR);
1229     }
1230 
1231     /* ................ set the tag ................ */
1232     UserPrivKey_ptr->valid_tag = CC_RSA_PRIV_KEY_VALIDATION_TAG;
1233 
1234     /* ................. end of the function .................................. */
1235     /* ------------------------------------------------------------------------ */
1236 Cleanup:
1237     /* if the structure created is not valid - clear it */
1238     if ( Error != CC_OK ) {
1239         CC_PalMemSetZero(UserPrivKey_ptr, sizeof(CCRsaUserPrivKey_t));
1240     }
1241 End:
1242     return Error;
1243 
1244 }
1245 
1246 #else // !defined(MBEDTLS_RSA_NO_CRT)
build_cc_priv_crt_key(IN mbedtls_rsa_context * ctx,OUT CCRsaUserPrivKey_t * UserPrivKey_ptr)1247 static CCError_t build_cc_priv_crt_key(
1248         IN mbedtls_rsa_context *ctx,
1249         OUT CCRsaUserPrivKey_t *UserPrivKey_ptr
1250         )
1251 {
1252     /* FUNCTION DECLARATIONS */
1253 
1254     /* the counter compare result */
1255     CCCommonCmpCounter_t CounterCmpResult;
1256 
1257     /* the size in bytes of the modulus buffer from mbedtls_rsa_ctx*/
1258     size_t ModulusSize;
1259 
1260     /* the effective size in bits of the modulus buffer */
1261     uint32_t ModulusEffectiveSizeInBits;
1262 
1263     /* the size in bytes of the exponent buffers (private and public) from mbedtls_rsa_ctx*/
1264     //size_t PrivExponentSize, PubExponentSize;
1265     size_t   PSize;
1266     size_t   QSize;
1267     size_t   dPSize;
1268     size_t   dQSize;
1269     size_t   qInvSize;
1270 
1271     /* the effective size in bits of the modulus factors buffer */
1272     uint32_t P_EffectiveSizeInBits;
1273     uint32_t Q_EffectiveSizeInBits;
1274     uint32_t dP_EffectiveSizeInBits;
1275     uint32_t dQ_EffectiveSizeInBits;
1276     uint32_t qInv_EffectiveSizeInBits;
1277 
1278     /* the private key database pointer */
1279     CCRsaPrivKey_t *PrivKey_ptr;
1280 
1281     /* the Error return code identifier */
1282     CCError_t Error = CC_OK;
1283 
1284     /* FUNCTION LOGIC */
1285 
1286     /* ................. checking the validity of the pointer arguments ....... */
1287     /* ------------------------------------------------------------------------ */
1288     CHECK_AND_RETURN_ERR_UPON_FIPS_ERROR();
1289     PSize    = mbedtls_mpi_size(&ctx->MBEDTLS_PRIVATE(P));
1290     QSize    = mbedtls_mpi_size(&ctx->MBEDTLS_PRIVATE(Q));
1291     dPSize   = mbedtls_mpi_size(&ctx->MBEDTLS_PRIVATE(DP));
1292     dQSize   = mbedtls_mpi_size(&ctx->MBEDTLS_PRIVATE(DQ));
1293     qInvSize = mbedtls_mpi_size(&ctx->MBEDTLS_PRIVATE(QP));
1294     ModulusSize = mbedtls_mpi_size(&ctx->MBEDTLS_PRIVATE(N));
1295 
1296 
1297     /* checking the input sizes */
1298     if (PSize > CC_RSA_MAX_VALID_KEY_SIZE_VALUE_IN_BYTES/2 ||
1299             QSize > CC_RSA_MAX_VALID_KEY_SIZE_VALUE_IN_BYTES/2) {
1300         GOTO_END(CC_RSA_INVALID_CRT_PARAMETR_SIZE_ERROR);
1301     }
1302 
1303     if (dPSize > PSize ||
1304             dQSize > QSize ||
1305             qInvSize > PSize) {
1306         GOTO_END(CC_RSA_INVALID_CRT_PARAMETR_SIZE_ERROR);
1307     }
1308 
1309     /* verifying the first factor exponent is less then the first factor */
1310     CounterCmpResult =
1311         CC_CommonCmpLsWordsUnsignedCounters(ctx->MBEDTLS_PRIVATE(DP).MBEDTLS_PRIVATE(p), mbedtls_mpi_size_in_words(&ctx->MBEDTLS_PRIVATE(DP)), ctx->MBEDTLS_PRIVATE(P).MBEDTLS_PRIVATE(p), mbedtls_mpi_size_in_words(&ctx->MBEDTLS_PRIVATE(P)));
1312 
1313     if (CounterCmpResult != CC_COMMON_CmpCounter2GreaterThenCounter1) {
1314         GOTO_END(CC_RSA_INVALID_CRT_FIRST_FACTOR_EXPONENT_VAL);
1315     }
1316 
1317     /* verifying the second factor exponent is less then the second factor */
1318     CounterCmpResult =
1319         CC_CommonCmpLsWordsUnsignedCounters(ctx->MBEDTLS_PRIVATE(DQ).MBEDTLS_PRIVATE(p), mbedtls_mpi_size_in_words(&ctx->MBEDTLS_PRIVATE(DQ)), ctx->MBEDTLS_PRIVATE(Q).MBEDTLS_PRIVATE(p), mbedtls_mpi_size_in_words(&ctx->MBEDTLS_PRIVATE(Q)));
1320 
1321     if (CounterCmpResult != CC_COMMON_CmpCounter2GreaterThenCounter1) {
1322         GOTO_END(CC_RSA_INVALID_CRT_SECOND_FACTOR_EXPONENT_VAL);
1323     }
1324 
1325     /* verifying the CRT coefficient is less then the first factor */
1326     CounterCmpResult =
1327         CC_CommonCmpLsWordsUnsignedCounters(ctx->MBEDTLS_PRIVATE(QP).MBEDTLS_PRIVATE(p), mbedtls_mpi_size_in_words(&ctx->MBEDTLS_PRIVATE(QP)), ctx->MBEDTLS_PRIVATE(P).MBEDTLS_PRIVATE(p), mbedtls_mpi_size_in_words(&ctx->MBEDTLS_PRIVATE(P)));
1328 
1329     if (CounterCmpResult != CC_COMMON_CmpCounter2GreaterThenCounter1) {
1330         GOTO_END(CC_RSA_INVALID_CRT_COEFF_VAL);
1331     }
1332 
1333     /* .................. copy the buffers to the key handle structure .... */
1334     /* -------------------------------------------------------------------- */
1335 
1336     /* setting the pointer to the key database */
1337     PrivKey_ptr = (CCRsaPrivKey_t *)UserPrivKey_ptr->PrivateKeyDbBuff;
1338 
1339 
1340     /* clear the private key db */
1341     CC_PalMemSetZero(PrivKey_ptr, sizeof(CCRsaPrivKey_t));
1342 
1343     CC_PalMemCopy(PrivKey_ptr->PriveKeyDb.Crt.P, ctx->MBEDTLS_PRIVATE(P).MBEDTLS_PRIVATE(p), PSize);
1344     CC_PalMemCopy(PrivKey_ptr->PriveKeyDb.Crt.Q, ctx->MBEDTLS_PRIVATE(Q).MBEDTLS_PRIVATE(p), QSize);
1345     CC_PalMemCopy(PrivKey_ptr->PriveKeyDb.Crt.dP, ctx->MBEDTLS_PRIVATE(DP).MBEDTLS_PRIVATE(p), dPSize);
1346     CC_PalMemCopy(PrivKey_ptr->PriveKeyDb.Crt.dQ, ctx->MBEDTLS_PRIVATE(DQ).MBEDTLS_PRIVATE(p), dQSize);
1347     CC_PalMemCopy(PrivKey_ptr->PriveKeyDb.Crt.qInv, ctx->MBEDTLS_PRIVATE(QP).MBEDTLS_PRIVATE(p), qInvSize);
1348 
1349     /* .................. initializing local variables ................... */
1350     /* ------------------------------------------------------------------- */
1351 
1352     /* .......... initializing the effective counters size in bits .......... */
1353     /* initializing the effective counters size in bits */
1354     P_EffectiveSizeInBits =
1355         CC_CommonGetWordsCounterEffectiveSizeInBits(PrivKey_ptr->PriveKeyDb.Crt.P, (PSize+3)/4);
1356 
1357     Q_EffectiveSizeInBits =
1358         CC_CommonGetWordsCounterEffectiveSizeInBits(PrivKey_ptr->PriveKeyDb.Crt.Q, (QSize+3)/4);
1359 
1360     dP_EffectiveSizeInBits =
1361         CC_CommonGetWordsCounterEffectiveSizeInBits(PrivKey_ptr->PriveKeyDb.Crt.dP, (dPSize+3)/4);
1362 
1363     dQ_EffectiveSizeInBits =
1364         CC_CommonGetWordsCounterEffectiveSizeInBits(PrivKey_ptr->PriveKeyDb.Crt.dQ, (dQSize+3)/4);
1365 
1366     qInv_EffectiveSizeInBits =
1367         CC_CommonGetWordsCounterEffectiveSizeInBits(PrivKey_ptr->PriveKeyDb.Crt.qInv, (qInvSize+3)/4);
1368 
1369 
1370     /*  the first factor size is not 0 in bits */
1371     if (P_EffectiveSizeInBits == 0|| P_EffectiveSizeInBits > 8*PSize) {
1372         GOTO_CLEANUP(CC_RSA_INVALID_CRT_FIRST_FACTOR_SIZE);
1373     }
1374 
1375     /* the second factor size is not 0 in bits */
1376     if (Q_EffectiveSizeInBits == 0 || Q_EffectiveSizeInBits > 8*QSize) {
1377         GOTO_CLEANUP(CC_RSA_INVALID_CRT_SECOND_FACTOR_SIZE);
1378     }
1379 
1380     /* checking that sizes of dP, dQ, qInv > 0 */
1381     if (dP_EffectiveSizeInBits == 0 || dQ_EffectiveSizeInBits == 0 || qInv_EffectiveSizeInBits == 0) {
1382         GOTO_CLEANUP(CC_RSA_INVALID_CRT_PARAMETR_SIZE_ERROR);
1383     }
1384 
1385 
1386     // The following code is copied from cc_rsa_build.c
1387     // For now we don't need as mbedtls_rsa_context contains n
1388     // In case this'll change, the code should be used.
1389 #ifdef MBEDTLS_RSA_PRIVATE_KEY_OPTIMIZED_IMPLEMENTATION
1390     /* ............... calculate the modulus N ........................... */
1391     /* -------------------------------------------------------------------- */
1392 
1393 
1394     Error = PkiLongNumMul(PrivKey_ptr->PriveKeyDb.Crt.P, P_EffectiveSizeInBits,
1395             PrivKey_ptr->PriveKeyDb.Crt.Q, PrivKey_ptr->n);
1396     if ( Error != CC_OK ) {
1397         GOTO_CLEANUP(CC_RSA_INTERNAL_ERROR);
1398     }
1399 #else
1400     CC_PalMemCopy(PrivKey_ptr->n, ctx->MBEDTLS_PRIVATE(N).MBEDTLS_PRIVATE(p), ModulusSize);
1401 #endif
1402 
1403     ModulusEffectiveSizeInBits =
1404         CC_CommonGetWordsCounterEffectiveSizeInBits(PrivKey_ptr->n, (2*CALC_FULL_32BIT_WORDS(P_EffectiveSizeInBits)));
1405 
1406     /* .................. checking the validity of the counters ............... */
1407     /* ------------------------------------------------------------------------ */
1408 
1409     /*  checking the size of the modulus  */
1410     if ( ( ModulusEffectiveSizeInBits < CC_RSA_MIN_VALID_KEY_SIZE_VALUE_IN_BITS ) ||
1411             ( ModulusEffectiveSizeInBits > CC_RSA_MAX_VALID_KEY_SIZE_VALUE_IN_BITS ) ||
1412             ( ModulusEffectiveSizeInBits % CC_RSA_VALID_KEY_SIZE_MULTIPLE_VALUE_IN_BITS ) ) {
1413         GOTO_CLEANUP(CC_RSA_INVALID_MODULUS_SIZE);
1414     }
1415 
1416     /*  verifying the modulus is odd  */
1417     if ((PrivKey_ptr->n[0] & 1UL) == 0) {
1418         GOTO_CLEANUP(CC_RSA_MODULUS_EVEN_ERROR);
1419     }
1420 
1421     if ((P_EffectiveSizeInBits + Q_EffectiveSizeInBits != ModulusEffectiveSizeInBits) &&
1422             (P_EffectiveSizeInBits + Q_EffectiveSizeInBits != ModulusEffectiveSizeInBits - 1)) {
1423         GOTO_CLEANUP(CC_RSA_INVALID_CRT_FIRST_AND_SECOND_FACTOR_SIZE);
1424     }
1425 
1426 
1427     /* ................. building the structure ............................. */
1428     /* ---------------------------------------------------------------------- */
1429 
1430     /* set the mode to non CRT mode */
1431     PrivKey_ptr->OperationMode = CC_RSA_Crt;
1432 
1433     /* set the key source as external */
1434     PrivKey_ptr->KeySource = CC_RSA_ExternalKey;
1435 
1436     /* loading to structure the buffer sizes... */
1437 
1438     PrivKey_ptr->PriveKeyDb.Crt.PSizeInBits    = P_EffectiveSizeInBits;
1439     PrivKey_ptr->PriveKeyDb.Crt.QSizeInBits    = Q_EffectiveSizeInBits;
1440     PrivKey_ptr->PriveKeyDb.Crt.dPSizeInBits   = dP_EffectiveSizeInBits;
1441     PrivKey_ptr->PriveKeyDb.Crt.dQSizeInBits   = dQ_EffectiveSizeInBits;
1442     PrivKey_ptr->PriveKeyDb.Crt.qInvSizeInBits = qInv_EffectiveSizeInBits;
1443     PrivKey_ptr->nSizeInBits = ModulusEffectiveSizeInBits;
1444 
1445     /* ................ initialize the low level data .............. */
1446     Error = RsaInitPrivKeyDb(PrivKey_ptr);
1447 
1448     if (Error) {
1449         GOTO_CLEANUP(CC_RSA_INTERNAL_ERROR);
1450     }
1451 
1452     /* ................ set the tag ................ */
1453     UserPrivKey_ptr->valid_tag = CC_RSA_PRIV_KEY_VALIDATION_TAG;
1454 
1455     /* ................. end of the function .................................. */
1456     /* ------------------------------------------------------------------------ */
1457 Cleanup:
1458     /* if the structure created is not valid - clear it */
1459     if ( Error != CC_OK ) {
1460         CC_PalMemSetZero(UserPrivKey_ptr, sizeof(CCRsaUserPrivKey_t));
1461     }
1462 End:
1463     return Error;
1464 
1465 }
1466 #endif
1467 
build_cc_pubkey(IN mbedtls_rsa_context * ctx,OUT CCRsaUserPubKey_t * UserPubKey_ptr)1468 static CCError_t build_cc_pubkey(
1469         IN mbedtls_rsa_context *ctx,
1470         OUT CCRsaUserPubKey_t *UserPubKey_ptr)
1471 {
1472     /* FUNCTION DECLARATIONS */
1473 
1474     /* the counter compare result */
1475     CCCommonCmpCounter_t CounterCmpResult;
1476 
1477     /* the size in bytes of the modulus buffer from mbedtls_rsa_ctx*/
1478     size_t ModulusSize;
1479 
1480     /* the effective size in bits of the modulus buffer */
1481     uint32_t ModulusEffectiveSizeInBits;
1482 
1483     /* the size in bytes of the exponent buffer from mbedtls_rsa_ctx*/
1484     size_t   ExponentSize;
1485 
1486     /* the effective size in bits of the exponent buffer */
1487     uint32_t ExponentEffectiveSizeInBits;
1488 
1489     /* the public key database pointer */
1490     CCRsaPubKey_t *PubKey_ptr;
1491 
1492     /* the Error return code identifier */
1493     CCError_t Error = CC_OK;
1494 
1495     /* FUNCTION LOGIC */
1496     /* ................. checking the validity of the pointer arguments ....... */
1497     /* ------------------------------------------------------------------------ */
1498 
1499     CHECK_AND_RETURN_ERR_UPON_FIPS_ERROR();
1500     ModulusSize = mbedtls_mpi_size(&ctx->MBEDTLS_PRIVATE(N));
1501     ExponentSize = mbedtls_mpi_size(&ctx->MBEDTLS_PRIVATE(E));
1502 
1503     if ((ExponentSize > CC_RSA_MAX_VALID_KEY_SIZE_VALUE_IN_BYTES) ||
1504             (ctx->MBEDTLS_PRIVATE(E).MBEDTLS_PRIVATE(n) == 0))
1505         return CC_RSA_INVALID_EXPONENT_SIZE;
1506 
1507     if ((ModulusSize  > CC_RSA_MAX_VALID_KEY_SIZE_VALUE_IN_BYTES) ||
1508             (ctx->MBEDTLS_PRIVATE(N).MBEDTLS_PRIVATE(n) == 0))
1509     {
1510         return CC_RSA_INVALID_MODULUS_SIZE;
1511     }
1512 
1513     /* .................. copy the buffers to the key handle structure .... */
1514     /* -------------------------------------------------------------------- */
1515     /* setting the pointer to the key database */
1516     PubKey_ptr = ( CCRsaPubKey_t * )UserPubKey_ptr->PublicKeyDbBuff;
1517 
1518     /* clear the public key db */
1519     CC_PalMemSetZero( PubKey_ptr, sizeof(CCRsaPubKey_t) );
1520     CC_PalMemCopy(PubKey_ptr->n, ctx->MBEDTLS_PRIVATE(N).MBEDTLS_PRIVATE(p), mbedtls_mpi_size(&ctx->MBEDTLS_PRIVATE(N)));
1521     CC_PalMemCopy(PubKey_ptr->e, ctx->MBEDTLS_PRIVATE(E).MBEDTLS_PRIVATE(p), mbedtls_mpi_size(&ctx->MBEDTLS_PRIVATE(E)));
1522 
1523     /* .................. initializing local variables ................... */
1524     /* ------------------------------------------------------------------- */
1525 
1526     /* .......... initializing the effective counters size in bits .......... */
1527     ModulusEffectiveSizeInBits =  CC_CommonGetWordsCounterEffectiveSizeInBits(PubKey_ptr->n, (ModulusSize+3)/4);
1528     ExponentEffectiveSizeInBits = CC_CommonGetWordsCounterEffectiveSizeInBits(PubKey_ptr->e, (ExponentSize+3)/4);
1529 
1530     /* .................. checking the validity of the counters ............... */
1531     /* ------------------------------------------------------------------------ */
1532     if ( ( ModulusEffectiveSizeInBits < CC_RSA_MIN_VALID_KEY_SIZE_VALUE_IN_BITS ) ||
1533             ( ModulusEffectiveSizeInBits > CC_RSA_MAX_VALID_KEY_SIZE_VALUE_IN_BITS ) ||
1534             ( ModulusEffectiveSizeInBits % CC_RSA_VALID_KEY_SIZE_MULTIPLE_VALUE_IN_BITS )) {
1535         Error = CC_RSA_INVALID_MODULUS_SIZE;
1536         goto End;
1537     }
1538     /*  verifying the modulus is odd  */
1539     if ( (PubKey_ptr->n[0] & 1UL) == 0 ) {
1540         Error = CC_RSA_MODULUS_EVEN_ERROR;
1541         goto End;
1542     }
1543 
1544     /*  checking the exponent size is not 0 in bytes */
1545     if (ExponentEffectiveSizeInBits == 0) {
1546         Error = CC_RSA_INVALID_EXPONENT_SIZE;
1547         goto End;
1548     }
1549 
1550     /*  verifying the exponent is less then the modulus */
1551     CounterCmpResult = CC_CommonCmpLsWordsUnsignedCounters(PubKey_ptr->e, (ExponentSize+3)/4, PubKey_ptr->n, (ModulusSize+3)/4);
1552 
1553     if (CounterCmpResult != CC_COMMON_CmpCounter2GreaterThenCounter1) {
1554         Error = CC_RSA_INVALID_EXPONENT_VAL;
1555         goto End;
1556     }
1557 
1558     /*  verifying the exponent is not less then 3 */
1559     if (ExponentEffectiveSizeInBits < 32 && PubKey_ptr->e[0] < CC_RSA_MIN_PUB_EXP_VALUE) {
1560         Error = CC_RSA_INVALID_EXPONENT_VAL;
1561         goto End;
1562     }
1563 
1564     /* ................. building the structure ............................. */
1565     /* ---------------------------------------------------------------------- */
1566 
1567     /* setting the modulus and exponent size in bits */
1568     PubKey_ptr->nSizeInBits = ModulusEffectiveSizeInBits;
1569     PubKey_ptr->eSizeInBits = ExponentEffectiveSizeInBits;
1570 
1571     /* ................ initialize the low level data .............. */
1572     Error = RsaInitPubKeyDb(PubKey_ptr);
1573 
1574     if ( Error != CC_OK ) {
1575         Error = CC_RSA_KEY_GENERATION_FAILURE_ERROR;
1576         goto End;
1577     }
1578 
1579     /* ................ set the tag ................ */
1580     UserPubKey_ptr->valid_tag = CC_RSA_PUB_KEY_VALIDATION_TAG;
1581 
1582     /* ................. end of the function .................................. */
1583     /* ------------------------------------------------------------------------ */
1584 
1585 End:
1586     /* if the structure created is not valid - clear it */
1587     if ( Error != CC_OK ) {
1588         CC_PalMemSetZero(UserPubKey_ptr, sizeof(CCRsaUserPubKey_t));
1589         return Error;
1590     }
1591 
1592     return CC_OK;
1593 
1594 }/* END OF build_cc_pubkey */
1595 
1596 
1597 
1598 /*
1599  * Do an RSA public key operation
1600  */
mbedtls_rsa_public(mbedtls_rsa_context * ctx,const unsigned char * input,unsigned char * output)1601 int mbedtls_rsa_public( mbedtls_rsa_context *ctx,
1602         const unsigned char *input,
1603         unsigned char *output )
1604 {
1605 #if defined(MBEDTLS_THREADING_C)
1606     int ret;
1607 #endif
1608     CCError_t Error = CC_OK;
1609     CCRsaUserPubKey_t * UserPubKey_ptr = NULL;
1610     CCRsaPrimeData_t * PrimeData_ptr = NULL;
1611 
1612 
1613     if (ctx == NULL) {
1614         Error = CC_RSA_INVALID_PTR_ERROR;
1615         goto End;
1616     }
1617 
1618 #if defined(MBEDTLS_THREADING_C)
1619     if ( (ret = mbedtls_mutex_lock(&ctx->MBEDTLS_PRIVATE(mutex)) ) != 0)
1620         return( ret );
1621 #endif
1622 
1623     /* ...... checking the validity of the exponent pointer ............... */
1624     if (ctx->MBEDTLS_PRIVATE(E).MBEDTLS_PRIVATE(p) == NULL)
1625         return CC_RSA_INVALID_EXPONENT_POINTER_ERROR;
1626 
1627     /* ...... checking the validity of the modulus pointer .............. */
1628     if (ctx->MBEDTLS_PRIVATE(N).MBEDTLS_PRIVATE(p) == NULL)
1629         return CC_RSA_INVALID_MODULUS_POINTER_ERROR;
1630 
1631     UserPubKey_ptr = (CCRsaUserPubKey_t *)mbedtls_calloc(1, sizeof(CCRsaUserPubKey_t));
1632     if (UserPubKey_ptr == NULL) {
1633         Error = CC_OUT_OF_RESOURCE_ERROR;
1634         goto End;
1635     }
1636 
1637     PrimeData_ptr = (CCRsaPrimeData_t *)mbedtls_calloc(1, sizeof(CCRsaPrimeData_t));
1638     if (PrimeData_ptr == NULL) {
1639         Error = CC_OUT_OF_RESOURCE_ERROR;
1640         goto End;
1641     }
1642 
1643     Error = build_cc_pubkey(ctx, UserPubKey_ptr);
1644     if ( Error != CC_OK ) {
1645         goto End;
1646     }
1647 
1648     Error = CC_RsaPrimEncrypt(UserPubKey_ptr, PrimeData_ptr, (unsigned char *)input, ctx->MBEDTLS_PRIVATE(len), output);
1649     if ( Error != CC_OK ) {
1650         goto End;
1651     }
1652 
1653 End:
1654     mbedtls_zeroize_internal(UserPubKey_ptr, sizeof(CCRsaUserPubKey_t));
1655     mbedtls_zeroize_internal(PrimeData_ptr, sizeof(CCRsaPrimeData_t));
1656     mbedtls_free(PrimeData_ptr);
1657     mbedtls_free(UserPubKey_ptr);
1658 
1659 #if defined(MBEDTLS_THREADING_C)
1660     if( mbedtls_mutex_unlock( &ctx->MBEDTLS_PRIVATE(mutex) ) != 0 )
1661         return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
1662 #endif
1663 
1664     return error_mapping_cc_to_mbedtls_rsa(Error, CC_RSA_OP_PUBLIC);
1665 }
1666 
1667 /*
1668  * Do an RSA private key operation
1669  */
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)1670 int mbedtls_rsa_private( mbedtls_rsa_context *ctx,
1671         int (*f_rng)(void *, unsigned char *, size_t),
1672         void *p_rng,
1673         const unsigned char *input,
1674         unsigned char *output )
1675 {
1676 #if defined(MBEDTLS_THREADING_C)
1677     int ret;
1678 #endif
1679     CCError_t Error = CC_OK;
1680     CCRsaUserPrivKey_t * UserPrivKey_ptr = NULL;
1681     CCRsaPrimeData_t * PrimeData_ptr = NULL;
1682 
1683     // f_rng and p_rng are used for blinding, which CC does not support
1684     CC_UNUSED_PARAM(f_rng);
1685     CC_UNUSED_PARAM(p_rng);
1686 
1687     /* Check input parameters */
1688     if (ctx == NULL){
1689         GOTO_END( CC_RSA_INVALID_PTR_ERROR );
1690     }
1691 
1692     /* Make sure we have private key info, prevent possible misuse */
1693     if( input == NULL || output == NULL )
1694     {
1695         GOTO_END( CC_RSA_INVALID_PTR_ERROR );
1696     }
1697 
1698     /* Validate mbedtls_rsa_context for private key actions*/
1699     if ( (Error = validate_mbedtls_rsa_context_private_key(ctx)) != 0 )
1700     {
1701         GOTO_END( Error );
1702     }
1703 
1704 #if defined(MBEDTLS_THREADING_C)
1705     if( ( ret = mbedtls_mutex_lock( &ctx->MBEDTLS_PRIVATE(mutex) ) ) != 0 )
1706         return( ret );
1707 #endif
1708 
1709     UserPrivKey_ptr = (CCRsaUserPrivKey_t *)mbedtls_calloc(1, sizeof(CCRsaUserPrivKey_t));
1710     if ( UserPrivKey_ptr == NULL ) {
1711         GOTO_CLEANUP(CC_OUT_OF_RESOURCE_ERROR);
1712     }
1713 
1714     PrimeData_ptr = (CCRsaPrimeData_t *)mbedtls_calloc(1, sizeof(CCRsaPrimeData_t));
1715     if ( PrimeData_ptr == NULL ) {
1716         GOTO_CLEANUP(CC_OUT_OF_RESOURCE_ERROR);
1717     }
1718 
1719     // In mbedTLS CRT vs. non-CRT it compilation-time define
1720 #if defined(MBEDTLS_RSA_NO_CRT)
1721     Error = build_cc_priv_non_crt_key(ctx, UserPrivKey_ptr);
1722 #else
1723     Error = build_cc_priv_crt_key(ctx, UserPrivKey_ptr);
1724 #endif
1725     if ( Error != CC_OK ) {
1726         GOTO_CLEANUP(Error);
1727     }
1728 
1729     Error = CC_RsaPrimDecrypt(UserPrivKey_ptr, PrimeData_ptr, (unsigned char *)input, ctx->MBEDTLS_PRIVATE(len), output);
1730     if ( Error != CC_OK ) {
1731         GOTO_CLEANUP(Error);
1732     }
1733 Cleanup:
1734     if ( Error != CC_OK ) {
1735         mbedtls_zeroize_internal(output, ctx->MBEDTLS_PRIVATE(len));
1736     }
1737     mbedtls_zeroize_internal(UserPrivKey_ptr, sizeof(CCRsaUserPrivKey_t));
1738     mbedtls_zeroize_internal(PrimeData_ptr, sizeof(CCRsaPrimeData_t));
1739     mbedtls_free(PrimeData_ptr);
1740     mbedtls_free(UserPrivKey_ptr);
1741 End:
1742 #if defined(MBEDTLS_THREADING_C)
1743     if( mbedtls_mutex_unlock( &ctx->MBEDTLS_PRIVATE(mutex) ) != 0 )
1744         return( MBEDTLS_ERR_THREADING_MUTEX_ERROR );
1745 #endif
1746 
1747     return error_mapping_cc_to_mbedtls_rsa(Error, CC_RSA_OP_PRIVATE);
1748 }
1749 
1750 
1751 #if defined(MBEDTLS_PKCS1_V21)
1752 /*
1753  * Implementation of the PKCS#1 v2.1 RSAES-OAEP-ENCRYPT function
1754  */
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)1755 int mbedtls_rsa_rsaes_oaep_encrypt( mbedtls_rsa_context *ctx,
1756         int (*f_rng)(void *, unsigned char *, size_t),
1757         void *p_rng,
1758         const unsigned char *label, size_t label_len,
1759         size_t ilen,
1760         const unsigned char *input,
1761         unsigned char *output )
1762 {
1763     size_t olen;
1764     unsigned int hlen;
1765     const mbedtls_md_info_t *md_info;
1766 
1767     CCError_t Error = CC_OK;
1768     CCRsaUserPubKey_t * UserPubKey_ptr = NULL;
1769     CCRsaPrimeData_t * PrimeData_ptr = NULL;
1770     CCRndContext_t rndContext;
1771     CCRndContext_t *rndContext_ptr = &rndContext;
1772     CCRsaHashOpMode_t hashOpMode = CC_RSA_HASH_OpModeLast;
1773     size_t hashOutputSizeBytes = 0;
1774 
1775     /* Check input parameters */
1776     if (ctx == NULL){
1777         GOTO_END( CC_RSA_INVALID_PTR_ERROR );
1778     }
1779 
1780     if( input == NULL || output == NULL )
1781     {
1782         GOTO_END( CC_RSA_INVALID_PTR_ERROR );
1783     }
1784 
1785     if( f_rng == NULL )
1786     {
1787         GOTO_END( CC_RND_STATE_PTR_INVALID_ERROR );
1788     }
1789 
1790     rndContext_ptr->rndState = p_rng;
1791     if ( (Error = CC_RndSetGenerateVectorFunc(rndContext_ptr, f_rng)) != CC_OK )
1792     {
1793         GOTO_END( Error );
1794     }
1795 
1796     if ( (Error = validate_mbedtls_rsa_context_public_key(ctx)) != CC_OK )
1797     {
1798         GOTO_END( Error );
1799     }
1800 
1801     if (ctx->MBEDTLS_PRIVATE(padding) != MBEDTLS_RSA_PKCS_V21)
1802     {
1803         GOTO_END( CC_RSA_DATA_POINTER_INVALID_ERROR );
1804     }
1805 
1806 
1807     if ( (Error = convert_mbedtls_md_type_to_cc_rsa_hash_opmode((mbedtls_md_type_t)ctx->MBEDTLS_PRIVATE(hash_id),
1808                                                0,     // HashMode - before
1809                                                &hashOpMode,
1810                                                &hashOutputSizeBytes)) != CC_OK )
1811     {
1812         GOTO_CLEANUP( Error );
1813     }
1814 
1815     md_info = mbedtls_md_info_from_type( (mbedtls_md_type_t) ctx->MBEDTLS_PRIVATE(hash_id) );
1816     if( md_info == NULL )
1817     {
1818         GOTO_END( CC_RSA_HASH_ILLEGAL_OPERATION_MODE_ERROR );
1819     }
1820 
1821     olen = ctx->MBEDTLS_PRIVATE(len);
1822     hlen = mbedtls_md_get_size( md_info );
1823 
1824     /* first comparison checks for overflow */
1825     if( ilen + 2 * hlen + 2 < ilen || olen < ilen + 2 * hlen + 2 )
1826     {
1827         GOTO_END( CC_RSA_INVALID_MESSAGE_DATA_SIZE );
1828     }
1829 
1830     UserPubKey_ptr = (CCRsaUserPubKey_t *)mbedtls_calloc(1, sizeof(CCRsaUserPubKey_t));
1831     if (UserPubKey_ptr == NULL) {
1832         GOTO_CLEANUP( CC_OUT_OF_RESOURCE_ERROR );
1833     }
1834 
1835     PrimeData_ptr = (CCRsaPrimeData_t *)mbedtls_calloc(1, sizeof(CCRsaPrimeData_t));
1836     if (PrimeData_ptr == NULL)
1837     {
1838         GOTO_CLEANUP( CC_OUT_OF_RESOURCE_ERROR );
1839     }
1840 
1841     Error = build_cc_pubkey(ctx, UserPubKey_ptr);
1842     if ( Error != CC_OK )
1843     {
1844         GOTO_CLEANUP( Error );
1845     }
1846 
1847     Error = CC_RsaOaepEncrypt(rndContext_ptr,
1848                   UserPubKey_ptr,
1849                   PrimeData_ptr,
1850                   hashOpMode,
1851                   (unsigned char *)label, // Need to remove the const-ness
1852                   label_len,
1853                   CC_PKCS1_MGF1,
1854                   (unsigned char *)input, // Need to remove the const-ness
1855                   ilen,
1856                   output);
1857 
1858     if ( Error != CC_OK )
1859     {
1860         GOTO_CLEANUP( Error );
1861     }
1862 
1863 Cleanup:
1864     if ( Error != CC_OK )
1865     {
1866         mbedtls_zeroize_internal(output, ctx->MBEDTLS_PRIVATE(len));
1867     }
1868     mbedtls_zeroize_internal(UserPubKey_ptr, sizeof(CCRsaUserPubKey_t));
1869     mbedtls_zeroize_internal(PrimeData_ptr, sizeof(CCRsaPrimeData_t));
1870     mbedtls_free(PrimeData_ptr);
1871     mbedtls_free(UserPubKey_ptr);
1872 End:
1873     return error_mapping_cc_to_mbedtls_rsa(Error, CC_RSA_OP_PUBLIC);
1874 }
1875 #endif /* MBEDTLS_PKCS1_V21 */
1876 
1877 #if defined(MBEDTLS_PKCS1_V15)
1878 /*
1879  * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-ENCRYPT function
1880  */
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)1881 int mbedtls_rsa_rsaes_pkcs1_v15_encrypt( mbedtls_rsa_context *ctx,
1882         int (*f_rng)(void *, unsigned char *, size_t),
1883         void *p_rng,
1884         size_t ilen,
1885         const unsigned char *input,
1886         unsigned char *output )
1887 {
1888 
1889     CCError_t Error = CC_OK;
1890     CCRsaUserPubKey_t * UserPubKey_ptr = NULL;
1891     CCRsaPrimeData_t * PrimeData_ptr = NULL;
1892     CCRndContext_t rndContext;
1893     CCRndContext_t *rndContext_ptr = &rndContext;
1894 
1895     /* Check input parameters */
1896     if (ctx == NULL){
1897         GOTO_END( CC_RSA_INVALID_PTR_ERROR );
1898     }
1899 
1900     if( input == NULL || output == NULL )
1901     {
1902         GOTO_END( CC_RSA_INVALID_PTR_ERROR );
1903     }
1904 
1905     if( f_rng == NULL )
1906     {
1907         GOTO_END( CC_RND_STATE_PTR_INVALID_ERROR );
1908     }
1909 
1910     rndContext_ptr->rndState = p_rng;
1911     if ( (Error = CC_RndSetGenerateVectorFunc(rndContext_ptr, f_rng)) != CC_OK )
1912         GOTO_END( Error );
1913 
1914     if ( (Error = validate_mbedtls_rsa_context_public_key(ctx)) != CC_OK )
1915     {
1916         GOTO_END( Error );
1917     }
1918 
1919     if ( ctx->MBEDTLS_PRIVATE(padding) != MBEDTLS_RSA_PKCS_V15 )
1920     {
1921         GOTO_END( CC_RSA_DATA_POINTER_INVALID_ERROR );
1922     }
1923 
1924     /* first comparison checks for overflow */
1925     if( ilen + 11 < ilen || ctx->MBEDTLS_PRIVATE(len) < ilen + 11 )
1926     {
1927         GOTO_END( CC_RSA_INVALID_MESSAGE_DATA_SIZE );
1928     }
1929 
1930     UserPubKey_ptr = (CCRsaUserPubKey_t *)mbedtls_calloc(1, sizeof(CCRsaUserPubKey_t));
1931     if ( UserPubKey_ptr == NULL )
1932     {
1933         GOTO_CLEANUP( CC_OUT_OF_RESOURCE_ERROR );
1934     }
1935 
1936     PrimeData_ptr = (CCRsaPrimeData_t *)mbedtls_calloc(1, sizeof(CCRsaPrimeData_t));
1937     if ( PrimeData_ptr == NULL )
1938     {
1939         GOTO_CLEANUP( CC_OUT_OF_RESOURCE_ERROR );
1940     }
1941 
1942     Error = build_cc_pubkey(ctx, UserPubKey_ptr);
1943     if ( Error != CC_OK )
1944     {
1945         GOTO_CLEANUP( Error );
1946     }
1947 
1948     Error = CC_RsaPkcs1V15Encrypt(rndContext_ptr,
1949                                   UserPubKey_ptr,
1950                                   PrimeData_ptr,
1951                                   (unsigned char *)input, // Need to remove the const-ness
1952                                   ilen,
1953                                   (unsigned char *)output); // Need to remove the const-ness
1954 
1955     if ( Error != CC_OK )
1956     {
1957         GOTO_CLEANUP( Error );
1958     }
1959 
1960 Cleanup:
1961     if ( Error != CC_OK )
1962     {
1963         mbedtls_zeroize_internal(output, ctx->MBEDTLS_PRIVATE(len));
1964     }
1965     mbedtls_zeroize_internal(UserPubKey_ptr, sizeof(CCRsaUserPubKey_t));
1966     mbedtls_zeroize_internal(PrimeData_ptr, sizeof(CCRsaPrimeData_t));
1967     mbedtls_free(PrimeData_ptr);
1968     mbedtls_free(UserPubKey_ptr);
1969 End:
1970 
1971     return error_mapping_cc_to_mbedtls_rsa(Error, CC_RSA_OP_PUBLIC);
1972 }
1973 
1974 #endif /* MBEDTLS_PKCS1_V15 */
1975 
1976 /*
1977  * Add the message padding, then do an RSA operation
1978  */
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)1979 int mbedtls_rsa_pkcs1_encrypt( mbedtls_rsa_context *ctx,
1980         int (*f_rng)(void *, unsigned char *, size_t),
1981         void *p_rng,
1982         size_t ilen,
1983         const unsigned char *input,
1984         unsigned char *output )
1985 {
1986     /* Check input parameters */
1987     if (ctx == NULL){
1988         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
1989     }
1990 
1991     switch( ctx->MBEDTLS_PRIVATE(padding) )
1992     {
1993 #if defined(MBEDTLS_PKCS1_V15)
1994         case MBEDTLS_RSA_PKCS_V15:
1995             return mbedtls_rsa_rsaes_pkcs1_v15_encrypt( ctx, f_rng, p_rng, ilen,
1996                     input, output );
1997 #endif
1998 
1999 #if defined(MBEDTLS_PKCS1_V21)
2000         case MBEDTLS_RSA_PKCS_V21:
2001             return mbedtls_rsa_rsaes_oaep_encrypt( ctx, f_rng, p_rng, NULL, 0,
2002                     ilen, input, output );
2003 #endif
2004 
2005         default:
2006             return( MBEDTLS_ERR_RSA_INVALID_PADDING );
2007     }
2008 }
2009 
2010 #if defined(MBEDTLS_PKCS1_V21)
2011 /*
2012  * Implementation of the PKCS#1 v2.1 RSAES-OAEP-DECRYPT function
2013  */
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)2014 int mbedtls_rsa_rsaes_oaep_decrypt( mbedtls_rsa_context *ctx,
2015         int (*f_rng)(void *, unsigned char *, size_t),
2016         void *p_rng,
2017         const unsigned char *label, size_t label_len,
2018         size_t *olen,
2019         const unsigned char *input,
2020         unsigned char *output,
2021         size_t output_max_len )
2022 {
2023     CCError_t Error = CC_OK;
2024     CCRsaUserPrivKey_t * UserPrivKey_ptr = NULL;
2025     CCRsaPrimeData_t * PrimeData_ptr = NULL;
2026     CCRsaHashOpMode_t hashOpMode = CC_RSA_HASH_OpModeLast;
2027     size_t hashOutputSizeBytes = 0;
2028 
2029     // in mbedtls decrypt scheme f_rng and p_rng are used for blinding
2030     // CC does not support blinding
2031     CC_UNUSED_PARAM(f_rng);
2032     CC_UNUSED_PARAM(p_rng);
2033 
2034     if( input == NULL || output == NULL )
2035     {
2036         GOTO_END( CC_RSA_INVALID_PTR_ERROR );
2037     }
2038 
2039     /* Validate mbedtls_rsa_context for private key actions*/
2040     if ( (Error = validate_mbedtls_rsa_context_private_key(ctx)) != CC_OK )
2041     {
2042         GOTO_END( Error );
2043     }
2044 
2045     if ( ctx->MBEDTLS_PRIVATE(padding) != MBEDTLS_RSA_PKCS_V21 )
2046         GOTO_END( CC_RSA_DATA_POINTER_INVALID_ERROR );
2047 
2048     // Sanity check on input length, not sure it's needed
2049     if( ctx->MBEDTLS_PRIVATE(len) < 16 || ctx->MBEDTLS_PRIVATE(len) > MBEDTLS_MPI_MAX_SIZE )
2050     {
2051         GOTO_END( CC_RSA_INVALID_MESSAGE_DATA_SIZE );
2052     }
2053 
2054     if ( ( Error = convert_mbedtls_md_type_to_cc_rsa_hash_opmode((mbedtls_md_type_t)ctx->MBEDTLS_PRIVATE(hash_id),
2055                                                0,    // HashMode - before
2056                                                &hashOpMode,
2057                                                &hashOutputSizeBytes) ) != CC_OK )
2058     {
2059         GOTO_END( Error );
2060     }
2061 
2062     // checking for integer underflow
2063     if( 2 * hashOutputSizeBytes + 2 > ctx->MBEDTLS_PRIVATE(len) )
2064     {
2065         GOTO_END( CC_RSA_INVALID_MESSAGE_DATA_SIZE );
2066     }
2067 
2068     UserPrivKey_ptr = (CCRsaUserPrivKey_t *)mbedtls_calloc(1, sizeof(CCRsaUserPrivKey_t));
2069     if ( UserPrivKey_ptr == NULL )
2070     {
2071         GOTO_CLEANUP(CC_OUT_OF_RESOURCE_ERROR);
2072     }
2073 
2074     PrimeData_ptr = (CCRsaPrimeData_t *)mbedtls_calloc(1, sizeof(CCRsaPrimeData_t));
2075     if ( PrimeData_ptr == NULL )
2076     {
2077         GOTO_CLEANUP(CC_OUT_OF_RESOURCE_ERROR);
2078     }
2079 
2080     // In mbedTLS CRT vs. non-CRT it compilation-time define
2081 #if defined(MBEDTLS_RSA_NO_CRT)
2082     Error = build_cc_priv_non_crt_key(ctx, UserPrivKey_ptr);
2083 #else
2084     Error = build_cc_priv_crt_key(ctx, UserPrivKey_ptr);
2085 #endif
2086     if ( Error != CC_OK )
2087     {
2088         GOTO_CLEANUP(Error);
2089     }
2090 
2091     *olen = output_max_len;
2092 
2093     Error = CC_RsaOaepDecrypt(UserPrivKey_ptr,
2094                               PrimeData_ptr,
2095                               hashOpMode,
2096                               (unsigned char *)label, // Need to remove the const-ness
2097                               label_len,
2098                               CC_PKCS1_MGF1,
2099                               (unsigned char *)input, // Need to remove the const-ness
2100                               ctx->MBEDTLS_PRIVATE(len),
2101                               output,
2102                               olen);
2103     if ( Error != CC_OK)
2104     {
2105         GOTO_CLEANUP(Error);
2106     }
2107 
2108     if( *olen > output_max_len )
2109     {
2110         GOTO_CLEANUP( CC_RSA_15_ERROR_IN_DECRYPTED_DATA_SIZE );
2111     }
2112 
2113 Cleanup:
2114     if ( Error != CC_OK )
2115     {
2116         mbedtls_zeroize_internal(output, output_max_len);
2117     }
2118     mbedtls_zeroize_internal(UserPrivKey_ptr, sizeof(CCRsaUserPrivKey_t));
2119     mbedtls_zeroize_internal(PrimeData_ptr, sizeof(CCRsaPrimeData_t));
2120     mbedtls_free(PrimeData_ptr);
2121     mbedtls_free(UserPrivKey_ptr);
2122 End:
2123     return error_mapping_cc_to_mbedtls_rsa(Error, CC_RSA_OP_PRIVATE);
2124 }
2125 #endif /* MBEDTLS_PKCS1_V21 */
2126 
2127 #if defined(MBEDTLS_PKCS1_V15)
2128 /*
2129  * Implementation of the PKCS#1 v2.1 RSAES-PKCS1-V1_5-DECRYPT function
2130  */
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)2131 int mbedtls_rsa_rsaes_pkcs1_v15_decrypt( mbedtls_rsa_context *ctx,
2132         int (*f_rng)(void *, unsigned char *, size_t),
2133         void *p_rng,
2134         size_t *olen,
2135         const unsigned char *input,
2136         unsigned char *output,
2137         size_t output_max_len)
2138 {
2139     CCError_t Error = CC_OK;
2140     CCRsaUserPrivKey_t * UserPrivKey_ptr = NULL;
2141     CCRsaPrimeData_t * PrimeData_ptr = NULL;
2142 
2143     /* Check input parameters */
2144     if (ctx == NULL){
2145         GOTO_END( CC_RSA_INVALID_PTR_ERROR );
2146     }
2147 
2148     // in mbedtls decrypt scheme f_rng and p_rng are used for blinding
2149     // CC does not support blinding
2150     CC_UNUSED_PARAM(f_rng);
2151     CC_UNUSED_PARAM(p_rng);
2152 
2153     if( input == NULL || output == NULL )
2154     {
2155         GOTO_END( CC_RSA_INVALID_PTR_ERROR );
2156     }
2157 
2158 
2159     /* Validate mbedtls_rsa_context for private key actions*/
2160     if ( (Error = validate_mbedtls_rsa_context_private_key(ctx)) != 0 )
2161     {
2162         GOTO_END( Error );
2163     }
2164 
2165     if( ctx->MBEDTLS_PRIVATE(padding) != MBEDTLS_RSA_PKCS_V15 )
2166     {
2167         GOTO_END( CC_RSA_DATA_POINTER_INVALID_ERROR );
2168     }
2169 
2170     // Sanity check on input length, not sure it's needed
2171     if( ctx->MBEDTLS_PRIVATE(len) < 16 || ctx->MBEDTLS_PRIVATE(len) > MBEDTLS_MPI_MAX_SIZE )
2172     {
2173         GOTO_END( CC_RSA_INVALID_MESSAGE_DATA_SIZE );
2174     }
2175 
2176     UserPrivKey_ptr = (CCRsaUserPrivKey_t *)mbedtls_calloc(1, sizeof(CCRsaUserPrivKey_t));
2177     if ( UserPrivKey_ptr == NULL )
2178     {
2179         GOTO_CLEANUP(CC_OUT_OF_RESOURCE_ERROR);
2180     }
2181 
2182     PrimeData_ptr = (CCRsaPrimeData_t *)mbedtls_calloc(1, sizeof(CCRsaPrimeData_t));
2183     if ( PrimeData_ptr == NULL )
2184     {
2185         GOTO_CLEANUP(CC_OUT_OF_RESOURCE_ERROR);
2186     }
2187 
2188     // In mbedTLS CRT vs. non-CRT it compilation-time define
2189 #if defined(MBEDTLS_RSA_NO_CRT)
2190     Error = build_cc_priv_non_crt_key(ctx, UserPrivKey_ptr);
2191 #else
2192     Error = build_cc_priv_crt_key(ctx, UserPrivKey_ptr);
2193 #endif
2194     if ( Error != CC_OK )
2195     {
2196         GOTO_CLEANUP(Error);
2197     }
2198 
2199     *olen = output_max_len;
2200 
2201     Error = CC_RsaPkcs1V15Decrypt(UserPrivKey_ptr,
2202                                   PrimeData_ptr,
2203                                   (unsigned char *)input, // Need to remove the const-ness
2204                                   ctx->MBEDTLS_PRIVATE(len),
2205                                   output,
2206                                   olen);
2207 
2208     if ( Error != CC_OK )
2209     {
2210         GOTO_CLEANUP(Error);
2211     }
2212 
2213     if( *olen > output_max_len )
2214     {
2215         GOTO_CLEANUP( CC_RSA_15_ERROR_IN_DECRYPTED_DATA_SIZE );
2216     }
2217 
2218 Cleanup:
2219     if ( Error != CC_OK )
2220     {
2221         mbedtls_zeroize_internal(output, output_max_len);
2222     }
2223     mbedtls_zeroize_internal(UserPrivKey_ptr, sizeof(CCRsaUserPrivKey_t));
2224     mbedtls_zeroize_internal(PrimeData_ptr, sizeof(CCRsaPrimeData_t));
2225     mbedtls_free(PrimeData_ptr);
2226     mbedtls_free(UserPrivKey_ptr);
2227 End:
2228 
2229     return error_mapping_cc_to_mbedtls_rsa(Error, CC_RSA_OP_PRIVATE);
2230 }
2231 #endif /* MBEDTLS_PKCS1_V15 */
2232 
2233 /*
2234  * Do an RSA operation, then remove the message padding
2235  */
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)2236 int mbedtls_rsa_pkcs1_decrypt( mbedtls_rsa_context *ctx,
2237         int (*f_rng)(void *, unsigned char *, size_t),
2238         void *p_rng,
2239         size_t *olen,
2240         const unsigned char *input,
2241         unsigned char *output,
2242         size_t output_max_len)
2243 {
2244     /* Check input parameters */
2245     if (ctx == NULL){
2246         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
2247     }
2248 
2249     switch( ctx->MBEDTLS_PRIVATE(padding) )
2250     {
2251 #if defined(MBEDTLS_PKCS1_V15)
2252         case MBEDTLS_RSA_PKCS_V15:
2253             return mbedtls_rsa_rsaes_pkcs1_v15_decrypt( ctx, f_rng, p_rng, olen,
2254                     input, output, output_max_len );
2255 #endif
2256 
2257 #if defined(MBEDTLS_PKCS1_V21)
2258         case MBEDTLS_RSA_PKCS_V21:
2259             return mbedtls_rsa_rsaes_oaep_decrypt( ctx, f_rng, p_rng, NULL, 0,
2260                     olen, input, output,
2261                     output_max_len );
2262 #endif
2263 
2264         default:
2265             return( MBEDTLS_ERR_RSA_INVALID_PADDING );
2266     }
2267 }
2268 
2269 #if defined(MBEDTLS_PKCS1_V21)
2270 /*
2271  * Implementation of the PKCS#1 v2.1 RSASSA-PSS-SIGN function
2272  */
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)2273 int mbedtls_rsa_rsassa_pss_sign( mbedtls_rsa_context *ctx,
2274         int (*f_rng)(void *, unsigned char *, size_t),
2275         void *p_rng,
2276         mbedtls_md_type_t md_alg,
2277         unsigned int hashlen,
2278         const unsigned char *hash,
2279         unsigned char *sig )
2280 {
2281 
2282     CCRndContext_t              rndContext;
2283     CCRsaPrivUserContext_t      *UserContext_ptr = NULL;
2284     CCRsaUserPrivKey_t          *UserPrivKey_ptr = NULL;
2285     CCRsaHashOpMode_t           hashOpMode;
2286     size_t                      hashOutputSizeBytes;
2287     size_t                      sig_size;
2288     CCError_t                   Error = CC_OK;
2289 
2290     CC_UNUSED_PARAM( hashlen );        /* message digest length (for MBEDTLS_MD_NONE only which is not supported.) */
2291     /* Check input parameters */
2292     if (ctx == NULL){
2293         GOTO_END( CC_RSA_INVALID_PTR_ERROR );
2294     }
2295     if ( NULL == sig || NULL == hash )
2296     {
2297         GOTO_END( CC_RSA_INVALID_PTR_ERROR );
2298     }
2299     if ( MBEDTLS_MD_NONE == md_alg )
2300     {
2301         mbedtls_printf( "ERROR: MBEDTLS_MD_NONE is not supported!\r\n" );
2302         GOTO_END(CC_RSA_HASH_ILLEGAL_OPERATION_MODE_ERROR); /* MD_NONE is not supported in cryptocell */
2303     }
2304         /* The hash_id in the RSA context is the one used for the
2305         encoding. md_alg in the function call is the type of hash
2306         that is encoded. According to RFC 3447 it is advised to keep
2307         both hashes the same. */
2308     if ( md_alg != ( mbedtls_md_type_t ) ctx->MBEDTLS_PRIVATE(hash_id) )
2309     {
2310         GOTO_END( CC_RSA_HASH_ILLEGAL_OPERATION_MODE_ERROR );
2311     }
2312     Error = convert_mbedtls_md_type_to_cc_rsa_hash_opmode( md_alg,
2313                                                            1, // After hash.
2314                                                            &hashOpMode,
2315                                                            &hashOutputSizeBytes );
2316     if ( CC_OK!= Error )
2317     {
2318         GOTO_END( Error );
2319     }
2320 
2321     rndContext.rndState = p_rng;
2322     if ( ( Error = CC_RndSetGenerateVectorFunc(&rndContext, f_rng)) != CC_OK )
2323     {
2324         GOTO_END( Error );
2325     }
2326 
2327     UserPrivKey_ptr = ( CCRsaUserPrivKey_t * )mbedtls_calloc( 1, sizeof(CCRsaUserPrivKey_t ) );
2328     if ( NULL == UserPrivKey_ptr )
2329     {
2330         GOTO_CLEANUP( CC_OUT_OF_RESOURCE_ERROR );
2331     }
2332     UserContext_ptr = ( CCRsaPrivUserContext_t * )mbedtls_calloc( 1, sizeof(CCRsaPrivUserContext_t ) );
2333     if ( NULL == UserContext_ptr )
2334     {
2335         GOTO_CLEANUP( CC_OUT_OF_RESOURCE_ERROR );
2336     }
2337     if ( (Error = validate_mbedtls_rsa_context_private_key( ctx ) ) != CC_OK )
2338     {
2339         GOTO_CLEANUP( Error );
2340     }
2341 #if defined(MBEDTLS_RSA_NO_CRT)
2342     Error = build_cc_priv_non_crt_key( ctx, UserPrivKey_ptr );
2343 #else
2344     Error = build_cc_priv_crt_key( ctx, UserPrivKey_ptr );
2345 #endif
2346     if ( CC_OK != Error )
2347     {
2348         GOTO_CLEANUP( Error );
2349     }
2350 
2351     sig_size = mbedtls_mpi_size( ( const mbedtls_mpi *)&( ctx->MBEDTLS_PRIVATE(N) ) );
2352 
2353     Error = CC_RsaPssSign( &rndContext,
2354         UserContext_ptr,
2355         UserPrivKey_ptr,
2356         hashOpMode,
2357         CC_PKCS1_MGF1,
2358         hashOutputSizeBytes,
2359         ( uint8_t * )hash,
2360         hashOutputSizeBytes,
2361         ( uint8_t * )sig,
2362         &sig_size );
2363 Cleanup:
2364         mbedtls_free( UserPrivKey_ptr );
2365         mbedtls_free( UserContext_ptr );
2366 End:
2367         return error_mapping_cc_to_mbedtls_rsa( Error, CC_RSA_OP_PRIVATE );
2368 }
2369 
2370 
2371 #endif /* MBEDTLS_PKCS1_V21 */
2372 
2373 #if defined(MBEDTLS_PKCS1_V15)
2374 /*
2375  * Implementation of the PKCS#1 v2.1 RSASSA-PKCS1-V1_5-SIGN function
2376  */
2377 /*
2378  * Do an RSA operation to sign the message digest
2379  */
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)2380 int mbedtls_rsa_rsassa_pkcs1_v15_sign( mbedtls_rsa_context *ctx,
2381         int (*f_rng)(void *, unsigned char *, size_t),
2382         void *p_rng,
2383         mbedtls_md_type_t md_alg,
2384         unsigned int hashlen,
2385         const unsigned char *hash,
2386         unsigned char *sig )
2387 {
2388     CCRndContext_t              rndContext;
2389     CCRsaPrivUserContext_t      *UserContext_ptr = NULL;
2390     CCRsaUserPrivKey_t          *UserPrivKey_ptr = NULL;
2391     CCRsaHashOpMode_t           hashOpMode;
2392     size_t                      hashOutputSizeBytes;
2393     size_t                      sig_size;
2394     CCError_t                   Error = CC_OK;
2395 
2396     CC_UNUSED_PARAM(hashlen); /* message digest length (for MBEDTLS_MD_NONE only which is not supported.) */
2397 
2398     /* Check input parameters */
2399     if (ctx == NULL){
2400         GOTO_END( CC_RSA_INVALID_PTR_ERROR );
2401     }
2402     if (NULL == sig || NULL == hash)
2403     {
2404         GOTO_END( CC_RSA_INVALID_PTR_ERROR );
2405     }
2406     if ( MBEDTLS_MD_NONE == md_alg )
2407     {
2408         mbedtls_printf("DVIR: ERROR: MBEDTLS_MD_NONE is not supported!\r\n");
2409         GOTO_END(CC_RSA_HASH_ILLEGAL_OPERATION_MODE_ERROR); /* MD_NONE is not supported in cryptocell */
2410     }
2411     Error = convert_mbedtls_md_type_to_cc_rsa_hash_opmode(md_alg,
2412                                                            1, // After hash.
2413                                                            &hashOpMode,
2414                                                            &hashOutputSizeBytes);
2415     if (Error != CC_OK)
2416     {
2417         GOTO_END(Error);
2418     }
2419 
2420     rndContext.rndState = p_rng;
2421     if ( (Error = CC_RndSetGenerateVectorFunc(&rndContext, f_rng)) != CC_OK)
2422     {
2423         GOTO_END(Error);
2424     }
2425 
2426     UserPrivKey_ptr = (CCRsaUserPrivKey_t *)mbedtls_calloc(1, sizeof(CCRsaUserPrivKey_t));
2427     if (NULL == UserPrivKey_ptr)
2428     {
2429         GOTO_CLEANUP( CC_OUT_OF_RESOURCE_ERROR );
2430     }
2431     UserContext_ptr = (CCRsaPrivUserContext_t *)mbedtls_calloc(1, sizeof(CCRsaPrivUserContext_t));
2432     if (NULL == UserContext_ptr)
2433     {
2434         GOTO_CLEANUP( CC_OUT_OF_RESOURCE_ERROR );
2435     }
2436     if ( (Error = validate_mbedtls_rsa_context_private_key(ctx)) != CC_OK )
2437     {
2438         GOTO_CLEANUP( Error );
2439     }
2440 #if defined(MBEDTLS_RSA_NO_CRT)
2441     Error = build_cc_priv_non_crt_key(ctx, UserPrivKey_ptr);
2442 #else
2443     Error = build_cc_priv_crt_key(ctx, UserPrivKey_ptr);
2444 #endif
2445     if ( Error != CC_OK )
2446     {
2447         GOTO_CLEANUP(Error);
2448     }
2449 
2450     sig_size = mbedtls_mpi_size( (const mbedtls_mpi *)&(ctx->MBEDTLS_PRIVATE(N)) );
2451     Error = CC_RsaPkcs1V15Sign(&rndContext,
2452         UserContext_ptr,
2453         UserPrivKey_ptr,
2454         hashOpMode,
2455         (uint8_t *)hash,
2456         hashOutputSizeBytes,
2457         (uint8_t *)sig,
2458         &sig_size);
2459 
2460 Cleanup:
2461         mbedtls_free(UserPrivKey_ptr);
2462         mbedtls_free(UserContext_ptr);
2463 End:
2464         return error_mapping_cc_to_mbedtls_rsa(Error, CC_RSA_OP_PRIVATE);
2465         }
2466 
2467 #endif /* MBEDTLS_PKCS1_V15 */
2468 
2469 /*
2470  * Do an RSA operation to sign the message digest
2471  */
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)2472 int mbedtls_rsa_pkcs1_sign( mbedtls_rsa_context *ctx,
2473         int (*f_rng)(void *, unsigned char *, size_t),
2474         void *p_rng,
2475         mbedtls_md_type_t md_alg,
2476         unsigned int hashlen,
2477         const unsigned char *hash,
2478         unsigned char *sig )
2479 {
2480     /* Check input parameters */
2481     if (ctx == NULL){
2482         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
2483     }
2484 
2485     switch( ctx->MBEDTLS_PRIVATE(padding) )
2486     {
2487 #if defined(MBEDTLS_PKCS1_V15)
2488         case MBEDTLS_RSA_PKCS_V15:
2489             return mbedtls_rsa_rsassa_pkcs1_v15_sign( ctx, f_rng, p_rng, md_alg,
2490                     hashlen, hash, sig );
2491 #endif
2492 
2493 #if defined(MBEDTLS_PKCS1_V21)
2494         case MBEDTLS_RSA_PKCS_V21:
2495             return mbedtls_rsa_rsassa_pss_sign( ctx, f_rng, p_rng, md_alg,
2496                     hashlen, hash, sig );
2497 #endif
2498 
2499         default:
2500             return( MBEDTLS_ERR_RSA_INVALID_PADDING );
2501     }
2502 }
2503 
2504 #if defined(MBEDTLS_PKCS1_V21)
2505 /*
2506  * Implementation of the PKCS#1 v2.1 RSASSA-PSS-VERIFY function
2507  */
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)2508 int mbedtls_rsa_rsassa_pss_verify_ext( mbedtls_rsa_context *ctx,
2509                                mbedtls_md_type_t md_alg,
2510                                unsigned int hashlen,
2511                                const unsigned char *hash,
2512                                mbedtls_md_type_t mgf1_hash_id,
2513                                int expected_salt_len,
2514                                const unsigned char *sig )
2515 {
2516     CCRsaPubUserContext_t        *UserContext_ptr = NULL;
2517     CCRsaUserPubKey_t            *UserPubKey_ptr = NULL;
2518     CCRsaHashOpMode_t            hashOpMode;
2519     int                          saltLen = CC_RSA_VERIFY_SALT_LENGTH_UNKNOWN;
2520     CCError_t Error = CC_OK;
2521     mbedtls_md_type_t mdType;
2522 
2523     /* Check input parameters */
2524     if (ctx == NULL){
2525         GOTO_END( CC_RSA_WRONG_PRIVATE_KEY_TYPE );
2526     }
2527 
2528     if (NULL == sig || NULL == hash)
2529     {
2530         GOTO_END( CC_RSA_INVALID_PTR_ERROR );
2531     }
2532 
2533     if (( md_alg != MBEDTLS_MD_NONE ) && ( mgf1_hash_id != MBEDTLS_MD_NONE ) && (md_alg != mgf1_hash_id)){
2534             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
2535     }
2536 
2537     mdType = ( md_alg != MBEDTLS_MD_NONE )? md_alg : mgf1_hash_id;
2538 
2539     //if md_alg == MD_NONE, use mgf1_hash_id, if no -> md_alg=mgf1_hash_id
2540     Error = convert_mbedtls_md_type_to_cc_rsa_hash_opmode(mdType,
2541                                                           1,
2542                                                           &hashOpMode,
2543                                                           &hashlen);
2544     if (Error != CC_OK)
2545     {
2546         GOTO_END(Error);
2547     }
2548     if (expected_salt_len != MBEDTLS_RSA_SALT_LEN_ANY)
2549     {
2550         saltLen = expected_salt_len;
2551     }
2552     UserPubKey_ptr = (CCRsaUserPubKey_t *)mbedtls_calloc(1, sizeof(CCRsaUserPubKey_t));
2553     if (NULL == UserPubKey_ptr)
2554     {
2555         GOTO_CLEANUP( CC_OUT_OF_RESOURCE_ERROR );
2556     }
2557     UserContext_ptr = (CCRsaPubUserContext_t *)mbedtls_calloc(1, sizeof(CCRsaPubUserContext_t));
2558     if (NULL == UserContext_ptr)
2559     {
2560         GOTO_CLEANUP( CC_OUT_OF_RESOURCE_ERROR );
2561     }
2562     if ( (Error = validate_mbedtls_rsa_context_public_key(ctx)) != CC_OK )
2563     {
2564         GOTO_CLEANUP( Error );
2565     }
2566     Error = build_cc_pubkey(ctx, UserPubKey_ptr);
2567     if (CC_OK != Error)
2568     {
2569         GOTO_CLEANUP(Error);
2570     }
2571 
2572     Error = CC_RsaPssVerify(UserContext_ptr,UserPubKey_ptr,hashOpMode,CC_PKCS1_MGF1,saltLen, (uint8_t *)hash, hashlen, (uint8_t *)sig);
2573 
2574 Cleanup:
2575         mbedtls_free(UserPubKey_ptr);
2576         mbedtls_free(UserContext_ptr);
2577 End:
2578         return error_mapping_cc_to_mbedtls_rsa(Error, CC_RSA_OP_PUBLIC);
2579 }
2580 
2581 /*
2582  * Simplified PKCS#1 v2.1 RSASSA-PSS-VERIFY function
2583  */
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)2584 int mbedtls_rsa_rsassa_pss_verify( mbedtls_rsa_context *ctx,
2585         mbedtls_md_type_t md_alg,
2586         unsigned int hashlen,
2587         const unsigned char *hash,
2588         const unsigned char *sig )
2589 {
2590     /* Check input parameters */
2591     if (ctx == NULL){
2592         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
2593     }
2594 
2595     if (( ctx->MBEDTLS_PRIVATE(hash_id) != MBEDTLS_MD_NONE ) && ((mbedtls_md_type_t) ctx->MBEDTLS_PRIVATE(hash_id) != md_alg)){
2596             return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2597     }
2598     return( mbedtls_rsa_rsassa_pss_verify_ext( ctx,
2599                 md_alg, hashlen, hash,
2600                 md_alg, MBEDTLS_RSA_SALT_LEN_ANY,
2601                 sig ) );
2602 
2603 }
2604 #endif /* MBEDTLS_PKCS1_V21 */
2605 
2606 #if defined(MBEDTLS_PKCS1_V15)
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)2607 int mbedtls_rsa_rsassa_pkcs1_v15_verify( mbedtls_rsa_context *ctx,
2608         mbedtls_md_type_t md_alg,
2609         unsigned int hashlen,
2610         const unsigned char *hash,
2611         const unsigned char *sig )
2612 {
2613     CCRsaPubUserContext_t        *UserContext_ptr = NULL;
2614     CCRsaUserPubKey_t            *UserPubKey_ptr = NULL;
2615     CCRsaHashOpMode_t            hashOpMode;
2616     size_t                       hashOutputSizeBytes = 0;
2617     CCError_t                    Error = CC_OK;
2618 
2619     /* Check input parameters */
2620     if (ctx == NULL){
2621         GOTO_END( CC_RSA_INVALID_PTR_ERROR );
2622     }
2623 
2624     if ( MBEDTLS_MD_NONE == md_alg )
2625     {
2626         mbedtls_printf("DVIR: ERROR: MBEDTLS_MD_NONE is not supported!\r\n");
2627         GOTO_END(CC_RSA_HASH_ILLEGAL_OPERATION_MODE_ERROR); /* MD_NONE is not supported in cryptocell */
2628     }
2629     Error = convert_mbedtls_md_type_to_cc_rsa_hash_opmode(md_alg,
2630                                                            1,
2631                                                            &hashOpMode,
2632                                                            &hashOutputSizeBytes);
2633     if (Error != CC_OK)
2634     {
2635         GOTO_END(Error);
2636     }
2637     if ( hashOutputSizeBytes != hashlen )
2638     {
2639         hashlen = hashOutputSizeBytes;
2640     }
2641     if (NULL == sig || NULL == hash)
2642     {
2643         GOTO_END( CC_RSA_INVALID_PTR_ERROR );
2644     }
2645     UserPubKey_ptr = (CCRsaUserPubKey_t *)mbedtls_calloc(1, sizeof(CCRsaUserPubKey_t));
2646     if (NULL == UserPubKey_ptr)
2647     {
2648         GOTO_CLEANUP( CC_OUT_OF_RESOURCE_ERROR );
2649     }
2650     UserContext_ptr = (CCRsaPubUserContext_t *)mbedtls_calloc(1, sizeof(CCRsaPubUserContext_t));
2651     if (NULL == UserContext_ptr)
2652     {
2653         GOTO_CLEANUP( CC_OUT_OF_RESOURCE_ERROR );
2654     }
2655     if ( (Error = validate_mbedtls_rsa_context_public_key(ctx)) != CC_OK )
2656     {
2657         GOTO_CLEANUP( Error );
2658     }
2659     Error = build_cc_pubkey(ctx, UserPubKey_ptr);
2660     if (CC_OK != Error)
2661     {
2662         GOTO_CLEANUP(Error);
2663     }
2664     Error = CC_RsaPkcs1V15Verify(UserContext_ptr,
2665                                     UserPubKey_ptr,
2666                                     hashOpMode,
2667                                     (uint8_t *)hash,
2668                                     hashlen,
2669                                     (uint8_t *)sig);
2670 Cleanup:
2671     mbedtls_free(UserPubKey_ptr);
2672     mbedtls_free(UserContext_ptr);
2673 End:
2674     return error_mapping_cc_to_mbedtls_rsa(Error, CC_RSA_OP_PUBLIC);
2675 
2676 }
2677 #endif /* MBEDTLS_PKCS1_V15 */
2678 
2679 /*
2680  * Do an RSA operation and check the message digest
2681  */
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)2682 int mbedtls_rsa_pkcs1_verify( mbedtls_rsa_context *ctx,
2683         mbedtls_md_type_t md_alg,
2684         unsigned int hashlen,
2685         const unsigned char *hash,
2686         const unsigned char *sig )
2687 {
2688     /* Check input parameters */
2689     if (ctx == NULL){
2690         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
2691     }
2692 
2693     switch( ctx->MBEDTLS_PRIVATE(padding) )
2694     {
2695 #if defined(MBEDTLS_PKCS1_V15)
2696         case MBEDTLS_RSA_PKCS_V15:
2697             return mbedtls_rsa_rsassa_pkcs1_v15_verify( ctx, md_alg,
2698                     hashlen, hash, sig );
2699 #endif
2700 
2701 #if defined(MBEDTLS_PKCS1_V21)
2702         case MBEDTLS_RSA_PKCS_V21:
2703             return mbedtls_rsa_rsassa_pss_verify( ctx, md_alg,
2704                     hashlen, hash, sig );
2705 #endif
2706 
2707         default:
2708             return( MBEDTLS_ERR_RSA_INVALID_PADDING );
2709     }
2710 }
2711 
2712 /*
2713  * Copy the components of an RSA key
2714  */
mbedtls_rsa_copy(mbedtls_rsa_context * dst,const mbedtls_rsa_context * src)2715 int mbedtls_rsa_copy( mbedtls_rsa_context *dst, const mbedtls_rsa_context *src )
2716 {
2717     int ret;
2718 
2719     if ((dst == NULL) || (src == NULL)){
2720         return MBEDTLS_ERR_RSA_BAD_INPUT_DATA;
2721     }
2722 
2723     dst->MBEDTLS_PRIVATE(ver) = src->MBEDTLS_PRIVATE(ver);
2724     dst->MBEDTLS_PRIVATE(len) = src->MBEDTLS_PRIVATE(len);
2725 
2726     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->MBEDTLS_PRIVATE(N), &src->MBEDTLS_PRIVATE(N) ) );
2727     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->MBEDTLS_PRIVATE(E), &src->MBEDTLS_PRIVATE(E) ) );
2728 
2729     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->MBEDTLS_PRIVATE(D), &src->MBEDTLS_PRIVATE(D) ) );
2730     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->MBEDTLS_PRIVATE(P), &src->MBEDTLS_PRIVATE(P) ) );
2731     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->MBEDTLS_PRIVATE(Q), &src->MBEDTLS_PRIVATE(Q) ) );
2732     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->MBEDTLS_PRIVATE(DP), &src->MBEDTLS_PRIVATE(DP) ) );
2733     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->MBEDTLS_PRIVATE(DQ), &src->MBEDTLS_PRIVATE(DQ) ) );
2734     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->MBEDTLS_PRIVATE(QP), &src->MBEDTLS_PRIVATE(QP) ) );
2735 
2736     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->MBEDTLS_PRIVATE(RN), &src->MBEDTLS_PRIVATE(RN) ) );
2737     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->MBEDTLS_PRIVATE(RP), &src->MBEDTLS_PRIVATE(RP) ) );
2738     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->MBEDTLS_PRIVATE(RQ), &src->MBEDTLS_PRIVATE(RQ) ) );
2739 
2740     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->MBEDTLS_PRIVATE(NP), &src->MBEDTLS_PRIVATE(NP) ) );
2741     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->MBEDTLS_PRIVATE(BPP), &src->MBEDTLS_PRIVATE(BPP) ) );
2742     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->MBEDTLS_PRIVATE(BQP), &src->MBEDTLS_PRIVATE(BQP) ) );
2743 
2744     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->MBEDTLS_PRIVATE(Vi), &src->MBEDTLS_PRIVATE(Vi) ) );
2745     MBEDTLS_MPI_CHK( mbedtls_mpi_copy( &dst->MBEDTLS_PRIVATE(Vf), &src->MBEDTLS_PRIVATE(Vf) ) );
2746 
2747     dst->MBEDTLS_PRIVATE(padding) = src->MBEDTLS_PRIVATE(padding);
2748     dst->MBEDTLS_PRIVATE(hash_id) = src->MBEDTLS_PRIVATE(hash_id);
2749 
2750 cleanup:
2751     if( ret != 0 )
2752         mbedtls_rsa_free( dst );
2753 
2754     return( ret );
2755 }
2756 
2757 /*
2758  * Free the components of an RSA key
2759  */
mbedtls_rsa_free(mbedtls_rsa_context * ctx)2760 void mbedtls_rsa_free( mbedtls_rsa_context *ctx )
2761 {
2762     if (ctx != NULL) {
2763         mbedtls_mpi_free( &ctx->MBEDTLS_PRIVATE(BQP) ); mbedtls_mpi_free( &ctx->MBEDTLS_PRIVATE(BPP) ); mbedtls_mpi_free( &ctx->MBEDTLS_PRIVATE(NP) );
2764         mbedtls_mpi_free( &ctx->MBEDTLS_PRIVATE(Vi) ); mbedtls_mpi_free( &ctx->MBEDTLS_PRIVATE(Vf) );
2765         mbedtls_mpi_free( &ctx->MBEDTLS_PRIVATE(RQ) ); mbedtls_mpi_free( &ctx->MBEDTLS_PRIVATE(RP) ); mbedtls_mpi_free( &ctx->MBEDTLS_PRIVATE(RN) );
2766         mbedtls_mpi_free( &ctx->MBEDTLS_PRIVATE(QP) ); mbedtls_mpi_free( &ctx->MBEDTLS_PRIVATE(DQ) ); mbedtls_mpi_free( &ctx->MBEDTLS_PRIVATE(DP) );
2767         mbedtls_mpi_free( &ctx->MBEDTLS_PRIVATE(Q)  ); mbedtls_mpi_free( &ctx->MBEDTLS_PRIVATE(P)  ); mbedtls_mpi_free( &ctx->MBEDTLS_PRIVATE(D) );
2768         mbedtls_mpi_free( &ctx->MBEDTLS_PRIVATE(E)  ); mbedtls_mpi_free( &ctx->MBEDTLS_PRIVATE(N)  );
2769 
2770 #if defined(MBEDTLS_THREADING_C)
2771         mbedtls_mutex_free( &ctx->MBEDTLS_PRIVATE(mutex) );
2772 #endif
2773     }
2774 }
2775 /**************************************************************************************/
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)2776 int mbedtls_rsa_import( mbedtls_rsa_context *ctx,
2777                         const mbedtls_mpi *N,
2778                         const mbedtls_mpi *P, const mbedtls_mpi *Q,
2779                         const mbedtls_mpi *D, const mbedtls_mpi *E )
2780 {
2781     int ret;
2782 
2783     /* Check input parameters */
2784     if (ctx == NULL){
2785         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
2786     }
2787 
2788     if( ( N != NULL && ( ret = mbedtls_mpi_copy( &ctx->MBEDTLS_PRIVATE(N), N ) ) != 0 ) ||
2789         ( P != NULL && ( ret = mbedtls_mpi_copy( &ctx->MBEDTLS_PRIVATE(P), P ) ) != 0 ) ||
2790         ( Q != NULL && ( ret = mbedtls_mpi_copy( &ctx->MBEDTLS_PRIVATE(Q), Q ) ) != 0 ) ||
2791         ( D != NULL && ( ret = mbedtls_mpi_copy( &ctx->MBEDTLS_PRIVATE(D), D ) ) != 0 ) ||
2792         ( E != NULL && ( ret = mbedtls_mpi_copy( &ctx->MBEDTLS_PRIVATE(E), E ) ) != 0 ) )
2793     {
2794         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
2795     }
2796 
2797     if( N != NULL )
2798         ctx->MBEDTLS_PRIVATE(len) = mbedtls_mpi_size( &ctx->MBEDTLS_PRIVATE(N) );
2799 
2800     return( 0 );
2801 }
2802 
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)2803 int mbedtls_rsa_import_raw( mbedtls_rsa_context *ctx,
2804                             unsigned char const *N, size_t N_len,
2805                             unsigned char const *P, size_t P_len,
2806                             unsigned char const *Q, size_t Q_len,
2807                             unsigned char const *D, size_t D_len,
2808                             unsigned char const *E, size_t E_len )
2809 {
2810     int ret = 0;
2811 
2812     if (ctx == NULL){
2813         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
2814     }
2815 
2816     if( N != NULL )
2817     {
2818         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->MBEDTLS_PRIVATE(N), N, N_len ) );
2819         ctx->MBEDTLS_PRIVATE(len) = mbedtls_mpi_size( &ctx->MBEDTLS_PRIVATE(N) );
2820     }
2821 
2822     if( P != NULL )
2823         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->MBEDTLS_PRIVATE(P), P, P_len ) );
2824 
2825     if( Q != NULL )
2826         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->MBEDTLS_PRIVATE(Q), Q, Q_len ) );
2827 
2828     if( D != NULL )
2829         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->MBEDTLS_PRIVATE(D), D, D_len ) );
2830 
2831     if( E != NULL )
2832         MBEDTLS_MPI_CHK( mbedtls_mpi_read_binary( &ctx->MBEDTLS_PRIVATE(E), E, E_len ) );
2833 
2834 cleanup:
2835 
2836     if( ret != 0 )
2837         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
2838 
2839     return( 0 );
2840 }
2841 
2842 /*
2843  * calculate crt parameters from the non crt
2844  * input - non crt key params P, Q, D
2845  * output - crt params DP, DQ, QP
2846  */
mbedtls_alt_rsa_deduce_crt(const mbedtls_mpi * P,const mbedtls_mpi * Q,const mbedtls_mpi * D,mbedtls_mpi * DP,mbedtls_mpi * DQ,mbedtls_mpi * QP)2847 static int mbedtls_alt_rsa_deduce_crt( const mbedtls_mpi *P, const mbedtls_mpi *Q,
2848                             const mbedtls_mpi *D, mbedtls_mpi *DP,
2849                             mbedtls_mpi *DQ, mbedtls_mpi *QP )
2850 {
2851     int ret = 0;
2852 
2853     const uint32_t rP =0;
2854     const uint32_t regNp = 1;
2855     const uint32_t rQ = 2;
2856     const uint32_t rT1 = 3;
2857     const uint32_t rT2 = 4;
2858     const uint32_t rT3 = 5;
2859     const uint32_t rD = 6;
2860 
2861     uint32_t regCount = 7;
2862 
2863     uint32_t* pTempBuf;
2864     uint32_t tempBufSize;
2865     uint32_t sizeBitsP;
2866 
2867     if ((DP == NULL) || (DQ == NULL) || (QP == NULL) || (P == NULL) || (Q == NULL) || (D == NULL)){
2868             return MBEDTLS_ERR_MPI_BAD_INPUT_DATA;
2869     }
2870 
2871     tempBufSize = P->MBEDTLS_PRIVATE(n);
2872     sizeBitsP = P->MBEDTLS_PRIVATE(n)*sizeof(uint32_t)*8;
2873 
2874     ret = PkaInitAndMutexLock(2*sizeBitsP, &regCount);
2875     if (ret != 0)
2876     {
2877             return MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
2878     }
2879 
2880     if( ( pTempBuf = (uint32_t*)mbedtls_calloc( tempBufSize, sizeof(uint32_t) ) ) == NULL ) {
2881         ret = MBEDTLS_ERR_MPI_ALLOC_FAILED;
2882         return( ret);
2883     }
2884 
2885     PKA_SET_REG_SIZE(sizeBitsP, PLEN_ID);
2886     PkaCopyDataIntoPkaReg(rP, REG_LEN_ID, P->MBEDTLS_PRIVATE(p), P->MBEDTLS_PRIVATE(n));
2887     PkaCopyDataIntoPkaReg(rQ, REG_LEN_ID, Q->MBEDTLS_PRIVATE(p), Q->MBEDTLS_PRIVATE(n));
2888     PkaCopyDataIntoPkaReg(rD, REG_LEN_ID, D->MBEDTLS_PRIVATE(p), D->MBEDTLS_PRIVATE(n));
2889 
2890     ret = PkaCalcNpIntoPkaReg(PLEN_ID, sizeBitsP, rP/*regN*/, regNp,  rT1, rT2 );
2891     if (ret != 0)
2892     {
2893             ret = MBEDTLS_ERR_MPI_NOT_ACCEPTABLE;
2894             goto cleanup;
2895     }
2896 
2897     /* DP = D mod P-1 */
2898     PKA_COPY(REG_LEN_ID, rT1, rD);     // rT1 = D
2899     PKA_SUB_IM(MOD_LEN_ID, rP, rP, 1); // P -= 1 (rP)
2900     PKA_DIV(MOD_LEN_ID, rT2, rT1, rP); // DP = rT1 = rT1 mod P
2901 
2902     /* DQ = D mod Q-1 */
2903     PKA_COPY(REG_LEN_ID, rT2, rD);     // rT2 = D
2904     PKA_SUB_IM(MOD_LEN_ID, rQ, rQ, 1); // Q -= 1 (rQ)
2905     PKA_DIV(MOD_LEN_ID, rT3, rT2, rQ); // DQ = rT2 = rT2 mod Q
2906 
2907     /* QP = Q^{-1} mod P */
2908     PKA_ADD_IM(MOD_LEN_ID, rP, rP, 1);
2909     PKA_ADD_IM(MOD_LEN_ID, rQ, rQ, 1);
2910     PKA_MOD_INV(PLEN_ID, rT3/*res*/, rQ);  // rT3 = Q^-1 mod P
2911     PkaCopyDataFromPkaReg(pTempBuf, P->MBEDTLS_PRIVATE(n), rT1);
2912     MBEDTLS_MPI_CHK(mbedtls_rsa_uint32_buf_to_mpi( DP, pTempBuf, P->MBEDTLS_PRIVATE(n) ));
2913 
2914     PkaCopyDataFromPkaReg(pTempBuf, P->MBEDTLS_PRIVATE(n), rT2);
2915     MBEDTLS_MPI_CHK(mbedtls_rsa_uint32_buf_to_mpi( DQ, pTempBuf, P->MBEDTLS_PRIVATE(n) ));
2916 
2917     PkaCopyDataFromPkaReg (pTempBuf, P->MBEDTLS_PRIVATE(n), rT3);
2918     MBEDTLS_MPI_CHK(mbedtls_rsa_uint32_buf_to_mpi( QP, pTempBuf, P->MBEDTLS_PRIVATE(n) ));
2919 
2920 cleanup:
2921     PkaFinishAndMutexUnlock(regCount);
2922     mbedtls_free(pTempBuf);
2923     return ret;
2924 }
2925 
mbedtls_rsa_complete(mbedtls_rsa_context * ctx)2926 int mbedtls_rsa_complete( mbedtls_rsa_context *ctx )
2927 {
2928     int ret = 0;
2929 
2930     int have_N;
2931     int have_P;
2932     int have_Q;
2933     int have_D;
2934     int have_E;
2935     int have_DP;
2936     int have_DQ;
2937     int have_QP;
2938 
2939     /*
2940     * 1. The user may insert N, D, E and the complete function will not derive the P and Q from it.
2941     * 2. If user inserted P, Q it means he wants to work in CRT mode:
2942     * we will derive the CRT values from it, we will not derive the D from it.
2943     * 3. If user inserted D, it means he wants to work in NON SRT mode:
2944     * we will not derive P, Q from it
2945     * 4. If N is missing, wi'll calculated it if there is enough information, but it will be done by sw with lower performance
2946     */
2947 
2948     int is_priv;
2949 
2950     int is_pub;
2951     int crt_missing;
2952 
2953     /* Check input parameters */
2954     if (ctx == NULL){
2955         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
2956     }
2957 
2958 
2959     have_N = mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(N), 0 ) != 0;
2960     have_P = mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(P), 0 ) != 0;
2961     have_Q = mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(Q), 0 ) != 0;
2962     have_D = mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(D), 0 ) != 0;
2963     have_E = mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(E), 0 ) != 0;
2964     have_DP = mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(DP), 0 ) != 0;
2965     have_DQ = mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(DQ), 0 ) != 0;
2966     have_QP = mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(QP), 0 ) != 0;
2967 
2968     /*
2969     * 1. The user may insert N, D, E and the complete function will not derive the P and Q from it.
2970     * 2. If user inserted P, Q it means he wants to work in CRT mode:
2971     * we will derive the CRT values from it, we will not derive the D from it.
2972     * 3. If user inserted D, it means he wants to work in NON SRT mode:
2973     * we will not derive P, Q from it
2974     * 4. If N is missing, wi'll calculated it if there is enough information, but it will be done by sw with lower performance
2975     */
2976 
2977 #if defined(MBEDTLS_RSA_NO_CRT)
2978     is_priv    =   have_D && have_E && (have_N || (have_P && have_Q));
2979 #else
2980     is_priv    =   have_D && have_E && have_P && have_Q;
2981 #endif
2982     is_pub     =   have_N && !have_P && !have_Q && !have_D && have_E;
2983     crt_missing =  !have_DP && !have_DQ && !have_QP;
2984 
2985 
2986     if( !is_priv && !is_pub ){
2987             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
2988     }
2989 
2990     /* Function should get or all DP,QP and DQ or no one of them*/
2991     if (((!have_DP) || (!have_DQ) || (!have_QP)) && (!crt_missing)){
2992         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
2993     }
2994     /*
2995      * Step 1: Deduce N if P, Q are provided.
2996      */
2997 
2998     //if N is requested to be calculated from P and Q, it will be done by sw
2999     if( !have_N && have_P && have_Q )
3000     {
3001         if( ( ret = mbedtls_mpi_mul_mpi( &ctx->MBEDTLS_PRIVATE(N), &ctx->MBEDTLS_PRIVATE(P),
3002                                          &ctx->MBEDTLS_PRIVATE(Q) ) ) != 0 )
3003         {
3004             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
3005         }
3006 
3007         ctx->MBEDTLS_PRIVATE(len) = mbedtls_mpi_size( &ctx->MBEDTLS_PRIVATE(N) );
3008     }
3009 
3010     /*
3011      * Step 2: Deduce all additional parameters specific
3012      *         to our current RSA implementation.
3013      */
3014 
3015 #if !defined(MBEDTLS_RSA_NO_CRT)
3016 
3017     if (( is_priv ) && (crt_missing))
3018     {
3019         ret = mbedtls_alt_rsa_deduce_crt( &ctx->MBEDTLS_PRIVATE(P),  &ctx->MBEDTLS_PRIVATE(Q),  &ctx->MBEDTLS_PRIVATE(D),
3020                                       &ctx->MBEDTLS_PRIVATE(DP), &ctx->MBEDTLS_PRIVATE(DQ), &ctx->MBEDTLS_PRIVATE(QP) );
3021         if( ret != 0 )
3022             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
3023     }
3024 #endif /* MBEDTLS_RSA_NO_CRT */
3025 
3026     /*
3027      * Step 3: Basic sanity checks
3028      */
3029 
3030     return( rsa_check_context_alt( ctx, is_priv, 1 ) );
3031 }
3032 
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)3033 int mbedtls_rsa_export_raw( const mbedtls_rsa_context *ctx,
3034                             unsigned char *N, size_t N_len,
3035                             unsigned char *P, size_t P_len,
3036                             unsigned char *Q, size_t Q_len,
3037                             unsigned char *D, size_t D_len,
3038                             unsigned char *E, size_t E_len )
3039 {
3040     int ret = 0;
3041     int is_priv;
3042 
3043     /* Check input parameters */
3044     if (ctx == NULL){
3045         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
3046     }
3047 
3048     /* Check if key is private or public */
3049     is_priv =
3050         mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(N), 0 ) != 0 &&
3051         mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(P), 0 ) != 0 &&
3052         mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(Q), 0 ) != 0 &&
3053         mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(D), 0 ) != 0 &&
3054         mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(E), 0 ) != 0;
3055 
3056     if( !is_priv )
3057     {
3058         /* If we're trying to export private parameters for a public key,
3059          * something must be wrong. */
3060         if( P != NULL || Q != NULL || D != NULL )
3061             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
3062 
3063     }
3064 
3065     if( N != NULL )
3066         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->MBEDTLS_PRIVATE(N), N, N_len ) );
3067 
3068     if( P != NULL )
3069         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->MBEDTLS_PRIVATE(P), P, P_len ) );
3070 
3071     if( Q != NULL )
3072         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->MBEDTLS_PRIVATE(Q), Q, Q_len ) );
3073 
3074     if( D != NULL )
3075         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->MBEDTLS_PRIVATE(D), D, D_len ) );
3076 
3077     if( E != NULL )
3078         MBEDTLS_MPI_CHK( mbedtls_mpi_write_binary( &ctx->MBEDTLS_PRIVATE(E), E, E_len ) );
3079 
3080 cleanup:
3081 
3082     return( ret );
3083 }
3084 
mbedtls_rsa_export(const mbedtls_rsa_context * ctx,mbedtls_mpi * N,mbedtls_mpi * P,mbedtls_mpi * Q,mbedtls_mpi * D,mbedtls_mpi * E)3085 int mbedtls_rsa_export( const mbedtls_rsa_context *ctx,
3086                         mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q,
3087                         mbedtls_mpi *D, mbedtls_mpi *E )
3088 {
3089     int ret = 0;
3090     int is_priv;
3091 
3092     /* Check input parameters */
3093     if (ctx == NULL){
3094         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
3095     }
3096 
3097     /* Check if key is private or public */
3098     is_priv =
3099         mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(N), 0 ) != 0 &&
3100         mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(P), 0 ) != 0 &&
3101         mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(Q), 0 ) != 0 &&
3102         mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(D), 0 ) != 0 &&
3103         mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(E), 0 ) != 0;
3104 
3105    if( !is_priv )
3106     {
3107         /* If we're trying to export private parameters for a public key,
3108          * something must be wrong. */
3109         if( P != NULL || Q != NULL || D != NULL )
3110             return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
3111 
3112     }
3113 
3114     /* Export all requested core parameters. */
3115     if( ( N != NULL && ( ret = mbedtls_mpi_copy( N, &ctx->MBEDTLS_PRIVATE(N) ) ) != 0 ) ||
3116         ( P != NULL && ( ret = mbedtls_mpi_copy( P, &ctx->MBEDTLS_PRIVATE(P) ) ) != 0 ) ||
3117         ( Q != NULL && ( ret = mbedtls_mpi_copy( Q, &ctx->MBEDTLS_PRIVATE(Q) ) ) != 0 ) ||
3118         ( D != NULL && ( ret = mbedtls_mpi_copy( D, &ctx->MBEDTLS_PRIVATE(D) ) ) != 0 ) ||
3119         ( E != NULL && ( ret = mbedtls_mpi_copy( E, &ctx->MBEDTLS_PRIVATE(E) ) ) != 0 ) )
3120     {
3121         return( ret );
3122     }
3123 
3124     return( ret );
3125 }
3126 
mbedtls_rsa_export_crt(const mbedtls_rsa_context * ctx,mbedtls_mpi * DP,mbedtls_mpi * DQ,mbedtls_mpi * QP)3127 int mbedtls_rsa_export_crt( const mbedtls_rsa_context *ctx,
3128                             mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP )
3129 {
3130     int ret = 0;
3131     int is_priv;
3132 
3133     /* Check input parameters */
3134     if (ctx == NULL){
3135         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
3136     }
3137 
3138     /* Check if key is private or public */
3139     is_priv =
3140         mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(N), 0 ) != 0 &&
3141         mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(P), 0 ) != 0 &&
3142         mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(Q), 0 ) != 0 &&
3143         mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(D), 0 ) != 0 &&
3144         mbedtls_mpi_cmp_int( &ctx->MBEDTLS_PRIVATE(E), 0 ) != 0;
3145 
3146     if( !is_priv )
3147         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA );
3148 
3149 #if !defined(MBEDTLS_RSA_NO_CRT)
3150     /* Export all requested blinding parameters. */
3151     if( ( DP != NULL && ( ret = mbedtls_mpi_copy( DP, &ctx->MBEDTLS_PRIVATE(DP) ) ) != 0 ) ||
3152         ( DQ != NULL && ( ret = mbedtls_mpi_copy( DQ, &ctx->MBEDTLS_PRIVATE(DQ) ) ) != 0 ) ||
3153         ( QP != NULL && ( ret = mbedtls_mpi_copy( QP, &ctx->MBEDTLS_PRIVATE(QP) ) ) != 0 ) )
3154     {
3155         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
3156     }
3157 #else
3158     if( ( ret = mbedtls_alt_rsa_deduce_crt( &ctx->MBEDTLS_PRIVATE(P), &ctx->MBEDTLS_PRIVATE(Q), &ctx->MBEDTLS_PRIVATE(D),
3159                                         DP, DQ, QP ) ) != 0 )
3160     {
3161         return( MBEDTLS_ERR_RSA_BAD_INPUT_DATA + ret );
3162     }
3163 #endif
3164 
3165     return( 0 );
3166 }
3167 
3168 /*
3169  * Get length in bytes of RSA modulus. If ctx is NULL the length output will be 0
3170  */
3171 
mbedtls_rsa_get_len(const mbedtls_rsa_context * ctx)3172 size_t mbedtls_rsa_get_len( const mbedtls_rsa_context *ctx )
3173 {
3174     if (ctx == NULL){
3175         return 0;
3176     }
3177 
3178     return( ctx->MBEDTLS_PRIVATE(len) );
3179 }
3180 
3181 /**************************************************************************************/
3182 
3183 #endif /*  defined (MBEDTLS_RSA_ALT)  */
3184 
3185 #endif /*  defined(MBEDTLS_RSA_C)  */
3186