GithubHelp home page GithubHelp logo

polhenarejos / pico-hsm Goto Github PK

View Code? Open in Web Editor NEW
183.0 9.0 24.0 1.92 MB

Hardware Security Module for Raspberry Pico

License: GNU General Public License v3.0

CMake 1.70% C 63.88% Shell 6.32% Python 27.41% Dockerfile 0.69%
firmware cryptography raspberry-pi-pico hsm

pico-hsm's Introduction

Raspberry Pico HSM

This project aims to transform a Raspberry Pi Pico or ESP32 microcontroller into a Hardware Security Module (HSM). The modified Pico or ESP32 board will be capable of generating and storing private keys, performing AES encryption or decryption, and signing data without exposing the private key. Specifically, the private key remains securely on the board and cannot be retrieved since it is encrypted within the flash memory.

Capabilities

> Key generation and encrypted storage

Private and secret keys are secured using a master AES 256 key (MKEK). The MKEK is encrypted with a hashed and salted version of the PIN. No private/secret keys, DKEK or PIN are stored in plain text ever. Never.

> RSA Key Generation (1024 to 4096 Bits)

RSA key generation is supported for 1024, 2048, 3072, and 4096 bits. Private keys never leave the device.

> ECDSA Key Generation (192 to 521 Bits)

ECDSA key generation supports various curves from 192 to 521 bits.

> ECC Curves

Supported ECC curves include secp192r1, secp256r1, secp384r1, secp521r1, brainpoolP256r1, brainpoolP384r1, brainpoolP512r1, secp192k1 (insecure), secp256k1, Curve25519, and Curve448.

> SHA Digests

ECDSA and RSA signatures can be combined with SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512 digests.

> Multiple RSA Signature Algorithms

Supported RSA signature algorithms include RSA-PSS, RSA-PKCS, and raw RSA signatures.

> ECDSA Signatures

ECDSA signatures can be raw or pre-hashed.

> ECDH Key Derivation

Supports the ECDH algorithm for calculating shared secrets.

> EC Private Key Derivation

Allows ECDSA key derivation.

> RSA Decryption

Supports RSA-OEP and RSA-X.509 decryption.

> AES Key Generation

Supports AES key generation with keys of 128, 192, and 256 bits.

> AES-CBC Encryption/Decryption

Performs AES-CBC encryption and decryption.

> Advanced AES Modes

Supports AES encryption and decryption in ECB, CBC, CFB, OFB, XTS, CTR, GCM, and CCM modes, with customizable IV/nonce and additional authenticated data (AAD).1

> AES Key Generation (128, 192, 256, 512 Bits)

Supports AES key generation up to 512 bits, useful for AES XTS where two 256-bit keys are concatenated.

> CMAC

Supports AES-CMAC authentication.2

> AES Secret Key Derivation

Supports AES secret key derivation.2

> PIN Authorization

Private and secret keys require prior PIN authentication. Supports alphanumeric PINs.

> PKCS11 Compliant Interface

Interfacing with the PKCS11 standard is supported.

> Hardware Random Number Generator (HRNG)

Contains an HRNG designed for maximum entropy.

> Device Key Encryption Key (DKEK) Shares

Supports importing DKEK shares to wrap, unwrap, and encrypt keys.

> DKEK n-of-m Threshold Scheme

Supports an n-of-m threshold scheme to prevent outages when a DKEK custodian is unavailable.

> USB/CCID Support

Full USB CCID stack for communication with the host via OpenSC and PCSC, allowing the use of frontend applications like OpenSSL via the PKCS11 module.

> Extended APDU Support

Supports extended APDU packets, allowing up to 65535 bytes.

> CV Certificates

Handles CVC certificates and requests to minimize internal certificate storage.

> Attestation

Each generated key is attached to a certificate signed by an external PKI, ensuring the key was generated by the specific device.

> Import External Keys and Certificates

Allows importing private keys and certificates via WKY or PKCS#12 files.34

> Transport PIN

Allows a transport PIN for provisioning, ensuring the device has not been tampered with during transportation.3

> Press-to-Confirm Button

Uses the BOOTSEL button to confirm operations with private/secret keys, providing a 15-second window to confirm the operation to protect against unauthorized use.

> Store and Retrieve Binary Data

Allows the storage of arbitrary binary data files.

> Real-Time Clock (RTC)

Includes an RTC with external date and time setting and retrieval.

> Secure Messaging

Supports secure channels to encrypt data packets between the host and device, preventing man-in-the-middle attacks.

> Session PIN

A specific session PIN can be set during session opening to avoid systematic PIN usage.

> PKI CVCert Remote Issuing for Secure Messaging

Secure channel messages are secured with a certificate issued by an external PKI.

> Multiple Key Domains

Supports separate key domains protected by independent DKEKs, allowing different keys in different domains.

> Key Usage Counter

Tracks and limits the usage of private/secret keys, disabling keys once their usage counter reaches zero.

> Public Key Authentication (PKA)

Supports PKA for enhanced security, requiring a secondary device for authentication using a challenge-response mechanism.

> Secure Lock

Adds an extra layer of security by locking the Pico HSM to a specific computer using a private key.

> ChaCha20-Poly1305

Supports the ChaCha20-Poly1305 encryption algorithm for secure data encryption.1

> X25519 and X448

Supports DH X25519 and X448 for key agreement, though these cannot be used for signing.

> Key Derivation Functions

Supports HKDF, PBKDF2, and X963-KDF for symmetric key derivation.

> HMAC

Supports HMAC generation with SHA digest algorithms.

> CMAC

Supports CMAC with AES for keys of 128, 192, and 256 bits.

> XKEK

Supports an advanced key sharing scheme (XKEK) for securely wrapping and unwrapping keys within authorized domains.

> Master Key Encryption Key (MKEK)

Uses an MKEK to securely store all keys, encrypted with an ephemeral key derived from the hashed PIN.

> Hierarchical Deterministic Key Generation

Supports BIP32 for asymmetric key derivation and SLIP10 for symmetric key derivation, enabling crypto wallet deployment with infinite key generation. Supports NIST 256 and Koblitz 256 curves for master key generation.1

> ESP32-S3 support

Pico HSM also supports ESP32-S3 boards, which add secure storage, flash encryption and secure boot.

> Dynamic VID/PID

Supports setting VID & PID on-the-fly. Use pico-hsm-tool.py for specify VID/PID values and reboot the device.

> Rescue Pico HSM Tool

Pico HSM Tool implements a new CCID stack to rescue the Pico HSM in case it has wrong VID/PID values and it is not recognized by the OS.

Security considerations

All secret keys (both asymmetric and symmetric) are encrypted and stored in the flash memory of the Raspberry Pico. The DKEK, a 256-bit AES key, is used to protect these private and secret keys. Keys are only held in RAM during signature and decryption operations, and are loaded and cleared each time to avoid potential security vulnerabilities.

The DKEK itself is encrypted using a doubly salted and hashed PIN, and the PIN is hashed in memory during sessions. This ensures that the PIN is never stored in plain text, either in flash memory or in RAM. However, if no secure channel is used, the PIN is transmitted in plain text from the host to the HSM.

In the event that the Pico is stolen, the private and secret key contents cannot be accessed without the PIN, even if the flash memory is dumped.

Download

If you own an ESP32-S3 board, go to ESP32 support for further information.

Please, go to the Release page and download the UF2 file for your board.

Note that UF2 files are shiped with a dummy VID/PID to avoid license issues (FEFF:FCFD). If you plan to use it with OpenSC or similar tools, you should modify Info.plist of CCID driver to add these VID/PID or use the Pico Patcher tool.

Alternatively you can use the legacy VID/PID patcher as follows: ./patch_vidpid.sh VID:PID input_hsm_file.uf2 output_hsm_file.uf2

You can use whatever VID/PID (i.e., 234b:0000 from FISJ), but remember that you are not authorized to distribute the binary with a VID/PID that you do not own.

Note that the pure-browser option Pico Patcher tool is the most recommended.

Build

Before building, ensure you have installed the toolchain for the Pico and the Pico SDK is properly located in your drive.

