Giter Site home page Giter Site logo

corepkcs11's Introduction

corePKCS11 Library

API Documentation Pages for current and previous releases of this library can be found here

PKCS #11 is a standardized and widely used API for manipulating common cryptographic objects. It is important because the functions it specifies allow application software to use, create, modify, and delete cryptographic objects, without ever exposing those objects to the application’s memory. For example, FreeRTOS AWS reference integrations use a small subset of the PKCS #11 API to, among other things, access the secret (private) key necessary to create a network connection that is authenticated and secured by the Transport Layer Security (TLS) protocol – without the application ever ‘seeing’ the key.

The Cryptoki or PKCS #11 standard defines a platform-independent API to manage and use cryptographic tokens. The name, "PKCS #11", is used interchangeably to refer to the API itself and the standard which defines it.

This repository contains a software based mock implementation of the PKCS #11 interface (API) that uses the cryptographic functionality provided by Mbed TLS. Using a software mock enables rapid development and flexibility, but it is expected that the mock be replaced by an implementation specific to your chosen secure key storage in production devices.

Only a subset of the PKCS #11 standard is implemented, with a focus on operations involving asymmetric keys, random number generation, and hashing.

The targeted use cases include certificate and key management for TLS authentication and code-sign signature verification, on small embedded devices.

corePKCS11 is implemented on PKCS #11 v2.4.0, the full PKCS #11 standard can be found on the oasis website.

This library has gone through code quality checks including verification that no function has a GNU Complexity score over 8, and checks against deviations from mandatory rules in the MISRA coding standard. Deviations from the MISRA C:2012 guidelines are documented under MISRA Deviations. This library has also undergone both static code analysis from Coverity static analysis and validation of memory safety through the CBMC automated reasoning tool.

See memory requirements for this library here.

corePKCS11 v3.6.1 source code is part of the FreeRTOS 202406.00 LTS release.

Purpose

Generally vendors for secure cryptoprocessors such as Trusted Platform Module (TPM), Hardware Security Module (HSM), Secure Element, or any other type of secure hardware enclave, distribute a PKCS #11 implementation with the hardware. The purpose of the corePKCS11 software only mock library is therefore to provide a non hardware specific PKCS #11 implementation that allows for rapid prototyping and development before switching to a cryptoprocessor specific PKCS #11 implementation in production devices.

Since the PKCS #11 interface is defined as part of the PKCS #11 specification replacing this library with another implementation should require little porting effort, as the interface will not change. The system tests distributed in this repository can be leveraged to verify the behavior of a different implementation is similar to corePKCS11.

corePKCS11 Configuration

The corePKCS11 library exposes preprocessor macros which must be defined prior to building the library. A list of all the configurations and their default values are defined in the doxygen documentation for this library.

Build Prerequisites

Library Usage

For building the library the following are required:

  • A C99 compiler
  • mbedcrypto library from mbedtls version 2.x or 3.x.
  • pkcs11 API header(s) available from OASIS or OpenSC

Optionally, variables from the pkcsFilePaths.cmake file may be referenced if your project uses cmake.

Integration and Unit Tests

In order to run the integration and unit test suites the following are dependencies are necessary:

  • C Compiler
  • CMake 3.13.0 or later
  • Ruby 2.0.0 or later required by CMock.
  • Python 3 required for configuring mbedtls.
  • git required for fetching dependencies.
  • GNU Make or Ninja

The mbedtls, CMock, and Unity libraries are downloaded and built automatically using the cmake FetchContent feature.

Coverage Measurement and Instrumentation

The following software is required to run the coverage target:

  • Linux, MacOS, or another POSIX-like environment.
  • A recent version of GCC or Clang with support for gcov-like coverage instrumentation.
  • gcov binary corresponding to your chosen compiler
  • lcov from the Linux Test Project
  • perl needed to run the lcov utility.

Coverage builds are validated on recent versions of Ubuntu Linux.

Running the Integration and Unit Tests

  1. Navigate to the root directory of this repository in your shell.

  2. Run cmake to construct a build tree: cmake -S test -B build

    • You may specify your preferred build tool by appending -G'Unix Makefiles' or -GNinja to the command above.
    • You may append -DUNITTEST=0 or -DSYSTEM_TESTS=0 to disable Unit Tests or Integration Tests respectively.
  3. Build the test binaries: cmake --build ./build --target all

  4. Run ctest --test-dir ./build or cmake --build ./build --target test to run the tests without capturing coverage.

  5. Run cmake --build ./build --target coverage to run the tests and capture coverage data.

CBMC

To learn more about CBMC and proofs specifically, review the training material here.

The test/cbmc/proofs directory contains CBMC proofs.

In order to run these proofs you will need to install CBMC and other tools by following the instructions here.

Reference examples

The FreeRTOS-Labs repository contains demos using the PKCS #11 library here using FreeRTOS on the Windows simulator platform. These can be used as reference examples for the library API.

Porting Guide

Documentation for porting corePKCS11 to a new platform can be found on the AWS docs web page.

