ACME Service and Go API for PicoHSM
README.md

picohsm: Go Client & Tooling for Raspberry Pi Pico HSM #

picohsm is a pure-Go library and administrative CLI for interacting with the Raspberry Pi Pico HSM (RP2040 and RP2350) running the SmartCard-HSM applet.

It communicates directly with the USB device via Linux USBFS (ioctl) using standard ISO 7816-4 and USB CCID protocols, eliminating the need for pcscd, OpenSC, or external C/C++ dependencies.

Features #

  • Pure Go & Minimal Dependencies: Zero CGO, zero external Go runtime dependencies. Relies strictly on the standard library.
  • Direct USBFS CCID Transport: Direct device communication via Linux /dev/bus/usb/ with automatic device discovery (2e8a:10fd).
  • Standard crypto.Signer Integration: Seamlessly integrates with Go's crypto/x509 and crypto/tls packages to issue certificates and establish mutual TLS across both modern Elliptic Curve (ECDSA P-256/P-384) and legacy RSA (PKCS#1 v1.5 with SHA-1, SHA-256, etc.).
  • Legacy CA Migration & Offline Wrapping (wrap-key): Securely wrap existing RSA private keys offline on air-gapped laptops under DKEK without needing an attached HSM, and import them seamlessly onto target Pico HSMs.
  • Hardware Key Backup & Replication (DKEK): Full support for Device Key Encryption Key (DKEK) share generation, import, key wrapping (INS 0x72), and key unwrapping (INS 0x74) with automatic large-payload staging (0x2F10) to enable hot standby, cold disaster recovery, and multi-HSM load balancing.
  • Administrative CLI (pico-hsm-tool): Comprehensive management of PINs, dynamic hardware options, EC keypair generation, DKEK lifecycle, CSR signing (sign-csr), and certificate issuance.

Installation & Setup #

Prerequisites #

  • Go 1.22 or newer
  • Linux host or container with access to /dev/bus/usb/
  • Raspberry Pi Pico (RP2040 or RP2350) flashed with pico-hsm firmware (USB ID 2e8a:10fd)

Build from Source #

git clone https://go.iscode.ca/picohsm.git # or local checkout
cd picohsm
go build -o bin/pico-hsm-tool ./cmd/pico-hsm-tool

To install directly to $GOPATH/bin:

go install ./cmd/pico-hsm-tool

Linux USB Permissions (udev) #

By default, Linux USBFS character devices (/dev/bus/usb/XXX/YYY) require root privileges unless a udev rule is configured.

To allow non-root users in the plugdev group to access the Pico HSM, create /etc/udev/rules.d/99-pico-hsm.rules:

# Raspberry Pi Pico HSM (Pol Henarejos Pico Key)
SUBSYSTEM=="usb", ATTR{idVendor}=="2e8a", ATTR{idProduct}=="10fd", MODE="0666", GROUP="plugdev"

Reload udev rules:

sudo udevadm control --reload-rules
sudo udevadm trigger

Crostini / LXD Passthrough (ChromeOS / Containers) #

If running inside an LXD or Crostini container, pass the USB device directly to your container instance:

# On the host / termina VM:
lxc config device add <container-name> picohsm usb vendorid=2e8a productid=10fd mode=0666

Verify that the device appears inside the container:

ls -l /dev/bus/usb/*/*
# Verify vendor and product ID
lsusb -d 2e8a:10fd

Administration Guide: pico-hsm-tool #

The pico-hsm-tool utility provides complete device administration. By default, it automatically detects the Pico HSM on the USB bus. You can explicitly specify the device node using -device /dev/bus/usb/XXX/YYY.

Flags can be specified either before or after the command name.

1. Device Inspection & Status #

Display Card ATR (Answer To Reset) #

Reads the CCID card ATR:

pico-hsm-tool atr

Output:

ATR (11 bytes): 3B80800101

Select SmartCard-HSM Applet #

Selects the CardContact SmartCard-HSM applet (E82B0601040181C31F0201):

pico-hsm-tool select

Query Firmware Version & Memory #

Queries the firmware version and available heap:

pico-hsm-tool status

Output:

Firmware Version: 6.6
Heap Free: 184560 bytes (180.23 KB)

Check PIN Retry Counter #

Queries the remaining PIN attempts without consuming a retry:

pico-hsm-tool pin-retries

Output:

Remaining PIN retries: 3

2. Device Initialization #

Initialization completely resets the file system, establishes the User PIN and Security Officer PIN (SO-PIN), and sets up default key domains.

Warning

Initialization erases all existing private keys and certificates stored on the HSM.

pico-hsm-tool initialize -pin 648219 -so-pin 3537363231383830 -dkek-shares 1

To skip interactive confirmation (useful in automated provisioning scripts), pass -force:

pico-hsm-tool initialize -pin 648219 -so-pin 3537363231383830 -dkek-shares 1 -force
  • User PIN: Standard PIN (default: 648219, 6 to 15 characters).
  • SO-PIN: 16-character hexadecimal Security Officer PIN (default: 3537363231383830).
  • -dkek-shares: Number of DKEK shares required for Key Domain 0 (default: 1). Setting this to 1 or higher enables key backup and replication under DKEK.

3. DKEK Management & Key Domains #

A Device Key Encryption Key (DKEK) allows private keys to be exported and imported securely between Pico HSM devices without ever exposing plaintext key material to host memory.

Generate a Random DKEK Share #

Generate a cryptographically random 32-byte DKEK share:

pico-hsm-tool dkek generate -out /etc/picohsm/dkek.share

Output:

DKEK share (32 bytes) written to /etc/picohsm/dkek.share (KCV: 5bb4ccfcd2e8c589)

The 8-byte Key Check Value (KCV) is derived from SHA-256(share)[:8].

Query DKEK Status #

Check the status of Key Domain 0 (provide -pin to decrypt and view the active KCV):

pico-hsm-tool dkek status -pin 648219

Output:

Key Domain: 0
  Configured Shares: 1
  Remaining Shares : 1
  Status           : Incomplete (Pending 1 share(s))

Import DKEK Share #

Import the DKEK share into the key domain:

pico-hsm-tool dkek import -pin 648219 /etc/picohsm/dkek.share

Output:

DKEK share imported into key domain 0 successfully.
  Configured Shares: 1
  Remaining Shares : 0
  Status           : Operational (KCV: 5bb4ccfcd2e8c589)

The device is now ready to wrap and unwrap private keys!


4. Dynamic Hardware Options #

The Pico HSM supports hardware-specific runtime options that govern physical security:

Inspect Current Options #

pico-hsm-tool options get

Output:

Dynamic Options (raw=0x0000):
  BUTTON  (Press-to-confirm) : OFF
  COUNTER (Key usage counter): OFF
  LOCK    (Secure lock)      : OFF
  AUTH    (Combined auth)    : OFF

Require Physical BOOTSEL Button Press #

To mitigate unauthorized automated signing, you can require a physical press of the Pico's BOOTSEL button for cryptographic operations:

# Enable press-to-confirm
pico-hsm-tool options set button on -pin 648219

# Disable press-to-confirm
pico-hsm-tool options set button off -pin 648219

Enable Key Usage Counters #

To track the exact number of signatures produced by a hardware key:

pico-hsm-tool options set counter on -pin 648219

5. Key Generation #

Generate an Elliptic Curve (EC) keypair directly in hardware:

pico-hsm-tool keygen -id 1 -curve secp256r1 -pin 648219

Supported curves:

  • secp256r1 (NIST P-256)
  • secp384r1 (NIST P-384)

The generated public key is printed in PEM format (PUBLIC KEY). Because Key Domain 0 has an active DKEK, this key is automatically bound to the DKEK and can be exported.


6. Key Backup, Replication & Legacy CA Migration #

To support hot standby, multi-node load balancing, offsite disaster recovery, or legacy CA migration, private keys can be wrapped under the DKEK and imported across multiple Pico HSM devices.

Export Key Under DKEK (Wrap) #

Export an existing private key in hardware slot 1 encrypted under the DKEK:

pico-hsm-tool wrap -id 1 -pin 648219 -out /tmp/key1.wrapped

Output:

Key 1 wrapped successfully (331 bytes) -> saved to /tmp/key1.wrapped (KCV: 5bb4ccfcd2e8c589)

The wrapped key blob begins with the 8-byte KCV followed by the encrypted key payload and integrity tag.

Offline Wrapping of Legacy RSA Private Keys (wrap-key) #

For legacy root/intermediate CAs stored offline (e.g. on air-gapped laptops in safes), pico-hsm-tool can wrap existing PKCS#1 or PKCS#8 RSA private keys in pure software without requiring an attached HSM:

# Wrap on the offline laptop using the pre-shared DKEK
pico-hsm-tool wrap-key -in /path/to/legacy-ca.key \
                       -dkek /etc/picohsm/dkek.share \
                       -out /media/usb/legacy-ca.wrapped

Output:

RSA-2048 key wrapped successfully (971 bytes) -> /media/usb/legacy-ca.wrapped (KCV: 5bb4ccfcd2e8c589)

Import Wrapped Key (Unwrap) #

On any target Pico HSM initialized with the same DKEK share, import the wrapped key into any slot (e.g. slot 1 for root CA or slot 2 for intermediate):

pico-hsm-tool unwrap -id 1 -pin 648219 /media/usb/legacy-ca.wrapped

Output:

Key 1 successfully unwrapped and imported from /media/usb/legacy-ca.wrapped

Note

Large key blobs (such as 2048-bit RSA keys at ~971 bytes) exceed standard APDU buffer limits. pico-hsm-tool automatically stages the blob via elementary file 0x2F10 using chunked writes (INS 0xD7) prior to calling INS 0x74, providing seamless import for keys of any size.

Multi-HSM Load Balancing & High Availability #

By initializing multiple Pico HSM units with identical DKEK shares, the same private key can be imported into every unit. In production, multiple Pico HSMs plugged into an ACME cluster or USB hub provide:

  • Active-Active Load Balancing: Distribute certificate signing operations across multiple RP2040 cores.
  • Instant Hot-Standby: Redundancy against physical disconnection or hardware failure.
  • Zero Key Extraction Risk: The plaintext private key is never resident in host memory or on disk.

7. Signing Data #

Sign arbitrary files using the private key residing inside the HSM:

# Create a test message
echo "Hello Zero Trust" > /tmp/payload.txt

# Sign SHA-256 digest with key 1
pico-hsm-tool sign -id 1 -pin 648219 /tmp/payload.txt

Output:

Signature (len=71): 3045022100A...0220...

The output signature is formatted in standard ASN.1 DER (ECDSA r and s).


8. Issuing Certificates & Signing CSRs #

Generate Self-Signed Root CA Certificate (cert) #

Generate a self-signed X.509 Certificate Authority root certificate directly on the device using Go's standard crypto/x509 and the hardware crypto.Signer:

pico-hsm-tool cert -id 1 -pin 648219 -cn "Pico HSM Modern Root CA" > /tmp/root-ca.crt

Inspect and verify the issued certificate using OpenSSL:

openssl x509 -in /tmp/root-ca.crt -text -noout
openssl verify -CAfile /tmp/root-ca.crt /tmp/root-ca.crt

Sign PKCS#10 CSRs with Hardware CA Key (sign-csr) #

Issue an end-entity server or client certificate from a standard CSR, signed by the CA private key inside the Pico HSM:

# Sign CSR using hardware key in slot 1 and the CA certificate
pico-hsm-tool sign-csr -csr /tmp/server.csr \
                       -ca /tmp/root-ca.crt \
                       -id 1 -pin 648219 \
                       -days 90 \
                       -out /tmp/server.crt

Output:

Certificate issued successfully (SHA1-RSA) -> /tmp/server.crt

Verify the issued server certificate against the CA:

openssl verify -CAfile /tmp/root-ca.crt /tmp/server.crt

9. Device Reboot #

Perform a clean software reboot of the Pico HSM:

pico-hsm-tool reboot

Library Usage (pkg/picohsm) #

The Go library can be embedded directly into custom services, such as an internal ACME CA daemon or mutual-TLS server:

package main

import (
	"crypto"
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"crypto/x509/pkix"
	"fmt"
	"log"
	"math/big"
	"os"
	"time"

	"go.iscode.ca/picohsm/pkg/ccid"
	"go.iscode.ca/picohsm/pkg/picohsm"
)

func main() {
	// Auto-detect and open the Pico HSM USB device
	devPath, err := ccid.FindDefaultDevice()
	if err != nil {
		log.Fatalf("device discovery failed: %v", err)
	}

	dev, err := ccid.Open(devPath)
	if err != nil {
		log.Fatalf("failed to open device: %v", err)
	}
	defer dev.Close()

	client := picohsm.New(dev)

	// Select the applet and authenticate session
	if _, err := client.SelectApplet(); err != nil {
		log.Fatalf("select applet: %v", err)
	}
	if err := client.VerifyPIN("648219"); err != nil {
		log.Fatalf("verify pin: %v", err)
	}

	// 1. Load CA certificate to retrieve the CA public key
	caCertPEM, err := os.ReadFile("ca.crt")
	if err != nil {
		log.Fatalf("read ca cert: %v", err)
	}
	// (Parse certificate to obtain caCert *x509.Certificate)
	// caCert, _ := x509.ParseCertificate(derBytes)

	// 2. Wrap hardware key in a standard Go crypto.Signer (supports ECDSA & RSA)
	// Slot 1 holds the CA private key in hardware
	signer := picohsm.NewSigner(client, 1, caCert.PublicKey)

	// 3. Issue a server certificate signed by the hardware key
	template := &x509.Certificate{
		SerialNumber: big.NewInt(2001),
		Subject: pkix.Name{
			CommonName: "terminal-042.example.internal",
		},
		NotBefore:             time.Now(),
		NotAfter:              time.Now().Add(90 * 24 * time.Hour),
		KeyUsage:              x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
		ExtKeyUsage:           []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},
		BasicConstraintsValid: true,
		SignatureAlgorithm:    caCert.SignatureAlgorithm, // e.g. SHA1WithRSA or ECDSAWithSHA256
	}

	certDER, err := x509.CreateCertificate(rand.Reader, template, caCert, clientPublicKey, signer)
	if err != nil {
		log.Fatalf("create certificate: %v", err)
	}

	fmt.Printf("Successfully signed certificate (%d bytes) with hardware key\n", len(certDER))
}

Internal ACME Service (pico-acme-server) #

pico-acme-server provides an RFC 8555 compliant ACME daemon backed directly by Raspberry Pi Pico HSMs. It exposes multiple issuing authorities via Configurable Profiles, allowing both modern microservices and legacy embedded devices to automate certificate renewal through standard ACME workflows.

Profile-Based Directory Routing #

Directories are exposed using logical profile slugs:

http://<host>:<port>/acme/{profile}/directory

A default alias (/acme/directory) automatically maps to the designated default profile.

ACME Directory Path Logical Profile Backing CA & Hardware Signature Typical Consumer
/acme/legacy/directory legacy Legacy Root CA (RSA-2048, SHA1-RSA) Embedded terminals & legacy devices
/acme/infra/directory infra Modern Internal Intermediate CA (EC P-256, ECDSA-SHA256) Internal servers, Kubernetes, microservices
/acme/directory (default) Aliased to default profile (infra or legacy) General ACME clients

Configuration File (acme.json) #

{
  "listen": ":8080",
  "base_url": "https://acme.example.internal",
  "default_profile": "infra",
  "pin": "648219",
  "profiles": [
    {
      "name": "legacy",
      "hsm_slot": 4,
      "ca_cert": "/etc/picohsm/certs/legacy-ca.crt",
      "sig_alg": "SHA1WithRSA",
      "validity_days": 365,
      "allowed_domains": ["*.example.internal", "*.example.com"],
      "auto_approve": true
    },
    {
      "name": "infra",
      "hsm_slot": 1,
      "ca_cert": "/etc/picohsm/certs/internal-intermediate.crt",
      "sig_alg": "ECDSAWithSHA256",
      "validity_days": 90,
      "allowed_domains": ["*.internal"],
      "auto_approve": true
    }
  ]
}

Running the ACME Daemon #

# Build daemon
go build -o bin/pico-acme-server ./cmd/pico-acme-server

# Run with configuration file
./bin/pico-acme-server -config /etc/picohsm/acme.json

Console output:

2026/10/09 14:02:55 Connected to Pico HSM (Firmware: 6.6, Heap Free: 192480 bytes)
2026/10/09 14:02:55 Registered ACME profile "legacy" -> Slot 4, CA: Example Legacy Certification Authority, Alg: SHA1-RSA, Directory: https://acme.example.internal/acme/legacy/directory
2026/10/09 14:02:55 Registered ACME profile "infra" -> Slot 1, CA: Internal Intermediate CA, Alg: ECDSA-SHA256, Directory: https://acme.example.internal/acme/infra/directory
2026/10/09 14:02:55 Default ACME directory alias: https://acme.example.internal/acme/directory -> Profile "infra"
2026/10/09 14:02:55 Starting Pico ACME Service on :8080 (BaseURL: https://acme.example.internal)

Client Integration (Certbot, Lego, acme.sh) #

Any RFC 8555 compliant ACME client can request certificates:

# Obtain legacy certificate using Lego
lego --server https://acme.example.internal/acme/legacy/directory \
     --email admin@example.com \
     --domains terminal-042.example.internal \
     --http \
     run

# Obtain modern infrastructure certificate using Certbot
certbot certonly --server https://acme.example.internal/acme/infra/directory \
                 --standalone \
                 -d api.internal

Testing & Code Quality #

Run all unit tests:

go test -v ./...

Run linter:

golangci-lint run ./...

Format code:

go fmt ./...