git clone https://github.com/polhenarejos/pico-hsm
git submodule update --init --recursive
cd pico-hsm
mkdir build
cd build
PICO_SDK_PATH=/path/to/pico-sdk cmake .. -DPICO_BOARD=board_type -DUSB_VID=0x1234 -DUSB_PID=0x5678
make

Note that PICO_BOARD, USB_VID and USB_PID are optional. If not provided, pico board and VID/PID FEFF:FCFD will be used.

Additionally, you can pass the VIDPID=value parameter to build the firmware with a known VID/PID. The supported values are:

  • NitroHSM
  • NitroFIDO2
  • NitroStart
  • NitroPro
  • Nitro3
  • Yubikey5
  • YubikeyNeo
  • YubiHSM
  • Gnuk
  • GnuPG

After running make, the binary file pico_hsm.uf2 will be generated. To load this onto your Pico board:

  1. Put the Pico board into loading mode by holding the BOOTSEL button while plugging it in.
  2. Copy the pico_hsm.uf2 file to the new USB mass storage device that appears.
  3. Once the file is copied, the Pico mass storage device will automatically disconnect, and the Pico board will reset with the new firmware.
  4. A blinking LED will indicate that the device is ready to work.

Docker

Independent from your Linux distribution or when using another OS that supports Docker, you could build a specific pico-hsm version in a Linux container.

sudo docker build \
    --build-arg VERSION_PICO_SDK=1.5.0 \
    --build-arg VERSION_MAJOR=3 \
    --build-arg VERSION_MINOR=4 \
    --build-arg PICO_BOARD=waveshare_rp2040_zero \
    --build-arg USB_VID=0xfeff \
    --build-arg USB_PID=0xfcfd \
    -t pico-hsm-builder .

sudo docker run \
    --name mybuild \
    -it pico-hsm-builder \
    ls -l /home/builduser/pico-hsm/build_release/pico_hsm.uf2

sudo docker cp mybuild:/home/builduser/pico-hsm/build_release/pico_hsm.uf2 .

sudo docker rm mybuild

Usage

The firmware uploaded to the Pico contains a reader and a virtual smart card, similar to having a physical reader with an inserted SIM card. We recommend using OpenSC to communicate with the reader. If OpenSC is not installed, you can download and build it or install the binaries for your system.

To ensure that the Pico is detected as an HSM, use the following command:

opensc-tool -an

It should return a text similar to:

Using reader with a card: Free Software Initiative of Japan Gnuk
3b:fe:18:00:00:81:31:fe:45:80:31:81:54:48:53:4d:31:73:80:21:40:81:07:fa
SmartCard-HSM

The name of the reader may vary if you modified the VID/PID.

For further details and operations, refer to the following documentation:

Operation time

Keypair generation

Generating EC keys is almost instant. RSA keypair generation takes some time, specially for 3072 and 4096 bits.

RSA key length (bits) Average time (seconds)
1024 16
2048 124
3072 600
4096 ~1000

Signature and decrypt

RSA key length (bits) Average time (seconds)
1024 1
2048 3
3072 7
4096 15

Press-to-confirm button

The Raspberry Pico includes a BOOTSEL button used for loading firmware initially. Once the Pico HSM firmware is running, this button can be repurposed for additional functionalities. Specifically, the Pico HSM utilizes this button to confirm private and secret operations, a feature that is optional but highly recommended for enhanced security.

When enabled, each time a private or secret key operation is initiated, the Pico HSM enters a waiting state where it awaits user confirmation by pressing the BOOTSEL button. During this waiting period, the Pico HSM's LED remains mostly illuminated but blinks off briefly every second, signaling to the user to press the button for confirmation. If no action is taken, the Pico HSM will continue to wait indefinitely. This operation mode includes periodic timeout commands sent to the host to prevent the session from timing out prematurely.

This feature adds an additional layer of security by requiring physical user intervention for sensitive operations such as signing or decrypting data. It mitigates risks associated with unauthorized applications or scripts using the Pico HSM without user awareness. However, it is not recommended for server environments or other automated settings where physical access to press the button may not be practical.

For more details on configuring and using this feature, refer to the doc/extra_command.md document.

Led blink

Pico HSM uses the led to indicate the current status. Four states are available:

Press to confirm

The Led is almost on all the time. It goes off for 100 miliseconds every second.

Press to confirm

Idle mode

In idle mode, the Pico HSM goes to sleep. It waits for a command and it is awaken by the driver. The Led is almost off all the time. It goes on for 500 milliseconds every second.

Idle mode

Active mode

In active mode, the Pico HSM is awaken and ready to receive a command. It blinks four times in a second.

Active

Processing

While processing, the Pico HSM is busy and cannot receive additional commands until the current is processed. In this state, the Led blinks 20 times in a second.

Processing

Driver

The Pico HSM uses either the sc-hsm driver from OpenSC or the sc-hsm-embedded driver from CardContact to interface with external applications. These drivers employ the standardized PKCS#11 interface, making it compatible with various cryptographic engines that support PKCS#11, such as OpenSSL, P11 library, or pkcs11-tool.

Internally, the Pico HSM organizes and manages its data using the PKCS#15 structure, which includes elements like PINs, private keys, and certificates. Commands can be issued to interact with these stored elements using tools such as pkcs15-tool. For example, pkcs15-tool -D lists all elements stored within the Pico HSM.

Communication with the Pico HSM follows the same protocols and methods used with other smart cards, such as OpenPGP cards or similar devices.

For advanced usage scenarios, refer to the documentation and examples provided. Additionally, the Pico HSM supports the SCS3 tool for more sophisticated operations and includes features like multiple key domains. For detailed information on SCS3 usage, refer to SCS3 documentation.

Important

OpenSC relies on PCSC driver, which reads a list (Info.plist) that contains a pair of VID/PID of supported readers. In order to be detectable, you have several options:

  • Use pico-hsm-tool.py to modify VID/PID on-the-fly.
  • Use the online Pico Patcher tool.
  • Patch the UF2 binary (if you just downloaded from the Release section)
  • Build and configure the project with the proper VID/PID with USB_VID and USB_PID parameters in CMake (see Build section). Note that you cannot distribute the patched/compiled binary if you do not own the VID/PID or have an explicit authorization.

Credits

Pico HSM uses the following libraries or portion of code:

  • mbedTLS for cryptographic operations.
  • TinyUSB for low level USB procedures.

Footnotes

  1. Available by using PicoHSM python tool. 2 3

  2. PKCS11 modules (pkcs11-tool and sc-tool) do not support CMAC and key derivation. It must be processed through raw APDU command (opensc-tool -s). 2

  3. Available via SCS3 tool. See SCS3 for more information. 2

  4. Imports are available only if the Pico HSM is previously initialized with a DKEK and DKEK shares are available during the import process.

pico-hsm's People

Contributors

al-heisner avatar fastchain avatar polhenarejos avatar rrottmann 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

pico-hsm's Issues

ModuleNotFoundError: No module named 'secure_key'

A search on pypy.org does not yield any results and also my google fu does not show meaningful results of how to obtain the library "secure_key". Is this an official python package? Would it be possible to populate a requirements.txt or point to the package name?

pkcs11-tool --write-object may corrupt flash

I'm using this shell script to test (erases all data on the hsm!):

#!/bin/bash

stty -F /dev/ttyUSB0 ispeed 115200 ospeed 115200 raw
cat /dev/ttyUSB0 > /tmp/hsm.log &
pid=$!

echo "" | python3 ../tools/pico-hsm-tool.py initialize

dd if=/dev/urandom of=/tmp/testfile bs=3000 count=1
for x in {01..06}; do
   pkcs11-tool --private --pin 'env:pass' --type data --write-object /tmp/testfile --label test.$x
done

echo "" | python3 ../tools/pico-hsm-tool.py initialize

dd if=/dev/urandom of=/tmp/testfile bs=2000 count=1
for x in {01..06}; do
   pkcs11-tool --private --pin 'env:pass' --type data --write-object /tmp/testfile --label test.$x
done

ps -ef | grep $pid
kill $pid
cat /tmp/hsm.log

