Git Product home page Git Product logo

pico-hsm's Introduction

Raspberry Pico HSM

This is a project to create a Hardware Security Module (HSM) with a Raspberry Pico. It converts your Pico board into a HSM which is able to generate and store private keys, encrypt or decrypt with AES or signing data without to disclose the private key. In detail, the private key never leaves the board and it cannot be retrieved as it is encrypted in the flash memory.

Capabilities

> Key generation and encrypted storage

Private and secret keys are stored with a master AES 256 key (MKEK). The MKEK is, at the same time, 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 from 1024 to 4096 bits

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

> ECDSA key generation from 192 to 521 bits

ECDSA key generation in place for different curves, from 192 to 521 bits.

> ECC curves

It supports secp192r1, secp256r1, secp384r1, secp521r1, brainpoolP256r1, brainpoolP384r1, brainpoolP512r1, secp192k1 (insecure), secp256k1 curves. Also Curve25519 and Curve448.

> SHA1, SHA224, SHA256, SHA384, SHA512 digests

ECDSA and RSA signature can be combined with SHA digest in place.

> Multiple RSA signature algorithms

It supports RSA-PSS, RSA-PKCS and raw RSA signatures.

> ECDSA raw and hash signature

ECDSA signatures can be in raw or pre-hashed formats.

> ECDH key derivation

It supports the calculation of shared secrets with ECDH algorithm.

> EC private key derivation

It allows ECDSA key derivation.1

> RSA-OEP and RSA-X-509 decryption

It allows private decryption in place with RSA-OEP and RSA-X-509 algorithms.

> AES key generation

It supports AES key generation in place with keys of 128, 192 and 256 bits.

> AES-CBC encryption/decryption

Legacy AES encryption and decryption is performed in place.

> AES ECB, CBC, CFB, OFB, XTS, CTR, GCM and CCM

Advanced AES encryption and decryption with multiples modes and customized IV/nonce and additional authenticated data (AAD).2

> AES key generation of 128, 192, 256 and 512 bits.

Besides 128, 192 and 256 bits, Pico HSM also supports key generation of 512 bits (64 bytes). These keys are specially indicated for running AES XTS, where two keys of 256 bits are concatenated.

> CMAC

It supports AES-CMAC authentication.1

> AES derivation

It supports AES secret key derivation.1

> PIN authorization

Private and secret keys cannot be used without prior PIN authentication. It supports alphanumeric PIN.

> PKCS11 compliant interface

The module can be interfaced with PKCS11 standard.

> HRNG (hardware random number generator)

It contains a harware random number generator properly modeled to guarantee maximum entropy.

> Device Key Encryption Key (DKEK) shares

It supports DKEK share imports. DKEK are used to wrap, unwrap and encrypt private and secret keys in the device.

> DKEK n-of-m threshold scheme

It supports a n-of-m threshold scheme to minimize outage when a DKEK custodian is not available during the import process.

> USB/CCID support with OpenSC, openssl, etc.

Pico HSM has a full USB CCID stack to communicate with the host via OpenSC and PCSC. It allows the use of frontend applications such as OpenSSL via PKCS11 module.

> Extended APDU support

It supports extended APDU packets, which allows up to 65535 bytes.

> CV Certificates

Pico HSM manipulates CVC certificates and requests to minimize the storage of internal certificates.

> Attestation

Every generated key is attached to a certificate, signed by an external PKI to ensure that a particular key is effectively generated by this specific device.

> Import external private keys and certificates

It allows private key and certificates import via WKY or PKCS#12 files.34

> Tranport PIN

It allows transport PIN for provisioning and forcing to set a new PIN.3 It is a tampered mechanism that ensures the device has not been unsealed during the transportation from the issuer to the legitimate user.

> Press-to-confirm button

It allows the use of BOOTSEL button to confirm operations with private/secret keys, such as signatures and decryption. When a private/secret key is loaded, the user has 15 seconds to press the button to confirm the operation. This feature protects the user from unwanted uses from background applications that may sign data without user notice.

> Store and retrieve binary data

It allows the storage of arbitrary files with binary data.

> Real time clock (RTC)

Pico HSM has a RTC with external datetime setting and getting.

> Secure Messaging (secure channel)

Pico HSM supports secure channel, where the data packets between the host and device are encrypted to avoid man-in-the-middle attacks.

> Session PIN

A specific session PIN can be set during the session opening to avoid the systemmatic use of PIN.

> PKI CVCert remote issuing for Secure Message

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

> Multiple key domains

Key domains are domains to store separate private/secret keys. Each domain is protected by a DKEK, independent from the other domains. Private/secret keys can be generated in different key domains to be used with separated DKEK. Therefore, a single device may contain different domains with independent keys.

> Key usage counter

A key usage counter is a counter that is reduced by 1 everytime that the private/secret key is used for signing, decrypting, derivation, etc. When it reaches 0, the key is disabled and cannot be used anymore.

Key usage can also be used to perform and auditory and track the usage of a particular key.

> Public Key Authentication

Public Key Authentication (PKA) allows to authenticate by using a secondary device with a private key and a registered public key in the primary device. A challenge is generated by the primary Pico HSM and given to the secondary for signature. The secondary device signs the challenge and returns the signature. Then, the primary device verifies the signature with the registered public key and if it is valid, it grants full access, as normal PIN authentication.

In PKA, the PIN is used for protecting the MKEK, as classic method with only PIN, and PKA is used for adding an extra security layer. Therefore, this mechanism provides a higher degree of security, since it needs a secondary Pico HSM to authenticate the primary one.

