From d0c3d60de20e21f0b02c25eb0d35e8586620f302 Mon Sep 17 00:00:00 2001 From: Hugues de Valon Date: Thu, 6 Feb 2020 11:53:14 +0000 Subject: [PATCH] Review ResponseStatus usage Adds a mapping between PKCS 11 and TSS error codes with our ResponseStatus. Adds a conversion between String and ResponseStatus in the Key ID Manager. Signed-off-by: Hugues de Valon --- Cargo.lock | 185 ++---------------- Cargo.toml | 4 +- src/key_id_managers/mod.rs | 13 +- src/providers/mbed_provider/mod.rs | 52 ++--- src/providers/mbed_provider/utils.rs | 60 +++--- src/providers/mod.rs | 16 +- src/providers/pkcs11_provider/mod.rs | 85 ++++---- src/providers/pkcs11_provider/utils.rs | 141 +++++++++++++ src/providers/tpm_provider/mod.rs | 76 +++---- src/providers/tpm_provider/utils.rs | 149 ++++++++++++++ .../normal_tests/asym_sign_verify.rs | 4 +- tests/per_provider/normal_tests/auth.rs | 2 +- tests/per_provider/normal_tests/basic.rs | 2 +- .../normal_tests/create_destroy_key.rs | 6 +- .../normal_tests/export_public_key.rs | 2 +- tests/per_provider/normal_tests/import_key.rs | 4 +- tests/per_provider/persistent_after.rs | 2 +- 17 files changed, 434 insertions(+), 369 deletions(-) create mode 100644 src/providers/pkcs11_provider/utils.rs create mode 100644 src/providers/tpm_provider/utils.rs diff --git a/Cargo.lock b/Cargo.lock index 5d462727..9c3e6679 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1,13 +1,8 @@ # This file is automatically @generated by Cargo. # It is not intended for manual editing. -[[package]] -name = "adler32" -version = "1.0.4" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "aho-corasick" -version = "0.7.7" +version = "0.7.8" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)", @@ -215,42 +210,6 @@ dependencies = [ "vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "crc32fast" -version = "1.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "curl" -version = "0.4.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "curl-sys 0.4.25 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", - "openssl-probe 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)", - "openssl-sys 0.9.54 (registry+https://github.com/rust-lang/crates.io-index)", - "schannel 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)", - "socket2 0.3.11 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - -[[package]] -name = "curl-sys" -version = "0.4.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cc 1.0.50 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", - "libz-sys 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)", - "openssl-sys 0.9.54 (registry+https://github.com/rust-lang/crates.io-index)", - "pkg-config 0.3.17 (registry+https://github.com/rust-lang/crates.io-index)", - "vcpkg 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "derivative" version = "1.0.3" @@ -308,33 +267,11 @@ dependencies = [ "backtrace 0.3.43 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "filetime" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", - "redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "fixedbitset" version = "0.1.9" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "flate2" -version = "1.0.13" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "crc32fast 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", - "miniz_oxide 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "fxhash" version = "0.2.1" @@ -422,17 +359,6 @@ dependencies = [ "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "libz-sys" -version = "1.0.25" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cc 1.0.50 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", - "pkg-config 0.3.17 (registry+https://github.com/rust-lang/crates.io-index)", - "vcpkg 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "log" version = "0.4.8" @@ -457,14 +383,6 @@ name = "memchr" version = "2.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "miniz_oxide" -version = "0.3.6" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "adler32 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "multimap" version = "0.4.0" @@ -576,23 +494,6 @@ dependencies = [ "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "openssl-probe" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" - -[[package]] -name = "openssl-sys" -version = "0.9.54" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "autocfg 1.0.0 (registry+https://github.com/rust-lang/crates.io-index)", - "cc 1.0.50 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", - "pkg-config 0.3.17 (registry+https://github.com/rust-lang/crates.io-index)", - "vcpkg 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "parsec" version = "0.1.0" @@ -606,8 +507,8 @@ dependencies = [ "env_logger 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "num_cpus 1.12.0 (registry+https://github.com/rust-lang/crates.io-index)", - "parsec-client-test 0.1.14 (git+https://github.com/parallaxsecond/parsec-client-test?tag=0.1.14)", - "parsec-interface 0.6.1 (git+https://github.com/parallaxsecond/parsec-interface-rs?tag=0.6.1)", + "parsec-client-test 0.1.15 (git+https://github.com/parallaxsecond/parsec-client-test?tag=0.1.15)", + "parsec-interface 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", "picky-asn1 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "picky-asn1-der 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", "pkcs11 0.4.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -625,26 +526,24 @@ dependencies = [ [[package]] name = "parsec-client-test" -version = "0.1.14" -source = "git+https://github.com/parallaxsecond/parsec-client-test?tag=0.1.14#92d66522b81cd5ac056a71df7e2bead2795fe6a0" +version = "0.1.15" +source = "git+https://github.com/parallaxsecond/parsec-client-test?tag=0.1.15#f2c5286ed046a1fcbb71723e8369869f594f8c3e" dependencies = [ "derivative 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "num 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", - "parsec-interface 0.6.1 (git+https://github.com/parallaxsecond/parsec-interface-rs?tag=0.6.1)", + "parsec-interface 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)", "rand 0.7.3 (registry+https://github.com/rust-lang/crates.io-index)", ] [[package]] name = "parsec-interface" -version = "0.6.1" -source = "git+https://github.com/parallaxsecond/parsec-interface-rs?tag=0.6.1#a94ee731bc1e1f17e1cc963cc1e89684114cc42b" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ "arbitrary 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", "bincode 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "bytes 0.4.12 (registry+https://github.com/rust-lang/crates.io-index)", - "curl 0.4.25 (registry+https://github.com/rust-lang/crates.io-index)", - "flate2 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)", "log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)", "num 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)", "num-derive 0.2.5 (registry+https://github.com/rust-lang/crates.io-index)", @@ -652,7 +551,6 @@ dependencies = [ "prost 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", "prost-build 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)", "serde 1.0.104 (registry+https://github.com/rust-lang/crates.io-index)", - "tar 0.4.26 (registry+https://github.com/rust-lang/crates.io-index)", "uuid 0.7.4 (registry+https://github.com/rust-lang/crates.io-index)", ] @@ -864,7 +762,7 @@ name = "regex" version = "1.3.4" source = "registry+https://github.com/rust-lang/crates.io-index" dependencies = [ - "aho-corasick 0.7.7 (registry+https://github.com/rust-lang/crates.io-index)", + "aho-corasick 0.7.8 (registry+https://github.com/rust-lang/crates.io-index)", "memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)", "regex-syntax 0.6.14 (registry+https://github.com/rust-lang/crates.io-index)", "thread_local 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)", @@ -914,15 +812,6 @@ dependencies = [ "syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "schannel" -version = "0.1.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "sd-notify" version = "0.1.1" @@ -990,17 +879,6 @@ dependencies = [ "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "socket2" -version = "0.3.11" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", - "redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)", - "winapi 0.3.8 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "stable_deref_trait" version = "1.1.1" @@ -1079,17 +957,6 @@ dependencies = [ "unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)", ] -[[package]] -name = "tar" -version = "0.4.26" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "filetime 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)", - "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", - "redox_syscall 0.1.56 (registry+https://github.com/rust-lang/crates.io-index)", - "xattr 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)", -] - [[package]] name = "tempfile" version = "3.1.0" @@ -1189,11 +1056,6 @@ name = "uuid" version = "0.7.4" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "vcpkg" -version = "0.2.8" -source = "registry+https://github.com/rust-lang/crates.io-index" - [[package]] name = "vec_map" version = "0.8.1" @@ -1253,17 +1115,8 @@ name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -[[package]] -name = "xattr" -version = "0.2.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -dependencies = [ - "libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)", -] - [metadata] -"checksum adler32 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "5d2e7343e7fc9de883d1b0341e0b13970f764c14101234857d2ddafa1cb1cac2" -"checksum aho-corasick 0.7.7 (registry+https://github.com/rust-lang/crates.io-index)" = "5f56c476256dc249def911d6f7580b5fc7e875895b5d7ee88f5d602208035744" +"checksum aho-corasick 0.7.8 (registry+https://github.com/rust-lang/crates.io-index)" = "743ad5a418686aad3b87fd14c43badd828cf26e214a00f92a384291cf22e1811" "checksum ansi_term 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ee49baf6cb617b853aa8d93bf420db2383fab46d314482ca2803b40d5fde979b" "checksum arbitrary 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "16971f2f0ce65c5cf2a1546cc6a0af102ecb11e265ddaa9433fb3e5bfdf676a4" "checksum arc-swap 0.4.4 (registry+https://github.com/rust-lang/crates.io-index)" = "d7b8a9123b8027467bce0099fe556c628a53c8d83df0507084c31e9ba2e39aff" @@ -1286,18 +1139,13 @@ dependencies = [ "checksum cfg-if 0.1.10 (registry+https://github.com/rust-lang/crates.io-index)" = "4785bdd1c96b2a846b2bd7cc02e86b6b3dbf14e7e53446c4f54c92a361040822" "checksum clang-sys 0.28.1 (registry+https://github.com/rust-lang/crates.io-index)" = "81de550971c976f176130da4b2978d3b524eaa0fd9ac31f3ceb5ae1231fb4853" "checksum clap 2.33.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5067f5bb2d80ef5d68b4c87db81601f0b75bca627bc2ef76b141d7b846a3c6d9" -"checksum crc32fast 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ba125de2af0df55319f41944744ad91c71113bf74a4646efff39afe1f6842db1" -"checksum curl 0.4.25 (registry+https://github.com/rust-lang/crates.io-index)" = "06aa71e9208a54def20792d877bc663d6aae0732b9852e612c4a933177c31283" -"checksum curl-sys 0.4.25 (registry+https://github.com/rust-lang/crates.io-index)" = "0c38ca47d60b86d0cc9d42caa90a0885669c2abc9791f871c81f58cdf39e979b" "checksum derivative 1.0.3 (registry+https://github.com/rust-lang/crates.io-index)" = "942ca430eef7a3806595a6737bc388bf51adb888d3fc0dd1b50f1c170167ee3a" "checksum derive_arbitrary 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "caedd6a71b6d00bdc458ec8ffbfd12689c1ee7ffa69ad9933310aaf2f08f18d8" "checksum either 1.5.3 (registry+https://github.com/rust-lang/crates.io-index)" = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3" "checksum env_logger 0.6.2 (registry+https://github.com/rust-lang/crates.io-index)" = "aafcde04e90a5226a6443b7aabdb016ba2f8307c847d524724bd9b346dd1a2d3" "checksum env_logger 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "44533bbbb3bb3c1fa17d9f2e4e38bbbaf8396ba82193c4cb1b6445d711445d36" "checksum failure 0.1.6 (registry+https://github.com/rust-lang/crates.io-index)" = "f8273f13c977665c5db7eb2b99ae520952fe5ac831ae4cd09d80c4c7042b5ed9" -"checksum filetime 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "1ff6d4dab0aa0c8e6346d46052e93b13a16cf847b54ed357087c35011048cc7d" "checksum fixedbitset 0.1.9 (registry+https://github.com/rust-lang/crates.io-index)" = "86d4de0081402f5e88cdac65c8dcdcc73118c1a7a465e2a05f0da05843a8ea33" -"checksum flate2 1.0.13 (registry+https://github.com/rust-lang/crates.io-index)" = "6bd6d6f4752952feb71363cffc9ebac9411b75b87c6ab6058c40c8900cf43c0f" "checksum fxhash 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c" "checksum getrandom 0.1.14 (registry+https://github.com/rust-lang/crates.io-index)" = "7abc8dd8451921606d809ba32e95b6111925cd2906060d2dcc29c070220503eb" "checksum glob 0.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" @@ -1310,11 +1158,9 @@ dependencies = [ "checksum lazycell 1.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b294d6fa9ee409a054354afc4352b0b9ef7ca222c69b8812cbea9e7d2bf3783f" "checksum libc 0.2.66 (registry+https://github.com/rust-lang/crates.io-index)" = "d515b1f41455adea1313a4a2ac8a8a477634fbae63cc6100e3aebb207ce61558" "checksum libloading 0.5.2 (registry+https://github.com/rust-lang/crates.io-index)" = "f2b111a074963af1d37a139918ac6d49ad1d0d5e47f72fd55388619691a7d753" -"checksum libz-sys 1.0.25 (registry+https://github.com/rust-lang/crates.io-index)" = "2eb5e43362e38e2bca2fd5f5134c4d4564a23a5c28e9b95411652021a8675ebe" "checksum log 0.4.8 (registry+https://github.com/rust-lang/crates.io-index)" = "14b6052be84e6b71ab17edffc2eeabf5c2c3ae1fdb464aae35ac50c67a44e1f7" "checksum mbox 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "5e3ae5479d6f010bca840f945a5ca2f3c343a74cccc98fcd13d62e176cf22361" "checksum memchr 2.3.0 (registry+https://github.com/rust-lang/crates.io-index)" = "3197e20c7edb283f87c071ddfc7a2cca8f8e0b888c242959846a6fce03c72223" -"checksum miniz_oxide 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "aa679ff6578b1cddee93d7e82e263b94a575e0bfced07284eb0c037c1d2416a5" "checksum multimap 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "2eb04b9f127583ed176e163fb9ec6f3e793b87e21deedd5734a69386a18a0151" "checksum nom 4.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2ad2a91a8e869eeb30b9cb3119ae87773a8f4ae617f41b1eb9c154b2905f7bd6" "checksum num 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "b8536030f9fea7127f841b45bb6243b27255787fb4eb83958aa1ef9d2fdc0c36" @@ -1327,10 +1173,8 @@ dependencies = [ "checksum num-traits 0.2.11 (registry+https://github.com/rust-lang/crates.io-index)" = "c62be47e61d1842b9170f0fdeec8eba98e60e90e5446449a0545e5152acd7096" "checksum num_cpus 1.12.0 (registry+https://github.com/rust-lang/crates.io-index)" = "46203554f085ff89c235cd12f7075f3233af9b11ed7c9e16dfe2560d03313ce6" "checksum oid 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "293d5f18898078ea69ba1c84f3688d1f2b6744df8211da36197153157cee7055" -"checksum openssl-probe 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "77af24da69f9d9341038eba93a073b1fdaaa1b788221b00a69bce9e762cb32de" -"checksum openssl-sys 0.9.54 (registry+https://github.com/rust-lang/crates.io-index)" = "1024c0a59774200a555087a6da3f253a9095a5f344e353b212ac4c8b8e450986" -"checksum parsec-client-test 0.1.14 (git+https://github.com/parallaxsecond/parsec-client-test?tag=0.1.14)" = "" -"checksum parsec-interface 0.6.1 (git+https://github.com/parallaxsecond/parsec-interface-rs?tag=0.6.1)" = "" +"checksum parsec-client-test 0.1.15 (git+https://github.com/parallaxsecond/parsec-client-test?tag=0.1.15)" = "" +"checksum parsec-interface 0.7.1 (registry+https://github.com/rust-lang/crates.io-index)" = "175c8b4d1b83d102da2cd3a6c622ac97574076eab01ebf38b36d658ab38c5f41" "checksum peeking_take_while 0.1.2 (registry+https://github.com/rust-lang/crates.io-index)" = "19b17cddbe7ec3f8bc800887bab5e717348c95ea2ca0b1bf0837fb964dc67099" "checksum petgraph 0.4.13 (registry+https://github.com/rust-lang/crates.io-index)" = "9c3659d1ee90221741f65dd128d9998311b0e40c5d3c23a62445938214abce4f" "checksum picky-asn1 0.2.1 (registry+https://github.com/rust-lang/crates.io-index)" = "462cc017444f8183daf4765fb682023c1c5ce68a649df4a5ce2830ef3f653a6d" @@ -1361,7 +1205,6 @@ dependencies = [ "checksum rustc-hash 1.0.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7540fc8b0c49f096ee9c961cda096467dce8084bec6bdca2fc83895fd9b28cb8" "checksum rustc_version 0.2.3 (registry+https://github.com/rust-lang/crates.io-index)" = "138e3e0acb6c9fb258b19b67cb8abd63c00679d2851805ea151465464fe9030a" "checksum rustversion 1.0.2 (registry+https://github.com/rust-lang/crates.io-index)" = "b3bba175698996010c4f6dce5e7f173b6eb781fce25d2cfc45e27091ce0b79f6" -"checksum schannel 0.1.16 (registry+https://github.com/rust-lang/crates.io-index)" = "87f550b06b6cba9c8b8be3ee73f391990116bf527450d2556e9b9ce263b9a021" "checksum sd-notify 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "aef40838bbb143707f8309b1e92e6ba3225287592968ba6f6e3b6de4a9816486" "checksum semver 0.9.0 (registry+https://github.com/rust-lang/crates.io-index)" = "1d7eb9ef2c18661902cc47e535f9bc51b78acd254da71d375c2f6720d9a40403" "checksum semver-parser 0.7.0 (registry+https://github.com/rust-lang/crates.io-index)" = "388a1df253eca08550bef6c72392cfe7c30914bf41df5269b68cbd6ff8f570a3" @@ -1371,7 +1214,6 @@ dependencies = [ "checksum shlex 0.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "7fdf1b9db47230893d76faad238fd6097fd6d6a9245cd7a4d90dbd639536bbd2" "checksum signal-hook 0.1.13 (registry+https://github.com/rust-lang/crates.io-index)" = "10b9f3a1686a29f53cfd91ee5e3db3c12313ec02d33765f02c1a9645a1811e2c" "checksum signal-hook-registry 1.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "94f478ede9f64724c5d173d7bb56099ec3e2d9fc2774aac65d34b8b890405f41" -"checksum socket2 0.3.11 (registry+https://github.com/rust-lang/crates.io-index)" = "e8b74de517221a2cb01a53349cf54182acdc31a074727d3079068448c0676d85" "checksum stable_deref_trait 1.1.1 (registry+https://github.com/rust-lang/crates.io-index)" = "dba1a27d3efae4351c8051072d619e3ade2820635c3958d826bfea39d59b54c8" "checksum std-semaphore 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "33ae9eec00137a8eed469fb4148acd9fc6ac8c3f9b110f52cd34698c8b5bfa0e" "checksum strsim 0.8.0 (registry+https://github.com/rust-lang/crates.io-index)" = "8ea5119cdb4c55b55d432abb513a0429384878c15dde60cc77b1c99de1a95a6a" @@ -1381,7 +1223,6 @@ dependencies = [ "checksum syn 1.0.14 (registry+https://github.com/rust-lang/crates.io-index)" = "af6f3550d8dff9ef7dc34d384ac6f107e5d31c8f57d9f28e0081503f547ac8f5" "checksum syn-mid 0.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7be3539f6c128a931cf19dcee741c1af532c7fd387baa739c03dd2e96479338a" "checksum synstructure 0.12.3 (registry+https://github.com/rust-lang/crates.io-index)" = "67656ea1dc1b41b1451851562ea232ec2e5a80242139f7e679ceccfb5d61f545" -"checksum tar 0.4.26 (registry+https://github.com/rust-lang/crates.io-index)" = "b3196bfbffbba3e57481b6ea32249fbaf590396a52505a2615adbb79d9d826d3" "checksum tempfile 3.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "7a6e24d9338a0a5be79593e2fa15a648add6138caa803e2d5bc782c371732ca9" "checksum termcolor 1.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bb6bfa289a4d7c5766392812c0a1f4c1ba45afa1ad47803c11e1f407d846d75f" "checksum textwrap 0.11.0 (registry+https://github.com/rust-lang/crates.io-index)" = "d326610f408c7a4eb6f51c37c330e496b08506c9457c9d34287ecc38809fb060" @@ -1395,7 +1236,6 @@ dependencies = [ "checksum unicode-xid 0.1.0 (registry+https://github.com/rust-lang/crates.io-index)" = "fc72304796d0818e357ead4e000d19c9c174ab23dc11093ac919054d20a6a7fc" "checksum unicode-xid 0.2.0 (registry+https://github.com/rust-lang/crates.io-index)" = "826e7639553986605ec5979c7dd957c7895e93eabed50ab2ffa7f6128a75097c" "checksum uuid 0.7.4 (registry+https://github.com/rust-lang/crates.io-index)" = "90dbc611eb48397705a6b0f6e917da23ae517e4d127123d2cf7674206627d32a" -"checksum vcpkg 0.2.8 (registry+https://github.com/rust-lang/crates.io-index)" = "3fc439f2794e98976c88a2a2dafce96b930fe8010b0a256b3c2199a773933168" "checksum vec_map 0.8.1 (registry+https://github.com/rust-lang/crates.io-index)" = "05c78687fb1a80548ae3250346c3db86a80a7cdd77bda190189f2d0a0987c81a" "checksum version_check 0.1.5 (registry+https://github.com/rust-lang/crates.io-index)" = "914b1a6776c4c929a602fafd8bc742e06365d4bcbe48c30f9cca5824f70dc9dd" "checksum wasi 0.9.0+wasi-snapshot-preview1 (registry+https://github.com/rust-lang/crates.io-index)" = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" @@ -1405,4 +1245,3 @@ dependencies = [ "checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" "checksum winapi-util 0.1.3 (registry+https://github.com/rust-lang/crates.io-index)" = "4ccfbf554c6ad11084fb7517daca16cfdcaccbdadba4fc336f032a8b12c2ad80" "checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" -"checksum xattr 0.2.2 (registry+https://github.com/rust-lang/crates.io-index)" = "244c3741f4240ef46274860397c7c74e50eb23624996930e484c16679633a54c" diff --git a/Cargo.toml b/Cargo.toml index f9ac9445..6d268cf2 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -17,7 +17,7 @@ name = "parsec" path = "src/bin/main.rs" [dependencies] -parsec-interface = { git = "https://github.com/parallaxsecond/parsec-interface-rs", tag = "0.6.1" } +parsec-interface = "0.7.1" rand = "0.7.2" base64 = "0.10.1" uuid = "0.7.4" @@ -39,7 +39,7 @@ derivative = "1.0.3" arbitrary = { version = "0.4.0", features = ["derive"], optional = true } [dev-dependencies] -parsec-client-test = { git = "https://github.com/parallaxsecond/parsec-client-test", tag = "0.1.14" } +parsec-client-test = { git = "https://github.com/parallaxsecond/parsec-client-test", tag = "0.1.15" } num_cpus = "1.10.1" [build-dependencies] diff --git a/src/key_id_managers/mod.rs b/src/key_id_managers/mod.rs index ef29352c..e5ec40fc 100644 --- a/src/key_id_managers/mod.rs +++ b/src/key_id_managers/mod.rs @@ -19,7 +19,8 @@ //! store this mapping using different means but it has to be persistent. use crate::authenticators::ApplicationName; -use parsec_interface::requests::ProviderID; +use log::error; +use parsec_interface::requests::{ProviderID, ResponseStatus}; use serde::Deserialize; use std::fmt; @@ -72,6 +73,16 @@ impl KeyTriple { } } +/// Converts the error string returned by the ManageKeyIDs methods to +/// ResponseStatus::KeyIDManagerError. +pub fn to_response_status(error_string: String) -> ResponseStatus { + error!( + "Converting error string \"{}\" to ResponseStatus:KeyIDManagerError.", + error_string + ); + ResponseStatus::KeyIDManagerError +} + pub trait ManageKeyIDs { /// Returns a reference to the key ID corresponding to this key triple or `None` if it does not /// exist. diff --git a/src/providers/mbed_provider/mod.rs b/src/providers/mbed_provider/mod.rs index bf81a6f9..b657983d 100644 --- a/src/providers/mbed_provider/mod.rs +++ b/src/providers/mbed_provider/mod.rs @@ -14,6 +14,7 @@ // limitations under the License. use super::Provide; use crate::authenticators::ApplicationName; +use crate::key_id_managers; use crate::key_id_managers::{KeyTriple, ManageKeyIDs}; use constants::PSA_SUCCESS; use derivative::Derivative; @@ -100,11 +101,8 @@ fn get_key_id(key_triple: &KeyTriple, store_handle: &dyn ManageKeyIDs) -> Result Err(ResponseStatus::KeyIDManagerError) } } - Ok(None) => Err(ResponseStatus::KeyDoesNotExist), - Err(string) => { - error!("Key ID Manager error: {}", string); - Err(ResponseStatus::KeyIDManagerError) - } + Ok(None) => Err(ResponseStatus::PsaErrorDoesNotExist), + Err(string) => Err(key_id_managers::to_response_status(string)), } } @@ -130,10 +128,7 @@ fn create_key_id( Ok(key_id) } - Err(string) => { - error!("Key ID Manager error: {}", string); - Err(ResponseStatus::KeyIDManagerError) - } + Err(string) => Err(key_id_managers::to_response_status(string)), } } @@ -148,21 +143,14 @@ fn remove_key_id( let _ = local_ids_handle.remove(&key_id); Ok(()) } - Err(string) => { - error!("Key ID Manager error: {}", string); - Err(ResponseStatus::KeyIDManagerError) - } + Err(string) => Err(key_id_managers::to_response_status(string)), } } fn key_id_exists(key_triple: &KeyTriple, store_handle: &dyn ManageKeyIDs) -> Result { - match store_handle.exists(key_triple) { - Ok(val) => Ok(val), - Err(string) => { - error!("Key ID Manager error: {}", string); - Err(ResponseStatus::KeyIDManagerError) - } - } + store_handle + .exists(key_triple) + .or_else(|e| Err(key_id_managers::to_response_status(e))) } impl MbedProvider { @@ -273,7 +261,7 @@ impl Provide for MbedProvider { let mut store_handle = self.key_id_store.write().expect("Key store lock poisoned"); let mut local_ids_handle = self.local_ids.write().expect("Local ID lock poisoned"); if key_id_exists(&key_triple, &*store_handle)? { - return Err(ResponseStatus::KeyAlreadyExists); + return Err(ResponseStatus::PsaErrorAlreadyExists); } let key_id = create_key_id( key_triple.clone(), @@ -321,7 +309,7 @@ impl Provide for MbedProvider { let mut store_handle = self.key_id_store.write().expect("Key store lock poisoned"); let mut local_ids_handle = self.local_ids.write().expect("Local ID lock poisoned"); if key_id_exists(&key_triple, &*store_handle)? { - return Err(ResponseStatus::KeyAlreadyExists); + return Err(ResponseStatus::PsaErrorAlreadyExists); } let key_id = create_key_id( key_triple.clone(), @@ -407,10 +395,7 @@ impl Provide for MbedProvider { if export_status != PSA_SUCCESS { error!("Export status: {}", export_status); // Safety: same conditions than above. - return Err(utils::convert_status(export_status).ok_or_else(|| { - error!("Failed to convert error status."); - ResponseStatus::PsaErrorGenericError - })?); + return Err(utils::convert_status(export_status)); } buffer.resize(actual_size, 0); @@ -453,10 +438,7 @@ impl Provide for MbedProvider { Ok(ResultDestroyKey {}) } else { error!("Destroy key status: {}", destroy_key_status); - Err(utils::convert_status(destroy_key_status).ok_or_else(|| { - error!("Failed to convert error status."); - ResponseStatus::PsaErrorGenericError - })?) + Err(utils::convert_status(destroy_key_status)) } } @@ -515,10 +497,7 @@ impl Provide for MbedProvider { Ok(res) } else { error!("Sign status: {}", sign_status); - Err(utils::convert_status(sign_status).ok_or_else(|| { - error!("Failed to convert error status."); - ResponseStatus::PsaErrorGenericError - })?) + Err(utils::convert_status(sign_status)) } } @@ -562,10 +541,7 @@ impl Provide for MbedProvider { if verify_status == PSA_SUCCESS { Ok(ResultAsymVerify {}) } else { - Err(utils::convert_status(verify_status).ok_or_else(|| { - error!("Failed to convert error status."); - ResponseStatus::PsaErrorGenericError - })?) + Err(utils::convert_status(verify_status)) } } } diff --git a/src/providers/mbed_provider/utils.rs b/src/providers/mbed_provider/utils.rs index f9969a22..2771ed09 100644 --- a/src/providers/mbed_provider/utils.rs +++ b/src/providers/mbed_provider/utils.rs @@ -87,12 +87,12 @@ pub fn convert_key_bits(key_size: u32) -> psa_key_bits_t { /// # Errors /// /// Only `KeyType::RsaKeypair` and `KeyType::RsaPublicKey` are supported. Returns -/// ResponseStatus::UnsupportedParameters otherwise. +/// ResponseStatus::PsaErrorNotSupported otherwise. pub fn convert_key_type(key_type: KeyType) -> Result { match key_type { KeyType::RsaKeypair => Ok(PSA_KEY_TYPE_RSA_KEYPAIR), KeyType::RsaPublicKey => Ok(PSA_KEY_TYPE_RSA_PUBLIC_KEY), - _ => Err(ResponseStatus::UnsupportedParameters), + _ => Err(ResponseStatus::PsaErrorNotSupported), } } @@ -136,20 +136,20 @@ pub fn convert_key_usage(operation: &key_attributes::KeyAttributes) -> psa_key_u /// /// Only `AlgorithmInner::Sign` is supported as algorithm with only the /// `SignAlgorithm::RsaPkcs1v15Sign` signing algorithm. Will return -/// ResponseStatus::UnsupportedParameters otherwise. +/// ResponseStatus::PsaErrorNotSupported otherwise. pub fn convert_algorithm(alg: &Algorithm) -> Result { let mut algo_val: psa_algorithm_t; match alg.inner() { AlgorithmInner::Sign(sign, hash) => { algo_val = match sign { SignAlgorithm::RsaPkcs1v15Sign => PSA_ALG_RSA_PKCS1V15_SIGN_BASE, - _ => return Err(ResponseStatus::UnsupportedParameters), + _ => return Err(ResponseStatus::PsaErrorNotSupported), }; if let Some(hash_alg) = hash { algo_val |= convert_hash_algorithm(*hash_alg) & PSA_ALG_HASH_MASK; } } - _ => return Err(ResponseStatus::UnsupportedParameters), + _ => return Err(ResponseStatus::PsaErrorNotSupported), } Ok(algo_val) } @@ -179,14 +179,25 @@ const PSA_STATUS_TO_RESPONSE_STATUS_OFFSET: psa_status_t = 1000; /// Converts between Mbed Crypto and native status values. /// Returns None if the conversion can not happen. -pub fn convert_status(psa_status: psa_status_t) -> Option { +pub fn convert_status(psa_status: psa_status_t) -> ResponseStatus { // psa_status_t errors are i32, negative values between -132 and -151. To map them to u16 // ResponseStatus values between 1000 and 1999 (as per the Wire Protocol), they are taken their // absolute values and added 1000. - let psa_status = psa_status.checked_abs()?; - let psa_status = psa_status.checked_add(PSA_STATUS_TO_RESPONSE_STATUS_OFFSET)?; - let psa_status = u16::try_from(psa_status).ok()?; - Some(psa_status.try_into().ok()?) + let psa_status = match psa_status.checked_abs() { + Some(status) => status, + None => return ResponseStatus::InvalidEncoding, + }; + let psa_status = match psa_status.checked_add(PSA_STATUS_TO_RESPONSE_STATUS_OFFSET) { + Some(status) => status, + None => return ResponseStatus::InvalidEncoding, + }; + let psa_status = match u16::try_from(psa_status) { + Ok(status) => status, + Err(_) => return ResponseStatus::InvalidEncoding, + }; + psa_status + .try_into() + .unwrap_or(ResponseStatus::InvalidEncoding) } macro_rules! bits_to_bytes { @@ -201,7 +212,7 @@ pub fn psa_asymmetric_sign_output_size(key_attrs: &psa_key_attributes_t) -> Resu match key_attrs.core.type_ { PSA_KEY_TYPE_RSA_KEYPAIR => Ok(usize::from(bits_to_bytes!(key_attrs.core.bits))), PSA_KEY_TYPE_ECC_KEYPAIR_BASE => Ok(usize::from(bits_to_bytes!(key_attrs.core.bits) * 2)), - _ => Err(ResponseStatus::UnsupportedParameters), + _ => Err(ResponseStatus::PsaErrorNotSupported), } } @@ -218,7 +229,7 @@ pub fn psa_export_public_key_size(key_attrs: &psa_key_attributes_t) -> Result Ok(usize::from( export_asn1_int_max_size!(key_attrs.core.bits) + 11, )), - _ => Err(ResponseStatus::UnsupportedParameters), + _ => Err(ResponseStatus::PsaErrorNotSupported), } } @@ -277,10 +288,7 @@ impl KeyHandle { let open_key_status = psa_crypto_binding::psa_open_key(key_id, &mut key_handle); if open_key_status != PSA_SUCCESS { error!("Open key status: {}", open_key_status); - Err(convert_status(open_key_status).ok_or_else(|| { - error!("Failed to convert error status."); - ResponseStatus::InvalidEncoding - })?) + Err(convert_status(open_key_status)) } else { Ok(KeyHandle(key_handle)) } @@ -299,10 +307,7 @@ impl KeyHandle { let status = psa_crypto_binding::psa_generate_key(attributes, &mut key_handle); if status != PSA_SUCCESS { error!("Generate key status: {}", status); - Err(convert_status(status).ok_or_else(|| { - error!("Failed to convert error status."); - ResponseStatus::InvalidEncoding - })?) + Err(convert_status(status)) } else { Ok(KeyHandle(key_handle)) } @@ -326,10 +331,7 @@ impl KeyHandle { ); if status != PSA_SUCCESS { error!("Import key status: {}", status); - Err(convert_status(status).ok_or_else(|| { - error!("Failed to convert error status."); - ResponseStatus::InvalidEncoding - })?) + Err(convert_status(status)) } else { Ok(KeyHandle(key_handle)) } @@ -347,10 +349,7 @@ impl KeyHandle { if get_attrs_status != PSA_SUCCESS { error!("Get key attributes status: {}", get_attrs_status); - Err(convert_status(get_attrs_status).ok_or_else(|| { - error!("Failed to convert error status."); - ResponseStatus::InvalidEncoding - })?) + Err(convert_status(get_attrs_status)) } else { Ok(KeyAttributes(key_attrs)) } @@ -372,10 +371,7 @@ impl KeyHandle { if status != PSA_SUCCESS { error!("Close key status: {}", status); - Err(convert_status(status).ok_or_else(|| { - error!("Failed to convert error status."); - ResponseStatus::InvalidEncoding - })?) + Err(convert_status(status)) } else { Ok(()) } diff --git a/src/providers/mod.rs b/src/providers/mod.rs index f67b54dc..d35da1ee 100644 --- a/src/providers/mod.rs +++ b/src/providers/mod.rs @@ -72,7 +72,7 @@ pub trait Provide { /// List the providers running in the service. fn list_providers(&self, _op: OpListProviders) -> Result { - Err(ResponseStatus::UnsupportedOperation) + Err(ResponseStatus::PsaErrorNotSupported) } /// List the opcodes supported by the current provider. @@ -85,17 +85,17 @@ pub trait Provide { /// This operation will only fail if not implemented. It will never fail when being called on /// the `CoreProvider`. fn ping(&self, _op: OpPing) -> Result { - Err(ResponseStatus::UnsupportedOperation) + Err(ResponseStatus::PsaErrorNotSupported) } /// Execute a CreateKey operation. fn create_key(&self, _app_name: ApplicationName, _op: OpCreateKey) -> Result { - Err(ResponseStatus::UnsupportedOperation) + Err(ResponseStatus::PsaErrorNotSupported) } /// Execute a ImportKey operation. fn import_key(&self, _app_name: ApplicationName, _op: OpImportKey) -> Result { - Err(ResponseStatus::UnsupportedOperation) + Err(ResponseStatus::PsaErrorNotSupported) } /// Execute a ExportPublicKey operation. @@ -104,7 +104,7 @@ pub trait Provide { _app_name: ApplicationName, _op: OpExportPublicKey, ) -> Result { - Err(ResponseStatus::UnsupportedOperation) + Err(ResponseStatus::PsaErrorNotSupported) } /// Execute a DestroyKey operation. @@ -113,13 +113,13 @@ pub trait Provide { _app_name: ApplicationName, _op: OpDestroyKey, ) -> Result { - Err(ResponseStatus::UnsupportedOperation) + Err(ResponseStatus::PsaErrorNotSupported) } /// Execute a AsymSign operation. This operation only signs the short digest given but does not /// hash it. fn asym_sign(&self, _app_name: ApplicationName, _op: OpAsymSign) -> Result { - Err(ResponseStatus::UnsupportedOperation) + Err(ResponseStatus::PsaErrorNotSupported) } /// Execute a AsymVerify operation. @@ -128,6 +128,6 @@ pub trait Provide { _app_name: ApplicationName, _op: OpAsymVerify, ) -> Result { - Err(ResponseStatus::UnsupportedOperation) + Err(ResponseStatus::PsaErrorNotSupported) } } diff --git a/src/providers/pkcs11_provider/mod.rs b/src/providers/pkcs11_provider/mod.rs index 688cf067..966679ee 100644 --- a/src/providers/pkcs11_provider/mod.rs +++ b/src/providers/pkcs11_provider/mod.rs @@ -14,6 +14,7 @@ // limitations under the License. use super::Provide; use crate::authenticators::ApplicationName; +use crate::key_id_managers; use crate::key_id_managers::{KeyTriple, ManageKeyIDs}; use derivative::Derivative; use log::{error, info, warn}; @@ -29,9 +30,8 @@ use parsec_interface::operations::{OpListOpcodes, ResultListOpcodes}; use parsec_interface::requests::{Opcode, ProviderID, ResponseStatus, Result}; use picky_asn1::wrapper::IntegerAsn1; use pkcs11::types::{ - CKF_OS_LOCKING_OK, CKF_RW_SESSION, CKF_SERIAL_SESSION, CKR_OK, CKR_SIGNATURE_INVALID, CKU_USER, - CK_ATTRIBUTE, CK_C_INITIALIZE_ARGS, CK_MECHANISM, CK_OBJECT_HANDLE, CK_SESSION_HANDLE, - CK_SLOT_ID, + CKF_OS_LOCKING_OK, CKF_RW_SESSION, CKF_SERIAL_SESSION, CKR_OK, CKU_USER, CK_ATTRIBUTE, + CK_C_INITIALIZE_ARGS, CK_MECHANISM, CK_OBJECT_HANDLE, CK_SESSION_HANDLE, CK_SLOT_ID, }; use pkcs11::Ctx; use serde::{Deserialize, Serialize}; @@ -43,6 +43,8 @@ use uuid::Uuid; type LocalIdStore = HashSet<[u8; 4]>; +mod utils; + const SUPPORTED_OPCODES: [Opcode; 7] = [ Opcode::CreateKey, Opcode::DestroyKey, @@ -146,7 +148,7 @@ impl Session<'_> { "Error opening session for slot {}: {}.", provider.slot_number, e ); - Err(ResponseStatus::PsaErrorCommunicationFailure) + Err(utils::to_response_status(e)) } } } @@ -191,7 +193,7 @@ impl Session<'_> { } Err(e) => { error!("Login operation failed with {}", e); - Err(ResponseStatus::PsaErrorHardwareFailure) + Err(utils::to_response_status(e)) } } } else { @@ -228,7 +230,7 @@ impl Session<'_> { "Failed to log out from session {} due to error {}. Continuing...", self.session_handle, e ); - Err(ResponseStatus::PsaErrorHardwareFailure) + Err(utils::to_response_status(e)) } } } else { @@ -272,11 +274,8 @@ fn get_key_id(key_triple: &KeyTriple, store_handle: &dyn ManageKeyIDs) -> Result Err(ResponseStatus::KeyIDManagerError) } } - Ok(None) => Err(ResponseStatus::KeyDoesNotExist), - Err(string) => { - error!("Key ID Manager error: {}", string); - Err(ResponseStatus::KeyIDManagerError) - } + Ok(None) => Err(ResponseStatus::PsaErrorDoesNotExist), + Err(string) => Err(key_id_managers::to_response_status(string)), } } @@ -298,10 +297,7 @@ fn create_key_id( Ok(key_id) } - Err(string) => { - error!("Key ID Manager error: {}", string); - Err(ResponseStatus::KeyIDManagerError) - } + Err(string) => Err(key_id_managers::to_response_status(string)), } } @@ -316,20 +312,14 @@ fn remove_key_id( let _ = local_ids_handle.remove(&key_id); Ok(()) } - Err(string) => { - error!("Key ID Manager error: {}", string); - Err(ResponseStatus::KeyIDManagerError) - } + Err(string) => Err(key_id_managers::to_response_status(string)), } } fn key_id_exists(key_triple: &KeyTriple, store_handle: &dyn ManageKeyIDs) -> Result { match store_handle.exists(key_triple) { Ok(val) => Ok(val), - Err(string) => { - error!("Key ID Manager error: {}", string); - Err(ResponseStatus::KeyIDManagerError) - } + Err(string) => Err(key_id_managers::to_response_status(string)), } } @@ -446,13 +436,13 @@ impl Pkcs11Provider { if let Err(e) = self.backend.find_objects_init(session, &template) { error!("Object enumeration init failed with {}", e); - Err(ResponseStatus::PsaErrorHardwareFailure) + Err(utils::to_response_status(e)) } else { match self.backend.find_objects(session, 1) { Ok(objects) => { if let Err(e) = self.backend.find_objects_final(session) { error!("Object enumeration final failed with {}", e); - Err(ResponseStatus::PsaErrorHardwareFailure) + Err(utils::to_response_status(e)) } else if objects.is_empty() { Err(ResponseStatus::PsaErrorDoesNotExist) } else { @@ -461,7 +451,7 @@ impl Pkcs11Provider { } Err(e) => { error!("Finding objects failed with {}", e); - Err(ResponseStatus::PsaErrorHardwareFailure) + Err(utils::to_response_status(e)) } } } @@ -497,7 +487,7 @@ impl Provide for Pkcs11Provider { { error!( "The PKCS11 provider currently only supports creating RSA key pairs for signing and verifying. The signature algorithm needs to be RSA PKCS#1 v1.5 and the text hashed with SHA-256."); - return Err(ResponseStatus::UnsupportedOperation); + return Err(ResponseStatus::PsaErrorNotSupported); } let key_name = op.key_name; @@ -508,7 +498,7 @@ impl Provide for Pkcs11Provider { let mut store_handle = self.key_id_store.write().expect("Key store lock poisoned"); let mut local_ids_handle = self.local_ids.write().expect("Local ID lock poisoned"); if key_id_exists(&key_triple, &*store_handle)? { - return Err(ResponseStatus::KeyAlreadyExists); + return Err(ResponseStatus::PsaErrorAlreadyExists); } let key_id = create_key_id( key_triple.clone(), @@ -592,7 +582,7 @@ impl Provide for Pkcs11Provider { { error!( "The PKCS 11 provider currently only supports importing RSA public key for verifying. The signature algorithm needs to be RSA PKCS#1 v1.5 and the text hashed with SHA-256."); - return Err(ResponseStatus::UnsupportedOperation); + return Err(ResponseStatus::PsaErrorNotSupported); } let key_name = op.key_name; @@ -600,7 +590,7 @@ impl Provide for Pkcs11Provider { let mut store_handle = self.key_id_store.write().expect("Key store lock poisoned"); let mut local_ids_handle = self.local_ids.write().expect("Local ID lock poisoned"); if key_id_exists(&key_triple, &*store_handle)? { - return Err(ResponseStatus::KeyAlreadyExists); + return Err(ResponseStatus::PsaErrorAlreadyExists); } let key_id = create_key_id( key_triple.clone(), @@ -686,7 +676,7 @@ impl Provide for Pkcs11Provider { &mut *store_handle, &mut local_ids_handle, )?; - Err(ResponseStatus::PsaErrorHardwareFailure) + Err(utils::to_response_status(e)) } } } @@ -725,14 +715,14 @@ impl Provide for Pkcs11Provider { Ok((rv, attrs)) => { if rv != CKR_OK { error!("Error when extracting attribute: {}.", rv); - Err(ResponseStatus::PsaErrorCommunicationFailure) + Err(utils::rv_to_response_status(rv)) } else { Ok((attrs[0].ulValueLen, attrs[1].ulValueLen)) } } Err(e) => { error!("Failed to read attributes from public key. Error: {}", e); - Err(ResponseStatus::PsaErrorCommunicationFailure) + Err(utils::to_response_status(e)) } }?; @@ -757,7 +747,7 @@ impl Provide for Pkcs11Provider { let (rv, attrs) = res; if rv != CKR_OK { error!("Error when extracting attribute: {}.", rv); - Err(ResponseStatus::PsaErrorCommunicationFailure) + Err(utils::rv_to_response_status(rv)) } else { let modulus = attrs[0].get_bytes(); let public_exponent = attrs[1].get_bytes(); @@ -780,7 +770,7 @@ impl Provide for Pkcs11Provider { } Err(e) => { error!("Failed to read attributes from public key. Error: {}", e); - Err(ResponseStatus::PsaErrorCommunicationFailure) + Err(utils::to_response_status(e)) } } } @@ -806,7 +796,7 @@ impl Provide for Pkcs11Provider { Ok(_) => info!("Private part of the key destroyed successfully."), Err(e) => { error!("Failed to destroy private part of the key. Error: {}", e); - return Err(ResponseStatus::PsaErrorGenericError); + return Err(utils::to_response_status(e)); } }; } @@ -823,7 +813,7 @@ impl Provide for Pkcs11Provider { Ok(_) => info!("Private part of the key destroyed successfully."), Err(e) => { error!("Failed to destroy private part of the key. Error: {}", e); - return Err(ResponseStatus::PsaErrorGenericError); + return Err(utils::to_response_status(e)); } }; } @@ -862,7 +852,7 @@ impl Provide for Pkcs11Provider { if hash.len() != 32 { error!("The PKCS11 provider currently only supports 256 bits long digests."); - return Err(ResponseStatus::UnsupportedOperation); + return Err(ResponseStatus::PsaErrorNotSupported); } let session = Session::new(self, ReadWriteSession::ReadWrite)?; @@ -891,13 +881,13 @@ impl Provide for Pkcs11Provider { Ok(signature) => Ok(ResultAsymSign { signature }), Err(e) => { error!("Failed to execute signing operation. Error: {}", e); - Err(ResponseStatus::PsaErrorGenericError) + Err(utils::to_response_status(e)) } } } Err(e) => { error!("Failed to initialize signing operation. Error: {}", e); - Err(ResponseStatus::PsaErrorGenericError) + Err(utils::to_response_status(e)) } } } @@ -921,7 +911,7 @@ impl Provide for Pkcs11Provider { if hash.len() != 32 { error!("The PKCS11 provider currently only supports 256 bits long digests."); - return Err(ResponseStatus::UnsupportedOperation); + return Err(ResponseStatus::PsaErrorNotSupported); } let session = Session::new(self, ReadWriteSession::ReadWrite)?; @@ -954,21 +944,12 @@ impl Provide for Pkcs11Provider { .verify(session.session_handle(), &digest_info, &signature) { Ok(_) => Ok(ResultAsymVerify {}), - Err(e) => match e { - pkcs11::errors::Error::Pkcs11(CKR_SIGNATURE_INVALID) => { - info!("Signature verification failed."); - Err(ResponseStatus::PsaErrorInvalidSignature) - } - err => { - error!("Failed to execute verify operation. Error: {}", err); - Err(ResponseStatus::PsaErrorGenericError) - } - }, + Err(e) => Err(utils::to_response_status(e)), } } Err(e) => { error!("Failed to initialize verifying operation. Error: {}", e); - Err(ResponseStatus::PsaErrorGenericError) + Err(utils::to_response_status(e)) } } } diff --git a/src/providers/pkcs11_provider/utils.rs b/src/providers/pkcs11_provider/utils.rs new file mode 100644 index 00000000..9818a89c --- /dev/null +++ b/src/providers/pkcs11_provider/utils.rs @@ -0,0 +1,141 @@ +// Copyright (c) 2020, Arm Limited, All Rights Reserved +// 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. + +use log::error; +use parsec_interface::requests::ResponseStatus; +use pkcs11::errors::Error; +use pkcs11::types::*; + +pub fn to_response_status(error: Error) -> ResponseStatus { + match error { + Error::Io(e) => ResponseStatus::from(e), + Error::Module(e) => { + error!("Conversion of error \"{}\"", e); + ResponseStatus::PsaErrorGenericError + } + Error::InvalidInput(e) => { + error!("Conversion of error \"{}\"", e); + ResponseStatus::PsaErrorInvalidArgument + } + Error::Pkcs11(ck_rv) => rv_to_response_status(ck_rv), + } +} + +pub fn rv_to_response_status(rv: CK_RV) -> ResponseStatus { + match rv { + CKR_OK => ResponseStatus::Success, + CKR_CANCEL => ResponseStatus::PsaErrorGenericError, + CKR_HOST_MEMORY => ResponseStatus::PsaErrorInsufficientMemory, + CKR_SLOT_ID_INVALID => ResponseStatus::PsaErrorInvalidArgument, + CKR_GENERAL_ERROR => ResponseStatus::PsaErrorGenericError, + CKR_FUNCTION_FAILED => ResponseStatus::PsaErrorGenericError, + CKR_ARGUMENTS_BAD => ResponseStatus::PsaErrorInvalidArgument, + CKR_NO_EVENT => ResponseStatus::PsaErrorGenericError, + CKR_NEED_TO_CREATE_THREADS => ResponseStatus::PsaErrorInvalidArgument, + CKR_CANT_LOCK => ResponseStatus::PsaErrorInvalidArgument, + CKR_ATTRIBUTE_READ_ONLY => ResponseStatus::PsaErrorNotPermitted, + CKR_ATTRIBUTE_SENSITIVE => ResponseStatus::PsaErrorNotPermitted, + CKR_ATTRIBUTE_TYPE_INVALID => ResponseStatus::PsaErrorInvalidArgument, + CKR_ATTRIBUTE_VALUE_INVALID => ResponseStatus::PsaErrorInvalidArgument, + CKR_ACTION_PROHIBITED => ResponseStatus::PsaErrorNotPermitted, + CKR_DATA_INVALID => ResponseStatus::PsaErrorInvalidArgument, + CKR_DATA_LEN_RANGE => ResponseStatus::PsaErrorInvalidArgument, + CKR_DEVICE_ERROR => ResponseStatus::PsaErrorHardwareFailure, + CKR_DEVICE_MEMORY => ResponseStatus::PsaErrorInsufficientStorage, + CKR_DEVICE_REMOVED => ResponseStatus::PsaErrorHardwareFailure, + CKR_ENCRYPTED_DATA_INVALID => ResponseStatus::PsaErrorInvalidArgument, + CKR_ENCRYPTED_DATA_LEN_RANGE => ResponseStatus::PsaErrorInvalidArgument, + CKR_FUNCTION_CANCELED => ResponseStatus::PsaErrorGenericError, + CKR_FUNCTION_NOT_PARALLEL => ResponseStatus::PsaErrorGenericError, + CKR_FUNCTION_NOT_SUPPORTED => ResponseStatus::PsaErrorNotSupported, + CKR_KEY_HANDLE_INVALID => ResponseStatus::PsaErrorInvalidHandle, + CKR_KEY_SIZE_RANGE => ResponseStatus::PsaErrorNotSupported, + CKR_KEY_TYPE_INCONSISTENT => ResponseStatus::PsaErrorInvalidArgument, + CKR_KEY_NOT_NEEDED => ResponseStatus::PsaErrorInvalidArgument, + CKR_KEY_CHANGED => ResponseStatus::PsaErrorInvalidArgument, + CKR_KEY_NEEDED => ResponseStatus::PsaErrorInvalidArgument, + CKR_KEY_INDIGESTIBLE => ResponseStatus::PsaErrorGenericError, + CKR_KEY_FUNCTION_NOT_PERMITTED => ResponseStatus::PsaErrorNotPermitted, + CKR_KEY_NOT_WRAPPABLE => ResponseStatus::PsaErrorNotSupported, + CKR_KEY_UNEXTRACTABLE => ResponseStatus::PsaErrorNotPermitted, + CKR_MECHANISM_INVALID => ResponseStatus::PsaErrorInvalidArgument, + CKR_MECHANISM_PARAM_INVALID => ResponseStatus::PsaErrorInvalidArgument, + CKR_OBJECT_HANDLE_INVALID => ResponseStatus::PsaErrorInvalidHandle, + CKR_OPERATION_ACTIVE => ResponseStatus::PsaErrorBadState, + CKR_OPERATION_NOT_INITIALIZED => ResponseStatus::PsaErrorGenericError, + CKR_PIN_INCORRECT => ResponseStatus::PsaErrorNotPermitted, + CKR_PIN_INVALID => ResponseStatus::PsaErrorInvalidArgument, + CKR_PIN_LEN_RANGE => ResponseStatus::PsaErrorInvalidArgument, + CKR_PIN_EXPIRED => ResponseStatus::PsaErrorBadState, + CKR_PIN_LOCKED => ResponseStatus::PsaErrorNotPermitted, + CKR_SESSION_CLOSED => ResponseStatus::PsaErrorBadState, + CKR_SESSION_COUNT => ResponseStatus::PsaErrorBadState, + CKR_SESSION_HANDLE_INVALID => ResponseStatus::PsaErrorInvalidHandle, + CKR_SESSION_PARALLEL_NOT_SUPPORTED => ResponseStatus::PsaErrorNotSupported, + CKR_SESSION_READ_ONLY => ResponseStatus::PsaErrorNotPermitted, + CKR_SESSION_EXISTS => ResponseStatus::PsaErrorBadState, + CKR_SESSION_READ_ONLY_EXISTS => ResponseStatus::PsaErrorBadState, + CKR_SESSION_READ_WRITE_SO_EXISTS => ResponseStatus::PsaErrorBadState, + CKR_SIGNATURE_INVALID => ResponseStatus::PsaErrorInvalidSignature, + CKR_SIGNATURE_LEN_RANGE => ResponseStatus::PsaErrorInvalidSignature, + CKR_TEMPLATE_INCOMPLETE => ResponseStatus::PsaErrorInvalidArgument, + CKR_TEMPLATE_INCONSISTENT => ResponseStatus::PsaErrorInvalidArgument, + CKR_TOKEN_NOT_PRESENT => ResponseStatus::PsaErrorHardwareFailure, + CKR_TOKEN_NOT_RECOGNIZED => ResponseStatus::PsaErrorHardwareFailure, + CKR_TOKEN_WRITE_PROTECTED => ResponseStatus::PsaErrorNotPermitted, + CKR_UNWRAPPING_KEY_HANDLE_INVALID => ResponseStatus::PsaErrorInvalidArgument, + CKR_UNWRAPPING_KEY_SIZE_RANGE => ResponseStatus::PsaErrorNotSupported, + CKR_UNWRAPPING_KEY_TYPE_INCONSISTENT => ResponseStatus::PsaErrorInvalidArgument, + CKR_USER_ALREADY_LOGGED_IN => ResponseStatus::PsaErrorBadState, + CKR_USER_NOT_LOGGED_IN => ResponseStatus::PsaErrorBadState, + CKR_USER_PIN_NOT_INITIALIZED => ResponseStatus::PsaErrorBadState, + CKR_USER_TYPE_INVALID => ResponseStatus::PsaErrorInvalidArgument, + CKR_USER_ANOTHER_ALREADY_LOGGED_IN => ResponseStatus::PsaErrorBadState, + CKR_USER_TOO_MANY_TYPES => ResponseStatus::PsaErrorBadState, + CKR_WRAPPED_KEY_INVALID => ResponseStatus::PsaErrorInvalidArgument, + CKR_WRAPPED_KEY_LEN_RANGE => ResponseStatus::PsaErrorInvalidArgument, + CKR_WRAPPING_KEY_HANDLE_INVALID => ResponseStatus::PsaErrorInvalidArgument, + CKR_WRAPPING_KEY_SIZE_RANGE => ResponseStatus::PsaErrorNotSupported, + CKR_WRAPPING_KEY_TYPE_INCONSISTENT => ResponseStatus::PsaErrorInvalidArgument, + CKR_RANDOM_SEED_NOT_SUPPORTED => ResponseStatus::PsaErrorInvalidArgument, + CKR_RANDOM_NO_RNG => ResponseStatus::PsaErrorInsufficientEntropy, + CKR_DOMAIN_PARAMS_INVALID => ResponseStatus::PsaErrorInvalidArgument, + CKR_CURVE_NOT_SUPPORTED => ResponseStatus::PsaErrorNotSupported, + CKR_BUFFER_TOO_SMALL => ResponseStatus::PsaErrorBufferTooSmall, + CKR_SAVED_STATE_INVALID => ResponseStatus::PsaErrorInvalidArgument, + CKR_INFORMATION_SENSITIVE => ResponseStatus::PsaErrorNotPermitted, + CKR_STATE_UNSAVEABLE => ResponseStatus::PsaErrorHardwareFailure, + CKR_CRYPTOKI_NOT_INITIALIZED => ResponseStatus::PsaErrorBadState, + CKR_CRYPTOKI_ALREADY_INITIALIZED => ResponseStatus::PsaErrorBadState, + CKR_MUTEX_BAD => ResponseStatus::PsaErrorInvalidArgument, + CKR_MUTEX_NOT_LOCKED => ResponseStatus::PsaErrorBadState, + CKR_NEW_PIN_MODE => ResponseStatus::PsaErrorGenericError, + CKR_NEXT_OTP => ResponseStatus::PsaErrorGenericError, + CKR_EXCEEDED_MAX_ITERATIONS => ResponseStatus::PsaErrorGenericError, + CKR_FIPS_SELF_TEST_FAILED => ResponseStatus::PsaErrorGenericError, + CKR_LIBRARY_LOAD_FAILED => ResponseStatus::ConnectionError, + CKR_PIN_TOO_WEAK => ResponseStatus::PsaErrorInvalidArgument, + CKR_PUBLIC_KEY_INVALID => ResponseStatus::PsaErrorInvalidArgument, + CKR_FUNCTION_REJECTED => ResponseStatus::PsaErrorGenericError, + CKR_VENDOR_DEFINED => ResponseStatus::PsaErrorGenericError, + e => { + error!( + "Can not encode value {} into on of the possible PKCS#11 return values.", + e + ); + ResponseStatus::InvalidEncoding + } + } +} diff --git a/src/providers/tpm_provider/mod.rs b/src/providers/tpm_provider/mod.rs index cd44f707..5458c436 100644 --- a/src/providers/tpm_provider/mod.rs +++ b/src/providers/tpm_provider/mod.rs @@ -14,6 +14,7 @@ // limitations under the License. use super::Provide; use crate::authenticators::ApplicationName; +use crate::key_id_managers; use crate::key_id_managers::{KeyTriple, ManageKeyIDs}; use derivative::Derivative; use log::{error, info}; @@ -32,11 +33,12 @@ use serde::{Deserialize, Serialize}; use std::io::ErrorKind; use std::sync::{Arc, Mutex, RwLock}; use tss_esapi::{ - constants::TPM2_ALG_SHA256, response_code::Error, response_code::Tss2ResponseCodeKind, - utils::AsymSchemeUnion, utils::Signature, utils::TpmsContext, Tcti, + constants::TPM2_ALG_SHA256, utils::AsymSchemeUnion, utils::Signature, utils::TpmsContext, Tcti, }; use uuid::Uuid; +mod utils; + const SUPPORTED_OPCODES: [Opcode; 7] = [ Opcode::CreateKey, Opcode::DestroyKey, @@ -91,25 +93,15 @@ fn insert_password_context( key_triple: KeyTriple, password_context: PasswordContext, ) -> Result<()> { - let error_storing = |e| { - error!("Error storing a mapping: {}.", e); - Err(ResponseStatus::KeyIDManagerError) - }; - let error_serializing = |e| { - error!("Error serializing the PasswordContext: {}.", e); - Err(ResponseStatus::KeyIDManagerError) - }; + let error_storing = |e| Err(key_id_managers::to_response_status(e)); if store_handle - .insert( - key_triple, - bincode::serialize(&password_context).or_else(error_serializing)?, - ) + .insert(key_triple, bincode::serialize(&password_context)?) .or_else(error_storing)? .is_some() { error!("Inserting a mapping in the Key ID Manager that would overwrite an existing one."); - Err(ResponseStatus::KeyAlreadyExists) + Err(ResponseStatus::PsaErrorAlreadyExists) } else { Ok(()) } @@ -120,10 +112,9 @@ fn get_password_context( store_handle: &dyn ManageKeyIDs, key_triple: KeyTriple, ) -> Result { - let password_context = store_handle.get(&key_triple).or_else(|e| { - error!("Error getting a mapping: {}.", e); - Err(ResponseStatus::KeyIDManagerError) - })?; + let password_context = store_handle + .get(&key_triple) + .or_else(|e| Err(key_id_managers::to_response_status(e)))?; let password_context = match password_context { Some(context) => context, None => { @@ -131,13 +122,10 @@ fn get_password_context( "Key triple \"{}\" does not exist in the Key ID Manager.", key_triple ); - return Err(ResponseStatus::KeyDoesNotExist); + return Err(ResponseStatus::PsaErrorDoesNotExist); } }; - Ok(bincode::deserialize(password_context).or_else(|e| { - error!("Error deserializing the PasswordContext: {}.", e); - Err(ResponseStatus::KeyIDManagerError) - })?) + Ok(bincode::deserialize(password_context)?) } impl TpmProvider { @@ -180,7 +168,7 @@ impl Provide for TpmProvider { { error!( "The TPM provider currently only supports creating RSA key pairs for signing and verifying. The signature algorithm needs to be RSA PKCS#1 v1.5 and the text hashed with SHA-256."); - return Err(ResponseStatus::UnsupportedOperation); + return Err(ResponseStatus::PsaErrorNotSupported); } let key_name = op.key_name; @@ -199,7 +187,7 @@ impl Provide for TpmProvider { .create_rsa_signing_key(key_size, AUTH_VAL_LEN) .or_else(|e| { error!("Error creating a RSA signing key: {}.", e); - Err(ResponseStatus::PsaErrorHardwareFailure) + Err(utils::to_response_status(e)) })?; insert_password_context( @@ -221,7 +209,7 @@ impl Provide for TpmProvider { { error!( "The TPM provider currently only supports importing RSA public key for verifying. The signature algorithm needs to be RSA PKCS#1 v1.5 and the text hashed with SHA-256."); - return Err(ResponseStatus::UnsupportedOperation); + return Err(ResponseStatus::PsaErrorNotSupported); } let key_name = op.key_name; @@ -236,7 +224,7 @@ impl Provide for TpmProvider { let public_key: RsaPublicKey = picky_asn1_der::from_bytes(&key_data).or_else(|err| { error!("Could not deserialise key elements: {}.", err); - Err(ResponseStatus::PsaErrorCommunicationFailure) + Err(ResponseStatus::PsaErrorInvalidArgument) })?; if public_key.modulus.is_negative() || public_key.public_exponent.is_negative() { @@ -246,7 +234,7 @@ impl Provide for TpmProvider { if public_key.public_exponent.as_unsigned_bytes_be() != PUBLIC_EXPONENT { error!("The TPM Provider only supports 0x101 as public exponent for RSA public keys, {:?} given.", public_key.public_exponent.as_unsigned_bytes_be()); - return Err(ResponseStatus::UnsupportedOperation); + return Err(ResponseStatus::PsaErrorNotSupported); } let key_data = public_key.modulus.as_unsigned_bytes_be(); @@ -256,14 +244,14 @@ impl Provide for TpmProvider { "The TPM provider only supports 1024 and 2048 bits RSA public keys ({} bits given).", len * 8 ); - return Err(ResponseStatus::UnsupportedOperation); + return Err(ResponseStatus::PsaErrorNotSupported); } let pub_key_context = esapi_context .load_external_rsa_public_key(&key_data) .or_else(|e| { error!("Error creating a RSA signing key: {}.", e); - Err(ResponseStatus::PsaErrorHardwareFailure) + Err(utils::to_response_status(e)) })?; insert_password_context( @@ -298,7 +286,7 @@ impl Provide for TpmProvider { .read_public_key(password_context.context) .or_else(|e| { error!("Error reading a public key: {}.", e); - Err(ResponseStatus::PsaErrorHardwareFailure) + Err(utils::to_response_status(e)) })?; let key = RsaPublicKey { @@ -320,10 +308,7 @@ impl Provide for TpmProvider { let key_triple = KeyTriple::new(app_name, ProviderID::TpmProvider, key_name); let mut store_handle = self.key_id_store.write().expect("Key store lock poisoned"); - let error_closure = |e| { - error!("Error storing a mapping: {}.", e); - Err(ResponseStatus::KeyIDManagerError) - }; + let error_closure = |e| Err(key_id_managers::to_response_status(e)); if store_handle .remove(&key_triple) .or_else(error_closure)? @@ -333,7 +318,7 @@ impl Provide for TpmProvider { "Key triple \"{}\" does not exist in the Key ID Manager.", key_triple ); - Err(ResponseStatus::KeyDoesNotExist) + Err(ResponseStatus::PsaErrorDoesNotExist) } else { Ok(ResultDestroyKey {}) } @@ -366,7 +351,7 @@ impl Provide for TpmProvider { ) .or_else(|e| { error!("Error signing: {}.", e); - Err(ResponseStatus::PsaErrorHardwareFailure) + Err(utils::to_response_status(e)) })?; Ok(ResultAsymSign { @@ -401,20 +386,7 @@ impl Provide for TpmProvider { let _ = esapi_context .verify_signature(password_context.context, &hash, signature) - .or_else(|e| { - if let Error::Tss2Error(rc) = e { - if rc.kind() == Some(Tss2ResponseCodeKind::Signature) { - error!("The verification failed."); - Err(ResponseStatus::PsaErrorInvalidSignature) - } else { - error!("Error verifying: {}.", rc); - Err(ResponseStatus::PsaErrorHardwareFailure) - } - } else { - error!("Error verifying: {}.", e); - Err(ResponseStatus::PsaErrorHardwareFailure) - } - })?; + .or_else(|e| Err(utils::to_response_status(e)))?; Ok(ResultAsymVerify {}) } diff --git a/src/providers/tpm_provider/utils.rs b/src/providers/tpm_provider/utils.rs new file mode 100644 index 00000000..193383ad --- /dev/null +++ b/src/providers/tpm_provider/utils.rs @@ -0,0 +1,149 @@ +// Copyright (c) 2020, Arm Limited, All Rights Reserved +// 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. + +use log::error; +use parsec_interface::requests::ResponseStatus; +use tss_esapi::response_code::{Error, Tss2ResponseCodeKind, WrapperErrorKind}; + +pub fn to_response_status(error: Error) -> ResponseStatus { + match error { + Error::WrapperError(e) => match e { + WrapperErrorKind::WrongParamSize + | WrapperErrorKind::ParamsMissing + | WrapperErrorKind::InconsistentParams => ResponseStatus::PsaErrorInvalidArgument, + WrapperErrorKind::UnsupportedParam => ResponseStatus::PsaErrorNotSupported, + }, + Error::Tss2Error(e) => { + if let Some(kind) = e.kind() { + match kind { + // FormatZero errors + Tss2ResponseCodeKind::Success => ResponseStatus::Success, + Tss2ResponseCodeKind::TpmVendorSpecific => ResponseStatus::PsaErrorGenericError, + Tss2ResponseCodeKind::Initialize => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::Failure => ResponseStatus::PsaErrorHardwareFailure, + Tss2ResponseCodeKind::Sequence => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::Private => ResponseStatus::PsaErrorGenericError, + Tss2ResponseCodeKind::Hmac => ResponseStatus::PsaErrorGenericError, + Tss2ResponseCodeKind::Disabled => ResponseStatus::PsaErrorNotPermitted, + Tss2ResponseCodeKind::Exclusive => ResponseStatus::PsaErrorNotPermitted, + Tss2ResponseCodeKind::AuthType => ResponseStatus::PsaErrorInvalidHandle, + Tss2ResponseCodeKind::AuthMissing => ResponseStatus::PsaErrorNotPermitted, + Tss2ResponseCodeKind::Policy => ResponseStatus::PsaErrorNotPermitted, + Tss2ResponseCodeKind::Pcr => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::PcrChanged => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::Upgrade => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::TooManyContexts => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::AuthUnavailable => ResponseStatus::PsaErrorGenericError, + Tss2ResponseCodeKind::Reboot => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::Unbalanced => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::CommandSize => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::CommandCode => ResponseStatus::PsaErrorNotSupported, + Tss2ResponseCodeKind::AuthSize => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::AuthContext => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::NvRange => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::NvSize => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::NvLocked => ResponseStatus::PsaErrorNotPermitted, + Tss2ResponseCodeKind::NvAuthorization => ResponseStatus::PsaErrorGenericError, + Tss2ResponseCodeKind::NvUninitialized => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::NvSpace => ResponseStatus::PsaErrorInsufficientStorage, + Tss2ResponseCodeKind::NvDefined => ResponseStatus::PsaErrorAlreadyExists, + Tss2ResponseCodeKind::BadContext => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::CpHash => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::Parent => ResponseStatus::PsaErrorInvalidHandle, + Tss2ResponseCodeKind::NeedsTest => ResponseStatus::PsaErrorGenericError, + Tss2ResponseCodeKind::NoResult => ResponseStatus::PsaErrorGenericError, + Tss2ResponseCodeKind::Sensitive => ResponseStatus::PsaErrorGenericError, + // FormatOne errors + Tss2ResponseCodeKind::Asymmetric => ResponseStatus::PsaErrorNotSupported, + Tss2ResponseCodeKind::Attributes => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::Hash => ResponseStatus::PsaErrorNotSupported, + Tss2ResponseCodeKind::Value => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::Hierarchy => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::KeySize => ResponseStatus::PsaErrorNotSupported, + Tss2ResponseCodeKind::Mgf => ResponseStatus::PsaErrorNotSupported, + Tss2ResponseCodeKind::Mode => ResponseStatus::PsaErrorNotSupported, + Tss2ResponseCodeKind::Type => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::Handle => ResponseStatus::PsaErrorInvalidHandle, + Tss2ResponseCodeKind::Kdf => ResponseStatus::PsaErrorNotSupported, + Tss2ResponseCodeKind::Range => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::AuthFail => ResponseStatus::PsaErrorNotPermitted, + Tss2ResponseCodeKind::Nonce => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::Pp => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::Scheme => ResponseStatus::PsaErrorNotSupported, + Tss2ResponseCodeKind::Size => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::Symmetric => ResponseStatus::PsaErrorNotSupported, + Tss2ResponseCodeKind::Tag => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::Selector => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::Insufficient => ResponseStatus::PsaErrorBufferTooSmall, + Tss2ResponseCodeKind::Signature => ResponseStatus::PsaErrorInvalidSignature, + Tss2ResponseCodeKind::Key => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::PolicyFail => ResponseStatus::PsaErrorNotPermitted, + Tss2ResponseCodeKind::Integrity => ResponseStatus::PsaErrorNotPermitted, + Tss2ResponseCodeKind::Ticket => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::ReservedBits => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::BadAuth => ResponseStatus::PsaErrorNotPermitted, + Tss2ResponseCodeKind::Expired => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::PolicyCc => ResponseStatus::PsaErrorGenericError, + Tss2ResponseCodeKind::Binding => ResponseStatus::PsaErrorGenericError, + Tss2ResponseCodeKind::Curve => ResponseStatus::PsaErrorNotSupported, + Tss2ResponseCodeKind::EccPoint => ResponseStatus::PsaErrorInvalidArgument, + // Warnings + Tss2ResponseCodeKind::ContextGap => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::ObjectMemory => { + ResponseStatus::PsaErrorInsufficientMemory + } + Tss2ResponseCodeKind::SessionMemory => { + ResponseStatus::PsaErrorInsufficientMemory + } + Tss2ResponseCodeKind::Memory => ResponseStatus::PsaErrorInsufficientMemory, + Tss2ResponseCodeKind::SessionHandles => { + ResponseStatus::PsaErrorInsufficientMemory + } + Tss2ResponseCodeKind::ObjectHandles => { + ResponseStatus::PsaErrorInsufficientMemory + } + Tss2ResponseCodeKind::Locality => ResponseStatus::PsaErrorInvalidArgument, + Tss2ResponseCodeKind::Yielded => ResponseStatus::PsaErrorGenericError, + Tss2ResponseCodeKind::Canceled => ResponseStatus::PsaErrorGenericError, + Tss2ResponseCodeKind::Testing => ResponseStatus::PsaErrorGenericError, + Tss2ResponseCodeKind::ReferenceH0 => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::ReferenceH1 => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::ReferenceH2 => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::ReferenceH3 => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::ReferenceH4 => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::ReferenceH5 => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::ReferenceH6 => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::ReferenceS0 => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::ReferenceS1 => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::ReferenceS2 => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::ReferenceS3 => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::ReferenceS4 => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::ReferenceS5 => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::ReferenceS6 => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::NvRate => ResponseStatus::PsaErrorBadState, + Tss2ResponseCodeKind::Lockout => ResponseStatus::PsaErrorHardwareFailure, + Tss2ResponseCodeKind::Retry => ResponseStatus::PsaErrorHardwareFailure, + Tss2ResponseCodeKind::NvUnavailable => ResponseStatus::PsaErrorHardwareFailure, + } + } else { + error!( + "Can not encode value {} into on of the possible TSS return values.", + e + ); + ResponseStatus::InvalidEncoding + } + } + } +} diff --git a/tests/per_provider/normal_tests/asym_sign_verify.rs b/tests/per_provider/normal_tests/asym_sign_verify.rs index 8aa8f226..002efffe 100644 --- a/tests/per_provider/normal_tests/asym_sign_verify.rs +++ b/tests/per_provider/normal_tests/asym_sign_verify.rs @@ -28,7 +28,7 @@ fn asym_sign_no_key() { let status = client .sign(key_name, HASH.to_vec()) .expect_err("Key should not exist."); - assert_eq!(status, ResponseStatus::KeyDoesNotExist); + assert_eq!(status, ResponseStatus::PsaErrorDoesNotExist); } #[test] @@ -39,7 +39,7 @@ fn asym_verify_no_key() { let status = client .verify(key_name, HASH.to_vec(), signature) .expect_err("Verification should have failed"); - assert_eq!(status, ResponseStatus::KeyDoesNotExist); + assert_eq!(status, ResponseStatus::PsaErrorDoesNotExist); } #[test] diff --git a/tests/per_provider/normal_tests/auth.rs b/tests/per_provider/normal_tests/auth.rs index 13ccba74..655b7842 100644 --- a/tests/per_provider/normal_tests/auth.rs +++ b/tests/per_provider/normal_tests/auth.rs @@ -43,7 +43,7 @@ fn delete_wrong_key() -> Result<()> { let status = client .destroy_key(key_name) .expect_err("Destroying key should have failed"); - assert_eq!(status, ResponseStatus::KeyDoesNotExist); + assert_eq!(status, ResponseStatus::PsaErrorDoesNotExist); Ok(()) } diff --git a/tests/per_provider/normal_tests/basic.rs b/tests/per_provider/normal_tests/basic.rs index faf2ba05..6e0ad1e9 100644 --- a/tests/per_provider/normal_tests/basic.rs +++ b/tests/per_provider/normal_tests/basic.rs @@ -141,5 +141,5 @@ fn wrong_provider_core() { let response_status = client .destroy_key(String::new()) .expect_err("Core Provider should not support DestroyKey operation!"); - assert_eq!(response_status, ResponseStatus::UnsupportedOperation); + assert_eq!(response_status, ResponseStatus::PsaErrorNotSupported); } diff --git a/tests/per_provider/normal_tests/create_destroy_key.rs b/tests/per_provider/normal_tests/create_destroy_key.rs index 77dacc66..dd13e40c 100644 --- a/tests/per_provider/normal_tests/create_destroy_key.rs +++ b/tests/per_provider/normal_tests/create_destroy_key.rs @@ -34,7 +34,7 @@ fn create_twice() -> Result<()> { let status = client .create_rsa_sign_key(key_name) .expect_err("A key with the same name can not be created twice."); - assert_eq!(status, ResponseStatus::KeyAlreadyExists); + assert_eq!(status, ResponseStatus::PsaErrorAlreadyExists); Ok(()) } @@ -47,7 +47,7 @@ fn destroy_without_create() { let status = client .destroy_key(key_name) .expect_err("The key should not already exist."); - assert_eq!(status, ResponseStatus::KeyDoesNotExist); + assert_eq!(status, ResponseStatus::PsaErrorDoesNotExist); } #[test] @@ -63,7 +63,7 @@ fn create_destroy_and_operation() -> Result<()> { let status = client .sign(key_name, hash) .expect_err("The key used by this operation should have been deleted."); - assert_eq!(status, ResponseStatus::KeyDoesNotExist); + assert_eq!(status, ResponseStatus::PsaErrorDoesNotExist); Ok(()) } diff --git a/tests/per_provider/normal_tests/export_public_key.rs b/tests/per_provider/normal_tests/export_public_key.rs index d274c681..9ff736e4 100644 --- a/tests/per_provider/normal_tests/export_public_key.rs +++ b/tests/per_provider/normal_tests/export_public_key.rs @@ -35,7 +35,7 @@ fn export_without_create() { let status = client .export_public_key(key_name) .expect_err("Key should not exist."); - assert_eq!(status, ResponseStatus::KeyDoesNotExist); + assert_eq!(status, ResponseStatus::PsaErrorDoesNotExist); } #[test] diff --git a/tests/per_provider/normal_tests/import_key.rs b/tests/per_provider/normal_tests/import_key.rs index ac3624cb..2dad3515 100644 --- a/tests/per_provider/normal_tests/import_key.rs +++ b/tests/per_provider/normal_tests/import_key.rs @@ -54,7 +54,7 @@ fn create_and_import_key() -> Result<()> { KEY_DATA.to_vec(), ) .expect_err("Key should have already existed"); - assert_eq!(status, ResponseStatus::KeyAlreadyExists); + assert_eq!(status, ResponseStatus::PsaErrorAlreadyExists); Ok(()) } @@ -78,7 +78,7 @@ fn import_key_twice() -> Result<()> { KEY_DATA.to_vec(), ) .expect_err("The key with the same name has already been created."); - assert_eq!(status, ResponseStatus::KeyAlreadyExists); + assert_eq!(status, ResponseStatus::PsaErrorAlreadyExists); Ok(()) } diff --git a/tests/per_provider/persistent_after.rs b/tests/per_provider/persistent_after.rs index 0f2c505b..e310cd28 100644 --- a/tests/per_provider/persistent_after.rs +++ b/tests/per_provider/persistent_after.rs @@ -51,6 +51,6 @@ fn should_have_been_deleted() { client .destroy_key(key_name) .expect_err("This key should have been destroyed."), - ResponseStatus::KeyDoesNotExist + ResponseStatus::PsaErrorDoesNotExist ); }