This produces a state where the HSM is unable to read or delete the last file written, and debug messages seem to show error followed by corrupted file id and size for last file written:

ERROR: ALL FLASH PAGES CACHED
ERROR: ALL FLASH PAGES CACHED
ERROR: ALL FLASH PAGES CACHED
SCAN
[101fffb4] scan fid 100a, len 52
[101fff74] scan fid 100b, len 52
[101fff47] scan fid cc00, len 33
[101ffd4a] scan fid ce00, len 497
[101ff992] scan fid c400, len 58
[101ff5f1] scan fid 2f02, len 917
[101fbfbf] scan fid 1081, len 33
[101fbf92] scan fid 1088, len 33
[101fbf85] scan fid 1083, len 1
[101fbf78] scan fid 108a, len 1
[101fbf6b] scan fid 1082, len 1
[101fbf5e] scan fid 1089, len 1
[101fbf50] scan fid 100e, len 2
[101fbf42] scan fid 10a0, len 2
[101fb766] scan fid cd00, len 2000
[101fb733] scan fid c900, len 39
[101fb700] scan fid c901, len 39
[101fb6cd] scan fid c902, len 39
[101fb69a] scan fid c903, len 39
[101fb667] scan fid c904, len 39
[101fb634] scan fid c905, len 39
[101fa824] scan fid cd01, len 2000
[101fa048] scan fid cd02, len 2000
[101f9824] scan fid cd03, len 2000
[101f9048] scan fid cd04, len 2000
[101f8824] scan fid 9531, len 61168

Through some trial and error testing, I've been able to get this to work by changing TOTAL_FLASH_PAGES to 5 in low_flash.c, then I'm able to write far more files with no corruption. However, I now get to 23 objects written and retrieved successfully, but the 24th, while it appears to write successfully it cannot be retrieved or deleted. I haven't figured out why it now fails at 24 objects, object size doesn't appear to matter.

Pico HSM 'hangs' on running "opensc-tool -an" or "pico-hsm-tool.py initialize"

Hi, I downloaded pico_hsm_pico-3.0.uf2 and patched it to change the VID/PID to 234b:0000 using pico-hsm-patch-vidpid.sh and the SHA-256 hash of the patched UF2 file is 359545acf49c9145e8d8b43ec92023586e0c8b0d42fdf03103a9cce7748b3b31

I tried running opensc-tool -an and the Pico outputs the following and 'hangs':

$ opensc-tool -an
Using reader with a card: Free Software Initiative of Japan Gnuk [Pico HSM Interface] (E6609103C32B7A2A) 00 00
3b:fe:18:00:00:81:31:fe:45:80:31:81:54:48:53:4d:31:73:80:21:40:81:07:fa

If I unplug the Pico at this point, the next line is printed:

SmartCard-HSM

I also ran python3 pico-hsm-tool.py initialize --so-pin 3537363231383830 --pin 648219 after plugging the Pico back in and I see this before it 'hangs':

Pico HSM Tool v1.4
Author: Pol Henarejos
Report bugs to https://github.com/polhenarejos/pico-hsm/issues


********************************
*   PLEASE READ IT CAREFULLY   *
********************************

This tool will erase and reset your device. It will delete all private and secret keys.
Are you sure?
[Press enter to confirm]

The LED on the Pico is blinking 4 times a second when it 'hangs'. Only once, I was able to get the opensc-tool -an command to finish execution (without plugging out the Pico) and the output looked like this:

$ opensc-tool -an
Using reader with a card: Free Software Initiative of Japan Gnuk [Pico HSM Interface] (E6609103C32B7A2A) 00 00
3b:fe:18:00:00:81:31:fe:45:80:31:81:54:48:53:4d:31:73:80:21:40:81:07:fa
SmartCard-HSM version 3.0

Any idea what's wrong here?

I checked pcscd logs and saw these:

Oct 27 21:28:09 ubuntu-box systemd[1]: Stopped PC/SC Smart Card Daemon.
Oct 27 21:28:12 ubuntu-box systemd[1]: Started PC/SC Smart Card Daemon.
Oct 27 21:28:12 ubuntu-box pcscd[3641]: 00000000 ccid_usb.c:993:ReadUSB() read failed (1/21): LIBUSB_ERROR_OVERFLOW
Oct 27 21:28:12 ubuntu-box pcscd[3641]: 00101227 ccid_usb.c:993:ReadUSB() read failed (1/21): LIBUSB_ERROR_TIMEOUT
Oct 27 21:28:12 ubuntu-box pcscd[3641]: 00002466 ccid_usb.c:993:ReadUSB() read failed (1/21): LIBUSB_ERROR_OVERFLOW
Oct 27 21:28:12 ubuntu-box pcscd[3641]: 00000024 ifdwrapper.c:364:IFDStatusICC() Card not transacted: 612
Oct 27 21:28:12 ubuntu-box pcscd[3641]: 00000006 eventhandler.c:336:EHStatusHandlerThread() Error communicating to: Free Software Initiative of Japan Gnuk [Pico HSM Interface] (E6609103C32B7A2A) 00 00
Oct 27 21:28:44 ubuntu-box systemd[1]: Stopping PC/SC Smart Card Daemon...
Oct 27 21:28:44 ubuntu-box systemd[1]: pcscd.service: Deactivated successfully.
Oct 27 21:28:44 ubuntu-box systemd[1]: Stopped PC/SC Smart Card Daemon.
Oct 27 21:28:47 ubuntu-box systemd[1]: Started PC/SC Smart Card Daemon.
Oct 27 21:29:55 ubuntu-box pcscd[3668]: 00000000 ccid_usb.c:993:ReadUSB() read failed (1/21): LIBUSB_ERROR_NO_DEVICE
Oct 27 21:29:55 ubuntu-box pcscd[3668]: 00000055 ifdwrapper.c:543:IFDTransmit() Card not transacted: 617
Oct 27 21:29:55 ubuntu-box pcscd[3668]: 00000054 ccid_usb.c:886:WriteUSB() write failed (1/21): LIBUSB_ERROR_NO_DEVICE
Oct 27 21:29:56 ubuntu-box pcscd[3668]: 01000724 winscard.c:1618:SCardTransmit() Card not transacted: 0x80100017
Oct 27 21:30:57 ubuntu-box systemd[1]: pcscd.service: Deactivated successfully.

BTW, unrelated:
pico-hsm-tool.py#L29 is a bit misleading as I had to also run pip install pycvc before I could get pico-hsm-tool.py to work

EC Key Creation

Morning

Different outcome based on the same key type?

  clear
  
  sudo service pcscd start
  
  ## Initialization
  echo "Initialize the HSM."
  
  time python3 ~/M1/pico-hsm/tools/pico-hsm-tool.py initialize --so-pin 3537363231383830 
  
  echo "Change the PIN"
  time pkcs11-tool --module /usr/local/lib/libsc-hsm-pkcs11.so --login --pin 648219 --change-pin --new-pin 123456
  
  # DSA - Test # 17 - DSA Key Gen
  
  time pkcs11-tool --module /usr/local/lib/libsc-hsm-pkcs11.so -l --pin 123456 --keypairgen --key-type EC:secp192r1 --id 11 --label "DSA192"
  
  time pkcs11-tool --module /usr/local/lib/libsc-hsm-pkcs11.so -l --pin 123456 --keypairgen --key-type EC:secp256r1 --id 12 --label "DSA256"
  
  time pkcs11-tool --module /usr/local/lib/libsc-hsm-pkcs11.so -l --pin 123456 --keypairgen --key-type EC:secp384r1 --id 13 --label "DSA384"
  
  time pkcs11-tool --module /usr/local/lib/libsc-hsm-pkcs11.so -l --pin 123456 --keypairgen --key-type EC:secp521r1 --id 14 --label "DSA521"
  
  time pkcs11-tool --module /usr/local/lib/libsc-hsm-pkcs11.so -l --pin 123456 --keypairgen --key-type EC:secp192k1 --id 15 --label "DSA192K"
  
  time pkcs11-tool --module /usr/local/lib/libsc-hsm-pkcs11.so -l --pin 123456 --keypairgen --key-type EC:secp256k1 --id 16 --label "DSA256K"

