1 /*
2  * FreeRTOS V202212.00
3  * Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
4  *
5  * Permission is hereby granted, free of charge, to any person obtaining a copy of
6  * this software and associated documentation files (the "Software"), to deal in
7  * the Software without restriction, including without limitation the rights to
8  * use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
9  * the Software, and to permit persons to whom the Software is furnished to do so,
10  * subject to the following conditions:
11  *
12  * The above copyright notice and this permission notice shall be included in all
13  * copies or substantial portions of the Software.
14  *
15  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16  * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
17  * FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
18  * COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
19  * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
20  * CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21  *
22  * https://www.FreeRTOS.org
23  * https://github.com/FreeRTOS
24  *
25  */
26 
27 #include "logging_levels.h"
28 
29 #ifndef LIBRARY_LOG_NAME
30     #define LIBRARY_LOG_NAME    "MbedTLSRNGP11"
31 #endif /* LIBRARY_LOG_NAME */
32 
33 #ifndef LIBRARY_LOG_LEVEL
34     #define LIBRARY_LOG_LEVEL    LOG_ERROR
35 #endif /* LIBRARY_LOG_LEVEL */
36 
37 #include "logging_stack.h"
38 
39 /**
40  * @file mbedtls_rng_pkcs11.c
41  * @brief Implements an mbedtls RNG callback using the PKCS#11 API
42  */
43 
44 #include "core_pkcs11_config.h"
45 #include "core_pkcs11.h"
46 
47 /*-----------------------------------------------------------*/
48 
lMbedCryptoRngCallbackPKCS11(void * pvCtx,unsigned char * pucOutput,size_t uxLen)49 int lMbedCryptoRngCallbackPKCS11( void * pvCtx,
50                                   unsigned char * pucOutput,
51                                   size_t uxLen )
52 {
53     int lRslt;
54     CK_FUNCTION_LIST_PTR pxFunctionList = NULL;
55     CK_SESSION_HANDLE * pxSessionHandle = ( CK_SESSION_HANDLE * ) pvCtx;
56 
57     if( pucOutput == NULL )
58     {
59         lRslt = -1;
60     }
61     else if( pvCtx == NULL )
62     {
63         lRslt = -1;
64         LogError( ( "pvCtx must not be NULL." ) );
65     }
66     else
67     {
68         lRslt = ( int ) C_GetFunctionList( &pxFunctionList );
69     }
70 
71     if( ( lRslt != CKR_OK ) ||
72         ( pxFunctionList == NULL ) ||
73         ( pxFunctionList->C_GenerateRandom == NULL ) )
74     {
75         lRslt = -1;
76     }
77     else
78     {
79         lRslt = ( int ) pxFunctionList->C_GenerateRandom( *pxSessionHandle, pucOutput, uxLen );
80     }
81 
82     return lRslt;
83 }
84 
85 /*-----------------------------------------------------------*/
86