202 Commits

Author SHA1 Message Date
Pol Henarejos
0ad7e3a610 Fix Secure boot enable.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2026-02-16 16:03:01 +01:00
Pol Henarejos
25889094e5 [BETA] Add support to Secure Boot in ESP32.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2026-02-07 14:32:31 +01:00
Pol Henarejos
b78c1485c1 Add support for HIGH/LOW ESP32 LED
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2026-02-04 23:45:14 +01:00
Pol Henarejos
7e651c78e3 Upgrade to v6.4
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2026-02-01 20:34:41 +01:00
Pol Henarejos
2dec7c0b4e Fix phy marker write.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2026-02-01 20:34:24 +01:00
Pol Henarejos
0b18ab5e3d Upgrade to Pico Keys SDK 8.5
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2026-01-29 16:12:41 +01:00
Pol Henarejos
868caff665 Use new VID:PID allocated to Pico HSM.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2026-01-22 12:33:42 +01:00
Pol Henarejos
ed980c3093 Use new layout
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2026-01-22 11:59:46 +01:00
Pol Henarejos
16d4d0d26e Update README with up-to-date info.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2026-01-06 21:20:13 +01:00
Pol Henarejos
380ff7afa4 Upgrade to v6.2
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2026-01-05 19:54:07 +01:00
Pol Henarejos
60dafec2e8 Upgrade Pico Keys SDK to v8.2
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2026-01-05 19:51:51 +01:00
Pol Henarejos
3207fe3451 Disable button press by default since LED may not be properly configured until it is commissioned.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2026-01-05 19:40:50 +01:00
Pol Henarejos
6914be4fea Fix build.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-29 20:36:55 +01:00
Pol Henarejos
7d551f6fea Blink led three times to acknowledge proper commissioning.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-29 20:17:03 +01:00
Pol Henarejos
d3a7ff425a Fix pimoroni led
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-27 22:03:47 +01:00
Pol Henarejos
97e7303505 Move pointer
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-26 20:00:59 +01:00
Pol Henarejos
e41f2ba712 Releaser is available up to 6.7.0
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-26 19:54:15 +01:00
Pol Henarejos
710eb70af7 Update reamde & usage.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-13 23:36:43 +01:00
Pol Henarejos
9dbd764c8c Reset by recopying memory file.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-13 21:12:45 +01:00
Pol Henarejos
feec958d10 Not used
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-11 20:05:08 +01:00
Pol Henarejos
9720bcfd4b Fix build
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-11 19:59:39 +01:00
Pol Henarejos
4bb81f5b25 Build only necessary boards.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-11 19:56:01 +01:00
Pol Henarejos
c9926a71d1 Do not call pytest
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-11 19:48:23 +01:00
Pol Henarejos
10c25b6a3a Update pointer.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-11 19:36:06 +01:00
Pol Henarejos
629f14ab0d Revert "Move EDDSA to another branch."
This reverts commit a0faf5308e.
2025-12-11 19:35:27 +01:00
Pol Henarejos
4d6f6e4635 Revert "Move Secure Boot to another branch."
This reverts commit 8978456524.
2025-12-11 19:35:20 +01:00
Pol Henarejos
8e35104695 Update memory.flash for tests
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-10 00:20:28 +01:00
Pol Henarejos
82f4b2201c Remove printf
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-09 21:38:15 +01:00
Pol Henarejos
8978456524 Move Secure Boot to another branch.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-09 21:37:52 +01:00
Pol Henarejos
a0faf5308e Move EDDSA to another branch.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-09 15:49:20 +01:00
Pol Henarejos
f4df9766b6 Fix MSOS/BOS descriptor.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-03 16:34:24 +01:00
Pol Henarejos
a1d64d2523 Set anti-rollback version only when the binary is signed.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-02 09:55:49 +01:00
Pol Henarejos
82c6badc48 Increase anti-rollback version to 2.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-01 23:42:16 +01:00
Pol Henarejos
2243629d58 Add anti-rollback argument.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-01 23:42:01 +01:00
Pol Henarejos
b5b5ccd53c Upgrade to v6.0
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-01 17:21:26 +01:00
Pol Henarejos
0df97c881f Update mbedtls only when necessary.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-01 17:20:36 +01:00
Pol Henarejos
3c0706f7b2 Fix on AID selection. It should support shorter AID if matches.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-12-01 01:45:43 +01:00
Pol Henarejos
0d1d77b3f6 Upgrade Pico Keys SDK to v8.0
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-11-30 18:30:57 +01:00
Pol Henarejos
25301f14e1 Upgrade to mbedtls v3.6.5
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-11-30 18:28:24 +01:00
Pol Henarejos
256e61d813 Update tests to new CA2/DV2
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-11-28 12:14:36 +01:00
Pol Henarejos
1fe771f074 Fix tests
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-11-28 01:13:27 +01:00
Pol Henarejos
0588dde490 Do not use editable mode.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-11-28 00:53:29 +01:00
Pol Henarejos
1d6cc6ff89 Do not install apt pyscard
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-11-28 00:21:42 +01:00
Pol Henarejos
8fde25eff2 Fix build, key generation for RP2040 and added reboot bootsel command.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-11-28 00:13:10 +01:00
Pol Henarejos
634eac50b1 Moved to pypicohsm.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-11-18 01:05:49 +01:00
Pol Henarejos
c4a1cf32e5 Add Pico Version Major
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-11-18 01:05:40 +01:00
Pol Henarejos
966b12ffad Merge pull request #108 from MageDelfador/esp32pr
ESP32 Optimization
2025-11-10 00:04:25 +01:00
Pol Henarejos
de33124d6b Fix test case with newer openssl.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-11-09 21:38:52 +01:00
Pol Henarejos
ae61150f5c Upgrade Dockerfile for fixing.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-11-09 20:00:23 +01:00
Pol Henarejos
605819f0a3 Fix build.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-11-09 19:56:18 +01:00
Pol Henarejos
c9dc70b095 Add template for pull requests.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-10-27 08:58:12 +01:00
Pol Henarejos
7060e4df7c Add CONTRIBUTING
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-10-27 08:53:48 +01:00
Pol Henarejos
28c99a21bd Update license models and add ENTERPRISE.md
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-10-26 20:46:01 +01:00
Pol Henarejos
dba614ed36 Relicense project under the GNU Affero General Public License v3 (AGPLv3)
and add the Enterprise / Commercial licensing option.

Main changes:
- Replace GPLv3 headers with AGPLv3 headers in source files.
- Update LICENSE file to the full AGPLv3 text.
- Add ENTERPRISE.md describing the dual-licensing model:
  * Community Edition: AGPLv3 (strong copyleft, including network use).
  * Enterprise / Commercial Edition: proprietary license for production /
    multi-user / OEM use without the obligation to disclose derivative code.
- Update README with a new "License and Commercial Use" section pointing to
  ENTERPRISE.md and clarifying how companies can obtain a commercial license.

Why this change:
- AGPLv3 ensures that modified versions offered as a service or deployed
  in production environments must provide corresponding source code.
- The Enterprise / Commercial edition provides organizations with an
  alternative proprietary license that allows internal, large-scale, or OEM
  use (bulk provisioning, policy enforcement, inventory / revocation,
  custom attestation, signed builds) without AGPL disclosure obligations.

