GithubHelp home page GithubHelp logo

microchiptech / cryptoauthlib Goto Github PK

View Code? Open in Web Editor NEW
361.0 40.0 208.0 74.55 MB

Library for interacting with the Crypto Authentication secure elements

License: Other

C 87.24% C++ 0.15% CMake 0.71% Python 10.84% FreeMarker 1.06%

cryptoauthlib's Introduction

CryptoAuthLib - Microchip CryptoAuthentication Library {#mainpage}

Introduction

This library implements the APIs required to communicate with Microchip Security device. The family of devices supported currently are:

CryptoAuth CryptoAuth2
ATECC608B ECC204
ATECC608A ECC206
ATECC508A SHA104
ATECC108A SHA105
ATSHA204A SHA106
ATSHA206A RNG90

The best place to start is with the Microchip Trust Platform

Online API documentation is at https://microchiptech.github.io/cryptoauthlib/

Latest software and examples can be found at:

Prerequisite hardware to run CryptoAuthLib examples:

Alternatively a Microchip MCU and Adapter Board:

For most development, using socketed top-boards is preferable until your configuration is well tested, then you can commit it to a CryptoAuth Xplained Pro Extension, for example. Keep in mind that once you lock a device, it will not be changeable.

Examples

  • Install the Trust Platform Design Suite to access Use Case examples for the different Security Solutions (ATECC608, SHA104/105, ECC204, TA010, TA100…)

Configuration

In order to properly configured the library there must be a header file in your project named atca_config.h at minimum this needs to contain defines for the hal and device types being used. Most integrations have an configuration mechanism for generating this file. See the atca_config.h.in template which is configured by CMake for Linux, MacOS, & Windows projects.

An example of the configuration:

/* Cryptoauthlib Configuration File */
#ifndef ATCA_CONFIG_H
#define ATCA_CONFIG_H

/* Include HALS */
#define ATCA_HAL_I2C

/* Included device support */
#define ATCA_ATECC608_SUPPORT

/* \brief How long to wait after an initial wake failure for the POST to
 *         complete.
 * If Power-on self test (POST) is enabled, the self test will run on waking
 * from sleep or during power-on, which delays the wake reply.
 */
#ifndef ATCA_POST_DELAY_MSEC
#define ATCA_POST_DELAY_MSEC 25
#endif

#endif // ATCA_CONFIG_H

There are two major compiler defines that affect the operation of the library.

  • ATCA_NO_POLL can be used to revert to a non-polling mechanism for device responses. Normally responses are polled for after sending a command, giving quicker response times. However, if ATCA_NO_POLL is defined, then the library will simply delay the max execution time of a command before reading the response.
  • ATCA_NO_HEAP can be used to remove the use of malloc/free from the main library. This can be helpful for smaller MCUs that don't have a heap implemented. If just using the basic API, then there shouldn't be any code changes required. The lower-level API will no longer use the new/delete functions and the init/release functions should be used directly.

Some specific options are available in the fully documented configuration files lib/calib/calib_config.h, atca_configuration.h, lib/crypto/crypto_config.h, lib/host/atca_host_config.h which is also the place where features can be selected. We provide some configurations focused on specific use cases and the checks are enabled by default.

Release notes

See Release Notes

Host Device Support

CryptoAuthLib will run on a variety of platforms from small micro-controllers to desktop host systems. See hal readme

Porting requires a time delay function of millisecond resolution (hal_delay_ms) which can be implemented via loop, timer, or rtos sleep/wait and a communication interface.

CryptoAuthLib Architecture

Cryptoauthlib API documentation is at https://microchiptech.github.io/cryptoauthlib/

The library is structured to support portability to:

  • multiple hardware/microcontroller platforms
  • multiple environments including bare-metal, RTOS and Windows/Linux/MacOS
  • multiple chip communication protocols (I2C, SPI, and SWI)

All platform dependencies are contained within the HAL (hardware abstraction layer).

Directory Structure

lib - primary library source code
lib/atcacert - certificate data and i/o methods
lib/calib - the Basic Cryptoauth API
lib/crypto - Software crypto implementations external crypto libraries support (primarily SHA1 and SHA256)
lib/hal - hardware abstraction layer code for supporting specific platforms
lib/host - support functions for common host-side calculations
lib/jwt - json web token functions
test - Integration test and examples. See test/cmd-processor.c for main() implementation.

For production code, test directories should be excluded by not compiling it
into a project, so it is up to the developer to include or not as needed.  Test
code adds significant bulk to an application - it's not intended to be included
in production code.

Tests

There is a set of integration tests found in the test directory which will at least partially demonstrate the use of the objects. Some tests may depend upon a certain device being configured in a certain way and may not work for all devices or specific configurations of the device. See test readme

Using CryptoAuthLib (Microchip CryptoAuth Library)

The best place to start is with the Microchip Trust Platform

Also application examples are included as part of the Harmony 3 framework and can be copied from the Harmony Content Manager or found with the Harmony 3 Framework Cryptoauthlib_apps

Incorporating CryptoAuthLib in a Linux project using USB HID devices

The Linux HID HAL files use the Linux udev development software package.

To install the udev development package under Ubuntu Linux, please type the following command at the terminal window:

sudo apt-get install libudev-dev

This adds the udev development development software package to the Ubuntu Linux installation.

The Linux HID HAL files also require a udev rule to be added to change the permissions of the USB HID Devices. Please add a new udev rule for the Microchip CryptoAuth USB devices.

cd /etc/udev/rules.d
sudo touch mchp-cryptoauth.rules

Edit the mchp-cryptoauth.rules file and add the following line to the file:

SUBSYSTEM=="hidraw", ATTRS{idVendor}=="03eb", ATTRS{idProduct}=="2312", MODE="0666"

cryptoauthlib's People

Contributors

benpoon-microchip avatar benudall-microchip avatar bryan-hunt avatar jamiehunter avatar mickeprag avatar rashedtalukder avatar srinivas-e 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  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  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  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

cryptoauthlib's Issues

Help configuring ATECC508 Slot Configuration

Hello,

I am trying to figure out how to setup the slot configuration (SlotConfig Byte 20 to 51) for the following

  1. Generate a public key using (genkey command) from a private key stored in a slot? As far as I see Bit 0 and bit 1 needs to be set.

  2. I want to perform ECDH operation on the chip using a given private key slot. But I do not want the master secret returned in unencrypted. The documentation says to set Bit 3 to 1. Which will store the master secret in slot N|1. What is slot N|1? How do I read from 'slot N|1`?

I also need to know how to run the GenKey command so that the private key is stored in the TempKey register? When I am performing ECDH I need to generate a new key pair using GenKey but I need to store the private key on the ATECC508. I want to use the TemKey register to do this. How can I achieve this?

atcacert_read_cert() the 416 byte "data" array looks like it should be outside the loop

In file "atcacert_client.c" at line 88. It looks like the array of 416 bytes should be outside the loop, because every time the loop run the variable is re-declared. I am guessing since you're not clearing the variable to zero i.e uint8_t data[416] = { 0 }; The data stay on the stack and you are not seeing an issue.
If the intention is to keep the data within the array then it should be initialise external to the loop and cleared to zero uint8_t data[416] = { 0 }

Also why is it 416 byte required?

Original Code

for (i = 0; i < device_locs_count; i++)
    {
        uint8_t data[416];
        if (device_locs[i].zone == DEVZONE_DATA && device_locs[i].is_genkey)
        {
            ret = atcab_get_pubkey(device_locs[i].slot, data);
            if (ret != ATCA_SUCCESS)
            {
                return ret;
            }
        }
        else
        {
            size_t start_block = device_locs[i].offset / 32;
            uint8_t block;
            size_t end_block = (device_locs[i].offset + device_locs[i].count) / 32;
            for (block = (uint8_t)start_block; block < end_block; block++)
            {
                ret = atcab_read_zone(device_locs[i].zone, device_locs[i].slot, block, 0, &data[block * 32 - device_locs[i].offset], 32);
                if (ret != ATCA_SUCCESS)
                {
                    return ret;
                }
            }
        }

        ret = atcacert_cert_build_process(&build_state, &device_locs[i], data);
        if( ret != ATMEL_SUCCESS )
        {
            return ret;
        }
    }

atcab_verify_extern() verification failure

I have had not had success using atcab_verify_extern() to verify a signature generated with openssl. Here is my process:

First, I create a private key, extract the public key, and save it to a file:

openssl ecparam -name prime256v1 -genkey -out private.pem
openssl ec -in private.pem -pubout -outform PEM -out public.pem

Here is the public key in public.pem:

-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAED/JwKRL+RTw8zpwRYqBJZoYBBTGj```
jJdOXcNH1GlDh83Pq1EeyEffhLZ3z/5pQ3se9ZQ8Gk0KrgXrUXbqsZfPgg==```
-----END PUBLIC KEY-----

My message is "hello." Its SHA256 digest is as follows:

15 89 99 9B 0C A6 EF 88 14 28 30 26 A9 F1 66 D5
1C 70 A9 10 67 1C 3D 44 04 97 55 F0 7F 2E B9 10

If I save this to a binary file using HxD, I can sign it with my private key and verify it:

openssl dgst -sign private.pem -keyform PEM hash.bin > sig
openssl dgst -verify public.pem -signature sig hash.bin

I get a result of Verified OK.

Here is the contents of the file "sig" so that you can verify this yourself:

30 45 02 20 4A 09 A5 2E 71 6B 6F 87 FD 7F C5 C4 E2 73 
30 11 4E CA 52 94 CD F2 1E 55 96 5B 87 89 9B 74 49 2E
02 21 00 EB 6B B0 DF F8 2B 4D F4 9B 09 5E 5E 1B CC 21
0B 1B 91 E8 EA 3D 9B 72 6E 1E 49 12 48 EB 14 55 54

To use this with atcab_verify_extern(), I need three C arrays.

The first is the SHA256 digest, which I generate using atcab_hw_sha2_256(). I verified that the results exactly match the contents of hash.bin above.

Next I need the signature. From the file "sig" I can extract the r and s components into an array:

uint8_t signature[64] = {
    0x4A, 0x09, 0xA5, 0x2E, 0x71, 0x6B, 0x6F, 0x87, 0xFD, 0x7F, 0xC5, 0xC4,
    0xE2, 0x73, 0x30, 0x11, 0x4E, 0xCA, 0x52, 0x94, 0xCD, 0xF2, 0x1E, 0x55,
    0x96, 0x5B, 0x87, 0x89, 0x9B, 0x74, 0x49, 0x2E, 0xEB, 0x6B, 0xB0, 0xDF,
    0xF8, 0x2B, 0x4D, 0xF4, 0x9B, 0x09, 0x5E, 0x5E, 0x1B, 0xCC, 0x21, 0x0B,
    0x1B, 0x91, 0xE8, 0xEA, 0x3D, 0x9B, 0x72, 0x6E, 0x1E, 0x49, 0x12, 0x48,
    0xEB, 0x14, 0x55, 0x54
};

Finally, I need the public key's x and y components. Using a B64 decode, I can extract those into the following array:

uint8_t publicKey[64] = {
	0x0F, 0xF2, 0x70, 0x29, 0x12, 0xFE, 0x45, 0x3C, 0x3C, 0xCE, 0x9C, 0x11,
	0x62, 0xA0, 0x49, 0x66, 0x86, 0x01, 0x05, 0x31, 0xA3, 0x8C, 0x97, 0x4E,
	0x5D, 0xC3, 0x47, 0xD4, 0x69, 0x43, 0x87, 0xCD, 0xCF, 0xAB, 0x51, 0x1E,
	0xC8, 0x47, 0xDF, 0x84, 0xB6, 0x77, 0xCF, 0xFE, 0x69, 0x43, 0x7B, 0x1E,
	0xF5, 0x94, 0x3C, 0x1A, 0x4D, 0x0A, 0xAE, 0x05, 0xEB, 0x51, 0x76, 0xEA,
	0xB1, 0x97, 0xCF, 0x82
};

Now I can call the function:

status =  atcab_verify_extern(hash, signature, publicKey, isVerified);

The result is a status of ATCA_SUCCESS, but isVerified is 0 indicating that the signature is not verified.

What am I doing wrong?

PrivWrite command can't write unencrypted data when use Python

I'm trying to write a unencrypted private key to the ATECC508A with python API, but I always get the return code "ATCA_EXECUTION_ERROR".

I think the issuse is that "write_key" is not NULL, maybe we can fix it by following:

def atcab_priv_write(key_id, priv_key, write_key_id, write_key):
    if write_key:
        status = _CRYPTO_LIB.atcab_priv_write(key_id, bytes(priv_key), write_key_id, bytes(write_key))
    else:
         status = _CRYPTO_LIB.atcab_priv_write(key_id, bytes(priv_key), write_key_id, None)
    return status

atcab_genkey and atcacert_read_cert return ATCA_COMM_FAIL on raspberry with i2c

Hello,
I have problem with some commands when I use ATECC508 on raspberry with i2c. The same code works fine if I run it with ATECC on AT88CK101. Also other commands ( atcab_priv_write, CheckLockStatus, etc.) work fine on raspberry.

Commands atcab_genkey and atcacert_read_cert return ATCA_COMM_FAIL.

The problem arises during reading response from /dev/i2c-1

Creating Signer certificate definition

I am trying to create my own signer certificate definition, but I am having some trouble rebuilding it and I believe I am creating the certification definition incorrectly. I believe the issue and expiry date are not stored correctly or at all.

The "issue" and expire "expiry" date are expected to be stored as part of the compressed certificate, since there is 3 byte were this can be encoded..

Do you have a sample template showing how this is done?
Assuming that comp_cert_dev_loc::slot is 15.

Thanks

ATCA_EXECUTION_ERROR when storing public keys or genrating private key using GenKey()

Hi,

I am using atecc508a and I have mentioned my config here. I am able to communicate generally with chip
but I am not able to (i)generate privet key in using atGenKey with mode 0x4 and key id 0x00000 and (ii)also I am not able to store public key in slot 11 or anyother slot. The general things such as random number genarating, applying below configuration, atcab info and all getting success. I am sure what config
I have to use get succeed (i) and (ii). Please provide the config which will work. I am struggling alot and I tried with different configs but I am always getting ATCA_EXECUTION_ERROR. Please find my below
config and please let me know what I have to change. It will be helpfull to all beginners.

uint8_t test_atecc508_configdata[ATCA_ECC_CONFIG_SIZE] = {
0x01, 0x23, 0x00, 0x00, 0x00, 0x00, 0x60, 0x00, 0x04, 0x05, 0x06, 0x07, 0xEE, 0x01, 0x01, 0x00, //15
0xC0, 0x00, 0xA1, 0x00, 0xAF, 0x2F, 0xC4, 0x44, 0x87, 0x20, 0xC4, 0xF4, 0x8F, 0x0F, 0x0F, 0x0F, //31, 5
0x9F, 0x8F, 0x83, 0x64, 0xC4, 0x44, 0xC4, 0x64, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, 0x0F, //47
0x0F, 0x0F, 0x0F, 0x0F, 0xFF, 0xFF, 0xFF, 0xFF, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0xFF, 0xFF, //63
0x00, 0x00, 0x00, 0x00, 0xFF, 0x84, 0x03, 0xBC, 0x09, 0x69, 0x76, 0x00, 0x00, 0x00, 0x00, 0x00, //79
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF, 0xFF, 0x06, 0x40, 0x00, 0x00, 0x00, 0x00, //95
0x33, 0x00, 0x1C, 0x00, 0x13, 0x00, 0x1C, 0x00, 0x3C, 0x00, 0x3E, 0x00, 0x1C, 0x00, 0x33, 0x00, //111
0x1C, 0x00, 0x1C, 0x00, 0x38, 0x10, 0x30, 0x00, 0x3C, 0x00, 0x3C, 0x00, 0x32, 0x00, 0x30, 0x00 //127
};

atcab_ecdh function returns ATCA_EXECUTION_ERROR

Hi Ben,

I'm trying to generate the preshared secret with output in the clear using an internal private key and an external public key to get it but the ecdh function returns ATCA_EXECUTION_ERROR.
Private key is stored in slot 0 with the following configs:

  • SlotConfig 0x00 0x87
  • KeyConfig 0x00 0x13

Every zone is locked except OTP.

The call is pretty simple and looks like this:
ret = atcab_ecdh(0, public_key, pms);

Anyway, I could use the key for ECDSA signing and worked well.
Do you have any idea what the problem could be?

Best regards,
Laszlo Babaly

ATECC608A actab_random returns strange results

I'm working on ESP8266 with new RTOS SDK v3.1 and use the ATECC608A.
With v3.1 the i2c interface is very similar to ESP32 so I'm using the hal_esp32_i2c.

It's working as expected, I'm able to wake up the the chip and also the actab_random() function returns valid results.
But the returned data are always the same and seems to be wrong: 8 times 0xff 0xff 0x00 0x00

Below I added some log messages (Except the 'Received Dump' I used the existing commented comments from hal_esp32_i2c

atcab_init() - default settings except: I2C Bus = I2C_NUM_0 && devtype = ATECC608A
I (602) HAL_I2C: Configuring I2C
D (602) HAL_I2C: I2C Driver Install; 0
D (622) HAL_I2C: I2C Param Config: 0
D (652) HAL_I2C: Received 4 bytes - Dump:
0x04 0x11 0x33 0x43
I (652) HAL_I2C: I2C wake successful
D (652) HAL_I2C: txdata: 0x3fff3720 , txlength: 8
D (672) HAL_I2C: Received 35 bytes - Dump:
0x23 0x01 0x23 0x88 0x05 0x00 0x00 0x60 0x02 0x81 0x97 0xba 0xf6 0xee 0x01 0x5d 0x00 0xc0 0x00 0x00 0x00 0x83 0x20 0x87 0x20 0x8f 0x20 0xc4 0x8f 0x8f 0x8f 0x8f 0x8f 0x90 0xa8
I (682) HAL_I2C: IDLE Command Sent

atcab_buffer() - returns always the same
D (712) HAL_I2C: Received 4 bytes - Dump:
0x04 0x11 0x33 0x43
I (712) HAL_I2C: I2C wake successful
D (712) HAL_I2C: txdata: 0x3fff37b0 , txlength: 8
D (732) HAL_I2C: Received 35 bytes - Dump:
0x23 0xff 0xff 0x00 0x00 0xff 0xff 0x00 0x00 0xff 0xff 0x0 0x00 0xff 0xff 0x00 0x00 0xff 0xff 0x00 0x00 0xff 0xff 0x00 0x00 0xff 0xff 0x00 0x00 0xff 0xff 0x0 0x0 0x41 0x1a
I (742) HAL_I2C: IDLE Command Sent

possible silicon bug in swi version(SOT23-3)

for ATSHA204A,i tested UpdateExtra command on some chips in SOT23-3 footprint,below is a description of the potiential problem:

  1. config&data&otp keep unlocked,unchanged, as it was shipped:
    Selector Mode ==0;
    UserExtra == 0;
    Selector == 0;
    Limit Use for slot 5 is true;Useflag 5 == 0xFF;
  2. chip A:run UpdateExtra with UPDATE_MODE_DEC_COUNTER,NewValue = 5;
    then check: UserExtra == 5; (??)
    Useflag 5 == 0xFF; (no change)
  3. Chip B:run 20+ times of UpdateExtra with UPDATE_MODE_DEC_COUNTER,NewValue = 0:
    for the first 10+ times,chip return success;
    after 20+ times run the UpdateExtra command,chip return atca_status == 0xf4;
    then check:UserExtra == non zero; (??)

i also tested another chip with same footprint,but config&data area were locked,and UserExtra == non zero;when run UpdateExtra with UPDATE_MODE_DEC_COUNTER,NewValue = 5;(while Limit Use for slot 5 is true;Useflag 5 == 0x3F;),but chip always return an err code f4,Useflag 5 keep unchanged.

Does that mean if UserExtra == non zero,UpdateExtra with UPDATE_MODE_DEC_COUNTER will always fail for SWI version?(TWI version tested OK in same environment).

i will test more and give feedback.

polling is duplicated

actual fuctions such as hal_i2c_receive(){in hal_i2c_bitbang.c} and hal_swi_receive(){in hal_swi_bitbang.c} ,they were also polling the chip(retries),then does that mean polling is duplicated if ATCA_NO_POLL was not defined?
i did test removing retries in older version,it worked.

node-auth-basic sample: client-provision command fails for first time

I have managed to build the node-auth-basic sample, released on 2017-11-17, against the latest version of cryptoauthlib. I have been able to run nearly most of all the unit tests successfully.

I am trying to run through this guide: http://ww1.microchip.com/downloads/en/AppNotes/Atmel-8983-CryptoAuth-ATECC508A-Node-Example-Asymmetric-PKI-ApplicationNote.pdf

While attempting to perform the client-provision command for the first time, I received this:
Warning: PrivWrite to slot 7 failed. Example may still work though.
client_provision failed with error code 44

Is there anything I might need to undo from the unit tests?

Thank you for any assistance,
Chris

clarification on atcab_write_enc / atcab_read_enc commands

Hi,

I would like to understand why atcab_write_enc and atcab_read_enc take the key and key slot used to encrypt / decrypt the message in parameter ?

In that case, any application that uses these functions is vulnerable no ? since the encryption key needs to be given in plain text.

Is it possible to only specify the encryption key slot in order to perform an atcab_(write/read)_enc ?

atcab_write_pubkey() fails

Hello,

I'm trying to store a 64-byte long ECC public key in slot 8 without any success. I get this error ATCA_EXECUTION_ERROR
Maybe the settings for the slot are not correct. I use these values to configure the slot:

  • SlotConfig08: 0x00 0x00
  • KeyConfig08: 0x00 0x30

Do you have any example that shows how to store an external public key?

Thank you,
Laszlo

HAL for ATmega324PB/328PB

I was surprised to find no apparent direct HAL support for the ATmega324PB/328PB MCUs in CryptoAuthLib, and no ATECC508a examples on Atmel Start for the ATmega324PB Xplained Pro board even though the board comes with the 508a installed.

What would you recommend for a HAL between ATmega328PB and ATECC608a? It is best to just use the i2c bitbanging hal? We have a solution which will deploy up to a million units and we're using the 608a on a custom PCB to implement node authentication/authorisation and encryption.

Thanks in advance.

Using Atmel508 with external library like mbedTLS

Hello,

I am working on a commercial product which utilises mbedTLS to provide the TLS client connection to a server.
The certificate information is stored Atmel508, but I am not sure how to retrieve it so that it can work with mbedTLS library.

The mbedTLS library can take DER and PEM certificate format. So I need to load the certificate in the library. The specific method in the library for parsing DER certificate is mbedtls_x509_crt_parse_der()
What's the best way to create these certificate from the fields stored in the Atmel508?

https://github.com/ARMmbed/mbedtls

Creating device CSR, how to get the certificate definition i.e atcacert_def_t

I am trying to create a the CSR for the device so I can create the device certificate. In order to create the CSR I need to create the CSR template (i. e atcacert_def_t). To create the CSR template I am looking at the python script cert2certdef.py which takes a CSR using --device-csr.

The CSR I feed the script is a CSR that I generate using openSSL with specific certificate element such as origination name, etc. The CSR is not correct the correct one for the device because the key pair used to create it is wrong. But the common elements would be correct. (I assume so)

I then plan to use the CSR template definition (atcacert_def_t) with atcacert_create_csr() method to create the device CSR.

Is this the correct way to achieve this?

AWSIoTMQTTClient with PKCS#11

For the Greengrass-HSI you already providing a solution with PKCS#11 support

But I cannot have a full-blown data hungry Greengrass core on my IoT device as I only have a very restricted data rate mqtt connection with a small M2M data budget.

Having a look at AWS IoT Device SDK for Python you find one example for a client MQTT connection
https://aws.amazon.com/de/blogs/iot/how-to-implement-mqtt-with-tls-client-authentication-on-port-443-from-client-devices-python/

.# Import SDK packages
from AWSIoTPythonSDK.MQTTLib import AWSIoTMQTTClient

.# For certificate based connection
myMQTTClient = AWSIoTMQTTClient("myClientID")

.# Configure the MQTT Client
myMQTTClient.configureCredentials("YOUR/ROOT/CA/PATH", YOUR/DEVICE/KEY/PATH ", " YOUR/DEVICE/CERT/PATH ")

The API function call configureCredentials requests for a /DEVICE/KEY/PATH and does not offer any means to use PKCS#11 instead.

Instead of using MQTTClient.configureCredentials with a path pointing to a file that has the private key stored on the embedded system what can you recommend as an alternative way to configure the credentials by making use of PKCS#11?

Thank you for your advice

Best Matthias

An anonymous union can only have non-static data members

I am trying to compile a c++ program with the cryptoauthlib and I get this (title) error in the atca_iface.h. I think this is a c11 feature, which is not compatible with c++:

All named structs in the unnamed union throw the error.

typedef struct
{

    ATCAIfaceType  iface_type;      // active iface - how to interpret the union below
    ATCADeviceType devtype;         // explicit device type

    union                           // each instance of an iface cfg defines a single type of interface
    {
        struct ATCAI2C
        {
            uint8_t  slave_address; // 8-bit slave address
            uint8_t  bus;           // logical i2c bus number, 0-based - HAL will map this to a pin pair for SDA SCL
            uint32_t baud;          // typically 400000
        } atcai2c;

        struct ATCASWI
        {
            uint8_t bus;        // logical SWI bus - HAL will map this to a pin	or uart port
        } atcaswi;

        struct ATCAUART
        {
            int      port;      // logic port number
            uint32_t baud;      // typically 115200
            uint8_t  wordsize;  // usually 8
            uint8_t  parity;    // 0 == even, 1 == odd, 2 == none
            uint8_t  stopbits;  // 0,1,2
        } atcauart;

        struct ATCAHID
        {
            int      idx;           // HID enumeration index
            uint32_t vid;           // Vendor ID of kit (0x03EB for CK101)
            uint32_t pid;           // Product ID of kit (0x2312 for CK101)
            uint32_t packetsize;    // Size of the USB packet
            uint8_t  guid[16];      // The GUID for this HID device
        } atcahid;

        struct ATCACUSTOM
        {
            ATCA_STATUS (*halinit)(void *hal, void *cfg);
            ATCA_STATUS (*halpostinit)(void *iface);
            ATCA_STATUS (*halsend)(void *iface, uint8_t *txdata, int txlength);
            ATCA_STATUS (*halreceive)(void *iface, uint8_t* rxdata, uint16_t* rxlength);
            ATCA_STATUS (*halwake)(void *iface);
            ATCA_STATUS (*halidle)(void *iface);
            ATCA_STATUS (*halsleep)(void *iface);
            ATCA_STATUS (*halrelease)(void* hal_data);
        } atcacustom;

    };

    uint16_t wake_delay;    // microseconds of tWHI + tWLO which varies based on chip type
    int      rx_retries;    // the number of retries to attempt for receiving bytes
    void *   cfg_data;      // opaque data used by HAL in device discovery
} ATCAIfaceCfg;

I changed these structs to unnamed structs and it compiles, but I unfortunately get a segmentation fault when calling the init function ATCA_STATUS atinit(ATCAIface ca_iface);... I do not call this function directly. I call atcab_init(&cfg_ateccx08a_i2c_default);

Is there a way to use this without modifying the interface like I did and why do I get the segmentation fault?

My hardwaresetup is a CM3 with a ATECC608a connected to I2C 1. The interface is up and I can query it. Do I need to modify the default interface to the correct device type and the correct I2C interface? When I do so I get the same segmentation fault.

Thanks in advance! Greetings i7clock

Setting up cryptoauthlib as a PKCS11 Provider - module failed to initialize

I was following the manual "Setting up cryptoauthlib as a PKCS11 Provider"
I got stuck with the following error

sudo p11tool --provider=/usr/lib/libcryptoauth.so
p11-kit: (unknown): module failed to initialize: Internal error
pkcs11_add_provider: PKCS #11 error.

One guess was the issue might be caused by a wrong slot config file. I defined
/var/lib/cryptoauthlib/slot.conf as


interface = i2c,0xB0
# freeslots = 1,2,3

# Slot 0 is the primary private key
object = private,device,0


what I was missing in the config file was a bus number for the i2c interface like e.g.
atcai2c.bus = 0

Where can I configure the bus setting?
Any other hint of the error I see?

atcab_sha fails at a size of over 4kb

Is there a data size limitation for the atecc508a for hashing data? I've tested multiple data sizes and at a data size of over 4kb I get the ATCA_GEN_FAIL= 0xE1, //!< unspecified error error. I use the atcab_sha command.

Thank you very much
Habebit

Potential bug in atcab_secureboot_mac()

This may be intentional, however in the atcab_secureboot_mac() function in atca_basic_secureboot.c source file

On line #168 the current code is:
// Encrypt the digest
memcpy(&sboot_enc_params, digest, sizeof(sboot_enc_params));

Is the memcpy() call correct? Shouldn't this be memset() instead? Like this:
memset(&sboot_enc_params, 0, sizeof(sboot_enc_params));

Dean Gereaux
Golden Bits Softare

Allow to build as either shared or static library

The type of library to build is currently hard-coded to SHARED:
add_library(cryptoauth SHARED ${CRYPTOAUTH_SRC} ${ATCACERT_DEF_SRC})

Some users want to build CryptoAuthLib as a static library instead.
A CMake option should allow that.

Missing extern "C" wrapper in atcacert_pem.h

The file atcacert_pem.h is missing the extern "C" wrapper needed for calling these functions from C++. These wrappers are implemented correctly in the other header files (ex. atcacert_der.h).

emit warning when key is passed to JWT sign/encode

as the key is properly ignored since signing is being done by the crypto element, might be worth emitting a python warning if anything other than "" is passed into the function so that people can catch improper calls.

Rights under Raspbian? Adding user to i2c group is not enough

My application works under root but does not with my created user. I added the user to the i2c group but that didn't do the trick. What rights does the library need?

I get f0 as return. Probably returned by the function hal_i2c_send() in hal_linux_i2c_userspace.c.

Custom HAL using Python

I was looking into using Python to with a custom HAL. I have done a similar thing in C, but have not been able to get Python to work. Is this possible?

I have attached my code here. It always crashes in atcab_init() before any of the HAL callbacks are called.

from cryptoauthlib import *
import ctypes as c

ATCA_SUCCESS = 0x00
revision = bytearray(4)
randomnum = bytearray(32)

class Ecc:
    def __init__(self):
        load_cryptoauthlib()
        icfg = ATCAIfaceCfg()
        icfg.devtype = 2
        icfg.iface_type = 5
        icfg.cfg.atcacustom.halinit = c.cast( self.halinit, c.c_void_p)
        icfg.cfg.atcacustom.halpostinit = c.cast( self.halpostinit, c.c_void_p)
        icfg.cfg.atcacustom.halsend = c.cast( self.halsend, c.c_void_p)
        icfg.cfg.atcacustom.halreceive = c.cast( self.halreceive, c.c_void_p)
        icfg.cfg.atcacustom.halwake = c.cast( self.halwake, c.c_void_p)
        icfg.cfg.atcacustom.halidle = c.cast( self.halidle, c.c_void_p)
        icfg.cfg.atcacustom.halsleep = c.cast( self.halsleep, c.c_void_p)
        icfg.cfg.atcacustom.halrelease = c.cast( self.halrelease, c.c_void_p)

        assert ATCA_SUCCESS == atcab_init(icfg)
        assert ATCA_SUCCESS == atcab_info(revision)
        print(''.join(['%02X ' % x for x in revision]))
        assert ATCA_SUCCESS == atcab_random(randomnum)
        print(''.join(['%02X ' % x for x in randomnum]))

    @c.CFUNCTYPE(c.c_int, c.c_void_p, c.c_void_p)
    def halinit(self, hal, cfg):
        pass

    @c.CFUNCTYPE(c.c_int, c.c_void_p) 
    def halpostinit(self, iface):
        pass

    @c.CFUNCTYPE(c.c_int, c.c_void_p, c.c_void_p, c.c_int)   
    def halsend(self, iface, txdata, txlength):
        pass

    @c.CFUNCTYPE(c.c_int, c.c_void_p, c.c_void_p, c.c_void_p,)  
    def halreceive(self, iface, rxdata, rxlength):
        pass
        
    @c.CFUNCTYPE(c.c_int, c.c_void_p) 
    def halwake(self, iface):
        pass 

    @c.CFUNCTYPE(c.c_int, c.c_void_p) 
    def halidle(self, iface):
        pass

    @c.CFUNCTYPE(c.c_int, c.c_void_p) 
    def halsleep(self, iface):
        pass
        
    @c.CFUNCTYPE(c.c_int, c.c_void_p) 
    def halrelease(self, haldata):
        pass

if __name__ == '__main__':
    ecc = Ecc()


big-endian

Hi,
what i want to know is that if the lib could work in a big-endian system......

decryption of pms_bob in "atca_tests_ecdh.c"

Hi,
in atca_tests_ecdh.c line 290 the fuction writes the encrypted premaster secret in "pms_bob" using io protection key "g_slot4_key" to encrypt it. I don't understand where the decryption happens.

Where in the example atca_tests_ecdh.c does the decryption of pms_bob take place?

Which operation must be performed to decrypt the encrypted pms outside the chip?

Thanks

improved ATCA_STATUS isATCAError(uint8_t *data):

ATCA_STATUS isATCAError(uint8_t *data)
{
//remove good[] check ,since atCheckCrc() firstly did the same work in atca_execute_command()

/* uint8_t good[4] = { 0x04, 0x00, 0x03, 0x40 };

if (memcmp(data, good, 4) == 0)
{
    return ATCA_SUCCESS;
}*/


if (data[0] == 0x04)        // error packets are always 4 bytes long
{
    switch (data[1])
    {
  //slm:add this single line is enough
    case 0x00:  return ATCA_SUCCESS; 

    case 0x01: // checkmac or verify failed
        return ATCA_CHECKMAC_VERIFY_FAILED;
        break;
        - - - - - - - - - - - - - - - - - - - - -- - - - - - -- 
        - - - - - - - - - - - - - - - - - - - - -- - - - - - -- 
        - - - - - - - - - - - - - - - - - - - - -- - - - - - -- 
      }

}

Documentation of the configuration

I couldn't find any information how exactly the configuration works and how I can use atcab_priv_write for example. Is there any information online? I think this should be part of the library since otherwise I don't know how to use parts of it.

Thanks and greetings,
i7clock

pointless to Check response size in atca_execute_command():

pointless to Check response size in atca_execute_command():
...............................................................................................................
// Check response size
if (packet->rxsize < 4)
{
if (packet->rxsize > 0)
{
status = ATCA_RX_FAIL;
}
else
{
status = ATCA_RX_NO_RESPONSE;
}
break;
}
...............................................................................................................
in function atreceive(),rxlength is passed by pointer,which means it will be updated(as a return value),
in fact,actual fuctions such as hal_i2c_receive(){in hal_i2c_bitbang.c} and hal_swi_receive(){in hal_swi_bitbang.c} didn't update rxlength at all,it updated rxdata[0] as actual length of data bytes been read;
so,revising atreceive(), just pass packet->rxsize by value rather than by pointer when calling atreceive(); which will only be used as expected reading length.

linux_i2c_userspace.c "hal_i2c_wake" returns ATCA_RX_NO_RESPONSE

Greetings,

I am using the linux_i2c_userspace HAL with the 508A chip. I've update the 508A configuration struct to match my slave address of 0x60 and bus of 1. When running the cmd-processor, I submit the "508" command to select the desired config. When I then execute the "sernum" command I am presented with an error: "atcab_read_serial_number() failed with ret=0x000000E7". I figured I'd start with something basic before even attempting the unit tests.

I traced this to the HAL's wakeup function. The read function is returning -1 and thus returning a status of ATCA_RX_NO_RESPONSE. i2cdetect does find my device at 0x60. Our device tree file has the i2c bus setup for the standard 100kHz.

Thank you for any guidance you can provide.

Create a CSR for the private key fails

All tests listed are successful e.g. "Get the public key for a private key"

sudo p11tool --export-pubkey "pkcs11:token=0123EE;object=device;type=private"
warning: --login was not specified and it may be required for this operation.
warning: no --outfile was specified and the public key will be printed on screen.
-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAELw702nQwPHTtqllf+pGlAvMTg1KP
uvaJh2ansPrizzdZw+TIZRo72zzl7lIVI8lNdgl514wlXfv8soaB3D0lSw==
-----END PUBLIC KEY-----

except for the test "Create a CSR for the private key"

sudo openssl req -engine pkcs11 -key "pkcs11:token=0123EE;object=device;type=private" -keyform engine -new -out new_device.csr -subj "/CN=NEW CSR EXAMPLE"
engine "pkcs11" set.
Found slot without user PIN
PKCS11_get_private_key returned NULL
cannot load Private Key from engine
3070100688:error:26096080:engine routines:ENGINE_load_private_key:failed loading private key:eng_pkey.c:124:
unable to load Private Key

Do you have any hint for the root cause?

possible bug in atca_execution.c

atca_execute_command():
.........................................................
do
{
// receive the response
if ((status = atreceive(device->mIface, packet->data, &(packet->rxsize))) == ATCA_SUCCESS)
{
break;
}

#ifndef ATCA_NO_POLL
// delay for polling frequency time
atca_delay_ms(ATCA_POLLING_FREQUENCY_TIME_MSEC);
#endif
}
while (max_delay_count-- > 0);
////////////////////////////////////////////////////////////////////
//i think below lines should be added to check status:
if ( status != ATCA_SUCCESS)
{
break;
}
///////////////////////////////////////////////////////////////////
// Check response size
if (packet->rxsize < 4)
{
if (packet->rxsize > 0)
{
status = ATCA_RX_FAIL;
}
else
{
status = ATCA_RX_NO_RESPONSE;
}
break;
}
..................................................................................................

Verify function

Hi, is there a way to verify a "sign" without using the verify command of the ATECC508A? For example, given the public key, message and "sign message", is there a way to verify this?

ATCA_PARSE_ERROR (0xD2) for ATECC608A AES-128 functions

Hello!

I'm running an ATECC608A off a raspberry pi (default installation of most recent, and updated raspbian) using I2C from the GPIO pins.

The chip appears to be working, and I initialised it wit the stock config zone, but whenever I try to do any of the AES functions (including atcab_aes() ) from within python, I consistently get an ATCA_PARSE_ERROR (0xD2) returned.

Everything else appears to work - the RNG, SHA256 functionality, etc. Is there a way of troubleshooting this functionality?

Any help would be appreciated!

Very best, M.

Is there a typo in atca_tests_gendig.c?

Hi there, thanks for your work. Is there a typo? I thought the configuration zone should be locked, before you can generate a private key and a corresponding public key. I think it should be called ...if data zone is locked instead of ...

* test will generate a private key if data zone is unlocked and return a public key

atcacert_create_csr() generates public key from the wrong slot

Hey there,

atcacert_create_csr() can either retrieve the public key from a slot on the device, or generate it from a private key. When is_genkey is requested for the source of the public key the wrong slot number is passed into atcab_get_pubkey().

status = atcab_get_pubkey(key_slot, pub_key);

key_slot is the slot for the public key, which in this instance is effectively undefined. This line should read:

status = atcab_get_pubkey(priv_key_slot, pub_key);

atcab_sha_hmac fails with ATCA_RX_CRC_ERROR

Hi,

I am testing the cryptoauthlib with i2c userspace interface.

I set up the baudrate to 1000000 usinga ATECC508A chip and during the atcab_sha_hmac tests, I have an 0XE5 error code corresponding to ATCA_RX_CRC_ERROR

Reproduced the issue on 2 differents chip. The workaround is increasing the ATCA_SHA delay in device_execution_time_508

Here is the code sample I am using:

char data[32] = {0};
size_t data_len = sizeof(data);

char digest[32] = {0};

ATCA_STATUS ret = atcab_sha_hmac(data, data_len, 1, digest, SHA_MODE_TARGET_TEMPKEY);
if(ret != ATCA_SUCCESS)
{
    printf("err code: 0x%x\n", ret);
    exit(EXIT_FAILURE);
}

Thanks for your help.

ESP32 IDF support

Issues Type: Question

Can we use it with ESP32, ESP-IDF (Espressif IoT Development Framework)?

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.