> Secure Lock

An extra layer can be added to the device by adding a private key stored on the computer to lock that Pico HSM to the specific computer. The content will be completely encrypted with a private key only available from a specific computer.

> ChaCha20-Poly1305

This is a novel fast and efficient symmetric encryption algorithm. Similarly to AES, it can be used to cipher your private data.2

> X25519 and X448

Both cruves Curve25519 and Curve448 are supported for doing DH X25519 and X448. Remember that cannot be used for signing.

> Key Derivation Functions: HKDF, PBKDF2 and X963-KDF

It supports symmetric key derivations from different standards and RFC.

> HMAC

It supports performing HMAC from a secret key on an arbitrary data with SHA digest algorithm.

> CMAC

Similarly to HMAC, Pico HSM also supports CMAC with AES algorithm for keys of 128, 192 and 256 bits.

> XKEK

Besides DKEK, it supports a more advanced scheme to share keys. Based on private key domains, it is possible to wrap and unwrap private and secret keys inside the domain to only authorized devices. If a device outside the domain tries to unwrap a key, it will fail.

> MKEK

A Master Key Encryption Key is used to store safely all the keys. This key is also ciphered with an ephemereal key derived from the hashed PIN. Therefore, we can ensure all the keys are encrypted and stored.

> Hierarchical Deterministic key generation

It supports BIP32 for asymmetric deterministic key derivation and SLIP10 for symmetric key derivation. With it, crypto wallets can be deployed with Pico HSM, as infinite keys can be derived for signature and symmetric encryption. Curves NIST 256 and Koblitz 256 are supported for master key generation.2

Security considerations

All secret keys (asymmetric and symmetric) are stored encrypted in the flash memory of the Raspberry Pico. DKEK is used as a 256 bit AES key to protect private and secret keys. Keys are never stored in RAM except for signature and decryption operations and only during the process. All keys (including DKEK) are loaded and cleared every time to avoid potential security flaws.

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.

Download

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 are planning to use it with OpenSC or similar, 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.

After make ends, the binary file pico_hsm.uf2 will be generated. Put your pico board into loading mode, by pushing BOOTSEL button while pluging on, and copy the UF2 to the new fresh usb mass storage Pico device. Once copied, the pico mass storage will be disconnected automatically and the pico board will reset with the new firmware. A blinking led will indicate 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. It is like having a physical reader with an inserted SIM card. We recommend the use of OpenSC to communicate with the reader. If it is not installed, you can download and build it or install the binaries for your system. The first command is to ensure that the Pico is detected as a HSM:

opensc-tool -an

It should return a text like the following:

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 initialization and asymmetric operations, check doc/usage.md.

For signing and verification operations, check doc/sign-verify.md.

For asymmetric encryption and decryption, check doc/asymmetric-ciphering.md.

For backup, restore and DKEK share management, check doc/backup-and-restore.md.

For AES key generation, encryption and decryption, check doc/aes.md.

For 4096 bits RSA support, check doc/scs3.md.

For storing and retrieving arbitrary data, check doc/store_data.md.

For extra options, such as set/get real datetime or enable/disable press-to-confirm button, check doc/extra_command.md.

For Public Key Authentication, check doc/public_key_authentication.md.

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

Raspberry Pico comes with the BOOTSEL button to load the firmware. When this firmware is running, the button can be used for other purposes. Pico HSM uses this button to confirm private/secret operations. This feature is optional and it shall be enabled. For more information, see doc/extra_command.md.

With this feature enabled, everytime that a private/secret key is loaded, the Pico HSM awaits for the user confirmation by pressing the BOOTSEL button. The Led of the Pico HSM will remain almost illuminated, turning off quickly once a second, indicating that the user must press the button to confirm the operation. Otherwise, the Pico HSM waits indefinitely. See Led blink for a picture of the blinking sequence. When in this mode, the Pico HSM sends periodic timeout commands to the host to do not trigger the timeout operation.

This feature is an extra layer of security, as it requires the user intervention to sign or decrypt and it ensures that any application will use the Pico HSM without user awareness. However, it is not recommended for servers or other environments where operations are authomatized, since it requires a physical access to the Pico HSM to push the button.

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

Pico HSM uses the sc-hsm driver provided by OpenSC or the sc-hsm-embedded driver provided by CardContact. This driver utilizes the standardized PKCS#11 interface to communicate with the user and it can be used with many engines that accept PKCS#11 interface, such as OpenSSL, P11 library or pkcs11-tool.

Pico HSM relies on PKCS#15 structure to store and manipulate the internal files (PINs, private keys, certificates, etc.) and directories. Therefore, it accepts the commands from pkcs15-tool. For instance, pkcs15-tool -D will list all elements stored in the Pico HSM.

The way to communicate is exactly the same as with other cards, such as OpenPGP or similar.

For an advanced usage, see the docs and examples.

Pico HSM also supports SCS3 tool for advanced use and multiple key domain. See SCS3 for more information.

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 must patch the UF2 binary (if you just downloaded from the Release section) or 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. 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

  2. Available by using PicoHSM python tool. โ†ฉ โ†ฉ2 โ†ฉ3

  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

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

pico-hsm's Issues

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

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.

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

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

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?

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?

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-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

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```

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.

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.

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.

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]

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 ?

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.

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

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

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.

Usage in Python

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

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

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?

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?

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

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

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.