Compare commits
292 Commits
v3.4
...
v4.0-eddsa
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7493f9eb3e | ||
|
|
d44b780970 | ||
|
|
e7080d6f82 | ||
|
|
9258c9ff70 | ||
|
|
ad18577e98 | ||
|
|
3cae928de8 | ||
|
|
b429616895 | ||
|
|
0c2e728c35 | ||
|
|
5630043a4d | ||
|
|
c1a47ed023 | ||
|
|
bf2f961b85 | ||
|
|
0811b8022e | ||
|
|
fd12758551 | ||
|
|
c65f921188 | ||
|
|
55cf9292d2 | ||
|
|
db5c7adef4 | ||
|
|
d3751e3918 | ||
|
|
d708158fea | ||
|
|
dc979194fa | ||
|
|
237e687c3b | ||
|
|
ed89175edc | ||
|
|
9a7be98e6e | ||
|
|
c4a08aff0f | ||
|
|
223fc117dd | ||
|
|
d1fb4d0c65 | ||
|
|
47acef71c8 | ||
|
|
bb641ee134 | ||
|
|
99c777c780 | ||
|
|
79f76a176d | ||
|
|
dd68554782 | ||
|
|
f20fdc9bda | ||
|
|
e7d4a5dd3d | ||
|
|
b4671c2ecb | ||
|
|
50a29519bd | ||
|
|
54cdbfc22c | ||
|
|
4a40cebe1f | ||
|
|
87ffd21543 | ||
|
|
7cb0bbf982 | ||
|
|
07079b6ba1 | ||
|
|
294ca81d7d | ||
|
|
218660e694 | ||
|
|
de89d61359 | ||
|
|
8e8192362c | ||
|
|
25c93c279f | ||
|
|
001d076fdf | ||
|
|
35d5d5e94e | ||
|
|
b034303193 | ||
|
|
623cf10dba | ||
|
|
fdc41e5856 | ||
|
|
5d0dc210da | ||
|
|
a674410826 | ||
|
|
920d22212a | ||
|
|
aeeb540a2f | ||
|
|
be071b0bc1 | ||
|
|
8bbbdb4dd8 | ||
|
|
45b633cc9d | ||
|
|
842919a26b | ||
|
|
3dbcefea85 | ||
|
|
60038f9345 | ||
|
|
d8c7fb0856 | ||
|
|
d6456b4dde | ||
|
|
ac781c1db6 | ||
|
|
c3b66773e8 | ||
|
|
3ca23b932c | ||
|
|
9fad920c3b | ||
|
|
38bef5b43f | ||
|
|
2034e436d1 | ||
|
|
215221b30e | ||
|
|
de4d95beb8 | ||
|
|
963b6f4f87 | ||
|
|
fa9b244c42 | ||
|
|
2b92d89ab7 | ||
|
|
a1d7733b95 | ||
|
|
39f1041dbb | ||
|
|
2e4fc568db | ||
|
|
4f4e6e09a2 | ||
|
|
08c0aaee6f | ||
|
|
de98e79c99 | ||
|
|
481cd5fd69 | ||
|
|
d9a8826a32 | ||
|
|
d82affa880 | ||
|
|
ab31a6615c | ||
|
|
677cceb130 | ||
|
|
29967c067a | ||
|
|
2974aa234a | ||
|
|
d90b296237 | ||
|
|
e98b26fee5 | ||
|
|
2086a68c53 | ||
|
|
74afa07512 | ||
|
|
e96e1d0097 | ||
|
|
4d47f0224e | ||
|
|
58692b2711 | ||
|
|
a5ab1cabc5 | ||
|
|
1c7cdc8564 | ||
|
|
d74b3418bc | ||
|
|
fb5be153ed | ||
|
|
0ac71f2fff | ||
|
|
6ec5235cc3 | ||
|
|
ff74d6306e | ||
|
|
ba562da00e | ||
|
|
98e9b72b42 | ||
|
|
1b0d23cf24 | ||
|
|
3ccff7881f | ||
|
|
a3bf2e9e14 | ||
|
|
88ff27f354 | ||
|
|
ed2925cfb6 | ||
|
|
cc19f8f061 | ||
|
|
b6831a4650 | ||
|
|
652a0f0d21 | ||
|
|
9dbf4b3172 | ||
|
|
76522829ef | ||
|
|
6b1eeb4004 | ||
|
|
2693ab4926 | ||
|
|
5d21e39aa6 | ||
|
|
1bf0d6337b | ||
|
|
1950b03d35 | ||
|
|
4be258f4c7 | ||
|
|
eddb1baf7b | ||
|
|
11bb00e186 | ||
|
|
aaed6bd7b6 | ||
|
|
2853b38b08 | ||
|
|
654cb1e4e0 | ||
|
|
185d19504f | ||
|
|
dbe0ef19de | ||
|
|
c3b57b229f | ||
|
|
43c46e9112 | ||
|
|
d5af9160c1 | ||
|
|
e27c8d4ff6 | ||
|
|
2ecfff0ebb | ||
|
|
3057aba041 | ||
|
|
011a594fe4 | ||
|
|
448d61dd2d | ||
|
|
fa821c43c8 | ||
|
|
9db3e78d32 | ||
|
|
b74c4070d1 | ||
|
|
a7770a7e57 | ||
|
|
78cbe59e64 | ||
|
|
42a9434c50 | ||
|
|
11a3472941 | ||
|
|
2f177eb8df | ||
|
|
c97680772d | ||
|
|
345ae2be69 | ||
|
|
ba036f4c0f | ||
|
|
4493afa84d | ||
|
|
d118b787a2 | ||
|
|
205356b848 | ||
|
|
c435764978 | ||
|
|
2e633abb2c | ||
|
|
3514c7ad82 | ||
|
|
4bba3c6f64 | ||
|
|
8321996a14 | ||
|
|
c3af303468 | ||
|
|
c44d7db4e1 | ||
|
|
cb1bba4f13 | ||
|
|
48301a5d71 | ||
|
|
1105a1263c | ||
|
|
37421d9aad | ||
|
|
d906df2809 | ||
|
|
08e7d74a81 | ||
|
|
433e509c94 | ||
|
|
9f08d612ae | ||
|
|
173ca7678d | ||
|
|
3d7f714936 | ||
|
|
f4a537f156 | ||
|
|
f09654ccf4 | ||
|
|
7506ccd263 | ||
|
|
ee442ac084 | ||
|
|
b94810d31d | ||
|
|
2c4be41ecf | ||
|
|
447d223de4 | ||
|
|
4f9f7f14fe | ||
|
|
6699913eff | ||
|
|
b0057bc3fe | ||
|
|
e3a773d145 | ||
|
|
10a47f9177 | ||
|
|
9f49a144ac | ||
|
|
e67a7091ff | ||
|
|
1d3232df36 | ||
|
|
7376817724 | ||
|
|
5e801fbae7 | ||
|
|
e18c413268 | ||
|
|
0e1c82196a | ||
|
|
c6a5272340 | ||
|
|
a6072b4ce8 | ||
|
|
5bdba8e1e8 | ||
|
|
5df4e62f81 | ||
|
|
685c7f25fc | ||
|
|
faef2dc278 | ||
|
|
22d8793683 | ||
|
|
32c8bc4a24 | ||
|
|
b5174d64af | ||
|
|
235bf342b3 | ||
|
|
57188ff877 | ||
|
|
f631e4a5f3 | ||
|
|
f880ee6c93 | ||
|
|
6af4cc7fec | ||
|
|
e3f1f45a9f | ||
|
|
fe315e7326 | ||
|
|
02903bbc65 | ||
|
|
ee3ee21e40 | ||
|
|
c6c00e7e43 | ||
|
|
29544a3f17 | ||
|
|
5135404083 | ||
|
|
55520ce184 | ||
|
|
525b05b7ef | ||
|
|
b61a34d415 | ||
|
|
0eea0fb096 | ||
|
|
82c03ee6c4 | ||
|
|
20dfbcaaed | ||
|
|
a9fb170c58 | ||
|
|
46d85c029e | ||
|
|
1c6f4cfd7f | ||
|
|
526869bc06 | ||
|
|
279df32acc | ||
|
|
c402b884cc | ||
|
|
8316196b42 | ||
|
|
7a6dafd7b6 | ||
|
|
6d3809a792 | ||
|
|
f22f58f983 | ||
|
|
405bf92e18 | ||
|
|
b5b6dcd2e6 | ||
|
|
d637dbec01 | ||
|
|
ebcac9dfdc | ||
|
|
510b148adf | ||
|
|
371ae93fcd | ||
|
|
f5e875a6b7 | ||
|
|
ad3304a384 | ||
|
|
4d647ba3c8 | ||
|
|
008db87fa7 | ||
|
|
1d80b45439 | ||
|
|
17560034ec | ||
|
|
8b0d85fbd4 | ||
|
|
3dcb2e9d70 | ||
|
|
0f12ff1c48 | ||
|
|
2a5fe1cc6d | ||
|
|
5e0f62265d | ||
|
|
0990805fb6 | ||
|
|
18bcf532e7 | ||
|
|
9f0316aedd | ||
|
|
088002863c | ||
|
|
7876f4b32a | ||
|
|
a5e3d4e0e5 | ||
|
|
0c842773d2 | ||
|
|
0aaf339353 | ||
|
|
efba39adc5 | ||
|
|
13755cb4d5 | ||
|
|
11a30863e8 | ||
|
|
a69d06b2d9 | ||
|
|
1c7bc18161 | ||
|
|
86ce01cac2 | ||
|
|
9cb60ba420 | ||
|
|
99f1620e7d | ||
|
|
755570e01a | ||
|
|
4b264597d6 | ||
|
|
67e3d908b3 | ||
|
|
7ae76354ef | ||
|
|
9291c2b4e3 | ||
|
|
657ee18730 | ||
|
|
132054c9b9 | ||
|
|
2a3b9b7474 | ||
|
|
4e73723747 | ||
|
|
09724d95db | ||
|
|
c1bfb597bc | ||
|
|
fd53b88397 | ||
|
|
11e5338736 | ||
|
|
3660120b11 | ||
|
|
75ca1b57d9 | ||
|
|
7af67713e7 | ||
|
|
63c465138b | ||
|
|
4d569df108 | ||
|
|
bee6a7bb92 | ||
|
|
e4583eb9c0 | ||
|
|
1c8582365d | ||
|
|
daf71678c5 | ||
|
|
26f0775772 | ||
|
|
ed674b379c | ||
|
|
6aa8d37d07 | ||
|
|
963456051e | ||
|
|
1e90699a3f | ||
|
|
f8110a9d75 | ||
|
|
d81b21695f | ||
|
|
51e9e6722e | ||
|
|
dba4630895 | ||
|
|
ee73c6e781 | ||
|
|
2f63966c60 | ||
|
|
e624f9ff72 | ||
|
|
fb4ff9424e | ||
|
|
63b245b858 | ||
|
|
cd525d91a3 | ||
|
|
8fd3b4d858 | ||
|
|
3c160f69c0 | ||
|
|
2c9fa8b19f |
4
.github/FUNDING.yml
vendored
Normal file
4
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1,4 @@
|
|||||||
|
# These are supported funding model platforms
|
||||||
|
|
||||||
|
github: polhenarejos
|
||||||
|
custom: ["https://www.paypal.me/polhenarejos"]
|
||||||
14
.github/workflows/codeql.yml
vendored
14
.github/workflows/codeql.yml
vendored
@@ -13,12 +13,13 @@ name: "CodeQL"
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ "master", "development" ]
|
branches: [ "master", "development", "development-eddsa" ]
|
||||||
pull_request:
|
pull_request:
|
||||||
# The branches below must be a subset of the branches above
|
# The branches below must be a subset of the branches above
|
||||||
branches: [ "master", "development" ]
|
branches: [ "master", "development", "development-eddsa" ]
|
||||||
schedule:
|
schedule:
|
||||||
- cron: '23 5 * * 4'
|
- cron: '23 5 * * 4'
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
analyze:
|
analyze:
|
||||||
@@ -35,6 +36,7 @@ jobs:
|
|||||||
language: [ 'cpp', 'python' ]
|
language: [ 'cpp', 'python' ]
|
||||||
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
|
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
|
||||||
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
|
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
|
||||||
|
mode: [ 'pico', 'local' ]
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository
|
- name: Checkout repository
|
||||||
@@ -48,11 +50,11 @@ jobs:
|
|||||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||||
# By default, queries listed here will override any specified in a config file.
|
# By default, queries listed here will override any specified in a config file.
|
||||||
# Prefix the list here with "+" to use these queries and those in the config file.
|
# Prefix the list here with "+" to use these queries and those in the config file.
|
||||||
|
|
||||||
# Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
|
# Details on CodeQL's query packs refer to : https://docs.github.com/en/code-security/code-scanning/automatically-scanning-your-code-for-vulnerabilities-and-errors/configuring-code-scanning#using-queries-in-ql-packs
|
||||||
# queries: security-extended,security-and-quality
|
# queries: security-extended,security-and-quality
|
||||||
|
|
||||||
|
|
||||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||||
# If this step fails, then you should remove it and run the build manually (see below)
|
# If this step fails, then you should remove it and run the build manually (see below)
|
||||||
# - name: Autobuild
|
# - name: Autobuild
|
||||||
@@ -61,12 +63,12 @@ jobs:
|
|||||||
# ℹ️ Command-line programs to run using the OS shell.
|
# ℹ️ Command-line programs to run using the OS shell.
|
||||||
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
|
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
|
||||||
|
|
||||||
# If the Autobuild fails above, remove it and uncomment the following three lines.
|
# If the Autobuild fails above, remove it and uncomment the following three lines.
|
||||||
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
|
# modify them (or add more) to build your code if your project, please refer to the EXAMPLE below for guidance.
|
||||||
|
|
||||||
- run: |
|
- run: |
|
||||||
echo "Run, Build Application using script"
|
echo "Run, Build Application using script"
|
||||||
./workflows/autobuild.sh
|
./workflows/autobuild.sh ${{ matrix.mode }}
|
||||||
|
|
||||||
- name: Perform CodeQL Analysis
|
- name: Perform CodeQL Analysis
|
||||||
uses: github/codeql-action/analyze@v2
|
uses: github/codeql-action/analyze@v2
|
||||||
|
|||||||
42
.github/workflows/test.yml
vendored
42
.github/workflows/test.yml
vendored
@@ -13,18 +13,17 @@ name: "Emulation and test"
|
|||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [ "master", "development" ]
|
branches: [ "master", "development", "development-eddsa" ]
|
||||||
pull_request:
|
pull_request:
|
||||||
# The branches below must be a subset of the branches above
|
# The branches below must be a subset of the branches above
|
||||||
branches: [ "master", "development" ]
|
branches: [ "master", "development", "development-eddsa" ]
|
||||||
schedule:
|
schedule:
|
||||||
- cron: '23 5 * * 4'
|
- cron: '23 5 * * 4'
|
||||||
|
workflow_dispatch:
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
build:
|
||||||
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- name: Checkout repository and submodules
|
- name: Checkout repository and submodules
|
||||||
uses: actions/checkout@v3
|
uses: actions/checkout@v3
|
||||||
@@ -32,5 +31,36 @@ jobs:
|
|||||||
submodules: recursive
|
submodules: recursive
|
||||||
- name: Build in container
|
- name: Build in container
|
||||||
run: ./tests/build-in-docker.sh
|
run: ./tests/build-in-docker.sh
|
||||||
- name: Start emulation and test
|
- name: Export image
|
||||||
run: ./tests/run-test-in-docker.sh
|
run: |
|
||||||
|
mkdir -p artifacts
|
||||||
|
docker save pico-hsm-test:bullseye -o artifacts/docker-image.tar
|
||||||
|
- name: Temporarily save image
|
||||||
|
uses: actions/upload-artifact@v3
|
||||||
|
with:
|
||||||
|
name: docker-artifact
|
||||||
|
path: artifacts
|
||||||
|
retention-days: 1
|
||||||
|
|
||||||
|
test:
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
needs: build
|
||||||
|
strategy:
|
||||||
|
matrix:
|
||||||
|
suite: ["pkcs11", "pytest", "sc-hsm-pkcs11"]
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository and submodules
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
with:
|
||||||
|
submodules: recursive
|
||||||
|
- name: Retrieve saved image
|
||||||
|
uses: actions/download-artifact@v3
|
||||||
|
with:
|
||||||
|
name: docker-artifact
|
||||||
|
path: artifacts
|
||||||
|
- name: Load image
|
||||||
|
run: |
|
||||||
|
cd artifacts
|
||||||
|
docker load -q -i docker-image.tar
|
||||||
|
- name: Test ${{ matrix.suite }}
|
||||||
|
run: ./tests/run-test-in-docker.sh ${{ matrix.suite }}
|
||||||
|
|||||||
6
.gitmodules
vendored
6
.gitmodules
vendored
@@ -1,3 +1,3 @@
|
|||||||
[submodule "pico-hsm-sdk"]
|
[submodule "pico-keys-sdk"]
|
||||||
path = pico-hsm-sdk
|
path = pico-keys-sdk
|
||||||
url = ../pico-hsm-sdk
|
url = https://github.com/polhenarejos/pico-keys-sdk
|
||||||
|
|||||||
@@ -17,6 +17,12 @@
|
|||||||
|
|
||||||
cmake_minimum_required(VERSION 3.13)
|
cmake_minimum_required(VERSION 3.13)
|
||||||
|
|
||||||
|
if(ESP_PLATFORM)
|
||||||
|
set(EXTRA_COMPONENT_DIRS src pico-keys-sdk/src)
|
||||||
|
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||||
|
set(USB_ITF_CCID 1)
|
||||||
|
set(USB_ITF_WCID 1)
|
||||||
|
else()
|
||||||
if(ENABLE_EMULATION)
|
if(ENABLE_EMULATION)
|
||||||
else()
|
else()
|
||||||
include(pico_sdk_import.cmake)
|
include(pico_sdk_import.cmake)
|
||||||
@@ -27,13 +33,19 @@ project(pico_hsm C CXX ASM)
|
|||||||
set(CMAKE_C_STANDARD 11)
|
set(CMAKE_C_STANDARD 11)
|
||||||
set(CMAKE_CXX_STANDARD 17)
|
set(CMAKE_CXX_STANDARD 17)
|
||||||
|
|
||||||
if(ENABLE_EMULATION)
|
if(NOT ENABLE_EMULATION)
|
||||||
else()
|
|
||||||
pico_sdk_init()
|
pico_sdk_init()
|
||||||
endif()
|
endif()
|
||||||
|
|
||||||
add_executable(pico_hsm)
|
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}
|
set(SOURCES ${SOURCES}
|
||||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/sc_hsm.c
|
${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_select.c
|
||||||
@@ -62,37 +74,52 @@ set(SOURCES ${SOURCES}
|
|||||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_session_pin.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_puk_auth.c
|
||||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_pso.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/cvc.c
|
||||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/files.c
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/files.c
|
||||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/kek.c
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/kek.c
|
||||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/oid.c
|
|
||||||
|
|
||||||
)
|
)
|
||||||
set(USB_ITF_CCID 1)
|
set(USB_ITF_CCID 1)
|
||||||
include(pico-hsm-sdk/pico_hsm_sdk_import.cmake)
|
set(USB_ITF_WCID 1)
|
||||||
|
include(pico-keys-sdk/pico_keys_sdk_import.cmake)
|
||||||
|
if(ESP_PLATFORM)
|
||||||
|
project(pico_hsm)
|
||||||
|
endif()
|
||||||
|
|
||||||
set(INCLUDES ${INCLUDES}
|
set(INCLUDES ${INCLUDES}
|
||||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm
|
||||||
)
|
)
|
||||||
|
if(NOT ESP_PLATFORM)
|
||||||
target_sources(pico_hsm PUBLIC ${SOURCES})
|
target_sources(pico_hsm PUBLIC ${SOURCES})
|
||||||
target_include_directories(pico_hsm PUBLIC ${INCLUDES})
|
target_include_directories(pico_hsm PUBLIC ${INCLUDES})
|
||||||
|
|
||||||
target_compile_options(pico_hsm PUBLIC
|
target_compile_options(pico_hsm PUBLIC
|
||||||
-Wall
|
-Wall
|
||||||
-Werror
|
|
||||||
)
|
)
|
||||||
|
if (NOT MSVC)
|
||||||
|
target_compile_options(pico_hsm PUBLIC
|
||||||
|
-Werror
|
||||||
|
)
|
||||||
|
endif()
|
||||||
|
|
||||||
if(ENABLE_EMULATION)
|
if(ENABLE_EMULATION)
|
||||||
|
if (NOT MSVC)
|
||||||
target_compile_options(pico_hsm PUBLIC
|
target_compile_options(pico_hsm PUBLIC
|
||||||
-fdata-sections
|
-fdata-sections
|
||||||
-ffunction-sections
|
-ffunction-sections
|
||||||
)
|
)
|
||||||
|
endif()
|
||||||
if(APPLE)
|
if(APPLE)
|
||||||
target_link_options(pico_hsm PUBLIC
|
target_link_options(pico_hsm PUBLIC
|
||||||
-Wl,-dead_strip
|
-Wl,-dead_strip
|
||||||
)
|
)
|
||||||
|
elseif(MSVC)
|
||||||
|
target_compile_options(pico_hsm PUBLIC
|
||||||
|
-WX
|
||||||
|
)
|
||||||
|
|
||||||
|
target_link_libraries(pico_hsm PUBLIC wsock32 ws2_32 Bcrypt)
|
||||||
else()
|
else()
|
||||||
target_link_options(pico_hsm PUBLIC
|
target_link_options(pico_hsm PUBLIC
|
||||||
-Wl,--gc-sections
|
-Wl,--gc-sections
|
||||||
@@ -100,6 +127,6 @@ target_link_options(pico_hsm PUBLIC
|
|||||||
endif (APPLE)
|
endif (APPLE)
|
||||||
else()
|
else()
|
||||||
pico_add_extra_outputs(pico_hsm)
|
pico_add_extra_outputs(pico_hsm)
|
||||||
|
target_link_libraries(pico_hsm PRIVATE pico_keys_sdk pico_stdlib pico_multicore hardware_flash hardware_sync hardware_adc pico_unique_id hardware_rtc tinyusb_device tinyusb_board)
|
||||||
target_link_libraries(pico_hsm PRIVATE pico_hsm_sdk pico_stdlib pico_multicore hardware_flash hardware_sync hardware_adc pico_unique_id hardware_rtc tinyusb_device tinyusb_board)
|
endif()
|
||||||
endif()
|
endif()
|
||||||
|
|||||||
278
README.md
278
README.md
@@ -1,155 +1,184 @@
|
|||||||
# Raspberry Pico HSM
|
# Raspberry Pico HSM
|
||||||
This is a project to create a Hardware Security Module (HSM) with a Raspberry Pico. It converts your Pico board into a HSM which is able to generate and store private keys, encrypt or decrypt with AES or signing data without to disclose the private key. In detail, the private key never leaves the board and it cannot be retrieved as it is encrypted in the flash memory.
|
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
|
## Capabilities
|
||||||
### > Key generation and encrypted storage
|
### > Key generation and encrypted storage
|
||||||
Private and secret keys are stored with a master AES 256 key (DKEK). The DKEK is, at the same time, encrypted with a hashed and salted version of the PIN.
|
Private and secret keys are secured using a master AES 256 key (MKEK). The MKEK is encrypted with a hashed and salted version of the PIN.
|
||||||
**No private/secret keys, DKEK or PIN are stored in plain text ever. Never.**
|
**No private/secret keys, DKEK or PIN are stored in plain text ever. Never.**
|
||||||
|
|
||||||
### > RSA key generation from 1024 to 4096 bits
|
### > RSA Key Generation (1024 to 4096 Bits)
|
||||||
RSA key generation in place for 1024, 2048, 3072 and 4096 bits. Private keys never leave the device.
|
RSA key generation is supported for 1024, 2048, 3072, and 4096 bits. Private keys never leave the device.
|
||||||
|
|
||||||
### > ECDSA key generation from 192 to 521 bits
|
### > ECDSA Key Generation (192 to 521 Bits)
|
||||||
ECDSA key generation in place for different curves, from 192 to 521 bits.
|
ECDSA key generation supports various curves from 192 to 521 bits.
|
||||||
|
|
||||||
### > ECC curves
|
### > ECC Curves
|
||||||
It supports secp192r1, secp256r1, secp384r1, secp521r1, brainpoolP256r1, brainpoolP384r1, brainpoolP512r1, secp192k1 (insecure), secp256k1 curves. Also Curve25519 and Curve448.
|
Supported ECC curves include secp192r1, secp256r1, secp384r1, secp521r1, brainpoolP256r1, brainpoolP384r1, brainpoolP512r1, secp192k1 (insecure), secp256k1, Curve25519, and Curve448.
|
||||||
|
|
||||||
### > SHA1, SHA224, SHA256, SHA384, SHA512 digests
|
### > SHA Digests
|
||||||
ECDSA and RSA signature can be combined with SHA digest in place.
|
ECDSA and RSA signatures can be combined with SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512 digests.
|
||||||
|
|
||||||
### > Multiple RSA signature algorithms
|
### > Multiple RSA Signature Algorithms
|
||||||
It supports RSA-PSS, RSA-PKCS and raw RSA signatures.
|
Supported RSA signature algorithms include RSA-PSS, RSA-PKCS, and raw RSA signatures.
|
||||||
|
|
||||||
### > ECDSA raw and hash signature
|
### > ECDSA Signatures
|
||||||
ECDSA signatures can be in raw or pre-hashed formats.
|
ECDSA signatures can be raw or pre-hashed.
|
||||||
|
|
||||||
### > ECDH key derivation
|
### > ECDH Key Derivation
|
||||||
It supports the calculation of shared secrets with ECDH algorithm.
|
Supports the ECDH algorithm for calculating shared secrets.
|
||||||
|
|
||||||
### > EC private key derivation
|
### > EC Private Key Derivation
|
||||||
It allows ECDSA key derivation.[^1]
|
Allows ECDSA key derivation.
|
||||||
|
|
||||||
### > RSA-OEP and RSA-X-509 decryption
|
### > RSA Decryption
|
||||||
It allows private decryption in place with RSA-OEP and RSA-X-509 algorithms.
|
Supports RSA-OEP and RSA-X.509 decryption.
|
||||||
|
|
||||||
### > AES key generation
|
### > AES Key Generation
|
||||||
It supports AES key generation in place with keys of 128, 192 and 256 bits.
|
Supports AES key generation with keys of 128, 192, and 256 bits.
|
||||||
|
|
||||||
### > AES-CBC encryption/decryption
|
### > AES-CBC Encryption/Decryption
|
||||||
AES encryption and decryption is performed in place.
|
Performs AES-CBC encryption and decryption.
|
||||||
|
|
||||||
|
### > Advanced AES Modes
|
||||||
|
Supports AES encryption and decryption in ECB, CBC, CFB, OFB, XTS, CTR, GCM, and CCM modes, with customizable IV/nonce and additional authenticated data (AAD).[^4]
|
||||||
|
|
||||||
|
### > AES Key Generation (128, 192, 256, 512 Bits)
|
||||||
|
Supports AES key generation up to 512 bits, useful for AES XTS where two 256-bit keys are concatenated.
|
||||||
|
|
||||||
### > CMAC
|
### > CMAC
|
||||||
It supports AES-CMAC authentication.[^1]
|
Supports AES-CMAC authentication.[^1]
|
||||||
|
|
||||||
### > AES derivation
|
### > AES Secret Key Derivation
|
||||||
It supports AES secret key derivation.[^1]
|
Supports AES secret key derivation.[^1]
|
||||||
|
|
||||||
### > PIN authorization
|
### > PIN Authorization
|
||||||
Private and secret keys cannot be used without prior PIN authentication. It supports alphanumeric PIN.
|
Private and secret keys require prior PIN authentication. Supports alphanumeric PINs.
|
||||||
|
|
||||||
### > PKCS11 compliant interface
|
### > PKCS11 Compliant Interface
|
||||||
The module can be interfaced with PKCS11 standard.
|
Interfacing with the PKCS11 standard is supported.
|
||||||
|
|
||||||
### > HRNG (hardware random number generator)
|
### > Hardware Random Number Generator (HRNG)
|
||||||
It contains a harware random number generator properly modeled to guarantee maximum entropy.
|
Contains an HRNG designed for maximum entropy.
|
||||||
|
|
||||||
### > Device Key Encryption Key (DKEK) shares
|
### > Device Key Encryption Key (DKEK) Shares
|
||||||
It supports DKEK share imports. DKEK are used to wrap, unwrap and encrypt private and secret keys in the device.
|
Supports importing DKEK shares to wrap, unwrap, and encrypt keys.
|
||||||
|
|
||||||
### > DKEK n-of-m threshold scheme
|
### > DKEK n-of-m Threshold Scheme
|
||||||
It supports a n-of-m threshold scheme to minimize outage when a DKEK custodian is not available during the import process.
|
Supports an n-of-m threshold scheme to prevent outages when a DKEK custodian is unavailable.
|
||||||
|
|
||||||
### > USB/CCID support with OpenSC, openssl, etc.
|
### > USB/CCID Support
|
||||||
Pico HSM has a full USB CCID stack to communicate with the host via OpenSC and PCSC. It allows the use of frontend applications such as OpenSSL via PKCS11 module.
|
Full USB CCID stack for communication with the host via OpenSC and PCSC, allowing the use of frontend applications like OpenSSL via the PKCS11 module.
|
||||||
|
|
||||||
### > Extended APDU support
|
### > Extended APDU Support
|
||||||
It supports extended APDU packets, which allows up to 65535 bytes.
|
Supports extended APDU packets, allowing up to 65535 bytes.
|
||||||
|
|
||||||
### > CV Certificates
|
### > CV Certificates
|
||||||
Pico HSM manipulates CVC certificates and requests to minimize the storage of internal certificates.
|
Handles CVC certificates and requests to minimize internal certificate storage.
|
||||||
|
|
||||||
### > Attestation
|
### > Attestation
|
||||||
Every generated key is attached to a certificate, signed by an external PKI to ensure that a particular key is effectively generated by this specific device.
|
Each generated key is attached to a certificate signed by an external PKI, ensuring the key was generated by the specific device.
|
||||||
|
|
||||||
### > Import external private keys and certificates
|
### > Import External Keys and Certificates
|
||||||
It allows private key and certificates import via WKY or PKCS#12 files.[^2][^3]
|
Allows importing private keys and certificates via WKY or PKCS#12 files.[^2][^3]
|
||||||
|
|
||||||
### > Tranport PIN
|
### > Transport PIN
|
||||||
It allows transport PIN for provisioning and forcing to set a new PIN.[^2] It is a tampered mechanism that ensures the device has not been unsealed during the transportation from the issuer to the legitimate user.
|
Allows a transport PIN for provisioning, ensuring the device has not been tampered with during transportation.[^2]
|
||||||
|
|
||||||
### > Press-to-confirm button
|
### > Press-to-Confirm Button
|
||||||
It allows the use of BOOTSEL button to confirm operations with private/secret keys, such as signatures and decryption. When a private/secret key is loaded, the user has 15 seconds to press the button to confirm the operation.
|
Uses the BOOTSEL button to confirm operations with private/secret keys, providing a 15-second window to confirm the operation to protect against unauthorized use.
|
||||||
This feature protects the user from unwanted uses from background applications that may sign data without user notice.
|
|
||||||
|
|
||||||
### > Store and retrieve binary data
|
### > Store and Retrieve Binary Data
|
||||||
It allows the storage of arbitrary files with binary data.
|
Allows the storage of arbitrary binary data files.
|
||||||
|
|
||||||
### > Real time clock (RTC)
|
### > Real-Time Clock (RTC)
|
||||||
Pico HSM has a RTC with external datetime setting and getting.
|
Includes an RTC with external date and time setting and retrieval.
|
||||||
|
|
||||||
### > Secure Messaging (secure channel)
|
### > Secure Messaging
|
||||||
Pico HSM supports secure channel, where the data packets between the host and device are encrypted to avoid man-in-the-middle attacks.
|
Supports secure channels to encrypt data packets between the host and device, preventing man-in-the-middle attacks.
|
||||||
|
|
||||||
### > Session PIN
|
### > Session PIN
|
||||||
A specific session PIN can be set during the session opening to avoid the systemmatic use of PIN.
|
A specific session PIN can be set during session opening to avoid systematic PIN usage.
|
||||||
|
|
||||||
### > PKI CVCert remote issuing for Secure Message
|
### > PKI CVCert Remote Issuing for Secure Messaging
|
||||||
Secure channel messages are secured with a certificate issued by an external PKI.
|
Secure channel messages are secured with a certificate issued by an external PKI.
|
||||||
|
|
||||||
### > Multiple key domains
|
### > Multiple Key Domains
|
||||||
Key domains are domains to store separate private/secret keys. Each domain is protected by a DKEK, independent from the other domains. Private/secret keys can be generated in different key domains to be used with separated DKEK.
|
Supports separate key domains protected by independent DKEKs, allowing different keys in different domains.
|
||||||
Therefore, a single device may contain different domains with independent keys.
|
|
||||||
|
|
||||||
### > Key usage counter
|
### > Key Usage Counter
|
||||||
A key usage counter is a counter that is reduced by 1 everytime that the private/secret key is used for signing, decrypting, derivation, etc. When it reaches 0, the key is disabled and cannot be used anymore.
|
Tracks and limits the usage of private/secret keys, disabling keys once their usage counter reaches zero.
|
||||||
|
|
||||||
Key usage can also be used to perform and auditory and track the usage of a particular key.
|
### > Public Key Authentication (PKA)
|
||||||
|
Supports PKA for enhanced security, requiring a secondary device for authentication using a challenge-response mechanism.
|
||||||
### > Public Key Authentication
|
|
||||||
Public Key Authentication (PKA) allows to authenticate by using a secondary device with a private key and a registered public key in the primary device. A challenge is generated by the primary Pico HSM and given to the secondary for signature. The secondary device signs the challenge and returns the signature. Then, the primary device verifies the signature with the registered public key and if it is valid, it grants full access, as normal PIN authentication.
|
|
||||||
|
|
||||||
In PKA, the PIN is used for protecting the DKEK, as classic method with only PIN, and PKA is used for adding an extra security layer. Therefore, this mechanism provides a higher degree of security, since it needs a secondary Pico HSM to authenticate the primary one.
|
|
||||||
|
|
||||||
### > Secure Lock
|
### > Secure Lock
|
||||||
An extra layer can be added to the device by adding a private key stored on the computer to lock that Pico HSM to the specific computer. The content will be completely encrypted with a private key only available from a specific computer.
|
Adds an extra layer of security by locking the Pico HSM to a specific computer using a private key.
|
||||||
|
|
||||||
### > ChaCha20-Poly1305
|
### > ChaCha20-Poly1305
|
||||||
This is a novel fast and efficient symmetric encryption algorithm. Similarly to AES, it can be used to cipher your private data.
|
Supports the ChaCha20-Poly1305 encryption algorithm for secure data encryption.[^4]
|
||||||
|
|
||||||
### > X25519 and X448
|
### > X25519 and X448
|
||||||
Both cruves Curve25519 and Curve448 are supported for doing DH X25519 and X448. Remember that cannot be used for signing.
|
Supports DH X25519 and X448 for key agreement, though these cannot be used for signing.
|
||||||
|
|
||||||
### > Key Derivation Functions: HKDF, PBKDF2 and X963-KDF
|
### > Key Derivation Functions
|
||||||
It supports symmetric key derivations from different standards and RFC.
|
Supports HKDF, PBKDF2, and X963-KDF for symmetric key derivation.
|
||||||
|
|
||||||
### > HMAC
|
### > HMAC
|
||||||
It supports performing HMAC from a secret key on a arbitrary data with SHA digest algorithm.
|
Supports HMAC generation with SHA digest algorithms.
|
||||||
|
|
||||||
|
### > CMAC
|
||||||
|
Supports CMAC with AES for keys of 128, 192, and 256 bits.
|
||||||
|
|
||||||
|
### > XKEK
|
||||||
|
Supports an advanced key sharing scheme (XKEK) for securely wrapping and unwrapping keys within authorized domains.
|
||||||
|
|
||||||
|
### > Master Key Encryption Key (MKEK)
|
||||||
|
Uses an MKEK to securely store all keys, encrypted with an ephemeral key derived from the hashed PIN.
|
||||||
|
|
||||||
|
### > Hierarchical Deterministic Key Generation
|
||||||
|
Supports BIP32 for asymmetric key derivation and SLIP10 for symmetric key derivation, enabling crypto wallet deployment with infinite key generation. Supports NIST 256 and Koblitz 256 curves for master key generation.[^4]
|
||||||
|
|
||||||
[^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`).
|
[^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.
|
[^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 the DKEK shares are available during the import process.
|
[^3]: Imports are available only if the Pico HSM is previously initialized with a DKEK and DKEK shares are available during the import process.
|
||||||
|
[^4]: Available by using PicoHSM python tool.
|
||||||
|
|
||||||
|
### > ESP32-S3 support
|
||||||
|
Pico HSM also supports ESP32-S3 boards, which add secure storage, flash encryption and secure boot.
|
||||||
|
|
||||||
|
### > Dynamic VID/PID
|
||||||
|
Supports setting VID & PID on-the-fly. Use `pico-hsm-tool.py` for specify VID/PID values and reboot the device.
|
||||||
|
|
||||||
|
### > Rescue Pico HSM Tool
|
||||||
|
Pico HSM Tool implements a new CCID stack to rescue the Pico HSM in case it has wrong VID/PID values and it is not recognized by the OS.
|
||||||
|
|
||||||
## Security considerations
|
## Security considerations
|
||||||
All secret keys (asymmetric and symmetric) are stored encrypted in the flash memory of the Raspberry Pico. DKEK is used as a 256 bit AES key to protect private and secret keys. Keys are never stored in RAM except for signature and decryption operations and only during the process. All keys (including DKEK) are loaded and cleared every time to avoid potential security flaws.
|
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.
|
||||||
|
|
||||||
At the same time, DKEK is encrypted with doubled salted and hashed PIN. Also, the PIN is hashed in memory during the session. Hence, PIN is never stored in plain text neither in flash nor in memory. Note that PIN is conveyed from the host to the HSM in plain text if no secure channel is provided.
|
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.
|
||||||
|
|
||||||
If the Pico is stolen the contents of private and secret keys cannot be read without the PIN, even if the flash memory is dumped.
|
In the event that the Pico is stolen, the private and secret key contents cannot be accessed without the PIN, even if the flash memory is dumped.
|
||||||
|
|
||||||
## Download
|
## Download
|
||||||
|
**If you own an ESP32-S3 board, go to [ESP32 support](https://www.picokeys.com/esp32-support/) for further information.**
|
||||||
|
|
||||||
Please, go to the Release page and download the UF2 file for your board.
|
Please, go to the Release page and download the UF2 file for your board.
|
||||||
|
|
||||||
Note that UF2 files are shiped with a dummy VID/PID to avoid license issues (FEFF:FCFD). If you are planning to use it with OpenSC or similar, you should modify Info.plist of CCID driver to add these VID/PID or use the VID/PID patcher as follows:
|
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/).
|
||||||
|
|
||||||
|
Alternatively you can use the legacy VID/PID patcher as follows:
|
||||||
`./patch_vidpid.sh VID:PID input_hsm_file.uf2 output_hsm_file.uf2`
|
`./patch_vidpid.sh VID:PID input_hsm_file.uf2 output_hsm_file.uf2`
|
||||||
|
|
||||||
You can use whatever VID/PID (i.e., 234b:0000 from FISJ), but remember that you are not authorized to distribute the binary with a VID/PID that you do not own.
|
You can use whatever VID/PID (i.e., 234b:0000 from FISJ), but remember that you are not authorized to distribute the binary with a VID/PID that you do not own.
|
||||||
|
|
||||||
|
Note that the pure-browser option [Pico Patcher tool](https://www.picokeys.com/pico-patcher/) is the most recommended.
|
||||||
|
|
||||||
## Build
|
## Build
|
||||||
Before building, ensure you have installed the toolchain for the Pico and the Pico SDK is properly located in your drive.
|
Before building, ensure you have installed the toolchain for the Pico and the Pico SDK is properly located in your drive.
|
||||||
|
|
||||||
```
|
```
|
||||||
git clone https://github.com/polhenarejos/pico-hsm
|
git clone https://github.com/polhenarejos/pico-hsm
|
||||||
|
git submodule update --init --recursive
|
||||||
cd pico-hsm
|
cd pico-hsm
|
||||||
mkdir build
|
mkdir build
|
||||||
cd build
|
cd build
|
||||||
@@ -158,17 +187,34 @@ make
|
|||||||
```
|
```
|
||||||
Note that `PICO_BOARD`, `USB_VID` and `USB_PID` are optional. If not provided, `pico` board and VID/PID `FEFF:FCFD` will be used.
|
Note that `PICO_BOARD`, `USB_VID` and `USB_PID` are optional. If not provided, `pico` board and VID/PID `FEFF:FCFD` will be used.
|
||||||
|
|
||||||
After `make` ends, the binary file `pico_hsm.uf2` will be generated. Put your pico board into loading mode, by pushing `BOOTSEL` button while pluging on, and copy the UF2 to the new fresh usb mass storage Pico device. Once copied, the pico mass storage will be disconnected automatically and the pico board will reset with the new firmware. A blinking led will indicate the device is ready to work.
|
Additionally, you can pass the `VIDPID=value` parameter to build the firmware with a known VID/PID. The supported values are:
|
||||||
|
|
||||||
|
- `NitroHSM`
|
||||||
|
- `NitroFIDO2`
|
||||||
|
- `NitroStart`
|
||||||
|
- `NitroPro`
|
||||||
|
- `Nitro3`
|
||||||
|
- `Yubikey5`
|
||||||
|
- `YubikeyNeo`
|
||||||
|
- `YubiHSM`
|
||||||
|
- `Gnuk`
|
||||||
|
- `GnuPG`
|
||||||
|
|
||||||
|
After running `make`, the binary file `pico_hsm.uf2` will be generated. To load this onto your Pico board:
|
||||||
|
|
||||||
|
1. Put the Pico board into loading mode by holding the `BOOTSEL` button while plugging it in.
|
||||||
|
2. Copy the `pico_hsm.uf2` file to the new USB mass storage device that appears.
|
||||||
|
3. Once the file is copied, the Pico mass storage device will automatically disconnect, and the Pico board will reset with the new firmware.
|
||||||
|
4. A blinking LED will indicate that the device is ready to work.
|
||||||
|
|
||||||
### Docker
|
### Docker
|
||||||
Independent from your Linux distribution or when using another OS that supports Docker, you could build a specific pico-hsm version in a Linux container.
|
Independent from your Linux distribution or when using another OS that supports Docker, you could build a specific pico-hsm version in a Linux container.
|
||||||
|
|
||||||
|
|
||||||
```
|
```
|
||||||
sudo docker build \
|
sudo docker build \
|
||||||
--build-arg VERSION_PICO_SDK=1.4.0 \
|
--build-arg VERSION_PICO_SDK=1.5.0 \
|
||||||
--build-arg VERSION_MAJOR=2 \
|
--build-arg VERSION_MAJOR=3 \
|
||||||
--build-arg VERSION_MINOR=6 \
|
--build-arg VERSION_MINOR=4 \
|
||||||
--build-arg PICO_BOARD=waveshare_rp2040_zero \
|
--build-arg PICO_BOARD=waveshare_rp2040_zero \
|
||||||
--build-arg USB_VID=0xfeff \
|
--build-arg USB_VID=0xfeff \
|
||||||
--build-arg USB_PID=0xfcfd \
|
--build-arg USB_PID=0xfcfd \
|
||||||
@@ -185,36 +231,31 @@ sudo docker rm mybuild
|
|||||||
```
|
```
|
||||||
|
|
||||||
## Usage
|
## Usage
|
||||||
The firmware uploaded to the Pico contains a reader and a virtual smart card. It is like having a physical reader with an inserted SIM card.
|
The firmware uploaded to the Pico contains a reader and a virtual smart card, similar to having a physical reader with an inserted SIM card. We recommend using [OpenSC](http://github.com/opensc/opensc/ "OpenSC") to communicate with the reader. If OpenSC is not installed, you can download and build it or install the binaries for your system.
|
||||||
We recommend the use of [OpenSC](http://github.com/opensc/opensc/ "OpenSC") to communicate with the reader. If it is not installed, you can download and build it or install the binaries for your system. The first command is to ensure that the Pico is detected as a HSM:
|
|
||||||
```
|
To ensure that the Pico is detected as an HSM, use the following command:
|
||||||
|
```sh
|
||||||
opensc-tool -an
|
opensc-tool -an
|
||||||
```
|
```
|
||||||
It should return a text like the following:
|
It should return a text similar to:
|
||||||
```
|
```sh
|
||||||
Using reader with a card: Free Software Initiative of Japan Gnuk
|
Using reader with a card: Free Software Initiative of Japan Gnuk
|
||||||
3b:fe:18:00:00:81:31:fe:45:80:31:81:54:48:53:4d:31:73:80:21:40:81:07:fa
|
3b:fe:18:00:00:81:31:fe:45:80:31:81:54:48:53:4d:31:73:80:21:40:81:07:fa
|
||||||
SmartCard-HSM
|
SmartCard-HSM
|
||||||
```
|
```
|
||||||
The name of the reader may vary if you modified the VID/PID.
|
The name of the reader may vary if you modified the VID/PID.
|
||||||
|
|
||||||
For initialization and asymmetric operations, check [doc/usage.md](/doc/usage.md).
|
For further details and operations, refer to the following documentation:
|
||||||
|
|
||||||
For signing and verification operations, check [doc/sign-verify.md](/doc/sign-verify.md).
|
- Initialization and Asymmetric Operations [doc/usage.md](/doc/usage.md)
|
||||||
|
- Signing and Verification Operations [doc/sign-verify.md](/doc/sign-verify.md)
|
||||||
For asymmetric encryption and decryption, check [doc/asymmetric-ciphering.md](/doc/asymmetric-ciphering.md).
|
- Asymmetric Encryption and Decryption [doc/asymmetric-ciphering.md](/doc/asymmetric-ciphering.md)
|
||||||
|
- Backup, Restore, and DKEK Share Management [doc/backup-and-restore.md](/doc/backup-and-restore.md)
|
||||||
For backup, restore and DKEK share management, check [doc/backup-and-restore.md](/doc/backup-and-restore.md).
|
- AES Key Generation, Encryption, and Decryption [doc/aes.md](/doc/aes.md)
|
||||||
|
- 4096 Bits RSA Support [doc/scs3.md](/doc/scs3.md)
|
||||||
For AES key generation, encryption and decryption, check [doc/aes.md](/doc/aes.md).
|
- Storing and Retrieving Arbitrary Data [doc/store_data.md](/doc/store_data.md)
|
||||||
|
- Extra Options (e.g., set/get real datetime, enable/disable press-to-confirm button [doc/extra_command.md](/doc/extra_command.md)
|
||||||
For 4096 bits RSA support, check [doc/scs3.md](/doc/scs3.md).
|
- Public Key Authentication [doc/public_key_authentication.md](/doc/public_key_authentication.md)
|
||||||
|
|
||||||
For storing and retrieving arbitrary data, check [doc/store_data.md](/doc/store_data.md).
|
|
||||||
|
|
||||||
For extra options, such as set/get real datetime or enable/disable press-to-confirm button, check [doc/extra_command.md](/doc/extra_command.md).
|
|
||||||
|
|
||||||
For Public Key Authentication, check [doc/public_key_authentication.md](/doc/public_key_authentication.md).
|
|
||||||
|
|
||||||
## Operation time
|
## Operation time
|
||||||
### Keypair generation
|
### Keypair generation
|
||||||
@@ -236,14 +277,17 @@ Generating EC keys is almost instant. RSA keypair generation takes some time, sp
|
|||||||
| 4096 | 15 |
|
| 4096 | 15 |
|
||||||
|
|
||||||
## Press-to-confirm button
|
## Press-to-confirm button
|
||||||
Raspberry Pico comes with the BOOTSEL button to load the firmware. When this firmware is running, the button can be used for other purposes. Pico HSM uses this button to confirm private/secret operations. This feature is optional and it shall be enabled. For more information, see [doc/extra_command.md](/doc/extra_command.md).
|
The Raspberry Pico includes a BOOTSEL button used for loading firmware initially. Once the Pico HSM firmware is running, this button can be repurposed for additional functionalities. Specifically, the Pico HSM utilizes this button to confirm private and secret operations, a feature that is optional but highly recommended for enhanced security.
|
||||||
|
|
||||||
With this feature enabled, everytime that a private/secret key is loaded, the Pico HSM awaits for the user confirmation by pressing the BOOTSEL button. The Led of the Pico HSM will remain almost illuminated, turning off quickly once a second, indicating that the user must press the button to confirm the operation. Otherwise, the Pico HSM waits indefinitely. See [Led blink](#press-to-confirm) for a picture of the blinking sequence. When in this mode, the Pico HSM sends periodic timeout commands to the host to do not trigger the timeout operation.
|
When enabled, each time a private or secret key operation is initiated, the Pico HSM enters a waiting state where it awaits user confirmation by pressing the BOOTSEL button. During this waiting period, the Pico HSM's LED remains mostly illuminated but blinks off briefly every second, signaling to the user to press the button for confirmation. If no action is taken, the Pico HSM will continue to wait indefinitely. This operation mode includes periodic timeout commands sent to the host to prevent the session from timing out prematurely.
|
||||||
|
|
||||||
This feature is an extra layer of security, as it requires the user intervention to sign or decrypt and it ensures that any application will use the Pico HSM without user awareness. However, it is not recommended for servers or other environments where operations are authomatized, since it requires a physical access to the Pico HSM to push the button.
|
This feature adds an additional layer of security by requiring physical user intervention for sensitive operations such as signing or decrypting data. It mitigates risks associated with unauthorized applications or scripts using the Pico HSM without user awareness. However, it is not recommended for server environments or other automated settings where physical access to press the button may not be practical.
|
||||||
|
|
||||||
|
For more details on configuring and using this feature, refer to the [doc/extra_command.md](/doc/extra_command.md) document.
|
||||||
|
|
||||||
## Led blink
|
## Led blink
|
||||||
Pico HSM uses the led to indicate the current status. Four states are available:
|
Pico HSM uses the led to indicate the current status. Four states are available:
|
||||||
|
|
||||||
### Press to confirm
|
### Press to confirm
|
||||||
The Led is almost on all the time. It goes off for 100 miliseconds every second.
|
The Led is almost on all the time. It goes off for 100 miliseconds every second.
|
||||||
|
|
||||||
@@ -266,18 +310,20 @@ While processing, the Pico HSM is busy and cannot receive additional commands un
|
|||||||
|
|
||||||
## Driver
|
## Driver
|
||||||
|
|
||||||
Pico HSM uses the `sc-hsm` driver provided by [OpenSC](https://github.com/OpenSC/OpenSC/ "OpenSC") or the `sc-hsm-embedded` driver provided by [CardContact](https://github.com/CardContact/sc-hsm-embedded "CardContact"). This driver utilizes the standardized PKCS#11 interface to communicate with the user and it can be used with many engines that accept PKCS#11 interface, such as OpenSSL, P11 library or pkcs11-tool.
|
The Pico HSM uses either the `sc-hsm` driver from [OpenSC](https://github.com/OpenSC/OpenSC/) or the `sc-hsm-embedded` driver from [CardContact](https://github.com/CardContact/sc-hsm-embedded/) to interface with external applications. These drivers employ the standardized PKCS#11 interface, making it compatible with various cryptographic engines that support PKCS#11, such as OpenSSL, P11 library, or pkcs11-tool.
|
||||||
|
|
||||||
Pico HSM relies on PKCS#15 structure to store and manipulate the internal files (PINs, private keys, certificates, etc.) and directories. Therefore, it accepts the commands from `pkcs15-tool`. For instance, `pkcs15-tool -D` will list all elements stored in the Pico HSM.
|
Internally, the Pico HSM organizes and manages its data using the PKCS#15 structure, which includes elements like PINs, private keys, and certificates. Commands can be issued to interact with these stored elements using tools such as `pkcs15-tool`. For example, `pkcs15-tool -D` lists all elements stored within the Pico HSM.
|
||||||
|
|
||||||
The way to communicate is exactly the same as with other cards, such as OpenPGP or similar.
|
Communication with the Pico HSM follows the same protocols and methods used with other smart cards, such as OpenPGP cards or similar devices.
|
||||||
|
|
||||||
For an advanced usage, see the docs and examples.
|
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).
|
||||||
|
|
||||||
Pico HSM also supports SCS3 tool for advanced use and multiple key domain. See [SCS3](/doc/scs3.md) for more information.
|
|
||||||
|
|
||||||
### Important
|
### Important
|
||||||
OpenSC relies on PCSC driver, which reads a list (`Info.plist`) that contains a pair of VID/PID of supported readers. In order to be detectable, you must patch the UF2 binary (if you just downloaded from the [Release section](https://github.com/polhenarejos/pico-hsm/releases "Release section")) or 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.
|
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.
|
||||||
|
|
||||||
## Credits
|
## Credits
|
||||||
Pico HSM uses the following libraries or portion of code:
|
Pico HSM uses the following libraries or portion of code:
|
||||||
|
|||||||
@@ -1,7 +1,7 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
|
||||||
VERSION_MAJOR="3"
|
VERSION_MAJOR="4"
|
||||||
VERSION_MINOR="2"
|
VERSION_MINOR="0-eddsa1"
|
||||||
|
|
||||||
rm -rf release/*
|
rm -rf release/*
|
||||||
cd build_release
|
cd build_release
|
||||||
@@ -17,6 +17,7 @@ for board in adafruit_feather_rp2040 \
|
|||||||
eetree_gamekit_rp2040 \
|
eetree_gamekit_rp2040 \
|
||||||
garatronic_pybstick26_rp2040 \
|
garatronic_pybstick26_rp2040 \
|
||||||
melopero_shake_rp2040 \
|
melopero_shake_rp2040 \
|
||||||
|
nullbits_bit_c_pro \
|
||||||
pico \
|
pico \
|
||||||
pico_w \
|
pico_w \
|
||||||
pimoroni_badger2040 \
|
pimoroni_badger2040 \
|
||||||
@@ -31,6 +32,7 @@ for board in adafruit_feather_rp2040 \
|
|||||||
pimoroni_servo2040 \
|
pimoroni_servo2040 \
|
||||||
pimoroni_tiny2040 \
|
pimoroni_tiny2040 \
|
||||||
pimoroni_tiny2040_2mb \
|
pimoroni_tiny2040_2mb \
|
||||||
|
pololu_3pi_2040_robot \
|
||||||
seeed_xiao_rp2040 \
|
seeed_xiao_rp2040 \
|
||||||
solderparty_rp2040_stamp \
|
solderparty_rp2040_stamp \
|
||||||
solderparty_rp2040_stamp_carrier \
|
solderparty_rp2040_stamp_carrier \
|
||||||
@@ -40,6 +42,8 @@ for board in adafruit_feather_rp2040 \
|
|||||||
sparkfun_thingplus \
|
sparkfun_thingplus \
|
||||||
vgaboard \
|
vgaboard \
|
||||||
waveshare_rp2040_lcd_0.96 \
|
waveshare_rp2040_lcd_0.96 \
|
||||||
|
waveshare_rp2040_lcd_1.28 \
|
||||||
|
waveshare_rp2040_one \
|
||||||
waveshare_rp2040_plus_4mb \
|
waveshare_rp2040_plus_4mb \
|
||||||
waveshare_rp2040_plus_16mb \
|
waveshare_rp2040_plus_16mb \
|
||||||
waveshare_rp2040_zero \
|
waveshare_rp2040_zero \
|
||||||
|
|||||||
@@ -30,7 +30,7 @@ PIN=648219
|
|||||||
## Initialization
|
## 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 the `pico-hsm-tool.py` in `tools` folder:
|
||||||
```
|
```
|
||||||
$ python3 pico-hsm-tool.py initialize --so-pin 3537363231383830 --pin 648219
|
$ python3 tools/pico-hsm-tool.py --pin 648219 initialize --so-pin 57621880
|
||||||
```
|
```
|
||||||
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 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.
|
The PIN accepts from 6 to 16 characters.
|
||||||
@@ -51,7 +51,7 @@ $ pkcs11-tool --login --pin 648219 --change-pin --new-pin 123456
|
|||||||
|
|
||||||
To unblock the PIN:
|
To unblock the PIN:
|
||||||
```
|
```
|
||||||
$ pkcs11-tool --login --login-type so --so-pin=3537363231383830 --init-pin --new-pin=648219
|
$ pkcs11-tool --login --login-type so --so-pin 3537363231383830 --init-pin --new-pin 648219
|
||||||
```
|
```
|
||||||
|
|
||||||
## Keypair generation
|
## Keypair generation
|
||||||
|
|||||||
Submodule pico-hsm-sdk deleted from 599e5edbd1
1
pico-keys-sdk
Submodule
1
pico-keys-sdk
Submodule
Submodule pico-keys-sdk added at b945ae4f0e
53
sdkconfig.defaults
Executable file
53
sdkconfig.defaults
Executable file
@@ -0,0 +1,53 @@
|
|||||||
|
# This file was generated using idf.py save-defconfig. It can be edited manually.
|
||||||
|
# Espressif IoT Development Framework (ESP-IDF) Project Minimal Configuration
|
||||||
|
#
|
||||||
|
IGNORE_UNKNOWN_FILES_FOR_MANAGED_COMPONENTS=1
|
||||||
|
|
||||||
|
CONFIG_TINYUSB=y
|
||||||
|
|
||||||
|
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||||
|
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="pico-keys-sdk/partitions.csv"
|
||||||
|
CONFIG_PARTITION_TABLE_FILENAME="pico-keys-sdk/partitions.csv"
|
||||||
|
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
|
||||||
|
CONFIG_WL_SECTOR_SIZE_512=y
|
||||||
|
CONFIG_WL_SECTOR_MODE_PERF=y
|
||||||
|
|
||||||
|
CONFIG_MBEDTLS_CMAC_C=y
|
||||||
|
CONFIG_MBEDTLS_CHACHA20_C=y
|
||||||
|
CONFIG_MBEDTLS_POLY1305_C=y
|
||||||
|
CONFIG_MBEDTLS_CHACHAPOLY_C=y
|
||||||
|
CONFIG_MBEDTLS_HKDF_C=y
|
||||||
|
CONFIG_MBEDTLS_HARDWARE_ECC=y
|
||||||
|
CONFIG_MBEDTLS_HARDWARE_GCM=y
|
||||||
|
# CONFIG_MBEDTLS_HARDWARE_MPI is not set
|
||||||
|
CONFIG_MBEDTLS_HARDWARE_SHA=y
|
||||||
|
CONFIG_MBEDTLS_HARDWARE_AES=y
|
||||||
|
# CONFIG_MBEDTLS_ROM_MD5 is not set
|
||||||
|
CONFIG_MBEDTLS_SHA512_C=y
|
||||||
|
CONFIG_MBEDTLS_TLS_DISABLED=y
|
||||||
|
# CONFIG_MBEDTLS_TLS_ENABLED is not set
|
||||||
|
# CONFIG_ESP_TLS_USE_DS_PERIPHERAL is not set
|
||||||
|
# CONFIG_ESP_WIFI_ENABLED is not set
|
||||||
|
# CONFIG_ESP_WIFI_MBEDTLS_CRYPTO is not set
|
||||||
|
# CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT is not set
|
||||||
|
# CONFIG_WPA_MBEDTLS_CRYPTO is not set
|
||||||
|
# CONFIG_MBEDTLS_PSK_MODES is not set
|
||||||
|
# CONFIG_MBEDTLS_KEY_EXCHANGE_RSA is not set
|
||||||
|
# CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE is not set
|
||||||
|
# CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA is not set
|
||||||
|
# CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA is not set
|
||||||
|
# CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA is not set
|
||||||
|
# CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA is not set
|
||||||
|
# CONFIG_MBEDTLS_SSL_RENEGOTIATION is not set
|
||||||
|
# CONFIG_MBEDTLS_SSL_PROTO_TLS1_2 is not set
|
||||||
|
# CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 is not set
|
||||||
|
# CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set
|
||||||
|
# CONFIG_MBEDTLS_SSL_ALPN is not set
|
||||||
|
# CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS is not set
|
||||||
|
# CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS is not set
|
||||||
|
# CONFIG_ESP32_WIFI_ENABLE_WPA3_SAE is not set
|
||||||
|
# CONFIG_ESP32_WIFI_ENABLE_WPA3_OWE_STA is not set
|
||||||
|
# CONFIG_ESP_WIFI_ENABLE_WPA3_SAE is not set
|
||||||
|
# CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA is not set
|
||||||
|
|
||||||
|
CONFIG_ESP_COREDUMP_ENABLE_TO_UART=y
|
||||||
6
src/hsm/CMakeLists.txt
Normal file
6
src/hsm/CMakeLists.txt
Normal file
@@ -0,0 +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
|
||||||
|
)
|
||||||
|
idf_component_set_property(${COMPONENT_NAME} WHOLE_ARCHIVE ON)
|
||||||
326
src/hsm/cmd_bip_slip.c
Normal file
326
src/hsm/cmd_bip_slip.c
Normal file
@@ -0,0 +1,326 @@
|
|||||||
|
/*
|
||||||
|
* 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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#include "sc_hsm.h"
|
||||||
|
#include "files.h"
|
||||||
|
#include "random.h"
|
||||||
|
#include "kek.h"
|
||||||
|
#include "asn1.h"
|
||||||
|
|
||||||
|
const uint8_t *k1_seed = (const uint8_t *) "Bitcoin seed";
|
||||||
|
const uint8_t *p1_seed = (const uint8_t *) "Nist256p1 seed";
|
||||||
|
const uint8_t *sym_seed = (const uint8_t *) "Symmetric key seed";
|
||||||
|
mbedtls_ecp_keypair hd_context = { 0 };
|
||||||
|
uint8_t hd_keytype = 0;
|
||||||
|
|
||||||
|
int node_derive_bip_child(const mbedtls_ecp_keypair *parent,
|
||||||
|
const uint8_t cpar[32],
|
||||||
|
const uint8_t *i,
|
||||||
|
mbedtls_ecp_keypair *child,
|
||||||
|
uint8_t cchild[32]) {
|
||||||
|
uint8_t data[1 + 32 + 4], I[64], *iL = I, *iR = I + 32;
|
||||||
|
mbedtls_mpi il, kchild;
|
||||||
|
mbedtls_mpi_init(&il);
|
||||||
|
mbedtls_mpi_init(&kchild);
|
||||||
|
if (i[0] >= 0x80) {
|
||||||
|
if (mbedtls_mpi_cmp_int(&parent->d, 0) == 0) {
|
||||||
|
return CCID_ERR_NULL_PARAM;
|
||||||
|
}
|
||||||
|
data[0] = 0x00;
|
||||||
|
mbedtls_mpi_write_binary(&parent->d, data + 1, 32);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
size_t olen = 0;
|
||||||
|
mbedtls_ecp_point_write_binary(&parent->grp,
|
||||||
|
&parent->Q,
|
||||||
|
MBEDTLS_ECP_PF_COMPRESSED,
|
||||||
|
&olen,
|
||||||
|
data,
|
||||||
|
33);
|
||||||
|
}
|
||||||
|
do {
|
||||||
|
memcpy(data + 33, i, 4);
|
||||||
|
mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA512),
|
||||||
|
cpar,
|
||||||
|
32,
|
||||||
|
data,
|
||||||
|
sizeof(data),
|
||||||
|
I);
|
||||||
|
mbedtls_mpi_read_binary(&il, iL, 32);
|
||||||
|
mbedtls_mpi_add_mpi(&kchild, &il, &parent->d);
|
||||||
|
mbedtls_mpi_mod_mpi(&kchild, &kchild, &parent->grp.N);
|
||||||
|
data[0] = 0x01;
|
||||||
|
memcpy(data + 1, iR, 32);
|
||||||
|
} while (mbedtls_mpi_cmp_mpi(&il,
|
||||||
|
&parent->grp.N) != -1 || mbedtls_mpi_cmp_int(&kchild, 0) == 0);
|
||||||
|
mbedtls_mpi_copy(&child->d, &kchild);
|
||||||
|
mbedtls_ecp_mul(&child->grp, &child->Q, &child->d, &child->grp.G, random_gen, NULL);
|
||||||
|
memcpy(cchild, iR, 32);
|
||||||
|
mbedtls_mpi_free(&il);
|
||||||
|
mbedtls_mpi_free(&kchild);
|
||||||
|
return CCID_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;
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
int node_fingerprint_bip(mbedtls_ecp_keypair *ctx, uint8_t fingerprint[4]) {
|
||||||
|
size_t olen = 0;
|
||||||
|
uint8_t buffer[33];
|
||||||
|
mbedtls_ecp_point_write_binary(&ctx->grp,
|
||||||
|
&ctx->Q,
|
||||||
|
MBEDTLS_ECP_PF_COMPRESSED,
|
||||||
|
&olen,
|
||||||
|
buffer,
|
||||||
|
sizeof(buffer));
|
||||||
|
sha256_ripemd160(buffer, sizeof(buffer), buffer);
|
||||||
|
memcpy(fingerprint, buffer, 4);
|
||||||
|
return CCID_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
int node_fingerprint_slip(mbedtls_ecp_keypair *ctx, uint8_t fingerprint[4]) {
|
||||||
|
uint8_t buffer[32];
|
||||||
|
mbedtls_mpi_write_binary(&ctx->d, buffer, sizeof(buffer));
|
||||||
|
sha256_ripemd160(buffer, sizeof(buffer), buffer);
|
||||||
|
memcpy(fingerprint, buffer, 4);
|
||||||
|
return CCID_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
int load_master_bip(uint16_t mid, mbedtls_ecp_keypair *ctx, uint8_t chain[32],
|
||||||
|
uint8_t key_type[1]) {
|
||||||
|
uint8_t mkey[65];
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
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 (mkey[0] == 0x1 || mkey[0] == 0x2) {
|
||||||
|
if (mkey[0] == 0x1) {
|
||||||
|
mbedtls_ecp_group_load(&ctx->grp, MBEDTLS_ECP_DP_SECP256K1);
|
||||||
|
}
|
||||||
|
else if (mkey[0] == 0x2) {
|
||||||
|
mbedtls_ecp_group_load(&ctx->grp, MBEDTLS_ECP_DP_SECP256R1);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
|
||||||
|
mbedtls_mpi_read_binary(&ctx->d, mkey + 1, 32);
|
||||||
|
memcpy(chain, mkey + 33, 32);
|
||||||
|
mbedtls_ecp_mul(&ctx->grp, &ctx->Q, &ctx->d, &ctx->grp.G, random_gen, NULL);
|
||||||
|
}
|
||||||
|
else if (mkey[0] == 0x3) {
|
||||||
|
mbedtls_mpi_read_binary(&ctx->d, mkey + 33, 32);
|
||||||
|
memcpy(chain, mkey + 1, 32);
|
||||||
|
}
|
||||||
|
key_type[0] = mkey[0];
|
||||||
|
return CCID_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
int node_derive_path(const uint8_t *path,
|
||||||
|
uint16_t path_len,
|
||||||
|
mbedtls_ecp_keypair *ctx,
|
||||||
|
uint8_t chain[32],
|
||||||
|
uint8_t fingerprint[4],
|
||||||
|
uint8_t *nodes,
|
||||||
|
uint8_t last_node[4],
|
||||||
|
uint8_t key_type[1]) {
|
||||||
|
uint8_t *tag_data = NULL, *p = NULL;
|
||||||
|
uint16_t tag_len = 0, tag = 0x0;
|
||||||
|
uint8_t node = 0, N[64] = { 0 };
|
||||||
|
int r = 0;
|
||||||
|
memset(last_node, 0, 4);
|
||||||
|
memset(fingerprint, 0, 4);
|
||||||
|
|
||||||
|
asn1_ctx_t ctxi;
|
||||||
|
asn1_ctx_init((uint8_t *)path, path_len, &ctxi);
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
if (node == 0) {
|
||||||
|
if ((r = load_master_bip(tag_data[0], ctx, chain, key_type)) != CCID_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) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
memcpy(last_node, tag_data, 4);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (tag == 0x04) {
|
||||||
|
if (node == 0) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
else if (node > 0) {
|
||||||
|
node_fingerprint_slip(ctx, fingerprint);
|
||||||
|
*(tag_data - 1) = 0;
|
||||||
|
mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA512),
|
||||||
|
chain,
|
||||||
|
32,
|
||||||
|
tag_data - 1,
|
||||||
|
tag_len + 1,
|
||||||
|
N);
|
||||||
|
memcpy(chain, N, 32);
|
||||||
|
mbedtls_mpi_read_binary(&ctx->d, N + 32, 32);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (nodes) {
|
||||||
|
*nodes = node;
|
||||||
|
}
|
||||||
|
return CCID_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
int cmd_bip_slip() {
|
||||||
|
uint8_t p1 = P1(apdu), p2 = P2(apdu);
|
||||||
|
if (p1 == 0x1 || p1 == 0x2 || p1 == 0x3) { // Master generation (K1 and P1)
|
||||||
|
if (p2 >= 10) {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
uint8_t mkey[65], *seed = mkey + 1, seed_len = 64;
|
||||||
|
const uint8_t *key_seed = NULL;
|
||||||
|
mbedtls_mpi il;
|
||||||
|
mbedtls_mpi_init(&il);
|
||||||
|
mbedtls_ecp_group grp;
|
||||||
|
mbedtls_ecp_group_init(&grp);
|
||||||
|
if (p1 == 0x1) {
|
||||||
|
mbedtls_ecp_group_load(&grp, MBEDTLS_ECP_DP_SECP256K1);
|
||||||
|
key_seed = k1_seed;
|
||||||
|
}
|
||||||
|
else if (p1 == 0x2) {
|
||||||
|
mbedtls_ecp_group_load(&grp, MBEDTLS_ECP_DP_SECP256R1);
|
||||||
|
key_seed = p1_seed;
|
||||||
|
}
|
||||||
|
else if (p1 == 0x3) {
|
||||||
|
key_seed = sym_seed;
|
||||||
|
}
|
||||||
|
if (apdu.nc == 0) {
|
||||||
|
seed_len = 64;
|
||||||
|
random_gen(NULL, seed, seed_len);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
seed_len = MIN((uint8_t)apdu.nc, 64);
|
||||||
|
memcpy(seed, apdu.data, seed_len);
|
||||||
|
}
|
||||||
|
if (p1 == 0x1 || p1 == 0x2) {
|
||||||
|
do {
|
||||||
|
mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA512), key_seed,
|
||||||
|
strlen((char *) key_seed), seed, seed_len, seed);
|
||||||
|
mbedtls_mpi_read_binary(&il, seed, 32);
|
||||||
|
seed_len = 64;
|
||||||
|
} while (mbedtls_mpi_cmp_int(&il, 0) == 0 || mbedtls_mpi_cmp_mpi(&il, &grp.N) != -1);
|
||||||
|
mbedtls_ecp_group_free(&grp);
|
||||||
|
mbedtls_mpi_free(&il);
|
||||||
|
}
|
||||||
|
else if (p1 == 0x3) {
|
||||||
|
mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA512), key_seed,
|
||||||
|
strlen((char *) key_seed), seed, seed_len, seed);
|
||||||
|
}
|
||||||
|
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) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
r = file_put_data(ef, mkey, sizeof(mkey));
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
low_flash_available();
|
||||||
|
}
|
||||||
|
else if (p1 == 0xA) {
|
||||||
|
if (apdu.nc == 0) {
|
||||||
|
return SW_WRONG_LENGTH();
|
||||||
|
}
|
||||||
|
mbedtls_ecp_keypair ctx;
|
||||||
|
uint8_t chain[32] = { 0 }, fgpt[4] = { 0 }, last_node[4] = { 0 }, key_type = 0, nodes = 0;
|
||||||
|
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) {
|
||||||
|
mbedtls_ecp_keypair_free(&ctx);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
uint8_t pubkey[33];
|
||||||
|
res_APDU_size = 0;
|
||||||
|
memcpy(res_APDU, "\x04\x88\xB2\x1E", 4);
|
||||||
|
res_APDU_size += 4;
|
||||||
|
res_APDU[res_APDU_size++] = nodes - 1;
|
||||||
|
memcpy(res_APDU + res_APDU_size, fgpt, 4);
|
||||||
|
res_APDU_size += 4;
|
||||||
|
memcpy(res_APDU + res_APDU_size, last_node, 4);
|
||||||
|
res_APDU_size += 4;
|
||||||
|
if (key_type == 0x1 || key_type == 0x2) {
|
||||||
|
memcpy(res_APDU + res_APDU_size, chain, 32);
|
||||||
|
res_APDU_size += 32;
|
||||||
|
mbedtls_ecp_point_write_binary(&ctx.grp,
|
||||||
|
&ctx.Q,
|
||||||
|
MBEDTLS_ECP_PF_COMPRESSED,
|
||||||
|
&olen,
|
||||||
|
pubkey,
|
||||||
|
sizeof(pubkey));
|
||||||
|
memcpy(res_APDU + res_APDU_size, pubkey, olen);
|
||||||
|
res_APDU_size += (uint16_t)olen;
|
||||||
|
}
|
||||||
|
else if (key_type == 0x3) {
|
||||||
|
sha256_sha256(chain, 32, chain);
|
||||||
|
memcpy(res_APDU + res_APDU_size, chain, 32);
|
||||||
|
res_APDU_size += 32;
|
||||||
|
mbedtls_mpi_write_binary(&ctx.d, pubkey, 32);
|
||||||
|
sha256_sha256(pubkey, 32, pubkey);
|
||||||
|
memcpy(res_APDU + res_APDU_size, pubkey, 32);
|
||||||
|
res_APDU_size += 32;
|
||||||
|
}
|
||||||
|
mbedtls_ecp_keypair_free(&ctx);
|
||||||
|
}
|
||||||
|
else if (p1 == 0x10) {
|
||||||
|
uint8_t chain[32] = { 0 }, fgpt[4] = { 0 }, last_node[4] = { 0 }, nodes = 0;
|
||||||
|
int r = node_derive_path(apdu.data,
|
||||||
|
(uint16_t)apdu.nc,
|
||||||
|
&hd_context,
|
||||||
|
chain,
|
||||||
|
fgpt,
|
||||||
|
&nodes,
|
||||||
|
last_node,
|
||||||
|
&hd_keytype);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
mbedtls_ecp_keypair_free(&hd_context);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
@@ -27,8 +27,8 @@ int cmd_challenge() {
|
|||||||
return SW_WRONG_LENGTH();
|
return SW_WRONG_LENGTH();
|
||||||
}
|
}
|
||||||
memcpy(res_APDU, rb, apdu.ne);
|
memcpy(res_APDU, rb, apdu.ne);
|
||||||
challenge_len = MIN(apdu.ne, sizeof(challenge));
|
challenge_len = (uint8_t)MIN(apdu.ne, sizeof(challenge));
|
||||||
memcpy(challenge, rb, challenge_len);
|
memcpy(challenge, rb, challenge_len);
|
||||||
res_APDU_size = apdu.ne;
|
res_APDU_size = (uint16_t)apdu.ne;
|
||||||
return SW_OK();
|
return SW_OK();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -35,7 +35,7 @@ int cmd_change_pin() {
|
|||||||
if (!file_has_data(file_pin)) {
|
if (!file_has_data(file_pin)) {
|
||||||
return SW_REFERENCE_NOT_FOUND();
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
uint8_t pin_len = file_read_uint8(file_get_data(file_pin));
|
uint8_t pin_len = file_read_uint8(file_pin);
|
||||||
int r = check_pin(file_pin, apdu.data, pin_len);
|
int r = check_pin(file_pin, apdu.data, pin_len);
|
||||||
if (r != 0x9000) {
|
if (r != 0x9000) {
|
||||||
return r;
|
return r;
|
||||||
@@ -48,11 +48,11 @@ int cmd_change_pin() {
|
|||||||
//encrypt MKEK with new pin
|
//encrypt MKEK with new pin
|
||||||
|
|
||||||
if (P2(apdu) == 0x81) {
|
if (P2(apdu) == 0x81) {
|
||||||
hash_multi(apdu.data + pin_len, apdu.nc - pin_len, session_pin);
|
hash_multi(apdu.data + pin_len, (uint16_t)(apdu.nc - pin_len), session_pin);
|
||||||
has_session_pin = true;
|
has_session_pin = true;
|
||||||
}
|
}
|
||||||
else if (P2(apdu) == 0x88) {
|
else if (P2(apdu) == 0x88) {
|
||||||
hash_multi(apdu.data + pin_len, apdu.nc - pin_len, session_sopin);
|
hash_multi(apdu.data + pin_len, (uint16_t)(apdu.nc - pin_len), session_sopin);
|
||||||
has_session_sopin = true;
|
has_session_sopin = true;
|
||||||
}
|
}
|
||||||
r = store_mkek(mkek);
|
r = store_mkek(mkek);
|
||||||
@@ -61,9 +61,9 @@ int cmd_change_pin() {
|
|||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
uint8_t dhash[33];
|
uint8_t dhash[33];
|
||||||
dhash[0] = apdu.nc - pin_len;
|
dhash[0] = (uint8_t)apdu.nc - pin_len;
|
||||||
double_hash_pin(apdu.data + pin_len, apdu.nc - pin_len, dhash + 1);
|
double_hash_pin(apdu.data + pin_len, (uint16_t)(apdu.nc - pin_len), dhash + 1);
|
||||||
flash_write_data_to_file(file_pin, dhash, sizeof(dhash));
|
file_put_data(file_pin, dhash, sizeof(dhash));
|
||||||
low_flash_available();
|
low_flash_available();
|
||||||
return SW_OK();
|
return SW_OK();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,15 +15,15 @@
|
|||||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include "common.h"
|
#include "sc_hsm.h"
|
||||||
#include "mbedtls/aes.h"
|
#include "mbedtls/aes.h"
|
||||||
#include "mbedtls/cmac.h"
|
#include "mbedtls/cmac.h"
|
||||||
#include "mbedtls/hkdf.h"
|
#include "mbedtls/hkdf.h"
|
||||||
#include "mbedtls/chachapoly.h"
|
#include "mbedtls/chachapoly.h"
|
||||||
#include "md_wrap.h"
|
#include "mbedtls/gcm.h"
|
||||||
|
//#include "mbedtls/md_wrap.h"
|
||||||
#include "mbedtls/md.h"
|
#include "mbedtls/md.h"
|
||||||
#include "crypto_utils.h"
|
#include "crypto_utils.h"
|
||||||
#include "sc_hsm.h"
|
|
||||||
#include "kek.h"
|
#include "kek.h"
|
||||||
#include "asn1.h"
|
#include "asn1.h"
|
||||||
#include "oid.h"
|
#include "oid.h"
|
||||||
@@ -32,13 +32,17 @@
|
|||||||
#include "mbedtls/asn1.h"
|
#include "mbedtls/asn1.h"
|
||||||
#include "mbedtls/cipher.h"
|
#include "mbedtls/cipher.h"
|
||||||
#include "mbedtls/oid.h"
|
#include "mbedtls/oid.h"
|
||||||
|
#include "mbedtls/ccm.h"
|
||||||
|
|
||||||
|
extern mbedtls_ecp_keypair hd_context;
|
||||||
|
extern uint8_t hd_keytype;
|
||||||
|
|
||||||
/* This is copied from pkcs5.c Mbedtls */
|
/* This is copied from pkcs5.c Mbedtls */
|
||||||
/** Unfortunately it is declared as static, so I cannot call it. **/
|
/** Unfortunately it is declared as static, so I cannot call it. **/
|
||||||
|
|
||||||
static int pkcs5_parse_pbkdf2_params(const mbedtls_asn1_buf *params,
|
static int pkcs5_parse_pbkdf2_params(const mbedtls_asn1_buf *params,
|
||||||
mbedtls_asn1_buf *salt, int *iterations,
|
mbedtls_asn1_buf *salt, int *iterations,
|
||||||
int *keylen, mbedtls_md_type_t *md_type) {
|
uint16_t *keylen, mbedtls_md_type_t *md_type) {
|
||||||
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
|
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
|
||||||
mbedtls_asn1_buf prf_alg_oid;
|
mbedtls_asn1_buf prf_alg_oid;
|
||||||
unsigned char *p = params->p;
|
unsigned char *p = params->p;
|
||||||
@@ -73,7 +77,7 @@ static int pkcs5_parse_pbkdf2_params(const mbedtls_asn1_buf *params,
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((ret = mbedtls_asn1_get_int(&p, end, keylen)) != 0) {
|
if ((ret = mbedtls_asn1_get_int(&p, end, (int *)keylen)) != 0) {
|
||||||
if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
|
if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
|
||||||
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS5_INVALID_FORMAT, ret);
|
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS5_INVALID_FORMAT, ret);
|
||||||
}
|
}
|
||||||
@@ -101,11 +105,11 @@ static int pkcs5_parse_pbkdf2_params(const mbedtls_asn1_buf *params,
|
|||||||
|
|
||||||
/* Taken from https://github.com/Mbed-TLS/mbedtls/issues/2335 */
|
/* Taken from https://github.com/Mbed-TLS/mbedtls/issues/2335 */
|
||||||
int mbedtls_ansi_x963_kdf(mbedtls_md_type_t md_type,
|
int mbedtls_ansi_x963_kdf(mbedtls_md_type_t md_type,
|
||||||
size_t input_len,
|
uint16_t input_len,
|
||||||
uint8_t *input,
|
uint8_t *input,
|
||||||
size_t shared_info_len,
|
uint16_t shared_info_len,
|
||||||
uint8_t *shared_info,
|
uint8_t *shared_info,
|
||||||
size_t output_len,
|
uint16_t output_len,
|
||||||
uint8_t *output) {
|
uint8_t *output) {
|
||||||
mbedtls_md_context_t md_ctx;
|
mbedtls_md_context_t md_ctx;
|
||||||
const mbedtls_md_info_t *md_info = NULL;
|
const mbedtls_md_info_t *md_info = NULL;
|
||||||
@@ -129,7 +133,7 @@ int mbedtls_ansi_x963_kdf(mbedtls_md_type_t md_type,
|
|||||||
}
|
}
|
||||||
|
|
||||||
// keydatalen equals output_len
|
// keydatalen equals output_len
|
||||||
hashlen = md_info->size;
|
hashlen = mbedtls_md_get_size(md_info);
|
||||||
if (output_len >= hashlen * ((1ULL << 32) - 1)) {
|
if (output_len >= hashlen * ((1ULL << 32) - 1)) {
|
||||||
return exit_code;
|
return exit_code;
|
||||||
}
|
}
|
||||||
@@ -158,25 +162,26 @@ int mbedtls_ansi_x963_kdf(mbedtls_md_type_t md_type,
|
|||||||
}
|
}
|
||||||
|
|
||||||
int cmd_cipher_sym() {
|
int cmd_cipher_sym() {
|
||||||
int key_id = P1(apdu);
|
uint8_t key_id = P1(apdu), algo = P2(apdu);
|
||||||
int algo = P2(apdu);
|
|
||||||
if (!isUserAuthenticated) {
|
if (!isUserAuthenticated) {
|
||||||
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
}
|
}
|
||||||
file_t *ef = search_dynamic_file((KEY_PREFIX << 8) | key_id);
|
|
||||||
if (!ef) {
|
|
||||||
return SW_FILE_NOT_FOUND();
|
|
||||||
}
|
|
||||||
if (key_has_purpose(ef, algo) == false) {
|
|
||||||
return SW_CONDITIONS_NOT_SATISFIED();
|
|
||||||
}
|
|
||||||
if (wait_button_pressed() == true) { // timeout
|
if (wait_button_pressed() == true) { // timeout
|
||||||
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
int key_size = file_get_size(ef);
|
file_t *ef = search_file((KEY_PREFIX << 8) | key_id);
|
||||||
uint8_t kdata[32]; //maximum AES key size
|
if (hd_keytype == 0) {
|
||||||
|
if (!ef) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
if (key_has_purpose(ef, algo) == false) {
|
||||||
|
return SW_CONDITIONS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
uint16_t key_size = file_get_size(ef);
|
||||||
|
uint8_t kdata[64]; //maximum AES key size
|
||||||
memcpy(kdata, file_get_data(ef), key_size);
|
memcpy(kdata, file_get_data(ef), key_size);
|
||||||
if (mkek_decrypt(kdata, key_size) != 0) {
|
if (hd_keytype == 0 && mkek_decrypt(kdata, key_size) != 0) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
if (algo == ALGO_AES_CBC_ENCRYPT || algo == ALGO_AES_CBC_DECRYPT) {
|
if (algo == ALGO_AES_CBC_ENCRYPT || algo == ALGO_AES_CBC_DECRYPT) {
|
||||||
@@ -189,8 +194,8 @@ int cmd_cipher_sym() {
|
|||||||
memset(tmp_iv, 0, sizeof(tmp_iv));
|
memset(tmp_iv, 0, sizeof(tmp_iv));
|
||||||
if (algo == ALGO_AES_CBC_ENCRYPT) {
|
if (algo == ALGO_AES_CBC_ENCRYPT) {
|
||||||
int r = mbedtls_aes_setkey_enc(&aes, kdata, key_size * 8);
|
int r = mbedtls_aes_setkey_enc(&aes, kdata, key_size * 8);
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
|
||||||
mbedtls_aes_free(&aes);
|
mbedtls_aes_free(&aes);
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
@@ -200,16 +205,14 @@ int cmd_cipher_sym() {
|
|||||||
tmp_iv,
|
tmp_iv,
|
||||||
apdu.data,
|
apdu.data,
|
||||||
res_APDU);
|
res_APDU);
|
||||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
mbedtls_aes_free(&aes);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
mbedtls_aes_free(&aes);
|
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (algo == ALGO_AES_CBC_DECRYPT) {
|
else if (algo == ALGO_AES_CBC_DECRYPT) {
|
||||||
int r = mbedtls_aes_setkey_dec(&aes, kdata, key_size * 8);
|
int r = mbedtls_aes_setkey_dec(&aes, kdata, key_size * 8);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
|
||||||
mbedtls_aes_free(&aes);
|
mbedtls_aes_free(&aes);
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
@@ -219,14 +222,12 @@ int cmd_cipher_sym() {
|
|||||||
tmp_iv,
|
tmp_iv,
|
||||||
apdu.data,
|
apdu.data,
|
||||||
res_APDU);
|
res_APDU);
|
||||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
mbedtls_aes_free(&aes);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
mbedtls_aes_free(&aes);
|
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
res_APDU_size = apdu.nc;
|
res_APDU_size = (uint16_t)apdu.nc;
|
||||||
mbedtls_aes_free(&aes);
|
|
||||||
}
|
}
|
||||||
else if (algo == ALGO_AES_CMAC) {
|
else if (algo == ALGO_AES_CMAC) {
|
||||||
const mbedtls_cipher_info_t *cipher_info;
|
const mbedtls_cipher_info_t *cipher_info;
|
||||||
@@ -254,7 +255,7 @@ int cmd_cipher_sym() {
|
|||||||
int r = mbedtls_hkdf(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256),
|
int r = mbedtls_hkdf(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256),
|
||||||
NULL,
|
NULL,
|
||||||
0,
|
0,
|
||||||
file_get_data(ef),
|
kdata,
|
||||||
key_size,
|
key_size,
|
||||||
apdu.data,
|
apdu.data,
|
||||||
apdu.nc,
|
apdu.nc,
|
||||||
@@ -264,109 +265,112 @@ int cmd_cipher_sym() {
|
|||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
res_APDU_size = apdu.nc;
|
res_APDU_size = (uint16_t)apdu.nc;
|
||||||
}
|
}
|
||||||
else if (algo == ALGO_EXT_CIPHER_ENCRYPT || algo == ALGO_EXT_CIPHER_DECRYPT) {
|
else if (algo == ALGO_EXT_CIPHER_ENCRYPT || algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||||
size_t oid_len = 0, aad_len = 0, iv_len = 0, enc_len = 0;
|
asn1_ctx_t ctxi, oid = {0}, enc = {0}, iv = {0}, aad = {0};
|
||||||
uint8_t *oid = NULL, *aad = NULL, *iv = NULL, *enc = NULL;
|
asn1_ctx_init(apdu.data, (uint16_t)apdu.nc, &ctxi);
|
||||||
if (!asn1_find_tag(apdu.data, apdu.nc, 0x6, &oid_len,
|
if (!asn1_find_tag(&ctxi, 0x6, &oid) || asn1_len(&oid) == 0) {
|
||||||
&oid) || oid_len == 0 || oid == NULL) {
|
|
||||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
}
|
}
|
||||||
asn1_find_tag(apdu.data, apdu.nc, 0x81, &enc_len, &enc);
|
asn1_find_tag(&ctxi, 0x81, &enc);
|
||||||
asn1_find_tag(apdu.data, apdu.nc, 0x82, &iv_len, &iv);
|
asn1_find_tag(&ctxi, 0x82, &iv);
|
||||||
asn1_find_tag(apdu.data, apdu.nc, 0x83, &aad_len, &aad);
|
asn1_find_tag(&ctxi, 0x83, &aad);
|
||||||
uint8_t tmp_iv[16];
|
uint8_t tmp_iv[16];
|
||||||
memset(tmp_iv, 0, sizeof(tmp_iv));
|
memset(tmp_iv, 0, sizeof(tmp_iv));
|
||||||
if (memcmp(oid, OID_CHACHA20_POLY1305, oid_len) == 0) {
|
if (memcmp(oid.data, OID_CHACHA20_POLY1305, oid.len) == 0) {
|
||||||
if (algo == ALGO_EXT_CIPHER_DECRYPT && enc_len < 16) {
|
if (algo == ALGO_EXT_CIPHER_DECRYPT && enc.len < 16) {
|
||||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
}
|
}
|
||||||
int r = 0;
|
int r = 0;
|
||||||
mbedtls_chachapoly_context ctx;
|
mbedtls_chachapoly_context ctx;
|
||||||
mbedtls_chachapoly_init(&ctx);
|
mbedtls_chachapoly_init(&ctx);
|
||||||
|
mbedtls_chachapoly_setkey(&ctx, kdata);
|
||||||
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
||||||
r = mbedtls_chachapoly_encrypt_and_tag(&ctx,
|
r = mbedtls_chachapoly_encrypt_and_tag(&ctx,
|
||||||
enc_len,
|
enc.len,
|
||||||
iv ? iv : tmp_iv,
|
asn1_len(&iv) > 0 ? iv.data : tmp_iv,
|
||||||
aad,
|
aad.data,
|
||||||
aad_len,
|
aad.len,
|
||||||
enc,
|
enc.data,
|
||||||
res_APDU,
|
res_APDU,
|
||||||
res_APDU + enc_len);
|
res_APDU + enc.len);
|
||||||
}
|
}
|
||||||
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||||
r = mbedtls_chachapoly_auth_decrypt(&ctx,
|
r = mbedtls_chachapoly_auth_decrypt(&ctx,
|
||||||
enc_len - 16,
|
enc.len - 16,
|
||||||
iv ? iv : tmp_iv,
|
asn1_len(&iv) > 0 ? iv.data : tmp_iv,
|
||||||
aad,
|
aad.data,
|
||||||
aad_len,
|
aad.len,
|
||||||
enc + enc_len - 16,
|
enc.data + enc.len - 16,
|
||||||
enc,
|
enc.data,
|
||||||
res_APDU);
|
res_APDU);
|
||||||
}
|
}
|
||||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
mbedtls_chachapoly_free(&ctx);
|
mbedtls_chachapoly_free(&ctx);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
|
if (r == MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
||||||
res_APDU_size = enc_len + 16;
|
res_APDU_size = enc.len + 16;
|
||||||
}
|
}
|
||||||
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||||
res_APDU_size = enc_len - 16;
|
res_APDU_size = enc.len - 16;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (memcmp(oid, OID_DIGEST, 7) == 0) {
|
else if (memcmp(oid.data, OID_DIGEST, 7) == 0) {
|
||||||
const mbedtls_md_info_t *md_info = NULL;
|
const mbedtls_md_info_t *md_info = NULL;
|
||||||
if (memcmp(oid, OID_HMAC_SHA1, oid_len) == 0) {
|
if (memcmp(oid.data, OID_HMAC_SHA1, oid.len) == 0) {
|
||||||
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA1);
|
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA1);
|
||||||
}
|
}
|
||||||
else if (memcmp(oid, OID_HMAC_SHA224, oid_len) == 0) {
|
else if (memcmp(oid.data, OID_HMAC_SHA224, oid.len) == 0) {
|
||||||
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA224);
|
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA224);
|
||||||
}
|
}
|
||||||
else if (memcmp(oid, OID_HMAC_SHA256, oid_len) == 0) {
|
else if (memcmp(oid.data, OID_HMAC_SHA256, oid.len) == 0) {
|
||||||
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
|
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
|
||||||
}
|
}
|
||||||
else if (memcmp(oid, OID_HMAC_SHA384, oid_len) == 0) {
|
else if (memcmp(oid.data, OID_HMAC_SHA384, oid.len) == 0) {
|
||||||
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA384);
|
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA384);
|
||||||
}
|
}
|
||||||
else if (memcmp(oid, OID_HMAC_SHA512, oid_len) == 0) {
|
else if (memcmp(oid.data, OID_HMAC_SHA512, oid.len) == 0) {
|
||||||
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA512);
|
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA512);
|
||||||
}
|
}
|
||||||
if (md_info == NULL) {
|
if (md_info == NULL) {
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
}
|
}
|
||||||
int r = mbedtls_md_hmac(md_info, kdata, key_size, enc, enc_len, res_APDU);
|
int r = mbedtls_md_hmac(md_info, kdata, key_size, enc.data, enc.len, res_APDU);
|
||||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
res_APDU_size = md_info->size;
|
res_APDU_size = mbedtls_md_get_size(md_info);
|
||||||
}
|
}
|
||||||
else if (memcmp(oid, OID_HKDF_SHA256,
|
else if (memcmp(oid.data, OID_HKDF_SHA256,
|
||||||
oid_len) == 0 ||
|
oid.len) == 0 ||
|
||||||
memcmp(oid, OID_HKDF_SHA384,
|
memcmp(oid.data, OID_HKDF_SHA384,
|
||||||
oid_len) == 0 || memcmp(oid, OID_HKDF_SHA512, oid_len) == 0) {
|
oid.len) == 0 || memcmp(oid.data, OID_HKDF_SHA512, oid.len) == 0) {
|
||||||
const mbedtls_md_info_t *md_info = NULL;
|
const mbedtls_md_info_t *md_info = NULL;
|
||||||
if (memcmp(oid, OID_HKDF_SHA256, oid_len) == 0) {
|
if (memcmp(oid.data, OID_HKDF_SHA256, oid.len) == 0) {
|
||||||
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
|
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
|
||||||
}
|
}
|
||||||
else if (memcmp(oid, OID_HKDF_SHA384, oid_len) == 0) {
|
else if (memcmp(oid.data, OID_HKDF_SHA384, oid.len) == 0) {
|
||||||
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA384);
|
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA384);
|
||||||
}
|
}
|
||||||
else if (memcmp(oid, OID_HKDF_SHA512, oid_len) == 0) {
|
else if (memcmp(oid.data, OID_HKDF_SHA512, oid.len) == 0) {
|
||||||
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA512);
|
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA512);
|
||||||
}
|
}
|
||||||
int r = mbedtls_hkdf(md_info,
|
int r = mbedtls_hkdf(md_info,
|
||||||
iv,
|
iv.data,
|
||||||
iv_len,
|
iv.len,
|
||||||
kdata,
|
kdata,
|
||||||
key_size,
|
key_size,
|
||||||
enc,
|
enc.data,
|
||||||
enc_len,
|
enc.len,
|
||||||
res_APDU,
|
res_APDU,
|
||||||
apdu.ne > 0 &&
|
apdu.ne > 0 &&
|
||||||
apdu.ne < 65536 ? apdu.ne : mbedtls_md_get_size(md_info));
|
apdu.ne < 65536 ? apdu.ne : mbedtls_md_get_size(md_info));
|
||||||
@@ -374,13 +378,14 @@ int cmd_cipher_sym() {
|
|||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
res_APDU_size = apdu.ne > 0 && apdu.ne < 65536 ? apdu.ne : mbedtls_md_get_size(md_info);
|
res_APDU_size = apdu.ne > 0 && apdu.ne < 65536 ? (uint16_t)apdu.ne : (uint16_t)mbedtls_md_get_size(md_info);
|
||||||
}
|
}
|
||||||
else if (memcmp(oid, OID_PKCS5_PBKDF2, oid_len) == 0) {
|
else if (memcmp(oid.data, OID_PKCS5_PBKDF2, oid.len) == 0) {
|
||||||
int iterations = 0, keylen = 0;
|
int iterations = 0;
|
||||||
|
uint16_t keylen = 0;
|
||||||
mbedtls_asn1_buf salt,
|
mbedtls_asn1_buf salt,
|
||||||
params =
|
params =
|
||||||
{ .p = enc, .len = enc_len, .tag = (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) };
|
{ .p = enc.data, .len = enc.len, .tag = (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) };
|
||||||
mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1;
|
mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1;
|
||||||
|
|
||||||
int r = pkcs5_parse_pbkdf2_params(¶ms, &salt, &iterations, &keylen, &md_type);
|
int r = pkcs5_parse_pbkdf2_params(¶ms, &salt, &iterations, &keylen, &md_type);
|
||||||
@@ -402,53 +407,301 @@ int cmd_cipher_sym() {
|
|||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
res_APDU_size = keylen ? keylen : (apdu.ne > 0 && apdu.ne < 65536 ? apdu.ne : 32);
|
res_APDU_size = keylen ? keylen : (apdu.ne > 0 && apdu.ne < 65536 ? (uint16_t)apdu.ne : 32);
|
||||||
}
|
}
|
||||||
else if (memcmp(oid, OID_PKCS5_PBES2, oid_len) == 0) {
|
else if (memcmp(oid.data, OID_PKCS5_PBES2, oid.len) == 0) {
|
||||||
|
size_t olen = 0;
|
||||||
mbedtls_asn1_buf params =
|
mbedtls_asn1_buf params =
|
||||||
{ .p = aad, .len = aad_len, .tag = (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) };
|
{.p = aad.data, .len = aad.len, .tag = (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)};
|
||||||
int r = mbedtls_pkcs5_pbes2(¶ms,
|
int r = mbedtls_pkcs5_pbes2_ext(¶ms,
|
||||||
algo == ALGO_EXT_CIPHER_ENCRYPT ? MBEDTLS_PKCS5_ENCRYPT : MBEDTLS_PKCS5_DECRYPT,
|
algo == ALGO_EXT_CIPHER_ENCRYPT ? MBEDTLS_PKCS5_ENCRYPT : MBEDTLS_PKCS5_DECRYPT,
|
||||||
kdata,
|
kdata,
|
||||||
key_size,
|
key_size,
|
||||||
enc,
|
enc.data,
|
||||||
enc_len,
|
enc.len,
|
||||||
res_APDU);
|
res_APDU, 4096, &olen);
|
||||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
}
|
}
|
||||||
res_APDU_size = enc_len;
|
res_APDU_size = (uint16_t)olen;
|
||||||
}
|
}
|
||||||
else if (memcmp(oid, OID_KDF_X963, oid_len) == 0) {
|
else if (memcmp(oid.data, OID_KDF_X963, oid.len) == 0) {
|
||||||
mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1;
|
mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1;
|
||||||
if (memcmp(enc, OID_HMAC_SHA1, enc_len) == 0) {
|
if (memcmp(enc.data, OID_HMAC_SHA1, enc.len) == 0) {
|
||||||
md_type = MBEDTLS_MD_SHA1;
|
md_type = MBEDTLS_MD_SHA1;
|
||||||
}
|
}
|
||||||
else if (memcmp(enc, OID_HMAC_SHA224, enc_len) == 0) {
|
else if (memcmp(enc.data, OID_HMAC_SHA224, enc.len) == 0) {
|
||||||
md_type = MBEDTLS_MD_SHA224;
|
md_type = MBEDTLS_MD_SHA224;
|
||||||
}
|
}
|
||||||
else if (memcmp(enc, OID_HMAC_SHA256, enc_len) == 0) {
|
else if (memcmp(enc.data, OID_HMAC_SHA256, enc.len) == 0) {
|
||||||
md_type = MBEDTLS_MD_SHA256;
|
md_type = MBEDTLS_MD_SHA256;
|
||||||
}
|
}
|
||||||
else if (memcmp(enc, OID_HMAC_SHA384, enc_len) == 0) {
|
else if (memcmp(enc.data, OID_HMAC_SHA384, enc.len) == 0) {
|
||||||
md_type = MBEDTLS_MD_SHA384;
|
md_type = MBEDTLS_MD_SHA384;
|
||||||
}
|
}
|
||||||
else if (memcmp(enc, OID_HMAC_SHA512, enc_len) == 0) {
|
else if (memcmp(enc.data, OID_HMAC_SHA512, enc.len) == 0) {
|
||||||
md_type = MBEDTLS_MD_SHA512;
|
md_type = MBEDTLS_MD_SHA512;
|
||||||
}
|
}
|
||||||
int r = mbedtls_ansi_x963_kdf(md_type,
|
int r = mbedtls_ansi_x963_kdf(md_type,
|
||||||
key_size,
|
key_size,
|
||||||
kdata,
|
kdata,
|
||||||
aad_len,
|
aad.len,
|
||||||
aad,
|
aad.data,
|
||||||
apdu.ne > 0 && apdu.ne < 65536 ? apdu.ne : 32,
|
apdu.ne > 0 && apdu.ne < 65536 ? (uint16_t)apdu.ne : 32,
|
||||||
res_APDU);
|
res_APDU);
|
||||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
}
|
}
|
||||||
res_APDU_size = apdu.ne > 0 && apdu.ne < 65536 ? apdu.ne : 32;
|
res_APDU_size = apdu.ne > 0 && apdu.ne < 65536 ? (uint16_t)apdu.ne : 32;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid.data, OID_NIST_AES, 8) == 0) {
|
||||||
|
if (oid.len != 9) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
uint8_t aes_algo = oid.data[8],
|
||||||
|
mode =
|
||||||
|
(algo == ALGO_EXT_CIPHER_ENCRYPT ? MBEDTLS_AES_ENCRYPT : MBEDTLS_AES_DECRYPT);
|
||||||
|
if ((aes_algo >= 0x01 && aes_algo <= 0x09 && key_size != 16) ||
|
||||||
|
(aes_algo >= 0x15 && aes_algo <= 0x1D && key_size != 24) ||
|
||||||
|
(aes_algo >= 0x29 && aes_algo <= 0x31 && key_size != 32)) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
mbedtls_aes_context ctx;
|
||||||
|
int r = 0;
|
||||||
|
mbedtls_aes_init(&ctx);
|
||||||
|
if (asn1_len(&iv) == 0) {
|
||||||
|
iv.data = tmp_iv;
|
||||||
|
iv.len = sizeof(tmp_iv);
|
||||||
|
}
|
||||||
|
if (aes_algo == 0x01 || aes_algo == 0x15 || aes_algo == 0x29) { /* ECB */
|
||||||
|
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
||||||
|
r = mbedtls_aes_setkey_enc(&ctx, kdata, key_size * 8);
|
||||||
|
}
|
||||||
|
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||||
|
r = mbedtls_aes_setkey_dec(&ctx, kdata, key_size * 8);
|
||||||
|
}
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
r = mbedtls_aes_crypt_ecb(&ctx, mode, enc.data, res_APDU);
|
||||||
|
mbedtls_aes_free(&ctx);
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
res_APDU_size = MIN(enc.len, 16); // ECB operates with 16-byte blocks
|
||||||
|
}
|
||||||
|
else if (aes_algo == 0x02 || aes_algo == 0x16 || aes_algo == 0x2A) { /* CBC */
|
||||||
|
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
||||||
|
r = mbedtls_aes_setkey_enc(&ctx, kdata, key_size * 8);
|
||||||
|
}
|
||||||
|
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||||
|
r = mbedtls_aes_setkey_dec(&ctx, kdata, key_size * 8);
|
||||||
|
}
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
r = mbedtls_aes_crypt_cbc(&ctx, mode, enc.len, iv.data, enc.data, res_APDU);
|
||||||
|
mbedtls_aes_free(&ctx);
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
res_APDU_size = enc.len;
|
||||||
|
}
|
||||||
|
else if (aes_algo == 0x03 || aes_algo == 0x17 || aes_algo == 0x2B) { /* OFB */
|
||||||
|
size_t iv_off = 0;
|
||||||
|
r = mbedtls_aes_setkey_enc(&ctx, kdata, key_size * 8);
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
r = mbedtls_aes_crypt_ofb(&ctx, enc.len, &iv_off, iv.data, enc.data, res_APDU);
|
||||||
|
mbedtls_aes_free(&ctx);
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
res_APDU_size = enc.len;
|
||||||
|
}
|
||||||
|
else if (aes_algo == 0x04 || aes_algo == 0x18 || aes_algo == 0x2C) { /* CFB */
|
||||||
|
size_t iv_off = 0;
|
||||||
|
r = mbedtls_aes_setkey_enc(&ctx, kdata, key_size * 8);
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
r = mbedtls_aes_crypt_cfb128(&ctx, mode, enc.len, &iv_off, iv.data, enc.data, res_APDU);
|
||||||
|
mbedtls_aes_free(&ctx);
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
res_APDU_size = enc.len;
|
||||||
|
}
|
||||||
|
else if (aes_algo == 0x06 || aes_algo == 0x1A || aes_algo == 0x2E) { /* GCM */
|
||||||
|
mbedtls_aes_free(&ctx); // No AES ctx used
|
||||||
|
mbedtls_gcm_context gctx;
|
||||||
|
mbedtls_gcm_init(&gctx);
|
||||||
|
r = mbedtls_gcm_setkey(&gctx, MBEDTLS_CIPHER_ID_AES, kdata, key_size * 8);
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
||||||
|
r = mbedtls_gcm_crypt_and_tag(&gctx,
|
||||||
|
MBEDTLS_GCM_ENCRYPT,
|
||||||
|
enc.len,
|
||||||
|
iv.data,
|
||||||
|
iv.len,
|
||||||
|
aad.data,
|
||||||
|
aad.len,
|
||||||
|
enc.data,
|
||||||
|
res_APDU,
|
||||||
|
16,
|
||||||
|
res_APDU + enc.len);
|
||||||
|
res_APDU_size = enc.len + 16;
|
||||||
|
}
|
||||||
|
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||||
|
r = mbedtls_gcm_auth_decrypt(&gctx,
|
||||||
|
enc.len - 16,
|
||||||
|
iv.data,
|
||||||
|
iv.len,
|
||||||
|
aad.data,
|
||||||
|
aad.len,
|
||||||
|
enc.data + enc.len - 16,
|
||||||
|
16,
|
||||||
|
enc.data,
|
||||||
|
res_APDU);
|
||||||
|
res_APDU_size = enc.len - 16;
|
||||||
|
}
|
||||||
|
mbedtls_gcm_free(&gctx);
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (aes_algo == 0x09 || aes_algo == 0x1D || aes_algo == 0x31) { /* CTR */
|
||||||
|
size_t iv_off = 0;
|
||||||
|
uint8_t stream_block[16];
|
||||||
|
r = mbedtls_aes_setkey_enc(&ctx, kdata, key_size * 8);
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
r = mbedtls_aes_crypt_ctr(&ctx, enc.len, &iv_off, iv.data, stream_block, enc.data, res_APDU);
|
||||||
|
mbedtls_aes_free(&ctx);
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
res_APDU_size = enc.len;
|
||||||
|
}
|
||||||
|
else if (aes_algo == 0x07 || aes_algo == 0x1B || aes_algo == 0x2F) { /* CCM */
|
||||||
|
mbedtls_aes_free(&ctx); // No AES ctx used
|
||||||
|
mbedtls_ccm_context gctx;
|
||||||
|
mbedtls_ccm_init(&gctx);
|
||||||
|
r = mbedtls_ccm_setkey(&gctx, MBEDTLS_CIPHER_ID_AES, kdata, key_size * 8);
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
if (iv.len == 16) {
|
||||||
|
iv.len = 12;
|
||||||
|
}
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
||||||
|
r = mbedtls_ccm_encrypt_and_tag(&gctx,
|
||||||
|
enc.len,
|
||||||
|
iv.data,
|
||||||
|
iv.len,
|
||||||
|
aad.data,
|
||||||
|
aad.len,
|
||||||
|
enc.data,
|
||||||
|
res_APDU,
|
||||||
|
res_APDU + enc.len,
|
||||||
|
16);
|
||||||
|
res_APDU_size = enc.len + 16;
|
||||||
|
}
|
||||||
|
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||||
|
r = mbedtls_ccm_auth_decrypt(&gctx,
|
||||||
|
enc.len - 16,
|
||||||
|
iv.data,
|
||||||
|
iv.len,
|
||||||
|
aad.data,
|
||||||
|
aad.len,
|
||||||
|
enc.data,
|
||||||
|
res_APDU,
|
||||||
|
enc.data + enc.len - 16,
|
||||||
|
16);
|
||||||
|
res_APDU_size = enc.len - 16;
|
||||||
|
}
|
||||||
|
mbedtls_ccm_free(&gctx);
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (memcmp(oid.data, OID_IEEE_ALG, 8) == 0) {
|
||||||
|
if (oid.len != 9) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
uint8_t aes_algo = oid.data[8],
|
||||||
|
mode =
|
||||||
|
(algo == ALGO_EXT_CIPHER_ENCRYPT ? MBEDTLS_AES_ENCRYPT : MBEDTLS_AES_DECRYPT);
|
||||||
|
int r = 0;
|
||||||
|
memset(tmp_iv, 0, sizeof(tmp_iv));
|
||||||
|
if (asn1_len(&iv) == 0) {
|
||||||
|
iv.data = tmp_iv;
|
||||||
|
iv.len = sizeof(tmp_iv);
|
||||||
|
}
|
||||||
|
if ((aes_algo == 0x01 && key_size != 32) || (aes_algo == 0x02 && key_size != 64)) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
mbedtls_aes_xts_context ctx;
|
||||||
|
mbedtls_aes_xts_init(&ctx);
|
||||||
|
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
||||||
|
r = mbedtls_aes_xts_setkey_enc(&ctx, kdata, key_size * 8);
|
||||||
|
}
|
||||||
|
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||||
|
r = mbedtls_aes_xts_setkey_dec(&ctx, kdata, key_size * 8);
|
||||||
|
}
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
r = mbedtls_aes_crypt_xts(&ctx, mode, enc.len, iv.data, enc.data, res_APDU);
|
||||||
|
mbedtls_aes_xts_free(&ctx);
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
res_APDU_size = enc.len;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid.data, OID_HD, 11) == 0) {
|
||||||
|
mbedtls_aes_context ctx;
|
||||||
|
int r = 0;
|
||||||
|
uint8_t mode =
|
||||||
|
(algo == ALGO_EXT_CIPHER_ENCRYPT ? MBEDTLS_AES_ENCRYPT : MBEDTLS_AES_DECRYPT),
|
||||||
|
secret[64] = { 0 };
|
||||||
|
mbedtls_aes_init(&ctx);
|
||||||
|
if (hd_keytype != 0x3) {
|
||||||
|
return SW_INCORRECT_PARAMS();
|
||||||
|
}
|
||||||
|
key_size = 32;
|
||||||
|
mbedtls_mpi_write_binary(&hd_context.d, kdata, key_size);
|
||||||
|
r = mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA512),
|
||||||
|
kdata,
|
||||||
|
key_size,
|
||||||
|
aad.data,
|
||||||
|
aad.len,
|
||||||
|
secret);
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
if (iv.data == tmp_iv || iv.len == 0) {
|
||||||
|
iv.data = secret + 32;
|
||||||
|
iv.len = 16;
|
||||||
|
}
|
||||||
|
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
||||||
|
r = mbedtls_aes_setkey_enc(&ctx, secret, key_size * 8);
|
||||||
|
}
|
||||||
|
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||||
|
r = mbedtls_aes_setkey_dec(&ctx, secret, key_size * 8);
|
||||||
|
}
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
r = mbedtls_aes_crypt_cbc(&ctx, mode, enc.len, iv.data, enc.data, res_APDU);
|
||||||
|
mbedtls_aes_free(&ctx);
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
res_APDU_size = enc.len;
|
||||||
|
mbedtls_ecdsa_free(&hd_context);
|
||||||
|
hd_keytype = 0;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
|
|||||||
@@ -15,10 +15,9 @@
|
|||||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include "common.h"
|
#include "sc_hsm.h"
|
||||||
#include "mbedtls/ecdh.h"
|
#include "mbedtls/ecdh.h"
|
||||||
#include "crypto_utils.h"
|
#include "crypto_utils.h"
|
||||||
#include "sc_hsm.h"
|
|
||||||
#include "kek.h"
|
#include "kek.h"
|
||||||
#include "files.h"
|
#include "files.h"
|
||||||
#include "asn1.h"
|
#include "asn1.h"
|
||||||
@@ -27,12 +26,12 @@
|
|||||||
#include "oid.h"
|
#include "oid.h"
|
||||||
|
|
||||||
int cmd_decrypt_asym() {
|
int cmd_decrypt_asym() {
|
||||||
int key_id = P1(apdu);
|
uint8_t key_id = P1(apdu);
|
||||||
uint8_t p2 = P2(apdu);
|
uint8_t p2 = P2(apdu);
|
||||||
if (!isUserAuthenticated) {
|
if (!isUserAuthenticated) {
|
||||||
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
}
|
}
|
||||||
file_t *ef = search_dynamic_file((KEY_PREFIX << 8) | key_id);
|
file_t *ef = search_file((KEY_PREFIX << 8) | key_id);
|
||||||
if (!ef) {
|
if (!ef) {
|
||||||
return SW_FILE_NOT_FOUND();
|
return SW_FILE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
@@ -56,7 +55,7 @@ int cmd_decrypt_asym() {
|
|||||||
}
|
}
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
int key_size = file_get_size(ef);
|
uint16_t key_size = file_get_size(ef);
|
||||||
if (apdu.nc < key_size) { //needs padding
|
if (apdu.nc < key_size) { //needs padding
|
||||||
memset(apdu.data + apdu.nc, 0, key_size - apdu.nc);
|
memset(apdu.data + apdu.nc, 0, key_size - apdu.nc);
|
||||||
}
|
}
|
||||||
@@ -64,7 +63,7 @@ int cmd_decrypt_asym() {
|
|||||||
size_t olen = apdu.nc;
|
size_t olen = apdu.nc;
|
||||||
r = mbedtls_rsa_pkcs1_decrypt(&ctx, random_gen, NULL, &olen, apdu.data, res_APDU, 512);
|
r = mbedtls_rsa_pkcs1_decrypt(&ctx, random_gen, NULL, &olen, apdu.data, res_APDU, 512);
|
||||||
if (r == 0) {
|
if (r == 0) {
|
||||||
res_APDU_size = olen;
|
res_APDU_size = (uint16_t)olen;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
@@ -84,7 +83,7 @@ int cmd_decrypt_asym() {
|
|||||||
if (wait_button_pressed() == true) { //timeout
|
if (wait_button_pressed() == true) { //timeout
|
||||||
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
int key_size = file_get_size(ef);
|
uint16_t key_size = file_get_size(ef);
|
||||||
uint8_t *kdata = (uint8_t *) calloc(1, key_size);
|
uint8_t *kdata = (uint8_t *) calloc(1, key_size);
|
||||||
memcpy(kdata, file_get_data(ef), key_size);
|
memcpy(kdata, file_get_data(ef), key_size);
|
||||||
if (mkek_decrypt(kdata, key_size) != 0) {
|
if (mkek_decrypt(kdata, key_size) != 0) {
|
||||||
@@ -102,7 +101,7 @@ int cmd_decrypt_asym() {
|
|||||||
free(kdata);
|
free(kdata);
|
||||||
return SW_DATA_INVALID();
|
return SW_DATA_INVALID();
|
||||||
}
|
}
|
||||||
r = mbedtls_mpi_read_binary(&ctx.ctx.mbed_ecdh.d, kdata + 1, key_size - 1);
|
r = mbedtls_ecp_read_key(gid, (mbedtls_ecdsa_context *)&ctx.ctx.mbed_ecdh, kdata + 1, key_size - 1);
|
||||||
mbedtls_platform_zeroize(kdata, key_size);
|
mbedtls_platform_zeroize(kdata, key_size);
|
||||||
free(kdata);
|
free(kdata);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
@@ -111,15 +110,18 @@ int cmd_decrypt_asym() {
|
|||||||
}
|
}
|
||||||
r = -1;
|
r = -1;
|
||||||
if (p2 == ALGO_EC_DH) {
|
if (p2 == ALGO_EC_DH) {
|
||||||
|
*(apdu.data - 1) = (uint8_t)apdu.nc;
|
||||||
r = mbedtls_ecdh_read_public(&ctx, apdu.data - 1, apdu.nc + 1);
|
r = mbedtls_ecdh_read_public(&ctx, apdu.data - 1, apdu.nc + 1);
|
||||||
}
|
}
|
||||||
else if (p2 == ALGO_EC_DH_XKEK) {
|
else if (p2 == ALGO_EC_DH_XKEK) {
|
||||||
size_t pub_len = 0;
|
uint16_t pub_len = 0;
|
||||||
const uint8_t *pub = cvc_get_pub(apdu.data, apdu.nc, &pub_len);
|
const uint8_t *pub = cvc_get_pub(apdu.data, (uint16_t)apdu.nc, &pub_len);
|
||||||
if (pub) {
|
if (pub) {
|
||||||
size_t t86_len = 0;
|
uint16_t t86_len = 0;
|
||||||
const uint8_t *t86 = cvc_get_field(pub, pub_len, &t86_len, 0x86);
|
const uint8_t *t86 = cvc_get_field(pub, pub_len, &t86_len, 0x86);
|
||||||
|
uint8_t *t86w = (uint8_t *)t86;
|
||||||
if (t86) {
|
if (t86) {
|
||||||
|
*(t86w - 1) = (uint8_t)t86_len;
|
||||||
r = mbedtls_ecdh_read_public(&ctx, t86 - 1, t86_len + 1);
|
r = mbedtls_ecdh_read_public(&ctx, t86 - 1, t86_len + 1);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -129,55 +131,57 @@ int cmd_decrypt_asym() {
|
|||||||
return SW_DATA_INVALID();
|
return SW_DATA_INVALID();
|
||||||
}
|
}
|
||||||
size_t olen = 0;
|
size_t olen = 0;
|
||||||
|
// The SmartCard-HSM returns the point result of the DH operation
|
||||||
|
// with a leading '04'
|
||||||
|
res_APDU[0] = 0x04;
|
||||||
r =
|
r =
|
||||||
mbedtls_ecdh_calc_secret(&ctx, &olen, res_APDU, MBEDTLS_ECP_MAX_BYTES, random_gen,
|
mbedtls_ecdh_calc_secret(&ctx, &olen, res_APDU + 1, MBEDTLS_ECP_MAX_BYTES, random_gen,
|
||||||
NULL);
|
NULL);
|
||||||
mbedtls_ecdh_free(&ctx);
|
mbedtls_ecdh_free(&ctx);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
if (p2 == ALGO_EC_DH) {
|
if (p2 == ALGO_EC_DH) {
|
||||||
res_APDU_size = olen;
|
res_APDU_size = (uint16_t)(olen + 1);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
res_APDU_size = 0;
|
res_APDU_size = 0;
|
||||||
size_t ext_len = 0;
|
uint16_t ext_len = 0;
|
||||||
const uint8_t *ext = NULL;
|
const uint8_t *ext = NULL;
|
||||||
if ((ext = cvc_get_ext(apdu.data, apdu.nc, &ext_len)) == NULL) {
|
if ((ext = cvc_get_ext(apdu.data, (uint16_t)apdu.nc, &ext_len)) == NULL) {
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
}
|
}
|
||||||
uint8_t *p = NULL, *tag_data = NULL, *kdom_uid = NULL;
|
uint8_t *p = NULL;
|
||||||
uint16_t tag = 0;
|
uint16_t tag = 0;
|
||||||
size_t tag_len = 0, kdom_uid_len = 0;
|
asn1_ctx_t ctxi, ctxo = { 0 }, kdom_uid = { 0 };
|
||||||
while (walk_tlv(ext, ext_len, &p, &tag, &tag_len, &tag_data)) {
|
asn1_ctx_init((uint8_t *)ext, ext_len, &ctxi);
|
||||||
|
while (walk_tlv(&ctxi, &p, &tag, &ctxo.len, &ctxo.data)) {
|
||||||
if (tag == 0x73) {
|
if (tag == 0x73) {
|
||||||
size_t oid_len = 0;
|
asn1_ctx_t oid = {0};
|
||||||
uint8_t *oid_data = NULL;
|
if (asn1_find_tag(&ctxo, 0x6, &oid) == true &&
|
||||||
if (asn1_find_tag(tag_data, tag_len, 0x6, &oid_len,
|
oid.len == strlen(OID_ID_KEY_DOMAIN_UID) &&
|
||||||
&oid_data) == true &&
|
memcmp(oid.data, OID_ID_KEY_DOMAIN_UID,
|
||||||
oid_len == strlen(OID_ID_KEY_DOMAIN_UID) &&
|
|
||||||
memcmp(oid_data, OID_ID_KEY_DOMAIN_UID,
|
|
||||||
strlen(OID_ID_KEY_DOMAIN_UID)) == 0) {
|
strlen(OID_ID_KEY_DOMAIN_UID)) == 0) {
|
||||||
if (asn1_find_tag(tag_data, tag_len, 0x80, &kdom_uid_len,
|
if (asn1_find_tag(&ctxo, 0x80, &kdom_uid) == false) {
|
||||||
&kdom_uid) == false) {
|
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
}
|
}
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (kdom_uid_len == 0 || kdom_uid == NULL) {
|
if (asn1_len(&kdom_uid) == 0) {
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
}
|
}
|
||||||
for (int n = 0; n < MAX_KEY_DOMAINS; n++) {
|
for (uint8_t n = 0; n < MAX_KEY_DOMAINS; n++) {
|
||||||
file_t *tf = search_dynamic_file(EF_XKEK + n);
|
file_t *tf = search_file(EF_XKEK + n);
|
||||||
if (tf) {
|
if (tf) {
|
||||||
if (file_get_size(tf) == kdom_uid_len &&
|
if (file_get_size(tf) == kdom_uid.len &&
|
||||||
memcmp(file_get_data(tf), kdom_uid, kdom_uid_len) == 0) {
|
memcmp(file_get_data(tf), kdom_uid.data, kdom_uid.len) == 0) {
|
||||||
file_new(EF_DKEK + n);
|
file_new(EF_DKEK + n);
|
||||||
if (store_dkek_key(n, res_APDU) != CCID_OK) {
|
if (store_dkek_key(n, res_APDU + 1) != CCID_OK) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
|
mbedtls_platform_zeroize(res_APDU, 32);
|
||||||
return SW_OK();
|
return SW_OK();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -25,13 +25,13 @@ int cmd_delete_file() {
|
|||||||
|
|
||||||
if (apdu.nc == 0) {
|
if (apdu.nc == 0) {
|
||||||
ef = currentEF;
|
ef = currentEF;
|
||||||
if (!(ef = search_dynamic_file(ef->fid))) {
|
if (!(ef = search_file(ef->fid))) {
|
||||||
return SW_FILE_NOT_FOUND();
|
return SW_FILE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
uint16_t fid = (apdu.data[0] << 8) | apdu.data[1];
|
uint16_t fid = (apdu.data[0] << 8) | apdu.data[1];
|
||||||
if (!(ef = search_dynamic_file(fid))) {
|
if (!(ef = search_file(fid))) {
|
||||||
return SW_FILE_NOT_FOUND();
|
return SW_FILE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,10 +15,9 @@
|
|||||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include "common.h"
|
#include "sc_hsm.h"
|
||||||
#include "mbedtls/ecdsa.h"
|
#include "mbedtls/ecdsa.h"
|
||||||
#include "crypto_utils.h"
|
#include "crypto_utils.h"
|
||||||
#include "sc_hsm.h"
|
|
||||||
#include "cvc.h"
|
#include "cvc.h"
|
||||||
|
|
||||||
#define MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED -0x006E
|
#define MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED -0x006E
|
||||||
@@ -43,7 +42,7 @@ int cmd_derive_asym() {
|
|||||||
if (!isUserAuthenticated) {
|
if (!isUserAuthenticated) {
|
||||||
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
}
|
}
|
||||||
if (!(fkey = search_dynamic_file((KEY_PREFIX << 8) | key_id)) || !file_has_data(fkey)) {
|
if (!(fkey = search_file((KEY_PREFIX << 8) | key_id)) || !file_has_data(fkey)) {
|
||||||
return SW_FILE_NOT_FOUND();
|
return SW_FILE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
if (key_has_purpose(fkey, ALGO_EC_DERIVE) == false) {
|
if (key_has_purpose(fkey, ALGO_EC_DERIVE) == false) {
|
||||||
@@ -53,13 +52,13 @@ int cmd_derive_asym() {
|
|||||||
return SW_WRONG_LENGTH();
|
return SW_WRONG_LENGTH();
|
||||||
}
|
}
|
||||||
if (apdu.data[0] == ALGO_EC_DERIVE) {
|
if (apdu.data[0] == ALGO_EC_DERIVE) {
|
||||||
mbedtls_ecdsa_context ctx;
|
mbedtls_ecp_keypair ctx;
|
||||||
mbedtls_ecdsa_init(&ctx);
|
mbedtls_ecp_keypair_init(&ctx);
|
||||||
|
|
||||||
int r;
|
int r;
|
||||||
r = load_private_key_ecdsa(&ctx, fkey);
|
r = load_private_key_ec(&ctx, fkey);
|
||||||
if (r != CCID_OK) {
|
if (r != CCID_OK) {
|
||||||
mbedtls_ecdsa_free(&ctx);
|
mbedtls_ecp_keypair_free(&ctx);
|
||||||
if (r == CCID_VERIFICATION_FAILED) {
|
if (r == CCID_VERIFICATION_FAILED) {
|
||||||
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
@@ -70,7 +69,7 @@ int cmd_derive_asym() {
|
|||||||
mbedtls_mpi_init(&nd);
|
mbedtls_mpi_init(&nd);
|
||||||
r = mbedtls_mpi_read_binary(&a, apdu.data + 1, apdu.nc - 1);
|
r = mbedtls_mpi_read_binary(&a, apdu.data + 1, apdu.nc - 1);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
mbedtls_ecdsa_free(&ctx);
|
mbedtls_ecp_keypair_free(&ctx);
|
||||||
mbedtls_mpi_free(&a);
|
mbedtls_mpi_free(&a);
|
||||||
mbedtls_mpi_free(&nd);
|
mbedtls_mpi_free(&nd);
|
||||||
return SW_DATA_INVALID();
|
return SW_DATA_INVALID();
|
||||||
@@ -78,22 +77,22 @@ int cmd_derive_asym() {
|
|||||||
r = mbedtls_mpi_add_mod(&ctx.grp, &nd, &ctx.d, &a);
|
r = mbedtls_mpi_add_mod(&ctx.grp, &nd, &ctx.d, &a);
|
||||||
mbedtls_mpi_free(&a);
|
mbedtls_mpi_free(&a);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
mbedtls_ecdsa_free(&ctx);
|
mbedtls_ecp_keypair_free(&ctx);
|
||||||
mbedtls_mpi_free(&nd);
|
mbedtls_mpi_free(&nd);
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
r = mbedtls_mpi_copy(&ctx.d, &nd);
|
r = mbedtls_mpi_copy(&ctx.d, &nd);
|
||||||
mbedtls_mpi_free(&nd);
|
mbedtls_mpi_free(&nd);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
mbedtls_ecdsa_free(&ctx);
|
mbedtls_ecp_keypair_free(&ctx);
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
r = store_keys(&ctx, HSM_KEY_EC, dest_id);
|
r = store_keys(&ctx, PICO_KEYS_KEY_EC, dest_id);
|
||||||
if (r != CCID_OK) {
|
if (r != CCID_OK) {
|
||||||
mbedtls_ecdsa_free(&ctx);
|
mbedtls_ecp_keypair_free(&ctx);
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
mbedtls_ecdsa_free(&ctx);
|
mbedtls_ecp_keypair_free(&ctx);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
|
|||||||
@@ -34,10 +34,11 @@ int cmd_external_authenticate() {
|
|||||||
if (apdu.nc == 0) {
|
if (apdu.nc == 0) {
|
||||||
return SW_WRONG_LENGTH();
|
return SW_WRONG_LENGTH();
|
||||||
}
|
}
|
||||||
file_t *ef_puk = search_by_fid(EF_PUKAUT, NULL, SPECIFY_EF);
|
file_t *ef_puk = search_file(EF_PUKAUT);
|
||||||
if (!file_has_data(ef_puk)) {
|
if (!file_has_data(ef_puk)) {
|
||||||
return SW_FILE_NOT_FOUND();
|
return SW_FILE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
|
puk_status[ef_puk_aut->fid & (MAX_PUK - 1)] = 0;
|
||||||
uint8_t *puk_data = file_get_data(ef_puk);
|
uint8_t *puk_data = file_get_data(ef_puk);
|
||||||
uint8_t *input = (uint8_t *) calloc(dev_name_len + challenge_len, sizeof(uint8_t)), hash[32];
|
uint8_t *input = (uint8_t *) calloc(dev_name_len + challenge_len, sizeof(uint8_t)), hash[32];
|
||||||
memcpy(input, dev_name, dev_name_len);
|
memcpy(input, dev_name, dev_name_len);
|
||||||
@@ -45,7 +46,7 @@ int cmd_external_authenticate() {
|
|||||||
hash256(input, dev_name_len + challenge_len, hash);
|
hash256(input, dev_name_len + challenge_len, hash);
|
||||||
int r =
|
int r =
|
||||||
puk_verify(apdu.data,
|
puk_verify(apdu.data,
|
||||||
apdu.nc,
|
(uint16_t)apdu.nc,
|
||||||
hash,
|
hash,
|
||||||
32,
|
32,
|
||||||
file_get_data(ef_puk_aut),
|
file_get_data(ef_puk_aut),
|
||||||
|
|||||||
@@ -15,11 +15,13 @@
|
|||||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include "common.h"
|
|
||||||
#include "mbedtls/ecdh.h"
|
|
||||||
#include "sc_hsm.h"
|
#include "sc_hsm.h"
|
||||||
#ifndef ENABLE_EMULATION
|
#include "mbedtls/ecdh.h"
|
||||||
|
#if !defined(ENABLE_EMULATION) && !defined(ESP_PLATFORM)
|
||||||
#include "hardware/rtc.h"
|
#include "hardware/rtc.h"
|
||||||
|
#else
|
||||||
|
#include <sys/time.h>
|
||||||
|
#include <time.h>
|
||||||
#endif
|
#endif
|
||||||
#include "files.h"
|
#include "files.h"
|
||||||
#include "random.h"
|
#include "random.h"
|
||||||
@@ -28,12 +30,22 @@
|
|||||||
#include "mbedtls/chachapoly.h"
|
#include "mbedtls/chachapoly.h"
|
||||||
|
|
||||||
int cmd_extras() {
|
int cmd_extras() {
|
||||||
|
#ifndef ENABLE_EMULATION
|
||||||
|
// Only allow change PHY without PIN
|
||||||
|
if (!isUserAuthenticated && P1(apdu) != 0x1B) {
|
||||||
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
//check button (if enabled)
|
||||||
|
if (wait_button_pressed() == true) {
|
||||||
|
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||||
|
}
|
||||||
if (P1(apdu) == 0xA) { //datetime operations
|
if (P1(apdu) == 0xA) { //datetime operations
|
||||||
if (P2(apdu) != 0x0) {
|
if (P2(apdu) != 0x0) {
|
||||||
return SW_INCORRECT_P1P2();
|
return SW_INCORRECT_P1P2();
|
||||||
}
|
}
|
||||||
if (apdu.nc == 0) {
|
if (apdu.nc == 0) {
|
||||||
#ifndef ENABLE_EMULATION
|
#if !defined(ENABLE_EMULATION) && !defined(ESP_PLATFORM)
|
||||||
datetime_t dt;
|
datetime_t dt;
|
||||||
if (!rtc_get_datetime(&dt)) {
|
if (!rtc_get_datetime(&dt)) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
@@ -46,13 +58,26 @@ int cmd_extras() {
|
|||||||
res_APDU[res_APDU_size++] = dt.hour;
|
res_APDU[res_APDU_size++] = dt.hour;
|
||||||
res_APDU[res_APDU_size++] = dt.min;
|
res_APDU[res_APDU_size++] = dt.min;
|
||||||
res_APDU[res_APDU_size++] = dt.sec;
|
res_APDU[res_APDU_size++] = dt.sec;
|
||||||
|
#else
|
||||||
|
struct timeval tv;
|
||||||
|
struct tm *tm;
|
||||||
|
gettimeofday(&tv, NULL);
|
||||||
|
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[res_APDU_size++] = tm->tm_mon;
|
||||||
|
res_APDU[res_APDU_size++] = tm->tm_mday;
|
||||||
|
res_APDU[res_APDU_size++] = tm->tm_wday;
|
||||||
|
res_APDU[res_APDU_size++] = tm->tm_hour;
|
||||||
|
res_APDU[res_APDU_size++] = tm->tm_min;
|
||||||
|
res_APDU[res_APDU_size++] = tm->tm_sec;
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
if (apdu.nc != 8) {
|
if (apdu.nc != 8) {
|
||||||
return SW_WRONG_LENGTH();
|
return SW_WRONG_LENGTH();
|
||||||
}
|
}
|
||||||
#ifndef ENABLE_EMULATION
|
#if !defined(ENABLE_EMULATION) && !defined(ESP_PLATFORM)
|
||||||
datetime_t dt;
|
datetime_t dt;
|
||||||
dt.year = (apdu.data[0] << 8) | (apdu.data[1]);
|
dt.year = (apdu.data[0] << 8) | (apdu.data[1]);
|
||||||
dt.month = apdu.data[2];
|
dt.month = apdu.data[2];
|
||||||
@@ -64,6 +89,18 @@ int cmd_extras() {
|
|||||||
if (!rtc_set_datetime(&dt)) {
|
if (!rtc_set_datetime(&dt)) {
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
}
|
}
|
||||||
|
#else
|
||||||
|
struct tm tm;
|
||||||
|
struct timeval tv;
|
||||||
|
tm.tm_year = ((apdu.data[0] << 8) | (apdu.data[1])) - 1900;
|
||||||
|
tm.tm_mon = apdu.data[2];
|
||||||
|
tm.tm_mday = apdu.data[3];
|
||||||
|
tm.tm_wday = apdu.data[4];
|
||||||
|
tm.tm_hour = apdu.data[5];
|
||||||
|
tm.tm_min = apdu.data[6];
|
||||||
|
tm.tm_sec = apdu.data[7];
|
||||||
|
tv.tv_sec = mktime(&tm);
|
||||||
|
settimeofday(&tv, NULL);
|
||||||
#endif
|
#endif
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -81,8 +118,8 @@ int cmd_extras() {
|
|||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
uint8_t newopts[] = { apdu.data[0], (opts & 0xff) };
|
uint8_t newopts[] = { apdu.data[0], (opts & 0xff) };
|
||||||
file_t *tf = search_by_fid(EF_DEVOPS, NULL, SPECIFY_EF);
|
file_t *tf = search_file(EF_DEVOPS);
|
||||||
flash_write_data_to_file(tf, newopts, sizeof(newopts));
|
file_put_data(tf, newopts, sizeof(newopts));
|
||||||
low_flash_available();
|
low_flash_available();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -149,7 +186,7 @@ int cmd_extras() {
|
|||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
mse.init = true;
|
mse.init = true;
|
||||||
res_APDU_size = olen;
|
res_APDU_size = (uint16_t)olen;
|
||||||
}
|
}
|
||||||
else if (P2(apdu) == 0x02 || P2(apdu) == 0x03 || P2(apdu) == 0x04) {
|
else if (P2(apdu) == 0x02 || P2(apdu) == 0x03 || P2(apdu) == 0x04) {
|
||||||
if (mse.init == false) {
|
if (mse.init == false) {
|
||||||
@@ -167,14 +204,14 @@ int cmd_extras() {
|
|||||||
(P2(apdu) == 0x04 && (opts & HSM_OPT_SECURE_LOCK))) {
|
(P2(apdu) == 0x04 && (opts & HSM_OPT_SECURE_LOCK))) {
|
||||||
uint16_t tfids[] = { EF_MKEK, EF_MKEK_SO };
|
uint16_t tfids[] = { EF_MKEK, EF_MKEK_SO };
|
||||||
for (int t = 0; t < sizeof(tfids) / sizeof(uint16_t); t++) {
|
for (int t = 0; t < sizeof(tfids) / sizeof(uint16_t); t++) {
|
||||||
file_t *tf = search_by_fid(tfids[t], NULL, SPECIFY_EF);
|
file_t *tf = search_file(tfids[t]);
|
||||||
if (tf) {
|
if (tf) {
|
||||||
uint8_t *tmp = (uint8_t *) calloc(1, file_get_size(tf));
|
uint8_t *tmp = (uint8_t *) calloc(1, file_get_size(tf));
|
||||||
memcpy(tmp, file_get_data(tf), file_get_size(tf));
|
memcpy(tmp, file_get_data(tf), file_get_size(tf));
|
||||||
for (int i = 0; i < MKEK_KEY_SIZE; i++) {
|
for (int i = 0; i < MKEK_KEY_SIZE; i++) {
|
||||||
MKEK_KEY(tmp)[i] ^= apdu.data[i];
|
MKEK_KEY(tmp)[i] ^= apdu.data[i];
|
||||||
}
|
}
|
||||||
flash_write_data_to_file(tf, tmp, file_get_size(tf));
|
file_put_data(tf, tmp, file_get_size(tf));
|
||||||
free(tmp);
|
free(tmp);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -185,8 +222,8 @@ int cmd_extras() {
|
|||||||
else if (P2(apdu) == 0x04) {
|
else if (P2(apdu) == 0x04) {
|
||||||
newopts[0] &= ~HSM_OPT_SECURE_LOCK >> 8;
|
newopts[0] &= ~HSM_OPT_SECURE_LOCK >> 8;
|
||||||
}
|
}
|
||||||
file_t *tf = search_by_fid(EF_DEVOPS, NULL, SPECIFY_EF);
|
file_t *tf = search_file(EF_DEVOPS);
|
||||||
flash_write_data_to_file(tf, newopts, sizeof(newopts));
|
file_put_data(tf, newopts, sizeof(newopts));
|
||||||
low_flash_available();
|
low_flash_available();
|
||||||
}
|
}
|
||||||
else if (P2(apdu) == 0x03) {
|
else if (P2(apdu) == 0x03) {
|
||||||
@@ -195,6 +232,60 @@ int cmd_extras() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#ifndef ENABLE_EMULATION
|
||||||
|
else if (P1(apdu) == 0x1B) { // Set PHY
|
||||||
|
if (apdu.nc == 0) {
|
||||||
|
if (file_has_data(ef_phy)) {
|
||||||
|
res_APDU_size = file_get_size(ef_phy);
|
||||||
|
memcpy(res_APDU, file_get_data(ef_phy), res_APDU_size);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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 (apdu.nc != 4) {
|
||||||
|
return SW_WRONG_LENGTH();
|
||||||
|
}
|
||||||
|
memcpy(tmp + PHY_VID, apdu.data, 4);
|
||||||
|
opts |= PHY_OPT_VPID;
|
||||||
|
}
|
||||||
|
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_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);
|
||||||
|
}
|
||||||
|
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();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
#endif
|
||||||
else {
|
else {
|
||||||
return SW_INCORRECT_P1P2();
|
return SW_INCORRECT_P1P2();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,10 +15,9 @@
|
|||||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include "common.h"
|
#include "sc_hsm.h"
|
||||||
#include "mbedtls/ecdh.h"
|
#include "mbedtls/ecdh.h"
|
||||||
#include "asn1.h"
|
#include "asn1.h"
|
||||||
#include "sc_hsm.h"
|
|
||||||
#include "random.h"
|
#include "random.h"
|
||||||
#include "oid.h"
|
#include "oid.h"
|
||||||
#include "eac.h"
|
#include "eac.h"
|
||||||
@@ -28,26 +27,28 @@ int cmd_general_authenticate() {
|
|||||||
if (P1(apdu) == 0x0 && P2(apdu) == 0x0) {
|
if (P1(apdu) == 0x0 && P2(apdu) == 0x0) {
|
||||||
if (apdu.data[0] == 0x7C) {
|
if (apdu.data[0] == 0x7C) {
|
||||||
int r = 0;
|
int r = 0;
|
||||||
size_t pubkey_len = 0;
|
uint16_t pubkey_len = 0;
|
||||||
const uint8_t *pubkey = NULL;
|
const uint8_t *pubkey = NULL;
|
||||||
uint16_t tag = 0x0;
|
uint16_t tag = 0x0;
|
||||||
uint8_t *tag_data = NULL, *p = NULL;
|
uint8_t *tag_data = NULL, *p = NULL;
|
||||||
size_t tag_len = 0;
|
uint16_t tag_len = 0;
|
||||||
while (walk_tlv(apdu.data + 2, apdu.nc - 2, &p, &tag, &tag_len, &tag_data)) {
|
asn1_ctx_t ctxi;
|
||||||
|
asn1_ctx_init(apdu.data + 2, (uint16_t)(apdu.nc - 2), &ctxi);
|
||||||
|
while (walk_tlv(&ctxi, &p, &tag, &tag_len, &tag_data)) {
|
||||||
if (tag == 0x80) {
|
if (tag == 0x80) {
|
||||||
pubkey = tag_data - 1; //mbedtls ecdh starts reading one pos before
|
pubkey = tag_data - 1; //mbedtls ecdh starts reading one pos before
|
||||||
pubkey_len = tag_len + 1;
|
pubkey_len = tag_len + 1;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
file_t *fkey = search_by_fid(EF_KEY_DEV, NULL, SPECIFY_EF);
|
file_t *fkey = search_file(EF_KEY_DEV);
|
||||||
if (!fkey) {
|
if (!fkey) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
mbedtls_ecdsa_context ectx;
|
mbedtls_ecp_keypair ectx;
|
||||||
mbedtls_ecdsa_init(&ectx);
|
mbedtls_ecp_keypair_init(&ectx);
|
||||||
r = load_private_key_ecdsa(&ectx, fkey);
|
r = load_private_key_ecdh(&ectx, fkey);
|
||||||
if (r != CCID_OK) {
|
if (r != CCID_OK) {
|
||||||
mbedtls_ecdsa_free(&ectx);
|
mbedtls_ecp_keypair_free(&ectx);
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
mbedtls_ecdh_context ctx;
|
mbedtls_ecdh_context ctx;
|
||||||
@@ -55,12 +56,12 @@ int cmd_general_authenticate() {
|
|||||||
mbedtls_ecp_group_id gid = MBEDTLS_ECP_DP_SECP256R1;
|
mbedtls_ecp_group_id gid = MBEDTLS_ECP_DP_SECP256R1;
|
||||||
r = mbedtls_ecdh_setup(&ctx, gid);
|
r = mbedtls_ecdh_setup(&ctx, gid);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
mbedtls_ecdsa_free(&ectx);
|
mbedtls_ecp_keypair_free(&ectx);
|
||||||
mbedtls_ecdh_free(&ctx);
|
mbedtls_ecdh_free(&ctx);
|
||||||
return SW_DATA_INVALID();
|
return SW_DATA_INVALID();
|
||||||
}
|
}
|
||||||
r = mbedtls_mpi_copy(&ctx.ctx.mbed_ecdh.d, &ectx.d);
|
r = mbedtls_mpi_copy(&ctx.ctx.mbed_ecdh.d, &ectx.d);
|
||||||
mbedtls_ecdsa_free(&ectx);
|
mbedtls_ecp_keypair_free(&ectx);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
mbedtls_ecdh_free(&ctx);
|
mbedtls_ecdh_free(&ctx);
|
||||||
return SW_DATA_INVALID();
|
return SW_DATA_INVALID();
|
||||||
|
|||||||
@@ -28,7 +28,7 @@ extern void scan_all();
|
|||||||
|
|
||||||
extern char __StackLimit;
|
extern char __StackLimit;
|
||||||
int heapLeft() {
|
int heapLeft() {
|
||||||
#ifndef ENABLE_EMULATION
|
#if !defined(ENABLE_EMULATION) && !defined(ESP_PLATFORM)
|
||||||
char *p = malloc(256); // try to avoid undue fragmentation
|
char *p = malloc(256); // try to avoid undue fragmentation
|
||||||
int left = &__StackLimit - p;
|
int left = &__StackLimit - p;
|
||||||
free(p);
|
free(p);
|
||||||
@@ -38,6 +38,7 @@ int heapLeft() {
|
|||||||
return left;
|
return left;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
extern void reset_puk_store();
|
||||||
int cmd_initialize() {
|
int cmd_initialize() {
|
||||||
if (apdu.nc > 0) {
|
if (apdu.nc > 0) {
|
||||||
uint8_t mkek[MKEK_SIZE];
|
uint8_t mkek[MKEK_SIZE];
|
||||||
@@ -47,18 +48,20 @@ int cmd_initialize() {
|
|||||||
has_session_pin = has_session_sopin = false;
|
has_session_pin = has_session_sopin = false;
|
||||||
uint16_t tag = 0x0;
|
uint16_t tag = 0x0;
|
||||||
uint8_t *tag_data = NULL, *p = NULL, *kds = NULL, *dkeks = NULL;
|
uint8_t *tag_data = NULL, *p = NULL, *kds = NULL, *dkeks = NULL;
|
||||||
size_t tag_len = 0;
|
uint16_t tag_len = 0;
|
||||||
while (walk_tlv(apdu.data, apdu.nc, &p, &tag, &tag_len, &tag_data)) {
|
asn1_ctx_t ctxi;
|
||||||
|
asn1_ctx_init(apdu.data, (uint16_t)apdu.nc, &ctxi);
|
||||||
|
while (walk_tlv(&ctxi, &p, &tag, &tag_len, &tag_data)) {
|
||||||
if (tag == 0x80) { //options
|
if (tag == 0x80) { //options
|
||||||
file_t *tf = search_by_fid(EF_DEVOPS, NULL, SPECIFY_EF);
|
file_t *tf = search_file(EF_DEVOPS);
|
||||||
flash_write_data_to_file(tf, tag_data, tag_len);
|
file_put_data(tf, tag_data, tag_len);
|
||||||
}
|
}
|
||||||
else if (tag == 0x81) { //user pin
|
else if (tag == 0x81) { //user pin
|
||||||
if (file_pin1 && file_pin1->data) {
|
if (file_pin1 && file_pin1->data) {
|
||||||
uint8_t dhash[33];
|
uint8_t dhash[33];
|
||||||
dhash[0] = tag_len;
|
dhash[0] = (uint8_t)tag_len;
|
||||||
double_hash_pin(tag_data, tag_len, dhash + 1);
|
double_hash_pin(tag_data, tag_len, dhash + 1);
|
||||||
flash_write_data_to_file(file_pin1, dhash, sizeof(dhash));
|
file_put_data(file_pin1, dhash, sizeof(dhash));
|
||||||
hash_multi(tag_data, tag_len, session_pin);
|
hash_multi(tag_data, tag_len, session_pin);
|
||||||
has_session_pin = true;
|
has_session_pin = true;
|
||||||
}
|
}
|
||||||
@@ -66,20 +69,20 @@ int cmd_initialize() {
|
|||||||
else if (tag == 0x82) { //sopin pin
|
else if (tag == 0x82) { //sopin pin
|
||||||
if (file_sopin && file_sopin->data) {
|
if (file_sopin && file_sopin->data) {
|
||||||
uint8_t dhash[33];
|
uint8_t dhash[33];
|
||||||
dhash[0] = tag_len;
|
dhash[0] = (uint8_t)tag_len;
|
||||||
double_hash_pin(tag_data, tag_len, dhash + 1);
|
double_hash_pin(tag_data, tag_len, dhash + 1);
|
||||||
flash_write_data_to_file(file_sopin, dhash, sizeof(dhash));
|
file_put_data(file_sopin, dhash, sizeof(dhash));
|
||||||
hash_multi(tag_data, tag_len, session_sopin);
|
hash_multi(tag_data, tag_len, session_sopin);
|
||||||
has_session_sopin = true;
|
has_session_sopin = true;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (tag == 0x91) { //retries user pin
|
else if (tag == 0x91) { //retries user pin
|
||||||
file_t *tf = search_by_fid(0x1082, NULL, SPECIFY_EF);
|
file_t *tf = search_file(EF_PIN1_MAX_RETRIES);
|
||||||
if (tf && tf->data) {
|
if (tf && tf->data) {
|
||||||
flash_write_data_to_file(tf, tag_data, tag_len);
|
file_put_data(tf, tag_data, tag_len);
|
||||||
}
|
}
|
||||||
if (file_retries_pin1 && file_retries_pin1->data) {
|
if (file_retries_pin1 && file_retries_pin1->data) {
|
||||||
flash_write_data_to_file(file_retries_pin1, tag_data, tag_len);
|
file_put_data(file_retries_pin1, tag_data, tag_len);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (tag == 0x92) {
|
else if (tag == 0x92) {
|
||||||
@@ -89,10 +92,10 @@ int cmd_initialize() {
|
|||||||
release_mkek(mkek);
|
release_mkek(mkek);
|
||||||
return SW_MEMORY_FAILURE();
|
return SW_MEMORY_FAILURE();
|
||||||
}
|
}
|
||||||
flash_write_data_to_file(tf, NULL, 0);
|
file_put_data(tf, NULL, 0);
|
||||||
}
|
}
|
||||||
else if (tag == 0x93) {
|
else if (tag == 0x93) {
|
||||||
file_t *ef_puk = search_by_fid(EF_PUKAUT, NULL, SPECIFY_EF);
|
file_t *ef_puk = search_file(EF_PUKAUT);
|
||||||
if (!ef_puk) {
|
if (!ef_puk) {
|
||||||
release_mkek(mkek);
|
release_mkek(mkek);
|
||||||
return SW_MEMORY_FAILURE();
|
return SW_MEMORY_FAILURE();
|
||||||
@@ -102,14 +105,14 @@ int cmd_initialize() {
|
|||||||
pk_status[0] = puks;
|
pk_status[0] = puks;
|
||||||
pk_status[1] = puks;
|
pk_status[1] = puks;
|
||||||
pk_status[2] = tag_data[1];
|
pk_status[2] = tag_data[1];
|
||||||
flash_write_data_to_file(ef_puk, pk_status, sizeof(pk_status));
|
file_put_data(ef_puk, pk_status, sizeof(pk_status));
|
||||||
for (int i = 0; i < puks; i++) {
|
for (uint8_t i = 0; i < puks; i++) {
|
||||||
file_t *tf = file_new(EF_PUK + i);
|
file_t *tf = file_new(EF_PUK + i);
|
||||||
if (!tf) {
|
if (!tf) {
|
||||||
release_mkek(mkek);
|
release_mkek(mkek);
|
||||||
return SW_MEMORY_FAILURE();
|
return SW_MEMORY_FAILURE();
|
||||||
}
|
}
|
||||||
flash_write_data_to_file(tf, NULL, 0);
|
file_put_data(tf, NULL, 0);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (tag == 0x97) {
|
else if (tag == 0x97) {
|
||||||
@@ -119,12 +122,12 @@ int cmd_initialize() {
|
|||||||
file_t *tf = file_new(EF_DKEK+i);
|
file_t *tf = file_new(EF_DKEK+i);
|
||||||
if (!tf)
|
if (!tf)
|
||||||
return SW_MEMORY_FAILURE();
|
return SW_MEMORY_FAILURE();
|
||||||
flash_write_data_to_file(tf, NULL, 0);
|
file_put_data(tf, NULL, 0);
|
||||||
}
|
}
|
||||||
*/
|
*/
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
file_t *tf_kd = search_by_fid(EF_KEY_DOMAIN, NULL, SPECIFY_EF);
|
file_t *tf_kd = search_file(EF_KEY_DOMAIN);
|
||||||
if (!tf_kd) {
|
if (!tf_kd) {
|
||||||
release_mkek(mkek);
|
release_mkek(mkek);
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
@@ -140,7 +143,7 @@ int cmd_initialize() {
|
|||||||
if (dkeks) {
|
if (dkeks) {
|
||||||
if (*dkeks > 0) {
|
if (*dkeks > 0) {
|
||||||
uint16_t d = *dkeks;
|
uint16_t d = *dkeks;
|
||||||
if (flash_write_data_to_file(tf_kd, (const uint8_t *) &d, sizeof(d)) != CCID_OK) {
|
if (file_put_data(tf_kd, (const uint8_t *) &d, sizeof(d)) != CCID_OK) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -150,28 +153,28 @@ int cmd_initialize() {
|
|||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
uint16_t d = 0x0101;
|
uint16_t d = 0x0101;
|
||||||
if (flash_write_data_to_file(tf_kd, (const uint8_t *) &d, sizeof(d)) != CCID_OK) {
|
if (file_put_data(tf_kd, (const uint8_t *) &d, sizeof(d)) != CCID_OK) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
uint16_t d = 0x0000;
|
uint16_t d = 0x0000;
|
||||||
if (flash_write_data_to_file(tf_kd, (const uint8_t *) &d, sizeof(d)) != CCID_OK) {
|
if (file_put_data(tf_kd, (const uint8_t *) &d, sizeof(d)) != CCID_OK) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (kds) {
|
if (kds) {
|
||||||
uint8_t t[MAX_KEY_DOMAINS * 2], k = MIN(*kds, MAX_KEY_DOMAINS);
|
uint8_t t[MAX_KEY_DOMAINS * 2], k = MIN(*kds, MAX_KEY_DOMAINS);
|
||||||
memset(t, 0xff, 2 * k);
|
memset(t, 0xff, 2 * k);
|
||||||
if (flash_write_data_to_file(tf_kd, t, 2 * k) != CCID_OK) {
|
if (file_put_data(tf_kd, t, 2 * k) != CCID_OK) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
/* When initialized, it has all credentials */
|
/* When initialized, it has all credentials */
|
||||||
isUserAuthenticated = true;
|
isUserAuthenticated = true;
|
||||||
/* Create terminal private key */
|
/* Create terminal private key */
|
||||||
file_t *fdkey = search_by_fid(EF_KEY_DEV, NULL, SPECIFY_EF);
|
file_t *fdkey = search_file(EF_KEY_DEV);
|
||||||
if (!fdkey) {
|
if (!fdkey) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
@@ -186,41 +189,55 @@ int cmd_initialize() {
|
|||||||
mbedtls_ecdsa_free(&ecdsa);
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
ret = store_keys(&ecdsa, HSM_KEY_EC, key_id);
|
ret = store_keys(&ecdsa, PICO_KEYS_KEY_EC, key_id);
|
||||||
if (ret != CCID_OK) {
|
if (ret != CCID_OK) {
|
||||||
mbedtls_ecdsa_free(&ecdsa);
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
size_t cvc_len = 0;
|
size_t cvc_len = 0;
|
||||||
if ((cvc_len = asn1_cvc_aut(&ecdsa, HSM_KEY_EC, res_APDU, 4096, NULL, 0)) == 0) {
|
if ((cvc_len = asn1_cvc_aut(&ecdsa, PICO_KEYS_KEY_EC, res_APDU, 4096, NULL, 0)) == 0) {
|
||||||
mbedtls_ecdsa_free(&ecdsa);
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
mbedtls_ecdsa_free(&ecdsa);
|
|
||||||
|
|
||||||
file_t *fpk = search_by_fid(EF_EE_DEV, NULL, SPECIFY_EF);
|
file_t *fpk = search_file(EF_EE_DEV);
|
||||||
ret = flash_write_data_to_file(fpk, res_APDU, cvc_len);
|
ret = file_put_data(fpk, res_APDU, (uint16_t)cvc_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) {
|
||||||
|
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));
|
||||||
if (ret != 0) {
|
if (ret != 0) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
|
|
||||||
const uint8_t *keyid =
|
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 *) "\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0",
|
||||||
*label = (const uint8_t *) "ESTERMHSM";
|
*label = (const uint8_t *) "ESPICOHSMTR";
|
||||||
size_t prkd_len = asn1_build_prkd_ecc(label,
|
uint16_t prkd_len = asn1_build_prkd_ecc(label,
|
||||||
strlen((const char *) label),
|
(uint16_t)strlen((const char *) label),
|
||||||
keyid,
|
keyid,
|
||||||
20,
|
20,
|
||||||
192,
|
256,
|
||||||
res_APDU,
|
res_APDU,
|
||||||
4096);
|
4096);
|
||||||
fpk = search_by_fid(EF_PRKD_DEV, NULL, SPECIFY_EF);
|
fpk = search_file(EF_PRKD_DEV);
|
||||||
ret = flash_write_data_to_file(fpk, res_APDU, prkd_len);
|
ret = file_put_data(fpk, res_APDU, prkd_len);
|
||||||
|
|
||||||
}
|
}
|
||||||
if (ret != 0) {
|
if (ret != 0) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
low_flash_available();
|
low_flash_available();
|
||||||
|
reset_puk_store();
|
||||||
}
|
}
|
||||||
else { //free memory bytes request
|
else { //free memory bytes request
|
||||||
int heap_left = heapLeft();
|
int heap_left = heapLeft();
|
||||||
|
|||||||
@@ -22,12 +22,15 @@
|
|||||||
#include "files.h"
|
#include "files.h"
|
||||||
|
|
||||||
uint8_t get_key_domain(file_t *fkey) {
|
uint8_t get_key_domain(file_t *fkey) {
|
||||||
size_t tag_len = 0;
|
uint16_t tag_len = 0;
|
||||||
|
if (!file_has_data(fkey)) {
|
||||||
|
return 0xff;
|
||||||
|
}
|
||||||
const uint8_t *meta_tag = get_meta_tag(fkey, 0x92, &tag_len);
|
const uint8_t *meta_tag = get_meta_tag(fkey, 0x92, &tag_len);
|
||||||
if (meta_tag) {
|
if (meta_tag) {
|
||||||
return *meta_tag;
|
return *meta_tag;
|
||||||
}
|
}
|
||||||
return 0xff;
|
return 0x0;
|
||||||
}
|
}
|
||||||
|
|
||||||
int cmd_key_domain() {
|
int cmd_key_domain() {
|
||||||
@@ -41,7 +44,7 @@ int cmd_key_domain() {
|
|||||||
if (p2 >= MAX_KEY_DOMAINS) {
|
if (p2 >= MAX_KEY_DOMAINS) {
|
||||||
return SW_WRONG_P1P2();
|
return SW_WRONG_P1P2();
|
||||||
}
|
}
|
||||||
file_t *tf_kd = search_by_fid(EF_KEY_DOMAIN, NULL, SPECIFY_EF);
|
file_t *tf_kd = search_file(EF_KEY_DOMAIN);
|
||||||
if (!tf_kd) {
|
if (!tf_kd) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
@@ -65,26 +68,32 @@ int cmd_key_domain() {
|
|||||||
}
|
}
|
||||||
import_dkek_share(p2, apdu.data);
|
import_dkek_share(p2, apdu.data);
|
||||||
if (++current_dkeks >= dkeks) {
|
if (++current_dkeks >= dkeks) {
|
||||||
if (save_dkek_key(p2, NULL) != CCID_OK) {
|
int r = save_dkek_key(p2, NULL);
|
||||||
/* On fail, it will return to previous dkek state. */
|
if (r != CCID_OK) {
|
||||||
import_dkek_share(p2, apdu.data);
|
if (r == CCID_NO_LOGIN) {
|
||||||
return SW_FILE_NOT_FOUND();
|
pending_save_dkek = p2;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
/* On fail, it will return to previous dkek state. */
|
||||||
|
import_dkek_share(p2, apdu.data);
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
uint8_t t[MAX_KEY_DOMAINS * 2];
|
uint8_t t[MAX_KEY_DOMAINS * 2];
|
||||||
memcpy(t, kdata, tf_kd_size);
|
memcpy(t, kdata, tf_kd_size);
|
||||||
t[2 * p2 + 1] = current_dkeks;
|
t[2 * p2 + 1] = current_dkeks;
|
||||||
if (flash_write_data_to_file(tf_kd, t, tf_kd_size) != CCID_OK) {
|
if (file_put_data(tf_kd, t, tf_kd_size) != CCID_OK) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
low_flash_available();
|
low_flash_available();
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
file_t *tf = search_dynamic_file(EF_XKEK + p2);
|
file_t *tf = search_file(EF_XKEK + p2);
|
||||||
if (2 * p2 >= tf_kd_size) {
|
if (2 * p2 >= tf_kd_size) {
|
||||||
return SW_INCORRECT_P1P2();
|
return SW_INCORRECT_P1P2();
|
||||||
}
|
}
|
||||||
if (current_dkeks == 0xff && !tf) { //XKEK have always 0xff
|
if (current_dkeks == 0xff && !file_has_data(tf)) { //XKEK have always 0xff
|
||||||
return SW_REFERENCE_NOT_FOUND();
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -94,8 +103,9 @@ int cmd_key_domain() {
|
|||||||
return SW_WRONG_LENGTH();
|
return SW_WRONG_LENGTH();
|
||||||
}
|
}
|
||||||
if (p1 == 0x3) { //if key domain is not empty, command is denied
|
if (p1 == 0x3) { //if key domain is not empty, command is denied
|
||||||
for (int i = 0; i < dynamic_files; i++) {
|
for (uint16_t i = 1; i < 256; i++) {
|
||||||
if (get_key_domain(&dynamic_file[i]) == p2) {
|
file_t *fkey = search_file(KEY_PREFIX << 8 | (uint8_t)i);
|
||||||
|
if (get_key_domain(fkey) == p2) {
|
||||||
return SW_FILE_EXISTS();
|
return SW_FILE_EXISTS();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -103,26 +113,32 @@ int cmd_key_domain() {
|
|||||||
uint8_t t[MAX_KEY_DOMAINS * 2];
|
uint8_t t[MAX_KEY_DOMAINS * 2];
|
||||||
memcpy(t, kdata, tf_kd_size);
|
memcpy(t, kdata, tf_kd_size);
|
||||||
if (p1 == 0x1) {
|
if (p1 == 0x1) {
|
||||||
|
if (t[2 * p2] != 0xff || t[2 * p2 + 1] != 0xff) {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
t[2 * p2] = dkeks = apdu.data[0];
|
t[2 * p2] = dkeks = apdu.data[0];
|
||||||
t[2 * p2 + 1] = current_dkeks = 0;
|
t[2 * p2 + 1] = current_dkeks = 0;
|
||||||
}
|
}
|
||||||
else if (p1 == 0x3) {
|
else if (p1 == 0x3) {
|
||||||
|
if (t[2 * p2] == 0xff && t[2 * p2 + 1] == 0xff) {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
t[2 * p2] = dkeks = 0xff;
|
t[2 * p2] = dkeks = 0xff;
|
||||||
t[2 * p2 + 1] = 0xff;
|
t[2 * p2 + 1] = 0xff;
|
||||||
}
|
}
|
||||||
else if (p1 == 0x4) {
|
else if (p1 == 0x4) {
|
||||||
t[2 * p2 + 1] = current_dkeks = 0;
|
t[2 * p2 + 1] = current_dkeks = 0;
|
||||||
}
|
}
|
||||||
if (flash_write_data_to_file(tf_kd, t, tf_kd_size) != CCID_OK) {
|
if (file_put_data(tf_kd, t, tf_kd_size) != CCID_OK) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
file_t *tf = NULL;
|
file_t *tf = NULL;
|
||||||
if ((tf = search_dynamic_file(EF_DKEK + p2))) {
|
if ((tf = search_file(EF_DKEK + p2))) {
|
||||||
if (delete_file(tf) != CCID_OK) {
|
if (delete_file(tf) != CCID_OK) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (p1 == 0x3 && (tf = search_dynamic_file(EF_XKEK + p2))) {
|
if (p1 == 0x3 && (tf = search_file(EF_XKEK + p2))) {
|
||||||
if (delete_file(tf) != CCID_OK) {
|
if (delete_file(tf) != CCID_OK) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
@@ -134,8 +150,8 @@ int cmd_key_domain() {
|
|||||||
}
|
}
|
||||||
else if (p1 == 0x2) { //XKEK Key Domain creation
|
else if (p1 == 0x2) { //XKEK Key Domain creation
|
||||||
if (apdu.nc > 0) {
|
if (apdu.nc > 0) {
|
||||||
size_t pub_len = 0;
|
uint16_t pub_len = 0;
|
||||||
file_t *fterm = search_by_fid(EF_TERMCA, NULL, SPECIFY_EF);
|
file_t *fterm = search_file(EF_TERMCA);
|
||||||
if (!fterm) {
|
if (!fterm) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
@@ -143,13 +159,13 @@ int cmd_key_domain() {
|
|||||||
if (!pub) {
|
if (!pub) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
size_t t86_len = 0;
|
uint16_t t86_len = 0;
|
||||||
const uint8_t *t86 = cvc_get_field(pub, pub_len, &t86_len, 0x86);
|
const uint8_t *t86 = cvc_get_field(pub, pub_len, &t86_len, 0x86);
|
||||||
if (!t86 || t86[0] != 0x4) {
|
if (!t86 || t86[0] != 0x4) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
size_t t54_len = 0;
|
uint16_t t54_len = 0;
|
||||||
const uint8_t *t54 = cvc_get_field(apdu.data, apdu.nc, &t54_len, 0x54);
|
const uint8_t *t54 = cvc_get_field(apdu.data, (uint16_t)apdu.nc, &t54_len, 0x54);
|
||||||
if (!t54) {
|
if (!t54) {
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
}
|
}
|
||||||
@@ -158,7 +174,7 @@ int cmd_key_domain() {
|
|||||||
memcpy(input + 1, t86 + 1, (t86_len - 1) / 2);
|
memcpy(input + 1, t86 + 1, (t86_len - 1) / 2);
|
||||||
hash256(input, (t86_len - 1) / 2 + 1, hash);
|
hash256(input, (t86_len - 1) / 2 + 1, hash);
|
||||||
free(input);
|
free(input);
|
||||||
int r = puk_verify(t54, t54_len, hash, 32, apdu.data, apdu.nc);
|
int r = puk_verify(t54, t54_len, hash, 32, apdu.data, (uint16_t)apdu.nc);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
return SW_CONDITIONS_NOT_SATISFIED();
|
return SW_CONDITIONS_NOT_SATISFIED();
|
||||||
}
|
}
|
||||||
@@ -168,12 +184,12 @@ int cmd_key_domain() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
//All checks done. Get Key Domain UID
|
//All checks done. Get Key Domain UID
|
||||||
pub = cvc_get_pub(apdu.data, apdu.nc, &pub_len);
|
pub = cvc_get_pub(apdu.data, (uint16_t)apdu.nc, &pub_len);
|
||||||
if (pub) {
|
if (pub) {
|
||||||
size_t t86_len = 0;
|
t86_len = 0;
|
||||||
const uint8_t *t86 = cvc_get_field(pub, pub_len, &t86_len, 0x86);
|
t86 = cvc_get_field(pub, pub_len, &t86_len, 0x86);
|
||||||
if (t86) {
|
if (t86) {
|
||||||
flash_write_data_to_file(tf, t86 + 1, t86_len - 1);
|
file_put_data(tf, t86 + 1, (uint16_t)t86_len - 1);
|
||||||
low_flash_available();
|
low_flash_available();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -187,8 +203,8 @@ int cmd_key_domain() {
|
|||||||
res_APDU[1] = dkeks > current_dkeks ? dkeks - current_dkeks : 0;
|
res_APDU[1] = dkeks > current_dkeks ? dkeks - current_dkeks : 0;
|
||||||
dkek_kcv(p2, res_APDU + 2);
|
dkek_kcv(p2, res_APDU + 2);
|
||||||
res_APDU_size = 2 + 8;
|
res_APDU_size = 2 + 8;
|
||||||
file_t *tf = search_dynamic_file(EF_XKEK + p2);
|
file_t *tf = search_file(EF_XKEK + p2);
|
||||||
if (tf) {
|
if (file_has_data(tf)) {
|
||||||
memcpy(res_APDU + 10, file_get_data(tf), file_get_size(tf));
|
memcpy(res_APDU + 10, file_get_data(tf), file_get_size(tf));
|
||||||
res_APDU_size += file_get_size(tf);
|
res_APDU_size += file_get_size(tf);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -27,7 +27,10 @@ int cmd_key_gen() {
|
|||||||
if (!isUserAuthenticated) {
|
if (!isUserAuthenticated) {
|
||||||
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
}
|
}
|
||||||
if (p2 == 0xB2) {
|
if (p2 == 0xB3) {
|
||||||
|
key_size = 64;
|
||||||
|
}
|
||||||
|
else if (p2 == 0xB2) {
|
||||||
key_size = 32;
|
key_size = 32;
|
||||||
}
|
}
|
||||||
else if (p2 == 0xB1) {
|
else if (p2 == 0xB1) {
|
||||||
@@ -37,17 +40,20 @@ int cmd_key_gen() {
|
|||||||
key_size = 16;
|
key_size = 16;
|
||||||
}
|
}
|
||||||
//at this moment, we do not use the template, as only CBC is supported by the driver (encrypt, decrypt and CMAC)
|
//at this moment, we do not use the template, as only CBC is supported by the driver (encrypt, decrypt and CMAC)
|
||||||
uint8_t aes_key[32]; //maximum AES key size
|
uint8_t aes_key[64]; //maximum AES key size
|
||||||
memcpy(aes_key, random_bytes_get(key_size), key_size);
|
memcpy(aes_key, random_bytes_get(key_size), key_size);
|
||||||
int aes_type = 0x0;
|
int aes_type = 0x0;
|
||||||
if (key_size == 16) {
|
if (key_size == 16) {
|
||||||
aes_type = HSM_KEY_AES_128;
|
aes_type = PICO_KEYS_KEY_AES_128;
|
||||||
}
|
}
|
||||||
else if (key_size == 24) {
|
else if (key_size == 24) {
|
||||||
aes_type = HSM_KEY_AES_192;
|
aes_type = PICO_KEYS_KEY_AES_192;
|
||||||
}
|
}
|
||||||
else if (key_size == 32) {
|
else if (key_size == 32) {
|
||||||
aes_type = HSM_KEY_AES_256;
|
aes_type = PICO_KEYS_KEY_AES_256;
|
||||||
|
}
|
||||||
|
else if (key_size == 64) {
|
||||||
|
aes_type = PICO_KEYS_KEY_AES_512;
|
||||||
}
|
}
|
||||||
r = store_keys(aes_key, aes_type, key_id);
|
r = store_keys(aes_key, aes_type, key_id);
|
||||||
if (r != CCID_OK) {
|
if (r != CCID_OK) {
|
||||||
|
|||||||
@@ -15,37 +15,49 @@
|
|||||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include "crypto_utils.h"
|
|
||||||
#include "sc_hsm.h"
|
#include "sc_hsm.h"
|
||||||
|
#include "crypto_utils.h"
|
||||||
#include "kek.h"
|
#include "kek.h"
|
||||||
#include "cvc.h"
|
#include "cvc.h"
|
||||||
|
|
||||||
int cmd_key_unwrap() {
|
int cmd_key_unwrap() {
|
||||||
int key_id = P1(apdu), r = 0;
|
uint8_t key_id = P1(apdu);
|
||||||
|
int r = 0;
|
||||||
if (P2(apdu) != 0x93) {
|
if (P2(apdu) != 0x93) {
|
||||||
return SW_WRONG_P1P2();
|
return SW_WRONG_P1P2();
|
||||||
}
|
}
|
||||||
if (!isUserAuthenticated) {
|
if (!isUserAuthenticated) {
|
||||||
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
}
|
}
|
||||||
int key_type = dkek_type_key(apdu.data);
|
uint8_t *data = apdu.data;
|
||||||
uint8_t kdom = -1, *allowed = NULL;
|
uint16_t data_len = apdu.nc;
|
||||||
size_t allowed_len = 0;
|
if (data_len == 0) { // New style
|
||||||
|
file_t *tef = search_file(0x2F10);
|
||||||
|
if (!file_has_data(tef)) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
data = file_get_data(tef);
|
||||||
|
data_len = file_get_size(tef);
|
||||||
|
}
|
||||||
|
int key_type = dkek_type_key(data);
|
||||||
|
uint8_t *allowed = NULL;
|
||||||
|
int16_t kdom = -1;
|
||||||
|
uint16_t allowed_len = 0;
|
||||||
if (key_type == 0x0) {
|
if (key_type == 0x0) {
|
||||||
return SW_DATA_INVALID();
|
return SW_DATA_INVALID();
|
||||||
}
|
}
|
||||||
if (key_type == HSM_KEY_RSA) {
|
if (key_type & PICO_KEYS_KEY_RSA) {
|
||||||
mbedtls_rsa_context ctx;
|
mbedtls_rsa_context ctx;
|
||||||
mbedtls_rsa_init(&ctx);
|
mbedtls_rsa_init(&ctx);
|
||||||
do {
|
do {
|
||||||
r = dkek_decode_key(++kdom, &ctx, apdu.data, apdu.nc, NULL, &allowed, &allowed_len);
|
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);
|
} while ((r == CCID_ERR_FILE_NOT_FOUND || r == CCID_WRONG_DKEK) && kdom < MAX_KEY_DOMAINS);
|
||||||
if (r != CCID_OK) {
|
if (r != CCID_OK) {
|
||||||
mbedtls_rsa_free(&ctx);
|
mbedtls_rsa_free(&ctx);
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
r = store_keys(&ctx, HSM_KEY_RSA, key_id);
|
r = store_keys(&ctx, PICO_KEYS_KEY_RSA, key_id);
|
||||||
if ((res_APDU_size = asn1_cvc_aut(&ctx, HSM_KEY_RSA, res_APDU, 4096, NULL, 0)) == 0) {
|
if ((res_APDU_size = (uint16_t)asn1_cvc_aut(&ctx, PICO_KEYS_KEY_RSA, res_APDU, 4096, NULL, 0)) == 0) {
|
||||||
mbedtls_rsa_free(&ctx);
|
mbedtls_rsa_free(&ctx);
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
@@ -54,34 +66,34 @@ int cmd_key_unwrap() {
|
|||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (key_type == HSM_KEY_EC) {
|
else if (key_type & PICO_KEYS_KEY_EC) {
|
||||||
mbedtls_ecdsa_context ctx;
|
mbedtls_ecp_keypair ctx;
|
||||||
mbedtls_ecdsa_init(&ctx);
|
mbedtls_ecp_keypair_init(&ctx);
|
||||||
do {
|
do {
|
||||||
r = dkek_decode_key(++kdom, &ctx, apdu.data, apdu.nc, NULL, &allowed, &allowed_len);
|
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);
|
} while ((r == CCID_ERR_FILE_NOT_FOUND || r == CCID_WRONG_DKEK) && kdom < MAX_KEY_DOMAINS);
|
||||||
if (r != CCID_OK) {
|
if (r != CCID_OK) {
|
||||||
mbedtls_ecdsa_free(&ctx);
|
mbedtls_ecp_keypair_free(&ctx);
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
r = store_keys(&ctx, HSM_KEY_EC, key_id);
|
r = store_keys(&ctx, PICO_KEYS_KEY_EC, key_id);
|
||||||
if ((res_APDU_size = asn1_cvc_aut(&ctx, HSM_KEY_EC, res_APDU, 4096, NULL, 0)) == 0) {
|
if ((res_APDU_size = (uint16_t)asn1_cvc_aut(&ctx, PICO_KEYS_KEY_EC, res_APDU, 4096, NULL, 0)) == 0) {
|
||||||
mbedtls_ecdsa_free(&ctx);
|
mbedtls_ecp_keypair_free(&ctx);
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
mbedtls_ecdsa_free(&ctx);
|
mbedtls_ecp_keypair_free(&ctx);
|
||||||
if (r != CCID_OK) {
|
if (r != CCID_OK) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (key_type == HSM_KEY_AES) {
|
else if (key_type & PICO_KEYS_KEY_AES) {
|
||||||
uint8_t aes_key[32];
|
uint8_t aes_key[64];
|
||||||
int key_size = 0, aes_type = 0;
|
int key_size = 0, aes_type = 0;
|
||||||
do {
|
do {
|
||||||
r = dkek_decode_key(++kdom,
|
r = dkek_decode_key((uint8_t)++kdom,
|
||||||
aes_key,
|
aes_key,
|
||||||
apdu.data,
|
data,
|
||||||
apdu.nc,
|
data_len,
|
||||||
&key_size,
|
&key_size,
|
||||||
&allowed,
|
&allowed,
|
||||||
&allowed_len);
|
&allowed_len);
|
||||||
@@ -89,14 +101,17 @@ int cmd_key_unwrap() {
|
|||||||
if (r != CCID_OK) {
|
if (r != CCID_OK) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
if (key_size == 32) {
|
if (key_size == 64) {
|
||||||
aes_type = HSM_KEY_AES_256;
|
aes_type = PICO_KEYS_KEY_AES_512;
|
||||||
|
}
|
||||||
|
else if (key_size == 32) {
|
||||||
|
aes_type = PICO_KEYS_KEY_AES_256;
|
||||||
}
|
}
|
||||||
else if (key_size == 24) {
|
else if (key_size == 24) {
|
||||||
aes_type = HSM_KEY_AES_192;
|
aes_type = PICO_KEYS_KEY_AES_192;
|
||||||
}
|
}
|
||||||
else if (key_size == 16) {
|
else if (key_size == 16) {
|
||||||
aes_type = HSM_KEY_AES_128;
|
aes_type = PICO_KEYS_KEY_AES_128;
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
@@ -107,17 +122,17 @@ int cmd_key_unwrap() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
if ((allowed != NULL && allowed_len > 0) || kdom >= 0) {
|
if ((allowed != NULL && allowed_len > 0) || kdom >= 0) {
|
||||||
size_t meta_len = (allowed_len > 0 ? 2 + allowed_len : 0) + (kdom >= 0 ? 3 : 0);
|
uint16_t meta_len = (allowed_len > 0 ? 2 + allowed_len : 0) + (kdom >= 0 ? 3 : 0);
|
||||||
uint8_t *meta = (uint8_t *) calloc(1, meta_len), *m = meta;
|
uint8_t *meta = (uint8_t *) calloc(1, meta_len), *m = meta;
|
||||||
if (allowed_len > 0) {
|
if (allowed_len > 0) {
|
||||||
*m++ = 0x91;
|
*m++ = 0x91;
|
||||||
*m++ = allowed_len;
|
*m++ = (uint8_t)allowed_len;
|
||||||
memcpy(m, allowed, allowed_len); m += allowed_len;
|
memcpy(m, allowed, allowed_len); m += allowed_len;
|
||||||
}
|
}
|
||||||
if (kdom >= 0) {
|
if (kdom >= 0) {
|
||||||
*m++ = 0x92;
|
*m++ = 0x92;
|
||||||
*m++ = 1;
|
*m++ = 1;
|
||||||
*m++ = kdom;
|
*m++ = (uint8_t)kdom;
|
||||||
}
|
}
|
||||||
r = meta_add((KEY_PREFIX << 8) | key_id, meta, meta_len);
|
r = meta_add((KEY_PREFIX << 8) | key_id, meta, meta_len);
|
||||||
free(meta);
|
free(meta);
|
||||||
@@ -127,12 +142,12 @@ int cmd_key_unwrap() {
|
|||||||
}
|
}
|
||||||
if (res_APDU_size > 0) {
|
if (res_APDU_size > 0) {
|
||||||
file_t *fpk = file_new((EE_CERTIFICATE_PREFIX << 8) | key_id);
|
file_t *fpk = file_new((EE_CERTIFICATE_PREFIX << 8) | key_id);
|
||||||
r = flash_write_data_to_file(fpk, res_APDU, res_APDU_size);
|
r = file_put_data(fpk, res_APDU, res_APDU_size);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
low_flash_available();
|
|
||||||
res_APDU_size = 0;
|
res_APDU_size = 0;
|
||||||
}
|
}
|
||||||
|
low_flash_available();
|
||||||
return SW_OK();
|
return SW_OK();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,32 +19,42 @@
|
|||||||
#include "sc_hsm.h"
|
#include "sc_hsm.h"
|
||||||
#include "asn1.h"
|
#include "asn1.h"
|
||||||
#include "kek.h"
|
#include "kek.h"
|
||||||
|
#include "files.h"
|
||||||
|
|
||||||
extern uint8_t get_key_domain(file_t *fkey);
|
extern uint8_t get_key_domain(file_t *fkey);
|
||||||
|
|
||||||
int cmd_key_wrap() {
|
int cmd_key_wrap() {
|
||||||
int key_id = P1(apdu), r = 0;
|
int r = 0;
|
||||||
|
uint8_t key_id = P1(apdu);
|
||||||
if (P2(apdu) != 0x92) {
|
if (P2(apdu) != 0x92) {
|
||||||
return SW_WRONG_P1P2();
|
return SW_WRONG_P1P2();
|
||||||
}
|
}
|
||||||
if (!isUserAuthenticated) {
|
if (!isUserAuthenticated) {
|
||||||
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
}
|
}
|
||||||
file_t *ef = search_dynamic_file((KEY_PREFIX << 8) | key_id);
|
file_t *ef = search_file((KEY_PREFIX << 8) | key_id);
|
||||||
uint8_t kdom = get_key_domain(ef);
|
|
||||||
if (!ef) {
|
if (!ef) {
|
||||||
return SW_FILE_NOT_FOUND();
|
return SW_FILE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
|
uint8_t kdom = get_key_domain(ef);
|
||||||
|
if (kdom == 0xff) {
|
||||||
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
file_t *tf_kd = search_file(EF_KEY_DOMAIN);
|
||||||
|
uint8_t *kdata = file_get_data(tf_kd), dkeks = kdata ? kdata[2 * kdom] : 0,
|
||||||
|
current_dkeks = kdata ? kdata[2 * kdom + 1] : 0;
|
||||||
|
if (dkeks != current_dkeks || dkeks == 0 || dkeks == 0xff) {
|
||||||
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
|
}
|
||||||
if (key_has_purpose(ef, ALGO_WRAP) == false) {
|
if (key_has_purpose(ef, ALGO_WRAP) == false) {
|
||||||
return SW_CONDITIONS_NOT_SATISFIED();
|
return SW_CONDITIONS_NOT_SATISFIED();
|
||||||
}
|
}
|
||||||
file_t *prkd = search_dynamic_file((PRKD_PREFIX << 8) | key_id);
|
file_t *prkd = search_file((PRKD_PREFIX << 8) | key_id);
|
||||||
if (!prkd) {
|
if (!prkd) {
|
||||||
return SW_FILE_NOT_FOUND();
|
return SW_FILE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
const uint8_t *dprkd = file_get_data(prkd);
|
const uint8_t *dprkd = file_get_data(prkd);
|
||||||
size_t wrap_len = MAX_DKEK_ENCODE_KEY_BUFFER;
|
uint16_t wrap_len = MAX_DKEK_ENCODE_KEY_BUFFER, tag_len = 0;
|
||||||
size_t tag_len = 0;
|
|
||||||
const uint8_t *meta_tag = get_meta_tag(ef, 0x91, &tag_len);
|
const uint8_t *meta_tag = get_meta_tag(ef, 0x91, &tag_len);
|
||||||
if (*dprkd == P15_KEYTYPE_RSA) {
|
if (*dprkd == P15_KEYTYPE_RSA) {
|
||||||
mbedtls_rsa_context ctx;
|
mbedtls_rsa_context ctx;
|
||||||
@@ -57,45 +67,48 @@ int cmd_key_wrap() {
|
|||||||
}
|
}
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
r = dkek_encode_key(kdom, &ctx, HSM_KEY_RSA, res_APDU, &wrap_len, meta_tag, tag_len);
|
r = dkek_encode_key(kdom, &ctx, PICO_KEYS_KEY_RSA, res_APDU, &wrap_len, meta_tag, tag_len);
|
||||||
mbedtls_rsa_free(&ctx);
|
mbedtls_rsa_free(&ctx);
|
||||||
}
|
}
|
||||||
else if (*dprkd == P15_KEYTYPE_ECC) {
|
else if (*dprkd == P15_KEYTYPE_ECC) {
|
||||||
mbedtls_ecdsa_context ctx;
|
mbedtls_ecp_keypair ctx;
|
||||||
mbedtls_ecdsa_init(&ctx);
|
mbedtls_ecp_keypair_init(&ctx);
|
||||||
r = load_private_key_ecdsa(&ctx, ef);
|
r = load_private_key_ec(&ctx, ef);
|
||||||
if (r != CCID_OK) {
|
if (r != CCID_OK) {
|
||||||
mbedtls_ecdsa_free(&ctx);
|
mbedtls_ecp_keypair_free(&ctx);
|
||||||
if (r == CCID_VERIFICATION_FAILED) {
|
if (r == CCID_VERIFICATION_FAILED) {
|
||||||
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
r = dkek_encode_key(kdom, &ctx, HSM_KEY_EC, res_APDU, &wrap_len, meta_tag, tag_len);
|
r = dkek_encode_key(kdom, &ctx, PICO_KEYS_KEY_EC, res_APDU, &wrap_len, meta_tag, tag_len);
|
||||||
mbedtls_ecdsa_free(&ctx);
|
mbedtls_ecp_keypair_free(&ctx);
|
||||||
}
|
}
|
||||||
else if (*dprkd == P15_KEYTYPE_AES) {
|
else if (*dprkd == P15_KEYTYPE_AES) {
|
||||||
uint8_t kdata[32]; //maximum AES key size
|
uint8_t kdata_aes[64]; //maximum AES key size
|
||||||
if (wait_button_pressed() == true) { //timeout
|
if (wait_button_pressed() == true) { //timeout
|
||||||
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
|
|
||||||
int key_size = file_get_size(ef), aes_type = HSM_KEY_AES;
|
uint16_t key_size = file_get_size(ef), aes_type = PICO_KEYS_KEY_AES;
|
||||||
memcpy(kdata, file_get_data(ef), key_size);
|
memcpy(kdata_aes, file_get_data(ef), key_size);
|
||||||
if (mkek_decrypt(kdata, key_size) != 0) {
|
if (mkek_decrypt(kdata_aes, key_size) != 0) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
if (key_size == 32) {
|
if (key_size == 64) {
|
||||||
aes_type = HSM_KEY_AES_256;
|
aes_type = PICO_KEYS_KEY_AES_512;
|
||||||
|
}
|
||||||
|
else if (key_size == 32) {
|
||||||
|
aes_type = PICO_KEYS_KEY_AES_256;
|
||||||
}
|
}
|
||||||
else if (key_size == 24) {
|
else if (key_size == 24) {
|
||||||
aes_type = HSM_KEY_AES_192;
|
aes_type = PICO_KEYS_KEY_AES_192;
|
||||||
}
|
}
|
||||||
else if (key_size == 16) {
|
else if (key_size == 16) {
|
||||||
aes_type = HSM_KEY_AES_128;
|
aes_type = PICO_KEYS_KEY_AES_128;
|
||||||
}
|
}
|
||||||
r = dkek_encode_key(kdom, kdata, aes_type, res_APDU, &wrap_len, meta_tag, tag_len);
|
r = dkek_encode_key(kdom, kdata_aes, aes_type, res_APDU, &wrap_len, meta_tag, tag_len);
|
||||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
mbedtls_platform_zeroize(kdata_aes, sizeof(kdata_aes));
|
||||||
}
|
}
|
||||||
if (r != CCID_OK) {
|
if (r != CCID_OK) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
|
|||||||
@@ -31,33 +31,23 @@ int cmd_keypair_gen() {
|
|||||||
}
|
}
|
||||||
int ret = 0;
|
int ret = 0;
|
||||||
|
|
||||||
size_t tout = 0;
|
|
||||||
//sc_asn1_print_tags(apdu.data, apdu.nc);
|
//sc_asn1_print_tags(apdu.data, apdu.nc);
|
||||||
uint8_t *p = NULL;
|
|
||||||
//DEBUG_DATA(apdu.data,apdu.nc);
|
//DEBUG_DATA(apdu.data,apdu.nc);
|
||||||
if (asn1_find_tag(apdu.data, apdu.nc, 0x7f49, &tout, &p) && tout > 0 && p != NULL) {
|
asn1_ctx_t ctxi, ctxo = { 0 };
|
||||||
size_t oid_len = 0;
|
asn1_ctx_init(apdu.data, (uint16_t)apdu.nc, &ctxi);
|
||||||
uint8_t *oid = NULL;
|
if (asn1_find_tag(&ctxi, 0x7f49, &ctxo) && asn1_len(&ctxo) > 0) {
|
||||||
if (asn1_find_tag(p, tout, 0x6, &oid_len, &oid) && oid_len > 0 && oid != NULL) {
|
asn1_ctx_t oid = { 0 };
|
||||||
if (memcmp(oid, OID_ID_TA_RSA_V1_5_SHA_256, oid_len) == 0) { //RSA
|
if (asn1_find_tag(&ctxo, 0x6, &oid) && asn1_len(&oid) > 0) {
|
||||||
size_t ex_len = 3, ks_len = 2;
|
if (memcmp(oid.data, OID_ID_TA_RSA_V1_5_SHA_256, oid.len) == 0) { //RSA
|
||||||
uint8_t *ex = NULL, *ks = NULL;
|
asn1_ctx_t ex = { 0 }, ks = { 0 };
|
||||||
uint32_t exponent = 65537, key_size = 2048;
|
uint32_t exponent = 65537, key_size = 2048;
|
||||||
if (asn1_find_tag(p, tout, 0x82, &ex_len, &ex) && ex_len > 0 && ex != NULL) {
|
if (asn1_find_tag(&ctxo, 0x82, &ex) && asn1_len(&ex) > 0) {
|
||||||
uint8_t *dt = ex;
|
exponent = asn1_get_uint(&ex);
|
||||||
exponent = 0;
|
|
||||||
for (int i = 0; i < ex_len; i++) {
|
|
||||||
exponent = (exponent << 8) | *dt++;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
if (asn1_find_tag(p, tout, 0x2, &ks_len, &ks) && ks_len > 0 && ks != NULL) {
|
if (asn1_find_tag(&ctxo, 0x2, &ks) && asn1_len(&ks) > 0) {
|
||||||
uint8_t *dt = ks;
|
key_size = asn1_get_uint(&ks);
|
||||||
key_size = 0;
|
|
||||||
for (int i = 0; i < ks_len; i++) {
|
|
||||||
key_size = (key_size << 8) | *dt++;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
printf("KEYPAIR RSA %lu (%lx)\r\n",
|
printf("KEYPAIR RSA %lu (%lx)\n",
|
||||||
(unsigned long) key_size,
|
(unsigned long) key_size,
|
||||||
(unsigned long) exponent);
|
(unsigned long) exponent);
|
||||||
mbedtls_rsa_context rsa;
|
mbedtls_rsa_context rsa;
|
||||||
@@ -69,27 +59,39 @@ int cmd_keypair_gen() {
|
|||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
if ((res_APDU_size =
|
if ((res_APDU_size =
|
||||||
asn1_cvc_aut(&rsa, HSM_KEY_RSA, res_APDU, 4096, NULL, 0)) == 0) {
|
(uint16_t)asn1_cvc_aut(&rsa, PICO_KEYS_KEY_RSA, res_APDU, 4096, NULL, 0)) == 0) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
ret = store_keys(&rsa, HSM_KEY_RSA, key_id);
|
ret = store_keys(&rsa, PICO_KEYS_KEY_RSA, key_id);
|
||||||
if (ret != CCID_OK) {
|
if (ret != CCID_OK) {
|
||||||
mbedtls_rsa_free(&rsa);
|
mbedtls_rsa_free(&rsa);
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
mbedtls_rsa_free(&rsa);
|
mbedtls_rsa_free(&rsa);
|
||||||
}
|
}
|
||||||
else if (memcmp(oid, OID_ID_TA_ECDSA_SHA_256, MIN(oid_len, 10)) == 0) { //ECC
|
else if (memcmp(oid.data, OID_ID_TA_ECDSA_SHA_256, MIN(oid.len, 10)) == 0) { //ECC
|
||||||
size_t prime_len;
|
asn1_ctx_t prime = { 0 };
|
||||||
uint8_t *prime = NULL;
|
if (asn1_find_tag(&ctxo, 0x81, &prime) != true) {
|
||||||
if (asn1_find_tag(p, tout, 0x81, &prime_len, &prime) != true) {
|
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
}
|
}
|
||||||
mbedtls_ecp_group_id ec_id = ec_get_curve_from_prime(prime, prime_len);
|
mbedtls_ecp_group_id ec_id = ec_get_curve_from_prime(prime.data, prime.len);
|
||||||
printf("KEYPAIR ECC %d\r\n", ec_id);
|
printf("KEYPAIR ECC %d\n", ec_id);
|
||||||
if (ec_id == MBEDTLS_ECP_DP_NONE) {
|
if (ec_id == MBEDTLS_ECP_DP_NONE) {
|
||||||
return SW_FUNC_NOT_SUPPORTED();
|
return SW_FUNC_NOT_SUPPORTED();
|
||||||
}
|
}
|
||||||
|
if (ec_id == MBEDTLS_ECP_DP_CURVE25519 || ec_id == MBEDTLS_ECP_DP_CURVE448) {
|
||||||
|
asn1_ctx_t g = { 0 };
|
||||||
|
if (asn1_find_tag(&ctxo, 0x83, &g) != true) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
printf("KEYPAIR ECC %d\r\n", ec_id);
|
||||||
mbedtls_ecdsa_context ecdsa;
|
mbedtls_ecdsa_context ecdsa;
|
||||||
mbedtls_ecdsa_init(&ecdsa);
|
mbedtls_ecdsa_init(&ecdsa);
|
||||||
uint8_t index = 0;
|
uint8_t index = 0;
|
||||||
@@ -98,52 +100,49 @@ int cmd_keypair_gen() {
|
|||||||
mbedtls_ecdsa_free(&ecdsa);
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
size_t l91 = 0, ext_len = 0;
|
asn1_ctx_t a91 = { 0 }, ext = { 0 };
|
||||||
uint8_t *p91 = NULL, *ext = NULL;
|
if (asn1_find_tag(&ctxi, 0x91, &a91) && asn1_len(&a91) > 0) {
|
||||||
if (asn1_find_tag(apdu.data, apdu.nc, 0x91, &l91, &p91) && p91 != NULL && l91 > 0) {
|
for (size_t n = 0; n < a91.len; n++) {
|
||||||
for (int n = 0; n < l91; n++) {
|
if (a91.data[n] == ALGO_EC_DH_XKEK) {
|
||||||
if (p91[n] == ALGO_EC_DH_XKEK) {
|
asn1_ctx_t a92 = {0};
|
||||||
size_t l92 = 0;
|
if (!asn1_find_tag(&ctxi, 0x92, &a92) || asn1_len(&a92) == 0) {
|
||||||
uint8_t *p92 = NULL;
|
|
||||||
if (!asn1_find_tag(apdu.data, apdu.nc, 0x92, &l92,
|
|
||||||
&p92) || p92 == NULL || l92 == 0) {
|
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
}
|
}
|
||||||
if (p92[0] > MAX_KEY_DOMAINS) {
|
if (a92.data[0] > MAX_KEY_DOMAINS) {
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
}
|
}
|
||||||
file_t *tf_xkek = search_dynamic_file(EF_XKEK + p92[0]);
|
file_t *tf_xkek = search_file(EF_XKEK + a92.data[0]);
|
||||||
if (!tf_xkek) {
|
if (!tf_xkek) {
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
}
|
}
|
||||||
ext_len = 2 + 2 + strlen(OID_ID_KEY_DOMAIN_UID) + 2 + file_get_size(
|
ext.len = 2 + 2 + (uint16_t)strlen(OID_ID_KEY_DOMAIN_UID) + 2 + file_get_size(
|
||||||
tf_xkek);
|
tf_xkek);
|
||||||
ext = (uint8_t *) calloc(1, ext_len);
|
ext.data = (uint8_t *) calloc(1, ext.len);
|
||||||
uint8_t *pe = ext;
|
uint8_t *pe = ext.data;
|
||||||
*pe++ = 0x73;
|
*pe++ = 0x73;
|
||||||
*pe++ = ext_len - 2;
|
*pe++ = (uint8_t)ext.len - 2;
|
||||||
*pe++ = 0x6;
|
*pe++ = 0x6;
|
||||||
*pe++ = strlen(OID_ID_KEY_DOMAIN_UID);
|
*pe++ = (uint8_t)strlen(OID_ID_KEY_DOMAIN_UID);
|
||||||
memcpy(pe, OID_ID_KEY_DOMAIN_UID, strlen(OID_ID_KEY_DOMAIN_UID));
|
memcpy(pe, OID_ID_KEY_DOMAIN_UID, strlen(OID_ID_KEY_DOMAIN_UID));
|
||||||
pe += strlen(OID_ID_KEY_DOMAIN_UID);
|
pe += strlen(OID_ID_KEY_DOMAIN_UID);
|
||||||
*pe++ = 0x80;
|
*pe++ = 0x80;
|
||||||
*pe++ = file_get_size(tf_xkek);
|
*pe++ = (uint8_t)file_get_size(tf_xkek);
|
||||||
memcpy(pe, file_get_data(tf_xkek), file_get_size(tf_xkek));
|
memcpy(pe, file_get_data(tf_xkek), file_get_size(tf_xkek));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if ((res_APDU_size =
|
if ((res_APDU_size =
|
||||||
asn1_cvc_aut(&ecdsa, HSM_KEY_EC, res_APDU, 4096, ext, ext_len)) == 0) {
|
(uint16_t)asn1_cvc_aut(&ecdsa, PICO_KEYS_KEY_EC, res_APDU, 4096, ext.data, ext.len)) == 0) {
|
||||||
if (ext) {
|
if (ext.data) {
|
||||||
free(ext);
|
free(ext.data);
|
||||||
}
|
}
|
||||||
mbedtls_ecdsa_free(&ecdsa);
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
if (ext) {
|
if (ext.data) {
|
||||||
free(ext);
|
free(ext.data);
|
||||||
}
|
}
|
||||||
ret = store_keys(&ecdsa, HSM_KEY_EC, key_id);
|
ret = store_keys(&ecdsa, PICO_KEYS_KEY_EC, key_id);
|
||||||
mbedtls_ecdsa_free(&ecdsa);
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
if (ret != CCID_OK) {
|
if (ret != CCID_OK) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
@@ -159,7 +158,7 @@ int cmd_keypair_gen() {
|
|||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
file_t *fpk = file_new((EE_CERTIFICATE_PREFIX << 8) | key_id);
|
file_t *fpk = file_new((EE_CERTIFICATE_PREFIX << 8) | key_id);
|
||||||
ret = flash_write_data_to_file(fpk, res_APDU, res_APDU_size);
|
ret = file_put_data(fpk, res_APDU, res_APDU_size);
|
||||||
if (ret != 0) {
|
if (ret != 0) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -21,11 +21,11 @@
|
|||||||
int cmd_list_keys() {
|
int cmd_list_keys() {
|
||||||
/* First we send DEV private key */
|
/* First we send DEV private key */
|
||||||
/* Both below conditions should be always TRUE */
|
/* Both below conditions should be always TRUE */
|
||||||
if (search_by_fid(EF_PRKD_DEV, NULL, SPECIFY_EF)) {
|
if (search_file(EF_PRKD_DEV)) {
|
||||||
res_APDU[res_APDU_size++] = EF_PRKD_DEV >> 8;
|
res_APDU[res_APDU_size++] = EF_PRKD_DEV >> 8;
|
||||||
res_APDU[res_APDU_size++] = EF_PRKD_DEV & 0xff;
|
res_APDU[res_APDU_size++] = EF_PRKD_DEV & 0xff;
|
||||||
}
|
}
|
||||||
if (search_by_fid(EF_KEY_DEV, NULL, SPECIFY_EF)) {
|
if (search_file(EF_KEY_DEV)) {
|
||||||
res_APDU[res_APDU_size++] = EF_KEY_DEV >> 8;
|
res_APDU[res_APDU_size++] = EF_KEY_DEV >> 8;
|
||||||
res_APDU[res_APDU_size++] = EF_KEY_DEV & 0xff;
|
res_APDU[res_APDU_size++] = EF_KEY_DEV & 0xff;
|
||||||
}
|
}
|
||||||
@@ -60,5 +60,11 @@ int cmd_list_keys() {
|
|||||||
res_APDU[res_APDU_size++] = f->fid & 0xff;
|
res_APDU[res_APDU_size++] = f->fid & 0xff;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
#if !defined(ENABLE_EMULATION) && !defined(ESP_PLATFORM)
|
||||||
|
if ((apdu.rlen + 2 + 10) % 64 == 0) { // FIX for strange behaviour with PSCS and multiple of 64
|
||||||
|
res_APDU[res_APDU_size++] = 0;
|
||||||
|
res_APDU[res_APDU_size++] = 0;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
return SW_OK();
|
return SW_OK();
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -33,8 +33,10 @@ int cmd_mse() {
|
|||||||
if (p1 & 0x1) { //SET
|
if (p1 & 0x1) { //SET
|
||||||
uint16_t tag = 0x0;
|
uint16_t tag = 0x0;
|
||||||
uint8_t *tag_data = NULL, *p = NULL;
|
uint8_t *tag_data = NULL, *p = NULL;
|
||||||
size_t tag_len = 0;
|
uint16_t tag_len = 0;
|
||||||
while (walk_tlv(apdu.data, apdu.nc, &p, &tag, &tag_len, &tag_data)) {
|
asn1_ctx_t ctxi;
|
||||||
|
asn1_ctx_init(apdu.data, (uint16_t)apdu.nc, &ctxi);
|
||||||
|
while (walk_tlv(&ctxi, &p, &tag, &tag_len, &tag_data)) {
|
||||||
if (tag == 0x80) {
|
if (tag == 0x80) {
|
||||||
if (p2 == 0xA4) {
|
if (p2 == 0xA4) {
|
||||||
if (tag_len == 10 &&
|
if (tag_len == 10 &&
|
||||||
@@ -54,20 +56,23 @@ int cmd_mse() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (p2 == 0xA4) { /* Aut */
|
else if (p2 == 0xA4) { /* Aut */
|
||||||
for (int i = 0; i < MAX_PUK; i++) {
|
for (uint8_t i = 0; i < MAX_PUK; i++) {
|
||||||
file_t *ef = search_dynamic_file(EF_PUK + i);
|
file_t *ef = search_file(EF_PUK + i);
|
||||||
if (!ef) {
|
if (!ef) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
if (!file_has_data(ef)) {
|
if (!file_has_data(ef)) {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
size_t chr_len = 0;
|
uint16_t chr_len = 0;
|
||||||
const uint8_t *chr = cvc_get_chr(file_get_data(ef),
|
const uint8_t *chr = cvc_get_chr(file_get_data(ef),
|
||||||
file_get_size(ef),
|
file_get_size(ef),
|
||||||
&chr_len);
|
&chr_len);
|
||||||
if (memcmp(chr, tag_data, chr_len) == 0) {
|
if (memcmp(chr, tag_data, chr_len) == 0) {
|
||||||
ef_puk_aut = ef;
|
ef_puk_aut = ef;
|
||||||
|
if (puk_status[i] == 1) {
|
||||||
|
return SW_CONDITIONS_NOT_SATISFIED(); // It is correct
|
||||||
|
}
|
||||||
return SW_OK();
|
return SW_OK();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -20,7 +20,7 @@
|
|||||||
#include "asn1.h"
|
#include "asn1.h"
|
||||||
#include "cvc.h"
|
#include "cvc.h"
|
||||||
|
|
||||||
extern int add_cert_puk_store(const uint8_t *data, size_t data_len, bool copy);
|
extern int add_cert_puk_store(const uint8_t *data, uint16_t data_len, bool copy);
|
||||||
extern PUK *current_puk;
|
extern PUK *current_puk;
|
||||||
|
|
||||||
int cmd_pso() {
|
int cmd_pso() {
|
||||||
@@ -33,13 +33,13 @@ int cmd_pso() {
|
|||||||
return SW_REFERENCE_NOT_FOUND();
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
if (apdu.data[0] != 0x7F || apdu.data[1] != 0x21) {
|
if (apdu.data[0] != 0x7F || apdu.data[1] != 0x21) {
|
||||||
uint8_t tlv_len = 2 + format_tlv_len(apdu.nc, NULL);
|
uint8_t tlv_len = 2 + format_tlv_len((uint16_t)apdu.nc, NULL);
|
||||||
memmove(apdu.data + tlv_len, apdu.data, apdu.nc);
|
memmove(apdu.data + tlv_len, apdu.data, apdu.nc);
|
||||||
memcpy(apdu.data, "\x7F\x21", 2);
|
memcpy(apdu.data, "\x7F\x21", 2);
|
||||||
format_tlv_len(apdu.nc, apdu.data + 2);
|
format_tlv_len((uint16_t)apdu.nc, apdu.data + 2);
|
||||||
apdu.nc += tlv_len;
|
apdu.nc += tlv_len;
|
||||||
}
|
}
|
||||||
int r = cvc_verify(apdu.data, apdu.nc, current_puk->cvcert, current_puk->cvcert_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_OK) {
|
||||||
if (r == CCID_WRONG_DATA) {
|
if (r == CCID_WRONG_DATA) {
|
||||||
return SW_DATA_INVALID();
|
return SW_DATA_INVALID();
|
||||||
@@ -49,28 +49,28 @@ int cmd_pso() {
|
|||||||
}
|
}
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
for (int i = 0; i < 0xfe; i++) {
|
for (uint8_t i = 0; i < 0xfe; i++) {
|
||||||
uint16_t fid = (CA_CERTIFICATE_PREFIX << 8) | i;
|
uint16_t fid = (CA_CERTIFICATE_PREFIX << 8) | i;
|
||||||
file_t *ca_ef = search_dynamic_file(fid);
|
file_t *ca_ef = search_file(fid);
|
||||||
if (!ca_ef) {
|
if (!ca_ef) {
|
||||||
ca_ef = file_new(fid);
|
ca_ef = file_new(fid);
|
||||||
flash_write_data_to_file(ca_ef, apdu.data, apdu.nc);
|
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),
|
if (add_cert_puk_store(file_get_data(ca_ef), file_get_size(ca_ef),
|
||||||
false) != CCID_OK) {
|
false) != CCID_OK) {
|
||||||
return SW_FILE_FULL();
|
return SW_FILE_FULL();
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t chr_len = 0;
|
uint16_t chr_len = 0;
|
||||||
const uint8_t *chr = cvc_get_chr(apdu.data, apdu.nc, &chr_len);
|
const uint8_t *chr = cvc_get_chr(apdu.data, (uint16_t)apdu.nc, &chr_len);
|
||||||
if (chr == NULL) {
|
if (chr == NULL) {
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
}
|
}
|
||||||
size_t puk_len = 0, puk_bin_len = 0;
|
uint16_t puk_len = 0, puk_bin_len = 0;
|
||||||
const uint8_t *puk = cvc_get_pub(apdu.data, apdu.nc, &puk_len), *puk_bin = NULL;
|
const uint8_t *puk = cvc_get_pub(apdu.data, (uint16_t)apdu.nc, &puk_len), *puk_bin = NULL;
|
||||||
if (puk == NULL) {
|
if (puk == NULL) {
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
}
|
}
|
||||||
size_t oid_len = 0;
|
uint16_t oid_len = 0;
|
||||||
const uint8_t *oid = cvc_get_field(puk, puk_len, &oid_len, 0x6);
|
const uint8_t *oid = cvc_get_field(puk, puk_len, &oid_len, 0x6);
|
||||||
if (oid == NULL) {
|
if (oid == NULL) {
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
@@ -82,15 +82,15 @@ int cmd_pso() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (memcmp(oid, OID_ID_TA_ECDSA, 9) == 0) { //ECC
|
else if (memcmp(oid, OID_ID_TA_ECDSA, 9) == 0) { //ECC
|
||||||
mbedtls_ecp_group_id ec_id = cvc_inherite_ec_group(apdu.data, apdu.nc);
|
mbedtls_ecp_group_id ec_id = cvc_inherite_ec_group(apdu.data, (uint16_t)apdu.nc);
|
||||||
mbedtls_ecp_group grp;
|
mbedtls_ecp_group grp;
|
||||||
mbedtls_ecp_group_init(&grp);
|
mbedtls_ecp_group_init(&grp);
|
||||||
if (mbedtls_ecp_group_load(&grp, ec_id) != 0) {
|
if (mbedtls_ecp_group_load(&grp, ec_id) != 0) {
|
||||||
mbedtls_ecp_group_free(&grp);
|
mbedtls_ecp_group_free(&grp);
|
||||||
return SW_WRONG_DATA();
|
return SW_WRONG_DATA();
|
||||||
}
|
}
|
||||||
size_t plen = mbedtls_mpi_size(&grp.P);
|
uint16_t plen = (uint16_t)mbedtls_mpi_size(&grp.P);
|
||||||
size_t t86_len = 0;
|
uint16_t t86_len = 0;
|
||||||
const uint8_t *t86 = cvc_get_field(puk, puk_len, &t86_len, 0x86);
|
const uint8_t *t86 = cvc_get_field(puk, puk_len, &t86_len, 0x86);
|
||||||
if (mbedtls_ecp_get_type(&grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
|
if (mbedtls_ecp_get_type(&grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
|
||||||
if (plen != t86_len) {
|
if (plen != t86_len) {
|
||||||
@@ -126,7 +126,7 @@ int cmd_pso() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
file_t *cd_ef = file_new((CD_PREFIX << 8) | i);
|
file_t *cd_ef = file_new((CD_PREFIX << 8) | i);
|
||||||
size_t cd_len = asn1_build_cert_description(chr,
|
uint16_t cd_len = (uint16_t)asn1_build_cert_description(chr,
|
||||||
chr_len,
|
chr_len,
|
||||||
puk_bin,
|
puk_bin,
|
||||||
puk_bin_len,
|
puk_bin_len,
|
||||||
@@ -137,14 +137,14 @@ int cmd_pso() {
|
|||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
uint8_t *buf = (uint8_t *) calloc(cd_len, sizeof(uint8_t));
|
uint8_t *buf = (uint8_t *) calloc(cd_len, sizeof(uint8_t));
|
||||||
int r = asn1_build_cert_description(chr,
|
r = (int)asn1_build_cert_description(chr,
|
||||||
chr_len,
|
chr_len,
|
||||||
puk_bin,
|
puk_bin,
|
||||||
puk_bin_len,
|
puk_bin_len,
|
||||||
fid,
|
fid,
|
||||||
buf,
|
buf,
|
||||||
cd_len);
|
cd_len);
|
||||||
flash_write_data_to_file(cd_ef, buf, cd_len);
|
file_put_data(cd_ef, buf, cd_len);
|
||||||
free(buf);
|
free(buf);
|
||||||
if (r == 0) {
|
if (r == 0) {
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
@@ -153,7 +153,6 @@ int cmd_pso() {
|
|||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return SW_OK();
|
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
return SW_INCORRECT_P1P2();
|
return SW_INCORRECT_P1P2();
|
||||||
|
|||||||
@@ -21,9 +21,12 @@
|
|||||||
|
|
||||||
int cmd_puk_auth() {
|
int cmd_puk_auth() {
|
||||||
uint8_t p1 = P1(apdu), p2 = P2(apdu);
|
uint8_t p1 = P1(apdu), p2 = P2(apdu);
|
||||||
file_t *ef_puk = search_by_fid(EF_PUKAUT, NULL, SPECIFY_EF);
|
file_t *ef_puk = search_file(EF_PUKAUT);
|
||||||
if (!file_has_data(ef_puk)) {
|
if (!file_has_data(ef_puk)) {
|
||||||
return SW_FILE_NOT_FOUND();
|
if (apdu.nc > 0) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
}
|
}
|
||||||
uint8_t *puk_data = file_get_data(ef_puk);
|
uint8_t *puk_data = file_get_data(ef_puk);
|
||||||
if (apdu.nc > 0) {
|
if (apdu.nc > 0) {
|
||||||
@@ -33,8 +36,8 @@ int cmd_puk_auth() {
|
|||||||
if (p2 != 0x0) {
|
if (p2 != 0x0) {
|
||||||
return SW_INCORRECT_P1P2();
|
return SW_INCORRECT_P1P2();
|
||||||
}
|
}
|
||||||
for (int i = 0; i < puk_data[0]; i++) {
|
for (uint8_t i = 0; i < puk_data[0]; i++) {
|
||||||
ef = search_dynamic_file(EF_PUK + i);
|
ef = search_file(EF_PUK + i);
|
||||||
if (!ef) { /* Never should not happen */
|
if (!ef) { /* Never should not happen */
|
||||||
return SW_MEMORY_FAILURE();
|
return SW_MEMORY_FAILURE();
|
||||||
}
|
}
|
||||||
@@ -45,7 +48,7 @@ int cmd_puk_auth() {
|
|||||||
uint8_t *tmp = (uint8_t *) calloc(file_get_size(ef_puk), sizeof(uint8_t));
|
uint8_t *tmp = (uint8_t *) calloc(file_get_size(ef_puk), sizeof(uint8_t));
|
||||||
memcpy(tmp, puk_data, file_get_size(ef_puk));
|
memcpy(tmp, puk_data, file_get_size(ef_puk));
|
||||||
tmp[1] = puk_data[1] - 1;
|
tmp[1] = puk_data[1] - 1;
|
||||||
flash_write_data_to_file(ef_puk, tmp, file_get_size(ef_puk));
|
file_put_data(ef_puk, tmp, file_get_size(ef_puk));
|
||||||
puk_data = file_get_data(ef_puk);
|
puk_data = file_get_data(ef_puk);
|
||||||
free(tmp);
|
free(tmp);
|
||||||
}
|
}
|
||||||
@@ -53,12 +56,12 @@ int cmd_puk_auth() {
|
|||||||
if (p2 >= puk_data[0]) {
|
if (p2 >= puk_data[0]) {
|
||||||
return SW_INCORRECT_P1P2();
|
return SW_INCORRECT_P1P2();
|
||||||
}
|
}
|
||||||
ef = search_dynamic_file(EF_PUK + p2);
|
ef = search_file(EF_PUK + p2);
|
||||||
if (!ef) { /* Never should not happen */
|
if (!ef) { /* Never should not happen */
|
||||||
return SW_MEMORY_FAILURE();
|
return SW_MEMORY_FAILURE();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
flash_write_data_to_file(ef, apdu.data, apdu.nc);
|
file_put_data(ef, apdu.data, (uint16_t)apdu.nc);
|
||||||
low_flash_available();
|
low_flash_available();
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
@@ -69,14 +72,14 @@ int cmd_puk_auth() {
|
|||||||
if (p2 >= puk_data[0]) {
|
if (p2 >= puk_data[0]) {
|
||||||
return SW_INCORRECT_P1P2();
|
return SW_INCORRECT_P1P2();
|
||||||
}
|
}
|
||||||
file_t *ef = search_dynamic_file(EF_PUK + p2);
|
file_t *ef = search_file(EF_PUK + p2);
|
||||||
if (!ef) {
|
if (!ef) {
|
||||||
return SW_INCORRECT_P1P2();
|
return SW_INCORRECT_P1P2();
|
||||||
}
|
}
|
||||||
if (!file_has_data(ef)) {
|
if (!file_has_data(ef)) {
|
||||||
return SW_REFERENCE_NOT_FOUND();
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
size_t chr_len = 0;
|
uint16_t chr_len = 0;
|
||||||
const uint8_t *chr = cvc_get_chr(file_get_data(ef), file_get_size(ef), &chr_len);
|
const uint8_t *chr = cvc_get_chr(file_get_data(ef), file_get_size(ef), &chr_len);
|
||||||
if (chr) {
|
if (chr) {
|
||||||
memcpy(res_APDU, chr, chr_len);
|
memcpy(res_APDU, chr, chr_len);
|
||||||
|
|||||||
@@ -18,14 +18,13 @@
|
|||||||
#include "sc_hsm.h"
|
#include "sc_hsm.h"
|
||||||
|
|
||||||
int cmd_read_binary() {
|
int cmd_read_binary() {
|
||||||
uint16_t fid = 0x0;
|
uint16_t offset = 0;
|
||||||
uint32_t offset = 0;
|
|
||||||
uint8_t ins = INS(apdu), p1 = P1(apdu), p2 = P2(apdu);
|
uint8_t ins = INS(apdu), p1 = P1(apdu), p2 = P2(apdu);
|
||||||
const file_t *ef = NULL;
|
const file_t *ef = NULL;
|
||||||
|
|
||||||
if ((ins & 0x1) == 0) {
|
if ((ins & 0x1) == 0) {
|
||||||
if ((p1 & 0x80) != 0) {
|
if ((p1 & 0x80) != 0) {
|
||||||
if (!(ef = search_by_fid(p1 & 0x1f, NULL, SPECIFY_EF))) {
|
if (!(ef = search_file(p1 & 0x1f))) {
|
||||||
return SW_FILE_NOT_FOUND();
|
return SW_FILE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
offset = p2;
|
offset = p2;
|
||||||
@@ -37,7 +36,7 @@ int cmd_read_binary() {
|
|||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
if (p1 == 0 && (p2 & 0xE0) == 0 && (p2 & 0x1f) != 0 && (p2 & 0x1f) != 0x1f) {
|
if (p1 == 0 && (p2 & 0xE0) == 0 && (p2 & 0x1f) != 0 && (p2 & 0x1f) != 0x1f) {
|
||||||
if (!(ef = search_by_fid(p2 & 0x1f, NULL, SPECIFY_EF))) {
|
if (!(ef = search_file(p2 & 0x1f))) {
|
||||||
return SW_FILE_NOT_FOUND();
|
return SW_FILE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -46,9 +45,7 @@ int cmd_read_binary() {
|
|||||||
if (file_id == 0x0) {
|
if (file_id == 0x0) {
|
||||||
ef = currentEF;
|
ef = currentEF;
|
||||||
}
|
}
|
||||||
else if (!(ef =
|
else if (!(ef = search_file(file_id))) {
|
||||||
search_by_fid(file_id, NULL,
|
|
||||||
SPECIFY_EF)) && !(ef = search_dynamic_file(file_id))) {
|
|
||||||
return SW_FILE_NOT_FOUND();
|
return SW_FILE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -63,12 +60,12 @@ int cmd_read_binary() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if ((fid >> 8) == KEY_PREFIX || !authenticate_action(ef, ACL_OP_READ_SEARCH)) {
|
if ((ef->fid >> 8) == KEY_PREFIX || !authenticate_action(ef, ACL_OP_READ_SEARCH)) {
|
||||||
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
}
|
}
|
||||||
if (ef->data) {
|
if (ef->data) {
|
||||||
if ((ef->type & FILE_DATA_FUNC) == FILE_DATA_FUNC) {
|
if ((ef->type & FILE_DATA_FUNC) == FILE_DATA_FUNC) {
|
||||||
uint16_t data_len = ((int (*)(const file_t *, int))(ef->data))((const file_t *) ef, 1); //already copies content to res_APDU
|
uint16_t data_len = (uint16_t)((int (*)(const file_t *, int))(ef->data))((const file_t *) ef, 1); //already copies content to res_APDU
|
||||||
if (offset > data_len) {
|
if (offset > data_len) {
|
||||||
return SW_WRONG_P1P2();
|
return SW_WRONG_P1P2();
|
||||||
}
|
}
|
||||||
@@ -85,13 +82,13 @@ int cmd_read_binary() {
|
|||||||
else {
|
else {
|
||||||
uint16_t data_len = file_get_size(ef);
|
uint16_t data_len = file_get_size(ef);
|
||||||
if (offset > data_len) {
|
if (offset > data_len) {
|
||||||
return SW_WRONG_P1P2();
|
return SW_WARNING_EOF();
|
||||||
}
|
}
|
||||||
|
|
||||||
uint16_t maxle = data_len - offset;
|
//uint16_t maxle = data_len - offset;
|
||||||
if (apdu.ne > maxle) {
|
//if (apdu.ne > maxle) {
|
||||||
apdu.ne = maxle;
|
// apdu.ne = maxle;
|
||||||
}
|
//}
|
||||||
memcpy(res_APDU, file_get_data(ef) + offset, data_len - offset);
|
memcpy(res_APDU, file_get_data(ef) + offset, data_len - offset);
|
||||||
res_APDU_size = data_len - offset;
|
res_APDU_size = data_len - offset;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -34,18 +34,17 @@ int cmd_reset_retry() {
|
|||||||
return SW_COMMAND_NOT_ALLOWED();
|
return SW_COMMAND_NOT_ALLOWED();
|
||||||
}
|
}
|
||||||
if (P1(apdu) == 0x0 || P1(apdu) == 0x2) {
|
if (P1(apdu) == 0x0 || P1(apdu) == 0x2) {
|
||||||
int newpin_len = 0;
|
uint8_t newpin_len = 0;
|
||||||
if (P1(apdu) == 0x0) {
|
if (P1(apdu) == 0x0) {
|
||||||
if (apdu.nc <= 8) {
|
uint8_t so_pin_len = file_read_uint8(file_sopin);
|
||||||
|
if ((uint16_t)apdu.nc <= so_pin_len + 1) {
|
||||||
return SW_WRONG_LENGTH();
|
return SW_WRONG_LENGTH();
|
||||||
}
|
}
|
||||||
uint16_t r = check_pin(file_sopin, apdu.data, 8);
|
uint16_t r = check_pin(file_sopin, apdu.data, so_pin_len);
|
||||||
if (r != 0x9000) {
|
if (r != 0x9000) {
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
newpin_len = apdu.nc - 8;
|
newpin_len = (uint8_t)apdu.nc - so_pin_len;
|
||||||
has_session_sopin = true;
|
|
||||||
hash_multi(apdu.data, 8, session_sopin);
|
|
||||||
}
|
}
|
||||||
else if (P1(apdu) == 0x2) {
|
else if (P1(apdu) == 0x2) {
|
||||||
if (!has_session_sopin) {
|
if (!has_session_sopin) {
|
||||||
@@ -54,12 +53,12 @@ int cmd_reset_retry() {
|
|||||||
if (apdu.nc > 16) {
|
if (apdu.nc > 16) {
|
||||||
return SW_WRONG_LENGTH();
|
return SW_WRONG_LENGTH();
|
||||||
}
|
}
|
||||||
newpin_len = apdu.nc;
|
newpin_len = (uint8_t)apdu.nc;
|
||||||
}
|
}
|
||||||
uint8_t dhash[33];
|
uint8_t dhash[33];
|
||||||
dhash[0] = newpin_len;
|
dhash[0] = newpin_len;
|
||||||
double_hash_pin(apdu.data + (apdu.nc - newpin_len), newpin_len, dhash + 1);
|
double_hash_pin(apdu.data + (apdu.nc - newpin_len), newpin_len, dhash + 1);
|
||||||
flash_write_data_to_file(file_pin1, dhash, sizeof(dhash));
|
file_put_data(file_pin1, dhash, sizeof(dhash));
|
||||||
if (pin_reset_retries(file_pin1, true) != CCID_OK) {
|
if (pin_reset_retries(file_pin1, true) != CCID_OK) {
|
||||||
return SW_MEMORY_FAILURE();
|
return SW_MEMORY_FAILURE();
|
||||||
}
|
}
|
||||||
@@ -83,15 +82,14 @@ int cmd_reset_retry() {
|
|||||||
return SW_COMMAND_NOT_ALLOWED();
|
return SW_COMMAND_NOT_ALLOWED();
|
||||||
}
|
}
|
||||||
if (P1(apdu) == 0x1) {
|
if (P1(apdu) == 0x1) {
|
||||||
if (apdu.nc != 8) {
|
uint8_t so_pin_len = file_read_uint8(file_sopin);
|
||||||
|
if (apdu.nc != so_pin_len) {
|
||||||
return SW_WRONG_LENGTH();
|
return SW_WRONG_LENGTH();
|
||||||
}
|
}
|
||||||
uint16_t r = check_pin(file_sopin, apdu.data, 8);
|
uint16_t r = check_pin(file_sopin, apdu.data, so_pin_len);
|
||||||
if (r != 0x9000) {
|
if (r != 0x9000) {
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
has_session_sopin = true;
|
|
||||||
hash_multi(apdu.data, 8, session_sopin);
|
|
||||||
}
|
}
|
||||||
else if (P1(apdu) == 0x3) {
|
else if (P1(apdu) == 0x3) {
|
||||||
if (!has_session_sopin) {
|
if (!has_session_sopin) {
|
||||||
|
|||||||
@@ -23,7 +23,7 @@ void select_file(file_t *pe) {
|
|||||||
currentDF = (file_t *) MF;
|
currentDF = (file_t *) MF;
|
||||||
currentEF = NULL;
|
currentEF = NULL;
|
||||||
}
|
}
|
||||||
else if (pe->type & FILE_TYPE_INTERNAL_EF) {
|
else if (pe->type & (FILE_TYPE_INTERNAL_EF|FILE_TYPE_WORKING_EF)) {
|
||||||
currentEF = pe;
|
currentEF = pe;
|
||||||
currentDF = &file_entries[pe->parent];
|
currentDF = &file_entries[pe->parent];
|
||||||
}
|
}
|
||||||
@@ -47,26 +47,26 @@ int cmd_select() {
|
|||||||
// return SW_INCORRECT_P1P2();
|
// return SW_INCORRECT_P1P2();
|
||||||
//}
|
//}
|
||||||
|
|
||||||
if (apdu.nc >= 2) {
|
if (apdu.nc == 2) {
|
||||||
fid = get_uint16_t(apdu.data, 0);
|
fid = get_uint16_t(apdu.data, 0);
|
||||||
}
|
}
|
||||||
|
|
||||||
//if ((fid & 0xff00) == (KEY_PREFIX << 8))
|
//if ((fid & 0xff00) == (KEY_PREFIX << 8))
|
||||||
// fid = (PRKD_PREFIX << 8) | (fid & 0xff);
|
// fid = (PRKD_PREFIX << 8) | (fid & 0xff);
|
||||||
|
|
||||||
uint8_t pfx = fid >> 8;
|
/*uint8_t pfx = fid >> 8;*/
|
||||||
if (pfx == PRKD_PREFIX ||
|
/*if (pfx == PRKD_PREFIX ||
|
||||||
pfx == CD_PREFIX ||
|
pfx == CD_PREFIX ||
|
||||||
pfx == CA_CERTIFICATE_PREFIX ||
|
pfx == CA_CERTIFICATE_PREFIX ||
|
||||||
pfx == KEY_PREFIX ||
|
pfx == KEY_PREFIX ||
|
||||||
pfx == EE_CERTIFICATE_PREFIX ||
|
pfx == EE_CERTIFICATE_PREFIX ||
|
||||||
pfx == DCOD_PREFIX ||
|
pfx == DCOD_PREFIX ||
|
||||||
pfx == DATA_PREFIX ||
|
pfx == DATA_PREFIX ||
|
||||||
pfx == PROT_DATA_PREFIX) {
|
pfx == PROT_DATA_PREFIX) {*/
|
||||||
if (!(pe = search_dynamic_file(fid)) && !(pe = search_by_fid(fid, NULL, SPECIFY_EF))) {
|
if (fid != 0x0 && !(pe = search_file(fid))) {
|
||||||
return SW_FILE_NOT_FOUND();
|
return SW_FILE_NOT_FOUND();
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
/*}*/
|
||||||
if (!pe) {
|
if (!pe) {
|
||||||
if (p1 == 0x0) { //Select MF, DF or EF - File identifier or absent
|
if (p1 == 0x0) { //Select MF, DF or EF - File identifier or absent
|
||||||
if (apdu.nc == 0) {
|
if (apdu.nc == 0) {
|
||||||
@@ -95,7 +95,7 @@ int cmd_select() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (p1 == 0x04) { //Select by DF name - e.g., [truncated] application identifier
|
else if (p1 == 0x04) { //Select by DF name - e.g., [truncated] application identifier
|
||||||
if (!(pe = search_by_name(apdu.data, apdu.nc))) {
|
if (!(pe = search_by_name(apdu.data, (uint16_t)apdu.nc))) {
|
||||||
return SW_FILE_NOT_FOUND();
|
return SW_FILE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
if (card_terminated) {
|
if (card_terminated) {
|
||||||
@@ -103,12 +103,12 @@ int cmd_select() {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (p1 == 0x08) { //Select from the MF - Path without the MF identifier
|
else if (p1 == 0x08) { //Select from the MF - Path without the MF identifier
|
||||||
if (!(pe = search_by_path(apdu.data, apdu.nc, MF))) {
|
if (!(pe = search_by_path(apdu.data, (uint8_t)apdu.nc, MF))) {
|
||||||
return SW_FILE_NOT_FOUND();
|
return SW_FILE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (p1 == 0x09) { //Select from the current DF - Path without the current DF identifier
|
else if (p1 == 0x09) { //Select from the current DF - Path without the current DF identifier
|
||||||
if (!(pe = search_by_path(apdu.data, apdu.nc, currentDF))) {
|
if (!(pe = search_by_path(apdu.data, (uint8_t)apdu.nc, currentDF))) {
|
||||||
return SW_FILE_NOT_FOUND();
|
return SW_FILE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -124,7 +124,7 @@ int cmd_select() {
|
|||||||
res_APDU[res_APDU_size++] = 0xFF;
|
res_APDU[res_APDU_size++] = 0xFF;
|
||||||
res_APDU[res_APDU_size++] = HSM_VERSION_MAJOR;
|
res_APDU[res_APDU_size++] = HSM_VERSION_MAJOR;
|
||||||
res_APDU[res_APDU_size++] = HSM_VERSION_MINOR;
|
res_APDU[res_APDU_size++] = HSM_VERSION_MINOR;
|
||||||
res_APDU[1] = res_APDU_size - 2;
|
res_APDU[1] = (uint8_t)res_APDU_size - 2;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
|
|||||||
@@ -14,12 +14,16 @@
|
|||||||
* You should have received a copy of the GNU General Public License
|
* You should have received a copy of the GNU General Public License
|
||||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
#include "sc_hsm.h"
|
||||||
#include "crypto_utils.h"
|
#include "crypto_utils.h"
|
||||||
#include "sc_hsm.h"
|
#include "sc_hsm.h"
|
||||||
#include "asn1.h"
|
#include "asn1.h"
|
||||||
#include "mbedtls/oid.h"
|
#include "mbedtls/oid.h"
|
||||||
#include "random.h"
|
#include "random.h"
|
||||||
|
#include "mbedtls/eddsa.h"
|
||||||
|
|
||||||
|
extern mbedtls_ecp_keypair hd_context;
|
||||||
|
extern uint8_t hd_keytype;
|
||||||
|
|
||||||
//-----
|
//-----
|
||||||
/* From OpenSC */
|
/* From OpenSC */
|
||||||
@@ -54,8 +58,8 @@ static const uint8_t hdr_ripemd160[] = {
|
|||||||
static const struct digest_info_prefix {
|
static const struct digest_info_prefix {
|
||||||
mbedtls_md_type_t algorithm;
|
mbedtls_md_type_t algorithm;
|
||||||
const uint8_t *hdr;
|
const uint8_t *hdr;
|
||||||
size_t hdr_len;
|
uint16_t hdr_len;
|
||||||
size_t hash_len;
|
uint16_t hash_len;
|
||||||
} digest_info_prefix[] = {
|
} digest_info_prefix[] = {
|
||||||
{ MBEDTLS_MD_MD5, hdr_md5, sizeof(hdr_md5), 16 },
|
{ MBEDTLS_MD_MD5, hdr_md5, sizeof(hdr_md5), 16 },
|
||||||
{ MBEDTLS_MD_SHA1, hdr_sha1, sizeof(hdr_sha1), 20 },
|
{ MBEDTLS_MD_SHA1, hdr_sha1, sizeof(hdr_sha1), 20 },
|
||||||
@@ -68,11 +72,11 @@ static const struct digest_info_prefix {
|
|||||||
};
|
};
|
||||||
int pkcs1_strip_digest_info_prefix(mbedtls_md_type_t *algorithm,
|
int pkcs1_strip_digest_info_prefix(mbedtls_md_type_t *algorithm,
|
||||||
const uint8_t *in_dat,
|
const uint8_t *in_dat,
|
||||||
size_t in_len,
|
uint16_t in_len,
|
||||||
uint8_t *out_dat,
|
uint8_t *out_dat,
|
||||||
size_t *out_len) {
|
uint16_t *out_len) {
|
||||||
for (int i = 0; digest_info_prefix[i].algorithm != 0; i++) {
|
for (int i = 0; digest_info_prefix[i].algorithm != 0; i++) {
|
||||||
size_t hdr_len = digest_info_prefix[i].hdr_len, hash_len = digest_info_prefix[i].hash_len;
|
uint16_t hdr_len = digest_info_prefix[i].hdr_len, hash_len = digest_info_prefix[i].hash_len;
|
||||||
const uint8_t *hdr = digest_info_prefix[i].hdr;
|
const uint8_t *hdr = digest_info_prefix[i].hdr;
|
||||||
if (in_len == (hdr_len + hash_len) && !memcmp(in_dat, hdr, hdr_len)) {
|
if (in_len == (hdr_len + hash_len) && !memcmp(in_dat, hdr, hdr_len)) {
|
||||||
if (algorithm) {
|
if (algorithm) {
|
||||||
@@ -101,7 +105,7 @@ int cmd_signature() {
|
|||||||
if (!isUserAuthenticated) {
|
if (!isUserAuthenticated) {
|
||||||
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
}
|
}
|
||||||
if (!(fkey = search_dynamic_file((KEY_PREFIX << 8) | key_id)) || !file_has_data(fkey)) {
|
if (!(fkey = search_file((KEY_PREFIX << 8) | key_id)) || !file_has_data(fkey)) {
|
||||||
return SW_FILE_NOT_FOUND();
|
return SW_FILE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
if (get_key_counter(fkey) == 0) {
|
if (get_key_counter(fkey) == 0) {
|
||||||
@@ -110,7 +114,7 @@ int cmd_signature() {
|
|||||||
if (key_has_purpose(fkey, p2) == false) {
|
if (key_has_purpose(fkey, p2) == false) {
|
||||||
return SW_CONDITIONS_NOT_SATISFIED();
|
return SW_CONDITIONS_NOT_SATISFIED();
|
||||||
}
|
}
|
||||||
int key_size = file_get_size(fkey);
|
uint16_t key_size = file_get_size(fkey);
|
||||||
if (p2 == ALGO_RSA_PKCS1_SHA1 || p2 == ALGO_RSA_PSS_SHA1 || p2 == ALGO_EC_SHA1) {
|
if (p2 == ALGO_RSA_PKCS1_SHA1 || p2 == ALGO_RSA_PSS_SHA1 || p2 == ALGO_EC_SHA1) {
|
||||||
md = MBEDTLS_MD_SHA1;
|
md = MBEDTLS_MD_SHA1;
|
||||||
}
|
}
|
||||||
@@ -146,11 +150,10 @@ int cmd_signature() {
|
|||||||
}
|
}
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
uint8_t *hash = apdu.data;
|
asn1_ctx_t hash = {.len = (uint16_t)apdu.nc, .data = apdu.data};
|
||||||
size_t hash_len = apdu.nc;
|
|
||||||
if (p2 == ALGO_RSA_PKCS1) { //DigestInfo attached
|
if (p2 == ALGO_RSA_PKCS1) { //DigestInfo attached
|
||||||
size_t nc = apdu.nc;
|
uint16_t nc = (uint16_t)apdu.nc;
|
||||||
if (pkcs1_strip_digest_info_prefix(&md, apdu.data, apdu.nc, apdu.data,
|
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) != CCID_OK) { //gets the MD algo id and strips it off
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
@@ -158,35 +161,34 @@ int cmd_signature() {
|
|||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
//sc_asn1_print_tags(apdu.data, apdu.nc);
|
//sc_asn1_print_tags(apdu.data, apdu.nc);
|
||||||
size_t tout = 0, oid_len = 0;
|
asn1_ctx_t ctxi, ctxo = { 0 }, oid = { 0 };
|
||||||
uint8_t *p = NULL, *oid = NULL;
|
asn1_ctx_init(apdu.data, (uint16_t)apdu.nc, &ctxi);
|
||||||
if (asn1_find_tag(apdu.data, apdu.nc, 0x30, &tout, &p) && tout > 0 && p != NULL) {
|
if (asn1_find_tag(&ctxi, 0x30, &ctxo) && asn1_len(&ctxo) > 0) {
|
||||||
size_t tout30 = 0;
|
asn1_ctx_t a30 = { 0 };
|
||||||
uint8_t *c30 = NULL;
|
if (asn1_find_tag(&ctxo, 0x30, &a30) && asn1_len(&a30) > 0) {
|
||||||
if (asn1_find_tag(p, tout, 0x30, &tout30, &c30) && tout30 > 0 && c30 != NULL) {
|
asn1_find_tag(&a30, 0x6, &oid);
|
||||||
asn1_find_tag(c30, tout30, 0x6, &oid_len, &oid);
|
|
||||||
}
|
}
|
||||||
asn1_find_tag(p, tout, 0x4, &hash_len, &hash);
|
asn1_find_tag(&ctxo, 0x4, &hash);
|
||||||
}
|
}
|
||||||
if (oid && oid_len > 0) {
|
if (asn1_len(&oid)) {
|
||||||
if (memcmp(oid, MBEDTLS_OID_DIGEST_ALG_SHA1, oid_len) == 0) {
|
if (memcmp(oid.data, MBEDTLS_OID_DIGEST_ALG_SHA1, oid.len) == 0) {
|
||||||
md = MBEDTLS_MD_SHA1;
|
md = MBEDTLS_MD_SHA1;
|
||||||
}
|
}
|
||||||
else if (memcmp(oid, MBEDTLS_OID_DIGEST_ALG_SHA224, oid_len) == 0) {
|
else if (memcmp(oid.data, MBEDTLS_OID_DIGEST_ALG_SHA224, oid.len) == 0) {
|
||||||
md = MBEDTLS_MD_SHA224;
|
md = MBEDTLS_MD_SHA224;
|
||||||
}
|
}
|
||||||
else if (memcmp(oid, MBEDTLS_OID_DIGEST_ALG_SHA256, oid_len) == 0) {
|
else if (memcmp(oid.data, MBEDTLS_OID_DIGEST_ALG_SHA256, oid.len) == 0) {
|
||||||
md = MBEDTLS_MD_SHA256;
|
md = MBEDTLS_MD_SHA256;
|
||||||
}
|
}
|
||||||
else if (memcmp(oid, MBEDTLS_OID_DIGEST_ALG_SHA384, oid_len) == 0) {
|
else if (memcmp(oid.data, MBEDTLS_OID_DIGEST_ALG_SHA384, oid.len) == 0) {
|
||||||
md = MBEDTLS_MD_SHA384;
|
md = MBEDTLS_MD_SHA384;
|
||||||
}
|
}
|
||||||
else if (memcmp(oid, MBEDTLS_OID_DIGEST_ALG_SHA512, oid_len) == 0) {
|
else if (memcmp(oid.data, MBEDTLS_OID_DIGEST_ALG_SHA512, oid.len) == 0) {
|
||||||
md = MBEDTLS_MD_SHA512;
|
md = MBEDTLS_MD_SHA512;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (p2 >= ALGO_RSA_PSS && p2 <= ALGO_RSA_PSS_SHA512) {
|
if (p2 >= ALGO_RSA_PSS && p2 <= ALGO_RSA_PSS_SHA512) {
|
||||||
if (p2 == ALGO_RSA_PSS && !oid) {
|
if (p2 == ALGO_RSA_PSS && asn1_len(&oid) == 0) {
|
||||||
if (apdu.nc == 20) { //default is sha1
|
if (apdu.nc == 20) { //default is sha1
|
||||||
md = MBEDTLS_MD_SHA1;
|
md = MBEDTLS_MD_SHA1;
|
||||||
}
|
}
|
||||||
@@ -214,7 +216,7 @@ int cmd_signature() {
|
|||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
uint8_t *signature = (uint8_t *) calloc(key_size, sizeof(uint8_t));
|
uint8_t *signature = (uint8_t *) calloc(key_size, sizeof(uint8_t));
|
||||||
r = mbedtls_rsa_pkcs1_sign(&ctx, random_gen, NULL, md, hash_len, hash, signature);
|
r = mbedtls_rsa_pkcs1_sign(&ctx, random_gen, NULL, md, hash.len, hash.data, signature);
|
||||||
memcpy(res_APDU, signature, key_size);
|
memcpy(res_APDU, signature, key_size);
|
||||||
free(signature);
|
free(signature);
|
||||||
}
|
}
|
||||||
@@ -227,8 +229,8 @@ int cmd_signature() {
|
|||||||
mbedtls_rsa_free(&ctx);
|
mbedtls_rsa_free(&ctx);
|
||||||
}
|
}
|
||||||
else if (p2 >= ALGO_EC_RAW && p2 <= ALGO_EC_SHA512) {
|
else if (p2 >= ALGO_EC_RAW && p2 <= ALGO_EC_SHA512) {
|
||||||
mbedtls_ecdsa_context ctx;
|
mbedtls_ecp_keypair ctx;
|
||||||
mbedtls_ecdsa_init(&ctx);
|
mbedtls_ecp_keypair_init(&ctx);
|
||||||
md = MBEDTLS_MD_SHA256;
|
md = MBEDTLS_MD_SHA256;
|
||||||
if (p2 == ALGO_EC_RAW) {
|
if (p2 == ALGO_EC_RAW) {
|
||||||
if (apdu.nc == 32) {
|
if (apdu.nc == 32) {
|
||||||
@@ -262,9 +264,9 @@ int cmd_signature() {
|
|||||||
else if (p2 == ALGO_EC_SHA512) {
|
else if (p2 == ALGO_EC_SHA512) {
|
||||||
md = MBEDTLS_MD_SHA512;
|
md = MBEDTLS_MD_SHA512;
|
||||||
}
|
}
|
||||||
int r = load_private_key_ecdsa(&ctx, fkey);
|
int r = load_private_key_ec(&ctx, fkey);
|
||||||
if (r != CCID_OK) {
|
if (r != CCID_OK) {
|
||||||
mbedtls_ecdsa_free(&ctx);
|
mbedtls_ecp_keypair_free(&ctx);
|
||||||
if (r == CCID_VERIFICATION_FAILED) {
|
if (r == CCID_VERIFICATION_FAILED) {
|
||||||
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
@@ -272,14 +274,41 @@ int cmd_signature() {
|
|||||||
}
|
}
|
||||||
size_t olen = 0;
|
size_t olen = 0;
|
||||||
uint8_t buf[MBEDTLS_ECDSA_MAX_LEN];
|
uint8_t buf[MBEDTLS_ECDSA_MAX_LEN];
|
||||||
if (mbedtls_ecdsa_write_signature(&ctx, md, apdu.data, apdu.nc, buf, MBEDTLS_ECDSA_MAX_LEN,
|
if (ctx.grp.id == MBEDTLS_ECP_DP_ED25519 || ctx.grp.id == MBEDTLS_ECP_DP_ED448) {
|
||||||
&olen, random_gen, NULL) != 0) {
|
r = mbedtls_eddsa_write_signature(&ctx, apdu.data, apdu.nc, buf, sizeof(buf), &olen, MBEDTLS_EDDSA_PURE, NULL, 0, random_gen, NULL);
|
||||||
mbedtls_ecdsa_free(&ctx);
|
}
|
||||||
|
else {
|
||||||
|
r = mbedtls_ecdsa_write_signature(&ctx, md, apdu.data, apdu.nc, buf, MBEDTLS_ECDSA_MAX_LEN,
|
||||||
|
&olen, random_gen, NULL);
|
||||||
|
}
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_ecp_keypair_free(&ctx);
|
||||||
return SW_EXEC_ERROR();
|
return SW_EXEC_ERROR();
|
||||||
}
|
}
|
||||||
memcpy(res_APDU, buf, olen);
|
memcpy(res_APDU, buf, olen);
|
||||||
res_APDU_size = olen;
|
res_APDU_size = (uint16_t)olen;
|
||||||
mbedtls_ecdsa_free(&ctx);
|
mbedtls_ecp_keypair_free(&ctx);
|
||||||
|
}
|
||||||
|
else if (p2 == ALGO_HD) {
|
||||||
|
size_t olen = 0;
|
||||||
|
uint8_t buf[MBEDTLS_ECDSA_MAX_LEN];
|
||||||
|
if (hd_context.grp.id == MBEDTLS_ECP_DP_NONE) {
|
||||||
|
return SW_CONDITIONS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
if (hd_keytype != 0x1 && hd_keytype != 0x2) {
|
||||||
|
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);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
memcpy(res_APDU, buf, olen);
|
||||||
|
res_APDU_size = (uint16_t)olen;
|
||||||
|
mbedtls_ecdsa_free(&hd_context);
|
||||||
|
hd_keytype = 0;
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
return SW_INCORRECT_P1P2();
|
return SW_INCORRECT_P1P2();
|
||||||
|
|||||||
@@ -33,11 +33,14 @@ int cmd_update_ef() {
|
|||||||
if (fid == 0x0) {
|
if (fid == 0x0) {
|
||||||
ef = currentEF;
|
ef = currentEF;
|
||||||
}
|
}
|
||||||
else if (p1 != EE_CERTIFICATE_PREFIX && p1 != PRKD_PREFIX && p1 != CA_CERTIFICATE_PREFIX &&
|
/*
|
||||||
|
// This should not happen
|
||||||
|
else if (p1 != EE_CERTIFICATE_PREFIX && p1 != PRKD_PREFIX && p1 != CA_CERTIFICATE_PREFIX &&
|
||||||
p1 != CD_PREFIX && p1 != DATA_PREFIX && p1 != DCOD_PREFIX &&
|
p1 != CD_PREFIX && p1 != DATA_PREFIX && p1 != DCOD_PREFIX &&
|
||||||
p1 != PROT_DATA_PREFIX) {
|
p1 != PROT_DATA_PREFIX) {
|
||||||
return SW_INCORRECT_P1P2();
|
return SW_INCORRECT_P1P2();
|
||||||
}
|
}
|
||||||
|
*/
|
||||||
|
|
||||||
if (ef && !authenticate_action(ef, ACL_OP_UPDATE_ERASE)) {
|
if (ef && !authenticate_action(ef, ACL_OP_UPDATE_ERASE)) {
|
||||||
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
@@ -45,15 +48,17 @@ int cmd_update_ef() {
|
|||||||
|
|
||||||
uint16_t tag = 0x0;
|
uint16_t tag = 0x0;
|
||||||
uint8_t *tag_data = NULL, *p = NULL;
|
uint8_t *tag_data = NULL, *p = NULL;
|
||||||
size_t tag_len = 0;
|
uint16_t tag_len = 0;
|
||||||
while (walk_tlv(apdu.data, apdu.nc, &p, &tag, &tag_len, &tag_data)) {
|
asn1_ctx_t ctxi;
|
||||||
|
asn1_ctx_init(apdu.data, (uint16_t)apdu.nc, &ctxi);
|
||||||
|
while (walk_tlv(&ctxi, &p, &tag, &tag_len, &tag_data)) {
|
||||||
if (tag == 0x54) { //ofset tag
|
if (tag == 0x54) { //ofset tag
|
||||||
for (int i = 1; i <= tag_len; i++) {
|
for (size_t i = 1; i <= tag_len; i++) {
|
||||||
offset |= (*tag_data++ << (8 * (tag_len - i)));
|
offset |= (*tag_data++ << (8 * (tag_len - i)));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else if (tag == 0x53) { //data
|
else if (tag == 0x53) { //data
|
||||||
data_len = tag_len;
|
data_len = (uint16_t)tag_len;
|
||||||
data = tag_data;
|
data = tag_data;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -67,15 +72,12 @@ int cmd_update_ef() {
|
|||||||
if (fid == 0x0 && !ef) {
|
if (fid == 0x0 && !ef) {
|
||||||
return SW_FILE_NOT_FOUND();
|
return SW_FILE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
else if (fid != 0x0 &&
|
else if (fid != 0x0 && !(ef = search_file(fid))) { //if does not exist, create it
|
||||||
!(ef =
|
|
||||||
search_by_fid(fid, NULL,
|
|
||||||
SPECIFY_EF)) && !(ef = search_dynamic_file(fid))) { //if does not exist, create it
|
|
||||||
//return SW_FILE_NOT_FOUND();
|
//return SW_FILE_NOT_FOUND();
|
||||||
ef = file_new(fid);
|
ef = file_new(fid);
|
||||||
}
|
}
|
||||||
if (offset == 0) {
|
if (offset == 0) {
|
||||||
int r = flash_write_data_to_file(ef, data, data_len);
|
int r = file_put_data(ef, data, data_len);
|
||||||
if (r != CCID_OK) {
|
if (r != CCID_OK) {
|
||||||
return SW_MEMORY_FAILURE();
|
return SW_MEMORY_FAILURE();
|
||||||
}
|
}
|
||||||
@@ -88,7 +90,7 @@ int cmd_update_ef() {
|
|||||||
uint8_t *data_merge = (uint8_t *) calloc(1, offset + data_len);
|
uint8_t *data_merge = (uint8_t *) calloc(1, offset + data_len);
|
||||||
memcpy(data_merge, file_get_data(ef), offset);
|
memcpy(data_merge, file_get_data(ef), offset);
|
||||||
memcpy(data_merge + offset, data, data_len);
|
memcpy(data_merge + offset, data, data_len);
|
||||||
int r = flash_write_data_to_file(ef, data_merge, offset + data_len);
|
int r = file_put_data(ef, data_merge, offset + data_len);
|
||||||
free(data_merge);
|
free(data_merge);
|
||||||
if (r != CCID_OK) {
|
if (r != CCID_OK) {
|
||||||
return SW_MEMORY_FAILURE();
|
return SW_MEMORY_FAILURE();
|
||||||
|
|||||||
@@ -37,27 +37,27 @@ int cmd_verify() {
|
|||||||
return SW_REFERENCE_NOT_FOUND();
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
if (apdu.nc > 0) {
|
if (apdu.nc > 0) {
|
||||||
return check_pin(file_pin1, apdu.data, apdu.nc);
|
return check_pin(file_pin1, apdu.data, (uint16_t)apdu.nc);
|
||||||
}
|
}
|
||||||
if (file_read_uint8(file_get_data(file_retries_pin1)) == 0) {
|
if (file_read_uint8(file_retries_pin1) == 0) {
|
||||||
return SW_PIN_BLOCKED();
|
return SW_PIN_BLOCKED();
|
||||||
}
|
}
|
||||||
return set_res_sw(0x63, 0xc0 | file_read_uint8(file_get_data(file_retries_pin1)));
|
return set_res_sw(0x63, 0xc0 | file_read_uint8(file_retries_pin1));
|
||||||
}
|
}
|
||||||
else if (p2 == 0x88) { //SOPin
|
else if (p2 == 0x88) { //SOPin
|
||||||
if (file_read_uint8(file_get_data(file_sopin)) == 0) { //not initialized
|
if (file_read_uint8(file_sopin) == 0) { //not initialized
|
||||||
return SW_REFERENCE_NOT_FOUND();
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
if (apdu.nc > 0) {
|
if (apdu.nc > 0) {
|
||||||
return check_pin(file_sopin, apdu.data, apdu.nc);
|
return check_pin(file_sopin, apdu.data, (uint16_t)apdu.nc);
|
||||||
}
|
}
|
||||||
if (file_read_uint8(file_get_data(file_retries_sopin)) == 0) {
|
if (file_read_uint8(file_retries_sopin) == 0) {
|
||||||
return SW_PIN_BLOCKED();
|
return SW_PIN_BLOCKED();
|
||||||
}
|
}
|
||||||
if (has_session_sopin) {
|
if (has_session_sopin) {
|
||||||
return SW_OK();
|
return SW_OK();
|
||||||
}
|
}
|
||||||
return set_res_sw(0x63, 0xc0 | file_read_uint8(file_get_data(file_retries_sopin)));
|
return set_res_sw(0x63, 0xc0 | file_read_uint8(file_retries_sopin));
|
||||||
}
|
}
|
||||||
else if (p2 == 0x85) {
|
else if (p2 == 0x85) {
|
||||||
return SW_OK();
|
return SW_OK();
|
||||||
|
|||||||
550
src/hsm/cvc.c
550
src/hsm/cvc.c
@@ -15,9 +15,8 @@
|
|||||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include "common.h"
|
|
||||||
#include "cvc.h"
|
|
||||||
#include "sc_hsm.h"
|
#include "sc_hsm.h"
|
||||||
|
#include "cvc.h"
|
||||||
#include "mbedtls/rsa.h"
|
#include "mbedtls/rsa.h"
|
||||||
#include "mbedtls/ecdsa.h"
|
#include "mbedtls/ecdsa.h"
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
@@ -27,16 +26,17 @@
|
|||||||
#include "oid.h"
|
#include "oid.h"
|
||||||
#include "mbedtls/md.h"
|
#include "mbedtls/md.h"
|
||||||
#include "files.h"
|
#include "files.h"
|
||||||
|
#include "mbedtls/eddsa.h"
|
||||||
|
|
||||||
extern const uint8_t *dev_name;
|
extern const uint8_t *dev_name;
|
||||||
extern size_t dev_name_len;
|
extern uint16_t dev_name_len;
|
||||||
|
|
||||||
size_t asn1_cvc_public_key_rsa(mbedtls_rsa_context *rsa, uint8_t *buf, size_t buf_len) {
|
uint16_t asn1_cvc_public_key_rsa(mbedtls_rsa_context *rsa, uint8_t *buf, uint16_t buf_len) {
|
||||||
const uint8_t oid_rsa[] = { 0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x02, 0x01, 0x02 };
|
const uint8_t oid_rsa[] = { 0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x02, 0x01, 0x02 };
|
||||||
size_t n_size = mbedtls_mpi_size(&rsa->N), e_size = mbedtls_mpi_size(&rsa->E);
|
uint16_t n_size = (uint16_t)mbedtls_mpi_size(&rsa->N), e_size = (uint16_t)mbedtls_mpi_size(&rsa->E);
|
||||||
size_t ntot_size = asn1_len_tag(0x81, n_size), etot_size = asn1_len_tag(0x82, e_size);
|
uint16_t ntot_size = asn1_len_tag(0x81, n_size), etot_size = asn1_len_tag(0x82, e_size);
|
||||||
size_t oid_len = asn1_len_tag(0x6, sizeof(oid_rsa));
|
uint16_t oid_len = asn1_len_tag(0x6, sizeof(oid_rsa));
|
||||||
size_t tot_len = asn1_len_tag(0x7f49, oid_len + ntot_size + etot_size);
|
uint16_t tot_len = asn1_len_tag(0x7f49, oid_len + ntot_size + etot_size);
|
||||||
if (buf == NULL || buf_len == 0) {
|
if (buf == NULL || buf_len == 0) {
|
||||||
return tot_len;
|
return tot_len;
|
||||||
}
|
}
|
||||||
@@ -72,33 +72,32 @@ const uint8_t *pointA[] = {
|
|||||||
"\x01\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC",
|
"\x01\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC",
|
||||||
};
|
};
|
||||||
|
|
||||||
size_t asn1_cvc_public_key_ecdsa(mbedtls_ecdsa_context *ecdsa, uint8_t *buf, size_t buf_len) {
|
uint16_t asn1_cvc_public_key_ecdsa(mbedtls_ecp_keypair *ecdsa, uint8_t *buf, uint16_t buf_len) {
|
||||||
uint8_t Y_buf[MBEDTLS_ECP_MAX_PT_LEN];
|
uint8_t Y_buf[MBEDTLS_ECP_MAX_PT_LEN], G_buf[MBEDTLS_ECP_MAX_PT_LEN];
|
||||||
const uint8_t oid_ecdsa[] = { 0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x02, 0x02, 0x03 };
|
const uint8_t oid_ecdsa[] = { 0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x02, 0x02, 0x03 };
|
||||||
|
const uint8_t oid_ri[] = { 0x04, 0x00, 0x7F, 0x00, 0x07, 0x02, 0x02, 0x05, 0x02, 0x03 };
|
||||||
|
const uint8_t *oid = oid_ecdsa;
|
||||||
size_t p_size = mbedtls_mpi_size(&ecdsa->grp.P), a_size = mbedtls_mpi_size(&ecdsa->grp.A);
|
size_t p_size = mbedtls_mpi_size(&ecdsa->grp.P), a_size = mbedtls_mpi_size(&ecdsa->grp.A);
|
||||||
size_t b_size = mbedtls_mpi_size(&ecdsa->grp.B),
|
size_t b_size = mbedtls_mpi_size(&ecdsa->grp.B), g_size = 0;
|
||||||
g_size = 1 + mbedtls_mpi_size(&ecdsa->grp.G.X) + mbedtls_mpi_size(&ecdsa->grp.G.X);
|
|
||||||
size_t o_size = mbedtls_mpi_size(&ecdsa->grp.N), y_size = 0;
|
size_t o_size = mbedtls_mpi_size(&ecdsa->grp.N), y_size = 0;
|
||||||
mbedtls_ecp_point_write_binary(&ecdsa->grp,
|
mbedtls_ecp_point_write_binary(&ecdsa->grp, &ecdsa->grp.G, MBEDTLS_ECP_PF_UNCOMPRESSED, &g_size, G_buf, sizeof(G_buf));
|
||||||
&ecdsa->Q,
|
mbedtls_ecp_point_write_binary(&ecdsa->grp, &ecdsa->Q, MBEDTLS_ECP_PF_UNCOMPRESSED, &y_size, Y_buf, sizeof(Y_buf));
|
||||||
MBEDTLS_ECP_PF_UNCOMPRESSED,
|
uint16_t c_size = 1;
|
||||||
&y_size,
|
uint16_t ptot_size = asn1_len_tag(0x81, (uint16_t)p_size), atot_size = asn1_len_tag(0x82, a_size ? (uint16_t)a_size : (pointA[ecdsa->grp.id] && ecdsa->grp.id < 6 ? (uint16_t)p_size : 1));
|
||||||
Y_buf,
|
uint16_t btot_size = asn1_len_tag(0x83, (uint16_t)b_size), gtot_size = asn1_len_tag(0x84, (uint16_t)g_size);
|
||||||
sizeof(Y_buf));
|
uint16_t otot_size = asn1_len_tag(0x85, (uint16_t)o_size), ytot_size = asn1_len_tag(0x86, (uint16_t)y_size);
|
||||||
size_t c_size = 1;
|
uint16_t ctot_size = asn1_len_tag(0x87, (uint16_t)c_size);
|
||||||
size_t ptot_size = asn1_len_tag(0x81, p_size), atot_size = asn1_len_tag(0x82,
|
uint16_t oid_len = asn1_len_tag(0x6, sizeof(oid_ecdsa));
|
||||||
a_size ? a_size : (
|
uint16_t tot_len = 0, tot_data_len = 0;
|
||||||
pointA[ecdsa->grp.id
|
if (mbedtls_ecp_get_type(&ecdsa->grp) == MBEDTLS_ECP_TYPE_MONTGOMERY || mbedtls_ecp_get_type(&ecdsa->grp) == MBEDTLS_ECP_TYPE_EDWARDS) {
|
||||||
] &&
|
tot_data_len = oid_len + ptot_size + otot_size + gtot_size + ytot_size;
|
||||||
ecdsa->grp.id <
|
oid = oid_ri;
|
||||||
6 ? p_size : 1));
|
}
|
||||||
size_t btot_size = asn1_len_tag(0x83, b_size), gtot_size = asn1_len_tag(0x84, g_size);
|
else {
|
||||||
size_t otot_size = asn1_len_tag(0x85, o_size), ytot_size = asn1_len_tag(0x86, y_size);
|
tot_data_len = oid_len + ptot_size + atot_size + btot_size + gtot_size + otot_size + ytot_size +
|
||||||
size_t ctot_size = asn1_len_tag(0x87, c_size);
|
ctot_size;
|
||||||
size_t oid_len = asn1_len_tag(0x6, sizeof(oid_ecdsa));
|
}
|
||||||
size_t tot_len = asn1_len_tag(0x7f49,
|
tot_len = asn1_len_tag(0x7f49, tot_data_len);
|
||||||
oid_len + ptot_size + atot_size + btot_size + gtot_size + otot_size + ytot_size +
|
|
||||||
ctot_size);
|
|
||||||
if (buf == NULL || buf_len == 0) {
|
if (buf == NULL || buf_len == 0) {
|
||||||
return tot_len;
|
return tot_len;
|
||||||
}
|
}
|
||||||
@@ -107,97 +106,103 @@ size_t asn1_cvc_public_key_ecdsa(mbedtls_ecdsa_context *ecdsa, uint8_t *buf, siz
|
|||||||
}
|
}
|
||||||
uint8_t *p = buf;
|
uint8_t *p = buf;
|
||||||
memcpy(p, "\x7F\x49", 2); p += 2;
|
memcpy(p, "\x7F\x49", 2); p += 2;
|
||||||
p += format_tlv_len(
|
p += format_tlv_len(tot_data_len, p);
|
||||||
oid_len + ptot_size + atot_size + btot_size + gtot_size + otot_size + ytot_size + ctot_size,
|
|
||||||
p);
|
|
||||||
//oid
|
//oid
|
||||||
*p++ = 0x6; p += format_tlv_len(sizeof(oid_ecdsa), p); memcpy(p, oid_ecdsa, sizeof(oid_ecdsa));
|
*p++ = 0x6; p += format_tlv_len(sizeof(oid_ecdsa), p); memcpy(p, oid, sizeof(oid_ecdsa));
|
||||||
p += sizeof(oid_ecdsa);
|
p += sizeof(oid_ecdsa);
|
||||||
//p
|
if (mbedtls_ecp_get_type(&ecdsa->grp) == MBEDTLS_ECP_TYPE_MONTGOMERY || mbedtls_ecp_get_type(&ecdsa->grp) == MBEDTLS_ECP_TYPE_EDWARDS) {
|
||||||
*p++ = 0x81; p += format_tlv_len(p_size, p); mbedtls_mpi_write_binary(&ecdsa->grp.P, p, p_size);
|
//p
|
||||||
p += p_size;
|
*p++ = 0x81; p += format_tlv_len((uint16_t)p_size, p); mbedtls_mpi_write_binary(&ecdsa->grp.P, p, p_size);
|
||||||
//A
|
p += p_size;
|
||||||
if (a_size) {
|
//order
|
||||||
*p++ = 0x82; p += format_tlv_len(a_size, p); mbedtls_mpi_write_binary(&ecdsa->grp.A,
|
*p++ = 0x82; p += format_tlv_len((uint16_t)o_size, p); mbedtls_mpi_write_binary(&ecdsa->grp.N, p, o_size);
|
||||||
p,
|
p += o_size;
|
||||||
a_size); p += a_size;
|
//G
|
||||||
}
|
*p++ = 0x83; p += format_tlv_len((uint16_t)g_size, p); memcpy(p, G_buf, g_size); p += g_size;
|
||||||
else { //mbedtls does not set point A for some curves
|
//Y
|
||||||
if (pointA[ecdsa->grp.id] && ecdsa->grp.id < 6) {
|
*p++ = 0x84; p += format_tlv_len((uint16_t)y_size, p); memcpy(p, Y_buf, y_size); p += y_size;
|
||||||
*p++ = 0x82; p += format_tlv_len(p_size, p); memcpy(p, pointA[ecdsa->grp.id], p_size);
|
|
||||||
p += p_size;
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
*p++ = 0x82; p += format_tlv_len(1, p);
|
|
||||||
*p++ = 0x0;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
//B
|
|
||||||
*p++ = 0x83; p += format_tlv_len(b_size, p); mbedtls_mpi_write_binary(&ecdsa->grp.B, p, b_size);
|
|
||||||
p += b_size;
|
|
||||||
//G
|
|
||||||
size_t g_new_size = 0;
|
|
||||||
*p++ = 0x84; p += format_tlv_len(g_size, p); mbedtls_ecp_point_write_binary(&ecdsa->grp,
|
|
||||||
&ecdsa->grp.G,
|
|
||||||
MBEDTLS_ECP_PF_UNCOMPRESSED,
|
|
||||||
&g_new_size,
|
|
||||||
p,
|
|
||||||
g_size);
|
|
||||||
p += g_size;
|
|
||||||
//order
|
|
||||||
*p++ = 0x85; p += format_tlv_len(o_size, p); mbedtls_mpi_write_binary(&ecdsa->grp.N, p, o_size);
|
|
||||||
p += o_size;
|
|
||||||
//Y
|
|
||||||
*p++ = 0x86; p += format_tlv_len(y_size, p); memcpy(p, Y_buf, y_size); p += y_size;
|
|
||||||
//cofactor
|
|
||||||
*p++ = 0x87; p += format_tlv_len(c_size, p);
|
|
||||||
if (ecdsa->grp.id == MBEDTLS_ECP_DP_CURVE448) {
|
|
||||||
*p++ = 4;
|
|
||||||
}
|
|
||||||
else if (ecdsa->grp.id == MBEDTLS_ECP_DP_CURVE25519) {
|
|
||||||
*p++ = 8;
|
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
|
//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;
|
||||||
|
//A
|
||||||
|
if (a_size) {
|
||||||
|
*p++ = 0x82; p += format_tlv_len((uint16_t)a_size, p); mbedtls_mpi_write_binary(&ecdsa->grp.A, p, a_size); p += a_size;
|
||||||
|
}
|
||||||
|
else { //mbedtls does not set point A for some curves
|
||||||
|
if (pointA[ecdsa->grp.id] && ecdsa->grp.id < 6) {
|
||||||
|
*p++ = 0x82; p += format_tlv_len((uint16_t)p_size, p); memcpy(p, pointA[ecdsa->grp.id], p_size);
|
||||||
|
p += p_size;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
*p++ = 0x82; p += format_tlv_len(1, p);
|
||||||
|
*p++ = 0x0;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//B
|
||||||
|
*p++ = 0x83; p += format_tlv_len((uint16_t)b_size, p); mbedtls_mpi_write_binary(&ecdsa->grp.B, p, b_size);
|
||||||
|
p += b_size;
|
||||||
|
//G
|
||||||
|
*p++ = 0x84; p += format_tlv_len((uint16_t)g_size, p); memcpy(p, G_buf, g_size); p += g_size;
|
||||||
|
//order
|
||||||
|
*p++ = 0x85; p += format_tlv_len((uint16_t)o_size, p); mbedtls_mpi_write_binary(&ecdsa->grp.N, p, o_size);
|
||||||
|
p += o_size;
|
||||||
|
//Y
|
||||||
|
*p++ = 0x86; p += format_tlv_len((uint16_t)y_size, p); memcpy(p, Y_buf, y_size); p += y_size;
|
||||||
|
//cofactor
|
||||||
|
*p++ = 0x87; p += format_tlv_len(c_size, p);
|
||||||
*p++ = 1;
|
*p++ = 1;
|
||||||
}
|
}
|
||||||
return tot_len;
|
return tot_len;
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t asn1_cvc_cert_body(void *rsa_ecdsa,
|
uint16_t asn1_cvc_cert_body(void *rsa_ecdsa,
|
||||||
uint8_t key_type,
|
uint8_t key_type,
|
||||||
uint8_t *buf,
|
uint8_t *buf,
|
||||||
size_t buf_len,
|
uint16_t buf_len,
|
||||||
const uint8_t *ext,
|
const uint8_t *ext,
|
||||||
size_t ext_len) {
|
uint16_t ext_len,
|
||||||
size_t pubkey_size = 0;
|
bool full) {
|
||||||
if (key_type == HSM_KEY_RSA) {
|
uint16_t pubkey_size = 0;
|
||||||
|
if (key_type & PICO_KEYS_KEY_RSA) {
|
||||||
pubkey_size = asn1_cvc_public_key_rsa(rsa_ecdsa, NULL, 0);
|
pubkey_size = asn1_cvc_public_key_rsa(rsa_ecdsa, NULL, 0);
|
||||||
}
|
}
|
||||||
else if (key_type == HSM_KEY_EC) {
|
else if (key_type & PICO_KEYS_KEY_EC) {
|
||||||
pubkey_size = asn1_cvc_public_key_ecdsa(rsa_ecdsa, NULL, 0);
|
pubkey_size = asn1_cvc_public_key_ecdsa(rsa_ecdsa, NULL, 0);
|
||||||
}
|
}
|
||||||
size_t cpi_size = 4;
|
uint16_t cpi_size = 4, ext_size = 0, role_size = 0, valid_size = 0;
|
||||||
size_t ext_size = 0;
|
|
||||||
if (ext && ext_len > 0) {
|
if (ext && ext_len > 0) {
|
||||||
ext_size = asn1_len_tag(0x65, ext_len);
|
ext_size = asn1_len_tag(0x65, ext_len);
|
||||||
}
|
}
|
||||||
|
const uint8_t *role = (const uint8_t *)"\x06\x09\x04\x00\x7F\x00\x07\x03\x01\x02\x02\x53\x01\x00";
|
||||||
uint8_t *car = NULL, *chr = NULL;
|
uint16_t rolelen = 14;
|
||||||
size_t lencar = 0, lenchr = 0;
|
if (full) {
|
||||||
|
role_size = asn1_len_tag(0x7f4c, rolelen);
|
||||||
if (asn1_find_tag(apdu.data, apdu.nc, 0x42, &lencar,
|
valid_size = asn1_len_tag(0x5f24, 6) + asn1_len_tag(0x5f25, 6);
|
||||||
&car) == false || lencar == 0 || car == NULL) {
|
|
||||||
car = (uint8_t *) dev_name;
|
|
||||||
lencar = dev_name_len;
|
|
||||||
}
|
}
|
||||||
if (asn1_find_tag(apdu.data, apdu.nc, 0x5f20, &lenchr,
|
|
||||||
&chr) == false || lenchr == 0 || chr == NULL) {
|
|
||||||
chr = (uint8_t *) dev_name;
|
|
||||||
lenchr = dev_name_len;
|
|
||||||
}
|
|
||||||
size_t car_size = asn1_len_tag(0x42, lencar), chr_size = asn1_len_tag(0x5f20, lenchr);
|
|
||||||
|
|
||||||
size_t tot_len = asn1_len_tag(0x7f4e, cpi_size + car_size + pubkey_size + chr_size + ext_size);
|
asn1_ctx_t ctxi, car = {0}, chr = {0};
|
||||||
|
asn1_ctx_init(apdu.data, (uint16_t)apdu.nc, &ctxi);
|
||||||
|
if (asn1_find_tag(&ctxi, 0x42, &car) == false || asn1_len(&car) == 0) {
|
||||||
|
car.data = (uint8_t *) dev_name;
|
||||||
|
car.len = dev_name_len;
|
||||||
|
if (dev_name == NULL) {
|
||||||
|
car.data = (uint8_t *)"ESPICOHSMTR00001";
|
||||||
|
car.len = (uint16_t)strlen((const char *)car.data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (asn1_find_tag(&ctxi, 0x5f20, &chr) == false || asn1_len(&chr) == 0) {
|
||||||
|
chr.data = (uint8_t *) dev_name;
|
||||||
|
chr.len = dev_name_len;
|
||||||
|
if (chr.data == NULL) {
|
||||||
|
chr.data = car.data;
|
||||||
|
chr.len = car.len;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
uint16_t car_size = asn1_len_tag(0x42, car.len), chr_size = asn1_len_tag(0x5f20, chr.len);
|
||||||
|
|
||||||
|
uint16_t tot_len = asn1_len_tag(0x7f4e, cpi_size + car_size + pubkey_size + chr_size + ext_size + role_size + valid_size);
|
||||||
|
|
||||||
if (buf_len == 0 || buf == NULL) {
|
if (buf_len == 0 || buf == NULL) {
|
||||||
return tot_len;
|
return tot_len;
|
||||||
@@ -207,20 +212,39 @@ size_t asn1_cvc_cert_body(void *rsa_ecdsa,
|
|||||||
}
|
}
|
||||||
uint8_t *p = buf;
|
uint8_t *p = buf;
|
||||||
memcpy(p, "\x7F\x4E", 2); p += 2;
|
memcpy(p, "\x7F\x4E", 2); p += 2;
|
||||||
p += format_tlv_len(cpi_size + car_size + pubkey_size + chr_size + ext_size, p);
|
p += format_tlv_len(cpi_size + car_size + pubkey_size + chr_size + role_size + valid_size + ext_size, p);
|
||||||
//cpi
|
//cpi
|
||||||
*p++ = 0x5f; *p++ = 0x29; *p++ = 1; *p++ = 0;
|
*p++ = 0x5f; *p++ = 0x29; *p++ = 1; *p++ = 0;
|
||||||
//car
|
//car
|
||||||
*p++ = 0x42; p += format_tlv_len(lencar, p); memcpy(p, car, lencar); p += lencar;
|
*p++ = 0x42; p += format_tlv_len(car.len, p); memcpy(p, car.data, car.len); p += car.len;
|
||||||
//pubkey
|
//pubkey
|
||||||
if (key_type == HSM_KEY_RSA) {
|
if (key_type & PICO_KEYS_KEY_RSA) {
|
||||||
p += asn1_cvc_public_key_rsa(rsa_ecdsa, p, pubkey_size);
|
p += asn1_cvc_public_key_rsa(rsa_ecdsa, p, pubkey_size);
|
||||||
}
|
}
|
||||||
else if (key_type == HSM_KEY_EC) {
|
else if (key_type & PICO_KEYS_KEY_EC) {
|
||||||
p += asn1_cvc_public_key_ecdsa(rsa_ecdsa, p, pubkey_size);
|
p += asn1_cvc_public_key_ecdsa(rsa_ecdsa, p, pubkey_size);
|
||||||
}
|
}
|
||||||
//chr
|
//chr
|
||||||
*p++ = 0x5f; *p++ = 0x20; p += format_tlv_len(lenchr, p); memcpy(p, chr, lenchr); p += lenchr;
|
*p++ = 0x5f; *p++ = 0x20; p += format_tlv_len(chr.len, p); memcpy(p, chr.data, chr.len); p += chr.len;
|
||||||
|
if (full) {
|
||||||
|
*p++ = 0x7f;
|
||||||
|
*p++ = 0x4c;
|
||||||
|
p += format_tlv_len(rolelen, p);
|
||||||
|
memcpy(p, role, rolelen);
|
||||||
|
p += rolelen;
|
||||||
|
|
||||||
|
*p++ = 0x5f;
|
||||||
|
*p++ = 0x25;
|
||||||
|
p += format_tlv_len(6, p);
|
||||||
|
memcpy(p, "\x02\x03\x00\x03\x02\x01", 6);
|
||||||
|
p += 6;
|
||||||
|
|
||||||
|
*p++ = 0x5f;
|
||||||
|
*p++ = 0x24;
|
||||||
|
p += format_tlv_len(6, p);
|
||||||
|
memcpy(p, "\x07\x00\x01\x02\x03\x01", 6);
|
||||||
|
p += 6;
|
||||||
|
}
|
||||||
if (ext && ext_len > 0) {
|
if (ext && ext_len > 0) {
|
||||||
*p++ = 0x65;
|
*p++ = 0x65;
|
||||||
p += format_tlv_len(ext_len, p);
|
p += format_tlv_len(ext_len, p);
|
||||||
@@ -230,25 +254,22 @@ size_t asn1_cvc_cert_body(void *rsa_ecdsa,
|
|||||||
return tot_len;
|
return tot_len;
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t asn1_cvc_cert(void *rsa_ecdsa,
|
uint16_t asn1_cvc_cert(void *rsa_ecdsa,
|
||||||
uint8_t key_type,
|
uint8_t key_type,
|
||||||
uint8_t *buf,
|
uint8_t *buf,
|
||||||
size_t buf_len,
|
uint16_t buf_len,
|
||||||
const uint8_t *ext,
|
const uint8_t *ext,
|
||||||
size_t ext_len) {
|
uint16_t ext_len,
|
||||||
size_t key_size = 0;
|
bool full) {
|
||||||
if (key_type == HSM_KEY_RSA) {
|
uint16_t key_size = 0;
|
||||||
key_size = mbedtls_mpi_size(&((mbedtls_rsa_context *) rsa_ecdsa)->N);
|
if (key_type & PICO_KEYS_KEY_RSA) {
|
||||||
|
key_size = (uint16_t)mbedtls_mpi_size(&((mbedtls_rsa_context *) rsa_ecdsa)->N);
|
||||||
}
|
}
|
||||||
else if (key_type == HSM_KEY_EC) {
|
else if (key_type & PICO_KEYS_KEY_EC) {
|
||||||
key_size = 2 *
|
key_size = 2 * (int)((mbedtls_ecp_curve_info_from_grp_id(((mbedtls_ecdsa_context *) rsa_ecdsa)->grp.id)->bit_size + 7) / 8);
|
||||||
(int) ((mbedtls_ecp_curve_info_from_grp_id(((mbedtls_ecdsa_context *) rsa_ecdsa)
|
|
||||||
->grp.id)->
|
|
||||||
bit_size + 7) / 8);
|
|
||||||
}
|
}
|
||||||
size_t body_size = asn1_cvc_cert_body(rsa_ecdsa, key_type, NULL, 0, ext, ext_len),
|
uint16_t body_size = asn1_cvc_cert_body(rsa_ecdsa, key_type, NULL, 0, ext, ext_len, full), sig_size = asn1_len_tag(0x5f37, key_size);
|
||||||
sig_size = asn1_len_tag(0x5f37, key_size);
|
uint16_t tot_len = asn1_len_tag(0x7f21, body_size + sig_size);
|
||||||
size_t tot_len = asn1_len_tag(0x7f21, body_size + sig_size);
|
|
||||||
if (buf_len == 0 || buf == NULL) {
|
if (buf_len == 0 || buf == NULL) {
|
||||||
return tot_len;
|
return tot_len;
|
||||||
}
|
}
|
||||||
@@ -259,26 +280,29 @@ size_t asn1_cvc_cert(void *rsa_ecdsa,
|
|||||||
memcpy(p, "\x7F\x21", 2); p += 2;
|
memcpy(p, "\x7F\x21", 2); p += 2;
|
||||||
p += format_tlv_len(body_size + sig_size, p);
|
p += format_tlv_len(body_size + sig_size, p);
|
||||||
body = p;
|
body = p;
|
||||||
p += asn1_cvc_cert_body(rsa_ecdsa, key_type, p, body_size, ext, ext_len);
|
p += asn1_cvc_cert_body(rsa_ecdsa, key_type, p, body_size, ext, ext_len, full);
|
||||||
uint8_t hsh[32];
|
uint8_t hsh[32];
|
||||||
hash256(body, body_size, hsh);
|
hash256(body, body_size, hsh);
|
||||||
memcpy(p, "\x5F\x37", 2); p += 2;
|
memcpy(p, "\x5F\x37", 2); p += 2;
|
||||||
p += format_tlv_len(key_size, p);
|
p += format_tlv_len(key_size, p);
|
||||||
if (key_type == HSM_KEY_RSA) {
|
if (key_type & PICO_KEYS_KEY_RSA) {
|
||||||
if (mbedtls_rsa_rsassa_pkcs1_v15_sign(rsa_ecdsa, random_gen, NULL, MBEDTLS_MD_SHA256, 32,
|
if (mbedtls_rsa_rsassa_pkcs1_v15_sign(rsa_ecdsa, random_gen, NULL, MBEDTLS_MD_SHA256, 32, hsh, p) != 0) {
|
||||||
hsh, p) != 0) {
|
|
||||||
memset(p, 0, key_size);
|
memset(p, 0, key_size);
|
||||||
}
|
}
|
||||||
p += key_size;
|
p += key_size;
|
||||||
}
|
}
|
||||||
else if (key_type == HSM_KEY_EC) {
|
else if (key_type & PICO_KEYS_KEY_EC) {
|
||||||
mbedtls_mpi r, s;
|
mbedtls_mpi r, s;
|
||||||
int ret = 0;
|
int ret = 0;
|
||||||
mbedtls_ecdsa_context *ecdsa = (mbedtls_ecdsa_context *) rsa_ecdsa;
|
mbedtls_ecp_keypair *ecdsa = (mbedtls_ecp_keypair *) rsa_ecdsa;
|
||||||
mbedtls_mpi_init(&r);
|
mbedtls_mpi_init(&r);
|
||||||
mbedtls_mpi_init(&s);
|
mbedtls_mpi_init(&s);
|
||||||
ret =
|
if (ecdsa->grp.id == MBEDTLS_ECP_DP_ED25519 || ecdsa->grp.id == MBEDTLS_ECP_DP_ED448) {
|
||||||
mbedtls_ecdsa_sign(&ecdsa->grp, &r, &s, &ecdsa->d, hsh, sizeof(hsh), random_gen, NULL);
|
ret = mbedtls_eddsa_sign(&ecdsa->grp, &r, &s, &ecdsa->d, body, body_size, MBEDTLS_EDDSA_PURE, NULL, 0, random_gen, NULL);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
ret = mbedtls_ecdsa_sign(&ecdsa->grp, &r, &s, &ecdsa->d, hsh, sizeof(hsh), random_gen, NULL);
|
||||||
|
}
|
||||||
if (ret == 0) {
|
if (ret == 0) {
|
||||||
mbedtls_mpi_write_binary(&r, p, key_size / 2); p += key_size / 2;
|
mbedtls_mpi_write_binary(&r, p, key_size / 2); p += key_size / 2;
|
||||||
mbedtls_mpi_write_binary(&s, p, key_size / 2); p += key_size / 2;
|
mbedtls_mpi_write_binary(&s, p, key_size / 2); p += key_size / 2;
|
||||||
@@ -290,33 +314,32 @@ size_t asn1_cvc_cert(void *rsa_ecdsa,
|
|||||||
mbedtls_mpi_free(&r);
|
mbedtls_mpi_free(&r);
|
||||||
mbedtls_mpi_free(&s);
|
mbedtls_mpi_free(&s);
|
||||||
}
|
}
|
||||||
return p - buf;
|
return (uint16_t)(p - buf);
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t asn1_cvc_aut(void *rsa_ecdsa,
|
uint16_t asn1_cvc_aut(void *rsa_ecdsa,
|
||||||
uint8_t key_type,
|
uint8_t key_type,
|
||||||
uint8_t *buf,
|
uint8_t *buf,
|
||||||
size_t buf_len,
|
uint16_t buf_len,
|
||||||
const uint8_t *ext,
|
const uint8_t *ext,
|
||||||
size_t ext_len) {
|
uint16_t ext_len) {
|
||||||
size_t cvcert_size = asn1_cvc_cert(rsa_ecdsa, key_type, NULL, 0, ext, ext_len);
|
uint16_t cvcert_size = asn1_cvc_cert(rsa_ecdsa, key_type, NULL, 0, ext, ext_len, false);
|
||||||
size_t outcar_len = dev_name_len;
|
uint16_t outcar_len = dev_name_len;
|
||||||
const uint8_t *outcar = dev_name;
|
const uint8_t *outcar = dev_name;
|
||||||
size_t outcar_size = asn1_len_tag(0x42, outcar_len);
|
uint16_t outcar_size = asn1_len_tag(0x42, outcar_len);
|
||||||
file_t *fkey = search_by_fid(EF_KEY_DEV, NULL, SPECIFY_EF);
|
file_t *fkey = search_file(EF_KEY_DEV);
|
||||||
if (!fkey) {
|
if (!fkey) {
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
mbedtls_ecdsa_context ectx;
|
mbedtls_ecp_keypair ectx;
|
||||||
mbedtls_ecdsa_init(&ectx);
|
mbedtls_ecp_keypair_init(&ectx);
|
||||||
if (load_private_key_ecdsa(&ectx, fkey) != CCID_OK) {
|
if (load_private_key_ec(&ectx, fkey) != CCID_OK) {
|
||||||
mbedtls_ecdsa_free(&ectx);
|
mbedtls_ecp_keypair_free(&ectx);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
int ret = 0, key_size = 2 * mbedtls_mpi_size(&ectx.d);
|
int ret = 0;
|
||||||
size_t outsig_size = asn1_len_tag(0x5f37, key_size), tot_len = asn1_len_tag(0x67,
|
uint16_t key_size = 2 * (uint16_t)mbedtls_mpi_size(&ectx.d);
|
||||||
cvcert_size + outcar_size +
|
uint16_t outsig_size = asn1_len_tag(0x5f37, key_size), tot_len = asn1_len_tag(0x67, cvcert_size + outcar_size + outsig_size);
|
||||||
outsig_size);
|
|
||||||
if (buf_len == 0 || buf == NULL) {
|
if (buf_len == 0 || buf == NULL) {
|
||||||
return tot_len;
|
return tot_len;
|
||||||
}
|
}
|
||||||
@@ -328,45 +351,50 @@ size_t asn1_cvc_aut(void *rsa_ecdsa,
|
|||||||
p += format_tlv_len(cvcert_size + outcar_size + outsig_size, p);
|
p += format_tlv_len(cvcert_size + outcar_size + outsig_size, p);
|
||||||
uint8_t *body = p;
|
uint8_t *body = p;
|
||||||
//cvcert
|
//cvcert
|
||||||
p += asn1_cvc_cert(rsa_ecdsa, key_type, p, cvcert_size, ext, ext_len);
|
p += asn1_cvc_cert(rsa_ecdsa, key_type, p, cvcert_size, ext, ext_len, false);
|
||||||
//outcar
|
//outcar
|
||||||
*p++ = 0x42; p += format_tlv_len(outcar_len, p); memcpy(p, outcar, outcar_len); p += outcar_len;
|
*p++ = 0x42; p += format_tlv_len(outcar_len, p); memcpy(p, outcar, outcar_len); p += outcar_len;
|
||||||
uint8_t hsh[32];
|
|
||||||
memcpy(p, "\x5f\x37", 2); p += 2;
|
memcpy(p, "\x5f\x37", 2); p += 2;
|
||||||
p += format_tlv_len(key_size, p);
|
p += format_tlv_len(key_size, p);
|
||||||
hash256(body, cvcert_size + outcar_size, hsh);
|
|
||||||
mbedtls_mpi r, s;
|
mbedtls_mpi r, s;
|
||||||
mbedtls_mpi_init(&r);
|
mbedtls_mpi_init(&r);
|
||||||
mbedtls_mpi_init(&s);
|
mbedtls_mpi_init(&s);
|
||||||
ret = mbedtls_ecdsa_sign(&ectx.grp, &r, &s, &ectx.d, hsh, sizeof(hsh), random_gen, NULL);
|
if (ectx.grp.id == MBEDTLS_ECP_DP_ED25519 || ectx.grp.id == MBEDTLS_ECP_DP_ED448) {
|
||||||
mbedtls_ecdsa_free(&ectx);
|
ret = mbedtls_eddsa_sign(&ectx.grp, &r, &s, &ectx.d, body, cvcert_size + outcar_size, MBEDTLS_EDDSA_PURE, NULL, 0, random_gen, NULL);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
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);
|
||||||
|
}
|
||||||
|
mbedtls_ecp_keypair_free(&ectx);
|
||||||
if (ret != 0) {
|
if (ret != 0) {
|
||||||
mbedtls_mpi_free(&r);
|
mbedtls_mpi_free(&r);
|
||||||
mbedtls_mpi_free(&s);
|
mbedtls_mpi_free(&s);
|
||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
mbedtls_mpi_write_binary(&r, p, mbedtls_mpi_size(&r)); p += mbedtls_mpi_size(&r);
|
mbedtls_mpi_write_binary(&r, p, key_size / 2); p += key_size / 2;
|
||||||
mbedtls_mpi_write_binary(&s, p, mbedtls_mpi_size(&s)); p += mbedtls_mpi_size(&s);
|
mbedtls_mpi_write_binary(&s, p, key_size / 2); p += key_size / 2;
|
||||||
mbedtls_mpi_free(&r);
|
mbedtls_mpi_free(&r);
|
||||||
mbedtls_mpi_free(&s);
|
mbedtls_mpi_free(&s);
|
||||||
return p - buf;
|
return (uint16_t)(p - buf);
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t asn1_build_cert_description(const uint8_t *label,
|
uint16_t asn1_build_cert_description(const uint8_t *label,
|
||||||
size_t label_len,
|
uint16_t label_len,
|
||||||
const uint8_t *puk,
|
const uint8_t *puk,
|
||||||
size_t puk_len,
|
uint16_t puk_len,
|
||||||
uint16_t fid,
|
uint16_t fid,
|
||||||
uint8_t *buf,
|
uint8_t *buf,
|
||||||
size_t buf_len) {
|
uint16_t buf_len) {
|
||||||
size_t opt_len = 2;
|
uint16_t opt_len = 2;
|
||||||
size_t seq1_size =
|
uint16_t seq1_size =
|
||||||
asn1_len_tag(0x30, asn1_len_tag(0xC, label_len) + asn1_len_tag(0x3, opt_len));
|
asn1_len_tag(0x30, asn1_len_tag(0xC, label_len) + asn1_len_tag(0x3, opt_len));
|
||||||
size_t seq2_size = asn1_len_tag(0x30, asn1_len_tag(0x4, 20)); /* SHA1 is 20 bytes length */
|
uint16_t seq2_size = asn1_len_tag(0x30, asn1_len_tag(0x4, 20)); /* SHA1 is 20 bytes length */
|
||||||
size_t seq3_size =
|
uint16_t seq3_size =
|
||||||
asn1_len_tag(0xA1,
|
asn1_len_tag(0xA1,
|
||||||
asn1_len_tag(0x30, asn1_len_tag(0x30, asn1_len_tag(0x4, sizeof(uint16_t)))));
|
asn1_len_tag(0x30, asn1_len_tag(0x30, asn1_len_tag(0x4, sizeof(uint16_t)))));
|
||||||
size_t tot_len = asn1_len_tag(0x30, seq1_size + seq2_size + seq3_size);
|
uint16_t tot_len = asn1_len_tag(0x30, seq1_size + seq2_size + seq3_size);
|
||||||
if (buf_len == 0 || buf == NULL) {
|
if (buf_len == 0 || buf == NULL) {
|
||||||
return tot_len;
|
return tot_len;
|
||||||
}
|
}
|
||||||
@@ -405,26 +433,47 @@ size_t asn1_build_cert_description(const uint8_t *label,
|
|||||||
p += format_tlv_len(sizeof(uint16_t), p);
|
p += format_tlv_len(sizeof(uint16_t), p);
|
||||||
*p++ = fid >> 8;
|
*p++ = fid >> 8;
|
||||||
*p++ = fid & 0xff;
|
*p++ = fid & 0xff;
|
||||||
return p - buf;
|
return (uint16_t)(p - buf);
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t asn1_build_prkd_generic(const uint8_t *label,
|
uint16_t asn1_build_prkd_generic(const uint8_t *label,
|
||||||
size_t label_len,
|
uint16_t label_len,
|
||||||
const uint8_t *keyid,
|
const uint8_t *keyid,
|
||||||
size_t keyid_len,
|
uint16_t keyid_len,
|
||||||
size_t keysize,
|
uint16_t keysize,
|
||||||
const uint8_t *seq,
|
int key_type,
|
||||||
size_t seq_len,
|
|
||||||
uint8_t *buf,
|
uint8_t *buf,
|
||||||
size_t buf_len) {
|
uint16_t buf_len) {
|
||||||
size_t seq1_size = asn1_len_tag(0x30, asn1_len_tag(0xC, label_len));
|
uint16_t seq_len = 0;
|
||||||
size_t seq2_size =
|
const uint8_t *seq = NULL;
|
||||||
|
uint8_t first_tag = 0x0;
|
||||||
|
if (key_type & PICO_KEYS_KEY_EC) {
|
||||||
|
seq = (const uint8_t *)"\x07\x20\x80";
|
||||||
|
seq_len = 3;
|
||||||
|
first_tag = 0xA0;
|
||||||
|
}
|
||||||
|
else if (key_type & PICO_KEYS_KEY_RSA) {
|
||||||
|
seq = (const uint8_t *)"\x02\x74";
|
||||||
|
seq_len = 2;
|
||||||
|
first_tag = 0x30;
|
||||||
|
}
|
||||||
|
else if (key_type & PICO_KEYS_KEY_AES) {
|
||||||
|
seq = (const uint8_t *)"\x07\xC0\x10";
|
||||||
|
seq_len = 3;
|
||||||
|
first_tag = 0xA8;
|
||||||
|
}
|
||||||
|
uint16_t seq1_size = asn1_len_tag(0x30, asn1_len_tag(0xC, label_len));
|
||||||
|
uint16_t seq2_size =
|
||||||
asn1_len_tag(0x30, asn1_len_tag(0x4, keyid_len) + asn1_len_tag(0x3, seq_len));
|
asn1_len_tag(0x30, asn1_len_tag(0x4, keyid_len) + asn1_len_tag(0x3, seq_len));
|
||||||
size_t seq3_size =
|
uint16_t seq3_size = 0, seq4_size = 0;
|
||||||
asn1_len_tag(0xA1,
|
if (key_type & PICO_KEYS_KEY_EC || key_type & PICO_KEYS_KEY_RSA) {
|
||||||
asn1_len_tag(0x30,
|
seq4_size = asn1_len_tag(0xA1, asn1_len_tag(0x30, asn1_len_tag(0x30, asn1_len_tag(0x4, 0)) + asn1_len_tag(0x2, 2)));
|
||||||
asn1_len_tag(0x30, asn1_len_tag(0x4, 0)) + asn1_len_tag(0x2, 2)));
|
}
|
||||||
size_t tot_len = asn1_len_tag(0xA0, seq1_size + seq2_size + seq3_size);
|
else if (key_type & PICO_KEYS_KEY_AES) {
|
||||||
|
seq3_size = asn1_len_tag(0xA0, asn1_len_tag(0x30, asn1_len_tag(0x2, 2)));
|
||||||
|
seq4_size = asn1_len_tag(0xA1, asn1_len_tag(0x30, asn1_len_tag(0x30, asn1_len_tag(0x4, 0))));
|
||||||
|
}
|
||||||
|
uint16_t tot_len = asn1_len_tag(first_tag, seq1_size + seq2_size + seq4_size);
|
||||||
if (buf_len == 0 || buf == NULL) {
|
if (buf_len == 0 || buf == NULL) {
|
||||||
return tot_len;
|
return tot_len;
|
||||||
}
|
}
|
||||||
@@ -432,8 +481,8 @@ size_t asn1_build_prkd_generic(const uint8_t *label,
|
|||||||
return 0;
|
return 0;
|
||||||
}
|
}
|
||||||
uint8_t *p = buf;
|
uint8_t *p = buf;
|
||||||
*p++ = 0xA0;
|
*p++ = first_tag;
|
||||||
p += format_tlv_len(seq1_size + seq2_size + seq3_size, p);
|
p += format_tlv_len(seq1_size + seq2_size + seq3_size + seq4_size, p);
|
||||||
//Seq 1
|
//Seq 1
|
||||||
*p++ = 0x30;
|
*p++ = 0x30;
|
||||||
p += format_tlv_len(asn1_len_tag(0xC, label_len), p);
|
p += format_tlv_len(asn1_len_tag(0xC, label_len), p);
|
||||||
@@ -452,73 +501,104 @@ size_t asn1_build_prkd_generic(const uint8_t *label,
|
|||||||
memcpy(p, seq, seq_len); p += seq_len;
|
memcpy(p, seq, seq_len); p += seq_len;
|
||||||
|
|
||||||
//Seq 3
|
//Seq 3
|
||||||
|
if (key_type & PICO_KEYS_KEY_AES) {
|
||||||
|
*p++ = 0xA0;
|
||||||
|
p += format_tlv_len(asn1_len_tag(0x30, asn1_len_tag(0x2, 2)), p);
|
||||||
|
*p++ = 0x30;
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
//Seq 4
|
||||||
*p++ = 0xA1;
|
*p++ = 0xA1;
|
||||||
p +=
|
uint16_t inseq4_len = asn1_len_tag(0x30, asn1_len_tag(0x4, 0));
|
||||||
format_tlv_len(asn1_len_tag(0x30,
|
if (key_type & PICO_KEYS_KEY_EC || key_type & PICO_KEYS_KEY_RSA) {
|
||||||
asn1_len_tag(0x30, asn1_len_tag(0x4, 0)) + asn1_len_tag(0x2,
|
inseq4_len += asn1_len_tag(0x2, 2);
|
||||||
2)),
|
}
|
||||||
p);
|
p += format_tlv_len(asn1_len_tag(0x30, inseq4_len), p);
|
||||||
*p++ = 0x30;
|
*p++ = 0x30;
|
||||||
p += format_tlv_len(asn1_len_tag(0x30, asn1_len_tag(0x4, 0)) + asn1_len_tag(0x2, 2), p);
|
p += format_tlv_len(inseq4_len, p);
|
||||||
*p++ = 0x30;
|
*p++ = 0x30;
|
||||||
p += format_tlv_len(asn1_len_tag(0x4, 0), p);
|
p += format_tlv_len(asn1_len_tag(0x4, 0), p);
|
||||||
*p++ = 0x4;
|
*p++ = 0x4;
|
||||||
p += format_tlv_len(0, p);
|
p += format_tlv_len(0, p);
|
||||||
*p++ = 0x2;
|
if (key_type & PICO_KEYS_KEY_EC || key_type & PICO_KEYS_KEY_RSA) {
|
||||||
p += format_tlv_len(2, p);
|
*p++ = 0x2;
|
||||||
*p++ = (keysize >> 8) & 0xff;
|
p += format_tlv_len(2, p);
|
||||||
*p++ = keysize & 0xff;
|
*p++ = (keysize >> 8) & 0xff;
|
||||||
return p - buf;
|
*p++ = keysize & 0xff;
|
||||||
|
}
|
||||||
|
return (uint16_t)(p - buf);
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t asn1_build_prkd_ecc(const uint8_t *label,
|
uint16_t asn1_build_prkd_ecc(const uint8_t *label,
|
||||||
size_t label_len,
|
uint16_t label_len,
|
||||||
const uint8_t *keyid,
|
const uint8_t *keyid,
|
||||||
size_t keyid_len,
|
uint16_t keyid_len,
|
||||||
size_t keysize,
|
uint16_t keysize,
|
||||||
uint8_t *buf,
|
uint8_t *buf,
|
||||||
size_t buf_len) {
|
uint16_t buf_len) {
|
||||||
return asn1_build_prkd_generic(label,
|
return asn1_build_prkd_generic(label,
|
||||||
label_len,
|
label_len,
|
||||||
keyid,
|
keyid,
|
||||||
keyid_len,
|
keyid_len,
|
||||||
keysize,
|
keysize,
|
||||||
(const uint8_t *) "\x07\x20\x80",
|
PICO_KEYS_KEY_EC,
|
||||||
3,
|
|
||||||
buf,
|
buf,
|
||||||
buf_len);
|
buf_len);
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t asn1_build_prkd_rsa(const uint8_t *label,
|
uint16_t asn1_build_prkd_rsa(const uint8_t *label,
|
||||||
size_t label_len,
|
uint16_t label_len,
|
||||||
const uint8_t *keyid,
|
const uint8_t *keyid,
|
||||||
size_t keyid_len,
|
uint16_t keyid_len,
|
||||||
size_t keysize,
|
uint16_t keysize,
|
||||||
uint8_t *buf,
|
uint8_t *buf,
|
||||||
size_t buf_len) {
|
uint16_t buf_len) {
|
||||||
return asn1_build_prkd_generic(label,
|
return asn1_build_prkd_generic(label,
|
||||||
label_len,
|
label_len,
|
||||||
keyid,
|
keyid,
|
||||||
keyid_len,
|
keyid_len,
|
||||||
keysize,
|
keysize,
|
||||||
(const uint8_t *) "\x02\x74",
|
PICO_KEYS_KEY_RSA,
|
||||||
2,
|
|
||||||
buf,
|
buf,
|
||||||
buf_len);
|
buf_len);
|
||||||
}
|
}
|
||||||
|
|
||||||
const uint8_t *cvc_get_field(const uint8_t *data, size_t len, size_t *olen, uint16_t tag) {
|
uint16_t asn1_build_prkd_aes(const uint8_t *label,
|
||||||
uint8_t *rdata = NULL;
|
uint16_t label_len,
|
||||||
if (data == NULL || len == 0) {
|
const uint8_t *keyid,
|
||||||
return NULL;
|
uint16_t keyid_len,
|
||||||
}
|
uint16_t keysize,
|
||||||
if (asn1_find_tag(data, len, tag, olen, &rdata) == false) {
|
uint8_t *buf,
|
||||||
return NULL;
|
uint16_t buf_len) {
|
||||||
}
|
return asn1_build_prkd_generic(label,
|
||||||
return rdata;
|
label_len,
|
||||||
|
keyid,
|
||||||
|
keyid_len,
|
||||||
|
keysize,
|
||||||
|
PICO_KEYS_KEY_AES,
|
||||||
|
buf,
|
||||||
|
buf_len);
|
||||||
}
|
}
|
||||||
|
|
||||||
const uint8_t *cvc_get_body(const uint8_t *data, size_t len, size_t *olen) {
|
const uint8_t *cvc_get_field(const uint8_t *data, uint16_t len, uint16_t *olen, uint16_t tag) {
|
||||||
|
asn1_ctx_t ctxi, ctxo = { 0 };
|
||||||
|
asn1_ctx_init((uint8_t *)data, len, &ctxi);
|
||||||
|
if (asn1_len(&ctxi) == 0) {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
if (asn1_find_tag(&ctxi, tag, &ctxo) == false) {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
*olen = ctxo.len;
|
||||||
|
return ctxo.data;
|
||||||
|
}
|
||||||
|
|
||||||
|
const uint8_t *cvc_get_body(const uint8_t *data, uint16_t len, uint16_t *olen) {
|
||||||
const uint8_t *bkdata = data;
|
const uint8_t *bkdata = data;
|
||||||
if ((data = cvc_get_field(data, len, olen, 0x67)) == NULL) { /* Check for CSR */
|
if ((data = cvc_get_field(data, len, olen, 0x67)) == NULL) { /* Check for CSR */
|
||||||
data = bkdata;
|
data = bkdata;
|
||||||
@@ -529,7 +609,7 @@ const uint8_t *cvc_get_body(const uint8_t *data, size_t len, size_t *olen) {
|
|||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
const uint8_t *cvc_get_sig(const uint8_t *data, size_t len, size_t *olen) {
|
const uint8_t *cvc_get_sig(const uint8_t *data, uint16_t len, uint16_t *olen) {
|
||||||
const uint8_t *bkdata = data;
|
const uint8_t *bkdata = data;
|
||||||
if ((data = cvc_get_field(data, len, olen, 0x67)) == NULL) { /* Check for CSR */
|
if ((data = cvc_get_field(data, len, olen, 0x67)) == NULL) { /* Check for CSR */
|
||||||
data = bkdata;
|
data = bkdata;
|
||||||
@@ -540,28 +620,28 @@ const uint8_t *cvc_get_sig(const uint8_t *data, size_t len, size_t *olen) {
|
|||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
const uint8_t *cvc_get_car(const uint8_t *data, size_t len, size_t *olen) {
|
const uint8_t *cvc_get_car(const uint8_t *data, uint16_t len, uint16_t *olen) {
|
||||||
if ((data = cvc_get_body(data, len, olen)) != NULL) {
|
if ((data = cvc_get_body(data, len, olen)) != NULL) {
|
||||||
return cvc_get_field(data, len, olen, 0x42);
|
return cvc_get_field(data, len, olen, 0x42);
|
||||||
}
|
}
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
const uint8_t *cvc_get_chr(const uint8_t *data, size_t len, size_t *olen) {
|
const uint8_t *cvc_get_chr(const uint8_t *data, uint16_t len, uint16_t *olen) {
|
||||||
if ((data = cvc_get_body(data, len, olen)) != NULL) {
|
if ((data = cvc_get_body(data, len, olen)) != NULL) {
|
||||||
return cvc_get_field(data, len, olen, 0x5F20);
|
return cvc_get_field(data, len, olen, 0x5F20);
|
||||||
}
|
}
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
const uint8_t *cvc_get_pub(const uint8_t *data, size_t len, size_t *olen) {
|
const uint8_t *cvc_get_pub(const uint8_t *data, uint16_t len, uint16_t *olen) {
|
||||||
if ((data = cvc_get_body(data, len, olen)) != NULL) {
|
if ((data = cvc_get_body(data, len, olen)) != NULL) {
|
||||||
return cvc_get_field(data, len, olen, 0x7F49);
|
return cvc_get_field(data, len, olen, 0x7F49);
|
||||||
}
|
}
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
|
|
||||||
const uint8_t *cvc_get_ext(const uint8_t *data, size_t len, size_t *olen) {
|
const uint8_t *cvc_get_ext(const uint8_t *data, uint16_t len, uint16_t *olen) {
|
||||||
if ((data = cvc_get_body(data, len, olen)) != NULL) {
|
if ((data = cvc_get_body(data, len, olen)) != NULL) {
|
||||||
return cvc_get_field(data, len, olen, 0x65);
|
return cvc_get_field(data, len, olen, 0x65);
|
||||||
}
|
}
|
||||||
@@ -571,7 +651,7 @@ const uint8_t *cvc_get_ext(const uint8_t *data, size_t len, size_t *olen) {
|
|||||||
extern PUK puk_store[MAX_PUK_STORE_ENTRIES];
|
extern PUK puk_store[MAX_PUK_STORE_ENTRIES];
|
||||||
extern int puk_store_entries;
|
extern int puk_store_entries;
|
||||||
|
|
||||||
int puk_store_index(const uint8_t *chr, size_t chr_len) {
|
int puk_store_index(const uint8_t *chr, uint16_t chr_len) {
|
||||||
for (int i = 0; i < puk_store_entries; i++) {
|
for (int i = 0; i < puk_store_entries; i++) {
|
||||||
if (memcmp(puk_store[i].chr, chr, chr_len) == 0) {
|
if (memcmp(puk_store[i].chr, chr, chr_len) == 0) {
|
||||||
return i;
|
return i;
|
||||||
@@ -580,8 +660,8 @@ int puk_store_index(const uint8_t *chr, size_t chr_len) {
|
|||||||
return -1;
|
return -1;
|
||||||
}
|
}
|
||||||
|
|
||||||
mbedtls_ecp_group_id cvc_inherite_ec_group(const uint8_t *ca, size_t ca_len) {
|
mbedtls_ecp_group_id cvc_inherite_ec_group(const uint8_t *ca, uint16_t ca_len) {
|
||||||
size_t chr_len = 0, car_len = 0;
|
uint16_t chr_len = 0, car_len = 0;
|
||||||
const uint8_t *chr = NULL, *car = NULL;
|
const uint8_t *chr = NULL, *car = NULL;
|
||||||
int eq = -1;
|
int eq = -1;
|
||||||
do {
|
do {
|
||||||
@@ -599,12 +679,12 @@ mbedtls_ecp_group_id cvc_inherite_ec_group(const uint8_t *ca, size_t ca_len) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
} while (car && chr && eq != 0);
|
} while (car && chr && eq != 0);
|
||||||
size_t ca_puk_len = 0;
|
uint16_t ca_puk_len = 0;
|
||||||
const uint8_t *ca_puk = cvc_get_pub(ca, ca_len, &ca_puk_len);
|
const uint8_t *ca_puk = cvc_get_pub(ca, ca_len, &ca_puk_len);
|
||||||
if (!ca_puk) {
|
if (!ca_puk) {
|
||||||
return MBEDTLS_ECP_DP_NONE;
|
return MBEDTLS_ECP_DP_NONE;
|
||||||
}
|
}
|
||||||
size_t t81_len = 0;
|
uint16_t t81_len = 0;
|
||||||
const uint8_t *t81 = cvc_get_field(ca_puk, ca_puk_len, &t81_len, 0x81);
|
const uint8_t *t81 = cvc_get_field(ca_puk, ca_puk_len, &t81_len, 0x81);
|
||||||
if (!t81) {
|
if (!t81) {
|
||||||
return MBEDTLS_ECP_DP_NONE;
|
return MBEDTLS_ECP_DP_NONE;
|
||||||
@@ -614,23 +694,23 @@ mbedtls_ecp_group_id cvc_inherite_ec_group(const uint8_t *ca, size_t ca_len) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int puk_verify(const uint8_t *sig,
|
int puk_verify(const uint8_t *sig,
|
||||||
size_t sig_len,
|
uint16_t sig_len,
|
||||||
const uint8_t *hash,
|
const uint8_t *hash,
|
||||||
size_t hash_len,
|
uint16_t hash_len,
|
||||||
const uint8_t *ca,
|
const uint8_t *ca,
|
||||||
size_t ca_len) {
|
uint16_t ca_len) {
|
||||||
size_t puk_len = 0;
|
uint16_t puk_len = 0;
|
||||||
const uint8_t *puk = cvc_get_pub(ca, ca_len, &puk_len);
|
const uint8_t *puk = cvc_get_pub(ca, ca_len, &puk_len);
|
||||||
if (!puk) {
|
if (!puk) {
|
||||||
return CCID_WRONG_DATA;
|
return CCID_WRONG_DATA;
|
||||||
}
|
}
|
||||||
size_t oid_len = 0;
|
uint16_t oid_len = 0;
|
||||||
const uint8_t *oid = cvc_get_field(puk, puk_len, &oid_len, 0x6);
|
const uint8_t *oid = cvc_get_field(puk, puk_len, &oid_len, 0x6);
|
||||||
if (!oid) {
|
if (!oid) {
|
||||||
return CCID_WRONG_DATA;
|
return CCID_WRONG_DATA;
|
||||||
}
|
}
|
||||||
if (memcmp(oid, OID_ID_TA_RSA, 9) == 0) { //RSA
|
if (memcmp(oid, OID_ID_TA_RSA, 9) == 0) { //RSA
|
||||||
size_t t81_len = 0, t82_len = 0;
|
uint16_t t81_len = 0, t82_len = 0;
|
||||||
const uint8_t *t81 = cvc_get_field(puk, puk_len, &t81_len, 0x81), *t82 = cvc_get_field(puk,
|
const uint8_t *t81 = cvc_get_field(puk, puk_len, &t81_len, 0x81), *t82 = cvc_get_field(puk,
|
||||||
puk_len,
|
puk_len,
|
||||||
&t81_len,
|
&t81_len,
|
||||||
@@ -686,7 +766,7 @@ int puk_verify(const uint8_t *sig,
|
|||||||
mbedtls_rsa_free(&rsa);
|
mbedtls_rsa_free(&rsa);
|
||||||
return CCID_EXEC_ERROR;
|
return CCID_EXEC_ERROR;
|
||||||
}
|
}
|
||||||
r = mbedtls_rsa_pkcs1_verify(&rsa, md, hash_len, hash, sig);
|
r = mbedtls_rsa_pkcs1_verify(&rsa, md, (unsigned int)hash_len, hash, sig);
|
||||||
mbedtls_rsa_free(&rsa);
|
mbedtls_rsa_free(&rsa);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
return CCID_WRONG_SIGNATURE;
|
return CCID_WRONG_SIGNATURE;
|
||||||
@@ -713,7 +793,7 @@ int puk_verify(const uint8_t *sig,
|
|||||||
return CCID_WRONG_DATA;
|
return CCID_WRONG_DATA;
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t t86_len = 0;
|
uint16_t t86_len = 0;
|
||||||
const uint8_t *t86 = cvc_get_field(puk, puk_len, &t86_len, 0x86);
|
const uint8_t *t86 = cvc_get_field(puk, puk_len, &t86_len, 0x86);
|
||||||
if (!t86) {
|
if (!t86) {
|
||||||
return CCID_WRONG_DATA;
|
return CCID_WRONG_DATA;
|
||||||
@@ -767,13 +847,13 @@ int puk_verify(const uint8_t *sig,
|
|||||||
return CCID_OK;
|
return CCID_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
int cvc_verify(const uint8_t *cert, size_t cert_len, const uint8_t *ca, size_t ca_len) {
|
int cvc_verify(const uint8_t *cert, uint16_t cert_len, const uint8_t *ca, uint16_t ca_len) {
|
||||||
size_t puk_len = 0;
|
uint16_t puk_len = 0;
|
||||||
const uint8_t *puk = cvc_get_pub(ca, ca_len, &puk_len);
|
const uint8_t *puk = cvc_get_pub(ca, ca_len, &puk_len);
|
||||||
if (!puk) {
|
if (!puk) {
|
||||||
return CCID_WRONG_DATA;
|
return CCID_WRONG_DATA;
|
||||||
}
|
}
|
||||||
size_t oid_len = 0, cv_body_len = 0, sig_len = 0;
|
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 *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 *cv_body = cvc_get_body(cert, cert_len, &cv_body_len);
|
||||||
const uint8_t *sig = cvc_get_sig(cert, cert_len, &sig_len);
|
const uint8_t *sig = cvc_get_sig(cert, cert_len, &sig_len);
|
||||||
|
|||||||
@@ -19,7 +19,7 @@
|
|||||||
#define _CVC_H_
|
#define _CVC_H_
|
||||||
|
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
#ifndef ENABLE_EMULATION
|
#if !defined(ENABLE_EMULATION) && !defined(ESP_PLATFORM)
|
||||||
#include "pico/stdlib.h"
|
#include "pico/stdlib.h"
|
||||||
#else
|
#else
|
||||||
#include <stdbool.h>
|
#include <stdbool.h>
|
||||||
@@ -28,62 +28,78 @@
|
|||||||
|
|
||||||
typedef struct PUK {
|
typedef struct PUK {
|
||||||
const uint8_t *puk;
|
const uint8_t *puk;
|
||||||
size_t puk_len;
|
uint16_t puk_len;
|
||||||
const uint8_t *car;
|
const uint8_t *car;
|
||||||
size_t car_len;
|
uint16_t car_len;
|
||||||
const uint8_t *chr;
|
const uint8_t *chr;
|
||||||
size_t chr_len;
|
uint16_t chr_len;
|
||||||
const uint8_t *cvcert;
|
const uint8_t *cvcert;
|
||||||
size_t cvcert_len;
|
uint16_t cvcert_len;
|
||||||
bool copied;
|
bool copied;
|
||||||
} PUK;
|
} PUK;
|
||||||
|
|
||||||
#define MAX_PUK_STORE_ENTRIES 4
|
#define MAX_PUK_STORE_ENTRIES 4
|
||||||
|
|
||||||
extern size_t asn1_cvc_cert(void *rsa_ecdsa,
|
extern uint16_t asn1_cvc_cert(void *rsa_ecdsa,
|
||||||
uint8_t key_type,
|
uint8_t key_type,
|
||||||
uint8_t *buf,
|
uint8_t *buf,
|
||||||
size_t buf_len,
|
uint16_t buf_len,
|
||||||
const uint8_t *ext,
|
const uint8_t *ext,
|
||||||
size_t ext_len);
|
uint16_t ext_len,
|
||||||
extern size_t asn1_cvc_aut(void *rsa_ecdsa,
|
bool full);
|
||||||
|
extern uint16_t asn1_cvc_aut(void *rsa_ecdsa,
|
||||||
uint8_t key_type,
|
uint8_t key_type,
|
||||||
uint8_t *buf,
|
uint8_t *buf,
|
||||||
size_t buf_len,
|
uint16_t buf_len,
|
||||||
const uint8_t *ext,
|
const uint8_t *ext,
|
||||||
size_t ext_len);
|
uint16_t ext_len);
|
||||||
extern size_t asn1_build_cert_description(const uint8_t *label,
|
extern uint16_t asn1_build_cert_description(const uint8_t *label,
|
||||||
size_t label_len,
|
uint16_t label_len,
|
||||||
const uint8_t *puk,
|
const uint8_t *puk,
|
||||||
size_t puk_len,
|
uint16_t puk_len,
|
||||||
uint16_t fid,
|
uint16_t fid,
|
||||||
uint8_t *buf,
|
uint8_t *buf,
|
||||||
size_t buf_len);
|
uint16_t buf_len);
|
||||||
extern const uint8_t *cvc_get_field(const uint8_t *data, size_t len, size_t *olen, uint16_t tag);
|
extern const uint8_t *cvc_get_field(const uint8_t *data, uint16_t len, uint16_t *olen, uint16_t tag);
|
||||||
extern const uint8_t *cvc_get_car(const uint8_t *data, size_t len, size_t *olen);
|
extern const uint8_t *cvc_get_car(const uint8_t *data, uint16_t len, uint16_t *olen);
|
||||||
extern const uint8_t *cvc_get_chr(const uint8_t *data, size_t len, size_t *olen);
|
extern const uint8_t *cvc_get_chr(const uint8_t *data, uint16_t len, uint16_t *olen);
|
||||||
extern const uint8_t *cvc_get_pub(const uint8_t *data, size_t len, size_t *olen);
|
extern const uint8_t *cvc_get_pub(const uint8_t *data, uint16_t len, uint16_t *olen);
|
||||||
extern const uint8_t *cvc_get_ext(const uint8_t *data, size_t len, size_t *olen);
|
extern const uint8_t *cvc_get_ext(const uint8_t *data, uint16_t len, uint16_t *olen);
|
||||||
extern int cvc_verify(const uint8_t *cert, size_t cert_len, const uint8_t *ca, size_t ca_len);
|
extern int cvc_verify(const uint8_t *cert, uint16_t cert_len, const uint8_t *ca, uint16_t ca_len);
|
||||||
extern mbedtls_ecp_group_id cvc_inherite_ec_group(const uint8_t *ca, size_t ca_len);
|
extern mbedtls_ecp_group_id cvc_inherite_ec_group(const uint8_t *ca, uint16_t ca_len);
|
||||||
extern int puk_verify(const uint8_t *sig,
|
extern int puk_verify(const uint8_t *sig,
|
||||||
size_t sig_len,
|
uint16_t sig_len,
|
||||||
const uint8_t *hash,
|
const uint8_t *hash,
|
||||||
size_t hash_len,
|
uint16_t hash_len,
|
||||||
const uint8_t *ca,
|
const uint8_t *ca,
|
||||||
size_t ca_len);
|
uint16_t ca_len);
|
||||||
extern size_t asn1_build_prkd_ecc(const uint8_t *label,
|
extern uint16_t asn1_build_prkd_ecc(const uint8_t *label,
|
||||||
size_t label_len,
|
uint16_t label_len,
|
||||||
const uint8_t *keyid,
|
const uint8_t *keyid,
|
||||||
size_t keyid_len,
|
uint16_t keyid_len,
|
||||||
size_t keysize,
|
uint16_t keysize,
|
||||||
uint8_t *buf,
|
uint8_t *buf,
|
||||||
size_t buf_len);
|
uint16_t buf_len);
|
||||||
extern size_t asn1_build_prkd_rsa(const uint8_t *label,
|
extern uint16_t asn1_build_prkd_rsa(const uint8_t *label,
|
||||||
size_t label_len,
|
uint16_t label_len,
|
||||||
const uint8_t *keyid,
|
const uint8_t *keyid,
|
||||||
size_t keyid_len,
|
uint16_t keyid_len,
|
||||||
size_t keysize,
|
uint16_t keysize,
|
||||||
uint8_t *buf,
|
uint8_t *buf,
|
||||||
size_t buf_len);
|
uint16_t buf_len);
|
||||||
|
extern uint16_t asn1_build_prkd_aes(const uint8_t *label,
|
||||||
|
uint16_t label_len,
|
||||||
|
const uint8_t *keyid,
|
||||||
|
uint16_t keyid_len,
|
||||||
|
uint16_t keysize,
|
||||||
|
uint8_t *buf,
|
||||||
|
uint16_t buf_len);
|
||||||
|
extern uint16_t asn1_build_prkd_generic(const uint8_t *label,
|
||||||
|
uint16_t label_len,
|
||||||
|
const uint8_t *keyid,
|
||||||
|
uint16_t keyid_len,
|
||||||
|
uint16_t keysize,
|
||||||
|
int key_tpe,
|
||||||
|
uint8_t *buf,
|
||||||
|
uint16_t buf_len);
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
@@ -19,11 +19,12 @@
|
|||||||
|
|
||||||
extern const uint8_t sc_hsm_aid[];
|
extern const uint8_t sc_hsm_aid[];
|
||||||
extern int parse_token_info(const file_t *f, int mode);
|
extern int parse_token_info(const file_t *f, int mode);
|
||||||
|
extern int parse_ef_dir(const file_t *f, int mode);
|
||||||
|
|
||||||
file_t file_entries[] = {
|
file_t file_entries[] = {
|
||||||
/* 0 */ { .fid = 0x3f00, .parent = 0xff, .name = NULL, .type = FILE_TYPE_DF, .data = NULL,
|
/* 0 */ { .fid = 0x3f00, .parent = 0xff, .name = NULL, .type = FILE_TYPE_DF, .data = NULL,
|
||||||
.ef_structure = 0, .acl = { 0 } }, // MF
|
.ef_structure = 0, .acl = { 0 } }, // MF
|
||||||
/* 1 */ { .fid = 0x2f00, .parent = 0, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL,
|
/* 1 */ { .fid = 0x2f00, .parent = 0, .name = NULL, .type = FILE_TYPE_WORKING_EF | FILE_DATA_FUNC, .data = (uint8_t *) parse_ef_dir,
|
||||||
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.DIR
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.DIR
|
||||||
/* 2 */ { .fid = 0x2f01, .parent = 0, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL,
|
/* 2 */ { .fid = 0x2f01, .parent = 0, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL,
|
||||||
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.ATR
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.ATR
|
||||||
@@ -41,22 +42,22 @@ file_t file_entries[] = {
|
|||||||
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.TokenInfo
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.TokenInfo
|
||||||
/* 8 */ { .fid = 0x5033, .parent = 0, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL,
|
/* 8 */ { .fid = 0x5033, .parent = 0, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL,
|
||||||
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.UnusedSpace
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.UnusedSpace
|
||||||
/* 9 */ { .fid = 0x1081, .parent = 5, .name = NULL,
|
/* 9 */ { .fid = EF_PIN1, .parent = 5, .name = NULL,
|
||||||
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
||||||
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //PIN (PIN1)
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //PIN (PIN1)
|
||||||
/* 10 */ { .fid = 0x1082, .parent = 5, .name = NULL,
|
/* 10 */ { .fid = EF_PIN1_MAX_RETRIES, .parent = 5, .name = NULL,
|
||||||
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
||||||
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //max retries PIN (PIN1)
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //max retries PIN (PIN1)
|
||||||
/* 11 */ { .fid = 0x1083, .parent = 5, .name = NULL,
|
/* 11 */ { .fid = EF_PIN1_RETRIES, .parent = 5, .name = NULL,
|
||||||
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
||||||
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //retries PIN (PIN1)
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //retries PIN (PIN1)
|
||||||
/* 12 */ { .fid = 0x1088, .parent = 5, .name = NULL,
|
/* 12 */ { .fid = EF_SOPIN, .parent = 5, .name = NULL,
|
||||||
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
||||||
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //PIN (SOPIN)
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //PIN (SOPIN)
|
||||||
/* 13 */ { .fid = 0x1089, .parent = 5, .name = NULL,
|
/* 13 */ { .fid = EF_SOPIN_MAX_RETRIES, .parent = 5, .name = NULL,
|
||||||
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
||||||
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //max retries PIN (SOPIN)
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //max retries PIN (SOPIN)
|
||||||
/* 14 */ { .fid = 0x108A, .parent = 5, .name = NULL,
|
/* 14 */ { .fid = EF_SOPIN_RETRIES, .parent = 5, .name = NULL,
|
||||||
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
||||||
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //retries PIN (SOPIN)
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //retries PIN (SOPIN)
|
||||||
/* 15 */ { .fid = EF_DEVOPS, .parent = 5, .name = NULL,
|
/* 15 */ { .fid = EF_DEVOPS, .parent = 5, .name = NULL,
|
||||||
@@ -101,7 +102,7 @@ file_t file_entries[] = {
|
|||||||
///* 30 */ { .fid = 0x0000, .parent = 0, .name = openpgpcard_aid, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} },
|
///* 30 */ { .fid = 0x0000, .parent = 0, .name = openpgpcard_aid, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} },
|
||||||
/* 31 */ { .fid = 0x0000, .parent = 5, .name = sc_hsm_aid, .type = FILE_TYPE_WORKING_EF,
|
/* 31 */ { .fid = 0x0000, .parent = 5, .name = sc_hsm_aid, .type = FILE_TYPE_WORKING_EF,
|
||||||
.data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } },
|
.data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } },
|
||||||
/* 32 */ { .fid = 0x0000, .parent = 0xff, .name = NULL, .type = FILE_TYPE_UNKNOWN, .data = NULL,
|
/* 32 */ { .fid = 0x0000, .parent = 0xff, .name = NULL, .type = FILE_TYPE_NOT_KNOWN, .data = NULL,
|
||||||
.ef_structure = 0, .acl = { 0 } } //end
|
.ef_structure = 0, .acl = { 0 } } //end
|
||||||
};
|
};
|
||||||
|
|
||||||
|
|||||||
@@ -24,11 +24,18 @@
|
|||||||
#define EF_DEVOPS 0x100E
|
#define EF_DEVOPS 0x100E
|
||||||
#define EF_MKEK 0x100A
|
#define EF_MKEK 0x100A
|
||||||
#define EF_MKEK_SO 0x100B
|
#define EF_MKEK_SO 0x100B
|
||||||
#define EF_XKEK 0x1080
|
#define EF_XKEK 0x1070
|
||||||
|
#define EF_PIN1 0x1081
|
||||||
|
#define EF_PIN1_MAX_RETRIES 0x1082
|
||||||
|
#define EF_PIN1_RETRIES 0x1083
|
||||||
|
#define EF_SOPIN 0x1088
|
||||||
|
#define EF_SOPIN_MAX_RETRIES 0x1089
|
||||||
|
#define EF_SOPIN_RETRIES 0x108A
|
||||||
#define EF_DKEK 0x1090
|
#define EF_DKEK 0x1090
|
||||||
#define EF_KEY_DOMAIN 0x10A0
|
#define EF_KEY_DOMAIN 0x10A0
|
||||||
#define EF_PUKAUT 0x10C0
|
#define EF_PUKAUT 0x10C0
|
||||||
#define EF_PUK 0X10D0
|
#define EF_PUK 0x10D0
|
||||||
|
#define EF_MASTER_SEED 0x1110
|
||||||
#define EF_PRKDFS 0x6040
|
#define EF_PRKDFS 0x6040
|
||||||
#define EF_PUKDFS 0x6041
|
#define EF_PUKDFS 0x6041
|
||||||
#define EF_CDFS 0x6042
|
#define EF_CDFS 0x6042
|
||||||
@@ -40,7 +47,9 @@
|
|||||||
#define EF_PRKD_DEV 0xC400
|
#define EF_PRKD_DEV 0xC400
|
||||||
#define EF_EE_DEV 0xCE00
|
#define EF_EE_DEV 0xCE00
|
||||||
|
|
||||||
#define EF_TERMCA 0x2f02
|
#define EF_TERMCA 0x2F02
|
||||||
|
#define EF_TOKENINFO 0x2F03
|
||||||
|
#define EF_STATICTOKEN 0xCB00
|
||||||
|
|
||||||
extern file_t *file_pin1;
|
extern file_t *file_pin1;
|
||||||
extern file_t *file_retries_pin1;
|
extern file_t *file_retries_pin1;
|
||||||
|
|||||||
187
src/hsm/kek.c
187
src/hsm/kek.c
@@ -15,16 +15,14 @@
|
|||||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#include <string.h>
|
#include "sc_hsm.h"
|
||||||
#include "common.h"
|
|
||||||
#include "stdlib.h"
|
#include "stdlib.h"
|
||||||
#ifndef ENABLE_EMULATION
|
#if !defined(ENABLE_EMULATION) && !defined(ESP_PLATFORM)
|
||||||
#include "pico/stdlib.h"
|
#include "pico/stdlib.h"
|
||||||
#endif
|
#endif
|
||||||
#include "kek.h"
|
#include "kek.h"
|
||||||
#include "crypto_utils.h"
|
#include "crypto_utils.h"
|
||||||
#include "random.h"
|
#include "random.h"
|
||||||
#include "sc_hsm.h"
|
|
||||||
#include "mbedtls/md.h"
|
#include "mbedtls/md.h"
|
||||||
#include "mbedtls/cmac.h"
|
#include "mbedtls/cmac.h"
|
||||||
#include "mbedtls/rsa.h"
|
#include "mbedtls/rsa.h"
|
||||||
@@ -36,11 +34,12 @@ extern bool has_session_pin, has_session_sopin;
|
|||||||
extern uint8_t session_pin[32], session_sopin[32];
|
extern uint8_t session_pin[32], session_sopin[32];
|
||||||
uint8_t mkek_mask[MKEK_KEY_SIZE];
|
uint8_t mkek_mask[MKEK_KEY_SIZE];
|
||||||
bool has_mkek_mask = false;
|
bool has_mkek_mask = false;
|
||||||
|
uint8_t pending_save_dkek = 0xff;
|
||||||
|
|
||||||
#define POLY 0xedb88320
|
#define POLY 0xedb88320
|
||||||
|
|
||||||
uint32_t crc32c(const uint8_t *buf, size_t len) {
|
uint32_t crc32c(const uint8_t *buf, size_t len) {
|
||||||
uint32_t crc = ~0;
|
uint32_t crc = 0xffffffff;
|
||||||
while (len--) {
|
while (len--) {
|
||||||
crc ^= *buf++;
|
crc ^= *buf++;
|
||||||
for (int k = 0; k < 8; k++) {
|
for (int k = 0; k < 8; k++) {
|
||||||
@@ -56,14 +55,14 @@ int load_mkek(uint8_t *mkek) {
|
|||||||
}
|
}
|
||||||
const uint8_t *pin = NULL;
|
const uint8_t *pin = NULL;
|
||||||
if (pin == NULL && has_session_pin == true) {
|
if (pin == NULL && has_session_pin == true) {
|
||||||
file_t *tf = search_by_fid(EF_MKEK, NULL, SPECIFY_EF);
|
file_t *tf = search_file(EF_MKEK);
|
||||||
if (file_has_data(tf)) {
|
if (file_has_data(tf)) {
|
||||||
memcpy(mkek, file_get_data(tf), MKEK_SIZE);
|
memcpy(mkek, file_get_data(tf), MKEK_SIZE);
|
||||||
pin = session_pin;
|
pin = session_pin;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (pin == NULL && has_session_sopin == true) {
|
if (pin == NULL && has_session_sopin == true) {
|
||||||
file_t *tf = search_by_fid(EF_MKEK_SO, NULL, SPECIFY_EF);
|
file_t *tf = search_file(EF_MKEK_SO);
|
||||||
if (file_has_data(tf)) {
|
if (file_has_data(tf)) {
|
||||||
memcpy(mkek, file_get_data(tf), MKEK_SIZE);
|
memcpy(mkek, file_get_data(tf), MKEK_SIZE);
|
||||||
pin = session_sopin;
|
pin = session_sopin;
|
||||||
@@ -108,8 +107,8 @@ int mse_decrypt_ct(uint8_t *data, size_t len) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int load_dkek(uint8_t id, uint8_t *dkek) {
|
int load_dkek(uint8_t id, uint8_t *dkek) {
|
||||||
file_t *tf = search_dynamic_file(EF_DKEK + id);
|
file_t *tf = search_file(EF_DKEK + id);
|
||||||
if (!tf) {
|
if (!file_has_data(tf)) {
|
||||||
return CCID_ERR_FILE_NOT_FOUND;
|
return CCID_ERR_FILE_NOT_FOUND;
|
||||||
}
|
}
|
||||||
memcpy(dkek, file_get_data(tf), DKEK_KEY_SIZE);
|
memcpy(dkek, file_get_data(tf), DKEK_KEY_SIZE);
|
||||||
@@ -136,7 +135,7 @@ int store_mkek(const uint8_t *mkek) {
|
|||||||
if (has_session_pin) {
|
if (has_session_pin) {
|
||||||
uint8_t tmp_mkek_pin[MKEK_SIZE];
|
uint8_t tmp_mkek_pin[MKEK_SIZE];
|
||||||
memcpy(tmp_mkek_pin, tmp_mkek, MKEK_SIZE);
|
memcpy(tmp_mkek_pin, tmp_mkek, MKEK_SIZE);
|
||||||
file_t *tf = search_by_fid(EF_MKEK, NULL, SPECIFY_EF);
|
file_t *tf = search_file(EF_MKEK);
|
||||||
if (!tf) {
|
if (!tf) {
|
||||||
release_mkek(tmp_mkek);
|
release_mkek(tmp_mkek);
|
||||||
release_mkek(tmp_mkek_pin);
|
release_mkek(tmp_mkek_pin);
|
||||||
@@ -146,13 +145,13 @@ int store_mkek(const uint8_t *mkek) {
|
|||||||
MKEK_IV(tmp_mkek_pin),
|
MKEK_IV(tmp_mkek_pin),
|
||||||
MKEK_KEY(tmp_mkek_pin),
|
MKEK_KEY(tmp_mkek_pin),
|
||||||
MKEK_KEY_SIZE + MKEK_KEY_CS_SIZE);
|
MKEK_KEY_SIZE + MKEK_KEY_CS_SIZE);
|
||||||
flash_write_data_to_file(tf, tmp_mkek_pin, MKEK_SIZE);
|
file_put_data(tf, tmp_mkek_pin, MKEK_SIZE);
|
||||||
release_mkek(tmp_mkek_pin);
|
release_mkek(tmp_mkek_pin);
|
||||||
}
|
}
|
||||||
if (has_session_sopin) {
|
if (has_session_sopin) {
|
||||||
uint8_t tmp_mkek_sopin[MKEK_SIZE];
|
uint8_t tmp_mkek_sopin[MKEK_SIZE];
|
||||||
memcpy(tmp_mkek_sopin, tmp_mkek, MKEK_SIZE);
|
memcpy(tmp_mkek_sopin, tmp_mkek, MKEK_SIZE);
|
||||||
file_t *tf = search_by_fid(EF_MKEK_SO, NULL, SPECIFY_EF);
|
file_t *tf = search_file(EF_MKEK_SO);
|
||||||
if (!tf) {
|
if (!tf) {
|
||||||
release_mkek(tmp_mkek);
|
release_mkek(tmp_mkek);
|
||||||
release_mkek(tmp_mkek_sopin);
|
release_mkek(tmp_mkek_sopin);
|
||||||
@@ -162,7 +161,7 @@ int store_mkek(const uint8_t *mkek) {
|
|||||||
MKEK_IV(tmp_mkek_sopin),
|
MKEK_IV(tmp_mkek_sopin),
|
||||||
MKEK_KEY(tmp_mkek_sopin),
|
MKEK_KEY(tmp_mkek_sopin),
|
||||||
MKEK_KEY_SIZE + MKEK_KEY_CS_SIZE);
|
MKEK_KEY_SIZE + MKEK_KEY_CS_SIZE);
|
||||||
flash_write_data_to_file(tf, tmp_mkek_sopin, MKEK_SIZE);
|
file_put_data(tf, tmp_mkek_sopin, MKEK_SIZE);
|
||||||
release_mkek(tmp_mkek_sopin);
|
release_mkek(tmp_mkek_sopin);
|
||||||
}
|
}
|
||||||
low_flash_available();
|
low_flash_available();
|
||||||
@@ -171,7 +170,7 @@ int store_mkek(const uint8_t *mkek) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int store_dkek_key(uint8_t id, uint8_t *dkek) {
|
int store_dkek_key(uint8_t id, uint8_t *dkek) {
|
||||||
file_t *tf = search_dynamic_file(EF_DKEK + id);
|
file_t *tf = search_file(EF_DKEK + id);
|
||||||
if (!tf) {
|
if (!tf) {
|
||||||
return CCID_ERR_FILE_NOT_FOUND;
|
return CCID_ERR_FILE_NOT_FOUND;
|
||||||
}
|
}
|
||||||
@@ -179,7 +178,7 @@ int store_dkek_key(uint8_t id, uint8_t *dkek) {
|
|||||||
if (r != CCID_OK) {
|
if (r != CCID_OK) {
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
flash_write_data_to_file(tf, dkek, DKEK_KEY_SIZE);
|
file_put_data(tf, dkek, DKEK_KEY_SIZE);
|
||||||
low_flash_available();
|
low_flash_available();
|
||||||
return CCID_OK;
|
return CCID_OK;
|
||||||
}
|
}
|
||||||
@@ -187,7 +186,7 @@ int store_dkek_key(uint8_t id, uint8_t *dkek) {
|
|||||||
int save_dkek_key(uint8_t id, const uint8_t *key) {
|
int save_dkek_key(uint8_t id, const uint8_t *key) {
|
||||||
uint8_t dkek[DKEK_KEY_SIZE];
|
uint8_t dkek[DKEK_KEY_SIZE];
|
||||||
if (!key) {
|
if (!key) {
|
||||||
file_t *tf = search_dynamic_file(EF_DKEK + id);
|
file_t *tf = search_file(EF_DKEK + id);
|
||||||
if (!tf) {
|
if (!tf) {
|
||||||
return CCID_ERR_FILE_NOT_FOUND;
|
return CCID_ERR_FILE_NOT_FOUND;
|
||||||
}
|
}
|
||||||
@@ -201,7 +200,7 @@ int save_dkek_key(uint8_t id, const uint8_t *key) {
|
|||||||
|
|
||||||
int import_dkek_share(uint8_t id, const uint8_t *share) {
|
int import_dkek_share(uint8_t id, const uint8_t *share) {
|
||||||
uint8_t tmp_dkek[DKEK_KEY_SIZE];
|
uint8_t tmp_dkek[DKEK_KEY_SIZE];
|
||||||
file_t *tf = search_dynamic_file(EF_DKEK + id);
|
file_t *tf = search_file(EF_DKEK + id);
|
||||||
if (!tf) {
|
if (!tf) {
|
||||||
return CCID_ERR_FILE_NOT_FOUND;
|
return CCID_ERR_FILE_NOT_FOUND;
|
||||||
}
|
}
|
||||||
@@ -212,7 +211,7 @@ int import_dkek_share(uint8_t id, const uint8_t *share) {
|
|||||||
for (int i = 0; i < DKEK_KEY_SIZE; i++) {
|
for (int i = 0; i < DKEK_KEY_SIZE; i++) {
|
||||||
tmp_dkek[i] ^= share[i];
|
tmp_dkek[i] ^= share[i];
|
||||||
}
|
}
|
||||||
flash_write_data_to_file(tf, tmp_dkek, DKEK_KEY_SIZE);
|
file_put_data(tf, tmp_dkek, DKEK_KEY_SIZE);
|
||||||
low_flash_available();
|
low_flash_available();
|
||||||
return CCID_OK;
|
return CCID_OK;
|
||||||
}
|
}
|
||||||
@@ -257,7 +256,7 @@ int dkek_kmac(uint8_t id, uint8_t *kmac) { //kmac 32 bytes
|
|||||||
return CCID_OK;
|
return CCID_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
int mkek_encrypt(uint8_t *data, size_t len) {
|
int mkek_encrypt(uint8_t *data, uint16_t len) {
|
||||||
int r;
|
int r;
|
||||||
uint8_t mkek[MKEK_SIZE + 4];
|
uint8_t mkek[MKEK_SIZE + 4];
|
||||||
if ((r = load_mkek(mkek)) != CCID_OK) {
|
if ((r = load_mkek(mkek)) != CCID_OK) {
|
||||||
@@ -268,7 +267,7 @@ int mkek_encrypt(uint8_t *data, size_t len) {
|
|||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
int mkek_decrypt(uint8_t *data, size_t len) {
|
int mkek_decrypt(uint8_t *data, uint16_t len) {
|
||||||
int r;
|
int r;
|
||||||
uint8_t mkek[MKEK_SIZE + 4];
|
uint8_t mkek[MKEK_SIZE + 4];
|
||||||
if ((r = load_mkek(mkek)) != CCID_OK) {
|
if ((r = load_mkek(mkek)) != CCID_OK) {
|
||||||
@@ -283,16 +282,17 @@ int dkek_encode_key(uint8_t id,
|
|||||||
void *key_ctx,
|
void *key_ctx,
|
||||||
int key_type,
|
int key_type,
|
||||||
uint8_t *out,
|
uint8_t *out,
|
||||||
size_t *out_len,
|
uint16_t *out_len,
|
||||||
const uint8_t *allowed,
|
const uint8_t *allowed,
|
||||||
size_t allowed_len) {
|
uint16_t allowed_len) {
|
||||||
if (!(key_type & HSM_KEY_RSA) && !(key_type & HSM_KEY_EC) && !(key_type & HSM_KEY_AES)) {
|
if (!(key_type & PICO_KEYS_KEY_RSA) && !(key_type & PICO_KEYS_KEY_EC) && !(key_type & PICO_KEYS_KEY_AES)) {
|
||||||
return CCID_WRONG_DATA;
|
return CCID_WRONG_DATA;
|
||||||
}
|
}
|
||||||
|
|
||||||
uint8_t kb[8 + 2 * 4 + 2 * 4096 / 8 + 3 + 13]; //worst case: RSA-4096 (plus, 13 bytes 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));
|
memset(kb, 0, sizeof(kb));
|
||||||
int kb_len = 0, r = 0;
|
uint16_t kb_len = 0;
|
||||||
|
int r = 0;
|
||||||
uint8_t *algo = NULL;
|
uint8_t *algo = NULL;
|
||||||
uint8_t algo_len = 0;
|
uint8_t algo_len = 0;
|
||||||
uint8_t kenc[32];
|
uint8_t kenc[32];
|
||||||
@@ -316,21 +316,24 @@ int dkek_encode_key(uint8_t id,
|
|||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (key_type & HSM_KEY_AES) {
|
if (key_type & PICO_KEYS_KEY_AES) {
|
||||||
if (key_type & HSM_KEY_AES_128) {
|
if (key_type & PICO_KEYS_KEY_AES_128) {
|
||||||
kb_len = 16;
|
kb_len = 16;
|
||||||
}
|
}
|
||||||
else if (key_type & HSM_KEY_AES_192) {
|
else if (key_type & PICO_KEYS_KEY_AES_192) {
|
||||||
kb_len = 24;
|
kb_len = 24;
|
||||||
}
|
}
|
||||||
else if (key_type & HSM_KEY_AES_256) {
|
else if (key_type & PICO_KEYS_KEY_AES_256) {
|
||||||
kb_len = 32;
|
kb_len = 32;
|
||||||
}
|
}
|
||||||
|
else if (key_type & PICO_KEYS_KEY_AES_512) {
|
||||||
|
kb_len = 64;
|
||||||
|
}
|
||||||
|
|
||||||
if (kb_len != 16 && kb_len != 24 && kb_len != 32) {
|
if (kb_len != 16 && kb_len != 24 && kb_len != 32 && kb_len != 64) {
|
||||||
return CCID_WRONG_DATA;
|
return CCID_WRONG_DATA;
|
||||||
}
|
}
|
||||||
if (*out_len < 8 + 1 + 10 + 6 + 4 + (2 + 32 + 14) + 16) {
|
if (*out_len < 8 + 1 + 10 + 6 + (2 + 64 + 14) + 16) { // 14 bytes padding
|
||||||
return CCID_WRONG_LENGTH;
|
return CCID_WRONG_LENGTH;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -341,66 +344,69 @@ int dkek_encode_key(uint8_t id,
|
|||||||
algo = (uint8_t *) "\x00\x08\x60\x86\x48\x01\x65\x03\x04\x01"; //2.16.840.1.101.3.4.1 (2+8)
|
algo = (uint8_t *) "\x00\x08\x60\x86\x48\x01\x65\x03\x04\x01"; //2.16.840.1.101.3.4.1 (2+8)
|
||||||
algo_len = 10;
|
algo_len = 10;
|
||||||
}
|
}
|
||||||
else if (key_type & HSM_KEY_RSA) {
|
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
|
if (*out_len < 8 + 1 + 12 + 6 + (8 + 2 * 4 + 2 * 4096 / 8 + 3 + 13) + 16) { //13 bytes pading
|
||||||
return CCID_WRONG_LENGTH;
|
return CCID_WRONG_LENGTH;
|
||||||
}
|
}
|
||||||
mbedtls_rsa_context *rsa = (mbedtls_rsa_context *) key_ctx;
|
mbedtls_rsa_context *rsa = (mbedtls_rsa_context *) key_ctx;
|
||||||
kb_len = 0;
|
kb_len = 0;
|
||||||
put_uint16_t(mbedtls_rsa_get_len(rsa) * 8, kb + 8 + kb_len); kb_len += 2;
|
put_uint16_t((uint16_t)mbedtls_rsa_get_len(rsa) * 8, kb + 8 + kb_len); kb_len += 2;
|
||||||
|
|
||||||
put_uint16_t(mbedtls_mpi_size(&rsa->D), kb + 8 + kb_len); kb_len += 2;
|
put_uint16_t((uint16_t)mbedtls_mpi_size(&rsa->D), kb + 8 + kb_len); kb_len += 2;
|
||||||
mbedtls_mpi_write_binary(&rsa->D, kb + 8 + kb_len, mbedtls_mpi_size(&rsa->D));
|
mbedtls_mpi_write_binary(&rsa->D, kb + 8 + kb_len, mbedtls_mpi_size(&rsa->D));
|
||||||
kb_len += mbedtls_mpi_size(&rsa->D);
|
kb_len += (uint16_t)mbedtls_mpi_size(&rsa->D);
|
||||||
put_uint16_t(mbedtls_mpi_size(&rsa->N), kb + 8 + kb_len); kb_len += 2;
|
put_uint16_t((uint16_t)mbedtls_mpi_size(&rsa->N), kb + 8 + kb_len); kb_len += 2;
|
||||||
mbedtls_mpi_write_binary(&rsa->N, kb + 8 + kb_len, mbedtls_mpi_size(&rsa->N));
|
mbedtls_mpi_write_binary(&rsa->N, kb + 8 + kb_len, mbedtls_mpi_size(&rsa->N));
|
||||||
kb_len += mbedtls_mpi_size(&rsa->N);
|
kb_len += (uint16_t)mbedtls_mpi_size(&rsa->N);
|
||||||
put_uint16_t(mbedtls_mpi_size(&rsa->E), kb + 8 + kb_len); kb_len += 2;
|
put_uint16_t((uint16_t)mbedtls_mpi_size(&rsa->E), kb + 8 + kb_len); kb_len += 2;
|
||||||
mbedtls_mpi_write_binary(&rsa->E, kb + 8 + kb_len, mbedtls_mpi_size(&rsa->E));
|
mbedtls_mpi_write_binary(&rsa->E, kb + 8 + kb_len, mbedtls_mpi_size(&rsa->E));
|
||||||
kb_len += mbedtls_mpi_size(&rsa->E);
|
kb_len += (uint16_t)mbedtls_mpi_size(&rsa->E);
|
||||||
|
|
||||||
algo = (uint8_t *) "\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x01\x02";
|
algo = (uint8_t *) "\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x01\x02";
|
||||||
algo_len = 12;
|
algo_len = 12;
|
||||||
}
|
}
|
||||||
else if (key_type & HSM_KEY_EC) {
|
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
|
if (*out_len < 8 + 1 + 12 + 6 + (8 + 2 * 8 + 9 * 66 + 2 + 4) + 16) { //4 bytes pading
|
||||||
return CCID_WRONG_LENGTH;
|
return CCID_WRONG_LENGTH;
|
||||||
}
|
}
|
||||||
mbedtls_ecdsa_context *ecdsa = (mbedtls_ecdsa_context *) key_ctx;
|
mbedtls_ecdsa_context *ecdsa = (mbedtls_ecdsa_context *) key_ctx;
|
||||||
kb_len = 0;
|
kb_len = 0;
|
||||||
put_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.P) * 8, kb + 8 + kb_len); kb_len += 2;
|
||||||
put_uint16_t(mbedtls_mpi_size(&ecdsa->grp.A), 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;
|
||||||
mbedtls_mpi_write_binary(&ecdsa->grp.A, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->grp.A));
|
mbedtls_mpi_write_binary(&ecdsa->grp.A, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->grp.A));
|
||||||
kb_len += mbedtls_mpi_size(&ecdsa->grp.A);
|
kb_len += (uint16_t)mbedtls_mpi_size(&ecdsa->grp.A);
|
||||||
put_uint16_t(mbedtls_mpi_size(&ecdsa->grp.B), kb + 8 + kb_len); kb_len += 2;
|
put_uint16_t((uint16_t)mbedtls_mpi_size(&ecdsa->grp.B), kb + 8 + kb_len); kb_len += 2;
|
||||||
mbedtls_mpi_write_binary(&ecdsa->grp.B, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->grp.B));
|
mbedtls_mpi_write_binary(&ecdsa->grp.B, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->grp.B));
|
||||||
kb_len += mbedtls_mpi_size(&ecdsa->grp.B);
|
kb_len += (uint16_t)mbedtls_mpi_size(&ecdsa->grp.B);
|
||||||
put_uint16_t(mbedtls_mpi_size(&ecdsa->grp.P), kb + 8 + kb_len); kb_len += 2;
|
put_uint16_t((uint16_t)mbedtls_mpi_size(&ecdsa->grp.P), kb + 8 + kb_len); kb_len += 2;
|
||||||
mbedtls_mpi_write_binary(&ecdsa->grp.P, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->grp.P));
|
mbedtls_mpi_write_binary(&ecdsa->grp.P, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->grp.P));
|
||||||
kb_len += mbedtls_mpi_size(&ecdsa->grp.P);
|
kb_len += (uint16_t)mbedtls_mpi_size(&ecdsa->grp.P);
|
||||||
put_uint16_t(mbedtls_mpi_size(&ecdsa->grp.N), kb + 8 + kb_len); kb_len += 2;
|
put_uint16_t((uint16_t)mbedtls_mpi_size(&ecdsa->grp.N), kb + 8 + kb_len); kb_len += 2;
|
||||||
mbedtls_mpi_write_binary(&ecdsa->grp.N, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->grp.N));
|
mbedtls_mpi_write_binary(&ecdsa->grp.N, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->grp.N));
|
||||||
kb_len += mbedtls_mpi_size(&ecdsa->grp.N);
|
kb_len += (uint16_t)mbedtls_mpi_size(&ecdsa->grp.N);
|
||||||
put_uint16_t(1 + mbedtls_mpi_size(&ecdsa->grp.G.X) + mbedtls_mpi_size(&ecdsa->grp.G.Y),
|
|
||||||
kb + 8 + kb_len); kb_len += 2;
|
size_t olen = 0;
|
||||||
kb[8 + kb_len++] = 0x4;
|
mbedtls_ecp_point_write_binary(&ecdsa->grp,
|
||||||
mbedtls_mpi_write_binary(&ecdsa->grp.G.X, kb + 8 + kb_len,
|
&ecdsa->grp.G,
|
||||||
mbedtls_mpi_size(&ecdsa->grp.G.X));
|
MBEDTLS_ECP_PF_UNCOMPRESSED,
|
||||||
kb_len += mbedtls_mpi_size(&ecdsa->grp.G.X);
|
&olen,
|
||||||
mbedtls_mpi_write_binary(&ecdsa->grp.G.Y, kb + 8 + kb_len,
|
kb + 8 + kb_len + 2,
|
||||||
mbedtls_mpi_size(&ecdsa->grp.G.Y));
|
sizeof(kb) - 8 - kb_len - 2);
|
||||||
kb_len += mbedtls_mpi_size(&ecdsa->grp.G.Y);
|
put_uint16_t((uint16_t)olen, kb + 8 + kb_len);
|
||||||
put_uint16_t(mbedtls_mpi_size(&ecdsa->d), kb + 8 + kb_len); kb_len += 2;
|
kb_len += 2 + (uint16_t)olen;
|
||||||
|
|
||||||
|
put_uint16_t((uint16_t)mbedtls_mpi_size(&ecdsa->d), kb + 8 + kb_len); kb_len += 2;
|
||||||
mbedtls_mpi_write_binary(&ecdsa->d, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->d));
|
mbedtls_mpi_write_binary(&ecdsa->d, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->d));
|
||||||
kb_len += mbedtls_mpi_size(&ecdsa->d);
|
kb_len += (uint16_t)mbedtls_mpi_size(&ecdsa->d);
|
||||||
put_uint16_t(1 + mbedtls_mpi_size(&ecdsa->Q.X) + mbedtls_mpi_size(&ecdsa->Q.Y),
|
|
||||||
kb + 8 + kb_len);
|
mbedtls_ecp_point_write_binary(&ecdsa->grp,
|
||||||
kb_len += 2;
|
&ecdsa->Q,
|
||||||
kb[8 + kb_len++] = 0x4;
|
MBEDTLS_ECP_PF_UNCOMPRESSED,
|
||||||
mbedtls_mpi_write_binary(&ecdsa->Q.X, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->Q.X));
|
&olen,
|
||||||
kb_len += mbedtls_mpi_size(&ecdsa->Q.X);
|
kb + 8 + kb_len + 2,
|
||||||
mbedtls_mpi_write_binary(&ecdsa->Q.Y, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->Q.Y));
|
sizeof(kb) - 8 - kb_len - 2);
|
||||||
kb_len += mbedtls_mpi_size(&ecdsa->Q.Y);
|
put_uint16_t((uint16_t)olen, kb + 8 + kb_len);
|
||||||
|
kb_len += 2 + (uint16_t)olen;
|
||||||
|
|
||||||
algo = (uint8_t *) "\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x02\x03";
|
algo = (uint8_t *) "\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x02\x03";
|
||||||
algo_len = 12;
|
algo_len = 12;
|
||||||
@@ -411,13 +417,13 @@ int dkek_encode_key(uint8_t id,
|
|||||||
memcpy(out + *out_len, kcv, 8);
|
memcpy(out + *out_len, kcv, 8);
|
||||||
*out_len += 8;
|
*out_len += 8;
|
||||||
|
|
||||||
if (key_type & HSM_KEY_AES) {
|
if (key_type & PICO_KEYS_KEY_AES) {
|
||||||
out[*out_len] = 15;
|
out[*out_len] = 15;
|
||||||
}
|
}
|
||||||
else if (key_type & HSM_KEY_RSA) {
|
else if (key_type & PICO_KEYS_KEY_RSA) {
|
||||||
out[*out_len] = 5;
|
out[*out_len] = 5;
|
||||||
}
|
}
|
||||||
else if (key_type & HSM_KEY_EC) {
|
else if (key_type & PICO_KEYS_KEY_EC) {
|
||||||
out[*out_len] = 12;
|
out[*out_len] = 12;
|
||||||
}
|
}
|
||||||
*out_len += 1;
|
*out_len += 1;
|
||||||
@@ -443,7 +449,7 @@ int dkek_encode_key(uint8_t id,
|
|||||||
|
|
||||||
memcpy(kb, random_bytes_get(8), 8);
|
memcpy(kb, random_bytes_get(8), 8);
|
||||||
kb_len += 8; //8 random bytes
|
kb_len += 8; //8 random bytes
|
||||||
int kb_len_pad = ((int) (kb_len / 16)) * 16;
|
uint16_t kb_len_pad = ((uint16_t) (kb_len / 16)) * 16;
|
||||||
if (kb_len % 16 > 0) {
|
if (kb_len % 16 > 0) {
|
||||||
kb_len_pad = ((int) (kb_len / 16) + 1) * 16;
|
kb_len_pad = ((int) (kb_len / 16) + 1) * 16;
|
||||||
}
|
}
|
||||||
@@ -451,7 +457,7 @@ int dkek_encode_key(uint8_t id,
|
|||||||
if (kb_len < kb_len_pad) {
|
if (kb_len < kb_len_pad) {
|
||||||
kb[kb_len] = 0x80;
|
kb[kb_len] = 0x80;
|
||||||
}
|
}
|
||||||
r = aes_encrypt(kenc, NULL, 256, HSM_AES_MODE_CBC, kb, kb_len_pad);
|
r = aes_encrypt(kenc, NULL, 256, PICO_KEYS_AES_MODE_CBC, kb, kb_len_pad);
|
||||||
if (r != CCID_OK) {
|
if (r != CCID_OK) {
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
@@ -475,13 +481,13 @@ int dkek_encode_key(uint8_t id,
|
|||||||
|
|
||||||
int dkek_type_key(const uint8_t *in) {
|
int dkek_type_key(const uint8_t *in) {
|
||||||
if (in[8] == 5 || in[8] == 6) {
|
if (in[8] == 5 || in[8] == 6) {
|
||||||
return HSM_KEY_RSA;
|
return PICO_KEYS_KEY_RSA;
|
||||||
}
|
}
|
||||||
else if (in[8] == 12) {
|
else if (in[8] == 12) {
|
||||||
return HSM_KEY_EC;
|
return PICO_KEYS_KEY_EC;
|
||||||
}
|
}
|
||||||
else if (in[8] == 15) {
|
else if (in[8] == 15) {
|
||||||
return HSM_KEY_AES;
|
return PICO_KEYS_KEY_AES;
|
||||||
}
|
}
|
||||||
return 0x0;
|
return 0x0;
|
||||||
}
|
}
|
||||||
@@ -489,10 +495,10 @@ int dkek_type_key(const uint8_t *in) {
|
|||||||
int dkek_decode_key(uint8_t id,
|
int dkek_decode_key(uint8_t id,
|
||||||
void *key_ctx,
|
void *key_ctx,
|
||||||
const uint8_t *in,
|
const uint8_t *in,
|
||||||
size_t in_len,
|
uint16_t in_len,
|
||||||
int *key_size_out,
|
int *key_size_out,
|
||||||
uint8_t **allowed,
|
uint8_t **allowed,
|
||||||
size_t *allowed_len) {
|
uint16_t *allowed_len) {
|
||||||
uint8_t kcv[8];
|
uint8_t kcv[8];
|
||||||
int r = 0;
|
int r = 0;
|
||||||
memset(kcv, 0, sizeof(kcv));
|
memset(kcv, 0, sizeof(kcv));
|
||||||
@@ -552,10 +558,10 @@ int dkek_decode_key(uint8_t id,
|
|||||||
return CCID_WRONG_DATA;
|
return CCID_WRONG_DATA;
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t ofs = 9;
|
uint16_t ofs = 9;
|
||||||
|
|
||||||
//OID
|
//OID
|
||||||
size_t len = get_uint16_t(in, ofs);
|
uint16_t len = get_uint16_t(in, ofs);
|
||||||
ofs += len + 2;
|
ofs += len + 2;
|
||||||
|
|
||||||
//Allowed algorithms
|
//Allowed algorithms
|
||||||
@@ -578,7 +584,7 @@ int dkek_decode_key(uint8_t id,
|
|||||||
uint8_t kb[8 + 2 * 4 + 2 * 4096 / 8 + 3 + 13]; //worst case: RSA-4096 (plus, 13 bytes 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));
|
memset(kb, 0, sizeof(kb));
|
||||||
memcpy(kb, in + ofs, in_len - 16 - ofs);
|
memcpy(kb, in + ofs, in_len - 16 - ofs);
|
||||||
r = aes_decrypt(kenc, NULL, 256, HSM_AES_MODE_CBC, kb, 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 != CCID_OK) {
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
@@ -689,7 +695,14 @@ int dkek_decode_key(uint8_t id,
|
|||||||
len = get_uint16_t(kb, ofs); ofs += len + 2;
|
len = get_uint16_t(kb, ofs); ofs += len + 2;
|
||||||
|
|
||||||
//G
|
//G
|
||||||
len = get_uint16_t(kb, ofs); ofs += len + 2;
|
len = get_uint16_t(kb, ofs);
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
ofs += len + 2;
|
||||||
|
|
||||||
//d
|
//d
|
||||||
len = get_uint16_t(kb, ofs); ofs += 2;
|
len = get_uint16_t(kb, ofs); ofs += 2;
|
||||||
@@ -704,8 +717,16 @@ int dkek_decode_key(uint8_t id,
|
|||||||
len = get_uint16_t(kb, ofs); ofs += 2;
|
len = get_uint16_t(kb, ofs); ofs += 2;
|
||||||
r = mbedtls_ecp_point_read_binary(&ecdsa->grp, &ecdsa->Q, kb + ofs, len);
|
r = mbedtls_ecp_point_read_binary(&ecdsa->grp, &ecdsa->Q, kb + ofs, len);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
mbedtls_ecdsa_free(ecdsa);
|
if (mbedtls_ecp_get_type(&ecdsa->grp) == MBEDTLS_ECP_TYPE_EDWARDS) {
|
||||||
return CCID_EXEC_ERROR;
|
r = mbedtls_ecp_point_edwards(&ecdsa->grp, &ecdsa->Q, &ecdsa->d, random_gen, NULL);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
r = mbedtls_ecp_check_pub_priv(ecdsa, ecdsa, random_gen, NULL);
|
r = mbedtls_ecp_check_pub_priv(ecdsa, ecdsa, random_gen, NULL);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
|
|||||||
@@ -19,10 +19,11 @@
|
|||||||
#define _DKEK_H_
|
#define _DKEK_H_
|
||||||
|
|
||||||
#include "crypto_utils.h"
|
#include "crypto_utils.h"
|
||||||
#ifdef ENABLE_EMULATION
|
#if defined(ENABLE_EMULATION) || defined(ESP_PLATFORM)
|
||||||
#include <stdbool.h>
|
#include <stdbool.h>
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
|
||||||
extern int load_mkek(uint8_t *);
|
extern int load_mkek(uint8_t *);
|
||||||
extern int store_mkek(const uint8_t *);
|
extern int store_mkek(const uint8_t *);
|
||||||
extern int save_dkek_key(uint8_t, const uint8_t *key);
|
extern int save_dkek_key(uint8_t, const uint8_t *key);
|
||||||
@@ -31,23 +32,23 @@ extern void init_mkek();
|
|||||||
extern void release_mkek(uint8_t *);
|
extern void release_mkek(uint8_t *);
|
||||||
extern int import_dkek_share(uint8_t, const uint8_t *share);
|
extern int import_dkek_share(uint8_t, const uint8_t *share);
|
||||||
extern int dkek_kcv(uint8_t, uint8_t *kcv);
|
extern int dkek_kcv(uint8_t, uint8_t *kcv);
|
||||||
extern int mkek_encrypt(uint8_t *data, size_t len);
|
extern int mkek_encrypt(uint8_t *data, uint16_t len);
|
||||||
extern int mkek_decrypt(uint8_t *data, size_t len);
|
extern int mkek_decrypt(uint8_t *data, uint16_t len);
|
||||||
extern int dkek_encode_key(uint8_t,
|
extern int dkek_encode_key(uint8_t,
|
||||||
void *key_ctx,
|
void *key_ctx,
|
||||||
int key_type,
|
int key_type,
|
||||||
uint8_t *out,
|
uint8_t *out,
|
||||||
size_t *out_len,
|
uint16_t *out_len,
|
||||||
const uint8_t *,
|
const uint8_t *,
|
||||||
size_t);
|
uint16_t);
|
||||||
extern int dkek_type_key(const uint8_t *in);
|
extern int dkek_type_key(const uint8_t *in);
|
||||||
extern int dkek_decode_key(uint8_t,
|
extern int dkek_decode_key(uint8_t,
|
||||||
void *key_ctx,
|
void *key_ctx,
|
||||||
const uint8_t *in,
|
const uint8_t *in,
|
||||||
size_t in_len,
|
uint16_t in_len,
|
||||||
int *key_size_out,
|
int *key_size_out,
|
||||||
uint8_t **,
|
uint8_t **,
|
||||||
size_t *);
|
uint16_t *);
|
||||||
|
|
||||||
#define MAX_DKEK_ENCODE_KEY_BUFFER (8 + 1 + 12 + 6 + (8 + 2 * 4 + 2 * 4096 / 8 + 3 + 13) + 16)
|
#define MAX_DKEK_ENCODE_KEY_BUFFER (8 + 1 + 12 + 6 + (8 + 2 * 4 + 2 * 4096 / 8 + 3 + 13) + 16)
|
||||||
|
|
||||||
@@ -74,4 +75,6 @@ extern mse_t mse;
|
|||||||
|
|
||||||
extern int mse_decrypt_ct(uint8_t *, size_t);
|
extern int mse_decrypt_ct(uint8_t *, size_t);
|
||||||
|
|
||||||
|
extern uint8_t pending_save_dkek;
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
@@ -144,4 +144,34 @@
|
|||||||
|
|
||||||
#define OID_KDF_X963 "\x2B\x81\x05\x10\x86\x48\x3F"
|
#define OID_KDF_X963 "\x2B\x81\x05\x10\x86\x48\x3F"
|
||||||
|
|
||||||
|
#define OID_NIST_ALG "\x60\x86\x48\x01\x65\x03\x04"
|
||||||
|
#define OID_NIST_AES OID_NIST_ALG "\x01"
|
||||||
|
#define OID_AES128_ECB OID_NIST_AES "\x01"
|
||||||
|
#define OID_AES128_CBC OID_NIST_AES "\x02"
|
||||||
|
#define OID_AES128_OFB OID_NIST_AES "\x03"
|
||||||
|
#define OID_AES128_CFB OID_NIST_AES "\x04"
|
||||||
|
#define OID_AES128_GCM OID_NIST_AES "\x06"
|
||||||
|
#define OID_AES128_CCM OID_NIST_AES "\x07"
|
||||||
|
#define OID_AES128_CTR OID_NIST_AES "\x09" // Not existing
|
||||||
|
#define OID_AES192_ECB OID_NIST_AES "\x15"
|
||||||
|
#define OID_AES192_CBC OID_NIST_AES "\x16"
|
||||||
|
#define OID_AES192_OFB OID_NIST_AES "\x17"
|
||||||
|
#define OID_AES192_CFB OID_NIST_AES "\x18"
|
||||||
|
#define OID_AES192_GCM OID_NIST_AES "\x1A"
|
||||||
|
#define OID_AES192_CCM OID_NIST_AES "\x1B"
|
||||||
|
#define OID_AES192_CTR OID_NIST_AES "\x1D" // Not existing
|
||||||
|
#define OID_AES256_ECB OID_NIST_AES "\x29"
|
||||||
|
#define OID_AES256_CBC OID_NIST_AES "\x2A"
|
||||||
|
#define OID_AES256_OFB OID_NIST_AES "\x2B"
|
||||||
|
#define OID_AES256_CFB OID_NIST_AES "\x2C"
|
||||||
|
#define OID_AES256_GCM OID_NIST_AES "\x2E"
|
||||||
|
#define OID_AES256_CCM OID_NIST_AES "\x2F"
|
||||||
|
#define OID_AES256_CTR OID_NIST_AES "\x31" // Not existing
|
||||||
|
|
||||||
|
#define OID_IEEE_ALG "\x2B\x6F\x02\x8C\x53\x00\x00\x01"
|
||||||
|
#define OID_AES128_XTS OID_IEEE_ALG "\x01"
|
||||||
|
#define OID_AES256_XTS OID_IEEE_ALG "\x02"
|
||||||
|
|
||||||
|
#define OID_HD "\x2B\x06\x01\x04\x01\x83\xA8\x78\x05\x8D\x6B"
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
313
src/hsm/sc_hsm.c
313
src/hsm/sc_hsm.c
@@ -17,15 +17,15 @@
|
|||||||
|
|
||||||
#include "sc_hsm.h"
|
#include "sc_hsm.h"
|
||||||
#include "files.h"
|
#include "files.h"
|
||||||
#include "common.h"
|
|
||||||
#include "version.h"
|
#include "version.h"
|
||||||
#include "crypto_utils.h"
|
#include "crypto_utils.h"
|
||||||
#include "kek.h"
|
#include "kek.h"
|
||||||
#include "eac.h"
|
#include "eac.h"
|
||||||
#include "cvc.h"
|
#include "cvc.h"
|
||||||
#include "asn1.h"
|
#include "asn1.h"
|
||||||
#include "hsm.h"
|
#include "pico_keys.h"
|
||||||
#include "usb.h"
|
#include "usb.h"
|
||||||
|
#include "random.h"
|
||||||
|
|
||||||
const uint8_t sc_hsm_aid[] = {
|
const uint8_t sc_hsm_aid[] = {
|
||||||
11,
|
11,
|
||||||
@@ -41,7 +41,7 @@ const uint8_t atr_sc_hsm[] = {
|
|||||||
uint8_t session_pin[32], session_sopin[32];
|
uint8_t session_pin[32], session_sopin[32];
|
||||||
bool has_session_pin = false, has_session_sopin = false;
|
bool has_session_pin = false, has_session_sopin = false;
|
||||||
const uint8_t *dev_name = NULL;
|
const uint8_t *dev_name = NULL;
|
||||||
size_t dev_name_len = 0;
|
uint16_t dev_name_len = 0;
|
||||||
|
|
||||||
static int sc_hsm_process_apdu();
|
static int sc_hsm_process_apdu();
|
||||||
|
|
||||||
@@ -51,6 +51,7 @@ static int sc_hsm_unload();
|
|||||||
extern int cmd_select();
|
extern int cmd_select();
|
||||||
extern void select_file(file_t *pe);
|
extern void select_file(file_t *pe);
|
||||||
extern int cmd_list_keys();
|
extern int cmd_list_keys();
|
||||||
|
|
||||||
extern int cmd_read_binary();
|
extern int cmd_read_binary();
|
||||||
extern int cmd_verify();
|
extern int cmd_verify();
|
||||||
extern int cmd_reset_retry();
|
extern int cmd_reset_retry();
|
||||||
@@ -75,93 +76,91 @@ extern int cmd_general_authenticate();
|
|||||||
extern int cmd_session_pin();
|
extern int cmd_session_pin();
|
||||||
extern int cmd_puk_auth();
|
extern int cmd_puk_auth();
|
||||||
extern int cmd_pso();
|
extern int cmd_pso();
|
||||||
|
extern int cmd_bip_slip();
|
||||||
|
|
||||||
extern const uint8_t *ccid_atr;
|
extern const uint8_t *ccid_atr;
|
||||||
|
|
||||||
app_t *sc_hsm_select_aid(app_t *a, const uint8_t *aid, uint8_t aid_len) {
|
int sc_hsm_select_aid(app_t *a) {
|
||||||
if (!memcmp(aid, sc_hsm_aid + 1, MIN(aid_len, sc_hsm_aid[0]))) {
|
a->process_apdu = sc_hsm_process_apdu;
|
||||||
a->aid = sc_hsm_aid;
|
a->unload = sc_hsm_unload;
|
||||||
a->process_apdu = sc_hsm_process_apdu;
|
init_sc_hsm();
|
||||||
a->unload = sc_hsm_unload;
|
return CCID_OK;
|
||||||
init_sc_hsm();
|
|
||||||
return a;
|
|
||||||
}
|
|
||||||
return NULL;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
void __attribute__((constructor)) sc_hsm_ctor() {
|
INITIALIZER( sc_hsm_ctor ) {
|
||||||
|
printf("INITIALIZER\n");
|
||||||
ccid_atr = atr_sc_hsm;
|
ccid_atr = atr_sc_hsm;
|
||||||
register_app(sc_hsm_select_aid);
|
register_app(sc_hsm_select_aid, sc_hsm_aid);
|
||||||
}
|
}
|
||||||
|
|
||||||
void scan_files() {
|
void scan_files() {
|
||||||
file_pin1 = search_by_fid(0x1081, NULL, SPECIFY_EF);
|
file_pin1 = search_file(EF_PIN1);
|
||||||
if (file_pin1) {
|
if (file_pin1) {
|
||||||
if (!file_pin1->data) {
|
if (!file_pin1->data) {
|
||||||
printf("PIN1 is empty. Initializing with default password\r\n");
|
printf("PIN1 is empty. Initializing with default password\n");
|
||||||
const uint8_t empty[33] = { 0 };
|
const uint8_t empty[33] = { 0 };
|
||||||
flash_write_data_to_file(file_pin1, empty, sizeof(empty));
|
file_put_data(file_pin1, empty, sizeof(empty));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
printf("FATAL ERROR: PIN1 not found in memory!\r\n");
|
printf("FATAL ERROR: PIN1 not found in memory!\n");
|
||||||
}
|
}
|
||||||
file_sopin = search_by_fid(0x1088, NULL, SPECIFY_EF);
|
file_sopin = search_file(EF_SOPIN);
|
||||||
if (file_sopin) {
|
if (file_sopin) {
|
||||||
if (!file_sopin->data) {
|
if (!file_sopin->data) {
|
||||||
printf("SOPIN is empty. Initializing with default password\r\n");
|
printf("SOPIN is empty. Initializing with default password\n");
|
||||||
const uint8_t empty[33] = { 0 };
|
const uint8_t empty[33] = { 0 };
|
||||||
flash_write_data_to_file(file_sopin, empty, sizeof(empty));
|
file_put_data(file_sopin, empty, sizeof(empty));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
printf("FATAL ERROR: SOPIN not found in memory!\r\n");
|
printf("FATAL ERROR: SOPIN not found in memory!\n");
|
||||||
}
|
}
|
||||||
file_retries_pin1 = search_by_fid(0x1083, NULL, SPECIFY_EF);
|
file_retries_pin1 = search_file(EF_PIN1_RETRIES);
|
||||||
if (file_retries_pin1) {
|
if (file_retries_pin1) {
|
||||||
if (!file_retries_pin1->data) {
|
if (!file_retries_pin1->data) {
|
||||||
printf("Retries PIN1 is empty. Initializing with default retriesr\n");
|
printf("Retries PIN1 is empty. Initializing with default retriesr\n");
|
||||||
const uint8_t retries = 3;
|
const uint8_t retries = 3;
|
||||||
flash_write_data_to_file(file_retries_pin1, &retries, sizeof(uint8_t));
|
file_put_data(file_retries_pin1, &retries, sizeof(uint8_t));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
printf("FATAL ERROR: Retries PIN1 not found in memory!\r\n");
|
printf("FATAL ERROR: Retries PIN1 not found in memory!\n");
|
||||||
}
|
}
|
||||||
file_retries_sopin = search_by_fid(0x108A, NULL, SPECIFY_EF);
|
file_retries_sopin = search_file(EF_SOPIN_RETRIES);
|
||||||
if (file_retries_sopin) {
|
if (file_retries_sopin) {
|
||||||
if (!file_retries_sopin->data) {
|
if (!file_retries_sopin->data) {
|
||||||
printf("Retries SOPIN is empty. Initializing with default retries\r\n");
|
printf("Retries SOPIN is empty. Initializing with default retries\n");
|
||||||
const uint8_t retries = 15;
|
const uint8_t retries = 15;
|
||||||
flash_write_data_to_file(file_retries_sopin, &retries, sizeof(uint8_t));
|
file_put_data(file_retries_sopin, &retries, sizeof(uint8_t));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
printf("FATAL ERROR: Retries SOPIN not found in memory!\r\n");
|
printf("FATAL ERROR: Retries SOPIN not found in memory!\n");
|
||||||
}
|
}
|
||||||
file_t *tf = NULL;
|
file_t *tf = NULL;
|
||||||
|
|
||||||
tf = search_by_fid(0x1082, NULL, SPECIFY_EF);
|
tf = search_file(EF_PIN1_MAX_RETRIES);
|
||||||
if (tf) {
|
if (tf) {
|
||||||
if (!tf->data) {
|
if (!tf->data) {
|
||||||
printf("Max retries PIN1 is empty. Initializing with default max retriesr\n");
|
printf("Max retries PIN1 is empty. Initializing with default max retriesr\n");
|
||||||
const uint8_t retries = 3;
|
const uint8_t retries = 3;
|
||||||
flash_write_data_to_file(tf, &retries, sizeof(uint8_t));
|
file_put_data(tf, &retries, sizeof(uint8_t));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
printf("FATAL ERROR: Max Retries PIN1 not found in memory!\r\n");
|
printf("FATAL ERROR: Max Retries PIN1 not found in memory!\n");
|
||||||
}
|
}
|
||||||
tf = search_by_fid(0x1089, NULL, SPECIFY_EF);
|
tf = search_file(EF_SOPIN_MAX_RETRIES);
|
||||||
if (tf) {
|
if (tf) {
|
||||||
if (!tf->data) {
|
if (!tf->data) {
|
||||||
printf("Max Retries SOPIN is empty. Initializing with default max retries\r\n");
|
printf("Max Retries SOPIN is empty. Initializing with default max retries\n");
|
||||||
const uint8_t retries = 15;
|
const uint8_t retries = 15;
|
||||||
flash_write_data_to_file(tf, &retries, sizeof(uint8_t));
|
file_put_data(tf, &retries, sizeof(uint8_t));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
printf("FATAL ERROR: Retries SOPIN not found in memory!\r\n");
|
printf("FATAL ERROR: Retries SOPIN not found in memory!\n");
|
||||||
}
|
}
|
||||||
low_flash_available();
|
low_flash_available();
|
||||||
}
|
}
|
||||||
@@ -176,7 +175,7 @@ int puk_store_entries = 0;
|
|||||||
PUK *current_puk = NULL;
|
PUK *current_puk = NULL;
|
||||||
uint8_t puk_status[MAX_PUK];
|
uint8_t puk_status[MAX_PUK];
|
||||||
|
|
||||||
int add_cert_puk_store(const uint8_t *data, size_t data_len, bool copy) {
|
int add_cert_puk_store(const uint8_t *data, uint16_t data_len, bool copy) {
|
||||||
if (data == NULL || data_len == 0) {
|
if (data == NULL || data_len == 0) {
|
||||||
return CCID_ERR_NULL_PARAM;
|
return CCID_ERR_NULL_PARAM;
|
||||||
}
|
}
|
||||||
@@ -218,11 +217,7 @@ int puk_store_select_chr(const uint8_t *chr) {
|
|||||||
return CCID_ERR_FILE_NOT_FOUND;
|
return CCID_ERR_FILE_NOT_FOUND;
|
||||||
}
|
}
|
||||||
|
|
||||||
void init_sc_hsm() {
|
void reset_puk_store() {
|
||||||
scan_all();
|
|
||||||
has_session_pin = has_session_sopin = false;
|
|
||||||
isUserAuthenticated = false;
|
|
||||||
cmd_select();
|
|
||||||
if (puk_store_entries > 0) { /* From previous session */
|
if (puk_store_entries > 0) { /* From previous session */
|
||||||
for (int i = 0; i < puk_store_entries; i++) {
|
for (int i = 0; i < puk_store_entries; i++) {
|
||||||
if (puk_store[i].copied == true) {
|
if (puk_store[i].copied == true) {
|
||||||
@@ -232,12 +227,19 @@ void init_sc_hsm() {
|
|||||||
}
|
}
|
||||||
memset(puk_store, 0, sizeof(puk_store));
|
memset(puk_store, 0, sizeof(puk_store));
|
||||||
puk_store_entries = 0;
|
puk_store_entries = 0;
|
||||||
file_t *fterm = search_by_fid(EF_TERMCA, NULL, SPECIFY_EF);
|
file_t *fterm = search_file(EF_TERMCA);
|
||||||
if (fterm) {
|
if (fterm) {
|
||||||
add_cert_puk_store(file_get_data(fterm), file_get_size(fterm), false);
|
uint8_t *p = NULL, *fterm_data = file_get_data(fterm), *pq = fterm_data;
|
||||||
|
uint16_t fterm_data_len = file_get_size(fterm);
|
||||||
|
asn1_ctx_t ctxi;
|
||||||
|
asn1_ctx_init(fterm_data, fterm_data_len, &ctxi);
|
||||||
|
while (walk_tlv(&ctxi, &p, NULL, NULL, NULL)) {
|
||||||
|
add_cert_puk_store(pq, (uint16_t)(p - pq), false);
|
||||||
|
pq = p;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
for (int i = 0; i < 0xfe; i++) {
|
for (int i = 0; i < 0xfe; i++) {
|
||||||
file_t *ef = search_dynamic_file((CA_CERTIFICATE_PREFIX << 8) | i);
|
file_t *ef = search_file((CA_CERTIFICATE_PREFIX << 8) | (uint8_t)i);
|
||||||
if (ef && file_get_size(ef) > 0) {
|
if (ef && file_get_size(ef) > 0) {
|
||||||
add_cert_puk_store(file_get_data(ef), file_get_size(ef), false);
|
add_cert_puk_store(file_get_data(ef), file_get_size(ef), false);
|
||||||
}
|
}
|
||||||
@@ -246,6 +248,14 @@ void init_sc_hsm() {
|
|||||||
memset(puk_status, 0, sizeof(puk_status));
|
memset(puk_status, 0, sizeof(puk_status));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
void init_sc_hsm() {
|
||||||
|
scan_all();
|
||||||
|
has_session_pin = has_session_sopin = false;
|
||||||
|
isUserAuthenticated = false;
|
||||||
|
cmd_select();
|
||||||
|
reset_puk_store();
|
||||||
|
}
|
||||||
|
|
||||||
int sc_hsm_unload() {
|
int sc_hsm_unload() {
|
||||||
has_session_pin = has_session_sopin = false;
|
has_session_pin = has_session_sopin = false;
|
||||||
isUserAuthenticated = false;
|
isUserAuthenticated = false;
|
||||||
@@ -254,9 +264,9 @@ int sc_hsm_unload() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
uint16_t get_device_options() {
|
uint16_t get_device_options() {
|
||||||
file_t *ef = search_by_fid(EF_DEVOPS, NULL, SPECIFY_EF);
|
file_t *ef = search_file(EF_DEVOPS);
|
||||||
if (file_has_data(ef)) {
|
if (file_has_data(ef)) {
|
||||||
return (file_read_uint8(file_get_data(ef)) << 8) | file_read_uint8(file_get_data(ef) + 1);
|
return (file_read_uint8(ef) << 8) | file_read_uint8_offset(ef, 1);
|
||||||
}
|
}
|
||||||
return 0x0;
|
return 0x0;
|
||||||
}
|
}
|
||||||
@@ -269,7 +279,7 @@ bool wait_button_pressed() {
|
|||||||
uint16_t opts = get_device_options();
|
uint16_t opts = get_device_options();
|
||||||
if (opts & HSM_OPT_BOOTSEL_BUTTON) {
|
if (opts & HSM_OPT_BOOTSEL_BUTTON) {
|
||||||
queue_try_add(&card_to_usb_q, &val);
|
queue_try_add(&card_to_usb_q, &val);
|
||||||
do {
|
do{
|
||||||
queue_remove_blocking(&usb_to_card_q, &val);
|
queue_remove_blocking(&usb_to_card_q, &val);
|
||||||
} while (val != EV_BUTTON_PRESSED && val != EV_BUTTON_TIMEOUT);
|
} while (val != EV_BUTTON_PRESSED && val != EV_BUTTON_TIMEOUT);
|
||||||
}
|
}
|
||||||
@@ -278,7 +288,12 @@ bool wait_button_pressed() {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int parse_token_info(const file_t *f, int mode) {
|
int parse_token_info(const file_t *f, int mode) {
|
||||||
|
(void)f;
|
||||||
|
#ifdef __FOR_CI
|
||||||
|
char *label = "SmartCard-HSM";
|
||||||
|
#else
|
||||||
char *label = "Pico-HSM";
|
char *label = "Pico-HSM";
|
||||||
|
#endif
|
||||||
char *manu = "Pol Henarejos";
|
char *manu = "Pol Henarejos";
|
||||||
if (mode == 1) {
|
if (mode == 1) {
|
||||||
uint8_t *p = res_APDU;
|
uint8_t *p = res_APDU;
|
||||||
@@ -286,34 +301,53 @@ int parse_token_info(const file_t *f, int mode) {
|
|||||||
*p++ = 0; //set later
|
*p++ = 0; //set later
|
||||||
*p++ = 0x2; *p++ = 1; *p++ = HSM_VERSION_MAJOR;
|
*p++ = 0x2; *p++ = 1; *p++ = HSM_VERSION_MAJOR;
|
||||||
#ifndef ENABLE_EMULATION
|
#ifndef ENABLE_EMULATION
|
||||||
*p++ = 0x4; *p++ = 8; pico_get_unique_board_id((pico_unique_board_id_t *) p); p += 8;
|
*p++ = 0x4; *p++ = 8; memcpy(p, pico_serial.id, 8); p += 8;
|
||||||
#else
|
#else
|
||||||
*p++ = 0x4; *p++ = 8; memset(p, 0, 8); p += 8;
|
*p++ = 0x4; *p++ = 8; memset(p, 0, 8); p += 8;
|
||||||
#endif
|
#endif
|
||||||
*p++ = 0xC; *p++ = strlen(manu); strcpy((char *) p, manu); p += strlen(manu);
|
*p++ = 0xC; *p++ = (uint8_t)strlen(manu); strcpy((char *) p, manu); p += strlen(manu);
|
||||||
*p++ = 0x80; *p++ = strlen(label); strcpy((char *) p, label); p += strlen(label);
|
*p++ = 0x80; *p++ = (uint8_t)strlen(label); strcpy((char *) p, label); p += strlen(label);
|
||||||
*p++ = 0x3; *p++ = 2; *p++ = 4; *p++ = 0x30;
|
*p++ = 0x3; *p++ = 2; *p++ = 4; *p++ = 0x30;
|
||||||
res_APDU_size = p - res_APDU;
|
res_APDU_size = (uint16_t)(p - res_APDU);
|
||||||
res_APDU[1] = res_APDU_size - 2;
|
res_APDU[1] = (uint8_t)res_APDU_size - 2;
|
||||||
}
|
}
|
||||||
return 2 + (2 + 1) + (2 + 8) + (2 + strlen(manu)) + (2 + strlen(label)) + (2 + 2);
|
return (int)(2 + (2 + 1) + (2 + 8) + (2 + strlen(manu)) + (2 + strlen(label)) + (2 + 2));
|
||||||
|
}
|
||||||
|
|
||||||
|
int parse_ef_dir(const file_t *f, int mode) {
|
||||||
|
(void)f;
|
||||||
|
#ifdef __FOR_CI
|
||||||
|
char *label = "SmartCard-HSM";
|
||||||
|
#else
|
||||||
|
char *label = "Pico-HSM";
|
||||||
|
#endif
|
||||||
|
if (mode == 1) {
|
||||||
|
uint8_t *p = res_APDU;
|
||||||
|
*p++ = 0x61;
|
||||||
|
*p++ = 0; //set later
|
||||||
|
*p++ = 0x4F; *p++ = sc_hsm_aid[0]; memcpy(p, sc_hsm_aid + 1, sc_hsm_aid[0]); p += sc_hsm_aid[0];
|
||||||
|
*p++ = 0x50; *p++ = (uint8_t)strlen(label); strcpy((char *) p, label); p += strlen(label);
|
||||||
|
res_APDU_size = (uint16_t)(p - res_APDU);
|
||||||
|
res_APDU[1] = (uint8_t)res_APDU_size - 2;
|
||||||
|
}
|
||||||
|
return (int)(2 + (2 + sc_hsm_aid[0]) + (2 + strlen(label)));
|
||||||
}
|
}
|
||||||
|
|
||||||
int pin_reset_retries(const file_t *pin, bool force) {
|
int pin_reset_retries(const file_t *pin, bool force) {
|
||||||
if (!pin) {
|
if (!pin) {
|
||||||
return CCID_ERR_NULL_PARAM;
|
return CCID_ERR_NULL_PARAM;
|
||||||
}
|
}
|
||||||
const file_t *max = search_by_fid(pin->fid + 1, NULL, SPECIFY_EF);
|
const file_t *max = search_file(pin->fid + 1);
|
||||||
const file_t *act = search_by_fid(pin->fid + 2, NULL, SPECIFY_EF);
|
const file_t *act = search_file(pin->fid + 2);
|
||||||
if (!max || !act) {
|
if (!max || !act) {
|
||||||
return CCID_ERR_FILE_NOT_FOUND;
|
return CCID_ERR_FILE_NOT_FOUND;
|
||||||
}
|
}
|
||||||
uint8_t retries = file_read_uint8(file_get_data(act));
|
uint8_t retries = file_read_uint8(act);
|
||||||
if (retries == 0 && force == false) { //blocked
|
if (retries == 0 && force == false) { // blocked
|
||||||
return CCID_ERR_BLOCKED;
|
return CCID_ERR_BLOCKED;
|
||||||
}
|
}
|
||||||
retries = file_read_uint8(file_get_data(max));
|
retries = file_read_uint8(max);
|
||||||
int r = flash_write_data_to_file((file_t *) act, &retries, sizeof(retries));
|
int r = file_put_data((file_t *) act, &retries, sizeof(retries));
|
||||||
low_flash_available();
|
low_flash_available();
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
@@ -322,14 +356,14 @@ int pin_wrong_retry(const file_t *pin) {
|
|||||||
if (!pin) {
|
if (!pin) {
|
||||||
return CCID_ERR_NULL_PARAM;
|
return CCID_ERR_NULL_PARAM;
|
||||||
}
|
}
|
||||||
const file_t *act = search_by_fid(pin->fid + 2, NULL, SPECIFY_EF);
|
const file_t *act = search_file(pin->fid + 2);
|
||||||
if (!act) {
|
if (!act) {
|
||||||
return CCID_ERR_FILE_NOT_FOUND;
|
return CCID_ERR_FILE_NOT_FOUND;
|
||||||
}
|
}
|
||||||
uint8_t retries = file_read_uint8(file_get_data(act));
|
uint8_t retries = file_read_uint8(act);
|
||||||
if (retries > 0) {
|
if (retries > 0) {
|
||||||
retries -= 1;
|
retries -= 1;
|
||||||
int r = flash_write_data_to_file((file_t *) act, &retries, sizeof(retries));
|
int r = file_put_data((file_t *) act, &retries, sizeof(retries));
|
||||||
if (r != CCID_OK) {
|
if (r != CCID_OK) {
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
@@ -343,11 +377,11 @@ int pin_wrong_retry(const file_t *pin) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bool pka_enabled() {
|
bool pka_enabled() {
|
||||||
file_t *ef_puk = search_by_fid(EF_PUKAUT, NULL, SPECIFY_EF);
|
file_t *ef_puk = search_file(EF_PUKAUT);
|
||||||
return file_has_data(ef_puk) && file_read_uint8(file_get_data(ef_puk)) > 0;
|
return file_has_data(ef_puk) && file_read_uint8(ef_puk) > 0;
|
||||||
}
|
}
|
||||||
|
|
||||||
int check_pin(const file_t *pin, const uint8_t *data, size_t len) {
|
uint16_t check_pin(const file_t *pin, const uint8_t *data, uint16_t len) {
|
||||||
if (!file_has_data((file_t *) pin)) {
|
if (!file_has_data((file_t *) pin)) {
|
||||||
return SW_REFERENCE_NOT_FOUND();
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
}
|
}
|
||||||
@@ -361,13 +395,13 @@ int check_pin(const file_t *pin, const uint8_t *data, size_t len) {
|
|||||||
if ((retries = pin_wrong_retry(pin)) < CCID_OK) {
|
if ((retries = pin_wrong_retry(pin)) < CCID_OK) {
|
||||||
return SW_PIN_BLOCKED();
|
return SW_PIN_BLOCKED();
|
||||||
}
|
}
|
||||||
return set_res_sw(0x63, 0xc0 | retries);
|
return set_res_sw(0x63, 0xc0 | (uint8_t)retries);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
uint8_t dhash[32];
|
uint8_t dhash[32];
|
||||||
double_hash_pin(data, len, dhash);
|
double_hash_pin(data, len, dhash);
|
||||||
if (sizeof(dhash) != file_get_size(pin) - 1) { //1 byte for pin len
|
if (sizeof(dhash) != file_get_size(pin) - 1) { // 1 byte for pin len
|
||||||
return SW_CONDITIONS_NOT_SATISFIED();
|
return SW_CONDITIONS_NOT_SATISFIED();
|
||||||
}
|
}
|
||||||
if (memcmp(file_get_data(pin) + 1, dhash, sizeof(dhash)) != 0) {
|
if (memcmp(file_get_data(pin) + 1, dhash, sizeof(dhash)) != 0) {
|
||||||
@@ -375,7 +409,7 @@ int check_pin(const file_t *pin, const uint8_t *data, size_t len) {
|
|||||||
if ((retries = pin_wrong_retry(pin)) < CCID_OK) {
|
if ((retries = pin_wrong_retry(pin)) < CCID_OK) {
|
||||||
return SW_PIN_BLOCKED();
|
return SW_PIN_BLOCKED();
|
||||||
}
|
}
|
||||||
return set_res_sw(0x63, 0xc0 | retries);
|
return set_res_sw(0x63, 0xc0 | (uint8_t)retries);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
int r = pin_reset_retries(pin, false);
|
int r = pin_reset_retries(pin, false);
|
||||||
@@ -396,19 +430,25 @@ int check_pin(const file_t *pin, const uint8_t *data, size_t len) {
|
|||||||
hash_multi(data, len, session_sopin);
|
hash_multi(data, len, session_sopin);
|
||||||
has_session_sopin = true;
|
has_session_sopin = true;
|
||||||
}
|
}
|
||||||
|
if (pending_save_dkek != 0xff) {
|
||||||
|
save_dkek_key(pending_save_dkek, NULL);
|
||||||
|
pending_save_dkek = 0xff;
|
||||||
|
}
|
||||||
return SW_OK();
|
return SW_OK();
|
||||||
}
|
}
|
||||||
|
|
||||||
const uint8_t *get_meta_tag(file_t *ef, uint16_t meta_tag, size_t *tag_len) {
|
const uint8_t *get_meta_tag(file_t *ef, uint16_t meta_tag, uint16_t *tag_len) {
|
||||||
if (ef == NULL) {
|
if (ef == NULL) {
|
||||||
return NULL;
|
return NULL;
|
||||||
}
|
}
|
||||||
uint8_t *meta_data = NULL;
|
uint8_t *meta_data = NULL;
|
||||||
uint8_t meta_size = meta_find(ef->fid, &meta_data);
|
uint16_t meta_size = meta_find(ef->fid, &meta_data);
|
||||||
if (meta_size > 0 && meta_data != NULL) {
|
if (meta_size > 0 && meta_data != NULL) {
|
||||||
uint16_t tag = 0x0;
|
uint16_t tag = 0x0;
|
||||||
uint8_t *tag_data = NULL, *p = NULL;
|
uint8_t *tag_data = NULL, *p = NULL;
|
||||||
while (walk_tlv(meta_data, meta_size, &p, &tag, tag_len, &tag_data)) {
|
asn1_ctx_t ctxi;
|
||||||
|
asn1_ctx_init(meta_data, meta_size, &ctxi);
|
||||||
|
while (walk_tlv(&ctxi, &p, &tag, tag_len, &tag_data)) {
|
||||||
if (tag == meta_tag) {
|
if (tag == meta_tag) {
|
||||||
return tag_data;
|
return tag_data;
|
||||||
}
|
}
|
||||||
@@ -418,7 +458,7 @@ const uint8_t *get_meta_tag(file_t *ef, uint16_t meta_tag, size_t *tag_len) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
uint32_t get_key_counter(file_t *fkey) {
|
uint32_t get_key_counter(file_t *fkey) {
|
||||||
size_t tag_len = 0;
|
uint16_t tag_len = 0;
|
||||||
const uint8_t *meta_tag = get_meta_tag(fkey, 0x90, &tag_len);
|
const uint8_t *meta_tag = get_meta_tag(fkey, 0x90, &tag_len);
|
||||||
if (meta_tag) {
|
if (meta_tag) {
|
||||||
return (meta_tag[0] << 24) | (meta_tag[1] << 16) | (meta_tag[2] << 8) | meta_tag[3];
|
return (meta_tag[0] << 24) | (meta_tag[1] << 16) | (meta_tag[2] << 8) | meta_tag[3];
|
||||||
@@ -427,10 +467,10 @@ uint32_t get_key_counter(file_t *fkey) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
bool key_has_purpose(file_t *ef, uint8_t purpose) {
|
bool key_has_purpose(file_t *ef, uint8_t purpose) {
|
||||||
size_t tag_len = 0;
|
uint16_t tag_len = 0;
|
||||||
const uint8_t *meta_tag = get_meta_tag(ef, 0x91, &tag_len);
|
const uint8_t *meta_tag = get_meta_tag(ef, 0x91, &tag_len);
|
||||||
if (meta_tag) {
|
if (meta_tag) {
|
||||||
for (int i = 0; i < tag_len; i++) {
|
for (unsigned i = 0; i < tag_len; i++) {
|
||||||
if (meta_tag[i] == purpose) {
|
if (meta_tag[i] == purpose) {
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
@@ -445,16 +485,18 @@ uint32_t decrement_key_counter(file_t *fkey) {
|
|||||||
return 0xffffff;
|
return 0xffffff;
|
||||||
}
|
}
|
||||||
uint8_t *meta_data = NULL;
|
uint8_t *meta_data = NULL;
|
||||||
uint8_t meta_size = meta_find(fkey->fid, &meta_data);
|
uint16_t meta_size = meta_find(fkey->fid, &meta_data);
|
||||||
if (meta_size > 0 && meta_data != NULL) {
|
if (meta_size > 0 && meta_data != NULL) {
|
||||||
uint16_t tag = 0x0;
|
uint16_t tag = 0x0;
|
||||||
uint8_t *tag_data = NULL, *p = NULL;
|
uint8_t *tag_data = NULL, *p = NULL;
|
||||||
size_t tag_len = 0;
|
uint16_t tag_len = 0;
|
||||||
uint8_t *cmeta = (uint8_t *) calloc(1, meta_size);
|
uint8_t *cmeta = (uint8_t *) calloc(1, meta_size);
|
||||||
/* We cannot modify meta_data, as it comes from flash memory. It must be cpied to an aux buffer */
|
/* We cannot modify meta_data, as it comes from flash memory. It must be cpied to an aux buffer */
|
||||||
memcpy(cmeta, meta_data, meta_size);
|
memcpy(cmeta, meta_data, meta_size);
|
||||||
while (walk_tlv(cmeta, meta_size, &p, &tag, &tag_len, &tag_data)) {
|
asn1_ctx_t ctxi;
|
||||||
if (tag == 0x90) { //ofset tag
|
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 =
|
uint32_t val =
|
||||||
(tag_data[0] << 24) | (tag_data[1] << 16) | (tag_data[2] << 8) | tag_data[3];
|
(tag_data[0] << 24) | (tag_data[1] << 16) | (tag_data[2] << 8) | tag_data[3];
|
||||||
val--;
|
val--;
|
||||||
@@ -463,7 +505,7 @@ uint32_t decrement_key_counter(file_t *fkey) {
|
|||||||
tag_data[2] = (val >> 8) & 0xff;
|
tag_data[2] = (val >> 8) & 0xff;
|
||||||
tag_data[3] = val & 0xff;
|
tag_data[3] = val & 0xff;
|
||||||
|
|
||||||
int r = meta_add(fkey->fid, cmeta, meta_size);
|
int r = meta_add(fkey->fid, cmeta, (uint16_t)meta_size);
|
||||||
free(cmeta);
|
free(cmeta);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
return 0xffffffff;
|
return 0xffffffff;
|
||||||
@@ -477,33 +519,37 @@ uint32_t decrement_key_counter(file_t *fkey) {
|
|||||||
return 0xffffffff;
|
return 0xffffffff;
|
||||||
}
|
}
|
||||||
|
|
||||||
//Stores the private and public keys in flash
|
// Stores the private and public keys in flash
|
||||||
int store_keys(void *key_ctx, int type, uint8_t key_id) {
|
int store_keys(void *key_ctx, int type, uint8_t key_id) {
|
||||||
int r, key_size = 0;
|
int r = 0;
|
||||||
uint8_t kdata[4096 / 8]; //worst case
|
uint16_t key_size = 0;
|
||||||
if (type == HSM_KEY_RSA) {
|
uint8_t kdata[4096 / 8]; // worst case
|
||||||
|
if (type & PICO_KEYS_KEY_RSA) {
|
||||||
mbedtls_rsa_context *rsa = (mbedtls_rsa_context *) key_ctx;
|
mbedtls_rsa_context *rsa = (mbedtls_rsa_context *) key_ctx;
|
||||||
key_size = mbedtls_mpi_size(&rsa->P) + mbedtls_mpi_size(&rsa->Q);
|
key_size = (uint16_t)mbedtls_mpi_size(&rsa->P) + (uint16_t)mbedtls_mpi_size(&rsa->Q);
|
||||||
mbedtls_mpi_write_binary(&rsa->P, kdata, key_size / 2);
|
mbedtls_mpi_write_binary(&rsa->P, kdata, key_size / 2);
|
||||||
mbedtls_mpi_write_binary(&rsa->Q, kdata + key_size / 2, key_size / 2);
|
mbedtls_mpi_write_binary(&rsa->Q, kdata + key_size / 2, key_size / 2);
|
||||||
}
|
}
|
||||||
else if (type == HSM_KEY_EC) {
|
else if (type & PICO_KEYS_KEY_EC) {
|
||||||
mbedtls_ecdsa_context *ecdsa = (mbedtls_ecdsa_context *) key_ctx;
|
mbedtls_ecdsa_context *ecdsa = (mbedtls_ecdsa_context *) key_ctx;
|
||||||
key_size = mbedtls_mpi_size(&ecdsa->d);
|
size_t olen = 0;
|
||||||
kdata[0] = ecdsa->grp.id & 0xff;
|
kdata[0] = ecdsa->grp.id & 0xff;
|
||||||
mbedtls_mpi_write_binary(&ecdsa->d, kdata + 1, key_size);
|
mbedtls_ecp_write_key_ext(ecdsa, &olen, kdata + 1, sizeof(kdata) - 1);
|
||||||
key_size++;
|
key_size = olen + 1;
|
||||||
}
|
}
|
||||||
else if (type & HSM_KEY_AES) {
|
else if (type & PICO_KEYS_KEY_AES) {
|
||||||
if (type == HSM_KEY_AES_128) {
|
if (type == PICO_KEYS_KEY_AES_128) {
|
||||||
key_size = 16;
|
key_size = 16;
|
||||||
}
|
}
|
||||||
else if (type == HSM_KEY_AES_192) {
|
else if (type == PICO_KEYS_KEY_AES_192) {
|
||||||
key_size = 24;
|
key_size = 24;
|
||||||
}
|
}
|
||||||
else if (type == HSM_KEY_AES_256) {
|
else if (type == PICO_KEYS_KEY_AES_256) {
|
||||||
key_size = 32;
|
key_size = 32;
|
||||||
}
|
}
|
||||||
|
else if (type == PICO_KEYS_KEY_AES_512) {
|
||||||
|
key_size = 64;
|
||||||
|
}
|
||||||
memcpy(kdata, key_ctx, key_size);
|
memcpy(kdata, key_ctx, key_size);
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
@@ -517,46 +563,56 @@ int store_keys(void *key_ctx, int type, uint8_t key_id) {
|
|||||||
if (r != CCID_OK) {
|
if (r != CCID_OK) {
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
r = flash_write_data_to_file(fpk, kdata, key_size);
|
r = file_put_data(fpk, kdata, (uint16_t)key_size);
|
||||||
if (r != CCID_OK) {
|
if (r != CCID_OK) {
|
||||||
return r;
|
return r;
|
||||||
}
|
}
|
||||||
|
char key_id_str[4] = {0};
|
||||||
|
sprintf(key_id_str, "%u", key_id);
|
||||||
|
if (type & PICO_KEYS_KEY_EC) {
|
||||||
|
key_size--;
|
||||||
|
}
|
||||||
|
uint16_t prkd_len = asn1_build_prkd_generic(NULL, 0, (uint8_t *)key_id_str, (uint16_t)strlen(key_id_str), key_size * 8, type, kdata, sizeof(kdata));
|
||||||
|
if (prkd_len > 0) {
|
||||||
|
fpk = file_new((PRKD_PREFIX << 8) | key_id);
|
||||||
|
r = file_put_data(fpk, kdata, prkd_len);
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
}
|
||||||
low_flash_available();
|
low_flash_available();
|
||||||
return CCID_OK;
|
return CCID_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
int find_and_store_meta_key(uint8_t key_id) {
|
int find_and_store_meta_key(uint8_t key_id) {
|
||||||
size_t lt[4] = { 0, 0, 0, 0 }, meta_size = 0;
|
uint16_t meta_size = 0;
|
||||||
uint8_t *pt[4] = { NULL, NULL, NULL, NULL };
|
|
||||||
uint8_t t90[4] = { 0xFF, 0xFF, 0xFF, 0xFE };
|
uint8_t t90[4] = { 0xFF, 0xFF, 0xFF, 0xFE };
|
||||||
for (int t = 0; t < 4; t++) {
|
asn1_ctx_t ctxi, ctxo[4] = { 0 };
|
||||||
uint8_t *ptt = NULL;
|
asn1_ctx_init(apdu.data, (uint16_t)apdu.nc, &ctxi);
|
||||||
size_t ltt = 0;
|
for (uint16_t t = 0; t < 4; t++) {
|
||||||
if (asn1_find_tag(apdu.data, apdu.nc, 0x90 + t, <t, &ptt) && ptt != NULL && ltt > 0) {
|
if (asn1_find_tag(&ctxi, 0x90 + t, &ctxo[t]) && asn1_len(&ctxo[t]) > 0) {
|
||||||
lt[t] = ltt;
|
meta_size += asn1_len_tag(0x90 + t, ctxo[t].len);
|
||||||
pt[t] = ptt;
|
|
||||||
meta_size += asn1_len_tag(0x90 + t, lt[t]);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (lt[0] == 0 && pt[0] == NULL) {
|
if (asn1_len(&ctxo[0]) == 0) {
|
||||||
uint16_t opts = get_device_options();
|
uint16_t opts = get_device_options();
|
||||||
if (opts & HSM_OPT_KEY_COUNTER_ALL) {
|
if (opts & HSM_OPT_KEY_COUNTER_ALL) {
|
||||||
lt[0] = 4;
|
ctxo[0].len = 4;
|
||||||
pt[0] = t90;
|
ctxo[0].data = t90;
|
||||||
meta_size += 6;
|
meta_size += 6;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
if (meta_size) {
|
if (meta_size) {
|
||||||
uint8_t *meta = (uint8_t *) calloc(1, meta_size), *m = meta;
|
uint8_t *meta = (uint8_t *) calloc(1, meta_size), *m = meta;
|
||||||
for (int t = 0; t < 4; t++) {
|
for (uint8_t t = 0; t < 4; t++) {
|
||||||
if (lt[t] > 0 && pt[t] != NULL) {
|
if (asn1_len(&ctxo[t]) > 0) {
|
||||||
*m++ = 0x90 + t;
|
*m++ = 0x90 + t;
|
||||||
m += format_tlv_len(lt[t], m);
|
m += format_tlv_len(ctxo[t].len, m);
|
||||||
memcpy(m, pt[t], lt[t]);
|
memcpy(m, ctxo[t].data, ctxo[t].len);
|
||||||
m += lt[t];
|
m += ctxo[t].len;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
int r = meta_add((KEY_PREFIX << 8) | key_id, meta, meta_size);
|
int r = meta_add((KEY_PREFIX << 8) | key_id, meta, (uint16_t)meta_size);
|
||||||
free(meta);
|
free(meta);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
return CCID_EXEC_ERROR;
|
return CCID_EXEC_ERROR;
|
||||||
@@ -566,11 +622,11 @@ int find_and_store_meta_key(uint8_t key_id) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
int load_private_key_rsa(mbedtls_rsa_context *ctx, file_t *fkey) {
|
int load_private_key_rsa(mbedtls_rsa_context *ctx, file_t *fkey) {
|
||||||
if (wait_button_pressed() == true) { //timeout
|
if (wait_button_pressed() == true) { // timeout
|
||||||
return CCID_VERIFICATION_FAILED;
|
return CCID_VERIFICATION_FAILED;
|
||||||
}
|
}
|
||||||
|
|
||||||
int key_size = file_get_size(fkey);
|
uint16_t key_size = file_get_size(fkey);
|
||||||
uint8_t kdata[4096 / 8];
|
uint8_t kdata[4096 / 8];
|
||||||
memcpy(kdata, file_get_data(fkey), key_size);
|
memcpy(kdata, file_get_data(fkey), key_size);
|
||||||
if (mkek_decrypt(kdata, key_size) != 0) {
|
if (mkek_decrypt(kdata, key_size) != 0) {
|
||||||
@@ -609,13 +665,13 @@ int load_private_key_rsa(mbedtls_rsa_context *ctx, file_t *fkey) {
|
|||||||
return CCID_OK;
|
return CCID_OK;
|
||||||
}
|
}
|
||||||
|
|
||||||
int load_private_key_ecdsa(mbedtls_ecdsa_context *ctx, file_t *fkey) {
|
int load_private_key_ec(mbedtls_ecp_keypair *ctx, file_t *fkey) {
|
||||||
if (wait_button_pressed() == true) { //timeout
|
if (wait_button_pressed() == true) { // timeout
|
||||||
return CCID_VERIFICATION_FAILED;
|
return CCID_VERIFICATION_FAILED;
|
||||||
}
|
}
|
||||||
|
|
||||||
int key_size = file_get_size(fkey);
|
uint16_t key_size = file_get_size(fkey);
|
||||||
uint8_t kdata[67]; //Worst case, 521 bit + 1byte
|
uint8_t kdata[67]; // Worst case, 521 bit + 1byte
|
||||||
memcpy(kdata, file_get_data(fkey), key_size);
|
memcpy(kdata, file_get_data(fkey), key_size);
|
||||||
if (mkek_decrypt(kdata, key_size) != 0) {
|
if (mkek_decrypt(kdata, key_size) != 0) {
|
||||||
return CCID_EXEC_ERROR;
|
return CCID_EXEC_ERROR;
|
||||||
@@ -624,12 +680,25 @@ int load_private_key_ecdsa(mbedtls_ecdsa_context *ctx, file_t *fkey) {
|
|||||||
int r = mbedtls_ecp_read_key(gid, ctx, kdata + 1, key_size - 1);
|
int r = mbedtls_ecp_read_key(gid, ctx, kdata + 1, key_size - 1);
|
||||||
if (r != 0) {
|
if (r != 0) {
|
||||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
mbedtls_ecdsa_free(ctx);
|
mbedtls_ecp_keypair_free(ctx);
|
||||||
return CCID_EXEC_ERROR;
|
return CCID_EXEC_ERROR;
|
||||||
}
|
}
|
||||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
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 {
|
||||||
|
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 CCID_OK;
|
return CCID_OK;
|
||||||
}
|
}
|
||||||
|
int load_private_key_ecdh(mbedtls_ecp_keypair *ctx, file_t *fkey) {
|
||||||
|
return load_private_key_ec(ctx, fkey);
|
||||||
|
}
|
||||||
|
|
||||||
#define INS_VERIFY 0x20
|
#define INS_VERIFY 0x20
|
||||||
#define INS_MSE 0x22
|
#define INS_MSE 0x22
|
||||||
@@ -638,6 +707,7 @@ int load_private_key_ecdsa(mbedtls_ecdsa_context *ctx, file_t *fkey) {
|
|||||||
#define INS_RESET_RETRY 0x2C
|
#define INS_RESET_RETRY 0x2C
|
||||||
#define INS_KEYPAIR_GEN 0x46
|
#define INS_KEYPAIR_GEN 0x46
|
||||||
#define INS_KEY_GEN 0x48
|
#define INS_KEY_GEN 0x48
|
||||||
|
#define INS_BIP_SLIP 0x4A
|
||||||
#define INS_INITIALIZE 0x50
|
#define INS_INITIALIZE 0x50
|
||||||
#define INS_KEY_DOMAIN 0x52
|
#define INS_KEY_DOMAIN 0x52
|
||||||
#define INS_PUK_AUTH 0x54
|
#define INS_PUK_AUTH 0x54
|
||||||
@@ -687,6 +757,7 @@ static const cmd_t cmds[] = {
|
|||||||
{ INS_PUK_AUTH, cmd_puk_auth },
|
{ INS_PUK_AUTH, cmd_puk_auth },
|
||||||
{ INS_PSO, cmd_pso },
|
{ INS_PSO, cmd_pso },
|
||||||
{ INS_EXTERNAL_AUTHENTICATE, cmd_external_authenticate },
|
{ INS_EXTERNAL_AUTHENTICATE, cmd_external_authenticate },
|
||||||
|
{ INS_BIP_SLIP, cmd_bip_slip },
|
||||||
{ 0x00, 0x0 }
|
{ 0x00, 0x0 }
|
||||||
};
|
};
|
||||||
|
|
||||||
@@ -697,9 +768,9 @@ int sc_hsm_process_apdu() {
|
|||||||
}
|
}
|
||||||
for (const cmd_t *cmd = cmds; cmd->ins != 0x00; cmd++) {
|
for (const cmd_t *cmd = cmds; cmd->ins != 0x00; cmd++) {
|
||||||
if (cmd->ins == INS(apdu)) {
|
if (cmd->ins == INS(apdu)) {
|
||||||
int r = cmd->cmd_handler();
|
int res = cmd->cmd_handler();
|
||||||
sm_wrap();
|
sm_wrap();
|
||||||
return r;
|
return res;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return SW_INS_NOT_SUPPORTED();
|
return SW_INS_NOT_SUPPORTED();
|
||||||
|
|||||||
@@ -19,15 +19,19 @@
|
|||||||
#define _SC_HSM_H_
|
#define _SC_HSM_H_
|
||||||
|
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
|
#ifndef ESP_PLATFORM
|
||||||
#include "common.h"
|
#include "common.h"
|
||||||
|
#else
|
||||||
|
#define MBEDTLS_ALLOW_PRIVATE_ACCESS
|
||||||
|
#endif
|
||||||
#include "mbedtls/rsa.h"
|
#include "mbedtls/rsa.h"
|
||||||
#include "mbedtls/ecdsa.h"
|
#include "mbedtls/ecdsa.h"
|
||||||
#ifndef ENABLE_EMULATION
|
#if !defined(ENABLE_EMULATION) && !defined(ESP_PLATFORM)
|
||||||
#include "pico/stdlib.h"
|
#include "pico/stdlib.h"
|
||||||
#endif
|
#endif
|
||||||
#include "file.h"
|
#include "file.h"
|
||||||
#include "apdu.h"
|
#include "apdu.h"
|
||||||
#include "hsm.h"
|
#include "pico_keys.h"
|
||||||
|
|
||||||
extern const uint8_t sc_hsm_aid[];
|
extern const uint8_t sc_hsm_aid[];
|
||||||
|
|
||||||
@@ -58,6 +62,7 @@ extern const uint8_t sc_hsm_aid[];
|
|||||||
#define ALGO_EC_DH 0x80 /* ECDH key derivation */
|
#define ALGO_EC_DH 0x80 /* ECDH key derivation */
|
||||||
#define ALGO_EC_DH_AUTPUK 0x83
|
#define ALGO_EC_DH_AUTPUK 0x83
|
||||||
#define ALGO_EC_DH_XKEK 0x84
|
#define ALGO_EC_DH_XKEK 0x84
|
||||||
|
#define ALGO_HD 0xA0
|
||||||
|
|
||||||
#define ALGO_WRAP 0x92
|
#define ALGO_WRAP 0x92
|
||||||
#define ALGO_UNWRAP 0x93
|
#define ALGO_UNWRAP 0x93
|
||||||
@@ -101,23 +106,22 @@ extern const uint8_t sc_hsm_aid[];
|
|||||||
extern int pin_reset_retries(const file_t *pin, bool);
|
extern int pin_reset_retries(const file_t *pin, bool);
|
||||||
extern int pin_wrong_retry(const file_t *pin);
|
extern int pin_wrong_retry(const file_t *pin);
|
||||||
|
|
||||||
extern void hash(const uint8_t *input, size_t len, uint8_t output[32]);
|
extern void hash(const uint8_t *input, uint16_t len, uint8_t output[32]);
|
||||||
extern void hash_multi(const uint8_t *input, size_t len, uint8_t output[32]);
|
|
||||||
extern void double_hash_pin(const uint8_t *pin, size_t len, uint8_t output[32]);
|
|
||||||
extern uint16_t get_device_options();
|
extern uint16_t get_device_options();
|
||||||
extern bool has_session_pin, has_session_sopin;
|
extern bool has_session_pin, has_session_sopin;
|
||||||
extern uint8_t session_pin[32], session_sopin[32];
|
extern uint8_t session_pin[32], session_sopin[32];
|
||||||
extern int check_pin(const file_t *pin, const uint8_t *data, size_t len);
|
extern uint16_t check_pin(const file_t *pin, const uint8_t *data, uint16_t len);
|
||||||
extern bool pka_enabled();
|
extern bool pka_enabled();
|
||||||
extern const uint8_t *dev_name;
|
extern const uint8_t *dev_name;
|
||||||
extern size_t dev_name_len;
|
extern uint16_t dev_name_len;
|
||||||
extern uint8_t puk_status[MAX_PUK];
|
extern uint8_t puk_status[MAX_PUK];
|
||||||
extern int puk_store_select_chr(const uint8_t *chr);
|
extern int puk_store_select_chr(const uint8_t *chr);
|
||||||
extern int delete_file(file_t *ef);
|
extern int delete_file(file_t *ef);
|
||||||
extern const uint8_t *get_meta_tag(file_t *ef, uint16_t meta_tag, size_t *tag_len);
|
extern const uint8_t *get_meta_tag(file_t *ef, uint16_t meta_tag, uint16_t *tag_len);
|
||||||
extern bool key_has_purpose(file_t *ef, uint8_t purpose);
|
extern bool key_has_purpose(file_t *ef, uint8_t purpose);
|
||||||
extern int load_private_key_rsa(mbedtls_rsa_context *ctx, file_t *fkey);
|
extern int load_private_key_rsa(mbedtls_rsa_context *ctx, file_t *fkey);
|
||||||
extern int load_private_key_ecdsa(mbedtls_ecdsa_context *ctx, file_t *fkey);
|
extern int load_private_key_ec(mbedtls_ecp_keypair *ctx, file_t *fkey);
|
||||||
|
extern int load_private_key_ecdh(mbedtls_ecp_keypair *ctx, file_t *fkey);
|
||||||
extern bool wait_button_pressed();
|
extern bool wait_button_pressed();
|
||||||
extern int store_keys(void *key_ctx, int type, uint8_t key_id);
|
extern int store_keys(void *key_ctx, int type, uint8_t key_id);
|
||||||
extern int find_and_store_meta_key(uint8_t key_id);
|
extern int find_and_store_meta_key(uint8_t key_id);
|
||||||
|
|||||||
@@ -18,7 +18,7 @@
|
|||||||
#ifndef __VERSION_H_
|
#ifndef __VERSION_H_
|
||||||
#define __VERSION_H_
|
#define __VERSION_H_
|
||||||
|
|
||||||
#define HSM_VERSION 0x0304
|
#define HSM_VERSION 0x0400
|
||||||
|
|
||||||
#define HSM_VERSION_MAJOR ((HSM_VERSION >> 8) & 0xff)
|
#define HSM_VERSION_MAJOR ((HSM_VERSION >> 8) & 0xff)
|
||||||
#define HSM_VERSION_MINOR (HSM_VERSION & 0xff)
|
#define HSM_VERSION_MINOR (HSM_VERSION & 0xff)
|
||||||
|
|||||||
@@ -1,7 +1,14 @@
|
|||||||
#!/bin/bash -eu
|
#!/bin/bash -eu
|
||||||
|
|
||||||
source tests/docker_env.sh
|
source tests/docker_env.sh
|
||||||
|
build_image
|
||||||
#run_in_docker rm -rf CMakeFiles
|
#run_in_docker rm -rf CMakeFiles
|
||||||
run_in_docker mkdir -p build_in_docker
|
run_in_docker mkdir -p build_in_docker
|
||||||
run_in_docker -w "$PWD/build_in_docker" cmake -DENABLE_EMULATION=1 ..
|
run_in_docker -w "$PWD/build_in_docker" cmake -DENABLE_EMULATION=1 -D__FOR_CI=1 ..
|
||||||
run_in_docker -w "$PWD/build_in_docker" make -j ${NUM_PROC}
|
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
|
||||||
|
docker commit temp_container pico-hsm-test:bullseye
|
||||||
|
docker stop temp_container
|
||||||
|
docker rm temp_container
|
||||||
|
docker image prune -f
|
||||||
|
|||||||
@@ -19,491 +19,15 @@
|
|||||||
|
|
||||||
import sys
|
import sys
|
||||||
import pytest
|
import pytest
|
||||||
import os
|
|
||||||
from binascii import hexlify
|
|
||||||
from utils import APDUResponse, DOPrefixes, KeyType, Algorithm, Padding, int_to_bytes
|
|
||||||
from const import *
|
|
||||||
import hashlib
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from cvc.asn1 import ASN1
|
from picohsm import PicoHSM
|
||||||
from cvc import oid
|
|
||||||
from cvc.certificates import CVC
|
|
||||||
from cvc.ec_curves import ec_domain, find_curve
|
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
print('ERROR: cvc module not found! Install pycvc package.\nTry with `pip install pycvc`')
|
print('ERROR: picohsm module not found! Install picohsm package.\nTry with `pip install pypicohsm`')
|
||||||
sys.exit(-1)
|
sys.exit(-1)
|
||||||
|
|
||||||
try:
|
|
||||||
from smartcard.CardType import AnyCardType
|
|
||||||
from smartcard.CardRequest import CardRequest
|
|
||||||
from smartcard.Exceptions import CardRequestTimeoutException, CardConnectionException
|
|
||||||
except ModuleNotFoundError:
|
|
||||||
print('ERROR: smarctard module not found! Install pyscard package.\nTry with `pip install pyscard`')
|
|
||||||
sys.exit(-1)
|
|
||||||
|
|
||||||
try:
|
|
||||||
from cryptography.hazmat.primitives.asymmetric import ec, rsa, utils, padding
|
|
||||||
from cryptography.hazmat.primitives import hashes, cmac
|
|
||||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
|
||||||
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
|
|
||||||
except ModuleNotFoundError:
|
|
||||||
print('ERROR: cryptography module not found! Install cryptography package.\nTry with `pip install cryptography`')
|
|
||||||
sys.exit(-1)
|
|
||||||
|
|
||||||
|
|
||||||
class Device:
|
|
||||||
class EcDummy:
|
|
||||||
def __init__(self, name):
|
|
||||||
self.name = name
|
|
||||||
|
|
||||||
def __init__(self,pin='648219'):
|
|
||||||
self.__pin = pin
|
|
||||||
cardtype = AnyCardType()
|
|
||||||
try:
|
|
||||||
# request card insertion
|
|
||||||
cardrequest = CardRequest(timeout=10, cardType=cardtype)
|
|
||||||
self.__card = cardrequest.waitforcard()
|
|
||||||
|
|
||||||
# connect to the card and perform a few transmits
|
|
||||||
self.__card.connection.connect()
|
|
||||||
|
|
||||||
except CardRequestTimeoutException:
|
|
||||||
raise Exception('time-out: no card inserted during last 10s')
|
|
||||||
self.select_applet()
|
|
||||||
|
|
||||||
def select_applet(self):
|
|
||||||
self.__card.connection.transmit([0x00, 0xA4, 0x04, 0x00, 0xB, 0xE8, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x81, 0xC3, 0x1F, 0x02, 0x01, 0x0])
|
|
||||||
|
|
||||||
def send(self, command, cla=0x00, p1=0x00, p2=0x00, ne=None, data=None, codes=[]):
|
|
||||||
lc = []
|
|
||||||
dataf = []
|
|
||||||
if (data):
|
|
||||||
lc = [0x00] + list(len(data).to_bytes(2, 'big'))
|
|
||||||
dataf = list(data)
|
|
||||||
else:
|
|
||||||
lc = [0x00*3]
|
|
||||||
if (ne is None):
|
|
||||||
le = [0x00, 0x00]
|
|
||||||
else:
|
|
||||||
le = list(ne.to_bytes(2, 'big'))
|
|
||||||
if (isinstance(command, list) and len(command) > 1):
|
|
||||||
apdu = command
|
|
||||||
else:
|
|
||||||
apdu = [cla, command]
|
|
||||||
|
|
||||||
apdu = apdu + [p1, p2] + lc + dataf + le
|
|
||||||
try:
|
|
||||||
response, sw1, sw2 = self.__card.connection.transmit(apdu)
|
|
||||||
except CardConnectionException:
|
|
||||||
self.__card.connection.reconnect()
|
|
||||||
response, sw1, sw2 = self.__card.connection.transmit(apdu)
|
|
||||||
|
|
||||||
code = (sw1<<8|sw2)
|
|
||||||
if (sw1 != 0x90):
|
|
||||||
if (sw1 == 0x63 and sw2 & 0xF0 == 0xC0):
|
|
||||||
pass
|
|
||||||
elif (code == 0x6A82):
|
|
||||||
self.select_applet()
|
|
||||||
if (sw1 == 0x90):
|
|
||||||
response, sw1, sw2 = self.__card.connection.transmit(apdu)
|
|
||||||
if (sw1 == 0x90):
|
|
||||||
return response
|
|
||||||
elif (code == 0x6982):
|
|
||||||
response, sw1, sw2 = self.__card.connection.transmit([0x00, 0x20, 0x00, 0x81, len(self.__pin)] + list(self.__pin.encode()) + [0x0])
|
|
||||||
if (sw1 == 0x90):
|
|
||||||
response, sw1, sw2 = self.__card.connection.transmit(apdu)
|
|
||||||
if (sw1 == 0x90):
|
|
||||||
return response
|
|
||||||
if (code not in codes):
|
|
||||||
raise APDUResponse(sw1, sw2)
|
|
||||||
if (len(codes) > 1):
|
|
||||||
return response, code
|
|
||||||
return response
|
|
||||||
|
|
||||||
def get_login_retries(self):
|
|
||||||
self.select_applet()
|
|
||||||
try:
|
|
||||||
self.send(command=0x20, p2=0x81)
|
|
||||||
except APDUResponse as e:
|
|
||||||
if (e.sw1 == 0x63 and e.sw2 & 0xF0 == 0xC0):
|
|
||||||
return e.sw2 & 0x0F
|
|
||||||
raise e
|
|
||||||
|
|
||||||
def initialize(self, pin=DEFAULT_PIN, sopin=DEFAULT_SOPIN, options=None, retries=DEFAULT_RETRIES, dkek_shares=None, puk_auts=None, puk_min_auts=None, key_domains=None):
|
|
||||||
if (retries is not None and not 0 < retries <= 10):
|
|
||||||
raise ValueError('Retries must be in the range (0,10]')
|
|
||||||
if (dkek_shares is not None and not 0 <= dkek_shares <= 10):
|
|
||||||
raise ValueError('DKEK shares must be in the range [0,10]')
|
|
||||||
if ((puk_auts is not None and puk_min_auts is None) or (puk_auts is None and puk_min_auts is not None)):
|
|
||||||
raise ValueError('PUK Auts and PUK Min Auts must be specified both')
|
|
||||||
if (puk_auts is not None and not 0 < puk_auts <= 8):
|
|
||||||
raise ValueError('PUK Auts must be in the range (0,8]')
|
|
||||||
if (puk_min_auts is not None and not 0 < puk_min_auts <= 8):
|
|
||||||
raise ValueError('PUK Min Auts must be in the range (0,8]')
|
|
||||||
if (puk_auts is not None and puk_min_auts is not None and puk_min_auts > puk_auts):
|
|
||||||
raise ValueError('PUK Min Auts must be less or equal to PUK Auts')
|
|
||||||
if (key_domains is not None and not 0 < key_domains <= 8):
|
|
||||||
raise ValueError('Key Domains must be in the range (0,8]')
|
|
||||||
|
|
||||||
a = ASN1()
|
|
||||||
if (pin is not None):
|
|
||||||
a = a.add_tag(0x81, pin.encode())
|
|
||||||
if (sopin is not None):
|
|
||||||
a = a.add_tag(0x82, sopin.encode())
|
|
||||||
if (retries is not None):
|
|
||||||
a = a.add_tag(0x91, bytes([retries]))
|
|
||||||
if (dkek_shares is not None):
|
|
||||||
a = a.add_tag(0x92, bytes([dkek_shares]))
|
|
||||||
if (puk_auts is not None and puk_min_auts is not None):
|
|
||||||
a = a.add_tag(0x93, bytes([puk_auts, puk_min_auts]))
|
|
||||||
if (key_domains is not None):
|
|
||||||
a = a.add_tag(0x97, bytes([key_domains]))
|
|
||||||
|
|
||||||
data = a.encode()
|
|
||||||
|
|
||||||
self.send(cla=0x80, command=0x50, data=data)
|
|
||||||
|
|
||||||
def login(self, pin=None):
|
|
||||||
if (pin is None):
|
|
||||||
pin = self.__pin
|
|
||||||
self.send(command=0x20, p2=0x81, data=pin.encode())
|
|
||||||
|
|
||||||
def get_first_free_id(self):
|
|
||||||
kids = self.list_keys(prefix=DOPrefixes.KEY_PREFIX)
|
|
||||||
mset = set(range(max(kids)))-set(kids)
|
|
||||||
if (len(mset) > 0):
|
|
||||||
return min(mset)
|
|
||||||
if (max(kids) == 255):
|
|
||||||
raise ValueError('Max number of key id reached')
|
|
||||||
return max(kids)+1
|
|
||||||
|
|
||||||
def list_keys(self, prefix=None):
|
|
||||||
resp = self.send(command=0x58)
|
|
||||||
if (prefix is not None):
|
|
||||||
grouped = [(resp[i],resp[i+1]) for i in range(0, len(resp), 2) if resp[i] == prefix.value]
|
|
||||||
_, kids = zip(*grouped)
|
|
||||||
return kids
|
|
||||||
return [(resp[i],resp[i+1]) for i in range(0, len(resp), 2)]
|
|
||||||
|
|
||||||
def key_generation(self, type, param):
|
|
||||||
if (type in [KeyType.RSA, KeyType.ECC]):
|
|
||||||
a = ASN1().add_tag(0x5f29, bytes([0])).add_tag(0x42, 'UTCA00001'.encode())
|
|
||||||
if (type == KeyType.RSA):
|
|
||||||
if (not 1024 <= param <= 4096):
|
|
||||||
raise ValueError('RSA bits must be in the range [1024,4096]')
|
|
||||||
a.add_tag(0x7f49, ASN1().add_oid(oid.ID_TA_RSA_V1_5_SHA_256).add_tag(0x2, param.to_bytes(2, 'big')).encode())
|
|
||||||
elif (type == KeyType.ECC):
|
|
||||||
if (param not in ('secp192r1', 'secp256r1', 'secp384r1', 'secp521r1', 'brainpoolP256r1', 'brainpoolP384r1', 'brainpoolP512r1', 'secp192k1', 'secp256k1')):
|
|
||||||
raise ValueError('Bad elliptic curve name')
|
|
||||||
|
|
||||||
dom = ec_domain(Device.EcDummy(param))
|
|
||||||
pubctx = [dom.P, dom.A, dom.B, dom.G, dom.O, None, dom.F]
|
|
||||||
a.add_object(0x7f49, oid.ID_TA_ECDSA_SHA_256, pubctx)
|
|
||||||
a.add_tag(0x5f20, 'UTCDUMMY00001'.encode())
|
|
||||||
data = a.encode()
|
|
||||||
|
|
||||||
keyid = self.get_first_free_id()
|
|
||||||
self.send(command=0x46, p1=keyid, data=list(data))
|
|
||||||
elif (type == KeyType.AES):
|
|
||||||
if (param == 128):
|
|
||||||
p2 = 0xB0
|
|
||||||
elif (param == 192):
|
|
||||||
p2 = 0xB1
|
|
||||||
elif (param == 256):
|
|
||||||
p2 = 0xB2
|
|
||||||
else:
|
|
||||||
raise ValueError('Bad AES key size')
|
|
||||||
keyid = self.get_first_free_id()
|
|
||||||
self.send(command=0x48, p1=keyid, p2=p2)
|
|
||||||
else:
|
|
||||||
raise ValueError('Bad KeyType')
|
|
||||||
return keyid
|
|
||||||
|
|
||||||
def delete_file(self, fid):
|
|
||||||
self.send(command=0xE4, data=[fid >> 8, fid & 0xff])
|
|
||||||
|
|
||||||
def get_contents(self, p1, p2=None):
|
|
||||||
if (p2):
|
|
||||||
resp = self.send(command=0xB1, p1=p1, p2=p2, data=[0x54, 0x02, 0x00, 0x00])
|
|
||||||
else:
|
|
||||||
resp = self.get_contents(p1=p1 >> 8, p2=p1 & 0xff)
|
|
||||||
return bytes(resp)
|
|
||||||
|
|
||||||
def public_key(self, keyid, param=None):
|
|
||||||
response = self.get_contents(p1=DOPrefixes.EE_CERTIFICATE_PREFIX.value, p2=keyid)
|
|
||||||
|
|
||||||
cert = bytearray(response)
|
|
||||||
roid = CVC().decode(cert).pubkey().oid()
|
|
||||||
if (roid == oid.ID_TA_ECDSA_SHA_256):
|
|
||||||
curve = find_curve(ec_domain(Device.EcDummy(param)).P)
|
|
||||||
Y = bytes(CVC().decode(cert).pubkey().find(0x86).data())
|
|
||||||
return ec.EllipticCurvePublicKey.from_encoded_point(
|
|
||||||
curve,
|
|
||||||
Y,
|
|
||||||
)
|
|
||||||
elif (roid == oid.ID_TA_RSA_V1_5_SHA_256):
|
|
||||||
n = int.from_bytes(bytes(CVC().decode(cert).pubkey().find(0x81).data()), 'big')
|
|
||||||
e = int.from_bytes(bytes(CVC().decode(cert).pubkey().find(0x82).data()), 'big')
|
|
||||||
return rsa.RSAPublicNumbers(e, n).public_key()
|
|
||||||
return None
|
|
||||||
|
|
||||||
def sign(self, keyid, scheme, data):
|
|
||||||
resp = self.send(cla=0x80, command=0x68, p1=keyid, p2=scheme.value, data=data)
|
|
||||||
return resp
|
|
||||||
|
|
||||||
def verify(self, pubkey, data, signature, scheme):
|
|
||||||
if (Algorithm.ALGO_EC_RAW.value <= scheme.value <= Algorithm.ALGO_EC_SHA512.value):
|
|
||||||
if (scheme == Algorithm.ALGO_EC_SHA1):
|
|
||||||
hsh = hashes.SHA1()
|
|
||||||
elif (scheme == Algorithm.ALGO_EC_SHA224):
|
|
||||||
hsh = hashes.SHA224()
|
|
||||||
elif (scheme == Algorithm.ALGO_EC_SHA256):
|
|
||||||
hsh = hashes.SHA256()
|
|
||||||
elif (scheme == Algorithm.ALGO_EC_RAW):
|
|
||||||
hsh = utils.Prehashed(hashes.SHA512())
|
|
||||||
elif (scheme == Algorithm.ALGO_EC_SHA384):
|
|
||||||
hsh = hashes.SHA384()
|
|
||||||
elif (scheme == Algorithm.ALGO_EC_SHA512):
|
|
||||||
hsh = hashes.SHA512()
|
|
||||||
return pubkey.verify(signature, data, ec.ECDSA(hsh))
|
|
||||||
elif (Algorithm.ALGO_RSA_PKCS1_SHA1.value <= scheme.value <= Algorithm.ALGO_RSA_PSS_SHA512.value):
|
|
||||||
if (scheme == Algorithm.ALGO_RSA_PKCS1_SHA1 or scheme == Algorithm.ALGO_RSA_PSS_SHA1):
|
|
||||||
hsh = hashes.SHA1()
|
|
||||||
elif (scheme == Algorithm.ALGO_RSA_PKCS1_SHA224 or scheme == Algorithm.ALGO_RSA_PSS_SHA224):
|
|
||||||
hsh = hashes.SHA224()
|
|
||||||
elif (scheme == Algorithm.ALGO_RSA_PKCS1_SHA256 or scheme == Algorithm.ALGO_RSA_PSS_SHA256):
|
|
||||||
hsh = hashes.SHA256()
|
|
||||||
elif (scheme == Algorithm.ALGO_RSA_PKCS1_SHA384 or scheme == Algorithm.ALGO_RSA_PSS_SHA384):
|
|
||||||
hsh = hashes.SHA384()
|
|
||||||
elif (scheme == Algorithm.ALGO_RSA_PKCS1_SHA512 or scheme == Algorithm.ALGO_RSA_PSS_SHA512):
|
|
||||||
hsh = hashes.SHA512()
|
|
||||||
if (Algorithm.ALGO_RSA_PKCS1_SHA1.value <= scheme.value <= Algorithm.ALGO_RSA_PKCS1_SHA512.value):
|
|
||||||
padd = padding.PKCS1v15()
|
|
||||||
elif (Algorithm.ALGO_RSA_PSS_SHA1.value <= scheme.value <= Algorithm.ALGO_RSA_PSS_SHA512.value):
|
|
||||||
padd = padding.PSS(
|
|
||||||
mgf=padding.MGF1(hsh),
|
|
||||||
salt_length=padding.PSS.AUTO
|
|
||||||
)
|
|
||||||
return pubkey.verify(signature, data, padd, hsh)
|
|
||||||
|
|
||||||
def decrypt(self, keyid, data, pad):
|
|
||||||
if (isinstance(pad, padding.OAEP)):
|
|
||||||
p2 = Padding.OAEP.value
|
|
||||||
elif (isinstance(pad, padding.PKCS1v15)):
|
|
||||||
p2 = Padding.PKCS.value
|
|
||||||
else:
|
|
||||||
p2 = Padding.RAW.value
|
|
||||||
resp = self.send(command=0x62, p1=keyid, p2=p2, data=list(data))
|
|
||||||
return bytes(resp)
|
|
||||||
|
|
||||||
def import_dkek(self, dkek):
|
|
||||||
resp = self.send(cla=0x80, command=0x52, p1=0x0, p2=0x0, data=dkek)
|
|
||||||
return resp
|
|
||||||
|
|
||||||
def import_key(self, pkey, dkek=None, purposes=None):
|
|
||||||
data = b''
|
|
||||||
kcv = hashlib.sha256(dkek or b'\x00'*32).digest()[:8]
|
|
||||||
kenc = hashlib.sha256((dkek or b'\x00'*32) + b'\x00\x00\x00\x01').digest()
|
|
||||||
kmac = hashlib.sha256((dkek or b'\x00'*32) + b'\x00\x00\x00\x02').digest()
|
|
||||||
data += kcv
|
|
||||||
if (isinstance(pkey, rsa.RSAPrivateKey)):
|
|
||||||
data += b'\x05'
|
|
||||||
algo = b'\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x01\x02'
|
|
||||||
elif (isinstance(pkey, ec.EllipticCurvePrivateKey)):
|
|
||||||
data += b'\x0C'
|
|
||||||
algo = b'\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x02\x03'
|
|
||||||
elif (isinstance(pkey, bytes)):
|
|
||||||
data += b'\x0F'
|
|
||||||
algo = b'\x00\x08\x60\x86\x48\x01\x65\x03\x04\x01'
|
|
||||||
|
|
||||||
data += algo
|
|
||||||
if (not purposes and isinstance(pkey, bytes)):
|
|
||||||
purposes = [Algorithm.ALGO_AES_CBC_ENCRYPT.value, Algorithm.ALGO_AES_CBC_DECRYPT.value, Algorithm.ALGO_AES_CMAC.value, Algorithm.ALGO_AES_DERIVE.value, Algorithm.ALGO_EXT_CIPHER_ENCRYPT.value, Algorithm.ALGO_EXT_CIPHER_DECRYPT.value]
|
|
||||||
if (purposes):
|
|
||||||
data += b'\x00' + bytes([len(purposes)]) + bytes(purposes) + b'\x00'*4
|
|
||||||
else:
|
|
||||||
data += b'\x00'*6
|
|
||||||
|
|
||||||
kb = os.urandom(8)
|
|
||||||
if (isinstance(pkey, rsa.RSAPrivateKey)):
|
|
||||||
kb += int_to_bytes(pkey.key_size, length=2)
|
|
||||||
pubnum = pkey.public_key().public_numbers()
|
|
||||||
pnum = pkey.private_numbers()
|
|
||||||
kb += int_to_bytes((pnum.d.bit_length()+7)//8, length=2)
|
|
||||||
kb += int_to_bytes(pnum.d)
|
|
||||||
kb += int_to_bytes((pubnum.n.bit_length()+7)//8, length=2)
|
|
||||||
kb += int_to_bytes(pubnum.n)
|
|
||||||
kb += int_to_bytes((pubnum.e.bit_length()+7)//8, length=2)
|
|
||||||
kb += int_to_bytes(pubnum.e)
|
|
||||||
elif (isinstance(pkey, ec.EllipticCurvePrivateKey)):
|
|
||||||
curve = ec_domain(pkey.curve)
|
|
||||||
kb += int_to_bytes(len(curve.P)*8, length=2)
|
|
||||||
kb += int_to_bytes(len(curve.A), length=2)
|
|
||||||
kb += curve.A
|
|
||||||
kb += int_to_bytes(len(curve.B), length=2)
|
|
||||||
kb += curve.B
|
|
||||||
kb += int_to_bytes(len(curve.P), length=2)
|
|
||||||
kb += curve.P
|
|
||||||
kb += int_to_bytes(len(curve.O), length=2)
|
|
||||||
kb += curve.O
|
|
||||||
kb += int_to_bytes(len(curve.G), length=2)
|
|
||||||
kb += curve.G
|
|
||||||
kb += int_to_bytes((pkey.private_numbers().private_value.bit_length()+7)//8, length=2)
|
|
||||||
kb += int_to_bytes(pkey.private_numbers().private_value)
|
|
||||||
p = pkey.public_key().public_bytes(Encoding.X962, PublicFormat.UncompressedPoint)
|
|
||||||
kb += int_to_bytes(len(p), length=2)
|
|
||||||
kb += p
|
|
||||||
elif (isinstance(pkey, bytes)):
|
|
||||||
kb += int_to_bytes(len(pkey), length=2)
|
|
||||||
kb += pkey
|
|
||||||
|
|
||||||
kb_len_pad = (len(kb)//16)*16
|
|
||||||
if (len(kb) % 16 > 0):
|
|
||||||
kb_len_pad = (len(kb)//16 + 1)*16
|
|
||||||
if (len(kb) < kb_len_pad):
|
|
||||||
kb += b'\x80'
|
|
||||||
kb += b'\x00' * (kb_len_pad-len(kb))
|
|
||||||
cipher = Cipher(algorithms.AES(kenc), modes.CBC(b'\x00'*16))
|
|
||||||
encryptor = cipher.encryptor()
|
|
||||||
ct = encryptor.update(kb) + encryptor.finalize()
|
|
||||||
data += ct
|
|
||||||
c = cmac.CMAC(algorithms.AES(kmac))
|
|
||||||
c.update(data)
|
|
||||||
data += c.finalize()
|
|
||||||
|
|
||||||
p1 = self.get_first_free_id()
|
|
||||||
_ = self.send(cla=0x80, command=0x74, p1=p1, p2=0x93, data=data)
|
|
||||||
return p1
|
|
||||||
|
|
||||||
def exchange(self, keyid, pubkey):
|
|
||||||
resp = self.send(cla=0x80, command=0x62, p1=keyid, p2=Algorithm.ALGO_EC_DH.value, data=pubkey.public_bytes(Encoding.X962, PublicFormat.UncompressedPoint))
|
|
||||||
return resp
|
|
||||||
|
|
||||||
def parse_cvc(self, data):
|
|
||||||
car = CVC().decode(data).car()
|
|
||||||
chr = CVC().decode(data).chr()
|
|
||||||
return {'car': car, 'chr': chr}
|
|
||||||
|
|
||||||
def get_termca(self):
|
|
||||||
resp = self.get_contents(EF_TERMCA)
|
|
||||||
cv_data = self.parse_cvc(resp)
|
|
||||||
a = ASN1().decode(resp).find(0x7f21).data()
|
|
||||||
tlen = len(ASN1.calculate_len(len(a)))
|
|
||||||
ret = {'cv': cv_data}
|
|
||||||
if (len(a)+2+tlen < len(resp)): # There's more certificate
|
|
||||||
resp = resp[2+len(a)+tlen:]
|
|
||||||
dv_data = self.parse_cvc(resp)
|
|
||||||
ret['dv'] = dv_data
|
|
||||||
return ret
|
|
||||||
|
|
||||||
def get_version(self):
|
|
||||||
resp = self.send(cla=0x80, command=0x50)
|
|
||||||
return resp[5]+0.1*resp[6]
|
|
||||||
|
|
||||||
def get_key_domain(self, key_domain=0):
|
|
||||||
resp, code = self.send(cla=0x80, command=0x52, p2=key_domain, codes=[0x9000, 0x6A88, 0x6A86])
|
|
||||||
if (code == 0x9000):
|
|
||||||
return {'dkek': { 'total': resp[0], 'missing': resp[1]}, 'kcv': resp[2:10]}
|
|
||||||
return {'error': code}
|
|
||||||
|
|
||||||
def get_key_domains(self):
|
|
||||||
for k in range(0xFF):
|
|
||||||
_, code = self.send(cla=0x80, command=0x52, p2=k, codes=[0x9000, 0x6A88, 0x6A86])
|
|
||||||
if (code == 0x6A86):
|
|
||||||
return k
|
|
||||||
return 0
|
|
||||||
|
|
||||||
def set_key_domain(self, key_domain=0, total=DEFAULT_DKEK_SHARES):
|
|
||||||
resp = self.send(cla=0x80, command=0x52, p1=0x1, p2=key_domain, data=[total])
|
|
||||||
return resp
|
|
||||||
|
|
||||||
def clear_key_domain(self, key_domain=0):
|
|
||||||
resp = self.send(cla=0x80, command=0x52, p1=0x4, p2=key_domain)
|
|
||||||
return resp
|
|
||||||
|
|
||||||
def delete_key_domain(self, key_domain=0):
|
|
||||||
self.send(cla=0x80, command=0x52, p1=0x3, p2=key_domain, codes=[0x6A88])
|
|
||||||
|
|
||||||
def get_challenge(self, length):
|
|
||||||
return self.send(cla=0x80, command=0x84, ne=length)
|
|
||||||
|
|
||||||
def cipher(self, algo, keyid, data):
|
|
||||||
resp = self.send(cla=0x80, command=0x78, p1=keyid, p2=algo.value, data=data)
|
|
||||||
return resp
|
|
||||||
|
|
||||||
def hmac(self, hash, keyid, data):
|
|
||||||
if (hash == hashes.SHA1):
|
|
||||||
algo = b'\x2A\x86\x48\x86\xF7\x0D\x02\x07'
|
|
||||||
elif (hash == hashes.SHA224):
|
|
||||||
algo = b'\x2A\x86\x48\x86\xF7\x0D\x02\x08'
|
|
||||||
elif (hash == hashes.SHA256):
|
|
||||||
algo = b'\x2A\x86\x48\x86\xF7\x0D\x02\x09'
|
|
||||||
elif (hash == hashes.SHA384):
|
|
||||||
algo = b'\x2A\x86\x48\x86\xF7\x0D\x02\x0A'
|
|
||||||
elif (hash == hashes.SHA512):
|
|
||||||
algo = b'\x2A\x86\x48\x86\xF7\x0D\x02\x0B'
|
|
||||||
else:
|
|
||||||
raise ValueError("Hash not supported")
|
|
||||||
data = [0x06, len(algo)] + list(algo) + [0x81, len(data)] + list(data)
|
|
||||||
resp = self.send(cla=0x80, command=0x78, p1=keyid, p2=0x51, data=data)
|
|
||||||
return resp
|
|
||||||
|
|
||||||
def cmac(self, keyid, data):
|
|
||||||
resp = self.send(cla=0x80, command=0x78, p1=keyid, p2=Algorithm.ALGO_AES_CMAC.value, data=data)
|
|
||||||
return resp
|
|
||||||
|
|
||||||
def hkdf(self, hash, keyid, data, salt, out_len=None):
|
|
||||||
if (hash == hashes.SHA256):
|
|
||||||
algo = b'\x2A\x86\x48\x86\xF7\x0D\x01\x09\x10\x03\x1D'
|
|
||||||
elif (hash == hashes.SHA384):
|
|
||||||
algo = b'\x2A\x86\x48\x86\xF7\x0D\x01\x09\x10\x03\x1E'
|
|
||||||
elif (hash == hashes.SHA512):
|
|
||||||
algo = b'\x2A\x86\x48\x86\xF7\x0D\x01\x09\x10\x03\x1F'
|
|
||||||
data = [0x06, len(algo)] + list(algo) + [0x81, len(data)] + list(data) + [0x82, len(salt)] + list(salt)
|
|
||||||
resp = self.send(cla=0x80, command=0x78, p1=keyid, p2=0x51, data=data, ne=out_len)
|
|
||||||
return resp
|
|
||||||
|
|
||||||
def pbkdf2(self, hash, keyid, salt, iterations, out_len=None):
|
|
||||||
oid = b'\x2A\x86\x48\x86\xF7\x0D\x01\x05\x0C'
|
|
||||||
salt = b'\x04' + bytes([len(salt)]) + salt
|
|
||||||
iteration = b'\x02' + bytes([len(int_to_bytes(iterations))]) + int_to_bytes(iterations)
|
|
||||||
prf = b'\x30\x0A\x06\x08\x2A\x86\x48\x86\xF7\x0D\x02'
|
|
||||||
if (hash == hashes.SHA1):
|
|
||||||
prf += b'\x07'
|
|
||||||
elif (hash == hashes.SHA224):
|
|
||||||
prf += b'\x08'
|
|
||||||
elif (hash == hashes.SHA256):
|
|
||||||
prf += b'\x09'
|
|
||||||
elif (hash == hashes.SHA384):
|
|
||||||
prf += b'\x0A'
|
|
||||||
elif (hash == hashes.SHA512):
|
|
||||||
prf += b'\x0B'
|
|
||||||
data = list(salt + iteration + prf)
|
|
||||||
data = [0x06, len(oid)] + list(oid) + [0x81, len(data)] + list(data)
|
|
||||||
resp = self.send(cla=0x80, command=0x78, p1=keyid, p2=0x51, data=data, ne=out_len)
|
|
||||||
return resp
|
|
||||||
|
|
||||||
def x963(self, hash, keyid, data, out_len=None):
|
|
||||||
oid = b'\x2B\x81\x05\x10\x86\x48\x3F'
|
|
||||||
enc = b'\x2A\x86\x48\x86\xF7\x0D\x02'
|
|
||||||
if (hash == hashes.SHA1):
|
|
||||||
enc += b'\x07'
|
|
||||||
elif (hash == hashes.SHA224):
|
|
||||||
enc += b'\x08'
|
|
||||||
elif (hash == hashes.SHA256):
|
|
||||||
enc += b'\x09'
|
|
||||||
elif (hash == hashes.SHA384):
|
|
||||||
enc += b'\x0A'
|
|
||||||
elif (hash == hashes.SHA512):
|
|
||||||
enc += b'\x0B'
|
|
||||||
else:
|
|
||||||
raise ValueError("Hash not supported")
|
|
||||||
data = [0x06, len(oid)] + list(oid) + [0x81, len(enc)] + list(enc) + [0x83, len(data)] + list(data)
|
|
||||||
resp = self.send(cla=0x80, command=0x78, p1=keyid, p2=0x51, data=data, ne=out_len)
|
|
||||||
return resp
|
|
||||||
|
|
||||||
@pytest.fixture(scope="session")
|
@pytest.fixture(scope="session")
|
||||||
def device():
|
def device():
|
||||||
dev = Device()
|
dev = PicoHSM()
|
||||||
return dev
|
return dev
|
||||||
|
|||||||
@@ -17,10 +17,9 @@
|
|||||||
*/
|
*/
|
||||||
"""
|
"""
|
||||||
|
|
||||||
DEFAULT_PIN = '648219'
|
from binascii import unhexlify
|
||||||
DEFAULT_SOPIN = '57621880'
|
|
||||||
DEFAULT_RETRIES = 3
|
|
||||||
DEFAULT_DKEK = [0x1] * 32
|
|
||||||
DEFAULT_DKEK_SHARES = 2
|
|
||||||
|
|
||||||
EF_TERMCA = 0x2f02
|
DEFAULT_DKEK = [0x1] * 32
|
||||||
|
|
||||||
|
TERM_CERT = unhexlify('7F2181E57F4E819E5F290100421045535049434F48534D445630303030317F494F060A04007F00070202020203864104F571E53AA8E75C929D925081CF0F893CB5991D48BD546C1A3F22199F037E4B12D601ACD91C67C88D3C5B3D04C08EC0A372485F7A248E080EE0C6237C1B075E1C5F201045535049434F48534D54525A474E50327F4C0E060904007F0007030102025301005F25060203000300055F24060204000300045F374041BF5E970739135770DBCC5DDA81FFD8B13419A9257D44CAF8404267C644E8F435B43F5E57EB2A8CF4B198045ACD094E0CB34E6217D9C8922CFB9BBEFD4088AD')
|
||||||
|
DICA_CERT = unhexlify('7F2181E97F4E81A25F290100421045535049434F48534D434130303030317F494F060A04007F0007020202020386410421EE4A21C16A10F737F12E78E5091B266612038CDABEBB722B15BF6D41B877FBF64D9AB69C39B9831B1AE00BEF2A4E81976F7688D45189BB232A24703D8A96A55F201045535049434F48534D445630303030317F4C12060904007F000703010202530580000000005F25060202000801085F24060203000601045F37403F75C08FFFC9186B56E6147199E82BFC327CEEF72495BC567961CD54D702F13E3C2766FCD1D11BD6A9D1F4A229B76B248CEB9AF88D59A74D0AB149448705159B')
|
||||||
|
|||||||
49
tests/docker/bullseye/Dockerfile
Normal file
49
tests/docker/bullseye/Dockerfile
Normal file
@@ -0,0 +1,49 @@
|
|||||||
|
FROM debian:bullseye
|
||||||
|
|
||||||
|
ARG DEBIAN_FRONTEND=noninteractive
|
||||||
|
|
||||||
|
RUN apt update && apt upgrade -y
|
||||||
|
RUN apt install -y apt-utils
|
||||||
|
RUN apt autoremove -y
|
||||||
|
RUN rm -rf /var/cache/apt/archives/*
|
||||||
|
RUN apt install -y libccid \
|
||||||
|
libpcsclite-dev \
|
||||||
|
git \
|
||||||
|
autoconf \
|
||||||
|
pkg-config \
|
||||||
|
libtool \
|
||||||
|
help2man \
|
||||||
|
automake \
|
||||||
|
gcc \
|
||||||
|
make \
|
||||||
|
build-essential \
|
||||||
|
python3 \
|
||||||
|
python3-pip \
|
||||||
|
swig \
|
||||||
|
libssl-dev \
|
||||||
|
cmake \
|
||||||
|
vsmartcard-vpcd \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
RUN pip3 install pytest pycvc cryptography pyscard base58
|
||||||
|
WORKDIR /
|
||||||
|
RUN git clone https://github.com/OpenSC/OpenSC
|
||||||
|
WORKDIR /OpenSC
|
||||||
|
RUN git checkout tags/0.25.1
|
||||||
|
RUN ./bootstrap
|
||||||
|
RUN ./configure --enable-openssl
|
||||||
|
RUN make -j `nproc`
|
||||||
|
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
|
||||||
|
RUN ./configure
|
||||||
|
RUN make -j `nproc`
|
||||||
|
RUN make install
|
||||||
|
RUN cp ./src/tests/sc-hsm-pkcs11-test /usr/local/bin/sc-hsm-pkcs11-test
|
||||||
|
RUN make clean
|
||||||
|
WORKDIR /
|
||||||
@@ -22,7 +22,7 @@ RUN apt install -y libccid \
|
|||||||
cmake \
|
cmake \
|
||||||
&& rm -rf /var/lib/apt/lists/*
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
RUN pip3 install pytest pycvc cryptography pyscard
|
RUN pip3 install pytest pycvc cryptography pyscard
|
||||||
RUN git clone https://github.com/frankmorgner/vsmartcard.git
|
RUN git clone https://github.com/polhenarejos/vsmartcard.git
|
||||||
WORKDIR /vsmartcard/virtualsmartcard
|
WORKDIR /vsmartcard/virtualsmartcard
|
||||||
RUN autoreconf --verbose --install
|
RUN autoreconf --verbose --install
|
||||||
RUN ./configure --sysconfdir=/etc
|
RUN ./configure --sysconfdir=/etc
|
||||||
|
|||||||
20
tests/docker_env.sh
Normal file → Executable file
20
tests/docker_env.sh
Normal file → Executable file
@@ -46,7 +46,7 @@
|
|||||||
|
|
||||||
|
|
||||||
# default values, can be overridden by the environment
|
# default values, can be overridden by the environment
|
||||||
: ${MBEDTLS_DOCKER_GUEST:=jammy}
|
: ${MBEDTLS_DOCKER_GUEST:=bullseye}
|
||||||
|
|
||||||
|
|
||||||
DOCKER_IMAGE_TAG="pico-hsm-test:${MBEDTLS_DOCKER_GUEST}"
|
DOCKER_IMAGE_TAG="pico-hsm-test:${MBEDTLS_DOCKER_GUEST}"
|
||||||
@@ -72,14 +72,16 @@ else
|
|||||||
NUM_PROC="$(nproc)"
|
NUM_PROC="$(nproc)"
|
||||||
fi
|
fi
|
||||||
|
|
||||||
# Build the Docker image
|
build_image() {
|
||||||
echo "Getting docker image up to date (this may take a few minutes)..."
|
# Build the Docker image
|
||||||
${DOCKER} image build \
|
echo "Getting docker image up to date (this may take a few minutes)..."
|
||||||
-t ${DOCKER_IMAGE_TAG} \
|
${DOCKER} image build \
|
||||||
--cache-from=${DOCKER_IMAGE_TAG} \
|
-t ${DOCKER_IMAGE_TAG} \
|
||||||
--network host \
|
--cache-from=${DOCKER_IMAGE_TAG} \
|
||||||
--build-arg MAKEFLAGS_PARALLEL="-j ${NUM_PROC}" \
|
--network host \
|
||||||
tests/docker/${MBEDTLS_DOCKER_GUEST}
|
--build-arg MAKEFLAGS_PARALLEL="-j ${NUM_PROC}" \
|
||||||
|
tests/docker/${MBEDTLS_DOCKER_GUEST}
|
||||||
|
}
|
||||||
|
|
||||||
run_in_docker()
|
run_in_docker()
|
||||||
{
|
{
|
||||||
|
|||||||
Binary file not shown.
@@ -18,17 +18,19 @@
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from const import EF_TERMCA
|
|
||||||
|
|
||||||
def test_select(device):
|
def test_select(device):
|
||||||
device.select_applet()
|
device.select_applet()
|
||||||
|
|
||||||
|
def test_initialization(device):
|
||||||
|
device.initialize()
|
||||||
|
|
||||||
def test_termca(device):
|
def test_termca(device):
|
||||||
data = device.get_termca()
|
data = device.get_termca()
|
||||||
assert(b'ESPICOHSMTR' == data['cv']['chr'][:11])
|
assert(b'ESPICOHSMTR' == data['cv']['chr'][:11])
|
||||||
assert(b'ESPICOHSMDV' == data['cv']['car'][:11])
|
assert(b'ESPICOHSMDV' == data['cv']['car'][:11] or b'ESPICOHSMTR' == data['cv']['car'][:11])
|
||||||
assert(b'ESPICOHSMDV' == data['dv']['chr'][:11])
|
assert(b'ESPICOHSMDV' == data['dv']['chr'][:11] or b'ESPICOHSMTR' == data['dv']['chr'][:11])
|
||||||
assert(b'ESPICOHSMCA' == data['dv']['car'][:11])
|
assert(b'ESPICOHSMCA' == data['dv']['car'][:11] or b'ESPICOHSMTR' == data['dv']['car'][:11])
|
||||||
assert(data['cv']['car'] == data['dv']['chr'])
|
assert(data['cv']['car'] == data['dv']['chr'])
|
||||||
|
|
||||||
def test_get_version(device):
|
def test_get_version(device):
|
||||||
|
|||||||
@@ -18,9 +18,13 @@
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from const import DEFAULT_DKEK_SHARES, DEFAULT_DKEK
|
import hashlib
|
||||||
|
from const import DEFAULT_DKEK
|
||||||
|
from picohsm import APDUResponse, SWCodes
|
||||||
|
from picohsm.const import DEFAULT_DKEK_SHARES
|
||||||
|
|
||||||
KEY_DOMAINS = 3
|
KEY_DOMAINS = 3
|
||||||
|
TEST_KEY_DOMAIN = 1
|
||||||
|
|
||||||
def test_key_domains(device):
|
def test_key_domains(device):
|
||||||
device.initialize(key_domains=KEY_DOMAINS)
|
device.initialize(key_domains=KEY_DOMAINS)
|
||||||
@@ -34,13 +38,28 @@ def test_key_domains(device):
|
|||||||
assert(kd['error'] == 0x6A86)
|
assert(kd['error'] == 0x6A86)
|
||||||
assert(device.get_key_domains() == KEY_DOMAINS)
|
assert(device.get_key_domains() == KEY_DOMAINS)
|
||||||
|
|
||||||
def test_set_key_domain(device):
|
def test_import_dkek_wrong_key_domain(device):
|
||||||
kd = device.get_key_domain(key_domain=0)
|
with pytest.raises(APDUResponse) as e:
|
||||||
|
device.import_dkek(DEFAULT_DKEK, key_domain=0)
|
||||||
|
assert(e.value.sw == SWCodes.SW_COMMAND_NOT_ALLOWED)
|
||||||
|
|
||||||
|
def test_import_dkek_fail(device):
|
||||||
|
with pytest.raises(APDUResponse) as e:
|
||||||
|
device.import_dkek(DEFAULT_DKEK, key_domain=TEST_KEY_DOMAIN)
|
||||||
|
assert(e.value.sw == SWCodes.SW_COMMAND_NOT_ALLOWED)
|
||||||
|
|
||||||
|
def test_set_key_domain_fail(device):
|
||||||
|
with pytest.raises(APDUResponse) as e:
|
||||||
|
device.set_key_domain(key_domain=10)
|
||||||
|
assert(e.value.sw == SWCodes.SW_INCORRECT_P1P2)
|
||||||
|
|
||||||
|
def test_set_key_domain_ok(device):
|
||||||
|
kd = device.get_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||||
assert('error' in kd)
|
assert('error' in kd)
|
||||||
assert(kd['error'] == 0x6A88)
|
assert(kd['error'] == 0x6A88)
|
||||||
|
|
||||||
device.set_key_domain(key_domain=0)
|
device.set_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||||
kd = device.get_key_domain(key_domain=0)
|
kd = device.get_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||||
assert('error' not in kd)
|
assert('error' not in kd)
|
||||||
assert('dkek' in kd)
|
assert('dkek' in kd)
|
||||||
assert('total' in kd['dkek'])
|
assert('total' in kd['dkek'])
|
||||||
@@ -48,25 +67,49 @@ def test_set_key_domain(device):
|
|||||||
assert('missing' in kd['dkek'])
|
assert('missing' in kd['dkek'])
|
||||||
assert(kd['dkek']['missing'] == DEFAULT_DKEK_SHARES)
|
assert(kd['dkek']['missing'] == DEFAULT_DKEK_SHARES)
|
||||||
|
|
||||||
|
def test_import_dkek_ok(device):
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK, key_domain=TEST_KEY_DOMAIN)
|
||||||
|
assert('dkek' in resp)
|
||||||
|
assert('kcv' in resp)
|
||||||
|
assert(resp['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
||||||
|
assert(resp['dkek']['missing'] == DEFAULT_DKEK_SHARES-1)
|
||||||
|
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK, key_domain=TEST_KEY_DOMAIN)
|
||||||
|
assert('dkek' in resp)
|
||||||
|
assert('kcv' in resp)
|
||||||
|
assert(resp['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
||||||
|
assert(resp['dkek']['missing'] == DEFAULT_DKEK_SHARES-2)
|
||||||
|
|
||||||
|
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]
|
||||||
|
assert(resp['kcv'] == kcv)
|
||||||
|
|
||||||
def test_clear_key_domain(device):
|
def test_clear_key_domain(device):
|
||||||
kd = device.get_key_domain(key_domain=0)
|
kd = device.get_key_domain(key_domain=0)
|
||||||
|
assert('error' in kd)
|
||||||
|
assert(kd['error'] == SWCodes.SW_REFERENCE_NOT_FOUND)
|
||||||
|
|
||||||
|
kd = device.get_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||||
assert(kd['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
assert(kd['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
||||||
|
|
||||||
device.import_dkek(DEFAULT_DKEK)
|
device.clear_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||||
kd = device.get_key_domain(key_domain=0)
|
kd = device.get_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||||
assert(kd['dkek']['missing'] == DEFAULT_DKEK_SHARES-1)
|
|
||||||
|
|
||||||
device.clear_key_domain(key_domain=0)
|
|
||||||
kd = device.get_key_domain(key_domain=0)
|
|
||||||
assert(kd['dkek']['missing'] == DEFAULT_DKEK_SHARES)
|
assert(kd['dkek']['missing'] == DEFAULT_DKEK_SHARES)
|
||||||
|
|
||||||
def test_delete_key_domain(device):
|
def test_delete_key_domain(device):
|
||||||
assert(device.get_key_domains() == KEY_DOMAINS)
|
assert(device.get_key_domains() == KEY_DOMAINS)
|
||||||
kd = device.get_key_domain(key_domain=0)
|
kd = device.get_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||||
|
assert(kd['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
||||||
|
with pytest.raises(APDUResponse) as e:
|
||||||
|
device.delete_key_domain(key_domain=0)
|
||||||
|
assert(e.value.sw == SWCodes.SW_INCORRECT_P1P2)
|
||||||
|
|
||||||
|
def test_delete_key_domain(device):
|
||||||
|
assert(device.get_key_domains() == KEY_DOMAINS)
|
||||||
|
kd = device.get_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||||
assert(kd['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
assert(kd['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
||||||
|
|
||||||
device.delete_key_domain(key_domain=0)
|
device.delete_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||||
assert(device.get_key_domains() == KEY_DOMAINS)
|
assert(device.get_key_domains() == KEY_DOMAINS)
|
||||||
kd = device.get_key_domain(key_domain=0)
|
kd = device.get_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||||
assert('error' in kd)
|
assert('error' in kd)
|
||||||
assert(kd['error'] == 0x6A88)
|
assert(kd['error'] == 0x6A88)
|
||||||
|
|||||||
@@ -19,19 +19,24 @@
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
import hashlib
|
import hashlib
|
||||||
from utils import APDUResponse, SWCodes
|
from picohsm.const import DEFAULT_DKEK_SHARES, DEFAULT_PIN, DEFAULT_RETRIES
|
||||||
from const import DEFAULT_PIN, DEFAULT_RETRIES, DEFAULT_DKEK, DEFAULT_DKEK_SHARES
|
from const import DEFAULT_DKEK
|
||||||
|
|
||||||
def test_dkek(device):
|
def test_dkek(device):
|
||||||
device.initialize(retries=DEFAULT_RETRIES, dkek_shares=DEFAULT_DKEK_SHARES)
|
device.initialize(retries=DEFAULT_RETRIES, dkek_shares=DEFAULT_DKEK_SHARES)
|
||||||
device.login(DEFAULT_PIN)
|
device.login(DEFAULT_PIN)
|
||||||
resp = device.import_dkek(DEFAULT_DKEK)
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
assert(resp[0] == DEFAULT_DKEK_SHARES)
|
assert('dkek' in resp)
|
||||||
assert(resp[1] == DEFAULT_DKEK_SHARES-1)
|
assert('kcv' in resp)
|
||||||
|
assert(resp['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
||||||
|
assert(resp['dkek']['missing'] == DEFAULT_DKEK_SHARES-1)
|
||||||
|
|
||||||
resp = device.import_dkek(DEFAULT_DKEK)
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
assert(resp[1] == DEFAULT_DKEK_SHARES-2)
|
assert('dkek' in resp)
|
||||||
|
assert('kcv' in resp)
|
||||||
|
assert(resp['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
||||||
|
assert(resp['dkek']['missing'] == DEFAULT_DKEK_SHARES-2)
|
||||||
|
|
||||||
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]
|
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]
|
||||||
assert(bytes(resp[2:]) == kcv)
|
assert(resp['kcv'] == kcv)
|
||||||
|
|
||||||
|
|||||||
@@ -18,36 +18,35 @@
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from utils import APDUResponse, SWCodes
|
from picohsm import APDUResponse, SWCodes
|
||||||
from const import DEFAULT_PIN, DEFAULT_RETRIES
|
from picohsm.const import DEFAULT_PIN, DEFAULT_RETRIES
|
||||||
|
|
||||||
WRONG_PIN = '112233'
|
WRONG_PIN = '112233'
|
||||||
RETRIES = DEFAULT_RETRIES
|
|
||||||
|
|
||||||
def test_pin_init_retries(device):
|
def test_pin_init_retries(device):
|
||||||
device.initialize(retries=RETRIES)
|
device.initialize(retries=DEFAULT_RETRIES)
|
||||||
retries = device.get_login_retries()
|
retries = device.get_login_retries()
|
||||||
assert(retries == RETRIES)
|
assert(retries == DEFAULT_RETRIES)
|
||||||
|
|
||||||
def test_pin_login(device):
|
def test_pin_login(device):
|
||||||
device.initialize(retries=RETRIES)
|
device.initialize(retries=DEFAULT_RETRIES)
|
||||||
device.login(DEFAULT_PIN)
|
device.login(DEFAULT_PIN)
|
||||||
|
|
||||||
def test_pin_retries(device):
|
def test_pin_retries(device):
|
||||||
device.initialize(retries=RETRIES)
|
device.initialize(retries=DEFAULT_RETRIES)
|
||||||
device.login(DEFAULT_PIN)
|
device.login(DEFAULT_PIN)
|
||||||
|
|
||||||
for ret in range(RETRIES-1):
|
for ret in range(DEFAULT_RETRIES-1):
|
||||||
with pytest.raises(APDUResponse) as e:
|
with pytest.raises(APDUResponse) as e:
|
||||||
device.login(WRONG_PIN)
|
device.login(WRONG_PIN)
|
||||||
assert(e.value.sw1 == 0x63 and e.value.sw2 == (0xC0 | (RETRIES-1-ret)))
|
assert(e.value.sw1 == 0x63 and e.value.sw2 == (0xC0 | (DEFAULT_RETRIES-1-ret)))
|
||||||
|
|
||||||
with pytest.raises(APDUResponse) as e:
|
with pytest.raises(APDUResponse) as e:
|
||||||
device.login(WRONG_PIN)
|
device.login(WRONG_PIN)
|
||||||
assert(e.value.sw == SWCodes.SW_PIN_BLOCKED.value)
|
assert(e.value.sw == SWCodes.SW_PIN_BLOCKED)
|
||||||
|
|
||||||
device.initialize(retries=RETRIES)
|
device.initialize(retries=DEFAULT_RETRIES)
|
||||||
retries = device.get_login_retries()
|
retries = device.get_login_retries()
|
||||||
assert(retries == RETRIES)
|
assert(retries == DEFAULT_RETRIES)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -18,20 +18,22 @@
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from utils import KeyType, DOPrefixes
|
from picohsm import KeyType, DOPrefixes
|
||||||
|
|
||||||
def test_gen_initialize(device):
|
def test_gen_initialize(device):
|
||||||
device.initialize()
|
device.initialize()
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
"curve", ['secp192r1', 'secp256r1', 'secp384r1', 'secp521r1', 'brainpoolP256r1', 'brainpoolP384r1', 'brainpoolP512r1', 'secp192k1', 'secp256k1']
|
"curve", ['secp192r1', 'secp256r1', 'secp384r1', 'secp521r1', 'brainpoolP256r1', 'brainpoolP384r1', 'brainpoolP512r1', 'secp192k1', 'secp256k1', 'curve25519', 'curve448', 'ed25519', 'ed448']
|
||||||
)
|
)
|
||||||
def test_gen_ecc(device, curve):
|
def test_gen_ecc(device, curve):
|
||||||
keyid = device.key_generation(KeyType.ECC, curve)
|
keyid = device.key_generation(KeyType.ECC, curve)
|
||||||
resp = device.list_keys()
|
resp = device.list_keys()
|
||||||
assert((DOPrefixes.KEY_PREFIX.value, keyid) in resp)
|
assert((DOPrefixes.KEY_PREFIX, keyid) in resp)
|
||||||
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||||
|
resp = device.list_keys()
|
||||||
|
assert((DOPrefixes.KEY_PREFIX, keyid) not in resp)
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
"modulus", [1024, 2048, 4096]
|
"modulus", [1024, 2048, 4096]
|
||||||
@@ -39,7 +41,7 @@ def test_gen_ecc(device, curve):
|
|||||||
def test_gen_rsa(device, modulus):
|
def test_gen_rsa(device, modulus):
|
||||||
keyid = device.key_generation(KeyType.RSA, modulus)
|
keyid = device.key_generation(KeyType.RSA, modulus)
|
||||||
resp = device.list_keys()
|
resp = device.list_keys()
|
||||||
assert((DOPrefixes.KEY_PREFIX.value, keyid) in resp)
|
assert((DOPrefixes.KEY_PREFIX, keyid) in resp)
|
||||||
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||||
|
|
||||||
|
|||||||
@@ -20,16 +20,18 @@
|
|||||||
import pytest
|
import pytest
|
||||||
import hashlib
|
import hashlib
|
||||||
import os
|
import os
|
||||||
from utils import KeyType, DOPrefixes
|
from picohsm import DOPrefixes
|
||||||
from cryptography.hazmat.primitives.asymmetric import rsa, ec
|
from cryptography.hazmat.primitives.asymmetric import rsa, ec, x25519, x448, ed25519, ed448
|
||||||
from const import DEFAULT_RETRIES, DEFAULT_DKEK_SHARES, DEFAULT_DKEK
|
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
|
||||||
|
from picohsm.const import DEFAULT_RETRIES, DEFAULT_DKEK_SHARES
|
||||||
|
from const import DEFAULT_DKEK
|
||||||
|
|
||||||
def test_prepare_dkek(device):
|
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)
|
||||||
resp = device.import_dkek(DEFAULT_DKEK)
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
resp = device.import_dkek(DEFAULT_DKEK)
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]
|
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]
|
||||||
assert(bytes(resp[2:]) == kcv)
|
assert(resp['kcv'] == kcv)
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
"modulus", [1024, 2048, 4096]
|
"modulus", [1024, 2048, 4096]
|
||||||
@@ -42,8 +44,8 @@ def test_import_rsa(device, modulus):
|
|||||||
keyid = device.import_key(pkey)
|
keyid = device.import_key(pkey)
|
||||||
pubkey = device.public_key(keyid)
|
pubkey = device.public_key(keyid)
|
||||||
assert(pubkey.public_numbers() == pkey.public_key().public_numbers())
|
assert(pubkey.public_numbers() == pkey.public_key().public_numbers())
|
||||||
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
@@ -54,8 +56,30 @@ def test_import_ecc(device, curve):
|
|||||||
keyid = device.import_key(pkey)
|
keyid = device.import_key(pkey)
|
||||||
pubkey = device.public_key(keyid, param=curve().name)
|
pubkey = device.public_key(keyid, param=curve().name)
|
||||||
assert(pubkey.public_numbers() == pkey.public_key().public_numbers())
|
assert(pubkey.public_numbers() == pkey.public_key().public_numbers())
|
||||||
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"curve", [x25519.X25519PrivateKey, x448.X448PrivateKey]
|
||||||
|
)
|
||||||
|
def test_import_montgomery(device, curve):
|
||||||
|
pkey = curve.generate()
|
||||||
|
keyid = device.import_key(pkey)
|
||||||
|
pubkey = device.public_key(keyid, param=curve)
|
||||||
|
assert(pubkey.public_bytes(Encoding.Raw, PublicFormat.Raw) == pkey.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw))
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
|
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"curve", [ed25519.Ed25519PrivateKey, ed448.Ed448PrivateKey]
|
||||||
|
)
|
||||||
|
def test_import_edwards(device, curve):
|
||||||
|
pkey = curve.generate()
|
||||||
|
keyid = device.import_key(pkey)
|
||||||
|
pubkey = device.public_key(keyid, param=curve)
|
||||||
|
assert(pubkey.public_bytes(Encoding.Raw, PublicFormat.Raw) == pkey.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw))
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
|
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
"size", [128, 192, 256]
|
"size", [128, 192, 256]
|
||||||
|
|||||||
@@ -19,16 +19,17 @@
|
|||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
import hashlib
|
import hashlib
|
||||||
from utils import KeyType, DOPrefixes
|
from picohsm import DOPrefixes
|
||||||
from cryptography.hazmat.primitives.asymmetric import rsa, ec
|
from cryptography.hazmat.primitives.asymmetric import ec, x25519, x448
|
||||||
from const import DEFAULT_RETRIES, DEFAULT_DKEK_SHARES, DEFAULT_DKEK
|
from picohsm.const import DEFAULT_RETRIES, DEFAULT_DKEK_SHARES
|
||||||
|
from const import DEFAULT_DKEK
|
||||||
|
|
||||||
def test_prepare_dkek(device):
|
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)
|
||||||
resp = device.import_dkek(DEFAULT_DKEK)
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
resp = device.import_dkek(DEFAULT_DKEK)
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]
|
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]
|
||||||
assert(bytes(resp[2:]) == kcv)
|
assert(resp['kcv'] == kcv)
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
"curve", [ec.SECP192R1, ec.SECP256R1, ec.SECP384R1, ec.SECP521R1, ec.SECP256K1, ec.BrainpoolP256R1, ec.BrainpoolP384R1, ec.BrainpoolP512R1]
|
"curve", [ec.SECP192R1, ec.SECP256R1, ec.SECP384R1, ec.SECP521R1, ec.SECP256K1, ec.BrainpoolP256R1, ec.BrainpoolP384R1, ec.BrainpoolP512R1]
|
||||||
@@ -43,10 +44,31 @@ def test_exchange_ecc(device, curve):
|
|||||||
sharedB = pkeyB.exchange(ec.ECDH(), pbkeyA)
|
sharedB = pkeyB.exchange(ec.ECDH(), pbkeyA)
|
||||||
sharedA = device.exchange(keyid, pbkeyB)
|
sharedA = device.exchange(keyid, pbkeyB)
|
||||||
|
|
||||||
assert(bytes(sharedA) == sharedB)
|
assert(sharedA == sharedB)
|
||||||
|
|
||||||
sharedAA = pkeyA.exchange(ec.ECDH(), pbkeyB)
|
sharedAA = pkeyA.exchange(ec.ECDH(), pbkeyB)
|
||||||
assert(bytes(sharedA) == sharedAA)
|
assert(sharedA == sharedAA)
|
||||||
|
|
||||||
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"curve", [x25519.X25519PrivateKey, x448.X448PrivateKey]
|
||||||
|
)
|
||||||
|
def test_exchange_montgomery(device, curve):
|
||||||
|
pkeyA = curve.generate()
|
||||||
|
pbkeyA = pkeyA.public_key()
|
||||||
|
keyid = device.import_key(pkeyA)
|
||||||
|
pkeyB = curve.generate()
|
||||||
|
pbkeyB = pkeyB.public_key()
|
||||||
|
|
||||||
|
sharedB = pkeyB.exchange(pbkeyA)
|
||||||
|
sharedA = device.exchange(keyid, pbkeyB)
|
||||||
|
|
||||||
|
assert(sharedA == sharedB)
|
||||||
|
|
||||||
|
sharedAA = pkeyA.exchange(pbkeyB)
|
||||||
|
assert(sharedA == sharedAA)
|
||||||
|
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
|
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||||
|
|||||||
@@ -18,7 +18,7 @@
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from utils import KeyType, DOPrefixes
|
from picohsm import KeyType, DOPrefixes
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
"size", [128, 192, 256]
|
"size", [128, 192, 256]
|
||||||
@@ -26,5 +26,5 @@ from utils import KeyType, DOPrefixes
|
|||||||
def test_gen_aes(device, size):
|
def test_gen_aes(device, size):
|
||||||
keyid = device.key_generation(KeyType.AES, size)
|
keyid = device.key_generation(KeyType.AES, size)
|
||||||
resp = device.list_keys()
|
resp = device.list_keys()
|
||||||
assert((DOPrefixes.KEY_PREFIX.value, keyid) in resp)
|
assert((DOPrefixes.KEY_PREFIX, keyid) in resp)
|
||||||
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
|
|||||||
137
tests/pico-hsm/test_025_key_export.py
Normal file
137
tests/pico-hsm/test_025_key_export.py
Normal file
@@ -0,0 +1,137 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* This file is part of the Pico HSM distribution (https://github.com/polhenarejos/pico-hsm).
|
||||||
|
* Copyright (c) 2023 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/>.
|
||||||
|
*/
|
||||||
|
"""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from picohsm import KeyType, DOPrefixes, APDUResponse, SWCodes
|
||||||
|
from binascii import hexlify
|
||||||
|
import hashlib
|
||||||
|
from const import DEFAULT_DKEK
|
||||||
|
from cryptography.hazmat.primitives import cmac
|
||||||
|
from cryptography.hazmat.primitives.ciphers import algorithms, Cipher, modes
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import ec
|
||||||
|
from cryptography.hazmat.primitives import serialization
|
||||||
|
|
||||||
|
def test_initialize(device):
|
||||||
|
device.initialize(key_domains=1)
|
||||||
|
assert(device.get_key_domains() == 1)
|
||||||
|
|
||||||
|
device.set_key_domain(key_domain=0, total=2)
|
||||||
|
|
||||||
|
keyid_in = -1
|
||||||
|
keyid_out = -1
|
||||||
|
def test_key_generation_no_key_domain(device):
|
||||||
|
global keyid_out
|
||||||
|
keyid_out = device.key_generation(KeyType.ECC, 'brainpoolP256r1')
|
||||||
|
device.put_contents(p1=DOPrefixes.PRKD_PREFIX, p2=keyid_out, data=[0xA0])
|
||||||
|
resp = device.list_keys()
|
||||||
|
assert((DOPrefixes.KEY_PREFIX, keyid_out) in resp)
|
||||||
|
assert((DOPrefixes.PRKD_PREFIX, keyid_out) in resp)
|
||||||
|
|
||||||
|
def test_key_generation_with_key_domain(device):
|
||||||
|
global keyid_in
|
||||||
|
keyid_in = device.key_generation(KeyType.ECC, 'brainpoolP256r1', key_domain=0)
|
||||||
|
device.put_contents(p1=DOPrefixes.PRKD_PREFIX, p2=keyid_in, data=[0xA0])
|
||||||
|
resp = device.list_keys()
|
||||||
|
assert((DOPrefixes.KEY_PREFIX, keyid_in) in resp)
|
||||||
|
assert((DOPrefixes.PRKD_PREFIX, keyid_in) in resp)
|
||||||
|
|
||||||
|
def test_export_key_out(device):
|
||||||
|
with pytest.raises(APDUResponse) as e:
|
||||||
|
device.export_key(keyid_out)
|
||||||
|
assert(e.value.sw == SWCodes.SW_REFERENCE_NOT_FOUND)
|
||||||
|
|
||||||
|
def test_export_key_in_fail(device):
|
||||||
|
with pytest.raises(APDUResponse) as e:
|
||||||
|
device.export_key(keyid_in)
|
||||||
|
assert(e.value.sw == SWCodes.SW_REFERENCE_NOT_FOUND)
|
||||||
|
|
||||||
|
def test_export_import_dkek(device):
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK, key_domain=0)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK, key_domain=0)
|
||||||
|
|
||||||
|
def test_export_key_in_ok(device):
|
||||||
|
resp = device.export_key(keyid_in)
|
||||||
|
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]
|
||||||
|
assert(kcv == resp[:8])
|
||||||
|
assert(resp[8] == 12)
|
||||||
|
assert(resp[9:21] == b"\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x02\x03")
|
||||||
|
|
||||||
|
pkey = hashlib.sha256(b'\x00'*32+b'\x00\x00\x00\x02').digest()
|
||||||
|
c = cmac.CMAC(algorithms.AES(pkey))
|
||||||
|
c.update(resp[:-16])
|
||||||
|
resCMAC = c.finalize()
|
||||||
|
assert(resCMAC == resp[-16:])
|
||||||
|
|
||||||
|
def test_delete_keys_in_out(device):
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid_in)
|
||||||
|
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid_in)
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid_out)
|
||||||
|
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid_out)
|
||||||
|
|
||||||
|
def test_export_import(device):
|
||||||
|
pkey_gen = ec.generate_private_key(ec.BrainpoolP256R1())
|
||||||
|
keyid = device.import_key(pkey_gen)
|
||||||
|
|
||||||
|
resp = device.export_key(keyid)
|
||||||
|
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]
|
||||||
|
assert(kcv == resp[:8])
|
||||||
|
assert(resp[8] == 12)
|
||||||
|
assert(resp[9:21] == b"\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x02\x03")
|
||||||
|
|
||||||
|
pkey = hashlib.sha256(b'\x00'*32+b'\x00\x00\x00\x02').digest()
|
||||||
|
c = cmac.CMAC(algorithms.AES(pkey))
|
||||||
|
c.update(resp[:-16])
|
||||||
|
resCMAC = c.finalize()
|
||||||
|
assert(resCMAC == resp[-16:])
|
||||||
|
|
||||||
|
iv = b'\x00'*16
|
||||||
|
pkey = hashlib.sha256(b'\x00'*32+b'\x00\x00\x00\x01').digest()
|
||||||
|
cipher = Cipher(algorithms.AES(pkey), modes.CBC(iv))
|
||||||
|
decryptor = cipher.decryptor()
|
||||||
|
payload = decryptor.update(resp[27:-16]) + decryptor.finalize()
|
||||||
|
|
||||||
|
rnd = payload[:8]
|
||||||
|
ofs = 8
|
||||||
|
key_size = int.from_bytes(payload[ofs:ofs+2], 'big')
|
||||||
|
ofs += 2
|
||||||
|
A_len = int.from_bytes(payload[ofs:ofs+2], 'big')
|
||||||
|
ofs += 2+A_len
|
||||||
|
B_len = int.from_bytes(payload[ofs:ofs+2], 'big')
|
||||||
|
ofs += 2+B_len
|
||||||
|
P_len = int.from_bytes(payload[ofs:ofs+2], 'big')
|
||||||
|
ofs += 2+P_len
|
||||||
|
N_len = int.from_bytes(payload[ofs:ofs+2], 'big')
|
||||||
|
ofs += 2+N_len
|
||||||
|
G_len = int.from_bytes(payload[ofs:ofs+2], 'big')
|
||||||
|
ofs += 2+G_len
|
||||||
|
d_len = int.from_bytes(payload[ofs:ofs+2], 'big')
|
||||||
|
ofs += 2
|
||||||
|
d = payload[ofs:ofs+d_len]
|
||||||
|
ofs += d_len
|
||||||
|
Q_len = int.from_bytes(payload[ofs:ofs+2], 'big')
|
||||||
|
ofs += 2
|
||||||
|
Q = payload[ofs:ofs+Q_len]
|
||||||
|
ofs += Q_len
|
||||||
|
|
||||||
|
pkey_ex = ec.EllipticCurvePrivateNumbers(int.from_bytes(d, 'big'), ec.EllipticCurvePublicKey.from_encoded_point(ec.BrainpoolP256R1(), Q).public_numbers()).private_key()
|
||||||
|
assert(pkey_gen.private_bytes(serialization.Encoding.DER, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()) == pkey_ex.private_bytes(serialization.Encoding.DER, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()))
|
||||||
|
assert(pkey_gen.public_key().public_bytes(serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint) == pkey_ex.public_key().public_bytes(serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint))
|
||||||
|
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
|
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||||
@@ -18,7 +18,7 @@
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from utils import KeyType, DOPrefixes, Algorithm
|
from picohsm import KeyType, DOPrefixes, Algorithm
|
||||||
from binascii import hexlify
|
from binascii import hexlify
|
||||||
import hashlib
|
import hashlib
|
||||||
|
|
||||||
@@ -39,7 +39,7 @@ def test_signature_ecc(device, curve, scheme):
|
|||||||
else:
|
else:
|
||||||
datab = data
|
datab = data
|
||||||
signature = device.sign(keyid=keyid, scheme=scheme, data=datab)
|
signature = device.sign(keyid=keyid, scheme=scheme, data=datab)
|
||||||
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
device.verify(pubkey, datab, signature, scheme)
|
device.verify(pubkey, datab, signature, scheme)
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
@@ -52,6 +52,15 @@ def test_signature_rsa(device, modulus, scheme):
|
|||||||
keyid = device.key_generation(KeyType.RSA, modulus)
|
keyid = device.key_generation(KeyType.RSA, modulus)
|
||||||
pubkey = device.public_key(keyid=keyid)
|
pubkey = device.public_key(keyid=keyid)
|
||||||
signature = device.sign(keyid=keyid, scheme=scheme, data=data)
|
signature = device.sign(keyid=keyid, scheme=scheme, data=data)
|
||||||
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
device.verify(pubkey, data, signature, scheme)
|
device.verify(pubkey, data, signature, scheme)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"curve", ['ed25519', 'ed448']
|
||||||
|
)
|
||||||
|
def test_signature_edwards(device, curve):
|
||||||
|
keyid = device.key_generation(KeyType.ECC, curve)
|
||||||
|
pubkey = device.public_key(keyid=keyid)
|
||||||
|
signature = device.sign(keyid=keyid, scheme=Algorithm.ALGO_EC_RAW, data=data)
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
|
device.verify(pubkey, data, signature)
|
||||||
|
|||||||
@@ -18,9 +18,8 @@
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
from utils import KeyType, DOPrefixes, Algorithm
|
from picohsm import KeyType, DOPrefixes
|
||||||
from binascii import hexlify
|
from binascii import hexlify
|
||||||
import hashlib
|
|
||||||
from cryptography.hazmat.primitives.asymmetric import padding
|
from cryptography.hazmat.primitives.asymmetric import padding
|
||||||
from cryptography.hazmat.primitives import hashes
|
from cryptography.hazmat.primitives import hashes
|
||||||
|
|
||||||
@@ -43,6 +42,6 @@ def test_decrypt_rsa(device, modulus, pad):
|
|||||||
message = data[:(modulus//8)-100]
|
message = data[:(modulus//8)-100]
|
||||||
ciphered = pubkey.encrypt(message, pad)
|
ciphered = pubkey.encrypt(message, pad)
|
||||||
datab = device.decrypt(keyid, ciphered, pad)
|
datab = device.decrypt(keyid, ciphered, pad)
|
||||||
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
assert(datab == message)
|
assert(datab == message)
|
||||||
|
|
||||||
|
|||||||
@@ -20,8 +20,9 @@
|
|||||||
import pytest
|
import pytest
|
||||||
import os
|
import os
|
||||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||||
from utils import Algorithm, DOPrefixes
|
from picohsm import Algorithm, DOPrefixes
|
||||||
from const import DEFAULT_DKEK_SHARES, DEFAULT_DKEK
|
from picohsm.const import DEFAULT_DKEK_SHARES
|
||||||
|
from const import DEFAULT_DKEK
|
||||||
|
|
||||||
MESSAGE = b'a secret message'
|
MESSAGE = b'a secret message'
|
||||||
|
|
||||||
@@ -42,11 +43,11 @@ def test_cipher_aes_cipher(device, size):
|
|||||||
encryptor = cipher.encryptor()
|
encryptor = cipher.encryptor()
|
||||||
ctA = encryptor.update(MESSAGE) + encryptor.finalize()
|
ctA = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||||
ctB = device.cipher(Algorithm.ALGO_AES_CBC_ENCRYPT, keyid, MESSAGE)
|
ctB = device.cipher(Algorithm.ALGO_AES_CBC_ENCRYPT, keyid, MESSAGE)
|
||||||
assert(bytes(ctB) == ctA)
|
assert(ctB == ctA)
|
||||||
|
|
||||||
decryptor = cipher.decryptor()
|
decryptor = cipher.decryptor()
|
||||||
plA = decryptor.update(ctA) + decryptor.finalize()
|
plA = decryptor.update(ctA) + decryptor.finalize()
|
||||||
plB = device.cipher(Algorithm.ALGO_AES_CBC_DECRYPT, keyid, ctA)
|
plB = device.cipher(Algorithm.ALGO_AES_CBC_DECRYPT, keyid, ctA)
|
||||||
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
assert(bytes(plB) == plA)
|
assert(plB == plA)
|
||||||
assert(bytes(plB) == MESSAGE)
|
assert(plB == MESSAGE)
|
||||||
|
|||||||
126
tests/pico-hsm/test_051_chachapoly.py
Normal file
126
tests/pico-hsm/test_051_chachapoly.py
Normal file
@@ -0,0 +1,126 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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/>.
|
||||||
|
*/
|
||||||
|
"""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
import os
|
||||||
|
from cryptography.hazmat.primitives.ciphers import aead
|
||||||
|
import cryptography.exceptions
|
||||||
|
from picohsm import APDUResponse, DOPrefixes, EncryptionMode, SWCodes
|
||||||
|
from picohsm.const import DEFAULT_DKEK_SHARES
|
||||||
|
from const import DEFAULT_DKEK
|
||||||
|
from binascii import hexlify
|
||||||
|
|
||||||
|
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)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
|
||||||
|
def generate_key(device):
|
||||||
|
# ChaCha uses 32 bytes key
|
||||||
|
pkey = os.urandom(256 // 8)
|
||||||
|
keyid = device.import_key(pkey)
|
||||||
|
return pkey, keyid
|
||||||
|
|
||||||
|
|
||||||
|
def test_cipher_chachapoly_cipher(device):
|
||||||
|
iv = b'\x00'*12
|
||||||
|
pkey, keyid = generate_key(device)
|
||||||
|
|
||||||
|
ctd = device.chachapoly(keyid, EncryptionMode.ENCRYPT, data=MESSAGE, aad=AAD)
|
||||||
|
|
||||||
|
chacha = aead.ChaCha20Poly1305(pkey)
|
||||||
|
ctg = chacha.encrypt(iv, MESSAGE, AAD)
|
||||||
|
assert(ctd == ctg)
|
||||||
|
|
||||||
|
pld = device.chachapoly(keyid, EncryptionMode.DECRYPT, data=ctd, aad=AAD)
|
||||||
|
|
||||||
|
plg = chacha.decrypt(iv, ctg, AAD)
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
|
assert(pld == plg)
|
||||||
|
assert(pld == MESSAGE)
|
||||||
|
|
||||||
|
def test_cipher_chachapoly_random_iv(device):
|
||||||
|
pkey, keyid = generate_key(device)
|
||||||
|
iv = os.urandom(12)
|
||||||
|
ctd = device.chachapoly(keyid, EncryptionMode.ENCRYPT, data=MESSAGE, iv=iv, aad=AAD)
|
||||||
|
|
||||||
|
chacha = aead.ChaCha20Poly1305(pkey)
|
||||||
|
ctg = chacha.encrypt(iv, MESSAGE, AAD)
|
||||||
|
assert(ctd == ctg)
|
||||||
|
|
||||||
|
pld = device.chachapoly(keyid, EncryptionMode.DECRYPT, data=ctd, iv=iv, aad=AAD)
|
||||||
|
|
||||||
|
plg = chacha.decrypt(iv, ctg, AAD)
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
|
assert(pld == plg)
|
||||||
|
assert(pld == MESSAGE)
|
||||||
|
|
||||||
|
def test_cipher_chachapoly_no_aad(device):
|
||||||
|
pkey, keyid = generate_key(device)
|
||||||
|
iv = os.urandom(12)
|
||||||
|
ctd = device.chachapoly(keyid, EncryptionMode.ENCRYPT, data=MESSAGE, iv=iv)
|
||||||
|
|
||||||
|
chacha = aead.ChaCha20Poly1305(pkey)
|
||||||
|
ctg = chacha.encrypt(iv, MESSAGE, b'')
|
||||||
|
assert(ctd == ctg)
|
||||||
|
|
||||||
|
pld = device.chachapoly(keyid, EncryptionMode.DECRYPT, data=ctd, iv=iv)
|
||||||
|
|
||||||
|
plg = chacha.decrypt(iv, ctg, b'')
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
|
assert(pld == plg)
|
||||||
|
assert(pld == MESSAGE)
|
||||||
|
|
||||||
|
def test_cipher_chachapoly_bad_random_iv(device):
|
||||||
|
pkey, keyid = generate_key(device)
|
||||||
|
iv = os.urandom(12)
|
||||||
|
ctd = device.chachapoly(keyid, EncryptionMode.ENCRYPT, data=MESSAGE, iv=iv, aad=AAD)
|
||||||
|
|
||||||
|
chacha = aead.ChaCha20Poly1305(pkey)
|
||||||
|
ctg = chacha.encrypt(iv, MESSAGE, AAD)
|
||||||
|
assert(ctd == ctg)
|
||||||
|
|
||||||
|
iv = os.urandom(12)
|
||||||
|
with pytest.raises(APDUResponse) as e:
|
||||||
|
pld = device.chachapoly(keyid, EncryptionMode.DECRYPT, data=ctd, iv=iv, aad=AAD)
|
||||||
|
assert (e.value.sw == SWCodes.SW_WRONG_DATA)
|
||||||
|
|
||||||
|
with pytest.raises(cryptography.exceptions.InvalidTag):
|
||||||
|
plg = chacha.decrypt(iv, ctg, AAD)
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
|
|
||||||
|
def test_cipher_chachapoly_bad_aad(device):
|
||||||
|
pkey, keyid = generate_key(device)
|
||||||
|
iv = os.urandom(12)
|
||||||
|
ctd = device.chachapoly(keyid, EncryptionMode.ENCRYPT, data=MESSAGE, iv=iv, aad=AAD)
|
||||||
|
|
||||||
|
chacha = aead.ChaCha20Poly1305(pkey)
|
||||||
|
ctg = chacha.encrypt(iv, MESSAGE, AAD)
|
||||||
|
assert(ctd == ctg)
|
||||||
|
|
||||||
|
with pytest.raises(APDUResponse) as e:
|
||||||
|
pld = device.chachapoly(keyid, EncryptionMode.DECRYPT, data=ctd, iv=iv, aad=AAD + b'bad')
|
||||||
|
assert (e.value.sw == SWCodes.SW_WRONG_DATA)
|
||||||
|
|
||||||
|
with pytest.raises(cryptography.exceptions.InvalidTag):
|
||||||
|
plg = chacha.decrypt(iv, ctg, AAD + b'bad')
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
342
tests/pico-hsm/test_052_aes_ext.py
Normal file
342
tests/pico-hsm/test_052_aes_ext.py
Normal file
@@ -0,0 +1,342 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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/>.
|
||||||
|
*/
|
||||||
|
"""
|
||||||
|
|
||||||
|
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.const import DEFAULT_DKEK_SHARES
|
||||||
|
from const import DEFAULT_DKEK
|
||||||
|
from binascii import hexlify
|
||||||
|
|
||||||
|
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)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
|
||||||
|
def generate_key(device, size):
|
||||||
|
pkey = os.urandom(size // 8)
|
||||||
|
keyid = device.import_key(pkey)
|
||||||
|
return pkey, keyid
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
def test_aes_ecb(device, size):
|
||||||
|
pkey, keyid = generate_key(device, size)
|
||||||
|
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.ECB, MESSAGE)
|
||||||
|
|
||||||
|
cipher = Cipher(algorithms.AES(pkey), modes.ECB())
|
||||||
|
encryptor = cipher.encryptor()
|
||||||
|
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||||
|
assert(ctA == ctB)
|
||||||
|
|
||||||
|
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.ECB, ctA)
|
||||||
|
decryptor = cipher.decryptor()
|
||||||
|
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||||
|
assert(dtA == dtB)
|
||||||
|
assert(dtA == MESSAGE)
|
||||||
|
device.delete_key(keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
def test_aes_cbc_no_iv(device, size):
|
||||||
|
pkey, keyid = generate_key(device, size)
|
||||||
|
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.CBC, MESSAGE)
|
||||||
|
|
||||||
|
iv = b'\x00' * 16
|
||||||
|
cipher = Cipher(algorithms.AES(pkey), modes.CBC(iv))
|
||||||
|
encryptor = cipher.encryptor()
|
||||||
|
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||||
|
assert(ctA == ctB)
|
||||||
|
|
||||||
|
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.CBC, ctA)
|
||||||
|
decryptor = cipher.decryptor()
|
||||||
|
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||||
|
assert(dtA == dtB)
|
||||||
|
assert(dtA == MESSAGE)
|
||||||
|
device.delete_key(keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
def test_aes_cbc_iv(device, size):
|
||||||
|
pkey, keyid = generate_key(device, size)
|
||||||
|
iv = os.urandom(16)
|
||||||
|
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.CBC, MESSAGE, iv=iv)
|
||||||
|
|
||||||
|
cipher = Cipher(algorithms.AES(pkey), modes.CBC(iv))
|
||||||
|
encryptor = cipher.encryptor()
|
||||||
|
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||||
|
assert(ctA == ctB)
|
||||||
|
|
||||||
|
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.CBC, ctA, iv=iv)
|
||||||
|
decryptor = cipher.decryptor()
|
||||||
|
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||||
|
assert(dtA == dtB)
|
||||||
|
assert(dtA == MESSAGE)
|
||||||
|
device.delete_key(keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
def test_aes_ofb_no_iv(device, size):
|
||||||
|
pkey, keyid = generate_key(device, size)
|
||||||
|
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.OFB, MESSAGE)
|
||||||
|
|
||||||
|
iv = b'\x00' * 16
|
||||||
|
cipher = Cipher(algorithms.AES(pkey), modes.OFB(iv))
|
||||||
|
encryptor = cipher.encryptor()
|
||||||
|
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||||
|
assert(ctA == ctB)
|
||||||
|
|
||||||
|
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.OFB, ctA)
|
||||||
|
decryptor = cipher.decryptor()
|
||||||
|
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||||
|
assert(dtA == dtB)
|
||||||
|
assert(dtA == MESSAGE)
|
||||||
|
device.delete_key(keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
def test_aes_ofb_iv(device, size):
|
||||||
|
pkey, keyid = generate_key(device, size)
|
||||||
|
iv = os.urandom(16)
|
||||||
|
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.OFB, MESSAGE, iv=iv)
|
||||||
|
|
||||||
|
cipher = Cipher(algorithms.AES(pkey), modes.OFB(iv))
|
||||||
|
encryptor = cipher.encryptor()
|
||||||
|
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||||
|
assert(ctA == ctB)
|
||||||
|
|
||||||
|
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.OFB, ctA, iv=iv)
|
||||||
|
decryptor = cipher.decryptor()
|
||||||
|
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||||
|
assert(dtA == dtB)
|
||||||
|
assert(dtA == MESSAGE)
|
||||||
|
device.delete_key(keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
def test_aes_cfb_no_iv(device, size):
|
||||||
|
pkey, keyid = generate_key(device, size)
|
||||||
|
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.CFB, MESSAGE)
|
||||||
|
|
||||||
|
iv = b'\x00' * 16
|
||||||
|
cipher = Cipher(algorithms.AES(pkey), modes.CFB(iv))
|
||||||
|
encryptor = cipher.encryptor()
|
||||||
|
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||||
|
assert(ctA == ctB)
|
||||||
|
|
||||||
|
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.CFB, ctA)
|
||||||
|
decryptor = cipher.decryptor()
|
||||||
|
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||||
|
assert(dtA == dtB)
|
||||||
|
assert(dtA == MESSAGE)
|
||||||
|
device.delete_key(keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
def test_aes_cfb_iv(device, size):
|
||||||
|
pkey, keyid = generate_key(device, size)
|
||||||
|
iv = os.urandom(16)
|
||||||
|
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.CFB, MESSAGE, iv=iv)
|
||||||
|
|
||||||
|
cipher = Cipher(algorithms.AES(pkey), modes.CFB(iv))
|
||||||
|
encryptor = cipher.encryptor()
|
||||||
|
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||||
|
assert(ctA == ctB)
|
||||||
|
|
||||||
|
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.CFB, ctA, iv=iv)
|
||||||
|
decryptor = cipher.decryptor()
|
||||||
|
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||||
|
assert(dtA == dtB)
|
||||||
|
assert(dtA == MESSAGE)
|
||||||
|
device.delete_key(keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
def test_aes_gcm_no_iv(device, size):
|
||||||
|
pkey, keyid = generate_key(device, size)
|
||||||
|
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.GCM, MESSAGE, aad=AAD)
|
||||||
|
|
||||||
|
iv = b'\x00' * 16
|
||||||
|
encryptor = Cipher(algorithms.AES(pkey), modes.GCM(iv)).encryptor()
|
||||||
|
encryptor.authenticate_additional_data(AAD)
|
||||||
|
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||||
|
assert(ctA == ctB + encryptor.tag)
|
||||||
|
|
||||||
|
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.GCM, ctA, aad=AAD)
|
||||||
|
decryptor = Cipher(algorithms.AES(pkey), modes.GCM(iv, encryptor.tag)).decryptor()
|
||||||
|
decryptor.authenticate_additional_data(AAD)
|
||||||
|
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||||
|
assert(dtA == dtB)
|
||||||
|
assert(dtA == MESSAGE)
|
||||||
|
device.delete_key(keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
def test_aes_gcm_iv(device, size):
|
||||||
|
pkey, keyid = generate_key(device, size)
|
||||||
|
iv = os.urandom(16)
|
||||||
|
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.GCM, MESSAGE, iv=iv, aad=AAD)
|
||||||
|
|
||||||
|
encryptor = Cipher(algorithms.AES(pkey), modes.GCM(iv)).encryptor()
|
||||||
|
encryptor.authenticate_additional_data(AAD)
|
||||||
|
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||||
|
assert(ctA == ctB + encryptor.tag)
|
||||||
|
|
||||||
|
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.GCM, ctA, iv=iv, aad=AAD)
|
||||||
|
decryptor = Cipher(algorithms.AES(pkey), modes.GCM(iv, encryptor.tag)).decryptor()
|
||||||
|
decryptor.authenticate_additional_data(AAD)
|
||||||
|
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||||
|
assert(dtA == dtB)
|
||||||
|
assert(dtA == MESSAGE)
|
||||||
|
device.delete_key(keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [256, 512]
|
||||||
|
)
|
||||||
|
def test_aes_xts_no_iv(device, size):
|
||||||
|
pkey, keyid = generate_key(device, size)
|
||||||
|
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.XTS, MESSAGE)
|
||||||
|
|
||||||
|
iv = b'\x00' * 16
|
||||||
|
cipher = Cipher(algorithms.AES(pkey), modes.XTS(iv))
|
||||||
|
encryptor = cipher.encryptor()
|
||||||
|
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||||
|
assert(ctA == ctB)
|
||||||
|
|
||||||
|
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.XTS, ctA)
|
||||||
|
decryptor = cipher.decryptor()
|
||||||
|
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||||
|
assert(dtA == dtB)
|
||||||
|
assert(dtA == MESSAGE)
|
||||||
|
device.delete_key(keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [256, 512]
|
||||||
|
)
|
||||||
|
def test_aes_xts_iv(device, size):
|
||||||
|
pkey, keyid = generate_key(device, size)
|
||||||
|
iv = os.urandom(16)
|
||||||
|
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.XTS, MESSAGE, iv=iv)
|
||||||
|
|
||||||
|
cipher = Cipher(algorithms.AES(pkey), modes.XTS(iv))
|
||||||
|
encryptor = cipher.encryptor()
|
||||||
|
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||||
|
assert(ctA == ctB)
|
||||||
|
|
||||||
|
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.XTS, ctA, iv=iv)
|
||||||
|
decryptor = cipher.decryptor()
|
||||||
|
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||||
|
assert(dtA == dtB)
|
||||||
|
assert(dtA == MESSAGE)
|
||||||
|
device.delete_key(keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
def test_aes_ctr_no_iv(device, size):
|
||||||
|
pkey, keyid = generate_key(device, size)
|
||||||
|
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.CTR, MESSAGE)
|
||||||
|
|
||||||
|
iv = b'\x00' * 16
|
||||||
|
cipher = Cipher(algorithms.AES(pkey), modes.CTR(iv))
|
||||||
|
encryptor = cipher.encryptor()
|
||||||
|
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||||
|
assert(ctA == ctB)
|
||||||
|
|
||||||
|
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.CTR, ctA)
|
||||||
|
decryptor = cipher.decryptor()
|
||||||
|
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||||
|
assert(dtA == dtB)
|
||||||
|
assert(dtA == MESSAGE)
|
||||||
|
device.delete_key(keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
def test_aes_ctr_iv(device, size):
|
||||||
|
pkey, keyid = generate_key(device, size)
|
||||||
|
iv = os.urandom(16)
|
||||||
|
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.CTR, MESSAGE, iv=iv)
|
||||||
|
|
||||||
|
cipher = Cipher(algorithms.AES(pkey), modes.CTR(iv))
|
||||||
|
encryptor = cipher.encryptor()
|
||||||
|
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||||
|
assert(ctA == ctB)
|
||||||
|
|
||||||
|
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.CTR, ctA, iv=iv)
|
||||||
|
decryptor = cipher.decryptor()
|
||||||
|
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||||
|
assert(dtA == dtB)
|
||||||
|
assert(dtA == MESSAGE)
|
||||||
|
device.delete_key(keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
def test_aes_ccm_no_iv(device, size):
|
||||||
|
pkey, keyid = generate_key(device, size)
|
||||||
|
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.CCM, MESSAGE, aad=AAD)
|
||||||
|
|
||||||
|
iv = b'\x00' * 12
|
||||||
|
encryptor = aead.AESCCM(pkey)
|
||||||
|
ctB = encryptor.encrypt(iv, MESSAGE, AAD)
|
||||||
|
assert(ctA == ctB)
|
||||||
|
|
||||||
|
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.CCM, ctA, aad=AAD)
|
||||||
|
decryptor = encryptor
|
||||||
|
dtB = decryptor.decrypt(iv, ctB, AAD)
|
||||||
|
assert(dtA == dtB)
|
||||||
|
assert(dtA == MESSAGE)
|
||||||
|
device.delete_key(keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"iv_len", [7, 8, 9, 10, 11, 12, 13]
|
||||||
|
)
|
||||||
|
def test_aes_ccm_iv(device, size, iv_len):
|
||||||
|
pkey, keyid = generate_key(device, size)
|
||||||
|
iv = os.urandom(iv_len)
|
||||||
|
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.CCM, MESSAGE, iv=iv, aad=AAD)
|
||||||
|
|
||||||
|
encryptor = aead.AESCCM(pkey)
|
||||||
|
ctB = encryptor.encrypt(iv, MESSAGE, AAD)
|
||||||
|
assert(ctA == ctB)
|
||||||
|
|
||||||
|
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.CCM, ctA, iv=iv, aad=AAD)
|
||||||
|
decryptor = encryptor
|
||||||
|
dtB = decryptor.decrypt(iv, ctB, AAD)
|
||||||
|
assert(dtA == dtB)
|
||||||
|
assert(dtA == MESSAGE)
|
||||||
|
device.delete_key(keyid)
|
||||||
@@ -21,8 +21,9 @@ import pytest
|
|||||||
import os
|
import os
|
||||||
from cryptography.hazmat.primitives import hashes, hmac, cmac
|
from cryptography.hazmat.primitives import hashes, hmac, cmac
|
||||||
from cryptography.hazmat.primitives.ciphers import algorithms
|
from cryptography.hazmat.primitives.ciphers import algorithms
|
||||||
from utils import Algorithm, DOPrefixes
|
from picohsm import DOPrefixes
|
||||||
from const import DEFAULT_DKEK_SHARES, DEFAULT_DKEK
|
from picohsm.const import DEFAULT_DKEK_SHARES
|
||||||
|
from const import DEFAULT_DKEK
|
||||||
|
|
||||||
MESSAGE = b'a secret message'
|
MESSAGE = b'a secret message'
|
||||||
|
|
||||||
@@ -44,8 +45,8 @@ def test_mac_hmac(device, size, algo):
|
|||||||
h = hmac.HMAC(pkey, algo())
|
h = hmac.HMAC(pkey, algo())
|
||||||
h.update(MESSAGE)
|
h.update(MESSAGE)
|
||||||
resB = h.finalize()
|
resB = h.finalize()
|
||||||
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
assert(bytes(resA) == resB)
|
assert(resA == resB)
|
||||||
|
|
||||||
@pytest.mark.parametrize(
|
@pytest.mark.parametrize(
|
||||||
"size", [128, 192, 256]
|
"size", [128, 192, 256]
|
||||||
@@ -57,6 +58,6 @@ def test_mac_cmac(device, size):
|
|||||||
c = cmac.CMAC(algorithms.AES(pkey))
|
c = cmac.CMAC(algorithms.AES(pkey))
|
||||||
c.update(MESSAGE)
|
c.update(MESSAGE)
|
||||||
resB = c.finalize()
|
resB = c.finalize()
|
||||||
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
assert(bytes(resA) == resB)
|
assert(resA == resB)
|
||||||
|
|
||||||
|
|||||||
@@ -22,8 +22,9 @@ import os
|
|||||||
from cryptography.hazmat.primitives import hashes
|
from cryptography.hazmat.primitives import hashes
|
||||||
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
||||||
from cryptography import exceptions
|
from cryptography import exceptions
|
||||||
from const import DEFAULT_DKEK_SHARES, DEFAULT_DKEK
|
from picohsm.const import DEFAULT_DKEK_SHARES
|
||||||
from utils import DOPrefixes
|
from const import DEFAULT_DKEK
|
||||||
|
from picohsm import DOPrefixes
|
||||||
|
|
||||||
INFO = b'info message'
|
INFO = b'info message'
|
||||||
|
|
||||||
@@ -47,7 +48,7 @@ class TestHKDF:
|
|||||||
keyid = device.import_key(pkey)
|
keyid = device.import_key(pkey)
|
||||||
salt = os.urandom(16)
|
salt = os.urandom(16)
|
||||||
resA = device.hkdf(algo, keyid, INFO, salt, out_len=out_len)
|
resA = device.hkdf(algo, keyid, INFO, salt, out_len=out_len)
|
||||||
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
hkdf = HKDF(
|
hkdf = HKDF(
|
||||||
algorithm=algo(),
|
algorithm=algo(),
|
||||||
length=out_len,
|
length=out_len,
|
||||||
@@ -55,21 +56,21 @@ class TestHKDF:
|
|||||||
info=INFO,
|
info=INFO,
|
||||||
)
|
)
|
||||||
resB = hkdf.derive(pkey)
|
resB = hkdf.derive(pkey)
|
||||||
assert(bytes(resA) == resB)
|
assert(resA == resB)
|
||||||
hkdf = HKDF(
|
hkdf = HKDF(
|
||||||
algorithm=algo(),
|
algorithm=algo(),
|
||||||
length=out_len,
|
length=out_len,
|
||||||
salt=salt,
|
salt=salt,
|
||||||
info=INFO,
|
info=INFO,
|
||||||
)
|
)
|
||||||
hkdf.verify(pkey, bytes(resA))
|
hkdf.verify(pkey, resA)
|
||||||
|
|
||||||
def test_hkdf_fail(self, device, size, algo, out_len):
|
def test_hkdf_fail(self, device, size, algo, out_len):
|
||||||
pkey = os.urandom(size // 8)
|
pkey = os.urandom(size // 8)
|
||||||
keyid = device.import_key(pkey)
|
keyid = device.import_key(pkey)
|
||||||
salt = os.urandom(16)
|
salt = os.urandom(16)
|
||||||
resA = device.hkdf(algo, keyid, INFO, salt, out_len=out_len)
|
resA = device.hkdf(algo, keyid, INFO, salt, out_len=out_len)
|
||||||
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
hkdf = HKDF(
|
hkdf = HKDF(
|
||||||
algorithm=algo(),
|
algorithm=algo(),
|
||||||
length=out_len,
|
length=out_len,
|
||||||
@@ -78,4 +79,4 @@ class TestHKDF:
|
|||||||
)
|
)
|
||||||
pkey = os.urandom(size // 8)
|
pkey = os.urandom(size // 8)
|
||||||
with pytest.raises(exceptions.InvalidKey):
|
with pytest.raises(exceptions.InvalidKey):
|
||||||
hkdf.verify(pkey, bytes(resA))
|
hkdf.verify(pkey, resA)
|
||||||
|
|||||||
@@ -22,8 +22,9 @@ import os
|
|||||||
from cryptography.hazmat.primitives import hashes
|
from cryptography.hazmat.primitives import hashes
|
||||||
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
||||||
from cryptography import exceptions
|
from cryptography import exceptions
|
||||||
from const import DEFAULT_DKEK_SHARES, DEFAULT_DKEK
|
from picohsm.const import DEFAULT_DKEK_SHARES
|
||||||
from utils import DOPrefixes
|
from const import DEFAULT_DKEK
|
||||||
|
from picohsm import DOPrefixes
|
||||||
|
|
||||||
INFO = b'info message'
|
INFO = b'info message'
|
||||||
|
|
||||||
@@ -50,7 +51,7 @@ class TestPBKDF2:
|
|||||||
keyid = device.import_key(pkey)
|
keyid = device.import_key(pkey)
|
||||||
salt = os.urandom(16)
|
salt = os.urandom(16)
|
||||||
resA = device.pbkdf2(algo, keyid, salt, iterations=iterations, out_len=out_len)
|
resA = device.pbkdf2(algo, keyid, salt, iterations=iterations, out_len=out_len)
|
||||||
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
kdf = PBKDF2HMAC(
|
kdf = PBKDF2HMAC(
|
||||||
algorithm=algo(),
|
algorithm=algo(),
|
||||||
length=out_len,
|
length=out_len,
|
||||||
@@ -58,21 +59,21 @@ class TestPBKDF2:
|
|||||||
iterations=iterations,
|
iterations=iterations,
|
||||||
)
|
)
|
||||||
resB = kdf.derive(pkey)
|
resB = kdf.derive(pkey)
|
||||||
assert(bytes(resA) == resB)
|
assert(resA == resB)
|
||||||
kdf = PBKDF2HMAC(
|
kdf = PBKDF2HMAC(
|
||||||
algorithm=algo(),
|
algorithm=algo(),
|
||||||
length=out_len,
|
length=out_len,
|
||||||
salt=salt,
|
salt=salt,
|
||||||
iterations=iterations,
|
iterations=iterations,
|
||||||
)
|
)
|
||||||
kdf.verify(pkey, bytes(resA))
|
kdf.verify(pkey, resA)
|
||||||
|
|
||||||
def test_pbkdf2_fail(self, device, size, algo, out_len, iterations):
|
def test_pbkdf2_fail(self, device, size, algo, out_len, iterations):
|
||||||
pkey = os.urandom(size // 8)
|
pkey = os.urandom(size // 8)
|
||||||
keyid = device.import_key(pkey)
|
keyid = device.import_key(pkey)
|
||||||
salt = os.urandom(16)
|
salt = os.urandom(16)
|
||||||
resA = device.pbkdf2(algo, keyid, salt, iterations=iterations, out_len=out_len)
|
resA = device.pbkdf2(algo, keyid, salt, iterations=iterations, out_len=out_len)
|
||||||
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
|
|
||||||
kdf = PBKDF2HMAC(
|
kdf = PBKDF2HMAC(
|
||||||
algorithm=algo(),
|
algorithm=algo(),
|
||||||
@@ -82,4 +83,4 @@ class TestPBKDF2:
|
|||||||
)
|
)
|
||||||
pkey = os.urandom(size // 8)
|
pkey = os.urandom(size // 8)
|
||||||
with pytest.raises(exceptions.InvalidKey):
|
with pytest.raises(exceptions.InvalidKey):
|
||||||
kdf.verify(pkey, bytes(resA))
|
kdf.verify(pkey, resA)
|
||||||
|
|||||||
@@ -22,8 +22,9 @@ import os
|
|||||||
from cryptography.hazmat.primitives import hashes
|
from cryptography.hazmat.primitives import hashes
|
||||||
from cryptography.hazmat.primitives.kdf.x963kdf import X963KDF
|
from cryptography.hazmat.primitives.kdf.x963kdf import X963KDF
|
||||||
from cryptography import exceptions
|
from cryptography import exceptions
|
||||||
from const import DEFAULT_DKEK_SHARES, DEFAULT_DKEK
|
from picohsm.const import DEFAULT_DKEK_SHARES
|
||||||
from utils import DOPrefixes
|
from const import DEFAULT_DKEK
|
||||||
|
from picohsm import DOPrefixes
|
||||||
|
|
||||||
INFO = b'shared message'
|
INFO = b'shared message'
|
||||||
|
|
||||||
@@ -46,26 +47,26 @@ class TestX963:
|
|||||||
pkey = os.urandom(size // 8)
|
pkey = os.urandom(size // 8)
|
||||||
keyid = device.import_key(pkey)
|
keyid = device.import_key(pkey)
|
||||||
resA = device.x963(algo, keyid, INFO, out_len=out_len)
|
resA = device.x963(algo, keyid, INFO, out_len=out_len)
|
||||||
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
xkdf = X963KDF(
|
xkdf = X963KDF(
|
||||||
algorithm=algo(),
|
algorithm=algo(),
|
||||||
length=out_len,
|
length=out_len,
|
||||||
sharedinfo=INFO,
|
sharedinfo=INFO,
|
||||||
)
|
)
|
||||||
resB = xkdf.derive(pkey)
|
resB = xkdf.derive(pkey)
|
||||||
assert(bytes(resA) == resB)
|
assert(resA == resB)
|
||||||
xkdf = X963KDF(
|
xkdf = X963KDF(
|
||||||
algorithm=algo(),
|
algorithm=algo(),
|
||||||
length=out_len,
|
length=out_len,
|
||||||
sharedinfo=INFO,
|
sharedinfo=INFO,
|
||||||
)
|
)
|
||||||
xkdf.verify(pkey, bytes(resA))
|
xkdf.verify(pkey, resA)
|
||||||
|
|
||||||
def test_x963_fail(self, device, size, algo, out_len):
|
def test_x963_fail(self, device, size, algo, out_len):
|
||||||
pkey = os.urandom(size // 8)
|
pkey = os.urandom(size // 8)
|
||||||
keyid = device.import_key(pkey)
|
keyid = device.import_key(pkey)
|
||||||
resA = device.x963(algo, keyid, INFO, out_len=out_len)
|
resA = device.x963(algo, keyid, INFO, out_len=out_len)
|
||||||
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
xkdf = X963KDF(
|
xkdf = X963KDF(
|
||||||
algorithm=algo(),
|
algorithm=algo(),
|
||||||
length=out_len,
|
length=out_len,
|
||||||
@@ -73,4 +74,4 @@ class TestX963:
|
|||||||
)
|
)
|
||||||
pkey = os.urandom(size // 8)
|
pkey = os.urandom(size // 8)
|
||||||
with pytest.raises(exceptions.InvalidKey):
|
with pytest.raises(exceptions.InvalidKey):
|
||||||
xkdf.verify(pkey, bytes(resA))
|
xkdf.verify(pkey, resA)
|
||||||
|
|||||||
146
tests/pico-hsm/test_080_pka.py
Normal file
146
tests/pico-hsm/test_080_pka.py
Normal file
@@ -0,0 +1,146 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* This file is part of the Pico HSM distribution (https://github.com/polhenarejos/pico-hsm).
|
||||||
|
* Copyright (c) 2023 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/>.
|
||||||
|
*/
|
||||||
|
"""
|
||||||
|
|
||||||
|
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 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_pk = ec.derive_private_key(int.from_bytes(AUT_KEY, 'big'), ec.BrainpoolP256R1())
|
||||||
|
AUT_PUK = unhexlify('678201ed7f218201937f4e82014b5f290100421045535049434f48534d54525a474e50327f4982011d060a04007f000702020202038120a9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e537782207d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9832026dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b68441048bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f0469978520a9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a78641040cc18ce246da678239af0913a1579dda58c07be404da4a65327794fac93f57a333267979905b5d046da7020226cc4e5fc477e8fc651a0cf87095259aafa88e648701015f201045535049434f48534d54525a474e50325f37401fc90bdab2a58c3cd25f18a90baa2c21d3d087002ba240fb274ff066759297f79e130053d902d637a448c8cdcd0670fe8ebcc06d8a3ee82079f08d1ff8660393421045535049434f48534d54525a474e50325f3740e24e7e23eae3c78f9fa88391004369a293c43ef99e2279170983e1dbe707fbf0382d09de3e60ef1addd2f055947c3efcef17926065ddb7a031f4905da474ed1d')
|
||||||
|
|
||||||
|
|
||||||
|
term_chr = CVC().decode(TERM_CERT).chr()
|
||||||
|
|
||||||
|
def test_initialize(device):
|
||||||
|
device.initialize(puk_auts=1, puk_min_auts=1)
|
||||||
|
device.logout()
|
||||||
|
|
||||||
|
def test_register_puk(device):
|
||||||
|
status = device.get_puk_status()
|
||||||
|
assert(status == bytes([1,1,1,0]))
|
||||||
|
|
||||||
|
status = device.register_puk(AUT_PUK, TERM_CERT, DICA_CERT)
|
||||||
|
assert(status == bytes([1,0,1,0]))
|
||||||
|
assert(device.check_puk_key(term_chr) == 0)
|
||||||
|
|
||||||
|
def test_enumerate_puk_reg(device):
|
||||||
|
puks = device.enumerate_puk()
|
||||||
|
assert(len(puks) == 1)
|
||||||
|
assert(puks[0]['status'] == 0)
|
||||||
|
|
||||||
|
def test_authentication(device):
|
||||||
|
input = device.puk_prepare_signature()
|
||||||
|
signature = aut_pk.sign(input, ec.ECDSA(hashes.SHA256()))
|
||||||
|
r,s = utils.decode_dss_signature(signature)
|
||||||
|
signature = list(int_to_bytes(r) + int_to_bytes(s))
|
||||||
|
device.authenticate_puk(term_chr, signature)
|
||||||
|
status = device.get_puk_status()
|
||||||
|
assert(status == bytes([1,0,1,1]))
|
||||||
|
|
||||||
|
def test_enumerate_puk_ok(device):
|
||||||
|
puks = device.enumerate_puk()
|
||||||
|
assert(len(puks) == 1)
|
||||||
|
assert(puks[0]['status'] == 1)
|
||||||
|
|
||||||
|
def test_check_key(device):
|
||||||
|
assert(device.check_puk_key(term_chr) == 1)
|
||||||
|
bad_chr = b'XXXXX'
|
||||||
|
assert(device.check_puk_key(bad_chr) == -1)
|
||||||
|
assert(device.check_puk_key(bad_chr) != 0)
|
||||||
|
assert(device.check_puk_key(bad_chr) != 1)
|
||||||
|
|
||||||
|
def test_puk_reset(device):
|
||||||
|
device.logout()
|
||||||
|
status = device.get_puk_status()
|
||||||
|
assert(status == bytes([1,0,1,0]))
|
||||||
|
assert(device.check_puk_key(term_chr) == 0)
|
||||||
|
|
||||||
|
def test_authentication_fail(device):
|
||||||
|
input = b'this is a fake input'
|
||||||
|
signature = aut_pk.sign(input, ec.ECDSA(hashes.SHA256()))
|
||||||
|
r,s = utils.decode_dss_signature(signature)
|
||||||
|
signature = list(int_to_bytes(r) + int_to_bytes(s))
|
||||||
|
with pytest.raises(APDUResponse) as e:
|
||||||
|
device.authenticate_puk(term_chr, signature)
|
||||||
|
assert(e.value.sw == SWCodes.SW_CONDITIONS_NOT_SATISFIED)
|
||||||
|
|
||||||
|
status = device.get_puk_status()
|
||||||
|
assert(status == bytes([1,0,1,0]))
|
||||||
|
assert(device.check_puk_key(term_chr) == 0)
|
||||||
|
|
||||||
|
def test_enumerate_puk_1(device):
|
||||||
|
device.initialize(puk_auts=1, puk_min_auts=1)
|
||||||
|
puks = device.enumerate_puk()
|
||||||
|
assert(len(puks) == 1)
|
||||||
|
assert(puks[0]['status'] == -1)
|
||||||
|
|
||||||
|
device.register_puk(AUT_PUK, TERM_CERT, DICA_CERT)
|
||||||
|
puks = device.enumerate_puk()
|
||||||
|
assert(len(puks) == 1)
|
||||||
|
assert(puks[0]['status'] == 0)
|
||||||
|
|
||||||
|
def test_enumerate_puk_2(device):
|
||||||
|
device.initialize(puk_auts=2, puk_min_auts=1)
|
||||||
|
puks = device.enumerate_puk()
|
||||||
|
assert(len(puks) == 2)
|
||||||
|
assert(puks[0]['status'] == -1)
|
||||||
|
assert(puks[1]['status'] == -1)
|
||||||
|
|
||||||
|
device.register_puk(AUT_PUK, TERM_CERT, DICA_CERT)
|
||||||
|
puks = device.enumerate_puk()
|
||||||
|
assert(len(puks) == 2)
|
||||||
|
assert(puks[0]['status'] == 0)
|
||||||
|
assert(puks[1]['status'] == -1)
|
||||||
|
|
||||||
|
def test_register_more_puks(device):
|
||||||
|
device.initialize(puk_auts=2, puk_min_auts=1)
|
||||||
|
status = device.get_puk_status()
|
||||||
|
assert(status == bytes([2,2,1,0]))
|
||||||
|
|
||||||
|
status = device.register_puk(AUT_PUK, TERM_CERT, DICA_CERT)
|
||||||
|
assert(status == bytes([2,1,1,0]))
|
||||||
|
|
||||||
|
def test_is_pku(device):
|
||||||
|
device.initialize(puk_auts=1, puk_min_auts=1)
|
||||||
|
assert(device.is_puk() == True)
|
||||||
|
|
||||||
|
device.initialize()
|
||||||
|
assert(device.is_puk() == False)
|
||||||
|
|
||||||
|
def test_check_puk_key(device):
|
||||||
|
device.initialize(puk_auts=1, puk_min_auts=1)
|
||||||
|
status = device.check_puk_key(term_chr)
|
||||||
|
assert(status == -1)
|
||||||
|
|
||||||
|
status = device.register_puk(AUT_PUK, TERM_CERT, DICA_CERT)
|
||||||
|
status = device.check_puk_key(term_chr)
|
||||||
|
assert(status == 0)
|
||||||
|
|
||||||
|
|
||||||
|
def test_register_puk_with_no_puk(device):
|
||||||
|
device.initialize()
|
||||||
|
with pytest.raises(APDUResponse) as e:
|
||||||
|
device.register_puk(AUT_PUK, TERM_CERT, DICA_CERT)
|
||||||
|
assert(e.value.sw == SWCodes.SW_FILE_NOT_FOUND)
|
||||||
98
tests/pico-hsm/test_090_xkek.py
Normal file
98
tests/pico-hsm/test_090_xkek.py
Normal file
@@ -0,0 +1,98 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* This file is part of the Pico HSM distribution (https://github.com/polhenarejos/pico-hsm).
|
||||||
|
* Copyright (c) 2023 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/>.
|
||||||
|
*/
|
||||||
|
"""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from binascii import unhexlify, hexlify
|
||||||
|
from picohsm.utils import int_to_bytes
|
||||||
|
from const import TERM_CERT, DICA_CERT
|
||||||
|
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
|
||||||
|
|
||||||
|
KDM = unhexlify(b'30820420060b2b0601040181c31f0402016181ed7f2181e97f4e81a25f290100421045535049434f48534d434130303030317f494f060a04007f0007020202020386410421ee4a21c16a10f737f12e78e5091b266612038cdabebb722b15bf6d41b877fbf64d9ab69c39b9831b1ae00bef2a4e81976f7688d45189bb232a24703d8a96a55f201045535049434f48534d445630303030317f4c12060904007f000703010202530580000000005f25060202000801085f24060203000601045f37403f75c08fffc9186b56e6147199e82bfc327ceef72495bc567961cd54d702f13e3c2766fcd1d11bd6a9d1f4a229b76b248ceb9af88d59a74d0ab149448705159b6281e97f2181e57f4e819e5f290100421045535049434f48534d445630303030317f494f060a04007f00070202020203864104c8561b41e54fea81bb80dd4a6d537e7c3904344e8ca90bc5f668111811e02c8d5d51ca93ca89558f2a8a9cbb147434e3441ec174505ff980fd7a7106286196915f201045535049434f48534d54524a444736387f4c0e060904007f0007030102025301005f25060203000300065f24060204000300055f3740983de63d0975b715ebd8a93cb38fa9638882c8b7064d51a6facabed693b92edc098e458b713203413ef6de0958c44772cbdbc264205c7b1bdb8b4fcb2516437f638201f1678201ed7f218201937f4e82014b5f290100421045535049434f48534d54524a444736387f4982011d060a04007f000702020202038120a9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e537782207d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9832026dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b68441048bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f0469978520a9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a78641048b1f450912a2e4d428b7eefc5fa05618a9ef295e90009a61cbb0970181b333474ea94f94cde5a11aba0589e85d4225002789ff1cdcf25756f059647b49fc2a158701015f201045535049434f48534d54524a444736385f3740372407c20de7257c89dae1e6606c8a046ca65efaa010c0a22b75c402ee243de51f5f1507457193679ed9db4fbbfe8efb9d695b684492b665ad8ba98c1f84ea38421045535049434f48534d54524a444736385f374098718e2e14a44386b689b71a101530316b65ab49a91bab0dd56099c5161ecb8aadff6cf27449f94034e58b7306f01e6ffa2766a2f5bb1281e12e5f1f9174733454400cf8926ca5bec9a91bcd47bf391c15d94ef6e3243d5fd1fffeaafd586766bc3221eafd808f17f8450f238cc1fe7ab1854443db31d622f53a2b3fdb3ad750d5ce')
|
||||||
|
|
||||||
|
def test_initialize(device):
|
||||||
|
device.initialize(key_domains=1)
|
||||||
|
device.logout()
|
||||||
|
|
||||||
|
def test_create_xkek(device):
|
||||||
|
with pytest.raises(APDUResponse) as e:
|
||||||
|
device.create_xkek(KDM)
|
||||||
|
assert(e.value.sw == SWCodes.SW_CONDITIONS_NOT_SATISFIED)
|
||||||
|
|
||||||
|
device.login()
|
||||||
|
kcv, did = device.create_xkek(KDM)
|
||||||
|
assert(kcv == b'\x00'*8)
|
||||||
|
|
||||||
|
gskcert = ASN1().decode(KDM).find(0x30).find(0x63).data()
|
||||||
|
gskQ = CVC().decode(gskcert).pubkey().find(0x86).data()
|
||||||
|
pub = ec.EllipticCurvePublicKey.from_encoded_point(ec.BrainpoolP256R1(), bytes(gskQ))
|
||||||
|
assert(did == int_to_bytes(pub.public_numbers().x)+int_to_bytes(pub.public_numbers().y))
|
||||||
|
|
||||||
|
keyid = -1
|
||||||
|
def test_derive_xkek(device):
|
||||||
|
global keyid
|
||||||
|
keyid = device.generate_xkek_key()
|
||||||
|
|
||||||
|
resp = device.list_keys()
|
||||||
|
assert((DOPrefixes.KEY_PREFIX, keyid) in resp)
|
||||||
|
|
||||||
|
xkek_dom = device.get_key_domain()['xkek']
|
||||||
|
pkey = ec.generate_private_key(ec.BrainpoolP256R1())
|
||||||
|
pubkey = pkey.public_key()
|
||||||
|
cert = CVC().cert(pubkey=pubkey, scheme=oid.ID_TA_ECDSA_SHA_256, signkey=pkey, signscheme=oid.ID_TA_ECDSA_SHA_256, car=b"UTCA00001", chr=b"UTCDUMMY00001", extensions=[
|
||||||
|
{
|
||||||
|
'tag': 0x73,
|
||||||
|
'oid': b'\x2B\x06\x01\x04\x01\x81\xC3\x1F\x03\x02\x02',
|
||||||
|
'contexts': {
|
||||||
|
0: xkek_dom
|
||||||
|
}
|
||||||
|
}
|
||||||
|
]).encode()
|
||||||
|
device.derive_xkek(keyid, cert)
|
||||||
|
|
||||||
|
resp = device.get_key_domain()
|
||||||
|
assert(resp['kcv'] != b'\x00'*8)
|
||||||
|
|
||||||
|
|
||||||
|
def test_delete_xkek(device):
|
||||||
|
device.delete_xkek()
|
||||||
|
|
||||||
|
resp = device.get_key_domain()
|
||||||
|
assert(resp['kcv'] == b'\x00'*8)
|
||||||
|
|
||||||
|
def test_delete_domain_with_key(device):
|
||||||
|
with pytest.raises(APDUResponse) as e:
|
||||||
|
device.delete_key_domain()
|
||||||
|
assert(e.value.sw == SWCodes.SW_FILE_EXISTS)
|
||||||
|
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||||
|
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||||
|
|
||||||
|
def test_delete_domain(device):
|
||||||
|
device.delete_key_domain()
|
||||||
|
|
||||||
|
resp = device.get_key_domain()
|
||||||
|
assert('kcv' not in resp)
|
||||||
|
assert('xkek' not in resp)
|
||||||
|
assert('error' in resp)
|
||||||
|
assert(resp['error'] == SWCodes.SW_REFERENCE_NOT_FOUND)
|
||||||
|
|
||||||
453
tests/pico-hsm/test_095_bip_slip.py
Normal file
453
tests/pico-hsm/test_095_bip_slip.py
Normal file
@@ -0,0 +1,453 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* This file is part of the Pico HSM distribution (https://github.com/polhenarejos/pico-hsm).
|
||||||
|
* Copyright (c) 2023 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/>.
|
||||||
|
*/
|
||||||
|
"""
|
||||||
|
|
||||||
|
import pytest
|
||||||
|
from binascii import unhexlify, hexlify
|
||||||
|
from picohsm.utils import int_to_bytes
|
||||||
|
from picohsm.const import DEFAULT_DKEK_SHARES
|
||||||
|
from const import DEFAULT_DKEK
|
||||||
|
from cvc.asn1 import ASN1
|
||||||
|
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
|
||||||
|
import hashlib
|
||||||
|
|
||||||
|
TEST_STRING = b'Pico Keys are awesome!'
|
||||||
|
|
||||||
|
def sha256_sha256(data):
|
||||||
|
return hashlib.sha256(hashlib.sha256(data).digest()).digest()
|
||||||
|
|
||||||
|
def test_initialize(device):
|
||||||
|
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
|
||||||
|
seeds = [
|
||||||
|
{
|
||||||
|
'name': 'secp256k1',
|
||||||
|
'id': 0,
|
||||||
|
'seed': unhexlify('000102030405060708090a0b0c0d0e0f'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'name': 'secp256k1',
|
||||||
|
'id': 1,
|
||||||
|
'seed': unhexlify('fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'name': 'secp256k1',
|
||||||
|
'id': 2,
|
||||||
|
'seed': unhexlify('4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'name': 'secp256k1',
|
||||||
|
'id': 3,
|
||||||
|
'seed': unhexlify('3ddd5602285899a946114506157c7997e5444528f3003f6134712147db19b678'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'name': 'secp256r1',
|
||||||
|
'id': 4,
|
||||||
|
'seed': unhexlify('000102030405060708090a0b0c0d0e0f'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'name': 'secp256r1',
|
||||||
|
'id': 5,
|
||||||
|
'seed': unhexlify('fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'name': 'secp256r1',
|
||||||
|
'id': 6,
|
||||||
|
'seed': unhexlify('a7305bc8df8d0951f0cb224c0e95d7707cbdf2c6ce7e8d481fec69c7ff5e9446'),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'name': 'symmetric',
|
||||||
|
'id': 7,
|
||||||
|
'seed': unhexlify('c76c4ac4f4e4a00d6b274d5c39c700bb4a7ddc04fbc6f78e85ca75007b5b495f74a9043eeb77bdd53aa6fc3a0e31462270316fa04b8c19114c8798706cd02ac8'),
|
||||||
|
},
|
||||||
|
]
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"seed", seeds
|
||||||
|
)
|
||||||
|
def test_generate_master(device, seed):
|
||||||
|
resp = device.hd_generate_master_node(curve=seed['name'], id=seed['id'], seed=seed['seed'])
|
||||||
|
|
||||||
|
def hardened(i):
|
||||||
|
return 0x80000000 + i
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"path", [
|
||||||
|
{
|
||||||
|
'path': [0],
|
||||||
|
'xpub': b'xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [0, hardened(0)],
|
||||||
|
'xpub': b'xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [0, hardened(0), 1],
|
||||||
|
'xpub': b'xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [0, hardened(0), 1, hardened(2)],
|
||||||
|
'xpub': b'xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [0, hardened(0), 1, hardened(2), 2],
|
||||||
|
'xpub': b'xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [0, hardened(0), 1, hardened(2), 2, 1000000000],
|
||||||
|
'xpub': b'xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [1],
|
||||||
|
'xpub': b'xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [1, 0],
|
||||||
|
'xpub': b'xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [1, 0, hardened(2147483647)],
|
||||||
|
'xpub': b'xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [1, 0, hardened(2147483647), 1],
|
||||||
|
'xpub': b'xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [1, 0, hardened(2147483647), 1, hardened(2147483646)],
|
||||||
|
'xpub': b'xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [1, 0, hardened(2147483647), 1, hardened(2147483646), 2],
|
||||||
|
'xpub': b'xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [2],
|
||||||
|
'xpub': b'xpub661MyMwAqRbcEZVB4dScxMAdx6d4nFc9nvyvH3v4gJL378CSRZiYmhRoP7mBy6gSPSCYk6SzXPTf3ND1cZAceL7SfJ1Z3GC8vBgp2epUt13',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [2, hardened(0)],
|
||||||
|
'xpub': b'xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [3],
|
||||||
|
'xpub': b'xpub661MyMwAqRbcGczjuMoRm6dXaLDEhW1u34gKenbeYqAix21mdUKJyuyu5F1rzYGVxyL6tmgBUAEPrEz92mBXjByMRiJdba9wpnN37RLLAXa',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [3, hardened(0)],
|
||||||
|
'xpub': b'xpub69AUMk3qDBi3uW1sXgjCmVjJ2G6WQoYSnNHyzkmdCHEhSZ4tBok37xfFEqHd2AddP56Tqp4o56AePAgCjYdvpW2PU2jbUPFKsav5ut6Ch1m',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [3, hardened(0), hardened(1)],
|
||||||
|
'xpub': b'xpub6BJA1jSqiukeaesWfxe6sNK9CCGaujFFSJLomWHprUL9DePQ4JDkM5d88n49sMGJxrhpjazuXYWdMf17C9T5XnxkopaeS7jGk1GyyVziaMt',
|
||||||
|
},
|
||||||
|
]
|
||||||
|
)
|
||||||
|
def test_derive_node_bip(device, path):
|
||||||
|
resp = device.hd_derive_node(path['path'])
|
||||||
|
assert(resp == path['xpub'])
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"path", [
|
||||||
|
{
|
||||||
|
'path': [0],
|
||||||
|
'fingerprint': unhexlify('00000000'),
|
||||||
|
'chain': unhexlify('873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d508'),
|
||||||
|
'public': unhexlify('0339a36013301597daef41fbe593a02cc513d0b55527ec2df1050e2e8ff49c85c2')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [0, hardened(0)],
|
||||||
|
'fingerprint': unhexlify('3442193e'),
|
||||||
|
'chain': unhexlify('47fdacbd0f1097043b78c63c20c34ef4ed9a111d980047ad16282c7ae6236141'),
|
||||||
|
'public': unhexlify('035a784662a4a20a65bf6aab9ae98a6c068a81c52e4b032c0fb5400c706cfccc56')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [0, hardened(0), 1],
|
||||||
|
'fingerprint': unhexlify('5c1bd648'),
|
||||||
|
'chain': unhexlify('2a7857631386ba23dacac34180dd1983734e444fdbf774041578e9b6adb37c19'),
|
||||||
|
'public': unhexlify('03501e454bf00751f24b1b489aa925215d66af2234e3891c3b21a52bedb3cd711c')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [0, hardened(0), 1, hardened(2)],
|
||||||
|
'fingerprint': unhexlify('bef5a2f9'),
|
||||||
|
'chain': unhexlify('04466b9cc8e161e966409ca52986c584f07e9dc81f735db683c3ff6ec7b1503f'),
|
||||||
|
'public': unhexlify('0357bfe1e341d01c69fe5654309956cbea516822fba8a601743a012a7896ee8dc2')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [0, hardened(0), 1, hardened(2), 2],
|
||||||
|
'fingerprint': unhexlify('ee7ab90c'),
|
||||||
|
'chain': unhexlify('cfb71883f01676f587d023cc53a35bc7f88f724b1f8c2892ac1275ac822a3edd'),
|
||||||
|
'public': unhexlify('02e8445082a72f29b75ca48748a914df60622a609cacfce8ed0e35804560741d29')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [0, hardened(0), 1, hardened(2), 2, 1000000000],
|
||||||
|
'fingerprint': unhexlify('d880d7d8'),
|
||||||
|
'chain': unhexlify('c783e67b921d2beb8f6b389cc646d7263b4145701dadd2161548a8b078e65e9e'),
|
||||||
|
'public': unhexlify('022a471424da5e657499d1ff51cb43c47481a03b1e77f951fe64cec9f5a48f7011')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [4],
|
||||||
|
'fingerprint': unhexlify('00000000'),
|
||||||
|
'chain': unhexlify('beeb672fe4621673f722f38529c07392fecaa61015c80c34f29ce8b41b3cb6ea'),
|
||||||
|
'public': unhexlify('0266874dc6ade47b3ecd096745ca09bcd29638dd52c2c12117b11ed3e458cfa9e8')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [4, hardened(0)],
|
||||||
|
'fingerprint': unhexlify('be6105b5'),
|
||||||
|
'chain': unhexlify('3460cea53e6a6bb5fb391eeef3237ffd8724bf0a40e94943c98b83825342ee11'),
|
||||||
|
'public': unhexlify('0384610f5ecffe8fda089363a41f56a5c7ffc1d81b59a612d0d649b2d22355590c')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [4, hardened(0), 1],
|
||||||
|
'fingerprint': unhexlify('9b02312f'),
|
||||||
|
'chain': unhexlify('4187afff1aafa8445010097fb99d23aee9f599450c7bd140b6826ac22ba21d0c'),
|
||||||
|
'public': unhexlify('03526c63f8d0b4bbbf9c80df553fe66742df4676b241dabefdef67733e070f6844')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [4, hardened(0), 1, hardened(2)],
|
||||||
|
'fingerprint': unhexlify('b98005c1'),
|
||||||
|
'chain': unhexlify('98c7514f562e64e74170cc3cf304ee1ce54d6b6da4f880f313e8204c2a185318'),
|
||||||
|
'public': unhexlify('0359cf160040778a4b14c5f4d7b76e327ccc8c4a6086dd9451b7482b5a4972dda0')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [4, hardened(0), 1, hardened(2), 2],
|
||||||
|
'fingerprint': unhexlify('0e9f3274'),
|
||||||
|
'chain': unhexlify('ba96f776a5c3907d7fd48bde5620ee374d4acfd540378476019eab70790c63a0'),
|
||||||
|
'public': unhexlify('029f871f4cb9e1c97f9f4de9ccd0d4a2f2a171110c61178f84430062230833ff20')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [4, hardened(0), 1, hardened(2), 2, 1000000000],
|
||||||
|
'fingerprint': unhexlify('8b2b5c4b'),
|
||||||
|
'chain': unhexlify('b9b7b82d326bb9cb5b5b121066feea4eb93d5241103c9e7a18aad40f1dde8059'),
|
||||||
|
'public': unhexlify('02216cd26d31147f72427a453c443ed2cde8a1e53c9cc44e5ddf739725413fe3f4')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [1],
|
||||||
|
'fingerprint': unhexlify('00000000'),
|
||||||
|
'chain': unhexlify('60499f801b896d83179a4374aeb7822aaeaceaa0db1f85ee3e904c4defbd9689'),
|
||||||
|
'public': unhexlify('03cbcaa9c98c877a26977d00825c956a238e8dddfbd322cce4f74b0b5bd6ace4a7')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [1, 0],
|
||||||
|
'fingerprint': unhexlify('bd16bee5'),
|
||||||
|
'chain': unhexlify('f0909affaa7ee7abe5dd4e100598d4dc53cd709d5a5c2cac40e7412f232f7c9c'),
|
||||||
|
'public': unhexlify('02fc9e5af0ac8d9b3cecfe2a888e2117ba3d089d8585886c9c826b6b22a98d12ea')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [1, 0, hardened(2147483647)],
|
||||||
|
'fingerprint': unhexlify('5a61ff8e'),
|
||||||
|
'chain': unhexlify('be17a268474a6bb9c61e1d720cf6215e2a88c5406c4aee7b38547f585c9a37d9'),
|
||||||
|
'public': unhexlify('03c01e7425647bdefa82b12d9bad5e3e6865bee0502694b94ca58b666abc0a5c3b')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [1, 0, hardened(2147483647), 1],
|
||||||
|
'fingerprint': unhexlify('d8ab4937'),
|
||||||
|
'chain': unhexlify('f366f48f1ea9f2d1d3fe958c95ca84ea18e4c4ddb9366c336c927eb246fb38cb'),
|
||||||
|
'public': unhexlify('03a7d1d856deb74c508e05031f9895dab54626251b3806e16b4bd12e781a7df5b9')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [1, 0, hardened(2147483647), 1, hardened(2147483646)],
|
||||||
|
'fingerprint': unhexlify('78412e3a'),
|
||||||
|
'chain': unhexlify('637807030d55d01f9a0cb3a7839515d796bd07706386a6eddf06cc29a65a0e29'),
|
||||||
|
'public': unhexlify('02d2b36900396c9282fa14628566582f206a5dd0bcc8d5e892611806cafb0301f0')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [1, 0, hardened(2147483647), 1, hardened(2147483646), 2],
|
||||||
|
'fingerprint': unhexlify('31a507b8'),
|
||||||
|
'chain': unhexlify('9452b549be8cea3ecb7a84bec10dcfd94afe4d129ebfd3b3cb58eedf394ed271'),
|
||||||
|
'public': unhexlify('024d902e1a2fc7a8755ab5b694c575fce742c48d9ff192e63df5193e4c7afe1f9c')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [5],
|
||||||
|
'fingerprint': unhexlify('00000000'),
|
||||||
|
'chain': unhexlify('96cd4465a9644e31528eda3592aa35eb39a9527769ce1855beafc1b81055e75d'),
|
||||||
|
'public': unhexlify('02c9e16154474b3ed5b38218bb0463e008f89ee03e62d22fdcc8014beab25b48fa')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [5, 0],
|
||||||
|
'fingerprint': unhexlify('607f628f'),
|
||||||
|
'chain': unhexlify('84e9c258bb8557a40e0d041115b376dd55eda99c0042ce29e81ebe4efed9b86a'),
|
||||||
|
'public': unhexlify('039b6df4bece7b6c81e2adfeea4bcf5c8c8a6e40ea7ffa3cf6e8494c61a1fc82cc')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [5, 0, hardened(2147483647)],
|
||||||
|
'fingerprint': unhexlify('946d2a54'),
|
||||||
|
'chain': unhexlify('f235b2bc5c04606ca9c30027a84f353acf4e4683edbd11f635d0dcc1cd106ea6'),
|
||||||
|
'public': unhexlify('02f89c5deb1cae4fedc9905f98ae6cbf6cbab120d8cb85d5bd9a91a72f4c068c76')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [5, 0, hardened(2147483647), 1],
|
||||||
|
'fingerprint': unhexlify('218182d8'),
|
||||||
|
'chain': unhexlify('7c0b833106235e452eba79d2bdd58d4086e663bc8cc55e9773d2b5eeda313f3b'),
|
||||||
|
'public': unhexlify('03abe0ad54c97c1d654c1852dfdc32d6d3e487e75fa16f0fd6304b9ceae4220c64')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [5, 0, hardened(2147483647), 1, hardened(2147483646)],
|
||||||
|
'fingerprint': unhexlify('931223e4'),
|
||||||
|
'chain': unhexlify('5794e616eadaf33413aa309318a26ee0fd5163b70466de7a4512fd4b1a5c9e6a'),
|
||||||
|
'public': unhexlify('03cb8cb067d248691808cd6b5a5a06b48e34ebac4d965cba33e6dc46fe13d9b933')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [5, 0, hardened(2147483647), 1, hardened(2147483646), 2],
|
||||||
|
'fingerprint': unhexlify('956c4629'),
|
||||||
|
'chain': unhexlify('3bfb29ee8ac4484f09db09c2079b520ea5616df7820f071a20320366fbe226a7'),
|
||||||
|
'public': unhexlify('020ee02e18967237cf62672983b253ee62fa4dd431f8243bfeccdf39dbe181387f')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [4],
|
||||||
|
'fingerprint': unhexlify('00000000'),
|
||||||
|
'chain': unhexlify('beeb672fe4621673f722f38529c07392fecaa61015c80c34f29ce8b41b3cb6ea'),
|
||||||
|
'public': unhexlify('0266874dc6ade47b3ecd096745ca09bcd29638dd52c2c12117b11ed3e458cfa9e8')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [4, hardened(28578)],
|
||||||
|
'fingerprint': unhexlify('be6105b5'),
|
||||||
|
'chain': unhexlify('e94c8ebe30c2250a14713212f6449b20f3329105ea15b652ca5bdfc68f6c65c2'),
|
||||||
|
'public': unhexlify('02519b5554a4872e8c9c1c847115363051ec43e93400e030ba3c36b52a3e70a5b7')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [4, hardened(28578), 33941],
|
||||||
|
'fingerprint': unhexlify('3e2b7bc6'),
|
||||||
|
'chain': unhexlify('9e87fe95031f14736774cd82f25fd885065cb7c358c1edf813c72af535e83071'),
|
||||||
|
'public': unhexlify('0235bfee614c0d5b2cae260000bb1d0d84b270099ad790022c1ae0b2e782efe120')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [6],
|
||||||
|
'fingerprint': unhexlify('00000000'),
|
||||||
|
'chain': unhexlify('7762f9729fed06121fd13f326884c82f59aa95c57ac492ce8c9654e60efd130c'),
|
||||||
|
'public': unhexlify('0383619fadcde31063d8c5cb00dbfe1713f3e6fa169d8541a798752a1c1ca0cb20')
|
||||||
|
},
|
||||||
|
]
|
||||||
|
)
|
||||||
|
def test_derive_node_xpub(device, path):
|
||||||
|
resp = device.hd_derive_node(path['path'])
|
||||||
|
xpub = PicoHSM.hd_decode_xpub(resp)
|
||||||
|
assert(xpub['fingerprint'] == path['fingerprint'])
|
||||||
|
assert(xpub['chain'] == path['chain'])
|
||||||
|
assert(xpub['public'] == path['public'])
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"path", [
|
||||||
|
{
|
||||||
|
'path': [7],
|
||||||
|
'fingerprint': unhexlify('00000000'),
|
||||||
|
'chain': unhexlify('8F8C33732530A0417DD446097EDB6F6617D52D627C6DB28581D74D11B385D25A'),
|
||||||
|
'public': unhexlify('dbf12b44133eaab506a740f6565cc117228cbf1dd70635cfa8ddfdc9af734756')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [7, b"SLIP-0021"],
|
||||||
|
'fingerprint': unhexlify('0e521cdd'),
|
||||||
|
'chain': unhexlify('446ADED06078CF950DAB737F014C7BAE81EEB6E7BEECC260A38E2E0FA9973104'),
|
||||||
|
'public': unhexlify('1d065e3ac1bbe5c7fad32cf2305f7d709dc070d672044a19e610c77cdf33de0d')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [7, b"SLIP-0021", b"Master encryption key"],
|
||||||
|
'fingerprint': unhexlify('4a6e721d'),
|
||||||
|
'chain': unhexlify('7072D5593032B84A90E2E2E42996D277026FF55C1082AC82A121D775FED0ACEB'),
|
||||||
|
'public': unhexlify('ea163130e35bbafdf5ddee97a17b39cef2be4b4f390180d65b54cf05c6a82fde')
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'path': [7, b"SLIP-0021", b"Authentication key"],
|
||||||
|
'fingerprint': unhexlify('4a6e721d'),
|
||||||
|
'chain': unhexlify('3D5C87DC62CE006681B8C3DF723AE50FEEA40D6C26AEF8135BD321BA390A5B42'),
|
||||||
|
'public': unhexlify('47194e938ab24cc82bfa25f6486ed54bebe79c40ae2a5a32ea6db294d81861a6')
|
||||||
|
},
|
||||||
|
]
|
||||||
|
)
|
||||||
|
def test_derive_node_slip(device, path):
|
||||||
|
resp = device.hd_derive_node(path['path'])
|
||||||
|
xpub = PicoHSM.hd_decode_xpub(resp)
|
||||||
|
assert(xpub['fingerprint'] == path['fingerprint'])
|
||||||
|
assert(xpub['chain'] == sha256_sha256(path['chain']))
|
||||||
|
assert(xpub['public'] == sha256_sha256(path['public']))
|
||||||
|
|
||||||
|
def get_master_curve(mid):
|
||||||
|
for m in seeds:
|
||||||
|
if (m['id'] == mid):
|
||||||
|
if (m['name'] == 'secp256k1'):
|
||||||
|
return ec.SECP256K1()
|
||||||
|
elif (m['name'] == 'secp256r1'):
|
||||||
|
return ec.SECP256R1()
|
||||||
|
return None
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"path", [
|
||||||
|
[0],
|
||||||
|
[0, hardened(0)],
|
||||||
|
[0, hardened(0), 1],
|
||||||
|
[0, hardened(0), 1, hardened(2)],
|
||||||
|
[0, hardened(0), 1, hardened(2), 2],
|
||||||
|
[0, hardened(0), 1, hardened(2), 2, 1000000000],
|
||||||
|
[1],
|
||||||
|
[1, 0],
|
||||||
|
[1, 0, hardened(2147483647)],
|
||||||
|
[1, 0, hardened(2147483647), 1],
|
||||||
|
[1, 0, hardened(2147483647), 1, hardened(2147483646)],
|
||||||
|
[1, 0, hardened(2147483647), 1, hardened(2147483646), 2],
|
||||||
|
[4],
|
||||||
|
[4, hardened(0)],
|
||||||
|
[4, hardened(0), 1],
|
||||||
|
[4, hardened(0), 1, hardened(2)],
|
||||||
|
[4, hardened(0), 1, hardened(2), 2],
|
||||||
|
[4, hardened(0), 1, hardened(2), 2, 1000000000],
|
||||||
|
[5],
|
||||||
|
[5, 0],
|
||||||
|
[5, 0, hardened(2147483647)],
|
||||||
|
[5, 0, hardened(2147483647), 1],
|
||||||
|
[5, 0, hardened(2147483647), 1, hardened(2147483646)],
|
||||||
|
[5, 0, hardened(2147483647), 1, hardened(2147483646), 2],
|
||||||
|
]
|
||||||
|
)
|
||||||
|
def test_signature(device, path):
|
||||||
|
pub = device.hd_derive_node(path)
|
||||||
|
xpub = PicoHSM.hd_decode_xpub(pub)
|
||||||
|
curve = get_master_curve(path[0])
|
||||||
|
pubkey = ec.EllipticCurvePublicKey.from_encoded_point(curve, xpub['public'])
|
||||||
|
resp = device.hd_signature(path, TEST_STRING)
|
||||||
|
pubkey.verify(resp, TEST_STRING, ec.ECDSA(hashes.SHA256()))
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"path", [
|
||||||
|
[7],
|
||||||
|
[7, b"SLIP-0021"],
|
||||||
|
[7, b"SLIP-0021", b"Master encryption key"],
|
||||||
|
[7, b"SLIP-0021", b"Authentication key"],
|
||||||
|
]
|
||||||
|
)
|
||||||
|
def test_signature_slip(device, path):
|
||||||
|
pub = device.hd_derive_node(path)
|
||||||
|
with pytest.raises(APDUResponse) as e:
|
||||||
|
resp = device.hd_signature(path, TEST_STRING)
|
||||||
|
assert (e.value.sw == SWCodes.SW_CONDITIONS_NOT_SATISFIED)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"ask_on_encrypt", [True, False]
|
||||||
|
)
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"ask_on_decrypt", [True, False]
|
||||||
|
)
|
||||||
|
def test_cipher_slip(device, ask_on_encrypt, ask_on_decrypt):
|
||||||
|
MSG1 = b"testing message!"
|
||||||
|
enctext = device.hd_cipher([7, b"\x01", b"\x02"], b"test", MSG1, EncryptionMode.ENCRYPT, ask_on_encrypt, ask_on_decrypt)
|
||||||
|
resp = device.hd_cipher([7, b"\x01", b"\x02"], b"test", enctext, EncryptionMode.DECRYPT, ask_on_encrypt, ask_on_decrypt)
|
||||||
|
assert(resp == MSG1)
|
||||||
@@ -1,5 +1,11 @@
|
|||||||
#!/bin/bash -eu
|
#!/bin/bash -eu
|
||||||
|
|
||||||
source tests/docker_env.sh
|
source tests/docker_env.sh
|
||||||
run_in_docker ./tests/start-up-and-test.sh
|
|
||||||
|
|
||||||
|
if [[ $1 == "pkcs11" ]]; then
|
||||||
|
run_in_docker ./tests/start-up-and-test-pkcs11.sh
|
||||||
|
elif [[ $1 == "sc-hsm-pkcs11" ]]; then
|
||||||
|
run_in_docker ./tests/scripts/sc_hsm_test.sh
|
||||||
|
else
|
||||||
|
run_in_docker ./tests/start-up-and-test.sh
|
||||||
|
fi
|
||||||
|
|||||||
38
tests/scripts/aes.sh
Executable file
38
tests/scripts/aes.sh
Executable file
@@ -0,0 +1,38 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
source ./tests/scripts/func.sh
|
||||||
|
reset
|
||||||
|
test $? -eq 0 || exit $?
|
||||||
|
|
||||||
|
TEST_DATA="This is a text."
|
||||||
|
|
||||||
|
echo "${TEST_DATA}" > test
|
||||||
|
|
||||||
|
sc_tool() {
|
||||||
|
pkcs11-tool --module /usr/local/lib/libsc-hsm-pkcs11.so -l --pin 648219 $@
|
||||||
|
}
|
||||||
|
|
||||||
|
aeses=("16" "24" "32")
|
||||||
|
|
||||||
|
for aes in ${aeses[*]}; do
|
||||||
|
echo " Test AES (AES:${aes})"
|
||||||
|
echo -n " Keygen... "
|
||||||
|
sc_tool --keygen --key-type "AES:${aes}" --id 1 --label "AES:${aes}" > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
e=$(sc_tool --list-object --type secrkey 2>&1)
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
grep -q "AES length ${aes}" <<< $e && echo -n "." || exit $?
|
||||||
|
grep -q "AES:${aes}" <<< $e && echo -e ".\t${OK}" || exit $?
|
||||||
|
|
||||||
|
echo -n " Encryption..."
|
||||||
|
sc_tool --encrypt --id 1 --input-file test --mechanism aes-cbc > crypted.aes 2>/dev/null
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
|
||||||
|
echo -n " Decryption..."
|
||||||
|
e=$(sc_tool --decrypt --id 1 --input-file crypted.aes --mechanism aes-cbc 2>/dev/null)
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
grep -q "${TEST_DATA}" <<< $e && echo -e ".\t${OK}" || exit $?
|
||||||
|
|
||||||
|
sc_tool --delete --type secrkey --id 1 > /dev/null 2>&1
|
||||||
|
done
|
||||||
|
rm -rf test crypted.aes
|
||||||
62
tests/scripts/asym_cipher.sh
Executable file
62
tests/scripts/asym_cipher.sh
Executable file
@@ -0,0 +1,62 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
source ./tests/scripts/func.sh
|
||||||
|
reset
|
||||||
|
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))
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
if [[ ${TEST_STRING} != "$TDATA" ]]; then
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
}
|
||||||
|
|
||||||
|
TEST_STRING="This is a test string. Be safe, be secure."
|
||||||
|
|
||||||
|
echo ${TEST_STRING} > data
|
||||||
|
|
||||||
|
echo -n " Keygen RSA 2048..."
|
||||||
|
keygen_and_export rsa:2048
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
|
||||||
|
echo -n " Test RSA-PKCS ciphering..."
|
||||||
|
rsa_encrypt_decrypt data "-pkeyopt rsa_padding_mode:pkcs1" "--mechanism RSA-PKCS"
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
|
||||||
|
echo -n " Test RSA-X-509 ciphering..."
|
||||||
|
cp data data_pad
|
||||||
|
tlen=${#TEST_STRING}
|
||||||
|
dd if=/dev/zero bs=1 count=$((256-$tlen-1)) >> data_pad 2> /dev/null
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
rsa_encrypt_decrypt data_pad "-pkeyopt rsa_padding_mode:none" "--mechanism RSA-X-509"
|
||||||
|
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"
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
|
||||||
|
rm -rf data* 1.*
|
||||||
|
pkcs11-tool -l --pin 648219 --delete-object --type privkey --id 1 > /dev/null 2>&1
|
||||||
|
|
||||||
|
algs=("secp192r1" "secp256r1" "secp384r1" "secp521r1" "brainpoolP256r1" "brainpoolP384r1" "brainpoolP512r1" "secp192k1" "secp256k1")
|
||||||
|
for alg in ${algs[*]}; do
|
||||||
|
echo -n " Test EC derive with ${alg}..."
|
||||||
|
keygen_and_export ec:${alg}
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
openssl ecparam -genkey -name ${alg} > bob.pem 2>/dev/null
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
openssl ec -in bob.pem -pubout -outform DER > bob.der 2>/dev/null
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
pkcs11-tool --pin 648219 --id 1 --derive -i bob.der -o mine-bob.der > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
openssl pkeyutl -derive -out bob-mine.der -inkey bob.pem -peerkey 1.pub 2>/dev/null
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
cmp bob-mine.der mine-bob.der
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
rm -rf data* 1.*
|
||||||
|
pkcs11-tool -l --pin 648219 --delete-object --type privkey --id 1 > /dev/null 2>&1
|
||||||
|
done
|
||||||
60
tests/scripts/backup.sh
Executable file
60
tests/scripts/backup.sh
Executable file
@@ -0,0 +1,60 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
source ./tests/scripts/func.sh
|
||||||
|
reset
|
||||||
|
test $? -eq 0 || exit $?
|
||||||
|
|
||||||
|
sc_backup() {
|
||||||
|
for i in $(seq 1 $1); do
|
||||||
|
sc-hsm-tool --create-dkek-share dkek.${i}.pbe --password testpw > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
done
|
||||||
|
sc-hsm-tool --initialize --so-pin 3537363231383830 --pin 648219 --dkek-shares $1 > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
pkcs11-tool -l --pin 648219 -I > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
for i in $(seq 1 $1); do
|
||||||
|
e=$(sc-hsm-tool --import-dkek-share dkek.${i}.pbe --password testpw 2>&1)
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
grep -q "DKEK share imported" <<< $e && echo -n "." || exit $?
|
||||||
|
grep -q "DKEK shares[[:blank:]]*: $1" <<< $e && echo -n "." || exit $?
|
||||||
|
if [[ $i -lt $1 ]]; then
|
||||||
|
grep -q "DKEK import pending, $(( $1 - $i ))" <<< $e && echo -n "." || exit $?
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
# Store DKEK, since it is not logged in
|
||||||
|
pkcs11-tool -l --pin 648219 -I > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
}
|
||||||
|
echo -n " Test single DKEK..."
|
||||||
|
sc_backup 1
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
|
||||||
|
echo -n " Test multiple DKEK..."
|
||||||
|
sc_backup 3
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
|
||||||
|
rm -rf dkek.*.pbe
|
||||||
|
|
||||||
|
echo " Test backup and restore"
|
||||||
|
algs=("rsa:1024" "rsa:2048" "ec:secp192r1" "ec:secp256r1" "ec:secp384r1" "ec:secp521r1" "ec:brainpoolP256r1" "ec:brainpoolP384r1" "ec:brainpoolP512r1" "ec:secp192k1" "ec:secp256k1")
|
||||||
|
for alg in ${algs[*]}; do
|
||||||
|
echo -n " Keygen ${alg}..."
|
||||||
|
gen_and_check ${alg}
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
echo -n " Wrap key..."
|
||||||
|
sc-hsm-tool --wrap-key wrap-key.bin --key-reference 1 --pin 648219 > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
e=$(pkcs15-tool -D 2>&1)
|
||||||
|
grep -q "Key ref[[:blank:]]*: 10" <<< $e && exit $? || echo -e ".\t${OK}"
|
||||||
|
echo -n " Unwrap key..."
|
||||||
|
sc-hsm-tool --unwrap-key wrap-key.bin --key-reference 10 --pin 648219 --force > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
e=$(pkcs15-tool -D 2>&1)
|
||||||
|
grep -q "Key ref[[:blank:]]*: 10" <<< $e && echo -e ".\t${OK}" || exit $?
|
||||||
|
echo -n " Cleaning..."
|
||||||
|
pkcs11-tool -l --pin 648219 --delete-object --type privkey --id 1 > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
pkcs11-tool -l --pin 648219 --delete-object --type privkey --id 1 > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
done
|
||||||
52
tests/scripts/func.sh
Executable file
52
tests/scripts/func.sh
Executable file
@@ -0,0 +1,52 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
OK="\033[32mok\033[0m"
|
||||||
|
FAIL="\033[31mfail\033[0m"
|
||||||
|
|
||||||
|
gen_and_check() {
|
||||||
|
e=$(pkcs11-tool -l --pin 648219 --keypairgen --key-type $1 --id 1 --label "TestLabel" 2>&1)
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
glabel=""
|
||||||
|
case $1 in
|
||||||
|
*"192"*)
|
||||||
|
glabel="EC_POINT 192 bits"
|
||||||
|
;;
|
||||||
|
*"256"*)
|
||||||
|
glabel="EC_POINT 256 bits"
|
||||||
|
;;
|
||||||
|
*"384"*)
|
||||||
|
glabel="EC_POINT 384 bits"
|
||||||
|
;;
|
||||||
|
*"512"*)
|
||||||
|
glabel="EC_POINT 512 bits"
|
||||||
|
;;
|
||||||
|
*"521"*)
|
||||||
|
glabel="EC_POINT 528 bits"
|
||||||
|
;;
|
||||||
|
*"rsa"*)
|
||||||
|
IFS=: read -r v1 bits <<< "$1"
|
||||||
|
glabel="RSA ${bits} bits"
|
||||||
|
;;
|
||||||
|
esac
|
||||||
|
grep -q "${glabel}" <<< $e && echo -n "." || exit $?
|
||||||
|
}
|
||||||
|
gen_and_delete() {
|
||||||
|
gen_and_check $1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
pkcs11-tool -l --pin 648219 --delete-object --type privkey --id 1 > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
}
|
||||||
|
reset() {
|
||||||
|
python3 tools/pico-hsm-tool.py --pin 648219 initialize --so-pin 57621880 --silent > /dev/null 2>&1
|
||||||
|
test $? -eq 0 || exit $?
|
||||||
|
}
|
||||||
|
|
||||||
|
keygen_and_export() {
|
||||||
|
gen_and_check $1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
pkcs11-tool --read-object --pin 648219 --id 1 --type pubkey > 1.der 2>/dev/null
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
IFS=: read -r mk bts <<< "$1"
|
||||||
|
openssl ${mk} -inform DER -outform PEM -in 1.der -pubin > 1.pub 2>/dev/null
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
}
|
||||||
49
tests/scripts/initialize.sh
Executable file
49
tests/scripts/initialize.sh
Executable file
@@ -0,0 +1,49 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
source ./tests/scripts/func.sh
|
||||||
|
reset
|
||||||
|
|
||||||
|
# Change SO-PIN
|
||||||
|
echo -n " Test SO-PIN change..."
|
||||||
|
pkcs11-tool --login --login-type so --so-pin 3537363231383830 --change-pin --new-pin 0123456789012345 > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
|
||||||
|
pkcs11-tool --login --login-type so --so-pin 0123456789012345 --change-pin --new-pin 3537363231383830 > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
|
||||||
|
# Change PIN
|
||||||
|
echo -n " Test PIN change..."
|
||||||
|
pkcs11-tool --login --pin 648219 --change-pin --new-pin 123456 > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
|
||||||
|
# Reset PIN
|
||||||
|
echo -n " Test PIN reset..."
|
||||||
|
pkcs11-tool --login --login-type so --so-pin 3537363231383830 --init-pin --new-pin 648219 > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
|
||||||
|
# Change PIN
|
||||||
|
pkcs11-tool --login --pin 648219 --change-pin --new-pin 123456 > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
|
||||||
|
pkcs11-tool --login --pin 123456 --change-pin --new-pin 648219 > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
|
||||||
|
# Wrong PIN (1st and 2nd PIN_INCORRECT, 3rd PIN_LOCKED)
|
||||||
|
echo -n " Test wrong PIN attempts..."
|
||||||
|
e=$(pkcs11-tool --login --pin 123456 -I 2>&1)
|
||||||
|
test $? -eq 1 && echo -n "." || exit $?
|
||||||
|
grep -q CKR_PIN_INCORRECT <<< $e && echo -n "." || exit $?
|
||||||
|
e=$(pkcs11-tool --login --pin 123456 -I 2>&1)
|
||||||
|
test $? -eq 1 && echo -n "." || exit $?
|
||||||
|
grep -q CKR_PIN_INCORRECT <<< $e && echo -n "." || exit $?
|
||||||
|
e=$(pkcs11-tool --login --pin 123456 -I 2>&1)
|
||||||
|
test $? -eq 1 && echo -n "." || exit $?
|
||||||
|
grep -q CKR_PIN_LOCKED <<< $e && echo -e "\t${OK}" || exit $?
|
||||||
|
|
||||||
|
# Reset PIN
|
||||||
|
echo -n " Test restore PIN..."
|
||||||
|
pkcs11-tool --login --login-type so --so-pin 3537363231383830 --init-pin --new-pin 648219 > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
|
||||||
|
pkcs11-tool --login --pin 648219 -I > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -e "\t${OK}" || exit $?
|
||||||
13
tests/scripts/keygen.sh
Executable file
13
tests/scripts/keygen.sh
Executable file
@@ -0,0 +1,13 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
source ./tests/scripts/func.sh
|
||||||
|
reset
|
||||||
|
test $? -eq 0 || exit $?
|
||||||
|
|
||||||
|
algs=("rsa:1024" "rsa:2048" "ec:secp192r1" "ec:secp256r1" "ec:secp384r1" "ec:secp521r1" "ec:brainpoolP256r1" "ec:brainpoolP384r1" "ec:brainpoolP512r1" "ec:secp192k1" "ec:secp256k1")
|
||||||
|
for alg in ${algs[*]}; do
|
||||||
|
IFS=: read -r a s <<< "${alg}"
|
||||||
|
au=$(awk '{print toupper($0)}' <<<${a})
|
||||||
|
echo -n " Test ${au} ${s}..."
|
||||||
|
gen_and_delete ${alg} && echo -e ".\t${OK}" || exit $?
|
||||||
|
done
|
||||||
58
tests/scripts/pkcs11.sh
Executable file
58
tests/scripts/pkcs11.sh
Executable file
@@ -0,0 +1,58 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
source ./tests/scripts/func.sh
|
||||||
|
echo "==== Test initialization ===="
|
||||||
|
./tests/scripts/initialize.sh
|
||||||
|
test $? -eq 0 || {
|
||||||
|
echo -e "\t${FAIL}"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "==== Test keygen ===="
|
||||||
|
./tests/scripts/keygen.sh
|
||||||
|
test $? -eq 0 || {
|
||||||
|
echo -e "\t${FAIL}"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "==== Test sign and verify ===="
|
||||||
|
./tests/scripts/sign_and_verify.sh
|
||||||
|
test $? -eq 0 || {
|
||||||
|
echo -e "\t${FAIL}"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "==== Test asymmetric ciphering ===="
|
||||||
|
./tests/scripts/asym_cipher.sh
|
||||||
|
test $? -eq 0 || {
|
||||||
|
echo -e "\t${FAIL}"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "==== Test binary storage ===="
|
||||||
|
./tests/scripts/store_binary.sh
|
||||||
|
test $? -eq 0 || {
|
||||||
|
echo -e "\t${FAIL}"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "==== Test AES ===="
|
||||||
|
./tests/scripts/aes.sh
|
||||||
|
test $? -eq 0 || {
|
||||||
|
echo -e "\t${FAIL}"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "==== Test PKCS11-tool ===="
|
||||||
|
./tests/scripts/pkcs11_test.sh
|
||||||
|
test $? -eq 0 || {
|
||||||
|
echo -e "\t${FAIL}"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
echo "==== Test backup and restore ===="
|
||||||
|
./tests/scripts/backup.sh
|
||||||
|
test $? -eq 0 || {
|
||||||
|
echo -e "\t${FAIL}"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
17
tests/scripts/pkcs11_test.sh
Executable file
17
tests/scripts/pkcs11_test.sh
Executable file
@@ -0,0 +1,17 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
source ./tests/scripts/func.sh
|
||||||
|
reset
|
||||||
|
test $? -eq 0 || exit $?
|
||||||
|
|
||||||
|
echo -n " Test PKCS11 tool..."
|
||||||
|
gen_and_check rsa:2048
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
e=$(pkcs11-tool --test -l --pin 648219 2>&1)
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
grep -q "No errors" <<< $e && echo -n "." || exit $?
|
||||||
|
pkcs11-tool -l --pin 648219 --delete-object --type privkey --id 1 > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
#e=$(pkcs11-tool --test-ec -l --pin 648219 --id 1 --key-type ec:secp256r1 2>&1)
|
||||||
|
#test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
#grep -q "==> OK" <<< $e && echo -e ".\t${OK}" || exit $?
|
||||||
24
tests/scripts/sc_hsm_test.sh
Executable file
24
tests/scripts/sc_hsm_test.sh
Executable file
@@ -0,0 +1,24 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
source ./tests/startup.sh
|
||||||
|
|
||||||
|
echo "==== Test SC HSM ===="
|
||||||
|
echo -n " Running sc-hsm-pkcs11-test..."
|
||||||
|
pkcs11-tool -l --pin 648219 --keypairgen --key-type ec:secp256r1 --id 1 --label "TestLabel" > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || {
|
||||||
|
echo -e "\t${FAIL}"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
e=$(/usr/local/bin/sc-hsm-pkcs11-test --module /usr/local/lib/libsc-hsm-pkcs11.so --pin 648219 --invasive 2>&1)
|
||||||
|
test $? -eq 0 && echo -n "." || {
|
||||||
|
echo -e "\t${FAIL}"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
grep -q "338 tests performed" <<< $e && echo -n "." || {
|
||||||
|
echo -e "\t${FAIL}"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
grep -q "0 tests failed" <<< $e && echo -e ".\t${OK}" || {
|
||||||
|
echo -e "\t${FAIL}"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
126
tests/scripts/sign_and_verify.sh
Executable file
126
tests/scripts/sign_and_verify.sh
Executable file
@@ -0,0 +1,126 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
source ./tests/scripts/func.sh
|
||||||
|
reset
|
||||||
|
test $? -eq 0 || exit $?
|
||||||
|
|
||||||
|
TEST_DATA="This is a test string. Be safe, be secure."
|
||||||
|
echo ${TEST_DATA} > data
|
||||||
|
|
||||||
|
create_dgst() {
|
||||||
|
openssl dgst -$1 -binary -out data.$1 data > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
}
|
||||||
|
|
||||||
|
dgsts=("sha256" "sha384" "sha512")
|
||||||
|
for dgst in ${dgsts[*]}; do
|
||||||
|
echo -n " Create digest ${dgst}..."
|
||||||
|
create_dgst ${dgst}
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
done
|
||||||
|
|
||||||
|
# $1 sign mechanism
|
||||||
|
# $2 sign input file
|
||||||
|
# $3 sign parameters
|
||||||
|
# $4 vrfy input file
|
||||||
|
# $5 vrfy parameters
|
||||||
|
sign_and_verify() {
|
||||||
|
pkcs11-tool --id 1 --sign --pin 648219 --mechanism $1 -i $2 -o data.sig $3 > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
e=$(openssl pkeyutl -verify -pubin -inkey 1.pub -in $4 -sigfile data.sig $5 2>&1)
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
grep -q "Signature Verified Successfully" <<< $e && echo -n "." || exit $?
|
||||||
|
}
|
||||||
|
|
||||||
|
sign_and_verify_rsa_pkcs() {
|
||||||
|
dgstl=$(awk '{print tolower($0)}' <<<$1)
|
||||||
|
dgstu=$(awk '{print toupper($0)}' <<<$1)
|
||||||
|
sign_and_verify "${dgstu}-RSA-PKCS" data "" data.${dgstl} "-pkeyopt digest:${dgstl}"
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
}
|
||||||
|
|
||||||
|
sign_and_verify_rsa_pss() {
|
||||||
|
dgstl=$(awk '{print tolower($0)}' <<<$1)
|
||||||
|
dgstu=$(awk '{print toupper($0)}' <<<$1)
|
||||||
|
sign_and_verify "RSA-PKCS-PSS" data.${dgstl} "--mgf MGF1-${dgstu} --hash-algorithm ${dgstu}" data.${dgstl} "-pkeyopt rsa_padding_mode:pss -pkeyopt rsa_pss_saltlen:-1 -pkeyopt digest:${dgstl}"
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
}
|
||||||
|
|
||||||
|
sign_and_verify_rsa_pss_dgst() {
|
||||||
|
dgstl=$(awk '{print tolower($0)}' <<<$1)
|
||||||
|
dgstu=$(awk '{print toupper($0)}' <<<$1)
|
||||||
|
sign_and_verify "${dgstu}-RSA-PKCS-PSS" data "" data.${dgstl} "-pkeyopt rsa_padding_mode:pss -pkeyopt rsa_pss_saltlen:-1 -pkeyopt digest:${dgstl}"
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
}
|
||||||
|
|
||||||
|
keygen_sign_and_verify_ec() {
|
||||||
|
echo " Test ECDSA with $1"
|
||||||
|
echo -n " Keygen $1..."
|
||||||
|
keygen_and_export $1
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
for dgst in ${dgsts[*]}; do
|
||||||
|
dgstu=$(awk '{print toupper($0)}' <<<${dgst})
|
||||||
|
echo -n " Test ECDSA with ${dgst} and $1..."
|
||||||
|
sign_and_verify ECDSA "data.${dgst}" "--signature-format openssl" data.${dgst}
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
echo -n " Test ECDSA-${dgstu} with $1..."
|
||||||
|
sign_and_verify "ECDSA-${dgstu}" data "--signature-format openssl" data.${dgst}
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
done
|
||||||
|
echo -n " Delete $1..."
|
||||||
|
pkcs11-tool -l --pin 648219 --delete-object --type privkey --id 1 > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
}
|
||||||
|
|
||||||
|
algs=("ec:secp192r1" "ec:secp256r1" "ec:secp384r1" "ec:secp521r1" "ec:brainpoolP256r1" "ec:brainpoolP384r1" "ec:brainpoolP512r1" "ec:secp192k1" "ec:secp256k1")
|
||||||
|
for alg in ${algs[*]}; do
|
||||||
|
keygen_sign_and_verify_ec ${alg} || exit $?
|
||||||
|
done
|
||||||
|
|
||||||
|
echo " Test RSA PKCS"
|
||||||
|
echo -n " Keygen rsa:2048..."
|
||||||
|
keygen_and_export "rsa:2048"
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
|
||||||
|
echo -n " Test RSA-PKCS..."
|
||||||
|
pkcs11-tool --id 1 --sign --pin 648219 --mechanism RSA-PKCS -i data -o data.sig > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
e=$(openssl pkeyutl -verify -pubin -inkey 1.pub -in data -sigfile data.sig 2>&1)
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
grep -q "Signature Verified Successfully" <<< $e && echo -e ".\t${OK}" || exit $?
|
||||||
|
|
||||||
|
for dgst in ${dgsts[*]}; do
|
||||||
|
dgstu=$(awk '{print toupper($0)}' <<<${dgst})
|
||||||
|
echo -n " Test RSA-PKCS-${dgstu}..."
|
||||||
|
sign_and_verify_rsa_pkcs ${dgst}
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
done
|
||||||
|
|
||||||
|
echo -n " Test RSA-X-509..."
|
||||||
|
cp data data_pad
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
tlen=${#TEST_DATA}
|
||||||
|
dd if=/dev/zero bs=1 count=$((256-$tlen)) >> data_pad > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
pkcs11-tool --id 1 --sign --pin 648219 --mechanism RSA-X-509 -i data_pad -o data.sig > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
TDATA=$(tr -d '\0' < <(openssl rsautl -verify -inkey 1.pub -in data.sig -pubin -raw 2>/dev/null))
|
||||||
|
if [[ ${TEST_DATA} != "$TDATA" ]]; then
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
|
||||||
|
for dgst in ${dgsts[*]}; do
|
||||||
|
dgstu=$(awk '{print toupper($0)}' <<<${dgst})
|
||||||
|
if [[ "${dgst}" != "sha1" ]]; then
|
||||||
|
echo -n " Test RSA-PKCS-PSS with ${dgst}..."
|
||||||
|
sign_and_verify_rsa_pss ${dgst}
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
fi
|
||||||
|
echo -n " Test ${dgstu}-RSA-PKCS-PSS..."
|
||||||
|
sign_and_verify_rsa_pss_dgst ${dgst}
|
||||||
|
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||||
|
done
|
||||||
|
|
||||||
|
rm -rf data* 1.*
|
||||||
|
pkcs11-tool -l --pin 648219 --delete-object --type privkey --id 1 > /dev/null 2>&1
|
||||||
28
tests/scripts/store_binary.sh
Executable file
28
tests/scripts/store_binary.sh
Executable file
@@ -0,0 +1,28 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
source ./tests/scripts/func.sh
|
||||||
|
reset
|
||||||
|
test $? -eq 0 || exit $?
|
||||||
|
|
||||||
|
TEST_DATA="Pico HSM is awesome!"
|
||||||
|
|
||||||
|
echo ${TEST_DATA} > test
|
||||||
|
|
||||||
|
echo -n " Test public binary storage..."
|
||||||
|
pkcs11-tool --pin 648219 --write-object test --type data --id 1 --label 'test1' > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
e=$(pkcs11-tool --read-object --type data --label 'test1' 2>&1)
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
grep -q "${TEST_DATA}" <<< $e && echo -e ".\t${OK}" || exit $?
|
||||||
|
pkcs11-tool --pin 648219 --delete-object --type data --label 'test1' > /dev/null 2>&1
|
||||||
|
|
||||||
|
echo -n " Test private binary storage..."
|
||||||
|
pkcs11-tool --pin 648219 --write-object test --type data --id 1 --label 'test1' --private > /dev/null 2>&1
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
e=$(pkcs11-tool --read-object --type data --label 'test1' --pin 648219 2>&1)
|
||||||
|
test $? -eq 0 && echo -n "." || exit $?
|
||||||
|
grep -q "${TEST_DATA}" <<< $e && echo -n "." || exit $?
|
||||||
|
e=$(pkcs11-tool --read-object --type data --label 'test1' 2>&1)
|
||||||
|
test $? -eq 1 && echo -n "." || exit $?
|
||||||
|
grep -q "error: object not found" <<< $e && echo -e ".\t${OK}" || exit $?
|
||||||
|
pkcs11-tool --pin 648219 --delete-object --type data --label 'test1' > /dev/null 2>&1
|
||||||
8
tests/start-up-and-test-pkcs11.sh
Executable file
8
tests/start-up-and-test-pkcs11.sh
Executable file
@@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
source ./tests/startup.sh
|
||||||
|
|
||||||
|
chmod a+x tests/scripts/*.sh
|
||||||
|
|
||||||
|
echo "======== PKCS11 Test suite ========"
|
||||||
|
./tests/scripts/pkcs11.sh
|
||||||
@@ -1,8 +1,5 @@
|
|||||||
#!/bin/bash -eu
|
#!/bin/bash
|
||||||
|
|
||||||
|
source ./tests/startup.sh
|
||||||
|
|
||||||
/usr/sbin/pcscd &
|
|
||||||
sleep 2
|
|
||||||
rm -f memory.flash
|
|
||||||
tar -xf tests/memory.tar.gz
|
|
||||||
./build_in_docker/pico_hsm > /dev/null &
|
|
||||||
pytest tests -W ignore::DeprecationWarning
|
pytest tests -W ignore::DeprecationWarning
|
||||||
|
|||||||
27
tests/startup.sh
Normal file
27
tests/startup.sh
Normal file
@@ -0,0 +1,27 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
OK="\t\033[32mok\033[0m"
|
||||||
|
FAIL="\t\033[31mfail\033[0m"
|
||||||
|
|
||||||
|
fail() {
|
||||||
|
echo -e "${FAIL}"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
|
||||||
|
echo -n "Start PCSC..."
|
||||||
|
/usr/sbin/pcscd &
|
||||||
|
test $? -eq 0 && echo -e "${OK}" || {
|
||||||
|
echo -e "${FAIL}"
|
||||||
|
exit 1
|
||||||
|
}
|
||||||
|
sleep 2
|
||||||
|
rm -f memory.flash
|
||||||
|
tar -xf tests/memory.tar.gz
|
||||||
|
echo -n "Start Pico HSM..."
|
||||||
|
/pico_hsm > /dev/null 2>&1 &
|
||||||
|
test $? -eq 0 && echo -n "." || fail
|
||||||
|
sleep 2
|
||||||
|
ATR="3b:fe:18:00:00:81:31:fe:45:80:31:81:54:48:53:4d:31:73:80:21:40:81:07:fa"
|
||||||
|
e=$(opensc-tool -an 2>&1)
|
||||||
|
grep -q "${ATR}" <<< $e && echo -n "." || fail
|
||||||
|
test $? -eq 0 && echo -e "${OK}" || fail
|
||||||
138
tests/utils.py
138
tests/utils.py
@@ -1,138 +0,0 @@
|
|||||||
"""
|
|
||||||
/*
|
|
||||||
* 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/>.
|
|
||||||
*/
|
|
||||||
"""
|
|
||||||
|
|
||||||
from enum import Enum
|
|
||||||
|
|
||||||
class SWCodes(Enum):
|
|
||||||
SW_BYTES_REMAINING_00 = 0x6100
|
|
||||||
SW_WARNING_STATE_UNCHANGED = 0x6200
|
|
||||||
SW_WARNING_CORRUPTED = 0x6281
|
|
||||||
SW_WARNING_EOF = 0x6282
|
|
||||||
SW_WARNING_EF_DEACTIVATED = 0x6283
|
|
||||||
SW_WARNING_WRONG_FCI = 0x6284
|
|
||||||
SW_WARNING_EF_TERMINATED = 0x6285
|
|
||||||
|
|
||||||
SW_WARNING_NOINFO = 0x6300
|
|
||||||
SW_WARNING_FILLUP = 0x6381
|
|
||||||
|
|
||||||
SW_EXEC_ERROR = 0x6400
|
|
||||||
|
|
||||||
SW_SECURE_MESSAGE_EXEC_ERROR = 0x6600
|
|
||||||
|
|
||||||
SW_WRONG_LENGTH = 0x6700
|
|
||||||
|
|
||||||
SW_LOGICAL_CHANNEL_NOT_SUPPORTED = 0x6881
|
|
||||||
SW_SECURE_MESSAGING_NOT_SUPPORTED = 0x6882
|
|
||||||
|
|
||||||
SW_COMMAND_INCOMPATIBLE = 0x6981
|
|
||||||
SW_SECURITY_STATUS_NOT_SATISFIED = 0x6982
|
|
||||||
SW_PIN_BLOCKED = 0x6983
|
|
||||||
SW_DATA_INVALID = 0x6984
|
|
||||||
SW_CONDITIONS_NOT_SATISFIED = 0x6985
|
|
||||||
SW_COMMAND_NOT_ALLOWED = 0x6986
|
|
||||||
SW_SECURE_MESSAGING_MISSING_DO = 0x6987
|
|
||||||
SW_SECURE_MESSAGING_INCORRECT_DO = 0x6988
|
|
||||||
SW_APPLET_SELECT_FAILED = 0x6999
|
|
||||||
|
|
||||||
SW_INCORRECT_PARAMS = 0x6A80
|
|
||||||
SW_FUNC_NOT_SUPPORTED = 0x6A81
|
|
||||||
SW_FILE_NOT_FOUND = 0x6A82
|
|
||||||
SW_RECORD_NOT_FOUND = 0x6A83
|
|
||||||
SW_FILE_FULL = 0x6A84
|
|
||||||
SW_WRONG_NE = 0x6A85
|
|
||||||
SW_INCORRECT_P1P2 = 0x6A86
|
|
||||||
SW_WRONG_NC = 0x6A87
|
|
||||||
SW_REFERENCE_NOT_FOUND = 0x6A88
|
|
||||||
SW_FILE_EXISTS = 0x6A89
|
|
||||||
|
|
||||||
SW_WRONG_P1P2 = 0x6B00
|
|
||||||
|
|
||||||
SW_CORRECT_LENGTH_00 = 0x6C00
|
|
||||||
|
|
||||||
SW_INS_NOT_SUPPORTED = 0x6D00
|
|
||||||
|
|
||||||
SW_CLA_NOT_SUPPORTED = 0x6E00
|
|
||||||
|
|
||||||
SW_UNKNOWN = 0x6F00
|
|
||||||
|
|
||||||
SW_OK = 0x900
|
|
||||||
|
|
||||||
class APDUResponse(Exception):
|
|
||||||
def __init__(self, sw1, sw2):
|
|
||||||
self.sw1 = sw1
|
|
||||||
self.sw2 = sw2
|
|
||||||
self.sw = sw1 << 8 | sw2
|
|
||||||
super().__init__(f'SW:{sw1:02X}{sw2:02X}')
|
|
||||||
|
|
||||||
class DOPrefixes(Enum):
|
|
||||||
PRKD_PREFIX = 0xC4
|
|
||||||
CD_PREFIX = 0xC8
|
|
||||||
DCOD_PREFIX = 0xC9
|
|
||||||
CA_CERTIFICATE_PREFIX = 0xCA
|
|
||||||
KEY_PREFIX = 0xCC
|
|
||||||
PROT_DATA_PREFIX = 0xCD
|
|
||||||
EE_CERTIFICATE_PREFIX = 0xCE
|
|
||||||
DATA_PREFIX = 0xCF
|
|
||||||
|
|
||||||
class KeyType(Enum):
|
|
||||||
RSA = 1
|
|
||||||
ECC = 2
|
|
||||||
AES = 3
|
|
||||||
|
|
||||||
class Algorithm(Enum):
|
|
||||||
ALGO_AES_CBC_ENCRYPT = 0x10
|
|
||||||
ALGO_AES_CBC_DECRYPT = 0x11
|
|
||||||
ALGO_AES_CMAC = 0x18
|
|
||||||
ALGO_EXT_CIPHER_ENCRYPT = 0x51
|
|
||||||
ALGO_EXT_CIPHER_DECRYPT = 0x52
|
|
||||||
ALGO_AES_DERIVE = 0x99
|
|
||||||
|
|
||||||
ALGO_EC_RAW = 0x70
|
|
||||||
ALGO_EC_SHA1 = 0x71
|
|
||||||
ALGO_EC_SHA224 = 0x72
|
|
||||||
ALGO_EC_SHA256 = 0x73
|
|
||||||
ALGO_EC_SHA384 = 0x74
|
|
||||||
ALGO_EC_SHA512 = 0x75
|
|
||||||
ALGO_EC_DH = 0x80
|
|
||||||
ALGO_EC_DERIVE = 0x98
|
|
||||||
|
|
||||||
ALGO_RSA_RAW = 0x20
|
|
||||||
ALGO_RSA_DECRYPT = 0x21
|
|
||||||
ALGO_RSA_DECRYPT_PKCS1 = 0x22
|
|
||||||
ALGO_RSA_DECRYPT_OEP = 0x23
|
|
||||||
ALGO_RSA_PKCS1 = 0x30
|
|
||||||
ALGO_RSA_PKCS1_SHA1 = 0x31
|
|
||||||
ALGO_RSA_PKCS1_SHA224 = 0x32
|
|
||||||
ALGO_RSA_PKCS1_SHA256 = 0x33
|
|
||||||
ALGO_RSA_PKCS1_SHA384 = 0x34
|
|
||||||
ALGO_RSA_PKCS1_SHA512 = 0x35
|
|
||||||
ALGO_RSA_PSS = 0x40
|
|
||||||
ALGO_RSA_PSS_SHA1 = 0x41
|
|
||||||
ALGO_RSA_PSS_SHA224 = 0x42
|
|
||||||
ALGO_RSA_PSS_SHA256 = 0x43
|
|
||||||
ALGO_RSA_PSS_SHA384 = 0x44
|
|
||||||
ALGO_RSA_PSS_SHA512 = 0x45
|
|
||||||
|
|
||||||
class Padding(Enum):
|
|
||||||
RAW = 0x21
|
|
||||||
PKCS = 0x22
|
|
||||||
OAEP = 0x23
|
|
||||||
|
|
||||||
def int_to_bytes(x, length=None, byteorder='big'):
|
|
||||||
return x.to_bytes(length or (x.bit_length() + 7) // 8, byteorder=byteorder)
|
|
||||||
@@ -17,7 +17,7 @@
|
|||||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||||
#
|
#
|
||||||
|
|
||||||
VERSION_MAJOR="4" #Version of Pico CCID Core
|
VERSION_MAJOR="6" #Version of Pico Keys SDK
|
||||||
VERSION_MINOR="0"
|
VERSION_MINOR="0"
|
||||||
|
|
||||||
echo "----------------------------"
|
echo "----------------------------"
|
||||||
|
|||||||
@@ -20,17 +20,8 @@
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import sys
|
import sys
|
||||||
try:
|
|
||||||
from smartcard.CardType import AnyCardType
|
|
||||||
from smartcard.CardRequest import CardRequest
|
|
||||||
from smartcard.Exceptions import CardRequestTimeoutException, CardConnectionException
|
|
||||||
except ModuleNotFoundError:
|
|
||||||
print('ERROR: smarctard module not found! Install pyscard package.\nTry with `pip install pyscard`')
|
|
||||||
sys.exit(-1)
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
from cvc.certificates import CVC
|
from cvc.certificates import CVC
|
||||||
from cvc.asn1 import ASN1
|
|
||||||
from cvc.oid import oid2scheme
|
from cvc.oid import oid2scheme
|
||||||
from cvc.utils import scheme_rsa
|
from cvc.utils import scheme_rsa
|
||||||
except ModuleNotFoundError:
|
except ModuleNotFoundError:
|
||||||
@@ -47,6 +38,11 @@ except ModuleNotFoundError:
|
|||||||
print('ERROR: cryptography module not found! Install cryptography package.\nTry with `pip install cryptography`')
|
print('ERROR: cryptography module not found! Install cryptography package.\nTry with `pip install cryptography`')
|
||||||
sys.exit(-1)
|
sys.exit(-1)
|
||||||
|
|
||||||
|
try:
|
||||||
|
from picohsm import PicoHSM, PinType, DOPrefixes, KeyType, EncryptionMode, utils, APDUResponse, SWCodes, AES
|
||||||
|
except ModuleNotFoundError:
|
||||||
|
print('ERROR: picohsm module not found! Install picohsm package.\nTry with `pip install pypicohsm`')
|
||||||
|
sys.exit(-1)
|
||||||
|
|
||||||
import json
|
import json
|
||||||
import urllib.request
|
import urllib.request
|
||||||
@@ -61,64 +57,22 @@ from argparse import RawTextHelpFormatter
|
|||||||
|
|
||||||
pin = None
|
pin = None
|
||||||
|
|
||||||
class APDUResponse(Exception):
|
|
||||||
def __init__(self, sw1, sw2):
|
|
||||||
self.sw1 = sw1
|
|
||||||
self.sw2 = sw2
|
|
||||||
super().__init__(f'SW:{sw1:02X}{sw2:02X}')
|
|
||||||
|
|
||||||
def hexy(a):
|
def hexy(a):
|
||||||
return [hex(i) for i in a]
|
return [hex(i) for i in a]
|
||||||
|
|
||||||
def send_apdu(card, command, p1, p2, data=None, ne=None):
|
|
||||||
lc = []
|
|
||||||
dataf = []
|
|
||||||
if (data):
|
|
||||||
lc = [0x00] + list(len(data).to_bytes(2, 'big'))
|
|
||||||
dataf = data
|
|
||||||
if (ne is None):
|
|
||||||
le = [0x00, 0x00]
|
|
||||||
else:
|
|
||||||
le = list(ne.to_bytes(2, 'big'))
|
|
||||||
if (isinstance(command, list) and len(command) > 1):
|
|
||||||
apdu = command
|
|
||||||
else:
|
|
||||||
apdu = [0x00, command]
|
|
||||||
|
|
||||||
apdu = apdu + [p1, p2] + lc + dataf + le
|
|
||||||
try:
|
|
||||||
response, sw1, sw2 = card.connection.transmit(apdu)
|
|
||||||
except CardConnectionException:
|
|
||||||
card.connection.reconnect()
|
|
||||||
response, sw1, sw2 = card.connection.transmit(apdu)
|
|
||||||
if (sw1 != 0x90):
|
|
||||||
if (sw1 == 0x6A and sw2 == 0x82):
|
|
||||||
response, sw1, sw2 = card.connection.transmit([0x00, 0xA4, 0x04, 0x00, 0xB, 0xE8, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x81, 0xC3, 0x1F, 0x02, 0x01, 0x0])
|
|
||||||
if (sw1 == 0x90):
|
|
||||||
response, sw1, sw2 = card.connection.transmit(apdu)
|
|
||||||
if (sw1 == 0x90):
|
|
||||||
return response
|
|
||||||
elif (sw1 == 0x69 and sw2 == 0x82):
|
|
||||||
response, sw1, sw2 = card.connection.transmit([0x00, 0x20, 0x00, 0x81, len(pin)] + list(pin.encode()) + [0x0])
|
|
||||||
if (sw1 == 0x90):
|
|
||||||
response, sw1, sw2 = card.connection.transmit(apdu)
|
|
||||||
if (sw1 == 0x90):
|
|
||||||
return response
|
|
||||||
raise APDUResponse(sw1, sw2)
|
|
||||||
return response
|
|
||||||
|
|
||||||
def parse_args():
|
def parse_args():
|
||||||
parser = argparse.ArgumentParser()
|
parser = argparse.ArgumentParser()
|
||||||
subparser = parser.add_subparsers(title="commands", dest="command")
|
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_init = subparser.add_parser('initialize', help='Performs the first initialization of the Pico HSM.')
|
||||||
parser.add_argument('--pin', help='PIN number')
|
parser.add_argument('--pin', help='PIN number')
|
||||||
parser_init.add_argument('--so-pin', help='SO-PIN number')
|
parser_init.add_argument('--so-pin', help='SO-PIN number')
|
||||||
|
parser_init.add_argument('--silent', help='Confirms initialization silently.', action='store_true')
|
||||||
|
|
||||||
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 = 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')
|
parser_attestate.add_argument('-k', '--key', help='The private key index', metavar='KEY_ID')
|
||||||
|
|
||||||
parser_pki = subparser.add_parser('pki', help='Performs PKI operations.')
|
parser_pki = subparser.add_parser('pki', help='Performs PKI operations.')
|
||||||
subparser_pki = parser_pki.add_subparsers(title='commands', dest='subcommand')
|
subparser_pki = parser_pki.add_subparsers(title='commands', dest='subcommand', required=True)
|
||||||
parser_pki_init = subparser_pki.add_parser('initialize', help='Initializes the Public Key Infrastructure (PKI)')
|
parser_pki_init = subparser_pki.add_parser('initialize', help='Initializes the Public Key Infrastructure (PKI)')
|
||||||
|
|
||||||
parser_pki_init.add_argument('--certs-dir', help='Store the PKI certificates into this directory.', default='certs')
|
parser_pki_init.add_argument('--certs-dir', help='Store the PKI certificates into this directory.', default='certs')
|
||||||
@@ -126,36 +80,42 @@ def parse_args():
|
|||||||
parser_pki_init.add_argument('--force', help='Forces the download of certificates.', action='store_true')
|
parser_pki_init.add_argument('--force', help='Forces the download of certificates.', action='store_true')
|
||||||
|
|
||||||
parser_rtc = subparser.add_parser('datetime', help='Datetime operations with the integrated Real Time Clock (RTC).')
|
parser_rtc = subparser.add_parser('datetime', help='Datetime operations with the integrated Real Time Clock (RTC).')
|
||||||
subparser_rtc = parser_rtc.add_subparsers(title='commands', dest='subcommand')
|
subparser_rtc = parser_rtc.add_subparsers(title='commands', dest='subcommand', required=True)
|
||||||
parser_rtc_set = subparser_rtc.add_parser('set', help='Sets the current datetime.')
|
parser_rtc_set = subparser_rtc.add_parser('set', help='Sets the current datetime.')
|
||||||
parser_rtc_get = subparser_rtc.add_parser('set', help='Gets the current datetime.')
|
parser_rtc_get = subparser_rtc.add_parser('get', help='Gets the current datetime.')
|
||||||
|
|
||||||
parser_opts = subparser.add_parser('options', help='Manage extra options.', formatter_class=RawTextHelpFormatter)
|
parser_opts = subparser.add_parser('options', help='Manage extra options.', formatter_class=RawTextHelpFormatter)
|
||||||
subparser_opts = parser_opts.add_subparsers(title='commands', dest='subcommand')
|
subparser_opts = parser_opts.add_subparsers(title='commands', dest='subcommand', required=True)
|
||||||
parser_opts_set = subparser_opts.add_parser('set', help='Sets option OPT.')
|
parser_opts_set = subparser_opts.add_parser('set', help='Sets option OPT.')
|
||||||
parser_opts_get = subparser_opts.add_parser('get', help='Gets optiont OPT.')
|
parser_opts_get = subparser_opts.add_parser('get', help='Gets option OPT.')
|
||||||
parser_opts.add_argument('opt', choices=['button', 'counter'], help='button: press-to-confirm button.\ncounter: every generated key has an internal counter.', metavar='OPT')
|
parser_opts.add_argument('opt', choices=['button', 'counter'], help='button: press-to-confirm button.\ncounter: every generated key has an internal counter.', metavar='OPT')
|
||||||
parser_opts_set.add_argument('onoff', choices=['on', 'off'], help='Toggles state ON or OFF', metavar='ON/OFF', nargs='?')
|
parser_opts_set.add_argument('onoff', choices=['on', 'off'], help='Toggles state ON or OFF', metavar='ON/OFF', nargs='?')
|
||||||
|
|
||||||
|
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_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_secure = subparser.add_parser('secure', help='Manages security of Pico HSM.')
|
parser_secure = subparser.add_parser('secure', help='Manages security of Pico HSM.')
|
||||||
subparser_secure = parser_secure.add_subparsers(title='commands', dest='subcommand')
|
subparser_secure = parser_secure.add_subparsers(title='commands', dest='subcommand', required=True)
|
||||||
parser_opts_enable = subparser_secure.add_parser('enable', help='Enables secure lock.')
|
parser_opts_enable = subparser_secure.add_parser('enable', help='Enables secure lock.')
|
||||||
parser_opts_unlock = subparser_secure.add_parser('unlock', help='Unlocks the secure lock.')
|
parser_opts_unlock = subparser_secure.add_parser('unlock', help='Unlocks the secure lock.')
|
||||||
parser_opts_disable = subparser_secure.add_parser('disable', help='Disables secure lock.')
|
parser_opts_disable = subparser_secure.add_parser('disable', help='Disables secure lock.')
|
||||||
|
|
||||||
parser_cipher = subparser.add_parser('cipher', help='Implements extended symmetric ciphering with new algorithms and options.\n\tIf no file input/output is specified, stdin/stoud will be used.')
|
parser_cipher = subparser.add_parser('cipher', help='Implements extended symmetric ciphering with new algorithms and options.\n\tIf no file input/output is specified, stdin/stdout will be used.')
|
||||||
subparser_cipher = parser_cipher.add_subparsers(title='commands', dest='subcommand')
|
subparser_cipher = parser_cipher.add_subparsers(title='commands', dest='subcommand', required=True)
|
||||||
parser_cipher_encrypt = subparser_cipher.add_parser('encrypt', help='Performs encryption.')
|
parser_cipher_encrypt = subparser_cipher.add_parser('encrypt', help='Performs encryption.')
|
||||||
parser_cipher_decrypt = subparser_cipher.add_parser('decrypt', help='Performs decryption.')
|
parser_cipher_decrypt = subparser_cipher.add_parser('decrypt', help='Performs decryption.')
|
||||||
parser_cipher_keygen = subparser_cipher.add_parser('keygen', help='Generates new AES key.')
|
parser_cipher_hmac = subparser_cipher.add_parser('mac', help='Computes MAC (HMAC or CMAC).')
|
||||||
parser_cipher_hmac = subparser_cipher.add_parser('hmac', help='Computes HMAC.')
|
|
||||||
parser_cipher_kdf = subparser_cipher.add_parser('kdf', help='Performs key derivation function on a secret key.')
|
parser_cipher_kdf = subparser_cipher.add_parser('kdf', help='Performs key derivation function on a secret key.')
|
||||||
parser_cipher_encrypt.add_argument('--alg', choices=['CHACHAPOLY'], required=True)
|
parser_cipher_encrypt.add_argument('--alg', choices=['CHACHAPOLY','AES-ECB','AES-CBC','AES-OFB','AES-CFB','AES-GCM','AES-CCM','AES-CTR','AES-XTS'], required=True)
|
||||||
parser_cipher_encrypt.add_argument('--iteration', help='Iteration count.', required=any(['PBKDF2' in s for s in sys.argv]))
|
parser_cipher_decrypt.add_argument('--alg', choices=['CHACHAPOLY','AES-ECB','AES-CBC','AES-OFB','AES-CFB','AES-GCM','AES-CCM','AES-CTR','AES-XTS'], required=True)
|
||||||
parser_cipher_decrypt.add_argument('--alg', choices=['CHACHAPOLY'], required=True)
|
|
||||||
parser_cipher_decrypt.add_argument('--iteration', help='Iteration count.', required=any(['PBKDF2' in s for s in sys.argv]))
|
|
||||||
|
|
||||||
parser_cipher_hmac.add_argument('--alg', choices=['HMAC-SHA1', 'HMAC-SHA224', 'HMAC-SHA256', 'HMAC-SHA384', 'HMAC-SHA512'], help='Selects the algorithm.', required=True)
|
parser_cipher_hmac.add_argument('--alg', choices=['CMAC', 'HMAC-SHA1', 'HMAC-SHA224', 'HMAC-SHA256', 'HMAC-SHA384', 'HMAC-SHA512'], help='Selects the algorithm.', required=True)
|
||||||
parser_cipher_kdf.add_argument('--alg', choices=['HKDF-SHA256', 'HKDF-SHA384', 'HKDF-SHA512', 'PBKDF2-SHA1', 'PBKDF2-SHA224', 'PBKDF2-SHA256', 'PBKDF2-SHA384', 'PBKDF2-SHA512', 'X963-SHA1', 'X963-SHA224', 'X963-SHA256', 'X963-SHA384', 'X963-SHA512'], help='Selects the algorithm.', required=True)
|
parser_cipher_kdf.add_argument('--alg', choices=['HKDF-SHA256', 'HKDF-SHA384', 'HKDF-SHA512', 'PBKDF2-SHA1', 'PBKDF2-SHA224', 'PBKDF2-SHA256', 'PBKDF2-SHA384', 'PBKDF2-SHA512', 'X963-SHA1', 'X963-SHA224', 'X963-SHA256', 'X963-SHA384', 'X963-SHA512'], help='Selects the algorithm.', required=True)
|
||||||
parser_cipher_kdf.add_argument('--output-len', help='Specifies the output length of derived material.')
|
parser_cipher_kdf.add_argument('--output-len', help='Specifies the output length of derived material.')
|
||||||
parser_cipher_kdf.add_argument('--iteration', help='Iteration count.', required=any(['PBKDF2' in s for s in sys.argv]))
|
parser_cipher_kdf.add_argument('--iteration', help='Iteration count.', required=any(['PBKDF2' in s for s in sys.argv]))
|
||||||
@@ -165,23 +125,15 @@ def parse_args():
|
|||||||
parser_cipher.add_argument('--file-out', help='File to write the result.')
|
parser_cipher.add_argument('--file-out', help='File to write the result.')
|
||||||
parser_cipher.add_argument('--aad', help='Specifies the authentication data (it can be a string or hex string. Combine with --hex if necesary).')
|
parser_cipher.add_argument('--aad', help='Specifies the authentication data (it can be a string or hex string. Combine with --hex if necesary).')
|
||||||
parser_cipher.add_argument('--hex', help='Parses the AAD parameter as a hex string (for binary data).', action='store_true')
|
parser_cipher.add_argument('--hex', help='Parses the AAD parameter as a hex string (for binary data).', action='store_true')
|
||||||
parser_cipher.add_argument('-k', '--key', help='The private key index', metavar='KEY_ID', required=True)
|
parser_cipher.add_argument('-k', '--key', help='The private key index', metavar='KEY_ID', required=all(['keygen' not in s for s in sys.argv]))
|
||||||
parser_cipher.add_argument('-s', '--key-size', default=32, help='Size of the key in bytes.')
|
parser_cipher.add_argument('-s', '--key-size', default=32, help='Size of the key in bytes.')
|
||||||
|
|
||||||
parser_x25519 = argparse.ArgumentParser(add_help=False)
|
parser_keygen = subparser.add_parser('keygen', help='Generates private keypair or secret key.')
|
||||||
subparser_x25519 = parser_x25519.add_subparsers(title='commands', dest='subcommand')
|
subparser_keygen = parser_keygen.add_subparsers(title='commands', dest='subcommand', required=True)
|
||||||
parser_x25519_keygen = subparser_x25519.add_parser('keygen', help='Generates a keypair for X25519 or X448.')
|
parser_keygen_aes = subparser_keygen.add_parser('aes', help='Generates an AES key.')
|
||||||
parser_x25519.add_argument('-k', '--key', help='The private key index', metavar='KEY_ID', required=True)
|
parser_keygen_aes.add_argument('--size', help='Specifies the size of AES key [128, 192 or 256]',choices=[128, 192, 256], default=128)
|
||||||
|
parser_keygen_x25519 = subparser_keygen.add_parser('x25519', help='Generates a private X25519 keypair.')
|
||||||
# Subparsers based on parent
|
parser_keygen_x448 = subparser_keygen.add_parser('x448', help='Generates a private X448 keypair.')
|
||||||
|
|
||||||
parser_create = subparser.add_parser("x25519", parents=[parser_x25519],
|
|
||||||
help='X25519 key management.')
|
|
||||||
# Add some arguments exclusively for parser_create
|
|
||||||
|
|
||||||
parser_update = subparser.add_parser("x448", parents=[parser_x25519],
|
|
||||||
help='X448 key management.')
|
|
||||||
# Add some arguments exclusively for parser_update
|
|
||||||
|
|
||||||
args = parser.parse_args()
|
args = parser.parse_args()
|
||||||
return args
|
return args
|
||||||
@@ -215,56 +167,44 @@ def get_pki_certs(certs_dir='certs', force=False):
|
|||||||
f.write(base64.urlsafe_b64decode(certs['dvca']['cert']))
|
f.write(base64.urlsafe_b64decode(certs['dvca']['cert']))
|
||||||
print(f'All PKI certificates are stored at {certs_dir} folder')
|
print(f'All PKI certificates are stored at {certs_dir} folder')
|
||||||
|
|
||||||
def pki(card, args):
|
def pki(_, args):
|
||||||
if (args.subcommand == 'initialize'):
|
if (args.subcommand == 'initialize'):
|
||||||
if (args.default is True):
|
if (args.default is True):
|
||||||
get_pki_certs(certs_dir=args.certs_dir, force=args.force)
|
get_pki_certs(certs_dir=args.certs_dir, force=args.force)
|
||||||
else:
|
else:
|
||||||
print('Error: no PKI is passed. Use --default to retrieve default PKI.')
|
print('Error: no PKI is passed. Use --default to retrieve default PKI.')
|
||||||
|
|
||||||
def login(card, args):
|
def initialize(picohsm, args):
|
||||||
global pin
|
if (not args.silent):
|
||||||
pin = args.pin
|
print('********************************')
|
||||||
try:
|
print('* PLEASE READ IT CAREFULLY *')
|
||||||
response = send_apdu(card, 0x20, 0x00, 0x81, list(args.pin.encode()))
|
print('********************************')
|
||||||
except APDUResponse:
|
print('')
|
||||||
pass
|
print('This tool will erase and reset your device. It will delete all '
|
||||||
|
'private and secret keys.')
|
||||||
|
print('Are you sure?')
|
||||||
|
_ = input('[Press enter to confirm]')
|
||||||
|
|
||||||
def initialize(card, args):
|
|
||||||
print('********************************')
|
|
||||||
print('* PLEASE READ IT CAREFULLY *')
|
|
||||||
print('********************************')
|
|
||||||
print('')
|
|
||||||
print('This tool will erase and reset your device. It will delete all '
|
|
||||||
'private and secret keys.')
|
|
||||||
print('Are you sure?')
|
|
||||||
_ = input('[Press enter to confirm]')
|
|
||||||
|
|
||||||
send_apdu(card, 0xA4, 0x04, 0x00, [0xE8, 0x2B, 0x06, 0x01, 0x04, 0x01, 0x81, 0xC3, 0x1F, 0x02, 0x01])
|
|
||||||
if (args.pin):
|
if (args.pin):
|
||||||
pin = args.pin.encode()
|
|
||||||
try:
|
try:
|
||||||
response = send_apdu(card, 0x20, 0x00, 0x81, list(pin))
|
picohsm.login(args.pin)
|
||||||
except APDUResponse:
|
except APDUResponse:
|
||||||
pass
|
pass
|
||||||
|
pin = args.pin
|
||||||
else:
|
else:
|
||||||
pin = b'648219'
|
pin = '648219'
|
||||||
|
|
||||||
if (args.so_pin):
|
if (args.so_pin):
|
||||||
so_pin = args.so_pin.encode()
|
|
||||||
try:
|
try:
|
||||||
response = send_apdu(card, 0x20, 0x00, 0x82, list(so_pin))
|
picohsm.login(args.so_pin, who=PinType.SO_PIN)
|
||||||
except APDUResponse:
|
except APDUResponse:
|
||||||
pass
|
pass
|
||||||
|
so_pin = args.so_pin
|
||||||
else:
|
else:
|
||||||
so_pin = b'57621880'
|
so_pin = '57621880'
|
||||||
|
|
||||||
pin_data = [0x81, len(pin)] + list(pin)
|
picohsm.initialize(pin=pin, sopin=so_pin)
|
||||||
so_pin_data = [0x82, len(so_pin)] + list(so_pin)
|
response = picohsm.get_contents(DOPrefixes.EE_CERTIFICATE_PREFIX, 0x00)
|
||||||
reset_data = [0x80, 0x02, 0x00, 0x01] + pin_data + so_pin_data + [0x91, 0x01, 0x03]
|
|
||||||
response = send_apdu(card, [0x80, 0x50], 0x00, 0x00, reset_data)
|
|
||||||
|
|
||||||
response = send_apdu(card, 0xB1, 0xCE, 0x00, [0x54, 0x02, 0x00, 0x00])
|
|
||||||
|
|
||||||
cert = bytearray(response)
|
cert = bytearray(response)
|
||||||
Y = CVC().decode(cert).pubkey().find(0x86).data()
|
Y = CVC().decode(cert).pubkey().find(0x86).data()
|
||||||
@@ -275,14 +215,10 @@ def initialize(card, args):
|
|||||||
j = get_pki_data('cvc', data=data)
|
j = get_pki_data('cvc', data=data)
|
||||||
print('Device name: '+j['devname'])
|
print('Device name: '+j['devname'])
|
||||||
dataef = base64.urlsafe_b64decode(
|
dataef = base64.urlsafe_b64decode(
|
||||||
j['cvcert']) + base64.urlsafe_b64decode(j['dvcert'])
|
j['cvcert']) + base64.urlsafe_b64decode(j['dvcert']) + base64.urlsafe_b64decode(j['cacert'])
|
||||||
|
|
||||||
response = send_apdu(card, 0xa4, 0x00, 0x00, [0x2f, 0x02])
|
picohsm.select_file(0x2f02)
|
||||||
response = send_apdu(card, 0x20, 0x00, 0x81, list(pin))
|
response = picohsm.put_contents(0x0000, data=dataef)
|
||||||
|
|
||||||
apdu_data = [0x54, 0x02, 0x00, 0x00] + \
|
|
||||||
list(ASN1.make_tag(0x53, dataef))
|
|
||||||
response = send_apdu(card, 0xd7, 0x00, 0x00, apdu_data)
|
|
||||||
|
|
||||||
print('Certificate uploaded successfully!')
|
print('Certificate uploaded successfully!')
|
||||||
print('')
|
print('')
|
||||||
@@ -291,22 +227,11 @@ def initialize(card, args):
|
|||||||
print('Now you can initialize the device as usual with your chosen PIN '
|
print('Now you can initialize the device as usual with your chosen PIN '
|
||||||
'and configuration options.')
|
'and configuration options.')
|
||||||
|
|
||||||
def attestate(card, args):
|
def attestate(picohsm, args):
|
||||||
kid = int(args.key)
|
kid = int(args.key)
|
||||||
try:
|
termca = picohsm.get_termca()
|
||||||
response = send_apdu(card, 0xB1, 0x2F, 0x02, [0x54, 0x02, 0x00, 0x00])
|
devcert = termca['cv']['data']
|
||||||
except APDUResponse as a:
|
cert = picohsm.get_contents(0xCE, kid)
|
||||||
print('ERROR: There is an error with the device certificate.')
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
devcert = ASN1().decode(response).find(0x7f21, pos=0).data(return_tag=True)
|
|
||||||
|
|
||||||
try:
|
|
||||||
cert = send_apdu(card, 0xB1, 0xCE, kid, [0x54, 0x02, 0x00, 0x00])
|
|
||||||
except APDUResponse as a:
|
|
||||||
if (a.sw1 == 0x6a and a.sw2 == 0x82):
|
|
||||||
print('ERROR: Key not found')
|
|
||||||
sys.exit(1)
|
|
||||||
|
|
||||||
print(hexlify(bytearray(cert)))
|
print(hexlify(bytearray(cert)))
|
||||||
print(f'Details of key {kid}:\n')
|
print(f'Details of key {kid}:\n')
|
||||||
@@ -345,42 +270,41 @@ def attestate(card, args):
|
|||||||
else:
|
else:
|
||||||
print(f'Key {kid} is NOT generated by device {chr.decode()}')
|
print(f'Key {kid} is NOT generated by device {chr.decode()}')
|
||||||
|
|
||||||
def rtc(card, args):
|
def rtc(picohsm, args):
|
||||||
if (args.subcommand == 'set'):
|
if (args.subcommand == 'set'):
|
||||||
now = datetime.now()
|
now = datetime.now()
|
||||||
_ = send_apdu(card, [0x80, 0x64], 0x0A, 0x00, list(now.year.to_bytes(2, 'big')) + [now.month, now.day, now.weekday(), now.hour, now.minute, now.second ])
|
_ = picohsm.send(cla=0x80, command=0x64, p1=0x0A, data=list(now.year.to_bytes(2, 'big')) + [now.month, now.day, now.weekday(), now.hour, now.minute, now.second ])
|
||||||
elif (args.subcommand == 'get'):
|
elif (args.subcommand == 'get'):
|
||||||
response = send_apdu(card, [0x80, 0x64], 0x0A, 0x00)
|
response = picohsm.send(cla=0x80, command=0x64, p1=0x0A)
|
||||||
dt = datetime(int.from_bytes(response[:2], 'big'), response[2], response[3], response[5], response[6], response[7])
|
dt = datetime(int.from_bytes(response[:2], 'big'), response[2], response[3], response[5], response[6], response[7])
|
||||||
print(f'Current date and time is: {dt.ctime()}')
|
print(f'Current date and time is: {dt.ctime()}')
|
||||||
|
|
||||||
def opts(card, args):
|
def opts(picohsm, args):
|
||||||
opt = 0x0
|
opt = 0x0
|
||||||
if (args.opt == 'button'):
|
if (args.opt == 'button'):
|
||||||
opt = 0x1
|
opt = 0x1
|
||||||
elif (args.opt == 'counter'):
|
elif (args.opt == 'counter'):
|
||||||
opt = 0x2
|
opt = 0x2
|
||||||
current = send_apdu(card, [0x80, 0x64], 0x6, 0x0)[0]
|
current = picohsm.send(cla=0x80, command=0x64, p1=0x6)[0]
|
||||||
if (args.subcommand == 'set'):
|
if (args.subcommand == 'set'):
|
||||||
if (args.onoff == 'on'):
|
if (args.onoff == 'on'):
|
||||||
newopt = current | opt
|
newopt = current | opt
|
||||||
else:
|
else:
|
||||||
newopt = current & ~opt
|
newopt = current & ~opt
|
||||||
send_apdu(card, [0x80, 0x64], 0x6, 0x0, [newopt])
|
picohsm.send(cla=0x80, command=0x64, p1=0x6, data=[newopt])
|
||||||
elif (args.subcommand == 'get'):
|
elif (args.subcommand == 'get'):
|
||||||
print(f'Option {args.opt.upper()} is {"ON" if current & opt else "OFF"}')
|
print(f'Option {args.opt.upper()} is {"ON" if current & opt else "OFF"}')
|
||||||
|
|
||||||
class SecureLock:
|
class SecureLock:
|
||||||
def __init__(self, card):
|
def __init__(self, picohsm):
|
||||||
self.card = card
|
self.picohsm = picohsm
|
||||||
|
|
||||||
def mse(self):
|
def mse(self):
|
||||||
sk = ec.generate_private_key(ec.SECP256R1())
|
sk = ec.generate_private_key(ec.SECP256R1())
|
||||||
pn = sk.public_key().public_numbers()
|
pn = sk.public_key().public_numbers()
|
||||||
self.__pb = sk.public_key().public_bytes(Encoding.X962, PublicFormat.UncompressedPoint)
|
self.__pb = sk.public_key().public_bytes(Encoding.X962, PublicFormat.UncompressedPoint)
|
||||||
|
|
||||||
|
ret = self.picohsm.send(cla=0x80, command=0x64, p1=0x3A, p2=0x01, data=list(self.__pb))
|
||||||
ret = send_apdu(self.card, [0x80, 0x64], 0x3A, 0x01, list(self.__pb))
|
|
||||||
|
|
||||||
pk = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), bytes(ret))
|
pk = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), bytes(ret))
|
||||||
shared_key = sk.exchange(ec.ECDH(), pk)
|
shared_key = sk.exchange(ec.ECDH(), pk)
|
||||||
@@ -402,7 +326,7 @@ class SecureLock:
|
|||||||
|
|
||||||
def unlock_device(self):
|
def unlock_device(self):
|
||||||
ct = self.get_skey()
|
ct = self.get_skey()
|
||||||
send_apdu(self.card, [0x80, 0x64], 0x3A, 0x03, list(ct))
|
self.picohsm.send(cla=0x80, command=0x64, p1=0x3A, p2=0x03, data=list(ct))
|
||||||
|
|
||||||
def _get_key_device(self):
|
def _get_key_device(self):
|
||||||
if (platform.system() == 'Windows' or platform.system() == 'Linux'):
|
if (platform.system() == 'Windows' or platform.system() == 'Linux'):
|
||||||
@@ -421,15 +345,14 @@ class SecureLock:
|
|||||||
|
|
||||||
def enable_device_aut(self):
|
def enable_device_aut(self):
|
||||||
ct = self.get_skey()
|
ct = self.get_skey()
|
||||||
send_apdu(self.card, [0x80, 0x64], 0x3A, 0x02, list(ct))
|
self.picohsm.send(cla=0x80, command=0x64, p1=0x3A, p2=0x02, data=list(ct))
|
||||||
|
|
||||||
def disable_device_aut(self):
|
def disable_device_aut(self):
|
||||||
ct = self.get_skey()
|
ct = self.get_skey()
|
||||||
send_apdu(self.card, [0x80, 0x64], 0x3A, 0x04, list(ct))
|
self.picohsm.send(cla=0x80, command=0x64, p1=0x3A, p2=0x04, p3=list(ct))
|
||||||
|
|
||||||
|
def secure(picohsm, args):
|
||||||
def secure(card, args):
|
slck = SecureLock(picohsm)
|
||||||
slck = SecureLock(card)
|
|
||||||
if (args.subcommand == 'enable'):
|
if (args.subcommand == 'enable'):
|
||||||
slck.enable_device_aut()
|
slck.enable_device_aut()
|
||||||
elif (args.subcommand == 'unlock'):
|
elif (args.subcommand == 'unlock'):
|
||||||
@@ -437,197 +360,145 @@ def secure(card, args):
|
|||||||
elif (args.subcommand == 'disable'):
|
elif (args.subcommand == 'disable'):
|
||||||
slck.disable_device_aut()
|
slck.disable_device_aut()
|
||||||
|
|
||||||
|
def cipher(picohsm, args):
|
||||||
def cipher(card, args):
|
if (args.file_in):
|
||||||
if (args.subcommand == 'keygen'):
|
fin = open(args.file_in, 'rb')
|
||||||
ksize = 0xB2
|
|
||||||
if (args.key_size == 24):
|
|
||||||
ksize = 0xB1
|
|
||||||
elif (args.key_size == 16):
|
|
||||||
ksize = 0xB0
|
|
||||||
ret = send_apdu(card, 0x48, int(args.key), ksize)
|
|
||||||
|
|
||||||
else:
|
else:
|
||||||
enc = None
|
fin = sys.stdin.buffer
|
||||||
aad = None
|
enc = fin.read()
|
||||||
if (args.alg == 'CHACHAPOLY'):
|
fin.close()
|
||||||
oid = b'\x2A\x86\x48\x86\xF7\x0D\x01\x09\x10\x03\x12'
|
iv = args.iv
|
||||||
elif (args.alg == 'HMAC-SHA1'):
|
if (args.iv and args.hex):
|
||||||
oid = b'\x2A\x86\x48\x86\xF7\x0D\x02\x07'
|
iv = unhexlify(iv)
|
||||||
elif (args.alg == 'HMAC-SHA224'):
|
aad = args.aad
|
||||||
oid = b'\x2A\x86\x48\x86\xF7\x0D\x02\x08'
|
if (args.aad and args.hex):
|
||||||
elif (args.alg == 'HMAC-SHA256'):
|
aad = unhexlify(aad)
|
||||||
oid = b'\x2A\x86\x48\x86\xF7\x0D\x02\x09'
|
kid = int(args.key)
|
||||||
elif (args.alg == 'HMAC-SHA384'):
|
|
||||||
oid = b'\x2A\x86\x48\x86\xF7\x0D\x02\x0A'
|
|
||||||
elif (args.alg == 'HMAC-SHA512'):
|
|
||||||
oid = b'\x2A\x86\x48\x86\xF7\x0D\x02\x0B'
|
|
||||||
elif (args.alg == 'HKDF-SHA256'):
|
|
||||||
oid = b'\x2A\x86\x48\x86\xF7\x0D\x01\x09\x10\x03\x1D'
|
|
||||||
elif (args.alg == 'HKDF-SHA384'):
|
|
||||||
oid = b'\x2A\x86\x48\x86\xF7\x0D\x01\x09\x10\x03\x1E'
|
|
||||||
elif (args.alg == 'HKDF-SHA512'):
|
|
||||||
oid = b'\x2A\x86\x48\x86\xF7\x0D\x01\x09\x10\x03\x1F'
|
|
||||||
elif (args.alg in ['PBKDF2-SHA1', 'PBKDF2-SHA224', 'PBKDF2-SHA256', 'PBKDF2-SHA384', 'PBKDF2-SHA512']):
|
|
||||||
if ('PBKDF2' in args.alg):
|
|
||||||
oid = b'\x2A\x86\x48\x86\xF7\x0D\x01\x05\x0C'
|
|
||||||
salt = b'\x04' + bytes([len(args.iv)//2]) + unhexlify(args.iv)
|
|
||||||
iteration = b'\x02' + bytes([len(int_to_bytes(int(args.iteration)))]) + int_to_bytes(int(args.iteration))
|
|
||||||
prf = b'\x30\x0A\x06\x08\x2A\x86\x48\x86\xF7\x0D\x02'
|
|
||||||
if (args.alg == 'PBKDF2-SHA1'):
|
|
||||||
prf += b'\x07'
|
|
||||||
elif (args.alg == 'PBKDF2-SHA224'):
|
|
||||||
prf += b'\x08'
|
|
||||||
elif (args.alg == 'PBKDF2-SHA256'):
|
|
||||||
prf += b'\x09'
|
|
||||||
elif (args.alg == 'PBKDF2-SHA384'):
|
|
||||||
prf += b'\x0A'
|
|
||||||
elif (args.alg == 'PBKDF2-SHA512'):
|
|
||||||
prf += b'\x0B'
|
|
||||||
enc = list(salt + iteration + prf)
|
|
||||||
elif (args.alg in 'X963-SHA1', 'X963-SHA224', 'X963-SHA256', 'X963-SHA384', 'X963-SHA512'):
|
|
||||||
oid = b'\x2B\x81\x05\x10\x86\x48\x3F'
|
|
||||||
enc = b'\x2A\x86\x48\x86\xF7\x0D\x02'
|
|
||||||
if (args.alg == 'X963-SHA1'):
|
|
||||||
enc += b'\x07'
|
|
||||||
elif (args.alg == 'X963-SHA224'):
|
|
||||||
enc += b'\x08'
|
|
||||||
elif (args.alg == 'X963-SHA256'):
|
|
||||||
enc += b'\x09'
|
|
||||||
elif (args.alg == 'X963-SHA384'):
|
|
||||||
enc += b'\x0A'
|
|
||||||
elif (args.alg == 'X963-SHA512'):
|
|
||||||
enc += b'\x0B'
|
|
||||||
'''
|
|
||||||
# To be finished: it does not work with AES (only supported by HSM)
|
|
||||||
elif (args.alg in ['PBES2-SHA1', 'PBES2-SHA224', 'PBES2-SHA256', 'PBES2-SHA384', 'PBES2-SHA512']):
|
|
||||||
oid = b'\x2A\x86\x48\x86\xF7\x0D\x01\x05\x0D'
|
|
||||||
if (not args.iv):
|
|
||||||
sys.stderr.buffer.write(b'ERROR: --iv required')
|
|
||||||
sys.exit(-1)
|
|
||||||
salt = b'\x04' + bytes([len(args.iv)//2]) + unhexlify(args.iv)
|
|
||||||
iteration = b'\x02' + bytes([len(int_to_bytes(int(args.iteration)))]) + int_to_bytes(int(args.iteration))
|
|
||||||
prf = b'\x30\x0A\x06\x08\x2A\x86\x48\x86\xF7\x0D\x02'
|
|
||||||
if (args.alg == 'PBES2-SHA1'):
|
|
||||||
prf += b'\x07'
|
|
||||||
elif (args.alg == 'PBES2-SHA224'):
|
|
||||||
prf += b'\x08'
|
|
||||||
elif (args.alg == 'PBES2-SHA256'):
|
|
||||||
prf += b'\x09'
|
|
||||||
elif (args.alg == 'PBES2-SHA384'):
|
|
||||||
prf += b'\x0A'
|
|
||||||
elif (args.alg == 'PBES2-SHA512'):
|
|
||||||
prf += b'\x0B'
|
|
||||||
oid_kdf = b'\x06\x09\x2A\x86\x48\x86\xF7\x0D\x01\x05\x0C'
|
|
||||||
aad = hexlify(oid_kdf + b'\x30' + bytes([len(salt)+len(iteration)+len(prf)]) + salt + iteration + prf)
|
|
||||||
args.hex = True
|
|
||||||
'''
|
|
||||||
|
|
||||||
if (args.subcommand[0] == 'e' or args.subcommand == 'hmac' or args.subcommand == 'kdf'):
|
mode = EncryptionMode.ENCRYPT if args.subcommand[0] == 'e' else EncryptionMode.DECRYPT
|
||||||
alg = 0x51
|
if (args.alg == 'CHACHAPOLY'):
|
||||||
elif (args.subcommand[0] == 'd'):
|
ret = picohsm.chachapoly(kid, mode, data=enc, iv=iv, aad=aad)
|
||||||
alg = 0x52
|
elif (args.alg == 'AES-ECB'):
|
||||||
|
ret = picohsm.aes(keyid=kid, mode=mode, algorithm=AES.ECB, data=enc, iv=iv, aad=aad)
|
||||||
|
elif (args.alg == 'AES-CBC'):
|
||||||
|
ret = picohsm.aes(keyid=kid, mode=mode, algorithm=AES.CBC, data=enc, iv=iv, aad=aad)
|
||||||
|
elif (args.alg == 'AES-OFB'):
|
||||||
|
ret = picohsm.aes(keyid=kid, mode=mode, algorithm=AES.OFB, data=enc, iv=iv, aad=aad)
|
||||||
|
elif (args.alg == 'AES-CFB'):
|
||||||
|
ret = picohsm.aes(keyid=kid, mode=mode, algorithm=AES.CFB, data=enc, iv=iv, aad=aad)
|
||||||
|
elif (args.alg == 'AES-GCM'):
|
||||||
|
ret = picohsm.aes(keyid=kid, mode=mode, algorithm=AES.GCM, data=enc, iv=iv, aad=aad)
|
||||||
|
elif (args.alg == 'AES-CCM'):
|
||||||
|
ret = picohsm.aes(keyid=kid, mode=mode, algorithm=AES.CCM, data=enc, iv=iv, aad=aad)
|
||||||
|
elif (args.alg == 'AES-CTR'):
|
||||||
|
ret = picohsm.aes(keyid=kid, mode=mode, algorithm=AES.CTR, data=enc, iv=iv, aad=aad)
|
||||||
|
elif (args.alg == 'AES-XTS'):
|
||||||
|
ret = picohsm.aes(keyid=kid, mode=mode, algorithm=AES.XTS, data=enc, iv=iv, aad=aad)
|
||||||
|
elif (args.alg == 'CMAC'):
|
||||||
|
ret = picohsm.cmac(keyid=kid, data=enc)
|
||||||
|
elif (args.alg == 'HMAC-SHA1'):
|
||||||
|
ret = picohsm.hmac(hashes.SHA1, kid, data=enc)
|
||||||
|
elif (args.alg == 'HMAC-SHA224'):
|
||||||
|
ret = picohsm.hmac(hashes.SHA224, kid, data=enc)
|
||||||
|
elif (args.alg == 'HMAC-SHA256'):
|
||||||
|
ret = picohsm.hmac(hashes.SHA256, kid, data=enc)
|
||||||
|
elif (args.alg == 'HMAC-SHA384'):
|
||||||
|
ret = picohsm.hmac(hashes.SHA384, kid, data=enc)
|
||||||
|
elif (args.alg == 'HMAC-SHA512'):
|
||||||
|
ret = picohsm.hmac(hashes.SHA512, kid, data=enc)
|
||||||
|
elif (args.alg == 'HKDF-SHA256'):
|
||||||
|
ret = picohsm.hkdf(hashes.SHA256, kid, data=enc, salt=iv, out_len=args.output_len)
|
||||||
|
elif (args.alg == 'HKDF-SHA384'):
|
||||||
|
ret = picohsm.hkdf(hashes.SHA384, kid, data=enc, salt=iv, out_len=args.output_len)
|
||||||
|
elif (args.alg == 'HKDF-SHA512'):
|
||||||
|
ret = picohsm.hkdf(hashes.SHA512, kid, data=enc, salt=iv, out_len=args.output_len)
|
||||||
|
elif (args.alg == 'PBKDF2-SHA1'):
|
||||||
|
ret = picohsm.pbkdf2(hashes.SHA1, kid, salt=iv, iterations=args.iteration, out_len=args.output_len)
|
||||||
|
elif (args.alg == 'PBKDF2-SHA224'):
|
||||||
|
ret = picohsm.pbkdf2(hashes.SHA224, kid, salt=iv, iterations=args.iteration, out_len=args.output_len)
|
||||||
|
elif (args.alg == 'PBKDF2-SHA256'):
|
||||||
|
ret = picohsm.pbkdf2(hashes.SHA256, kid, salt=iv, iterations=args.iteration, out_len=args.output_len)
|
||||||
|
elif (args.alg == 'PBKDF2-SHA384'):
|
||||||
|
ret = picohsm.pbkdf2(hashes.SHA384, kid, salt=iv, iterations=args.iteration, out_len=args.output_len)
|
||||||
|
elif (args.alg == 'PBKDF2-SHA512'):
|
||||||
|
ret = picohsm.pbkdf2(hashes.SHA512, kid, salt=iv, iterations=args.iteration, out_len=args.output_len)
|
||||||
|
elif (args.alg == 'X963-SHA1'):
|
||||||
|
ret = picohsm.x963(hashes.SHA1, kid, data=enc, out_len=args.output_len)
|
||||||
|
elif (args.alg == 'X963-SHA224'):
|
||||||
|
ret = picohsm.x963(hashes.SHA224, kid, data=enc, out_len=args.output_len)
|
||||||
|
elif (args.alg == 'X963-SHA256'):
|
||||||
|
ret = picohsm.x963(hashes.SHA256, kid, data=enc, out_len=args.output_len)
|
||||||
|
elif (args.alg == 'X963-SHA384'):
|
||||||
|
ret = picohsm.x963(hashes.SHA384, kid, data=enc, out_len=args.output_len)
|
||||||
|
elif (args.alg == 'X963-SHA512'):
|
||||||
|
ret = picohsm.x963(hashes.SHA512, kid, data=enc, out_len=args.output_len)
|
||||||
|
|
||||||
if (not enc):
|
if (args.file_out):
|
||||||
if (args.file_in):
|
fout = open(args.file_out, 'wb')
|
||||||
fin = open(args.file_in, 'rb')
|
else:
|
||||||
else:
|
fout = sys.stdout.buffer
|
||||||
fin = sys.stdin.buffer
|
if (args.hex):
|
||||||
enc = fin.read()
|
fout.write(hexlify(bytes(ret)))
|
||||||
fin.close()
|
else:
|
||||||
|
fout.write(bytes(ret))
|
||||||
|
if (args.file_out):
|
||||||
|
fout.close()
|
||||||
|
|
||||||
data = [0x06, len(oid)] + list(oid) + [0x81, len(enc)] + list(enc)
|
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:]
|
||||||
|
ret = picohsm.key_generation(KeyType.ECC, curve)
|
||||||
|
print('Key generated successfully.')
|
||||||
|
print(f'Key ID: {ret}')
|
||||||
|
|
||||||
if (args.iv and not 'PBKDF2' in args.alg and not 'PBES2' in args.alg):
|
def phy(picohsm, args):
|
||||||
data += [0x82, len(args.iv)//2] + list(unhexlify(args.iv))
|
val = args.value if 'value' in args else None
|
||||||
if (not aad):
|
if (val):
|
||||||
aad = args.aad
|
if (args.subcommand == 'vidpid'):
|
||||||
if (aad):
|
sp = val.split(':')
|
||||||
if (args.hex):
|
if (len(sp) != 2):
|
||||||
data += [0x83, len(aad)//2] + list(unhexlify(aad))
|
print('ERROR: VID/PID have wrong format. Use VID:PID format (e.g. 1234:5678)')
|
||||||
else:
|
val = int(sp[0],16).to_bytes(2, 'big') + int(sp[1],16).to_bytes(2, 'big')
|
||||||
data += [0x83, len(aad)] + list(aad)
|
elif (args.subcommand == 'led'):
|
||||||
|
val = [int(val)]
|
||||||
ne = int(args.output_len) if 'output_len' in args and args.output_len else None
|
elif (args.subcommand == 'wcid'):
|
||||||
|
val = val == 'enable'
|
||||||
ret = send_apdu(card, [0x80, 0x78], int(args.key), alg, data=data, ne=ne)
|
ret = picohsm.phy(args.subcommand, val)
|
||||||
if (args.file_out):
|
if (ret):
|
||||||
fout = open(args.file_out, 'wb')
|
print(f'Current value: {hexlify(ret)}')
|
||||||
else:
|
else:
|
||||||
fout = sys.stdout.buffer
|
print('Command executed successfully. Please, restart your Pico Key.')
|
||||||
if (args.hex):
|
|
||||||
fout.write(hexlify(bytes(ret)))
|
|
||||||
else:
|
|
||||||
fout.write(bytes(ret))
|
|
||||||
if (args.file_out):
|
|
||||||
fout.close()
|
|
||||||
|
|
||||||
def int_to_bytes(x: int) -> bytes:
|
|
||||||
return x.to_bytes((x.bit_length() + 7) // 8, 'big')
|
|
||||||
|
|
||||||
def x25519(card, args):
|
|
||||||
if (args.command == 'x25519'):
|
|
||||||
P = b'\x7f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xed'
|
|
||||||
A = int_to_bytes(0x01DB42)
|
|
||||||
N = b'\x10\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x14\xDE\xF9\xDE\xA2\xF7\x9C\xD6\x58\x12\x63\x1A\x5C\xF5\xD3\xED'
|
|
||||||
G = b'\x04\x09\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xd9\xd3\xce\x7e\xa2\xc5\xe9\x29\xb2\x61\x7c\x6d\x7e\x4d\x3d\x92\x4c\xd1\x48\x77\x2c\xdd\x1e\xe0\xb4\x86\xa0\xb8\xa1\x19\xae\x20'
|
|
||||||
h = b'\x08'
|
|
||||||
elif (args.command == 'x448'):
|
|
||||||
P = b'\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xfe\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff'
|
|
||||||
A = int_to_bytes(0x98AA)
|
|
||||||
N = b'\x3f\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\xff\x7c\xca\x23\xe9\xc4\x4e\xdb\x49\xae\xd6\x36\x90\x21\x6c\xc2\x72\x8d\xc5\x8f\x55\x23\x78\xc2\x92\xab\x58\x44\xf3'
|
|
||||||
G = b'\x04\x05\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x1a\x5b\x7b\x45\x3d\x22\xd7\x6f\xf7\x7a\x67\x50\xb1\xc4\x12\x13\x21\x0d\x43\x46\x23\x7e\x02\xb8\xed\xf6\xf3\x8d\xc2\x5d\xf7\x60\xd0\x45\x55\xf5\x34\x5d\xae\xcb\xce\x6f\x32\x58\x6e\xab\x98\x6c\xf6\xb1\xf5\x95\x12\x5d\x23\x7d'
|
|
||||||
h = b'\x04'
|
|
||||||
oid = b'\x06\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x02\x03'
|
|
||||||
p_data = b'\x81' + bytes([len(P)]) + P
|
|
||||||
a_data = b'\x82' + bytes([len(A)]) + A
|
|
||||||
g_data = b'\x84' + bytes([len(G)]) + G
|
|
||||||
n_data = b'\x85' + bytes([len(N)]) + N
|
|
||||||
h_data = b'\x87' + bytes([len(h)]) + h
|
|
||||||
|
|
||||||
cdata = b'\x5F\x29\x01\x00'
|
|
||||||
cdata += b'\x42\x0C\x55\x54\x44\x55\x4D\x4D\x59\x30\x30\x30\x30\x31'
|
|
||||||
cdata += b'\x7f\x49\x81' + bytes([len(oid)+len(p_data)+len(a_data)+len(g_data)+len(n_data)+len(h_data)]) + oid + p_data + a_data + g_data + n_data + h_data
|
|
||||||
cdata += b'\x5F\x20\x0C\x55\x54\x44\x55\x4D\x4D\x59\x30\x30\x30\x30\x31'
|
|
||||||
ret = send_apdu(card, 0x46, int(args.key), 0x00, list(cdata))
|
|
||||||
|
|
||||||
def main(args):
|
def main(args):
|
||||||
sys.stderr.buffer.write(b'Pico HSM Tool v1.8\n')
|
sys.stderr.buffer.write(b'Pico HSM Tool v1.14\n')
|
||||||
sys.stderr.buffer.write(b'Author: Pol Henarejos\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'Report bugs to https://github.com/polhenarejos/pico-hsm/issues\n')
|
||||||
sys.stderr.buffer.write(b'\n\n')
|
sys.stderr.buffer.write(b'\n\n')
|
||||||
cardtype = AnyCardType()
|
sys.stderr.flush()
|
||||||
try:
|
|
||||||
# request card insertion
|
|
||||||
cardrequest = CardRequest(timeout=10, cardType=cardtype)
|
|
||||||
card = cardrequest.waitforcard()
|
|
||||||
|
|
||||||
# connect to the card and perform a few transmits
|
picohsm = PicoHSM(args.pin)
|
||||||
card.connection.connect()
|
|
||||||
|
|
||||||
except CardRequestTimeoutException:
|
|
||||||
raise Exception('time-out: no card inserted during last 10s')
|
|
||||||
|
|
||||||
if (args.pin):
|
|
||||||
login(card, args)
|
|
||||||
|
|
||||||
# Following commands may raise APDU exception on error
|
# Following commands may raise APDU exception on error
|
||||||
if (args.command == 'initialize'):
|
if (args.command == 'initialize'):
|
||||||
initialize(card, args)
|
initialize(picohsm, args)
|
||||||
elif (args.command == 'attestate'):
|
elif (args.command == 'attestate'):
|
||||||
attestate(card, args)
|
attestate(picohsm, args)
|
||||||
elif (args.command == 'pki'):
|
elif (args.command == 'pki'):
|
||||||
pki(card, args)
|
pki(picohsm, args)
|
||||||
elif (args.command == 'datetime'):
|
elif (args.command == 'datetime'):
|
||||||
rtc(card, args)
|
rtc(picohsm, args)
|
||||||
elif (args.command == 'options'):
|
elif (args.command == 'options'):
|
||||||
opts(card, args)
|
opts(picohsm, args)
|
||||||
elif (args.command == 'secure'):
|
elif (args.command == 'secure'):
|
||||||
secure(card, args)
|
secure(picohsm, args)
|
||||||
elif (args.command == 'cipher'):
|
elif (args.command == 'cipher'):
|
||||||
cipher(card, args)
|
cipher(picohsm, args)
|
||||||
elif (args.command == 'x25519' or args.command == 'x448'):
|
elif (args.command == 'keygen'):
|
||||||
x25519(card, args)
|
keygen(picohsm, args)
|
||||||
|
elif (args.command == 'phy'):
|
||||||
|
phy(picohsm, args)
|
||||||
|
|
||||||
|
|
||||||
def run():
|
def run():
|
||||||
|
|||||||
@@ -51,7 +51,9 @@ def get_secure_key():
|
|||||||
try:
|
try:
|
||||||
backend = get_backend(False)
|
backend = get_backend(False)
|
||||||
key = backend.get_password(DOMAIN, USERNAME)[0]
|
key = backend.get_password(DOMAIN, USERNAME)[0]
|
||||||
except keyring.errors.KeyringError:
|
if (key is None):
|
||||||
|
raise TypeError
|
||||||
|
except (keyring.errors.KeyringError, TypeError):
|
||||||
try:
|
try:
|
||||||
key = generate_secure_key(False)[0] # It should be True, but secure enclave causes python segfault
|
key = generate_secure_key(False)[0] # It should be True, but secure enclave causes python segfault
|
||||||
except keyring.errors.PasswordSetError:
|
except keyring.errors.PasswordSetError:
|
||||||
|
|||||||
@@ -8,7 +8,7 @@ USERNAME = "Pico-HSM"
|
|||||||
try:
|
try:
|
||||||
import keyring
|
import keyring
|
||||||
except:
|
except:
|
||||||
print('ERROR: keyring module not found! Install keyring package.\nTry with `pip install keyrings.osx-keychain-keys`')
|
print('ERROR: keyring module not found! Install keyring package.\nTry with `pip install keyring`')
|
||||||
sys.exit(-1)
|
sys.exit(-1)
|
||||||
|
|
||||||
try:
|
try:
|
||||||
@@ -39,6 +39,8 @@ def get_secure_key():
|
|||||||
key = None
|
key = None
|
||||||
try:
|
try:
|
||||||
key = keyring.get_password(DOMAIN, USERNAME)
|
key = keyring.get_password(DOMAIN, USERNAME)
|
||||||
except keyring.errors.KeyringError:
|
if (key is None):
|
||||||
|
raise TypeError
|
||||||
|
except (keyring.errors.KeyringError, TypeError):
|
||||||
key = generate_secure_key()
|
key = generate_secure_key()
|
||||||
return get_d(key.encode())
|
return get_d(key.encode())
|
||||||
|
|||||||
@@ -9,5 +9,9 @@ git submodule update --init
|
|||||||
cd ..
|
cd ..
|
||||||
mkdir build
|
mkdir build
|
||||||
cd build
|
cd build
|
||||||
|
if [[ $1 == "pico" ]]; then
|
||||||
cmake -DPICO_SDK_PATH=../pico-sdk ..
|
cmake -DPICO_SDK_PATH=../pico-sdk ..
|
||||||
|
else
|
||||||
|
cmake -DENABLE_EMULATION=1 ..
|
||||||
|
fi
|
||||||
make
|
make
|
||||||
|
|||||||
Reference in New Issue
Block a user