Compare commits
621 Commits
v2.6
...
v5.0-eddsa
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bb45c9b3a8 | ||
|
|
1ea0a91ba8 | ||
|
|
6f572954d5 | ||
|
|
99a9803328 | ||
|
|
5535f3ec10 | ||
|
|
f992a04142 | ||
|
|
d858a1e1d5 | ||
|
|
b7c6ca58d0 | ||
|
|
2f3d70fcac | ||
|
|
91c641033a | ||
|
|
f3bf3cd8f4 | ||
|
|
e4736cc448 | ||
|
|
bfa8891c8d | ||
|
|
618fdb4c1a | ||
|
|
9457433844 | ||
|
|
c239b4dd7c | ||
|
|
96359ebe03 | ||
|
|
f301b2a1b1 | ||
|
|
4ec1d4d891 | ||
|
|
f1410bbf04 | ||
|
|
9b9ea7cae5 | ||
|
|
f5b89aed69 | ||
|
|
f74a374c64 | ||
|
|
3c6684cdab | ||
|
|
20ef94c301 | ||
|
|
68360978d6 | ||
|
|
1933498a33 | ||
|
|
0ce89ae968 | ||
|
|
9fa3758dad | ||
|
|
d1ee43baab | ||
|
|
2856ec6917 | ||
|
|
ccec83dfb1 | ||
|
|
9de1b4ca5d | ||
|
|
cbd9a5d296 | ||
|
|
eaf3d051e3 | ||
|
|
8e3801e9a2 | ||
|
|
5388c11182 | ||
|
|
2b77519a3b | ||
|
|
812a737ff5 | ||
|
|
6163b870ed | ||
|
|
08d4dc58aa | ||
|
|
0193e55f7b | ||
|
|
9dc3ea3232 | ||
|
|
48d92f53a0 | ||
|
|
3b083f9bd7 | ||
|
|
9cd7bc7b3e | ||
|
|
4bea47faca | ||
|
|
954eb1d890 | ||
|
|
f7451f56ed | ||
|
|
1a8c8440cf | ||
|
|
9f1e5d0abd | ||
|
|
4b314470b4 | ||
|
|
d0461f81f4 | ||
|
|
4454c633e4 | ||
|
|
15664da61d | ||
|
|
1a2bff33a8 | ||
|
|
cf44794bb6 | ||
|
|
33a6a70457 | ||
|
|
c3ddfe9689 | ||
|
|
72eb5a2a69 | ||
|
|
95f3a464b1 | ||
|
|
bb37a3ddb8 | ||
|
|
6da49336c9 | ||
|
|
fc69f5e1b1 | ||
|
|
3602577b6e | ||
|
|
c6a72e4ffb | ||
|
|
c889cef488 | ||
|
|
d78e925d49 | ||
|
|
bb8fcbcd3f | ||
|
|
c433e131eb | ||
|
|
11d52495d7 | ||
|
|
f450279370 | ||
|
|
b571b0b945 | ||
|
|
5ae63959d5 | ||
|
|
8e8bd32b44 | ||
|
|
68d2909653 | ||
|
|
e64eb2157c | ||
|
|
af23b401cb | ||
|
|
1da29f22c1 | ||
|
|
f458750c91 | ||
|
|
c5143df212 | ||
|
|
60f471cdd7 | ||
|
|
5c3c45a189 | ||
|
|
3b92ce0597 | ||
|
|
56ab770a26 | ||
|
|
09f7ed6640 | ||
|
|
aaf1bc2bbd | ||
|
|
f7e8359835 | ||
|
|
1c45295d28 | ||
|
|
af099cd416 | ||
|
|
36d1011471 | ||
|
|
c5714a91ab | ||
|
|
b8002a1a08 | ||
|
|
604fc1aa45 | ||
|
|
39a5af8649 | ||
|
|
28c63a500c | ||
|
|
ef03ce4020 | ||
|
|
9335b088cf | ||
|
|
9cc934282c | ||
|
|
2ad67e5e17 | ||
|
|
7493f9eb3e | ||
|
|
d44b780970 | ||
|
|
e7080d6f82 | ||
|
|
9258c9ff70 | ||
|
|
ad18577e98 | ||
|
|
3cae928de8 | ||
|
|
b429616895 | ||
|
|
0c2e728c35 | ||
|
|
5630043a4d | ||
|
|
c1a47ed023 | ||
|
|
bf2f961b85 | ||
|
|
0811b8022e | ||
|
|
fd12758551 | ||
|
|
c65f921188 | ||
|
|
55cf9292d2 | ||
|
|
db5c7adef4 | ||
|
|
d3751e3918 | ||
|
|
d708158fea | ||
|
|
dc979194fa | ||
|
|
237e687c3b | ||
|
|
ed89175edc | ||
|
|
9a7be98e6e | ||
|
|
c4a08aff0f | ||
|
|
223fc117dd | ||
|
|
d1fb4d0c65 | ||
|
|
47acef71c8 | ||
|
|
bb641ee134 | ||
|
|
99c777c780 | ||
|
|
79f76a176d | ||
|
|
dd68554782 | ||
|
|
f20fdc9bda | ||
|
|
e7d4a5dd3d | ||
|
|
b4671c2ecb | ||
|
|
50a29519bd | ||
|
|
54cdbfc22c | ||
|
|
4a40cebe1f | ||
|
|
87ffd21543 | ||
|
|
7cb0bbf982 | ||
|
|
07079b6ba1 | ||
|
|
294ca81d7d | ||
|
|
218660e694 | ||
|
|
de89d61359 | ||
|
|
8e8192362c | ||
|
|
25c93c279f | ||
|
|
001d076fdf | ||
|
|
35d5d5e94e | ||
|
|
b034303193 | ||
|
|
623cf10dba | ||
|
|
fdc41e5856 | ||
|
|
5d0dc210da | ||
|
|
a674410826 | ||
|
|
920d22212a | ||
|
|
aeeb540a2f | ||
|
|
be071b0bc1 | ||
|
|
8bbbdb4dd8 | ||
|
|
45b633cc9d | ||
|
|
842919a26b | ||
|
|
3dbcefea85 | ||
|
|
60038f9345 | ||
|
|
d8c7fb0856 | ||
|
|
d6456b4dde | ||
|
|
ac781c1db6 | ||
|
|
c3b66773e8 | ||
|
|
3ca23b932c | ||
|
|
9fad920c3b | ||
|
|
38bef5b43f | ||
|
|
2034e436d1 | ||
|
|
215221b30e | ||
|
|
de4d95beb8 | ||
|
|
963b6f4f87 | ||
|
|
fa9b244c42 | ||
|
|
2b92d89ab7 | ||
|
|
a1d7733b95 | ||
|
|
39f1041dbb | ||
|
|
2e4fc568db | ||
|
|
4f4e6e09a2 | ||
|
|
08c0aaee6f | ||
|
|
de98e79c99 | ||
|
|
481cd5fd69 | ||
|
|
d9a8826a32 | ||
|
|
d82affa880 | ||
|
|
ab31a6615c | ||
|
|
677cceb130 | ||
|
|
29967c067a | ||
|
|
2974aa234a | ||
|
|
d90b296237 | ||
|
|
e98b26fee5 | ||
|
|
2086a68c53 | ||
|
|
74afa07512 | ||
|
|
e96e1d0097 | ||
|
|
4d47f0224e | ||
|
|
58692b2711 | ||
|
|
a5ab1cabc5 | ||
|
|
1c7cdc8564 | ||
|
|
d74b3418bc | ||
|
|
fb5be153ed | ||
|
|
0ac71f2fff | ||
|
|
6ec5235cc3 | ||
|
|
ff74d6306e | ||
|
|
ba562da00e | ||
|
|
98e9b72b42 | ||
|
|
1b0d23cf24 | ||
|
|
3ccff7881f | ||
|
|
a3bf2e9e14 | ||
|
|
88ff27f354 | ||
|
|
ed2925cfb6 | ||
|
|
cc19f8f061 | ||
|
|
b6831a4650 | ||
|
|
652a0f0d21 | ||
|
|
9dbf4b3172 | ||
|
|
76522829ef | ||
|
|
6b1eeb4004 | ||
|
|
2693ab4926 | ||
|
|
5d21e39aa6 | ||
|
|
1bf0d6337b | ||
|
|
1950b03d35 | ||
|
|
4be258f4c7 | ||
|
|
eddb1baf7b | ||
|
|
11bb00e186 | ||
|
|
aaed6bd7b6 | ||
|
|
2853b38b08 | ||
|
|
654cb1e4e0 | ||
|
|
185d19504f | ||
|
|
dbe0ef19de | ||
|
|
c3b57b229f | ||
|
|
43c46e9112 | ||
|
|
d5af9160c1 | ||
|
|
e27c8d4ff6 | ||
|
|
2ecfff0ebb | ||
|
|
3057aba041 | ||
|
|
011a594fe4 | ||
|
|
448d61dd2d | ||
|
|
fa821c43c8 | ||
|
|
9db3e78d32 | ||
|
|
b74c4070d1 | ||
|
|
a7770a7e57 | ||
|
|
78cbe59e64 | ||
|
|
42a9434c50 | ||
|
|
11a3472941 | ||
|
|
2f177eb8df | ||
|
|
c97680772d | ||
|
|
345ae2be69 | ||
|
|
ba036f4c0f | ||
|
|
4493afa84d | ||
|
|
d118b787a2 | ||
|
|
205356b848 | ||
|
|
c435764978 | ||
|
|
2e633abb2c | ||
|
|
3514c7ad82 | ||
|
|
4bba3c6f64 | ||
|
|
8321996a14 | ||
|
|
c3af303468 | ||
|
|
c44d7db4e1 | ||
|
|
cb1bba4f13 | ||
|
|
48301a5d71 | ||
|
|
1105a1263c | ||
|
|
37421d9aad | ||
|
|
d906df2809 | ||
|
|
08e7d74a81 | ||
|
|
433e509c94 | ||
|
|
9f08d612ae | ||
|
|
173ca7678d | ||
|
|
3d7f714936 | ||
|
|
f4a537f156 | ||
|
|
f09654ccf4 | ||
|
|
7506ccd263 | ||
|
|
ee442ac084 | ||
|
|
b94810d31d | ||
|
|
2c4be41ecf | ||
|
|
447d223de4 | ||
|
|
4f9f7f14fe | ||
|
|
6699913eff | ||
|
|
b0057bc3fe | ||
|
|
e3a773d145 | ||
|
|
10a47f9177 | ||
|
|
9f49a144ac | ||
|
|
e67a7091ff | ||
|
|
1d3232df36 | ||
|
|
7376817724 | ||
|
|
5e801fbae7 | ||
|
|
e18c413268 | ||
|
|
0e1c82196a | ||
|
|
c6a5272340 | ||
|
|
a6072b4ce8 | ||
|
|
5bdba8e1e8 | ||
|
|
5df4e62f81 | ||
|
|
685c7f25fc | ||
|
|
faef2dc278 | ||
|
|
22d8793683 | ||
|
|
32c8bc4a24 | ||
|
|
b5174d64af | ||
|
|
235bf342b3 | ||
|
|
57188ff877 | ||
|
|
f631e4a5f3 | ||
|
|
f880ee6c93 | ||
|
|
6af4cc7fec | ||
|
|
e3f1f45a9f | ||
|
|
fe315e7326 | ||
|
|
02903bbc65 | ||
|
|
ee3ee21e40 | ||
|
|
c6c00e7e43 | ||
|
|
29544a3f17 | ||
|
|
5135404083 | ||
|
|
55520ce184 | ||
|
|
525b05b7ef | ||
|
|
b61a34d415 | ||
|
|
0eea0fb096 | ||
|
|
82c03ee6c4 | ||
|
|
20dfbcaaed | ||
|
|
a9fb170c58 | ||
|
|
46d85c029e | ||
|
|
1c6f4cfd7f | ||
|
|
526869bc06 | ||
|
|
279df32acc | ||
|
|
c402b884cc | ||
|
|
8316196b42 | ||
|
|
7a6dafd7b6 | ||
|
|
6d3809a792 | ||
|
|
f22f58f983 | ||
|
|
405bf92e18 | ||
|
|
b5b6dcd2e6 | ||
|
|
d637dbec01 | ||
|
|
ebcac9dfdc | ||
|
|
510b148adf | ||
|
|
371ae93fcd | ||
|
|
f5e875a6b7 | ||
|
|
ad3304a384 | ||
|
|
4d647ba3c8 | ||
|
|
008db87fa7 | ||
|
|
1d80b45439 | ||
|
|
17560034ec | ||
|
|
8b0d85fbd4 | ||
|
|
3dcb2e9d70 | ||
|
|
0f12ff1c48 | ||
|
|
2a5fe1cc6d | ||
|
|
5e0f62265d | ||
|
|
0990805fb6 | ||
|
|
18bcf532e7 | ||
|
|
9f0316aedd | ||
|
|
088002863c | ||
|
|
7876f4b32a | ||
|
|
a5e3d4e0e5 | ||
|
|
0c842773d2 | ||
|
|
0aaf339353 | ||
|
|
efba39adc5 | ||
|
|
13755cb4d5 | ||
|
|
11a30863e8 | ||
|
|
a69d06b2d9 | ||
|
|
1c7bc18161 | ||
|
|
86ce01cac2 | ||
|
|
9cb60ba420 | ||
|
|
99f1620e7d | ||
|
|
755570e01a | ||
|
|
4b264597d6 | ||
|
|
67e3d908b3 | ||
|
|
7ae76354ef | ||
|
|
9291c2b4e3 | ||
|
|
657ee18730 | ||
|
|
132054c9b9 | ||
|
|
2a3b9b7474 | ||
|
|
4e73723747 | ||
|
|
09724d95db | ||
|
|
c1bfb597bc | ||
|
|
fd53b88397 | ||
|
|
11e5338736 | ||
|
|
3660120b11 | ||
|
|
75ca1b57d9 | ||
|
|
7af67713e7 | ||
|
|
63c465138b | ||
|
|
4d569df108 | ||
|
|
bee6a7bb92 | ||
|
|
e4583eb9c0 | ||
|
|
1c8582365d | ||
|
|
daf71678c5 | ||
|
|
26f0775772 | ||
|
|
ed674b379c | ||
|
|
6aa8d37d07 | ||
|
|
963456051e | ||
|
|
1e90699a3f | ||
|
|
f8110a9d75 | ||
|
|
d81b21695f | ||
|
|
51e9e6722e | ||
|
|
dba4630895 | ||
|
|
ee73c6e781 | ||
|
|
2f63966c60 | ||
|
|
e624f9ff72 | ||
|
|
fb4ff9424e | ||
|
|
63b245b858 | ||
|
|
cd525d91a3 | ||
|
|
8fd3b4d858 | ||
|
|
3c160f69c0 | ||
|
|
2c9fa8b19f | ||
|
|
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 |
4
.github/FUNDING.yml
vendored
Normal file
4
.github/FUNDING.yml
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
# These are supported funding model platforms
|
||||
|
||||
github: polhenarejos
|
||||
custom: ["https://www.paypal.me/polhenarejos"]
|
||||
74
.github/workflows/codeql.yml
vendored
Normal file
74
.github/workflows/codeql.yml
vendored
Normal file
@@ -0,0 +1,74 @@
|
||||
# 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", "development-eddsa" ]
|
||||
pull_request:
|
||||
# The branches below must be a subset of the branches above
|
||||
branches: [ "master", "development", "development-eddsa" ]
|
||||
schedule:
|
||||
- cron: '23 5 * * 4'
|
||||
workflow_dispatch:
|
||||
|
||||
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
|
||||
mode: [ 'pico', 'local' ]
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v3
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||
# 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 ${{ matrix.mode }}
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v3
|
||||
34
.github/workflows/nightly.yml
vendored
Normal file
34
.github/workflows/nightly.yml
vendored
Normal file
@@ -0,0 +1,34 @@
|
||||
name: "Nightly deploy"
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 2 * * *'
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
nightly:
|
||||
name: Deploy nightly
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
refs: [master, development]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ matrix.refs }}
|
||||
submodules: 'recursive'
|
||||
- name : Build
|
||||
env:
|
||||
PICO_SDK_PATH: ../pico-sdk
|
||||
run: |
|
||||
./workflows/autobuild.sh pico
|
||||
./build_pico_hsm.sh
|
||||
- name: Update nightly release
|
||||
uses: pyTooling/Actions/releaser@main
|
||||
with:
|
||||
tag: nightly-${{ matrix.refs }}
|
||||
rm: true
|
||||
token: ${{ secrets.GITHUB_TOKEN }}
|
||||
files: release/*.*
|
||||
66
.github/workflows/test.yml
vendored
Normal file
66
.github/workflows/test.yml
vendored
Normal file
@@ -0,0 +1,66 @@
|
||||
# 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", "development-eddsa" ]
|
||||
pull_request:
|
||||
# The branches below must be a subset of the branches above
|
||||
branches: [ "master", "development", "development-eddsa" ]
|
||||
schedule:
|
||||
- cron: '23 5 * * 4'
|
||||
workflow_dispatch:
|
||||
|
||||
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: Export image
|
||||
run: |
|
||||
mkdir -p artifacts
|
||||
docker save pico-hsm-test:bullseye -o artifacts/docker-image.tar
|
||||
- name: Temporarily save image
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: docker-artifact
|
||||
path: artifacts
|
||||
retention-days: 1
|
||||
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
needs: build
|
||||
strategy:
|
||||
matrix:
|
||||
suite: ["pkcs11", "pytest", "sc-hsm-pkcs11"]
|
||||
steps:
|
||||
- name: Checkout repository and submodules
|
||||
uses: actions/checkout@v3
|
||||
with:
|
||||
submodules: recursive
|
||||
- name: Retrieve saved image
|
||||
uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: docker-artifact
|
||||
path: artifacts
|
||||
- name: Load image
|
||||
run: |
|
||||
cd artifacts
|
||||
docker load -q -i docker-image.tar
|
||||
- name: Test ${{ matrix.suite }}
|
||||
run: ./tests/run-test-in-docker.sh ${{ matrix.suite }}
|
||||
6
.gitmodules
vendored
6
.gitmodules
vendored
@@ -1,3 +1,3 @@
|
||||
[submodule "pico-ccid"]
|
||||
path = pico-ccid
|
||||
url = https://github.com/polhenarejos/pico-ccid
|
||||
[submodule "pico-keys-sdk"]
|
||||
path = pico-keys-sdk
|
||||
url = https://github.com/polhenarejos/pico-keys-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)
|
||||
230
CMakeLists.txt
230
CMakeLists.txt
@@ -1,129 +1,129 @@
|
||||
#
|
||||
# This file is part of the Pico HSM distribution (https://github.com/polhenarejos/pico-hsm).
|
||||
# Copyright (c) 2022 Pol Henarejos.
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, version 3.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful, but
|
||||
# WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
# General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
#
|
||||
# This file is part of the Pico HSM distribution (https://github.com/polhenarejos/pico-hsm).
|
||||
# Copyright (c) 2022 Pol Henarejos.
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, version 3.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful, but
|
||||
# WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
# General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
cmake_minimum_required(VERSION 3.13)
|
||||
|
||||
include(pico_sdk_import.cmake)
|
||||
if(ESP_PLATFORM)
|
||||
set(EXTRA_COMPONENT_DIRS src pico-keys-sdk/src)
|
||||
include($ENV{IDF_PATH}/tools/cmake/project.cmake)
|
||||
else()
|
||||
if(NOT ENABLE_EMULATION)
|
||||
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_CXX_STANDARD 17)
|
||||
set(CMAKE_C_STANDARD 11)
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
|
||||
pico_sdk_init()
|
||||
if(NOT ENABLE_EMULATION)
|
||||
pico_sdk_init()
|
||||
endif()
|
||||
|
||||
add_executable(pico_hsm)
|
||||
if(NOT DEFINED __FOR_CI)
|
||||
set(__FOR_CI 0)
|
||||
endif()
|
||||
if(__FOR_CI)
|
||||
add_definitions(-D__FOR_CI)
|
||||
endif()
|
||||
|
||||
if (NOT DEFINED USB_VID)
|
||||
set(USB_VID 0xFEFF)
|
||||
add_executable(pico_hsm)
|
||||
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/cvc.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/files.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/dkek.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
|
||||
)
|
||||
|
||||
target_include_directories(pico_hsm PUBLIC
|
||||
${CMAKE_CURRENT_LIST_DIR}/pico-ccid/src/fs
|
||||
${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_compile_options(pico_hsm PUBLIC
|
||||
-Wall
|
||||
-Werror
|
||||
set(SOURCES ${SOURCES}
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/sc_hsm.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_select.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_list_keys.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_read_binary.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_verify.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_reset_retry.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_challenge.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_external_authenticate.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_mse.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_initialize.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_key_domain.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_key_wrap.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_keypair_gen.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_update_ef.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_delete_file.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_change_pin.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_key_gen.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_signature.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_key_unwrap.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_decrypt_asym.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_cipher_sym.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_derive_asym.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_extras.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_general_authenticate.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_session_pin.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_puk_auth.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_pso.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cmd_bip_slip.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/cvc.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/files.c
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm/kek.c
|
||||
)
|
||||
set(USB_ITF_CCID 1)
|
||||
set(USB_ITF_WCID 1)
|
||||
include(pico-keys-sdk/pico_keys_sdk_import.cmake)
|
||||
|
||||
pico_add_extra_outputs(pico_hsm)
|
||||
SET_VERSION(ver_major ver_minor "${CMAKE_CURRENT_LIST_DIR}/src/hsm/version.h")
|
||||
|
||||
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)
|
||||
if(ESP_PLATFORM)
|
||||
project(pico_hsm)
|
||||
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)
|
||||
set(INCLUDES ${INCLUDES}
|
||||
${CMAKE_CURRENT_LIST_DIR}/src/hsm
|
||||
)
|
||||
if(NOT ESP_PLATFORM)
|
||||
target_sources(pico_hsm PUBLIC ${SOURCES})
|
||||
target_include_directories(pico_hsm PUBLIC ${INCLUDES})
|
||||
|
||||
#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)
|
||||
target_compile_options(pico_hsm PUBLIC
|
||||
-Wall
|
||||
)
|
||||
if(NOT MSVC)
|
||||
target_compile_options(pico_hsm PUBLIC
|
||||
-Werror
|
||||
)
|
||||
endif()
|
||||
|
||||
if(ENABLE_EMULATION)
|
||||
if(NOT MSVC)
|
||||
target_compile_options(pico_hsm PUBLIC
|
||||
-fdata-sections
|
||||
-ffunction-sections
|
||||
)
|
||||
endif()
|
||||
if(APPLE)
|
||||
target_link_options(pico_hsm PUBLIC
|
||||
-Wl,-dead_strip
|
||||
)
|
||||
elseif(MSVC)
|
||||
target_compile_options(pico_hsm PUBLIC
|
||||
-WX
|
||||
)
|
||||
|
||||
target_link_libraries(pico_hsm PUBLIC wsock32 ws2_32 Bcrypt)
|
||||
else()
|
||||
target_link_options(pico_hsm PUBLIC
|
||||
-Wl,--gc-sections
|
||||
)
|
||||
endif(APPLE)
|
||||
target_link_libraries(pico_hsm PRIVATE pthread m)
|
||||
endif()
|
||||
endif()
|
||||
|
||||
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 2.0.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 4
|
||||
ARG VERSION_MINOR 2
|
||||
|
||||
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
|
||||
337
README.md
337
README.md
@@ -1,140 +1,211 @@
|
||||
# Raspberry Pico HSM
|
||||
This is a project to create a Hardware Security Module (HSM) with a Raspberry Pico. It converts your Pico board into a HSM which is able to generate and store private keys, encrypt or decrypt with AES or signing data without to disclose the private key. In detail, the private key never leaves the board and it cannot be retrieved as it is encrypted in the flash memory.
|
||||
This project aims to transform a Raspberry Pi Pico or ESP32 microcontroller into a Hardware Security Module (HSM). The modified Pico or ESP32 board will be capable of generating and storing private keys, performing AES encryption or decryption, and signing data without exposing the private key. Specifically, the private key remains securely on the board and cannot be retrieved since it is encrypted within the flash memory.
|
||||
|
||||
## Capabilities
|
||||
### 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.
|
||||
### > Key generation and encrypted storage
|
||||
Private and secret keys are secured using a master AES 256 key (MKEK). The MKEK is encrypted with a hashed and salted version of the PIN.
|
||||
**No private/secret keys, DKEK or PIN are stored in plain text ever. Never.**
|
||||
|
||||
### 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 (1024 to 4096 Bits)
|
||||
RSA key generation is supported for 1024, 2048, 3072, and 4096 bits. Private keys never leave the device.
|
||||
|
||||
### ECDSA key generation from 192 to 521 bits
|
||||
ECDSA key generation in place for different curves, from 192 to 521 bits.
|
||||
### > ECDSA Key Generation (192 to 521 Bits)
|
||||
ECDSA key generation supports various curves from 192 to 521 bits.
|
||||
|
||||
### ECC curves
|
||||
It supports secp192r1, secp256r1, secp384r1, secp521r1, brainpoolP256r1, brainpoolP384r1, brainpoolP512r1, secp192k1 (insecure), secp256k1 curves.
|
||||
### > ECC Curves
|
||||
Supported ECC curves include secp192r1, secp256r1, secp384r1, secp521r1, brainpoolP256r1, brainpoolP384r1, brainpoolP512r1, secp192k1 (insecure), secp256k1, Curve25519, and Curve448.
|
||||
|
||||
### SHA1, SHA224, SHA256, SHA384, SHA512 digests
|
||||
ECDSA and RSA signature can be combined with SHA digest in place.
|
||||
### > SHA Digests
|
||||
ECDSA and RSA signatures can be combined with SHA-1, SHA-224, SHA-256, SHA-384, and SHA-512 digests.
|
||||
|
||||
### Multiple RSA signature algorithms
|
||||
It supports RSA-PSS, RSA-PKCS and raw RSA signatures.
|
||||
### > Multiple RSA Signature Algorithms
|
||||
Supported RSA signature algorithms include RSA-PSS, RSA-PKCS, and raw RSA signatures.
|
||||
|
||||
### ECDSA raw and hash signature
|
||||
ECDSA signatures can be in raw or pre-hashed formats.
|
||||
### > ECDSA Signatures
|
||||
ECDSA signatures can be raw or pre-hashed.
|
||||
|
||||
### ECDH key derivation
|
||||
It supports the calculation of shared secrets with ECDH algorithm.
|
||||
### > ECDH Key Derivation
|
||||
Supports the ECDH algorithm for calculating shared secrets.
|
||||
|
||||
### EC private key derivation
|
||||
It allows ECDSA key derivation.[^1]
|
||||
### > EC Private Key Derivation
|
||||
Allows ECDSA key derivation.
|
||||
|
||||
### RSA-OEP and RSA-X-509 decryption
|
||||
It allows private decryption in place with RSA-OEP and RSA-X-509 algorithms.
|
||||
### > RSA Decryption
|
||||
Supports RSA-OEP and RSA-X.509 decryption.
|
||||
|
||||
### AES key generation
|
||||
It supports AES key generation in place with keys of 128, 192 and 256 bits.
|
||||
### > AES Key Generation
|
||||
Supports AES key generation with keys of 128, 192, and 256 bits.
|
||||
|
||||
### AES-CBC encryption/decryption
|
||||
AES encryption and decryption is performed in place.
|
||||
### > AES-CBC Encryption/Decryption
|
||||
Performs AES-CBC encryption and decryption.
|
||||
|
||||
### CMAC
|
||||
It supports AES-CMAC authentication.[^1]
|
||||
### > Advanced AES Modes
|
||||
Supports AES encryption and decryption in ECB, CBC, CFB, OFB, XTS, CTR, GCM, and CCM modes, with customizable IV/nonce and additional authenticated data (AAD).[^4]
|
||||
|
||||
### AES derivation
|
||||
It supports AES secret key derivation.[^1]
|
||||
### > AES Key Generation (128, 192, 256, 512 Bits)
|
||||
Supports AES key generation up to 512 bits, useful for AES XTS where two 256-bit keys are concatenated.
|
||||
|
||||
### PIN authorization
|
||||
Private and secret keys cannot be used without prior PIN authentication. It supports alphanumeric PIN.
|
||||
### > CMAC
|
||||
Supports AES-CMAC authentication.[^1]
|
||||
|
||||
### PKCS11 compliant interface
|
||||
The module can be interfaced with PKCS11 standard.
|
||||
### > AES Secret Key Derivation
|
||||
Supports AES secret key derivation.[^1]
|
||||
|
||||
### HRNG (hardware random number generator)
|
||||
It contains a harware random number generator properly modeled to guarantee maximum entropy.
|
||||
### > PIN Authorization
|
||||
Private and secret keys require prior PIN authentication. Supports alphanumeric PINs.
|
||||
|
||||
### 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.
|
||||
### > PKCS11 Compliant Interface
|
||||
Interfacing with the PKCS11 standard is supported.
|
||||
|
||||
### 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.
|
||||
### > Hardware Random Number Generator (HRNG)
|
||||
Contains an HRNG designed for maximum entropy.
|
||||
|
||||
### 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.
|
||||
### > Device Key Encryption Key (DKEK) Shares
|
||||
Supports importing DKEK shares to wrap, unwrap, and encrypt keys.
|
||||
|
||||
### Extended APDU support
|
||||
It supports extended APDU packets, which allows up to 65535 bytes.
|
||||
### > DKEK n-of-m Threshold Scheme
|
||||
Supports an n-of-m threshold scheme to prevent outages when a DKEK custodian is unavailable.
|
||||
|
||||
### CVC certificates
|
||||
Pico HSM manipulates CVC certificates and requests to minimize the storage of internal certificates.
|
||||
### > USB/CCID Support
|
||||
Full USB CCID stack for communication with the host via OpenSC and PCSC, allowing the use of frontend applications like OpenSSL via the PKCS11 module.
|
||||
|
||||
### 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.
|
||||
### > Extended APDU Support
|
||||
Supports extended APDU packets, allowing up to 65535 bytes.
|
||||
|
||||
### Import external private keys and certificates
|
||||
It allows private key and certificates import via WKY or PKCS#12 files.[^2][^3]
|
||||
### > CV Certificates
|
||||
Handles CVC certificates and requests to minimize internal certificate storage.
|
||||
|
||||
### 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.
|
||||
### > Attestation
|
||||
Each generated key is attached to a certificate signed by an external PKI, ensuring the key was generated by the specific device.
|
||||
|
||||
### Press-to-confirm button
|
||||
It allows the use of BOOTSEL button to confirm operations with private/secret keys, such as signatures and decryption. When a private/secret key is loaded, the user has 15 seconds to press the button to confirm the operation.
|
||||
This feature protects the user from unwanted uses from background applications that may sign data without user notice.
|
||||
### > Import External Keys and Certificates
|
||||
Allows importing private keys and certificates via WKY or PKCS#12 files.[^2][^3]
|
||||
|
||||
### Store and retrieve binary data
|
||||
It allows the storage of arbitrary files with binary data.
|
||||
### > Transport PIN
|
||||
Allows a transport PIN for provisioning, ensuring the device has not been tampered with during transportation.[^2]
|
||||
|
||||
### Real time clock (RTC)
|
||||
Pico HSM has a RTC with external datetime setting and getting.
|
||||
### > Press-to-Confirm Button
|
||||
Uses the BOOTSEL button to confirm operations with private/secret keys, providing a 15-second window to confirm the operation to protect against unauthorized use.
|
||||
|
||||
### 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.
|
||||
### > Store and Retrieve Binary Data
|
||||
Allows the storage of arbitrary binary data files.
|
||||
|
||||
### Session PIN
|
||||
A specific session PIN can be set during the session opening to avoid the systemmatic use of PIN.
|
||||
### > Real-Time Clock (RTC)
|
||||
Includes an RTC with external date and time setting and retrieval.
|
||||
|
||||
### PKI CVCert remote issuing for Secure Message
|
||||
### > Secure Messaging
|
||||
Supports secure channels to encrypt data packets between the host and device, preventing man-in-the-middle attacks.
|
||||
|
||||
### > Session PIN
|
||||
A specific session PIN can be set during session opening to avoid systematic PIN usage.
|
||||
|
||||
### > PKI CVCert Remote Issuing for Secure Messaging
|
||||
Secure channel messages are secured with a certificate issued by an external PKI.
|
||||
|
||||
### Multiple key domains
|
||||
Key domains are domains to store separate private/secret keys. Each domain is protected by a DKEK, independent from the other domains. Private/secret keys can be generated in different key domains to be used with separated DKEK.
|
||||
Therefore, a single device may contain different domains with independent keys.
|
||||
### > Multiple Key Domains
|
||||
Supports separate key domains protected by independent DKEKs, allowing different keys in different domains.
|
||||
|
||||
### Key usage counter
|
||||
A key usage counter is a counter that is reduced by 1 everytime that the private/secret key is used for signing, decrypting, derivation, etc. When it reaches 0, the key is disabled and cannot be used anymore.
|
||||
### > Key Usage Counter
|
||||
Tracks and limits the usage of private/secret keys, disabling keys once their usage counter reaches zero.
|
||||
|
||||
Key usage can also be used to perform and auditory and track the usage of a particular key.
|
||||
### > Public Key Authentication (PKA)
|
||||
Supports PKA for enhanced security, requiring a secondary device for authentication using a challenge-response mechanism.
|
||||
|
||||
### Public Key Authentication
|
||||
Public Key Authentication (PKA) allows to authenticate by using a secondary device with a private key and a registered public key in the primary device. A challenge is generated by the primary Pico HSM and given to the secondary for signature. The secondary device signs the challenge and returns the signature. Then, the primary device verifies the signature with the registered public key and if it is valid, it grants full access, as normal PIN authentication.
|
||||
### > Secure Lock
|
||||
Adds an extra layer of security by locking the Pico HSM to a specific computer using a private key.
|
||||
|
||||
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.
|
||||
### > ChaCha20-Poly1305
|
||||
Supports the ChaCha20-Poly1305 encryption algorithm for secure data encryption.[^4]
|
||||
|
||||
### > X25519 and X448
|
||||
Supports DH X25519 and X448 for key agreement, though these cannot be used for signing.
|
||||
|
||||
### > Key Derivation Functions
|
||||
Supports HKDF, PBKDF2, and X963-KDF for symmetric key derivation.
|
||||
|
||||
### > HMAC
|
||||
Supports HMAC generation with SHA digest algorithms.
|
||||
|
||||
### > CMAC
|
||||
Supports CMAC with AES for keys of 128, 192, and 256 bits.
|
||||
|
||||
### > XKEK
|
||||
Supports an advanced key sharing scheme (XKEK) for securely wrapping and unwrapping keys within authorized domains.
|
||||
|
||||
### > Master Key Encryption Key (MKEK)
|
||||
Uses an MKEK to securely store all keys, encrypted with an ephemeral key derived from the hashed PIN.
|
||||
|
||||
### > Hierarchical Deterministic Key Generation
|
||||
Supports BIP32 for asymmetric key derivation and SLIP10 for symmetric key derivation, enabling crypto wallet deployment with infinite key generation. Supports NIST 256 and Koblitz 256 curves for master key generation.[^4]
|
||||
|
||||
### > One Time Programming (OTP) Storage
|
||||
The OTP securely stores the MKEK (Master Key Encryption Key) and Device Key permanently, making it inaccessible from external interfaces. This ensures that the key is protected against unauthorized access and tampering.
|
||||
|
||||
### > Secure Boot
|
||||
Secure Boot ensures only authenticated firmware can run on the device, verifying each firmware’s digital signature to block unauthorized code.
|
||||
|
||||
### > Secure Lock
|
||||
Secure Lock restricts the device to the manufacturer’s firmware only, locking out debug access and preventing any further boot key installations.
|
||||
|
||||
### > Rescue Interface
|
||||
A built-in rescue interface allows recovery of the device if it becomes unresponsive or undetectable. This feature provides a way to restore the device to operational status without compromising security.
|
||||
|
||||
### > LED Customization
|
||||
The LED can be customized to reflect device status and user preferences, offering flexible color and brightness options for an enhanced user experience.
|
||||
|
||||
[^1]: PKCS11 modules (`pkcs11-tool` and `sc-tool`) do not support CMAC and key derivation. It must be processed through raw APDU command (`opensc-tool -s`).
|
||||
[^2]: Available via SCS3 tool. See [SCS3](/doc/scs3.md "SCS3") for more information.
|
||||
[^3]: Imports are available only if the Pico HSM is previously initialized with a DKEK and the DKEK shares are available during the import process.
|
||||
[^3]: Imports are available only if the Pico HSM is previously initialized with a DKEK and DKEK shares are available during the import process.
|
||||
[^4]: Available by using PicoHSM python tool.
|
||||
|
||||
### > ESP32-S3 support
|
||||
Pico HSM also supports ESP32-S3 boards, which add secure storage, flash encryption and secure boot.
|
||||
|
||||
### > Dynamic VID/PID
|
||||
Supports setting VID & PID on-the-fly. Use `pico-hsm-tool.py` or [Pico Commissioner](https://www.picokeys.com/pico-commissioner/ "Pico Commissioner") for specify VID/PID values and reboot the device.
|
||||
|
||||
### > Rescue Pico HSM Tool and Commissioner
|
||||
Pico HSM Tool implements a new CCID stack to rescue the Pico HSM in case it has wrong VID/PID values and it is not recognized by the OS. It can be accessed through `pico-hsm-tool.py` or [Pico Commissioner](https://www.picokeys.com/pico-commissioner/ "Pico Commissioner").
|
||||
|
||||
## Security considerations
|
||||
All secret keys (asymmetric and symmetric) are stored encrypted in the flash memory of the Raspberry Pico. DKEK is used as a 256 bit AES key to protect private and secret keys. Keys are never stored in RAM except for signature and decryption operations and only during the process. All keys (including DKEK) are loaded and cleared every time to avoid potential security flaws.
|
||||
All secret keys (both asymmetric and symmetric) are encrypted and stored in the flash memory. The MKEK, a 256-bit AES key, is used to protect these private and secret keys. Keys are held in RAM only during signature and decryption operations, and are loaded and cleared each time to avoid potential security vulnerabilities.
|
||||
|
||||
At the same time, DKEK is encrypted with doubled salted and hashed PIN. Also, the PIN is hashed in memory during the session. Hence, PIN is never stored in plain text neither in flash nor in memory. Note that PIN is conveyed from the host to the HSM in plain text if no secure channel is provided.
|
||||
The MKEK itself is encrypted using a doubly salted and hashed PIN, and the PIN is hashed in memory during sessions. This ensures that the PIN is never stored in plaintext, neither in flash memory nor in RAM. However, if no secure channel is used, the PIN may be transmitted in plaintext from the host to the HSM.
|
||||
|
||||
If the Pico is stolen the contents of private and secret keys cannot be read without the PIN, even if the flash memory is dumped.
|
||||
DKEKs are used during the export and import of private/secret keys and are part of a Key Domain. A Key Domain is a set of secret/private keys that share the same DKEK. These are also shared by the custodians and are not specific to Pico HSM. Therefore, if a key does not belong to a Key Domain (and thus lacks a DKEK), it cannot be exported.
|
||||
|
||||
In the event that the Pico is stolen, the private and secret key contents cannot be accessed without the PIN, even if the flash memory is dumped.
|
||||
|
||||
### RP2350 and ESP32-S3
|
||||
RP2350 and ESP32-S3 microcontrollers are equipped with advanced security features, including Secure Boot and Secure Lock, ensuring that firmware integrity and authenticity are tightly controlled. Both devices support the storage of the Master Key Encryption Key (MKEK) in an OTP (One-Time Programmable) memory region, making it permanently inaccessible for external access or tampering. This secure, non-volatile region guarantees that critical security keys are embedded into the hardware, preventing unauthorized access and supporting robust defenses against code injection or firmware modification. Together, Secure Boot and Secure Lock enforce firmware authentication, while the MKEK in OTP memory solidifies the foundation for secure operations.
|
||||
|
||||
### Secure Boot
|
||||
Secure Boot is a security feature that ensures that only trusted firmware, verified through digital signatures, can be loaded onto the device during the boot process. Once enabled, Secure Boot checks every piece of firmware against a cryptographic signature before execution, rejecting any unauthorized or modified code. This prevents malicious firmware from compromising the device’s operation and integrity. With Secure Boot activated, only firmware versions signed by a trusted authority, such as the device manufacturer, will be accepted, ensuring the device remains protected from unauthorized software modifications. **This is irreversible. Once enabled, it CANNOT be disabled.**
|
||||
|
||||
**IMPORTANT:** For users wishing to develop and compile custom firmware, a private-public key pair is essential. Activating Secure Boot requires users to generate and manage their own unique private-public key pair. The public key from this pair must be embedded into the device to validate all firmware. Firmware will not boot without a proper digital signature from this key pair. This means that users must sign all future firmware versions with their private key and embed the public key in the device to ensure compatibility.
|
||||
|
||||
### Secure Lock
|
||||
Secure Lock builds on Secure Boot by imposing an even stricter security model. Once activated, Secure Lock prevents any further installation of new boot keys, effectively locking the device to only run firmware that is authorized by the device's primary vendor—in this case, Pico Keys. In addition to preventing additional keys, Secure Lock disables debugging interfaces and puts additional safeguards in place to resist tampering and intrusion attempts. This ensures that the device operates exclusively with the original vendor’s firmware and resists unauthorized access, making it highly secure against external threats. **This is irreversible. Once enabled, it CANNOT be disabled.**
|
||||
|
||||
**IMPORTANT:** Activating Secure Lock not only enables Secure Boot but also invalidates all keys except the official Pico Key. This means that only firmware signed by Pico Key will be recognized, and custom code will no longer be allowed. Once enabled, the Pico Key device will run solely on the official firmware available on the website, with no option for generating or compiling new code for the device.
|
||||
|
||||
## Download
|
||||
Please, go to the Release page and download the UF2 file for your board.
|
||||
**If you own an ESP32-S3 board, go to [ESP32 Flasher](https://www.picokeys.com/esp32-flasher/) for flashing your Pico HSM.**
|
||||
|
||||
Note that UF2 files are shiped with a dummy VID/PID to avoid license issues (FEFF:FCFD). If you are planning to use it with OpenSC or similar, you should modify Info.plist of CCID driver to add these VID/PID or use the VID/PID patcher as follows:
|
||||
`./patch_vidpid.sh VID:PID input_hsm_file.uf2 output_hsm_file.uf2`
|
||||
If you own a Raspberry Pico (RP2040 or RP2350), go to [Download page](https://www.picokeys.com/getting-started/), select your vendor and model and download the proper firmware; or go to [Release page](https://www.github.com/polhenarejos/pico-hsm/releases/) and download the UF2 file for your board.
|
||||
|
||||
Note that UF2 files are shiped with a dummy VID/PID to avoid license issues (FEFF:FCFD). If you plan to use it with OpenSC or similar tools, you should modify Info.plist of CCID driver to add these VID/PID or use the [Pico Commissioner](https://www.picokeys.com/pico-commissioner/ "Pico Commissioner").
|
||||
|
||||
You can use whatever VID/PID (i.e., 234b:0000 from FISJ), but remember that you are not authorized to distribute the binary with a VID/PID that you do not own.
|
||||
|
||||
## Build
|
||||
Note that the pure-browser option [Pico Commissioner](https://www.picokeys.com/pico-commissioner/ "Pico Commissioner") is the most recommended.
|
||||
|
||||
## Build for Raspberry Pico
|
||||
Before building, ensure you have installed the toolchain for the Pico and the Pico SDK is properly located in your drive.
|
||||
|
||||
```
|
||||
git clone https://github.com/polhenarejos/pico-hsm
|
||||
git submodule update --init --recursive
|
||||
cd pico-hsm
|
||||
mkdir build
|
||||
cd build
|
||||
@@ -143,43 +214,79 @@ make
|
||||
```
|
||||
Note that `PICO_BOARD`, `USB_VID` and `USB_PID` are optional. If not provided, `pico` board and VID/PID `FEFF:FCFD` will be used.
|
||||
|
||||
After `make` ends, the binary file `pico_hsm.uf2` will be generated. Put your pico board into loading mode, by pushing `BOOTSEL` button while pluging on, and copy the UF2 to the new fresh usb mass storage Pico device. Once copied, the pico mass storage will be disconnected automatically and the pico board will reset with the new firmware. A blinking led will indicate the device is ready to work.
|
||||
Additionally, you can pass the `VIDPID=value` parameter to build the firmware with a known VID/PID. The supported values are:
|
||||
|
||||
- `NitroHSM`
|
||||
- `NitroFIDO2`
|
||||
- `NitroStart`
|
||||
- `NitroPro`
|
||||
- `Nitro3`
|
||||
- `Yubikey5`
|
||||
- `YubikeyNeo`
|
||||
- `YubiHSM`
|
||||
- `Gnuk`
|
||||
- `GnuPG`
|
||||
|
||||
After running `make`, the binary file `pico_hsm.uf2` will be generated. To load this onto your Pico board:
|
||||
|
||||
1. Put the Pico board into loading mode by holding the `BOOTSEL` button while plugging it in.
|
||||
2. Copy the `pico_hsm.uf2` file to the new USB mass storage device that appears.
|
||||
3. Once the file is copied, the Pico mass storage device will automatically disconnect, and the Pico board will reset with the new firmware.
|
||||
4. A blinking LED will indicate that the device is ready to work.
|
||||
|
||||
### Docker
|
||||
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=2.0.0 \
|
||||
--build-arg VERSION_MAJOR=5 \
|
||||
--build-arg VERSION_MINOR=0 \
|
||||
--build-arg PICO_BOARD=waveshare_rp2040_zero \
|
||||
--build-arg USB_VID=0xfeff \
|
||||
--build-arg USB_PID=0xfcfd \
|
||||
-t pico-hsm-builder .
|
||||
|
||||
sudo docker run \
|
||||
--name mybuild \
|
||||
-it pico-hsm-builder \
|
||||
ls -l /home/builduser/pico-hsm/build_release/pico_hsm.uf2
|
||||
|
||||
sudo docker cp mybuild:/home/builduser/pico-hsm/build_release/pico_hsm.uf2 .
|
||||
|
||||
sudo docker rm mybuild
|
||||
```
|
||||
|
||||
## Usage
|
||||
The firmware uploaded to the Pico contains a reader and a virtual smart card. It is like having a physical reader with an inserted SIM card.
|
||||
We recommend the use of [OpenSC](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:
|
||||
```
|
||||
The firmware uploaded to the Pico contains a reader and a virtual smart card, similar to having a physical reader with an inserted SIM card. We recommend using [OpenSC](http://github.com/opensc/opensc/ "OpenSC") to communicate with the reader. If OpenSC is not installed, you can download and build it or install the binaries for your system.
|
||||
|
||||
To ensure that the Pico is detected as an HSM, use the following command:
|
||||
```sh
|
||||
opensc-tool -an
|
||||
```
|
||||
It should return a text like the following:
|
||||
```
|
||||
It should return a text similar to:
|
||||
```sh
|
||||
Using reader with a card: Free Software Initiative of Japan Gnuk
|
||||
3b:fe:18:00:00:81:31:fe:45:80:31:81:54:48:53:4d:31:73:80:21:40:81:07:fa
|
||||
SmartCard-HSM
|
||||
```
|
||||
The name of the reader may vary if you modified the VID/PID.
|
||||
|
||||
For initialization and asymmetric operations, check [doc/usage.md](/doc/usage.md).
|
||||
For further details and operations, refer to the following documentation:
|
||||
|
||||
For signing and verification operations, check [doc/sign-verify.md](/doc/sign-verify.md).
|
||||
|
||||
For asymmetric encryption and decryption, check [doc/asymmetric-ciphering.md](/doc/asymmetric-ciphering.md).
|
||||
|
||||
For backup, restore and DKEK share management, check [doc/backup-and-restore.md](/doc/backup-and-restore.md).
|
||||
|
||||
For AES key generation, encryption and decryption, check [doc/aes.md](/doc/aes.md).
|
||||
|
||||
For 4096 bits RSA support, check [doc/scs3.md](/doc/scs3.md).
|
||||
|
||||
For storing and retrieving arbitrary data, check [doc/store_data.md](/doc/store_data.md).
|
||||
|
||||
For extra options, such as set/get real datetime or enable/disable press-to-confirm button, check [doc/extra_command.md](/doc/extra_command.md).
|
||||
|
||||
For Public Key Authentication, check [doc/public_key_authentication.md](/doc/public_key_authentication.md).
|
||||
- Initialization and Asymmetric Operations [doc/usage.md](/doc/usage.md)
|
||||
- Signing and Verification Operations [doc/sign-verify.md](/doc/sign-verify.md)
|
||||
- Asymmetric Encryption and Decryption [doc/asymmetric-ciphering.md](/doc/asymmetric-ciphering.md)
|
||||
- Backup, Restore, and DKEK Share Management [doc/backup-and-restore.md](/doc/backup-and-restore.md)
|
||||
- AES Key Generation, Encryption, and Decryption [doc/aes.md](/doc/aes.md)
|
||||
- 4096 Bits RSA Support [doc/scs3.md](/doc/scs3.md)
|
||||
- Storing and Retrieving Arbitrary Data [doc/store_data.md](/doc/store_data.md)
|
||||
- Extra Options (e.g., set/get real datetime, enable/disable press-to-confirm button [doc/extra_command.md](/doc/extra_command.md)
|
||||
- Public Key Authentication [doc/public_key_authentication.md](/doc/public_key_authentication.md)
|
||||
|
||||
## Operation time
|
||||
### Keypair generation
|
||||
Generating EC keys is almost instant. RSA keypair generation takes some time, specially for `3072` and `4096` bits.
|
||||
Generating EC keys is almost instant. RSA keypair generation takes some time, specially for `3072` and `4096` bits.
|
||||
|
||||
| RSA key length (bits) | Average time (seconds) |
|
||||
| :---: | :---: |
|
||||
@@ -197,14 +304,17 @@ Generating EC keys is almost instant. RSA keypair generation takes some time, sp
|
||||
| 4096 | 15 |
|
||||
|
||||
## Press-to-confirm button
|
||||
Raspberry Pico comes with the BOOTSEL button to load the firmware. When this firmware is running, the button can be used for other purposes. Pico HSM uses this button to confirm private/secret operations. This feature is optional and it shall be enabled. For more information, see [doc/extra_command.md](/doc/extra_command.md).
|
||||
The Raspberry Pico includes a BOOTSEL button used for loading firmware initially. Once the Pico HSM firmware is running, this button can be repurposed for additional functionalities. Specifically, the Pico HSM utilizes this button to confirm private and secret operations, a feature that is optional but highly recommended for enhanced security.
|
||||
|
||||
With this feature enabled, everytime that a private/secret key is loaded, the Pico HSM awaits for the user confirmation by pressing the BOOTSEL button. The Led of the Pico HSM will remain almost illuminated, turning off quickly once a second, indicating that the user must press the button to confirm the operation. Otherwise, the Pico HSM waits indefinitely. See [Led blink](#press-to-confirm) for a picture of the blinking sequence. When in this mode, the Pico HSM sends periodic timeout commands to the host to do not trigger the timeout operation.
|
||||
When enabled, each time a private or secret key operation is initiated, the Pico HSM enters a waiting state where it awaits user confirmation by pressing the BOOTSEL button. During this waiting period, the Pico HSM's LED remains mostly illuminated but blinks off briefly every second, signaling to the user to press the button for confirmation. If no action is taken, the Pico HSM will continue to wait indefinitely. This operation mode includes periodic timeout commands sent to the host to prevent the session from timing out prematurely.
|
||||
|
||||
This feature is an extra layer of security, as it requires the user intervention to sign or decrypt and it ensures that any application will use the Pico HSM without user awareness. However, it is not recommended for servers or other environments where operations are authomatized, since it requires a physical access to the Pico HSM to push the button.
|
||||
This feature adds an additional layer of security by requiring physical user intervention for sensitive operations such as signing or decrypting data. It mitigates risks associated with unauthorized applications or scripts using the Pico HSM without user awareness. However, it is not recommended for server environments or other automated settings where physical access to press the button may not be practical.
|
||||
|
||||
For more details on configuring and using this feature, refer to the [doc/extra_command.md](/doc/extra_command.md) document.
|
||||
|
||||
## Led blink
|
||||
Pico HSM uses the led to indicate the current status. Four states are available:
|
||||
|
||||
### Press to confirm
|
||||
The Led is almost on all the time. It goes off for 100 miliseconds every second.
|
||||
|
||||
@@ -227,18 +337,19 @@ While processing, the Pico HSM is busy and cannot receive additional commands un
|
||||
|
||||
## Driver
|
||||
|
||||
Pico HSM uses the `sc-hsm` driver provided by [OpenSC](https://github.com/OpenSC/OpenSC/ "OpenSC") or the `sc-hsm-embedded` driver provided by [CardContact](https://github.com/CardContact/sc-hsm-embedded "CardContact"). This driver utilizes the standardized PKCS#11 interface to communicate with the user and it can be used with many engines that accept PKCS#11 interface, such as OpenSSL, P11 library or pkcs11-tool.
|
||||
The Pico HSM uses either the `sc-hsm` driver from [OpenSC](https://github.com/OpenSC/OpenSC/) or the `sc-hsm-embedded` driver from [CardContact](https://github.com/CardContact/sc-hsm-embedded/) to interface with external applications. These drivers employ the standardized PKCS#11 interface, making it compatible with various cryptographic engines that support PKCS#11, such as OpenSSL, P11 library, or pkcs11-tool.
|
||||
|
||||
Pico HSM relies on PKCS#15 structure to store and manipulate the internal files (PINs, private keys, certificates, etc.) and directories. Therefore, it accepts the commands from `pkcs15-tool`. For instance, `pkcs15-tool -D` will list all elements stored in the Pico HSM.
|
||||
Internally, the Pico HSM organizes and manages its data using the PKCS#15 structure, which includes elements like PINs, private keys, and certificates. Commands can be issued to interact with these stored elements using tools such as `pkcs15-tool`. For example, `pkcs15-tool -D` lists all elements stored within the Pico HSM.
|
||||
|
||||
The way to communicate is exactly the same as with other cards, such as OpenPGP or similar.
|
||||
Communication with the Pico HSM follows the same protocols and methods used with other smart cards, such as OpenPGP cards or similar devices.
|
||||
|
||||
For an advanced usage, see the docs and examples.
|
||||
|
||||
Pico HSM also supports SCS3 tool for advanced use and multiple key domain. See [SCS3](/doc/scs3.md) for more information.
|
||||
For advanced usage scenarios, refer to the documentation and examples provided. Additionally, the Pico HSM supports the SCS3 tool for more sophisticated operations and includes features like multiple key domains. For detailed information on SCS3 usage, refer to [SCS3 documentation](/doc/scs3.md).
|
||||
|
||||
### Important
|
||||
OpenSC relies on PCSC driver, which reads a list (`Info.plist`) that contains a pair of VID/PID of supported readers. In order to be detectable, you must patch the UF2 binary (if you just downloaded from the [Release section](https://github.com/polhenarejos/pico-hsm/releases "Release section")) or configure the project with the proper VID/PID with `USB_VID` and `USB_PID` parameters in `CMake` (see [Build section](#build "Build section")). Note that you cannot distribute the patched/compiled binary if you do not own the VID/PID or have an explicit authorization.
|
||||
OpenSC relies on PCSC driver, which reads a list (`Info.plist`) that contains a pair of VID/PID of supported readers. In order to be detectable, you have several options:
|
||||
- Use `pico-hsm-tool.py` to modify VID/PID on-the-fly.
|
||||
- Use the pure-browser online [Pico Commissioner](https://www.picokeys.com/pico-commissioner/ "Pico Commissioner") that commissions the Pico Key on-the-fly without external tools.
|
||||
- Build and configure the project with the proper VID/PID with `USB_VID` and `USB_PID` parameters in `CMake` (see [Build section](#build "Build section")). Note that you cannot distribute the patched/compiled binary if you do not own the VID/PID or have an explicit authorization.
|
||||
|
||||
## Credits
|
||||
Pico HSM uses the following libraries or portion of code:
|
||||
|
||||
@@ -1,21 +1,108 @@
|
||||
#!/bin/bash
|
||||
|
||||
VERSION_MAJOR="2"
|
||||
VERSION_MINOR="6"
|
||||
VERSION_MAJOR="5"
|
||||
VERSION_MINOR="0-eddsa1"
|
||||
SUFFIX="${VERSION_MAJOR}.${VERSION_MINOR}"
|
||||
#if ! [[ -z "${GITHUB_SHA}" ]]; then
|
||||
# SUFFIX="${SUFFIX}.${GITHUB_SHA}"
|
||||
#fi
|
||||
|
||||
rm -rf release/*
|
||||
mkdir -p build_release
|
||||
mkdir -p release
|
||||
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 0xcb_helios \
|
||||
adafruit_feather_rp2040_usb_host \
|
||||
adafruit_feather_rp2040 \
|
||||
adafruit_itsybitsy_rp2040 \
|
||||
adafruit_kb2040 \
|
||||
adafruit_macropad_rp2040 \
|
||||
adafruit_qtpy_rp2040 \
|
||||
adafruit_trinkey_qt2040 \
|
||||
amethyst_fpga \
|
||||
archi \
|
||||
arduino_nano_rp2040_connect \
|
||||
cytron_maker_pi_rp2040 \
|
||||
datanoisetv_rp2040_dsp \
|
||||
eetree_gamekit_rp2040 \
|
||||
garatronic_pybstick26_rp2040 \
|
||||
gen4_rp2350_24 \
|
||||
gen4_rp2350_24ct \
|
||||
gen4_rp2350_24t \
|
||||
gen4_rp2350_28 \
|
||||
gen4_rp2350_28ct \
|
||||
gen4_rp2350_28t \
|
||||
gen4_rp2350_32 \
|
||||
gen4_rp2350_32ct \
|
||||
gen4_rp2350_32t \
|
||||
gen4_rp2350_35 \
|
||||
gen4_rp2350_35ct \
|
||||
gen4_rp2350_35t \
|
||||
hellbender_2350A_devboard \
|
||||
ilabs_challenger_rp2350_bconnect \
|
||||
ilabs_challenger_rp2350_wifi_ble \
|
||||
ilabs_opendec02 \
|
||||
melopero_perpetuo_rp2350_lora \
|
||||
melopero_shake_rp2040 \
|
||||
metrotech_xerxes_rp2040 \
|
||||
net8086_usb_interposer \
|
||||
nullbits_bit_c_pro \
|
||||
phyx_rick_tny_rp2350 \
|
||||
pi-plates_micropi \
|
||||
pico \
|
||||
pico_w \
|
||||
pico2 \
|
||||
pimoroni_badger2040 \
|
||||
pimoroni_interstate75 \
|
||||
pimoroni_keybow2040 \
|
||||
pimoroni_motor2040 \
|
||||
pimoroni_pga2040 \
|
||||
pimoroni_pga2350 \
|
||||
pimoroni_pico_plus2_rp2350 \
|
||||
pimoroni_picolipo_4mb \
|
||||
pimoroni_picolipo_16mb \
|
||||
pimoroni_picosystem \
|
||||
pimoroni_plasma2040 \
|
||||
pimoroni_plasma2350 \
|
||||
pimoroni_servo2040 \
|
||||
pimoroni_tiny2040 \
|
||||
pimoroni_tiny2040_2mb \
|
||||
pimoroni_tiny2350 \
|
||||
pololu_3pi_2040_robot \
|
||||
pololu_zumo_2040_robot \
|
||||
seeed_xiao_rp2040 \
|
||||
seeed_xiao_rp2350 \
|
||||
solderparty_rp2040_stamp \
|
||||
solderparty_rp2040_stamp_carrier \
|
||||
solderparty_rp2040_stamp_round_carrier \
|
||||
solderparty_rp2350_stamp_xl \
|
||||
solderparty_rp2350_stamp \
|
||||
sparkfun_micromod \
|
||||
sparkfun_promicro \
|
||||
sparkfun_promicro_rp2350 \
|
||||
sparkfun_thingplus \
|
||||
switchscience_picossci2_conta_base \
|
||||
switchscience_picossci2_dev_board \
|
||||
switchscience_picossci2_micro \
|
||||
switchscience_picossci2_rp2350_breakout \
|
||||
switchscience_picossci2_tiny \
|
||||
tinycircuits_thumby_color_rp2350 \
|
||||
vgaboard \
|
||||
waveshare_rp2040_lcd_0.96 \
|
||||
waveshare_rp2040_lcd_1.28 \
|
||||
waveshare_rp2040_one \
|
||||
waveshare_rp2040_plus_4mb \
|
||||
waveshare_rp2040_plus_16mb \
|
||||
waveshare_rp2040_zero \
|
||||
weact_studio_rp2040_2mb \
|
||||
weact_studio_rp2040_4mb \
|
||||
weact_studio_rp2040_8mb \
|
||||
weact_studio_rp2040_16mb \
|
||||
wiznet_w5100s_evb_pico
|
||||
do
|
||||
rm -rf *
|
||||
PICO_SDK_PATH=~/Devel/pico/pico-sdk cmake .. -DPICO_BOARD=$board
|
||||
make -kj20
|
||||
mv pico_hsm.uf2 ../release/pico_hsm_$board-$VERSION_MAJOR.$VERSION_MINOR.uf2
|
||||
|
||||
PICO_SDK_PATH="${PICO_SDK_PATH:-../../pico-sdk}" cmake .. -DPICO_BOARD=$board
|
||||
make -j`nproc`
|
||||
mv pico_hsm.uf2 ../release/pico_hsm_$board-$SUFFIX.uf2
|
||||
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
|
||||
116
burn-cvcerts.py
116
burn-cvcerts.py
@@ -1,116 +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
|
||||
import ssl
|
||||
|
||||
ssl._create_default_https_context = ssl._create_unverified_context
|
||||
|
||||
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
|
||||
]
|
||||
|
||||
cvca = [
|
||||
0x7f, 0x21, 0x82, 0x01, 0x65, 0x7f, 0x4e, 0x82, 0x01, 0x2d, 0x5f, 0x29,
|
||||
0x01, 0x00, 0x42, 0x0e, 0x45, 0x53, 0x43, 0x56, 0x43, 0x41, 0x48, 0x53,
|
||||
0x4d, 0x30, 0x30, 0x30, 0x30, 0x31, 0x7f, 0x49, 0x81, 0xdd, 0x06, 0x0a,
|
||||
0x04, 0x00, 0x7f, 0x00, 0x07, 0x02, 0x02, 0x02, 0x02, 0x03, 0x81, 0x18,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0x82, 0x18, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xfe, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
|
||||
0xff, 0xfc, 0x83, 0x18, 0x64, 0x21, 0x05, 0x19, 0xe5, 0x9c, 0x80, 0xe7,
|
||||
0x0f, 0xa7, 0xe9, 0xab, 0x72, 0x24, 0x30, 0x49, 0xfe, 0xb8, 0xde, 0xec,
|
||||
0xc1, 0x46, 0xb9, 0xb1, 0x84, 0x31, 0x04, 0x18, 0x8d, 0xa8, 0x0e, 0xb0,
|
||||
0x30, 0x90, 0xf6, 0x7c, 0xbf, 0x20, 0xeb, 0x43, 0xa1, 0x88, 0x00, 0xf4,
|
||||
0xff, 0x0a, 0xfd, 0x82, 0xff, 0x10, 0x12, 0x07, 0x19, 0x2b, 0x95, 0xff,
|
||||
0xc8, 0xda, 0x78, 0x63, 0x10, 0x11, 0xed, 0x6b, 0x24, 0xcd, 0xd5, 0x73,
|
||||
0xf9, 0x77, 0xa1, 0x1e, 0x79, 0x48, 0x11, 0x85, 0x18, 0xff, 0xff, 0xff,
|
||||
0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x99, 0xde, 0xf8,
|
||||
0x36, 0x14, 0x6b, 0xc9, 0xb1, 0xb4, 0xd2, 0x28, 0x31, 0x86, 0x31, 0x04,
|
||||
0x08, 0x8f, 0xcd, 0xfc, 0xce, 0x87, 0xed, 0xd2, 0x85, 0x92, 0x06, 0x15,
|
||||
0xe6, 0x51, 0xd7, 0x64, 0x52, 0xd8, 0x57, 0xec, 0xbb, 0x40, 0x8c, 0x32,
|
||||
0x7a, 0xdb, 0x48, 0xa2, 0xa5, 0x14, 0xc1, 0xc9, 0xbd, 0x77, 0xcc, 0x97,
|
||||
0x83, 0x60, 0x7a, 0x74, 0x14, 0x93, 0xa7, 0x42, 0x74, 0x4a, 0xd1, 0x73,
|
||||
0x87, 0x01, 0x01, 0x5f, 0x20, 0x0e, 0x45, 0x53, 0x43, 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,
|
||||
0xc0, 0x00, 0x00, 0x00, 0x04, 0x5f, 0x25, 0x06, 0x02, 0x02, 0x00, 0x03,
|
||||
0x02, 0x06, 0x5f, 0x24, 0x06, 0x03, 0x00, 0x01, 0x02, 0x03, 0x01, 0x5f,
|
||||
0x37, 0x30, 0x72, 0x97, 0x77, 0x76, 0x64, 0xb6, 0x0c, 0x57, 0xa2, 0xc4,
|
||||
0x5e, 0x7b, 0xfd, 0x12, 0xe5, 0x20, 0x14, 0x3e, 0xde, 0x90, 0x38, 0xbf,
|
||||
0xb3, 0x02, 0x73, 0x91, 0x06, 0xf2, 0x73, 0x0d, 0x76, 0x06, 0x65, 0xd7,
|
||||
0x46, 0x49, 0x91, 0x0c, 0x51, 0x90, 0x89, 0x84, 0x8d, 0x4f, 0xb6, 0xe5,
|
||||
0x13, 0x40
|
||||
]
|
||||
|
||||
s = '#ifndef _CVCERTS_H_\n#define _CVCERTS_H_\n'
|
||||
s += print_var(cvca,'cvca')
|
||||
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()
|
||||
@@ -54,4 +54,4 @@ Using decrypt algorithm AES-CBC
|
||||
This is a text.
|
||||
```
|
||||
|
||||
AES-CBC it is a block operation and it requires an input size multiple of 16 bytes. Thus, for a trivial data, a padding operation has to be performed beforehand.
|
||||
AES-CBC it is a block operation and it requires an input size multiple of 16 bytes. Thus, for a trivial data, a padding operation has to be performed beforehand.
|
||||
|
||||
@@ -24,12 +24,12 @@ This algorithm uses the PKCSv1.5 padding. It is considered deprecated and insecu
|
||||
First, we encrypt the data with the public key:
|
||||
|
||||
```
|
||||
$ openssl rsautl -encrypt -inkey 1.pub -in data -pubin -out data.crypt
|
||||
$ openssl rsautl -encrypt -inkey 1.pub -in data -pubin -out data.crypt
|
||||
```
|
||||
|
||||
Then, we decrypt with the private key inside the Pico HSM:
|
||||
|
||||
```
|
||||
```
|
||||
$ pkcs11-tool --id 1 --pin 648219 --decrypt --mechanism RSA-PKCS -i data.crypt
|
||||
Using slot 0 with a present token (0x0)
|
||||
Using decrypt algorithm RSA-PKCS
|
||||
@@ -54,7 +54,7 @@ $ openssl rsautl -encrypt -inkey 1.pub -in data_pad -pubin -out data.crypt -raw
|
||||
|
||||
Then, we decrypt with the private key inside the Pico HSM:
|
||||
```
|
||||
$ cat data.crypt|pkcs11-tool --id 4 --pin 648219 --decrypt --mechanism RSA-X-509
|
||||
$ cat data.crypt|pkcs11-tool --id 4 --pin 648219 --decrypt --mechanism RSA-X-509
|
||||
Using slot 0 with a present token (0x0)
|
||||
Using decrypt algorithm RSA-X-509
|
||||
This is a test string. Be safe, be secure.
|
||||
@@ -78,7 +78,7 @@ This is a test string. Be safe, be secure.
|
||||
```
|
||||
|
||||
## ECDH-DERIVE
|
||||
ECC keys do not allow ciphering operations. Instead, the ECDH scheme provides a mechanism to exchange a shared symmetric key without transmitting it to the remote part. The shared key is composed by multiplying the local private key and the remote public key.
|
||||
ECC keys do not allow ciphering operations. Instead, the ECDH scheme provides a mechanism to exchange a shared symmetric key without transmitting it to the remote part. The shared key is composed by multiplying the local private key and the remote public key.
|
||||
|
||||
First, we create the remote part, Bob, by generating an ECC keypair and getting the public key:
|
||||
```
|
||||
@@ -104,8 +104,8 @@ No output is displayed if both are equal.
|
||||
|
||||
You can also view the contents of both keys:
|
||||
```
|
||||
$ xxd -p bob-mine.der
|
||||
$ xxd -p bob-mine.der
|
||||
9874558aefa9d92cc051e5da6d1753987e5314925d6d78bf
|
||||
$ xxd -p mine-bob.der
|
||||
$ xxd -p mine-bob.der
|
||||
9874558aefa9d92cc051e5da6d1753987e5314925d6d78bf
|
||||
```
|
||||
|
||||
@@ -29,15 +29,15 @@ symbols.
|
||||
Please keep the generated DKEK share file in a safe location. We also recommend to keep a
|
||||
paper printout, in case the electronic version becomes unavailable. A printable version
|
||||
of the file can be generated using "openssl base64 -in <filename>".
|
||||
Enter password to encrypt DKEK share :
|
||||
Enter password to encrypt DKEK share :
|
||||
|
||||
Please retype password to confirm :
|
||||
Please retype password to confirm :
|
||||
|
||||
Enciphering DKEK share, please wait...
|
||||
DKEK share created and saved to dkek.pbe
|
||||
```
|
||||
|
||||
The generated file `dkek.pbe` contains the DKEK. Technically, it contains a share. But if a device is initialized with one share, it is equivalent to contain the full DKEK.
|
||||
The generated file `dkek.pbe` contains the DKEK. Technically, it contains a share. But if a device is initialized with one share, it is equivalent to contain the full DKEK.
|
||||
|
||||
Keep these file in a safe place. If this file is lost, you can export the private keys but you will not be able to import into another device or in the same device if it is initialized again.
|
||||
|
||||
@@ -52,7 +52,7 @@ At this moment, the Pico HSM expects the DKEK. It is loaded with the following c
|
||||
```
|
||||
$ sc-hsm-tool --import-dkek-share dkek.pbe
|
||||
Using reader with a card: Free Software Initiative of Japan Gnuk
|
||||
Enter password to decrypt DKEK share :
|
||||
Enter password to decrypt DKEK share :
|
||||
|
||||
Deciphering DKEK share, please wait...
|
||||
DKEK share imported
|
||||
@@ -81,7 +81,7 @@ And finally, all are imported one after the other, without special order:
|
||||
```
|
||||
$ sc-hsm-tool --import-dkek-share dkek-share-1.pbe
|
||||
Using reader with a card: Free Software Initiative of Japan Gnuk
|
||||
Enter password to decrypt DKEK share :
|
||||
Enter password to decrypt DKEK share :
|
||||
|
||||
Deciphering DKEK share, please wait...
|
||||
DKEK share imported
|
||||
@@ -90,7 +90,7 @@ DKEK import pending, 2 share(s) still missing
|
||||
|
||||
$ sc-hsm-tool --import-dkek-share dkek-share-2.pbe
|
||||
Using reader with a card: Free Software Initiative of Japan Gnuk
|
||||
Enter password to decrypt DKEK share :
|
||||
Enter password to decrypt DKEK share :
|
||||
|
||||
Deciphering DKEK share, please wait...
|
||||
DKEK share imported
|
||||
@@ -99,7 +99,7 @@ DKEK import pending, 1 share(s) still missing
|
||||
|
||||
$ sc-hsm-tool --import-dkek-share dkek-share-1.pbe
|
||||
Using reader with a card: Free Software Initiative of Japan Gnuk
|
||||
Enter password to decrypt DKEK share :
|
||||
Enter password to decrypt DKEK share :
|
||||
|
||||
Deciphering DKEK share, please wait...
|
||||
DKEK share imported
|
||||
@@ -110,7 +110,7 @@ DKEK key check value : 4B7DA256ACD4EF62
|
||||
### DKEK n-of-m threshold scheme
|
||||
This scheme provides an extra level of flexiblity, as not all custodians are necessary to import the DKEK share. For instance, with the previous schemes, if a custodian gets unavailable, the initialization will block until the missing custodian can got to finalize the initialization.
|
||||
|
||||
With n-of-m threshold scheme, it flexibilizes the number of required custodians to reduce failure points. If a share is lost, the DKEK can still be recovered without major implications.
|
||||
With n-of-m threshold scheme, it flexibilizes the number of required custodians to reduce failure points. If a share is lost, the DKEK can still be recovered without major implications.
|
||||
|
||||
This scheme is not a replacement of DKEK shares. Instead, it splits the DKEK share encryption password amongst the n-of-m threshold scheme. For instance, if you define 2 shares and a scheme of 3-of-5 threshold for each share, it will imply 10 different custodians, where 6 are necessary to load both shares. You can also mix one share with traditional passphrase and the other with the n-of-m threshold scheme.
|
||||
|
||||
@@ -123,7 +123,7 @@ Using reader with a card:Free Software Initiative of Japan Gnuk
|
||||
The DKEK will be enciphered using a randomly generated 64 bit password.
|
||||
This password is split using a (3-of-5) threshold scheme.
|
||||
|
||||
Please keep the generated and encrypted DKEK file in a safe location. We also recommend
|
||||
Please keep the generated and encrypted DKEK file in a safe location. We also recommend
|
||||
to keep a paper printout, in case the electronic version becomes unavailable. A printable version
|
||||
of the file can be generated using "openssl base64 -in <filename>".
|
||||
|
||||
@@ -191,7 +191,7 @@ Private RSA Key [Certificate]
|
||||
...
|
||||
```
|
||||
|
||||
Note that `Key ref` and `ID` may be different. Whilst different keys may share the same `ID` (highly discouraged), the `Key ref` is a value internally computed and unique.
|
||||
Note that `Key ref` and `ID` may be different. Whilst different keys may share the same `ID` (highly discouraged), the `Key ref` is a value internally computed and unique.
|
||||
|
||||
To export and wrap the private key:
|
||||
|
||||
@@ -199,10 +199,10 @@ To export and wrap the private key:
|
||||
$ sc-hsm-tool --wrap-key wrap-key.bin --key-reference 1 --pin 648219
|
||||
```
|
||||
|
||||
A file named `wrap-key.bin` is created with the private key encrypted securely with the DKEK.
|
||||
A file named `wrap-key.bin` is created with the private key encrypted securely with the DKEK.
|
||||
|
||||
## Restore
|
||||
To restore the wraped key, a device initialized with the same DKEK is mandatory.
|
||||
To restore the wraped key, a device initialized with the same DKEK is mandatory.
|
||||
|
||||
To unwrap the key:
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# Extra command
|
||||
|
||||
Pico HSM supports a customized extra command to use with different options. Since the drivers in the market do not support the following features, a raw APDU command shall be sent.
|
||||
Pico HSM supports a customized extra command to use with different options. Since the drivers in the market do not support the following features, a raw APDU command shall be sent.
|
||||
|
||||
To send a raw APDU command, `opensc-tool -s <APDU>` can be used. The `APDU` parameter is a string of hexadecimal numbers and it takes the following form:
|
||||
```
|
||||
@@ -27,7 +27,7 @@ For example, to obtain the current datetime:
|
||||
```
|
||||
$ opensc-tool -s 80640A0008
|
||||
Using reader with a card: Free Software Initiative of Japan Gnuk
|
||||
Sending: 80 64 0A 00 08
|
||||
Sending: 80 64 0A 00 08
|
||||
Received (SW1=0x90, SW2=0x00):
|
||||
07 E6 04 06 03 13 29 1E ......).
|
||||
```
|
||||
@@ -49,7 +49,7 @@ To set the reference datetime, a datetime string must be provided. For example:
|
||||
```
|
||||
$ opensc-tool -s 80640A000807E6040603132917
|
||||
Using reader with a card: Free Software Initiative of Japan Gnuk
|
||||
Sending: 80 64 0A 00 08 07 E6 04 06 03 13 29 17
|
||||
Sending: 80 64 0A 00 08 07 E6 04 06 03 13 29 17
|
||||
Received (SW1=0x90, SW2=0x00)
|
||||
```
|
||||
|
||||
@@ -72,7 +72,7 @@ This feature is disabled by default but can be enabled rapidly by setting the LS
|
||||
```
|
||||
$ opensc-tool -s 806406000101
|
||||
Using reader with a card: Free Software Initiative of Japan Gnuk
|
||||
Sending: 80 64 06 00 01 01
|
||||
Sending: 80 64 06 00 01 01
|
||||
Received (SW1=0x90, SW2=0x00)
|
||||
```
|
||||
|
||||
@@ -99,7 +99,7 @@ This feature is disabled by default but can be enabled rapidly by setting the 2n
|
||||
```
|
||||
$ opensc-tool -s 806406000102
|
||||
Using reader with a card: Free Software Initiative of Japan Gnuk
|
||||
Sending: 80 64 06 00 01 01
|
||||
Sending: 80 64 06 00 01 01
|
||||
Received (SW1=0x90, SW2=0x00)
|
||||
```
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ On a secondary device, generate a private key, on the ECC 256 bits (`brainpoolP2
|
||||
|
||||
<img width="1037" src="https://user-images.githubusercontent.com/55573252/173353764-4620ece4-0d82-4a23-a153-99bf912621a7.png">
|
||||
|
||||
Once finished, export the public key.
|
||||
Once finished, export the public key.
|
||||
|
||||
<img width="350" src="https://user-images.githubusercontent.com/55573252/173353732-63f40572-a42f-4e5c-a9ab-6e52a083956b.png">
|
||||
|
||||
@@ -64,17 +64,17 @@ From now on, you have full access and can operate normally with the primary devi
|
||||
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.
|
||||
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.
|
||||
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.
|
||||
**Note:** do not import any DKEK share or DKEK operation before PKA and PIN setup.
|
||||
|
||||
### With OpenSC
|
||||
|
||||
@@ -84,9 +84,9 @@ Use the following command (or similar), which accepts the use of PIN parameter *
|
||||
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.
|
||||
and PKA and PIN are enabled, jointly with DKEK protection.
|
||||
|
||||
### With SCS3
|
||||
### 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:
|
||||
|
||||
@@ -94,4 +94,4 @@ Unfortunately, SCS3 does not allow to initialize the device with PKA and PIN at
|
||||
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.
|
||||
When done, the device will be configured with PIN **and** PKA.
|
||||
|
||||
23
doc/scs3.md
23
doc/scs3.md
@@ -4,16 +4,16 @@ SCS3 tool is a specific tool developed by CardContact to manage HSM. Thanks to i
|
||||
|
||||
- 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").
|
||||
|
||||
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.
|
||||
|
||||
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:
|
||||
@@ -22,26 +22,27 @@ Therefore, the whole variable becomes:
|
||||
SmartCardHSM.rootCerts = {
|
||||
DESRCACC100001: new CVC(new ByteString("7F218201B47F4E82016C5F290100420E44455352434143433130303030317F4982011D060A04007F000702020202038120A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E537782207D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9832026DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B68441048BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F0469978520A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A78641046D025A8026CDBA245F10DF1B72E9880FFF746DAB40A43A3D5C6BEBF27707C30F6DEA72430EE3287B0665C1EAA6EAA4FA26C46303001983F82BD1AA31E03DA0628701015F200E44455352434143433130303030317F4C10060B2B0601040181C31F0301015301C05F25060102010100095F24060302010100085F37409DBB382B1711D2BAACB0C623D40C6267D0B52BA455C01F56333DC9554810B9B2878DAF9EC3ADA19C7B065D780D6C9C3C2ECEDFD78DEB18AF40778ADF89E861CA", HEX)),
|
||||
UTSRCACC100001: new CVC(new ByteString("7F218201B47F4E82016C5F290100420E55545352434143433130303030317F4982011D060A04007F000702020202038120A9FB57DBA1EEA9BC3E660A909D838D726E3BF623D52620282013481D1F6E537782207D5A0975FC2C3057EEF67530417AFFE7FB8055C126DC5C6CE94A4B44F330B5D9832026DC5C6CE94A4B44F330B5D9BBD77CBF958416295CF7E1CE6BCCDC18FF8C07B68441048BD2AEB9CB7E57CB2C4B482FFC81B7AFB9DE27E1E3BD23C23A4453BD9ACE3262547EF835C3DAC4FD97F8461A14611DC9C27745132DED8E545C1D54C72F0469978520A9FB57DBA1EEA9BC3E660A909D838D718C397AA3B561A6F7901E0E82974856A7864104A041FEB2FD116B2AD19CA6B7EACD71C9892F941BB88D67DCEEC92501F070011957E22122BA6C2CF5FF02936F482E35A6129CCBBA8E9383836D3106879C408EF08701015F200E55545352434143433130303030317F4C10060B2B0601040181C31F0301015301C05F25060102010100095F24060302010100085F3740914DD0FA00615C44048D1467435400423A4AD1BD37FD98D6DE84FD8037489582325C72956D4FDFABC6EDBA48184A754F37F1BE5142DD1C27D66569308CE19AAF", HEX)),
|
||||
ESCVCAHSM00001: new CVC(new ByteString("7F218201657F4E82012D5F290100420E45534356434148534D30303030317F4981DD060A04007F000702020202038118FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFF8218FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEFFFFFFFFFFFFFFFC831864210519E59C80E70FA7E9AB72243049FEB8DEECC146B9B1843104188DA80EB03090F67CBF20EB43A18800F4FF0AFD82FF101207192B95FFC8DA78631011ED6B24CDD573F977A11E7948118518FFFFFFFFFFFFFFFFFFFFFFFF99DEF836146BC9B1B4D22831863104088FCDFCCE87EDD285920615E651D76452D857ECBB408C327ADB48A2A514C1C9BD77CC9783607A741493A742744AD1738701015F200E45534356434148534D30303030317F4C12060904007F0007030102025305C0000000045F25060202000302065F24060300010203015F37307297777664B60C57A2C45E7BFD12E520143EDE9038BFB302739106F2730D760665D74649910C519089848D4FB6E51340", HEX))
|
||||
ESPICOHSMCA00001: new CVC(new ByteString("7F218201BA7F4E8201725F290100421045535049434F48534D434130303030317F4982011D060A04007F000702020202038120FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFF8220FFFFFFFF00000001000000000000000000000000FFFFFFFFFFFFFFFFFFFFFFFC83205AC635D8AA3A93E7B3EBBD55769886BC651D06B0CC53B0F63BCE3C3E27D2604B8441046B17D1F2E12C4247F8BCE6E563A440F277037D812DEB33A0F4A13945D898C2964FE342E2FE1A7F9B8EE7EB4A7C0F9E162BCE33576B315ECECBB6406837BF51F58520FFFFFFFF00000000FFFFFFFFFFFFFFFFBCE6FAADA7179E84F3B9CAC2FC6325518641046A82C0A4FEAF41D6A1336AE7E992D81AD4F827929145DD0D777E1AB63D7E3325C8F7DAC0F74B6EAE13A72F6366777EC133AC5C28F456868E5F2C315044EB54EF8701015F201045535049434F48534D434130303030317F4C12060904007F0007030102025305C0000000005F25060202000801085F24060203000801085F3740601E974F57DDE060875FE6121AEF5BC02E10FC655311C7A32CA822FD18E53A80298EDC56E0D5EBF38FB470DC12987B1600AE91A0ADB5B22C4D80080782E278AD", HEX))
|
||||
}
|
||||
```
|
||||
|
||||
Similarly, replace the line `1531` in file `scs3/keymanager/keymanager.js` with:
|
||||
|
||||
```
|
||||
assert(devcert.verifyWith(this.crypto, dicacert.getPublicKey(SmartCardHSM.rootCerts.ESCVCAHSM00001.getPublicKey()), dicacert.getPublicKeyOID()));
|
||||
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/8890050/scs3.patch.txt) can be applied.
|
||||
|
||||
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");
|
||||
|
||||
SmartCard-HSM Version 1.6 on JCOP Free memory 217104 byte
|
||||
Issuer Certificate : CVC id-AT DV (official domestic) CAR=ESCVCAHSM00001 CHR=ESDVCAHSM00001 CED=27 / de març / 2022 CXD=31 / de desembre / 2025
|
||||
Device Certificate : CVC id-AT Terminal CAR=ESDVCAHSM00001 CHR=ESTERMHSM00001 CED=27 / de març / 2022 CXD=31 / de desembre / 2023
|
||||
Default Key Domain : 0F89B400975EDD2D425ABF85F2FBD318779B3D85475E65D4
|
||||
SmartCard-HSM Version 2.6 on JCOP Free memory 215512 byte
|
||||
Issuer Certificate : CVC id-AT DV (official domestic) CAR=ESPICOHSMCA00001 CHR=ESPICOHSMDV00001 CED=18 / d’agost / 2022 CXD=14 / de juny / 2023
|
||||
Device Certificate : CVC id-AT Terminal CAR=ESPICOHSMDV00001 CHR=ESPICOHSMTRYZRGW CED=22 / d’agost / 2022 CXD=22 / d’agost / 2023
|
||||
Default Key Domain : 223CD8D8F794889AC163305881BF8C04960BBB8658120491F1C0601F6BF97183
|
||||
-------------------------------------------------------------------
|
||||
Please right-click on nodes in the outline to see possible actions.
|
||||
For most operations you will need to authenticate first using a
|
||||
@@ -60,7 +61,7 @@ It can be executed in a Terminal via
|
||||
```
|
||||
## 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.
|
||||
|
||||
Note that the DKEK share shall be available before the import. In this way, all custodians must be present during the import process, since they will have to introduce their respective DKEK.
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
# Sign and verify
|
||||
|
||||
Pico HSM supports in place signature of arbitrary data. It supports the following algorithms:
|
||||
* RSA-PKCS
|
||||
* RSA-PKCS
|
||||
* RSA-X-509
|
||||
* SHA1-RSA-PKCS
|
||||
* SHA256-RSA-PKCS
|
||||
@@ -32,7 +32,7 @@ $ openssl rsa -inform DER -outform PEM -in 1.der -pubin > 1.pub
|
||||
At this moment, you are able to verify with the public key in `1.pub`. The signature is computed inside the Pico HSM with the private key. It never leaves the device.
|
||||
|
||||
## RSA-PKCS
|
||||
This algorithm is used to sign raw data.
|
||||
This algorithm is used to sign raw data.
|
||||
|
||||
To sign the data:
|
||||
```
|
||||
@@ -91,7 +91,7 @@ This algorithm uses the RSA-PKCS with PSS salt to randomize the signature. Pico
|
||||
To sign the data:
|
||||
```
|
||||
$ pkcs11-tool --id 1 --sign --pin 648219 --mechanism RSA-PKCS-PSS -i data.sha1 -o data.sig
|
||||
```
|
||||
```
|
||||
|
||||
To verify the signature:
|
||||
```
|
||||
@@ -105,7 +105,7 @@ This algorithm takes the file as the input and sends its hash for signing with t
|
||||
To sign the data:
|
||||
```
|
||||
$ pkcs11-tool --id 1 --sign --pin 648219 --mechanism SHA1-RSA-PKCS-PSS -i data -o data.sig
|
||||
```
|
||||
```
|
||||
|
||||
To verify the signature:
|
||||
```
|
||||
@@ -118,14 +118,14 @@ This is a raw ECDSA signature, which is usually used to sign a hashed message. `
|
||||
|
||||
To sign the data:
|
||||
```
|
||||
$ pkcs11-tool --id 11 --sign --pin 648219 --mechanism ECDSA -i data.sha1 -o data.sig --signature-format openssl
|
||||
$ pkcs11-tool --id 11 --sign --pin 648219 --mechanism ECDSA -i data.sha1 -o data.sig --signature-format openssl
|
||||
Using slot 0 with a present token (0x0)
|
||||
Using signature algorithm ECDSA
|
||||
```
|
||||
|
||||
To verify the signature:
|
||||
```
|
||||
$ openssl pkeyutl -verify -pubin -inkey 11.pub -in data.sha1 -sigfile data.sig
|
||||
$ openssl pkeyutl -verify -pubin -inkey 11.pub -in data.sha1 -sigfile data.sig
|
||||
Signature Verified Successfully
|
||||
```
|
||||
|
||||
@@ -143,6 +143,6 @@ Using signature algorithm ECDSA-SHA256
|
||||
|
||||
The signature is verified with the hash:
|
||||
```
|
||||
$ openssl pkeyutl -verify -pubin -inkey 11.pub -in data.sha1 -sigfile data.sig
|
||||
$ openssl pkeyutl -verify -pubin -inkey 11.pub -in data.sha1 -sigfile data.sig
|
||||
Signature Verified Successfully
|
||||
```
|
||||
|
||||
@@ -9,7 +9,7 @@ Before writting a file into the Pico HSM, we generate the data file with the fol
|
||||
|
||||
```
|
||||
$ echo 'Pico HSM is awesome!' > test
|
||||
```
|
||||
```
|
||||
|
||||
Then, we can store the data file with the following command:
|
||||
|
||||
@@ -43,7 +43,7 @@ Always provide a unique `--label`, as it will be used to index and reference the
|
||||
To view the stored file, we can use the following command with the same label we employed:
|
||||
|
||||
```
|
||||
$ pkcs11-tool --read-object --type data --label 'test1'
|
||||
$ pkcs11-tool --read-object --type data --label 'test1'
|
||||
Using slot 0 with a present token (0x0)
|
||||
Pico HSM is awesome!
|
||||
```
|
||||
@@ -98,7 +98,7 @@ Data object 'test1'
|
||||
applicationName: test1
|
||||
Path: e82b0601040181c31f0201::cf00
|
||||
Data (21 bytes): 5069636F2048534D20697320617765736F6D65210A
|
||||
|
||||
|
||||
Data object 'test2'
|
||||
applicationName: test2
|
||||
Path: e82b0601040181c31f0201::cd01
|
||||
|
||||
24
doc/usage.md
24
doc/usage.md
@@ -1,7 +1,7 @@
|
||||
# Usage
|
||||
|
||||
## Tools
|
||||
We use multiple tools and PKCS#11 drivers and modules, depending on the purpose.
|
||||
We use multiple tools and PKCS#11 drivers and modules, depending on the purpose.
|
||||
* **pkcs11-tool**: from OpenSC. It interfaces with the HSM via PKCS#11 interface. It supports different drivers and modules.
|
||||
* **sc-tool**: an alias of pkcs11-tool with the sc-hsm-embedded module. It is mainly used for AES management and it is defined as:
|
||||
```
|
||||
@@ -22,20 +22,20 @@ init=0
|
||||
PIN=648219
|
||||
```
|
||||
`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.
|
||||
|
||||
[^1]: `openssl version -a` will return the `OPENSSLDIR`, which contains `openssl.cnf` file and `ENGINESDIR`, which contains the p11 engine.
|
||||
|
||||
## Initialization
|
||||
The first step is to initialize the HSM:
|
||||
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 tools/pico-hsm-tool.py --pin 648219 initialize --so-pin 57621880
|
||||
```
|
||||
The PIN number is used to manage all private keys in the device. It supports three attemps. After the third PIN failure, it gets blocked.
|
||||
The PIN number is used to manage all private keys in the device. It supports three attemps. After the third PIN failure, it gets blocked.
|
||||
The PIN accepts from 6 to 16 characters.
|
||||
|
||||
The SO-PIN is used to unblock the PIN. It accepts 15 attemps. After 15 failed attempts, the device will be completely blocked and will be necessary to initialize again, erasing all private keys and losing the access. Therefore, keep the SO-PIN in a safe place.
|
||||
The SO-PIN is used to unblock the PIN. It accepts 15 attemps. After 15 failed attempts, the device will be completely blocked and will be necessary to initialize again, erasing all private keys and losing the access. Therefore, keep the SO-PIN in a safe place.
|
||||
The SO-PIN is always 16 hexadecimal characters.
|
||||
|
||||
## PIN and SO-PIN management
|
||||
@@ -51,7 +51,7 @@ $ pkcs11-tool --login --pin 648219 --change-pin --new-pin 123456
|
||||
|
||||
To unblock the PIN:
|
||||
```
|
||||
$ pkcs11-tool --login --login-type so --so-pin=3537363231383830 --init-pin --new-pin=648219
|
||||
$ pkcs11-tool --login --login-type so --so-pin 3537363231383830 --init-pin --new-pin 648219
|
||||
```
|
||||
|
||||
## Keypair generation
|
||||
@@ -62,7 +62,7 @@ To generate a RSA 2048 bits, use the following command:
|
||||
$ pkcs11-tool -l --pin 648219 --keypairgen --key-type rsa:2048 --id 1 --label "RSA2K"
|
||||
Using slot 0 with a present token (0x0)
|
||||
Key pair generated:
|
||||
Private Key Object; RSA
|
||||
Private Key Object; RSA
|
||||
label: RSA2K
|
||||
ID: 1
|
||||
Usage: decrypt, sign
|
||||
@@ -77,7 +77,7 @@ The ID parameter is an internal hexadecimal number for easy identification. The
|
||||
|
||||
Pico HSM accepts RSA of 1024 (`rsa:1024`), 2048 (`rsa:2048`) and 4096 bits (`rsa:4096`).
|
||||
|
||||
**Caution**: RSA 2048 bits may take more than 20 seconds. RSA 4096 bits may take more than 20 minutes. The Pico HSM will work as normally and neither the HSM nor the host will block. But, in the meantime, the Pico HSM will not accept any command.
|
||||
**Caution**: RSA 2048 bits may take more than 20 seconds. RSA 4096 bits may take more than 20 minutes. The Pico HSM will work as normally and neither the HSM nor the host will block. But, in the meantime, the Pico HSM will not accept any command.
|
||||
An alternative is to generate the private key locally and import it to the HSM. This approach, however, is less secure as it does not use a True RNG or HRNG like Pico HSM. Use this approach if you have plugged a TRNG or you are not worried about obtaining the highest entropy.
|
||||
|
||||
Pico HSM also accepts ECDSA keypairs:
|
||||
@@ -157,9 +157,9 @@ Certificate:
|
||||
a0:30:b2:ec:d3:d6:0d:58:f3
|
||||
Exponent: 65537 (0x10001)
|
||||
X509v3 extensions:
|
||||
X509v3 Subject Key Identifier:
|
||||
X509v3 Subject Key Identifier:
|
||||
98:07:DA:13:B0:8E:A0:5C:97:83:68:FE:4A:25:8D:50:C4:DC:16:FA
|
||||
X509v3 Authority Key Identifier:
|
||||
X509v3 Authority Key Identifier:
|
||||
keyid:98:07:DA:13:B0:8E:A0:5C:97:83:68:FE:4A:25:8D:50:C4:DC:16:FA
|
||||
|
||||
X509v3 Basic Constraints: critical
|
||||
@@ -173,7 +173,7 @@ Certificate:
|
||||
99:2b:b2:82:66:c1:06:a7:2c:62:af:e2:e4:93:42:36:66:8d:
|
||||
c5:3f:e1:ec:5f:9a:f8:5f:b3:6a:8f:0e:12:5d:c9:46:38:ea:
|
||||
0b:08
|
||||
```
|
||||
```
|
||||
|
||||
The resulting file `cert.pem` contains the signed certificate in PEM format. Convert it into DER format and load it into the Pico HSM:
|
||||
|
||||
|
||||
@@ -1,94 +0,0 @@
|
||||
#!/bin/bash
|
||||
|
||||
#
|
||||
# This file is part of the Pico HSM distribution (https://github.com/polhenarejos/pico-hsm).
|
||||
# Copyright (c) 2022 Pol Henarejos.
|
||||
#
|
||||
# This program is free software: you can redistribute it and/or modify
|
||||
# it under the terms of the GNU General Public License as published by
|
||||
# the Free Software Foundation, version 3.
|
||||
#
|
||||
# This program is distributed in the hope that it will be useful, but
|
||||
# WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
# General Public License for more details.
|
||||
#
|
||||
# You should have received a copy of the GNU General Public License
|
||||
# along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
#
|
||||
|
||||
VERSION_MAJOR="2" #Version of Pico CCID Core
|
||||
VERSION_MINOR="0"
|
||||
|
||||
echo "----------------------------"
|
||||
echo "VID/PID patcher for Pico HSM"
|
||||
echo "----------------------------"
|
||||
echo ""
|
||||
|
||||
if [ "$#" -le 0 ]; then
|
||||
echo "Usage: $0 VID:PID [input_uf2_file] [output_uf2_file]"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
IFS=':' read -r -a ARR <<< "$1"
|
||||
|
||||
if [ ${#ARR[@]} -ne 2 ]; then
|
||||
echo "ERROR: Specify vendor and product ids as VID:PID (e.g., $0 CAFE:1234)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
VID=${ARR[0]}
|
||||
PID=${ARR[1]}
|
||||
|
||||
if [ ${#VID} -ne 4 ]; then
|
||||
echo "ERROR: VID length must be 4 hexadecimal characters"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ ${#PID} -ne 4 ]; then
|
||||
echo "ERROR: PID length must be 4 hexadecimal characters"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! [[ $VID =~ ^[0-9A-Fa-f]{1,}$ ]] ; then
|
||||
echo "ERROR: VID must contain hexadecimal characters"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! [[ $PID =~ ^[0-9A-Fa-f]{1,}$ ]] ; then
|
||||
echo "ERROR: PID must contain hexadecimal characters"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
UF2_FILE_IF="hsm2040.uf2"
|
||||
UF2_FILE_OF="$UF2_FILE_IF"
|
||||
|
||||
if [ "$#" -ge 2 ]; then
|
||||
UF2_FILE_IF="$2"
|
||||
UF2_FILE_OF="$UF2_FILE_IF"
|
||||
fi
|
||||
|
||||
if [ "$#" -ge 3 ]; then
|
||||
UF2_FILE_OF="$3"
|
||||
fi
|
||||
|
||||
|
||||
echo -n "Patching ${UF2_FILE_IF}... "
|
||||
|
||||
if [[ ! -f "$UF2_FILE_IF" ]]; then
|
||||
echo "ERROR: UF2 file ${UF2_FILE_IF} does not exist"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$UF2_FILE_IF" != "$UF2_FILE_OF" ]; then
|
||||
cp -R $UF2_FILE_IF $UF2_FILE_OF
|
||||
fi
|
||||
|
||||
LITTLE_VID="\x${VID:2:2}\x${VID:0:2}"
|
||||
LITTLE_PID="\x${PID:2:2}\x${PID:0:2}"
|
||||
|
||||
perl -pi -e "s/\xff\xfe\xfd\xfc\x$VERSION_MINOR\x$VERSION_MAJOR\x01\x02\x03\x01/$LITTLE_VID$LITTLE_PID\x$VERSION_MINOR\x$VERSION_MAJOR\x01\x02\x03\x01/" $UF2_FILE_OF
|
||||
|
||||
echo "Done!"
|
||||
echo ""
|
||||
echo "Patched file was saved in ${UF2_FILE_OF}"
|
||||
Submodule pico-ccid deleted from be86197b0b
1
pico-keys-sdk
Submodule
1
pico-keys-sdk
Submodule
Submodule pico-keys-sdk added at 1d86efa33b
@@ -18,9 +18,20 @@ if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT_PATH} AND (NOT PICO_SDK_FETCH_FROM_GIT_P
|
||||
message("Using PICO_SDK_FETCH_FROM_GIT_PATH from environment ('${PICO_SDK_FETCH_FROM_GIT_PATH}')")
|
||||
endif ()
|
||||
|
||||
if (DEFINED ENV{PICO_SDK_FETCH_FROM_GIT_TAG} AND (NOT PICO_SDK_FETCH_FROM_GIT_TAG))
|
||||
set(PICO_SDK_FETCH_FROM_GIT_TAG $ENV{PICO_SDK_FETCH_FROM_GIT_TAG})
|
||||
message("Using PICO_SDK_FETCH_FROM_GIT_TAG from environment ('${PICO_SDK_FETCH_FROM_GIT_TAG}')")
|
||||
endif ()
|
||||
|
||||
if (PICO_SDK_FETCH_FROM_GIT AND NOT PICO_SDK_FETCH_FROM_GIT_TAG)
|
||||
set(PICO_SDK_FETCH_FROM_GIT_TAG "master")
|
||||
message("Using master as default value for PICO_SDK_FETCH_FROM_GIT_TAG")
|
||||
endif()
|
||||
|
||||
set(PICO_SDK_PATH "${PICO_SDK_PATH}" CACHE PATH "Path to the Raspberry Pi Pico SDK")
|
||||
set(PICO_SDK_FETCH_FROM_GIT "${PICO_SDK_FETCH_FROM_GIT}" CACHE BOOL "Set to ON to fetch copy of SDK from git if not otherwise locatable")
|
||||
set(PICO_SDK_FETCH_FROM_GIT_PATH "${PICO_SDK_FETCH_FROM_GIT_PATH}" CACHE FILEPATH "location to download SDK")
|
||||
set(PICO_SDK_FETCH_FROM_GIT_TAG "${PICO_SDK_FETCH_FROM_GIT_TAG}" CACHE FILEPATH "release tag for SDK")
|
||||
|
||||
if (NOT PICO_SDK_PATH)
|
||||
if (PICO_SDK_FETCH_FROM_GIT)
|
||||
@@ -29,11 +40,22 @@ if (NOT PICO_SDK_PATH)
|
||||
if (PICO_SDK_FETCH_FROM_GIT_PATH)
|
||||
get_filename_component(FETCHCONTENT_BASE_DIR "${PICO_SDK_FETCH_FROM_GIT_PATH}" REALPATH BASE_DIR "${CMAKE_SOURCE_DIR}")
|
||||
endif ()
|
||||
FetchContent_Declare(
|
||||
pico_sdk
|
||||
GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk
|
||||
GIT_TAG master
|
||||
)
|
||||
# GIT_SUBMODULES_RECURSE was added in 3.17
|
||||
if (${CMAKE_VERSION} VERSION_GREATER_EQUAL "3.17.0")
|
||||
FetchContent_Declare(
|
||||
pico_sdk
|
||||
GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk
|
||||
GIT_TAG ${PICO_SDK_FETCH_FROM_GIT_TAG}
|
||||
GIT_SUBMODULES_RECURSE FALSE
|
||||
)
|
||||
else ()
|
||||
FetchContent_Declare(
|
||||
pico_sdk
|
||||
GIT_REPOSITORY https://github.com/raspberrypi/pico-sdk
|
||||
GIT_TAG ${PICO_SDK_FETCH_FROM_GIT_TAG}
|
||||
)
|
||||
endif ()
|
||||
|
||||
if (NOT pico_sdk)
|
||||
message("Downloading Raspberry Pi Pico SDK")
|
||||
FetchContent_Populate(pico_sdk)
|
||||
|
||||
52
sdkconfig.defaults
Executable file
52
sdkconfig.defaults
Executable file
@@ -0,0 +1,52 @@
|
||||
# This file was generated using idf.py save-defconfig. It can be edited manually.
|
||||
# Espressif IoT Development Framework (ESP-IDF) Project Minimal Configuration
|
||||
#
|
||||
IGNORE_UNKNOWN_FILES_FOR_MANAGED_COMPONENTS=y
|
||||
|
||||
CONFIG_PARTITION_TABLE_CUSTOM=y
|
||||
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="pico-keys-sdk/config/esp32/partitions.csv"
|
||||
CONFIG_PARTITION_TABLE_FILENAME="pico-keys-sdk/config/esp32/partitions.csv"
|
||||
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
|
||||
CONFIG_WL_SECTOR_SIZE_512=y
|
||||
CONFIG_WL_SECTOR_MODE_PERF=y
|
||||
COMPILER_OPTIMIZATION="Performance"
|
||||
|
||||
CONFIG_MBEDTLS_CMAC_C=y
|
||||
CONFIG_MBEDTLS_CHACHA20_C=y
|
||||
CONFIG_MBEDTLS_POLY1305_C=y
|
||||
CONFIG_MBEDTLS_CHACHAPOLY_C=y
|
||||
CONFIG_MBEDTLS_HKDF_C=y
|
||||
CONFIG_MBEDTLS_HARDWARE_ECC=y
|
||||
CONFIG_MBEDTLS_HARDWARE_GCM=y
|
||||
# CONFIG_MBEDTLS_HARDWARE_MPI is not set
|
||||
CONFIG_MBEDTLS_HARDWARE_SHA=y
|
||||
CONFIG_MBEDTLS_HARDWARE_AES=y
|
||||
# CONFIG_MBEDTLS_ROM_MD5 is not set
|
||||
CONFIG_MBEDTLS_SHA512_C=y
|
||||
CONFIG_MBEDTLS_TLS_DISABLED=y
|
||||
# CONFIG_MBEDTLS_TLS_ENABLED is not set
|
||||
# CONFIG_ESP_TLS_USE_DS_PERIPHERAL is not set
|
||||
# CONFIG_ESP_WIFI_ENABLED is not set
|
||||
# CONFIG_ESP_WIFI_MBEDTLS_CRYPTO is not set
|
||||
# CONFIG_ESP_WIFI_MBEDTLS_TLS_CLIENT is not set
|
||||
# CONFIG_ESP_WIFI_MBEDTLS_CRYPTO is not set
|
||||
# CONFIG_MBEDTLS_PSK_MODES is not set
|
||||
# CONFIG_MBEDTLS_KEY_EXCHANGE_RSA is not set
|
||||
# CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE is not set
|
||||
# CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA is not set
|
||||
# CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA is not set
|
||||
# CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA is not set
|
||||
# CONFIG_MBEDTLS_KEY_EXCHANGE_ECDH_RSA is not set
|
||||
# CONFIG_MBEDTLS_SSL_RENEGOTIATION is not set
|
||||
# CONFIG_MBEDTLS_SSL_PROTO_TLS1_2 is not set
|
||||
# CONFIG_MBEDTLS_SSL_PROTO_GMTSSL1_1 is not set
|
||||
# CONFIG_MBEDTLS_SSL_PROTO_DTLS is not set
|
||||
# CONFIG_MBEDTLS_SSL_ALPN is not set
|
||||
# CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS is not set
|
||||
# CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS is not set
|
||||
# CONFIG_ESP_WIFI_ENABLE_WPA3_SAE is not set
|
||||
# CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA is not set
|
||||
# CONFIG_ESP_WIFI_ENABLE_WPA3_SAE is not set
|
||||
# CONFIG_ESP_WIFI_ENABLE_WPA3_OWE_STA is not set
|
||||
|
||||
CONFIG_ESP_COREDUMP_ENABLE_TO_UART=y
|
||||
6
src/hsm/CMakeLists.txt
Normal file
6
src/hsm/CMakeLists.txt
Normal file
@@ -0,0 +1,6 @@
|
||||
idf_component_register(
|
||||
SRCS ${SOURCES}
|
||||
INCLUDE_DIRS . ../../pico-keys-sdk/src ../../pico-keys-sdk/src/fs ../../pico-keys-sdk/src/rng ../../pico-keys-sdk/src/usb
|
||||
REQUIRES bootloader_support esp_partition esp_tinyusb zorxx__neopixel mbedtls efuse
|
||||
)
|
||||
idf_component_set_property(${COMPONENT_NAME} WHOLE_ARCHIVE ON)
|
||||
326
src/hsm/cmd_bip_slip.c
Normal file
326
src/hsm/cmd_bip_slip.c
Normal file
@@ -0,0 +1,326 @@
|
||||
/*
|
||||
* This file is part of the Pico HSM distribution (https://github.com/polhenarejos/pico-hsm).
|
||||
* Copyright (c) 2022 Pol Henarejos.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
#include "sc_hsm.h"
|
||||
#include "files.h"
|
||||
#include "random.h"
|
||||
#include "kek.h"
|
||||
#include "asn1.h"
|
||||
|
||||
const uint8_t *k1_seed = (const uint8_t *) "Bitcoin seed";
|
||||
const uint8_t *p1_seed = (const uint8_t *) "Nist256p1 seed";
|
||||
const uint8_t *sym_seed = (const uint8_t *) "Symmetric key seed";
|
||||
mbedtls_ecp_keypair hd_context = { 0 };
|
||||
uint8_t hd_keytype = 0;
|
||||
|
||||
int node_derive_bip_child(const mbedtls_ecp_keypair *parent,
|
||||
const uint8_t cpar[32],
|
||||
const uint8_t *i,
|
||||
mbedtls_ecp_keypair *child,
|
||||
uint8_t cchild[32]) {
|
||||
uint8_t data[1 + 32 + 4], I[64], *iL = I, *iR = I + 32;
|
||||
mbedtls_mpi il, kchild;
|
||||
mbedtls_mpi_init(&il);
|
||||
mbedtls_mpi_init(&kchild);
|
||||
if (i[0] >= 0x80) {
|
||||
if (mbedtls_mpi_cmp_int(&parent->d, 0) == 0) {
|
||||
return PICOKEY_ERR_NULL_PARAM;
|
||||
}
|
||||
data[0] = 0x00;
|
||||
mbedtls_mpi_write_binary(&parent->d, data + 1, 32);
|
||||
}
|
||||
else {
|
||||
size_t olen = 0;
|
||||
mbedtls_ecp_point_write_binary(&parent->grp,
|
||||
&parent->Q,
|
||||
MBEDTLS_ECP_PF_COMPRESSED,
|
||||
&olen,
|
||||
data,
|
||||
33);
|
||||
}
|
||||
do {
|
||||
memcpy(data + 33, i, 4);
|
||||
mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA512),
|
||||
cpar,
|
||||
32,
|
||||
data,
|
||||
sizeof(data),
|
||||
I);
|
||||
mbedtls_mpi_read_binary(&il, iL, 32);
|
||||
mbedtls_mpi_add_mpi(&kchild, &il, &parent->d);
|
||||
mbedtls_mpi_mod_mpi(&kchild, &kchild, &parent->grp.N);
|
||||
data[0] = 0x01;
|
||||
memcpy(data + 1, iR, 32);
|
||||
} while (mbedtls_mpi_cmp_mpi(&il,
|
||||
&parent->grp.N) != -1 || mbedtls_mpi_cmp_int(&kchild, 0) == 0);
|
||||
mbedtls_mpi_copy(&child->d, &kchild);
|
||||
mbedtls_ecp_mul(&child->grp, &child->Q, &child->d, &child->grp.G, random_gen, NULL);
|
||||
memcpy(cchild, iR, 32);
|
||||
mbedtls_mpi_free(&il);
|
||||
mbedtls_mpi_free(&kchild);
|
||||
return PICOKEY_OK;
|
||||
}
|
||||
|
||||
int sha256_ripemd160(const uint8_t *buffer, size_t buffer_len, uint8_t *output) {
|
||||
mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), buffer, buffer_len, output);
|
||||
mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_RIPEMD160), output, 32, output);
|
||||
return PICOKEY_OK;
|
||||
}
|
||||
|
||||
int sha256_sha256(const uint8_t *buffer, size_t buffer_len, uint8_t *output) {
|
||||
mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), buffer, buffer_len, output);
|
||||
mbedtls_md(mbedtls_md_info_from_type(MBEDTLS_MD_SHA256), output, 32, output);
|
||||
return PICOKEY_OK;
|
||||
}
|
||||
|
||||
int node_fingerprint_bip(mbedtls_ecp_keypair *ctx, uint8_t fingerprint[4]) {
|
||||
size_t olen = 0;
|
||||
uint8_t buffer[33];
|
||||
mbedtls_ecp_point_write_binary(&ctx->grp,
|
||||
&ctx->Q,
|
||||
MBEDTLS_ECP_PF_COMPRESSED,
|
||||
&olen,
|
||||
buffer,
|
||||
sizeof(buffer));
|
||||
sha256_ripemd160(buffer, sizeof(buffer), buffer);
|
||||
memcpy(fingerprint, buffer, 4);
|
||||
return PICOKEY_OK;
|
||||
}
|
||||
|
||||
int node_fingerprint_slip(mbedtls_ecp_keypair *ctx, uint8_t fingerprint[4]) {
|
||||
uint8_t buffer[32];
|
||||
mbedtls_mpi_write_binary(&ctx->d, buffer, sizeof(buffer));
|
||||
sha256_ripemd160(buffer, sizeof(buffer), buffer);
|
||||
memcpy(fingerprint, buffer, 4);
|
||||
return PICOKEY_OK;
|
||||
}
|
||||
|
||||
int load_master_bip(uint16_t mid, mbedtls_ecp_keypair *ctx, uint8_t chain[32],
|
||||
uint8_t key_type[1]) {
|
||||
uint8_t mkey[65];
|
||||
mbedtls_ecp_keypair_init(ctx);
|
||||
file_t *ef = search_file(EF_MASTER_SEED | mid);
|
||||
if (!file_has_data(ef)) {
|
||||
return PICOKEY_ERR_FILE_NOT_FOUND;
|
||||
}
|
||||
memcpy(mkey, file_get_data(ef), sizeof(mkey));
|
||||
int r = mkek_decrypt(mkey + 1,
|
||||
sizeof(mkey) - 1);
|
||||
if (r != PICOKEY_OK) {
|
||||
return PICOKEY_EXEC_ERROR;
|
||||
}
|
||||
if (mkey[0] == 0x1 || mkey[0] == 0x2) {
|
||||
if (mkey[0] == 0x1) {
|
||||
mbedtls_ecp_group_load(&ctx->grp, MBEDTLS_ECP_DP_SECP256K1);
|
||||
}
|
||||
else if (mkey[0] == 0x2) {
|
||||
mbedtls_ecp_group_load(&ctx->grp, MBEDTLS_ECP_DP_SECP256R1);
|
||||
}
|
||||
else {
|
||||
return PICOKEY_WRONG_DATA;
|
||||
}
|
||||
|
||||
mbedtls_mpi_read_binary(&ctx->d, mkey + 1, 32);
|
||||
memcpy(chain, mkey + 33, 32);
|
||||
mbedtls_ecp_mul(&ctx->grp, &ctx->Q, &ctx->d, &ctx->grp.G, random_gen, NULL);
|
||||
}
|
||||
else if (mkey[0] == 0x3) {
|
||||
mbedtls_mpi_read_binary(&ctx->d, mkey + 33, 32);
|
||||
memcpy(chain, mkey + 1, 32);
|
||||
}
|
||||
key_type[0] = mkey[0];
|
||||
return PICOKEY_OK;
|
||||
}
|
||||
|
||||
int node_derive_path(const uint8_t *path,
|
||||
uint16_t path_len,
|
||||
mbedtls_ecp_keypair *ctx,
|
||||
uint8_t chain[32],
|
||||
uint8_t fingerprint[4],
|
||||
uint8_t *nodes,
|
||||
uint8_t last_node[4],
|
||||
uint8_t key_type[1]) {
|
||||
uint8_t *tag_data = NULL, *p = NULL;
|
||||
uint16_t tag_len = 0, tag = 0x0;
|
||||
uint8_t node = 0, N[64] = { 0 };
|
||||
int r = 0;
|
||||
memset(last_node, 0, 4);
|
||||
memset(fingerprint, 0, 4);
|
||||
|
||||
asn1_ctx_t ctxi;
|
||||
asn1_ctx_init((uint8_t *)path, path_len, &ctxi);
|
||||
for (; walk_tlv(&ctxi, &p, &tag, &tag_len, &tag_data); node++) {
|
||||
if (tag == 0x02) {
|
||||
if ((node == 0 && tag_len != 1) || (node != 0 && tag_len != 4)) {
|
||||
return PICOKEY_WRONG_DATA;
|
||||
}
|
||||
if (node == 0) {
|
||||
if ((r = load_master_bip(tag_data[0], ctx, chain, key_type)) != PICOKEY_OK) {
|
||||
return r;
|
||||
}
|
||||
}
|
||||
else if (node > 0) {
|
||||
node_fingerprint_bip(ctx, fingerprint);
|
||||
if ((r = node_derive_bip_child(ctx, chain, tag_data, ctx, chain)) != PICOKEY_OK) {
|
||||
return r;
|
||||
}
|
||||
memcpy(last_node, tag_data, 4);
|
||||
}
|
||||
}
|
||||
else if (tag == 0x04) {
|
||||
if (node == 0) {
|
||||
return PICOKEY_WRONG_DATA;
|
||||
}
|
||||
else if (node > 0) {
|
||||
node_fingerprint_slip(ctx, fingerprint);
|
||||
*(tag_data - 1) = 0;
|
||||
mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA512),
|
||||
chain,
|
||||
32,
|
||||
tag_data - 1,
|
||||
tag_len + 1,
|
||||
N);
|
||||
memcpy(chain, N, 32);
|
||||
mbedtls_mpi_read_binary(&ctx->d, N + 32, 32);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (nodes) {
|
||||
*nodes = node;
|
||||
}
|
||||
return PICOKEY_OK;
|
||||
}
|
||||
|
||||
int cmd_bip_slip() {
|
||||
uint8_t p1 = P1(apdu), p2 = P2(apdu);
|
||||
if (p1 == 0x1 || p1 == 0x2 || p1 == 0x3) { // Master generation (K1 and P1)
|
||||
if (p2 >= 10) {
|
||||
return SW_INCORRECT_P1P2();
|
||||
}
|
||||
uint8_t mkey[65], *seed = mkey + 1, seed_len = 64;
|
||||
const uint8_t *key_seed = NULL;
|
||||
mbedtls_mpi il;
|
||||
mbedtls_mpi_init(&il);
|
||||
mbedtls_ecp_group grp;
|
||||
mbedtls_ecp_group_init(&grp);
|
||||
if (p1 == 0x1) {
|
||||
mbedtls_ecp_group_load(&grp, MBEDTLS_ECP_DP_SECP256K1);
|
||||
key_seed = k1_seed;
|
||||
}
|
||||
else if (p1 == 0x2) {
|
||||
mbedtls_ecp_group_load(&grp, MBEDTLS_ECP_DP_SECP256R1);
|
||||
key_seed = p1_seed;
|
||||
}
|
||||
else if (p1 == 0x3) {
|
||||
key_seed = sym_seed;
|
||||
}
|
||||
if (apdu.nc == 0) {
|
||||
seed_len = 64;
|
||||
random_gen(NULL, seed, seed_len);
|
||||
}
|
||||
else {
|
||||
seed_len = MIN((uint8_t)apdu.nc, 64);
|
||||
memcpy(seed, apdu.data, seed_len);
|
||||
}
|
||||
if (p1 == 0x1 || p1 == 0x2) {
|
||||
do {
|
||||
mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA512), key_seed,
|
||||
strlen((char *) key_seed), seed, seed_len, seed);
|
||||
mbedtls_mpi_read_binary(&il, seed, 32);
|
||||
seed_len = 64;
|
||||
} while (mbedtls_mpi_cmp_int(&il, 0) == 0 || mbedtls_mpi_cmp_mpi(&il, &grp.N) != -1);
|
||||
mbedtls_ecp_group_free(&grp);
|
||||
mbedtls_mpi_free(&il);
|
||||
}
|
||||
else if (p1 == 0x3) {
|
||||
mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA512), key_seed,
|
||||
strlen((char *) key_seed), seed, seed_len, seed);
|
||||
}
|
||||
mkey[0] = p1;
|
||||
file_t *ef = file_new(EF_MASTER_SEED | p2);
|
||||
int r = mkek_encrypt(mkey + 1, sizeof(mkey) - 1);
|
||||
if (r != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
r = file_put_data(ef, mkey, sizeof(mkey));
|
||||
if (r != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
low_flash_available();
|
||||
}
|
||||
else if (p1 == 0xA) {
|
||||
if (apdu.nc == 0) {
|
||||
return SW_WRONG_LENGTH();
|
||||
}
|
||||
mbedtls_ecp_keypair ctx;
|
||||
uint8_t chain[32] = { 0 }, fgpt[4] = { 0 }, last_node[4] = { 0 }, key_type = 0, nodes = 0;
|
||||
size_t olen = 0;
|
||||
int r =
|
||||
node_derive_path(apdu.data, (uint16_t)apdu.nc, &ctx, chain, fgpt, &nodes, last_node, &key_type);
|
||||
if (r != PICOKEY_OK) {
|
||||
mbedtls_ecp_keypair_free(&ctx);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
uint8_t pubkey[33];
|
||||
res_APDU_size = 0;
|
||||
memcpy(res_APDU, "\x04\x88\xB2\x1E", 4);
|
||||
res_APDU_size += 4;
|
||||
res_APDU[res_APDU_size++] = nodes - 1;
|
||||
memcpy(res_APDU + res_APDU_size, fgpt, 4);
|
||||
res_APDU_size += 4;
|
||||
memcpy(res_APDU + res_APDU_size, last_node, 4);
|
||||
res_APDU_size += 4;
|
||||
if (key_type == 0x1 || key_type == 0x2) {
|
||||
memcpy(res_APDU + res_APDU_size, chain, 32);
|
||||
res_APDU_size += 32;
|
||||
mbedtls_ecp_point_write_binary(&ctx.grp,
|
||||
&ctx.Q,
|
||||
MBEDTLS_ECP_PF_COMPRESSED,
|
||||
&olen,
|
||||
pubkey,
|
||||
sizeof(pubkey));
|
||||
memcpy(res_APDU + res_APDU_size, pubkey, olen);
|
||||
res_APDU_size += (uint16_t)olen;
|
||||
}
|
||||
else if (key_type == 0x3) {
|
||||
sha256_sha256(chain, 32, chain);
|
||||
memcpy(res_APDU + res_APDU_size, chain, 32);
|
||||
res_APDU_size += 32;
|
||||
mbedtls_mpi_write_binary(&ctx.d, pubkey, 32);
|
||||
sha256_sha256(pubkey, 32, pubkey);
|
||||
memcpy(res_APDU + res_APDU_size, pubkey, 32);
|
||||
res_APDU_size += 32;
|
||||
}
|
||||
mbedtls_ecp_keypair_free(&ctx);
|
||||
}
|
||||
else if (p1 == 0x10) {
|
||||
uint8_t chain[32] = { 0 }, fgpt[4] = { 0 }, last_node[4] = { 0 }, nodes = 0;
|
||||
int r = node_derive_path(apdu.data,
|
||||
(uint16_t)apdu.nc,
|
||||
&hd_context,
|
||||
chain,
|
||||
fgpt,
|
||||
&nodes,
|
||||
last_node,
|
||||
&hd_keytype);
|
||||
if (r != PICOKEY_OK) {
|
||||
mbedtls_ecp_keypair_free(&hd_context);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
}
|
||||
return SW_OK();
|
||||
}
|
||||
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 = (uint8_t)MIN(apdu.ne, sizeof(challenge));
|
||||
memcpy(challenge, rb, challenge_len);
|
||||
res_APDU_size = (uint16_t)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_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 != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
//encrypt MKEK with new pin
|
||||
|
||||
if (P2(apdu) == 0x81) {
|
||||
hash_multi(apdu.data + pin_len, (uint16_t)(apdu.nc - pin_len), session_pin);
|
||||
has_session_pin = true;
|
||||
}
|
||||
else if (P2(apdu) == 0x88) {
|
||||
hash_multi(apdu.data + pin_len, (uint16_t)(apdu.nc - pin_len), session_sopin);
|
||||
has_session_sopin = true;
|
||||
}
|
||||
r = store_mkek(mkek);
|
||||
release_mkek(mkek);
|
||||
if (r != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
uint8_t dhash[33];
|
||||
dhash[0] = (uint8_t)apdu.nc - pin_len;
|
||||
double_hash_pin(apdu.data + pin_len, (uint16_t)(apdu.nc - pin_len), dhash + 1);
|
||||
file_put_data(file_pin, dhash, sizeof(dhash));
|
||||
low_flash_available();
|
||||
return SW_OK();
|
||||
}
|
||||
}
|
||||
return SW_WRONG_P1P2();
|
||||
}
|
||||
713
src/hsm/cmd_cipher_sym.c
Normal file
713
src/hsm/cmd_cipher_sym.c
Normal file
@@ -0,0 +1,713 @@
|
||||
/*
|
||||
* 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 "mbedtls/aes.h"
|
||||
#include "mbedtls/cmac.h"
|
||||
#include "mbedtls/hkdf.h"
|
||||
#include "mbedtls/chachapoly.h"
|
||||
#include "mbedtls/gcm.h"
|
||||
//#include "mbedtls/md_wrap.h"
|
||||
#include "mbedtls/md.h"
|
||||
#include "crypto_utils.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"
|
||||
#include "mbedtls/ccm.h"
|
||||
|
||||
extern mbedtls_ecp_keypair hd_context;
|
||||
extern uint8_t hd_keytype;
|
||||
|
||||
/* 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,
|
||||
uint16_t *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, (int *)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,
|
||||
uint16_t input_len,
|
||||
uint8_t *input,
|
||||
uint16_t shared_info_len,
|
||||
uint8_t *shared_info,
|
||||
uint16_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 = mbedtls_md_get_size(md_info);
|
||||
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() {
|
||||
uint8_t key_id = P1(apdu), algo = P2(apdu);
|
||||
if (!isUserAuthenticated) {
|
||||
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||
}
|
||||
if (wait_button_pressed() == true) { // timeout
|
||||
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||
}
|
||||
file_t *ef = search_file((KEY_PREFIX << 8) | key_id);
|
||||
if (hd_keytype == 0) {
|
||||
if (!ef) {
|
||||
return SW_FILE_NOT_FOUND();
|
||||
}
|
||||
if (key_has_purpose(ef, algo) == false) {
|
||||
return SW_CONDITIONS_NOT_SATISFIED();
|
||||
}
|
||||
}
|
||||
uint16_t key_size = file_get_size(ef);
|
||||
uint8_t kdata[64]; //maximum AES key size
|
||||
memcpy(kdata, file_get_data(ef), key_size);
|
||||
if (hd_keytype == 0 && 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);
|
||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||
if (r != 0) {
|
||||
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_aes_free(&aes);
|
||||
if (r != 0) {
|
||||
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_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_aes_free(&aes);
|
||||
if (r != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
}
|
||||
res_APDU_size = (uint16_t)apdu.nc;
|
||||
}
|
||||
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,
|
||||
kdata,
|
||||
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 = (uint16_t)apdu.nc;
|
||||
}
|
||||
else if (algo == ALGO_EXT_CIPHER_ENCRYPT || algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||
asn1_ctx_t ctxi, oid = {0}, enc = {0}, iv = {0}, aad = {0};
|
||||
asn1_ctx_init(apdu.data, (uint16_t)apdu.nc, &ctxi);
|
||||
if (!asn1_find_tag(&ctxi, 0x6, &oid) || asn1_len(&oid) == 0) {
|
||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
asn1_find_tag(&ctxi, 0x81, &enc);
|
||||
asn1_find_tag(&ctxi, 0x82, &iv);
|
||||
asn1_find_tag(&ctxi, 0x83, &aad);
|
||||
uint8_t tmp_iv[16];
|
||||
memset(tmp_iv, 0, sizeof(tmp_iv));
|
||||
if (memcmp(oid.data, 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);
|
||||
mbedtls_chachapoly_setkey(&ctx, kdata);
|
||||
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
||||
r = mbedtls_chachapoly_encrypt_and_tag(&ctx,
|
||||
enc.len,
|
||||
asn1_len(&iv) > 0 ? iv.data : tmp_iv,
|
||||
aad.data,
|
||||
aad.len,
|
||||
enc.data,
|
||||
res_APDU,
|
||||
res_APDU + enc.len);
|
||||
}
|
||||
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||
r = mbedtls_chachapoly_auth_decrypt(&ctx,
|
||||
enc.len - 16,
|
||||
asn1_len(&iv) > 0 ? iv.data : tmp_iv,
|
||||
aad.data,
|
||||
aad.len,
|
||||
enc.data + enc.len - 16,
|
||||
enc.data,
|
||||
res_APDU);
|
||||
}
|
||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||
mbedtls_chachapoly_free(&ctx);
|
||||
if (r != 0) {
|
||||
if (r == MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
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.data, OID_DIGEST, 7) == 0) {
|
||||
const mbedtls_md_info_t *md_info = NULL;
|
||||
if (memcmp(oid.data, OID_HMAC_SHA1, oid.len) == 0) {
|
||||
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA1);
|
||||
}
|
||||
else if (memcmp(oid.data, OID_HMAC_SHA224, oid.len) == 0) {
|
||||
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA224);
|
||||
}
|
||||
else if (memcmp(oid.data, OID_HMAC_SHA256, oid.len) == 0) {
|
||||
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
|
||||
}
|
||||
else if (memcmp(oid.data, OID_HMAC_SHA384, oid.len) == 0) {
|
||||
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA384);
|
||||
}
|
||||
else if (memcmp(oid.data, 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.data, enc.len, res_APDU);
|
||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||
if (r != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
res_APDU_size = mbedtls_md_get_size(md_info);
|
||||
}
|
||||
else if (memcmp(oid.data, OID_HKDF_SHA256,
|
||||
oid.len) == 0 ||
|
||||
memcmp(oid.data, OID_HKDF_SHA384,
|
||||
oid.len) == 0 || memcmp(oid.data, OID_HKDF_SHA512, oid.len) == 0) {
|
||||
const mbedtls_md_info_t *md_info = NULL;
|
||||
if (memcmp(oid.data, OID_HKDF_SHA256, oid.len) == 0) {
|
||||
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
|
||||
}
|
||||
else if (memcmp(oid.data, OID_HKDF_SHA384, oid.len) == 0) {
|
||||
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA384);
|
||||
}
|
||||
else if (memcmp(oid.data, OID_HKDF_SHA512, oid.len) == 0) {
|
||||
md_info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA512);
|
||||
}
|
||||
int r = mbedtls_hkdf(md_info,
|
||||
iv.data,
|
||||
iv.len,
|
||||
kdata,
|
||||
key_size,
|
||||
enc.data,
|
||||
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 ? (uint16_t)apdu.ne : (uint16_t)mbedtls_md_get_size(md_info);
|
||||
}
|
||||
else if (memcmp(oid.data, OID_PKCS5_PBKDF2, oid.len) == 0) {
|
||||
int iterations = 0;
|
||||
uint16_t keylen = 0;
|
||||
mbedtls_asn1_buf salt,
|
||||
params =
|
||||
{ .p = enc.data, .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 ? (uint16_t)apdu.ne : 32);
|
||||
}
|
||||
else if (memcmp(oid.data, OID_PKCS5_PBES2, oid.len) == 0) {
|
||||
size_t olen = 0;
|
||||
mbedtls_asn1_buf params =
|
||||
{.p = aad.data, .len = aad.len, .tag = (MBEDTLS_ASN1_CONSTRUCTED | MBEDTLS_ASN1_SEQUENCE)};
|
||||
int r = mbedtls_pkcs5_pbes2_ext(¶ms,
|
||||
algo == ALGO_EXT_CIPHER_ENCRYPT ? MBEDTLS_PKCS5_ENCRYPT : MBEDTLS_PKCS5_DECRYPT,
|
||||
kdata,
|
||||
key_size,
|
||||
enc.data,
|
||||
enc.len,
|
||||
res_APDU, 4096, &olen);
|
||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||
if (r != 0) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
res_APDU_size = (uint16_t)olen;
|
||||
}
|
||||
else if (memcmp(oid.data, OID_KDF_X963, oid.len) == 0) {
|
||||
mbedtls_md_type_t md_type = MBEDTLS_MD_SHA1;
|
||||
if (memcmp(enc.data, OID_HMAC_SHA1, enc.len) == 0) {
|
||||
md_type = MBEDTLS_MD_SHA1;
|
||||
}
|
||||
else if (memcmp(enc.data, OID_HMAC_SHA224, enc.len) == 0) {
|
||||
md_type = MBEDTLS_MD_SHA224;
|
||||
}
|
||||
else if (memcmp(enc.data, OID_HMAC_SHA256, enc.len) == 0) {
|
||||
md_type = MBEDTLS_MD_SHA256;
|
||||
}
|
||||
else if (memcmp(enc.data, OID_HMAC_SHA384, enc.len) == 0) {
|
||||
md_type = MBEDTLS_MD_SHA384;
|
||||
}
|
||||
else if (memcmp(enc.data, 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.data,
|
||||
apdu.ne > 0 && apdu.ne < 65536 ? (uint16_t)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 ? (uint16_t)apdu.ne : 32;
|
||||
}
|
||||
else if (memcmp(oid.data, OID_NIST_AES, 8) == 0) {
|
||||
if (oid.len != 9) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
uint8_t aes_algo = oid.data[8],
|
||||
mode =
|
||||
(algo == ALGO_EXT_CIPHER_ENCRYPT ? MBEDTLS_AES_ENCRYPT : MBEDTLS_AES_DECRYPT);
|
||||
if ((aes_algo >= 0x01 && aes_algo <= 0x09 && key_size != 16) ||
|
||||
(aes_algo >= 0x15 && aes_algo <= 0x1D && key_size != 24) ||
|
||||
(aes_algo >= 0x29 && aes_algo <= 0x31 && key_size != 32)) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
mbedtls_aes_context ctx;
|
||||
int r = 0;
|
||||
mbedtls_aes_init(&ctx);
|
||||
if (asn1_len(&iv) == 0) {
|
||||
iv.data = tmp_iv;
|
||||
iv.len = sizeof(tmp_iv);
|
||||
}
|
||||
if (aes_algo == 0x01 || aes_algo == 0x15 || aes_algo == 0x29) { /* ECB */
|
||||
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
||||
r = mbedtls_aes_setkey_enc(&ctx, kdata, key_size * 8);
|
||||
}
|
||||
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||
r = mbedtls_aes_setkey_dec(&ctx, kdata, key_size * 8);
|
||||
}
|
||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||
r = mbedtls_aes_crypt_ecb(&ctx, mode, enc.data, res_APDU);
|
||||
mbedtls_aes_free(&ctx);
|
||||
if (r != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
res_APDU_size = MIN(enc.len, 16); // ECB operates with 16-byte blocks
|
||||
}
|
||||
else if (aes_algo == 0x02 || aes_algo == 0x16 || aes_algo == 0x2A) { /* CBC */
|
||||
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
||||
r = mbedtls_aes_setkey_enc(&ctx, kdata, key_size * 8);
|
||||
}
|
||||
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||
r = mbedtls_aes_setkey_dec(&ctx, kdata, key_size * 8);
|
||||
}
|
||||
if (r != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||
r = mbedtls_aes_crypt_cbc(&ctx, mode, enc.len, iv.data, enc.data, res_APDU);
|
||||
mbedtls_aes_free(&ctx);
|
||||
if (r != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
res_APDU_size = enc.len;
|
||||
}
|
||||
else if (aes_algo == 0x03 || aes_algo == 0x17 || aes_algo == 0x2B) { /* OFB */
|
||||
size_t iv_off = 0;
|
||||
r = mbedtls_aes_setkey_enc(&ctx, kdata, key_size * 8);
|
||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||
r = mbedtls_aes_crypt_ofb(&ctx, enc.len, &iv_off, iv.data, enc.data, res_APDU);
|
||||
mbedtls_aes_free(&ctx);
|
||||
if (r != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
res_APDU_size = enc.len;
|
||||
}
|
||||
else if (aes_algo == 0x04 || aes_algo == 0x18 || aes_algo == 0x2C) { /* CFB */
|
||||
size_t iv_off = 0;
|
||||
r = mbedtls_aes_setkey_enc(&ctx, kdata, key_size * 8);
|
||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||
r = mbedtls_aes_crypt_cfb128(&ctx, mode, enc.len, &iv_off, iv.data, enc.data, res_APDU);
|
||||
mbedtls_aes_free(&ctx);
|
||||
if (r != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
res_APDU_size = enc.len;
|
||||
}
|
||||
else if (aes_algo == 0x06 || aes_algo == 0x1A || aes_algo == 0x2E) { /* GCM */
|
||||
mbedtls_aes_free(&ctx); // No AES ctx used
|
||||
mbedtls_gcm_context gctx;
|
||||
mbedtls_gcm_init(&gctx);
|
||||
r = mbedtls_gcm_setkey(&gctx, MBEDTLS_CIPHER_ID_AES, kdata, key_size * 8);
|
||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
||||
r = mbedtls_gcm_crypt_and_tag(&gctx,
|
||||
MBEDTLS_GCM_ENCRYPT,
|
||||
enc.len,
|
||||
iv.data,
|
||||
iv.len,
|
||||
aad.data,
|
||||
aad.len,
|
||||
enc.data,
|
||||
res_APDU,
|
||||
16,
|
||||
res_APDU + enc.len);
|
||||
res_APDU_size = enc.len + 16;
|
||||
}
|
||||
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||
r = mbedtls_gcm_auth_decrypt(&gctx,
|
||||
enc.len - 16,
|
||||
iv.data,
|
||||
iv.len,
|
||||
aad.data,
|
||||
aad.len,
|
||||
enc.data + enc.len - 16,
|
||||
16,
|
||||
enc.data,
|
||||
res_APDU);
|
||||
res_APDU_size = enc.len - 16;
|
||||
}
|
||||
mbedtls_gcm_free(&gctx);
|
||||
if (r != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
}
|
||||
else if (aes_algo == 0x09 || aes_algo == 0x1D || aes_algo == 0x31) { /* CTR */
|
||||
size_t iv_off = 0;
|
||||
uint8_t stream_block[16];
|
||||
r = mbedtls_aes_setkey_enc(&ctx, kdata, key_size * 8);
|
||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||
r = mbedtls_aes_crypt_ctr(&ctx, enc.len, &iv_off, iv.data, stream_block, enc.data, res_APDU);
|
||||
mbedtls_aes_free(&ctx);
|
||||
if (r != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
res_APDU_size = enc.len;
|
||||
}
|
||||
else if (aes_algo == 0x07 || aes_algo == 0x1B || aes_algo == 0x2F) { /* CCM */
|
||||
mbedtls_aes_free(&ctx); // No AES ctx used
|
||||
mbedtls_ccm_context gctx;
|
||||
mbedtls_ccm_init(&gctx);
|
||||
r = mbedtls_ccm_setkey(&gctx, MBEDTLS_CIPHER_ID_AES, kdata, key_size * 8);
|
||||
if (r != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
if (iv.len == 16) {
|
||||
iv.len = 12;
|
||||
}
|
||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
||||
r = mbedtls_ccm_encrypt_and_tag(&gctx,
|
||||
enc.len,
|
||||
iv.data,
|
||||
iv.len,
|
||||
aad.data,
|
||||
aad.len,
|
||||
enc.data,
|
||||
res_APDU,
|
||||
res_APDU + enc.len,
|
||||
16);
|
||||
res_APDU_size = enc.len + 16;
|
||||
}
|
||||
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||
r = mbedtls_ccm_auth_decrypt(&gctx,
|
||||
enc.len - 16,
|
||||
iv.data,
|
||||
iv.len,
|
||||
aad.data,
|
||||
aad.len,
|
||||
enc.data,
|
||||
res_APDU,
|
||||
enc.data + enc.len - 16,
|
||||
16);
|
||||
res_APDU_size = enc.len - 16;
|
||||
}
|
||||
mbedtls_ccm_free(&gctx);
|
||||
if (r != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
}
|
||||
}
|
||||
else if (memcmp(oid.data, OID_IEEE_ALG, 8) == 0) {
|
||||
if (oid.len != 9) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
uint8_t aes_algo = oid.data[8],
|
||||
mode =
|
||||
(algo == ALGO_EXT_CIPHER_ENCRYPT ? MBEDTLS_AES_ENCRYPT : MBEDTLS_AES_DECRYPT);
|
||||
int r = 0;
|
||||
memset(tmp_iv, 0, sizeof(tmp_iv));
|
||||
if (asn1_len(&iv) == 0) {
|
||||
iv.data = tmp_iv;
|
||||
iv.len = sizeof(tmp_iv);
|
||||
}
|
||||
if ((aes_algo == 0x01 && key_size != 32) || (aes_algo == 0x02 && key_size != 64)) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
mbedtls_aes_xts_context ctx;
|
||||
mbedtls_aes_xts_init(&ctx);
|
||||
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
||||
r = mbedtls_aes_xts_setkey_enc(&ctx, kdata, key_size * 8);
|
||||
}
|
||||
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||
r = mbedtls_aes_xts_setkey_dec(&ctx, kdata, key_size * 8);
|
||||
}
|
||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||
r = mbedtls_aes_crypt_xts(&ctx, mode, enc.len, iv.data, enc.data, res_APDU);
|
||||
mbedtls_aes_xts_free(&ctx);
|
||||
if (r != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
res_APDU_size = enc.len;
|
||||
}
|
||||
else if (memcmp(oid.data, OID_HD, 11) == 0) {
|
||||
mbedtls_aes_context ctx;
|
||||
int r = 0;
|
||||
uint8_t mode =
|
||||
(algo == ALGO_EXT_CIPHER_ENCRYPT ? MBEDTLS_AES_ENCRYPT : MBEDTLS_AES_DECRYPT),
|
||||
secret[64] = { 0 };
|
||||
mbedtls_aes_init(&ctx);
|
||||
if (hd_keytype != 0x3) {
|
||||
mbedtls_ecdsa_free(&hd_context);
|
||||
return SW_INCORRECT_PARAMS();
|
||||
}
|
||||
key_size = 32;
|
||||
mbedtls_mpi_write_binary(&hd_context.d, kdata, key_size);
|
||||
r = mbedtls_md_hmac(mbedtls_md_info_from_type(MBEDTLS_MD_SHA512),
|
||||
kdata,
|
||||
key_size,
|
||||
aad.data,
|
||||
aad.len,
|
||||
secret);
|
||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||
if (r != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
if (iv.data == tmp_iv || iv.len == 0) {
|
||||
iv.data = secret + 32;
|
||||
iv.len = 16;
|
||||
}
|
||||
if (algo == ALGO_EXT_CIPHER_ENCRYPT) {
|
||||
r = mbedtls_aes_setkey_enc(&ctx, secret, key_size * 8);
|
||||
}
|
||||
else if (algo == ALGO_EXT_CIPHER_DECRYPT) {
|
||||
r = mbedtls_aes_setkey_dec(&ctx, secret, key_size * 8);
|
||||
}
|
||||
if (r != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
r = mbedtls_aes_crypt_cbc(&ctx, mode, enc.len, iv.data, enc.data, res_APDU);
|
||||
mbedtls_aes_free(&ctx);
|
||||
if (r != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
res_APDU_size = enc.len;
|
||||
mbedtls_ecdsa_free(&hd_context);
|
||||
hd_keytype = 0;
|
||||
}
|
||||
else {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
}
|
||||
else {
|
||||
mbedtls_platform_zeroize(kdata, sizeof(kdata));
|
||||
return SW_WRONG_P1P2();
|
||||
}
|
||||
return SW_OK();
|
||||
}
|
||||
197
src/hsm/cmd_decrypt_asym.c
Normal file
197
src/hsm/cmd_decrypt_asym.c
Normal file
@@ -0,0 +1,197 @@
|
||||
/*
|
||||
* 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 "mbedtls/ecdh.h"
|
||||
#include "crypto_utils.h"
|
||||
#include "kek.h"
|
||||
#include "files.h"
|
||||
#include "asn1.h"
|
||||
#include "cvc.h"
|
||||
#include "random.h"
|
||||
#include "oid.h"
|
||||
|
||||
int cmd_decrypt_asym() {
|
||||
uint8_t key_id = P1(apdu);
|
||||
uint8_t p2 = P2(apdu);
|
||||
if (!isUserAuthenticated) {
|
||||
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||
}
|
||||
file_t *ef = search_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 != PICOKEY_OK) {
|
||||
mbedtls_rsa_free(&ctx);
|
||||
if (r == PICOKEY_VERIFICATION_FAILED) {
|
||||
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||
}
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
uint16_t 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 = (uint16_t)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();
|
||||
}
|
||||
uint16_t 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_ecp_read_key(gid, (mbedtls_ecdsa_context *)&ctx.ctx.mbed_ecdh, 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) {
|
||||
*(apdu.data - 1) = (uint8_t)apdu.nc;
|
||||
r = mbedtls_ecdh_read_public(&ctx, apdu.data - 1, apdu.nc + 1);
|
||||
}
|
||||
else if (p2 == ALGO_EC_DH_XKEK) {
|
||||
uint16_t pub_len = 0;
|
||||
const uint8_t *pub = cvc_get_pub(apdu.data, (uint16_t)apdu.nc, &pub_len);
|
||||
if (pub) {
|
||||
uint16_t t86_len = 0;
|
||||
const uint8_t *t86 = cvc_get_field(pub, pub_len, &t86_len, 0x86);
|
||||
uint8_t *t86w = (uint8_t *)t86;
|
||||
if (t86) {
|
||||
*(t86w - 1) = (uint8_t)t86_len;
|
||||
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;
|
||||
// The SmartCard-HSM returns the point result of the DH operation
|
||||
// with a leading '04'
|
||||
res_APDU[0] = 0x04;
|
||||
r =
|
||||
mbedtls_ecdh_calc_secret(&ctx, &olen, res_APDU + 1, 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 = (uint16_t)(olen + 1);
|
||||
}
|
||||
else {
|
||||
res_APDU_size = 0;
|
||||
uint16_t ext_len = 0;
|
||||
const uint8_t *ext = NULL;
|
||||
if ((ext = cvc_get_ext(apdu.data, (uint16_t)apdu.nc, &ext_len)) == NULL) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
uint8_t *p = NULL;
|
||||
uint16_t tag = 0;
|
||||
asn1_ctx_t ctxi, ctxo = { 0 }, kdom_uid = { 0 };
|
||||
asn1_ctx_init((uint8_t *)ext, ext_len, &ctxi);
|
||||
while (walk_tlv(&ctxi, &p, &tag, &ctxo.len, &ctxo.data)) {
|
||||
if (tag == 0x73) {
|
||||
asn1_ctx_t oid = {0};
|
||||
if (asn1_find_tag(&ctxo, 0x6, &oid) == 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(&ctxo, 0x80, &kdom_uid) == false) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (asn1_len(&kdom_uid) == 0) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
for (uint8_t n = 0; n < MAX_KEY_DOMAINS; n++) {
|
||||
file_t *tf = search_file(EF_XKEK + n);
|
||||
if (tf) {
|
||||
if (file_get_size(tf) == kdom_uid.len &&
|
||||
memcmp(file_get_data(tf), kdom_uid.data, kdom_uid.len) == 0) {
|
||||
file_new(EF_DKEK + n);
|
||||
if (store_dkek_key(n, res_APDU + 1) != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
mbedtls_platform_zeroize(res_APDU, 32);
|
||||
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_file(ef->fid))) {
|
||||
return SW_FILE_NOT_FOUND();
|
||||
}
|
||||
}
|
||||
else {
|
||||
uint16_t fid = (apdu.data[0] << 8) | apdu.data[1];
|
||||
if (!(ef = search_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) != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
return SW_OK();
|
||||
}
|
||||
101
src/hsm/cmd_derive_asym.c
Normal file
101
src/hsm/cmd_derive_asym.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"
|
||||
#include "mbedtls/ecdsa.h"
|
||||
#include "crypto_utils.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_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_ecp_keypair ctx;
|
||||
mbedtls_ecp_keypair_init(&ctx);
|
||||
|
||||
int r;
|
||||
r = load_private_key_ec(&ctx, fkey);
|
||||
if (r != PICOKEY_OK) {
|
||||
mbedtls_ecp_keypair_free(&ctx);
|
||||
if (r == PICOKEY_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_ecp_keypair_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_ecp_keypair_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_ecp_keypair_free(&ctx);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
r = store_keys(&ctx, PICO_KEYS_KEY_EC, dest_id);
|
||||
if (r != PICOKEY_OK) {
|
||||
mbedtls_ecp_keypair_free(&ctx);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
mbedtls_ecp_keypair_free(&ctx);
|
||||
}
|
||||
else {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
return SW_OK();
|
||||
}
|
||||
67
src/hsm/cmd_external_authenticate.c
Normal file
67
src/hsm/cmd_external_authenticate.c
Normal file
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* 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_file(EF_PUKAUT);
|
||||
if (!file_has_data(ef_puk)) {
|
||||
return SW_FILE_NOT_FOUND();
|
||||
}
|
||||
puk_status[ef_puk_aut->fid & (MAX_PUK - 1)] = 0;
|
||||
uint8_t *puk_data = file_get_data(ef_puk);
|
||||
uint8_t *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,
|
||||
(uint16_t)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();
|
||||
}
|
||||
295
src/hsm/cmd_extras.c
Normal file
295
src/hsm/cmd_extras.c
Normal file
@@ -0,0 +1,295 @@
|
||||
/*
|
||||
* 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 "mbedtls/ecdh.h"
|
||||
#ifdef PICO_PLATFORM
|
||||
#include "pico/aon_timer.h"
|
||||
#else
|
||||
#include <sys/time.h>
|
||||
#include <time.h>
|
||||
#endif
|
||||
#include "files.h"
|
||||
#include "random.h"
|
||||
#include "kek.h"
|
||||
#include "mbedtls/hkdf.h"
|
||||
#include "mbedtls/chachapoly.h"
|
||||
#ifdef PICO_RP2350
|
||||
#include "otp.h"
|
||||
#endif
|
||||
|
||||
#define CMD_DATETIME 0xA
|
||||
#define CMD_DYNOPS 0x6
|
||||
#define CMD_SECURE_LOCK 0x3A
|
||||
#define SECURE_LOCK_KEY_AGREEMENT 0x1
|
||||
#define SECURE_LOCK_ENABLE 0x2
|
||||
#define SECURE_LOCK_MASK 0x3
|
||||
#define SECURE_LOCK_DISABLE 0x4
|
||||
#define CMD_PHY 0x1B
|
||||
#define CMD_OTP 0x4C
|
||||
|
||||
int cmd_extras() {
|
||||
#ifndef ENABLE_EMULATION
|
||||
// Only allow change PHY without PIN
|
||||
if (!isUserAuthenticated && P1(apdu) != 0x1B) {
|
||||
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||
}
|
||||
#endif
|
||||
//check button (if enabled)
|
||||
if (wait_button_pressed() == true) {
|
||||
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||
}
|
||||
if (P1(apdu) == CMD_DATETIME) { //datetime operations
|
||||
if (P2(apdu) != 0x0) {
|
||||
return SW_INCORRECT_P1P2();
|
||||
}
|
||||
if (apdu.nc == 0) {
|
||||
#ifdef PICO_PLATFORM
|
||||
struct timespec tv;
|
||||
aon_timer_get_time(&tv);
|
||||
#else
|
||||
struct timeval tv;
|
||||
gettimeofday(&tv, NULL);
|
||||
#endif
|
||||
struct tm *tm = localtime(&tv.tv_sec);
|
||||
res_APDU[res_APDU_size++] = (tm->tm_year + 1900) >> 8;
|
||||
res_APDU[res_APDU_size++] = (tm->tm_year + 1900) & 0xff;
|
||||
res_APDU[res_APDU_size++] = tm->tm_mon;
|
||||
res_APDU[res_APDU_size++] = tm->tm_mday;
|
||||
res_APDU[res_APDU_size++] = tm->tm_wday;
|
||||
res_APDU[res_APDU_size++] = tm->tm_hour;
|
||||
res_APDU[res_APDU_size++] = tm->tm_min;
|
||||
res_APDU[res_APDU_size++] = tm->tm_sec;
|
||||
}
|
||||
else {
|
||||
if (apdu.nc != 8) {
|
||||
return SW_WRONG_LENGTH();
|
||||
}
|
||||
struct tm tm;
|
||||
tm.tm_year = ((apdu.data[0] << 8) | (apdu.data[1])) - 1900;
|
||||
tm.tm_mon = apdu.data[2];
|
||||
tm.tm_mday = apdu.data[3];
|
||||
tm.tm_wday = apdu.data[4];
|
||||
tm.tm_hour = apdu.data[5];
|
||||
tm.tm_min = apdu.data[6];
|
||||
tm.tm_sec = apdu.data[7];
|
||||
time_t tv_sec = mktime(&tm);
|
||||
#ifdef PICO_PLATFORM
|
||||
struct timespec tv = {.tv_sec = tv_sec, .tv_nsec = 0};
|
||||
aon_timer_set_time(&tv);
|
||||
#else
|
||||
struct timeval tv = {.tv_sec = tv_sec, .tv_usec = 0};
|
||||
settimeofday(&tv, NULL);
|
||||
#endif
|
||||
}
|
||||
}
|
||||
else if (P1(apdu) == CMD_DYNOPS) { //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_file(EF_DEVOPS);
|
||||
file_put_data(tf, newopts, sizeof(newopts));
|
||||
low_flash_available();
|
||||
}
|
||||
}
|
||||
else if (P1(apdu) == CMD_SECURE_LOCK) { // secure lock
|
||||
if (apdu.nc == 0) {
|
||||
return SW_WRONG_LENGTH();
|
||||
}
|
||||
if (P2(apdu) == SECURE_LOCK_KEY_AGREEMENT) { // Key Agreement
|
||||
mbedtls_ecdh_context hkey;
|
||||
mbedtls_ecdh_init(&hkey);
|
||||
mbedtls_ecdh_setup(&hkey, MBEDTLS_ECP_DP_SECP256R1);
|
||||
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 = (uint16_t)olen;
|
||||
}
|
||||
else if (P2(apdu) == SECURE_LOCK_ENABLE || P2(apdu) == SECURE_LOCK_MASK || P2(apdu) == SECURE_LOCK_DISABLE) {
|
||||
if (mse.init == false) {
|
||||
return SW_COMMAND_NOT_ALLOWED();
|
||||
}
|
||||
|
||||
int ret = mse_decrypt_ct(apdu.data, apdu.nc);
|
||||
if (ret != 0) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
if (P2(apdu) == SECURE_LOCK_ENABLE || P2(apdu) == SECURE_LOCK_DISABLE) { // Enable
|
||||
uint16_t opts = get_device_options();
|
||||
uint8_t newopts[] = { opts >> 8, (opts & 0xff) };
|
||||
if ((P2(apdu) == SECURE_LOCK_ENABLE && !(opts & HSM_OPT_SECURE_LOCK)) ||
|
||||
(P2(apdu) == SECURE_LOCK_DISABLE && (opts & HSM_OPT_SECURE_LOCK))) {
|
||||
uint16_t tfids[] = { EF_MKEK, EF_MKEK_SO };
|
||||
for (int t = 0; t < sizeof(tfids) / sizeof(uint16_t); t++) {
|
||||
file_t *tf = search_file(tfids[t]);
|
||||
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];
|
||||
}
|
||||
file_put_data(tf, tmp, file_get_size(tf));
|
||||
free(tmp);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (P2(apdu) == SECURE_LOCK_ENABLE) {
|
||||
newopts[0] |= HSM_OPT_SECURE_LOCK >> 8;
|
||||
}
|
||||
else if (P2(apdu) == SECURE_LOCK_DISABLE) {
|
||||
newopts[0] &= ~HSM_OPT_SECURE_LOCK >> 8;
|
||||
}
|
||||
file_t *tf = search_file(EF_DEVOPS);
|
||||
file_put_data(tf, newopts, sizeof(newopts));
|
||||
low_flash_available();
|
||||
}
|
||||
else if (P2(apdu) == SECURE_LOCK_MASK) {
|
||||
memcpy(mkek_mask, apdu.data, apdu.nc);
|
||||
has_mkek_mask = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
#ifndef ENABLE_EMULATION
|
||||
else if (P1(apdu) == CMD_PHY) { // Set PHY
|
||||
if (apdu.nc == 0) {
|
||||
if (file_has_data(ef_phy)) {
|
||||
res_APDU_size = file_get_size(ef_phy);
|
||||
memcpy(res_APDU, file_get_data(ef_phy), res_APDU_size);
|
||||
}
|
||||
}
|
||||
else {
|
||||
if (P2(apdu) == PHY_VIDPID) { // VIDPID
|
||||
if (apdu.nc != 4) {
|
||||
return SW_WRONG_LENGTH();
|
||||
}
|
||||
phy_data.vid = (apdu.data[0] << 8) | apdu.data[1];
|
||||
phy_data.pid = (apdu.data[2] << 8) | apdu.data[3];
|
||||
phy_data.vidpid_present = true;
|
||||
}
|
||||
else if (P2(apdu) == PHY_LED_GPIO) {
|
||||
phy_data.led_gpio = apdu.data[0];
|
||||
phy_data.led_gpio_present = true;
|
||||
}
|
||||
else if (P2(apdu) == PHY_LED_BTNESS) {
|
||||
phy_data.led_brightness = apdu.data[0];
|
||||
phy_data.led_brightness_present = true;
|
||||
}
|
||||
else if (P2(apdu) == PHY_OPTS) {
|
||||
if (apdu.nc != 2) {
|
||||
return SW_WRONG_LENGTH();
|
||||
}
|
||||
phy_data.opts = (apdu.data[0] << 8) | apdu.data[1];
|
||||
}
|
||||
else {
|
||||
return SW_INCORRECT_P1P2();
|
||||
}
|
||||
uint8_t tmp[PHY_MAX_SIZE];
|
||||
uint16_t tmp_len = 0;
|
||||
memset(tmp, 0, sizeof(tmp));
|
||||
if (phy_serialize_data(&phy_data, tmp, &tmp_len) != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
file_put_data(ef_phy, tmp, tmp_len);
|
||||
low_flash_available();
|
||||
}
|
||||
}
|
||||
#endif
|
||||
#if PICO_RP2350
|
||||
else if (P1(apdu) == CMD_OTP) {
|
||||
if (apdu.nc < 2) {
|
||||
return SW_WRONG_LENGTH();
|
||||
}
|
||||
uint16_t row = (apdu.data[0] << 8) | apdu.data[1];
|
||||
bool israw = P2(apdu) == 0x1;
|
||||
if (apdu.nc == 2) {
|
||||
if (row > 0xbf && row < 0xf48) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
if (israw) {
|
||||
memcpy(res_APDU, otp_buffer_raw(row), apdu.ne);
|
||||
}
|
||||
else {
|
||||
memcpy(res_APDU, otp_buffer(row), apdu.ne);
|
||||
}
|
||||
res_APDU_size = apdu.ne;
|
||||
}
|
||||
else {
|
||||
apdu.nc -= 2;
|
||||
apdu.data += 2;
|
||||
if (apdu.nc > 1024) {
|
||||
return SW_WRONG_LENGTH();
|
||||
}
|
||||
if (apdu.nc % (israw ? 4 : 2)) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
uint8_t adata[1024] __attribute__((aligned(4)));
|
||||
memcpy(adata, apdu.data, apdu.nc);
|
||||
int ret = 0;
|
||||
if (israw) {
|
||||
ret = otp_write_data_raw(row, adata, apdu.nc);
|
||||
}
|
||||
else {
|
||||
ret = otp_write_data(row, adata, apdu.nc);
|
||||
}
|
||||
if (ret != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
else {
|
||||
return SW_INCORRECT_P1P2();
|
||||
}
|
||||
return SW_OK();
|
||||
}
|
||||
116
src/hsm/cmd_general_authenticate.c
Normal file
116
src/hsm/cmd_general_authenticate.c
Normal file
@@ -0,0 +1,116 @@
|
||||
/*
|
||||
* 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 "mbedtls/ecdh.h"
|
||||
#include "asn1.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;
|
||||
uint16_t pubkey_len = 0;
|
||||
const uint8_t *pubkey = NULL;
|
||||
uint16_t tag = 0x0;
|
||||
uint8_t *tag_data = NULL, *p = NULL;
|
||||
uint16_t tag_len = 0;
|
||||
asn1_ctx_t ctxi;
|
||||
asn1_ctx_init(apdu.data + 2, (uint16_t)(apdu.nc - 2), &ctxi);
|
||||
while (walk_tlv(&ctxi, &p, &tag, &tag_len, &tag_data)) {
|
||||
if (tag == 0x80) {
|
||||
pubkey = tag_data - 1; //mbedtls ecdh starts reading one pos before
|
||||
pubkey_len = tag_len + 1;
|
||||
}
|
||||
}
|
||||
file_t *fkey = search_file(EF_KEY_DEV);
|
||||
if (!fkey) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
mbedtls_ecp_keypair ectx;
|
||||
mbedtls_ecp_keypair_init(&ectx);
|
||||
r = load_private_key_ecdh(&ectx, fkey);
|
||||
if (r != PICOKEY_OK) {
|
||||
mbedtls_ecp_keypair_free(&ectx);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
mbedtls_ecdh_context ctx;
|
||||
mbedtls_ecdh_init(&ctx);
|
||||
mbedtls_ecp_group_id gid = MBEDTLS_ECP_DP_SECP256R1;
|
||||
r = mbedtls_ecdh_setup(&ctx, gid);
|
||||
if (r != 0) {
|
||||
mbedtls_ecp_keypair_free(&ectx);
|
||||
mbedtls_ecdh_free(&ctx);
|
||||
return SW_DATA_INVALID();
|
||||
}
|
||||
r = mbedtls_mpi_copy(&ctx.ctx.mbed_ecdh.d, &ectx.d);
|
||||
mbedtls_ecp_keypair_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 != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
res_APDU_size += 8;
|
||||
}
|
||||
}
|
||||
return SW_OK();
|
||||
}
|
||||
256
src/hsm/cmd_initialize.c
Normal file
256
src/hsm/cmd_initialize.c
Normal file
@@ -0,0 +1,256 @@
|
||||
/*
|
||||
* 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 "crypto_utils.h"
|
||||
#include "files.h"
|
||||
#include "random.h"
|
||||
#include "kek.h"
|
||||
#include "version.h"
|
||||
#include "asn1.h"
|
||||
#include "cvc.h"
|
||||
#include "otp.h"
|
||||
|
||||
extern void scan_all();
|
||||
|
||||
extern char __StackLimit;
|
||||
int heapLeft() {
|
||||
#if !defined(ENABLE_EMULATION) && !defined(ESP_PLATFORM)
|
||||
char *p = malloc(256); // try to avoid undue fragmentation
|
||||
int left = &__StackLimit - p;
|
||||
free(p);
|
||||
#else
|
||||
int left = 1024 * 1024;
|
||||
#endif
|
||||
return left;
|
||||
}
|
||||
|
||||
extern void reset_puk_store();
|
||||
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;
|
||||
uint16_t tag_len = 0;
|
||||
asn1_ctx_t ctxi;
|
||||
asn1_ctx_init(apdu.data, (uint16_t)apdu.nc, &ctxi);
|
||||
while (walk_tlv(&ctxi, &p, &tag, &tag_len, &tag_data)) {
|
||||
if (tag == 0x80) { //options
|
||||
file_t *tf = search_file(EF_DEVOPS);
|
||||
file_put_data(tf, tag_data, tag_len);
|
||||
}
|
||||
else if (tag == 0x81) { //user pin
|
||||
if (file_pin1 && file_pin1->data) {
|
||||
uint8_t dhash[33];
|
||||
dhash[0] = (uint8_t)tag_len;
|
||||
double_hash_pin(tag_data, tag_len, dhash + 1);
|
||||
file_put_data(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] = (uint8_t)tag_len;
|
||||
double_hash_pin(tag_data, tag_len, dhash + 1);
|
||||
file_put_data(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_file(EF_PIN1_MAX_RETRIES);
|
||||
if (tf && tf->data) {
|
||||
file_put_data(tf, tag_data, tag_len);
|
||||
}
|
||||
if (file_retries_pin1 && file_retries_pin1->data) {
|
||||
file_put_data(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();
|
||||
}
|
||||
file_put_data(tf, NULL, 0);
|
||||
}
|
||||
else if (tag == 0x93) {
|
||||
file_t *ef_puk = search_file(EF_PUKAUT);
|
||||
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];
|
||||
file_put_data(ef_puk, pk_status, sizeof(pk_status));
|
||||
for (uint8_t i = 0; i < puks; i++) {
|
||||
file_t *tf = file_new(EF_PUK + i);
|
||||
if (!tf) {
|
||||
release_mkek(mkek);
|
||||
return SW_MEMORY_FAILURE();
|
||||
}
|
||||
file_put_data(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();
|
||||
file_put_data(tf, NULL, 0);
|
||||
}
|
||||
*/
|
||||
}
|
||||
}
|
||||
file_t *tf_kd = search_file(EF_KEY_DOMAIN);
|
||||
if (!tf_kd) {
|
||||
release_mkek(mkek);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
if (ret_mkek != PICOKEY_OK) {
|
||||
ret_mkek = load_mkek(mkek); //Try again with new PIN/SO-PIN just in case some is the same
|
||||
}
|
||||
if (store_mkek(ret_mkek == PICOKEY_OK ? mkek : NULL) != PICOKEY_OK) {
|
||||
release_mkek(mkek);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
release_mkek(mkek);
|
||||
if (dkeks) {
|
||||
if (*dkeks > 0) {
|
||||
uint16_t d = *dkeks;
|
||||
if (file_put_data(tf_kd, (const uint8_t *) &d, sizeof(d)) != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
}
|
||||
else {
|
||||
int r = save_dkek_key(0, random_bytes_get(32));
|
||||
if (r != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
uint16_t d = 0x0101;
|
||||
if (file_put_data(tf_kd, (const uint8_t *) &d, sizeof(d)) != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
uint16_t d = 0x0000;
|
||||
if (file_put_data(tf_kd, (const uint8_t *) &d, sizeof(d)) != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
}
|
||||
if (kds) {
|
||||
uint8_t t[MAX_KEY_DOMAINS * 2], k = MIN(*kds, MAX_KEY_DOMAINS);
|
||||
memset(t, 0xff, 2 * k);
|
||||
if (file_put_data(tf_kd, t, 2 * k) != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
}
|
||||
/* When initialized, it has all credentials */
|
||||
isUserAuthenticated = true;
|
||||
/* Create terminal private key */
|
||||
file_t *fdkey = search_file(EF_KEY_DEV);
|
||||
if (!fdkey) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
int ret = 0;
|
||||
if (ret_mkek != PICOKEY_OK || !file_has_data(fdkey)) {
|
||||
mbedtls_ecdsa_context ecdsa;
|
||||
mbedtls_ecdsa_init(&ecdsa);
|
||||
mbedtls_ecp_group_id ec_id = MBEDTLS_ECP_DP_SECP256R1;
|
||||
uint8_t key_id = 0;
|
||||
if (otp_key_2) {
|
||||
ret = mbedtls_ecp_read_key(MBEDTLS_ECP_DP_SECP256K1, &ecdsa, otp_key_2, 32);
|
||||
if (ret != 0) {
|
||||
mbedtls_ecdsa_free(&ecdsa);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
ret = mbedtls_ecp_mul(&ecdsa.grp, &ecdsa.Q, &ecdsa.d, &ecdsa.grp.G, random_gen, NULL);
|
||||
}
|
||||
else {
|
||||
ret = mbedtls_ecdsa_genkey(&ecdsa, ec_id, random_gen, NULL);
|
||||
}
|
||||
if (ret != 0) {
|
||||
mbedtls_ecdsa_free(&ecdsa);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
ret = store_keys(&ecdsa, PICO_KEYS_KEY_EC, key_id);
|
||||
if (ret != PICOKEY_OK) {
|
||||
mbedtls_ecdsa_free(&ecdsa);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
uint16_t ee_len = 0, term_len = 0;
|
||||
if ((ee_len = asn1_cvc_aut(&ecdsa, PICO_KEYS_KEY_EC, res_APDU, 4096, NULL, 0)) == 0) {
|
||||
mbedtls_ecdsa_free(&ecdsa);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
|
||||
file_t *fpk = search_file(EF_EE_DEV);
|
||||
ret = file_put_data(fpk, res_APDU, ee_len);
|
||||
if (ret != 0) {
|
||||
mbedtls_ecdsa_free(&ecdsa);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
|
||||
if ((term_len = asn1_cvc_cert(&ecdsa, PICO_KEYS_KEY_EC, res_APDU + ee_len, 4096 - ee_len, NULL, 0, true)) == 0) {
|
||||
mbedtls_ecdsa_free(&ecdsa);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
mbedtls_ecdsa_free(&ecdsa);
|
||||
fpk = search_file(EF_TERMCA);
|
||||
ret = file_put_data(fpk, res_APDU, ee_len + term_len);
|
||||
if (ret != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
|
||||
const uint8_t *keyid = (const uint8_t *) "\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0\x0",
|
||||
*label = (const uint8_t *) "ESPICOHSMTR";
|
||||
uint16_t prkd_len = asn1_build_prkd_ecc(label, (uint16_t)strlen((const char *) label), keyid, 20, 256, res_APDU, 4096);
|
||||
fpk = search_file(EF_PRKD_DEV);
|
||||
ret = file_put_data(fpk, res_APDU, prkd_len);
|
||||
}
|
||||
if (ret != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
low_flash_available();
|
||||
reset_puk_store();
|
||||
}
|
||||
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();
|
||||
}
|
||||
212
src/hsm/cmd_key_domain.c
Normal file
212
src/hsm/cmd_key_domain.c
Normal file
@@ -0,0 +1,212 @@
|
||||
/*
|
||||
* 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) {
|
||||
uint16_t tag_len = 0;
|
||||
if (!file_has_data(fkey)) {
|
||||
return 0xff;
|
||||
}
|
||||
const uint8_t *meta_tag = get_meta_tag(fkey, 0x92, &tag_len);
|
||||
if (meta_tag) {
|
||||
return *meta_tag;
|
||||
}
|
||||
return 0x0;
|
||||
}
|
||||
|
||||
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_file(EF_KEY_DOMAIN);
|
||||
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();
|
||||
}
|
||||
if (2 * p2 >= tf_kd_size) {
|
||||
return SW_INCORRECT_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) {
|
||||
int r = save_dkek_key(p2, NULL);
|
||||
if (r != PICOKEY_OK) {
|
||||
if (r == PICOKEY_NO_LOGIN) {
|
||||
pending_save_dkek = p2;
|
||||
}
|
||||
else {
|
||||
/* On fail, it will return to previous dkek state. */
|
||||
import_dkek_share(p2, apdu.data);
|
||||
return SW_FILE_NOT_FOUND();
|
||||
}
|
||||
}
|
||||
}
|
||||
uint8_t t[MAX_KEY_DOMAINS * 2];
|
||||
memcpy(t, kdata, tf_kd_size);
|
||||
t[2 * p2 + 1] = current_dkeks;
|
||||
if (file_put_data(tf_kd, t, tf_kd_size) != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
low_flash_available();
|
||||
}
|
||||
else {
|
||||
file_t *tf = search_file(EF_XKEK + p2);
|
||||
if (current_dkeks == 0xff && !file_has_data(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 (uint16_t i = 1; i < 256; i++) {
|
||||
file_t *fkey = search_file(KEY_PREFIX << 8 | (uint8_t)i);
|
||||
if (get_key_domain(fkey) == p2) {
|
||||
return SW_FILE_EXISTS();
|
||||
}
|
||||
}
|
||||
}
|
||||
uint8_t t[MAX_KEY_DOMAINS * 2];
|
||||
memcpy(t, kdata, tf_kd_size);
|
||||
if (p1 == 0x1) {
|
||||
if (t[2 * p2] != 0xff || t[2 * p2 + 1] != 0xff) {
|
||||
return SW_INCORRECT_P1P2();
|
||||
}
|
||||
t[2 * p2] = dkeks = apdu.data[0];
|
||||
t[2 * p2 + 1] = current_dkeks = 0;
|
||||
}
|
||||
else if (p1 == 0x3) {
|
||||
if (t[2 * p2] == 0xff && t[2 * p2 + 1] == 0xff) {
|
||||
return SW_INCORRECT_P1P2();
|
||||
}
|
||||
t[2 * p2] = dkeks = 0xff;
|
||||
t[2 * p2 + 1] = 0xff;
|
||||
}
|
||||
else if (p1 == 0x4) {
|
||||
t[2 * p2 + 1] = current_dkeks = 0;
|
||||
}
|
||||
if (file_put_data(tf_kd, t, tf_kd_size) != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
file_t *tf = NULL;
|
||||
if ((tf = search_file(EF_DKEK + p2))) {
|
||||
if (delete_file(tf) != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
}
|
||||
if (p1 == 0x3 && (tf = search_file(EF_XKEK + p2))) {
|
||||
if (delete_file(tf) != PICOKEY_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) {
|
||||
uint16_t pub_len = 0;
|
||||
file_t *fterm = search_file(EF_TERMCA);
|
||||
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();
|
||||
}
|
||||
uint16_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();
|
||||
}
|
||||
uint16_t t54_len = 0;
|
||||
const uint8_t *t54 = cvc_get_field(apdu.data, (uint16_t)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, (uint16_t)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, (uint16_t)apdu.nc, &pub_len);
|
||||
if (pub) {
|
||||
t86_len = 0;
|
||||
t86 = cvc_get_field(pub, pub_len, &t86_len, 0x86);
|
||||
if (t86) {
|
||||
file_put_data(tf, t86 + 1, (uint16_t)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_file(EF_XKEK + p2);
|
||||
if (file_has_data(tf)) {
|
||||
memcpy(res_APDU + 10, file_get_data(tf), file_get_size(tf));
|
||||
res_APDU_size += file_get_size(tf);
|
||||
}
|
||||
return SW_OK();
|
||||
}
|
||||
67
src/hsm/cmd_key_gen.c
Normal file
67
src/hsm/cmd_key_gen.c
Normal file
@@ -0,0 +1,67 @@
|
||||
/*
|
||||
* 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 == 0xB3) {
|
||||
key_size = 64;
|
||||
}
|
||||
else 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[64]; //maximum AES key size
|
||||
memcpy(aes_key, random_bytes_get(key_size), key_size);
|
||||
int aes_type = 0x0;
|
||||
if (key_size == 16) {
|
||||
aes_type = PICO_KEYS_KEY_AES_128;
|
||||
}
|
||||
else if (key_size == 24) {
|
||||
aes_type = PICO_KEYS_KEY_AES_192;
|
||||
}
|
||||
else if (key_size == 32) {
|
||||
aes_type = PICO_KEYS_KEY_AES_256;
|
||||
}
|
||||
else if (key_size == 64) {
|
||||
aes_type = PICO_KEYS_KEY_AES_512;
|
||||
}
|
||||
r = store_keys(aes_key, aes_type, key_id);
|
||||
if (r != PICOKEY_OK) {
|
||||
return SW_MEMORY_FAILURE();
|
||||
}
|
||||
if (find_and_store_meta_key(key_id) != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
low_flash_available();
|
||||
return SW_OK();
|
||||
}
|
||||
153
src/hsm/cmd_key_unwrap.c
Normal file
153
src/hsm/cmd_key_unwrap.c
Normal file
@@ -0,0 +1,153 @@
|
||||
/*
|
||||
* 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 "crypto_utils.h"
|
||||
#include "kek.h"
|
||||
#include "cvc.h"
|
||||
|
||||
int cmd_key_unwrap() {
|
||||
uint8_t key_id = P1(apdu);
|
||||
int r = 0;
|
||||
if (P2(apdu) != 0x93) {
|
||||
return SW_WRONG_P1P2();
|
||||
}
|
||||
if (!isUserAuthenticated) {
|
||||
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||
}
|
||||
uint8_t *data = apdu.data;
|
||||
uint16_t data_len = apdu.nc;
|
||||
if (data_len == 0) { // New style
|
||||
file_t *tef = search_file(0x2F10);
|
||||
if (!file_has_data(tef)) {
|
||||
return SW_FILE_NOT_FOUND();
|
||||
}
|
||||
data = file_get_data(tef);
|
||||
data_len = file_get_size(tef);
|
||||
}
|
||||
int key_type = dkek_type_key(data);
|
||||
uint8_t *allowed = NULL;
|
||||
int16_t kdom = -1;
|
||||
uint16_t allowed_len = 0;
|
||||
if (key_type == 0x0) {
|
||||
return SW_DATA_INVALID();
|
||||
}
|
||||
if (key_type & PICO_KEYS_KEY_RSA) {
|
||||
mbedtls_rsa_context ctx;
|
||||
mbedtls_rsa_init(&ctx);
|
||||
do {
|
||||
r = dkek_decode_key((uint8_t)++kdom, &ctx, data, data_len, NULL, &allowed, &allowed_len);
|
||||
} while ((r == PICOKEY_ERR_FILE_NOT_FOUND || r == PICOKEY_WRONG_DKEK) && kdom < MAX_KEY_DOMAINS);
|
||||
if (r != PICOKEY_OK) {
|
||||
mbedtls_rsa_free(&ctx);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
r = store_keys(&ctx, PICO_KEYS_KEY_RSA, key_id);
|
||||
if ((res_APDU_size = (uint16_t)asn1_cvc_aut(&ctx, PICO_KEYS_KEY_RSA, res_APDU, 4096, NULL, 0)) == 0) {
|
||||
mbedtls_rsa_free(&ctx);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
mbedtls_rsa_free(&ctx);
|
||||
if (r != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
}
|
||||
else if (key_type & PICO_KEYS_KEY_EC) {
|
||||
mbedtls_ecp_keypair ctx;
|
||||
mbedtls_ecp_keypair_init(&ctx);
|
||||
do {
|
||||
r = dkek_decode_key((uint8_t)++kdom, &ctx, data, data_len, NULL, &allowed, &allowed_len);
|
||||
} while ((r == PICOKEY_ERR_FILE_NOT_FOUND || r == PICOKEY_WRONG_DKEK) && kdom < MAX_KEY_DOMAINS);
|
||||
if (r != PICOKEY_OK) {
|
||||
mbedtls_ecp_keypair_free(&ctx);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
r = store_keys(&ctx, PICO_KEYS_KEY_EC, key_id);
|
||||
if ((res_APDU_size = (uint16_t)asn1_cvc_aut(&ctx, PICO_KEYS_KEY_EC, res_APDU, 4096, NULL, 0)) == 0) {
|
||||
mbedtls_ecp_keypair_free(&ctx);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
mbedtls_ecp_keypair_free(&ctx);
|
||||
if (r != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
}
|
||||
else if (key_type & PICO_KEYS_KEY_AES) {
|
||||
uint8_t aes_key[64];
|
||||
int key_size = 0, aes_type = 0;
|
||||
do {
|
||||
r = dkek_decode_key((uint8_t)++kdom,
|
||||
aes_key,
|
||||
data,
|
||||
data_len,
|
||||
&key_size,
|
||||
&allowed,
|
||||
&allowed_len);
|
||||
} while ((r == PICOKEY_ERR_FILE_NOT_FOUND || r == PICOKEY_WRONG_DKEK) && kdom < MAX_KEY_DOMAINS);
|
||||
if (r != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
if (key_size == 64) {
|
||||
aes_type = PICO_KEYS_KEY_AES_512;
|
||||
}
|
||||
else if (key_size == 32) {
|
||||
aes_type = PICO_KEYS_KEY_AES_256;
|
||||
}
|
||||
else if (key_size == 24) {
|
||||
aes_type = PICO_KEYS_KEY_AES_192;
|
||||
}
|
||||
else if (key_size == 16) {
|
||||
aes_type = PICO_KEYS_KEY_AES_128;
|
||||
}
|
||||
else {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
r = store_keys(aes_key, aes_type, key_id);
|
||||
if (r != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
}
|
||||
if ((allowed != NULL && allowed_len > 0) || kdom >= 0) {
|
||||
uint16_t meta_len = (allowed_len > 0 ? 2 + allowed_len : 0) + (kdom >= 0 ? 3 : 0);
|
||||
uint8_t *meta = (uint8_t *) calloc(1, meta_len), *m = meta;
|
||||
if (allowed_len > 0) {
|
||||
*m++ = 0x91;
|
||||
*m++ = (uint8_t)allowed_len;
|
||||
memcpy(m, allowed, allowed_len); m += allowed_len;
|
||||
}
|
||||
if (kdom >= 0) {
|
||||
*m++ = 0x92;
|
||||
*m++ = 1;
|
||||
*m++ = (uint8_t)kdom;
|
||||
}
|
||||
r = meta_add((KEY_PREFIX << 8) | key_id, meta, meta_len);
|
||||
free(meta);
|
||||
if (r != PICOKEY_OK) {
|
||||
return r;
|
||||
}
|
||||
}
|
||||
if (res_APDU_size > 0) {
|
||||
file_t *fpk = file_new((EE_CERTIFICATE_PREFIX << 8) | key_id);
|
||||
r = file_put_data(fpk, res_APDU, res_APDU_size);
|
||||
if (r != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
res_APDU_size = 0;
|
||||
}
|
||||
low_flash_available();
|
||||
return SW_OK();
|
||||
}
|
||||
118
src/hsm/cmd_key_wrap.c
Normal file
118
src/hsm/cmd_key_wrap.c
Normal file
@@ -0,0 +1,118 @@
|
||||
/*
|
||||
* 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"
|
||||
#include "files.h"
|
||||
|
||||
extern uint8_t get_key_domain(file_t *fkey);
|
||||
|
||||
int cmd_key_wrap() {
|
||||
int r = 0;
|
||||
uint8_t key_id = P1(apdu);
|
||||
if (P2(apdu) != 0x92) {
|
||||
return SW_WRONG_P1P2();
|
||||
}
|
||||
if (!isUserAuthenticated) {
|
||||
return SW_SECURITY_STATUS_NOT_SATISFIED();
|
||||
}
|
||||
file_t *ef = search_file((KEY_PREFIX << 8) | key_id);
|
||||
if (!ef) {
|
||||
return SW_FILE_NOT_FOUND();
|
||||
}
|
||||
uint8_t kdom = get_key_domain(ef);
|
||||
if (kdom == 0xff) {
|
||||
return SW_REFERENCE_NOT_FOUND();
|
||||
}
|
||||
file_t *tf_kd = search_file(EF_KEY_DOMAIN);
|
||||
uint8_t *kdata = file_get_data(tf_kd), dkeks = kdata ? kdata[2 * kdom] : 0,
|
||||
current_dkeks = kdata ? kdata[2 * kdom + 1] : 0;
|
||||
if (dkeks != current_dkeks || dkeks == 0 || dkeks == 0xff) {
|
||||
return SW_REFERENCE_NOT_FOUND();
|
||||
}
|
||||
if (key_has_purpose(ef, ALGO_WRAP) == false) {
|
||||
return SW_CONDITIONS_NOT_SATISFIED();
|
||||
}
|
||||
file_t *prkd = search_file((PRKD_PREFIX << 8) | key_id);
|
||||
if (!prkd) {
|
||||
return SW_FILE_NOT_FOUND();
|
||||
}
|
||||
const uint8_t *dprkd = file_get_data(prkd);
|
||||
uint16_t wrap_len = MAX_DKEK_ENCODE_KEY_BUFFER, 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 != PICOKEY_OK) {
|
||||
mbedtls_rsa_free(&ctx);
|
||||
if (r == PICOKEY_VERIFICATION_FAILED) {
|
||||
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||
}
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
r = dkek_encode_key(kdom, &ctx, PICO_KEYS_KEY_RSA, res_APDU, &wrap_len, meta_tag, tag_len);
|
||||
mbedtls_rsa_free(&ctx);
|
||||
}
|
||||
else if (*dprkd == P15_KEYTYPE_ECC) {
|
||||
mbedtls_ecp_keypair ctx;
|
||||
mbedtls_ecp_keypair_init(&ctx);
|
||||
r = load_private_key_ec(&ctx, ef);
|
||||
if (r != PICOKEY_OK) {
|
||||
mbedtls_ecp_keypair_free(&ctx);
|
||||
if (r == PICOKEY_VERIFICATION_FAILED) {
|
||||
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||
}
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
r = dkek_encode_key(kdom, &ctx, PICO_KEYS_KEY_EC, res_APDU, &wrap_len, meta_tag, tag_len);
|
||||
mbedtls_ecp_keypair_free(&ctx);
|
||||
}
|
||||
else if (*dprkd == P15_KEYTYPE_AES) {
|
||||
uint8_t kdata_aes[64]; //maximum AES key size
|
||||
if (wait_button_pressed() == true) { //timeout
|
||||
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||
}
|
||||
|
||||
uint16_t key_size = file_get_size(ef), aes_type = PICO_KEYS_KEY_AES;
|
||||
memcpy(kdata_aes, file_get_data(ef), key_size);
|
||||
if (mkek_decrypt(kdata_aes, key_size) != 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
if (key_size == 64) {
|
||||
aes_type = PICO_KEYS_KEY_AES_512;
|
||||
}
|
||||
else if (key_size == 32) {
|
||||
aes_type = PICO_KEYS_KEY_AES_256;
|
||||
}
|
||||
else if (key_size == 24) {
|
||||
aes_type = PICO_KEYS_KEY_AES_192;
|
||||
}
|
||||
else if (key_size == 16) {
|
||||
aes_type = PICO_KEYS_KEY_AES_128;
|
||||
}
|
||||
r = dkek_encode_key(kdom, kdata_aes, aes_type, res_APDU, &wrap_len, meta_tag, tag_len);
|
||||
mbedtls_platform_zeroize(kdata_aes, sizeof(kdata_aes));
|
||||
}
|
||||
if (r != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
res_APDU_size = wrap_len;
|
||||
return SW_OK();
|
||||
}
|
||||
170
src/hsm/cmd_keypair_gen.c
Normal file
170
src/hsm/cmd_keypair_gen.c
Normal file
@@ -0,0 +1,170 @@
|
||||
/*
|
||||
* 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;
|
||||
|
||||
//sc_asn1_print_tags(apdu.data, apdu.nc);
|
||||
//DEBUG_DATA(apdu.data,apdu.nc);
|
||||
asn1_ctx_t ctxi, ctxo = { 0 };
|
||||
asn1_ctx_init(apdu.data, (uint16_t)apdu.nc, &ctxi);
|
||||
if (asn1_find_tag(&ctxi, 0x7f49, &ctxo) && asn1_len(&ctxo) > 0) {
|
||||
asn1_ctx_t oid = { 0 };
|
||||
if (asn1_find_tag(&ctxo, 0x6, &oid) && asn1_len(&oid) > 0) {
|
||||
if (memcmp(oid.data, OID_ID_TA_RSA_V1_5_SHA_256, oid.len) == 0) { //RSA
|
||||
asn1_ctx_t ex = { 0 }, ks = { 0 };
|
||||
uint32_t exponent = 65537, key_size = 2048;
|
||||
if (asn1_find_tag(&ctxo, 0x82, &ex) && asn1_len(&ex) > 0) {
|
||||
exponent = asn1_get_uint(&ex);
|
||||
}
|
||||
if (asn1_find_tag(&ctxo, 0x2, &ks) && asn1_len(&ks) > 0) {
|
||||
key_size = asn1_get_uint(&ks);
|
||||
}
|
||||
printf("KEYPAIR RSA %lu (%lx)\n",
|
||||
(unsigned long) key_size,
|
||||
(unsigned long) exponent);
|
||||
mbedtls_rsa_context rsa;
|
||||
mbedtls_rsa_init(&rsa);
|
||||
uint8_t index = 0;
|
||||
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 =
|
||||
(uint16_t)asn1_cvc_aut(&rsa, PICO_KEYS_KEY_RSA, res_APDU, 4096, NULL, 0)) == 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
ret = store_keys(&rsa, PICO_KEYS_KEY_RSA, key_id);
|
||||
if (ret != PICOKEY_OK) {
|
||||
mbedtls_rsa_free(&rsa);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
mbedtls_rsa_free(&rsa);
|
||||
}
|
||||
else if (memcmp(oid.data, OID_ID_TA_ECDSA_SHA_256, MIN(oid.len, 10)) == 0) { //ECC
|
||||
asn1_ctx_t prime = { 0 };
|
||||
if (asn1_find_tag(&ctxo, 0x81, &prime) != true) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
mbedtls_ecp_group_id ec_id = ec_get_curve_from_prime(prime.data, prime.len);
|
||||
printf("KEYPAIR ECC %d\n", ec_id);
|
||||
if (ec_id == MBEDTLS_ECP_DP_NONE) {
|
||||
return SW_FUNC_NOT_SUPPORTED();
|
||||
}
|
||||
if (ec_id == MBEDTLS_ECP_DP_CURVE25519 || ec_id == MBEDTLS_ECP_DP_CURVE448) {
|
||||
asn1_ctx_t g = { 0 };
|
||||
if (asn1_find_tag(&ctxo, 0x83, &g) != true) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
if (ec_id == MBEDTLS_ECP_DP_CURVE25519 && (g.data[0] != 9)) {
|
||||
ec_id = MBEDTLS_ECP_DP_ED25519;
|
||||
}
|
||||
else if (ec_id == MBEDTLS_ECP_DP_CURVE448 && (g.len != 56 || g.data[0] != 5)) {
|
||||
ec_id = MBEDTLS_ECP_DP_ED448;
|
||||
}
|
||||
}
|
||||
printf("KEYPAIR ECC %d\r\n", ec_id);
|
||||
mbedtls_ecdsa_context ecdsa;
|
||||
mbedtls_ecdsa_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();
|
||||
}
|
||||
asn1_ctx_t a91 = { 0 }, ext = { 0 };
|
||||
if (asn1_find_tag(&ctxi, 0x91, &a91) && asn1_len(&a91) > 0) {
|
||||
for (size_t n = 0; n < a91.len; n++) {
|
||||
if (a91.data[n] == ALGO_EC_DH_XKEK) {
|
||||
asn1_ctx_t a92 = {0};
|
||||
if (!asn1_find_tag(&ctxi, 0x92, &a92) || asn1_len(&a92) == 0) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
if (a92.data[0] > MAX_KEY_DOMAINS) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
file_t *tf_xkek = search_file(EF_XKEK + a92.data[0]);
|
||||
if (!tf_xkek) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
ext.len = 2 + 2 + (uint16_t)strlen(OID_ID_KEY_DOMAIN_UID) + 2 + file_get_size(
|
||||
tf_xkek);
|
||||
ext.data = (uint8_t *) calloc(1, ext.len);
|
||||
uint8_t *pe = ext.data;
|
||||
*pe++ = 0x73;
|
||||
*pe++ = (uint8_t)ext.len - 2;
|
||||
*pe++ = 0x6;
|
||||
*pe++ = (uint8_t)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++ = (uint8_t)file_get_size(tf_xkek);
|
||||
memcpy(pe, file_get_data(tf_xkek), file_get_size(tf_xkek));
|
||||
}
|
||||
}
|
||||
}
|
||||
if ((res_APDU_size =
|
||||
(uint16_t)asn1_cvc_aut(&ecdsa, PICO_KEYS_KEY_EC, res_APDU, 4096, ext.data, ext.len)) == 0) {
|
||||
if (ext.data) {
|
||||
free(ext.data);
|
||||
}
|
||||
mbedtls_ecdsa_free(&ecdsa);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
if (ext.data) {
|
||||
free(ext.data);
|
||||
}
|
||||
ret = store_keys(&ecdsa, PICO_KEYS_KEY_EC, key_id);
|
||||
mbedtls_ecdsa_free(&ecdsa);
|
||||
if (ret != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
else {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
if (find_and_store_meta_key(key_id) != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
file_t *fpk = file_new((EE_CERTIFICATE_PREFIX << 8) | key_id);
|
||||
ret = file_put_data(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();
|
||||
}
|
||||
70
src/hsm/cmd_list_keys.c
Normal file
70
src/hsm/cmd_list_keys.c
Normal file
@@ -0,0 +1,70 @@
|
||||
/*
|
||||
* 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_file(EF_PRKD_DEV)) {
|
||||
res_APDU[res_APDU_size++] = EF_PRKD_DEV >> 8;
|
||||
res_APDU[res_APDU_size++] = EF_PRKD_DEV & 0xff;
|
||||
}
|
||||
if (search_file(EF_KEY_DEV)) {
|
||||
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;
|
||||
}
|
||||
}
|
||||
#if !defined(ENABLE_EMULATION) && !defined(ESP_PLATFORM)
|
||||
if ((apdu.rlen + 2 + 10) % 64 == 0) { // FIX for strange behaviour with PSCS and multiple of 64
|
||||
res_APDU[res_APDU_size++] = 0;
|
||||
res_APDU[res_APDU_size++] = 0;
|
||||
}
|
||||
#endif
|
||||
return SW_OK();
|
||||
}
|
||||
89
src/hsm/cmd_mse.c
Normal file
89
src/hsm/cmd_mse.c
Normal file
@@ -0,0 +1,89 @@
|
||||
/*
|
||||
* 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;
|
||||
uint16_t tag_len = 0;
|
||||
asn1_ctx_t ctxi;
|
||||
asn1_ctx_init(apdu.data, (uint16_t)apdu.nc, &ctxi);
|
||||
while (walk_tlv(&ctxi, &p, &tag, &tag_len, &tag_data)) {
|
||||
if (tag == 0x80) {
|
||||
if (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) == PICOKEY_OK) {
|
||||
return SW_OK();
|
||||
}
|
||||
}
|
||||
else if (p2 == 0xA4) { /* Aut */
|
||||
for (uint8_t i = 0; i < MAX_PUK; i++) {
|
||||
file_t *ef = search_file(EF_PUK + i);
|
||||
if (!ef) {
|
||||
break;
|
||||
}
|
||||
if (!file_has_data(ef)) {
|
||||
break;
|
||||
}
|
||||
uint16_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;
|
||||
if (puk_status[i] == 1) {
|
||||
return SW_CONDITIONS_NOT_SATISFIED(); // It is correct
|
||||
}
|
||||
return SW_OK();
|
||||
}
|
||||
}
|
||||
}
|
||||
return SW_REFERENCE_NOT_FOUND();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
return SW_INCORRECT_P1P2();
|
||||
}
|
||||
return SW_OK();
|
||||
}
|
||||
161
src/hsm/cmd_pso.c
Normal file
161
src/hsm/cmd_pso.c
Normal file
@@ -0,0 +1,161 @@
|
||||
/*
|
||||
* 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, uint16_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((uint16_t)apdu.nc, NULL);
|
||||
memmove(apdu.data + tlv_len, apdu.data, apdu.nc);
|
||||
memcpy(apdu.data, "\x7F\x21", 2);
|
||||
format_tlv_len((uint16_t)apdu.nc, apdu.data + 2);
|
||||
apdu.nc += tlv_len;
|
||||
}
|
||||
int r = cvc_verify(apdu.data, (uint16_t)apdu.nc, current_puk->cvcert, current_puk->cvcert_len);
|
||||
if (r != PICOKEY_OK) {
|
||||
if (r == PICOKEY_WRONG_DATA) {
|
||||
return SW_DATA_INVALID();
|
||||
}
|
||||
else if (r == PICOKEY_WRONG_SIGNATURE) {
|
||||
return SW_CONDITIONS_NOT_SATISFIED();
|
||||
}
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
for (uint8_t i = 0; i < 0xfe; i++) {
|
||||
uint16_t fid = (CA_CERTIFICATE_PREFIX << 8) | i;
|
||||
file_t *ca_ef = search_file(fid);
|
||||
if (!ca_ef) {
|
||||
ca_ef = file_new(fid);
|
||||
file_put_data(ca_ef, apdu.data, (uint16_t)apdu.nc);
|
||||
if (add_cert_puk_store(file_get_data(ca_ef), file_get_size(ca_ef),
|
||||
false) != PICOKEY_OK) {
|
||||
return SW_FILE_FULL();
|
||||
}
|
||||
|
||||
uint16_t chr_len = 0;
|
||||
const uint8_t *chr = cvc_get_chr(apdu.data, (uint16_t)apdu.nc, &chr_len);
|
||||
if (chr == NULL) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
uint16_t puk_len = 0, puk_bin_len = 0;
|
||||
const uint8_t *puk = cvc_get_pub(apdu.data, (uint16_t)apdu.nc, &puk_len), *puk_bin = NULL;
|
||||
if (puk == NULL) {
|
||||
return SW_WRONG_DATA();
|
||||
}
|
||||
uint16_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, (uint16_t)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();
|
||||
}
|
||||
uint16_t plen = (uint16_t)mbedtls_mpi_size(&grp.P);
|
||||
uint16_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);
|
||||
uint16_t cd_len = (uint16_t)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));
|
||||
r = (int)asn1_build_cert_description(chr,
|
||||
chr_len,
|
||||
puk_bin,
|
||||
puk_bin_len,
|
||||
fid,
|
||||
buf,
|
||||
cd_len);
|
||||
file_put_data(cd_ef, buf, cd_len);
|
||||
free(buf);
|
||||
if (r == 0) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
low_flash_available();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
else {
|
||||
return SW_INCORRECT_P1P2();
|
||||
}
|
||||
return SW_OK();
|
||||
}
|
||||
99
src/hsm/cmd_puk_auth.c
Normal file
99
src/hsm/cmd_puk_auth.c
Normal file
@@ -0,0 +1,99 @@
|
||||
/*
|
||||
* 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_file(EF_PUKAUT);
|
||||
if (!file_has_data(ef_puk)) {
|
||||
if (apdu.nc > 0) {
|
||||
return SW_FILE_NOT_FOUND();
|
||||
}
|
||||
return SW_INCORRECT_P1P2();
|
||||
}
|
||||
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 (uint8_t i = 0; i < puk_data[0]; i++) {
|
||||
ef = search_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;
|
||||
file_put_data(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_file(EF_PUK + p2);
|
||||
if (!ef) { /* Never should not happen */
|
||||
return SW_MEMORY_FAILURE();
|
||||
}
|
||||
}
|
||||
file_put_data(ef, apdu.data, (uint16_t)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_file(EF_PUK + p2);
|
||||
if (!ef) {
|
||||
return SW_INCORRECT_P1P2();
|
||||
}
|
||||
if (!file_has_data(ef)) {
|
||||
return SW_REFERENCE_NOT_FOUND();
|
||||
}
|
||||
uint16_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();
|
||||
}
|
||||
98
src/hsm/cmd_read_binary.c
Normal file
98
src/hsm/cmd_read_binary.c
Normal file
@@ -0,0 +1,98 @@
|
||||
/*
|
||||
* 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 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_file(p1 & 0x1f))) {
|
||||
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_file(p2 & 0x1f))) {
|
||||
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_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 ((ef->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 = (uint16_t)((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_WARNING_EOF();
|
||||
}
|
||||
|
||||
//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();
|
||||
}
|
||||
108
src/hsm/cmd_reset_retry.c
Normal file
108
src/hsm/cmd_reset_retry.c
Normal file
@@ -0,0 +1,108 @@
|
||||
/*
|
||||
* 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) {
|
||||
uint8_t newpin_len = 0;
|
||||
if (P1(apdu) == 0x0) {
|
||||
uint8_t so_pin_len = file_read_uint8(file_sopin);
|
||||
if ((uint16_t)apdu.nc <= so_pin_len + 1) {
|
||||
return SW_WRONG_LENGTH();
|
||||
}
|
||||
uint16_t r = check_pin(file_sopin, apdu.data, so_pin_len);
|
||||
if (r != 0x9000) {
|
||||
return r;
|
||||
}
|
||||
newpin_len = (uint8_t)apdu.nc - so_pin_len;
|
||||
}
|
||||
else if (P1(apdu) == 0x2) {
|
||||
if (!has_session_sopin) {
|
||||
return SW_CONDITIONS_NOT_SATISFIED();
|
||||
}
|
||||
if (apdu.nc > 16) {
|
||||
return SW_WRONG_LENGTH();
|
||||
}
|
||||
newpin_len = (uint8_t)apdu.nc;
|
||||
}
|
||||
uint8_t dhash[33];
|
||||
dhash[0] = newpin_len;
|
||||
double_hash_pin(apdu.data + (apdu.nc - newpin_len), newpin_len, dhash + 1);
|
||||
file_put_data(file_pin1, dhash, sizeof(dhash));
|
||||
if (pin_reset_retries(file_pin1, true) != PICOKEY_OK) {
|
||||
return SW_MEMORY_FAILURE();
|
||||
}
|
||||
uint8_t mkek[MKEK_SIZE];
|
||||
int r = load_mkek(mkek); //loads the MKEK with SO pin
|
||||
if (r != PICOKEY_OK) {
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
hash_multi(apdu.data + (apdu.nc - newpin_len), newpin_len, session_pin);
|
||||
has_session_pin = true;
|
||||
r = store_mkek(mkek);
|
||||
release_mkek(mkek);
|
||||
if (r != PICOKEY_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) {
|
||||
uint8_t so_pin_len = file_read_uint8(file_sopin);
|
||||
if (apdu.nc != so_pin_len) {
|
||||
return SW_WRONG_LENGTH();
|
||||
}
|
||||
uint16_t r = check_pin(file_sopin, apdu.data, so_pin_len);
|
||||
if (r != 0x9000) {
|
||||
return r;
|
||||
}
|
||||
}
|
||||
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) != PICOKEY_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|FILE_TYPE_WORKING_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 (fid != 0x0 && !(pe = search_file(fid))) {
|
||||
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, (uint16_t)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, (uint8_t)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, (uint8_t)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] = (uint8_t)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();
|
||||
}
|
||||
320
src/hsm/cmd_signature.c
Normal file
320
src/hsm/cmd_signature.c
Normal file
@@ -0,0 +1,320 @@
|
||||
/*
|
||||
* 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 "crypto_utils.h"
|
||||
#include "sc_hsm.h"
|
||||
#include "asn1.h"
|
||||
#include "mbedtls/oid.h"
|
||||
#include "random.h"
|
||||
#include "mbedtls/eddsa.h"
|
||||
|
||||
extern mbedtls_ecp_keypair hd_context;
|
||||
extern uint8_t hd_keytype;
|
||||
|
||||
//-----
|
||||
/* 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;
|
||||
uint16_t hdr_len;
|
||||
uint16_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,
|
||||
uint16_t in_len,
|
||||
uint8_t *out_dat,
|
||||
uint16_t *out_len) {
|
||||
for (int i = 0; digest_info_prefix[i].algorithm != 0; i++) {
|
||||
uint16_t hdr_len = digest_info_prefix[i].hdr_len, hash_len = digest_info_prefix[i].hash_len;
|
||||
const uint8_t *hdr = digest_info_prefix[i].hdr;
|
||||
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 PICOKEY_OK;
|
||||
}
|
||||
if (*out_len < hash_len) {
|
||||
return PICOKEY_WRONG_DATA;
|
||||
}
|
||||
memmove(out_dat, in_dat + hdr_len, hash_len);
|
||||
*out_len = hash_len;
|
||||
return PICOKEY_OK;
|
||||
}
|
||||
}
|
||||
return PICOKEY_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_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();
|
||||
}
|
||||
uint16_t 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 != PICOKEY_OK) {
|
||||
mbedtls_rsa_free(&ctx);
|
||||
if (r == PICOKEY_VERIFICATION_FAILED) {
|
||||
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||
}
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
asn1_ctx_t hash = {.len = (uint16_t)apdu.nc, .data = apdu.data};
|
||||
if (p2 == ALGO_RSA_PKCS1) { //DigestInfo attached
|
||||
uint16_t nc = (uint16_t)apdu.nc;
|
||||
if (pkcs1_strip_digest_info_prefix(&md, apdu.data, (uint16_t)apdu.nc, apdu.data,
|
||||
&nc) != PICOKEY_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);
|
||||
asn1_ctx_t ctxi, ctxo = { 0 }, oid = { 0 };
|
||||
asn1_ctx_init(apdu.data, (uint16_t)apdu.nc, &ctxi);
|
||||
if (asn1_find_tag(&ctxi, 0x30, &ctxo) && asn1_len(&ctxo) > 0) {
|
||||
asn1_ctx_t a30 = { 0 };
|
||||
if (asn1_find_tag(&ctxo, 0x30, &a30) && asn1_len(&a30) > 0) {
|
||||
asn1_find_tag(&a30, 0x6, &oid);
|
||||
}
|
||||
asn1_find_tag(&ctxo, 0x4, &hash);
|
||||
}
|
||||
if (asn1_len(&oid)) {
|
||||
if (memcmp(oid.data, MBEDTLS_OID_DIGEST_ALG_SHA1, oid.len) == 0) {
|
||||
md = MBEDTLS_MD_SHA1;
|
||||
}
|
||||
else if (memcmp(oid.data, MBEDTLS_OID_DIGEST_ALG_SHA224, oid.len) == 0) {
|
||||
md = MBEDTLS_MD_SHA224;
|
||||
}
|
||||
else if (memcmp(oid.data, MBEDTLS_OID_DIGEST_ALG_SHA256, oid.len) == 0) {
|
||||
md = MBEDTLS_MD_SHA256;
|
||||
}
|
||||
else if (memcmp(oid.data, MBEDTLS_OID_DIGEST_ALG_SHA384, oid.len) == 0) {
|
||||
md = MBEDTLS_MD_SHA384;
|
||||
}
|
||||
else if (memcmp(oid.data, 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 && asn1_len(&oid) == 0) {
|
||||
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.data, 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_ecp_keypair ctx;
|
||||
mbedtls_ecp_keypair_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_ec(&ctx, fkey);
|
||||
if (r != PICOKEY_OK) {
|
||||
mbedtls_ecp_keypair_free(&ctx);
|
||||
if (r == PICOKEY_VERIFICATION_FAILED) {
|
||||
return SW_SECURE_MESSAGE_EXEC_ERROR();
|
||||
}
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
size_t olen = 0;
|
||||
uint8_t buf[MBEDTLS_ECDSA_MAX_LEN];
|
||||
if (ctx.grp.id == MBEDTLS_ECP_DP_ED25519 || ctx.grp.id == MBEDTLS_ECP_DP_ED448) {
|
||||
r = mbedtls_eddsa_write_signature(&ctx, apdu.data, apdu.nc, buf, sizeof(buf), &olen, MBEDTLS_EDDSA_PURE, NULL, 0, random_gen, NULL);
|
||||
}
|
||||
else {
|
||||
r = mbedtls_ecdsa_write_signature(&ctx, md, apdu.data, apdu.nc, buf, MBEDTLS_ECDSA_MAX_LEN,
|
||||
&olen, random_gen, NULL);
|
||||
}
|
||||
if (r != 0) {
|
||||
mbedtls_ecp_keypair_free(&ctx);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
memcpy(res_APDU, buf, olen);
|
||||
res_APDU_size = (uint16_t)olen;
|
||||
mbedtls_ecp_keypair_free(&ctx);
|
||||
}
|
||||
else if (p2 == ALGO_HD) {
|
||||
size_t olen = 0;
|
||||
uint8_t buf[MBEDTLS_ECDSA_MAX_LEN] = {0};
|
||||
if (hd_context.grp.id == MBEDTLS_ECP_DP_NONE) {
|
||||
mbedtls_ecdsa_free(&hd_context);
|
||||
return SW_CONDITIONS_NOT_SATISFIED();
|
||||
}
|
||||
if (hd_keytype != 0x1 && hd_keytype != 0x2) {
|
||||
mbedtls_ecdsa_free(&hd_context);
|
||||
return SW_INCORRECT_PARAMS();
|
||||
}
|
||||
md = MBEDTLS_MD_SHA256;
|
||||
if (mbedtls_ecdsa_write_signature(&hd_context, md, apdu.data, apdu.nc, buf,
|
||||
MBEDTLS_ECDSA_MAX_LEN,
|
||||
&olen, random_gen, NULL) != 0) {
|
||||
mbedtls_ecdsa_free(&hd_context);
|
||||
return SW_EXEC_ERROR();
|
||||
}
|
||||
memcpy(res_APDU, buf, olen);
|
||||
res_APDU_size = (uint16_t)olen;
|
||||
mbedtls_ecdsa_free(&hd_context);
|
||||
hd_keytype = 0;
|
||||
}
|
||||
else {
|
||||
return SW_INCORRECT_P1P2();
|
||||
}
|
||||
decrement_key_counter(fkey);
|
||||
return SW_OK();
|
||||
}
|
||||
102
src/hsm/cmd_update_ef.c
Normal file
102
src/hsm/cmd_update_ef.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 "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;
|
||||
}
|
||||
/*
|
||||
// This should not happen
|
||||
else if (p1 != EE_CERTIFICATE_PREFIX && p1 != PRKD_PREFIX && p1 != CA_CERTIFICATE_PREFIX &&
|
||||
p1 != CD_PREFIX && p1 != DATA_PREFIX && p1 != DCOD_PREFIX &&
|
||||
p1 != 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;
|
||||
uint16_t tag_len = 0;
|
||||
asn1_ctx_t ctxi;
|
||||
asn1_ctx_init(apdu.data, (uint16_t)apdu.nc, &ctxi);
|
||||
while (walk_tlv(&ctxi, &p, &tag, &tag_len, &tag_data)) {
|
||||
if (tag == 0x54) { //ofset tag
|
||||
for (size_t i = 1; i <= tag_len; i++) {
|
||||
offset |= (*tag_data++ << (8 * (tag_len - i)));
|
||||
}
|
||||
}
|
||||
else if (tag == 0x53) { //data
|
||||
data_len = (uint16_t)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_file(fid))) { //if does not exist, create it
|
||||
//return SW_FILE_NOT_FOUND();
|
||||
ef = file_new(fid);
|
||||
}
|
||||
if (offset == 0) {
|
||||
int r = file_put_data(ef, data, data_len);
|
||||
if (r != PICOKEY_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 = file_put_data(ef, data_merge, offset + data_len);
|
||||
free(data_merge);
|
||||
if (r != PICOKEY_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, (uint16_t)apdu.nc);
|
||||
}
|
||||
if (file_read_uint8(file_retries_pin1) == 0) {
|
||||
return SW_PIN_BLOCKED();
|
||||
}
|
||||
return set_res_sw(0x63, 0xc0 | file_read_uint8(file_retries_pin1));
|
||||
}
|
||||
else if (p2 == 0x88) { //SOPin
|
||||
if (file_read_uint8(file_sopin) == 0) { //not initialized
|
||||
return SW_REFERENCE_NOT_FOUND();
|
||||
}
|
||||
if (apdu.nc > 0) {
|
||||
return check_pin(file_sopin, apdu.data, (uint16_t)apdu.nc);
|
||||
}
|
||||
if (file_read_uint8(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_retries_sopin));
|
||||
}
|
||||
else if (p2 == 0x85) {
|
||||
return SW_OK();
|
||||
}
|
||||
return SW_REFERENCE_NOT_FOUND();
|
||||
}
|
||||
861
src/hsm/cvc.c
861
src/hsm/cvc.c
File diff suppressed because it is too large
Load Diff
102
src/hsm/cvc.h
102
src/hsm/cvc.h
@@ -1,17 +1,17 @@
|
||||
/*
|
||||
/*
|
||||
* 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
|
||||
*
|
||||
* 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
|
||||
* 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
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
@@ -19,33 +19,87 @@
|
||||
#define _CVC_H_
|
||||
|
||||
#include <stdlib.h>
|
||||
#if !defined(ENABLE_EMULATION) && !defined(ESP_PLATFORM)
|
||||
#include "pico/stdlib.h"
|
||||
#else
|
||||
#include <stdbool.h>
|
||||
#endif
|
||||
#include "mbedtls/ecp.h"
|
||||
|
||||
typedef struct PUK {
|
||||
const uint8_t *puk;
|
||||
size_t puk_len;
|
||||
uint16_t puk_len;
|
||||
const uint8_t *car;
|
||||
size_t car_len;
|
||||
uint16_t car_len;
|
||||
const uint8_t *chr;
|
||||
size_t chr_len;
|
||||
uint16_t chr_len;
|
||||
const uint8_t *cvcert;
|
||||
size_t cvcert_len;
|
||||
uint16_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);
|
||||
extern size_t asn1_cvc_aut(void *rsa_ecdsa, uint8_t key_type, uint8_t *buf, size_t buf_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 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 uint16_t asn1_cvc_cert(void *rsa_ecdsa,
|
||||
uint8_t key_type,
|
||||
uint8_t *buf,
|
||||
uint16_t buf_len,
|
||||
const uint8_t *ext,
|
||||
uint16_t ext_len,
|
||||
bool full);
|
||||
extern uint16_t asn1_cvc_aut(void *rsa_ecdsa,
|
||||
uint8_t key_type,
|
||||
uint8_t *buf,
|
||||
uint16_t buf_len,
|
||||
const uint8_t *ext,
|
||||
uint16_t ext_len);
|
||||
extern uint16_t asn1_build_cert_description(const uint8_t *label,
|
||||
uint16_t label_len,
|
||||
const uint8_t *puk,
|
||||
uint16_t puk_len,
|
||||
uint16_t fid,
|
||||
uint8_t *buf,
|
||||
uint16_t buf_len);
|
||||
extern const uint8_t *cvc_get_field(const uint8_t *data, uint16_t len, uint16_t *olen, uint16_t tag);
|
||||
extern const uint8_t *cvc_get_car(const uint8_t *data, uint16_t len, uint16_t *olen);
|
||||
extern const uint8_t *cvc_get_chr(const uint8_t *data, uint16_t len, uint16_t *olen);
|
||||
extern const uint8_t *cvc_get_pub(const uint8_t *data, uint16_t len, uint16_t *olen);
|
||||
extern const uint8_t *cvc_get_ext(const uint8_t *data, uint16_t len, uint16_t *olen);
|
||||
extern int cvc_verify(const uint8_t *cert, uint16_t cert_len, const uint8_t *ca, uint16_t ca_len);
|
||||
extern mbedtls_ecp_group_id cvc_inherite_ec_group(const uint8_t *ca, uint16_t ca_len);
|
||||
extern int puk_verify(const uint8_t *sig,
|
||||
uint16_t sig_len,
|
||||
const uint8_t *hash,
|
||||
uint16_t hash_len,
|
||||
const uint8_t *ca,
|
||||
uint16_t ca_len);
|
||||
extern uint16_t asn1_build_prkd_ecc(const uint8_t *label,
|
||||
uint16_t label_len,
|
||||
const uint8_t *keyid,
|
||||
uint16_t keyid_len,
|
||||
uint16_t keysize,
|
||||
uint8_t *buf,
|
||||
uint16_t buf_len);
|
||||
extern uint16_t asn1_build_prkd_rsa(const uint8_t *label,
|
||||
uint16_t label_len,
|
||||
const uint8_t *keyid,
|
||||
uint16_t keyid_len,
|
||||
uint16_t keysize,
|
||||
uint8_t *buf,
|
||||
uint16_t buf_len);
|
||||
extern uint16_t asn1_build_prkd_aes(const uint8_t *label,
|
||||
uint16_t label_len,
|
||||
const uint8_t *keyid,
|
||||
uint16_t keyid_len,
|
||||
uint16_t keysize,
|
||||
uint8_t *buf,
|
||||
uint16_t buf_len);
|
||||
extern uint16_t asn1_build_prkd_generic(const uint8_t *label,
|
||||
uint16_t label_len,
|
||||
const uint8_t *keyid,
|
||||
uint16_t keyid_len,
|
||||
uint16_t keysize,
|
||||
int key_tpe,
|
||||
uint8_t *buf,
|
||||
uint16_t buf_len);
|
||||
#endif
|
||||
|
||||
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
|
||||
139
src/hsm/files.c
139
src/hsm/files.c
@@ -1,17 +1,17 @@
|
||||
/*
|
||||
/*
|
||||
* 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
|
||||
*
|
||||
* 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
|
||||
* 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
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
@@ -19,47 +19,98 @@
|
||||
|
||||
extern const uint8_t sc_hsm_aid[];
|
||||
extern int parse_token_info(const file_t *f, int mode);
|
||||
extern int parse_cvca(const file_t *f, int mode);
|
||||
extern int parse_ef_dir(const file_t *f, int mode);
|
||||
|
||||
file_t file_entries[] = {
|
||||
/* 0 */ { .fid = 0x3f00 , .parent = 0xff, .name = NULL, .type = FILE_TYPE_DF, .data = NULL, .ef_structure = 0, .acl = {0} }, // MF
|
||||
/* 1 */ { .fid = 0x2f00 , .parent = 0, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} }, //EF.DIR
|
||||
/* 2 */ { .fid = 0x2f01 , .parent = 0, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} }, //EF.ATR
|
||||
/* 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
|
||||
/* 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
|
||||
/* 5 */ { .fid = 0x5015 , .parent = 0, .name = NULL, .type = FILE_TYPE_DF, .data = NULL, .ef_structure = 0, .acl = {0} }, //DF.PKCS15
|
||||
/* 6 */ { .fid = 0x5031 , .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} }, //EF.ODF
|
||||
/* 7 */ { .fid = 0x5032 , .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} }, //EF.TokenInfo
|
||||
/* 8 */ { .fid = 0x5033 , .parent = 0, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} }, //EF.UnusedSpace
|
||||
/* 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)
|
||||
/* 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)
|
||||
/* 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, .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, .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, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0xff} }, //End Entity Certificate Device
|
||||
///* 28 */ { .fid = 0x0000, .parent = 0, .name = openpgpcard_aid, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} },
|
||||
/* 29 */ { .fid = 0x0000, .parent = 5, .name = sc_hsm_aid, .type = FILE_TYPE_WORKING_EF, .data = NULL, .ef_structure = FILE_EF_TRANSPARENT, .acl = {0} },
|
||||
/* 30 */ { .fid = 0x0000, .parent = 0xff, .name = NULL, .type = FILE_TYPE_UNKNOWN, .data = NULL, .ef_structure = 0, .acl = {0} } //end
|
||||
/* 0 */ { .fid = 0x3f00, .parent = 0xff, .name = NULL, .type = FILE_TYPE_DF, .data = NULL,
|
||||
.ef_structure = 0, .acl = { 0 } }, // MF
|
||||
/* 1 */ { .fid = 0x2f00, .parent = 0, .name = NULL, .type = FILE_TYPE_WORKING_EF | FILE_DATA_FUNC, .data = (uint8_t *) parse_ef_dir,
|
||||
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.DIR
|
||||
/* 2 */ { .fid = 0x2f01, .parent = 0, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL,
|
||||
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.ATR
|
||||
/* 3 */ { .fid = EF_TERMCA, .parent = 0, .name = NULL,
|
||||
.type = FILE_TYPE_WORKING_EF | FILE_DATA_FLASH | FILE_PERSISTENT, .data = NULL,
|
||||
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.GDO
|
||||
/* 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
|
||||
/* 5 */ { .fid = 0x5015, .parent = 0, .name = NULL, .type = FILE_TYPE_DF, .data = NULL,
|
||||
.ef_structure = 0, .acl = { 0 } }, //DF.PKCS15
|
||||
/* 6 */ { .fid = 0x5031, .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL,
|
||||
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.ODF
|
||||
/* 7 */ { .fid = 0x5032, .parent = 5, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL,
|
||||
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.TokenInfo
|
||||
/* 8 */ { .fid = 0x5033, .parent = 0, .name = NULL, .type = FILE_TYPE_WORKING_EF, .data = NULL,
|
||||
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0 } }, //EF.UnusedSpace
|
||||
/* 9 */ { .fid = EF_PIN1, .parent = 5, .name = NULL,
|
||||
.type = FILE_TYPE_INTERNAL_EF | FILE_DATA_FLASH, .data = NULL,
|
||||
.ef_structure = FILE_EF_TRANSPARENT, .acl = { 0xff } }, //PIN (PIN1)
|
||||
/* 10 */ { .fid = EF_PIN1_MAX_RETRIES, .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)
|
||||
/* 11 */ { .fid = EF_PIN1_RETRIES, .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 = EF_SOPIN, .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 = EF_SOPIN_MAX_RETRIES, .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 = EF_SOPIN_RETRIES, .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_NOT_KNOWN, .data = NULL,
|
||||
.ef_structure = 0, .acl = { 0 } } //end
|
||||
};
|
||||
|
||||
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_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_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_sc_hsm = &file_entries[sizeof(file_entries) / sizeof(file_t) - 2];
|
||||
file_t *file_pin1 = NULL;
|
||||
file_t *file_retries_pin1 = NULL;
|
||||
file_t *file_sopin = NULL;
|
||||
file_t *file_retries_sopin = NULL;
|
||||
file_t *file_retries_sopin = NULL;
|
||||
|
||||
@@ -1,17 +1,17 @@
|
||||
/*
|
||||
/*
|
||||
* 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
|
||||
*
|
||||
* 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
|
||||
* 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
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
@@ -22,10 +22,20 @@
|
||||
#include "file.h"
|
||||
|
||||
#define EF_DEVOPS 0x100E
|
||||
#define EF_MKEK 0x100A
|
||||
#define EF_MKEK_SO 0x100B
|
||||
#define EF_XKEK 0x1070
|
||||
#define EF_PIN1 0x1081
|
||||
#define EF_PIN1_MAX_RETRIES 0x1082
|
||||
#define EF_PIN1_RETRIES 0x1083
|
||||
#define EF_SOPIN 0x1088
|
||||
#define EF_SOPIN_MAX_RETRIES 0x1089
|
||||
#define EF_SOPIN_RETRIES 0x108A
|
||||
#define EF_DKEK 0x1090
|
||||
#define EF_KEY_DOMAIN 0x10A0
|
||||
#define EF_PUKAUT 0x10C0
|
||||
#define EF_PUK 0X10D0
|
||||
#define EF_PUK 0x10D0
|
||||
#define EF_MASTER_SEED 0x1110
|
||||
#define EF_PRKDFS 0x6040
|
||||
#define EF_PUKDFS 0x6041
|
||||
#define EF_CDFS 0x6042
|
||||
@@ -37,9 +47,13 @@
|
||||
#define EF_PRKD_DEV 0xC400
|
||||
#define EF_EE_DEV 0xCE00
|
||||
|
||||
#define EF_TERMCA 0x2F02
|
||||
#define EF_TOKENINFO 0x2F03
|
||||
#define EF_STATICTOKEN 0xCB00
|
||||
|
||||
extern file_t *file_pin1;
|
||||
extern file_t *file_retries_pin1;
|
||||
extern file_t *file_sopin;
|
||||
extern file_t *file_retries_sopin;
|
||||
|
||||
#endif
|
||||
#endif
|
||||
|
||||
697
src/hsm/kek.c
Normal file
697
src/hsm/kek.c
Normal file
@@ -0,0 +1,697 @@
|
||||
/*
|
||||
* 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 "stdlib.h"
|
||||
#if !defined(ENABLE_EMULATION) && !defined(ESP_PLATFORM)
|
||||
#include "pico/stdlib.h"
|
||||
#endif
|
||||
#include "kek.h"
|
||||
#include "crypto_utils.h"
|
||||
#include "random.h"
|
||||
#include "mbedtls/md.h"
|
||||
#include "mbedtls/cmac.h"
|
||||
#include "mbedtls/rsa.h"
|
||||
#include "mbedtls/ecdsa.h"
|
||||
#include "mbedtls/chachapoly.h"
|
||||
#include "files.h"
|
||||
#include "otp.h"
|
||||
|
||||
extern bool has_session_pin, has_session_sopin;
|
||||
extern uint8_t session_pin[32], session_sopin[32];
|
||||
uint8_t mkek_mask[MKEK_KEY_SIZE];
|
||||
bool has_mkek_mask = false;
|
||||
uint8_t pending_save_dkek = 0xff;
|
||||
|
||||
#define POLY 0xedb88320
|
||||
|
||||
uint32_t crc32c(const uint8_t *buf, size_t len) {
|
||||
uint32_t crc = 0xffffffff;
|
||||
while (len--) {
|
||||
crc ^= *buf++;
|
||||
for (int k = 0; k < 8; k++) {
|
||||
crc = (crc >> 1) ^ (POLY & (0 - (crc & 1)));
|
||||
}
|
||||
}
|
||||
return ~crc;
|
||||
}
|
||||
|
||||
int load_mkek(uint8_t *mkek) {
|
||||
if (has_session_pin == false && has_session_sopin == false) {
|
||||
return PICOKEY_NO_LOGIN;
|
||||
}
|
||||
const uint8_t *pin = NULL;
|
||||
if (pin == NULL && has_session_pin == true) {
|
||||
file_t *tf = search_file(EF_MKEK);
|
||||
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_file(EF_MKEK_SO);
|
||||
if (file_has_data(tf)) {
|
||||
memcpy(mkek, file_get_data(tf), MKEK_SIZE);
|
||||
pin = session_sopin;
|
||||
}
|
||||
}
|
||||
if (pin == NULL) { //Should never happen
|
||||
return PICOKEY_EXEC_ERROR;
|
||||
}
|
||||
|
||||
int ret = aes_decrypt_cfb_256(pin, MKEK_IV(mkek), MKEK_KEY(mkek), MKEK_KEY_SIZE + MKEK_KEY_CS_SIZE);
|
||||
if (ret != 0) {
|
||||
return PICOKEY_EXEC_ERROR;
|
||||
}
|
||||
if (crc32c(MKEK_KEY(mkek), MKEK_KEY_SIZE) != *(uint32_t *) MKEK_CHECKSUM(mkek)) {
|
||||
return PICOKEY_WRONG_DKEK;
|
||||
}
|
||||
if (has_mkek_mask || otp_key_1) {
|
||||
const uint8_t *mask = otp_key_1 ? otp_key_1 : mkek_mask;
|
||||
for (int i = 0; i < MKEK_KEY_SIZE; i++) {
|
||||
MKEK_KEY(mkek)[i] ^= mask[i];
|
||||
}
|
||||
}
|
||||
return PICOKEY_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_file(EF_DKEK + id);
|
||||
if (!file_has_data(tf)) {
|
||||
return PICOKEY_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 PICOKEY_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_file(EF_MKEK);
|
||||
if (!tf) {
|
||||
release_mkek(tmp_mkek);
|
||||
release_mkek(tmp_mkek_pin);
|
||||
return PICOKEY_ERR_FILE_NOT_FOUND;
|
||||
}
|
||||
aes_encrypt_cfb_256(session_pin, MKEK_IV(tmp_mkek_pin), MKEK_KEY(tmp_mkek_pin), MKEK_KEY_SIZE + MKEK_KEY_CS_SIZE);
|
||||
file_put_data(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_file(EF_MKEK_SO);
|
||||
if (!tf) {
|
||||
release_mkek(tmp_mkek);
|
||||
release_mkek(tmp_mkek_sopin);
|
||||
return PICOKEY_ERR_FILE_NOT_FOUND;
|
||||
}
|
||||
aes_encrypt_cfb_256(session_sopin, MKEK_IV(tmp_mkek_sopin), MKEK_KEY(tmp_mkek_sopin), MKEK_KEY_SIZE + MKEK_KEY_CS_SIZE);
|
||||
file_put_data(tf, tmp_mkek_sopin, MKEK_SIZE);
|
||||
release_mkek(tmp_mkek_sopin);
|
||||
}
|
||||
low_flash_available();
|
||||
release_mkek(tmp_mkek);
|
||||
return PICOKEY_OK;
|
||||
}
|
||||
|
||||
int store_dkek_key(uint8_t id, uint8_t *dkek) {
|
||||
file_t *tf = search_file(EF_DKEK + id);
|
||||
if (!tf) {
|
||||
return PICOKEY_ERR_FILE_NOT_FOUND;
|
||||
}
|
||||
int r = mkek_encrypt(dkek, DKEK_KEY_SIZE);
|
||||
if (r != PICOKEY_OK) {
|
||||
return r;
|
||||
}
|
||||
file_put_data(tf, dkek, DKEK_KEY_SIZE);
|
||||
low_flash_available();
|
||||
return PICOKEY_OK;
|
||||
}
|
||||
|
||||
int save_dkek_key(uint8_t id, const uint8_t *key) {
|
||||
uint8_t dkek[DKEK_KEY_SIZE];
|
||||
if (!key) {
|
||||
file_t *tf = search_file(EF_DKEK + id);
|
||||
if (!tf) {
|
||||
return PICOKEY_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_file(EF_DKEK + id);
|
||||
if (!tf) {
|
||||
return PICOKEY_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];
|
||||
}
|
||||
file_put_data(tf, tmp_dkek, DKEK_KEY_SIZE);
|
||||
low_flash_available();
|
||||
return PICOKEY_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 != PICOKEY_OK) {
|
||||
return r;
|
||||
}
|
||||
hash256(dkek, DKEK_KEY_SIZE, hsh);
|
||||
mbedtls_platform_zeroize(dkek, sizeof(dkek));
|
||||
memcpy(kcv, hsh, 8);
|
||||
return PICOKEY_OK;
|
||||
}
|
||||
|
||||
int dkek_kenc(uint8_t id, uint8_t *kenc) { //kenc 32 bytes
|
||||
uint8_t dkek[DKEK_KEY_SIZE + 4];
|
||||
memset(kenc, 0, 32);
|
||||
int r = load_dkek(id, dkek);
|
||||
if (r != PICOKEY_OK) {
|
||||
return r;
|
||||
}
|
||||
memcpy(dkek + DKEK_KEY_SIZE, "\x0\x0\x0\x1", 4);
|
||||
hash256(dkek, sizeof(dkek), kenc);
|
||||
mbedtls_platform_zeroize(dkek, sizeof(dkek));
|
||||
return PICOKEY_OK;
|
||||
}
|
||||
|
||||
int dkek_kmac(uint8_t id, uint8_t *kmac) { //kmac 32 bytes
|
||||
uint8_t dkek[DKEK_KEY_SIZE + 4];
|
||||
memset(kmac, 0, 32);
|
||||
int r = load_dkek(id, dkek);
|
||||
if (r != PICOKEY_OK) {
|
||||
return r;
|
||||
}
|
||||
memcpy(dkek + DKEK_KEY_SIZE, "\x0\x0\x0\x2", 4);
|
||||
hash256(dkek, DKEK_KEY_SIZE + 4, kmac);
|
||||
mbedtls_platform_zeroize(dkek, sizeof(dkek));
|
||||
return PICOKEY_OK;
|
||||
}
|
||||
|
||||
int mkek_encrypt(uint8_t *data, uint16_t len) {
|
||||
int r;
|
||||
uint8_t mkek[MKEK_SIZE + 4];
|
||||
if ((r = load_mkek(mkek)) != PICOKEY_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, uint16_t len) {
|
||||
int r;
|
||||
uint8_t mkek[MKEK_SIZE + 4];
|
||||
if ((r = load_mkek(mkek)) != PICOKEY_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, uint16_t *out_len, const uint8_t *allowed, uint16_t allowed_len) {
|
||||
if (!(key_type & PICO_KEYS_KEY_RSA) && !(key_type & PICO_KEYS_KEY_EC) && !(key_type & PICO_KEYS_KEY_AES)) {
|
||||
return PICOKEY_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));
|
||||
uint16_t kb_len = 0;
|
||||
int 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 != PICOKEY_OK) {
|
||||
return r;
|
||||
}
|
||||
|
||||
uint8_t kcv[8];
|
||||
memset(kcv, 0, sizeof(kcv));
|
||||
r = dkek_kcv(id, kcv);
|
||||
if (r != PICOKEY_OK) {
|
||||
return r;
|
||||
}
|
||||
|
||||
uint8_t kmac[32];
|
||||
memset(kmac, 0, sizeof(kmac));
|
||||
r = dkek_kmac(id, kmac);
|
||||
if (r != PICOKEY_OK) {
|
||||
return r;
|
||||
}
|
||||
|
||||
if (key_type & PICO_KEYS_KEY_AES) {
|
||||
if (key_type & PICO_KEYS_KEY_AES_128) {
|
||||
kb_len = 16;
|
||||
}
|
||||
else if (key_type & PICO_KEYS_KEY_AES_192) {
|
||||
kb_len = 24;
|
||||
}
|
||||
else if (key_type & PICO_KEYS_KEY_AES_256) {
|
||||
kb_len = 32;
|
||||
}
|
||||
else if (key_type & PICO_KEYS_KEY_AES_512) {
|
||||
kb_len = 64;
|
||||
}
|
||||
|
||||
if (kb_len != 16 && kb_len != 24 && kb_len != 32 && kb_len != 64) {
|
||||
return PICOKEY_WRONG_DATA;
|
||||
}
|
||||
if (*out_len < 8 + 1 + 10 + 6 + (2 + 64 + 14) + 16) { // 14 bytes padding
|
||||
return PICOKEY_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 & PICO_KEYS_KEY_RSA) {
|
||||
if (*out_len < 8 + 1 + 12 + 6 + (8 + 2 * 4 + 2 * 4096 / 8 + 3 + 13) + 16) { //13 bytes pading
|
||||
return PICOKEY_WRONG_LENGTH;
|
||||
}
|
||||
mbedtls_rsa_context *rsa = (mbedtls_rsa_context *) key_ctx;
|
||||
kb_len = 0;
|
||||
put_uint16_t((uint16_t)mbedtls_rsa_get_len(rsa) * 8, kb + 8 + kb_len); kb_len += 2;
|
||||
|
||||
put_uint16_t((uint16_t)mbedtls_mpi_size(&rsa->D), kb + 8 + kb_len); kb_len += 2;
|
||||
mbedtls_mpi_write_binary(&rsa->D, kb + 8 + kb_len, mbedtls_mpi_size(&rsa->D));
|
||||
kb_len += (uint16_t)mbedtls_mpi_size(&rsa->D);
|
||||
put_uint16_t((uint16_t)mbedtls_mpi_size(&rsa->N), kb + 8 + kb_len); kb_len += 2;
|
||||
mbedtls_mpi_write_binary(&rsa->N, kb + 8 + kb_len, mbedtls_mpi_size(&rsa->N));
|
||||
kb_len += (uint16_t)mbedtls_mpi_size(&rsa->N);
|
||||
put_uint16_t((uint16_t)mbedtls_mpi_size(&rsa->E), kb + 8 + kb_len); kb_len += 2;
|
||||
mbedtls_mpi_write_binary(&rsa->E, kb + 8 + kb_len, mbedtls_mpi_size(&rsa->E));
|
||||
kb_len += (uint16_t)mbedtls_mpi_size(&rsa->E);
|
||||
|
||||
algo = (uint8_t *) "\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x01\x02";
|
||||
algo_len = 12;
|
||||
}
|
||||
else if (key_type & PICO_KEYS_KEY_EC) {
|
||||
if (*out_len < 8 + 1 + 12 + 6 + (8 + 2 * 8 + 9 * 66 + 2 + 4) + 16) { //4 bytes pading
|
||||
return PICOKEY_WRONG_LENGTH;
|
||||
}
|
||||
mbedtls_ecdsa_context *ecdsa = (mbedtls_ecdsa_context *) key_ctx;
|
||||
kb_len = 0;
|
||||
put_uint16_t((uint16_t)mbedtls_mpi_size(&ecdsa->grp.P) * 8, kb + 8 + kb_len); kb_len += 2;
|
||||
put_uint16_t((uint16_t)mbedtls_mpi_size(&ecdsa->grp.A), kb + 8 + kb_len); kb_len += 2;
|
||||
mbedtls_mpi_write_binary(&ecdsa->grp.A, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->grp.A));
|
||||
kb_len += (uint16_t)mbedtls_mpi_size(&ecdsa->grp.A);
|
||||
put_uint16_t((uint16_t)mbedtls_mpi_size(&ecdsa->grp.B), kb + 8 + kb_len); kb_len += 2;
|
||||
mbedtls_mpi_write_binary(&ecdsa->grp.B, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->grp.B));
|
||||
kb_len += (uint16_t)mbedtls_mpi_size(&ecdsa->grp.B);
|
||||
put_uint16_t((uint16_t)mbedtls_mpi_size(&ecdsa->grp.P), kb + 8 + kb_len); kb_len += 2;
|
||||
mbedtls_mpi_write_binary(&ecdsa->grp.P, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->grp.P));
|
||||
kb_len += (uint16_t)mbedtls_mpi_size(&ecdsa->grp.P);
|
||||
put_uint16_t((uint16_t)mbedtls_mpi_size(&ecdsa->grp.N), kb + 8 + kb_len); kb_len += 2;
|
||||
mbedtls_mpi_write_binary(&ecdsa->grp.N, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->grp.N));
|
||||
kb_len += (uint16_t)mbedtls_mpi_size(&ecdsa->grp.N);
|
||||
|
||||
size_t olen = 0;
|
||||
mbedtls_ecp_point_write_binary(&ecdsa->grp, &ecdsa->grp.G, MBEDTLS_ECP_PF_UNCOMPRESSED, &olen, kb + 8 + kb_len + 2, sizeof(kb) - 8 - kb_len - 2);
|
||||
put_uint16_t((uint16_t)olen, kb + 8 + kb_len);
|
||||
kb_len += 2 + (uint16_t)olen;
|
||||
|
||||
put_uint16_t((uint16_t)mbedtls_mpi_size(&ecdsa->d), kb + 8 + kb_len); kb_len += 2;
|
||||
mbedtls_mpi_write_binary(&ecdsa->d, kb + 8 + kb_len, mbedtls_mpi_size(&ecdsa->d));
|
||||
kb_len += (uint16_t)mbedtls_mpi_size(&ecdsa->d);
|
||||
|
||||
mbedtls_ecp_point_write_binary(&ecdsa->grp, &ecdsa->Q, MBEDTLS_ECP_PF_UNCOMPRESSED, &olen, kb + 8 + kb_len + 2, sizeof(kb) - 8 - kb_len - 2);
|
||||
put_uint16_t((uint16_t)olen, kb + 8 + kb_len);
|
||||
kb_len += 2 + (uint16_t)olen;
|
||||
|
||||
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 & PICO_KEYS_KEY_AES) {
|
||||
out[*out_len] = 15;
|
||||
}
|
||||
else if (key_type & PICO_KEYS_KEY_RSA) {
|
||||
out[*out_len] = 5;
|
||||
}
|
||||
else if (key_type & PICO_KEYS_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
|
||||
uint16_t kb_len_pad = ((uint16_t) (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, PICO_KEYS_AES_MODE_CBC, kb, kb_len_pad);
|
||||
if (r != PICOKEY_OK) {
|
||||
return r;
|
||||
}
|
||||
|
||||
memcpy(out + *out_len, kb, kb_len_pad);
|
||||
*out_len += kb_len_pad;
|
||||
|
||||
r = mbedtls_cipher_cmac(mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_256_ECB), kmac, 256, out, *out_len, out + *out_len);
|
||||
|
||||
*out_len += 16;
|
||||
if (r != 0) {
|
||||
return r;
|
||||
}
|
||||
return PICOKEY_OK;
|
||||
}
|
||||
|
||||
int dkek_type_key(const uint8_t *in) {
|
||||
if (in[8] == 5 || in[8] == 6) {
|
||||
return PICO_KEYS_KEY_RSA;
|
||||
}
|
||||
else if (in[8] == 12) {
|
||||
return PICO_KEYS_KEY_EC;
|
||||
}
|
||||
else if (in[8] == 15) {
|
||||
return PICO_KEYS_KEY_AES;
|
||||
}
|
||||
return 0x0;
|
||||
}
|
||||
|
||||
int dkek_decode_key(uint8_t id, void *key_ctx, const uint8_t *in, uint16_t in_len, int *key_size_out, uint8_t **allowed, uint16_t *allowed_len) {
|
||||
uint8_t kcv[8];
|
||||
int r = 0;
|
||||
memset(kcv, 0, sizeof(kcv));
|
||||
r = dkek_kcv(id, kcv);
|
||||
if (r != PICOKEY_OK) {
|
||||
return r;
|
||||
}
|
||||
|
||||
uint8_t kmac[32];
|
||||
memset(kmac, 0, sizeof(kmac));
|
||||
r = dkek_kmac(id, kmac);
|
||||
if (r != PICOKEY_OK) {
|
||||
return r;
|
||||
}
|
||||
|
||||
uint8_t kenc[32];
|
||||
memset(kenc, 0, sizeof(kenc));
|
||||
r = dkek_kenc(id, kenc);
|
||||
if (r != PICOKEY_OK) {
|
||||
return r;
|
||||
}
|
||||
|
||||
if (memcmp(kcv, in, 8) != 0) {
|
||||
return PICOKEY_WRONG_DKEK;
|
||||
}
|
||||
|
||||
uint8_t signature[16];
|
||||
r = mbedtls_cipher_cmac(mbedtls_cipher_info_from_type(MBEDTLS_CIPHER_AES_256_ECB), kmac, 256, in, in_len - 16, signature);
|
||||
if (r != 0) {
|
||||
return PICOKEY_WRONG_SIGNATURE;
|
||||
}
|
||||
if (memcmp(signature, in + in_len - 16, 16) != 0) {
|
||||
return PICOKEY_WRONG_SIGNATURE;
|
||||
}
|
||||
|
||||
int key_type = in[8];
|
||||
if (key_type != 5 && key_type != 6 && key_type != 12 && key_type != 15) {
|
||||
return PICOKEY_WRONG_DATA;
|
||||
}
|
||||
|
||||
if ((key_type == 5 || key_type == 6) &&
|
||||
memcmp(in + 9, "\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x01\x02", 12) != 0) {
|
||||
return PICOKEY_WRONG_DATA;
|
||||
}
|
||||
|
||||
if (key_type == 12 &&
|
||||
memcmp(in + 9, "\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x02\x03", 12) != 0) {
|
||||
return PICOKEY_WRONG_DATA;
|
||||
}
|
||||
|
||||
if (key_type == 15 && memcmp(in + 9, "\x00\x08\x60\x86\x48\x01\x65\x03\x04\x01", 10) != 0) {
|
||||
return PICOKEY_WRONG_DATA;
|
||||
}
|
||||
|
||||
uint16_t ofs = 9;
|
||||
|
||||
//OID
|
||||
uint16_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 PICOKEY_WRONG_PADDING;
|
||||
}
|
||||
uint8_t kb[8 + 2 * 4 + 2 * 4096 / 8 + 3 + 13]; //worst case: RSA-4096 (plus, 13 bytes padding)
|
||||
memset(kb, 0, sizeof(kb));
|
||||
memcpy(kb, in + ofs, in_len - 16 - ofs);
|
||||
r = aes_decrypt(kenc, NULL, 256, PICO_KEYS_AES_MODE_CBC, kb, in_len - 16 - ofs);
|
||||
if (r != PICOKEY_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 PICOKEY_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 PICOKEY_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 PICOKEY_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 PICOKEY_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 PICOKEY_WRONG_DATA;
|
||||
}
|
||||
|
||||
if (key_type == 5) {
|
||||
r = mbedtls_rsa_import(rsa, &rsa->N, NULL, NULL, &rsa->D, &rsa->E);
|
||||
if (r != 0) {
|
||||
mbedtls_rsa_free(rsa);
|
||||
return PICOKEY_EXEC_ERROR;
|
||||
}
|
||||
}
|
||||
else if (key_type == 6) {
|
||||
r = mbedtls_rsa_import(rsa, NULL, &rsa->P, &rsa->Q, NULL, &rsa->E);
|
||||
if (r != 0) {
|
||||
mbedtls_rsa_free(rsa);
|
||||
return PICOKEY_EXEC_ERROR;
|
||||
}
|
||||
}
|
||||
|
||||
r = mbedtls_rsa_complete(rsa);
|
||||
if (r != 0) {
|
||||
mbedtls_rsa_free(rsa);
|
||||
return PICOKEY_EXEC_ERROR;
|
||||
}
|
||||
r = mbedtls_rsa_check_privkey(rsa);
|
||||
if (r != 0) {
|
||||
mbedtls_rsa_free(rsa);
|
||||
return PICOKEY_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 PICOKEY_WRONG_DATA;
|
||||
}
|
||||
ofs += len;
|
||||
|
||||
//N
|
||||
len = get_uint16_t(kb, ofs); ofs += len + 2;
|
||||
|
||||
//G
|
||||
len = get_uint16_t(kb, ofs);
|
||||
if (ec_id == MBEDTLS_ECP_DP_CURVE25519 && kb[ofs + 2] != 0x09) {
|
||||
ec_id = MBEDTLS_ECP_DP_ED25519;
|
||||
}
|
||||
else if (ec_id == MBEDTLS_ECP_DP_CURVE448 && (len != 56 || kb[ofs + 2] != 0x05)) {
|
||||
ec_id = MBEDTLS_ECP_DP_ED448;
|
||||
}
|
||||
ofs += len + 2;
|
||||
|
||||
//d
|
||||
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 PICOKEY_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) {
|
||||
if (mbedtls_ecp_get_type(&ecdsa->grp) == MBEDTLS_ECP_TYPE_EDWARDS) {
|
||||
r = mbedtls_ecp_point_edwards(&ecdsa->grp, &ecdsa->Q, &ecdsa->d, random_gen, NULL);
|
||||
}
|
||||
else {
|
||||
r = mbedtls_ecp_mul(&ecdsa->grp, &ecdsa->Q, &ecdsa->d, &ecdsa->grp.G, random_gen, NULL);
|
||||
}
|
||||
if (r != 0) {
|
||||
mbedtls_ecdsa_free(ecdsa);
|
||||
return PICOKEY_EXEC_ERROR;
|
||||
}
|
||||
}
|
||||
r = mbedtls_ecp_check_pub_priv(ecdsa, ecdsa, random_gen, NULL);
|
||||
if (r != 0) {
|
||||
mbedtls_ecdsa_free(ecdsa);
|
||||
return PICOKEY_EXEC_ERROR;
|
||||
}
|
||||
}
|
||||
else if (key_type == 15) {
|
||||
memcpy(key_ctx, kb + ofs, key_size);
|
||||
}
|
||||
return PICOKEY_OK;
|
||||
}
|
||||
80
src/hsm/kek.h
Normal file
80
src/hsm/kek.h
Normal file
@@ -0,0 +1,80 @@
|
||||
/*
|
||||
* 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"
|
||||
#if defined(ENABLE_EMULATION) || defined(ESP_PLATFORM)
|
||||
#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, uint16_t len);
|
||||
extern int mkek_decrypt(uint8_t *data, uint16_t len);
|
||||
extern int dkek_encode_key(uint8_t,
|
||||
void *key_ctx,
|
||||
int key_type,
|
||||
uint8_t *out,
|
||||
uint16_t *out_len,
|
||||
const uint8_t *,
|
||||
uint16_t);
|
||||
extern int dkek_type_key(const uint8_t *in);
|
||||
extern int dkek_decode_key(uint8_t,
|
||||
void *key_ctx,
|
||||
const uint8_t *in,
|
||||
uint16_t in_len,
|
||||
int *key_size_out,
|
||||
uint8_t **,
|
||||
uint16_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);
|
||||
|
||||
extern uint8_t pending_save_dkek;
|
||||
|
||||
#endif
|
||||
@@ -1,17 +1,17 @@
|
||||
/*
|
||||
/*
|
||||
* 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
|
||||
*
|
||||
* 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
|
||||
* 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
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
|
||||
162
src/hsm/oid.h
162
src/hsm/oid.h
@@ -1,45 +1,42 @@
|
||||
/*
|
||||
/*
|
||||
* 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
|
||||
*
|
||||
* 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
|
||||
* 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
|
||||
* 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_
|
||||
|
||||
#include <stdlib.h>
|
||||
#include "pico/stdlib.h"
|
||||
|
||||
#define OID_BSI_DE "\x04\x00\x7F\x00\x07"
|
||||
|
||||
#define OID_ID_CA OID_BSI_DE "\x02\x02\x03"
|
||||
#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_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_PK OID_BSI_DE "\x02\x02\0x1"
|
||||
#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"
|
||||
|
||||
@@ -56,11 +53,25 @@
|
||||
|
||||
#define OID_ID_TA_ECDSA OID_ID_TA "\x02"
|
||||
|
||||
#define OID_IT_TA_ECDSA_SHA_1 OID_ID_TA_ECDSA "\x01"
|
||||
#define OID_IT_TA_ECDSA_SHA_224 OID_ID_TA_ECDSA "\x02"
|
||||
#define OID_IT_TA_ECDSA_SHA_256 OID_ID_TA_ECDSA "\x03"
|
||||
#define OID_IT_TA_ECDSA_SHA_384 OID_ID_TA_ECDSA "\x04"
|
||||
#define OID_IT_TA_ECDSA_SHA_512 OID_ID_TA_ECDSA "\x05"
|
||||
#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"
|
||||
|
||||
@@ -70,7 +81,7 @@
|
||||
#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 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"
|
||||
@@ -78,4 +89,89 @@
|
||||
|
||||
#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"
|
||||
|
||||
#define OID_NIST_ALG "\x60\x86\x48\x01\x65\x03\x04"
|
||||
#define OID_NIST_AES OID_NIST_ALG "\x01"
|
||||
#define OID_AES128_ECB OID_NIST_AES "\x01"
|
||||
#define OID_AES128_CBC OID_NIST_AES "\x02"
|
||||
#define OID_AES128_OFB OID_NIST_AES "\x03"
|
||||
#define OID_AES128_CFB OID_NIST_AES "\x04"
|
||||
#define OID_AES128_GCM OID_NIST_AES "\x06"
|
||||
#define OID_AES128_CCM OID_NIST_AES "\x07"
|
||||
#define OID_AES128_CTR OID_NIST_AES "\x09" // Not existing
|
||||
#define OID_AES192_ECB OID_NIST_AES "\x15"
|
||||
#define OID_AES192_CBC OID_NIST_AES "\x16"
|
||||
#define OID_AES192_OFB OID_NIST_AES "\x17"
|
||||
#define OID_AES192_CFB OID_NIST_AES "\x18"
|
||||
#define OID_AES192_GCM OID_NIST_AES "\x1A"
|
||||
#define OID_AES192_CCM OID_NIST_AES "\x1B"
|
||||
#define OID_AES192_CTR OID_NIST_AES "\x1D" // Not existing
|
||||
#define OID_AES256_ECB OID_NIST_AES "\x29"
|
||||
#define OID_AES256_CBC OID_NIST_AES "\x2A"
|
||||
#define OID_AES256_OFB OID_NIST_AES "\x2B"
|
||||
#define OID_AES256_CFB OID_NIST_AES "\x2C"
|
||||
#define OID_AES256_GCM OID_NIST_AES "\x2E"
|
||||
#define OID_AES256_CCM OID_NIST_AES "\x2F"
|
||||
#define OID_AES256_CTR OID_NIST_AES "\x31" // Not existing
|
||||
|
||||
#define OID_IEEE_ALG "\x2B\x6F\x02\x8C\x53\x00\x00\x01"
|
||||
#define OID_AES128_XTS OID_IEEE_ALG "\x01"
|
||||
#define OID_AES256_XTS OID_IEEE_ALG "\x02"
|
||||
|
||||
#define OID_HD "\x2B\x06\x01\x04\x01\x83\xA8\x78\x05\x8D\x6B"
|
||||
|
||||
#endif
|
||||
|
||||
2510
src/hsm/sc_hsm.c
2510
src/hsm/sc_hsm.c
File diff suppressed because it is too large
Load Diff
116
src/hsm/sc_hsm.h
116
src/hsm/sc_hsm.h
@@ -1,17 +1,17 @@
|
||||
/*
|
||||
/*
|
||||
* 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
|
||||
*
|
||||
* 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
|
||||
* 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
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
|
||||
@@ -19,48 +19,63 @@
|
||||
#define _SC_HSM_H_
|
||||
|
||||
#include <stdlib.h>
|
||||
#ifndef ESP_PLATFORM
|
||||
#include "common.h"
|
||||
#else
|
||||
#define MBEDTLS_ALLOW_PRIVATE_ACCESS
|
||||
#endif
|
||||
#include "mbedtls/rsa.h"
|
||||
#include "mbedtls/ecdsa.h"
|
||||
#if !defined(ENABLE_EMULATION) && !defined(ESP_PLATFORM)
|
||||
#include "pico/stdlib.h"
|
||||
#include "ccid2040.h"
|
||||
#endif
|
||||
#include "file.h"
|
||||
#include "apdu.h"
|
||||
#include "pico_keys.h"
|
||||
|
||||
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_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 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_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_PSS 0x40 /* RSA signature with external hash and PKCS#1 PSS padding*/
|
||||
#define ALGO_RSA_PSS_SHA1 0x41 /* RSA signature with SHA-1 hash and PKCS#1 PSS padding */
|
||||
#define ALGO_RSA_PSS 0x40 /* RSA signature with external hash and PKCS#1 PSS padding*/
|
||||
#define ALGO_RSA_PSS_SHA1 0x41 /* RSA signature with SHA-1 hash and PKCS#1 PSS padding */
|
||||
#define ALGO_RSA_PSS_SHA224 0x42
|
||||
#define ALGO_RSA_PSS_SHA256 0x43 /* RSA signature with SHA-256 hash and PKCS#1 PSS padding */
|
||||
#define ALGO_RSA_PSS_SHA256 0x43 /* RSA signature with SHA-256 hash and PKCS#1 PSS padding */
|
||||
#define ALGO_RSA_PSS_SHA384 0x44
|
||||
#define ALGO_RSA_PSS_SHA512 0x45
|
||||
|
||||
#define ALGO_EC_RAW 0x70 /* ECDSA signature with hash input */
|
||||
#define ALGO_EC_SHA1 0x71 /* ECDSA signature with SHA-1 hash */
|
||||
#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_RAW 0x70 /* ECDSA signature with hash input */
|
||||
#define ALGO_EC_SHA1 0x71 /* ECDSA signature with SHA-1 hash */
|
||||
#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 0x80 /* ECDH key derivation */
|
||||
#define ALGO_EC_DH_AUTPUK 0x83
|
||||
#define ALGO_EC_DH_XKEK 0x84
|
||||
#define ALGO_HD 0xA0
|
||||
|
||||
#define ALGO_WRAP 0x92
|
||||
#define ALGO_UNWRAP 0x93
|
||||
#define ALGO_REPLACE 0x94
|
||||
|
||||
#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_DECRYPT 0x11
|
||||
#define ALGO_AES_CMAC 0x18
|
||||
#define ALGO_AES_DERIVE 0x99
|
||||
#define ALGO_AES_CBC_ENCRYPT 0x10
|
||||
#define ALGO_AES_CBC_DECRYPT 0x11
|
||||
#define ALGO_AES_CMAC 0x18
|
||||
#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_TRANSPORT_PIN 0x0002
|
||||
@@ -71,27 +86,46 @@ extern const uint8_t sc_hsm_aid[];
|
||||
#define HSM_OPT_RRC_RESET_ONLY 0x0020
|
||||
#define HSM_OPT_BOOTSEL_BUTTON 0x0100
|
||||
#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 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 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 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 DATA_PREFIX 0xCF /* Hi byte in file identifier for readable data 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 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 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 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 P15_KEYTYPE_RSA 0x30
|
||||
#define P15_KEYTYPE_ECC 0xA0
|
||||
#define P15_KEYTYPE_AES 0xA8
|
||||
|
||||
#define MAX_PUK 8
|
||||
|
||||
extern int pin_reset_retries(const file_t *pin, bool);
|
||||
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_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 hash(const uint8_t *input, uint16_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 uint16_t check_pin(const file_t *pin, const uint8_t *data, uint16_t len);
|
||||
extern bool pka_enabled();
|
||||
extern const uint8_t *dev_name;
|
||||
extern uint16_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, uint16_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_ec(mbedtls_ecp_keypair *ctx, file_t *fkey);
|
||||
extern int load_private_key_ecdh(mbedtls_ecp_keypair *ctx, file_t *fkey);
|
||||
extern bool wait_button_pressed();
|
||||
extern 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
|
||||
|
||||
@@ -1,27 +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
|
||||
*
|
||||
* 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
|
||||
* 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
|
||||
* 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 __VERSION_H_
|
||||
#define __VERSION_H_
|
||||
|
||||
#define HSM_VERSION 0x0206
|
||||
#define HSM_VERSION 0x0500
|
||||
|
||||
#define HSM_VERSION_MAJOR ((HSM_VERSION >> 8) & 0xff)
|
||||
#define HSM_VERSION_MINOR (HSM_VERSION & 0xff)
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
14
tests/build-in-docker.sh
Executable file
14
tests/build-in-docker.sh
Executable file
@@ -0,0 +1,14 @@
|
||||
#!/bin/bash -eu
|
||||
|
||||
source tests/docker_env.sh
|
||||
build_image
|
||||
#run_in_docker rm -rf CMakeFiles
|
||||
run_in_docker mkdir -p build_in_docker
|
||||
run_in_docker -w "$PWD/build_in_docker" cmake -DENABLE_EMULATION=1 -D__FOR_CI=1 ..
|
||||
run_in_docker -w "$PWD/build_in_docker" make -j ${NUM_PROC}
|
||||
docker create --name temp_container pico-hsm-test:bullseye
|
||||
docker cp $PWD/build_in_docker/pico_hsm temp_container:/pico_hsm
|
||||
docker commit temp_container pico-hsm-test:bullseye
|
||||
docker stop temp_container
|
||||
docker rm temp_container
|
||||
docker image prune -f
|
||||
33
tests/conftest.py
Normal file
33
tests/conftest.py
Normal file
@@ -0,0 +1,33 @@
|
||||
"""
|
||||
/*
|
||||
* 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
|
||||
|
||||
try:
|
||||
from picohsm import PicoHSM
|
||||
except ModuleNotFoundError:
|
||||
print('ERROR: picohsm module not found! Install picohsm package.\nTry with `pip install pypicohsm`')
|
||||
sys.exit(-1)
|
||||
|
||||
|
||||
@pytest.fixture(scope="session")
|
||||
def device():
|
||||
dev = PicoHSM()
|
||||
return dev
|
||||
25
tests/const.py
Normal file
25
tests/const.py
Normal file
@@ -0,0 +1,25 @@
|
||||
"""
|
||||
/*
|
||||
* 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 binascii import unhexlify
|
||||
|
||||
DEFAULT_DKEK = [0x1] * 32
|
||||
|
||||
TERM_CERT = unhexlify('7F2181E57F4E819E5F290100421045535049434F48534D445630303030317F494F060A04007F00070202020203864104F571E53AA8E75C929D925081CF0F893CB5991D48BD546C1A3F22199F037E4B12D601ACD91C67C88D3C5B3D04C08EC0A372485F7A248E080EE0C6237C1B075E1C5F201045535049434F48534D54525A474E50327F4C0E060904007F0007030102025301005F25060203000300055F24060204000300045F374041BF5E970739135770DBCC5DDA81FFD8B13419A9257D44CAF8404267C644E8F435B43F5E57EB2A8CF4B198045ACD094E0CB34E6217D9C8922CFB9BBEFD4088AD')
|
||||
DICA_CERT = unhexlify('7F2181E97F4E81A25F290100421045535049434F48534D434130303030317F494F060A04007F0007020202020386410421EE4A21C16A10F737F12E78E5091B266612038CDABEBB722B15BF6D41B877FBF64D9AB69C39B9831B1AE00BEF2A4E81976F7688D45189BB232A24703D8A96A55F201045535049434F48534D445630303030317F4C12060904007F000703010202530580000000005F25060202000801085F24060203000601045F37403F75C08FFFC9186B56E6147199E82BFC327CEEF72495BC567961CD54D702F13E3C2766FCD1D11BD6A9D1F4A229B76B248CEB9AF88D59A74D0AB149448705159B')
|
||||
49
tests/docker/bullseye/Dockerfile
Normal file
49
tests/docker/bullseye/Dockerfile
Normal file
@@ -0,0 +1,49 @@
|
||||
FROM debian:bullseye
|
||||
|
||||
ARG DEBIAN_FRONTEND=noninteractive
|
||||
|
||||
RUN apt update && apt upgrade -y
|
||||
RUN apt install -y apt-utils
|
||||
RUN apt autoremove -y
|
||||
RUN rm -rf /var/cache/apt/archives/*
|
||||
RUN apt install -y libccid \
|
||||
libpcsclite-dev \
|
||||
git \
|
||||
autoconf \
|
||||
pkg-config \
|
||||
libtool \
|
||||
help2man \
|
||||
automake \
|
||||
gcc \
|
||||
make \
|
||||
build-essential \
|
||||
python3 \
|
||||
python3-pip \
|
||||
swig \
|
||||
libssl-dev \
|
||||
cmake \
|
||||
vsmartcard-vpcd \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
RUN pip3 install pytest pycvc cryptography pyscard base58
|
||||
WORKDIR /
|
||||
RUN git clone https://github.com/OpenSC/OpenSC
|
||||
WORKDIR /OpenSC
|
||||
RUN git checkout tags/0.25.1
|
||||
RUN ./bootstrap
|
||||
RUN ./configure --enable-openssl
|
||||
RUN make -j `nproc`
|
||||
RUN make install
|
||||
RUN make clean
|
||||
RUN ldconfig
|
||||
WORKDIR /
|
||||
RUN git clone https://github.com/polhenarejos/pypicohsm.git
|
||||
RUN pip3 install -e pypicohsm
|
||||
RUN git clone https://github.com/CardContact/sc-hsm-embedded
|
||||
WORKDIR /sc-hsm-embedded
|
||||
RUN autoreconf -fi
|
||||
RUN ./configure
|
||||
RUN make -j `nproc`
|
||||
RUN make install
|
||||
RUN cp ./src/tests/sc-hsm-pkcs11-test /usr/local/bin/sc-hsm-pkcs11-test
|
||||
RUN make clean
|
||||
WORKDIR /
|
||||
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/polhenarejos/vsmartcard.git
|
||||
WORKDIR /vsmartcard/virtualsmartcard
|
||||
RUN autoreconf --verbose --install
|
||||
RUN ./configure --sysconfdir=/etc
|
||||
RUN make && make install
|
||||
WORKDIR /
|
||||
108
tests/docker_env.sh
Executable file
108
tests/docker_env.sh
Executable file
@@ -0,0 +1,108 @@
|
||||
#!/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:=bullseye}
|
||||
|
||||
|
||||
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_image() {
|
||||
# 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.
37
tests/pico-hsm/test_000_info.py
Normal file
37
tests/pico-hsm/test_000_info.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
|
||||
|
||||
def test_select(device):
|
||||
device.select_applet()
|
||||
|
||||
def test_initialization(device):
|
||||
device.initialize()
|
||||
|
||||
def test_termca(device):
|
||||
data = device.get_termca()
|
||||
assert(b'ESPICOHSMTR' == data['cv']['chr'][:11])
|
||||
assert(b'ESPICOHSMDV' == data['cv']['car'][:11] or b'ESPICOHSMTR' == data['cv']['car'][:11])
|
||||
assert(b'ESPICOHSMDV' == data['dv']['chr'][:11] or b'ESPICOHSMTR' == data['dv']['chr'][:11])
|
||||
assert(b'ESPICOHSMCA' == data['dv']['car'][:11] or b'ESPICOHSMTR' == 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)
|
||||
|
||||
115
tests/pico-hsm/test_004_key_domains.py
Normal file
115
tests/pico-hsm/test_004_key_domains.py
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/>.
|
||||
*/
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import hashlib
|
||||
from const import DEFAULT_DKEK
|
||||
from picohsm import APDUResponse, SWCodes
|
||||
from picohsm.const import DEFAULT_DKEK_SHARES
|
||||
|
||||
KEY_DOMAINS = 3
|
||||
TEST_KEY_DOMAIN = 1
|
||||
|
||||
def test_key_domains(device):
|
||||
device.initialize(key_domains=KEY_DOMAINS)
|
||||
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_import_dkek_wrong_key_domain(device):
|
||||
with pytest.raises(APDUResponse) as e:
|
||||
device.import_dkek(DEFAULT_DKEK, key_domain=0)
|
||||
assert(e.value.sw == SWCodes.SW_COMMAND_NOT_ALLOWED)
|
||||
|
||||
def test_import_dkek_fail(device):
|
||||
with pytest.raises(APDUResponse) as e:
|
||||
device.import_dkek(DEFAULT_DKEK, key_domain=TEST_KEY_DOMAIN)
|
||||
assert(e.value.sw == SWCodes.SW_COMMAND_NOT_ALLOWED)
|
||||
|
||||
def test_set_key_domain_fail(device):
|
||||
with pytest.raises(APDUResponse) as e:
|
||||
device.set_key_domain(key_domain=10)
|
||||
assert(e.value.sw == SWCodes.SW_INCORRECT_P1P2)
|
||||
|
||||
def test_set_key_domain_ok(device):
|
||||
kd = device.get_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||
assert('error' in kd)
|
||||
assert(kd['error'] == 0x6A88)
|
||||
|
||||
device.set_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||
kd = device.get_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||
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_import_dkek_ok(device):
|
||||
resp = device.import_dkek(DEFAULT_DKEK, key_domain=TEST_KEY_DOMAIN)
|
||||
assert('dkek' in resp)
|
||||
assert('kcv' in resp)
|
||||
assert(resp['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
||||
assert(resp['dkek']['missing'] == DEFAULT_DKEK_SHARES-1)
|
||||
|
||||
resp = device.import_dkek(DEFAULT_DKEK, key_domain=TEST_KEY_DOMAIN)
|
||||
assert('dkek' in resp)
|
||||
assert('kcv' in resp)
|
||||
assert(resp['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
||||
assert(resp['dkek']['missing'] == DEFAULT_DKEK_SHARES-2)
|
||||
|
||||
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]
|
||||
assert(resp['kcv'] == kcv)
|
||||
|
||||
def test_clear_key_domain(device):
|
||||
kd = device.get_key_domain(key_domain=0)
|
||||
assert('error' in kd)
|
||||
assert(kd['error'] == SWCodes.SW_REFERENCE_NOT_FOUND)
|
||||
|
||||
kd = device.get_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||
assert(kd['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
||||
|
||||
device.clear_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||
kd = device.get_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||
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=TEST_KEY_DOMAIN)
|
||||
assert(kd['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
||||
with pytest.raises(APDUResponse) as e:
|
||||
device.delete_key_domain(key_domain=0)
|
||||
assert(e.value.sw == SWCodes.SW_INCORRECT_P1P2)
|
||||
|
||||
def test_delete_key_domain(device):
|
||||
assert(device.get_key_domains() == KEY_DOMAINS)
|
||||
kd = device.get_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||
assert(kd['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
||||
|
||||
device.delete_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||
assert(device.get_key_domains() == KEY_DOMAINS)
|
||||
kd = device.get_key_domain(key_domain=TEST_KEY_DOMAIN)
|
||||
assert('error' in kd)
|
||||
assert(kd['error'] == 0x6A88)
|
||||
42
tests/pico-hsm/test_005_dkek.py
Normal file
42
tests/pico-hsm/test_005_dkek.py
Normal file
@@ -0,0 +1,42 @@
|
||||
"""
|
||||
/*
|
||||
* 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 picohsm.const import DEFAULT_DKEK_SHARES, DEFAULT_PIN, DEFAULT_RETRIES
|
||||
from const import DEFAULT_DKEK
|
||||
|
||||
def test_dkek(device):
|
||||
device.initialize(retries=DEFAULT_RETRIES, dkek_shares=DEFAULT_DKEK_SHARES)
|
||||
device.login(DEFAULT_PIN)
|
||||
resp = device.import_dkek(DEFAULT_DKEK)
|
||||
assert('dkek' in resp)
|
||||
assert('kcv' in resp)
|
||||
assert(resp['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
||||
assert(resp['dkek']['missing'] == DEFAULT_DKEK_SHARES-1)
|
||||
|
||||
resp = device.import_dkek(DEFAULT_DKEK)
|
||||
assert('dkek' in resp)
|
||||
assert('kcv' in resp)
|
||||
assert(resp['dkek']['total'] == DEFAULT_DKEK_SHARES)
|
||||
assert(resp['dkek']['missing'] == DEFAULT_DKEK_SHARES-2)
|
||||
|
||||
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]
|
||||
assert(resp['kcv'] == kcv)
|
||||
|
||||
52
tests/pico-hsm/test_010_pin.py
Normal file
52
tests/pico-hsm/test_010_pin.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
|
||||
from picohsm import APDUResponse, SWCodes
|
||||
from picohsm.const import DEFAULT_PIN, DEFAULT_RETRIES
|
||||
|
||||
WRONG_PIN = '112233'
|
||||
|
||||
def test_pin_init_retries(device):
|
||||
device.initialize(retries=DEFAULT_RETRIES)
|
||||
retries = device.get_login_retries()
|
||||
assert(retries == DEFAULT_RETRIES)
|
||||
|
||||
def test_pin_login(device):
|
||||
device.initialize(retries=DEFAULT_RETRIES)
|
||||
device.login(DEFAULT_PIN)
|
||||
|
||||
def test_pin_retries(device):
|
||||
device.initialize(retries=DEFAULT_RETRIES)
|
||||
device.login(DEFAULT_PIN)
|
||||
|
||||
for ret in range(DEFAULT_RETRIES-1):
|
||||
with pytest.raises(APDUResponse) as e:
|
||||
device.login(WRONG_PIN)
|
||||
assert(e.value.sw1 == 0x63 and e.value.sw2 == (0xC0 | (DEFAULT_RETRIES-1-ret)))
|
||||
|
||||
with pytest.raises(APDUResponse) as e:
|
||||
device.login(WRONG_PIN)
|
||||
assert(e.value.sw == SWCodes.SW_PIN_BLOCKED)
|
||||
|
||||
device.initialize(retries=DEFAULT_RETRIES)
|
||||
retries = device.get_login_retries()
|
||||
assert(retries == DEFAULT_RETRIES)
|
||||
|
||||
|
||||
47
tests/pico-hsm/test_020_keypair_gen.py
Normal file
47
tests/pico-hsm/test_020_keypair_gen.py
Normal file
@@ -0,0 +1,47 @@
|
||||
"""
|
||||
/*
|
||||
* 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 picohsm import KeyType, DOPrefixes
|
||||
|
||||
def test_gen_initialize(device):
|
||||
device.initialize()
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"curve", ['secp192r1', 'secp256r1', 'secp384r1', 'secp521r1', 'brainpoolP256r1', 'brainpoolP384r1', 'brainpoolP512r1', 'secp192k1', 'secp256k1', 'curve25519', 'curve448', 'ed25519', 'ed448']
|
||||
)
|
||||
def test_gen_ecc(device, curve):
|
||||
keyid = device.key_generation(KeyType.ECC, curve)
|
||||
resp = device.list_keys()
|
||||
assert((DOPrefixes.KEY_PREFIX, keyid) in resp)
|
||||
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||
resp = device.list_keys()
|
||||
assert((DOPrefixes.KEY_PREFIX, keyid) not in resp)
|
||||
|
||||
@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, keyid) in resp)
|
||||
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||
|
||||
89
tests/pico-hsm/test_021_key_import.py
Normal file
89
tests/pico-hsm/test_021_key_import.py
Normal file
@@ -0,0 +1,89 @@
|
||||
"""
|
||||
/*
|
||||
* 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 picohsm import DOPrefixes
|
||||
from cryptography.hazmat.primitives.asymmetric import rsa, ec, x25519, x448, ed25519, ed448
|
||||
from cryptography.hazmat.primitives.serialization import Encoding, PublicFormat
|
||||
from picohsm.const import DEFAULT_RETRIES, DEFAULT_DKEK_SHARES
|
||||
from const import DEFAULT_DKEK
|
||||
|
||||
def test_prepare_dkek(device):
|
||||
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(resp['kcv'] == 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, keyid)
|
||||
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, 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, keyid)
|
||||
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"curve", [x25519.X25519PrivateKey, x448.X448PrivateKey]
|
||||
)
|
||||
def test_import_montgomery(device, curve):
|
||||
pkey = curve.generate()
|
||||
keyid = device.import_key(pkey)
|
||||
pubkey = device.public_key(keyid, param=curve)
|
||||
assert(pubkey.public_bytes(Encoding.Raw, PublicFormat.Raw) == pkey.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw))
|
||||
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"curve", [ed25519.Ed25519PrivateKey, ed448.Ed448PrivateKey]
|
||||
)
|
||||
def test_import_edwards(device, curve):
|
||||
pkey = curve.generate()
|
||||
keyid = device.import_key(pkey)
|
||||
pubkey = device.public_key(keyid, param=curve)
|
||||
assert(pubkey.public_bytes(Encoding.Raw, PublicFormat.Raw) == pkey.public_key().public_bytes(Encoding.Raw, PublicFormat.Raw))
|
||||
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"size", [128, 192, 256]
|
||||
)
|
||||
def test_import_aes(device, size):
|
||||
pkey = os.urandom(size // 8)
|
||||
keyid = device.import_key(pkey)
|
||||
74
tests/pico-hsm/test_022_key_exchange.py
Normal file
74
tests/pico-hsm/test_022_key_exchange.py
Normal file
@@ -0,0 +1,74 @@
|
||||
"""
|
||||
/*
|
||||
* 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 picohsm import DOPrefixes
|
||||
from cryptography.hazmat.primitives.asymmetric import ec, x25519, x448
|
||||
from picohsm.const import DEFAULT_RETRIES, DEFAULT_DKEK_SHARES
|
||||
from const import DEFAULT_DKEK
|
||||
|
||||
def test_prepare_dkek(device):
|
||||
device.initialize(retries=DEFAULT_RETRIES, dkek_shares=DEFAULT_DKEK_SHARES)
|
||||
resp = device.import_dkek(DEFAULT_DKEK)
|
||||
resp = device.import_dkek(DEFAULT_DKEK)
|
||||
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]
|
||||
assert(resp['kcv'] == 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(sharedA == sharedB)
|
||||
|
||||
sharedAA = pkeyA.exchange(ec.ECDH(), pbkeyB)
|
||||
assert(sharedA == sharedAA)
|
||||
|
||||
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"curve", [x25519.X25519PrivateKey, x448.X448PrivateKey]
|
||||
)
|
||||
def test_exchange_montgomery(device, curve):
|
||||
pkeyA = curve.generate()
|
||||
pbkeyA = pkeyA.public_key()
|
||||
keyid = device.import_key(pkeyA)
|
||||
pkeyB = curve.generate()
|
||||
pbkeyB = pkeyB.public_key()
|
||||
|
||||
sharedB = pkeyB.exchange(pbkeyA)
|
||||
sharedA = device.exchange(keyid, pbkeyB)
|
||||
|
||||
assert(sharedA == sharedB)
|
||||
|
||||
sharedAA = pkeyA.exchange(pbkeyB)
|
||||
assert(sharedA == sharedAA)
|
||||
|
||||
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||
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 picohsm 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, keyid) in resp)
|
||||
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||
137
tests/pico-hsm/test_025_key_export.py
Normal file
137
tests/pico-hsm/test_025_key_export.py
Normal file
@@ -0,0 +1,137 @@
|
||||
"""
|
||||
/*
|
||||
* This file is part of the Pico HSM distribution (https://github.com/polhenarejos/pico-hsm).
|
||||
* Copyright (c) 2023 Pol Henarejos.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from picohsm import KeyType, DOPrefixes, APDUResponse, SWCodes
|
||||
from binascii import hexlify
|
||||
import hashlib
|
||||
from const import DEFAULT_DKEK
|
||||
from cryptography.hazmat.primitives import cmac
|
||||
from cryptography.hazmat.primitives.ciphers import algorithms, Cipher, modes
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.hazmat.primitives import serialization
|
||||
|
||||
def test_initialize(device):
|
||||
device.initialize(key_domains=1)
|
||||
assert(device.get_key_domains() == 1)
|
||||
|
||||
device.set_key_domain(key_domain=0, total=2)
|
||||
|
||||
keyid_in = -1
|
||||
keyid_out = -1
|
||||
def test_key_generation_no_key_domain(device):
|
||||
global keyid_out
|
||||
keyid_out = device.key_generation(KeyType.ECC, 'brainpoolP256r1')
|
||||
device.put_contents(p1=DOPrefixes.PRKD_PREFIX, p2=keyid_out, data=[0xA0])
|
||||
resp = device.list_keys()
|
||||
assert((DOPrefixes.KEY_PREFIX, keyid_out) in resp)
|
||||
assert((DOPrefixes.PRKD_PREFIX, keyid_out) in resp)
|
||||
|
||||
def test_key_generation_with_key_domain(device):
|
||||
global keyid_in
|
||||
keyid_in = device.key_generation(KeyType.ECC, 'brainpoolP256r1', key_domain=0)
|
||||
device.put_contents(p1=DOPrefixes.PRKD_PREFIX, p2=keyid_in, data=[0xA0])
|
||||
resp = device.list_keys()
|
||||
assert((DOPrefixes.KEY_PREFIX, keyid_in) in resp)
|
||||
assert((DOPrefixes.PRKD_PREFIX, keyid_in) in resp)
|
||||
|
||||
def test_export_key_out(device):
|
||||
with pytest.raises(APDUResponse) as e:
|
||||
device.export_key(keyid_out)
|
||||
assert(e.value.sw == SWCodes.SW_REFERENCE_NOT_FOUND)
|
||||
|
||||
def test_export_key_in_fail(device):
|
||||
with pytest.raises(APDUResponse) as e:
|
||||
device.export_key(keyid_in)
|
||||
assert(e.value.sw == SWCodes.SW_REFERENCE_NOT_FOUND)
|
||||
|
||||
def test_export_import_dkek(device):
|
||||
resp = device.import_dkek(DEFAULT_DKEK, key_domain=0)
|
||||
resp = device.import_dkek(DEFAULT_DKEK, key_domain=0)
|
||||
|
||||
def test_export_key_in_ok(device):
|
||||
resp = device.export_key(keyid_in)
|
||||
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]
|
||||
assert(kcv == resp[:8])
|
||||
assert(resp[8] == 12)
|
||||
assert(resp[9:21] == b"\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x02\x03")
|
||||
|
||||
pkey = hashlib.sha256(b'\x00'*32+b'\x00\x00\x00\x02').digest()
|
||||
c = cmac.CMAC(algorithms.AES(pkey))
|
||||
c.update(resp[:-16])
|
||||
resCMAC = c.finalize()
|
||||
assert(resCMAC == resp[-16:])
|
||||
|
||||
def test_delete_keys_in_out(device):
|
||||
device.delete_file(DOPrefixes.KEY_PREFIX, keyid_in)
|
||||
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid_in)
|
||||
device.delete_file(DOPrefixes.KEY_PREFIX, keyid_out)
|
||||
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid_out)
|
||||
|
||||
def test_export_import(device):
|
||||
pkey_gen = ec.generate_private_key(ec.BrainpoolP256R1())
|
||||
keyid = device.import_key(pkey_gen)
|
||||
|
||||
resp = device.export_key(keyid)
|
||||
kcv = hashlib.sha256(b'\x00'*32).digest()[:8]
|
||||
assert(kcv == resp[:8])
|
||||
assert(resp[8] == 12)
|
||||
assert(resp[9:21] == b"\x00\x0A\x04\x00\x7F\x00\x07\x02\x02\x02\x02\x03")
|
||||
|
||||
pkey = hashlib.sha256(b'\x00'*32+b'\x00\x00\x00\x02').digest()
|
||||
c = cmac.CMAC(algorithms.AES(pkey))
|
||||
c.update(resp[:-16])
|
||||
resCMAC = c.finalize()
|
||||
assert(resCMAC == resp[-16:])
|
||||
|
||||
iv = b'\x00'*16
|
||||
pkey = hashlib.sha256(b'\x00'*32+b'\x00\x00\x00\x01').digest()
|
||||
cipher = Cipher(algorithms.AES(pkey), modes.CBC(iv))
|
||||
decryptor = cipher.decryptor()
|
||||
payload = decryptor.update(resp[27:-16]) + decryptor.finalize()
|
||||
|
||||
rnd = payload[:8]
|
||||
ofs = 8
|
||||
key_size = int.from_bytes(payload[ofs:ofs+2], 'big')
|
||||
ofs += 2
|
||||
A_len = int.from_bytes(payload[ofs:ofs+2], 'big')
|
||||
ofs += 2+A_len
|
||||
B_len = int.from_bytes(payload[ofs:ofs+2], 'big')
|
||||
ofs += 2+B_len
|
||||
P_len = int.from_bytes(payload[ofs:ofs+2], 'big')
|
||||
ofs += 2+P_len
|
||||
N_len = int.from_bytes(payload[ofs:ofs+2], 'big')
|
||||
ofs += 2+N_len
|
||||
G_len = int.from_bytes(payload[ofs:ofs+2], 'big')
|
||||
ofs += 2+G_len
|
||||
d_len = int.from_bytes(payload[ofs:ofs+2], 'big')
|
||||
ofs += 2
|
||||
d = payload[ofs:ofs+d_len]
|
||||
ofs += d_len
|
||||
Q_len = int.from_bytes(payload[ofs:ofs+2], 'big')
|
||||
ofs += 2
|
||||
Q = payload[ofs:ofs+Q_len]
|
||||
ofs += Q_len
|
||||
|
||||
pkey_ex = ec.EllipticCurvePrivateNumbers(int.from_bytes(d, 'big'), ec.EllipticCurvePublicKey.from_encoded_point(ec.BrainpoolP256R1(), Q).public_numbers()).private_key()
|
||||
assert(pkey_gen.private_bytes(serialization.Encoding.DER, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()) == pkey_ex.private_bytes(serialization.Encoding.DER, serialization.PrivateFormat.PKCS8, serialization.NoEncryption()))
|
||||
assert(pkey_gen.public_key().public_bytes(serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint) == pkey_ex.public_key().public_bytes(serialization.Encoding.X962, serialization.PublicFormat.UncompressedPoint))
|
||||
|
||||
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||
66
tests/pico-hsm/test_030_signature.py
Normal file
66
tests/pico-hsm/test_030_signature.py
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/>.
|
||||
*/
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from picohsm 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, 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, keyid)
|
||||
device.verify(pubkey, data, signature, scheme)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"curve", ['ed25519', 'ed448']
|
||||
)
|
||||
def test_signature_edwards(device, curve):
|
||||
keyid = device.key_generation(KeyType.ECC, curve)
|
||||
pubkey = device.public_key(keyid=keyid)
|
||||
signature = device.sign(keyid=keyid, scheme=Algorithm.ALGO_EC_RAW, data=data)
|
||||
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||
device.verify(pubkey, data, signature)
|
||||
47
tests/pico-hsm/test_040_decrypt.py
Normal file
47
tests/pico-hsm/test_040_decrypt.py
Normal file
@@ -0,0 +1,47 @@
|
||||
"""
|
||||
/*
|
||||
* 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 picohsm import KeyType, DOPrefixes
|
||||
from binascii import hexlify
|
||||
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, keyid)
|
||||
assert(datab == message)
|
||||
|
||||
53
tests/pico-hsm/test_050_cipher.py
Normal file
53
tests/pico-hsm/test_050_cipher.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
|
||||
import os
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes
|
||||
from picohsm import Algorithm, DOPrefixes
|
||||
from picohsm.const import DEFAULT_DKEK_SHARES
|
||||
from const import 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(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, keyid)
|
||||
assert(plB == plA)
|
||||
assert(plB == MESSAGE)
|
||||
126
tests/pico-hsm/test_051_chachapoly.py
Normal file
126
tests/pico-hsm/test_051_chachapoly.py
Normal file
@@ -0,0 +1,126 @@
|
||||
"""
|
||||
/*
|
||||
* This file is part of the Pico HSM distribution (https://github.com/polhenarejos/pico-hsm).
|
||||
* Copyright (c) 2022 Pol Henarejos.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import os
|
||||
from cryptography.hazmat.primitives.ciphers import aead
|
||||
import cryptography.exceptions
|
||||
from picohsm import APDUResponse, DOPrefixes, EncryptionMode, SWCodes
|
||||
from picohsm.const import DEFAULT_DKEK_SHARES
|
||||
from const import DEFAULT_DKEK
|
||||
from binascii import hexlify
|
||||
|
||||
MESSAGE = b'a secret message'
|
||||
AAD = b'this is a tag for AAD'
|
||||
|
||||
def test_prepare_chachapoly(device):
|
||||
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES)
|
||||
resp = device.import_dkek(DEFAULT_DKEK)
|
||||
resp = device.import_dkek(DEFAULT_DKEK)
|
||||
|
||||
def generate_key(device):
|
||||
# ChaCha uses 32 bytes key
|
||||
pkey = os.urandom(256 // 8)
|
||||
keyid = device.import_key(pkey)
|
||||
return pkey, keyid
|
||||
|
||||
|
||||
def test_cipher_chachapoly_cipher(device):
|
||||
iv = b'\x00'*12
|
||||
pkey, keyid = generate_key(device)
|
||||
|
||||
ctd = device.chachapoly(keyid, EncryptionMode.ENCRYPT, data=MESSAGE, aad=AAD)
|
||||
|
||||
chacha = aead.ChaCha20Poly1305(pkey)
|
||||
ctg = chacha.encrypt(iv, MESSAGE, AAD)
|
||||
assert(ctd == ctg)
|
||||
|
||||
pld = device.chachapoly(keyid, EncryptionMode.DECRYPT, data=ctd, aad=AAD)
|
||||
|
||||
plg = chacha.decrypt(iv, ctg, AAD)
|
||||
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||
assert(pld == plg)
|
||||
assert(pld == MESSAGE)
|
||||
|
||||
def test_cipher_chachapoly_random_iv(device):
|
||||
pkey, keyid = generate_key(device)
|
||||
iv = os.urandom(12)
|
||||
ctd = device.chachapoly(keyid, EncryptionMode.ENCRYPT, data=MESSAGE, iv=iv, aad=AAD)
|
||||
|
||||
chacha = aead.ChaCha20Poly1305(pkey)
|
||||
ctg = chacha.encrypt(iv, MESSAGE, AAD)
|
||||
assert(ctd == ctg)
|
||||
|
||||
pld = device.chachapoly(keyid, EncryptionMode.DECRYPT, data=ctd, iv=iv, aad=AAD)
|
||||
|
||||
plg = chacha.decrypt(iv, ctg, AAD)
|
||||
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||
assert(pld == plg)
|
||||
assert(pld == MESSAGE)
|
||||
|
||||
def test_cipher_chachapoly_no_aad(device):
|
||||
pkey, keyid = generate_key(device)
|
||||
iv = os.urandom(12)
|
||||
ctd = device.chachapoly(keyid, EncryptionMode.ENCRYPT, data=MESSAGE, iv=iv)
|
||||
|
||||
chacha = aead.ChaCha20Poly1305(pkey)
|
||||
ctg = chacha.encrypt(iv, MESSAGE, b'')
|
||||
assert(ctd == ctg)
|
||||
|
||||
pld = device.chachapoly(keyid, EncryptionMode.DECRYPT, data=ctd, iv=iv)
|
||||
|
||||
plg = chacha.decrypt(iv, ctg, b'')
|
||||
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||
assert(pld == plg)
|
||||
assert(pld == MESSAGE)
|
||||
|
||||
def test_cipher_chachapoly_bad_random_iv(device):
|
||||
pkey, keyid = generate_key(device)
|
||||
iv = os.urandom(12)
|
||||
ctd = device.chachapoly(keyid, EncryptionMode.ENCRYPT, data=MESSAGE, iv=iv, aad=AAD)
|
||||
|
||||
chacha = aead.ChaCha20Poly1305(pkey)
|
||||
ctg = chacha.encrypt(iv, MESSAGE, AAD)
|
||||
assert(ctd == ctg)
|
||||
|
||||
iv = os.urandom(12)
|
||||
with pytest.raises(APDUResponse) as e:
|
||||
pld = device.chachapoly(keyid, EncryptionMode.DECRYPT, data=ctd, iv=iv, aad=AAD)
|
||||
assert (e.value.sw == SWCodes.SW_WRONG_DATA)
|
||||
|
||||
with pytest.raises(cryptography.exceptions.InvalidTag):
|
||||
plg = chacha.decrypt(iv, ctg, AAD)
|
||||
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||
|
||||
def test_cipher_chachapoly_bad_aad(device):
|
||||
pkey, keyid = generate_key(device)
|
||||
iv = os.urandom(12)
|
||||
ctd = device.chachapoly(keyid, EncryptionMode.ENCRYPT, data=MESSAGE, iv=iv, aad=AAD)
|
||||
|
||||
chacha = aead.ChaCha20Poly1305(pkey)
|
||||
ctg = chacha.encrypt(iv, MESSAGE, AAD)
|
||||
assert(ctd == ctg)
|
||||
|
||||
with pytest.raises(APDUResponse) as e:
|
||||
pld = device.chachapoly(keyid, EncryptionMode.DECRYPT, data=ctd, iv=iv, aad=AAD + b'bad')
|
||||
assert (e.value.sw == SWCodes.SW_WRONG_DATA)
|
||||
|
||||
with pytest.raises(cryptography.exceptions.InvalidTag):
|
||||
plg = chacha.decrypt(iv, ctg, AAD + b'bad')
|
||||
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||
342
tests/pico-hsm/test_052_aes_ext.py
Normal file
342
tests/pico-hsm/test_052_aes_ext.py
Normal file
@@ -0,0 +1,342 @@
|
||||
"""
|
||||
/*
|
||||
* This file is part of the Pico HSM distribution (https://github.com/polhenarejos/pico-hsm).
|
||||
* Copyright (c) 2022 Pol Henarejos.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import os
|
||||
from cryptography.hazmat.primitives.ciphers import Cipher, algorithms, modes, aead
|
||||
import cryptography.exceptions
|
||||
from picohsm import APDUResponse, DOPrefixes, EncryptionMode, SWCodes, AES
|
||||
from picohsm.const import DEFAULT_DKEK_SHARES
|
||||
from const import DEFAULT_DKEK
|
||||
from binascii import hexlify
|
||||
|
||||
MESSAGE = b'a secret message'
|
||||
AAD = b'this is a tag for AAD'
|
||||
|
||||
def test_prepare_aes(device):
|
||||
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES)
|
||||
resp = device.import_dkek(DEFAULT_DKEK)
|
||||
resp = device.import_dkek(DEFAULT_DKEK)
|
||||
|
||||
def generate_key(device, size):
|
||||
pkey = os.urandom(size // 8)
|
||||
keyid = device.import_key(pkey)
|
||||
return pkey, keyid
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"size", [128, 192, 256]
|
||||
)
|
||||
def test_aes_ecb(device, size):
|
||||
pkey, keyid = generate_key(device, size)
|
||||
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.ECB, MESSAGE)
|
||||
|
||||
cipher = Cipher(algorithms.AES(pkey), modes.ECB())
|
||||
encryptor = cipher.encryptor()
|
||||
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||
assert(ctA == ctB)
|
||||
|
||||
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.ECB, ctA)
|
||||
decryptor = cipher.decryptor()
|
||||
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||
assert(dtA == dtB)
|
||||
assert(dtA == MESSAGE)
|
||||
device.delete_key(keyid)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"size", [128, 192, 256]
|
||||
)
|
||||
def test_aes_cbc_no_iv(device, size):
|
||||
pkey, keyid = generate_key(device, size)
|
||||
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.CBC, MESSAGE)
|
||||
|
||||
iv = b'\x00' * 16
|
||||
cipher = Cipher(algorithms.AES(pkey), modes.CBC(iv))
|
||||
encryptor = cipher.encryptor()
|
||||
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||
assert(ctA == ctB)
|
||||
|
||||
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.CBC, ctA)
|
||||
decryptor = cipher.decryptor()
|
||||
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||
assert(dtA == dtB)
|
||||
assert(dtA == MESSAGE)
|
||||
device.delete_key(keyid)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"size", [128, 192, 256]
|
||||
)
|
||||
def test_aes_cbc_iv(device, size):
|
||||
pkey, keyid = generate_key(device, size)
|
||||
iv = os.urandom(16)
|
||||
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.CBC, MESSAGE, iv=iv)
|
||||
|
||||
cipher = Cipher(algorithms.AES(pkey), modes.CBC(iv))
|
||||
encryptor = cipher.encryptor()
|
||||
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||
assert(ctA == ctB)
|
||||
|
||||
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.CBC, ctA, iv=iv)
|
||||
decryptor = cipher.decryptor()
|
||||
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||
assert(dtA == dtB)
|
||||
assert(dtA == MESSAGE)
|
||||
device.delete_key(keyid)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"size", [128, 192, 256]
|
||||
)
|
||||
def test_aes_ofb_no_iv(device, size):
|
||||
pkey, keyid = generate_key(device, size)
|
||||
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.OFB, MESSAGE)
|
||||
|
||||
iv = b'\x00' * 16
|
||||
cipher = Cipher(algorithms.AES(pkey), modes.OFB(iv))
|
||||
encryptor = cipher.encryptor()
|
||||
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||
assert(ctA == ctB)
|
||||
|
||||
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.OFB, ctA)
|
||||
decryptor = cipher.decryptor()
|
||||
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||
assert(dtA == dtB)
|
||||
assert(dtA == MESSAGE)
|
||||
device.delete_key(keyid)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"size", [128, 192, 256]
|
||||
)
|
||||
def test_aes_ofb_iv(device, size):
|
||||
pkey, keyid = generate_key(device, size)
|
||||
iv = os.urandom(16)
|
||||
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.OFB, MESSAGE, iv=iv)
|
||||
|
||||
cipher = Cipher(algorithms.AES(pkey), modes.OFB(iv))
|
||||
encryptor = cipher.encryptor()
|
||||
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||
assert(ctA == ctB)
|
||||
|
||||
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.OFB, ctA, iv=iv)
|
||||
decryptor = cipher.decryptor()
|
||||
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||
assert(dtA == dtB)
|
||||
assert(dtA == MESSAGE)
|
||||
device.delete_key(keyid)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"size", [128, 192, 256]
|
||||
)
|
||||
def test_aes_cfb_no_iv(device, size):
|
||||
pkey, keyid = generate_key(device, size)
|
||||
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.CFB, MESSAGE)
|
||||
|
||||
iv = b'\x00' * 16
|
||||
cipher = Cipher(algorithms.AES(pkey), modes.CFB(iv))
|
||||
encryptor = cipher.encryptor()
|
||||
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||
assert(ctA == ctB)
|
||||
|
||||
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.CFB, ctA)
|
||||
decryptor = cipher.decryptor()
|
||||
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||
assert(dtA == dtB)
|
||||
assert(dtA == MESSAGE)
|
||||
device.delete_key(keyid)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"size", [128, 192, 256]
|
||||
)
|
||||
def test_aes_cfb_iv(device, size):
|
||||
pkey, keyid = generate_key(device, size)
|
||||
iv = os.urandom(16)
|
||||
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.CFB, MESSAGE, iv=iv)
|
||||
|
||||
cipher = Cipher(algorithms.AES(pkey), modes.CFB(iv))
|
||||
encryptor = cipher.encryptor()
|
||||
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||
assert(ctA == ctB)
|
||||
|
||||
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.CFB, ctA, iv=iv)
|
||||
decryptor = cipher.decryptor()
|
||||
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||
assert(dtA == dtB)
|
||||
assert(dtA == MESSAGE)
|
||||
device.delete_key(keyid)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"size", [128, 192, 256]
|
||||
)
|
||||
def test_aes_gcm_no_iv(device, size):
|
||||
pkey, keyid = generate_key(device, size)
|
||||
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.GCM, MESSAGE, aad=AAD)
|
||||
|
||||
iv = b'\x00' * 16
|
||||
encryptor = Cipher(algorithms.AES(pkey), modes.GCM(iv)).encryptor()
|
||||
encryptor.authenticate_additional_data(AAD)
|
||||
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||
assert(ctA == ctB + encryptor.tag)
|
||||
|
||||
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.GCM, ctA, aad=AAD)
|
||||
decryptor = Cipher(algorithms.AES(pkey), modes.GCM(iv, encryptor.tag)).decryptor()
|
||||
decryptor.authenticate_additional_data(AAD)
|
||||
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||
assert(dtA == dtB)
|
||||
assert(dtA == MESSAGE)
|
||||
device.delete_key(keyid)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"size", [128, 192, 256]
|
||||
)
|
||||
def test_aes_gcm_iv(device, size):
|
||||
pkey, keyid = generate_key(device, size)
|
||||
iv = os.urandom(16)
|
||||
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.GCM, MESSAGE, iv=iv, aad=AAD)
|
||||
|
||||
encryptor = Cipher(algorithms.AES(pkey), modes.GCM(iv)).encryptor()
|
||||
encryptor.authenticate_additional_data(AAD)
|
||||
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||
assert(ctA == ctB + encryptor.tag)
|
||||
|
||||
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.GCM, ctA, iv=iv, aad=AAD)
|
||||
decryptor = Cipher(algorithms.AES(pkey), modes.GCM(iv, encryptor.tag)).decryptor()
|
||||
decryptor.authenticate_additional_data(AAD)
|
||||
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||
assert(dtA == dtB)
|
||||
assert(dtA == MESSAGE)
|
||||
device.delete_key(keyid)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"size", [256, 512]
|
||||
)
|
||||
def test_aes_xts_no_iv(device, size):
|
||||
pkey, keyid = generate_key(device, size)
|
||||
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.XTS, MESSAGE)
|
||||
|
||||
iv = b'\x00' * 16
|
||||
cipher = Cipher(algorithms.AES(pkey), modes.XTS(iv))
|
||||
encryptor = cipher.encryptor()
|
||||
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||
assert(ctA == ctB)
|
||||
|
||||
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.XTS, ctA)
|
||||
decryptor = cipher.decryptor()
|
||||
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||
assert(dtA == dtB)
|
||||
assert(dtA == MESSAGE)
|
||||
device.delete_key(keyid)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"size", [256, 512]
|
||||
)
|
||||
def test_aes_xts_iv(device, size):
|
||||
pkey, keyid = generate_key(device, size)
|
||||
iv = os.urandom(16)
|
||||
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.XTS, MESSAGE, iv=iv)
|
||||
|
||||
cipher = Cipher(algorithms.AES(pkey), modes.XTS(iv))
|
||||
encryptor = cipher.encryptor()
|
||||
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||
assert(ctA == ctB)
|
||||
|
||||
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.XTS, ctA, iv=iv)
|
||||
decryptor = cipher.decryptor()
|
||||
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||
assert(dtA == dtB)
|
||||
assert(dtA == MESSAGE)
|
||||
device.delete_key(keyid)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"size", [128, 192, 256]
|
||||
)
|
||||
def test_aes_ctr_no_iv(device, size):
|
||||
pkey, keyid = generate_key(device, size)
|
||||
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.CTR, MESSAGE)
|
||||
|
||||
iv = b'\x00' * 16
|
||||
cipher = Cipher(algorithms.AES(pkey), modes.CTR(iv))
|
||||
encryptor = cipher.encryptor()
|
||||
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||
assert(ctA == ctB)
|
||||
|
||||
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.CTR, ctA)
|
||||
decryptor = cipher.decryptor()
|
||||
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||
assert(dtA == dtB)
|
||||
assert(dtA == MESSAGE)
|
||||
device.delete_key(keyid)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"size", [128, 192, 256]
|
||||
)
|
||||
def test_aes_ctr_iv(device, size):
|
||||
pkey, keyid = generate_key(device, size)
|
||||
iv = os.urandom(16)
|
||||
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.CTR, MESSAGE, iv=iv)
|
||||
|
||||
cipher = Cipher(algorithms.AES(pkey), modes.CTR(iv))
|
||||
encryptor = cipher.encryptor()
|
||||
ctB = encryptor.update(MESSAGE) + encryptor.finalize()
|
||||
assert(ctA == ctB)
|
||||
|
||||
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.CTR, ctA, iv=iv)
|
||||
decryptor = cipher.decryptor()
|
||||
dtB = decryptor.update(ctB) + decryptor.finalize()
|
||||
assert(dtA == dtB)
|
||||
assert(dtA == MESSAGE)
|
||||
device.delete_key(keyid)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"size", [128, 192, 256]
|
||||
)
|
||||
def test_aes_ccm_no_iv(device, size):
|
||||
pkey, keyid = generate_key(device, size)
|
||||
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.CCM, MESSAGE, aad=AAD)
|
||||
|
||||
iv = b'\x00' * 12
|
||||
encryptor = aead.AESCCM(pkey)
|
||||
ctB = encryptor.encrypt(iv, MESSAGE, AAD)
|
||||
assert(ctA == ctB)
|
||||
|
||||
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.CCM, ctA, aad=AAD)
|
||||
decryptor = encryptor
|
||||
dtB = decryptor.decrypt(iv, ctB, AAD)
|
||||
assert(dtA == dtB)
|
||||
assert(dtA == MESSAGE)
|
||||
device.delete_key(keyid)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"size", [128, 192, 256]
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"iv_len", [7, 8, 9, 10, 11, 12, 13]
|
||||
)
|
||||
def test_aes_ccm_iv(device, size, iv_len):
|
||||
pkey, keyid = generate_key(device, size)
|
||||
iv = os.urandom(iv_len)
|
||||
ctA = device.aes(keyid, EncryptionMode.ENCRYPT, AES.CCM, MESSAGE, iv=iv, aad=AAD)
|
||||
|
||||
encryptor = aead.AESCCM(pkey)
|
||||
ctB = encryptor.encrypt(iv, MESSAGE, AAD)
|
||||
assert(ctA == ctB)
|
||||
|
||||
dtA = device.aes(keyid, EncryptionMode.DECRYPT, AES.CCM, ctA, iv=iv, aad=AAD)
|
||||
decryptor = encryptor
|
||||
dtB = decryptor.decrypt(iv, ctB, AAD)
|
||||
assert(dtA == dtB)
|
||||
assert(dtA == MESSAGE)
|
||||
device.delete_key(keyid)
|
||||
63
tests/pico-hsm/test_060_mac.py
Normal file
63
tests/pico-hsm/test_060_mac.py
Normal file
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
/*
|
||||
* 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 picohsm import DOPrefixes
|
||||
from picohsm.const import DEFAULT_DKEK_SHARES
|
||||
from const import 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, keyid)
|
||||
assert(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, keyid)
|
||||
assert(resA == resB)
|
||||
|
||||
82
tests/pico-hsm/test_070_hkdf.py
Normal file
82
tests/pico-hsm/test_070_hkdf.py
Normal file
@@ -0,0 +1,82 @@
|
||||
"""
|
||||
/*
|
||||
* 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 picohsm.const import DEFAULT_DKEK_SHARES
|
||||
from const import DEFAULT_DKEK
|
||||
from picohsm 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, keyid)
|
||||
hkdf = HKDF(
|
||||
algorithm=algo(),
|
||||
length=out_len,
|
||||
salt=salt,
|
||||
info=INFO,
|
||||
)
|
||||
resB = hkdf.derive(pkey)
|
||||
assert(resA == resB)
|
||||
hkdf = HKDF(
|
||||
algorithm=algo(),
|
||||
length=out_len,
|
||||
salt=salt,
|
||||
info=INFO,
|
||||
)
|
||||
hkdf.verify(pkey, 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, 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, resA)
|
||||
86
tests/pico-hsm/test_071_pbkdf2.py
Normal file
86
tests/pico-hsm/test_071_pbkdf2.py
Normal file
@@ -0,0 +1,86 @@
|
||||
"""
|
||||
/*
|
||||
* 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 picohsm.const import DEFAULT_DKEK_SHARES
|
||||
from const import DEFAULT_DKEK
|
||||
from picohsm 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, keyid)
|
||||
kdf = PBKDF2HMAC(
|
||||
algorithm=algo(),
|
||||
length=out_len,
|
||||
salt=salt,
|
||||
iterations=iterations,
|
||||
)
|
||||
resB = kdf.derive(pkey)
|
||||
assert(resA == resB)
|
||||
kdf = PBKDF2HMAC(
|
||||
algorithm=algo(),
|
||||
length=out_len,
|
||||
salt=salt,
|
||||
iterations=iterations,
|
||||
)
|
||||
kdf.verify(pkey, 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, 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, resA)
|
||||
77
tests/pico-hsm/test_072_x963.py
Normal file
77
tests/pico-hsm/test_072_x963.py
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/>.
|
||||
*/
|
||||
"""
|
||||
|
||||
import pytest
|
||||
import os
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from cryptography.hazmat.primitives.kdf.x963kdf import X963KDF
|
||||
from cryptography import exceptions
|
||||
from picohsm.const import DEFAULT_DKEK_SHARES
|
||||
from const import DEFAULT_DKEK
|
||||
from picohsm 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, keyid)
|
||||
xkdf = X963KDF(
|
||||
algorithm=algo(),
|
||||
length=out_len,
|
||||
sharedinfo=INFO,
|
||||
)
|
||||
resB = xkdf.derive(pkey)
|
||||
assert(resA == resB)
|
||||
xkdf = X963KDF(
|
||||
algorithm=algo(),
|
||||
length=out_len,
|
||||
sharedinfo=INFO,
|
||||
)
|
||||
xkdf.verify(pkey, 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, keyid)
|
||||
xkdf = X963KDF(
|
||||
algorithm=algo(),
|
||||
length=out_len,
|
||||
sharedinfo=INFO,
|
||||
)
|
||||
pkey = os.urandom(size // 8)
|
||||
with pytest.raises(exceptions.InvalidKey):
|
||||
xkdf.verify(pkey, resA)
|
||||
146
tests/pico-hsm/test_080_pka.py
Normal file
146
tests/pico-hsm/test_080_pka.py
Normal file
@@ -0,0 +1,146 @@
|
||||
"""
|
||||
/*
|
||||
* This file is part of the Pico HSM distribution (https://github.com/polhenarejos/pico-hsm).
|
||||
* Copyright (c) 2023 Pol Henarejos.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from binascii import unhexlify, hexlify
|
||||
from cvc.certificates import CVC
|
||||
from picohsm.utils import int_to_bytes
|
||||
from picohsm import APDUResponse, SWCodes
|
||||
from const import TERM_CERT, DICA_CERT
|
||||
from cryptography.hazmat.primitives.asymmetric import ec, utils
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
|
||||
AUT_KEY = unhexlify('0A40E11E672C28C558B72C25D93BCF28C08D39AFDD5A1A2FD3BAF7A6B27F0C2E')
|
||||
aut_pk = ec.derive_private_key(int.from_bytes(AUT_KEY, 'big'), ec.BrainpoolP256R1())
|
||||
AUT_PUK = unhexlify('678201ed7f218201937f4e82014b5f290100421045535049434f48534d54525a474e50327f4982011d060a04007f000702020202038120a9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e537782207d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9832026dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b68441048bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f0469978520a9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a78641040cc18ce246da678239af0913a1579dda58c07be404da4a65327794fac93f57a333267979905b5d046da7020226cc4e5fc477e8fc651a0cf87095259aafa88e648701015f201045535049434f48534d54525a474e50325f37401fc90bdab2a58c3cd25f18a90baa2c21d3d087002ba240fb274ff066759297f79e130053d902d637a448c8cdcd0670fe8ebcc06d8a3ee82079f08d1ff8660393421045535049434f48534d54525a474e50325f3740e24e7e23eae3c78f9fa88391004369a293c43ef99e2279170983e1dbe707fbf0382d09de3e60ef1addd2f055947c3efcef17926065ddb7a031f4905da474ed1d')
|
||||
|
||||
|
||||
term_chr = CVC().decode(TERM_CERT).chr()
|
||||
|
||||
def test_initialize(device):
|
||||
device.initialize(puk_auts=1, puk_min_auts=1)
|
||||
device.logout()
|
||||
|
||||
def test_register_puk(device):
|
||||
status = device.get_puk_status()
|
||||
assert(status == bytes([1,1,1,0]))
|
||||
|
||||
status = device.register_puk(AUT_PUK, TERM_CERT, DICA_CERT)
|
||||
assert(status == bytes([1,0,1,0]))
|
||||
assert(device.check_puk_key(term_chr) == 0)
|
||||
|
||||
def test_enumerate_puk_reg(device):
|
||||
puks = device.enumerate_puk()
|
||||
assert(len(puks) == 1)
|
||||
assert(puks[0]['status'] == 0)
|
||||
|
||||
def test_authentication(device):
|
||||
input = device.puk_prepare_signature()
|
||||
signature = aut_pk.sign(input, ec.ECDSA(hashes.SHA256()))
|
||||
r,s = utils.decode_dss_signature(signature)
|
||||
signature = list(int_to_bytes(r) + int_to_bytes(s))
|
||||
device.authenticate_puk(term_chr, signature)
|
||||
status = device.get_puk_status()
|
||||
assert(status == bytes([1,0,1,1]))
|
||||
|
||||
def test_enumerate_puk_ok(device):
|
||||
puks = device.enumerate_puk()
|
||||
assert(len(puks) == 1)
|
||||
assert(puks[0]['status'] == 1)
|
||||
|
||||
def test_check_key(device):
|
||||
assert(device.check_puk_key(term_chr) == 1)
|
||||
bad_chr = b'XXXXX'
|
||||
assert(device.check_puk_key(bad_chr) == -1)
|
||||
assert(device.check_puk_key(bad_chr) != 0)
|
||||
assert(device.check_puk_key(bad_chr) != 1)
|
||||
|
||||
def test_puk_reset(device):
|
||||
device.logout()
|
||||
status = device.get_puk_status()
|
||||
assert(status == bytes([1,0,1,0]))
|
||||
assert(device.check_puk_key(term_chr) == 0)
|
||||
|
||||
def test_authentication_fail(device):
|
||||
input = b'this is a fake input'
|
||||
signature = aut_pk.sign(input, ec.ECDSA(hashes.SHA256()))
|
||||
r,s = utils.decode_dss_signature(signature)
|
||||
signature = list(int_to_bytes(r) + int_to_bytes(s))
|
||||
with pytest.raises(APDUResponse) as e:
|
||||
device.authenticate_puk(term_chr, signature)
|
||||
assert(e.value.sw == SWCodes.SW_CONDITIONS_NOT_SATISFIED)
|
||||
|
||||
status = device.get_puk_status()
|
||||
assert(status == bytes([1,0,1,0]))
|
||||
assert(device.check_puk_key(term_chr) == 0)
|
||||
|
||||
def test_enumerate_puk_1(device):
|
||||
device.initialize(puk_auts=1, puk_min_auts=1)
|
||||
puks = device.enumerate_puk()
|
||||
assert(len(puks) == 1)
|
||||
assert(puks[0]['status'] == -1)
|
||||
|
||||
device.register_puk(AUT_PUK, TERM_CERT, DICA_CERT)
|
||||
puks = device.enumerate_puk()
|
||||
assert(len(puks) == 1)
|
||||
assert(puks[0]['status'] == 0)
|
||||
|
||||
def test_enumerate_puk_2(device):
|
||||
device.initialize(puk_auts=2, puk_min_auts=1)
|
||||
puks = device.enumerate_puk()
|
||||
assert(len(puks) == 2)
|
||||
assert(puks[0]['status'] == -1)
|
||||
assert(puks[1]['status'] == -1)
|
||||
|
||||
device.register_puk(AUT_PUK, TERM_CERT, DICA_CERT)
|
||||
puks = device.enumerate_puk()
|
||||
assert(len(puks) == 2)
|
||||
assert(puks[0]['status'] == 0)
|
||||
assert(puks[1]['status'] == -1)
|
||||
|
||||
def test_register_more_puks(device):
|
||||
device.initialize(puk_auts=2, puk_min_auts=1)
|
||||
status = device.get_puk_status()
|
||||
assert(status == bytes([2,2,1,0]))
|
||||
|
||||
status = device.register_puk(AUT_PUK, TERM_CERT, DICA_CERT)
|
||||
assert(status == bytes([2,1,1,0]))
|
||||
|
||||
def test_is_pku(device):
|
||||
device.initialize(puk_auts=1, puk_min_auts=1)
|
||||
assert(device.is_puk() == True)
|
||||
|
||||
device.initialize()
|
||||
assert(device.is_puk() == False)
|
||||
|
||||
def test_check_puk_key(device):
|
||||
device.initialize(puk_auts=1, puk_min_auts=1)
|
||||
status = device.check_puk_key(term_chr)
|
||||
assert(status == -1)
|
||||
|
||||
status = device.register_puk(AUT_PUK, TERM_CERT, DICA_CERT)
|
||||
status = device.check_puk_key(term_chr)
|
||||
assert(status == 0)
|
||||
|
||||
|
||||
def test_register_puk_with_no_puk(device):
|
||||
device.initialize()
|
||||
with pytest.raises(APDUResponse) as e:
|
||||
device.register_puk(AUT_PUK, TERM_CERT, DICA_CERT)
|
||||
assert(e.value.sw == SWCodes.SW_FILE_NOT_FOUND)
|
||||
98
tests/pico-hsm/test_090_xkek.py
Normal file
98
tests/pico-hsm/test_090_xkek.py
Normal file
@@ -0,0 +1,98 @@
|
||||
"""
|
||||
/*
|
||||
* This file is part of the Pico HSM distribution (https://github.com/polhenarejos/pico-hsm).
|
||||
* Copyright (c) 2023 Pol Henarejos.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from binascii import unhexlify, hexlify
|
||||
from picohsm.utils import int_to_bytes
|
||||
from const import TERM_CERT, DICA_CERT
|
||||
from cvc.asn1 import ASN1
|
||||
from cvc.certificates import CVC
|
||||
from cvc import oid
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from picohsm import DOPrefixes, APDUResponse, SWCodes
|
||||
|
||||
KDM = unhexlify(b'30820420060b2b0601040181c31f0402016181ed7f2181e97f4e81a25f290100421045535049434f48534d434130303030317f494f060a04007f0007020202020386410421ee4a21c16a10f737f12e78e5091b266612038cdabebb722b15bf6d41b877fbf64d9ab69c39b9831b1ae00bef2a4e81976f7688d45189bb232a24703d8a96a55f201045535049434f48534d445630303030317f4c12060904007f000703010202530580000000005f25060202000801085f24060203000601045f37403f75c08fffc9186b56e6147199e82bfc327ceef72495bc567961cd54d702f13e3c2766fcd1d11bd6a9d1f4a229b76b248ceb9af88d59a74d0ab149448705159b6281e97f2181e57f4e819e5f290100421045535049434f48534d445630303030317f494f060a04007f00070202020203864104c8561b41e54fea81bb80dd4a6d537e7c3904344e8ca90bc5f668111811e02c8d5d51ca93ca89558f2a8a9cbb147434e3441ec174505ff980fd7a7106286196915f201045535049434f48534d54524a444736387f4c0e060904007f0007030102025301005f25060203000300065f24060204000300055f3740983de63d0975b715ebd8a93cb38fa9638882c8b7064d51a6facabed693b92edc098e458b713203413ef6de0958c44772cbdbc264205c7b1bdb8b4fcb2516437f638201f1678201ed7f218201937f4e82014b5f290100421045535049434f48534d54524a444736387f4982011d060a04007f000702020202038120a9fb57dba1eea9bc3e660a909d838d726e3bf623d52620282013481d1f6e537782207d5a0975fc2c3057eef67530417affe7fb8055c126dc5c6ce94a4b44f330b5d9832026dc5c6ce94a4b44f330b5d9bbd77cbf958416295cf7e1ce6bccdc18ff8c07b68441048bd2aeb9cb7e57cb2c4b482ffc81b7afb9de27e1e3bd23c23a4453bd9ace3262547ef835c3dac4fd97f8461a14611dc9c27745132ded8e545c1d54c72f0469978520a9fb57dba1eea9bc3e660a909d838d718c397aa3b561a6f7901e0e82974856a78641048b1f450912a2e4d428b7eefc5fa05618a9ef295e90009a61cbb0970181b333474ea94f94cde5a11aba0589e85d4225002789ff1cdcf25756f059647b49fc2a158701015f201045535049434f48534d54524a444736385f3740372407c20de7257c89dae1e6606c8a046ca65efaa010c0a22b75c402ee243de51f5f1507457193679ed9db4fbbfe8efb9d695b684492b665ad8ba98c1f84ea38421045535049434f48534d54524a444736385f374098718e2e14a44386b689b71a101530316b65ab49a91bab0dd56099c5161ecb8aadff6cf27449f94034e58b7306f01e6ffa2766a2f5bb1281e12e5f1f9174733454400cf8926ca5bec9a91bcd47bf391c15d94ef6e3243d5fd1fffeaafd586766bc3221eafd808f17f8450f238cc1fe7ab1854443db31d622f53a2b3fdb3ad750d5ce')
|
||||
|
||||
def test_initialize(device):
|
||||
device.initialize(key_domains=1)
|
||||
device.logout()
|
||||
|
||||
def test_create_xkek(device):
|
||||
with pytest.raises(APDUResponse) as e:
|
||||
device.create_xkek(KDM)
|
||||
assert(e.value.sw == SWCodes.SW_CONDITIONS_NOT_SATISFIED)
|
||||
|
||||
device.login()
|
||||
kcv, did = device.create_xkek(KDM)
|
||||
assert(kcv == b'\x00'*8)
|
||||
|
||||
gskcert = ASN1().decode(KDM).find(0x30).find(0x63).data()
|
||||
gskQ = CVC().decode(gskcert).pubkey().find(0x86).data()
|
||||
pub = ec.EllipticCurvePublicKey.from_encoded_point(ec.BrainpoolP256R1(), bytes(gskQ))
|
||||
assert(did == int_to_bytes(pub.public_numbers().x)+int_to_bytes(pub.public_numbers().y))
|
||||
|
||||
keyid = -1
|
||||
def test_derive_xkek(device):
|
||||
global keyid
|
||||
keyid = device.generate_xkek_key()
|
||||
|
||||
resp = device.list_keys()
|
||||
assert((DOPrefixes.KEY_PREFIX, keyid) in resp)
|
||||
|
||||
xkek_dom = device.get_key_domain()['xkek']
|
||||
pkey = ec.generate_private_key(ec.BrainpoolP256R1())
|
||||
pubkey = pkey.public_key()
|
||||
cert = CVC().cert(pubkey=pubkey, scheme=oid.ID_TA_ECDSA_SHA_256, signkey=pkey, signscheme=oid.ID_TA_ECDSA_SHA_256, car=b"UTCA00001", chr=b"UTCDUMMY00001", extensions=[
|
||||
{
|
||||
'tag': 0x73,
|
||||
'oid': b'\x2B\x06\x01\x04\x01\x81\xC3\x1F\x03\x02\x02',
|
||||
'contexts': {
|
||||
0: xkek_dom
|
||||
}
|
||||
}
|
||||
]).encode()
|
||||
device.derive_xkek(keyid, cert)
|
||||
|
||||
resp = device.get_key_domain()
|
||||
assert(resp['kcv'] != b'\x00'*8)
|
||||
|
||||
|
||||
def test_delete_xkek(device):
|
||||
device.delete_xkek()
|
||||
|
||||
resp = device.get_key_domain()
|
||||
assert(resp['kcv'] == b'\x00'*8)
|
||||
|
||||
def test_delete_domain_with_key(device):
|
||||
with pytest.raises(APDUResponse) as e:
|
||||
device.delete_key_domain()
|
||||
assert(e.value.sw == SWCodes.SW_FILE_EXISTS)
|
||||
|
||||
device.delete_file(DOPrefixes.KEY_PREFIX, keyid)
|
||||
device.delete_file(DOPrefixes.EE_CERTIFICATE_PREFIX, keyid)
|
||||
|
||||
def test_delete_domain(device):
|
||||
device.delete_key_domain()
|
||||
|
||||
resp = device.get_key_domain()
|
||||
assert('kcv' not in resp)
|
||||
assert('xkek' not in resp)
|
||||
assert('error' in resp)
|
||||
assert(resp['error'] == SWCodes.SW_REFERENCE_NOT_FOUND)
|
||||
|
||||
453
tests/pico-hsm/test_095_bip_slip.py
Normal file
453
tests/pico-hsm/test_095_bip_slip.py
Normal file
@@ -0,0 +1,453 @@
|
||||
"""
|
||||
/*
|
||||
* This file is part of the Pico HSM distribution (https://github.com/polhenarejos/pico-hsm).
|
||||
* Copyright (c) 2023 Pol Henarejos.
|
||||
*
|
||||
* This program is free software: you can redistribute it and/or modify
|
||||
* it under the terms of the GNU General Public License as published by
|
||||
* the Free Software Foundation, version 3.
|
||||
*
|
||||
* This program is distributed in the hope that it will be useful, but
|
||||
* WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
|
||||
* General Public License for more details.
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License
|
||||
* along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
*/
|
||||
"""
|
||||
|
||||
import pytest
|
||||
from binascii import unhexlify, hexlify
|
||||
from picohsm.utils import int_to_bytes
|
||||
from picohsm.const import DEFAULT_DKEK_SHARES
|
||||
from const import DEFAULT_DKEK
|
||||
from cvc.asn1 import ASN1
|
||||
from cvc.certificates import CVC
|
||||
from cvc import oid
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.hazmat.primitives import hashes
|
||||
from picohsm import EncryptionMode, APDUResponse, SWCodes, PicoHSM
|
||||
import hashlib
|
||||
|
||||
TEST_STRING = b'Pico Keys are awesome!'
|
||||
|
||||
def sha256_sha256(data):
|
||||
return hashlib.sha256(hashlib.sha256(data).digest()).digest()
|
||||
|
||||
def test_initialize(device):
|
||||
device.initialize(dkek_shares=DEFAULT_DKEK_SHARES)
|
||||
resp = device.import_dkek(DEFAULT_DKEK)
|
||||
resp = device.import_dkek(DEFAULT_DKEK)
|
||||
|
||||
seeds = [
|
||||
{
|
||||
'name': 'secp256k1',
|
||||
'id': 0,
|
||||
'seed': unhexlify('000102030405060708090a0b0c0d0e0f'),
|
||||
},
|
||||
{
|
||||
'name': 'secp256k1',
|
||||
'id': 1,
|
||||
'seed': unhexlify('fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542'),
|
||||
},
|
||||
{
|
||||
'name': 'secp256k1',
|
||||
'id': 2,
|
||||
'seed': unhexlify('4b381541583be4423346c643850da4b320e46a87ae3d2a4e6da11eba819cd4acba45d239319ac14f863b8d5ab5a0d0c64d2e8a1e7d1457df2e5a3c51c73235be'),
|
||||
},
|
||||
{
|
||||
'name': 'secp256k1',
|
||||
'id': 3,
|
||||
'seed': unhexlify('3ddd5602285899a946114506157c7997e5444528f3003f6134712147db19b678'),
|
||||
},
|
||||
{
|
||||
'name': 'secp256r1',
|
||||
'id': 4,
|
||||
'seed': unhexlify('000102030405060708090a0b0c0d0e0f'),
|
||||
},
|
||||
{
|
||||
'name': 'secp256r1',
|
||||
'id': 5,
|
||||
'seed': unhexlify('fffcf9f6f3f0edeae7e4e1dedbd8d5d2cfccc9c6c3c0bdbab7b4b1aeaba8a5a29f9c999693908d8a8784817e7b7875726f6c696663605d5a5754514e4b484542'),
|
||||
},
|
||||
{
|
||||
'name': 'secp256r1',
|
||||
'id': 6,
|
||||
'seed': unhexlify('a7305bc8df8d0951f0cb224c0e95d7707cbdf2c6ce7e8d481fec69c7ff5e9446'),
|
||||
},
|
||||
{
|
||||
'name': 'symmetric',
|
||||
'id': 7,
|
||||
'seed': unhexlify('c76c4ac4f4e4a00d6b274d5c39c700bb4a7ddc04fbc6f78e85ca75007b5b495f74a9043eeb77bdd53aa6fc3a0e31462270316fa04b8c19114c8798706cd02ac8'),
|
||||
},
|
||||
]
|
||||
@pytest.mark.parametrize(
|
||||
"seed", seeds
|
||||
)
|
||||
def test_generate_master(device, seed):
|
||||
resp = device.hd_generate_master_node(curve=seed['name'], id=seed['id'], seed=seed['seed'])
|
||||
|
||||
def hardened(i):
|
||||
return 0x80000000 + i
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"path", [
|
||||
{
|
||||
'path': [0],
|
||||
'xpub': b'xpub661MyMwAqRbcFtXgS5sYJABqqG9YLmC4Q1Rdap9gSE8NqtwybGhePY2gZ29ESFjqJoCu1Rupje8YtGqsefD265TMg7usUDFdp6W1EGMcet8',
|
||||
},
|
||||
{
|
||||
'path': [0, hardened(0)],
|
||||
'xpub': b'xpub68Gmy5EdvgibQVfPdqkBBCHxA5htiqg55crXYuXoQRKfDBFA1WEjWgP6LHhwBZeNK1VTsfTFUHCdrfp1bgwQ9xv5ski8PX9rL2dZXvgGDnw',
|
||||
},
|
||||
{
|
||||
'path': [0, hardened(0), 1],
|
||||
'xpub': b'xpub6ASuArnXKPbfEwhqN6e3mwBcDTgzisQN1wXN9BJcM47sSikHjJf3UFHKkNAWbWMiGj7Wf5uMash7SyYq527Hqck2AxYysAA7xmALppuCkwQ',
|
||||
},
|
||||
{
|
||||
'path': [0, hardened(0), 1, hardened(2)],
|
||||
'xpub': b'xpub6D4BDPcP2GT577Vvch3R8wDkScZWzQzMMUm3PWbmWvVJrZwQY4VUNgqFJPMM3No2dFDFGTsxxpG5uJh7n7epu4trkrX7x7DogT5Uv6fcLW5',
|
||||
},
|
||||
{
|
||||
'path': [0, hardened(0), 1, hardened(2), 2],
|
||||
'xpub': b'xpub6FHa3pjLCk84BayeJxFW2SP4XRrFd1JYnxeLeU8EqN3vDfZmbqBqaGJAyiLjTAwm6ZLRQUMv1ZACTj37sR62cfN7fe5JnJ7dh8zL4fiyLHV',
|
||||
},
|
||||
{
|
||||
'path': [0, hardened(0), 1, hardened(2), 2, 1000000000],
|
||||
'xpub': b'xpub6H1LXWLaKsWFhvm6RVpEL9P4KfRZSW7abD2ttkWP3SSQvnyA8FSVqNTEcYFgJS2UaFcxupHiYkro49S8yGasTvXEYBVPamhGW6cFJodrTHy',
|
||||
},
|
||||
{
|
||||
'path': [1],
|
||||
'xpub': b'xpub661MyMwAqRbcFW31YEwpkMuc5THy2PSt5bDMsktWQcFF8syAmRUapSCGu8ED9W6oDMSgv6Zz8idoc4a6mr8BDzTJY47LJhkJ8UB7WEGuduB',
|
||||
},
|
||||
{
|
||||
'path': [1, 0],
|
||||
'xpub': b'xpub69H7F5d8KSRgmmdJg2KhpAK8SR3DjMwAdkxj3ZuxV27CprR9LgpeyGmXUbC6wb7ERfvrnKZjXoUmmDznezpbZb7ap6r1D3tgFxHmwMkQTPH',
|
||||
},
|
||||
{
|
||||
'path': [1, 0, hardened(2147483647)],
|
||||
'xpub': b'xpub6ASAVgeehLbnwdqV6UKMHVzgqAG8Gr6riv3Fxxpj8ksbH9ebxaEyBLZ85ySDhKiLDBrQSARLq1uNRts8RuJiHjaDMBU4Zn9h8LZNnBC5y4a',
|
||||
},
|
||||
{
|
||||
'path': [1, 0, hardened(2147483647), 1],
|
||||
'xpub': b'xpub6DF8uhdarytz3FWdA8TvFSvvAh8dP3283MY7p2V4SeE2wyWmG5mg5EwVvmdMVCQcoNJxGoWaU9DCWh89LojfZ537wTfunKau47EL2dhHKon',
|
||||
},
|
||||
{
|
||||
'path': [1, 0, hardened(2147483647), 1, hardened(2147483646)],
|
||||
'xpub': b'xpub6ERApfZwUNrhLCkDtcHTcxd75RbzS1ed54G1LkBUHQVHQKqhMkhgbmJbZRkrgZw4koxb5JaHWkY4ALHY2grBGRjaDMzQLcgJvLJuZZvRcEL',
|
||||
},
|
||||
{
|
||||
'path': [1, 0, hardened(2147483647), 1, hardened(2147483646), 2],
|
||||
'xpub': b'xpub6FnCn6nSzZAw5Tw7cgR9bi15UV96gLZhjDstkXXxvCLsUXBGXPdSnLFbdpq8p9HmGsApME5hQTZ3emM2rnY5agb9rXpVGyy3bdW6EEgAtqt',
|
||||
},
|
||||
{
|
||||
'path': [2],
|
||||
'xpub': b'xpub661MyMwAqRbcEZVB4dScxMAdx6d4nFc9nvyvH3v4gJL378CSRZiYmhRoP7mBy6gSPSCYk6SzXPTf3ND1cZAceL7SfJ1Z3GC8vBgp2epUt13',
|
||||
},
|
||||
{
|
||||
'path': [2, hardened(0)],
|
||||
'xpub': b'xpub68NZiKmJWnxxS6aaHmn81bvJeTESw724CRDs6HbuccFQN9Ku14VQrADWgqbhhTHBaohPX4CjNLf9fq9MYo6oDaPPLPxSb7gwQN3ih19Zm4Y',
|
||||
},
|
||||
{
|
||||
'path': [3],
|
||||
'xpub': b'xpub661MyMwAqRbcGczjuMoRm6dXaLDEhW1u34gKenbeYqAix21mdUKJyuyu5F1rzYGVxyL6tmgBUAEPrEz92mBXjByMRiJdba9wpnN37RLLAXa',
|
||||
},
|
||||
{
|
||||
'path': [3, hardened(0)],
|
||||
'xpub': b'xpub69AUMk3qDBi3uW1sXgjCmVjJ2G6WQoYSnNHyzkmdCHEhSZ4tBok37xfFEqHd2AddP56Tqp4o56AePAgCjYdvpW2PU2jbUPFKsav5ut6Ch1m',
|
||||
},
|
||||
{
|
||||
'path': [3, hardened(0), hardened(1)],
|
||||
'xpub': b'xpub6BJA1jSqiukeaesWfxe6sNK9CCGaujFFSJLomWHprUL9DePQ4JDkM5d88n49sMGJxrhpjazuXYWdMf17C9T5XnxkopaeS7jGk1GyyVziaMt',
|
||||
},
|
||||
]
|
||||
)
|
||||
def test_derive_node_bip(device, path):
|
||||
resp = device.hd_derive_node(path['path'])
|
||||
assert(resp == path['xpub'])
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"path", [
|
||||
{
|
||||
'path': [0],
|
||||
'fingerprint': unhexlify('00000000'),
|
||||
'chain': unhexlify('873dff81c02f525623fd1fe5167eac3a55a049de3d314bb42ee227ffed37d508'),
|
||||
'public': unhexlify('0339a36013301597daef41fbe593a02cc513d0b55527ec2df1050e2e8ff49c85c2')
|
||||
},
|
||||
{
|
||||
'path': [0, hardened(0)],
|
||||
'fingerprint': unhexlify('3442193e'),
|
||||
'chain': unhexlify('47fdacbd0f1097043b78c63c20c34ef4ed9a111d980047ad16282c7ae6236141'),
|
||||
'public': unhexlify('035a784662a4a20a65bf6aab9ae98a6c068a81c52e4b032c0fb5400c706cfccc56')
|
||||
},
|
||||
{
|
||||
'path': [0, hardened(0), 1],
|
||||
'fingerprint': unhexlify('5c1bd648'),
|
||||
'chain': unhexlify('2a7857631386ba23dacac34180dd1983734e444fdbf774041578e9b6adb37c19'),
|
||||
'public': unhexlify('03501e454bf00751f24b1b489aa925215d66af2234e3891c3b21a52bedb3cd711c')
|
||||
},
|
||||
{
|
||||
'path': [0, hardened(0), 1, hardened(2)],
|
||||
'fingerprint': unhexlify('bef5a2f9'),
|
||||
'chain': unhexlify('04466b9cc8e161e966409ca52986c584f07e9dc81f735db683c3ff6ec7b1503f'),
|
||||
'public': unhexlify('0357bfe1e341d01c69fe5654309956cbea516822fba8a601743a012a7896ee8dc2')
|
||||
},
|
||||
{
|
||||
'path': [0, hardened(0), 1, hardened(2), 2],
|
||||
'fingerprint': unhexlify('ee7ab90c'),
|
||||
'chain': unhexlify('cfb71883f01676f587d023cc53a35bc7f88f724b1f8c2892ac1275ac822a3edd'),
|
||||
'public': unhexlify('02e8445082a72f29b75ca48748a914df60622a609cacfce8ed0e35804560741d29')
|
||||
},
|
||||
{
|
||||
'path': [0, hardened(0), 1, hardened(2), 2, 1000000000],
|
||||
'fingerprint': unhexlify('d880d7d8'),
|
||||
'chain': unhexlify('c783e67b921d2beb8f6b389cc646d7263b4145701dadd2161548a8b078e65e9e'),
|
||||
'public': unhexlify('022a471424da5e657499d1ff51cb43c47481a03b1e77f951fe64cec9f5a48f7011')
|
||||
},
|
||||
{
|
||||
'path': [4],
|
||||
'fingerprint': unhexlify('00000000'),
|
||||
'chain': unhexlify('beeb672fe4621673f722f38529c07392fecaa61015c80c34f29ce8b41b3cb6ea'),
|
||||
'public': unhexlify('0266874dc6ade47b3ecd096745ca09bcd29638dd52c2c12117b11ed3e458cfa9e8')
|
||||
},
|
||||
{
|
||||
'path': [4, hardened(0)],
|
||||
'fingerprint': unhexlify('be6105b5'),
|
||||
'chain': unhexlify('3460cea53e6a6bb5fb391eeef3237ffd8724bf0a40e94943c98b83825342ee11'),
|
||||
'public': unhexlify('0384610f5ecffe8fda089363a41f56a5c7ffc1d81b59a612d0d649b2d22355590c')
|
||||
},
|
||||
{
|
||||
'path': [4, hardened(0), 1],
|
||||
'fingerprint': unhexlify('9b02312f'),
|
||||
'chain': unhexlify('4187afff1aafa8445010097fb99d23aee9f599450c7bd140b6826ac22ba21d0c'),
|
||||
'public': unhexlify('03526c63f8d0b4bbbf9c80df553fe66742df4676b241dabefdef67733e070f6844')
|
||||
},
|
||||
{
|
||||
'path': [4, hardened(0), 1, hardened(2)],
|
||||
'fingerprint': unhexlify('b98005c1'),
|
||||
'chain': unhexlify('98c7514f562e64e74170cc3cf304ee1ce54d6b6da4f880f313e8204c2a185318'),
|
||||
'public': unhexlify('0359cf160040778a4b14c5f4d7b76e327ccc8c4a6086dd9451b7482b5a4972dda0')
|
||||
},
|
||||
{
|
||||
'path': [4, hardened(0), 1, hardened(2), 2],
|
||||
'fingerprint': unhexlify('0e9f3274'),
|
||||
'chain': unhexlify('ba96f776a5c3907d7fd48bde5620ee374d4acfd540378476019eab70790c63a0'),
|
||||
'public': unhexlify('029f871f4cb9e1c97f9f4de9ccd0d4a2f2a171110c61178f84430062230833ff20')
|
||||
},
|
||||
{
|
||||
'path': [4, hardened(0), 1, hardened(2), 2, 1000000000],
|
||||
'fingerprint': unhexlify('8b2b5c4b'),
|
||||
'chain': unhexlify('b9b7b82d326bb9cb5b5b121066feea4eb93d5241103c9e7a18aad40f1dde8059'),
|
||||
'public': unhexlify('02216cd26d31147f72427a453c443ed2cde8a1e53c9cc44e5ddf739725413fe3f4')
|
||||
},
|
||||
{
|
||||
'path': [1],
|
||||
'fingerprint': unhexlify('00000000'),
|
||||
'chain': unhexlify('60499f801b896d83179a4374aeb7822aaeaceaa0db1f85ee3e904c4defbd9689'),
|
||||
'public': unhexlify('03cbcaa9c98c877a26977d00825c956a238e8dddfbd322cce4f74b0b5bd6ace4a7')
|
||||
},
|
||||
{
|
||||
'path': [1, 0],
|
||||
'fingerprint': unhexlify('bd16bee5'),
|
||||
'chain': unhexlify('f0909affaa7ee7abe5dd4e100598d4dc53cd709d5a5c2cac40e7412f232f7c9c'),
|
||||
'public': unhexlify('02fc9e5af0ac8d9b3cecfe2a888e2117ba3d089d8585886c9c826b6b22a98d12ea')
|
||||
},
|
||||
{
|
||||
'path': [1, 0, hardened(2147483647)],
|
||||
'fingerprint': unhexlify('5a61ff8e'),
|
||||
'chain': unhexlify('be17a268474a6bb9c61e1d720cf6215e2a88c5406c4aee7b38547f585c9a37d9'),
|
||||
'public': unhexlify('03c01e7425647bdefa82b12d9bad5e3e6865bee0502694b94ca58b666abc0a5c3b')
|
||||
},
|
||||
{
|
||||
'path': [1, 0, hardened(2147483647), 1],
|
||||
'fingerprint': unhexlify('d8ab4937'),
|
||||
'chain': unhexlify('f366f48f1ea9f2d1d3fe958c95ca84ea18e4c4ddb9366c336c927eb246fb38cb'),
|
||||
'public': unhexlify('03a7d1d856deb74c508e05031f9895dab54626251b3806e16b4bd12e781a7df5b9')
|
||||
},
|
||||
{
|
||||
'path': [1, 0, hardened(2147483647), 1, hardened(2147483646)],
|
||||
'fingerprint': unhexlify('78412e3a'),
|
||||
'chain': unhexlify('637807030d55d01f9a0cb3a7839515d796bd07706386a6eddf06cc29a65a0e29'),
|
||||
'public': unhexlify('02d2b36900396c9282fa14628566582f206a5dd0bcc8d5e892611806cafb0301f0')
|
||||
},
|
||||
{
|
||||
'path': [1, 0, hardened(2147483647), 1, hardened(2147483646), 2],
|
||||
'fingerprint': unhexlify('31a507b8'),
|
||||
'chain': unhexlify('9452b549be8cea3ecb7a84bec10dcfd94afe4d129ebfd3b3cb58eedf394ed271'),
|
||||
'public': unhexlify('024d902e1a2fc7a8755ab5b694c575fce742c48d9ff192e63df5193e4c7afe1f9c')
|
||||
},
|
||||
{
|
||||
'path': [5],
|
||||
'fingerprint': unhexlify('00000000'),
|
||||
'chain': unhexlify('96cd4465a9644e31528eda3592aa35eb39a9527769ce1855beafc1b81055e75d'),
|
||||
'public': unhexlify('02c9e16154474b3ed5b38218bb0463e008f89ee03e62d22fdcc8014beab25b48fa')
|
||||
},
|
||||
{
|
||||
'path': [5, 0],
|
||||
'fingerprint': unhexlify('607f628f'),
|
||||
'chain': unhexlify('84e9c258bb8557a40e0d041115b376dd55eda99c0042ce29e81ebe4efed9b86a'),
|
||||
'public': unhexlify('039b6df4bece7b6c81e2adfeea4bcf5c8c8a6e40ea7ffa3cf6e8494c61a1fc82cc')
|
||||
},
|
||||
{
|
||||
'path': [5, 0, hardened(2147483647)],
|
||||
'fingerprint': unhexlify('946d2a54'),
|
||||
'chain': unhexlify('f235b2bc5c04606ca9c30027a84f353acf4e4683edbd11f635d0dcc1cd106ea6'),
|
||||
'public': unhexlify('02f89c5deb1cae4fedc9905f98ae6cbf6cbab120d8cb85d5bd9a91a72f4c068c76')
|
||||
},
|
||||
{
|
||||
'path': [5, 0, hardened(2147483647), 1],
|
||||
'fingerprint': unhexlify('218182d8'),
|
||||
'chain': unhexlify('7c0b833106235e452eba79d2bdd58d4086e663bc8cc55e9773d2b5eeda313f3b'),
|
||||
'public': unhexlify('03abe0ad54c97c1d654c1852dfdc32d6d3e487e75fa16f0fd6304b9ceae4220c64')
|
||||
},
|
||||
{
|
||||
'path': [5, 0, hardened(2147483647), 1, hardened(2147483646)],
|
||||
'fingerprint': unhexlify('931223e4'),
|
||||
'chain': unhexlify('5794e616eadaf33413aa309318a26ee0fd5163b70466de7a4512fd4b1a5c9e6a'),
|
||||
'public': unhexlify('03cb8cb067d248691808cd6b5a5a06b48e34ebac4d965cba33e6dc46fe13d9b933')
|
||||
},
|
||||
{
|
||||
'path': [5, 0, hardened(2147483647), 1, hardened(2147483646), 2],
|
||||
'fingerprint': unhexlify('956c4629'),
|
||||
'chain': unhexlify('3bfb29ee8ac4484f09db09c2079b520ea5616df7820f071a20320366fbe226a7'),
|
||||
'public': unhexlify('020ee02e18967237cf62672983b253ee62fa4dd431f8243bfeccdf39dbe181387f')
|
||||
},
|
||||
{
|
||||
'path': [4],
|
||||
'fingerprint': unhexlify('00000000'),
|
||||
'chain': unhexlify('beeb672fe4621673f722f38529c07392fecaa61015c80c34f29ce8b41b3cb6ea'),
|
||||
'public': unhexlify('0266874dc6ade47b3ecd096745ca09bcd29638dd52c2c12117b11ed3e458cfa9e8')
|
||||
},
|
||||
{
|
||||
'path': [4, hardened(28578)],
|
||||
'fingerprint': unhexlify('be6105b5'),
|
||||
'chain': unhexlify('e94c8ebe30c2250a14713212f6449b20f3329105ea15b652ca5bdfc68f6c65c2'),
|
||||
'public': unhexlify('02519b5554a4872e8c9c1c847115363051ec43e93400e030ba3c36b52a3e70a5b7')
|
||||
},
|
||||
{
|
||||
'path': [4, hardened(28578), 33941],
|
||||
'fingerprint': unhexlify('3e2b7bc6'),
|
||||
'chain': unhexlify('9e87fe95031f14736774cd82f25fd885065cb7c358c1edf813c72af535e83071'),
|
||||
'public': unhexlify('0235bfee614c0d5b2cae260000bb1d0d84b270099ad790022c1ae0b2e782efe120')
|
||||
},
|
||||
{
|
||||
'path': [6],
|
||||
'fingerprint': unhexlify('00000000'),
|
||||
'chain': unhexlify('7762f9729fed06121fd13f326884c82f59aa95c57ac492ce8c9654e60efd130c'),
|
||||
'public': unhexlify('0383619fadcde31063d8c5cb00dbfe1713f3e6fa169d8541a798752a1c1ca0cb20')
|
||||
},
|
||||
]
|
||||
)
|
||||
def test_derive_node_xpub(device, path):
|
||||
resp = device.hd_derive_node(path['path'])
|
||||
xpub = PicoHSM.hd_decode_xpub(resp)
|
||||
assert(xpub['fingerprint'] == path['fingerprint'])
|
||||
assert(xpub['chain'] == path['chain'])
|
||||
assert(xpub['public'] == path['public'])
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"path", [
|
||||
{
|
||||
'path': [7],
|
||||
'fingerprint': unhexlify('00000000'),
|
||||
'chain': unhexlify('8F8C33732530A0417DD446097EDB6F6617D52D627C6DB28581D74D11B385D25A'),
|
||||
'public': unhexlify('dbf12b44133eaab506a740f6565cc117228cbf1dd70635cfa8ddfdc9af734756')
|
||||
},
|
||||
{
|
||||
'path': [7, b"SLIP-0021"],
|
||||
'fingerprint': unhexlify('0e521cdd'),
|
||||
'chain': unhexlify('446ADED06078CF950DAB737F014C7BAE81EEB6E7BEECC260A38E2E0FA9973104'),
|
||||
'public': unhexlify('1d065e3ac1bbe5c7fad32cf2305f7d709dc070d672044a19e610c77cdf33de0d')
|
||||
},
|
||||
{
|
||||
'path': [7, b"SLIP-0021", b"Master encryption key"],
|
||||
'fingerprint': unhexlify('4a6e721d'),
|
||||
'chain': unhexlify('7072D5593032B84A90E2E2E42996D277026FF55C1082AC82A121D775FED0ACEB'),
|
||||
'public': unhexlify('ea163130e35bbafdf5ddee97a17b39cef2be4b4f390180d65b54cf05c6a82fde')
|
||||
},
|
||||
{
|
||||
'path': [7, b"SLIP-0021", b"Authentication key"],
|
||||
'fingerprint': unhexlify('4a6e721d'),
|
||||
'chain': unhexlify('3D5C87DC62CE006681B8C3DF723AE50FEEA40D6C26AEF8135BD321BA390A5B42'),
|
||||
'public': unhexlify('47194e938ab24cc82bfa25f6486ed54bebe79c40ae2a5a32ea6db294d81861a6')
|
||||
},
|
||||
]
|
||||
)
|
||||
def test_derive_node_slip(device, path):
|
||||
resp = device.hd_derive_node(path['path'])
|
||||
xpub = PicoHSM.hd_decode_xpub(resp)
|
||||
assert(xpub['fingerprint'] == path['fingerprint'])
|
||||
assert(xpub['chain'] == sha256_sha256(path['chain']))
|
||||
assert(xpub['public'] == sha256_sha256(path['public']))
|
||||
|
||||
def get_master_curve(mid):
|
||||
for m in seeds:
|
||||
if (m['id'] == mid):
|
||||
if (m['name'] == 'secp256k1'):
|
||||
return ec.SECP256K1()
|
||||
elif (m['name'] == 'secp256r1'):
|
||||
return ec.SECP256R1()
|
||||
return None
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"path", [
|
||||
[0],
|
||||
[0, hardened(0)],
|
||||
[0, hardened(0), 1],
|
||||
[0, hardened(0), 1, hardened(2)],
|
||||
[0, hardened(0), 1, hardened(2), 2],
|
||||
[0, hardened(0), 1, hardened(2), 2, 1000000000],
|
||||
[1],
|
||||
[1, 0],
|
||||
[1, 0, hardened(2147483647)],
|
||||
[1, 0, hardened(2147483647), 1],
|
||||
[1, 0, hardened(2147483647), 1, hardened(2147483646)],
|
||||
[1, 0, hardened(2147483647), 1, hardened(2147483646), 2],
|
||||
[4],
|
||||
[4, hardened(0)],
|
||||
[4, hardened(0), 1],
|
||||
[4, hardened(0), 1, hardened(2)],
|
||||
[4, hardened(0), 1, hardened(2), 2],
|
||||
[4, hardened(0), 1, hardened(2), 2, 1000000000],
|
||||
[5],
|
||||
[5, 0],
|
||||
[5, 0, hardened(2147483647)],
|
||||
[5, 0, hardened(2147483647), 1],
|
||||
[5, 0, hardened(2147483647), 1, hardened(2147483646)],
|
||||
[5, 0, hardened(2147483647), 1, hardened(2147483646), 2],
|
||||
]
|
||||
)
|
||||
def test_signature(device, path):
|
||||
pub = device.hd_derive_node(path)
|
||||
xpub = PicoHSM.hd_decode_xpub(pub)
|
||||
curve = get_master_curve(path[0])
|
||||
pubkey = ec.EllipticCurvePublicKey.from_encoded_point(curve, xpub['public'])
|
||||
resp = device.hd_signature(path, TEST_STRING)
|
||||
pubkey.verify(resp, TEST_STRING, ec.ECDSA(hashes.SHA256()))
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"path", [
|
||||
[7],
|
||||
[7, b"SLIP-0021"],
|
||||
[7, b"SLIP-0021", b"Master encryption key"],
|
||||
[7, b"SLIP-0021", b"Authentication key"],
|
||||
]
|
||||
)
|
||||
def test_signature_slip(device, path):
|
||||
pub = device.hd_derive_node(path)
|
||||
with pytest.raises(APDUResponse) as e:
|
||||
resp = device.hd_signature(path, TEST_STRING)
|
||||
assert (e.value.sw == SWCodes.SW_CONDITIONS_NOT_SATISFIED)
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"ask_on_encrypt", [True, False]
|
||||
)
|
||||
@pytest.mark.parametrize(
|
||||
"ask_on_decrypt", [True, False]
|
||||
)
|
||||
def test_cipher_slip(device, ask_on_encrypt, ask_on_decrypt):
|
||||
MSG1 = b"testing message!"
|
||||
enctext = device.hd_cipher([7, b"\x01", b"\x02"], b"test", MSG1, EncryptionMode.ENCRYPT, ask_on_encrypt, ask_on_decrypt)
|
||||
resp = device.hd_cipher([7, b"\x01", b"\x02"], b"test", enctext, EncryptionMode.DECRYPT, ask_on_encrypt, ask_on_decrypt)
|
||||
assert(resp == MSG1)
|
||||
11
tests/run-test-in-docker.sh
Executable file
11
tests/run-test-in-docker.sh
Executable file
@@ -0,0 +1,11 @@
|
||||
#!/bin/bash -eu
|
||||
|
||||
source tests/docker_env.sh
|
||||
|
||||
if [[ $1 == "pkcs11" ]]; then
|
||||
run_in_docker ./tests/start-up-and-test-pkcs11.sh
|
||||
elif [[ $1 == "sc-hsm-pkcs11" ]]; then
|
||||
run_in_docker ./tests/scripts/sc_hsm_test.sh
|
||||
else
|
||||
run_in_docker ./tests/start-up-and-test.sh
|
||||
fi
|
||||
38
tests/scripts/aes.sh
Executable file
38
tests/scripts/aes.sh
Executable file
@@ -0,0 +1,38 @@
|
||||
#!/bin/bash
|
||||
|
||||
source ./tests/scripts/func.sh
|
||||
reset
|
||||
test $? -eq 0 || exit $?
|
||||
|
||||
TEST_DATA="This is a text."
|
||||
|
||||
echo "${TEST_DATA}" > test
|
||||
|
||||
sc_tool() {
|
||||
pkcs11-tool --module /usr/local/lib/libsc-hsm-pkcs11.so -l --pin 648219 $@
|
||||
}
|
||||
|
||||
aeses=("16" "24" "32")
|
||||
|
||||
for aes in ${aeses[*]}; do
|
||||
echo " Test AES (AES:${aes})"
|
||||
echo -n " Keygen... "
|
||||
sc_tool --keygen --key-type "AES:${aes}" --id 1 --label "AES:${aes}" > /dev/null 2>&1
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
e=$(sc_tool --list-object --type secrkey 2>&1)
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
grep -q "AES length ${aes}" <<< $e && echo -n "." || exit $?
|
||||
grep -q "AES:${aes}" <<< $e && echo -e ".\t${OK}" || exit $?
|
||||
|
||||
echo -n " Encryption..."
|
||||
sc_tool --encrypt --id 1 --input-file test --mechanism aes-cbc > crypted.aes 2>/dev/null
|
||||
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||
|
||||
echo -n " Decryption..."
|
||||
e=$(sc_tool --decrypt --id 1 --input-file crypted.aes --mechanism aes-cbc 2>/dev/null)
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
grep -q "${TEST_DATA}" <<< $e && echo -e ".\t${OK}" || exit $?
|
||||
|
||||
sc_tool --delete --type secrkey --id 1 > /dev/null 2>&1
|
||||
done
|
||||
rm -rf test crypted.aes
|
||||
62
tests/scripts/asym_cipher.sh
Executable file
62
tests/scripts/asym_cipher.sh
Executable file
@@ -0,0 +1,62 @@
|
||||
#!/bin/bash
|
||||
|
||||
source ./tests/scripts/func.sh
|
||||
reset
|
||||
test $? -eq 0 || exit $?
|
||||
|
||||
rsa_encrypt_decrypt() {
|
||||
openssl pkeyutl -encrypt -pubin -inkey 1.pub $2 -in $1 -out data.crypt
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
TDATA=$(tr -d '\0' < <(pkcs11-tool --id 1 --pin 648219 --decrypt $3 -i data.crypt 2>/dev/null))
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
if [[ ${TEST_STRING} != "$TDATA" ]]; then
|
||||
exit 1
|
||||
fi
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
}
|
||||
|
||||
TEST_STRING="This is a test string. Be safe, be secure."
|
||||
|
||||
echo ${TEST_STRING} > data
|
||||
|
||||
echo -n " Keygen RSA 2048..."
|
||||
keygen_and_export rsa:2048
|
||||
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||
|
||||
echo -n " Test RSA-PKCS ciphering..."
|
||||
rsa_encrypt_decrypt data "-pkeyopt rsa_padding_mode:pkcs1" "--mechanism RSA-PKCS"
|
||||
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||
|
||||
echo -n " Test RSA-X-509 ciphering..."
|
||||
cp data data_pad
|
||||
tlen=${#TEST_STRING}
|
||||
dd if=/dev/zero bs=1 count=$((256-$tlen-1)) >> data_pad 2> /dev/null
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
rsa_encrypt_decrypt data_pad "-pkeyopt rsa_padding_mode:none" "--mechanism RSA-X-509"
|
||||
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||
|
||||
echo -n " Test RSA-PKCS-OAEP ciphering..."
|
||||
rsa_encrypt_decrypt data "-pkeyopt rsa_padding_mode:oaep -pkeyopt rsa_oaep_md:sha256 -pkeyopt rsa_mgf1_md:sha256" "--mechanism RSA-PKCS-OAEP"
|
||||
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||
|
||||
rm -rf data* 1.*
|
||||
pkcs11-tool -l --pin 648219 --delete-object --type privkey --id 1 > /dev/null 2>&1
|
||||
|
||||
algs=("secp192r1" "secp256r1" "secp384r1" "secp521r1" "brainpoolP256r1" "brainpoolP384r1" "brainpoolP512r1" "secp192k1" "secp256k1")
|
||||
for alg in ${algs[*]}; do
|
||||
echo -n " Test EC derive with ${alg}..."
|
||||
keygen_and_export ec:${alg}
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
openssl ecparam -genkey -name ${alg} > bob.pem 2>/dev/null
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
openssl ec -in bob.pem -pubout -outform DER > bob.der 2>/dev/null
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
pkcs11-tool --pin 648219 --id 1 --derive -i bob.der -o mine-bob.der > /dev/null 2>&1
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
openssl pkeyutl -derive -out bob-mine.der -inkey bob.pem -peerkey 1.pub 2>/dev/null
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
cmp bob-mine.der mine-bob.der
|
||||
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||
rm -rf data* 1.*
|
||||
pkcs11-tool -l --pin 648219 --delete-object --type privkey --id 1 > /dev/null 2>&1
|
||||
done
|
||||
60
tests/scripts/backup.sh
Executable file
60
tests/scripts/backup.sh
Executable file
@@ -0,0 +1,60 @@
|
||||
#!/bin/bash
|
||||
|
||||
source ./tests/scripts/func.sh
|
||||
reset
|
||||
test $? -eq 0 || exit $?
|
||||
|
||||
sc_backup() {
|
||||
for i in $(seq 1 $1); do
|
||||
sc-hsm-tool --create-dkek-share dkek.${i}.pbe --password testpw > /dev/null 2>&1
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
done
|
||||
sc-hsm-tool --initialize --so-pin 3537363231383830 --pin 648219 --dkek-shares $1 > /dev/null 2>&1
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
pkcs11-tool -l --pin 648219 -I > /dev/null 2>&1
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
for i in $(seq 1 $1); do
|
||||
e=$(sc-hsm-tool --import-dkek-share dkek.${i}.pbe --password testpw 2>&1)
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
grep -q "DKEK share imported" <<< $e && echo -n "." || exit $?
|
||||
grep -q "DKEK shares[[:blank:]]*: $1" <<< $e && echo -n "." || exit $?
|
||||
if [[ $i -lt $1 ]]; then
|
||||
grep -q "DKEK import pending, $(( $1 - $i ))" <<< $e && echo -n "." || exit $?
|
||||
fi
|
||||
done
|
||||
# Store DKEK, since it is not logged in
|
||||
pkcs11-tool -l --pin 648219 -I > /dev/null 2>&1
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
}
|
||||
echo -n " Test single DKEK..."
|
||||
sc_backup 1
|
||||
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||
|
||||
echo -n " Test multiple DKEK..."
|
||||
sc_backup 3
|
||||
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||
|
||||
rm -rf dkek.*.pbe
|
||||
|
||||
echo " Test backup and restore"
|
||||
algs=("rsa:1024" "rsa:2048" "ec:secp192r1" "ec:secp256r1" "ec:secp384r1" "ec:secp521r1" "ec:brainpoolP256r1" "ec:brainpoolP384r1" "ec:brainpoolP512r1" "ec:secp192k1" "ec:secp256k1")
|
||||
for alg in ${algs[*]}; do
|
||||
echo -n " Keygen ${alg}..."
|
||||
gen_and_check ${alg}
|
||||
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||
echo -n " Wrap key..."
|
||||
sc-hsm-tool --wrap-key wrap-key.bin --key-reference 1 --pin 648219 > /dev/null 2>&1
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
e=$(pkcs15-tool -D 2>&1)
|
||||
grep -q "Key ref[[:blank:]]*: 10" <<< $e && exit $? || echo -e ".\t${OK}"
|
||||
echo -n " Unwrap key..."
|
||||
sc-hsm-tool --unwrap-key wrap-key.bin --key-reference 10 --pin 648219 --force > /dev/null 2>&1
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
e=$(pkcs15-tool -D 2>&1)
|
||||
grep -q "Key ref[[:blank:]]*: 10" <<< $e && echo -e ".\t${OK}" || exit $?
|
||||
echo -n " Cleaning..."
|
||||
pkcs11-tool -l --pin 648219 --delete-object --type privkey --id 1 > /dev/null 2>&1
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
pkcs11-tool -l --pin 648219 --delete-object --type privkey --id 1 > /dev/null 2>&1
|
||||
test $? -eq 0 && echo -e ".\t${OK}" || exit $?
|
||||
done
|
||||
52
tests/scripts/func.sh
Executable file
52
tests/scripts/func.sh
Executable file
@@ -0,0 +1,52 @@
|
||||
#!/bin/bash
|
||||
|
||||
OK="\033[32mok\033[0m"
|
||||
FAIL="\033[31mfail\033[0m"
|
||||
|
||||
gen_and_check() {
|
||||
e=$(pkcs11-tool -l --pin 648219 --keypairgen --key-type $1 --id 1 --label "TestLabel" 2>&1)
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
glabel=""
|
||||
case $1 in
|
||||
*"192"*)
|
||||
glabel="EC_POINT 192 bits"
|
||||
;;
|
||||
*"256"*)
|
||||
glabel="EC_POINT 256 bits"
|
||||
;;
|
||||
*"384"*)
|
||||
glabel="EC_POINT 384 bits"
|
||||
;;
|
||||
*"512"*)
|
||||
glabel="EC_POINT 512 bits"
|
||||
;;
|
||||
*"521"*)
|
||||
glabel="EC_POINT 528 bits"
|
||||
;;
|
||||
*"rsa"*)
|
||||
IFS=: read -r v1 bits <<< "$1"
|
||||
glabel="RSA ${bits} bits"
|
||||
;;
|
||||
esac
|
||||
grep -q "${glabel}" <<< $e && echo -n "." || exit $?
|
||||
}
|
||||
gen_and_delete() {
|
||||
gen_and_check $1
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
pkcs11-tool -l --pin 648219 --delete-object --type privkey --id 1 > /dev/null 2>&1
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
}
|
||||
reset() {
|
||||
python3 tools/pico-hsm-tool.py --pin 648219 initialize --so-pin 57621880 --silent --no-dev-cert > /dev/null 2>&1
|
||||
test $? -eq 0 || exit $?
|
||||
}
|
||||
|
||||
keygen_and_export() {
|
||||
gen_and_check $1
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
pkcs11-tool --read-object --pin 648219 --id 1 --type pubkey > 1.der 2>/dev/null
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
IFS=: read -r mk bts <<< "$1"
|
||||
openssl ${mk} -inform DER -outform PEM -in 1.der -pubin > 1.pub 2>/dev/null
|
||||
test $? -eq 0 && echo -n "." || exit $?
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user