From 313804f79bba170f99a7b5415251f09df1dd5f87 Mon Sep 17 00:00:00 2001 From: wanghaixiang Date: Wed, 30 Jun 2021 12:33:53 +0800 Subject: [PATCH 1/3] add L0L1 huks 3.0 verson code Signed-off-by: wanghaixiang --- build/config.gni | 18 + frameworks/huks_standard/main/common/BUILD.gn | 6 +- .../main/common/include/hks_base_check.h | 2 +- .../main/common/include/hks_check_paramset.h | 6 +- .../main/common/include/hks_cmd_id.h | 2 +- .../main/common/include/hks_common_check.h | 6 +- .../{hks_crypto_hal_config.h => hks_config.h} | 260 +++-- .../main/common/include/hks_log.h | 14 + .../main/common/include/hks_mem.h.orig | 52 + .../main/common/include/hks_mem.h.rej | 10 + .../main/common/include/hks_type.h | 13 +- .../main/common/include/hks_type_inner.h | 22 + .../main/common/src/hks_base_check.c | 131 +-- .../main/common/src/hks_check_paramset.c | 235 +++-- .../main/common/src/hks_common_check.c | 3 - .../main/common/src/hks_crypto_adapter.c | 7 +- .../huks_standard/main/common/src/hks_param.c | 6 +- frameworks/huks_standard/main/core/BUILD.gn | 5 + .../main/core/include/hks_local_engine.h | 2 +- .../main/core/src/hks_local_engine.c | 48 +- .../huks_standard/main/crypto_engine/BUILD.gn | 5 + .../mbedtls/include/hks_crypto_ed25519.h | 50 + .../mbedtls/include/hks_mbedtls_aes.h | 46 + .../mbedtls/include/hks_mbedtls_bn.h | 38 + .../mbedtls/include/hks_mbedtls_common.h | 44 + .../mbedtls/include/hks_mbedtls_ecc.h | 59 ++ .../mbedtls/include/hks_mbedtls_ecdh.h | 39 + .../mbedtls/include/hks_mbedtls_ecdsa.h | 42 + .../mbedtls/include/hks_mbedtls_hash.h | 37 + .../mbedtls/include/hks_mbedtls_hmac.h | 38 + .../mbedtls/include/hks_mbedtls_kdf.h | 39 + .../mbedtls/include/hks_mbedtls_rsa.h | 57 ++ .../mbedtls/include/hks_mbedtls_x25519.h | 54 + .../mbedtls/src/hks_crypto_ed25519.c | 213 ++++ .../mbedtls/src/hks_mbedtls_aes.c | 366 +++++++ .../mbedtls/src/hks_mbedtls_bn.c | 100 ++ .../mbedtls/src/hks_mbedtls_common.c | 70 ++ .../mbedtls/src/hks_mbedtls_ecc.c | 285 ++++++ .../mbedtls/src/hks_mbedtls_ecdh.c | 114 +++ .../mbedtls/src/hks_mbedtls_ecdsa.c | 138 +++ .../mbedtls/src/hks_mbedtls_engine.c | 308 ++++++ .../mbedtls/src/hks_mbedtls_hash.c | 66 ++ .../mbedtls/src/hks_mbedtls_hmac.c | 57 ++ .../mbedtls/src/hks_mbedtls_kdf.c | 112 +++ .../mbedtls/src/hks_mbedtls_rsa.c | 402 ++++++++ .../mbedtls/src/hks_mbedtls_x25519.c | 875 +++++++++++++++++ .../main/crypto_engine/openssl/BUILD.gn | 5 + .../openssl/include/hks_openssl_engine.h | 2 +- .../openssl/src/hks_openssl_aes.c | 2 +- .../openssl/src/hks_openssl_engine.c | 2 +- .../openssl/src/hks_openssl_hash.c | 2 +- .../openssl/src/hks_openssl_hmac.c | 2 +- .../huks_standard/main/os_dependency/BUILD.gn | 5 + ..._client_service_ipc.h => hks_client_ipc.h} | 12 +- .../os_dependency/ipc/include/hks_ipc_check.h | 2 +- .../ipc/include/hks_ipc_serialization.h | 2 +- .../os_dependency/ipc/include/hks_ipc_slice.h | 2 +- .../os_dependency/ipc/include/hks_request.h | 2 +- .../ipc/src/hks_client_service_ipc.c | 7 +- .../ipc/src/hks_client_service_passthrough.c | 256 +++++ .../main/os_dependency/log/hks_log.c | 19 +- .../main/os_dependency/log/hks_log_lite.c | 81 ++ .../main/os_dependency/posix/hks_mem.c | 17 +- .../sysinfo/include/hks_get_process_info.h | 31 + .../sysinfo/include/hks_get_udid.h | 31 + .../src/hks_get_process_info_passthrough.c | 24 + .../os_dependency/sysinfo/src/hks_get_udid.c | 65 ++ interfaces/innerkits/huks_lite/BUILD.gn | 206 ++++ .../innerkits/huks_standard/main/BUILD.gn | 6 +- .../huks_standard/main/include/hks_api.h | 3 +- .../huks_standard/main/include/hks_param.h | 1 - .../huks_standard/main/include/hks_type.h | 14 +- .../main/include/hks_type_inner.h | 22 + .../huks_standard/main/src/hks_api.c | 118 ++- .../include/hks_test_api_performance.h | 3 +- .../test/unittest/include/hks_test_common.h | 1 + .../unittest/include/hks_test_curve25519.h | 2 + .../unittest/src/hks_test_file_operator.c | 2 + services/huks_standard/BUILD.gn | 6 +- .../huks_standard/huks_engine/main/BUILD.gn | 5 + .../huks_engine/main/core/BUILD.gn | 5 + .../huks_engine/main/core/include/hks_auth.h | 2 +- .../main/core/include/hks_core_service.h | 8 +- .../main/core/include/hks_keyblob.h | 2 +- .../huks_engine/main/core/include/hks_rkc.h | 37 + .../main/core/include/hks_rkc_rw.h | 113 +++ .../main/core/include/hks_upgrade_key_info.h | 31 + .../huks_engine/main/core/src/hks_auth.c | 5 +- .../main/core/src/hks_core_service.c | 137 ++- .../huks_engine/main/core/src/hks_keyblob.c | 21 +- .../main/core/src/hks_keyblob_lite.c | 539 ++++++++++ .../huks_engine/main/core/src/hks_rkc.c | 764 +++++++++++++++ .../huks_engine/main/core/src/hks_rkc_rw.c | 587 +++++++++++ .../main/core/src/hks_upgrade_key_info.c | 661 +++++++++++++ .../huks_engine/main/os_dependency/BUILD.gn | 5 + .../huks_standard/huks_service/main/BUILD.gn | 5 + .../huks_service/main/core/BUILD.gn | 5 + .../main/core/include/hks_access.h | 9 +- .../main/core/include/hks_client_check.h | 2 +- .../main/core/include/hks_client_service.h | 5 +- .../core/include/hks_client_service_adapter.h | 4 +- .../main/core/include/hks_file_operator.h | 43 +- .../main/core/include/hks_operation.h | 3 +- .../main/core/include/hks_storage.h | 18 +- .../main/core/include/hks_storage_adapter.h | 38 + .../core/include/hks_upgrade_storage_data.h | 33 + .../main/core/src/hks_client_check.c | 43 +- .../main/core/src/hks_client_service.c | 231 ++++- .../core/src/hks_client_service_adapter.c | 12 +- .../src/hks_client_service_adapter_lite.c | 506 ++++++++++ .../huks_service/main/core/src/hks_storage.c | 169 +++- .../main/core/src/hks_storage_adapter.c | 152 +++ .../main/core/src/hks_storage_lite.c | 921 ++++++++++++++++++ .../main/core/src/hks_upgrade_storage_data.c | 480 +++++++++ .../huks_service/main/os_dependency/BUILD.gn | 5 + .../main/os_dependency/idl/BUILD.gn | 5 + .../idl/ipc/hks_ipc_serialization.h | 2 +- .../os_dependency/idl/ipc/hks_ipc_service.h | 76 +- .../os_dependency/idl/ipc/hks_response.cpp | 2 +- .../main/os_dependency/idl/ipc/hks_response.h | 2 +- .../idl/passthrough/hks_passthrough_access.c | 39 +- .../os_dependency/posix/hks_file_operator.c | 46 +- .../posix/hks_file_operator_lite.c | 492 ++++++++++ test/BUILD.gn | 21 + test/unittest/src/common/BUILD.gn | 55 ++ test/unittest/src/common/hks_test_aes.c | 588 +++++++++++ .../src/common/hks_test_api_performance.c | 232 +++++ test/unittest/src/common/hks_test_cipher.c | 743 ++++++++++++++ test/unittest/src/common/hks_test_common.c | 736 ++++++++++++++ .../unittest/src/common/hks_test_curve25519.c | 467 +++++++++ .../src/common/hks_test_file_operator.c | 336 +++++++ test/unittest/src/common/hks_test_log.c | 65 ++ test/unittest/src/common/hks_test_mem.c | 29 + .../src/common/include/hks_aes_test.h | 25 + .../src/common/include/hks_agreement_test.h | 21 + .../src/common/include/hks_bn_exp_mod_test.h | 21 + .../src/common/include/hks_cipher_test.h | 43 + .../src/common/include/hks_curve25519_test.h | 27 + .../src/common/include/hks_delete_test.h | 21 + .../src/common/include/hks_derive_test.h | 23 + .../src/common/include/hks_exist_test.h | 21 + .../common/include/hks_generate_key_test.h | 21 + .../common/include/hks_generate_random_test.h | 21 + .../src/common/include/hks_hash_test.h | 21 + .../src/common/include/hks_mac_test.h | 23 + .../src/common/include/hks_modify_key_test.h | 21 + .../src/common/include/hks_others_test.h | 35 + .../common/include/hks_safe_cipher_key_test.h | 21 + .../include/hks_safe_compare_key_test.h | 21 + .../src/common/include/hks_test_aes.h | 36 + .../common/include/hks_test_api_performance.h | 60 ++ .../src/common/include/hks_test_cipher.h | 68 ++ .../src/common/include/hks_test_common.h | 422 ++++++++ .../src/common/include/hks_test_curve25519.h | 40 + .../common/include/hks_test_file_operator.h | 38 + .../src/common/include/hks_test_log.h | 61 ++ .../src/common/include/hks_test_mem.h | 32 + test/unittest/src/liteos_a_adapter/BUILD.gn | 60 ++ .../src/liteos_a_adapter/hks_aes_test.cpp | 95 ++ .../liteos_a_adapter/hks_agreement_test.cpp | 206 ++++ .../liteos_a_adapter/hks_bn_exp_mod_test.cpp | 144 +++ .../src/liteos_a_adapter/hks_cipher_test.cpp | 120 +++ .../liteos_a_adapter/hks_curve25519_test.cpp | 95 ++ .../src/liteos_a_adapter/hks_delete_test.cpp | 91 ++ .../src/liteos_a_adapter/hks_derive_test.cpp | 223 +++++ .../src/liteos_a_adapter/hks_exist_test.cpp | 94 ++ .../hks_generate_key_test.cpp | 130 +++ .../hks_generate_random_test.cpp | 87 ++ .../src/liteos_a_adapter/hks_hash_test.cpp | 114 +++ .../src/liteos_a_adapter/hks_mac_test.cpp | 203 ++++ .../liteos_a_adapter/hks_modify_key_test.cpp | 357 +++++++ .../src/liteos_a_adapter/hks_others_test.cpp | 143 +++ .../hks_safe_cipher_key_test.cpp | 116 +++ .../hks_safe_compare_key_test.cpp | 164 ++++ test/unittest/src/liteos_m_adapter/BUILD.gn | 52 + test/unittest/src/liteos_m_adapter/Test.json | 26 + .../src/liteos_m_adapter/hks_aes_test.c | 95 ++ .../src/liteos_m_adapter/hks_agreement_test.c | 216 ++++ .../liteos_m_adapter/hks_bn_exp_mod_test.c | 147 +++ .../src/liteos_m_adapter/hks_cipher_test.c | 131 +++ .../liteos_m_adapter/hks_curve25519_test.c | 134 +++ .../src/liteos_m_adapter/hks_delete_test.c | 95 ++ .../src/liteos_m_adapter/hks_derive_test.c | 225 +++++ .../src/liteos_m_adapter/hks_exist_test.c | 97 ++ .../liteos_m_adapter/hks_generate_key_test.c | 135 +++ .../hks_generate_random_test.c | 89 ++ .../src/liteos_m_adapter/hks_hash_test.c | 120 +++ .../src/liteos_m_adapter/hks_mac_test.c | 206 ++++ .../liteos_m_adapter/hks_modify_key_test.c | 367 +++++++ .../src/liteos_m_adapter/hks_others_test.c | 146 +++ .../hks_safe_cipher_key_test.c | 165 ++++ .../hks_safe_compare_key_test.c | 212 ++++ 192 files changed, 20685 insertions(+), 557 deletions(-) rename frameworks/huks_standard/main/common/include/{hks_crypto_hal_config.h => hks_config.h} (47%) mode change 100755 => 100644 create mode 100644 frameworks/huks_standard/main/common/include/hks_mem.h.orig create mode 100644 frameworks/huks_standard/main/common/include/hks_mem.h.rej create mode 100644 frameworks/huks_standard/main/common/include/hks_type_inner.h create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_crypto_ed25519.h create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_aes.h create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_bn.h create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_common.h create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_ecc.h create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_ecdh.h create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_ecdsa.h create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_hash.h create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_hmac.h create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_kdf.h create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_rsa.h create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_x25519.h create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_crypto_ed25519.c create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_aes.c create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_bn.c create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_common.c create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_ecc.c create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_ecdh.c create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_ecdsa.c create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_engine.c create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_hash.c create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_hmac.c create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_kdf.c create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_rsa.c create mode 100644 frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_x25519.c rename frameworks/huks_standard/main/os_dependency/ipc/include/{hks_client_service_ipc.h => hks_client_ipc.h} (91%) mode change 100755 => 100644 create mode 100644 frameworks/huks_standard/main/os_dependency/ipc/src/hks_client_service_passthrough.c create mode 100644 frameworks/huks_standard/main/os_dependency/log/hks_log_lite.c create mode 100644 frameworks/huks_standard/main/os_dependency/sysinfo/include/hks_get_process_info.h create mode 100644 frameworks/huks_standard/main/os_dependency/sysinfo/include/hks_get_udid.h create mode 100644 frameworks/huks_standard/main/os_dependency/sysinfo/src/hks_get_process_info_passthrough.c create mode 100644 frameworks/huks_standard/main/os_dependency/sysinfo/src/hks_get_udid.c create mode 100644 interfaces/innerkits/huks_lite/BUILD.gn create mode 100644 interfaces/innerkits/huks_standard/main/include/hks_type_inner.h create mode 100644 services/huks_standard/huks_engine/main/core/include/hks_rkc.h create mode 100644 services/huks_standard/huks_engine/main/core/include/hks_rkc_rw.h create mode 100644 services/huks_standard/huks_engine/main/core/include/hks_upgrade_key_info.h create mode 100644 services/huks_standard/huks_engine/main/core/src/hks_keyblob_lite.c create mode 100644 services/huks_standard/huks_engine/main/core/src/hks_rkc.c create mode 100644 services/huks_standard/huks_engine/main/core/src/hks_rkc_rw.c create mode 100644 services/huks_standard/huks_engine/main/core/src/hks_upgrade_key_info.c create mode 100644 services/huks_standard/huks_service/main/core/include/hks_storage_adapter.h create mode 100644 services/huks_standard/huks_service/main/core/include/hks_upgrade_storage_data.h create mode 100644 services/huks_standard/huks_service/main/core/src/hks_client_service_adapter_lite.c create mode 100644 services/huks_standard/huks_service/main/core/src/hks_storage_adapter.c create mode 100644 services/huks_standard/huks_service/main/core/src/hks_storage_lite.c create mode 100644 services/huks_standard/huks_service/main/core/src/hks_upgrade_storage_data.c create mode 100644 services/huks_standard/huks_service/main/os_dependency/posix/hks_file_operator_lite.c create mode 100644 test/BUILD.gn create mode 100644 test/unittest/src/common/BUILD.gn create mode 100644 test/unittest/src/common/hks_test_aes.c create mode 100644 test/unittest/src/common/hks_test_api_performance.c create mode 100644 test/unittest/src/common/hks_test_cipher.c create mode 100644 test/unittest/src/common/hks_test_common.c create mode 100644 test/unittest/src/common/hks_test_curve25519.c create mode 100644 test/unittest/src/common/hks_test_file_operator.c create mode 100644 test/unittest/src/common/hks_test_log.c create mode 100644 test/unittest/src/common/hks_test_mem.c create mode 100644 test/unittest/src/common/include/hks_aes_test.h create mode 100644 test/unittest/src/common/include/hks_agreement_test.h create mode 100644 test/unittest/src/common/include/hks_bn_exp_mod_test.h create mode 100644 test/unittest/src/common/include/hks_cipher_test.h create mode 100644 test/unittest/src/common/include/hks_curve25519_test.h create mode 100644 test/unittest/src/common/include/hks_delete_test.h create mode 100644 test/unittest/src/common/include/hks_derive_test.h create mode 100644 test/unittest/src/common/include/hks_exist_test.h create mode 100644 test/unittest/src/common/include/hks_generate_key_test.h create mode 100644 test/unittest/src/common/include/hks_generate_random_test.h create mode 100644 test/unittest/src/common/include/hks_hash_test.h create mode 100644 test/unittest/src/common/include/hks_mac_test.h create mode 100644 test/unittest/src/common/include/hks_modify_key_test.h create mode 100644 test/unittest/src/common/include/hks_others_test.h create mode 100644 test/unittest/src/common/include/hks_safe_cipher_key_test.h create mode 100644 test/unittest/src/common/include/hks_safe_compare_key_test.h create mode 100644 test/unittest/src/common/include/hks_test_aes.h create mode 100644 test/unittest/src/common/include/hks_test_api_performance.h create mode 100644 test/unittest/src/common/include/hks_test_cipher.h create mode 100644 test/unittest/src/common/include/hks_test_common.h create mode 100644 test/unittest/src/common/include/hks_test_curve25519.h create mode 100644 test/unittest/src/common/include/hks_test_file_operator.h create mode 100644 test/unittest/src/common/include/hks_test_log.h create mode 100644 test/unittest/src/common/include/hks_test_mem.h create mode 100644 test/unittest/src/liteos_a_adapter/BUILD.gn create mode 100644 test/unittest/src/liteos_a_adapter/hks_aes_test.cpp create mode 100644 test/unittest/src/liteos_a_adapter/hks_agreement_test.cpp create mode 100644 test/unittest/src/liteos_a_adapter/hks_bn_exp_mod_test.cpp create mode 100644 test/unittest/src/liteos_a_adapter/hks_cipher_test.cpp create mode 100644 test/unittest/src/liteos_a_adapter/hks_curve25519_test.cpp create mode 100644 test/unittest/src/liteos_a_adapter/hks_delete_test.cpp create mode 100644 test/unittest/src/liteos_a_adapter/hks_derive_test.cpp create mode 100644 test/unittest/src/liteos_a_adapter/hks_exist_test.cpp create mode 100644 test/unittest/src/liteos_a_adapter/hks_generate_key_test.cpp create mode 100644 test/unittest/src/liteos_a_adapter/hks_generate_random_test.cpp create mode 100644 test/unittest/src/liteos_a_adapter/hks_hash_test.cpp create mode 100644 test/unittest/src/liteos_a_adapter/hks_mac_test.cpp create mode 100644 test/unittest/src/liteos_a_adapter/hks_modify_key_test.cpp create mode 100644 test/unittest/src/liteos_a_adapter/hks_others_test.cpp create mode 100644 test/unittest/src/liteos_a_adapter/hks_safe_cipher_key_test.cpp create mode 100644 test/unittest/src/liteos_a_adapter/hks_safe_compare_key_test.cpp create mode 100644 test/unittest/src/liteos_m_adapter/BUILD.gn create mode 100644 test/unittest/src/liteos_m_adapter/Test.json create mode 100644 test/unittest/src/liteos_m_adapter/hks_aes_test.c create mode 100644 test/unittest/src/liteos_m_adapter/hks_agreement_test.c create mode 100644 test/unittest/src/liteos_m_adapter/hks_bn_exp_mod_test.c create mode 100644 test/unittest/src/liteos_m_adapter/hks_cipher_test.c create mode 100644 test/unittest/src/liteos_m_adapter/hks_curve25519_test.c create mode 100644 test/unittest/src/liteos_m_adapter/hks_delete_test.c create mode 100644 test/unittest/src/liteos_m_adapter/hks_derive_test.c create mode 100644 test/unittest/src/liteos_m_adapter/hks_exist_test.c create mode 100644 test/unittest/src/liteos_m_adapter/hks_generate_key_test.c create mode 100644 test/unittest/src/liteos_m_adapter/hks_generate_random_test.c create mode 100644 test/unittest/src/liteos_m_adapter/hks_hash_test.c create mode 100644 test/unittest/src/liteos_m_adapter/hks_mac_test.c create mode 100644 test/unittest/src/liteos_m_adapter/hks_modify_key_test.c create mode 100644 test/unittest/src/liteos_m_adapter/hks_others_test.c create mode 100644 test/unittest/src/liteos_m_adapter/hks_safe_cipher_key_test.c create mode 100644 test/unittest/src/liteos_m_adapter/hks_safe_compare_key_test.c diff --git a/build/config.gni b/build/config.gni index cd700468..e92699ec 100755 --- a/build/config.gni +++ b/build/config.gni @@ -18,4 +18,22 @@ declare_args() { # cut abilities for authentication disable_authenticate = false + + # if HUKS use mbedlts engine + use_mbedlts = true + + # mbedtls path when HUKS using mbedlts engine + mbedtls_path = "//third_party/mbedtls/include" + + # whether use lite storeage + use_lite_storage = false + + # whether use hardware root key + use_hardware_root_key = false + + # whether use hks config file + hks_config_file = "" + + # whether huks enable log + enable_huks_log = false } diff --git a/frameworks/huks_standard/main/common/BUILD.gn b/frameworks/huks_standard/main/common/BUILD.gn index a25331e7..33391f99 100644 --- a/frameworks/huks_standard/main/common/BUILD.gn +++ b/frameworks/huks_standard/main/common/BUILD.gn @@ -20,7 +20,11 @@ config("huks_config") { ohos_static_library("libhuks_common_standard_static") { subsystem_name = "security" part_name = "huks_standard" - + defines = [ + "L2_STANDARD", + "_HARDWARE_ROOT_KEY_", + "_HUKS_LOG_ENABLE_", + ] public_configs = [ ":huks_config" ] # Share include files for other gn when deps. diff --git a/frameworks/huks_standard/main/common/include/hks_base_check.h b/frameworks/huks_standard/main/common/include/hks_base_check.h index a108fc14..106db9d7 100644 --- a/frameworks/huks_standard/main/common/include/hks_base_check.h +++ b/frameworks/huks_standard/main/common/include/hks_base_check.h @@ -17,7 +17,7 @@ #define HKS_BASE_CHECK_H #include "hks_param.h" -#include "hks_type.h" +#include "hks_type_inner.h" enum CheckKeyType { HKS_CHECK_TYPE_GEN_KEY, diff --git a/frameworks/huks_standard/main/common/include/hks_check_paramset.h b/frameworks/huks_standard/main/common/include/hks_check_paramset.h index e6792e72..d708f034 100755 --- a/frameworks/huks_standard/main/common/include/hks_check_paramset.h +++ b/frameworks/huks_standard/main/common/include/hks_check_paramset.h @@ -17,17 +17,17 @@ #define HKS_CHECK_PARAMSET_H #include "hks_param.h" -#include "hks_type.h" +#include "hks_type_inner.h" #ifdef __cplusplus extern "C" { #endif int32_t HksCoreCheckGenKeyParams(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, - const struct HksBlob *keyIn, struct HksBlob *keyOut); + const struct HksBlob *keyIn, const struct HksBlob *keyOut); int32_t HksCoreCheckImportKeyParams(const struct HksBlob *keyAlias, const struct HksBlob *key, - const struct HksParamSet *paramSet, struct HksBlob *keyOut); + const struct HksParamSet *paramSet, const struct HksBlob *keyOut); int32_t HksCoreCheckSignVerifyParams(uint32_t cmdId, const struct HksBlob *key, const struct HksParamSet *paramSet, const struct HksBlob *srcData, const struct HksBlob *signature); diff --git a/frameworks/huks_standard/main/common/include/hks_cmd_id.h b/frameworks/huks_standard/main/common/include/hks_cmd_id.h index 5e972c1f..89606c1b 100644 --- a/frameworks/huks_standard/main/common/include/hks_cmd_id.h +++ b/frameworks/huks_standard/main/common/include/hks_cmd_id.h @@ -16,7 +16,7 @@ #ifndef HKS_CMD_ID_H #define HKS_CMD_ID_H -#include "hks_type.h" +#include "hks_type_inner.h" enum HksCmdId { HKS_CMD_ID_INVALID = 0x0, diff --git a/frameworks/huks_standard/main/common/include/hks_common_check.h b/frameworks/huks_standard/main/common/include/hks_common_check.h index 35064a1e..44f16ba5 100644 --- a/frameworks/huks_standard/main/common/include/hks_common_check.h +++ b/frameworks/huks_standard/main/common/include/hks_common_check.h @@ -17,7 +17,7 @@ #define HKS_COMMON_CHECK_H #include "hks_param.h" -#include "hks_type.h" +#include "hks_type_inner.h" #define HKS_DIGEST_SHA256_LEN 32 #define HKS_DIGEST_SHA384_LEN 48 @@ -51,10 +51,8 @@ int32_t HksGetDigestLen(uint32_t digest, uint32_t *digestLen); int32_t HksCheckAesAeMode(const struct HksParamSet *paramSet, bool *isAes, bool *isAeMode); -int32_t HksGetProcessName(char **processName); - #ifdef __cplusplus } #endif -#endif +#endif /* HKS_COMMON_CHECK_H */ diff --git a/frameworks/huks_standard/main/common/include/hks_crypto_hal_config.h b/frameworks/huks_standard/main/common/include/hks_config.h old mode 100755 new mode 100644 similarity index 47% rename from frameworks/huks_standard/main/common/include/hks_crypto_hal_config.h rename to frameworks/huks_standard/main/common/include/hks_config.h index 1798ab1c..c8fb50ce --- a/frameworks/huks_standard/main/common/include/hks_crypto_hal_config.h +++ b/frameworks/huks_standard/main/common/include/hks_config.h @@ -1,100 +1,160 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * 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. - */ - -#ifndef HKS_CRYPTO_HAL_CONFIG_H -#define HKS_CRYPTO_HAL_CONFIG_H - -/* AES */ -#define HKS_SUPPORT_AES_C -#define HKS_SUPPORT_AES_GENERATE_KEY -#define HKS_SUPPORT_AES_CBC_NOPADDING -#define HKS_SUPPORT_AES_CBC_PKCS7 -#define HKS_SUPPORT_AES_GCM -#define HKS_SUPPORT_AES_CCM - -/* BN */ -#define HKS_SUPPORT_BN_C - -/* ECC */ -#define HKS_SUPPORT_ECC_C -#define HKS_SUPPORT_ECC_GENERATE_KEY -#define HKS_SUPPORT_ECC_GET_PUBLIC_KEY -#define HKS_SUPPORT_ECDH_C -#define HKS_SUPPORT_ECDSA_C - -/* ED25519 */ -#define HKS_SUPPORT_ED25519_C -#define HKS_SUPPORT_ED25519_GENERATE_KEY -#define HKS_SUPPORT_ED25519_SIGN_VERIFY -#define HKS_SUPPORT_ED2519_GET_PUBLIC_KEY - -/* HASH */ -#define HKS_SUPPORT_HASH_C - -/* HMAC */ -#define HKS_SUPPORT_HMAC_C - -/* KDF */ -#define HKS_SUPPORT_KDF_C -#define HKS_SUPPORT_KDF_PBKDF2 -#define HKS_SUPPORT_KDF_HKDF - -/* RSA */ -#define HKS_SUPPORT_RSA_C -#define HKS_SUPPORT_RSA_GENERATE_KEY -#define HKS_SUPPORT_RSA_CRYPT -#define HKS_SUPPORT_RSA_SIGN_VERIFY -#define HKS_SUPPORT_RSA_GET_PUBLIC_KEY - -/* X25519 */ -#define HKS_SUPPORT_X25519_C -#define HKS_SUPPORT_X25519_GENERATE_KEY -#define HKS_SUPPORT_X25519_AGREE_KEY -#define HKS_SUPPORT_X25519_GET_PUBLIC_KEY -#define HKS_SUPPORT_ED25519_TO_X25519 -#define HKS_SUPPORT_HASH_TO_POINT - -/* HksGetKeyInfoList */ -#define HKS_SUPPORT_GET_KEY_INFO_LIST - -#if defined(HKS_SUPPORT_ECC_C) || defined(HKS_SUPPORT_ED25519_C) || defined(HKS_SUPPORT_RSA_C) -#define HKS_SUPPORT_SIGN_VERIFY -#endif - -#if defined(HKS_SUPPORT_AES_C) || defined(HKS_SUPPORT_RSA_C) -#define HKS_SUPPORT_CIPHER -#endif - -#if defined(HKS_SUPPORT_ECC_C) || defined(HKS_SUPPORT_RSA_C) || \ - defined(HKS_SUPPORT_ED25519_C) || defined(HKS_SUPPORT_X25519_C) || \ - defined(HKS_SUPPORT_AES_C) -#define HKS_SUPPORT_IMPORT -#endif - -#if defined(HKS_SUPPORT_ECC_C) || defined(HKS_SUPPORT_RSA_C) || \ - defined(HKS_SUPPORT_ED25519_C) || defined(HKS_SUPPORT_X25519_C) -#define HKS_SUPPORT_EXPORT -#endif - -#define HKS_SUPPORT_GENERATE_KEY -#define HKS_SUPPORT_GENERATE_RANDOM -#define HKS_SUPPORT_AGREE_KEY -#define HKS_SUPPORT_DERIVE_KEY -#define HKS_SUPPORT_MAC -#define HKS_SUPPORT_HASH -#define HKS_SUPPORT_BN_EXP_MOD - -#endif - +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_CONFIG_H +#define HKS_CONFIG_H + +#ifdef HKS_SUPPORT_PRODUCT_GT_WATCH +#define HKS_SUPPORT_LITE_HEAP +#endif + +#ifdef HKS_SUPPORT_PRODUCT_WINDOWS_PC +#define HKS_SUPPORT_UPGRADE_STORAGE_DATA +#endif + +/* AES */ +#define HKS_SUPPORT_AES_C +#define HKS_SUPPORT_AES_GENERATE_KEY +#define HKS_SUPPORT_AES_CBC_NOPADDING +#define HKS_SUPPORT_AES_CBC_PKCS7 +#define HKS_SUPPORT_AES_GCM +#ifdef HKS_SUPPORT_PRODUCT_GT_WATCH +#define HKS_SUPPORT_AES_CCM +#endif + +#define HKS_SUPPORT_POSIX + +/* BN */ +#define HKS_SUPPORT_BN_C + +/* ECC */ +#ifndef HKS_SUPPORT_PRODUCT_GT_WATCH +#define HKS_SUPPORT_ECC_C +#define HKS_SUPPORT_ECC_GENERATE_KEY +#define HKS_SUPPORT_ECC_GET_PUBLIC_KEY +#define HKS_SUPPORT_ECDH_C +#define HKS_SUPPORT_ECDSA_C +#endif + +/* ED25519 */ +#ifndef HKS_SUPPORT_PRODUCT_GT_WATCH +#define HKS_SUPPORT_ED25519_C +#define HKS_SUPPORT_ED25519_GENERATE_KEY +#define HKS_SUPPORT_ED25519_SIGN_VERIFY +#define HKS_SUPPORT_ED2519_GET_PUBLIC_KEY +#endif + +/* HASH */ +#define HKS_SUPPORT_HASH_C + +/* HMAC */ +#define HKS_SUPPORT_HMAC_C + +/* KDF */ +#define HKS_SUPPORT_KDF_C +#define HKS_SUPPORT_KDF_PBKDF2 +#define HKS_SUPPORT_KDF_HKDF + +/* RSA */ +#ifndef HKS_SUPPORT_PRODUCT_GT_WATCH +#define HKS_SUPPORT_RSA_C +#define HKS_SUPPORT_RSA_GENERATE_KEY +#define HKS_SUPPORT_RSA_CRYPT +#define HKS_SUPPORT_RSA_SIGN_VERIFY +#define HKS_SUPPORT_RSA_GET_PUBLIC_KEY +#endif + +/* X25519 */ +#define HKS_SUPPORT_X25519_C +#define HKS_SUPPORT_X25519_GENERATE_KEY +#define HKS_SUPPORT_X25519_AGREE_KEY +#define HKS_SUPPORT_X25519_GET_PUBLIC_KEY + +#ifdef L2_STANDARD +#define HKS_SUPPORT_AGREE_TO_SAVE +#endif + +#ifdef HKS_SUPPORT_AGREE_TO_SAVE /* default: disable */ +#define HKS_SUPPORT_ED25519_TO_X25519 +#endif + +#if defined(CHIP_VER_Hi3861) +#undef HKS_SUPPORT_RSA_C +#undef HKS_SUPPORT_ECC_C +#endif + +#if defined(HKS_SUPPORT_AES_GENERATE_KEY) || defined(HKS_SUPPORT_ECC_GENERATE_KEY) || \ + defined(HKS_SUPPORT_ED25519_GENERATE_KEY) || defined(HKS_SUPPORT_RSA_GENERATE_KEY) || \ + defined(HKS_SUPPORT_X25519_GENERATE_KEY) +#define HKS_SUPPORT_API_GENERATE_KEY +#define HKS_SUPPORT_API_DELETE_KEY +#define HKS_SUPPORT_API_GET_KEY_PARAM_SET +#define HKS_SUPPORT_API_KEY_EXIST +#endif + +#if defined(HKS_SUPPORT_ECC_C) || defined(HKS_SUPPORT_RSA_C) || \ + defined(HKS_SUPPORT_ED25519_C) || defined(HKS_SUPPORT_X25519_C) || \ + defined(HKS_SUPPORT_AES_C) +#define HKS_SUPPORT_API_IMPORT +#endif + +#if defined(HKS_SUPPORT_ECC_C) || defined(HKS_SUPPORT_RSA_C) || \ + defined(HKS_SUPPORT_ED25519_C) || defined(HKS_SUPPORT_X25519_C) +#define HKS_SUPPORT_API_EXPORT +#endif + +#define HKS_SUPPORT_API_GENERATE_RANDOM + +#if defined(HKS_SUPPORT_ECDSA_C) || defined(HKS_SUPPORT_ED25519_SIGN_VERIFY) || \ + defined(HKS_SUPPORT_RSA_SIGN_VERIFY) +#define HKS_SUPPORT_API_SIGN_VERIFY +#endif + +#if defined(HKS_SUPPORT_AES_C) || defined(HKS_SUPPORT_RSA_CRYPT) +#define HKS_SUPPORT_API_CIPHER +#endif + +#if defined(HKS_SUPPORT_X25519_AGREE_KEY) || defined(HKS_SUPPORT_ECDH_C) +#define HKS_SUPPORT_API_AGREE_KEY +#endif + +#ifdef HKS_SUPPORT_KDF_C +#define HKS_SUPPORT_API_DERIVE_KEY +#endif + +#ifdef HKS_SUPPORT_HMAC_C +#define HKS_SUPPORT_API_MAC +#endif + +#ifdef HKS_SUPPORT_HASH_C +#define HKS_SUPPORT_API_HASH +#endif + +#ifdef HKS_SUPPORT_BN_C +#define HKS_SUPPORT_API_BN_EXP_MOD +#endif + +#ifndef HKS_SUPPORT_LITE_HEAP +#define HKS_SUPPORT_API_GET_KEY_INFO_LIST +#endif + +#if defined(HKS_SUPPORT_PRODUCT_ROUTER) || defined(HKS_SUPPORT_PRODUCT_CPE) +#define HKS_SUPPORT_API_ATTEST_KEY +#define HKS_SUPPORT_API_GET_CERTIFICATE_CHAIN +#define HKS_SUPPORT_API_WRAP_KEY +#define HKS_SUPPORT_API_UNWRAP_KEY +#endif + +#endif /* HKS_CONFIG_H */ diff --git a/frameworks/huks_standard/main/common/include/hks_log.h b/frameworks/huks_standard/main/common/include/hks_log.h index af30b8f2..c10535be 100644 --- a/frameworks/huks_standard/main/common/include/hks_log.h +++ b/frameworks/huks_standard/main/common/include/hks_log.h @@ -18,6 +18,13 @@ #include "hks_type.h" +#ifdef _HUKS_LOG_ENABLE_ +#undef LOG_TAG +#define LOG_TAG "HUKS" +#undef LOG_DOMAIN +#define LOG_DOMAIN 0xD002F00 /* Security subsystem's domain id */ +#endif + enum HksLogLevel { HKS_LOG_LEVEL_I, HKS_LOG_LEVEL_E, @@ -29,12 +36,19 @@ enum HksLogLevel { extern "C" { #endif +#ifdef _HUKS_LOG_ENABLE_ void HksLog(uint32_t logLevel, const char *funcName, uint32_t lineNo, const char *format, ...); #define HKS_LOG_I(...) HksLog(HKS_LOG_LEVEL_I, __func__, __LINE__, __VA_ARGS__) #define HKS_LOG_W(...) HksLog(HKS_LOG_LEVEL_W, __func__, __LINE__, __VA_ARGS__) #define HKS_LOG_E(...) HksLog(HKS_LOG_LEVEL_E, __func__, __LINE__, __VA_ARGS__) #define HKS_LOG_D(...) HksLog(HKS_LOG_LEVEL_D, __func__, __LINE__, __VA_ARGS__) +#else +#define HKS_LOG_I(...) +#define HKS_LOG_W(...) +#define HKS_LOG_E(...) +#define HKS_LOG_D(...) +#endif #ifdef __cplusplus } diff --git a/frameworks/huks_standard/main/common/include/hks_mem.h.orig b/frameworks/huks_standard/main/common/include/hks_mem.h.orig new file mode 100644 index 00000000..c0f7569a --- /dev/null +++ b/frameworks/huks_standard/main/common/include/hks_mem.h.orig @@ -0,0 +1,52 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_MEM_H +#define HKS_MEM_H + +#include +#include + +#ifdef __cplusplus +extern "C" { +#endif + +void *HksMalloc(size_t size); +void HksFree(void *ptr); +int32_t HksMemCmp(const void *ptr1, const void *ptr2, uint32_t size); + +#define SELF_FREE_PTR(PTR, FREE_FUNC) \ +{ \ + if ((PTR) != NULL) { \ + FREE_FUNC(PTR); \ + (PTR) = NULL; \ + } \ +} + +#define HKS_FREE_PTR(p) SELF_FREE_PTR(p, HksFree) + +#define HKS_FREE_BLOB(blob) do { \ + if ((blob).data != NULL) { \ + HksFree((blob).data); \ + (blob).data = NULL; \ + } \ + (blob).size = 0; \ +} while (0) + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_MEM_H */ diff --git a/frameworks/huks_standard/main/common/include/hks_mem.h.rej b/frameworks/huks_standard/main/common/include/hks_mem.h.rej new file mode 100644 index 00000000..de5643ec --- /dev/null +++ b/frameworks/huks_standard/main/common/include/hks_mem.h.rej @@ -0,0 +1,10 @@ +--- security_huks/frameworks/huks_standard/main/common/include/hks_mem.h 2021-06-10 14:20:35.000000000 +0800 ++++ security_huks_new/frameworks/huks_standard/main/common/include/hks_mem.h 2021-06-25 16:59:51.737430980 +0800 +@@ -16,6 +16,7 @@ + #ifndef HKS_MEM_H + #define HKS_MEM_H + ++#include + #include + + #ifdef __cplusplus diff --git a/frameworks/huks_standard/main/common/include/hks_type.h b/frameworks/huks_standard/main/common/include/hks_type.h index 20475a98..dfb1d58a 100755 --- a/frameworks/huks_standard/main/common/include/hks_type.h +++ b/frameworks/huks_standard/main/common/include/hks_type.h @@ -20,19 +20,13 @@ #include #include -#include "securec.h" - #ifdef __cplusplus extern "C" { #endif #ifndef HKS_API_PUBLIC - #if defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__) - #ifdef HKS_DLL_EXPORT - #define HKS_API_EXPORT __declspec(dllexport) - #else - #define HKS_API_EXPORT __declspec(dllimport) - #endif + #if defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__) || defined(__ICCARM__) /* __ICCARM__ for iar */ + #define HKS_API_EXPORT #else #define HKS_API_EXPORT __attribute__ ((visibility("default"))) #endif @@ -211,6 +205,8 @@ enum HksErrorCode { HKS_ERROR_IPC_INIT_FAIL = -33, HKS_ERROR_IPC_DLOPEN_FAIL = -34, HKS_ERROR_EFUSE_READ_FAIL = -35, + HKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST = -36, + HKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL = -37, HKS_ERROR_CHECK_GET_ALG_FAIL = -100, HKS_ERROR_CHECK_GET_KEY_SIZE_FAIL = -101, @@ -282,6 +278,7 @@ enum HksTag { HKS_TAG_KEY_GENERATE_TYPE = HKS_TAG_TYPE_UINT | 15, /* choose from enum HksKeyGenerateType */ HKS_TAG_DERIVE_MAIN_KEY = HKS_TAG_TYPE_BYTES | 16, HKS_TAG_DERIVE_FACTOR = HKS_TAG_TYPE_BYTES | 17, + HKS_TAG_DERIVE_ALG = HKS_TAG_TYPE_UINT | 18, HKS_TAG_AGREE_ALG = HKS_TAG_TYPE_UINT | 19, HKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS = HKS_TAG_TYPE_BOOL | 20, HKS_TAG_AGREE_PRIVATE_KEY_ALIAS = HKS_TAG_TYPE_BYTES | 21, diff --git a/frameworks/huks_standard/main/common/include/hks_type_inner.h b/frameworks/huks_standard/main/common/include/hks_type_inner.h new file mode 100644 index 00000000..36ce5c41 --- /dev/null +++ b/frameworks/huks_standard/main/common/include/hks_type_inner.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_TYPE_INNER_H +#define HKS_TYPE_INNER_H + +#include "hks_type.h" +#include "securec.h" + +#endif /* HKS_TYPE_INNER_H */ diff --git a/frameworks/huks_standard/main/common/src/hks_base_check.c b/frameworks/huks_standard/main/common/src/hks_base_check.c index 45eaefe4..3906e080 100755 --- a/frameworks/huks_standard/main/common/src/hks_base_check.c +++ b/frameworks/huks_standard/main/common/src/hks_base_check.c @@ -13,17 +13,26 @@ * limitations under the License. */ +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + #include "hks_base_check.h" #include "hks_cmd_id.h" #include "hks_common_check.h" -#ifdef HKS_HAL_ENGINE_CONFIG_FILE -#include HKS_HAL_ENGINE_CONFIG_FILE -#else -#include "hks_crypto_hal_config.h" -#endif #include "hks_log.h" +#ifdef _CUT_AUTHENTICATE_ +#undef HKS_SUPPORT_RSA_C +#undef HKS_SUPPORT_ECC_C +#undef HKS_SUPPORT_ECDH_C +#undef HKS_SUPPORT_X25519_C +#undef HKS_SUPPORT_ED25519_C +#endif + #define HKS_AES_CBC_IV_LEN 16 #define HKS_AES_CCM_AAD_LEN_MIN 4 #define HKS_AES_CCM_NONCE_LEN_MIN 7 @@ -231,6 +240,7 @@ static const struct ExpectParamsValuesChecker g_expectCurve25519Params[] = { }; #endif +#ifndef _CUT_AUTHENTICATE_ #ifndef _STORAGE_LITE_ static int32_t CheckAndGetKeySize(const struct HksBlob *key, const uint32_t *expectKeySize, uint32_t expectCnt, uint32_t *keySize) @@ -283,58 +293,6 @@ static int32_t CheckAndGetKeySize(const struct HksBlob *key, const uint32_t *exp } #endif -static int32_t GetInputParams(const struct HksParamSet *paramSet, struct ParamsValues *inputParams) -{ - int32_t ret = HKS_SUCCESS; - struct HksParam *checkParam = NULL; - if (inputParams->keyLen.needCheck) { - ret = HksGetParam(paramSet, HKS_TAG_KEY_SIZE, &checkParam); - if (ret != HKS_SUCCESS) { - HKS_LOG_E("get Param get tag:0x%x failed", HKS_TAG_KEY_SIZE); - return HKS_ERROR_CHECK_GET_KEY_SIZE_FAIL; - } - inputParams->keyLen.value = checkParam->uint32Param; - } - - if (inputParams->padding.needCheck) { - ret = HksGetParam(paramSet, HKS_TAG_PADDING, &checkParam); - if (ret != HKS_SUCCESS) { - HKS_LOG_E("get Param get tag:0x%x failed", HKS_TAG_PADDING); - return HKS_ERROR_CHECK_GET_PADDING_FAIL; - } - inputParams->padding.value = checkParam->uint32Param; - } - - if (inputParams->purpose.needCheck) { - ret = HksGetParam(paramSet, HKS_TAG_PURPOSE, &checkParam); - if (ret != HKS_SUCCESS) { - HKS_LOG_E("get Param get tag:0x%x failed", HKS_TAG_PURPOSE); - return HKS_ERROR_CHECK_GET_PURPOSE_FAIL; - } - inputParams->purpose.value = checkParam->uint32Param; - } - - if (inputParams->digest.needCheck) { - ret = HksGetParam(paramSet, HKS_TAG_DIGEST, &checkParam); - if (ret != HKS_SUCCESS) { - HKS_LOG_E("get Param get tag:0x%x failed", HKS_TAG_DIGEST); - return HKS_ERROR_CHECK_GET_DIGEST_FAIL; - } - inputParams->digest.value = checkParam->uint32Param; - } - - if (inputParams->mode.needCheck) { - ret = HksGetParam(paramSet, HKS_TAG_BLOCK_MODE, &checkParam); - if (ret != HKS_SUCCESS) { - HKS_LOG_E("get Param get tag:0x%x failed", HKS_TAG_BLOCK_MODE); - return HKS_ERROR_CHECK_GET_MODE_FAIL; - } - inputParams->mode.value = checkParam->uint32Param; - } - - return ret; -} - static int32_t CheckPurposeUnique(uint32_t inputPurpose) { /* key usage uniqueness */ @@ -395,6 +353,60 @@ static int32_t CheckPurposeValid(uint32_t alg, uint32_t inputPurpose) return HKS_SUCCESS; } +#endif /* _CUT_AUTHENTICATE_ */ + +static int32_t GetInputParams(const struct HksParamSet *paramSet, struct ParamsValues *inputParams) +{ + int32_t ret = HKS_SUCCESS; + struct HksParam *checkParam = NULL; + if (inputParams->keyLen.needCheck) { + ret = HksGetParam(paramSet, HKS_TAG_KEY_SIZE, &checkParam); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get Param get tag:0x%x failed", HKS_TAG_KEY_SIZE); + return HKS_ERROR_CHECK_GET_KEY_SIZE_FAIL; + } + inputParams->keyLen.value = checkParam->uint32Param; + } + + if (inputParams->padding.needCheck) { + ret = HksGetParam(paramSet, HKS_TAG_PADDING, &checkParam); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get Param get tag:0x%x failed", HKS_TAG_PADDING); + return HKS_ERROR_CHECK_GET_PADDING_FAIL; + } + inputParams->padding.value = checkParam->uint32Param; + } + + if (inputParams->purpose.needCheck) { + ret = HksGetParam(paramSet, HKS_TAG_PURPOSE, &checkParam); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get Param get tag:0x%x failed", HKS_TAG_PURPOSE); + return HKS_ERROR_CHECK_GET_PURPOSE_FAIL; + } + inputParams->purpose.value = checkParam->uint32Param; + } + + if (inputParams->digest.needCheck) { + ret = HksGetParam(paramSet, HKS_TAG_DIGEST, &checkParam); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get Param get tag:0x%x failed", HKS_TAG_DIGEST); + return HKS_ERROR_CHECK_GET_DIGEST_FAIL; + } + inputParams->digest.value = checkParam->uint32Param; + } + + if (inputParams->mode.needCheck) { + ret = HksGetParam(paramSet, HKS_TAG_BLOCK_MODE, &checkParam); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get Param get tag:0x%x failed", HKS_TAG_BLOCK_MODE); + return HKS_ERROR_CHECK_GET_MODE_FAIL; + } + inputParams->mode.value = checkParam->uint32Param; + } + + return ret; +} + static int32_t InitInputParams(enum CheckKeyType checkType, struct ParamsValues *inputParams, const struct ParamsValuesChecker *checkSet, uint32_t checkSetSize) @@ -859,6 +871,7 @@ int32_t HksCheckValue(uint32_t inputValue, const uint32_t *expectValues, uint32_ return ret; } +#ifndef _CUT_AUTHENTICATE_ int32_t HksCheckGenKeyPurpose(uint32_t alg, uint32_t inputPurpose) { int32_t ret = CheckPurposeUnique(inputPurpose); @@ -894,6 +907,7 @@ int32_t HksGetKeySize(uint32_t alg, const struct HksBlob *key, uint32_t *keySize return HKS_ERROR_INVALID_ALGORITHM; } } +#endif /* _CUT_AUTHENTICATE_ */ int32_t HksGetInputParmasByAlg(uint32_t alg, enum CheckKeyType checkType, const struct HksParamSet *paramSet, struct ParamsValues *inputParams) @@ -963,6 +977,7 @@ int32_t HksCheckFixedParams(uint32_t alg, enum CheckKeyType checkType, const str return ret; } +#ifndef _CUT_AUTHENTICATE_ int32_t HksCheckGenKeyMutableParams(uint32_t alg, const struct ParamsValues *inputParams) { int32_t ret = HksCheckGenKeyPurpose(alg, inputParams->purpose.value); @@ -997,6 +1012,7 @@ int32_t HksCheckGenKeyMutableParams(uint32_t alg, const struct ParamsValues *inp return ret; } + int32_t HksCheckSignature(uint32_t cmdId, uint32_t alg, const struct HksBlob *key, const struct HksBlob *signature) { uint32_t keySize = 0; @@ -1056,6 +1072,7 @@ int32_t HksCheckSignVerifyMutableParams(uint32_t cmdId, uint32_t alg, const stru } return HKS_SUCCESS; } +#endif /* _CUT_AUTHENTICATE_ */ int32_t HksCheckCipherMutableParams(uint32_t cmdId, uint32_t alg, const struct ParamsValues *inputParams) { diff --git a/frameworks/huks_standard/main/common/src/hks_check_paramset.c b/frameworks/huks_standard/main/common/src/hks_check_paramset.c index 6507e01e..afdbfc4d 100755 --- a/frameworks/huks_standard/main/common/src/hks_check_paramset.c +++ b/frameworks/huks_standard/main/common/src/hks_check_paramset.c @@ -13,20 +13,31 @@ * limitations under the License. */ -#include "hks_check_paramset.h" - -#include "hks_common_check.h" -#ifdef HKS_HAL_ENGINE_CONFIG_FILE -#include HKS_HAL_ENGINE_CONFIG_FILE +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE #else -#include "hks_crypto_hal_config.h" +#include "hks_config.h" #endif + +#include "hks_check_paramset.h" + #include "hks_base_check.h" +#include "hks_common_check.h" #include "hks_log.h" +#ifdef _CUT_AUTHENTICATE_ +#undef HKS_SUPPORT_HASH_C +#undef HKS_SUPPORT_RSA_C +#undef HKS_SUPPORT_ECC_C +#undef HKS_SUPPORT_X25519_C +#undef HKS_SUPPORT_ED25519_C +#undef HKS_SUPPORT_KDF_PBKDF2 +#endif /* _CUT_AUTHENTICATE_ */ + #define HKS_DEFAULT_PBKDF2_ITERATION 1000 #define HKS_DEFAULT_PBKDF2_SALT_SIZE 16 +#ifndef _CUT_AUTHENTICATE_ static uint32_t g_genKeyAlg[] = { #ifdef HKS_SUPPORT_RSA_C HKS_ALG_RSA, @@ -71,14 +82,7 @@ static uint32_t g_cipherAlg[] = { HKS_ALG_AES, #endif }; - -static uint32_t g_cipherAlgLocal[] = { -#ifdef HKS_SUPPORT_AES_C - HKS_ALG_AES, -#endif -}; - -#ifdef HKS_SUPPORT_SIGN_VERIFY +#ifdef HKS_SUPPORT_API_SIGN_VERIFY static uint32_t g_signAlg[] = { #ifdef HKS_SUPPORT_RSA_C HKS_ALG_RSA, @@ -106,6 +110,7 @@ static uint32_t g_agreeAlgLocal[] = { HKS_ALG_X25519, #endif }; +#endif /* _CUT_AUTHENTICATE_ */ static uint32_t g_deriveAlg[] = { #ifdef HKS_SUPPORT_KDF_HKDF @@ -136,6 +141,12 @@ static uint32_t g_aesKeySizeLocal[] = { HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256) }; +static uint32_t g_cipherAlgLocal[] = { +#ifdef HKS_SUPPORT_AES_C + HKS_ALG_AES, +#endif +}; + static int32_t CheckAndGetAlgorithm(const struct HksParamSet *paramSet, const uint32_t *expectAlg, uint32_t expectCnt, uint32_t *alg) { @@ -176,6 +187,7 @@ static int32_t CheckAndGetDigest(const struct HksParamSet *paramSet, const uint3 return ret; } +#ifndef _CUT_AUTHENTICATE_ static int32_t CheckGenKeyParamsByAlg(uint32_t alg, const struct HksParamSet *paramSet, struct ParamsValues *params) { @@ -309,6 +321,7 @@ static int32_t CheckSignVerifyParamsByAlg(uint32_t cmdId, uint32_t alg, const st return ret; } +#endif /* _CUT_AUTHENTICATE_ */ static int32_t CheckCipherParamsByAlg(uint32_t cmdId, uint32_t alg, const struct HksParamSet *paramSet, const struct ParamsValues *inputParams) @@ -333,6 +346,7 @@ static int32_t CheckCipherParamsByAlg(uint32_t cmdId, uint32_t alg, const struct return ret; } +#ifndef _CUT_AUTHENTICATE_ #ifdef HKS_SUPPORT_KDF_PBKDF2 static int32_t CheckPbkdf2DeriveKeyParams(const struct HksParamSet *paramSet) { @@ -360,58 +374,8 @@ static int32_t CheckPbkdf2DeriveKeyParams(const struct HksParamSet *paramSet) } #endif -static int32_t CheckMacPurpose(const struct HksParamSet *paramSet) -{ - struct HksParam *purposeParam = NULL; - int32_t ret = HksGetParam(paramSet, HKS_TAG_PURPOSE, &purposeParam); - if (ret != HKS_SUCCESS) { - return HKS_ERROR_CHECK_GET_PURPOSE_FAIL; - } - - if (purposeParam->uint32Param != HKS_KEY_PURPOSE_MAC) { - return HKS_ERROR_INVALID_PURPOSE; - } - - return HKS_SUCCESS; -} - -static int32_t CheckMacOutput(const struct HksBlob *key, const struct HksParamSet *paramSet, - const struct HksBlob *mac, bool isLocalCheck) -{ - uint32_t digest; - int32_t ret; - if (isLocalCheck) { - ret = CheckAndGetDigest(paramSet, g_digest, HKS_ARRAY_SIZE(g_digest), &digest); - } else { - ret = CheckAndGetDigest(paramSet, g_macDigest, HKS_ARRAY_SIZE(g_macDigest), &digest); - } - if (ret != HKS_SUCCESS) { - HKS_LOG_E("check digest failed"); - return ret; - } - - uint32_t digestLen; - ret = HksGetDigestLen(digest, &digestLen); - if (ret != HKS_SUCCESS) { - HKS_LOG_E("get digest lenght failed, ret = %d", ret); - return ret; - } - - if (mac->size < digestLen) { - HKS_LOG_E("mac buffer too small, size %u", mac->size); - return HKS_ERROR_BUFFER_TOO_SMALL; - } - - if ((isLocalCheck) && (key->size < digestLen)) { /* the unit of local engine input key size is byte */ - HKS_LOG_E("key size too small, size = %u", key->size); - return HKS_ERROR_INVALID_KEY_SIZE; - } - - return HKS_SUCCESS; -} - int32_t HksCoreCheckGenKeyParams(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, - const struct HksBlob *keyIn, struct HksBlob *keyOut) + const struct HksBlob *keyIn, const struct HksBlob *keyOut) { (void)keyAlias; (void)keyIn; @@ -422,7 +386,7 @@ int32_t HksCoreCheckGenKeyParams(const struct HksBlob *keyAlias, const struct Hk } int32_t HksCoreCheckImportKeyParams(const struct HksBlob *keyAlias, const struct HksBlob *key, - const struct HksParamSet *paramSet, struct HksBlob *keyOut) + const struct HksParamSet *paramSet, const struct HksBlob *keyOut) { (void)keyAlias; (void)keyOut; @@ -456,7 +420,7 @@ int32_t HksCoreCheckImportKeyParams(const struct HksBlob *keyAlias, const struct int32_t HksCoreCheckSignVerifyParams(uint32_t cmdId, const struct HksBlob *key, const struct HksParamSet *paramSet, const struct HksBlob *srcData, const struct HksBlob *signature) { -#ifdef HKS_SUPPORT_SIGN_VERIFY +#ifdef HKS_SUPPORT_API_SIGN_VERIFY (void)srcData; uint32_t alg; int32_t ret = CheckAndGetAlgorithm(paramSet, g_signAlg, HKS_ARRAY_SIZE(g_signAlg), &alg); @@ -487,10 +451,55 @@ int32_t HksCoreCheckSignVerifyParams(uint32_t cmdId, const struct HksBlob *key, return ret; #else + (void)cmdId; + (void)key; + (void)paramSet; + (void)srcData; + (void)signature; return HKS_ERROR_NOT_SUPPORTED; #endif } +int32_t HksCoreCheckAgreeKeyParams(const struct HksParamSet *paramSet, const struct HksBlob *privateKey, + const struct HksBlob *peerPublicKey, const struct HksBlob *agreedKey, bool isLocalCheck) +{ + uint32_t alg; + int32_t ret; + + if (isLocalCheck) { + ret = CheckAndGetAlgorithm(paramSet, g_agreeAlgLocal, HKS_ARRAY_SIZE(g_agreeAlgLocal), &alg); + } else { + ret = CheckAndGetAlgorithm(paramSet, g_agreeAlg, HKS_ARRAY_SIZE(g_agreeAlg), &alg); + } + if (ret != HKS_SUCCESS) { + HKS_LOG_E("check alg failed"); + return ret; + } + + uint32_t keySize = 0; + if (isLocalCheck) { + if ((privateKey->size != HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256)) || + (peerPublicKey->size != HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256))) { + return HKS_ERROR_INVALID_KEY_SIZE; + } + keySize = privateKey->size * HKS_BITS_PER_BYTE; + } else { + ret = HksGetKeySize(alg, privateKey, &keySize); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get key size failed"); + return ret; + } + } + + uint32_t size = keySize / HKS_BITS_PER_BYTE + keySize % HKS_BITS_PER_BYTE; + if (agreedKey->size < size) { + HKS_LOG_E("agreeKey buffer too small, size %u", agreedKey->size); + return HKS_ERROR_BUFFER_TOO_SMALL; + } + + return HKS_SUCCESS; +} + int32_t HksCoreCheckCipherParams(uint32_t cmdId, const struct HksBlob *key, const struct HksParamSet *paramSet, const struct HksBlob *inData, const struct HksBlob *outData) { @@ -531,6 +540,7 @@ int32_t HksCoreCheckCipherParams(uint32_t cmdId, const struct HksBlob *key, cons return ret; } +#endif /* _CUT_AUTHENTICATE_ */ int32_t HksLocalCheckCipherParams(uint32_t cmdId, const struct HksBlob *key, const struct HksParamSet *paramSet, const struct HksBlob *inData, const struct HksBlob *outData) @@ -571,47 +581,6 @@ int32_t HksLocalCheckCipherParams(uint32_t cmdId, const struct HksBlob *key, con return ret; } - -int32_t HksCoreCheckAgreeKeyParams(const struct HksParamSet *paramSet, const struct HksBlob *privateKey, - const struct HksBlob *peerPublicKey, const struct HksBlob *agreedKey, bool isLocalCheck) -{ - uint32_t alg; - int32_t ret; - - if (isLocalCheck) { - ret = CheckAndGetAlgorithm(paramSet, g_agreeAlgLocal, HKS_ARRAY_SIZE(g_agreeAlgLocal), &alg); - } else { - ret = CheckAndGetAlgorithm(paramSet, g_agreeAlg, HKS_ARRAY_SIZE(g_agreeAlg), &alg); - } - if (ret != HKS_SUCCESS) { - HKS_LOG_E("check alg failed"); - return ret; - } - - uint32_t keySize = 0; - if (isLocalCheck) { - if ((privateKey->size != HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256)) || - (peerPublicKey->size != HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256))) { - return HKS_ERROR_INVALID_KEY_SIZE; - } - keySize = privateKey->size * HKS_BITS_PER_BYTE; - } else { - ret = HksGetKeySize(alg, privateKey, &keySize); - if (ret != HKS_SUCCESS) { - HKS_LOG_E("get key size failed"); - return ret; - } - } - - uint32_t size = keySize / HKS_BITS_PER_BYTE + keySize % HKS_BITS_PER_BYTE; - if (agreedKey->size < size) { - HKS_LOG_E("agreeKey buffer too small, size %u", agreedKey->size); - return HKS_ERROR_BUFFER_TOO_SMALL; - } - - return HKS_SUCCESS; -} - int32_t HksCoreCheckDeriveKeyParams(const struct HksParamSet *paramSet, const struct HksBlob *mainKey, const struct HksBlob *derivedKey, bool isLocalCheck) { @@ -657,6 +626,56 @@ int32_t HksCoreCheckDeriveKeyParams(const struct HksParamSet *paramSet, const st return HKS_SUCCESS; } +static int32_t CheckMacPurpose(const struct HksParamSet *paramSet) +{ + struct HksParam *purposeParam = NULL; + int32_t ret = HksGetParam(paramSet, HKS_TAG_PURPOSE, &purposeParam); + if (ret != HKS_SUCCESS) { + return HKS_ERROR_CHECK_GET_PURPOSE_FAIL; + } + + if (purposeParam->uint32Param != HKS_KEY_PURPOSE_MAC) { + return HKS_ERROR_INVALID_PURPOSE; + } + + return HKS_SUCCESS; +} + +static int32_t CheckMacOutput(const struct HksBlob *key, const struct HksParamSet *paramSet, + const struct HksBlob *mac, bool isLocalCheck) +{ + uint32_t digest; + int32_t ret; + if (isLocalCheck) { + ret = CheckAndGetDigest(paramSet, g_digest, HKS_ARRAY_SIZE(g_digest), &digest); + } else { + ret = CheckAndGetDigest(paramSet, g_macDigest, HKS_ARRAY_SIZE(g_macDigest), &digest); + } + if (ret != HKS_SUCCESS) { + HKS_LOG_E("check digest failed"); + return ret; + } + + uint32_t digestLen; + ret = HksGetDigestLen(digest, &digestLen); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get digest lenght failed, ret = %d", ret); + return ret; + } + + if (mac->size < digestLen) { + HKS_LOG_E("mac buffer too small, size %u", mac->size); + return HKS_ERROR_BUFFER_TOO_SMALL; + } + + if ((isLocalCheck) && (key->size < digestLen)) { /* the unit of local engine input key size is byte */ + HKS_LOG_E("key size too small, size = %u", key->size); + return HKS_ERROR_INVALID_KEY_SIZE; + } + + return HKS_SUCCESS; +} + int32_t HksCoreCheckMacParams(const struct HksBlob *key, const struct HksParamSet *paramSet, const struct HksBlob *srcData, const struct HksBlob *mac, bool isLocalCheck) { diff --git a/frameworks/huks_standard/main/common/src/hks_common_check.c b/frameworks/huks_standard/main/common/src/hks_common_check.c index 3a924d27..0d2497b3 100644 --- a/frameworks/huks_standard/main/common/src/hks_common_check.c +++ b/frameworks/huks_standard/main/common/src/hks_common_check.c @@ -14,9 +14,6 @@ */ #include "hks_common_check.h" - -#include - #include "hks_log.h" #include "hks_param.h" diff --git a/frameworks/huks_standard/main/common/src/hks_crypto_adapter.c b/frameworks/huks_standard/main/common/src/hks_crypto_adapter.c index 50204703..65429aaf 100755 --- a/frameworks/huks_standard/main/common/src/hks_crypto_adapter.c +++ b/frameworks/huks_standard/main/common/src/hks_crypto_adapter.c @@ -231,6 +231,7 @@ int32_t HksGetEncryptAeTag(const struct HksParamSet *paramSet, const struct HksB return HKS_SUCCESS; } +#ifndef _CUT_AUTHENTICATE_ static int32_t SetCurve25519KeyMaterial(bool isPubKey, const struct HksBlob *keyIn, struct HksBlob *keyOut) { struct KeyMaterial25519 curve25519Km = {0}; @@ -368,14 +369,14 @@ int32_t GetCurve25519FromKeyMaterial(const bool isPubKey, const struct HksBlob * const struct KeyMaterial25519 *km = (struct KeyMaterial25519 *)(keyMaterial->data); - uint32_t size = isPubKey ? km->pubKeySize : km->priKeySize; + uint32_t size = (isPubKey ? km->pubKeySize : km->priKeySize); uint8_t *buffer = (uint8_t *)HksMalloc(size); if (buffer == NULL) { return HKS_ERROR_MALLOC_FAIL; } uint32_t offset = sizeof(struct KeyMaterial25519); - uint8_t *tmp = isPubKey ? (keyMaterial->data + offset) : (keyMaterial->data + offset + km->pubKeySize); + uint8_t *tmp = (isPubKey ? (keyMaterial->data + offset) : (keyMaterial->data + offset + km->pubKeySize)); if (memcpy_s(buffer, size, tmp, size) != EOK) { (void)memset_s(buffer, size, 0, size); HKS_FREE_PTR(buffer); @@ -387,7 +388,6 @@ int32_t GetCurve25519FromKeyMaterial(const bool isPubKey, const struct HksBlob * return HKS_SUCCESS; } - int32_t HksSetKeyToMaterial(uint32_t alg, bool isPubKey, const struct HksBlob *key, struct HksBlob *keyMaterial) { switch (alg) { @@ -423,3 +423,4 @@ int32_t HksFormatKeyFromMaterial(uint32_t alg, const struct HksBlob *keyMaterial return HKS_ERROR_INVALID_ALGORITHM; } } +#endif diff --git a/frameworks/huks_standard/main/common/src/hks_param.c b/frameworks/huks_standard/main/common/src/hks_param.c index dd7714a2..0add8e14 100755 --- a/frameworks/huks_standard/main/common/src/hks_param.c +++ b/frameworks/huks_standard/main/common/src/hks_param.c @@ -16,6 +16,7 @@ #include "hks_param.h" #include "hks_log.h" #include "hks_mem.h" +#include "hks_type_inner.h" enum HksTag g_validTags[] = { HKS_TAG_ALGORITHM, @@ -37,6 +38,7 @@ enum HksTag g_validTags[] = { HKS_TAG_KEY_GENERATE_TYPE, HKS_TAG_DERIVE_MAIN_KEY, HKS_TAG_DERIVE_FACTOR, + HKS_TAG_DERIVE_ALG, HKS_TAG_AGREE_ALG, HKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS, HKS_TAG_AGREE_PRIVATE_KEY_ALIAS, @@ -88,6 +90,9 @@ enum HksTag g_validTags[] = { HKS_TAG_KEY, HKS_TAG_KEY_VERSION, HKS_TAG_IS_KEY_HANDLE, + HKS_TAG_SYMMETRIC_KEY_DATA, + HKS_TAG_ASYMMETRIC_PUBLIC_KEY_DATA, + HKS_TAG_ASYMMETRIC_PRIVATE_KEY_DATA, }; static enum HksTagType GetTagType(enum HksTag tag) @@ -268,7 +273,6 @@ HKS_API_EXPORT int32_t HksAddParams(struct HksParamSet *paramSet, (void)memcpy_s(¶mSet->params[paramSet->paramsCnt++], sizeof(struct HksParam), ¶ms[i], sizeof(struct HksParam)); } - return HKS_SUCCESS; } diff --git a/frameworks/huks_standard/main/core/BUILD.gn b/frameworks/huks_standard/main/core/BUILD.gn index 5d6754ce..2f66ee03 100644 --- a/frameworks/huks_standard/main/core/BUILD.gn +++ b/frameworks/huks_standard/main/core/BUILD.gn @@ -22,6 +22,11 @@ ohos_static_library("libhuks_core_standard_static") { part_name = "huks_standard" public_configs = [ ":huks_config" ] include_dirs = [ "//utils/native/base/include" ] + defines = [ + "L2_STANDARD", + "_HARDWARE_ROOT_KEY_", + "_HUKS_LOG_ENABLE_", + ] sources = [ "./src/hks_local_engine.c" ] deps = [ "//base/security/huks/frameworks/huks_standard/main/common:libhuks_common_standard_static" ] complete_static_lib = true diff --git a/frameworks/huks_standard/main/core/include/hks_local_engine.h b/frameworks/huks_standard/main/core/include/hks_local_engine.h index c9895d5b..de59d19b 100755 --- a/frameworks/huks_standard/main/core/include/hks_local_engine.h +++ b/frameworks/huks_standard/main/core/include/hks_local_engine.h @@ -17,7 +17,7 @@ #define HKS_LOCAL_ENGINE_H #include "hks_cmd_id.h" -#include "hks_type.h" +#include "hks_type_inner.h" #ifdef __cplusplus extern "C" { diff --git a/frameworks/huks_standard/main/core/src/hks_local_engine.c b/frameworks/huks_standard/main/core/src/hks_local_engine.c index 0ceb5525..18e26eff 100755 --- a/frameworks/huks_standard/main/core/src/hks_local_engine.c +++ b/frameworks/huks_standard/main/core/src/hks_local_engine.c @@ -27,27 +27,7 @@ #define MAX_DEGIST_SIZE 64 #define X25519_KEY_BYTE_SIZE 32 -int32_t HksLocalMac(const struct HksBlob *key, const struct HksParamSet *paramSet, - const struct HksBlob *srcData, struct HksBlob *mac) -{ - if (HksCheckBlob3AndParamSet(key, srcData, mac, paramSet) != HKS_SUCCESS) { - return HKS_ERROR_INVALID_ARGUMENT; - } - int32_t ret = HksCoreCheckMacParams(key, paramSet, srcData, mac, true); - if (ret != HKS_SUCCESS) { - return ret; - } - - struct HksParam *digestAlg = NULL; - ret = HksGetParam(paramSet, HKS_TAG_DIGEST, &digestAlg); - if (ret != HKS_SUCCESS) { - HKS_LOG_E("get param digest failed"); - return HKS_ERROR_CHECK_GET_DIGEST_FAIL; - } - - return HksCryptoHalHmac(key, digestAlg->uint32Param, srcData, mac); -} - +#ifndef _CUT_AUTHENTICATE_ int32_t HksLocalHash(const struct HksParamSet *paramSet, const struct HksBlob *srcData, struct HksBlob *hash) { if (HksCheckBlob2AndParamSet(srcData, hash, paramSet) != HKS_SUCCESS) { @@ -75,6 +55,28 @@ int32_t HksLocalHash(const struct HksParamSet *paramSet, const struct HksBlob *s return HksCryptoHalHash(digestAlg->uint32Param, srcData, hash); } +#endif + +int32_t HksLocalMac(const struct HksBlob *key, const struct HksParamSet *paramSet, + const struct HksBlob *srcData, struct HksBlob *mac) +{ + if (HksCheckBlob3AndParamSet(key, srcData, mac, paramSet) != HKS_SUCCESS) { + return HKS_ERROR_INVALID_ARGUMENT; + } + int32_t ret = HksCoreCheckMacParams(key, paramSet, srcData, mac, true); + if (ret != HKS_SUCCESS) { + return ret; + } + + struct HksParam *digestAlg = NULL; + ret = HksGetParam(paramSet, HKS_TAG_DIGEST, &digestAlg); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get param digest failed"); + return HKS_ERROR_CHECK_GET_DIGEST_FAIL; + } + + return HksCryptoHalHmac(key, digestAlg->uint32Param, srcData, mac); +} int32_t HksLocalBnExpMod(struct HksBlob *x, const struct HksBlob *a, const struct HksBlob *e, const struct HksBlob *n) { @@ -85,6 +87,7 @@ int32_t HksLocalBnExpMod(struct HksBlob *x, const struct HksBlob *a, const struc return HksCryptoHalBnExpMod(x, a, e, n); } +#ifndef _CUT_AUTHENTICATE_ static int32_t CheckLocalGenerateKeyParams(const struct HksParamSet *paramSetIn, struct HksParamSet *paramSetOut) { if ((HksCheckParamSetValidity(paramSetIn) != HKS_SUCCESS) || (paramSetOut == NULL)) { @@ -182,6 +185,7 @@ int32_t HksLocalAgreeKey(const struct HksParamSet *paramSet, const struct HksBlo HKS_FREE_PTR(publicKeyMaterial.data); return ret; } +#endif static int32_t CipherEncrypt(const struct HksBlob *key, const struct HksParamSet *paramSet, const struct HksUsageSpec *usageSpec, const struct HksBlob *inData, struct HksBlob *outData) @@ -275,6 +279,7 @@ int32_t HksLocalDeriveKey(const struct HksParamSet *paramSet, const struct HksBl return HksCryptoHalDeriveKey(mainKey, &derivationSpec, derivedKey); } +#ifndef _CUT_AUTHENTICATE_ static int32_t CheckLocalVerifyParams(const struct HksBlob *key, const struct HksParamSet *paramSet, const struct HksBlob *srcData, const struct HksBlob *signature) { @@ -334,3 +339,4 @@ int32_t HksLocalVerify(const struct HksBlob *key, const struct HksParamSet *para HKS_FREE_PTR(keyMaterial.data); return ret; } +#endif \ No newline at end of file diff --git a/frameworks/huks_standard/main/crypto_engine/BUILD.gn b/frameworks/huks_standard/main/crypto_engine/BUILD.gn index 1a89816e..4d18709c 100644 --- a/frameworks/huks_standard/main/crypto_engine/BUILD.gn +++ b/frameworks/huks_standard/main/crypto_engine/BUILD.gn @@ -14,6 +14,11 @@ import("//build/ohos.gni") ohos_static_library("libhuks_crypto_engine_standard_static") { + defines = [ + "L2_STANDARD", + "_HARDWARE_ROOT_KEY_", + "_HUKS_LOG_ENABLE_", + ] subsystem_name = "security" part_name = "huks_standard" public_deps = [ "//base/security/huks/frameworks/huks_standard/main/crypto_engine/openssl:libhuks_openssl_standard_static" ] diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_crypto_ed25519.h b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_crypto_ed25519.h new file mode 100644 index 00000000..815c56d9 --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_crypto_ed25519.h @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_CRYPTO_ED25519_H +#define HKS_CRYPTO_ED25519_H + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#include "hks_type_inner.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#if defined(HKS_SUPPORT_ED25519_C) || defined(HKS_SUPPORT_ED25519_GENERATE_KEY) +int32_t HksEd25519GenerateKey(struct HksBlob *keyOut); +#endif + +#if defined(HKS_SUPPORT_ED25519_C) || defined(HKS_SUPPORT_ED2519_GET_PUBLIC_KEY) +int32_t HksGetEd25519PubKey(const struct HksBlob *input, struct HksBlob *output); +#endif + +#if defined(HKS_SUPPORT_ED25519_C) || defined(HKS_SUPPORT_ED25519_SIGN_VERIFY) +int32_t HksEd25519Sign(const struct HksBlob *key, const struct HksBlob *message, struct HksBlob *signature); + +int32_t HksEd25519Verify(const struct HksBlob *key, const struct HksBlob *message, + const struct HksBlob *signature); +#endif + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_aes.h b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_aes.h new file mode 100644 index 00000000..91fc1239 --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_aes.h @@ -0,0 +1,46 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_MBEDTLS_AES_H +#define HKS_MBEDTLS_AES_H + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#include "hks_crypto_hal.h" +#include "hks_type_inner.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef HKS_SUPPORT_AES_GENERATE_KEY +int32_t HksMbedtlsAesGenerateKey(const struct HksKeySpec *spec, struct HksBlob *key); +#endif + +int32_t HksMbedtlsAesEncrypt(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, struct HksBlob *cipherText, struct HksBlob *tagAead); + +int32_t HksMbedtlsAesDecrypt(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, struct HksBlob *cipherText); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_MBEDTLS_AES_H */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_bn.h b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_bn.h new file mode 100644 index 00000000..e1f97935 --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_bn.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_MBEDTLS_BN_H +#define HKS_MBEDTLS_BN_H + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#include "hks_type.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t HksMbedtlsBnExpMod(const struct HksBlob *a, + const struct HksBlob *e, const struct HksBlob *n, struct HksBlob *x); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_MBEDTLS_BN_H */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_common.h b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_common.h new file mode 100644 index 00000000..c2da8bcc --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_common.h @@ -0,0 +1,44 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_MBEDTLS_COMMON_H +#define HKS_MBEDTLS_COMMON_H + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#include +#include + +#include "hks_type.h" + +#define HKS_MBEDTLS_SUCCESS ((int32_t)0) + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t HksToMbedtlsDigestAlg(const uint32_t hksAlg, uint32_t *mbedtlsAlg); + +int32_t HksCtrDrbgSeed(mbedtls_ctr_drbg_context *ctrDrbg, mbedtls_entropy_context *entropy); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_MBEDTLS_COMMON_H */ \ No newline at end of file diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_ecc.h b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_ecc.h new file mode 100644 index 00000000..83f86722 --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_ecc.h @@ -0,0 +1,59 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_MBEDTLS_ECC_H +#define HKS_MBEDTLS_ECC_H + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#include +#include + +#include "hks_crypto_hal.h" +#include "hks_type_inner.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t GetEccGroupId(const uint32_t keyLen, mbedtls_ecp_group_id *grpId); + +int32_t EccKeyCheck(const struct HksBlob *key); + +#if defined(HKS_SUPPORT_ECDH_C) || defined(HKS_SUPPORT_ECDSA_C) +int32_t HksMbedtlsEccGetKeyCurveNist(const struct KeyMaterialEcc *keyMaterial, mbedtls_ecp_group_id *curve); + +int32_t HksEccKeyMaterialToPub(const struct HksBlob *key, mbedtls_ecp_point *pub); + +int32_t HksEccKeyMaterialToPri(const struct HksBlob *key, mbedtls_mpi *pri); +#endif + +#ifdef HKS_SUPPORT_ECC_GENERATE_KEY +int32_t HksMbedtlsEccGenerateKey(const struct HksKeySpec *spec, struct HksBlob *key); +#endif + +#ifdef HKS_SUPPORT_ECC_GET_PUBLIC_KEY +int32_t HksMbedtlsGetEccPubKey(const struct HksBlob *keyIn, struct HksBlob *keyOut); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_MBEDTLS_ECC_H */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_ecdh.h b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_ecdh.h new file mode 100644 index 00000000..78210275 --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_ecdh.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_MBEDTLS_ECDH_H +#define HKS_MBEDTLS_ECDH_H + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#include "hks_crypto_hal.h" +#include "hks_type.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t HksMbedtlsEcdh(const struct HksBlob *nativeKey, + const struct HksBlob *pubKey, const struct HksKeySpec *spec, struct HksBlob *sharedKey); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_MBEDTLS_ECDH_H */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_ecdsa.h b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_ecdsa.h new file mode 100644 index 00000000..055f3437 --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_ecdsa.h @@ -0,0 +1,42 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_MBEDTLS_ECDSA_H +#define HKS_MBEDTLS_ECDSA_H + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#include "hks_crypto_hal.h" +#include "hks_type.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t HksMbedtlsEcdsaSign(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, struct HksBlob *signature); + +int32_t HksMbedtlsEcdsaVerify(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, const struct HksBlob *signature); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_MBEDTLS_ECDSA_H */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_hash.h b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_hash.h new file mode 100644 index 00000000..40e4a70f --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_hash.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_MBEDTLS_HASH_H +#define HKS_MBEDTLS_HASH_H + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#include "hks_type.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t HksMbedtlsHash(uint32_t alg, const struct HksBlob *msg, struct HksBlob *hash); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_MBEDTLS_HASH_H */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_hmac.h b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_hmac.h new file mode 100644 index 00000000..68b7888c --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_hmac.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_MBEDTLS_HMAC_H +#define HKS_MBEDTLS_HMAC_H + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#include "hks_type.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t HksMbedtlsHmac(const struct HksBlob *key, + uint32_t digestAlg, const struct HksBlob *msg, struct HksBlob *mac); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_MBEDTLS_HMAC_H */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_kdf.h b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_kdf.h new file mode 100644 index 00000000..a4828ebc --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_kdf.h @@ -0,0 +1,39 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_MBEDTLS_KDF_H +#define HKS_MBEDTLS_KDF_H + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#include "hks_crypto_hal.h" +#include "hks_type.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t HksMbedtlsDeriveKey(const struct HksBlob *mainKey, + const struct HksKeySpec *derivationSpec, struct HksBlob *derivedKey); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_MBEDTLS_KDF_H */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_rsa.h b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_rsa.h new file mode 100644 index 00000000..df7c0ca9 --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_rsa.h @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_MBEDTLS_RSA_H +#define HKS_MBEDTLS_RSA_H + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#include "hks_crypto_hal.h" +#include "hks_type_inner.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef HKS_SUPPORT_RSA_GENERATE_KEY +int32_t HksMbedtlsRsaGenerateKey(const struct HksKeySpec *spec, struct HksBlob *key); +#endif + +#ifdef HKS_SUPPORT_RSA_CRYPT +int32_t HksMbedtlsRsaCrypt(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, const bool encrypt, struct HksBlob *cipherText); +#endif + +#ifdef HKS_SUPPORT_RSA_SIGN_VERIFY +int32_t HksMbedtlsRsaSign(const struct HksBlob *key, + const struct HksUsageSpec *usageSpec, const struct HksBlob *message, struct HksBlob *signature); + +int32_t HksMbedtlsRsaVerify(const struct HksBlob *key, + const struct HksUsageSpec *usageSpec, const struct HksBlob *message, const struct HksBlob *signature); +#endif + +#ifdef HKS_SUPPORT_RSA_GET_PUBLIC_KEY +int32_t HksMbedtlsGetRsaPubKey(const struct HksBlob *keyIn, struct HksBlob *keyOut); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_MBEDTLS_RSA_H */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_x25519.h b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_x25519.h new file mode 100644 index 00000000..1066a7d2 --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/include/hks_mbedtls_x25519.h @@ -0,0 +1,54 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_MBEDTLS_X25519_H +#define HKS_MBEDTLS_X25519_H + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#include "hks_crypto_hal.h" +#include "hks_type_inner.h" + +#ifdef __cplusplus +extern "C" { +#endif + +#ifdef HKS_SUPPORT_X25519_GENERATE_KEY +int32_t HksMbedtlsX25519GenerateKey(struct HksBlob *key); +#endif + +#ifdef HKS_SUPPORT_X25519_AGREE_KEY +int32_t HksMbedtlsX25519KeyAgreement(const struct HksBlob *nativeKey, + const struct HksBlob *pubKey, struct HksBlob *sharedKey); +#endif + +#ifdef HKS_SUPPORT_X25519_GET_PUBLIC_KEY +int32_t HksMbedtlsGetX25519PubKey(const struct HksBlob *keyIn, struct HksBlob *keyOut); +#endif + +#ifdef HKS_SUPPORT_ED25519_TO_X25519 +int32_t HksMbedtlsEd25519KeyAgreement(const struct HksBlob *nativeKey, + const struct HksBlob *pubKey, struct HksBlob *sharedKey); +#endif + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_MBEDTLS_X25519_H */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_crypto_ed25519.c b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_crypto_ed25519.c new file mode 100644 index 00000000..5db5fa3f --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_crypto_ed25519.c @@ -0,0 +1,213 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#ifdef _CUT_AUTHENTICATE_ +#undef HKS_SUPPORT_ED25519_C +#endif + +#ifdef HKS_SUPPORT_ED25519_C + +#include "hks_crypto_ed25519.h" + +#include + +#include "hks_crypto_hal.h" +#include "hks_log.h" +#include "hks_mem.h" + +#define CRYPTO_SUCCESS 1 +#define ED25519_PRIVATE_KEY_LEN 32 +#define ED25519_PUBLIC_KEY_LEN 32 + +#ifdef HKS_SUPPORT_ED25519_GENERATE_KEY +static int32_t SaveEd25519KeyMaterial(const struct HksBlob *pubKey, const struct HksBlob *priKey, + struct HksBlob *keyOut) +{ + uint32_t totalSize = sizeof(struct KeyMaterial25519) + pubKey->size + priKey->size; + uint8_t *buffer = (uint8_t *)HksMalloc(totalSize); + if (buffer == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + + struct KeyMaterial25519 *keyMaterial = (struct KeyMaterial25519 *)buffer; + keyMaterial->keyAlg = HKS_ALG_ED25519; + keyMaterial->keySize = HKS_CURVE25519_KEY_SIZE_256; + keyMaterial->pubKeySize = pubKey->size; + keyMaterial->priKeySize = priKey->size; + keyMaterial->reserved = 0; + + uint32_t offset = sizeof(struct KeyMaterial25519); + if (memcpy_s(buffer + offset, pubKey->size, pubKey->data, pubKey->size) != EOK) { + HKS_LOG_E("copy ed25519 public key failed"); + (void)memset_s(buffer, totalSize, 0, totalSize); + HKS_FREE_PTR(buffer); + return HKS_ERROR_BAD_STATE; + } + + offset += pubKey->size; + if (memcpy_s(buffer + offset, priKey->size, priKey->data, priKey->size) != EOK) { + HKS_LOG_E("copy ed25519 private key failed"); + (void)memset_s(buffer, totalSize, 0, totalSize); + HKS_FREE_PTR(buffer); + return HKS_ERROR_BAD_STATE; + } + + keyOut->data = buffer; + keyOut->size = totalSize; + return HKS_SUCCESS; +} + +static bool IsBlobZero(const struct HksBlob *key) +{ + for (uint32_t i = 0; i < key->size; ++i) { + if (key->data[i] != 0) { + return false; + } + } + return true; +} + +int32_t HksEd25519GenerateKey(struct HksBlob *keyOut) +{ + uint8_t pubKey[ED25519_PUBLIC_KEY_LEN] = {0}; + uint8_t priKey[ED25519_PRIVATE_KEY_LEN] = {0}; + struct HksBlob pubKeyBlob = { ED25519_PUBLIC_KEY_LEN, pubKey }; + struct HksBlob priKeyBlob = { ED25519_PRIVATE_KEY_LEN, priKey }; + + struct HksBlob tmp = { ED25519_PUBLIC_KEY_LEN, priKeyBlob.data }; + int32_t ret = HksCryptoHalFillRandom(&tmp); + if (ret != HKS_SUCCESS) { + return ret; + } + + ED25519_public_from_private(pubKeyBlob.data, priKeyBlob.data); + if (IsBlobZero(&pubKeyBlob) || IsBlobZero(&priKeyBlob)) { + return HKS_ERROR_CRYPTO_ENGINE_ERROR; + } + + return SaveEd25519KeyMaterial(&pubKeyBlob, &priKeyBlob, keyOut); +} +#endif /* HKS_SUPPORT_ED25519_GENERATE_KEY */ + +static int32_t CheckEd25519Material(const struct HksBlob *key) +{ + uint32_t totalSize = sizeof(struct KeyMaterial25519); + if (key->size < totalSize) { + HKS_LOG_E("Ed25519 key material too small"); + return HKS_ERROR_INVALID_KEY_INFO; + } + + struct KeyMaterial25519 *km = (struct KeyMaterial25519 *)key->data; + if (((key->size - totalSize) < km->pubKeySize) || + ((key->size - totalSize) < km->priKeySize) || + ((key->size - totalSize) < (km->pubKeySize + km->priKeySize))) { + HKS_LOG_E("Ed25519 key material wrong pub and pri key size %u, %u, %u", + key->size, km->pubKeySize, km->priKeySize); + return HKS_ERROR_INVALID_KEY_INFO; + } + + return HKS_SUCCESS; +} + +#ifdef HKS_SUPPORT_ED2519_GET_PUBLIC_KEY +static int32_t GetEd25519PubKeyCheck(const struct HksBlob *key, const struct HksBlob *keyOut) +{ + int32_t ret = CheckEd25519Material(key); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* check keyOut */ + struct KeyMaterial25519 *km = (struct KeyMaterial25519 *)key->data; + if ((km->pubKeySize > (INT32_MAX - sizeof(struct KeyMaterial25519))) || + (keyOut->size < (sizeof(struct KeyMaterial25519) + km->pubKeySize))) { + HKS_LOG_E("Ecc public keyOut size too small! keyOut size = 0x%X", keyOut->size); + return HKS_ERROR_BUFFER_TOO_SMALL; + } + + return HKS_SUCCESS; +} + +int32_t HksGetEd25519PubKey(const struct HksBlob *input, struct HksBlob *output) +{ + int32_t ret = GetEd25519PubKeyCheck(input, output); + if (ret != HKS_SUCCESS) { + return ret; + } + + struct KeyMaterial25519 *key = (struct KeyMaterial25519 *)input->data; + uint32_t outLen = sizeof(struct KeyMaterial25519) + key->pubKeySize; + if (memcpy_s(output->data, output->size, key, outLen) != EOK) { + HKS_LOG_E("memcpy_s ed25519 pub key failed"); + return HKS_ERROR_BAD_STATE; + } + + ((struct KeyMaterial25519 *)output->data)->priKeySize = 0; + output->size = outLen; + return HKS_SUCCESS; +} +#endif + +#ifdef HKS_SUPPORT_ED25519_SIGN_VERIFY +int32_t HksEd25519Sign(const struct HksBlob *key, const struct HksBlob *message, struct HksBlob *signature) +{ + int32_t ret = CheckEd25519Material(key); + if (ret != HKS_SUCCESS) { + return ret; + } + if (signature->size < HKS_SIGNATURE_MIN_SIZE) { + return HKS_ERROR_INVALID_ARGUMENT; + } + + ret = ED25519_sign(signature->data, message->data, message->size, + key->data + sizeof(struct KeyMaterial25519), + key->data + sizeof(struct KeyMaterial25519) + ED25519_PUBLIC_KEY_LEN); + if (ret != CRYPTO_SUCCESS) { + HKS_LOG_E("ED25519_sign failed"); + return HKS_ERROR_CRYPTO_ENGINE_ERROR; + } + signature->size = HKS_SIGNATURE_MIN_SIZE; + + return HKS_SUCCESS; +} + +int32_t HksEd25519Verify(const struct HksBlob *key, const struct HksBlob *message, + const struct HksBlob *signature) +{ + int32_t ret = CheckEd25519Material(key); + if (ret != HKS_SUCCESS) { + return ret; + } + if (signature->size < HKS_SIGNATURE_MIN_SIZE) { + return HKS_ERROR_INVALID_ARGUMENT; + } + + ret = ED25519_verify(message->data, message->size, signature->data, + key->data + sizeof(struct KeyMaterial25519)); + if (ret != CRYPTO_SUCCESS) { + HKS_LOG_E("ED25519_verify failed"); + return HKS_ERROR_CRYPTO_ENGINE_ERROR; + } + + return HKS_SUCCESS; +} +#endif /* HKS_SUPPORT_ED25519_SIGN_VERIFY */ +#endif /* HKS_SUPPORT_ED25519_C */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_aes.c b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_aes.c new file mode 100644 index 00000000..aa4f6af3 --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_aes.c @@ -0,0 +1,366 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#ifdef HKS_SUPPORT_AES_C + +#include "hks_mbedtls_aes.h" + +#include +#include +#include +#include +#include +#include + +#include "hks_log.h" +#include "hks_mbedtls_common.h" +#include "hks_mem.h" + +#define HKS_AES_CBC_NOPADDING_IV_SIZE 16 + +#ifdef HKS_SUPPORT_AES_GENERATE_KEY +int32_t HksMbedtlsAesGenerateKey(const struct HksKeySpec *spec, struct HksBlob *key) +{ + const uint32_t keyByteLen = spec->keyLen / HKS_BITS_PER_BYTE; + + uint8_t *outKey = (uint8_t *)HksMalloc(keyByteLen); + if (outKey == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + + mbedtls_entropy_context entropy; + mbedtls_ctr_drbg_context ctrDrbg; + int32_t ret = HksCtrDrbgSeed(&ctrDrbg, &entropy); + if (ret != HKS_SUCCESS) { + HKS_FREE_PTR(outKey); + return ret; + } + + do { + ret = mbedtls_ctr_drbg_random(&ctrDrbg, outKey, keyByteLen); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls ctr drbg random failed! mbedtls ret = 0x%X", ret); + (void)memset_s(outKey, keyByteLen, 0, keyByteLen); + HKS_FREE_PTR(outKey); + break; + } + + key->data = outKey; + key->size = keyByteLen; + } while (0); + + mbedtls_ctr_drbg_free(&ctrDrbg); + mbedtls_entropy_free(&entropy); + return ret; +} +#endif /* HKS_SUPPORT_AES_GENERATE_KEY */ + +#ifdef HKS_SUPPORT_AES_CBC_NOPADDING +static int32_t AesCbcNoPaddingCrypt(const struct HksBlob *key, const struct HksCipherParam *cipherParam, + const struct HksBlob *message, const bool encrypt, struct HksBlob *cipherText) +{ + mbedtls_aes_context ctx; + mbedtls_aes_init(&ctx); + + int32_t ret; + do { + if (encrypt) { + ret = mbedtls_aes_setkey_enc(&ctx, key->data, key->size * HKS_BITS_PER_BYTE); + } else { + ret = mbedtls_aes_setkey_dec(&ctx, key->data, key->size * HKS_BITS_PER_BYTE); + } + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls aes set key failed! mbedtls ret = 0x%X", ret); + break; + } + + /* mbedtls_aes_crypt_cbc will refresh iv, so need a temp iv */ + uint8_t tmpIv[HKS_AES_CBC_NOPADDING_IV_SIZE]; + if (memcpy_s(tmpIv, HKS_AES_CBC_NOPADDING_IV_SIZE, cipherParam->iv.data, cipherParam->iv.size) != EOK) { + HKS_LOG_E("Memcpy temp iv failed!"); + break; + } + + ret = mbedtls_aes_crypt_cbc(&ctx, (encrypt ? MBEDTLS_AES_ENCRYPT : MBEDTLS_AES_DECRYPT), + message->size, tmpIv, message->data, cipherText->data); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtks aes cbc crypt failed! mbedtls ret = 0x%X", ret); + (void)memset_s(cipherText->data, cipherText->size, 0, cipherText->size); + break; + } + cipherText->size = message->size; + } while (0); + + mbedtls_aes_free(&ctx); + return ret; +} +#endif /* HKS_SUPPORT_AES_CBC_NOPADDING */ + +#ifdef HKS_SUPPORT_AES_CBC_PKCS7 +static int32_t AesCbcPkcs7Crypt(const struct HksBlob *key, const struct HksCipherParam *cipherParam, + const struct HksBlob *message, const bool encrypt, struct HksBlob *cipherText) +{ + const uint32_t keyBitLen = key->size * HKS_BITS_PER_BYTE; + const mbedtls_cipher_info_t *info = + mbedtls_cipher_info_from_values(MBEDTLS_CIPHER_ID_AES, keyBitLen, MBEDTLS_MODE_CBC); + + mbedtls_cipher_context_t ctx; + mbedtls_cipher_init(&ctx); + + int32_t ret; + do { + ret = mbedtls_cipher_setup(&ctx, info); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Mbedtls cbc pkcs7 setup ctx failed! mbedtls ret = 0x%X", ret); + break; + } + + ret = mbedtls_cipher_setkey(&ctx, key->data, keyBitLen, (encrypt ? MBEDTLS_ENCRYPT : MBEDTLS_DECRYPT)); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Mbedtls cbc pkcs7 set key failed! mbedtls ret = 0x%X", ret); + break; + } + + ret = mbedtls_cipher_crypt(&ctx, cipherParam->iv.data, cipherParam->iv.size, + message->data, message->size, cipherText->data, (size_t *)&(cipherText->size)); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls cbc pkcs7 crypt failed! mbedtls ret = 0x%X", ret); + (void)memset_s(cipherText->data, cipherText->size, 0, cipherText->size); + } + } while (0); + + mbedtls_cipher_free(&ctx); + return ret; +} +#endif /* HKS_SUPPORT_AES_CBC_PKCS7 */ + +#if defined(HKS_SUPPORT_AES_CBC_NOPADDING) || defined(HKS_SUPPORT_AES_CBC_PKCS7) +static int32_t AesCbcCrypt(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, const bool encrypt, struct HksBlob *cipherText) +{ + const struct HksCipherParam *cipherParam = (struct HksCipherParam *)(usageSpec->algParam); + + switch (usageSpec->padding) { +#ifdef HKS_SUPPORT_AES_CBC_NOPADDING + case HKS_PADDING_NONE: + return AesCbcNoPaddingCrypt(key, cipherParam, message, encrypt, cipherText); +#endif +#ifdef HKS_SUPPORT_AES_CBC_PKCS7 + case HKS_PADDING_PKCS7: + return AesCbcPkcs7Crypt(key, cipherParam, message, encrypt, cipherText); +#endif + default: + HKS_LOG_E("Unsupport padding! mode = 0x%X", usageSpec->padding); + return HKS_ERROR_INVALID_PADDING; + } +} +#endif /* HKS_SUPPORT_AES_CBC_NOPADDING or HKS_SUPPORT_AES_CBC_PKCS7 */ + +#ifdef HKS_SUPPORT_AES_GCM +static int32_t AesEncryptGcm(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, struct HksBlob *cipherText, struct HksBlob *tagAead) +{ + mbedtls_gcm_context ctx; + mbedtls_gcm_init(&ctx); + + int32_t ret; + do { + ret = mbedtls_gcm_setkey(&ctx, MBEDTLS_CIPHER_ID_AES, key->data, key->size * HKS_BITS_PER_BYTE); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls aes gcm set key failed! mbedtls ret = 0x%X", ret); + break; + } + + const struct HksAeadParam *aeadParam = (struct HksAeadParam *)(usageSpec->algParam); + ret = mbedtls_gcm_crypt_and_tag(&ctx, MBEDTLS_GCM_ENCRYPT, message->size, + aeadParam->nonce.data, aeadParam->nonce.size, aeadParam->aad.data, aeadParam->aad.size, + message->data, cipherText->data, tagAead->size, tagAead->data); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls aes gcm encryot failed! mbedtls ret = 0x%X", ret); + (void)memset_s(cipherText->data, cipherText->size, 0, cipherText->size); + (void)memset_s(tagAead->data, tagAead->size, 0, tagAead->size); + break; + } + cipherText->size = message->size; + } while (0); + + mbedtls_gcm_free(&ctx); + return ret; +} + +static int32_t AesDecryptGcm(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, struct HksBlob *cipherText) +{ + mbedtls_gcm_context ctx; + mbedtls_gcm_init(&ctx); + + int32_t ret; + do { + ret = mbedtls_gcm_setkey(&ctx, MBEDTLS_CIPHER_ID_AES, key->data, key->size * HKS_BITS_PER_BYTE); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls aes gcm set key failed! mbedtls ret = 0x%X", ret); + break; + } + + const struct HksAeadParam *aeadParam = (struct HksAeadParam *)(usageSpec->algParam); + ret = mbedtls_gcm_auth_decrypt(&ctx, message->size, aeadParam->nonce.data, aeadParam->nonce.size, + aeadParam->aad.data, aeadParam->aad.size, aeadParam->tagDec.data, aeadParam->tagDec.size, + message->data, cipherText->data); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls aes gcm decrypt failed! mbedtls ret = 0x%X", ret); + (void)memset_s(cipherText->data, cipherText->size, 0, cipherText->size); + break; + } + cipherText->size = message->size; + } while (0); + + mbedtls_gcm_free(&ctx); + return ret; +} +#endif /* HKS_SUPPORT_AES_GCM */ + +#ifdef HKS_SUPPORT_AES_CCM +static int32_t AesEncryptCcm(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, struct HksBlob *cipherText, struct HksBlob *tagAead) +{ + mbedtls_ccm_context ctx; + mbedtls_ccm_init(&ctx); + + int32_t ret; + do { + ret = mbedtls_ccm_setkey(&ctx, MBEDTLS_CIPHER_ID_AES, key->data, key->size * HKS_BITS_PER_BYTE); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls aes ccm set key failed! mbedtls ret = 0x%X", ret); + break; + } + + const struct HksAeadParam *aeadParam = (struct HksAeadParam *)(usageSpec->algParam); + ret = mbedtls_ccm_encrypt_and_tag(&ctx, message->size, + aeadParam->nonce.data, aeadParam->nonce.size, aeadParam->aad.data, aeadParam->aad.size, + message->data, cipherText->data, tagAead->data, tagAead->size); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls aes ccm encrypt failed! mbedtls ret = 0x%X", ret); + (void)memset_s(cipherText->data, cipherText->size, 0, cipherText->size); + (void)memset_s(tagAead->data, tagAead->size, 0, tagAead->size); + break; + } + cipherText->size = message->size; + } while (0); + + mbedtls_ccm_free(&ctx); + return ret; +} + +static int32_t AesDecryptCcm(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, struct HksBlob *cipherText) +{ + mbedtls_ccm_context ctx; + mbedtls_ccm_init(&ctx); + + int32_t ret; + do { + ret = mbedtls_ccm_setkey(&ctx, MBEDTLS_CIPHER_ID_AES, key->data, key->size * HKS_BITS_PER_BYTE); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls aes ccm set key failed! mbedtls ret = 0x%X", ret); + break; + } + + const struct HksAeadParam *aeadParam = (struct HksAeadParam *)(usageSpec->algParam); + ret = mbedtls_ccm_auth_decrypt(&ctx, message->size, aeadParam->nonce.data, aeadParam->nonce.size, + aeadParam->aad.data, aeadParam->aad.size, message->data, cipherText->data, + aeadParam->tagDec.data, aeadParam->tagDec.size); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls aes ccm decrypt failed! mbedtls ret = 0x%X", ret); + (void)memset_s(cipherText->data, cipherText->size, 0, cipherText->size); + break; + } + cipherText->size = message->size; + } while (0); + + mbedtls_ccm_free(&ctx); + return ret; +} +#endif /* HKS_SUPPORT_AES_CCM */ + +static int32_t CheckKeySize(const struct HksBlob *key) +{ + if ((key->size != HKS_KEY_BYTES(HKS_AES_KEY_SIZE_128)) && (key->size != HKS_KEY_BYTES(HKS_AES_KEY_SIZE_192)) && + (key->size != HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256))) { + return HKS_ERROR_INVALID_KEY_SIZE; + } + + return HKS_SUCCESS; +} + +int32_t HksMbedtlsAesEncrypt(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, struct HksBlob *cipherText, struct HksBlob *tagAead) +{ + if (CheckKeySize(key) != HKS_SUCCESS) { + HKS_LOG_E("Invalid aes keySiz = 0x%X", key->size); + return HKS_ERROR_INVALID_KEY_SIZE; + } + + switch (usageSpec->mode) { +#if defined(HKS_SUPPORT_AES_CBC_NOPADDING) || defined(HKS_SUPPORT_AES_CBC_PKCS7) + case HKS_MODE_CBC: + return AesCbcCrypt(key, usageSpec, message, true, cipherText); +#endif +#ifdef HKS_SUPPORT_AES_GCM + case HKS_MODE_GCM: + return AesEncryptGcm(key, usageSpec, message, cipherText, tagAead); +#endif +#ifdef HKS_SUPPORT_AES_CCM + case HKS_MODE_CCM: + return AesEncryptCcm(key, usageSpec, message, cipherText, tagAead); +#endif + default: + HKS_LOG_E("Unsupport key alg! mode = 0x%X", usageSpec->mode); + return HKS_ERROR_INVALID_ARGUMENT; + } +} + +int32_t HksMbedtlsAesDecrypt(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, struct HksBlob *cipherText) +{ + if (CheckKeySize(key) != HKS_SUCCESS) { + HKS_LOG_E("Invalid aes keySize = 0x%X", key->size); + return HKS_ERROR_INVALID_KEY_SIZE; + } + + switch (usageSpec->mode) { +#if defined(HKS_SUPPORT_AES_CBC_NOPADDING) || defined(HKS_SUPPORT_AES_CBC_PKCS7) + case HKS_MODE_CBC: + return AesCbcCrypt(key, usageSpec, message, false, cipherText); +#endif +#ifdef HKS_SUPPORT_AES_GCM + case HKS_MODE_GCM: + return AesDecryptGcm(key, usageSpec, message, cipherText); +#endif +#ifdef HKS_SUPPORT_AES_CCM + case HKS_MODE_CCM: + return AesDecryptCcm(key, usageSpec, message, cipherText); +#endif + default: + HKS_LOG_E("Unsupport key alg! mode = 0x%X", usageSpec->mode); + return HKS_ERROR_INVALID_ARGUMENT; + } +} +#endif /* HKS_SUPPORT_AES_C */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_bn.c b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_bn.c new file mode 100644 index 00000000..2cef4a9e --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_bn.c @@ -0,0 +1,100 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#ifdef HKS_SUPPORT_BN_C + +#include "hks_mbedtls_bn.h" + +#include + +#include "hks_log.h" +#include "hks_mbedtls_common.h" + +static int32_t CheckBnExpModNx(const struct HksBlob *n, const struct HksBlob *x) +{ + /* zero is even number, so doesn't have to be checked */ + if ((n->data[n->size - 1] & 0x1) == 0x0) { + HKS_LOG_E("The param n(modular) must be odd!"); + return HKS_ERROR_INVALID_ARGUMENT; + } + + if (x->size < n->size) { + HKS_LOG_E("The param x's size is too samll! x size = 0x%X", x->size); + return HKS_ERROR_BUFFER_TOO_SMALL; + } + + return HKS_SUCCESS; +} + +int32_t HksMbedtlsBnExpMod(const struct HksBlob *a, + const struct HksBlob *e, const struct HksBlob *n, struct HksBlob *x) +{ + int32_t ret = CheckBnExpModNx(n, x); + if (ret != HKS_SUCCESS) { + return ret; + } + + mbedtls_mpi bnX; + mbedtls_mpi bnA; + mbedtls_mpi bnE; + mbedtls_mpi bnN; + + mbedtls_mpi_init(&bnX); + mbedtls_mpi_init(&bnA); + mbedtls_mpi_init(&bnE); + mbedtls_mpi_init(&bnN); + + do { + ret = mbedtls_mpi_read_binary(&bnA, a->data, a->size); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls mpi read a failed! mbedtls ret = 0x%X", ret); + break; + } + ret = mbedtls_mpi_read_binary(&bnE, e->data, e->size); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls mpi read e failed! mbedtls ret = 0x%X", ret); + break; + } + ret = mbedtls_mpi_read_binary(&bnN, n->data, n->size); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls mpi read n failed! mbedtls ret = 0x%X", ret); + break; + } + + ret = mbedtls_mpi_exp_mod(&bnX, &bnA, &bnE, &bnN, NULL); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls exp mod failed! mbedtls ret = 0x%X", ret); + break; + } + + ret = mbedtls_mpi_write_binary(&bnX, x->data, x->size); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls mpi write x failed! mbedtls ret = 0x%X", ret); + } + } while (0); + + mbedtls_mpi_free(&bnX); + mbedtls_mpi_free(&bnA); + mbedtls_mpi_free(&bnE); + mbedtls_mpi_free(&bnN); + return ret; +} +#endif /* HKS_SUPPORT_BN_C */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_common.c b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_common.c new file mode 100644 index 00000000..ecc29077 --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_common.c @@ -0,0 +1,70 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#include "hks_mbedtls_common.h" + +#include +#include + +#include "hks_log.h" + +/* the custom data of random seed */ +const unsigned char g_hksRandomSeedCustom[] = { + /* H K S */ + 0x48, 0x4B, 0x53 +}; + +int32_t HksToMbedtlsDigestAlg(const uint32_t hksAlg, uint32_t *mbedtlsAlg) +{ + switch (hksAlg) { + case HKS_DIGEST_SHA256: + *mbedtlsAlg = MBEDTLS_MD_SHA256; + break; + case HKS_DIGEST_SHA384: + *mbedtlsAlg = MBEDTLS_MD_SHA384; + break; + case HKS_DIGEST_SHA512: + *mbedtlsAlg = MBEDTLS_MD_SHA512; + break; + default: + HKS_LOG_E("Unsupported digest algorithm! digestAlg: 0x%X", hksAlg); + return HKS_ERROR_INVALID_DIGEST; + } + return HKS_SUCCESS; +} + +int32_t HksCtrDrbgSeed(mbedtls_ctr_drbg_context *ctrDrbg, mbedtls_entropy_context *entropy) +{ + mbedtls_ctr_drbg_init(ctrDrbg); + mbedtls_entropy_init(entropy); + + /* use the g_hksRandomSeedCustom without string terminator */ + int32_t ret = mbedtls_ctr_drbg_seed(ctrDrbg, mbedtls_entropy_func, + entropy, g_hksRandomSeedCustom, sizeof(g_hksRandomSeedCustom)); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Ctr drbg seed failed! mbedtls ret = 0x%X", ret); + mbedtls_ctr_drbg_free(ctrDrbg); + mbedtls_entropy_free(entropy); + return ret; + } + + return HKS_SUCCESS; +} \ No newline at end of file diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_ecc.c b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_ecc.c new file mode 100644 index 00000000..0b2e8ced --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_ecc.c @@ -0,0 +1,285 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#ifdef _CUT_AUTHENTICATE_ +#undef HKS_SUPPORT_ECC_C +#endif /* _CUT_AUTHENTICATE_ */ + +#ifdef HKS_SUPPORT_ECC_C + +#include "hks_mbedtls_ecc.h" + +#include +#include +#include +#include + +#include "hks_log.h" +#include "hks_mbedtls_common.h" +#include "hks_mem.h" + +#define HKS_ECC_KEYPAIR_CNT 3 + +static int32_t HksMbedtlsEccCheckKeySize(const uint32_t keySize) +{ + if ((keySize != HKS_ECC_KEY_SIZE_256) && (keySize != HKS_ECC_KEY_SIZE_384)) { + HKS_LOG_E("Invalid ecc keySize! keySize = 0x%X", keySize); + return HKS_ERROR_INVALID_KEY_SIZE; + } + + return HKS_SUCCESS; +} + +int32_t GetEccGroupId(const uint32_t keyLen, mbedtls_ecp_group_id *grpId) +{ + switch (keyLen) { + case HKS_ECC_KEY_SIZE_256: + *grpId = MBEDTLS_ECP_DP_SECP256R1; + break; + case HKS_ECC_KEY_SIZE_384: + *grpId = MBEDTLS_ECP_DP_SECP384R1; + break; + default: + HKS_LOG_E("Unsupported key length! keyLen: 0x%X", keyLen); + return HKS_ERROR_INVALID_KEY_SIZE; + } + return HKS_SUCCESS; +} + +static int32_t EccKeyMaterialXyzSizeCheck(const struct KeyMaterialEcc *keyMaterial) +{ + const uint32_t maxKeyByteLen = HKS_ECC_KEY_SIZE_384 / HKS_BITS_PER_BYTE; + if ((keyMaterial->xSize > maxKeyByteLen) || + (keyMaterial->ySize > maxKeyByteLen) || (keyMaterial->zSize > maxKeyByteLen)) { + HKS_LOG_E("Invalid ecc keyMaterial! xSize = 0x%X, ySize = 0x%X, zSize = 0x%X", + keyMaterial->xSize, keyMaterial->ySize, keyMaterial->zSize); + return HKS_ERROR_INVALID_ARGUMENT; + } + + return HKS_SUCCESS; +} + +int32_t EccKeyCheck(const struct HksBlob *key) +{ + const struct KeyMaterialEcc *keyMaterial = (struct KeyMaterialEcc *)(key->data); + int32_t ret = HksMbedtlsEccCheckKeySize(keyMaterial->keySize); + if (ret != HKS_SUCCESS) { + return ret; + } + + ret = EccKeyMaterialXyzSizeCheck(keyMaterial); + if (ret != HKS_SUCCESS) { + return ret; + } + + if (key->size < (sizeof(struct KeyMaterialEcc) + keyMaterial->xSize + keyMaterial->ySize + keyMaterial->zSize)) { + HKS_LOG_E("Ecc key size too small! key size = 0x%X", key->size); + return HKS_ERROR_INVALID_KEY_INFO; + } + + return HKS_SUCCESS; +} + +#if defined(HKS_SUPPORT_ECDH_C) || defined(HKS_SUPPORT_ECDSA_C) +int32_t HksMbedtlsEccGetKeyCurveNist(const struct KeyMaterialEcc *keyMaterial, mbedtls_ecp_group_id *curve) +{ + if ((keyMaterial->keyAlg != HKS_ALG_ECC) && (keyMaterial->keyAlg != HKS_ALG_ECDH)) { + HKS_LOG_E("Invalid param key! key mode = 0x%X", keyMaterial->keyAlg); + return HKS_ERROR_INVALID_ARGUMENT; + } + + return GetEccGroupId(keyMaterial->keySize, curve); +} + +int32_t HksEccKeyMaterialToPub(const struct HksBlob *key, mbedtls_ecp_point *pub) +{ + const struct KeyMaterialEcc *keyMaterial = (struct KeyMaterialEcc *)(key->data); + + uint32_t offset = sizeof(*keyMaterial); + int32_t ret = mbedtls_mpi_read_binary(&(pub->X), key->data + offset, keyMaterial->xSize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Ecc keyMaterial to public key read X failed! mbedtls ret = 0x%X", ret); + return ret; + } + + offset = offset + keyMaterial->xSize; + ret = mbedtls_mpi_read_binary(&(pub->Y), key->data + offset, keyMaterial->ySize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Ecc keyMaterial to public key read Y failed! mbedtls ret = 0x%X", ret); + return ret; + } + + /* Z = 1, X and Y are its standard (affine) coordinates */ + ret = mbedtls_mpi_lset(&(pub->Z), 1); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Ecc keyMaterial to public key set Z failed! mbedtls ret = 0x%X", ret); + return ret; + } + + return HKS_SUCCESS; +} + +int32_t HksEccKeyMaterialToPri(const struct HksBlob *key, mbedtls_mpi *pri) +{ + const struct KeyMaterialEcc *keyMaterial = (struct KeyMaterialEcc *)(key->data); + + uint32_t offset = sizeof(*keyMaterial) + keyMaterial->xSize + keyMaterial->ySize; + int32_t ret = mbedtls_mpi_read_binary(pri, key->data + offset, keyMaterial->zSize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Ecc keyMaterial to private key read Z failed! mbedtls ret = 0x%X", ret); + return ret; + } + + return HKS_SUCCESS; +} +#endif /* HKS_SUPPORT_ECDH_C or HKS_SUPPORT_ECDSA_C */ + +#ifdef HKS_SUPPORT_ECC_GENERATE_KEY +static int32_t EccSaveKeyMaterial(const mbedtls_ecp_keypair *ecp, + const uint32_t keySize, struct HksBlob *key) +{ + /* public exponent x and y, and private exponent, so need size is: key_size / 8 * 3 */ + const uint32_t keyByteLen = keySize / HKS_BITS_PER_BYTE; + const uint32_t rawMaterialLen = sizeof(struct KeyMaterialEcc) + keyByteLen * HKS_ECC_KEYPAIR_CNT; + uint8_t *rawMaterial = (uint8_t *)HksMalloc(rawMaterialLen); + if (rawMaterial == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + (void)memset_s(rawMaterial, rawMaterialLen, 0, rawMaterialLen); + + /* ECC key data internel struct: struct KeyMaterialEcc + pubXData + pubYData + priData */ + struct KeyMaterialEcc *keyMaterial = (struct KeyMaterialEcc *)rawMaterial; + keyMaterial->keyAlg = HKS_ALG_ECC; + keyMaterial->keySize = keySize; + keyMaterial->xSize = keyByteLen; + keyMaterial->ySize = keyByteLen; + keyMaterial->zSize = keyByteLen; + + int32_t ret; + do { + uint32_t offset = sizeof(struct KeyMaterialEcc); + ret = mbedtls_mpi_write_binary(&(ecp->Q.X), rawMaterial + offset, keyMaterial->xSize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Save ecc keyMaterial write X failed! mbedtls ret = 0x%X", ret); + break; + } + + offset = offset + keyMaterial->xSize; + ret = mbedtls_mpi_write_binary(&(ecp->Q.Y), rawMaterial + offset, keyMaterial->ySize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Save ecc keyMaterial write Y failed! mbedtls ret = 0x%X", ret); + break; + } + + offset = offset + keyMaterial->ySize; + ret = mbedtls_mpi_write_binary(&(ecp->d), rawMaterial + offset, keyMaterial->zSize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Save ecc keyMaterial write D failed! mbedtls ret = 0x%X", ret); + break; + } + + key->data = rawMaterial; + key->size = rawMaterialLen; + } while (0); + + if (ret != HKS_MBEDTLS_SUCCESS) { + (void)memset_s(rawMaterial, rawMaterialLen, 0, rawMaterialLen); + HKS_FREE_PTR(rawMaterial); + } + + return ret; +} + +int32_t HksMbedtlsEccGenerateKey(const struct HksKeySpec *spec, struct HksBlob *key) +{ + mbedtls_ecp_group_id grpId; + int32_t ret = GetEccGroupId(spec->keyLen, &grpId); + if (ret != HKS_SUCCESS) { + return ret; + } + + mbedtls_entropy_context entropy; + mbedtls_ctr_drbg_context ctrDrbg; + ret = HksCtrDrbgSeed(&ctrDrbg, &entropy); + if (ret != HKS_SUCCESS) { + return ret; + } + + mbedtls_ecp_keypair ecp; + mbedtls_ecp_keypair_init(&ecp); + + do { + ret = mbedtls_ecp_gen_key(grpId, &ecp, mbedtls_ctr_drbg_random, &ctrDrbg); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls ecc generate key failed! ret = 0x%X", ret); + break; + } + + ret = EccSaveKeyMaterial(&ecp, spec->keyLen, key); + } while (0); + + mbedtls_ctr_drbg_free(&ctrDrbg); + mbedtls_entropy_free(&entropy); + mbedtls_ecp_keypair_free(&ecp); + return ret; +} +#endif /* HKS_SUPPORT_ECC_GENERATE_KEY */ + +#ifdef HKS_SUPPORT_ECC_GET_PUBLIC_KEY +static int32_t GetEccPubKeyCheckParams(const struct HksBlob *keyIn, const struct HksBlob *keyOut) +{ + int32_t ret = EccKeyCheck(keyIn); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* check keyOut size */ + const struct KeyMaterialEcc *keyMaterial = (struct KeyMaterialEcc *)(keyIn->data); + if (keyOut->size < (sizeof(struct KeyMaterialEcc) + keyMaterial->xSize + keyMaterial->ySize)) { + HKS_LOG_E("Ecc public keyOut size too small! keyOut size = 0x%X", keyOut->size); + return HKS_ERROR_BUFFER_TOO_SMALL; + } + + return HKS_SUCCESS; +} + +int32_t HksMbedtlsGetEccPubKey(const struct HksBlob *keyIn, struct HksBlob *keyOut) +{ + int32_t ret = GetEccPubKeyCheckParams(keyIn, keyOut); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* x + y, so need size is: sizeof(struct HksPubKeyInfo) + xSize + ySize */ + const struct KeyMaterialEcc *keyMaterial = (struct KeyMaterialEcc *)(keyIn->data); + uint32_t outLen = sizeof(struct KeyMaterialEcc) + keyMaterial->xSize + keyMaterial->ySize; + if (memcpy_s(keyOut->data, keyOut->size, (void *)keyMaterial, outLen) != EOK) { + HKS_LOG_E("Memcpy ecc public key fail!"); + (void)memset_s(keyOut->data, keyOut->size, 0, keyOut->size); + return HKS_ERROR_BAD_STATE; + } + ((struct KeyMaterialEcc *)(keyOut->data))->zSize = 0; + keyOut->size = outLen; + + return HKS_SUCCESS; +} +#endif /* HKS_SUPPORT_ECC_GET_PUBLIC_KEY */ +#endif /* HKS_SUPPORT_ECC_C */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_ecdh.c b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_ecdh.c new file mode 100644 index 00000000..30552c32 --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_ecdh.c @@ -0,0 +1,114 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#ifdef _CUT_AUTHENTICATE_ +#undef HKS_SUPPORT_ECDH_C +#endif /* _CUT_AUTHENTICATE_ */ + +#ifdef HKS_SUPPORT_ECDH_C + +#include "hks_mbedtls_ecdh.h" + +#include +#include +#include +#include +#include + +#include "hks_log.h" +#include "hks_mbedtls_common.h" +#include "hks_mbedtls_ecc.h" + +static int32_t EccKeyMaterialToCtx(const struct HksBlob *nativeKey, + const struct HksBlob *pubKey, mbedtls_ecdh_context *ctx) +{ + int32_t ret = HksEccKeyMaterialToPub(pubKey, &(ctx->Qp)); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Ecc keyMaterial to public key failed! ret = 0x%X", ret); + return ret; + } + + ret = HksEccKeyMaterialToPri(nativeKey, &(ctx->d)); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Ecc keyMaterial to private key failed! ret = 0x%X", ret); + } + + return ret; +} + +int32_t HksMbedtlsEcdh(const struct HksBlob *nativeKey, + const struct HksBlob *pubKey, const struct HksKeySpec *spec, struct HksBlob *sharedKey) +{ + int32_t ret = EccKeyCheck(pubKey); + if (ret != HKS_SUCCESS) { + return ret; + } + + mbedtls_ecp_group_id mbedtlsCurveNist = MBEDTLS_ECP_DP_NONE; + ret = HksMbedtlsEccGetKeyCurveNist((struct KeyMaterialEcc *)(nativeKey->data), &mbedtlsCurveNist); + if (ret != HKS_SUCCESS) { + return ret; + } + + mbedtls_ctr_drbg_context ctrDrbg; + mbedtls_entropy_context entropy; + ret = HksCtrDrbgSeed(&ctrDrbg, &entropy); + if (ret != HKS_SUCCESS) { + return ret; + } + + mbedtls_ecdh_context ctx; + mbedtls_ecdh_init(&ctx); + + do { + ret = mbedtls_ecp_group_load(&(ctx.grp), mbedtlsCurveNist); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls ecdh load group failed! mbedtls ret = 0x%X", ret); + break; + } + + ret = EccKeyMaterialToCtx(nativeKey, pubKey, &ctx); + if (ret != HKS_SUCCESS) { + break; + } + + ret = mbedtls_ecdh_compute_shared(&(ctx.grp), &(ctx.z), &(ctx.Qp), &(ctx.d), mbedtls_ctr_drbg_random, &ctrDrbg); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls ecdh shared key failed! mbedtls ret = 0x%X", ret); + break; + } + + const uint32_t keyByteLen = spec->keyLen / HKS_BITS_PER_BYTE; + ret = mbedtls_mpi_write_binary(&(ctx.z), sharedKey->data, keyByteLen); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls ecdh mpi write to sharedKey failed! mbedtls ret = 0x%X", ret); + (void)memset_s(sharedKey->data, sharedKey->size, 0, sharedKey->size); + break; + } + sharedKey->size = keyByteLen; + } while (0); + + mbedtls_ecdh_free(&ctx); + mbedtls_ctr_drbg_free(&ctrDrbg); + mbedtls_entropy_free(&entropy); + return ret; +} +#endif /* HKS_SUPPORT_ECDH_C */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_ecdsa.c b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_ecdsa.c new file mode 100644 index 00000000..9ca5c449 --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_ecdsa.c @@ -0,0 +1,138 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#ifdef _CUT_AUTHENTICATE_ +#undef HKS_SUPPORT_ECDSA_C +#endif /* _CUT_AUTHENTICATE_ */ + +#ifdef HKS_SUPPORT_ECDSA_C + +#include "hks_mbedtls_ecdsa.h" + +#include +#include +#include +#include + +#include "hks_log.h" +#include "hks_mbedtls_common.h" +#include "hks_mbedtls_ecc.h" + +/* users must ensure the input params not null */ +int32_t HksMbedtlsEcdsaSign(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, struct HksBlob *signature) +{ + int32_t ret = EccKeyCheck(key); + if (ret != HKS_SUCCESS) { + return ret; + } + + mbedtls_ecp_group_id curveNist = MBEDTLS_ECP_DP_NONE; + ret = HksMbedtlsEccGetKeyCurveNist((struct KeyMaterialEcc *)(key->data), &curveNist); + if (ret != HKS_SUCCESS) { + return ret; + } + + mbedtls_ctr_drbg_context ctrDrbg; + mbedtls_entropy_context entropy; + ret = HksCtrDrbgSeed(&ctrDrbg, &entropy); + if (ret != HKS_SUCCESS) { + return ret; + } + + mbedtls_ecdsa_context ctx; + mbedtls_ecdsa_init(&ctx); + + do { + ret = mbedtls_ecp_group_load(&(ctx.grp), curveNist); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls ecp group load fail! mbedtls ret = 0x%X", ret); + break; + } + + ret = HksEccKeyMaterialToPri(key, &(ctx.d)); + if (ret != HKS_SUCCESS) { + break; + } + + uint32_t mbedtlsAlg; + ret = HksToMbedtlsDigestAlg(usageSpec->digest, &mbedtlsAlg); + if (ret != HKS_SUCCESS) { + break; + } + + ret = mbedtls_ecdsa_write_signature(&ctx, mbedtlsAlg, message->data, (size_t)message->size, + signature->data, (size_t *)&(signature->size), mbedtls_ctr_drbg_random, &ctrDrbg); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Ecc mbedtls sign fail! mbedtls ret = 0x%X", ret); + (void)memset_s(signature->data, signature->size, 0, signature->size); + } + } while (0); + + mbedtls_ctr_drbg_free(&ctrDrbg); + mbedtls_entropy_free(&entropy); + mbedtls_ecdsa_free(&ctx); + return ret; +} + +/* users must ensure the input params not null */ +int32_t HksMbedtlsEcdsaVerify(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, const struct HksBlob *signature) +{ + (void)usageSpec; + int32_t ret = EccKeyCheck(key); + if (ret != HKS_SUCCESS) { + return ret; + } + + mbedtls_ecp_group_id curveNist = MBEDTLS_ECP_DP_NONE; + ret = HksMbedtlsEccGetKeyCurveNist((struct KeyMaterialEcc *)(key->data), &curveNist); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Get ecc KeyCureNist fail! ret = 0x%X", ret); + return ret; + } + + mbedtls_ecdsa_context ctx; + mbedtls_ecdsa_init(&ctx); + + do { + ret = mbedtls_ecp_group_load(&(ctx.grp), curveNist); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls ecp group load fail! mbedtls ret = 0x%X", ret); + break; + } + + ret = HksEccKeyMaterialToPub(key, &(ctx.Q)); + if (ret != HKS_SUCCESS) { + break; + } + + ret = mbedtls_ecdsa_read_signature(&ctx, + message->data, message->size, signature->data, signature->size); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Ecc mbedtls verify fail! mbedtls ret = 0x%X", ret); + } + }while (0); + + mbedtls_ecdsa_free(&ctx); + return ret; +} +#endif /* HKS_SUPPORT_ECDSA_C */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_engine.c b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_engine.c new file mode 100644 index 00000000..3bca5046 --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_engine.c @@ -0,0 +1,308 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#include "hks_crypto_hal.h" + +#include +#include + +#include "hks_crypto_ed25519.h" +#include "hks_log.h" +#include "hks_mbedtls_aes.h" +#include "hks_mbedtls_bn.h" +#include "hks_mbedtls_common.h" +#include "hks_mbedtls_ecc.h" +#include "hks_mbedtls_ecdh.h" +#include "hks_mbedtls_ecdsa.h" +#include "hks_mbedtls_hash.h" +#include "hks_mbedtls_hmac.h" +#include "hks_mbedtls_kdf.h" +#include "hks_mbedtls_rsa.h" +#include "hks_mbedtls_x25519.h" +#include "hks_rkc.h" + +#ifdef _CUT_AUTHENTICATE_ +#undef HKS_SUPPORT_HASH_C +#undef HKS_SUPPORT_RSA_C +#undef HKS_SUPPORT_ECC_C +#undef HKS_SUPPORT_X25519_C +#undef HKS_SUPPORT_ED25519_C +#undef HKS_SUPPORT_KDF_PBKDF2 +#endif + +int32_t HksCryptoHalHmac(const struct HksBlob *key, uint32_t digestAlg, const struct HksBlob *msg, + struct HksBlob *mac) +{ +#ifdef HKS_SUPPORT_HMAC_C + return HksMbedtlsHmac(key, digestAlg, msg, mac); +#else + HKS_LOG_E("HKS_SUPPORT_HMAC_C macro is not on!"); + return HKS_ERROR_INVALID_ARGUMENT; +#endif +} + +#ifndef _CUT_AUTHENTICATE_ +int32_t HksCryptoHalHash(uint32_t alg, const struct HksBlob *msg, struct HksBlob *hash) +{ +#ifdef HKS_SUPPORT_HASH_C + return HksMbedtlsHash(alg, msg, hash); +#else + HKS_LOG_E("HKS_SUPPORT_HASH_C macro is not on!"); + return HKS_ERROR_INVALID_ARGUMENT; +#endif +} +#endif /* _CUT_AUTHENTICATE_ */ + +int32_t HksCryptoHalBnExpMod(struct HksBlob *x, const struct HksBlob *a, + const struct HksBlob *e, const struct HksBlob *n) +{ +#ifdef HKS_SUPPORT_BN_C + return HksMbedtlsBnExpMod(a, e, n, x); +#else + HKS_LOG_E("HKS_SUPPORT_BN_C macro is not on!"); + return HKS_ERROR_INVALID_ARGUMENT; +#endif +} + +#ifndef _CUT_AUTHENTICATE_ +int32_t HksCryptoHalGenerateKey(const struct HksKeySpec *spec, struct HksBlob *key) +{ + switch (spec->algType) { +#if defined(HKS_SUPPORT_AES_C) && defined(HKS_SUPPORT_AES_GENERATE_KEY) + case HKS_ALG_AES: + return HksMbedtlsAesGenerateKey(spec, key); +#endif +#if defined(HKS_SUPPORT_RSA_C) && defined(HKS_SUPPORT_RSA_GENERATE_KEY) + case HKS_ALG_RSA: + return HksMbedtlsRsaGenerateKey(spec, key); +#endif +#if defined(HKS_SUPPORT_ECC_C) && defined(HKS_SUPPORT_ECC_GENERATE_KEY) + case HKS_ALG_ECC: + return HksMbedtlsEccGenerateKey(spec, key); +#endif +#if defined(HKS_SUPPORT_X25519_C) && defined(HKS_SUPPORT_X25519_GENERATE_KEY) + case HKS_ALG_X25519: + return HksMbedtlsX25519GenerateKey(key); +#endif +#if defined(HKS_SUPPORT_ED25519_C) && defined(HKS_SUPPORT_ED25519_GENERATE_KEY) + case HKS_ALG_ED25519: + return HksEd25519GenerateKey(key); +#endif + default: + HKS_LOG_E("Unsupport alg type or macro is not on! type = 0x%X", spec->algType); + return HKS_ERROR_INVALID_ARGUMENT; + } +} + +int32_t HksCryptoHalGetMainKey(const struct HksBlob *message, struct HksBlob *mainKey) +{ + (void)message; + +#ifndef _HARDWARE_ROOT_KEY_ + return HksRkcGetMainKey(mainKey); +#else + /* + * Currently, root key is implemented using stubs. + * Product adaptation needs to be performed based on hardware capabilities. + */ + uint8_t stubBuf[] = { + 0x0c, 0xb4, 0x29, 0x39, 0xb7, 0x46, 0xa6, 0x4b, + 0xdd, 0xf3, 0x75, 0x4c, 0xe0, 0x73, 0x91, 0x51, + 0xc4, 0x88, 0xbe, 0xa4, 0xe1, 0x87, 0xb5, 0x42, + 0x06, 0x27, 0x08, 0x21, 0xe2, 0x8f, 0x9b, 0xc1, + }; + + if (memcpy_s(mainKey->data, mainKey->size, stubBuf, sizeof(stubBuf)) != EOK) { + HKS_LOG_E("memcpy failed, get stub main key failed"); + return HKS_ERROR_BAD_STATE; + } + return HKS_SUCCESS; +#endif +} + +int32_t HksCryptoHalGetPubKey(const struct HksBlob *keyIn, struct HksBlob *keyOut) +{ + /* KeyMaterialRsa, KeyMaterialEcc, KeyMaterial25519's size are same */ + if (keyIn->size < sizeof(struct KeyMaterialRsa)) { + return HKS_ERROR_INVALID_KEY_SIZE; + } + + struct KeyMaterialRsa *key = (struct KeyMaterialRsa *)(keyIn->data); + switch (key->keyAlg) { +#if defined(HKS_SUPPORT_RSA_C) && defined(HKS_SUPPORT_RSA_GET_PUBLIC_KEY) + case HKS_ALG_RSA: + return HksMbedtlsGetRsaPubKey(keyIn, keyOut); +#endif +#if defined(HKS_SUPPORT_ECC_C) && defined(HKS_SUPPORT_ECC_GET_PUBLIC_KEY) + case HKS_ALG_ECC: + return HksMbedtlsGetEccPubKey(keyIn, keyOut); +#endif +#if defined(HKS_SUPPORT_ED25519_C) && defined(HKS_SUPPORT_ED2519_GET_PUBLIC_KEY) + case HKS_ALG_ED25519: + return HksGetEd25519PubKey(keyIn, keyOut); +#endif +#if defined(HKS_SUPPORT_X25519_C) && defined(HKS_SUPPORT_X25519_GET_PUBLIC_KEY) + case HKS_ALG_X25519: + return HksMbedtlsGetX25519PubKey(keyIn, keyOut); +#endif + default: + HKS_LOG_E("Unsupport key mode or macro is not on! mode = 0x%X", key->keyAlg); + return HKS_ERROR_INVALID_ARGUMENT; + } +} +#endif /* _CUT_AUTHENTICATE_ */ + +int32_t HksCryptoHalDeriveKey(const struct HksBlob *mainKey, + const struct HksKeySpec *derivationSpec, struct HksBlob *derivedKey) +{ +#ifdef HKS_SUPPORT_KDF_C + return HksMbedtlsDeriveKey(mainKey, derivationSpec, derivedKey); +#else + HKS_LOG_E("HKS_SUPPORT_KDF_C macro is not on!"); + return HKS_ERROR_INVALID_ARGUMENT; +#endif +} + +#ifndef _CUT_AUTHENTICATE_ +int32_t HksCryptoHalAgreeKey(const struct HksBlob *nativeKey, const struct HksBlob *pubKey, + const struct HksKeySpec *spec, struct HksBlob *sharedKey) +{ + switch (spec->algType) { +#if defined(HKS_SUPPORT_ECC_C) && defined(HKS_SUPPORT_ECDH_C) + case HKS_ALG_ECDH: + return HksMbedtlsEcdh(nativeKey, pubKey, spec, sharedKey); +#endif +#if defined(HKS_SUPPORT_X25519_C) && defined(HKS_SUPPORT_X25519_AGREE_KEY) + case HKS_ALG_X25519: + return HksMbedtlsX25519KeyAgreement(nativeKey, pubKey, sharedKey); +#endif +#ifdef HKS_SUPPORT_ED25519_TO_X25519 + case HKS_ALG_ED25519: + return HksMbedtlsEd25519KeyAgreement(nativeKey, pubKey, sharedKey); +#endif + default: + HKS_LOG_E("Unsupport alg or macro is not on! alg = 0x%X", spec->algType); + return HKS_ERROR_INVALID_ARGUMENT; + } +} + +int32_t HksCryptoHalSign(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, struct HksBlob *signature) +{ + switch (usageSpec->algType) { +#if defined(HKS_SUPPORT_RSA_C) && defined(HKS_SUPPORT_RSA_SIGN_VERIFY) + case HKS_ALG_RSA: + return HksMbedtlsRsaSign(key, usageSpec, message, signature); +#endif +#if defined(HKS_SUPPORT_ECC_C) && defined(HKS_SUPPORT_ECDSA_C) + case HKS_ALG_ECC: + return HksMbedtlsEcdsaSign(key, usageSpec, message, signature); +#endif +#if defined(HKS_SUPPORT_ED25519_C) && defined(HKS_SUPPORT_ED25519_SIGN_VERIFY) + case HKS_ALG_ED25519: + return HksEd25519Sign(key, message, signature); +#endif + default: + HKS_LOG_E("Unsupport alg or macro is not on! alg = 0x%X", usageSpec->algType); + return HKS_ERROR_INVALID_ARGUMENT; + } +} + +int32_t HksCryptoHalVerify(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, const struct HksBlob *signature) +{ + switch (usageSpec->algType) { +#if defined(HKS_SUPPORT_RSA_C) && defined(HKS_SUPPORT_RSA_SIGN_VERIFY) + case HKS_ALG_RSA: + return HksMbedtlsRsaVerify(key, usageSpec, message, signature); +#endif +#if defined(HKS_SUPPORT_ECC_C) && defined(HKS_SUPPORT_ECDSA_C) + case HKS_ALG_ECC: + return HksMbedtlsEcdsaVerify(key, usageSpec, message, signature); +#endif +#if defined(HKS_SUPPORT_ED25519_C) && defined(HKS_SUPPORT_ED25519_SIGN_VERIFY) + case HKS_ALG_ED25519: + return HksEd25519Verify(key, message, signature); +#endif + default: + HKS_LOG_E("Unsupport alg or macro is not on! alg = 0x%X", usageSpec->algType); + return HKS_ERROR_INVALID_ARGUMENT; + } +} +#endif /* _CUT_AUTHENTICATE_ */ + +int32_t HksCryptoHalFillRandom(struct HksBlob *randomData) +{ + mbedtls_entropy_context entropy; + mbedtls_ctr_drbg_context ctrDrbg; + int32_t ret = HksCtrDrbgSeed(&ctrDrbg, &entropy); + if (ret != HKS_SUCCESS) { + return ret; + } + + do { + ret = mbedtls_ctr_drbg_random(&ctrDrbg, randomData->data, randomData->size); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls random failed! mbedtls ret = 0x%X", ret); + (void)memset_s(randomData->data, randomData->size, 0, randomData->size); + } + } while (0); + + mbedtls_ctr_drbg_free(&ctrDrbg); + mbedtls_entropy_free(&entropy); + return ret; +} + +int32_t HksCryptoHalEncrypt(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, struct HksBlob *cipherText, struct HksBlob *tagAead) +{ + switch (usageSpec->algType) { +#ifdef HKS_SUPPORT_AES_C + case HKS_ALG_AES: + return HksMbedtlsAesEncrypt(key, usageSpec, message, cipherText, tagAead); +#endif +#if defined(HKS_SUPPORT_RSA_C) && defined(HKS_SUPPORT_RSA_CRYPT) + case HKS_ALG_RSA: + return HksMbedtlsRsaCrypt(key, usageSpec, message, true, cipherText); +#endif + default: + HKS_LOG_E("Unsupport alg or macro is not on! alg = 0x%X", usageSpec->algType); + return HKS_ERROR_INVALID_ARGUMENT; + } +} + +int32_t HksCryptoHalDecrypt(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, struct HksBlob *cipherText) +{ + switch (usageSpec->algType) { +#ifdef HKS_SUPPORT_AES_C + case HKS_ALG_AES: + return HksMbedtlsAesDecrypt(key, usageSpec, message, cipherText); +#endif +#if defined(HKS_SUPPORT_RSA_C) && defined(HKS_SUPPORT_RSA_CRYPT) + case HKS_ALG_RSA: + return HksMbedtlsRsaCrypt(key, usageSpec, message, false, cipherText); +#endif + default: + HKS_LOG_E("Unsupport alg or macro is not on! alg = 0x%X", usageSpec->algType); + return HKS_ERROR_INVALID_ARGUMENT; + } +} diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_hash.c b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_hash.c new file mode 100644 index 00000000..7678da9c --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_hash.c @@ -0,0 +1,66 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#ifdef _CUT_AUTHENTICATE_ +#undef HKS_SUPPORT_HASH_C +#endif /* _CUT_AUTHENTICATE_ */ + +#ifdef HKS_SUPPORT_HASH_C + +#include "hks_mbedtls_hash.h" + +#include +#include + +#include "hks_common_check.h" +#include "hks_log.h" +#include "hks_mbedtls_common.h" + +int32_t HksMbedtlsHash(uint32_t alg, const struct HksBlob *msg, struct HksBlob *hash) +{ + int32_t ret; + switch (alg) { + case HKS_DIGEST_SHA256: + ret = mbedtls_sha256_ret(msg->data, msg->size, hash->data, 0); /* 0 for SHA-256 */ + break; + case HKS_DIGEST_SHA384: + ret = mbedtls_sha512_ret(msg->data, msg->size, hash->data, 1); /* 1 for SHA-384 */ + break; + case HKS_DIGEST_SHA512: + ret = mbedtls_sha512_ret(msg->data, msg->size, hash->data, 0); /* 0 for SHA-512 */ + break; + default: + return HKS_ERROR_INVALID_DIGEST; + } + + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls hash failed! mbedtls ret = 0x%X", ret); + return ret; + } + + ret = HksGetDigestLen(alg, &(hash->size)); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Get digest len failed!"); + } + + return ret; +} +#endif /* HKS_SUPPORT_HASH_C */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_hmac.c b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_hmac.c new file mode 100644 index 00000000..9914df8f --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_hmac.c @@ -0,0 +1,57 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#ifdef HKS_SUPPORT_HMAC_C + +#include "hks_mbedtls_hmac.h" + +#include + +#include "hks_common_check.h" +#include "hks_log.h" +#include "hks_mbedtls_common.h" + +int32_t HksMbedtlsHmac(const struct HksBlob *key, + uint32_t digestAlg, const struct HksBlob *msg, struct HksBlob *mac) +{ + /* input params have been checked */ + uint32_t mbedtlsAlg; + int32_t ret = HksToMbedtlsDigestAlg(digestAlg, &mbedtlsAlg); + if (ret != HKS_SUCCESS) { + return ret; + } + + ret = mbedtls_md_hmac(mbedtls_md_info_from_type(mbedtlsAlg), + key->data, key->size, msg->data, msg->size, mac->data); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls hmac failed! mbedtls ret = 0x%X", ret); + (void)memset_s(mac->data, mac->size, 0, mac->size); + return ret; + } + + ret = HksGetDigestLen(digestAlg, &(mac->size)); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Get digest len failed!"); + } + + return ret; +} +#endif /* HKS_SUPPORT_HMAC_C */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_kdf.c b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_kdf.c new file mode 100644 index 00000000..9034fe7f --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_kdf.c @@ -0,0 +1,112 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#ifdef HKS_SUPPORT_KDF_C + +#include "hks_mbedtls_kdf.h" + +#include +#include +#include + +#include "hks_log.h" +#include "hks_mbedtls_common.h" +#include "hks_type_inner.h" + +#ifdef _CUT_AUTHENTICATE +#undef HKS_SUPPORT_KDF_PBKDF2 +#endif + +#ifdef HKS_SUPPORT_KDF_PBKDF2 +static int32_t DeriveKeyPbkdf2(const struct HksBlob *mainKey, const struct HksKeyDerivationParam *derParam, + const mbedtls_md_info_t *info, struct HksBlob *derivedKey) +{ + mbedtls_md_context_t ctx; + mbedtls_md_init(&ctx); + + int32_t ret; + do { + ret = mbedtls_md_setup(&ctx, info, 1); /* 1 for using HMAC */ + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls md setup failed! mbedtls ret = 0x%X", ret); + break; + } + + ret = mbedtls_pkcs5_pbkdf2_hmac(&ctx, mainKey->data, mainKey->size, derParam->salt.data, + derParam->salt.size, derParam->iterations, derivedKey->size, derivedKey->data); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls pbkdf2 failed! mbedtls ret = 0x%X", ret); + (void)memset_s(derivedKey->data, derivedKey->size, 0, derivedKey->size); + } + } while (0); + + mbedtls_md_free(&ctx); + return ret; +} +#endif /* HKS_SUPPORT_KDF_PBKDF2 */ + +#ifdef HKS_SUPPORT_KDF_HKDF +static int32_t DeriveKeyHkdf(const struct HksBlob *mainKey, const struct HksKeyDerivationParam *derParam, + const mbedtls_md_info_t *info, struct HksBlob *derivedKey) +{ + int32_t ret = mbedtls_hkdf(info, derParam->salt.data, derParam->salt.size, mainKey->data, mainKey->size, + derParam->info.data, derParam->info.size, derivedKey->data, derivedKey->size); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls hkdf failed! mbedtls ret = 0x%X", ret); + (void)memset_s(derivedKey->data, derivedKey->size, 0, derivedKey->size); + } + + return ret; +} +#endif /* HKS_SUPPORT_KDF_HKDF */ + +int32_t HksMbedtlsDeriveKey(const struct HksBlob *mainKey, + const struct HksKeySpec *derivationSpec, struct HksBlob *derivedKey) +{ + const struct HksKeyDerivationParam *derParam = (struct HksKeyDerivationParam *)(derivationSpec->algParam); + + uint32_t mbedtlsAlg; + int32_t ret = HksToMbedtlsDigestAlg(derParam->digestAlg, &mbedtlsAlg); + if (ret != HKS_SUCCESS) { + return ret; + } + + const mbedtls_md_info_t *info = mbedtls_md_info_from_type(mbedtlsAlg); + if (info == NULL) { + HKS_LOG_E("Mbedtls get md info failed! mbedtls ret = 0x%X", ret); + return HKS_FAILURE; + } + + switch (derivationSpec->algType) { +#ifdef HKS_SUPPORT_KDF_PBKDF2 + case HKS_ALG_PBKDF2: + return DeriveKeyPbkdf2(mainKey, derParam, info, derivedKey); +#endif +#ifdef HKS_SUPPORT_KDF_HKDF + case HKS_ALG_HKDF: + return DeriveKeyHkdf(mainKey, derParam, info, derivedKey); +#endif + default: + HKS_LOG_E("Unsupport derive key alg! mode = 0x%X", derivationSpec->algType); + return HKS_ERROR_INVALID_ARGUMENT; + } +} +#endif /* HKS_SUPPORT_KDF_C */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_rsa.c b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_rsa.c new file mode 100644 index 00000000..d497b3d4 --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_rsa.c @@ -0,0 +1,402 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#ifdef _CUT_AUTHENTICATE_ +#undef HKS_SUPPORT_RSA_C +#endif + +#ifdef HKS_SUPPORT_RSA_C + +#include "hks_mbedtls_rsa.h" + +#include +#include +#include +#include + +#include "hks_log.h" +#include "hks_mbedtls_common.h" +#include "hks_mem.h" + +#define HKS_RSA_PUBLIC_EXPONENT 65537 +#define HKS_RSA_KEYPAIR_CNT 3 + +static int32_t RsaCheckKeySize(const uint32_t keySize) +{ + switch (keySize) { + case HKS_RSA_KEY_SIZE_2048: + case HKS_RSA_KEY_SIZE_3072: + case HKS_RSA_KEY_SIZE_4096: + break; + default: + HKS_LOG_E("Invalid rsa key size! keySize = 0x%X", keySize); + return HKS_ERROR_INVALID_KEY_SIZE; + } + + return HKS_SUCCESS; +} + +static int32_t RsaKeyMaterialNedSizeCheck(const struct KeyMaterialRsa *keyMaterial) +{ + const uint32_t maxKeyByteLen = HKS_RSA_KEY_SIZE_4096 / HKS_BITS_PER_BYTE; + if ((keyMaterial->nSize > maxKeyByteLen) || (keyMaterial->eSize > maxKeyByteLen) || + (keyMaterial->dSize > maxKeyByteLen)) { + HKS_LOG_E("Invalid rsa keyMaterial! nSize = 0x%X, eSize = 0x%X, dSize = 0x%X", + keyMaterial->nSize, keyMaterial->eSize, keyMaterial->dSize); + return HKS_ERROR_INVALID_ARGUMENT; + } + + return HKS_SUCCESS; +} + +static int32_t RsaKeyCheck(const struct HksBlob *key) +{ + const struct KeyMaterialRsa *keyMaterial = (struct KeyMaterialRsa *)(key->data); + + int32_t ret = RsaCheckKeySize(keyMaterial->keySize); + if (ret != HKS_SUCCESS) { + return ret; + } + + ret = RsaKeyMaterialNedSizeCheck(keyMaterial); + if (ret != HKS_SUCCESS) { + return ret; + } + + if (key->size < (sizeof(struct KeyMaterialRsa) + keyMaterial->nSize + keyMaterial->eSize + keyMaterial->dSize)) { + HKS_LOG_E("Rsa key size too small! key size = 0x%X", key->size); + return HKS_ERROR_INVALID_KEY_INFO; + } + + return HKS_SUCCESS; +} + +#ifdef HKS_SUPPORT_RSA_GENERATE_KEY +static int32_t RsaSaveKeyMaterial(const mbedtls_rsa_context *ctx, + const uint32_t keySize, struct HksBlob *key) +{ + const uint32_t keyByteLen = keySize / HKS_BITS_PER_BYTE; + const uint32_t rawMaterialLen = sizeof(struct KeyMaterialRsa) + keyByteLen * HKS_RSA_KEYPAIR_CNT; + uint8_t *rawMaterial = (uint8_t *)HksMalloc(rawMaterialLen); + if (rawMaterial == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + (void)memset_s(rawMaterial, rawMaterialLen, 0, rawMaterialLen); + + /* RSA key data internel struct: struct KeyMaterialRsa + nData + eData + dData */ + struct KeyMaterialRsa *keyMaterial = (struct KeyMaterialRsa *)rawMaterial; + keyMaterial->keyAlg = HKS_ALG_RSA; + keyMaterial->keySize = keySize; + keyMaterial->nSize = keyByteLen; + keyMaterial->eSize = keyByteLen; + keyMaterial->dSize = keyByteLen; + + int32_t ret; + do { + uint32_t offset = sizeof(*keyMaterial); + ret = mbedtls_mpi_write_binary(&(ctx->N), rawMaterial + offset, keyMaterial->nSize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Rsa save keyMaterial mpi write N failed! mbedtls ret = 0x%X", ret); + break; + } + + offset = offset + keyMaterial->nSize; + ret = mbedtls_mpi_write_binary(&(ctx->E), rawMaterial + offset, keyMaterial->eSize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Rsa save keyMaterial mpi write E failed! mbedtls ret = 0x%X", ret); + break; + } + + offset = offset + keyMaterial->eSize; + ret = mbedtls_mpi_write_binary(&(ctx->D), rawMaterial + offset, keyMaterial->dSize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Rsa save keyMaterial mpi write D failed! mbedtls ret = 0x%X", ret); + break; + } + + key->data = rawMaterial; + key->size = rawMaterialLen; + } while (0); + + if (ret != HKS_MBEDTLS_SUCCESS) { + (void)memset_s(rawMaterial, rawMaterialLen, 0, rawMaterialLen); + HKS_FREE_PTR(rawMaterial); + } + + return ret; +} + +int32_t HksMbedtlsRsaGenerateKey(const struct HksKeySpec *spec, struct HksBlob *key) +{ + mbedtls_rsa_context ctx; + mbedtls_rsa_init(&ctx, MBEDTLS_RSA_PKCS_V21, MBEDTLS_MD_SHA256); + ctx.padding = 0; + ctx.hash_id = 0; + + mbedtls_ctr_drbg_context ctrDrbg; + mbedtls_entropy_context entropy; + int32_t ret = HksCtrDrbgSeed(&ctrDrbg, &entropy); + if (ret != HKS_SUCCESS) { + return ret; + } + + do { + ret = mbedtls_rsa_gen_key(&ctx, mbedtls_ctr_drbg_random, &ctrDrbg, spec->keyLen, HKS_RSA_PUBLIC_EXPONENT); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls rsa generate key failed! mbedtls ret = 0x%X", ret); + break; + } + + ret = RsaSaveKeyMaterial(&ctx, spec->keyLen, key); + } while (0); + + mbedtls_rsa_free(&ctx); + mbedtls_ctr_drbg_free(&ctrDrbg); + mbedtls_entropy_free(&entropy); + return ret; +} +#endif /* HKS_SUPPORT_RSA_GENERATE_KEY */ + +#if defined(HKS_SUPPORT_RSA_CRYPT) || defined(HKS_SUPPORT_RSA_SIGN_VERIFY) +static int32_t RsaKeyMaterialToCtx(const struct HksBlob *key, + const bool needPrivateExponent, mbedtls_rsa_context *ctx) +{ + const struct KeyMaterialRsa *keyMaterial = (struct KeyMaterialRsa *)(key->data); + + mbedtls_mpi n; + mbedtls_mpi e; + mbedtls_mpi d; + + mbedtls_mpi_init(&n); + mbedtls_mpi_init(&e); + mbedtls_mpi_init(&d); + + int32_t ret; + do { + uint32_t offset = sizeof(*keyMaterial); + ret = mbedtls_mpi_read_binary(&n, key->data + offset, keyMaterial->nSize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls rsa keyMaterial to ctx read N failed! mbedtls ret = 0x%X", ret); + break; + } + + offset = offset + keyMaterial->nSize; + ret = mbedtls_mpi_read_binary(&e, key->data + offset, keyMaterial->eSize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls rsa keyMaterial to ctx read E failed! mbedtls ret = 0x%X", ret); + break; + } + + if (needPrivateExponent) { + offset = offset + keyMaterial->eSize; + ret = mbedtls_mpi_read_binary(&d, key->data + offset, keyMaterial->dSize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls rsa keyMaterial to ctx read D failed! mbedtls ret = 0x%X", ret); + break; + } + } + + ret = mbedtls_rsa_import(ctx, &n, NULL, NULL, (needPrivateExponent ? &d : NULL), &e); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls rsa keyMaterial to ctx import failed! mbedtls ret = 0x%X", ret); + break; + } + + ret = mbedtls_rsa_complete(ctx); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls rsa keyMaterial to ctx complete failed! mbedtls ret = 0x%X", ret); + } + } while (0); + + mbedtls_mpi_free(&n); + mbedtls_mpi_free(&e); + mbedtls_mpi_free(&d); + return ret; +} +#endif /* HKS_SUPPORT_RSA_CRYPT or HKS_SUPPORT_RSA_SIGN_VERIFY */ + +#ifdef HKS_SUPPORT_RSA_CRYPT +int32_t HksMbedtlsRsaCrypt(const struct HksBlob *key, const struct HksUsageSpec *usageSpec, + const struct HksBlob *message, const bool encrypt, struct HksBlob *cipherText) +{ + int32_t ret = RsaKeyCheck(key); + if (ret != HKS_SUCCESS) { + return ret; + } + + uint32_t mbedtlsAlg; + ret = HksToMbedtlsDigestAlg(usageSpec->digest, &mbedtlsAlg); + if (ret != HKS_SUCCESS) { + return ret; + } + + mbedtls_ctr_drbg_context ctrDrbg; + mbedtls_entropy_context entropy; + ret = HksCtrDrbgSeed(&ctrDrbg, &entropy); + if (ret != HKS_SUCCESS) { + return ret; + } + + mbedtls_rsa_context ctx; + mbedtls_rsa_init(&ctx, MBEDTLS_RSA_PKCS_V21, mbedtlsAlg); /* only support oaep padding */ + + do { + ret = RsaKeyMaterialToCtx(key, !encrypt, &ctx); /* encrypt don't need private exponent (d) */ + if (ret != HKS_SUCCESS) { + break; + } + + size_t outlen; + if (encrypt) { + ret = mbedtls_rsa_pkcs1_encrypt(&ctx, mbedtls_ctr_drbg_random, + &ctrDrbg, MBEDTLS_RSA_PUBLIC, (size_t)message->size, message->data, cipherText->data); + outlen = mbedtls_rsa_get_len(&ctx); + } else { + ret = mbedtls_rsa_pkcs1_decrypt(&ctx, mbedtls_ctr_drbg_random, &ctrDrbg, MBEDTLS_RSA_PRIVATE, + &outlen, message->data, cipherText->data, (size_t)cipherText->size); + } + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Mbedtls rsa crypt failed! mbedtls ret = 0x%X", ret); + (void)memset_s(cipherText->data, cipherText->size, 0, cipherText->size); + break; + } + cipherText->size = (uint32_t)outlen; + } while (0); + + mbedtls_rsa_free(&ctx); + mbedtls_ctr_drbg_free(&ctrDrbg); + mbedtls_entropy_free(&entropy); + return ret; +} +#endif /* HKS_SUPPORT_RSA_CRYPT */ + +#ifdef HKS_SUPPORT_RSA_SIGN_VERIFY +static int32_t HksMbedtlsRsaSignVerify(const struct HksBlob *key, + const struct HksUsageSpec *usageSpec, const struct HksBlob *message, const bool sign, struct HksBlob *signature) +{ + uint32_t mbedtlsAlg; + int32_t ret = HksToMbedtlsDigestAlg(usageSpec->digest, &mbedtlsAlg); + if (ret != HKS_SUCCESS) { + return ret; + } + + mbedtls_ctr_drbg_context ctrDrbg; + mbedtls_entropy_context entropy; + ret = HksCtrDrbgSeed(&ctrDrbg, &entropy); + if (ret != HKS_SUCCESS) { + return ret; + } + + mbedtls_rsa_context ctx; + mbedtls_rsa_init(&ctx, MBEDTLS_RSA_PKCS_V21, mbedtlsAlg); /* only support pss padding */ + + do { + ret = RsaKeyMaterialToCtx(key, sign, &ctx); /* sign need private exponent (d) */ + if (ret != HKS_SUCCESS) { + break; + } + + if (sign) { + ret = mbedtls_rsa_pkcs1_sign(&ctx, mbedtls_ctr_drbg_random, &ctrDrbg, + MBEDTLS_RSA_PRIVATE, mbedtlsAlg, message->size, message->data, signature->data); + } else { + ret = mbedtls_rsa_pkcs1_verify(&ctx, mbedtls_ctr_drbg_random, &ctrDrbg, + MBEDTLS_RSA_PUBLIC, mbedtlsAlg, message->size, message->data, signature->data); + } + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Mbedtls rsa sign/verify failed! mbedtls ret = 0x%X", ret); + (void)memset_s(signature->data, signature->size, 0, signature->size); + } + } while (0); + + if (sign) { + signature->size = mbedtls_rsa_get_len(&ctx); + } + + mbedtls_rsa_free(&ctx); + mbedtls_ctr_drbg_free(&ctrDrbg); + mbedtls_entropy_free(&entropy); + return ret; +} + +int32_t HksMbedtlsRsaSign(const struct HksBlob *key, + const struct HksUsageSpec *usageSpec, const struct HksBlob *message, struct HksBlob *signature) +{ + int32_t ret = RsaKeyCheck(key); + if (ret != HKS_SUCCESS) { + return ret; + } + + return HksMbedtlsRsaSignVerify(key, usageSpec, message, true, signature); /* true: is sign */ +} + +int32_t HksMbedtlsRsaVerify(const struct HksBlob *key, + const struct HksUsageSpec *usageSpec, const struct HksBlob *message, const struct HksBlob *signature) +{ + int32_t ret = RsaKeyCheck(key); + if (ret != HKS_SUCCESS) { + return ret; + } + + return HksMbedtlsRsaSignVerify(key, usageSpec, message, false, (struct HksBlob *)signature); /* false: is verify */ +} +#endif /* HKS_SUPPORT_RSA_SIGN_VERIFY */ + +#ifdef HKS_SUPPORT_RSA_GET_PUBLIC_KEY +static int32_t GetRsaPubKeyCheckParams(const struct HksBlob *keyIn, const struct HksBlob *keyOut) +{ + int32_t ret = RsaKeyCheck(keyIn); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* check keyOut size */ + const struct KeyMaterialRsa *keyMaterial = (struct KeyMaterialRsa *)(keyIn->data); + if (keyOut->size < (sizeof(struct HksPubKeyInfo) + keyMaterial->nSize + keyMaterial->eSize)) { + HKS_LOG_E("Rsa public keyOut size too small! keyOut size = 0x%X", keyOut->size); + return HKS_ERROR_BUFFER_TOO_SMALL; + } + + return HKS_SUCCESS; +} + +int32_t HksMbedtlsGetRsaPubKey(const struct HksBlob *keyIn, struct HksBlob *keyOut) +{ + int32_t ret = GetRsaPubKeyCheckParams(keyIn, keyOut); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* n + e, so need size is: sizeof(struct HksPubKeyInfo) + nSize + eSize */ + const struct KeyMaterialRsa *keyMaterial = (struct KeyMaterialRsa *)(keyIn->data); + const uint32_t outLen = sizeof(struct HksPubKeyInfo) + keyMaterial->nSize + keyMaterial->eSize; + if (memcpy_s(keyOut->data, keyOut->size, (void *)keyMaterial, outLen) != EOK) { + HKS_LOG_E("Memcpy rsa pub key failed!"); + (void)memset_s(keyOut->data, keyOut->size, 0, keyOut->size); + return HKS_ERROR_BAD_STATE; + } + ((struct KeyMaterialRsa *)(keyOut->data))->dSize = 0; + keyOut->size = outLen; + + return HKS_SUCCESS; +} +#endif /* HKS_SUPPORT_RSA_GET_PUBLIC_KEY */ +#endif /* HKS_SUPPORT_RSA_C */ diff --git a/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_x25519.c b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_x25519.c new file mode 100644 index 00000000..782563ed --- /dev/null +++ b/frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_x25519.c @@ -0,0 +1,875 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#ifdef _CUT_AUTHENTICATE_ +#undef HKS_SUPPORT_X25519_C +#endif /* _CUT_AUTHENTICATE_ */ + +#ifdef HKS_SUPPORT_X25519_C + +#include "hks_mbedtls_x25519.h" + +#include +#include +#include +#include +#include + +#ifdef HKS_SUPPORT_ED25519_TO_X25519 +#include "hks_crypto_adapter.h" +#endif + +#include "hks_log.h" +#include "hks_mbedtls_common.h" +#include "hks_mem.h" + +#define HKS_X25519_KEY_BITS 256 +#define HKS_X25519_KEY_BYTES 32 +#define HASH512_OUT_SIZE 64 + +struct HksCurveConstPara { + mbedtls_mpi mpiP; + mbedtls_mpi mpiOne; + mbedtls_mpi mpiD; + mbedtls_mpi mpiK; + mbedtls_mpi mpiCapitalA; + mbedtls_mpi mpiMinusA; + mbedtls_mpi mpiU; + mbedtls_mpi mpiQ; +}; + +#ifdef HKS_SUPPORT_ED25519_TO_X25519 +#define CURVE25519_KEY_BYTE_SIZE HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256) +static const uint8_t g_hksCurveParamP[CURVE25519_KEY_BYTE_SIZE] = { + 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xed +}; + +/* RFC 8032, one = 1 */ +static const uint8_t g_hksCurveParamOne[CURVE25519_KEY_BYTE_SIZE] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01 +}; + +/* RFC 8032, A non-zero element in the finite field GF(p), not equal to 1 */ +static const uint8_t g_hksCurveParamD[CURVE25519_KEY_BYTE_SIZE] = { + 0xa3, 0x78, 0x59, 0x13, 0xca, 0x4d, 0xeb, 0x75, 0xab, 0xd8, 0x41, 0x41, 0x4d, 0x0a, 0x70, 0x00, + 0x98, 0xe8, 0x79, 0x77, 0x79, 0x40, 0xc7, 0x8c, 0x73, 0xfe, 0x6f, 0x2b, 0xee, 0x6c, 0x03, 0x52 +}; + +/* RFC 8032, k = (p - 1) / 2 */ +static const uint8_t g_hksCurveParamK[CURVE25519_KEY_BYTE_SIZE] = { + 0xf6, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0x3f +}; + +/* RFC 8032, A = 486662 */ +static const uint8_t g_hksCurveParamCapitalA[CURVE25519_KEY_BYTE_SIZE] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x07, 0x6d, 0x06 +}; + +/* RFC 8032, -A = -486662 */ +static const uint8_t g_hksCurveParamMinusA[CURVE25519_KEY_BYTE_SIZE] = { + 0x7f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf8, 0x92, 0xe7 +}; + +/* RFC 8032, u = 2 */ +static const uint8_t g_hksCurveParamU[CURVE25519_KEY_BYTE_SIZE] = { + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, + 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x02 +}; + +/* RFC 8032, q = endian_swap(k) */ +static const uint8_t g_hksCurveParamQ[CURVE25519_KEY_BYTE_SIZE] = { + 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, + 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xf6 +}; +#endif + +static int32_t X25519CheckKeyMaterialPubPriSize(const struct KeyMaterial25519 *keyMaterial) +{ + if ((keyMaterial->pubKeySize > HKS_X25519_KEY_BYTES) || + (keyMaterial->priKeySize > HKS_X25519_KEY_BYTES)) { + HKS_LOG_E("Invalid x25519 keyMaterial! pubKeySize = 0x%X, priKeySize = 0x%X", + keyMaterial->pubKeySize, keyMaterial->priKeySize); + return HKS_ERROR_INVALID_ARGUMENT; + } + + return HKS_SUCCESS; +} + +static int32_t EndianSwap(uint8_t *pData, const int32_t length) +{ + if ((pData == NULL) || (length <= 0)) { + HKS_LOG_E("Endian swap invalid input!"); + return HKS_ERROR_INVALID_ARGUMENT; + } + + const int32_t end = length - 1; + const int32_t count = length / 2; /* 2: count is half of length */ + + for (int32_t i = 0; i < count; ++i) { + uint8_t tmp = pData[i]; + pData[i] = pData[end - i]; + pData[end - i] = tmp; + } + + return HKS_SUCCESS; +} + +static int32_t X25519CheckKeySize(const struct HksBlob *key, const struct KeyMaterial25519 *keyMaterial, bool isPubKey) +{ + if (key->size < (sizeof(struct KeyMaterial25519) + keyMaterial->pubKeySize + + (isPubKey ? 0 : keyMaterial->priKeySize))) { + HKS_LOG_E("X25519 key size too small! key size = 0x%X", key->size); + return HKS_ERROR_INVALID_KEY_INFO; + } + + return HKS_SUCCESS; +} + +static int32_t X25519CheckKeyMaterialSize(const struct HksBlob *priKey, const struct HksBlob *pubKey) +{ + const struct KeyMaterial25519 *priKm = (struct KeyMaterial25519 *)(priKey->data); + const struct KeyMaterial25519 *pubKm = (struct KeyMaterial25519 *)(pubKey->data); + + /* x25519's keySize is fixed at 256, so don't need to check */ + int32_t ret = X25519CheckKeyMaterialPubPriSize(priKm); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("invalid privateKey size"); + return ret; + } + ret = X25519CheckKeyMaterialPubPriSize(pubKm); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("invalid publicKey size"); + return ret; + } + + ret = X25519CheckKeySize(priKey, priKm, false); + if (ret != HKS_SUCCESS) { + return ret; + } + + return X25519CheckKeySize(priKey, pubKm, true); +} + +#ifdef HKS_SUPPORT_X25519_GENERATE_KEY +static int32_t X25519SaveKeyMaterial(const mbedtls_ecp_point *pub, + const mbedtls_mpi *pri, struct HksBlob *key) +{ + const uint32_t keyByteLen = HKS_X25519_KEY_BITS / HKS_BITS_PER_BYTE; + const uint32_t rawMaterialLen = sizeof(struct KeyMaterial25519) + keyByteLen + keyByteLen; + uint8_t *rawMaterial = (uint8_t *)HksMalloc(rawMaterialLen); + if (rawMaterial == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + (void)memset_s(rawMaterial, rawMaterialLen, 0, rawMaterialLen); + + struct KeyMaterial25519 *keyMaterial = (struct KeyMaterial25519 *)rawMaterial; + keyMaterial->keyAlg = HKS_ALG_X25519; + keyMaterial->keySize = HKS_X25519_KEY_BITS; + keyMaterial->pubKeySize = keyByteLen; + keyMaterial->priKeySize = keyByteLen; + + /* mbedtls mbedtls_ecp_point.X is x25519's public key */ + uint32_t offset = sizeof(struct KeyMaterial25519); + int32_t ret = mbedtls_mpi_write_binary(&(pub->X), rawMaterial + offset, keyMaterial->pubKeySize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls mpi write to x25519 public key failed! mbedtls ret = 0x%X", ret); + (void)memset_s(rawMaterial, rawMaterialLen, 0, rawMaterialLen); + HKS_FREE_PTR(rawMaterial); + return ret; + } + + ret = EndianSwap(rawMaterial + offset, keyMaterial->pubKeySize); + if (ret != HKS_SUCCESS) { + (void)memset_s(rawMaterial, rawMaterialLen, 0, rawMaterialLen); + HKS_FREE_PTR(rawMaterial); + return ret; + } + + offset = offset + keyMaterial->pubKeySize; + ret = mbedtls_mpi_write_binary(pri, rawMaterial + offset, keyMaterial->priKeySize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls mpi write to x25519 private key failed! mbedtls ret = 0x%X", ret); + (void)memset_s(rawMaterial, rawMaterialLen, 0, rawMaterialLen); + HKS_FREE_PTR(rawMaterial); + return ret; + } + + key->data = rawMaterial; + key->size = rawMaterialLen; + + return HKS_SUCCESS; +} + +int32_t HksMbedtlsX25519GenerateKey(struct HksBlob *key) +{ + mbedtls_ecp_group grp; + mbedtls_ecp_point pub; + mbedtls_mpi pri; + + mbedtls_ctr_drbg_context ctrDrbg; + mbedtls_entropy_context entropy; + int32_t ret = HksCtrDrbgSeed(&ctrDrbg, &entropy); + if (ret != HKS_SUCCESS) { + return ret; + } + + mbedtls_ecp_group_init(&grp); + mbedtls_ecp_point_init(&pub); + mbedtls_mpi_init(&pri); + + do { + ret = mbedtls_ecp_group_load(&grp, MBEDTLS_ECP_DP_CURVE25519); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls load x25519 group failed! mbedtls ret = 0x%X", ret); + break; + } + + ret = mbedtls_ecdh_gen_public(&grp, &pri, &pub, mbedtls_ctr_drbg_random, &ctrDrbg); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls generate x25519 key failed! mbedtls ret = 0x%X", ret); + break; + } + + ret = X25519SaveKeyMaterial(&pub, &pri, key); + } while (0); + + mbedtls_ecp_group_free(&grp); + mbedtls_ecp_point_free(&pub); + mbedtls_mpi_free(&pri); + mbedtls_ctr_drbg_free(&ctrDrbg); + mbedtls_entropy_free(&entropy); + return ret; +} +#endif /* HKS_SUPPORT_X25519_GENERATE_KEY */ + +#ifdef HKS_SUPPORT_X25519_AGREE_KEY +static int32_t X25519KeyMaterialToPub(const struct HksBlob *pubKey, mbedtls_ecp_point *pub) +{ + const struct KeyMaterial25519 *keyMaterial = (struct KeyMaterial25519 *)(pubKey->data); + uint32_t offset = sizeof(struct KeyMaterial25519); + + uint8_t *tmpPubKey = (uint8_t *)HksMalloc(keyMaterial->pubKeySize); + if (tmpPubKey == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + + int32_t ret; + do { + if (memcpy_s(tmpPubKey, keyMaterial->pubKeySize, pubKey->data + offset, keyMaterial->pubKeySize) != EOK) { + ret = HKS_ERROR_BAD_STATE; + break; + } + + ret = EndianSwap(tmpPubKey, keyMaterial->pubKeySize); + if (ret != HKS_SUCCESS) { + break; + } + + ret = mbedtls_mpi_read_binary(&(pub->X), tmpPubKey, keyMaterial->pubKeySize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls mpi read from x25519 public key failed! mbedtls ret = 0x%X", ret); + break; + } + + /* set initial coordinates. Z = 1, X and Y are its standard(affine) coordinates. */ + ret = mbedtls_mpi_lset(&(pub->Z), 1); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls mpi set Z = 1 failed! mbedtls ret = 0x%X", ret); + } + } while (0); + + HKS_FREE_PTR(tmpPubKey); + return ret; +} + +static int32_t X25519KeyMaterialToPri(const struct HksBlob *nativeKey, mbedtls_mpi *pri) +{ + const struct KeyMaterial25519 *keyMaterial = (struct KeyMaterial25519 *)(nativeKey->data); + + uint32_t offset = sizeof(struct KeyMaterial25519) + keyMaterial->pubKeySize; + int32_t ret = mbedtls_mpi_read_binary(pri, nativeKey->data + offset, keyMaterial->priKeySize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls mpi read from x25519 private key failed! mbedtls ret = 0x%X", ret); + return ret; + } + + return HKS_SUCCESS; +} + +int32_t HksMbedtlsX25519KeyAgreement(const struct HksBlob *nativeKey, + const struct HksBlob *pubKey, struct HksBlob *sharedKey) +{ + int32_t ret = X25519CheckKeyMaterialSize(nativeKey, pubKey); + if (ret != HKS_SUCCESS) { + return ret; + } + + mbedtls_ecdh_context ctx; + mbedtls_ecdh_init(&ctx); + + mbedtls_ctr_drbg_context ctrDrbg; + mbedtls_entropy_context entropy; + ret = HksCtrDrbgSeed(&ctrDrbg, &entropy); + if (ret != HKS_SUCCESS) { + return ret; + } + + do { + ret = mbedtls_ecp_group_load(&(ctx.grp), MBEDTLS_ECP_DP_CURVE25519); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls load x25519 group failed! mbedtls ret = 0x%X", ret); + break; + } + + ret = X25519KeyMaterialToPub(pubKey, &(ctx.Qp)); + if (ret != HKS_SUCCESS) { + break; + } + + ret = X25519KeyMaterialToPri(nativeKey, &(ctx.d)); + if (ret != HKS_SUCCESS) { + break; + } + + ret = mbedtls_ecdh_compute_shared(&(ctx.grp), &(ctx.z), &(ctx.Qp), &(ctx.d), mbedtls_ctr_drbg_random, &ctrDrbg); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls x25519 shared key failed! mbedtls ret = 0x%X", ret); + break; + } + + ret = mbedtls_mpi_write_binary(&(ctx.z), sharedKey->data, HKS_X25519_KEY_BYTES); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls mpi write to shared key failed! mbedtls ret = 0x%X", ret); + (void)memset_s(sharedKey->data, sharedKey->size, 0, sharedKey->size); + break; + } + sharedKey->size = HKS_X25519_KEY_BYTES; + + ret = EndianSwap(sharedKey->data, sharedKey->size); + } while (0); + + mbedtls_ecdh_free(&ctx); + mbedtls_ctr_drbg_free(&ctrDrbg); + mbedtls_entropy_free(&entropy); + return ret; +} +#endif /* HKS_SUPPORT_X25519_AGREE_KEY */ + +#ifdef HKS_SUPPORT_X25519_GET_PUBLIC_KEY +static int32_t GetX25519PubKeyCheckParams(const struct HksBlob *keyIn, const struct HksBlob *keyOut) +{ + const struct KeyMaterial25519 *keyMaterial = (struct KeyMaterial25519 *)(keyIn->data); + int32_t ret = X25519CheckKeyMaterialPubPriSize(keyMaterial); + if (ret != HKS_SUCCESS) { + return ret; + } + + ret = X25519CheckKeySize(keyIn, keyMaterial, false); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* check keyOut */ + if (keyOut->size < (sizeof(struct KeyMaterial25519) + keyMaterial->pubKeySize)) { + HKS_LOG_E("X25519 public keyOut size too small! keyOut size = 0x%X", keyOut->size); + return HKS_ERROR_BUFFER_TOO_SMALL; + } + + return HKS_SUCCESS; +} + +int32_t HksMbedtlsGetX25519PubKey(const struct HksBlob *keyIn, struct HksBlob *keyOut) +{ + int32_t ret = GetX25519PubKeyCheckParams(keyIn, keyOut); + if (ret != HKS_SUCCESS) { + return ret; + } + + const struct KeyMaterial25519 *keyMaterial = (struct KeyMaterial25519 *)(keyIn->data); + const uint32_t outLen = sizeof(struct KeyMaterial25519) + keyMaterial->pubKeySize; + if (memcpy_s(keyOut->data, keyOut->size, (void *)keyMaterial, outLen) != EOK) { + HKS_LOG_E("Memcpy x25519 pub key failed!"); + return HKS_ERROR_BAD_STATE; + } + ((struct KeyMaterial25519 *)(keyOut->data))->priKeySize = 0; + keyOut->size = outLen; + + return HKS_SUCCESS; +} +#endif /* HKS_SUPPORT_X25519_GET_PUBLIC_KEY */ + +#if defined(HKS_SUPPORT_ED25519_TO_X25519) +static void HksCurveInitConstPara(struct HksCurveConstPara *para) +{ + mbedtls_mpi_init(&(para->mpiP)); + mbedtls_mpi_init(&(para->mpiOne)); + mbedtls_mpi_init(&(para->mpiD)); + mbedtls_mpi_init(&(para->mpiK)); + mbedtls_mpi_init(&(para->mpiCapitalA)); + mbedtls_mpi_init(&(para->mpiMinusA)); + mbedtls_mpi_init(&(para->mpiU)); + mbedtls_mpi_init(&(para->mpiQ)); +} + +static void HksCurveFreeConstPara(struct HksCurveConstPara *para) +{ + mbedtls_mpi_free(&(para->mpiP)); + mbedtls_mpi_free(&(para->mpiOne)); + mbedtls_mpi_free(&(para->mpiD)); + mbedtls_mpi_free(&(para->mpiK)); + mbedtls_mpi_free(&(para->mpiCapitalA)); + mbedtls_mpi_free(&(para->mpiMinusA)); + mbedtls_mpi_free(&(para->mpiU)); + mbedtls_mpi_free(&(para->mpiQ)); +} + +static int32_t HksCurveSetConstPara(struct HksCurveConstPara *para) +{ + int32_t ret = mbedtls_mpi_read_binary(&(para->mpiP), g_hksCurveParamP, CURVE25519_KEY_BYTE_SIZE); + if (ret != HKS_MBEDTLS_SUCCESS) { + return ret; + } + + ret = mbedtls_mpi_read_binary(&(para->mpiOne), g_hksCurveParamOne, CURVE25519_KEY_BYTE_SIZE); + if (ret != HKS_MBEDTLS_SUCCESS) { + return ret; + } + + ret = mbedtls_mpi_read_binary(&(para->mpiD), g_hksCurveParamD, CURVE25519_KEY_BYTE_SIZE); + if (ret != HKS_MBEDTLS_SUCCESS) { + return ret; + } + + ret = mbedtls_mpi_read_binary(&(para->mpiK), g_hksCurveParamK, CURVE25519_KEY_BYTE_SIZE); + if (ret != HKS_MBEDTLS_SUCCESS) { + return ret; + } + + ret = mbedtls_mpi_read_binary(&(para->mpiCapitalA), g_hksCurveParamCapitalA, CURVE25519_KEY_BYTE_SIZE); + if (ret != HKS_MBEDTLS_SUCCESS) { + return ret; + } + + ret = mbedtls_mpi_read_binary(&(para->mpiMinusA), g_hksCurveParamMinusA, CURVE25519_KEY_BYTE_SIZE); + if (ret != HKS_MBEDTLS_SUCCESS) { + return ret; + } + + ret = mbedtls_mpi_read_binary(&(para->mpiU), g_hksCurveParamU, CURVE25519_KEY_BYTE_SIZE); + if (ret != HKS_MBEDTLS_SUCCESS) { + return ret; + } + + ret = mbedtls_mpi_read_binary(&(para->mpiQ), g_hksCurveParamQ, CURVE25519_KEY_BYTE_SIZE); + if (ret != HKS_MBEDTLS_SUCCESS) { + return ret; + } + + return HKS_SUCCESS; +} +#endif /* HKS_SUPPORT_ED25519_TO_X25519 */ + +#ifdef HKS_SUPPORT_ED25519_TO_X25519 +struct HksEd25519ToX25519Blob { + struct HksBlob rawNativeKey; + struct HksBlob rawPubKey; + struct HksBlob rawX25519NativeKey; + struct HksBlob rawX25519PubKey; + struct HksBlob kmX25519NativeKey; + struct HksBlob kmX25519PubKey; +}; + +static int32_t HksCurvePskCalcA(const mbedtls_mpi *edwardsY, + const struct HksCurveConstPara *curvePara, mbedtls_mpi *mpiA) +{ + mbedtls_mpi mpiE; + mbedtls_mpi swap; + + mbedtls_mpi_init(&mpiE); + mbedtls_mpi_init(&swap); + + int32_t ret = HKS_ERROR_CRYPTO_ENGINE_ERROR; + do { + /* mpiA := (y ^ 2 - 1) / (1 + d * y ^ 2) */ + if (mbedtls_mpi_mul_mpi(&mpiE, edwardsY, edwardsY) != HKS_MBEDTLS_SUCCESS) { + break; + } + + if (mbedtls_mpi_mod_mpi(&mpiE, &mpiE, &(curvePara->mpiP)) != HKS_MBEDTLS_SUCCESS) { + break; + } + + if (mbedtls_mpi_mul_mpi(&swap, &(curvePara->mpiD), &mpiE) != HKS_MBEDTLS_SUCCESS) { + break; + } + + if (mbedtls_mpi_add_mpi(&swap, &swap, &(curvePara->mpiOne)) != HKS_MBEDTLS_SUCCESS) { + break; + } + + if (mbedtls_mpi_mod_mpi(&swap, &swap, &(curvePara->mpiP)) != HKS_MBEDTLS_SUCCESS) { + break; + } + + if (mbedtls_mpi_inv_mod(&swap, &swap, &(curvePara->mpiP)) != HKS_MBEDTLS_SUCCESS) { + break; + } + + if (mbedtls_mpi_sub_mpi(&mpiE, &mpiE, &(curvePara->mpiOne)) != HKS_MBEDTLS_SUCCESS) { + break; + } + + if (mbedtls_mpi_mod_mpi(&mpiE, &mpiE, &(curvePara->mpiP)) != HKS_MBEDTLS_SUCCESS) { + break; + } + + if (mbedtls_mpi_mul_mpi(&mpiE, &mpiE, &swap) != HKS_MBEDTLS_SUCCESS) { + break; + } + + if (mbedtls_mpi_mod_mpi(&mpiE, &mpiE, &(curvePara->mpiP)) != HKS_MBEDTLS_SUCCESS) { + break; + } + + if (mbedtls_mpi_add_mpi(&mpiE, &mpiE, &(curvePara->mpiP)) != HKS_MBEDTLS_SUCCESS) { + break; + } + + /* Sliding-window exponentiation: mpiA = e^k mod p */ + ret = mbedtls_mpi_exp_mod(mpiA, &mpiE, &(curvePara->mpiK), &(curvePara->mpiP), NULL); + } while (0); + + mbedtls_mpi_free(&mpiE); + mbedtls_mpi_free(&swap); + + return ret; +} + +static int32_t HksCurvePskCheckA(mbedtls_mpi *mpiA, const uint8_t *ed25519PublicKey, + size_t len, const struct HksCurveConstPara *curvePara) +{ + /* Check, whether a is a square modulo p (including a = 0) */ + int32_t ret = mbedtls_mpi_cmp_mpi(&(curvePara->mpiOne), mpiA); + if (ret > 0) { + HKS_LOG_E("a is not a square modulo p"); + return HKS_ERROR_INVALID_PUBLIC_KEY; + } + + /* If a == p, the parity bit must be 0 */ + ret = mbedtls_mpi_cmp_mpi(mpiA, &(curvePara->mpiP)); + if (ret == 0) { + uint32_t value = ed25519PublicKey[len - 1] >> 7; /* 7: RFC8032 */ + /* The previous check has guaranteed that a must be greater than or equal to one */ + value = (value & (uint32_t)mbedtls_mpi_sub_mpi(mpiA, mpiA, &(curvePara->mpiOne))); + if (value != 0) { + HKS_LOG_E("the parity bit not zero"); + return HKS_ERROR_INVALID_PUBLIC_KEY; + } + } + + return HKS_SUCCESS; +} + +static int32_t HksCurvePskCheckPoint(const mbedtls_mpi *edwardsY, const uint8_t *ed25519PublicKey, + size_t len, const struct HksCurveConstPara *curvePara) +{ + mbedtls_mpi mpiA; + mbedtls_mpi_init(&mpiA); + + int32_t ret; + do { + /* if y >= p, return error */ + ret = mbedtls_mpi_cmp_mpi(edwardsY, &(curvePara->mpiP)); + if (ret >= 0) { + HKS_LOG_E("edwardsY is greater than or equal to p", ret); + ret = HKS_ERROR_INVALID_PUBLIC_KEY; + break; + } + + /* if y == 1, return error */ + ret = mbedtls_mpi_cmp_mpi(edwardsY, &(curvePara->mpiOne)); + if (ret == 0) { + HKS_LOG_E("edwards_y equals one"); + ret = HKS_ERROR_INVALID_PUBLIC_KEY; + break; + } + + /* a := (y ^ 2 - 1) / (1 + d * y ^ 2) */ + ret = HksCurvePskCalcA(edwardsY, curvePara, &mpiA); + if (ret != HKS_SUCCESS) + break; + + ret = HksCurvePskCheckA(&mpiA, ed25519PublicKey, len, curvePara); + } while (0); + + mbedtls_mpi_free(&mpiA); + return ret; +} + +static int32_t HksCurvePskCalcC(const mbedtls_mpi *edwardsY, struct HksBlob *x25519Key, + const struct HksCurveConstPara *curvePara) +{ + mbedtls_mpi curveX; + mbedtls_mpi result; + + mbedtls_mpi_init(&curveX); + mbedtls_mpi_init(&result); + + int32_t ret; + do { + /* If y != 1, c := (1 + y) / (1 - y), otherwise c := 0 */ + ret = mbedtls_mpi_sub_mpi(&result, &(curvePara->mpiOne), edwardsY); + if (ret != HKS_MBEDTLS_SUCCESS) { + break; + } + + ret = mbedtls_mpi_mod_mpi(&result, &result, &(curvePara->mpiP)); + if (ret != HKS_MBEDTLS_SUCCESS) { + break; + } + + ret = mbedtls_mpi_inv_mod(&result, &result, &(curvePara->mpiP)); + if (ret != HKS_MBEDTLS_SUCCESS) { + break; + } + + ret = mbedtls_mpi_add_mpi(&curveX, &(curvePara->mpiOne), edwardsY); + if (ret != HKS_MBEDTLS_SUCCESS) { + break; + } + + ret = mbedtls_mpi_mul_mpi(&result, &curveX, &result); + if (ret != HKS_MBEDTLS_SUCCESS) { + break; + } + + ret = mbedtls_mpi_mod_mpi(&result, &result, &(curvePara->mpiP)); + if (ret != HKS_MBEDTLS_SUCCESS) { + break; + } + + ret = mbedtls_mpi_write_binary(&result, x25519Key->data, x25519Key->size); + } while (0); + + mbedtls_mpi_free(&curveX); + mbedtls_mpi_free(&result); + + return ret; +} + +static int32_t ConvertPublicKey(const struct HksBlob *publicKeyIn, struct HksBlob *x25519PublicKey) +{ + /* RFC 8032 */ + publicKeyIn->data[publicKeyIn->size - 1] = publicKeyIn->data[publicKeyIn->size - 1] & 0x7f; + int32_t ret = EndianSwap(publicKeyIn->data, publicKeyIn->size); + if (ret != HKS_SUCCESS) { + return ret; + } + + mbedtls_mpi edwardsY; + struct HksCurveConstPara curvePara; + + mbedtls_mpi_init(&edwardsY); + HksCurveInitConstPara(&curvePara); + + do { + ret = HksCurveSetConstPara(&curvePara); + if (ret != HKS_SUCCESS) { + break; + } + + ret = mbedtls_mpi_read_binary(&edwardsY, publicKeyIn->data, publicKeyIn->size); + if (ret != HKS_MBEDTLS_SUCCESS) { + break; + } + + ret = HksCurvePskCheckPoint(&edwardsY, publicKeyIn->data, publicKeyIn->size, &curvePara); + if (ret != HKS_SUCCESS) { + break; + } + + x25519PublicKey->size = CURVE25519_KEY_BYTE_SIZE; + x25519PublicKey->data = (uint8_t *)HksMalloc(x25519PublicKey->size); + if (x25519PublicKey->data == NULL) { + HKS_LOG_E("malloc failed"); + ret = HKS_ERROR_MALLOC_FAIL; + break; + } + + ret = HksCurvePskCalcC(&edwardsY, x25519PublicKey, &curvePara); + if (ret != HKS_SUCCESS) { + break; + } + + ret = EndianSwap(x25519PublicKey->data, x25519PublicKey->size); + } while (0); + + HksCurveFreeConstPara(&curvePara); + mbedtls_mpi_free(&edwardsY); + if ((ret != HKS_SUCCESS) && (x25519PublicKey->data != NULL)) { + (void)memset_s(x25519PublicKey->data, x25519PublicKey->size, 0, x25519PublicKey->size); + HKS_FREE_BLOB(*x25519PublicKey); + } + + return ret; +} + +static int32_t ConvertPrivateKey(const struct HksBlob *privateKeyIn, struct HksBlob *x25519PrivateKey) +{ + uint8_t hash512Data[HASH512_OUT_SIZE] = {0}; + struct HksBlob hash512 = { HASH512_OUT_SIZE, hash512Data }; + + /* Get 32-bit private key data as the hash input parameter (little endian) */ + int32_t ret = HksCryptoHalHash(HKS_DIGEST_SHA512, privateKeyIn, &hash512); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("convert private key calc hash failed"); + return ret; + } + + x25519PrivateKey->size = CURVE25519_KEY_BYTE_SIZE; + x25519PrivateKey->data = (uint8_t *)HksMalloc(x25519PrivateKey->size); + if (x25519PrivateKey->data == NULL) { + HKS_LOG_E("malloc failed"); + return HKS_ERROR_MALLOC_FAIL; + } + + do { + /* Get the first 32 bytes of the hash value (little endian) */ + if (memcpy_s(x25519PrivateKey->data, x25519PrivateKey->size, hash512.data, CURVE25519_KEY_BYTE_SIZE) != EOK) { + ret = HKS_ERROR_BAD_STATE; + break; + } + + x25519PrivateKey->data[0] &= 248; /* 248: RFC 8032 */ + x25519PrivateKey->data[x25519PrivateKey->size - 1] &= 127; /* 127: RFC 8032 */ + x25519PrivateKey->data[x25519PrivateKey->size - 1] |= 64; /* 64: RFC 8032 */ + + ret = EndianSwap(x25519PrivateKey->data, x25519PrivateKey->size); + } while (0); + + if ((ret != HKS_SUCCESS) && (x25519PrivateKey->data != NULL)) { + (void)memset_s(x25519PrivateKey->data, x25519PrivateKey->size, 0, x25519PrivateKey->size); + HKS_FREE_BLOB(*x25519PrivateKey); + } + return ret; +} + +int32_t MbedtlsEd25519KeyToX25519(const struct HksBlob *ed25519NativeKey, + const struct HksBlob *ed25519PubKey, struct HksBlob *x25519NativeKey, struct HksBlob *x25519PubKey) +{ + int32_t ret = ConvertPublicKey(ed25519PubKey, x25519PubKey); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("convert ed25519 public key to x25519 public key failed! ret = %d", ret); + return ret; + } + + ret = ConvertPrivateKey(ed25519NativeKey, x25519NativeKey); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("convert ed25519 private key to x25519 private key failed! ret = %d", ret); + return ret; + } + + return HKS_SUCCESS; +} + +void HksFreeKeyInfo(struct HksEd25519ToX25519Blob *key) +{ + if (key->rawNativeKey.data != NULL) { + (void)memset_s(key->rawNativeKey.data, key->rawNativeKey.size, 0, key->rawNativeKey.size); + HKS_FREE_PTR(key->rawNativeKey.data); + } + if (key->rawPubKey.data != NULL) { + (void)memset_s(key->rawPubKey.data, key->rawPubKey.size, 0, key->rawPubKey.size); + HKS_FREE_PTR(key->rawPubKey.data); + } + if (key->rawX25519NativeKey.data != NULL) { + (void)memset_s(key->rawX25519NativeKey.data, key->rawX25519NativeKey.size, 0, key->rawX25519NativeKey.size); + HKS_FREE_PTR(key->rawX25519NativeKey.data); + } + if (key->rawX25519PubKey.data != NULL) { + (void)memset_s(key->rawX25519PubKey.data, key->rawX25519PubKey.size, 0, key->rawX25519PubKey.size); + HKS_FREE_PTR(key->rawX25519PubKey.data); + } + if (key->kmX25519NativeKey.data != NULL) { + (void)memset_s(key->kmX25519NativeKey.data, key->kmX25519NativeKey.size, 0, key->kmX25519NativeKey.size); + HKS_FREE_PTR(key->kmX25519NativeKey.data); + } + if (key->kmX25519PubKey.data != NULL) { + (void)memset_s(key->kmX25519PubKey.data, key->kmX25519PubKey.size, 0, key->kmX25519PubKey.size); + HKS_FREE_PTR(key->kmX25519PubKey.data); + } +} + +int32_t HksMbedtlsEd25519KeyAgreement(const struct HksBlob *nativeKey, + const struct HksBlob *pubKey, struct HksBlob *sharedKey) +{ + int32_t ret = X25519CheckKeyMaterialSize(nativeKey, pubKey); + if (ret != HKS_SUCCESS) { + return ret; + } + + struct HksEd25519ToX25519Blob key; + (void)memset_s(&key, sizeof(key), 0, sizeof(key)); + + do { + ret = HksGetKeyFromMaterial(HKS_ALG_ED25519, false, nativeKey, &(key.rawNativeKey)); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get private key from material failed, ret = 0x%X", ret); + break; + } + ret = HksGetKeyFromMaterial(HKS_ALG_ED25519, true, pubKey, &(key.rawPubKey)); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get public key from material failed, ret = 0x%X", ret); + break; + } + + ret = MbedtlsEd25519KeyToX25519(&(key.rawNativeKey), &(key.rawPubKey), + &(key.rawX25519NativeKey), &(key.rawX25519PubKey)); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("covert from ed25519 to x25519 failed, ret = 0x%X", ret); + break; + } + + ret = HksSetKeyToMaterial(HKS_ALG_X25519, false, &(key.rawX25519NativeKey), &(key.kmX25519NativeKey)); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("set private key to material failed, ret = 0x%X", ret); + break; + } + ret = HksSetKeyToMaterial(HKS_ALG_X25519, true, &(key.rawX25519PubKey), &(key.kmX25519PubKey)); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("set publicy key to material failed, ret = 0x%X", ret); + break; + } + + ret = HksMbedtlsX25519KeyAgreement(&(key.kmX25519NativeKey), &(key.kmX25519PubKey), sharedKey); + } while (0); + + HksFreeKeyInfo(&key); + return ret; +} +#endif + +#endif /* HKS_SUPPORT_X25519_C */ diff --git a/frameworks/huks_standard/main/crypto_engine/openssl/BUILD.gn b/frameworks/huks_standard/main/crypto_engine/openssl/BUILD.gn index e98edde5..12dc2d00 100644 --- a/frameworks/huks_standard/main/crypto_engine/openssl/BUILD.gn +++ b/frameworks/huks_standard/main/crypto_engine/openssl/BUILD.gn @@ -27,6 +27,11 @@ ohos_static_library("libhuks_openssl_standard_static") { "//third_party/openssl/include/", ] + defines = [ + "L2_STANDARD", + "_HARDWARE_ROOT_KEY_", + "_HUKS_LOG_ENABLE_", + ] sources = [ "src/hks_openssl_aes.c", "src/hks_openssl_curve25519.c", diff --git a/frameworks/huks_standard/main/crypto_engine/openssl/include/hks_openssl_engine.h b/frameworks/huks_standard/main/crypto_engine/openssl/include/hks_openssl_engine.h index f10fd7ca..742b097b 100644 --- a/frameworks/huks_standard/main/crypto_engine/openssl/include/hks_openssl_engine.h +++ b/frameworks/huks_standard/main/crypto_engine/openssl/include/hks_openssl_engine.h @@ -18,7 +18,7 @@ #include -#include "hks_type.h" +#include "hks_type_inner.h" struct HksBnExpModParams { BIGNUM *bnX; diff --git a/frameworks/huks_standard/main/crypto_engine/openssl/src/hks_openssl_aes.c b/frameworks/huks_standard/main/crypto_engine/openssl/src/hks_openssl_aes.c index 6cf1ffb9..037e95cb 100755 --- a/frameworks/huks_standard/main/crypto_engine/openssl/src/hks_openssl_aes.c +++ b/frameworks/huks_standard/main/crypto_engine/openssl/src/hks_openssl_aes.c @@ -21,7 +21,7 @@ #include "hks_log.h" #include "hks_mem.h" #include "hks_openssl_engine.h" -#include "hks_type.h" +#include "hks_type_inner.h" static int32_t AesGenKeyCheckParam(const struct HksKeySpec *spec) { diff --git a/frameworks/huks_standard/main/crypto_engine/openssl/src/hks_openssl_engine.c b/frameworks/huks_standard/main/crypto_engine/openssl/src/hks_openssl_engine.c index 3ced1763..b0979cf4 100755 --- a/frameworks/huks_standard/main/crypto_engine/openssl/src/hks_openssl_engine.c +++ b/frameworks/huks_standard/main/crypto_engine/openssl/src/hks_openssl_engine.c @@ -31,7 +31,7 @@ #include "hks_openssl_hash.h" #include "hks_openssl_hmac.h" #include "hks_openssl_kdf.h" -#include "hks_type.h" +#include "hks_type_inner.h" void HksLogOpensslError() { diff --git a/frameworks/huks_standard/main/crypto_engine/openssl/src/hks_openssl_hash.c b/frameworks/huks_standard/main/crypto_engine/openssl/src/hks_openssl_hash.c index f9998543..72a1902d 100644 --- a/frameworks/huks_standard/main/crypto_engine/openssl/src/hks_openssl_hash.c +++ b/frameworks/huks_standard/main/crypto_engine/openssl/src/hks_openssl_hash.c @@ -19,7 +19,7 @@ #include "hks_log.h" #include "hks_openssl_engine.h" -#include "hks_type.h" +#include "hks_type_inner.h" static int32_t CheckDigestAlg(uint32_t alg) { diff --git a/frameworks/huks_standard/main/crypto_engine/openssl/src/hks_openssl_hmac.c b/frameworks/huks_standard/main/crypto_engine/openssl/src/hks_openssl_hmac.c index 6702a17c..1647fad2 100755 --- a/frameworks/huks_standard/main/crypto_engine/openssl/src/hks_openssl_hmac.c +++ b/frameworks/huks_standard/main/crypto_engine/openssl/src/hks_openssl_hmac.c @@ -20,7 +20,7 @@ #include "hks_log.h" #include "hks_openssl_engine.h" -#include "hks_type.h" +#include "hks_type_inner.h" static int32_t HmacCheckBuffer(const struct HksBlob *key, const struct HksBlob *msg, const struct HksBlob *mac) { diff --git a/frameworks/huks_standard/main/os_dependency/BUILD.gn b/frameworks/huks_standard/main/os_dependency/BUILD.gn index b6f25bd6..3524e363 100644 --- a/frameworks/huks_standard/main/os_dependency/BUILD.gn +++ b/frameworks/huks_standard/main/os_dependency/BUILD.gn @@ -29,6 +29,11 @@ ohos_static_library("libhuks_os_dependency_standard_static") { "//utils/native/base/include", "//utils/system/safwk/native/include", ] + defines = [ + "L2_STANDARD", + "_HARDWARE_ROOT_KEY_", + "_HUKS_LOG_ENABLE_", + ] sources = [ "./ipc/src/hks_client_service_ipc.c", "./ipc/src/hks_ipc_check.c", diff --git a/frameworks/huks_standard/main/os_dependency/ipc/include/hks_client_service_ipc.h b/frameworks/huks_standard/main/os_dependency/ipc/include/hks_client_ipc.h old mode 100755 new mode 100644 similarity index 91% rename from frameworks/huks_standard/main/os_dependency/ipc/include/hks_client_service_ipc.h rename to frameworks/huks_standard/main/os_dependency/ipc/include/hks_client_ipc.h index 68a98613..425d16d2 --- a/frameworks/huks_standard/main/os_dependency/ipc/include/hks_client_service_ipc.h +++ b/frameworks/huks_standard/main/os_dependency/ipc/include/hks_client_ipc.h @@ -1,5 +1,5 @@ /* - * Copyright (c) 2021 Huawei Device Co., Ltd. + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. * 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 @@ -13,10 +13,10 @@ * limitations under the License. */ -#ifndef HKS_CLIENT_SERVICE_IPC_H -#define HKS_CLIENT_SERVICE_IPC_H +#ifndef HKS_CLIENT_IPC_H +#define HKS_CLIENT_IPC_H -#include "hks_type.h" +#include "hks_type_inner.h" #ifdef __cplusplus extern "C" { @@ -24,6 +24,8 @@ extern "C" { int32_t HksClientInitialize(void); +int32_t HksClientRefreshKeyInfo(void); + int32_t HksClientGenerateKey(const struct HksBlob *keyAlias, const struct HksParamSet *paramSetIn, struct HksParamSet *paramSetOut); @@ -80,4 +82,4 @@ int32_t HksClientUnwrapKey(const struct HksBlob *keyAlias, const struct HksBlob } #endif -#endif +#endif /* HKS_CLIENT_IPC_H */ diff --git a/frameworks/huks_standard/main/os_dependency/ipc/include/hks_ipc_check.h b/frameworks/huks_standard/main/os_dependency/ipc/include/hks_ipc_check.h index 5ccbad92..89c7a122 100644 --- a/frameworks/huks_standard/main/os_dependency/ipc/include/hks_ipc_check.h +++ b/frameworks/huks_standard/main/os_dependency/ipc/include/hks_ipc_check.h @@ -16,7 +16,7 @@ #ifndef HKS_CRYPTO_CHECK_H #define HKS_CRYPTO_CHECK_H -#include "hks_type.h" +#include "hks_type_inner.h" #ifdef __cplusplus extern "C" { diff --git a/frameworks/huks_standard/main/os_dependency/ipc/include/hks_ipc_serialization.h b/frameworks/huks_standard/main/os_dependency/ipc/include/hks_ipc_serialization.h index be55bbd2..e80cf37d 100644 --- a/frameworks/huks_standard/main/os_dependency/ipc/include/hks_ipc_serialization.h +++ b/frameworks/huks_standard/main/os_dependency/ipc/include/hks_ipc_serialization.h @@ -16,7 +16,7 @@ #ifndef HKS_IPC_SERIALIZATION_H #define HKS_IPC_SERIALIZATION_H -#include "hks_type.h" +#include "hks_type_inner.h" #define MAX_IPC_BUF_SIZE 0x10000 /* Maximun IPC message buffer size. */ #define MAX_IPC_RSV_SIZE 0x400 /* Reserve IPC message buffer size */ diff --git a/frameworks/huks_standard/main/os_dependency/ipc/include/hks_ipc_slice.h b/frameworks/huks_standard/main/os_dependency/ipc/include/hks_ipc_slice.h index c4895e94..620f402d 100644 --- a/frameworks/huks_standard/main/os_dependency/ipc/include/hks_ipc_slice.h +++ b/frameworks/huks_standard/main/os_dependency/ipc/include/hks_ipc_slice.h @@ -16,7 +16,7 @@ #ifndef HKS_IPC_SLICE_H #define HKS_IPC_SLICE_H -#include "hks_type.h" +#include "hks_type_inner.h" #ifdef __cplusplus extern "C" { diff --git a/frameworks/huks_standard/main/os_dependency/ipc/include/hks_request.h b/frameworks/huks_standard/main/os_dependency/ipc/include/hks_request.h index 0f81c197..95f00da7 100644 --- a/frameworks/huks_standard/main/os_dependency/ipc/include/hks_request.h +++ b/frameworks/huks_standard/main/os_dependency/ipc/include/hks_request.h @@ -16,7 +16,7 @@ #ifndef HKS_REQUEST_H #define HKS_REQUEST_H -#include "hks_type.h" +#include "hks_type_inner.h" enum HksMessage { HKS_MSG_BASE = 0x3a400, /* range of message value defined by router. globally unique */ diff --git a/frameworks/huks_standard/main/os_dependency/ipc/src/hks_client_service_ipc.c b/frameworks/huks_standard/main/os_dependency/ipc/src/hks_client_service_ipc.c index ca7e9c96..96453e35 100755 --- a/frameworks/huks_standard/main/os_dependency/ipc/src/hks_client_service_ipc.c +++ b/frameworks/huks_standard/main/os_dependency/ipc/src/hks_client_service_ipc.c @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "hks_client_service_ipc.h" +#include "hks_client_ipc.h" #include "hks_common_check.h" #include "hks_ipc_check.h" #include "hks_ipc_serialization.h" @@ -28,6 +28,11 @@ int32_t HksClientInitialize(void) return HKS_SUCCESS; } +int32_t HksClientRefreshKeyInfo(void) +{ + return HKS_SUCCESS; +} + int32_t HksClientGenerateKey(const struct HksBlob *keyAlias, const struct HksParamSet *paramSetIn, struct HksParamSet *paramSetOut) { diff --git a/frameworks/huks_standard/main/os_dependency/ipc/src/hks_client_service_passthrough.c b/frameworks/huks_standard/main/os_dependency/ipc/src/hks_client_service_passthrough.c new file mode 100644 index 00000000..3b3ead57 --- /dev/null +++ b/frameworks/huks_standard/main/os_dependency/ipc/src/hks_client_service_passthrough.c @@ -0,0 +1,256 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#include "hks_client_ipc.h" +#include "hks_client_service.h" +#include "hks_get_process_info.h" +#include "hks_log.h" + +#ifndef _CUT_AUTHENTICATE_ +int32_t HksClientInitialize(void) +{ + return HksServiceInitialize(); +} + +int32_t HksClientRefreshKeyInfo(void) +{ + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + return HksServiceRefreshKeyInfo(&processNameBlob); +} + +int32_t HksClientGenerateKey(const struct HksBlob *keyAlias, const struct HksParamSet *paramSetIn, + struct HksParamSet *paramSetOut) +{ + (void)paramSetOut; + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + return HksServiceGenerateKey(&processNameBlob, keyAlias, paramSetIn, NULL); +} + +int32_t HksClientImportKey(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, + const struct HksBlob *key) +{ + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + return HksServiceImportKey(&processNameBlob, keyAlias, paramSet, key); +} + +int32_t HksClientExportPublicKey(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, + struct HksBlob *key) +{ + (void)paramSet; + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + return HksServiceExportPublicKey(&processNameBlob, keyAlias, key); +} + +int32_t HksClientDeleteKey(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet) +{ + (void)paramSet; + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + return HksServiceDeleteKey(&processNameBlob, keyAlias); +} + +int32_t HksClientGetKeyParamSet(const struct HksBlob *keyAlias, struct HksParamSet *paramSetOut) +{ + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + return HksServiceGetKeyParamSet(&processNameBlob, keyAlias, paramSetOut); +} + +int32_t HksClientKeyExist(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet) +{ + (void)paramSet; + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + return HksServiceKeyExist(&processNameBlob, keyAlias); +} + +int32_t HksClientSign(const struct HksBlob *key, const struct HksParamSet *paramSet, + const struct HksBlob *srcData, struct HksBlob *signature) +{ + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + return HksServiceSign(&processNameBlob, key, paramSet, srcData, signature); +} + +int32_t HksClientVerify(const struct HksBlob *key, const struct HksParamSet *paramSet, + const struct HksBlob *srcData, const struct HksBlob *signature) +{ + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + return HksServiceVerify(&processNameBlob, key, paramSet, srcData, signature); +} + +int32_t HksClientEncrypt(const struct HksBlob *key, const struct HksParamSet *paramSet, + const struct HksBlob *plainText, struct HksBlob *cipherText) +{ + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + return HksServiceEncrypt(&processNameBlob, key, paramSet, plainText, cipherText); +} + +int32_t HksClientDecrypt(const struct HksBlob *key, const struct HksParamSet *paramSet, + const struct HksBlob *cipherText, struct HksBlob *plainText) +{ + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + return HksServiceDecrypt(&processNameBlob, key, paramSet, cipherText, plainText); +} + +int32_t HksClientAgreeKey(const struct HksParamSet *paramSet, const struct HksBlob *privateKey, + const struct HksBlob *peerPublicKey, struct HksBlob *agreedKey) +{ + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + return HksServiceAgreeKey(&processNameBlob, paramSet, privateKey, peerPublicKey, agreedKey); +} + +int32_t HksClientDeriveKey(const struct HksParamSet *paramSet, const struct HksBlob *mainKey, + struct HksBlob *derivedKey) +{ + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + return HksServiceDeriveKey(&processNameBlob, paramSet, mainKey, derivedKey); +} + +int32_t HksClientMac(const struct HksBlob *key, const struct HksParamSet *paramSet, const struct HksBlob *srcData, + struct HksBlob *mac) +{ + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + return HksServiceMac(&processNameBlob, key, paramSet, srcData, mac); +} + +int32_t HksClientGetKeyInfoList(struct HksKeyInfo *keyInfoList, uint32_t *listCount) +{ + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + return HksServiceGetKeyInfoList(&processNameBlob, keyInfoList, listCount); +} + +int32_t HksClientAttestKey(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, + struct HksCertChain *certChain) +{ + (void)keyAlias; + (void)paramSet; + (void)certChain; + return HKS_ERROR_NOT_SUPPORTED; +} + +int32_t HksClientGetCertificateChain(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, + struct HksCertChain *certChain) +{ + (void)keyAlias; + (void)paramSet; + (void)certChain; + return HKS_ERROR_NOT_SUPPORTED; +} + +int32_t HksClientWrapKey(const struct HksBlob *keyAlias, const struct HksBlob *targetKeyAlias, + const struct HksParamSet *paramSet, struct HksBlob *wrappedData) +{ + (void)keyAlias; + (void)targetKeyAlias; + (void)paramSet; + (void)wrappedData; + return HKS_ERROR_NOT_SUPPORTED; +} + +int32_t HksClientUnwrapKey(const struct HksBlob *keyAlias, const struct HksBlob *targetKeyAlias, + const struct HksBlob *wrappedData, const struct HksParamSet *paramSet) +{ + (void)keyAlias; + (void)targetKeyAlias; + (void)paramSet; + (void)wrappedData; + return HKS_ERROR_NOT_SUPPORTED; +} +#endif + +int32_t HksClientGenerateRandom(struct HksBlob *random, const struct HksParamSet *paramSet) +{ + (void)paramSet; + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + return HksServiceGenerateRandom(&processNameBlob, random); +} + diff --git a/frameworks/huks_standard/main/os_dependency/log/hks_log.c b/frameworks/huks_standard/main/os_dependency/log/hks_log.c index bc9b51a5..fa06eb36 100644 --- a/frameworks/huks_standard/main/os_dependency/log/hks_log.c +++ b/frameworks/huks_standard/main/os_dependency/log/hks_log.c @@ -15,8 +15,9 @@ #include "hks_log.h" -#include +#include "securec.h" #include "hilog/log.h" +#include "hks_mem.h" #undef LOG_DOMAIN #undef LOG_TAG @@ -27,13 +28,20 @@ static const char* LOG_TAG = "HUKS"; void HksLog(uint32_t logLevel, const char *funcName, uint32_t lineNo, const char *format, ...) { - char buf[MAX_LOG_BUFF_LEN] = {0}; - va_list ap = {0}; + char *buf = (char *)HksMalloc(MAX_LOG_BUFF_LEN); + if (buf == NULL) { + HILOG_ERROR(LOG_CORE, "hks log malloc fail"); + return; + } + (void)memset_s(buf, MAX_LOG_BUFF_LEN, 0, MAX_LOG_BUFF_LEN); + + va_list ap; va_start(ap, format); - int32_t ret = vsnprintf_s(buf, MAX_LOG_BUFF_LEN, sizeof(buf) - 1, format, ap); + int32_t ret = vsnprintf_s(buf, MAX_LOG_BUFF_LEN, MAX_LOG_BUFF_LEN - 1, format, ap); va_end(ap); if (ret < 0) { HILOG_ERROR(LOG_CORE, "hks log concatenate error."); + HKS_FREE_PTR(buf); return; } @@ -51,6 +59,9 @@ void HksLog(uint32_t logLevel, const char *funcName, uint32_t lineNo, const char HILOG_DEBUG(LOG_CORE, "%{public}s[%{public}u]: %{private}s\n", funcName, lineNo, buf); break; default: + HKS_FREE_PTR(buf); return; } + + HKS_FREE_PTR(buf); } \ No newline at end of file diff --git a/frameworks/huks_standard/main/os_dependency/log/hks_log_lite.c b/frameworks/huks_standard/main/os_dependency/log/hks_log_lite.c new file mode 100644 index 00000000..a87e5935 --- /dev/null +++ b/frameworks/huks_standard/main/os_dependency/log/hks_log_lite.c @@ -0,0 +1,81 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#include "hks_log.h" + +#include "securec.h" + +#include "log.h" + +#include "hks_mem.h" + +#define MAX_LOG_BUFF_LEN 512 + +void HksLog(uint32_t logLevel, const char *funcName, uint32_t lineNo, const char *format, ...) +{ + char *buf = (char *)HksMalloc(MAX_LOG_BUFF_LEN); + if (buf == NULL) { + HILOG_ERROR(HILOG_MODULE_SCY, "hks log malloc fail"); + return; + } + (void)memset_s(buf, MAX_LOG_BUFF_LEN, 0, MAX_LOG_BUFF_LEN); + + va_list ap; + va_start(ap, format); + int32_t ret = vsnprintf_s(buf, MAX_LOG_BUFF_LEN, MAX_LOG_BUFF_LEN - 1, format, ap); + va_end(ap); + if (ret < 0) { + HILOG_ERROR(HILOG_MODULE_SCY, "hks log concatenate error."); + HKS_FREE_PTR(buf); + return; + } + + switch (logLevel) { + case HKS_LOG_LEVEL_I: +#if defined(__LINUX__) + HILOG_INFO(HILOG_MODULE_SCY, "%s[%u]: %s\n", funcName, lineNo, buf); + +#else + HILOG_INFO(HILOG_MODULE_SCY, "%{public}s[%{public}u]: %{public}s\n", funcName, lineNo, buf); +#endif + break; + case HKS_LOG_LEVEL_E: +#if defined(__LINUX__) + HILOG_ERROR(HILOG_MODULE_SCY, "%s[%u]: %s\n", funcName, lineNo, buf); +#else + HILOG_ERROR(HILOG_MODULE_SCY, "%{public}s[%{public}u]: %{public}s\n", funcName, lineNo, buf); +#endif + break; + case HKS_LOG_LEVEL_W: +#if defined(__LINUX__) + HILOG_WARN(HILOG_MODULE_SCY, "%s[%u]: %s\n", funcName, lineNo, buf); +#else + HILOG_WARN(HILOG_MODULE_SCY, "%{public}s[%{public}u]: %{public}s\n", funcName, lineNo, buf); +#endif + break; + case HKS_LOG_LEVEL_D: +#if defined(__LINUX__) + HILOG_DEBUG(HILOG_MODULE_SCY, "%s[%u]: %s\n", funcName, lineNo, buf); +#else + HILOG_DEBUG(HILOG_MODULE_SCY, "%{public}s[%{public}u]: %{private}s\n", funcName, lineNo, buf); +#endif + break; + default: + HKS_FREE_PTR(buf); + return; + } + + HKS_FREE_PTR(buf); +} \ No newline at end of file diff --git a/frameworks/huks_standard/main/os_dependency/posix/hks_mem.c b/frameworks/huks_standard/main/os_dependency/posix/hks_mem.c index c5a9af89..39dbe731 100644 --- a/frameworks/huks_standard/main/os_dependency/posix/hks_mem.c +++ b/frameworks/huks_standard/main/os_dependency/posix/hks_mem.c @@ -17,6 +17,19 @@ #include +#ifdef HKS_SUPPORT_PRODUCT_GT_WATCH +#include "ohos_mem_pool.h" + +void *HksMalloc(size_t size) +{ + return OhosMalloc(MEM_TYPE_HICHAIN, size); +} + +void HksFree(void *ptr) +{ + OhosFree(ptr); +} +#else void *HksMalloc(size_t size) { return malloc(size); @@ -26,8 +39,10 @@ void HksFree(void *ptr) { free(ptr); } +#endif int32_t HksMemCmp(const void *ptr1, const void *ptr2, uint32_t size) { return memcmp(ptr1, ptr2, size); -} \ No newline at end of file +} + diff --git a/frameworks/huks_standard/main/os_dependency/sysinfo/include/hks_get_process_info.h b/frameworks/huks_standard/main/os_dependency/sysinfo/include/hks_get_process_info.h new file mode 100644 index 00000000..e8ab4e41 --- /dev/null +++ b/frameworks/huks_standard/main/os_dependency/sysinfo/include/hks_get_process_info.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_GET_PROCESS_INFO_H +#define HKS_GET_PROCESS_INFO_H + +#include "hks_type.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t HksGetProcessName(char **processName); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_GET_PROCESS_INFO_H */ diff --git a/frameworks/huks_standard/main/os_dependency/sysinfo/include/hks_get_udid.h b/frameworks/huks_standard/main/os_dependency/sysinfo/include/hks_get_udid.h new file mode 100644 index 00000000..6e3fe0ed --- /dev/null +++ b/frameworks/huks_standard/main/os_dependency/sysinfo/include/hks_get_udid.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_GET_UDID_H +#define HKS_GET_UDID_H + +#include "hks_type.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t HksGetHardwareUdid(uint8_t *udid, uint32_t udidLen); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_GET_UDID_H */ diff --git a/frameworks/huks_standard/main/os_dependency/sysinfo/src/hks_get_process_info_passthrough.c b/frameworks/huks_standard/main/os_dependency/sysinfo/src/hks_get_process_info_passthrough.c new file mode 100644 index 00000000..8f1326c0 --- /dev/null +++ b/frameworks/huks_standard/main/os_dependency/sysinfo/src/hks_get_process_info_passthrough.c @@ -0,0 +1,24 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#include "hks_get_process_info.h" + +static char g_processName[] = "hks_client"; +int32_t HksGetProcessName(char **processName) +{ + *processName = g_processName; + return HKS_SUCCESS; +} + diff --git a/frameworks/huks_standard/main/os_dependency/sysinfo/src/hks_get_udid.c b/frameworks/huks_standard/main/os_dependency/sysinfo/src/hks_get_udid.c new file mode 100644 index 00000000..64d4054e --- /dev/null +++ b/frameworks/huks_standard/main/os_dependency/sysinfo/src/hks_get_udid.c @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#include "hks_get_udid.h" + +#include "securec.h" + +#include "hks_log.h" +#include "hks_type.h" + +#define HKS_HARDWARE_UDID_LEN 32 + +#ifndef _CUT_AUTHENTICATE_ +#if defined(HKS_SUPPORT_PRODUCT_GT_WATCH) +extern uint8_t GetUdid(uint8_t *buf, uint8_t length); + +int32_t HksGetHardwareUdid(uint8_t *udid, uint32_t udidLen) +{ + uint8_t hardwareUdid[HKS_HARDWARE_UDID_LEN] = {0}; + uint8_t resultLen = GetUdid(hardwareUdid, HKS_HARDWARE_UDID_LEN); + if (resultLen != HKS_HARDWARE_UDID_LEN) { + HKS_LOG_E("Get Udid failed!"); + return HKS_FAILURE; + } + + if (memcpy_s(udid, udidLen, hardwareUdid, HKS_HARDWARE_UDID_LEN) != EOK) { + HKS_LOG_E("Memcpy udid failed!"); + return HKS_ERROR_BAD_STATE; + } + + return HKS_SUCCESS; +} + +#else +int32_t HksGetHardwareUdid(uint8_t *udid, uint32_t udidLen) +{ + const uint8_t testUdid[HKS_HARDWARE_UDID_LEN] = { + 0xFE, 0xF1, 0xFA, 0xD5, 0xB6, 0x9D, 0x4A, 0xC8, + 0x52, 0xE7, 0xF5, 0xA3, 0x8F, 0x0D, 0xE1, 0xC0, + 0x87, 0xA4, 0x40, 0xF2, 0x10, 0x5A, 0xC9, 0x31, + 0xC4, 0xD7, 0x2E, 0xDE, 0x51, 0xE3, 0x73, 0x11, + }; + + if (memcpy_s(udid, udidLen, testUdid, HKS_HARDWARE_UDID_LEN) != EOK) { + HKS_LOG_E("Memcpy udid failed!"); + return HKS_ERROR_BAD_STATE; + } + + return HKS_SUCCESS; +} +#endif + +#endif /* _CUT_AUTHENTICATE_ */ diff --git a/interfaces/innerkits/huks_lite/BUILD.gn b/interfaces/innerkits/huks_lite/BUILD.gn new file mode 100644 index 00000000..e281ff89 --- /dev/null +++ b/interfaces/innerkits/huks_lite/BUILD.gn @@ -0,0 +1,206 @@ +# +# Copyright (c) 2021 Huawei Device Co., Ltd. +# 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. +# + +import("//build/lite/config/component/lite_component.gni") +import("//base/security/huks/build/config.gni") + +huks_sources = [ + "../../../services/huks_standard/huks_service/main/core/src/hks_client_check.c", + "../../../services/huks_standard/huks_service/main/core/src/hks_client_service.c", + "../../../services/huks_standard/huks_service/main/core/src/hks_client_service_adapter_lite.c", + "../../../frameworks/huks_standard/main/os_dependency/ipc/src/hks_client_service_passthrough.c", + "../../../services/huks_standard/huks_service/main/os_dependency/posix/hks_file_operator_lite.c", + "../../../services/huks_standard/huks_service/main/core/src/hks_upgrade_storage_data.c", + "../../../frameworks/huks_standard/main/common/src/hks_common_check.c", + "../../../frameworks/huks_standard/main/common/src/hks_crypto_adapter.c", + "../../../frameworks/huks_standard/main/os_dependency/sysinfo/src/hks_get_process_info_passthrough.c", + "../../../frameworks/huks_standard/main/os_dependency/sysinfo/src/hks_get_udid.c", + "../../../frameworks/huks_standard/main/common/src/hks_param.c", + "../../../frameworks/huks_standard/main/os_dependency/posix/hks_mem.c", + "../../../frameworks/huks_standard/main/core/src/hks_local_engine.c", + "../../../services/huks_standard/huks_engine/main/core/src/hks_auth.c", + "../../../frameworks/huks_standard/main/common/src/hks_base_check.c", + "../../../frameworks/huks_standard/main/common/src/hks_check_paramset.c", + "../../../services/huks_standard/huks_engine/main/core/src/hks_core_service.c", + "../../../services/huks_standard/huks_engine/main/core/src/hks_keyblob.c", + "../../../services/huks_standard/huks_engine/main/core/src/hks_rkc.c", + "../../../services/huks_standard/huks_engine/main/core/src/hks_rkc_rw.c", + "../../../services/huks_standard/huks_engine/main/core/src/hks_upgrade_key_info.c", + "../../../interfaces/innerkits/huks_standard/main/src/hks_api.c", +] + +if (use_mbedlts == true) { + huks_mbedlts_engine_sources = [ + "../../../frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_crypto_ed25519.c", + "../../../frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_aes.c", + "../../../frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_bn.c", + "../../../frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_common.c", + "../../../frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_ecc.c", + "../../../frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_ecdh.c", + "../../../frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_ecdsa.c", + "../../../frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_engine.c", + "../../../frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_hash.c", + "../../../frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_hmac.c", + "../../../frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_kdf.c", + "../../../frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_rsa.c", + "../../../frameworks/huks_standard/main/crypto_engine/mbedtls/src/hks_mbedtls_x25519.c", + ] +} + +huks_access_sources = + [ "../../../services/huks_standard/huks_service/main/os_dependency/idl/passthrough/hks_passthrough_access.c" ] + +if (use_lite_storage == true) { + huks_storage_source = [ + "../../../services/huks_standard/huks_service/main/core/src/hks_storage_adapter.c", + "../../../services/huks_standard/huks_service/main/core/src/hks_storage_lite.c", + + "../../../services/huks_standard/huks_engine/main/core/src/hks_keyblob_lite.c", + ] +} else { + huks_storage_source = [ "../../../services/huks_standard/huks_service/main/core/src/hks_storage.c" ] +} +config("hilog_dir") { + include_dirs = + [ "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog/" ] +} +config("hilog_lite_dir") { + include_dirs = + [ "//base/hiviewdfx/hilog_lite/interfaces/native/kits/hilog_lite/" ] +} + +config("mbedtls_engine") { + include_dirs = [ + "../../../frameworks/huks_standard/main/crypto_engine/mbedtls/include", + mbedtls_path, + ] +} + +config("soft_huks_config") { + include_dirs = [ + "../../../frameworks/huks_standard/main/common/include", + "../../../frameworks/huks_standard/main/core/include", + "../../../frameworks/huks_standard/main/crypto_engine/mbedtls/include", + "../../../frameworks/huks_standard/main/os_dependency/ipc/include", + "../../../frameworks/huks_standard/main/os_dependency/sysinfo/include", + "../../../services/huks_standard/huks_engine/main/core/include", + "../../../services/huks_standard/huks_service/main/core/include", + "//utils/native/lite/memory/include/", + "//utils/native/lite/include/", + ] + + defines = [ "_FORTIFY_SOURCE = 2" ] + + cflags = [ + "-fvisibility=hidden", + "-Wall", + ] + + if (disable_authenticate == true) { + cflags += [ "-D_CUT_AUTHENTICATE_" ] + } + + if (ohos_kernel_type != "liteos_m") { + cflags += [ "-flto" ] + } + + if (use_hardware_root_key == true) { + cflags += [ "-D_HARDWARE_ROOT_KEY_" ] + } + + if (use_lite_storage == true) { + cflags += [ "-D_STORAGE_LITE_" ] + } else { + if (ohos_kernel_type == "liteos_a") { + cflags += [ "-D_BSD_SOURCE" ] + } else { + cflags += [ "-D_DEFAULT_SOURCE" ] + } + } + + if (ohos_kernel_type != "liteos_m" || enable_huks_log == true) { + cflags += [ "-D_HUKS_LOG_ENABLE_" ] + } + + if (hks_config_file != "") { + print(hks_config_file) + cflags += [ "-DHKS_CONFIG_FILE=\"${hks_config_file}\"" ] + } +} + +config("public_huks_config") { + include_dirs = [ + "../../../interfaces/innerkits/huks_standard/main/include", + ] +} + +#begin: add +if (ohos_kernel_type == "liteos_m") { + static_library("huks_new1") { + public_configs = [ ":public_huks_config" ] + configs += [ ":soft_huks_config" ] + + sources = huks_sources + sources += huks_storage_source + sources += huks_access_sources + + if (use_mbedlts == true) { + sources += huks_mbedlts_engine_sources + deps = [ "//build/lite/config/component/openssl:openssl_static" ] + configs += [ ":mbedtls_engine" ] + } + + if (enable_huks_log == true) { + sources += [ "../../../frameworks/huks_standard/main/os_dependency/log/hks_log_lite.c" ] + configs += [ ":hilog_lite_dir" ] + deps += [ "//base/hiviewdfx/hilog_lite/frameworks/mini:hilog_lite" ] + } + } + #if (ohos_build_type == "debug") { + # group("huks_new_test") { + # deps = [ "//base/security/huks/test:huks_new_test" ] + # } + #} +} else { + shared_library("huks_new1") { + public_configs = [ ":public_huks_config" ] + configs += [ ":soft_huks_config" ] + + sources = huks_sources + sources += huks_storage_source + sources += huks_access_sources + sources += [ "../../../frameworks/huks_standard/main/os_dependency/log/hks_log_lite.c" ] + + deps = [] + + if (use_mbedlts == true) { + sources += huks_mbedlts_engine_sources + deps += [ + "//build/lite/config/component/openssl:openssl_shared", + "//third_party/bounds_checking_function:libsec_shared", + "//third_party/mbedtls:mbedtls_shared", + ] + configs += [ ":mbedtls_engine" ] + } + + configs += [ ":hilog_dir" ] + deps += [ "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared" ] + #if (ohos_build_type == "debug") { + # group("huks_new_test") { + # deps = [ "//base/security/huks/test:huks_new_test" ] + # } + #} + } +} diff --git a/interfaces/innerkits/huks_standard/main/BUILD.gn b/interfaces/innerkits/huks_standard/main/BUILD.gn index 6cbe31ec..12830950 100644 --- a/interfaces/innerkits/huks_standard/main/BUILD.gn +++ b/interfaces/innerkits/huks_standard/main/BUILD.gn @@ -21,7 +21,11 @@ ohos_shared_library("libhukssdk") { subsystem_name = "security" part_name = "huks_standard" public_configs = [ ":huks_config" ] - + defines = [ + "L2_STANDARD", + "_HARDWARE_ROOT_KEY_", + "_HUKS_LOG_ENABLE_", + ] include_dirs = [ "//utils/native/base/include" ] sources = [ "src/hks_api.c" ] diff --git a/interfaces/innerkits/huks_standard/main/include/hks_api.h b/interfaces/innerkits/huks_standard/main/include/hks_api.h index e095eaf4..a9bf6f50 100755 --- a/interfaces/innerkits/huks_standard/main/include/hks_api.h +++ b/interfaces/innerkits/huks_standard/main/include/hks_api.h @@ -13,7 +13,6 @@ * limitations under the License. */ - #ifndef HKS_API_H #define HKS_API_H @@ -27,6 +26,8 @@ HKS_API_EXPORT int32_t HksGetSdkVersion(struct HksBlob *sdkVersion); HKS_API_EXPORT int32_t HksInitialize(void); +HKS_API_EXPORT int32_t HksRefreshKeyInfo(void); + HKS_API_EXPORT int32_t HksGenerateKey(const struct HksBlob *keyAlias, const struct HksParamSet *paramSetIn, struct HksParamSet *paramSetOut); diff --git a/interfaces/innerkits/huks_standard/main/include/hks_param.h b/interfaces/innerkits/huks_standard/main/include/hks_param.h index e7e0a0cb..5baaac7e 100644 --- a/interfaces/innerkits/huks_standard/main/include/hks_param.h +++ b/interfaces/innerkits/huks_standard/main/include/hks_param.h @@ -13,7 +13,6 @@ * limitations under the License. */ - #ifndef HKS_PARAM_H #define HKS_PARAM_H diff --git a/interfaces/innerkits/huks_standard/main/include/hks_type.h b/interfaces/innerkits/huks_standard/main/include/hks_type.h index 517faba7..dfb1d58a 100755 --- a/interfaces/innerkits/huks_standard/main/include/hks_type.h +++ b/interfaces/innerkits/huks_standard/main/include/hks_type.h @@ -13,7 +13,6 @@ * limitations under the License. */ - #ifndef HKS_TYPE_H #define HKS_TYPE_H @@ -21,19 +20,13 @@ #include #include -#include "securec.h" - #ifdef __cplusplus extern "C" { #endif #ifndef HKS_API_PUBLIC - #if defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__) - #ifdef HKS_DLL_EXPORT - #define HKS_API_EXPORT __declspec(dllexport) - #else - #define HKS_API_EXPORT __declspec(dllimport) - #endif + #if defined(WIN32) || defined(_WIN32) || defined(__CYGWIN__) || defined(__ICCARM__) /* __ICCARM__ for iar */ + #define HKS_API_EXPORT #else #define HKS_API_EXPORT __attribute__ ((visibility("default"))) #endif @@ -212,6 +205,8 @@ enum HksErrorCode { HKS_ERROR_IPC_INIT_FAIL = -33, HKS_ERROR_IPC_DLOPEN_FAIL = -34, HKS_ERROR_EFUSE_READ_FAIL = -35, + HKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST = -36, + HKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL = -37, HKS_ERROR_CHECK_GET_ALG_FAIL = -100, HKS_ERROR_CHECK_GET_KEY_SIZE_FAIL = -101, @@ -283,6 +278,7 @@ enum HksTag { HKS_TAG_KEY_GENERATE_TYPE = HKS_TAG_TYPE_UINT | 15, /* choose from enum HksKeyGenerateType */ HKS_TAG_DERIVE_MAIN_KEY = HKS_TAG_TYPE_BYTES | 16, HKS_TAG_DERIVE_FACTOR = HKS_TAG_TYPE_BYTES | 17, + HKS_TAG_DERIVE_ALG = HKS_TAG_TYPE_UINT | 18, HKS_TAG_AGREE_ALG = HKS_TAG_TYPE_UINT | 19, HKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS = HKS_TAG_TYPE_BOOL | 20, HKS_TAG_AGREE_PRIVATE_KEY_ALIAS = HKS_TAG_TYPE_BYTES | 21, diff --git a/interfaces/innerkits/huks_standard/main/include/hks_type_inner.h b/interfaces/innerkits/huks_standard/main/include/hks_type_inner.h new file mode 100644 index 00000000..36ce5c41 --- /dev/null +++ b/interfaces/innerkits/huks_standard/main/include/hks_type_inner.h @@ -0,0 +1,22 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_TYPE_INNER_H +#define HKS_TYPE_INNER_H + +#include "hks_type.h" +#include "securec.h" + +#endif /* HKS_TYPE_INNER_H */ diff --git a/interfaces/innerkits/huks_standard/main/src/hks_api.c b/interfaces/innerkits/huks_standard/main/src/hks_api.c index eed95760..39a64ddc 100755 --- a/interfaces/innerkits/huks_standard/main/src/hks_api.c +++ b/interfaces/innerkits/huks_standard/main/src/hks_api.c @@ -13,19 +13,36 @@ * limitations under the License. */ - -#include "hks_api.h" -#include "hks_client_service_ipc.h" - -#ifdef HKS_HAL_ENGINE_CONFIG_FILE -#include HKS_HAL_ENGINE_CONFIG_FILE +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE #else -#include "hks_crypto_hal_config.h" +#include "hks_config.h" #endif +#include "hks_api.h" + +#include "hks_client_ipc.h" #include "hks_local_engine.h" #include "hks_param.h" +#ifdef _CUT_AUTHENTICATE_ +#undef HKS_SUPPORT_API_GENERATE_KEY +#undef HKS_SUPPORT_API_IMPORT +#undef HKS_SUPPORT_API_EXPORT +#undef HKS_SUPPORT_API_DELETE_KEY +#undef HKS_SUPPORT_API_GET_KEY_PARAM_SET +#undef HKS_SUPPORT_API_KEY_EXIST +#undef HKS_SUPPORT_API_SIGN_VERIFY +#undef HKS_SUPPORT_API_SIGN_VERIFY +#undef HKS_SUPPORT_API_AGREE_KEY +#undef HKS_SUPPORT_API_HASH +#undef HKS_SUPPORT_API_GET_KEY_INFO_LIST +#undef HKS_SUPPORT_API_ATTEST_KEY +#undef HKS_SUPPORT_API_GET_CERTIFICATE_CHAIN +#undef HKS_SUPPORT_API_WRAP_KEY +#undef HKS_SUPPORT_API_UNWRAP_KEY +#endif + HKS_API_EXPORT int32_t HksGetSdkVersion(struct HksBlob *sdkVersion) { if ((sdkVersion == NULL) || (sdkVersion->data == NULL)) { @@ -48,13 +65,26 @@ HKS_API_EXPORT int32_t HksGetSdkVersion(struct HksBlob *sdkVersion) HKS_API_EXPORT int32_t HksInitialize(void) { +#ifndef _CUT_AUTHENTICATE_ return HksClientInitialize(); +#else + return HKS_SUCCESS; +#endif +} + +HKS_API_EXPORT int32_t HksRefreshKeyInfo(void) +{ +#ifndef _CUT_AUTHENTICATE_ + return HksClientRefreshKeyInfo(); +#else + return HKS_ERROR_NOT_SUPPORTED; +#endif } HKS_API_EXPORT int32_t HksGenerateKey(const struct HksBlob *keyAlias, const struct HksParamSet *paramSetIn, struct HksParamSet *paramSetOut) { -#ifdef HKS_SUPPORT_GENERATE_KEY +#ifdef HKS_SUPPORT_API_GENERATE_KEY struct HksParam *storageFlag = NULL; int32_t ret = HksGetParam(paramSetIn, HKS_TAG_KEY_STORAGE_FLAG, &storageFlag); if ((ret == HKS_SUCCESS) && (storageFlag->uint32Param == HKS_STORAGE_TEMP)) { @@ -64,6 +94,7 @@ HKS_API_EXPORT int32_t HksGenerateKey(const struct HksBlob *keyAlias, return HksLocalGenerateKey(paramSetIn, paramSetOut); } + /* generate persistent keys */ if ((paramSetIn == NULL) || (keyAlias == NULL)) { return HKS_ERROR_NULL_POINTER; } @@ -79,7 +110,7 @@ HKS_API_EXPORT int32_t HksGenerateKey(const struct HksBlob *keyAlias, HKS_API_EXPORT int32_t HksImportKey(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, const struct HksBlob *key) { -#ifdef HKS_SUPPORT_IMPORT +#ifdef HKS_SUPPORT_API_IMPORT if ((keyAlias == NULL) || (paramSet == NULL) || (key == NULL)) { return HKS_ERROR_NULL_POINTER; } @@ -95,7 +126,7 @@ HKS_API_EXPORT int32_t HksImportKey(const struct HksBlob *keyAlias, HKS_API_EXPORT int32_t HksExportPublicKey(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, struct HksBlob *key) { -#ifdef HKS_SUPPORT_EXPORT +#ifdef HKS_SUPPORT_API_EXPORT if ((keyAlias == NULL) || (key == NULL)) { return HKS_ERROR_NULL_POINTER; } @@ -110,33 +141,52 @@ HKS_API_EXPORT int32_t HksExportPublicKey(const struct HksBlob *keyAlias, HKS_API_EXPORT int32_t HksDeleteKey(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet) { +#ifdef HKS_SUPPORT_API_DELETE_KEY if (keyAlias == NULL) { return HKS_ERROR_NULL_POINTER; } return HksClientDeleteKey(keyAlias, paramSet); +#else + (void)keyAlias; + (void)paramSet; + return HKS_ERROR_NOT_SUPPORTED; +#endif } HKS_API_EXPORT int32_t HksGetKeyParamSet(const struct HksBlob *keyAlias, const struct HksParamSet *paramSetIn, struct HksParamSet *paramSetOut) { +#ifdef HKS_SUPPORT_API_GET_KEY_PARAM_SET (void)paramSetIn; if ((keyAlias == NULL) || (paramSetOut == NULL)) { return HKS_ERROR_NULL_POINTER; } return HksClientGetKeyParamSet(keyAlias, paramSetOut); +#else + (void)keyAlias; + (void)paramSetIn; + (void)paramSetOut; + return HKS_ERROR_NOT_SUPPORTED; +#endif } HKS_API_EXPORT int32_t HksKeyExist(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet) { +#ifdef HKS_SUPPORT_API_KEY_EXIST if (keyAlias == NULL) { return HKS_ERROR_NULL_POINTER; } return HksClientKeyExist(keyAlias, paramSet); +#else + (void)keyAlias; + (void)paramSet; + return HKS_ERROR_NOT_SUPPORTED; +#endif } HKS_API_EXPORT int32_t HksGenerateRandom(const struct HksParamSet *paramSet, struct HksBlob *random) { -#ifdef HKS_SUPPORT_GENERATE_RANDOM +#ifdef HKS_SUPPORT_API_GENERATE_RANDOM if (random == NULL) { return HKS_ERROR_NULL_POINTER; } @@ -150,7 +200,7 @@ HKS_API_EXPORT int32_t HksGenerateRandom(const struct HksParamSet *paramSet, str HKS_API_EXPORT int32_t HksSign(const struct HksBlob *key, const struct HksParamSet *paramSet, const struct HksBlob *srcData, struct HksBlob *signature) { -#ifdef HKS_SUPPORT_SIGN_VERIFY +#ifdef HKS_SUPPORT_API_SIGN_VERIFY if ((key == NULL) || (paramSet == NULL) || (srcData == NULL) || (signature == NULL)) { return HKS_ERROR_NULL_POINTER; } @@ -167,7 +217,7 @@ HKS_API_EXPORT int32_t HksSign(const struct HksBlob *key, const struct HksParamS HKS_API_EXPORT int32_t HksVerify(const struct HksBlob *key, const struct HksParamSet *paramSet, const struct HksBlob *srcData, const struct HksBlob *signature) { -#ifdef HKS_SUPPORT_SIGN_VERIFY +#ifdef HKS_SUPPORT_API_SIGN_VERIFY if ((key == NULL) || (paramSet == NULL) || (srcData == NULL) || (signature == NULL)) { return HKS_ERROR_NULL_POINTER; } @@ -190,7 +240,7 @@ HKS_API_EXPORT int32_t HksVerify(const struct HksBlob *key, const struct HksPara HKS_API_EXPORT int32_t HksEncrypt(const struct HksBlob *key, const struct HksParamSet *paramSet, const struct HksBlob *plainText, struct HksBlob *cipherText) { -#ifdef HKS_SUPPORT_CIPHER +#ifdef HKS_SUPPORT_API_CIPHER if ((key == NULL) || (paramSet == NULL) || (plainText == NULL) || (cipherText == NULL)) { return HKS_ERROR_NULL_POINTER; } @@ -200,7 +250,11 @@ HKS_API_EXPORT int32_t HksEncrypt(const struct HksBlob *key, const struct HksPar if ((ret == HKS_SUCCESS) && (!isKeyAlias->boolParam)) { return HksLocalEncrypt(key, paramSet, plainText, cipherText); } +#ifndef _CUT_AUTHENTICATE_ return HksClientEncrypt(key, paramSet, plainText, cipherText); +#else + return HKS_ERROR_NOT_SUPPORTED; +#endif #else (void)key; (void)paramSet; @@ -213,7 +267,7 @@ HKS_API_EXPORT int32_t HksEncrypt(const struct HksBlob *key, const struct HksPar HKS_API_EXPORT int32_t HksDecrypt(const struct HksBlob *key, const struct HksParamSet *paramSet, const struct HksBlob *cipherText, struct HksBlob *plainText) { -#ifdef HKS_SUPPORT_CIPHER +#ifdef HKS_SUPPORT_API_CIPHER if ((key == NULL) || (paramSet == NULL) || (cipherText == NULL) || (plainText == NULL)) { return HKS_ERROR_NULL_POINTER; } @@ -223,7 +277,11 @@ HKS_API_EXPORT int32_t HksDecrypt(const struct HksBlob *key, const struct HksPar if ((ret == HKS_SUCCESS) && (!isKeyAlias->boolParam)) { return HksLocalDecrypt(key, paramSet, cipherText, plainText); } +#ifndef _CUT_AUTHENTICATE_ return HksClientDecrypt(key, paramSet, cipherText, plainText); +#else + return HKS_ERROR_NOT_SUPPORTED; +#endif #else (void)key; (void)paramSet; @@ -236,7 +294,7 @@ HKS_API_EXPORT int32_t HksDecrypt(const struct HksBlob *key, const struct HksPar HKS_API_EXPORT int32_t HksAgreeKey(const struct HksParamSet *paramSet, const struct HksBlob *privateKey, const struct HksBlob *peerPublicKey, struct HksBlob *agreedKey) { -#ifdef HKS_SUPPORT_AGREE_KEY +#ifdef HKS_SUPPORT_API_AGREE_KEY if ((paramSet == NULL) || (privateKey == NULL) || (peerPublicKey == NULL) || (agreedKey == NULL)) { return HKS_ERROR_NULL_POINTER; } @@ -246,6 +304,7 @@ HKS_API_EXPORT int32_t HksAgreeKey(const struct HksParamSet *paramSet, const str if ((ret == HKS_SUCCESS) && (!isKeyAlias->boolParam)) { return HksLocalAgreeKey(paramSet, privateKey, peerPublicKey, agreedKey); } + return HksClientAgreeKey(paramSet, privateKey, peerPublicKey, agreedKey); #else (void)paramSet; @@ -259,7 +318,7 @@ HKS_API_EXPORT int32_t HksAgreeKey(const struct HksParamSet *paramSet, const str HKS_API_EXPORT int32_t HksDeriveKey(const struct HksParamSet *paramSet, const struct HksBlob *mainKey, struct HksBlob *derivedKey) { -#ifdef HKS_SUPPORT_DERIVE_KEY +#ifdef HKS_SUPPORT_API_DERIVE_KEY if ((paramSet == NULL) || (mainKey == NULL) || (derivedKey == NULL)) { return HKS_ERROR_NULL_POINTER; } @@ -269,7 +328,11 @@ HKS_API_EXPORT int32_t HksDeriveKey(const struct HksParamSet *paramSet, const st if ((ret == HKS_SUCCESS) && (!isKeyAlias->boolParam)) { return HksLocalDeriveKey(paramSet, mainKey, derivedKey); } +#ifndef _CUT_AUTHENTICATE_ return HksClientDeriveKey(paramSet, mainKey, derivedKey); +#else + return HKS_ERROR_NOT_SUPPORTED; +#endif #else (void)paramSet; (void)mainKey; @@ -281,7 +344,7 @@ HKS_API_EXPORT int32_t HksDeriveKey(const struct HksParamSet *paramSet, const st HKS_API_EXPORT int32_t HksMac(const struct HksBlob *key, const struct HksParamSet *paramSet, const struct HksBlob *srcData, struct HksBlob *mac) { -#ifdef HKS_SUPPORT_MAC +#ifdef HKS_SUPPORT_API_MAC if ((key == NULL) || (paramSet == NULL) || (srcData == NULL) || (mac == NULL)) { return HKS_ERROR_NULL_POINTER; } @@ -291,7 +354,11 @@ HKS_API_EXPORT int32_t HksMac(const struct HksBlob *key, const struct HksParamSe if ((ret == HKS_SUCCESS) && (!isKeyAlias->boolParam)) { return HksLocalMac(key, paramSet, srcData, mac); } +#ifndef _CUT_AUTHENTICATE_ return HksClientMac(key, paramSet, srcData, mac); +#else + return HKS_ERROR_NOT_SUPPORTED; +#endif #else (void)key; (void)paramSet; @@ -304,7 +371,7 @@ HKS_API_EXPORT int32_t HksMac(const struct HksBlob *key, const struct HksParamSe HKS_API_EXPORT int32_t HksHash(const struct HksParamSet *paramSet, const struct HksBlob *srcData, struct HksBlob *hash) { -#ifdef HKS_SUPPORT_HASH +#ifdef HKS_SUPPORT_API_HASH if ((paramSet == NULL) || (srcData == NULL) || (hash == NULL)) { return HKS_ERROR_NULL_POINTER; } @@ -320,7 +387,7 @@ HKS_API_EXPORT int32_t HksHash(const struct HksParamSet *paramSet, HKS_API_EXPORT int32_t HksGetKeyInfoList(const struct HksParamSet *paramSet, struct HksKeyInfo *keyInfoList, uint32_t *listCount) { -#ifdef HKS_SUPPORT_GET_KEY_INFO_LIST +#ifdef HKS_SUPPORT_API_GET_KEY_INFO_LIST (void)paramSet; if ((keyInfoList == NULL) || (listCount == NULL)) { return HKS_ERROR_NULL_POINTER; @@ -337,7 +404,7 @@ HKS_API_EXPORT int32_t HksGetKeyInfoList(const struct HksParamSet *paramSet, HKS_API_EXPORT int32_t HksAttestKey(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, struct HksCertChain *certChain) { -#ifdef HKS_SUPPORT_ATTEST_KEY +#ifdef HKS_SUPPORT_API_ATTEST_KEY if ((keyAlias == NULL) || (paramSet == NULL) || (certChain == NULL)) { return HKS_ERROR_NULL_POINTER; } @@ -353,7 +420,7 @@ HKS_API_EXPORT int32_t HksAttestKey(const struct HksBlob *keyAlias, const struct HKS_API_EXPORT int32_t HksGetCertificateChain(const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, struct HksCertChain *certChain) { -#ifdef HKS_SUPPORT_ATTEST_KEY +#ifdef HKS_SUPPORT_API_GET_CERTIFICATE_CHAIN if ((keyAlias == NULL) || (paramSet == NULL) || (certChain == NULL)) { return HKS_ERROR_NULL_POINTER; } @@ -369,7 +436,7 @@ HKS_API_EXPORT int32_t HksGetCertificateChain(const struct HksBlob *keyAlias, co HKS_API_EXPORT int32_t HksWrapKey(const struct HksBlob *keyAlias, const struct HksBlob *targetKeyAlias, const struct HksParamSet *paramSet, struct HksBlob *wrappedData) { -#ifdef HKS_SUPPORT_WRAP_KEY +#ifdef HKS_SUPPORT_API_WRAP_KEY if ((keyAlias == NULL) || (targetKeyAlias == NULL) || (paramSet == NULL) || (wrappedData == NULL)) { return HKS_ERROR_NULL_POINTER; } @@ -386,7 +453,7 @@ HKS_API_EXPORT int32_t HksWrapKey(const struct HksBlob *keyAlias, const struct H HKS_API_EXPORT int32_t HksUnwrapKey(const struct HksBlob *keyAlias, const struct HksBlob *targetKeyAlias, const struct HksBlob *wrappedData, const struct HksParamSet *paramSet) { -#ifdef HKS_SUPPORT_UNWRAP_KEY +#ifdef HKS_SUPPORT_API_UNWRAP_KEY if ((keyAlias == NULL) || (targetKeyAlias == NULL) || (wrappedData == NULL) || (paramSet == NULL)) { return HKS_ERROR_NULL_POINTER; } @@ -403,10 +470,11 @@ HKS_API_EXPORT int32_t HksUnwrapKey(const struct HksBlob *keyAlias, const struct HKS_API_EXPORT int32_t HksBnExpMod(struct HksBlob *x, const struct HksBlob *a, const struct HksBlob *e, const struct HksBlob *n) { -#ifdef HKS_SUPPORT_BN_EXP_MOD +#ifdef HKS_SUPPORT_API_BN_EXP_MOD if ((x == NULL) || (a == NULL) || (e == NULL) || (n == NULL)) { return HKS_ERROR_NULL_POINTER; } + return HksLocalBnExpMod(x, a, e, n); #else (void)x; diff --git a/interfaces/innerkits/huks_standard/test/unittest/include/hks_test_api_performance.h b/interfaces/innerkits/huks_standard/test/unittest/include/hks_test_api_performance.h index fdc64f4d..5f626b04 100755 --- a/interfaces/innerkits/huks_standard/test/unittest/include/hks_test_api_performance.h +++ b/interfaces/innerkits/huks_standard/test/unittest/include/hks_test_api_performance.h @@ -18,6 +18,8 @@ #include "hks_type.h" +#include "securec.h" + #ifdef __cplusplus extern "C" { #endif @@ -37,7 +39,6 @@ int32_t HksMacRun(const struct HksBlob *key, const struct HksParamSet *paramSet, int32_t HksDeriveKeyRun(const struct HksParamSet *paramSet, const struct HksBlob *masterKey, struct HksBlob *derivedKey, uint32_t performTimes); - int32_t HksDeleteKeyRun(const struct HksBlob *keyAlias, uint32_t performTimes); int32_t HksKeyExistRun(const struct HksBlob *keyAlias, uint32_t performTimes); diff --git a/interfaces/innerkits/huks_standard/test/unittest/include/hks_test_common.h b/interfaces/innerkits/huks_standard/test/unittest/include/hks_test_common.h index ae681ec6..1b4b06fd 100755 --- a/interfaces/innerkits/huks_standard/test/unittest/include/hks_test_common.h +++ b/interfaces/innerkits/huks_standard/test/unittest/include/hks_test_common.h @@ -17,6 +17,7 @@ #define HKS_TEST_COMMON_H #include "hks_type.h" +#include "securec.h" #define GOTO_ERROR_IF_FAIL(ret, err) \ if ((ret) != 0) { \ diff --git a/interfaces/innerkits/huks_standard/test/unittest/include/hks_test_curve25519.h b/interfaces/innerkits/huks_standard/test/unittest/include/hks_test_curve25519.h index faee5af3..68b88ec5 100755 --- a/interfaces/innerkits/huks_standard/test/unittest/include/hks_test_curve25519.h +++ b/interfaces/innerkits/huks_standard/test/unittest/include/hks_test_curve25519.h @@ -17,6 +17,8 @@ #define HKS_TEST_CURVE25519 #include "hks_type.h" +#include "securec.h" + #ifdef __cplusplus extern "C" { #endif diff --git a/interfaces/innerkits/huks_standard/test/unittest/src/hks_test_file_operator.c b/interfaces/innerkits/huks_standard/test/unittest/src/hks_test_file_operator.c index a5faa512..1f316816 100755 --- a/interfaces/innerkits/huks_standard/test/unittest/src/hks_test_file_operator.c +++ b/interfaces/innerkits/huks_standard/test/unittest/src/hks_test_file_operator.c @@ -27,6 +27,8 @@ #include "hks_test_mem.h" #include "hks_type.h" +#include "securec.h" + #define HKS_MAX_FILE_NAME_LEN 512 static int32_t GetFileName(const char *path, const char *fileName, char *fullFileName, uint32_t fullFileNameLen) diff --git a/services/huks_standard/BUILD.gn b/services/huks_standard/BUILD.gn index 6cd90fd1..40a12e8d 100644 --- a/services/huks_standard/BUILD.gn +++ b/services/huks_standard/BUILD.gn @@ -16,7 +16,11 @@ import("//build/ohos.gni") ohos_shared_library("libhukssrv") { subsystem_name = "security" part_name = "huks_standard" - + defines = [ + "L2_STANDARD", + "_HARDWARE_ROOT_KEY_", + "_HUKS_LOG_ENABLE_", + ] deps = [ "//base/security/huks/services/huks_standard/huks_engine/main:libhuks_engine_standard_static", "//base/security/huks/services/huks_standard/huks_service/main:libhuks_service_standard_static", diff --git a/services/huks_standard/huks_engine/main/BUILD.gn b/services/huks_standard/huks_engine/main/BUILD.gn index 7ee15d76..c117b48a 100644 --- a/services/huks_standard/huks_engine/main/BUILD.gn +++ b/services/huks_standard/huks_engine/main/BUILD.gn @@ -16,6 +16,11 @@ import("//build/ohos.gni") ohos_static_library("libhuks_engine_standard_static") { subsystem_name = "security" part_name = "huks_standard" + defines = [ + "L2_STANDARD", + "_HARDWARE_ROOT_KEY_", + "_HUKS_LOG_ENABLE_", + ] public_deps = [ "//base/security/huks/services/huks_standard/huks_engine/main/core:libhuks_engine_core_standard_static" ] complete_static_lib = true diff --git a/services/huks_standard/huks_engine/main/core/BUILD.gn b/services/huks_standard/huks_engine/main/core/BUILD.gn index 74d71f9a..193a3212 100644 --- a/services/huks_standard/huks_engine/main/core/BUILD.gn +++ b/services/huks_standard/huks_engine/main/core/BUILD.gn @@ -21,6 +21,11 @@ ohos_static_library("libhuks_engine_core_standard_static") { subsystem_name = "security" part_name = "huks_standard" public_configs = [ ":huks_config" ] + defines = [ + "L2_STANDARD", + "_HARDWARE_ROOT_KEY_", + "_HUKS_LOG_ENABLE_", + ] include_dirs = [ "//utils/native/base/include", "//third_party/openssl/include/", diff --git a/services/huks_standard/huks_engine/main/core/include/hks_auth.h b/services/huks_standard/huks_engine/main/core/include/hks_auth.h index 79408a85..bd7ddd1d 100644 --- a/services/huks_standard/huks_engine/main/core/include/hks_auth.h +++ b/services/huks_standard/huks_engine/main/core/include/hks_auth.h @@ -17,7 +17,7 @@ #define HKS_AUTH_H #include "hks_keyblob.h" -#include "hks_type.h" +#include "hks_type_inner.h" enum HksAuthId { HKS_AUTH_ID_SIGN_VERIFY_RSA = 0x1, diff --git a/services/huks_standard/huks_engine/main/core/include/hks_core_service.h b/services/huks_standard/huks_engine/main/core/include/hks_core_service.h index 661d3946..0afcc01d 100755 --- a/services/huks_standard/huks_engine/main/core/include/hks_core_service.h +++ b/services/huks_standard/huks_engine/main/core/include/hks_core_service.h @@ -17,7 +17,7 @@ #define HKS_CORE_SERVICE_H #include "hks_crypto_hal.h" -#include "hks_type.h" +#include "hks_type_inner.h" #define MAX_HASH_SIZE 64 @@ -61,13 +61,13 @@ int32_t HksCoreInitialize(void); int32_t HksCoreRefreshKeyInfo(void); -#ifdef _STORAGE_LITE_ +int32_t HksCoreUpgradeKeyInfo(const struct HksBlob *keyAlias, const struct HksBlob *keyInfo, struct HksBlob *keyOut); + int32_t HksCoreCalcMacHeader(const struct HksParamSet *paramSet, const struct HksBlob *salt, const struct HksBlob *srcData, struct HksBlob *mac); -#endif #ifdef __cplusplus } #endif -#endif /* HKS_ACCESS_H */ +#endif /* HKS_CORE_SERVICE_H */ diff --git a/services/huks_standard/huks_engine/main/core/include/hks_keyblob.h b/services/huks_standard/huks_engine/main/core/include/hks_keyblob.h index 444fb63c..01a47f5e 100644 --- a/services/huks_standard/huks_engine/main/core/include/hks_keyblob.h +++ b/services/huks_standard/huks_engine/main/core/include/hks_keyblob.h @@ -16,7 +16,7 @@ #ifndef HKS_KEYBLOB_H #define HKS_KEYBLOB_H -#include "hks_type.h" +#include "hks_type_inner.h" #define HKS_KEY_BLOB_DERIVE_SALT_SIZE 16 #define HKS_KEY_BLOB_DERIVE_CNT 1000 diff --git a/services/huks_standard/huks_engine/main/core/include/hks_rkc.h b/services/huks_standard/huks_engine/main/core/include/hks_rkc.h new file mode 100644 index 00000000..6cdfa3d4 --- /dev/null +++ b/services/huks_standard/huks_engine/main/core/include/hks_rkc.h @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_RKC_H +#define HKS_RKC_H + +#include "hks_type_inner.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t HksRkcInit(void); + +void HksRkcDestroy(void); + +void HksRkcClearMem(void); + +int32_t HksRkcGetMainKey(struct HksBlob *mainKey); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_RKC_H */ diff --git a/services/huks_standard/huks_engine/main/core/include/hks_rkc_rw.h b/services/huks_standard/huks_engine/main/core/include/hks_rkc_rw.h new file mode 100644 index 00000000..f27d593d --- /dev/null +++ b/services/huks_standard/huks_engine/main/core/include/hks_rkc_rw.h @@ -0,0 +1,113 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_RKC_RW_H +#define HKS_RKC_RW_H + +#include "hks_type_inner.h" + +#define HKS_RKC_VER 1 /* the version of root key component */ +#define HKS_RKC_RMK_ITER 1 /* the iterator number of times which derive Root Main Key */ +#define HKS_RKC_RMK_HMAC_SHA256 1 /* the hash algorithm which derive Root Main Key */ +#define HKS_RKC_MK_CRYPT_ALG_AES256_GCM 1 /* the encrypt algorithm of main key */ +#define HKS_RKC_CFG_RSV_LEN 32 /* the reserve length of the system configuration */ +#define HKS_RKC_KSF_FLAG_LEN 8 /* the length of keystore file flag */ +#define HKS_RKC_MATERIAL_LEN 32 /* the material length of root key component */ +#define HKS_RKC_SALT_LEN 32 /* the salt length of root key component */ +#define HKS_RKC_KSF_DATA_RSV_LEN 8 /* the reserve length of the keystore file data */ +#define HKS_RKC_MK_IV_LEN 16 /* the tag length of main key */ +#define HKS_RKC_MK_CIPHER_TEXT_LEN 48 /* the cipher length of main key */ +#define HKS_RKC_MK_LEN 32 /* the length of main key */ +#define HKS_RKC_KSF_NUM 2 /* the keystore file number of root key component */ + +/* the storage type of root key component */ +enum HksRkcStorageType { + HKS_RKC_STORAGE_FILE_SYS = 0, /* file system */ + HKS_RKC_STORAGE_FLASH = 1, /* flash */ +}; + +/* the state of root key component */ +enum HksRkcState { + HKS_RKC_STATE_INVALID = 0, + HKS_RKC_STATE_VALID = 1, +}; + +/* time */ +struct HksTime { + uint16_t hksYear; + uint8_t hksMon; + uint8_t hksDay; + uint8_t hksHour; + uint8_t hksMin; + uint8_t hksSec; +}; + +/* the attribute of keystore file */ +struct HksRkcKsfAttr { + uint8_t num; /* the number of files */ + char *name[HKS_RKC_KSF_NUM]; +}; + +/* the keystore file data of root key component */ +struct HksRkcKsfData { + uint16_t version; /* version */ + struct HksTime rkCreatedTime; /* the created time of rook key */ + struct HksTime rkExpiredTime; /* the expired time of rook key */ + uint8_t rkMaterial1[HKS_RKC_MATERIAL_LEN]; /* the first material of root key */ + uint8_t rkMaterial2[HKS_RKC_MATERIAL_LEN]; /* the second material of root key */ + uint32_t rmkIter; /* the iterator number of times which derive root main key */ + uint8_t rmkSalt[HKS_RKC_SALT_LEN]; /* the salt which derive root main key */ + uint32_t rmkHashAlg; /* the hash algorithm which derive root main key */ + uint8_t rkRsv[HKS_RKC_KSF_DATA_RSV_LEN]; /* mk_rsv data for root key, 32 byte */ + struct HksTime mkCreatedTime; /* the created time of main key */ + struct HksTime mkExpiredTime; /* the expired time of main key */ + uint32_t mkEncryptAlg; /* the encrption algorithm of main key */ + uint8_t mkIv[HKS_RKC_MK_IV_LEN]; /* the IV of main key */ + uint8_t mkCiphertext[HKS_RKC_MK_CIPHER_TEXT_LEN]; /* the ciphertext of main key */ + uint8_t mkRsv[HKS_RKC_KSF_DATA_RSV_LEN]; /* mk_rsv data for main key, 32 byte */ +}; + +/* the configuration of root key component */ +struct HksRkcCfg { + uint8_t state; /* system state */ + uint16_t version; /* the version of root key component */ + uint8_t storageType; /* the storage type of root key component */ + struct HksTime rkCreatedTime; /* the created time of rook key */ + struct HksTime rkExpiredTime; /* the expired time of rook key */ + struct HksRkcKsfAttr ksfAttr; /* the attribute of keystore file */ + uint32_t rmkIter; /* the iterator number of times which derive Root Main Key */ + uint32_t rmkHashAlg; /* the hash algorithm which derive Root Main Key */ + uint8_t mkMask[HKS_RKC_MK_LEN]; /* the mask of main key */ + uint32_t mkEncryptAlg; /* the encrption algorithm of main key */ + uint8_t reserve[HKS_RKC_CFG_RSV_LEN]; /* reserve data, 32 byte */ +}; + +extern struct HksRkcCfg g_hksRkcCfg; + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t HksRkcReadKsf(const char *ksfName, struct HksRkcKsfData *ksfData); + +int32_t HksRkcWriteKsf(const char *ksfName, const struct HksRkcKsfData *ksfData); + +bool RkcKsfExist(void); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_RKC_RW_H */ diff --git a/services/huks_standard/huks_engine/main/core/include/hks_upgrade_key_info.h b/services/huks_standard/huks_engine/main/core/include/hks_upgrade_key_info.h new file mode 100644 index 00000000..9c735f47 --- /dev/null +++ b/services/huks_standard/huks_engine/main/core/include/hks_upgrade_key_info.h @@ -0,0 +1,31 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_UPGRADE_KEY_INFO_H +#define HKS_UPGRADE_KEY_INFO_H + +#include "hks_type_inner.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t HksUpgradeKeyInfo(const struct HksBlob *keyAlias, const struct HksBlob *keyInfo, struct HksBlob *keyOut); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_UPGRADE_KEY_INFO_H */ diff --git a/services/huks_standard/huks_engine/main/core/src/hks_auth.c b/services/huks_standard/huks_engine/main/core/src/hks_auth.c index 7c0ad032..3e458f8b 100644 --- a/services/huks_standard/huks_engine/main/core/src/hks_auth.c +++ b/services/huks_standard/huks_engine/main/core/src/hks_auth.c @@ -16,7 +16,7 @@ #include "hks_auth.h" #include "hks_log.h" #include "hks_param.h" -#include "hks_type.h" +#include "hks_type_inner.h" struct HksAuthPolicy { uint32_t authId; @@ -24,6 +24,7 @@ struct HksAuthPolicy { uint32_t *policyTag; }; +#ifndef _CUT_AUTHENTICATE_ static uint32_t g_symCipherPolicyTag[] = { HKS_TAG_ALGORITHM, HKS_TAG_BLOCK_MODE, HKS_TAG_PADDING, HKS_TAG_PURPOSE }; static uint32_t g_asymCipherPolicyTag[] = { HKS_TAG_ALGORITHM, HKS_TAG_DIGEST, HKS_TAG_PADDING, HKS_TAG_PURPOSE }; static uint32_t g_signVerifyRsaPolicyTag[] = { HKS_TAG_ALGORITHM, HKS_TAG_DIGEST, HKS_TAG_PADDING, HKS_TAG_PURPOSE }; @@ -93,3 +94,5 @@ int32_t HksAuth(uint32_t authId, const struct HksKeyNode *keyNode, const struct } return HKS_ERROR_BAD_STATE; } + +#endif /* _CUT_AUTHENTICATE_ */ diff --git a/services/huks_standard/huks_engine/main/core/src/hks_core_service.c b/services/huks_standard/huks_engine/main/core/src/hks_core_service.c index 30cb23bf..38f061ae 100755 --- a/services/huks_standard/huks_engine/main/core/src/hks_core_service.c +++ b/services/huks_standard/huks_engine/main/core/src/hks_core_service.c @@ -13,24 +13,35 @@ * limitations under the License. */ +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + #include "hks_core_service.h" + #include "hks_auth.h" #include "hks_check_paramset.h" #include "hks_cmd_id.h" #include "hks_crypto_adapter.h" #include "hks_crypto_hal.h" -#ifdef HKS_HAL_ENGINE_CONFIG_FILE -#include HKS_HAL_ENGINE_CONFIG_FILE -#else -#include "hks_crypto_hal_config.h" -#endif #include "hks_keyblob.h" #include "hks_log.h" #include "hks_mem.h" #include "hks_param.h" -#include "hks_type.h" +#include "hks_type_inner.h" + +#ifndef _HARDWARE_ROOT_KEY_ +#include "hks_rkc.h" +#endif + +#ifdef HKS_SUPPORT_UPGRADE_STORAGE_DATA +#include "hks_upgrade_key_info.h" +#endif -#define CURVE25519_KEY_BYTE_SIZE HKS_CURVE25519_KEY_SIZE_256 / HKS_BITS_PER_BYTE +#ifndef _CUT_AUTHENTICATE_ +#define CURVE25519_KEY_BYTE_SIZE HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256) static int32_t GetGenType(const struct HksParamSet *paramSet, uint32_t *genType) { @@ -63,13 +74,13 @@ static int32_t GetGenType(const struct HksParamSet *paramSet, uint32_t *genType) } break; default: - HKS_LOG_E("invalid generated key tpye"); + HKS_LOG_E("invalid generated key type"); } return ret; } -#if defined(HKS_SUPPORT_X25519_C) || defined(HKS_SUPPORT_ED25519_C) +#ifdef HKS_SUPPORT_ED25519_TO_X25519 int32_t CheckAgreeKeyIn(const struct HksBlob *key) { if (CheckBlob(key) != HKS_SUCCESS) { @@ -82,7 +93,8 @@ int32_t CheckAgreeKeyIn(const struct HksBlob *key) } struct Hks25519KeyPair *keyPair = (struct Hks25519KeyPair *)(key->data); - if (key->size < (sizeof(*keyPair) + keyPair->privateBufferSize + keyPair->publicBufferSize)) { /* overflow check */ + if ((keyPair->privateBufferSize > (key->size - sizeof(*keyPair))) || + (keyPair->publicBufferSize > (key->size - sizeof(*keyPair) - keyPair->privateBufferSize))) { HKS_LOG_E("invlaid agree key size, small than keyPair"); return HKS_ERROR_INVALID_ARGUMENT; } @@ -140,7 +152,7 @@ int32_t GetAgreePubKey(const struct HksBlob *keyIn, const struct HksParamSet *pa { struct HksParam *isKeyAliasParam = NULL; int32_t ret = HksGetParam(paramSet, HKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS, &isKeyAliasParam); - if ((ret == HKS_SUCCESS) && (isKeyAliasParam->boolParam == false)) { + if ((ret == HKS_SUCCESS) && (!(isKeyAliasParam->boolParam))) { return GetAgreeBaseKey(true, true, keyIn, keyOut); } @@ -242,7 +254,7 @@ int32_t HksCoreGenerateKey(const struct HksBlob *keyAlias, const struct HksParam break; } case HKS_KEY_GENERATE_TYPE_AGREE: -#if defined(HKS_SUPPORT_X25519_C) || defined(HKS_SUPPORT_ED25519_C) +#ifdef HKS_SUPPORT_ED25519_TO_X25519 ret = GenKeyByAgree(keyIn, paramSet, &key); #else ret = HKS_ERROR_INVALID_ARGUMENT; @@ -253,8 +265,6 @@ int32_t HksCoreGenerateKey(const struct HksBlob *keyAlias, const struct HksParam } if (ret != HKS_SUCCESS) { HKS_LOG_E("GenerateKey failed, ret:%x!", ret); - (void)memset_s(key.data, key.size, 0, key.size); - HKS_FREE_BLOB(key); return ret; } @@ -513,12 +523,6 @@ int32_t HksCheckKeyValidity(const struct HksParamSet *paramSet, const struct Hks return HKS_SUCCESS; } -int32_t HksCoreGenerateRandom(const struct HksParamSet *paramSet, struct HksBlob *random) -{ - (void)paramSet; - return HksCryptoHalFillRandom(random); -} - int32_t HksCoreImportKey(const struct HksBlob *keyAlias, const struct HksBlob *key, const struct HksParamSet *paramSet, struct HksBlob *keyOut) { @@ -674,5 +678,98 @@ int32_t HksCoreMac(const struct HksBlob *key, const struct HksParamSet *paramSet int32_t HksCoreInitialize(void) { +#ifndef _HARDWARE_ROOT_KEY_ + int32_t ret = HksRkcInit(); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Hks rkc init failed! ret = 0x%X", ret); + } + + return ret; +#else return HKS_SUCCESS; +#endif } + +int32_t HksCoreRefreshKeyInfo(void) +{ +#ifndef _HARDWARE_ROOT_KEY_ + HksRkcDestroy(); + int32_t ret = HksRkcInit(); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Hks rkc refresh info failed! ret = 0x%X", ret); + } + + return ret; +#else + return HKS_SUCCESS; +#endif +} + +#ifdef HKS_SUPPORT_UPGRADE_STORAGE_DATA +int32_t HksCoreUpgradeKeyInfo(const struct HksBlob *keyAlias, const struct HksBlob *keyInfo, struct HksBlob *keyOut) +{ + return HksUpgradeKeyInfo(keyAlias, keyInfo, keyOut); +} +#endif + +#ifdef _STORAGE_LITE_ +static int32_t GetMacKey(const struct HksBlob *salt, struct HksBlob *macKey) +{ + uint8_t keyBuf[HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256)] = {0}; + struct HksBlob mk = { HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256), keyBuf }; + + int32_t ret = HksCryptoHalGetMainKey(NULL, &mk); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get kek failed, ret = %d", ret); + return ret; + } + + struct HksKeyDerivationParam derParam = { + .salt = *salt, + .iterations = HKS_KEY_BLOB_DERIVE_CNT, + .digestAlg = HKS_DIGEST_SHA256, + }; + struct HksKeySpec derivationSpec = { HKS_ALG_PBKDF2, HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256), &derParam }; + ret = HksCryptoHalDeriveKey(&mk, &derivationSpec, macKey); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get keyblob derive key failed!"); + } + + (void)memset_s(mk.data, mk.size, 0, mk.size); + return ret; +} + +int32_t HksCoreCalcMacHeader(const struct HksParamSet *paramSet, const struct HksBlob *salt, + const struct HksBlob *srcData, struct HksBlob *mac) +{ + /* 1. get mac key by derive from salt */ + uint8_t keyBuf[HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256)] = {0}; + struct HksBlob macKey = { HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256), keyBuf }; + int32_t ret = GetMacKey(salt, &macKey); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get mac key failed, ret = %d", ret); + return ret; + } + + struct HksParam *digestParam = NULL; + ret = HksGetParam(paramSet, HKS_TAG_DIGEST, &digestParam); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("calc mac header get HKS_TAG_DIGEST param failed, ret = %d", ret); + (void)memset_s(macKey.data, macKey.size, 0, macKey.size); + return ret; + } + + /* 2. do mac */ + ret = HksCryptoHalHmac(&macKey, digestParam->uint32Param, srcData, mac); + (void)memset_s(macKey.data, macKey.size, 0, macKey.size); + return ret; +} +#endif +#endif /* _CUT_AUTHENTICATE_ */ + +int32_t HksCoreGenerateRandom(const struct HksParamSet *paramSet, struct HksBlob *random) +{ + (void)paramSet; + return HksCryptoHalFillRandom(random); +} + diff --git a/services/huks_standard/huks_engine/main/core/src/hks_keyblob.c b/services/huks_standard/huks_engine/main/core/src/hks_keyblob.c index afffb90c..7883a44e 100755 --- a/services/huks_standard/huks_engine/main/core/src/hks_keyblob.c +++ b/services/huks_standard/huks_engine/main/core/src/hks_keyblob.c @@ -14,13 +14,16 @@ */ #include "hks_keyblob.h" + #include "hks_crypto_adapter.h" #include "hks_crypto_hal.h" #include "hks_file_operator.h" #include "hks_log.h" #include "hks_mem.h" #include "hks_param.h" -#include "hks_type.h" +#include "hks_type_inner.h" + +#ifndef _CUT_AUTHENTICATE_ #define HKS_KEY_BLOB_DUMMY_KEY_VERSION 1 #define HKS_KEY_BLOB_DUMMY_OS_VERSION 1 @@ -33,7 +36,7 @@ struct HksKeyBlobInfo { uint32_t keySize; }; -static void CleanKey(struct HksParamSet *paramSet) +static void CleanKey(const struct HksParamSet *paramSet) { struct HksParam *keyParam = NULL; int32_t ret = HksGetParam(paramSet, HKS_TAG_KEY, &keyParam); @@ -59,6 +62,8 @@ void HksFreeKeyNode(struct HksKeyNode **keyNode) } } +#ifndef _STORAGE_LITE_ +#ifdef L2_STANDARD #define HKS_ENCRYPT_KEY_NAME "root_encrypt_key" static int32_t WriteEncryptKey(struct HksBlob *key) @@ -90,6 +95,12 @@ static int32_t GetEncryptKey(struct HksBlob *key) return HKS_SUCCESS; } } +#else +static int32_t GetEncryptKey(struct HksBlob *mainKey) +{ + return HksCryptoHalGetMainKey(NULL, mainKey); +} +#endif static int32_t GetSalt(const struct HksParamSet *paramSet, const struct HksKeyBlobInfo *keyBlobInfo, struct HksBlob *salt) @@ -158,6 +169,7 @@ static int32_t GetDeriveKey(const struct HksParamSet *paramSet, const struct Hks if (derivedKey->data == NULL) { HKS_LOG_E("malloc failed"); HKS_FREE_BLOB(salt); + (void)memset_s(encryptKeyData, HKS_KEY_BLOB_MAIN_KEY_SIZE, 0, HKS_KEY_BLOB_MAIN_KEY_SIZE); return HKS_ERROR_MALLOC_FAIL; } @@ -166,6 +178,7 @@ static int32_t GetDeriveKey(const struct HksParamSet *paramSet, const struct Hks HKS_LOG_E("get keyblob derived key failed!"); HKS_FREE_PTR(derivedKey->data); } + (void)memset_s(encryptKeyData, HKS_KEY_BLOB_MAIN_KEY_SIZE, 0, HKS_KEY_BLOB_MAIN_KEY_SIZE); HKS_FREE_BLOB(salt); return ret; @@ -547,3 +560,7 @@ int32_t HksBuildKeyBlob(const struct HksBlob *keyAlias, uint8_t keyFlag, const s HksFreeParamSet(&keyBlobParamSet); return HKS_SUCCESS; } + +#endif + +#endif /* _CUT_AUTHENTICATE_ */ diff --git a/services/huks_standard/huks_engine/main/core/src/hks_keyblob_lite.c b/services/huks_standard/huks_engine/main/core/src/hks_keyblob_lite.c new file mode 100644 index 00000000..ddfa2e11 --- /dev/null +++ b/services/huks_standard/huks_engine/main/core/src/hks_keyblob_lite.c @@ -0,0 +1,539 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + + +#ifndef _CUT_AUTHENTICATE_ +#ifdef _STORAGE_LITE_ + +#include "hks_keyblob.h" +#include "hks_crypto_hal.h" +#include "hks_log.h" +#include "hks_mem.h" +#include "hks_param.h" +#include "hks_storage_adapter.h" + +static const char g_deriveKekTag[] = "derive_key"; +static const char g_deriveNonceTag[] = "derive_nonce"; + +enum DeriveType { + DERIVE_KEK = 0, + DERIVE_NONCE = 1, +}; + +static int32_t HksBlobInit(struct HksBlob *blob, uint32_t size) +{ + blob->data = (uint8_t *)HksMalloc(size); + if (blob->data == NULL) { + HKS_LOG_E("malloc failed"); + return HKS_ERROR_MALLOC_FAIL; + } + blob->size = size; + return HKS_SUCCESS; +} + +static int32_t GetSalt(enum DeriveType type, const struct HksBlob *random, struct HksBlob *salt) +{ + struct HksBlob tag = { 0, NULL }; + if (type == DERIVE_KEK) { + tag.size = strlen(g_deriveKekTag); + tag.data = (uint8_t *)g_deriveKekTag; + } else if (type == DERIVE_NONCE) { + tag.size = strlen(g_deriveNonceTag); + tag.data = (uint8_t *)g_deriveNonceTag; + } + + int32_t ret = HksBlobInit(salt, random->size + tag.size); + if (ret != HKS_SUCCESS) { + return ret; + } + + if ((memcpy_s(salt->data, salt->size, random->data, random->size) != EOK) || + (memcpy_s(salt->data + random->size, salt->size - random->size, tag.data, tag.size) != EOK)) { + HKS_FREE_PTR(salt->data); + return HKS_ERROR_BAD_STATE; + } + return ret; +} + +static int32_t GetDeriveMaterial(enum DeriveType type, const struct HksBlob *random, struct HksBlob *derivedMaterial) +{ + uint8_t keyBuf[HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256)] = {0}; + struct HksBlob mk = { HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256), keyBuf }; + + int32_t ret = HksCryptoHalGetMainKey(NULL, &mk); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get kek failed, ret = %d", ret); + return ret; + } + + struct HksBlob salt = { 0, NULL }; + ret = GetSalt(type, random, &salt); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get salt failed, ret = %d", ret); + (void)memset_s(mk.data, mk.size, 0, mk.size); + return ret; + } + + struct HksKeyDerivationParam derParam = { + .salt = salt, + .iterations = HKS_KEY_BLOB_DERIVE_CNT, + .digestAlg = HKS_DIGEST_SHA256, + }; + struct HksKeySpec derivationSpec = { HKS_ALG_PBKDF2, HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256), &derParam }; + ret = HksCryptoHalDeriveKey(&mk, &derivationSpec, derivedMaterial); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get keyblob derive material failed, type = %u", type); + } + + HKS_FREE_BLOB(salt); + (void)memset_s(mk.data, mk.size, 0, mk.size); + return ret; +} + +static int32_t BuildKeyBlobUsageSpec(const struct HksBlob *cipherKey, const struct HksBlob *random, + bool isEncrypt, struct HksUsageSpec *usageSpec) +{ + usageSpec->mode = HKS_MODE_GCM; + usageSpec->padding = HKS_PADDING_NONE; + usageSpec->digest = HKS_DIGEST_NONE; + usageSpec->algType = HKS_ALG_AES; + + struct HksStoreKeyInfo *keyInfo = (struct HksStoreKeyInfo *)cipherKey->data; + + /* get nonce, derive from random + tag("derive_nonce") */ + struct HksBlob nonce = { 0, NULL }; + int32_t ret = HksBlobInit(&nonce, HKS_KEY_BLOB_NONCE_SIZE); /* need free by caller function */ + if (ret != HKS_SUCCESS) { + return ret; + } + ret = GetDeriveMaterial(DERIVE_NONCE, random, &nonce); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get derive material nonce failed, ret = %d", ret); + HKS_FREE_PTR(nonce.data); + return ret; + } + + /* aad: from keyInfo->keySize to authId */ + struct HksBlob aad = { + .size = sizeof(*keyInfo) - sizeof(keyInfo->keyInfoLen) + keyInfo->aliasSize + keyInfo->authIdSize, + .data = cipherKey->data + sizeof(keyInfo->keyInfoLen) + }; + + struct HksAeadParam *aeadParam = (struct HksAeadParam *)usageSpec->algParam; + aeadParam->nonce = nonce; + aeadParam->aad = aad; + aeadParam->payloadLen = keyInfo->keySize - HKS_AE_TAG_LEN; + + if (isEncrypt) { + aeadParam->tagLenEnc = HKS_AE_TAG_LEN; + } else { + aeadParam->tagDec.data = cipherKey->data + keyInfo->keyInfoLen - HKS_AE_TAG_LEN; /* the last 16 bytes */ + aeadParam->tagDec.size = HKS_AE_TAG_LEN; + } + return HKS_SUCCESS; +} + +static int32_t EncryptAndDecryptKeyBlob(struct HksBlob *rawKey, struct HksBlob *cipherKey, bool isEncrypt) +{ + struct HksStoreKeyInfo *keyInfo = (struct HksStoreKeyInfo *)cipherKey->data; + int32_t ret; + + /* 1. generate random */ + struct HksBlob random = { HKS_DEFAULT_RANDOM_LEN, keyInfo->random }; + if (isEncrypt) { + ret = HksCryptoHalFillRandom(&random); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get random failed"); + return ret; + } + } + + /* 2. get kek, derive from random + tag("derive_kek") */ + uint8_t kekBuf[HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256)] = {0}; + struct HksBlob kek = { HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256), kekBuf }; + ret = GetDeriveMaterial(DERIVE_KEK, &random, &kek); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* 3. get usage spec */ + struct HksAeadParam aeadParam = {0}; + struct HksUsageSpec usageSpec = { .algParam = (void *)&aeadParam }; + ret = BuildKeyBlobUsageSpec(cipherKey, &random, isEncrypt, &usageSpec); + if (ret != HKS_SUCCESS) { + (void)memset_s(kekBuf, HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256), 0, HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256)); + return ret; + } + + /* 4. get encrypted/decrypted key */ + struct HksBlob encKey = { keyInfo->keySize, cipherKey->data + keyInfo->keyInfoLen - keyInfo->keySize }; + if (isEncrypt) { + struct HksBlob tag = { HKS_AE_TAG_LEN, cipherKey->data + keyInfo->keyInfoLen - HKS_AE_TAG_LEN }; + ret = HksCryptoHalEncrypt(&kek, &usageSpec, rawKey, &encKey, &tag); + } else { + encKey.size -= HKS_AE_TAG_LEN; /* the decrypt len should remove the tag len */ + ret = HksCryptoHalDecrypt(&kek, &usageSpec, &encKey, rawKey); + } + if (ret != HKS_SUCCESS) { + HKS_LOG_E("cipher key[0x%x] failed, ret = %d", isEncrypt, ret); + } + + /* need clean kek buf */ + (void)memset_s(kekBuf, HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256), 0, HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256)); + HKS_FREE_BLOB(aeadParam.nonce); + return ret; +} + +static int32_t EncryptKeyBlob(const struct HksBlob *rawKey, struct HksBlob *cipherKey) +{ + return EncryptAndDecryptKeyBlob((struct HksBlob *)rawKey, cipherKey, true); +} + +static int32_t DecryptKeyBlob(const struct HksBlob *cipherKey, struct HksBlob *rawKey) +{ + return EncryptAndDecryptKeyBlob(rawKey, (struct HksBlob *)cipherKey, false); +} + +static int32_t CopyKey(const struct HksBlob *key, struct HksBlob *adjustedKey) +{ + int32_t ret = HksBlobInit(adjustedKey, key->size); + if (ret != HKS_SUCCESS) { + return ret; + } + if (memcpy_s(adjustedKey->data, adjustedKey->size, key->data, key->size) != EOK) { + HKS_FREE_PTR(adjustedKey->data); + return HKS_ERROR_BAD_STATE; + } + return ret; +} + +static int32_t Ed25519BlobToKeyMaterial(const struct HksBlob *key, struct HksBlob *adjustedKey) +{ + if (key->size != (HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256) << 1)) { + HKS_LOG_E("invalid keySize %u", key->size); + return HKS_ERROR_INVALID_KEY_FILE; + } + + int32_t ret = HksBlobInit(adjustedKey, sizeof(struct KeyMaterial25519) + + (HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256) << 1)); + if (ret != HKS_SUCCESS) { + return ret; + } + (void)memset_s(adjustedKey->data, adjustedKey->size, 0, adjustedKey->size); + + struct KeyMaterial25519 *keyMaterial = (struct KeyMaterial25519 *)adjustedKey->data; + keyMaterial->keyAlg = HKS_ALG_ED25519; + keyMaterial->keySize = HKS_CURVE25519_KEY_SIZE_256; + keyMaterial->pubKeySize = HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256); + keyMaterial->priKeySize = HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256); + + uint32_t offset = sizeof(*keyMaterial); + /* copy public key: the first 32 bytes of input key value; then private key: next 32 bytes */ + if (memcpy_s(adjustedKey->data + offset, adjustedKey->size - offset, + key->data, (HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256) << 1)) != EOK) { + HKS_LOG_E("copy ed25519 public and private value failed"); + memset_s(adjustedKey->data, adjustedKey->size, 0, adjustedKey->size); + HKS_FREE_PTR(adjustedKey->data); + return HKS_ERROR_BAD_STATE; + } + return ret; +} + +static int32_t Ed25519KeyMaterialToBlob(const struct HksBlob *key, struct HksBlob *adjustedKey) +{ + if (key->size < sizeof(struct KeyMaterial25519)) { + HKS_LOG_E("key size invalid, size = %u smaller than struct size", key->size); + return HKS_ERROR_INVALID_KEY_INFO; + } + + struct KeyMaterial25519 *keyMaterial = (struct KeyMaterial25519 *)key->data; + if ((keyMaterial->pubKeySize != HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256)) || + (keyMaterial->priKeySize != HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256)) || + (key->size < (sizeof(*keyMaterial) + keyMaterial->pubKeySize + keyMaterial->priKeySize))) { + HKS_LOG_E("key size invalid, keySize = %u, pubSize %u, priSize %u", + key->size, keyMaterial->pubKeySize, keyMaterial->priKeySize); + return HKS_ERROR_INVALID_KEY_INFO; + } + + int32_t ret = HksBlobInit(adjustedKey, keyMaterial->priKeySize + keyMaterial->pubKeySize); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* 32 bytes pubkey first, then 32 bytes private key */ + if (memcpy_s(adjustedKey->data, adjustedKey->size, key->data + sizeof(*keyMaterial), + keyMaterial->pubKeySize + keyMaterial->priKeySize) != EOK) { + HKS_LOG_E("copy pubKey and private key failed."); + HKS_FREE_PTR(adjustedKey->data); + return HKS_ERROR_BAD_STATE; + } + return ret; +} + +static int32_t GetRawKeyMaterial(const struct HksBlob *key, struct HksBlob *rawKey) +{ + if (key->size < sizeof(struct HksStoreKeyInfo)) { + HKS_LOG_E("invalid key, size too small, size = %u", key->size); + return HKS_ERROR_INVALID_KEY_INFO; + } + + struct HksStoreKeyInfo *keyInfo = (struct HksStoreKeyInfo *)key->data; + if (HksIsKeyInfoLenInvalid(keyInfo)) { + HKS_LOG_E("invalid keyInfoBlob len"); + return HKS_ERROR_INVALID_KEY_INFO; + } + + struct HksBlob tmpKey = { 0, NULL }; + int32_t ret = HksBlobInit(&tmpKey, keyInfo->keySize); + if (ret != HKS_SUCCESS) { + return ret; + } + + ret = DecryptKeyBlob(key, &tmpKey); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("decrypt key blob failed, ret = %d", ret); + HKS_FREE_BLOB(tmpKey); + return ret; + } + + if ((keyInfo->keyAlg == HKS_ALG_ED25519) && (keyInfo->flag == HKS_KEY_FLAG_GENERATE_KEY)) { + ret = Ed25519BlobToKeyMaterial(&tmpKey, rawKey); + } else { + ret = CopyKey(&tmpKey, rawKey); + } + if (ret != HKS_SUCCESS) { + HKS_LOG_E("operate failed, alg:%u, ret = %d", keyInfo->keyAlg, ret); + } + + (void)memset_s(tmpKey.data, tmpKey.size, 0, tmpKey.size); + HKS_FREE_BLOB(tmpKey); + return HKS_SUCCESS; +} + +struct HksKeyNode *HksGenerateKeyNode(const struct HksBlob *key) +{ + if (key->size > MAX_KEY_SIZE) { + HKS_LOG_E("invalid key blob size %x", key->size); + return NULL; + } + struct HksKeyNode *keyNode = (struct HksKeyNode *)HksMalloc(sizeof(struct HksKeyNode)); + if (keyNode == NULL) { + HKS_LOG_E("malloc keynode failed"); + return NULL; + } + keyNode->refCnt = 1; + keyNode->status = HKS_KEYNODE_INACTIVE; + keyNode->handle = 0; + + int32_t ret; + do { + struct HksBlob rawKey = { 0, NULL }; + ret = GetRawKeyMaterial(key, &rawKey); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get raw key material failed, ret = %d", ret); + break; + } + + struct HksParamSet *keyBlobParamSet = NULL; + ret = TranslateKeyInfoBlobToParamSet(&rawKey, key, &keyBlobParamSet); + (void)memset_s(rawKey.data, rawKey.size, 0, rawKey.size); + HKS_FREE_BLOB(rawKey); + + if (ret != HKS_SUCCESS) { + HKS_LOG_E("translate key info to paramset failed, ret = %d", ret); + break; + } + keyNode->paramSet = keyBlobParamSet; + } while (0); + + if (ret != HKS_SUCCESS) { + HKS_FREE_PTR(keyNode); + return NULL; + } + + return keyNode; +} + +static int32_t FillBaseInfo(const struct HksParamSet *paramSet, struct HksBlob *keyOut) +{ + struct HksStoreKeyInfo *keyInfo = (struct HksStoreKeyInfo *)keyOut->data; + for (uint32_t i = 0; i < paramSet->paramsCnt; i++) { + switch (paramSet->params[i].tag) { + case HKS_TAG_ALGORITHM: + keyInfo->keyAlg = paramSet->params[i].uint32Param; + break; + case HKS_TAG_PADDING: + keyInfo->padding = paramSet->params[i].uint32Param; + break; + case HKS_TAG_DIGEST: + keyInfo->digest = paramSet->params[i].uint32Param; + break; + case HKS_TAG_BLOCK_MODE: + keyInfo->keyMode = paramSet->params[i].uint32Param; + break; + case HKS_TAG_PURPOSE: + keyInfo->purpose = paramSet->params[i].uint32Param; + break; + case HKS_TAG_KEY_SIZE: + keyInfo->keyLen = paramSet->params[i].uint32Param; + break; + case HKS_TAG_KEY_ROLE: + keyInfo->role = paramSet->params[i].uint32Param; + break; + case HKS_TAG_KEY_DOMAIN: + keyInfo->domain = paramSet->params[i].uint32Param; + break; + case HKS_TAG_KEY_AUTH_ID: + if (paramSet->params[i].blob.size > HKS_MAX_KEY_AUTH_ID_LEN) { + HKS_LOG_E("invlaid authId size %u", paramSet->params[i].blob.size); + return HKS_ERROR_INVALID_ARGUMENT; + } + if (memcpy_s(keyOut->data + sizeof(*keyInfo) + keyInfo->aliasSize, HKS_MAX_KEY_AUTH_ID_LEN, + paramSet->params[i].blob.data, paramSet->params[i].blob.size) != EOK) { + HKS_LOG_E("memcpy key auth id failed"); + return HKS_ERROR_BAD_STATE; + } + keyInfo->authIdSize = paramSet->params[i].blob.size; + break; + default: + break; + } + } + return HKS_SUCCESS; +} + +static int32_t FillStoreKeyInfo(const struct HksBlob *keyAlias, uint8_t keyFlag, const struct HksBlob *key, + const struct HksParamSet *paramSet, struct HksBlob *keyOut) +{ + if ((keyAlias->size > HKS_MAX_KEY_ALIAS_LEN) || (key->size > HKS_MAX_KEY_LEN)) { + HKS_LOG_E("invalid keyAlias size %u, or key size %u", keyAlias->size, key->size); + return HKS_ERROR_INVALID_ARGUMENT; + } + + struct HksStoreKeyInfo *keyInfo = (struct HksStoreKeyInfo *)keyOut->data; + keyInfo->flag = keyFlag; + keyInfo->keySize = key->size + HKS_AE_TAG_LEN; + + /* 1. copy keyAlias */ + if (memcpy_s(keyOut->data + sizeof(*keyInfo), HKS_MAX_KEY_ALIAS_LEN, keyAlias->data, keyAlias->size) != EOK) { + HKS_LOG_E("memcpy keyAlias failed"); + return HKS_ERROR_BAD_STATE; + } + keyInfo->aliasSize = keyAlias->size; + + /* 2. copy keyAuthId, keyAlg, purpose ect. */ + int32_t ret = FillBaseInfo(paramSet, keyOut); + if (ret != HKS_SUCCESS) { + return ret; + } + keyInfo->keyInfoLen = sizeof(*keyInfo) + keyInfo->aliasSize + keyInfo->authIdSize + keyInfo->keySize; + + /* 3. encrypt key */ + ret = EncryptKeyBlob(key, keyOut); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("encrypt key blob failed, ret = %d", ret); + return ret; + } + keyOut->size = keyInfo->keyInfoLen; + + return ret; +} + +static int32_t AdjustKey(uint8_t keyFlag, const struct HksParamSet *paramSet, + const struct HksBlob *key, struct HksBlob *adjustedKey) +{ + struct HksParam *algParam = NULL; + int32_t ret = HksGetParam(paramSet, HKS_TAG_ALGORITHM, &algParam); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get alg param failed"); + return ret; + } + + /* for storage-restricted products, when generate ed25519 key, only 64-byte private key can be stored */ + if ((algParam->uint32Param == HKS_ALG_ED25519) && (keyFlag == HKS_KEY_FLAG_GENERATE_KEY)) { + ret = Ed25519KeyMaterialToBlob(key, adjustedKey); + } else { + ret = CopyKey(key, adjustedKey); + } + if (ret != HKS_SUCCESS) { + HKS_LOG_E("operate failed, alg = %u, ret = %d", algParam->uint32Param, ret); + } + return ret; +} + +int32_t HksGetRawKey(const struct HksParamSet *paramSet, struct HksBlob *rawKey) +{ + struct HksParam *keyParam = NULL; + int32_t ret = HksGetParam(paramSet, HKS_TAG_KEY, &keyParam); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get key param failed!"); + return ret; + } + + uint8_t *data = HksMalloc(keyParam->blob.size); + if (data == NULL) { + HKS_LOG_E("fail to malloc raw key"); + return HKS_ERROR_BAD_STATE; + } + (void)memcpy_s(data, keyParam->blob.size, keyParam->blob.data, keyParam->blob.size); + + rawKey->size = keyParam->blob.size; + rawKey->data = data; + return HKS_SUCCESS; +} + +int32_t HksBuildKeyBlob(const struct HksBlob *keyAlias, uint8_t keyFlag, const struct HksBlob *key, + const struct HksParamSet *paramSet, struct HksBlob *keyOut) +{ + struct HksBlob adjustedKey = { 0, NULL }; + int32_t ret = AdjustKey(keyFlag, paramSet, key, &adjustedKey); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("adjust key failed, ret = %d", ret); + return ret; + } + + struct HksBlob tmpOut = { 0, NULL }; + do { + uint32_t totalLen = sizeof(struct HksStoreKeyInfo) + HKS_MAX_KEY_ALIAS_LEN + HKS_MAX_KEY_AUTH_ID_LEN + + HKS_MAX_KEY_MATERIAL_LEN; + ret = HksBlobInit(&tmpOut, totalLen); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("hks blob init failed, ret = %d", ret); + break; + } + (void)memset_s(tmpOut.data, tmpOut.size, 0, tmpOut.size); /* need init 0 */ + + ret = FillStoreKeyInfo(keyAlias, keyFlag, &adjustedKey, paramSet, &tmpOut); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("fill storage key info failed, ret = %d", ret); + break; + } + + if (memcpy_s(keyOut->data, keyOut->size, tmpOut.data, tmpOut.size) != EOK) { + HKS_LOG_E("copy keyblob out failed!"); + ret = HKS_ERROR_BAD_STATE; + break; + } + keyOut->size = tmpOut.size; + } while (0); + + (void)memset_s(adjustedKey.data, adjustedKey.size, 0, adjustedKey.size); /* need clean key */ + HKS_FREE_BLOB(adjustedKey); + HKS_FREE_BLOB(tmpOut); + return ret; +} + +#endif /* _STORAGE_LITE_ */ +#endif /* _CUT_AUTHENTICATE_ */ \ No newline at end of file diff --git a/services/huks_standard/huks_engine/main/core/src/hks_rkc.c b/services/huks_standard/huks_engine/main/core/src/hks_rkc.c new file mode 100644 index 00000000..d7757cb0 --- /dev/null +++ b/services/huks_standard/huks_engine/main/core/src/hks_rkc.c @@ -0,0 +1,764 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef _CUT_AUTHENTICATE_ + +#include "hks_rkc.h" + +#include "hks_crypto_hal.h" +#include "hks_get_udid.h" +#include "hks_log.h" +#include "hks_mem.h" +#include "hks_rkc_rw.h" + +#define HKS_RKC_RMK_LEN 64 /* the length of root main key */ +#define HKS_RKC_RMK_EK_LEN 32 /* the encryption key length of root main key */ +#define HKS_RKC_RAW_KEY_LEN 64 /* the raw key length of root key component */ +#define HKS_HARDWARE_UDID_LEN 32 /* the length of hardware UDID */ +#define HKS_RKC_MK_ADD_DATA_LEN 8 /* the additional data length of main key */ +#define HKS_RKC_KSF_NAME_LEN_MAX 256 /* the max length of keystore filename */ + +/* the initialization parameter of root key component */ +struct HksRkcInitParam { + uint16_t version; /* the version of root key component */ + uint8_t storageType; /* the storage type of root key component */ + struct HksRkcKsfAttr ksfAttr; /* the attribute of keystore file */ + uint32_t rmkIter; /* the iterator number of times which derive Root Main Key */ + uint32_t rmkHashAlg; /* the hash algorithm which derive Root Main Key */ + uint32_t mkEncryptAlg; /* the encrption algorithm of main key */ +}; + +/* main key */ +struct HksRkcMk { + bool valid; /* whether main key is valid */ + struct HksTime mkCreatedTime; /* the created time of main key */ + struct HksTime mkExpiredTime; /* the expired time of main key */ + uint8_t mkWithMask[HKS_RKC_MK_LEN]; /* the main key with mask */ +}; + +/* the default initialized parameter of root key component */ +const struct HksRkcInitParam g_hksRkcDefaultInitParam = { + .version = HKS_RKC_VER, + .storageType = HKS_RKC_STORAGE_FILE_SYS, + .ksfAttr = { HKS_RKC_KSF_NUM, { "info1.data", "info2.data" } }, + .rmkIter = HKS_RKC_RMK_ITER, + .rmkHashAlg = HKS_RKC_RMK_HMAC_SHA256, + .mkEncryptAlg = HKS_RKC_MK_CRYPT_ALG_AES256_GCM, +}; + +/* the data of main key */ +struct HksRkcMk g_hksRkcMk = { false, { 0, 0, 0, 0, 0, 0 }, { 0, 0, 0, 0, 0, 0 }, {0} }; + +/* the additional data of main key. 'H', 'K', 'S', 'R', 'K', 'C', 'M', 'K' */ +const uint8_t g_hksRkcMkAddData[HKS_RKC_MK_ADD_DATA_LEN] = { 0x48, 0x4B, 0x53, 0x52, 0x4B, 0x43, 0x4D, 0x4B }; + +static int32_t RkcReadAllKsf(int32_t *allKsfRet, struct HksRkcKsfData *allKsfData, uint32_t ksfCount, + struct HksRkcKsfData **validKsfData, uint32_t *validKsfIndex) +{ + if (ksfCount > g_hksRkcCfg.ksfAttr.num) { + HKS_LOG_E("Invalid ksf count!"); + return HKS_ERROR_INVALID_ARGUMENT; + } + + /* Read all ksf */ + bool someCaseSuccess = false; + for (uint32_t i = 0; i < g_hksRkcCfg.ksfAttr.num; ++i) { + allKsfRet[i] = HksRkcReadKsf(g_hksRkcCfg.ksfAttr.name[i], &(allKsfData[i])); + if (allKsfRet[i] != HKS_SUCCESS) { + continue; + } + + /* the first valid ksf is found, save data and index */ + if (*validKsfData == NULL) { + *validKsfData = &(allKsfData[i]); + *validKsfIndex = i; + someCaseSuccess = true; + } + } + + return (someCaseSuccess ? HKS_SUCCESS : HKS_ERROR_INVALID_KEY_FILE); +} + +static int32_t RkcRecoverRkTime(const struct HksRkcKsfData *ksfData) +{ + if (memcpy_s(&(g_hksRkcCfg.rkCreatedTime), sizeof(g_hksRkcCfg.rkCreatedTime), + &(ksfData->rkCreatedTime), sizeof(ksfData->rkCreatedTime)) != EOK) { + HKS_LOG_E("Memcpy rkCreatedTime failed!"); + return HKS_ERROR_BAD_STATE; + } + + if (memcpy_s(&(g_hksRkcCfg.rkExpiredTime), sizeof(g_hksRkcCfg.rkExpiredTime), + &(ksfData->rkExpiredTime), sizeof(ksfData->rkExpiredTime)) != EOK) { + HKS_LOG_E("Memcpy rkExpiredTime failed!"); + return HKS_ERROR_BAD_STATE; + } + + return HKS_SUCCESS; +} + +static int32_t RkcGetFixedMaterial(struct HksBlob *material) +{ + /* consistent with the old hks */ + const uint8_t fixedMaterial[HKS_RKC_MATERIAL_LEN] = { + 0xB2, 0xA1, 0x0C, 0x73, 0x52, 0x73, 0x76, 0xA1, + 0x60, 0x62, 0x2E, 0x08, 0x52, 0x08, 0x2E, 0xA9, + 0x60, 0xBC, 0x2E, 0x73, 0x52, 0x0B, 0x0C, 0xBC, + 0xEE, 0x0A, 0x2E, 0x08, 0x52, 0x9C, 0x76, 0xA9 + }; + + if (memcpy_s(material->data, material->size, fixedMaterial, HKS_RKC_MATERIAL_LEN) != EOK) { + HKS_LOG_E("Memcpy fiexd material failed!"); + return HKS_ERROR_BAD_STATE; + } + + return HKS_SUCCESS; +} + +static int32_t RkcGetRmkRawKey(const struct HksRkcKsfData *ksfData, struct HksBlob *rawKey) +{ + uint8_t material3Data[HKS_RKC_MATERIAL_LEN] = {0}; + struct HksBlob material3 = { HKS_RKC_MATERIAL_LEN, material3Data }; + + /* Get the fixed material */ + int32_t ret = RkcGetFixedMaterial(&material3); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Get fixed material failed! ret = 0x%X", ret); + return ret; + } + + /* materials xor */ + for (uint32_t i = 0; i < HKS_RKC_MATERIAL_LEN; ++i) { + rawKey->data[i] = ksfData->rkMaterial1[i] ^ ksfData->rkMaterial2[i] ^ material3.data[i]; + } + + /* append hardware UDID */ + ret = HksGetHardwareUdid(rawKey->data + HKS_RKC_MATERIAL_LEN, HKS_HARDWARE_UDID_LEN); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Get hardware udid failed! ret = 0x%X", ret); + return ret; + } + + return HKS_SUCCESS; +} + +static uint32_t RkcDigestToHks(const uint32_t rkcDigest) +{ + if (rkcDigest == HKS_RKC_RMK_HMAC_SHA256) { + return HKS_DIGEST_SHA256; + } + + /* if digest is invalid, will use default digest */ + return HKS_DIGEST_SHA256; +} + +static int32_t RkcPbkdf2Hmac(const uint32_t hashAlg, const struct HksBlob *rawKey, + const struct HksBlob *salt, const uint32_t iterNum, struct HksBlob *dk) +{ + struct HksKeyDerivationParam derParam = { + .salt = *salt, + .iterations = iterNum, + .digestAlg = RkcDigestToHks(hashAlg), + }; + const struct HksKeySpec derivationSpec = { HKS_ALG_PBKDF2, dk->size, &derParam }; + int32_t ret = HksCryptoHalDeriveKey(rawKey, &derivationSpec, dk); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Crypto hal derive key failed! ret = 0x%X", ret); + } + + return ret; +} + +static int32_t RkcDeriveRmk(const struct HksRkcKsfData *ksfData, struct HksBlob *rmk) +{ + struct HksBlob rawKey; + rawKey.data = (uint8_t *)HksMalloc(HKS_RKC_RAW_KEY_LEN); + if (rawKey.data == NULL) { + HKS_LOG_E("Malloc rawKey failed!"); + return HKS_ERROR_MALLOC_FAIL; + } + rawKey.size = HKS_RKC_RAW_KEY_LEN; + (void)memset_s(rawKey.data, rawKey.size, 0, rawKey.size); + + int32_t ret; + do { + /* get the raw key */ + ret = RkcGetRmkRawKey(ksfData, &rawKey); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Get rmk raw key failed! ret = 0x%X", ret); + break; + } + + /* PBKDF2-HMAC */ + const struct HksBlob salt = { HKS_RKC_SALT_LEN, (uint8_t *)(ksfData->rmkSalt) }; + ret = RkcPbkdf2Hmac(ksfData->rmkHashAlg, &rawKey, &salt, ksfData->rmkIter, rmk); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Pbkdf2 failed! ret = 0x%X", ret); + } + } while (0); + + (void)memset_s(rawKey.data, rawKey.size, 0, rawKey.size); + HKS_FREE_BLOB(rawKey); + return ret; +} + +static int32_t InitMkCryptUsageSpec(uint8_t *iv, const uint32_t ivSize, struct HksUsageSpec *usageSpec) +{ + usageSpec->mode = HKS_MODE_GCM; + usageSpec->padding = HKS_PADDING_NONE; + usageSpec->digest = HKS_DIGEST_NONE; + usageSpec->algType = HKS_ALG_AES; + + struct HksAeadParam *aeadParam = (struct HksAeadParam *)usageSpec->algParam; + aeadParam->aad.size = HKS_RKC_MK_ADD_DATA_LEN; + aeadParam->aad.data = (uint8_t *)&g_hksRkcMkAddData; + aeadParam->nonce.size = ivSize; + aeadParam->nonce.data = iv; + aeadParam->payloadLen = HKS_RKC_RMK_EK_LEN; + + return HKS_SUCCESS; +} + +static int32_t RkcMkCrypt(const struct HksRkcKsfData *ksfData, + struct HksBlob *plainText, struct HksBlob *cipherText, const bool encrypt) +{ + struct HksBlob rmk; + rmk.data = (uint8_t *)HksMalloc(HKS_RKC_RMK_LEN); + if (rmk.data == NULL) { + HKS_LOG_E("Malloc rmk failed!"); + return HKS_ERROR_MALLOC_FAIL; + } + rmk.size = HKS_RKC_RMK_LEN; + (void)memset_s(rmk.data, rmk.size, 0, rmk.size); + + int32_t ret; + do { + ret = RkcDeriveRmk(ksfData, &rmk); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Derive rmk failed! ret = 0x%X", ret); + break; + } + + struct HksAeadParam aeadParam = {0}; + struct HksUsageSpec usageSpec = { .algParam = (void *)(&aeadParam) }; + ret = InitMkCryptUsageSpec((uint8_t *)ksfData->mkIv, HKS_RKC_MK_IV_LEN, &usageSpec); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Init mk crypt usageSpec failed! ret = 0x%X", ret); + break; + } + + const struct HksBlob key = { HKS_RKC_RMK_EK_LEN, rmk.data }; + if (encrypt) { + aeadParam.tagLenEnc = HKS_AE_TAG_LEN; + struct HksBlob tag = { HKS_AE_TAG_LEN, cipherText->data + key.size }; + ret = HksCryptoHalEncrypt(&key, &usageSpec, plainText, cipherText, &tag); + } else { + aeadParam.tagDec.size = HKS_AE_TAG_LEN; + aeadParam.tagDec.data = cipherText->data + cipherText->size - HKS_AE_TAG_LEN; + cipherText->size -= HKS_AE_TAG_LEN; /* the decrypt len should remove the tag len */ + ret = HksCryptoHalDecrypt(&key, &usageSpec, cipherText, plainText); + } + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Crypto mk failed! ret = 0x%X", ret); + ret = HKS_ERROR_CRYPTO_ENGINE_ERROR; /* need return this error code for hichian call refresh func */ + } + } while (0); + + /* the data of root key should be cleared after use */ + (void)memset_s(rmk.data, rmk.size, 0, rmk.size); + HKS_FREE_BLOB(rmk); + return ret; +} + +static void RkcMaskMk(const struct HksBlob *mk) +{ + for (uint32_t i = 0; i < HKS_RKC_MK_LEN; ++i) { + g_hksRkcMk.mkWithMask[i] = mk->data[i] ^ g_hksRkcCfg.mkMask[i]; + } + + g_hksRkcMk.valid = true; +} + +static int32_t RkcRecoverMkTime(const struct HksRkcKsfData *ksfData) +{ + if (memcpy_s(&(g_hksRkcMk.mkCreatedTime), sizeof(g_hksRkcMk.mkCreatedTime), + &(ksfData->mkCreatedTime), sizeof(ksfData->mkCreatedTime)) != EOK) { + HKS_LOG_E("Memcpy mkCreatedTime failed!"); + return HKS_ERROR_BAD_STATE; + } + + if (memcpy_s(&(g_hksRkcMk.mkExpiredTime), sizeof(g_hksRkcMk.mkExpiredTime), + &(ksfData->mkExpiredTime), sizeof(ksfData->mkExpiredTime)) != EOK) { + HKS_LOG_E("Memcpy mkExpiredTime failed!"); + return HKS_ERROR_BAD_STATE; + } + + struct HksBlob mk; + mk.data = (uint8_t *)HksMalloc(HKS_RKC_MK_LEN); + if (mk.data == NULL) { + HKS_LOG_E("Malloc mk failed!"); + return HKS_ERROR_MALLOC_FAIL; + } + mk.size = HKS_RKC_MK_LEN; + + int32_t ret; + do { + struct HksBlob mkMaskBlob = { HKS_RKC_MK_LEN, g_hksRkcCfg.mkMask }; + ret = HksCryptoHalFillRandom(&mkMaskBlob); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Generate mk failed! ret = 0x%X", ret); + break; + } + + struct HksBlob mkCipherText = { HKS_RKC_MK_CIPHER_TEXT_LEN, (uint8_t *)ksfData->mkCiphertext }; + ret = RkcMkCrypt(ksfData, &mk, &mkCipherText, false); /* false: decrypt */ + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Main key crypt failed! ret = 0x%X", ret); + break; + } + + /* the main key in memory should be masked */ + (void)RkcMaskMk(&mk); + } while (0); + + memset_s(mk.data, mk.size, 0, mk.size); + HKS_FREE_BLOB(mk); + return ret; +} + +static int32_t RkcCheckKsf(const char *ksfName, int32_t ret, + const struct HksRkcKsfData *ksfData, const struct HksRkcKsfData *validKsfData) +{ + /* If this ksf is different from the first valid ksf, try to overwrite it by the first valid ksf. */ + if ((ret != HKS_SUCCESS) || (HksMemCmp(validKsfData, ksfData, sizeof(struct HksRkcKsfData)) != 0)) { + HKS_LOG_E("Repair ksf[%s]", ksfName); + return HksRkcWriteKsf(ksfName, validKsfData); + } + + return HKS_SUCCESS; +} + +static int32_t RkcCheckAllKsf(const int32_t *allKsfRet, const struct HksRkcKsfData *allKsfData, + uint32_t ksfCount, const struct HksRkcKsfData *validKsfData, const uint32_t validKsfIndex) +{ + if (ksfCount > g_hksRkcCfg.ksfAttr.num) { + HKS_LOG_E("Invalid ksf count!"); + return HKS_ERROR_INVALID_ARGUMENT; + } + + for (uint32_t i = 0; i < g_hksRkcCfg.ksfAttr.num; ++i) { + if (i == validKsfIndex) { + continue; + } + + /* if fail, continue */ + int32_t ret = RkcCheckKsf(g_hksRkcCfg.ksfAttr.name[i], allKsfRet[i], allKsfData + i, validKsfData); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Check 0x%X ksf failed! ret = 0x%X", i, ret); + } + } + + return HKS_SUCCESS; +} + +static int32_t RkcLoadKsf(void) +{ + const uint32_t allKsfDataSize = sizeof(struct HksRkcKsfData) * HKS_RKC_KSF_NUM; + struct HksRkcKsfData *allKsfData = (struct HksRkcKsfData *)HksMalloc(allKsfDataSize); + if (allKsfData == NULL) { + HKS_LOG_E("Malloc all ksf data failed! malloc size = 0x%X", allKsfDataSize); + return HKS_ERROR_MALLOC_FAIL; + } + (void)memset_s(allKsfData, allKsfDataSize, 0, allKsfDataSize); + + int32_t ret; + do { + int32_t allKsfRet[HKS_RKC_KSF_NUM] = {0}; + uint32_t validKsfIndex = 0; + struct HksRkcKsfData *validKsfData = NULL; + + ret = RkcReadAllKsf(allKsfRet, allKsfData, HKS_RKC_KSF_NUM, &validKsfData, &validKsfIndex); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("All ksf file are invalid! ret = 0x%X", ret); + break; + } + + ret = RkcRecoverRkTime(validKsfData); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Recover rook key memory failed! ret = 0x%X", ret); + break; + } + + ret = RkcRecoverMkTime(validKsfData); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Recover main key memory failed! ret = 0x%X", ret); + break; + } + + ret = RkcCheckAllKsf(allKsfRet, allKsfData, HKS_RKC_KSF_NUM, validKsfData, validKsfIndex); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Check all ksf failed! ret = 0x%X", ret); + } + } while (0); + + (void)memset_s(allKsfData, allKsfDataSize, 0, allKsfDataSize); + HKS_FREE_PTR(allKsfData); + return ret; +} + +static int32_t RkcCalculateMaterial(const struct HksBlob *random1, const struct HksBlob *random2, + struct HksRkcKsfData *ksfData) +{ + /* + * calculate material + * material1: SHA256(0x1 + R1 + R2 + E) + * material2: SHA256(0x2 + R1 + R2 + E) + */ + struct HksBlob hashSrc; + hashSrc.data = (uint8_t *)HksMalloc(1 + HKS_RKC_MATERIAL_LEN + HKS_RKC_MATERIAL_LEN); + if (hashSrc.data == NULL) { + HKS_LOG_E("Malloc hash src data failed!"); + return HKS_ERROR_MALLOC_FAIL; + } + hashSrc.size = 1 + HKS_RKC_MATERIAL_LEN + HKS_RKC_MATERIAL_LEN; + + struct HksBlob hashResult1 = { HKS_RKC_MATERIAL_LEN, ksfData->rkMaterial1 }; + struct HksBlob hashResult2 = { HKS_RKC_MATERIAL_LEN, ksfData->rkMaterial2 }; + + int32_t ret; + do { + /* 1: sn is 0x01 or 0x02 */ + if (memcpy_s(hashSrc.data + 1, HKS_RKC_MATERIAL_LEN, random1->data, random1->size) != EOK) { + HKS_LOG_E("Memcpy random1 failed!"); + ret = HKS_ERROR_BAD_STATE; + break; + } + + if (memcpy_s(hashSrc.data + 1 + HKS_RKC_MATERIAL_LEN, HKS_RKC_MATERIAL_LEN, + random2->data, random2->size) != EOK) { + HKS_LOG_E("Memcpy random2 failed!"); + ret = HKS_ERROR_BAD_STATE; + break; + } + + hashSrc.data[0] = 0x01; + ret = HksCryptoHalHash(HKS_DIGEST_SHA256, &hashSrc, &hashResult1); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Hash rkMaterial1 failed!"); + break; + } + + hashSrc.data[0] = 0x02; + ret = HksCryptoHalHash(HKS_DIGEST_SHA256, &hashSrc, &hashResult2); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Hash rkMaterial1 failed!"); + } + } while (0); + + (void)memset_s(hashSrc.data, hashSrc.size, 0, hashSrc.size); + HKS_FREE_BLOB(hashSrc); + return ret; +} + +static int32_t RkcMakeRandomMaterial(struct HksRkcKsfData *ksfData) +{ + /* two random number */ + uint8_t random1Data[HKS_RKC_MATERIAL_LEN] = {0}; + uint8_t random2Data[HKS_RKC_MATERIAL_LEN] = {0}; + struct HksBlob random1 = { HKS_RKC_MATERIAL_LEN, random1Data }; + struct HksBlob random2 = { HKS_RKC_MATERIAL_LEN, random2Data }; + + int32_t ret; + do { + /* Generate 32 * 2 random number: R1 + R2 */ + ret = HksCryptoHalFillRandom(&random1); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Generate random1 failed! ret = 0x%X", ret); + break; + } + + ret = HksCryptoHalFillRandom(&random2); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Generate random2 failed! ret = 0x%X", ret); + break; + } + + /* calculate material */ + ret = RkcCalculateMaterial(&random1, &random2, ksfData); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Calc material failed! ret = 0x%X", ret); + } + } while (0); + + (void)memset_s(random1Data, HKS_RKC_MATERIAL_LEN, 0, HKS_RKC_MATERIAL_LEN); + (void)memset_s(random2Data, HKS_RKC_MATERIAL_LEN, 0, HKS_RKC_MATERIAL_LEN); + return ret; +} + +static int32_t RkcMakeMk(struct HksRkcKsfData *ksfData) +{ + struct HksBlob mk; + mk.data = (uint8_t *)HksMalloc(HKS_RKC_MK_LEN); + if (mk.data == NULL) { + HKS_LOG_E("Malloc mk failed!"); + return HKS_ERROR_MALLOC_FAIL; + } + mk.size = HKS_RKC_MK_LEN; + + int32_t ret; + do { + ksfData->mkEncryptAlg = g_hksRkcCfg.mkEncryptAlg; + + /* generate the mask of main key */ + struct HksBlob mkMaskBlob = { HKS_RKC_MK_LEN, g_hksRkcCfg.mkMask }; + ret = HksCryptoHalFillRandom(&mkMaskBlob); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Generate mkMask failed! ret = 0x%X", ret); + break; + } + + /* generate main key */ + ret = HksCryptoHalFillRandom(&mk); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Generate mk failed! ret = 0x%X", ret); + break; + } + + /* generate the IV of main key */ + struct HksBlob mkIvBlob = { HKS_RKC_MK_IV_LEN, ksfData->mkIv }; + ret = HksCryptoHalFillRandom(&mkIvBlob); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Generate mkIv failed! ret = 0x%X", ret); + break; + } + + struct HksBlob cipherTextBlob = { HKS_RKC_MK_CIPHER_TEXT_LEN, ksfData->mkCiphertext }; + ret = RkcMkCrypt(ksfData, &mk, &cipherTextBlob, true); /* true: encrypt */ + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Encrypt mk failed! ret = 0x%X", ret); + break; + } + + /* the main key in memory should be masked */ + (void)RkcMaskMk(&mk); + } while (0); + + (void)memset_s(mk.data, mk.size, 0, mk.size); + HKS_FREE_BLOB(mk); + return ret; +} + +static int32_t RkcWriteAllKsf(const struct HksRkcKsfData *ksfData) +{ + bool isSuccess = false; + for (uint32_t i = 0; i < g_hksRkcCfg.ksfAttr.num; ++i) { + int32_t ret = HksRkcWriteKsf(g_hksRkcCfg.ksfAttr.name[i], ksfData); + if (ret == HKS_SUCCESS) { + isSuccess = true; + } + } + + /* If all keystore file were written fail, return error code, otherwise, return success code. */ + return (isSuccess ? HKS_SUCCESS : HKS_ERROR_WRITE_FILE_FAIL); +} + +static int32_t RkcCreateKsf(void) +{ + struct HksRkcKsfData *newKsfData = (struct HksRkcKsfData *)HksMalloc(sizeof(struct HksRkcKsfData)); + if (newKsfData == NULL) { + HKS_LOG_E("Malloc ksf data failed!"); + return HKS_ERROR_MALLOC_FAIL; + } + (void)memset_s(newKsfData, sizeof(struct HksRkcKsfData), 0, sizeof(struct HksRkcKsfData)); + + int32_t ret; + do { + /* Fill some fixed field. */ + newKsfData->version = g_hksRkcCfg.version; + newKsfData->rmkIter = g_hksRkcCfg.rmkIter; + newKsfData->rmkHashAlg = g_hksRkcCfg.rmkHashAlg; + + /* Two material are generated by random number. */ + ret = RkcMakeRandomMaterial(newKsfData); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Generate material failed! ret = 0x%X", ret); + break; + } + + /* The salt value is generated by random number. */ + struct HksBlob salt = { HKS_RKC_SALT_LEN, newKsfData->rmkSalt }; + ret = HksCryptoHalFillRandom(&salt); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Generate salt failed! ret = 0x%X", ret); + break; + } + + /* make main key. */ + ret = RkcMakeMk(newKsfData); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("make mk failed! ret = 0x%X", ret); + break; + } + + /* Write the root key component data into all keystore files */ + ret = RkcWriteAllKsf(newKsfData); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Write ksf failed! ret = 0x%X", ret); + } + } while (0); + + /* the data of root key should be cleared after use */ + (void)memset_s(newKsfData, sizeof(struct HksRkcKsfData), 0, sizeof(struct HksRkcKsfData)); + HKS_FREE_PTR(newKsfData); + return ret; +} + +static int32_t RkcInitKsf(void) +{ + int32_t ret; + if (RkcKsfExist()) { + HKS_LOG_I("Rkc ksf is exist, start to load ksf"); + ret = RkcLoadKsf(); + } else { + HKS_LOG_I("Rkc ksf doesn't exist, start to creat ksf"); + ret = RkcCreateKsf(); + } + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Load/Create ksf failed! ret = 0x%X", ret); + } + + return ret; +} + +static char *CloneNewStr(const char *srcStr, const uint32_t strLenMax) +{ + if (srcStr == NULL) { + HKS_LOG_E("Invalid input string!"); + return NULL; + } + + const size_t strLen = strlen(srcStr); + if ((strLen == 0) || (strLen > strLenMax)) { + HKS_LOG_E("Invalid input string! len = 0x%X, maxLen = 0x%X", strLen, strLenMax); + return NULL; + } + + char *newBuf = (char *)HksMalloc(strLen + 1); /* 1: end char */ + if (newBuf == NULL) { + HKS_LOG_E("Malloc new buffer failed!"); + return NULL; + } + + if (memcpy_s(newBuf, strLen, srcStr, strLen) != EOK) { + HKS_LOG_E("Memcpy new buffer failed!"); + HKS_FREE_PTR(newBuf); + return NULL; + } + newBuf[strLen] = '\0'; + + return newBuf; +} + +static int32_t RkcInitKsfAttr(const struct HksRkcKsfAttr *ksfAttr) +{ + /* clone keystore filename from parameter. */ + for (uint32_t i = 0; i < ksfAttr->num; ++i) { + char *fileName = CloneNewStr(ksfAttr->name[i], HKS_RKC_KSF_NAME_LEN_MAX); + if (fileName == NULL) { + /* the memory will be freed by hksRkcDestroy() */ + return HKS_ERROR_MALLOC_FAIL; + } + + g_hksRkcCfg.ksfAttr.name[i] = fileName; + } + + g_hksRkcCfg.ksfAttr.num = ksfAttr->num; + return HKS_SUCCESS; +} + +int32_t HksRkcInit(void) +{ + if (g_hksRkcCfg.state == HKS_RKC_STATE_VALID) { + HKS_LOG_I("Hks rkc is running!"); + return HKS_SUCCESS; + } + + int32_t ret; + const struct HksRkcInitParam *initParamInner = &g_hksRkcDefaultInitParam; + do { + g_hksRkcCfg.version = initParamInner->version; + g_hksRkcCfg.storageType = initParamInner->storageType; + g_hksRkcCfg.rmkIter = initParamInner->rmkIter; + g_hksRkcCfg.rmkHashAlg = initParamInner->rmkHashAlg; + g_hksRkcCfg.mkEncryptAlg = initParamInner->mkEncryptAlg; + + /* Initialize the attribute of keystore file */ + ret = RkcInitKsfAttr(&(initParamInner->ksfAttr)); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Init attribute of keystore file failed! ret = 0x%X", ret); + break; + } + + /* Initialize the keystore file of root key component. */ + ret = RkcInitKsf(); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Init root key component failed! ret = 0x%X", ret); + } + } while (0); + + if (ret != HKS_SUCCESS) { + (void)HksRkcDestroy(); + return ret; + } + + g_hksRkcCfg.state = HKS_RKC_STATE_VALID; + return HKS_SUCCESS; +} + +void HksRkcDestroy(void) +{ + g_hksRkcCfg.state = HKS_RKC_STATE_INVALID; + HksRkcClearMem(); +} + +void HksRkcClearMem(void) +{ + for (uint32_t i = 0; i < HKS_RKC_KSF_NUM; ++i) { + HKS_FREE_PTR(g_hksRkcCfg.ksfAttr.name[i]); + } + + (void)memset_s(&g_hksRkcCfg, sizeof(g_hksRkcCfg), 0, sizeof(g_hksRkcCfg)); + (void)memset_s(&g_hksRkcMk, sizeof(g_hksRkcMk), 0, sizeof(g_hksRkcMk)); +} + +int32_t HksRkcGetMainKey(struct HksBlob *mainKey) +{ + if (!g_hksRkcMk.valid) { + HKS_LOG_E("Main key is invalid now, initialization is required before Getting main key!"); + return HKS_FAILURE; + } + + if (mainKey->size != HKS_RKC_MK_LEN) { + HKS_LOG_E("Invalid mainKey size! size = 0x%X", mainKey->size); + return HKS_ERROR_INVALID_ARGUMENT; + } + + /* remove mask */ + for (uint32_t i = 0; i < HKS_RKC_MK_LEN; ++i) { + mainKey->data[i] = g_hksRkcMk.mkWithMask[i] ^ g_hksRkcCfg.mkMask[i]; + } + + return HKS_SUCCESS; +} +#endif /* _CUT_AUTHENTICATE_ */ diff --git a/services/huks_standard/huks_engine/main/core/src/hks_rkc_rw.c b/services/huks_standard/huks_engine/main/core/src/hks_rkc_rw.c new file mode 100644 index 00000000..81499ab8 --- /dev/null +++ b/services/huks_standard/huks_engine/main/core/src/hks_rkc_rw.c @@ -0,0 +1,587 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef _CUT_AUTHENTICATE_ +#include "hks_rkc_rw.h" + +#include "hks_crypto_hal.h" +#include "hks_get_process_info.h" +#include "hks_log.h" +#include "hks_mem.h" +#include "hks_storage.h" + +#define HKS_RKC_HASH_LEN 32 /* the hash value length of root key component */ +#define HKS_RKC_KSF_BUF_LEN 258 /* the length of keystore buffer */ + +/* the flag of keystore file, used to identify files as HKS keystore file, don't modify. */ +const uint8_t g_hksRkcKsfFlag[HKS_RKC_KSF_FLAG_LEN] = { 0x5F, 0x64, 0x97, 0x8D, 0x19, 0x4F, 0x89, 0xCF }; + +/* the configuration of root key component */ +struct HksRkcCfg g_hksRkcCfg = { + .state = HKS_RKC_STATE_INVALID, + .version = HKS_RKC_VER, + .storageType = HKS_RKC_STORAGE_FILE_SYS, + .rkCreatedTime = { 0, 0, 0, 0, 0, 0 }, + .rkExpiredTime = { 0, 0, 0, 0, 0, 0 }, + .ksfAttr = { 0, { NULL, NULL} }, + .rmkIter = HKS_RKC_RMK_ITER, + .rmkHashAlg = HKS_RKC_RMK_HMAC_SHA256, + .mkMask = {0}, + .mkEncryptAlg = HKS_RKC_MK_CRYPT_ALG_AES256_GCM, + .reserve = {0} +}; + +static int32_t RkcExtractKsfFileFlag(const struct HksBlob *ksfFromFile, uint32_t *ksfBufOffset) +{ + uint8_t fileFlag[HKS_RKC_KSF_FLAG_LEN] = {0}; + + /* Extract file flag. */ + if (memcpy_s(fileFlag, HKS_RKC_KSF_FLAG_LEN, ksfFromFile->data + *ksfBufOffset, HKS_RKC_KSF_FLAG_LEN) != EOK) { + HKS_LOG_E("Memcpy file flag failed!"); + return HKS_ERROR_BAD_STATE; + } + + /* Check file flag. */ + if (HksMemCmp(fileFlag, g_hksRkcKsfFlag, HKS_RKC_KSF_FLAG_LEN) != 0) { + HKS_LOG_E("Ksf file flag is invalid!"); + return HKS_ERROR_READ_FILE_FAIL; + } + + *ksfBufOffset += HKS_RKC_KSF_FLAG_LEN; + return HKS_SUCCESS; +} + +static int32_t RkcExtractTime(const struct HksBlob *ksfFromFile, uint32_t *ksfBufOffset, struct HksTime *time) +{ + if (memcpy_s(&(time->hksYear), sizeof(uint16_t), ksfFromFile->data + *ksfBufOffset, sizeof(uint16_t)) != EOK) { + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint16_t); + + if (memcpy_s(&(time->hksMon), sizeof(uint8_t), ksfFromFile->data + *ksfBufOffset, sizeof(uint8_t)) != EOK) { + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint8_t); + + if (memcpy_s(&(time->hksDay), sizeof(uint8_t), ksfFromFile->data + *ksfBufOffset, sizeof(uint8_t)) != EOK) { + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint8_t); + + if (memcpy_s(&(time->hksHour), sizeof(uint8_t), ksfFromFile->data + *ksfBufOffset, sizeof(uint8_t)) != EOK) { + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint8_t); + + if (memcpy_s(&(time->hksMin), sizeof(uint8_t), ksfFromFile->data + *ksfBufOffset, sizeof(uint8_t)) != EOK) { + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint8_t); + + if (memcpy_s(&(time->hksSec), sizeof(uint8_t), ksfFromFile->data + *ksfBufOffset, sizeof(uint8_t)) != EOK) { + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint8_t); + + return HKS_SUCCESS; +} + +static int32_t RkcExtractKsfRk(const struct HksBlob *ksfFromFile, + uint32_t *ksfBufOffset, struct HksRkcKsfData *ksfData) +{ + /* Extract version */ + if (memcpy_s(&(ksfData->version), sizeof(uint16_t), ksfFromFile->data + *ksfBufOffset, sizeof(uint16_t)) != EOK) { + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint16_t); + + /* Extract rkCreatedTime */ + int32_t ret = RkcExtractTime(ksfFromFile, ksfBufOffset, &(ksfData->rkCreatedTime)); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* Extract rkExpiredTime */ + ret = RkcExtractTime(ksfFromFile, ksfBufOffset, &(ksfData->rkExpiredTime)); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* Extract the first material */ + if (memcpy_s(&(ksfData->rkMaterial1), HKS_RKC_MATERIAL_LEN, + ksfFromFile->data + *ksfBufOffset, HKS_RKC_MATERIAL_LEN) != EOK) { + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += HKS_RKC_MATERIAL_LEN; + + /* Extract the second material */ + if (memcpy_s(&(ksfData->rkMaterial2), HKS_RKC_MATERIAL_LEN, + ksfFromFile->data + *ksfBufOffset, HKS_RKC_MATERIAL_LEN) != EOK) { + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += HKS_RKC_MATERIAL_LEN; + + /* Extract iterator number */ + if (memcpy_s(&(ksfData->rmkIter), sizeof(uint32_t), ksfFromFile->data + *ksfBufOffset, sizeof(uint32_t)) != EOK) { + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint32_t); + + /* Extract salt */ + if (memcpy_s(&(ksfData->rmkSalt), HKS_RKC_SALT_LEN, ksfFromFile->data + *ksfBufOffset, HKS_RKC_SALT_LEN) != EOK) { + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += HKS_RKC_SALT_LEN; + + /* Extract hash algorithm */ + if (memcpy_s(&(ksfData->rmkHashAlg), sizeof(uint32_t), + ksfFromFile->data + *ksfBufOffset, sizeof(uint32_t)) != EOK) { + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint32_t); + + /* Extract reserve field */ + if (memcpy_s(&(ksfData->rkRsv), HKS_RKC_KSF_DATA_RSV_LEN, + ksfFromFile->data + *ksfBufOffset, HKS_RKC_KSF_DATA_RSV_LEN) != EOK) { + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += HKS_RKC_KSF_DATA_RSV_LEN; + + return HKS_SUCCESS; +} + +static int32_t RkcExtractKsfMk(const struct HksBlob *ksfFromFile, + uint32_t *ksfBufOffset, struct HksRkcKsfData *ksfData) +{ + /* Extract mkCreatedTime */ + int32_t ret = RkcExtractTime(ksfFromFile, ksfBufOffset, &(ksfData->mkCreatedTime)); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Extract mkCreatedTime failed!"); + return ret; + } + + /* Extract mkExpiredTime */ + ret = RkcExtractTime(ksfFromFile, ksfBufOffset, &(ksfData->mkExpiredTime)); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Extract mkExpiredTime failed!"); + return ret; + } + + /* Fill encrption algorithm */ + if (memcpy_s(&(ksfData->mkEncryptAlg), sizeof(uint32_t), + ksfFromFile->data + *ksfBufOffset, sizeof(uint32_t)) != EOK) { + HKS_LOG_E("Memcpy mkEncryptAlg failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint32_t); + + /* Fill IV */ + if (memcpy_s(&(ksfData->mkIv), HKS_RKC_MK_IV_LEN, ksfFromFile->data + *ksfBufOffset, HKS_RKC_MK_IV_LEN) != EOK) { + HKS_LOG_E("Memcpy mkIv failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += HKS_RKC_MK_IV_LEN; + + /* Fill ciphertext */ + if (memcpy_s(&(ksfData->mkCiphertext), HKS_RKC_MK_CIPHER_TEXT_LEN, + ksfFromFile->data + *ksfBufOffset, HKS_RKC_MK_CIPHER_TEXT_LEN) != EOK) { + HKS_LOG_E("Memcpy mkCiphertext failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += HKS_RKC_MK_CIPHER_TEXT_LEN; + + /* Fill reserve field */ + if (memcpy_s(&(ksfData->mkRsv), HKS_RKC_KSF_DATA_RSV_LEN, + ksfFromFile->data + *ksfBufOffset, HKS_RKC_KSF_DATA_RSV_LEN) != EOK) { + HKS_LOG_E("Memcpy mkRsv failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += HKS_RKC_KSF_DATA_RSV_LEN; + + return HKS_SUCCESS; +} + +static int32_t RkcExtractKsfHash(const struct HksBlob *ksfFromFile, uint32_t *ksfBufOffset) +{ + /* calculate sha256, skip file flag, begin with version, end with reserve field. */ + uint8_t hashResult[HKS_RKC_HASH_LEN] = {0}; + struct HksBlob hashResultBlob = { HKS_RKC_HASH_LEN, hashResult }; + /* the upper layer ensures no overflow */ + const struct HksBlob hashSrc = { *ksfBufOffset - HKS_RKC_KSF_FLAG_LEN, ksfFromFile->data + HKS_RKC_KSF_FLAG_LEN }; + int32_t ret = HksCryptoHalHash(HKS_DIGEST_SHA256, &hashSrc, &hashResultBlob); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Hks hash failed! ret = 0x%X", ret); + return ret; + } + + /* Extract hash from ksf buffer */ + uint8_t ksfHash[HKS_RKC_HASH_LEN] = {0}; + if (memcpy_s(&ksfHash, HKS_RKC_HASH_LEN, ksfFromFile->data + *ksfBufOffset, HKS_RKC_HASH_LEN) != EOK) { + HKS_LOG_E("Memcpy ksfHash failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += HKS_RKC_HASH_LEN; + + /* Check hash result. */ + if (HksMemCmp(hashResult, ksfHash, HKS_RKC_HASH_LEN) != 0) { + HKS_LOG_E("Ksf hash result is Invalid!"); + return HKS_ERROR_INVALID_KEY_FILE; + } + + return HKS_SUCCESS; +} + +static int32_t RkcExtractKsfBuf(const struct HksBlob *ksfFromFile, struct HksRkcKsfData *ksfData) +{ + uint32_t ksfBufOffset = 0; + + /* Extract file flag. */ + int32_t ret = RkcExtractKsfFileFlag(ksfFromFile, &ksfBufOffset); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* Extract root key data */ + ret = RkcExtractKsfRk(ksfFromFile, &ksfBufOffset, ksfData); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Rkc extract ksf rk failed! ret = 0x%X", ret); + return ret; + } + + /* Extract main key data */ + ret = RkcExtractKsfMk(ksfFromFile, &ksfBufOffset, ksfData); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* Extract hash */ + return RkcExtractKsfHash(ksfFromFile, &ksfBufOffset); +} + +int32_t HksRkcReadKsf(const char *ksfName, struct HksRkcKsfData *ksfData) +{ + struct HksBlob tmpKsf; + tmpKsf.data = (uint8_t *)HksMalloc(HKS_RKC_KSF_BUF_LEN); + if (tmpKsf.data == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + tmpKsf.size = HKS_RKC_KSF_BUF_LEN; + (void)memset_s(tmpKsf.data, tmpKsf.size, 0, tmpKsf.size); + + int32_t ret; + do { + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + ret = HKS_ERROR_INTERNAL_ERROR; + break; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + const struct HksBlob fileNameBlob = { strlen(ksfName), (uint8_t *)ksfName }; + + ret = HksStoreGetKeyBlob(&processNameBlob, &fileNameBlob, HKS_STORAGE_TYPE_ROOT_KEY, &tmpKsf); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Get ksf file failed! ret = 0x%X", ret); + break; + } + + ret = RkcExtractKsfBuf(&tmpKsf, ksfData); + } while (0); + + /* the data of root key should be cleared after use */ + (void)memset_s(tmpKsf.data, tmpKsf.size, 0, tmpKsf.size); + HKS_FREE_BLOB(tmpKsf); + return ret; +} + +static int32_t RkcFillKsfTime(const struct HksTime *time, struct HksBlob *ksfBuf, uint32_t *ksfBufOffset) +{ + if (memcpy_s(ksfBuf->data + *ksfBufOffset, sizeof(uint16_t), &(time->hksYear), sizeof(uint16_t)) != EOK) { + HKS_LOG_E("Memcpy hksYear failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint16_t); + + if (memcpy_s(ksfBuf->data + *ksfBufOffset, sizeof(uint8_t), &(time->hksMon), sizeof(uint8_t)) != EOK) { + HKS_LOG_E("Memcpy hksMon failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint8_t); + + if (memcpy_s(ksfBuf->data + *ksfBufOffset, sizeof(uint8_t), &(time->hksDay), sizeof(uint8_t)) != EOK) { + HKS_LOG_E("Memcpy hksDay failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint8_t); + + if (memcpy_s(ksfBuf->data + *ksfBufOffset, sizeof(uint8_t), &(time->hksHour), sizeof(uint8_t)) != EOK) { + HKS_LOG_E("Memcpy hksHour failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint8_t); + + if (memcpy_s(ksfBuf->data + *ksfBufOffset, sizeof(uint8_t), &(time->hksMin), sizeof(uint8_t)) != EOK) { + HKS_LOG_E("Memcpy hksMin failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint8_t); + + if (memcpy_s(ksfBuf->data + *ksfBufOffset, sizeof(uint8_t), &(time->hksSec), sizeof(uint8_t)) != EOK) { + HKS_LOG_E("Memcpy hksSec failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint8_t); + + return HKS_SUCCESS; +} + +static int32_t RkcFillKsfRk(const struct HksRkcKsfData *ksfData, struct HksBlob *ksfBuf, uint32_t *ksfBufOffset) +{ + /* Fill version */ + if (memcpy_s(ksfBuf->data + *ksfBufOffset, sizeof(uint16_t), &(ksfData->version), sizeof(uint16_t)) != EOK) { + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint16_t); + + /* Fill rkCreatedTime */ + int32_t ret = RkcFillKsfTime(&(ksfData->rkCreatedTime), ksfBuf, ksfBufOffset); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* Fill rkExpiredTime */ + ret = RkcFillKsfTime(&(ksfData->rkExpiredTime), ksfBuf, ksfBufOffset); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* Fill the first material */ + if (memcpy_s(ksfBuf->data + *ksfBufOffset, HKS_RKC_MATERIAL_LEN, + ksfData->rkMaterial1, HKS_RKC_MATERIAL_LEN) != EOK) { + HKS_LOG_E("Memcpy first material to ksf buf failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += HKS_RKC_MATERIAL_LEN; + + /* Fill the second material */ + if (memcpy_s(ksfBuf->data + *ksfBufOffset, HKS_RKC_MATERIAL_LEN, + ksfData->rkMaterial2, HKS_RKC_MATERIAL_LEN) != EOK) { + HKS_LOG_E("Memcpy second material to ksf buf failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += HKS_RKC_MATERIAL_LEN; + + /* Fill iterator number */ + if (memcpy_s(ksfBuf->data + *ksfBufOffset, sizeof(uint32_t), &(ksfData->rmkIter), sizeof(uint32_t)) != EOK) { + HKS_LOG_E("Memcpy iterator number to ksf buf failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint32_t); + + /* Fill salt */ + if (memcpy_s(ksfBuf->data + *ksfBufOffset, HKS_RKC_SALT_LEN, ksfData->rmkSalt, HKS_RKC_SALT_LEN) != EOK) { + HKS_LOG_E("Memcpy salt to ksf buf failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += HKS_RKC_SALT_LEN; + + /* Fill hash algorithm */ + if (memcpy_s(ksfBuf->data + *ksfBufOffset, sizeof(uint32_t), &(ksfData->rmkHashAlg), sizeof(uint32_t)) != EOK) { + HKS_LOG_E("Memcpy hash algorithm to ksf buf failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint32_t); + + /* Fill reserve field */ + if (memcpy_s(ksfBuf->data + *ksfBufOffset, HKS_RKC_KSF_DATA_RSV_LEN, + ksfData->rkRsv, HKS_RKC_KSF_DATA_RSV_LEN) != EOK) { + HKS_LOG_E("Memcpy reserve field to ksf buf failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += HKS_RKC_KSF_DATA_RSV_LEN; + + return HKS_SUCCESS; +} + +static int32_t RkcFillKsfMk(const struct HksRkcKsfData *ksfData, struct HksBlob *ksfBuf, uint32_t *ksfBufOffset) +{ + /* Fill mkCreatedTime */ + int32_t ret = RkcFillKsfTime(&(ksfData->mkCreatedTime), ksfBuf, ksfBufOffset); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Fill mk created time to ksf buf failed!"); + return ret; + } + + /* Fill mkExpiredTime */ + ret = RkcFillKsfTime(&(ksfData->mkExpiredTime), ksfBuf, ksfBufOffset); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Fill mk expired time to ksf buf failed!"); + return ret; + } + + /* Fill encrption algorithm */ + if (memcpy_s(ksfBuf->data + *ksfBufOffset, sizeof(uint32_t), &(ksfData->mkEncryptAlg), sizeof(uint32_t)) != EOK) { + HKS_LOG_E("Memcpy encrption algorithm to ksf buf failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += sizeof(uint32_t); + + /* Fill IV */ + if (memcpy_s(ksfBuf->data + *ksfBufOffset, HKS_RKC_MK_IV_LEN, ksfData->mkIv, HKS_RKC_MK_IV_LEN) != EOK) { + HKS_LOG_E("Memcpy iv to ksf buf failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += HKS_RKC_MK_IV_LEN; + + /* Fill ciphertext */ + if (memcpy_s(ksfBuf->data + *ksfBufOffset, HKS_RKC_MK_CIPHER_TEXT_LEN, + ksfData->mkCiphertext, HKS_RKC_MK_CIPHER_TEXT_LEN) != EOK) { + HKS_LOG_E("Memcpy ciphertext to ksf buf failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += HKS_RKC_MK_CIPHER_TEXT_LEN; + + /* Fill reserve field */ + if (memcpy_s(ksfBuf->data + *ksfBufOffset, HKS_RKC_KSF_DATA_RSV_LEN, + ksfData->mkRsv, HKS_RKC_KSF_DATA_RSV_LEN) != EOK) { + HKS_LOG_E("Memcpy reserve field to ksf buf failed!"); + return HKS_ERROR_BAD_STATE; + } + *ksfBufOffset += HKS_RKC_KSF_DATA_RSV_LEN; + + return HKS_SUCCESS; +} + +static int32_t RkcFillKsfHash(struct HksBlob *ksfBuf, uint32_t *ksfBufOffset) +{ + if ((ksfBuf->size < HKS_RKC_KSF_FLAG_LEN) || (*ksfBufOffset <= HKS_RKC_KSF_FLAG_LEN) || + (ksfBuf->size < *ksfBufOffset)) { + return HKS_ERROR_INVALID_ARGUMENT; + } + + /* calculate sha256, skip file flag, begin with version, end with reserve field. */ + const struct HksBlob hashSrc = { *ksfBufOffset - HKS_RKC_KSF_FLAG_LEN, ksfBuf->data + HKS_RKC_KSF_FLAG_LEN }; + struct HksBlob hash = { HKS_RKC_HASH_LEN, ksfBuf->data + *ksfBufOffset }; + int32_t ret = HksCryptoHalHash(HKS_DIGEST_SHA256, &hashSrc, &hash); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Hash failed! ret = 0x%X", ret); + return ret; + } + *ksfBufOffset += HKS_RKC_HASH_LEN; + + return HKS_SUCCESS; +} + +static int32_t RkcFillKsfBuf(const struct HksRkcKsfData *ksfData, struct HksBlob *ksfBuf) +{ + uint32_t ksfBufOffset = 0; + + /* Fill file flag */ + if (memcpy_s(ksfBuf->data, HKS_RKC_KSF_FLAG_LEN, g_hksRkcKsfFlag, HKS_RKC_KSF_FLAG_LEN) != EOK) { + HKS_LOG_E("Memcpy file flag to ksd buf failed!"); + return HKS_ERROR_BAD_STATE; + } + ksfBufOffset += HKS_RKC_KSF_FLAG_LEN; + + /* Fill root key */ + int32_t ret = RkcFillKsfRk(ksfData, ksfBuf, &ksfBufOffset); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Fill root key info to ksf buf failed! ret = 0x%X", ret); + return ret; + } + + /* Fill main key */ + ret = RkcFillKsfMk(ksfData, ksfBuf, &ksfBufOffset); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Fill main key info to ksf buf failed! ret = 0x%X", ret); + return ret; + } + + /* calculate and fill SHA256 result, skip file flag, begin with version, end with reserve field. */ + ret = RkcFillKsfHash(ksfBuf, &ksfBufOffset); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Fill hash to ksf buf failed! ret = 0x%X", ret); + return ret; + } + + return HKS_SUCCESS; +} + +int32_t HksRkcWriteKsf(const char *ksfName, const struct HksRkcKsfData *ksfData) +{ + struct HksBlob ksfBuf; + ksfBuf.data = (uint8_t *)HksMalloc(HKS_RKC_KSF_BUF_LEN); + if (ksfBuf.data == NULL) { + HKS_LOG_E("Malloc ksf buffer failed!"); + return HKS_ERROR_MALLOC_FAIL; + } + ksfBuf.size = HKS_RKC_KSF_BUF_LEN; + (void)memset_s(ksfBuf.data, ksfBuf.size, 0, ksfBuf.size); + + int32_t ret; + do { + /* Fill data into buffer */ + ret = RkcFillKsfBuf(ksfData, &ksfBuf); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Fill ksf buf failed! ret = 0x%X", ret); + break; + } + + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + ret = HKS_ERROR_INTERNAL_ERROR; + break; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + + /* write buffer data into keystore file */ + const struct HksBlob fileNameBlob = { strlen(ksfName), (uint8_t *)ksfName }; + ret = HksStoreKeyBlob(&processNameBlob, &fileNameBlob, HKS_STORAGE_TYPE_ROOT_KEY, &ksfBuf); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Store ksf failed! ret = 0x%X", ret); + } + } while (0); + + (void)memset_s(ksfBuf.data, ksfBuf.size, 0, ksfBuf.size); + HKS_FREE_BLOB(ksfBuf); + return ret; +} + +bool RkcKsfExist(void) +{ + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return false; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + + for (uint32_t i = 0; i < g_hksRkcCfg.ksfAttr.num; ++i) { + const struct HksBlob fileNameBlob = { + strlen(g_hksRkcCfg.ksfAttr.name[i]), + (uint8_t *)(g_hksRkcCfg.ksfAttr.name[i]) + }; + + int32_t ret = HksStoreIsKeyBlobExist(&processNameBlob, &fileNameBlob, HKS_STORAGE_TYPE_ROOT_KEY); + if (ret == HKS_SUCCESS) { + /* return true if one exists */ + return true; + } + } + + return false; +} +#endif /* _CUT_AUTHENTICATE_ */ diff --git a/services/huks_standard/huks_engine/main/core/src/hks_upgrade_key_info.c b/services/huks_standard/huks_engine/main/core/src/hks_upgrade_key_info.c new file mode 100644 index 00000000..7ca83b41 --- /dev/null +++ b/services/huks_standard/huks_engine/main/core/src/hks_upgrade_key_info.c @@ -0,0 +1,661 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef _CUT_AUTHENTICATE_ + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#ifdef HKS_SUPPORT_UPGRADE_STORAGE_DATA + +#include "hks_upgrade_key_info.h" + +#include "hks_common_check.h" +#include "hks_crypto_hal.h" +#include "hks_get_process_info.h" +#include "hks_keyblob.h" +#include "hks_log.h" +#include "hks_mem.h" +#include "hks_param.h" + +#define HKS_SEALING_NONCE_SIZE 16 +#define HKS_KEY_PAIR_CIPHER_ED25519 80 + +#define HKS_SLOT_PUBLIC_KEY_OCCUPY ((uint8_t)0x01) /* ed25519 public key */ +#define HKS_SLOT_KEYPAIR_OCCUPY ((uint8_t)0x03) /* ed25519 private and public key pair */ +#define HKS_SLOT_DERIVE_OCCUPY ((uint8_t)0x04) /* aes key: generate by ed25519 agreement */ + +#define HKS_KEY_TYPE_PUBLIC_KEY_ED25519 ((uint32_t)0xe001001d) +#define HKS_KEY_TYPE_KEY_PAIR_ED25519 ((uint32_t)0xf001001d) + +struct HksKeyStoreInfo { + uint32_t keyType; + uint32_t keyUsage; + uint32_t keyMode; + uint32_t keyRole; + uint16_t keyLen; + uint16_t keyDomain; + uint8_t keyPadding; + uint8_t authIdType; + uint8_t authIdSize; + uint8_t rsv; + uint8_t *authIdData; +}; + +struct HksNewVersionValue { + uint32_t algType; + uint32_t keySize; + uint32_t purpose; + uint32_t digest; +}; + +/* + * +------------------------------------------------------------------------------------------+ + * KeyInfo: | flags | sealingNonce | aliasSize | keyAlias | keyType | keyLen | usage | + * | 1bytes | 16bytes | 1bytes | max64bytes | 4bytes | 2bytes | 4bytes | + * +------------------------------------------------------------------------------------------+ + * | padding | keyMode | key_role | domain | authIdType | authIdSize | auth_id_data | + * | 1bytes | 4bytes | 4bytes | 2bytes | 1bytes | 1bytes | max64bytes | + * +------------------------------------------------------------------------------------------+ + * | keySize | key | + * | 1bytes | max80bytes | + * +------------------------+ +*/ +static uint32_t GetKeySlotLen(void) +{ + return (sizeof(uint8_t) + HKS_SEALING_NONCE_SIZE + sizeof(uint8_t) + HKS_MAX_KEY_ALIAS_LEN + + (sizeof(uint32_t) + sizeof(uint16_t) + sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint32_t) + + sizeof(uint32_t) + sizeof(uint16_t) + sizeof(uint8_t) + sizeof(uint8_t) + HKS_MAX_KEY_AUTH_ID_LEN) + + sizeof(uint8_t) + HKS_KEY_PAIR_CIPHER_ED25519); +} + +static int32_t GetParamPosition(const struct HksBlob *keyInfo, uint32_t *paramPosition) +{ + /* keyInfo size has beed checked */ + uint32_t offset = sizeof(uint8_t) + HKS_SEALING_NONCE_SIZE; /* offset: flag and sealing nonce */ + uint8_t keyAliasSize = *(keyInfo->data + offset); + if (keyAliasSize > HKS_MAX_KEY_ALIAS_LEN) { + HKS_LOG_E("invalid keyAlias size, size = %u", keyAliasSize); + return HKS_ERROR_INVALID_KEY_FILE; + } + + offset += sizeof(uint8_t) + keyAliasSize; /* offset: add keyAlias size and real size */ + *paramPosition = offset; + return HKS_SUCCESS; +} + +static int32_t GetKeySizePosition(const struct HksBlob *keyInfo, uint32_t *keySizePosition) +{ + /* keyInfo size has beed checked */ + uint32_t offset = 0; + int32_t ret = GetParamPosition(keyInfo, &offset); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* offset keyType + keyLen + keyUsage + padding + mode + role + domain + authIdType */ + offset += sizeof(uint32_t) + sizeof(uint16_t) + sizeof(uint32_t) + + sizeof(uint8_t) + sizeof(uint32_t) + sizeof(uint32_t) + sizeof(uint16_t) + sizeof(uint8_t); + + uint8_t authIdSize = *(keyInfo->data + offset); + if (authIdSize > HKS_MAX_KEY_AUTH_ID_LEN) { + HKS_LOG_E("invalid auth id size, size = %u", authIdSize); + return HKS_ERROR_INVALID_KEY_FILE; + } + + offset += sizeof(uint8_t) + authIdSize; /* offset: add key authId size and real size */ + *keySizePosition = offset; + return HKS_SUCCESS; +} + +static int32_t GetKeyInfo(const struct HksBlob *keyInfo, struct HksKeyStoreInfo *keyStoreInfo) +{ + /* keyInfo size has beed checked */ + uint32_t offset = 0; + int32_t ret = GetParamPosition(keyInfo, &offset); + if (ret != HKS_SUCCESS) { + return ret; + } + + uint8_t *tmp = keyInfo->data; + keyStoreInfo->rsv = 0; + keyStoreInfo->keyType = *((uint32_t *)(tmp + offset)); + offset += sizeof(uint32_t); + + keyStoreInfo->keyLen = *((uint16_t *)(tmp + offset)); + offset += sizeof(uint16_t); + + keyStoreInfo->keyUsage = *((uint32_t *)(tmp + offset)); + offset += sizeof(uint32_t); + + keyStoreInfo->keyPadding = *(tmp + offset); + offset += sizeof(uint8_t); + + keyStoreInfo->keyMode = *((uint32_t *)(tmp + offset)); + offset += sizeof(uint32_t); + + keyStoreInfo->keyRole = *((uint32_t *)(tmp + offset)); + offset += sizeof(uint32_t); + + keyStoreInfo->keyDomain = *((uint16_t *)(tmp + offset)); + offset += sizeof(uint16_t); + + keyStoreInfo->authIdType = *(tmp + offset); + offset += sizeof(uint8_t); + + keyStoreInfo->authIdSize = *(tmp + offset); + if (keyStoreInfo->authIdSize > HKS_MAX_KEY_AUTH_ID_LEN) { + HKS_LOG_E("invalid auth id size, size = %u", keyStoreInfo->authIdSize); + return HKS_ERROR_INVALID_KEY_FILE; + } + offset += sizeof(uint8_t); + + if (keyStoreInfo->authIdSize != 0) { + uint8_t *tmpAuthId = (uint8_t *)HksMalloc(keyStoreInfo->authIdSize); + if (tmpAuthId == NULL) { + HKS_LOG_E("malloc failed"); + return HKS_ERROR_MALLOC_FAIL; + } + (void)memcpy_s(tmpAuthId, keyStoreInfo->authIdSize, tmp + offset, keyStoreInfo->authIdSize); + keyStoreInfo->authIdData = tmpAuthId; + } + return HKS_SUCCESS; +} + +static int32_t GetNonce(const struct HksBlob *keyInfo, struct HksBlob *nonce) +{ + uint8_t *tmp = (uint8_t *)HksMalloc(HKS_SEALING_NONCE_SIZE); + if (tmp == NULL) { + HKS_LOG_E("malloc failed"); + return HKS_ERROR_MALLOC_FAIL; + } + + uint32_t offset = sizeof(uint8_t); /* offset: flags */ + /* keyInfo size has beed checked */ + if (memcpy_s(tmp, HKS_SEALING_NONCE_SIZE, keyInfo->data + offset, HKS_SEALING_NONCE_SIZE) != EOK) { + HKS_LOG_E("memcpy nonce failed"); + HKS_FREE_PTR(tmp); + return HKS_ERROR_BAD_STATE; + } + + nonce->data = tmp; + nonce->size = HKS_SEALING_NONCE_SIZE; + return HKS_SUCCESS; +} + +static int32_t BuildDecryptMeterail(const struct HksBlob *keyInfo, const struct HksBlob *nonce, + struct HksUsageSpec *usageSpec, struct HksBlob *cipherKey) +{ + uint32_t keySizePosition = 0; + int32_t ret = GetKeySizePosition(keyInfo, &keySizePosition); + if (ret != HKS_SUCCESS) { + return ret; + } + uint32_t keyPos = keySizePosition + sizeof(uint8_t); + struct HksBlob aad = { keyPos, keyInfo->data }; /* aad: from flags to keySize */ + + usageSpec->mode = HKS_MODE_GCM; + usageSpec->padding = HKS_PADDING_NONE; + usageSpec->digest = HKS_DIGEST_NONE; + usageSpec->algType = HKS_ALG_AES; + + uint8_t encryptedKeySize = *(keyInfo->data + keySizePosition); + if ((encryptedKeySize > HKS_KEY_PAIR_CIPHER_ED25519) || (encryptedKeySize <= HKS_AE_TAG_LEN)) { + HKS_LOG_E("invalid key size, size = %u", encryptedKeySize); + return HKS_ERROR_INVALID_KEY_FILE; + } + + struct HksAeadParam *aeadParam = (struct HksAeadParam *)usageSpec->algParam; + aeadParam->nonce = *nonce; + aeadParam->aad = aad; + aeadParam->payloadLen = encryptedKeySize - HKS_AE_TAG_LEN; + + aeadParam->tagDec.data = keyInfo->data + keyPos + encryptedKeySize - HKS_AE_TAG_LEN; + aeadParam->tagDec.size = HKS_AE_TAG_LEN; + + cipherKey->size = encryptedKeySize - HKS_AE_TAG_LEN; + cipherKey->data = keyInfo->data + keyPos; + return HKS_SUCCESS; +} + +static int32_t GetKek(const struct HksBlob *salt, struct HksBlob *kek) +{ + uint8_t mainKeyData[HKS_KEY_BLOB_MAIN_KEY_SIZE] = {0}; + struct HksBlob mainKey = { HKS_KEY_BLOB_MAIN_KEY_SIZE, mainKeyData }; + int32_t ret = HksCryptoHalGetMainKey(NULL, &mainKey); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get main key failed, ret = %d", ret); + return ret; + } + + struct HksKeyDerivationParam derParam = { + .salt = *salt, + .iterations = 1, /* old version only derive 1 time */ + .digestAlg = HKS_DIGEST_SHA256, + }; + struct HksKeySpec derivationSpec = { HKS_ALG_PBKDF2, HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256), &derParam }; + + kek->size = HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256); + kek->data = (uint8_t *)HksMalloc(kek->size); + if (kek->data == NULL) { + HKS_LOG_E("malloc failed"); + (void)memset_s(mainKeyData, HKS_KEY_BLOB_MAIN_KEY_SIZE, 0, HKS_KEY_BLOB_MAIN_KEY_SIZE); + return HKS_ERROR_MALLOC_FAIL; + } + + ret = HksCryptoHalDeriveKey(&mainKey, &derivationSpec, kek); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get keyblob derive key failed!"); + HKS_FREE_PTR(kek->data); + } + (void)memset_s(mainKeyData, HKS_KEY_BLOB_MAIN_KEY_SIZE, 0, HKS_KEY_BLOB_MAIN_KEY_SIZE); + + return ret; +} + +static int32_t DecryptKey(const struct HksBlob *kek, const struct HksUsageSpec *usageSpec, + const struct HksBlob *cipherKey, struct HksBlob *key) +{ + key->data = HksMalloc(cipherKey->size); + if (key->data == NULL) { + HKS_LOG_E("malloc failed"); + return HKS_ERROR_MALLOC_FAIL; + } + key->size = cipherKey->size; + + int32_t ret = HksCryptoHalDecrypt(kek, usageSpec, cipherKey, key); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("crypto hal decrypt failed, ret = %d", ret); + HKS_FREE_PTR(key->data); /* decrypted failed, no need clear memory */ + key->size = 0; + return HKS_ERROR_CRYPTO_ENGINE_ERROR; /* need return this error code for hichian call refresh func */ + } + return ret; +} + +static int32_t CopyToNewBlob(const struct HksBlob *key, struct HksBlob *outKey) +{ + uint8_t *keyBuffer = (uint8_t *)HksMalloc(key->size); + if (keyBuffer == NULL) { + HKS_LOG_E("public key to inner key format malloc keyBuffer failed!"); + return HKS_ERROR_MALLOC_FAIL; + } + + (void)memcpy_s(keyBuffer, key->size, key->data, key->size); + outKey->data = keyBuffer; + outKey->size = key->size; + return HKS_SUCCESS; +} + +static int32_t ConvertEd25519ToNewFormat(uint8_t flag, const struct HksBlob *pubKey, const struct HksBlob *priKey, + struct HksBlob *keyOut) +{ + uint32_t totalSize = sizeof(struct KeyMaterial25519) + pubKey->size + priKey->size; + uint8_t *buffer = (uint8_t *)HksMalloc(totalSize); + if (buffer == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + + struct KeyMaterial25519 *keyMaterial = (struct KeyMaterial25519 *)buffer; + keyMaterial->keyAlg = HKS_ALG_ED25519; + keyMaterial->keySize = HKS_CURVE25519_KEY_SIZE_256; + keyMaterial->pubKeySize = pubKey->size; + keyMaterial->priKeySize = priKey->size; + keyMaterial->reserved = 0; + + uint32_t offset = sizeof(struct KeyMaterial25519); + if (memcpy_s(buffer + offset, pubKey->size, pubKey->data, pubKey->size) != EOK) { + HKS_LOG_E("copy ed25519 public key failed"); + (void)memset_s(buffer, totalSize, 0, totalSize); + HKS_FREE_PTR(buffer); + return HKS_ERROR_BAD_STATE; + } + + if (flag == HKS_SLOT_KEYPAIR_OCCUPY) { + offset += pubKey->size; + if (memcpy_s(buffer + offset, priKey->size, priKey->data, priKey->size) != EOK) { + HKS_LOG_E("copy ed25519 private key failed"); + (void)memset_s(buffer, totalSize, 0, totalSize); + HKS_FREE_PTR(buffer); + return HKS_ERROR_BAD_STATE; + } + } + + keyOut->data = buffer; + keyOut->size = totalSize; + return HKS_SUCCESS; +} + +static int32_t ConvertToNewFormat(const struct HksBlob *keyInfo, const struct HksBlob *rawKey, struct HksBlob *key) +{ + uint8_t flag = *(keyInfo->data); + struct HksBlob priKey = { 0, NULL }; + struct HksBlob pubKey = { 0, NULL }; + switch (flag) { + case HKS_SLOT_PUBLIC_KEY_OCCUPY: + if (rawKey->size != HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256)) { + return HKS_ERROR_INVALID_KEY_FILE; + } + + pubKey.size = rawKey->size; + pubKey.data = rawKey->data; + + return ConvertEd25519ToNewFormat(flag, &pubKey, &priKey, key); + case HKS_SLOT_KEYPAIR_OCCUPY: + if (rawKey->size != (HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256) << 1)) { + return HKS_ERROR_INVALID_KEY_FILE; + } + + /* old version: the first 32 bytes is private key; next 32 bytes is public key */ + priKey.size = HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256); + priKey.data = rawKey->data; + pubKey.size = HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256); + pubKey.data = rawKey->data + priKey.size; + + return ConvertEd25519ToNewFormat(flag, &pubKey, &priKey, key); + case HKS_SLOT_DERIVE_OCCUPY: + if (rawKey->size != HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256)) { + return HKS_ERROR_INVALID_KEY_FILE; + } + + return CopyToNewBlob(rawKey, key); + default: + return HKS_ERROR_INVALID_KEY_FILE; + } +} + +static int32_t GetNewFormatKey(const struct HksBlob *keyInfo, struct HksBlob *key) +{ + struct HksBlob kek = { 0, NULL }; + struct HksBlob nonce = { 0, NULL }; + struct HksBlob rawKey = { 0, NULL }; + int32_t ret = GetNonce(keyInfo, &nonce); + if (ret != HKS_SUCCESS) { + return ret; + } + + do { + ret = GetKek(&nonce, &kek); + if (ret != HKS_SUCCESS) { + break; + } + + struct HksAeadParam aeadParam; + struct HksUsageSpec usageSpec; + (void)memset_s(&aeadParam, sizeof(aeadParam), 0, sizeof(aeadParam)); + (void)memset_s(&usageSpec, sizeof(usageSpec), 0, sizeof(usageSpec)); + usageSpec.algParam = (void *)&aeadParam; + + struct HksBlob cipherKey = { 0, NULL }; + ret = BuildDecryptMeterail(keyInfo, &nonce, &usageSpec, &cipherKey); + if (ret != HKS_SUCCESS) { + break; + } + + ret = DecryptKey(&kek, &usageSpec, &cipherKey, &rawKey); + if (ret != HKS_SUCCESS) { + break; + } + + ret = ConvertToNewFormat(keyInfo, &rawKey, key); + if (ret != HKS_SUCCESS) { + break; + } + } while (0); + + HKS_FREE_BLOB(nonce); + if (kek.data != NULL) { + (void)memset_s(kek.data, kek.size, 0, kek.size); + HKS_FREE_BLOB(kek); + } + if (rawKey.data != NULL) { + (void)memset_s(rawKey.data, rawKey.size, 0, rawKey.size); + HKS_FREE_BLOB(rawKey); + } + return ret; +} + +static int32_t AddKeyAuthIdParam(const struct HksKeyStoreInfo *keyStoreInfo, struct HksParamSet *paramSet) +{ + if (keyStoreInfo->authIdSize == 0) { + return HKS_SUCCESS; + } + + struct HksBlob keyAuthId = { keyStoreInfo->authIdSize, keyStoreInfo->authIdData }; + struct HksParam keyAuthIdParam = { + .tag = HKS_TAG_KEY_AUTH_ID, + .blob = keyAuthId + }; + + int32_t ret = HksAddParams(paramSet, &keyAuthIdParam, 1); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("add param keyAuthId failed!"); + } + return ret; +} + +static int32_t TranslateToNewValue(uint8_t flag, const struct HksKeyStoreInfo *keyStoreInfo, + struct HksNewVersionValue *spec) +{ + if (((flag == HKS_SLOT_KEYPAIR_OCCUPY) && (keyStoreInfo->keyType != HKS_KEY_TYPE_KEY_PAIR_ED25519)) || + ((flag == HKS_SLOT_PUBLIC_KEY_OCCUPY) && (keyStoreInfo->keyType != HKS_KEY_TYPE_PUBLIC_KEY_ED25519))) { + return HKS_ERROR_INVALID_KEY_FILE; + } + + spec->algType = HKS_ALG_ED25519; + spec->keySize = HKS_CURVE25519_KEY_SIZE_256; + spec->digest = HKS_DIGEST_SHA256; /* upgrade DERIVE_OCCUPY type key: set to default sha256 */ + if (flag == HKS_SLOT_KEYPAIR_OCCUPY) { + spec->purpose = HKS_KEY_PURPOSE_SIGN | HKS_KEY_PURPOSE_VERIFY; + } else if (flag == HKS_SLOT_PUBLIC_KEY_OCCUPY) { + spec->purpose = HKS_KEY_PURPOSE_VERIFY; + } else if (flag == HKS_SLOT_DERIVE_OCCUPY) { + spec->algType = HKS_ALG_AES; + spec->keySize = HKS_AES_KEY_SIZE_256; + spec->purpose = HKS_KEY_PURPOSE_DERIVE; + } else { + return HKS_ERROR_INVALID_KEY_FILE; + } + return HKS_SUCCESS; +} + +static int32_t AddKeyInfoParams(uint8_t flag, const struct HksKeyStoreInfo *keyStoreInfo, struct HksParamSet *paramSet) +{ + struct HksNewVersionValue spec; + (void)memset_s(&spec, sizeof(spec), 0, sizeof(spec)); + int32_t ret = TranslateToNewValue(flag, keyStoreInfo, &spec); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("translate to new value failed, ret = %d", ret); + return ret; + } + + struct HksParam params[] = { + { + .tag = HKS_TAG_ALGORITHM, + .uint32Param = spec.algType + }, { + .tag = HKS_TAG_PURPOSE, + .uint32Param = spec.purpose + }, { + .tag = HKS_TAG_KEY_SIZE, + .uint32Param = spec.keySize + }, { + .tag = HKS_TAG_DIGEST, + .uint32Param = spec.digest + }, { + .tag = HKS_TAG_KEY_ROLE, + .uint32Param = keyStoreInfo->keyRole + }, { + .tag = HKS_TAG_KEY_DOMAIN, + .uint32Param = keyStoreInfo->keyDomain + }, + }; + + ret = HksAddParams(paramSet, params, sizeof(params) / sizeof(params[0])); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("add params failed!"); + return ret; + } + + return AddKeyAuthIdParam(keyStoreInfo, paramSet); +} + +static int32_t AddProcessNameParam(struct HksParamSet *paramSet) +{ + char *processName = NULL; + int32_t ret = HksGetProcessName(&processName); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + struct HksParam processNameParam = { + .tag = HKS_TAG_PROCESS_NAME, + .blob = processNameBlob + }; + + ret = HksAddParams(paramSet, &processNameParam, 1); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("add param proceseName failed!"); + } + return ret; +} + +static int32_t AddParams(const struct HksBlob *keyInfo, struct HksParamSet *paramSet) +{ + int32_t ret = AddProcessNameParam(paramSet); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* add params from key storage file */ + struct HksKeyStoreInfo keyStoreInfo; + (void)memset_s(&keyStoreInfo, sizeof(keyStoreInfo), 0, sizeof(keyStoreInfo)); + ret = GetKeyInfo(keyInfo, &keyStoreInfo); + if (ret != HKS_SUCCESS) { + return ret; + } + + uint8_t flag = *(keyInfo->data); + ret = AddKeyInfoParams(flag, &keyStoreInfo, paramSet); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("add key info params failed, ret = %d", ret); + } + if (keyStoreInfo.authIdData != NULL) { + HKS_FREE_PTR(keyStoreInfo.authIdData); + } + return ret; +} + +static int32_t GetParamSet(const struct HksBlob *keyInfo, struct HksParamSet **paramSet) +{ + struct HksParamSet *outputParamSet = NULL; + int32_t ret = HksInitParamSet(&outputParamSet); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("HksInitParamSet failed!"); + return ret; + } + + do { + ret = AddParams(keyInfo, outputParamSet); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("AddParams failed!"); + break; + } + + ret = HksBuildParamSet(&outputParamSet); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("HksBuildParamSet failed!"); + break; + } + } while (0); + + if (ret != HKS_SUCCESS) { + HKS_LOG_E("ConstructParamSet failed."); + HksFreeParamSet(&outputParamSet); + return ret; + } + + *paramSet = outputParamSet; + return ret; +} + +static int32_t GetKeyFlag(const struct HksBlob *keyInfo, uint8_t *keyFlag) +{ + uint8_t flag = *(keyInfo->data); + switch (flag) { + case HKS_SLOT_PUBLIC_KEY_OCCUPY: + *keyFlag = HKS_KEY_FLAG_IMPORT_KEY; + break; + case HKS_SLOT_KEYPAIR_OCCUPY: + case HKS_SLOT_DERIVE_OCCUPY: + *keyFlag = HKS_KEY_FLAG_GENERATE_KEY; + break; + default: + return HKS_ERROR_INVALID_KEY_FILE; + } + return HKS_SUCCESS; +} + +int32_t HksUpgradeKeyInfo(const struct HksBlob *keyAlias, const struct HksBlob *keyInfo, struct HksBlob *keyOut) +{ + int32_t ret = HksCheckBlob3(keyAlias, keyInfo, keyOut); + if (ret != HKS_SUCCESS) { + return ret; + } + if (keyInfo->size < GetKeySlotLen()) { + HKS_LOG_E("invalid key info size, size = %u", keyInfo->size); + return ret; + } + + struct HksBlob key = { 0, NULL }; + struct HksParamSet *paramSet = NULL; + + do { + ret = GetNewFormatKey(keyInfo, &key); + if (ret != HKS_SUCCESS) { + break; + } + + ret = GetParamSet(keyInfo, ¶mSet); + if (ret != HKS_SUCCESS) { + break; + } + + uint8_t keyFlag = 0; + ret = GetKeyFlag(keyInfo, &keyFlag); + if (ret != HKS_SUCCESS) { + break; + } + + ret = HksBuildKeyBlob(keyAlias, keyFlag, &key, paramSet, keyOut); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("generate key blob failed, ret = %d", ret); + break; + } + } while (0); + + if (key.data != NULL) { + (void)memset_s(key.data, key.size, 0, key.size); + HKS_FREE_BLOB(key); + } + HksFreeParamSet(¶mSet); + return ret; +} +#endif /* HKS_SUPPORT_UPGRADE_STORAGE_DATA */ +#endif /* _CUT_AUTHENTICATE_ */ diff --git a/services/huks_standard/huks_engine/main/os_dependency/BUILD.gn b/services/huks_standard/huks_engine/main/os_dependency/BUILD.gn index 748e8ded..abccc5a8 100644 --- a/services/huks_standard/huks_engine/main/os_dependency/BUILD.gn +++ b/services/huks_standard/huks_engine/main/os_dependency/BUILD.gn @@ -25,6 +25,11 @@ ohos_static_library("libhuks_engine_os_dependency_standard_static") { "//utils/native/base/include", "//utils/system/safwk/native/include", ] + defines = [ + "L2_STANDARD", + "_HARDWARE_ROOT_KEY_", + "_HUKS_LOG_ENABLE_", + ] sources = [] deps = [ "//base/security/huks/frameworks/huks_standard/main/common:libhuks_common_standard_static", diff --git a/services/huks_standard/huks_service/main/BUILD.gn b/services/huks_standard/huks_service/main/BUILD.gn index b071cb32..f172316d 100644 --- a/services/huks_standard/huks_service/main/BUILD.gn +++ b/services/huks_standard/huks_service/main/BUILD.gn @@ -16,6 +16,11 @@ import("//build/ohos.gni") ohos_static_library("libhuks_service_standard_static") { subsystem_name = "security" part_name = "huks_standard" + defines = [ + "L2_STANDARD", + "_HARDWARE_ROOT_KEY_", + "_HUKS_LOG_ENABLE_", + ] public_deps = [ "//base/security/huks/services/huks_standard/huks_service/main/core:libhuks_service_core_standard_static", "//base/security/huks/services/huks_standard/huks_service/main/os_dependency:libhuks_service_os_dependency_standard_static", diff --git a/services/huks_standard/huks_service/main/core/BUILD.gn b/services/huks_standard/huks_service/main/core/BUILD.gn index 6c51310e..100e44d6 100644 --- a/services/huks_standard/huks_service/main/core/BUILD.gn +++ b/services/huks_standard/huks_service/main/core/BUILD.gn @@ -25,6 +25,11 @@ ohos_static_library("libhuks_service_core_standard_static") { "//utils/native/base/include", "//third_party/openssl/include/", ] + defines = [ + "L2_STANDARD", + "_HARDWARE_ROOT_KEY_", + "_HUKS_LOG_ENABLE_", + ] sources = [ "src/hks_client_check.c", "src/hks_client_service.c", diff --git a/services/huks_standard/huks_service/main/core/include/hks_access.h b/services/huks_standard/huks_service/main/core/include/hks_access.h index f8456fca..d12e60df 100755 --- a/services/huks_standard/huks_service/main/core/include/hks_access.h +++ b/services/huks_standard/huks_service/main/core/include/hks_access.h @@ -16,7 +16,7 @@ #ifndef HKS_ACCESS_H #define HKS_ACCESS_H -#include "hks_type.h" +#include "hks_type_inner.h" #include "hks_cmd_id.h" #ifdef __cplusplus @@ -70,8 +70,13 @@ int32_t HksAccessInitialize(void); int32_t HksAccessRefresh(void); +int32_t HksAccessUpgradeKeyInfo(const struct HksBlob *keyAlias, const struct HksBlob *keyInfo, struct HksBlob *keyOut); + +int32_t HksAccessCalcHeaderMac(const struct HksParamSet *paramSet, const struct HksBlob *salt, + const struct HksBlob *srcData, struct HksBlob *mac); + #ifdef __cplusplus } #endif -#endif +#endif /* HKS_ACCESS_H */ diff --git a/services/huks_standard/huks_service/main/core/include/hks_client_check.h b/services/huks_standard/huks_service/main/core/include/hks_client_check.h index 992219c0..fc9576d7 100644 --- a/services/huks_standard/huks_service/main/core/include/hks_client_check.h +++ b/services/huks_standard/huks_service/main/core/include/hks_client_check.h @@ -16,7 +16,7 @@ #ifndef HKS_CLIENT_CHECK_H #define HKS_CLIENT_CHECK_H -#include "hks_type.h" +#include "hks_type_inner.h" #ifdef __cplusplus extern "C" { diff --git a/services/huks_standard/huks_service/main/core/include/hks_client_service.h b/services/huks_standard/huks_service/main/core/include/hks_client_service.h index b777805b..afc4907a 100755 --- a/services/huks_standard/huks_service/main/core/include/hks_client_service.h +++ b/services/huks_standard/huks_service/main/core/include/hks_client_service.h @@ -16,7 +16,8 @@ #ifndef HKS_CLIENT_SERVICE_H #define HKS_CLIENT_SERVICE_H -#include "hks_type.h" +#include "hks_type_inner.h" + #include "hks_param.h" #ifdef __cplusplus @@ -25,6 +26,8 @@ extern "C" { int32_t HksServiceInitialize(void); +int32_t HksServiceRefreshKeyInfo(const struct HksBlob *processName); + int32_t HksServiceProvision(const struct HksBlob *keybox, const struct HksBlob *challengeIn); int32_t HksServiceProvisionVerify(const struct HksBlob *srcData, const struct HksBlob *challengeIn); diff --git a/services/huks_standard/huks_service/main/core/include/hks_client_service_adapter.h b/services/huks_standard/huks_service/main/core/include/hks_client_service_adapter.h index 32f2a539..3cc74f40 100755 --- a/services/huks_standard/huks_service/main/core/include/hks_client_service_adapter.h +++ b/services/huks_standard/huks_service/main/core/include/hks_client_service_adapter.h @@ -16,7 +16,7 @@ #ifndef HKS_CLIENT_SERVICE_ADAPTER_H #define HKS_CLIENT_SERVICE_ADAPTER_H -#include "hks_type.h" +#include "hks_type_inner.h" #ifdef __cplusplus extern "C" { @@ -34,4 +34,4 @@ int32_t TranslateToInnerAesFormat(const struct HksBlob *key, struct HksBlob *out } #endif -#endif +#endif /* HKS_CLIENT_SERVICE_ADAPTER_H */ \ No newline at end of file diff --git a/services/huks_standard/huks_service/main/core/include/hks_file_operator.h b/services/huks_standard/huks_service/main/core/include/hks_file_operator.h index 81fc51e3..ab12439f 100755 --- a/services/huks_standard/huks_service/main/core/include/hks_file_operator.h +++ b/services/huks_standard/huks_service/main/core/include/hks_file_operator.h @@ -21,17 +21,33 @@ #define HKS_MAX_FILE_NAME_LEN 512 #ifdef _STORAGE_LITE_ -#define HKS_KEY_STORE_PATH "./hks_store/" + #define HKS_KEY_STORE_PATH "/storage/" #else -#define HKS_KEY_STORE_PATH "/data/data/maindata" -#define HKS_KEY_STORE_BAK_PATH "/data/data/bakdata" + #ifdef HKS_SUPPORT_PRODUCT_GT_WATCH + #define HKS_KEY_STORE_PATH "user/maindata" + #define HKS_KEY_STORE_BAK_PATH "user/bakdata" + #else + #ifdef L2_STANDARD + #define HKS_KEY_STORE_PATH "/data/data/maindata" + #define HKS_KEY_STORE_BAK_PATH "/data/data/bakdata" + #else + #define HKS_KEY_STORE_PATH "/storage/maindata" + #define HKS_KEY_STORE_BAK_PATH "/storage/bakdata" + #endif + #endif +#endif #define HKS_KEY_STORE_KEY_PATH "key" #define HKS_KEY_STORE_CERTCHAIN_PATH "certchain" #define HKS_KEY_STORE_ROOT_KEY_PATH "info" -#endif +#define HKS_MAX_DIRENT_FILE_LEN 128 struct HksFileDirentInfo { - char *fileName; /* point to dirent->d_name */ + char fileName[HKS_MAX_DIRENT_FILE_LEN]; /* point to dirent->d_name */ +}; + +enum HksStoragePathType { + HKS_STORAGE_MAIN_PATH, + HKS_STORAGE_BACKUP_PATH, }; #ifdef __cplusplus @@ -48,6 +64,8 @@ uint32_t HksFileSize(const char *path, const char *fileName); int32_t HksIsFileExist(const char *path, const char *fileName); +int32_t HksIsDirExist(const char *path); + int32_t HksMakeDir(const char *path); void *HksOpenDir(const char *path); @@ -58,8 +76,21 @@ int32_t HksGetDirFile(void *dirp, struct HksFileDirentInfo *direntInfo); int32_t HksRemoveDir(const char *dirPath); +/* return < 0 error; > 0 realFileSize; == 0 no data */ +int32_t HksOldVersionFileRead(const char *fileName, uint32_t offset, uint8_t *buf, uint32_t len); + +int32_t HksOldVersionFileRemove(const char *fileName); + +/* return < 0 error; >= 0 realFileSize */ +int32_t HksOldVersionFileSize(const char *fileName); + +/* return true, exist; false not exist */ +bool HksOldVersionIsFileExist(const char *fileName); + +int32_t HksGetStoragePath(enum HksStoragePathType pathType, char *path, uint32_t *len); + #ifdef __cplusplus } #endif -#endif +#endif /* HKS_FILE_OPERATOR_H */ \ No newline at end of file diff --git a/services/huks_standard/huks_service/main/core/include/hks_operation.h b/services/huks_standard/huks_service/main/core/include/hks_operation.h index d63b2c4b..bc90ee0f 100644 --- a/services/huks_standard/huks_service/main/core/include/hks_operation.h +++ b/services/huks_standard/huks_service/main/core/include/hks_operation.h @@ -19,7 +19,8 @@ #include #include -#include "hks_type.h" +#include "hks_type_inner.h" + #include "hks_double_list.h" struct HksOperation { diff --git a/services/huks_standard/huks_service/main/core/include/hks_storage.h b/services/huks_standard/huks_service/main/core/include/hks_storage.h index 8031ea4b..66ac4a56 100644 --- a/services/huks_standard/huks_service/main/core/include/hks_storage.h +++ b/services/huks_standard/huks_service/main/core/include/hks_storage.h @@ -16,7 +16,7 @@ #ifndef HKS_STORAGE_H #define HKS_STORAGE_H -#include "hks_type.h" +#include "hks_type_inner.h" enum HksStorageType { HKS_STORAGE_TYPE_KEY = 0, @@ -49,8 +49,22 @@ int32_t HksGetKeyAliasByProcessName(const struct HksBlob *processName, struct Hk int32_t HksStoreDestory(const struct HksBlob *processName); +#ifdef _STORAGE_LITE_ + +#define HKS_KEY_STORE_FILE_NAME "hks_keystore" + +int32_t HksLoadFileToBuffer(void); + +int32_t HksFileBufferRefresh(void); + +int32_t HksStoreGetToatalSize(uint32_t *size); + +int32_t HksStoreGetKeyInfoList(struct HksKeyInfo *keyInfoList, uint32_t *listCount); + +#endif /* _STORAGE_LITE_ */ + #ifdef __cplusplus } #endif -#endif +#endif /* HKS_STORAGE_H */ \ No newline at end of file diff --git a/services/huks_standard/huks_service/main/core/include/hks_storage_adapter.h b/services/huks_standard/huks_service/main/core/include/hks_storage_adapter.h new file mode 100644 index 00000000..f7bb362d --- /dev/null +++ b/services/huks_standard/huks_service/main/core/include/hks_storage_adapter.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_STORAGE_ADAPTER_H +#define HKS_STORAGE_ADAPTER_H + +#ifdef _STORAGE_LITE_ + +#include "hks_type_inner.h" + +#ifdef __cplusplus +extern "C" { +#endif + +bool HksIsKeyInfoLenInvalid(struct HksStoreKeyInfo *keyInfo); + +int32_t TranslateKeyInfoBlobToParamSet(const struct HksBlob *key, const struct HksBlob *keyInfoBlob, + struct HksParamSet **paramSet); + +#ifdef __cplusplus +} +#endif + +#endif /* _STORAGE_LITE_ */ + +#endif /* HKS_STORAGE_ADAPTER_H */ \ No newline at end of file diff --git a/services/huks_standard/huks_service/main/core/include/hks_upgrade_storage_data.h b/services/huks_standard/huks_service/main/core/include/hks_upgrade_storage_data.h new file mode 100644 index 00000000..08db5a44 --- /dev/null +++ b/services/huks_standard/huks_service/main/core/include/hks_upgrade_storage_data.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_UPGRADE_STORAGE_DATA_H +#define HKS_UPGRADE_STORAGE_DATA_H + +#include "hks_type_inner.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t HksUpgradeStorageData(void); + +int32_t HksDestroyOldVersionFiles(void); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_UPGRADE_STORAGE_DATA_H */ diff --git a/services/huks_standard/huks_service/main/core/src/hks_client_check.c b/services/huks_standard/huks_service/main/core/src/hks_client_check.c index c47339d3..06adaf57 100644 --- a/services/huks_standard/huks_service/main/core/src/hks_client_check.c +++ b/services/huks_standard/huks_service/main/core/src/hks_client_check.c @@ -18,6 +18,7 @@ #include "hks_common_check.h" #include "hks_log.h" +#ifndef _CUT_AUTHENTICATE_ static int32_t CheckProcessNameAndKeyAliasSize(uint32_t processNameSize, uint32_t keyAliasSize) { if (processNameSize > HKS_MAX_PROCESS_NAME_LEN) { @@ -79,25 +80,6 @@ int32_t HksCheckGetKeyParamSetParams(const struct HksBlob *processName, const st return HKS_SUCCESS; } -int32_t HksCheckGenerateRandomParams(const struct HksBlob *processName, const struct HksBlob *random) -{ - if (HksCheckBlob2(processName, random) != HKS_SUCCESS) { - return HKS_ERROR_INVALID_ARGUMENT; - } - - if (processName->size > HKS_MAX_PROCESS_NAME_LEN) { - HKS_LOG_E("processName size too long, size %u.", processName->size); - return HKS_ERROR_INVALID_ARGUMENT; - } - - if (random->size > HKS_MAX_RANDOM_LEN) { - HKS_LOG_E("random size too long, size %u.", random->size); - return HKS_ERROR_INVALID_ARGUMENT; - } - - return HKS_SUCCESS; -} - int32_t HksCheckExportPublicKeyParams(const struct HksBlob *processName, const struct HksBlob *keyAlias, const struct HksBlob *key) { @@ -161,4 +143,25 @@ int32_t HksCheckInitParams(const struct HksBlob *processName, const struct HksBl } return HKS_SUCCESS; -} \ No newline at end of file +} +#endif /* _CUT_AUTHENTICATE_ */ + +int32_t HksCheckGenerateRandomParams(const struct HksBlob *processName, const struct HksBlob *random) +{ + if (HksCheckBlob2(processName, random) != HKS_SUCCESS) { + return HKS_ERROR_INVALID_ARGUMENT; + } + + if (processName->size > HKS_MAX_PROCESS_NAME_LEN) { + HKS_LOG_E("processName size too long, size %u.", processName->size); + return HKS_ERROR_INVALID_ARGUMENT; + } + + if (random->size > HKS_MAX_RANDOM_LEN) { + HKS_LOG_E("random size too long, size %u.", random->size); + return HKS_ERROR_INVALID_ARGUMENT; + } + + return HKS_SUCCESS; +} + diff --git a/services/huks_standard/huks_service/main/core/src/hks_client_service.c b/services/huks_standard/huks_service/main/core/src/hks_client_service.c index fd6dd350..4e4de694 100755 --- a/services/huks_standard/huks_service/main/core/src/hks_client_service.c +++ b/services/huks_standard/huks_service/main/core/src/hks_client_service.c @@ -13,27 +13,98 @@ * limitations under the License. */ +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + #include "hks_client_service.h" #include "hks_access.h" #include "hks_client_check.h" #include "hks_client_service_adapter.h" - -#ifdef HKS_HAL_ENGINE_CONFIG_FILE -#include HKS_HAL_ENGINE_CONFIG_FILE -#else -#include "hks_crypto_hal_config.h" -#endif - #include "hks_log.h" #include "hks_mem.h" #include "hks_operation.h" #include "hks_storage.h" +#ifdef _STORAGE_LITE_ +#include "hks_storage_adapter.h" +#endif + +#ifdef HKS_SUPPORT_UPGRADE_STORAGE_DATA +#include "hks_upgrade_storage_data.h" +#endif #define MAX_KEY_COUNT 256 -#define AGREE_KEY_MAX_SIZE 1024 #define MAX_STORAGE_SIZE (2 * 1024 * 1024) +#ifndef _CUT_AUTHENTICATE_ +#ifdef _STORAGE_LITE_ +static int32_t GetKeyData(const struct HksBlob *processName, const struct HksBlob *keyAlias, + struct HksBlob *key, int32_t mode) +{ + int32_t ret = HksStoreGetKeyBlob(processName, keyAlias, mode, key); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get key blob from storage failed, ret = %d", ret); + } + return ret; +} + +static int32_t CheckKeyCondition(const struct HksBlob *processName, const struct HksBlob *keyAlias) +{ + /* check is enough buffer to store */ + uint32_t size = 0; + int32_t ret = HksStoreGetToatalSize(&size); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get total size from storage failed, ret = %d", ret); + return ret; + } + + if (size >= MAX_STORAGE_SIZE) { + /* is key exist */ + ret = HksStoreIsKeyBlobExist(processName, keyAlias, HKS_STORAGE_TYPE_KEY); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("buffer exceeds limit"); + return HKS_ERROR_STORAGE_FAILURE; + } + } + + return HKS_SUCCESS; +} + +static int32_t GetKeyParamSet(const struct HksBlob *key, struct HksParamSet *paramSet) +{ + struct HksParamSet *tmpParamSet = NULL; + int32_t ret = TranslateKeyInfoBlobToParamSet(NULL, key, &tmpParamSet); + if (ret != HKS_SUCCESS) { + return ret; + } + + if (paramSet->paramSetSize < tmpParamSet->paramSetSize) { + HksFreeParamSet(&tmpParamSet); + return HKS_ERROR_BUFFER_TOO_SMALL; + } + if (memcpy_s(paramSet, paramSet->paramSetSize, tmpParamSet, tmpParamSet->paramSetSize) != EOK) { + HKS_LOG_E("memcpy paramSet failed"); + ret = HKS_ERROR_BAD_STATE; + } + + HksFreeParamSet(&tmpParamSet); + return ret; +} + +int32_t HksServiceGetKeyInfoList(const struct HksBlob *processName, struct HksKeyInfo *keyInfoList, + uint32_t *listCount) +{ + int32_t ret = HksCheckGetKeyInfoListParams(processName, keyInfoList, listCount); + if (ret != HKS_SUCCESS) { + return ret; + } + + return HksStoreGetKeyInfoList(keyInfoList, listCount); +} +#else static int32_t GetKeyData(const struct HksBlob *processName, const struct HksBlob *keyAlias, struct HksBlob *key, int32_t mode) { @@ -228,6 +299,8 @@ int32_t HksServiceGetKeyInfoList(const struct HksBlob *processName, struct HksKe return ret; } +#endif +#endif /* _CUT_AUTHENTICATE_ */ static int32_t AppendToNewParamSet(const struct HksParamSet *paramSet, struct HksParamSet **outParamSet) { @@ -309,6 +382,7 @@ static int32_t AppendProcessNameTag(const struct HksParamSet *paramSet, const st return ret; } +#ifndef _CUT_AUTHENTICATE_ static int32_t GetKeyAndNewParamSet(const struct HksBlob *processName, const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, struct HksBlob *key, struct HksParamSet **outParamSet) { @@ -358,7 +432,7 @@ static int32_t GetHksInnerKeyFormat(const struct HksParamSet *paramSet, const st } } -#if defined(HKS_SUPPORT_X25519_C) || defined(HKS_SUPPORT_ED25519_C) +#ifdef HKS_SUPPORT_ED25519_TO_X25519 static int32_t GetAgreeStoreKey(uint32_t keyAliasTag, const struct HksBlob *processName, const struct HksParamSet *paramSet, struct HksBlob *key) { @@ -374,7 +448,7 @@ static int32_t GetAgreeStoreKey(uint32_t keyAliasTag, const struct HksBlob *proc return HKS_ERROR_INVALID_ARGUMENT; } - return GetKeyData(processName, &keyAliasParam->blob, key, HKS_STORAGE_TYPE_KEY); + return GetKeyData(processName, &(keyAliasParam->blob), key, HKS_STORAGE_TYPE_KEY); } static int32_t GetAgreePublicKey(const uint32_t alg, const struct HksBlob *processName, @@ -382,7 +456,7 @@ static int32_t GetAgreePublicKey(const uint32_t alg, const struct HksBlob *proce { struct HksParam *isKeyAliasParam = NULL; int32_t ret = HksGetParam(paramSet, HKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS, &isKeyAliasParam); - if ((ret == HKS_SUCCESS) && (isKeyAliasParam->boolParam == false)) { + if ((ret == HKS_SUCCESS) && (!(isKeyAliasParam->boolParam))) { struct HksParam *keyParam = NULL; ret = HksGetParam(paramSet, HKS_TAG_AGREE_PUBLIC_KEY, &keyParam); if (ret != HKS_SUCCESS) { @@ -467,6 +541,8 @@ static int32_t GetAgreeKeyPair(const uint32_t alg, const struct HksBlob *process static int32_t GetAgreeBaseKey(const struct HksBlob *processName, const struct HksParamSet *paramSet, struct HksBlob *key) { + (void)key; + (void)processName; struct HksParam *keyAlgParam = NULL; int32_t ret = HksGetParam(paramSet, HKS_TAG_ALGORITHM, &keyAlgParam); if (ret != HKS_SUCCESS) { @@ -479,7 +555,7 @@ static int32_t GetAgreeBaseKey(const struct HksBlob *processName, const struct H return HKS_SUCCESS; } -#if defined(HKS_SUPPORT_X25519_C) || defined(HKS_SUPPORT_ED25519_C) +#ifdef HKS_SUPPORT_ED25519_TO_X25519 struct HksParam *agreeAlgParam = NULL; ret = HksGetParam(paramSet, HKS_TAG_AGREE_ALG, &agreeAlgParam); if (ret != HKS_SUCCESS) { @@ -502,8 +578,7 @@ static int32_t GetDeriveMainKey(const struct HksBlob *processName, const struct struct HksParam *keyGenTypeParam = NULL; int32_t ret = HksGetParam(paramSet, HKS_TAG_KEY_GENERATE_TYPE, &keyGenTypeParam); if (ret != HKS_SUCCESS) { - HKS_LOG_I("KEY_GENERATE_TYPE has not been set, generate a key of the default type"); - return HKS_SUCCESS; + return HKS_SUCCESS; /* not set tag KEY_GENERATE_TYPE, gen key by default type */ } if (keyGenTypeParam->uint32Param == HKS_KEY_GENERATE_TYPE_AGREE) { @@ -514,6 +589,27 @@ static int32_t GetDeriveMainKey(const struct HksBlob *processName, const struct return HKS_ERROR_INVALID_ARGUMENT; } +static int32_t GetKeyIn(const struct HksBlob *processName, const struct HksParamSet *paramSet, + struct HksBlob *key) +{ + int32_t ret = GetDeriveMainKey(processName, paramSet, key); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* if not generate by derive, init keyIn by default value(ca to ta not accept null pointer) */ + if (key->data == NULL) { + key->size = 1; /* malloc least buffer as keyIn buffer */ + key->data = (uint8_t *)HksMalloc(key->size); + if (key->data == NULL) { + HKS_LOG_E("malloc failed"); + return HKS_ERROR_MALLOC_FAIL; + } + key->data[0] = 0; + } + return HKS_SUCCESS; +} + int32_t HksServiceGenerateKey(const struct HksBlob *processName, const struct HksBlob *keyAlias, const struct HksParamSet *paramSetIn, struct HksBlob *keyOut) { @@ -550,9 +646,9 @@ int32_t HksServiceGenerateKey(const struct HksBlob *processName, const struct Hk break; } - ret = GetDeriveMainKey(processName, newParamSet, &keyIn); + ret = GetKeyIn(processName, newParamSet, &keyIn); if (ret != HKS_SUCCESS) { - HKS_LOG_E("get derive main key failed, ret = %d", ret); + HKS_LOG_E("get keyIn failed, ret = %d", ret); break; } @@ -612,7 +708,7 @@ int32_t HksServiceVerify(const struct HksBlob *processName, const struct HksBlob do { ret = HksCheckAllParams(processName, keyAlias, paramSet, srcData, signature); if (ret != HKS_SUCCESS) { - HKS_LOG_E("check verify params failed,, ret = %d", ret); + HKS_LOG_E("check verify params failed, ret = %d", ret); break; } @@ -758,31 +854,6 @@ int32_t HksServiceGetKeyParamSet(const struct HksBlob *processName, const struct return ret; } -int32_t HksServiceGenerateRandom(const struct HksBlob *processName, struct HksBlob *random) -{ - int32_t ret; - struct HksParamSet *newParamSet = NULL; - - do { - ret = HksCheckGenerateRandomParams(processName, random); - if (ret != HKS_SUCCESS) { - HKS_LOG_E("check generate random params failed, ret = %d", ret); - break; - } - - ret = AppendProcessNameTag(NULL, processName, &newParamSet); - if (ret != HKS_SUCCESS) { - HKS_LOG_E("append processName tag failed, ret = %d", ret); - break; - } - - ret = HksAccessGenerateRandom(newParamSet, random); - } while (0); - - HksFreeParamSet(&newParamSet); - return ret; -} - int32_t HksServiceImportKey(const struct HksBlob *processName, const struct HksBlob *keyAlias, const struct HksParamSet *paramSet, const struct HksBlob *x509Key) { @@ -988,19 +1059,59 @@ int32_t HksServiceMac(const struct HksBlob *processName, const struct HksBlob *k int32_t HksServiceInitialize(void) { - int32_t ret; -#ifdef _STORAGE_LITE_ - ret = HksLoadFileToBuffer(HKS_KEY_STORE_FILE_NAME); + int32_t ret = HKS_SUCCESS; + +#ifdef HKS_SUPPORT_UPGRADE_STORAGE_DATA + ret = HksUpgradeStorageData(); if (ret != HKS_SUCCESS) { - HKS_LOG_E("load file to buffer failed, ret = %d", ret); + HKS_LOG_E("hks update storage data failed, ret = %d", ret); + return ret; } -#else +#endif + +#ifndef _HARDWARE_ROOT_KEY_ ret = HksAccessInitialize(); if (ret != HKS_SUCCESS) { HKS_LOG_E("hks core service initialize failed! ret = %d", ret); return ret; } #endif + +#ifdef _STORAGE_LITE_ + ret = HksLoadFileToBuffer(); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("load file to buffer failed, ret = %d", ret); + return ret; + } +#endif + return ret; +} + +int32_t HksServiceRefreshKeyInfo(const struct HksBlob *processName) +{ + int32_t ret = HksStoreDestory(processName); + HKS_LOG_I("destroy storage files ret = 0x%X", ret); /* only recode log */ + +#ifdef HKS_SUPPORT_UPGRADE_STORAGE_DATA + ret = HksDestroyOldVersionFiles(); + HKS_LOG_I("destroy old version files ret = 0x%X", ret); /* only recode log */ +#endif + +#ifndef _HARDWARE_ROOT_KEY_ + ret = HksAccessRefresh(); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Hks core service refresh info failed! ret = 0x%X", ret); + return ret; + } +#endif + +#ifdef _STORAGE_LITE_ + ret = HksFileBufferRefresh(); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("load file to buffer failed, ret = %d", ret); + return ret; + } +#endif return ret; } @@ -1144,4 +1255,30 @@ int32_t HksServiceExportTrustCerts(const struct HksBlob *processName, struct Hks { return 0; } +#endif + +int32_t HksServiceGenerateRandom(const struct HksBlob *processName, struct HksBlob *random) +{ + int32_t ret; + struct HksParamSet *newParamSet = NULL; + + do { + ret = HksCheckGenerateRandomParams(processName, random); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("check generate random params failed, ret = %d", ret); + break; + } + + ret = AppendProcessNameTag(NULL, processName, &newParamSet); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("append processName tag failed, ret = %d", ret); + break; + } + + ret = HksAccessGenerateRandom(newParamSet, random); + } while (0); + + HksFreeParamSet(&newParamSet); + return ret; +} diff --git a/services/huks_standard/huks_service/main/core/src/hks_client_service_adapter.c b/services/huks_standard/huks_service/main/core/src/hks_client_service_adapter.c index 93cc41b7..55caad99 100755 --- a/services/huks_standard/huks_service/main/core/src/hks_client_service_adapter.c +++ b/services/huks_standard/huks_service/main/core/src/hks_client_service_adapter.c @@ -13,6 +13,12 @@ * limitations under the License. */ +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + #include "hks_client_service_adapter.h" #include @@ -22,12 +28,6 @@ #include #include -#ifdef HKS_HAL_ENGINE_CONFIG_FILE -#include HKS_HAL_ENGINE_CONFIG_FILE -#else -#include "hks_crypto_hal_config.h" -#endif - #include "hks_log.h" #include "hks_mem.h" diff --git a/services/huks_standard/huks_service/main/core/src/hks_client_service_adapter_lite.c b/services/huks_standard/huks_service/main/core/src/hks_client_service_adapter_lite.c new file mode 100644 index 00000000..4b8eb3ba --- /dev/null +++ b/services/huks_standard/huks_service/main/core/src/hks_client_service_adapter_lite.c @@ -0,0 +1,506 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#include "hks_client_service_adapter.h" + +#include +#include +#include +#include + +#include "hks_log.h" +#include "hks_mbedtls_common.h" +#include "hks_mbedtls_ecc.h" +#include "hks_mem.h" + +#ifdef _CUT_AUTHENTICATE_ +#undef HKS_SUPPORT_HASH_C +#undef HKS_SUPPORT_RSA_C +#undef HKS_SUPPORT_ECC_C +#undef HKS_SUPPORT_X25519_C +#undef HKS_SUPPORT_ED25519_C +#undef HKS_SUPPORT_KDF_PBKDF2 +#endif /* _CUT_AUTHENTICATE_ */ + +#if defined(HKS_SUPPORT_RSA_C) || defined(HKS_SUPPORT_ECC_C) +static int32_t PkCtxToX509(mbedtls_pk_context *ctx, struct HksBlob *x509Key) +{ + uint8_t *tmpBuf = (uint8_t *)HksMalloc(MAX_KEY_SIZE); + if (tmpBuf == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + + int32_t ret = HKS_SUCCESS; + do { + int32_t x509Size = mbedtls_pk_write_pubkey_der(ctx, tmpBuf, MAX_KEY_SIZE); + if (x509Size < HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("public key to x509 write der failed! mbedtls ret = 0x%X", x509Size); + ret = x509Size; + break; + } + + uint8_t *x509KeyData = (uint8_t *)HksMalloc(x509Size); + if (x509KeyData == NULL) { + HKS_LOG_E("Malloc x509 key data failed!"); + ret = HKS_ERROR_MALLOC_FAIL; + break; + } + + /* mbedtls_pk_write_pubkey_der use little-endian for storage */ + if (memcpy_s(x509KeyData, x509Size, tmpBuf + MAX_KEY_SIZE - x509Size, x509Size) != EOK) { + HKS_LOG_E("public key to x509 memcpy to x509key failed!"); + HKS_FREE_PTR(x509KeyData); + ret = HKS_ERROR_BAD_STATE; + break; + } + + x509Key->size = x509Size; + x509Key->data = x509KeyData; + } while (0); + + HKS_FREE_PTR(tmpBuf); + return ret; +} + +#ifdef HKS_SUPPORT_RSA_C +static int32_t InitRsaPkCtx(const struct HksBlob *mod, const struct HksBlob *e, mbedtls_pk_context *ctx) +{ + int32_t ret = mbedtls_pk_setup(ctx, mbedtls_pk_info_from_type(MBEDTLS_PK_RSA)); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls setup pk context failed! mbedtls ret = 0x%X", ret); + return ret; + } + + mbedtls_mpi mpiN; + mbedtls_mpi mpiE; + + mbedtls_mpi_init(&mpiN); + mbedtls_mpi_init(&mpiE); + + do { + ret = mbedtls_mpi_read_binary(&mpiN, mod->data, mod->size); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Hks init rsa pk context read N failed! mbedtls ret = 0x%X", ret); + break; + } + + ret = mbedtls_mpi_read_binary(&mpiE, e->data, e->size); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Hks init rsa pk context read E failed! mbedtls ret = 0x%X", ret); + break; + } + + mbedtls_rsa_context *rsaCtx = mbedtls_pk_rsa(*ctx); + ret = mbedtls_rsa_import(rsaCtx, &mpiN, NULL, NULL, NULL, &mpiE); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Hks init rsa pk context import rsa context failed! mbedtls ret = 0x%X", ret); + break; + } + + ret = mbedtls_rsa_complete(rsaCtx); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Hks init rsa pk context complete rsa context failed! mbedtls ret = 0x%X", ret); + } + } while (0); + + mbedtls_mpi_free(&mpiN); + mbedtls_mpi_free(&mpiE); + return ret; +} + +static int32_t RsaToX509PublicKey(const struct HksBlob *mod, const struct HksBlob *e, struct HksBlob *x509Key) +{ + mbedtls_pk_context ctx; + mbedtls_pk_init(&ctx); + + int32_t ret; + do { + ret = InitRsaPkCtx(mod, e, &ctx); + if (ret != HKS_SUCCESS) { + break; + } + + ret = PkCtxToX509(&ctx, x509Key); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Pk context to rsa x509 failed! ret = 0x%X", ret); + } + } while (0); + + mbedtls_pk_free(&ctx); + return ret; +} +#endif + +#ifdef HKS_SUPPORT_ECC_C +static int32_t InitEccPkCtx(uint32_t keySize, const struct HksBlob *x, const struct HksBlob *y, + mbedtls_pk_context *ctx) +{ + int32_t ret = mbedtls_pk_setup(ctx, mbedtls_pk_info_from_type(MBEDTLS_PK_ECKEY)); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Mbedtls setup pk context failed! mbedtls ret = 0x%X", ret); + return ret; + } + + mbedtls_ecp_group_id grp_id; + ret = GetEccGroupId(keySize, &grp_id); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Get ecc group id failed! ret = 0x%X", ret); + return ret; + } + + mbedtls_ecp_keypair *pubKey = mbedtls_pk_ec(*ctx); + ret = mbedtls_ecp_group_load(&(pubKey->grp), grp_id); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Hks init ecc pk context load group failed! mbedtls ret = 0x%X", ret); + return ret; + } + + ret = mbedtls_mpi_read_binary(&(pubKey->Q.X), x->data, x->size); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Hks init ecc pk context read X failed! mbedtls ret = 0x%X", ret); + return ret; + } + + ret = mbedtls_mpi_read_binary(&(pubKey->Q.Y), y->data, y->size); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Hks init ecc pk context read Y failed! mbedtls ret = 0x%X", ret); + return ret; + } + + /* Z = 1, X and Y are its standard (affine) coordinates */ + ret = mbedtls_mpi_lset(&(pubKey->Q.Z), 1); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("Hks init ecc pk context set Z failed! mbedtls ret = 0x%X", ret); + return ret; + } + + return HKS_SUCCESS; +} + +static int32_t EccToX509PublicKey(uint32_t keySize, const struct HksBlob *x, const struct HksBlob *y, + struct HksBlob *x509Key) +{ + mbedtls_pk_context ctx; + mbedtls_pk_init(&ctx); + + int32_t ret; + do { + ret = InitEccPkCtx(keySize, x, y, &ctx); + if (ret != HKS_SUCCESS) { + break; + } + + ret = PkCtxToX509(&ctx, x509Key); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Pk context to ecc x509 failed! ret = 0x%X", ret); + } + } while (0); + + mbedtls_pk_free(&ctx); + return ret; +} +#endif +#endif + +#if defined(HKS_SUPPORT_X25519_C) || defined(HKS_SUPPORT_ED25519_C) +static int32_t Curve25519ToX509PublicKey(const struct HksBlob *publicKey, struct HksBlob *x509Key) +{ + if (publicKey->size != HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256)) { + HKS_LOG_E("Invalid public key size! key size = 0x%X", publicKey->size); + return HKS_ERROR_INVALID_ARGUMENT; + } + + x509Key->data = (uint8_t *)HksMalloc(publicKey->size); + if (x509Key->data == NULL) { + HKS_LOG_E("X25519/Ed25519 to x509 public key malloc x509 key data failed!"); + return HKS_ERROR_MALLOC_FAIL; + } + + if (memcpy_s(x509Key->data, publicKey->size, publicKey->data, publicKey->size) != EOK) { + HKS_LOG_E("X25519/Ed25519 to x509 public key memcpy to x509 key data failed!"); + HKS_FREE_PTR(x509Key->data); + return HKS_ERROR_BAD_STATE; + } + x509Key->size = publicKey->size; + + return HKS_SUCCESS; +} +#endif + +int32_t TranslateToX509PublicKey(const struct HksBlob *publicKey, struct HksBlob *x509Key) +{ +#if defined(HKS_SUPPORT_RSA_C) || defined(HKS_SUPPORT_ECC_C) || defined(HKS_SUPPORT_X25519_C) || \ + defined(HKS_SUPPORT_ED25519_C) + if ((publicKey == NULL) || (publicKey->data == NULL) || (publicKey->size == 0) || (x509Key == NULL)) { + HKS_LOG_E("translate to x509 public key invalid args"); + return HKS_ERROR_INVALID_ARGUMENT; + } + + if (publicKey->size < sizeof(struct HksPubKeyInfo)) { + HKS_LOG_E("translate to x509 public key invalid publicKey size"); + return HKS_ERROR_INVALID_ARGUMENT; + } + + struct HksPubKeyInfo *publicKeyInfo = (struct HksPubKeyInfo *)publicKey->data; + uint32_t offset = sizeof(struct HksPubKeyInfo); + if ((publicKey->size - offset) < publicKeyInfo->nOrXSize) { + HKS_LOG_E("translate to x509 public key invalid nOrXSize size"); + return HKS_ERROR_INVALID_ARGUMENT; + } + + struct HksBlob material1 = { publicKeyInfo->nOrXSize, publicKey->data + offset }; + offset += publicKeyInfo->nOrXSize; + if ((publicKey->size - offset) < publicKeyInfo->eOrYSize) { + HKS_LOG_E("translate to x509 public key invalid eOrYSize size"); + return HKS_ERROR_INVALID_ARGUMENT; + } + +#if defined(HKS_SUPPORT_RSA_C) || defined(HKS_SUPPORT_ECC_C) + struct HksBlob material2 = { publicKeyInfo->eOrYSize, publicKey->data + offset }; +#endif + switch (publicKeyInfo->keyAlg) { +#ifdef HKS_SUPPORT_RSA_C + case HKS_ALG_RSA: + return RsaToX509PublicKey(&material1, &material2, x509Key); +#endif +#ifdef HKS_SUPPORT_ECC_C + case HKS_ALG_ECC: + return EccToX509PublicKey(publicKeyInfo->keySize, &material1, &material2, x509Key); +#endif +#if defined(HKS_SUPPORT_X25519_C) || defined(HKS_SUPPORT_ED25519_C) + case HKS_ALG_X25519: + case HKS_ALG_ED25519: + return Curve25519ToX509PublicKey(&material1, x509Key); +#endif + default: + HKS_LOG_E("Unsupport alg type! type = 0x%X", publicKeyInfo->keyAlg); + return HKS_ERROR_INVALID_ARGUMENT; + } +#else + (void)publicKey; + (void)x509Key; + return HKS_ERROR_NOT_SUPPORTED; +#endif +} + +#if defined(HKS_SUPPORT_RSA_C) || defined(HKS_SUPPORT_ECC_C) +#ifdef HKS_SUPPORT_RSA_C +static int32_t CheckRsaCtx(const mbedtls_rsa_context *rsaCtx) +{ + uint32_t maxKeyByteLen = HKS_RSA_KEY_SIZE_4096 / HKS_BITS_PER_BYTE; + if (rsaCtx->len > maxKeyByteLen) { + HKS_LOG_E("Invalid mbedtls rsa context's len! len = 0x%X", rsaCtx->len); + return HKS_ERROR_INVALID_ARGUMENT; + } + + return HKS_SUCCESS; +} + +static int32_t X509PublicKeyToRsa(mbedtls_rsa_context *rsaCtx, struct HksBlob *rsaPublicKey) +{ + int32_t ret = CheckRsaCtx(rsaCtx); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Check rsa ctx failed! ret = 0x%X", ret); + return ret; + } + + uint32_t nSize = rsaCtx->len; + uint32_t eSize = rsaCtx->len; + + uint32_t totalSize = sizeof(struct HksPubKeyInfo) + nSize + eSize; + uint8_t *keyBuffer = (uint8_t *)HksMalloc(totalSize); + if (keyBuffer == NULL) { + HKS_LOG_E("X509 public key to rsa malloc keyBuffer failed!"); + return HKS_ERROR_MALLOC_FAIL; + } + + struct HksPubKeyInfo *pubKeyInfo = (struct HksPubKeyInfo *)keyBuffer; + pubKeyInfo->keyAlg = HKS_ALG_RSA; + pubKeyInfo->keySize = rsaCtx->len * HKS_BITS_PER_BYTE; + pubKeyInfo->nOrXSize = nSize; + pubKeyInfo->eOrYSize = eSize; + pubKeyInfo->placeHolder = 0; + + ret = mbedtls_mpi_write_binary(&rsaCtx->N, keyBuffer + sizeof(struct HksPubKeyInfo), nSize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("X509 public key to rsa write N failed! mbedtls ret = 0x%X", ret); + HKS_FREE_PTR(keyBuffer); + return ret; + } + + ret = mbedtls_mpi_write_binary(&rsaCtx->E, keyBuffer + sizeof(struct HksPubKeyInfo) + nSize, eSize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("X509 public key to rsa write E failed! mbedtls ret = 0x%X", ret); + HKS_FREE_PTR(keyBuffer); + return ret; + } + + rsaPublicKey->data = keyBuffer; + rsaPublicKey->size = totalSize; + + return HKS_SUCCESS; +} +#endif + +#ifdef HKS_SUPPORT_ECC_C +static int32_t CheckEccXySize(const uint32_t xSize, const uint32_t ySize) +{ + uint32_t maxKeyByteLen = HKS_ECC_KEY_SIZE_521 / HKS_BITS_PER_BYTE; + if ((xSize > maxKeyByteLen) || (ySize > maxKeyByteLen)) { + HKS_LOG_E("Invalid ecc public key size! xSize = 0x%X, ySize = 0x%X", xSize, ySize); + return HKS_ERROR_INVALID_ARGUMENT; + } + + return HKS_SUCCESS; +} + +static int32_t X509PublicKeyToEcc(mbedtls_ecp_keypair *pubKey, struct HksBlob *eccPublicKey) +{ + uint32_t xSize = mbedtls_mpi_size(&(pubKey->Q.X)); + uint32_t ySize = mbedtls_mpi_size(&(pubKey->Q.Y)); + + int32_t ret = CheckEccXySize(xSize, ySize); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("Check ecc public key size failed! ret = 0x%X", ret); + return ret; + } + + uint32_t totalSize = sizeof(struct HksPubKeyInfo) + xSize + ySize; + uint8_t *keyBuffer = (uint8_t *)HksMalloc(totalSize); + if (keyBuffer == NULL) { + HKS_LOG_E("X509 public key to ecc malloc keyBuffer failed!"); + return HKS_ERROR_MALLOC_FAIL; + } + + struct HksPubKeyInfo *pubKeyInfo = (struct HksPubKeyInfo *)keyBuffer; + pubKeyInfo->keyAlg = HKS_ALG_ECC; + pubKeyInfo->keySize = mbedtls_mpi_size(&(pubKey->grp.P)) * HKS_BITS_PER_BYTE; + pubKeyInfo->nOrXSize = xSize; + pubKeyInfo->eOrYSize = ySize; + pubKeyInfo->placeHolder = 0; + + ret = mbedtls_mpi_write_binary(&(pubKey->Q.X), keyBuffer + sizeof(struct HksPubKeyInfo), xSize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("X509 public key to ecc write X failed! mbedtls ret = 0x%X", ret); + HKS_FREE_PTR(keyBuffer); + return ret; + } + + ret = mbedtls_mpi_write_binary(&(pubKey->Q.Y), keyBuffer + sizeof(struct HksPubKeyInfo) + xSize, ySize); + if (ret != HKS_MBEDTLS_SUCCESS) { + HKS_LOG_E("X509 public key to ecc write Y failed! mbedtls ret = 0x%X", ret); + HKS_FREE_PTR(keyBuffer); + return ret; + } + + eccPublicKey->data = keyBuffer; + eccPublicKey->size = totalSize; + + return HKS_SUCCESS; +} +#endif +int32_t TranslateFromX509PublicKey(const struct HksBlob *x509Key, struct HksBlob *publicKey) +{ + mbedtls_pk_context ctx; + mbedtls_pk_init(&ctx); + + int32_t ret = mbedtls_pk_parse_public_key(&ctx, x509Key->data, x509Key->size); + if (ret != HKS_MBEDTLS_SUCCESS) { + mbedtls_pk_free(&ctx); + return HKS_ERROR_INVALID_ARGUMENT; + } + + /* 1: if the context can do operations on the given type. */ + if (mbedtls_pk_can_do(&ctx, MBEDTLS_PK_RSA) == 1) { +#ifdef HKS_SUPPORT_RSA_C + ret = X509PublicKeyToRsa(mbedtls_pk_rsa(ctx), publicKey); +#else + ret = HKS_ERROR_INVALID_ALGORITHM; +#endif + } else if (mbedtls_pk_can_do(&ctx, MBEDTLS_PK_ECKEY) == 1) { +#ifdef HKS_SUPPORT_ECC_C + ret = X509PublicKeyToEcc(mbedtls_pk_ec(ctx), publicKey); +#else + ret = HKS_ERROR_INVALID_ALGORITHM; +#endif + } else { + HKS_LOG_E("Unsupport alg type!"); + ret = HKS_ERROR_INVALID_ARGUMENT; + } + + mbedtls_pk_free(&ctx); + return ret; +} +#endif + +#if defined(HKS_SUPPORT_ED25519_C) || defined(HKS_SUPPORT_X25519_C) +int32_t TranslateToInnerCurve25519Format(const uint32_t alg, const struct HksBlob *key, struct HksBlob *publicKey) +{ + if (key->size != HKS_KEY_BYTES(HKS_CURVE25519_KEY_SIZE_256)) { + HKS_LOG_E("Invalid curve25519 public key size! key size = 0x%X", key->size); + return HKS_ERROR_INVALID_KEY_INFO; + } + + uint32_t totalSize = sizeof(struct HksPubKeyInfo) + key->size; + uint8_t *buffer = (uint8_t *)HksMalloc(totalSize); + if (buffer == NULL) { + HKS_LOG_E("malloc failed! %u", totalSize); + return HKS_ERROR_MALLOC_FAIL; + } + (void)memset_s(buffer, totalSize, 0, totalSize); + + struct HksPubKeyInfo *curve25519Key = (struct HksPubKeyInfo *)buffer; + curve25519Key->keyAlg = alg; + curve25519Key->keySize = HKS_CURVE25519_KEY_SIZE_256; + curve25519Key->nOrXSize = key->size; /* curve25519 public key */ + + uint32_t offset = sizeof(struct HksPubKeyInfo); + if (memcpy_s(buffer + offset, totalSize - offset, key->data, key->size) != EOK) { + HKS_LOG_E("copy pub key failed!"); + HKS_FREE_PTR(buffer); + return HKS_ERROR_BAD_STATE; + } + publicKey->data = buffer; + publicKey->size = totalSize; + return HKS_SUCCESS; +} +#endif + +#ifdef HKS_SUPPORT_AES_C +int32_t TranslateToInnerAesFormat(const struct HksBlob *key, struct HksBlob *outKey) +{ + if ((key->size != HKS_KEY_BYTES(HKS_AES_KEY_SIZE_128)) && (key->size != HKS_KEY_BYTES(HKS_AES_KEY_SIZE_256))) { + HKS_LOG_E("Invalid aes key size! key size = 0x%X", key->size); + return HKS_ERROR_INVALID_KEY_INFO; + } + + uint8_t *keyBuffer = (uint8_t *)HksMalloc(key->size); + if (keyBuffer == NULL) { + HKS_LOG_E("public key to inner key format malloc keyBuffer failed!"); + return HKS_ERROR_MALLOC_FAIL; + } + + (void)memcpy_s(keyBuffer, key->size, key->data, key->size); + outKey->data = keyBuffer; + outKey->size = key->size; + return HKS_SUCCESS; +} +#endif diff --git a/services/huks_standard/huks_service/main/core/src/hks_storage.c b/services/huks_standard/huks_service/main/core/src/hks_storage.c index 28ebafb3..86548ddd 100755 --- a/services/huks_standard/huks_service/main/core/src/hks_storage.c +++ b/services/huks_standard/huks_service/main/core/src/hks_storage.c @@ -13,7 +13,16 @@ * limitations under the License. */ +#ifndef _CUT_AUTHENTICATE_ + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + #include "hks_storage.h" + #include "hks_file_operator.h" #include "hks_log.h" #include "hks_mem.h" @@ -22,6 +31,19 @@ #define HKS_ENCODE_KEY_SALT_VALUE 0x3f #define HKS_STORAGE_BAK_FLAG_TRUE 1 #define HKS_STORAGE_BAK_FLAG_FLASE 0 +#define KEY_ALIAS_ANONYMOUS_LEN 4 +#define KEY_ALIAS_SUFFIX_LEN 4 + +enum KeyOperation { + KEY_OPERATION_SAVE = 0, + KEY_OPERATION_GET = 1, + KEY_OPERATION_DELETE = 2, +}; + +static bool g_setRootMainPath = false; +static bool g_setRootBakPath = false; +static char g_keyStoreMainPath[HKS_MAX_FILE_NAME_LEN + 1] = {0}; +static char g_keyStoreBakPath[HKS_MAX_FILE_NAME_LEN + 1] = {0}; struct HksStoreInfo { char *processPath; /* file path include process */ @@ -42,7 +64,7 @@ struct HksFileEntry { uint32_t fileNameLen; }; -#ifdef HKS_SUPPORT_GT_WATCH +#ifdef HKS_SUPPORT_POSIX static void ConstructInvalidCharacter(const char input, char *output) { switch (input) { @@ -115,7 +137,7 @@ static int32_t ConstructName(const struct HksBlob *blob, char *targetName, uint3 targetName[count++] = blob->data[i]; } -#ifdef HKS_SUPPORT_GT_WATCH +#ifdef HKS_SUPPORT_POSIX ConstructInvalidCharacter(targetName[count - 1], &targetName[count - 1]); #endif } @@ -217,9 +239,39 @@ static int32_t GetFullPath(const char *path, const char *processName, const char HKS_STORAGE_BAK_FLAG_FLASE); } +static int32_t GetStoreRootPath(enum HksStoragePathType type, char **path) +{ + if (type == HKS_STORAGE_MAIN_PATH) { + if (!g_setRootMainPath) { + uint32_t len = sizeof(g_keyStoreMainPath); + int32_t ret = HksGetStoragePath(HKS_STORAGE_MAIN_PATH, g_keyStoreMainPath, &len); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get mainStorage path fail"); + return ret; + } + g_setRootMainPath = true; + } + *path = g_keyStoreMainPath; + } else if (type == HKS_STORAGE_BACKUP_PATH) { + if (!g_setRootBakPath) { + uint32_t len = sizeof(g_keyStoreBakPath); + int32_t ret = HksGetStoragePath(HKS_STORAGE_BACKUP_PATH, g_keyStoreBakPath, &len); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get backup storage path fail"); + return ret; + } + g_setRootBakPath = true; + } + *path = g_keyStoreBakPath; + } else { + return HKS_ERROR_INVALID_ARGUMENT; + } + return HKS_SUCCESS; +} + static int32_t MakeDirIfNotExist(const char *path) { - int32_t ret = HksIsFileExist(NULL, path); + int32_t ret = HksIsDirExist(path); if (ret != HKS_SUCCESS) { HKS_LOG_I("dir not exist, path = %s", path); if (HksMakeDir(path) != HKS_SUCCESS) { @@ -543,26 +595,38 @@ static void FileInfoFree(struct HksStoreFileInfo *fileInfo) static int32_t GetStorePath(const char *processName, const char *storageName, struct HksStoreFileInfo *fileInfo) { - int32_t ret = MakeDirIfNotExist(HKS_KEY_STORE_PATH); + char *mainRootPath = NULL; + int32_t ret = GetStoreRootPath(HKS_STORAGE_MAIN_PATH, &mainRootPath); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get root path failed"); + return ret; + } + ret = MakeDirIfNotExist(mainRootPath); if (ret != HKS_SUCCESS) { HKS_LOG_E("makedir main path failed"); return ret; } - ret = GetFullPath(HKS_KEY_STORE_PATH, processName, storageName, fileInfo); + ret = GetFullPath(mainRootPath, processName, storageName, fileInfo); if (ret != HKS_SUCCESS) { HKS_LOG_E("get full path failed, ret = %d.", ret); return ret; } #ifdef SUPPORT_STORAGE_BACKUP - ret = MakeDirIfNotExist(HKS_KEY_STORE_BAK_PATH); + char *bakRootPath = NULL; + ret = GetStoreRootPath(HKS_STORAGE_BACKUP_PATH, &bakRootPath); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get root path failed"); + return ret; + } + ret = MakeDirIfNotExist(bakRootPath); if (ret != HKS_SUCCESS) { HKS_LOG_E("makedir backup path failed"); return ret; } - ret = GetBakFullPath(HKS_KEY_STORE_BAK_PATH, processName, storageName, fileInfo); + ret = GetBakFullPath(bakRootPath, processName, storageName, fileInfo); if (ret != HKS_SUCCESS) { HKS_LOG_E("get backup full path failed, ret = %d.", ret); } @@ -624,6 +688,50 @@ static int32_t GetFileInfo(const struct HksBlob *processName, const struct HksBl return ret; } +/* + * keyAlias: xxxxxxxxxxxxxxxxxxx********************xxxxxxxxxxxxxxxxxx + * |<- anonymous len ->||<- suffix len ->| + * |<----------------- keyAlias len ----------------------->| + */ +static int32_t RecordKeyOperation(uint32_t operation, const char *path, const char *keyAlias) +{ + uint32_t bufSize = strlen(keyAlias) + 1; + char *outKeyAlias = (char *)HksMalloc(bufSize); + if (outKeyAlias == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + (void)memset_s(outKeyAlias, bufSize, 0, bufSize); + + uint32_t keyAliasLen = strlen(keyAlias); + for (uint32_t i = 0; i < keyAliasLen; ++i) { + if ((keyAliasLen < (i + 1 + KEY_ALIAS_ANONYMOUS_LEN + KEY_ALIAS_SUFFIX_LEN)) && + ((i + 1 + KEY_ALIAS_SUFFIX_LEN) <= keyAliasLen)) { + outKeyAlias[i] = '*'; + } else { + outKeyAlias[i] = keyAlias[i]; + } + } + outKeyAlias[keyAliasLen] = '\0'; + + int32_t ret = HKS_SUCCESS; + switch (operation) { + case KEY_OPERATION_SAVE: + HKS_LOG_I("generate key or certchain, storage path: %s, key alias: %s", path, outKeyAlias); + break; + case KEY_OPERATION_GET: + HKS_LOG_I("use key, storage path: %s, key alias: %s", path, outKeyAlias); + break; + case KEY_OPERATION_DELETE: + HKS_LOG_I("delete key or certchain, storage path: %s, key alias: %s", path, outKeyAlias); + break; + default: + ret = HKS_ERROR_INVALID_ARGUMENT; + } + + HKS_FREE_PTR(outKeyAlias); + return ret; +} + int32_t HksStoreKeyBlob(const struct HksBlob *processName, const struct HksBlob *keyAlias, enum HksStorageType storageType, const struct HksBlob *keyBlob) { @@ -638,8 +746,11 @@ int32_t HksStoreKeyBlob(const struct HksBlob *processName, const struct HksBlob HKS_LOG_E("hks get file info failed, ret = %d.", ret); break; } - HKS_LOG_E("generate key or certchain, storage path: %s, key alias:%s.", - fileInfo.mainPath.path, fileInfo.mainPath.fileName); + + ret = RecordKeyOperation(KEY_OPERATION_SAVE, fileInfo.mainPath.path, fileInfo.mainPath.fileName); + if (ret != HKS_SUCCESS) { + break; + } ret = SaveKeyBlob(fileInfo.mainPath.processPath, fileInfo.mainPath.path, fileInfo.mainPath.fileName, keyBlob); if (ret != HKS_SUCCESS) { @@ -672,8 +783,11 @@ int32_t HksStoreDeleteKeyBlob(const struct HksBlob *processName, const struct Hk HKS_LOG_E("hks get file info failed, ret = %d.", ret); break; } - HKS_LOG_E("delete key or certchain, storage path: %s, key alias:%s.", - fileInfo.mainPath.path, fileInfo.mainPath.fileName); + + ret = RecordKeyOperation(KEY_OPERATION_DELETE, fileInfo.mainPath.path, fileInfo.mainPath.fileName); + if (ret != HKS_SUCCESS) { + break; + } ret = DeleteKeyBlob(&fileInfo); } while (0); @@ -720,8 +834,11 @@ int32_t HksStoreGetKeyBlob(const struct HksBlob *processName, const struct HksBl HKS_LOG_E("hks get file info failed, ret = %d.", ret); break; } - HKS_LOG_E("use key, storage path: %s, key alias:%s.", - fileInfo.mainPath.path, fileInfo.mainPath.fileName); + + ret = RecordKeyOperation(KEY_OPERATION_GET, fileInfo.mainPath.path, fileInfo.mainPath.fileName); + if (ret != HKS_SUCCESS) { + break; + } ret = GetKeyBlob(&fileInfo, keyBlob); if (ret != HKS_SUCCESS) { @@ -772,7 +889,7 @@ static int32_t GetFileCount(const char *path, uint32_t *fileCount) } uint32_t count = 0; - struct HksFileDirentInfo dire = { NULL }; + struct HksFileDirentInfo dire = {{0}}; int32_t ret = HksGetDirFile(dir, &dire); while (ret == HKS_SUCCESS) { count++; @@ -798,7 +915,7 @@ static int32_t GetFileNameList(const char *path, struct HksFileEntry *fileNameLi } uint32_t count = 0; - struct HksFileDirentInfo dire = { NULL }; + struct HksFileDirentInfo dire = {{0}}; int32_t ret = HksGetDirFile(dir, &dire); while (ret == HKS_SUCCESS) { count++; @@ -1029,7 +1146,7 @@ static int32_t DestoryType(const char *storePath, const char *typePath, uint32_t return ret; } - ret = HksIsFileExist(NULL, destoryPath); + ret = HksIsDirExist(destoryPath); if (ret != HKS_SUCCESS) { HKS_FREE_PTR(destoryPath); return HKS_SUCCESS; @@ -1046,18 +1163,25 @@ static int32_t DestoryType(const char *storePath, const char *typePath, uint32_t static int32_t StoreDestory(const char *processNameEncoded, uint32_t bakFlag) { + int32_t ret; + char *rootPath = NULL; + if (bakFlag == HKS_STORAGE_BAK_FLAG_TRUE) { + ret = GetStoreRootPath(HKS_STORAGE_BACKUP_PATH, &rootPath); + } else { + ret = GetStoreRootPath(HKS_STORAGE_MAIN_PATH, &rootPath); + } + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get root path failed"); + return ret; + } + char *storePath = (char *)HksMalloc(HKS_MAX_FILE_NAME_LEN); if (storePath == NULL) { return HKS_ERROR_MALLOC_FAIL; } (void)memset_s(storePath, HKS_MAX_FILE_NAME_LEN, 0, HKS_MAX_FILE_NAME_LEN); - int32_t ret; - if (bakFlag == HKS_STORAGE_BAK_FLAG_TRUE) { - ret = GetPath(HKS_KEY_STORE_BAK_PATH, processNameEncoded, storePath, HKS_MAX_FILE_NAME_LEN, bakFlag); - } else { - ret = GetPath(HKS_KEY_STORE_PATH, processNameEncoded, storePath, HKS_MAX_FILE_NAME_LEN, bakFlag); - } + ret = GetPath(rootPath, processNameEncoded, storePath, HKS_MAX_FILE_NAME_LEN, bakFlag); if (ret != HKS_SUCCESS) { HKS_LOG_E("Get Path failed! ret = 0x%X", ret); HKS_FREE_PTR(storePath); @@ -1117,3 +1241,4 @@ int32_t HksStoreDestory(const struct HksBlob *processName) HKS_FREE_PTR(name); return ret; } +#endif /* _CUT_AUTHENTICATE_ */ diff --git a/services/huks_standard/huks_service/main/core/src/hks_storage_adapter.c b/services/huks_standard/huks_service/main/core/src/hks_storage_adapter.c new file mode 100644 index 00000000..1b11140b --- /dev/null +++ b/services/huks_standard/huks_service/main/core/src/hks_storage_adapter.c @@ -0,0 +1,152 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef _CUT_AUTHENTICATE_ +#ifdef _STORAGE_LITE_ + +#include "hks_storage_adapter.h" +#include "hks_log.h" +#include "hks_param.h" + +bool HksIsKeyInfoLenInvalid(struct HksStoreKeyInfo *keyInfo) +{ + return (keyInfo->aliasSize > HKS_MAX_KEY_ALIAS_LEN) || (keyInfo->aliasSize == 0) || + (keyInfo->keySize > HKS_MAX_KEY_MATERIAL_LEN) || (keyInfo->keySize == 0) || + (keyInfo->authIdSize > HKS_MAX_KEY_AUTH_ID_LEN) || + (keyInfo->keyInfoLen != (sizeof(*keyInfo) + keyInfo->aliasSize + keyInfo->authIdSize + keyInfo->keySize)); +} + +static int32_t AddStorageFixedParams(const struct HksStoreKeyInfo *keyInfo, struct HksParamSet *paramSet) +{ + struct HksParam params[] = { + { + .tag = HKS_TAG_KEY_FLAG, + .uint32Param = keyInfo->flag + }, { + .tag = HKS_TAG_ALGORITHM, + .uint32Param = keyInfo->keyAlg + }, { + .tag = HKS_TAG_PURPOSE, + .uint32Param = keyInfo->purpose + }, { + .tag = HKS_TAG_KEY_SIZE, + .uint32Param = keyInfo->keyLen + }, { + .tag = HKS_TAG_DIGEST, + .uint32Param = keyInfo->digest + }, { + .tag = HKS_TAG_PADDING, + .uint32Param = keyInfo->padding + }, { + .tag = HKS_TAG_BLOCK_MODE, + .uint32Param = keyInfo->keyMode + }, { + .tag = HKS_TAG_KEY_ROLE, + .uint32Param = keyInfo->role + }, { + .tag = HKS_TAG_KEY_DOMAIN, + .uint32Param = keyInfo->domain + }, + }; + + int32_t ret = HksAddParams(paramSet, params, sizeof(params) / sizeof(params[0])); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("HksAddParams failed!"); + } + return ret; +} + +static int32_t AddStorageParams(const struct HksBlob *key, const struct HksBlob *keyInfoBlob, + struct HksParamSet *paramSet) +{ + if (keyInfoBlob->size < sizeof(struct HksStoreKeyInfo)) { + HKS_LOG_E("invalid keyInfoBlob, size too small, size = %u", keyInfoBlob->size); + return HKS_ERROR_INVALID_KEY_INFO; + } + + struct HksStoreKeyInfo *keyInfo = (struct HksStoreKeyInfo *)keyInfoBlob->data; + if (HksIsKeyInfoLenInvalid(keyInfo)) { + HKS_LOG_E("invalid keyInfoBlob len"); + return HKS_ERROR_INVALID_KEY_INFO; + } + + int32_t ret = AddStorageFixedParams(keyInfo, paramSet); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("add storage fixed params failed!"); + return ret; + } + + if (keyInfo->authIdSize != 0) { + struct HksBlob keyAuthId = { keyInfo->authIdSize, keyInfoBlob->data + sizeof(*keyInfo) + keyInfo->aliasSize }; + struct HksParam keyAuthIdParam = { + .tag = HKS_TAG_KEY_AUTH_ID, + .blob = keyAuthId + }; + ret = HksAddParams(paramSet, &keyAuthIdParam, 1); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("HksAddParams keyAuthId failed!"); + return ret; + } + } + + if (key != NULL) { + struct HksParam keyParam = { + .tag = HKS_TAG_KEY, + .blob = *key + }; + ret = HksAddParams(paramSet, &keyParam, 1); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("HksAddParams key failed!"); + return ret; + } + } + return ret; +} + +int32_t TranslateKeyInfoBlobToParamSet(const struct HksBlob *key, const struct HksBlob *keyInfoBlob, + struct HksParamSet **paramSet) +{ + struct HksParamSet *outputParamSet = NULL; + int32_t ret = HksInitParamSet(&outputParamSet); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("HksInitParamSet failed!"); + return ret; + } + + do { + ret = AddStorageParams(key, keyInfoBlob, outputParamSet); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("AddParams failed!"); + break; + } + + ret = HksBuildParamSet(&outputParamSet); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("HksBuildParamSet failed!"); + } + } while (0); + + if (ret != HKS_SUCCESS) { + HKS_LOG_E("ConstructParamSet failed."); + HksFreeParamSet(&outputParamSet); + return ret; + } + + *paramSet = outputParamSet; + return ret; +} + +#endif /* _STORAGE_LITE_ */ +#endif /* _CUT_AUTHENTICATE_ */ diff --git a/services/huks_standard/huks_service/main/core/src/hks_storage_lite.c b/services/huks_standard/huks_service/main/core/src/hks_storage_lite.c new file mode 100644 index 00000000..1ae53851 --- /dev/null +++ b/services/huks_standard/huks_service/main/core/src/hks_storage_lite.c @@ -0,0 +1,921 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef _CUT_AUTHENTICATE_ + +#ifdef _STORAGE_LITE_ + +#include "hks_storage.h" + +#include "hks_access.h" +#include "hks_file_operator.h" +#include "hks_log.h" +#include "hks_mem.h" +#include "hks_param.h" +#include "hks_storage_adapter.h" + +#define HKS_FILE_OFFSET_BASE 0 +#define MAX_STORAGE_SIZE 5120 +#define MAX_BUF_SIZE 65536 +#define MAX_KEY_COUNT 256 +#define BUF_SIZE_ADDEND_PER_TIME 1024 +#define HKS_STORAGE_VERSION 1 +#define HKS_STORAGE_RESERVED_SEALING_ALG 0xFEDCBA98 + +struct HksBlob g_storageImageBuffer = { 0, NULL }; + +static uint32_t HksGetStoreFileOffset(void) +{ + return HKS_FILE_OFFSET_BASE; +} + +static int32_t ConstructCalcMacParamSet(struct HksParamSet **paramSet) +{ + struct HksParamSet *outputParamSet = NULL; + int32_t ret = HksInitParamSet(&outputParamSet); + if (ret != HKS_SUCCESS) { + return ret; + } + + do { + struct HksParam digestParam = { + .tag = HKS_TAG_DIGEST, + .uint32Param = HKS_DIGEST_SHA512 + }; + + ret = HksAddParams(outputParamSet, &digestParam, 1); /* 1: param count */ + if (ret != HKS_SUCCESS) { + break; + } + + ret = HksBuildParamSet(&outputParamSet); + } while (0); + + if (ret != HKS_SUCCESS) { + HksFreeParamSet(&outputParamSet); + return ret; + } + + *paramSet = outputParamSet; + return ret; +} + +static int32_t CalcHeaderMac(const struct HksBlob *salt, const uint8_t *buf, + const uint32_t srcSize, struct HksBlob *mac) +{ + if (srcSize == 0) { + return HKS_ERROR_INVALID_ARGUMENT; + } + + struct HksBlob srcData = { srcSize, NULL }; + srcData.data = (uint8_t *)HksMalloc(srcData.size); + if (srcData.data == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + + int32_t ret; + struct HksParamSet *paramSet = NULL; + do { + if (memcpy_s(srcData.data, srcData.size, buf, srcSize) != EOK) { + ret = HKS_ERROR_BAD_STATE; + break; + } + + ret = ConstructCalcMacParamSet(¶mSet); + if (ret != HKS_SUCCESS) { + break; + } + + ret = HksAccessCalcHeaderMac(paramSet, salt, &srcData, mac); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("access calc header mac failed, ret = %d.", ret); + } + } while (0); + + HKS_FREE_BLOB(srcData); + HksFreeParamSet(¶mSet); + return ret; +} + +static int32_t InitImageBuffer(void) +{ + /* caller func ensure g_storageImageBuffer.size is larger than sizeof(*keyInfoHead) */ + struct HksStoreHeaderInfo *keyInfoHead = (struct HksStoreHeaderInfo *)g_storageImageBuffer.data; + keyInfoHead->version = HKS_STORAGE_VERSION; + keyInfoHead->keyCount = 0; + keyInfoHead->totalLen = sizeof(*keyInfoHead); + keyInfoHead->sealingAlg = HKS_STORAGE_RESERVED_SEALING_ALG; + + struct HksBlob salt = { HKS_DERIVE_DEFAULT_SALT_LEN, keyInfoHead->salt }; + int32_t ret = HksAccessGenerateRandom(NULL, &salt); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("generate random failed, ret = %d", ret); + return ret; + } + + struct HksBlob mac = { HKS_HMAC_DIGEST_SHA512_LEN, keyInfoHead->hmac }; + uint16_t size = sizeof(*keyInfoHead) - HKS_HMAC_DIGEST_SHA512_LEN; + + return CalcHeaderMac(&salt, g_storageImageBuffer.data, size, &mac); +} + +static void CleanImageBuffer(void) +{ + if (g_storageImageBuffer.data == NULL) { + return; + } + (void)memset_s(g_storageImageBuffer.data, g_storageImageBuffer.size, 0, g_storageImageBuffer.size); +} + +static int32_t ApplyImageBuffer(uint32_t size) +{ + if (g_storageImageBuffer.data != NULL) { + return HKS_SUCCESS; + } + + if ((size == 0) || (size > MAX_BUF_SIZE)) { + HKS_LOG_E("invalid size = %u", size); + return HKS_ERROR_INVALID_ARGUMENT; + } + + g_storageImageBuffer.data = (uint8_t *)HksMalloc(size); + if (g_storageImageBuffer.data == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + g_storageImageBuffer.size = size; + + return HKS_SUCCESS; +} + +static void FreeImageBuffer(void) +{ + CleanImageBuffer(); + HKS_FREE_BLOB(g_storageImageBuffer); +} + +static int32_t FreshImageBuffer(const char *fileName) +{ + /* caller func ensure g_storageImageBuffer.size is larger than sizeof(*keyInfoHead) */ + struct HksStoreHeaderInfo *keyInfoHead = (struct HksStoreHeaderInfo *)g_storageImageBuffer.data; + uint32_t totalLen = keyInfoHead->totalLen; + + /* check totalLen */ + if ((totalLen < sizeof(*keyInfoHead)) || (totalLen > MAX_STORAGE_SIZE)) { + return HKS_ERROR_INVALID_KEY_FILE; + } + + if (totalLen == sizeof(*keyInfoHead)) { + return HKS_SUCCESS; + } + + uint32_t offset = HksGetStoreFileOffset(); + uint32_t fileLen = HksFileSize(HKS_KEY_STORE_PATH, fileName); + if (fileLen < (totalLen + offset)) { /* keyfile len at least totalLen + offset */ + HKS_LOG_E("total Len: %u, invalid file size: %u", totalLen, fileLen); + return HKS_ERROR_INVALID_KEY_FILE; + } + + uint8_t *buf = (uint8_t *)HksMalloc(totalLen); + if (buf == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + + fileLen = HksFileRead(HKS_KEY_STORE_PATH, fileName, offset, buf, totalLen); + if (fileLen == 0) { + HKS_FREE_PTR(buf); + return HKS_ERROR_READ_FILE_FAIL; + } + + FreeImageBuffer(); + g_storageImageBuffer.data = buf; + g_storageImageBuffer.size = totalLen; + + return HKS_SUCCESS; +} + +static int32_t CheckKeyInfoHeaderValid(void) +{ + /* caller func ensure g_storageImageBuffer.size is larger than sizeof(*keyInfoHead) */ + struct HksStoreHeaderInfo *keyInfoHead = (struct HksStoreHeaderInfo *)g_storageImageBuffer.data; + + uint8_t mac512[HKS_HMAC_DIGEST_SHA512_LEN] = {0}; + struct HksBlob mac = { HKS_HMAC_DIGEST_SHA512_LEN, mac512 }; + struct HksBlob salt = { HKS_DERIVE_DEFAULT_SALT_LEN, keyInfoHead->salt }; + uint16_t size = sizeof(*keyInfoHead) - HKS_HMAC_DIGEST_SHA512_LEN; + + int32_t ret = CalcHeaderMac(&salt, g_storageImageBuffer.data, size, &mac); + if (ret != HKS_SUCCESS) { + return ret; + } + + if (HksMemCmp(mac.data, keyInfoHead->hmac, HKS_HMAC_DIGEST_SHA512_LEN) != 0) { + HKS_LOG_E("hmac value not match"); + return HKS_ERROR_INVALID_KEY_FILE; + } + + return HKS_SUCCESS; +} + +static int32_t RefreshKeyInfoHeaderHmac(struct HksStoreHeaderInfo *keyInfoHead) +{ + struct HksBlob mac = { HKS_HMAC_DIGEST_SHA512_LEN, keyInfoHead->hmac }; + struct HksBlob salt = { HKS_DERIVE_DEFAULT_SALT_LEN, keyInfoHead->salt }; + uint16_t size = sizeof(*keyInfoHead) - HKS_HMAC_DIGEST_SHA512_LEN; + + uint8_t *buffer = (uint8_t *)HksMalloc(sizeof(*keyInfoHead)); + if (buffer == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + (void)memcpy_s(buffer, sizeof(*keyInfoHead), keyInfoHead, sizeof(*keyInfoHead)); + + int32_t ret = CalcHeaderMac(&salt, buffer, size, &mac); + HKS_FREE_PTR(buffer); + return ret; +} + +static struct HksBlob HksGetImageBuffer(void) +{ + return g_storageImageBuffer; +} + +static int32_t LoadFileToBuffer(const char *fileName) +{ + /* 1. read key info header */ + uint32_t offset = HksGetStoreFileOffset(); + uint32_t len = HksFileRead(HKS_KEY_STORE_PATH, fileName, offset, + g_storageImageBuffer.data, g_storageImageBuffer.size); + + int32_t ret; + do { + /* 2. file not exist or read nothing, init image */ + if (len == 0) { + HKS_LOG_I("file not exist, init buffer."); + ret = InitImageBuffer(); + if (ret != HKS_SUCCESS) { + break; /* init fail, need free global buf */ + } + return ret; + } + + /* 3. read header success, check keyinfo header */ + HKS_LOG_I("file exist, check buffer."); + ret = CheckKeyInfoHeaderValid(); + if (ret != HKS_SUCCESS) { + break; + } + + /* 4. check success, load full buffer */ + ret = FreshImageBuffer(fileName); + } while (0); + + if (ret != HKS_SUCCESS) { + FreeImageBuffer(); + } + + return ret; +} + +int32_t HksLoadFileToBuffer(void) +{ + if (g_storageImageBuffer.data != NULL) { + return HKS_SUCCESS; + } + + /* 1. malloc keyinfo header size buffer */ + int32_t ret = ApplyImageBuffer(sizeof(struct HksStoreHeaderInfo)); + if (ret != HKS_SUCCESS) { + return ret; + } + CleanImageBuffer(); + + /* 2. read file to buffer */ + return LoadFileToBuffer(HKS_KEY_STORE_FILE_NAME); +} + +static int32_t CleanStorageKeyInfo(const char *fileName) +{ + int32_t ret = InitImageBuffer(); + if (ret != HKS_SUCCESS) { + FreeImageBuffer(); + return ret; + } + + /* write to file */ + uint32_t totalLen = sizeof(struct HksStoreHeaderInfo); + uint32_t fileOffset = HksGetStoreFileOffset(); + ret = HksFileWrite(HKS_KEY_STORE_PATH, fileName, fileOffset, g_storageImageBuffer.data, totalLen); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("write file failed when hks refresh file buffer"); + FreeImageBuffer(); + } + return ret; +} + +int32_t HksFileBufferRefresh(void) +{ + /* malloc keyinfo header size buffer */ + int32_t ret = ApplyImageBuffer(sizeof(struct HksStoreHeaderInfo)); + if (ret != HKS_SUCCESS) { + return ret; + } + CleanImageBuffer(); + + return CleanStorageKeyInfo(HKS_KEY_STORE_FILE_NAME); +} + +/* + * Storage format: + * keyInfoHeader + keyInfo1 + keyInfo2 + ... + keyInfoN + * + * +--------------------------------------------------------------+ + * KeyInfoHeader: | version | keyCount | totalLen | sealingAlg | salt | hmac | + * | 2bytes | 2bytes | 4bytes | 4bytes |16bytes |64bytes | + * +--------------------------------------------------------------+ + * + * +---------------------------------------------------------------------+ + * KeyInfo: | keyInfoLen | keySize | nonce | flag | keyAlg | keyMode | digest | + * | 2bytes | 2bytes | 16bytes | 1bytes | 1bytes | 1bytes | 1bytes | + * +---------------------------------------------------------------------+ + * | padding | rsv | keyLen | purpose | role | domain | aliasSize | + * | 1bytes | 1bytes | 2bytes | 4bytes | 4bytes | 21bytes | 1bytes | + * +--------------------------------------------------------------------+ + * | AuthIdSize | keyAlias | keyAuthId | key | + * | 1bytes | max 64bytes | max 64bytes | max keyMaterial size | + * +---------------------------------------------------------------+ + */ +static int32_t GetKeyOffsetByKeyAlias(const struct HksBlob *keyAlias, uint32_t *keyOffset) +{ + struct HksBlob storageBuf = HksGetImageBuffer(); + if (storageBuf.size < sizeof(struct HksStoreHeaderInfo)) { + HKS_LOG_E("invalid keyinfo buffer size %u.", storageBuf.size); + return HKS_ERROR_INVALID_KEY_FILE; + } + + /* 1. get imageBuffer total Len */ + struct HksStoreHeaderInfo *keyInfoHead = (struct HksStoreHeaderInfo *)storageBuf.data; + uint32_t keyCount = keyInfoHead->keyCount; + uint32_t totalLen = keyInfoHead->totalLen; + if (keyCount == 0) { + return HKS_ERROR_NOT_EXIST; + } + if ((keyCount > MAX_KEY_COUNT) || (totalLen > storageBuf.size)) { + HKS_LOG_E("keyCount invalid, or storageBuf size invalid"); + return HKS_ERROR_INVALID_KEY_FILE; + } + + /* 2. traverse imageBuffer to search for keyAlias */ + uint32_t offset = sizeof(*keyInfoHead); + for (uint16_t i = 0; i < keyCount; ++i) { + if ((totalLen < offset) || ((totalLen - offset) < sizeof(struct HksStoreKeyInfo))) { + HKS_LOG_E("invalid keyinfo size."); + return HKS_ERROR_INVALID_KEY_FILE; + } + + uint8_t *tmpBuf = storageBuf.data + offset; + struct HksStoreKeyInfo *keyInfo = (struct HksStoreKeyInfo *)tmpBuf; + if (HksIsKeyInfoLenInvalid(keyInfo) || (keyInfo->keyInfoLen > (totalLen - offset))) { + HKS_LOG_E("invalid keyinfo len"); + return HKS_ERROR_INVALID_KEY_FILE; + } + + if (keyInfo->aliasSize == keyAlias->size) { + if (HksMemCmp(keyAlias->data, tmpBuf + sizeof(*keyInfo), keyAlias->size) == 0) { + *keyOffset = offset; + return HKS_SUCCESS; + } + } + + offset += keyInfo->keyInfoLen; + } + + return HKS_ERROR_NOT_EXIST; +} + +static int32_t AdjustImageBuffer(uint32_t totalLenAdded, const struct HksBlob *keyBlob) +{ + struct HksStoreHeaderInfo *keyInfoHead = (struct HksStoreHeaderInfo *)g_storageImageBuffer.data; + + /* buffer has been checked will not overflow */ + uint32_t newBufLen = g_storageImageBuffer.size + + ((keyBlob->size > BUF_SIZE_ADDEND_PER_TIME) ? keyBlob->size : BUF_SIZE_ADDEND_PER_TIME); + uint8_t *buf = (uint8_t *)HksMalloc(newBufLen); + if (buf == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + (void)memset_s(buf, newBufLen, 0, newBufLen); + + /* copy old imagebuf to new malloc buf */ + if (memcpy_s(buf, newBufLen, g_storageImageBuffer.data, keyInfoHead->totalLen) != EOK) { + HKS_FREE_PTR(buf); + return HKS_ERROR_BAD_STATE; + } + + /* append new add key buffer to the end */ + if (memcpy_s(buf + keyInfoHead->totalLen, newBufLen - keyInfoHead->totalLen, + keyBlob->data, keyBlob->size) != EOK) { + HKS_FREE_PTR(buf); + return HKS_ERROR_BAD_STATE; + } + + struct HksStoreHeaderInfo *newHead = (struct HksStoreHeaderInfo *)buf; + newHead->totalLen = totalLenAdded; + newHead->keyCount += 1; + + FreeImageBuffer(); + g_storageImageBuffer.data = buf; + g_storageImageBuffer.size = newBufLen; + + return HKS_SUCCESS; +} + +static int32_t AppendNewKey(const struct HksBlob *keyBlob) +{ + struct HksBlob storageBuf = HksGetImageBuffer(); + if (storageBuf.size < sizeof(struct HksStoreHeaderInfo)) { + HKS_LOG_E("invalid keyinfo buffer size %u.", storageBuf.size); + return HKS_ERROR_INVALID_KEY_FILE; + } + + /* 1. get imagebuf total Len */ + struct HksStoreHeaderInfo *keyInfoHead = (struct HksStoreHeaderInfo *)storageBuf.data; + + if (IsAdditionOverflow(keyInfoHead->totalLen, keyBlob->size)) { + return HKS_ERROR_BAD_STATE; + } + + uint32_t totalLenAdded = keyInfoHead->totalLen + keyBlob->size; + if (totalLenAdded > MAX_STORAGE_SIZE) { + HKS_LOG_E("after add, buffer too big to store"); + return HKS_ERROR_STORAGE_FAILURE; + } + + /* imagebuf is enough to append new keyinfo */ + if (storageBuf.size >= totalLenAdded) { + if (memcpy_s(storageBuf.data + keyInfoHead->totalLen, storageBuf.size - keyInfoHead->totalLen, + keyBlob->data, keyBlob->size) != EOK) { + return HKS_ERROR_BAD_STATE; + } + keyInfoHead->totalLen = totalLenAdded; + keyInfoHead->keyCount += 1; + return HKS_SUCCESS; + } + + /* need malloc new buffer */ + return AdjustImageBuffer(totalLenAdded, keyBlob); +} + +static int32_t GetLenAfterAddKey(const struct HksBlob *keyBlob, uint32_t totalLen, uint32_t *totalLenAdded) +{ + if (IsAdditionOverflow(totalLen, keyBlob->size)) { + return HKS_ERROR_BAD_STATE; + } + + uint32_t newTotalLen = totalLen + keyBlob->size; + if (newTotalLen > MAX_STORAGE_SIZE) { + HKS_LOG_E("after add, buffer too big to store"); + return HKS_ERROR_STORAGE_FAILURE; + } + + *totalLenAdded = newTotalLen; + return HKS_SUCCESS; +} + +static int32_t DeleteKey(uint32_t keyOffset) +{ + struct HksStoreHeaderInfo *keyInfoHead = (struct HksStoreHeaderInfo *)g_storageImageBuffer.data; + struct HksStoreKeyInfo *keyInfo = (struct HksStoreKeyInfo *)(g_storageImageBuffer.data + keyOffset); + + uint32_t keyInfoLen = keyInfo->keyInfoLen; + uint32_t nextKeyOffset = keyOffset + keyInfoLen; + if (nextKeyOffset > keyInfoHead->totalLen) { + return HKS_ERROR_INVALID_KEY_FILE; + } + + (void)memset_s(keyInfo, keyInfoLen, 0, keyInfoLen); + + /* If key to delete is not the last key, need to be move image buffer */ + if (nextKeyOffset < keyInfoHead->totalLen) { + if (memmove_s(keyInfo, keyInfoHead->totalLen - keyOffset, g_storageImageBuffer.data + nextKeyOffset, + keyInfoHead->totalLen - nextKeyOffset) != EOK) { + HKS_LOG_E("memmove image buffer failed"); + return HKS_ERROR_BAD_STATE; + } + /* clear the last buffer */ + (void)memset_s(g_storageImageBuffer.data + keyInfoHead->totalLen - keyInfoLen, keyInfoLen, 0, keyInfoLen); + } + keyInfoHead->keyCount -= 1; + keyInfoHead->totalLen -= keyInfoLen; + + return HKS_SUCCESS; +} + +static int32_t StoreKeyBlob(bool needDeleteKey, uint32_t offset, const struct HksBlob *keyBlob) +{ + struct HksStoreHeaderInfo *keyInfoHead = (struct HksStoreHeaderInfo *)g_storageImageBuffer.data; + struct HksStoreKeyInfo *keyInfo = (struct HksStoreKeyInfo *)(g_storageImageBuffer.data + offset); + + struct HksStoreHeaderInfo newkeyInfoHead; + if (memcpy_s(&newkeyInfoHead, sizeof(newkeyInfoHead), keyInfoHead, sizeof(*keyInfoHead)) != EOK) { + return HKS_ERROR_BAD_STATE; + } + + uint32_t totalLenAdded; + int32_t ret; + + /* 1. check storage buffer enough for store new key */ + if (needDeleteKey) { + ret = GetLenAfterAddKey(keyBlob, keyInfoHead->totalLen - keyInfo->keyInfoLen, &totalLenAdded); + } else { + newkeyInfoHead.keyCount += 1, + ret = GetLenAfterAddKey(keyBlob, keyInfoHead->totalLen, &totalLenAdded); + } + if (ret != HKS_SUCCESS) { + return ret; + } + + /* 2. calc temp hmac */ + newkeyInfoHead.totalLen = totalLenAdded; + ret = RefreshKeyInfoHeaderHmac(&newkeyInfoHead); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* 3. delete key if keyExist */ + if (needDeleteKey) { + ret = DeleteKey(offset); + if (ret != HKS_SUCCESS) { + return ret; + } + } + + /* 4. append key */ + ret = AppendNewKey(keyBlob); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* 5. replace header */ + if (memcpy_s(g_storageImageBuffer.data, sizeof(newkeyInfoHead), &newkeyInfoHead, sizeof(newkeyInfoHead)) != EOK) { + HKS_LOG_E("repalce header memcpy failed"); + return HKS_ERROR_BAD_STATE; + } + return HKS_SUCCESS; +} + +static int32_t GetFileName(const struct HksBlob *name, char **fileName) +{ + char *tmpName = (char *)HksMalloc(name->size + 1); /* \0 at the end */ + if (tmpName == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + + (void)memcpy_s(tmpName, name->size, name->data, name->size); + tmpName[name->size] = '\0'; + *fileName = tmpName; + return HKS_SUCCESS; +} + +static int32_t StoreRootMaterial(const struct HksBlob *name, const struct HksBlob *buffer) +{ + char *fileName = NULL; + int32_t ret = GetFileName(name, &fileName); + if (ret != HKS_SUCCESS) { + return ret; + } + ret = HksFileWrite(HKS_KEY_STORE_PATH, fileName, 0, buffer->data, buffer->size); + HKS_FREE_PTR(fileName); + return ret; +} + +static int32_t IsRootMaterialExist(const struct HksBlob *name) +{ + char *fileName = NULL; + int32_t ret = GetFileName(name, &fileName); + if (ret != HKS_SUCCESS) { + return ret; + } + ret = HksIsFileExist(HKS_KEY_STORE_PATH, fileName); + HKS_FREE_PTR(fileName); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("file not exist"); + return HKS_ERROR_NOT_EXIST; + } + return ret; +} + +static int32_t GetRootMaterial(const struct HksBlob *name, struct HksBlob *buffer) +{ + char *fileName = NULL; + int32_t ret = GetFileName(name, &fileName); + if (ret != HKS_SUCCESS) { + return ret; + } + uint32_t len = HksFileRead(HKS_KEY_STORE_PATH, fileName, 0, buffer->data, buffer->size); + HKS_FREE_PTR(fileName); + if (len == 0) { + return HKS_ERROR_READ_FILE_FAIL; + } + return HKS_SUCCESS; +} + +int32_t HksStoreKeyBlob(const struct HksBlob *processName, const struct HksBlob *keyAlias, + enum HksStorageType storageType, const struct HksBlob *keyBlob) +{ + (void)processName; + if (storageType == HKS_STORAGE_TYPE_ROOT_KEY) { + return StoreRootMaterial(keyAlias, keyBlob); + } + + /* 1. check key exist or not */ + uint32_t offset = 0; + int32_t ret = GetKeyOffsetByKeyAlias(keyAlias, &offset); + if ((ret != HKS_SUCCESS) && (ret != HKS_ERROR_NOT_EXIST)) { + return ret; + } + + /* 2. store key blob */ + bool needDeleteKey = (ret == HKS_SUCCESS); + ret = StoreKeyBlob(needDeleteKey, offset, keyBlob); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* 3. write to file */ + uint32_t totalLen = 0; + ret = HksStoreGetToatalSize(&totalLen); + if (ret != HKS_SUCCESS) { + return ret; + } + uint32_t fileOffset = HksGetStoreFileOffset(); + return HksFileWrite(HKS_KEY_STORE_PATH, HKS_KEY_STORE_FILE_NAME, fileOffset, g_storageImageBuffer.data, totalLen); +} + +int32_t HksStoreDeleteKeyBlob(const struct HksBlob *processName, + const struct HksBlob *keyAlias, uint32_t storageType) +{ + (void)processName; + (void)storageType; + + /* 1. check key exist or not */ + uint32_t offset = 0; + int32_t ret = GetKeyOffsetByKeyAlias(keyAlias, &offset); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* 2. calc tmp header hmac */ + struct HksStoreHeaderInfo *keyInfoHead = (struct HksStoreHeaderInfo *)g_storageImageBuffer.data; + struct HksStoreKeyInfo *keyInfo = (struct HksStoreKeyInfo *)(g_storageImageBuffer.data + offset); + struct HksStoreHeaderInfo newkeyInfoHead; + if (memcpy_s(&newkeyInfoHead, sizeof(newkeyInfoHead), keyInfoHead, sizeof(*keyInfoHead)) != EOK) { + return HKS_ERROR_BAD_STATE; + } + newkeyInfoHead.totalLen -= keyInfo->keyInfoLen; + newkeyInfoHead.keyCount -= 1; + + ret = RefreshKeyInfoHeaderHmac(&newkeyInfoHead); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* 3. delete key */ + ret = DeleteKey(offset); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* 4. replace header */ + if (memcpy_s(keyInfoHead, sizeof(*keyInfoHead), &newkeyInfoHead, sizeof(newkeyInfoHead)) != EOK) { + return HKS_ERROR_BAD_STATE; + } + + uint32_t fileOffset = HksGetStoreFileOffset(); + return HksFileWrite(HKS_KEY_STORE_PATH, HKS_KEY_STORE_FILE_NAME, fileOffset, + g_storageImageBuffer.data, keyInfoHead->totalLen); +} + +int32_t HksStoreIsKeyBlobExist(const struct HksBlob *processName, + const struct HksBlob *keyAlias, uint32_t storageType) +{ + (void)processName; + if (storageType == HKS_STORAGE_TYPE_ROOT_KEY) { + return IsRootMaterialExist(keyAlias); + } + + uint32_t offset = 0; + return GetKeyOffsetByKeyAlias(keyAlias, &offset); +} + +int32_t HksStoreGetKeyBlob(const struct HksBlob *processName, + const struct HksBlob *keyAlias, uint32_t storageType, struct HksBlob *keyBlob) +{ + (void)processName; + if (storageType == HKS_STORAGE_TYPE_ROOT_KEY) { + return GetRootMaterial(keyAlias, keyBlob); + } + + uint32_t offset = 0; + int32_t ret = GetKeyOffsetByKeyAlias(keyAlias, &offset); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* get offset success, len has been check valid */ + uint8_t *tmpBuf = g_storageImageBuffer.data + offset; + struct HksStoreKeyInfo *keyInfo = (struct HksStoreKeyInfo *)tmpBuf; + + keyBlob->data = (uint8_t *)HksMalloc(keyInfo->keyInfoLen); /* need be freed by caller functions */ + if (keyBlob->data == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + keyBlob->size = keyInfo->keyInfoLen; + + if (memcpy_s(keyBlob->data, keyBlob->size, tmpBuf, keyInfo->keyInfoLen) != EOK) { + HKS_LOG_E("memcpy to key blob failed."); + HKS_FREE_PTR(keyBlob->data); + return HKS_ERROR_BAD_STATE; + } + + return HKS_SUCCESS; +} + +int32_t HksStoreGetKeyBlobSize(const struct HksBlob *processName, + const struct HksBlob *keyAlias, uint32_t storageType, uint32_t *keyBlobSize) +{ + (void)processName; + (void)storageType; + + uint32_t offset = 0; + int32_t ret = GetKeyOffsetByKeyAlias(keyAlias, &offset); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* get offset success, len has been check valid */ + struct HksStoreKeyInfo *keyInfo = (struct HksStoreKeyInfo *)(g_storageImageBuffer.data + offset); + *keyBlobSize = keyInfo->keyInfoLen; + return HKS_SUCCESS; +} + +int32_t HksGetKeyCountByProcessName(const struct HksBlob *processName, uint32_t *keyCount) +{ + (void)processName; + if (g_storageImageBuffer.size < sizeof(struct HksStoreHeaderInfo)) { + HKS_LOG_E("invalid keyinfo buffer size %u.", g_storageImageBuffer.size); + return HKS_ERROR_INVALID_KEY_FILE; + } + + struct HksStoreHeaderInfo *keyInfoHead = (struct HksStoreHeaderInfo *)g_storageImageBuffer.data; + *keyCount = keyInfoHead->keyCount; + return HKS_SUCCESS; +} + +int32_t HksStoreGetToatalSize(uint32_t *size) +{ + if (g_storageImageBuffer.size < sizeof(struct HksStoreHeaderInfo)) { + HKS_LOG_E("invalid keyinfo buffer size %u.", g_storageImageBuffer.size); + return HKS_ERROR_INVALID_KEY_FILE; + } + + struct HksStoreHeaderInfo *keyInfoHead = (struct HksStoreHeaderInfo *)g_storageImageBuffer.data; + *size = keyInfoHead->totalLen; + return HKS_SUCCESS; +} + +static int32_t GetKeyInfoList(struct HksKeyInfo *keyInfoList, const struct HksBlob *keyInfoBlob) +{ + struct HksStoreKeyInfo *keyInfo = (struct HksStoreKeyInfo *)keyInfoBlob->data; + + if (keyInfoList->alias.size < keyInfo->aliasSize) { + return HKS_ERROR_BUFFER_TOO_SMALL; + } + + if (memcpy_s(keyInfoList->alias.data, keyInfoList->alias.size, + keyInfoBlob->data + sizeof(*keyInfo), keyInfo->aliasSize) != EOK) { + HKS_LOG_E("memcpy keyAlias failed"); + return HKS_ERROR_BAD_STATE; + } + keyInfoList->alias.size = keyInfo->aliasSize; + + struct HksParamSet *paramSet = NULL; + int32_t ret = TranslateKeyInfoBlobToParamSet(NULL, keyInfoBlob, ¶mSet); + if (ret != HKS_SUCCESS) { + return ret; + } + + if (keyInfoList->paramSet->paramSetSize < paramSet->paramSetSize) { + HksFreeParamSet(¶mSet); + return HKS_ERROR_BUFFER_TOO_SMALL; + } + if (memcpy_s(keyInfoList->paramSet, keyInfoList->paramSet->paramSetSize, + paramSet, paramSet->paramSetSize) != EOK) { + HKS_LOG_E("memcpy paramSet failed."); + HksFreeParamSet(¶mSet); + return HKS_ERROR_BAD_STATE; + } + + HksFreeParamSet(¶mSet); + return HKS_SUCCESS; +} + +static int32_t GetAndCheckKeyCount(uint32_t *inputCount, uint32_t *keyCount) +{ + struct HksBlob storageBuf = HksGetImageBuffer(); + if (storageBuf.size < sizeof(struct HksStoreHeaderInfo)) { + HKS_LOG_E("invalid keyinfo buffer size %u.", storageBuf.size); + return HKS_ERROR_INVALID_KEY_FILE; + } + + struct HksStoreHeaderInfo *keyInfoHead = (struct HksStoreHeaderInfo *)storageBuf.data; + *keyCount = keyInfoHead->keyCount; + if (*keyCount == 0) { + *inputCount = 0; + return HKS_SUCCESS; + } + + if ((*keyCount > MAX_KEY_COUNT) || (storageBuf.size < keyInfoHead->totalLen)) { + HKS_LOG_E("keyCount invalid, or storageBuf size invalid"); + return HKS_ERROR_INVALID_KEY_FILE; + } + + if (*inputCount < *keyCount) { + HKS_LOG_E("listCount space not enough"); + return HKS_ERROR_BUFFER_TOO_SMALL; + } + return HKS_SUCCESS; +} + +int32_t HksStoreGetKeyInfoList(struct HksKeyInfo *keyInfoList, uint32_t *listCount) +{ + uint32_t keyCount; + int32_t ret = GetAndCheckKeyCount(listCount, &keyCount); + if (ret != HKS_SUCCESS) { + return ret; + } + + /* 2. traverse ImageBuffer to search for keyAlias */ + struct HksBlob storageBuf = HksGetImageBuffer(); + struct HksStoreHeaderInfo *keyInfoHead = (struct HksStoreHeaderInfo *)storageBuf.data; + uint32_t totalLen = keyInfoHead->totalLen; + uint32_t num = 0; + uint32_t offset = sizeof(*keyInfoHead); + for (uint32_t i = 0; i < keyCount; ++i) { + if ((totalLen < offset) || ((totalLen - offset) < sizeof(struct HksStoreKeyInfo))) { + HKS_LOG_E("invalid keyinfo size."); + return HKS_ERROR_INVALID_KEY_FILE; + } + + uint8_t *tmpBuf = storageBuf.data + offset; /* storageBuf.size has been checked */ + struct HksStoreKeyInfo *keyInfo = (struct HksStoreKeyInfo *)tmpBuf; + + if (HksIsKeyInfoLenInvalid(keyInfo) || ((totalLen - offset) < keyInfo->keyInfoLen)) { + HKS_LOG_E("invalid keyinfo len"); + return HKS_ERROR_INVALID_KEY_FILE; + } + + struct HksBlob keyInfoBlob = { keyInfo->keyInfoLen, tmpBuf }; + ret = GetKeyInfoList(&keyInfoList[i], &keyInfoBlob); + if (ret != HKS_SUCCESS) { + return ret; + } + num++; + offset += keyInfo->keyInfoLen; + } + + *listCount = num; + return HKS_SUCCESS; +} + +int32_t HksStoreDestory(const struct HksBlob *processName) +{ + (void)processName; + int32_t ret = HksFileRemove(HKS_KEY_STORE_PATH, HKS_KEY_STORE_FILE_NAME); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("remove key store file failed"); /* only record log, continue delete */ + } + ret = HksFileRemove(HKS_KEY_STORE_PATH, "info1.data"); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("remove info1 file failed"); /* only record log, continue delete */ + } + ret = HksFileRemove(HKS_KEY_STORE_PATH, "info2.data"); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("remove info2 file failed"); + } + return ret; +} +#endif /* _STORAGE_LITE_ */ + +#endif /* _CUT_AUTHENTICATE_ */ + diff --git a/services/huks_standard/huks_service/main/core/src/hks_upgrade_storage_data.c b/services/huks_standard/huks_service/main/core/src/hks_upgrade_storage_data.c new file mode 100644 index 00000000..f671fda7 --- /dev/null +++ b/services/huks_standard/huks_service/main/core/src/hks_upgrade_storage_data.c @@ -0,0 +1,480 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef _CUT_AUTHENTICATE_ + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#ifdef HKS_SUPPORT_UPGRADE_STORAGE_DATA + +#include "hks_upgrade_storage_data.h" + +#include "hks_access.h" +#include "hks_crypto_hal.h" +#include "hks_file_operator.h" +#include "hks_get_process_info.h" +#include "hks_log.h" +#include "hks_mem.h" +#include "hks_storage.h" + +#define HKS_SEALING_NONCE_SIZE 16 +#define HKS_HEADER_HASH_SIZE 64 +#define HKS_KEY_PAIR_CIPHER_ED25519 80 + +#define HKS_RKC_KSF_BUF_LEN 258 +#define HKS_FILE_OFFSET_BASE 0 +#if defined(_HILINK_PRODUCT_) +#define HKS_LOCAL_STORAGE_KEY_MAX_NUM 15 +#define HKS_BUF_BYTES 4096 +#else +#define HKS_LOCAL_STORAGE_KEY_MAX_NUM 20 +#define HKS_BUF_BYTES 5120 +#endif + +#define HKS_KEY_STORE_FILE_NAME "hks_keystore" +#define HKS_ROOT_MATERIAL_FILE_NAME "info1.data" +#define HKS_BAK_ROOT_MATERIAL_FILE_NAME "info2.data" +#define HKS_ROOT_MATERIAL_FILE_NAME_LEN 10 + +static struct HksBlob g_rootKeyMaterialFile[] = { + { HKS_ROOT_MATERIAL_FILE_NAME_LEN, (uint8_t *)HKS_ROOT_MATERIAL_FILE_NAME }, + { HKS_ROOT_MATERIAL_FILE_NAME_LEN, (uint8_t *)HKS_BAK_ROOT_MATERIAL_FILE_NAME }, +}; + +/* + * +----------------------------------------------------------------------+ + * Header: | version | keyCount | slotCount | sealingAlg | sealingNonce | Hash | + * | 2bytes | 1bytes | 1bytes | 4bytes | 16bytes | 64bytes | + * +----------------------------------------------------------------------+ +*/ +static uint32_t GetHeaderLen(void) +{ + return (sizeof(uint16_t) + sizeof(uint8_t) + sizeof(uint8_t) + sizeof(uint32_t) + + HKS_SEALING_NONCE_SIZE + HKS_HEADER_HASH_SIZE); +} + +/* + * +------------------------------------------------------------------------------------------+ + * KeyInfo: | flags | sealingNonce | aliasSize | keyAlias | keyType | keyLen | usage | + * | 1bytes | 16bytes | 1bytes | max64bytes | 4bytes | 2bytes | 4bytes | + * +------------------------------------------------------------------------------------------+ + * | padding | keyMode | key_role | domain | authIdType | authIdSize | auth_id_data | + * | 1bytes | 4bytes | 4bytes | 2bytes | 1bytes | 1bytes | max64bytes | + * +------------------------------------------------------------------------------------------+ + * | keySize | key | + * | 1bytes | max80bytes | + * +------------------------+ +*/ +static uint32_t GetKeySlotLen(void) +{ + return (sizeof(uint8_t) + HKS_SEALING_NONCE_SIZE + sizeof(uint8_t) + HKS_MAX_KEY_ALIAS_LEN + + (sizeof(uint32_t) + sizeof(uint16_t) + sizeof(uint32_t) + sizeof(uint8_t) + sizeof(uint32_t) + + sizeof(uint32_t) + sizeof(uint16_t) + sizeof(uint8_t) + sizeof(uint8_t) + HKS_MAX_KEY_AUTH_ID_LEN) + + sizeof(uint8_t) + HKS_KEY_PAIR_CIPHER_ED25519); +} + +uint32_t HksGetStoreFileOffset(void) +{ +#if defined(_HILINK_PRODUCT_) + return HKS_RKC_KSF_BUF_LEN; +#else + return HKS_FILE_OFFSET_BASE; +#endif +} + +static int32_t CopyRootKeyMaterialFile(bool isFileExist, const char *oldFileName, const struct HksBlob *newFile) +{ + if (!isFileExist) { + return HKS_SUCCESS; + } + + char *processName = NULL; + int32_t ret = HksGetProcessName(&processName); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + + int32_t fileSize = HksOldVersionFileSize(oldFileName); + if (fileSize < HKS_RKC_KSF_BUF_LEN) { + HKS_LOG_E("get old version file size failed, ret = %d", fileSize); + return HKS_ERROR_FILE_SIZE_FAIL; + } + + uint8_t *tmpBuf = (uint8_t *)HksMalloc(fileSize); + if (tmpBuf == NULL) { + HKS_LOG_E("malloc failed"); + return HKS_ERROR_MALLOC_FAIL; + } + + do { + ret = HksOldVersionFileRead(oldFileName, 0, tmpBuf, fileSize); + if (ret <= 0) { + HKS_LOG_E("read old version file failed"); + ret = HKS_ERROR_READ_FILE_FAIL; + break; + } + + struct HksBlob newFileBlob = { fileSize, tmpBuf }; + ret = HksStoreKeyBlob(&processNameBlob, newFile, HKS_STORAGE_TYPE_ROOT_KEY, &newFileBlob); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("copy to new file failed"); + break; + } + } while (0); + + HKS_FREE_PTR(tmpBuf); + return ret; +} + +static int32_t RollBackNewVersionFiles(void) +{ + char *processName = NULL; + int32_t ret = HksGetProcessName(&processName); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get process name failed, ret = %d", ret); + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + + ret = HksStoreDestory(&processNameBlob); + if (ret != HKS_SUCCESS) { + HKS_LOG_D("destroy new files failed"); + } + return ret; +} + +static int32_t RemoveOldVersionFiles(void) +{ + int32_t ret = HksOldVersionFileRemove(HKS_KEY_STORE_FILE_NAME); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("remove key store file failed, ret = %d", ret); /* continue delete */ + } +#ifndef _HARDWARE_ROOT_KEY_ + ret = HksOldVersionFileRemove(HKS_ROOT_MATERIAL_FILE_NAME); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("remove root key material file failed, ret = %d", ret); /* continue delete */ + } + + ret = HksOldVersionFileRemove(HKS_BAK_ROOT_MATERIAL_FILE_NAME); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("remove backup root key material file failed, ret = %d", ret); + } +#endif + return ret; +} + +static int32_t UpgradeRootKeyMaterialFile(void) +{ + char *processName = NULL; + if (HksGetProcessName(&processName) != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + + /* check if new root key material file exist, if exist, return error, no need update hks_keystore file */ + for (uint32_t i = 0; i < HKS_ARRAY_SIZE(g_rootKeyMaterialFile); ++i) { + int32_t ret = HksStoreIsKeyBlobExist(&processNameBlob, &g_rootKeyMaterialFile[i], HKS_STORAGE_TYPE_ROOT_KEY); + if (ret != HKS_ERROR_NOT_EXIST) { + HKS_LOG_D("exist new root key material file, exit upgrading process."); + (void)RemoveOldVersionFiles(); /* new version file exist, remove old version files */ + return HKS_ERROR_NEW_ROOT_KEY_MATERIAL_EXIST; + } + } + + /* check old root key material files */ + bool isMainFileExist = HksOldVersionIsFileExist(HKS_ROOT_MATERIAL_FILE_NAME); + bool isBakFileExist = HksOldVersionIsFileExist(HKS_BAK_ROOT_MATERIAL_FILE_NAME); + if (!isMainFileExist && !isBakFileExist) { + HKS_LOG_E("old root key material file not exist."); + return HKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL; + } + + int32_t copyMainRet = CopyRootKeyMaterialFile(isMainFileExist, HKS_ROOT_MATERIAL_FILE_NAME, + &g_rootKeyMaterialFile[0]); + int32_t copyBakRet = CopyRootKeyMaterialFile(isBakFileExist, HKS_BAK_ROOT_MATERIAL_FILE_NAME, + &g_rootKeyMaterialFile[1]); + if ((copyMainRet != HKS_SUCCESS) && (copyBakRet != HKS_SUCCESS)) { + HKS_LOG_E("copy old key materail file to new file failed."); + return HKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL; + } + + return HKS_SUCCESS; +} + +static int32_t GetOldVersionKeyStoreBuf(struct HksBlob *keyInfo) +{ + uint32_t offset = HksGetStoreFileOffset(); + int32_t fileSize = HksOldVersionFileSize(HKS_KEY_STORE_FILE_NAME); + if ((fileSize < 0) || ((uint32_t)fileSize < offset)) { + HKS_LOG_E("get old version file size or invalid file size failed"); + return HKS_ERROR_FILE_SIZE_FAIL; + } + + uint8_t *tmpBuf = (uint8_t *)HksMalloc(HKS_BUF_BYTES); + if (tmpBuf == NULL) { + HKS_LOG_E("malloc failed"); + return HKS_ERROR_MALLOC_FAIL; + } + + fileSize = HksOldVersionFileRead(HKS_KEY_STORE_FILE_NAME, offset, tmpBuf, HKS_BUF_BYTES - offset); + if ((fileSize <= 0) || ((uint32_t)fileSize < (HKS_BUF_BYTES - offset))) { + HKS_LOG_E("read key store file failed"); + HKS_FREE_PTR(tmpBuf); + return HKS_ERROR_READ_FILE_FAIL; + } + + keyInfo->size = fileSize; + keyInfo->data = tmpBuf; + return HKS_SUCCESS; +} + +static int32_t CheckKeyStoreHeaderValid(const struct HksBlob *keyInfo) +{ + uint32_t headerLen = GetHeaderLen(); + /* keyInfo->size has been checked lager than header len */ + struct HksBlob srcData = { headerLen - HKS_HEADER_HASH_SIZE, keyInfo->data }; + + uint8_t *tmpBuf = (uint8_t *)HksMalloc(HKS_HEADER_HASH_SIZE); + if (tmpBuf == NULL) { + HKS_LOG_E("malloc failed"); + return HKS_ERROR_MALLOC_FAIL; + } + struct HksBlob hashBlob = { HKS_HEADER_HASH_SIZE, tmpBuf }; + + int32_t ret; + do { + ret = HksCryptoHalHash(HKS_DIGEST_SHA512, &srcData, &hashBlob); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("hks calculate header hash failed, ret = %d", ret); + break; + } + + if ((hashBlob.size != HKS_HEADER_HASH_SIZE) || + (HksMemCmp(hashBlob.data, keyInfo->data + srcData.size, HKS_HEADER_HASH_SIZE) != 0)) { + HKS_LOG_E("hks header hash invalid"); + ret = HKS_ERROR_INVALID_KEY_FILE; + break; + } + } while (0); + + HKS_FREE_BLOB(hashBlob); + return ret; +} + +static uint8_t GetSlotCountLoop(const struct HksBlob *keyInfo) +{ + uint32_t slotCountPos = sizeof(uint16_t) + sizeof(uint8_t); /* offset version and keyCount */ + uint8_t slotCount = *(keyInfo->data + slotCountPos); /* keyInfo size has been checked */ + + return (slotCount < HKS_LOCAL_STORAGE_KEY_MAX_NUM) ? slotCount : HKS_LOCAL_STORAGE_KEY_MAX_NUM; +} + +static int32_t GetKeyAlias(const struct HksBlob *keyInfo, struct HksBlob *keyAlias) +{ + /* keyInfo size has been checked */ + uint32_t aliasSizePos = sizeof(uint8_t) + HKS_SEALING_NONCE_SIZE; + uint8_t aliasSize = *(keyInfo->data + aliasSizePos); + uint32_t aliasPos = aliasSizePos + sizeof(uint8_t); + + if ((aliasSize == 0) || (aliasSize > HKS_MAX_KEY_ALIAS_LEN)) { + HKS_LOG_E("invalid key alias size, size = %u", aliasSize); + return HKS_ERROR_INVALID_KEY_FILE; + } + + uint8_t *tmpBuf = (uint8_t *)HksMalloc(aliasSize); + if (tmpBuf == NULL) { + HKS_LOG_E("malloc failed"); + return HKS_ERROR_MALLOC_FAIL; + } + + (void)memcpy_s(tmpBuf, aliasSize, keyInfo->data + aliasPos, aliasSize); + keyAlias->size = aliasSize; + keyAlias->data = tmpBuf; + return HKS_SUCCESS; +} + +static int32_t UpgradeSingleKeyInfo(const struct HksBlob *keyInfo) +{ + char *processName = NULL; + int32_t ret = HksGetProcessName(&processName); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get process name failed"); + return HKS_ERROR_INTERNAL_ERROR; + } + struct HksBlob processNameBlob = { strlen(processName), (uint8_t *)processName }; + + struct HksBlob keyAlias = { 0, NULL }; + ret = GetKeyAlias(keyInfo, &keyAlias); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get key alias failed, ret = %d", ret); + return ret; + } + + struct HksBlob output = { MAX_KEY_SIZE, NULL }; + do { + output.data = (uint8_t *)HksMalloc(output.size); + if (output.data == NULL) { + HKS_LOG_E("malloc failed"); + ret = HKS_ERROR_MALLOC_FAIL; + break; + } + + ret = HksAccessUpgradeKeyInfo(&keyAlias, keyInfo, &output); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("access update key info faild"); + break; + } + + ret = HksStoreKeyBlob(&processNameBlob, &keyAlias, HKS_STORAGE_TYPE_KEY, &output); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("store keyblob to storage failed, ret = %d", ret); + break; + } + } while (0); + + HKS_FREE_BLOB(keyAlias); + HKS_FREE_BLOB(output); + return ret; +} + +static bool IsBufferAllZero(uint8_t *buf, uint32_t len) +{ + for (uint32_t i = 0; i < len; i++) { + if (buf[i] != 0) { + return false; + } + } + return true; +} + +static int32_t UpgradeKeyStoreInfo(const struct HksBlob *keyInfo) +{ + uint8_t slotCountLoop = GetSlotCountLoop(keyInfo); + uint32_t slotShift = GetKeySlotLen(); + uint8_t *tmp = keyInfo->data + GetHeaderLen(); /* keyInfo size has been checked lager than header len */ + int32_t ret = HKS_SUCCESS; + + /* Ensure that the number of cycles is within the range of keyinfo size */ + for (uint8_t i = 0; i < slotCountLoop; ++i) { + if (IsBufferAllZero(tmp, slotShift)) { /* current key slot all zero, no need update */ + tmp += slotShift; + continue; + } + + struct HksBlob key = { slotShift, tmp }; + ret = UpgradeSingleKeyInfo(&key); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("update the [%u]st key failed, ret = %d", i, ret); + break; + } + tmp += slotShift; + } + + return ret; +} + +static int32_t UpgradeKeyStoreFiles(void) +{ + struct HksBlob keyInfo = { 0, NULL }; + int32_t ret = GetOldVersionKeyStoreBuf(&keyInfo); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get old version key info failed"); + return ret; + } + + do { + ret = CheckKeyStoreHeaderValid(&keyInfo); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("key store file header invalid, ret = %d", ret); + break; + } + + ret = UpgradeKeyStoreInfo(&keyInfo); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("update key store info failed, ret = %d", ret); + break; + } + } while (0); + + HKS_FREE_BLOB(keyInfo); + return ret; +} + +int32_t HksUpgradeStorageData(void) +{ + bool isOldKeyStoreFileExist = HksOldVersionIsFileExist(HKS_KEY_STORE_FILE_NAME); + if (!isOldKeyStoreFileExist) { + HKS_LOG_D("old key store file not exist, no need upgrading process."); + return HKS_SUCCESS; + } + + int32_t ret; +#ifndef _HARDWARE_ROOT_KEY_ + ret = UpgradeRootKeyMaterialFile(); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("update root key material file failed, ret = %d", ret); + return (ret == HKS_ERROR_UPDATE_ROOT_KEY_MATERIAL_FAIL) ? ret : HKS_SUCCESS; + } +#endif + + do { +#ifndef _HARDWARE_ROOT_KEY_ + /* init rkc and update key store files, if process failed, need roolback all new files */ + ret = HksAccessInitialize(); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("init rkc failed, ret = %d", ret); + break; + } +#endif +#ifdef _STORAGE_LITE_ + ret = HksLoadFileToBuffer(); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("load file to buffer failed, ret = %d", ret); + break; + } +#endif + ret = UpgradeKeyStoreFiles(); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("update key store files failed, ret = %d", ret); + break; + } + HKS_LOG_I("upgrading key info files success"); + + if (RemoveOldVersionFiles() != HKS_SUCCESS) { + HKS_LOG_E("remove old key store files failed, ret = %d", ret); /* add log, no proccess error code */ + } + } while (0); + + if (ret != HKS_SUCCESS) { + HKS_LOG_E("update storage data failed, need delete new files, ret = %d", ret); + if (RollBackNewVersionFiles() != HKS_SUCCESS) { + HKS_LOG_D("rollback new files failed"); /* add log, no proccess error code */ + } + } + return ret; +} + +int32_t HksDestroyOldVersionFiles(void) +{ + return RemoveOldVersionFiles(); +} +#endif /* HKS_SUPPORT_UPGRADE_STORAGE_DATA */ +#endif /* _CUT_AUTHENTICATE_ */ \ No newline at end of file diff --git a/services/huks_standard/huks_service/main/os_dependency/BUILD.gn b/services/huks_standard/huks_service/main/os_dependency/BUILD.gn index 3d070b22..a7867304 100644 --- a/services/huks_standard/huks_service/main/os_dependency/BUILD.gn +++ b/services/huks_standard/huks_service/main/os_dependency/BUILD.gn @@ -25,6 +25,11 @@ ohos_static_library("libhuks_service_os_dependency_standard_static") { "//utils/native/base/include", "//utils/system/safwk/native/include", ] + defines = [ + "L2_STANDARD", + "_HARDWARE_ROOT_KEY_", + "_HUKS_LOG_ENABLE_", + ] sources = [ "posix/hks_file_operator.c", "sa/hks_sa.cpp", diff --git a/services/huks_standard/huks_service/main/os_dependency/idl/BUILD.gn b/services/huks_standard/huks_service/main/os_dependency/idl/BUILD.gn index f899219d..6cc13974 100755 --- a/services/huks_standard/huks_service/main/os_dependency/idl/BUILD.gn +++ b/services/huks_standard/huks_service/main/os_dependency/idl/BUILD.gn @@ -25,6 +25,11 @@ ohos_static_library("libhuks_service_idl_standard_static") { "//utils/native/base/include", "//base/security/huks/services/huks_standard/huks_engine/main/core/include", ] + defines = [ + "L2_STANDARD", + "_HARDWARE_ROOT_KEY_", + "_HUKS_LOG_ENABLE_", + ] sources = [ "ipc/hks_ipc_serialization.c", "ipc/hks_ipc_service.c", diff --git a/services/huks_standard/huks_service/main/os_dependency/idl/ipc/hks_ipc_serialization.h b/services/huks_standard/huks_service/main/os_dependency/idl/ipc/hks_ipc_serialization.h index 857ed976..4d1bf677 100644 --- a/services/huks_standard/huks_service/main/os_dependency/idl/ipc/hks_ipc_serialization.h +++ b/services/huks_standard/huks_service/main/os_dependency/idl/ipc/hks_ipc_serialization.h @@ -16,7 +16,7 @@ #ifndef HKS_IPC_SERIALIZATION_H #define HKS_IPC_SERIALIZATION_H -#include "hks_type.h" +#include "hks_type_inner.h" #ifdef __cplusplus extern "C" { diff --git a/services/huks_standard/huks_service/main/os_dependency/idl/ipc/hks_ipc_service.h b/services/huks_standard/huks_service/main/os_dependency/idl/ipc/hks_ipc_service.h index 5e1cd421..793fee96 100644 --- a/services/huks_standard/huks_service/main/os_dependency/idl/ipc/hks_ipc_service.h +++ b/services/huks_standard/huks_service/main/os_dependency/idl/ipc/hks_ipc_service.h @@ -16,85 +16,85 @@ #ifndef HKS_IPC_SERVICE_H #define HKS_IPC_SERVICE_H -#include "hks_type.h" +#include "hks_type_inner.h" #ifdef __cplusplus extern "C" { #endif -void HksIpcServiceProvision(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceProvision(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceProvisionVerify(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceProvisionVerify(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceGenerateKey(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceGenerateKey(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceImportKey(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceImportKey(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceExportPublicKey(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceExportPublicKey(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceDeleteKey(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceDeleteKey(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceGetKeyParamSet(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceGetKeyParamSet(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceKeyExist(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceKeyExist(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceGenerateRandom(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceGenerateRandom(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceSign(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceSign(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceSignInit(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceSignInit(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceSignUpdate(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceSignUpdate(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceSignFinal(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceSignFinal(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceVerify(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceVerify(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceVerifyInit(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceVerifyInit(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceVerifyUpdate(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceVerifyUpdate(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceVerifyFinal(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceVerifyFinal(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceEncrypt(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceEncrypt(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceEncryptInit(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceEncryptInit(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceEncryptUpdate(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceEncryptUpdate(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceEncryptFinal(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceEncryptFinal(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceDecrypt(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceDecrypt(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceDecryptInit(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceDecryptInit(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceDecryptUpdate(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceDecryptUpdate(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceDecryptFinal(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceDecryptFinal(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceAgreeKey(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceAgreeKey(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceDeriveKey(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceDeriveKey(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceMac(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceMac(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceMacInit(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceMacInit(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceMacUpdate(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceMacUpdate(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceMacFinal(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceMacFinal(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceGetKeyInfoList(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceGetKeyInfoList(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceAttestKey(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceAttestKey(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceGetCertificateChain(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceGetCertificateChain(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceWrapKey(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceWrapKey(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceUnwrapKey(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceUnwrapKey(const struct HksBlob *srcData, const uint8_t *context); -void HksIpcServiceSignWithDeviceKey(const struct HksBlob *msg, const uint8_t *context); +void HksIpcServiceSignWithDeviceKey(const struct HksBlob *srcData, const uint8_t *context); void HksIpcServiceExportTrustCerts(const struct HksBlob *srcData, const uint8_t *context); diff --git a/services/huks_standard/huks_service/main/os_dependency/idl/ipc/hks_response.cpp b/services/huks_standard/huks_service/main/os_dependency/idl/ipc/hks_response.cpp index 89768649..f51c7a17 100755 --- a/services/huks_standard/huks_service/main/os_dependency/idl/ipc/hks_response.cpp +++ b/services/huks_standard/huks_service/main/os_dependency/idl/ipc/hks_response.cpp @@ -24,7 +24,7 @@ #include "hks_log.h" #include "hks_mem.h" -#include "hks_type.h" +#include "hks_type_inner.h" using namespace OHOS; diff --git a/services/huks_standard/huks_service/main/os_dependency/idl/ipc/hks_response.h b/services/huks_standard/huks_service/main/os_dependency/idl/ipc/hks_response.h index 9fc9084d..61a102a8 100644 --- a/services/huks_standard/huks_service/main/os_dependency/idl/ipc/hks_response.h +++ b/services/huks_standard/huks_service/main/os_dependency/idl/ipc/hks_response.h @@ -16,7 +16,7 @@ #ifndef HKS_RESPONSE_H #define HKS_RESPONSE_H -#include "hks_type.h" +#include "hks_type_inner.h" #ifdef __cplusplus extern "C" { diff --git a/services/huks_standard/huks_service/main/os_dependency/idl/passthrough/hks_passthrough_access.c b/services/huks_standard/huks_service/main/os_dependency/idl/passthrough/hks_passthrough_access.c index 426a8ad1..507269db 100755 --- a/services/huks_standard/huks_service/main/os_dependency/idl/passthrough/hks_passthrough_access.c +++ b/services/huks_standard/huks_service/main/os_dependency/idl/passthrough/hks_passthrough_access.c @@ -13,9 +13,16 @@ * limitations under the License. */ +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + #include "hks_access.h" #include "hks_core_service.h" +#ifndef _CUT_AUTHENTICATE_ int32_t HksAccessGenerateKey(const struct HksBlob *keyBlob, const struct HksParamSet *paramSetIn, const struct HksBlob *keyIn, struct HksBlob *keyOut) { @@ -51,11 +58,6 @@ int32_t HksAccessCheckKeyValidity(const struct HksParamSet *paramSet, const stru return HksCheckKeyValidity(paramSet, key); } -int32_t HksAccessGenerateRandom(const struct HksParamSet *paramSet, struct HksBlob *random) -{ - return HksCoreGenerateRandom(paramSet, random); -} - int32_t HksAccessImportKey(const struct HksBlob *keyAlias, const struct HksBlob *key, const struct HksParamSet *paramSet, struct HksBlob *keyOut) { @@ -108,3 +110,30 @@ int32_t HksAccessProcessFinal(uint32_t msgId, uint64_t operationHandle, const st { return 0; } + +int32_t HksAccessRefresh(void) +{ + return HksCoreRefreshKeyInfo(); +} + +#ifdef _STORAGE_LITE_ +int32_t HksAccessCalcHeaderMac(const struct HksParamSet *paramSet, const struct HksBlob *salt, + const struct HksBlob *srcData, struct HksBlob *mac) +{ + return HksCoreCalcMacHeader(paramSet, salt, srcData, mac); +} +#endif + +#ifdef HKS_SUPPORT_UPGRADE_STORAGE_DATA +int32_t HksAccessUpgradeKeyInfo(const struct HksBlob *keyAlias, const struct HksBlob *keyInfo, struct HksBlob *keyOut) +{ + return HksCoreUpgradeKeyInfo(keyAlias, keyInfo, keyOut); +} + +#endif +#endif /* _CUT_AUTHENTICATE_ */ + +int32_t HksAccessGenerateRandom(const struct HksParamSet *paramSet, struct HksBlob *random) +{ + return HksCoreGenerateRandom(paramSet, random); +} \ No newline at end of file diff --git a/services/huks_standard/huks_service/main/os_dependency/posix/hks_file_operator.c b/services/huks_standard/huks_service/main/os_dependency/posix/hks_file_operator.c index 225146df..5384b165 100755 --- a/services/huks_standard/huks_service/main/os_dependency/posix/hks_file_operator.c +++ b/services/huks_standard/huks_service/main/os_dependency/posix/hks_file_operator.c @@ -13,6 +13,12 @@ * limitations under the License. */ +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + #include "hks_file_operator.h" #include @@ -20,6 +26,7 @@ #include #include #include +#include "securec.h" #include "hks_log.h" #include "hks_mem.h" @@ -222,6 +229,14 @@ int32_t HksIsFileExist(const char *path, const char *fileName) return ret; } +int32_t HksIsDirExist(const char *path) +{ + if (path == NULL) { + return HKS_ERROR_NULL_POINTER; + } + return IsFileExist(path); +} + int32_t HksMakeDir(const char *path) { return mkdir(path, S_IRWXU); @@ -248,13 +263,42 @@ int32_t HksGetDirFile(void *dirp, struct HksFileDirentInfo *direntInfo) continue; } - direntInfo->fileName = dire->d_name; + uint32_t len = strlen(dire->d_name); + if (memcpy_s(direntInfo->fileName, sizeof(direntInfo->fileName) - 1, dire->d_name, len) != EOK) { + return HKS_ERROR_BAD_STATE; + } + direntInfo->fileName[len] = '\0'; return HKS_SUCCESS; } return HKS_ERROR_NOT_EXIST; } +int32_t HksGetStoragePath(enum HksStoragePathType pathType, char *path, uint32_t *len) +{ + if ((path == NULL) || (len == NULL) || (*len <= 1)) { + return HKS_ERROR_INVALID_ARGUMENT; + } + errno_t ret; + uint32_t pathLen; + if (pathType == HKS_STORAGE_MAIN_PATH) { + pathLen = strlen(HKS_KEY_STORE_PATH); + ret = memcpy_s(path, *len - 1, HKS_KEY_STORE_PATH, pathLen); + } else if (pathType == HKS_STORAGE_BACKUP_PATH) { + pathLen = strlen(HKS_KEY_STORE_BAK_PATH); + ret = memcpy_s(path, *len - 1, HKS_KEY_STORE_BAK_PATH, pathLen); + } else { + return HKS_ERROR_INVALID_ARGUMENT; + } + if (ret != EOK) { + HKS_LOG_E("memcpy failed"); + return HKS_ERROR_BAD_STATE; + } + path[pathLen] = '\0'; + *len = pathLen + 1; + return HKS_SUCCESS; +} + int32_t HksRemoveDir(const char *dirPath) { struct stat fileStat; diff --git a/services/huks_standard/huks_service/main/os_dependency/posix/hks_file_operator_lite.c b/services/huks_standard/huks_service/main/os_dependency/posix/hks_file_operator_lite.c new file mode 100644 index 00000000..be430ecc --- /dev/null +++ b/services/huks_standard/huks_service/main/os_dependency/posix/hks_file_operator_lite.c @@ -0,0 +1,492 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifdef HKS_CONFIG_FILE +#include HKS_CONFIG_FILE +#else +#include "hks_config.h" +#endif + +#include "hks_file_operator.h" + +#ifndef _STORAGE_LITE_ +#include +#include +#include +#include +#include + +/* use product definitions temporarily */ +#define DEFAULT_FILE_PERMISSION 0666 +#else + +#include + +#endif /* _STORAGE_LITE_ */ + +#include "securec.h" + +#include "hks_log.h" +#include "hks_mem.h" + +#ifndef _CUT_AUTHENTICATE_ +static int32_t GetFileName(const char *path, const char *fileName, char *fullFileName, uint32_t fullFileNameLen) +{ + if (path != NULL) { + if (strncpy_s(fullFileName, fullFileNameLen, path, strlen(path)) != EOK) { + return HKS_ERROR_INTERNAL_ERROR; + } + + if (path[strlen(path) - 1] != '/') { + if (strncat_s(fullFileName, fullFileNameLen, "/", strlen("/")) != EOK) { + return HKS_ERROR_INTERNAL_ERROR; + } + } + + if (strncat_s(fullFileName, fullFileNameLen, fileName, strlen(fileName)) != EOK) { + return HKS_ERROR_INTERNAL_ERROR; + } + } else { + if (strncpy_s(fullFileName, fullFileNameLen, fileName, strlen(fileName)) != EOK) { + return HKS_ERROR_INTERNAL_ERROR; + } + } + + return HKS_SUCCESS; +} + +static int32_t GetFullFileName(const char *path, const char *fileName, char **fullFileName) +{ + uint32_t nameLen = HKS_MAX_FILE_NAME_LEN; + char *tmpFileName = (char *)HksMalloc(nameLen); + if (tmpFileName == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + (void)memset_s(tmpFileName, nameLen, 0, nameLen); + + int32_t ret = GetFileName(path, fileName, tmpFileName, nameLen); + if (ret != HKS_SUCCESS) { + HKS_LOG_E("get full fileName failed"); + HKS_FREE_PTR(tmpFileName); + return ret; + } + + *fullFileName = tmpFileName; + return HKS_SUCCESS; +} + +#ifndef _STORAGE_LITE_ +static int32_t IsFileExist(const char *fileName) +{ + struct stat fileStat; + int32_t ret = stat(fileName, &fileStat); + if (ret == -1) { + if (errno == ENOENT) { + return HKS_ERROR_NOT_EXIST; + } else { + HKS_LOG_E("file stat failed, errno = 0x%x", errno); + return HKS_ERROR_OPEN_FILE_FAIL; + } + } + + return HKS_SUCCESS; +} + +static uint32_t FileRead(const char *fileName, uint32_t offset, uint8_t *buf, uint32_t len) +{ + (void)offset; + int32_t fd = open(fileName, O_RDONLY); + if (fd < 0) { + HKS_LOG_E("failed to open file, errno = 0x%x", errno); + return 0; + } + + int32_t size = read(fd, buf, len); + close(fd); + if (size < 0) { + HKS_LOG_E("failed to read file, errno = 0x%x", errno); + return 0; + } + + return (uint32_t)size; +} + +static uint32_t FileSize(const char *fileName) +{ + struct stat fileStat; + (void)memset_s(&fileStat, sizeof(fileStat), 0, sizeof(fileStat)); + if (stat(fileName, &fileStat) != 0) { + HKS_LOG_E("file stat failed, errno = 0x%x", errno); + return 0; + } + + return (uint32_t)fileStat.st_size; +} + +static int32_t FileWrite(const char *fileName, uint32_t offset, const uint8_t *buf, uint32_t len) +{ + (void)offset; + int32_t fd = open(fileName, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR); + if (fd < 0) { + HKS_LOG_E("open file failed, errno = 0x%x", errno); + return HKS_ERROR_OPEN_FILE_FAIL; + } + + int32_t size = write(fd, buf, len); + close(fd); + if (size < 0) { + HKS_LOG_E("write file size failed, errno = 0x%x", errno); + return HKS_ERROR_WRITE_FILE_FAIL; + } + + return HKS_SUCCESS; +} + +static int32_t FileRemove(const char *fileName) +{ + struct stat fileStat; + int32_t ret = stat(fileName, &fileStat); + if (ret == -1) { + if (errno == ENOENT) { + return HKS_SUCCESS; /* if file not exist, return ok */ + } else { + HKS_LOG_E("file stat failed, errno = 0x%x", errno); + return HKS_ERROR_OPEN_FILE_FAIL; + } + } + + if (S_ISDIR(fileStat.st_mode)) { + return HKS_ERROR_INVALID_ARGUMENT; /* FileRemove func only care about files. */ + } + + if (unlink(fileName) != 0) { + HKS_LOG_E("remove file failed, errno = 0x%x", errno); + return HKS_ERROR_REMOVE_FILE_FAIL; + } + + return HKS_SUCCESS; +} + +int32_t HksIsDirExist(const char *path) +{ + if (path == NULL) { + return HKS_ERROR_NULL_POINTER; + } + return IsFileExist(path); +} + +int32_t HksMakeDir(const char *path) +{ + return mkdir(path, DEFAULT_FILE_PERMISSION); +} + +void *HksOpenDir(const char *path) +{ + return (void *)opendir(path); +} + +int32_t HksCloseDir(void *dirp) +{ + return closedir((DIR *)dirp); +} + +int32_t HksGetDirFile(void *dirp, struct HksFileDirentInfo *direntInfo) +{ + DIR *dir = (DIR *)dirp; + struct dirent *dire = readdir(dir); + + while (dire != NULL) { + if (dire->d_type != DT_REG) { /* only care about files. */ + dire = readdir(dir); + continue; + } + + uint32_t len = strlen(dire->d_name); + if (memcpy_s(direntInfo->fileName, sizeof(direntInfo->fileName) - 1, dire->d_name, len) != EOK) { + return HKS_ERROR_BAD_STATE; + } + direntInfo->fileName[len] = '\0'; + return HKS_SUCCESS; + } + + return HKS_ERROR_NOT_EXIST; +} + +int32_t HksGetStoragePath(enum HksStoragePathType pathType, char *path, uint32_t *len) +{ + if ((path == NULL) || (len == NULL) || (*len <= 1)) { + return HKS_ERROR_INVALID_ARGUMENT; + } + errno_t ret; + uint32_t pathLen; + if (pathType == HKS_STORAGE_MAIN_PATH) { + pathLen = strlen(HKS_KEY_STORE_PATH); + ret = memcpy_s(path, *len - 1, HKS_KEY_STORE_PATH, pathLen); + } else if (pathType == HKS_STORAGE_BACKUP_PATH) { + pathLen = strlen(HKS_KEY_STORE_BAK_PATH); + ret = memcpy_s(path, *len - 1, HKS_KEY_STORE_BAK_PATH, pathLen); + } else { + return HKS_ERROR_INVALID_ARGUMENT; + } + if (ret != EOK) { + HKS_LOG_E("memcpy failed"); + return HKS_ERROR_BAD_STATE; + } + path[pathLen] = '\0'; + *len = pathLen + 1; + return HKS_SUCCESS; +} + +int32_t HksRemoveDir(const char *dirPath) +{ + struct stat fileStat; + int32_t ret = stat(dirPath, &fileStat); + if (ret != 0) { + HKS_LOG_E("file stat failed"); + return HKS_FAILURE; + } + + if (S_ISDIR(fileStat.st_mode) == false) { + HKS_LOG_E("path is not dir"); + return HKS_FAILURE; + } + + DIR *dir = opendir(dirPath); + if (dir == NULL) { + HKS_LOG_E("open dir failed"); + return HKS_ERROR_OPEN_FILE_FAIL; + } + + struct dirent *dire = readdir(dir); + while (dire != NULL) { + if (dire->d_type == DT_REG) { /* only care about files. */ + ret = HksFileRemove(dirPath, dire->d_name); + if (ret != HKS_SUCCESS) { /* Continue to delete remaining files */ + HKS_LOG_E("remove file failed when remove dir files, ret = %d.", ret); + } + } + dire = readdir(dir); + } + + closedir(dir); + return HKS_SUCCESS; +} +#else +static int32_t IsFileExist(const char *fileName) +{ + unsigned int fileSize; + int32_t ret = UtilsFileStat(fileName, &fileSize); + if (ret < 0) { + return HKS_ERROR_NOT_EXIST; + } + return HKS_SUCCESS; +} + +static uint32_t FileRead(const char *fileName, uint32_t offset, uint8_t *buf, uint32_t len) +{ + /* now offset is 0, but we maybe extend hi1131 file interfaces in the future */ + if (offset != 0) { + return 0; + } + + unsigned int fileSize; + int32_t ret = UtilsFileStat(fileName, &fileSize); + if (ret < 0) { + HKS_LOG_E("stat file failed, errno = 0x%x", ret); + return 0; + } + + if (len > fileSize) { + HKS_LOG_E("read data over file size!\n, file size = %d\n, buf len = %d\n", fileSize, len); + return 0; + } + + int fd = UtilsFileOpen(fileName, O_RDONLY_FS, 0); + if (fd < 0) { + HKS_LOG_E("failed to open file, errno = 0x%x", fd); + return 0; + } + + ret = UtilsFileRead(fd, (char *)buf, len); + UtilsFileClose(fd); + if (ret < 0) { + HKS_LOG_E("failed to read file, errno = 0x%x", ret); + return 0; + } + + return len; +} + +static int32_t FileWrite(const char *fileName, uint32_t offset, const uint8_t *buf, uint32_t len) +{ + /* now offset is 0, but we maybe extend hi1131 file interfaces in the future */ + if (offset != 0) { + return HKS_ERROR_INVALID_ARGUMENT; + } + + int fd = UtilsFileOpen(fileName, O_CREAT_FS | O_TRUNC_FS | O_RDWR_FS, 0); + if (fd < 0) { + HKS_LOG_E("failed to open key file, errno = 0x%x\n", fd); + return HKS_ERROR_OPEN_FILE_FAIL; + } + + int32_t ret = UtilsFileWrite(fd, (const char*)buf, len); + (void)UtilsFileClose(fd); + if (ret < 0) { + HKS_LOG_E("failed to write key file, errno = 0x%x\n", ret); + return HKS_ERROR_WRITE_FILE_FAIL; + } + + return HKS_SUCCESS; +} + +static uint32_t FileSize(const char *fileName) +{ + unsigned int fileSize; + int32_t ret = UtilsFileStat(fileName, &fileSize); + if (ret < 0) { + HKS_LOG_E("stat file failed, errno = 0x%x", ret); + return 0; + } + return fileSize; +} + +static int32_t FileRemove(const char *fileName) +{ + int32_t ret = UtilsFileDelete(fileName); + if (ret < 0) { + HKS_LOG_E("remove file failed"); + return HKS_ERROR_REMOVE_FILE_FAIL; + } + return HKS_SUCCESS; +} + +#endif + +uint32_t HksFileRead(const char *path, const char *fileName, uint32_t offset, uint8_t *buf, uint32_t len) +{ + if ((fileName == NULL) || (buf == NULL) || (len == 0)) { + return 0; + } + + char *fullFileName = NULL; + int32_t ret = GetFullFileName(path, fileName, &fullFileName); + if (ret != HKS_SUCCESS) { + return 0; + } + + uint32_t size = FileRead(fullFileName, offset, buf, len); + HKS_FREE_PTR(fullFileName); + return size; +} + +int32_t HksFileWrite(const char *path, const char *fileName, uint32_t offset, const uint8_t *buf, uint32_t len) +{ + if ((fileName == NULL) || (buf == NULL) || (len == 0)) { + return HKS_ERROR_INVALID_ARGUMENT; + } + + char *fullFileName = NULL; + int32_t ret = GetFullFileName(path, fileName, &fullFileName); + if (ret != HKS_SUCCESS) { + return ret; + } + + ret = FileWrite(fullFileName, offset, buf, len); + HKS_FREE_PTR(fullFileName); + return ret; +} + +uint32_t HksFileSize(const char *path, const char *fileName) +{ + if (fileName == NULL) { + return 0; + } + + char *fullFileName = NULL; + int32_t ret = GetFullFileName(path, fileName, &fullFileName); + if (ret != HKS_SUCCESS) { + return 0; + } + + uint32_t size = FileSize(fullFileName); + HKS_FREE_PTR(fullFileName); + return size; +} + +int32_t HksIsFileExist(const char *path, const char *fileName) +{ + if (fileName == NULL) { + return HKS_ERROR_NULL_POINTER; + } + + char *fullFileName = NULL; + int32_t ret = GetFullFileName(path, fileName, &fullFileName); + if (ret != HKS_SUCCESS) { + return ret; + } + + ret = IsFileExist(fullFileName); + HKS_FREE_PTR(fullFileName); + return ret; +} + +int32_t HksFileRemove(const char *path, const char *fileName) +{ + if (fileName == NULL) { + return HKS_ERROR_INVALID_ARGUMENT; + } + + char *fullFileName = NULL; + int32_t ret = GetFullFileName(path, fileName, &fullFileName); + if (ret != HKS_SUCCESS) { + return ret; + } + + ret = FileRemove(fullFileName); + HKS_FREE_PTR(fullFileName); + return ret; +} + +#ifdef HKS_SUPPORT_UPGRADE_STORAGE_DATA +/* return < 0 error; > 0 realFileSize; == 0 no data */ +int32_t HksOldVersionFileRead(const char *fileName, uint32_t offset, uint8_t *buf, uint32_t len) +{ + HKS_LOG_D("piling"); + return HKS_ERROR_NOT_SUPPORTED; +} + +int32_t HksOldVersionFileRemove(const char *fileName) +{ + HKS_LOG_D("piling"); + return HKS_ERROR_NOT_SUPPORTED; +} + +/* return < 0 error; >= 0 realFileSize */ +int32_t HksOldVersionFileSize(const char *fileName) +{ + HKS_LOG_D("piling"); + return HKS_ERROR_NOT_SUPPORTED; +} + +/* return true, exist; false not exist */ +bool HksOldVersionIsFileExist(const char *fileName) +{ + HKS_LOG_D("piling"); + return false; +} +#endif + +#endif /* _CUT_AUTHENTICATE_ */ diff --git a/test/BUILD.gn b/test/BUILD.gn new file mode 100644 index 00000000..54e759db --- /dev/null +++ b/test/BUILD.gn @@ -0,0 +1,21 @@ +# +# Copyright (c) 2021 Huawei Device Co., Ltd. +# 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. +# +group("huks_new_test") { + if (ohos_kernel_type == "liteos_m") { + deps = [ "unittest/src/liteos_m_adapter:huks_new_test" ] + } else { + deps = [ "unittest/src/liteos_a_adapter:unittest" ] + } +} diff --git a/test/unittest/src/common/BUILD.gn b/test/unittest/src/common/BUILD.gn new file mode 100644 index 00000000..6f8e7a76 --- /dev/null +++ b/test/unittest/src/common/BUILD.gn @@ -0,0 +1,55 @@ +# +# Copyright (c) 2020 Huawei Device Co., Ltd. +# 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. +# + +config("hilog_dir") { + include_dirs = + [ "//base/hiviewdfx/hilog_lite/interfaces/native/innerkits/hilog/" ] +} +config("hilog_lite_dir") { + include_dirs = + [ "//base/hiviewdfx/hilog_lite/interfaces/native/kits/hilog_lite/" ] +} + +config("huks_test_common") { + include_dirs = [ + "//base/security/huks/interfaces/innerkits/huks_standard/main/include", + "include", + ] +} + +static_library("huks_new_test_common") { + sources = [ + "hks_test_aes.c", + "hks_test_api_performance.c", + "hks_test_cipher.c", + "hks_test_common.c", + "hks_test_curve25519.c", + "hks_test_file_operator.c", + "hks_test_log.c", + "hks_test_mem.c", + ] + + deps = [] + + configs += [ ":huks_test_common" ] + + if (ohos_kernel_type == "liteos_m") { + configs += [ ":hilog_lite_dir" ] + deps += [ "//base/hiviewdfx/hilog_lite/frameworks/mini:hilog_lite" ] + } else { + configs += [ ":hilog_dir" ] + deps += [ "//base/hiviewdfx/hilog_lite/frameworks/featured:hilog_shared" ] + } +} diff --git a/test/unittest/src/common/hks_test_aes.c b/test/unittest/src/common/hks_test_aes.c new file mode 100644 index 00000000..f6b4c705 --- /dev/null +++ b/test/unittest/src/common/hks_test_aes.c @@ -0,0 +1,588 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include "hks_test_aes.h" +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_common.h" +#include "hks_test_log.h" + +#define TEST_PLAIN_TEST "This is a plain text! Hello world and thanks for watching AES^^" +#define TEST_AES_12 12 +#define TEST_AES_16 16 +#define TEST_AES_32 32 +#define TEST_AES_128 128 +#define TEST_AES_256 256 + +static uint8_t g_buffer[TEST_AES_256]; +static uint32_t g_bufferSize = TEST_AES_256; + +uint8_t g_nonce[TEST_AES_12] = "hahahahahah"; +uint8_t g_aad[TEST_AES_16] = "bababababababab"; +uint8_t g_iv[TEST_AES_16] = "aabaabaabaabaab"; + +static int32_t ConstructParamSetEncryptDecryptAesPre(uint32_t mode, uint32_t padding, bool isEncrypt, + struct HksParamSet **paramSet) +{ + int32_t ret = HksInitParamSet(paramSet); + if (ret != 0) { + HKS_TEST_LOG_E("HksAddParamInit failed!\n"); + return ret; + } + + do { + struct HksParam algParam = {0}; + algParam.tag = HKS_TAG_ALGORITHM; + algParam.uint32Param = HKS_ALG_AES; + ret = HksAddParams(*paramSet, (const struct HksParam *)&algParam, 1); + if (ret != 0) { + HKS_TEST_LOG_E("HksAddParam algParam failed!\n"); + break; + } + + struct HksParam modeParam = {0}; + modeParam.tag = HKS_TAG_BLOCK_MODE; + modeParam.uint32Param = mode; + ret = HksAddParams(*paramSet, (const struct HksParam *)&modeParam, 1); + if (ret != 0) { + HKS_TEST_LOG_E("HksAddParam algParam failed!\n"); + break; + } + + struct HksParam padParam = {0}; + padParam.tag = HKS_TAG_PADDING; + padParam.uint32Param = padding; + ret = HksAddParams(*paramSet, (const struct HksParam *)&padParam, 1); + if (ret != 0) { + HKS_TEST_LOG_E("HksAddParam algParam failed!\n"); + break; + } + + struct HksParam purposeParam = {0}; + purposeParam.tag = HKS_TAG_PURPOSE; + if (isEncrypt) { + purposeParam.uint32Param = HKS_KEY_PURPOSE_ENCRYPT; + } else { + purposeParam.uint32Param = HKS_KEY_PURPOSE_DECRYPT; + } + ret = HksAddParams(*paramSet, (const struct HksParam *)&purposeParam, 1); + if (ret != 0) { + HKS_TEST_LOG_E("HksAddParam algParam failed!\n"); + break; + } + } while (0); + return ret; +} + +static int32_t ConstructParamSetEncryptDecryptAesPost(uint32_t mode, struct HksParamSet **paramSet) +{ + int32_t ret; + do { + struct HksParam aadParam = {0}; + aadParam.tag = HKS_TAG_ASSOCIATED_DATA; + aadParam.blob.data = g_aad; + aadParam.blob.size = sizeof(g_aad); + ret = HksAddParams(*paramSet, (const struct HksParam *)&aadParam, 1); + if (ret != 0) { + HKS_TEST_LOG_E("HksAddParam aadParam failed!\n"); + break; + } + + if (mode == HKS_MODE_CBC) { + struct HksParam ivParam = {0}; + ivParam.tag = HKS_TAG_IV; + ivParam.blob.data = g_iv; + ivParam.blob.size = sizeof(g_iv); + ret = HksAddParams(*paramSet, (const struct HksParam *)&ivParam, 1); + if (ret != 0) { + HKS_TEST_LOG_E("HksAddParam ivParam failed!\n"); + break; + } + } else { + struct HksParam nonceParam = {0}; + nonceParam.tag = HKS_TAG_NONCE; + nonceParam.blob.data = g_nonce; + nonceParam.blob.size = sizeof(g_nonce); + ret = HksAddParams(*paramSet, (const struct HksParam *)&nonceParam, 1); + if (ret != 0) { + HKS_TEST_LOG_E("HksAddParam nonceParam failed!\n"); + break; + } + } + + ret = HksBuildParamSet(paramSet); + if (ret != 0) { + HKS_TEST_LOG_E("HksAddParamFinal failed!\n"); + break; + } + } while (0); + + return ret; +} + +static int32_t ConstructParamSetEncryptDecryptAes(uint32_t mode, uint32_t padding, bool isEncrypt, + struct HksParamSet **paramSet) +{ + int32_t ret = ConstructParamSetEncryptDecryptAesPre(mode, padding, isEncrypt, paramSet); + HKS_TEST_ASSERT(ret == 0); + ret = ConstructParamSetEncryptDecryptAesPost(mode, paramSet); + HKS_TEST_ASSERT(ret == 0); + return ret; +} + +#define TEST_KEY_AUTH_ID "This is a test auth id for generate ed25519 key, keyauthIdvalid!" +void GenerateBaseKey(const struct HksBlob *alias) +{ + HKS_TEST_LOG_I("Test_Aes_gen_by_derive BASEKEY!\n"); + struct HksParamSet *paramSet = NULL; + HKS_TEST_ASSERT(HksInitParamSet(¶mSet) == 0); + + struct HksBlob authId = { strlen(TEST_KEY_AUTH_ID), (uint8_t *)TEST_KEY_AUTH_ID }; + + struct HksParam tmpParams[] = { + { .tag = HKS_TAG_ALGORITHM, + .uint32Param = HKS_ALG_ED25519 }, + { .tag = HKS_TAG_KEY_SIZE, + .uint32Param = TEST_AES_256 }, + { .tag = HKS_TAG_PURPOSE, + .uint32Param = HKS_KEY_PURPOSE_SIGN | HKS_KEY_PURPOSE_VERIFY }, + { .tag = HKS_TAG_DIGEST, + .uint32Param = HKS_DIGEST_SHA512 }, + { .tag = HKS_TAG_PADDING, + .uint32Param = HKS_PADDING_NONE }, + { .tag = HKS_TAG_KEY_AUTH_ID, + .blob = authId }, + { .tag = HKS_TAG_KEY_GENERATE_TYPE, + .uint32Param = HKS_KEY_GENERATE_TYPE_AGREE }, /* no use */ + }; + + HKS_TEST_ASSERT(HksAddParams(paramSet, tmpParams, sizeof(tmpParams) / sizeof(tmpParams[0])) == 0); + HKS_TEST_ASSERT(HksBuildParamSet(¶mSet) == 0); + HKS_TEST_ASSERT(HksGenerateKey(alias, paramSet, NULL) == 0); + + HksFreeParamSet(¶mSet); +} + +#define TEST_AES_KEY_BASE_NAME_1 "test_aes_key_by_derive_base_name_ed25519_1" +#define TEST_AES_KEY_BASE_NAME_2 "test_aes_key_by_derive_base_name_ed25519_2" +#define TEST_AES_KEY_BASE_NAME_1_PUBKEY "test_aes_key_by_derive_base_name_ed25519_1_pubkey" +#define TEST_AES_KEY_BASE_NAME_2_PUBKEY "test_aes_key_by_derive_base_name_ed25519_2_pubkey" + +#define TEST_AES_KEY_AGREE_NAME1 "test_aes_key_by_agree_name_keyAlias1" +#define TEST_AES_KEY_AGREE_NAME2 "test_aes_key_by_agree_name_keyAlias2" + +static void PlainPubKey(const struct HksBlob *baseKey, const struct HksBlob *peerPubKey, + struct HksParamSet *paramSet) +{ + struct HksParam tmpParams[] = { + { .tag = HKS_TAG_ALGORITHM, + .uint32Param = HKS_ALG_AES }, + { .tag = HKS_TAG_KEY_SIZE, + .uint32Param = TEST_AES_256 }, + { .tag = HKS_TAG_PURPOSE, + .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, + { .tag = HKS_TAG_BLOCK_MODE, + .uint32Param = HKS_MODE_GCM }, + { .tag = HKS_TAG_PADDING, + .uint32Param = HKS_PADDING_NONE }, + { .tag = HKS_TAG_KEY_GENERATE_TYPE, + .uint32Param = 0 }, + { .tag = HKS_TAG_AGREE_PRIVATE_KEY_ALIAS, + .blob = *baseKey }, + { .tag = HKS_TAG_AGREE_PUBLIC_KEY, + .blob = *peerPubKey }, + { .tag = HKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS, + .boolParam = false }, + { .tag = HKS_TAG_AGREE_ALG, + .uint32Param = HKS_ALG_ED25519 }, + }; + + HKS_TEST_ASSERT(HksAddParams(paramSet, tmpParams, sizeof(tmpParams) / sizeof(tmpParams[0])) == 0); +} + +static void SetKeyAliasTrue(const struct HksBlob *baseKey, const struct HksBlob *peerPubKey, + struct HksParamSet *paramSet) +{ + struct HksParam tmpParams[] = { + { .tag = HKS_TAG_ALGORITHM, + .uint32Param = HKS_ALG_AES }, + { .tag = HKS_TAG_KEY_SIZE, + .uint32Param = TEST_AES_256 }, + { .tag = HKS_TAG_PURPOSE, + .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, + { .tag = HKS_TAG_BLOCK_MODE, + .uint32Param = HKS_MODE_GCM }, + { .tag = HKS_TAG_PADDING, + .uint32Param = HKS_PADDING_NONE }, + { .tag = HKS_TAG_KEY_GENERATE_TYPE, + .uint32Param = 0 }, + { .tag = HKS_TAG_AGREE_PRIVATE_KEY_ALIAS, + .blob = *baseKey }, + { .tag = HKS_TAG_AGREE_PUBLIC_KEY_IS_KEY_ALIAS, + .boolParam = true }, + { .tag = HKS_TAG_AGREE_PUBLIC_KEY, + .blob = *peerPubKey }, + { .tag = HKS_TAG_AGREE_ALG, + .uint32Param = HKS_ALG_ED25519 }, + }; + + HKS_TEST_ASSERT(HksAddParams(paramSet, tmpParams, sizeof(tmpParams) / sizeof(tmpParams[0])) == 0); +} + +static void SetKeyAliasWrong(const struct HksBlob *baseKey, const struct HksBlob *peerPubKey, + struct HksParamSet *paramSet) +{ + struct HksParam tmpParams[] = { + { .tag = HKS_TAG_ALGORITHM, + .uint32Param = HKS_ALG_AES }, + { .tag = HKS_TAG_KEY_SIZE, + .uint32Param = TEST_AES_256 }, + { .tag = HKS_TAG_PURPOSE, + .uint32Param = HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT }, + { .tag = HKS_TAG_BLOCK_MODE, + .uint32Param = HKS_MODE_GCM }, + { .tag = HKS_TAG_PADDING, + .uint32Param = HKS_PADDING_NONE }, + { .tag = HKS_TAG_KEY_GENERATE_TYPE, + .uint32Param = 0 }, + { .tag = HKS_TAG_AGREE_PRIVATE_KEY_ALIAS, + .blob = *baseKey }, + { .tag = HKS_TAG_AGREE_PUBLIC_KEY, + .blob = *peerPubKey }, + { .tag = HKS_TAG_AGREE_ALG, + .uint32Param = HKS_ALG_ED25519 }, + }; + + HKS_TEST_ASSERT(HksAddParams(paramSet, tmpParams, sizeof(tmpParams) / sizeof(tmpParams[0])) == 0); +} + +static void GenerateAesAgreeKey(const struct HksBlob *alias, const struct HksBlob *baseKey, + const struct HksBlob *peerPubKey, bool isPlainPubKey, bool isSetKeyAliasTrue) +{ + HKS_TEST_LOG_I("Test_Aes_gen_by_agree key!\n"); + struct HksParamSet *paramSet = NULL; + HKS_TEST_ASSERT(HksInitParamSet(¶mSet) == 0); + + if (isPlainPubKey) { + PlainPubKey(baseKey, peerPubKey, paramSet); + } else { + if (isSetKeyAliasTrue) { + SetKeyAliasTrue(baseKey, peerPubKey, paramSet); + } else { + SetKeyAliasWrong(baseKey, peerPubKey, paramSet); + } + } + HKS_TEST_ASSERT(HksBuildParamSet(¶mSet) == 0); + HKS_TEST_ASSERT(HksGenerateKey(alias, paramSet, NULL) == 0); + HKS_TEST_LOG_I("End Test_Aes_gen_by_agree key!\n"); + + HksFreeParamSet(¶mSet); +} + +static void ExportPubKey(const struct HksBlob *alias, struct HksBlob *pubKey) +{ + HKS_TEST_ASSERT(HksExportPublicKey(alias, NULL, pubKey) == 0); +} + +static void ImportPubKey(const struct HksBlob *alias, const struct HksBlob *pubKey) +{ + HKS_TEST_LOG_I("Test_Import pubKey!\n"); + struct HksParamSet *paramSet = NULL; + HKS_TEST_ASSERT(HksInitParamSet(¶mSet) == 0); + + struct HksBlob authId = { strlen(TEST_KEY_AUTH_ID), (uint8_t *)TEST_KEY_AUTH_ID }; + + struct HksParam tmpParams[] = { + { .tag = HKS_TAG_ALGORITHM, + .uint32Param = HKS_ALG_ED25519 }, + { .tag = HKS_TAG_KEY_SIZE, + .uint32Param = TEST_AES_256 }, + { .tag = HKS_TAG_PURPOSE, + .uint32Param = HKS_KEY_PURPOSE_VERIFY }, + { .tag = HKS_TAG_DIGEST, + .uint32Param = HKS_DIGEST_SHA512 }, + { .tag = HKS_TAG_PADDING, + .uint32Param = HKS_PADDING_NONE }, + { .tag = HKS_TAG_KEY_AUTH_ID, + .blob = authId }, + { .tag = HKS_TAG_KEY_GENERATE_TYPE, + .uint32Param = HKS_KEY_GENERATE_TYPE_DEFAULT }, /* no use */ + }; + + HKS_TEST_ASSERT(HksAddParams(paramSet, tmpParams, sizeof(tmpParams) / sizeof(tmpParams[0])) == 0); + HKS_TEST_ASSERT(HksBuildParamSet(¶mSet) == 0); + HKS_TEST_ASSERT(HksImportKey(alias, paramSet, pubKey) == 0); + + HksFreeParamSet(¶mSet); +} + +#define TEST_AES_KEY_BASE_NAME "test_aes_key_by_derive_base_name_ed25519" +#define TEST_AES_KEY_DERIVE_NAME1 "test_aes_key_by_derive_name_keyAlias1" +#define TEST_AES_KEY_DERIVE_NAME2 "test_aes_key_by_derive_name_keyAlias2" +int32_t TestAes256ByAgree() +{ + HKS_TEST_LOG_I("enter"); + /* generate ed25519 key */ + struct HksBlob baseKeyAlias1 = { strlen(TEST_AES_KEY_BASE_NAME_1), (uint8_t *)TEST_AES_KEY_BASE_NAME_1 }; + GenerateBaseKey(&baseKeyAlias1); + + struct HksBlob baseKeyAlias2 = { strlen(TEST_AES_KEY_BASE_NAME_2), (uint8_t *)TEST_AES_KEY_BASE_NAME_2 }; + GenerateBaseKey(&baseKeyAlias2); + + uint8_t pubKey1[TEST_AES_128] = {0}; + uint8_t pubKey2[TEST_AES_128] = {0}; + struct HksBlob pubKeyBlob1 = { TEST_AES_128, pubKey1 }; + struct HksBlob pubKeyBlob2 = { TEST_AES_128, pubKey2 }; + ExportPubKey(&baseKeyAlias1, &pubKeyBlob1); + ExportPubKey(&baseKeyAlias2, &pubKeyBlob2); + + struct HksBlob pubKeyAlias1 = { + strlen(TEST_AES_KEY_BASE_NAME_1_PUBKEY), (uint8_t *)TEST_AES_KEY_BASE_NAME_1_PUBKEY + }; + struct HksBlob pubKeyAlias2 = { + strlen(TEST_AES_KEY_BASE_NAME_2_PUBKEY), (uint8_t *)TEST_AES_KEY_BASE_NAME_2_PUBKEY + }; + ImportPubKey(&pubKeyAlias1, &pubKeyBlob1); + ImportPubKey(&pubKeyAlias2, &pubKeyBlob2); + + /* generate aes key 1 */ + struct HksBlob aesKeyAlias1 = { strlen(TEST_AES_KEY_AGREE_NAME1), (uint8_t *)TEST_AES_KEY_AGREE_NAME1 }; + GenerateAesAgreeKey(&aesKeyAlias1, &baseKeyAlias1, &pubKeyAlias2, false, false); + + /* generate aes key 2 */ + struct HksBlob aesKeyAlias2 = { strlen(TEST_AES_KEY_DERIVE_NAME2), (uint8_t *)TEST_AES_KEY_DERIVE_NAME2 }; + GenerateAesAgreeKey(&aesKeyAlias2, &baseKeyAlias2, &pubKeyAlias1, false, false); + + /* encrypt by aes key 1 */ + struct HksParamSet *paramSet = NULL; + int32_t ret = ConstructParamSetEncryptDecryptAes(HKS_MODE_GCM, HKS_PADDING_NONE, true, ¶mSet); + HKS_TEST_ASSERT(ret == 0); + struct HksBlob plainText1 = { strlen(TEST_PLAIN_TEST) + 1, (uint8_t*)TEST_PLAIN_TEST }; + struct HksBlob cipherText1 = { TEST_AES_256, g_buffer }; + (void)memset_s(cipherText1.data, cipherText1.size, 0, cipherText1.size); + HKS_TEST_ASSERT(HksEncrypt(&aesKeyAlias1, paramSet, &plainText1, &cipherText1) == 0); + g_bufferSize = cipherText1.size; + + HksFreeParamSet(¶mSet); + + /* decrypt by aes key 2 */ + ret = ConstructParamSetEncryptDecryptAes(HKS_MODE_GCM, HKS_PADDING_NONE, false, ¶mSet); + HKS_TEST_ASSERT(ret == 0); + struct HksBlob cipherText = { g_bufferSize, g_buffer }; + uint8_t tmp[TEST_AES_256] = {0}; + struct HksBlob plainText = { TEST_AES_256, tmp }; + ret = HksDecrypt(&aesKeyAlias1, paramSet, &cipherText, &plainText); + HKS_TEST_ASSERT(ret == 0); + HKS_TEST_LOG_I("ConstructParamSetEncryptDecryptAes plainText: %s", plainText.data); + HksFreeParamSet(¶mSet); + + HksDeleteKey(&baseKeyAlias1, NULL); + HksDeleteKey(&baseKeyAlias2, NULL); + HksDeleteKey(&pubKeyAlias1, NULL); + HksDeleteKey(&pubKeyAlias2, NULL); + HksDeleteKey(&aesKeyAlias1, NULL); + HksDeleteKey(&aesKeyAlias2, NULL); + HKS_TEST_LOG_I("end"); + return ret; +} + +int32_t TestAes256ByAgree1() +{ + HKS_TEST_LOG_I("enter"); + + /* generate ed25519 key */ + struct HksBlob baseKeyAlias1 = { strlen(TEST_AES_KEY_BASE_NAME_1), (uint8_t *)TEST_AES_KEY_BASE_NAME_1 }; + GenerateBaseKey(&baseKeyAlias1); + + struct HksBlob baseKeyAlias2 = { strlen(TEST_AES_KEY_BASE_NAME_2), (uint8_t *)TEST_AES_KEY_BASE_NAME_2 }; + GenerateBaseKey(&baseKeyAlias2); + + uint8_t pubKey1[TEST_AES_128] = {0}; + uint8_t pubKey2[TEST_AES_128] = {0}; + struct HksBlob pubKeyBlob1 = { TEST_AES_128, pubKey1 }; + struct HksBlob pubKeyBlob2 = { TEST_AES_128, pubKey2 }; + ExportPubKey(&baseKeyAlias1, &pubKeyBlob1); + ExportPubKey(&baseKeyAlias2, &pubKeyBlob2); + + struct HksBlob pubKeyAlias1 = { + strlen(TEST_AES_KEY_BASE_NAME_1_PUBKEY), (uint8_t *)TEST_AES_KEY_BASE_NAME_1_PUBKEY + }; + struct HksBlob pubKeyAlias2 = { + strlen(TEST_AES_KEY_BASE_NAME_2_PUBKEY), (uint8_t *)TEST_AES_KEY_BASE_NAME_2_PUBKEY + }; + ImportPubKey(&pubKeyAlias1, &pubKeyBlob1); + ImportPubKey(&pubKeyAlias2, &pubKeyBlob2); + + /* generate aes key 1 */ + struct HksBlob aesKeyAlias1 = { strlen(TEST_AES_KEY_AGREE_NAME1), (uint8_t *)TEST_AES_KEY_AGREE_NAME1 }; + GenerateAesAgreeKey(&aesKeyAlias1, &baseKeyAlias1, &pubKeyAlias2, false, true); + + /* generate aes key 2 */ + struct HksBlob aesKeyAlias2 = { strlen(TEST_AES_KEY_DERIVE_NAME2), (uint8_t *)TEST_AES_KEY_DERIVE_NAME2 }; + GenerateAesAgreeKey(&aesKeyAlias2, &baseKeyAlias2, &pubKeyAlias1, false, true); + + /* encrypt by aes key 1 */ + struct HksParamSet *paramSet = NULL; + int32_t ret = ConstructParamSetEncryptDecryptAes(HKS_MODE_GCM, HKS_PADDING_NONE, true, ¶mSet); + HKS_TEST_ASSERT(ret == 0); + struct HksBlob plainText1 = { strlen(TEST_PLAIN_TEST) + 1, (uint8_t*)TEST_PLAIN_TEST }; + struct HksBlob cipherText1 = { TEST_AES_256, g_buffer }; + (void)memset_s(cipherText1.data, cipherText1.size, 0, cipherText1.size); + HKS_TEST_ASSERT(HksEncrypt(&aesKeyAlias1, paramSet, &plainText1, &cipherText1) == 0); + g_bufferSize = cipherText1.size; + + HksFreeParamSet(¶mSet); + + /* decrypt by aes key 2 */ + ret = ConstructParamSetEncryptDecryptAes(HKS_MODE_GCM, HKS_PADDING_NONE, false, ¶mSet); + HKS_TEST_ASSERT(ret == 0); + struct HksBlob cipherText = { g_bufferSize, g_buffer }; + uint8_t tmp[TEST_AES_256] = {0}; + struct HksBlob plainText = { TEST_AES_256, tmp }; + ret = HksDecrypt(&aesKeyAlias1, paramSet, &cipherText, &plainText); + HKS_TEST_ASSERT(ret == 0); + HKS_TEST_LOG_I("ConstructParamSetEncryptDecryptAes plainText: %s", plainText.data); + HksFreeParamSet(¶mSet); + + HksDeleteKey(&baseKeyAlias1, NULL); + HksDeleteKey(&baseKeyAlias2, NULL); + HksDeleteKey(&pubKeyAlias1, NULL); + HksDeleteKey(&pubKeyAlias2, NULL); + HksDeleteKey(&aesKeyAlias1, NULL); + HksDeleteKey(&aesKeyAlias2, NULL); + HKS_TEST_LOG_I("end"); + return ret; +} + +int32_t TestAes256ByAgree2() +{ + HKS_TEST_LOG_I("enter"); + /* generate ed25519 key */ + struct HksBlob baseKeyAlias1 = { strlen(TEST_AES_KEY_BASE_NAME_1), (uint8_t *)TEST_AES_KEY_BASE_NAME_1 }; + GenerateBaseKey(&baseKeyAlias1); + + struct HksBlob baseKeyAlias2 = { strlen(TEST_AES_KEY_BASE_NAME_2), (uint8_t *)TEST_AES_KEY_BASE_NAME_2 }; + GenerateBaseKey(&baseKeyAlias2); + + uint8_t pubKey1[TEST_AES_128] = {0}; + uint8_t pubKey2[TEST_AES_128] = {0}; + struct HksBlob pubKeyBlob1 = { TEST_AES_128, pubKey1 }; + struct HksBlob pubKeyBlob2 = { TEST_AES_128, pubKey2 }; + ExportPubKey(&baseKeyAlias1, &pubKeyBlob1); + ExportPubKey(&baseKeyAlias2, &pubKeyBlob2); + + /* generate aes key 1 */ + struct HksBlob aesKeyAlias1 = { strlen(TEST_AES_KEY_AGREE_NAME1), (uint8_t *)TEST_AES_KEY_AGREE_NAME1 }; + GenerateAesAgreeKey(&aesKeyAlias1, &baseKeyAlias1, &pubKeyBlob2, true, false); + + /* generate aes key 2 */ + struct HksBlob aesKeyAlias2 = { strlen(TEST_AES_KEY_DERIVE_NAME2), (uint8_t *)TEST_AES_KEY_DERIVE_NAME2 }; + GenerateAesAgreeKey(&aesKeyAlias2, &baseKeyAlias2, &pubKeyBlob1, true, false); + + /* encrypt by aes key 1 */ + struct HksParamSet *paramSet = NULL; + int32_t ret = ConstructParamSetEncryptDecryptAes(HKS_MODE_GCM, HKS_PADDING_NONE, true, ¶mSet); + HKS_TEST_ASSERT(ret == 0); + struct HksBlob plainText1 = { strlen(TEST_PLAIN_TEST) + 1, (uint8_t*)TEST_PLAIN_TEST }; + struct HksBlob cipherText1 = { TEST_AES_256, g_buffer }; + (void)memset_s(cipherText1.data, cipherText1.size, 0, cipherText1.size); + HKS_TEST_ASSERT(HksEncrypt(&aesKeyAlias1, paramSet, &plainText1, &cipherText1) == 0); + g_bufferSize = cipherText1.size; + + HksFreeParamSet(¶mSet); + + /* decrypt by aes key 2 */ + ret = ConstructParamSetEncryptDecryptAes(HKS_MODE_GCM, HKS_PADDING_NONE, false, ¶mSet); + HKS_TEST_ASSERT(ret == 0); + struct HksBlob cipherText = { g_bufferSize, g_buffer }; + uint8_t tmp[TEST_AES_256] = {0}; + struct HksBlob plainText = { TEST_AES_256, tmp }; + ret = HksDecrypt(&aesKeyAlias1, paramSet, &cipherText, &plainText); + HKS_TEST_ASSERT(ret == 0); + HKS_TEST_LOG_I("ConstructParamSetEncryptDecryptAes plainText: %s", plainText.data); + HksFreeParamSet(¶mSet); + + HksDeleteKey(&baseKeyAlias1, NULL); + HksDeleteKey(&baseKeyAlias2, NULL); + HksDeleteKey(&aesKeyAlias1, NULL); + HksDeleteKey(&aesKeyAlias2, NULL); + HKS_TEST_LOG_I("end"); + return ret; +} + +int32_t TestAes256ByLocal() +{ + HKS_TEST_LOG_I("enter"); + + /* generate aes key 1 */ + char testKey[TEST_AES_32]; + struct HksBlob keyBlob; + + for (int i = 0; i < TEST_AES_32; ++i) { + testKey[i] = i + TEST_AES_32; + } + + keyBlob.data = testKey; + keyBlob.size = sizeof(testKey); + + /* encrypt by aes key 1 */ + struct HksParamSet *paramSet = NULL; + struct HksParam algParam = { + .tag = HKS_TAG_IS_KEY_ALIAS, + .uint32Param = 0 + }; + + int32_t ret = ConstructParamSetEncryptDecryptAes(HKS_MODE_GCM, HKS_PADDING_NONE, true, ¶mSet); + HKS_TEST_ASSERT(ret == 0); + + ret = HksAddParams(paramSet, (const struct HksParam *)&algParam, 1); + if (ret != 0) { + HKS_TEST_LOG_E("HksAddParam algParam failed!\n"); + HksFreeParamSet(¶mSet); + return ret; + } + + struct HksBlob plainText1 = { strlen(TEST_PLAIN_TEST) + 1, (uint8_t*)TEST_PLAIN_TEST }; + struct HksBlob cipherText1 = { TEST_AES_256, g_buffer }; + (void)memset_s(cipherText1.data, cipherText1.size, 0, cipherText1.size); + HKS_TEST_ASSERT(HksEncrypt(&keyBlob, paramSet, &plainText1, &cipherText1) == 0); + g_bufferSize = cipherText1.size; + + HksFreeParamSet(¶mSet); + + /* decrypt by aes key 2 */ + ret = ConstructParamSetEncryptDecryptAes(HKS_MODE_GCM, HKS_PADDING_NONE, false, ¶mSet); + HKS_TEST_ASSERT(ret == 0); + algParam.tag = HKS_TAG_IS_KEY_ALIAS; + algParam.uint32Param = 0; + ret = HksAddParams(paramSet, (const struct HksParam *)&algParam, 1); + if (ret != 0) { + HKS_TEST_LOG_E("HksAddParam algParam failed!\n"); + HksFreeParamSet(¶mSet); + return ret; + } + + struct HksBlob cipherText = { g_bufferSize, g_buffer }; + uint8_t tmp[TEST_AES_256] = {0}; + struct HksBlob plainText = { TEST_AES_256, tmp }; + ret = HksDecrypt(&keyBlob, paramSet, &cipherText, &plainText); + HKS_TEST_ASSERT(ret == 0); + HKS_TEST_ASSERT(memcmp(plainText.data, plainText1.data, plainText.size) == 0); + HksFreeParamSet(¶mSet); + + HKS_TEST_LOG_I("end"); + return ret; +} + diff --git a/test/unittest/src/common/hks_test_api_performance.c b/test/unittest/src/common/hks_test_api_performance.c new file mode 100644 index 00000000..81641228 --- /dev/null +++ b/test/unittest/src/common/hks_test_api_performance.c @@ -0,0 +1,232 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include + +#include "hks_test_api_performance.h" +#include "hks_api.h" +#include "hks_param.h" + +#define USEC_MINT 1000 +#define USEC_UINT 1000000 + +int32_t HksGenerateKeyRun(const struct HksBlob *keyAlias, const struct HksParamSet *paramSetIn, + struct HksParamSet *paramSetOut, uint32_t performTimes) +{ + int32_t ret; + /* if keyAlias exist, the key will be generated and refreshed */ + for (uint32_t i = 0; i < performTimes; ++i) { + ret = HksGenerateKey(keyAlias, paramSetIn, paramSetOut); + if (ret != HKS_SUCCESS) { + return ret; + } + } + return HKS_SUCCESS; +} + +int32_t HksEncryptRun(const struct HksBlob *key, const struct HksParamSet *paramSet, + const struct HksBlob *plainText, struct HksBlob *cipherText, uint32_t performTimes) +{ + int32_t ret; + uint32_t oriCipherTestSize = 0; + if (cipherText != NULL) { + oriCipherTestSize = cipherText->size; + } + + for (uint32_t i = 0; i < performTimes; ++i) { + if (cipherText != NULL) { + (void)memset_s(cipherText->data, oriCipherTestSize, 0, oriCipherTestSize); + cipherText->size = oriCipherTestSize; + } + + ret = HksEncrypt(key, paramSet, plainText, cipherText); + if (ret != HKS_SUCCESS) { + return ret; + } + } + return HKS_SUCCESS; +} + +int32_t HksDecryptRun(const struct HksBlob *key, const struct HksParamSet *paramSet, + const struct HksBlob *cipherText, struct HksBlob *plainText, uint32_t performTimes) +{ + int32_t ret; + uint32_t oriPlainTextSize = 0; + if (plainText != NULL) { + oriPlainTextSize = plainText->size; + } + + for (uint32_t i = 0; i < performTimes; ++i) { + if (plainText != NULL) { + (void)memset_s(plainText->data, oriPlainTextSize, 0, oriPlainTextSize); + plainText->size = oriPlainTextSize; + } + ret = HksDecrypt(key, paramSet, cipherText, plainText); + if (ret != HKS_SUCCESS) { + return ret; + } + } + return HKS_SUCCESS; +} + +int32_t HksMacRun(const struct HksBlob *key, const struct HksParamSet *paramSet, + const struct HksBlob *srcData, struct HksBlob *mac, uint32_t performTimes) +{ + int32_t ret; + uint32_t oriMacSize = 0; + if (mac != NULL) { + oriMacSize = mac->size; + } + + for (uint32_t i = 0; i < performTimes; ++i) { + if (mac != NULL) { + (void)memset_s(mac->data, oriMacSize, 0, oriMacSize); + mac->size = oriMacSize; + } + ret = HksMac(key, paramSet, srcData, mac); + if (ret != HKS_SUCCESS) { + return ret; + } + } + return HKS_SUCCESS; +} + +int32_t HksDeriveKeyRun(const struct HksParamSet *paramSet, const struct HksBlob *masterKey, + struct HksBlob *derivedKey, uint32_t performTimes) +{ + int32_t ret; + uint32_t oriDerivedKeySize = 0; + if (derivedKey != NULL) { + oriDerivedKeySize = derivedKey->size; + } + + for (uint32_t i = 0; i < performTimes; ++i) { + if (derivedKey != NULL) { + (void)memset_s(derivedKey->data, oriDerivedKeySize, 0, oriDerivedKeySize); + derivedKey->size = oriDerivedKeySize; + } + ret = HksDeriveKey(paramSet, masterKey, derivedKey); + if (ret != HKS_SUCCESS) { + return ret; + } + } + return HKS_SUCCESS; +} + +int32_t HksDeleteKeyRun(const struct HksBlob *keyAlias, uint32_t performTimes) +{ + (void)performTimes; + return HksDeleteKey(keyAlias, NULL); +} + +int32_t HksKeyExistRun(const struct HksBlob *keyAlias, uint32_t performTimes) +{ + int32_t ret; + for (uint32_t i = 0; i < performTimes; ++i) { + ret = HksKeyExist(keyAlias, NULL); + if (ret != HKS_SUCCESS) { + return ret; + } + } + return HKS_SUCCESS; +} + +int32_t HksGenerateRandomRun(struct HksBlob *random, uint32_t performTimes) +{ + int32_t ret; + uint32_t oriRandomSize = 0; + if (random != NULL) { + oriRandomSize = random->size; + } + + for (uint32_t i = 0; i < performTimes; ++i) { + if (random != NULL) { + (void)memset_s(random->data, oriRandomSize, 0, oriRandomSize); + random->size = oriRandomSize; + } + ret = HksGenerateRandom(NULL, random); + if (ret != HKS_SUCCESS) { + return ret; + } + } + return HKS_SUCCESS; +} + +int32_t HksAgreeKeyRun(const struct HksParamSet *paramSet, const struct HksBlob *privateKey, + const struct HksBlob *peerPublicKey, struct HksBlob *agreedKey, uint32_t performTimes) +{ + int32_t ret; + uint32_t oriAgreedKeySize = 0; + if (agreedKey != NULL) { + oriAgreedKeySize = agreedKey->size; + } + + for (uint32_t i = 0; i < performTimes; ++i) { + if (agreedKey != NULL) { + (void)memset_s(agreedKey->data, oriAgreedKeySize, 0, oriAgreedKeySize); + agreedKey->size = oriAgreedKeySize; + } + ret = HksAgreeKey(paramSet, privateKey, peerPublicKey, agreedKey); + if (ret != HKS_SUCCESS) { + return ret; + } + } + return HKS_SUCCESS; +} + +int32_t HksHashRun(const struct HksParamSet *paramSet, + const struct HksBlob *srcData, struct HksBlob *hash, uint32_t performTimes) +{ + int32_t ret; + uint32_t oriHashSize = 0; + if (hash != NULL) { + oriHashSize = hash->size; + } + + for (uint32_t i = 0; i < performTimes; ++i) { + if (hash != NULL) { + (void)memset_s(hash->data, oriHashSize, 0, oriHashSize); + hash->size = oriHashSize; + } + + ret = HksHash(paramSet, srcData, hash); + if (ret != HKS_SUCCESS) { + return ret; + } + } + return HKS_SUCCESS; +} + +int32_t HksBnExpModRun(struct HksBlob *x, const struct HksBlob *a, + const struct HksBlob *e, const struct HksBlob *n, uint32_t performTimes) +{ + int32_t ret; + uint32_t oriXSize = 0; + if (x != NULL) { + oriXSize = x->size; + } + + for (uint32_t i = 0; i < performTimes; ++i) { + if (x != NULL) { + (void)memset_s(x->data, oriXSize, 0, oriXSize); + x->size = oriXSize; + } + ret = HksBnExpMod(x, a, e, n); + if (ret != HKS_SUCCESS) { + return ret; + } + } + return HKS_SUCCESS; +} diff --git a/test/unittest/src/common/hks_test_cipher.c b/test/unittest/src/common/hks_test_cipher.c new file mode 100644 index 00000000..7d6d57ff --- /dev/null +++ b/test/unittest/src/common/hks_test_cipher.c @@ -0,0 +1,743 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ +#include "hks_test_cipher.h" +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" + +#define DEFAULT_AES_CIPHER_PLAIN_SIZE 1000 +#define AES_DEFAULT_GCM_NONCE_LENGTH 12 +#define AES_DEFAULT_AAD_LEN 4 +#define DEFAULT_AES_LOCAL_PARAM_SET_OUT_SIZE 256 +#define AES_LOCAL_KEY_SIZE_128 16 +#define AES_LOCAL_KEY_SIZE_256 32 + +static const struct HksTestCipherParams g_testCipherParams[] = { + /* success: local aes256-gcm-none */ + { 0, HKS_SUCCESS, { false, 0, false, 0 }, + { + true, /* genKey params */ + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + true, HKS_STORAGE_TEMP + }, + { false, 0 }, + { + HKS_TEST_CIPHER_TYPE_AES, true, /* encrypt params */ + true, HKS_ALG_AES, + true, HKS_KEY_PURPOSE_ENCRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0, + true, AES_DEFAULT_GCM_NONCE_LENGTH, + true, AES_DEFAULT_AAD_LEN, + true, false + }, + { + HKS_TEST_CIPHER_TYPE_AES, true, /* decrypt params */ + true, HKS_ALG_AES, + true, HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0, + true, AES_DEFAULT_GCM_NONCE_LENGTH, + true, AES_DEFAULT_AAD_LEN, + true, false + }, + { + true, DEFAULT_AES_CIPHER_PLAIN_SIZE, true, DEFAULT_AES_CIPHER_PLAIN_SIZE }, + { + true, DEFAULT_AES_CIPHER_PLAIN_SIZE + 16, true, DEFAULT_AES_CIPHER_PLAIN_SIZE + 16 }, + { + true, DEFAULT_AES_CIPHER_PLAIN_SIZE, true, DEFAULT_AES_CIPHER_PLAIN_SIZE }, + { + true, AES_LOCAL_KEY_SIZE_256, true, AES_LOCAL_KEY_SIZE_256 } + }, + + /* success: aes256-gcm-none */ + { 1, HKS_SUCCESS, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, /* genKey params */ + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0 + }, + { false, 0 }, + { + HKS_TEST_CIPHER_TYPE_AES, true, /* encrypt params */ + true, HKS_ALG_AES, + true, HKS_KEY_PURPOSE_ENCRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0, + true, AES_DEFAULT_GCM_NONCE_LENGTH, + true, AES_DEFAULT_AAD_LEN + }, + { + HKS_TEST_CIPHER_TYPE_AES, true, /* decrypt params */ + true, HKS_ALG_AES, + true, HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0, + true, AES_DEFAULT_GCM_NONCE_LENGTH, + true, AES_DEFAULT_AAD_LEN + }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE, true, DEFAULT_AES_CIPHER_PLAIN_SIZE }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE + 16, true, DEFAULT_AES_CIPHER_PLAIN_SIZE + 16 }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE, true, DEFAULT_AES_CIPHER_PLAIN_SIZE }, + { false, 0, false, 0 } + }, +}; + +static const struct HksTestEncryptParams g_testEncryptParams[] = { + /* aes gcm nonce not set */ + { 0, HKS_ERROR_CHECK_GET_NONCE_FAIL, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, /* genKey params */ + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM + }, + { 0 }, + { + HKS_TEST_CIPHER_TYPE_AES, true, /* encrypt params */ + true, HKS_ALG_AES, + true, HKS_KEY_PURPOSE_ENCRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0, + false, 0, + true, AES_DEFAULT_AAD_LEN, + false, true + }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE, true, DEFAULT_AES_CIPHER_PLAIN_SIZE }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE + 16, true, DEFAULT_AES_CIPHER_PLAIN_SIZE + 16 }, + { false, 0, false, 0 } + }, + + /* aes gcm nonce size invalid */ + { 1, HKS_ERROR_INVALID_NONCE, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, /* genKey params */ + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM + }, + { 0 }, + { + HKS_TEST_CIPHER_TYPE_AES, true, /* encrypt params */ + true, HKS_ALG_AES, + true, HKS_KEY_PURPOSE_ENCRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0, + true, AES_DEFAULT_GCM_NONCE_LENGTH - 1, + true, AES_DEFAULT_AAD_LEN, + false, true + }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE, true, DEFAULT_AES_CIPHER_PLAIN_SIZE }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE + 16, true, DEFAULT_AES_CIPHER_PLAIN_SIZE + 16 }, + { false, 0, false, 0 } + }, + + /* aes gcm aad not set */ + { 2, HKS_ERROR_CHECK_GET_AAD_FAIL, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, /* genKey params */ + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM + }, + { 0 }, + { + HKS_TEST_CIPHER_TYPE_AES, true, /* encrypt params */ + true, HKS_ALG_AES, + true, HKS_KEY_PURPOSE_ENCRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0, + true, AES_DEFAULT_GCM_NONCE_LENGTH, + false, 0, + false, true + }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE, true, DEFAULT_AES_CIPHER_PLAIN_SIZE }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE + 16, true, DEFAULT_AES_CIPHER_PLAIN_SIZE + 16 }, + { false, 0, false, 0 } + }, + /* aes gcm inSize == 0 */ + { 3, HKS_ERROR_INVALID_ARGUMENT, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, /* genKey params */ + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM + }, + { 0 }, + { + HKS_TEST_CIPHER_TYPE_AES, true, /* encrypt params */ + true, HKS_ALG_AES, + true, HKS_KEY_PURPOSE_ENCRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0, + true, AES_DEFAULT_GCM_NONCE_LENGTH, + true, AES_DEFAULT_AAD_LEN, + false, true + }, + { true, 0, true, DEFAULT_AES_CIPHER_PLAIN_SIZE }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE + 16, true, DEFAULT_AES_CIPHER_PLAIN_SIZE + 16 }, + { false, 0, false, 0 } + }, + + /* aes gcm outSize too small */ + { 4, HKS_ERROR_BUFFER_TOO_SMALL, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, /* genKey params */ + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM }, + { 0 }, + { + HKS_TEST_CIPHER_TYPE_AES, true, /* encrypt params */ + true, HKS_ALG_AES, + true, HKS_KEY_PURPOSE_ENCRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0, + true, AES_DEFAULT_GCM_NONCE_LENGTH, + true, AES_DEFAULT_AAD_LEN, + false, true + }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE, true, DEFAULT_AES_CIPHER_PLAIN_SIZE }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE + 16 - 1, true, DEFAULT_AES_CIPHER_PLAIN_SIZE + 16 - 1 }, + { false, 0, false, 0 } + }, +}; + +static const struct HksTestDecryptParams g_testDecryptParams[] = { + /* aes gcm nonce not set */ + { 0, HKS_ERROR_CHECK_GET_NONCE_FAIL, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, /* genKey params */ + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM + }, + { 0 }, + { + HKS_TEST_CIPHER_TYPE_AES, true, /* decrypt params */ + true, HKS_ALG_AES, + true, HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0, + false, AES_DEFAULT_GCM_NONCE_LENGTH, + true, AES_DEFAULT_AAD_LEN, + false, true + }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE, true, DEFAULT_AES_CIPHER_PLAIN_SIZE }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE - 16, true, DEFAULT_AES_CIPHER_PLAIN_SIZE - 16 }, + { false, 0, false, 0 } + }, + + /* aes gcm nonce size invalid */ + { 1, HKS_ERROR_INVALID_NONCE, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, /* genKey params */ + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM + }, + { 0 }, + { + HKS_TEST_CIPHER_TYPE_AES, true, /* decrypt params */ + true, HKS_ALG_AES, + true, HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0, + true, AES_DEFAULT_GCM_NONCE_LENGTH - 1, + true, AES_DEFAULT_AAD_LEN, + false, true + }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE, true, DEFAULT_AES_CIPHER_PLAIN_SIZE }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE - 16, true, DEFAULT_AES_CIPHER_PLAIN_SIZE - 16 }, + { false, 0, false, 0 } + }, + + /* aes gcm aad not set */ + { 2, HKS_ERROR_CHECK_GET_AAD_FAIL, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, /* genKey params */ + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM + }, + { 0 }, + { + HKS_TEST_CIPHER_TYPE_AES, true, /* decrypt params */ + true, HKS_ALG_AES, + true, HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0, + true, AES_DEFAULT_GCM_NONCE_LENGTH, + false, 0, + false, true + }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE, true, DEFAULT_AES_CIPHER_PLAIN_SIZE }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE - 16, true, DEFAULT_AES_CIPHER_PLAIN_SIZE - 16 }, + { false, 0, false, 0 } + }, + /* aes gcm inSize <= 16 */ + { 3, HKS_ERROR_INVALID_ARGUMENT, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, /* genKey params */ + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM + }, + { 0 }, + { + HKS_TEST_CIPHER_TYPE_AES, true, /* decrypt params */ + true, HKS_ALG_AES, + true, HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0, + true, AES_DEFAULT_GCM_NONCE_LENGTH, + true, AES_DEFAULT_AAD_LEN, + false, true + }, + { true, 16, true, 16 }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE - 16, true, DEFAULT_AES_CIPHER_PLAIN_SIZE - 16 }, + { false, 0, false, 0 } + }, + + /* aes gcm outSize too small */ + { 4, HKS_ERROR_BUFFER_TOO_SMALL, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, /* genKey params */ + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM + }, + { 0 }, + { + HKS_TEST_CIPHER_TYPE_AES, true, /* decrypt params */ + true, HKS_ALG_AES, + true, HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0, + true, AES_DEFAULT_GCM_NONCE_LENGTH, + true, AES_DEFAULT_AAD_LEN, + false, true + }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE, true, DEFAULT_AES_CIPHER_PLAIN_SIZE }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE - 16 - 1, true, DEFAULT_AES_CIPHER_PLAIN_SIZE - 16 -1 }, + { false, 0, false, 0 } + }, +}; + +static int32_t ConstructDataToBlob(struct HksBlob **inData, struct HksBlob **outData, + const struct HksTestBlobParams *inTextParams, const struct HksTestBlobParams *outTextParams) +{ + int32_t ret = TestConstuctBlob(inData, + inTextParams->blobExist, + inTextParams->blobSize, + inTextParams->blobDataExist, + inTextParams->blobDataSize); + HKS_TEST_ASSERT(ret == 0); + + ret = TestConstuctBlob(outData, + outTextParams->blobExist, + outTextParams->blobSize, + outTextParams->blobDataExist, + outTextParams->blobDataSize); + HKS_TEST_ASSERT(ret == 0); + return ret; +} + +static int32_t Encrypt(struct CipherEncryptStructure *encryptStruct) +{ + int32_t ret; + struct HksParamSet *encryptParamSet = NULL; + + if (encryptStruct->cipherParms->cipherType == HKS_TEST_CIPHER_TYPE_RSA) { + struct TestRsaCipherParamSet rsaCipherParamStructure = { + &encryptParamSet, + encryptStruct->cipherParms->paramSetExist, + encryptStruct->cipherParms->setAlg, encryptStruct->cipherParms->alg, + encryptStruct->cipherParms->setPurpose, encryptStruct->cipherParms->purpose, + encryptStruct->cipherParms->setDigest, encryptStruct->cipherParms->digest, + encryptStruct->cipherParms->setPadding, encryptStruct->cipherParms->padding + }; + ret = TestConstructRsaCipherParamSet(&rsaCipherParamStructure); + } else { + uint32_t ivSize = encryptStruct->cipherParms->ivSize; + uint32_t nonceSize = encryptStruct->cipherParms->nonceSize; + uint32_t aadSize = encryptStruct->cipherParms->aadSize; + if (ivSize != 0) { + ret = TestConstuctBlob(encryptStruct->ivData, true, ivSize, true, ivSize); + HKS_TEST_ASSERT(ret == 0); + } + if (nonceSize != 0) { + ret = TestConstuctBlob(encryptStruct->nonceData, true, nonceSize, true, nonceSize); + HKS_TEST_ASSERT(ret == 0); + } + if (aadSize != 0) { + ret = TestConstuctBlob(encryptStruct->aadData, true, aadSize, true, aadSize); + HKS_TEST_ASSERT(ret == 0); + } + struct AesCipherParamSetStructure enParamStruct = { + &encryptParamSet, + encryptStruct->cipherParms->paramSetExist, + encryptStruct->cipherParms->setAlg, encryptStruct->cipherParms->alg, + encryptStruct->cipherParms->setPurpose, encryptStruct->cipherParms->purpose, + encryptStruct->cipherParms->setPadding, encryptStruct->cipherParms->padding, + encryptStruct->cipherParms->setBlockMode, encryptStruct->cipherParms->mode, + encryptStruct->cipherParms->setIv, *(encryptStruct->ivData), + encryptStruct->cipherParms->setNonce, *(encryptStruct->nonceData), + encryptStruct->cipherParms->setAad, *(encryptStruct->aadData), + encryptStruct->cipherParms->setIsKeyAlias, encryptStruct->cipherParms->isKeyAlias + }; + ret = TestConstructAesCipherParamSet(&enParamStruct); + HKS_TEST_ASSERT(ret == 0); + } + + ret = HksEncryptRun(encryptStruct->keyAlias, encryptParamSet, encryptStruct->plainData, encryptStruct->cipherData, + encryptStruct->performTimes); + HksFreeParamSet(&encryptParamSet); + return ret; +} + +static int32_t DecryptCipher(struct CipherDecryptStructure *decryptStruct) +{ + int32_t ret = TestConstuctBlob(decryptStruct->decryptedData, + decryptStruct->cipherParms->decryptedTextParams.blobExist, + decryptStruct->cipherParms->decryptedTextParams.blobSize, + decryptStruct->cipherParms->decryptedTextParams.blobDataExist, + decryptStruct->cipherParms->decryptedTextParams.blobDataSize); + HKS_TEST_ASSERT(ret == 0); + + struct HksParamSet *decryptParamSet = NULL; + if (decryptStruct->cipherParms->decryptParamSetParams.cipherType == HKS_TEST_CIPHER_TYPE_RSA) { + struct TestRsaCipherParamSet rsaDeCipherParamStructure = { + &decryptParamSet, + decryptStruct->cipherParms->decryptParamSetParams.paramSetExist, + decryptStruct->cipherParms->decryptParamSetParams.setAlg, + decryptStruct->cipherParms->decryptParamSetParams.alg, + decryptStruct->cipherParms->decryptParamSetParams.setPurpose, + decryptStruct->cipherParms->decryptParamSetParams.purpose, + decryptStruct->cipherParms->decryptParamSetParams.setDigest, + decryptStruct->cipherParms->decryptParamSetParams.digest, + decryptStruct->cipherParms->decryptParamSetParams.setPadding, + decryptStruct->cipherParms->decryptParamSetParams.padding + }; + ret = TestConstructRsaCipherParamSet(&rsaDeCipherParamStructure); + } else { + struct AesCipherParamSetStructure deParamStruct = { + &decryptParamSet, + decryptStruct->cipherParms->decryptParamSetParams.paramSetExist, + decryptStruct->cipherParms->decryptParamSetParams.setAlg, + decryptStruct->cipherParms->decryptParamSetParams.alg, + decryptStruct->cipherParms->decryptParamSetParams.setPurpose, + decryptStruct->cipherParms->decryptParamSetParams.purpose, + decryptStruct->cipherParms->decryptParamSetParams.setPadding, + decryptStruct->cipherParms->decryptParamSetParams.padding, + decryptStruct->cipherParms->decryptParamSetParams.setBlockMode, + decryptStruct->cipherParms->decryptParamSetParams.mode, + decryptStruct->cipherParms->decryptParamSetParams.setIv, decryptStruct->ivData, + decryptStruct->cipherParms->decryptParamSetParams.setNonce, decryptStruct->nonceData, + decryptStruct->cipherParms->decryptParamSetParams.setAad, decryptStruct->aadData, + decryptStruct->cipherParms->decryptParamSetParams.setIsKeyAlias, + decryptStruct->cipherParms->decryptParamSetParams.isKeyAlias + }; + ret = TestConstructAesCipherParamSet(&deParamStruct); + HKS_TEST_ASSERT(ret == 0); + } + + ret = HksDecryptRun(decryptStruct->keyAlias, decryptParamSet, decryptStruct->cipherData, + *(decryptStruct->decryptedData), decryptStruct->performTimes); + HksFreeParamSet(&decryptParamSet); + return ret; +} + +static int32_t Decrypt(struct OnlyDecryptStructure *onlyDecryptStruct) +{ + struct HksParamSet *decryptParamSet = NULL; + int32_t ret; + if (onlyDecryptStruct->cipherParms->cipherType == HKS_TEST_CIPHER_TYPE_RSA) { + struct TestRsaCipherParamSet rsaCipherParamStructure = { + &decryptParamSet, + onlyDecryptStruct->cipherParms->paramSetExist, + onlyDecryptStruct->cipherParms->setAlg, onlyDecryptStruct->cipherParms->alg, + onlyDecryptStruct->cipherParms->setPurpose, onlyDecryptStruct->cipherParms->purpose, + onlyDecryptStruct->cipherParms->setDigest, onlyDecryptStruct->cipherParms->digest, + onlyDecryptStruct->cipherParms->setPadding, onlyDecryptStruct->cipherParms->padding + }; + ret = TestConstructRsaCipherParamSet(&rsaCipherParamStructure); + } else { + uint32_t ivSize = onlyDecryptStruct->cipherParms->ivSize; + uint32_t nonceSize = onlyDecryptStruct->cipherParms->nonceSize; + uint32_t aadSize = onlyDecryptStruct->cipherParms->aadSize; + if (ivSize != 0) { + ret = TestConstuctBlob(onlyDecryptStruct->ivData, true, ivSize, true, ivSize); + HKS_TEST_ASSERT(ret == 0); + } + if (nonceSize != 0) { + ret = TestConstuctBlob(onlyDecryptStruct->nonceData, true, nonceSize, true, nonceSize); + HKS_TEST_ASSERT(ret == 0); + } + if (aadSize != 0) { + ret = TestConstuctBlob(onlyDecryptStruct->aadData, true, aadSize, true, aadSize); + HKS_TEST_ASSERT(ret == 0); + } + struct AesCipherParamSetStructure onlyDeParamStruct = { + &decryptParamSet, + onlyDecryptStruct->cipherParms->paramSetExist, + onlyDecryptStruct->cipherParms->setAlg, onlyDecryptStruct->cipherParms->alg, + onlyDecryptStruct->cipherParms->setPurpose, onlyDecryptStruct->cipherParms->purpose, + onlyDecryptStruct->cipherParms->setPadding, onlyDecryptStruct->cipherParms->padding, + onlyDecryptStruct->cipherParms->setBlockMode, onlyDecryptStruct->cipherParms->mode, + onlyDecryptStruct->cipherParms->setIv, *(onlyDecryptStruct->ivData), + onlyDecryptStruct->cipherParms->setNonce, *(onlyDecryptStruct->nonceData), + onlyDecryptStruct->cipherParms->setAad, *(onlyDecryptStruct->aadData), + onlyDecryptStruct->cipherParms->setIsKeyAlias, onlyDecryptStruct->cipherParms->isKeyAlias + }; + ret = TestConstructAesCipherParamSet(&onlyDeParamStruct); + } + HKS_TEST_ASSERT(ret == 0); + + ret = HksDecryptRun(onlyDecryptStruct->keyAlias, decryptParamSet, onlyDecryptStruct->cipherData, + onlyDecryptStruct->decryptedData, onlyDecryptStruct->performTimes); + HksFreeParamSet(&decryptParamSet); + return ret; +} + + +int32_t BaseTestCipher(uint32_t times, uint32_t index, uint32_t performTimes) +{ + /* 1. generate key */ + struct HksBlob *keyAlias = NULL; + int32_t ret; + if ((g_testCipherParams[index].genKeyParamSetParams.setKeyStorageFlag) && + g_testCipherParams[index].genKeyParamSetParams.keyStorageFlag == HKS_STORAGE_TEMP) { + ret = GenerateLocalRandomKey(&keyAlias, &g_testCipherParams[index].localKeyParams); + } else { + ret = GenerateKey(&keyAlias, &g_testCipherParams[index].keyAliasParams, + &g_testCipherParams[index].genKeyParamSetParams, &g_testCipherParams[index].genKeyParamSetParamsOut); + } + HKS_TEST_ASSERT(ret == 0); + struct HksBlob *plainData = NULL; + struct HksBlob *cipherData = NULL; + ret = ConstructDataToBlob(&plainData, &cipherData, + &g_testCipherParams[index].plainTextParams, &g_testCipherParams[index].cipherTextParams); + HKS_TEST_ASSERT(ret == 0); + struct HksBlob *ivData = NULL; + struct HksBlob *nonceData = NULL; + struct HksBlob *aadData = NULL; + /* 2. encrypt */ + struct CipherEncryptStructure testEncryptStruct = { + keyAlias, &g_testCipherParams[index].encryptParamSetParams, + plainData, cipherData, &ivData, &nonceData, &aadData, performTimes + }; + ret = Encrypt(&testEncryptStruct); + HKS_TEST_ASSERT(ret == g_testCipherParams[index].expectResult); + + /* 3. decrypt */ + struct HksBlob *decryptedData = NULL; + struct CipherDecryptStructure testDecryptStruct = { + keyAlias, &g_testCipherParams[index], cipherData, + &decryptedData, ivData, nonceData, aadData, performTimes + }; + ret = DecryptCipher(&testDecryptStruct); + HKS_TEST_ASSERT(ret == g_testCipherParams[index].expectResult); + + HKS_TEST_ASSERT(plainData->size == decryptedData->size); + HKS_TEST_ASSERT(memcmp(plainData->data, decryptedData->data, plainData->size) == 0); + if (!((g_testCipherParams[index].genKeyParamSetParams.setKeyStorageFlag) && + g_testCipherParams[index].genKeyParamSetParams.keyStorageFlag == HKS_STORAGE_TEMP)) { + HKS_TEST_ASSERT(HksDeleteKey(keyAlias, NULL) == 0); + } + TestFreeBlob(&keyAlias); + TestFreeBlob(&plainData); + TestFreeBlob(&cipherData); + TestFreeBlob(&decryptedData); + TestFreeBlob(&ivData); + TestFreeBlob(&nonceData); + TestFreeBlob(&aadData); + return (ret != g_testCipherParams[index].expectResult); +} + +int32_t BaseTestEncrypt(uint32_t times, uint32_t index, uint32_t performTimes) +{ + /* 1. generate key */ + struct HksBlob *keyAlias = NULL; + int32_t ret; + if (g_testEncryptParams[index].encryptParamSetParams.setIsKeyAlias && + !g_testEncryptParams[index].encryptParamSetParams.isKeyAlias) { + ret = GenerateLocalRandomKey(&keyAlias, &g_testEncryptParams[index].localKeyParams); + } else { + if (g_testEncryptParams[index].keyAliasParams.blobExist) { + ret = GenerateKey(&keyAlias, &g_testEncryptParams[index].keyAliasParams, + &g_testEncryptParams[index].genKeyParamSetParams, NULL); + } else { + ret = TestConstuctBlob(&keyAlias, + g_testEncryptParams[index].encryptAliasParams.blobExist, + g_testEncryptParams[index].encryptAliasParams.blobSize, + g_testEncryptParams[index].encryptAliasParams.blobDataExist, + g_testEncryptParams[index].encryptAliasParams.blobDataSize); + } + } + HKS_TEST_ASSERT(ret == 0); + + struct HksBlob *plainData = NULL; + struct HksBlob *cipherData = NULL; + ret = ConstructDataToBlob(&plainData, &cipherData, + &g_testEncryptParams[index].inDataParams, &g_testEncryptParams[index].outDataParams); + HKS_TEST_ASSERT(ret == 0); + + struct HksBlob *ivData = NULL; + struct HksBlob *nonceData = NULL; + struct HksBlob *aadData = NULL; + /* 2. encrypt */ + struct CipherEncryptStructure encryptStruct = { + keyAlias, &g_testEncryptParams[index].encryptParamSetParams, plainData, cipherData, &ivData, + &nonceData, &aadData, performTimes + }; + ret = Encrypt(&encryptStruct); + HKS_TEST_ASSERT(ret == g_testEncryptParams[index].expectResult); + + /* 4. delete key */ + if (g_testEncryptParams[index].keyAliasParams.blobExist) { + HKS_TEST_ASSERT(HksDeleteKey(keyAlias, NULL) == 0); + } + TestFreeBlob(&keyAlias); + TestFreeBlob(&plainData); + TestFreeBlob(&cipherData); + TestFreeBlob(&ivData); + TestFreeBlob(&nonceData); + TestFreeBlob(&aadData); + return (ret != g_testEncryptParams[index].expectResult); +} + +int32_t BaseTestDecrypt(uint32_t times, uint32_t index, uint32_t performTimes) +{ + /* 1. generate key */ + struct HksBlob *keyAlias = NULL; + int32_t ret; + if (g_testDecryptParams[index].decryptParamSetParams.setIsKeyAlias && + !g_testDecryptParams[index].decryptParamSetParams.isKeyAlias) { + ret = GenerateLocalRandomKey(&keyAlias, &g_testDecryptParams[index].localKeyParams); + } else { + if (g_testDecryptParams[index].keyAliasParams.blobExist) { + ret = GenerateKey(&keyAlias, &g_testDecryptParams[index].keyAliasParams, + &g_testDecryptParams[index].genKeyParamSetParams, NULL); + } else { + ret = TestConstuctBlob(&keyAlias, + g_testDecryptParams[index].decryptAliasParams.blobExist, + g_testDecryptParams[index].decryptAliasParams.blobSize, + g_testDecryptParams[index].decryptAliasParams.blobDataExist, + g_testDecryptParams[index].decryptAliasParams.blobDataSize); + } + } + HKS_TEST_ASSERT(ret == 0); + + struct HksBlob *cipherData = NULL; + struct HksBlob *decryptedData = NULL; + ret = ConstructDataToBlob(&cipherData, &decryptedData, + &g_testDecryptParams[index].inDataParams, &g_testDecryptParams[index].outDataParams); + HKS_TEST_ASSERT(ret == 0); + + struct HksBlob *ivData = NULL; + struct HksBlob *nonceData = NULL; + struct HksBlob *aadData = NULL; + /* 3. encrypt */ + struct OnlyDecryptStructure onlyDecryptStruct = { + keyAlias, &g_testDecryptParams[index].decryptParamSetParams, cipherData, decryptedData, &ivData, + &nonceData, &aadData, performTimes + }; + ret = Decrypt(&onlyDecryptStruct); + HKS_TEST_ASSERT(ret == g_testDecryptParams[index].expectResult); + + /* 4. delete key */ + if (g_testDecryptParams[index].keyAliasParams.blobExist) { + HKS_TEST_ASSERT(HksDeleteKey(keyAlias, NULL) == 0); + } + TestFreeBlob(&keyAlias); + TestFreeBlob(&decryptedData); + TestFreeBlob(&cipherData); + TestFreeBlob(&ivData); + TestFreeBlob(&nonceData); + TestFreeBlob(&aadData); + return (ret != g_testDecryptParams[index].expectResult); +} \ No newline at end of file diff --git a/test/unittest/src/common/hks_test_common.c b/test/unittest/src/common/hks_test_common.c new file mode 100644 index 00000000..5ded2daf --- /dev/null +++ b/test/unittest/src/common/hks_test_common.c @@ -0,0 +1,736 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include "hks_test_common.h" + +#include +#include + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_log.h" +#include "hks_test_mem.h" + +#include "securec.h" + +#define HKS_TEST_1024 1024 +#define HKS_TEST_COMMON_8 8 +#define HKS_TEST_COMMON_128 128 + +void TestFreeBlob(struct HksBlob **key) +{ + if (key == NULL || *key == NULL) { + return; + } + HksTestFree((*key)->data); + HksTestFree(*key); +} + +int32_t TestConstuctBlob(struct HksBlob **blob, bool blobExist, uint32_t blobSize, bool blobDataExist, + uint32_t realBlobDataSize) +{ + if (!blobExist) { // blob not exist + return 0; // do nothing, return null + } + + *blob = (struct HksBlob *)HksTestMalloc(sizeof(struct HksBlob)); + if (*blob == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + (void)memset_s(*blob, sizeof(struct HksBlob), 0, sizeof(struct HksBlob)); + + if (blobDataExist) { + (*blob)->size = realBlobDataSize; + (*blob)->data = (uint8_t *)HksTestMalloc(realBlobDataSize); + if ((*blob)->data == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + (void)memset_s((*blob)->data, realBlobDataSize, 0, realBlobDataSize); + uint32_t offset = 0; + for (uint32_t i = 0; i < (realBlobDataSize - 1) / HKS_TEST_1024; i++) { + struct HksBlob tmp; + tmp.size = HKS_TEST_1024; + tmp.data = (uint8_t *)HksTestMalloc(tmp.size); + HKS_TEST_ASSERT(tmp.data != NULL); + (void)memset_s(tmp.data, tmp.size, 0, tmp.size); + + HKS_TEST_ASSERT(HksGenerateRandom(NULL, &tmp) == 0); + + HKS_TEST_ASSERT(memcpy_s((*blob)->data + offset, realBlobDataSize - offset, tmp.data, tmp.size) == EOK); + offset += tmp.size; + HksTestFree(tmp.data); + } + + uint32_t remainSize = realBlobDataSize - offset; + struct HksBlob tmp; + tmp.size = remainSize; + tmp.data = (uint8_t *)HksTestMalloc(tmp.size); + HKS_TEST_ASSERT(tmp.data != NULL); + (void)memset_s(tmp.data, tmp.size, 0, tmp.size); + + HKS_TEST_ASSERT(HksGenerateRandom(NULL, &tmp) == 0); + HKS_TEST_ASSERT(memcpy_s((*blob)->data + offset, remainSize, tmp.data, tmp.size) == EOK); + offset += tmp.size; + HksTestFree(tmp.data); + } else { + (*blob)->data = NULL; + } + + (*blob)->size = blobSize; + return 0; +} + +static int32_t TestGenerateKeyParamSetPre(struct GenerateKeyParamSetStructure *paramStruct, + struct HksParamSet *paramSet) +{ + if (!paramStruct->paramSetExist) { + return 0; // do nothing, return null + } + int32_t ret = 1; + + if (paramStruct->setAlg) { + struct HksParam algParam = {0}; + algParam.tag = HKS_TAG_ALGORITHM; + algParam.uint32Param = paramStruct->alg; + ret = HksAddParams(paramSet, (const struct HksParam *) &algParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setKeySize) { + struct HksParam keySizeParam = {0}; + keySizeParam.tag = HKS_TAG_KEY_SIZE; + keySizeParam.uint32Param = paramStruct->keySize; + ret = HksAddParams(paramSet, (const struct HksParam *) &keySizeParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setPurpose) { + struct HksParam purposeParam = {0}; + purposeParam.tag = HKS_TAG_PURPOSE; + purposeParam.uint32Param = paramStruct->purpose; + ret = HksAddParams(paramSet, (const struct HksParam *) &purposeParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setDigest) { + struct HksParam digestParam = {0}; + digestParam.tag = HKS_TAG_DIGEST; + digestParam.uint32Param = paramStruct->digest; + ret = HksAddParams(paramSet, (const struct HksParam *) &digestParam, 1); + HKS_TEST_LOG_I("HksAddParams ret = 0x%X", ret); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setPadding) { + struct HksParam paddingParam = {0}; + paddingParam.tag = HKS_TAG_PADDING; + paddingParam.uint32Param = paramStruct->padding; + ret = HksAddParams(paramSet, (const struct HksParam *) &paddingParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + return ret; +} + +static int32_t TestGenerateKeyParamSetPost(struct GenerateKeyParamSetStructure *paramStruct, + struct HksParamSet *paramSet) +{ + if (!paramStruct->paramSetExist) { + return 0; // do nothing, return null + } + int32_t ret; + if (paramStruct->setBlockMode) { + struct HksParam keyMode = {0}; + keyMode.tag = HKS_TAG_BLOCK_MODE; + keyMode.uint32Param = paramStruct->mode; + ret = HksAddParams(paramSet, (const struct HksParam *) &keyMode, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setKeyStorageFlag) { + struct HksParam keyStorageFlagParam = {0}; + keyStorageFlagParam.tag = HKS_TAG_KEY_STORAGE_FLAG; + keyStorageFlagParam.uint32Param = paramStruct->keyStorageFlag; + ret = HksAddParams(paramSet, (const struct HksParam *) &keyStorageFlagParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + struct HksParam tmpParam = {0}; + tmpParam.tag = HKS_TAG_KEY_ROLE; + tmpParam.uint32Param = 0xFFFFFFFF; + ret = HksAddParams(paramSet, (const struct HksParam *) &tmpParam, 1); + HKS_TEST_ASSERT(ret == 0); + + ret = HksBuildParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + + *(paramStruct->outParamSet) = paramSet; + return ret; +} + +int32_t TestConstructGenerateKeyParamSet(struct GenerateKeyParamSetStructure *paramStruct) +{ + struct HksParamSet *paramSet = NULL; + int32_t ret = HksInitParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + + ret = TestGenerateKeyParamSetPre(paramStruct, paramSet); + HKS_TEST_ASSERT(ret == 0); + ret = TestGenerateKeyParamSetPost(paramStruct, paramSet); + HKS_TEST_ASSERT(ret == 0); + return ret; +} + +int32_t TestConstructGenerateKeyParamSetOut( + struct HksParamSet **outParamSet, + bool paramSetExist, uint32_t paramSetSize) +{ + if (!paramSetExist) { + return 0; // do nothing, return null + } + struct HksParamSet *tempParamSet = (struct HksParamSet *)HksTestMalloc(paramSetSize); + if (tempParamSet == NULL) { + return -1; // -1 is error code + } + (void)memset_s(tempParamSet, paramSetSize, 0, paramSetSize); + tempParamSet->paramSetSize = paramSetSize; + + *outParamSet = tempParamSet; + return 0; +} + +int32_t TestConstructRsaCipherParamSet(struct TestRsaCipherParamSet *paramStruct) +{ + struct GenerateKeyParamSetStructure genParamStruct = { + paramStruct->outParamSet, paramStruct->paramSetExist, + paramStruct->setAlg, paramStruct->alg, + false, 0, + paramStruct->setPurpose, paramStruct->purpose, + paramStruct->setDigest, paramStruct->digest, + paramStruct->setPadding, paramStruct->padding, + false, 0, + false, 0 + }; + return TestConstructGenerateKeyParamSet(&genParamStruct); +} + +int32_t TestAesCipherParamSetPre(struct AesCipherParamSetStructure *paramStruct, struct HksParamSet *paramSet) +{ + if (!paramStruct->paramSetExist) { + return 0; // do nothing, return null + } + int32_t ret = 1; + if (paramStruct->setAlg) { + struct HksParam algParam = {0}; + algParam.tag = HKS_TAG_ALGORITHM; + algParam.uint32Param = paramStruct->alg; + ret = HksAddParams(paramSet, (const struct HksParam *) &algParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setPurpose) { + struct HksParam purposeParam = {0}; + purposeParam.tag = HKS_TAG_PURPOSE; + purposeParam.uint32Param = paramStruct->purpose; + ret = HksAddParams(paramSet, (const struct HksParam *) &purposeParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setPadding) { + struct HksParam paddingParam = {0}; + paddingParam.tag = HKS_TAG_PADDING; + paddingParam.uint32Param = paramStruct->padding; + ret = HksAddParams(paramSet, (const struct HksParam *) &paddingParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setBlockMode) { + struct HksParam keyMode = {0}; + keyMode.tag = HKS_TAG_BLOCK_MODE; + keyMode.uint32Param = paramStruct->mode; + ret = HksAddParams(paramSet, (const struct HksParam *) &keyMode, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setIv) { + struct HksParam ivParam = {0}; + ivParam.tag = HKS_TAG_IV; + ivParam.blob = *(paramStruct->ivBlob); + ret = HksAddParams(paramSet, (const struct HksParam *)&ivParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + return ret; +} + +int32_t TestAesCipherParamSetPost(struct AesCipherParamSetStructure *paramStruct, struct HksParamSet *paramSet) +{ + if (!paramStruct->paramSetExist) { + return 0; // do nothing, return null + } + int32_t ret; + if (paramStruct->setNonce) { + struct HksParam nonceParam = {0}; + nonceParam.tag = HKS_TAG_NONCE; + nonceParam.blob = *(paramStruct->nonceBlob); + ret = HksAddParams(paramSet, (const struct HksParam *)&nonceParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setAad) { + struct HksParam aadParam = {0}; + aadParam.tag = HKS_TAG_ASSOCIATED_DATA; + aadParam.blob = *(paramStruct->aadBlob); + ret = HksAddParams(paramSet, (const struct HksParam *)&aadParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setIsKeyAlias) { + struct HksParam isKeyAilasParam = {0}; + isKeyAilasParam.tag = HKS_TAG_IS_KEY_ALIAS; + isKeyAilasParam.boolParam = paramStruct->isKeyAlias; + ret = HksAddParams(paramSet, (const struct HksParam *) &isKeyAilasParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + struct HksParam tmpParam = {0}; + tmpParam.tag = HKS_TAG_KEY_ROLE; + tmpParam.uint32Param = 0xFFFFFFFF; + ret = HksAddParams(paramSet, (const struct HksParam *) &tmpParam, 1); + HKS_TEST_ASSERT(ret == 0); + + ret = HksBuildParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + + *(paramStruct->outParamSet) = paramSet; + return ret; +} + +int32_t TestConstructAesCipherParamSet(struct AesCipherParamSetStructure *paramStruct) +{ + struct HksParamSet *paramSet = NULL; + int32_t ret = HksInitParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + + ret = TestAesCipherParamSetPre(paramStruct, paramSet); + HKS_TEST_ASSERT(ret == 0); + ret = TestAesCipherParamSetPost(paramStruct, paramSet); + HKS_TEST_ASSERT(ret == 0); + return ret; +} + +int32_t TestConstructMacParamSet(struct TestMacParamSetStructure *paramStruct) +{ + if (!paramStruct->paramSetExist) { + return 0; // do nothing, return null + } + struct HksParamSet *paramSet = NULL; + int32_t ret = HksInitParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + + if (paramStruct->setPurpose) { + struct HksParam purposeParam = {0}; + purposeParam.tag = HKS_TAG_PURPOSE; + purposeParam.uint32Param = paramStruct->purpose; + ret = HksAddParams(paramSet, (const struct HksParam *) &purposeParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setDigest) { + struct HksParam digestParam = {0}; + digestParam.tag = HKS_TAG_DIGEST; + digestParam.uint32Param = paramStruct->digest; + ret = HksAddParams(paramSet, (const struct HksParam *) &digestParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setKeyAlias) { + struct HksParam keyIsKeyAlias = {0}; + keyIsKeyAlias.tag = HKS_TAG_IS_KEY_ALIAS; + keyIsKeyAlias.boolParam = paramStruct->isKeyAlias; + ret = HksAddParams(paramSet, (const struct HksParam *) &keyIsKeyAlias, 1); + HKS_TEST_ASSERT(ret == 0); + } + + struct HksParam tmpParam = {0}; + tmpParam.tag = HKS_TAG_KEY_ROLE; + tmpParam.uint32Param = 0xFFFFFFFF; + ret = HksAddParams(paramSet, (const struct HksParam *) &tmpParam, 1); + HKS_TEST_ASSERT(ret == 0); + + ret = HksBuildParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + + *(paramStruct->outParamSet) = paramSet; + return ret; +} + +int32_t TestConstructAgreeParamSet(struct TestAgreeParamSetStructure *paramStruct) +{ + if (!paramStruct->paramSetExist) { + return 0; // do nothing, return null + } + struct HksParamSet *paramSet = NULL; + int32_t ret = HksInitParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + + if (paramStruct->setAlg) { + struct HksParam algParam = {0}; + algParam.tag = HKS_TAG_ALGORITHM; + algParam.uint32Param = paramStruct->alg; + ret = HksAddParams(paramSet, (const struct HksParam *) &algParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setKeySize) { + struct HksParam keySizeParam = {0}; + keySizeParam.tag = HKS_TAG_KEY_SIZE; + keySizeParam.uint32Param = paramStruct->keySize; + ret = HksAddParams(paramSet, (const struct HksParam *) &keySizeParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setIsKeyAlias) { + struct HksParam isKeyAliasParam = {0}; + isKeyAliasParam.tag = HKS_TAG_IS_KEY_ALIAS; + isKeyAliasParam.uint32Param = paramStruct->isKeyAlias; + ret = HksAddParams(paramSet, (const struct HksParam *) &isKeyAliasParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + struct HksParam tmpParam = {0}; + tmpParam.tag = HKS_TAG_KEY_ROLE; + tmpParam.uint32Param = 0xFFFFFFFF; + ret = HksAddParams(paramSet, (const struct HksParam *) &tmpParam, 1); + HKS_TEST_ASSERT(ret == 0); + + ret = HksBuildParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + + *(paramStruct->outParamSet) = paramSet; + return ret; +} + + +int32_t TestDeriveParamSetPre(struct TestDeriveParamSetStructure *paramStruct, struct HksParamSet *paramSet) +{ + if (!paramStruct->paramSetExist) { + return 0; // do nothing, return null + } + int32_t ret = 1; + if (paramStruct->setAlg) { + struct HksParam algParam = {0}; + algParam.tag = HKS_TAG_ALGORITHM; + algParam.uint32Param = paramStruct->alg; + ret = HksAddParams(paramSet, (const struct HksParam *) &algParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setPurpose) { + struct HksParam purposeParam = {0}; + purposeParam.tag = HKS_TAG_PURPOSE; + purposeParam.uint32Param = paramStruct->purpose; + ret = HksAddParams(paramSet, (const struct HksParam *) &purposeParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setDigest) { + struct HksParam digestParam = {0}; + digestParam.tag = HKS_TAG_DIGEST; + digestParam.uint32Param = paramStruct->digest; + ret = HksAddParams(paramSet, (const struct HksParam *)&digestParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setIteration) { + struct HksParam iterationParam = {0}; + iterationParam.tag = HKS_TAG_ITERATION; + iterationParam.uint32Param = paramStruct->iteration; + ret = HksAddParams(paramSet, (const struct HksParam *)&iterationParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + return ret; +} + +int32_t TestDeriveParamSetPost(struct TestDeriveParamSetStructure *paramStruct, struct HksParamSet *paramSet) +{ + if (!paramStruct->paramSetExist) { + return 0; // do nothing, return null + } + int32_t ret; + if (paramStruct->setSalt) { + struct HksParam saltParam = {0}; + saltParam.tag = HKS_TAG_SALT; + saltParam.blob = *(paramStruct->saltBlob); + ret = HksAddParams(paramSet, (const struct HksParam *)&saltParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setInfo) { + struct HksParam infoParam = {0}; + infoParam.tag = HKS_TAG_INFO; + infoParam.blob = *(paramStruct->infoBlob); + ret = HksAddParams(paramSet, (const struct HksParam *)&infoParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + if (paramStruct->setIsKeyAlias) { + struct HksParam isKeyAliasParam = {0}; + isKeyAliasParam.tag = HKS_TAG_IS_KEY_ALIAS; + isKeyAliasParam.boolParam = paramStruct->isKeyAlias; + ret = HksAddParams(paramSet, (const struct HksParam *)&isKeyAliasParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + struct HksParam tmpParam = {0}; + tmpParam.tag = HKS_TAG_KEY_ROLE; + tmpParam.uint32Param = 0xFFFFFFFF; + ret = HksAddParams(paramSet, (const struct HksParam *) &tmpParam, 1); + HKS_TEST_ASSERT(ret == 0); + + ret = HksBuildParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + + *(paramStruct->outParamSet) = paramSet; + return ret; +} + +int32_t TestConstructDeriveParamSet(struct TestDeriveParamSetStructure *paramStruct) +{ + struct HksParamSet *paramSet = NULL; + int32_t ret = HksInitParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + + ret = TestDeriveParamSetPre(paramStruct, paramSet); + HKS_TEST_ASSERT(ret == 0); + ret = TestDeriveParamSetPost(paramStruct, paramSet); + HKS_TEST_ASSERT(ret == 0); + return ret; +} + +int32_t TestConstructHashParamSet( + struct HksParamSet **outParamSet, + bool paramSetExist, + bool setDigest, uint32_t digest) +{ + if (!paramSetExist) { + return 0; // do nothing, return null + } + struct HksParamSet *paramSet = NULL; + int32_t ret = HksInitParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + + if (setDigest) { + struct HksParam digestParam = {0}; + digestParam.tag = HKS_TAG_DIGEST; + digestParam.uint32Param = digest; + ret = HksAddParams(paramSet, (const struct HksParam *) &digestParam, 1); + HKS_TEST_ASSERT(ret == 0); + } + + struct HksParam tmpParam = {0}; + tmpParam.tag = HKS_TAG_KEY_ROLE; + tmpParam.uint32Param = 0xFFFFFFFF; + ret = HksAddParams(paramSet, (const struct HksParam *) &tmpParam, 1); + HKS_TEST_ASSERT(ret == 0); + + ret = HksBuildParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + + *outParamSet = paramSet; + return ret; +} + +int32_t GenerateKey(struct HksBlob **keyAlias, const struct HksTestBlobParams *keyAliasParams, + const struct HksTestGenKeyParamsParamSet *genKeyParamSetParams, + const struct HksTestGenKeyParamsParamSetOut *genKeyParamSetParamsOut) +{ + int32_t ret = TestConstuctBlob(keyAlias, + keyAliasParams->blobExist, + keyAliasParams->blobSize, + keyAliasParams->blobDataExist, + keyAliasParams->blobDataSize); + HKS_TEST_ASSERT(ret == 0); + + struct HksParamSet *paramSet = NULL; + struct GenerateKeyParamSetStructure paramStruct = { + ¶mSet, + genKeyParamSetParams->paramSetExist, + genKeyParamSetParams->setAlg, genKeyParamSetParams->alg, + genKeyParamSetParams->setKeySize, genKeyParamSetParams->keySize, + genKeyParamSetParams->setPurpose, genKeyParamSetParams->purpose, + genKeyParamSetParams->setDigest, genKeyParamSetParams->digest, + genKeyParamSetParams->setPadding, genKeyParamSetParams->padding, + genKeyParamSetParams->setBlockMode, genKeyParamSetParams->mode, + genKeyParamSetParams->setKeyStorageFlag, genKeyParamSetParams->keyStorageFlag + }; + ret = TestConstructGenerateKeyParamSet(¶mStruct); + HKS_TEST_ASSERT(ret == 0); + + struct HksParamSet *paramSetOut = NULL; + if (genKeyParamSetParamsOut != NULL) { + ret = TestConstructGenerateKeyParamSetOut(¶mSet, + genKeyParamSetParamsOut->paramSetExist, genKeyParamSetParamsOut->paramSetSize); + HKS_TEST_ASSERT(ret == 0); + } + + ret = HksGenerateKey(*keyAlias, paramSet, paramSetOut); + HKS_TEST_ASSERT(ret == 0); + + HksFreeParamSet(¶mSet); + return ret; +} + +int32_t GenerateLocalRandomKey(struct HksBlob **keyAlias, const struct HksTestBlobParams *localKeyParams) +{ + int32_t ret = TestConstuctBlob(keyAlias, + localKeyParams->blobExist, + localKeyParams->blobSize, + localKeyParams->blobDataExist, + localKeyParams->blobDataSize); + HKS_TEST_ASSERT(ret == 0); + return ret; +} + +int32_t TestConstructBlobOut(struct HksBlob **blob, + bool blobExist, + uint32_t blobSize, + bool blobDataExist, + uint32_t realBlobDataSize) +{ + if (!blobExist) { // blob not exist + return 0; // do nothing, return null + } + + *blob = (struct HksBlob *)HksTestMalloc(sizeof(struct HksBlob)); + if (*blob == NULL) { + HKS_TEST_LOG_E("malloc fail"); + return HKS_ERROR_MALLOC_FAIL; + } + (void)memset_s(*blob, sizeof(struct HksBlob), 0, sizeof(struct HksBlob)); + + if (blobDataExist) { + (*blob)->size = realBlobDataSize; + (*blob)->data = (uint8_t *)HksTestMalloc(realBlobDataSize); + if ((*blob)->data == NULL) { + HKS_TEST_LOG_E("malloc fail"); + return HKS_ERROR_MALLOC_FAIL; + } + (void)memset_s((*blob)->data, realBlobDataSize, 0, realBlobDataSize); + } else { + (*blob)->data = NULL; + } + + (*blob)->size = blobSize; + return 0; +} + +int32_t GenerateLocalX25519Key(struct HksBlob **privateKey, struct HksBlob **publicKey, + const struct HksTestBlobParams *localPrivateKeyParams, const struct HksTestBlobParams *localPublicKeyParams) +{ + int32_t ret; + if ((privateKey != NULL) && (localPrivateKeyParams != NULL)) { + ret = TestConstuctBlob(privateKey, + localPrivateKeyParams->blobExist, + localPrivateKeyParams->blobSize, + localPrivateKeyParams->blobDataExist, + localPrivateKeyParams->blobDataSize); + HKS_TEST_ASSERT(ret == 0); + } + + if ((publicKey != NULL) && (localPublicKeyParams != NULL)) { + ret = TestConstuctBlob(publicKey, + localPublicKeyParams->blobExist, + localPublicKeyParams->blobSize, + localPublicKeyParams->blobDataExist, + localPublicKeyParams->blobDataSize); + HKS_TEST_ASSERT(ret == 0); + } + + struct HksParamSet *paramSet = NULL; + struct GenerateKeyParamSetStructure paramStruct = { + ¶mSet, true, true, HKS_ALG_X25519, + true, HKS_CURVE25519_KEY_SIZE_256, true, HKS_KEY_PURPOSE_SIGN | HKS_KEY_PURPOSE_VERIFY, false, 0, + false, 0, false, 0, true, HKS_STORAGE_TEMP + }; + ret = TestConstructGenerateKeyParamSet(¶mStruct); + HKS_TEST_ASSERT(ret == 0); + + struct HksParamSet *paramSetOut = NULL; + ret = TestConstructGenerateKeyParamSetOut(¶mSetOut, true, HKS_TEST_COMMON_128); + HKS_TEST_ASSERT(ret == 0); + + ret = HksGenerateKey(NULL, paramSet, paramSetOut); + HKS_TEST_ASSERT(ret == 0); + + if ((publicKey != NULL) && ((*publicKey) != NULL) && + (localPublicKeyParams->blobDataExist) && + (localPublicKeyParams->blobDataSize == (HKS_CURVE25519_KEY_SIZE_256 / HKS_TEST_COMMON_8))) { + (void)memcpy_s((*publicKey)->data, (*publicKey)->size, + paramSetOut->params[0].blob.data, paramSetOut->params[0].blob.size); + } + + if ((privateKey != NULL) && ((*privateKey) != NULL) && + (localPrivateKeyParams->blobDataExist) && + (localPrivateKeyParams->blobDataSize == (HKS_CURVE25519_KEY_SIZE_256 / HKS_TEST_COMMON_8))) { + (void)memcpy_s((*privateKey)->data, (*privateKey)->size, + paramSetOut->params[1].blob.data, paramSetOut->params[1].blob.size); + } + + HksFreeParamSet(¶mSet); + HksFreeParamSet(¶mSetOut); + return ret; +} + +int32_t TestGenDefaultKeyAndGetAlias(struct HksBlob **keyAlias) +{ + struct HksTestGenKeyParams genKeyParam = { + 0xffffffff, HKS_SUCCESS, + { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, { + true, + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_128, + true, HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT, + true, HKS_DIGEST_SHA256, + true, HKS_PADDING_NONE, + true, HKS_MODE_CBC }, + { false, 0 } + }; + + int32_t ret = TestConstuctBlob(keyAlias, + genKeyParam.keyAliasParams.blobExist, + genKeyParam.keyAliasParams.blobSize, + genKeyParam.keyAliasParams.blobDataExist, + genKeyParam.keyAliasParams.blobDataSize); + HKS_TEST_ASSERT(ret == 0); + + struct HksParamSet *paramSet = NULL; + struct GenerateKeyParamSetStructure paramStruct = { + ¶mSet, genKeyParam.paramSetParams.paramSetExist, + genKeyParam.paramSetParams.setAlg, genKeyParam.paramSetParams.alg, + genKeyParam.paramSetParams.setKeySize, genKeyParam.paramSetParams.keySize, + genKeyParam.paramSetParams.setPurpose, genKeyParam.paramSetParams.purpose, + genKeyParam.paramSetParams.setDigest, genKeyParam.paramSetParams.digest, + genKeyParam.paramSetParams.setPadding, genKeyParam.paramSetParams.padding, + genKeyParam.paramSetParams.setBlockMode, genKeyParam.paramSetParams.mode, + false, 0 + }; + ret = TestConstructGenerateKeyParamSet(¶mStruct); + HKS_TEST_ASSERT(ret == 0); + + ret = HksGenerateKey(*keyAlias, paramSet, NULL); + HKS_TEST_ASSERT(ret == 0); + + HksFreeParamSet(¶mSet); + return ret; +} diff --git a/test/unittest/src/common/hks_test_curve25519.c b/test/unittest/src/common/hks_test_curve25519.c new file mode 100644 index 00000000..605a5156 --- /dev/null +++ b/test/unittest/src/common/hks_test_curve25519.c @@ -0,0 +1,467 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include "hks_test_curve25519.h" +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_log.h" +#include "hks_type.h" + +#define TEST_ALIAS_ED25519 "test_ed25519" +#define TEST_PLAIN_TEST_ED25519 "This is a plain text! Hello world and thanks for watching ED25519~" +#define TEST_CURVE_256 256 +#define TEST_CURVE_512 512 + +static uint8_t g_buffer[TEST_CURVE_256]; +static uint32_t g_bufferSize = TEST_CURVE_256; +static uint8_t g_pubKey[TEST_CURVE_512] = {0}; +static uint32_t g_pubKeyLen = TEST_CURVE_512; + +int32_t TestGenerateEd25519Key(struct HksBlob alias) +{ + HKS_TEST_LOG_I("Test_GenerateEd25519!\n"); + struct HksParamSet *paramSet = NULL; + int32_t ret = HksInitParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + struct HksParam algParam = {0}; + algParam.tag = HKS_TAG_ALGORITHM; + algParam.uint32Param = HKS_ALG_ED25519; + ret = HksAddParams(paramSet, &algParam, 1); + HKS_TEST_ASSERT(ret == 0); + struct HksParam keySizeParam = {0}; + keySizeParam.tag = HKS_TAG_KEY_SIZE; + keySizeParam.uint32Param = TEST_CURVE_256; + ret = HksAddParams(paramSet, &keySizeParam, 1); + HKS_TEST_ASSERT(ret == 0); + struct HksParam purposeParam = {0}; + purposeParam.tag = HKS_TAG_PURPOSE; + purposeParam.uint32Param = HKS_KEY_PURPOSE_SIGN | HKS_KEY_PURPOSE_VERIFY; + ret = HksAddParams(paramSet, &purposeParam, 1); + HKS_TEST_ASSERT(ret == 0); + struct HksParam digestParam = {0}; + digestParam.tag = HKS_TAG_DIGEST; + digestParam.uint32Param = HKS_DIGEST_SHA512; + ret = HksAddParams(paramSet, &digestParam, 1); + HKS_TEST_ASSERT(ret == 0); + struct HksParam paddingParam = {0}; + paddingParam.tag = HKS_TAG_PADDING; + paddingParam.uint32Param = HKS_PADDING_NONE; + ret = HksAddParams(paramSet, &paddingParam, 1); + HKS_TEST_ASSERT(ret == 0); + ret = HksBuildParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + ret = HksGenerateKey(&alias, paramSet, NULL); + HKS_TEST_ASSERT(ret == 0); + HksFreeParamSet(¶mSet); + return ret; +} + +static int32_t TestSignEd25519(struct HksBlob alias) +{ + struct HksBlob msg = {strlen(TEST_PLAIN_TEST_ED25519), (uint8_t *)TEST_PLAIN_TEST_ED25519}; + + struct HksParamSet *paramSet = NULL; + int32_t ret = HksInitParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + struct HksParam algParam = {0}; + algParam.tag = HKS_TAG_ALGORITHM; + algParam.uint32Param = HKS_ALG_ED25519; + ret = HksAddParams(paramSet, &algParam, 1); + HKS_TEST_ASSERT(ret == 0); + struct HksParam purposeParam = {0}; + purposeParam.tag = HKS_TAG_PURPOSE; + purposeParam.uint32Param = HKS_KEY_PURPOSE_SIGN; + ret = HksAddParams(paramSet, &purposeParam, 1); + HKS_TEST_ASSERT(ret == 0); + struct HksParam digestParam = {0}; + digestParam.tag = HKS_TAG_DIGEST; + digestParam.uint32Param = HKS_DIGEST_SHA512; + ret = HksAddParams(paramSet, &digestParam, 1); + HKS_TEST_ASSERT(ret == 0); + struct HksParam paddingParam = {0}; + paddingParam.tag = HKS_TAG_PADDING; + paddingParam.uint32Param = HKS_PADDING_NONE; + ret = HksAddParams(paramSet, &paddingParam, 1); + HKS_TEST_ASSERT(ret == 0); + ret = HksBuildParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + struct HksBlob signature = { TEST_CURVE_256, g_buffer }; + ret = HksSign(&alias, paramSet, &msg, &signature); + HKS_TEST_ASSERT(ret == 0); + g_bufferSize = signature.size; + HKS_TEST_LOG_I("TestSignEd25519 signature size is %u", signature.size); + HksFreeParamSet(¶mSet); + return ret; +} + +static int32_t TestVerifyEd25519(struct HksBlob alias) +{ + struct HksBlob msg = {strlen(TEST_PLAIN_TEST_ED25519), (uint8_t *)TEST_PLAIN_TEST_ED25519}; + + HKS_TEST_LOG_I("TestVerifyEd25519!\n"); + struct HksParamSet *paramSet = NULL; + int32_t ret = HksInitParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam algParam = {0}; + algParam.tag = HKS_TAG_ALGORITHM; + algParam.uint32Param = HKS_ALG_ED25519; + ret = HksAddParams(paramSet, &algParam, 1); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam purposeParam = {0}; + purposeParam.tag = HKS_TAG_PURPOSE; + purposeParam.uint32Param = HKS_KEY_PURPOSE_VERIFY; + ret = HksAddParams(paramSet, &purposeParam, 1); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam digestParam = {0}; + digestParam.tag = HKS_TAG_DIGEST; + digestParam.uint32Param = HKS_DIGEST_SHA512; + ret = HksAddParams(paramSet, &digestParam, 1); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam paddingParam = {0}; + paddingParam.tag = HKS_TAG_PADDING; + paddingParam.uint32Param = HKS_PADDING_NONE; + ret = HksAddParams(paramSet, &paddingParam, 1); + HKS_TEST_ASSERT(ret == 0); + + ret = HksBuildParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + + struct HksBlob signature = { g_bufferSize, g_buffer }; + ret = HksVerify(&alias, paramSet, &msg, &signature); + HKS_TEST_ASSERT(ret == 0); + HksFreeParamSet(¶mSet); + return ret; +} + +int32_t TestImportEd25519(struct HksBlob alias, struct HksBlob *pubKeyInfo) +{ + HKS_TEST_LOG_I("TestImportEd25519!\n"); + struct HksParamSet *paramSet = NULL; + int32_t ret = HksInitParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam algParam = {0}; + algParam.tag = HKS_TAG_ALGORITHM; + algParam.uint32Param = HKS_ALG_ED25519; + ret = HksAddParams(paramSet, &algParam, 1); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam keySizeParam = {0}; + keySizeParam.tag = HKS_TAG_KEY_SIZE; + keySizeParam.uint32Param = TEST_CURVE_256; + ret = HksAddParams(paramSet, &keySizeParam, 1); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam purposeParam = {0}; + purposeParam.tag = HKS_TAG_PURPOSE; + purposeParam.uint32Param = HKS_KEY_PURPOSE_VERIFY; + ret = HksAddParams(paramSet, &purposeParam, 1); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam digestParam = {0}; + digestParam.tag = HKS_TAG_DIGEST; + digestParam.uint32Param = HKS_DIGEST_SHA512; + ret = HksAddParams(paramSet, &digestParam, 1); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam paddingParam = {0}; + paddingParam.tag = HKS_TAG_PADDING; + paddingParam.uint32Param = HKS_PADDING_NONE; + ret = HksAddParams(paramSet, &paddingParam, 1); + HKS_TEST_ASSERT(ret == 0); + + ret = HksBuildParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + + ret = HksImportKey(&alias, paramSet, pubKeyInfo); + HKS_TEST_ASSERT(ret == 0); + HksFreeParamSet(¶mSet); + return ret; +} + +static int32_t TestExportImportEd25519SignVerify(struct HksBlob alias) +{ + uint8_t pubKey[32] = {0}; + uint32_t pubKeyLen = 32; + struct HksBlob pubKeyInfo = { pubKeyLen, pubKey }; + int32_t ret = TestGenerateEd25519Key(alias); + HKS_TEST_ASSERT(ret == 0); + + ret = HksExportPublicKey(&alias, NULL, &pubKeyInfo); + HKS_TEST_ASSERT(ret == 0); + + ret = TestSignEd25519(alias); + HKS_TEST_ASSERT(ret == 0); + + ret = HksDeleteKey(&alias, NULL); + HKS_TEST_ASSERT(ret == 0); + + struct HksBlob newAlias = { strlen("test_ed25519_2"), (uint8_t *)"test_ed25519_2" }; + ret = TestImportEd25519(newAlias, &pubKeyInfo); + HKS_TEST_ASSERT(ret == 0); + ret = TestVerifyEd25519(newAlias); + HKS_TEST_ASSERT(ret == 0); + + ret = HksDeleteKey(&newAlias, NULL); + HKS_TEST_ASSERT(ret == 0); + return ret; +} + +int32_t TestCurve25519All() +{ + struct HksBlob ed25519Alias = { strlen(TEST_ALIAS_ED25519), (uint8_t *)TEST_ALIAS_ED25519 }; + int32_t ret = TestGenerateEd25519Key(ed25519Alias); + HKS_TEST_ASSERT(ret == 0); + ret = TestSignEd25519(ed25519Alias); + HKS_TEST_ASSERT(ret == 0); + ret = TestVerifyEd25519(ed25519Alias); + HKS_TEST_ASSERT(ret == 0); + ret = HksDeleteKey(&ed25519Alias, NULL); + HKS_TEST_ASSERT(ret == 0); + + ret = TestExportImportEd25519SignVerify(ed25519Alias); + HKS_TEST_ASSERT(ret == 0); + return ret; +} + +static int32_t BuildTeeSignParamSet(struct HksParamSet **paramSet) +{ + int32_t ret = HksInitParamSet(paramSet); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam algParam = {0}; + algParam.tag = HKS_TAG_ALGORITHM; + algParam.uint32Param = HKS_ALG_ED25519; + ret = HksAddParams(*paramSet, &algParam, 1); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam purposeParam = {0}; + purposeParam.tag = HKS_TAG_PURPOSE; + purposeParam.uint32Param = HKS_KEY_PURPOSE_SIGN; + ret = HksAddParams(*paramSet, &purposeParam, 1); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam digestParam = {0}; + digestParam.tag = HKS_TAG_DIGEST; + digestParam.uint32Param = HKS_DIGEST_SHA512; + ret = HksAddParams(*paramSet, &digestParam, 1); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam paddingParam = {0}; + paddingParam.tag = HKS_TAG_PADDING; + paddingParam.uint32Param = HKS_PADDING_NONE; + ret = HksAddParams(*paramSet, &paddingParam, 1); + HKS_TEST_ASSERT(ret == 0); + + ret = HksBuildParamSet(paramSet); + HKS_TEST_ASSERT(ret == 0); + return ret; +} + +static int32_t BuildLocalVerifyParamSet(struct HksParamSet **paramSet) +{ + int32_t ret = HksInitParamSet(paramSet); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam algParam = {0}; + algParam.tag = HKS_TAG_ALGORITHM; + algParam.uint32Param = HKS_ALG_ED25519; + ret = HksAddParams(*paramSet, &algParam, 1); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam isKeyAlias = {0}; + isKeyAlias.tag = HKS_TAG_IS_KEY_ALIAS; + isKeyAlias.boolParam = false; + ret = HksAddParams(*paramSet, &isKeyAlias, 1); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam keySizeParam = {0}; + keySizeParam.tag = HKS_TAG_KEY_SIZE; + keySizeParam.uint32Param = TEST_CURVE_256; + ret = HksAddParams(*paramSet, &keySizeParam, 1); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam purposeParam = {0}; + purposeParam.tag = HKS_TAG_PURPOSE; + purposeParam.uint32Param = HKS_KEY_PURPOSE_VERIFY; + ret = HksAddParams(*paramSet, &purposeParam, 1); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam digestParam = {0}; + digestParam.tag = HKS_TAG_DIGEST; + digestParam.uint32Param = HKS_DIGEST_SHA512; + ret = HksAddParams(*paramSet, &digestParam, 1); + HKS_TEST_ASSERT(ret == 0); + + ret = HksBuildParamSet(paramSet); + HKS_TEST_ASSERT(ret == 0); + return ret; +} + +int32_t TestEd25519SignTeeVerifyLocal() +{ + HKS_TEST_LOG_D("TestEd25519SignTeeVerifyLocal enter!"); + + struct HksBlob ed25519Alias = { strlen(TEST_ALIAS_ED25519), (uint8_t *)TEST_ALIAS_ED25519 }; + struct HksBlob msg = {strlen(TEST_PLAIN_TEST_ED25519), (uint8_t *)TEST_PLAIN_TEST_ED25519}; + struct HksBlob signature = { TEST_CURVE_256, g_buffer }; + struct HksParamSet *paramSetSign = NULL; + struct HksParamSet *paramSetVerify = NULL; + struct HksBlob pubKeyInfo = { g_pubKeyLen, g_pubKey }; + + int32_t ret = TestGenerateEd25519Key(ed25519Alias); + HKS_TEST_ASSERT(ret == 0); + + ret = HksExportPublicKey(&ed25519Alias, NULL, &pubKeyInfo); + HKS_TEST_ASSERT(ret == 0); + HKS_TEST_LOG_I("HksExportPublicKey puKey size is %u", pubKeyInfo.size); + + ret = BuildTeeSignParamSet(¶mSetSign); + HKS_TEST_ASSERT(ret == 0); + ret = HksSign(&ed25519Alias, paramSetSign, &msg, &signature); + HKS_TEST_ASSERT(ret == 0); + HKS_TEST_LOG_I("Test_Ed25519_Sign_TEE signature size is %u", signature.size); + + ret = BuildLocalVerifyParamSet(¶mSetVerify); + HKS_TEST_ASSERT(ret == 0); + ret = HksVerify(&pubKeyInfo, paramSetVerify, &msg, &signature); + HKS_TEST_ASSERT(ret == 0); + HKS_TEST_LOG_I("Test_Ed25519_Verify_Local Success"); + + ret = HksDeleteKey(&ed25519Alias, NULL); + HKS_TEST_ASSERT(ret == 0); + + HksFreeParamSet(¶mSetSign); + HksFreeParamSet(¶mSetVerify); + HKS_TEST_LOG_D("TestEd25519SignTeeVerifyLocal End!\n"); + return ret; +} + +static int32_t TestSignEd25519Wrong(struct HksBlob alias) +{ + struct HksBlob msg = {strlen(TEST_PLAIN_TEST_ED25519), (uint8_t *)TEST_PLAIN_TEST_ED25519}; + + struct HksParamSet *paramSet = NULL; + int32_t ret = HksInitParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + struct HksParam algParam = {0}; + algParam.tag = HKS_TAG_ALGORITHM; + algParam.uint32Param = HKS_ALG_ED25519; + ret = HksAddParams(paramSet, &algParam, 1); + HKS_TEST_ASSERT(ret == 0); + struct HksParam purposeParam = {0}; + purposeParam.tag = HKS_TAG_PURPOSE; + purposeParam.uint32Param = HKS_KEY_PURPOSE_VERIFY; + ret = HksAddParams(paramSet, &purposeParam, 1); + HKS_TEST_ASSERT(ret == 0); + struct HksParam digestParam = {0}; + digestParam.tag = HKS_TAG_DIGEST; + digestParam.uint32Param = HKS_DIGEST_SHA256; + ret = HksAddParams(paramSet, &digestParam, 1); + HKS_TEST_ASSERT(ret == 0); + struct HksParam paddingParam = {0}; + paddingParam.tag = HKS_TAG_PADDING; + paddingParam.uint32Param = HKS_PADDING_PKCS5; + ret = HksAddParams(paramSet, &paddingParam, 1); + HKS_TEST_ASSERT(ret == 0); + ret = HksBuildParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + struct HksBlob signature = { TEST_CURVE_256, g_buffer }; + ret = HksSign(&alias, paramSet, &msg, &signature); + HKS_TEST_ASSERT(ret != 0); + g_bufferSize = signature.size; + HKS_TEST_LOG_I("TestSignEd25519 signature size is %u", signature.size); + HksFreeParamSet(¶mSet); + return ret; +} + +int32_t TestCurve25519SignWrong() +{ + struct HksBlob ed25519Alias = { strlen(TEST_ALIAS_ED25519), (uint8_t *)TEST_ALIAS_ED25519 }; + int32_t ret = TestGenerateEd25519Key(ed25519Alias); + HKS_TEST_ASSERT(ret == 0); + ret = TestSignEd25519Wrong(ed25519Alias); + HKS_TEST_ASSERT(ret != 0); + int32_t retTwo = HksDeleteKey(&ed25519Alias, NULL); + HKS_TEST_ASSERT(retTwo == 0); + if ((ret != 0) && (retTwo == 0)) { + return 0; + } + return 1; +} + +static int32_t TestVerifyEd25519Wrong(struct HksBlob alias) +{ + struct HksBlob msg = {strlen(TEST_PLAIN_TEST_ED25519), (uint8_t *)TEST_PLAIN_TEST_ED25519}; + + HKS_TEST_LOG_I("TestVerifyEd25519!\n"); + struct HksParamSet *paramSet = NULL; + int32_t ret = HksInitParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam algParam = {0}; + algParam.tag = HKS_TAG_ALGORITHM; + algParam.uint32Param = HKS_ALG_ED25519; + ret = HksAddParams(paramSet, &algParam, 1); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam purposeParam = {0}; + purposeParam.tag = HKS_TAG_PURPOSE; + purposeParam.uint32Param = HKS_KEY_PURPOSE_SIGN; + ret = HksAddParams(paramSet, &purposeParam, 1); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam digestParam = {0}; + digestParam.tag = HKS_TAG_DIGEST; + digestParam.uint32Param = HKS_DIGEST_SHA256; + ret = HksAddParams(paramSet, &digestParam, 1); + HKS_TEST_ASSERT(ret == 0); + + struct HksParam paddingParam = {0}; + paddingParam.tag = HKS_TAG_PADDING; + paddingParam.uint32Param = HKS_PADDING_PKCS5; + ret = HksAddParams(paramSet, &paddingParam, 1); + HKS_TEST_ASSERT(ret == 0); + + ret = HksBuildParamSet(¶mSet); + HKS_TEST_ASSERT(ret == 0); + + struct HksBlob signature = { g_bufferSize, g_buffer }; + ret = HksVerify(&alias, paramSet, &msg, &signature); + HKS_TEST_ASSERT(ret != 0); + HksFreeParamSet(¶mSet); + return ret; +} + +int32_t TestCurve25519verifyWrong() +{ + struct HksBlob ed25519Alias = { strlen(TEST_ALIAS_ED25519), (uint8_t *)TEST_ALIAS_ED25519 }; + int32_t ret = TestGenerateEd25519Key(ed25519Alias); + HKS_TEST_ASSERT(ret == 0); + ret = TestSignEd25519(ed25519Alias); + HKS_TEST_ASSERT(ret == 0); + ret = TestVerifyEd25519Wrong(ed25519Alias); + HKS_TEST_ASSERT(ret != 0); + int32_t retTwo = HksDeleteKey(&ed25519Alias, NULL); + HKS_TEST_ASSERT(retTwo == 0); + if ((ret != 0) && (retTwo == 0)) { + return 0; + } + return 1; +} \ No newline at end of file diff --git a/test/unittest/src/common/hks_test_file_operator.c b/test/unittest/src/common/hks_test_file_operator.c new file mode 100644 index 00000000..1598aeeb --- /dev/null +++ b/test/unittest/src/common/hks_test_file_operator.c @@ -0,0 +1,336 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include "hks_test_file_operator.h" + +#ifndef __LITEOS_M__ +#include +#include +#include +#include +#include +#include + +/* use product definitions temporarily */ +#define DEFAULT_FILE_PERMISSION 0666 +#else + +#include + +#endif /* _STORAGE_LITE_ */ + + +#include "hks_param.h" +#include "hks_test_log.h" +#include "hks_test_mem.h" +#include "hks_type.h" +#include "securec.h" + +#define HKS_MAX_FILE_NAME_LEN 512 + +static int32_t GetFileName(const char *path, const char *fileName, char *fullFileName, uint32_t fullFileNameLen) +{ + if (path != NULL) { + if (strncpy_s(fullFileName, fullFileNameLen, path, strlen(path)) != EOK) { + return HKS_ERROR_INTERNAL_ERROR; + } + + if (path[strlen(path) - 1] != '/') { + if (strncat_s(fullFileName, fullFileNameLen, "/", strlen("/")) != EOK) { + return HKS_ERROR_INTERNAL_ERROR; + } + } + + if (strncat_s(fullFileName, fullFileNameLen, fileName, strlen(fileName)) != EOK) { + return HKS_ERROR_INTERNAL_ERROR; + } + } else { + if (strncpy_s(fullFileName, fullFileNameLen, fileName, strlen(fileName)) != EOK) { + return HKS_ERROR_INTERNAL_ERROR; + } + } + + return HKS_SUCCESS; +} + +static int32_t GetFullFileName(const char *path, const char *fileName, char **fullFileName) +{ + uint32_t nameLen = HKS_MAX_FILE_NAME_LEN; + char *tmpFileName = (char *)HksTestMalloc(nameLen); + if (tmpFileName == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + (void)memset_s(tmpFileName, nameLen, 0, nameLen); + + int32_t ret = GetFileName(path, fileName, tmpFileName, nameLen); + if (ret != HKS_SUCCESS) { + HKS_TEST_LOG_E("get full fileName failed"); + HksTestFree(tmpFileName); + return ret; + } + + *fullFileName = tmpFileName; + return HKS_SUCCESS; +} + +#ifndef __LITEOS_M__ +static int32_t IsFileExist(const char *fileName) +{ + if (access(fileName, F_OK) != 0) { + return HKS_ERROR_NOT_EXIST; + } + + return HKS_SUCCESS; +} + +static uint32_t FileRead(const char *fileName, uint32_t offset, uint8_t *buf, uint32_t len) +{ + (void)offset; + if (IsFileExist(fileName) != HKS_SUCCESS) { + return 0; + } + + char filePath[PATH_MAX + 1] = {0}; + (void)realpath(fileName, filePath); + if (strstr(filePath, "../") != NULL) { + HKS_TEST_LOG_E("invalid filePath, path %s", filePath); + return 0; + } + + FILE *fp = fopen(filePath, "rb"); + if (fp == NULL) { + HKS_TEST_LOG_E("failed to open file"); + return 0; + } + + uint32_t size = fread(buf, 1, len, fp); + if (fclose(fp) < 0) { + HKS_TEST_LOG_E("failed to close file"); + return 0; + } + + return size; +} + +static uint32_t FileSize(const char *fileName) +{ + if (IsFileExist(fileName) != HKS_SUCCESS) { + return 0; + } + + struct stat fileStat; + (void)memset_s(&fileStat, sizeof(fileStat), 0, sizeof(fileStat)); + if (stat(fileName, &fileStat) != 0) { + HKS_TEST_LOG_E("file stat fail."); + return 0; + } + + return fileStat.st_size; +} + +static int32_t FileWrite(const char *fileName, uint32_t offset, const uint8_t *buf, uint32_t len) +{ + (void)offset; + char filePath[PATH_MAX + 1] = {0}; + if (memcpy_s(filePath, sizeof(filePath) - 1, fileName, strlen(fileName)) != EOK) { + return HKS_ERROR_BAD_STATE; + } + (void)realpath(fileName, filePath); + if (strstr(filePath, "../") != NULL) { + HKS_TEST_LOG_E("invalid filePath, path %s", filePath); + return HKS_ERROR_INVALID_KEY_FILE; + } + + /* caller function ensures that the folder exists */ + FILE *fp = fopen(filePath, "wb+"); + if (fp == NULL) { + HKS_TEST_LOG_E("open file fail"); + return HKS_ERROR_OPEN_FILE_FAIL; + } + + if (chmod(filePath, S_IRUSR | S_IWUSR) < 0) { + HKS_TEST_LOG_E("chmod file fail."); + fclose(fp); + return HKS_ERROR_OPEN_FILE_FAIL; + } + + uint32_t size = fwrite(buf, 1, len, fp); + if (size != len) { + HKS_TEST_LOG_E("write file size fail."); + fclose(fp); + return HKS_ERROR_WRITE_FILE_FAIL; + } + + if (fclose(fp) < 0) { + HKS_TEST_LOG_E("failed to close file"); + return HKS_ERROR_CLOSE_FILE_FAIL; + } + + return HKS_SUCCESS; +} + +int32_t HksIsFileExist(const char *path, const char *fileName) +{ + if (fileName == NULL) { + return HKS_ERROR_NULL_POINTER; + } + + char *fullFileName = NULL; + int32_t ret = GetFullFileName(path, fileName, &fullFileName); + if (ret != HKS_SUCCESS) { + return ret; + } + + ret = IsFileExist(fullFileName); + HksTestFree(fullFileName); + return ret; +} +#else +static uint32_t FileRead(const char *fileName, uint32_t offset, uint8_t *buf, uint32_t len) +{ + /* now offset is 0, but we maybe extend hi1131 file interfaces in the future */ + if (offset != 0) { + return HKS_ERROR_INVALID_ARGUMENT; + } + + unsigned int fileSize; + int32_t ret = UtilsFileStat(fileName, &fileSize); + if (ret < 0) { + HKS_TEST_LOG_E("stat file failed, errno = 0x%x", ret); + return 0; + } + + if (len > fileSize) { + HKS_TEST_LOG_E("read data over file size!\n, file size = %d\n, buf len = %d\n", fileSize, len); + return 0; + } + + int fd = UtilsFileOpen(fileName, O_RDONLY_FS, 0); + if (fd < 0) { + HKS_TEST_LOG_E("failed to open file, errno = 0x%x", fd); + return 0; + } + + ret = UtilsFileRead(fd, buf, len); + UtilsFileClose(fd); + if (ret < 0) { + HKS_TEST_LOG_E("failed to read file, errno = 0x%x", ret); + return 0; + } + + return len; +} + +static int32_t FileWrite(const char *fileName, uint32_t offset, const uint8_t *buf, uint32_t len) +{ + /* now offset is 0, but we maybe extend hi1131 file interfaces in the future */ + if (offset != 0) { + return HKS_ERROR_INVALID_ARGUMENT; + } + + int fd = UtilsFileOpen(fileName, O_CREAT_FS | O_TRUNC_FS | O_RDWR_FS, 0); + if (fd < 0) { + HKS_TEST_LOG_E("failed to open key file, errno = 0x%x\n", fd); + return HKS_ERROR_OPEN_FILE_FAIL; + } + + int32_t ret = UtilsFileWrite(fd, buf, len); + if (ret < 0) { + HKS_TEST_LOG_E("failed to write key file, errno = 0x%x\n", ret); + ret = HKS_ERROR_WRITE_FILE_FAIL; + } + + ret = UtilsFileClose(fd); + if (ret < 0) { + HKS_TEST_LOG_E("failed to close file, errno = 0x%x\n", ret); + ret = HKS_ERROR_CLOSE_FILE_FAIL; + } + + return ret; +} + +static uint32_t FileSize(const char *fileName) +{ + unsigned int fileSize; + int32_t ret = UtilsFileStat(fileName, &fileSize); + if (ret < 0) { + HKS_TEST_LOG_E("stat file failed, errno = 0x%x", ret); + return 0; + } + return fileSize; +} + +int32_t HksTestFileRemove(const char *path, const char *fileName) +{ + char *fullFileName = NULL; + int32_t ret = GetFullFileName(path, fileName, &fullFileName); + if (ret != HKS_SUCCESS) { + return 0; + } + + return UtilsFileDelete(fullFileName); +} + +#endif +uint32_t HksTestFileRead(const char *path, const char *fileName, uint32_t offset, uint8_t *buf, uint32_t len) +{ + if ((fileName == NULL) || (buf == NULL) || (len == 0)) { + return 0; + } + + char *fullFileName = NULL; + int32_t ret = GetFullFileName(path, fileName, &fullFileName); + if (ret != HKS_SUCCESS) { + return 0; + } + + uint32_t size = FileRead(fullFileName, offset, buf, len); + HksTestFree(fullFileName); + return size; +} + +int32_t HksTestFileWrite(const char *path, const char *fileName, uint32_t offset, const uint8_t *buf, uint32_t len) +{ + if ((fileName == NULL) || (buf == NULL) || (len == 0)) { + return HKS_ERROR_INVALID_ARGUMENT; + } + + char *fullFileName = NULL; + int32_t ret = GetFullFileName(path, fileName, &fullFileName); + if (ret != HKS_SUCCESS) { + return ret; + } + + ret = FileWrite(fullFileName, offset, buf, len); + HksTestFree(fullFileName); + return ret; +} + +uint32_t HksTestFileSize(const char *path, const char *fileName) +{ + if (fileName == NULL) { + return 0; + } + + char *fullFileName = NULL; + int32_t ret = GetFullFileName(path, fileName, &fullFileName); + if (ret != HKS_SUCCESS) { + return 0; + } + + uint32_t size = FileSize(fullFileName); + HksTestFree(fullFileName); + return size; +} diff --git a/test/unittest/src/common/hks_test_log.c b/test/unittest/src/common/hks_test_log.c new file mode 100644 index 00000000..65f0abcb --- /dev/null +++ b/test/unittest/src/common/hks_test_log.c @@ -0,0 +1,65 @@ +/* + * Copyright (c) 2020-2021 Huawei Device Co., Ltd. + * 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. + */ + +#include "hks_test_log.h" + +#include "securec.h" + +#include "stdlib.h" + +#include "time.h" + +#define MAX_LOG_BUFF_LEN 512 +#define WAIT_TO_LOG_DONE 100000 + +void HksTestLog(uint32_t logLevel, const char *funcName, int32_t lineNo, const char *format, ...) +{ + char buf[MAX_LOG_BUFF_LEN] = { 0 }; + + va_list ap; + va_start(ap, format); + int32_t ret = vsnprintf_s(buf, MAX_LOG_BUFF_LEN, MAX_LOG_BUFF_LEN - 1, format, ap); + va_end(ap); + if (ret < 0) { + printf("hks log concatenate error."); + return; + } + + switch (logLevel) { + case HKS_LOG_LEVEL_I: + printf("[INFO] %s [%d]: %s\n", funcName, lineNo, buf); + break; + case HKS_LOG_LEVEL_E: + printf("[ERROR] %s [%d]: %s\n", funcName, lineNo, buf); + break; + case HKS_LOG_LEVEL_W: + printf("[WARNING] %s [%d]: %s\n", funcName, lineNo, buf); + break; + case HKS_LOG_LEVEL_D: + printf("[DEBUG] %s [%d]: %s\n", funcName, lineNo, buf); + break; + default: + return; + } + + usleep(WAIT_TO_LOG_DONE); +} + +void HksAssertLog(bool test) +{ + if (!(test)) { + HKS_TEST_LOG_E("[ASSERT] :fail\n"); + } +} diff --git a/test/unittest/src/common/hks_test_mem.c b/test/unittest/src/common/hks_test_mem.c new file mode 100644 index 00000000..c2d749ed --- /dev/null +++ b/test/unittest/src/common/hks_test_mem.c @@ -0,0 +1,29 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include "hks_test_mem.h" + +#include +#include + +void *HksTestMalloc(size_t size) +{ + return malloc(size); +} + +void HksTestFree(void *ptr) +{ + free(ptr); +} diff --git a/test/unittest/src/common/include/hks_aes_test.h b/test/unittest/src/common/include/hks_aes_test.h new file mode 100644 index 00000000..b28e7f0d --- /dev/null +++ b/test/unittest/src/common/include/hks_aes_test.h @@ -0,0 +1,25 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HUKS_AES_TEST_H +#define HUKS_AES_TEST_H + +int HksAesTest001(void); + +int HksAesTest002(void); + +int HksAesTest003(void); + +#endif diff --git a/test/unittest/src/common/include/hks_agreement_test.h b/test/unittest/src/common/include/hks_agreement_test.h new file mode 100644 index 00000000..4c8c8082 --- /dev/null +++ b/test/unittest/src/common/include/hks_agreement_test.h @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HUKS_AGREEMENT_TEST_H +#define HUKS_AGREEMENT_TEST_H + +int HksAgreementTest001(void); + +#endif diff --git a/test/unittest/src/common/include/hks_bn_exp_mod_test.h b/test/unittest/src/common/include/hks_bn_exp_mod_test.h new file mode 100644 index 00000000..daa07ba1 --- /dev/null +++ b/test/unittest/src/common/include/hks_bn_exp_mod_test.h @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HUKS_BN_EXP_MOD_TEST_H +#define HUKS_BN_EXP_MOD_TEST_H + +int HksBnExpModTest001(void); + +#endif diff --git a/test/unittest/src/common/include/hks_cipher_test.h b/test/unittest/src/common/include/hks_cipher_test.h new file mode 100644 index 00000000..4c2a27bc --- /dev/null +++ b/test/unittest/src/common/include/hks_cipher_test.h @@ -0,0 +1,43 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HUKS_CIPHER_TEST_H +#define HUKS_CIPHER_TEST_H + +int HksCipherTest001(void); + +int HksCipherTest002(void); + +int HksCipherTest003(void); + +int HksCipherTest004(void); + +int HksCipherTest005(void); + +int HksCipherTest006(void); + +int HksCipherTest007(void); + +int HksCipherTest008(void); + +int HksCipherTest009(void); + +int HksCipherTest010(void); + +int HksCipherTest011(void); + +int HksCipherTest012(void); + +#endif diff --git a/test/unittest/src/common/include/hks_curve25519_test.h b/test/unittest/src/common/include/hks_curve25519_test.h new file mode 100644 index 00000000..1e7cf3bc --- /dev/null +++ b/test/unittest/src/common/include/hks_curve25519_test.h @@ -0,0 +1,27 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HUKS_CURVE25519_TEST_H +#define HUKS_CURVE25519_TEST_H + +int HksCurve25519Test001(void); + +int HksCurve25519Test002(void); + +int HksCurve25519Test003(void); + +int HksCurve25519Test004(void); + +#endif \ No newline at end of file diff --git a/test/unittest/src/common/include/hks_delete_test.h b/test/unittest/src/common/include/hks_delete_test.h new file mode 100644 index 00000000..426745e7 --- /dev/null +++ b/test/unittest/src/common/include/hks_delete_test.h @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HUKS_DELETE_TEST_H +#define HUKS_DELETE_TEST_H + +int HksDeleteTest001(void); + +#endif diff --git a/test/unittest/src/common/include/hks_derive_test.h b/test/unittest/src/common/include/hks_derive_test.h new file mode 100644 index 00000000..356c4f42 --- /dev/null +++ b/test/unittest/src/common/include/hks_derive_test.h @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HUKS_DERIVE_TEST_H +#define HUKS_DERIVE_TEST_H + +int HksDeriveTest001(void); + +int HksDeriveTest002(void); + +#endif diff --git a/test/unittest/src/common/include/hks_exist_test.h b/test/unittest/src/common/include/hks_exist_test.h new file mode 100644 index 00000000..90c044bf --- /dev/null +++ b/test/unittest/src/common/include/hks_exist_test.h @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HUKS_EXIST_TEST_H +#define HUKS_EXIST_TEST_H + +int HksExistTest001(void); + +#endif diff --git a/test/unittest/src/common/include/hks_generate_key_test.h b/test/unittest/src/common/include/hks_generate_key_test.h new file mode 100644 index 00000000..8a829b66 --- /dev/null +++ b/test/unittest/src/common/include/hks_generate_key_test.h @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HUKS_GENERATE_KEY_TEST_H +#define HUKS_GENERATE_KEY_TEST_H + +int HksGenerateKeyTest001(void); + +#endif diff --git a/test/unittest/src/common/include/hks_generate_random_test.h b/test/unittest/src/common/include/hks_generate_random_test.h new file mode 100644 index 00000000..cfb5718c --- /dev/null +++ b/test/unittest/src/common/include/hks_generate_random_test.h @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HUKS_GENERATE_RANDOM_TEST_H +#define HUKS_GENERATE_RANDOM_TEST_H + +int HksGenerateRandomTest001(void); + +#endif diff --git a/test/unittest/src/common/include/hks_hash_test.h b/test/unittest/src/common/include/hks_hash_test.h new file mode 100644 index 00000000..2b7e1ee0 --- /dev/null +++ b/test/unittest/src/common/include/hks_hash_test.h @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HUKS_HASH_TEST_H +#define HUKS_HASH_TEST_H + +int HksHashTest001(void); + +#endif diff --git a/test/unittest/src/common/include/hks_mac_test.h b/test/unittest/src/common/include/hks_mac_test.h new file mode 100644 index 00000000..0c0ba458 --- /dev/null +++ b/test/unittest/src/common/include/hks_mac_test.h @@ -0,0 +1,23 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HUKS_MAC_TEST_H +#define HUKS_MAC_TEST_H + +int HksMacTest001(void); + +int HksMacTest002(void); + +#endif diff --git a/test/unittest/src/common/include/hks_modify_key_test.h b/test/unittest/src/common/include/hks_modify_key_test.h new file mode 100644 index 00000000..d1c41bc4 --- /dev/null +++ b/test/unittest/src/common/include/hks_modify_key_test.h @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HUKS_MODIFY_KEY_TEST_H +#define HUKS_MODIFY_KEY_TEST_H + +int HksModifyKeyTest001(void); + +#endif diff --git a/test/unittest/src/common/include/hks_others_test.h b/test/unittest/src/common/include/hks_others_test.h new file mode 100644 index 00000000..639a481d --- /dev/null +++ b/test/unittest/src/common/include/hks_others_test.h @@ -0,0 +1,35 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HUKS_OTHERS_TEST_H +#define HUKS_OTHERS_TEST_H + +int HksOthersTest001(void); + +int HksOthersTest002(void); + +int HksOthersTest003(void); + +int HksOthersTest004(void); + +int HksOthersTest005(void); + +int HksOthersTest006(void); + +int HksOthersTest007(void); + +int HksOthersTest008(void); + +#endif diff --git a/test/unittest/src/common/include/hks_safe_cipher_key_test.h b/test/unittest/src/common/include/hks_safe_cipher_key_test.h new file mode 100644 index 00000000..574d32a5 --- /dev/null +++ b/test/unittest/src/common/include/hks_safe_cipher_key_test.h @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HUKS_SAFE_CIPHER_KEY_TEST_H +#define HUKS_SAFE_CIPHER_KEY_TEST_H + +int HksSafeCipherKeyTest001(void); + +#endif diff --git a/test/unittest/src/common/include/hks_safe_compare_key_test.h b/test/unittest/src/common/include/hks_safe_compare_key_test.h new file mode 100644 index 00000000..f9af96e0 --- /dev/null +++ b/test/unittest/src/common/include/hks_safe_compare_key_test.h @@ -0,0 +1,21 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HUKS_SAFE_COMPARE_KEY_TEST_H +#define HUKS_SAFE_COMPARE_KEY_TEST_H + +int HksSafeCompareKeyTest001(void); + +#endif diff --git a/test/unittest/src/common/include/hks_test_aes.h b/test/unittest/src/common/include/hks_test_aes.h new file mode 100644 index 00000000..8ac79393 --- /dev/null +++ b/test/unittest/src/common/include/hks_test_aes.h @@ -0,0 +1,36 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_TEST_AES_H +#define HKS_TEST_AES_H +#include "hks_type.h" +#define TEST_ALIAS_AES "test_key_alias_aes" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t TestAes256ByAgree(); + +int32_t TestAes256ByAgree1(); + +int32_t TestAes256ByAgree2(); + +int32_t TestAes256ByLocal(); +#ifdef __cplusplus +} +#endif + +#endif /* HKS_TEST_AES_H */ diff --git a/test/unittest/src/common/include/hks_test_api_performance.h b/test/unittest/src/common/include/hks_test_api_performance.h new file mode 100644 index 00000000..fdc64f4d --- /dev/null +++ b/test/unittest/src/common/include/hks_test_api_performance.h @@ -0,0 +1,60 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_TEST_API_PERFORMANCE_H +#define HKS_TEST_API_PERFORMANCE_H + +#include "hks_type.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t HksGenerateKeyRun(const struct HksBlob *keyAlias, const struct HksParamSet *paramSetIn, + struct HksParamSet *paramSetOut, uint32_t performTimes); + +int32_t HksEncryptRun(const struct HksBlob *key, const struct HksParamSet *paramSet, + const struct HksBlob *plainText, struct HksBlob *cipherText, uint32_t performTimes); + +int32_t HksDecryptRun(const struct HksBlob *key, const struct HksParamSet *paramSet, + const struct HksBlob *cipherText, struct HksBlob *plainText, uint32_t performTimes); + +int32_t HksMacRun(const struct HksBlob *key, const struct HksParamSet *paramSet, + const struct HksBlob *srcData, struct HksBlob *mac, uint32_t performTimes); + +int32_t HksDeriveKeyRun(const struct HksParamSet *paramSet, const struct HksBlob *masterKey, + struct HksBlob *derivedKey, uint32_t performTimes); + + +int32_t HksDeleteKeyRun(const struct HksBlob *keyAlias, uint32_t performTimes); + +int32_t HksKeyExistRun(const struct HksBlob *keyAlias, uint32_t performTimes); + +int32_t HksGenerateRandomRun(struct HksBlob *random, uint32_t performTimes); + +int32_t HksAgreeKeyRun(const struct HksParamSet *paramSet, const struct HksBlob *privateKey, + const struct HksBlob *peerPublicKey, struct HksBlob *agreedKey, uint32_t performTimes); + +int32_t HksHashRun(const struct HksParamSet *paramSet, + const struct HksBlob *srcData, struct HksBlob *hash, uint32_t performTimes); + +int32_t HksBnExpModRun(struct HksBlob *x, const struct HksBlob *a, + const struct HksBlob *e, const struct HksBlob *n, uint32_t performTimes); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_TEST_API_PERFORMANCE_H */ \ No newline at end of file diff --git a/test/unittest/src/common/include/hks_test_cipher.h b/test/unittest/src/common/include/hks_test_cipher.h new file mode 100644 index 00000000..a45288c8 --- /dev/null +++ b/test/unittest/src/common/include/hks_test_cipher.h @@ -0,0 +1,68 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_TEST_CIPHER_H +#define HKS_TEST_CIPHER_H + +#include "hks_type.h" + +struct CipherEncryptStructure { + const struct HksBlob *keyAlias; + const struct HksTestCipherParamsParamSet *cipherParms; + struct HksBlob *plainData; + struct HksBlob *cipherData; + struct HksBlob **ivData; + struct HksBlob **nonceData; + struct HksBlob **aadData; + uint32_t performTimes; +}; + +struct OnlyDecryptStructure { + struct HksBlob *keyAlias; + const struct HksTestCipherParamsParamSet *cipherParms; + struct HksBlob *cipherData; + struct HksBlob *decryptedData; + struct HksBlob **ivData; + struct HksBlob **nonceData; + struct HksBlob **aadData; + uint32_t performTimes; +}; + +struct CipherDecryptStructure { + struct HksBlob *keyAlias; + const struct HksTestCipherParams *cipherParms; + struct HksBlob *cipherData; + struct HksBlob **decryptedData; + struct HksBlob *ivData; + struct HksBlob *nonceData; + struct HksBlob *aadData; + uint32_t performTimes; +}; + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t BaseTestCipher(uint32_t times, uint32_t index, uint32_t performTimes); + +int32_t BaseTestEncrypt(uint32_t times, uint32_t index, uint32_t performTimes); + +int32_t BaseTestDecrypt(uint32_t times, uint32_t index, uint32_t performTimes); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_TEST_COMMON_H */ \ No newline at end of file diff --git a/test/unittest/src/common/include/hks_test_common.h b/test/unittest/src/common/include/hks_test_common.h new file mode 100644 index 00000000..345afd08 --- /dev/null +++ b/test/unittest/src/common/include/hks_test_common.h @@ -0,0 +1,422 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_TEST_COMMON_H +#define HKS_TEST_COMMON_H + +#include "hks_type.h" + +#define HKS_SLICE_MAX_LEN 64 * 1024 + +#define DEFAULT_TEST_CASE_ID 0xFFFFFFFF +#define DEFAULT_EXECUTION_TIMES 0xFFFFFFFF +#define DEFAULT_PERFORM_TIMES 0xFFFFFFFF + +#define MAX_ARGS_LEN 20 +#define DEFAULT_KEY_ALIAS_SIZE 64 +#define DEFAULT_SLICE_SIZE (2 * 128 + 1) + +#define DEFAULT_PARAM_SET_OUT_SIZE 4096 +#define HKS_MAX_RANDOM_LEN 1024 +#define MAX_OUT_BLOB_SIZE (5 * 1024 * 1024) + +#define TEST_MAX_FILE_NAME_LEN 512 + +#define DEFAULT_LOCAL_KEY_SIZE 256 + +/* inputparams: struct HksBlob *blob */ +struct HksTestBlobParams { + bool blobExist; /* blob null or not */ + uint32_t blobSize; /* blob->size value */ + bool blobDataExist; /* blob->data null or not */ + uint32_t blobDataSize; /* blob->data malloc size */ +}; + +/* inputparams: struct HksParamSet *paramSet */ +struct HksTestGenKeyParamsParamSet { + bool paramSetExist; /* paramSet null or not */ + bool setAlg; + uint32_t alg; + bool setKeySize; + uint32_t keySize; + bool setPurpose; + uint32_t purpose; + bool setDigest; + uint32_t digest; + bool setPadding; + uint32_t padding; + bool setBlockMode; + uint32_t mode; + bool setKeyStorageFlag; + uint32_t keyStorageFlag; +}; + +struct HksTestGenKeyParamsParamSetOut { + bool paramSetExist; /* paramSet null or not */ + uint32_t paramSetSize; +}; + +enum HksTestCipherType { + HKS_TEST_CIPHER_TYPE_AES, + HKS_TEST_CIPHER_TYPE_RSA, +}; + +struct TestRsaCipherParamSet { + struct HksParamSet **outParamSet; + bool paramSetExist; + bool setAlg; + uint32_t alg; + bool setPurpose; + uint32_t purpose; + bool setDigest; + uint32_t digest; + bool setPadding; + uint32_t padding; +}; + +struct HksTestCipherParamsParamSet { + enum HksTestCipherType cipherType; + bool paramSetExist; /* paramSet null or not */ + bool setAlg; + uint32_t alg; + bool setPurpose; + uint32_t purpose; + bool setDigest; + uint32_t digest; + bool setPadding; + uint32_t padding; + bool setBlockMode; + uint32_t mode; + bool setIv; + uint32_t ivSize; + bool setNonce; + uint32_t nonceSize; + bool setAad; + uint32_t aadSize; + bool setIsKeyAlias; + bool isKeyAlias; +}; + +struct HksTestMacParamSet { + bool paramSetExist; /* paramSet null or not */ + bool setPurpose; + uint32_t purpose; + bool setDigest; + uint32_t digest; +}; + +struct HksTestDeriveParamSet { + bool paramSetExist; /* paramSet null or not */ + bool setAlg; + uint32_t alg; + bool setPurpose; + uint32_t purpose; + bool setDigest; + uint32_t digest; + bool setIteration; + uint32_t iteration; + bool setSalt; + uint32_t saltSize; + bool setInfo; + uint32_t infoSize; + bool setIsKeyAlias; + bool isKeyAlias; +}; + +struct HksTestAgreeParamSet { + bool paramSetExist; /* paramSet null or not */ + bool setAlg; + uint32_t alg; + bool setKeySize; + uint32_t keySize; + bool setIsKeyAlias; + bool isKeyAlias; +}; + +enum HksTestMacType { + HKS_TEST_MAC_TYPE_REE, + HKS_TEST_MAC_TYPE_TEE, +}; + +struct HksTestHashParamsParamSet { + bool paramSetExist; /* paramSet null or not */ + bool setDigest; + uint32_t digest; +}; + +struct HksTestParamSetOut { + bool paramSetExist; + uint32_t paramSetSize; + uint32_t realParamSetSize; +}; + +struct HksTestGenKeyParams { + uint32_t testId; + int32_t expectResult; + struct HksTestBlobParams keyAliasParams; + struct HksTestGenKeyParamsParamSet paramSetParams; + struct HksTestGenKeyParamsParamSetOut paramSetParamsOut; +}; + +struct HksTestCipherParams { + uint32_t testId; + int32_t expectResult; + struct HksTestBlobParams keyAliasParams; + struct HksTestGenKeyParamsParamSet genKeyParamSetParams; + struct HksTestGenKeyParamsParamSetOut genKeyParamSetParamsOut; + struct HksTestCipherParamsParamSet encryptParamSetParams; + struct HksTestCipherParamsParamSet decryptParamSetParams; + struct HksTestBlobParams plainTextParams; + struct HksTestBlobParams cipherTextParams; + struct HksTestBlobParams decryptedTextParams; + struct HksTestBlobParams localKeyParams; +}; + +struct HksTestEncryptParams { + uint32_t testId; + int32_t expectResult; + struct HksTestBlobParams keyAliasParams; + struct HksTestGenKeyParamsParamSet genKeyParamSetParams; + struct HksTestBlobParams encryptAliasParams; + struct HksTestCipherParamsParamSet encryptParamSetParams; + struct HksTestBlobParams inDataParams; + struct HksTestBlobParams outDataParams; + struct HksTestBlobParams localKeyParams; +}; + +struct HksTestDecryptParams { + uint32_t testId; + int32_t expectResult; + struct HksTestBlobParams keyAliasParams; + struct HksTestGenKeyParamsParamSet genKeyParamSetParams; + struct HksTestBlobParams decryptAliasParams; + struct HksTestCipherParamsParamSet decryptParamSetParams; + struct HksTestBlobParams inDataParams; + struct HksTestBlobParams outDataParams; + struct HksTestBlobParams localKeyParams; +}; + +struct HksTestMacParams { + uint32_t testId; + int32_t expectResult; + enum HksTestMacType macType; + struct HksTestBlobParams keyAliasParams; + struct HksTestGenKeyParamsParamSet genKeyParamSetParams; + struct HksTestBlobParams keyParams; + struct HksTestMacParamSet macParamSetParams; + struct HksTestBlobParams srcDataParams; + struct HksTestBlobParams macParams; +}; + +struct HksTestDeriveParams { + uint32_t testId; + int32_t expectResult; + struct HksTestBlobParams keyAliasParams; + struct HksTestGenKeyParamsParamSet genKeyParamSetParams; + struct HksTestBlobParams masterKeyParams; + struct HksTestDeriveParamSet deriveParamSetParams; + struct HksTestBlobParams derivedKeyParams; + struct HksTestBlobParams localKeyParams; +}; + +struct HksTestKeyExistParams { + uint32_t testId; + int32_t expectResult; + bool isGenKey; + struct HksTestBlobParams keyAliasParams; +}; + +struct HksTestGetKeyParamSetParams { + uint32_t testId; + int32_t expectResult; + bool isGenKey; + struct HksTestBlobParams keyAliasParams; + struct HksTestParamSetOut paramSetOutParams; +}; + +struct HksTestGenRandomParams { + uint32_t testId; + int32_t expectResult; + struct HksTestBlobParams randomParams; +}; + +struct HksTestHashParams { + uint32_t testId; + int32_t expectResult; + struct HksTestHashParamsParamSet paramSetParams; + struct HksTestBlobParams srcDataParams; + struct HksTestBlobParams hashParams; +}; + +struct HksTestBnExpModParams { + uint32_t testId; + int32_t expectResult; + bool isTestValue; + struct HksTestBlobParams xParams; + struct HksTestBlobParams aParams; + struct HksTestBlobParams eParams; + struct HksTestBlobParams nParams; +}; + +struct HksTestAgreeParams { + uint32_t testId; + int32_t expectResult; + struct HksTestBlobParams keyAlias1Params; + struct HksTestBlobParams keyAlias2Params; + struct HksTestGenKeyParamsParamSet genKeyParamSetParams; + struct HksTestBlobParams privateKeyParams; + struct HksTestAgreeParamSet agreeParamSetParams; + struct HksTestBlobParams peerPublicParams; + struct HksTestBlobParams agreedKeyParams; + struct HksTestBlobParams localPrivateKeyParams; + struct HksTestBlobParams localPublicKeyParams; +}; + +struct TestAgreeParamSetStructure { + struct HksParamSet **outParamSet; + bool paramSetExist; + bool setAlg; + uint32_t alg; + bool setKeySize; + uint32_t keySize; + bool setIsKeyAlias; + bool isKeyAlias; +}; + +struct GenerateKeyParamSetStructure { + struct HksParamSet **outParamSet; + bool paramSetExist; + bool setAlg; + uint32_t alg; + bool setKeySize; + uint32_t keySize; + bool setPurpose; + uint32_t purpose; + bool setDigest; + uint32_t digest; + bool setPadding; + uint32_t padding; + bool setBlockMode; + uint32_t mode; + bool setKeyStorageFlag; + uint32_t keyStorageFlag; +}; + +struct AesCipherParamSetStructure { + struct HksParamSet **outParamSet; + bool paramSetExist; + bool setAlg; + uint32_t alg; + bool setPurpose; + uint32_t purpose; + bool setPadding; + uint32_t padding; + bool setBlockMode; + uint32_t mode; + bool setIv; + const struct HksBlob *ivBlob; + bool setNonce; + const struct HksBlob *nonceBlob; + bool setAad; + const struct HksBlob *aadBlob; + bool setIsKeyAlias; + bool isKeyAlias; +}; + +struct TestMacParamSetStructure { + struct HksParamSet **outParamSet; + bool paramSetExist; + bool setPurpose; + uint32_t purpose; + bool setDigest; + uint32_t digest; + bool setKeyAlias; + bool isKeyAlias; +}; + +struct TestDeriveParamSetStructure { + struct HksParamSet **outParamSet; + bool paramSetExist; + bool setAlg; + uint32_t alg; + bool setPurpose; + uint32_t purpose; + bool setDigest; + uint32_t digest; + bool setIteration; + uint32_t iteration; + bool setSalt; + const struct HksBlob *saltBlob; + bool setInfo; + const struct HksBlob *infoBlob; + bool setIsKeyAlias; + bool isKeyAlias; +}; + +#ifdef __cplusplus +extern "C" { +#endif + +void TestFreeBlob(struct HksBlob **key); + +int32_t TestConstuctBlob(struct HksBlob **blob, + bool blobExist, + uint32_t blobSize, + bool blobDataExist, + uint32_t realBlobDataSize); + +int32_t TestConstructGenerateKeyParamSetOut( + struct HksParamSet **outParamSet, + bool paramSetExist, uint32_t paramSetSize); + +int32_t TestConstructGenerateKeyParamSet(struct GenerateKeyParamSetStructure *paramStruct); + +int32_t TestConstructRsaCipherParamSet(struct TestRsaCipherParamSet *paramStruct); + +int32_t TestConstructAesCipherParamSet(struct AesCipherParamSetStructure *paramStruct); + +int32_t TestConstructMacParamSet(struct TestMacParamSetStructure *paramStruct); + +int32_t TestConstructAgreeParamSet(struct TestAgreeParamSetStructure *paramStruct); + +int32_t GenerateLocalX25519Key(struct HksBlob **privateKey, struct HksBlob **publicKey, + const struct HksTestBlobParams *localPrivateKeyParams, const struct HksTestBlobParams *localPublicKeyParams); + +int32_t TestConstructDeriveParamSet(struct TestDeriveParamSetStructure *paramStruct); + +int32_t TestConstructHashParamSet( + struct HksParamSet **outParamSet, + bool paramSetExist, + bool setDigest, uint32_t digest); + +int32_t GenerateKey(struct HksBlob **keyAlias, const struct HksTestBlobParams *keyAliasParams, + const struct HksTestGenKeyParamsParamSet *genKeyParamSetParams, + const struct HksTestGenKeyParamsParamSetOut *genKeyParamSetParamsOut); + +int32_t GenerateLocalRandomKey(struct HksBlob **keyAlias, const struct HksTestBlobParams *localKeyParams); + +int32_t TestConstructBlobOut(struct HksBlob **blob, + bool blobExist, + uint32_t blobSize, + bool blobDataExist, + uint32_t realBlobDataSize); + +int32_t TestGenDefaultKeyAndGetAlias(struct HksBlob **keyAlias); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_TEST_COMMON_H */ diff --git a/test/unittest/src/common/include/hks_test_curve25519.h b/test/unittest/src/common/include/hks_test_curve25519.h new file mode 100644 index 00000000..faee5af3 --- /dev/null +++ b/test/unittest/src/common/include/hks_test_curve25519.h @@ -0,0 +1,40 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_TEST_CURVE25519 +#define HKS_TEST_CURVE25519 +#include "hks_type.h" + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t TestGenerateEd25519Key(struct HksBlob alias); + +int32_t TestImportEd25519(struct HksBlob alias, struct HksBlob *pubKeyInfo); + +int32_t TestCurve25519All(); + +int32_t TestEd25519SignTeeVerifyLocal(); + +int32_t TestCurve25519SignWrong(); + +int32_t TestCurve25519verifyWrong(); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/test/unittest/src/common/include/hks_test_file_operator.h b/test/unittest/src/common/include/hks_test_file_operator.h new file mode 100644 index 00000000..0673ec79 --- /dev/null +++ b/test/unittest/src/common/include/hks_test_file_operator.h @@ -0,0 +1,38 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include "hks_type.h" + +#ifndef HKS_TEST_FILE_OPERATOR_H +#define HKS_TEST_FILE_OPERATOR_H + +#ifdef __cplusplus +extern "C" { +#endif + +int32_t HksIsFileExist(const char *path, const char *fileName); + +uint32_t HksTestFileSize(const char *path, const char *fileName); + +uint32_t HksTestFileRead(const char *path, const char *fileName, uint32_t offset, uint8_t *buf, uint32_t len); + +int32_t HksTestFileWrite(const char *path, const char *fileName, uint32_t offset, const uint8_t *buf, uint32_t len); + +int32_t HksTestFileRemove(const char *path, const char *fileName); +#ifdef __cplusplus +} +#endif + +#endif /* HKS_TEST_FILE_OPERATOR_H */ diff --git a/test/unittest/src/common/include/hks_test_log.h b/test/unittest/src/common/include/hks_test_log.h new file mode 100644 index 00000000..051e52e1 --- /dev/null +++ b/test/unittest/src/common/include/hks_test_log.h @@ -0,0 +1,61 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_TEST_LOG_H +#define HKS_TEST_LOG_H + +#include "stdint.h" +#include "stdbool.h" + +enum HksLogLevel { + HKS_LOG_LEVEL_I, + HKS_LOG_LEVEL_E, + HKS_LOG_LEVEL_W, + HKS_LOG_LEVEL_D, +}; + +#ifdef __cplusplus +extern "C" { +#endif +void HksTestLog(uint32_t logLevel, const char *funcName, int32_t lineNo, const char *format, ...); +void HksAssertLog(bool test); + +#ifdef __cplusplus +} +#endif + +#define HKS_TEST_LOG_E(...) \ +do { \ + HksTestLog(HKS_LOG_LEVEL_E, __FUNCTION__, __LINE__, __VA_ARGS__); \ +} while (0) + +#define HKS_TEST_LOG_I(...) \ +do { \ + HksTestLog(HKS_LOG_LEVEL_I, __FUNCTION__, __LINE__, __VA_ARGS__); \ +} while (0) + +#define HKS_TEST_LOG_W(...) \ +do { \ + HksTestLog(HKS_LOG_LEVEL_W, __FUNCTION__, __LINE__, __VA_ARGS__); \ +} while (0) + +#define HKS_TEST_LOG_D(...) \ +do { \ + HksTestLog(HKS_LOG_LEVEL_D, __FUNCTION__, __LINE__, __VA_ARGS__); \ +} while (0) + +#define HKS_TEST_ASSERT HksAssertLog + +#endif /* HKS_TEST_LOG_H */ diff --git a/test/unittest/src/common/include/hks_test_mem.h b/test/unittest/src/common/include/hks_test_mem.h new file mode 100644 index 00000000..f0b7fba9 --- /dev/null +++ b/test/unittest/src/common/include/hks_test_mem.h @@ -0,0 +1,32 @@ +/* + * Copyright (c) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_TEST_MEM_H +#define HKS_TEST_MEM_H + +#include + +#ifdef __cplusplus +extern "C" { +#endif + +void *HksTestMalloc(size_t size); +void HksTestFree(void *ptr); + +#ifdef __cplusplus +} +#endif + +#endif /* HKS_TEST_MEM_H */ diff --git a/test/unittest/src/liteos_a_adapter/BUILD.gn b/test/unittest/src/liteos_a_adapter/BUILD.gn new file mode 100644 index 00000000..7aa194e9 --- /dev/null +++ b/test/unittest/src/liteos_a_adapter/BUILD.gn @@ -0,0 +1,60 @@ +# +# Copyright (c) 2021 Huawei Device Co., Ltd. +# 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. +# + +import("//base/security/huks/build/config.gni") +import("//build/lite/config/component/lite_component.gni") +import("//build/lite/config/test.gni") + +unittest("huks_new_test") { + output_extension = "bin" + output_dir = "$root_out_dir/test/unittest/security/" + sources = [ + "hks_aes_test.cpp", + "hks_agreement_test.cpp", + "hks_bn_exp_mod_test.cpp", + "hks_cipher_test.cpp", + "hks_curve25519_test.cpp", + "hks_delete_test.cpp", + "hks_derive_test.cpp", + "hks_exist_test.cpp", + "hks_generate_key_test.cpp", + "hks_generate_random_test.cpp", + "hks_hash_test.cpp", + "hks_mac_test.cpp", + "hks_modify_key_test.cpp", + "hks_others_test.cpp", + "hks_safe_cipher_key_test.cpp", + "hks_safe_compare_key_test.cpp", + ] + + include_dirs = [ + "//base/security/huks/huawei_property/include", + "../common/include", + ] + + deps = [ + "//base/security/huks/huawei_property/source:huks_new", + "//base/security/huks/huawei_property/test/unittest/src/common:huks_new_test_common", + ] + cflags = [ "-Wno-error" ] + + if (disable_authenticate == true) { + defines = [ "_CUT_AUTHENTICATE_" ] + } +} + +group("unittest") { + deps = [ ":huks_new_test" ] +} diff --git a/test/unittest/src/liteos_a_adapter/hks_aes_test.cpp b/test/unittest/src/liteos_a_adapter/hks_aes_test.cpp new file mode 100644 index 00000000..4dcc6d88 --- /dev/null +++ b/test/unittest/src/liteos_a_adapter/hks_aes_test.cpp @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include + +#include "hks_aes_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_aes.h" + +using namespace testing::ext; +namespace { +class HksAesTest : public testing::Test { +public: + static void SetUpTestCase(void); + + static void TearDownTestCase(void); + + void SetUp(); + + void TearDown(); +}; + +void HksAesTest::SetUpTestCase(void) +{ +} + +void HksAesTest::TearDownTestCase(void) +{ +} + +void HksAesTest::SetUp() +{ + EXPECT_EQ(HksInitialize(), 0); +} + +void HksAesTest::TearDown() +{ +} + +#ifndef _CUT_AUTHENTICATE_ +/** + * @tc.name: HksCipherTest.HksCipherTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksAesTest, HksAesTest001, TestSize.Level1) +{ + ASSERT_TRUE(TestAes256ByAgree() == 0); +} + +/** + * @tc.name: HksCipherTest.HksCipherTest002 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksAesTest, HksAesTest002, TestSize.Level1) +{ + ASSERT_TRUE(TestAes256ByAgree1() == 0); +} + +/** + * @tc.name: HksCipherTest.HksCipherTest003 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksAesTest, HksAesTest003, TestSize.Level1) +{ + ASSERT_TRUE(TestAes256ByAgree2() == 0); +} +#endif /* _CUT_AUTHENTICATE_ */ + +/** + * @tc.name: HksCipherTest.HksCipherTest003 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksAesTest, HksAesTest004, TestSize.Level1) +{ + ASSERT_EQ(TestAes256ByLocal(), 0); +} +} diff --git a/test/unittest/src/liteos_a_adapter/hks_agreement_test.cpp b/test/unittest/src/liteos_a_adapter/hks_agreement_test.cpp new file mode 100644 index 00000000..1752786e --- /dev/null +++ b/test/unittest/src/liteos_a_adapter/hks_agreement_test.cpp @@ -0,0 +1,206 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include + +#include "hks_agreement_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" +#include "hks_type.h" + +using namespace testing::ext; +namespace { +#ifndef _CUT_AUTHENTICATE_ + +class HksAgreementTest : public testing::Test { +public: + static void SetUpTestCase(void); + + static void TearDownTestCase(void); + + void SetUp(); + + void TearDown(); +}; + +void HksAgreementTest::SetUpTestCase(void) +{ +} + +void HksAgreementTest::TearDownTestCase(void) +{ +} + +void HksAgreementTest::SetUp() +{ + EXPECT_EQ(HksInitialize(), 0); +} + +void HksAgreementTest::TearDown() +{ +} + +const int TMP_SIZE = 512; +const int X25519_KEY_SIZE = 32; +const struct HksTestAgreeParams g_testAgreeParams[] = { + /* ree x25519 success */ + { 0, HKS_SUCCESS, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { true, true, HKS_ALG_X25519, true, HKS_CURVE25519_KEY_SIZE_256, true, + HKS_KEY_PURPOSE_SIGN | HKS_KEY_PURPOSE_VERIFY, true, HKS_DIGEST_SHA256, + false, 0, false, 0, true, HKS_STORAGE_TEMP }, + { 0 }, + { true, true, HKS_ALG_X25519, true, HKS_CURVE25519_KEY_SIZE_256, true, false }, + { true, TMP_SIZE, true, TMP_SIZE }, + { true, X25519_KEY_SIZE, true, X25519_KEY_SIZE }, + { true, X25519_KEY_SIZE, true, X25519_KEY_SIZE }, + { true, X25519_KEY_SIZE, true, X25519_KEY_SIZE } + }, +}; + +static int32_t AgreeKey(const struct HksTestAgreeParamSet *agreeParamSetParams, struct HksBlob *privateKey, + struct HksBlob *peerPublicKey, struct HksBlob *agreedKey) +{ + struct HksParamSet *agreeParamSet = NULL; + struct TestAgreeParamSetStructure paramStruct = { + &agreeParamSet, + agreeParamSetParams->paramSetExist, + agreeParamSetParams->setAlg, agreeParamSetParams->alg, + agreeParamSetParams->setKeySize, agreeParamSetParams->keySize, + agreeParamSetParams->setIsKeyAlias, agreeParamSetParams->isKeyAlias + }; + int32_t ret = TestConstructAgreeParamSet(¶mStruct); + HKS_TEST_ASSERT(ret == 0); + + ret = HksAgreeKeyRun(agreeParamSet, privateKey, peerPublicKey, agreedKey, 1); + HksFreeParamSet(&agreeParamSet); + return ret; +} + +/** + * @tc.name: HksDeleteTest.HksDeleteTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksAgreementTest, HksAgreementTest001, TestSize.Level1) +{ + /* 1. generate key */ + struct HksBlob *privateKey = NULL; + struct HksBlob *peerPubKeyAlias = NULL; + struct HksBlob *peerPublicKey = NULL; + int32_t ret; + + if (g_testAgreeParams[0].genKeyParamSetParams.setKeyStorageFlag && + (g_testAgreeParams[0].genKeyParamSetParams.keyStorageFlag == HKS_STORAGE_TEMP)) { + ret = GenerateLocalX25519Key(&privateKey, NULL, &g_testAgreeParams[0].localPrivateKeyParams, NULL); + ASSERT_TRUE(ret == 0); + ret = GenerateLocalX25519Key(NULL, &peerPublicKey, NULL, &g_testAgreeParams[0].localPublicKeyParams); + ASSERT_TRUE(ret == 0); + } + /* 2. agreeKey */ + struct HksBlob *agreeKey = NULL; + ret = TestConstuctBlob(&agreeKey, + g_testAgreeParams[0].agreedKeyParams.blobExist, + g_testAgreeParams[0].agreedKeyParams.blobSize, + g_testAgreeParams[0].agreedKeyParams.blobDataExist, + g_testAgreeParams[0].agreedKeyParams.blobDataSize); + ASSERT_TRUE(ret == 0); + + ret = AgreeKey(&g_testAgreeParams[0].agreeParamSetParams, privateKey, peerPublicKey, agreeKey); + ASSERT_TRUE(ret == g_testAgreeParams[0].expectResult); + + /* 3. delete key */ + if (!(g_testAgreeParams[0].genKeyParamSetParams.setKeyStorageFlag && + (g_testAgreeParams[0].genKeyParamSetParams.keyStorageFlag == HKS_STORAGE_TEMP)) && + ((g_testAgreeParams[0].keyAlias1Params.blobExist) && + (g_testAgreeParams[0].keyAlias2Params.blobExist))) { + ret = HksDeleteKey(privateKey, NULL); + ASSERT_TRUE(ret == 0); + ret = HksDeleteKey(peerPubKeyAlias, NULL); + ASSERT_TRUE(ret == 0); + } + TestFreeBlob(&privateKey); + TestFreeBlob(&peerPubKeyAlias); + TestFreeBlob(&peerPublicKey); + TestFreeBlob(&agreeKey); + ASSERT_TRUE(ret == 0); +} + +/** + * @tc.name: HksDeleteTest.HksDeleteTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksAgreementTest, HksAgreementTest002, TestSize.Level1) +{ + /* 1. generate key */ + struct HksBlob *privateKey = NULL; + struct HksBlob *peerPubKeyAlias = NULL; + struct HksBlob *peerPublicKey = NULL; + struct HksBlob *privateKey2 = NULL; + struct HksBlob *peerPubKeyAlias2 = NULL; + struct HksBlob *peerPublicKey2 = NULL; + int32_t ret; + + if (g_testAgreeParams[0].genKeyParamSetParams.setKeyStorageFlag && + (g_testAgreeParams[0].genKeyParamSetParams.keyStorageFlag == HKS_STORAGE_TEMP)) { + ret = GenerateLocalX25519Key(&privateKey, &peerPublicKey, &g_testAgreeParams[0].localPrivateKeyParams, \ + &g_testAgreeParams[0].localPublicKeyParams); + ASSERT_TRUE(ret == 0); + ret = GenerateLocalX25519Key(&privateKey2, &peerPublicKey2, &g_testAgreeParams[0].localPrivateKeyParams, \ + &g_testAgreeParams[0].localPublicKeyParams); + ASSERT_TRUE(ret == 0); + } + /* 2. agreeKey */ + struct HksBlob *agreeKey = NULL; + ret = TestConstuctBlob(&agreeKey, g_testAgreeParams[0].agreedKeyParams.blobExist, \ + g_testAgreeParams[0].agreedKeyParams.blobSize, g_testAgreeParams[0].agreedKeyParams.blobDataExist, \ + g_testAgreeParams[0].agreedKeyParams.blobDataSize); + ASSERT_TRUE(ret == 0); + + struct HksBlob *agreeKey2 = NULL; + ret = TestConstuctBlob(&agreeKey2, g_testAgreeParams[0].agreedKeyParams.blobExist, \ + g_testAgreeParams[0].agreedKeyParams.blobSize, g_testAgreeParams[0].agreedKeyParams.blobDataExist, \ + g_testAgreeParams[0].agreedKeyParams.blobDataSize); + ASSERT_TRUE(ret == 0); + + ret = AgreeKey(&g_testAgreeParams[0].agreeParamSetParams, privateKey, peerPublicKey2, agreeKey); + ASSERT_TRUE(ret == g_testAgreeParams[0].expectResult); + + ret = AgreeKey(&g_testAgreeParams[0].agreeParamSetParams, privateKey2, peerPublicKey, agreeKey2); + ASSERT_TRUE(ret == g_testAgreeParams[0].expectResult); + EXPECT_EQ(agreeKey->size, agreeKey2->size); + EXPECT_EQ(memcmp(agreeKey->data, agreeKey2->data, agreeKey->size), 0); + + /* 3. delete key */ + if (!(g_testAgreeParams[0].genKeyParamSetParams.setKeyStorageFlag && \ + (g_testAgreeParams[0].genKeyParamSetParams.keyStorageFlag == HKS_STORAGE_TEMP)) && \ + ((g_testAgreeParams[0].keyAlias1Params.blobExist) && (g_testAgreeParams[0].keyAlias2Params.blobExist))) { + ASSERT_TRUE(HksDeleteKey(privateKey, NULL) == 0); + ASSERT_TRUE(HksDeleteKey(peerPubKeyAlias, NULL) == 0); + } + TestFreeBlob(&privateKey); + TestFreeBlob(&peerPubKeyAlias); + TestFreeBlob(&peerPublicKey); + TestFreeBlob(&agreeKey); +} + + +#endif /* _CUT_AUTHENTICATE_ */ +} \ No newline at end of file diff --git a/test/unittest/src/liteos_a_adapter/hks_bn_exp_mod_test.cpp b/test/unittest/src/liteos_a_adapter/hks_bn_exp_mod_test.cpp new file mode 100644 index 00000000..fa182c31 --- /dev/null +++ b/test/unittest/src/liteos_a_adapter/hks_bn_exp_mod_test.cpp @@ -0,0 +1,144 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include + +#include "hks_bn_exp_mod_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" +#include "hks_type.h" + +using namespace testing::ext; +namespace { +class HksBnExpModTest : public testing::Test { +public: + static void SetUpTestCase(void); + + static void TearDownTestCase(void); + + void SetUp(); + + void TearDown(); +}; + +void HksBnExpModTest::SetUpTestCase(void) +{ +} + +void HksBnExpModTest::TearDownTestCase(void) +{ +} + +void HksBnExpModTest::SetUp() +{ + EXPECT_EQ(HksInitialize(), 0); +} + +void HksBnExpModTest::TearDown() +{ +} + +const int DEFAULT_X_SIZE = 256; +const int DEFAULT_A_SIZE = 256; +const int DEFAULT_E_SIZE = 256; +const int DEFAULT_N_SIZE = 256; +const int HKS_TEST_2 = 2; +const int HKS_TEST_8 = 8; + +const struct HksTestBnExpModParams g_testBnExpModParams[] = { + /* normal case */ + { 0, HKS_SUCCESS, false, + { true, DEFAULT_X_SIZE, true, DEFAULT_X_SIZE }, + { true, DEFAULT_A_SIZE, true, DEFAULT_A_SIZE }, + { true, DEFAULT_E_SIZE, true, DEFAULT_E_SIZE }, + { true, DEFAULT_N_SIZE, true, DEFAULT_N_SIZE } + }, +}; + +static int32_t TestValue() +{ + HKS_TEST_LOG_I("test value"); + uint8_t bufX[HKS_TEST_8] = { 0, 0, 0, 0, 0, 0, 0, 0x40 }; + uint8_t bufA[HKS_TEST_8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; + uint8_t bufE[HKS_TEST_2] = { 0, 2 }; + uint8_t bufN[HKS_TEST_8] = { 0, 1, 2, 3, 4, 5, 6, 7 }; + uint8_t tmpBufX[HKS_TEST_8] = {0}; + struct HksBlob tmpX = { HKS_TEST_8, tmpBufX }; + struct HksBlob tmpA = { HKS_TEST_8, bufA }; + struct HksBlob tmpE = { HKS_TEST_2, bufE }; + struct HksBlob tmpN = { HKS_TEST_8, bufN }; + int32_t ret = HksBnExpModRun(&tmpX, &tmpA, &tmpE, &tmpN, 1); + for (int i = 0; i < HKS_TEST_8; ++i) { + HKS_TEST_LOG_I("%x, %x", tmpBufX[i], bufX[i]); + HKS_TEST_ASSERT(tmpBufX[i] == bufX[i]); + } + return ret; +} + +/** + * @tc.name: HksBnExpModTest.HksBnExpModTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksBnExpModTest, HksBnExpModTest001, TestSize.Level1) +{ + int32_t ret; + if (g_testBnExpModParams[0].isTestValue) { + ret = TestValue(); + ASSERT_TRUE(ret == 0); + } else { + struct HksBlob *x = NULL; + struct HksBlob *a = NULL; + struct HksBlob *e = NULL; + struct HksBlob *n = NULL; + ret = TestConstuctBlob(&x, g_testBnExpModParams[0].xParams.blobExist, + g_testBnExpModParams[0].xParams.blobSize, g_testBnExpModParams[0].xParams.blobDataExist, + g_testBnExpModParams[0].xParams.blobDataSize); + HKS_TEST_ASSERT(ret == 0); + + ret = TestConstructBlobOut(&a, g_testBnExpModParams[0].aParams.blobExist, + g_testBnExpModParams[0].aParams.blobSize, g_testBnExpModParams[0].aParams.blobDataExist, + g_testBnExpModParams[0].aParams.blobDataSize); + HKS_TEST_ASSERT(ret == 0); + + ret = TestConstuctBlob(&e, g_testBnExpModParams[0].eParams.blobExist, + g_testBnExpModParams[0].eParams.blobSize, g_testBnExpModParams[0].eParams.blobDataExist, + g_testBnExpModParams[0].eParams.blobDataSize); + HKS_TEST_ASSERT(ret == 0); + + ret = TestConstuctBlob(&n, g_testBnExpModParams[0].nParams.blobExist, + g_testBnExpModParams[0].nParams.blobSize, g_testBnExpModParams[0].nParams.blobDataExist, + g_testBnExpModParams[0].nParams.blobDataSize); + HKS_TEST_ASSERT(ret == 0); + if ((n != NULL) && (n->data != NULL) && (n->size != 0)) { + n->data[n->size - 1] = n->data[n->size - 1] | 0x00000001; /* make sure n is odd */ + } + + ret = HksBnExpModRun(x, a, e, n, 1); + + HKS_TEST_ASSERT(ret == g_testBnExpModParams[0].expectResult); + + TestFreeBlob(&x); + TestFreeBlob(&a); + TestFreeBlob(&e); + TestFreeBlob(&n); + ASSERT_TRUE(ret == 0); + } +} +} \ No newline at end of file diff --git a/test/unittest/src/liteos_a_adapter/hks_cipher_test.cpp b/test/unittest/src/liteos_a_adapter/hks_cipher_test.cpp new file mode 100644 index 00000000..22de5c8e --- /dev/null +++ b/test/unittest/src/liteos_a_adapter/hks_cipher_test.cpp @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include + +#include "hks_cipher_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_cipher.h" + +using namespace testing::ext; +namespace { +class HksCipherTest : public testing::Test { +public: + static void SetUpTestCase(void); + + static void TearDownTestCase(void); + + void SetUp(); + + void TearDown(); +}; + +void HksCipherTest::SetUpTestCase(void) +{ +} + +void HksCipherTest::TearDownTestCase(void) +{ +} + +void HksCipherTest::SetUp() +{ + EXPECT_EQ(HksInitialize(), 0); +} + +void HksCipherTest::TearDown() +{ +} + +/** + * @tc.name: HksCipherTest.HksCipherTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksCipherTest, HksCipherTest001, TestSize.Level1) +{ + ASSERT_TRUE(BaseTestCipher(1, 0, 1) == 0); +} + +#ifndef _CUT_AUTHENTICATE_ +HWTEST_F(HksCipherTest, HksCipherTest002, TestSize.Level1) +{ + ASSERT_TRUE(BaseTestCipher(1, 1, 1) == 0); +} + +HWTEST_F(HksCipherTest, HksCipherTest003, TestSize.Level1) +{ + ASSERT_TRUE(BaseTestEncrypt(1, 0, 1) == 0); +} + +HWTEST_F(HksCipherTest, HksCipherTest004, TestSize.Level1) +{ + ASSERT_TRUE(BaseTestEncrypt(1, 1, 1) == 0); +} + +HWTEST_F(HksCipherTest, HksCipherTest005, TestSize.Level1) +{ + ASSERT_TRUE(BaseTestEncrypt(1, 2, 1) == 0); +} + +HWTEST_F(HksCipherTest, HksCipherTest006, TestSize.Level1) +{ + ASSERT_TRUE(BaseTestEncrypt(1, 3, 1) == 0); +} + +HWTEST_F(HksCipherTest, HksCipherTest007, TestSize.Level1) +{ + ASSERT_TRUE(BaseTestEncrypt(1, 4, 1) == 0); +} + +HWTEST_F(HksCipherTest, HksCipherTest008, TestSize.Level1) +{ + ASSERT_TRUE(BaseTestDecrypt(1, 0, 1) == 0); +} + +HWTEST_F(HksCipherTest, HksCipherTest009, TestSize.Level1) +{ + ASSERT_TRUE(BaseTestDecrypt(1, 1, 1) == 0); +} + +HWTEST_F(HksCipherTest, HksCipherTest010, TestSize.Level1) +{ + ASSERT_TRUE(BaseTestDecrypt(1, 2, 1) == 0); +} + +HWTEST_F(HksCipherTest, HksCipherTest011, TestSize.Level1) +{ + ASSERT_TRUE(BaseTestDecrypt(1, 3, 1) == 0); +} + +HWTEST_F(HksCipherTest, HksCipherTest012, TestSize.Level1) +{ + ASSERT_TRUE(BaseTestDecrypt(1, 4, 1) == 0); +} +#endif /* _CUT_AUTHENTICATE_ */ +} \ No newline at end of file diff --git a/test/unittest/src/liteos_a_adapter/hks_curve25519_test.cpp b/test/unittest/src/liteos_a_adapter/hks_curve25519_test.cpp new file mode 100644 index 00000000..13bd2c35 --- /dev/null +++ b/test/unittest/src/liteos_a_adapter/hks_curve25519_test.cpp @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include + +#include "hks_curve25519_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_curve25519.h" + +using namespace testing::ext; +namespace { +#ifndef _CUT_AUTHENTICATE_ +class HksCurve25519Test : public testing::Test { +public: + static void SetUpTestCase(void); + + static void TearDownTestCase(void); + + void SetUp(); + + void TearDown(); +}; + +void HksCurve25519Test::SetUpTestCase(void) +{ +} + +void HksCurve25519Test::TearDownTestCase(void) +{ +} + +void HksCurve25519Test::SetUp() +{ + EXPECT_EQ(HksInitialize(), 0); +} + +void HksCurve25519Test::TearDown() +{ +} + +/** + * @tc.name: HksCurve25519Test.HksCurve25519Test001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksCurve25519Test, HksCurve25519Test001, TestSize.Level1) +{ + ASSERT_TRUE(TestCurve25519All() == 0); +} + +/** + * @tc.name: HksCurve25519Test.HksCurve25519Test002 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksCurve25519Test, HksCurve25519Test002, TestSize.Level1) +{ + ASSERT_TRUE(TestEd25519SignTeeVerifyLocal() == 0); +} + +/** + * @tc.name: HksCurve25519Test.HksCurve25519Test003 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksCurve25519Test, HksCurve25519Test003, TestSize.Level1) +{ + ASSERT_TRUE(TestCurve25519SignWrong() == 0); +} + +/** + * @tc.name: HksCurve25519Test.HksCurve25519Test004 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksCurve25519Test, HksCurve25519Test004, TestSize.Level1) +{ + ASSERT_TRUE(TestCurve25519verifyWrong() == 0); +} +#endif /* _CUT_AUTHENTICATE_ */ +} \ No newline at end of file diff --git a/test/unittest/src/liteos_a_adapter/hks_delete_test.cpp b/test/unittest/src/liteos_a_adapter/hks_delete_test.cpp new file mode 100644 index 00000000..db5c8341 --- /dev/null +++ b/test/unittest/src/liteos_a_adapter/hks_delete_test.cpp @@ -0,0 +1,91 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include + +#include "hks_delete_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" +#include "hks_type.h" + +using namespace testing::ext; +namespace { +#ifndef _CUT_AUTHENTICATE_ +class HksDeleteTest : public testing::Test { +public: + static void SetUpTestCase(void); + + static void TearDownTestCase(void); + + void SetUp(); + + void TearDown(); +}; + +void HksDeleteTest::SetUpTestCase(void) +{ +} + +void HksDeleteTest::TearDownTestCase(void) +{ +} + +void HksDeleteTest::SetUp() +{ + EXPECT_EQ(HksInitialize(), 0); +} + +void HksDeleteTest::TearDown() +{ +} + +const struct HksTestKeyExistParams g_testKeyExistParams[] = { + /* normal case */ + { 0, HKS_SUCCESS, true, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE } }, +}; + +/** + * @tc.name: HksDeleteTest.HksDeleteTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksDeleteTest, HksDeleteTest001, TestSize.Level1) +{ + int32_t ret; + struct HksBlob *keyAlias = NULL; + if (g_testKeyExistParams[0].isGenKey) { + HKS_TEST_ASSERT(TestGenDefaultKeyAndGetAlias(&keyAlias) == 0); + } else { + ret = TestConstuctBlob(&keyAlias, + g_testKeyExistParams[0].keyAliasParams.blobExist, + g_testKeyExistParams[0].keyAliasParams.blobSize, + g_testKeyExistParams[0].keyAliasParams.blobDataExist, + g_testKeyExistParams[0].keyAliasParams.blobDataSize); + HKS_TEST_ASSERT(ret == 0); + } + + ret = HksDeleteKeyRun(keyAlias, 1); + HKS_TEST_ASSERT(ret == g_testKeyExistParams[0].expectResult); + + TestFreeBlob(&keyAlias); + ASSERT_TRUE(ret == 0); +} + +#endif /* _CUT_AUTHENTICATE_ */ +} \ No newline at end of file diff --git a/test/unittest/src/liteos_a_adapter/hks_derive_test.cpp b/test/unittest/src/liteos_a_adapter/hks_derive_test.cpp new file mode 100644 index 00000000..2f0f33a8 --- /dev/null +++ b/test/unittest/src/liteos_a_adapter/hks_derive_test.cpp @@ -0,0 +1,223 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include + +#include "hks_derive_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" + +using namespace testing::ext; +namespace { +class HksDeriveTest : public testing::Test { +public: + static void SetUpTestCase(void); + + static void TearDownTestCase(void); + + void SetUp(); + + void TearDown(); +}; + +void HksDeriveTest::SetUpTestCase(void) +{ +} + +void HksDeriveTest::TearDownTestCase(void) +{ +} + +void HksDeriveTest::SetUp() +{ + EXPECT_EQ(HksInitialize(), 0); +} + +void HksDeriveTest::TearDown() +{ +} + +const int DEFAULT_DERIVE_SIZE = 32; +const int DEFAULT_INFO_SIZE = 55; +const int DEFAULT_SALT_SIZE = 16; + +const struct HksTestDeriveParams g_testDeriveParams[] = { + /* hkdf-sha256-salt-info */ + { 0, HKS_SUCCESS, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, /* genKey params */ + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_DERIVE, + true, HKS_DIGEST_SHA256, + false, 0, + false, 0, + false, 0 }, + { 0 }, + { + true, /* derive params */ + true, HKS_ALG_HKDF, + true, HKS_KEY_PURPOSE_DERIVE, + true, HKS_DIGEST_SHA256, + false, 0, + true, DEFAULT_SALT_SIZE, + true, DEFAULT_INFO_SIZE, + false, true }, + { + true, DEFAULT_DERIVE_SIZE, true, DEFAULT_DERIVE_SIZE }, + { + false, 0, false, 0 } + }, + + /* local: hkdf-sha256-salt-info */ + { 1, HKS_SUCCESS, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, /* genKey params */ + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_DERIVE, + true, HKS_DIGEST_SHA256, + false, 0, + false, 0, + true, HKS_STORAGE_TEMP }, + { 0 }, + { + true, /* derive params */ + true, HKS_ALG_HKDF, + true, HKS_KEY_PURPOSE_DERIVE, + true, HKS_DIGEST_SHA256, + false, 0, + true, DEFAULT_SALT_SIZE, + true, DEFAULT_INFO_SIZE, + true, false }, + { + true, DEFAULT_DERIVE_SIZE, true, DEFAULT_DERIVE_SIZE }, + { + true, DEFAULT_LOCAL_KEY_SIZE, true, DEFAULT_LOCAL_KEY_SIZE } + }, +}; + +static int32_t DeriveKey(const struct HksTestDeriveParamSet *deriveParamSetParams, const struct HksBlob *masterKey, + struct HksBlob *derivedKey, struct HksBlob **saltData, struct HksBlob **infoData) +{ + struct HksParamSet *deriveParamSet = NULL; + uint32_t saltSize = deriveParamSetParams->saltSize; + uint32_t infoSize = deriveParamSetParams->infoSize; + if (saltSize != 0) { + HKS_TEST_ASSERT(TestConstuctBlob(saltData, true, saltSize, true, saltSize) == 0); + } + if (infoSize != 0) { + HKS_TEST_ASSERT(TestConstuctBlob(infoData, true, infoSize, true, infoSize) == 0); + } + struct TestDeriveParamSetStructure paramStruct = { + &deriveParamSet, + deriveParamSetParams->paramSetExist, + deriveParamSetParams->setAlg, deriveParamSetParams->alg, + deriveParamSetParams->setPurpose, deriveParamSetParams->purpose, + deriveParamSetParams->setDigest, deriveParamSetParams->digest, + deriveParamSetParams->setIteration, deriveParamSetParams->iteration, + deriveParamSetParams->setSalt, *saltData, + deriveParamSetParams->setInfo, *infoData, + deriveParamSetParams->setIsKeyAlias, deriveParamSetParams->isKeyAlias + }; + int32_t ret = TestConstructDeriveParamSet(¶mStruct); + HKS_TEST_ASSERT(ret == 0); + + ret = HksDeriveKeyRun(deriveParamSet, masterKey, derivedKey, 1); + HksFreeParamSet(&deriveParamSet); + return ret; +} + +static int32_t BaseTestDerive(uint32_t index) +{ + /* 1. generate key */ + struct HksBlob *keyAlias = NULL; + int32_t ret; + if (g_testDeriveParams[index].genKeyParamSetParams.setKeyStorageFlag && + (g_testDeriveParams[index].genKeyParamSetParams.keyStorageFlag == HKS_STORAGE_TEMP)) { + ret = GenerateLocalRandomKey(&keyAlias, &g_testDeriveParams[index].localKeyParams); + } else { + if (g_testDeriveParams[index].keyAliasParams.blobExist) { + ret = GenerateKey(&keyAlias, &g_testDeriveParams[index].keyAliasParams, + &g_testDeriveParams[index].genKeyParamSetParams, NULL); + } else { + ret = TestConstuctBlob(&keyAlias, + g_testDeriveParams[index].masterKeyParams.blobExist, + g_testDeriveParams[index].masterKeyParams.blobSize, + g_testDeriveParams[index].masterKeyParams.blobDataExist, + g_testDeriveParams[index].masterKeyParams.blobDataSize); + } + } + HKS_TEST_ASSERT(ret == 0); + + /* 2. derive */ + struct HksBlob *derivedKey = NULL; + ret = TestConstuctBlob(&derivedKey, + g_testDeriveParams[index].derivedKeyParams.blobExist, + g_testDeriveParams[index].derivedKeyParams.blobSize, + g_testDeriveParams[index].derivedKeyParams.blobDataExist, + g_testDeriveParams[index].derivedKeyParams.blobDataSize); + HKS_TEST_ASSERT(ret == 0); + + struct HksBlob *saltData = NULL; + struct HksBlob *infoData = NULL; + ret = DeriveKey(&g_testDeriveParams[index].deriveParamSetParams, keyAlias, derivedKey, &saltData, &infoData); + if (ret != g_testDeriveParams[index].expectResult) { + HKS_TEST_LOG_I("failed, ret[%u] = %d", g_testDeriveParams[index].testId, ret); + } + HKS_TEST_ASSERT(ret == g_testDeriveParams[index].expectResult); + + /* 3. delete key */ + if (!(g_testDeriveParams[index].genKeyParamSetParams.setKeyStorageFlag && + (g_testDeriveParams[index].genKeyParamSetParams.keyStorageFlag == HKS_STORAGE_TEMP)) && + (g_testDeriveParams[index].keyAliasParams.blobExist)) { + HKS_TEST_ASSERT(HksDeleteKey(keyAlias, NULL) == 0); + } + TestFreeBlob(&keyAlias); + TestFreeBlob(&derivedKey); + TestFreeBlob(&saltData); + TestFreeBlob(&infoData); + + return ret; +} + +#ifndef _CUT_AUTHENTICATE_ +/** + * @tc.name: HksDeriveTest.HksDeriveTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksDeriveTest, HksDeriveTest001, TestSize.Level1) +{ + int32_t ret = BaseTestDerive(0); + ASSERT_TRUE(ret == 0); +} +#endif /* _CUT_AUTHENTICATE_ */ + +/** + * @tc.name: HksDeriveTest.HksDeriveTest002 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksDeriveTest, HksDeriveTest002, TestSize.Level1) +{ + int32_t ret = BaseTestDerive(1); + ASSERT_TRUE(ret == 0); +} +} \ No newline at end of file diff --git a/test/unittest/src/liteos_a_adapter/hks_exist_test.cpp b/test/unittest/src/liteos_a_adapter/hks_exist_test.cpp new file mode 100644 index 00000000..d347851e --- /dev/null +++ b/test/unittest/src/liteos_a_adapter/hks_exist_test.cpp @@ -0,0 +1,94 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include + +#include "hks_exist_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" +#include "hks_type.h" + +using namespace testing::ext; +namespace { +#ifndef _CUT_AUTHENTICATE_ +class HksExistTest : public testing::Test { +public: + static void SetUpTestCase(void); + + static void TearDownTestCase(void); + + void SetUp(); + + void TearDown(); +}; + +void HksExistTest::SetUpTestCase(void) +{ +} + +void HksExistTest::TearDownTestCase(void) +{ +} + +void HksExistTest::SetUp() +{ + EXPECT_EQ(HksInitialize(), 0); +} + +void HksExistTest::TearDown() +{ +} + +const struct HksTestKeyExistParams g_testKeyExistParams[] = { + /* normal case */ + { 0, HKS_SUCCESS, true, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE } }, +}; + +/** + * @tc.name: HksExistTest.HksExistTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksExistTest, HksExistTest001, TestSize.Level1) +{ + int32_t ret; + struct HksBlob *keyAlias = NULL; + if (g_testKeyExistParams[0].isGenKey) { + HKS_TEST_ASSERT(TestGenDefaultKeyAndGetAlias(&keyAlias) == 0); + ret = HksKeyExistRun(keyAlias, 1); + HKS_TEST_ASSERT(ret == g_testKeyExistParams[0].expectResult); + HKS_TEST_ASSERT(HksDeleteKey(keyAlias, NULL) == HKS_SUCCESS); + } else { + ret = TestConstuctBlob(&keyAlias, + g_testKeyExistParams[0].keyAliasParams.blobExist, + g_testKeyExistParams[0].keyAliasParams.blobSize, + g_testKeyExistParams[0].keyAliasParams.blobDataExist, + g_testKeyExistParams[0].keyAliasParams.blobDataSize); + HKS_TEST_ASSERT(ret == 0); + ret = HksKeyExistRun(keyAlias, 1); + if (ret != g_testKeyExistParams[0].expectResult) { + HKS_TEST_LOG_I("HksKeyExistRun 2 failed, ret[%u] = %d", g_testKeyExistParams[0].testId, ret); + } + HKS_TEST_ASSERT(ret == g_testKeyExistParams[0].expectResult); + } + TestFreeBlob(&keyAlias); + ASSERT_TRUE(ret == 0); +} +#endif /* _CUT_AUTHENTICATE_ */ +} \ No newline at end of file diff --git a/test/unittest/src/liteos_a_adapter/hks_generate_key_test.cpp b/test/unittest/src/liteos_a_adapter/hks_generate_key_test.cpp new file mode 100644 index 00000000..43894c0e --- /dev/null +++ b/test/unittest/src/liteos_a_adapter/hks_generate_key_test.cpp @@ -0,0 +1,130 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include + +#include "hks_generate_key_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" + +using namespace testing::ext; +namespace { +#ifndef _CUT_AUTHENTICATE_ +class HksGenerateKeyTest : public testing::Test { +public: + static void SetUpTestCase(void); + + static void TearDownTestCase(void); + + void SetUp(); + + void TearDown(); +}; + +void HksGenerateKeyTest::SetUpTestCase(void) +{ +} + +void HksGenerateKeyTest::TearDownTestCase(void) +{ +} + +void HksGenerateKeyTest::SetUp() +{ + EXPECT_EQ(HksInitialize(), 0); +} + +void HksGenerateKeyTest::TearDown() +{ +} + +const int DEFAULT_X25519_PARAM_SET_OUT = 104; + +const struct HksTestGenKeyParams g_testGenKeyParams[] = { + /* x25519: ree sign/verify */ + { 0, HKS_SUCCESS, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, { + true, + true, HKS_ALG_X25519, + true, HKS_CURVE25519_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_SIGN | HKS_KEY_PURPOSE_VERIFY, + false, 0, + false, 0, + false, 0, + true, HKS_STORAGE_TEMP }, + { true, DEFAULT_X25519_PARAM_SET_OUT }, + }, +}; + +/** + * @tc.name: HksGenerateKeyTest.HksGenerateKeyTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksGenerateKeyTest, HksGenerateKeyTest001, TestSize.Level1) +{ + uint32_t times = 1; + uint32_t index = 0; + uint32_t performTimes = 1; + struct HksBlob *keyAlias = NULL; + int32_t ret = TestConstuctBlob(&keyAlias, + g_testGenKeyParams[index].keyAliasParams.blobExist, + g_testGenKeyParams[index].keyAliasParams.blobSize, + g_testGenKeyParams[index].keyAliasParams.blobDataExist, + g_testGenKeyParams[index].keyAliasParams.blobDataSize); + HKS_TEST_ASSERT(ret == 0); + + struct HksParamSet *paramSet = NULL; + struct GenerateKeyParamSetStructure paramStruct = { ¶mSet, + g_testGenKeyParams[index].paramSetParams.paramSetExist, + g_testGenKeyParams[index].paramSetParams.setAlg, g_testGenKeyParams[index].paramSetParams.alg, + g_testGenKeyParams[index].paramSetParams.setKeySize, g_testGenKeyParams[index].paramSetParams.keySize, + g_testGenKeyParams[index].paramSetParams.setPurpose, g_testGenKeyParams[index].paramSetParams.purpose, + g_testGenKeyParams[index].paramSetParams.setDigest, g_testGenKeyParams[index].paramSetParams.digest, + g_testGenKeyParams[index].paramSetParams.setPadding, g_testGenKeyParams[index].paramSetParams.padding, + g_testGenKeyParams[index].paramSetParams.setBlockMode, g_testGenKeyParams[index].paramSetParams.mode, + g_testGenKeyParams[index].paramSetParams.setKeyStorageFlag, + g_testGenKeyParams[index].paramSetParams.keyStorageFlag }; + ret = TestConstructGenerateKeyParamSet(¶mStruct); + HKS_TEST_ASSERT(ret == 0); + + struct HksParamSet *paramSetOut = NULL; + ret = TestConstructGenerateKeyParamSetOut(¶mSetOut, + g_testGenKeyParams[index].paramSetParamsOut.paramSetExist, + g_testGenKeyParams[index].paramSetParamsOut.paramSetSize); + HKS_TEST_ASSERT(ret == 0); + + ret = HksGenerateKeyRun(keyAlias, paramSet, paramSetOut, performTimes); + if (ret != g_testGenKeyParams[index].expectResult) { + HKS_TEST_LOG_I("failed, ret[%u] = %d", g_testGenKeyParams[index].testId, ret); + } + HKS_TEST_ASSERT(ret == g_testGenKeyParams[index].expectResult); + + if ((ret == HKS_SUCCESS) && + !(g_testGenKeyParams[index].paramSetParams.setKeyStorageFlag == true) && + (g_testGenKeyParams[index].paramSetParams.keyStorageFlag == HKS_STORAGE_TEMP)) { + HKS_TEST_ASSERT(HksDeleteKey(keyAlias, NULL) == 0); + } + TestFreeBlob(&keyAlias); + HksFreeParamSet(¶mSet); + HksFreeParamSet(¶mSetOut); + HKS_TEST_LOG_I("[%u]TestGenerateKey, Testcase_GenerateKey_[%03u] pass!", times, g_testGenKeyParams[index].testId); + ASSERT_TRUE(ret == 0); +} +#endif /* _CUT_AUTHENTICATE_ */ +} \ No newline at end of file diff --git a/test/unittest/src/liteos_a_adapter/hks_generate_random_test.cpp b/test/unittest/src/liteos_a_adapter/hks_generate_random_test.cpp new file mode 100644 index 00000000..f5ad2e91 --- /dev/null +++ b/test/unittest/src/liteos_a_adapter/hks_generate_random_test.cpp @@ -0,0 +1,87 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include + +#include "hks_generate_random_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" +#include "hks_type.h" + +using namespace testing::ext; +namespace { +class HksGenerateRandomTest : public testing::Test { +public: + static void SetUpTestCase(void); + + static void TearDownTestCase(void); + + void SetUp(); + + void TearDown(); +}; + +void HksGenerateRandomTest::SetUpTestCase(void) +{ +} + +void HksGenerateRandomTest::TearDownTestCase(void) +{ +} + +void HksGenerateRandomTest::SetUp() +{ + EXPECT_EQ(HksInitialize(), 0); +} + +void HksGenerateRandomTest::TearDown() +{ +} + +const struct HksTestGenRandomParams g_testGenRandomParams[] = { + /* normal case */ + { 0, HKS_SUCCESS, { true, HKS_MAX_RANDOM_LEN, true, HKS_MAX_RANDOM_LEN } }, +}; +/** + * @tc.name: HksGenerateRandomTest.HksGenerateRandomTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksGenerateRandomTest, HksGenerateRandomTest001, TestSize.Level1) +{ + int32_t ret; + struct HksBlob *random = NULL; + + ret = TestConstructBlobOut(&random, + g_testGenRandomParams[0].randomParams.blobExist, + g_testGenRandomParams[0].randomParams.blobSize, + g_testGenRandomParams[0].randomParams.blobDataExist, + g_testGenRandomParams[0].randomParams.blobDataSize); + HKS_TEST_ASSERT(ret == 0); + + ret = HksGenerateRandomRun(random, 1); + if (ret != g_testGenRandomParams[0].expectResult) { + HKS_TEST_LOG_I("HksGenerateRandomRun failed, ret[%u] = %d", g_testGenRandomParams[0].testId, ret); + } + HKS_TEST_ASSERT(ret == g_testGenRandomParams[0].expectResult); + + TestFreeBlob(&random); + ASSERT_TRUE(ret == 0); +} +} \ No newline at end of file diff --git a/test/unittest/src/liteos_a_adapter/hks_hash_test.cpp b/test/unittest/src/liteos_a_adapter/hks_hash_test.cpp new file mode 100644 index 00000000..4e457513 --- /dev/null +++ b/test/unittest/src/liteos_a_adapter/hks_hash_test.cpp @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include + +#include "hks_hash_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" +#include "hks_type.h" + +using namespace testing::ext; +namespace { +#ifndef _CUT_AUTHENTICATE_ + +class HksHashTest : public testing::Test { +public: + static void SetUpTestCase(void); + + static void TearDownTestCase(void); + + void SetUp(); + + void TearDown(); +}; + +void HksHashTest::SetUpTestCase(void) +{ +} + +void HksHashTest::TearDownTestCase(void) +{ +} + +void HksHashTest::SetUp() +{ + EXPECT_EQ(HksInitialize(), 0); +} + +void HksHashTest::TearDown() +{ +} + +const int DEFAULT_SRC_DATA_SIZE = 200; +const int DIGEST_SHA256_HASH_SIZE = 32; + +const struct HksTestHashParams g_testHashParams[] = { + /* normal case */ + { 0, HKS_SUCCESS, + { true, true, HKS_DIGEST_SHA256}, + { true, DEFAULT_SRC_DATA_SIZE, true, DEFAULT_SRC_DATA_SIZE }, + { true, DIGEST_SHA256_HASH_SIZE, true, DIGEST_SHA256_HASH_SIZE } + }, +}; + +/** + * @tc.name: HksHashTest.HksHashTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksHashTest, HksHashTest001, TestSize.Level1) +{ + struct HksParamSet *paramSet = NULL; + struct HksBlob *srcData = NULL; + struct HksBlob *hash = NULL; + + int32_t ret = TestConstructHashParamSet(¶mSet, + g_testHashParams[0].paramSetParams.paramSetExist, + g_testHashParams[0].paramSetParams.setDigest, g_testHashParams[0].paramSetParams.digest); + HKS_TEST_ASSERT(ret == 0); + + ret = TestConstuctBlob(&srcData, + g_testHashParams[0].srcDataParams.blobExist, + g_testHashParams[0].srcDataParams.blobSize, + g_testHashParams[0].srcDataParams.blobDataExist, + g_testHashParams[0].srcDataParams.blobDataSize); + HKS_TEST_ASSERT(ret == 0); + + ret = TestConstructBlobOut(&hash, + g_testHashParams[0].hashParams.blobExist, + g_testHashParams[0].hashParams.blobSize, + g_testHashParams[0].hashParams.blobDataExist, + g_testHashParams[0].hashParams.blobDataSize); + HKS_TEST_ASSERT(ret == 0); + + ret = HksHashRun(paramSet, srcData, hash, 1); + if (ret != g_testHashParams[0].expectResult) { + HKS_TEST_LOG_I("HksHashRun failed, ret[%u] = %d", g_testHashParams[0].testId, ret); + } + HKS_TEST_ASSERT(ret == g_testHashParams[0].expectResult); + + HksFreeParamSet(¶mSet); + TestFreeBlob(&srcData); + TestFreeBlob(&hash); + HKS_TEST_LOG_I("[%u]TestHash, Testcase_Hash_[%03u] pass!", 1, g_testHashParams[0].testId); + ASSERT_TRUE(ret == 0); +} +#endif /* _CUT_AUTHENTICATE_ */ +} \ No newline at end of file diff --git a/test/unittest/src/liteos_a_adapter/hks_mac_test.cpp b/test/unittest/src/liteos_a_adapter/hks_mac_test.cpp new file mode 100644 index 00000000..f590c65c --- /dev/null +++ b/test/unittest/src/liteos_a_adapter/hks_mac_test.cpp @@ -0,0 +1,203 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include + +#include "hks_mac_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" + +using namespace testing::ext; +namespace { +class HksMacTest : public testing::Test { +public: + static void SetUpTestCase(void); + + static void TearDownTestCase(void); + + void SetUp(); + + void TearDown(); +}; + +void HksMacTest::SetUpTestCase(void) +{ +} + +void HksMacTest::TearDownTestCase(void) +{ +} + +void HksMacTest::SetUp() +{ + EXPECT_EQ(HksInitialize(), 0); +} + +void HksMacTest::TearDown() +{ +} + +const int HKS_TEST_MAC_REE_KEY_SIZE_32 = 32; +const int HKS_DEFAULT_MAC_SRCDATA_SIZE = 253; +const int HKS_DEFAULT_MAC_SHA256_SIZE = 32; + + +const struct HksTestMacParams g_testMacParams[] = { + /* success: ree-sha256 */ + { 0, HKS_SUCCESS, HKS_TEST_MAC_TYPE_REE, { 0 }, { 0 }, + { true, HKS_TEST_MAC_REE_KEY_SIZE_32, true, HKS_TEST_MAC_REE_KEY_SIZE_32 }, + { true, true, HKS_KEY_PURPOSE_MAC, true, HKS_DIGEST_SHA256 }, + { true, HKS_DEFAULT_MAC_SRCDATA_SIZE, true, HKS_DEFAULT_MAC_SRCDATA_SIZE }, + { true, HKS_DEFAULT_MAC_SHA256_SIZE, true, HKS_DEFAULT_MAC_SHA256_SIZE } + }, + + /* success: tee-sha256 */ + { 1, HKS_SUCCESS, HKS_TEST_MAC_TYPE_TEE, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + {true, true, HKS_ALG_AES, true, HKS_AES_KEY_SIZE_256, true, HKS_KEY_PURPOSE_MAC, + true, HKS_DIGEST_SHA256, false, 0, false, 0 }, + { 0 }, + { true, true, HKS_KEY_PURPOSE_MAC, true, HKS_DIGEST_SHA256 }, + { true, HKS_DEFAULT_MAC_SRCDATA_SIZE, true, HKS_DEFAULT_MAC_SRCDATA_SIZE }, + { true, HKS_DEFAULT_MAC_SHA256_SIZE, true, HKS_DEFAULT_MAC_SHA256_SIZE } + }, +}; + +static int32_t ConstructDataToBlob(struct HksBlob **srcData, struct HksBlob **macData, + const struct HksTestBlobParams *srcDataParams, const struct HksTestBlobParams *macDataParams) +{ + int32_t ret = TestConstuctBlob(srcData, + srcDataParams->blobExist, + srcDataParams->blobSize, + srcDataParams->blobDataExist, + srcDataParams->blobDataSize); + HKS_TEST_ASSERT(ret == 0); + + ret = TestConstuctBlob(macData, + macDataParams->blobExist, + macDataParams->blobSize, + macDataParams->blobDataExist, + macDataParams->blobDataSize); + HKS_TEST_ASSERT(ret == 0); + return ret; +} + +static int32_t Mac(const struct HksBlob *key, const struct HksBlob *srcData, struct HksBlob *macData, + const struct HksTestMacParamSet *macParamSetParams, enum HksTestMacType macType) +{ + struct HksParamSet *macParamSet = NULL; + int32_t ret; + if (macType == HKS_TEST_MAC_TYPE_REE) { + struct TestMacParamSetStructure paramStructTrue = { + &macParamSet, + macParamSetParams->paramSetExist, + macParamSetParams->setPurpose, macParamSetParams->purpose, + macParamSetParams->setDigest, macParamSetParams->digest, true, false + }; + ret = TestConstructMacParamSet(¶mStructTrue); + } else { + struct TestMacParamSetStructure paramStructFalse = { + &macParamSet, + macParamSetParams->paramSetExist, + macParamSetParams->setPurpose, macParamSetParams->purpose, + macParamSetParams->setDigest, macParamSetParams->digest, false, false + }; + ret = TestConstructMacParamSet(¶mStructFalse); + } + HKS_TEST_ASSERT(ret == 0); + + ret = HksMacRun(key, macParamSet, srcData, macData, 1); + HksFreeParamSet(&macParamSet); + return ret; +} + +static int32_t BaseTestMac(uint32_t index) +{ + /* 1. generate key */ + struct HksBlob *key = NULL; + int32_t ret; + + if (g_testMacParams[index].macType == HKS_TEST_MAC_TYPE_REE) { + ret = TestConstuctBlob(&key, + g_testMacParams[index].keyParams.blobExist, + g_testMacParams[index].keyParams.blobSize, + g_testMacParams[index].keyParams.blobDataExist, + g_testMacParams[index].keyParams.blobDataSize); + } else { + if (g_testMacParams[index].keyAliasParams.blobExist) { + ret = GenerateKey(&key, &(g_testMacParams[index].keyAliasParams), + &g_testMacParams[index].genKeyParamSetParams, NULL); + } else { + ret = TestConstuctBlob(&key, + g_testMacParams[index].keyParams.blobExist, + g_testMacParams[index].keyParams.blobSize, + g_testMacParams[index].keyParams.blobDataExist, + g_testMacParams[index].keyParams.blobDataSize); + } + } + HKS_TEST_ASSERT(ret == 0); + + /* 2. mac */ + struct HksBlob *srcData = NULL; + struct HksBlob *macData = NULL; + ret = ConstructDataToBlob(&srcData, &macData, + &g_testMacParams[index].srcDataParams, &g_testMacParams[index].macParams); + HKS_TEST_ASSERT(ret == 0); + + ret = Mac(key, srcData, macData, &g_testMacParams[index].macParamSetParams, g_testMacParams[index].macType); + if (ret != g_testMacParams[index].expectResult) { + HKS_TEST_LOG_I("failed, ret[%u] = %d", g_testMacParams[index].testId, ret); + } + HKS_TEST_ASSERT(ret == g_testMacParams[index].expectResult); + + /* 3. deletekey */ + if ((g_testMacParams[index].macType == HKS_TEST_MAC_TYPE_TEE) && + (g_testMacParams[index].keyAliasParams.blobExist)) { + ret = HksDeleteKey(key, NULL); + HKS_TEST_ASSERT(ret == 0); + } + TestFreeBlob(&key); + TestFreeBlob(&srcData); + TestFreeBlob(&macData); + return ret; +} + +/** + * @tc.name: HksMacTest.HksMacTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksMacTest, HksMacTest001, TestSize.Level1) +{ + int32_t ret = BaseTestMac(0); + ASSERT_TRUE(ret == 0); +} + +#ifndef _CUT_AUTHENTICATE_ +/** + * @tc.name: HksMacTest.HksMacTest002 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksMacTest, HksMacTest002, TestSize.Level1) +{ + int32_t ret = BaseTestMac(1); + ASSERT_TRUE(ret == 0); +} +#endif /* _CUT_AUTHENTICATE_ */ +} \ No newline at end of file diff --git a/test/unittest/src/liteos_a_adapter/hks_modify_key_test.cpp b/test/unittest/src/liteos_a_adapter/hks_modify_key_test.cpp new file mode 100644 index 00000000..2b099954 --- /dev/null +++ b/test/unittest/src/liteos_a_adapter/hks_modify_key_test.cpp @@ -0,0 +1,357 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include + +#include "hks_modify_key_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_cipher.h" +#include "hks_test_common.h" +#include "hks_test_file_operator.h" +#include "hks_test_log.h" +#include "hks_test_mem.h" + +#include "securec.h" + +using namespace testing::ext; +namespace { +#ifndef _CUT_AUTHENTICATE_ + +class HksModifyKeyTest : public testing::Test { +public: + static void SetUpTestCase(void); + + static void TearDownTestCase(void); + + void SetUp(); + + void TearDown(); +}; + +void HksModifyKeyTest::SetUpTestCase(void) +{ +} + +void HksModifyKeyTest::TearDownTestCase(void) +{ +} + +void HksModifyKeyTest::SetUp() +{ + EXPECT_EQ(HksInitialize(), 0); +} + +void HksModifyKeyTest::TearDown() +{ +} + +const int DEFAULT_AES_CIPHER_PLAIN_SIZE = 1000; +const int AES_DEFAULT_GCM_NONCE_LENGTH = 12; +const int AES_DEFAULT_AAD_LEN = 4; +const char *g_storePath = "/storage/maindata/hks_client/key"; +const char *g_testName = "TestName"; + +const struct HksTestCipherParams g_testCipherParams[] = { + /* success: aes256-gcm-none */ + { 0, HKS_SUCCESS, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, /* genKey params */ + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0 + }, + { false, 0 }, + { + HKS_TEST_CIPHER_TYPE_AES, true, /* encrypt params */ + true, HKS_ALG_AES, + true, HKS_KEY_PURPOSE_ENCRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0, + true, AES_DEFAULT_GCM_NONCE_LENGTH, + true, AES_DEFAULT_AAD_LEN + }, + { + HKS_TEST_CIPHER_TYPE_AES, true, /* decrypt params */ + true, HKS_ALG_AES, + true, HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0, + true, AES_DEFAULT_GCM_NONCE_LENGTH, + true, AES_DEFAULT_AAD_LEN + }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE, true, DEFAULT_AES_CIPHER_PLAIN_SIZE }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE + 16, true, DEFAULT_AES_CIPHER_PLAIN_SIZE + 16 }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE, true, DEFAULT_AES_CIPHER_PLAIN_SIZE }, + { false, 0, false, 0 } + }, +}; + +static int32_t ConstructDataToBlob(struct HksBlob **inData, struct HksBlob **outData, + const struct HksTestBlobParams *inTextParams, const struct HksTestBlobParams *outTextParams) +{ + int32_t ret = TestConstuctBlob(inData, + inTextParams->blobExist, + inTextParams->blobSize, + inTextParams->blobDataExist, + inTextParams->blobDataSize); + HKS_TEST_ASSERT(ret == 0); + + ret = TestConstuctBlob(outData, + outTextParams->blobExist, + outTextParams->blobSize, + outTextParams->blobDataExist, + outTextParams->blobDataSize); + HKS_TEST_ASSERT(ret == 0); + return ret; +} + +static int32_t Encrypt(struct CipherEncryptStructure *encryptStruct) +{ + int32_t ret; + struct HksParamSet *encryptParamSet = NULL; + + uint32_t ivSize = encryptStruct->cipherParms->ivSize; + uint32_t nonceSize = encryptStruct->cipherParms->nonceSize; + uint32_t aadSize = encryptStruct->cipherParms->aadSize; + if (ivSize != 0) { + ret = TestConstuctBlob(encryptStruct->ivData, true, ivSize, true, ivSize); + HKS_TEST_ASSERT(ret == 0); + } + if (nonceSize != 0) { + ret = TestConstuctBlob(encryptStruct->nonceData, true, nonceSize, true, nonceSize); + HKS_TEST_ASSERT(ret == 0); + } + if (aadSize != 0) { + ret = TestConstuctBlob(encryptStruct->aadData, true, aadSize, true, aadSize); + HKS_TEST_ASSERT(ret == 0); + } + struct AesCipherParamSetStructure enParamStruct = { + &encryptParamSet, + encryptStruct->cipherParms->paramSetExist, + encryptStruct->cipherParms->setAlg, encryptStruct->cipherParms->alg, + encryptStruct->cipherParms->setPurpose, encryptStruct->cipherParms->purpose, + encryptStruct->cipherParms->setPadding, encryptStruct->cipherParms->padding, + encryptStruct->cipherParms->setBlockMode, encryptStruct->cipherParms->mode, + encryptStruct->cipherParms->setIv, *(encryptStruct->ivData), + encryptStruct->cipherParms->setNonce, *(encryptStruct->nonceData), + encryptStruct->cipherParms->setAad, *(encryptStruct->aadData), + encryptStruct->cipherParms->setIsKeyAlias, encryptStruct->cipherParms->isKeyAlias + }; + ret = TestConstructAesCipherParamSet(&enParamStruct); + HKS_TEST_ASSERT(ret == 0); + + ret = HksEncryptRun(encryptStruct->keyAlias, encryptParamSet, encryptStruct->plainData, encryptStruct->cipherData, + encryptStruct->performTimes); + HksFreeParamSet(&encryptParamSet); + return ret; +} + +static int32_t DecryptCipher(struct CipherDecryptStructure *decryptStruct) +{ + int32_t ret = TestConstuctBlob(decryptStruct->decryptedData, + decryptStruct->cipherParms->decryptedTextParams.blobExist, + decryptStruct->cipherParms->decryptedTextParams.blobSize, + decryptStruct->cipherParms->decryptedTextParams.blobDataExist, + decryptStruct->cipherParms->decryptedTextParams.blobDataSize); + HKS_TEST_ASSERT(ret == 0); + + struct HksParamSet *decryptParamSet = NULL; + struct AesCipherParamSetStructure deParamStruct = { + &decryptParamSet, + decryptStruct->cipherParms->decryptParamSetParams.paramSetExist, + decryptStruct->cipherParms->decryptParamSetParams.setAlg, + decryptStruct->cipherParms->decryptParamSetParams.alg, + decryptStruct->cipherParms->decryptParamSetParams.setPurpose, + decryptStruct->cipherParms->decryptParamSetParams.purpose, + decryptStruct->cipherParms->decryptParamSetParams.setPadding, + decryptStruct->cipherParms->decryptParamSetParams.padding, + decryptStruct->cipherParms->decryptParamSetParams.setBlockMode, + decryptStruct->cipherParms->decryptParamSetParams.mode, + decryptStruct->cipherParms->decryptParamSetParams.setIv, decryptStruct->ivData, + decryptStruct->cipherParms->decryptParamSetParams.setNonce, decryptStruct->nonceData, + decryptStruct->cipherParms->decryptParamSetParams.setAad, decryptStruct->aadData, + decryptStruct->cipherParms->decryptParamSetParams.setIsKeyAlias, + decryptStruct->cipherParms->decryptParamSetParams.isKeyAlias + }; + ret = TestConstructAesCipherParamSet(&deParamStruct); + HKS_TEST_ASSERT(ret == 0); + + ret = HksDecryptRun(decryptStruct->keyAlias, decryptParamSet, decryptStruct->cipherData, + *(decryptStruct->decryptedData), decryptStruct->performTimes); + HksFreeParamSet(&decryptParamSet); + return ret; +} + +int32_t GenerateKeyTwo(struct HksBlob *keyAlias, const struct HksTestBlobParams *keyAliasParams, + const struct HksTestGenKeyParamsParamSet *genKeyParamSetParams, + const struct HksTestGenKeyParamsParamSetOut *genKeyParamSetParamsOut) +{ + struct HksParamSet *paramSet = NULL; + struct GenerateKeyParamSetStructure paramStruct = { + ¶mSet, + genKeyParamSetParams->paramSetExist, + genKeyParamSetParams->setAlg, genKeyParamSetParams->alg, + genKeyParamSetParams->setKeySize, genKeyParamSetParams->keySize, + genKeyParamSetParams->setPurpose, genKeyParamSetParams->purpose, + genKeyParamSetParams->setDigest, genKeyParamSetParams->digest, + genKeyParamSetParams->setPadding, genKeyParamSetParams->padding, + genKeyParamSetParams->setBlockMode, genKeyParamSetParams->mode, + genKeyParamSetParams->setKeyStorageFlag, genKeyParamSetParams->keyStorageFlag + }; + int32_t ret = TestConstructGenerateKeyParamSet(¶mStruct); + HKS_TEST_ASSERT(ret == 0); + + struct HksParamSet *paramSetOut = NULL; + if (genKeyParamSetParamsOut != NULL) { + ret = TestConstructGenerateKeyParamSetOut(¶mSet, + genKeyParamSetParamsOut->paramSetExist, genKeyParamSetParamsOut->paramSetSize); + HKS_TEST_ASSERT(ret == 0); + } + + ret = HksGenerateKey(keyAlias, paramSet, paramSetOut); + HKS_TEST_ASSERT(ret == 0); + + HksFreeParamSet(¶mSet); + return ret; +} + +static int32_t ModifyKey(struct HksBlob *keyAlias) +{ + uint32_t sizeOne = HksTestFileSize(g_storePath, (char *)keyAlias->data); + uint8_t *bufOne = (uint8_t *)HksTestMalloc(sizeOne); + if (bufOne == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + uint32_t sizeRead = HksTestFileRead(g_storePath, (char *)keyAlias->data, 0, bufOne, sizeOne); + (void)memset_s(bufOne, sizeRead, 0, sizeRead); + + int32_t ret = HksTestFileWrite(g_storePath, (char *)keyAlias->data, 0, bufOne, sizeOne); + HksTestFree(bufOne); + + return ret; +} + + +int32_t BaseTestCipherProcess(struct HksBlob *keyAlias, uint32_t index) +{ + struct HksBlob *plainData = NULL; + struct HksBlob *cipherData = NULL; + int32_t ret = ConstructDataToBlob(&plainData, &cipherData, + &g_testCipherParams[index].plainTextParams, &g_testCipherParams[index].cipherTextParams); + HKS_TEST_ASSERT(ret == 0); + struct HksBlob *ivData = NULL; + struct HksBlob *nonceData = NULL; + struct HksBlob *aadData = NULL; + struct HksBlob *decryptedData = NULL; + /* 2. encrypt */ + do { + struct CipherEncryptStructure testEncryptStruct = { + keyAlias, &g_testCipherParams[index].encryptParamSetParams, + plainData, cipherData, &ivData, &nonceData, &aadData, 1 + }; + ret = Encrypt(&testEncryptStruct); + if (ret != g_testCipherParams[index].expectResult) { + break; + } + /* 3. decrypt */ + struct CipherDecryptStructure testDecryptStruct = { + keyAlias, &g_testCipherParams[index], cipherData, + &decryptedData, ivData, nonceData, aadData, 1 + }; + ret = DecryptCipher(&testDecryptStruct); + if (ret != g_testCipherParams[index].expectResult) { + break; + } + + if (ret == g_testCipherParams[index].expectResult) { + if (plainData->size != decryptedData->size) { + break; + }; + ret = memcmp(plainData->data, decryptedData->data, plainData->size); + } + } while (0); + TestFreeBlob(&plainData); + TestFreeBlob(&cipherData); + TestFreeBlob(&decryptedData); + TestFreeBlob(&ivData); + TestFreeBlob(&nonceData); + TestFreeBlob(&aadData); + return ret; +} + +/** + * @tc.name: HksModifyKeyTest.HksModifyKeyTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksModifyKeyTest, HksModifyKeyTest001, TestSize.Level1) +{ + uint32_t index = 0; + struct HksBlob keyAlias = { strlen(g_testName), (uint8_t *)g_testName }; + int32_t ret = GenerateKeyTwo(&keyAlias, &g_testCipherParams[index].keyAliasParams, + &g_testCipherParams[index].genKeyParamSetParams, &g_testCipherParams[index].genKeyParamSetParamsOut); + EXPECT_EQ(ret, 0); + + ret = BaseTestCipherProcess(&keyAlias, 0); + EXPECT_EQ(ret, 0); + + struct HksBlob *plainData = NULL; + struct HksBlob *cipherData = NULL; + ret = ConstructDataToBlob(&plainData, &cipherData, + &g_testCipherParams[index].plainTextParams, &g_testCipherParams[index].cipherTextParams); + EXPECT_EQ(ret, 0); + struct HksBlob *ivData = NULL; + struct HksBlob *nonceData = NULL; + struct HksBlob *aadData = NULL; + + /* 2. encrypt */ + struct CipherEncryptStructure testEncryptStruct = { + &keyAlias, &g_testCipherParams[index].encryptParamSetParams, + plainData, cipherData, &ivData, &nonceData, &aadData, 1 + }; + ret = Encrypt(&testEncryptStruct); + EXPECT_EQ(ret, 0); + ret = ModifyKey(&keyAlias); + EXPECT_EQ(ret, 0); + /* 3. decrypt */ + struct HksBlob *decryptedData = NULL; + struct CipherDecryptStructure testDecryptStruct = { + &keyAlias, &g_testCipherParams[index], cipherData, + &decryptedData, ivData, nonceData, aadData, 1 + }; + ret = DecryptCipher(&testDecryptStruct); + + HKS_TEST_ASSERT(ret != g_testCipherParams[index].expectResult); + TestFreeBlob(&plainData); + TestFreeBlob(&cipherData); + TestFreeBlob(&decryptedData); + TestFreeBlob(&ivData); + TestFreeBlob(&nonceData); + TestFreeBlob(&aadData); + EXPECT_NE(ret, 0); +} +#endif /* _CUT_AUTHENTICATE_ */ +} diff --git a/test/unittest/src/liteos_a_adapter/hks_others_test.cpp b/test/unittest/src/liteos_a_adapter/hks_others_test.cpp new file mode 100644 index 00000000..359c2168 --- /dev/null +++ b/test/unittest/src/liteos_a_adapter/hks_others_test.cpp @@ -0,0 +1,143 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include + +#include "hks_others_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_type.h" + +using namespace testing::ext; +namespace { +#ifndef _CUT_AUTHENTICATE_ +class HksOthersTest : public testing::Test { +public: + static void SetUpTestCase(void); + + static void TearDownTestCase(void); + + void SetUp(); + + void TearDown(); +}; + +void HksOthersTest::SetUpTestCase(void) +{ +} + +void HksOthersTest::TearDownTestCase(void) +{ +} + +void HksOthersTest::SetUp() +{ + EXPECT_EQ(HksInitialize(), 0); +} + +void HksOthersTest::TearDown() +{ +} + +/** + * @tc.name: HksOthersTest.HksOthersTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksOthersTest, HksOthersTest001, TestSize.Level1) +{ + int32_t ret = HksGetKeyParamSet(NULL, NULL, NULL); + ASSERT_TRUE(ret == HKS_ERROR_NULL_POINTER); +} + +/** + * @tc.name: HksOthersTest.HksOthersTest002 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksOthersTest, HksOthersTest002, TestSize.Level1) +{ + int32_t ret = HksGetKeyInfoList(NULL, NULL, NULL); + ASSERT_TRUE(ret == HKS_ERROR_NULL_POINTER); +} + +/** + * @tc.name: HksOthersTest.HksOthersTest003 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksOthersTest, HksOthersTest003, TestSize.Level1) +{ + int32_t ret = HksAttestKey(NULL, NULL, NULL); + ASSERT_TRUE(ret == HKS_ERROR_NOT_SUPPORTED); +} + +/** + * @tc.name: HksOthersTest.HksOthersTest004 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksOthersTest, HksOthersTest004, TestSize.Level1) +{ + int32_t ret = HksGetCertificateChain(NULL, NULL, NULL); + ASSERT_TRUE(ret == HKS_ERROR_NOT_SUPPORTED); +} + +/** + * @tc.name: HksOthersTest.HksOthersTest005 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksOthersTest, HksOthersTest005, TestSize.Level1) +{ + int32_t ret = HksWrapKey(NULL, NULL, NULL, NULL); + ASSERT_TRUE(ret == HKS_ERROR_NOT_SUPPORTED); +} + +/** + * @tc.name: HksOthersTest.HksOthersTest006 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksOthersTest, HksOthersTest006, TestSize.Level1) +{ + int32_t ret = HksUnwrapKey(NULL, NULL, NULL, NULL); + ASSERT_TRUE(ret == HKS_ERROR_NOT_SUPPORTED); +} + +/** + * @tc.name: HksOthersTest.HksOthersTest006 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksOthersTest, HksOthersTest007, TestSize.Level1) +{ + int32_t ret = HksGetSdkVersion(NULL); + ASSERT_TRUE(ret == HKS_ERROR_NULL_POINTER); +} + +/** + * @tc.name: HksOthersTest.HksOthersTest008 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksOthersTest, HksOthersTest008, TestSize.Level1) +{ + int32_t ret = HksInitialize(); + ASSERT_TRUE(ret == HKS_SUCCESS); +} +#endif /* _CUT_AUTHENTICATE_ */ +} \ No newline at end of file diff --git a/test/unittest/src/liteos_a_adapter/hks_safe_cipher_key_test.cpp b/test/unittest/src/liteos_a_adapter/hks_safe_cipher_key_test.cpp new file mode 100644 index 00000000..736afdca --- /dev/null +++ b/test/unittest/src/liteos_a_adapter/hks_safe_cipher_key_test.cpp @@ -0,0 +1,116 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include + +#include "hks_safe_cipher_key_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_curve25519.h" +#include "hks_test_file_operator.h" +#include "hks_test_mem.h" + +using namespace testing::ext; +namespace { +#ifndef _CUT_AUTHENTICATE_ +class HksSafeCipherKeyTest : public testing::Test { +public: + static void SetUpTestCase(void); + + static void TearDownTestCase(void); + + void SetUp(); + + void TearDown(); +}; + +void HksSafeCipherKeyTest::SetUpTestCase(void) +{ +} + +void HksSafeCipherKeyTest::TearDownTestCase(void) +{ +} + +void HksSafeCipherKeyTest::SetUp() +{ + EXPECT_EQ(HksInitialize(), 0); +} + +void HksSafeCipherKeyTest::TearDown() +{ +} + +const char *g_storePath = "/storage/maindata/hks_client/key"; +const char *g_testEd25519 = "test_ed25519"; + +static int32_t CompareTwoKey(struct HksBlob *keyAliasOne, struct HksBlob *keyAliasTwo) +{ + uint32_t sizeOne = HksTestFileSize(g_storePath, (char *)keyAliasOne->data); + uint8_t *bufOne = (uint8_t *)HksTestMalloc(sizeOne); + if (bufOne == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + uint32_t sizeRead = HksTestFileRead(g_storePath, (char *)keyAliasOne->data, 0, bufOne, sizeOne); + + uint32_t sizeTwo = HksTestFileSize(g_storePath, (char *)keyAliasTwo->data); + uint8_t *bufTwo = (uint8_t *)HksTestMalloc(sizeTwo); + if (bufTwo == NULL) { + HksTestFree(bufOne); + return HKS_ERROR_MALLOC_FAIL; + } + sizeRead = HksTestFileRead(g_storePath, (char *)keyAliasTwo->data, 0, bufTwo, sizeOne); + int32_t ret = memcmp(bufOne, bufTwo, sizeRead); + HksTestFree(bufOne); + HksTestFree(bufTwo); + return ret; +} + +/** + * @tc.name: HksSafeCipherKeyTest.HksSafeCipherKeyTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksSafeCipherKeyTest, HksSafeCipherKeyTest001, TestSize.Level1) +{ + struct HksBlob ed25519Alias = { strlen(g_testEd25519), (uint8_t *)g_testEd25519 }; + int32_t ret = TestGenerateEd25519Key(ed25519Alias); + uint8_t pubKey[32] = {0}; + uint32_t pubKeyLen = 32; + struct HksBlob pubKeyInfo = { pubKeyLen, pubKey }; + ret = HksExportPublicKey(&ed25519Alias, NULL, &pubKeyInfo); + EXPECT_EQ(ret, 0); + ret = HksDeleteKey(&ed25519Alias, NULL); + EXPECT_EQ(ret, 0); + + struct HksBlob newAliasOne = { strlen("test_ed25519_1"), (uint8_t *)"test_ed25519_1" }; + ret = TestImportEd25519(newAliasOne, &pubKeyInfo); + EXPECT_EQ(ret, 0); + + struct HksBlob newAliasTwo = { strlen("test_ed25519_2"), (uint8_t *)"test_ed25519_2" }; + ret = TestImportEd25519(newAliasTwo, &pubKeyInfo); + EXPECT_EQ(ret, 0); + + ret = CompareTwoKey(&newAliasOne, &newAliasTwo); + EXPECT_NE(ret, 0); + + ret = HksDeleteKey(&newAliasOne, NULL); + EXPECT_EQ(ret, 0); + ret = HksDeleteKey(&newAliasTwo, NULL); + EXPECT_EQ(ret, 0); +} +#endif /* _CUT_AUTHENTICATE_ */ +} \ No newline at end of file diff --git a/test/unittest/src/liteos_a_adapter/hks_safe_compare_key_test.cpp b/test/unittest/src/liteos_a_adapter/hks_safe_compare_key_test.cpp new file mode 100644 index 00000000..b0309605 --- /dev/null +++ b/test/unittest/src/liteos_a_adapter/hks_safe_compare_key_test.cpp @@ -0,0 +1,164 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include + +#include "hks_safe_compare_key_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_file_operator.h" +#include "hks_test_log.h" +#include "hks_test_mem.h" + +using namespace testing::ext; +namespace { +#ifndef _CUT_AUTHENTICATE_ +class HksSafeCompareKeyTest : public testing::Test { +public: + static void SetUpTestCase(void); + + static void TearDownTestCase(void); + + void SetUp(); + + void TearDown(); +}; + +void HksSafeCompareKeyTest::SetUpTestCase(void) +{ +} + +void HksSafeCompareKeyTest::TearDownTestCase(void) +{ +} + +void HksSafeCompareKeyTest::SetUp() +{ + EXPECT_EQ(HksInitialize(), 0); +} + +void HksSafeCompareKeyTest::TearDown() +{ +} + +const char *g_storePath = "/storage/maindata/hks_client/key/"; +const char *g_testOne = "TestOne"; +const char *g_testTwo = "TestTwo"; + +const struct HksTestGenKeyParams g_testGenKeyParams[] = { + /* x25519: tee sign/verify */ + { 0, HKS_SUCCESS, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, + true, HKS_ALG_X25519, + true, HKS_CURVE25519_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_SIGN | HKS_KEY_PURPOSE_VERIFY, + false, 0, + false, 0, + false, 0, + false, 0 + }, + { false, 0 }, + }, +}; + +static int32_t SafeTestGenerateKey(struct HksBlob *keyAlias) +{ + uint32_t index = 0; + uint32_t performTimes = 1; + + struct HksParamSet *paramSet = NULL; + struct GenerateKeyParamSetStructure paramStruct = { + ¶mSet, + g_testGenKeyParams[index].paramSetParams.paramSetExist, + g_testGenKeyParams[index].paramSetParams.setAlg, g_testGenKeyParams[index].paramSetParams.alg, + g_testGenKeyParams[index].paramSetParams.setKeySize, g_testGenKeyParams[index].paramSetParams.keySize, + g_testGenKeyParams[index].paramSetParams.setPurpose, g_testGenKeyParams[index].paramSetParams.purpose, + g_testGenKeyParams[index].paramSetParams.setDigest, g_testGenKeyParams[index].paramSetParams.digest, + g_testGenKeyParams[index].paramSetParams.setPadding, g_testGenKeyParams[index].paramSetParams.padding, + g_testGenKeyParams[index].paramSetParams.setBlockMode, g_testGenKeyParams[index].paramSetParams.mode, + g_testGenKeyParams[index].paramSetParams.setKeyStorageFlag, + g_testGenKeyParams[index].paramSetParams.keyStorageFlag + }; + int32_t ret = TestConstructGenerateKeyParamSet(¶mStruct); + HKS_TEST_ASSERT(ret == 0); + + struct HksParamSet *paramSetOut = NULL; + ret = TestConstructGenerateKeyParamSetOut(¶mSetOut, + g_testGenKeyParams[index].paramSetParamsOut.paramSetExist, + g_testGenKeyParams[index].paramSetParamsOut.paramSetSize); + HKS_TEST_ASSERT(ret == 0); + + ret = HksGenerateKeyRun(keyAlias, paramSet, paramSetOut, performTimes); + if (ret != g_testGenKeyParams[index].expectResult) { + HKS_TEST_LOG_I("failed, ret[%u] = %d", g_testGenKeyParams[index].testId, ret); + } + EXPECT_EQ(ret, g_testGenKeyParams[index].expectResult); + + if (ret == g_testGenKeyParams[index].expectResult) { + ret = 0; + } else { + ret = 1; + } + HksFreeParamSet(¶mSet); + HksFreeParamSet(¶mSetOut); + return ret; +} + +static int32_t CompareKeyData(struct HksBlob *keyAliasOne, struct HksBlob *keyAliasTwo) +{ + uint32_t sizeOne = HksTestFileSize(g_storePath, (char *)keyAliasOne->data); + uint8_t *bufOne = (uint8_t *)HksTestMalloc(sizeOne); + if (bufOne == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + uint32_t sizeRead = HksTestFileRead(g_storePath, (char *)keyAliasOne->data, 0, bufOne, sizeOne); + + uint32_t sizeTwo = HksTestFileSize(g_storePath, (char *)keyAliasTwo->data); + uint8_t *bufTwo = (uint8_t *)HksTestMalloc(sizeTwo); + if (bufTwo == NULL) { + HksTestFree(bufOne); + return HKS_ERROR_MALLOC_FAIL; + } + sizeRead = HksTestFileRead(g_storePath, (char *)keyAliasTwo->data, 0, bufTwo, sizeOne); + int32_t ret = memcmp(bufOne, bufTwo, sizeOne); + HksTestFree(bufOne); + HksTestFree(bufTwo); + return ret; +} + +/** + * @tc.name: HksSafeCompareKeyTest.HksSafeCompareKeyTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +HWTEST_F(HksSafeCompareKeyTest, HksSafeCompareKeyTest001, TestSize.Level1) +{ + struct HksBlob keyAliasOne = { strlen(g_testOne), (uint8_t *)g_testOne }; + int32_t ret = SafeTestGenerateKey(&keyAliasOne); + EXPECT_EQ(ret, 0); + + struct HksBlob keyAliasTwo = { strlen(g_testTwo), (uint8_t *)g_testTwo }; + ret = SafeTestGenerateKey(&keyAliasTwo); + EXPECT_EQ(ret, 0); + + ret = CompareKeyData(&keyAliasOne, &keyAliasTwo); + EXPECT_NE(ret, 0); +} +#endif /* _CUT_AUTHENTICATE_ */ +} \ No newline at end of file diff --git a/test/unittest/src/liteos_m_adapter/BUILD.gn b/test/unittest/src/liteos_m_adapter/BUILD.gn new file mode 100644 index 00000000..c653eb33 --- /dev/null +++ b/test/unittest/src/liteos_m_adapter/BUILD.gn @@ -0,0 +1,52 @@ +# +# Copyright (c) 2021 Huawei Device Co., Ltd. +# 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. +# + +import("//base/security/huks/build/config.gni") +import("//test/xts/tools/lite/build/suite_lite.gni") + +hctest_suite("huks_new_test") { + suite_name = "huks_new_test" + sources = [ + "hks_aes_test.c", + "hks_agreement_test.c", + "hks_bn_exp_mod_test.c", + "hks_cipher_test.c", + "hks_curve25519_test.c", + "hks_delete_test.c", + "hks_derive_test.c", + "hks_exist_test.c", + "hks_generate_key_test.c", + "hks_generate_random_test.c", + "hks_hash_test.c", + "hks_mac_test.c", + "hks_modify_key_test.c", + "hks_others_test.c", + "hks_safe_cipher_key_test.c", + "hks_safe_compare_key_test.c", + ] + include_dirs = [ + "//base/security/huks/interfaces/innerkits/huks_standard/main/include", + "../common/include", + ] + + deps = [ + #"//base/security/huks/huawei_property/source:huks_new", + "//base/security/huks/test/unittest/src/common:huks_new_test_common", + ] + + if (disable_authenticate == true) { + cflags = [ "-D_CUT_AUTHENTICATE_" ] + } +} diff --git a/test/unittest/src/liteos_m_adapter/Test.json b/test/unittest/src/liteos_m_adapter/Test.json new file mode 100644 index 00000000..e4fe1ba3 --- /dev/null +++ b/test/unittest/src/liteos_m_adapter/Test.json @@ -0,0 +1,26 @@ +{ + "description": "Config for hcpptest demo test cases", + "environment": [ + { + "type": "device", + "label": "ipcamera" + } + ], + "kits": [ + { + "type": "MountKit", + "server": "NfsServer", + "mount": [ + { + "source": "testcases/security", + "target": "/test_root/security" + } + ] + } + ], + "driver": { + "type": "CppTestLite", + "execute": "/test_root/security/huks_new_test.bin" + } +} + diff --git a/test/unittest/src/liteos_m_adapter/hks_aes_test.c b/test/unittest/src/liteos_m_adapter/hks_aes_test.c new file mode 100644 index 00000000..f5dc9de6 --- /dev/null +++ b/test/unittest/src/liteos_m_adapter/hks_aes_test.c @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include "hctest.h" +#include +#include "hks_api.h" +#include "hks_param.h" +#include "securec.h" + +/* + * @tc.register: register a test suit named "CalcMultiTest" + * @param: test subsystem name + * @param: c_example module name + * @param: CalcMultiTest test suit name + */ +LITE_TEST_SUIT(husk, huks_lite, HksAesTest); + +/** + * @tc.setup: define a setup for test suit, format:"CalcMultiTest + SetUp" + * @return: true——setup success + */ +static BOOL HksAesTestSetUp() +{ + LiteTestPrint("setup\n"); + hi_watchdog_disable(); + TEST_ASSERT_TRUE(HksInitialize() == 0); + return TRUE; +} + +/** + * @tc.teardown: define a setup for test suit, format:"CalcMultiTest + TearDown" + * @return: true——teardown success + */ +static BOOL HksAesTestTearDown() +{ + LiteTestPrint("tearDown\n"); + hi_watchdog_enable(); + return TRUE; +} + +#ifndef _CUT_AUTHENTICATE_ +/** + * @tc.name: HksCipherTest.HksCipherTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksAesTest, HksAesTest001, Level1) +{ + TEST_ASSERT_TRUE(TestAes256ByAgree() == 0); +} + +/** + * @tc.name: HksCipherTest.HksCipherTest002 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksAesTest, HksAesTest002, Level1) +{ + TEST_ASSERT_TRUE(TestAes256ByAgree1() == 0); +} + +/** + * @tc.name: HksCipherTest.HksCipherTest003 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksAesTest, HksAesTest003, Level1) +{ + TEST_ASSERT_TRUE(TestAes256ByAgree2() == 0); +} +#endif /* _CUT_AUTHENTICATE_ */ + +/** + * @tc.name: HksCipherTest.HksCipherTest004 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksAesTest, HksAesTest004, Level1) +{ + TEST_ASSERT_EQUAL(TestAes256ByLocal(), 0); +} + +RUN_TEST_SUITE(HksAesTest); diff --git a/test/unittest/src/liteos_m_adapter/hks_agreement_test.c b/test/unittest/src/liteos_m_adapter/hks_agreement_test.c new file mode 100644 index 00000000..dedf596f --- /dev/null +++ b/test/unittest/src/liteos_m_adapter/hks_agreement_test.c @@ -0,0 +1,216 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include "hctest.h" +#include "hi_watchdog.h" +#include "hks_agreement_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" +#include "hks_type.h" + +#ifndef _CUT_AUTHENTICATE_ + +/* + * @tc.register: register a test suit named "CalcMultiTest" + * @param: test subsystem name + * @param: c_example module name + * @param: CalcMultiTest test suit name + */ +LITE_TEST_SUIT(husk, huks_lite, HksAgreementTest); + +/** + * @tc.setup: define a setup for test suit, format:"CalcMultiTest + SetUp" + * @return: true——setup success + */ +static BOOL HksAgreementTestSetUp() +{ + LiteTestPrint("setup\n"); + + hi_watchdog_disable(); + TEST_ASSERT_TRUE(HksInitialize() == 0); + return TRUE; +} + +/** + * @tc.teardown: define a setup for test suit, format:"CalcMultiTest + TearDown" + * @return: true——teardown success + */ +static BOOL HksAgreementTestTearDown() +{ + LiteTestPrint("tearDown\n"); + + hi_watchdog_enable(); + return TRUE; +} + +#define TMP_SIZE 512 +#define X25519_KEY_SIZE 32 +static const struct HksTestAgreeParams g_testAgreeParams[] = { + /* ree x25519 success */ + { 0, HKS_SUCCESS, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { true, true, HKS_ALG_X25519, true, HKS_CURVE25519_KEY_SIZE_256, true, + HKS_KEY_PURPOSE_SIGN | HKS_KEY_PURPOSE_VERIFY, true, HKS_DIGEST_SHA256, + false, 0, false, 0, true, HKS_STORAGE_TEMP }, + { 0 }, + { true, true, HKS_ALG_X25519, true, HKS_CURVE25519_KEY_SIZE_256, true, false }, + { true, TMP_SIZE, true, TMP_SIZE }, + { true, X25519_KEY_SIZE, true, X25519_KEY_SIZE }, + { true, X25519_KEY_SIZE, true, X25519_KEY_SIZE }, + { true, X25519_KEY_SIZE, true, X25519_KEY_SIZE } + }, +}; + +static int32_t AgreeKey(const struct HksTestAgreeParamSet *agreeParamSetParams, struct HksBlob *privateKey, + struct HksBlob *peerPublicKey, struct HksBlob *agreedKey) +{ + struct HksParamSet *agreeParamSet = NULL; + struct TestAgreeParamSetStructure paramStruct = { + &agreeParamSet, + agreeParamSetParams->paramSetExist, + agreeParamSetParams->setAlg, agreeParamSetParams->alg, + agreeParamSetParams->setKeySize, agreeParamSetParams->keySize, + agreeParamSetParams->setIsKeyAlias, agreeParamSetParams->isKeyAlias + }; + int32_t ret = TestConstructAgreeParamSet(¶mStruct); + HKS_TEST_ASSERT(ret == 0); + + ret = HksAgreeKeyRun(agreeParamSet, privateKey, peerPublicKey, agreedKey, 1); + HksFreeParamSet(&agreeParamSet); + return ret; +} + +/** + * @tc.name: HksDeleteTest.HksDeleteTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksAgreementTest, HksAgreementTest001, Level1) +{ + /* 1. generate key */ + struct HksBlob *privateKey = NULL; + struct HksBlob *peerPubKeyAlias = NULL; + struct HksBlob *peerPublicKey = NULL; + int32_t ret; + + if (g_testAgreeParams[0].genKeyParamSetParams.setKeyStorageFlag && + (g_testAgreeParams[0].genKeyParamSetParams.keyStorageFlag == HKS_STORAGE_TEMP)) { + ret = GenerateLocalX25519Key(&privateKey, NULL, &g_testAgreeParams[0].localPrivateKeyParams, NULL); + HKS_TEST_ASSERT(ret == 0); + ret = GenerateLocalX25519Key(NULL, &peerPublicKey, NULL, &g_testAgreeParams[0].localPublicKeyParams); + HKS_TEST_ASSERT(ret == 0); + } + /* 2. agreeKey */ + struct HksBlob *agreeKey = NULL; + ret = TestConstuctBlob(&agreeKey, + g_testAgreeParams[0].agreedKeyParams.blobExist, + g_testAgreeParams[0].agreedKeyParams.blobSize, + g_testAgreeParams[0].agreedKeyParams.blobDataExist, + g_testAgreeParams[0].agreedKeyParams.blobDataSize); + HKS_TEST_ASSERT(ret == 0); + + ret = AgreeKey(&g_testAgreeParams[0].agreeParamSetParams, privateKey, peerPublicKey, agreeKey); + HKS_TEST_ASSERT(ret == g_testAgreeParams[0].expectResult); + + /* 3. delete key */ + if (!(g_testAgreeParams[0].genKeyParamSetParams.setKeyStorageFlag && + (g_testAgreeParams[0].genKeyParamSetParams.keyStorageFlag == HKS_STORAGE_TEMP)) && + ((g_testAgreeParams[0].keyAlias1Params.blobExist) && + (g_testAgreeParams[0].keyAlias2Params.blobExist))) { + ret = HksDeleteKey(privateKey, NULL); + HKS_TEST_ASSERT(ret == 0); + ret = HksDeleteKey(peerPubKeyAlias, NULL); + HKS_TEST_ASSERT(ret == 0); + } + TestFreeBlob(&privateKey); + TestFreeBlob(&peerPubKeyAlias); + TestFreeBlob(&peerPublicKey); + TestFreeBlob(&agreeKey); + TEST_ASSERT_TRUE(ret == 0); +} + + +/** + * @tc.name: HksDeleteTest.HksDeleteTest002 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksAgreementTest, HksAgreementTest002, Level1) +{ + /* 1. generate key */ + struct HksBlob *privateKey = NULL; + struct HksBlob *peerPubKeyAlias = NULL; + struct HksBlob *peerPublicKey = NULL; + struct HksBlob *privateKey1 = NULL; + struct HksBlob *peerPubKeyAlias1 = NULL; + struct HksBlob *peerPublicKey1 = NULL; + int32_t ret; + + if (g_testAgreeParams[0].genKeyParamSetParams.setKeyStorageFlag && + (g_testAgreeParams[0].genKeyParamSetParams.keyStorageFlag == HKS_STORAGE_TEMP)) { + ret = GenerateLocalX25519Key(&privateKey, &peerPublicKey, &g_testAgreeParams[0].localPrivateKeyParams, \ + &g_testAgreeParams[0].localPublicKeyParams); + TEST_ASSERT_TRUE(ret == 0); + ret = GenerateLocalX25519Key(&privateKey1, &peerPublicKey1, &g_testAgreeParams[0].localPrivateKeyParams, \ + &g_testAgreeParams[0].localPublicKeyParams); + TEST_ASSERT_TRUE(ret == 0); + } + /* 2. agreeKey */ + struct HksBlob *agreeKey = NULL; + ret = TestConstuctBlob(&agreeKey, g_testAgreeParams[0].agreedKeyParams.blobExist, \ + g_testAgreeParams[0].agreedKeyParams.blobSize, g_testAgreeParams[0].agreedKeyParams.blobDataExist, \ + g_testAgreeParams[0].agreedKeyParams.blobDataSize); + TEST_ASSERT_TRUE(ret == 0); + + ret = AgreeKey(&g_testAgreeParams[0].agreeParamSetParams, privateKey, peerPublicKey1, agreeKey); + TEST_ASSERT_TRUE(ret == g_testAgreeParams[0].expectResult); + + struct HksBlob *agreeKey1 = NULL; + ret = TestConstuctBlob(&agreeKey1, g_testAgreeParams[0].agreedKeyParams.blobExist, \ + g_testAgreeParams[0].agreedKeyParams.blobSize, g_testAgreeParams[0].agreedKeyParams.blobDataExist, \ + g_testAgreeParams[0].agreedKeyParams.blobDataSize); + TEST_ASSERT_TRUE(ret == 0); + + ret = AgreeKey(&g_testAgreeParams[0].agreeParamSetParams, privateKey1, peerPublicKey, agreeKey1); + TEST_ASSERT_TRUE(ret == g_testAgreeParams[0].expectResult); + TEST_ASSERT_EQUAL(agreeKey->size, agreeKey1->size); + TEST_ASSERT_TRUE(memcmp(agreeKey->data, agreeKey1->data, agreeKey->size) == 0); + + /* 3. delete key */ + if (!(g_testAgreeParams[0].genKeyParamSetParams.setKeyStorageFlag && + (g_testAgreeParams[0].genKeyParamSetParams.keyStorageFlag == HKS_STORAGE_TEMP)) && + ((g_testAgreeParams[0].keyAlias1Params.blobExist) && (g_testAgreeParams[0].keyAlias2Params.blobExist))) { + TEST_ASSERT_TRUE(HksDeleteKey(privateKey, NULL) == 0); + TEST_ASSERT_TRUE(HksDeleteKey(peerPubKeyAlias, NULL) == 0); + TEST_ASSERT_TRUE(HksDeleteKey(privateKey1, NULL) == 0); + TEST_ASSERT_TRUE(HksDeleteKey(peerPubKeyAlias1, NULL) == 0); + } + TestFreeBlob(&privateKey); + TestFreeBlob(&peerPubKeyAlias); + TestFreeBlob(&peerPublicKey); + TestFreeBlob(&agreeKey); + TestFreeBlob(&privateKey1); + TestFreeBlob(&peerPubKeyAlias1); + TestFreeBlob(&peerPublicKey1); + TestFreeBlob(&agreeKey1); +} + +RUN_TEST_SUITE(HksAgreementTest); +#endif /* _CUT_AUTHENTICATE_ */ + diff --git a/test/unittest/src/liteos_m_adapter/hks_bn_exp_mod_test.c b/test/unittest/src/liteos_m_adapter/hks_bn_exp_mod_test.c new file mode 100644 index 00000000..ecec3c59 --- /dev/null +++ b/test/unittest/src/liteos_m_adapter/hks_bn_exp_mod_test.c @@ -0,0 +1,147 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include "hctest.h" +#include "hi_watchdog.h" +#include "hks_bn_exp_mod_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" +#include "hks_type.h" + +/* + * @tc.register: register a test suit named "CalcMultiTest" + * @param: test subsystem name + * @param: c_example module name + * @param: CalcMultiTest test suit name + */ +LITE_TEST_SUIT(husk, huks_lite, HksBnExpModTest); + +/** + * @tc.setup: define a setup for test suit, format:"CalcMultiTest + SetUp" + * @return: true——setup success + */ +static BOOL HksBnExpModTestSetUp() +{ + LiteTestPrint("setup\n"); + hi_watchdog_disable(); + TEST_ASSERT_TRUE(HksInitialize() == 0); + return TRUE; +} + +/** + * @tc.teardown: define a setup for test suit, format:"CalcMultiTest + TearDown" + * @return: true——teardown success + */ +static BOOL HksBnExpModTestTearDown() +{ + LiteTestPrint("tearDown\n"); + hi_watchdog_enable(); + return TRUE; +} + + +#define DEFAULT_X_SIZE 256 +#define DEFAULT_A_SIZE 256 +#define DEFAULT_E_SIZE 256 +#define DEFAULT_N_SIZE 256 +#define HKS_TEST_2 2 +#define HKS_TEST_8 8 + +static const struct HksTestBnExpModParams g_testBnExpModParams[] = { + /* normal case */ + { 0, HKS_SUCCESS, false, + { true, DEFAULT_X_SIZE, true, DEFAULT_X_SIZE }, + { true, DEFAULT_A_SIZE, true, DEFAULT_A_SIZE }, + { true, DEFAULT_E_SIZE, true, DEFAULT_E_SIZE }, + { true, DEFAULT_N_SIZE, true, DEFAULT_N_SIZE } + }, +}; + +static int32_t TestValue() +{ + HKS_TEST_LOG_I("test value"); + uint8_t bufX[HKS_TEST_8] = { 0, 0, 0, 0, 0, 0, 0, 0x40 }; + uint8_t bufA[HKS_TEST_8] = { 1, 2, 3, 4, 5, 6, 7, 8 }; + uint8_t bufE[HKS_TEST_2] = { 0, 2 }; + uint8_t bufN[HKS_TEST_8] = { 0, 1, 2, 3, 4, 5, 6, 7 }; + uint8_t tmpBufX[HKS_TEST_8] = {0}; + struct HksBlob tmpX = { HKS_TEST_8, tmpBufX }; + struct HksBlob tmpA = { HKS_TEST_8, bufA }; + struct HksBlob tmpE = { HKS_TEST_2, bufE }; + struct HksBlob tmpN = { HKS_TEST_8, bufN }; + int32_t ret = HksBnExpModRun(&tmpX, &tmpA, &tmpE, &tmpN, 1); + for (int i = 0; i < HKS_TEST_8; ++i) { + HKS_TEST_LOG_I("%x, %x", tmpBufX[i], bufX[i]); + HKS_TEST_ASSERT(tmpBufX[i] == bufX[i]); + } + return ret; +} + +/** + * @tc.name: HksBnExpModTest.HksBnExpModTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksBnExpModTest, HksBnExpModTest001, Level1) +{ + int32_t ret; + if (g_testBnExpModParams[0].isTestValue) { + ret = TestValue(); + TEST_ASSERT_TRUE(ret == 0); + } else { + struct HksBlob *x = NULL; + struct HksBlob *a = NULL; + struct HksBlob *e = NULL; + struct HksBlob *n = NULL; + ret = TestConstuctBlob(&x, g_testBnExpModParams[0].xParams.blobExist, + g_testBnExpModParams[0].xParams.blobSize, g_testBnExpModParams[0].xParams.blobDataExist, + g_testBnExpModParams[0].xParams.blobDataSize); + TEST_ASSERT_TRUE(ret == 0); + + ret = TestConstructBlobOut(&a, g_testBnExpModParams[0].aParams.blobExist, + g_testBnExpModParams[0].aParams.blobSize, g_testBnExpModParams[0].aParams.blobDataExist, + g_testBnExpModParams[0].aParams.blobDataSize); + TEST_ASSERT_TRUE(ret == 0); + + ret = TestConstuctBlob(&e, g_testBnExpModParams[0].eParams.blobExist, + g_testBnExpModParams[0].eParams.blobSize, g_testBnExpModParams[0].eParams.blobDataExist, + g_testBnExpModParams[0].eParams.blobDataSize); + TEST_ASSERT_TRUE(ret == 0); + + ret = TestConstuctBlob(&n, g_testBnExpModParams[0].nParams.blobExist, + g_testBnExpModParams[0].nParams.blobSize, g_testBnExpModParams[0].nParams.blobDataExist, + g_testBnExpModParams[0].nParams.blobDataSize); + TEST_ASSERT_TRUE(ret == 0); + if ((n != NULL) && (n->data != NULL) && (n->size != 0)) { + n->data[n->size - 1] = n->data[n->size - 1] | 0x00000001; /* make sure n is odd */ + } + + ret = HksBnExpModRun(x, a, e, n, 1); + + TEST_ASSERT_TRUE(ret == g_testBnExpModParams[0].expectResult); + + TestFreeBlob(&x); + TestFreeBlob(&a); + TestFreeBlob(&e); + TestFreeBlob(&n); + TEST_ASSERT_TRUE(ret == 0); + } +} + +RUN_TEST_SUITE(HksBnExpModTest); diff --git a/test/unittest/src/liteos_m_adapter/hks_cipher_test.c b/test/unittest/src/liteos_m_adapter/hks_cipher_test.c new file mode 100644 index 00000000..734b95fb --- /dev/null +++ b/test/unittest/src/liteos_m_adapter/hks_cipher_test.c @@ -0,0 +1,131 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include "hks_cipher_test.h" + +#include "hctest.h" +#include "hi_watchdog.h" +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_cipher.h" +#include "securec.h" + +#define TEST_INDEX_0 0 +#define TEST_INDEX_1 1 +#define TEST_INDEX_2 2 +#define TEST_INDEX_3 3 +#define TEST_INDEX_4 4 + +/* + * @tc.register: register a test suit named "CalcMultiTest" + * @param: test subsystem name + * @param: c_example module name + * @param: CalcMultiTest test suit name + */ +LITE_TEST_SUIT(husk, huks_lite, HksCipherTest); + +/** + * @tc.setup: define a setup for test suit, format:"CalcMultiTest + SetUp" + * @return: true——setup success + */ +static BOOL HksCipherTestSetUp() +{ + LiteTestPrint("setup\n"); + hi_watchdog_disable(); + TEST_ASSERT_TRUE(HksInitialize() == 0); + return TRUE; +} + +/** + * @tc.teardown: define a setup for test suit, format:"CalcMultiTest + TearDown" + * @return: true——teardown success + */ +static BOOL HksCipherTestTearDown() +{ + LiteTestPrint("tearDown\n"); + hi_watchdog_enable(); + return TRUE; +} + + +/** + * @tc.name: HksCipherTest.HksCipherTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksCipherTest, HksCipherTest001, Level1) +{ + TEST_ASSERT_TRUE(BaseTestCipher(1, TEST_INDEX_0, 1) == 0); +} + +#ifndef _CUT_AUTHENTICATE_ + +LITE_TEST_CASE(HksCipherTest, HksCipherTest002, Level1) +{ + TEST_ASSERT_TRUE(BaseTestCipher(1, TEST_INDEX_1, 1) == 0); +} + +LITE_TEST_CASE(HksCipherTest, HksCipherTest003, Level1) +{ + TEST_ASSERT_TRUE(BaseTestEncrypt(1, TEST_INDEX_0, 1) == 0); +} + +LITE_TEST_CASE(HksCipherTest, HksCipherTest004, Level1) +{ + TEST_ASSERT_TRUE(BaseTestEncrypt(1, TEST_INDEX_1, 1) == 0); +} + +LITE_TEST_CASE(HksCipherTest, HksCipherTest005, Level1) +{ + TEST_ASSERT_TRUE(BaseTestEncrypt(1, TEST_INDEX_2, 1) == 0); +} + +LITE_TEST_CASE(HksCipherTest, HksCipherTest006, Level1) +{ + TEST_ASSERT_TRUE(BaseTestEncrypt(1, TEST_INDEX_3, 1) == 0); +} + +LITE_TEST_CASE(HksCipherTest, HksCipherTest007, Level1) +{ + TEST_ASSERT_TRUE(BaseTestEncrypt(1, TEST_INDEX_4, 1) == 0); +} + +LITE_TEST_CASE(HksCipherTest, HksCipherTest008, Level1) +{ + TEST_ASSERT_TRUE(BaseTestDecrypt(1, TEST_INDEX_0, 1) == 0); +} + +LITE_TEST_CASE(HksCipherTest, HksCipherTest009, Level1) +{ + TEST_ASSERT_TRUE(BaseTestDecrypt(1, TEST_INDEX_1, 1) == 0); +} + +LITE_TEST_CASE(HksCipherTest, HksCipherTest010, Level1) +{ + TEST_ASSERT_TRUE(BaseTestDecrypt(1, TEST_INDEX_2, 1) == 0); +} + +LITE_TEST_CASE(HksCipherTest, HksCipherTest011, Level1) +{ + TEST_ASSERT_TRUE(BaseTestDecrypt(1, TEST_INDEX_3, 1) == 0); +} + +LITE_TEST_CASE(HksCipherTest, HksCipherTest012, Level1) +{ + TEST_ASSERT_TRUE(BaseTestDecrypt(1, TEST_INDEX_4, 1) == 0); +} +#endif /* _CUT_AUTHENTICATE_ */ + +RUN_TEST_SUITE(HksCipherTest); diff --git a/test/unittest/src/liteos_m_adapter/hks_curve25519_test.c b/test/unittest/src/liteos_m_adapter/hks_curve25519_test.c new file mode 100644 index 00000000..b4e18dd2 --- /dev/null +++ b/test/unittest/src/liteos_m_adapter/hks_curve25519_test.c @@ -0,0 +1,134 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef _CUT_AUTHENTICATE_ + +#include "hks_curve25519_test.h" + +#include "cmsis_os2.h" +#include "hctest.h" +#include "hi_watchdog.h" +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_curve25519.h" +#include "los_config.h" +#include "ohos_types.h" +#include "securec.h" + +/* + * @tc.register: register a test suit named "CalcMultiTest" + * @param: test subsystem name + * @param: c_example module name + * @param: CalcMultiTest test suit name + */ +LITE_TEST_SUIT(husk, huks_lite, HksCurve25519Test); + +/** + * @tc.setup: define a setup for test suit, format:"CalcMultiTest + SetUp" + * @return: true——setup success + */ +static BOOL HksCurve25519TestSetUp() +{ + LiteTestPrint("setup\n"); + hi_watchdog_disable(); + TEST_ASSERT_TRUE(HksInitialize() == 0); + return TRUE; +} + +/** + * @tc.teardown: define a setup for test suit, format:"CalcMultiTest + TearDown" + * @return: true——teardown success + */ +static BOOL HksCurve25519TestTearDown() +{ + LiteTestPrint("tearDown\n"); + hi_watchdog_enable(); + return TRUE; +} + + +/** + * @tc.name: HksCurve25519Test.HksCurve25519Test001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksCurve25519Test, HksCurve25519Test001, Level1) +{ + LiteTestPrint("HksCurve25519Test001 Begin!\n"); + TEST_ASSERT_TRUE(TestCurve25519All() == 0); + LiteTestPrint("HksCurve25519Test001 End!\n"); +} + +#define TEST_TASK_STACK_SIZE 0x2000 +#define WAIT_TO_TEST_DONE 4 + +static osPriority_t g_setPriority; + +static void LocalHksCurve25519Test002(void const *argument) +{ + LiteTestPrint("HksCurve25519Test002 Begin!\n"); + TEST_ASSERT_TRUE(TestEd25519SignTeeVerifyLocal() == 0); + LiteTestPrint("HksCurve25519Test002 End!\n"); + + osThreadExit(); +} + +/** + * @tc.name: HksCurve25519Test.HksCurve25519Test002 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksCurve25519Test, HksCurve25519Test002, Level1) +{ + osThreadId_t id; + osThreadAttr_t attr; + g_setPriority = osPriorityAboveNormal6; + attr.name = "test"; + attr.attr_bits = 0U; + attr.cb_mem = NULL; + attr.cb_size = 0U; + attr.stack_mem = NULL; + attr.stack_size = TEST_TASK_STACK_SIZE; + attr.priority = g_setPriority; + id = osThreadNew((osThreadFunc_t)LocalHksCurve25519Test002, NULL, &attr); + + sleep(WAIT_TO_TEST_DONE); + + LiteTestPrint("HksCurve25519Test002 End2!\n"); +} + +/** + * @tc.name: HksCurve25519Test.HksCurve25519Test003 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksCurve25519Test, HksCurve25519Test003, Level1) +{ + TEST_ASSERT_TRUE(TestCurve25519SignWrong() == 0); +} + +/** + * @tc.name: HksCurve25519Test.HksCurve25519Test004 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksCurve25519Test, HksCurve25519Test004, Level1) +{ + TEST_ASSERT_TRUE(TestCurve25519verifyWrong() == 0); +} + +RUN_TEST_SUITE(HksCurve25519Test); +#endif /* _CUT_AUTHENTICATE_ */ + diff --git a/test/unittest/src/liteos_m_adapter/hks_delete_test.c b/test/unittest/src/liteos_m_adapter/hks_delete_test.c new file mode 100644 index 00000000..921af6d9 --- /dev/null +++ b/test/unittest/src/liteos_m_adapter/hks_delete_test.c @@ -0,0 +1,95 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef _CUT_AUTHENTICATE_ + +#include "hctest.h" +#include "hi_watchdog.h" +#include "hks_delete_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" +#include "hks_type.h" + +/* + * @tc.register: register a test suit named "CalcMultiTest" + * @param: test subsystem name + * @param: c_example module name + * @param: CalcMultiTest test suit name + */ +LITE_TEST_SUIT(husk, huks_lite, HksDeleteTest); + +/** + * @tc.setup: define a setup for test suit, format:"CalcMultiTest + SetUp" + * @return: true——setup success + */ +static BOOL HksDeleteTestSetUp() +{ + LiteTestPrint("setup\n"); + hi_watchdog_disable(); + TEST_ASSERT_TRUE(HksInitialize() == 0); + return TRUE; +} + +/** + * @tc.teardown: define a setup for test suit, format:"CalcMultiTest + TearDown" + * @return: true——teardown success + */ +static BOOL HksDeleteTestTearDown() +{ + LiteTestPrint("tearDown\n"); + hi_watchdog_enable(); + return TRUE; +} + + +static const struct HksTestKeyExistParams g_testKeyExistParams[] = { + /* normal case */ + { 0, HKS_SUCCESS, true, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE } }, +}; + +/** + * @tc.name: HksDeleteTest.HksDeleteTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksDeleteTest, HksDeleteTest001, Level1) +{ + int32_t ret; + struct HksBlob *keyAlias = NULL; + if (g_testKeyExistParams[0].isGenKey) { + HKS_TEST_ASSERT(TestGenDefaultKeyAndGetAlias(&keyAlias) == 0); + } else { + ret = TestConstuctBlob(&keyAlias, + g_testKeyExistParams[0].keyAliasParams.blobExist, + g_testKeyExistParams[0].keyAliasParams.blobSize, + g_testKeyExistParams[0].keyAliasParams.blobDataExist, + g_testKeyExistParams[0].keyAliasParams.blobDataSize); + HKS_TEST_ASSERT(ret == 0); + } + + ret = HksDeleteKeyRun(keyAlias, 1); + HKS_TEST_ASSERT(ret == g_testKeyExistParams[0].expectResult); + + TestFreeBlob(&keyAlias); + TEST_ASSERT_TRUE(ret == 0); +} + +RUN_TEST_SUITE(HksDeleteTest); +#endif /* _CUT_AUTHENTICATE_ */ + diff --git a/test/unittest/src/liteos_m_adapter/hks_derive_test.c b/test/unittest/src/liteos_m_adapter/hks_derive_test.c new file mode 100644 index 00000000..c2a1f3c2 --- /dev/null +++ b/test/unittest/src/liteos_m_adapter/hks_derive_test.c @@ -0,0 +1,225 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ +#include "hi_watchdog.h" +#include + +#include "hks_derive_test.h" + +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" + +#define DEFAULT_DERIVE_SIZE 32 +#define DEFAULT_INFO_SIZE 55 +#define DEFAULT_SALT_SIZE 16 + +/* + * @tc.register: register a test suit named "CalcMultiTest" + * @param: test subsystem name + * @param: c_example module name + * @param: CalcMultiTest test suit name + */ +LITE_TEST_SUIT(husk, huks_lite, HksDeriveTest); + +/** + * @tc.setup: define a setup for test suit, format:"CalcMultiTest + SetUp" + * @return: true——setup success + */ +static BOOL HksDeriveTestSetUp() +{ + LiteTestPrint("setup\n"); + hi_watchdog_disable(); + TEST_ASSERT_TRUE(HksInitialize() == 0); + return TRUE; +} + +/** + * @tc.teardown: define a setup for test suit, format:"CalcMultiTest + TearDown" + * @return: true——teardown success + */ +static BOOL HksDeriveTestTearDown() +{ + LiteTestPrint("tearDown\n"); + hi_watchdog_enable(); + return TRUE; +} + + +static const struct HksTestDeriveParams g_testDeriveParams[] = { + /* hkdf-sha256-salt-info */ + { 0, HKS_SUCCESS, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, /* genKey params */ + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_DERIVE, + true, HKS_DIGEST_SHA256, + false, 0, + false, 0, + false, 0 }, + { 0 }, + { + true, /* derive params */ + true, HKS_ALG_HKDF, + true, HKS_KEY_PURPOSE_DERIVE, + true, HKS_DIGEST_SHA256, + false, 0, + true, DEFAULT_SALT_SIZE, + true, DEFAULT_INFO_SIZE, + false, true }, + { + true, DEFAULT_DERIVE_SIZE, true, DEFAULT_DERIVE_SIZE }, + { + false, 0, false, 0 } + }, + + /* local: hkdf-sha256-salt-info */ + { 1, HKS_SUCCESS, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, /* genKey params */ + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_DERIVE, + true, HKS_DIGEST_SHA256, + false, 0, + false, 0, + true, HKS_STORAGE_TEMP }, + { 0 }, + { + true, /* derive params */ + true, HKS_ALG_HKDF, + true, HKS_KEY_PURPOSE_DERIVE, + true, HKS_DIGEST_SHA256, + false, 0, + true, DEFAULT_SALT_SIZE, + true, DEFAULT_INFO_SIZE, + true, false }, + { + true, DEFAULT_DERIVE_SIZE, true, DEFAULT_DERIVE_SIZE }, + { + true, DEFAULT_LOCAL_KEY_SIZE, true, DEFAULT_LOCAL_KEY_SIZE } + }, +}; + +static int32_t DeriveKey(const struct HksTestDeriveParamSet *deriveParamSetParams, const struct HksBlob *masterKey, + struct HksBlob *derivedKey, struct HksBlob **saltData, struct HksBlob **infoData) +{ + struct HksParamSet *deriveParamSet = NULL; + uint32_t saltSize = deriveParamSetParams->saltSize; + uint32_t infoSize = deriveParamSetParams->infoSize; + if (saltSize != 0) { + HKS_TEST_ASSERT(TestConstuctBlob(saltData, true, saltSize, true, saltSize) == 0); + } + if (infoSize != 0) { + HKS_TEST_ASSERT(TestConstuctBlob(infoData, true, infoSize, true, infoSize) == 0); + } + struct TestDeriveParamSetStructure paramStruct = { + &deriveParamSet, + deriveParamSetParams->paramSetExist, + deriveParamSetParams->setAlg, deriveParamSetParams->alg, + deriveParamSetParams->setPurpose, deriveParamSetParams->purpose, + deriveParamSetParams->setDigest, deriveParamSetParams->digest, + deriveParamSetParams->setIteration, deriveParamSetParams->iteration, + deriveParamSetParams->setSalt, *saltData, + deriveParamSetParams->setInfo, *infoData, + deriveParamSetParams->setIsKeyAlias, deriveParamSetParams->isKeyAlias + }; + int32_t ret = TestConstructDeriveParamSet(¶mStruct); + HKS_TEST_ASSERT(ret == 0); + + ret = HksDeriveKeyRun(deriveParamSet, masterKey, derivedKey, 1); + HksFreeParamSet(&deriveParamSet); + return ret; +} + +static int32_t BaseTestDerive(uint32_t index) +{ + /* 1. generate key */ + struct HksBlob *keyAlias = NULL; + int32_t ret; + if (g_testDeriveParams[index].genKeyParamSetParams.setKeyStorageFlag && + (g_testDeriveParams[index].genKeyParamSetParams.keyStorageFlag == HKS_STORAGE_TEMP)) { + ret = GenerateLocalRandomKey(&keyAlias, &g_testDeriveParams[index].localKeyParams); + } else { + if (g_testDeriveParams[index].keyAliasParams.blobExist) { + ret = GenerateKey(&keyAlias, &g_testDeriveParams[index].keyAliasParams, + &g_testDeriveParams[index].genKeyParamSetParams, NULL); + } else { + ret = TestConstuctBlob(&keyAlias, + g_testDeriveParams[index].masterKeyParams.blobExist, + g_testDeriveParams[index].masterKeyParams.blobSize, + g_testDeriveParams[index].masterKeyParams.blobDataExist, + g_testDeriveParams[index].masterKeyParams.blobDataSize); + } + } + TEST_ASSERT_TRUE(ret == 0); + + /* 2. derive */ + struct HksBlob *derivedKey = NULL; + ret = TestConstuctBlob(&derivedKey, + g_testDeriveParams[index].derivedKeyParams.blobExist, + g_testDeriveParams[index].derivedKeyParams.blobSize, + g_testDeriveParams[index].derivedKeyParams.blobDataExist, + g_testDeriveParams[index].derivedKeyParams.blobDataSize); + TEST_ASSERT_TRUE(ret == 0); + + struct HksBlob *saltData = NULL; + struct HksBlob *infoData = NULL; + ret = DeriveKey(&g_testDeriveParams[index].deriveParamSetParams, keyAlias, derivedKey, &saltData, &infoData); + if (ret != g_testDeriveParams[index].expectResult) { + HKS_TEST_LOG_I("failed, ret[%u] = %d", g_testDeriveParams[index].testId, ret); + } + TEST_ASSERT_TRUE(ret == g_testDeriveParams[index].expectResult); + + /* 3. delete key */ + if (!(g_testDeriveParams[index].genKeyParamSetParams.setKeyStorageFlag && + (g_testDeriveParams[index].genKeyParamSetParams.keyStorageFlag == HKS_STORAGE_TEMP)) && + (g_testDeriveParams[index].keyAliasParams.blobExist)) { + TEST_ASSERT_TRUE(HksDeleteKey(keyAlias, NULL) == 0); + } + TestFreeBlob(&keyAlias); + TestFreeBlob(&derivedKey); + TestFreeBlob(&saltData); + TestFreeBlob(&infoData); + + return ret; +} + +#ifndef _CUT_AUTHENTICATE_ +/** + * @tc.name: HksDeriveTest.HksDeriveTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksDeriveTest, HksDeriveTest001, Level1) +{ + int32_t ret = BaseTestDerive(0); + TEST_ASSERT_TRUE(ret == 0); +} +#endif /* _CUT_AUTHENTICATE_ */ + +/** + * @tc.name: HksDeriveTest.HksDeriveTest002 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksDeriveTest, HksDeriveTest002, Level1) +{ + int32_t ret = BaseTestDerive(1); + TEST_ASSERT_TRUE(ret == 0); +} +RUN_TEST_SUITE(HksDeriveTest); diff --git a/test/unittest/src/liteos_m_adapter/hks_exist_test.c b/test/unittest/src/liteos_m_adapter/hks_exist_test.c new file mode 100644 index 00000000..db0fe9db --- /dev/null +++ b/test/unittest/src/liteos_m_adapter/hks_exist_test.c @@ -0,0 +1,97 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef _CUT_AUTHENTICATE_ + +#include "hctest.h" +#include "hi_watchdog.h" +#include "hks_api.h" +#include "hks_exist_test.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" +#include "hks_type.h" + +/* + * @tc.register: register a test suit named "CalcMultiTest" + * @param: test subsystem name + * @param: c_example module name + * @param: CalcMultiTest test suit name + */ +LITE_TEST_SUIT(husk, huks_lite, HksExistTest); + +/** + * @tc.setup: define a setup for test suit, format:"CalcMultiTest + SetUp" + * @return: true——setup success + */ +static BOOL HksExistTestSetUp() +{ + LiteTestPrint("setup\n"); + hi_watchdog_disable(); + TEST_ASSERT_TRUE(HksInitialize() == 0); + return TRUE; +} + +/** + * @tc.teardown: define a setup for test suit, format:"CalcMultiTest + TearDown" + * @return: true——teardown success + */ +static BOOL HksExistTestTearDown() +{ + LiteTestPrint("tearDown\n"); + hi_watchdog_enable(); + return TRUE; +} + + +static const struct HksTestKeyExistParams g_testKeyExistParams[] = { + /* normal case */ + { 0, HKS_SUCCESS, true, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE } }, +}; + +/** + * @tc.name: HksExistTest.HksExistTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksExistTest, HksExistTest001, Level1) +{ + int32_t ret; + struct HksBlob *keyAlias = NULL; + if (g_testKeyExistParams[0].isGenKey) { + TEST_ASSERT_TRUE(TestGenDefaultKeyAndGetAlias(&keyAlias) == 0); + ret = HksKeyExistRun(keyAlias, 1); + TEST_ASSERT_TRUE(ret == g_testKeyExistParams[0].expectResult); + TEST_ASSERT_TRUE(HksDeleteKey(keyAlias, NULL) == HKS_SUCCESS); + } else { + ret = TestConstuctBlob(&keyAlias, + g_testKeyExistParams[0].keyAliasParams.blobExist, + g_testKeyExistParams[0].keyAliasParams.blobSize, + g_testKeyExistParams[0].keyAliasParams.blobDataExist, + g_testKeyExistParams[0].keyAliasParams.blobDataSize); + TEST_ASSERT_TRUE(ret == 0); + ret = HksKeyExistRun(keyAlias, 1); + if (ret != g_testKeyExistParams[0].expectResult) { + HKS_TEST_LOG_I("HksKeyExistRun 2 failed, ret[%u] = %d", g_testKeyExistParams[0].testId, ret); + } + TEST_ASSERT_TRUE(ret == g_testKeyExistParams[0].expectResult); + } + TestFreeBlob(&keyAlias); + TEST_ASSERT_TRUE(ret == 0); +} +RUN_TEST_SUITE(HksExistTest); +#endif /* _CUT_AUTHENTICATE_ */ + diff --git a/test/unittest/src/liteos_m_adapter/hks_generate_key_test.c b/test/unittest/src/liteos_m_adapter/hks_generate_key_test.c new file mode 100644 index 00000000..a7259b5e --- /dev/null +++ b/test/unittest/src/liteos_m_adapter/hks_generate_key_test.c @@ -0,0 +1,135 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef _CUT_AUTHENTICATE_ + +#include "hks_generate_key_test.h" + +#include +#include "hi_watchdog.h" +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" + +#define DEFAULT_X25519_PARAM_SET_OUT 104 + +/* + * @tc.register: register a test suit named "CalcMultiTest" + * @param: test subsystem name + * @param: c_example module name + * @param: CalcMultiTest test suit name + */ +LITE_TEST_SUIT(husk, huks_lite, HksGenerateKeyTest); + +/** + * @tc.setup: define a setup for test suit, format:"CalcMultiTest + SetUp" + * @return: true——setup success + */ +static BOOL HksGenerateKeyTestSetUp() +{ + LiteTestPrint("setup\n"); + hi_watchdog_disable(); + TEST_ASSERT_TRUE(HksInitialize() == 0); + return TRUE; +} + +/** + * @tc.teardown: define a setup for test suit, format:"CalcMultiTest + TearDown" + * @return: true——teardown success + */ +static BOOL HksGenerateKeyTestTearDown() +{ + LiteTestPrint("tearDown\n"); + hi_watchdog_enable(); + return TRUE; +} + + +static const struct HksTestGenKeyParams g_testGenKeyParams[] = { + /* x25519: ree sign/verify */ + { 0, HKS_SUCCESS, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, { + true, + true, HKS_ALG_X25519, + true, HKS_CURVE25519_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_SIGN | HKS_KEY_PURPOSE_VERIFY, + false, 0, + false, 0, + false, 0, + true, HKS_STORAGE_TEMP }, + { true, DEFAULT_X25519_PARAM_SET_OUT }, + }, +}; + +/** + * @tc.name: HksGenerateKeyTest.HksGenerateKeyTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksGenerateKeyTest, HksGenerateKeyTest001, Level1) +{ + uint32_t times = 1; + uint32_t index = 0; + uint32_t performTimes = 1; + struct HksBlob *keyAlias = NULL; + int32_t ret = TestConstuctBlob(&keyAlias, + g_testGenKeyParams[index].keyAliasParams.blobExist, + g_testGenKeyParams[index].keyAliasParams.blobSize, + g_testGenKeyParams[index].keyAliasParams.blobDataExist, + g_testGenKeyParams[index].keyAliasParams.blobDataSize); + TEST_ASSERT_TRUE(ret == 0); + + struct HksParamSet *paramSet = NULL; + struct GenerateKeyParamSetStructure paramStruct = { ¶mSet, + g_testGenKeyParams[index].paramSetParams.paramSetExist, + g_testGenKeyParams[index].paramSetParams.setAlg, g_testGenKeyParams[index].paramSetParams.alg, + g_testGenKeyParams[index].paramSetParams.setKeySize, g_testGenKeyParams[index].paramSetParams.keySize, + g_testGenKeyParams[index].paramSetParams.setPurpose, g_testGenKeyParams[index].paramSetParams.purpose, + g_testGenKeyParams[index].paramSetParams.setDigest, g_testGenKeyParams[index].paramSetParams.digest, + g_testGenKeyParams[index].paramSetParams.setPadding, g_testGenKeyParams[index].paramSetParams.padding, + g_testGenKeyParams[index].paramSetParams.setBlockMode, g_testGenKeyParams[index].paramSetParams.mode, + g_testGenKeyParams[index].paramSetParams.setKeyStorageFlag, + g_testGenKeyParams[index].paramSetParams.keyStorageFlag }; + ret = TestConstructGenerateKeyParamSet(¶mStruct); + TEST_ASSERT_TRUE(ret == 0); + + struct HksParamSet *paramSetOut = NULL; + ret = TestConstructGenerateKeyParamSetOut(¶mSetOut, + g_testGenKeyParams[index].paramSetParamsOut.paramSetExist, + g_testGenKeyParams[index].paramSetParamsOut.paramSetSize); + TEST_ASSERT_TRUE(ret == 0); + + ret = HksGenerateKeyRun(keyAlias, paramSet, paramSetOut, performTimes); + if (ret != g_testGenKeyParams[index].expectResult) { + HKS_TEST_LOG_I("failed, ret[%u] = %d", g_testGenKeyParams[index].testId, ret); + } + TEST_ASSERT_TRUE(ret == g_testGenKeyParams[index].expectResult); + + if ((ret == HKS_SUCCESS) && + !(g_testGenKeyParams[index].paramSetParams.setKeyStorageFlag == true) && + (g_testGenKeyParams[index].paramSetParams.keyStorageFlag == HKS_STORAGE_TEMP)) { + HKS_TEST_ASSERT(HksDeleteKey(keyAlias, NULL) == 0); + } + TestFreeBlob(&keyAlias); + HksFreeParamSet(¶mSet); + HksFreeParamSet(¶mSetOut); + HKS_TEST_LOG_I("[%u]TestGenerateKey, Testcase_GenerateKey_[%03u] pass!", times, g_testGenKeyParams[index].testId); + TEST_ASSERT_TRUE(ret == 0); +} + +RUN_TEST_SUITE(HksGenerateKeyTest); +#endif /* _CUT_AUTHENTICATE_ */ + diff --git a/test/unittest/src/liteos_m_adapter/hks_generate_random_test.c b/test/unittest/src/liteos_m_adapter/hks_generate_random_test.c new file mode 100644 index 00000000..f96c51f6 --- /dev/null +++ b/test/unittest/src/liteos_m_adapter/hks_generate_random_test.c @@ -0,0 +1,89 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include "hks_generate_random_test.h" + +#include "hctest.h" +#include "hi_watchdog.h" +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" +#include "hks_type.h" + +/* + * @tc.register: register a test suit named "CalcMultiTest" + * @param: test subsystem name + * @param: c_example module name + * @param: CalcMultiTest test suit name + */ +LITE_TEST_SUIT(husk, huks_lite, HksGenerateRandomTest); + +/** + * @tc.setup: define a setup for test suit, format:"CalcMultiTest + SetUp" + * @return: true——setup success + */ +static BOOL HksGenerateRandomTestSetUp() +{ + LiteTestPrint("setup\n"); + hi_watchdog_disable(); + TEST_ASSERT_TRUE(HksInitialize() == 0); + return TRUE; +} + +/** + * @tc.teardown: define a setup for test suit, format:"CalcMultiTest + TearDown" + * @return: true——teardown success + */ +static BOOL HksGenerateRandomTestTearDown() +{ + LiteTestPrint("tearDown\n"); + hi_watchdog_enable(); + return TRUE; +} + +static const struct HksTestGenRandomParams g_testGenRandomParams[] = { + /* normal case */ + { 0, HKS_SUCCESS, { true, HKS_MAX_RANDOM_LEN, true, HKS_MAX_RANDOM_LEN } }, +}; +/** + * @tc.name: HksGenerateRandomTest.HksGenerateRandomTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksGenerateRandomTest, HksGenerateRandomTest001, Level1) +{ + int32_t ret; + struct HksBlob *random = NULL; + + ret = TestConstructBlobOut(&random, + g_testGenRandomParams[0].randomParams.blobExist, + g_testGenRandomParams[0].randomParams.blobSize, + g_testGenRandomParams[0].randomParams.blobDataExist, + g_testGenRandomParams[0].randomParams.blobDataSize); + TEST_ASSERT_TRUE(ret == 0); + + ret = HksGenerateRandomRun(random, 1); + if (ret != g_testGenRandomParams[0].expectResult) { + HKS_TEST_LOG_I("HksGenerateRandomRun failed, ret[%u] = %d", g_testGenRandomParams[0].testId, ret); + } + TEST_ASSERT_TRUE(ret == g_testGenRandomParams[0].expectResult); + + TestFreeBlob(&random); + TEST_ASSERT_TRUE(ret == 0); +} + +RUN_TEST_SUITE(HksGenerateRandomTest); diff --git a/test/unittest/src/liteos_m_adapter/hks_hash_test.c b/test/unittest/src/liteos_m_adapter/hks_hash_test.c new file mode 100644 index 00000000..3d57b37c --- /dev/null +++ b/test/unittest/src/liteos_m_adapter/hks_hash_test.c @@ -0,0 +1,120 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef _CUT_AUTHENTICATE_ + +#include "hks_hash_test.h" + +#include +#include "hi_watchdog.h" +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" +#include "hks_type.h" + + +#define DEFAULT_SRC_DATA_SIZE 200 + +#define DIGEST_SHA256_HASH_SIZE 32 + +/* + * @tc.register: register a test suit named "CalcMultiTest" + * @param: test subsystem name + * @param: c_example module name + * @param: CalcMultiTest test suit name + */ +LITE_TEST_SUIT(husk, huks_lite, HksHashTest); + +/** + * @tc.setup: define a setup for test suit, format:"CalcMultiTest + SetUp" + * @return: true——setup success + */ +static BOOL HksHashTestSetUp() +{ + LiteTestPrint("setup\n"); + hi_watchdog_disable(); + TEST_ASSERT_TRUE(HksInitialize() == 0); + return TRUE; +} + +/** + * @tc.teardown: define a setup for test suit, format:"CalcMultiTest + TearDown" + * @return: true——teardown success + */ +static BOOL HksHashTestTearDown() +{ + LiteTestPrint("tearDown\n"); + hi_watchdog_enable(); + return TRUE; +} + + +static const struct HksTestHashParams g_testHashParams[] = { + /* normal case */ + { 0, HKS_SUCCESS, + { true, true, HKS_DIGEST_SHA256}, + { true, DEFAULT_SRC_DATA_SIZE, true, DEFAULT_SRC_DATA_SIZE }, + { true, DIGEST_SHA256_HASH_SIZE, true, DIGEST_SHA256_HASH_SIZE } + }, +}; + +/** + * @tc.name: HksHashTest.HksHashTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksHashTest, HksHashTest001, Level1) +{ + struct HksParamSet *paramSet = NULL; + struct HksBlob *srcData = NULL; + struct HksBlob *hash = NULL; + + int32_t ret = TestConstructHashParamSet(¶mSet, + g_testHashParams[0].paramSetParams.paramSetExist, + g_testHashParams[0].paramSetParams.setDigest, g_testHashParams[0].paramSetParams.digest); + TEST_ASSERT_TRUE(ret == 0); + + ret = TestConstuctBlob(&srcData, + g_testHashParams[0].srcDataParams.blobExist, + g_testHashParams[0].srcDataParams.blobSize, + g_testHashParams[0].srcDataParams.blobDataExist, + g_testHashParams[0].srcDataParams.blobDataSize); + TEST_ASSERT_TRUE(ret == 0); + + ret = TestConstructBlobOut(&hash, + g_testHashParams[0].hashParams.blobExist, + g_testHashParams[0].hashParams.blobSize, + g_testHashParams[0].hashParams.blobDataExist, + g_testHashParams[0].hashParams.blobDataSize); + TEST_ASSERT_TRUE(ret == 0); + + ret = HksHashRun(paramSet, srcData, hash, 1); + if (ret != g_testHashParams[0].expectResult) { + HKS_TEST_LOG_I("HksHashRun failed, ret[%u] = %d", g_testHashParams[0].testId, ret); + } + TEST_ASSERT_TRUE(ret == g_testHashParams[0].expectResult); + + HksFreeParamSet(¶mSet); + TestFreeBlob(&srcData); + TestFreeBlob(&hash); + HKS_TEST_LOG_I("[%u]TestHash, Testcase_Hash_[%03u] pass!", 1, g_testHashParams[0].testId); + TEST_ASSERT_TRUE(ret == 0); +} +RUN_TEST_SUITE(HksHashTest); + +#endif /* _CUT_AUTHENTICATE_ */ + diff --git a/test/unittest/src/liteos_m_adapter/hks_mac_test.c b/test/unittest/src/liteos_m_adapter/hks_mac_test.c new file mode 100644 index 00000000..14ac72ed --- /dev/null +++ b/test/unittest/src/liteos_m_adapter/hks_mac_test.c @@ -0,0 +1,206 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#include "hks_mac_test.h" + +#include +#include "hi_watchdog.h" +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_log.h" + +#define HKS_TEST_MAC_REE_KEY_SIZE_32 32 +#define HKS_DEFAULT_MAC_SRCDATA_SIZE 253 +#define HKS_DEFAULT_MAC_SHA256_SIZE 32 + + +static const struct HksTestMacParams g_testMacParams[] = { + /* success: ree-sha256 */ + { 0, HKS_SUCCESS, HKS_TEST_MAC_TYPE_REE, { 0 }, { 0 }, + { true, HKS_TEST_MAC_REE_KEY_SIZE_32, true, HKS_TEST_MAC_REE_KEY_SIZE_32 }, + { true, true, HKS_KEY_PURPOSE_MAC, true, HKS_DIGEST_SHA256 }, + { true, HKS_DEFAULT_MAC_SRCDATA_SIZE, true, HKS_DEFAULT_MAC_SRCDATA_SIZE }, + { true, HKS_DEFAULT_MAC_SHA256_SIZE, true, HKS_DEFAULT_MAC_SHA256_SIZE } + }, + + /* success: tee-sha256 */ + { 1, HKS_SUCCESS, HKS_TEST_MAC_TYPE_TEE, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + {true, true, HKS_ALG_AES, true, HKS_AES_KEY_SIZE_256, true, HKS_KEY_PURPOSE_MAC, + true, HKS_DIGEST_SHA256, false, 0, false, 0 }, + { 0 }, + { true, true, HKS_KEY_PURPOSE_MAC, true, HKS_DIGEST_SHA256 }, + { true, HKS_DEFAULT_MAC_SRCDATA_SIZE, true, HKS_DEFAULT_MAC_SRCDATA_SIZE }, + { true, HKS_DEFAULT_MAC_SHA256_SIZE, true, HKS_DEFAULT_MAC_SHA256_SIZE } + }, +}; + +/* + * @tc.register: register a test suit named "CalcMultiTest" + * @param: test subsystem name + * @param: c_example module name + * @param: CalcMultiTest test suit name + */ +LITE_TEST_SUIT(husk, huks_lite, HksMacTest); + +/** + * @tc.setup: define a setup for test suit, format:"CalcMultiTest + SetUp" + * @return: true——setup success + */ +static BOOL HksMacTestSetUp() +{ + LiteTestPrint("setup\n"); + hi_watchdog_disable(); + TEST_ASSERT_TRUE(HksInitialize() == 0); + return TRUE; +} + +/** + * @tc.teardown: define a setup for test suit, format:"CalcMultiTest + TearDown" + * @return: true——teardown success + */ +static BOOL HksMacTestTearDown() +{ + LiteTestPrint("tearDown\n"); + hi_watchdog_enable(); + return TRUE; +} + + +static int32_t ConstructDataToBlob(struct HksBlob **srcData, struct HksBlob **macData, + const struct HksTestBlobParams *srcDataParams, const struct HksTestBlobParams *macDataParams) +{ + int32_t ret = TestConstuctBlob(srcData, + srcDataParams->blobExist, + srcDataParams->blobSize, + srcDataParams->blobDataExist, + srcDataParams->blobDataSize); + TEST_ASSERT_TRUE(ret == 0); + + ret = TestConstuctBlob(macData, + macDataParams->blobExist, + macDataParams->blobSize, + macDataParams->blobDataExist, + macDataParams->blobDataSize); + TEST_ASSERT_TRUE(ret == 0); + return ret; +} + +static int32_t Mac(const struct HksBlob *key, const struct HksBlob *srcData, struct HksBlob *macData, + const struct HksTestMacParamSet *macParamSetParams, enum HksTestMacType macType) +{ + struct HksParamSet *macParamSet = NULL; + int32_t ret; + if (macType == HKS_TEST_MAC_TYPE_REE) { + struct TestMacParamSetStructure paramStructTrue = { + &macParamSet, + macParamSetParams->paramSetExist, + macParamSetParams->setPurpose, macParamSetParams->purpose, + macParamSetParams->setDigest, macParamSetParams->digest, true, false + }; + ret = TestConstructMacParamSet(¶mStructTrue); + } else { + struct TestMacParamSetStructure paramStructFalse = { + &macParamSet, + macParamSetParams->paramSetExist, + macParamSetParams->setPurpose, macParamSetParams->purpose, + macParamSetParams->setDigest, macParamSetParams->digest, false, false + }; + ret = TestConstructMacParamSet(¶mStructFalse); + } + TEST_ASSERT_TRUE(ret == 0); + + ret = HksMacRun(key, macParamSet, srcData, macData, 1); + HksFreeParamSet(&macParamSet); + return ret; +} + +static int32_t BaseTestMac(uint32_t index) +{ + /* 1. generate key */ + struct HksBlob *key = NULL; + int32_t ret; + + if (g_testMacParams[index].macType == HKS_TEST_MAC_TYPE_REE) { + ret = TestConstuctBlob(&key, + g_testMacParams[index].keyParams.blobExist, + g_testMacParams[index].keyParams.blobSize, + g_testMacParams[index].keyParams.blobDataExist, + g_testMacParams[index].keyParams.blobDataSize); + } else { + if (g_testMacParams[index].keyAliasParams.blobExist) { + ret = GenerateKey(&key, &(g_testMacParams[index].keyAliasParams), + &g_testMacParams[index].genKeyParamSetParams, NULL); + } else { + ret = TestConstuctBlob(&key, + g_testMacParams[index].keyParams.blobExist, + g_testMacParams[index].keyParams.blobSize, + g_testMacParams[index].keyParams.blobDataExist, + g_testMacParams[index].keyParams.blobDataSize); + } + } + TEST_ASSERT_TRUE(ret == 0); + + /* 2. mac */ + struct HksBlob *srcData = NULL; + struct HksBlob *macData = NULL; + ret = ConstructDataToBlob(&srcData, &macData, + &g_testMacParams[index].srcDataParams, &g_testMacParams[index].macParams); + TEST_ASSERT_TRUE(ret == 0); + + ret = Mac(key, srcData, macData, &g_testMacParams[index].macParamSetParams, g_testMacParams[index].macType); + if (ret != g_testMacParams[index].expectResult) { + HKS_TEST_LOG_I("failed, ret[%u] = %d", g_testMacParams[index].testId, ret); + } + TEST_ASSERT_TRUE(ret == g_testMacParams[index].expectResult); + + /* 3. deletekey */ + if ((g_testMacParams[index].macType == HKS_TEST_MAC_TYPE_TEE) && + (g_testMacParams[index].keyAliasParams.blobExist)) { + ret = HksDeleteKey(key, NULL); + TEST_ASSERT_TRUE(ret == 0); + } + TestFreeBlob(&key); + TestFreeBlob(&srcData); + TestFreeBlob(&macData); + return ret; +} + +/** + * @tc.name: HksMacTest.HksMacTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksMacTest, HksMacTest001, Level1) +{ + int32_t ret = BaseTestMac(0); + TEST_ASSERT_TRUE(ret == 0); +} + +#ifndef _CUT_AUTHENTICATE_ +/** + * @tc.name: HksMacTest.HksMacTest002 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksMacTest, HksMacTest002, Level1) +{ + int32_t ret = BaseTestMac(1); + TEST_ASSERT_TRUE(ret == 0); +} +#endif /* _CUT_AUTHENTICATE_ */ + +RUN_TEST_SUITE(HksMacTest); diff --git a/test/unittest/src/liteos_m_adapter/hks_modify_key_test.c b/test/unittest/src/liteos_m_adapter/hks_modify_key_test.c new file mode 100644 index 00000000..0b7e5b5e --- /dev/null +++ b/test/unittest/src/liteos_m_adapter/hks_modify_key_test.c @@ -0,0 +1,367 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef _CUT_AUTHENTICATE_ + + +#include "hks_modify_key_test.h" + +#include +#include "hi_watchdog.h" +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_cipher.h" +#include "hks_test_common.h" +#include "hks_test_log.h" +#include "stdlib.h" + +#define DEFAULT_AES_CIPHER_PLAIN_SIZE 1000 +#define AES_DEFAULT_GCM_NONCE_LENGTH 12 +#define AES_DEFAULT_AAD_LEN 4 +static const char *g_storePath = "./hks_store/"; +static const char *g_testName = "TestName"; + +static const struct HksTestCipherParams g_testCipherParams[] = { + /* success: aes256-gcm-none */ + { 0, HKS_SUCCESS, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, /* genKey params */ + true, HKS_ALG_AES, + true, HKS_AES_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_ENCRYPT | HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0 + }, + { false, 0 }, + { + HKS_TEST_CIPHER_TYPE_AES, true, /* encrypt params */ + true, HKS_ALG_AES, + true, HKS_KEY_PURPOSE_ENCRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0, + true, AES_DEFAULT_GCM_NONCE_LENGTH, + true, AES_DEFAULT_AAD_LEN + }, + { + HKS_TEST_CIPHER_TYPE_AES, true, /* decrypt params */ + true, HKS_ALG_AES, + true, HKS_KEY_PURPOSE_DECRYPT, + false, 0, + true, HKS_PADDING_NONE, + true, HKS_MODE_GCM, + false, 0, + true, AES_DEFAULT_GCM_NONCE_LENGTH, + true, AES_DEFAULT_AAD_LEN + }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE, true, DEFAULT_AES_CIPHER_PLAIN_SIZE }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE + 16, true, DEFAULT_AES_CIPHER_PLAIN_SIZE + 16 }, + { true, DEFAULT_AES_CIPHER_PLAIN_SIZE, true, DEFAULT_AES_CIPHER_PLAIN_SIZE }, + { false, 0, false, 0 } + }, +}; + +/* + * @tc.register: register a test suit named "CalcMultiTest" + * @param: test subsystem name + * @param: c_example module name + * @param: CalcMultiTest test suit name + */ +LITE_TEST_SUIT(husk, huks_lite, HksModifyKeyTest); + +/** + * @tc.setup: define a setup for test suit, format:"CalcMultiTest + SetUp" + * @return: true——setup success + */ +static BOOL HksModifyKeyTestSetUp() +{ + LiteTestPrint("setup\n"); + hi_watchdog_disable(); + TEST_ASSERT_TRUE(HksInitialize() == 0); + return TRUE; +} + +static void HksTestRemoveFile() +{ +} + +/** + * @tc.teardown: define a setup for test suit, format:"CalcMultiTest + TearDown" + * @return: true——teardown success + */ +static BOOL HksModifyKeyTestTearDown() +{ + LiteTestPrint("tearDown\n"); + HksTestRemoveFile(); + hi_watchdog_enable(); + return TRUE; +} + + +static int32_t ConstructDataToBlob(struct HksBlob **inData, struct HksBlob **outData, + const struct HksTestBlobParams *inTextParams, const struct HksTestBlobParams *outTextParams) +{ + int32_t ret = TestConstuctBlob(inData, + inTextParams->blobExist, + inTextParams->blobSize, + inTextParams->blobDataExist, + inTextParams->blobDataSize); + HKS_TEST_ASSERT(ret == 0); + + ret = TestConstuctBlob(outData, + outTextParams->blobExist, + outTextParams->blobSize, + outTextParams->blobDataExist, + outTextParams->blobDataSize); + HKS_TEST_ASSERT(ret == 0); + return ret; +} + +static int32_t Encrypt(struct CipherEncryptStructure *encryptStruct) +{ + int32_t ret; + struct HksParamSet *encryptParamSet = NULL; + + uint32_t ivSize = encryptStruct->cipherParms->ivSize; + uint32_t nonceSize = encryptStruct->cipherParms->nonceSize; + uint32_t aadSize = encryptStruct->cipherParms->aadSize; + if (ivSize != 0) { + ret = TestConstuctBlob(encryptStruct->ivData, true, ivSize, true, ivSize); + HKS_TEST_ASSERT(ret == 0); + } + if (nonceSize != 0) { + ret = TestConstuctBlob(encryptStruct->nonceData, true, nonceSize, true, nonceSize); + HKS_TEST_ASSERT(ret == 0); + } + if (aadSize != 0) { + ret = TestConstuctBlob(encryptStruct->aadData, true, aadSize, true, aadSize); + HKS_TEST_ASSERT(ret == 0); + } + struct AesCipherParamSetStructure enParamStruct = { + &encryptParamSet, + encryptStruct->cipherParms->paramSetExist, + encryptStruct->cipherParms->setAlg, encryptStruct->cipherParms->alg, + encryptStruct->cipherParms->setPurpose, encryptStruct->cipherParms->purpose, + encryptStruct->cipherParms->setPadding, encryptStruct->cipherParms->padding, + encryptStruct->cipherParms->setBlockMode, encryptStruct->cipherParms->mode, + encryptStruct->cipherParms->setIv, *(encryptStruct->ivData), + encryptStruct->cipherParms->setNonce, *(encryptStruct->nonceData), + encryptStruct->cipherParms->setAad, *(encryptStruct->aadData), + encryptStruct->cipherParms->setIsKeyAlias, encryptStruct->cipherParms->isKeyAlias + }; + ret = TestConstructAesCipherParamSet(&enParamStruct); + HKS_TEST_ASSERT(ret == 0); + + ret = HksEncryptRun(encryptStruct->keyAlias, encryptParamSet, encryptStruct->plainData, encryptStruct->cipherData, + encryptStruct->performTimes); + HksFreeParamSet(&encryptParamSet); + return ret; +} + +static int32_t DecryptCipher(struct CipherDecryptStructure *decryptStruct) +{ + int32_t ret = TestConstuctBlob(decryptStruct->decryptedData, + decryptStruct->cipherParms->decryptedTextParams.blobExist, + decryptStruct->cipherParms->decryptedTextParams.blobSize, + decryptStruct->cipherParms->decryptedTextParams.blobDataExist, + decryptStruct->cipherParms->decryptedTextParams.blobDataSize); + HKS_TEST_ASSERT(ret == 0); + + struct HksParamSet *decryptParamSet = NULL; + struct AesCipherParamSetStructure deParamStruct = { + &decryptParamSet, + decryptStruct->cipherParms->decryptParamSetParams.paramSetExist, + decryptStruct->cipherParms->decryptParamSetParams.setAlg, + decryptStruct->cipherParms->decryptParamSetParams.alg, + decryptStruct->cipherParms->decryptParamSetParams.setPurpose, + decryptStruct->cipherParms->decryptParamSetParams.purpose, + decryptStruct->cipherParms->decryptParamSetParams.setPadding, + decryptStruct->cipherParms->decryptParamSetParams.padding, + decryptStruct->cipherParms->decryptParamSetParams.setBlockMode, + decryptStruct->cipherParms->decryptParamSetParams.mode, + decryptStruct->cipherParms->decryptParamSetParams.setIv, decryptStruct->ivData, + decryptStruct->cipherParms->decryptParamSetParams.setNonce, decryptStruct->nonceData, + decryptStruct->cipherParms->decryptParamSetParams.setAad, decryptStruct->aadData, + decryptStruct->cipherParms->decryptParamSetParams.setIsKeyAlias, + decryptStruct->cipherParms->decryptParamSetParams.isKeyAlias + }; + ret = TestConstructAesCipherParamSet(&deParamStruct); + HKS_TEST_ASSERT(ret == 0); + + ret = HksDecryptRun(decryptStruct->keyAlias, decryptParamSet, decryptStruct->cipherData, + *(decryptStruct->decryptedData), decryptStruct->performTimes); + HksFreeParamSet(&decryptParamSet); + return ret; +} + +int32_t GenerateKeyTwo(const struct HksBlob *keyAlias, const struct HksTestBlobParams *keyAliasParams, + const struct HksTestGenKeyParamsParamSet *genKeyParamSetParams, + const struct HksTestGenKeyParamsParamSetOut *genKeyParamSetParamsOut) +{ + struct HksParamSet *paramSet = NULL; + struct GenerateKeyParamSetStructure paramStruct = { + ¶mSet, + genKeyParamSetParams->paramSetExist, + genKeyParamSetParams->setAlg, genKeyParamSetParams->alg, + genKeyParamSetParams->setKeySize, genKeyParamSetParams->keySize, + genKeyParamSetParams->setPurpose, genKeyParamSetParams->purpose, + genKeyParamSetParams->setDigest, genKeyParamSetParams->digest, + genKeyParamSetParams->setPadding, genKeyParamSetParams->padding, + genKeyParamSetParams->setBlockMode, genKeyParamSetParams->mode, + genKeyParamSetParams->setKeyStorageFlag, genKeyParamSetParams->keyStorageFlag + }; + int32_t ret = TestConstructGenerateKeyParamSet(¶mStruct); + HKS_TEST_ASSERT(ret == 0); + + struct HksParamSet *paramSetOut = NULL; + if (genKeyParamSetParamsOut != NULL) { + ret = TestConstructGenerateKeyParamSetOut(¶mSet, + genKeyParamSetParamsOut->paramSetExist, genKeyParamSetParamsOut->paramSetSize); + HKS_TEST_ASSERT(ret == 0); + } + + ret = HksGenerateKey(keyAlias, paramSet, paramSetOut); + HKS_TEST_ASSERT(ret == 0); + + HksFreeParamSet(¶mSet); + return ret; +} + +int32_t BaseTestCipherProcess(const struct HksBlob *keyAlias, uint32_t index) +{ + struct HksBlob *plainData = NULL; + struct HksBlob *cipherData = NULL; + int32_t ret = ConstructDataToBlob(&plainData, &cipherData, + &g_testCipherParams[index].plainTextParams, &g_testCipherParams[index].cipherTextParams); + HKS_TEST_ASSERT(ret == 0); + struct HksBlob *ivData = NULL; + struct HksBlob *nonceData = NULL; + struct HksBlob *aadData = NULL; + struct HksBlob *decryptedData = NULL; + /* 2. encrypt */ + do { + struct CipherEncryptStructure testEncryptStruct = { + keyAlias, &g_testCipherParams[index].encryptParamSetParams, + plainData, cipherData, &ivData, &nonceData, &aadData, 1 + }; + ret = Encrypt(&testEncryptStruct); + if (ret != g_testCipherParams[index].expectResult) { + break; + } + /* 3. decrypt */ + struct CipherDecryptStructure testDecryptStruct = { + keyAlias, &g_testCipherParams[index], cipherData, + &decryptedData, ivData, nonceData, aadData, 1 + }; + ret = DecryptCipher(&testDecryptStruct); + if (ret != g_testCipherParams[index].expectResult) { + break; + } + + if (ret == g_testCipherParams[index].expectResult) { + if (plainData->size != decryptedData->size) { + break; + }; + ret = memcmp(plainData->data, decryptedData->data, plainData->size); + } + } while (0); + TestFreeBlob(&plainData); + TestFreeBlob(&cipherData); + TestFreeBlob(&decryptedData); + TestFreeBlob(&ivData); + TestFreeBlob(&nonceData); + TestFreeBlob(&aadData); + return ret; +} + +enum HksStorageType { + HKS_STORAGE_TYPE_KEY = 0, + HKS_STORAGE_TYPE_CERTCHAIN, + HKS_STORAGE_TYPE_ROOT_KEY, +}; + +extern int32_t HksStoreKeyBlob(const struct HksBlob *processName, const struct HksBlob *keyAlias, + enum HksStorageType storageType, const struct HksBlob *keyBlob); +int32_t __attribute__((weak)) HksStoreKeyBlob(const struct HksBlob *processName, const struct HksBlob *keyAlias, + enum HksStorageType storageType, const struct HksBlob *keyBlob) +{ + (void)processName; + (void)keyAlias; + (void)storageType; + (void)keyBlob; +} + +/** + * @tc.name: HksModifyKeyTest.HksModifyKeyTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksModifyKeyTest, HksModifyKeyTest001, Level1) +{ + uint32_t index = 0; + struct HksBlob keyAlias = { strlen(g_testName), (uint8_t *)g_testName }; + int32_t ret = GenerateKeyTwo(&keyAlias, &g_testCipherParams[index].keyAliasParams, + &g_testCipherParams[index].genKeyParamSetParams, &g_testCipherParams[index].genKeyParamSetParamsOut); + TEST_ASSERT_TRUE(ret == 0); + + ret = BaseTestCipherProcess(&keyAlias, 0); + TEST_ASSERT_TRUE(ret == 0); + + struct HksBlob *plainData = NULL; + struct HksBlob *cipherData = NULL; + ret = ConstructDataToBlob(&plainData, &cipherData, + &g_testCipherParams[index].plainTextParams, &g_testCipherParams[index].cipherTextParams); + TEST_ASSERT_TRUE(ret == 0); + struct HksBlob *ivData = NULL; + struct HksBlob *nonceData = NULL; + struct HksBlob *aadData = NULL; + + /* 2. encrypt */ + struct CipherEncryptStructure testEncryptStruct = { + &keyAlias, &g_testCipherParams[index].encryptParamSetParams, + plainData, cipherData, &ivData, &nonceData, &aadData, 1 + }; + ret = Encrypt(&testEncryptStruct); + TEST_ASSERT_TRUE(ret == 0); + + ret = GenerateKeyTwo(&keyAlias, &g_testCipherParams[index].keyAliasParams, + &g_testCipherParams[index].genKeyParamSetParams, &g_testCipherParams[index].genKeyParamSetParamsOut); + TEST_ASSERT_TRUE(ret == 0); + + /* 3. decrypt */ + struct HksBlob *decryptedData = NULL; + struct CipherDecryptStructure testDecryptStruct = { + &keyAlias, &g_testCipherParams[index], cipherData, + &decryptedData, ivData, nonceData, aadData, 1 + }; + ret = DecryptCipher(&testDecryptStruct); + + HKS_TEST_ASSERT(ret != g_testCipherParams[index].expectResult); + TestFreeBlob(&plainData); + TestFreeBlob(&cipherData); + TestFreeBlob(&decryptedData); + TestFreeBlob(&ivData); + TestFreeBlob(&nonceData); + TestFreeBlob(&aadData); + TEST_ASSERT_TRUE(ret != 0); +} + +RUN_TEST_SUITE(HksModifyKeyTest); +#endif /* _CUT_AUTHENTICATE_ */ + diff --git a/test/unittest/src/liteos_m_adapter/hks_others_test.c b/test/unittest/src/liteos_m_adapter/hks_others_test.c new file mode 100644 index 00000000..e19f5bbf --- /dev/null +++ b/test/unittest/src/liteos_m_adapter/hks_others_test.c @@ -0,0 +1,146 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef _CUT_AUTHENTICATE_ + +#include "hks_others_test.h" + +#include +#include "hi_watchdog.h" +#include "hks_api.h" +#include "hks_param.h" +#include "hks_type.h" + +/* + * @tc.register: register a test suit named "CalcMultiTest" + * @param: test subsystem name + * @param: c_example module name + * @param: CalcMultiTest test suit name + */ +LITE_TEST_SUIT(husk, huks_lite, HksOthersTest); + +/** + * @tc.setup: define a setup for test suit, format:"CalcMultiTest + SetUp" + * @return: true——setup success + */ +static BOOL HksOthersTestSetUp() +{ + LiteTestPrint("setup\n"); + hi_watchdog_disable(); + TEST_ASSERT_TRUE(HksInitialize() == 0); + return TRUE; +} + +/** + * @tc.teardown: define a setup for test suit, format:"CalcMultiTest + TearDown" + * @return: true——teardown success + */ +static BOOL HksOthersTestTearDown() +{ + LiteTestPrint("tearDown\n"); + hi_watchdog_enable(); + return TRUE; +} + +/** + * @tc.name: HksOthersTest.HksOthersTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksOthersTest, HksOthersTest001, Level1) +{ + int32_t ret = HksGetKeyParamSet(NULL, NULL, NULL); + TEST_ASSERT_TRUE(ret == HKS_ERROR_NULL_POINTER); +} + +/** + * @tc.name: HksOthersTest.HksOthersTest002 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksOthersTest, HksOthersTest002, Level1) +{ + int32_t ret = HksGetKeyInfoList(NULL, NULL, NULL); + TEST_ASSERT_TRUE(ret == HKS_ERROR_NULL_POINTER); +} + +/** + * @tc.name: HksOthersTest.HksOthersTest003 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksOthersTest, HksOthersTest003, Level1) +{ + int32_t ret = HksAttestKey(NULL, NULL, NULL); + TEST_ASSERT_TRUE(ret == HKS_ERROR_NOT_SUPPORTED); +} + +/** + * @tc.name: HksOthersTest.HksOthersTest004 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksOthersTest, HksOthersTest004, Level1) +{ + int32_t ret = HksGetCertificateChain(NULL, NULL, NULL); + TEST_ASSERT_TRUE(ret == HKS_ERROR_NOT_SUPPORTED); +} + +/** + * @tc.name: HksOthersTest.HksOthersTest005 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksOthersTest, HksOthersTest005, Level1) +{ + int32_t ret = HksWrapKey(NULL, NULL, NULL, NULL); + TEST_ASSERT_TRUE(ret == HKS_ERROR_NOT_SUPPORTED); +} + +/** + * @tc.name: HksOthersTest.HksOthersTest006 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksOthersTest, HksOthersTest006, Level1) +{ + int32_t ret = HksUnwrapKey(NULL, NULL, NULL, NULL); + TEST_ASSERT_TRUE(ret == HKS_ERROR_NOT_SUPPORTED); +} + +/** + * @tc.name: HksOthersTest.HksOthersTest006 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksOthersTest, HksOthersTest007, Level1) +{ + int32_t ret = HksGetSdkVersion(NULL); + TEST_ASSERT_TRUE(ret == HKS_ERROR_NULL_POINTER); +} + +/** + * @tc.name: HksOthersTest.HksOthersTest008 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksOthersTest, HksOthersTest008, Level1) +{ + int32_t ret = HksInitialize(); + TEST_ASSERT_TRUE(ret == HKS_SUCCESS); +} +RUN_TEST_SUITE(HksOthersTest); + +#endif /* _CUT_AUTHENTICATE_ */ diff --git a/test/unittest/src/liteos_m_adapter/hks_safe_cipher_key_test.c b/test/unittest/src/liteos_m_adapter/hks_safe_cipher_key_test.c new file mode 100644 index 00000000..7653f78d --- /dev/null +++ b/test/unittest/src/liteos_m_adapter/hks_safe_cipher_key_test.c @@ -0,0 +1,165 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef _CUT_AUTHENTICATE_ + + +#include "hks_safe_cipher_key_test.h" + +#include +#include "hi_watchdog.h" +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_curve25519.h" +#include "hks_test_log.h" +#include "hks_test_mem.h" +#include "stdlib.h" + +const char *g_storePath = "/storage/"; +const char *g_testEd25519 = "test_ed25519"; + +/* + * @tc.register: register a test suit named "CalcMultiTest" + * @param: test subsystem name + * @param: c_example module name + * @param: CalcMultiTest test suit name + */ +LITE_TEST_SUIT(husk, huks_lite, HksSafeCipherKeyTest); + +/** + * @tc.setup: define a setup for test suit, format:"CalcMultiTest + SetUp" + * @return: true——setup success + */ +static BOOL HksSafeCipherKeyTestSetUp() +{ + LiteTestPrint("setup\n"); + hi_watchdog_disable(); + TEST_ASSERT_TRUE(HksInitialize() == 0); + return TRUE; +} + +/** + * @tc.teardown: define a setup for test suit, format:"CalcMultiTest + TearDown" + * @return: true——teardown success + */ +static BOOL HksSafeCipherKeyTestTearDown() +{ + LiteTestPrint("tearDown\n"); + hi_watchdog_enable(); + return TRUE; +} + +static struct HksBlob g_storageImageBuffer; + +static int32_t GetKeyOffsetByKeyAlias(const struct HksBlob *keyAlias, uint32_t *keyOffset) +{ + struct HksBlob storageBuf = g_storageImageBuffer; + + /* 1. get imageBuffer total Len */ + struct HksStoreHeaderInfo *keyInfoHead = (struct HksStoreHeaderInfo *)storageBuf.data; + uint32_t keyCount = keyInfoHead->keyCount; + uint32_t totalLen = keyInfoHead->totalLen; + + /* 2. traverse imageBuffer to search for keyAlias */ + uint32_t offset = sizeof(*keyInfoHead); + for (uint16_t i = 0; i < keyCount; ++i) { + uint8_t *tmpBuf = storageBuf.data + offset; + struct HksStoreKeyInfo *keyInfo = (struct HksStoreKeyInfo *)tmpBuf; + if (keyInfo->aliasSize == keyAlias->size) { + if (HksMemCmp(keyAlias->data, tmpBuf + sizeof(*keyInfo), keyAlias->size) == 0) { + *keyOffset = offset; + return HKS_SUCCESS; + } + } + + offset += keyInfo->keyInfoLen; + } + + return HKS_ERROR_NOT_EXIST; +} + +static int32_t CompareTwoKey(struct HksBlob *keyAliasOne, struct HksBlob *keyAliasTwo) +{ + uint32_t sizeOne = HksTestFileSize(g_storePath, "hks_keystore"); + uint8_t *bufOne = (uint8_t *)HksTestMalloc(sizeOne); + if (bufOne == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + + uint32_t sizeRead = HksTestFileRead(g_storePath, "hks_keystore", 0, bufOne, sizeOne); + TEST_ASSERT_TRUE(sizeRead > 0); + + g_storageImageBuffer.data = bufOne; + g_storageImageBuffer.size = sizeOne; + + int32_t offset1; + int ret = GetKeyOffsetByKeyAlias(keyAliasOne, &offset1); + TEST_ASSERT_TRUE(ret == 0); + + struct HksStoreKeyInfo *keyInfo1 = (struct HksStoreKeyInfo *)(g_storageImageBuffer.data + offset1); + + int32_t offset2; + ret = GetKeyOffsetByKeyAlias(keyAliasTwo, &offset2); + TEST_ASSERT_TRUE(ret == 0); + + struct HksStoreKeyInfo *keyInfo2 = (struct HksStoreKeyInfo *)(g_storageImageBuffer.data + offset2); + + TEST_ASSERT_TRUE(keyInfo1->keyInfoLen == keyInfo2->keyInfoLen); + + ret = memcmp(keyInfo1, keyInfo2, keyInfo1->keyInfoLen); + HksTestFree(bufOne); + return ret; +} + +/** + * @tc.name: HksSafeCipherKeyTest.HksSafeCipherKeyTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksSafeCipherKeyTest, HksSafeCipherKeyTest001, Level1) +{ + struct HksBlob ed25519Alias = { strlen(g_testEd25519), (uint8_t *)g_testEd25519 }; + uint8_t pubKey[32] = {0}; + uint32_t pubKeyLen = 32; + struct HksBlob pubKeyInfo = { pubKeyLen, pubKey }; + int32_t ret = TestGenerateEd25519Key(ed25519Alias); + TEST_ASSERT_TRUE(ret == 0); + + ret = HksExportPublicKey(&ed25519Alias, NULL, &pubKeyInfo); + TEST_ASSERT_TRUE(ret == 0); + + ret = HksDeleteKey(&ed25519Alias, NULL); + TEST_ASSERT_TRUE(ret == 0); + + struct HksBlob newAliasOne = { strlen("test_ed25519_1"), (uint8_t *)"test_ed25519_1" }; + ret = TestImportEd25519(newAliasOne, &pubKeyInfo); + TEST_ASSERT_TRUE(ret == 0); + + struct HksBlob newAliasTwo = { strlen("test_ed25519_2"), (uint8_t *)"test_ed25519_2" }; + ret = TestImportEd25519(newAliasTwo, &pubKeyInfo); + TEST_ASSERT_TRUE(ret == 0); + + ret = CompareTwoKey(&newAliasOne, &newAliasTwo); + TEST_ASSERT_TRUE(ret != 0); + + ret = HksDeleteKey(&newAliasOne, NULL); + HKS_TEST_ASSERT(ret == 0); + TEST_ASSERT_TRUE(ret == 0); + ret = HksDeleteKey(&newAliasTwo, NULL); + TEST_ASSERT_TRUE(ret == 0); +} +RUN_TEST_SUITE(HksSafeCipherKeyTest); + +#endif /* _CUT_AUTHENTICATE_ */ diff --git a/test/unittest/src/liteos_m_adapter/hks_safe_compare_key_test.c b/test/unittest/src/liteos_m_adapter/hks_safe_compare_key_test.c new file mode 100644 index 00000000..35832170 --- /dev/null +++ b/test/unittest/src/liteos_m_adapter/hks_safe_compare_key_test.c @@ -0,0 +1,212 @@ +/* + * Copyright (C) 2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef _CUT_AUTHENTICATE_ + + +#include "hks_safe_compare_key_test.h" + +#include +#include "hi_watchdog.h" +#include "hks_api.h" +#include "hks_param.h" +#include "hks_test_api_performance.h" +#include "hks_test_common.h" +#include "hks_test_file_operator.h" +#include "hks_test_log.h" +#include "hks_test_mem.h" + +static const char *g_storePath = "/storage/"; +static const char *g_testOne = "TestOne"; +static const char *g_testTwo = "TestTwo"; + +/* + * @tc.register: register a test suit named "CalcMultiTest" + * @param: test subsystem name + * @param: c_example module name + * @param: CalcMultiTest test suit name + */ +LITE_TEST_SUIT(husk, huks_lite, HksSafeCompareKeyTest); + +/** + * @tc.setup: define a setup for test suit, format:"CalcMultiTest + SetUp" + * @return: true——setup success + */ +static BOOL HksSafeCompareKeyTestSetUp() +{ + LiteTestPrint("setup\n"); + hi_watchdog_disable(); + TEST_ASSERT_TRUE(HksInitialize() == 0); + return TRUE; +} + +/** + * @tc.teardown: define a setup for test suit, format:"CalcMultiTest + TearDown" + * @return: true——teardown success + */ +static BOOL HksSafeCompareKeyTestTearDown() +{ + LiteTestPrint("tearDown\n"); + hi_watchdog_enable(); + return TRUE; +} + + +static const struct HksTestGenKeyParams g_testGenKeyParams[] = { + /* x25519: tee sign/verify */ + { 0, HKS_SUCCESS, { true, DEFAULT_KEY_ALIAS_SIZE, true, DEFAULT_KEY_ALIAS_SIZE }, + { + true, + true, HKS_ALG_X25519, + true, HKS_CURVE25519_KEY_SIZE_256, + true, HKS_KEY_PURPOSE_SIGN | HKS_KEY_PURPOSE_VERIFY, + false, 0, + false, 0, + false, 0, + false, 0 + }, + { false, 0 }, + }, +}; + +static int32_t SafeTestGenerateKey(struct HksBlob *keyAlias) +{ + uint32_t index = 0; + uint32_t performTimes = 1; + + struct HksParamSet *paramSet = NULL; + struct GenerateKeyParamSetStructure paramStruct = { + ¶mSet, + g_testGenKeyParams[index].paramSetParams.paramSetExist, + g_testGenKeyParams[index].paramSetParams.setAlg, g_testGenKeyParams[index].paramSetParams.alg, + g_testGenKeyParams[index].paramSetParams.setKeySize, g_testGenKeyParams[index].paramSetParams.keySize, + g_testGenKeyParams[index].paramSetParams.setPurpose, g_testGenKeyParams[index].paramSetParams.purpose, + g_testGenKeyParams[index].paramSetParams.setDigest, g_testGenKeyParams[index].paramSetParams.digest, + g_testGenKeyParams[index].paramSetParams.setPadding, g_testGenKeyParams[index].paramSetParams.padding, + g_testGenKeyParams[index].paramSetParams.setBlockMode, g_testGenKeyParams[index].paramSetParams.mode, + g_testGenKeyParams[index].paramSetParams.setKeyStorageFlag, + g_testGenKeyParams[index].paramSetParams.keyStorageFlag + }; + int32_t ret = TestConstructGenerateKeyParamSet(¶mStruct); + HKS_TEST_ASSERT(ret == 0); + + struct HksParamSet *paramSetOut = NULL; + ret = TestConstructGenerateKeyParamSetOut(¶mSetOut, + g_testGenKeyParams[index].paramSetParamsOut.paramSetExist, + g_testGenKeyParams[index].paramSetParamsOut.paramSetSize); + HKS_TEST_ASSERT(ret == 0); + + ret = HksGenerateKeyRun(keyAlias, paramSet, paramSetOut, performTimes); + if (ret != g_testGenKeyParams[index].expectResult) { + HKS_TEST_LOG_I("failed, ret[%u] = %d", g_testGenKeyParams[index].testId, ret); + } + HKS_TEST_ASSERT(ret == g_testGenKeyParams[index].expectResult); + + if (ret == g_testGenKeyParams[index].expectResult) { + ret = 0; + } + HksFreeParamSet(¶mSet); + HksFreeParamSet(¶mSetOut); + return ret; +} + + +static struct HksBlob g_storageImageBuffer; + +static int32_t GetKeyOffsetByKeyAlias(const struct HksBlob *keyAlias, uint32_t *keyOffset) +{ + struct HksBlob storageBuf = g_storageImageBuffer; + + /* 1. get imageBuffer total Len */ + struct HksStoreHeaderInfo *keyInfoHead = (struct HksStoreHeaderInfo *)storageBuf.data; + uint32_t keyCount = keyInfoHead->keyCount; + uint32_t totalLen = keyInfoHead->totalLen; + + /* 2. traverse imageBuffer to search for keyAlias */ + uint32_t offset = sizeof(*keyInfoHead); + for (uint16_t i = 0; i < keyCount; ++i) { + uint8_t *tmpBuf = storageBuf.data + offset; + struct HksStoreKeyInfo *keyInfo = (struct HksStoreKeyInfo *)tmpBuf; + if (keyInfo->aliasSize == keyAlias->size) { + if (HksMemCmp(keyAlias->data, tmpBuf + sizeof(*keyInfo), keyAlias->size) == 0) { + *keyOffset = offset; + return HKS_SUCCESS; + } + } + + offset += keyInfo->keyInfoLen; + } + + return HKS_ERROR_NOT_EXIST; +} + + +static int32_t CompareKeyData(struct HksBlob *keyAliasOne, struct HksBlob *keyAliasTwo) +{ + uint32_t sizeOne = HksTestFileSize(g_storePath, "hks_keystore"); + if (sizeOne == 0) { + return 0; + } + uint8_t *bufOne = (uint8_t *)HksTestMalloc(sizeOne); + if (bufOne == NULL) { + return HKS_ERROR_MALLOC_FAIL; + } + + uint32_t sizeRead = HksTestFileRead(g_storePath, "hks_keystore", 0, bufOne, sizeOne); + TEST_ASSERT_TRUE(sizeRead > 0); + + g_storageImageBuffer.data = bufOne; + g_storageImageBuffer.size = sizeOne; + + int32_t offset1; + int ret = GetKeyOffsetByKeyAlias(keyAliasOne, &offset1); + TEST_ASSERT_TRUE(ret == 0); + + struct HksStoreKeyInfo *keyInfo1 = (struct HksStoreKeyInfo *)(g_storageImageBuffer.data + offset1); + + int32_t offset2; + ret = GetKeyOffsetByKeyAlias(keyAliasTwo, &offset2); + TEST_ASSERT_TRUE(ret == 0); + + struct HksStoreKeyInfo *keyInfo2 = (struct HksStoreKeyInfo *)(g_storageImageBuffer.data + offset2); + + TEST_ASSERT_TRUE(keyInfo1->keyInfoLen == keyInfo2->keyInfoLen); + + ret = memcmp(keyInfo1, keyInfo2, keyInfo1->keyInfoLen); + HksTestFree(bufOne); + return ret; +} + +/** + * @tc.name: HksSafeCompareKeyTest.HksSafeCompareKeyTest001 + * @tc.desc: The static function will return true; + * @tc.type: FUNC + */ +LITE_TEST_CASE(HksSafeCompareKeyTest, HksSafeCompareKeyTest001, Level1) +{ + struct HksBlob keyAliasOne = { strlen(g_testOne), (uint8_t *)g_testOne }; + int32_t ret = SafeTestGenerateKey(&keyAliasOne); + HKS_TEST_ASSERT(ret == 0); + struct HksBlob keyAliasTwo = { strlen(g_testTwo), (uint8_t *)g_testTwo }; + ret = SafeTestGenerateKey(&keyAliasTwo); + HKS_TEST_ASSERT(ret == 0); + + ret = CompareKeyData(&keyAliasOne, &keyAliasTwo); + HKS_TEST_ASSERT(ret != 0); + TEST_ASSERT_TRUE(ret != 0); +} +RUN_TEST_SUITE(HksSafeCompareKeyTest); + +#endif /* _CUT_AUTHENTICATE_ */ -- Gitee From 89358eaa41338c786d30314284237fdf70a77054 Mon Sep 17 00:00:00 2001 From: wanghaixiang Date: Wed, 30 Jun 2021 12:56:36 +0800 Subject: [PATCH 2/3] =?UTF-8?q?=E5=88=A0=E9=99=A4=E5=A4=9A=E4=BD=99?= =?UTF-8?q?=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wanghaixiang --- .../main/common/include/hks_mem.h.orig | 52 ------------------- .../main/common/include/hks_mem.h.rej | 10 ---- 2 files changed, 62 deletions(-) delete mode 100644 frameworks/huks_standard/main/common/include/hks_mem.h.orig delete mode 100644 frameworks/huks_standard/main/common/include/hks_mem.h.rej diff --git a/frameworks/huks_standard/main/common/include/hks_mem.h.orig b/frameworks/huks_standard/main/common/include/hks_mem.h.orig deleted file mode 100644 index c0f7569a..00000000 --- a/frameworks/huks_standard/main/common/include/hks_mem.h.orig +++ /dev/null @@ -1,52 +0,0 @@ -/* - * Copyright (c) 2021 Huawei Device Co., Ltd. - * 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. - */ - -#ifndef HKS_MEM_H -#define HKS_MEM_H - -#include -#include - -#ifdef __cplusplus -extern "C" { -#endif - -void *HksMalloc(size_t size); -void HksFree(void *ptr); -int32_t HksMemCmp(const void *ptr1, const void *ptr2, uint32_t size); - -#define SELF_FREE_PTR(PTR, FREE_FUNC) \ -{ \ - if ((PTR) != NULL) { \ - FREE_FUNC(PTR); \ - (PTR) = NULL; \ - } \ -} - -#define HKS_FREE_PTR(p) SELF_FREE_PTR(p, HksFree) - -#define HKS_FREE_BLOB(blob) do { \ - if ((blob).data != NULL) { \ - HksFree((blob).data); \ - (blob).data = NULL; \ - } \ - (blob).size = 0; \ -} while (0) - -#ifdef __cplusplus -} -#endif - -#endif /* HKS_MEM_H */ diff --git a/frameworks/huks_standard/main/common/include/hks_mem.h.rej b/frameworks/huks_standard/main/common/include/hks_mem.h.rej deleted file mode 100644 index de5643ec..00000000 --- a/frameworks/huks_standard/main/common/include/hks_mem.h.rej +++ /dev/null @@ -1,10 +0,0 @@ ---- security_huks/frameworks/huks_standard/main/common/include/hks_mem.h 2021-06-10 14:20:35.000000000 +0800 -+++ security_huks_new/frameworks/huks_standard/main/common/include/hks_mem.h 2021-06-25 16:59:51.737430980 +0800 -@@ -16,6 +16,7 @@ - #ifndef HKS_MEM_H - #define HKS_MEM_H - -+#include - #include - - #ifdef __cplusplus -- Gitee From 65132ed43d294adcdaafa35448ad9d4957ae897d Mon Sep 17 00:00:00 2001 From: wanghaixiang Date: Wed, 30 Jun 2021 17:10:33 +0800 Subject: [PATCH 3/3] =?UTF-8?q?=E4=BF=AE=E6=94=B9config=E6=96=87=E4=BB=B6?= =?UTF-8?q?=C2=BC=C2=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: wanghaixiang --- .../main/common/include/hks_config.h | 28 ---- .../main/common/include/hks_config_base.h | 133 ++++++++++++++++++ .../os_dependency/sysinfo/src/hks_get_udid.c | 24 +--- .../main/core/include/hks_file_operator.h | 15 +- 4 files changed, 139 insertions(+), 61 deletions(-) create mode 100644 frameworks/huks_standard/main/common/include/hks_config_base.h diff --git a/frameworks/huks_standard/main/common/include/hks_config.h b/frameworks/huks_standard/main/common/include/hks_config.h index c8fb50ce..13c76480 100644 --- a/frameworks/huks_standard/main/common/include/hks_config.h +++ b/frameworks/huks_standard/main/common/include/hks_config.h @@ -16,23 +16,12 @@ #ifndef HKS_CONFIG_H #define HKS_CONFIG_H -#ifdef HKS_SUPPORT_PRODUCT_GT_WATCH -#define HKS_SUPPORT_LITE_HEAP -#endif - -#ifdef HKS_SUPPORT_PRODUCT_WINDOWS_PC -#define HKS_SUPPORT_UPGRADE_STORAGE_DATA -#endif - /* AES */ #define HKS_SUPPORT_AES_C #define HKS_SUPPORT_AES_GENERATE_KEY #define HKS_SUPPORT_AES_CBC_NOPADDING #define HKS_SUPPORT_AES_CBC_PKCS7 #define HKS_SUPPORT_AES_GCM -#ifdef HKS_SUPPORT_PRODUCT_GT_WATCH -#define HKS_SUPPORT_AES_CCM -#endif #define HKS_SUPPORT_POSIX @@ -40,21 +29,17 @@ #define HKS_SUPPORT_BN_C /* ECC */ -#ifndef HKS_SUPPORT_PRODUCT_GT_WATCH #define HKS_SUPPORT_ECC_C #define HKS_SUPPORT_ECC_GENERATE_KEY #define HKS_SUPPORT_ECC_GET_PUBLIC_KEY #define HKS_SUPPORT_ECDH_C #define HKS_SUPPORT_ECDSA_C -#endif /* ED25519 */ -#ifndef HKS_SUPPORT_PRODUCT_GT_WATCH #define HKS_SUPPORT_ED25519_C #define HKS_SUPPORT_ED25519_GENERATE_KEY #define HKS_SUPPORT_ED25519_SIGN_VERIFY #define HKS_SUPPORT_ED2519_GET_PUBLIC_KEY -#endif /* HASH */ #define HKS_SUPPORT_HASH_C @@ -68,13 +53,11 @@ #define HKS_SUPPORT_KDF_HKDF /* RSA */ -#ifndef HKS_SUPPORT_PRODUCT_GT_WATCH #define HKS_SUPPORT_RSA_C #define HKS_SUPPORT_RSA_GENERATE_KEY #define HKS_SUPPORT_RSA_CRYPT #define HKS_SUPPORT_RSA_SIGN_VERIFY #define HKS_SUPPORT_RSA_GET_PUBLIC_KEY -#endif /* X25519 */ #define HKS_SUPPORT_X25519_C @@ -83,10 +66,6 @@ #define HKS_SUPPORT_X25519_GET_PUBLIC_KEY #ifdef L2_STANDARD -#define HKS_SUPPORT_AGREE_TO_SAVE -#endif - -#ifdef HKS_SUPPORT_AGREE_TO_SAVE /* default: disable */ #define HKS_SUPPORT_ED25519_TO_X25519 #endif @@ -150,11 +129,4 @@ #define HKS_SUPPORT_API_GET_KEY_INFO_LIST #endif -#if defined(HKS_SUPPORT_PRODUCT_ROUTER) || defined(HKS_SUPPORT_PRODUCT_CPE) -#define HKS_SUPPORT_API_ATTEST_KEY -#define HKS_SUPPORT_API_GET_CERTIFICATE_CHAIN -#define HKS_SUPPORT_API_WRAP_KEY -#define HKS_SUPPORT_API_UNWRAP_KEY -#endif - #endif /* HKS_CONFIG_H */ diff --git a/frameworks/huks_standard/main/common/include/hks_config_base.h b/frameworks/huks_standard/main/common/include/hks_config_base.h new file mode 100644 index 00000000..301f5333 --- /dev/null +++ b/frameworks/huks_standard/main/common/include/hks_config_base.h @@ -0,0 +1,133 @@ +/* + * Copyright (c) 2021-2021 Huawei Device Co., Ltd. + * 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. + */ + +#ifndef HKS_CONFIG_H +#define HKS_CONFIG_H + +#define HKS_SUPPORT_LITE_HEAP +#define HKS_SUPPORT_UPGRADE_STORAGE_DATA +#define HKS_SUPPORT_POSIX + +/* AES */ +#define HKS_SUPPORT_AES_C +#define HKS_SUPPORT_AES_GENERATE_KEY +#define HKS_SUPPORT_AES_CBC_NOPADDING +#define HKS_SUPPORT_AES_CBC_PKCS7 +#define HKS_SUPPORT_AES_GCM +#define HKS_SUPPORT_AES_CCM + +/* BN */ +#define HKS_SUPPORT_BN_C + +/* ECC */ +#define HKS_SUPPORT_ECC_C +#define HKS_SUPPORT_ECC_GENERATE_KEY +#define HKS_SUPPORT_ECC_GET_PUBLIC_KEY +#define HKS_SUPPORT_ECDH_C +#define HKS_SUPPORT_ECDSA_C + +/* ED25519 */ +#define HKS_SUPPORT_ED25519_C +#define HKS_SUPPORT_ED25519_GENERATE_KEY +#define HKS_SUPPORT_ED25519_SIGN_VERIFY +#define HKS_SUPPORT_ED2519_GET_PUBLIC_KEY + +/* HASH */ +#define HKS_SUPPORT_HASH_C + +/* HMAC */ +#define HKS_SUPPORT_HMAC_C + +/* KDF */ +#define HKS_SUPPORT_KDF_C +#define HKS_SUPPORT_KDF_PBKDF2 +#define HKS_SUPPORT_KDF_HKDF + +/* RSA */ +#define HKS_SUPPORT_RSA_C +#define HKS_SUPPORT_RSA_GENERATE_KEY +#define HKS_SUPPORT_RSA_CRYPT +#define HKS_SUPPORT_RSA_SIGN_VERIFY +#define HKS_SUPPORT_RSA_GET_PUBLIC_KEY + +/* X25519 */ +#define HKS_SUPPORT_X25519_C +#define HKS_SUPPORT_X25519_GENERATE_KEY +#define HKS_SUPPORT_X25519_AGREE_KEY +#define HKS_SUPPORT_X25519_GET_PUBLIC_KEY + +#define HKS_SUPPORT_ED25519_TO_X25519 + +#if defined(HKS_SUPPORT_AES_GENERATE_KEY) || defined(HKS_SUPPORT_ECC_GENERATE_KEY) || \ + defined(HKS_SUPPORT_ED25519_GENERATE_KEY) || defined(HKS_SUPPORT_RSA_GENERATE_KEY) || \ + defined(HKS_SUPPORT_X25519_GENERATE_KEY) +#define HKS_SUPPORT_API_GENERATE_KEY +#define HKS_SUPPORT_API_DELETE_KEY +#define HKS_SUPPORT_API_GET_KEY_PARAM_SET +#define HKS_SUPPORT_API_KEY_EXIST +#endif + +#if defined(HKS_SUPPORT_ECC_C) || defined(HKS_SUPPORT_RSA_C) || \ + defined(HKS_SUPPORT_ED25519_C) || defined(HKS_SUPPORT_X25519_C) || \ + defined(HKS_SUPPORT_AES_C) +#define HKS_SUPPORT_API_IMPORT +#endif + +#if defined(HKS_SUPPORT_ECC_C) || defined(HKS_SUPPORT_RSA_C) || \ + defined(HKS_SUPPORT_ED25519_C) || defined(HKS_SUPPORT_X25519_C) +#define HKS_SUPPORT_API_EXPORT +#endif + +#define HKS_SUPPORT_API_GENERATE_RANDOM + +#if defined(HKS_SUPPORT_ECDSA_C) || defined(HKS_SUPPORT_ED25519_SIGN_VERIFY) || \ + defined(HKS_SUPPORT_RSA_SIGN_VERIFY) +#define HKS_SUPPORT_API_SIGN_VERIFY +#endif + +#if defined(HKS_SUPPORT_AES_C) || defined(HKS_SUPPORT_RSA_CRYPT) +#define HKS_SUPPORT_API_CIPHER +#endif + +#if defined(HKS_SUPPORT_X25519_AGREE_KEY) || defined(HKS_SUPPORT_ECDH_C) +#define HKS_SUPPORT_API_AGREE_KEY +#endif + +#ifdef HKS_SUPPORT_KDF_C +#define HKS_SUPPORT_API_DERIVE_KEY +#endif + +#ifdef HKS_SUPPORT_HMAC_C +#define HKS_SUPPORT_API_MAC +#endif + +#ifdef HKS_SUPPORT_HASH_C +#define HKS_SUPPORT_API_HASH +#endif + +#ifdef HKS_SUPPORT_BN_C +#define HKS_SUPPORT_API_BN_EXP_MOD +#endif + +#ifndef HKS_SUPPORT_LITE_HEAP +#define HKS_SUPPORT_API_GET_KEY_INFO_LIST +#endif + +#define HKS_SUPPORT_API_ATTEST_KEY +#define HKS_SUPPORT_API_GET_CERTIFICATE_CHAIN +#define HKS_SUPPORT_API_WRAP_KEY +#define HKS_SUPPORT_API_UNWRAP_KEY + +#endif /* HKS_CONFIG_H */ diff --git a/frameworks/huks_standard/main/os_dependency/sysinfo/src/hks_get_udid.c b/frameworks/huks_standard/main/os_dependency/sysinfo/src/hks_get_udid.c index 64d4054e..ffe6f3cf 100644 --- a/frameworks/huks_standard/main/os_dependency/sysinfo/src/hks_get_udid.c +++ b/frameworks/huks_standard/main/os_dependency/sysinfo/src/hks_get_udid.c @@ -23,29 +23,9 @@ #define HKS_HARDWARE_UDID_LEN 32 #ifndef _CUT_AUTHENTICATE_ -#if defined(HKS_SUPPORT_PRODUCT_GT_WATCH) -extern uint8_t GetUdid(uint8_t *buf, uint8_t length); - -int32_t HksGetHardwareUdid(uint8_t *udid, uint32_t udidLen) -{ - uint8_t hardwareUdid[HKS_HARDWARE_UDID_LEN] = {0}; - uint8_t resultLen = GetUdid(hardwareUdid, HKS_HARDWARE_UDID_LEN); - if (resultLen != HKS_HARDWARE_UDID_LEN) { - HKS_LOG_E("Get Udid failed!"); - return HKS_FAILURE; - } - - if (memcpy_s(udid, udidLen, hardwareUdid, HKS_HARDWARE_UDID_LEN) != EOK) { - HKS_LOG_E("Memcpy udid failed!"); - return HKS_ERROR_BAD_STATE; - } - - return HKS_SUCCESS; -} - -#else int32_t HksGetHardwareUdid(uint8_t *udid, uint32_t udidLen) { + /* simulation implementation */ const uint8_t testUdid[HKS_HARDWARE_UDID_LEN] = { 0xFE, 0xF1, 0xFA, 0xD5, 0xB6, 0x9D, 0x4A, 0xC8, 0x52, 0xE7, 0xF5, 0xA3, 0x8F, 0x0D, 0xE1, 0xC0, @@ -60,6 +40,4 @@ int32_t HksGetHardwareUdid(uint8_t *udid, uint32_t udidLen) return HKS_SUCCESS; } -#endif - #endif /* _CUT_AUTHENTICATE_ */ diff --git a/services/huks_standard/huks_service/main/core/include/hks_file_operator.h b/services/huks_standard/huks_service/main/core/include/hks_file_operator.h index ab12439f..54864681 100755 --- a/services/huks_standard/huks_service/main/core/include/hks_file_operator.h +++ b/services/huks_standard/huks_service/main/core/include/hks_file_operator.h @@ -23,17 +23,12 @@ #ifdef _STORAGE_LITE_ #define HKS_KEY_STORE_PATH "/storage/" #else - #ifdef HKS_SUPPORT_PRODUCT_GT_WATCH - #define HKS_KEY_STORE_PATH "user/maindata" - #define HKS_KEY_STORE_BAK_PATH "user/bakdata" + #ifdef L2_STANDARD + #define HKS_KEY_STORE_PATH "/data/data/maindata" + #define HKS_KEY_STORE_BAK_PATH "/data/data/bakdata" #else - #ifdef L2_STANDARD - #define HKS_KEY_STORE_PATH "/data/data/maindata" - #define HKS_KEY_STORE_BAK_PATH "/data/data/bakdata" - #else - #define HKS_KEY_STORE_PATH "/storage/maindata" - #define HKS_KEY_STORE_BAK_PATH "/storage/bakdata" - #endif + #define HKS_KEY_STORE_PATH "/storage/maindata" + #define HKS_KEY_STORE_BAK_PATH "/storage/bakdata" #endif #endif #define HKS_KEY_STORE_KEY_PATH "key" -- Gitee