All works as expected.

  for i in `seq 11 16`
  do
      echo ""
      echo ""
      echo -e "\e[0;31mCreation \e[0m of key $i"
      time pkcs11-tool --module /usr/local/lib/libsc-hsm-pkcs11.so --read-object --pin 123456 --id $i --type pubkey > $i.der
      time openssl ec -inform DER -outform PEM -in $i.der -pubin > $i.pub
      echo ""
   
      echo ""
      echo -e "\e[0;31mSigning \e[0m using key $i"
      time pkcs11-tool --module /usr/local/lib/libsc-hsm-pkcs11.so --id $i --sign --pin 123456 --mechanism ECDSA -i data.file -o $i.sig --signature-format openssl
      echo ""
      echo -e "\e[0;32mVerifing \e[0m using key $i"
      time openssl pkeyutl -verify -pubin -inkey $i.pub -in data.file -sigfile $i.sig
  done

All of the odd numbers done work? But the odd numbers don't with an EVP_PKEY issue?

Creation of key 11
Using slot 0 with a present token (0x1)
error: cannot create EVP_PKEY
Aborting.

real 0m0.446s
user 0m0.004s
sys 0m0.005s
read EC key
Could not read public key from 11.der
unable to load Key

real 0m0.006s
user 0m0.006s
sys 0m0.000s

Signing using key 11
Using slot 0 with a present token (0x1)
Using signature algorithm ECDSA

real 0m0.160s
user 0m0.000s
sys 0m0.006s

Verifing using key 11
Could not read public key from 11.pub
pkeyutl: Error initializing context

real 0m0.006s
user 0m0.006s
sys 0m0.000s

Creation of key 12
Using slot 0 with a present token (0x1)

real 0m0.191s
user 0m0.004s
sys 0m0.008s
read EC key
writing EC key

real 0m0.007s
user 0m0.007s
sys 0m0.000s

Signing using key 12
Using slot 0 with a present token (0x1)
Using signature algorithm ECDSA

real 0m0.296s
user 0m0.007s
sys 0m0.000s

Verifing using key 12
Signature Verified Successfully

real 0m0.007s
user 0m0.001s
sys 0m0.007s

Creation of key 13
Using slot 0 with a present token (0x1)
error: cannot create EVP_PKEY
Aborting.

real 0m0.191s
user 0m0.006s
sys 0m0.005s
read EC key
Could not read public key from 13.der
unable to load Key

real 0m0.006s
user 0m0.006s
sys 0m0.001s

Signing using key 13
Using slot 0 with a present token (0x1)
Using signature algorithm ECDSA

real 0m0.312s
user 0m0.000s
sys 0m0.006s

Verifing using key 13
Could not read public key from 13.pub
pkeyutl: Error initializing context

real 0m0.005s
user 0m0.005s
sys 0m0.001s

Creation of key 14
Using slot 0 with a present token (0x1)

real 0m0.192s
user 0m0.004s
sys 0m0.008s
read EC key
writing EC key

real 0m0.008s
user 0m0.000s
sys 0m0.008s

Signing using key 14
Using slot 0 with a present token (0x1)
Using signature algorithm ECDSA

real 0m0.552s
user 0m0.000s
sys 0m0.007s

Verifing using key 14
Signature Verified Successfully

real 0m0.009s
user 0m0.004s
sys 0m0.005s

Creation of key 15
Using slot 0 with a present token (0x1)
error: cannot create EVP_PKEY
Aborting.

real 0m0.189s
user 0m0.003s
sys 0m0.007s
read EC key
Could not read public key from 15.der
unable to load Key

real 0m0.006s
user 0m0.005s
sys 0m0.001s

Signing using key 15
Using slot 0 with a present token (0x1)
Using signature algorithm ECDSA

real 0m0.173s
user 0m0.000s
sys 0m0.006s

Verifing using key 15
Could not read public key from 15.pub
pkeyutl: Error initializing context

real 0m0.006s
user 0m0.006s
sys 0m0.001s

Creation of key 16
Using slot 0 with a present token (0x1)

real 0m0.198s
user 0m0.008s
sys 0m0.004s
read EC key
writing EC key

real 0m0.008s
user 0m0.007s
sys 0m0.001s

Signing using key 16
Using slot 0 with a present token (0x1)
Using signature algorithm ECDSA

real 0m0.305s
user 0m0.006s
sys 0m0.001s

Verifing using key 16
Signature Verified Successfully

real 0m0.009s
user 0m0.008s
sys 0m0.001s

Any suggestions?

Br,

markone [b00148917]

Failing to detect pico hsm

I should RTFM before submitting issues :(

My misunderstanding was that the device should be detectable at any VID:PID, not at the specific ones that opensc expected. Using 234b:0000 solved the problem. And since this is for personal use, I don't have to worry about acquiring my own vid.

USB IDs

You can get a free USB PID allocated with the openmoko VID here: https://github.com/openmoko/openmoko-usb-oui

By applying for an Openmoko Product ID, you acknowledge that either

  • the USB device you are developing is an open hardware project (as per the OSHW Definition), or
  • the firmware/software running on your USB device is Free / Open Source software, licensed under an OSI-Approved, FSF-Recognized or DFSG-Approved Free / Open Source software license

pico-hsm satisfies the second condition, and I think it would be a good idea to get a PID for the project to avoid all the ID patching step moving forward.

Usage on MacOS and Windows with Microsoft CCID driver

I have tried to use this project on RPi Pico and on Waveshare RP2040 Zero. As the LED on the Zero is not working, I am mainly using the original RPi Pico.

Under Linux (Ubuntu 22.04) I was able to get this project to work after editing the Info.plist to include the default VID/PID combination. I was using the release version 3.2. So I know my Pico board is working correctly here.

On MacOS without changing the VID and PID, the default combination is not known to the Apple CCID driver. On older versions of MacOS, it used to be possible to manually edit the Info.plist and add a new VID/PID combination, but now the Info.plist is in the read-only partition. Is there any known way to get it working with the default VID/PID or does one have to set one of the known VID/PID combinations to get it to work on a Mac?

However, on Windows, the Device Manager shows the Microsoft CCID driver attached to the VID/PID combination, but any attempt to use it just hangs (like doing reset in SCSH3 after selecting the pico-hsm in Reader selection). The task needs to be killed from the Task Manager, it is blocked that it cannot be closed normally.

Is this a known problem with Windows or is it something specific on my machine? I have multiple other CCID drivers installed and working correctly, I am a long term regular user of SCSH3.

Response time issue

Hi,
I started testing your product and I have a strange situation, when I send a request/command I am waiting a long time.

Example:

>>> opensc-tool -an Using reader with a card: Free Software Initiative of Japan Gnuk [Pico HSM Interface] (E6614104035DC431) 00 00 3b:fe:18:00:00:81:31:fe:45:80:31:81:54:48:53:4d:31:73:80:21:40:81:07:fa

Lack of end line.

python3 pico-hsm-tool.py --pin - the same.

DMESG:
4515.751306] usb 3-4.4: new full-speed USB device number 33 using xhci_hcd [ 4515.946418] usb 3-4.4: New USB device found, idVendor=234b, idProduct=0000, bcdDevice= 3.04 [ 4515.946425] usb 3-4.4: New USB device strings: Mfr=1, Product=2, SerialNumber=3 [ 4515.946427] usb 3-4.4: Product: Pico HSM CCID [ 4515.946428] usb 3-4.4: Manufacturer: Pol Henarejos [ 4515.946429] usb 3-4.4: SerialNumber: E6614104035DC431 [ 4903.460914] usb 3-4.4: USB disconnect, device number 33 [ 4903.874538] usb 3-4.4: new full-speed USB device number 34 using xhci_hcd [ 4908.374478] usb 3-4.4: new full-speed USB device number 35 using xhci_hcd [ 4908.566918] usb 3-4.4: New USB device found, idVendor=234b, idProduct=0000, bcdDevice= 3.04 [ 4908.566932] usb 3-4.4: New USB device strings: Mfr=1, Product=2, SerialNumber=3 [ 4908.566938] usb 3-4.4: Product: Pico HSM CCID [ 4908.566942] usb 3-4.4: Manufacturer: Pol Henarejos [ 4908.566946] usb 3-4.4: SerialNumber: E6614104035DC431