corePKCS11 is not meant to be ported to projects that have a TPM, HSM, or other hardware for offloading crypto-processing. This library is specifically meant to be used for development and prototyping.

Related Example Implementations

These projects implement the PKCS #11 interface on real hardware and have similar behavior to corePKCS11. It is preferred to use these, over corePKCS11, as they allow for offloading Cryptography to separate hardware.

Documentation

Existing Documentation

For pre-generated documentation, please see the documentation linked in the locations below:

Location
AWS IoT Device SDK for Embedded C
FreeRTOS.org

Note that the latest included version of corePKCS11 may differ across repositories.

Generating Documentation

The Doxygen references were created using Doxygen version 1.9.6. To generate the Doxygen pages, please run the following command from the root of this repository:

doxygen docs/doxygen/config.doxyfile

Security

See CONTRIBUTING for more information.

License

This library is licensed under the MIT-0 License. See the LICENSE file.

corepkcs11's People

Contributors

aggarg avatar aggarw13 avatar amazon-auto avatar angelonakos avatar aniruddhakanhere avatar archigup avatar chinglee-iot avatar dachalco avatar giuspen avatar gshvang avatar karkhaz avatar kstribrnamzn avatar leegeth avatar lundinc2 avatar markrtuttle avatar muneebahmed10 avatar nrdg42 avatar paulbartell avatar ronakfof avatar sarenameas avatar skptak avatar xlin7799 avatar xuelix avatar yourslab avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

corepkcs11's Issues

C_GetAttributeValue does not set the attribute length in all cases

The attribute length is only set when the pointer is NULL. It should also be set in cases where the buffer is too large or too small.

From PKCS11-base-v2.40:
For each (type, pValue, ulValueLen) triple in the template, C_GetAttributeValue performs the following algorithm:

  1. If the specified attribute (i.e., the attribute specified by the type field) for the object cannot be revealed because the object is sensitive or unextractable, then the ulValueLen field in that triple is modified to hold the value CK_UNAVAILABLE_INFORMATION.
  2. Otherwise, if the specified value for the object is invalid (the object does not possess such an attribute), then the ulValueLen field in that triple is modified to hold the value CK_UNAVAILABLE_INFORMATION.
  3. Otherwise, if the pValue field has the value NULL_PTR, then the ulValueLen field is modified to hold the exact length of the specified attribute for the object.
  4. Otherwise, if the length specified in ulValueLen is large enough to hold the value of the specified attribute for the object, then that attribute is copied into the buffer located at pValue, and the ulValueLen field is modified to hold the exact length of the attribute.
  5. Otherwise, the ulValueLen field is modified to hold the value CK_UNAVAILABLE_INFORMATION.

How to build this project as a shared library?

Hi, I'm not sure where to ask questions, so I'm posting it here.

I'm trying to use this library as a test target in my project, but I'm not that familiar with c++ and I'm not sure how to build it as an .so file to use like softHSM and such.

Any help would be appriciated.

List of misspelled words

List of misspelled words,

  • existance is a common misspelling of: existence
  • Loggign is a misspell.
  • combile is a misspell.
./lexicon.txt:77: existance ==> existence
./source/portable/windows/core_pkcs11_pal.c:82: existance ==> existence
./source/portable/windows/core_pkcs11_pal.c:105: existance ==> existence
./source/portable/windows/core_pkcs11_pal.c:156: existance ==> existence
./source/portable/posix/core_pkcs11_pal.c:72: existance ==> existence
./source/portable/posix/core_pkcs11_pal.c:102: existance ==> existence
./source/portable/posix/core_pkcs11_pal.c:158: existance ==> existence
./source/portable/posix/core_pkcs11_pal.c:213: existance ==> existence
./test/system-test/system-tests/pkcs11_system_test.c:36: Loggign ==> Logging
./tools/cmock/coverage.cmake:55: combile ==> combine

corePKCS11 State Access Audit

Description

CorePKCS11 may rely upon state - state which may be accessible across FreeRTOS tasks. We want to verify the SDK is task/thread safe by ensuring that state access across FreeRTOS tasks is done so behind a synchronization mechanism.

Help is wanted to audit the repository for state which can be used outside of corePKSC11 task/thread or functions.

This work is being tracked by the FreeRTOS team however it may not be prioritized for some time. Your help in identifying problem state variables/structures will help us in correcting these issues faster. As always, if you are able to fix the issue, we appreciate the help and will gladly look at your PR.

Related Issues

Submodule 'mbedtls' Not Pulling In

I can't seem to get the submodule under "source/dependency/3rdparty/mbedtls" to pull in when doing the following under a custom embedded project:

git submodule add https://github.com/FreeRTOS/corePKCS11.git ec_lib/standard/corePKCS11/corePKCS11
git submodule update --init --recursive
git submodule update --recursive --remote

[submodule "source/dependency/3rdparty/mbedtls"]
path = source/dependency/3rdparty/mbedtls
url = https://github.com/ARMmbed/mbedtls.git
branch = v2.28.0
update = none

