Compare commits
285 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ccfe7ca8a8 | ||
|
|
d2d038f14d | ||
|
|
1a05d7b51f | ||
|
|
fa60ed5049 | ||
|
|
35aec06391 | ||
|
|
61359c7ebd | ||
|
|
20c01eb08d | ||
|
|
0b71bf693d | ||
|
|
a1f478239d | ||
|
|
420e55901c | ||
|
|
414cab78e3 | ||
|
|
36e5282d19 | ||
|
|
367651fe75 | ||
|
|
7b62ca5327 | ||
|
|
9be176e523 | ||
|
|
b24e109a3c | ||
|
|
f61d0dd677 | ||
|
|
215fdca9f8 | ||
|
|
9279773073 | ||
|
|
d5b718ca58 | ||
|
|
cd6e280f4f | ||
|
|
e7495d11f2 | ||
|
|
daaa5bf402 | ||
|
|
cab72f200a | ||
|
|
380d47faa1 | ||
|
|
962d1c6916 | ||
|
|
d81d51d6fc | ||
|
|
319000df1a | ||
|
|
5508e531a0 | ||
|
|
1e846600dd | ||
|
|
43a49d2a14 | ||
|
|
3b9c2d159b | ||
|
|
14c7852143 | ||
|
|
407110def4 | ||
|
|
79d86a335c | ||
|
|
0685be5f1e | ||
|
|
8f6ae52c70 | ||
|
|
af16be64a2 | ||
|
|
68071825c2 | ||
|
|
fbabb81acd | ||
|
|
8bc4b133ca | ||
|
|
2ce458dad5 | ||
|
|
478b186094 | ||
|
|
ab71b3163b | ||
|
|
c4de88e6c6 | ||
|
|
3b0e34f465 | ||
|
|
9077e78315 | ||
|
|
2f5fcd1f14 | ||
|
|
24d430a3ac | ||
|
|
307eb63ee5 | ||
|
|
07f85dc4b8 | ||
|
|
a4026e0ca0 | ||
|
|
ebd8dc7bb8 | ||
|
|
bac15d5472 | ||
|
|
8540fdcf19 | ||
|
|
fc8d39882f | ||
|
|
ca093eb81e | ||
|
|
35c42bccb4 | ||
|
|
52114b2d85 | ||
|
|
8f593f6357 | ||
|
|
6f8769ee8d | ||
|
|
1af461c206 | ||
|
|
8976dc1f79 | ||
|
|
9d47e62041 | ||
|
|
0daddfd477 | ||
|
|
89d617110f | ||
|
|
17941397e9 | ||
|
|
f2aa4aae79 | ||
|
|
e29b3143ed | ||
|
|
5419ff74ee | ||
|
|
723011078c | ||
|
|
fe7c0333ab | ||
|
|
c01940b62b | ||
|
|
7195a8f3ec | ||
|
|
7764de4e10 | ||
|
|
e05c526b4d | ||
|
|
bc20f98b44 | ||
|
|
742c3f3e3c | ||
|
|
9793977ffc | ||
|
|
6c85772fff | ||
|
|
9ff3254a4c | ||
|
|
7d906851dd | ||
|
|
691aa3308c | ||
|
|
6a57e67629 | ||
|
|
202c8a4b22 | ||
|
|
f2874ae3ef | ||
|
|
9e9cf9b768 | ||
|
|
c95dee84f2 | ||
|
|
65cde9960f | ||
|
|
7ca96178fb | ||
|
|
020feaf325 | ||
|
|
e70461e551 | ||
|
|
0e918434a2 | ||
|
|
63c85000d0 | ||
|
|
4113f6a65d | ||
|
|
f98d744076 | ||
|
|
bb4c293736 | ||
|
|
aa8b1e6efe | ||
|
|
0cb2e8ec2e | ||
|
|
0e96753ccb | ||
|
|
2b2df22d75 | ||
|
|
f65167e3c7 | ||
|
|
8fe2677a56 | ||
|
|
d09a7cf9c8 | ||
|
|
6bf72e5a59 | ||
|
|
7c877ebea2 | ||
|
|
e1983f7bcc | ||
|
|
a5e025a4e5 | ||
|
|
a7682d2639 | ||
|
|
30301c68f1 | ||
|
|
abf980d84e | ||
|
|
8718f55df2 | ||
|
|
d1a3a24527 | ||
|
|
f363b77a07 | ||
|
|
d5899a90c1 | ||
|
|
f1058ea611 | ||
|
|
00279da8d5 | ||
|
|
eda8b53949 | ||
|
|
cfc0cc8f6e | ||
|
|
ab61b2a2d5 | ||
|
|
f79a6ed30a | ||
|
|
4313722b06 | ||
|
|
eec4612a6f | ||
|
|
b2ac893efc | ||
|
|
14e8d9cd04 | ||
|
|
1a6cfd17cb | ||
|
|
3835507e00 | ||
|
|
4536589e2c | ||
|
|
1e39558fbc | ||
|
|
a089cc279b | ||
|
|
84f646dbad | ||
|
|
b9ec473aaa | ||
|
|
b7eb0dff02 | ||
|
|
06f550cc04 | ||
|
|
1752b1aec7 | ||
|
|
67ea640a14 | ||
|
|
f593060007 | ||
|
|
8504eed35c | ||
|
|
8b29b137a8 | ||
|
|
08d3ca6d27 | ||
|
|
e6767f4c0a | ||
|
|
9e5d65706e | ||
|
|
61d7b6da38 | ||
|
|
6affe64ec5 | ||
|
|
ab75718927 | ||
|
|
9e1747e539 | ||
|
|
a7396dc698 | ||
|
|
67699bd24c | ||
|
|
62c72c48a5 | ||
|
|
3944c8437a | ||
|
|
b7d603342e | ||
|
|
6e5db3c292 | ||
|
|
4fb26559f4 | ||
|
|
c366c1d1a3 | ||
|
|
e8cc6a169e | ||
|
|
7d7b6b88ba | ||
|
|
138af5c113 | ||
|
|
b3bcad9ce6 | ||
|
|
cd6f898f8e | ||
|
|
9ef088971b | ||
|
|
e399b1c0b1 | ||
|
|
59bacaf5b4 | ||
|
|
d872a156c1 | ||
|
|
c5e4583762 | ||
|
|
38b9c06138 | ||
|
|
df18a1e917 | ||
|
|
2bc40771ca | ||
|
|
5696c7a5da | ||
|
|
c5f980fc98 | ||
|
|
aebb68724a | ||
|
|
1f2ccd8c1c | ||
|
|
874058d86a | ||
|
|
8fccb80295 | ||
|
|
c9c60575c7 | ||
|
|
7e6ed20b26 | ||
|
|
52c7be4e16 | ||
|
|
36d250fc2b | ||
|
|
84ba0e03de | ||
|
|
7d27c4b546 | ||
|
|
80b2bab0f8 | ||
|
|
79372ced2f | ||
|
|
6fc91962bd | ||
|
|
fb76c23694 | ||
|
|
fc6c852e09 | ||
|
|
82f61ff1d4 | ||
|
|
64052f4f70 | ||
|
|
36c8150f25 | ||
|
|
cb492728ec | ||
|
|
fec02ca733 | ||
|
|
4e01a78286 | ||
|
|
538b39386b | ||
|
|
977aced343 | ||
|
|
83b5753bb5 | ||
|
|
a57c3b691f | ||
|
|
648a374ebb | ||
|
|
c3568e1211 | ||
|
|
6a16d4d55c | ||
|
|
ab2e71cc40 | ||
|
|
f79fe9f7d0 | ||
|
|
6956587106 | ||
|
|
349df56b09 | ||
|
|
e6f082d512 | ||
|
|
87feed1222 | ||
|
|
55c8a66613 | ||
|
|
2e88422c86 | ||
|
|
da841b82d4 | ||
|
|
9256a72c3e | ||
|
|
69120cc961 | ||
|
|
06aaf58f0b | ||
|
|
12e5a586d2 | ||
|
|
0e76ed7077 | ||
|
|
be911a7aa7 | ||
|
|
0556a528f3 | ||
|
|
de789cef66 | ||
|
|
7208d01547 | ||
|
|
46cb0a455d | ||
|
|
300e19b612 | ||
|
|
2666573050 | ||
|
|
5506b46c9d | ||
|
|
7b27cb7a1c | ||
|
|
84a70a1de0 | ||
|
|
1756ec49ad | ||
|
|
7b286b04b1 | ||
|
|
a731e88c78 | ||
|
|
ffd31f2ea7 | ||
|
|
356eeea505 | ||
|
|
34d9469157 | ||
|
|
36b1bf9875 | ||
|
|
7badd19a07 | ||
|
|
f122a9ab28 | ||
|
|
14dbad4dd7 | ||
|
|
cdce9ab50b | ||
|
|
30d3270e1d | ||
|
|
157923decc | ||
|
|
7bbcbc57eb | ||
|
|
9074463f4e | ||
|
|
3ebf4fdff5 | ||
|
|
77e5fa2d2b | ||
|
|
6bd2e65459 | ||
|
|
3363e9ad0c | ||
|
|
d1f0f45525 | ||
|
|
efc1b4a4ae | ||
|
|
a45303d9e6 | ||
|
|
871ff69f56 | ||
|
|
d4b4289c0b | ||
|
|
32af000435 | ||
|
|
64178192ad | ||
|
|
598752956f | ||
|
|
4dce0e5958 | ||
|
|
9f02aef930 | ||
|
|
0c25b0968b | ||
|
|
ddc0bd7202 | ||
|
|
20727e1508 | ||
|
|
3afc1964dc | ||
|
|
914020fd36 | ||
|
|
168a8cd5a6 | ||
|
|
eb94ed7806 | ||
|
|
db6b3ec427 | ||
|
|
32d0cdcea7 | ||
|
|
332fe8c884 | ||
|
|
59f0cf7732 | ||
|
|
b803505287 | ||
|
|
3542062ecd | ||
|
|
824c327a2c | ||
|
|
76a41dffa1 | ||
|
|
65482cad9c | ||
|
|
a17a4c0a3c | ||
|
|
2437cf09d1 | ||
|
|
c4c394845d | ||
|
|
a4d4f9a944 | ||
|
|
5eb086935e | ||
|
|
83a583a33f | ||
|
|
143c2d279b | ||
|
|
08dd596883 | ||
|
|
a4ffcebb0f | ||
|
|
8a14c22056 | ||
|
|
39f7b5284a | ||
|
|
4f58cd255b | ||
|
|
d96d7a533e | ||
|
|
0e59166c64 | ||
|
|
6d8161de73 | ||
|
|
494df64674 | ||
|
|
d057729675 | ||
|
|
b14a323ef8 | ||
|
|
f2b66468ec |
72
.github/workflows/codeql.yml
vendored
Normal file
72
.github/workflows/codeql.yml
vendored
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
# For most projects, this workflow file will not need changing; you simply need
|
||||||
|
# to commit it to your repository.
|
||||||
|
#
|
||||||
|
# You may wish to alter this file to override the set of languages analyzed,
|
||||||
|
# or to provide custom queries or build logic.
|
||||||
|
#
|
||||||
|
# ******** NOTE ********
|
||||||
|
# We have attempted to detect the languages in your repository. Please check
|
||||||
|
# the `language` matrix defined below to confirm you have the correct set of
|
||||||
|
# supported CodeQL languages.
|
||||||
|
#
|
||||||
|
name: "CodeQL"
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ "master", "development" ]
|
||||||
|
pull_request:
|
||||||
|
# The branches below must be a subset of the branches above
|
||||||
|
branches: [ "master", "development" ]
|
||||||
|
schedule:
|
||||||
|
- cron: '23 5 * * 4'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
analyze:
|
||||||
|
name: Analyze
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
actions: read
|
||||||
|
contents: read
|
||||||
|
security-events: write
|
||||||
|
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
language: [ 'cpp', 'python' ]
|
||||||
|
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python', 'ruby' ]
|
||||||
|
# Learn more about CodeQL language support at https://aka.ms/codeql-docs/language-support
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
|
||||||
|
# Initializes the CodeQL tools for scanning.
|
||||||
|
- name: Initialize CodeQL
|
||||||
|
uses: github/codeql-action/init@v2
|
||||||
|
with:
|
||||||
|
languages: ${{ matrix.language }}
|
||||||
|
# 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.
|
||||||
|
# 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
|
||||||
|
# queries: security-extended,security-and-quality
|
||||||
|
|
||||||
|
|
||||||
|
# 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)
|
||||||
|
# - name: Autobuild
|
||||||
|
# uses: github/codeql-action/autobuild@v2
|
||||||
|
|
||||||
|
# ℹ️ 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
|
||||||
|
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
- run: |
|
||||||
|
echo "Run, Build Application using script"
|
||||||
|
./workflows/autobuild.sh
|
||||||
|
|
||||||
|
- name: Perform CodeQL Analysis
|
||||||
|
uses: github/codeql-action/analyze@v2
|
||||||
36
.github/workflows/test.yml
vendored
Normal file
36
.github/workflows/test.yml
vendored
Normal file
@@ -0,0 +1,36 @@
|
|||||||
|
# For most projects, this workflow file will not need changing; you simply need
|
||||||
|
# to commit it to your repository.
|
||||||
|
#
|
||||||
|
# You may wish to alter this file to override the set of languages analyzed,
|
||||||
|
# or to provide custom queries or build logic.
|
||||||
|
#
|
||||||
|
# ******** NOTE ********
|
||||||
|
# We have attempted to detect the languages in your repository. Please check
|
||||||
|
# the `language` matrix defined below to confirm you have the correct set of
|
||||||
|
# supported CodeQL languages.
|
||||||
|
#
|
||||||
|
name: "Emulation and test"
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [ "master", "development" ]
|
||||||
|
pull_request:
|
||||||
|
# The branches below must be a subset of the branches above
|
||||||
|
branches: [ "master", "development" ]
|
||||||
|
schedule:
|
||||||
|
- cron: '23 5 * * 4'
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build:
|
||||||
|
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository and submodules
|
||||||
|
uses: actions/checkout@v3
|
||||||
|
with:
|
||||||
|
submodules: recursive
|
||||||
|
- name: Build in container
|
||||||
|
run: ./tests/build-in-docker.sh
|
||||||
|
- name: Start emulation and test
|
||||||
|
run: ./tests/run-test-in-docker.sh
|
||||||
6
.gitmodules
vendored
6
.gitmodules
vendored
@@ -1,3 +1,3 @@
|
|||||||
[submodule "pico-ccid"]
|
[submodule "pico-hsm-sdk"]
|
||||||
path = pico-ccid
|
path = pico-hsm-sdk
|
||||||
url = https://github.com/polhenarejos/pico-ccid
|
url = ../pico-hsm-sdk
|
||||||
|
|||||||
317
.uncrustify.cfg
Normal file
317
.uncrustify.cfg
Normal file
@@ -0,0 +1,317 @@
|
|||||||
|
#
|
||||||
|
# Uncrustify Configuration File
|
||||||
|
# File Created With UncrustifyX 0.4.3 (252)
|
||||||
|
#
|
||||||
|
|
||||||
|
# Code-Modifying
|
||||||
|
# --------------
|
||||||
|
|
||||||
|
## Braces
|
||||||
|
|
||||||
|
# Braces on single-line do statement
|
||||||
|
mod_full_brace_do = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Braces on single-line else statement
|
||||||
|
mod_full_brace_if = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Braces on single-line for statement
|
||||||
|
mod_full_brace_for = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Braces on single-line while statement
|
||||||
|
mod_full_brace_while = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
## Parentheses
|
||||||
|
|
||||||
|
# Remove unnecessary parentheses on return statement
|
||||||
|
mod_paren_on_return = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Comments
|
||||||
|
# --------
|
||||||
|
|
||||||
|
## Other
|
||||||
|
|
||||||
|
# Remove leading spaces from multi-line comments
|
||||||
|
cmt_multi_check_last = false # boolean (false/true)
|
||||||
|
|
||||||
|
# General
|
||||||
|
# -------
|
||||||
|
|
||||||
|
## Other
|
||||||
|
|
||||||
|
# Input tab size
|
||||||
|
input_tab_size = 4 # number
|
||||||
|
|
||||||
|
# Indentation
|
||||||
|
# -----------
|
||||||
|
|
||||||
|
## Indentation Size
|
||||||
|
|
||||||
|
# Indentation column size
|
||||||
|
indent_columns = 4 # number
|
||||||
|
|
||||||
|
# Indentation size between case and switch
|
||||||
|
indent_switch_case = 4 # number
|
||||||
|
|
||||||
|
## Other
|
||||||
|
|
||||||
|
# Align strings broken by backslash
|
||||||
|
indent_align_string = true # boolean (false/true)
|
||||||
|
|
||||||
|
# Indent with tabs
|
||||||
|
indent_with_tabs = 0 # number
|
||||||
|
|
||||||
|
# Line-Splitting
|
||||||
|
# --------------
|
||||||
|
|
||||||
|
## Splitting
|
||||||
|
|
||||||
|
# Code width
|
||||||
|
code_width = 100 # number
|
||||||
|
|
||||||
|
# Split long for statements at semicolons
|
||||||
|
ls_for_split_full = true # boolean (false/true)
|
||||||
|
|
||||||
|
# Split long function prototypes/calls at commas
|
||||||
|
ls_func_split_full = true # boolean (false/true)
|
||||||
|
|
||||||
|
# Newlines
|
||||||
|
# --------
|
||||||
|
|
||||||
|
## Newline Between
|
||||||
|
|
||||||
|
# Newline between assignment and open brace
|
||||||
|
nl_assign_brace = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Newline between close brace and else
|
||||||
|
nl_brace_else = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Newline between close brace and while
|
||||||
|
nl_brace_while = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Newline between do and open brace
|
||||||
|
nl_do_brace = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Newline between else and open brace
|
||||||
|
nl_else_brace = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Newline between enum and open brace
|
||||||
|
nl_enum_brace = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Newline between for and open brace
|
||||||
|
nl_for_brace = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Newline between function call and open brace
|
||||||
|
nl_fcall_brace = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Newline between function signature and open brace
|
||||||
|
nl_fdef_brace = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Newline between if and open brace
|
||||||
|
nl_if_brace = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Newline between struct and open brace
|
||||||
|
nl_struct_brace = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Newline between switch and open brace
|
||||||
|
nl_switch_brace = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Newline between union and open brace
|
||||||
|
nl_union_brace = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Newline between while and open brace
|
||||||
|
nl_while_brace = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
## Other
|
||||||
|
|
||||||
|
# Newline count at end of file
|
||||||
|
nl_end_of_file_min = 1 # number
|
||||||
|
|
||||||
|
# Newlines at end of file
|
||||||
|
nl_end_of_file = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Newlines at start of file
|
||||||
|
nl_start_of_file = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Spacing
|
||||||
|
# -------
|
||||||
|
|
||||||
|
## Space After
|
||||||
|
|
||||||
|
# Space after address-of operator
|
||||||
|
sp_addr = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space after cast
|
||||||
|
sp_after_cast = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space after comma
|
||||||
|
sp_after_comma = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space after dereference operator
|
||||||
|
sp_deref = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space after final semicolon in empty for statement
|
||||||
|
sp_after_semi_for_empty = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space after invert operator
|
||||||
|
sp_inv = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space after not operator
|
||||||
|
sp_not = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space after pointer star
|
||||||
|
sp_after_ptr_star = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space after pointer star followed by function
|
||||||
|
sp_after_ptr_star_func = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space after semicolon
|
||||||
|
sp_after_semi = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space after semicolon in non-empty for statements
|
||||||
|
sp_after_semi_for = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space after sign in assignment
|
||||||
|
sp_sign = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space after type
|
||||||
|
sp_after_type = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
## Space Around
|
||||||
|
|
||||||
|
# Space around arithmetic operators
|
||||||
|
sp_arith = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space around assignment operator
|
||||||
|
sp_assign = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space around boolean operators
|
||||||
|
sp_bool = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space around compare operators
|
||||||
|
sp_compare = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space around increment/decrement operators
|
||||||
|
sp_incdec = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space around member operators
|
||||||
|
sp_member = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space around preprocessor concatenation operator
|
||||||
|
sp_pp_concat = ignore # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space around ternary condition colon
|
||||||
|
sp_cond_colon = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space around ternary condition question mark
|
||||||
|
sp_cond_question = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
## Space Before
|
||||||
|
|
||||||
|
# Space before backslash-newline at end of line
|
||||||
|
sp_before_nl_cont = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space before case colon
|
||||||
|
sp_before_case_colon = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space before comma
|
||||||
|
sp_before_comma = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space before if/for/switch/while open parenthesis
|
||||||
|
sp_before_sparen = force # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space before pointer star
|
||||||
|
sp_before_ptr_star = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space before semicolon
|
||||||
|
sp_before_semi = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space before semicolon in empty for statement
|
||||||
|
sp_before_semi_for_empty = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space before semicolon in for statements
|
||||||
|
sp_before_semi_for = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
## Space Between
|
||||||
|
|
||||||
|
# Space between __attribute__ and open parenthesis
|
||||||
|
sp_attribute_paren = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space between close brace and else
|
||||||
|
sp_brace_else = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space between close brace and typedef name
|
||||||
|
sp_brace_typedef = force # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space between closing parenthesis and open brace
|
||||||
|
sp_fparen_brace = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space between defined and open parenthesis
|
||||||
|
sp_defined_paren = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space between else and open brace
|
||||||
|
sp_else_brace = force # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space between function name and open parenthesis
|
||||||
|
sp_func_call_paren = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space between function name and open parenthesis in declaration
|
||||||
|
sp_func_proto_paren = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space between function name and open parenthesis in function definition
|
||||||
|
sp_func_def_paren = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space between if/for/switch/while close parenthesis and open brace
|
||||||
|
sp_sparen_brace = force # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space between macro and value
|
||||||
|
sp_macro = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space between macro function close parenthesis and value
|
||||||
|
sp_macro_func = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space between nested parentheses
|
||||||
|
sp_paren_paren = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space between pointer stars
|
||||||
|
sp_between_ptr_star = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space between preprocessor else and comment
|
||||||
|
sp_endif_cmt = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space between return type and function name
|
||||||
|
sp_type_func = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space between sizeof and open parenthesis
|
||||||
|
sp_sizeof_paren = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
## Space Inside
|
||||||
|
|
||||||
|
# Space inside braces
|
||||||
|
sp_inside_braces = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space inside cast parentheses
|
||||||
|
sp_inside_paren_cast = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space inside empty function parentheses
|
||||||
|
sp_inside_fparens = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space inside enum braces
|
||||||
|
sp_inside_braces_enum = add # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space inside function parentheses
|
||||||
|
sp_inside_fparen = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space inside if-condition parentheses
|
||||||
|
sp_inside_sparen = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space inside non-empty square brackets
|
||||||
|
sp_inside_square = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space inside parentheses
|
||||||
|
sp_inside_paren = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space inside parentheses in function type
|
||||||
|
sp_inside_tparen = remove # string (add/force/ignore/remove)
|
||||||
|
|
||||||
|
# Space inside struct/union braces
|
||||||
|
sp_inside_braces_struct = add # string (add/force/ignore/remove)
|
||||||
141
CMakeLists.txt
141
CMakeLists.txt
@@ -17,112 +17,89 @@
|
|||||||
|
|
||||||
cmake_minimum_required(VERSION 3.13)
|
cmake_minimum_required(VERSION 3.13)
|
||||||
|
|
||||||
|
if(ENABLE_EMULATION)
|
||||||
|
else()
|
||||||
include(pico_sdk_import.cmake)
|
include(pico_sdk_import.cmake)
|
||||||
|
endif()
|
||||||
|
|
||||||
project(pico_hsm C CXX ASM)
|
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)
|
||||||
|
else()
|
||||||
pico_sdk_init()
|
pico_sdk_init()
|
||||||
|
endif()
|
||||||
|
|
||||||
add_executable(pico_hsm)
|
add_executable(pico_hsm)
|
||||||
|
|
||||||
if (NOT DEFINED USB_VID)
|
set(SOURCES ${SOURCES}
|
||||||
set(USB_VID 0xFEFF)
|
|
||||||
endif()
|
|
||||||
add_definitions(-DUSB_VID=${USB_VID})
|
|
||||||
if (NOT DEFINED USB_PID)
|
|
||||||
set(USB_PID 0xFCFD)
|
|
||||||
endif()
|
|
||||||
add_definitions(-DUSB_PID=${USB_PID})
|
|
||||||
|
|
||||||
find_package( PythonInterp 3.7 REQUIRED )
|
|
||||||
|
|
||||||
if (NOT EXISTS ${CMAKE_CURRENT_LIST_DIR}/src/hsm/cvcerts.h)
|
|
||||||
execute_process(COMMAND ${PYTHON_EXECUTABLE} ${CMAKE_CURRENT_LIST_DIR}/burn-cvcerts.py ${CMAKE_CURRENT_LIST_DIR})
|
|
||||||
message("Burning CVCert")
|
|
||||||
endif()
|
|
||||||
|
|
||||||
configure_file(${CMAKE_CURRENT_LIST_DIR}/pico-ccid/config/mbedtls_config.h ${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/include/mbedtls COPYONLY)
|
|
||||||
|
|
||||||
target_sources(pico_hsm PUBLIC
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/src/usb/usb.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/src/usb/usb_descriptors.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/src/ccid/ccid2040.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/src/ccid/asn1.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/src/fs/file.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/src/fs/flash.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/src/fs/low_flash.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/src/rng/random.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/src/rng/neug.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/src/ccid/crypto_utils.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/src/ccid/eac.c
|
|
||||||
${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_list_keys.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_read_binary.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_verify.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_reset_retry.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_challenge.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_external_authenticate.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_mse.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_initialize.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_key_domain.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_key_wrap.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_keypair_gen.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_update_ef.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_delete_file.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_change_pin.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_key_gen.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_signature.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_key_unwrap.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_decrypt_asym.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_cipher_sym.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_derive_asym.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_extras.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_general_authenticate.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_session_pin.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_puk_auth.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_pso.c
|
||||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/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/dkek.c
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/kek.c
|
||||||
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm/oid.c
|
||||||
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/aes.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/asn1write.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/bignum.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/cmac.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/cipher.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/cipher_wrap.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/constant_time.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/ecdsa.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/ecdh.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/ecp.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/ecp_curves.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/hkdf.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/md.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/md5.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/oid.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/platform_util.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/ripemd160.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/rsa.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/rsa_alt_helpers.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/sha1.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/sha256.c
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library/sha512.c
|
|
||||||
)
|
)
|
||||||
|
set(USB_ITF_CCID 1)
|
||||||
|
include(pico-hsm-sdk/pico_hsm_sdk_import.cmake)
|
||||||
|
|
||||||
target_include_directories(pico_hsm PUBLIC
|
set(INCLUDES ${INCLUDES}
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/src/fs
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm
|
${CMAKE_CURRENT_LIST_DIR}/src/hsm
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/src/ccid
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/src/rng
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/src/usb
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/include
|
|
||||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/mbedtls/library
|
|
||||||
)
|
)
|
||||||
|
|
||||||
|
target_sources(pico_hsm PUBLIC ${SOURCES})
|
||||||
|
target_include_directories(pico_hsm PUBLIC ${INCLUDES})
|
||||||
|
|
||||||
target_compile_options(pico_hsm PUBLIC
|
target_compile_options(pico_hsm PUBLIC
|
||||||
-Wall
|
-Wall
|
||||||
-Werror
|
-Werror
|
||||||
)
|
)
|
||||||
|
|
||||||
|
if(ENABLE_EMULATION)
|
||||||
|
|
||||||
|
target_compile_options(pico_hsm PUBLIC
|
||||||
|
-fdata-sections
|
||||||
|
-ffunction-sections
|
||||||
|
)
|
||||||
|
if(APPLE)
|
||||||
|
target_link_options(pico_hsm PUBLIC
|
||||||
|
-Wl,-dead_strip
|
||||||
|
)
|
||||||
|
else()
|
||||||
|
target_link_options(pico_hsm PUBLIC
|
||||||
|
-Wl,--gc-sections
|
||||||
|
)
|
||||||
|
endif (APPLE)
|
||||||
|
else()
|
||||||
pico_add_extra_outputs(pico_hsm)
|
pico_add_extra_outputs(pico_hsm)
|
||||||
|
|
||||||
target_link_libraries(pico_hsm PRIVATE 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()
|
||||||
#
|
|
||||||
#project(flash_nuke C CXX ASM)
|
|
||||||
#add_executable(flash_nuke nuke.c)
|
|
||||||
#target_link_libraries(flash_nuke
|
|
||||||
# pico_stdlib
|
|
||||||
# hardware_flash
|
|
||||||
# )
|
|
||||||
#pico_set_binary_type(flash_nuke no_flash)
|
|
||||||
#
|
|
||||||
#pico_add_extra_outputs(flash_nuke)
|
|
||||||
|
|
||||||
#project(memory C CXX ASM)
|
|
||||||
#add_executable(memory memory.c)
|
|
||||||
#target_link_libraries(memory
|
|
||||||
# pico_stdlib
|
|
||||||
# hardware_flash
|
|
||||||
# )
|
|
||||||
#pico_set_binary_type(memory no_flash)
|
|
||||||
#
|
|
||||||
#pico_add_extra_outputs(memory)
|
|
||||||
|
|||||||
54
Dockerfile
Normal file
54
Dockerfile
Normal file
@@ -0,0 +1,54 @@
|
|||||||
|
FROM debian:bullseye
|
||||||
|
ENV DEBIAN_FRONTEND noninteractive
|
||||||
|
RUN apt-get update && apt-get install -y \
|
||||||
|
build-essential \
|
||||||
|
git \
|
||||||
|
cmake \
|
||||||
|
gcc-arm-none-eabi \
|
||||||
|
libnewlib-arm-none-eabi \
|
||||||
|
libstdc++-arm-none-eabi-newlib \
|
||||||
|
python3 \
|
||||||
|
python3-pip
|
||||||
|
|
||||||
|
RUN useradd -m builduser
|
||||||
|
|
||||||
|
USER builduser
|
||||||
|
|
||||||
|
WORKDIR /home/builduser
|
||||||
|
|
||||||
|
VOLUME /home/builduser/release
|
||||||
|
|
||||||
|
ARG VERSION_PICO_SDK 1.4.0
|
||||||
|
|
||||||
|
RUN mkdir -p /home/builduser/Devel/pico
|
||||||
|
RUN cd /home/builduser/Devel/pico \
|
||||||
|
&& git clone https://github.com/raspberrypi/pico-sdk.git \
|
||||||
|
&& cd pico-sdk \
|
||||||
|
&& git checkout $VERSION_PICO_SDK \
|
||||||
|
&& git submodule update --init --recursive
|
||||||
|
|
||||||
|
RUN pip install cryptography
|
||||||
|
|
||||||
|
ARG VERSION_MAJOR 2
|
||||||
|
ARG VERSION_MINOR 6
|
||||||
|
|
||||||
|
RUN cd /home/builduser \
|
||||||
|
&& git clone https://github.com/polhenarejos/pico-hsm.git \
|
||||||
|
&& cd pico-hsm \
|
||||||
|
&& git checkout v${VERSION_MAJOR}.${VERSION_MINOR} \
|
||||||
|
&& git submodule update --init --recursive \
|
||||||
|
&& mkdir build_release
|
||||||
|
|
||||||
|
ENV PICO_SDK_PATH /home/builduser/Devel/pico/pico-sdk
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
ARG USB_VID 0xfeff
|
||||||
|
ARG USB_PID 0xfcfd
|
||||||
|
|
||||||
|
ARG PICO_BOARD waveshare_rp2040_zero
|
||||||
|
|
||||||
|
RUN cd /home/builduser/pico-hsm \
|
||||||
|
&& cd build_release \
|
||||||
|
&& cmake .. -DPICO_BOARD=$PICO_BOARD -DUSB_VID=${USB_VID} -DUSB_PID=${USB_PID} \
|
||||||
|
&& make -kj20
|
||||||
114
README.md
114
README.md
@@ -2,110 +2,130 @@
|
|||||||
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 is a project to create a Hardware Security Module (HSM) with a Raspberry Pico. It converts your Pico board into a HSM which is able to generate and store private keys, encrypt or decrypt with AES or signing data without to disclose the private key. In detail, the private key never leaves the board and it cannot be retrieved as it is encrypted in the flash memory.
|
||||||
|
|
||||||
## Capabilities
|
## 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 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.
|
||||||
**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 from 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 in place for 1024, 2048, 3072 and 4096 bits. Private keys never leave the device.
|
||||||
|
|
||||||
### ECDSA key generation from 192 to 521 bits
|
### > ECDSA key generation from 192 to 521 bits
|
||||||
ECDSA key generation in place for different curves, from 192 to 521 bits.
|
ECDSA key generation in place for different curves, from 192 to 521 bits.
|
||||||
|
|
||||||
### ECC curves
|
### > ECC curves
|
||||||
It supports secp192r1, secp256r1, secp384r1, secp521r1, brainpoolP256r1, brainpoolP384r1, brainpoolP512r1, secp192k1 (insecure), secp256k1 curves.
|
It supports secp192r1, secp256r1, secp384r1, secp521r1, brainpoolP256r1, brainpoolP384r1, brainpoolP512r1, secp192k1 (insecure), secp256k1 curves. Also Curve25519 and Curve448.
|
||||||
|
|
||||||
### SHA1, SHA224, SHA256, SHA384, SHA512 digests
|
### > SHA1, SHA224, SHA256, SHA384, SHA512 digests
|
||||||
ECDSA and RSA signature can be combined with SHA digest in place.
|
ECDSA and RSA signature can be combined with SHA digest in place.
|
||||||
|
|
||||||
### Multiple RSA signature algorithms
|
### > Multiple RSA signature algorithms
|
||||||
It supports RSA-PSS, RSA-PKCS and raw RSA signatures.
|
It supports RSA-PSS, RSA-PKCS and raw RSA signatures.
|
||||||
|
|
||||||
### ECDSA raw and hash signature
|
### > ECDSA raw and hash signature
|
||||||
ECDSA signatures can be in raw or pre-hashed formats.
|
ECDSA signatures can be in raw or pre-hashed formats.
|
||||||
|
|
||||||
### ECDH key derivation
|
### > ECDH key derivation
|
||||||
It supports the calculation of shared secrets with ECDH algorithm.
|
It supports the calculation of shared secrets with ECDH algorithm.
|
||||||
|
|
||||||
### EC private key derivation
|
### > EC private key derivation
|
||||||
It allows ECDSA key derivation.[^1]
|
It allows ECDSA key derivation.[^1]
|
||||||
|
|
||||||
### RSA-OEP and RSA-X-509 decryption
|
### > RSA-OEP and RSA-X-509 decryption
|
||||||
It allows private decryption in place with RSA-OEP and RSA-X-509 algorithms.
|
It allows private decryption in place with RSA-OEP and RSA-X-509 algorithms.
|
||||||
|
|
||||||
### AES key generation
|
### > AES key generation
|
||||||
It supports AES key generation in place with keys of 128, 192 and 256 bits.
|
It supports AES key generation in place with keys of 128, 192 and 256 bits.
|
||||||
|
|
||||||
### AES-CBC encryption/decryption
|
### > AES-CBC encryption/decryption
|
||||||
AES encryption and decryption is performed in place.
|
AES encryption and decryption is performed in place.
|
||||||
|
|
||||||
### CMAC
|
### > CMAC
|
||||||
It supports AES-CMAC authentication.[^1]
|
It supports AES-CMAC authentication.[^1]
|
||||||
|
|
||||||
### AES derivation
|
### > AES derivation
|
||||||
It supports AES secret key derivation.[^1]
|
It 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 cannot be used without prior PIN authentication. It supports alphanumeric PIN.
|
||||||
|
|
||||||
### PKCS11 compliant interface
|
### > PKCS11 compliant interface
|
||||||
The module can be interfaced with PKCS11 standard.
|
The module can be interfaced with PKCS11 standard.
|
||||||
|
|
||||||
### HRNG (hardware random number generator)
|
### > HRNG (hardware random number generator)
|
||||||
It contains a harware random number generator properly modeled to guarantee maximum entropy.
|
It contains a harware random number generator properly modeled to guarantee 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.
|
It supports DKEK share imports. DKEK are used to wrap, unwrap and encrypt private and secret keys in the device.
|
||||||
|
|
||||||
### DKEK n-of-m threshold scheme
|
### > 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.
|
It supports a n-of-m threshold scheme to minimize outage when a DKEK custodian is not available during the import process.
|
||||||
|
|
||||||
### USB/CCID support with OpenSC, openssl, etc.
|
### > USB/CCID support with OpenSC, openssl, etc.
|
||||||
Pico HSM has a full USB CCID stack to communicate with the host via OpenSC and PCSC. It allows the use of frontend applications such as OpenSSL via PKCS11 module.
|
Pico HSM has a full USB CCID stack to communicate with the host via OpenSC and PCSC. It allows the use of frontend applications such as OpenSSL via PKCS11 module.
|
||||||
|
|
||||||
### Extended APDU support
|
### > Extended APDU support
|
||||||
It supports extended APDU packets, which allows up to 65535 bytes.
|
It supports extended APDU packets, which allows up to 65535 bytes.
|
||||||
|
|
||||||
### CVC certificates
|
### > CV Certificates
|
||||||
Pico HSM manipulates CVC certificates and requests to minimize the storage of internal certificates.
|
Pico HSM manipulates CVC certificates and requests to minimize the storage of internal certificates.
|
||||||
|
|
||||||
### 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.
|
Every generated key is attached to a certificate, signed by an external PKI to ensure that a particular key is effectively generated by this specific device.
|
||||||
|
|
||||||
### Import external private keys and certificates
|
### > Import external private keys and certificates
|
||||||
It allows private key and certificates import via WKY or PKCS#12 files.[^2][^3]
|
It allows private key and certificates import via WKY or PKCS#12 files.[^2][^3]
|
||||||
|
|
||||||
### Tranport PIN
|
### > Tranport 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.
|
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.
|
||||||
|
|
||||||
### 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.
|
It allows the use of BOOTSEL button to confirm operations with private/secret keys, such as signatures and decryption. When a private/secret key is loaded, the user has 15 seconds to press the button to confirm the operation.
|
||||||
This feature protects the user from unwanted uses from background applications that may sign data without user notice.
|
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.
|
It allows the storage of arbitrary files with binary data.
|
||||||
|
|
||||||
### Real time clock (RTC)
|
### > Real time clock (RTC)
|
||||||
Pico HSM has a RTC with external datetime setting and getting.
|
Pico HSM has a RTC with external datetime setting and getting.
|
||||||
|
|
||||||
### Secure Messaging (secure channel)
|
### > Secure Messaging (secure channel)
|
||||||
Pico HSM supports secure channel, where the data packets between the host and device are encrypted to avoid man-in-the-middle attacks.
|
Pico HSM supports secure channel, where the data packets between the host and device are encrypted to avoid man-in-the-middle attacks.
|
||||||
|
|
||||||
### Session PIN
|
### > 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 the session opening to avoid the systemmatic use of PIN.
|
||||||
|
|
||||||
### PKI CVCert remote issuing for Secure Message
|
### > PKI CVCert remote issuing for Secure Message
|
||||||
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.
|
Key domains are domains to store separate private/secret keys. Each domain is protected by a DKEK, independent from the other domains. Private/secret keys can be generated in different key domains to be used with separated DKEK.
|
||||||
Therefore, a single device may contain different domains with independent keys.
|
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.
|
A key usage counter is a counter that is reduced by 1 everytime that the private/secret key is used for signing, decrypting, derivation, etc. When it reaches 0, the key is disabled and cannot be used anymore.
|
||||||
|
|
||||||
Key usage can also be used to perform and auditory and track the usage of a particular key.
|
Key usage can also be used to perform and auditory and track the usage of a particular key.
|
||||||
|
|
||||||
|
### > Public Key Authentication
|
||||||
|
Public Key Authentication (PKA) allows to authenticate by using a secondary device with a private key and a registered public key in the primary device. A challenge is generated by the primary Pico HSM and given to the secondary for signature. The secondary device signs the challenge and returns the signature. Then, the primary device verifies the signature with the registered public key and if it is valid, it grants full access, as normal PIN authentication.
|
||||||
|
|
||||||
|
In PKA, the PIN is used for protecting the 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
|
||||||
|
An extra layer can be added to the device by adding a private key stored on the computer to lock that Pico HSM to the specific computer. The content will be completely encrypted with a private key only available from a specific computer.
|
||||||
|
|
||||||
|
### > ChaCha20-Poly1305
|
||||||
|
This is a novel fast and efficient symmetric encryption algorithm. Similarly to AES, it can be used to cipher your private data.
|
||||||
|
|
||||||
|
### > X25519 and X448
|
||||||
|
Both cruves Curve25519 and Curve448 are supported for doing DH X25519 and X448. Remember that cannot be used for signing.
|
||||||
|
|
||||||
|
### > Key Derivation Functions: HKDF, PBKDF2 and X963-KDF
|
||||||
|
It supports symmetric key derivations from different standards and RFC.
|
||||||
|
|
||||||
|
### > HMAC
|
||||||
|
It supports performing HMAC from a secret key on a arbitrary data with SHA digest algorithm.
|
||||||
|
|
||||||
[^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 the DKEK shares are available during the import process.
|
||||||
@@ -140,6 +160,30 @@ Note that `PICO_BOARD`, `USB_VID` and `USB_PID` are optional. If not provided, `
|
|||||||
|
|
||||||
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.
|
After `make` ends, the binary file `pico_hsm.uf2` will be generated. Put your pico board into loading mode, by pushing `BOOTSEL` button while pluging on, and copy the UF2 to the new fresh usb mass storage Pico device. Once copied, the pico mass storage will be disconnected automatically and the pico board will reset with the new firmware. A blinking led will indicate the device is ready to work.
|
||||||
|
|
||||||
|
### Docker
|
||||||
|
Independent from your Linux distribution or when using another OS that supports Docker, you could build a specific pico-hsm version in a Linux container.
|
||||||
|
|
||||||
|
|
||||||
|
```
|
||||||
|
sudo docker build \
|
||||||
|
--build-arg VERSION_PICO_SDK=1.4.0 \
|
||||||
|
--build-arg VERSION_MAJOR=2 \
|
||||||
|
--build-arg VERSION_MINOR=6 \
|
||||||
|
--build-arg PICO_BOARD=waveshare_rp2040_zero \
|
||||||
|
--build-arg USB_VID=0xfeff \
|
||||||
|
--build-arg USB_PID=0xfcfd \
|
||||||
|
-t pico-hsm-builder .
|
||||||
|
|
||||||
|
sudo docker run \
|
||||||
|
--name mybuild \
|
||||||
|
-it pico-hsm-builder \
|
||||||
|
ls -l /home/builduser/pico-hsm/build_release/pico_hsm.uf2
|
||||||
|
|
||||||
|
sudo docker cp mybuild:/home/builduser/pico-hsm/build_release/pico_hsm.uf2 .
|
||||||
|
|
||||||
|
sudo docker rm mybuild
|
||||||
|
```
|
||||||
|
|
||||||
## Usage
|
## 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. It is like having a physical reader with an inserted SIM card.
|
||||||
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:
|
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:
|
||||||
@@ -170,6 +214,8 @@ For storing and retrieving arbitrary data, check [doc/store_data.md](/doc/store_
|
|||||||
|
|
||||||
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 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
|
||||||
Generating EC keys is almost instant. RSA keypair generation takes some time, specially for `3072` and `4096` bits.
|
Generating EC keys is almost instant. RSA keypair generation takes some time, specially for `3072` and `4096` bits.
|
||||||
|
|||||||
@@ -1,12 +1,49 @@
|
|||||||
#!/bin/bash
|
#!/bin/bash
|
||||||
|
|
||||||
VERSION_MAJOR="2"
|
VERSION_MAJOR="3"
|
||||||
VERSION_MINOR="2"
|
VERSION_MINOR="2"
|
||||||
|
|
||||||
rm -rf release/*
|
rm -rf release/*
|
||||||
cd build_release
|
cd build_release
|
||||||
|
|
||||||
for board in adafruit_feather_rp2040 adafruit_itsybitsy_rp2040 adafruit_qtpy_rp2040 adafruit_trinkey_qt2040 arduino_nano_rp2040_connect melopero_shake_rp2040 pimoroni_interstate75 pimoroni_keybow2040 pimoroni_pga2040 pimoroni_picolipo_4mb pimoroni_picolipo_16mb pimoroni_picosystem pimoroni_plasma2040 pimoroni_tiny2040 pybstick26_rp2040 sparkfun_micromod sparkfun_promicro sparkfun_thingplus vgaboard waveshare_rp2040_lcd_0.96 waveshare_rp2040_plus_4mb waveshare_rp2040_plus_16mb waveshare_rp2040_zero
|
for board in adafruit_feather_rp2040 \
|
||||||
|
adafruit_itsybitsy_rp2040 \
|
||||||
|
adafruit_kb2040 \
|
||||||
|
adafruit_macropad_rp2040 \
|
||||||
|
adafruit_qtpy_rp2040 \
|
||||||
|
adafruit_trinkey_qt2040 \
|
||||||
|
arduino_nano_rp2040_connect \
|
||||||
|
datanoisetv_rp2040_dsp \
|
||||||
|
eetree_gamekit_rp2040 \
|
||||||
|
garatronic_pybstick26_rp2040 \
|
||||||
|
melopero_shake_rp2040 \
|
||||||
|
pico \
|
||||||
|
pico_w \
|
||||||
|
pimoroni_badger2040 \
|
||||||
|
pimoroni_interstate75 \
|
||||||
|
pimoroni_keybow2040 \
|
||||||
|
pimoroni_motor2040 \
|
||||||
|
pimoroni_pga2040 \
|
||||||
|
pimoroni_picolipo_4mb \
|
||||||
|
pimoroni_picolipo_16mb \
|
||||||
|
pimoroni_picosystem \
|
||||||
|
pimoroni_plasma2040 \
|
||||||
|
pimoroni_servo2040 \
|
||||||
|
pimoroni_tiny2040 \
|
||||||
|
pimoroni_tiny2040_2mb \
|
||||||
|
seeed_xiao_rp2040 \
|
||||||
|
solderparty_rp2040_stamp \
|
||||||
|
solderparty_rp2040_stamp_carrier \
|
||||||
|
solderparty_rp2040_stamp_round_carrier \
|
||||||
|
sparkfun_micromod \
|
||||||
|
sparkfun_promicro \
|
||||||
|
sparkfun_thingplus \
|
||||||
|
vgaboard \
|
||||||
|
waveshare_rp2040_lcd_0.96 \
|
||||||
|
waveshare_rp2040_plus_4mb \
|
||||||
|
waveshare_rp2040_plus_16mb \
|
||||||
|
waveshare_rp2040_zero \
|
||||||
|
wiznet_w5100s_evb_pico
|
||||||
do
|
do
|
||||||
rm -rf *
|
rm -rf *
|
||||||
PICO_SDK_PATH=~/Devel/pico/pico-sdk cmake .. -DPICO_BOARD=$board
|
PICO_SDK_PATH=~/Devel/pico/pico-sdk cmake .. -DPICO_BOARD=$board
|
||||||
@@ -14,8 +51,3 @@ do
|
|||||||
mv pico_hsm.uf2 ../release/pico_hsm_$board-$VERSION_MAJOR.$VERSION_MINOR.uf2
|
mv pico_hsm.uf2 ../release/pico_hsm_$board-$VERSION_MAJOR.$VERSION_MINOR.uf2
|
||||||
|
|
||||||
done
|
done
|
||||||
|
|
||||||
rm -rf *
|
|
||||||
PICO_SDK_PATH=~/Devel/pico/pico-sdk cmake ..
|
|
||||||
make -kj20
|
|
||||||
mv pico_hsm.uf2 ../release/pico_hsm_pico_generic-$VERSION_MAJOR.$VERSION_MINOR.uf2
|
|
||||||
@@ -1,78 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""
|
|
||||||
Created on Wed Apr 13 20:15:01 2022
|
|
||||||
|
|
||||||
@author: Pol Henarejos
|
|
||||||
"""
|
|
||||||
|
|
||||||
from cryptography.hazmat.backends import default_backend
|
|
||||||
from cryptography.hazmat.primitives import serialization
|
|
||||||
from cryptography.hazmat.primitives.asymmetric import ec
|
|
||||||
import base64
|
|
||||||
import urllib.request
|
|
||||||
import json
|
|
||||||
import sys
|
|
||||||
|
|
||||||
def print_var(v, name):
|
|
||||||
s = '\n'
|
|
||||||
s += "static const unsigned char "+name+"[] = {\n"
|
|
||||||
s += "\t0x{:02x},0x{:02x},\n".format((len(v) & 0xff),((len(v)>> 8) & 0xff))
|
|
||||||
for i in range(len(v)):
|
|
||||||
if (i%16 == 0):
|
|
||||||
s += '\t'
|
|
||||||
s += "0x{:02x}".format((v[i]))
|
|
||||||
if (i < len(v)-1):
|
|
||||||
s += ','
|
|
||||||
if (i%16 == 15):
|
|
||||||
s += '\n'
|
|
||||||
s += '\n'
|
|
||||||
s += '};\n'
|
|
||||||
return s
|
|
||||||
|
|
||||||
def main():
|
|
||||||
args = sys.argv[1:]
|
|
||||||
|
|
||||||
private_key = ec.generate_private_key(ec.SECP192R1(), default_backend())
|
|
||||||
public_key = private_key.public_key()
|
|
||||||
pub_num = public_key.public_numbers()
|
|
||||||
pbk = base64.urlsafe_b64encode(b'\x04'+pub_num.x.to_bytes(24,'big')+pub_num.y.to_bytes(24,'big'))
|
|
||||||
|
|
||||||
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
|
|
||||||
|
|
||||||
data = urllib.parse.urlencode({'pubkey':pbk}).encode()
|
|
||||||
req = urllib.request.Request("https://www.henarejos.me/pico-hsm.php", method='POST', data=data, headers={'User-Agent':user_agent,} ) #The assembled request
|
|
||||||
response = urllib.request.urlopen(req)
|
|
||||||
resp = response.read().decode('utf-8')
|
|
||||||
j = json.loads(resp)
|
|
||||||
cvcert = base64.b64decode(j['cvcert'])
|
|
||||||
|
|
||||||
dica = [
|
|
||||||
0x7f,0x21,0x81,0xc5,0x7f,0x4e,0x81,0x8e,0x5f,0x29,0x01,0x00,0x42,0x0e,0x45,0x53,
|
|
||||||
0x43,0x56,0x43,0x41,0x48,0x53,0x4d,0x30,0x30,0x30,0x30,0x31,0x7f,0x49,0x3f,0x06,
|
|
||||||
0x0a,0x04,0x00,0x7f,0x00,0x07,0x02,0x02,0x02,0x02,0x03,0x86,0x31,0x04,0x93,0x7e,
|
|
||||||
0xdf,0xf1,0xa6,0xd2,0x40,0x7e,0xb4,0x71,0xb2,0x97,0x50,0xdb,0x7e,0xe1,0x70,0xfb,
|
|
||||||
0x6c,0xcd,0x06,0x47,0x2a,0x3e,0x9c,0x8d,0x59,0x56,0x57,0xbe,0x11,0x11,0x0a,0x08,
|
|
||||||
0x81,0x54,0xed,0x22,0xc0,0x83,0xac,0xa1,0x2e,0x39,0x7b,0xd4,0x65,0x1f,0x5f,0x20,
|
|
||||||
0x0e,0x45,0x53,0x44,0x56,0x43,0x41,0x48,0x53,0x4d,0x30,0x30,0x30,0x30,0x31,0x7f,
|
|
||||||
0x4c,0x12,0x06,0x09,0x04,0x00,0x7f,0x00,0x07,0x03,0x01,0x02,0x02,0x53,0x05,0x80,
|
|
||||||
0x00,0x00,0x00,0x04,0x5f,0x25,0x06,0x02,0x02,0x00,0x03,0x02,0x07,0x5f,0x24,0x06,
|
|
||||||
0x02,0x05,0x01,0x02,0x03,0x01,0x5f,0x37,0x30,0x8b,0xb2,0x01,0xb6,0x24,0xfe,0xe5,
|
|
||||||
0x4e,0x65,0x3a,0x02,0xa2,0xb2,0x27,0x2d,0x3d,0xb4,0xb0,0xc9,0xdd,0xbf,0x10,0x6d,
|
|
||||||
0x99,0x49,0x46,0xd6,0xd0,0x72,0xc1,0xf3,0x4c,0xab,0x4f,0x32,0x14,0x7c,0xb0,0x99,
|
|
||||||
0xb7,0x33,0x70,0xd6,0x00,0xff,0x73,0x0c,0x5d
|
|
||||||
]
|
|
||||||
|
|
||||||
s = '#ifndef _CVCERTS_H_\n#define _CVCERTS_H_\n'
|
|
||||||
s += print_var(dica,'dica')
|
|
||||||
s += print_var(cvcert,'termca')
|
|
||||||
|
|
||||||
pvk = private_key.private_numbers().private_value.to_bytes(24,'big')
|
|
||||||
s += print_var(pvk,'termca_pk')
|
|
||||||
s += '\n#endif\n'
|
|
||||||
f = open(args[0] + '/src/hsm/cvcerts.h','w')
|
|
||||||
f.write(s)
|
|
||||||
f.close()
|
|
||||||
|
|
||||||
if __name__ == '__main__':
|
|
||||||
main()
|
|
||||||
@@ -60,6 +60,10 @@ Pico HSM support initialize options, such as setting Transport PIN or reset retr
|
|||||||
|
|
||||||
To specify a set of options, the `XX` parameter shall be set to `06`. The data parameter shall be 1 byte, where the options are combined with the or operand `|`. The length `YY` shall be set to `01`.
|
To specify a set of options, the `XX` parameter shall be set to `06`. The data parameter shall be 1 byte, where the options are combined with the or operand `|`. The length `YY` shall be set to `01`.
|
||||||
|
|
||||||
|
Available options (counting from LSB):
|
||||||
|
- Bit `0`: enable/disable press-to-confirm button.
|
||||||
|
- Bit `1`: enable/disable key usage counter for all keys.
|
||||||
|
|
||||||
### Press-to-confirm button
|
### Press-to-confirm button
|
||||||
Press-to-confirm button offers an extra security layer by requiring the user confirmation everytime that a private/secret key is loaded. This avoids ghost applications thay may perform hidden opperations without noticing the user, such as signing or decrypting. Pico HSM will inform the user that is awaiting for a confirmation by making almost a fixed Led blink.
|
Press-to-confirm button offers an extra security layer by requiring the user confirmation everytime that a private/secret key is loaded. This avoids ghost applications thay may perform hidden opperations without noticing the user, such as signing or decrypting. Pico HSM will inform the user that is awaiting for a confirmation by making almost a fixed Led blink.
|
||||||
|
|
||||||
@@ -89,3 +93,23 @@ Pico HSM supports a key usage counter to audit the usage of a particular key. Fo
|
|||||||
This option is disabled by default. When enabled, each generated key in the device is attached to a counter, starting at `2^32-1` (`FFFFFFFEh`). Therefore, it allows to count how many times a key is used for signing or decryption.
|
This option is disabled by default. When enabled, each generated key in the device is attached to a counter, starting at `2^32-1` (`FFFFFFFEh`). Therefore, it allows to count how many times a key is used for signing or decryption.
|
||||||
|
|
||||||
The counter can be viewed by using the SCS3 tool. More info at [doc/scs3.md](/doc/scs3.md).
|
The counter can be viewed by using the SCS3 tool. More info at [doc/scs3.md](/doc/scs3.md).
|
||||||
|
|
||||||
|
This feature is disabled by default but can be enabled rapidly by setting the 2nd LSB bit to 1:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ opensc-tool -s 806406000102
|
||||||
|
Using reader with a card: Free Software Initiative of Japan Gnuk
|
||||||
|
Sending: 80 64 06 00 01 01
|
||||||
|
Received (SW1=0x90, SW2=0x00)
|
||||||
|
```
|
||||||
|
|
||||||
|
At this moment, when a private/secret key is loaded, the Pico HSM will wait for the pressed BOOTSEL button to confirm the operation.
|
||||||
|
|
||||||
|
To disable, the LSB bit must be set to 0:
|
||||||
|
|
||||||
|
```
|
||||||
|
$ opensc-tool -s 806406000100
|
||||||
|
Using reader with a card: Free Software Initiative of Japan Gnuk
|
||||||
|
Sending: 80 64 06 00 01 00
|
||||||
|
Received (SW1=0x90, SW2=0x00)
|
||||||
|
```
|
||||||
|
|||||||
97
doc/public_key_authentication.md
Normal file
97
doc/public_key_authentication.md
Normal file
@@ -0,0 +1,97 @@
|
|||||||
|
# Public Key Authentication
|
||||||
|
|
||||||
|
Public Key Authentication (PKA) is a mechanism to authenticate a legit user without introducing any PIN (see Notes below). The authentication is performed by signing a challenge and checking the signature result.
|
||||||
|
|
||||||
|
1. A Pico HSM #A contains a private key, whose public key will be used for authentication.
|
||||||
|
2. The public key of #A is registered into a second Pico HSM #B.
|
||||||
|
3. When a user wants to login into #B, #B generates a challenge that is passed to #A for signature.
|
||||||
|
4. #A signs the challenge and returns the signature.
|
||||||
|
5. #B verifies the signature against the challenge with the public key of #A, previously registered.
|
||||||
|
6. If the signature is valid, #B grants access to the user.
|
||||||
|
|
||||||
|
To enable PKA, the device must be initialized beforehand. In case the device has secret/private keys, all shall be exported and reimported when the set up is finished.
|
||||||
|
|
||||||
|
## Requirements
|
||||||
|
|
||||||
|
To take advantage of PKA, the following is required:
|
||||||
|
|
||||||
|
1. Two Pico HSM: one will be used only for authentication (it can be any device able to generate a private key and sign arbitrary data).
|
||||||
|
2. [SCS3](/doc/scs3.md "SCS3") tool to authenticate the user. At this time, OpenSC does not support PKA, only initialization.
|
||||||
|
3. A secret key of ECC 256 bits.
|
||||||
|
|
||||||
|
## Usage
|
||||||
|
|
||||||
|
Before using SCS3, it must be patched [scs3.patch.txt](https://github.com/polhenarejos/pico-hsm/files/8890050/scs3.patch.txt). See [SCS3](/doc/scs3.md "SCS3") for further details.
|
||||||
|
|
||||||
|
### Generate the authentication key
|
||||||
|
|
||||||
|
On a secondary device, generate a private key, on the ECC 256 bits (`brainpoolP256r1` or `secp192r1`). Label it with an easy name, such as "Authentication".
|
||||||
|
|
||||||
|
<img width="1037" src="https://user-images.githubusercontent.com/55573252/173353764-4620ece4-0d82-4a23-a153-99bf912621a7.png">
|
||||||
|
|
||||||
|
Once finished, export the public key.
|
||||||
|
|
||||||
|
<img width="350" src="https://user-images.githubusercontent.com/55573252/173353732-63f40572-a42f-4e5c-a9ab-6e52a083956b.png">
|
||||||
|
|
||||||
|
### Initialization
|
||||||
|
|
||||||
|
On the primary device, initialize it. When prompting for an authentication mechanism, select "Public Key Authentication".
|
||||||
|
|
||||||
|
<img width="412" src="https://user-images.githubusercontent.com/55573252/173353661-17caf6db-0c76-4903-9b70-5afa79f5ae54.png"><img width="1037" alt="Captura de Pantalla 2022-06-13 a les 12 14 48" src="https://user-images.githubusercontent.com/55573252/173353822-310219dc-7c7d-4ece-9fd9-c7835c2688df.png">
|
||||||
|
|
||||||
|
Once finished, register the exported public key. A message of `0 authenticated public key(s) in 1 of 1 scheme` will appear if it is properly registered.
|
||||||
|
|
||||||
|
<img width="342" src="https://user-images.githubusercontent.com/55573252/173353917-f3f99405-c7ff-43ce-8914-6f3b713df952.png"><img width="1037" alt="Captura de Pantalla 2022-06-13 a les 12 16 17" src="https://user-images.githubusercontent.com/55573252/173353946-ee7eacf9-cead-4804-ac7a-57848f7c822b.png">
|
||||||
|
|
||||||
|
### Authentication
|
||||||
|
|
||||||
|
Plug the secondary device that stores the private key (do not load the device in the SCS3 tool) and initiate the public key authentication.
|
||||||
|
|
||||||
|
<img width="321" src="https://user-images.githubusercontent.com/55573252/173353998-8f418ec6-d90d-4168-801f-51008c78824d.png">
|
||||||
|
|
||||||
|
Select the secondary card and the Authentication private key (or the name you labeled it).
|
||||||
|
|
||||||
|
<img width="435" src="https://user-images.githubusercontent.com/55573252/173354044-50163113-829e-4d80-bbda-7b589849af73.png">
|
||||||
|
|
||||||
|
Introduce the PIN of the secondary device.
|
||||||
|
|
||||||
|
If the private key matches with the registered public key, the primary device will grant access and it will display `User PIN authenticated (9000)` (despite no PIN is provided).
|
||||||
|
|
||||||
|
From now on, you have full access and can operate normally with the primary device.
|
||||||
|
|
||||||
|
## Notes on DKEK
|
||||||
|
|
||||||
|
Pico HSM uses the PIN to protect the DKEK, which is lately used to protect private/secret keys and wrap/unwrap. However, when PKA is enabled, the authentication is not performed by introducing any PIN.
|
||||||
|
Authenticated privileges are granted when PKA succeeds, regardless of PIN, which is optional.
|
||||||
|
|
||||||
|
Nevertheless, **it is extremely recommended to combine PKA with PIN**. Note that when combined, only PKA grants authenticated privileges. Therefore, if both schemes are setup, it is necessary to unlock the DKEK with PIN verification.
|
||||||
|
Otherwise, it will not be possible to operate with private/secret keys despite the user will be logged in.
|
||||||
|
|
||||||
|
With this scheme, multiple custodians may authenticate the device individually and remotely and, when fully authenticated, the master user can unlock the DKEK with the PIN.
|
||||||
|
|
||||||
|
Moreover, with this approach the device is kept safe and neither the DKEK nor the private/secret keys are stored in plain text in the device.
|
||||||
|
Even though the flash memory is dumped by an attacker, it will not be possible to decipher any sensitive data or key.
|
||||||
|
|
||||||
|
Initialization of the device with PKA **and** PIN can be achieved with SCS3 or OpenSC:
|
||||||
|
|
||||||
|
**Note:** do not import any DKEK share or DKEK operation before PKA and PIN setup.
|
||||||
|
|
||||||
|
### With OpenSC
|
||||||
|
|
||||||
|
Use the following command (or similar), which accepts the use of PIN parameter **and** PKA configuration:
|
||||||
|
|
||||||
|
```
|
||||||
|
sc-hsm-tool -X --so-pin 1234567890123456 --pin 648219 -K 1 -n 1 -s 1
|
||||||
|
```
|
||||||
|
|
||||||
|
and PKA and PIN are enabled, jointly with DKEK protection.
|
||||||
|
|
||||||
|
### With SCS3
|
||||||
|
|
||||||
|
Unfortunately, SCS3 does not allow to initialize the device with PKA and PIN at the same time, though it can be achieved in separated steps:
|
||||||
|
|
||||||
|
1. Initialize the device with PKA. When done, the PIN will not be initialized but it will advice that 3 attemps can be performed.
|
||||||
|
2. There is NO default PIN. So, DO NOT attempt to log in yet. A reset PIN shall be requested.
|
||||||
|
3. Click on ``Reset User-PIN``, introduce the SO-PIN configured during the initialization and introduce the desired User-PIN.
|
||||||
|
|
||||||
|
When done, the device will be configured with PIN **and** PKA.
|
||||||
36
doc/scs3.md
36
doc/scs3.md
@@ -1,5 +1,11 @@
|
|||||||
# SCS3 tool
|
# SCS3 tool
|
||||||
|
|
||||||
|
SCS3 tool is a specific tool developed by CardContact to manage HSM. Thanks to its interface, Pico HSM can be enhanced with more advanced functionalities, not present in the PKCS11 module:
|
||||||
|
|
||||||
|
- Import PKCS12 private keys and certificates.
|
||||||
|
- Import private keys and certificates from other Pico HSM devices in WKY format.
|
||||||
|
-
|
||||||
|
|
||||||
Unfortunately, there is no pkcs11 tool or equivalent capable to perform the import. Since it uses the SC-HSM driver, it also supports the communication with the [SCS3 tool](https://www.openscdp.org/scsh3/ "SCS3 tool"). It can be downloaded from [here](https://www.openscdp.org/scsh3/download.html "here").
|
Unfortunately, there is no pkcs11 tool or equivalent capable to perform the import. Since it uses the SC-HSM driver, it also supports the communication with the [SCS3 tool](https://www.openscdp.org/scsh3/ "SCS3 tool"). It can be downloaded from [here](https://www.openscdp.org/scsh3/download.html "here").
|
||||||
|
|
||||||
However, SCS3 only works with those HSM manufactured by CardContact. The check is performed by means of trust store against the manufacturing certificates. For obvious reasons, these certificates can only be signed with the private keys of the Certificate Authorities listed in the trust store.
|
However, SCS3 only works with those HSM manufactured by CardContact. The check is performed by means of trust store against the manufacturing certificates. For obvious reasons, these certificates can only be signed with the private keys of the Certificate Authorities listed in the trust store.
|
||||||
@@ -7,7 +13,7 @@ However, SCS3 only works with those HSM manufactured by CardContact. The check i
|
|||||||
Pico HSM is shipped with its own CA certificates. To load this certificate onto the trust store of SCS3, the following line has to be appended to `SmartCardHSM.rootCerts` variable, near line `235` in the file `scs3/scsh/sc-hsm/SmartCardHSM.js`.
|
Pico HSM is shipped with its own CA certificates. To load this certificate onto the trust store of SCS3, the following line has to be appended to `SmartCardHSM.rootCerts` variable, near line `235` in the file `scs3/scsh/sc-hsm/SmartCardHSM.js`.
|
||||||
|
|
||||||
```
|
```
|
||||||
ESCVCAHSM00001: new CVC(new ByteString("7F218201657F4E82012D5F290100420E45534356434148534D30303030317F4981DD060A04007F000702020202038118FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF8218FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC831864210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1843104188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF101207192B95FFC8DA78631011ED6B24CDD573F977A11E7948118518FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831863104088FCDFCCE87EDD285920615E651D76452D857ECBB408C327ADB48A2A514C1C9BD77CC9783607A741493A742744AD1738701015F200E45534356434148534D30303030317F4C12060904007F0007030102025305C0000000045F25060202000302065F24060300010203015F37307297777664B60C57A2C45E7BFD12E520143EDE9038BFB302739106F2730D760665D74649910C519089848D4FB6E51340", HEX))
|
ESPICOHSMCA00001: new CVC(new ByteString("7F218201BA7F4E8201725F290100421045535049434F48534D434130303030317F4982011D060A04007F000702020202038120FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF8220FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC83205AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B8441046B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C2964FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F58520FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC6325518641046A82C0A4FEAF41D6A1336AE7E992D81AD4F827929145DD0D777E1AB63D7E3325C8F7DAC0F74B6EAE13A72F6366777EC133AC5C28F456868E5F2C315044EB54EF8701015F201045535049434F48534D434130303030317F4C12060904007F0007030102025305C0000000005F25060202000801085F24060203000801085F3740601E974F57DDE060875FE6121AEF5BC02E10FC655311C7A32CA822FD18E53A80298EDC56E0D5EBF38FB470DC12987B1600AE91A0ADB5B22C4D80080782E278AD", HEX))
|
||||||
```
|
```
|
||||||
|
|
||||||
Therefore, the whole variable becomes:
|
Therefore, the whole variable becomes:
|
||||||
@@ -16,18 +22,27 @@ Therefore, the whole variable becomes:
|
|||||||
SmartCardHSM.rootCerts = {
|
SmartCardHSM.rootCerts = {
|
||||||
DESRCACC100001: new CVC(new ByteString("7F218201B47F4E82016C5F290100420E44455352434143433130303030317F4982011D060A04007F000702020202038120A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E537782207D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9832026DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B68441048BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F0469978520A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A78641046D025A8026CDBA245F10DF1B72E9880FFF746DAB40A43A3D5C6BEBF27707C30F6DEA72430EE3287B0665C1EAA6EAA4FA26C46303001983F82BD1AA31E03DA0628701015F200E44455352434143433130303030317F4C10060B2B0601040181C31F0301015301C05F25060102010100095F24060302010100085F37409DBB382B1711D2BAACB0C623D40C6267D0B52BA455C01F56333DC9554810B9B2878DAF9EC3ADA19C7B065D780D6C9C3C2ECEDFD78DEB18AF40778ADF89E861CA", HEX)),
|
DESRCACC100001: new CVC(new ByteString("7F218201B47F4E82016C5F290100420E44455352434143433130303030317F4982011D060A04007F000702020202038120A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E537782207D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9832026DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B68441048BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F0469978520A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A78641046D025A8026CDBA245F10DF1B72E9880FFF746DAB40A43A3D5C6BEBF27707C30F6DEA72430EE3287B0665C1EAA6EAA4FA26C46303001983F82BD1AA31E03DA0628701015F200E44455352434143433130303030317F4C10060B2B0601040181C31F0301015301C05F25060102010100095F24060302010100085F37409DBB382B1711D2BAACB0C623D40C6267D0B52BA455C01F56333DC9554810B9B2878DAF9EC3ADA19C7B065D780D6C9C3C2ECEDFD78DEB18AF40778ADF89E861CA", HEX)),
|
||||||
UTSRCACC100001: new CVC(new ByteString("7F218201B47F4E82016C5F290100420E55545352434143433130303030317F4982011D060A04007F000702020202038120A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E537782207D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9832026DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B68441048BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F0469978520A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7864104A041FEB2FD116B2AD19CA6B7EACD71C9892F941BB88D67DCEEC92501F070011957E22122BA6C2CF5FF02936F482E35A6129CCBBA8E9383836D3106879C408EF08701015F200E55545352434143433130303030317F4C10060B2B0601040181C31F0301015301C05F25060102010100095F24060302010100085F3740914DD0FA00615C44048D1467435400423A4AD1BD37FD98D6DE84FD8037489582325C72956D4FDFABC6EDBA48184A754F37F1BE5142DD1C27D66569308CE19AAF", HEX)),
|
UTSRCACC100001: new CVC(new ByteString("7F218201B47F4E82016C5F290100420E55545352434143433130303030317F4982011D060A04007F000702020202038120A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E537782207D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9832026DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B68441048BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F0469978520A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7864104A041FEB2FD116B2AD19CA6B7EACD71C9892F941BB88D67DCEEC92501F070011957E22122BA6C2CF5FF02936F482E35A6129CCBBA8E9383836D3106879C408EF08701015F200E55545352434143433130303030317F4C10060B2B0601040181C31F0301015301C05F25060102010100095F24060302010100085F3740914DD0FA00615C44048D1467435400423A4AD1BD37FD98D6DE84FD8037489582325C72956D4FDFABC6EDBA48184A754F37F1BE5142DD1C27D66569308CE19AAF", HEX)),
|
||||||
ESCVCAHSM00001: new CVC(new ByteString("7F218201657F4E82012D5F290100420E45534356434148534D30303030317F4981DD060A04007F000702020202038118FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF8218FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC831864210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1843104188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF101207192B95FFC8DA78631011ED6B24CDD573F977A11E7948118518FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831863104088FCDFCCE87EDD285920615E651D76452D857ECBB408C327ADB48A2A514C1C9BD77CC9783607A741493A742744AD1738701015F200E45534356434148534D30303030317F4C12060904007F0007030102025305C0000000045F25060202000302065F24060300010203015F37307297777664B60C57A2C45E7BFD12E520143EDE9038BFB302739106F2730D760665D74649910C519089848D4FB6E51340", HEX))
|
ESPICOHSMCA00001: new CVC(new ByteString("7F218201BA7F4E8201725F290100421045535049434F48534D434130303030317F4982011D060A04007F000702020202038120FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF8220FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC83205AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B8441046B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C2964FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F58520FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC6325518641046A82C0A4FEAF41D6A1336AE7E992D81AD4F827929145DD0D777E1AB63D7E3325C8F7DAC0F74B6EAE13A72F6366777EC133AC5C28F456868E5F2C315044EB54EF8701015F201045535049434F48534D434130303030317F4C12060904007F0007030102025305C0000000005F25060202000801085F24060203000801085F3740601E974F57DDE060875FE6121AEF5BC02E10FC655311C7A32CA822FD18E53A80298EDC56E0D5EBF38FB470DC12987B1600AE91A0ADB5B22C4D80080782E278AD", HEX))
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
After this ammendment, the KeyManager can be invoked (CTRL+M) and it will output something similar to:
|
Similarly, replace the line `1531` in file `scs3/keymanager/keymanager.js` with:
|
||||||
|
|
||||||
|
```
|
||||||
|
assert(devcert.verifyWith(this.crypto, dicacert.getPublicKey(SmartCardHSM.rootCerts.ESPICOHSMCA00001.getPublicKey()), dicacert.getPublicKeyOID()));
|
||||||
|
```
|
||||||
|
|
||||||
|
|
||||||
|
Alternatively, this patch [scs3.patch.txt](https://github.com/polhenarejos/pico-hsm/files/9415877/scs3.patch.txt) can be applied.
|
||||||
|
|
||||||
|
After this ammendment, the program can be started and the KeyManager can be invoked (CTRL+M) and it will output something similar to:
|
||||||
```
|
```
|
||||||
>load("keymanager/keymanager.js");
|
>load("keymanager/keymanager.js");
|
||||||
|
|
||||||
SmartCard-HSM Version 1.6 on JCOP Free memory 217104 byte
|
SmartCard-HSM Version 2.6 on JCOP Free memory 215512 byte
|
||||||
Issuer Certificate : CVC id-AT DV (official domestic) CAR=ESCVCAHSM00001 CHR=ESDVCAHSM00001 CED=27 / de març / 2022 CXD=31 / de desembre / 2025
|
Issuer Certificate : CVC id-AT DV (official domestic) CAR=ESPICOHSMCA00001 CHR=ESPICOHSMDV00001 CED=18 / d’agost / 2022 CXD=14 / de juny / 2023
|
||||||
Device Certificate : CVC id-AT Terminal CAR=ESDVCAHSM00001 CHR=ESTERMHSM00001 CED=27 / de març / 2022 CXD=31 / de desembre / 2023
|
Device Certificate : CVC id-AT Terminal CAR=ESPICOHSMDV00001 CHR=ESPICOHSMTRYZRGW CED=22 / d’agost / 2022 CXD=22 / d’agost / 2023
|
||||||
Default Key Domain : 0F89B400975EDD2D425ABF85F2FBD318779B3D85475E65D4
|
Default Key Domain : 223CD8D8F794889AC163305881BF8C04960BBB8658120491F1C0601F6BF97183
|
||||||
-------------------------------------------------------------------
|
-------------------------------------------------------------------
|
||||||
Please right-click on nodes in the outline to see possible actions.
|
Please right-click on nodes in the outline to see possible actions.
|
||||||
For most operations you will need to authenticate first using a
|
For most operations you will need to authenticate first using a
|
||||||
@@ -37,6 +52,13 @@ mechanism from the User PIN context menu.
|
|||||||
|
|
||||||
The SCS3 tool is ready to import private keys and certificates, wraped in WKY files or in PKCS#12 format. Also, all stored keys can be exported, combined with their respective certificates. Note that the user has to be previously logged in.
|
The SCS3 tool is ready to import private keys and certificates, wraped in WKY files or in PKCS#12 format. Also, all stored keys can be exported, combined with their respective certificates. Note that the user has to be previously logged in.
|
||||||
|
|
||||||
|
## macOS users
|
||||||
|
In macOS, the PCSC must be explicitly specified. Otherwise, the reader will not be found.
|
||||||
|
|
||||||
|
It can be executed in a Terminal via
|
||||||
|
```
|
||||||
|
java -Dsun.security.smartcardio.library=/System/Library/Frameworks/PCSC.framework/Versions/Current/PCSC -Dorg.bouncycastle.asn1.allow_unsafe_integer=true -Djava.library.path=./lib -classpath 'lib/*' de.cardcontact.scdp.scsh3.GUIShell
|
||||||
|
```
|
||||||
## DKEK requirement
|
## DKEK requirement
|
||||||
|
|
||||||
In order to perform the import, private keys must be wrapped with the same DKEK present in the Pico HSM. Thus, the Pico HSM must be previously initialized with at minimum of 1 DKEK share. This share will be used to wrap the private key before import.
|
In order to perform the import, private keys must be wrapped with the same DKEK present in the Pico HSM. Thus, the Pico HSM must be previously initialized with at minimum of 1 DKEK share. This share will be used to wrap the private key before import.
|
||||||
|
|||||||
@@ -22,15 +22,15 @@ init=0
|
|||||||
PIN=648219
|
PIN=648219
|
||||||
```
|
```
|
||||||
`opensc-pkcs11.so` can be replaced by `libsc-hsm-pkcs11.so` if desired.
|
`opensc-pkcs11.so` can be replaced by `libsc-hsm-pkcs11.so` if desired.
|
||||||
* **sc-hsm-tool**: from OpenSC. Used to initialize the device.
|
* **pico-hsm-tool**: Used to initialize the device.
|
||||||
* **opensc-tool**: from OpenSC. Used to list and detect the reader with the HSM.
|
* **opensc-tool**: from OpenSC. Used to list and detect the reader with the HSM.
|
||||||
|
|
||||||
[^1]: `openssl version -a` will return the `OPENSSLDIR`, which contains `openssl.cnf` file and `ENGINESDIR`, which contains the p11 engine.
|
[^1]: `openssl version -a` will return the `OPENSSLDIR`, which contains `openssl.cnf` file and `ENGINESDIR`, which contains the p11 engine.
|
||||||
|
|
||||||
## Initialization
|
## Initialization
|
||||||
The first step is to initialize the HSM:
|
The first step is to initialize the HSM. To do so, use the `pico-hsm-tool.py` in `tools` folder:
|
||||||
```
|
```
|
||||||
$ sc-hsm-tool --initialize --so-pin 3537363231383830 --pin 648219
|
$ python3 pico-hsm-tool.py initialize --so-pin 3537363231383830 --pin 648219
|
||||||
```
|
```
|
||||||
The PIN number is used to manage all private keys in the device. It supports three attemps. After the third PIN failure, it gets blocked.
|
The PIN 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.
|
||||||
|
|||||||
Submodule pico-ccid deleted from fe53f9a729
1
pico-hsm-sdk
Submodule
1
pico-hsm-sdk
Submodule
Submodule pico-hsm-sdk added at 599e5edbd1
34
src/hsm/cmd_challenge.c
Normal file
34
src/hsm/cmd_challenge.c
Normal file
@@ -0,0 +1,34 @@
|
|||||||
|
/*
|
||||||
|
* 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 "random.h"
|
||||||
|
#include "sc_hsm.h"
|
||||||
|
|
||||||
|
uint8_t challenge[256];
|
||||||
|
uint8_t challenge_len = 0;
|
||||||
|
|
||||||
|
int cmd_challenge() {
|
||||||
|
uint8_t *rb = (uint8_t *) random_bytes_get(apdu.ne);
|
||||||
|
if (!rb) {
|
||||||
|
return SW_WRONG_LENGTH();
|
||||||
|
}
|
||||||
|
memcpy(res_APDU, rb, apdu.ne);
|
||||||
|
challenge_len = MIN(apdu.ne, sizeof(challenge));
|
||||||
|
memcpy(challenge, rb, challenge_len);
|
||||||
|
res_APDU_size = apdu.ne;
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
72
src/hsm/cmd_change_pin.c
Normal file
72
src/hsm/cmd_change_pin.c
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
/*
|
||||||
|
* 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 "crypto_utils.h"
|
||||||
|
#include "sc_hsm.h"
|
||||||
|
#include "kek.h"
|
||||||
|
|
||||||
|
int cmd_change_pin() {
|
||||||
|
if (P1(apdu) == 0x0) {
|
||||||
|
if (P2(apdu) == 0x81 || P2(apdu) == 0x88) {
|
||||||
|
file_t *file_pin = NULL;
|
||||||
|
if (P2(apdu) == 0x81) {
|
||||||
|
file_pin = file_pin1;
|
||||||
|
}
|
||||||
|
else if (P2(apdu) == 0x88) {
|
||||||
|
file_pin = file_sopin;
|
||||||
|
}
|
||||||
|
if (!file_pin) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
if (!file_has_data(file_pin)) {
|
||||||
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
uint8_t pin_len = file_read_uint8(file_get_data(file_pin));
|
||||||
|
int r = check_pin(file_pin, apdu.data, pin_len);
|
||||||
|
if (r != 0x9000) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
uint8_t mkek[MKEK_SIZE];
|
||||||
|
r = load_mkek(mkek); //loads the MKEK with old pin
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
//encrypt MKEK with new pin
|
||||||
|
|
||||||
|
if (P2(apdu) == 0x81) {
|
||||||
|
hash_multi(apdu.data + pin_len, apdu.nc - pin_len, session_pin);
|
||||||
|
has_session_pin = true;
|
||||||
|
}
|
||||||
|
else if (P2(apdu) == 0x88) {
|
||||||
|
hash_multi(apdu.data + pin_len, apdu.nc - pin_len, session_sopin);
|
||||||
|
has_session_sopin = true;
|
||||||
|
}
|
||||||
|
r = store_mkek(mkek);
|
||||||
|
release_mkek(mkek);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
uint8_t dhash[33];
|
||||||
|
dhash[0] = apdu.nc - pin_len;
|
||||||
|
double_hash_pin(apdu.data + pin_len, apdu.nc - pin_len, dhash + 1);
|
||||||
|
flash_write_data_to_file(file_pin, dhash, sizeof(dhash));
|
||||||
|
low_flash_available();
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return SW_WRONG_P1P2();
|
||||||
|
}
|
||||||
459
src/hsm/cmd_cipher_sym.c
Normal file
459
src/hsm/cmd_cipher_sym.c
Normal file
@@ -0,0 +1,459 @@
|
|||||||
|
/*
|
||||||
|
* 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 "common.h"
|
||||||
|
#include "mbedtls/aes.h"
|
||||||
|
#include "mbedtls/cmac.h"
|
||||||
|
#include "mbedtls/hkdf.h"
|
||||||
|
#include "mbedtls/chachapoly.h"
|
||||||
|
#include "md_wrap.h"
|
||||||
|
#include "mbedtls/md.h"
|
||||||
|
#include "crypto_utils.h"
|
||||||
|
#include "sc_hsm.h"
|
||||||
|
#include "kek.h"
|
||||||
|
#include "asn1.h"
|
||||||
|
#include "oid.h"
|
||||||
|
#include "mbedtls/pkcs5.h"
|
||||||
|
#include "mbedtls/error.h"
|
||||||
|
#include "mbedtls/asn1.h"
|
||||||
|
#include "mbedtls/cipher.h"
|
||||||
|
#include "mbedtls/oid.h"
|
||||||
|
|
||||||
|
/* This is copied from pkcs5.c Mbedtls */
|
||||||
|
/** Unfortunately it is declared as static, so I cannot call it. **/
|
||||||
|
|
||||||
|
static int pkcs5_parse_pbkdf2_params(const mbedtls_asn1_buf *params,
|
||||||
|
mbedtls_asn1_buf *salt, int *iterations,
|
||||||
|
int *keylen, mbedtls_md_type_t *md_type) {
|
||||||
|
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
|
||||||
|
mbedtls_asn1_buf prf_alg_oid;
|
||||||
|
unsigned char *p = params->p;
|
||||||
|
const unsigned char *end = params->p + params->len;
|
||||||
|
|
||||||
|
if (params->tag != (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)) {
|
||||||
|
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS5_INVALID_FORMAT,
|
||||||
|
MBEDTLS_ERR_ASN1_UNEXPECTED_TAG);
|
||||||
|
}
|
||||||
|
/*
|
||||||
|
* PBKDF2-params ::= SEQUENCE {
|
||||||
|
* salt OCTET STRING,
|
||||||
|
* iterationCount INTEGER,
|
||||||
|
* keyLength INTEGER OPTIONAL
|
||||||
|
* prf AlgorithmIdentifier DEFAULT algid-hmacWithSHA1
|
||||||
|
* }
|
||||||
|
*
|
||||||
|
*/
|
||||||
|
if ((ret = mbedtls_asn1_get_tag(&p, end, &salt->len,
|
||||||
|
MBEDTLS_ASN1_OCTET_STRING)) != 0) {
|
||||||
|
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS5_INVALID_FORMAT, ret);
|
||||||
|
}
|
||||||
|
|
||||||
|
salt->p = p;
|
||||||
|
p += salt->len;
|
||||||
|
|
||||||
|
if ((ret = mbedtls_asn1_get_int(&p, end, iterations)) != 0) {
|
||||||
|
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS5_INVALID_FORMAT, ret);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (p == end) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((ret = mbedtls_asn1_get_int(&p, end, keylen)) != 0) {
|
||||||
|
if (ret != MBEDTLS_ERR_ASN1_UNEXPECTED_TAG) {
|
||||||
|
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS5_INVALID_FORMAT, ret);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (p == end) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((ret = mbedtls_asn1_get_alg_null(&p, end, &prf_alg_oid)) != 0) {
|
||||||
|
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS5_INVALID_FORMAT, ret);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mbedtls_oid_get_md_hmac(&prf_alg_oid, md_type) != 0) {
|
||||||
|
return MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (p != end) {
|
||||||
|
return MBEDTLS_ERROR_ADD(MBEDTLS_ERR_PKCS5_INVALID_FORMAT,
|
||||||
|
MBEDTLS_ERR_ASN1_LENGTH_MISMATCH);
|
||||||
|
}
|
||||||
|
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* Taken from https://github.com/Mbed-TLS/mbedtls/issues/2335 */
|
||||||
|
int mbedtls_ansi_x963_kdf(mbedtls_md_type_t md_type,
|
||||||
|
size_t input_len,
|
||||||
|
uint8_t *input,
|
||||||
|
size_t shared_info_len,
|
||||||
|
uint8_t *shared_info,
|
||||||
|
size_t output_len,
|
||||||
|
uint8_t *output) {
|
||||||
|
mbedtls_md_context_t md_ctx;
|
||||||
|
const mbedtls_md_info_t *md_info = NULL;
|
||||||
|
int hashlen = 0, exit_code = MBEDTLS_ERR_MD_BAD_INPUT_DATA;
|
||||||
|
uint8_t counter_buf[4], tmp_output[64]; //worst case
|
||||||
|
|
||||||
|
mbedtls_md_init(&md_ctx);
|
||||||
|
|
||||||
|
md_info = mbedtls_md_info_from_type(md_type);
|
||||||
|
|
||||||
|
if (md_info == NULL) {
|
||||||
|
return exit_code;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (mbedtls_md_setup(&md_ctx, md_info, 0)) {
|
||||||
|
return exit_code;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input_len + shared_info_len + 4 >= (1ULL << 61) - 1) {
|
||||||
|
return exit_code;
|
||||||
|
}
|
||||||
|
|
||||||
|
// keydatalen equals output_len
|
||||||
|
hashlen = md_info->size;
|
||||||
|
if (output_len >= hashlen * ((1ULL << 32) - 1)) {
|
||||||
|
return exit_code;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0, counter = 1; i < output_len; counter++) {
|
||||||
|
mbedtls_md_starts(&md_ctx);
|
||||||
|
mbedtls_md_update(&md_ctx, input, input_len);
|
||||||
|
|
||||||
|
//TODO: be careful with architecture little vs. big
|
||||||
|
counter_buf[0] = (uint8_t) ((counter >> 24) & 0xff);
|
||||||
|
counter_buf[1] = (uint8_t) ((counter >> 16) & 0xff);
|
||||||
|
counter_buf[2] = (uint8_t) ((counter >> 8) & 0xff);
|
||||||
|
counter_buf[3] = (uint8_t) ((counter >> 0) & 0xff);
|
||||||
|
|
||||||
|
mbedtls_md_update(&md_ctx, counter_buf, 4);
|
||||||
|
|
||||||
|
if (shared_info_len > 0 && shared_info != NULL) {
|
||||||
|
mbedtls_md_update(&md_ctx, shared_info, shared_info_len);
|
||||||
|
}
|
||||||
|
mbedtls_md_finish(&md_ctx, tmp_output);
|
||||||
|
memcpy(&output[i], tmp_output, (output_len - i < hashlen) ? output_len - i : hashlen);
|
||||||
|
i += hashlen;
|
||||||
|
}
|
||||||
|
mbedtls_md_free(&md_ctx);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int cmd_cipher_sym() {
|
||||||
|
int key_id = P1(apdu);
|
||||||
|
int algo = P2(apdu);
|
||||||
|
if (!isUserAuthenticated) {
|
||||||
|
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
|
||||||
|
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
int key_size = file_get_size(ef);
|
||||||
|
uint8_t kdata[32]; //maximum AES key size
|
||||||
|
memcpy(kdata, file_get_data(ef), key_size);
|
||||||
|
if (mkek_decrypt(kdata, key_size) != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
if (algo == ALGO_AES_CBC_ENCRYPT || algo == ALGO_AES_CBC_DECRYPT) {
|
||||||
|
if ((apdu.nc % 16) != 0) {
|
||||||
|
return SW_WRONG_LENGTH();
|
||||||
|
}
|
||||||
|
mbedtls_aes_context aes;
|
||||||
|
mbedtls_aes_init(&aes);
|
||||||
|
uint8_t tmp_iv[IV_SIZE];
|
||||||
|
memset(tmp_iv, 0, sizeof(tmp_iv));
|
||||||
|
if (algo == ALGO_AES_CBC_ENCRYPT) {
|
||||||
|
int r = mbedtls_aes_setkey_enc(&aes, kdata, key_size * 8);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
mbedtls_aes_free(&aes);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
r = mbedtls_aes_crypt_cbc(&aes,
|
||||||
|
MBEDTLS_AES_ENCRYPT,
|
||||||
|
apdu.nc,
|
||||||
|
tmp_iv,
|
||||||
|
apdu.data,
|
||||||
|
res_APDU);
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_aes_free(&aes);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (algo == ALGO_AES_CBC_DECRYPT) {
|
||||||
|
int r = mbedtls_aes_setkey_dec(&aes, kdata, key_size * 8);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
mbedtls_aes_free(&aes);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
r = mbedtls_aes_crypt_cbc(&aes,
|
||||||
|
MBEDTLS_AES_DECRYPT,
|
||||||
|
apdu.nc,
|
||||||
|
tmp_iv,
|
||||||
|
apdu.data,
|
||||||
|
res_APDU);
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_aes_free(&aes);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
res_APDU_size = apdu.nc;
|
||||||
|
mbedtls_aes_free(&aes);
|
||||||
|
}
|
||||||
|
else if (algo == ALGO_AES_CMAC) {
|
||||||
|
const mbedtls_cipher_info_t *cipher_info;
|
||||||
|
if (key_size == 16) {
|
||||||
|
cipher_info = mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_128_ECB);
|
||||||
|
}
|
||||||
|
else if (key_size == 24) {
|
||||||
|
cipher_info = mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_192_ECB);
|
||||||
|
}
|
||||||
|
else if (key_size == 32) {
|
||||||
|
cipher_info = mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_256_ECB);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
int r = mbedtls_cipher_cmac(cipher_info, kdata, key_size * 8, apdu.data, apdu.nc, res_APDU);
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
res_APDU_size = 16;
|
||||||
|
}
|
||||||
|
else if (algo == ALGO_AES_DERIVE) {
|
||||||
|
int r = mbedtls_hkdf(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256),
|
||||||
|
NULL,
|
||||||
|
0,
|
||||||
|
file_get_data(ef),
|
||||||
|
key_size,
|
||||||
|
apdu.data,
|
||||||
|
apdu.nc,
|
||||||
|
res_APDU,
|
||||||
|
apdu.nc);
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
res_APDU_size = apdu.nc;
|
||||||
|
}
|
||||||
|
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;
|
||||||
|
uint8_t *oid = NULL, *aad = NULL, *iv = NULL, *enc = NULL;
|
||||||
|
if (!asn1_find_tag(apdu.data, apdu.nc, 0x6, &oid_len,
|
||||||
|
&oid) || oid_len == 0 || oid == NULL) {
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
asn1_find_tag(apdu.data, apdu.nc, 0x81, &enc_len, &enc);
|
||||||
|
asn1_find_tag(apdu.data, apdu.nc, 0x82, &iv_len, &iv);
|
||||||
|
asn1_find_tag(apdu.data, apdu.nc, 0x83, &aad_len, &aad);
|
||||||
|
uint8_t tmp_iv[16];
|
||||||
|
memset(tmp_iv, 0, sizeof(tmp_iv));
|
||||||
|
if (memcmp(oid, OID_CHACHA20_POLY1305, oid_len) == 0) {
|
||||||
|
if (algo == ALGO_EXT_CIPHER_DECRYPT && enc_len < 16) {
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
int r = 0;
|
||||||
|
mbedtls_chachapoly_context ctx;
|
||||||
|
mbedtls_chachapoly_init(&ctx);
|
||||||
|
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
||||||
|
r = mbedtls_chachapoly_encrypt_and_tag(&ctx,
|
||||||
|
enc_len,
|
||||||
|
iv ? iv : tmp_iv,
|
||||||
|
aad,
|
||||||
|
aad_len,
|
||||||
|
enc,
|
||||||
|
res_APDU,
|
||||||
|
res_APDU + enc_len);
|
||||||
|
}
|
||||||
|
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||||
|
r = mbedtls_chachapoly_auth_decrypt(&ctx,
|
||||||
|
enc_len - 16,
|
||||||
|
iv ? iv : tmp_iv,
|
||||||
|
aad,
|
||||||
|
aad_len,
|
||||||
|
enc + enc_len - 16,
|
||||||
|
enc,
|
||||||
|
res_APDU);
|
||||||
|
}
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
mbedtls_chachapoly_free(&ctx);
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
||||||
|
res_APDU_size = enc_len + 16;
|
||||||
|
}
|
||||||
|
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||||
|
res_APDU_size = enc_len - 16;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_DIGEST, 7) == 0) {
|
||||||
|
const mbedtls_md_info_t *md_info = NULL;
|
||||||
|
if (memcmp(oid, OID_HMAC_SHA1, oid_len) == 0) {
|
||||||
|
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA1);
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_HMAC_SHA224, oid_len) == 0) {
|
||||||
|
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA224);
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_HMAC_SHA256, oid_len) == 0) {
|
||||||
|
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_HMAC_SHA384, oid_len) == 0) {
|
||||||
|
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA384);
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_HMAC_SHA512, oid_len) == 0) {
|
||||||
|
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA512);
|
||||||
|
}
|
||||||
|
if (md_info == NULL) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
int r = mbedtls_md_hmac(md_info, kdata, key_size, enc, enc_len, res_APDU);
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
res_APDU_size = md_info->size;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_HKDF_SHA256,
|
||||||
|
oid_len) == 0 ||
|
||||||
|
memcmp(oid, OID_HKDF_SHA384,
|
||||||
|
oid_len) == 0 || memcmp(oid, OID_HKDF_SHA512, oid_len) == 0) {
|
||||||
|
const mbedtls_md_info_t *md_info = NULL;
|
||||||
|
if (memcmp(oid, OID_HKDF_SHA256, oid_len) == 0) {
|
||||||
|
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_HKDF_SHA384, oid_len) == 0) {
|
||||||
|
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA384);
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_HKDF_SHA512, oid_len) == 0) {
|
||||||
|
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA512);
|
||||||
|
}
|
||||||
|
int r = mbedtls_hkdf(md_info,
|
||||||
|
iv,
|
||||||
|
iv_len,
|
||||||
|
kdata,
|
||||||
|
key_size,
|
||||||
|
enc,
|
||||||
|
enc_len,
|
||||||
|
res_APDU,
|
||||||
|
apdu.ne > 0 &&
|
||||||
|
apdu.ne < 65536 ? apdu.ne : mbedtls_md_get_size(md_info));
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
res_APDU_size = apdu.ne > 0 && apdu.ne < 65536 ? apdu.ne : mbedtls_md_get_size(md_info);
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_PKCS5_PBKDF2, oid_len) == 0) {
|
||||||
|
int iterations = 0, keylen = 0;
|
||||||
|
mbedtls_asn1_buf salt,
|
||||||
|
params =
|
||||||
|
{ .p = enc, .len = enc_len, .tag = (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) };
|
||||||
|
mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1;
|
||||||
|
|
||||||
|
int r = pkcs5_parse_pbkdf2_params(¶ms, &salt, &iterations, &keylen, &md_type);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
|
||||||
|
r = mbedtls_pkcs5_pbkdf2_hmac_ext(md_type,
|
||||||
|
kdata,
|
||||||
|
key_size,
|
||||||
|
salt.p,
|
||||||
|
salt.len,
|
||||||
|
iterations,
|
||||||
|
keylen ? keylen : (apdu.ne > 0 &&
|
||||||
|
apdu.ne < 65536 ? apdu.ne : 32),
|
||||||
|
res_APDU);
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
res_APDU_size = keylen ? keylen : (apdu.ne > 0 && apdu.ne < 65536 ? apdu.ne : 32);
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_PKCS5_PBES2, oid_len) == 0) {
|
||||||
|
mbedtls_asn1_buf params =
|
||||||
|
{ .p = aad, .len = aad_len, .tag = (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE) };
|
||||||
|
int r = mbedtls_pkcs5_pbes2(¶ms,
|
||||||
|
algo == ALGO_EXT_CIPHER_ENCRYPT ? MBEDTLS_PKCS5_ENCRYPT : MBEDTLS_PKCS5_DECRYPT,
|
||||||
|
kdata,
|
||||||
|
key_size,
|
||||||
|
enc,
|
||||||
|
enc_len,
|
||||||
|
res_APDU);
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
res_APDU_size = enc_len;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_KDF_X963, oid_len) == 0) {
|
||||||
|
mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1;
|
||||||
|
if (memcmp(enc, OID_HMAC_SHA1, enc_len) == 0) {
|
||||||
|
md_type = MBEDTLS_MD_SHA1;
|
||||||
|
}
|
||||||
|
else if (memcmp(enc, OID_HMAC_SHA224, enc_len) == 0) {
|
||||||
|
md_type = MBEDTLS_MD_SHA224;
|
||||||
|
}
|
||||||
|
else if (memcmp(enc, OID_HMAC_SHA256, enc_len) == 0) {
|
||||||
|
md_type = MBEDTLS_MD_SHA256;
|
||||||
|
}
|
||||||
|
else if (memcmp(enc, OID_HMAC_SHA384, enc_len) == 0) {
|
||||||
|
md_type = MBEDTLS_MD_SHA384;
|
||||||
|
}
|
||||||
|
else if (memcmp(enc, OID_HMAC_SHA512, enc_len) == 0) {
|
||||||
|
md_type = MBEDTLS_MD_SHA512;
|
||||||
|
}
|
||||||
|
int r = mbedtls_ansi_x963_kdf(md_type,
|
||||||
|
key_size,
|
||||||
|
kdata,
|
||||||
|
aad_len,
|
||||||
|
aad,
|
||||||
|
apdu.ne > 0 && apdu.ne < 65536 ? apdu.ne : 32,
|
||||||
|
res_APDU);
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
res_APDU_size = apdu.ne > 0 && apdu.ne < 65536 ? apdu.ne : 32;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
return SW_WRONG_P1P2();
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
193
src/hsm/cmd_decrypt_asym.c
Normal file
193
src/hsm/cmd_decrypt_asym.c
Normal file
@@ -0,0 +1,193 @@
|
|||||||
|
/*
|
||||||
|
* 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 "common.h"
|
||||||
|
#include "mbedtls/ecdh.h"
|
||||||
|
#include "crypto_utils.h"
|
||||||
|
#include "sc_hsm.h"
|
||||||
|
#include "kek.h"
|
||||||
|
#include "files.h"
|
||||||
|
#include "asn1.h"
|
||||||
|
#include "cvc.h"
|
||||||
|
#include "random.h"
|
||||||
|
#include "oid.h"
|
||||||
|
|
||||||
|
int cmd_decrypt_asym() {
|
||||||
|
int key_id = P1(apdu);
|
||||||
|
uint8_t p2 = P2(apdu);
|
||||||
|
if (!isUserAuthenticated) {
|
||||||
|
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 (get_key_counter(ef) == 0) {
|
||||||
|
return SW_FILE_FULL();
|
||||||
|
}
|
||||||
|
if (key_has_purpose(ef, p2) == false) {
|
||||||
|
return SW_CONDITIONS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
if (p2 >= ALGO_RSA_DECRYPT && p2 <= ALGO_RSA_DECRYPT_OEP) {
|
||||||
|
mbedtls_rsa_context ctx;
|
||||||
|
mbedtls_rsa_init(&ctx);
|
||||||
|
if (p2 == ALGO_RSA_DECRYPT_OEP) {
|
||||||
|
mbedtls_rsa_set_padding(&ctx, MBEDTLS_RSA_PKCS_V21, MBEDTLS_MD_SHA256);
|
||||||
|
}
|
||||||
|
int r = load_private_key_rsa(&ctx, ef);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
mbedtls_rsa_free(&ctx);
|
||||||
|
if (r == CCID_VERIFICATION_FAILED) {
|
||||||
|
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
int key_size = file_get_size(ef);
|
||||||
|
if (apdu.nc < key_size) { //needs padding
|
||||||
|
memset(apdu.data + apdu.nc, 0, key_size - apdu.nc);
|
||||||
|
}
|
||||||
|
if (p2 == ALGO_RSA_DECRYPT_PKCS1 || p2 == ALGO_RSA_DECRYPT_OEP) {
|
||||||
|
size_t olen = apdu.nc;
|
||||||
|
r = mbedtls_rsa_pkcs1_decrypt(&ctx, random_gen, NULL, &olen, apdu.data, res_APDU, 512);
|
||||||
|
if (r == 0) {
|
||||||
|
res_APDU_size = olen;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
r = mbedtls_rsa_private(&ctx, random_gen, NULL, apdu.data, res_APDU);
|
||||||
|
if (r == 0) {
|
||||||
|
res_APDU_size = key_size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_rsa_free(&ctx);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
mbedtls_rsa_free(&ctx);
|
||||||
|
}
|
||||||
|
else if (p2 == ALGO_EC_DH || p2 == ALGO_EC_DH_XKEK) {
|
||||||
|
mbedtls_ecdh_context ctx;
|
||||||
|
if (wait_button_pressed() == true) { //timeout
|
||||||
|
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
int key_size = file_get_size(ef);
|
||||||
|
uint8_t *kdata = (uint8_t *) calloc(1, key_size);
|
||||||
|
memcpy(kdata, file_get_data(ef), key_size);
|
||||||
|
if (mkek_decrypt(kdata, key_size) != 0) {
|
||||||
|
mbedtls_platform_zeroize(kdata, key_size);
|
||||||
|
free(kdata);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
mbedtls_ecdh_init(&ctx);
|
||||||
|
mbedtls_ecp_group_id gid = kdata[0];
|
||||||
|
int r = 0;
|
||||||
|
r = mbedtls_ecdh_setup(&ctx, gid);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_platform_zeroize(kdata, key_size);
|
||||||
|
mbedtls_ecdh_free(&ctx);
|
||||||
|
free(kdata);
|
||||||
|
return SW_DATA_INVALID();
|
||||||
|
}
|
||||||
|
r = mbedtls_mpi_read_binary(&ctx.ctx.mbed_ecdh.d, kdata + 1, key_size - 1);
|
||||||
|
mbedtls_platform_zeroize(kdata, key_size);
|
||||||
|
free(kdata);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_ecdh_free(&ctx);
|
||||||
|
return SW_DATA_INVALID();
|
||||||
|
}
|
||||||
|
r = -1;
|
||||||
|
if (p2 == ALGO_EC_DH) {
|
||||||
|
r = mbedtls_ecdh_read_public(&ctx, apdu.data - 1, apdu.nc + 1);
|
||||||
|
}
|
||||||
|
else if (p2 == ALGO_EC_DH_XKEK) {
|
||||||
|
size_t pub_len = 0;
|
||||||
|
const uint8_t *pub = cvc_get_pub(apdu.data, apdu.nc, &pub_len);
|
||||||
|
if (pub) {
|
||||||
|
size_t t86_len = 0;
|
||||||
|
const uint8_t *t86 = cvc_get_field(pub, pub_len, &t86_len, 0x86);
|
||||||
|
if (t86) {
|
||||||
|
r = mbedtls_ecdh_read_public(&ctx, t86 - 1, t86_len + 1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_ecdh_free(&ctx);
|
||||||
|
return SW_DATA_INVALID();
|
||||||
|
}
|
||||||
|
size_t olen = 0;
|
||||||
|
r =
|
||||||
|
mbedtls_ecdh_calc_secret(&ctx, &olen, res_APDU, MBEDTLS_ECP_MAX_BYTES, random_gen,
|
||||||
|
NULL);
|
||||||
|
mbedtls_ecdh_free(&ctx);
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
if (p2 == ALGO_EC_DH) {
|
||||||
|
res_APDU_size = olen;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
res_APDU_size = 0;
|
||||||
|
size_t ext_len = 0;
|
||||||
|
const uint8_t *ext = NULL;
|
||||||
|
if ((ext = cvc_get_ext(apdu.data, apdu.nc, &ext_len)) == NULL) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
uint8_t *p = NULL, *tag_data = NULL, *kdom_uid = NULL;
|
||||||
|
uint16_t tag = 0;
|
||||||
|
size_t tag_len = 0, kdom_uid_len = 0;
|
||||||
|
while (walk_tlv(ext, ext_len, &p, &tag, &tag_len, &tag_data)) {
|
||||||
|
if (tag == 0x73) {
|
||||||
|
size_t oid_len = 0;
|
||||||
|
uint8_t *oid_data = NULL;
|
||||||
|
if (asn1_find_tag(tag_data, tag_len, 0x6, &oid_len,
|
||||||
|
&oid_data) == true &&
|
||||||
|
oid_len == strlen(OID_ID_KEY_DOMAIN_UID) &&
|
||||||
|
memcmp(oid_data, OID_ID_KEY_DOMAIN_UID,
|
||||||
|
strlen(OID_ID_KEY_DOMAIN_UID)) == 0) {
|
||||||
|
if (asn1_find_tag(tag_data, tag_len, 0x80, &kdom_uid_len,
|
||||||
|
&kdom_uid) == false) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (kdom_uid_len == 0 || kdom_uid == NULL) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
for (int n = 0; n < MAX_KEY_DOMAINS; n++) {
|
||||||
|
file_t *tf = search_dynamic_file(EF_XKEK + n);
|
||||||
|
if (tf) {
|
||||||
|
if (file_get_size(tf) == kdom_uid_len &&
|
||||||
|
memcmp(file_get_data(tf), kdom_uid, kdom_uid_len) == 0) {
|
||||||
|
file_new(EF_DKEK + n);
|
||||||
|
if (store_dkek_key(n, res_APDU) != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return SW_WRONG_P1P2();
|
||||||
|
}
|
||||||
|
decrement_key_counter(ef);
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
45
src/hsm/cmd_delete_file.c
Normal file
45
src/hsm/cmd_delete_file.c
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
/*
|
||||||
|
* 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"
|
||||||
|
|
||||||
|
int cmd_delete_file() {
|
||||||
|
file_t *ef = NULL;
|
||||||
|
if (!isUserAuthenticated) {
|
||||||
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (apdu.nc == 0) {
|
||||||
|
ef = currentEF;
|
||||||
|
if (!(ef = search_dynamic_file(ef->fid))) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
uint16_t fid = (apdu.data[0] << 8) | apdu.data[1];
|
||||||
|
if (!(ef = search_dynamic_file(fid))) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!authenticate_action(ef, ACL_OP_DELETE_SELF)) {
|
||||||
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
if (delete_file(ef) != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
102
src/hsm/cmd_derive_asym.c
Normal file
102
src/hsm/cmd_derive_asym.c
Normal file
@@ -0,0 +1,102 @@
|
|||||||
|
/*
|
||||||
|
* 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 "common.h"
|
||||||
|
#include "mbedtls/ecdsa.h"
|
||||||
|
#include "crypto_utils.h"
|
||||||
|
#include "sc_hsm.h"
|
||||||
|
#include "cvc.h"
|
||||||
|
|
||||||
|
#define MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED -0x006E
|
||||||
|
#define MOD_ADD(N) \
|
||||||
|
while (mbedtls_mpi_cmp_mpi(&(N), &grp->P) >= 0) \
|
||||||
|
MBEDTLS_MPI_CHK(mbedtls_mpi_sub_abs(&(N), &(N), &grp->P))
|
||||||
|
static inline int mbedtls_mpi_add_mod(const mbedtls_ecp_group *grp,
|
||||||
|
mbedtls_mpi *X,
|
||||||
|
const mbedtls_mpi *A,
|
||||||
|
const mbedtls_mpi *B) {
|
||||||
|
int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
|
||||||
|
MBEDTLS_MPI_CHK(mbedtls_mpi_add_mpi(X, A, B));
|
||||||
|
MOD_ADD(*X);
|
||||||
|
cleanup:
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
int cmd_derive_asym() {
|
||||||
|
uint8_t key_id = P1(apdu);
|
||||||
|
uint8_t dest_id = P2(apdu);
|
||||||
|
file_t *fkey;
|
||||||
|
if (!isUserAuthenticated) {
|
||||||
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
if (!(fkey = search_dynamic_file((KEY_PREFIX << 8) | key_id)) || !file_has_data(fkey)) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
if (key_has_purpose(fkey, ALGO_EC_DERIVE) == false) {
|
||||||
|
return SW_CONDITIONS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
if (apdu.nc == 0) {
|
||||||
|
return SW_WRONG_LENGTH();
|
||||||
|
}
|
||||||
|
if (apdu.data[0] == ALGO_EC_DERIVE) {
|
||||||
|
mbedtls_ecdsa_context ctx;
|
||||||
|
mbedtls_ecdsa_init(&ctx);
|
||||||
|
|
||||||
|
int r;
|
||||||
|
r = load_private_key_ecdsa(&ctx, fkey);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
mbedtls_ecdsa_free(&ctx);
|
||||||
|
if (r == CCID_VERIFICATION_FAILED) {
|
||||||
|
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
mbedtls_mpi a, nd;
|
||||||
|
mbedtls_mpi_init(&a);
|
||||||
|
mbedtls_mpi_init(&nd);
|
||||||
|
r = mbedtls_mpi_read_binary(&a, apdu.data + 1, apdu.nc - 1);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_ecdsa_free(&ctx);
|
||||||
|
mbedtls_mpi_free(&a);
|
||||||
|
mbedtls_mpi_free(&nd);
|
||||||
|
return SW_DATA_INVALID();
|
||||||
|
}
|
||||||
|
r = mbedtls_mpi_add_mod(&ctx.grp, &nd, &ctx.d, &a);
|
||||||
|
mbedtls_mpi_free(&a);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_ecdsa_free(&ctx);
|
||||||
|
mbedtls_mpi_free(&nd);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
r = mbedtls_mpi_copy(&ctx.d, &nd);
|
||||||
|
mbedtls_mpi_free(&nd);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_ecdsa_free(&ctx);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
r = store_keys(&ctx, HSM_KEY_EC, dest_id);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
mbedtls_ecdsa_free(&ctx);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
mbedtls_ecdsa_free(&ctx);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
66
src/hsm/cmd_external_authenticate.c
Normal file
66
src/hsm/cmd_external_authenticate.c
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
/*
|
||||||
|
* 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 "crypto_utils.h"
|
||||||
|
#include "sc_hsm.h"
|
||||||
|
#include "cvc.h"
|
||||||
|
#include "files.h"
|
||||||
|
|
||||||
|
extern file_t *ef_puk_aut;
|
||||||
|
extern uint8_t challenge[256];
|
||||||
|
extern uint8_t challenge_len;
|
||||||
|
|
||||||
|
int cmd_external_authenticate() {
|
||||||
|
if (P1(apdu) != 0x0 || P2(apdu) != 0x0) {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
if (ef_puk_aut == NULL) {
|
||||||
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
if (apdu.nc == 0) {
|
||||||
|
return SW_WRONG_LENGTH();
|
||||||
|
}
|
||||||
|
file_t *ef_puk = search_by_fid(EF_PUKAUT, NULL, SPECIFY_EF);
|
||||||
|
if (!file_has_data(ef_puk)) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
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];
|
||||||
|
memcpy(input, dev_name, dev_name_len);
|
||||||
|
memcpy(input + dev_name_len, challenge, challenge_len);
|
||||||
|
hash256(input, dev_name_len + challenge_len, hash);
|
||||||
|
int r =
|
||||||
|
puk_verify(apdu.data,
|
||||||
|
apdu.nc,
|
||||||
|
hash,
|
||||||
|
32,
|
||||||
|
file_get_data(ef_puk_aut),
|
||||||
|
file_get_size(ef_puk_aut));
|
||||||
|
free(input);
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_CONDITIONS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
puk_status[ef_puk_aut->fid & (MAX_PUK - 1)] = 1;
|
||||||
|
uint8_t auts = 0;
|
||||||
|
for (int i = 0; i < puk_data[0]; i++) {
|
||||||
|
auts += puk_status[i];
|
||||||
|
}
|
||||||
|
if (auts >= puk_data[2]) {
|
||||||
|
isUserAuthenticated = true;
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
202
src/hsm/cmd_extras.c
Normal file
202
src/hsm/cmd_extras.c
Normal file
@@ -0,0 +1,202 @@
|
|||||||
|
/*
|
||||||
|
* 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 "common.h"
|
||||||
|
#include "mbedtls/ecdh.h"
|
||||||
|
#include "sc_hsm.h"
|
||||||
|
#ifndef ENABLE_EMULATION
|
||||||
|
#include "hardware/rtc.h"
|
||||||
|
#endif
|
||||||
|
#include "files.h"
|
||||||
|
#include "random.h"
|
||||||
|
#include "kek.h"
|
||||||
|
#include "mbedtls/hkdf.h"
|
||||||
|
#include "mbedtls/chachapoly.h"
|
||||||
|
|
||||||
|
int cmd_extras() {
|
||||||
|
if (P1(apdu) == 0xA) { //datetime operations
|
||||||
|
if (P2(apdu) != 0x0) {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
if (apdu.nc == 0) {
|
||||||
|
#ifndef ENABLE_EMULATION
|
||||||
|
datetime_t dt;
|
||||||
|
if (!rtc_get_datetime(&dt)) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
res_APDU[res_APDU_size++] = dt.year >> 8;
|
||||||
|
res_APDU[res_APDU_size++] = dt.year & 0xff;
|
||||||
|
res_APDU[res_APDU_size++] = dt.month;
|
||||||
|
res_APDU[res_APDU_size++] = dt.day;
|
||||||
|
res_APDU[res_APDU_size++] = dt.dotw;
|
||||||
|
res_APDU[res_APDU_size++] = dt.hour;
|
||||||
|
res_APDU[res_APDU_size++] = dt.min;
|
||||||
|
res_APDU[res_APDU_size++] = dt.sec;
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if (apdu.nc != 8) {
|
||||||
|
return SW_WRONG_LENGTH();
|
||||||
|
}
|
||||||
|
#ifndef ENABLE_EMULATION
|
||||||
|
datetime_t dt;
|
||||||
|
dt.year = (apdu.data[0] << 8) | (apdu.data[1]);
|
||||||
|
dt.month = apdu.data[2];
|
||||||
|
dt.day = apdu.data[3];
|
||||||
|
dt.dotw = apdu.data[4];
|
||||||
|
dt.hour = apdu.data[5];
|
||||||
|
dt.min = apdu.data[6];
|
||||||
|
dt.sec = apdu.data[7];
|
||||||
|
if (!rtc_set_datetime(&dt)) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (P1(apdu) == 0x6) { //dynamic options
|
||||||
|
if (P2(apdu) != 0x0) {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
if (apdu.nc > sizeof(uint8_t)) {
|
||||||
|
return SW_WRONG_LENGTH();
|
||||||
|
}
|
||||||
|
uint16_t opts = get_device_options();
|
||||||
|
if (apdu.nc == 0) {
|
||||||
|
res_APDU[res_APDU_size++] = opts >> 8;
|
||||||
|
res_APDU[res_APDU_size++] = opts & 0xff;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
uint8_t newopts[] = { apdu.data[0], (opts & 0xff) };
|
||||||
|
file_t *tf = search_by_fid(EF_DEVOPS, NULL, SPECIFY_EF);
|
||||||
|
flash_write_data_to_file(tf, newopts, sizeof(newopts));
|
||||||
|
low_flash_available();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (P1(apdu) == 0x3A) { // secure lock
|
||||||
|
if (apdu.nc == 0) {
|
||||||
|
return SW_WRONG_LENGTH();
|
||||||
|
}
|
||||||
|
if (P2(apdu) == 0x01) { // Key Agreement
|
||||||
|
mbedtls_ecdh_context hkey;
|
||||||
|
mbedtls_ecdh_init(&hkey);
|
||||||
|
mbedtls_ecdh_setup(&hkey, MBEDTLS_ECP_DP_SECP256R1);
|
||||||
|
int ret = mbedtls_ecdh_gen_public(&hkey.ctx.mbed_ecdh.grp,
|
||||||
|
&hkey.ctx.mbed_ecdh.d,
|
||||||
|
&hkey.ctx.mbed_ecdh.Q,
|
||||||
|
random_gen,
|
||||||
|
NULL);
|
||||||
|
mbedtls_mpi_lset(&hkey.ctx.mbed_ecdh.Qp.Z, 1);
|
||||||
|
ret = mbedtls_ecp_point_read_binary(&hkey.ctx.mbed_ecdh.grp,
|
||||||
|
&hkey.ctx.mbed_ecdh.Qp,
|
||||||
|
apdu.data,
|
||||||
|
apdu.nc);
|
||||||
|
if (ret != 0) {
|
||||||
|
mbedtls_ecdh_free(&hkey);
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
memcpy(mse.Qpt, apdu.data, sizeof(mse.Qpt));
|
||||||
|
|
||||||
|
uint8_t buf[MBEDTLS_ECP_MAX_BYTES];
|
||||||
|
size_t olen = 0;
|
||||||
|
ret = mbedtls_ecdh_calc_secret(&hkey,
|
||||||
|
&olen,
|
||||||
|
buf,
|
||||||
|
MBEDTLS_ECP_MAX_BYTES,
|
||||||
|
random_gen,
|
||||||
|
NULL);
|
||||||
|
if (ret != 0) {
|
||||||
|
mbedtls_ecdh_free(&hkey);
|
||||||
|
mbedtls_platform_zeroize(buf, sizeof(buf));
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
ret = mbedtls_hkdf(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256),
|
||||||
|
NULL,
|
||||||
|
0,
|
||||||
|
buf,
|
||||||
|
olen,
|
||||||
|
mse.Qpt,
|
||||||
|
sizeof(mse.Qpt),
|
||||||
|
mse.key_enc,
|
||||||
|
sizeof(mse.key_enc));
|
||||||
|
mbedtls_platform_zeroize(buf, sizeof(buf));
|
||||||
|
if (ret != 0) {
|
||||||
|
mbedtls_ecdh_free(&hkey);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
|
||||||
|
ret = mbedtls_ecp_point_write_binary(&hkey.ctx.mbed_ecdh.grp,
|
||||||
|
&hkey.ctx.mbed_ecdh.Q,
|
||||||
|
MBEDTLS_ECP_PF_UNCOMPRESSED,
|
||||||
|
&olen,
|
||||||
|
res_APDU,
|
||||||
|
4096);
|
||||||
|
mbedtls_ecdh_free(&hkey);
|
||||||
|
if (ret != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
mse.init = true;
|
||||||
|
res_APDU_size = olen;
|
||||||
|
}
|
||||||
|
else if (P2(apdu) == 0x02 || P2(apdu) == 0x03 || P2(apdu) == 0x04) {
|
||||||
|
if (mse.init == false) {
|
||||||
|
return SW_COMMAND_NOT_ALLOWED();
|
||||||
|
}
|
||||||
|
|
||||||
|
int ret = mse_decrypt_ct(apdu.data, apdu.nc);
|
||||||
|
if (ret != 0) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
if (P2(apdu) == 0x02 || P2(apdu) == 0x04) { // Enable
|
||||||
|
uint16_t opts = get_device_options();
|
||||||
|
uint8_t newopts[] = { opts >> 8, (opts & 0xff) };
|
||||||
|
if ((P2(apdu) == 0x02 && !(opts & HSM_OPT_SECURE_LOCK)) ||
|
||||||
|
(P2(apdu) == 0x04 && (opts & HSM_OPT_SECURE_LOCK))) {
|
||||||
|
uint16_t tfids[] = { EF_MKEK, EF_MKEK_SO };
|
||||||
|
for (int t = 0; t < sizeof(tfids) / sizeof(uint16_t); t++) {
|
||||||
|
file_t *tf = search_by_fid(tfids[t], NULL, SPECIFY_EF);
|
||||||
|
if (tf) {
|
||||||
|
uint8_t *tmp = (uint8_t *) calloc(1, file_get_size(tf));
|
||||||
|
memcpy(tmp, file_get_data(tf), file_get_size(tf));
|
||||||
|
for (int i = 0; i < MKEK_KEY_SIZE; i++) {
|
||||||
|
MKEK_KEY(tmp)[i] ^= apdu.data[i];
|
||||||
|
}
|
||||||
|
flash_write_data_to_file(tf, tmp, file_get_size(tf));
|
||||||
|
free(tmp);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (P2(apdu) == 0x02) {
|
||||||
|
newopts[0] |= HSM_OPT_SECURE_LOCK >> 8;
|
||||||
|
}
|
||||||
|
else if (P2(apdu) == 0x04) {
|
||||||
|
newopts[0] &= ~HSM_OPT_SECURE_LOCK >> 8;
|
||||||
|
}
|
||||||
|
file_t *tf = search_by_fid(EF_DEVOPS, NULL, SPECIFY_EF);
|
||||||
|
flash_write_data_to_file(tf, newopts, sizeof(newopts));
|
||||||
|
low_flash_available();
|
||||||
|
}
|
||||||
|
else if (P2(apdu) == 0x03) {
|
||||||
|
memcpy(mkek_mask, apdu.data, apdu.nc);
|
||||||
|
has_mkek_mask = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
115
src/hsm/cmd_general_authenticate.c
Normal file
115
src/hsm/cmd_general_authenticate.c
Normal file
@@ -0,0 +1,115 @@
|
|||||||
|
/*
|
||||||
|
* 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 "common.h"
|
||||||
|
#include "mbedtls/ecdh.h"
|
||||||
|
#include "asn1.h"
|
||||||
|
#include "sc_hsm.h"
|
||||||
|
#include "random.h"
|
||||||
|
#include "oid.h"
|
||||||
|
#include "eac.h"
|
||||||
|
#include "files.h"
|
||||||
|
|
||||||
|
int cmd_general_authenticate() {
|
||||||
|
if (P1(apdu) == 0x0 && P2(apdu) == 0x0) {
|
||||||
|
if (apdu.data[0] == 0x7C) {
|
||||||
|
int r = 0;
|
||||||
|
size_t pubkey_len = 0;
|
||||||
|
const uint8_t *pubkey = NULL;
|
||||||
|
uint16_t tag = 0x0;
|
||||||
|
uint8_t *tag_data = NULL, *p = NULL;
|
||||||
|
size_t tag_len = 0;
|
||||||
|
while (walk_tlv(apdu.data + 2, apdu.nc - 2, &p, &tag, &tag_len, &tag_data)) {
|
||||||
|
if (tag == 0x80) {
|
||||||
|
pubkey = tag_data - 1; //mbedtls ecdh starts reading one pos before
|
||||||
|
pubkey_len = tag_len + 1;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file_t *fkey = search_by_fid(EF_KEY_DEV, NULL, SPECIFY_EF);
|
||||||
|
if (!fkey) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
mbedtls_ecdsa_context ectx;
|
||||||
|
mbedtls_ecdsa_init(&ectx);
|
||||||
|
r = load_private_key_ecdsa(&ectx, fkey);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
mbedtls_ecdsa_free(&ectx);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
mbedtls_ecdh_context ctx;
|
||||||
|
mbedtls_ecdh_init(&ctx);
|
||||||
|
mbedtls_ecp_group_id gid = MBEDTLS_ECP_DP_SECP256R1;
|
||||||
|
r = mbedtls_ecdh_setup(&ctx, gid);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_ecdsa_free(&ectx);
|
||||||
|
mbedtls_ecdh_free(&ctx);
|
||||||
|
return SW_DATA_INVALID();
|
||||||
|
}
|
||||||
|
r = mbedtls_mpi_copy(&ctx.ctx.mbed_ecdh.d, &ectx.d);
|
||||||
|
mbedtls_ecdsa_free(&ectx);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_ecdh_free(&ctx);
|
||||||
|
return SW_DATA_INVALID();
|
||||||
|
}
|
||||||
|
r = mbedtls_ecdh_read_public(&ctx, pubkey, pubkey_len);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_ecdh_free(&ctx);
|
||||||
|
return SW_DATA_INVALID();
|
||||||
|
}
|
||||||
|
size_t olen = 0;
|
||||||
|
uint8_t derived[MBEDTLS_ECP_MAX_BYTES];
|
||||||
|
r = mbedtls_ecdh_calc_secret(&ctx,
|
||||||
|
&olen,
|
||||||
|
derived,
|
||||||
|
MBEDTLS_ECP_MAX_BYTES,
|
||||||
|
random_gen,
|
||||||
|
NULL);
|
||||||
|
mbedtls_ecdh_free(&ctx);
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
|
||||||
|
sm_derive_all_keys(derived, olen);
|
||||||
|
|
||||||
|
uint8_t *t = (uint8_t *) calloc(1, pubkey_len + 16);
|
||||||
|
memcpy(t, "\x7F\x49\x4F\x06\x0A", 5);
|
||||||
|
if (sm_get_protocol() == MSE_AES) {
|
||||||
|
memcpy(t + 5, OID_ID_CA_ECDH_AES_CBC_CMAC_128, 10);
|
||||||
|
}
|
||||||
|
t[15] = 0x86;
|
||||||
|
memcpy(t + 16, pubkey, pubkey_len);
|
||||||
|
|
||||||
|
res_APDU[res_APDU_size++] = 0x7C;
|
||||||
|
res_APDU[res_APDU_size++] = 20;
|
||||||
|
res_APDU[res_APDU_size++] = 0x81;
|
||||||
|
res_APDU[res_APDU_size++] = 8;
|
||||||
|
memcpy(res_APDU + res_APDU_size, sm_get_nonce(), 8);
|
||||||
|
res_APDU_size += 8;
|
||||||
|
res_APDU[res_APDU_size++] = 0x82;
|
||||||
|
res_APDU[res_APDU_size++] = 8;
|
||||||
|
|
||||||
|
r = sm_sign(t, pubkey_len + 16, res_APDU + res_APDU_size);
|
||||||
|
|
||||||
|
free(t);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
res_APDU_size += 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
237
src/hsm/cmd_initialize.c
Normal file
237
src/hsm/cmd_initialize.c
Normal file
@@ -0,0 +1,237 @@
|
|||||||
|
/*
|
||||||
|
* 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 "crypto_utils.h"
|
||||||
|
#include "sc_hsm.h"
|
||||||
|
#include "files.h"
|
||||||
|
#include "random.h"
|
||||||
|
#include "kek.h"
|
||||||
|
#include "version.h"
|
||||||
|
#include "asn1.h"
|
||||||
|
#include "cvc.h"
|
||||||
|
|
||||||
|
extern void scan_all();
|
||||||
|
|
||||||
|
extern char __StackLimit;
|
||||||
|
int heapLeft() {
|
||||||
|
#ifndef ENABLE_EMULATION
|
||||||
|
char *p = malloc(256); // try to avoid undue fragmentation
|
||||||
|
int left = &__StackLimit - p;
|
||||||
|
free(p);
|
||||||
|
#else
|
||||||
|
int left = 1024 * 1024;
|
||||||
|
#endif
|
||||||
|
return left;
|
||||||
|
}
|
||||||
|
|
||||||
|
int cmd_initialize() {
|
||||||
|
if (apdu.nc > 0) {
|
||||||
|
uint8_t mkek[MKEK_SIZE];
|
||||||
|
int ret_mkek = load_mkek(mkek); //Try loading MKEK with previous session
|
||||||
|
initialize_flash(true);
|
||||||
|
scan_all();
|
||||||
|
has_session_pin = has_session_sopin = false;
|
||||||
|
uint16_t tag = 0x0;
|
||||||
|
uint8_t *tag_data = NULL, *p = NULL, *kds = NULL, *dkeks = NULL;
|
||||||
|
size_t tag_len = 0;
|
||||||
|
while (walk_tlv(apdu.data, apdu.nc, &p, &tag, &tag_len, &tag_data)) {
|
||||||
|
if (tag == 0x80) { //options
|
||||||
|
file_t *tf = search_by_fid(EF_DEVOPS, NULL, SPECIFY_EF);
|
||||||
|
flash_write_data_to_file(tf, tag_data, tag_len);
|
||||||
|
}
|
||||||
|
else if (tag == 0x81) { //user pin
|
||||||
|
if (file_pin1 && file_pin1->data) {
|
||||||
|
uint8_t dhash[33];
|
||||||
|
dhash[0] = tag_len;
|
||||||
|
double_hash_pin(tag_data, tag_len, dhash + 1);
|
||||||
|
flash_write_data_to_file(file_pin1, dhash, sizeof(dhash));
|
||||||
|
hash_multi(tag_data, tag_len, session_pin);
|
||||||
|
has_session_pin = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (tag == 0x82) { //sopin pin
|
||||||
|
if (file_sopin && file_sopin->data) {
|
||||||
|
uint8_t dhash[33];
|
||||||
|
dhash[0] = tag_len;
|
||||||
|
double_hash_pin(tag_data, tag_len, dhash + 1);
|
||||||
|
flash_write_data_to_file(file_sopin, dhash, sizeof(dhash));
|
||||||
|
hash_multi(tag_data, tag_len, session_sopin);
|
||||||
|
has_session_sopin = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (tag == 0x91) { //retries user pin
|
||||||
|
file_t *tf = search_by_fid(0x1082, NULL, SPECIFY_EF);
|
||||||
|
if (tf && tf->data) {
|
||||||
|
flash_write_data_to_file(tf, tag_data, tag_len);
|
||||||
|
}
|
||||||
|
if (file_retries_pin1 && file_retries_pin1->data) {
|
||||||
|
flash_write_data_to_file(file_retries_pin1, tag_data, tag_len);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (tag == 0x92) {
|
||||||
|
dkeks = tag_data;
|
||||||
|
file_t *tf = file_new(EF_DKEK);
|
||||||
|
if (!tf) {
|
||||||
|
release_mkek(mkek);
|
||||||
|
return SW_MEMORY_FAILURE();
|
||||||
|
}
|
||||||
|
flash_write_data_to_file(tf, NULL, 0);
|
||||||
|
}
|
||||||
|
else if (tag == 0x93) {
|
||||||
|
file_t *ef_puk = search_by_fid(EF_PUKAUT, NULL, SPECIFY_EF);
|
||||||
|
if (!ef_puk) {
|
||||||
|
release_mkek(mkek);
|
||||||
|
return SW_MEMORY_FAILURE();
|
||||||
|
}
|
||||||
|
uint8_t pk_status[4], puks = MIN(tag_data[0], MAX_PUK);
|
||||||
|
memset(pk_status, 0, sizeof(pk_status));
|
||||||
|
pk_status[0] = puks;
|
||||||
|
pk_status[1] = puks;
|
||||||
|
pk_status[2] = tag_data[1];
|
||||||
|
flash_write_data_to_file(ef_puk, pk_status, sizeof(pk_status));
|
||||||
|
for (int i = 0; i < puks; i++) {
|
||||||
|
file_t *tf = file_new(EF_PUK + i);
|
||||||
|
if (!tf) {
|
||||||
|
release_mkek(mkek);
|
||||||
|
return SW_MEMORY_FAILURE();
|
||||||
|
}
|
||||||
|
flash_write_data_to_file(tf, NULL, 0);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (tag == 0x97) {
|
||||||
|
kds = tag_data;
|
||||||
|
/*
|
||||||
|
for (int i = 0; i < MIN(*kds,MAX_KEY_DOMAINS); i++) {
|
||||||
|
file_t *tf = file_new(EF_DKEK+i);
|
||||||
|
if (!tf)
|
||||||
|
return SW_MEMORY_FAILURE();
|
||||||
|
flash_write_data_to_file(tf, NULL, 0);
|
||||||
|
}
|
||||||
|
*/
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file_t *tf_kd = search_by_fid(EF_KEY_DOMAIN, NULL, SPECIFY_EF);
|
||||||
|
if (!tf_kd) {
|
||||||
|
release_mkek(mkek);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
if (ret_mkek != CCID_OK) {
|
||||||
|
ret_mkek = load_mkek(mkek); //Try again with new PIN/SO-PIN just in case some is the same
|
||||||
|
}
|
||||||
|
if (store_mkek(ret_mkek == CCID_OK ? mkek : NULL) != CCID_OK) {
|
||||||
|
release_mkek(mkek);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
release_mkek(mkek);
|
||||||
|
if (dkeks) {
|
||||||
|
if (*dkeks > 0) {
|
||||||
|
uint16_t d = *dkeks;
|
||||||
|
if (flash_write_data_to_file(tf_kd, (const uint8_t *) &d, sizeof(d)) != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
int r = save_dkek_key(0, random_bytes_get(32));
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
uint16_t d = 0x0101;
|
||||||
|
if (flash_write_data_to_file(tf_kd, (const uint8_t *) &d, sizeof(d)) != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
uint16_t d = 0x0000;
|
||||||
|
if (flash_write_data_to_file(tf_kd, (const uint8_t *) &d, sizeof(d)) != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (kds) {
|
||||||
|
uint8_t t[MAX_KEY_DOMAINS * 2], k = MIN(*kds, MAX_KEY_DOMAINS);
|
||||||
|
memset(t, 0xff, 2 * k);
|
||||||
|
if (flash_write_data_to_file(tf_kd, t, 2 * k) != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
/* When initialized, it has all credentials */
|
||||||
|
isUserAuthenticated = true;
|
||||||
|
/* Create terminal private key */
|
||||||
|
file_t *fdkey = search_by_fid(EF_KEY_DEV, NULL, SPECIFY_EF);
|
||||||
|
if (!fdkey) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
int ret = 0;
|
||||||
|
if (ret_mkek != CCID_OK || !file_has_data(fdkey)) {
|
||||||
|
mbedtls_ecdsa_context ecdsa;
|
||||||
|
mbedtls_ecdsa_init(&ecdsa);
|
||||||
|
mbedtls_ecp_group_id ec_id = MBEDTLS_ECP_DP_SECP256R1;
|
||||||
|
uint8_t index = 0, key_id = 0;
|
||||||
|
ret = mbedtls_ecdsa_genkey(&ecdsa, ec_id, random_gen, &index);
|
||||||
|
if (ret != 0) {
|
||||||
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
ret = store_keys(&ecdsa, HSM_KEY_EC, key_id);
|
||||||
|
if (ret != CCID_OK) {
|
||||||
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
size_t cvc_len = 0;
|
||||||
|
if ((cvc_len = asn1_cvc_aut(&ecdsa, HSM_KEY_EC, res_APDU, 4096, NULL, 0)) == 0) {
|
||||||
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
|
|
||||||
|
file_t *fpk = search_by_fid(EF_EE_DEV, NULL, SPECIFY_EF);
|
||||||
|
ret = flash_write_data_to_file(fpk, res_APDU, cvc_len);
|
||||||
|
if (ret != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
|
||||||
|
const uint8_t *keyid =
|
||||||
|
(const uint8_t *) "\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0",
|
||||||
|
*label = (const uint8_t *) "ESTERMHSM";
|
||||||
|
size_t prkd_len = asn1_build_prkd_ecc(label,
|
||||||
|
strlen((const char *) label),
|
||||||
|
keyid,
|
||||||
|
20,
|
||||||
|
192,
|
||||||
|
res_APDU,
|
||||||
|
4096);
|
||||||
|
fpk = search_by_fid(EF_PRKD_DEV, NULL, SPECIFY_EF);
|
||||||
|
ret = flash_write_data_to_file(fpk, res_APDU, prkd_len);
|
||||||
|
}
|
||||||
|
if (ret != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
low_flash_available();
|
||||||
|
}
|
||||||
|
else { //free memory bytes request
|
||||||
|
int heap_left = heapLeft();
|
||||||
|
res_APDU[0] = ((heap_left >> 24) & 0xff);
|
||||||
|
res_APDU[1] = ((heap_left >> 16) & 0xff);
|
||||||
|
res_APDU[2] = ((heap_left >> 8) & 0xff);
|
||||||
|
res_APDU[3] = ((heap_left >> 0) & 0xff);
|
||||||
|
res_APDU[4] = 0;
|
||||||
|
res_APDU[5] = HSM_VERSION_MAJOR;
|
||||||
|
res_APDU[6] = HSM_VERSION_MINOR;
|
||||||
|
res_APDU_size = 7;
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
196
src/hsm/cmd_key_domain.c
Normal file
196
src/hsm/cmd_key_domain.c
Normal file
@@ -0,0 +1,196 @@
|
|||||||
|
/*
|
||||||
|
* 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 "crypto_utils.h"
|
||||||
|
#include "sc_hsm.h"
|
||||||
|
#include "cvc.h"
|
||||||
|
#include "kek.h"
|
||||||
|
#include "files.h"
|
||||||
|
|
||||||
|
uint8_t get_key_domain(file_t *fkey) {
|
||||||
|
size_t tag_len = 0;
|
||||||
|
const uint8_t *meta_tag = get_meta_tag(fkey, 0x92, &tag_len);
|
||||||
|
if (meta_tag) {
|
||||||
|
return *meta_tag;
|
||||||
|
}
|
||||||
|
return 0xff;
|
||||||
|
}
|
||||||
|
|
||||||
|
int cmd_key_domain() {
|
||||||
|
//if (dkeks == 0)
|
||||||
|
// return SW_COMMAND_NOT_ALLOWED();
|
||||||
|
uint8_t p1 = P1(apdu), p2 = P2(apdu);
|
||||||
|
if ((has_session_pin == false || isUserAuthenticated == false) && apdu.nc > 0 &&
|
||||||
|
!(p1 == 0x0 && p2 == 0x0)) {
|
||||||
|
return SW_CONDITIONS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
if (p2 >= MAX_KEY_DOMAINS) {
|
||||||
|
return SW_WRONG_P1P2();
|
||||||
|
}
|
||||||
|
file_t *tf_kd = search_by_fid(EF_KEY_DOMAIN, NULL, SPECIFY_EF);
|
||||||
|
if (!tf_kd) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
uint16_t tf_kd_size = file_get_size(tf_kd);
|
||||||
|
if (tf_kd_size == 0) {
|
||||||
|
return SW_WRONG_P1P2();
|
||||||
|
}
|
||||||
|
uint8_t *kdata = file_get_data(tf_kd), dkeks = kdata ? kdata[2 * p2] : 0,
|
||||||
|
current_dkeks = kdata ? kdata[2 * p2 + 1] : 0;
|
||||||
|
if (p1 == 0x0) { //dkek import
|
||||||
|
if (apdu.nc > 0) {
|
||||||
|
file_t *tf = file_new(EF_DKEK + p2);
|
||||||
|
if (!tf) {
|
||||||
|
return SW_MEMORY_FAILURE();
|
||||||
|
}
|
||||||
|
if (apdu.nc < 32) {
|
||||||
|
return SW_WRONG_LENGTH();
|
||||||
|
}
|
||||||
|
if (current_dkeks == dkeks) {
|
||||||
|
return SW_COMMAND_NOT_ALLOWED();
|
||||||
|
}
|
||||||
|
import_dkek_share(p2, apdu.data);
|
||||||
|
if (++current_dkeks >= dkeks) {
|
||||||
|
if (save_dkek_key(p2, NULL) != CCID_OK) {
|
||||||
|
/* 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];
|
||||||
|
memcpy(t, kdata, tf_kd_size);
|
||||||
|
t[2 * p2 + 1] = current_dkeks;
|
||||||
|
if (flash_write_data_to_file(tf_kd, t, tf_kd_size) != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
low_flash_available();
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
file_t *tf = search_dynamic_file(EF_XKEK + p2);
|
||||||
|
if (2 * p2 >= tf_kd_size) {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
if (current_dkeks == 0xff && !tf) { //XKEK have always 0xff
|
||||||
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (p1 == 0x1 || p1 == 0x3 || p1 == 0x4) { //key domain setup
|
||||||
|
if (p1 == 0x1 && apdu.nc != 1) {
|
||||||
|
return SW_WRONG_LENGTH();
|
||||||
|
}
|
||||||
|
if (p1 == 0x3) { //if key domain is not empty, command is denied
|
||||||
|
for (int i = 0; i < dynamic_files; i++) {
|
||||||
|
if (get_key_domain(&dynamic_file[i]) == p2) {
|
||||||
|
return SW_FILE_EXISTS();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
uint8_t t[MAX_KEY_DOMAINS * 2];
|
||||||
|
memcpy(t, kdata, tf_kd_size);
|
||||||
|
if (p1 == 0x1) {
|
||||||
|
t[2 * p2] = dkeks = apdu.data[0];
|
||||||
|
t[2 * p2 + 1] = current_dkeks = 0;
|
||||||
|
}
|
||||||
|
else if (p1 == 0x3) {
|
||||||
|
t[2 * p2] = dkeks = 0xff;
|
||||||
|
t[2 * p2 + 1] = 0xff;
|
||||||
|
}
|
||||||
|
else if (p1 == 0x4) {
|
||||||
|
t[2 * p2 + 1] = current_dkeks = 0;
|
||||||
|
}
|
||||||
|
if (flash_write_data_to_file(tf_kd, t, tf_kd_size) != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
file_t *tf = NULL;
|
||||||
|
if ((tf = search_dynamic_file(EF_DKEK + p2))) {
|
||||||
|
if (delete_file(tf) != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (p1 == 0x3 && (tf = search_dynamic_file(EF_XKEK + p2))) {
|
||||||
|
if (delete_file(tf) != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
low_flash_available();
|
||||||
|
if (p1 == 0x3) {
|
||||||
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (p1 == 0x2) { //XKEK Key Domain creation
|
||||||
|
if (apdu.nc > 0) {
|
||||||
|
size_t pub_len = 0;
|
||||||
|
file_t *fterm = search_by_fid(EF_TERMCA, NULL, SPECIFY_EF);
|
||||||
|
if (!fterm) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
const uint8_t *pub = cvc_get_pub(file_get_data(fterm), file_get_size(fterm), &pub_len);
|
||||||
|
if (!pub) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
size_t t86_len = 0;
|
||||||
|
const uint8_t *t86 = cvc_get_field(pub, pub_len, &t86_len, 0x86);
|
||||||
|
if (!t86 || t86[0] != 0x4) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
size_t t54_len = 0;
|
||||||
|
const uint8_t *t54 = cvc_get_field(apdu.data, apdu.nc, &t54_len, 0x54);
|
||||||
|
if (!t54) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
uint8_t hash[32], *input = (uint8_t *) calloc(1, (t86_len - 1) / 2 + 1);
|
||||||
|
input[0] = 0x54;
|
||||||
|
memcpy(input + 1, t86 + 1, (t86_len - 1) / 2);
|
||||||
|
hash256(input, (t86_len - 1) / 2 + 1, hash);
|
||||||
|
free(input);
|
||||||
|
int r = puk_verify(t54, t54_len, hash, 32, apdu.data, apdu.nc);
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_CONDITIONS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
file_t *tf = file_new(EF_XKEK + p2);
|
||||||
|
if (!tf) {
|
||||||
|
return SW_MEMORY_FAILURE();
|
||||||
|
}
|
||||||
|
|
||||||
|
//All checks done. Get Key Domain UID
|
||||||
|
pub = cvc_get_pub(apdu.data, apdu.nc, &pub_len);
|
||||||
|
if (pub) {
|
||||||
|
size_t t86_len = 0;
|
||||||
|
const uint8_t *t86 = cvc_get_field(pub, pub_len, &t86_len, 0x86);
|
||||||
|
if (t86) {
|
||||||
|
flash_write_data_to_file(tf, t86 + 1, t86_len - 1);
|
||||||
|
low_flash_available();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
memset(res_APDU, 0, 10);
|
||||||
|
res_APDU[0] = dkeks;
|
||||||
|
res_APDU[1] = dkeks > current_dkeks ? dkeks - current_dkeks : 0;
|
||||||
|
dkek_kcv(p2, res_APDU + 2);
|
||||||
|
res_APDU_size = 2 + 8;
|
||||||
|
file_t *tf = search_dynamic_file(EF_XKEK + p2);
|
||||||
|
if (tf) {
|
||||||
|
memcpy(res_APDU + 10, file_get_data(tf), file_get_size(tf));
|
||||||
|
res_APDU_size += file_get_size(tf);
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
61
src/hsm/cmd_key_gen.c
Normal file
61
src/hsm/cmd_key_gen.c
Normal file
@@ -0,0 +1,61 @@
|
|||||||
|
/*
|
||||||
|
* 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 "crypto_utils.h"
|
||||||
|
#include "sc_hsm.h"
|
||||||
|
#include "random.h"
|
||||||
|
|
||||||
|
int cmd_key_gen() {
|
||||||
|
uint8_t key_id = P1(apdu);
|
||||||
|
uint8_t p2 = P2(apdu);
|
||||||
|
uint8_t key_size = 32;
|
||||||
|
int r;
|
||||||
|
if (!isUserAuthenticated) {
|
||||||
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
if (p2 == 0xB2) {
|
||||||
|
key_size = 32;
|
||||||
|
}
|
||||||
|
else if (p2 == 0xB1) {
|
||||||
|
key_size = 24;
|
||||||
|
}
|
||||||
|
else if (p2 == 0xB0) {
|
||||||
|
key_size = 16;
|
||||||
|
}
|
||||||
|
//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
|
||||||
|
memcpy(aes_key, random_bytes_get(key_size), key_size);
|
||||||
|
int aes_type = 0x0;
|
||||||
|
if (key_size == 16) {
|
||||||
|
aes_type = HSM_KEY_AES_128;
|
||||||
|
}
|
||||||
|
else if (key_size == 24) {
|
||||||
|
aes_type = HSM_KEY_AES_192;
|
||||||
|
}
|
||||||
|
else if (key_size == 32) {
|
||||||
|
aes_type = HSM_KEY_AES_256;
|
||||||
|
}
|
||||||
|
r = store_keys(aes_key, aes_type, key_id);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return SW_MEMORY_FAILURE();
|
||||||
|
}
|
||||||
|
if (find_and_store_meta_key(key_id) != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
low_flash_available();
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
138
src/hsm/cmd_key_unwrap.c
Normal file
138
src/hsm/cmd_key_unwrap.c
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
/*
|
||||||
|
* 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 "crypto_utils.h"
|
||||||
|
#include "sc_hsm.h"
|
||||||
|
#include "kek.h"
|
||||||
|
#include "cvc.h"
|
||||||
|
|
||||||
|
int cmd_key_unwrap() {
|
||||||
|
int key_id = P1(apdu), r = 0;
|
||||||
|
if (P2(apdu) != 0x93) {
|
||||||
|
return SW_WRONG_P1P2();
|
||||||
|
}
|
||||||
|
if (!isUserAuthenticated) {
|
||||||
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
int key_type = dkek_type_key(apdu.data);
|
||||||
|
uint8_t kdom = -1, *allowed = NULL;
|
||||||
|
size_t allowed_len = 0;
|
||||||
|
if (key_type == 0x0) {
|
||||||
|
return SW_DATA_INVALID();
|
||||||
|
}
|
||||||
|
if (key_type == HSM_KEY_RSA) {
|
||||||
|
mbedtls_rsa_context ctx;
|
||||||
|
mbedtls_rsa_init(&ctx);
|
||||||
|
do {
|
||||||
|
r = dkek_decode_key(++kdom, &ctx, apdu.data, apdu.nc, NULL, &allowed, &allowed_len);
|
||||||
|
} while ((r == CCID_ERR_FILE_NOT_FOUND || r == CCID_WRONG_DKEK) && kdom < MAX_KEY_DOMAINS);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
mbedtls_rsa_free(&ctx);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
r = store_keys(&ctx, HSM_KEY_RSA, key_id);
|
||||||
|
if ((res_APDU_size = asn1_cvc_aut(&ctx, HSM_KEY_RSA, res_APDU, 4096, NULL, 0)) == 0) {
|
||||||
|
mbedtls_rsa_free(&ctx);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
mbedtls_rsa_free(&ctx);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (key_type == HSM_KEY_EC) {
|
||||||
|
mbedtls_ecdsa_context ctx;
|
||||||
|
mbedtls_ecdsa_init(&ctx);
|
||||||
|
do {
|
||||||
|
r = dkek_decode_key(++kdom, &ctx, apdu.data, apdu.nc, NULL, &allowed, &allowed_len);
|
||||||
|
} while ((r == CCID_ERR_FILE_NOT_FOUND || r == CCID_WRONG_DKEK) && kdom < MAX_KEY_DOMAINS);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
mbedtls_ecdsa_free(&ctx);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
r = store_keys(&ctx, HSM_KEY_EC, key_id);
|
||||||
|
if ((res_APDU_size = asn1_cvc_aut(&ctx, HSM_KEY_EC, res_APDU, 4096, NULL, 0)) == 0) {
|
||||||
|
mbedtls_ecdsa_free(&ctx);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
mbedtls_ecdsa_free(&ctx);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (key_type == HSM_KEY_AES) {
|
||||||
|
uint8_t aes_key[32];
|
||||||
|
int key_size = 0, aes_type = 0;
|
||||||
|
do {
|
||||||
|
r = dkek_decode_key(++kdom,
|
||||||
|
aes_key,
|
||||||
|
apdu.data,
|
||||||
|
apdu.nc,
|
||||||
|
&key_size,
|
||||||
|
&allowed,
|
||||||
|
&allowed_len);
|
||||||
|
} while ((r == CCID_ERR_FILE_NOT_FOUND || r == CCID_WRONG_DKEK) && kdom < MAX_KEY_DOMAINS);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
if (key_size == 32) {
|
||||||
|
aes_type = HSM_KEY_AES_256;
|
||||||
|
}
|
||||||
|
else if (key_size == 24) {
|
||||||
|
aes_type = HSM_KEY_AES_192;
|
||||||
|
}
|
||||||
|
else if (key_size == 16) {
|
||||||
|
aes_type = HSM_KEY_AES_128;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
r = store_keys(aes_key, aes_type, key_id);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ((allowed != NULL && allowed_len > 0) || kdom >= 0) {
|
||||||
|
size_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;
|
||||||
|
if (allowed_len > 0) {
|
||||||
|
*m++ = 0x91;
|
||||||
|
*m++ = allowed_len;
|
||||||
|
memcpy(m, allowed, allowed_len); m += allowed_len;
|
||||||
|
}
|
||||||
|
if (kdom >= 0) {
|
||||||
|
*m++ = 0x92;
|
||||||
|
*m++ = 1;
|
||||||
|
*m++ = kdom;
|
||||||
|
}
|
||||||
|
r = meta_add((KEY_PREFIX << 8) | key_id, meta, meta_len);
|
||||||
|
free(meta);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (res_APDU_size > 0) {
|
||||||
|
file_t *fpk = file_new((EE_CERTIFICATE_PREFIX << 8) | key_id);
|
||||||
|
r = flash_write_data_to_file(fpk, res_APDU, res_APDU_size);
|
||||||
|
if (r != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
low_flash_available();
|
||||||
|
res_APDU_size = 0;
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
105
src/hsm/cmd_key_wrap.c
Normal file
105
src/hsm/cmd_key_wrap.c
Normal file
@@ -0,0 +1,105 @@
|
|||||||
|
/*
|
||||||
|
* 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 "crypto_utils.h"
|
||||||
|
#include "sc_hsm.h"
|
||||||
|
#include "asn1.h"
|
||||||
|
#include "kek.h"
|
||||||
|
|
||||||
|
extern uint8_t get_key_domain(file_t *fkey);
|
||||||
|
|
||||||
|
int cmd_key_wrap() {
|
||||||
|
int key_id = P1(apdu), r = 0;
|
||||||
|
if (P2(apdu) != 0x92) {
|
||||||
|
return SW_WRONG_P1P2();
|
||||||
|
}
|
||||||
|
if (!isUserAuthenticated) {
|
||||||
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
file_t *ef = search_dynamic_file((KEY_PREFIX << 8) | key_id);
|
||||||
|
uint8_t kdom = get_key_domain(ef);
|
||||||
|
if (!ef) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
if (key_has_purpose(ef, ALGO_WRAP) == false) {
|
||||||
|
return SW_CONDITIONS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
file_t *prkd = search_dynamic_file((PRKD_PREFIX << 8) | key_id);
|
||||||
|
if (!prkd) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
const uint8_t *dprkd = file_get_data(prkd);
|
||||||
|
size_t wrap_len = MAX_DKEK_ENCODE_KEY_BUFFER;
|
||||||
|
size_t tag_len = 0;
|
||||||
|
const uint8_t *meta_tag = get_meta_tag(ef, 0x91, &tag_len);
|
||||||
|
if (*dprkd == P15_KEYTYPE_RSA) {
|
||||||
|
mbedtls_rsa_context ctx;
|
||||||
|
mbedtls_rsa_init(&ctx);
|
||||||
|
r = load_private_key_rsa(&ctx, ef);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
mbedtls_rsa_free(&ctx);
|
||||||
|
if (r == CCID_VERIFICATION_FAILED) {
|
||||||
|
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
r = dkek_encode_key(kdom, &ctx, HSM_KEY_RSA, res_APDU, &wrap_len, meta_tag, tag_len);
|
||||||
|
mbedtls_rsa_free(&ctx);
|
||||||
|
}
|
||||||
|
else if (*dprkd == P15_KEYTYPE_ECC) {
|
||||||
|
mbedtls_ecdsa_context ctx;
|
||||||
|
mbedtls_ecdsa_init(&ctx);
|
||||||
|
r = load_private_key_ecdsa(&ctx, ef);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
mbedtls_ecdsa_free(&ctx);
|
||||||
|
if (r == CCID_VERIFICATION_FAILED) {
|
||||||
|
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
r = dkek_encode_key(kdom, &ctx, HSM_KEY_EC, res_APDU, &wrap_len, meta_tag, tag_len);
|
||||||
|
mbedtls_ecdsa_free(&ctx);
|
||||||
|
}
|
||||||
|
else if (*dprkd == P15_KEYTYPE_AES) {
|
||||||
|
uint8_t kdata[32]; //maximum AES key size
|
||||||
|
if (wait_button_pressed() == true) { //timeout
|
||||||
|
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
|
||||||
|
int key_size = file_get_size(ef), aes_type = HSM_KEY_AES;
|
||||||
|
memcpy(kdata, file_get_data(ef), key_size);
|
||||||
|
if (mkek_decrypt(kdata, key_size) != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
if (key_size == 32) {
|
||||||
|
aes_type = HSM_KEY_AES_256;
|
||||||
|
}
|
||||||
|
else if (key_size == 24) {
|
||||||
|
aes_type = HSM_KEY_AES_192;
|
||||||
|
}
|
||||||
|
else if (key_size == 16) {
|
||||||
|
aes_type = HSM_KEY_AES_128;
|
||||||
|
}
|
||||||
|
r = dkek_encode_key(kdom, kdata, aes_type, res_APDU, &wrap_len, meta_tag, tag_len);
|
||||||
|
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||||
|
}
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
res_APDU_size = wrap_len;
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
171
src/hsm/cmd_keypair_gen.c
Normal file
171
src/hsm/cmd_keypair_gen.c
Normal file
@@ -0,0 +1,171 @@
|
|||||||
|
/*
|
||||||
|
* 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 "crypto_utils.h"
|
||||||
|
#include "sc_hsm.h"
|
||||||
|
#include "files.h"
|
||||||
|
#include "asn1.h"
|
||||||
|
#include "cvc.h"
|
||||||
|
#include "oid.h"
|
||||||
|
#include "random.h"
|
||||||
|
#include "kek.h"
|
||||||
|
|
||||||
|
int cmd_keypair_gen() {
|
||||||
|
uint8_t key_id = P1(apdu);
|
||||||
|
if (!isUserAuthenticated) {
|
||||||
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
int ret = 0;
|
||||||
|
|
||||||
|
size_t tout = 0;
|
||||||
|
//sc_asn1_print_tags(apdu.data, apdu.nc);
|
||||||
|
uint8_t *p = NULL;
|
||||||
|
//DEBUG_DATA(apdu.data,apdu.nc);
|
||||||
|
if (asn1_find_tag(apdu.data, apdu.nc, 0x7f49, &tout, &p) && tout > 0 && p != NULL) {
|
||||||
|
size_t oid_len = 0;
|
||||||
|
uint8_t *oid = NULL;
|
||||||
|
if (asn1_find_tag(p, tout, 0x6, &oid_len, &oid) && oid_len > 0 && oid != NULL) {
|
||||||
|
if (memcmp(oid, OID_ID_TA_RSA_V1_5_SHA_256, oid_len) == 0) { //RSA
|
||||||
|
size_t ex_len = 3, ks_len = 2;
|
||||||
|
uint8_t *ex = NULL, *ks = NULL;
|
||||||
|
uint32_t exponent = 65537, key_size = 2048;
|
||||||
|
if (asn1_find_tag(p, tout, 0x82, &ex_len, &ex) && ex_len > 0 && ex != NULL) {
|
||||||
|
uint8_t *dt = 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) {
|
||||||
|
uint8_t *dt = 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",
|
||||||
|
(unsigned long) key_size,
|
||||||
|
(unsigned long) exponent);
|
||||||
|
mbedtls_rsa_context rsa;
|
||||||
|
mbedtls_rsa_init(&rsa);
|
||||||
|
uint8_t index = 0;
|
||||||
|
ret = mbedtls_rsa_gen_key(&rsa, random_gen, &index, key_size, exponent);
|
||||||
|
if (ret != 0) {
|
||||||
|
mbedtls_rsa_free(&rsa);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
if ((res_APDU_size =
|
||||||
|
asn1_cvc_aut(&rsa, HSM_KEY_RSA, res_APDU, 4096, NULL, 0)) == 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
ret = store_keys(&rsa, HSM_KEY_RSA, key_id);
|
||||||
|
if (ret != CCID_OK) {
|
||||||
|
mbedtls_rsa_free(&rsa);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
mbedtls_rsa_free(&rsa);
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_ECDSA_SHA_256, MIN(oid_len, 10)) == 0) { //ECC
|
||||||
|
size_t prime_len;
|
||||||
|
uint8_t *prime = NULL;
|
||||||
|
if (asn1_find_tag(p, tout, 0x81, &prime_len, &prime) != true) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
mbedtls_ecp_group_id ec_id = ec_get_curve_from_prime(prime, prime_len);
|
||||||
|
printf("KEYPAIR ECC %d\r\n", ec_id);
|
||||||
|
if (ec_id == MBEDTLS_ECP_DP_NONE) {
|
||||||
|
return SW_FUNC_NOT_SUPPORTED();
|
||||||
|
}
|
||||||
|
mbedtls_ecdsa_context ecdsa;
|
||||||
|
mbedtls_ecdsa_init(&ecdsa);
|
||||||
|
uint8_t index = 0;
|
||||||
|
ret = mbedtls_ecdsa_genkey(&ecdsa, ec_id, random_gen, &index);
|
||||||
|
if (ret != 0) {
|
||||||
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
size_t l91 = 0, ext_len = 0;
|
||||||
|
uint8_t *p91 = NULL, *ext = NULL;
|
||||||
|
if (asn1_find_tag(apdu.data, apdu.nc, 0x91, &l91, &p91) && p91 != NULL && l91 > 0) {
|
||||||
|
for (int n = 0; n < l91; n++) {
|
||||||
|
if (p91[n] == ALGO_EC_DH_XKEK) {
|
||||||
|
size_t l92 = 0;
|
||||||
|
uint8_t *p92 = NULL;
|
||||||
|
if (!asn1_find_tag(apdu.data, apdu.nc, 0x92, &l92,
|
||||||
|
&p92) || p92 == NULL || l92 == 0) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
if (p92[0] > MAX_KEY_DOMAINS) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
file_t *tf_xkek = search_dynamic_file(EF_XKEK + p92[0]);
|
||||||
|
if (!tf_xkek) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
ext_len = 2 + 2 + strlen(OID_ID_KEY_DOMAIN_UID) + 2 + file_get_size(
|
||||||
|
tf_xkek);
|
||||||
|
ext = (uint8_t *) calloc(1, ext_len);
|
||||||
|
uint8_t *pe = ext;
|
||||||
|
*pe++ = 0x73;
|
||||||
|
*pe++ = ext_len - 2;
|
||||||
|
*pe++ = 0x6;
|
||||||
|
*pe++ = 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++ = 0x80;
|
||||||
|
*pe++ = file_get_size(tf_xkek);
|
||||||
|
memcpy(pe, file_get_data(tf_xkek), file_get_size(tf_xkek));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ((res_APDU_size =
|
||||||
|
asn1_cvc_aut(&ecdsa, HSM_KEY_EC, res_APDU, 4096, ext, ext_len)) == 0) {
|
||||||
|
if (ext) {
|
||||||
|
free(ext);
|
||||||
|
}
|
||||||
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
if (ext) {
|
||||||
|
free(ext);
|
||||||
|
}
|
||||||
|
ret = store_keys(&ecdsa, HSM_KEY_EC, key_id);
|
||||||
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
|
if (ret != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
if (find_and_store_meta_key(key_id) != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
file_t *fpk = file_new((EE_CERTIFICATE_PREFIX << 8) | key_id);
|
||||||
|
ret = flash_write_data_to_file(fpk, res_APDU, res_APDU_size);
|
||||||
|
if (ret != 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
if (apdu.ne == 0) {
|
||||||
|
apdu.ne = res_APDU_size;
|
||||||
|
}
|
||||||
|
low_flash_available();
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
64
src/hsm/cmd_list_keys.c
Normal file
64
src/hsm/cmd_list_keys.c
Normal file
@@ -0,0 +1,64 @@
|
|||||||
|
/*
|
||||||
|
* 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"
|
||||||
|
|
||||||
|
int cmd_list_keys() {
|
||||||
|
/* First we send DEV private key */
|
||||||
|
/* Both below conditions should be always TRUE */
|
||||||
|
if (search_by_fid(EF_PRKD_DEV, NULL, SPECIFY_EF)) {
|
||||||
|
res_APDU[res_APDU_size++] = EF_PRKD_DEV >> 8;
|
||||||
|
res_APDU[res_APDU_size++] = EF_PRKD_DEV & 0xff;
|
||||||
|
}
|
||||||
|
if (search_by_fid(EF_KEY_DEV, NULL, SPECIFY_EF)) {
|
||||||
|
res_APDU[res_APDU_size++] = EF_KEY_DEV >> 8;
|
||||||
|
res_APDU[res_APDU_size++] = EF_KEY_DEV & 0xff;
|
||||||
|
}
|
||||||
|
//first CC
|
||||||
|
for (int i = 0; i < dynamic_files; i++) {
|
||||||
|
file_t *f = &dynamic_file[i];
|
||||||
|
if ((f->fid & 0xff00) == (KEY_PREFIX << 8)) {
|
||||||
|
res_APDU[res_APDU_size++] = KEY_PREFIX;
|
||||||
|
res_APDU[res_APDU_size++] = f->fid & 0xff;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
for (int i = 0; i < dynamic_files; i++) {
|
||||||
|
file_t *f = &dynamic_file[i];
|
||||||
|
if ((f->fid & 0xff00) == (PRKD_PREFIX << 8)) {
|
||||||
|
res_APDU[res_APDU_size++] = PRKD_PREFIX;
|
||||||
|
res_APDU[res_APDU_size++] = f->fid & 0xff;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
//second CD
|
||||||
|
for (int i = 0; i < dynamic_files; i++) {
|
||||||
|
file_t *f = &dynamic_file[i];
|
||||||
|
if ((f->fid & 0xff00) == (CD_PREFIX << 8)) {
|
||||||
|
res_APDU[res_APDU_size++] = CD_PREFIX;
|
||||||
|
res_APDU[res_APDU_size++] = f->fid & 0xff;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
for (int i = 0; i < dynamic_files; i++) {
|
||||||
|
file_t *f = &dynamic_file[i];
|
||||||
|
if ((f->fid & 0xff00) == (DCOD_PREFIX << 8)) {
|
||||||
|
res_APDU[res_APDU_size++] = DCOD_PREFIX;
|
||||||
|
res_APDU[res_APDU_size++] = f->fid & 0xff;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
84
src/hsm/cmd_mse.c
Normal file
84
src/hsm/cmd_mse.c
Normal file
@@ -0,0 +1,84 @@
|
|||||||
|
/*
|
||||||
|
* 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 "asn1.h"
|
||||||
|
#include "oid.h"
|
||||||
|
#include "eac.h"
|
||||||
|
#include "files.h"
|
||||||
|
#include "cvc.h"
|
||||||
|
|
||||||
|
file_t *ef_puk_aut = NULL;
|
||||||
|
|
||||||
|
int cmd_mse() {
|
||||||
|
int p1 = P1(apdu);
|
||||||
|
int p2 = P2(apdu);
|
||||||
|
if (p2 != 0xA4 && p2 != 0xA6 && p2 != 0xAA && p2 != 0xB4 && p2 != 0xB6 && p2 != 0xB8) {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
if (p1 & 0x1) { //SET
|
||||||
|
uint16_t tag = 0x0;
|
||||||
|
uint8_t *tag_data = NULL, *p = NULL;
|
||||||
|
size_t tag_len = 0;
|
||||||
|
while (walk_tlv(apdu.data, apdu.nc, &p, &tag, &tag_len, &tag_data)) {
|
||||||
|
if (tag == 0x80) {
|
||||||
|
if (p2 == 0xA4) {
|
||||||
|
if (tag_len == 10 &&
|
||||||
|
memcmp(tag_data, OID_ID_CA_ECDH_AES_CBC_CMAC_128, tag_len) == 0) {
|
||||||
|
sm_set_protocol(MSE_AES);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (tag == 0x83) {
|
||||||
|
if (tag_len == 1) {
|
||||||
|
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if (p2 == 0xB6) {
|
||||||
|
if (puk_store_select_chr(tag_data) == CCID_OK) {
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (p2 == 0xA4) { /* Aut */
|
||||||
|
for (int i = 0; i < MAX_PUK; i++) {
|
||||||
|
file_t *ef = search_dynamic_file(EF_PUK + i);
|
||||||
|
if (!ef) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
if (!file_has_data(ef)) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
size_t chr_len = 0;
|
||||||
|
const uint8_t *chr = cvc_get_chr(file_get_data(ef),
|
||||||
|
file_get_size(ef),
|
||||||
|
&chr_len);
|
||||||
|
if (memcmp(chr, tag_data, chr_len) == 0) {
|
||||||
|
ef_puk_aut = ef;
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
162
src/hsm/cmd_pso.c
Normal file
162
src/hsm/cmd_pso.c
Normal file
@@ -0,0 +1,162 @@
|
|||||||
|
/*
|
||||||
|
* 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 "oid.h"
|
||||||
|
#include "asn1.h"
|
||||||
|
#include "cvc.h"
|
||||||
|
|
||||||
|
extern int add_cert_puk_store(const uint8_t *data, size_t data_len, bool copy);
|
||||||
|
extern PUK *current_puk;
|
||||||
|
|
||||||
|
int cmd_pso() {
|
||||||
|
uint8_t p1 = P1(apdu), p2 = P2(apdu);
|
||||||
|
if (p1 == 0x0 && (p2 == 0x92 || p2 == 0xAE || p2 == 0xBE)) { /* Verify certificate */
|
||||||
|
if (apdu.nc == 0) {
|
||||||
|
return SW_WRONG_LENGTH();
|
||||||
|
}
|
||||||
|
if (current_puk == NULL) {
|
||||||
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
if (apdu.data[0] != 0x7F || apdu.data[1] != 0x21) {
|
||||||
|
uint8_t tlv_len = 2 + format_tlv_len(apdu.nc, NULL);
|
||||||
|
memmove(apdu.data + tlv_len, apdu.data, apdu.nc);
|
||||||
|
memcpy(apdu.data, "\x7F\x21", 2);
|
||||||
|
format_tlv_len(apdu.nc, apdu.data + 2);
|
||||||
|
apdu.nc += tlv_len;
|
||||||
|
}
|
||||||
|
int r = cvc_verify(apdu.data, apdu.nc, current_puk->cvcert, current_puk->cvcert_len);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
if (r == CCID_WRONG_DATA) {
|
||||||
|
return SW_DATA_INVALID();
|
||||||
|
}
|
||||||
|
else if (r == CCID_WRONG_SIGNATURE) {
|
||||||
|
return SW_CONDITIONS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
for (int i = 0; i < 0xfe; i++) {
|
||||||
|
uint16_t fid = (CA_CERTIFICATE_PREFIX << 8) | i;
|
||||||
|
file_t *ca_ef = search_dynamic_file(fid);
|
||||||
|
if (!ca_ef) {
|
||||||
|
ca_ef = file_new(fid);
|
||||||
|
flash_write_data_to_file(ca_ef, apdu.data, apdu.nc);
|
||||||
|
if (add_cert_puk_store(file_get_data(ca_ef), file_get_size(ca_ef),
|
||||||
|
false) != CCID_OK) {
|
||||||
|
return SW_FILE_FULL();
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t chr_len = 0;
|
||||||
|
const uint8_t *chr = cvc_get_chr(apdu.data, apdu.nc, &chr_len);
|
||||||
|
if (chr == NULL) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
size_t puk_len = 0, puk_bin_len = 0;
|
||||||
|
const uint8_t *puk = cvc_get_pub(apdu.data, apdu.nc, &puk_len), *puk_bin = NULL;
|
||||||
|
if (puk == NULL) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
size_t oid_len = 0;
|
||||||
|
const uint8_t *oid = cvc_get_field(puk, puk_len, &oid_len, 0x6);
|
||||||
|
if (oid == NULL) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
if (memcmp(oid, OID_ID_TA_RSA, 9) == 0) { //RSA
|
||||||
|
puk_bin = cvc_get_field(puk, puk_len, &puk_bin_len, 0x81);
|
||||||
|
if (!puk_bin) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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 grp;
|
||||||
|
mbedtls_ecp_group_init(&grp);
|
||||||
|
if (mbedtls_ecp_group_load(&grp, ec_id) != 0) {
|
||||||
|
mbedtls_ecp_group_free(&grp);
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
size_t plen = mbedtls_mpi_size(&grp.P);
|
||||||
|
size_t t86_len = 0;
|
||||||
|
const uint8_t *t86 = cvc_get_field(puk, puk_len, &t86_len, 0x86);
|
||||||
|
if (mbedtls_ecp_get_type(&grp) == MBEDTLS_ECP_TYPE_MONTGOMERY) {
|
||||||
|
if (plen != t86_len) {
|
||||||
|
mbedtls_ecp_group_free(&grp);
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
puk_bin = t86;
|
||||||
|
puk_bin_len = t86_len;
|
||||||
|
}
|
||||||
|
else if (mbedtls_ecp_get_type(&grp) == MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS) {
|
||||||
|
if (t86[0] == 0x2 || t86[0] == 0x3) {
|
||||||
|
if (t86_len != plen + 1) {
|
||||||
|
mbedtls_ecp_group_free(&grp);
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (t86[0] == 0x4) {
|
||||||
|
if (t86_len != 2 * plen + 1) {
|
||||||
|
mbedtls_ecp_group_free(&grp);
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
mbedtls_ecp_group_free(&grp);
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
puk_bin = t86 + 1;
|
||||||
|
puk_bin_len = plen;
|
||||||
|
}
|
||||||
|
mbedtls_ecp_group_free(&grp);
|
||||||
|
if (!puk_bin) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
file_t *cd_ef = file_new((CD_PREFIX << 8) | i);
|
||||||
|
size_t cd_len = asn1_build_cert_description(chr,
|
||||||
|
chr_len,
|
||||||
|
puk_bin,
|
||||||
|
puk_bin_len,
|
||||||
|
fid,
|
||||||
|
NULL,
|
||||||
|
0);
|
||||||
|
if (cd_len == 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
uint8_t *buf = (uint8_t *) calloc(cd_len, sizeof(uint8_t));
|
||||||
|
int r = asn1_build_cert_description(chr,
|
||||||
|
chr_len,
|
||||||
|
puk_bin,
|
||||||
|
puk_bin_len,
|
||||||
|
fid,
|
||||||
|
buf,
|
||||||
|
cd_len);
|
||||||
|
flash_write_data_to_file(cd_ef, buf, cd_len);
|
||||||
|
free(buf);
|
||||||
|
if (r == 0) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
low_flash_available();
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
96
src/hsm/cmd_puk_auth.c
Normal file
96
src/hsm/cmd_puk_auth.c
Normal file
@@ -0,0 +1,96 @@
|
|||||||
|
/*
|
||||||
|
* 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 "cvc.h"
|
||||||
|
|
||||||
|
int cmd_puk_auth() {
|
||||||
|
uint8_t p1 = P1(apdu), p2 = P2(apdu);
|
||||||
|
file_t *ef_puk = search_by_fid(EF_PUKAUT, NULL, SPECIFY_EF);
|
||||||
|
if (!file_has_data(ef_puk)) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
uint8_t *puk_data = file_get_data(ef_puk);
|
||||||
|
if (apdu.nc > 0) {
|
||||||
|
if (p1 == 0x0 || p1 == 0x1) {
|
||||||
|
file_t *ef = NULL;
|
||||||
|
if (p1 == 0x0) { /* Add */
|
||||||
|
if (p2 != 0x0) {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
for (int i = 0; i < puk_data[0]; i++) {
|
||||||
|
ef = search_dynamic_file(EF_PUK + i);
|
||||||
|
if (!ef) { /* Never should not happen */
|
||||||
|
return SW_MEMORY_FAILURE();
|
||||||
|
}
|
||||||
|
if (!file_has_data(ef)) { /* found first empty slot */
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
uint8_t *tmp = (uint8_t *) calloc(file_get_size(ef_puk), sizeof(uint8_t));
|
||||||
|
memcpy(tmp, puk_data, file_get_size(ef_puk));
|
||||||
|
tmp[1] = puk_data[1] - 1;
|
||||||
|
flash_write_data_to_file(ef_puk, tmp, file_get_size(ef_puk));
|
||||||
|
puk_data = file_get_data(ef_puk);
|
||||||
|
free(tmp);
|
||||||
|
}
|
||||||
|
else if (p1 == 0x1) { /* Replace */
|
||||||
|
if (p2 >= puk_data[0]) {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
ef = search_dynamic_file(EF_PUK + p2);
|
||||||
|
if (!ef) { /* Never should not happen */
|
||||||
|
return SW_MEMORY_FAILURE();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
flash_write_data_to_file(ef, apdu.data, apdu.nc);
|
||||||
|
low_flash_available();
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (p1 == 0x2) {
|
||||||
|
if (p2 >= puk_data[0]) {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
file_t *ef = search_dynamic_file(EF_PUK + p2);
|
||||||
|
if (!ef) {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
if (!file_has_data(ef)) {
|
||||||
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
size_t chr_len = 0;
|
||||||
|
const uint8_t *chr = cvc_get_chr(file_get_data(ef), file_get_size(ef), &chr_len);
|
||||||
|
if (chr) {
|
||||||
|
memcpy(res_APDU, chr, chr_len);
|
||||||
|
res_APDU_size = chr_len;
|
||||||
|
}
|
||||||
|
return set_res_sw(0x90, puk_status[p2]);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
memcpy(res_APDU, puk_data, 3);
|
||||||
|
res_APDU[3] = 0;
|
||||||
|
for (int i = 0; i < puk_data[0]; i++) {
|
||||||
|
res_APDU[3] += puk_status[i];
|
||||||
|
}
|
||||||
|
res_APDU_size = 4;
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
101
src/hsm/cmd_read_binary.c
Normal file
101
src/hsm/cmd_read_binary.c
Normal file
@@ -0,0 +1,101 @@
|
|||||||
|
/*
|
||||||
|
* 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"
|
||||||
|
|
||||||
|
int cmd_read_binary() {
|
||||||
|
uint16_t fid = 0x0;
|
||||||
|
uint32_t offset = 0;
|
||||||
|
uint8_t ins = INS(apdu), p1 = P1(apdu), p2 = P2(apdu);
|
||||||
|
const file_t *ef = NULL;
|
||||||
|
|
||||||
|
if ((ins & 0x1) == 0) {
|
||||||
|
if ((p1 & 0x80) != 0) {
|
||||||
|
if (!(ef = search_by_fid(p1 & 0x1f, NULL, SPECIFY_EF))) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
offset = p2;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
offset = make_uint16_t(p1, p2) & 0x7fff;
|
||||||
|
ef = currentEF;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if (p1 == 0 && (p2 & 0xE0) == 0 && (p2 & 0x1f) != 0 && (p2 & 0x1f) != 0x1f) {
|
||||||
|
if (!(ef = search_by_fid(p2 & 0x1f, NULL, SPECIFY_EF))) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
uint16_t file_id = make_uint16_t(p1, p2); // & 0x7fff;
|
||||||
|
if (file_id == 0x0) {
|
||||||
|
ef = currentEF;
|
||||||
|
}
|
||||||
|
else if (!(ef =
|
||||||
|
search_by_fid(file_id, NULL,
|
||||||
|
SPECIFY_EF)) && !(ef = search_dynamic_file(file_id))) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (apdu.data[0] != 0x54) {
|
||||||
|
return SW_WRONG_DATA();
|
||||||
|
}
|
||||||
|
|
||||||
|
offset = 0;
|
||||||
|
for (int d = 0; d < apdu.data[1]; d++) {
|
||||||
|
offset |= apdu.data[2 + d] << (apdu.data[1] - 1 - d) * 8;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((fid >> 8) == KEY_PREFIX || !authenticate_action(ef, ACL_OP_READ_SEARCH)) {
|
||||||
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
if (ef->data) {
|
||||||
|
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
|
||||||
|
if (offset > data_len) {
|
||||||
|
return SW_WRONG_P1P2();
|
||||||
|
}
|
||||||
|
uint16_t maxle = data_len - offset;
|
||||||
|
if (apdu.ne > maxle) {
|
||||||
|
apdu.ne = maxle;
|
||||||
|
}
|
||||||
|
if (offset) {
|
||||||
|
memmove(res_APDU, res_APDU + offset, res_APDU_size - offset);
|
||||||
|
//res_APDU += offset;
|
||||||
|
res_APDU_size -= offset;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
uint16_t data_len = file_get_size(ef);
|
||||||
|
if (offset > data_len) {
|
||||||
|
return SW_WRONG_P1P2();
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16_t maxle = data_len - offset;
|
||||||
|
if (apdu.ne > maxle) {
|
||||||
|
apdu.ne = maxle;
|
||||||
|
}
|
||||||
|
memcpy(res_APDU, file_get_data(ef) + offset, data_len - offset);
|
||||||
|
res_APDU_size = data_len - offset;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
110
src/hsm/cmd_reset_retry.c
Normal file
110
src/hsm/cmd_reset_retry.c
Normal file
@@ -0,0 +1,110 @@
|
|||||||
|
/*
|
||||||
|
* 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 "crypto_utils.h"
|
||||||
|
#include "sc_hsm.h"
|
||||||
|
#include "kek.h"
|
||||||
|
|
||||||
|
int cmd_reset_retry() {
|
||||||
|
if (P2(apdu) != 0x81) {
|
||||||
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
if (!file_sopin || !file_pin1) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
if (!file_has_data(file_sopin)) {
|
||||||
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
uint16_t opts = get_device_options();
|
||||||
|
if (!(opts & HSM_OPT_RRC)) {
|
||||||
|
return SW_COMMAND_NOT_ALLOWED();
|
||||||
|
}
|
||||||
|
if (P1(apdu) == 0x0 || P1(apdu) == 0x2) {
|
||||||
|
int newpin_len = 0;
|
||||||
|
if (P1(apdu) == 0x0) {
|
||||||
|
if (apdu.nc <= 8) {
|
||||||
|
return SW_WRONG_LENGTH();
|
||||||
|
}
|
||||||
|
uint16_t r = check_pin(file_sopin, apdu.data, 8);
|
||||||
|
if (r != 0x9000) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
newpin_len = apdu.nc - 8;
|
||||||
|
has_session_sopin = true;
|
||||||
|
hash_multi(apdu.data, 8, session_sopin);
|
||||||
|
}
|
||||||
|
else if (P1(apdu) == 0x2) {
|
||||||
|
if (!has_session_sopin) {
|
||||||
|
return SW_CONDITIONS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
if (apdu.nc > 16) {
|
||||||
|
return SW_WRONG_LENGTH();
|
||||||
|
}
|
||||||
|
newpin_len = apdu.nc;
|
||||||
|
}
|
||||||
|
uint8_t dhash[33];
|
||||||
|
dhash[0] = newpin_len;
|
||||||
|
double_hash_pin(apdu.data + (apdu.nc - newpin_len), newpin_len, dhash + 1);
|
||||||
|
flash_write_data_to_file(file_pin1, dhash, sizeof(dhash));
|
||||||
|
if (pin_reset_retries(file_pin1, true) != CCID_OK) {
|
||||||
|
return SW_MEMORY_FAILURE();
|
||||||
|
}
|
||||||
|
uint8_t mkek[MKEK_SIZE];
|
||||||
|
int r = load_mkek(mkek); //loads the MKEK with SO pin
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
hash_multi(apdu.data + (apdu.nc - newpin_len), newpin_len, session_pin);
|
||||||
|
has_session_pin = true;
|
||||||
|
r = store_mkek(mkek);
|
||||||
|
release_mkek(mkek);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
low_flash_available();
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
|
else if (P1(apdu) == 0x1 || P1(apdu) == 0x3) {
|
||||||
|
if (!(opts & HSM_OPT_RRC_RESET_ONLY)) {
|
||||||
|
return SW_COMMAND_NOT_ALLOWED();
|
||||||
|
}
|
||||||
|
if (P1(apdu) == 0x1) {
|
||||||
|
if (apdu.nc != 8) {
|
||||||
|
return SW_WRONG_LENGTH();
|
||||||
|
}
|
||||||
|
uint16_t r = check_pin(file_sopin, apdu.data, 8);
|
||||||
|
if (r != 0x9000) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
has_session_sopin = true;
|
||||||
|
hash_multi(apdu.data, 8, session_sopin);
|
||||||
|
}
|
||||||
|
else if (P1(apdu) == 0x3) {
|
||||||
|
if (!has_session_sopin) {
|
||||||
|
return SW_CONDITIONS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
if (apdu.nc != 0) {
|
||||||
|
return SW_WRONG_LENGTH();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (pin_reset_retries(file_pin1, true) != CCID_OK) {
|
||||||
|
return SW_MEMORY_FAILURE();
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
135
src/hsm/cmd_select.c
Normal file
135
src/hsm/cmd_select.c
Normal file
@@ -0,0 +1,135 @@
|
|||||||
|
/*
|
||||||
|
* 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 "version.h"
|
||||||
|
|
||||||
|
void select_file(file_t *pe) {
|
||||||
|
if (!pe) {
|
||||||
|
currentDF = (file_t *) MF;
|
||||||
|
currentEF = NULL;
|
||||||
|
}
|
||||||
|
else if (pe->type & FILE_TYPE_INTERNAL_EF) {
|
||||||
|
currentEF = pe;
|
||||||
|
currentDF = &file_entries[pe->parent];
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
currentDF = pe;
|
||||||
|
}
|
||||||
|
if (currentEF == file_openpgp || currentEF == file_sc_hsm) {
|
||||||
|
selected_applet = currentEF;
|
||||||
|
//sc_hsm_unload(); //reset auth status
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
int cmd_select() {
|
||||||
|
uint8_t p1 = P1(apdu);
|
||||||
|
uint8_t p2 = P2(apdu);
|
||||||
|
file_t *pe = NULL;
|
||||||
|
uint16_t fid = 0x0;
|
||||||
|
|
||||||
|
// Only "first or only occurence" supported
|
||||||
|
//if ((p2 & 0xF3) != 0x00) {
|
||||||
|
// return SW_INCORRECT_P1P2();
|
||||||
|
//}
|
||||||
|
|
||||||
|
if (apdu.nc >= 2) {
|
||||||
|
fid = get_uint16_t(apdu.data, 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
//if ((fid & 0xff00) == (KEY_PREFIX << 8))
|
||||||
|
// fid = (PRKD_PREFIX << 8) | (fid & 0xff);
|
||||||
|
|
||||||
|
uint8_t pfx = fid >> 8;
|
||||||
|
if (pfx == PRKD_PREFIX ||
|
||||||
|
pfx == CD_PREFIX ||
|
||||||
|
pfx == CA_CERTIFICATE_PREFIX ||
|
||||||
|
pfx == KEY_PREFIX ||
|
||||||
|
pfx == EE_CERTIFICATE_PREFIX ||
|
||||||
|
pfx == DCOD_PREFIX ||
|
||||||
|
pfx == DATA_PREFIX ||
|
||||||
|
pfx == PROT_DATA_PREFIX) {
|
||||||
|
if (!(pe = search_dynamic_file(fid)) && !(pe = search_by_fid(fid, NULL, SPECIFY_EF))) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!pe) {
|
||||||
|
if (p1 == 0x0) { //Select MF, DF or EF - File identifier or absent
|
||||||
|
if (apdu.nc == 0) {
|
||||||
|
pe = (file_t *) MF;
|
||||||
|
//ac_fini();
|
||||||
|
}
|
||||||
|
else if (apdu.nc == 2) {
|
||||||
|
if (!(pe = search_by_fid(fid, NULL, SPECIFY_ANY))) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (p1 == 0x01) { //Select child DF - DF identifier
|
||||||
|
if (!(pe = search_by_fid(fid, currentDF, SPECIFY_DF))) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (p1 == 0x02) { //Select EF under the current DF - EF identifier
|
||||||
|
if (!(pe = search_by_fid(fid, currentDF, SPECIFY_EF))) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (p1 == 0x03) { //Select parent DF of the current DF - Absent
|
||||||
|
if (apdu.nc != 0) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (p1 == 0x04) { //Select by DF name - e.g., [truncated] application identifier
|
||||||
|
if (!(pe = search_by_name(apdu.data, apdu.nc))) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
if (card_terminated) {
|
||||||
|
return set_res_sw(0x62, 0x85);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (p1 == 0x08) { //Select from the MF - Path without the MF identifier
|
||||||
|
if (!(pe = search_by_path(apdu.data, apdu.nc, MF))) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
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))) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if ((p2 & 0xfc) == 0x00 || (p2 & 0xfc) == 0x04) {
|
||||||
|
process_fci(pe, 0);
|
||||||
|
if (pe == file_sc_hsm) {
|
||||||
|
res_APDU[res_APDU_size++] = 0x85;
|
||||||
|
res_APDU[res_APDU_size++] = 5;
|
||||||
|
uint16_t opts = get_device_options();
|
||||||
|
res_APDU[res_APDU_size++] = opts >> 8;
|
||||||
|
res_APDU[res_APDU_size++] = opts & 0xff;
|
||||||
|
res_APDU[res_APDU_size++] = 0xFF;
|
||||||
|
res_APDU[res_APDU_size++] = HSM_VERSION_MAJOR;
|
||||||
|
res_APDU[res_APDU_size++] = HSM_VERSION_MINOR;
|
||||||
|
res_APDU[1] = res_APDU_size - 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
select_file(pe);
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
35
src/hsm/cmd_session_pin.c
Normal file
35
src/hsm/cmd_session_pin.c
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
/*
|
||||||
|
* 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 "random.h"
|
||||||
|
#include "eac.h"
|
||||||
|
|
||||||
|
int cmd_session_pin() {
|
||||||
|
if (P1(apdu) == 0x01 && P2(apdu) == 0x81) {
|
||||||
|
memcpy(sm_session_pin, random_bytes_get(8), 8);
|
||||||
|
sm_session_pin_len = 8;
|
||||||
|
|
||||||
|
memcpy(res_APDU, sm_session_pin, sm_session_pin_len);
|
||||||
|
res_APDU_size = sm_session_pin_len;
|
||||||
|
apdu.ne = sm_session_pin_len;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
289
src/hsm/cmd_signature.c
Normal file
289
src/hsm/cmd_signature.c
Normal file
@@ -0,0 +1,289 @@
|
|||||||
|
/*
|
||||||
|
* 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 "crypto_utils.h"
|
||||||
|
#include "sc_hsm.h"
|
||||||
|
#include "asn1.h"
|
||||||
|
#include "mbedtls/oid.h"
|
||||||
|
#include "random.h"
|
||||||
|
|
||||||
|
//-----
|
||||||
|
/* From OpenSC */
|
||||||
|
static const uint8_t hdr_md5[] = {
|
||||||
|
0x30, 0x20, 0x30, 0x0c, 0x06, 0x08, 0x2a, 0x86, 0x48, 0x86, 0xf7,
|
||||||
|
0x0d, 0x02, 0x05, 0x05, 0x00, 0x04, 0x10
|
||||||
|
};
|
||||||
|
static const uint8_t hdr_sha1[] = {
|
||||||
|
0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x0e, 0x03, 0x02, 0x1a,
|
||||||
|
0x05, 0x00, 0x04, 0x14
|
||||||
|
};
|
||||||
|
static const uint8_t hdr_sha256[] = {
|
||||||
|
0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65,
|
||||||
|
0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20
|
||||||
|
};
|
||||||
|
static const uint8_t hdr_sha384[] = {
|
||||||
|
0x30, 0x41, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65,
|
||||||
|
0x03, 0x04, 0x02, 0x02, 0x05, 0x00, 0x04, 0x30
|
||||||
|
};
|
||||||
|
static const uint8_t hdr_sha512[] = {
|
||||||
|
0x30, 0x51, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65,
|
||||||
|
0x03, 0x04, 0x02, 0x03, 0x05, 0x00, 0x04, 0x40
|
||||||
|
};
|
||||||
|
static const uint8_t hdr_sha224[] = {
|
||||||
|
0x30, 0x2d, 0x30, 0x0d, 0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65,
|
||||||
|
0x03, 0x04, 0x02, 0x04, 0x05, 0x00, 0x04, 0x1c
|
||||||
|
};
|
||||||
|
static const uint8_t hdr_ripemd160[] = {
|
||||||
|
0x30, 0x21, 0x30, 0x09, 0x06, 0x05, 0x2b, 0x24, 0x03, 0x02, 0x01,
|
||||||
|
0x05, 0x00, 0x04, 0x14
|
||||||
|
};
|
||||||
|
static const struct digest_info_prefix {
|
||||||
|
mbedtls_md_type_t algorithm;
|
||||||
|
const uint8_t *hdr;
|
||||||
|
size_t hdr_len;
|
||||||
|
size_t hash_len;
|
||||||
|
} digest_info_prefix[] = {
|
||||||
|
{ MBEDTLS_MD_MD5, hdr_md5, sizeof(hdr_md5), 16 },
|
||||||
|
{ MBEDTLS_MD_SHA1, hdr_sha1, sizeof(hdr_sha1), 20 },
|
||||||
|
{ MBEDTLS_MD_SHA256, hdr_sha256, sizeof(hdr_sha256), 32 },
|
||||||
|
{ MBEDTLS_MD_SHA384, hdr_sha384, sizeof(hdr_sha384), 48 },
|
||||||
|
{ MBEDTLS_MD_SHA512, hdr_sha512, sizeof(hdr_sha512), 64 },
|
||||||
|
{ MBEDTLS_MD_SHA224, hdr_sha224, sizeof(hdr_sha224), 28 },
|
||||||
|
{ MBEDTLS_MD_RIPEMD160, hdr_ripemd160, sizeof(hdr_ripemd160), 20 },
|
||||||
|
{ 0, NULL, 0, 0 }
|
||||||
|
};
|
||||||
|
int pkcs1_strip_digest_info_prefix(mbedtls_md_type_t *algorithm,
|
||||||
|
const uint8_t *in_dat,
|
||||||
|
size_t in_len,
|
||||||
|
uint8_t *out_dat,
|
||||||
|
size_t *out_len) {
|
||||||
|
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;
|
||||||
|
const uint8_t *hdr = digest_info_prefix[i].hdr;
|
||||||
|
if (in_len == (hdr_len + hash_len) && !memcmp(in_dat, hdr, hdr_len)) {
|
||||||
|
if (algorithm) {
|
||||||
|
*algorithm = digest_info_prefix[i].algorithm;
|
||||||
|
}
|
||||||
|
if (out_dat == NULL) {
|
||||||
|
return CCID_OK;
|
||||||
|
}
|
||||||
|
if (*out_len < hash_len) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
memmove(out_dat, in_dat + hdr_len, hash_len);
|
||||||
|
*out_len = hash_len;
|
||||||
|
return CCID_OK;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
//-----
|
||||||
|
|
||||||
|
int cmd_signature() {
|
||||||
|
uint8_t key_id = P1(apdu);
|
||||||
|
uint8_t p2 = P2(apdu);
|
||||||
|
mbedtls_md_type_t md = MBEDTLS_MD_NONE;
|
||||||
|
file_t *fkey;
|
||||||
|
if (!isUserAuthenticated) {
|
||||||
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
if (!(fkey = search_dynamic_file((KEY_PREFIX << 8) | key_id)) || !file_has_data(fkey)) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
if (get_key_counter(fkey) == 0) {
|
||||||
|
return SW_FILE_FULL();
|
||||||
|
}
|
||||||
|
if (key_has_purpose(fkey, p2) == false) {
|
||||||
|
return SW_CONDITIONS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
int key_size = file_get_size(fkey);
|
||||||
|
if (p2 == ALGO_RSA_PKCS1_SHA1 || p2 == ALGO_RSA_PSS_SHA1 || p2 == ALGO_EC_SHA1) {
|
||||||
|
md = MBEDTLS_MD_SHA1;
|
||||||
|
}
|
||||||
|
else if (p2 == ALGO_RSA_PKCS1_SHA256 || p2 == ALGO_RSA_PSS_SHA256 || p2 == ALGO_EC_SHA256) {
|
||||||
|
md = MBEDTLS_MD_SHA256;
|
||||||
|
}
|
||||||
|
else if (p2 == ALGO_EC_SHA224 || p2 == ALGO_RSA_PKCS1_SHA224 || p2 == ALGO_RSA_PSS_SHA224) {
|
||||||
|
md = MBEDTLS_MD_SHA224;
|
||||||
|
}
|
||||||
|
else if (p2 == ALGO_EC_SHA384 || p2 == ALGO_RSA_PKCS1_SHA384 || p2 == ALGO_RSA_PSS_SHA384) {
|
||||||
|
md = MBEDTLS_MD_SHA384;
|
||||||
|
}
|
||||||
|
else if (p2 == ALGO_EC_SHA512 || p2 == ALGO_RSA_PKCS1_SHA512 || p2 == ALGO_RSA_PSS_SHA512) {
|
||||||
|
md = MBEDTLS_MD_SHA512;
|
||||||
|
}
|
||||||
|
if (p2 == ALGO_RSA_PKCS1_SHA1 || p2 == ALGO_RSA_PSS_SHA1 || p2 == ALGO_EC_SHA1 ||
|
||||||
|
p2 == ALGO_RSA_PKCS1_SHA256 || p2 == ALGO_RSA_PSS_SHA256 || p2 == ALGO_EC_SHA256 ||
|
||||||
|
p2 == ALGO_EC_SHA224 || p2 == ALGO_EC_SHA384 || p2 == ALGO_EC_SHA512 ||
|
||||||
|
p2 == ALGO_RSA_PKCS1_SHA224 || p2 == ALGO_RSA_PKCS1_SHA384 || p2 == ALGO_RSA_PKCS1_SHA512 ||
|
||||||
|
p2 == ALGO_RSA_PSS_SHA224 || p2 == ALGO_RSA_PSS_SHA384 || p2 == ALGO_RSA_PSS_SHA512) {
|
||||||
|
generic_hash(md, apdu.data, apdu.nc, apdu.data);
|
||||||
|
apdu.nc = mbedtls_md_get_size(mbedtls_md_info_from_type(md));
|
||||||
|
}
|
||||||
|
if (p2 >= ALGO_RSA_RAW && p2 <= ALGO_RSA_PSS_SHA512) {
|
||||||
|
mbedtls_rsa_context ctx;
|
||||||
|
mbedtls_rsa_init(&ctx);
|
||||||
|
|
||||||
|
int r = load_private_key_rsa(&ctx, fkey);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
mbedtls_rsa_free(&ctx);
|
||||||
|
if (r == CCID_VERIFICATION_FAILED) {
|
||||||
|
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
uint8_t *hash = apdu.data;
|
||||||
|
size_t hash_len = apdu.nc;
|
||||||
|
if (p2 == ALGO_RSA_PKCS1) { //DigestInfo attached
|
||||||
|
size_t nc = apdu.nc;
|
||||||
|
if (pkcs1_strip_digest_info_prefix(&md, apdu.data, apdu.nc, apdu.data,
|
||||||
|
&nc) != CCID_OK) { //gets the MD algo id and strips it off
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
apdu.nc = nc;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
//sc_asn1_print_tags(apdu.data, apdu.nc);
|
||||||
|
size_t tout = 0, oid_len = 0;
|
||||||
|
uint8_t *p = NULL, *oid = NULL;
|
||||||
|
if (asn1_find_tag(apdu.data, apdu.nc, 0x30, &tout, &p) && tout > 0 && p != NULL) {
|
||||||
|
size_t tout30 = 0;
|
||||||
|
uint8_t *c30 = NULL;
|
||||||
|
if (asn1_find_tag(p, tout, 0x30, &tout30, &c30) && tout30 > 0 && c30 != NULL) {
|
||||||
|
asn1_find_tag(c30, tout30, 0x6, &oid_len, &oid);
|
||||||
|
}
|
||||||
|
asn1_find_tag(p, tout, 0x4, &hash_len, &hash);
|
||||||
|
}
|
||||||
|
if (oid && oid_len > 0) {
|
||||||
|
if (memcmp(oid, MBEDTLS_OID_DIGEST_ALG_SHA1, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA1;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, MBEDTLS_OID_DIGEST_ALG_SHA224, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA224;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, MBEDTLS_OID_DIGEST_ALG_SHA256, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA256;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, MBEDTLS_OID_DIGEST_ALG_SHA384, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA384;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, MBEDTLS_OID_DIGEST_ALG_SHA512, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA512;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (p2 >= ALGO_RSA_PSS && p2 <= ALGO_RSA_PSS_SHA512) {
|
||||||
|
if (p2 == ALGO_RSA_PSS && !oid) {
|
||||||
|
if (apdu.nc == 20) { //default is sha1
|
||||||
|
md = MBEDTLS_MD_SHA1;
|
||||||
|
}
|
||||||
|
else if (apdu.nc == 28) {
|
||||||
|
md = MBEDTLS_MD_SHA224;
|
||||||
|
}
|
||||||
|
else if (apdu.nc == 32) {
|
||||||
|
md = MBEDTLS_MD_SHA256;
|
||||||
|
}
|
||||||
|
else if (apdu.nc == 48) {
|
||||||
|
md = MBEDTLS_MD_SHA384;
|
||||||
|
}
|
||||||
|
else if (apdu.nc == 64) {
|
||||||
|
md = MBEDTLS_MD_SHA512;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
mbedtls_rsa_set_padding(&ctx, MBEDTLS_RSA_PKCS_V21, md);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (md == MBEDTLS_MD_NONE) {
|
||||||
|
if (apdu.nc < key_size) { //needs padding
|
||||||
|
memset(apdu.data + apdu.nc, 0, key_size - apdu.nc);
|
||||||
|
}
|
||||||
|
r = mbedtls_rsa_private(&ctx, random_gen, NULL, apdu.data, res_APDU);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
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);
|
||||||
|
memcpy(res_APDU, signature, key_size);
|
||||||
|
free(signature);
|
||||||
|
}
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_rsa_free(&ctx);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
res_APDU_size = key_size;
|
||||||
|
apdu.ne = key_size;
|
||||||
|
mbedtls_rsa_free(&ctx);
|
||||||
|
}
|
||||||
|
else if (p2 >= ALGO_EC_RAW && p2 <= ALGO_EC_SHA512) {
|
||||||
|
mbedtls_ecdsa_context ctx;
|
||||||
|
mbedtls_ecdsa_init(&ctx);
|
||||||
|
md = MBEDTLS_MD_SHA256;
|
||||||
|
if (p2 == ALGO_EC_RAW) {
|
||||||
|
if (apdu.nc == 32) {
|
||||||
|
md = MBEDTLS_MD_SHA256;
|
||||||
|
}
|
||||||
|
else if (apdu.nc == 20) {
|
||||||
|
md = MBEDTLS_MD_SHA1;
|
||||||
|
}
|
||||||
|
else if (apdu.nc == 28) {
|
||||||
|
md = MBEDTLS_MD_SHA224;
|
||||||
|
}
|
||||||
|
else if (apdu.nc == 48) {
|
||||||
|
md = MBEDTLS_MD_SHA384;
|
||||||
|
}
|
||||||
|
else if (apdu.nc == 64) {
|
||||||
|
md = MBEDTLS_MD_SHA512;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (p2 == ALGO_EC_SHA1) {
|
||||||
|
md = MBEDTLS_MD_SHA1;
|
||||||
|
}
|
||||||
|
else if (p2 == ALGO_EC_SHA224) {
|
||||||
|
md = MBEDTLS_MD_SHA224;
|
||||||
|
}
|
||||||
|
else if (p2 == ALGO_EC_SHA256) {
|
||||||
|
md = MBEDTLS_MD_SHA256;
|
||||||
|
}
|
||||||
|
else if (p2 == ALGO_EC_SHA384) {
|
||||||
|
md = MBEDTLS_MD_SHA384;
|
||||||
|
}
|
||||||
|
else if (p2 == ALGO_EC_SHA512) {
|
||||||
|
md = MBEDTLS_MD_SHA512;
|
||||||
|
}
|
||||||
|
int r = load_private_key_ecdsa(&ctx, fkey);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
mbedtls_ecdsa_free(&ctx);
|
||||||
|
if (r == CCID_VERIFICATION_FAILED) {
|
||||||
|
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
size_t olen = 0;
|
||||||
|
uint8_t buf[MBEDTLS_ECDSA_MAX_LEN];
|
||||||
|
if (mbedtls_ecdsa_write_signature(&ctx, md, apdu.data, apdu.nc, buf, MBEDTLS_ECDSA_MAX_LEN,
|
||||||
|
&olen, random_gen, NULL) != 0) {
|
||||||
|
mbedtls_ecdsa_free(&ctx);
|
||||||
|
return SW_EXEC_ERROR();
|
||||||
|
}
|
||||||
|
memcpy(res_APDU, buf, olen);
|
||||||
|
res_APDU_size = olen;
|
||||||
|
mbedtls_ecdsa_free(&ctx);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
decrement_key_counter(fkey);
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
100
src/hsm/cmd_update_ef.c
Normal file
100
src/hsm/cmd_update_ef.c
Normal file
@@ -0,0 +1,100 @@
|
|||||||
|
/*
|
||||||
|
* 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 "asn1.h"
|
||||||
|
|
||||||
|
extern void select_file(file_t *pe);
|
||||||
|
|
||||||
|
int cmd_update_ef() {
|
||||||
|
uint8_t p1 = P1(apdu), p2 = P2(apdu);
|
||||||
|
uint16_t fid = (p1 << 8) | p2;
|
||||||
|
uint8_t *data = NULL;
|
||||||
|
uint16_t offset = 0;
|
||||||
|
uint16_t data_len = 0;
|
||||||
|
file_t *ef = NULL;
|
||||||
|
if (!isUserAuthenticated) {
|
||||||
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
if (fid == 0x0) {
|
||||||
|
ef = currentEF;
|
||||||
|
}
|
||||||
|
else if (p1 != EE_CERTIFICATE_PREFIX && p1 != PRKD_PREFIX && p1 != CA_CERTIFICATE_PREFIX &&
|
||||||
|
p1 != CD_PREFIX && p1 != DATA_PREFIX && p1 != DCOD_PREFIX &&
|
||||||
|
p1 != PROT_DATA_PREFIX) {
|
||||||
|
return SW_INCORRECT_P1P2();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (ef && !authenticate_action(ef, ACL_OP_UPDATE_ERASE)) {
|
||||||
|
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||||
|
}
|
||||||
|
|
||||||
|
uint16_t tag = 0x0;
|
||||||
|
uint8_t *tag_data = NULL, *p = NULL;
|
||||||
|
size_t tag_len = 0;
|
||||||
|
while (walk_tlv(apdu.data, apdu.nc, &p, &tag, &tag_len, &tag_data)) {
|
||||||
|
if (tag == 0x54) { //ofset tag
|
||||||
|
for (int i = 1; i <= tag_len; i++) {
|
||||||
|
offset |= (*tag_data++ << (8 * (tag_len - i)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (tag == 0x53) { //data
|
||||||
|
data_len = tag_len;
|
||||||
|
data = tag_data;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (data_len == 0 && offset == 0) { //new file
|
||||||
|
ef = file_new(fid);
|
||||||
|
//if ((fid & 0xff00) == (EE_CERTIFICATE_PREFIX << 8))
|
||||||
|
// add_file_to_chain(ef, &ef_pukdf);
|
||||||
|
select_file(ef);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if (fid == 0x0 && !ef) {
|
||||||
|
return SW_FILE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
else if (fid != 0x0 &&
|
||||||
|
!(ef =
|
||||||
|
search_by_fid(fid, NULL,
|
||||||
|
SPECIFY_EF)) && !(ef = search_dynamic_file(fid))) { //if does not exist, create it
|
||||||
|
//return SW_FILE_NOT_FOUND();
|
||||||
|
ef = file_new(fid);
|
||||||
|
}
|
||||||
|
if (offset == 0) {
|
||||||
|
int r = flash_write_data_to_file(ef, data, data_len);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return SW_MEMORY_FAILURE();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
if (!file_has_data(ef)) {
|
||||||
|
return SW_DATA_INVALID();
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t *data_merge = (uint8_t *) calloc(1, offset + data_len);
|
||||||
|
memcpy(data_merge, file_get_data(ef), offset);
|
||||||
|
memcpy(data_merge + offset, data, data_len);
|
||||||
|
int r = flash_write_data_to_file(ef, data_merge, offset + data_len);
|
||||||
|
free(data_merge);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return SW_MEMORY_FAILURE();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
low_flash_available();
|
||||||
|
}
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
66
src/hsm/cmd_verify.c
Normal file
66
src/hsm/cmd_verify.c
Normal file
@@ -0,0 +1,66 @@
|
|||||||
|
/*
|
||||||
|
* 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"
|
||||||
|
|
||||||
|
int cmd_verify() {
|
||||||
|
uint8_t p1 = P1(apdu);
|
||||||
|
uint8_t p2 = P2(apdu);
|
||||||
|
|
||||||
|
if (p1 != 0x0 || (p2 & 0x60) != 0x0) {
|
||||||
|
return SW_WRONG_P1P2();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (p2 == 0x81) { //UserPin
|
||||||
|
uint16_t opts = get_device_options();
|
||||||
|
if (opts & HSM_OPT_TRANSPORT_PIN) {
|
||||||
|
return SW_DATA_INVALID();
|
||||||
|
}
|
||||||
|
if (has_session_pin && apdu.nc == 0) {
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
|
if (*file_get_data(file_pin1) == 0 && pka_enabled() == false) { //not initialized
|
||||||
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
if (apdu.nc > 0) {
|
||||||
|
return check_pin(file_pin1, apdu.data, apdu.nc);
|
||||||
|
}
|
||||||
|
if (file_read_uint8(file_get_data(file_retries_pin1)) == 0) {
|
||||||
|
return SW_PIN_BLOCKED();
|
||||||
|
}
|
||||||
|
return set_res_sw(0x63, 0xc0 | file_read_uint8(file_get_data(file_retries_pin1)));
|
||||||
|
}
|
||||||
|
else if (p2 == 0x88) { //SOPin
|
||||||
|
if (file_read_uint8(file_get_data(file_sopin)) == 0) { //not initialized
|
||||||
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
|
}
|
||||||
|
if (apdu.nc > 0) {
|
||||||
|
return check_pin(file_sopin, apdu.data, apdu.nc);
|
||||||
|
}
|
||||||
|
if (file_read_uint8(file_get_data(file_retries_sopin)) == 0) {
|
||||||
|
return SW_PIN_BLOCKED();
|
||||||
|
}
|
||||||
|
if (has_session_sopin) {
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
|
return set_res_sw(0x63, 0xc0 | file_read_uint8(file_get_data(file_retries_sopin)));
|
||||||
|
}
|
||||||
|
else if (p2 == 0x85) {
|
||||||
|
return SW_OK();
|
||||||
|
}
|
||||||
|
return SW_REFERENCE_NOT_FOUND();
|
||||||
|
}
|
||||||
796
src/hsm/cvc.c
796
src/hsm/cvc.c
@@ -15,220 +15,331 @@
|
|||||||
* 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 "cvc.h"
|
|
||||||
#include "common.h"
|
#include "common.h"
|
||||||
|
#include "cvc.h"
|
||||||
|
#include "sc_hsm.h"
|
||||||
#include "mbedtls/rsa.h"
|
#include "mbedtls/rsa.h"
|
||||||
#include "mbedtls/ecdsa.h"
|
#include "mbedtls/ecdsa.h"
|
||||||
#include "cvcerts.h"
|
|
||||||
#include <string.h>
|
#include <string.h>
|
||||||
#include "asn1.h"
|
#include "asn1.h"
|
||||||
#include "ccid2040.h"
|
|
||||||
#include "crypto_utils.h"
|
#include "crypto_utils.h"
|
||||||
#include "random.h"
|
#include "random.h"
|
||||||
|
#include "oid.h"
|
||||||
|
#include "mbedtls/md.h"
|
||||||
|
#include "files.h"
|
||||||
|
|
||||||
|
extern const uint8_t *dev_name;
|
||||||
|
extern size_t dev_name_len;
|
||||||
|
|
||||||
size_t asn1_cvc_public_key_rsa(mbedtls_rsa_context *rsa, uint8_t *buf, size_t buf_len) {
|
size_t asn1_cvc_public_key_rsa(mbedtls_rsa_context *rsa, uint8_t *buf, size_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);
|
size_t n_size = mbedtls_mpi_size(&rsa->N), e_size = mbedtls_mpi_size(&rsa->E);
|
||||||
size_t ntot_size = asn1_len_tag(0x81, n_size), etot_size = asn1_len_tag(0x82, e_size);
|
size_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));
|
size_t oid_len = asn1_len_tag(0x6, sizeof(oid_rsa));
|
||||||
size_t tot_len = asn1_len_tag(0x7f49, oid_len+ntot_size+etot_size);
|
size_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;
|
||||||
if (buf_len < tot_len)
|
}
|
||||||
|
if (buf_len < tot_len) {
|
||||||
return 0;
|
return 0;
|
||||||
|
}
|
||||||
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(oid_len+ntot_size+etot_size, p);
|
p += format_tlv_len(oid_len + ntot_size + etot_size, p);
|
||||||
//oid
|
//oid
|
||||||
*p++ = 0x6; p += format_tlv_len(sizeof(oid_rsa), p); memcpy(p, oid_rsa, sizeof(oid_rsa)); p += sizeof(oid_rsa);
|
*p++ = 0x6; p += format_tlv_len(sizeof(oid_rsa), p); memcpy(p, oid_rsa, sizeof(oid_rsa));
|
||||||
|
p += sizeof(oid_rsa);
|
||||||
//n
|
//n
|
||||||
*p++ = 0x81; p += format_tlv_len(n_size, p); mbedtls_mpi_write_binary(&rsa->N, p, n_size); p += n_size;
|
*p++ = 0x81; p += format_tlv_len(n_size, p); mbedtls_mpi_write_binary(&rsa->N, p, n_size);
|
||||||
|
p += n_size;
|
||||||
//n
|
//n
|
||||||
*p++ = 0x82; p += format_tlv_len(e_size, p); mbedtls_mpi_write_binary(&rsa->E, p, e_size); p += e_size;
|
*p++ = 0x82; p += format_tlv_len(e_size, p); mbedtls_mpi_write_binary(&rsa->E, p, e_size);
|
||||||
|
p += e_size;
|
||||||
return tot_len;
|
return tot_len;
|
||||||
}
|
}
|
||||||
|
|
||||||
const uint8_t *pointA[] = {
|
const uint8_t *pointA[] = {
|
||||||
NULL,
|
NULL,
|
||||||
(uint8_t *)"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC",
|
(uint8_t *)
|
||||||
(uint8_t *)"\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\xFE",
|
"\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFE\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC",
|
||||||
(uint8_t *)"\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC",
|
(uint8_t *)
|
||||||
(uint8_t *)"\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\xFE\xFF\xFF\xFF\xFF\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFC",
|
"\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\xFE",
|
||||||
(uint8_t *)"\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",
|
(uint8_t *)
|
||||||
|
"\xFF\xFF\xFF\xFF\x00\x00\x00\x01\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFF\xFC",
|
||||||
|
(uint8_t *)
|
||||||
|
"\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\xFE\xFF\xFF\xFF\xFF\x00\x00\x00\x00\x00\x00\x00\x00\xFF\xFF\xFF\xFC",
|
||||||
|
(uint8_t *)
|
||||||
|
"\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) {
|
size_t asn1_cvc_public_key_ecdsa(mbedtls_ecdsa_context *ecdsa, uint8_t *buf, size_t buf_len) {
|
||||||
|
uint8_t Y_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 };
|
||||||
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), g_size = 1+mbedtls_mpi_size(&ecdsa->grp.G.X)+mbedtls_mpi_size(&ecdsa->grp.G.X);
|
size_t b_size = mbedtls_mpi_size(&ecdsa->grp.B),
|
||||||
size_t o_size = mbedtls_mpi_size(&ecdsa->grp.N), y_size = 1+mbedtls_mpi_size(&ecdsa->Q.X)+mbedtls_mpi_size(&ecdsa->Q.X);
|
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;
|
||||||
|
mbedtls_ecp_point_write_binary(&ecdsa->grp,
|
||||||
|
&ecdsa->Q,
|
||||||
|
MBEDTLS_ECP_PF_UNCOMPRESSED,
|
||||||
|
&y_size,
|
||||||
|
Y_buf,
|
||||||
|
sizeof(Y_buf));
|
||||||
size_t c_size = 1;
|
size_t c_size = 1;
|
||||||
size_t ptot_size = asn1_len_tag(0x81, p_size), atot_size = asn1_len_tag(0x82, a_size ? a_size : (pointA[ecdsa->grp.id] ? p_size : 0));
|
size_t ptot_size = asn1_len_tag(0x81, p_size), atot_size = asn1_len_tag(0x82,
|
||||||
|
a_size ? a_size : (
|
||||||
|
pointA[ecdsa->grp.id
|
||||||
|
] &&
|
||||||
|
ecdsa->grp.id <
|
||||||
|
6 ? p_size : 1));
|
||||||
size_t btot_size = asn1_len_tag(0x83, b_size), gtot_size = asn1_len_tag(0x84, g_size);
|
size_t btot_size = asn1_len_tag(0x83, b_size), gtot_size = asn1_len_tag(0x84, g_size);
|
||||||
size_t otot_size = asn1_len_tag(0x85, o_size), ytot_size = asn1_len_tag(0x86, y_size);
|
size_t otot_size = asn1_len_tag(0x85, o_size), ytot_size = asn1_len_tag(0x86, y_size);
|
||||||
size_t ctot_size = asn1_len_tag(0x87, c_size);
|
size_t ctot_size = asn1_len_tag(0x87, c_size);
|
||||||
size_t oid_len = asn1_len_tag(0x6, sizeof(oid_ecdsa));
|
size_t oid_len = asn1_len_tag(0x6, sizeof(oid_ecdsa));
|
||||||
size_t tot_len = asn1_len_tag(0x7f49, oid_len+ptot_size+atot_size+btot_size+gtot_size+otot_size+ytot_size+ctot_size);
|
size_t tot_len = asn1_len_tag(0x7f49,
|
||||||
if (buf == NULL || buf_len == 0)
|
oid_len + ptot_size + atot_size + btot_size + gtot_size + otot_size + ytot_size +
|
||||||
|
ctot_size);
|
||||||
|
if (buf == NULL || buf_len == 0) {
|
||||||
return tot_len;
|
return tot_len;
|
||||||
if (buf_len < tot_len)
|
}
|
||||||
|
if (buf_len < tot_len) {
|
||||||
return 0;
|
return 0;
|
||||||
|
}
|
||||||
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(oid_len+ptot_size+atot_size+btot_size+gtot_size+otot_size+ytot_size+ctot_size, p);
|
p += format_tlv_len(
|
||||||
|
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 += sizeof(oid_ecdsa);
|
*p++ = 0x6; p += format_tlv_len(sizeof(oid_ecdsa), p); memcpy(p, oid_ecdsa, sizeof(oid_ecdsa));
|
||||||
|
p += sizeof(oid_ecdsa);
|
||||||
//p
|
//p
|
||||||
*p++ = 0x81; p += format_tlv_len(p_size, p); mbedtls_mpi_write_binary(&ecdsa->grp.P, p, p_size); p += p_size;
|
*p++ = 0x81; p += format_tlv_len(p_size, p); mbedtls_mpi_write_binary(&ecdsa->grp.P, p, p_size);
|
||||||
|
p += p_size;
|
||||||
//A
|
//A
|
||||||
if (a_size) {
|
if (a_size) {
|
||||||
*p++ = 0x82; p += format_tlv_len(a_size, p); mbedtls_mpi_write_binary(&ecdsa->grp.A, p, a_size); p += a_size;
|
*p++ = 0x82; p += format_tlv_len(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
|
else { //mbedtls does not set point A for some curves
|
||||||
if (pointA[ecdsa->grp.id]) {
|
if (pointA[ecdsa->grp.id] && ecdsa->grp.id < 6) {
|
||||||
*p++ = 0x82; p += format_tlv_len(p_size, p); memcpy(p, pointA[ecdsa->grp.id], p_size); p += p_size;
|
*p++ = 0x82; p += format_tlv_len(p_size, p); memcpy(p, pointA[ecdsa->grp.id], p_size);
|
||||||
|
p += p_size;
|
||||||
}
|
}
|
||||||
else {
|
else {
|
||||||
*p++ = 0x82; p += format_tlv_len(0, p);
|
*p++ = 0x82; p += format_tlv_len(1, p);
|
||||||
|
*p++ = 0x0;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
//B
|
//B
|
||||||
*p++ = 0x83; p += format_tlv_len(b_size, p); mbedtls_mpi_write_binary(&ecdsa->grp.B, p, b_size); p += b_size;
|
*p++ = 0x83; p += format_tlv_len(b_size, p); mbedtls_mpi_write_binary(&ecdsa->grp.B, p, b_size);
|
||||||
|
p += b_size;
|
||||||
//G
|
//G
|
||||||
size_t g_new_size = 0;
|
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;
|
*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
|
//order
|
||||||
*p++ = 0x85; p += format_tlv_len(o_size, p); mbedtls_mpi_write_binary(&ecdsa->grp.N, p, o_size); p += o_size;
|
*p++ = 0x85; p += format_tlv_len(o_size, p); mbedtls_mpi_write_binary(&ecdsa->grp.N, p, o_size);
|
||||||
|
p += o_size;
|
||||||
//Y
|
//Y
|
||||||
size_t y_new_size = 0;
|
*p++ = 0x86; p += format_tlv_len(y_size, p); memcpy(p, Y_buf, y_size); p += y_size;
|
||||||
*p++ = 0x86; p += format_tlv_len(y_size, p); mbedtls_ecp_point_write_binary(&ecdsa->grp, &ecdsa->Q, MBEDTLS_ECP_PF_UNCOMPRESSED, &y_new_size, p, y_size); p += y_size;
|
|
||||||
//cofactor
|
//cofactor
|
||||||
*p++ = 0x87; p += format_tlv_len(c_size, p); *p++ = 1;
|
*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 {
|
||||||
|
*p++ = 1;
|
||||||
|
}
|
||||||
return tot_len;
|
return tot_len;
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t asn1_cvc_cert_body(void *rsa_ecdsa, uint8_t key_type, uint8_t *buf, size_t buf_len) {
|
size_t asn1_cvc_cert_body(void *rsa_ecdsa,
|
||||||
|
uint8_t key_type,
|
||||||
|
uint8_t *buf,
|
||||||
|
size_t buf_len,
|
||||||
|
const uint8_t *ext,
|
||||||
|
size_t ext_len) {
|
||||||
size_t pubkey_size = 0;
|
size_t pubkey_size = 0;
|
||||||
if (key_type == HSM_KEY_RSA)
|
if (key_type == HSM_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 == HSM_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;
|
size_t cpi_size = 4;
|
||||||
|
size_t ext_size = 0;
|
||||||
|
if (ext && ext_len > 0) {
|
||||||
|
ext_size = asn1_len_tag(0x65, ext_len);
|
||||||
|
}
|
||||||
|
|
||||||
uint8_t *car = NULL, *chr = NULL;
|
uint8_t *car = NULL, *chr = NULL;
|
||||||
size_t lencar = 0, lenchr = 0;
|
size_t lencar = 0, lenchr = 0;
|
||||||
|
|
||||||
if (asn1_find_tag(apdu.data, apdu.nc, 0x42, &lencar, &car) == false || lencar == 0 || car == NULL) {
|
if (asn1_find_tag(apdu.data, apdu.nc, 0x42, &lencar,
|
||||||
car = (uint8_t *)"UTSRCACC100001";
|
&car) == false || lencar == 0 || car == NULL) {
|
||||||
lencar = strlen((char *)car);
|
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) {
|
if (asn1_find_tag(apdu.data, apdu.nc, 0x5f20, &lenchr,
|
||||||
chr = (uint8_t *)"ESHSMCVCA00001";
|
&chr) == false || lenchr == 0 || chr == NULL) {
|
||||||
lenchr = strlen((char *)chr);
|
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 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);
|
size_t tot_len = asn1_len_tag(0x7f4e, cpi_size + car_size + pubkey_size + chr_size + ext_size);
|
||||||
|
|
||||||
if (buf_len == 0 || buf == NULL)
|
if (buf_len == 0 || buf == NULL) {
|
||||||
return tot_len;
|
return tot_len;
|
||||||
if (buf_len < tot_len)
|
}
|
||||||
|
if (buf_len < tot_len) {
|
||||||
return 0;
|
return 0;
|
||||||
|
}
|
||||||
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, p);
|
p += format_tlv_len(cpi_size + car_size + pubkey_size + chr_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(lencar, p); memcpy(p, car, lencar); p += lencar;
|
||||||
//pubkey
|
//pubkey
|
||||||
if (key_type == HSM_KEY_RSA)
|
if (key_type == HSM_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 == HSM_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(lenchr, p); memcpy(p, chr, lenchr); p += lenchr;
|
||||||
|
if (ext && ext_len > 0) {
|
||||||
|
*p++ = 0x65;
|
||||||
|
p += format_tlv_len(ext_len, p);
|
||||||
|
memcpy(p, ext, ext_len);
|
||||||
|
p += ext_len;
|
||||||
|
}
|
||||||
return tot_len;
|
return tot_len;
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t asn1_cvc_cert(void *rsa_ecdsa, uint8_t key_type, uint8_t *buf, size_t buf_len) {
|
size_t asn1_cvc_cert(void *rsa_ecdsa,
|
||||||
|
uint8_t key_type,
|
||||||
|
uint8_t *buf,
|
||||||
|
size_t buf_len,
|
||||||
|
const uint8_t *ext,
|
||||||
|
size_t ext_len) {
|
||||||
size_t key_size = 0;
|
size_t key_size = 0;
|
||||||
if (key_type == HSM_KEY_RSA)
|
if (key_type == HSM_KEY_RSA) {
|
||||||
key_size = mbedtls_mpi_size(&((mbedtls_rsa_context *)rsa_ecdsa)->N);
|
key_size = mbedtls_mpi_size(&((mbedtls_rsa_context *) rsa_ecdsa)->N);
|
||||||
else if (key_type == HSM_KEY_EC)
|
}
|
||||||
key_size = 2*mbedtls_mpi_size(&((mbedtls_ecdsa_context *)rsa_ecdsa)->d);
|
else if (key_type == HSM_KEY_EC) {
|
||||||
size_t body_size = asn1_cvc_cert_body(rsa_ecdsa, key_type, NULL, 0), sig_size = asn1_len_tag(0x5f37, key_size);
|
key_size = 2 *
|
||||||
size_t tot_len = asn1_len_tag(0x7f21, body_size+sig_size);
|
(int) ((mbedtls_ecp_curve_info_from_grp_id(((mbedtls_ecdsa_context *) rsa_ecdsa)
|
||||||
if (buf_len == 0 || buf == NULL)
|
->grp.id)->
|
||||||
|
bit_size + 7) / 8);
|
||||||
|
}
|
||||||
|
size_t body_size = asn1_cvc_cert_body(rsa_ecdsa, key_type, NULL, 0, ext, ext_len),
|
||||||
|
sig_size = asn1_len_tag(0x5f37, key_size);
|
||||||
|
size_t tot_len = asn1_len_tag(0x7f21, body_size + sig_size);
|
||||||
|
if (buf_len == 0 || buf == NULL) {
|
||||||
return tot_len;
|
return tot_len;
|
||||||
if (buf_len < tot_len)
|
}
|
||||||
|
if (buf_len < tot_len) {
|
||||||
return 0;
|
return 0;
|
||||||
|
}
|
||||||
uint8_t *p = buf, *body = NULL;
|
uint8_t *p = buf, *body = NULL;
|
||||||
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);
|
p += asn1_cvc_cert_body(rsa_ecdsa, key_type, p, body_size, ext, ext_len);
|
||||||
|
|
||||||
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 == HSM_KEY_RSA) {
|
||||||
if (mbedtls_rsa_rsassa_pkcs1_v15_sign(rsa_ecdsa, random_gen, NULL, MBEDTLS_MD_SHA256, 32, hsh, p) != 0)
|
if (mbedtls_rsa_rsassa_pkcs1_v15_sign(rsa_ecdsa, random_gen, NULL, MBEDTLS_MD_SHA256, 32,
|
||||||
return 0;
|
hsh, p) != 0) {
|
||||||
|
memset(p, 0, key_size);
|
||||||
|
}
|
||||||
p += key_size;
|
p += key_size;
|
||||||
}
|
}
|
||||||
else if (key_type == HSM_KEY_EC) {
|
else if (key_type == HSM_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_ecdsa_context *ecdsa = (mbedtls_ecdsa_context *) rsa_ecdsa;
|
||||||
mbedtls_mpi_init(&r);
|
mbedtls_mpi_init(&r);
|
||||||
mbedtls_mpi_init(&s);
|
mbedtls_mpi_init(&s);
|
||||||
ret = mbedtls_ecdsa_sign(&ecdsa->grp, &r, &s, &ecdsa->d, hsh, sizeof(hsh), random_gen, NULL);
|
ret =
|
||||||
if (ret != 0) {
|
mbedtls_ecdsa_sign(&ecdsa->grp, &r, &s, &ecdsa->d, hsh, sizeof(hsh), random_gen, NULL);
|
||||||
mbedtls_mpi_free(&r);
|
if (ret == 0) {
|
||||||
mbedtls_mpi_free(&s);
|
mbedtls_mpi_write_binary(&r, p, key_size / 2); p += key_size / 2;
|
||||||
return 0;
|
mbedtls_mpi_write_binary(&s, p, key_size / 2); p += key_size / 2;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
memset(p, 0, key_size);
|
||||||
|
p += key_size;
|
||||||
}
|
}
|
||||||
mbedtls_mpi_write_binary(&r, p, mbedtls_mpi_size(&r)); p += mbedtls_mpi_size(&r);
|
|
||||||
mbedtls_mpi_write_binary(&s, p, mbedtls_mpi_size(&s)); p += mbedtls_mpi_size(&s);
|
|
||||||
mbedtls_mpi_free(&r);
|
mbedtls_mpi_free(&r);
|
||||||
mbedtls_mpi_free(&s);
|
mbedtls_mpi_free(&s);
|
||||||
}
|
}
|
||||||
return p-buf;
|
return p - buf;
|
||||||
}
|
}
|
||||||
|
|
||||||
size_t asn1_cvc_aut(void *rsa_ecdsa, uint8_t key_type, uint8_t *buf, size_t buf_len) {
|
size_t asn1_cvc_aut(void *rsa_ecdsa,
|
||||||
size_t cvcert_size = asn1_cvc_cert(rsa_ecdsa, key_type, NULL, 0);
|
uint8_t key_type,
|
||||||
uint8_t *outcar = (uint8_t *)"ESHSM00001";
|
uint8_t *buf,
|
||||||
size_t lenoutcar = strlen((char *)outcar), outcar_size = asn1_len_tag(0x42, lenoutcar);
|
size_t buf_len,
|
||||||
int key_size = 2*file_read_uint16(termca_pk), ret = 0;
|
const uint8_t *ext,
|
||||||
size_t outsig_size = asn1_len_tag(0x5f37, key_size), tot_len = asn1_len_tag(0x67, cvcert_size+outcar_size+outsig_size);
|
size_t ext_len) {
|
||||||
if (buf_len == 0 || buf == NULL)
|
size_t cvcert_size = asn1_cvc_cert(rsa_ecdsa, key_type, NULL, 0, ext, ext_len);
|
||||||
return tot_len;
|
size_t outcar_len = dev_name_len;
|
||||||
if (buf_len < tot_len)
|
const uint8_t *outcar = dev_name;
|
||||||
|
size_t outcar_size = asn1_len_tag(0x42, outcar_len);
|
||||||
|
file_t *fkey = search_by_fid(EF_KEY_DEV, NULL, SPECIFY_EF);
|
||||||
|
if (!fkey) {
|
||||||
return 0;
|
return 0;
|
||||||
|
}
|
||||||
|
mbedtls_ecdsa_context ectx;
|
||||||
|
mbedtls_ecdsa_init(&ectx);
|
||||||
|
if (load_private_key_ecdsa(&ectx, fkey) != CCID_OK) {
|
||||||
|
mbedtls_ecdsa_free(&ectx);
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
int ret = 0, key_size = 2 * mbedtls_mpi_size(&ectx.d);
|
||||||
|
size_t outsig_size = asn1_len_tag(0x5f37, key_size), tot_len = asn1_len_tag(0x67,
|
||||||
|
cvcert_size + outcar_size +
|
||||||
|
outsig_size);
|
||||||
|
if (buf_len == 0 || buf == NULL) {
|
||||||
|
return tot_len;
|
||||||
|
}
|
||||||
|
if (buf_len < tot_len) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
uint8_t *p = buf;
|
uint8_t *p = buf;
|
||||||
*p++ = 0x67;
|
*p++ = 0x67;
|
||||||
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);
|
p += asn1_cvc_cert(rsa_ecdsa, key_type, p, cvcert_size, ext, ext_len);
|
||||||
//outcar
|
//outcar
|
||||||
*p++ = 0x42; p += format_tlv_len(lenoutcar, p); memcpy(p, outcar, lenoutcar); p += lenoutcar;
|
*p++ = 0x42; p += format_tlv_len(outcar_len, p); memcpy(p, outcar, outcar_len); p += outcar_len;
|
||||||
mbedtls_ecdsa_context ctx;
|
|
||||||
mbedtls_ecdsa_init(&ctx);
|
|
||||||
if (mbedtls_ecp_read_key(MBEDTLS_ECP_DP_SECP192R1, &ctx, termca_pk+2, file_read_uint16(termca_pk)) != 0)
|
|
||||||
return 0;
|
|
||||||
uint8_t hsh[32];
|
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);
|
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(&ctx.grp, &r, &s, &ctx.d, hsh, sizeof(hsh), random_gen, NULL);
|
ret = mbedtls_ecdsa_sign(&ectx.grp, &r, &s, &ectx.d, hsh, sizeof(hsh), random_gen, NULL);
|
||||||
mbedtls_ecdsa_free(&ctx);
|
mbedtls_ecdsa_free(&ectx);
|
||||||
if (ret != 0) {
|
if (ret != 0) {
|
||||||
mbedtls_mpi_free(&r);
|
mbedtls_mpi_free(&r);
|
||||||
mbedtls_mpi_free(&s);
|
mbedtls_mpi_free(&s);
|
||||||
@@ -238,5 +349,494 @@ size_t asn1_cvc_aut(void *rsa_ecdsa, uint8_t key_type, uint8_t *buf, size_t buf_
|
|||||||
mbedtls_mpi_write_binary(&s, p, mbedtls_mpi_size(&s)); p += mbedtls_mpi_size(&s);
|
mbedtls_mpi_write_binary(&s, p, mbedtls_mpi_size(&s)); p += mbedtls_mpi_size(&s);
|
||||||
mbedtls_mpi_free(&r);
|
mbedtls_mpi_free(&r);
|
||||||
mbedtls_mpi_free(&s);
|
mbedtls_mpi_free(&s);
|
||||||
return p-buf;
|
return p - buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t asn1_build_cert_description(const uint8_t *label,
|
||||||
|
size_t label_len,
|
||||||
|
const uint8_t *puk,
|
||||||
|
size_t puk_len,
|
||||||
|
uint16_t fid,
|
||||||
|
uint8_t *buf,
|
||||||
|
size_t buf_len) {
|
||||||
|
size_t opt_len = 2;
|
||||||
|
size_t seq1_size =
|
||||||
|
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 */
|
||||||
|
size_t seq3_size =
|
||||||
|
asn1_len_tag(0xA1,
|
||||||
|
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);
|
||||||
|
if (buf_len == 0 || buf == NULL) {
|
||||||
|
return tot_len;
|
||||||
|
}
|
||||||
|
if (buf_len < tot_len) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
uint8_t *p = buf;
|
||||||
|
*p++ = 0x30;
|
||||||
|
p += format_tlv_len(seq1_size + seq2_size + seq3_size, p);
|
||||||
|
//Seq 1
|
||||||
|
*p++ = 0x30;
|
||||||
|
p += format_tlv_len(asn1_len_tag(0xC, label_len) + asn1_len_tag(0x3, opt_len), p);
|
||||||
|
*p++ = 0xC;
|
||||||
|
p += format_tlv_len(label_len, p);
|
||||||
|
memcpy(p, label, label_len); p += label_len;
|
||||||
|
*p++ = 0x3;
|
||||||
|
p += format_tlv_len(opt_len, p);
|
||||||
|
memcpy(p, "\x06\x40", 2); p += 2;
|
||||||
|
|
||||||
|
//Seq 2
|
||||||
|
*p++ = 0x30;
|
||||||
|
p += format_tlv_len(asn1_len_tag(0x4, 20), p);
|
||||||
|
*p++ = 0x4;
|
||||||
|
p += format_tlv_len(20, p);
|
||||||
|
mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA1), puk, puk_len, p); p += 20;
|
||||||
|
|
||||||
|
//Seq 3
|
||||||
|
*p++ = 0xA1;
|
||||||
|
p += format_tlv_len(asn1_len_tag(0x30, asn1_len_tag(0x30, asn1_len_tag(0x4, sizeof(uint16_t)))),
|
||||||
|
p);
|
||||||
|
*p++ = 0x30;
|
||||||
|
p += format_tlv_len(asn1_len_tag(0x30, asn1_len_tag(0x4, sizeof(uint16_t))), p);
|
||||||
|
*p++ = 0x30;
|
||||||
|
p += format_tlv_len(asn1_len_tag(0x4, sizeof(uint16_t)), p);
|
||||||
|
*p++ = 0x4;
|
||||||
|
p += format_tlv_len(sizeof(uint16_t), p);
|
||||||
|
*p++ = fid >> 8;
|
||||||
|
*p++ = fid & 0xff;
|
||||||
|
return p - buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t asn1_build_prkd_generic(const uint8_t *label,
|
||||||
|
size_t label_len,
|
||||||
|
const uint8_t *keyid,
|
||||||
|
size_t keyid_len,
|
||||||
|
size_t keysize,
|
||||||
|
const uint8_t *seq,
|
||||||
|
size_t seq_len,
|
||||||
|
uint8_t *buf,
|
||||||
|
size_t buf_len) {
|
||||||
|
size_t seq1_size = asn1_len_tag(0x30, asn1_len_tag(0xC, label_len));
|
||||||
|
size_t seq2_size =
|
||||||
|
asn1_len_tag(0x30, asn1_len_tag(0x4, keyid_len) + asn1_len_tag(0x3, seq_len));
|
||||||
|
size_t seq3_size =
|
||||||
|
asn1_len_tag(0xA1,
|
||||||
|
asn1_len_tag(0x30,
|
||||||
|
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);
|
||||||
|
if (buf_len == 0 || buf == NULL) {
|
||||||
|
return tot_len;
|
||||||
|
}
|
||||||
|
if (buf_len < tot_len) {
|
||||||
|
return 0;
|
||||||
|
}
|
||||||
|
uint8_t *p = buf;
|
||||||
|
*p++ = 0xA0;
|
||||||
|
p += format_tlv_len(seq1_size + seq2_size + seq3_size, p);
|
||||||
|
//Seq 1
|
||||||
|
*p++ = 0x30;
|
||||||
|
p += format_tlv_len(asn1_len_tag(0xC, label_len), p);
|
||||||
|
*p++ = 0xC;
|
||||||
|
p += format_tlv_len(label_len, p);
|
||||||
|
memcpy(p, label, label_len); p += label_len;
|
||||||
|
|
||||||
|
//Seq 2
|
||||||
|
*p++ = 0x30;
|
||||||
|
p += format_tlv_len(asn1_len_tag(0x4, keyid_len) + asn1_len_tag(0x3, seq_len), p);
|
||||||
|
*p++ = 0x4;
|
||||||
|
p += format_tlv_len(keyid_len, p);
|
||||||
|
memcpy(p, keyid, keyid_len); p += keyid_len;
|
||||||
|
*p++ = 0x3;
|
||||||
|
p += format_tlv_len(seq_len, p);
|
||||||
|
memcpy(p, seq, seq_len); p += seq_len;
|
||||||
|
|
||||||
|
//Seq 3
|
||||||
|
*p++ = 0xA1;
|
||||||
|
p +=
|
||||||
|
format_tlv_len(asn1_len_tag(0x30,
|
||||||
|
asn1_len_tag(0x30, asn1_len_tag(0x4, 0)) + asn1_len_tag(0x2,
|
||||||
|
2)),
|
||||||
|
p);
|
||||||
|
*p++ = 0x30;
|
||||||
|
p += format_tlv_len(asn1_len_tag(0x30, asn1_len_tag(0x4, 0)) + asn1_len_tag(0x2, 2), p);
|
||||||
|
*p++ = 0x30;
|
||||||
|
p += format_tlv_len(asn1_len_tag(0x4, 0), p);
|
||||||
|
*p++ = 0x4;
|
||||||
|
p += format_tlv_len(0, p);
|
||||||
|
*p++ = 0x2;
|
||||||
|
p += format_tlv_len(2, p);
|
||||||
|
*p++ = (keysize >> 8) & 0xff;
|
||||||
|
*p++ = keysize & 0xff;
|
||||||
|
return p - buf;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t asn1_build_prkd_ecc(const uint8_t *label,
|
||||||
|
size_t label_len,
|
||||||
|
const uint8_t *keyid,
|
||||||
|
size_t keyid_len,
|
||||||
|
size_t keysize,
|
||||||
|
uint8_t *buf,
|
||||||
|
size_t buf_len) {
|
||||||
|
return asn1_build_prkd_generic(label,
|
||||||
|
label_len,
|
||||||
|
keyid,
|
||||||
|
keyid_len,
|
||||||
|
keysize,
|
||||||
|
(const uint8_t *) "\x07\x20\x80",
|
||||||
|
3,
|
||||||
|
buf,
|
||||||
|
buf_len);
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t asn1_build_prkd_rsa(const uint8_t *label,
|
||||||
|
size_t label_len,
|
||||||
|
const uint8_t *keyid,
|
||||||
|
size_t keyid_len,
|
||||||
|
size_t keysize,
|
||||||
|
uint8_t *buf,
|
||||||
|
size_t buf_len) {
|
||||||
|
return asn1_build_prkd_generic(label,
|
||||||
|
label_len,
|
||||||
|
keyid,
|
||||||
|
keyid_len,
|
||||||
|
keysize,
|
||||||
|
(const uint8_t *) "\x02\x74",
|
||||||
|
2,
|
||||||
|
buf,
|
||||||
|
buf_len);
|
||||||
|
}
|
||||||
|
|
||||||
|
const uint8_t *cvc_get_field(const uint8_t *data, size_t len, size_t *olen, uint16_t tag) {
|
||||||
|
uint8_t *rdata = NULL;
|
||||||
|
if (data == NULL || len == 0) {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
if (asn1_find_tag(data, len, tag, olen, &rdata) == false) {
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
return rdata;
|
||||||
|
}
|
||||||
|
|
||||||
|
const uint8_t *cvc_get_body(const uint8_t *data, size_t len, size_t *olen) {
|
||||||
|
const uint8_t *bkdata = data;
|
||||||
|
if ((data = cvc_get_field(data, len, olen, 0x67)) == NULL) { /* Check for CSR */
|
||||||
|
data = bkdata;
|
||||||
|
}
|
||||||
|
if ((data = cvc_get_field(data, len, olen, 0x7F21)) != NULL) {
|
||||||
|
return cvc_get_field(data, len, olen, 0x7F4E);
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
const uint8_t *cvc_get_sig(const uint8_t *data, size_t len, size_t *olen) {
|
||||||
|
const uint8_t *bkdata = data;
|
||||||
|
if ((data = cvc_get_field(data, len, olen, 0x67)) == NULL) { /* Check for CSR */
|
||||||
|
data = bkdata;
|
||||||
|
}
|
||||||
|
if ((data = cvc_get_field(data, len, olen, 0x7F21)) != NULL) {
|
||||||
|
return cvc_get_field(data, len, olen, 0x5F37);
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
const uint8_t *cvc_get_car(const uint8_t *data, size_t len, size_t *olen) {
|
||||||
|
if ((data = cvc_get_body(data, len, olen)) != NULL) {
|
||||||
|
return cvc_get_field(data, len, olen, 0x42);
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
const uint8_t *cvc_get_chr(const uint8_t *data, size_t len, size_t *olen) {
|
||||||
|
if ((data = cvc_get_body(data, len, olen)) != NULL) {
|
||||||
|
return cvc_get_field(data, len, olen, 0x5F20);
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
const uint8_t *cvc_get_pub(const uint8_t *data, size_t len, size_t *olen) {
|
||||||
|
if ((data = cvc_get_body(data, len, olen)) != NULL) {
|
||||||
|
return cvc_get_field(data, len, olen, 0x7F49);
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
const uint8_t *cvc_get_ext(const uint8_t *data, size_t len, size_t *olen) {
|
||||||
|
if ((data = cvc_get_body(data, len, olen)) != NULL) {
|
||||||
|
return cvc_get_field(data, len, olen, 0x65);
|
||||||
|
}
|
||||||
|
return NULL;
|
||||||
|
}
|
||||||
|
|
||||||
|
extern PUK puk_store[MAX_PUK_STORE_ENTRIES];
|
||||||
|
extern int puk_store_entries;
|
||||||
|
|
||||||
|
int puk_store_index(const uint8_t *chr, size_t chr_len) {
|
||||||
|
for (int i = 0; i < puk_store_entries; i++) {
|
||||||
|
if (memcmp(puk_store[i].chr, chr, chr_len) == 0) {
|
||||||
|
return i;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return -1;
|
||||||
|
}
|
||||||
|
|
||||||
|
mbedtls_ecp_group_id cvc_inherite_ec_group(const uint8_t *ca, size_t ca_len) {
|
||||||
|
size_t chr_len = 0, car_len = 0;
|
||||||
|
const uint8_t *chr = NULL, *car = NULL;
|
||||||
|
int eq = -1;
|
||||||
|
do {
|
||||||
|
chr = cvc_get_chr(ca, ca_len, &chr_len);
|
||||||
|
car = cvc_get_car(ca, ca_len, &car_len);
|
||||||
|
eq = memcmp(car, chr, MAX(car_len, chr_len));
|
||||||
|
if (car && eq != 0) {
|
||||||
|
int idx = puk_store_index(car, car_len);
|
||||||
|
if (idx != -1) {
|
||||||
|
ca = puk_store[idx].cvcert;
|
||||||
|
ca_len = puk_store[idx].cvcert_len;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
ca = NULL;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} while (car && chr && eq != 0);
|
||||||
|
size_t ca_puk_len = 0;
|
||||||
|
const uint8_t *ca_puk = cvc_get_pub(ca, ca_len, &ca_puk_len);
|
||||||
|
if (!ca_puk) {
|
||||||
|
return MBEDTLS_ECP_DP_NONE;
|
||||||
|
}
|
||||||
|
size_t t81_len = 0;
|
||||||
|
const uint8_t *t81 = cvc_get_field(ca_puk, ca_puk_len, &t81_len, 0x81);
|
||||||
|
if (!t81) {
|
||||||
|
return MBEDTLS_ECP_DP_NONE;
|
||||||
|
}
|
||||||
|
|
||||||
|
return ec_get_curve_from_prime(t81, t81_len);
|
||||||
|
}
|
||||||
|
|
||||||
|
int puk_verify(const uint8_t *sig,
|
||||||
|
size_t sig_len,
|
||||||
|
const uint8_t *hash,
|
||||||
|
size_t hash_len,
|
||||||
|
const uint8_t *ca,
|
||||||
|
size_t ca_len) {
|
||||||
|
size_t puk_len = 0;
|
||||||
|
const uint8_t *puk = cvc_get_pub(ca, ca_len, &puk_len);
|
||||||
|
if (!puk) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
size_t oid_len = 0;
|
||||||
|
const uint8_t *oid = cvc_get_field(puk, puk_len, &oid_len, 0x6);
|
||||||
|
if (!oid) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
if (memcmp(oid, OID_ID_TA_RSA, 9) == 0) { //RSA
|
||||||
|
size_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,
|
||||||
|
puk_len,
|
||||||
|
&t81_len,
|
||||||
|
0x82);
|
||||||
|
if (!t81 || !t82) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
mbedtls_rsa_context rsa;
|
||||||
|
mbedtls_rsa_init(&rsa);
|
||||||
|
mbedtls_md_type_t md = MBEDTLS_MD_NONE;
|
||||||
|
if (memcmp(oid, OID_ID_TA_RSA_V1_5_SHA_1, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA1;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_RSA_V1_5_SHA_256, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA256;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_RSA_V1_5_SHA_512, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA512;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_RSA_PSS_SHA_1, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA1;
|
||||||
|
mbedtls_rsa_set_padding(&rsa, MBEDTLS_RSA_PKCS_V21, md);
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_RSA_PSS_SHA_256, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA256;
|
||||||
|
mbedtls_rsa_set_padding(&rsa, MBEDTLS_RSA_PKCS_V21, md);
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_RSA_PSS_SHA_512, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA512;
|
||||||
|
mbedtls_rsa_set_padding(&rsa, MBEDTLS_RSA_PKCS_V21, md);
|
||||||
|
}
|
||||||
|
if (md == MBEDTLS_MD_NONE) {
|
||||||
|
mbedtls_rsa_free(&rsa);
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
int r = mbedtls_mpi_read_binary(&rsa.N, t81, t81_len);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_rsa_free(&rsa);
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
r = mbedtls_mpi_read_binary(&rsa.E, t82, t82_len);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_rsa_free(&rsa);
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
r = mbedtls_rsa_complete(&rsa);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_rsa_free(&rsa);
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
r = mbedtls_rsa_check_pubkey(&rsa);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_rsa_free(&rsa);
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
r = mbedtls_rsa_pkcs1_verify(&rsa, md, hash_len, hash, sig);
|
||||||
|
mbedtls_rsa_free(&rsa);
|
||||||
|
if (r != 0) {
|
||||||
|
return CCID_WRONG_SIGNATURE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_ECDSA, 9) == 0) { //ECC
|
||||||
|
mbedtls_md_type_t md = MBEDTLS_MD_NONE;
|
||||||
|
if (memcmp(oid, OID_ID_TA_ECDSA_SHA_1, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA1;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_ECDSA_SHA_224, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA224;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_ECDSA_SHA_256, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA256;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_ECDSA_SHA_384, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA384;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_ECDSA_SHA_512, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA512;
|
||||||
|
}
|
||||||
|
if (md == MBEDTLS_MD_NONE) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t t86_len = 0;
|
||||||
|
const uint8_t *t86 = cvc_get_field(puk, puk_len, &t86_len, 0x86);
|
||||||
|
if (!t86) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
mbedtls_ecp_group_id ec_id = cvc_inherite_ec_group(ca, ca_len);
|
||||||
|
if (ec_id == MBEDTLS_ECP_DP_NONE) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
mbedtls_ecdsa_context ecdsa;
|
||||||
|
mbedtls_ecdsa_init(&ecdsa);
|
||||||
|
int ret = mbedtls_ecp_group_load(&ecdsa.grp, ec_id);
|
||||||
|
if (ret != 0) {
|
||||||
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
ret = mbedtls_ecp_point_read_binary(&ecdsa.grp, &ecdsa.Q, t86, t86_len);
|
||||||
|
if (ret != 0) {
|
||||||
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
ret = mbedtls_ecp_check_pubkey(&ecdsa.grp, &ecdsa.Q);
|
||||||
|
if (ret != 0) {
|
||||||
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
mbedtls_mpi r, s;
|
||||||
|
mbedtls_mpi_init(&r);
|
||||||
|
mbedtls_mpi_init(&s);
|
||||||
|
ret = mbedtls_mpi_read_binary(&r, sig, sig_len / 2);
|
||||||
|
if (ret != 0) {
|
||||||
|
mbedtls_mpi_free(&r);
|
||||||
|
mbedtls_mpi_free(&s);
|
||||||
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
ret = mbedtls_mpi_read_binary(&s, sig + sig_len / 2, sig_len / 2);
|
||||||
|
if (ret != 0) {
|
||||||
|
mbedtls_mpi_free(&r);
|
||||||
|
mbedtls_mpi_free(&s);
|
||||||
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
ret = mbedtls_ecdsa_verify(&ecdsa.grp, hash, hash_len, &ecdsa.Q, &r, &s);
|
||||||
|
mbedtls_mpi_free(&r);
|
||||||
|
mbedtls_mpi_free(&s);
|
||||||
|
mbedtls_ecdsa_free(&ecdsa);
|
||||||
|
if (ret != 0) {
|
||||||
|
return CCID_WRONG_SIGNATURE;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return CCID_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
int cvc_verify(const uint8_t *cert, size_t cert_len, const uint8_t *ca, size_t ca_len) {
|
||||||
|
size_t puk_len = 0;
|
||||||
|
const uint8_t *puk = cvc_get_pub(ca, ca_len, &puk_len);
|
||||||
|
if (!puk) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
size_t oid_len = 0, cv_body_len = 0, sig_len = 0;
|
||||||
|
const uint8_t *oid = cvc_get_field(puk, puk_len, &oid_len, 0x6);
|
||||||
|
const uint8_t *cv_body = cvc_get_body(cert, cert_len, &cv_body_len);
|
||||||
|
const uint8_t *sig = cvc_get_sig(cert, cert_len, &sig_len);
|
||||||
|
if (!sig) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
if (!cv_body) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
if (!oid) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
mbedtls_md_type_t md = MBEDTLS_MD_NONE;
|
||||||
|
if (memcmp(oid, OID_ID_TA_RSA, 9) == 0) { //RSA
|
||||||
|
if (memcmp(oid, OID_ID_TA_RSA_V1_5_SHA_1, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA1;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_RSA_V1_5_SHA_256, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA256;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_RSA_V1_5_SHA_512, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA512;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_RSA_PSS_SHA_1, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA1;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_RSA_PSS_SHA_256, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA256;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_RSA_PSS_SHA_512, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA512;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_ECDSA, 9) == 0) { //ECC
|
||||||
|
if (memcmp(oid, OID_ID_TA_ECDSA_SHA_1, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA1;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_ECDSA_SHA_224, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA224;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_ECDSA_SHA_256, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA256;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_ECDSA_SHA_384, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA384;
|
||||||
|
}
|
||||||
|
else if (memcmp(oid, OID_ID_TA_ECDSA_SHA_512, oid_len) == 0) {
|
||||||
|
md = MBEDTLS_MD_SHA512;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (md == MBEDTLS_MD_NONE) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
const mbedtls_md_info_t *md_info = mbedtls_md_info_from_type(md);
|
||||||
|
uint8_t hash[64], hash_len = mbedtls_md_get_size(md_info);
|
||||||
|
uint8_t tlv_body = 2 + format_tlv_len(cv_body_len, NULL);
|
||||||
|
int r = mbedtls_md(md_info, cv_body - tlv_body, cv_body_len + tlv_body, hash);
|
||||||
|
if (r != 0) {
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
r = puk_verify(sig, sig_len, hash, hash_len, ca, ca_len);
|
||||||
|
if (r != 0) {
|
||||||
|
return CCID_WRONG_SIGNATURE;
|
||||||
|
}
|
||||||
|
return CCID_OK;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -19,9 +19,71 @@
|
|||||||
#define _CVC_H_
|
#define _CVC_H_
|
||||||
|
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
|
#ifndef ENABLE_EMULATION
|
||||||
#include "pico/stdlib.h"
|
#include "pico/stdlib.h"
|
||||||
|
#else
|
||||||
extern size_t asn1_cvc_cert(void *rsa_ecdsa, uint8_t key_type, uint8_t *buf, size_t buf_len);
|
#include <stdbool.h>
|
||||||
extern size_t asn1_cvc_aut(void *rsa_ecdsa, uint8_t key_type, uint8_t *buf, size_t buf_len);
|
#endif
|
||||||
|
#include "mbedtls/ecp.h"
|
||||||
|
|
||||||
|
typedef struct PUK {
|
||||||
|
const uint8_t *puk;
|
||||||
|
size_t puk_len;
|
||||||
|
const uint8_t *car;
|
||||||
|
size_t car_len;
|
||||||
|
const uint8_t *chr;
|
||||||
|
size_t chr_len;
|
||||||
|
const uint8_t *cvcert;
|
||||||
|
size_t cvcert_len;
|
||||||
|
bool copied;
|
||||||
|
} PUK;
|
||||||
|
|
||||||
|
#define MAX_PUK_STORE_ENTRIES 4
|
||||||
|
|
||||||
|
extern size_t asn1_cvc_cert(void *rsa_ecdsa,
|
||||||
|
uint8_t key_type,
|
||||||
|
uint8_t *buf,
|
||||||
|
size_t buf_len,
|
||||||
|
const uint8_t *ext,
|
||||||
|
size_t ext_len);
|
||||||
|
extern size_t asn1_cvc_aut(void *rsa_ecdsa,
|
||||||
|
uint8_t key_type,
|
||||||
|
uint8_t *buf,
|
||||||
|
size_t buf_len,
|
||||||
|
const uint8_t *ext,
|
||||||
|
size_t ext_len);
|
||||||
|
extern size_t asn1_build_cert_description(const uint8_t *label,
|
||||||
|
size_t label_len,
|
||||||
|
const uint8_t *puk,
|
||||||
|
size_t puk_len,
|
||||||
|
uint16_t fid,
|
||||||
|
uint8_t *buf,
|
||||||
|
size_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_car(const uint8_t *data, size_t len, size_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_pub(const uint8_t *data, size_t len, size_t *olen);
|
||||||
|
extern const uint8_t *cvc_get_ext(const uint8_t *data, size_t len, size_t *olen);
|
||||||
|
extern int cvc_verify(const uint8_t *cert, size_t cert_len, const uint8_t *ca, size_t ca_len);
|
||||||
|
extern mbedtls_ecp_group_id cvc_inherite_ec_group(const uint8_t *ca, size_t ca_len);
|
||||||
|
extern int puk_verify(const uint8_t *sig,
|
||||||
|
size_t sig_len,
|
||||||
|
const uint8_t *hash,
|
||||||
|
size_t hash_len,
|
||||||
|
const uint8_t *ca,
|
||||||
|
size_t ca_len);
|
||||||
|
extern size_t asn1_build_prkd_ecc(const uint8_t *label,
|
||||||
|
size_t label_len,
|
||||||
|
const uint8_t *keyid,
|
||||||
|
size_t keyid_len,
|
||||||
|
size_t keysize,
|
||||||
|
uint8_t *buf,
|
||||||
|
size_t buf_len);
|
||||||
|
extern size_t asn1_build_prkd_rsa(const uint8_t *label,
|
||||||
|
size_t label_len,
|
||||||
|
const uint8_t *keyid,
|
||||||
|
size_t keyid_len,
|
||||||
|
size_t keysize,
|
||||||
|
uint8_t *buf,
|
||||||
|
size_t buf_len);
|
||||||
#endif
|
#endif
|
||||||
|
|||||||
511
src/hsm/dkek.c
511
src/hsm/dkek.c
@@ -1,511 +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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#include <string.h>
|
|
||||||
#include "common.h"
|
|
||||||
#include "stdlib.h"
|
|
||||||
#include "pico/stdlib.h"
|
|
||||||
#include "dkek.h"
|
|
||||||
#include "crypto_utils.h"
|
|
||||||
#include "random.h"
|
|
||||||
#include "sc_hsm.h"
|
|
||||||
#include "mbedtls/md.h"
|
|
||||||
#include "mbedtls/cmac.h"
|
|
||||||
#include "mbedtls/rsa.h"
|
|
||||||
#include "mbedtls/ecdsa.h"
|
|
||||||
#include "files.h"
|
|
||||||
|
|
||||||
extern bool has_session_pin;
|
|
||||||
extern uint8_t session_pin[32];
|
|
||||||
|
|
||||||
#define POLY 0xedb88320
|
|
||||||
|
|
||||||
uint32_t crc32c(const uint8_t *buf, size_t len)
|
|
||||||
{
|
|
||||||
uint32_t crc = ~0;
|
|
||||||
while (len--) {
|
|
||||||
crc ^= *buf++;
|
|
||||||
for (int k = 0; k < 8; k++)
|
|
||||||
crc = (crc >> 1) ^ (POLY & (0 - (crc & 1)));
|
|
||||||
}
|
|
||||||
return ~crc;
|
|
||||||
}
|
|
||||||
|
|
||||||
int load_dkek(uint8_t id, uint8_t *dkek) {
|
|
||||||
if (has_session_pin == false)
|
|
||||||
return CCID_NO_LOGIN;
|
|
||||||
file_t *tf = search_dynamic_file(EF_DKEK+id);
|
|
||||||
if (!tf)
|
|
||||||
return CCID_ERR_FILE_NOT_FOUND;
|
|
||||||
memcpy(dkek, file_get_data(tf), DKEK_SIZE);
|
|
||||||
int ret = aes_decrypt_cfb_256(session_pin, DKEK_IV(dkek), DKEK_KEY(dkek), DKEK_KEY_SIZE+DKEK_KEY_CS_SIZE);
|
|
||||||
if (ret != 0)
|
|
||||||
return CCID_EXEC_ERROR;
|
|
||||||
if (crc32c(DKEK_KEY(dkek), DKEK_KEY_SIZE) != *(uint32_t*)DKEK_CHECKSUM(dkek))
|
|
||||||
return CCID_WRONG_DKEK;
|
|
||||||
return CCID_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
void release_dkek(uint8_t *dkek) {
|
|
||||||
memset(dkek, 0, DKEK_SIZE);
|
|
||||||
}
|
|
||||||
|
|
||||||
int store_dkek_key(uint8_t id, uint8_t *dkek) {
|
|
||||||
file_t *tf = search_dynamic_file(EF_DKEK+id);
|
|
||||||
if (!tf)
|
|
||||||
return CCID_ERR_FILE_NOT_FOUND;
|
|
||||||
*(uint32_t*)DKEK_CHECKSUM(dkek) = crc32c(DKEK_KEY(dkek), DKEK_KEY_SIZE);
|
|
||||||
aes_encrypt_cfb_256(session_pin, DKEK_IV(dkek), DKEK_KEY(dkek), DKEK_KEY_SIZE+DKEK_KEY_CS_SIZE);
|
|
||||||
flash_write_data_to_file(tf, dkek, DKEK_SIZE);
|
|
||||||
low_flash_available();
|
|
||||||
release_dkek(dkek);
|
|
||||||
return CCID_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
int save_dkek_key(uint8_t id, const uint8_t *key) {
|
|
||||||
uint8_t dkek[DKEK_SIZE];
|
|
||||||
const uint8_t *iv = random_bytes_get(32);
|
|
||||||
memcpy(dkek, iv, DKEK_IV_SIZE);
|
|
||||||
if (!key) {
|
|
||||||
file_t *tf = search_dynamic_file(EF_DKEK+id);
|
|
||||||
if (!tf)
|
|
||||||
return CCID_ERR_FILE_NOT_FOUND;
|
|
||||||
memcpy(DKEK_KEY(dkek), file_get_data(tf), DKEK_KEY_SIZE);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
memcpy(DKEK_KEY(dkek), key, DKEK_KEY_SIZE);
|
|
||||||
return store_dkek_key(id, dkek);
|
|
||||||
}
|
|
||||||
|
|
||||||
int import_dkek_share(uint8_t id, const uint8_t *share) {
|
|
||||||
uint8_t tmp_dkek[DKEK_KEY_SIZE];
|
|
||||||
file_t *tf = search_dynamic_file(EF_DKEK+id);
|
|
||||||
if (!tf)
|
|
||||||
return CCID_ERR_FILE_NOT_FOUND;
|
|
||||||
memset(tmp_dkek, 0, sizeof(tmp_dkek));
|
|
||||||
if (file_get_size(tf) == DKEK_KEY_SIZE)
|
|
||||||
memcpy(tmp_dkek, file_get_data(tf),DKEK_KEY_SIZE);
|
|
||||||
for (int i = 0; i < DKEK_KEY_SIZE; i++)
|
|
||||||
tmp_dkek[i] ^= share[i];
|
|
||||||
flash_write_data_to_file(tf, tmp_dkek, DKEK_KEY_SIZE);
|
|
||||||
low_flash_available();
|
|
||||||
return CCID_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
int dkek_kcv(uint8_t id, uint8_t *kcv) { //kcv 8 bytes
|
|
||||||
uint8_t hsh[32], dkek[DKEK_SIZE];
|
|
||||||
int r = load_dkek(id, dkek);
|
|
||||||
if (r != CCID_OK)
|
|
||||||
return r;
|
|
||||||
hash256(DKEK_KEY(dkek), DKEK_KEY_SIZE, hsh);
|
|
||||||
release_dkek(dkek);
|
|
||||||
memcpy(kcv, hsh, 8);
|
|
||||||
return CCID_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
int dkek_kenc(uint8_t id, uint8_t *kenc) { //kenc 32 bytes
|
|
||||||
uint8_t dkek[DKEK_SIZE+4];
|
|
||||||
int r = load_dkek(id, dkek);
|
|
||||||
if (r != CCID_OK)
|
|
||||||
return r;
|
|
||||||
memcpy(DKEK_KEY(dkek)+DKEK_KEY_SIZE, "\x0\x0\x0\x1", 4);
|
|
||||||
hash256(DKEK_KEY(dkek), DKEK_KEY_SIZE+4, kenc);
|
|
||||||
release_dkek(dkek);
|
|
||||||
return CCID_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
int dkek_kmac(uint8_t id, uint8_t *kmac) { //kmac 32 bytes
|
|
||||||
uint8_t dkek[DKEK_SIZE+4];
|
|
||||||
int r = load_dkek(id, dkek);
|
|
||||||
if (r != CCID_OK)
|
|
||||||
return r;
|
|
||||||
memcpy(DKEK_KEY(dkek)+DKEK_KEY_SIZE, "\x0\x0\x0\x2", 4);
|
|
||||||
hash256(DKEK_KEY(dkek), DKEK_KEY_SIZE+4, kmac);
|
|
||||||
release_dkek(dkek);
|
|
||||||
return CCID_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
int dkek_encrypt(uint8_t id, uint8_t *data, size_t len) {
|
|
||||||
int r;
|
|
||||||
uint8_t dkek[DKEK_SIZE+4];
|
|
||||||
if ((r = load_dkek(id, dkek)) != CCID_OK)
|
|
||||||
return r;
|
|
||||||
r = aes_encrypt_cfb_256(DKEK_KEY(dkek), DKEK_IV(dkek), data, len);
|
|
||||||
release_dkek(dkek);
|
|
||||||
return r;
|
|
||||||
}
|
|
||||||
|
|
||||||
int dkek_decrypt(uint8_t id, uint8_t *data, size_t len) {
|
|
||||||
int r;
|
|
||||||
uint8_t dkek[DKEK_SIZE+4];
|
|
||||||
if ((r = load_dkek(id, dkek)) != CCID_OK)
|
|
||||||
return r;
|
|
||||||
r = aes_decrypt_cfb_256(DKEK_KEY(dkek), DKEK_IV(dkek), data, len);
|
|
||||||
release_dkek(dkek);
|
|
||||||
return r;
|
|
||||||
}
|
|
||||||
|
|
||||||
int dkek_encode_key(uint8_t id, void *key_ctx, int key_type, uint8_t *out, size_t *out_len) {
|
|
||||||
if (!(key_type & HSM_KEY_RSA) && !(key_type & HSM_KEY_EC) && !(key_type & HSM_KEY_AES))
|
|
||||||
return CCID_WRONG_DATA;
|
|
||||||
|
|
||||||
uint8_t kb[8+2*4+2*4096/8+3+13]; //worst case: RSA-4096 (plus, 13 bytes padding)
|
|
||||||
memset(kb, 0, sizeof(kb));
|
|
||||||
int kb_len = 0, r = 0;
|
|
||||||
uint8_t *algo = NULL;
|
|
||||||
uint8_t algo_len = 0;
|
|
||||||
uint8_t *allowed = NULL;
|
|
||||||
uint8_t allowed_len = 0;
|
|
||||||
uint8_t kenc[32];
|
|
||||||
memset(kenc, 0, sizeof(kenc));
|
|
||||||
r = dkek_kenc(id, kenc);
|
|
||||||
if (r != CCID_OK)
|
|
||||||
return r;
|
|
||||||
|
|
||||||
uint8_t kcv[8];
|
|
||||||
memset(kcv, 0, sizeof(kcv));
|
|
||||||
r = dkek_kcv(id, kcv);
|
|
||||||
if (r != CCID_OK)
|
|
||||||
return r;
|
|
||||||
|
|
||||||
uint8_t kmac[32];
|
|
||||||
memset(kmac, 0, sizeof(kmac));
|
|
||||||
r = dkek_kmac(id, kmac);
|
|
||||||
if (r != CCID_OK)
|
|
||||||
return r;
|
|
||||||
|
|
||||||
if (key_type & HSM_KEY_AES) {
|
|
||||||
if (key_type & HSM_KEY_AES_128)
|
|
||||||
kb_len = 16;
|
|
||||||
else if (key_type & HSM_KEY_AES_192)
|
|
||||||
kb_len = 24;
|
|
||||||
else if (key_type & HSM_KEY_AES_256)
|
|
||||||
kb_len = 32;
|
|
||||||
|
|
||||||
if (kb_len != 16 && kb_len != 24 && kb_len != 32)
|
|
||||||
return CCID_WRONG_DATA;
|
|
||||||
if (*out_len < 8+1+10+6+4+(2+32+14)+16)
|
|
||||||
return CCID_WRONG_LENGTH;
|
|
||||||
|
|
||||||
put_uint16_t(kb_len, kb+8);
|
|
||||||
memcpy(kb+10, key_ctx, kb_len);
|
|
||||||
kb_len += 2;
|
|
||||||
|
|
||||||
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;
|
|
||||||
allowed = (uint8_t *)"\x00\x04\x10\x11\x18\x99"; //(2+4)
|
|
||||||
allowed_len = 6;
|
|
||||||
}
|
|
||||||
else if (key_type & HSM_KEY_RSA) {
|
|
||||||
if (*out_len < 8+1+12+6+(8+2*4+2*4096/8+3+13)+16) //13 bytes pading
|
|
||||||
return CCID_WRONG_LENGTH;
|
|
||||||
mbedtls_rsa_context *rsa = (mbedtls_rsa_context *)key_ctx;
|
|
||||||
kb_len = 0;
|
|
||||||
put_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;
|
|
||||||
mbedtls_mpi_write_binary(&rsa->D, kb+8+kb_len, mbedtls_mpi_size(&rsa->D)); kb_len += mbedtls_mpi_size(&rsa->D);
|
|
||||||
put_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)); kb_len += mbedtls_mpi_size(&rsa->N);
|
|
||||||
put_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)); kb_len += mbedtls_mpi_size(&rsa->E);
|
|
||||||
|
|
||||||
algo = (uint8_t *)"\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x01\x02";
|
|
||||||
algo_len = 12;
|
|
||||||
}
|
|
||||||
else if (key_type & HSM_KEY_EC) {
|
|
||||||
if (*out_len < 8+1+12+6+(8+2*8+9*66+2+4)+16) //4 bytes pading
|
|
||||||
return CCID_WRONG_LENGTH;
|
|
||||||
mbedtls_ecdsa_context *ecdsa = (mbedtls_ecdsa_context *)key_ctx;
|
|
||||||
kb_len = 0;
|
|
||||||
put_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;
|
|
||||||
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);
|
|
||||||
put_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)); kb_len += mbedtls_mpi_size(&ecdsa->grp.B);
|
|
||||||
put_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)); kb_len += mbedtls_mpi_size(&ecdsa->grp.P);
|
|
||||||
put_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)); kb_len += 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;
|
|
||||||
kb[8+kb_len++] = 0x4;
|
|
||||||
mbedtls_mpi_write_binary(&ecdsa->grp.G.X, kb+8+kb_len, mbedtls_mpi_size(&ecdsa->grp.G.X)); kb_len += mbedtls_mpi_size(&ecdsa->grp.G.X);
|
|
||||||
mbedtls_mpi_write_binary(&ecdsa->grp.G.Y, kb+8+kb_len, mbedtls_mpi_size(&ecdsa->grp.G.Y)); kb_len += mbedtls_mpi_size(&ecdsa->grp.G.Y);
|
|
||||||
put_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)); kb_len += 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); kb_len += 2;
|
|
||||||
kb[8+kb_len++] = 0x4;
|
|
||||||
mbedtls_mpi_write_binary(&ecdsa->Q.X, kb+8+kb_len, mbedtls_mpi_size(&ecdsa->Q.X)); kb_len += mbedtls_mpi_size(&ecdsa->Q.X);
|
|
||||||
mbedtls_mpi_write_binary(&ecdsa->Q.Y, kb+8+kb_len, mbedtls_mpi_size(&ecdsa->Q.Y)); kb_len += mbedtls_mpi_size(&ecdsa->Q.Y);
|
|
||||||
|
|
||||||
algo = (uint8_t *)"\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x02\x03";
|
|
||||||
algo_len = 12;
|
|
||||||
}
|
|
||||||
memset(out, 0, *out_len);
|
|
||||||
*out_len = 0;
|
|
||||||
|
|
||||||
memcpy(out+*out_len, kcv, 8);
|
|
||||||
*out_len += 8;
|
|
||||||
|
|
||||||
if (key_type & HSM_KEY_AES)
|
|
||||||
out[*out_len] = 15;
|
|
||||||
else if (key_type & HSM_KEY_RSA)
|
|
||||||
out[*out_len] = 5;
|
|
||||||
else if (key_type & HSM_KEY_EC)
|
|
||||||
out[*out_len] = 12;
|
|
||||||
*out_len += 1;
|
|
||||||
|
|
||||||
if (algo) {
|
|
||||||
memcpy(out+*out_len, algo, algo_len);
|
|
||||||
*out_len += algo_len;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
*out_len += 2;
|
|
||||||
|
|
||||||
if (allowed) {
|
|
||||||
memcpy(out+*out_len, allowed, allowed_len);
|
|
||||||
*out_len += allowed_len;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
*out_len += 2;
|
|
||||||
//add 4 zeros
|
|
||||||
*out_len += 4;
|
|
||||||
|
|
||||||
memcpy(kb, random_bytes_get(8), 8);
|
|
||||||
kb_len += 8; //8 random bytes
|
|
||||||
int kb_len_pad = ((int)(kb_len/16))*16;
|
|
||||||
if (kb_len % 16 > 0)
|
|
||||||
kb_len_pad = ((int)(kb_len/16)+1)*16;
|
|
||||||
//key already copied at kb+10
|
|
||||||
if (kb_len < kb_len_pad) {
|
|
||||||
kb[kb_len] = 0x80;
|
|
||||||
}
|
|
||||||
r = aes_encrypt(kenc, NULL, 256, HSM_AES_MODE_CBC, kb, kb_len_pad);
|
|
||||||
if (r != CCID_OK)
|
|
||||||
return r;
|
|
||||||
|
|
||||||
memcpy(out+*out_len, kb, kb_len_pad);
|
|
||||||
*out_len += kb_len_pad;
|
|
||||||
|
|
||||||
r = mbedtls_cipher_cmac(mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_256_ECB), kmac, 256, out, *out_len, out+*out_len);
|
|
||||||
|
|
||||||
*out_len += 16;
|
|
||||||
if (r != 0)
|
|
||||||
return r;
|
|
||||||
return CCID_OK;
|
|
||||||
}
|
|
||||||
|
|
||||||
int dkek_type_key(const uint8_t *in) {
|
|
||||||
if (in[8] == 5 || in[8] == 6)
|
|
||||||
return HSM_KEY_RSA;
|
|
||||||
else if (in[8] == 12)
|
|
||||||
return HSM_KEY_EC;
|
|
||||||
else if (in[8] == 15)
|
|
||||||
return HSM_KEY_AES;
|
|
||||||
return 0x0;
|
|
||||||
}
|
|
||||||
|
|
||||||
int dkek_decode_key(uint8_t id, void *key_ctx, const uint8_t *in, size_t in_len, int *key_size_out) {
|
|
||||||
uint8_t kcv[8];
|
|
||||||
int r = 0;
|
|
||||||
memset(kcv, 0, sizeof(kcv));
|
|
||||||
r = dkek_kcv(id, kcv);
|
|
||||||
if (r != CCID_OK)
|
|
||||||
return r;
|
|
||||||
|
|
||||||
uint8_t kmac[32];
|
|
||||||
memset(kmac, 0, sizeof(kmac));
|
|
||||||
r = dkek_kmac(id, kmac);
|
|
||||||
if (r != CCID_OK)
|
|
||||||
return r;
|
|
||||||
|
|
||||||
uint8_t kenc[32];
|
|
||||||
memset(kenc, 0, sizeof(kenc));
|
|
||||||
r = dkek_kenc(id, kenc);
|
|
||||||
if (r != CCID_OK)
|
|
||||||
return r;
|
|
||||||
|
|
||||||
if (memcmp(kcv, in, 8) != 0)
|
|
||||||
return CCID_WRONG_DKEK;
|
|
||||||
|
|
||||||
uint8_t signature[16];
|
|
||||||
r = mbedtls_cipher_cmac(mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_256_ECB), kmac, 256, in, in_len-16, signature);
|
|
||||||
if (r != 0)
|
|
||||||
return CCID_WRONG_SIGNATURE;
|
|
||||||
if (memcmp(signature, in+in_len-16, 16) != 0)
|
|
||||||
return CCID_WRONG_SIGNATURE;
|
|
||||||
|
|
||||||
int key_type = in[8];
|
|
||||||
if (key_type != 5 && key_type != 6 && key_type != 12 && key_type != 15)
|
|
||||||
return CCID_WRONG_DATA;
|
|
||||||
|
|
||||||
if ((key_type == 5 || key_type == 6) && memcmp(in+9, "\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x01\x02", 12) != 0)
|
|
||||||
return CCID_WRONG_DATA;
|
|
||||||
|
|
||||||
if (key_type == 12 && memcmp(in+9, "\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x02\x03", 12) != 0)
|
|
||||||
return CCID_WRONG_DATA;
|
|
||||||
|
|
||||||
if (key_type == 15 && memcmp(in+9, "\x00\x08\x60\x86\x48\x01\x65\x03\x04\x01", 10) != 0)
|
|
||||||
return CCID_WRONG_DATA;
|
|
||||||
|
|
||||||
size_t ofs = 9;
|
|
||||||
|
|
||||||
//OID
|
|
||||||
size_t len = get_uint16_t(in, ofs);
|
|
||||||
ofs += len+2;
|
|
||||||
|
|
||||||
//Allowed algorithms
|
|
||||||
len = get_uint16_t(in, ofs);
|
|
||||||
ofs += len+2;
|
|
||||||
|
|
||||||
//Access conditions
|
|
||||||
len = get_uint16_t(in, ofs);
|
|
||||||
ofs += len+2;
|
|
||||||
|
|
||||||
//Key OID
|
|
||||||
len = get_uint16_t(in, ofs);
|
|
||||||
ofs += len+2;
|
|
||||||
|
|
||||||
if ((in_len-16-ofs) % 16 != 0)
|
|
||||||
return CCID_WRONG_PADDING;
|
|
||||||
uint8_t kb[8+2*4+2*4096/8+3+13]; //worst case: RSA-4096 (plus, 13 bytes padding)
|
|
||||||
memset(kb, 0, sizeof(kb));
|
|
||||||
memcpy(kb, in+ofs, in_len-16-ofs);
|
|
||||||
r = aes_decrypt(kenc, NULL, 256, HSM_AES_MODE_CBC, kb, in_len-16-ofs);
|
|
||||||
if (r != CCID_OK)
|
|
||||||
return r;
|
|
||||||
|
|
||||||
int key_size = get_uint16_t(kb, 8);
|
|
||||||
if (key_size_out)
|
|
||||||
*key_size_out = key_size;
|
|
||||||
ofs = 10;
|
|
||||||
if (key_type == 5 || key_type == 6) {
|
|
||||||
mbedtls_rsa_context *rsa = (mbedtls_rsa_context *)key_ctx;
|
|
||||||
mbedtls_rsa_init(rsa);
|
|
||||||
if (key_type == 5) {
|
|
||||||
len = get_uint16_t(kb, ofs); ofs += 2;
|
|
||||||
r = mbedtls_mpi_read_binary(&rsa->D, kb+ofs, len); ofs += len;
|
|
||||||
if (r != 0) {
|
|
||||||
mbedtls_rsa_free(rsa);
|
|
||||||
return CCID_WRONG_DATA;
|
|
||||||
}
|
|
||||||
|
|
||||||
len = get_uint16_t(kb, ofs); ofs += 2;
|
|
||||||
r = mbedtls_mpi_read_binary(&rsa->N, kb+ofs, len); ofs += len;
|
|
||||||
if (r != 0) {
|
|
||||||
mbedtls_rsa_free(rsa);
|
|
||||||
return CCID_WRONG_DATA;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (key_type == 6) {
|
|
||||||
//DP-1
|
|
||||||
len = get_uint16_t(kb, ofs); ofs += len+2;
|
|
||||||
|
|
||||||
//DQ-1
|
|
||||||
len = get_uint16_t(kb, ofs); ofs += len+2;
|
|
||||||
|
|
||||||
len = get_uint16_t(kb, ofs); ofs += 2;
|
|
||||||
r = mbedtls_mpi_read_binary(&rsa->P, kb+ofs, len); ofs += len;
|
|
||||||
if (r != 0) {
|
|
||||||
mbedtls_rsa_free(rsa);
|
|
||||||
return CCID_WRONG_DATA;
|
|
||||||
}
|
|
||||||
|
|
||||||
//PQ
|
|
||||||
len = get_uint16_t(kb, ofs); ofs += len+2;
|
|
||||||
|
|
||||||
len = get_uint16_t(kb, ofs); ofs += 2;
|
|
||||||
r = mbedtls_mpi_read_binary(&rsa->Q, kb+ofs, len); ofs += len;
|
|
||||||
if (r != 0) {
|
|
||||||
mbedtls_rsa_free(rsa);
|
|
||||||
return CCID_WRONG_DATA;
|
|
||||||
}
|
|
||||||
//N
|
|
||||||
len = get_uint16_t(kb, ofs); ofs += len+2;
|
|
||||||
}
|
|
||||||
|
|
||||||
len = get_uint16_t(kb, ofs); ofs += 2;
|
|
||||||
r = mbedtls_mpi_read_binary(&rsa->E, kb+ofs, len); ofs += len;
|
|
||||||
if (r != 0) {
|
|
||||||
mbedtls_rsa_free(rsa);
|
|
||||||
return CCID_WRONG_DATA;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (key_type == 5) {
|
|
||||||
r = mbedtls_rsa_import(rsa, &rsa->N, NULL, NULL, &rsa->D, &rsa->E);
|
|
||||||
if (r != 0) {
|
|
||||||
mbedtls_rsa_free(rsa);
|
|
||||||
return CCID_EXEC_ERROR;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (key_type == 6) {
|
|
||||||
r = mbedtls_rsa_import(rsa, NULL, &rsa->P, &rsa->Q, NULL, &rsa->E);
|
|
||||||
if (r != 0) {
|
|
||||||
mbedtls_rsa_free(rsa);
|
|
||||||
return CCID_EXEC_ERROR;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
r = mbedtls_rsa_complete(rsa);
|
|
||||||
if (r != 0) {
|
|
||||||
mbedtls_rsa_free(rsa);
|
|
||||||
return CCID_EXEC_ERROR;
|
|
||||||
}
|
|
||||||
r = mbedtls_rsa_check_privkey(rsa);
|
|
||||||
if (r != 0) {
|
|
||||||
mbedtls_rsa_free(rsa);
|
|
||||||
return CCID_EXEC_ERROR;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (key_type == 12) {
|
|
||||||
mbedtls_ecdsa_context *ecdsa = (mbedtls_ecdsa_context *)key_ctx;
|
|
||||||
mbedtls_ecdsa_init(ecdsa);
|
|
||||||
|
|
||||||
//A
|
|
||||||
len = get_uint16_t(kb, ofs); ofs += len+2;
|
|
||||||
|
|
||||||
//B
|
|
||||||
len = get_uint16_t(kb, ofs); ofs += len+2;
|
|
||||||
|
|
||||||
//P
|
|
||||||
len = get_uint16_t(kb, ofs); ofs += 2;
|
|
||||||
mbedtls_ecp_group_id ec_id = ec_get_curve_from_prime(kb+ofs, len);
|
|
||||||
if (ec_id == MBEDTLS_ECP_DP_NONE) {
|
|
||||||
mbedtls_ecdsa_free(ecdsa);
|
|
||||||
return CCID_WRONG_DATA;
|
|
||||||
}
|
|
||||||
ofs += len;
|
|
||||||
|
|
||||||
//N
|
|
||||||
len = get_uint16_t(kb, ofs); ofs += len+2;
|
|
||||||
|
|
||||||
//G
|
|
||||||
len = get_uint16_t(kb, ofs); ofs += len+2;
|
|
||||||
|
|
||||||
//d
|
|
||||||
len = get_uint16_t(kb, ofs); ofs += 2;
|
|
||||||
r = mbedtls_ecp_read_key(ec_id, ecdsa, kb+ofs, len);
|
|
||||||
if (r != 0) {
|
|
||||||
mbedtls_ecdsa_free(ecdsa);
|
|
||||||
return CCID_EXEC_ERROR;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if (key_type == 15) {
|
|
||||||
memcpy(key_ctx, kb+ofs, key_size);
|
|
||||||
}
|
|
||||||
return CCID_OK;
|
|
||||||
}
|
|
||||||
@@ -1,46 +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/>.
|
|
||||||
*/
|
|
||||||
|
|
||||||
#ifndef _DKEK_H_
|
|
||||||
#define _DKEK_H_
|
|
||||||
|
|
||||||
extern int load_dkek(uint8_t, uint8_t *);
|
|
||||||
extern int save_dkek_key(uint8_t, const uint8_t *key);
|
|
||||||
extern int store_dkek_key(uint8_t, uint8_t *);
|
|
||||||
extern void init_dkek();
|
|
||||||
extern void release_dkek(uint8_t *);
|
|
||||||
extern int import_dkek_share(uint8_t, const uint8_t *share);
|
|
||||||
extern int dkek_kcv(uint8_t, uint8_t *kcv);
|
|
||||||
extern int dkek_encrypt(uint8_t, uint8_t *data, size_t len);
|
|
||||||
extern int dkek_decrypt(uint8_t, uint8_t *data, size_t len);
|
|
||||||
extern int dkek_encode_key(uint8_t, void *key_ctx, int key_type, uint8_t *out, size_t *out_len);
|
|
||||||
extern int dkek_type_key(const uint8_t *in);
|
|
||||||
extern int dkek_decode_key(uint8_t, void *key_ctx, const uint8_t *in, size_t in_len, int *key_size_out);
|
|
||||||
|
|
||||||
#define MAX_DKEK_ENCODE_KEY_BUFFER (8+1+12+6+(8+2*4+2*4096/8+3+13)+16)
|
|
||||||
|
|
||||||
#define MAX_KEY_DOMAINS 16
|
|
||||||
|
|
||||||
#define DKEK_IV_SIZE (IV_SIZE)
|
|
||||||
#define DKEK_KEY_SIZE (32)
|
|
||||||
#define DKEK_KEY_CS_SIZE (4)
|
|
||||||
#define DKEK_SIZE (DKEK_IV_SIZE+DKEK_KEY_SIZE+DKEK_KEY_CS_SIZE)
|
|
||||||
#define DKEK_KEY(p) (p+DKEK_IV_SIZE)
|
|
||||||
#define DKEK_IV(p) (p)
|
|
||||||
#define DKEK_CHECKSUM(p) (p+DKEK_IV_SIZE+DKEK_KEY_SIZE)
|
|
||||||
|
|
||||||
#endif
|
|
||||||
116
src/hsm/files.c
116
src/hsm/files.c
@@ -19,42 +19,96 @@
|
|||||||
|
|
||||||
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_cvca(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, .ef_structure = 0, .acl = {0} }, // MF
|
/* 0 */ { .fid = 0x3f00, .parent = 0xff, .name = NULL, .type = FILE_TYPE_DF, .data = NULL,
|
||||||
/* 1 */ { .fid = 0x2f00 , .parent = 0, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} }, //EF.DIR
|
.ef_structure = 0, .acl = { 0 } }, // MF
|
||||||
/* 2 */ { .fid = 0x2f01 , .parent = 0, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} }, //EF.ATR
|
/* 1 */ { .fid = 0x2f00, .parent = 0, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL,
|
||||||
/* 3 */ { .fid = 0x2f02 , .parent = 0, .name = NULL, .type = FILE_TYPE_WORKING_EF | FILE_DATA_FUNC,.data = (uint8_t *)parse_cvca, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} }, //EF.GDO
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.DIR
|
||||||
/* 4 */ { .fid = 0x2f03 , .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF | FILE_DATA_FUNC,.data = (uint8_t *)parse_token_info, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} }, //EF.TokenInfo
|
/* 2 */ { .fid = 0x2f01, .parent = 0, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL,
|
||||||
/* 5 */ { .fid = 0x5015 , .parent = 0, .name = NULL, .type = FILE_TYPE_DF, .data = NULL, .ef_structure = 0, .acl = {0} }, //DF.PKCS15
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.ATR
|
||||||
/* 6 */ { .fid = 0x5031 , .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} }, //EF.ODF
|
/* 3 */ { .fid = EF_TERMCA, .parent = 0, .name = NULL,
|
||||||
/* 7 */ { .fid = 0x5032 , .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} }, //EF.TokenInfo
|
.type = FILE_TYPE_WORKING_EF | FILE_DATA_FLASH | FILE_PERSISTENT, .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.GDO
|
||||||
/* 9 */ { .fid = 0x1081 , .parent = 5, .name = NULL, .type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0xff} }, //PIN (PIN1)
|
/* 4 */ { .fid = 0x2f03, .parent = 5, .name = NULL,
|
||||||
/* 10 */ { .fid = 0x1082 , .parent = 5, .name = NULL, .type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0xff} }, //max retries PIN (PIN1)
|
.type = FILE_TYPE_WORKING_EF | FILE_DATA_FUNC, .data = (uint8_t *) parse_token_info,
|
||||||
/* 11 */ { .fid = 0x1083 , .parent = 5, .name = 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 = { 0 } }, //EF.TokenInfo
|
||||||
/* 12 */ { .fid = 0x1088 , .parent = 5, .name = NULL, .type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0xff} }, //PIN (SOPIN)
|
/* 5 */ { .fid = 0x5015, .parent = 0, .name = NULL, .type = FILE_TYPE_DF, .data = NULL,
|
||||||
/* 13 */ { .fid = 0x1089 , .parent = 5, .name = NULL, .type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0xff} }, //max retries PIN (SOPIN)
|
.ef_structure = 0, .acl = { 0 } }, //DF.PKCS15
|
||||||
/* 14 */ { .fid = 0x108A , .parent = 5, .name = NULL, .type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0xff} }, //retries PIN (SOPIN)
|
/* 6 */ { .fid = 0x5031, .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL,
|
||||||
/* 15 */ { .fid = EF_DEVOPS , .parent = 5, .name = NULL, .type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0xff} }, //Device options
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.ODF
|
||||||
/* 16 */ { .fid = EF_PRKDFS , .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} }, //EF.PrKDFs
|
/* 7 */ { .fid = 0x5032, .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL,
|
||||||
/* 17 */ { .fid = EF_PUKDFS , .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} }, //EF.PuKDFs
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.TokenInfo
|
||||||
/* 18 */ { .fid = EF_CDFS , .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} }, //EF.CDFs
|
/* 8 */ { .fid = 0x5033, .parent = 0, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL,
|
||||||
/* 19 */ { .fid = EF_AODFS , .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} }, //EF.AODFs
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.UnusedSpace
|
||||||
/* 20 */ { .fid = EF_DODFS , .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} }, //EF.DODFs
|
/* 9 */ { .fid = 0x1081, .parent = 5, .name = NULL,
|
||||||
/* 21 */ { .fid = EF_SKDFS , .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} }, //EF.SKDFs
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
||||||
/* 22 */ { .fid = EF_KEY_DOMAIN, .parent = 5, .name = NULL, .type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0xff} }, //Key domain options
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //PIN (PIN1)
|
||||||
/* 23 */ { .fid = EF_META , .parent = 5, .name = NULL, .type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0xff} }, //EF.CDFs
|
/* 10 */ { .fid = 0x1082, .parent = 5, .name = NULL,
|
||||||
///* 22 */ { .fid = 0x0000, .parent = 0, .name = openpgpcard_aid, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} },
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
||||||
/* 24 */ { .fid = 0x0000, .parent = 5, .name = sc_hsm_aid, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} },
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //max retries PIN (PIN1)
|
||||||
/* 25 */ { .fid = 0x0000, .parent = 0xff, .name = NULL, .type = FILE_TYPE_UNKNOWN, .data = NULL, .ef_structure = 0, .acl = {0} } //end
|
/* 11 */ { .fid = 0x1083, .parent = 5, .name = NULL,
|
||||||
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
||||||
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //retries PIN (PIN1)
|
||||||
|
/* 12 */ { .fid = 0x1088, .parent = 5, .name = NULL,
|
||||||
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
||||||
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //PIN (SOPIN)
|
||||||
|
/* 13 */ { .fid = 0x1089, .parent = 5, .name = NULL,
|
||||||
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
||||||
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //max retries PIN (SOPIN)
|
||||||
|
/* 14 */ { .fid = 0x108A, .parent = 5, .name = NULL,
|
||||||
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
||||||
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //retries PIN (SOPIN)
|
||||||
|
/* 15 */ { .fid = EF_DEVOPS, .parent = 5, .name = NULL,
|
||||||
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
||||||
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //Device options
|
||||||
|
/* 16 */ { .fid = EF_PRKDFS, .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF,
|
||||||
|
.data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.PrKDFs
|
||||||
|
/* 17 */ { .fid = EF_PUKDFS, .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF,
|
||||||
|
.data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.PuKDFs
|
||||||
|
/* 18 */ { .fid = EF_CDFS, .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF,
|
||||||
|
.data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.CDFs
|
||||||
|
/* 19 */ { .fid = EF_AODFS, .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF,
|
||||||
|
.data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.AODFs
|
||||||
|
/* 20 */ { .fid = EF_DODFS, .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF,
|
||||||
|
.data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.DODFs
|
||||||
|
/* 21 */ { .fid = EF_SKDFS, .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF,
|
||||||
|
.data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.SKDFs
|
||||||
|
/* 22 */ { .fid = EF_KEY_DOMAIN, .parent = 5, .name = NULL,
|
||||||
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
||||||
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //Key domain options
|
||||||
|
/* 23 */ { .fid = EF_META, .parent = 5, .name = NULL,
|
||||||
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
||||||
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //EF.CDFs
|
||||||
|
/* 24 */ { .fid = EF_PUKAUT, .parent = 5, .name = NULL,
|
||||||
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
||||||
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //Public Key Authentication
|
||||||
|
/* 25 */ { .fid = EF_KEY_DEV, .parent = 5, .name = NULL,
|
||||||
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH | FILE_PERSISTENT, .data = NULL,
|
||||||
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //Device Key
|
||||||
|
/* 26 */ { .fid = EF_PRKD_DEV, .parent = 5, .name = NULL,
|
||||||
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH | FILE_PERSISTENT, .data = NULL,
|
||||||
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //PrKD Device
|
||||||
|
/* 27 */ { .fid = EF_EE_DEV, .parent = 5, .name = NULL,
|
||||||
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH | FILE_PERSISTENT, .data = NULL,
|
||||||
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //End Entity Certificate Device
|
||||||
|
/* 28 */ { .fid = EF_MKEK, .parent = 5, .name = NULL,
|
||||||
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH | FILE_PERSISTENT, .data = NULL,
|
||||||
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //MKEK
|
||||||
|
/* 29 */ { .fid = EF_MKEK_SO, .parent = 5, .name = NULL,
|
||||||
|
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH | FILE_PERSISTENT, .data = NULL,
|
||||||
|
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //MKEK with SO-PIN
|
||||||
|
///* 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,
|
||||||
|
.data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } },
|
||||||
|
/* 32 */ { .fid = 0x0000, .parent = 0xff, .name = NULL, .type = FILE_TYPE_UNKNOWN, .data = NULL,
|
||||||
|
.ef_structure = 0, .acl = { 0 } } //end
|
||||||
};
|
};
|
||||||
|
|
||||||
const file_t *MF = &file_entries[0];
|
const file_t *MF = &file_entries[0];
|
||||||
const file_t *file_last = &file_entries[sizeof(file_entries)/sizeof(file_t)-1];
|
const file_t *file_last = &file_entries[sizeof(file_entries) / sizeof(file_t) - 1];
|
||||||
const file_t *file_openpgp = &file_entries[sizeof(file_entries)/sizeof(file_t)-3];
|
const file_t *file_openpgp = &file_entries[sizeof(file_entries) / sizeof(file_t) - 3];
|
||||||
const file_t *file_sc_hsm = &file_entries[sizeof(file_entries)/sizeof(file_t)-2];
|
const file_t *file_sc_hsm = &file_entries[sizeof(file_entries) / sizeof(file_t) - 2];
|
||||||
file_t *file_pin1 = NULL;
|
file_t *file_pin1 = NULL;
|
||||||
file_t *file_retries_pin1 = NULL;
|
file_t *file_retries_pin1 = NULL;
|
||||||
file_t *file_sopin = NULL;
|
file_t *file_sopin = NULL;
|
||||||
|
|||||||
@@ -22,8 +22,13 @@
|
|||||||
#include "file.h"
|
#include "file.h"
|
||||||
|
|
||||||
#define EF_DEVOPS 0x100E
|
#define EF_DEVOPS 0x100E
|
||||||
|
#define EF_MKEK 0x100A
|
||||||
|
#define EF_MKEK_SO 0x100B
|
||||||
|
#define EF_XKEK 0x1080
|
||||||
#define EF_DKEK 0x1090
|
#define EF_DKEK 0x1090
|
||||||
#define EF_KEY_DOMAIN 0x10A0
|
#define EF_KEY_DOMAIN 0x10A0
|
||||||
|
#define EF_PUKAUT 0x10C0
|
||||||
|
#define EF_PUK 0X10D0
|
||||||
#define EF_PRKDFS 0x6040
|
#define EF_PRKDFS 0x6040
|
||||||
#define EF_PUKDFS 0x6041
|
#define EF_PUKDFS 0x6041
|
||||||
#define EF_CDFS 0x6042
|
#define EF_CDFS 0x6042
|
||||||
@@ -31,6 +36,12 @@
|
|||||||
#define EF_DODFS 0x6044
|
#define EF_DODFS 0x6044
|
||||||
#define EF_SKDFS 0x6045
|
#define EF_SKDFS 0x6045
|
||||||
|
|
||||||
|
#define EF_KEY_DEV 0xCC00
|
||||||
|
#define EF_PRKD_DEV 0xC400
|
||||||
|
#define EF_EE_DEV 0xCE00
|
||||||
|
|
||||||
|
#define EF_TERMCA 0x2f02
|
||||||
|
|
||||||
extern file_t *file_pin1;
|
extern file_t *file_pin1;
|
||||||
extern file_t *file_retries_pin1;
|
extern file_t *file_retries_pin1;
|
||||||
extern file_t *file_sopin;
|
extern file_t *file_sopin;
|
||||||
|
|||||||
720
src/hsm/kek.c
Normal file
720
src/hsm/kek.c
Normal file
@@ -0,0 +1,720 @@
|
|||||||
|
/*
|
||||||
|
* 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 <string.h>
|
||||||
|
#include "common.h"
|
||||||
|
#include "stdlib.h"
|
||||||
|
#ifndef ENABLE_EMULATION
|
||||||
|
#include "pico/stdlib.h"
|
||||||
|
#endif
|
||||||
|
#include "kek.h"
|
||||||
|
#include "crypto_utils.h"
|
||||||
|
#include "random.h"
|
||||||
|
#include "sc_hsm.h"
|
||||||
|
#include "mbedtls/md.h"
|
||||||
|
#include "mbedtls/cmac.h"
|
||||||
|
#include "mbedtls/rsa.h"
|
||||||
|
#include "mbedtls/ecdsa.h"
|
||||||
|
#include "mbedtls/chachapoly.h"
|
||||||
|
#include "files.h"
|
||||||
|
|
||||||
|
extern bool has_session_pin, has_session_sopin;
|
||||||
|
extern uint8_t session_pin[32], session_sopin[32];
|
||||||
|
uint8_t mkek_mask[MKEK_KEY_SIZE];
|
||||||
|
bool has_mkek_mask = false;
|
||||||
|
|
||||||
|
#define POLY 0xedb88320
|
||||||
|
|
||||||
|
uint32_t crc32c(const uint8_t *buf, size_t len) {
|
||||||
|
uint32_t crc = ~0;
|
||||||
|
while (len--) {
|
||||||
|
crc ^= *buf++;
|
||||||
|
for (int k = 0; k < 8; k++) {
|
||||||
|
crc = (crc >> 1) ^ (POLY & (0 - (crc & 1)));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return ~crc;
|
||||||
|
}
|
||||||
|
|
||||||
|
int load_mkek(uint8_t *mkek) {
|
||||||
|
if (has_session_pin == false && has_session_sopin == false) {
|
||||||
|
return CCID_NO_LOGIN;
|
||||||
|
}
|
||||||
|
const uint8_t *pin = NULL;
|
||||||
|
if (pin == NULL && has_session_pin == true) {
|
||||||
|
file_t *tf = search_by_fid(EF_MKEK, NULL, SPECIFY_EF);
|
||||||
|
if (file_has_data(tf)) {
|
||||||
|
memcpy(mkek, file_get_data(tf), MKEK_SIZE);
|
||||||
|
pin = session_pin;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (pin == NULL && has_session_sopin == true) {
|
||||||
|
file_t *tf = search_by_fid(EF_MKEK_SO, NULL, SPECIFY_EF);
|
||||||
|
if (file_has_data(tf)) {
|
||||||
|
memcpy(mkek, file_get_data(tf), MKEK_SIZE);
|
||||||
|
pin = session_sopin;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (pin == NULL) { //Should never happen
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (has_mkek_mask) {
|
||||||
|
for (int i = 0; i < MKEK_KEY_SIZE; i++) {
|
||||||
|
MKEK_KEY(mkek)[i] ^= mkek_mask[i];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
int ret =
|
||||||
|
aes_decrypt_cfb_256(pin, MKEK_IV(mkek), MKEK_KEY(mkek), MKEK_KEY_SIZE + MKEK_KEY_CS_SIZE);
|
||||||
|
if (ret != 0) {
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
if (crc32c(MKEK_KEY(mkek), MKEK_KEY_SIZE) != *(uint32_t *) MKEK_CHECKSUM(mkek)) {
|
||||||
|
return CCID_WRONG_DKEK;
|
||||||
|
}
|
||||||
|
return CCID_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
mse_t mse = { .init = false };
|
||||||
|
|
||||||
|
int mse_decrypt_ct(uint8_t *data, size_t len) {
|
||||||
|
mbedtls_chachapoly_context chatx;
|
||||||
|
mbedtls_chachapoly_init(&chatx);
|
||||||
|
mbedtls_chachapoly_setkey(&chatx, mse.key_enc + 12);
|
||||||
|
int ret = mbedtls_chachapoly_auth_decrypt(&chatx,
|
||||||
|
len - 16,
|
||||||
|
mse.key_enc,
|
||||||
|
mse.Qpt,
|
||||||
|
65,
|
||||||
|
data + len - 16,
|
||||||
|
data,
|
||||||
|
data);
|
||||||
|
mbedtls_chachapoly_free(&chatx);
|
||||||
|
return ret;
|
||||||
|
}
|
||||||
|
|
||||||
|
int load_dkek(uint8_t id, uint8_t *dkek) {
|
||||||
|
file_t *tf = search_dynamic_file(EF_DKEK + id);
|
||||||
|
if (!tf) {
|
||||||
|
return CCID_ERR_FILE_NOT_FOUND;
|
||||||
|
}
|
||||||
|
memcpy(dkek, file_get_data(tf), DKEK_KEY_SIZE);
|
||||||
|
return mkek_decrypt(dkek, DKEK_KEY_SIZE);
|
||||||
|
}
|
||||||
|
|
||||||
|
void release_mkek(uint8_t *mkek) {
|
||||||
|
mbedtls_platform_zeroize(mkek, MKEK_SIZE);
|
||||||
|
}
|
||||||
|
|
||||||
|
int store_mkek(const uint8_t *mkek) {
|
||||||
|
if (has_session_pin == false && has_session_sopin == false) {
|
||||||
|
return CCID_NO_LOGIN;
|
||||||
|
}
|
||||||
|
uint8_t tmp_mkek[MKEK_SIZE];
|
||||||
|
if (mkek == NULL) {
|
||||||
|
const uint8_t *rd = random_bytes_get(MKEK_IV_SIZE + MKEK_KEY_SIZE);
|
||||||
|
memcpy(tmp_mkek, rd, MKEK_IV_SIZE + MKEK_KEY_SIZE);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
memcpy(tmp_mkek, mkek, MKEK_SIZE);
|
||||||
|
}
|
||||||
|
*(uint32_t *) MKEK_CHECKSUM(tmp_mkek) = crc32c(MKEK_KEY(tmp_mkek), MKEK_KEY_SIZE);
|
||||||
|
if (has_session_pin) {
|
||||||
|
uint8_t tmp_mkek_pin[MKEK_SIZE];
|
||||||
|
memcpy(tmp_mkek_pin, tmp_mkek, MKEK_SIZE);
|
||||||
|
file_t *tf = search_by_fid(EF_MKEK, NULL, SPECIFY_EF);
|
||||||
|
if (!tf) {
|
||||||
|
release_mkek(tmp_mkek);
|
||||||
|
release_mkek(tmp_mkek_pin);
|
||||||
|
return CCID_ERR_FILE_NOT_FOUND;
|
||||||
|
}
|
||||||
|
aes_encrypt_cfb_256(session_pin,
|
||||||
|
MKEK_IV(tmp_mkek_pin),
|
||||||
|
MKEK_KEY(tmp_mkek_pin),
|
||||||
|
MKEK_KEY_SIZE + MKEK_KEY_CS_SIZE);
|
||||||
|
flash_write_data_to_file(tf, tmp_mkek_pin, MKEK_SIZE);
|
||||||
|
release_mkek(tmp_mkek_pin);
|
||||||
|
}
|
||||||
|
if (has_session_sopin) {
|
||||||
|
uint8_t tmp_mkek_sopin[MKEK_SIZE];
|
||||||
|
memcpy(tmp_mkek_sopin, tmp_mkek, MKEK_SIZE);
|
||||||
|
file_t *tf = search_by_fid(EF_MKEK_SO, NULL, SPECIFY_EF);
|
||||||
|
if (!tf) {
|
||||||
|
release_mkek(tmp_mkek);
|
||||||
|
release_mkek(tmp_mkek_sopin);
|
||||||
|
return CCID_ERR_FILE_NOT_FOUND;
|
||||||
|
}
|
||||||
|
aes_encrypt_cfb_256(session_sopin,
|
||||||
|
MKEK_IV(tmp_mkek_sopin),
|
||||||
|
MKEK_KEY(tmp_mkek_sopin),
|
||||||
|
MKEK_KEY_SIZE + MKEK_KEY_CS_SIZE);
|
||||||
|
flash_write_data_to_file(tf, tmp_mkek_sopin, MKEK_SIZE);
|
||||||
|
release_mkek(tmp_mkek_sopin);
|
||||||
|
}
|
||||||
|
low_flash_available();
|
||||||
|
release_mkek(tmp_mkek);
|
||||||
|
return CCID_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
int store_dkek_key(uint8_t id, uint8_t *dkek) {
|
||||||
|
file_t *tf = search_dynamic_file(EF_DKEK + id);
|
||||||
|
if (!tf) {
|
||||||
|
return CCID_ERR_FILE_NOT_FOUND;
|
||||||
|
}
|
||||||
|
int r = mkek_encrypt(dkek, DKEK_KEY_SIZE);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
flash_write_data_to_file(tf, dkek, DKEK_KEY_SIZE);
|
||||||
|
low_flash_available();
|
||||||
|
return CCID_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
int save_dkek_key(uint8_t id, const uint8_t *key) {
|
||||||
|
uint8_t dkek[DKEK_KEY_SIZE];
|
||||||
|
if (!key) {
|
||||||
|
file_t *tf = search_dynamic_file(EF_DKEK + id);
|
||||||
|
if (!tf) {
|
||||||
|
return CCID_ERR_FILE_NOT_FOUND;
|
||||||
|
}
|
||||||
|
memcpy(dkek, file_get_data(tf), DKEK_KEY_SIZE);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
memcpy(dkek, key, DKEK_KEY_SIZE);
|
||||||
|
}
|
||||||
|
return store_dkek_key(id, dkek);
|
||||||
|
}
|
||||||
|
|
||||||
|
int import_dkek_share(uint8_t id, const uint8_t *share) {
|
||||||
|
uint8_t tmp_dkek[DKEK_KEY_SIZE];
|
||||||
|
file_t *tf = search_dynamic_file(EF_DKEK + id);
|
||||||
|
if (!tf) {
|
||||||
|
return CCID_ERR_FILE_NOT_FOUND;
|
||||||
|
}
|
||||||
|
memset(tmp_dkek, 0, sizeof(tmp_dkek));
|
||||||
|
if (file_get_size(tf) == DKEK_KEY_SIZE) {
|
||||||
|
memcpy(tmp_dkek, file_get_data(tf), DKEK_KEY_SIZE);
|
||||||
|
}
|
||||||
|
for (int i = 0; i < DKEK_KEY_SIZE; i++) {
|
||||||
|
tmp_dkek[i] ^= share[i];
|
||||||
|
}
|
||||||
|
flash_write_data_to_file(tf, tmp_dkek, DKEK_KEY_SIZE);
|
||||||
|
low_flash_available();
|
||||||
|
return CCID_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
int dkek_kcv(uint8_t id, uint8_t *kcv) { //kcv 8 bytes
|
||||||
|
uint8_t hsh[32], dkek[DKEK_KEY_SIZE];
|
||||||
|
memset(kcv, 0, 8);
|
||||||
|
memset(hsh, 0, sizeof(hsh));
|
||||||
|
int r = load_dkek(id, dkek);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
hash256(dkek, DKEK_KEY_SIZE, hsh);
|
||||||
|
mbedtls_platform_zeroize(dkek, sizeof(dkek));
|
||||||
|
memcpy(kcv, hsh, 8);
|
||||||
|
return CCID_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
int dkek_kenc(uint8_t id, uint8_t *kenc) { //kenc 32 bytes
|
||||||
|
uint8_t dkek[DKEK_KEY_SIZE + 4];
|
||||||
|
memset(kenc, 0, 32);
|
||||||
|
int r = load_dkek(id, dkek);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
memcpy(dkek + DKEK_KEY_SIZE, "\x0\x0\x0\x1", 4);
|
||||||
|
hash256(dkek, sizeof(dkek), kenc);
|
||||||
|
mbedtls_platform_zeroize(dkek, sizeof(dkek));
|
||||||
|
return CCID_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
int dkek_kmac(uint8_t id, uint8_t *kmac) { //kmac 32 bytes
|
||||||
|
uint8_t dkek[DKEK_KEY_SIZE + 4];
|
||||||
|
memset(kmac, 0, 32);
|
||||||
|
int r = load_dkek(id, dkek);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
memcpy(dkek + DKEK_KEY_SIZE, "\x0\x0\x0\x2", 4);
|
||||||
|
hash256(dkek, DKEK_KEY_SIZE + 4, kmac);
|
||||||
|
mbedtls_platform_zeroize(dkek, sizeof(dkek));
|
||||||
|
return CCID_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
int mkek_encrypt(uint8_t *data, size_t len) {
|
||||||
|
int r;
|
||||||
|
uint8_t mkek[MKEK_SIZE + 4];
|
||||||
|
if ((r = load_mkek(mkek)) != CCID_OK) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
r = aes_encrypt_cfb_256(MKEK_KEY(mkek), MKEK_IV(mkek), data, len);
|
||||||
|
release_mkek(mkek);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
int mkek_decrypt(uint8_t *data, size_t len) {
|
||||||
|
int r;
|
||||||
|
uint8_t mkek[MKEK_SIZE + 4];
|
||||||
|
if ((r = load_mkek(mkek)) != CCID_OK) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
r = aes_decrypt_cfb_256(MKEK_KEY(mkek), MKEK_IV(mkek), data, len);
|
||||||
|
release_mkek(mkek);
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
int dkek_encode_key(uint8_t id,
|
||||||
|
void *key_ctx,
|
||||||
|
int key_type,
|
||||||
|
uint8_t *out,
|
||||||
|
size_t *out_len,
|
||||||
|
const uint8_t *allowed,
|
||||||
|
size_t allowed_len) {
|
||||||
|
if (!(key_type & HSM_KEY_RSA) && !(key_type & HSM_KEY_EC) && !(key_type & HSM_KEY_AES)) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t kb[8 + 2 * 4 + 2 * 4096 / 8 + 3 + 13]; //worst case: RSA-4096 (plus, 13 bytes padding)
|
||||||
|
memset(kb, 0, sizeof(kb));
|
||||||
|
int kb_len = 0, r = 0;
|
||||||
|
uint8_t *algo = NULL;
|
||||||
|
uint8_t algo_len = 0;
|
||||||
|
uint8_t kenc[32];
|
||||||
|
memset(kenc, 0, sizeof(kenc));
|
||||||
|
r = dkek_kenc(id, kenc);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t kcv[8];
|
||||||
|
memset(kcv, 0, sizeof(kcv));
|
||||||
|
r = dkek_kcv(id, kcv);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t kmac[32];
|
||||||
|
memset(kmac, 0, sizeof(kmac));
|
||||||
|
r = dkek_kmac(id, kmac);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (key_type & HSM_KEY_AES) {
|
||||||
|
if (key_type & HSM_KEY_AES_128) {
|
||||||
|
kb_len = 16;
|
||||||
|
}
|
||||||
|
else if (key_type & HSM_KEY_AES_192) {
|
||||||
|
kb_len = 24;
|
||||||
|
}
|
||||||
|
else if (key_type & HSM_KEY_AES_256) {
|
||||||
|
kb_len = 32;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (kb_len != 16 && kb_len != 24 && kb_len != 32) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
if (*out_len < 8 + 1 + 10 + 6 + 4 + (2 + 32 + 14) + 16) {
|
||||||
|
return CCID_WRONG_LENGTH;
|
||||||
|
}
|
||||||
|
|
||||||
|
put_uint16_t(kb_len, kb + 8);
|
||||||
|
memcpy(kb + 10, key_ctx, kb_len);
|
||||||
|
kb_len += 2;
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
else if (key_type & HSM_KEY_RSA) {
|
||||||
|
if (*out_len < 8 + 1 + 12 + 6 + (8 + 2 * 4 + 2 * 4096 / 8 + 3 + 13) + 16) { //13 bytes pading
|
||||||
|
return CCID_WRONG_LENGTH;
|
||||||
|
}
|
||||||
|
mbedtls_rsa_context *rsa = (mbedtls_rsa_context *) key_ctx;
|
||||||
|
kb_len = 0;
|
||||||
|
put_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;
|
||||||
|
mbedtls_mpi_write_binary(&rsa->D, kb + 8 + kb_len, mbedtls_mpi_size(&rsa->D));
|
||||||
|
kb_len += mbedtls_mpi_size(&rsa->D);
|
||||||
|
put_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));
|
||||||
|
kb_len += mbedtls_mpi_size(&rsa->N);
|
||||||
|
put_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));
|
||||||
|
kb_len += mbedtls_mpi_size(&rsa->E);
|
||||||
|
|
||||||
|
algo = (uint8_t *) "\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x01\x02";
|
||||||
|
algo_len = 12;
|
||||||
|
}
|
||||||
|
else if (key_type & HSM_KEY_EC) {
|
||||||
|
if (*out_len < 8 + 1 + 12 + 6 + (8 + 2 * 8 + 9 * 66 + 2 + 4) + 16) { //4 bytes pading
|
||||||
|
return CCID_WRONG_LENGTH;
|
||||||
|
}
|
||||||
|
mbedtls_ecdsa_context *ecdsa = (mbedtls_ecdsa_context *) key_ctx;
|
||||||
|
kb_len = 0;
|
||||||
|
put_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;
|
||||||
|
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);
|
||||||
|
put_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));
|
||||||
|
kb_len += mbedtls_mpi_size(&ecdsa->grp.B);
|
||||||
|
put_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));
|
||||||
|
kb_len += mbedtls_mpi_size(&ecdsa->grp.P);
|
||||||
|
put_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));
|
||||||
|
kb_len += 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;
|
||||||
|
kb[8 + kb_len++] = 0x4;
|
||||||
|
mbedtls_mpi_write_binary(&ecdsa->grp.G.X, kb + 8 + kb_len,
|
||||||
|
mbedtls_mpi_size(&ecdsa->grp.G.X));
|
||||||
|
kb_len += mbedtls_mpi_size(&ecdsa->grp.G.X);
|
||||||
|
mbedtls_mpi_write_binary(&ecdsa->grp.G.Y, kb + 8 + kb_len,
|
||||||
|
mbedtls_mpi_size(&ecdsa->grp.G.Y));
|
||||||
|
kb_len += mbedtls_mpi_size(&ecdsa->grp.G.Y);
|
||||||
|
put_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));
|
||||||
|
kb_len += 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);
|
||||||
|
kb_len += 2;
|
||||||
|
kb[8 + kb_len++] = 0x4;
|
||||||
|
mbedtls_mpi_write_binary(&ecdsa->Q.X, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->Q.X));
|
||||||
|
kb_len += mbedtls_mpi_size(&ecdsa->Q.X);
|
||||||
|
mbedtls_mpi_write_binary(&ecdsa->Q.Y, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->Q.Y));
|
||||||
|
kb_len += mbedtls_mpi_size(&ecdsa->Q.Y);
|
||||||
|
|
||||||
|
algo = (uint8_t *) "\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x02\x03";
|
||||||
|
algo_len = 12;
|
||||||
|
}
|
||||||
|
memset(out, 0, *out_len);
|
||||||
|
*out_len = 0;
|
||||||
|
|
||||||
|
memcpy(out + *out_len, kcv, 8);
|
||||||
|
*out_len += 8;
|
||||||
|
|
||||||
|
if (key_type & HSM_KEY_AES) {
|
||||||
|
out[*out_len] = 15;
|
||||||
|
}
|
||||||
|
else if (key_type & HSM_KEY_RSA) {
|
||||||
|
out[*out_len] = 5;
|
||||||
|
}
|
||||||
|
else if (key_type & HSM_KEY_EC) {
|
||||||
|
out[*out_len] = 12;
|
||||||
|
}
|
||||||
|
*out_len += 1;
|
||||||
|
|
||||||
|
if (algo) {
|
||||||
|
memcpy(out + *out_len, algo, algo_len);
|
||||||
|
*out_len += algo_len;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
*out_len += 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (allowed && allowed_len > 0) {
|
||||||
|
put_uint16_t(allowed_len, out + *out_len); *out_len += 2;
|
||||||
|
memcpy(out + *out_len, allowed, allowed_len);
|
||||||
|
*out_len += allowed_len;
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
*out_len += 2;
|
||||||
|
}
|
||||||
|
//add 4 zeros
|
||||||
|
*out_len += 4;
|
||||||
|
|
||||||
|
memcpy(kb, random_bytes_get(8), 8);
|
||||||
|
kb_len += 8; //8 random bytes
|
||||||
|
int kb_len_pad = ((int) (kb_len / 16)) * 16;
|
||||||
|
if (kb_len % 16 > 0) {
|
||||||
|
kb_len_pad = ((int) (kb_len / 16) + 1) * 16;
|
||||||
|
}
|
||||||
|
//key already copied at kb+10
|
||||||
|
if (kb_len < kb_len_pad) {
|
||||||
|
kb[kb_len] = 0x80;
|
||||||
|
}
|
||||||
|
r = aes_encrypt(kenc, NULL, 256, HSM_AES_MODE_CBC, kb, kb_len_pad);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
memcpy(out + *out_len, kb, kb_len_pad);
|
||||||
|
*out_len += kb_len_pad;
|
||||||
|
|
||||||
|
r = mbedtls_cipher_cmac(mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_256_ECB),
|
||||||
|
kmac,
|
||||||
|
256,
|
||||||
|
out,
|
||||||
|
*out_len,
|
||||||
|
out + *out_len);
|
||||||
|
|
||||||
|
*out_len += 16;
|
||||||
|
if (r != 0) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
return CCID_OK;
|
||||||
|
}
|
||||||
|
|
||||||
|
int dkek_type_key(const uint8_t *in) {
|
||||||
|
if (in[8] == 5 || in[8] == 6) {
|
||||||
|
return HSM_KEY_RSA;
|
||||||
|
}
|
||||||
|
else if (in[8] == 12) {
|
||||||
|
return HSM_KEY_EC;
|
||||||
|
}
|
||||||
|
else if (in[8] == 15) {
|
||||||
|
return HSM_KEY_AES;
|
||||||
|
}
|
||||||
|
return 0x0;
|
||||||
|
}
|
||||||
|
|
||||||
|
int dkek_decode_key(uint8_t id,
|
||||||
|
void *key_ctx,
|
||||||
|
const uint8_t *in,
|
||||||
|
size_t in_len,
|
||||||
|
int *key_size_out,
|
||||||
|
uint8_t **allowed,
|
||||||
|
size_t *allowed_len) {
|
||||||
|
uint8_t kcv[8];
|
||||||
|
int r = 0;
|
||||||
|
memset(kcv, 0, sizeof(kcv));
|
||||||
|
r = dkek_kcv(id, kcv);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t kmac[32];
|
||||||
|
memset(kmac, 0, sizeof(kmac));
|
||||||
|
r = dkek_kmac(id, kmac);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t kenc[32];
|
||||||
|
memset(kenc, 0, sizeof(kenc));
|
||||||
|
r = dkek_kenc(id, kenc);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (memcmp(kcv, in, 8) != 0) {
|
||||||
|
return CCID_WRONG_DKEK;
|
||||||
|
}
|
||||||
|
|
||||||
|
uint8_t signature[16];
|
||||||
|
r = mbedtls_cipher_cmac(mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_256_ECB),
|
||||||
|
kmac,
|
||||||
|
256,
|
||||||
|
in,
|
||||||
|
in_len - 16,
|
||||||
|
signature);
|
||||||
|
if (r != 0) {
|
||||||
|
return CCID_WRONG_SIGNATURE;
|
||||||
|
}
|
||||||
|
if (memcmp(signature, in + in_len - 16, 16) != 0) {
|
||||||
|
return CCID_WRONG_SIGNATURE;
|
||||||
|
}
|
||||||
|
|
||||||
|
int key_type = in[8];
|
||||||
|
if (key_type != 5 && key_type != 6 && key_type != 12 && key_type != 15) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
|
||||||
|
if ((key_type == 5 || key_type == 6) &&
|
||||||
|
memcmp(in + 9, "\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x01\x02", 12) != 0) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (key_type == 12 &&
|
||||||
|
memcmp(in + 9, "\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x02\x03", 12) != 0) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (key_type == 15 && memcmp(in + 9, "\x00\x08\x60\x86\x48\x01\x65\x03\x04\x01", 10) != 0) {
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
|
||||||
|
size_t ofs = 9;
|
||||||
|
|
||||||
|
//OID
|
||||||
|
size_t len = get_uint16_t(in, ofs);
|
||||||
|
ofs += len + 2;
|
||||||
|
|
||||||
|
//Allowed algorithms
|
||||||
|
len = get_uint16_t(in, ofs);
|
||||||
|
*allowed = (uint8_t *) (in + ofs + 2);
|
||||||
|
*allowed_len = len;
|
||||||
|
ofs += len + 2;
|
||||||
|
|
||||||
|
//Access conditions
|
||||||
|
len = get_uint16_t(in, ofs);
|
||||||
|
ofs += len + 2;
|
||||||
|
|
||||||
|
//Key OID
|
||||||
|
len = get_uint16_t(in, ofs);
|
||||||
|
ofs += len + 2;
|
||||||
|
|
||||||
|
if ((in_len - 16 - ofs) % 16 != 0) {
|
||||||
|
return CCID_WRONG_PADDING;
|
||||||
|
}
|
||||||
|
uint8_t kb[8 + 2 * 4 + 2 * 4096 / 8 + 3 + 13]; //worst case: RSA-4096 (plus, 13 bytes padding)
|
||||||
|
memset(kb, 0, sizeof(kb));
|
||||||
|
memcpy(kb, in + ofs, in_len - 16 - ofs);
|
||||||
|
r = aes_decrypt(kenc, NULL, 256, HSM_AES_MODE_CBC, kb, in_len - 16 - ofs);
|
||||||
|
if (r != CCID_OK) {
|
||||||
|
return r;
|
||||||
|
}
|
||||||
|
|
||||||
|
int key_size = get_uint16_t(kb, 8);
|
||||||
|
if (key_size_out) {
|
||||||
|
*key_size_out = key_size;
|
||||||
|
}
|
||||||
|
ofs = 10;
|
||||||
|
if (key_type == 5 || key_type == 6) {
|
||||||
|
mbedtls_rsa_context *rsa = (mbedtls_rsa_context *) key_ctx;
|
||||||
|
mbedtls_rsa_init(rsa);
|
||||||
|
if (key_type == 5) {
|
||||||
|
len = get_uint16_t(kb, ofs); ofs += 2;
|
||||||
|
r = mbedtls_mpi_read_binary(&rsa->D, kb + ofs, len); ofs += len;
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_rsa_free(rsa);
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
|
||||||
|
len = get_uint16_t(kb, ofs); ofs += 2;
|
||||||
|
r = mbedtls_mpi_read_binary(&rsa->N, kb + ofs, len); ofs += len;
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_rsa_free(rsa);
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (key_type == 6) {
|
||||||
|
//DP-1
|
||||||
|
len = get_uint16_t(kb, ofs); ofs += len + 2;
|
||||||
|
|
||||||
|
//DQ-1
|
||||||
|
len = get_uint16_t(kb, ofs); ofs += len + 2;
|
||||||
|
|
||||||
|
len = get_uint16_t(kb, ofs); ofs += 2;
|
||||||
|
r = mbedtls_mpi_read_binary(&rsa->P, kb + ofs, len); ofs += len;
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_rsa_free(rsa);
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
|
||||||
|
//PQ
|
||||||
|
len = get_uint16_t(kb, ofs); ofs += len + 2;
|
||||||
|
|
||||||
|
len = get_uint16_t(kb, ofs); ofs += 2;
|
||||||
|
r = mbedtls_mpi_read_binary(&rsa->Q, kb + ofs, len); ofs += len;
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_rsa_free(rsa);
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
//N
|
||||||
|
len = get_uint16_t(kb, ofs); ofs += len + 2;
|
||||||
|
}
|
||||||
|
|
||||||
|
len = get_uint16_t(kb, ofs); ofs += 2;
|
||||||
|
r = mbedtls_mpi_read_binary(&rsa->E, kb + ofs, len); ofs += len;
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_rsa_free(rsa);
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (key_type == 5) {
|
||||||
|
r = mbedtls_rsa_import(rsa, &rsa->N, NULL, NULL, &rsa->D, &rsa->E);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_rsa_free(rsa);
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (key_type == 6) {
|
||||||
|
r = mbedtls_rsa_import(rsa, NULL, &rsa->P, &rsa->Q, NULL, &rsa->E);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_rsa_free(rsa);
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
r = mbedtls_rsa_complete(rsa);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_rsa_free(rsa);
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
r = mbedtls_rsa_check_privkey(rsa);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_rsa_free(rsa);
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (key_type == 12) {
|
||||||
|
mbedtls_ecdsa_context *ecdsa = (mbedtls_ecdsa_context *) key_ctx;
|
||||||
|
mbedtls_ecdsa_init(ecdsa);
|
||||||
|
|
||||||
|
//A
|
||||||
|
len = get_uint16_t(kb, ofs); ofs += len + 2;
|
||||||
|
|
||||||
|
//B
|
||||||
|
len = get_uint16_t(kb, ofs); ofs += len + 2;
|
||||||
|
|
||||||
|
//P
|
||||||
|
len = get_uint16_t(kb, ofs); ofs += 2;
|
||||||
|
mbedtls_ecp_group_id ec_id = ec_get_curve_from_prime(kb + ofs, len);
|
||||||
|
if (ec_id == MBEDTLS_ECP_DP_NONE) {
|
||||||
|
mbedtls_ecdsa_free(ecdsa);
|
||||||
|
return CCID_WRONG_DATA;
|
||||||
|
}
|
||||||
|
ofs += len;
|
||||||
|
|
||||||
|
//N
|
||||||
|
len = get_uint16_t(kb, ofs); ofs += len + 2;
|
||||||
|
|
||||||
|
//G
|
||||||
|
len = get_uint16_t(kb, ofs); ofs += len + 2;
|
||||||
|
|
||||||
|
//d
|
||||||
|
len = get_uint16_t(kb, ofs); ofs += 2;
|
||||||
|
r = mbedtls_ecp_read_key(ec_id, ecdsa, kb + ofs, len);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_ecdsa_free(ecdsa);
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
ofs += len;
|
||||||
|
|
||||||
|
//Q
|
||||||
|
len = get_uint16_t(kb, ofs); ofs += 2;
|
||||||
|
r = mbedtls_ecp_point_read_binary(&ecdsa->grp, &ecdsa->Q, kb + ofs, len);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_ecdsa_free(ecdsa);
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
r = mbedtls_ecp_check_pub_priv(ecdsa, ecdsa, random_gen, NULL);
|
||||||
|
if (r != 0) {
|
||||||
|
mbedtls_ecdsa_free(ecdsa);
|
||||||
|
return CCID_EXEC_ERROR;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
else if (key_type == 15) {
|
||||||
|
memcpy(key_ctx, kb + ofs, key_size);
|
||||||
|
}
|
||||||
|
return CCID_OK;
|
||||||
|
}
|
||||||
77
src/hsm/kek.h
Normal file
77
src/hsm/kek.h
Normal file
@@ -0,0 +1,77 @@
|
|||||||
|
/*
|
||||||
|
* 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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef _DKEK_H_
|
||||||
|
#define _DKEK_H_
|
||||||
|
|
||||||
|
#include "crypto_utils.h"
|
||||||
|
#ifdef ENABLE_EMULATION
|
||||||
|
#include <stdbool.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
extern int load_mkek(uint8_t *);
|
||||||
|
extern int store_mkek(const uint8_t *);
|
||||||
|
extern int save_dkek_key(uint8_t, const uint8_t *key);
|
||||||
|
extern int store_dkek_key(uint8_t, uint8_t *);
|
||||||
|
extern void init_mkek();
|
||||||
|
extern void release_mkek(uint8_t *);
|
||||||
|
extern int import_dkek_share(uint8_t, const uint8_t *share);
|
||||||
|
extern int dkek_kcv(uint8_t, uint8_t *kcv);
|
||||||
|
extern int mkek_encrypt(uint8_t *data, size_t len);
|
||||||
|
extern int mkek_decrypt(uint8_t *data, size_t len);
|
||||||
|
extern int dkek_encode_key(uint8_t,
|
||||||
|
void *key_ctx,
|
||||||
|
int key_type,
|
||||||
|
uint8_t *out,
|
||||||
|
size_t *out_len,
|
||||||
|
const uint8_t *,
|
||||||
|
size_t);
|
||||||
|
extern int dkek_type_key(const uint8_t *in);
|
||||||
|
extern int dkek_decode_key(uint8_t,
|
||||||
|
void *key_ctx,
|
||||||
|
const uint8_t *in,
|
||||||
|
size_t in_len,
|
||||||
|
int *key_size_out,
|
||||||
|
uint8_t **,
|
||||||
|
size_t *);
|
||||||
|
|
||||||
|
#define MAX_DKEK_ENCODE_KEY_BUFFER (8 + 1 + 12 + 6 + (8 + 2 * 4 + 2 * 4096 / 8 + 3 + 13) + 16)
|
||||||
|
|
||||||
|
#define MAX_KEY_DOMAINS 16
|
||||||
|
|
||||||
|
#define MKEK_IV_SIZE (IV_SIZE)
|
||||||
|
#define MKEK_KEY_SIZE (32)
|
||||||
|
#define MKEK_KEY_CS_SIZE (4)
|
||||||
|
#define MKEK_SIZE (MKEK_IV_SIZE + MKEK_KEY_SIZE + MKEK_KEY_CS_SIZE)
|
||||||
|
#define MKEK_IV(p) (p)
|
||||||
|
#define MKEK_KEY(p) (MKEK_IV(p) + MKEK_IV_SIZE)
|
||||||
|
#define MKEK_CHECKSUM(p) (MKEK_KEY(p) + MKEK_KEY_SIZE)
|
||||||
|
#define DKEK_KEY_SIZE (32)
|
||||||
|
|
||||||
|
extern uint8_t mkek_mask[MKEK_KEY_SIZE];
|
||||||
|
extern bool has_mkek_mask;
|
||||||
|
|
||||||
|
typedef struct mse {
|
||||||
|
uint8_t Qpt[65];
|
||||||
|
uint8_t key_enc[12 + 32];
|
||||||
|
bool init;
|
||||||
|
} mse_t;
|
||||||
|
extern mse_t mse;
|
||||||
|
|
||||||
|
extern int mse_decrypt_ct(uint8_t *, size_t);
|
||||||
|
|
||||||
|
#endif
|
||||||
18
src/hsm/oid.c
Normal file
18
src/hsm/oid.c
Normal file
@@ -0,0 +1,18 @@
|
|||||||
|
/*
|
||||||
|
* 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 "oid.h"
|
||||||
147
src/hsm/oid.h
Normal file
147
src/hsm/oid.h
Normal file
@@ -0,0 +1,147 @@
|
|||||||
|
/*
|
||||||
|
* 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/>.
|
||||||
|
*/
|
||||||
|
|
||||||
|
#ifndef _OID_H_
|
||||||
|
#define _OID_H_
|
||||||
|
|
||||||
|
#define OID_BSI_DE "\x04\x00\x7F\x00\x07"
|
||||||
|
|
||||||
|
#define OID_ECKA OID_BSI_DE "\x01\x01\x05"
|
||||||
|
#define OID_ECKA_EG OID_ECKA "\x01"
|
||||||
|
#define OID_ECKA_EG_X963KDF OID_ECKA_EG "\x01"
|
||||||
|
#define OID_ECKA_EG_X963KDF_SHA1 OID_ECKA_EG_X963KDF "\x01"
|
||||||
|
#define OID_ECKA_EG_X963KDF_SHA224 OID_ECKA_EG_X963KDF "\x02"
|
||||||
|
#define OID_ECKA_EG_X963KDF_SHA256 OID_ECKA_EG_X963KDF "\x03"
|
||||||
|
#define OID_ECKA_EG_X963KDF_SHA384 OID_ECKA_EG_X963KDF "\x04"
|
||||||
|
#define OID_ECKA_EG_X963KDF_SHA512 OID_ECKA_EG_X963KDF "\x05"
|
||||||
|
#define OID_ECKA_DH OID_ECKA "\x02"
|
||||||
|
#define OID_ECKA_DH_X963KDF OID_ECKA_DH "\x01"
|
||||||
|
#define OID_ECKA_DH_X963KDF_SHA1 OID_ECKA_DH_X963KDF "\x01"
|
||||||
|
#define OID_ECKA_DH_X963KDF_SHA224 OID_ECKA_DH_X963KDF "\x02"
|
||||||
|
#define OID_ECKA_DH_X963KDF_SHA256 OID_ECKA_DH_X963KDF "\x03"
|
||||||
|
#define OID_ECKA_DH_X963KDF_SHA384 OID_ECKA_DH_X963KDF "\x04"
|
||||||
|
#define OID_ECKA_DH_X963KDF_SHA512 OID_ECKA_DH_X963KDF "\x05"
|
||||||
|
|
||||||
|
#define OID_ID_PK OID_BSI_DE "\x02\x02\x01"
|
||||||
|
#define OID_ID_PK_DH OID_ID_PK "\x01"
|
||||||
|
#define OID_ID_PK_ECDH OID_ID_PK "\x02"
|
||||||
|
|
||||||
|
#define OID_ID_TA OID_BSI_DE "\x02\x02\x02"
|
||||||
|
|
||||||
|
#define OID_ID_TA_RSA OID_ID_TA "\x01"
|
||||||
|
|
||||||
|
#define OID_ID_TA_RSA_V1_5_SHA_1 OID_ID_TA_RSA "\x01"
|
||||||
|
#define OID_ID_TA_RSA_V1_5_SHA_256 OID_ID_TA_RSA "\x02"
|
||||||
|
#define OID_ID_TA_RSA_PSS_SHA_1 OID_ID_TA_RSA "\x03"
|
||||||
|
#define OID_ID_TA_RSA_PSS_SHA_256 OID_ID_TA_RSA "\x04"
|
||||||
|
#define OID_ID_TA_RSA_V1_5_SHA_512 OID_ID_TA_RSA "\x05"
|
||||||
|
#define OID_ID_TA_RSA_PSS_SHA_512 OID_ID_TA_RSA "\x06"
|
||||||
|
|
||||||
|
#define OID_ID_TA_ECDSA OID_ID_TA "\x02"
|
||||||
|
|
||||||
|
#define OID_ID_TA_ECDSA_SHA_1 OID_ID_TA_ECDSA "\x01"
|
||||||
|
#define OID_ID_TA_ECDSA_SHA_224 OID_ID_TA_ECDSA "\x02"
|
||||||
|
#define OID_ID_TA_ECDSA_SHA_256 OID_ID_TA_ECDSA "\x03"
|
||||||
|
#define OID_ID_TA_ECDSA_SHA_384 OID_ID_TA_ECDSA "\x04"
|
||||||
|
#define OID_ID_TA_ECDSA_SHA_512 OID_ID_TA_ECDSA "\x05"
|
||||||
|
|
||||||
|
#define OID_ID_CA OID_BSI_DE "\x02\x02\x03"
|
||||||
|
|
||||||
|
#define OID_ID_CA_DH OID_ID_CA "\x01"
|
||||||
|
#define OID_ID_CA_DH_3DES_CBC_CBC OID_ID_CA_DH "\x01"
|
||||||
|
#define OID_ID_CA_DH_AES_CBC_CMAC_128 OID_ID_CA_DH "\x02"
|
||||||
|
#define OID_ID_CA_DH_AES_CBC_CMAC_192 OID_ID_CA_DH "\x03"
|
||||||
|
#define OID_ID_CA_DH_AES_CBC_CMAC_256 OID_ID_CA_DH "\x04"
|
||||||
|
|
||||||
|
#define OID_ID_CA_ECDH OID_ID_CA "\x02"
|
||||||
|
#define OID_ID_CA_ECDH_3DES_CBC_CBC OID_ID_CA_ECDH "\x01"
|
||||||
|
#define OID_ID_CA_ECDH_AES_CBC_CMAC_128 OID_ID_CA_ECDH "\x02"
|
||||||
|
#define OID_ID_CA_ECDH_AES_CBC_CMAC_192 OID_ID_CA_ECDH "\x03"
|
||||||
|
#define OID_ID_CA_ECDH_AES_CBC_CMAC_256 OID_ID_CA_ECDH "\x04"
|
||||||
|
|
||||||
|
#define OID_ID_RI OID_BSI_DE "\x02\x02\x05"
|
||||||
|
|
||||||
|
#define OID_ID_RI_DH OID_ID_RI "\x01"
|
||||||
|
|
||||||
|
#define OID_ID_RI_DH_SHA_1 OID_ID_RI_DH "\x01"
|
||||||
|
#define OID_ID_RI_DH_SHA_224 OID_ID_RI_DH "\x02"
|
||||||
|
#define OID_ID_RI_DH_SHA_256 OID_ID_RI_DH "\x03"
|
||||||
|
|
||||||
|
#define OID_ID_RI_ECDH OID_ID_RI "\x02"
|
||||||
|
|
||||||
|
#define OID_ID_RI_ECDH_SHA_1 OID_ID_RI_ECDH "\x01"
|
||||||
|
#define OID_ID_RI_ECDH_SHA_224 OID_ID_RI_ECDH "\x02"
|
||||||
|
#define OID_ID_RI_ECDH_SHA_256 OID_ID_RI_ECDH "\x03"
|
||||||
|
|
||||||
|
#define OID_ID_CI OID_BSI_DE "\x02\x02\x06"
|
||||||
|
|
||||||
|
#define OID_CARDCONTACT "\x2B\x06\x01\x04\x01\x81\xC3\x1F"
|
||||||
|
|
||||||
|
#define OID_OPENSCDP OID_CARDCONTACT "\x01"
|
||||||
|
#define OID_CC_ISO7816 OID_CARDCONTACT "\x02"
|
||||||
|
#define OID_CC_PKI OID_CARDCONTACT "\x03"
|
||||||
|
#define OID_CC_FORMAT OID_CARDCONTACT "\x04"
|
||||||
|
#define OID_CC_GP_PROFILES OID_CARDCONTACT "\x10"
|
||||||
|
|
||||||
|
#define OID_SCSH3 OID_OPENSCDP "\x01"
|
||||||
|
#define OID_SCSH3GUI OID_OPENSCDP "\x02"
|
||||||
|
|
||||||
|
#define OID_SMARCARD_HSM OID_CC_ISO7816 "\x01"
|
||||||
|
#define OID_CC_APDUTEST OID_CC_ISO7816 "\x02"
|
||||||
|
#define OID_CC_PACKAGES OID_CC_ISO7816 "\x7F"
|
||||||
|
|
||||||
|
#define OID_CC_ROLES OID_CC_PKI "\x01"
|
||||||
|
#define OID_CC_ROLE_SC_HSM OID_CC_ROLES "\x01"
|
||||||
|
|
||||||
|
#define OID_CC_EXTENSIONS OID_CC_PKI "\x02"
|
||||||
|
#define OID_ID_IMPU OID_CC_EXTENSIONS "\x01"
|
||||||
|
#define OID_ID_KEY_DOMAIN_UID OID_CC_EXTENSIONS "\x02"
|
||||||
|
|
||||||
|
#define OID_CC_FF_DEVICEID OID_CC_FORMAT "\x01"
|
||||||
|
#define OID_CC_FF_KDM OID_CC_FORMAT "\x02"
|
||||||
|
#define OID_CC_FF_PKA OID_CC_FORMAT "\x03"
|
||||||
|
#define OID_CC_FF_KDA OID_CC_FORMAT "\x04"
|
||||||
|
|
||||||
|
#define OID_RSADSI "\x2A\x86\x48\x86\xF7\x0D"
|
||||||
|
|
||||||
|
#define OID_PKCS OID_RSADSI "\x01"
|
||||||
|
|
||||||
|
#define OID_PKCS_5 OID_PKCS "\x05"
|
||||||
|
#define OID_PKCS5_PBKDF2 OID_PKCS_5 "\x0C"
|
||||||
|
#define OID_PKCS5_PBES2 OID_PKCS_5 "\x0D"
|
||||||
|
|
||||||
|
#define OID_PKCS_9 OID_PKCS "\x09"
|
||||||
|
|
||||||
|
#define OID_PKCS9_SMIME_ALG OID_PKCS_9 "\x10\x03"
|
||||||
|
|
||||||
|
#define OID_CHACHA20_POLY1305 OID_PKCS9_SMIME_ALG "\x12"
|
||||||
|
#define OID_HKDF_SHA256 OID_PKCS9_SMIME_ALG "\x1D"
|
||||||
|
#define OID_HKDF_SHA384 OID_PKCS9_SMIME_ALG "\x1E"
|
||||||
|
#define OID_HKDF_SHA512 OID_PKCS9_SMIME_ALG "\x1F"
|
||||||
|
|
||||||
|
|
||||||
|
#define OID_DIGEST OID_RSADSI "\x02"
|
||||||
|
|
||||||
|
#define OID_HMAC_SHA1 OID_DIGEST "\x07"
|
||||||
|
#define OID_HMAC_SHA224 OID_DIGEST "\x08"
|
||||||
|
#define OID_HMAC_SHA256 OID_DIGEST "\x09"
|
||||||
|
#define OID_HMAC_SHA384 OID_DIGEST "\x0A"
|
||||||
|
#define OID_HMAC_SHA512 OID_DIGEST "\x0B"
|
||||||
|
|
||||||
|
#define OID_KDF_X963 "\x2B\x81\x05\x10\x86\x48\x3F"
|
||||||
|
|
||||||
|
#endif
|
||||||
1943
src/hsm/sc_hsm.c
1943
src/hsm/sc_hsm.c
File diff suppressed because it is too large
Load Diff
100
src/hsm/sc_hsm.h
100
src/hsm/sc_hsm.h
@@ -19,34 +19,58 @@
|
|||||||
#define _SC_HSM_H_
|
#define _SC_HSM_H_
|
||||||
|
|
||||||
#include <stdlib.h>
|
#include <stdlib.h>
|
||||||
|
#include "common.h"
|
||||||
|
#include "mbedtls/rsa.h"
|
||||||
|
#include "mbedtls/ecdsa.h"
|
||||||
|
#ifndef ENABLE_EMULATION
|
||||||
#include "pico/stdlib.h"
|
#include "pico/stdlib.h"
|
||||||
#include "ccid2040.h"
|
#endif
|
||||||
|
#include "file.h"
|
||||||
|
#include "apdu.h"
|
||||||
|
#include "hsm.h"
|
||||||
|
|
||||||
extern const uint8_t sc_hsm_aid[];
|
extern const uint8_t sc_hsm_aid[];
|
||||||
|
|
||||||
|
#define ALGO_RSA_RAW 0x20 /* RSA signature with external padding */
|
||||||
|
#define ALGO_RSA_DECRYPT 0x21 /* RSA raw decrypt */
|
||||||
|
#define ALGO_RSA_DECRYPT_PKCS1 0x22
|
||||||
|
#define ALGO_RSA_DECRYPT_OEP 0x23
|
||||||
|
#define ALGO_RSA_PKCS1 0x30 /* RSA signature with DigestInfo input and PKCS#1 V1.5 padding */
|
||||||
|
#define ALGO_RSA_PKCS1_SHA1 0x31 /* RSA signature with SHA-1 hash and PKCS#1 V1.5 padding */
|
||||||
|
#define ALGO_RSA_PKCS1_SHA224 0x32
|
||||||
|
#define ALGO_RSA_PKCS1_SHA256 0x33 /* RSA signature with SHA-256 hash and PKCS#1 V1.5 padding */
|
||||||
|
#define ALGO_RSA_PKCS1_SHA384 0x34
|
||||||
|
#define ALGO_RSA_PKCS1_SHA512 0x35
|
||||||
|
|
||||||
#define ALGO_RSA_RAW 0x20 /* RSA signature with external padding */
|
#define ALGO_RSA_PSS 0x40 /* RSA signature with external hash and PKCS#1 PSS padding*/
|
||||||
#define ALGO_RSA_DECRYPT 0x21 /* RSA decrypt */
|
#define ALGO_RSA_PSS_SHA1 0x41 /* RSA signature with SHA-1 hash and PKCS#1 PSS padding */
|
||||||
#define ALGO_RSA_PKCS1 0x30 /* RSA signature with DigestInfo input and PKCS#1 V1.5 padding */
|
#define ALGO_RSA_PSS_SHA224 0x42
|
||||||
#define ALGO_RSA_PKCS1_SHA1 0x31 /* RSA signature with SHA-1 hash and PKCS#1 V1.5 padding */
|
#define ALGO_RSA_PSS_SHA256 0x43 /* RSA signature with SHA-256 hash and PKCS#1 PSS padding */
|
||||||
#define ALGO_RSA_PKCS1_SHA256 0x33 /* RSA signature with SHA-256 hash and PKCS#1 V1.5 padding */
|
#define ALGO_RSA_PSS_SHA384 0x44
|
||||||
|
#define ALGO_RSA_PSS_SHA512 0x45
|
||||||
|
|
||||||
#define ALGO_RSA_PSS 0x40 /* RSA signature with external hash and PKCS#1 PSS padding*/
|
#define ALGO_EC_RAW 0x70 /* ECDSA signature with hash input */
|
||||||
#define ALGO_RSA_PSS_SHA1 0x41 /* RSA signature with SHA-1 hash and PKCS#1 PSS padding */
|
#define ALGO_EC_SHA1 0x71 /* ECDSA signature with SHA-1 hash */
|
||||||
#define ALGO_RSA_PSS_SHA256 0x43 /* RSA signature with SHA-256 hash and PKCS#1 PSS padding */
|
#define ALGO_EC_SHA224 0x72 /* ECDSA signature with SHA-224 hash */
|
||||||
|
#define ALGO_EC_SHA256 0x73 /* ECDSA signature with SHA-256 hash */
|
||||||
|
#define ALGO_EC_SHA384 0x74
|
||||||
|
#define ALGO_EC_SHA512 0x75
|
||||||
|
#define ALGO_EC_DH 0x80 /* ECDH key derivation */
|
||||||
|
#define ALGO_EC_DH_AUTPUK 0x83
|
||||||
|
#define ALGO_EC_DH_XKEK 0x84
|
||||||
|
|
||||||
#define ALGO_EC_RAW 0x70 /* ECDSA signature with hash input */
|
#define ALGO_WRAP 0x92
|
||||||
#define ALGO_EC_SHA1 0x71 /* ECDSA signature with SHA-1 hash */
|
#define ALGO_UNWRAP 0x93
|
||||||
#define ALGO_EC_SHA224 0x72 /* ECDSA signature with SHA-224 hash */
|
#define ALGO_REPLACE 0x94
|
||||||
#define ALGO_EC_SHA256 0x73 /* ECDSA signature with SHA-256 hash */
|
|
||||||
#define ALGO_EC_DH 0x80 /* ECDH key derivation */
|
|
||||||
|
|
||||||
#define ALGO_EC_DERIVE 0x98 /* Derive EC key from EC key */
|
#define ALGO_EC_DERIVE 0x98 /* Derive EC key from EC key */
|
||||||
|
|
||||||
#define ALGO_AES_CBC_ENCRYPT 0x10
|
#define ALGO_AES_CBC_ENCRYPT 0x10
|
||||||
#define ALGO_AES_CBC_DECRYPT 0x11
|
#define ALGO_AES_CBC_DECRYPT 0x11
|
||||||
#define ALGO_AES_CMAC 0x18
|
#define ALGO_AES_CMAC 0x18
|
||||||
#define ALGO_AES_DERIVE 0x99
|
#define ALGO_EXT_CIPHER_ENCRYPT 0x51 /* Extended ciphering Encrypt */
|
||||||
|
#define ALGO_EXT_CIPHER_DECRYPT 0x52 /* Extended ciphering Decrypt */
|
||||||
|
#define ALGO_AES_DERIVE 0x99
|
||||||
|
|
||||||
#define HSM_OPT_RRC 0x0001
|
#define HSM_OPT_RRC 0x0001
|
||||||
#define HSM_OPT_TRANSPORT_PIN 0x0002
|
#define HSM_OPT_TRANSPORT_PIN 0x0002
|
||||||
@@ -57,27 +81,47 @@ extern const uint8_t sc_hsm_aid[];
|
|||||||
#define HSM_OPT_RRC_RESET_ONLY 0x0020
|
#define HSM_OPT_RRC_RESET_ONLY 0x0020
|
||||||
#define HSM_OPT_BOOTSEL_BUTTON 0x0100
|
#define HSM_OPT_BOOTSEL_BUTTON 0x0100
|
||||||
#define HSM_OPT_KEY_COUNTER_ALL 0x0200
|
#define HSM_OPT_KEY_COUNTER_ALL 0x0200
|
||||||
|
#define HSM_OPT_SECURE_LOCK 0x0400
|
||||||
|
|
||||||
#define PRKD_PREFIX 0xC4 /* Hi byte in file identifier for PKCS#15 PRKD objects */
|
#define PRKD_PREFIX 0xC4 /* Hi byte in file identifier for PKCS#15 PRKD objects */
|
||||||
#define CD_PREFIX 0xC8 /* Hi byte in file identifier for PKCS#15 CD objects */
|
#define CD_PREFIX 0xC8 /* Hi byte in file identifier for PKCS#15 CD objects */
|
||||||
#define DCOD_PREFIX 0xC9 /* Hi byte in file identifier for PKCS#15 DCOD objects */
|
#define DCOD_PREFIX 0xC9 /* Hi byte in file identifier for PKCS#15 DCOD objects */
|
||||||
#define CA_CERTIFICATE_PREFIX 0xCA /* Hi byte in file identifier for CA certificates */
|
#define CA_CERTIFICATE_PREFIX 0xCA /* Hi byte in file identifier for CA certificates */
|
||||||
#define KEY_PREFIX 0xCC /* Hi byte in file identifier for key objects */
|
#define KEY_PREFIX 0xCC /* Hi byte in file identifier for key objects */
|
||||||
#define PROT_DATA_PREFIX 0xCD /* Hi byte in file identifier for PIN protected data objects */
|
#define PROT_DATA_PREFIX 0xCD /* Hi byte in file identifier for PIN protected data objects */
|
||||||
#define EE_CERTIFICATE_PREFIX 0xCE /* Hi byte in file identifier for EE certificates */
|
#define EE_CERTIFICATE_PREFIX 0xCE /* Hi byte in file identifier for EE certificates */
|
||||||
#define DATA_PREFIX 0xCF /* Hi byte in file identifier for readable data objects */
|
#define DATA_PREFIX 0xCF /* Hi byte in file identifier for readable data objects */
|
||||||
|
|
||||||
#define P15_KEYTYPE_RSA 0x30
|
#define P15_KEYTYPE_RSA 0x30
|
||||||
#define P15_KEYTYPE_ECC 0xA0
|
#define P15_KEYTYPE_ECC 0xA0
|
||||||
#define P15_KEYTYPE_AES 0xA8
|
#define P15_KEYTYPE_AES 0xA8
|
||||||
|
|
||||||
|
#define MAX_PUK 8
|
||||||
|
|
||||||
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, size_t len, uint8_t output[32]);
|
||||||
extern void hash_multi(const uint8_t *input, size_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 void double_hash_pin(const uint8_t *pin, size_t len, uint8_t output[32]);
|
||||||
|
extern uint16_t get_device_options();
|
||||||
|
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 bool pka_enabled();
|
||||||
|
extern const uint8_t *dev_name;
|
||||||
|
extern size_t dev_name_len;
|
||||||
|
extern uint8_t puk_status[MAX_PUK];
|
||||||
|
extern int puk_store_select_chr(const uint8_t *chr);
|
||||||
|
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 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_ecdsa(mbedtls_ecdsa_context *ctx, file_t *fkey);
|
||||||
|
extern bool wait_button_pressed();
|
||||||
|
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 uint32_t get_key_counter(file_t *fkey);
|
||||||
|
extern uint32_t decrement_key_counter(file_t *fkey);
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
@@ -18,10 +18,9 @@
|
|||||||
#ifndef __VERSION_H_
|
#ifndef __VERSION_H_
|
||||||
#define __VERSION_H_
|
#define __VERSION_H_
|
||||||
|
|
||||||
#define HSM_VERSION 0x0202
|
#define HSM_VERSION 0x0304
|
||||||
|
|
||||||
#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)
|
||||||
|
|
||||||
#endif
|
#endif
|
||||||
|
|
||||||
|
|||||||
7
tests/build-in-docker.sh
Executable file
7
tests/build-in-docker.sh
Executable file
@@ -0,0 +1,7 @@
|
|||||||
|
#!/bin/bash -eu
|
||||||
|
|
||||||
|
source tests/docker_env.sh
|
||||||
|
#run_in_docker rm -rf CMakeFiles
|
||||||
|
run_in_docker mkdir -p build_in_docker
|
||||||
|
run_in_docker -w "$PWD/build_in_docker" cmake -DENABLE_EMULATION=1 ..
|
||||||
|
run_in_docker -w "$PWD/build_in_docker" make -j ${NUM_PROC}
|
||||||
509
tests/conftest.py
Normal file
509
tests/conftest.py
Normal file
@@ -0,0 +1,509 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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 sys
|
||||||
|
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:
|
||||||
|
from cvc.asn1 import ASN1
|
||||||
|
from cvc import oid
|
||||||
|
from cvc.certificates import CVC
|
||||||
|
from cvc.ec_curves import ec_domain, find_curve
|
||||||
|
except ModuleNotFoundError:
|
||||||
|
print('ERROR: cvc module not found! Install pycvc package.\nTry with `pip install pycvc`')
|
||||||
|
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")
|
||||||
|
def device():
|
||||||
|
dev = Device()
|
||||||
|
return dev
|
||||||
26
tests/const.py
Normal file
26
tests/const.py
Normal file
@@ -0,0 +1,26 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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/>.
|
||||||
|
*/
|
||||||
|
"""
|
||||||
|
|
||||||
|
DEFAULT_PIN = '648219'
|
||||||
|
DEFAULT_SOPIN = '57621880'
|
||||||
|
DEFAULT_RETRIES = 3
|
||||||
|
DEFAULT_DKEK = [0x1] * 32
|
||||||
|
DEFAULT_DKEK_SHARES = 2
|
||||||
|
|
||||||
|
EF_TERMCA = 0x2f02
|
||||||
30
tests/docker/jammy/Dockerfile
Normal file
30
tests/docker/jammy/Dockerfile
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
FROM ubuntu:jammy
|
||||||
|
|
||||||
|
ARG DEBIAN_FRONTEND=noninteractive
|
||||||
|
|
||||||
|
RUN apt update && apt upgrade -y
|
||||||
|
RUN apt install -y apt-utils
|
||||||
|
RUN apt install -y libccid \
|
||||||
|
libpcsclite-dev \
|
||||||
|
git \
|
||||||
|
autoconf \
|
||||||
|
pkg-config \
|
||||||
|
libtool \
|
||||||
|
help2man \
|
||||||
|
automake \
|
||||||
|
gcc \
|
||||||
|
make \
|
||||||
|
build-essential \
|
||||||
|
opensc \
|
||||||
|
python3 \
|
||||||
|
python3-pip \
|
||||||
|
swig \
|
||||||
|
cmake \
|
||||||
|
&& rm -rf /var/lib/apt/lists/*
|
||||||
|
RUN pip3 install pytest pycvc cryptography pyscard
|
||||||
|
RUN git clone https://github.com/frankmorgner/vsmartcard.git
|
||||||
|
WORKDIR /vsmartcard/virtualsmartcard
|
||||||
|
RUN autoreconf --verbose --install
|
||||||
|
RUN ./configure --sysconfdir=/etc
|
||||||
|
RUN make && make install
|
||||||
|
WORKDIR /
|
||||||
106
tests/docker_env.sh
Normal file
106
tests/docker_env.sh
Normal file
@@ -0,0 +1,106 @@
|
|||||||
|
#!/bin/bash -eu
|
||||||
|
|
||||||
|
# Taken from Mbed-TLS project
|
||||||
|
# https://github.com/Mbed-TLS/mbedtls/blob/master/tests/scripts/docker_env.sh
|
||||||
|
#
|
||||||
|
# docker_env.sh
|
||||||
|
#
|
||||||
|
# Purpose
|
||||||
|
# -------
|
||||||
|
#
|
||||||
|
# This is a helper script to enable running tests under a Docker container,
|
||||||
|
# thus making it easier to get set up as well as isolating test dependencies
|
||||||
|
# (which include legacy/insecure configurations of openssl and gnutls).
|
||||||
|
#
|
||||||
|
# WARNING: the Dockerfile used by this script is no longer maintained! See
|
||||||
|
# https://github.com/Mbed-TLS/mbedtls-test/blob/master/README.md#quick-start
|
||||||
|
# for the set of Docker images we use on the CI.
|
||||||
|
#
|
||||||
|
# Notes for users
|
||||||
|
# ---------------
|
||||||
|
# This script expects a Linux x86_64 system with a recent version of Docker
|
||||||
|
# installed and available for use, as well as http/https access. If a proxy
|
||||||
|
# server must be used, invoke this script with the usual environment variables
|
||||||
|
# (http_proxy and https_proxy) set appropriately. If an alternate Docker
|
||||||
|
# registry is needed, specify MBEDTLS_DOCKER_REGISTRY to point at the
|
||||||
|
# host name.
|
||||||
|
#
|
||||||
|
#
|
||||||
|
# Running this script directly will check for Docker availability and set up
|
||||||
|
# the Docker image.
|
||||||
|
|
||||||
|
# Copyright The Mbed TLS Contributors
|
||||||
|
# SPDX-License-Identifier: Apache-2.0
|
||||||
|
#
|
||||||
|
# Licensed under the Apache License, Version 2.0 (the "License"); you may
|
||||||
|
# not use this file except in compliance with the License.
|
||||||
|
# You may obtain a copy of the License at
|
||||||
|
#
|
||||||
|
# http://www.apache.org/licenses/LICENSE-2.0
|
||||||
|
#
|
||||||
|
# Unless required by applicable law or agreed to in writing, software
|
||||||
|
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
|
||||||
|
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||||
|
# See the License for the specific language governing permissions and
|
||||||
|
# limitations under the License.
|
||||||
|
|
||||||
|
|
||||||
|
# default values, can be overridden by the environment
|
||||||
|
: ${MBEDTLS_DOCKER_GUEST:=jammy}
|
||||||
|
|
||||||
|
|
||||||
|
DOCKER_IMAGE_TAG="pico-hsm-test:${MBEDTLS_DOCKER_GUEST}"
|
||||||
|
|
||||||
|
# Make sure docker is available
|
||||||
|
if ! which docker > /dev/null; then
|
||||||
|
echo "Docker is required but doesn't seem to be installed. See https://www.docker.com/ to get started"
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Figure out if we need to 'sudo docker'
|
||||||
|
if groups | grep docker > /dev/null; then
|
||||||
|
DOCKER="docker"
|
||||||
|
else
|
||||||
|
echo "Using sudo to invoke docker since you're not a member of the docker group..."
|
||||||
|
DOCKER="docker"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Figure out the number of processors available
|
||||||
|
if [ "$(uname)" == "Darwin" ]; then
|
||||||
|
NUM_PROC="$(sysctl -n hw.logicalcpu)"
|
||||||
|
else
|
||||||
|
NUM_PROC="$(nproc)"
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Build the Docker image
|
||||||
|
echo "Getting docker image up to date (this may take a few minutes)..."
|
||||||
|
${DOCKER} image build \
|
||||||
|
-t ${DOCKER_IMAGE_TAG} \
|
||||||
|
--cache-from=${DOCKER_IMAGE_TAG} \
|
||||||
|
--network host \
|
||||||
|
--build-arg MAKEFLAGS_PARALLEL="-j ${NUM_PROC}" \
|
||||||
|
tests/docker/${MBEDTLS_DOCKER_GUEST}
|
||||||
|
|
||||||
|
run_in_docker()
|
||||||
|
{
|
||||||
|
ENV_ARGS=""
|
||||||
|
while [ "$1" == "-e" ]; do
|
||||||
|
ENV_ARGS="${ENV_ARGS} $1 $2"
|
||||||
|
shift 2
|
||||||
|
done
|
||||||
|
|
||||||
|
WORKDIR="${PWD}"
|
||||||
|
if [ "$1" == '-w' ]; then
|
||||||
|
WORKDIR="$2"
|
||||||
|
shift 2
|
||||||
|
fi
|
||||||
|
|
||||||
|
${DOCKER} container run --rm \
|
||||||
|
--cap-add SYS_PTRACE \
|
||||||
|
--volume $PWD:$PWD \
|
||||||
|
--workdir ${WORKDIR} \
|
||||||
|
-e MAKEFLAGS \
|
||||||
|
${ENV_ARGS} \
|
||||||
|
${DOCKER_IMAGE_TAG} \
|
||||||
|
$@
|
||||||
|
}
|
||||||
BIN
tests/memory.tar.gz
Normal file
BIN
tests/memory.tar.gz
Normal file
Binary file not shown.
35
tests/pico-hsm/test_000_info.py
Normal file
35
tests/pico-hsm/test_000_info.py
Normal file
@@ -0,0 +1,35 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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
|
||||||
|
from const import EF_TERMCA
|
||||||
|
|
||||||
|
def test_select(device):
|
||||||
|
device.select_applet()
|
||||||
|
|
||||||
|
def test_termca(device):
|
||||||
|
data = device.get_termca()
|
||||||
|
assert(b'ESPICOHSMTR' == data['cv']['chr'][:11])
|
||||||
|
assert(b'ESPICOHSMDV' == data['cv']['car'][:11])
|
||||||
|
assert(b'ESPICOHSMDV' == data['dv']['chr'][:11])
|
||||||
|
assert(b'ESPICOHSMCA' == data['dv']['car'][:11])
|
||||||
|
assert(data['cv']['car'] == data['dv']['chr'])
|
||||||
|
|
||||||
|
def test_get_version(device):
|
||||||
|
version = device.get_version()
|
||||||
57
tests/pico-hsm/test_003_challenge.py
Normal file
57
tests/pico-hsm/test_003_challenge.py
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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 math
|
||||||
|
from collections import Counter
|
||||||
|
|
||||||
|
def mean(x):
|
||||||
|
sum = 0
|
||||||
|
for i in x:
|
||||||
|
sum += i
|
||||||
|
return sum/len(x)
|
||||||
|
|
||||||
|
def var(x):
|
||||||
|
sum = 0
|
||||||
|
m = mean(x)
|
||||||
|
for i in x:
|
||||||
|
sum += (i-m)**2
|
||||||
|
return sum/len(x)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"length", [1, 256, 1024]
|
||||||
|
)
|
||||||
|
def test_challenge(device, length):
|
||||||
|
data = device.get_challenge(length)
|
||||||
|
assert(len(data) == length)
|
||||||
|
|
||||||
|
def test_randomness(device):
|
||||||
|
data = []
|
||||||
|
N = 1000
|
||||||
|
for k2 in range(N):
|
||||||
|
data += device.get_challenge(1024)
|
||||||
|
|
||||||
|
_, values = zip(*Counter(data).items())
|
||||||
|
|
||||||
|
nm = mean(values)/(N*1024/256)
|
||||||
|
sm = math.sqrt(var(values))/mean(values)
|
||||||
|
|
||||||
|
assert(0.99 <= nm <= 1.01)
|
||||||
|
assert(sm <= 0.02)
|
||||||
|
|
||||||
72
tests/pico-hsm/test_004_key_domains.py
Normal file
72
tests/pico-hsm/test_004_key_domains.py
Normal file
@@ -0,0 +1,72 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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
|
||||||
|
from const import DEFAULT_DKEK_SHARES, DEFAULT_DKEK
|
||||||
|
|
||||||
|
KEY_DOMAINS = 3
|
||||||
|
|
||||||
|
def test_key_domains(device):
|
||||||
|
device.initialize(key_domains=KEY_DOMAINS)
|
||||||
|
for k in range(KEY_DOMAINS):
|
||||||
|
kd = device.get_key_domain(key_domain=k)
|
||||||
|
assert('error' in kd)
|
||||||
|
assert(kd['error'] == 0x6A88)
|
||||||
|
|
||||||
|
kd = device.get_key_domain(key_domain=KEY_DOMAINS)
|
||||||
|
assert('error' in kd)
|
||||||
|
assert(kd['error'] == 0x6A86)
|
||||||
|
assert(device.get_key_domains() == KEY_DOMAINS)
|
||||||
|
|
||||||
|
def test_set_key_domain(device):
|
||||||
|
kd = device.get_key_domain(key_domain=0)
|
||||||
|
assert('error' in kd)
|
||||||
|
assert(kd['error'] == 0x6A88)
|
||||||
|
|
||||||
|
device.set_key_domain(key_domain=0)
|
||||||
|
kd = device.get_key_domain(key_domain=0)
|
||||||
|
assert('error' not in kd)
|
||||||
|
assert('dkek' in kd)
|
||||||
|
assert('total' in kd['dkek'])
|
||||||
|
assert(kd['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
||||||
|
assert('missing' in kd['dkek'])
|
||||||
|
assert(kd['dkek']['missing'] == DEFAULT_DKEK_SHARES)
|
||||||
|
|
||||||
|
def test_clear_key_domain(device):
|
||||||
|
kd = device.get_key_domain(key_domain=0)
|
||||||
|
assert(kd['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
||||||
|
|
||||||
|
device.import_dkek(DEFAULT_DKEK)
|
||||||
|
kd = device.get_key_domain(key_domain=0)
|
||||||
|
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)
|
||||||
|
|
||||||
|
def test_delete_key_domain(device):
|
||||||
|
assert(device.get_key_domains() == KEY_DOMAINS)
|
||||||
|
kd = device.get_key_domain(key_domain=0)
|
||||||
|
assert(kd['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
||||||
|
|
||||||
|
device.delete_key_domain(key_domain=0)
|
||||||
|
assert(device.get_key_domains() == KEY_DOMAINS)
|
||||||
|
kd = device.get_key_domain(key_domain=0)
|
||||||
|
assert('error' in kd)
|
||||||
|
assert(kd['error'] == 0x6A88)
|
||||||
37
tests/pico-hsm/test_005_dkek.py
Normal file
37
tests/pico-hsm/test_005_dkek.py
Normal file
@@ -0,0 +1,37 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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 hashlib
|
||||||
|
from utils import APDUResponse, SWCodes
|
||||||
|
from const import DEFAULT_PIN, DEFAULT_RETRIES, DEFAULT_DKEK, DEFAULT_DKEK_SHARES
|
||||||
|
|
||||||
|
def test_dkek(device):
|
||||||
|
device.initialize(retries=DEFAULT_RETRIES, dkek_shares=DEFAULT_DKEK_SHARES)
|
||||||
|
device.login(DEFAULT_PIN)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
assert(resp[0] == DEFAULT_DKEK_SHARES)
|
||||||
|
assert(resp[1] == DEFAULT_DKEK_SHARES-1)
|
||||||
|
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
assert(resp[1] == DEFAULT_DKEK_SHARES-2)
|
||||||
|
|
||||||
|
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]
|
||||||
|
assert(bytes(resp[2:]) == kcv)
|
||||||
|
|
||||||
53
tests/pico-hsm/test_010_pin.py
Normal file
53
tests/pico-hsm/test_010_pin.py
Normal file
@@ -0,0 +1,53 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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
|
||||||
|
from utils import APDUResponse, SWCodes
|
||||||
|
from const import DEFAULT_PIN, DEFAULT_RETRIES
|
||||||
|
|
||||||
|
WRONG_PIN = '112233'
|
||||||
|
RETRIES = DEFAULT_RETRIES
|
||||||
|
|
||||||
|
def test_pin_init_retries(device):
|
||||||
|
device.initialize(retries=RETRIES)
|
||||||
|
retries = device.get_login_retries()
|
||||||
|
assert(retries == RETRIES)
|
||||||
|
|
||||||
|
def test_pin_login(device):
|
||||||
|
device.initialize(retries=RETRIES)
|
||||||
|
device.login(DEFAULT_PIN)
|
||||||
|
|
||||||
|
def test_pin_retries(device):
|
||||||
|
device.initialize(retries=RETRIES)
|
||||||
|
device.login(DEFAULT_PIN)
|
||||||
|
|
||||||
|
for ret in range(RETRIES-1):
|
||||||
|
with pytest.raises(APDUResponse) as e:
|
||||||
|
device.login(WRONG_PIN)
|
||||||
|
assert(e.value.sw1 == 0x63 and e.value.sw2 == (0xC0 | (RETRIES-1-ret)))
|
||||||
|
|
||||||
|
with pytest.raises(APDUResponse) as e:
|
||||||
|
device.login(WRONG_PIN)
|
||||||
|
assert(e.value.sw == SWCodes.SW_PIN_BLOCKED.value)
|
||||||
|
|
||||||
|
device.initialize(retries=RETRIES)
|
||||||
|
retries = device.get_login_retries()
|
||||||
|
assert(retries == RETRIES)
|
||||||
|
|
||||||
|
|
||||||
45
tests/pico-hsm/test_020_keypair_gen.py
Normal file
45
tests/pico-hsm/test_020_keypair_gen.py
Normal file
@@ -0,0 +1,45 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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
|
||||||
|
from utils import KeyType, DOPrefixes
|
||||||
|
|
||||||
|
def test_gen_initialize(device):
|
||||||
|
device.initialize()
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"curve", ['secp192r1', 'secp256r1', 'secp384r1', 'secp521r1', 'brainpoolP256r1', 'brainpoolP384r1', 'brainpoolP512r1', 'secp192k1', 'secp256k1']
|
||||||
|
)
|
||||||
|
def test_gen_ecc(device, curve):
|
||||||
|
keyid = device.key_generation(KeyType.ECC, curve)
|
||||||
|
resp = device.list_keys()
|
||||||
|
assert((DOPrefixes.KEY_PREFIX.value, keyid) in resp)
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
||||||
|
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX.value << 8 | keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"modulus", [1024, 2048, 4096]
|
||||||
|
)
|
||||||
|
def test_gen_rsa(device, modulus):
|
||||||
|
keyid = device.key_generation(KeyType.RSA, modulus)
|
||||||
|
resp = device.list_keys()
|
||||||
|
assert((DOPrefixes.KEY_PREFIX.value, keyid) in resp)
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
||||||
|
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX.value << 8 | keyid)
|
||||||
|
|
||||||
65
tests/pico-hsm/test_021_key_import.py
Normal file
65
tests/pico-hsm/test_021_key_import.py
Normal file
@@ -0,0 +1,65 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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 hashlib
|
||||||
|
import os
|
||||||
|
from utils import KeyType, DOPrefixes
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import rsa, ec
|
||||||
|
from const import DEFAULT_RETRIES, DEFAULT_DKEK_SHARES, DEFAULT_DKEK
|
||||||
|
|
||||||
|
def test_prepare_dkek(device):
|
||||||
|
device.initialize(retries=DEFAULT_RETRIES, dkek_shares=DEFAULT_DKEK_SHARES)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]
|
||||||
|
assert(bytes(resp[2:]) == kcv)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"modulus", [1024, 2048, 4096]
|
||||||
|
)
|
||||||
|
def test_import_rsa(device, modulus):
|
||||||
|
pkey = rsa.generate_private_key(
|
||||||
|
public_exponent=65537,
|
||||||
|
key_size=modulus,
|
||||||
|
)
|
||||||
|
keyid = device.import_key(pkey)
|
||||||
|
pubkey = device.public_key(keyid)
|
||||||
|
assert(pubkey.public_numbers() == pkey.public_key().public_numbers())
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
||||||
|
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX.value << 8 | keyid)
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"curve", [ec.SECP192R1, ec.SECP256R1, ec.SECP384R1, ec.SECP521R1, ec.SECP256K1, ec.BrainpoolP256R1, ec.BrainpoolP384R1, ec.BrainpoolP512R1]
|
||||||
|
)
|
||||||
|
def test_import_ecc(device, curve):
|
||||||
|
pkey = ec.generate_private_key(curve())
|
||||||
|
keyid = device.import_key(pkey)
|
||||||
|
pubkey = device.public_key(keyid, param=curve().name)
|
||||||
|
assert(pubkey.public_numbers() == pkey.public_key().public_numbers())
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
||||||
|
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX.value << 8 | keyid)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
def test_import_aes(device, size):
|
||||||
|
pkey = os.urandom(size // 8)
|
||||||
|
keyid = device.import_key(pkey)
|
||||||
52
tests/pico-hsm/test_022_key_exchange.py
Normal file
52
tests/pico-hsm/test_022_key_exchange.py
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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 hashlib
|
||||||
|
from utils import KeyType, DOPrefixes
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import rsa, ec
|
||||||
|
from const import DEFAULT_RETRIES, DEFAULT_DKEK_SHARES, DEFAULT_DKEK
|
||||||
|
|
||||||
|
def test_prepare_dkek(device):
|
||||||
|
device.initialize(retries=DEFAULT_RETRIES, dkek_shares=DEFAULT_DKEK_SHARES)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]
|
||||||
|
assert(bytes(resp[2:]) == kcv)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"curve", [ec.SECP192R1, ec.SECP256R1, ec.SECP384R1, ec.SECP521R1, ec.SECP256K1, ec.BrainpoolP256R1, ec.BrainpoolP384R1, ec.BrainpoolP512R1]
|
||||||
|
)
|
||||||
|
def test_exchange_ecc(device, curve):
|
||||||
|
pkeyA = ec.generate_private_key(curve())
|
||||||
|
pbkeyA = pkeyA.public_key()
|
||||||
|
keyid = device.import_key(pkeyA)
|
||||||
|
pkeyB = ec.generate_private_key(curve())
|
||||||
|
pbkeyB = pkeyB.public_key()
|
||||||
|
|
||||||
|
sharedB = pkeyB.exchange(ec.ECDH(), pbkeyA)
|
||||||
|
sharedA = device.exchange(keyid, pbkeyB)
|
||||||
|
|
||||||
|
assert(bytes(sharedA) == sharedB)
|
||||||
|
|
||||||
|
sharedAA = pkeyA.exchange(ec.ECDH(), pbkeyB)
|
||||||
|
assert(bytes(sharedA) == sharedAA)
|
||||||
|
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
||||||
|
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX.value << 8 | keyid)
|
||||||
30
tests/pico-hsm/test_023_key_generation.py
Normal file
30
tests/pico-hsm/test_023_key_generation.py
Normal file
@@ -0,0 +1,30 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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
|
||||||
|
from utils import KeyType, DOPrefixes
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
def test_gen_aes(device, size):
|
||||||
|
keyid = device.key_generation(KeyType.AES, size)
|
||||||
|
resp = device.list_keys()
|
||||||
|
assert((DOPrefixes.KEY_PREFIX.value, keyid) in resp)
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
||||||
57
tests/pico-hsm/test_030_signature.py
Normal file
57
tests/pico-hsm/test_030_signature.py
Normal file
@@ -0,0 +1,57 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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
|
||||||
|
from utils import KeyType, DOPrefixes, Algorithm
|
||||||
|
from binascii import hexlify
|
||||||
|
import hashlib
|
||||||
|
|
||||||
|
data = b'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam neque urna, iaculis quis auctor scelerisque, auctor ut risus. In rhoncus, odio consequat consequat ultrices, ex libero dictum risus, accumsan interdum nisi orci ac neque. Ut vitae sem in metus hendrerit facilisis. Mauris maximus tristique mi, quis blandit lectus convallis eget.'
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"curve", ['secp192r1', 'secp256r1', 'secp384r1', 'secp521r1', 'brainpoolP256r1', 'brainpoolP384r1', 'brainpoolP512r1', 'secp256k1']
|
||||||
|
)
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"scheme", [Algorithm.ALGO_EC_RAW, Algorithm.ALGO_EC_SHA1, Algorithm.ALGO_EC_SHA224, Algorithm.ALGO_EC_SHA256, Algorithm.ALGO_EC_SHA384, Algorithm.ALGO_EC_SHA512]
|
||||||
|
)
|
||||||
|
def test_signature_ecc(device, curve, scheme):
|
||||||
|
keyid = device.key_generation(KeyType.ECC, curve)
|
||||||
|
pubkey = device.public_key(keyid=keyid, param=curve)
|
||||||
|
if (scheme == Algorithm.ALGO_EC_RAW):
|
||||||
|
datab = hashlib.sha512(data).digest()
|
||||||
|
else:
|
||||||
|
datab = data
|
||||||
|
signature = device.sign(keyid=keyid, scheme=scheme, data=datab)
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
||||||
|
device.verify(pubkey, datab, signature, scheme)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"modulus", [1024,2048,4096]
|
||||||
|
)
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"scheme", [Algorithm.ALGO_RSA_PKCS1_SHA1, Algorithm.ALGO_RSA_PKCS1_SHA224, Algorithm.ALGO_RSA_PKCS1_SHA256, Algorithm.ALGO_RSA_PKCS1_SHA384, Algorithm.ALGO_RSA_PKCS1_SHA512, Algorithm.ALGO_RSA_PSS_SHA1, Algorithm.ALGO_RSA_PSS_SHA224, Algorithm.ALGO_RSA_PSS_SHA256, Algorithm.ALGO_RSA_PSS_SHA384, Algorithm.ALGO_RSA_PSS_SHA512]
|
||||||
|
)
|
||||||
|
def test_signature_rsa(device, modulus, scheme):
|
||||||
|
keyid = device.key_generation(KeyType.RSA, modulus)
|
||||||
|
pubkey = device.public_key(keyid=keyid)
|
||||||
|
signature = device.sign(keyid=keyid, scheme=scheme, data=data)
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
||||||
|
device.verify(pubkey, data, signature, scheme)
|
||||||
|
|
||||||
48
tests/pico-hsm/test_040_decrypt.py
Normal file
48
tests/pico-hsm/test_040_decrypt.py
Normal file
@@ -0,0 +1,48 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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
|
||||||
|
from utils import KeyType, DOPrefixes, Algorithm
|
||||||
|
from binascii import hexlify
|
||||||
|
import hashlib
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import padding
|
||||||
|
from cryptography.hazmat.primitives import hashes
|
||||||
|
|
||||||
|
data = b'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nullam neque urna, iaculis quis auctor scelerisque, auctor ut risus. In rhoncus, odio consequat consequat ultrices, ex libero dictum risus, accumsan interdum nisi orci ac neque. Ut vitae sem in metus hendrerit facilisis. Mauris maximus tristique mi, quis blandit lectus convallis eget.'
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"modulus", [1024,2048,4096]
|
||||||
|
)
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"pad", [padding.PKCS1v15(), padding.OAEP(
|
||||||
|
mgf=padding.MGF1(algorithm=hashes.SHA256()),
|
||||||
|
algorithm=hashes.SHA256(),
|
||||||
|
label=None
|
||||||
|
)]
|
||||||
|
)
|
||||||
|
def test_decrypt_rsa(device, modulus, pad):
|
||||||
|
|
||||||
|
keyid = device.key_generation(KeyType.RSA, modulus)
|
||||||
|
pubkey = device.public_key(keyid=keyid)
|
||||||
|
message = data[:(modulus//8)-100]
|
||||||
|
ciphered = pubkey.encrypt(message, pad)
|
||||||
|
datab = device.decrypt(keyid, ciphered, pad)
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
||||||
|
assert(datab == message)
|
||||||
|
|
||||||
52
tests/pico-hsm/test_050_cipher.py
Normal file
52
tests/pico-hsm/test_050_cipher.py
Normal file
@@ -0,0 +1,52 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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
|
||||||
|
from utils import Algorithm, DOPrefixes
|
||||||
|
from const import DEFAULT_DKEK_SHARES, DEFAULT_DKEK
|
||||||
|
|
||||||
|
MESSAGE = b'a secret message'
|
||||||
|
|
||||||
|
def test_prepare_aes(device):
|
||||||
|
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
def test_cipher_aes_cipher(device, size):
|
||||||
|
pkey = os.urandom(size // 8)
|
||||||
|
iv = b'\x00'*16
|
||||||
|
keyid = device.import_key(pkey)
|
||||||
|
|
||||||
|
cipher = Cipher(algorithms.AES(pkey), modes.CBC(iv))
|
||||||
|
encryptor = cipher.encryptor()
|
||||||
|
ctA = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||||
|
ctB = device.cipher(Algorithm.ALGO_AES_CBC_ENCRYPT, keyid, MESSAGE)
|
||||||
|
assert(bytes(ctB) == ctA)
|
||||||
|
|
||||||
|
decryptor = cipher.decryptor()
|
||||||
|
plA = decryptor.update(ctA) + decryptor.finalize()
|
||||||
|
plB = device.cipher(Algorithm.ALGO_AES_CBC_DECRYPT, keyid, ctA)
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
||||||
|
assert(bytes(plB) == plA)
|
||||||
|
assert(bytes(plB) == MESSAGE)
|
||||||
62
tests/pico-hsm/test_060_mac.py
Normal file
62
tests/pico-hsm/test_060_mac.py
Normal file
@@ -0,0 +1,62 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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 import hashes, hmac, cmac
|
||||||
|
from cryptography.hazmat.primitives.ciphers import algorithms
|
||||||
|
from utils import Algorithm, DOPrefixes
|
||||||
|
from const import DEFAULT_DKEK_SHARES, DEFAULT_DKEK
|
||||||
|
|
||||||
|
MESSAGE = b'a secret message'
|
||||||
|
|
||||||
|
def test_prepare_aes(device):
|
||||||
|
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"algo", [hashes.SHA1, hashes.SHA224, hashes.SHA256, hashes.SHA384, hashes.SHA512]
|
||||||
|
)
|
||||||
|
def test_mac_hmac(device, size, algo):
|
||||||
|
pkey = os.urandom(size // 8)
|
||||||
|
keyid = device.import_key(pkey)
|
||||||
|
resA = device.hmac(algo, keyid, MESSAGE)
|
||||||
|
h = hmac.HMAC(pkey, algo())
|
||||||
|
h.update(MESSAGE)
|
||||||
|
resB = h.finalize()
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
||||||
|
assert(bytes(resA) == resB)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
def test_mac_cmac(device, size):
|
||||||
|
pkey = os.urandom(size // 8)
|
||||||
|
keyid = device.import_key(pkey)
|
||||||
|
resA = device.cmac(keyid, MESSAGE)
|
||||||
|
c = cmac.CMAC(algorithms.AES(pkey))
|
||||||
|
c.update(MESSAGE)
|
||||||
|
resB = c.finalize()
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
||||||
|
assert(bytes(resA) == resB)
|
||||||
|
|
||||||
81
tests/pico-hsm/test_070_hkdf.py
Normal file
81
tests/pico-hsm/test_070_hkdf.py
Normal file
@@ -0,0 +1,81 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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 import hashes
|
||||||
|
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
||||||
|
from cryptography import exceptions
|
||||||
|
from const import DEFAULT_DKEK_SHARES, DEFAULT_DKEK
|
||||||
|
from utils import DOPrefixes
|
||||||
|
|
||||||
|
INFO = b'info message'
|
||||||
|
|
||||||
|
def test_prepare_kd(device):
|
||||||
|
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"algo", [hashes.SHA256, hashes.SHA384, hashes.SHA512]
|
||||||
|
)
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"out_len", [32, 64, 256, 1024]
|
||||||
|
)
|
||||||
|
class TestHKDF:
|
||||||
|
def test_hkdf_ok(self, device, size, algo, out_len):
|
||||||
|
pkey = os.urandom(size // 8)
|
||||||
|
keyid = device.import_key(pkey)
|
||||||
|
salt = os.urandom(16)
|
||||||
|
resA = device.hkdf(algo, keyid, INFO, salt, out_len=out_len)
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
||||||
|
hkdf = HKDF(
|
||||||
|
algorithm=algo(),
|
||||||
|
length=out_len,
|
||||||
|
salt=salt,
|
||||||
|
info=INFO,
|
||||||
|
)
|
||||||
|
resB = hkdf.derive(pkey)
|
||||||
|
assert(bytes(resA) == resB)
|
||||||
|
hkdf = HKDF(
|
||||||
|
algorithm=algo(),
|
||||||
|
length=out_len,
|
||||||
|
salt=salt,
|
||||||
|
info=INFO,
|
||||||
|
)
|
||||||
|
hkdf.verify(pkey, bytes(resA))
|
||||||
|
|
||||||
|
def test_hkdf_fail(self, device, size, algo, out_len):
|
||||||
|
pkey = os.urandom(size // 8)
|
||||||
|
keyid = device.import_key(pkey)
|
||||||
|
salt = os.urandom(16)
|
||||||
|
resA = device.hkdf(algo, keyid, INFO, salt, out_len=out_len)
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
||||||
|
hkdf = HKDF(
|
||||||
|
algorithm=algo(),
|
||||||
|
length=out_len,
|
||||||
|
salt=salt,
|
||||||
|
info=INFO,
|
||||||
|
)
|
||||||
|
pkey = os.urandom(size // 8)
|
||||||
|
with pytest.raises(exceptions.InvalidKey):
|
||||||
|
hkdf.verify(pkey, bytes(resA))
|
||||||
85
tests/pico-hsm/test_071_pbkdf2.py
Normal file
85
tests/pico-hsm/test_071_pbkdf2.py
Normal file
@@ -0,0 +1,85 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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 import hashes
|
||||||
|
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
|
||||||
|
from cryptography import exceptions
|
||||||
|
from const import DEFAULT_DKEK_SHARES, DEFAULT_DKEK
|
||||||
|
from utils import DOPrefixes
|
||||||
|
|
||||||
|
INFO = b'info message'
|
||||||
|
|
||||||
|
def test_prepare_kd(device):
|
||||||
|
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"algo", [hashes.SHA1, hashes.SHA224, hashes.SHA256, hashes.SHA384, hashes.SHA512]
|
||||||
|
)
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"out_len", [32, 64, 256, 1024]
|
||||||
|
)
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"iterations", [1024, 2048]
|
||||||
|
)
|
||||||
|
class TestPBKDF2:
|
||||||
|
def test_pbkdf2_ok(self, device, size, algo, out_len, iterations):
|
||||||
|
pkey = os.urandom(size // 8)
|
||||||
|
keyid = device.import_key(pkey)
|
||||||
|
salt = os.urandom(16)
|
||||||
|
resA = device.pbkdf2(algo, keyid, salt, iterations=iterations, out_len=out_len)
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
||||||
|
kdf = PBKDF2HMAC(
|
||||||
|
algorithm=algo(),
|
||||||
|
length=out_len,
|
||||||
|
salt=salt,
|
||||||
|
iterations=iterations,
|
||||||
|
)
|
||||||
|
resB = kdf.derive(pkey)
|
||||||
|
assert(bytes(resA) == resB)
|
||||||
|
kdf = PBKDF2HMAC(
|
||||||
|
algorithm=algo(),
|
||||||
|
length=out_len,
|
||||||
|
salt=salt,
|
||||||
|
iterations=iterations,
|
||||||
|
)
|
||||||
|
kdf.verify(pkey, bytes(resA))
|
||||||
|
|
||||||
|
def test_pbkdf2_fail(self, device, size, algo, out_len, iterations):
|
||||||
|
pkey = os.urandom(size // 8)
|
||||||
|
keyid = device.import_key(pkey)
|
||||||
|
salt = os.urandom(16)
|
||||||
|
resA = device.pbkdf2(algo, keyid, salt, iterations=iterations, out_len=out_len)
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
||||||
|
|
||||||
|
kdf = PBKDF2HMAC(
|
||||||
|
algorithm=algo(),
|
||||||
|
length=out_len,
|
||||||
|
salt=salt,
|
||||||
|
iterations=iterations,
|
||||||
|
)
|
||||||
|
pkey = os.urandom(size // 8)
|
||||||
|
with pytest.raises(exceptions.InvalidKey):
|
||||||
|
kdf.verify(pkey, bytes(resA))
|
||||||
76
tests/pico-hsm/test_072_x963.py
Normal file
76
tests/pico-hsm/test_072_x963.py
Normal file
@@ -0,0 +1,76 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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 import hashes
|
||||||
|
from cryptography.hazmat.primitives.kdf.x963kdf import X963KDF
|
||||||
|
from cryptography import exceptions
|
||||||
|
from const import DEFAULT_DKEK_SHARES, DEFAULT_DKEK
|
||||||
|
from utils import DOPrefixes
|
||||||
|
|
||||||
|
INFO = b'shared message'
|
||||||
|
|
||||||
|
def test_prepare_kd(device):
|
||||||
|
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
resp = device.import_dkek(DEFAULT_DKEK)
|
||||||
|
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"size", [128, 192, 256]
|
||||||
|
)
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"algo", [hashes.SHA1, hashes.SHA224, hashes.SHA256, hashes.SHA384, hashes.SHA512]
|
||||||
|
)
|
||||||
|
@pytest.mark.parametrize(
|
||||||
|
"out_len", [32, 64, 256, 1024]
|
||||||
|
)
|
||||||
|
class TestX963:
|
||||||
|
def test_x963_ok(self, device, size, algo, out_len):
|
||||||
|
pkey = os.urandom(size // 8)
|
||||||
|
keyid = device.import_key(pkey)
|
||||||
|
resA = device.x963(algo, keyid, INFO, out_len=out_len)
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
||||||
|
xkdf = X963KDF(
|
||||||
|
algorithm=algo(),
|
||||||
|
length=out_len,
|
||||||
|
sharedinfo=INFO,
|
||||||
|
)
|
||||||
|
resB = xkdf.derive(pkey)
|
||||||
|
assert(bytes(resA) == resB)
|
||||||
|
xkdf = X963KDF(
|
||||||
|
algorithm=algo(),
|
||||||
|
length=out_len,
|
||||||
|
sharedinfo=INFO,
|
||||||
|
)
|
||||||
|
xkdf.verify(pkey, bytes(resA))
|
||||||
|
|
||||||
|
def test_x963_fail(self, device, size, algo, out_len):
|
||||||
|
pkey = os.urandom(size // 8)
|
||||||
|
keyid = device.import_key(pkey)
|
||||||
|
resA = device.x963(algo, keyid, INFO, out_len=out_len)
|
||||||
|
device.delete_file(DOPrefixes.KEY_PREFIX.value << 8 | keyid)
|
||||||
|
xkdf = X963KDF(
|
||||||
|
algorithm=algo(),
|
||||||
|
length=out_len,
|
||||||
|
sharedinfo=INFO,
|
||||||
|
)
|
||||||
|
pkey = os.urandom(size // 8)
|
||||||
|
with pytest.raises(exceptions.InvalidKey):
|
||||||
|
xkdf.verify(pkey, bytes(resA))
|
||||||
5
tests/run-test-in-docker.sh
Executable file
5
tests/run-test-in-docker.sh
Executable file
@@ -0,0 +1,5 @@
|
|||||||
|
#!/bin/bash -eu
|
||||||
|
|
||||||
|
source tests/docker_env.sh
|
||||||
|
run_in_docker ./tests/start-up-and-test.sh
|
||||||
|
|
||||||
8
tests/start-up-and-test.sh
Executable file
8
tests/start-up-and-test.sh
Executable file
@@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/bash -eu
|
||||||
|
|
||||||
|
/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
|
||||||
138
tests/utils.py
Normal file
138
tests/utils.py
Normal file
@@ -0,0 +1,138 @@
|
|||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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="2" #Version of Pico CCID Core
|
VERSION_MAJOR="4" #Version of Pico CCID Core
|
||||||
VERSION_MINOR="0"
|
VERSION_MINOR="0"
|
||||||
|
|
||||||
echo "----------------------------"
|
echo "----------------------------"
|
||||||
638
tools/pico-hsm-tool.py
Normal file
638
tools/pico-hsm-tool.py
Normal file
@@ -0,0 +1,638 @@
|
|||||||
|
#!/usr/bin/env python3
|
||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""
|
||||||
|
/*
|
||||||
|
* 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 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:
|
||||||
|
from cvc.certificates import CVC
|
||||||
|
from cvc.asn1 import ASN1
|
||||||
|
from cvc.oid import oid2scheme
|
||||||
|
from cvc.utils import scheme_rsa
|
||||||
|
except ModuleNotFoundError:
|
||||||
|
print('ERROR: cvc module not found! Install pycvc package.\nTry with `pip install pycvc`')
|
||||||
|
sys.exit(-1)
|
||||||
|
|
||||||
|
try:
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import ec
|
||||||
|
from cryptography.hazmat.primitives.kdf.hkdf import HKDF
|
||||||
|
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
|
||||||
|
from cryptography.hazmat.primitives.ciphers.aead import ChaCha20Poly1305
|
||||||
|
from cryptography.hazmat.primitives import hashes
|
||||||
|
except ModuleNotFoundError:
|
||||||
|
print('ERROR: cryptography module not found! Install cryptography package.\nTry with `pip install cryptography`')
|
||||||
|
sys.exit(-1)
|
||||||
|
|
||||||
|
|
||||||
|
import json
|
||||||
|
import urllib.request
|
||||||
|
import base64
|
||||||
|
from binascii import hexlify, unhexlify
|
||||||
|
import sys
|
||||||
|
import argparse
|
||||||
|
import os
|
||||||
|
import platform
|
||||||
|
from datetime import datetime
|
||||||
|
from argparse import RawTextHelpFormatter
|
||||||
|
|
||||||
|
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):
|
||||||
|
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():
|
||||||
|
parser = argparse.ArgumentParser()
|
||||||
|
subparser = parser.add_subparsers(title="commands", dest="command")
|
||||||
|
parser_init = subparser.add_parser('initialize', help='Performs the first initialization of the Pico HSM.')
|
||||||
|
parser.add_argument('--pin', help='PIN number')
|
||||||
|
parser_init.add_argument('--so-pin', help='SO-PIN number')
|
||||||
|
|
||||||
|
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_pki = subparser.add_parser('pki', help='Performs PKI operations.')
|
||||||
|
subparser_pki = parser_pki.add_subparsers(title='commands', dest='subcommand')
|
||||||
|
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('--default', help='Setups the default public PKI from public Pico HSM PKI.', 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).')
|
||||||
|
subparser_rtc = parser_rtc.add_subparsers(title='commands', dest='subcommand')
|
||||||
|
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_opts = subparser.add_parser('options', help='Manage extra options.', formatter_class=RawTextHelpFormatter)
|
||||||
|
subparser_opts = parser_opts.add_subparsers(title='commands', dest='subcommand')
|
||||||
|
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.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_secure = subparser.add_parser('secure', help='Manages security of Pico HSM.')
|
||||||
|
subparser_secure = parser_secure.add_subparsers(title='commands', dest='subcommand')
|
||||||
|
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_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.')
|
||||||
|
subparser_cipher = parser_cipher.add_subparsers(title='commands', dest='subcommand')
|
||||||
|
parser_cipher_encrypt = subparser_cipher.add_parser('encrypt', help='Performs encryption.')
|
||||||
|
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('hmac', help='Computes HMAC.')
|
||||||
|
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('--iteration', help='Iteration count.', required=any(['PBKDF2' in s for s in sys.argv]))
|
||||||
|
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_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('--iteration', help='Iteration count.', required=any(['PBKDF2' in s for s in sys.argv]))
|
||||||
|
|
||||||
|
parser_cipher.add_argument('--iv', help='Sets the IV/nonce (hex string).')
|
||||||
|
parser_cipher.add_argument('--file-in', help='File to encrypt or decrypt.')
|
||||||
|
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('--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('-s', '--key-size', default=32, help='Size of the key in bytes.')
|
||||||
|
|
||||||
|
parser_x25519 = argparse.ArgumentParser(add_help=False)
|
||||||
|
subparser_x25519 = parser_x25519.add_subparsers(title='commands', dest='subcommand')
|
||||||
|
parser_x25519_keygen = subparser_x25519.add_parser('keygen', help='Generates a keypair for X25519 or X448.')
|
||||||
|
parser_x25519.add_argument('-k', '--key', help='The private key index', metavar='KEY_ID', required=True)
|
||||||
|
|
||||||
|
# Subparsers based on parent
|
||||||
|
|
||||||
|
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()
|
||||||
|
return args
|
||||||
|
|
||||||
|
def get_pki_data(url, data=None, method='GET'):
|
||||||
|
user_agent = 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; '
|
||||||
|
'rv:1.9.0.7) Gecko/2009021910 Firefox/3.0.7'
|
||||||
|
method = 'GET'
|
||||||
|
if (data is not None):
|
||||||
|
method = 'POST'
|
||||||
|
req = urllib.request.Request(f"https://www.picokeys.com/pico/pico-hsm/{url}/",
|
||||||
|
method=method,
|
||||||
|
data=data,
|
||||||
|
headers={'User-Agent': user_agent, })
|
||||||
|
response = urllib.request.urlopen(req)
|
||||||
|
resp = response.read().decode('utf-8')
|
||||||
|
j = json.loads(resp)
|
||||||
|
return j
|
||||||
|
|
||||||
|
def get_pki_certs(certs_dir='certs', force=False):
|
||||||
|
certs = get_pki_data('certs')
|
||||||
|
if (os.path.exists(certs_dir) is False):
|
||||||
|
os.mkdir(certs_dir)
|
||||||
|
cvcap = os.path.join(certs_dir, certs['cvca']['CHR'])
|
||||||
|
dvcap = os.path.join(certs_dir, certs['dvca']['CHR'])
|
||||||
|
if (os.path.exists(cvcap) is False or force is True):
|
||||||
|
with open(cvcap, 'wb') as f:
|
||||||
|
f.write(base64.urlsafe_b64decode(certs['cvca']['cert']))
|
||||||
|
if (os.path.exists(dvcap) is False or force is True):
|
||||||
|
with open(dvcap, 'wb') as f:
|
||||||
|
f.write(base64.urlsafe_b64decode(certs['dvca']['cert']))
|
||||||
|
print(f'All PKI certificates are stored at {certs_dir} folder')
|
||||||
|
|
||||||
|
def pki(card, args):
|
||||||
|
if (args.subcommand == 'initialize'):
|
||||||
|
if (args.default is True):
|
||||||
|
get_pki_certs(certs_dir=args.certs_dir, force=args.force)
|
||||||
|
else:
|
||||||
|
print('Error: no PKI is passed. Use --default to retrieve default PKI.')
|
||||||
|
|
||||||
|
def login(card, args):
|
||||||
|
global pin
|
||||||
|
pin = args.pin
|
||||||
|
try:
|
||||||
|
response = send_apdu(card, 0x20, 0x00, 0x81, list(args.pin.encode()))
|
||||||
|
except APDUResponse:
|
||||||
|
pass
|
||||||
|
|
||||||
|
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):
|
||||||
|
pin = args.pin.encode()
|
||||||
|
try:
|
||||||
|
response = send_apdu(card, 0x20, 0x00, 0x81, list(pin))
|
||||||
|
except APDUResponse:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
pin = b'648219'
|
||||||
|
|
||||||
|
if (args.so_pin):
|
||||||
|
so_pin = args.so_pin.encode()
|
||||||
|
try:
|
||||||
|
response = send_apdu(card, 0x20, 0x00, 0x82, list(so_pin))
|
||||||
|
except APDUResponse:
|
||||||
|
pass
|
||||||
|
else:
|
||||||
|
so_pin = b'57621880'
|
||||||
|
|
||||||
|
pin_data = [0x81, len(pin)] + list(pin)
|
||||||
|
so_pin_data = [0x82, len(so_pin)] + list(so_pin)
|
||||||
|
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)
|
||||||
|
Y = CVC().decode(cert).pubkey().find(0x86).data()
|
||||||
|
print(f'Public Point: {hexlify(Y).decode()}')
|
||||||
|
|
||||||
|
pbk = base64.urlsafe_b64encode(Y)
|
||||||
|
data = urllib.parse.urlencode({'pubkey': pbk}).encode()
|
||||||
|
j = get_pki_data('cvc', data=data)
|
||||||
|
print('Device name: '+j['devname'])
|
||||||
|
dataef = base64.urlsafe_b64decode(
|
||||||
|
j['cvcert']) + base64.urlsafe_b64decode(j['dvcert'])
|
||||||
|
|
||||||
|
response = send_apdu(card, 0xa4, 0x00, 0x00, [0x2f, 0x02])
|
||||||
|
response = send_apdu(card, 0x20, 0x00, 0x81, list(pin))
|
||||||
|
|
||||||
|
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('')
|
||||||
|
print('Note that the device is initialized with a default PIN and '
|
||||||
|
'configuration.')
|
||||||
|
print('Now you can initialize the device as usual with your chosen PIN '
|
||||||
|
'and configuration options.')
|
||||||
|
|
||||||
|
def attestate(card, args):
|
||||||
|
kid = int(args.key)
|
||||||
|
try:
|
||||||
|
response = send_apdu(card, 0xB1, 0x2F, 0x02, [0x54, 0x02, 0x00, 0x00])
|
||||||
|
except APDUResponse as a:
|
||||||
|
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(f'Details of key {kid}:\n')
|
||||||
|
print(f' CAR: {(CVC().decode(cert).car()).decode()}')
|
||||||
|
print(' Public Key:')
|
||||||
|
puboid = CVC().decode(cert).pubkey().oid()
|
||||||
|
print(f' Scheme: {oid2scheme(puboid)}')
|
||||||
|
chr = CVC().decode(cert).chr()
|
||||||
|
car = CVC().decode(cert).car()
|
||||||
|
if (scheme_rsa(puboid)):
|
||||||
|
print(f' Modulus: {hexlify(CVC().decode(cert).pubkey().find(0x81).data()).decode()}')
|
||||||
|
print(f' Exponent: {hexlify(CVC().decode(cert).pubkey().find(0x82).data()).decode()}')
|
||||||
|
else:
|
||||||
|
print(f' Public Point: {hexlify(CVC().decode(cert).pubkey().find(0x86).data()).decode()}')
|
||||||
|
print(f' CHR: {chr.decode()}')
|
||||||
|
print(' Key signature:')
|
||||||
|
inret = CVC().decode(cert).verify()
|
||||||
|
if (inret):
|
||||||
|
print(' Status: VALID')
|
||||||
|
print(f' This certificate is signed with private key {kid}')
|
||||||
|
else:
|
||||||
|
print(' Status: NOT VALID')
|
||||||
|
print(f' This certificate is NOT signed with private key {kid}')
|
||||||
|
print(' Cert signature:')
|
||||||
|
print(f' Outer CAR: {CVC().decode(cert).outer_car().decode()}')
|
||||||
|
outret = CVC().decode(cert).verify(outer=True, dica=devcert, curve=ec.SECP256R1())
|
||||||
|
if (outret):
|
||||||
|
print(' Status: VALID')
|
||||||
|
print(' This certificate is signed with the device key')
|
||||||
|
else:
|
||||||
|
print(' Status: NOT VALID')
|
||||||
|
print(' This certificate is NOT signed with the device key')
|
||||||
|
|
||||||
|
if (inret is True and outret is True):
|
||||||
|
print(f'Key {kid} is generated by device {chr.decode()}')
|
||||||
|
else:
|
||||||
|
print(f'Key {kid} is NOT generated by device {chr.decode()}')
|
||||||
|
|
||||||
|
def rtc(card, args):
|
||||||
|
if (args.subcommand == 'set'):
|
||||||
|
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 ])
|
||||||
|
elif (args.subcommand == 'get'):
|
||||||
|
response = send_apdu(card, [0x80, 0x64], 0x0A, 0x00)
|
||||||
|
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()}')
|
||||||
|
|
||||||
|
def opts(card, args):
|
||||||
|
opt = 0x0
|
||||||
|
if (args.opt == 'button'):
|
||||||
|
opt = 0x1
|
||||||
|
elif (args.opt == 'counter'):
|
||||||
|
opt = 0x2
|
||||||
|
current = send_apdu(card, [0x80, 0x64], 0x6, 0x0)[0]
|
||||||
|
if (args.subcommand == 'set'):
|
||||||
|
if (args.onoff == 'on'):
|
||||||
|
newopt = current | opt
|
||||||
|
else:
|
||||||
|
newopt = current & ~opt
|
||||||
|
send_apdu(card, [0x80, 0x64], 0x6, 0x0, [newopt])
|
||||||
|
elif (args.subcommand == 'get'):
|
||||||
|
print(f'Option {args.opt.upper()} is {"ON" if current & opt else "OFF"}')
|
||||||
|
|
||||||
|
class SecureLock:
|
||||||
|
def __init__(self, card):
|
||||||
|
self.card = card
|
||||||
|
|
||||||
|
def mse(self):
|
||||||
|
sk = ec.generate_private_key(ec.SECP256R1())
|
||||||
|
pn = sk.public_key().public_numbers()
|
||||||
|
self.__pb = sk.public_key().public_bytes(Encoding.X962, PublicFormat.UncompressedPoint)
|
||||||
|
|
||||||
|
|
||||||
|
ret = send_apdu(self.card, [0x80, 0x64], 0x3A, 0x01, list(self.__pb))
|
||||||
|
|
||||||
|
pk = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256R1(), bytes(ret))
|
||||||
|
shared_key = sk.exchange(ec.ECDH(), pk)
|
||||||
|
|
||||||
|
xkdf = HKDF(
|
||||||
|
algorithm=hashes.SHA256(),
|
||||||
|
length=12+32,
|
||||||
|
salt=None,
|
||||||
|
info=self.__pb
|
||||||
|
)
|
||||||
|
kdf_out = xkdf.derive(shared_key)
|
||||||
|
self.__key_enc = kdf_out[12:]
|
||||||
|
self.__iv = kdf_out[:12]
|
||||||
|
|
||||||
|
def encrypt_chacha(self, data):
|
||||||
|
chacha = ChaCha20Poly1305(self.__key_enc)
|
||||||
|
ct = chacha.encrypt(self.__iv, data, self.__pb)
|
||||||
|
return ct
|
||||||
|
|
||||||
|
def unlock_device(self):
|
||||||
|
ct = self.get_skey()
|
||||||
|
send_apdu(self.card, [0x80, 0x64], 0x3A, 0x03, list(ct))
|
||||||
|
|
||||||
|
def _get_key_device(self):
|
||||||
|
if (platform.system() == 'Windows' or platform.system() == 'Linux'):
|
||||||
|
from secure_key import windows as skey
|
||||||
|
elif (platform.system() == 'Darwin'):
|
||||||
|
from secure_key import macos as skey
|
||||||
|
else:
|
||||||
|
print('ERROR: platform not supported')
|
||||||
|
sys.exit(-1)
|
||||||
|
return skey.get_secure_key()
|
||||||
|
|
||||||
|
def get_skey(self):
|
||||||
|
self.mse()
|
||||||
|
ct = self.encrypt_chacha(self._get_key_device())
|
||||||
|
return ct
|
||||||
|
|
||||||
|
def enable_device_aut(self):
|
||||||
|
ct = self.get_skey()
|
||||||
|
send_apdu(self.card, [0x80, 0x64], 0x3A, 0x02, list(ct))
|
||||||
|
|
||||||
|
def disable_device_aut(self):
|
||||||
|
ct = self.get_skey()
|
||||||
|
send_apdu(self.card, [0x80, 0x64], 0x3A, 0x04, list(ct))
|
||||||
|
|
||||||
|
|
||||||
|
def secure(card, args):
|
||||||
|
slck = SecureLock(card)
|
||||||
|
if (args.subcommand == 'enable'):
|
||||||
|
slck.enable_device_aut()
|
||||||
|
elif (args.subcommand == 'unlock'):
|
||||||
|
slck.unlock_device()
|
||||||
|
elif (args.subcommand == 'disable'):
|
||||||
|
slck.disable_device_aut()
|
||||||
|
|
||||||
|
|
||||||
|
def cipher(card, args):
|
||||||
|
if (args.subcommand == 'keygen'):
|
||||||
|
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:
|
||||||
|
enc = None
|
||||||
|
aad = None
|
||||||
|
if (args.alg == 'CHACHAPOLY'):
|
||||||
|
oid = b'\x2A\x86\x48\x86\xF7\x0D\x01\x09\x10\x03\x12'
|
||||||
|
elif (args.alg == 'HMAC-SHA1'):
|
||||||
|
oid = b'\x2A\x86\x48\x86\xF7\x0D\x02\x07'
|
||||||
|
elif (args.alg == 'HMAC-SHA224'):
|
||||||
|
oid = b'\x2A\x86\x48\x86\xF7\x0D\x02\x08'
|
||||||
|
elif (args.alg == 'HMAC-SHA256'):
|
||||||
|
oid = b'\x2A\x86\x48\x86\xF7\x0D\x02\x09'
|
||||||
|
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'):
|
||||||
|
alg = 0x51
|
||||||
|
elif (args.subcommand[0] == 'd'):
|
||||||
|
alg = 0x52
|
||||||
|
|
||||||
|
if (not enc):
|
||||||
|
if (args.file_in):
|
||||||
|
fin = open(args.file_in, 'rb')
|
||||||
|
else:
|
||||||
|
fin = sys.stdin.buffer
|
||||||
|
enc = fin.read()
|
||||||
|
fin.close()
|
||||||
|
|
||||||
|
data = [0x06, len(oid)] + list(oid) + [0x81, len(enc)] + list(enc)
|
||||||
|
|
||||||
|
if (args.iv and not 'PBKDF2' in args.alg and not 'PBES2' in args.alg):
|
||||||
|
data += [0x82, len(args.iv)//2] + list(unhexlify(args.iv))
|
||||||
|
if (not aad):
|
||||||
|
aad = args.aad
|
||||||
|
if (aad):
|
||||||
|
if (args.hex):
|
||||||
|
data += [0x83, len(aad)//2] + list(unhexlify(aad))
|
||||||
|
else:
|
||||||
|
data += [0x83, len(aad)] + list(aad)
|
||||||
|
|
||||||
|
ne = int(args.output_len) if 'output_len' in args and args.output_len else None
|
||||||
|
|
||||||
|
ret = send_apdu(card, [0x80, 0x78], int(args.key), alg, data=data, ne=ne)
|
||||||
|
if (args.file_out):
|
||||||
|
fout = open(args.file_out, 'wb')
|
||||||
|
else:
|
||||||
|
fout = sys.stdout.buffer
|
||||||
|
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):
|
||||||
|
sys.stderr.buffer.write(b'Pico HSM Tool v1.8\n')
|
||||||
|
sys.stderr.buffer.write(b'Author: Pol Henarejos\n')
|
||||||
|
sys.stderr.buffer.write(b'Report bugs to https://github.com/polhenarejos/pico-hsm/issues\n')
|
||||||
|
sys.stderr.buffer.write(b'\n\n')
|
||||||
|
cardtype = AnyCardType()
|
||||||
|
try:
|
||||||
|
# request card insertion
|
||||||
|
cardrequest = CardRequest(timeout=10, cardType=cardtype)
|
||||||
|
card = cardrequest.waitforcard()
|
||||||
|
|
||||||
|
# connect to the card and perform a few transmits
|
||||||
|
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
|
||||||
|
if (args.command == 'initialize'):
|
||||||
|
initialize(card, args)
|
||||||
|
elif (args.command == 'attestate'):
|
||||||
|
attestate(card, args)
|
||||||
|
elif (args.command == 'pki'):
|
||||||
|
pki(card, args)
|
||||||
|
elif (args.command == 'datetime'):
|
||||||
|
rtc(card, args)
|
||||||
|
elif (args.command == 'options'):
|
||||||
|
opts(card, args)
|
||||||
|
elif (args.command == 'secure'):
|
||||||
|
secure(card, args)
|
||||||
|
elif (args.command == 'cipher'):
|
||||||
|
cipher(card, args)
|
||||||
|
elif (args.command == 'x25519' or args.command == 'x448'):
|
||||||
|
x25519(card, args)
|
||||||
|
|
||||||
|
|
||||||
|
def run():
|
||||||
|
args = parse_args()
|
||||||
|
main(args)
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
run()
|
||||||
59
tools/secure_key/macos.py
Normal file
59
tools/secure_key/macos.py
Normal file
@@ -0,0 +1,59 @@
|
|||||||
|
import sys
|
||||||
|
import keyring
|
||||||
|
|
||||||
|
DOMAIN = "PicoKeys.com"
|
||||||
|
USERNAME = "Pico-HSM"
|
||||||
|
|
||||||
|
try:
|
||||||
|
import keyring
|
||||||
|
from keyrings.osx_keychain_keys.backend import OSXKeychainKeysBackend, OSXKeychainKeyType, OSXKeyChainKeyClassType
|
||||||
|
except:
|
||||||
|
print('ERROR: keyring module not found! Install keyring package.\nTry with `pip install keyrings.osx-keychain-keys`')
|
||||||
|
sys.exit(-1)
|
||||||
|
|
||||||
|
try:
|
||||||
|
from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, NoEncryption
|
||||||
|
except:
|
||||||
|
print('ERROR: cryptography module not found! Install cryptography package.\nTry with `pip install cryptography`')
|
||||||
|
sys.exit(-1)
|
||||||
|
|
||||||
|
|
||||||
|
def get_backend(use_secure_enclave=False):
|
||||||
|
backend = OSXKeychainKeysBackend(
|
||||||
|
key_type=OSXKeychainKeyType.EC, # Key type, e.g. RSA, RC, DSA, ...
|
||||||
|
key_class_type=OSXKeyChainKeyClassType.Private, # Private key, Public key, Symmetric-key
|
||||||
|
key_size_in_bits=256,
|
||||||
|
is_permanent=True, # If set, saves the key in keychain; else, returns a transient key
|
||||||
|
use_secure_enclave=use_secure_enclave, # Saves the key in the T2 (TPM) chip, requires a code-signed interpreter
|
||||||
|
access_group=None, # Limits key management and retrieval to set group, requires a code-signed interpreter
|
||||||
|
is_extractable=True # If set, private key is extractable; else, it can't be retrieved, but only operated against
|
||||||
|
)
|
||||||
|
return backend
|
||||||
|
|
||||||
|
def generate_secure_key(use_secure_enclave=False):
|
||||||
|
backend = get_backend(use_secure_enclave)
|
||||||
|
backend.set_password(DOMAIN, USERNAME, password=None)
|
||||||
|
return backend.get_password(DOMAIN, USERNAME)
|
||||||
|
|
||||||
|
def get_d(key):
|
||||||
|
return key.private_numbers().private_value.to_bytes(32, 'big')
|
||||||
|
|
||||||
|
def set_secure_key(pk):
|
||||||
|
backend = get_backend(False)
|
||||||
|
try:
|
||||||
|
backend.delete_password(DOMAIN, USERNAME)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
backend.set_password(DOMAIN, USERNAME, pk.private_bytes(Encoding.PEM, PrivateFormat.TraditionalOpenSSL, NoEncryption()))
|
||||||
|
|
||||||
|
def get_secure_key():
|
||||||
|
key = None
|
||||||
|
try:
|
||||||
|
backend = get_backend(False)
|
||||||
|
key = backend.get_password(DOMAIN, USERNAME)[0]
|
||||||
|
except keyring.errors.KeyringError:
|
||||||
|
try:
|
||||||
|
key = generate_secure_key(False)[0] # It should be True, but secure enclave causes python segfault
|
||||||
|
except keyring.errors.PasswordSetError:
|
||||||
|
key = generate_secure_key(False)[0]
|
||||||
|
return get_d(key)
|
||||||
44
tools/secure_key/windows.py
Normal file
44
tools/secure_key/windows.py
Normal file
@@ -0,0 +1,44 @@
|
|||||||
|
import sys
|
||||||
|
import os
|
||||||
|
import base64
|
||||||
|
|
||||||
|
DOMAIN = "PicoKeys.com"
|
||||||
|
USERNAME = "Pico-HSM"
|
||||||
|
|
||||||
|
try:
|
||||||
|
import keyring
|
||||||
|
except:
|
||||||
|
print('ERROR: keyring module not found! Install keyring package.\nTry with `pip install keyrings.osx-keychain-keys`')
|
||||||
|
sys.exit(-1)
|
||||||
|
|
||||||
|
try:
|
||||||
|
from cryptography.hazmat.primitives.serialization import Encoding, PrivateFormat, NoEncryption, load_pem_private_key
|
||||||
|
from cryptography.hazmat.primitives.asymmetric import ec
|
||||||
|
except:
|
||||||
|
print('ERROR: cryptography module not found! Install cryptography package.\nTry with `pip install cryptography`')
|
||||||
|
sys.exit(-1)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def generate_secure_key():
|
||||||
|
pkey = ec.generate_private_key(ec.SECP256R1())
|
||||||
|
set_secure_key(pkey)
|
||||||
|
return keyring.get_password(DOMAIN, USERNAME)
|
||||||
|
|
||||||
|
def get_d(key):
|
||||||
|
return load_pem_private_key(key, password=None).private_numbers().private_value.to_bytes(32, 'big')
|
||||||
|
|
||||||
|
def set_secure_key(pk):
|
||||||
|
try:
|
||||||
|
keyring.delete_password(DOMAIN, USERNAME)
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
keyring.set_password(DOMAIN, USERNAME, pk.private_bytes(Encoding.PEM, PrivateFormat.PKCS8, NoEncryption()).decode())
|
||||||
|
|
||||||
|
def get_secure_key():
|
||||||
|
key = None
|
||||||
|
try:
|
||||||
|
key = keyring.get_password(DOMAIN, USERNAME)
|
||||||
|
except keyring.errors.KeyringError:
|
||||||
|
key = generate_secure_key()
|
||||||
|
return get_d(key.encode())
|
||||||
13
workflows/autobuild.sh
Executable file
13
workflows/autobuild.sh
Executable file
@@ -0,0 +1,13 @@
|
|||||||
|
#!/bin/bash
|
||||||
|
|
||||||
|
git submodule update --init --recursive
|
||||||
|
sudo apt update
|
||||||
|
sudo apt install -y cmake gcc-arm-none-eabi libnewlib-arm-none-eabi libstdc++-arm-none-eabi-newlib
|
||||||
|
git clone https://github.com/raspberrypi/pico-sdk
|
||||||
|
cd pico-sdk
|
||||||
|
git submodule update --init
|
||||||
|
cd ..
|
||||||
|
mkdir build
|
||||||
|
cd build
|
||||||
|
cmake -DPICO_SDK_PATH=../pico-sdk ..
|
||||||
|
make
|
||||||
Reference in New Issue
Block a user