I tested the software on RPi Pico and RPi Pico-W.

BR
Kamil

mistake in pico-hsm-tool.py

Hi all,

Very good job ... an HSM module for 4 euros !

Line 114 it should be
parser._init.add_argument('--pin', help='PIN number')
not
parser.add_argument('--pin', help='PIN number')

Line 131 it should be
parser_rtc_get = subparser_rtc.add_parser('get', help='Gets the current datetime.')
not
parser_rtc_get = subparser_rtc.add_parser('set', help='Gets the current datetime.')

bye

pico-hsm 2.6 becomes unavailable after first boot

When building 2.6 release with custom VID/PID so that pcscd recognizes the hardware, copying the uf2 file to a Waveshare RP2040 Zero, the pico-hsm gets recognized by sc-hsm-tool and I can initialize it and create a RSA key using pkcs11-tool.

After reboot, the pcio-hsm seems to be stuck and no dmes output appears.

The most success I had on Debian. On Arch/EndeavorOS, the pico-hsm gets recognized after uploading the firmware file but even sc-hsm-tool is not able to initialize it and it hangs.

I suspect that maybe the driver to interact with the smartcard APDUs somehow blocks the card and corrupts it somehow. Maybe I selected also a wrong VID/PID combination that uses different commands/timings to interact? Just guessing here as I cannot make sense out of the debug output of pcscd -f -d.

Also on Windows when trying to use Smartcardshell3 (patched) this somewhat works just after the MCU resets during flashing but fails after unplug / plug of the board.

Is there some firstboot running, that needs to settle some time when it gets first used? Maybe I am too impatient and unplug when the card still rolls some internal dices?

Error importing dkek in development branch

I'm using the development branch because I hit the hanging issue on Ubuntu 22.04.

I'm following the dkek instructions and cannot get past an error when importing it.

********************************
*   PLEASE READ IT CAREFULLY   *
********************************

This tool will erase and reset your device. It will delete all private and secret keys.
Are you sure?
Pico HSM Tool v1.8
Author: Pol Henarejos
Report bugs to https://github.com/polhenarejos/pico-hsm/issues


[Press enter to confirm]
Public Point: 04f7f3ed82312e21654cff1d092cb55d10c6d6f783a9357c3e117e5b358a454643662e1fc557ef614f153b48a77ccc6dabfbbc1e0c03af56fb412f4a3d090d1cd0
Device name: ESPICOHSMTRZVZUV
Certificate uploaded successfully!

Note that the device is initialized with a default PIN and configuration.
Now you can initialize the device as usual with your chosen PIN and configuration options.

$ sc-hsm-tool --initialize --so-pin 1234123412341234 --pin 12341234 --dkek-shares 1
Using reader with a card: Free Software Initiative of Japan Gnuk [Pico HSM Interface] (DF60BCA003425C33) 00 00
$ sc-hsm-tool --import-dkek-share dkek.pbe --pin 12341234

Using reader with a card: Free Software Initiative of Japan Gnuk [Pico HSM Interface] (DF60BCA003425C33) 00 00
Enter password to decrypt DKEK share : 