I see that the 'update' tag is set to 'none'. When cloning and updating the aws-iot-device-sdk-embedded-c the repository pulls in fine. Am I missing something when pulling the FreeRTOS cores individually?

Thanks!

Double PKCS11_FREE() in source/core_pkcs11.c

Double PKCS11_FREE() in source/core_pkcs11.c

  • Risk of double PKCS11_FREE() in source/core_pkcs11.c.

    • First in xGetSlotList() then followed by xInitializePkcs11Token()
  • The following 1 file has risk of double PKCS11_FREE().

    • corePKCS11.git:
      • source/core_pkcs11.c
      • function: CK_RV xInitializePkcs11Token( void );
      • function: CK_RV xGetSlotList( ... );
    • When use in aws-iot-device-sdk-embedded-C.git:
      • libraries/standard/corePKCS11/source/core_pkcs11.c
  • My comments are inline with the below code.

  • corePKCS11.git: main branch with commit hash a739b86 (tag: v3.0.1)

CK_RV xInitializePkcs11Token( void )
{
  CK_SLOT_ID * pxSlotId = NULL;
  ...

  if( ( xResult == CKR_OK ) || ( xResult == CKR_CRYPTOKI_ALREADY_INITIALIZED ) ) /* Taking TRUE branch */
  {
    /* Calling xGetSlotList() with pxSlotId == NULL.
     * If returned with (xResult != CKR_OK) and (pxSlotId != NULL) but 
     * pxSlotId memory already released at the end of xGetSlotList().
     * Now code trace to xGetSlotList().
     */
    xResult = xGetSlotList( &pxSlotId, &xSlotCount );  /* Returning with memory already released for pxSlotId */
  }

  if( ( xResult == CKR_OK ) &&
      ( NULL != pxFunctionList->C_GetTokenInfo ) &&
       ( NULL != pxFunctionList->C_InitToken ) )  /* Taking FALSE branch */
  {
    ...
  }

  if( pxTokenInfo != NULL )  /* Taking FALSE branch */
  {
    ...
  }

  if( pxSlotId != NULL )  /* Taking TRUE branch	*/
  {
    PKCS11_FREE( pxSlotId );  /* Attempt to free an already released memory */
  }

  return xResult;
}
CK_RV xGetSlotList( CK_SLOT_ID ** ppxSlotId, ... )
{
  CK_SLOT_ID * pxSlotId = NULL;
  ...

  if( xResult == CKR_OK )
  {
    if( *pxSlotCount == ( ( sizeof( CK_SLOT_ID ) * ( *pxSlotCount ) ) / ( sizeof( CK_SLOT_ID ) ) ) )
    {
        pxSlotId = PKCS11_MALLOC( sizeof( CK_SLOT_ID ) * ( *pxSlotCount ) );   /* Memory allocation OK */

        if( pxSlotId == NULL )
        {
            xResult = CKR_HOST_MEMORY;
        }
        else
        {
            *ppxSlotId = pxSlotId;  /* Will return with allocated memory pointer */
        }
    }
    else
    {
        xResult = CKR_HOST_MEMORY;
    }
  }

  if( xResult == CKR_OK )
  {
    xResult = pxFunctionList->C_GetSlotList( CK_TRUE, pxSlotId, pxSlotCount ); /* Assuming xResult != CKR_OK */
  }

  if( ( xResult != CKR_OK ) && ( pxSlotId != NULL ) )
  {
    /* ISSUE: If pxSlotId is to be freed, the returning *ppxSlotId need re-update to NULL, 
     * but here is not updated. The calling function xInitializePkcs11Token() will attempt to free again.
     */
    PKCS11_FREE( pxSlotId );
  }

  return xResult;
}
  • The proposed fix.
  • If pxSlotId is freed, the returning *ppxSlotId need re-update to NULL
diff --git a/source/core_pkcs11.c b/source/core_pkcs11.c
index 54d2a10..7223eab 100644
--- a/source/core_pkcs11.c
+++ b/source/core_pkcs11.c
@@ -134,6 +134,7 @@ CK_RV xGetSlotList( CK_SLOT_ID ** ppxSlotId,
     if( ( xResult != CKR_OK ) && ( pxSlotId != NULL ) )
     {
         PKCS11_FREE( pxSlotId );
+        *ppxSlotId = NULL;
     }
 
     return xResult;

compilation error when logLevel set to DEBUG

When compiling for ESP32 using the esp-aws-iot library the build fails due to an error in the corePKCS11 library

On line 452 in the file source/portable/mbedtls/core_pkcs11_mbedtls.c
the log debug call fails to compile with the following error:
error: format '%ld' expects argument of type 'long int', but argument 6 has type 'size_t' {aka 'unsigned int'} [-Werror=format=]

Line:
LogDebug( ( "Ready to sign: xSignatureLength=%ld *pulSignatureLen=%ld", xSignatureLength,*pulSignatureLen ) );

Proposed change:
LogDebug( ( "Ready to sign: xSignatureLength=%ld *pulSignatureLen=%ld", ( long int )xSignatureLength,( long int ) *pulSignatureLen ) );

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.