This commit formally marks the first release that is dual-licensed:
AGPLv3 for the Community Edition and a proprietary commercial license
for Enterprise customers.

Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-10-26 20:18:45 +01:00
MageDelfador
2471c747d6 Update sdkconfig.defaults 2025-10-15 23:52:34 +08:00
Pol Henarejos
c7006b6319 Merge pull request #102 from eliasnaur/push-upprymyooxrs
implement bip32 operations in pico-hsm-tool
2025-08-12 12:29:23 +02:00
Pol Henarejos
5f5e010a19 Stick with Espressif v5.5
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-08-12 00:51:24 +02:00
Elias Naur
ad5a503d36 implement bip32 operations in pico-hsm-tool 2025-08-08 16:32:01 +02:00
Pol Henarejos
5e4f2286e6 Add autobuild for RP2350.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-07-05 00:52:06 +02:00
Pol Henarejos
f0f8e4382a Fix cross build.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-06-22 20:33:06 +02:00
Pol Henarejos
a0f6abf6a6 Remove the tweak for packets multiple of 64 bytes. It was fixed in the USB stack handling (don't remember where).
Fixes #95.

Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-05-23 20:18:29 +02:00
Pol Henarejos
cbf9bb9281 Update scs3.md 2025-05-19 09:16:43 +02:00
Pol Henarejos
bd0796b217 Update scs3.md 2025-05-18 19:34:48 +02:00
Pol Henarejos
defa18a5ec Add ESPICOHSMCA00002 to scs3 docs.
Fixes #87.

Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-05-18 19:06:23 +02:00
Pol Henarejos
bf06081b9c Fix interface descriptor when HID is disabled.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-05-02 18:28:43 +02:00
Pol Henarejos
f1a8d8bc91 Use pyscard 2.2.1 since 2.2.2 has a bug
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-04-24 19:11:32 +02:00
Pol Henarejos
d6f15f8384 Fix eddsa output folder.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-04-10 19:56:20 +02:00
Pol Henarejos
dce4e304bc Upgrade to v5.6
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-04-10 18:41:31 +02:00
Pol Henarejos
f97aaadd17 Update build script to automatize EdDSA builds.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-04-10 18:41:00 +02:00
Pol Henarejos
611b762a1f Use K1 curve in emulation mode.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-04-07 01:29:02 +02:00
Pol Henarejos
7c1ef56799 Fix ne parameter when secure message protocol is used.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-04-07 01:27:57 +02:00
Pol Henarejos
4b59bd6481 0x85 and 0x86 should return not found to avoid authentication path.
Fixes #81 and #84.

Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-04-07 01:27:21 +02:00
Pol Henarejos
9b1dceb8da Use K1 curve for general authentication.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-04-07 01:24:22 +02:00
Pol Henarejos
c4bc346d98 Sign release builds.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-04-06 18:37:36 +02:00
Pol Henarejos
3e1b29f72a Add support for slot selection.
Fixes #83.

Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-03-23 20:03:46 +01:00
Pol Henarejos
bb27c2324b Only pin to core in ESP32-S3 since it is multicore.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-03-07 19:35:25 +01:00
Pol Henarejos
8c0a7c6681 Fix commissioned values for LED.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-02-23 00:53:50 +01:00
Pol Henarejos
2db265c9c8 Merge branch 'development' 2025-02-21 20:35:19 +01:00
Pol Henarejos
c58823f9ef Build tests for EDDSA.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-02-21 20:22:07 +01:00
Pol Henarejos
21b6a7782a Add EdDSA support as a conditional build.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-02-21 20:20:43 +01:00
Pol Henarejos
26f9e0dd54 Fix cyw43 build.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-02-21 18:02:42 +01:00
Pol Henarejos
4053b22f2e Fix cyw43 build.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-02-21 17:32:42 +01:00
Pol Henarejos
ef71ec6a29 Upgrade to v5.4
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-02-20 18:10:49 +01:00
Pol Henarejos
72f2e0a58b Upgrade to v5.4
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-02-20 18:09:50 +01:00
Pol Henarejos
17ca65a41b Upgrade to v5.4
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-02-19 20:21:57 +01:00
Pol Henarejos
92fe26c1e1 Upgrade to v6.4
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-02-19 19:18:02 +01:00
Pol Henarejos
5c2dce9e52 Take led_driver on build.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-02-19 19:14:07 +01:00
Pol Henarejos
1cbcfce23f Use all available boards.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-02-19 19:13:36 +01:00
Pol Henarejos
1f3cecea8b Use fastest clk for rp2040.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-02-19 19:13:18 +01:00
Pol Henarejos
ac8d05b9e9 Add support for esp32s2 autobuild.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-02-19 12:14:47 +01:00
Pol Henarejos
e00e620264 Upgrade to Pico SDK 2.1.1 autobuild.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-02-19 12:13:58 +01:00
Pol Henarejos
64d8dafa2b Fix multiple interfaces in older PCSC versions.
Fixes #74 again.

Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-02-12 13:25:43 +01:00
Pol Henarejos
0f3bb8242c Fix multiple interfaces in older PCSC versions.
Fixes #74 again.

Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-02-12 13:25:07 +01:00
Pol Henarejos
747e5fbe86 Added phy_save() and phy_load() to save and load PHY.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-01-29 17:09:29 +01:00
Pol Henarejos
8eb4669c0f Fixes #74.
LibCCID allows propietary class for CCID (ALLOW_PROPIETARY_CLASS in LibCCID). Then both interfaces are loaded but since both belong to same device, only the last is opened.

We change maxSlot value even it breaks the ICCD spec to cause a timeout in LibCCID and deactivate WebCCID interface.

Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-01-17 20:56:11 +01:00
Pol Henarejos
4c636e0ce5 Upgrade to v5.2
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-01-15 13:07:35 +01:00
Pol Henarejos
297f2e6228 Upgrade to v5.2
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-01-15 12:06:00 +01:00
Pol Henarejos
12a26f8506 Merge branch 'development' 2025-01-15 12:04:47 +01:00
Pol Henarejos
45a96f8742 Add rollback version to 1.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-01-15 12:04:20 +01:00
Pol Henarejos
ca2e04af53 Update initial memory for tests and KDM
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-01-08 14:47:23 +01:00
Pol Henarejos
f0a9d03ca8 Fix storing MKEK in devices with OTP_1 available.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-01-08 14:38:02 +01:00
Pol Henarejos
2502f99aff Add OTP for emulation.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2025-01-08 13:26:08 +01:00
Pol Henarejos
71636f4d66 Use partition bounds if available.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-30 21:42:33 +01:00
Pol Henarejos
310bcb8092 Fix bin name.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-27 02:22:20 +01:00
Pol Henarejos
6c5735fc4b Fix bin name.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-27 02:21:58 +01:00
Pol Henarejos
3430655897 Fix merge file.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-27 02:09:16 +01:00
Pol Henarejos
3d9e806409 Fix merge file.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-27 02:09:05 +01:00
Pol Henarejos
ff8b343df4 Auto generate an esp32-s3 firmware bin file.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-27 02:08:30 +01:00
Pol Henarejos
0c6b0d295f Auto generate an esp32-s3 firmware bin file.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-27 02:03:08 +01:00
Pol Henarejos
c6b03e54ca Fix TX/RX buffers to align them with USB buffers and avoid overflows.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-24 02:06:15 +01:00
Pol Henarejos
991f5fc960 More uint funcs.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-23 21:41:40 +01:00
Pol Henarejos
6d516b1b78 Use BE/LE functions for packing uint16.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-23 21:01:12 +01:00
Pol Henarejos
2a3ac550ec Pack file struct.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-23 20:40:11 +01:00
Pol Henarejos
73232b6de4 Add LE/BE functions for uint16, 32 and 64.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-23 20:39:03 +01:00
Pol Henarejos
d56b540324 Add support for displaying memory usage.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-23 20:24:10 +01:00
Pol Henarejos
74b635fa3c Increase TinyUSB task stack size.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-23 20:12:15 +01:00
Pol Henarejos
07d9e225d2 Use PHY value for LED GPIO number. Fixes #71.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-16 13:12:11 +01:00
Pol Henarejos
3d960b931a Fix MKEK masking order. Fixes #69.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-08 01:26:47 +01:00
Pol Henarejos
ff7ef56cda Dev options file must be persistent, since it manipulates MKEK which is in turn persistent.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-08 01:25:19 +01:00
Pol Henarejos
320455815f Only allow initialize if secure lock is disabled or has mkek mask.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-08 01:24:35 +01:00
Pol Henarejos
859dec7e4a Accept mkek mask only if secure lock is enabled.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-08 01:23:51 +01:00
Pol Henarejos
053ccf4a89 Fix esp32 build.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-03 08:47:44 +01:00
Pol Henarejos
f88aad1e2c Fixed buffer overflow when unlocking the device.
Fixes #68.

Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-12-03 08:36:05 +01:00
Pol Henarejos
866aac8fe3 Add reboot extra command.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-27 21:48:04 +01:00
Pol Henarejos
a242a28394 Fix disable secure aut.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-27 16:11:18 +01:00
Pol Henarejos
c33ed9b968 Fix autobuild for Pico SDK 2.1.0
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-25 23:59:54 +01:00
Pol Henarejos
65a4474dec Fix build for RP2350.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-25 23:46:12 +01:00
Pol Henarejos
e243def565 Add UP button timeout for PHY.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-25 15:24:27 +01:00
Pol Henarejos
78bc34827e Autobuild for Pico SDK 2.0.0
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-25 13:13:31 +01:00
Pol Henarejos
a69cb8a95a Add CCID SET_CLOCK_AND_FREQUENCY command for latest IFD.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-25 12:55:28 +01:00
Pol Henarejos
bb45c9b3a8 Merge branch 'master' into development-eddsa 2024-11-12 20:10:07 +01:00
Pol Henarejos
1ea0a91ba8 Fix initialization when initializing a RP2350 board for first time.
Fixes #60.

Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-12 19:25:22 +01:00
Pol Henarejos
6f572954d5 If the board is RP2350 or ESP32, the requested certificate must be for secp256k1 key.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-12 19:24:10 +01:00
Pol Henarejos
99a9803328 Update README.md
Fix headings
2024-11-10 19:00:29 +01:00
Pol Henarejos
5535f3ec10 No esp32 in eddsa workflows.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-09 18:47:41 +01:00
Pol Henarejos
f992a04142 Fix eddsa signature.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-09 18:45:05 +01:00
Pol Henarejos
d858a1e1d5 Upgrade to v5.0
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-09 18:10:56 +01:00
Pol Henarejos
b7c6ca58d0 Upgrade to v5.0
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-09 15:47:40 +01:00
Pol Henarejos
2f3d70fcac Upgrade mbedtls v3.6.2
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-09 15:16:32 +01:00
Pol Henarejos
91c641033a Merge branch 'development' 2024-11-09 15:00:26 +01:00
Pol Henarejos
f3bf3cd8f4 Do not use pico patcher script anymore.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-09 14:58:42 +01:00
Pol Henarejos
e4736cc448 Upgrade Pico Keys SDK to v7.0
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-09 14:58:06 +01:00
Pol Henarejos
bfa8891c8d Update README.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-09 14:54:51 +01:00
Pol Henarejos
618fdb4c1a Do not request dev cert when performing tests.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-09 00:50:51 +01:00
Pol Henarejos
9457433844 Add compile flags for optimization build in ESP32.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-09 00:20:31 +01:00
Pol Henarejos
c239b4dd7c Fix secure otp build for non rp2350.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-08 19:46:00 +01:00
Pol Henarejos
96359ebe03 Add secure boot and secure lock commands via rescue.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-08 19:36:54 +01:00
Pol Henarejos
f301b2a1b1 Add --no-dev-cert to do not request a certificate and use a self-signed one. Do not use if attestation is needed.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-08 19:13:14 +01:00
Pol Henarejos
4ec1d4d891 Fix initialization and terminal certificate generation.
Fixes #59.

Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-08 17:52:13 +01:00
Pol Henarejos
f1410bbf04 Only request and upload the device certificate if needed.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-08 17:45:48 +01:00
Pol Henarejos
9b9ea7cae5 Add product and mcu to info in rescue mode.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-07 20:00:41 +01:00
Pol Henarejos
f5b89aed69 Use DEV key from OTP if available when initializing.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-07 00:16:22 +01:00
Pol Henarejos
f74a374c64 Fix version header.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-05 19:33:07 +01:00
Pol Henarejos
3c6684cdab Rename CCID_ codes to PICOKEY_
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-11-05 19:29:00 +01:00
Pol Henarejos
20ef94c301 Upgrade Pico HSM Tool to v2.0
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-28 00:28:49 +01:00
Pol Henarejos
68360978d6 Use BOOTKEY instead of reading json.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-28 00:25:22 +01:00
Pol Henarejos
1933498a33 Add optional bootkey index param for secure_boot.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-28 00:24:17 +01:00
Pol Henarejos
0ce89ae968 Add support for lock chip on secure_boot.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-28 00:19:55 +01:00
Pol Henarejos
9fa3758dad Add support for OTP raw read/write.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-28 00:15:48 +01:00
Pol Henarejos
d1ee43baab Add secure_boot enable.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-27 02:37:16 +02:00
Pol Henarejos
2856ec6917 Align data in case it's not.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-27 02:14:51 +02:00
Pol Henarejos
ccec83dfb1 Fix otp write length check.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-27 01:41:12 +02:00
Pol Henarejos
9de1b4ca5d Fix OTP data check size.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-27 01:24:49 +02:00
Pol Henarejos
cbd9a5d296 Add sanitize check.
Only pages 0 and 1 are allowed for reading.

Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-27 01:24:36 +02:00
Pol Henarejos
eaf3d051e3 Fix sc-hsm test.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-15 23:16:02 +02:00
Pol Henarejos
8e3801e9a2 Revert "Update flash memory for tests."
This reverts commit 5388c11182.
2024-10-15 23:00:35 +02:00
Pol Henarejos
5388c11182 Update flash memory for tests.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-15 22:54:18 +02:00
Pol Henarejos
2b77519a3b Add OTP command to Pico HSM Tool.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-15 22:12:34 +02:00
Pol Henarejos
812a737ff5 Fix length.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-13 20:52:29 +02:00
Pol Henarejos
6163b870ed Fix haders.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-13 20:51:18 +02:00
Pol Henarejos
08d4dc58aa Add OTP extra command to read/write OTP without bootmode.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-13 20:25:59 +02:00
Pol Henarejos
0193e55f7b Use macros in extras.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-13 20:06:58 +02:00
Pol Henarejos
9dc3ea3232 Fix emulation alignment.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-01 14:38:56 +02:00
Pol Henarejos
48d92f53a0 Update Dockerfile with latest versions.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-10-01 14:38:44 +02:00
Pol Henarejos
3b083f9bd7 Fix nightly build for master branch
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-30 09:27:22 +02:00
Pol Henarejos
9cd7bc7b3e Fix nightly build for master branch
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-30 09:26:59 +02:00
Pol Henarejos
4bea47faca Add nightly builds workflow
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-30 09:25:06 +02:00
Pol Henarejos
954eb1d890 Add nightly builds workflow
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-30 09:22:23 +02:00
Pol Henarejos
f7451f56ed Add support for led dimming and max. brightness.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-30 09:21:39 +02:00
Pol Henarejos
1a8c8440cf Add support for LED management
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-30 09:08:15 +02:00
Pol Henarejos
9f1e5d0abd Update pico_sdk_import
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-24 00:44:38 +02:00
Pol Henarejos
4b314470b4 Fix header in Linux.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-20 07:19:47 +02:00
Pol Henarejos
d0461f81f4 Upgrade codeaction to v3
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-20 07:19:15 +02:00
Pol Henarejos
4454c633e4 Autobuild esp32
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-20 07:16:55 +02:00
Pol Henarejos
15664da61d Added ESP32 OTP support.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-16 00:54:47 +02:00
Pol Henarejos
1a2bff33a8 Added ESP32 OTP support.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-16 00:51:21 +02:00
Pol Henarejos
cf44794bb6 Fix build.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-13 08:47:41 +02:00
Pol Henarejos
33a6a70457 Use sha256 hardware if available.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-13 00:27:16 +02:00
Pol Henarejos
c3ddfe9689 Use OTP
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-11 23:16:51 +02:00
Pol Henarejos
72eb5a2a69 Enable OTP to store a permanent secret key.
It can be used by HSM or Fido to protect the keys and use it as MKEK.
2024-09-11 23:16:23 +02:00
Pol Henarejos
95f3a464b1 Use internal TRNG of Pico.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-06 15:16:34 +02:00
Pol Henarejos
bb37a3ddb8 Fix artifacts version
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-05 15:21:51 +02:00
Pol Henarejos
6da49336c9 Use v4 for artifacts
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-05 09:16:20 +02:00
Pol Henarejos
fc69f5e1b1 Upgrade upload-artifact
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-05 07:46:25 +02:00
Pol Henarejos
3602577b6e Merge branch 'master' into development 2024-09-05 07:45:51 +02:00
Pol Henarejos
c6a72e4ffb Fix indent
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-05 07:44:17 +02:00
Pol Henarejos
c889cef488 Merge pull request #52 from polhenarejos/dependabot/github_actions/dot-github/workflows/actions/download-artifact-4.1.7
Bump actions/download-artifact from 3 to 4.1.7 in /.github/workflows
2024-09-04 01:34:34 +02:00
Pol Henarejos
d78e925d49 Parse and set binary version
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-04 01:30:38 +02:00
dependabot[bot]
bb8fcbcd3f Bump actions/download-artifact from 3 to 4.1.7 in /.github/workflows
Bumps [actions/download-artifact](https://github.com/actions/download-artifact) from 3 to 4.1.7.
- [Release notes](https://github.com/actions/download-artifact/releases)
- [Commits](https://github.com/actions/download-artifact/compare/v3...v4.1.7)

---
updated-dependencies:
- dependency-name: actions/download-artifact
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-09-03 23:24:23 +00:00
Pol Henarejos
c433e131eb Use new led color module.
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-03 18:08:03 +02:00
Pol Henarejos
11d52495d7 Upgrade to MbedTLS 3.6.1
Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-03 12:12:40 +02:00
Pol Henarejos
f450279370 Add support for Edwards curves generation.
Fixes #51

Signed-off-by: Pol Henarejos <pol.henarejos@cttc.es>
2024-09-03 11:50:46 +02:00
84 changed files with 1528 additions and 1150 deletions

50
.github/PULL_REQUEST_TEMPLATE.md vendored Normal file
View File

@@ -0,0 +1,50 @@
## Summary
Describe in plain language what this PR does and why.
- What problem does it solve?
- Is it a bug fix, a new feature, a cleanup/refactor…?
## Details / Impact
Please include any relevant details:
- Hardware / board(s) tested:
- Firmware / commit/base version:
- Security impact (if any):
- e.g. changes PIN handling, touches key storage, affects attestation, etc.
- Behavior changes:
- e.g. new command, new API surface, different defaults, etc.
## Testing
How did you test this change?
- Steps to reproduce / validate:
- Expected vs actual results:
- Any logs / traces (please remove secrets):
## Licensing confirmation (required)
By checking the box below, you confirm ALL of the following:
- You are the author of this contribution, or you have the right to contribute it.
- You have read `CONTRIBUTING.md`.
- You agree that this contribution may be merged, used, modified, and redistributed:
- under the AGPLv3 Community Edition, **and**
- under any proprietary / commercial / Enterprise editions of this project,
now or in the future.
- You understand that submitting this PR does not create any support obligation,
SLA, or guarantee of merge.
**I confirm the above licensing terms:**
- [ ] Yes, I agree
## Anything else?
Optional: mention known limitations, follow-ups, or if this is related to an existing Issue.

View File

@@ -44,7 +44,7 @@ jobs:
# Initializes the CodeQL tools for scanning.
- name: Initialize CodeQL
uses: github/codeql-action/init@v2
uses: github/codeql-action/init@v3
with:
languages: ${{ matrix.language }}
# If you wish to specify custom queries, you can do so here or in a config file.
@@ -71,4 +71,4 @@ jobs:
./workflows/autobuild.sh ${{ matrix.mode }}
- name: Perform CodeQL Analysis
uses: github/codeql-action/analyze@v2
uses: github/codeql-action/analyze@v3

42
.github/workflows/nightly.yml vendored Normal file
View File

@@ -0,0 +1,42 @@
name: "Nightly deploy"
on:
schedule:
- cron: '0 2 * * *'
workflow_dispatch:
jobs:
nightly:
name: Deploy nightly
strategy:
fail-fast: false
matrix:
refs: [master, development]
runs-on: ubuntu-latest
steps:
- name: Checkout repository
uses: actions/checkout@v4
with:
ref: ${{ matrix.refs }}
submodules: 'recursive'
- name: Restore private key
run: |
echo "${{ secrets.PRIVATE_KEY_B64 }}" | base64 -d > private.pem
chmod 600 private.pem
- name : Build
env:
PICO_SDK_PATH: ../pico-sdk
SECURE_BOOT_PKEY: ../private.pem
run: |
./workflows/autobuild.sh pico
./build_pico_hsm.sh --no-eddsa
./workflows/autobuild.sh esp32
- name: Delete private key
run: rm private.pem
- name: Update nightly release
uses: pyTooling/Actions/releaser@v6.7.0
with:
tag: nightly-${{ matrix.refs }}
rm: true
token: ${{ secrets.GITHUB_TOKEN }}
files: release/*.*

View File

@@ -36,7 +36,7 @@ jobs:
mkdir -p artifacts
docker save pico-hsm-test:bullseye -o artifacts/docker-image.tar
- name: Temporarily save image
uses: actions/upload-artifact@v3
uses: actions/upload-artifact@v4
with:
name: docker-artifact
path: artifacts
@@ -54,7 +54,7 @@ jobs:
with:
submodules: recursive
- name: Retrieve saved image
uses: actions/download-artifact@v3
uses: actions/download-artifact@v4
with:
name: docker-artifact
path: artifacts

View File

@@ -1,131 +1,134 @@
#
# This file is part of the Pico HSM distribution (https://github.com/polhenarejos/pico-hsm).
# Copyright (c) 2022 Pol Henarejos.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#
# This file is part of the Pico HSM distribution (https://github.com/polhenarejos/pico-hsm).
# Copyright (c) 2022 Pol Henarejos.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
cmake_minimum_required(VERSION 3.13)
set(USB_VID 0x2E8A)
set(USB_PID 0x10FD)
if(ESP_PLATFORM)
set(EXTRA_COMPONENT_DIRS src pico-keys-sdk/src)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
set(EXTRA_COMPONENT_DIRS pico-keys-sdk/config/esp32/components src/hsm)
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
else()
if(ENABLE_EMULATION)
else()
include(pico_sdk_import.cmake)
if(NOT ENABLE_EMULATION)
set(PICO_USE_FASTEST_SUPPORTED_CLOCK 1)
include(pico_sdk_import.cmake)
endif()
project(pico_hsm C CXX ASM)
set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 17)
if(NOT DEFINED __FOR_CI)
set(__FOR_CI 0)
endif()
if(__FOR_CI)
add_definitions(-D__FOR_CI)
endif()
add_executable(pico_hsm)
endif()
project(pico_hsm C CXX ASM)
set(CMAKE_C_STANDARD 11)
set(CMAKE_CXX_STANDARD 17)
if(NOT ENABLE_EMULATION)
pico_sdk_init()
endif()
if (NOT DEFINED __FOR_CI)
set(__FOR_CI 0)
endif()
if (__FOR_CI)
add_definitions(-D__FOR_CI)
endif()
add_executable(pico_hsm)
endif()
set(SOURCES ${SOURCES}
${CMAKE_CURRENT_LIST_DIR}/src/hsm/sc_hsm.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_select.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_list_keys.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_read_binary.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_verify.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_reset_retry.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_challenge.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_external_authenticate.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_mse.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_initialize.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_key_domain.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_key_wrap.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_keypair_gen.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_update_ef.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_delete_file.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_change_pin.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_key_gen.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_signature.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_key_unwrap.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_decrypt_asym.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_cipher_sym.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_derive_asym.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_extras.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_general_authenticate.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_session_pin.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_puk_auth.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_pso.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_bip_slip.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cvc.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/files.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/kek.c
)
set(USB_ITF_CCID 1)
set(USB_ITF_WCID 1)
include(pico-keys-sdk/pico_keys_sdk_import.cmake)
if(NOT ESP_PLATFORM)
set(SOURCES ${PICO_KEYS_SOURCES})
endif()
set(SOURCES ${SOURCES}
${CMAKE_CURRENT_LIST_DIR}/src/hsm/sc_hsm.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_select.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_list_keys.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_read_binary.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_verify.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_reset_retry.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_challenge.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_external_authenticate.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_mse.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_initialize.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_key_domain.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_key_wrap.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_keypair_gen.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_update_ef.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_delete_file.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_change_pin.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_key_gen.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_signature.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_key_unwrap.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_decrypt_asym.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_cipher_sym.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_derive_asym.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_extras.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_general_authenticate.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_session_pin.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_puk_auth.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_pso.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_bip_slip.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cvc.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/files.c
${CMAKE_CURRENT_LIST_DIR}/src/hsm/kek.c
)
SET_VERSION(ver_major ver_minor "${CMAKE_CURRENT_LIST_DIR}/src/hsm/version.h" 3)
if(ESP_PLATFORM)
project(pico_hsm)
endif()
set(INCLUDES ${INCLUDES}
${CMAKE_CURRENT_LIST_DIR}/src/hsm
)
if(NOT ESP_PLATFORM)
target_sources(pico_hsm PUBLIC ${SOURCES})
target_include_directories(pico_hsm PUBLIC ${INCLUDES})
target_compile_options(pico_hsm PUBLIC
-Wall
${CMAKE_CURRENT_LIST_DIR}/src/hsm
)
if (NOT MSVC)
if(NOT ESP_PLATFORM)
target_sources(pico_hsm PUBLIC ${SOURCES})
target_include_directories(pico_hsm PUBLIC ${INCLUDES})
target_compile_options(pico_hsm PUBLIC
-Werror
-Wall
)
endif()
if(ENABLE_EMULATION)
if (NOT MSVC)
target_compile_options(pico_hsm PUBLIC
-fdata-sections
-ffunction-sections
)
endif()
if(APPLE)
target_link_options(pico_hsm PUBLIC
-Wl,-dead_strip
)
elseif(MSVC)
if(NOT MSVC)
target_compile_options(pico_hsm PUBLIC
-WX
-Werror
)
endif()
target_link_libraries(pico_hsm PUBLIC wsock32 ws2_32 Bcrypt)
else()
target_link_options(pico_hsm PUBLIC
-Wl,--gc-sections
if(ENABLE_EMULATION)
if(NOT MSVC)
target_compile_options(pico_hsm PUBLIC
-fdata-sections
-ffunction-sections
)
endif()
if(APPLE)
target_link_options(pico_hsm PUBLIC
-Wl,-dead_strip
)
elseif(MSVC)
target_compile_options(pico_hsm PUBLIC
-WX
)
endif (APPLE)
target_link_libraries(pico_hsm PRIVATE pthread m)
else()
target_link_libraries(pico_hsm PRIVATE pico_keys_sdk pico_stdlib pico_multicore hardware_flash hardware_sync hardware_adc pico_unique_id pico_aon_timer tinyusb_device tinyusb_board)
endif()
target_link_libraries(pico_hsm PUBLIC wsock32 ws2_32 Bcrypt)
else()
target_link_options(pico_hsm PUBLIC
-Wl,--gc-sections
)
endif(APPLE)
target_link_libraries(pico_hsm PRIVATE pico_keys_sdk pthread m mbedtls)
else()
pico_add_extra_outputs(${CMAKE_PROJECT_NAME})
endif()
endif()

105
CONTRIBUTING.md Normal file
View File

@@ -0,0 +1,105 @@
# Contributing
Thank you for your interest in contributing to this project.
This repository is published in two forms:
- a Community Edition released under AGPLv3, and
- a proprietary / commercial / Enterprise Edition offered to organizations.
To keep that model legally clean, we need to be explicit about how contributions can be used.
By opening a pull request, you agree to all of the following:
1. **You have the right to contribute this code.**
You are either the original author of the contribution, or you have obtained the necessary rights/permissions to contribute it under these terms.
2. **Dual licensing permission.**
You agree that your contribution may be:
- merged into this repository, and
- used, copied, modified, sublicensed, and redistributed
- under the AGPLv3 Community Edition, and
- under any proprietary / commercial / Enterprise editions of this project,
now or in the future.
In other words: you are granting the project maintainer(s) the right to include
your contribution in both the open-source (AGPLv3) codebase and in closed-source /
commercially licensed builds, without any additional approval or payment.
3. **Attribution.**
The maintainers may keep or add attribution lines such as
`Copyright (c) <your name>` or an AUTHORS / CONTRIBUTORS list.
The maintainers may also make changes for clarity, style, security, refactoring,
or integration reasons.
4. **No automatic SLA.**
Submitting a pull request does *not* create any support obligation,
service-level agreement, warranty, or guarantee that the contribution
will be reviewed, merged, or maintained.
5. **Potential rejection for business reasons.**
Features that fall under "Enterprise / Commercial" functionality
(e.g. multi-tenant provisioning at scale, centralized audit trails,
corporate policy enforcement, attestation/branding flows, key escrow / dual-control,
etc.) may be declined for the public AGPLv3 tree even if technically valid.
That is normal: some functionality is intentionally offered only
under commercial terms.
If you are not comfortable with these terms, **do not open a pull request yet.**
Instead, please open an Issue to start a discussion.
## How to contribute (technical side)
### 1. Bug reports / issues
- Please include:
- hardware / board revision
- firmware / commit hash
- exact steps to reproduce
- expected vs actual behavior
- logs / traces if available (strip secrets)
Security-sensitive findings: do **not** post publicly.
Send a short report by email instead so it can be triaged responsibly.
### 2. Small fixes / minor improvements
- You can open a PR directly for:
- bug fixes
- portability fixes / new board definitions
- clarifications in code comments
- build / tooling cleanup
- documentation of existing behavior
Please keep PRs focused (one logical change per PR if possible).
### 3. Larger features / behavior changes
- Please open an Issue first and describe:
- what problem you're solving (not just "add feature X")
- impact on existing flows / security model
- any new dependencies
This helps avoid doing a bunch of work on something that won't be accepted
in the Community Edition.
### 4. Coding style / security posture
- Aim for clarity and small, auditable changes. This code runs in places
where secrets live.
- No debug backdoors, no "just for testing" shortcuts left enabled.
- Keep external dependencies minimal and license-compatible
(MIT / Apache 2.0 / similarly permissive is usually fine).
### 5. Commit / PR format
- Use descriptive commit messages ("Fix PIN retry counter wrap" is better than "fix stuff").
- In the PR description, please include a short summary of what was changed and why.
- At the bottom of the PR description, **copy/paste and confirm the licensing line below**:
> I confirm that I have read `CONTRIBUTING.md` and I agree that this contribution may be used under both the AGPLv3 Community Edition and any proprietary / commercial / Enterprise editions of this project, now or in the future.
A PR without that confirmation may be delayed or closed without merge.
## Thank you
This project exists because people build on it, break it, fix it,
and push it into places it wasn't originally designed to go.
Whether you are here for research, hacking on hardware,
rolling out secure keys for a team, or building a commercial product:
thank you for helping improve it.

View File

@@ -18,7 +18,7 @@ WORKDIR /home/builduser
VOLUME /home/builduser/release
ARG VERSION_PICO_SDK 1.4.0
ARG VERSION_PICO_SDK 2.0.0
RUN mkdir -p /home/builduser/Devel/pico
RUN cd /home/builduser/Devel/pico \
@@ -29,8 +29,8 @@ RUN cd /home/builduser/Devel/pico \
RUN pip install cryptography
ARG VERSION_MAJOR 2
ARG VERSION_MINOR 6
ARG VERSION_MAJOR 4
ARG VERSION_MINOR 2
RUN cd /home/builduser \
&& git clone https://github.com/polhenarejos/pico-hsm.git \
@@ -46,7 +46,7 @@ ENV PICO_SDK_PATH /home/builduser/Devel/pico/pico-sdk
ARG USB_VID 0xfeff
ARG USB_PID 0xfcfd
ARG PICO_BOARD waveshare_rp2040_zero
ARG PICO_BOARD waveshare_rp2040_zero
RUN cd /home/builduser/pico-hsm \
&& cd build_release \

116
ENTERPRISE.md Normal file
View File

@@ -0,0 +1,116 @@
# Enterprise / Commercial Edition
This project is offered under two editions:
## 1. Community Edition (FOSS)
The Community Edition is released under the GNU Affero General Public License v3 (AGPLv3).
Intended for:
- individual users and researchers
- evaluation / prototyping
- internal lab / security testing
You are allowed to:
- read and study the source code
- modify it
- run it internally
Obligations under AGPLv3:
- If you distribute modified firmware/binaries/libraries to third parties, you must provide the corresponding source code of your modifications.
- If you run a modified version of this project as a network-accessible service (internal or external), you must offer the source code of those modifications to the users of that service.
- No warranty, no support, no SLA.
- Enterprise features (bulk provisioning, multi-user policy enforcement, device inventory / revocation, corporate PIN rules, custom attestation/identity, etc.) are NOT included.
The Community Edition will continue to exist.
## 2. Enterprise / Commercial Edition
The Enterprise / Commercial Edition is a proprietary license for organizations that need to:
- deploy this in production at scale (multiple devices / multiple users / multiple teams)
- integrate it into their own physical product or appliance
- run it as an internal service (VM / container / private cloud "HSM / auth backend") for multiple internal teams or tenants
- enforce internal security policy (admin vs user roles, mandatory PIN rules, secure offboarding / revocation)
- avoid any AGPLv3 disclosure obligations for their own modifications and integration code
### What the Enterprise Edition provides
**Base license package (always included):**
- **Commercial license (proprietary).**
You may run and integrate the software/firmware in production — including virtualized / internal-cloud style deployments — without being required to disclose derivative source code under AGPLv3.
- **Official signed builds.**
You receive signed builds from the original developer so you can prove integrity and provenance.
- **Onboarding call (up to 1 hour).**
A live remote session to get you from "we have it" to "its actually running in our environment" with minimal guesswork.
**Optional enterprise components (available on demand, scoped and priced per customer):**
- **Production / multi-user readiness.**
Permission to operate the system with multiple users, multiple devices and multiple teams in real environments.
- **Bulk / fleet provisioning.**
Automated enrollment for many tokens/devices/users at once (CSV / directory import), scripted onboarding of new users, initial PIN assignment / reset workflows, and role-based access (admin vs user).
- **Policy & lifecycle tooling.**
Corporate PIN policy enforcement, per-user / per-team access control, device inventory / traceability, and secure revocation / retirement when someone leaves.
- **Custom attestation / per-organization identity.**
Per-company certificate chains and attestation keys so devices can prove "this token/HSM is officially ours," including anti-cloning / unique device identity for OEM and fleet use.
- **Virtualization / internal cloud deployment support.**
Guidance and components to run this as an internal service (VM, container, private-cloud HSM/auth backend) serving multiple internal teams or tenants under your brand.
- **Post-quantum (PQC) key material handling.**
Integration/roadmap support for PQC algorithms (auth / signing) and secure PQC key storage inside the device or service.
- **Hierarchical deterministic key derivation (HD).**
Wallet-style hierarchical key trees (BIP32-like concepts adapted to this platform) for issuing per-user / per-tenant / per-purpose subkeys without exporting the root secret — e.g. embedded wallet logic, tenant isolation, firmware signing trees, large fleets.
- **Cryptographically signed audit trail / tamper-evident event logging.**
High-assurance logging of sensitive actions (key use, provisioning, PIN resets, revocations) with integrity protection for forensic / compliance needs.
- **Dual-control / two-person approval ("four-eyes").**
Require multi-party authorization for high-risk actions such as firmware signing, key export, or critical configuration changes — standard in high-assurance / regulated environments.
- **Secure key escrow / disaster recovery design.**
Split-secret or escrowed backup strategies so you dont lose critical signing keys if a single admin disappears or hardware is lost.
- **Release-signing / supply-chain hardening pipeline.**
Reference tooling and process so every production firmware/binary is signed with hardware-backed keys, proving origin and preventing tampering in transit or at manufacturing.
- **Policy-locked hardened mode ("FIPS-style profile").**
Restricted algorithms, debug disabled, no raw key export, tamper-evident configuration for regulated / high-assurance deployments.
- **Priority support / security response SLA.**
A direct line and guaranteed response window for production-impacting security issues.
- **White-label demo / pre-sales bundle.**
Branded demo firmware + safe onboarding script so you can show "your product" to your own customers without exposing real production secrets.
These components are NOT automatically bundled. They are available case-by-case depending on your use case and are priced separately.
### Licensing models
- **Internal Use License**
Internal production use within one legal entity (your company), including internal private cloud / virtualized deployments for multiple internal teams.
Optional enterprise components can be added as needed.
- **OEM / Redistribution / Service License**
Integration into a product/appliance you ship to customers, OR operating this as a managed service / hosted feature for external clients or third parties.
Optional enterprise components (attestation branding, PQC support, HD key derivation, multi-tenant service hardening, audit trail, etc.) can be added as required.
Pricing depends on scope, fleet size, number of users/tenants, regulatory requirements, and which optional components you select.
### Request a quote
Email: pol@henarejos.me
Subject: `ENTERPRISE LICENSE <your company name>`
Please include:
- Company name and country
- Intended use:
- Internal private deployment
- OEM / external service to third parties
- Approximate scale (number of devices/tokens, number of users/tenants)
- Which optional components you are interested in (bulk provisioning, policy & lifecycle tooling, attestation branding / anti-cloning, virtualization/cloud, PQC, HD key derivation, audit trail, dual-control, key escrow, supply-chain signing, hardened mode, SLA, white-label demo)
You will receive:
1. A short commercial license agreement naming your company.
2. Access to the base package (and any optional components agreed).
3. Scheduling of the onboarding call.
## Why Enterprise exists
- Companies often need hardware-backed security (HSM, FIDO2, OpenPGP, etc.) under their own control, but cannot or will not open-source their internal security workflows.
- They also need multi-user / fleet-management features that hobby users do not.
- The commercial license funds continued development, maintenance and new hardware support.
The Community Edition remains AGPLv3.
The Enterprise Edition is for production, scale, and legal clarity.

143
LICENSE
View File

@@ -1,5 +1,5 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
@@ -7,17 +7,15 @@
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
@@ -26,44 +24,34 @@ them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
@@ -72,7 +60,7 @@ modification follow.
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
@@ -549,35 +537,45 @@ to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
@@ -635,40 +633,29 @@ the "copyright" line and a pointer to where the full notice is found.
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
GNU Affero General Public License for more details.
You should have received a copy of the GNU General Public License
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <https://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<https://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<https://www.gnu.org/licenses/why-not-lgpl.html>.
For more information on this, and how to apply and follow the GNU AGPL, see
<https://www.gnu.org/licenses/>.

103
README.md
View File

@@ -1,4 +1,4 @@
# Raspberry Pico HSM
# 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
@@ -138,6 +138,21 @@ Uses an MKEK to securely store all keys, encrypted with an ephemeral key derived
### > 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.[^4]
### > One Time Programming (OTP) Storage
The OTP securely stores the MKEK (Master Key Encryption Key) and Device Key permanently, making it inaccessible from external interfaces. This ensures that the key is protected against unauthorized access and tampering.
### > Secure Boot
Secure Boot ensures only authenticated firmware can run on the device, verifying each firmwares digital signature to block unauthorized code.
### > Secure Lock
Secure Lock restricts the device to the manufacturers firmware only, locking out debug access and preventing any further boot key installations.
### > Rescue Interface
A built-in rescue interface allows recovery of the device if it becomes unresponsive or undetectable. This feature provides a way to restore the device to operational status without compromising security.
### > LED Customization
The LED can be customized to reflect device status and user preferences, offering flexible color and brightness options for an enhanced user experience.
[^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]: Available via SCS3 tool. See [SCS3](/doc/scs3.md "SCS3") for more information.
[^3]: Imports are available only if the Pico HSM is previously initialized with a DKEK and DKEK shares are available during the import process.
@@ -147,33 +162,35 @@ Supports BIP32 for asymmetric key derivation and SLIP10 for symmetric key deriva
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.
Supports setting VID & PID on-the-fly. U
### > Rescue Pico HSM Tool
### > Rescue Pico HSM
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.
All secret keys (both asymmetric and symmetric) are encrypted and stored in the flash memory. The MKEK, a 256-bit AES key, is used to protect these private and secret keys. Keys are held in RAM only 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.
The MKEK 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 plaintext, neither in flash memory nor in RAM. However, if no secure channel is used, the PIN may be transmitted in plaintext from the host to the HSM.
DKEKs are used during the export and import of private/secret keys and are part of a Key Domain. A Key Domain is a set of secret/private keys that share the same DKEK. These are also shared by the custodians and are not specific to Pico HSM. Therefore, if a key does not belong to a Key Domain (and thus lacks a DKEK), it cannot be exported.
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.
### RP2350 and ESP32-S3
RP2350 and ESP32-S3 microcontrollers are equipped with advanced security features, including Secure Boot and Secure Lock, ensuring that firmware integrity and authenticity are tightly controlled. Both devices support the storage of the Master Key Encryption Key (MKEK) in an OTP (One-Time Programmable) memory region, making it permanently inaccessible for external access or tampering. This secure, non-volatile region guarantees that critical security keys are embedded into the hardware, preventing unauthorized access and supporting robust defenses against code injection or firmware modification. Together, Secure Boot and Secure Lock enforce firmware authentication, while the MKEK in OTP memory solidifies the foundation for secure operations.
## Download
**If you own an ESP32-S3 board, go to [ESP32 support](https://www.picokeys.com/esp32-support/) for further information.**
**If you own an ESP32-S3 board, go to [ESP32 Flasher](https://www.picokeys.com/esp32-flasher/) for flashing your Pico HSM.**
Please, go to the Release page and download the UF2 file for your board.
If you own a Raspberry Pico (RP2040 or RP2350), go to [Download page](https://www.picokeys.com/getting-started/). If your board is mounted with the RP2040, then select Pico. If your board is mounted with the RP2350 or RP2354, select Pico2.
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](https://www.picokeys.com/pico-patcher/).
UF2 files are shiped with a VID/PID granted by RaspberryPi (2E8A:10FD). 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 [PicoKey App](https://www.picokeys.com/picokeyapp/ "PicoKey App").
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 for internal purposes, but remember that you are not authorized to distribute the binary with a VID/PID that you do not own.
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 [PicoKey App](https://www.picokeys.com/picokeyapp/ "PicoKey App") is the most recommended.
Note that the pure-browser option [Pico Patcher tool](https://www.picokeys.com/pico-patcher/) is the most recommended.
## Build
## Build for Raspberry Pico
Before building, ensure you have installed the toolchain for the Pico and the Pico SDK is properly located in your drive.
```
@@ -212,9 +229,9 @@ Independent from your Linux distribution or when using another OS that supports
```
sudo docker build \
--build-arg VERSION_PICO_SDK=1.5.0 \
--build-arg VERSION_MAJOR=3 \
--build-arg VERSION_MINOR=4 \
--build-arg VERSION_PICO_SDK=2.0.0 \
--build-arg VERSION_MAJOR=5 \
--build-arg VERSION_MINOR=0 \
--build-arg PICO_BOARD=waveshare_rp2040_zero \
--build-arg USB_VID=0xfeff \
--build-arg USB_PID=0xfcfd \
@@ -318,12 +335,52 @@ Communication with the Pico HSM follows the same protocols and methods used with
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](/doc/scs3.md).
### 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](https://www.picokeys.com/pico-patcher/).
- Patch the UF2 binary (if you just downloaded from the [Release section](https://github.com/polhenarejos/pico-hsm/releases "Release section"))
- Build and configure the project with the proper VID/PID with `USB_VID` and `USB_PID` parameters in `CMake` (see [Build section](#build "Build section")). Note that you cannot distribute the patched/compiled binary if you do not own the VID/PID or have an explicit authorization.
## License and Commercial Use
This project is available under two editions:
**Community Edition (FOSS)**
- Released under the GNU Affero General Public License v3 (AGPLv3).
- You are free to study, modify, and run the code, including for internal evaluation.
- If you distribute modified binaries/firmware, OR if you run a modified version of this project as a network-accessible service, you must provide the corresponding source code to the users of that binary or service, as required by AGPLv3.
- No warranty. No SLA. No guaranteed support.
**Enterprise / Commercial Edition**
- Proprietary license for organizations that want to:
- run this in production with multiple users/devices,
- integrate it into their own product/appliance,
- enforce corporate policies (PIN policy, admin/user roles, revocation),
- deploy it as an internal virtualized / cloud-style service,
- and *not* be required to publish derivative source code.
- Base package includes:
- commercial license (no AGPLv3 disclosure obligation for your modifications / integration)
- onboarding call
- access to officially signed builds
- Optional / on-demand enterprise components that can be added case-by-case:
- ability to operate in multi-user / multi-device environments
- device inventory, traceability and secure revocation/offboarding
- custom attestation, per-organization device identity / anti-cloning
- virtualization / internal "HSM or auth backend" service for multiple teams or tenants
- post-quantum (PQC) key material handling and secure PQC credential storage
- hierarchical deterministic key derivation (HD walletstyle key trees for per-user / per-tenant keys, firmware signing trees, etc.)
- cryptographically signed audit trail / tamper-evident logging
- dual-control / two-person approval for high-risk operations
- secure key escrow / disaster recovery strategy
- release-signing / supply-chain hardening toolchain
- policy-locked hardened mode ("FIPS-style profile")
- priority security-response SLA
- white-label demo / pre-sales bundle
Typical licensing models:
- Internal use (single legal entity, including internal private cloud / virtualized deployments).
- OEM / Redistribution / Service (ship in your product OR offer it as a service to third parties).
These options are scoped and priced individually depending on which components you actually need.
For commercial licensing and enterprise features, email pol@henarejos.me
Subject: `ENTERPRISE LICENSE <your company name>`
See `ENTERPRISE.md` for details.
## Credits
Pico HSM uses the following libraries or portion of code:

View File

@@ -1,103 +1,25 @@
#!/bin/bash
VERSION_MAJOR="4"
VERSION_MINOR="2-eddsa1"
VERSION_MAJOR="6"
VERSION_MINOR="4"
SUFFIX="${VERSION_MAJOR}.${VERSION_MINOR}"
#if ! [[ -z "${GITHUB_SHA}" ]]; then
# SUFFIX="${SUFFIX}.${GITHUB_SHA}"
#fi
rm -rf release/*
mkdir -p build_release
mkdir -p release
rm -rf -- release/*
cd build_release
for board in 0xcb_helios \
adafruit_feather_rp2040_usb_host \
adafruit_feather_rp2040 \
adafruit_itsybitsy_rp2040 \
adafruit_kb2040 \
adafruit_macropad_rp2040 \
adafruit_qtpy_rp2040 \
adafruit_trinkey_qt2040 \
amethyst_fpga \
archi \
arduino_nano_rp2040_connect \
cytron_maker_pi_rp2040 \
datanoisetv_rp2040_dsp \
eetree_gamekit_rp2040 \
garatronic_pybstick26_rp2040 \
gen4_rp2350_24 \
gen4_rp2350_24ct \
gen4_rp2350_24t \
gen4_rp2350_28 \
gen4_rp2350_28ct \
gen4_rp2350_28t \
gen4_rp2350_32 \
gen4_rp2350_32ct \
gen4_rp2350_32t \
gen4_rp2350_35 \
gen4_rp2350_35ct \
gen4_rp2350_35t \
hellbender_2350A_devboard \
ilabs_challenger_rp2350_bconnect \
ilabs_challenger_rp2350_wifi_ble \
ilabs_opendec02 \
melopero_perpetuo_rp2350_lora \
melopero_shake_rp2040 \
metrotech_xerxes_rp2040 \
net8086_usb_interposer \
nullbits_bit_c_pro \
phyx_rick_tny_rp2350 \
pi-plates_micropi \
pico \
pico_w \
pico2 \
pimoroni_badger2040 \
pimoroni_interstate75 \
pimoroni_keybow2040 \
pimoroni_motor2040 \
pimoroni_pga2040 \
pimoroni_pga2350 \
pimoroni_pico_plus2_rp2350 \
pimoroni_picolipo_4mb \
pimoroni_picolipo_16mb \
pimoroni_picosystem \
pimoroni_plasma2040 \
pimoroni_plasma2350 \
pimoroni_servo2040 \
pimoroni_tiny2040 \
pimoroni_tiny2040_2mb \
pimoroni_tiny2350 \
pololu_3pi_2040_robot \
pololu_zumo_2040_robot \
seeed_xiao_rp2040 \
seeed_xiao_rp2350 \
solderparty_rp2040_stamp \
solderparty_rp2040_stamp_carrier \
solderparty_rp2040_stamp_round_carrier \
solderparty_rp2350_stamp_xl \
solderparty_rp2350_stamp \
sparkfun_micromod \
sparkfun_promicro \
sparkfun_promicro_rp2350 \
sparkfun_thingplus \
switchscience_picossci2_conta_base \
switchscience_picossci2_dev_board \
switchscience_picossci2_micro \
switchscience_picossci2_rp2350_breakout \
switchscience_picossci2_tiny \
tinycircuits_thumby_color_rp2350 \
vgaboard \
waveshare_rp2040_lcd_0.96 \
waveshare_rp2040_lcd_1.28 \
waveshare_rp2040_one \
waveshare_rp2040_plus_4mb \
waveshare_rp2040_plus_16mb \
waveshare_rp2040_zero \
weact_studio_rp2040_2mb \
weact_studio_rp2040_4mb \
weact_studio_rp2040_8mb \
weact_studio_rp2040_16mb \
wiznet_w5100s_evb_pico
do
rm -rf *
PICO_SDK_PATH=~/Devel/pico/pico-sdk cmake .. -DPICO_BOARD=$board
make -kj20
mv pico_hsm.uf2 ../release/pico_hsm_$board-$VERSION_MAJOR.$VERSION_MINOR.uf2
PICO_SDK_PATH="${PICO_SDK_PATH:-../../pico-sdk}"
SECURE_BOOT_PKEY="${SECURE_BOOT_PKEY:-../../ec_private_key.pem}"
boards=("pico" "pico2")
for board_name in "${boards[@]}"
do
rm -rf -- ./*
PICO_SDK_PATH="${PICO_SDK_PATH}" cmake .. -DPICO_BOARD=$board_name -DSECURE_BOOT_PKEY=${SECURE_BOOT_PKEY}
make -j`nproc`
mv pico_hsm.uf2 ../release/pico_hsm_$board_name-$SUFFIX.uf2
done

View File

@@ -13,7 +13,8 @@ However, SCS3 only works with those HSM manufactured by CardContact. The check i
Pico HSM is shipped with its own CA certificates. To load this certificate onto the trust store of SCS3, the following line has to be appended to `SmartCardHSM.rootCerts` variable, near line `235` in the file `scs3/scsh/sc-hsm/SmartCardHSM.js`.
```
ESPICOHSMCA00001: new CVC(new ByteString("7F218201BA7F4E8201725F290100421045535049434F48534D434130303030317F4982011D060A04007F000702020202038120FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF8220FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC83205AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B8441046B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C2964FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F58520FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC6325518641046A82C0A4FEAF41D6A1336AE7E992D81AD4F827929145DD0D777E1AB63D7E3325C8F7DAC0F74B6EAE13A72F6366777EC133AC5C28F456868E5F2C315044EB54EF8701015F201045535049434F48534D434130303030317F4C12060904007F0007030102025305C0000000005F25060202000801085F24060203000801085F3740601E974F57DDE060875FE6121AEF5BC02E10FC655311C7A32CA822FD18E53A80298EDC56E0D5EBF38FB470DC12987B1600AE91A0ADB5B22C4D80080782E278AD", HEX))
ESPICOHSMCA00001: new CVC(new ByteString("7F218201BA7F4E8201725F290100421045535049434F48534D434130303030317F4982011D060A04007F000702020202038120FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF8220FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC83205AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B8441046B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C2964FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F58520FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC6325518641046A82C0A4FEAF41D6A1336AE7E992D81AD4F827929145DD0D777E1AB63D7E3325C8F7DAC0F74B6EAE13A72F6366777EC133AC5C28F456868E5F2C315044EB54EF8701015F201045535049434F48534D434130303030317F4C12060904007F0007030102025305C0000000005F25060202000801085F24060203000801085F3740601E974F57DDE060875FE6121AEF5BC02E10FC655311C7A32CA822FD18E53A80298EDC56E0D5EBF38FB470DC12987B1600AE91A0ADB5B22C4D80080782E278AD", HEX)),
ESPICOHSMCA00002: new CVC(new ByteString("7F218201BA7F4E8201725F290100421045535049434F48534D434130303030327F4982011D060A04007F000702020202038120FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F822000000000000000000000000000000000000000000000000000000000000000008320000000000000000000000000000000000000000000000000000000000000000784410479BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B88520FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141864104FD4DDCD165DD64494F5F1DB76CDAE4E6BD10DA59BF6D48B684E9D50BCC4C2114D2A8BC7C9C1ACAA24C982B1383D4D02E0F32323F657E146E8A051DEB7F6CD40C8701015F201045535049434F48534D434130303030327F4C12060904007F0007030102025305C0000000045F25060205000400065F24060308000302065F3740472AA7A7945F6352F8A65388C2810AEFB657356FFD31CBB2FCC516BC4ECC953D0BACA935B22D73F49802DD9E9DE6439FD8AEA18BD71E1439ABF458C085BD70C8", HEX))
```
Therefore, the whole variable becomes:
@@ -22,7 +23,8 @@ Therefore, the whole variable becomes:
SmartCardHSM.rootCerts = {
DESRCACC100001: new CVC(new ByteString("7F218201B47F4E82016C5F290100420E44455352434143433130303030317F4982011D060A04007F000702020202038120A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E537782207D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9832026DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B68441048BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F0469978520A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A78641046D025A8026CDBA245F10DF1B72E9880FFF746DAB40A43A3D5C6BEBF27707C30F6DEA72430EE3287B0665C1EAA6EAA4FA26C46303001983F82BD1AA31E03DA0628701015F200E44455352434143433130303030317F4C10060B2B0601040181C31F0301015301C05F25060102010100095F24060302010100085F37409DBB382B1711D2BAACB0C623D40C6267D0B52BA455C01F56333DC9554810B9B2878DAF9EC3ADA19C7B065D780D6C9C3C2ECEDFD78DEB18AF40778ADF89E861CA", HEX)),
UTSRCACC100001: new CVC(new ByteString("7F218201B47F4E82016C5F290100420E55545352434143433130303030317F4982011D060A04007F000702020202038120A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E537782207D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9832026DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B68441048BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F0469978520A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7864104A041FEB2FD116B2AD19CA6B7EACD71C9892F941BB88D67DCEEC92501F070011957E22122BA6C2CF5FF02936F482E35A6129CCBBA8E9383836D3106879C408EF08701015F200E55545352434143433130303030317F4C10060B2B0601040181C31F0301015301C05F25060102010100095F24060302010100085F3740914DD0FA00615C44048D1467435400423A4AD1BD37FD98D6DE84FD8037489582325C72956D4FDFABC6EDBA48184A754F37F1BE5142DD1C27D66569308CE19AAF", HEX)),
ESPICOHSMCA00001: new CVC(new ByteString("7F218201BA7F4E8201725F290100421045535049434F48534D434130303030317F4982011D060A04007F000702020202038120FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF8220FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC83205AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B8441046B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C2964FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F58520FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC6325518641046A82C0A4FEAF41D6A1336AE7E992D81AD4F827929145DD0D777E1AB63D7E3325C8F7DAC0F74B6EAE13A72F6366777EC133AC5C28F456868E5F2C315044EB54EF8701015F201045535049434F48534D434130303030317F4C12060904007F0007030102025305C0000000005F25060202000801085F24060203000801085F3740601E974F57DDE060875FE6121AEF5BC02E10FC655311C7A32CA822FD18E53A80298EDC56E0D5EBF38FB470DC12987B1600AE91A0ADB5B22C4D80080782E278AD", HEX))
ESPICOHSMCA00001: new CVC(new ByteString("7F218201BA7F4E8201725F290100421045535049434F48534D434130303030317F4982011D060A04007F000702020202038120FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF8220FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC83205AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B8441046B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C2964FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F58520FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC6325518641046A82C0A4FEAF41D6A1336AE7E992D81AD4F827929145DD0D777E1AB63D7E3325C8F7DAC0F74B6EAE13A72F6366777EC133AC5C28F456868E5F2C315044EB54EF8701015F201045535049434F48534D434130303030317F4C12060904007F0007030102025305C0000000005F25060202000801085F24060203000801085F3740601E974F57DDE060875FE6121AEF5BC02E10FC655311C7A32CA822FD18E53A80298EDC56E0D5EBF38FB470DC12987B1600AE91A0ADB5B22C4D80080782E278AD", HEX)),
ESPICOHSMCA00002: new CVC(new ByteString("7F218201BA7F4E8201725F290100421045535049434F48534D434130303030327F4982011D060A04007F000702020202038120FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFC2F822000000000000000000000000000000000000000000000000000000000000000008320000000000000000000000000000000000000000000000000000000000000000784410479BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B88520FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141864104FD4DDCD165DD64494F5F1DB76CDAE4E6BD10DA59BF6D48B684E9D50BCC4C2114D2A8BC7C9C1ACAA24C982B1383D4D02E0F32323F657E146E8A051DEB7F6CD40C8701015F201045535049434F48534D434130303030327F4C12060904007F0007030102025305C0000000045F25060205000400065F24060308000302065F3740472AA7A7945F6352F8A65388C2810AEFB657356FFD31CBB2FCC516BC4ECC953D0BACA935B22D73F49802DD9E9DE6439FD8AEA18BD71E1439ABF458C085BD70C8", HEX))
}
```
@@ -33,15 +35,15 @@ Similarly, replace the line `1531` in file `scs3/keymanager/keymanager.js` with:
```
Alternatively, this patch [scs3.patch.txt](https://github.com/polhenarejos/pico-hsm/files/9415877/scs3.patch.txt) can be applied.
Alternatively, this patch [scs3.patch.txt](https://github.com/user-attachments/files/20274013/scs3.patch.txt) can be applied.
After this ammendment, the program can be started and the KeyManager can be invoked (CTRL+M) and it will output something similar to:
```
>load("keymanager/keymanager.js");
SmartCard-HSM Version 2.6 on JCOP Free memory 215512 byte
Issuer Certificate : CVC id-AT DV (official domestic) CAR=ESPICOHSMCA00001 CHR=ESPICOHSMDV00001 CED=18 / dagost / 2022 CXD=14 / de juny / 2023
Device Certificate : CVC id-AT Terminal CAR=ESPICOHSMDV00001 CHR=ESPICOHSMTRYZRGW CED=22 / dagost / 2022 CXD=22 / dagost / 2023
Issuer Certificate : CVC id-AT DV (official domestic) CAR=ESPICOHSMCA00001 CHR=ESPICOHSMDV00001 CED=18 / dagost / 2022 CXD=14 / de juny / 2023
Device Certificate : CVC id-AT Terminal CAR=ESPICOHSMDV00001 CHR=ESPICOHSMTRYZRGW CED=22 / dagost / 2022 CXD=22 / dagost / 2023
Default Key Domain : 223CD8D8F794889AC163305881BF8C04960BBB8658120491F1C0601F6BF97183
-------------------------------------------------------------------
Please right-click on nodes in the outline to see possible actions.

View File

@@ -28,9 +28,9 @@ PIN=648219
[^1]: `openssl version -a` will return the `OPENSSLDIR`, which contains `openssl.cnf` file and `ENGINESDIR`, which contains the p11 engine.
## Initialization
The first step is to initialize the HSM. To do so, use the `pico-hsm-tool.py` in `tools` folder:
The first step is to initialize the HSM. To do so, use:
```
$ python3 tools/pico-hsm-tool.py --pin 648219 initialize --so-pin 57621880
$ sc-hsm-tool --initialize --so-pin 3537363231383830 --pin 648219
```
The PIN number is used to manage all private keys in the device. It supports three attemps. After the third PIN failure, it gets blocked.
The PIN accepts from 6 to 16 characters.

View File

@@ -18,9 +18,20 @@ if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT_PATH} AND (NOT PICO_SDK_FETCH_FROM_GIT_P
message("Using PICO_SDK_FETCH_FROM_GIT_PATH from environment ('${PICO_SDK_FETCH_FROM_GIT_PATH}')")
endif ()
if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT_TAG} AND (NOT PICO_SDK_FETCH_FROM_GIT_TAG))
set(PICO_SDK_FETCH_FROM_GIT_TAG $ENV{PICO_SDK_FETCH_FROM_GIT_TAG})
message("Using PICO_SDK_FETCH_FROM_GIT_TAG from environment ('${PICO_SDK_FETCH_FROM_GIT_TAG}')")
endif ()
if (PICO_SDK_FETCH_FROM_GIT AND NOT PICO_SDK_FETCH_FROM_GIT_TAG)
set(PICO_SDK_FETCH_FROM_GIT_TAG "master")
message("Using master as default value for PICO_SDK_FETCH_FROM_GIT_TAG")
endif()
set(PICO_SDK_PATH "${PICO_SDK_PATH}" CACHE PATH "Path to the Raspberry Pi Pico SDK")
set(PICO_SDK_FETCH_FROM_GIT "${PICO_SDK_FETCH_FROM_GIT}" CACHE BOOL "Set to ON to fetch copy of SDK from git if not otherwise locatable")
set(PICO_SDK_FETCH_FROM_GIT_PATH "${PICO_SDK_FETCH_FROM_GIT_PATH}" CACHE FILEPATH "location to download SDK")
set(PICO_SDK_FETCH_FROM_GIT_TAG "${PICO_SDK_FETCH_FROM_GIT_TAG}" CACHE FILEPATH "release tag for SDK")
if (NOT PICO_SDK_PATH)
if (PICO_SDK_FETCH_FROM_GIT)
@@ -29,11 +40,22 @@ if (NOT PICO_SDK_PATH)
if (PICO_SDK_FETCH_FROM_GIT_PATH)
get_filename_component(FETCHCONTENT_BASE_DIR "${PICO_SDK_FETCH_FROM_GIT_PATH}" REALPATH BASE_DIR "${CMAKE_SOURCE_DIR}")
endif ()
FetchContent_Declare(
pico_sdk
GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk
GIT_TAG master
)
# GIT_SUBMODULES_RECURSE was added in 3.17
if (${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.17.0")
FetchContent_Declare(
pico_sdk
GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk
GIT_TAG ${PICO_SDK_FETCH_FROM_GIT_TAG}
GIT_SUBMODULES_RECURSE FALSE
)
else ()
FetchContent_Declare(
pico_sdk
GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk
GIT_TAG ${PICO_SDK_FETCH_FROM_GIT_TAG}
)
endif ()
if (NOT pico_sdk)
message("Downloading Raspberry Pi Pico SDK")
FetchContent_Populate(pico_sdk)

View File

@@ -3,12 +3,19 @@
#
IGNORE_UNKNOWN_FILES_FOR_MANAGED_COMPONENTS=y
CONFIG_TINYUSB=y
CONFIG_TINYUSB_TASK_STACK_SIZE=16384
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="pico-keys-sdk/config/esp32/partitions.csv"
CONFIG_PARTITION_TABLE_FILENAME="pico-keys-sdk/config/esp32/partitions.csv"
CONFIG_PARTITION_TABLE_OFFSET=0x10000
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
CONFIG_ESPTOOLPY_FLASHMODE_QIO=y
CONFIG_ESP_DEFAULT_CPU_FREQ_MHZ_240=y
CONFIG_WL_SECTOR_SIZE_512=y
CONFIG_WL_SECTOR_MODE_PERF=y
COMPILER_OPTIMIZATION="Performance"
CONFIG_MBEDTLS_CMAC_C=y
CONFIG_MBEDTLS_CHACHA20_C=y

View File

@@ -1,6 +1,6 @@
idf_component_register(
SRCS ${SOURCES}
INCLUDE_DIRS . ../../pico-keys-sdk/src ../../pico-keys-sdk/src/fs ../../pico-keys-sdk/src/rng ../../pico-keys-sdk/src/usb
REQUIRES bootloader_support esp_partition esp_tinyusb zorxx__neopixel mbedtls efuse
INCLUDE_DIRS .
REQUIRES mbedtls efuse pico-keys-sdk
)
idf_component_set_property(${COMPONENT_NAME} WHOLE_ARCHIVE ON)

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"
@@ -38,7 +38,7 @@ int node_derive_bip_child(const mbedtls_ecp_keypair *parent,
mbedtls_mpi_init(&kchild);
if (i[0] >= 0x80) {
if (mbedtls_mpi_cmp_int(&parent->d, 0) == 0) {
return CCID_ERR_NULL_PARAM;
return PICOKEY_ERR_NULL_PARAM;
}
data[0] = 0x00;
mbedtls_mpi_write_binary(&parent->d, data + 1, 32);
@@ -72,19 +72,19 @@ int node_derive_bip_child(const mbedtls_ecp_keypair *parent,
memcpy(cchild, iR, 32);
mbedtls_mpi_free(&il);
mbedtls_mpi_free(&kchild);
return CCID_OK;
return PICOKEY_OK;
}
int sha256_ripemd160(const uint8_t *buffer, size_t buffer_len, uint8_t *output) {
mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), buffer, buffer_len, output);
mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_RIPEMD160), output, 32, output);
return CCID_OK;
return PICOKEY_OK;
}
int sha256_sha256(const uint8_t *buffer, size_t buffer_len, uint8_t *output) {
mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), buffer, buffer_len, output);
mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), output, 32, output);
return CCID_OK;
return PICOKEY_OK;
}
int node_fingerprint_bip(mbedtls_ecp_keypair *ctx, uint8_t fingerprint[4]) {
@@ -98,7 +98,7 @@ int node_fingerprint_bip(mbedtls_ecp_keypair *ctx, uint8_t fingerprint[4]) {
sizeof(buffer));
sha256_ripemd160(buffer, sizeof(buffer), buffer);
memcpy(fingerprint, buffer, 4);
return CCID_OK;
return PICOKEY_OK;
}
int node_fingerprint_slip(mbedtls_ecp_keypair *ctx, uint8_t fingerprint[4]) {
@@ -106,7 +106,7 @@ int node_fingerprint_slip(mbedtls_ecp_keypair *ctx, uint8_t fingerprint[4]) {
mbedtls_mpi_write_binary(&ctx->d, buffer, sizeof(buffer));
sha256_ripemd160(buffer, sizeof(buffer), buffer);
memcpy(fingerprint, buffer, 4);
return CCID_OK;
return PICOKEY_OK;
}
int load_master_bip(uint16_t mid, mbedtls_ecp_keypair *ctx, uint8_t chain[32],
@@ -115,13 +115,13 @@ int load_master_bip(uint16_t mid, mbedtls_ecp_keypair *ctx, uint8_t chain[32],
mbedtls_ecp_keypair_init(ctx);
file_t *ef = search_file(EF_MASTER_SEED | mid);
if (!file_has_data(ef)) {
return CCID_ERR_FILE_NOT_FOUND;
return PICOKEY_ERR_FILE_NOT_FOUND;
}
memcpy(mkey, file_get_data(ef), sizeof(mkey));
int r = mkek_decrypt(mkey + 1,
sizeof(mkey) - 1);
if (r != CCID_OK) {
return CCID_EXEC_ERROR;
if (r != PICOKEY_OK) {
return PICOKEY_EXEC_ERROR;
}
if (mkey[0] == 0x1 || mkey[0] == 0x2) {
if (mkey[0] == 0x1) {
@@ -131,7 +131,7 @@ int load_master_bip(uint16_t mid, mbedtls_ecp_keypair *ctx, uint8_t chain[32],
mbedtls_ecp_group_load(&ctx->grp, MBEDTLS_ECP_DP_SECP256R1);
}
else {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
mbedtls_mpi_read_binary(&ctx->d, mkey + 1, 32);
@@ -143,7 +143,7 @@ int load_master_bip(uint16_t mid, mbedtls_ecp_keypair *ctx, uint8_t chain[32],
memcpy(chain, mkey + 1, 32);
}
key_type[0] = mkey[0];
return CCID_OK;
return PICOKEY_OK;
}
int node_derive_path(const uint8_t *path,
@@ -166,16 +166,16 @@ int node_derive_path(const uint8_t *path,
for (; walk_tlv(&ctxi, &p, &tag, &tag_len, &tag_data); node++) {
if (tag == 0x02) {
if ((node == 0 && tag_len != 1) || (node != 0 && tag_len != 4)) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
if (node == 0) {
if ((r = load_master_bip(tag_data[0], ctx, chain, key_type)) != CCID_OK) {
if ((r = load_master_bip(tag_data[0], ctx, chain, key_type)) != PICOKEY_OK) {
return r;
}
}
else if (node > 0) {
node_fingerprint_bip(ctx, fingerprint);
if ((r = node_derive_bip_child(ctx, chain, tag_data, ctx, chain)) != CCID_OK) {
if ((r = node_derive_bip_child(ctx, chain, tag_data, ctx, chain)) != PICOKEY_OK) {
return r;
}
memcpy(last_node, tag_data, 4);
@@ -183,7 +183,7 @@ int node_derive_path(const uint8_t *path,
}
else if (tag == 0x04) {
if (node == 0) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
else if (node > 0) {
node_fingerprint_slip(ctx, fingerprint);
@@ -202,7 +202,7 @@ int node_derive_path(const uint8_t *path,
if (nodes) {
*nodes = node;
}
return CCID_OK;
return PICOKEY_OK;
}
int cmd_bip_slip() {
@@ -253,11 +253,11 @@ int cmd_bip_slip() {
mkey[0] = p1;
file_t *ef = file_new(EF_MASTER_SEED | p2);
int r = mkek_encrypt(mkey + 1, sizeof(mkey) - 1);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
r = file_put_data(ef, mkey, sizeof(mkey));
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
low_flash_available();
@@ -271,7 +271,7 @@ int cmd_bip_slip() {
size_t olen = 0;
int r =
node_derive_path(apdu.data, (uint16_t)apdu.nc, &ctx, chain, fgpt, &nodes, last_node, &key_type);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
mbedtls_ecp_keypair_free(&ctx);
return SW_EXEC_ERROR();
}
@@ -317,7 +317,7 @@ int cmd_bip_slip() {
&nodes,
last_node,
&hd_keytype);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
mbedtls_ecp_keypair_free(&hd_context);
return SW_EXEC_ERROR();
}

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "random.h"

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "crypto_utils.h"
@@ -42,7 +42,7 @@ int cmd_change_pin() {
}
uint8_t mkek[MKEK_SIZE];
r = load_mkek(mkek); //loads the MKEK with old pin
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
//encrypt MKEK with new pin
@@ -57,7 +57,7 @@ int cmd_change_pin() {
}
r = store_mkek(mkek);
release_mkek(mkek);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
uint8_t dhash[33];

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"
@@ -143,10 +143,7 @@ int mbedtls_ansi_x963_kdf(mbedtls_md_type_t md_type,
mbedtls_md_update(&md_ctx, input, input_len);
//TODO: be careful with architecture little vs. big
counter_buf[0] = (uint8_t) ((counter >> 24) & 0xff);
counter_buf[1] = (uint8_t) ((counter >> 16) & 0xff);
counter_buf[2] = (uint8_t) ((counter >> 8) & 0xff);
counter_buf[3] = (uint8_t) ((counter >> 0) & 0xff);
put_uint32_t_be(counter, counter_buf);
mbedtls_md_update(&md_ctx, counter_buf, 4);
@@ -413,13 +410,7 @@ int cmd_cipher_sym() {
size_t olen = 0;
mbedtls_asn1_buf params =
{.p = aad.data, .len = aad.len, .tag = (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)};
int r = mbedtls_pkcs5_pbes2_ext(&params,
algo == ALGO_EXT_CIPHER_ENCRYPT ? MBEDTLS_PKCS5_ENCRYPT : MBEDTLS_PKCS5_DECRYPT,
kdata,
key_size,
enc.data,
enc.len,
res_APDU, 4096, &olen);
int r = mbedtls_pkcs5_pbes2_ext(&params, algo == ALGO_EXT_CIPHER_ENCRYPT ? MBEDTLS_PKCS5_ENCRYPT : MBEDTLS_PKCS5_DECRYPT, kdata, key_size, enc.data, enc.len, res_APDU, MAX_APDU_DATA, &olen);
mbedtls_platform_zeroize(kdata, sizeof(kdata));
if (r != 0) {
return SW_WRONG_DATA();
@@ -664,7 +655,7 @@ int cmd_cipher_sym() {
secret[64] = { 0 };
mbedtls_aes_init(&ctx);
if (hd_keytype != 0x3) {
mbedtls_ecdsa_free(&hd_context);
mbedtls_ecp_keypair_free(&hd_context);
return SW_INCORRECT_PARAMS();
}
key_size = 32;
@@ -698,7 +689,7 @@ int cmd_cipher_sym() {
return SW_EXEC_ERROR();
}
res_APDU_size = enc.len;
mbedtls_ecdsa_free(&hd_context);
mbedtls_ecp_keypair_free(&hd_context);
hd_keytype = 0;
}
else {

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"
@@ -48,9 +48,9 @@ int cmd_decrypt_asym() {
mbedtls_rsa_set_padding(&ctx, MBEDTLS_RSA_PKCS_V21, MBEDTLS_MD_SHA256);
}
int r = load_private_key_rsa(&ctx, ef);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
mbedtls_rsa_free(&ctx);
if (r == CCID_VERIFICATION_FAILED) {
if (r == PICOKEY_VERIFICATION_FAILED) {
return SW_SECURE_MESSAGE_EXEC_ERROR();
}
return SW_EXEC_ERROR();
@@ -178,7 +178,7 @@ int cmd_decrypt_asym() {
if (file_get_size(tf) == kdom_uid.len &&
memcmp(file_get_data(tf), kdom_uid.data, kdom_uid.len) == 0) {
file_new(EF_DKEK + n);
if (store_dkek_key(n, res_APDU + 1) != CCID_OK) {
if (store_dkek_key(n, res_APDU + 1) != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
mbedtls_platform_zeroize(res_APDU, 32);

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"
@@ -30,7 +30,7 @@ int cmd_delete_file() {
}
}
else {
uint16_t fid = (apdu.data[0] << 8) | apdu.data[1];
uint16_t fid = get_uint16_t_be(apdu.data);
if (!(ef = search_file(fid))) {
return SW_FILE_NOT_FOUND();
}
@@ -38,7 +38,7 @@ int cmd_delete_file() {
if (!authenticate_action(ef, ACL_OP_DELETE_SELF)) {
return SW_SECURITY_STATUS_NOT_SATISFIED();
}
if (delete_file(ef) != CCID_OK) {
if (delete_file(ef) != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
return SW_OK();

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"
@@ -57,9 +57,9 @@ int cmd_derive_asym() {
int r;
r = load_private_key_ec(&ctx, fkey);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
mbedtls_ecp_keypair_free(&ctx);
if (r == CCID_VERIFICATION_FAILED) {
if (r == PICOKEY_VERIFICATION_FAILED) {
return SW_SECURE_MESSAGE_EXEC_ERROR();
}
return SW_EXEC_ERROR();
@@ -88,7 +88,7 @@ int cmd_derive_asym() {
return SW_EXEC_ERROR();
}
r = store_keys(&ctx, PICO_KEYS_KEY_EC, dest_id);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
mbedtls_ecp_keypair_free(&ctx);
return SW_EXEC_ERROR();
}

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "crypto_utils.h"

View File

@@ -3,22 +3,23 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"
#include "mbedtls/ecdh.h"
#ifdef PICO_PLATFORM
#include "pico/aon_timer.h"
#include "hardware/watchdog.h"
#else
#include <sys/time.h>
#include <time.h>
@@ -28,11 +29,27 @@
#include "kek.h"
#include "mbedtls/hkdf.h"
#include "mbedtls/chachapoly.h"
#ifdef PICO_RP2350
#include "otp.h"
#endif
#define CMD_DATETIME 0xA
#define CMD_DYNOPS 0x6
#define CMD_SECURE_LOCK 0x3A
#define CMD_REBOOT 0xFB
#define SECURE_LOCK_KEY_AGREEMENT 0x1
#define SECURE_LOCK_ENABLE 0x2
#define SECURE_LOCK_MASK 0x3
#define SECURE_LOCK_DISABLE 0x4
#define CMD_PHY 0x1B
#define CMD_OTP 0x4C
#define CMD_MEMORY 0x5
int cmd_extras() {
int cmd = P1(apdu);
#ifndef ENABLE_EMULATION
// Only allow change PHY without PIN
if (!isUserAuthenticated && P1(apdu) != 0x1B) {
if (!isUserAuthenticated && cmd != CMD_PHY && cmd != CMD_MEMORY) {
return SW_SECURITY_STATUS_NOT_SATISFIED();
}
#endif
@@ -40,7 +57,7 @@ int cmd_extras() {
if (wait_button_pressed() == true) {
return SW_SECURE_MESSAGE_EXEC_ERROR();
}
if (P1(apdu) == 0xA) { //datetime operations
if (cmd == CMD_DATETIME) { //datetime operations
if (P2(apdu) != 0x0) {
return SW_INCORRECT_P1P2();
}
@@ -53,8 +70,7 @@ int cmd_extras() {
gettimeofday(&tv, NULL);
#endif
struct tm *tm = localtime(&tv.tv_sec);
res_APDU[res_APDU_size++] = (tm->tm_year + 1900) >> 8;
res_APDU[res_APDU_size++] = (tm->tm_year + 1900) & 0xff;
res_APDU_size += put_uint16_t_be(tm->tm_year + 1900, res_APDU);
res_APDU[res_APDU_size++] = tm->tm_mon;
res_APDU[res_APDU_size++] = tm->tm_mday;
res_APDU[res_APDU_size++] = tm->tm_wday;
@@ -67,7 +83,7 @@ int cmd_extras() {
return SW_WRONG_LENGTH();
}
struct tm tm;
tm.tm_year = ((apdu.data[0] << 8) | (apdu.data[1])) - 1900;
tm.tm_year = get_uint16_t_be(apdu.data) - 1900;
tm.tm_mon = apdu.data[2];
tm.tm_mday = apdu.data[3];
tm.tm_wday = apdu.data[4];
@@ -84,7 +100,7 @@ int cmd_extras() {
#endif
}
}
else if (P1(apdu) == 0x6) { //dynamic options
else if (cmd == CMD_DYNOPS) { //dynamic options
if (P2(apdu) != 0x0) {
return SW_INCORRECT_P1P2();
}
@@ -93,8 +109,7 @@ int cmd_extras() {
}
uint16_t opts = get_device_options();
if (apdu.nc == 0) {
res_APDU[res_APDU_size++] = opts >> 8;
res_APDU[res_APDU_size++] = opts & 0xff;
res_APDU_size += put_uint16_t_be(opts, res_APDU);
}
else {
uint8_t newopts[] = { apdu.data[0], (opts & 0xff) };
@@ -103,11 +118,11 @@ int cmd_extras() {
low_flash_available();
}
}
else if (P1(apdu) == 0x3A) { // secure lock
else if (cmd == CMD_SECURE_LOCK) { // secure lock
if (apdu.nc == 0) {
return SW_WRONG_LENGTH();
}
if (P2(apdu) == 0x01) { // Key Agreement
if (P2(apdu) == SECURE_LOCK_KEY_AGREEMENT) { // Key Agreement
mbedtls_ecdh_context hkey;
mbedtls_ecdh_init(&hkey);
mbedtls_ecdh_setup(&hkey, MBEDTLS_ECP_DP_SECP256R1);
@@ -135,7 +150,7 @@ int cmd_extras() {
return SW_EXEC_ERROR();
}
ret = mbedtls_ecp_point_write_binary(&hkey.ctx.mbed_ecdh.grp, &hkey.ctx.mbed_ecdh.Q, MBEDTLS_ECP_PF_UNCOMPRESSED, &olen, res_APDU, 4096);
ret = mbedtls_ecp_point_write_binary(&hkey.ctx.mbed_ecdh.grp, &hkey.ctx.mbed_ecdh.Q, MBEDTLS_ECP_PF_UNCOMPRESSED, &olen, res_APDU, MAX_APDU_DATA);
mbedtls_ecdh_free(&hkey);
if (ret != 0) {
return SW_EXEC_ERROR();
@@ -143,20 +158,19 @@ int cmd_extras() {
mse.init = true;
res_APDU_size = (uint16_t)olen;
}
else if (P2(apdu) == 0x02 || P2(apdu) == 0x03 || P2(apdu) == 0x04) {
else if (P2(apdu) == SECURE_LOCK_ENABLE || P2(apdu) == SECURE_LOCK_MASK || P2(apdu) == SECURE_LOCK_DISABLE) {
if (mse.init == false) {
return SW_COMMAND_NOT_ALLOWED();
}
uint16_t opts = get_device_options();
int ret = mse_decrypt_ct(apdu.data, apdu.nc);
if (ret != 0) {
return SW_WRONG_DATA();
}
if (P2(apdu) == 0x02 || P2(apdu) == 0x04) { // Enable
uint16_t opts = get_device_options();
if (P2(apdu) == SECURE_LOCK_ENABLE || P2(apdu) == SECURE_LOCK_DISABLE) { // Enable
uint8_t newopts[] = { opts >> 8, (opts & 0xff) };
if ((P2(apdu) == 0x02 && !(opts & HSM_OPT_SECURE_LOCK)) ||
(P2(apdu) == 0x04 && (opts & HSM_OPT_SECURE_LOCK))) {
if ((P2(apdu) == SECURE_LOCK_ENABLE && !(opts & HSM_OPT_SECURE_LOCK)) ||
(P2(apdu) == SECURE_LOCK_DISABLE && (opts & HSM_OPT_SECURE_LOCK))) {
uint16_t tfids[] = { EF_MKEK, EF_MKEK_SO };
for (int t = 0; t < sizeof(tfids) / sizeof(uint16_t); t++) {
file_t *tf = search_file(tfids[t]);
@@ -171,24 +185,24 @@ int cmd_extras() {
}
}
}
if (P2(apdu) == 0x02) {
if (P2(apdu) == SECURE_LOCK_ENABLE) {
newopts[0] |= HSM_OPT_SECURE_LOCK >> 8;
}
else if (P2(apdu) == 0x04) {
else if (P2(apdu) == SECURE_LOCK_DISABLE) {
newopts[0] &= ~HSM_OPT_SECURE_LOCK >> 8;
}
file_t *tf = search_file(EF_DEVOPS);
file_put_data(tf, newopts, sizeof(newopts));
low_flash_available();
}
else if (P2(apdu) == 0x03) {
memcpy(mkek_mask, apdu.data, apdu.nc);
else if (P2(apdu) == SECURE_LOCK_MASK && (opts & HSM_OPT_SECURE_LOCK)) {
memcpy(mkek_mask, apdu.data, MKEK_KEY_SIZE);
has_mkek_mask = true;
}
}
}
#ifndef ENABLE_EMULATION
else if (P1(apdu) == 0x1B) { // Set PHY
else if (cmd == CMD_PHY) { // Set PHY
if (apdu.nc == 0) {
if (file_has_data(ef_phy)) {
res_APDU_size = file_get_size(ef_phy);
@@ -196,51 +210,97 @@ int cmd_extras() {
}
}
else {
uint8_t tmp[PHY_MAX_SIZE];
memset(tmp, 0, sizeof(tmp));
uint16_t opts = 0;
if (file_has_data(ef_phy)) {
memcpy(tmp, file_get_data(ef_phy), MIN(sizeof(tmp), file_get_size(ef_phy)));
if (file_get_size(ef_phy) >= 8) {
opts = (tmp[PHY_OPTS] << 8) | tmp[PHY_OPTS + 1];
}
}
if (P2(apdu) == PHY_VID) { // VIDPID
if (P2(apdu) == PHY_VIDPID) { // VIDPID
if (apdu.nc != 4) {
return SW_WRONG_LENGTH();
}
memcpy(tmp + PHY_VID, apdu.data, 4);
opts |= PHY_OPT_VPID;
phy_data.vid = get_uint16_t_be(apdu.data);
phy_data.pid = get_uint16_t_be(apdu.data + 2);
phy_data.vidpid_present = true;
}
else if (P2(apdu) == PHY_LED_GPIO || P2(apdu) == PHY_LED_MODE) {
if (apdu.nc != 1) {
return SW_WRONG_LENGTH();
}
tmp[P2(apdu)] = apdu.data[0];
if (P2(apdu) == PHY_LED_GPIO) {
opts |= PHY_OPT_GPIO;
}
else if (P2(apdu) == PHY_LED_MODE) {
opts |= PHY_OPT_LED;
}
else if (P2(apdu) == PHY_LED_GPIO) {
phy_data.led_gpio = apdu.data[0];
phy_data.led_gpio_present = true;
}
else if (P2(apdu) == PHY_LED_BTNESS) {
phy_data.led_brightness = apdu.data[0];
phy_data.led_brightness_present = true;
}
else if (P2(apdu) == PHY_OPTS) {
if (apdu.nc != 2) {
return SW_WRONG_LENGTH();
}
uint16_t opt = (apdu.data[0] << 8) | apdu.data[1];
opts = (opts & ~PHY_OPT_MASK) | (opt & PHY_OPT_MASK);
phy_data.opts = get_uint16_t_be(apdu.data);
}
else {
return SW_INCORRECT_P1P2();
}
tmp[PHY_OPTS] = opts >> 8;
tmp[PHY_OPTS + 1] = opts & 0xff;
file_put_data(ef_phy, tmp, sizeof(tmp));
low_flash_available();
if (phy_save() != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
}
}
#endif
#if PICO_RP2350
else if (cmd == CMD_OTP) {
if (apdu.nc < 2) {
return SW_WRONG_LENGTH();
}
uint16_t row = get_uint16_t_be(apdu.data);
bool israw = P2(apdu) == 0x1;
if (apdu.nc == 2) {
if (row > 0xbf && row < 0xf48) {
return SW_WRONG_DATA();
}
if (israw) {
memcpy(res_APDU, otp_buffer_raw(row), apdu.ne);
}
else {
memcpy(res_APDU, otp_buffer(row), apdu.ne);
}
res_APDU_size = apdu.ne;
}
else {
apdu.nc -= 2;
apdu.data += 2;
if (apdu.nc > 1024) {
return SW_WRONG_LENGTH();
}
if (apdu.nc % (israw ? 4 : 2)) {
return SW_WRONG_DATA();
}
uint8_t adata[1024] __attribute__((aligned(4)));
memcpy(adata, apdu.data, apdu.nc);
int ret = 0;
if (israw) {
ret = otp_write_data_raw(row, adata, apdu.nc);
}
else {
ret = otp_write_data(row, adata, apdu.nc);
}
if (ret != 0) {
return SW_EXEC_ERROR();
}
}
}
#endif
#ifdef PICO_PLATFORM
else if (cmd == CMD_REBOOT) {
if (apdu.nc != 0) {
return SW_WRONG_LENGTH();
}
watchdog_reboot(0, 0, 100);
}
#endif
else if (cmd == CMD_MEMORY) {
res_APDU_size = 0;
uint32_t free = flash_free_space(), total = flash_total_space(), used = flash_used_space(), nfiles = flash_num_files(), size = flash_size();
res_APDU_size += put_uint32_t_be(free, res_APDU + res_APDU_size);
res_APDU_size += put_uint32_t_be(used, res_APDU + res_APDU_size);
res_APDU_size += put_uint32_t_be(total, res_APDU + res_APDU_size);
res_APDU_size += put_uint32_t_be(nfiles, res_APDU + res_APDU_size);
res_APDU_size += put_uint32_t_be(size, res_APDU + res_APDU_size);
}
else {
return SW_INCORRECT_P1P2();
}

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"
@@ -22,6 +22,7 @@
#include "oid.h"
#include "eac.h"
#include "files.h"
#include "otp.h"
int cmd_general_authenticate() {
if (P1(apdu) == 0x0 && P2(apdu) == 0x0) {
@@ -47,13 +48,16 @@ int cmd_general_authenticate() {
mbedtls_ecp_keypair ectx;
mbedtls_ecp_keypair_init(&ectx);
r = load_private_key_ecdh(&ectx, fkey);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
mbedtls_ecp_keypair_free(&ectx);
return SW_EXEC_ERROR();
}
mbedtls_ecdh_context ctx;
mbedtls_ecdh_init(&ctx);
mbedtls_ecp_group_id gid = MBEDTLS_ECP_DP_SECP256R1;
if (otp_key_2) {
gid = MBEDTLS_ECP_DP_SECP256K1;
}
r = mbedtls_ecdh_setup(&ctx, gid);
if (r != 0) {
mbedtls_ecp_keypair_free(&ectx);
@@ -106,7 +110,7 @@ int cmd_general_authenticate() {
r = sm_sign(t, pubkey_len + 16, res_APDU + res_APDU_size);
free(t);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
res_APDU_size += 8;

View File

@@ -3,26 +3,27 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "crypto_utils.h"
#include "sc_hsm.h"
#include "crypto_utils.h"
#include "files.h"
#include "random.h"
#include "kek.h"
#include "version.h"
#include "asn1.h"
#include "cvc.h"
#include "otp.h"
extern void scan_all();
@@ -42,10 +43,14 @@ extern void reset_puk_store();
int cmd_initialize() {
if (apdu.nc > 0) {
uint8_t mkek[MKEK_SIZE];
uint16_t opts = get_device_options();
if (opts & HSM_OPT_SECURE_LOCK && !has_mkek_mask) {
return SW_SECURITY_STATUS_NOT_SATISFIED();
}
int ret_mkek = load_mkek(mkek); //Try loading MKEK with previous session
initialize_flash(true);
scan_all();
has_session_pin = has_session_sopin = false;
has_session_pin = has_session_sopin = has_mkek_mask = false;
uint16_t tag = 0x0;
uint8_t *tag_data = NULL, *p = NULL, *kds = NULL, *dkeks = NULL;
uint16_t tag_len = 0;
@@ -132,10 +137,10 @@ int cmd_initialize() {
release_mkek(mkek);
return SW_EXEC_ERROR();
}
if (ret_mkek != CCID_OK) {
if (ret_mkek != PICOKEY_OK) {
ret_mkek = load_mkek(mkek); //Try again with new PIN/SO-PIN just in case some is the same
}
if (store_mkek(ret_mkek == CCID_OK ? mkek : NULL) != CCID_OK) {
if (store_mkek(ret_mkek == PICOKEY_OK ? mkek : NULL) != PICOKEY_OK) {
release_mkek(mkek);
return SW_EXEC_ERROR();
}
@@ -143,31 +148,31 @@ int cmd_initialize() {
if (dkeks) {
if (*dkeks > 0) {
uint16_t d = *dkeks;
if (file_put_data(tf_kd, (const uint8_t *) &d, sizeof(d)) != CCID_OK) {
if (file_put_data(tf_kd, (const uint8_t *) &d, sizeof(d)) != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
}
else {
int r = save_dkek_key(0, random_bytes_get(32));
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
uint16_t d = 0x0101;
if (file_put_data(tf_kd, (const uint8_t *) &d, sizeof(d)) != CCID_OK) {
if (file_put_data(tf_kd, (const uint8_t *) &d, sizeof(d)) != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
}
}
else {
uint16_t d = 0x0000;
if (file_put_data(tf_kd, (const uint8_t *) &d, sizeof(d)) != CCID_OK) {
if (file_put_data(tf_kd, (const uint8_t *) &d, sizeof(d)) != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
}
if (kds) {
uint8_t t[MAX_KEY_DOMAINS * 2], k = MIN(*kds, MAX_KEY_DOMAINS);
memset(t, 0xff, 2 * k);
if (file_put_data(tf_kd, t, 2 * k) != CCID_OK) {
if (file_put_data(tf_kd, t, 2 * k) != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
}
@@ -179,59 +184,60 @@ int cmd_initialize() {
return SW_EXEC_ERROR();
}
int ret = 0;
if (ret_mkek != CCID_OK || !file_has_data(fdkey)) {
if (ret_mkek != PICOKEY_OK || !file_has_data(fdkey)) {
mbedtls_ecdsa_context ecdsa;
mbedtls_ecdsa_init(&ecdsa);
mbedtls_ecp_group_id ec_id = MBEDTLS_ECP_DP_SECP256R1;
uint8_t index = 0, key_id = 0;
ret = mbedtls_ecdsa_genkey(&ecdsa, ec_id, random_gen, &index);
uint8_t key_id = 0;
if (otp_key_2) {
ret = mbedtls_ecp_read_key(MBEDTLS_ECP_DP_SECP256K1, &ecdsa, otp_key_2, 32);
if (ret != 0) {
mbedtls_ecdsa_free(&ecdsa);
return SW_EXEC_ERROR();
}
ret = mbedtls_ecp_mul(&ecdsa.grp, &ecdsa.Q, &ecdsa.d, &ecdsa.grp.G, random_gen, NULL);
}
else {
ret = mbedtls_ecdsa_genkey(&ecdsa, ec_id, random_gen, NULL);
}
if (ret != 0) {
mbedtls_ecdsa_free(&ecdsa);
return SW_EXEC_ERROR();
}
ret = store_keys(&ecdsa, PICO_KEYS_KEY_EC, key_id);
if (ret != CCID_OK) {
if (ret != PICOKEY_OK) {
mbedtls_ecdsa_free(&ecdsa);
return SW_EXEC_ERROR();
}
size_t cvc_len = 0;
if ((cvc_len = asn1_cvc_aut(&ecdsa, PICO_KEYS_KEY_EC, res_APDU, 4096, NULL, 0)) == 0) {
uint16_t ee_len = 0, term_len = 0;
if ((ee_len = asn1_cvc_aut(&ecdsa, PICO_KEYS_KEY_EC, res_APDU, MAX_APDU_DATA, NULL, 0)) == 0) {
mbedtls_ecdsa_free(&ecdsa);
return SW_EXEC_ERROR();
}
file_t *fpk = search_file(EF_EE_DEV);
ret = file_put_data(fpk, res_APDU, (uint16_t)cvc_len);
ret = file_put_data(fpk, res_APDU, ee_len);
if (ret != 0) {
mbedtls_ecdsa_free(&ecdsa);
return SW_EXEC_ERROR();
}
if ((cvc_len = asn1_cvc_cert(&ecdsa, PICO_KEYS_KEY_EC, res_APDU, 4096, NULL, 0, true)) == 0) {
if ((term_len = asn1_cvc_cert(&ecdsa, PICO_KEYS_KEY_EC, res_APDU + ee_len, MAX_APDU_DATA - ee_len, NULL, 0, true)) == 0) {
mbedtls_ecdsa_free(&ecdsa);
return SW_EXEC_ERROR();
}
memcpy(res_APDU + cvc_len, res_APDU, cvc_len);
mbedtls_ecdsa_free(&ecdsa);
fpk = search_file(EF_TERMCA);
ret = file_put_data(fpk, res_APDU, (uint16_t)(2 * cvc_len));
ret = file_put_data(fpk, res_APDU, ee_len + term_len);
if (ret != 0) {
return SW_EXEC_ERROR();
}
const uint8_t *keyid =
(const uint8_t *) "\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0",
const uint8_t *keyid = (const uint8_t *) "\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0",
*label = (const uint8_t *) "ESPICOHSMTR";
uint16_t prkd_len = asn1_build_prkd_ecc(label,
(uint16_t)strlen((const char *) label),
keyid,
20,
256,
res_APDU,
4096);
uint16_t prkd_len = asn1_build_prkd_ecc(label, (uint16_t)strlen((const char *) label), keyid, 20, 256, res_APDU, MAX_APDU_DATA);
fpk = search_file(EF_PRKD_DEV);
ret = file_put_data(fpk, res_APDU, prkd_len);
}
if (ret != 0) {
return SW_EXEC_ERROR();
@@ -241,10 +247,7 @@ int cmd_initialize() {
}
else { //free memory bytes request
int heap_left = heapLeft();
res_APDU[0] = ((heap_left >> 24) & 0xff);
res_APDU[1] = ((heap_left >> 16) & 0xff);
res_APDU[2] = ((heap_left >> 8) & 0xff);
res_APDU[3] = ((heap_left >> 0) & 0xff);
res_APDU_size += put_uint32_t_be(heap_left, res_APDU);
res_APDU[4] = 0;
res_APDU[5] = HSM_VERSION_MAJOR;
res_APDU[6] = HSM_VERSION_MINOR;

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "crypto_utils.h"
@@ -72,8 +72,8 @@ int cmd_key_domain() {
import_dkek_share(p2, apdu.data);
if (++current_dkeks >= dkeks) {
int r = save_dkek_key(p2, NULL);
if (r != CCID_OK) {
if (r == CCID_NO_LOGIN) {
if (r != PICOKEY_OK) {
if (r == PICOKEY_NO_LOGIN) {
pending_save_dkek = p2;
}
else {
@@ -86,7 +86,7 @@ int cmd_key_domain() {
uint8_t t[MAX_KEY_DOMAINS * 2];
memcpy(t, kdata, tf_kd_size);
t[2 * p2 + 1] = current_dkeks;
if (file_put_data(tf_kd, t, tf_kd_size) != CCID_OK) {
if (file_put_data(tf_kd, t, tf_kd_size) != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
low_flash_available();
@@ -129,17 +129,17 @@ int cmd_key_domain() {
else if (p1 == 0x4) {
t[2 * p2 + 1] = current_dkeks = 0;
}
if (file_put_data(tf_kd, t, tf_kd_size) != CCID_OK) {
if (file_put_data(tf_kd, t, tf_kd_size) != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
file_t *tf = NULL;
if ((tf = search_file(EF_DKEK + p2))) {
if (delete_file(tf) != CCID_OK) {
if (delete_file(tf) != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
}
if (p1 == 0x3 && (tf = search_file(EF_XKEK + p2))) {
if (delete_file(tf) != CCID_OK) {
if (delete_file(tf) != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
}

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "crypto_utils.h"
@@ -56,10 +56,10 @@ int cmd_key_gen() {
aes_type = PICO_KEYS_KEY_AES_512;
}
r = store_keys(aes_key, aes_type, key_id);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return SW_MEMORY_FAILURE();
}
if (find_and_store_meta_key(key_id) != CCID_OK) {
if (find_and_store_meta_key(key_id) != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
low_flash_available();

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"
@@ -51,18 +51,18 @@ int cmd_key_unwrap() {
mbedtls_rsa_init(&ctx);
do {
r = dkek_decode_key((uint8_t)++kdom, &ctx, data, data_len, NULL, &allowed, &allowed_len);
} while ((r == CCID_ERR_FILE_NOT_FOUND || r == CCID_WRONG_DKEK) && kdom < MAX_KEY_DOMAINS);
if (r != CCID_OK) {
} while ((r == PICOKEY_ERR_FILE_NOT_FOUND || r == PICOKEY_WRONG_DKEK) && kdom < MAX_KEY_DOMAINS);
if (r != PICOKEY_OK) {
mbedtls_rsa_free(&ctx);
return SW_EXEC_ERROR();
}
r = store_keys(&ctx, PICO_KEYS_KEY_RSA, key_id);
if ((res_APDU_size = (uint16_t)asn1_cvc_aut(&ctx, PICO_KEYS_KEY_RSA, res_APDU, 4096, NULL, 0)) == 0) {
if ((res_APDU_size = (uint16_t)asn1_cvc_aut(&ctx, PICO_KEYS_KEY_RSA, res_APDU, MAX_APDU_DATA, NULL, 0)) == 0) {
mbedtls_rsa_free(&ctx);
return SW_EXEC_ERROR();
}
mbedtls_rsa_free(&ctx);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
}
@@ -71,18 +71,18 @@ int cmd_key_unwrap() {
mbedtls_ecp_keypair_init(&ctx);
do {
r = dkek_decode_key((uint8_t)++kdom, &ctx, data, data_len, NULL, &allowed, &allowed_len);
} while ((r == CCID_ERR_FILE_NOT_FOUND || r == CCID_WRONG_DKEK) && kdom < MAX_KEY_DOMAINS);
if (r != CCID_OK) {
} while ((r == PICOKEY_ERR_FILE_NOT_FOUND || r == PICOKEY_WRONG_DKEK) && kdom < MAX_KEY_DOMAINS);
if (r != PICOKEY_OK) {
mbedtls_ecp_keypair_free(&ctx);
return SW_EXEC_ERROR();
}
r = store_keys(&ctx, PICO_KEYS_KEY_EC, key_id);
if ((res_APDU_size = (uint16_t)asn1_cvc_aut(&ctx, PICO_KEYS_KEY_EC, res_APDU, 4096, NULL, 0)) == 0) {
if ((res_APDU_size = (uint16_t)asn1_cvc_aut(&ctx, PICO_KEYS_KEY_EC, res_APDU, MAX_APDU_DATA, NULL, 0)) == 0) {
mbedtls_ecp_keypair_free(&ctx);
return SW_EXEC_ERROR();
}
mbedtls_ecp_keypair_free(&ctx);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
}
@@ -97,8 +97,8 @@ int cmd_key_unwrap() {
&key_size,
&allowed,
&allowed_len);
} while ((r == CCID_ERR_FILE_NOT_FOUND || r == CCID_WRONG_DKEK) && kdom < MAX_KEY_DOMAINS);
if (r != CCID_OK) {
} while ((r == PICOKEY_ERR_FILE_NOT_FOUND || r == PICOKEY_WRONG_DKEK) && kdom < MAX_KEY_DOMAINS);
if (r != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
if (key_size == 64) {
@@ -117,7 +117,7 @@ int cmd_key_unwrap() {
return SW_EXEC_ERROR();
}
r = store_keys(aes_key, aes_type, key_id);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
}
@@ -136,7 +136,7 @@ int cmd_key_unwrap() {
}
r = meta_add((KEY_PREFIX << 8) | key_id, meta, meta_len);
free(meta);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return r;
}
}

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "crypto_utils.h"
@@ -60,9 +60,9 @@ int cmd_key_wrap() {
mbedtls_rsa_context ctx;
mbedtls_rsa_init(&ctx);
r = load_private_key_rsa(&ctx, ef);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
mbedtls_rsa_free(&ctx);
if (r == CCID_VERIFICATION_FAILED) {
if (r == PICOKEY_VERIFICATION_FAILED) {
return SW_SECURE_MESSAGE_EXEC_ERROR();
}
return SW_EXEC_ERROR();
@@ -74,9 +74,9 @@ int cmd_key_wrap() {
mbedtls_ecp_keypair ctx;
mbedtls_ecp_keypair_init(&ctx);
r = load_private_key_ec(&ctx, ef);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
mbedtls_ecp_keypair_free(&ctx);
if (r == CCID_VERIFICATION_FAILED) {
if (r == PICOKEY_VERIFICATION_FAILED) {
return SW_SECURE_MESSAGE_EXEC_ERROR();
}
return SW_EXEC_ERROR();
@@ -110,7 +110,7 @@ int cmd_key_wrap() {
r = dkek_encode_key(kdom, kdata_aes, aes_type, res_APDU, &wrap_len, meta_tag, tag_len);
mbedtls_platform_zeroize(kdata_aes, sizeof(kdata_aes));
}
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
res_APDU_size = wrap_len;

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "crypto_utils.h"
@@ -47,9 +47,6 @@ int cmd_keypair_gen() {
if (asn1_find_tag(&ctxo, 0x2, &ks) && asn1_len(&ks) > 0) {
key_size = asn1_get_uint(&ks);
}
printf("KEYPAIR RSA %lu (%lx)\n",
(unsigned long) key_size,
(unsigned long) exponent);
mbedtls_rsa_context rsa;
mbedtls_rsa_init(&rsa);
uint8_t index = 0;
@@ -58,12 +55,11 @@ int cmd_keypair_gen() {
mbedtls_rsa_free(&rsa);
return SW_EXEC_ERROR();
}
if ((res_APDU_size =
(uint16_t)asn1_cvc_aut(&rsa, PICO_KEYS_KEY_RSA, res_APDU, 4096, NULL, 0)) == 0) {
if ((res_APDU_size = (uint16_t)asn1_cvc_aut(&rsa, PICO_KEYS_KEY_RSA, res_APDU, MAX_APDU_DATA, NULL, 0)) == 0) {
return SW_EXEC_ERROR();
}
ret = store_keys(&rsa, PICO_KEYS_KEY_RSA, key_id);
if (ret != CCID_OK) {
if (ret != PICOKEY_OK) {
mbedtls_rsa_free(&rsa);
return SW_EXEC_ERROR();
}
@@ -75,7 +71,6 @@ int cmd_keypair_gen() {
return SW_WRONG_DATA();
}
mbedtls_ecp_group_id ec_id = ec_get_curve_from_prime(prime.data, prime.len);
printf("KEYPAIR ECC %d\n", ec_id);
if (ec_id == MBEDTLS_ECP_DP_NONE) {
return SW_FUNC_NOT_SUPPORTED();
}
@@ -84,14 +79,15 @@ int cmd_keypair_gen() {
if (asn1_find_tag(&ctxo, 0x83, &g) != true) {
return SW_WRONG_DATA();
}
#ifdef MBEDTLS_EDDSA_C
if (ec_id == MBEDTLS_ECP_DP_CURVE25519 && (g.data[0] != 9)) {
ec_id = MBEDTLS_ECP_DP_ED25519;
}
else if (ec_id == MBEDTLS_ECP_DP_CURVE448 && (g.len != 56 || g.data[0] != 5)) {
ec_id = MBEDTLS_ECP_DP_ED448;
}
#endif
}
printf("KEYPAIR ECC %d\r\n", ec_id);
mbedtls_ecdsa_context ecdsa;
mbedtls_ecdsa_init(&ecdsa);
uint8_t index = 0;
@@ -131,8 +127,7 @@ int cmd_keypair_gen() {
}
}
}
if ((res_APDU_size =
(uint16_t)asn1_cvc_aut(&ecdsa, PICO_KEYS_KEY_EC, res_APDU, 4096, ext.data, ext.len)) == 0) {
if ((res_APDU_size = (uint16_t)asn1_cvc_aut(&ecdsa, PICO_KEYS_KEY_EC, res_APDU, MAX_APDU_DATA, ext.data, ext.len)) == 0) {
if (ext.data) {
free(ext.data);
}
@@ -144,7 +139,7 @@ int cmd_keypair_gen() {
}
ret = store_keys(&ecdsa, PICO_KEYS_KEY_EC, key_id);
mbedtls_ecdsa_free(&ecdsa);
if (ret != CCID_OK) {
if (ret != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
}
@@ -154,7 +149,7 @@ int cmd_keypair_gen() {
else {
return SW_WRONG_DATA();
}
if (find_and_store_meta_key(key_id) != CCID_OK) {
if (find_and_store_meta_key(key_id) != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
file_t *fpk = file_new((EE_CERTIFICATE_PREFIX << 8) | key_id);

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"
@@ -22,12 +22,10 @@ int cmd_list_keys() {
/* First we send DEV private key */
/* Both below conditions should be always TRUE */
if (search_file(EF_PRKD_DEV)) {
res_APDU[res_APDU_size++] = EF_PRKD_DEV >> 8;
res_APDU[res_APDU_size++] = EF_PRKD_DEV & 0xff;
res_APDU_size += put_uint16_t_be(EF_PRKD_DEV, res_APDU + res_APDU_size);
}
if (search_file(EF_KEY_DEV)) {
res_APDU[res_APDU_size++] = EF_KEY_DEV >> 8;
res_APDU[res_APDU_size++] = EF_KEY_DEV & 0xff;
res_APDU_size += put_uint16_t_be(EF_KEY_DEV, res_APDU + res_APDU_size);
}
//first CC
for (int i = 0; i < dynamic_files; i++) {

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"
@@ -51,7 +51,7 @@ int cmd_mse() {
}
else {
if (p2 == 0xB6) {
if (puk_store_select_chr(tag_data) == CCID_OK) {
if (puk_store_select_chr(tag_data) == PICOKEY_OK) {
return SW_OK();
}
}

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"
@@ -40,11 +40,11 @@ int cmd_pso() {
apdu.nc += tlv_len;
}
int r = cvc_verify(apdu.data, (uint16_t)apdu.nc, current_puk->cvcert, current_puk->cvcert_len);
if (r != CCID_OK) {
if (r == CCID_WRONG_DATA) {
if (r != PICOKEY_OK) {
if (r == PICOKEY_WRONG_DATA) {
return SW_DATA_INVALID();
}
else if (r == CCID_WRONG_SIGNATURE) {
else if (r == PICOKEY_WRONG_SIGNATURE) {
return SW_CONDITIONS_NOT_SATISFIED();
}
return SW_EXEC_ERROR();
@@ -56,7 +56,7 @@ int cmd_pso() {
ca_ef = file_new(fid);
file_put_data(ca_ef, apdu.data, (uint16_t)apdu.nc);
if (add_cert_puk_store(file_get_data(ca_ef), file_get_size(ca_ef),
false) != CCID_OK) {
false) != PICOKEY_OK) {
return SW_FILE_FULL();
}

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"
@@ -30,7 +30,7 @@ int cmd_read_binary() {
offset = p2;
}
else {
offset = make_uint16_t(p1, p2) & 0x7fff;
offset = make_uint16_t_be(p1, p2) & 0x7fff;
ef = currentEF;
}
}
@@ -41,7 +41,7 @@ int cmd_read_binary() {
}
}
else {
uint16_t file_id = make_uint16_t(p1, p2); // & 0x7fff;
uint16_t file_id = make_uint16_t_be(p1, p2); // & 0x7fff;
if (file_id == 0x0) {
ef = currentEF;
}

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "crypto_utils.h"
@@ -59,19 +59,19 @@ int cmd_reset_retry() {
dhash[0] = newpin_len;
double_hash_pin(apdu.data + (apdu.nc - newpin_len), newpin_len, dhash + 1);
file_put_data(file_pin1, dhash, sizeof(dhash));
if (pin_reset_retries(file_pin1, true) != CCID_OK) {
if (pin_reset_retries(file_pin1, true) != PICOKEY_OK) {
return SW_MEMORY_FAILURE();
}
uint8_t mkek[MKEK_SIZE];
int r = load_mkek(mkek); //loads the MKEK with SO pin
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
hash_multi(apdu.data + (apdu.nc - newpin_len), newpin_len, session_pin);
has_session_pin = true;
r = store_mkek(mkek);
release_mkek(mkek);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return SW_EXEC_ERROR();
}
low_flash_available();
@@ -99,7 +99,7 @@ int cmd_reset_retry() {
return SW_WRONG_LENGTH();
}
}
if (pin_reset_retries(file_pin1, true) != CCID_OK) {
if (pin_reset_retries(file_pin1, true) != PICOKEY_OK) {
return SW_MEMORY_FAILURE();
}
return SW_OK();

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"
@@ -48,7 +48,7 @@ int cmd_select() {
//}
if (apdu.nc == 2) {
fid = get_uint16_t(apdu.data, 0);
fid = get_uint16_t_be(apdu.data);
}
//if ((fid & 0xff00) == (KEY_PREFIX << 8))
@@ -119,8 +119,7 @@ int cmd_select() {
res_APDU[res_APDU_size++] = 0x85;
res_APDU[res_APDU_size++] = 5;
uint16_t opts = get_device_options();
res_APDU[res_APDU_size++] = opts >> 8;
res_APDU[res_APDU_size++] = opts & 0xff;
res_APDU_size += put_uint16_t_be(opts, res_APDU + res_APDU_size);
res_APDU[res_APDU_size++] = 0xFF;
res_APDU[res_APDU_size++] = HSM_VERSION_MAJOR;
res_APDU[res_APDU_size++] = HSM_VERSION_MINOR;

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"
#include "crypto_utils.h"
@@ -20,7 +20,9 @@
#include "asn1.h"
#include "mbedtls/oid.h"
#include "random.h"
#ifdef MBEDTLS_EDDSA_C
#include "mbedtls/eddsa.h"
#endif
extern mbedtls_ecp_keypair hd_context;
extern uint8_t hd_keytype;
@@ -83,17 +85,17 @@ int pkcs1_strip_digest_info_prefix(mbedtls_md_type_t *algorithm,
*algorithm = digest_info_prefix[i].algorithm;
}
if (out_dat == NULL) {
return CCID_OK;
return PICOKEY_OK;
}
if (*out_len < hash_len) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
memmove(out_dat, in_dat + hdr_len, hash_len);
*out_len = hash_len;
return CCID_OK;
return PICOKEY_OK;
}
}
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
//-----
@@ -143,9 +145,9 @@ int cmd_signature() {
mbedtls_rsa_init(&ctx);
int r = load_private_key_rsa(&ctx, fkey);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
mbedtls_rsa_free(&ctx);
if (r == CCID_VERIFICATION_FAILED) {
if (r == PICOKEY_VERIFICATION_FAILED) {
return SW_SECURE_MESSAGE_EXEC_ERROR();
}
return SW_EXEC_ERROR();
@@ -154,7 +156,7 @@ int cmd_signature() {
if (p2 == ALGO_RSA_PKCS1) { //DigestInfo attached
uint16_t nc = (uint16_t)apdu.nc;
if (pkcs1_strip_digest_info_prefix(&md, apdu.data, (uint16_t)apdu.nc, apdu.data,
&nc) != CCID_OK) { //gets the MD algo id and strips it off
&nc) != PICOKEY_OK) { //gets the MD algo id and strips it off
return SW_EXEC_ERROR();
}
apdu.nc = nc;
@@ -265,19 +267,22 @@ int cmd_signature() {
md = MBEDTLS_MD_SHA512;
}
int r = load_private_key_ec(&ctx, fkey);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
mbedtls_ecp_keypair_free(&ctx);
if (r == CCID_VERIFICATION_FAILED) {
if (r == PICOKEY_VERIFICATION_FAILED) {
return SW_SECURE_MESSAGE_EXEC_ERROR();
}
return SW_EXEC_ERROR();
}
size_t olen = 0;
uint8_t buf[MBEDTLS_ECDSA_MAX_LEN];
#ifdef MBEDTLS_EDDSA_C
if (ctx.grp.id == MBEDTLS_ECP_DP_ED25519 || ctx.grp.id == MBEDTLS_ECP_DP_ED448) {
r = mbedtls_eddsa_write_signature(&ctx, apdu.data, apdu.nc, buf, sizeof(buf), &olen, MBEDTLS_EDDSA_PURE, NULL, 0, random_gen, NULL);
}
else {
else
#endif
{
r = mbedtls_ecdsa_write_signature(&ctx, md, apdu.data, apdu.nc, buf, MBEDTLS_ECDSA_MAX_LEN,
&olen, random_gen, NULL);
}
@@ -293,23 +298,23 @@ int cmd_signature() {
size_t olen = 0;
uint8_t buf[MBEDTLS_ECDSA_MAX_LEN] = {0};
if (hd_context.grp.id == MBEDTLS_ECP_DP_NONE) {
mbedtls_ecdsa_free(&hd_context);
mbedtls_ecp_keypair_free(&hd_context);
return SW_CONDITIONS_NOT_SATISFIED();
}
if (hd_keytype != 0x1 && hd_keytype != 0x2) {
mbedtls_ecdsa_free(&hd_context);
mbedtls_ecp_keypair_free(&hd_context);
return SW_INCORRECT_PARAMS();
}
md = MBEDTLS_MD_SHA256;
if (mbedtls_ecdsa_write_signature(&hd_context, md, apdu.data, apdu.nc, buf,
MBEDTLS_ECDSA_MAX_LEN,
&olen, random_gen, NULL) != 0) {
mbedtls_ecdsa_free(&hd_context);
mbedtls_ecp_keypair_free(&hd_context);
return SW_EXEC_ERROR();
}
memcpy(res_APDU, buf, olen);
res_APDU_size = (uint16_t)olen;
mbedtls_ecdsa_free(&hd_context);
mbedtls_ecp_keypair_free(&hd_context);
hd_keytype = 0;
}
else {

View File

@@ -78,7 +78,7 @@ int cmd_update_ef() {
}
if (offset == 0) {
int r = file_put_data(ef, data, data_len);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return SW_MEMORY_FAILURE();
}
}
@@ -92,7 +92,7 @@ int cmd_update_ef() {
memcpy(data_merge + offset, data, data_len);
int r = file_put_data(ef, data_merge, offset + data_len);
free(data_merge);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return SW_MEMORY_FAILURE();
}
}

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"
@@ -59,8 +59,5 @@ int cmd_verify() {
}
return set_res_sw(0x63, 0xc0 | file_read_uint8(file_retries_sopin));
}
else if (p2 == 0x85) {
return SW_OK();
}
return SW_REFERENCE_NOT_FOUND();
}

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"
@@ -26,7 +26,9 @@
#include "oid.h"
#include "mbedtls/md.h"
#include "files.h"
#ifdef MBEDTLS_EDDSA_C
#include "mbedtls/eddsa.h"
#endif
extern const uint8_t *dev_name;
extern uint16_t dev_name_len;
@@ -89,7 +91,11 @@ uint16_t asn1_cvc_public_key_ecdsa(mbedtls_ecp_keypair *ecdsa, uint8_t *buf, uin
uint16_t ctot_size = asn1_len_tag(0x87, (uint16_t)c_size);
uint16_t oid_len = asn1_len_tag(0x6, sizeof(oid_ecdsa));
uint16_t tot_len = 0, tot_data_len = 0;
if (mbedtls_ecp_get_type(&ecdsa->grp) == MBEDTLS_ECP_TYPE_MONTGOMERY || mbedtls_ecp_get_type(&ecdsa->grp) == MBEDTLS_ECP_TYPE_EDWARDS) {
if (mbedtls_ecp_get_type(&ecdsa->grp) == MBEDTLS_ECP_TYPE_MONTGOMERY
#ifdef MBEDTLS_EDDSA_C
|| mbedtls_ecp_get_type(&ecdsa->grp) == MBEDTLS_ECP_TYPE_EDWARDS
#endif
) {
tot_data_len = oid_len + ptot_size + otot_size + gtot_size + ytot_size;
oid = oid_ri;
}
@@ -110,7 +116,11 @@ uint16_t asn1_cvc_public_key_ecdsa(mbedtls_ecp_keypair *ecdsa, uint8_t *buf, uin
//oid
*p++ = 0x6; p += format_tlv_len(sizeof(oid_ecdsa), p); memcpy(p, oid, sizeof(oid_ecdsa));
p += sizeof(oid_ecdsa);
if (mbedtls_ecp_get_type(&ecdsa->grp) == MBEDTLS_ECP_TYPE_MONTGOMERY || mbedtls_ecp_get_type(&ecdsa->grp) == MBEDTLS_ECP_TYPE_EDWARDS) {
if (mbedtls_ecp_get_type(&ecdsa->grp) == MBEDTLS_ECP_TYPE_MONTGOMERY
#ifdef MBEDTLS_EDDSA_C
|| mbedtls_ecp_get_type(&ecdsa->grp) == MBEDTLS_ECP_TYPE_EDWARDS
#endif
) {
//p
*p++ = 0x81; p += format_tlv_len((uint16_t)p_size, p); mbedtls_mpi_write_binary(&ecdsa->grp.P, p, p_size);
p += p_size;
@@ -297,10 +307,13 @@ uint16_t asn1_cvc_cert(void *rsa_ecdsa,
mbedtls_ecp_keypair *ecdsa = (mbedtls_ecp_keypair *) rsa_ecdsa;
mbedtls_mpi_init(&r);
mbedtls_mpi_init(&s);
#ifdef MBEDTLS_EDDSA_C
if (ecdsa->grp.id == MBEDTLS_ECP_DP_ED25519 || ecdsa->grp.id == MBEDTLS_ECP_DP_ED448) {
ret = mbedtls_eddsa_sign(&ecdsa->grp, &r, &s, &ecdsa->d, body, body_size, MBEDTLS_EDDSA_PURE, NULL, 0, random_gen, NULL);
}
else {
else
#endif
{
ret = mbedtls_ecdsa_sign(&ecdsa->grp, &r, &s, &ecdsa->d, hsh, sizeof(hsh), random_gen, NULL);
}
if (ret == 0) {
@@ -333,7 +346,7 @@ uint16_t asn1_cvc_aut(void *rsa_ecdsa,
}
mbedtls_ecp_keypair ectx;
mbedtls_ecp_keypair_init(&ectx);
if (load_private_key_ec(&ectx, fkey) != CCID_OK) {
if (load_private_key_ec(&ectx, fkey) != PICOKEY_OK) {
mbedtls_ecp_keypair_free(&ectx);
return 0;
}
@@ -359,10 +372,13 @@ uint16_t asn1_cvc_aut(void *rsa_ecdsa,
mbedtls_mpi r, s;
mbedtls_mpi_init(&r);
mbedtls_mpi_init(&s);
#ifdef MBEDTLS_EDDSA_C
if (ectx.grp.id == MBEDTLS_ECP_DP_ED25519 || ectx.grp.id == MBEDTLS_ECP_DP_ED448) {
ret = mbedtls_eddsa_sign(&ectx.grp, &r, &s, &ectx.d, body, cvcert_size + outcar_size, MBEDTLS_EDDSA_PURE, NULL, 0, random_gen, NULL);
}
else {
else
#endif
{
uint8_t hsh[32];
hash256(body, cvcert_size + outcar_size, hsh);
ret = mbedtls_ecdsa_sign(&ectx.grp, &r, &s, &ectx.d, hsh, sizeof(hsh), random_gen, NULL);
@@ -431,8 +447,7 @@ uint16_t asn1_build_cert_description(const uint8_t *label,
p += format_tlv_len(asn1_len_tag(0x4, sizeof(uint16_t)), p);
*p++ = 0x4;
p += format_tlv_len(sizeof(uint16_t), p);
*p++ = fid >> 8;
*p++ = fid & 0xff;
put_uint16_t_be(fid, p); p += sizeof(uint16_t);
return (uint16_t)(p - buf);
}
@@ -508,8 +523,7 @@ uint16_t asn1_build_prkd_generic(const uint8_t *label,
p += format_tlv_len(asn1_len_tag(0x2, 2), p);
*p++ = 0x2;
p += format_tlv_len(2, p);
*p++ = (keysize >> 8) & 0xff;
*p++ = keysize & 0xff;
p += put_uint16_t_be(keysize, p);
}
//Seq 4
@@ -528,8 +542,7 @@ uint16_t asn1_build_prkd_generic(const uint8_t *label,
if (key_type & PICO_KEYS_KEY_EC || key_type & PICO_KEYS_KEY_RSA) {
*p++ = 0x2;
p += format_tlv_len(2, p);
*p++ = (keysize >> 8) & 0xff;
*p++ = keysize & 0xff;
p += put_uint16_t_be(keysize, p);
}
return (uint16_t)(p - buf);
}
@@ -702,12 +715,12 @@ int puk_verify(const uint8_t *sig,
uint16_t puk_len = 0;
const uint8_t *puk = cvc_get_pub(ca, ca_len, &puk_len);
if (!puk) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
uint16_t oid_len = 0;
const uint8_t *oid = cvc_get_field(puk, puk_len, &oid_len, 0x6);
if (!oid) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
if (memcmp(oid, OID_ID_TA_RSA, 9) == 0) { //RSA
uint16_t t81_len = 0, t82_len = 0;
@@ -716,7 +729,7 @@ int puk_verify(const uint8_t *sig,
&t81_len,
0x82);
if (!t81 || !t82) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
mbedtls_rsa_context rsa;
mbedtls_rsa_init(&rsa);
@@ -744,32 +757,32 @@ int puk_verify(const uint8_t *sig,
}
if (md == MBEDTLS_MD_NONE) {
mbedtls_rsa_free(&rsa);
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
int r = mbedtls_mpi_read_binary(&rsa.N, t81, t81_len);
if (r != 0) {
mbedtls_rsa_free(&rsa);
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
r = mbedtls_mpi_read_binary(&rsa.E, t82, t82_len);
if (r != 0) {
mbedtls_rsa_free(&rsa);
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
r = mbedtls_rsa_complete(&rsa);
if (r != 0) {
mbedtls_rsa_free(&rsa);
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
r = mbedtls_rsa_check_pubkey(&rsa);
if (r != 0) {
mbedtls_rsa_free(&rsa);
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
r = mbedtls_rsa_pkcs1_verify(&rsa, md, (unsigned int)hash_len, hash, sig);
mbedtls_rsa_free(&rsa);
if (r != 0) {
return CCID_WRONG_SIGNATURE;
return PICOKEY_WRONG_SIGNATURE;
}
}
else if (memcmp(oid, OID_ID_TA_ECDSA, 9) == 0) { //ECC
@@ -790,34 +803,34 @@ int puk_verify(const uint8_t *sig,
md = MBEDTLS_MD_SHA512;
}
if (md == MBEDTLS_MD_NONE) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
uint16_t t86_len = 0;
const uint8_t *t86 = cvc_get_field(puk, puk_len, &t86_len, 0x86);
if (!t86) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
mbedtls_ecp_group_id ec_id = cvc_inherite_ec_group(ca, ca_len);
if (ec_id == MBEDTLS_ECP_DP_NONE) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
mbedtls_ecdsa_context ecdsa;
mbedtls_ecdsa_init(&ecdsa);
int ret = mbedtls_ecp_group_load(&ecdsa.grp, ec_id);
if (ret != 0) {
mbedtls_ecdsa_free(&ecdsa);
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
ret = mbedtls_ecp_point_read_binary(&ecdsa.grp, &ecdsa.Q, t86, t86_len);
if (ret != 0) {
mbedtls_ecdsa_free(&ecdsa);
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
ret = mbedtls_ecp_check_pubkey(&ecdsa.grp, &ecdsa.Q);
if (ret != 0) {
mbedtls_ecdsa_free(&ecdsa);
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
mbedtls_mpi r, s;
mbedtls_mpi_init(&r);
@@ -827,44 +840,44 @@ int puk_verify(const uint8_t *sig,
mbedtls_mpi_free(&r);
mbedtls_mpi_free(&s);
mbedtls_ecdsa_free(&ecdsa);
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
ret = mbedtls_mpi_read_binary(&s, sig + sig_len / 2, sig_len / 2);
if (ret != 0) {
mbedtls_mpi_free(&r);
mbedtls_mpi_free(&s);
mbedtls_ecdsa_free(&ecdsa);
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
ret = mbedtls_ecdsa_verify(&ecdsa.grp, hash, hash_len, &ecdsa.Q, &r, &s);
mbedtls_mpi_free(&r);
mbedtls_mpi_free(&s);
mbedtls_ecdsa_free(&ecdsa);
if (ret != 0) {
return CCID_WRONG_SIGNATURE;
return PICOKEY_WRONG_SIGNATURE;
}
}
return CCID_OK;
return PICOKEY_OK;
}
int cvc_verify(const uint8_t *cert, uint16_t cert_len, const uint8_t *ca, uint16_t ca_len) {
uint16_t puk_len = 0;
const uint8_t *puk = cvc_get_pub(ca, ca_len, &puk_len);
if (!puk) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
uint16_t oid_len = 0, cv_body_len = 0, sig_len = 0;
const uint8_t *oid = cvc_get_field(puk, puk_len, &oid_len, 0x6);
const uint8_t *cv_body = cvc_get_body(cert, cert_len, &cv_body_len);
const uint8_t *sig = cvc_get_sig(cert, cert_len, &sig_len);
if (!sig) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
if (!cv_body) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
if (!oid) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
mbedtls_md_type_t md = MBEDTLS_MD_NONE;
if (memcmp(oid, OID_ID_TA_RSA, 9) == 0) { //RSA
@@ -905,18 +918,18 @@ int cvc_verify(const uint8_t *cert, uint16_t cert_len, const uint8_t *ca, uint16
}
}
if (md == MBEDTLS_MD_NONE) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md);
uint8_t hash[64], hash_len = mbedtls_md_get_size(md_info);
uint8_t tlv_body = 2 + format_tlv_len(cv_body_len, NULL);
int r = mbedtls_md(md_info, cv_body - tlv_body, cv_body_len + tlv_body, hash);
if (r != 0) {
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
r = puk_verify(sig, sig_len, hash, hash_len, ca, ca_len);
if (r != 0) {
return CCID_WRONG_SIGNATURE;
return PICOKEY_WRONG_SIGNATURE;
}
return CCID_OK;
return PICOKEY_OK;
}

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef _CVC_H_

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "files.h"
@@ -61,7 +61,7 @@ file_t file_entries[] = {
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //retries PIN (SOPIN)
/* 15 */ { .fid = EF_DEVOPS, .parent = 5, .name = NULL,
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH | FILE_PERSISTENT, .data = NULL,
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //Device options
/* 16 */ { .fid = EF_PRKDFS, .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF,
.data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.PrKDFs

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"
@@ -29,6 +29,7 @@
#include "mbedtls/ecdsa.h"
#include "mbedtls/chachapoly.h"
#include "files.h"
#include "otp.h"
extern bool has_session_pin, has_session_sopin;
extern uint8_t session_pin[32], session_sopin[32];
@@ -36,22 +37,17 @@ uint8_t mkek_mask[MKEK_KEY_SIZE];
bool has_mkek_mask = false;
uint8_t pending_save_dkek = 0xff;
#define POLY 0xedb88320
uint32_t crc32c(const uint8_t *buf, size_t len) {
uint32_t crc = 0xffffffff;
while (len--) {
crc ^= *buf++;
for (int k = 0; k < 8; k++) {
crc = (crc >> 1) ^ (POLY & (0 - (crc & 1)));
void mkek_masked(uint8_t *mkek, const uint8_t *mask) {
if (mask) {
for (int i = 0; i < MKEK_KEY_SIZE; i++) {
MKEK_KEY(mkek)[i] ^= mask[i];
}
}
return ~crc;
}
int load_mkek(uint8_t *mkek) {
if (has_session_pin == false && has_session_sopin == false) {
return CCID_NO_LOGIN;
return PICOKEY_NO_LOGIN;
}
const uint8_t *pin = NULL;
if (pin == NULL && has_session_pin == true) {
@@ -69,23 +65,24 @@ int load_mkek(uint8_t *mkek) {
}
}
if (pin == NULL) { //Should never happen
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
if (has_mkek_mask) {
for (int i = 0; i < MKEK_KEY_SIZE; i++) {
MKEK_KEY(mkek)[i] ^= mkek_mask[i];
}
mkek_masked(mkek, mkek_mask);
}
int ret =
aes_decrypt_cfb_256(pin, MKEK_IV(mkek), MKEK_KEY(mkek), MKEK_KEY_SIZE + MKEK_KEY_CS_SIZE);
int ret = aes_decrypt_cfb_256(pin, MKEK_IV(mkek), MKEK_KEY(mkek), MKEK_KEY_SIZE + MKEK_KEY_CS_SIZE);
if (ret != 0) {
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
if (crc32c(MKEK_KEY(mkek), MKEK_KEY_SIZE) != *(uint32_t *) MKEK_CHECKSUM(mkek)) {
return CCID_WRONG_DKEK;
return PICOKEY_WRONG_DKEK;
}
return CCID_OK;
if (otp_key_1) {
mkek_masked(mkek, otp_key_1);
}
return PICOKEY_OK;
}
mse_t mse = { .init = false };
@@ -94,14 +91,7 @@ int mse_decrypt_ct(uint8_t *data, size_t len) {
mbedtls_chachapoly_context chatx;
mbedtls_chachapoly_init(&chatx);
mbedtls_chachapoly_setkey(&chatx, mse.key_enc + 12);
int ret = mbedtls_chachapoly_auth_decrypt(&chatx,
len - 16,
mse.key_enc,
mse.Qpt,
65,
data + len - 16,
data,
data);
int ret = mbedtls_chachapoly_auth_decrypt(&chatx, len - 16, mse.key_enc, mse.Qpt, 65, data + len - 16, data, data);
mbedtls_chachapoly_free(&chatx);
return ret;
}
@@ -109,7 +99,7 @@ int mse_decrypt_ct(uint8_t *data, size_t len) {
int load_dkek(uint8_t id, uint8_t *dkek) {
file_t *tf = search_file(EF_DKEK + id);
if (!file_has_data(tf)) {
return CCID_ERR_FILE_NOT_FOUND;
return PICOKEY_ERR_FILE_NOT_FOUND;
}
memcpy(dkek, file_get_data(tf), DKEK_KEY_SIZE);
return mkek_decrypt(dkek, DKEK_KEY_SIZE);
@@ -121,7 +111,7 @@ void release_mkek(uint8_t *mkek) {
int store_mkek(const uint8_t *mkek) {
if (has_session_pin == false && has_session_sopin == false) {
return CCID_NO_LOGIN;
return PICOKEY_NO_LOGIN;
}
uint8_t tmp_mkek[MKEK_SIZE];
if (mkek == NULL) {
@@ -131,6 +121,9 @@ int store_mkek(const uint8_t *mkek) {
else {
memcpy(tmp_mkek, mkek, MKEK_SIZE);
}
if (otp_key_1) {
mkek_masked(tmp_mkek, otp_key_1);
}
*(uint32_t *) MKEK_CHECKSUM(tmp_mkek) = crc32c(MKEK_KEY(tmp_mkek), MKEK_KEY_SIZE);
if (has_session_pin) {
uint8_t tmp_mkek_pin[MKEK_SIZE];
@@ -139,12 +132,9 @@ int store_mkek(const uint8_t *mkek) {
if (!tf) {
release_mkek(tmp_mkek);
release_mkek(tmp_mkek_pin);
return CCID_ERR_FILE_NOT_FOUND;
return PICOKEY_ERR_FILE_NOT_FOUND;
}
aes_encrypt_cfb_256(session_pin,
MKEK_IV(tmp_mkek_pin),
MKEK_KEY(tmp_mkek_pin),
MKEK_KEY_SIZE + MKEK_KEY_CS_SIZE);
aes_encrypt_cfb_256(session_pin, MKEK_IV(tmp_mkek_pin), MKEK_KEY(tmp_mkek_pin), MKEK_KEY_SIZE + MKEK_KEY_CS_SIZE);
file_put_data(tf, tmp_mkek_pin, MKEK_SIZE);
release_mkek(tmp_mkek_pin);
}
@@ -155,32 +145,29 @@ int store_mkek(const uint8_t *mkek) {
if (!tf) {
release_mkek(tmp_mkek);
release_mkek(tmp_mkek_sopin);
return CCID_ERR_FILE_NOT_FOUND;
return PICOKEY_ERR_FILE_NOT_FOUND;
}
aes_encrypt_cfb_256(session_sopin,
MKEK_IV(tmp_mkek_sopin),
MKEK_KEY(tmp_mkek_sopin),
MKEK_KEY_SIZE + MKEK_KEY_CS_SIZE);
aes_encrypt_cfb_256(session_sopin, MKEK_IV(tmp_mkek_sopin), MKEK_KEY(tmp_mkek_sopin), MKEK_KEY_SIZE + MKEK_KEY_CS_SIZE);
file_put_data(tf, tmp_mkek_sopin, MKEK_SIZE);
release_mkek(tmp_mkek_sopin);
}
low_flash_available();
release_mkek(tmp_mkek);
return CCID_OK;
return PICOKEY_OK;
}
int store_dkek_key(uint8_t id, uint8_t *dkek) {
file_t *tf = search_file(EF_DKEK + id);
if (!tf) {
return CCID_ERR_FILE_NOT_FOUND;
return PICOKEY_ERR_FILE_NOT_FOUND;
}
int r = mkek_encrypt(dkek, DKEK_KEY_SIZE);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return r;
}
file_put_data(tf, dkek, DKEK_KEY_SIZE);
low_flash_available();
return CCID_OK;
return PICOKEY_OK;
}
int save_dkek_key(uint8_t id, const uint8_t *key) {
@@ -188,7 +175,7 @@ int save_dkek_key(uint8_t id, const uint8_t *key) {
if (!key) {
file_t *tf = search_file(EF_DKEK + id);
if (!tf) {
return CCID_ERR_FILE_NOT_FOUND;
return PICOKEY_ERR_FILE_NOT_FOUND;
}
memcpy(dkek, file_get_data(tf), DKEK_KEY_SIZE);
}
@@ -202,7 +189,7 @@ int import_dkek_share(uint8_t id, const uint8_t *share) {
uint8_t tmp_dkek[DKEK_KEY_SIZE];
file_t *tf = search_file(EF_DKEK + id);
if (!tf) {
return CCID_ERR_FILE_NOT_FOUND;
return PICOKEY_ERR_FILE_NOT_FOUND;
}
memset(tmp_dkek, 0, sizeof(tmp_dkek));
if (file_get_size(tf) == DKEK_KEY_SIZE) {
@@ -213,7 +200,7 @@ int import_dkek_share(uint8_t id, const uint8_t *share) {
}
file_put_data(tf, tmp_dkek, DKEK_KEY_SIZE);
low_flash_available();
return CCID_OK;
return PICOKEY_OK;
}
int dkek_kcv(uint8_t id, uint8_t *kcv) { //kcv 8 bytes
@@ -221,45 +208,45 @@ int dkek_kcv(uint8_t id, uint8_t *kcv) { //kcv 8 bytes
memset(kcv, 0, 8);
memset(hsh, 0, sizeof(hsh));
int r = load_dkek(id, dkek);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return r;
}
hash256(dkek, DKEK_KEY_SIZE, hsh);
mbedtls_platform_zeroize(dkek, sizeof(dkek));
memcpy(kcv, hsh, 8);
return CCID_OK;
return PICOKEY_OK;
}
int dkek_kenc(uint8_t id, uint8_t *kenc) { //kenc 32 bytes
uint8_t dkek[DKEK_KEY_SIZE + 4];
memset(kenc, 0, 32);
int r = load_dkek(id, dkek);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return r;
}
memcpy(dkek + DKEK_KEY_SIZE, "\x0\x0\x0\x1", 4);
hash256(dkek, sizeof(dkek), kenc);
mbedtls_platform_zeroize(dkek, sizeof(dkek));
return CCID_OK;
return PICOKEY_OK;
}
int dkek_kmac(uint8_t id, uint8_t *kmac) { //kmac 32 bytes
uint8_t dkek[DKEK_KEY_SIZE + 4];
memset(kmac, 0, 32);
int r = load_dkek(id, dkek);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return r;
}
memcpy(dkek + DKEK_KEY_SIZE, "\x0\x0\x0\x2", 4);
hash256(dkek, DKEK_KEY_SIZE + 4, kmac);
mbedtls_platform_zeroize(dkek, sizeof(dkek));
return CCID_OK;
return PICOKEY_OK;
}
int mkek_encrypt(uint8_t *data, uint16_t len) {
int r;
uint8_t mkek[MKEK_SIZE + 4];
if ((r = load_mkek(mkek)) != CCID_OK) {
if ((r = load_mkek(mkek)) != PICOKEY_OK) {
return r;
}
r = aes_encrypt_cfb_256(MKEK_KEY(mkek), MKEK_IV(mkek), data, len);
@@ -270,7 +257,7 @@ int mkek_encrypt(uint8_t *data, uint16_t len) {
int mkek_decrypt(uint8_t *data, uint16_t len) {
int r;
uint8_t mkek[MKEK_SIZE + 4];
if ((r = load_mkek(mkek)) != CCID_OK) {
if ((r = load_mkek(mkek)) != PICOKEY_OK) {
return r;
}
r = aes_decrypt_cfb_256(MKEK_KEY(mkek), MKEK_IV(mkek), data, len);
@@ -278,15 +265,9 @@ int mkek_decrypt(uint8_t *data, uint16_t len) {
return r;
}
int dkek_encode_key(uint8_t id,
void *key_ctx,
int key_type,
uint8_t *out,
uint16_t *out_len,
const uint8_t *allowed,
uint16_t allowed_len) {
int dkek_encode_key(uint8_t id, void *key_ctx, int key_type, uint8_t *out, uint16_t *out_len, const uint8_t *allowed, uint16_t allowed_len) {
if (!(key_type & PICO_KEYS_KEY_RSA) && !(key_type & PICO_KEYS_KEY_EC) && !(key_type & PICO_KEYS_KEY_AES)) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
uint8_t kb[8 + 2 * 4 + 2 * 4096 / 8 + 3 + 13]; //worst case: RSA-4096 (plus, 13 bytes padding)
@@ -298,21 +279,21 @@ int dkek_encode_key(uint8_t id,
uint8_t kenc[32];
memset(kenc, 0, sizeof(kenc));
r = dkek_kenc(id, kenc);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return r;
}
uint8_t kcv[8];
memset(kcv, 0, sizeof(kcv));
r = dkek_kcv(id, kcv);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return r;
}
uint8_t kmac[32];
memset(kmac, 0, sizeof(kmac));
r = dkek_kmac(id, kmac);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return r;
}
@@ -331,13 +312,13 @@ int dkek_encode_key(uint8_t id,
}
if (kb_len != 16 && kb_len != 24 && kb_len != 32 && kb_len != 64) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
if (*out_len < 8 + 1 + 10 + 6 + (2 + 64 + 14) + 16) { // 14 bytes padding
return CCID_WRONG_LENGTH;
return PICOKEY_WRONG_LENGTH;
}
put_uint16_t(kb_len, kb + 8);
put_uint16_t_be(kb_len, kb + 8);
memcpy(kb + 10, key_ctx, kb_len);
kb_len += 2;
@@ -346,19 +327,19 @@ int dkek_encode_key(uint8_t id,
}
else if (key_type & PICO_KEYS_KEY_RSA) {
if (*out_len < 8 + 1 + 12 + 6 + (8 + 2 * 4 + 2 * 4096 / 8 + 3 + 13) + 16) { //13 bytes pading
return CCID_WRONG_LENGTH;
return PICOKEY_WRONG_LENGTH;
}
mbedtls_rsa_context *rsa = (mbedtls_rsa_context *) key_ctx;
kb_len = 0;
put_uint16_t((uint16_t)mbedtls_rsa_get_len(rsa) * 8, kb + 8 + kb_len); kb_len += 2;
kb_len += put_uint16_t_be((uint16_t)mbedtls_rsa_get_len(rsa) * 8, kb + 8 + kb_len);
put_uint16_t((uint16_t)mbedtls_mpi_size(&rsa->D), kb + 8 + kb_len); kb_len += 2;
kb_len += put_uint16_t_be((uint16_t)mbedtls_mpi_size(&rsa->D), kb + 8 + kb_len);
mbedtls_mpi_write_binary(&rsa->D, kb + 8 + kb_len, mbedtls_mpi_size(&rsa->D));
kb_len += (uint16_t)mbedtls_mpi_size(&rsa->D);
put_uint16_t((uint16_t)mbedtls_mpi_size(&rsa->N), kb + 8 + kb_len); kb_len += 2;
kb_len += put_uint16_t_be((uint16_t)mbedtls_mpi_size(&rsa->N), kb + 8 + kb_len);
mbedtls_mpi_write_binary(&rsa->N, kb + 8 + kb_len, mbedtls_mpi_size(&rsa->N));
kb_len += (uint16_t)mbedtls_mpi_size(&rsa->N);
put_uint16_t((uint16_t)mbedtls_mpi_size(&rsa->E), kb + 8 + kb_len); kb_len += 2;
kb_len += put_uint16_t_be((uint16_t)mbedtls_mpi_size(&rsa->E), kb + 8 + kb_len);
mbedtls_mpi_write_binary(&rsa->E, kb + 8 + kb_len, mbedtls_mpi_size(&rsa->E));
kb_len += (uint16_t)mbedtls_mpi_size(&rsa->E);
@@ -367,46 +348,36 @@ int dkek_encode_key(uint8_t id,
}
else if (key_type & PICO_KEYS_KEY_EC) {
if (*out_len < 8 + 1 + 12 + 6 + (8 + 2 * 8 + 9 * 66 + 2 + 4) + 16) { //4 bytes pading
return CCID_WRONG_LENGTH;
return PICOKEY_WRONG_LENGTH;
}
mbedtls_ecdsa_context *ecdsa = (mbedtls_ecdsa_context *) key_ctx;
kb_len = 0;
put_uint16_t((uint16_t)mbedtls_mpi_size(&ecdsa->grp.P) * 8, kb + 8 + kb_len); kb_len += 2;
put_uint16_t((uint16_t)mbedtls_mpi_size(&ecdsa->grp.A), kb + 8 + kb_len); kb_len += 2;
kb_len += put_uint16_t_be((uint16_t)mbedtls_mpi_size(&ecdsa->grp.P) * 8, kb + 8 + kb_len);
kb_len += put_uint16_t_be((uint16_t)mbedtls_mpi_size(&ecdsa->grp.A), kb + 8 + kb_len);
mbedtls_mpi_write_binary(&ecdsa->grp.A, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->grp.A));
kb_len += (uint16_t)mbedtls_mpi_size(&ecdsa->grp.A);
put_uint16_t((uint16_t)mbedtls_mpi_size(&ecdsa->grp.B), kb + 8 + kb_len); kb_len += 2;
kb_len += put_uint16_t_be((uint16_t)mbedtls_mpi_size(&ecdsa->grp.B), kb + 8 + kb_len);
mbedtls_mpi_write_binary(&ecdsa->grp.B, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->grp.B));
kb_len += (uint16_t)mbedtls_mpi_size(&ecdsa->grp.B);
put_uint16_t((uint16_t)mbedtls_mpi_size(&ecdsa->grp.P), kb + 8 + kb_len); kb_len += 2;
kb_len += put_uint16_t_be((uint16_t)mbedtls_mpi_size(&ecdsa->grp.P), kb + 8 + kb_len);
mbedtls_mpi_write_binary(&ecdsa->grp.P, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->grp.P));
kb_len += (uint16_t)mbedtls_mpi_size(&ecdsa->grp.P);
put_uint16_t((uint16_t)mbedtls_mpi_size(&ecdsa->grp.N), kb + 8 + kb_len); kb_len += 2;
kb_len += put_uint16_t_be((uint16_t)mbedtls_mpi_size(&ecdsa->grp.N), kb + 8 + kb_len);
mbedtls_mpi_write_binary(&ecdsa->grp.N, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->grp.N));
kb_len += (uint16_t)mbedtls_mpi_size(&ecdsa->grp.N);
size_t olen = 0;
mbedtls_ecp_point_write_binary(&ecdsa->grp,
&ecdsa->grp.G,
MBEDTLS_ECP_PF_UNCOMPRESSED,
&olen,
kb + 8 + kb_len + 2,
sizeof(kb) - 8 - kb_len - 2);
put_uint16_t((uint16_t)olen, kb + 8 + kb_len);
kb_len += 2 + (uint16_t)olen;
mbedtls_ecp_point_write_binary(&ecdsa->grp, &ecdsa->grp.G, MBEDTLS_ECP_PF_UNCOMPRESSED, &olen, kb + 8 + kb_len + 2, sizeof(kb) - 8 - kb_len - 2);
kb_len += put_uint16_t_be((uint16_t)olen, kb + 8 + kb_len);
kb_len += (uint16_t)olen;
put_uint16_t((uint16_t)mbedtls_mpi_size(&ecdsa->d), kb + 8 + kb_len); kb_len += 2;
kb_len += put_uint16_t_be((uint16_t)mbedtls_mpi_size(&ecdsa->d), kb + 8 + kb_len);
mbedtls_mpi_write_binary(&ecdsa->d, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->d));
kb_len += (uint16_t)mbedtls_mpi_size(&ecdsa->d);
mbedtls_ecp_point_write_binary(&ecdsa->grp,
&ecdsa->Q,
MBEDTLS_ECP_PF_UNCOMPRESSED,
&olen,
kb + 8 + kb_len + 2,
sizeof(kb) - 8 - kb_len - 2);
put_uint16_t((uint16_t)olen, kb + 8 + kb_len);
kb_len += 2 + (uint16_t)olen;
mbedtls_ecp_point_write_binary(&ecdsa->grp, &ecdsa->Q, MBEDTLS_ECP_PF_UNCOMPRESSED, &olen, kb + 8 + kb_len + 2, sizeof(kb) - 8 - kb_len - 2);
kb_len += put_uint16_t_be((uint16_t)olen, kb + 8 + kb_len);
kb_len += (uint16_t)olen;
algo = (uint8_t *) "\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x02\x03";
algo_len = 12;
@@ -437,7 +408,7 @@ int dkek_encode_key(uint8_t id,
}
if (allowed && allowed_len > 0) {
put_uint16_t(allowed_len, out + *out_len); *out_len += 2;
*out_len += put_uint16_t_be(allowed_len, out + *out_len);
memcpy(out + *out_len, allowed, allowed_len);
*out_len += allowed_len;
}
@@ -458,25 +429,20 @@ int dkek_encode_key(uint8_t id,
kb[kb_len] = 0x80;
}
r = aes_encrypt(kenc, NULL, 256, PICO_KEYS_AES_MODE_CBC, kb, kb_len_pad);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return r;
}
memcpy(out + *out_len, kb, kb_len_pad);
*out_len += kb_len_pad;
r = mbedtls_cipher_cmac(mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_256_ECB),
kmac,
256,
out,
*out_len,
out + *out_len);
r = mbedtls_cipher_cmac(mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_256_ECB), kmac, 256, out, *out_len, out + *out_len);
*out_len += 16;
if (r != 0) {
return r;
}
return CCID_OK;
return PICOKEY_OK;
}
int dkek_type_key(const uint8_t *in) {
@@ -492,104 +458,93 @@ int dkek_type_key(const uint8_t *in) {
return 0x0;
}
int dkek_decode_key(uint8_t id,
void *key_ctx,
const uint8_t *in,
uint16_t in_len,
int *key_size_out,
uint8_t **allowed,
uint16_t *allowed_len) {
int dkek_decode_key(uint8_t id, void *key_ctx, const uint8_t *in, uint16_t in_len, int *key_size_out, uint8_t **allowed, uint16_t *allowed_len) {
uint8_t kcv[8];
int r = 0;
memset(kcv, 0, sizeof(kcv));
r = dkek_kcv(id, kcv);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return r;
}
uint8_t kmac[32];
memset(kmac, 0, sizeof(kmac));
r = dkek_kmac(id, kmac);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return r;
}
uint8_t kenc[32];
memset(kenc, 0, sizeof(kenc));
r = dkek_kenc(id, kenc);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return r;
}
if (memcmp(kcv, in, 8) != 0) {
return CCID_WRONG_DKEK;
return PICOKEY_WRONG_DKEK;
}
uint8_t signature[16];
r = mbedtls_cipher_cmac(mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_256_ECB),
kmac,
256,
in,
in_len - 16,
signature);
r = mbedtls_cipher_cmac(mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_256_ECB), kmac, 256, in, in_len - 16, signature);
if (r != 0) {
return CCID_WRONG_SIGNATURE;
return PICOKEY_WRONG_SIGNATURE;
}
if (memcmp(signature, in + in_len - 16, 16) != 0) {
return CCID_WRONG_SIGNATURE;
return PICOKEY_WRONG_SIGNATURE;
}
int key_type = in[8];
if (key_type != 5 && key_type != 6 && key_type != 12 && key_type != 15) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
if ((key_type == 5 || key_type == 6) &&
memcmp(in + 9, "\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x01\x02", 12) != 0) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
if (key_type == 12 &&
memcmp(in + 9, "\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x02\x03", 12) != 0) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
if (key_type == 15 && memcmp(in + 9, "\x00\x08\x60\x86\x48\x01\x65\x03\x04\x01", 10) != 0) {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
uint16_t ofs = 9;
//OID
uint16_t len = get_uint16_t(in, ofs);
uint16_t len = get_uint16_t_be(in + ofs);
ofs += len + 2;
//Allowed algorithms
len = get_uint16_t(in, ofs);
len = get_uint16_t_be(in + ofs);
*allowed = (uint8_t *) (in + ofs + 2);
*allowed_len = len;
ofs += len + 2;
//Access conditions
len = get_uint16_t(in, ofs);
len = get_uint16_t_be(in + ofs);
ofs += len + 2;
//Key OID
len = get_uint16_t(in, ofs);
len = get_uint16_t_be(in + ofs);
ofs += len + 2;
if ((in_len - 16 - ofs) % 16 != 0) {
return CCID_WRONG_PADDING;
return PICOKEY_WRONG_PADDING;
}
uint8_t kb[8 + 2 * 4 + 2 * 4096 / 8 + 3 + 13]; //worst case: RSA-4096 (plus, 13 bytes padding)
memset(kb, 0, sizeof(kb));
memcpy(kb, in + ofs, in_len - 16 - ofs);
r = aes_decrypt(kenc, NULL, 256, PICO_KEYS_AES_MODE_CBC, kb, in_len - 16 - ofs);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return r;
}
int key_size = get_uint16_t(kb, 8);
int key_size = get_uint16_t_be(kb + 8);
if (key_size_out) {
*key_size_out = key_size;
}
@@ -598,78 +553,78 @@ int dkek_decode_key(uint8_t id,
mbedtls_rsa_context *rsa = (mbedtls_rsa_context *) key_ctx;
mbedtls_rsa_init(rsa);
if (key_type == 5) {
len = get_uint16_t(kb, ofs); ofs += 2;
len = get_uint16_t_be(kb + ofs); ofs += 2;
r = mbedtls_mpi_read_binary(&rsa->D, kb + ofs, len); ofs += len;
if (r != 0) {
mbedtls_rsa_free(rsa);
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
len = get_uint16_t(kb, ofs); ofs += 2;
len = get_uint16_t_be(kb + ofs); ofs += 2;
r = mbedtls_mpi_read_binary(&rsa->N, kb + ofs, len); ofs += len;
if (r != 0) {
mbedtls_rsa_free(rsa);
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
}
else if (key_type == 6) {
//DP-1
len = get_uint16_t(kb, ofs); ofs += len + 2;
len = get_uint16_t_be(kb + ofs); ofs += len + 2;
//DQ-1
len = get_uint16_t(kb, ofs); ofs += len + 2;
len = get_uint16_t_be(kb + ofs); ofs += len + 2;
len = get_uint16_t(kb, ofs); ofs += 2;
len = get_uint16_t_be(kb + ofs); ofs += 2;
r = mbedtls_mpi_read_binary(&rsa->P, kb + ofs, len); ofs += len;
if (r != 0) {
mbedtls_rsa_free(rsa);
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
//PQ
len = get_uint16_t(kb, ofs); ofs += len + 2;
len = get_uint16_t_be(kb + ofs); ofs += len + 2;
len = get_uint16_t(kb, ofs); ofs += 2;
len = get_uint16_t_be(kb + ofs); ofs += 2;
r = mbedtls_mpi_read_binary(&rsa->Q, kb + ofs, len); ofs += len;
if (r != 0) {
mbedtls_rsa_free(rsa);
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
//N
len = get_uint16_t(kb, ofs); ofs += len + 2;
len = get_uint16_t_be(kb + ofs); ofs += len + 2;
}
len = get_uint16_t(kb, ofs); ofs += 2;
len = get_uint16_t_be(kb + ofs); ofs += 2;
r = mbedtls_mpi_read_binary(&rsa->E, kb + ofs, len); ofs += len;
if (r != 0) {
mbedtls_rsa_free(rsa);
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
if (key_type == 5) {
r = mbedtls_rsa_import(rsa, &rsa->N, NULL, NULL, &rsa->D, &rsa->E);
if (r != 0) {
mbedtls_rsa_free(rsa);
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
}
else if (key_type == 6) {
r = mbedtls_rsa_import(rsa, NULL, &rsa->P, &rsa->Q, NULL, &rsa->E);
if (r != 0) {
mbedtls_rsa_free(rsa);
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
}
r = mbedtls_rsa_complete(rsa);
if (r != 0) {
mbedtls_rsa_free(rsa);
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
r = mbedtls_rsa_check_privkey(rsa);
if (r != 0) {
mbedtls_rsa_free(rsa);
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
}
else if (key_type == 12) {
@@ -677,65 +632,70 @@ int dkek_decode_key(uint8_t id,
mbedtls_ecdsa_init(ecdsa);
//A
len = get_uint16_t(kb, ofs); ofs += len + 2;
len = get_uint16_t_be(kb + ofs); ofs += len + 2;
//B
len = get_uint16_t(kb, ofs); ofs += len + 2;
len = get_uint16_t_be(kb + ofs); ofs += len + 2;
//P
len = get_uint16_t(kb, ofs); ofs += 2;
len = get_uint16_t_be(kb + ofs); ofs += 2;
mbedtls_ecp_group_id ec_id = ec_get_curve_from_prime(kb + ofs, len);
if (ec_id == MBEDTLS_ECP_DP_NONE) {
mbedtls_ecdsa_free(ecdsa);
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
ofs += len;
//N
len = get_uint16_t(kb, ofs); ofs += len + 2;
len = get_uint16_t_be(kb + ofs); ofs += len + 2;
//G
len = get_uint16_t(kb, ofs);
len = get_uint16_t_be(kb + ofs);
#ifdef MBEDTLS_EDDSA_C
if (ec_id == MBEDTLS_ECP_DP_CURVE25519 && kb[ofs + 2] != 0x09) {
ec_id = MBEDTLS_ECP_DP_ED25519;
}
else if (ec_id == MBEDTLS_ECP_DP_CURVE448 && (len != 56 || kb[ofs + 2] != 0x05)) {
ec_id = MBEDTLS_ECP_DP_ED448;
}
#endif
ofs += len + 2;
//d
len = get_uint16_t(kb, ofs); ofs += 2;
len = get_uint16_t_be(kb + ofs); ofs += 2;
r = mbedtls_ecp_read_key(ec_id, ecdsa, kb + ofs, len);
if (r != 0) {
mbedtls_ecdsa_free(ecdsa);
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
ofs += len;
//Q
len = get_uint16_t(kb, ofs); ofs += 2;
len = get_uint16_t_be(kb + ofs); ofs += 2;
r = mbedtls_ecp_point_read_binary(&ecdsa->grp, &ecdsa->Q, kb + ofs, len);
if (r != 0) {
#ifdef MBEDTLS_EDDSA_C
if (mbedtls_ecp_get_type(&ecdsa->grp) == MBEDTLS_ECP_TYPE_EDWARDS) {
r = mbedtls_ecp_point_edwards(&ecdsa->grp, &ecdsa->Q, &ecdsa->d, random_gen, NULL);
}
else {
else
#endif
{
r = mbedtls_ecp_mul(&ecdsa->grp, &ecdsa->Q, &ecdsa->d, &ecdsa->grp.G, random_gen, NULL);
}
if (r != 0) {
mbedtls_ecdsa_free(ecdsa);
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
}
r = mbedtls_ecp_check_pub_priv(ecdsa, ecdsa, random_gen, NULL);
if (r != 0) {
mbedtls_ecdsa_free(ecdsa);
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
}
else if (key_type == 15) {
memcpy(key_ctx, kb + ofs, key_size);
}
return CCID_OK;
return PICOKEY_OK;
}

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef _DKEK_H_

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "oid.h"

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef _OID_H_

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#include "sc_hsm.h"
@@ -26,6 +26,7 @@
#include "pico_keys.h"
#include "usb.h"
#include "random.h"
#include "version.h"
const uint8_t sc_hsm_aid[] = {
11,
@@ -43,6 +44,10 @@ bool has_session_pin = false, has_session_sopin = false;
const uint8_t *dev_name = NULL;
uint16_t dev_name_len = 0;
uint8_t PICO_PRODUCT = 1;
uint8_t PICO_VERSION_MAJOR = HSM_VERSION_MAJOR;
uint8_t PICO_VERSION_MINOR = HSM_VERSION_MINOR;
static int sc_hsm_process_apdu();
static void init_sc_hsm();
@@ -85,7 +90,7 @@ int sc_hsm_select_aid(app_t *a, uint8_t force) {
a->process_apdu = sc_hsm_process_apdu;
a->unload = sc_hsm_unload;
init_sc_hsm();
return CCID_OK;
return PICOKEY_OK;
}
INITIALIZER( sc_hsm_ctor ) {
@@ -178,10 +183,10 @@ uint8_t puk_status[MAX_PUK];
int add_cert_puk_store(const uint8_t *data, uint16_t data_len, bool copy) {
if (data == NULL || data_len == 0) {
return CCID_ERR_NULL_PARAM;
return PICOKEY_ERR_NULL_PARAM;
}
if (puk_store_entries == MAX_PUK_STORE_ENTRIES) {
return CCID_ERR_MEMORY_FATAL;
return PICOKEY_ERR_MEMORY_FATAL;
}
puk_store[puk_store_entries].copied = copy;
@@ -205,17 +210,17 @@ int add_cert_puk_store(const uint8_t *data, uint16_t data_len, bool copy) {
&puk_store[puk_store_entries].puk_len);
puk_store_entries++;
return CCID_OK;
return PICOKEY_OK;
}
int puk_store_select_chr(const uint8_t *chr) {
for (int i = 0; i < puk_store_entries; i++) {
if (memcmp(puk_store[i].chr, chr, puk_store[i].chr_len) == 0) {
current_puk = &puk_store[i];
return CCID_OK;
return PICOKEY_OK;
}
}
return CCID_ERR_FILE_NOT_FOUND;
return PICOKEY_ERR_FILE_NOT_FOUND;
}
void reset_puk_store() {
@@ -261,13 +266,13 @@ int sc_hsm_unload() {
has_session_pin = has_session_sopin = false;
isUserAuthenticated = false;
sm_session_pin_len = 0;
return CCID_OK;
return PICOKEY_OK;
}
uint16_t get_device_options() {
file_t *ef = search_file(EF_DEVOPS);
if (file_has_data(ef)) {
return (file_read_uint8(ef) << 8) | file_read_uint8_offset(ef, 1);
return get_uint16_t_be(file_get_data(ef));
}
return 0x0;
}
@@ -334,16 +339,16 @@ int parse_ef_dir(const file_t *f, int mode) {
int pin_reset_retries(const file_t *pin, bool force) {
if (!pin) {
return CCID_ERR_NULL_PARAM;
return PICOKEY_ERR_NULL_PARAM;
}
const file_t *max = search_file(pin->fid + 1);
const file_t *act = search_file(pin->fid + 2);
if (!max || !act) {
return CCID_ERR_FILE_NOT_FOUND;
return PICOKEY_ERR_FILE_NOT_FOUND;
}
uint8_t retries = file_read_uint8(act);
if (retries == 0 && force == false) { // blocked
return CCID_ERR_BLOCKED;
return PICOKEY_ERR_BLOCKED;
}
retries = file_read_uint8(max);
int r = file_put_data((file_t *) act, &retries, sizeof(retries));
@@ -353,26 +358,26 @@ int pin_reset_retries(const file_t *pin, bool force) {
int pin_wrong_retry(const file_t *pin) {
if (!pin) {
return CCID_ERR_NULL_PARAM;
return PICOKEY_ERR_NULL_PARAM;
}
const file_t *act = search_file(pin->fid + 2);
if (!act) {
return CCID_ERR_FILE_NOT_FOUND;
return PICOKEY_ERR_FILE_NOT_FOUND;
}
uint8_t retries = file_read_uint8(act);
if (retries > 0) {
retries -= 1;
int r = file_put_data((file_t *) act, &retries, sizeof(retries));
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return r;
}
low_flash_available();
if (retries == 0) {
return CCID_ERR_BLOCKED;
return PICOKEY_ERR_BLOCKED;
}
return retries;
}
return CCID_ERR_BLOCKED;
return PICOKEY_ERR_BLOCKED;
}
bool pka_enabled() {
@@ -391,7 +396,7 @@ uint16_t check_pin(const file_t *pin, const uint8_t *data, uint16_t len) {
if (is_secured_apdu() && sm_session_pin_len > 0 && pin == file_pin1) {
if (len == sm_session_pin_len && memcmp(data, sm_session_pin, len) != 0) {
int retries;
if ((retries = pin_wrong_retry(pin)) < CCID_OK) {
if ((retries = pin_wrong_retry(pin)) < PICOKEY_OK) {
return SW_PIN_BLOCKED();
}
return set_res_sw(0x63, 0xc0 | (uint8_t)retries);
@@ -405,17 +410,17 @@ uint16_t check_pin(const file_t *pin, const uint8_t *data, uint16_t len) {
}
if (memcmp(file_get_data(pin) + 1, dhash, sizeof(dhash)) != 0) {
int retries;
if ((retries = pin_wrong_retry(pin)) < CCID_OK) {
if ((retries = pin_wrong_retry(pin)) < PICOKEY_OK) {
return SW_PIN_BLOCKED();
}
return set_res_sw(0x63, 0xc0 | (uint8_t)retries);
}
}
int r = pin_reset_retries(pin, false);
if (r == CCID_ERR_BLOCKED) {
if (r == PICOKEY_ERR_BLOCKED) {
return SW_PIN_BLOCKED();
}
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return SW_MEMORY_FAILURE();
}
if (pka_enabled() == false) {
@@ -460,7 +465,7 @@ uint32_t get_key_counter(file_t *fkey) {
uint16_t tag_len = 0;
const uint8_t *meta_tag = get_meta_tag(fkey, 0x90, &tag_len);
if (meta_tag) {
return (meta_tag[0] << 24) | (meta_tag[1] << 16) | (meta_tag[2] << 8) | meta_tag[3];
return get_uint32_t_be(meta_tag);
}
return 0xffffffff;
}
@@ -496,14 +501,9 @@ uint32_t decrement_key_counter(file_t *fkey) {
asn1_ctx_init(meta_data, meta_size, &ctxi);
while (walk_tlv(&ctxi, &p, &tag, &tag_len, &tag_data)) {
if (tag == 0x90) { // ofset tag
uint32_t val =
(tag_data[0] << 24) | (tag_data[1] << 16) | (tag_data[2] << 8) | tag_data[3];
uint32_t val = get_uint32_t_be(tag_data);
val--;
tag_data[0] = (val >> 24) & 0xff;
tag_data[1] = (val >> 16) & 0xff;
tag_data[2] = (val >> 8) & 0xff;
tag_data[3] = val & 0xff;
put_uint32_t_be(val, tag_data);
int r = meta_add(fkey->fid, cmeta, (uint16_t)meta_size);
free(cmeta);
if (r != 0) {
@@ -552,18 +552,18 @@ int store_keys(void *key_ctx, int type, uint8_t key_id) {
memcpy(kdata, key_ctx, key_size);
}
else {
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
file_t *fpk = file_new((KEY_PREFIX << 8) | key_id);
if (!fpk) {
return CCID_ERR_MEMORY_FATAL;
return PICOKEY_ERR_MEMORY_FATAL;
}
r = mkek_encrypt(kdata, key_size);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return r;
}
r = file_put_data(fpk, kdata, (uint16_t)key_size);
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return r;
}
char key_id_str[4] = {0};
@@ -580,7 +580,7 @@ int store_keys(void *key_ctx, int type, uint8_t key_id) {
}
}
low_flash_available();
return CCID_OK;
return PICOKEY_OK;
}
int find_and_store_meta_key(uint8_t key_id) {
@@ -614,86 +614,89 @@ int find_and_store_meta_key(uint8_t key_id) {
int r = meta_add((KEY_PREFIX << 8) | key_id, meta, (uint16_t)meta_size);
free(meta);
if (r != 0) {
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
}
return CCID_OK;
return PICOKEY_OK;
}
int load_private_key_rsa(mbedtls_rsa_context *ctx, file_t *fkey) {
if (wait_button_pressed() == true) { // timeout
return CCID_VERIFICATION_FAILED;
return PICOKEY_VERIFICATION_FAILED;
}
uint16_t key_size = file_get_size(fkey);
uint8_t kdata[4096 / 8];
memcpy(kdata, file_get_data(fkey), key_size);
if (mkek_decrypt(kdata, key_size) != 0) {
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
if (mbedtls_mpi_read_binary(&ctx->P, kdata, key_size / 2) != 0) {
mbedtls_platform_zeroize(kdata, sizeof(kdata));
mbedtls_rsa_free(ctx);
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
if (mbedtls_mpi_read_binary(&ctx->Q, kdata + key_size / 2, key_size / 2) != 0) {
mbedtls_platform_zeroize(kdata, sizeof(kdata));
mbedtls_rsa_free(ctx);
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
if (mbedtls_mpi_lset(&ctx->E, 0x10001) != 0) {
mbedtls_platform_zeroize(kdata, sizeof(kdata));
mbedtls_rsa_free(ctx);
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
if (mbedtls_rsa_import(ctx, NULL, &ctx->P, &ctx->Q, NULL, &ctx->E) != 0) {
mbedtls_platform_zeroize(kdata, sizeof(kdata));
mbedtls_rsa_free(ctx);
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
if (mbedtls_rsa_complete(ctx) != 0) {
mbedtls_platform_zeroize(kdata, sizeof(kdata));
mbedtls_rsa_free(ctx);
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
if (mbedtls_rsa_check_privkey(ctx) != 0) {
mbedtls_platform_zeroize(kdata, sizeof(kdata));
mbedtls_rsa_free(ctx);
return CCID_WRONG_DATA;
return PICOKEY_WRONG_DATA;
}
return CCID_OK;
return PICOKEY_OK;
}
int load_private_key_ec(mbedtls_ecp_keypair *ctx, file_t *fkey) {
if (wait_button_pressed() == true) { // timeout
return CCID_VERIFICATION_FAILED;
return PICOKEY_VERIFICATION_FAILED;
}
uint16_t key_size = file_get_size(fkey);
uint8_t kdata[67]; // Worst case, 521 bit + 1byte
memcpy(kdata, file_get_data(fkey), key_size);
if (mkek_decrypt(kdata, key_size) != 0) {
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
mbedtls_ecp_group_id gid = kdata[0];
int r = mbedtls_ecp_read_key(gid, ctx, kdata + 1, key_size - 1);
if (r != 0) {
mbedtls_platform_zeroize(kdata, sizeof(kdata));
mbedtls_ecp_keypair_free(ctx);
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
mbedtls_platform_zeroize(kdata, sizeof(kdata));
#ifdef MBEDTLS_EDDSA_C
if (gid == MBEDTLS_ECP_DP_ED25519 || gid == MBEDTLS_ECP_DP_ED448) {
r = mbedtls_ecp_point_edwards(&ctx->grp, &ctx->Q, &ctx->d, random_gen, NULL);
}
else {
else
#endif
{
r = mbedtls_ecp_mul(&ctx->grp, &ctx->Q, &ctx->d, &ctx->grp.G, random_gen, NULL);
}
if (r != 0) {
mbedtls_ecp_keypair_free(ctx);
return CCID_EXEC_ERROR;
return PICOKEY_EXEC_ERROR;
}
return CCID_OK;
return PICOKEY_OK;
}
int load_private_key_ecdh(mbedtls_ecp_keypair *ctx, file_t *fkey) {
return load_private_key_ec(ctx, fkey);
@@ -761,14 +764,18 @@ static const cmd_t cmds[] = {
};
int sc_hsm_process_apdu() {
uint32_t ne = apdu.ne;
int r = sm_unwrap();
if (r != CCID_OK) {
if (r != PICOKEY_OK) {
return SW_DATA_INVALID();
}
for (const cmd_t *cmd = cmds; cmd->ins != 0x00; cmd++) {
if (cmd->ins == INS(apdu)) {
int res = cmd->cmd_handler();
sm_wrap();
if ((CLA(apdu) >> 2) & 0x3) {
apdu.ne = ne;
}
return res;
}
}

View File

@@ -3,16 +3,16 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef _SC_HSM_H_
@@ -32,6 +32,9 @@
#include "file.h"
#include "apdu.h"
#include "pico_keys.h"
#include "usb.h"
#define MAX_APDU_DATA (USB_BUFFER_SIZE - 20)
extern const uint8_t sc_hsm_aid[];

View File

@@ -3,22 +3,22 @@
* Copyright (c) 2022 Pol Henarejos.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, version 3.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
* Affero General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <https://www.gnu.org/licenses/>.
*/
#ifndef __VERSION_H_
#define __VERSION_H_
#define HSM_VERSION 0x0402
#define HSM_VERSION 0x0604
#define HSM_VERSION_MAJOR ((HSM_VERSION >> 8) & 0xff)
#define HSM_VERSION_MINOR (HSM_VERSION & 0xff)

View File

@@ -4,7 +4,7 @@ source tests/docker_env.sh
build_image
#run_in_docker rm -rf CMakeFiles
run_in_docker mkdir -p build_in_docker
run_in_docker -w "$PWD/build_in_docker" cmake -DENABLE_EMULATION=1 -D__FOR_CI=1 ..
run_in_docker -w "$PWD/build_in_docker" cmake -DENABLE_EMULATION=1 -D__FOR_CI=1 -DENABLE_EDDSA=1 ..
run_in_docker -w "$PWD/build_in_docker" make -j ${NUM_PROC}
docker create --name temp_container pico-hsm-test:bullseye
docker cp $PWD/build_in_docker/pico_hsm temp_container:/pico_hsm

View File

@@ -21,5 +21,5 @@ from binascii import unhexlify
DEFAULT_DKEK = [0x1] * 32
TERM_CERT = unhexlify('7F2181E57F4E819E5F290100421045535049434F48534D445630303030317F494F060A04007F00070202020203864104F571E53AA8E75C929D925081CF0F893CB5991D48BD546C1A3F22199F037E4B12D601ACD91C67C88D3C5B3D04C08EC0A372485F7A248E080EE0C6237C1B075E1C5F201045535049434F48534D54525A474E50327F4C0E060904007F0007030102025301005F25060203000300055F24060204000300045F374041BF5E970739135770DBCC5DDA81FFD8B13419A9257D44CAF8404267C644E8F435B43F5E57EB2A8CF4B198045ACD094E0CB34E6217D9C8922CFB9BBEFD4088AD')
DICA_CERT = unhexlify('7F2181E97F4E81A25F290100421045535049434F48534D434130303030317F494F060A04007F0007020202020386410421EE4A21C16A10F737F12E78E5091B266612038CDABEBB722B15BF6D41B877FBF64D9AB69C39B9831B1AE00BEF2A4E81976F7688D45189BB232A24703D8A96A55F201045535049434F48534D445630303030317F4C12060904007F000703010202530580000000005F25060202000801085F24060203000601045F37403F75C08FFFC9186B56E6147199E82BFC327CEEF72495BC567961CD54D702F13E3C2766FCD1D11BD6A9D1F4A229B76B248CEB9AF88D59A74D0AB149448705159B')
TERM_CERT = unhexlify('7f2181e57f4e819e5f290100421045535049434f48534d445630303030327f494f060a04007f000702020202038641043400e4f42ea8b78b2ab58d24c8297a4b1c13a73a631b531e58d0efb60d70dd6666c8fce4130e9b15ffa4ad29708d32764ac4b0cc0e5301898522f4c735f5a90d5f201045535049434f48534d54524c524134437f4c0e060904007f0007030102025301005f25060205010102085f24060206010102085f3740569f6fe91796f95fa77ecdb680468417eed7b4e00ccc2e091a6b56389213f913c4cf91da96fbcb12d363fead30a5598f737975d58b5170b7f45e9e87ec546883')
DICA_CERT = unhexlify('7f2181e97f4e81a25f290100421045535049434f48534d434130303030327f494f060a04007f00070202020203864104e66b473ec328caf39eaed840f9c7a4ba237e1dd19004861fa3f4f134bd2d5ea5f71c6c2e6321add4c8a7793ba41119c5783f48a5d9dfc0898d9ae9e7b14da8d65f201045535049434f48534d445630303030327f4c12060904007f000703010202530580000000045f25060205000400065f24060206000400065f3740a645594c6c338cd6bda6cad039cee54fd822b1011c0af1e4e3a2a6d03d43bdbb8be68a66a8757e7b1f963589bdd80d8e65de5055b722609041ec63f0498ddc8b')

View File

@@ -24,11 +24,11 @@ RUN apt install -y libccid \
cmake \
vsmartcard-vpcd \
&& rm -rf /var/lib/apt/lists/*
RUN pip3 install pytest pycvc cryptography pyscard base58
RUN pip3 install pytest pycvc cryptography base58
WORKDIR /
RUN git clone https://github.com/OpenSC/OpenSC
WORKDIR /OpenSC
RUN git checkout tags/0.25.1
RUN git checkout tags/0.26.1
RUN ./bootstrap
RUN ./configure --enable-openssl
RUN make -j `nproc`
@@ -36,8 +36,6 @@ RUN make install
RUN make clean
RUN ldconfig
WORKDIR /
RUN git clone https://github.com/polhenarejos/pypicohsm.git
RUN pip3 install -e pypicohsm
RUN git clone https://github.com/CardContact/sc-hsm-embedded
WORKDIR /sc-hsm-embedded
RUN autoreconf -fi

Binary file not shown.

View File

@@ -23,7 +23,7 @@ def test_select(device):
device.select_applet()
def test_initialization(device):
device.initialize()
device.initialize(no_dev_cert=True)
def test_termca(device):
data = device.get_termca()

View File

@@ -20,14 +20,14 @@
import pytest
import hashlib
from const import DEFAULT_DKEK
from picohsm import APDUResponse, SWCodes
from picokey import APDUResponse, SWCodes
from picohsm.const import DEFAULT_DKEK_SHARES
KEY_DOMAINS = 3
TEST_KEY_DOMAIN = 1
def test_key_domains(device):
device.initialize(key_domains=KEY_DOMAINS)
device.initialize(key_domains=KEY_DOMAINS, no_dev_cert=True)
for k in range(KEY_DOMAINS):
kd = device.get_key_domain(key_domain=k)
assert('error' in kd)

View File

@@ -23,7 +23,7 @@ from picohsm.const import DEFAULT_DKEK_SHARES, DEFAULT_PIN, DEFAULT_RETRIES
from const import DEFAULT_DKEK
def test_dkek(device):
device.initialize(retries=DEFAULT_RETRIES, dkek_shares=DEFAULT_DKEK_SHARES)
device.initialize(retries=DEFAULT_RETRIES, dkek_shares=DEFAULT_DKEK_SHARES, no_dev_cert=True)
device.login(DEFAULT_PIN)
resp = device.import_dkek(DEFAULT_DKEK)
assert('dkek' in resp)

View File

@@ -18,22 +18,22 @@
"""
import pytest
from picohsm import APDUResponse, SWCodes
from picokey import APDUResponse, SWCodes
from picohsm.const import DEFAULT_PIN, DEFAULT_RETRIES
WRONG_PIN = '112233'
def test_pin_init_retries(device):
device.initialize(retries=DEFAULT_RETRIES)
device.initialize(retries=DEFAULT_RETRIES, no_dev_cert=True)
retries = device.get_login_retries()
assert(retries == DEFAULT_RETRIES)
def test_pin_login(device):
device.initialize(retries=DEFAULT_RETRIES)
device.initialize(retries=DEFAULT_RETRIES, no_dev_cert=True)
device.login(DEFAULT_PIN)
def test_pin_retries(device):
device.initialize(retries=DEFAULT_RETRIES)
device.initialize(retries=DEFAULT_RETRIES, no_dev_cert=True)
device.login(DEFAULT_PIN)
for ret in range(DEFAULT_RETRIES-1):
@@ -45,7 +45,7 @@ def test_pin_retries(device):
device.login(WRONG_PIN)
assert(e.value.sw == SWCodes.SW_PIN_BLOCKED)
device.initialize(retries=DEFAULT_RETRIES)
device.initialize(retries=DEFAULT_RETRIES, no_dev_cert=True)
retries = device.get_login_retries()
assert(retries == DEFAULT_RETRIES)

View File

@@ -21,7 +21,7 @@ import pytest
from picohsm import KeyType, DOPrefixes
def test_gen_initialize(device):
device.initialize()
device.initialize(no_dev_cert=True)
@pytest.mark.parametrize(
"curve", ['secp192r1', 'secp256r1', 'secp384r1', 'secp521r1', 'brainpoolP256r1', 'brainpoolP384r1', 'brainpoolP512r1', 'secp192k1', 'secp256k1', 'curve25519', 'curve448', 'ed25519', 'ed448']

View File

@@ -27,7 +27,7 @@ from picohsm.const import DEFAULT_RETRIES, DEFAULT_DKEK_SHARES
from const import DEFAULT_DKEK
def test_prepare_dkek(device):
device.initialize(retries=DEFAULT_RETRIES, dkek_shares=DEFAULT_DKEK_SHARES)
device.initialize(retries=DEFAULT_RETRIES, dkek_shares=DEFAULT_DKEK_SHARES, no_dev_cert=True)
resp = device.import_dkek(DEFAULT_DKEK)
resp = device.import_dkek(DEFAULT_DKEK)
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]

View File

@@ -25,7 +25,7 @@ from picohsm.const import DEFAULT_RETRIES, DEFAULT_DKEK_SHARES
from const import DEFAULT_DKEK
def test_prepare_dkek(device):
device.initialize(retries=DEFAULT_RETRIES, dkek_shares=DEFAULT_DKEK_SHARES)
device.initialize(retries=DEFAULT_RETRIES, dkek_shares=DEFAULT_DKEK_SHARES, no_dev_cert=True)
resp = device.import_dkek(DEFAULT_DKEK)
resp = device.import_dkek(DEFAULT_DKEK)
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]

View File

@@ -18,7 +18,8 @@
"""
import pytest
from picohsm import KeyType, DOPrefixes, APDUResponse, SWCodes
from picohsm import KeyType, DOPrefixes
from picokey import APDUResponse, SWCodes
from binascii import hexlify
import hashlib
from const import DEFAULT_DKEK
@@ -28,7 +29,7 @@ from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization
def test_initialize(device):
device.initialize(key_domains=1)
device.initialize(key_domains=1, no_dev_cert=True)
assert(device.get_key_domains() == 1)
device.set_key_domain(key_domain=0, total=2)

View File

@@ -27,7 +27,7 @@ from const import DEFAULT_DKEK
MESSAGE = b'a secret message'
def test_prepare_aes(device):
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES)
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES, no_dev_cert=True)
resp = device.import_dkek(DEFAULT_DKEK)
resp = device.import_dkek(DEFAULT_DKEK)

View File

@@ -21,7 +21,8 @@ import pytest
import os
from cryptography.hazmat.primitives.ciphers import aead
import cryptography.exceptions
from picohsm import APDUResponse, DOPrefixes, EncryptionMode, SWCodes
from picohsm import DOPrefixes, EncryptionMode
from picokey import APDUResponse, SWCodes
from picohsm.const import DEFAULT_DKEK_SHARES
from const import DEFAULT_DKEK
from binascii import hexlify
@@ -30,7 +31,7 @@ MESSAGE = b'a secret message'
AAD = b'this is a tag for AAD'
def test_prepare_chachapoly(device):
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES)
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES, no_dev_cert=True)
resp = device.import_dkek(DEFAULT_DKEK)
resp = device.import_dkek(DEFAULT_DKEK)

View File

@@ -20,8 +20,7 @@
import pytest
import os
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes, aead
import cryptography.exceptions
from picohsm import APDUResponse, DOPrefixes, EncryptionMode, SWCodes, AES
from picohsm import EncryptionMode, AES
from picohsm.const import DEFAULT_DKEK_SHARES
from const import DEFAULT_DKEK
from binascii import hexlify
@@ -30,7 +29,7 @@ MESSAGE = b'a secret message'
AAD = b'this is a tag for AAD'
def test_prepare_aes(device):
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES)
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES, no_dev_cert=True)
resp = device.import_dkek(DEFAULT_DKEK)
resp = device.import_dkek(DEFAULT_DKEK)

View File

@@ -28,7 +28,7 @@ from const import DEFAULT_DKEK
MESSAGE = b'a secret message'
def test_prepare_aes(device):
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES)
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES, no_dev_cert=True)
resp = device.import_dkek(DEFAULT_DKEK)
resp = device.import_dkek(DEFAULT_DKEK)

View File

@@ -29,7 +29,7 @@ from picohsm import DOPrefixes
INFO = b'info message'
def test_prepare_kd(device):
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES)
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES, no_dev_cert=True)
resp = device.import_dkek(DEFAULT_DKEK)
resp = device.import_dkek(DEFAULT_DKEK)

View File

@@ -29,7 +29,7 @@ from picohsm import DOPrefixes
INFO = b'info message'
def test_prepare_kd(device):
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES)
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES, no_dev_cert=True)
resp = device.import_dkek(DEFAULT_DKEK)
resp = device.import_dkek(DEFAULT_DKEK)

View File

@@ -29,7 +29,7 @@ from picohsm import DOPrefixes
INFO = b'shared message'
def test_prepare_kd(device):
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES)
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES, no_dev_cert=True)
resp = device.import_dkek(DEFAULT_DKEK)
resp = device.import_dkek(DEFAULT_DKEK)

View File

@@ -21,20 +21,20 @@ import pytest
from binascii import unhexlify, hexlify
from cvc.certificates import CVC
from picohsm.utils import int_to_bytes
from picohsm import APDUResponse, SWCodes
from picokey import APDUResponse, SWCodes
from const import TERM_CERT, DICA_CERT
from cryptography.hazmat.primitives.asymmetric import ec, utils
from cryptography.hazmat.primitives import hashes
AUT_KEY = unhexlify('0A40E11E672C28C558B72C25D93BCF28C08D39AFDD5A1A2FD3BAF7A6B27F0C2E')
AUT_KEY = unhexlify('579A995BD7BA35AD3D3968940FA4CDA34116E121A8AC01396234DAFB132B3FD7')
aut_pk = ec.derive_private_key(int.from_bytes(AUT_KEY, 'big'), ec.BrainpoolP256R1())
AUT_PUK = unhexlify('678201ed7f218201937f4e82014b5f290100421045535049434f48534d54525a474e50327f4982011d060a04007f000702020202038120a9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e537782207d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9832026dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b68441048bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f0469978520a9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a78641040cc18ce246da678239af0913a1579dda58c07be404da4a65327794fac93f57a333267979905b5d046da7020226cc4e5fc477e8fc651a0cf87095259aafa88e648701015f201045535049434f48534d54525a474e50325f37401fc90bdab2a58c3cd25f18a90baa2c21d3d087002ba240fb274ff066759297f79e130053d902d637a448c8cdcd0670fe8ebcc06d8a3ee82079f08d1ff8660393421045535049434f48534d54525a474e50325f3740e24e7e23eae3c78f9fa88391004369a293c43ef99e2279170983e1dbe707fbf0382d09de3e60ef1addd2f055947c3efcef17926065ddb7a031f4905da474ed1d')
AUT_PUK = unhexlify('678201ed7f218201937f4e82014b5f290100421045535049434f48534d54524c524134437f4982011d060a04007f000702020202038120a9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e537782207d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9832026dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b68441048bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f0469978520a9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a7864104a8217de2cec275cdf9dcda68128aff6061199291532545ab394e2554015962e16d568012a9d01b3da60d062aeed11356467fa3af9ebf9aad3d2933ebb9d86e0f8701015f201045535049434f48534d54524c524134435f374022d9f4480995e8370f8377e8bd4a63547be7740f7836456de5196839c6689540889acd573338d68bdea3db2e31c8dd00e670a4bcccdef497a156c39170d3c837421045535049434f48534d54524c524134435f374014445d219facb3bb745867d945e46526a2a6d03441dba52911d8f9483abbe4272a0beee7cecc69c661f3459c9b5431719ebf7e11f93d903a2cf705899eb4b631')
term_chr = CVC().decode(TERM_CERT).chr()
def test_initialize(device):
device.initialize(puk_auts=1, puk_min_auts=1)
device.initialize(puk_auts=1, puk_min_auts=1, no_dev_cert=False)
device.logout()
def test_register_puk(device):
@@ -102,7 +102,7 @@ def test_enumerate_puk_1(device):
assert(puks[0]['status'] == 0)
def test_enumerate_puk_2(device):
device.initialize(puk_auts=2, puk_min_auts=1)
device.initialize(puk_auts=2, puk_min_auts=1, no_dev_cert=True)
puks = device.enumerate_puk()
assert(len(puks) == 2)
assert(puks[0]['status'] == -1)
@@ -115,7 +115,7 @@ def test_enumerate_puk_2(device):
assert(puks[1]['status'] == -1)
def test_register_more_puks(device):
device.initialize(puk_auts=2, puk_min_auts=1)
device.initialize(puk_auts=2, puk_min_auts=1, no_dev_cert=True)
status = device.get_puk_status()
assert(status == bytes([2,2,1,0]))
@@ -123,14 +123,14 @@ def test_register_more_puks(device):
assert(status == bytes([2,1,1,0]))
def test_is_pku(device):
device.initialize(puk_auts=1, puk_min_auts=1)
device.initialize(puk_auts=1, puk_min_auts=1, no_dev_cert=True)
assert(device.is_puk() == True)
device.initialize()
device.initialize(no_dev_cert=True)
assert(device.is_puk() == False)
def test_check_puk_key(device):
device.initialize(puk_auts=1, puk_min_auts=1)
device.initialize(puk_auts=1, puk_min_auts=1, no_dev_cert=True)
status = device.check_puk_key(term_chr)
assert(status == -1)
@@ -140,7 +140,7 @@ def test_check_puk_key(device):
def test_register_puk_with_no_puk(device):
device.initialize()
device.initialize(no_dev_cert=True)
with pytest.raises(APDUResponse) as e:
device.register_puk(AUT_PUK, TERM_CERT, DICA_CERT)
assert(e.value.sw == SWCodes.SW_FILE_NOT_FOUND)

View File

@@ -25,12 +25,13 @@ from cvc.asn1 import ASN1
from cvc.certificates import CVC
from cvc import oid
from cryptography.hazmat.primitives.asymmetric import ec
from picohsm import DOPrefixes, APDUResponse, SWCodes
from picohsm import DOPrefixes
from picokey import APDUResponse, SWCodes
KDM = unhexlify(b'30820420060b2b0601040181c31f0402016181ed7f2181e97f4e81a25f290100421045535049434f48534d434130303030317f494f060a04007f0007020202020386410421ee4a21c16a10f737f12e78e5091b266612038cdabebb722b15bf6d41b877fbf64d9ab69c39b9831b1ae00bef2a4e81976f7688d45189bb232a24703d8a96a55f201045535049434f48534d445630303030317f4c12060904007f000703010202530580000000005f25060202000801085f24060203000601045f37403f75c08fffc9186b56e6147199e82bfc327ceef72495bc567961cd54d702f13e3c2766fcd1d11bd6a9d1f4a229b76b248ceb9af88d59a74d0ab149448705159b6281e97f2181e57f4e819e5f290100421045535049434f48534d445630303030317f494f060a04007f00070202020203864104c8561b41e54fea81bb80dd4a6d537e7c3904344e8ca90bc5f668111811e02c8d5d51ca93ca89558f2a8a9cbb147434e3441ec174505ff980fd7a7106286196915f201045535049434f48534d54524a444736387f4c0e060904007f0007030102025301005f25060203000300065f24060204000300055f3740983de63d0975b715ebd8a93cb38fa9638882c8b7064d51a6facabed693b92edc098e458b713203413ef6de0958c44772cbdbc264205c7b1bdb8b4fcb2516437f638201f1678201ed7f218201937f4e82014b5f290100421045535049434f48534d54524a444736387f4982011d060a04007f000702020202038120a9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e537782207d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9832026dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b68441048bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f0469978520a9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a78641048b1f450912a2e4d428b7eefc5fa05618a9ef295e90009a61cbb0970181b333474ea94f94cde5a11aba0589e85d4225002789ff1cdcf25756f059647b49fc2a158701015f201045535049434f48534d54524a444736385f3740372407c20de7257c89dae1e6606c8a046ca65efaa010c0a22b75c402ee243de51f5f1507457193679ed9db4fbbfe8efb9d695b684492b665ad8ba98c1f84ea38421045535049434f48534d54524a444736385f374098718e2e14a44386b689b71a101530316b65ab49a91bab0dd56099c5161ecb8aadff6cf27449f94034e58b7306f01e6ffa2766a2f5bb1281e12e5f1f9174733454400cf8926ca5bec9a91bcd47bf391c15d94ef6e3243d5fd1fffeaafd586766bc3221eafd808f17f8450f238cc1fe7ab1854443db31d622f53a2b3fdb3ad750d5ce')
KDM = unhexlify(b'30820420060b2b0601040181c31f0402016181ed7f2181e97f4e81a25f290100421045535049434f48534d434130303030327f494f060a04007f00070202020203864104e66b473ec328caf39eaed840f9c7a4ba237e1dd19004861fa3f4f134bd2d5ea5f71c6c2e6321add4c8a7793ba41119c5783f48a5d9dfc0898d9ae9e7b14da8d65f201045535049434f48534d445630303030327f4c12060904007f000703010202530580000000045f25060205000400065f24060206000400065f3740a645594c6c338cd6bda6cad039cee54fd822b1011c0af1e4e3a2a6d03d43bdbb8be68a66a8757e7b1f963589bdd80d8e65de5055b722609041ec63f0498ddc8b6281e97f2181e57f4e819e5f290100421045535049434f48534d445630303030327f494f060a04007f000702020202038641043359f5234ce62e0eb80460046d8fd1aae018cc8b9e687b40aa2c047e352409b45153d1ad888e4e7e780a3b1fa8c69ca8998bd271c8849137149142e96816a5a45f201045535049434f48534d54524a5a58314a7f4c0e060904007f0007030102025301005f25060205010102085f24060206010102085f37409add1c1c8a05e7bc56a8bd846c9122d9214cc43c86b6952a961dce525d830a58130cbb275e9408af38dc16160f958d2b9ac6ac4f0f1b9b863284f00121d447ce638201f1678201ed7f218201937f4e82014b5f290100421045535049434f48534d54524a5a58314a7f4982011d060a04007f000702020202038120a9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e537782207d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9832026dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b68441048bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f0469978520a9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a78641049de55b50b921de72bbf740d3518905ff893e8208cfe8d144de34d79da3645d1c0cb551a19d6e6a5fee050e479a65d36fdf638af741e52dad4df9960b8ed443d18701015f201045535049434f48534d54524a5a58314a5f374099dede270b9a2def89a4d12dc0314e6289bd565808683f362e9f9ac9554ec5113bf7e412ecc386af12d2a9b43f27e54e10dfc6d8f2d6b618b1776459c13c0bec421045535049434f48534d54524a5a58314a5f3740459f6385f28a84f1c57f421a7f6cb4f1177084497321be94c87998c2e01af0202bab6984411cde1aab34e4e59cc27961b85855bae6340305281ff838253b0f3554404b6a2fe6947faa91f6ffa0d707cd4cbb43192935f561be137f4b3680304fc28b41210b671b8b033e06b4ad720010bcd36b92282844616261f944f3c4f67bfda5')
def test_initialize(device):
device.initialize(key_domains=1)
device.initialize(key_domains=1, no_dev_cert=True)
device.logout()
def test_create_xkek(device):

View File

@@ -27,7 +27,8 @@ from cvc.certificates import CVC
from cvc import oid
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import hashes
from picohsm import EncryptionMode, APDUResponse, SWCodes, PicoHSM
from picohsm import EncryptionMode, PicoHSM
from picokey import APDUResponse, SWCodes
import hashlib
TEST_STRING = b'Pico Keys are awesome!'
@@ -36,7 +37,7 @@ def sha256_sha256(data):
return hashlib.sha256(hashlib.sha256(data).digest()).digest()
def test_initialize(device):
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES)
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES, no_dev_cert=True)
resp = device.import_dkek(DEFAULT_DKEK)
resp = device.import_dkek(DEFAULT_DKEK)

View File

@@ -7,9 +7,9 @@ test $? -eq 0 || exit $?
rsa_encrypt_decrypt() {
openssl pkeyutl -encrypt -pubin -inkey 1.pub $2 -in $1 -out data.crypt
test $? -eq 0 && echo -n "." || exit $?
TDATA=$(tr -d '\0' < <(pkcs11-tool --id 1 --pin 648219 --decrypt $3 -i data.crypt 2>/dev/null))
TDATA=$(pkcs11-tool --id 1 --pin 648219 --decrypt $3 -i data.crypt 2>/dev/null | sed '/^OAEP parameters:/d' | tr -d '\0')
test $? -eq 0 && echo -n "." || exit $?
if [[ ${TEST_STRING} != "$TDATA" ]]; then
if [[ "$TEST_STRING" != "$TDATA" ]]; then
exit 1
fi
test $? -eq 0 && echo -n "." || exit $?
@@ -36,7 +36,7 @@ rsa_encrypt_decrypt data_pad "-pkeyopt rsa_padding_mode:none" "--mechanism RSA-X
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
echo -n " Test RSA-PKCS-OAEP ciphering..."
rsa_encrypt_decrypt data "-pkeyopt rsa_padding_mode:oaep -pkeyopt rsa_oaep_md:sha256 -pkeyopt rsa_mgf1_md:sha256" "--mechanism RSA-PKCS-OAEP"
rsa_encrypt_decrypt data "-pkeyopt rsa_padding_mode:oaep -pkeyopt rsa_oaep_md:sha256 -pkeyopt rsa_mgf1_md:sha256" "--mechanism RSA-PKCS-OAEP --hash-algorithm SHA256 --mgf MGF1-SHA256"
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
rm -rf data* 1.*

View File

@@ -37,7 +37,9 @@ gen_and_delete() {
test $? -eq 0 && echo -n "." || exit $?
}
reset() {
python3 tools/pico-hsm-tool.py --pin 648219 initialize --so-pin 57621880 --silent > /dev/null 2>&1
#python3 tools/pico-hsm-tool.py --pin 648219 initialize --so-pin 57621880 --silent --no-dev-cert > /dev/null 2>&1
rm -f memory.flash
tar -xf tests/memory.tar.gz
test $? -eq 0 || exit $?
}

View File

@@ -14,7 +14,7 @@ test $? -eq 0 && echo -n "." || {
echo -e "\t${FAIL}"
exit 1
}
grep -q "338 tests performed" <<< $e && echo -n "." || {
grep -q "334 tests performed" <<< $e && echo -n "." || {
echo -e "\t${FAIL}"
exit 1
}

View File

@@ -2,4 +2,4 @@
source ./tests/startup.sh
pytest tests -W ignore::DeprecationWarning
# pytest tests -W ignore::DeprecationWarning

View File

@@ -1,94 +0,0 @@
#!/bin/bash
#
# This file is part of the Pico HSM distribution (https://github.com/polhenarejos/pico-hsm).
# Copyright (c) 2022 Pol Henarejos.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, version 3.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
VERSION_MAJOR="6" #Version of Pico Keys SDK
VERSION_MINOR="0"
echo "----------------------------"
echo "VID/PID patcher for Pico HSM"
echo "----------------------------"
echo ""
if [ "$#" -le 0 ]; then
echo "Usage: $0 VID:PID [input_uf2_file] [output_uf2_file]"
exit 1
fi
IFS=':' read -r -a ARR <<< "$1"
if [ ${#ARR[@]} -ne 2 ]; then
echo "ERROR: Specify vendor and product ids as VID:PID (e.g., $0 CAFE:1234)"
exit 1
fi
VID=${ARR[0]}
PID=${ARR[1]}
if [ ${#VID} -ne 4 ]; then
echo "ERROR: VID length must be 4 hexadecimal characters"
exit 1
fi
if [ ${#PID} -ne 4 ]; then
echo "ERROR: PID length must be 4 hexadecimal characters"
exit 1
fi
if ! [[ $VID =~ ^[0-9A-Fa-f]{1,}$ ]] ; then
echo "ERROR: VID must contain hexadecimal characters"
exit 1
fi
if ! [[ $PID =~ ^[0-9A-Fa-f]{1,}$ ]] ; then
echo "ERROR: PID must contain hexadecimal characters"
exit 1
fi
UF2_FILE_IF="hsm2040.uf2"
UF2_FILE_OF="$UF2_FILE_IF"
if [ "$#" -ge 2 ]; then
UF2_FILE_IF="$2"
UF2_FILE_OF="$UF2_FILE_IF"
fi
if [ "$#" -ge 3 ]; then
UF2_FILE_OF="$3"
fi
echo -n "Patching ${UF2_FILE_IF}... "
if [[ ! -f "$UF2_FILE_IF" ]]; then
echo "ERROR: UF2 file ${UF2_FILE_IF} does not exist"
exit 1
fi
if [ "$UF2_FILE_IF" != "$UF2_FILE_OF" ]; then
cp -R $UF2_FILE_IF $UF2_FILE_OF
fi
LITTLE_VID="\x${VID:2:2}\x${VID:0:2}"
LITTLE_PID="\x${PID:2:2}\x${PID:0:2}"
perl -pi -e "s/\xff\xfe\xfd\xfc\x$VERSION_MINOR\x$VERSION_MAJOR\x01\x02\x03\x01/$LITTLE_VID$LITTLE_PID\x$VERSION_MINOR\x$VERSION_MAJOR\x01\x02\x03\x01/" $UF2_FILE_OF
echo "Done!"
echo ""
echo "Patched file was saved in ${UF2_FILE_OF}"

View File

@@ -39,13 +39,13 @@ except ModuleNotFoundError:
sys.exit(-1)
try:
from picohsm import PicoHSM, PinType, DOPrefixes, KeyType, EncryptionMode, utils, APDUResponse, SWCodes, AES
from picohsm import PicoHSM, PinType, DOPrefixes, KeyType, EncryptionMode, AES
from picohsm.utils import get_pki_data
from picokey import APDUResponse, Platform
except ModuleNotFoundError:
print('ERROR: picohsm module not found! Install picohsm package.\nTry with `pip install pypicohsm`')
sys.exit(-1)
import json
import urllib.request
import base64
from binascii import hexlify, unhexlify
import sys
@@ -57,6 +57,8 @@ from argparse import RawTextHelpFormatter
pin = None
BOOTKEY = [225, 209, 107, 167, 100, 171, 215, 18, 212, 239, 110, 62, 221, 116, 78, 213, 99, 140, 38, 11, 119, 28, 249, 129, 81, 17, 11, 175, 172, 155, 200, 113]
def hexy(a):
return [hex(i) for i in a]
@@ -65,8 +67,10 @@ def parse_args():
subparser = parser.add_subparsers(title="commands", dest="command", required=True)
parser_init = subparser.add_parser('initialize', help='Performs the first initialization of the Pico HSM.')
parser.add_argument('--pin', help='PIN number')
parser.add_argument('--slot', help='Select specific slot', type=int, default=-1)
parser_init.add_argument('--so-pin', help='SO-PIN number')
parser_init.add_argument('--silent', help='Confirms initialization silently.', action='store_true')
parser_init.add_argument('--no-dev-cert', help='Do not request a device certificate (it will use a self-signed certificate). Do not use if attestation is needed.', action='store_true', default=False)
parser_attestate = subparser.add_parser('attestate', help='Generates an attestation report for a private key and verifies the private key was generated in the devices or outside.')
parser_attestate.add_argument('-k', '--key', help='The private key index', metavar='KEY_ID')
@@ -94,11 +98,15 @@ def parse_args():
parser_phy = subparser.add_parser('phy', help='Set PHY options.')
subparser_phy = parser_phy.add_subparsers(title='commands', dest='subcommand', required=True)
parser_phy_vp = subparser_phy.add_parser('vidpid', help='Sets VID/PID. Use VID:PID format (e.g. 1234:5678)')
parser_phy_ledn = subparser_phy.add_parser('led', help='Sets LED GPIO number.')
parser_phy_ledn = subparser_phy.add_parser('led_gpio', help='Sets LED GPIO number.')
parser_phy_optwcid = subparser_phy.add_parser('wcid', help='Enable/Disable Web CCID interface.')
parser_phy_vp.add_argument('value', help='Value of the PHY option.', metavar='VAL', nargs='?')
parser_phy_ledn.add_argument('value', help='Value of the PHY option.', metavar='VAL', nargs='?')
parser_phy_optwcid.add_argument('value', choices=['enable', 'disable'], help='Enable/Disable Web CCID interface.', nargs='?')
parser_phy_ledbtness = subparser_phy.add_parser('led_brightness', help='Sets LED max. brightness.')
parser_phy_ledbtness.add_argument('value', help='Value of the max. brightness.', metavar='VAL', nargs='?')
parser_phy_optdimm = subparser_phy.add_parser('led_dimmable', help='Enable/Disable LED dimming.')
parser_phy_optdimm.add_argument('value', choices=['enable', 'disable'], help='Enable/Disable LED dimming.', nargs='?')
parser_secure = subparser.add_parser('secure', help='Manages security of Pico HSM.')
subparser_secure = parser_secure.add_subparsers(title='commands', dest='subcommand', required=True)
@@ -131,28 +139,42 @@ def parse_args():
parser_keygen = subparser.add_parser('keygen', help='Generates private keypair or secret key.')
subparser_keygen = parser_keygen.add_subparsers(title='commands', dest='subcommand', required=True)
parser_keygen_aes = subparser_keygen.add_parser('aes', help='Generates an AES key.')
parser_keygen_aes.add_argument('--size', help='Specifies the size of AES key [128, 192 or 256]',choices=[128, 192, 256], default=128, type=int)
parser_keygen_aes.add_argument('--size', help='Specifies the size of AES key [128, 192 or 256]', choices=[128, 192, 256], default=128, type=int)
parser_keygen_x25519 = subparser_keygen.add_parser('x25519', help='Generates a private X25519 keypair.')
parser_keygen_x448 = subparser_keygen.add_parser('x448', help='Generates a private X448 keypair.')
parser_keygen_x25519 = subparser_keygen.add_parser('ed25519', help='Generates a private Ed25519 keypair.')
parser_keygen_x448 = subparser_keygen.add_parser('ed448', help='Generates a private Ed448 keypair.')
parser_otp = subparser.add_parser('otp', help='Read/write OTP values.')
parser_otp.add_argument('subcommand', choices=['read', 'write', 'secure_boot'], help='Read, write or enable Secure Boot', nargs='?')
parser_otp.add_argument('--row', help='OTP row (in HEX)', required='write' in sys.argv or 'read' in sys.argv)
parser_otp.add_argument('-d', '--data', help='Data to write (in HEX) [e.g. 0011223344556677889900AABBCCDDEEFF]', required='write' in sys.argv)
parser_otp.add_argument('--lock', help='Lock & protect (no other firmwares can be loaded)', action='store_true')
parser_otp.add_argument('--index', help='Bootkey index [0-3]', type=int, default=0, choices=[0, 1, 2, 3])
parser_reboot = subparser.add_parser('reboot', help='Reboots the Pico HSM.')
parser_memory = subparser.add_parser('memory', help='Get memory usage.')
parser_bip32 = subparser.add_parser('bip32', help='Performs bip32 operations.')
parser_bip32.add_argument('--id', help='Master key id (0-255)', required=True)
subparser_bip32 = parser_bip32.add_subparsers(title='commands', dest='subcommand', required=True)
parser_bip32_init = subparser_bip32.add_parser('initialize', help='Initializes a master key.')
parser_bip32_derive = subparser_bip32.add_parser('derive', help='Derives a extended public key (xpub).')
parser_bip32_sign = subparser_bip32.add_parser('sign', help='Sign message.\n\tIf no file input/output is specified, stdin/stdout will be used.')
parser_bip32_init.add_argument('--curve', choices=['secp256k1', 'secp256r1', 'symmetric'], required=True)
parser_bip32_init.add_argument('--seed-file', help='File with the master seed. Specify "-" for stdin.')
parser_bip32_derive.add_argument('--path', help='Derivation path (e.g. m/0h/1/2)', required=True)
parser_bip32_sign.add_argument('--path', help='Derivation path (e.g. m/0h/1/2)', required=True)
parser_bip32_sign.add_argument('--file-in', help='File to sign.')
parser_bip32_sign.add_argument('--file-out', help='File to write the signature.')
args = parser.parse_args()
return args
def get_pki_data(url, data=None, method='GET'):
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; '
'rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
method = 'GET'
if (data is not None):
method = 'POST'
req = urllib.request.Request(f"https://www.picokeys.com/pico/pico-hsm/{url}/",
method=method,
data=data,
headers={'User-Agent': user_agent, })
response = urllib.request.urlopen(req)
resp = response.read().decode('utf-8')
j = json.loads(resp)
return j
def get_pki_certs(certs_dir='certs', force=False):
certs = get_pki_data('certs')
if (os.path.exists(certs_dir) is False):
@@ -185,43 +207,11 @@ def initialize(picohsm, args):
print('Are you sure?')
_ = input('[Press enter to confirm]')
if (args.pin):
try:
picohsm.login(args.pin)
except APDUResponse:
pass
pin = args.pin
else:
pin = '648219'
picohsm.initialize(pin=args.pin, sopin=args.so_pin, no_dev_cert=args.no_dev_cert)
if (args.so_pin):
try:
picohsm.login(args.so_pin, who=PinType.SO_PIN)
except APDUResponse:
pass
so_pin = args.so_pin
else:
so_pin = '57621880'
picohsm.initialize(pin=pin, sopin=so_pin)
response = picohsm.get_contents(DOPrefixes.EE_CERTIFICATE_PREFIX, 0x00)
cert = bytearray(response)
Y = CVC().decode(cert).pubkey().find(0x86).data()
print(f'Public Point: {hexlify(Y).decode()}')
pbk = base64.urlsafe_b64encode(Y)
data = urllib.parse.urlencode({'pubkey': pbk}).encode()
j = get_pki_data('cvc', data=data)
print('Device name: '+j['devname'])
dataef = base64.urlsafe_b64decode(
j['cvcert']) + base64.urlsafe_b64decode(j['dvcert']) + base64.urlsafe_b64decode(j['cacert'])
picohsm.select_file(0x2f02)
response = picohsm.put_contents(0x0000, data=dataef)
print('Certificate uploaded successfully!')
print('')
if (not args.no_dev_cert):
print('Certificate uploaded successfully!')
print('')
print('Note that the device is initialized with a default PIN and '
'configuration.')
print('Now you can initialize the device as usual with your chosen PIN '
@@ -349,7 +339,7 @@ class SecureLock:
def disable_device_aut(self):
ct = self.get_skey()
self.picohsm.send(cla=0x80, command=0x64, p1=0x3A, p2=0x04, p3=list(ct))
self.picohsm.send(cla=0x80, command=0x64, p1=0x3A, p2=0x04, data=list(ct))
def secure(picohsm, args):
slck = SecureLock(picohsm)
@@ -447,8 +437,10 @@ def cipher(picohsm, args):
def keygen(picohsm, args):
if (args.subcommand == 'aes'):
ret = picohsm.key_generation(KeyType.AES, param=args.size)
elif (args.subcommand in ['x25519', 'x448']):
curve = 'curve' + args.subcommand[1:]
elif (args.subcommand in ['x25519', 'x448', 'ed25519', 'ed448']):
curve = args.subcommand
if (args.subcommand in ['x25519', 'x448']):
curve = 'curve' + args.subcommand[1:]
ret = picohsm.key_generation(KeyType.ECC, curve)
print('Key generated successfully.')
print(f'Key ID: {ret}')
@@ -460,10 +452,15 @@ def phy(picohsm, args):
sp = val.split(':')
if (len(sp) != 2):
print('ERROR: VID/PID have wrong format. Use VID:PID format (e.g. 1234:5678)')
return
val = int(sp[0],16).to_bytes(2, 'big') + int(sp[1],16).to_bytes(2, 'big')
elif (args.subcommand == 'led'):
elif (args.subcommand in ['led_gpio', 'led_brightness']):
if (args.subcommand == 'led_brightness'):
if (int(val) > 15 or int(val) < 0):
print('ERROR: LED brightness must be between 0 and 15.')
return
val = [int(val)]
elif (args.subcommand == 'wcid'):
elif (args.subcommand in ['wcid', 'led_dimmable']):
val = val == 'enable'
ret = picohsm.phy(args.subcommand, val)
if (ret):
@@ -471,14 +468,92 @@ def phy(picohsm, args):
else:
print('Command executed successfully. Please, restart your Pico Key.')
def otp(picohsm, args):
if (args.subcommand == 'read'):
row = int(args.row, 16)
ret = picohsm.otp(row=row)
print(f'OTP row {args.row}: {hexlify(ret).decode()}')
elif (args.subcommand == 'write'):
row = int(args.row, 16)
data = unhexlify(args.data)
picohsm.otp(row=row, data=data)
print(f'OTP row {args.row} written successfully.')
elif (args.subcommand == 'secure_boot'):
picohsm.secure_boot(BOOTKEY, bootkey_index=args.index, lock=args.lock)
def reboot(picohsm, args):
picohsm.reboot()
def memory(picohsm, args):
mem = picohsm.memory()
print(f'Memory usage:')
print(f'\tFree: {mem["free"]/1024:.2f} kilobytes ({mem["free"]*100/mem["total"]:.2f}%)')
print(f'\tUsed: {mem["used"]/1024:.2f} kilobytes ({mem["used"]*100/mem["total"]:.2f}%)')
print(f'\tTotal: {mem["total"]/1024:.2f} kilobytes')
print(f'\tFlash size: {mem["size"]/1024:.2f} kilobytes')
print(f'\tFiles: {mem["files"]}')
def bip32(picohsm, args):
id = 0
if args.id != "":
id = int(args.id)
if (args.subcommand == 'initialize'):
seed = None
if args.seed_file:
if args.seed_file != '-':
fin = open(args.seed_file, 'rb')
seed = fin.read()
fin.close()
else:
seed = sys.stdin.buffer.read()
picohsm.hd_generate_master_node(curve=args.curve, id=id, seed=seed)
elif (args.subcommand == 'derive'):
path = parse_derivation_path(args.path)
ret = picohsm.hd_derive_node([id] + path)
sys.stdout.buffer.write(bytes(ret))
elif (args.subcommand == 'sign'):
if (args.file_in):
fin = open(args.file_in, 'rb')
else:
fin = sys.stdin.buffer
data = fin.read()
fin.close()
path = parse_derivation_path(args.path)
ret = picohsm.hd_signature([id] + path, data)
if (args.file_out):
fout = open(args.file_out, 'wb')
fout.write(bytes(ret))
fout.close()
else:
sys.stdout.buffer.write(bytes(ret))
def parse_derivation_path(path):
if path == "m":
return []
if len(path) < 3:
raise ValueError(f"derivation path too short: {path}")
elems = path.split("/")
if elems[0] != 'm':
raise ValueError(f"derivation path {path} does not begin with 'm/'")
indices = []
for e in elems[1:]:
if len(e) == 0:
raise ValueError(f"derivation path contains empty index: {path}")
off = 0
if e[-1:] in ["'", "h"]:
off = 0x80000000
e = e[:-1]
indices.append(int(e) + off)
return indices
def main(args):
sys.stderr.buffer.write(b'Pico HSM Tool v1.14\n')
sys.stderr.buffer.write(b'Pico HSM Tool v2.4\n')
sys.stderr.buffer.write(b'Author: Pol Henarejos\n')
sys.stderr.buffer.write(b'Report bugs to https://github.com/polhenarejos/pico-hsm/issues\n')
sys.stderr.buffer.write(b'\n\n')
sys.stderr.flush()
picohsm = PicoHSM(args.pin)
picohsm = PicoHSM(args.pin, slot=args.slot)
# Following commands may raise APDU exception on error
if (args.command == 'initialize'):
@@ -499,7 +574,14 @@ def main(args):
keygen(picohsm, args)
elif (args.command == 'phy'):
phy(picohsm, args)
elif (args.command == 'otp'):
otp(picohsm, args)
elif (args.command == 'reboot'):
reboot(picohsm, args)
elif (args.command == 'memory'):
memory(picohsm, args)
elif (args.command == 'bip32'):
bip32(picohsm, args)
def run():
args = parse_args()

View File

@@ -2,16 +2,55 @@
git submodule update --init --recursive
sudo apt update
if [[ $1 == "pico" ]]; then
sudo apt install -y cmake gcc-arm-none-eabi libnewlib-arm-none-eabi libstdc++-arm-none-eabi-newlib
git clone https://github.com/raspberrypi/pico-sdk
cd pico-sdk
git checkout tags/2.1.1
git submodule update --init
cd ..
git clone https://github.com/raspberrypi/picotool
cd picotool
git submodule update --init
mkdir build
cd build
if [[ $1 == "pico" ]]; then
cmake -DPICO_SDK_PATH=../../pico-sdk ..
make -j`nproc`
sudo make install
cd ../..
mkdir build_pico
cd build_pico
cmake -DPICO_SDK_PATH=../pico-sdk ..
else
cmake -DENABLE_EMULATION=1 ..
fi
make
cd ..
elif [[ $1 == "esp32" ]]; then
sudo apt install -y git wget flex bison gperf python3 python3-pip python3-venv cmake ninja-build ccache libffi-dev libssl-dev dfu-util libusb-1.0-0
git clone --recursive https://github.com/espressif/esp-idf.git
cd esp-idf
git checkout tags/v5.5
./install.sh esp32s3
. ./export.sh
cd ..
idf.py set-target esp32s3
idf.py all
mkdir -p release
cd build
esptool.py --chip ESP32-S3 merge_bin -o ../release/pico_hsm_esp32-s3.bin @flash_args
cd ..
cd esp-idf
./install.sh esp32s2
. ./export.sh
cd ..
idf.py set-target esp32s2
idf.py all
mkdir -p release
cd build
esptool.py --chip ESP32-S2 merge_bin -o ../release/pico_hsm_esp32-s2.bin @flash_args
cd ..
else
mkdir build
cd build
cmake -DENABLE_EMULATION=1 ..
make
fi