Deciphering DKEK share, please wait...
sc_card_ctl(*, SC_CARDCTL_SC_HSM_IMPORT_DKEK_SHARE, *) failed with Not allowed```

security consideration info

At the same time, DKEK is encrypted with doubled salted and hashed PIN. Also, the PIN is hashed in memory during the session. Hence, PIN is never stored in plain text neither in flash nor in memory. Note that PIN is conveyed from the host to the HSM in plain text if no secure channel is provided.

If the Pico is stolen the contents of private and secret keys cannot be read without the PIN, even if the flash memory is dumped.

Could you detail resistance to brute force attack ?
Dumping to flash and try to brute force pin to recover DKEK.

What are the recommended pin len/complexity to prevent brute force attack ?

urllib.error.HTTPError: HTTP Error 500: Internal Server Error in "pico-hsm-tool.py" initialize command

When executing the python command - "python3 pico-hsm-tool.py initialize --so-pin 3537363231383830 "
I am facing an exception "urllib.error.HTTPError: HTTP Error 500: Internal Server"

PS D:\PICO\pico-hsm\tools> python3 pico-hsm-tool.py initialize --so-pin 3537363231383830


  • PLEASE READ IT CAREFULLY *

This tool will erase and reset your device. It will delete all private and secret keys.
Are you sure?
Pico HSM Tool v1.8
Author: Pol Henarejos
Report bugs to https://github.com/polhenarejos/pico-hsm/issues

[Press enter to confirm]
Public Point: 0499220c3a32eaed086a775774cb4fde1942b4fc15118ae4470d60af41f72de24f57d405e9c0fbaffd156ab84bc6c602e4121db4ac934364a080ad5fa769468a7e
Traceback (most recent call last):
File "D:\PICO\pico-hsm\tools\pico-hsm-tool.py", line 640, in
run()
File "D:\PICO\pico-hsm\tools\pico-hsm-tool.py", line 637, in run
main(args)
File "D:\PICO\pico-hsm\tools\pico-hsm-tool.py", line 618, in main
initialize(card, args)
File "D:\PICO\pico-hsm\tools\pico-hsm-tool.py", line 277, in initialize
j = get_pki_data('cvc', data=data)
File "D:\PICO\pico-hsm\tools\pico-hsm-tool.py", line 199, in get_pki_data
response = urllib.request.urlopen(req)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\urllib\request.py", line 216, in urlopen
return opener.open(url, data, timeout)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\urllib\request.py", line 525, in open
response = meth(req, response)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\urllib\request.py", line 634, in http_response
response = self.parent.error(
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\urllib\request.py", line 563, in error
return self._call_chain(*args)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\urllib\request.py", line 496, in _call_chain
result = func(*args)
File "C:\Program Files\WindowsApps\PythonSoftwareFoundation.Python.3.10_3.10.3056.0_x64__qbz5n2kfra8p0\lib\urllib\request.py", line 643, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 500: Internal Server Error

ERROR - common.h missing

Hi,

I have tried numerous times not to 'make' but I get the following:

[ 25%] Building C object CMakeFiles/pico_hsm.dir/src/hsm/sc_hsm.c.obj
In file included from /home/tinus/pico-hsm/src/hsm/sc_hsm.c:18:
/home/tinus/pico-hsm/src/hsm/sc_hsm.h:22:10: fatal error: common.h: No such file or directory
#include "common.h"
^~~~~~~~~~
compilation terminated.
make[2]: *** [CMakeFiles/pico_hsm.dir/build.make:82: CMakeFiles/pico_hsm.dir/src/hsm/sc_hsm.c.obj] Error 1
make[1]: *** [CMakeFiles/Makefile2:1767: CMakeFiles/pico_hsm.dir/all] Error 2
make: *** [Makefile:103: all] Error

PLEASE HELP! :)
Tinus

CKR_USER_PIN_NOT_INITIALIZED / failed with Incorrect parameters in APDU

Thanks for the latest code changes. With them, I could build a recent version for RP2040 Waveshare Zero.
After nuking the flash I have installed the uf2 file. I build the uf2 using the latest code in repo using the following commands on Debian 11:

export PICO_SDK_PATH=~/Devel/pico/pico-sdk
export USB_VID=0x234b
export USB_PID=0x0000
export PICO_BOARD=waveshare_rp2040_zero 
cmake .. -DENABLE_DELAYED_BOOT=1 -DPICO_BOARD=$PICO_BOARD -DUSB_VID=${USB_VID} -DUSB_PID=${USB_PID}
make -j4

I also compiled latest git versions of opensc and sc-hsm-embedded.

After flashing, unplugging and inserting the RP2040 it gets recognized:

$ sudo dmesg
[ 2671.810277] usb 2-2: new full-speed USB device number 8 using ohci-pci
[ 2672.163479] usb 2-2: New USB device found, idVendor=234b, idProduct=0000, bcdDevice= 3.04
[ 2672.163482] usb 2-2: New USB device strings: Mfr=1, Product=2, SerialNumber=3
[ 2672.163483] usb 2-2: Product: Pico HSM CCID
[ 2672.163484] usb 2-2: Manufacturer: Pol Henarejos
[ 2672.163485] usb 2-2: SerialNumber: E66138935F5B1A28

Initialization seems to somewhat work but shows error message Incorrect parameters in APDU:

$ sc-hsm-tool 
Using reader with a card: Free Software Initiative of Japan Gnuk [Pico HSM Interface] (E66138935F5B1A28) 00 00
Version              : 2.6
SmartCard-HSM has never been initialized. Please use --initialize to set SO-PIN and user PIN.
sc_card_ctl(*, SC_CARDCTL_SC_HSM_IMPORT_DKEK_SHARE, *) failed with Incorrect parameters in APDU
DKEK shares          : 0
DKEK key check value : 0000000000000000

$  sc-hsm-tool --initialize --so-pin 3537363231383830 --pin 648219
Using reader with a card: Free Software Initiative of Japan Gnuk [Pico HSM Interface] (E66138935F5B1A28) 00 00

$ sc-hsm-tool 
Using reader with a card: Free Software Initiative of Japan Gnuk [Pico HSM Interface] (E66138935F5B1A28) 00 00
Version              : 2.6
Config options       :
  User PIN reset with SO-PIN enabled
SO-PIN tries left    : 15
User PIN tries left  : 3
sc_card_ctl(*, SC_CARDCTL_SC_HSM_IMPORT_DKEK_SHARE, *) failed with Incorrect parameters in APDU
DKEK shares          : 0
DKEK key check value : 0000000000000000

$ pkcs11-tool --login --login-type so --so-pin 3537363231383830 --change-pin --new-pin 0123456789012345
Using slot 0 with a present token (0x0)
error: PKCS11 function C_SetPIN failed: rv = CKR_USER_PIN_NOT_INITIALIZED (0x102)
Aborting.

$ pkcs11-tool -l --pin 648219 --keypairgen --key-type rsa:2048 --id 1 --label "RSA2K"
Using slot 0 with a present token (0x0)
error: PKCS11 function C_Login failed: rv = CKR_USER_PIN_NOT_INITIALIZED (0x102)
Aborting.

$ sc-tool -l --pin 648219 --keypairgen --key-type rsa:2048 --id 1 --label "RSA2K"
No slot with a token was found.

$ sc-tool --login --login-type so --so-pin 3537363231383830 --change-pin --new-pin 0123456789012345
No slot with a token was found.

$ sc-tool -I
Cryptoki version 2.20
Manufacturer     CardContact (www.cardcontact.de)
Library          SmartCard-HSM via PC/SC (ver 2.12)
No slot with a token was found.

Similar experience also with tools from opensc Debian package but I wanted to test potential fixes from upstream git version / CardContact tools.

Am I doing something wrong (e.g. wrong VID/PID) or are there some differences in the Waveshare board? I also notice that the LED is not working. Or is this only happening when running user APDUs to enable user confirmation?

It would be good to know some details about OS/tools versions that you use in order to build/test on your devel machine.
I will also source some Pimoroni Tiny2040 to compare with the expected behaviour.

CardContact/Nitrokey HSM works fine:

$ sc-tool -I
Cryptoki version 2.20
Manufacturer     CardContact (www.cardcontact.de)
Library          SmartCard-HSM via PC/SC (ver 2.12)
Using slot 0 with a present token (0x1)

$ sc-hsm-tool 
Using reader with a card: Nitrokey Nitrokey HSM (DE00000000         ) 00 00
Version              : 3.5
Config options       :
  User PIN reset with SO-PIN enabled
SO-PIN tries left    : 15
User PIN tries left  : 3

$ sc-tool -l --pin ** --keypairgen --key-type rsa:2048 --id 1 --label "RSA2K"
Using slot 0 with a present token (0x1)
Key pair generated:
Private Key Object; RSA 
  label:      RSA2K
  ID:         01
  Usage:      decrypt, sign
  Access:     sensitive, always sensitive, never extractable, local
Public Key Object; RSA 2048 bits
  label:      RSA2K
  ID:         01
  Usage:      encrypt, verify
  Access:     local

pico-hsm-tool urllib.error.HTTPError: HTTP Error 500: Internal Server Error

looks like this error is back?

using pico 3.2 firmware
Python 3.11.6
Ubuntu 23.10

./pico-hsm-tool.py --pin 648219 initialize --so-pin 648219


  • PLEASE READ IT CAREFULLY *

This tool will erase and reset your device. It will delete all private and secret keys.
Are you sure?
Pico HSM Tool v1.10
Author: Pol Henarejos
Report bugs to https://github.com/polhenarejos/pico-hsm/issues

[Press enter to confirm]
Public Point: 0486d34865bbf6b4aabf431dc94cbfdecf3901e4f2db315fe593cdd43080c258ddc6074f8ecfd11e7af3e535cc67da5c6b969025f928d2b96e895345582a0924e5
Traceback (most recent call last):
File "/home/cicero/hsmtesting/pico-hsm/tools/./pico-hsm-tool.py", line 491, in
run()
File "/home/cicero/hsmtesting/pico-hsm/tools/./pico-hsm-tool.py", line 488, in run
main(args)
File "/home/cicero/hsmtesting/pico-hsm/tools/./pico-hsm-tool.py", line 469, in main
initialize(picohsm, args)
File "/home/cicero/hsmtesting/pico-hsm/tools/./pico-hsm-tool.py", line 217, in initialize
j = get_pki_data('cvc', data=data)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/cicero/hsmtesting/pico-hsm/tools/./pico-hsm-tool.py", line 153, in get_pki_data
response = urllib.request.urlopen(req)
^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/urllib/request.py", line 216, in urlopen
return opener.open(url, data, timeout)
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/urllib/request.py", line 525, in open
response = meth(req, response)
^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/urllib/request.py", line 634, in http_response
response = self.parent.error(
^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/urllib/request.py", line 563, in error
return self._call_chain(*args)
^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.11/urllib/request.py", line 496, in _call_chain
result = func(*args)
^^^^^^^^^^^
File "/usr/lib/python3.11/urllib/request.py", line 643, in http_error_default
raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 500: Internal Server Error

Strange behaviours betwwen Windows 10 & 11

Hi Pol,

With the same pico device I have two radically different behaviours between Windows 10 and 11, with the same open-cs version.

opensc-tool --version OpenSC-0.23.0, rev: 5497519e, commit-time: 2022-11-29 09:34:43 +0100

On Windows 11
opensc-tool -na Using reader with a card: Broadcom Corp Contacted SmartCard 0 Card not present. Failed to connect to reader: Card not present

On Windows 10
opensc-tool -na Using reader with a card: Pol Henarejos Pico Key 0 3b:fe:18:00:00:81:31:fe:45:80:31:81:54:48:53:4d:31:73:80:21:40:81:07:fa SmartCard-HSM version 3.4

... one can see version 3.4 using the uf2 firmware file named pico_hsm_pico-3.2.uf2.

pkcs15-tool is OK on Windows 10 but give also a card not dectected message on Windows 11

pkcs15-tool.exe -D Using reader with a card: Broadcom Corp Contacted SmartCard 0 Card not present.

But on both operating system using XCA with the dll (64bits) from CardContact I can create and use keys (not the dll coming from open/SC setup where the pin code is not requested when working with the card ... so fail bad PIN.

I'm also able to create key on both operting systems using pkcs11-tool commands such as

pkcs11-tool -l --pin 000000 --keypairgen --key-type EC:secp256r1 --id 1 --label "secp256"

Bye.

Unable to restore PicoHSM Private key (Issue importing DKEK?)

Hi,

I am following the instructions for Backup and restore to setup my Pico HSM with a known DKEK so that it is possible to backup/restore the keys in it. So far all steps seem successful except that I am unable to restore (unwrap) a backed up key.

I suspect there is an issue with the import of the DKEK as when importing the DKEK with (sensitive data is stored in environment variables):

sc-hsm-tool --initialize --so-pin env:HSM_SOPIN  --pin env:HSM_PIN --dkek-shares 1
sc-hsm-tool --import-dkek-share dkek.pbe--password env:DKEK_PASSWORD

I always get output like:

Using reader with a card: Pol Henarejos Pico Key CCID Interface
Deciphering DKEK share, please wait...
DKEK share imported
DKEK shares          : 1
DKEK key check value : 0000000000000000

This also happens when I initialise it with multiple DKEK files, the check value being 0000000000000000 does not seem to be correct (is at least not what I would expect). However, this is always the case with every dkek.pbe file I generate (and these files are not the same)

I have wrapped the a 2048 bit RSA key (tried with and without loadin the cert) with:

sc-hsm-tool --pin env:HSM_PIN --wrap-key hsm-wrapped-key.bin--key-reference 1

but when I try to load is back after I have reinitialised the PicoHSM) with:

sc-hsm-tool --pin env:HSM_PIN --unwrap-key hsm-wrapped-key.bin --key-reference 1 --force

I get the following output:

Using reader with a card: Pol Henarejos Pico Key CCID Interface
Wrapped key contains:
  Key blob
  Private Key Description (PRKD)
  Certificate
sc_card_ctl(*, SC_CARDCTL_SC_HSM_UNWRAP_KEY, *) failed with Reference data not usable

The device I am using is a WaveShare Pico RP2040 Zero and us image pico_hsm_waveshare_rp2040_zero-3.6.gnuk.uf2.

I also tried to use pico_hsm_waveshare_rp2040_zero-3.4.gnuk.uf2 but tht could not load a DKEK at all with my board

Is there something I am missing in my steps or is this a (known) issue? Any help or hints would be appreciated.

regards,

Frederik

How to list pkcs11 url of the private key?

For signing an intermediate CA with openssl, I need to state the pkcs11 URL in the config file.
I can list the public keys but fail to do so for the private keys:

p11tool --list-all pkcs11:model=PKCS%2315%20emulated;manufacturer=Pol%20Henarejos;serial=ESPICOHSMTR;token=Pico-HSM%20%28UserPIN%29
Object 0:
        URL: pkcs11:model=PKCS%2315%20emulated;manufacturer=Pol%20Henarejos;serial=ESPICOHSMTR;token=Pico-HSM%20%28UserPIN%29;id=%01;object=RSA2K;type=public
        Type: Public key (RSA-2048)
        Label: RSA2K
        Flags: CKA_WRAP/UNWRAP;
        ID: 01

Object 1:
        URL: pkcs11:model=PKCS%2315%20emulated;manufacturer=Pol%20Henarejos;serial=ESPICOHSMTR;token=Pico-HSM%20%28UserPIN%29;id=%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00%00;object=ESPICOHSMTR;type=public
        Type: Public key (EC/ECDSA-SECP256R1)
        Label: ESPICOHSMTR
        ID: 00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00:00

Object 2:
        URL: pkcs11:model=PKCS%2315%20emulated;manufacturer=Pol%20Henarejos;serial=ESPICOHSMTR;token=Pico-HSM%20%28UserPIN%29;id=%11;object=ECDSA;type=public
        Type: Public key (EC/ECDSA-SECP192R1)
        Label: ECDSA
        ID: 11

Object 3:
        URL: pkcs11:model=PKCS%2315%20emulated;manufacturer=Pol%20Henarejos;serial=ESPICOHSMTR;token=Pico-HSM%20%28UserPIN%29;id=%6B%52%23%26%27%0F%20%10%7F%64%A4%31%FB%EE%05%0D%9F%29%F9%77;object=root;type=public
        Type: Public key (EC/ECDSA-SECP384R1)
        Label: root
        ID: 6b:52:23:26:27:0f:20:10:7f:64:a4:31:fb:ee:05:0d:9f:29:f9:77

Object 4:
        URL: pkcs11:model=PKCS%2315%20emulated;manufacturer=Pol%20Henarejos;serial=ESPICOHSMTR;token=Pico-HSM%20%28UserPIN%29;id=%8C%23%52%12%36%77%D5%04%AB%A4%86%89%F7%88%77%C4%A2%97%11%00;object=intermediate;type=public
        Type: Public key (EC/ECDSA-SECP384R1)
        Label: intermediate
        ID: 8c:23:52:12:36:77:d5:04:ab:a4:86:89:f7:88:77:c4:a2:97:11:00
export GNUTLS_PIN=648219
p11tool --login --list-all pkcs11:model=PKCS%2315%20emulated;manufacturer=Pol%20Henarejos;serial=ESPICOHSMTR;token=Pico-HSM%20%28UserPIN%29
Error in crt_list_import (1): Error in provided PIN.

Is this the correct way to get those URLs? Any alternatve to get those?

Press-to-confirm button

Hello!

Thank you for the great project!

According to this description

https://github.com/polhenarejos/pico-hsm/blob/98e9b72b42a128d5cc2bd74dedb742a59662ccc0/doc/extra_command.md#press-to-confirm-button

It seems the press-to-confirm function can be enabled and disabled without requiring any authentication. This raises a concern that malware could potentially disable it without notice, rendering the press-to-confirm control ineffective. Is it possible lock this setting to prevent such actions?

pico-hsm-patch-vidpid.sh does not work as expected

Right now, the tool pico-hsm-patch-vidpid.sh cannot be used to patch vid/pid and produces unmodified output:

d=`mktemp -d`
cd $d
wget https://github.com/polhenarejos/pico-hsm/releases/download/v2.6/pico_hsm_waveshare_rp2040_zero-2.6.uf2
wget https://github.com/polhenarejos/pico-hsm/raw/master/tools/pico-hsm-patch-vidpid.sh
chmod +x pico-hsm-patch-vidpid.sh
perl --version
#(...)This is perl 5, version 36, subversion 0 (v5.36.0) built for x86_64-linux-thread-multi(...)
/pico-hsm-patch-vidpid.sh abcd:1234 pico_hsm_waveshare_rp2040_zero-2.6.uf2 pico_hsm_waveshare_rp2040_zero-2.6.uf2.patched 
#----------------------------
#VID/PID patcher for Pico HSM
#----------------------------
#
#Patching pico_hsm_waveshare_rp2040_zero-2.6.uf2... Done!
#
#Patched file was saved in pico_hsm_waveshare_rp2040_zero-2.6.uf2.patched
md5sum pico_hsm_waveshare_rp2040_zero-2.6.uf2*
#2a595f9a4aa893e5dc200429dcdc3564  pico_hsm_waveshare_rp2040_zero-2.6.uf2
#2a595f9a4aa893e5dc200429dcdc3564  pico_hsm_waveshare_rp2040_zero-2.6.uf2.patched
cd
rm -rf $d

Usage in Python

Hi! I want to use your project in mine, can you please write documents about usage in Python (Specifically CircuitPython)? Thanks.

Unable to initialize a new Pico-HSM

Hi,

I am trying this very interesting project but when trying to initialize a new Pico-HSM and bump into 2 issues:

  1. The --pin option for the initialise subcommand of python pico-hsm-tool.py does not seem to work as documented
  2. When executing the initialize command without a --pin (or when I put it before the initialise keyword) results in an issue:
tools % python pico-hsm-tool.py initialize --so-pin 3537363231383830
********************************
*   PLEASE READ IT CAREFULLY   *
********************************

This tool will erase and reset your device. It will delete all private and secret keys.
Are you sure?
Pico HSM Tool v1.8
Author: Pol Henarejos
Report bugs to https://github.com/polhenarejos/pico-hsm/issues


[Press enter to confirm]
Public Point: 04e5e6192c215f560abf97e84c80317ce4ef9f47a939783189e0b86bd54019ec069a6425a59e1251cf343596e98ebed10856a508347a995649aed671548f24c45a
Traceback (most recent call last):
  File "/Users/me/projects/pico-hsm/tools/pico-hsm-tool.py", line 638, in <module>
    run()
  File "/Users/me/projects/pico-hsm/tools/pico-hsm-tool.py", line 635, in run
    main(args)
  File "/Users/me/projects/pico-hsm/tools/pico-hsm-tool.py", line 616, in main
    initialize(card, args)
  File "/Users/me/projects/pico-hsm/tools/pico-hsm-tool.py", line 275, in initialize
    j = get_pki_data('cvc', data=data)
  File "/Users/me/projects/pico-hsm/tools/pico-hsm-tool.py", line 199, in get_pki_data
    response = urllib.request.urlopen(req)
  File "/usr/local/Cellar/[email protected]/3.10.9/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 216, in urlopen
    return opener.open(url, data, timeout)
  File "/usr/local/Cellar/[email protected]/3.10.9/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 525, in open
    response = meth(req, response)
  File "/usr/local/Cellar/[email protected]/3.10.9/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 634, in http_response
    response = self.parent.error(
  File "/usr/local/Cellar/[email protected]/3.10.9/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 563, in error
    return self._call_chain(*args)
  File "/usr/local/Cellar/[email protected]/3.10.9/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 496, in _call_chain
    result = func(*args)
  File "/usr/local/Cellar/[email protected]/3.10.9/Frameworks/Python.framework/Versions/3.10/lib/python3.10/urllib/request.py", line 643, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 500: Internal Server Error

It looks like the initiallization calls an external web service that doesn't function as expected. Any clue what is going wrong and would it be possible to explain this process (i.e. why is it using an external service and for what?) so that the dependency is clear?

any help is appreciated!

Thanks!

Frederik

ECDH derived key is missing one byte compared with openssl-pkeyutl

Issue

In a hybrid scenario where one symmetric key is derived on the HSM and the partner derives it in software with openssl pkeyutl, there is a single byte at the beginning missing when comparing both derived keys.

General Info

Using Waveshare RP2040 One with latest stable release.

$ sc-tool -I
Cryptoki version 2.20
Manufacturer     CardContact (www.cardcontact.de)
Library          SmartCard-HSM via PC/SC (ver 2.12)
Using slot 0 with a present token (0x1)

$ sc-tool -M
Using slot 0 with a present token (0x1)
Supported mechanisms:
  RSA-X-509, keySize={1024,4096}, hw, decrypt, sign
  RSA-PKCS, keySize={1024,4096}, hw, decrypt, sign
  RSA-PKCS-PSS, keySize={1024,4096}, hw, sign
  SHA1-RSA-PKCS, keySize={1024,4096}, hw, sign
  SHA256-RSA-PKCS, keySize={1024,4096}, hw, sign
  SHA1-RSA-PKCS-PSS, keySize={1024,4096}, hw, sign
  SHA256-RSA-PKCS-PSS, keySize={1024,4096}, hw, sign
  ECDSA, keySize={192,521}, hw, sign
  ECDSA-SHA1, keySize={192,521}, hw, sign
  AES-CBC, keySize={16,32}, hw, encrypt, decrypt
  AES-CMAC, keySize={16,32}, hw, sign
  ECDSA-KEY-PAIR-GEN, keySize={192,521}, hw, generate_key_pair
  RSA-PKCS-KEY-PAIR-GEN, keySize={1024,4096}, hw, generate_key_pair
  AES-KEY-GEN, keySize={16,32}, hw, generate
  mechtype-0x80000001, keySize={1024,4096}, hw, sign
  mechtype-0x80000003, keySize={1024,4096}, hw, sign
  mechtype-0x80000010, keySize={192,521}, hw, sign
  mechtype-0x80000011, keySize={192,521}, hw, sign

$ sc-tool -O
Using slot 0 with a present token (0x1)
Certificate Object; type = unknown cert type
  label:      C.DevAut
Certificate Object; type = unknown cert type
  label:      C.DICA
Public Key Object; RSA 2048 bits
  label:      RSA2K
  ID:         01
  Usage:      encrypt, verify
  Access:     local
Public Key Object; EC  EC_POINT 192 bits
  EC_POINT:   0431040dcdc12372f719b30294579a6e0117653ea6d3ba7a2881217e7fecc79f76823f3533877607238123d3eda9c4dd48887b
  EC_PARAMS:  06082a8648ce3d030101
  label:      ECDSA
  ID:         11
  Usage:      encrypt, verify
  Access:     local


$ pkcs11-tool -I
Cryptoki version 3.0
Manufacturer     OpenSC Project
Library          OpenSC smartcard framework (ver 0.23)
Using slot 0 with a present token (0x0)

alias sc-tool='/tmp/tmp.uUVSWTVRrA/opensc-compiled/pkcs11-tool --module /tmp/tmp.uUVSWTVRrA/opensc-compiled/libsc-hsm-pkcs11.so'

How to reproduce

openssl ecparam -genkey -name prime192v1 > bob.pem
openssl ec -in bob.pem -pubout -outform DER > bob.der
sc-tool -l --pin 648219 --delete-object --type privkey --id 11
sc-tool -l --pin 648219 --keypairgen --key-type EC:secp192r1 --id 11 --label "ECDSA"
pkcs11-tool --read-object --pin 648219 --id 11 --type pubkey > 11.der
openssl ec -inform DER -outform PEM -in 11.der -pubin > 11.pub
pkcs11-tool --pin 648219 --id 11 --derive -i bob.der -o mine-bob.der
openssl pkeyutl -derive -out bob-mine.der -inkey bob.pem -peerkey 11.pub

xxd bob-mine.der
# 00000000: 1b39 a93c 2948 2b66 6677 5967 02c7 27a1  .9.<)H+ffwYg..'.
# 00000010: ce5a f6b6 197b 42ff                      .Z...{B.
xxd mine-bob.der
# 00000000: 39a9 3c29 482b 6666 7759 6702 c727 a1ce  9.<)H+ffwYg..'..
# 00000010: 5af6 b619 7b42 ff                        Z...{B.

openssl pkeyutil -derive key in this example contains an additional 1b. This is different with every fresh ecdh parameter set but always the first byte is missing in the HSM output of the derived key.

AES Encrypt / Decrypt

Morning,

Testing Pico HSM with a number of different RP2040's and it works very well.

I'm having a problem with AES encryption process

I've built my Ubuntu 22.04 using the following

sudo apt-get install libusb-dev libusb++ -y
sudo apt-get install libccid -y
sudo apt-get install pcscd -y
sudo apt-get install libpcsclite1 -y
sudo apt-get install libpcsclite-dev -y
sudo apt-get install libpcsc-perl -y
sudo apt-get install pcsc-tools -y
sudo apt-get update -y
sudo apt install opensc -y
sudo apt install pkgconf libssl-dev -y
sudo apt-get install autoconf -y
sudo apt install libtool-bin -y

sudo apt install pip -y
sudo apt install swig -y
pip install pyscard
pip install pycvc

git clone https://github.com/polhenarejos/pico-hsm.git
git clone https://github.com/OpenSC/OpenSC.git
git clone https://github.com/OpenSC/libp11.git
cd libp11
./bootstrap
./configure && make
make check
sudo make install
cd ..

git clone https://github.com/CardContact/sc-hsm-embedded.git
cd sc-hsm-embedded
autoreconf -fi
./configure && make
sudo make install
cd ..

alias sc-tool='pkcs11-tool --module /usr/local/lib/libsc-hsm-pkcs11.so'

ls /usr/lib/x86_64-linux-gnu/engines-3/pkcs11.so
ls /usr/lib/x86_64-linux-gnu/opensc-pkcs11.so

All works fine, but when I use the AES example given in the doc's

echo "This is a text." | sc-tool -l --pin 123456 --encrypt --id 12 --mechanism aes-cbc > crypted.aes

I get

pkcs11-tool: unrecognized option '--encrypt'

Am I using the module for pkcs11?

M

USB not recognized

hi
Iv updated the code to release 4.0 , build it ok without errors (on debian running inside VMware)
but after flashing the firmware it is no more recognized - im getting an error on windows (usb not recognized) and also cant mount it on linux
i also tried with a prebuild uf2 file from the repo here and the same problem
test it on pico simple board and also on seeed xiao

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.