From cd49bd12a2018cecf17c3512921bb4e96398481a Mon Sep 17 00:00:00 2001 From: yanglijun294 Date: Fri, 1 Dec 2023 10:34:26 +0800 Subject: [PATCH] =?UTF-8?q?=E6=94=AF=E6=8C=81=E5=BA=94=E7=94=A8=E7=BA=A7?= =?UTF-8?q?=E7=BB=91=E5=AE=9A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: yanglijun294 --- frameworks/inc/ipc_sdk.h | 7 + frameworks/src/ipc_sdk.c | 199 +++ frameworks/src/ipc_service.c | 167 +++ frameworks/src/standard/ipc_adapt.cpp | 10 +- interfaces/inner_api/device_auth.h | 99 ++ interfaces/inner_api/device_auth_defines.h | 1 + services/BUILD.gn | 7 + services/creds_manager/inc/creds_manager.h | 10 +- services/creds_manager/src/creds_manager.c | 953 ++---------- .../creds_manager/src/creds_operation_utils.c | 381 ----- services/device_auth.c | 273 +++- services/device_auth.map | 4 + services/deviceauth.gni | 38 +- services/deviceauth_account.gni | 45 +- services/frameworks/inc/common_defs.h | 5 + .../permission_adapter/permission_adapter.cpp | 30 + .../inc/cert_operation.h} | 12 +- .../inc/identity_common.h} | 20 +- .../inc/identity_defines.h} | 59 +- .../identity_manager/inc/identity_manager.h | 75 + .../src/cert_operation.c} | 162 +- .../src/credential_operator.c | 667 +++++++++ .../identity_manager/src/identity_common.c | 189 +++ .../identity_manager/src/identity_group.c | 808 ++++++++++ .../identity_manager/src/identity_manager.c | 61 + services/identity_manager/src/identity_p2p.c | 333 +++++ services/identity_manager/src/identity_pin.c | 363 +++++ .../src/mock/cert_operation_mock.c} | 7 +- .../src/mock/identity_common_mock.c | 51 + .../src/mock/identity_manager_mock.c | 65 + .../inc/account_related/account_module.h | 0 .../account_related/account_module_defines.h | 0 .../account_multi_task_manager.h | 92 +- .../inc/account_related/account_task_main.h | 94 +- .../account_related/account_version_util.h | 138 +- .../auth/iso_auth_task/iso_auth_client_task.h | 76 +- .../auth/iso_auth_task/iso_auth_server_task.h | 76 +- .../auth/iso_auth_task/iso_auth_task_common.h | 124 +- .../pake_v2_auth_client_task.h | 76 +- .../pake_v2_auth_server_task.h | 76 +- .../pake_v2_auth_task_common.h | 152 +- .../creds_manager/asy_token_manager.h | 0 .../creds_manager/sym_token_manager.h | 0 .../inc/account_unrelated/base_sub_task.h | 0 .../inc/account_unrelated/das_module.h | 0 .../account_unrelated/das_module_defines.h | 13 - .../inc/account_unrelated/das_task_common.h | 1 + .../inc/account_unrelated/das_task_main.h | 0 .../inc/account_unrelated/das_token_manager.h | 0 .../inc/account_unrelated/das_version_util.h | 0 .../iso_task/iso_base_cur_task.h | 0 .../iso_task/iso_client_task.h | 0 .../iso_client_protocol_task.h | 0 .../iso_server_protocol_task.h | 0 .../iso_task/iso_server_task.h | 0 .../iso_task/iso_task_common.h | 0 .../iso_task/iso_task_main.h | 0 .../das_lite_token_manager.h | 0 .../iso_client_bind_exchange_task.h | 0 .../iso_client_unbind_exchange_task.h | 0 .../iso_server_bind_exchange_task.h | 0 .../iso_server_unbind_exchange_task.h | 0 .../pake_task/common_standard_bind_exchange.h | 0 .../pake_task/das_standard_token_manager.h | 0 .../pake_task/pake_base_cur_task.h | 0 .../pake_task/pake_message_util.h | 0 .../pake_task/pake_task_common.h | 0 .../pake_v1_client_protocol_task.h | 0 .../pake_v1_task/pake_v1_client_task.h | 0 .../pake_v1_protocol_task_common.h | 0 .../pake_v1_server_protocol_task.h | 0 .../pake_v1_task/pake_v1_server_task.h | 0 .../pake_v1_task/pake_v1_task_main.h | 0 .../pake_v2_client_protocol_task.h | 0 .../pake_v2_task/pake_v2_client_task.h | 0 .../pake_v2_protocol_task_common.h | 0 .../pake_v2_server_protocol_task.h | 0 .../pake_v2_task/pake_v2_server_task.h | 0 .../pake_v2_task/pake_v2_task_main.h | 0 .../standard_client_bind_exchange_task.h | 0 .../standard_exchange_message_util.h | 0 .../standard_server_bind_exchange_task.h | 0 .../src/account_related/account_module.c | 0 .../account_multi_task_manager.c | 254 ++-- .../src/account_related/account_task_main.c | 442 +++--- .../account_related/account_version_util.c | 212 +-- .../auth/iso_auth_task/iso_auth_client_task.c | 774 +++++----- .../auth/iso_auth_task/iso_auth_server_task.c | 686 ++++----- .../auth/iso_auth_task/iso_auth_task_common.c | 848 +++++------ .../pake_v2_auth_client_task.c | 0 .../pake_v2_auth_server_task.c | 0 .../pake_v2_auth_task_common.c | 908 +++++------ .../creds_manager/asy_token_manager.c | 0 .../creds_manager/sym_token_manager.c | 0 .../account_module_mock.c | 0 .../src/account_unrelated/das_module.c | 0 .../src/account_unrelated/das_task_common.c | 19 +- .../src/account_unrelated/das_task_main.c | 0 .../src/account_unrelated/das_version_util.c | 0 .../iso_task/iso_client_task.c | 0 .../iso_client_protocol_task.c | 0 .../iso_server_protocol_task.c | 0 .../iso_task/iso_server_task.c | 0 .../iso_task/iso_task_common.c | 0 .../iso_task/iso_task_main.c | 0 .../das_lite_token_manager.c | 0 .../iso_client_bind_exchange_task.c | 0 .../iso_server_bind_exchange_task.c | 0 .../iso_task_mock/iso_task_main_mock.c | 0 .../pake_task/pake_message_util.c | 0 .../pake_task/pake_task_common.c | 0 .../pake_v1_task/pake_v1_client_task.c | 0 .../pake_v1_client_protocol_task.c | 0 .../pake_v1_protocol_task_common.c | 0 .../pake_v1_server_protocol_task.c | 0 .../pake_v1_task/pake_v1_server_task.c | 0 .../pake_v1_task/pake_v1_task_main.c | 0 .../pake_v1_task_main_mock.c | 0 .../pake_v2_task_main_mock.c | 0 .../common_standard_bind_exchange.c | 0 .../das_standard_token_manager.c | 0 .../standard_client_bind_exchange_task.c | 0 .../standard_exchange_message_util.c | 0 .../standard_server_bind_exchange_task.c | 0 .../standard_exchange_task_mock.c | 0 .../account_unrelated_mock/das_module_mock.c | 0 .../account_related_group_auth.h | 0 .../account_unrelated_group_auth.h | 0 .../group_auth/inc/base_group_auth.h | 0 .../inc/group_auth_data_operation.h | 0 .../account_related_group_auth.c | 0 .../account_related_group_auth_mock.c | 0 .../account_unrelated_group_auth.c | 0 .../account_unrelated_group_auth_mock.c | 0 .../group_auth_data_operation.c | 0 .../group_manager/inc/across_account_group.h | 0 .../group_manager/inc/base_group.h | 0 .../inc/base_group_manager_task.h | 0 .../inc/broadcast_manager/broadcast_manager.h | 0 .../inc/callback_manager/callback_manager.h | 0 .../inc/channel_manager/channel_manager.h | 0 .../soft_bus_channel/soft_bus_channel.h | 0 .../group_manager/inc/group_manager.h | 0 .../group_manager/inc/group_manager_common.h | 0 .../group_manager/inc/group_operation.h | 0 .../inc/group_operation_common.h | 0 .../inc/identical_account_group.h | 0 .../group_manager/inc/peer_to_peer_group.h | 0 .../src/broadcast_manager/broadcast_manager.c | 0 .../broadcast_manager_mock.c | 0 .../src/callback_manager/callback_manager.c | 0 .../src/channel_manager/channel_manager.c | 0 .../soft_bus_channel/soft_bus_channel.c | 0 .../soft_bus_channel_mock.c | 0 .../group_manager/src/group_manager.c | 0 .../group_manager/src/group_manager_common.c | 0 .../across_account_group.c | 1328 ++++++++--------- .../across_account_group_mock.c | 0 .../src/group_operation/group_operation.c | 0 .../group_operation/group_operation_common.c | 0 .../identical_account_group.c | 0 .../identical_account_group_mock.c | 0 .../peer_to_peer_group/peer_to_peer_group.c | 0 .../peer_to_peer_group_mock.c | 0 .../inc/session/dev_session_def.h | 2 +- .../inc/session/v2/dev_session_util.h | 2 +- .../src/session/dev_session_fwk.c | 32 +- .../compatible_auth_sub_session.c | 2 +- .../compatible_auth_sub_session_common.c | 2 +- .../src/session/v2/dev_session_util.c | 6 + .../src/session/v2/dev_session_v2.c | 90 +- .../expand_process_lib/auth_code_import.c | 21 +- .../expand_process_lib/pub_key_exchange.c | 33 +- test/unittest/deviceauth/BUILD.gn | 19 +- .../source/device_auth_ipc_test.cpp | 396 +++++ .../source/deviceauth_func_test.cpp | 889 +++++++++++ .../source/standard_exchange_task_test.cpp | 3 +- ...account_related_creds_manager_dir_test.cpp | 2 +- .../source/across_account_group_test.cpp | 2 +- .../source/identical_account_group_test.cpp | 2 +- .../source/peer_to_peer_group_test.cpp | 2 +- .../unit_test/services/creds_manager/BUILD.gn | 3 + .../creds_manager/creds_manager_test.cpp | 1 - .../frameworks/os_account_adapter/BUILD.gn | 3 + .../session/v2/expand_sub_session/BUILD.gn | 17 + .../expand_process_lib/BUILD.gn | 34 + 186 files changed, 8455 insertions(+), 4598 deletions(-) delete mode 100644 services/creds_manager/src/creds_operation_utils.c rename services/{creds_manager/inc/account_related/account_related_creds_manager.h => identity_manager/inc/cert_operation.h} (80%) rename services/{creds_manager/inc/creds_operation_utils.h => identity_manager/inc/identity_common.h} (71%) rename services/{creds_manager/inc/creds_manager_defines.h => identity_manager/inc/identity_defines.h} (62%) create mode 100644 services/identity_manager/inc/identity_manager.h rename services/{creds_manager/src/account_related/account_related_creds_manager.c => identity_manager/src/cert_operation.c} (82%) create mode 100644 services/identity_manager/src/credential_operator.c create mode 100644 services/identity_manager/src/identity_common.c create mode 100644 services/identity_manager/src/identity_group.c create mode 100644 services/identity_manager/src/identity_manager.c create mode 100644 services/identity_manager/src/identity_p2p.c create mode 100644 services/identity_manager/src/identity_pin.c rename services/{creds_manager/src/account_related_mock/account_related_creds_manager_mock.c => identity_manager/src/mock/cert_operation_mock.c} (89%) create mode 100644 services/identity_manager/src/mock/identity_common_mock.c create mode 100644 services/identity_manager/src/mock/identity_manager_mock.c rename services/{ => legacy}/authenticators/inc/account_related/account_module.h (100%) rename services/{ => legacy}/authenticators/inc/account_related/account_module_defines.h (100%) rename services/{ => legacy}/authenticators/inc/account_related/account_multi_task_manager.h (96%) rename services/{ => legacy}/authenticators/inc/account_related/account_task_main.h (96%) rename services/{ => legacy}/authenticators/inc/account_related/account_version_util.h (96%) rename services/{ => legacy}/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_client_task.h (96%) mode change 100755 => 100644 rename services/{ => legacy}/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_server_task.h (96%) mode change 100755 => 100644 rename services/{ => legacy}/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_task_common.h (96%) mode change 100755 => 100644 rename services/{ => legacy}/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_client_task.h (96%) rename services/{ => legacy}/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_server_task.h (96%) rename services/{ => legacy}/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_task_common.h (96%) rename services/{ => legacy}/authenticators/inc/account_related/creds_manager/asy_token_manager.h (100%) rename services/{ => legacy}/authenticators/inc/account_related/creds_manager/sym_token_manager.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/base_sub_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/das_module.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/das_module_defines.h (86%) rename services/{ => legacy}/authenticators/inc/account_unrelated/das_task_common.h (98%) rename services/{ => legacy}/authenticators/inc/account_unrelated/das_task_main.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/das_token_manager.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/das_version_util.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/iso_task/iso_base_cur_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/iso_task/iso_client_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/iso_task/iso_protocol_task/iso_client_protocol_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/iso_task/iso_protocol_task/iso_server_protocol_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/iso_task/iso_server_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/iso_task/iso_task_common.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/iso_task/iso_task_main.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/das_lite_token_manager.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_client_bind_exchange_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_client_unbind_exchange_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_server_bind_exchange_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_server_unbind_exchange_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/common_standard_bind_exchange.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/das_standard_token_manager.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/pake_base_cur_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/pake_message_util.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/pake_task_common.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_client_protocol_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_client_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task_common.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_server_protocol_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_server_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_task_main.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_client_protocol_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_client_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_protocol_task_common.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_server_protocol_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_server_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_task_main.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/standard_client_bind_exchange_task.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/standard_exchange_message_util.h (100%) rename services/{ => legacy}/authenticators/inc/account_unrelated/pake_task/standard_server_bind_exchange_task.h (100%) rename services/{ => legacy}/authenticators/src/account_related/account_module.c (100%) rename services/{ => legacy}/authenticators/src/account_related/account_multi_task_manager.c (96%) rename services/{ => legacy}/authenticators/src/account_related/account_task_main.c (96%) rename services/{ => legacy}/authenticators/src/account_related/account_version_util.c (97%) rename services/{ => legacy}/authenticators/src/account_related/auth/iso_auth_task/iso_auth_client_task.c (97%) mode change 100755 => 100644 rename services/{ => legacy}/authenticators/src/account_related/auth/iso_auth_task/iso_auth_server_task.c (97%) mode change 100755 => 100644 rename services/{ => legacy}/authenticators/src/account_related/auth/iso_auth_task/iso_auth_task_common.c (97%) mode change 100755 => 100644 rename services/{ => legacy}/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_client_task.c (100%) rename services/{ => legacy}/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_server_task.c (100%) rename services/{ => legacy}/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_task_common.c (97%) rename services/{ => legacy}/authenticators/src/account_related/creds_manager/asy_token_manager.c (100%) rename services/{ => legacy}/authenticators/src/account_related/creds_manager/sym_token_manager.c (100%) rename services/{ => legacy}/authenticators/src/account_related_mock/account_module_mock.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/das_module.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/das_task_common.c (95%) rename services/{ => legacy}/authenticators/src/account_unrelated/das_task_main.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/das_version_util.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/iso_task/iso_client_task.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/iso_task/iso_protocol_task/iso_client_protocol_task.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/iso_task/iso_protocol_task/iso_server_protocol_task.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/iso_task/iso_server_task.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/iso_task/iso_task_common.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/iso_task/iso_task_main.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/iso_task/lite_exchange_task/das_lite_token_manager.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/iso_task/lite_exchange_task/iso_client_bind_exchange_task.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/iso_task/lite_exchange_task/iso_server_bind_exchange_task.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/iso_task_mock/iso_task_main_mock.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/pake_task/pake_message_util.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/pake_task/pake_task_common.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_client_task.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task/pake_v1_client_protocol_task.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task/pake_v1_protocol_task_common.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task/pake_v1_server_protocol_task.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_server_task.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_task_main.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/pake_task/pake_v1_task_mock/pake_v1_task_main_mock.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/pake_task/pake_v2_task_mock/pake_v2_task_main_mock.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/pake_task/standard_exchange_task/common_standard_bind_exchange.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/pake_task/standard_exchange_task/das_standard_token_manager.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/pake_task/standard_exchange_task/standard_client_bind_exchange_task.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/pake_task/standard_exchange_task/standard_exchange_message_util.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/pake_task/standard_exchange_task/standard_server_bind_exchange_task.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated/pake_task/standard_exchange_task_mock/standard_exchange_task_mock.c (100%) rename services/{ => legacy}/authenticators/src/account_unrelated_mock/das_module_mock.c (100%) rename services/{ => legacy}/group_auth/inc/account_related_group_auth/account_related_group_auth.h (100%) rename services/{ => legacy}/group_auth/inc/account_unrelated_group_auth/account_unrelated_group_auth.h (100%) rename services/{ => legacy}/group_auth/inc/base_group_auth.h (100%) rename services/{ => legacy}/group_auth/inc/group_auth_data_operation.h (100%) rename services/{ => legacy}/group_auth/src/group_auth_manager/account_related_group_auth/account_related_group_auth.c (100%) rename services/{ => legacy}/group_auth/src/group_auth_manager/account_related_group_auth_mock/account_related_group_auth_mock.c (100%) rename services/{ => legacy}/group_auth/src/group_auth_manager/account_unrelated_group_auth/account_unrelated_group_auth.c (100%) rename services/{ => legacy}/group_auth/src/group_auth_manager/account_unrelated_group_auth_mock/account_unrelated_group_auth_mock.c (100%) rename services/{ => legacy}/group_auth/src/group_auth_manager/group_auth_data_operation.c (100%) rename services/{ => legacy}/group_manager/inc/across_account_group.h (100%) rename services/{ => legacy}/group_manager/inc/base_group.h (100%) rename services/{ => legacy}/group_manager/inc/base_group_manager_task.h (100%) rename services/{ => legacy}/group_manager/inc/broadcast_manager/broadcast_manager.h (100%) rename services/{ => legacy}/group_manager/inc/callback_manager/callback_manager.h (100%) rename services/{ => legacy}/group_manager/inc/channel_manager/channel_manager.h (100%) rename services/{ => legacy}/group_manager/inc/channel_manager/soft_bus_channel/soft_bus_channel.h (100%) rename services/{ => legacy}/group_manager/inc/group_manager.h (100%) rename services/{ => legacy}/group_manager/inc/group_manager_common.h (100%) rename services/{ => legacy}/group_manager/inc/group_operation.h (100%) rename services/{ => legacy}/group_manager/inc/group_operation_common.h (100%) rename services/{ => legacy}/group_manager/inc/identical_account_group.h (100%) rename services/{ => legacy}/group_manager/inc/peer_to_peer_group.h (100%) rename services/{ => legacy}/group_manager/src/broadcast_manager/broadcast_manager.c (100%) rename services/{ => legacy}/group_manager/src/broadcast_manager_mock/broadcast_manager_mock.c (100%) rename services/{ => legacy}/group_manager/src/callback_manager/callback_manager.c (100%) rename services/{ => legacy}/group_manager/src/channel_manager/channel_manager.c (100%) rename services/{ => legacy}/group_manager/src/channel_manager/soft_bus_channel/soft_bus_channel.c (100%) rename services/{ => legacy}/group_manager/src/channel_manager/soft_bus_channel_mock/soft_bus_channel_mock.c (100%) rename services/{ => legacy}/group_manager/src/group_manager.c (100%) rename services/{ => legacy}/group_manager/src/group_manager_common.c (100%) rename services/{ => legacy}/group_manager/src/group_operation/across_account_group/across_account_group.c (97%) rename services/{ => legacy}/group_manager/src/group_operation/across_account_group_mock/across_account_group_mock.c (100%) rename services/{ => legacy}/group_manager/src/group_operation/group_operation.c (100%) rename services/{ => legacy}/group_manager/src/group_operation/group_operation_common.c (100%) rename services/{ => legacy}/group_manager/src/group_operation/identical_account_group/identical_account_group.c (100%) rename services/{ => legacy}/group_manager/src/group_operation/identical_account_group_mock/identical_account_group_mock.c (100%) rename services/{ => legacy}/group_manager/src/group_operation/peer_to_peer_group/peer_to_peer_group.c (100%) rename services/{ => legacy}/group_manager/src/group_operation/peer_to_peer_group_mock/peer_to_peer_group_mock.c (100%) create mode 100644 test/unittest/deviceauth/source/deviceauth_func_test.cpp diff --git a/frameworks/inc/ipc_sdk.h b/frameworks/inc/ipc_sdk.h index b500759d..e09e1591 100644 --- a/frameworks/inc/ipc_sdk.h +++ b/frameworks/inc/ipc_sdk.h @@ -24,6 +24,9 @@ extern "C" { #define IPC_CALL_BACK_STUB_AUTH_ID 0 #define IPC_CALL_BACK_STUB_BIND_ID 1 +#define IPC_CALL_BACK_STUB_DIRECT_AUTH_ID 2 + +#define IPC_CALL_CONTEXT_INIT 0x0 /* params type for ipc call */ #define PARAM_TYPE_APPID 1 @@ -91,6 +94,10 @@ enum { IPC_CALL_GA_CANCEL_REQUEST, IPC_CALL_ID_GET_REAL_INFO, IPC_CALL_ID_GET_PSEUDONYM_ID, + IPC_CALL_ID_PROCESS_CREDENTIAL, + IPC_CALL_ID_DA_PROC_DATA, + IPC_CALL_ID_DA_AUTH_DEVICE, + IPC_CALL_ID_DA_CANCEL_REQUEST, }; #ifdef __cplusplus diff --git a/frameworks/src/ipc_sdk.c b/frameworks/src/ipc_sdk.c index 2f131dfd..d2e47e9d 100644 --- a/frameworks/src/ipc_sdk.c +++ b/frameworks/src/ipc_sdk.c @@ -1765,6 +1765,205 @@ static void InitIpcGaMethods(GroupAuthManager *gaMethodObj) return; } +DEVICE_AUTH_API_PUBLIC int32_t ProcessCredential(int32_t operationCode, const char *reqJsonStr, char **returnData) +{ + uintptr_t callCtx = IPC_CALL_CONTEXT_INIT; + int32_t ret; + IpcDataInfo replyCache = { 0 }; + + LOGI("starting ..."); + if (IsStrInvalid(reqJsonStr) || (returnData == NULL)) { + LOGE("Invalid params."); + return HC_ERR_INVALID_PARAMS; + } + ret = CreateCallCtx(&callCtx, NULL); + if (ret != HC_SUCCESS) { + LOGE("CreateCallCtx failed, ret %d", ret); + return HC_ERR_IPC_INIT; + } + ret = SetCallRequestParamInfo( + callCtx, PARAM_TYPE_OPCODE, (const uint8_t *)&operationCode, sizeof(operationCode)); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_OPCODE); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = + SetCallRequestParamInfo(callCtx, PARAM_TYPE_REQ_JSON, (const uint8_t *)reqJsonStr, strlen(reqJsonStr) + 1); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_REQ_JSON); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = DoBinderCall(callCtx, IPC_CALL_ID_PROCESS_CREDENTIAL, true); + if (ret == HC_ERR_IPC_INTERNAL_FAILED) { + LOGE("ipc call failed"); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_PROC_FAILED; + } + DecodeCallReply(callCtx, &replyCache, REPLAY_CACHE_NUM(replyCache)); + ret = GetIpcReplyByTypeInner(&replyCache, REPLAY_CACHE_NUM(replyCache), returnData); + if (ret != HC_SUCCESS) { + LOGE("GetIpcReplyByType failed, ret %d", ret); + } + DestroyCallCtx(&callCtx, NULL); + return ret; +} + +DEVICE_AUTH_API_PUBLIC int32_t ProcessAuthDevice( + int64_t requestId, const char *authParams, const DeviceAuthCallback *callback) +{ + uintptr_t callCtx = IPC_CALL_CONTEXT_INIT; + int32_t ret; + int32_t inOutLen; + IpcDataInfo replyCache = { 0 }; + + LOGI("starting ..."); + if (IsStrInvalid(authParams) || (callback == NULL)) { + LOGE("invalid params"); + return HC_ERR_INVALID_PARAMS; + } + ret = CreateCallCtx(&callCtx, NULL); + if (ret != HC_SUCCESS) { + LOGE("CreateCallCtx failed, ret %d", ret); + return HC_ERR_IPC_INIT; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_REQID, (const uint8_t *)(&requestId), sizeof(requestId)); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_REQID); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo( + callCtx, PARAM_TYPE_AUTH_PARAMS, (const uint8_t *)authParams, strlen(authParams) + 1); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_AUTH_PARAMS); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_DEV_AUTH_CB, (const uint8_t *)callback, sizeof(*callback)); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_DEV_AUTH_CB); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_BUILD_PARAM; + } + SetCbCtxToDataCtx(callCtx, IPC_CALL_BACK_STUB_DIRECT_AUTH_ID); + ret = DoBinderCall(callCtx, IPC_CALL_ID_DA_PROC_DATA, true); + if (ret == HC_ERR_IPC_INTERNAL_FAILED) { + LOGE("ipc call failed"); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_PROC_FAILED; + } + DecodeCallReply(callCtx, &replyCache, REPLAY_CACHE_NUM(replyCache)); + ret = HC_ERR_IPC_UNKNOW_REPLY; + inOutLen = sizeof(int32_t); + GetIpcReplyByType( + &replyCache, REPLAY_CACHE_NUM(replyCache), PARAM_TYPE_IPC_RESULT, (uint8_t *)&ret, &inOutLen); + LOGI("process done, ret %d", ret); + DestroyCallCtx(&callCtx, NULL); + return ret; +} + +DEVICE_AUTH_API_PUBLIC int32_t StartAuthDevice( + int64_t authReqId, const char *authParams, const DeviceAuthCallback *callback) +{ + uintptr_t callCtx = IPC_CALL_CONTEXT_INIT; + int32_t ret; + int32_t inOutLen; + IpcDataInfo replyCache = { 0 }; + + LOGI("starting ..."); + if (IsStrInvalid(authParams) || (callback == NULL)) { + LOGE("invalid params"); + return HC_ERR_INVALID_PARAMS; + } + ret = CreateCallCtx(&callCtx, NULL); + if (ret != HC_SUCCESS) { + LOGE("CreateCallCtx failed, ret %d", ret); + return HC_ERR_IPC_INIT; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_REQID, (const uint8_t *)(&authReqId), sizeof(authReqId)); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_REQID); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo( + callCtx, PARAM_TYPE_AUTH_PARAMS, (const uint8_t *)authParams, strlen(authParams) + 1); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_AUTH_PARAMS); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_BUILD_PARAM; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_DEV_AUTH_CB, (const uint8_t *)callback, sizeof(*callback)); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_DEV_AUTH_CB); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_BUILD_PARAM; + } + SetCbCtxToDataCtx(callCtx, IPC_CALL_BACK_STUB_DIRECT_AUTH_ID); + ret = DoBinderCall(callCtx, IPC_CALL_ID_DA_AUTH_DEVICE, true); + if (ret == HC_ERR_IPC_INTERNAL_FAILED) { + LOGE("ipc call failed"); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_PROC_FAILED; + } + DecodeCallReply(callCtx, &replyCache, REPLAY_CACHE_NUM(replyCache)); + ret = HC_ERR_IPC_UNKNOW_REPLY; + inOutLen = sizeof(int32_t); + GetIpcReplyByType( + &replyCache, REPLAY_CACHE_NUM(replyCache), PARAM_TYPE_IPC_RESULT, (uint8_t *)&ret, &inOutLen); + LOGI("process done, ret %d", ret); + DestroyCallCtx(&callCtx, NULL); + return ret; +} + +DEVICE_AUTH_API_PUBLIC int32_t CancelAuthRequest(int64_t requestId, const char *authParams) +{ + uintptr_t callCtx = IPC_CALL_CONTEXT_INIT; + int32_t ret; + int32_t inOutLen; + IpcDataInfo replyCache = { 0 }; + + LOGI("starting ..."); + if (IsStrInvalid(authParams)) { + LOGE("Invalid params."); + return HC_ERR_INVALID_PARAMS; + } + ret = CreateCallCtx(&callCtx, NULL); + if (ret != HC_SUCCESS) { + LOGE("CreateCallCtx failed, ret %d", ret); + return HC_ERR_NULL_PTR; + } + ret = SetCallRequestParamInfo(callCtx, PARAM_TYPE_REQID, (const uint8_t *)(&requestId), sizeof(requestId)); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, type %d", ret, PARAM_TYPE_REQID); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_NULL_PTR; + } + ret = SetCallRequestParamInfo( + callCtx, PARAM_TYPE_AUTH_PARAMS, (const uint8_t *)authParams, strlen(authParams) + 1); + if (ret != HC_SUCCESS) { + LOGE("set request param failed, ret %d, param id %d", ret, PARAM_TYPE_AUTH_PARAMS); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_NULL_PTR; + } + ret = DoBinderCall(callCtx, IPC_CALL_ID_DA_CANCEL_REQUEST, true); + if (ret != HC_SUCCESS) { + LOGE("ipc call failed"); + DestroyCallCtx(&callCtx, NULL); + return HC_ERR_IPC_PROC_FAILED; + } + DecodeCallReply(callCtx, &replyCache, REPLAY_CACHE_NUM(replyCache)); + ret = HC_ERR_IPC_UNKNOW_REPLY; + inOutLen = sizeof(int32_t); + GetIpcReplyByType( + &replyCache, REPLAY_CACHE_NUM(replyCache), PARAM_TYPE_IPC_RESULT, (uint8_t *)&ret, &inOutLen); + LOGI("process done, ret %d", ret); + DestroyCallCtx(&callCtx, NULL); + return ret; +} + DEVICE_AUTH_API_PUBLIC int InitDeviceAuthService(void) { InitHcMutex(&g_ipcMutex); diff --git a/frameworks/src/ipc_service.c b/frameworks/src/ipc_service.c index b7e7ba54..9357cc08 100644 --- a/frameworks/src/ipc_service.c +++ b/frameworks/src/ipc_service.c @@ -1110,6 +1110,167 @@ static int32_t IpcServiceGaGetPseudonymId(const IpcDataInfo *ipcParams, int32_t return ret; } +static int32_t IpcServiceDaProcessCredential(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache) +{ + int32_t ret; + int32_t operationCode = 0; + const char *reqJsonStr = NULL; + char *returnData = NULL; + + LOGI("starting ..."); + int32_t inOutLen = sizeof(int32_t); + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_OPCODE, (uint8_t *)&operationCode, &inOutLen); + if ((inOutLen != sizeof(int32_t)) || (ret != HC_SUCCESS)) { + LOGE("get param error, type %d", PARAM_TYPE_OPCODE); + return HC_ERR_IPC_BAD_PARAM; + } + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_REQ_JSON, (uint8_t *)&reqJsonStr, NULL); + if ((reqJsonStr == NULL) || (ret != HC_SUCCESS)) { + LOGE("get param error, type %d", PARAM_TYPE_REQ_JSON); + return HC_ERR_IPC_BAD_PARAM; + } + ret = ProcessCredential(operationCode, reqJsonStr, &returnData); + if (ret != HC_SUCCESS) { + LOGI("call ProcessCredential failed %d", ret); + } + if (returnData != NULL) { + ret = IpcEncodeCallReplay( + outCache, PARAM_TYPE_RETURN_DATA, (const uint8_t *)returnData, strlen(returnData) + 1); + HcFree(returnData); + } else { + ret = IpcEncodeCallReplay(outCache, PARAM_TYPE_RETURN_DATA, NULL, 0); + } + LOGI("process done, ipc ret %d", ret); + return ret; +} + +static int32_t IpcServiceDaProcessData(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache) +{ + int32_t callRet; + int32_t ret; + const DeviceAuthCallback *callback = NULL; + int64_t authReqId = 0; + const char *authParams = NULL; + int32_t inOutLen; + int32_t cbObjIdx = -1; + + LOGI("starting ..."); + inOutLen = sizeof(authReqId); + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_REQID, (uint8_t *)&authReqId, &inOutLen); + if ((inOutLen != sizeof(authReqId)) || (ret != HC_SUCCESS)) { + LOGE("get param error, type %d", PARAM_TYPE_REQID); + return HC_ERR_IPC_BAD_PARAM; + } + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_AUTH_PARAMS, (uint8_t *)&authParams, NULL); + if ((authParams == NULL) || (ret != HC_SUCCESS)) { + LOGE("get param error, type %d", PARAM_TYPE_AUTH_PARAMS); + return HC_ERR_IPC_BAD_PARAM; + } + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_DEV_AUTH_CB, (uint8_t *)&callback, NULL); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_DEV_AUTH_CB); + return ret; + } + ret = AddIpcCallBackByReqId( + authReqId, (const uint8_t *)callback, sizeof(DeviceAuthCallback), CB_TYPE_TMP_DEV_AUTH); + if (ret != HC_SUCCESS) { + LOGE("add ipc callback failed"); + return HC_ERROR; + } + inOutLen = sizeof(cbObjIdx); + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_CB_OBJECT, (uint8_t *)&cbObjIdx, &inOutLen); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_CB_OBJECT); + DelIpcCallBackByReqId(authReqId, CB_TYPE_TMP_DEV_AUTH, true); + return ret; + } + AddIpcCbObjByReqId(authReqId, cbObjIdx, CB_TYPE_TMP_DEV_AUTH); + InitDeviceAuthCbCtx(&g_authCbAdt, CB_TYPE_TMP_DEV_AUTH); + callRet = ProcessAuthDevice(authReqId, authParams, &g_authCbAdt); + if (callRet != HC_SUCCESS) { + DelIpcCallBackByReqId(authReqId, CB_TYPE_TMP_DEV_AUTH, true); + } + ret = IpcEncodeCallReplay(outCache, PARAM_TYPE_IPC_RESULT, (const uint8_t *)&callRet, sizeof(int32_t)); + LOGI("process done, call ret %d, ipc ret %d", callRet, ret); + return ret; +} + +static int32_t IpcServiceDaAuthDevice(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache) +{ + int32_t callRet; + int32_t ret; + DeviceAuthCallback *callback = NULL; + int64_t authReqId = 0; + const char *authParams = NULL; + int32_t inOutLen; + int32_t cbObjIdx = -1; + + LOGI("starting ..."); + inOutLen = sizeof(authReqId); + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_REQID, (uint8_t *)&authReqId, &inOutLen); + if ((inOutLen != sizeof(authReqId)) || (ret != HC_SUCCESS)) { + LOGE("get param error, type %d", PARAM_TYPE_REQID); + return HC_ERR_IPC_BAD_PARAM; + } + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_AUTH_PARAMS, (uint8_t *)&authParams, NULL); + if ((authParams == NULL) || (ret != HC_SUCCESS)) { + LOGE("get param error, type %d", PARAM_TYPE_AUTH_PARAMS); + return HC_ERR_IPC_BAD_PARAM; + } + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_DEV_AUTH_CB, (uint8_t *)&callback, NULL); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_DEV_AUTH_CB); + return ret; + } + ret = AddIpcCallBackByReqId( + authReqId, (const uint8_t *)callback, sizeof(DeviceAuthCallback), CB_TYPE_TMP_DEV_AUTH); + if (ret != HC_SUCCESS) { + LOGE("add ipc callback failed"); + return HC_ERROR; + } + inOutLen = sizeof(cbObjIdx); + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_CB_OBJECT, (uint8_t *)&cbObjIdx, &inOutLen); + if (ret != HC_SUCCESS) { + LOGE("get param error, type %d", PARAM_TYPE_CB_OBJECT); + DelIpcCallBackByReqId(authReqId, CB_TYPE_TMP_DEV_AUTH, true); + return ret; + } + AddIpcCbObjByReqId(authReqId, cbObjIdx, CB_TYPE_TMP_DEV_AUTH); + InitDeviceAuthCbCtx(&g_authCbAdt, CB_TYPE_TMP_DEV_AUTH); + callRet = StartAuthDevice(authReqId, authParams, &g_authCbAdt); + if (callRet != HC_SUCCESS) { + DelIpcCallBackByReqId(authReqId, CB_TYPE_TMP_DEV_AUTH, true); + } + ret = IpcEncodeCallReplay(outCache, PARAM_TYPE_IPC_RESULT, (const uint8_t *)&callRet, sizeof(int32_t)); + LOGI("process done, call ret %d, ipc ret %d", callRet, ret); + return ret; +} + +static int32_t IpcServiceDaCancelRequest(const IpcDataInfo *ipcParams, int32_t paramNum, uintptr_t outCache) +{ + int32_t ret; + int64_t requestId = 0; + const char *authParams = NULL; + + LOGI("starting ..."); + int32_t inOutLen = sizeof(int64_t); + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_REQID, (uint8_t *)&requestId, &inOutLen); + if ((inOutLen != sizeof(requestId)) || (ret != HC_SUCCESS)) { + LOGE("get param error, type %d", PARAM_TYPE_REQID); + return HC_ERR_IPC_BAD_PARAM; + } + ret = GetIpcRequestParamByType(ipcParams, paramNum, PARAM_TYPE_AUTH_PARAMS, (uint8_t *)&authParams, NULL); + if ((authParams == NULL) || (ret != HC_SUCCESS)) { + LOGE("get param error, type %d", PARAM_TYPE_AUTH_PARAMS); + return HC_ERR_IPC_BAD_PARAM; + } + ret = CancelAuthRequest(requestId, authParams); + DelIpcCallBackByReqId(requestId, CB_TYPE_TMP_DEV_AUTH, true); + ret = IpcEncodeCallReplay(outCache, PARAM_TYPE_IPC_RESULT, (const uint8_t *)&ret, sizeof(int32_t)); + LOGI("process done, ipc ret %d", ret); + return ret; +} + int32_t AddMethodMap(uintptr_t ipcInstance) { uint32_t ret; @@ -1144,6 +1305,12 @@ int32_t AddMethodMap(uintptr_t ipcInstance) ret &= SetIpcCallMap(ipcInstance, IpcServiceGaCancelRequest, IPC_CALL_GA_CANCEL_REQUEST); ret &= SetIpcCallMap(ipcInstance, IpcServiceGaGetRealInfo, IPC_CALL_ID_GET_REAL_INFO); ret &= SetIpcCallMap(ipcInstance, IpcServiceGaGetPseudonymId, IPC_CALL_ID_GET_PSEUDONYM_ID); + + // Direct Auth Interfaces + ret &= SetIpcCallMap(ipcInstance, IpcServiceDaProcessCredential, IPC_CALL_ID_PROCESS_CREDENTIAL); + ret &= SetIpcCallMap(ipcInstance, IpcServiceDaAuthDevice, IPC_CALL_ID_DA_AUTH_DEVICE); + ret &= SetIpcCallMap(ipcInstance, IpcServiceDaProcessData, IPC_CALL_ID_DA_PROC_DATA); + ret &= SetIpcCallMap(ipcInstance, IpcServiceDaCancelRequest, IPC_CALL_ID_DA_CANCEL_REQUEST); LOGI("process done, ret %u", ret); return ret; } diff --git a/frameworks/src/standard/ipc_adapt.cpp b/frameworks/src/standard/ipc_adapt.cpp index 8073acc6..6f93eb48 100644 --- a/frameworks/src/standard/ipc_adapt.cpp +++ b/frameworks/src/standard/ipc_adapt.cpp @@ -33,10 +33,10 @@ using namespace OHOS; namespace { static const int32_t BUFF_MAX_SZ = 128; static const int32_t IPC_CALL_BACK_MAX_NODES = 64; - static const int32_t IPC_CALL_BACK_STUB_NODES = 2; + static const int32_t IPC_CALL_BACK_STUB_NODES = 3; } -static sptr g_sdkCbStub[IPC_CALL_BACK_STUB_NODES] = { nullptr, nullptr }; +static sptr g_sdkCbStub[IPC_CALL_BACK_STUB_NODES] = { nullptr, nullptr, nullptr }; typedef void (*CallbackStub)(uintptr_t, const IpcDataInfo *, int32_t, MessageParcel &); typedef struct { @@ -1509,6 +1509,7 @@ int32_t GetIpcRequestParamByType(const IpcDataInfo *ipcParams, int32_t paramNum, bool IsCallbackMethod(int32_t methodId) { if ((methodId == IPC_CALL_ID_REG_CB) || (methodId == IPC_CALL_ID_REG_LISTENER) || + (methodId == IPC_CALL_ID_DA_AUTH_DEVICE) || (methodId == IPC_CALL_ID_DA_PROC_DATA) || (methodId == IPC_CALL_ID_GA_PROC_DATA) || (methodId == IPC_CALL_ID_AUTH_DEVICE)) { return true; } @@ -1519,6 +1520,7 @@ void UnInitProxyAdapt(void) { g_sdkCbStub[IPC_CALL_BACK_STUB_AUTH_ID] = nullptr; g_sdkCbStub[IPC_CALL_BACK_STUB_BIND_ID] = nullptr; + g_sdkCbStub[IPC_CALL_BACK_STUB_DIRECT_AUTH_ID] = nullptr; return; } @@ -1526,7 +1528,9 @@ int32_t InitProxyAdapt(void) { g_sdkCbStub[IPC_CALL_BACK_STUB_AUTH_ID] = new(std::nothrow) StubDevAuthCb; g_sdkCbStub[IPC_CALL_BACK_STUB_BIND_ID] = new(std::nothrow) StubDevAuthCb; - if (!g_sdkCbStub[IPC_CALL_BACK_STUB_AUTH_ID] || !g_sdkCbStub[IPC_CALL_BACK_STUB_BIND_ID]) { + g_sdkCbStub[IPC_CALL_BACK_STUB_DIRECT_AUTH_ID] = new(std::nothrow) StubDevAuthCb; + if (!g_sdkCbStub[IPC_CALL_BACK_STUB_AUTH_ID] || !g_sdkCbStub[IPC_CALL_BACK_STUB_BIND_ID] || + !g_sdkCbStub[IPC_CALL_BACK_STUB_DIRECT_AUTH_ID]) { LOGE("alloc callback stub object failed"); UnInitProxyAdapt(); return HC_ERR_ALLOC_MEMORY; diff --git a/interfaces/inner_api/device_auth.h b/interfaces/inner_api/device_auth.h index eea7ae4f..5fc022c9 100644 --- a/interfaces/inner_api/device_auth.h +++ b/interfaces/inner_api/device_auth.h @@ -65,6 +65,9 @@ #define FIELD_EXPIRE_TIME "expireTime" #define FIELD_IS_DELETE_ALL "isDeleteAll" #define FIELD_OS_ACCOUNT_ID "osAccountId" +#define FIELD_ACQURIED_TYPE "acquireType" +#define FIELD_CRED_OP_FLAG "flag" +#define FIELD_CRED_OP_RESULT "result" #define FIELD_AUTH_CODE "authCode" #define FIELD_DEVICE_LIST "deviceList" #define FIELD_IS_UDID_HASH "isUdidHash" @@ -285,10 +288,106 @@ typedef struct { void (*destroyInfo)(char **returnInfo); } DeviceGroupManager; +/** + * @brief This enum provides all the operationCode of interface ProcessCredential. + */ +enum { + /** invalid operationCode for initialize */ + CRED_OP_INVALID = -1, + /** operationCode for ProcessCredential to query credential */ + CRED_OP_QUERY, + /** operationCode for ProcessCredential to create credential */ + CRED_OP_CREATE, + /** operationCode for ProcessCredential to import credential */ + CRED_OP_IMPORT, + /** operationCode for ProcessCredential to delete credential */ + CRED_OP_DELETE, +}; + +/** + * @brief This enum provides all the flag of reqJsion for interface ProcessCredential. + */ +enum { + /** invalid flag for initialize */ + RETURN_FLAG_INVALID = -1, + /** flag for only return result */ + RETURN_FLAG_DEFAULT, + /** flag for return result and publicKey */ + RETURN_FLAG_PUBLIC_KEY, +}; + +/** + * @brief This enum provides all the acquireType of interface StartAuthDevice & ProcessAuthDevice. + */ +typedef enum { + /** invalid acquireType for initialize */ + ACQUIRE_TYPE_INVALID = -1, + /** acquireType for p2p bind */ + P2P_BIND, +} AcquireType; + #ifdef __cplusplus extern "C" { #endif +/** + * @brief Process Credential data. + * + * This API is used to process Credential data. + * + * @param operationCode: use one of CRED_OP_QUERY|CRED_OP_CREATE|CRED_OP_IMPORT|CRED_OP_DELETE + * @param requestParams: json string contains group of osAccountId|deviceId|serviceType|acquireType|flag + * @param returnData: json string contains group of result|publicKey + * + * @return When the ipc call is successful, it returns HC_SUCCESS. + * Otherwise, it returns other values. + */ +DEVICE_AUTH_API_PUBLIC int32_t ProcessCredential( + int32_t operationCode, const char *requestParams, char **returnData); + +/** + * @brief Start to auth device. + * + * This API is used to start to auth device. + * + * @param requestId: id of a request + * @param authParams: json string contains group of osAccountId|deviceId|serviceType|acquireType|pinCode + * @param callbak: callback object + * + * @return When the ipc call is successful, it returns HC_SUCCESS. + * Otherwise, it returns other values. + */ +DEVICE_AUTH_API_PUBLIC int32_t StartAuthDevice( + int64_t requestId, const char *authParams, const DeviceAuthCallback *callbak); + +/** + * @brief Process auth device data. + * + * This API is used to process auth device data. + * + * @param requestId: id of a request + * @param authParams: json string contains group of osAccountId|data + * @param callbak: callback object + * + * @return When the ipc call is successful, it returns HC_SUCCESS. + * Otherwise, it returns other values. + */ +DEVICE_AUTH_API_PUBLIC int32_t ProcessAuthDevice( + int64_t requestId, const char *authParams, const DeviceAuthCallback *callbak); + +/** + * @brief Cancle auth device request. + * + * This API is used to cancle auth device request. + * + * @param requestId: id of a request + * @param authParams: json string contains osAccountId or NULL + * + * @return When the ipc call is successful, it returns HC_SUCCESS. + * Otherwise, it returns other values. + */ +DEVICE_AUTH_API_PUBLIC int32_t CancelAuthRequest(int64_t requestId, const char *authParams); + /** * @brief Initialize device auth service. * diff --git a/interfaces/inner_api/device_auth_defines.h b/interfaces/inner_api/device_auth_defines.h index e5b675e6..00433181 100644 --- a/interfaces/inner_api/device_auth_defines.h +++ b/interfaces/inner_api/device_auth_defines.h @@ -96,6 +96,7 @@ enum { HC_ERR_GENERATE_RANDOM = 0x00004011, // 16401 HC_ERR_STATUS = 0x00004012, // 16402 HC_ERR_STEP = 0x00004013, // 16403 + HC_ERR_IDENTITY_DUPLICATED = 0x00004014, // 16404 /* error code for group , 0x00005000 ~ 0x00005FFF */ HC_ERR_ACCESS_DENIED = 0x00005001, // 20481 diff --git a/services/BUILD.gn b/services/BUILD.gn index 8f44248d..a3d1f3fb 100644 --- a/services/BUILD.gn +++ b/services/BUILD.gn @@ -34,6 +34,10 @@ if (os_level == "mini" || os_level == "small") { sources = deviceauth_files defines = [ "HILOG_ENABLE" ] defines += deviceauth_defines + + sources += identity_manager_files + include_dirs += identity_manager_inc + deps = [ "${deps_adapter_path}:${hal_module_name}", "//build/lite/config/component/cJSON:cjson_shared", @@ -199,6 +203,9 @@ if (os_level == "mini" || os_level == "small") { ] } + sources += identity_manager_files + include_dirs += identity_manager_inc + branch_protector_ret = "pac_ret" sanitize = { cfi = true diff --git a/services/creds_manager/inc/creds_manager.h b/services/creds_manager/inc/creds_manager.h index 41b7e428..62956b4f 100644 --- a/services/creds_manager/inc/creds_manager.h +++ b/services/creds_manager/inc/creds_manager.h @@ -16,7 +16,7 @@ #ifndef CREDS_MANAGER_H #define CREDS_MANAGER_H -#include "creds_manager_defines.h" +#include "identity_manager.h" #include "json_utils.h" #ifdef __cplusplus @@ -26,11 +26,11 @@ extern "C" { int32_t AddCertInfoToJson(const CertInfo *certInfo, CJson *out); int32_t GetCredInfosByPeerIdentity(const CJson *in, IdentityInfoVec *vec); int32_t GetCredInfoByPeerUrl(const CJson *in, const Uint8Buff *presharedUrl, IdentityInfo **returnInfo); -int32_t GetSharedSecretByUrl(const CJson *in, const Uint8Buff *presharedUrl, ProtocolAlgType protocolType, - Uint8Buff *sharedSecret); +int32_t GetSharedSecretByUrl( + const CJson *in, const Uint8Buff *presharedUrl, ProtocolAlgType protocolType, Uint8Buff *sharedSecret); int32_t GetCredInfoByPeerCert(const CJson *in, const CertInfo *certInfo, IdentityInfo **returnInfo); -int32_t GetSharedSecretByPeerCert(const CJson *in, const CertInfo *peerCertInfo, ProtocolAlgType protocolType, - Uint8Buff *sharedSecret); +int32_t GetSharedSecretByPeerCert( + const CJson *in, const CertInfo *peerCertInfo, ProtocolAlgType protocolType, Uint8Buff *sharedSecret); #ifdef __cplusplus } diff --git a/services/creds_manager/src/creds_manager.c b/services/creds_manager/src/creds_manager.c index 32344783..77d74016 100644 --- a/services/creds_manager/src/creds_manager.c +++ b/services/creds_manager/src/creds_manager.c @@ -15,790 +15,118 @@ #include "creds_manager.h" -#include "account_auth_plugin_proxy.h" -#include "account_module_defines.h" -#include "account_related_creds_manager.h" -#include "account_related_group_auth.h" -#include "alg_defs.h" -#include "alg_loader.h" -#include "creds_operation_utils.h" -#include "das_task_common.h" -#include "data_manager.h" -#include "group_auth_data_operation.h" -#include "group_operation_common.h" #include "hc_log.h" -#include "hc_types.h" -#include "securec.h" -static int32_t GetAccountRelatedCandidateGroups(int32_t osAccountId, const CJson *in, bool isDeviceLevel, - GroupEntryVec *vec) +static bool IsDirectAuth(const CJson *context) { - BaseGroupAuth *groupAuth = GetAccountRelatedGroupAuth(); - if (groupAuth == NULL) { - return HC_ERR_NULL_PTR; - } - QueryGroupParams queryParams = InitQueryGroupParams(); - if (!isDeviceLevel) { - queryParams.groupVisibility = GROUP_VISIBILITY_PUBLIC; - } - ((AccountRelatedGroupAuth *)groupAuth)->getAccountCandidateGroup(osAccountId, in, &queryParams, vec); - // All return success, only notify the plugin. - if (HasAccountAuthPlugin() == HC_SUCCESS && vec->size(vec) == 0) { - CJson *input = CreateJson(); - if (input == NULL) { - return HC_SUCCESS; - } - CJson *output = CreateJson(); - if (output == NULL) { - FreeJson(input); - return HC_SUCCESS; - } - int32_t ret = ExcuteCredMgrCmd(osAccountId, QUERY_SELF_CREDENTIAL_INFO, input, output); - if (ret != HC_SUCCESS) { - LOGE("Account cred is empty."); - } - FreeJson(input); - FreeJson(output); - } - return HC_SUCCESS; + bool isDirectAuth = false; + (void)GetBoolFromJson(context, FIELD_IS_DIRECT_AUTH, &isDirectAuth); + return isDirectAuth; } -static int32_t GetAccountUnrelatedCandidateGroups(int32_t osAccountId, bool isDeviceLevel, GroupEntryVec *vec) +static bool IsDeviceLevelAuth(const CJson *context) { - QueryGroupParams queryParams = InitQueryGroupParams(); - queryParams.groupType = PEER_TO_PEER_GROUP; - if (!isDeviceLevel) { - queryParams.groupVisibility = GROUP_VISIBILITY_PUBLIC; - } - return QueryGroups(osAccountId, &queryParams, vec); + bool isDeviceLevel = false; + (void)GetBoolFromJson(context, FIELD_IS_DEVICE_LEVEL, &isDeviceLevel); + return isDeviceLevel; } -static bool IsP2pAuthTokenExist(const TrustedDeviceEntry *deviceEntry) +static bool IsPinAuth(const CJson *context, const Uint8Buff *presharedUrl) { - Uint8Buff pkgNameBuff = { (uint8_t *)GROUP_MANAGER_PACKAGE_NAME, strlen(GROUP_MANAGER_PACKAGE_NAME) }; - - const char *serviceType = StringGet(&deviceEntry->serviceType); - Uint8Buff serviceTypeBuff = { (uint8_t *)serviceType, strlen(serviceType) }; - - const char *peerAuthId = StringGet(&deviceEntry->authId); - Uint8Buff peerAuthIdBuff = { (uint8_t *)peerAuthId, strlen(peerAuthId) }; - - uint8_t keyAliasVal[ISO_KEY_ALIAS_LEN] = { 0 }; - Uint8Buff keyAlias = { keyAliasVal, ISO_KEY_ALIAS_LEN }; - int32_t ret = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, KEY_ALIAS_AUTH_TOKEN, &peerAuthIdBuff, &keyAlias); - if (ret != HC_SUCCESS) { - LOGE("Failed to generate key alias!"); - return false; + const char *pinCode = GetStringFromJson(context, FIELD_PIN_CODE); + if (pinCode != NULL) { + return true; } - ret = GetLoaderInstance()->checkKeyExist(&keyAlias); - if (ret != HC_SUCCESS) { - LOGE("auth token not exist!"); - return false; - } - return true; -} - -static int32_t GetAccountUnrelatedIdentityInfo(int32_t osAccountId, const char *groupId, - const char *deviceId, bool isUdid, IdentityInfo *info) -{ - TrustedDeviceEntry *deviceEntry = CreateDeviceEntry(); - if (deviceEntry == NULL) { - LOGE("Failed to create deviceEntry!"); - return HC_ERR_ALLOC_MEMORY; - } - int32_t ret = GaGetTrustedDeviceEntryById(osAccountId, deviceId, isUdid, groupId, deviceEntry); - if (ret != HC_SUCCESS) { - LOGE("Failed to get device entry!"); - DestroyDeviceEntry(deviceEntry); - return ret; - } - - int32_t keyType = IsP2pAuthTokenExist(deviceEntry) ? KEY_TYPE_SYM : KEY_TYPE_ASYM; - DestroyDeviceEntry(deviceEntry); - ret = GetIdentityInfoByType(keyType, TRUST_TYPE_P2P, groupId, info); - if (ret != HC_SUCCESS) { - LOGE("Failed to get p2p identity by key type!"); - } - return ret; -} - -static int32_t GetIdentityInfo(int32_t osAccountId, const TrustedGroupEntry *groupEntry, - const char *deviceId, bool isUdid, IdentityInfo **returnInfo) -{ - IdentityInfo *info = CreateIdentityInfo(); - if (info == NULL) { - LOGE("Failed to create identity info!"); - return HC_ERR_ALLOC_MEMORY; - } - int32_t ret; - const char *groupId = StringGet(&groupEntry->id); - if (groupEntry->type == PEER_TO_PEER_GROUP) { - ret = GetAccountUnrelatedIdentityInfo(osAccountId, groupId, deviceId, isUdid, info); - } else { - ret = GetAccountRelatedCredInfo(osAccountId, groupId, deviceId, isUdid, info); - } - if (ret != HC_SUCCESS) { - LOGE("Failed to get identity info!"); - DestroyIdentityInfo(info); - return ret; - } - *returnInfo = info; - return HC_SUCCESS; -} - -static bool IsDeviceInGroup(int32_t osAccountId, int32_t groupType, const char *deviceId, const char *groupId, - bool isUdid) -{ - if (isUdid) { - return GaIsDeviceInGroup(groupType, osAccountId, deviceId, NULL, groupId); - } else { - return GaIsDeviceInGroup(groupType, osAccountId, NULL, deviceId, groupId); - } -} - -static void AddNoPseudonymIdentityInfo(int32_t osAccountId, const TrustedGroupEntry *groupEntry, const char *deviceId, - bool isUdid, IdentityInfoVec *identityInfoVec) -{ - IdentityInfo *info = NULL; - if (GetIdentityInfo(osAccountId, groupEntry, deviceId, isUdid, &info) != HC_SUCCESS) { - return; - } - info->proof.certInfo.isPseudonym = false; - identityInfoVec->pushBack(identityInfoVec, (const IdentityInfo **)&info); -} - -static int32_t GetIdentityInfos(int32_t osAccountId, const CJson *in, const GroupEntryVec *groupEntryVec, - IdentityInfoVec *identityInfoVec) -{ - const char *pkgName = GetStringFromJson(in, FIELD_SERVICE_PKG_NAME); - if (pkgName == NULL) { - LOGE("Failed to get service package name!"); - return HC_ERR_JSON_GET; - } - bool isUdid = false; - const char *deviceId = GetPeerDevIdFromJson(in, &isUdid); - if (deviceId == NULL) { - LOGE("Failed to get peer device id!"); - return HC_ERR_JSON_GET; - } - uint32_t index; - TrustedGroupEntry **ptr = NULL; - FOR_EACH_HC_VECTOR(*groupEntryVec, index, ptr) { - const TrustedGroupEntry *groupEntry = (TrustedGroupEntry *)(*ptr); - const char *groupId = StringGet(&(groupEntry->id)); - if (groupId == NULL) { - continue; - } - if (!GaIsGroupAccessible(osAccountId, groupId, pkgName)) { - continue; - } - if (!IsDeviceInGroup(osAccountId, groupEntry->type, deviceId, groupId, isUdid)) { - continue; - } - IdentityInfo *info = NULL; - if (GetIdentityInfo(osAccountId, groupEntry, deviceId, isUdid, &info) != HC_SUCCESS) { - continue; - } - if (info->proofType == CERTIFICATED) { - info->proof.certInfo.isPseudonym = true; - } - identityInfoVec->pushBack(identityInfoVec, (const IdentityInfo **)&info); - if (info->proofType == CERTIFICATED) { - AddNoPseudonymIdentityInfo(osAccountId, groupEntry, deviceId, isUdid, identityInfoVec); - } - } - LOGI("The identity info size is: %u", identityInfoVec->size(identityInfoVec)); - return HC_SUCCESS; -} - -static int32_t GetCredInfosForPinType(const CJson *in, IdentityInfoVec *identityInfoVec) -{ - IdentityInfo *info = CreateIdentityInfo(); - if (info == NULL) { - LOGE("Failed to create identity info!"); - return HC_ERR_ALLOC_MEMORY; - } - int32_t ret = GetIdentityInfoForPinType(in, info); - if (ret != HC_SUCCESS) { - LOGE("Failed to get credential info for pin!"); - DestroyIdentityInfo(info); - return ret; - } - identityInfoVec->pushBack(identityInfoVec, (const IdentityInfo **)&info); - return HC_SUCCESS; -} - -static int32_t CheckAndGetP2pCredInfo(const CJson *in, const CJson *urlJson, IdentityInfo *info) -{ - int32_t osAccountId = INVALID_OS_ACCOUNT; - if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { - LOGE("Failed to get osAccountId!"); - return HC_ERR_JSON_GET; - } - const char *groupId = GetStringFromJson(urlJson, FIELD_GROUP_ID); - if (groupId == NULL) { - LOGE("Failed to get groupId!"); - return HC_ERR_JSON_GET; - } - int32_t ret = CheckGroupExist(osAccountId, groupId); - if (ret != HC_SUCCESS) { - LOGE("group not exist!"); - return ret; - } - TrustedDeviceEntry *deviceEntry = CreateDeviceEntry(); - if (deviceEntry == NULL) { - LOGE("Failed to create device entry!"); - return HC_ERR_ALLOC_MEMORY; - } - ret = GetPeerDeviceEntry(osAccountId, in, groupId, deviceEntry); - DestroyDeviceEntry(deviceEntry); - if (ret != HC_SUCCESS) { - LOGE("peer device not found!"); - return ret; - } - int32_t keyType = 0; - if (GetIntFromJson(urlJson, PRESHARED_URL_KEY_TYPE, &keyType) != HC_SUCCESS) { - LOGE("Failed to get key type!"); - return HC_ERR_JSON_GET; - } - ret = GetIdentityInfoByType(keyType, TRUST_TYPE_P2P, groupId, info); - if (ret != HC_SUCCESS) { - LOGE("Failed to get p2p identity info by key type!"); - } - return ret; -} - -static int32_t GetCredInfoByPeerUrlInner(const CJson *in, const Uint8Buff *presharedUrl, IdentityInfo *info) -{ CJson *urlJson = CreateJsonFromString((const char *)presharedUrl->val); if (urlJson == NULL) { LOGE("Failed to create url json!"); - return HC_ERR_JSON_CREATE; + return false; } + int32_t keyType = 0; + if (GetIntFromJson(urlJson, PRESHARED_URL_KEY_TYPE, &keyType) != HC_SUCCESS) { + LOGE("Failed to get trust type!"); + FreeJson(urlJson); + return false; + } + int32_t trustType = 0; if (GetIntFromJson(urlJson, PRESHARED_URL_TRUST_TYPE, &trustType) != HC_SUCCESS) { LOGE("Failed to get trust type!"); FreeJson(urlJson); - return HC_ERR_JSON_GET; - } - int32_t ret; - switch (trustType) { - case TRUST_TYPE_PIN: - ret = GetIdentityInfoForPinType(in, info); - break; - case TRUST_TYPE_UID: - ret = GetAccountSymCredInfoByPeerUrl(in, urlJson, info); - break; - case TRUST_TYPE_P2P: - ret = CheckAndGetP2pCredInfo(in, urlJson, info); - break; - default: - LOGE("Invalid trust type!"); - ret = HC_ERR_INVALID_PARAMS; - break; + return false; } FreeJson(urlJson); - return ret; + + return (keyType == KEY_TYPE_SYM) && (trustType == TRUST_TYPE_PIN); } -static int32_t GetSharedSecretForPinInPake(const CJson *in, Uint8Buff *sharedSecret) +static const AuthIdentity *getAuthIdentity(const CJson *in, const Uint8Buff *presharedUrl) { - const char *pinCode = GetStringFromJson(in, FIELD_PIN_CODE); - if (pinCode == NULL) { - LOGE("Failed to get pinCode!"); - return HC_ERR_JSON_GET; - } - uint32_t pinLen = strlen(pinCode); - if (pinLen < PIN_CODE_LEN_SHORT) { - LOGE("Invalid pin code len!"); - return HC_ERR_INVALID_LEN; - } - sharedSecret->val = (uint8_t *)HcMalloc(pinLen, 0); - if (sharedSecret->val == NULL) { - LOGE("Failed to alloc sharedSecret memory!"); - return HC_ERR_ALLOC_MEMORY; - } - if (memcpy_s(sharedSecret->val, pinLen, pinCode, pinLen) != HC_SUCCESS) { - LOGE("Failed to memcpy pinCode!"); - FreeBuffData(sharedSecret); - return HC_ERR_MEMORY_COPY; - } - sharedSecret->length = pinLen; - return HC_SUCCESS; -} + AuthIdentityType identityType = AUTH_IDENTITY_TYPE_INVALID; -static int32_t GenerateKeyAliasInIso(const CJson *in, const char *groupId, uint8_t *keyAlias, - uint32_t keyAliasLen) -{ - int32_t osAccountId = INVALID_OS_ACCOUNT; - if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { - LOGE("Failed to get osAccountId!"); - return HC_ERR_JSON_GET; - } - TrustedDeviceEntry *deviceEntry = CreateDeviceEntry(); - if (deviceEntry == NULL) { - LOGE("Failed to create device entry!"); - return HC_ERR_ALLOC_MEMORY; - } - int32_t ret = GetPeerDeviceEntry(osAccountId, in, groupId, deviceEntry); - if (ret != HC_SUCCESS) { - LOGE("Failed to get peer device entry!"); - DestroyDeviceEntry(deviceEntry); - return ret; - } - Uint8Buff pkgNameBuff = { (uint8_t *)GROUP_MANAGER_PACKAGE_NAME, (uint32_t)strlen(GROUP_MANAGER_PACKAGE_NAME) }; - const char *serviceType = StringGet(&deviceEntry->serviceType); - Uint8Buff serviceTypeBuff = { (uint8_t *)serviceType, (uint32_t)strlen(serviceType) }; - const char *peerAuthId = StringGet(&deviceEntry->authId); - Uint8Buff peerAuthIdBuff = { (uint8_t *)peerAuthId, (uint32_t)strlen(peerAuthId) }; - Uint8Buff outKeyAlias = { keyAlias, keyAliasLen }; - ret = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, KEY_ALIAS_AUTH_TOKEN, &peerAuthIdBuff, - &outKeyAlias); - DestroyDeviceEntry(deviceEntry); - return ret; -} - -static int32_t AuthGeneratePsk(const CJson *in, const char *groupId, const Uint8Buff *seed, - Uint8Buff *sharedSecret) -{ - uint8_t keyAlias[ISO_KEY_ALIAS_LEN] = { 0 }; - int ret = GenerateKeyAliasInIso(in, groupId, keyAlias, sizeof(keyAlias)); - if (ret != HC_SUCCESS) { - LOGE("Failed to generate key alias in iso!"); - return ret; - } - Uint8Buff keyAliasBuf = { keyAlias, sizeof(keyAlias) }; - return GetLoaderInstance()->computeHmac(&keyAliasBuf, seed, sharedSecret, true); -} - -static int32_t AuthGeneratePskUsePin(const Uint8Buff *seed, const char *pinCode, Uint8Buff *sharedSecret) -{ - Uint8Buff messageBuf = { (uint8_t *)pinCode, (uint32_t)strlen(pinCode) }; - uint8_t hash[SHA256_LEN] = { 0 }; - Uint8Buff hashBuf = { hash, sizeof(hash) }; - int ret = GetLoaderInstance()->sha256(&messageBuf, &hashBuf); - if (ret != HC_SUCCESS) { - LOGE("sha256 failed, ret:%d", ret); - return ret; - } - return GetLoaderInstance()->computeHmac(&hashBuf, seed, sharedSecret, false); -} - -#ifdef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK -static bool CheckPinLenForStandardIso(const CJson *in, const char *pinCode) -{ - int32_t protocolExpandVal = INVALID_PROTOCOL_EXPAND_VALUE; - (void)GetIntFromJson(in, FIELD_PROTOCOL_EXPAND, &protocolExpandVal); - if (protocolExpandVal != LITE_PROTOCOL_STANDARD_MODE) { - LOGI("not standard iso, no need to check."); - return true; - } - return HcStrlen(pinCode) >= PIN_CODE_LEN_LONG; -} -#endif - -static int32_t GetSharedSecretForPinInIso(const CJson *in, Uint8Buff *sharedSecret) -{ - const char *pinCode = GetStringFromJson(in, FIELD_PIN_CODE); - if (pinCode == NULL) { - LOGE("Failed to get pinCode!"); - return HC_ERR_JSON_GET; - } - if (HcStrlen(pinCode) < PIN_CODE_LEN_SHORT) { - LOGE("Pin code is too short!"); - return HC_ERR_INVALID_LEN; - } -#ifdef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK - if (!CheckPinLenForStandardIso(in, pinCode)) { - LOGE("Invalid pin code len!"); - return HC_ERR_INVALID_LEN; - } -#endif - uint8_t *seedVal = (uint8_t *)HcMalloc(SEED_LEN, 0); - if (seedVal == NULL) { - LOGE("Failed to alloc seed memory!"); - return HC_ERR_ALLOC_MEMORY; - } - Uint8Buff seedBuff = { seedVal, SEED_LEN }; - int32_t ret = GetByteFromJson(in, FIELD_SEED, seedBuff.val, seedBuff.length); - if (ret != HC_SUCCESS) { - LOGE("Failed to get seed!"); - HcFree(seedVal); - return HC_ERR_JSON_GET; - } - uint8_t *pskVal = (uint8_t *)HcMalloc(ISO_PSK_LEN, 0); - if (pskVal == NULL) { - LOGE("Failed to alloc psk memory!"); - HcFree(seedVal); - return HC_ERR_ALLOC_MEMORY; - } - sharedSecret->val = pskVal; - sharedSecret->length = ISO_PSK_LEN; - ret = AuthGeneratePskUsePin(&seedBuff, pinCode, sharedSecret); - HcFree(seedVal); - if (ret != HC_SUCCESS) { - LOGE("Failed to generate psk use pin!"); - FreeBuffData(sharedSecret); - } - return ret; -} - -static int32_t GetSharedSecretForP2pInIso(const CJson *in, const char *groupId, Uint8Buff *sharedSecret) -{ - uint8_t *seedVal = (uint8_t *)HcMalloc(SEED_LEN, 0); - if (seedVal == NULL) { - LOGE("Failed to alloc memory for seed!"); - return HC_ERR_ALLOC_MEMORY; - } - Uint8Buff seedBuff = { seedVal, SEED_LEN }; - int32_t ret = GetByteFromJson(in, FIELD_SEED, seedBuff.val, seedBuff.length); - if (ret != HC_SUCCESS) { - LOGE("Failed to get seed!"); - HcFree(seedVal); - return HC_ERR_JSON_GET; - } - uint8_t *pskVal = (uint8_t *)HcMalloc(ISO_PSK_LEN, 0); - if (pskVal == NULL) { - LOGE("Failed to alloc memory for psk!"); - HcFree(seedVal); - return HC_ERR_ALLOC_MEMORY; - } - sharedSecret->val = pskVal; - sharedSecret->length = ISO_PSK_LEN; - ret = AuthGeneratePsk(in, groupId, &seedBuff, sharedSecret); - HcFree(seedVal); - if (ret != HC_SUCCESS) { - LOGE("Failed to generate psk!"); - FreeBuffData(sharedSecret); - } - return ret; -} - -static int32_t GetSelfAuthIdAndUserType(int32_t osAccountId, const char *groupId, Uint8Buff *authIdBuff, - int32_t *userType) -{ - TrustedDeviceEntry *deviceEntry = CreateDeviceEntry(); - if (deviceEntry == NULL) { - LOGE("Failed to create device entry!"); - return HC_ERR_ALLOC_MEMORY; - } - int32_t ret = GetSelfDeviceEntry(osAccountId, groupId, deviceEntry); - if (ret != HC_SUCCESS) { - LOGE("Failed to get self device entry!"); - DestroyDeviceEntry(deviceEntry); - return ret; - } - const char *selfAuthId = StringGet(&deviceEntry->authId); - uint32_t authIdLen = strlen(selfAuthId); - authIdBuff->val = (uint8_t *)HcMalloc(authIdLen + 1, 0); - if (authIdBuff->val == NULL) { - LOGE("Failed to alloc memory for authId!"); - DestroyDeviceEntry(deviceEntry); - return HC_ERR_ALLOC_MEMORY; - } - if (memcpy_s(authIdBuff->val, authIdLen + 1, selfAuthId, authIdLen) != EOK) { - LOGE("Failed to copy authId!"); - HcFree(authIdBuff->val); - authIdBuff->val = NULL; - DestroyDeviceEntry(deviceEntry); - return HC_ERR_MEMORY_COPY; - } - authIdBuff->length = authIdLen; - *userType = deviceEntry->devType; - DestroyDeviceEntry(deviceEntry); - return HC_SUCCESS; -} - -static int32_t ComputeAndSavePsk(int32_t osAccountId, const char *groupId, const TrustedDeviceEntry *peerDeviceEntry, - const Uint8Buff *sharedKeyAlias) -{ - Uint8Buff selfAuthIdBuff = { NULL, 0 }; - int32_t selfUserType = 0; - int32_t ret = GetSelfAuthIdAndUserType(osAccountId, groupId, &selfAuthIdBuff, &selfUserType); - if (ret != HC_SUCCESS) { - LOGE("Failed to get self auth id and user type!"); - return ret; - } - - Uint8Buff pkgNameBuff = { (uint8_t *)GROUP_MANAGER_PACKAGE_NAME, strlen(GROUP_MANAGER_PACKAGE_NAME) }; - const char *serviceType = StringGet(&peerDeviceEntry->serviceType); - Uint8Buff serviceTypeBuff = { (uint8_t *)serviceType, strlen(serviceType) }; - KeyAliasType keyType = (KeyAliasType)selfUserType; - uint8_t selfKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 }; - Uint8Buff selfKeyAlias = { selfKeyAliasVal, PAKE_KEY_ALIAS_LEN }; - ret = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, keyType, &selfAuthIdBuff, &selfKeyAlias); - HcFree(selfAuthIdBuff.val); - if (ret != HC_SUCCESS) { - LOGE("Failed to generate self key alias!"); - return ret; - } - -#ifdef DEV_AUTH_FUNC_TEST - KeyAliasType keyTypePeer = KEY_ALIAS_LT_KEY_PAIR; -#else - KeyAliasType keyTypePeer = (KeyAliasType)peerDeviceEntry->devType; -#endif - const char *peerAuthId = StringGet(&peerDeviceEntry->authId); - Uint8Buff peerAuthIdBuff = { (uint8_t *)peerAuthId, strlen(peerAuthId) }; - uint8_t peerKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 }; - Uint8Buff peerKeyAlias = { peerKeyAliasVal, PAKE_KEY_ALIAS_LEN }; - ret = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, keyTypePeer, &peerAuthIdBuff, &peerKeyAlias); - if (ret != HC_SUCCESS) { - LOGE("Failed to generate peer key alias!"); - return ret; - } - - ret = GetLoaderInstance()->checkKeyExist(&selfKeyAlias); - if (ret != HC_SUCCESS) { - LOGE("self auth keyPair not exist!"); - return ret; - } - ret = GetLoaderInstance()->checkKeyExist(&peerKeyAlias); - if (ret != HC_SUCCESS) { - LOGE("peer auth pubKey not exist!"); - return ret; - } - - KeyBuff selfKeyAliasBuff = { selfKeyAlias.val, selfKeyAlias.length, true }; - KeyBuff peerKeyAliasBuff = { peerKeyAlias.val, peerKeyAlias.length, true }; - return GetLoaderInstance()->agreeSharedSecretWithStorage(&selfKeyAliasBuff, &peerKeyAliasBuff, ED25519, - PAKE_PSK_LEN, sharedKeyAlias); -} - -static int32_t GeneratePskAliasAndCheckExist(const CJson *in, const char *groupId, Uint8Buff *pskKeyAlias) -{ - int32_t osAccountId = INVALID_OS_ACCOUNT; - if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { - LOGE("Failed to get osAccountId!"); - return HC_ERR_JSON_GET; - } - TrustedDeviceEntry *deviceEntry = CreateDeviceEntry(); - if (deviceEntry == NULL) { - LOGE("Failed to create device entry!"); - return HC_ERR_ALLOC_MEMORY; - } - int32_t ret = GetPeerDeviceEntry(osAccountId, in, groupId, deviceEntry); - if (ret != HC_SUCCESS) { - LOGE("Failed to get peer device entry!"); - DestroyDeviceEntry(deviceEntry); - return ret; - } - Uint8Buff pkgNameBuff = { (uint8_t *)GROUP_MANAGER_PACKAGE_NAME, strlen(GROUP_MANAGER_PACKAGE_NAME) }; - const char *serviceType = StringGet(&deviceEntry->serviceType); - Uint8Buff serviceTypeBuff = { (uint8_t *)serviceType, strlen(serviceType) }; - const char *peerAuthId = StringGet(&deviceEntry->authId); - Uint8Buff peerAuthIdBuff = { (uint8_t *)peerAuthId, strlen(peerAuthId) }; - ret = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, KEY_ALIAS_PSK, &peerAuthIdBuff, pskKeyAlias); - if (ret != HC_SUCCESS) { - LOGE("Failed to generate psk key alias!"); - DestroyDeviceEntry(deviceEntry); - return ret; - } - LOGI("psk alias: %x %x %x %x****.", pskKeyAlias->val[DEV_AUTH_ZERO], pskKeyAlias->val[DEV_AUTH_ONE], - pskKeyAlias->val[DEV_AUTH_TWO], pskKeyAlias->val[DEV_AUTH_THREE]); - if (GetLoaderInstance()->checkKeyExist(pskKeyAlias) != HC_SUCCESS) { - ret = ComputeAndSavePsk(osAccountId, groupId, deviceEntry, pskKeyAlias); - } - DestroyDeviceEntry(deviceEntry); - return ret; -} - -static void UpperToLowercase(Uint8Buff *hex) -{ - for (uint32_t i = 0; i < hex->length; i++) { - if (hex->val[i] >= 'A' && hex->val[i] <= 'F') { - hex->val[i] += ASCII_CASE_DIFFERENCE_VALUE; + if (IsPinAuth(in, presharedUrl)) { + identityType = AUTH_IDENTITY_TYPE_PIN; + } else { + if (IsDirectAuth(in)) { + identityType = AUTH_IDENTITY_TYPE_P2P; + } else { + identityType = AUTH_IDENTITY_TYPE_GROUP; } } + LOGD("AuthIdentityType: %d", identityType); + + if (identityType == AUTH_IDENTITY_TYPE_INVALID) { + LOGE("invalid AuthIdentityType !"); + return NULL; + } + return GetAuthIdentityByType(identityType); } -static int32_t ConvertPsk(const Uint8Buff *srcPsk, Uint8Buff *sharedSecret) +int32_t GetCredInfosByPeerIdentity(const CJson *in, IdentityInfoVec *vec) { - uint32_t len = PAKE_PSK_LEN * BYTE_TO_HEX_OPER_LENGTH; - sharedSecret->val = (uint8_t *)HcMalloc(len + 1, 0); - if (sharedSecret->val == NULL) { - LOGE("Failed to alloc memory for sharedSecret!"); - return HC_ERR_ALLOC_MEMORY; - } - - if (ByteToHexString(srcPsk->val, srcPsk->length, (char *)sharedSecret->val, len + 1) != HC_SUCCESS) { - LOGE("Convert psk from byte to hex string failed!"); - HcFree(sharedSecret->val); - return HC_ERR_CONVERT_FAILED; - } - sharedSecret->length = len; - (void)UpperToLowercase(sharedSecret); - return HC_SUCCESS; -} - -static int32_t GetSharedSecretForP2pInPake(const CJson *in, const char *groupId, Uint8Buff *sharedSecret) -{ - uint8_t pskKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 }; - Uint8Buff pskKeyAlias = { pskKeyAliasVal, PAKE_KEY_ALIAS_LEN }; - int32_t ret = GeneratePskAliasAndCheckExist(in, groupId, &pskKeyAlias); - if (ret != HC_SUCCESS) { - LOGE("Failed to generate key alias for psk!"); - return ret; - } - uint8_t *pskVal = (uint8_t *)HcMalloc(PAKE_PSK_LEN, 0); - if (pskVal == NULL) { - LOGE("Failed to alloc memory for psk!"); - return HC_ERR_ALLOC_MEMORY; - } - Uint8Buff pskBuff = { pskVal, PAKE_PSK_LEN }; - uint8_t *nonceVal = (uint8_t *)HcMalloc(PAKE_NONCE_LEN, 0); - if (nonceVal == NULL) { - LOGE("Failed to alloc memory for nonce!"); - HcFree(pskVal); - return HC_ERR_ALLOC_MEMORY; - } - Uint8Buff nonceBuff = { nonceVal, PAKE_NONCE_LEN }; - ret = GetByteFromJson(in, FIELD_NONCE, nonceBuff.val, nonceBuff.length); - if (ret != HC_SUCCESS) { - LOGE("Failed to get nonce!"); - HcFree(pskVal); - HcFree(nonceVal); - return HC_ERR_JSON_GET; - } - Uint8Buff keyInfo = { (uint8_t *)TMP_AUTH_KEY_FACTOR, strlen(TMP_AUTH_KEY_FACTOR) }; - ret = GetLoaderInstance()->computeHkdf(&pskKeyAlias, &nonceBuff, &keyInfo, &pskBuff, true); - HcFree(nonceVal); - if (ret != HC_SUCCESS) { - LOGE("Failed to compute hkdf for psk!"); - HcFree(pskVal); - return ret; - } - - ret = ConvertPsk(&pskBuff, sharedSecret); - HcFree(pskVal); - if (ret != HC_SUCCESS) { - LOGE("Failed to convert psk!"); - } - return ret; -} - -static int32_t GetSharedSecretForPin(const CJson *in, ProtocolAlgType protocolType, Uint8Buff *sharedSecret) -{ - int32_t ret; - if (protocolType == ALG_ISO) { - ret = GetSharedSecretForPinInIso(in, sharedSecret); - LOGI("get shared secret for pin in iso result: %d", ret); - } else { - ret = GetSharedSecretForPinInPake(in, sharedSecret); - LOGI("get shared secret for pin in pake result: %d", ret); - } - return ret; -} - -static int32_t GetSharedSecretForP2p(const CJson *in, const CJson *urlJson, ProtocolAlgType protocolType, - Uint8Buff *sharedSecret) -{ - const char *groupId = GetStringFromJson(urlJson, FIELD_GROUP_ID); - if (groupId == NULL) { - LOGE("Failed to get groupId!"); - return HC_ERR_JSON_GET; - } - int32_t ret; - if (protocolType == ALG_ISO) { - ret = GetSharedSecretForP2pInIso(in, groupId, sharedSecret); - LOGI("get shared secret for p2p in iso result: %d", ret); - } else { - ret = GetSharedSecretForP2pInPake(in, groupId, sharedSecret); - LOGI("get shared secret for p2p in pake result: %d", ret); - } - return ret; -} - -static void GetGroupInfoByGroupId(int32_t osAccountId, const char *groupId, GroupEntryVec *groupEntryVec) -{ - QueryGroupParams queryParams = InitQueryGroupParams(); - queryParams.groupId = groupId; - int32_t ret = QueryGroups(osAccountId, &queryParams, groupEntryVec); - if (ret != HC_SUCCESS) { - LOGE("Failed to query groups for groupId: %s!", groupId); - } -} - -static void GetCandidateGroups(int32_t osAccountId, const CJson *in, GroupEntryVec *groupEntryVec) -{ - bool isDeviceLevel = false; - (void)GetBoolFromJson(in, FIELD_IS_DEVICE_LEVEL, &isDeviceLevel); - - int32_t ret = GetAccountRelatedCandidateGroups(osAccountId, in, isDeviceLevel, groupEntryVec); - if (ret != HC_SUCCESS) { - LOGE("Failed to get account related groups!"); - } - - ret = GetAccountUnrelatedCandidateGroups(osAccountId, isDeviceLevel, groupEntryVec); - if (ret != HC_SUCCESS) { - LOGE("Failed to get p2p groups!"); - } -} - -static int32_t GetCredInfosForGroups(const CJson *in, IdentityInfoVec *identityInfoVec) -{ - int32_t osAccountId = INVALID_OS_ACCOUNT; - if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { - LOGE("Failed to get osAccountId!"); - return HC_ERR_JSON_GET; - } - const char *groupId = GetStringFromJson(in, FIELD_GROUP_ID); - if (groupId == NULL) { - groupId = GetStringFromJson(in, FIELD_SERVICE_TYPE); - } - - GroupEntryVec groupEntryVec = CreateGroupEntryVec(); - if (groupId == NULL) { - GetCandidateGroups(osAccountId, in, &groupEntryVec); - } else { - GetGroupInfoByGroupId(osAccountId, groupId, &groupEntryVec); - } - - if (groupEntryVec.size(&groupEntryVec) == 0) { - LOGE("No satisfied candidate group!"); - ClearGroupEntryVec(&groupEntryVec); - return HC_ERR_NO_CANDIDATE_GROUP; - } - int32_t ret = GetIdentityInfos(osAccountId, in, &groupEntryVec, identityInfoVec); - ClearGroupEntryVec(&groupEntryVec); - return ret; -} - -int32_t AddCertInfoToJson(const CertInfo *certInfo, CJson *out) -{ - if (certInfo == NULL || out == NULL) { - LOGE("Invalid cert info or out!"); - return HC_ERR_INVALID_PARAMS; - } - if (AddIntToJson(out, FIELD_SIGN_ALG, certInfo->signAlg) != HC_SUCCESS) { - LOGE("add sign alg to json failed!"); - return HC_ERR_JSON_ADD; - } - if (AddStringToJson(out, FIELD_PK_INFO, (const char *)certInfo->pkInfoStr.val) != HC_SUCCESS) { - LOGE("add pk info str to json failed!"); - return HC_ERR_JSON_ADD; - } - if (AddByteToJson(out, FIELD_PK_INFO_SIGNATURE, certInfo->pkInfoSignature.val, - certInfo->pkInfoSignature.length) != HC_SUCCESS) { - LOGE("add pk info sign to json failed!"); - return HC_ERR_JSON_ADD; - } - return HC_SUCCESS; -} - -int32_t GetCredInfosByPeerIdentity(const CJson *in, IdentityInfoVec *identityInfoVec) -{ - if (in == NULL || identityInfoVec == NULL) { + if (in == NULL || vec == NULL) { LOGE("Invalid input params!"); return HC_ERR_INVALID_PARAMS; } + + AuthIdentityType identityType = AUTH_IDENTITY_TYPE_INVALID; const char *pinCode = GetStringFromJson(in, FIELD_PIN_CODE); if (pinCode != NULL) { - return GetCredInfosForPinType(in, identityInfoVec); + identityType = AUTH_IDENTITY_TYPE_PIN; } else { - return GetCredInfosForGroups(in, identityInfoVec); + if (IsDirectAuth(in)) { + identityType = AUTH_IDENTITY_TYPE_P2P; + } else { + identityType = AUTH_IDENTITY_TYPE_GROUP; + } } + if (identityType == AUTH_IDENTITY_TYPE_INVALID) { + LOGE("invalid AuthIdentityType !"); + return HC_ERR_INVALID_PARAMS; + } + + LOGD("AuthIdentityType: %d", identityType); + const AuthIdentity *authIdentity = GetAuthIdentityByType(identityType); + if (authIdentity == NULL) { + LOGI("getAuthIdentity failed."); + return HC_ERR_INVALID_PARAMS; + } + + int32_t ret = authIdentity->getCredInfosByPeerIdentity(in, vec); + /* Device level auth also need to try auth with the direct auth identityInfo */ + if (IsDeviceLevelAuth(in) && identityType == AUTH_IDENTITY_TYPE_GROUP) { + int32_t identityCount = HC_VECTOR_SIZE(vec); + authIdentity = GetAuthIdentityByType(AUTH_IDENTITY_TYPE_P2P); + if (authIdentity != NULL) { + int32_t res = authIdentity->getCredInfosByPeerIdentity(in, vec); + if (res != HC_SUCCESS && (identityCount > 0)) { + return HC_SUCCESS; + } + return res; + } + } + return ret; } int32_t GetCredInfoByPeerUrl(const CJson *in, const Uint8Buff *presharedUrl, IdentityInfo **returnInfo) @@ -807,62 +135,45 @@ int32_t GetCredInfoByPeerUrl(const CJson *in, const Uint8Buff *presharedUrl, Ide LOGE("Invalid input params!"); return HC_ERR_INVALID_PARAMS; } - IdentityInfo *info = CreateIdentityInfo(); - if (info == NULL) { - LOGE("Failed to create identity info!"); - return HC_ERR_ALLOC_MEMORY; + + const AuthIdentity *authIdentity = getAuthIdentity(in, presharedUrl); + if (!authIdentity) { + LOGI("getAuthIdentity failed."); + return HC_ERR_INVALID_PARAMS; } - int32_t ret = GetCredInfoByPeerUrlInner(in, presharedUrl, info); - if (ret != HC_SUCCESS) { - LOGE("Failed to get credential info by peer url!"); - DestroyIdentityInfo(info); - return ret; - } - *returnInfo = info; - return HC_SUCCESS; + + return authIdentity->getCredInfoByPeerUrl(in, presharedUrl, returnInfo); } -int32_t GetSharedSecretByUrl(const CJson *in, const Uint8Buff *presharedUrl, ProtocolAlgType protocolType, - Uint8Buff *sharedSecret) +int32_t GetSharedSecretByUrl( + const CJson *in, const Uint8Buff *presharedUrl, ProtocolAlgType protocolType, Uint8Buff *sharedSecret) { if (in == NULL || presharedUrl == NULL || sharedSecret == NULL) { LOGE("Invalid input params!"); return HC_ERR_INVALID_PARAMS; } - CJson *urlJson = CreateJsonFromString((const char *)presharedUrl->val); - if (urlJson == NULL) { - LOGE("Failed to create url json!"); - return HC_ERR_JSON_CREATE; + +#ifdef DEV_AUTH_FUNC_TEST // Add for coverage test + const AuthIdentity *authIdentityTest = GetAuthIdentityByType(AUTH_IDENTITY_TYPE_P2P); + if (authIdentityTest == NULL) { + return HC_ERR_INVALID_PARAMS; } - int32_t trustType = 0; - if (GetIntFromJson(urlJson, PRESHARED_URL_TRUST_TYPE, &trustType) != HC_SUCCESS) { - LOGE("Failed to get trust type!"); - FreeJson(urlJson); - return HC_ERR_JSON_GET; + authIdentityTest->getSharedSecretByUrl(in, presharedUrl, protocolType, sharedSecret); + + authIdentityTest = GetAuthIdentityByType(AUTH_IDENTITY_TYPE_PIN); + if (authIdentityTest == NULL) { + return HC_ERR_INVALID_PARAMS; } - int32_t ret; - switch (trustType) { - case TRUST_TYPE_PIN: - ret = GetSharedSecretForPin(in, protocolType, sharedSecret); - break; - case TRUST_TYPE_P2P: - ret = GetSharedSecretForP2p(in, urlJson, protocolType, sharedSecret); - break; - case TRUST_TYPE_UID: - if (protocolType != ALG_ISO) { - LOGE("protocol type is not iso, not supported!"); - ret = HC_ERR_INVALID_PARAMS; - } else { - ret = GetAccountSymSharedSecret(in, urlJson, sharedSecret); - } - break; - default: - LOGE("Invalid trust type!"); - ret = HC_ERR_INVALID_PARAMS; - break; + authIdentityTest->getSharedSecretByUrl(in, presharedUrl, protocolType, sharedSecret); +#endif + + const AuthIdentity *authIdentity = getAuthIdentity(in, presharedUrl); + if (!authIdentity) { + LOGI("getAuthIdentity failed."); + return HC_ERR_INVALID_PARAMS; } - FreeJson(urlJson); - return ret; + + return authIdentity->getSharedSecretByUrl(in, presharedUrl, protocolType, sharedSecret); } int32_t GetCredInfoByPeerCert(const CJson *in, const CertInfo *certInfo, IdentityInfo **returnInfo) @@ -871,39 +182,53 @@ int32_t GetCredInfoByPeerCert(const CJson *in, const CertInfo *certInfo, Identit LOGE("Invalid input params!"); return HC_ERR_INVALID_PARAMS; } - int32_t osAccountId = INVALID_OS_ACCOUNT; - if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { - LOGE("Failed to get osAccountId!"); - return HC_ERR_JSON_GET; + +#ifdef DEV_AUTH_FUNC_TEST // Add for coverage test + const AuthIdentity *authIdentityTest = GetAuthIdentityByType(AUTH_IDENTITY_TYPE_P2P); + if (authIdentityTest == NULL) { + return HC_ERR_INVALID_PARAMS; } - int32_t res = GetAccountAsymCredInfo(osAccountId, certInfo, returnInfo); - if (res != HC_SUCCESS) { - LOGE("Failed to get account asym cred info!"); - return res; + authIdentityTest->getCredInfoByPeerCert(in, certInfo, returnInfo); + + authIdentityTest = GetAuthIdentityByType(AUTH_IDENTITY_TYPE_PIN); + if (authIdentityTest == NULL) { + return HC_ERR_INVALID_PARAMS; } - if (certInfo->isPseudonym) { - (*returnInfo)->proof.certInfo.isPseudonym = true; - } else { - (*returnInfo)->proof.certInfo.isPseudonym = false; + authIdentityTest->getCredInfoByPeerCert(in, certInfo, returnInfo); +#endif + + const AuthIdentity *authIdentity = GetAuthIdentityByType(AUTH_IDENTITY_TYPE_GROUP); + if (authIdentity == NULL) { + return HC_ERR_INVALID_PARAMS; } - return HC_SUCCESS; + return authIdentity->getCredInfoByPeerCert(in, certInfo, returnInfo); } -int32_t GetSharedSecretByPeerCert(const CJson *in, const CertInfo *peerCertInfo, ProtocolAlgType protocolType, - Uint8Buff *sharedSecret) +int32_t GetSharedSecretByPeerCert( + const CJson *in, const CertInfo *peerCertInfo, ProtocolAlgType protocolType, Uint8Buff *sharedSecret) { if (in == NULL || peerCertInfo == NULL || sharedSecret == NULL) { LOGE("Invalid input params!"); return HC_ERR_INVALID_PARAMS; } - if (protocolType != ALG_EC_SPEKE) { - LOGE("protocol type is not ec speke, not support!"); + +#ifdef DEV_AUTH_FUNC_TEST // Add for coverage test + const AuthIdentity *authIdentityTest = GetAuthIdentityByType(AUTH_IDENTITY_TYPE_P2P); + if (authIdentityTest == NULL) { return HC_ERR_INVALID_PARAMS; } - int32_t osAccountId = INVALID_OS_ACCOUNT; - if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { - LOGE("Failed to get osAccountId!"); - return HC_ERR_JSON_GET; + authIdentityTest->getSharedSecretByPeerCert(in, peerCertInfo, protocolType, sharedSecret); + + authIdentityTest = GetAuthIdentityByType(AUTH_IDENTITY_TYPE_PIN); + if (authIdentityTest == NULL) { + return HC_ERR_INVALID_PARAMS; } - return GetAccountAsymSharedSecret(osAccountId, peerCertInfo, sharedSecret); + authIdentityTest->getSharedSecretByPeerCert(in, peerCertInfo, protocolType, sharedSecret); +#endif + + const AuthIdentity *authIdentity = GetAuthIdentityByType(AUTH_IDENTITY_TYPE_GROUP); + if (authIdentity == NULL) { + return HC_ERR_INVALID_PARAMS; + } + return authIdentity->getSharedSecretByPeerCert(in, peerCertInfo, protocolType, sharedSecret); } \ No newline at end of file diff --git a/services/creds_manager/src/creds_operation_utils.c b/services/creds_manager/src/creds_operation_utils.c deleted file mode 100644 index a1440aa8..00000000 --- a/services/creds_manager/src/creds_operation_utils.c +++ /dev/null @@ -1,381 +0,0 @@ -/* - * Copyright (C) 2023 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 "creds_operation_utils.h" - -#include "common_defs.h" -#include "creds_manager_defines.h" -#include "device_auth.h" -#include "device_auth_defines.h" -#include "group_auth_data_operation.h" -#include "hc_dev_info.h" -#include "hc_log.h" -#include "hc_types.h" -#include "json_utils.h" -#include "string_util.h" - -IMPLEMENT_HC_VECTOR(ProtocolEntityVec, ProtocolEntity*, 1) -IMPLEMENT_HC_VECTOR(IdentityInfoVec, IdentityInfo*, 1) - -static int32_t SetDlSpekeProtocol(IdentityInfo *info) -{ -#ifdef ENABLE_P2P_BIND_DL_SPEKE - ProtocolEntity *dlSpekeEntity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); - if (dlSpekeEntity == NULL) { - LOGE("Failed to alloc memory for dl speke entity!"); - return HC_ERR_ALLOC_MEMORY; - } - dlSpekeEntity->protocolType = ALG_DL_SPEKE; - dlSpekeEntity->expandProcessCmds = CMD_IMPORT_AUTH_CODE | CMD_ADD_TRUST_DEVICE; - if (info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&dlSpekeEntity) == NULL) { - LOGE("Failed to push dl speke entity!"); - HcFree(dlSpekeEntity); - return HC_ERR_ALLOC_MEMORY; - } - return HC_SUCCESS; -#else - (void)info; - return HC_SUCCESS; -#endif -} - -static int32_t SetIsoProtocol(IdentityInfo *info) -{ -#ifdef ENABLE_P2P_BIND_ISO - ProtocolEntity *isoEntity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); - if (isoEntity == NULL) { - LOGE("Failed to alloc memory for iso entity!"); - return HC_ERR_ALLOC_MEMORY; - } - isoEntity->protocolType = ALG_ISO; - isoEntity->expandProcessCmds = CMD_IMPORT_AUTH_CODE | CMD_ADD_TRUST_DEVICE; - if (info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&isoEntity) == NULL) { - LOGE("Failed to push iso entity!"); - HcFree(isoEntity); - return HC_ERR_ALLOC_MEMORY; - } - return HC_SUCCESS; -#else - (void)info; - return HC_SUCCESS; -#endif -} - -static int32_t SetLiteProtocols(IdentityInfo *info) -{ - int32_t res = SetDlSpekeProtocol(info); - if (res != HC_SUCCESS) { - return res; - } - return SetIsoProtocol(info); -} - -static int32_t SetLiteProtocolsForPinType(const CJson *in, IdentityInfo *info) -{ -#ifndef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK - (void)in; - return SetLiteProtocols(info); -#else - int32_t protocolExpandVal = INVALID_PROTOCOL_EXPAND_VALUE; - (void)GetIntFromJson(in, FIELD_PROTOCOL_EXPAND, &protocolExpandVal); - int32_t res = HC_SUCCESS; - if (protocolExpandVal == LITE_PROTOCOL_STANDARD_MODE || protocolExpandVal == LITE_PROTOCOL_COMPATIBILITY_MODE) { - res = SetLiteProtocols(info); - } - return res; -#endif -} - -static int32_t SetProtocolsForPinType(const CJson *in, IdentityInfo *info) -{ -#ifdef ENABLE_P2P_BIND_EC_SPEKE - ProtocolEntity *ecSpekeEntity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); - if (ecSpekeEntity == NULL) { - LOGE("Failed to alloc memory for ec speke entity!"); - return HC_ERR_ALLOC_MEMORY; - } - ecSpekeEntity->protocolType = ALG_EC_SPEKE; - ecSpekeEntity->expandProcessCmds = CMD_EXCHANGE_PK | CMD_ADD_TRUST_DEVICE; - if (info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&ecSpekeEntity) == NULL) { - LOGE("Failed to push ec speke entity!"); - HcFree(ecSpekeEntity); - return HC_ERR_ALLOC_MEMORY; - } -#endif - - return SetLiteProtocolsForPinType(in, info); -} - -static int32_t SetProtocolsForUidType(IdentityInfo *info) -{ -#ifdef ENABLE_ACCOUNT_AUTH_ISO - ProtocolEntity *entity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); - if (entity == NULL) { - LOGE("Failed to alloc memory for entity!"); - return HC_ERR_ALLOC_MEMORY; - } - entity->protocolType = ALG_ISO; - entity->expandProcessCmds = CMD_ADD_TRUST_DEVICE; - info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&entity); -#else - (void)info; -#endif - - return HC_SUCCESS; -} - -static int32_t SetProtocolsForP2pType(int32_t keyType, IdentityInfo *info) -{ - if (keyType == KEY_TYPE_ASYM) { - #ifdef ENABLE_P2P_AUTH_EC_SPEKE - ProtocolEntity *entity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); - if (entity == NULL) { - LOGE("Failed to alloc memory for entity!"); - return HC_ERR_ALLOC_MEMORY; - } - entity->protocolType = ALG_EC_SPEKE; - info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&entity); - #else - (void)info; - #endif - } else { - #ifdef ENABLE_P2P_AUTH_ISO - ProtocolEntity *entity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); - if (entity == NULL) { - LOGE("Failed to alloc memory for entity!"); - return HC_ERR_ALLOC_MEMORY; - } - entity->protocolType = ALG_ISO; - info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&entity); - #else - (void)info; - #endif - } - - return HC_SUCCESS; -} - -static int32_t SetPreSharedUrlForProof(const char *urlStr, Uint8Buff *preSharedUrl) -{ - uint32_t urlLen = HcStrlen(urlStr); - preSharedUrl->val = (uint8_t *)HcMalloc(urlLen + 1, 0); - if (preSharedUrl->val == NULL) { - LOGE("Failed to alloc preSharedUrl memory!"); - return HC_ERR_ALLOC_MEMORY; - } - if (memcpy_s(preSharedUrl->val, urlLen + 1, urlStr, urlLen) != EOK) { - LOGE("Failed to copy url string to preSharedUrl"); - HcFree(preSharedUrl->val); - preSharedUrl->val = NULL; - return HC_ERR_MEMORY_COPY; - } - preSharedUrl->length = urlLen + 1; - return HC_SUCCESS; -} - -static int32_t SetProtocolsForPresharedCred(int32_t trustType, int32_t keyType, IdentityInfo *info) -{ - if (trustType == TRUST_TYPE_UID) { - return SetProtocolsForUidType(info); - } else { - return SetProtocolsForP2pType(keyType, info); - } -} - -int32_t GetSelfDeviceEntry(int32_t osAccountId, const char *groupId, TrustedDeviceEntry *deviceEntry) -{ - char selfUdid[INPUT_UDID_LEN] = { 0 }; - int32_t ret = HcGetUdid((uint8_t *)selfUdid, INPUT_UDID_LEN); - if (ret != HC_SUCCESS) { - LOGE("Failed to get local udid!"); - return ret; - } - return GaGetTrustedDeviceEntryById(osAccountId, selfUdid, true, groupId, deviceEntry); -} - -const char *GetPeerDevIdFromJson(const CJson *in, bool *isUdid) -{ - const char *deviceId = GetStringFromJson(in, FIELD_PEER_UDID); - if (deviceId != NULL) { - *isUdid = true; - return deviceId; - } - return GetStringFromJson(in, FIELD_PEER_AUTH_ID); -} - -int32_t GetPeerDeviceEntry(int32_t osAccountId, const CJson *in, const char *groupId, - TrustedDeviceEntry *returnDeviceEntry) -{ - bool isUdid = false; - const char *peerDeviceId = GetPeerDevIdFromJson(in, &isUdid); - if (peerDeviceId == NULL) { - LOGE("Failed to get peer deviceId!"); - return HC_ERR_JSON_GET; - } - return GaGetTrustedDeviceEntryById(osAccountId, peerDeviceId, isUdid, groupId, returnDeviceEntry); -} - -int32_t GetIdentityInfoForPinType(const CJson *in, IdentityInfo *info) -{ - CJson *urlJson = CreateJson(); - if (urlJson == NULL) { - LOGE("Failed to create url json!"); - return HC_ERR_JSON_CREATE; - } - if (AddIntToJson(urlJson, PRESHARED_URL_CREDENTIAL_TYPE, PRE_SHARED) != HC_SUCCESS) { - LOGE("Failed to add credential type!"); - FreeJson(urlJson); - return HC_ERR_JSON_ADD; - } - if (AddIntToJson(urlJson, PRESHARED_URL_KEY_TYPE, KEY_TYPE_SYM) != HC_SUCCESS) { - LOGE("Failed to add key type!"); - FreeJson(urlJson); - return HC_ERR_JSON_ADD; - } - if (AddIntToJson(urlJson, PRESHARED_URL_TRUST_TYPE, TRUST_TYPE_PIN) != HC_SUCCESS) { - LOGE("Failed to add trust type!"); - FreeJson(urlJson); - return HC_ERR_JSON_ADD; - } - char *urlStr = PackJsonToString(urlJson); - FreeJson(urlJson); - if (urlStr == NULL) { - LOGE("Failed to pack url json to string!"); - return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL; - } - - int32_t ret = SetPreSharedUrlForProof(urlStr, &info->proof.preSharedUrl); - FreeJsonString(urlStr); - if (ret != HC_SUCCESS) { - LOGE("Failed to set preSharedUrl of proof!"); - return ret; - } - - ret = SetProtocolsForPinType(in, info); - if (ret != HC_SUCCESS) { - LOGE("Failed to set protocols!"); - return ret; - } - - info->proofType = PRE_SHARED; - return ret; -} - -int32_t GetIdentityInfoByType(int32_t keyType, int32_t trustType, const char *groupId, IdentityInfo *info) -{ - CJson *urlJson = CreateJson(); - if (urlJson == NULL) { - LOGE("Failed to create url json!"); - return HC_ERR_JSON_CREATE; - } - if (AddIntToJson(urlJson, PRESHARED_URL_CREDENTIAL_TYPE, PRE_SHARED) != HC_SUCCESS) { - LOGE("Failed to add credential type!"); - FreeJson(urlJson); - return HC_ERR_JSON_ADD; - } - if (AddIntToJson(urlJson, PRESHARED_URL_KEY_TYPE, keyType) != HC_SUCCESS) { - LOGE("Failed to add key type!"); - FreeJson(urlJson); - return HC_ERR_JSON_ADD; - } - if (AddIntToJson(urlJson, PRESHARED_URL_TRUST_TYPE, trustType) != HC_SUCCESS) { - LOGE("Failed to add trust type!"); - FreeJson(urlJson); - return HC_ERR_JSON_ADD; - } - if ((trustType == TRUST_TYPE_P2P || trustType == TRUST_TYPE_UID) && - AddStringToJson(urlJson, FIELD_GROUP_ID, groupId) != HC_SUCCESS) { - LOGE("Failed to add group id!"); - FreeJson(urlJson); - return HC_ERR_JSON_ADD; - } - char *urlStr = PackJsonToString(urlJson); - FreeJson(urlJson); - if (urlStr == NULL) { - LOGE("Failed to pack url json to string!"); - return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL; - } - - int32_t ret = SetPreSharedUrlForProof(urlStr, &info->proof.preSharedUrl); - FreeJsonString(urlStr); - if (ret != HC_SUCCESS) { - LOGE("Failed to set preSharedUrl of proof!"); - return ret; - } - - ret = SetProtocolsForPresharedCred(trustType, keyType, info); - if (ret != HC_SUCCESS) { - LOGE("Failed to set protocols!"); - return ret; - } - - info->proofType = PRE_SHARED; - return ret; -} - -void FreeBuffData(Uint8Buff *buff) -{ - if (buff == NULL) { - return; - } - HcFree(buff->val); - buff->val = NULL; - buff->length = 0; -} - -IdentityInfo *CreateIdentityInfo(void) -{ - IdentityInfo *info = (IdentityInfo *)HcMalloc(sizeof(IdentityInfo), 0); - if (info == NULL) { - LOGE("Failed to alloc memory for identity info!"); - return NULL; - } - info->protocolVec = CreateProtocolEntityVec(); - return info; -} - -void DestroyIdentityInfo(IdentityInfo *info) -{ - if (info == NULL) { - return; - } - - FreeBuffData(&info->proof.preSharedUrl); - FreeBuffData(&info->proof.certInfo.pkInfoStr); - FreeBuffData(&info->proof.certInfo.pkInfoSignature); - ClearProtocolEntityVec(&info->protocolVec); - - HcFree(info); -} - -void ClearIdentityInfoVec(IdentityInfoVec *vec) -{ - uint32_t index; - IdentityInfo **info; - FOR_EACH_HC_VECTOR(*vec, index, info) { - DestroyIdentityInfo(*info); - } - DESTROY_HC_VECTOR(IdentityInfoVec, vec); -} - -void ClearProtocolEntityVec(ProtocolEntityVec *vec) -{ - uint32_t index; - ProtocolEntity **entity; - FOR_EACH_HC_VECTOR(*vec, index, entity) { - HcFree(*entity); - } - DESTROY_HC_VECTOR(ProtocolEntityVec, vec); -} \ No newline at end of file diff --git a/services/device_auth.c b/services/device_auth.c index 4e80aa26..c09a2ee1 100644 --- a/services/device_auth.c +++ b/services/device_auth.c @@ -39,6 +39,7 @@ #include "pseudonym_manager.h" #include "task_manager.h" #include "performance_dumper.h" +#include "identity_manager.h" static GroupAuthManager *g_groupAuthManager = NULL; static DeviceGroupManager *g_groupManagerInstance = NULL; @@ -154,7 +155,7 @@ static const char *GetPeerUdidFromJson(int32_t osAccountId, const CJson *in) { const char *peerConnDeviceId = GetStringFromJson(in, FIELD_PEER_CONN_DEVICE_ID); if (peerConnDeviceId == NULL) { - LOGE("get peerConnDeviceId from json fail."); + LOGI("get peerConnDeviceId from json fail."); return NULL; } bool isUdidHash = false; @@ -855,6 +856,32 @@ static int32_t BuildClientAuthContext(int32_t osAccountId, int64_t requestId, co return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context); } +static int32_t BuildP2PBindContext(CJson *context) +{ + int32_t acquireType = -1; + if (GetIntFromJson(context, FIELD_ACQURIED_TYPE, &acquireType) != HC_SUCCESS) { + LOGE("Failed to get acquireType from reqJsonStr!"); + return HC_ERR_JSON_FAIL; + } + if ((acquireType == P2P_BIND) && AddBoolToJson(context, FIELD_IS_DIRECT_AUTH, true) != HC_SUCCESS) { + LOGE("add isDirectAuth to context fail."); + return HC_ERR_JSON_ADD; + } + if (AddIntToJson(context, FIELD_OPERATION_CODE, acquireType) != HC_SUCCESS) { + LOGE("add opCode to context fail."); + return HC_ERR_JSON_ADD; + } + const char *serviceType = GetStringFromJson(context, FIELD_SERVICE_TYPE); + if (serviceType == NULL) { + if ((acquireType == P2P_BIND) && + AddStringToJson(context, FIELD_SERVICE_TYPE, DEFAULT_SERVICE_TYPE) != HC_SUCCESS) { + LOGE("add serviceType to context fail."); + return HC_ERR_JSON_ADD; + } + } + return HC_SUCCESS; +} + static int32_t AuthDevice(int32_t osAccountId, int64_t authReqId, const char *authParams, const DeviceAuthCallback *gaCallback) { @@ -967,6 +994,58 @@ static int32_t BuildServerAuthContext(int64_t requestId, int32_t opCode, const c return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context); } +static int32_t BuildServerP2PAuthContext(int64_t requestId, int32_t opCode, const char *appId, CJson *context) +{ + int32_t osAccountId = ANY_OS_ACCOUNT; + (void)GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId); + osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId); + if (osAccountId == INVALID_OS_ACCOUNT) { + return HC_ERR_INVALID_PARAMS; + } + if (!IsOsAccountUnlocked(osAccountId)) { + LOGE("Os account is not unlocked!"); + return HC_ERR_OS_ACCOUNT_NOT_UNLOCKED; + } + const char *peerUdid = GetStringFromJson(context, FIELD_PEER_CONN_DEVICE_ID); + const char *pinCode = GetStringFromJson(context, FIELD_PIN_CODE); + if (peerUdid == NULL && pinCode == NULL) { + LOGE("need peerConnDeviceId or pinCode!"); + return HC_ERR_JSON_GET; + } + if (peerUdid != NULL) { + PRINT_SENSITIVE_DATA("PeerUdid", peerUdid); + if (AddDeviceIdToJson(context, peerUdid) != HC_SUCCESS) { + LOGE("add deviceId to context fail."); + return HC_ERR_JSON_ADD; + } + } + if (AddBoolToJson(context, FIELD_IS_BIND, false) != HC_SUCCESS) { + LOGE("add isBind to context fail."); + return HC_ERR_JSON_ADD; + } + if (AddBoolToJson(context, FIELD_IS_CLIENT, false) != HC_SUCCESS) { + LOGE("add isClient to context fail."); + return HC_ERR_JSON_ADD; + } + if (AddIntToJson(context, FIELD_OS_ACCOUNT_ID, osAccountId) != HC_SUCCESS) { + LOGE("add operationCode to context fail."); + return HC_ERR_JSON_ADD; + } + if (AddInt64StringToJson(context, FIELD_REQUEST_ID, requestId) != HC_SUCCESS) { + LOGE("add requestId to context fail."); + return HC_ERR_JSON_ADD; + } + if (AddStringToJson(context, FIELD_APP_ID, appId) != HC_SUCCESS) { + LOGE("add appId to context fail."); + return HC_ERR_JSON_ADD; + } + if (AddIntToJson(context, FIELD_OPERATION_CODE, opCode) != HC_SUCCESS) { + LOGE("add opCode to context fail."); + return HC_ERR_JSON_ADD; + } + return AddChannelInfoToContext(SERVICE_CHANNEL, DEFAULT_CHANNEL_ID, context); +} + static int32_t OpenServerAuthSession(int64_t requestId, const CJson *receivedMsg, const DeviceAuthCallback *callback) { int32_t opCode = AUTH_FORM_ACCOUNT_UNRELATED; @@ -1009,6 +1088,59 @@ static int32_t OpenServerAuthSession(int64_t requestId, const CJson *receivedMsg return res; } +static int32_t OpenServerAuthSessionForP2P( + int64_t requestId, const CJson *receivedMsg, const DeviceAuthCallback *callback) +{ + int32_t opCode = P2P_BIND; + if (GetIntFromJson(receivedMsg, FIELD_OP_CODE, &opCode) != HC_SUCCESS) { + opCode = P2P_BIND; + LOGW("use default opCode."); + } + char *returnDataStr = ProcessRequestCallback(requestId, opCode, NULL, callback); + if (returnDataStr == NULL) { + LOGE("The OnRequest callback is fail!"); + return HC_ERR_REQ_REJECTED; + } + CJson *context = CreateJsonFromString(returnDataStr); + FreeJsonString(returnDataStr); + if (context == NULL) { + LOGE("Failed to create context from string!"); + return HC_ERR_JSON_FAIL; + } + if (AddBoolToJson(context, FIELD_IS_DIRECT_AUTH, true) != HC_SUCCESS) { + LOGE("Failed to add isDirectAuth to context!"); + FreeJson(context); + return HC_ERR_JSON_ADD; + } + const char *pkgName = GetStringFromJson(context, FIELD_SERVICE_PKG_NAME); + if (pkgName == NULL && AddStringToJson(context, FIELD_SERVICE_PKG_NAME, DEFAULT_PACKAGE_NAME) != HC_SUCCESS) { + LOGE("Failed to add default package name to context!"); + FreeJson(context); + return HC_ERR_JSON_ADD; + } + const char *serviceType = GetStringFromJson(context, FIELD_SERVICE_TYPE); + if (serviceType == NULL && AddStringToJson(context, FIELD_SERVICE_TYPE, DEFAULT_SERVICE_TYPE) != HC_SUCCESS) { + LOGE("Failed to add default package name to context!"); + FreeJson(context); + return HC_ERR_JSON_ADD; + } + const char *appId = pkgName != NULL ? pkgName : DEFAULT_PACKAGE_NAME; + int32_t res = CheckAcceptRequest(context); + if (res != HC_SUCCESS) { + FreeJson(context); + return res; + } + res = BuildServerP2PAuthContext(requestId, opCode, appId, context); + if (res != HC_SUCCESS) { + FreeJson(context); + return res; + } + SessionInitParams params = { context, *callback }; + res = OpenDevSession(requestId, appId, ¶ms); + FreeJson(context); + return res; +} + static int32_t ProcessData(int64_t authReqId, const uint8_t *data, uint32_t dataLen, const DeviceAuthCallback *gaCallback) { @@ -1092,6 +1224,145 @@ static int32_t GetPseudonymId(int32_t osAccountId, const char *indexKey, char ** return pseudonymInstance->getPseudonymId(osAccountId, indexKey, pseudonymId); } +DEVICE_AUTH_API_PUBLIC int32_t ProcessCredential(int32_t operationCode, const char *reqJsonStr, char **returnData) +{ + if (reqJsonStr == NULL || returnData == NULL) { + LOGE("Invalid params!"); + return HC_ERR_INVALID_PARAMS; + } + + const CredentialOperator *credOperator = GetCredentialOperator(); + if (credOperator == NULL) { + LOGE("credOperator is null!"); + return HC_ERR_NOT_SUPPORT; + } + + int32_t res = HC_ERR_UNSUPPORTED_OPCODE; + switch (operationCode) { + case CRED_OP_QUERY: + res = credOperator->queryCredential(reqJsonStr, returnData); + break; + case CRED_OP_CREATE: + res = credOperator->genarateCredential(reqJsonStr, returnData); + break; + case CRED_OP_IMPORT: + res = credOperator->importCredential(reqJsonStr, returnData); + break; + case CRED_OP_DELETE: + res = credOperator->deleteCredential(reqJsonStr, returnData); + break; + default: + LOGE("invalid opCode: %d", operationCode); + break; + } + + return res; +} + +DEVICE_AUTH_API_PUBLIC int32_t ProcessAuthDevice( + int64_t authReqId, const char *authParams, const DeviceAuthCallback *callback) +{ + SET_LOG_MODE(TRACE_MODE); + SET_TRACE_ID(authReqId); + LOGI("[DA] Begin ProcessAuthDevice [ReqId]: %" PRId64, authReqId); + if (authParams == NULL) { + LOGE("Invalid input for ProcessData!"); + return HC_ERR_INVALID_PARAMS; + } + CJson *json = CreateJsonFromString(authParams); + if (json == NULL) { + LOGE("Failed to create json from string!"); + return HC_ERR_JSON_FAIL; + } + const char *data = GetStringFromJson(json, "data"); + if (data == NULL) { + LOGE("Failed to get received data from parameter!"); + FreeJson(json); + return HC_ERR_INVALID_PARAMS; + } + CJson *receivedMsg = CreateJsonFromString(data); + FreeJson(json); + if (receivedMsg == NULL) { + LOGE("Failed to create json from string!"); + return HC_ERR_JSON_FAIL; + } + int32_t res; + if (!IsSessionExist(authReqId)) { + res = OpenServerAuthSessionForP2P(authReqId, receivedMsg, callback); + if (res != HC_SUCCESS) { + FreeJson(receivedMsg); + return res; + } + } + res = PushProcSessionTask(authReqId, receivedMsg); + if (res != HC_SUCCESS) { + FreeJson(receivedMsg); + return res; + } + return HC_SUCCESS; +} + +DEVICE_AUTH_API_PUBLIC int32_t StartAuthDevice( + int64_t authReqId, const char *authParams, const DeviceAuthCallback *callback) +{ + SET_LOG_MODE(TRACE_MODE); + SET_TRACE_ID(authReqId); + LOGI("StartAuthDevice. [ReqId]:%" PRId64, authReqId); + + if ((authParams == NULL) || (callback == NULL)) { + LOGE("The input auth params is invalid!"); + return HC_ERR_INVALID_PARAMS; + } + CJson *context = CreateJsonFromString(authParams); + if (context == NULL) { + LOGE("Failed to create json from string!"); + return HC_ERR_JSON_FAIL; + } + int32_t osAccountId = INVALID_OS_ACCOUNT; + if (GetIntFromJson(context, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { + LOGE("Failed to get osAccountId from json!"); + FreeJson(context); + return HC_ERR_JSON_FAIL; + } + + osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId); + if (osAccountId == INVALID_OS_ACCOUNT) { + FreeJson(context); + return HC_ERR_INVALID_PARAMS; + } + int32_t res = BuildClientAuthContext(osAccountId, authReqId, DEFAULT_PACKAGE_NAME, context); + if (res != HC_SUCCESS) { + FreeJson(context); + return res; + } + res = BuildP2PBindContext(context); + if (res != HC_SUCCESS) { + FreeJson(context); + return res; + } + SessionInitParams params = { context, *callback }; + res = OpenDevSession(authReqId, DEFAULT_PACKAGE_NAME, ¶ms); + FreeJson(context); + if (res != HC_SUCCESS) { + LOGE("OpenDevSession fail. [Res]: %d", res); + return res; + } + return PushStartSessionTask(authReqId); +} + +DEVICE_AUTH_API_PUBLIC int32_t CancelAuthRequest(int64_t requestId, const char *authParams) +{ + SET_LOG_MODE(TRACE_MODE); + SET_TRACE_ID(requestId); + if (authParams == NULL) { + LOGE("Invalid authParams!"); + return HC_ERR_INVALID_PARAMS; + } + LOGI("cancel request. [ReqId]: %" PRId64, requestId); + CancelDevSession(requestId, DEFAULT_PACKAGE_NAME); + return HC_SUCCESS; +} + static int32_t AllocGmAndGa(void) { if (g_groupManagerInstance == NULL) { diff --git a/services/device_auth.map b/services/device_auth.map index b58ae083..b387dc6e 100644 --- a/services/device_auth.map +++ b/services/device_auth.map @@ -19,6 +19,10 @@ DestroyDeviceAuthService; GetGaInstance; GetGmInstance; + ProcessCredential; + StartAuthDevice; + ProcessAuthDevice; + CancelAuthRequest; local: *; }; diff --git a/services/deviceauth.gni b/services/deviceauth.gni index 8bf36609..1515d5c9 100644 --- a/services/deviceauth.gni +++ b/services/deviceauth.gni @@ -13,18 +13,18 @@ import("//base/security/device_auth/deviceauth_env.gni") -group_auth_path = "${services_path}/group_auth" -authenticators_path = "${services_path}/authenticators" +group_auth_path = "${services_path}/legacy/group_auth" +authenticators_path = "${services_path}/legacy/authenticators" protocol_path = "${services_path}/protocol" cred_manager_path = "${services_path}/cred_manager" data_manager_path = "${services_path}/data_manager" privacy_enhancement_path = "${services_path}/privacy_enhancement" dev_frameworks_path = "${services_path}/frameworks" -group_manager_path = "${services_path}/group_manager" +group_manager_path = "${services_path}/legacy/group_manager" session_manager_path = "${services_path}/session_manager" creds_manager_path = "${services_path}/creds_manager" mk_agree_path = "${services_path}/mk_agree" - +identity_manager_path = "${services_path}/identity_manager" enable_broadcast = true deviceauth_defines = [] @@ -198,11 +198,9 @@ auth_code_import_files = [ "${session_manager_path}/src/session/v2/expand_sub_se pub_key_exchange_files = [ "${session_manager_path}/src/session/v2/expand_sub_session/expand_process_lib/pub_key_exchange.c" ] save_trusted_info_files = [ "${session_manager_path}/src/session/v2/expand_sub_session/expand_process_lib/save_trusted_info.c" ] -creds_manager_files = [ - "${creds_manager_path}/src/creds_manager.c", - "${creds_manager_path}/src/creds_operation_utils.c", -] -account_related_creds_manager_mock_files = [ "${creds_manager_path}/src/account_related_mock/account_related_creds_manager_mock.c" ] +creds_manager_files = [ "${creds_manager_path}/src/creds_manager.c" ] +account_related_creds_manager_mock_files = + [ "${identity_manager_path}/src/mock/cert_operation_mock.c" ] group_manager_peer_to_peer_files = [ "${group_manager_path}/src/group_operation/peer_to_peer_group/peer_to_peer_group.c" ] group_manager_peer_to_peer_mock_files = [ "${group_manager_path}/src/group_operation/peer_to_peer_group_mock/peer_to_peer_group_mock.c" ] @@ -447,3 +445,25 @@ deviceauth_ipc_files = [ "${frameworks_path}/src/${ipc_adapt_path}/ipc_callback_proxy.${ipc_src_suffix}", "${frameworks_path}/src/${ipc_adapt_path}/ipc_callback_stub.${ipc_src_suffix}", ] + +identity_manager_inc = [ "${identity_manager_path}/inc" ] + +declare_args() { + identity_manager_files = [] +} + +if (defined(ohos_lite)) { + identity_manager_files = [ + "${identity_manager_path}/src/mock/identity_manager_mock.c", + "${identity_manager_path}/src/mock/identity_common_mock.c", + ] +} else { + identity_manager_files = [ + "${identity_manager_path}/src/identity_manager.c", + "${identity_manager_path}/src/credential_operator.c", + "${identity_manager_path}/src/identity_common.c", + "${identity_manager_path}/src/identity_group.c", + "${identity_manager_path}/src/identity_p2p.c", + "${identity_manager_path}/src/identity_pin.c", + ] +} diff --git a/services/deviceauth_account.gni b/services/deviceauth_account.gni index 736bd169..42fddb34 100644 --- a/services/deviceauth_account.gni +++ b/services/deviceauth_account.gni @@ -19,40 +19,41 @@ account_related_defines = [ ] account_related_inc_path = [] -deviceauth_account_group_manager_path = "${services_path}/group_manager" -deviceauth_account_group_auth_path = "${services_path}/group_auth" - +deviceauth_account_group_manager_path = "${services_path}/legacy/group_manager" +deviceauth_account_group_auth_path = "${services_path}/legacy/group_auth" +authenticators_path = "${services_path}/legacy/authenticators" group_manager_identical_account_files = [ "${deviceauth_account_group_manager_path}/src/group_operation/identical_account_group/identical_account_group.c" ] group_manager_across_account_files = [ "${deviceauth_account_group_manager_path}/src/group_operation/across_account_group/across_account_group.c" ] group_auth_account_related_files = [ "${deviceauth_account_group_auth_path}/src/group_auth_manager/account_related_group_auth/account_related_group_auth.c" ] - +identity_manager_path = "${services_path}/identity_manager" account_related_inc_path += [ - "${services_path}/authenticators/inc", - "${services_path}/authenticators/inc/account_related", - "${services_path}/authenticators/inc/account_related/auth/iso_auth_task", - "${services_path}/authenticators/inc/account_related/auth/pake_v2_auth_task", - "${services_path}/authenticators/inc/account_related/creds_manager", + "${authenticators_path}/inc", + "${authenticators_path}/inc/account_related", + "${authenticators_path}/inc/account_related/auth/iso_auth_task", + "${authenticators_path}/inc/account_related/auth/pake_v2_auth_task", + "${authenticators_path}/inc/account_related/creds_manager", ] authenticators_account_related_files = [ - "${services_path}/authenticators/src/account_related/account_module.c", - "${services_path}/authenticators/src/account_related/account_multi_task_manager.c", - "${services_path}/authenticators/src/account_related/account_task_main.c", - "${services_path}/authenticators/src/account_related/account_version_util.c", - "${services_path}/authenticators/src/account_related/creds_manager/asy_token_manager.c", - "${services_path}/authenticators/src/account_related/creds_manager/sym_token_manager.c", - "${services_path}/authenticators/src/account_related/auth/iso_auth_task/iso_auth_client_task.c", - "${services_path}/authenticators/src/account_related/auth/iso_auth_task/iso_auth_server_task.c", - "${services_path}/authenticators/src/account_related/auth/iso_auth_task/iso_auth_task_common.c", - "${services_path}/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_task_common.c", - "${services_path}/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_client_task.c", - "${services_path}/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_server_task.c", + "${authenticators_path}/src/account_related/account_module.c", + "${authenticators_path}/src/account_related/account_multi_task_manager.c", + "${authenticators_path}/src/account_related/account_task_main.c", + "${authenticators_path}/src/account_related/account_version_util.c", + "${authenticators_path}/src/account_related/creds_manager/asy_token_manager.c", + "${authenticators_path}/src/account_related/creds_manager/sym_token_manager.c", + "${authenticators_path}/src/account_related/auth/iso_auth_task/iso_auth_client_task.c", + "${authenticators_path}/src/account_related/auth/iso_auth_task/iso_auth_server_task.c", + "${authenticators_path}/src/account_related/auth/iso_auth_task/iso_auth_task_common.c", + "${authenticators_path}/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_task_common.c", + "${authenticators_path}/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_client_task.c", + "${authenticators_path}/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_server_task.c", ] account_related_cred_plugin_files = [ "${services_path}/cred_manager/src/account_related/account_related_cred_plugin.c" ] -account_related_creds_manager_files = [ "${services_path}/creds_manager/src/account_related/account_related_creds_manager.c" ] +account_related_creds_manager_files = + [ "${identity_manager_path}/src/cert_operation.c" ] account_related_files = group_auth_account_related_files + group_manager_identical_account_files + diff --git a/services/frameworks/inc/common_defs.h b/services/frameworks/inc/common_defs.h index 37126b20..63104e49 100644 --- a/services/frameworks/inc/common_defs.h +++ b/services/frameworks/inc/common_defs.h @@ -70,8 +70,10 @@ #define FIELD_IS_BIND "isBind" #define FIELD_IS_FORCE_DELETE "isForceDelete" #define FIELD_IS_CREDENTIAL_EXISTS "isCredentialExists" +#define FIELD_IS_DIRECT_AUTH "isDirectAuth" #define FIELD_KCF_DATA "kcfData" #define FIELD_KEY_TYPE "keyType" +#define FIELD_TRUST_TYPE "trustType" #define FIELD_MESSAGE "message" #define FIELD_GROUP_ERROR_MSG "groupErrorMsg" #define FIELD_MIN_VERSION "minVersion" @@ -144,6 +146,9 @@ #define DEFAULT_REQUEST_ID 0 #define DEFAULT_CHANNEL_ID (-1) #define DEFAULT_EXPIRE_TIME 90 +#define DEFAULT_SERVICE_TYPE "service.type.default" +#define SERVICE_TYPE_IMPORT "service.type.import" +#define DEFAULT_PACKAGE_NAME "deviceauth_service" #define GROUP_MANAGER_PACKAGE_NAME "com.huawei.devicegroupmanage" #define DM_APP_ID "ohos.distributedhardware.devicemanager" #define SOFTBUS_APP_ID "softbus_auth" diff --git a/services/frameworks/src/permission_adapter/permission_adapter.cpp b/services/frameworks/src/permission_adapter/permission_adapter.cpp index 43779ddc..69cc6ffd 100644 --- a/services/frameworks/src/permission_adapter/permission_adapter.cpp +++ b/services/frameworks/src/permission_adapter/permission_adapter.cpp @@ -34,6 +34,13 @@ using namespace OHOS::Security::AccessToken; #define PROC_NAME_SOFT_BUS "softbus_server" #define PROC_NAME_DEVICE_SECURITY_LEVEL "dslm_service" +static unordered_map> g_apiAccessWhitelist = { + { IPC_CALL_ID_PROCESS_CREDENTIAL, { PROC_NAME_DEVICE_MANAGER } }, + { IPC_CALL_ID_DA_AUTH_DEVICE, { PROC_NAME_DEVICE_MANAGER, PROC_NAME_SOFT_BUS } }, + { IPC_CALL_ID_DA_PROC_DATA, { PROC_NAME_DEVICE_MANAGER, PROC_NAME_SOFT_BUS } }, + { IPC_CALL_ID_DA_CANCEL_REQUEST, { PROC_NAME_DEVICE_MANAGER, PROC_NAME_SOFT_BUS } }, +}; + static unordered_map> g_apiAccessConfig = { { IPC_CALL_ID_REG_CB, { PROC_NAME_DEVICE_MANAGER } }, { IPC_CALL_ID_UNREG_CB, { PROC_NAME_DEVICE_MANAGER } }, @@ -61,6 +68,23 @@ static bool IsProcessAllowAccess(const string &processName, int32_t methodId) g_apiAccessConfig[methodId].end(); } +static bool IsProcessInWhitelist(const string& processName, int32_t methodId) +{ + if (g_apiAccessWhitelist.find(methodId) == g_apiAccessWhitelist.end()) { + return true; + } + int32_t ret = find(g_apiAccessWhitelist[methodId].begin(), g_apiAccessWhitelist[methodId].end(), processName) != + g_apiAccessWhitelist[methodId].end(); + if (ret) { + LOGI("%s %d", processName.c_str(), ret); + } else { + LOGE("Access Denied: Process(%s) not in access whitlist", processName.c_str()); + return false; + } + + return true; +} + int32_t CheckPermission(int32_t methodId) { AccessTokenID tokenId = IPCSkeleton::GetCallingTokenID(); @@ -78,6 +102,12 @@ int32_t CheckPermission(int32_t methodId) LOGE("Check permission(APL3=SYSTEM_CORE or APL2=SYSTEM_BASIC) failed! APL: %d", findInfo.apl); return HC_ERROR; } + + if (!IsProcessInWhitelist(findInfo.processName, methodId)) { + LOGE("Check permission(Access Whitelist) failed!"); + return HC_ERROR; + } + if (!IsProcessAllowAccess(findInfo.processName, methodId)) { LOGE("Check permission(Interface Access List) failed!"); return HC_ERROR; diff --git a/services/creds_manager/inc/account_related/account_related_creds_manager.h b/services/identity_manager/inc/cert_operation.h similarity index 80% rename from services/creds_manager/inc/account_related/account_related_creds_manager.h rename to services/identity_manager/inc/cert_operation.h index 79f8749c..66c6d73c 100644 --- a/services/creds_manager/inc/account_related/account_related_creds_manager.h +++ b/services/identity_manager/inc/cert_operation.h @@ -13,18 +13,18 @@ * limitations under the License. */ -#ifndef ACCOUNT_RELATED_CREDS_MANAGER_H -#define ACCOUNT_RELATED_CREDS_MANAGER_H +#ifndef CERT_OPERATION_H +#define CERT_OPERATION_H -#include "creds_manager_defines.h" +#include "identity_defines.h" #include "json_utils.h" #ifdef __cplusplus extern "C" { #endif - -int32_t GetAccountRelatedCredInfo(int32_t osAccountId, const char *groupId, const char *deviceId, - bool isUdid, IdentityInfo *info); +int32_t AddCertInfoToJson(const CertInfo *certInfo, CJson *out); +int32_t GetAccountRelatedCredInfo( + int32_t osAccountId, const char *groupId, const char *deviceId, bool isUdid, IdentityInfo *info); int32_t GetAccountAsymSharedSecret(int32_t osAccountId, const CertInfo *peerCertInfo, Uint8Buff *sharedSecret); int32_t GetAccountSymSharedSecret(const CJson *in, const CJson *urlJson, Uint8Buff *sharedSecret); int32_t GetAccountAsymCredInfo(int32_t osAccountId, const CertInfo *certInfo, IdentityInfo **returnInfo); diff --git a/services/creds_manager/inc/creds_operation_utils.h b/services/identity_manager/inc/identity_common.h similarity index 71% rename from services/creds_manager/inc/creds_operation_utils.h rename to services/identity_manager/inc/identity_common.h index 59b68e22..c954d726 100644 --- a/services/creds_manager/inc/creds_operation_utils.h +++ b/services/identity_manager/inc/identity_common.h @@ -13,23 +13,28 @@ * limitations under the License. */ -#ifndef CREDS_OPERATION_UTILS_H -#define CREDS_OPERATION_UTILS_H +#ifndef AUTH_IDENTITY_COMMON_H +#define AUTH_IDENTITY_COMMON_H -#include "creds_manager_defines.h" #include "data_manager.h" +#include "hc_vector.h" +#include "identity_defines.h" #include "json_utils.h" #ifdef __cplusplus extern "C" { #endif +int32_t ConvertPsk(const Uint8Buff *srcPsk, Uint8Buff *sharedSecret); +int32_t SetPreSharedUrlForProof(const char *urlStr, Uint8Buff *preSharedUrl); +CJson *CreateCredUrlJson(int32_t credentailType, int32_t keyType, int32_t trustType); + +#if 1 int32_t GetSelfDeviceEntry(int32_t osAccountId, const char *groupId, TrustedDeviceEntry *deviceEntry); const char *GetPeerDevIdFromJson(const CJson *in, bool *isUdid); -int32_t GetPeerDeviceEntry(int32_t osAccountId, const CJson *in, const char *groupId, - TrustedDeviceEntry *returnDeviceEntry); -int32_t GetIdentityInfoForPinType(const CJson *in, IdentityInfo *info); -int32_t GetIdentityInfoByType(int32_t keyType, int32_t trustType, const char *groupId, IdentityInfo *info); +int32_t GetPeerDeviceEntry( + int32_t osAccountId, const CJson *in, const char *groupId, TrustedDeviceEntry *returnDeviceEntry); + void FreeBuffData(Uint8Buff *buff); IdentityInfo *CreateIdentityInfo(void); @@ -40,6 +45,7 @@ void ClearIdentityInfoVec(IdentityInfoVec *vec); ProtocolEntityVec CreateProtocolEntityVec(void); void ClearProtocolEntityVec(ProtocolEntityVec *vec); +#endif #ifdef __cplusplus } diff --git a/services/creds_manager/inc/creds_manager_defines.h b/services/identity_manager/inc/identity_defines.h similarity index 62% rename from services/creds_manager/inc/creds_manager_defines.h rename to services/identity_manager/inc/identity_defines.h index 623eff3d..f52d9131 100644 --- a/services/creds_manager/inc/creds_manager_defines.h +++ b/services/identity_manager/inc/identity_defines.h @@ -13,8 +13,8 @@ * limitations under the License. */ -#ifndef CREDS_MANAGER_DEFINES_H -#define CREDS_MANAGER_DEFINES_H +#ifndef AUTH_IDENTITY_DEFINE_H +#define AUTH_IDENTITY_DEFINE_H #include "alg_defs.h" #include "hc_vector.h" @@ -27,6 +27,7 @@ #define SHARED_KEY_ALIAS "sharedKeyAlias" #define KEY_INFO_PERSISTENT_TOKEN "persistent_token" #define TMP_AUTH_KEY_FACTOR "hichain_tmp_auth_enc_key" + #define ASCII_CASE_DIFFERENCE_VALUE 32 #define P256_SHARED_SECRET_KEY_SIZE 32 #define AUTH_TOKEN_SIZE 32 @@ -36,32 +37,42 @@ #define ISO_PSK_LEN 32 #define SEED_LEN 32 #define ISO_KEY_ALIAS_LEN 32 +#define KEY_TYPE_PAIR_LEN 2 +#define PAKE_ED25519_KEY_PAIR_LEN 32 +#define PAKE_ED25519_KEY_STR_LEN 64 +#define AUTH_CODE_LEN 32 +#define KEY_ALIAS_LEN 32 +#define PACKAGE_NAME_MAX_LEN 256 +#define SERVICE_TYPE_MAX_LEN 256 +#define AUTH_ID_MAX_LEN 64 #ifdef __cplusplus extern "C" { #endif -typedef enum { - KEY_TYPE_SYM, - KEY_TYPE_ASYM -} KeyType; +typedef enum { KEY_TYPE_SYM, KEY_TYPE_ASYM } KeyType; + +typedef enum { TRUST_TYPE_PIN, TRUST_TYPE_P2P, TRUST_TYPE_UID } TrustType; + +typedef enum { PRE_SHARED, CERTIFICATED } IdentityProofType; + +typedef enum { ALG_EC_SPEKE = 0x0001, ALG_DL_SPEKE = 0x0002, ALG_ISO = 0x0004 } ProtocolAlgType; typedef enum { - TRUST_TYPE_PIN, - TRUST_TYPE_P2P, - TRUST_TYPE_UID -} TrustType; + KEY_ALIAS_ACCESSOR_PK = 0, + KEY_ALIAS_CONTROLLER_PK = 1, + KEY_ALIAS_LT_KEY_PAIR = 2, + KEY_ALIAS_KEK = 3, + KEY_ALIAS_DEK = 4, + KEY_ALIAS_TMP = 5, + KEY_ALIAS_PSK = 6, + KEY_ALIAS_AUTH_TOKEN = 7, + KEY_ALIAS_P2P_AUTH = 8, -typedef enum { - PRE_SHARED, - CERTIFICATED -} IdentityProofType; + KEY_ALIAS_TYPE_END +} KeyAliasType; // 0 ~ 2^8-1, don't change the order -typedef enum { - ALG_EC_SPEKE = 0x0001, - ALG_DL_SPEKE = 0x0002, - ALG_ISO = 0x0004 -} ProtocolAlgType; +uint8_t *GetKeyTypePair(KeyAliasType keyAliasType); typedef enum { CMD_EXCHANGE_PK = 0x0001, @@ -70,11 +81,16 @@ typedef enum { CMD_MK_AGREE = 0x0008, } ExpandProcessCmd; +typedef enum { + DEFAULT_ID_TYPE = 0, + P2P_DIRECT_AUTH = 1, +} IdentityInfoType; + typedef struct { ProtocolAlgType protocolType; uint32_t expandProcessCmds; } ProtocolEntity; -DECLARE_HC_VECTOR(ProtocolEntityVec, ProtocolEntity*) +DECLARE_HC_VECTOR(ProtocolEntityVec, ProtocolEntity *) typedef struct { Uint8Buff pkInfoStr; @@ -92,8 +108,9 @@ typedef struct { IdentityProofType proofType; IdentityProof proof; ProtocolEntityVec protocolVec; + int32_t IdInfoType; } IdentityInfo; -DECLARE_HC_VECTOR(IdentityInfoVec, IdentityInfo*) +DECLARE_HC_VECTOR(IdentityInfoVec, IdentityInfo *) #ifdef __cplusplus } diff --git a/services/identity_manager/inc/identity_manager.h b/services/identity_manager/inc/identity_manager.h new file mode 100644 index 00000000..c726dee6 --- /dev/null +++ b/services/identity_manager/inc/identity_manager.h @@ -0,0 +1,75 @@ +/* + * Copyright (C) 2023 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 AUTH_IDENTITY_MANAGER_H +#define AUTH_IDENTITY_MANAGER_H + +#include "alg_defs.h" +#include "alg_loader.h" +#include "common_defs.h" +#include "das_task_common.h" +#include "device_auth_defines.h" +#include "hc_log.h" +#include "hc_types.h" +#include "identity_common.h" +#include "identity_defines.h" +#include "json_utils.h" +#include "securec.h" + +#ifdef __cplusplus +extern "C" { +#endif + +typedef enum { + AUTH_IDENTITY_TYPE_INVALID = -1, + AUTH_IDENTITY_TYPE_GROUP, + AUTH_IDENTITY_TYPE_PIN, + AUTH_IDENTITY_TYPE_P2P, +} AuthIdentityType; + +typedef struct { + int32_t (*getCredInfosByPeerIdentity)(const CJson *in, IdentityInfoVec *vec); + int32_t (*getCredInfoByPeerUrl)(const CJson *in, const Uint8Buff *presharedUrl, IdentityInfo **returnInfo); + int32_t (*getSharedSecretByUrl)( + const CJson *in, const Uint8Buff *presharedUrl, ProtocolAlgType protocolType, Uint8Buff *sharedSecret); + int32_t (*getCredInfoByPeerCert)(const CJson *in, const CertInfo *certInfo, IdentityInfo **returnInfo); + int32_t (*getSharedSecretByPeerCert)( + const CJson *in, const CertInfo *peerCertInfo, ProtocolAlgType protocolType, Uint8Buff *sharedSecret); +} AuthIdentity; + +typedef struct { + int32_t (*queryCredential)(const char *reqJsonStr, char **returnData); + int32_t (*genarateCredential)(const char *reqJsonStr, char **returnData); + int32_t (*importCredential)(const char *reqJsonStr, char **returnData); + int32_t (*deleteCredential)(const char *reqJsonStr, char **returnData); +} CredentialOperator; + +typedef struct { + const AuthIdentity *(*getAuthIdentityByType)(AuthIdentityType type); + const CredentialOperator *(*getCredentialOperator)(void); +} AuthIdentityManager; + +const AuthIdentity *GetGroupAuthIdentity(void); +const AuthIdentity *GetPinAuthIdentity(void); +const AuthIdentity *GetP2pAuthIdentity(void); +const AuthIdentity *GetAuthIdentityByType(AuthIdentityType type); +const CredentialOperator *GetCredentialOperator(void); +const AuthIdentityManager *GetAuthIdentityManager(void); + +#ifdef __cplusplus +} +#endif + +#endif // AUTH_IDENTITY_MANAGER_H \ No newline at end of file diff --git a/services/creds_manager/src/account_related/account_related_creds_manager.c b/services/identity_manager/src/cert_operation.c similarity index 82% rename from services/creds_manager/src/account_related/account_related_creds_manager.c rename to services/identity_manager/src/cert_operation.c index 04a98b94..bb9f9b4e 100644 --- a/services/creds_manager/src/account_related/account_related_creds_manager.c +++ b/services/identity_manager/src/cert_operation.c @@ -13,24 +13,115 @@ * limitations under the License. */ -#include "account_related_creds_manager.h" +#include "cert_operation.h" #include "account_auth_plugin_proxy.h" #include "account_related_group_auth.h" #include "alg_loader.h" #include "asy_token_manager.h" -#include "creds_manager.h" -#include "creds_operation_utils.h" #include "data_manager.h" #include "group_auth_data_operation.h" #include "group_operation_common.h" #include "hc_log.h" #include "hc_types.h" +#include "identity_common.h" #include "pseudonym_manager.h" #include "sym_token_manager.h" #define FIELD_SHARED_SECRET "sharedSecret" +static int32_t SetProtocolsForUidType(IdentityInfo *info) +{ +#ifdef ENABLE_ACCOUNT_AUTH_ISO + ProtocolEntity *entity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); + if (entity == NULL) { + LOGE("Failed to alloc memory for entity!"); + return HC_ERR_ALLOC_MEMORY; + } + entity->protocolType = ALG_ISO; + entity->expandProcessCmds = CMD_ADD_TRUST_DEVICE; + info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&entity); +#else + (void)info; +#endif + + return HC_SUCCESS; +} + +static int32_t GetIdentityInfoByType(int32_t keyType, int32_t trustType, const char *groupId, IdentityInfo *info) +{ + CJson *urlJson = CreateJson(); + if (urlJson == NULL) { + LOGE("Failed to create url json!"); + return HC_ERR_JSON_CREATE; + } + if (AddIntToJson(urlJson, PRESHARED_URL_CREDENTIAL_TYPE, PRE_SHARED) != HC_SUCCESS) { + LOGE("Failed to add credential type!"); + FreeJson(urlJson); + return HC_ERR_JSON_ADD; + } + if (AddIntToJson(urlJson, PRESHARED_URL_KEY_TYPE, keyType) != HC_SUCCESS) { + LOGE("Failed to add key type!"); + FreeJson(urlJson); + return HC_ERR_JSON_ADD; + } + if (AddIntToJson(urlJson, PRESHARED_URL_TRUST_TYPE, trustType) != HC_SUCCESS) { + LOGE("Failed to add trust type!"); + FreeJson(urlJson); + return HC_ERR_JSON_ADD; + } + if ((trustType == TRUST_TYPE_P2P || trustType == TRUST_TYPE_UID) && + AddStringToJson(urlJson, FIELD_GROUP_ID, groupId) != HC_SUCCESS) { + LOGE("Failed to add group id!"); + FreeJson(urlJson); + return HC_ERR_JSON_ADD; + } + char *urlStr = PackJsonToString(urlJson); + FreeJson(urlJson); + if (urlStr == NULL) { + LOGE("Failed to pack url json to string!"); + return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL; + } + + int32_t ret = SetPreSharedUrlForProof(urlStr, &info->proof.preSharedUrl); + FreeJsonString(urlStr); + if (ret != HC_SUCCESS) { + LOGE("Failed to set preSharedUrl of proof!"); + return ret; + } + + ret = SetProtocolsForUidType(info); + if (ret != HC_SUCCESS) { + LOGE("Failed to set protocols!"); + return ret; + } + + info->proofType = PRE_SHARED; + return ret; +} + +int32_t AddCertInfoToJson(const CertInfo *certInfo, CJson *out) +{ + if (certInfo == NULL || out == NULL) { + LOGE("Invalid cert info or out!"); + return HC_ERR_INVALID_PARAMS; + } + if (AddIntToJson(out, FIELD_SIGN_ALG, certInfo->signAlg) != HC_SUCCESS) { + LOGE("add sign alg to json failed!"); + return HC_ERR_JSON_ADD; + } + if (AddStringToJson(out, FIELD_PK_INFO, (const char *)certInfo->pkInfoStr.val) != HC_SUCCESS) { + LOGE("add pk info str to json failed!"); + return HC_ERR_JSON_ADD; + } + if (AddByteToJson(out, FIELD_PK_INFO_SIGNATURE, certInfo->pkInfoSignature.val, + certInfo->pkInfoSignature.length) != HC_SUCCESS) { + LOGE("add pk info sign to json failed!"); + return HC_ERR_JSON_ADD; + } + return HC_SUCCESS; +} + static TrustedGroupEntry *GetSelfGroupEntryByPeerCert(int32_t osAccountId, const CertInfo *certInfo) { CJson *peerPkInfoJson = CreateJsonFromString((const char *)certInfo->pkInfoStr.val); @@ -65,7 +156,8 @@ static TrustedGroupEntry *GetSelfGroupEntryByPeerCert(int32_t osAccountId, const } GroupEntryVec groupEntryVec = CreateGroupEntryVec(); QueryGroupParams queryParams = InitQueryGroupParams(); - ((AccountRelatedGroupAuth *)groupAuth)->getAccountCandidateGroup(osAccountId, param, &queryParams, &groupEntryVec); + ((AccountRelatedGroupAuth *)groupAuth) + ->getAccountCandidateGroup(osAccountId, param, &queryParams, &groupEntryVec); FreeJson(param); if (groupEntryVec.size(&groupEntryVec) == 0) { LOGE("group not found by peer user id!"); @@ -77,8 +169,8 @@ static TrustedGroupEntry *GetSelfGroupEntryByPeerCert(int32_t osAccountId, const return returnEntry; } -static int32_t GetSelfDeviceEntryByPeerCert(int32_t osAccountId, const CertInfo *certInfo, - TrustedDeviceEntry *deviceEntry) +static int32_t GetSelfDeviceEntryByPeerCert( + int32_t osAccountId, const CertInfo *certInfo, TrustedDeviceEntry *deviceEntry) { TrustedGroupEntry *groupEntry = GetSelfGroupEntryByPeerCert(osAccountId, certInfo); if (groupEntry == NULL) { @@ -98,18 +190,15 @@ static int32_t VerifyPeerCertInfo(const char *selfUserId, const char *selfAuthId LOGE("Failed to alloc memory for key alias value!"); return HC_ERR_ALLOC_MEMORY; } - Uint8Buff keyAlias = { - .val = keyAliasValue, - .length = SHA256_LEN - }; + Uint8Buff keyAlias = { .val = keyAliasValue, .length = SHA256_LEN }; int32_t ret = GetAccountAuthTokenManager()->generateKeyAlias(selfUserId, selfAuthId, &keyAlias, true); if (ret != HC_SUCCESS) { LOGE("Failed to generate server pk alias!"); HcFree(keyAliasValue); return ret; } - ret = GetLoaderInstance()->verify(&keyAlias, &certInfo->pkInfoStr, certInfo->signAlg, - &certInfo->pkInfoSignature, true); + ret = GetLoaderInstance()->verify( + &keyAlias, &certInfo->pkInfoStr, certInfo->signAlg, &certInfo->pkInfoSignature, true); HcFree(keyAliasValue); if (ret != HC_SUCCESS) { return HC_ERR_VERIFY_FAILED; @@ -148,8 +237,8 @@ static int32_t GetPeerPubKeyFromCert(const CertInfo *peerCertInfo, Uint8Buff *pe return HC_SUCCESS; } -static int32_t GetSharedSecretForAccountInPake(const char *userId, const char *authId, - const CertInfo *peerCertInfo, Uint8Buff *sharedSecret) +static int32_t GetSharedSecretForAccountInPake( + const char *userId, const char *authId, const CertInfo *peerCertInfo, Uint8Buff *sharedSecret) { uint8_t *priAliasVal = (uint8_t *)HcMalloc(SHA256_LEN, 0); if (priAliasVal == NULL) { @@ -162,22 +251,14 @@ static int32_t GetSharedSecretForAccountInPake(const char *userId, const char *a HcFree(priAliasVal); return ret; } - KeyBuff priAliasKeyBuff = { - .key = aliasBuff.val, - .keyLen = aliasBuff.length, - .isAlias = true - }; - Uint8Buff peerPkBuff = { 0 }; + KeyBuff priAliasKeyBuff = { .key = aliasBuff.val, .keyLen = aliasBuff.length, .isAlias = true }; + Uint8Buff peerPkBuff = { 0 }; ret = GetPeerPubKeyFromCert(peerCertInfo, &peerPkBuff); if (ret != HC_SUCCESS) { HcFree(priAliasVal); return ret; } - KeyBuff publicKeyBuff = { - .key = peerPkBuff.val, - .keyLen = peerPkBuff.length, - .isAlias = false - }; + KeyBuff publicKeyBuff = { .key = peerPkBuff.val, .keyLen = peerPkBuff.length, .isAlias = false }; uint32_t sharedKeyAliasLen = HcStrlen(SHARED_KEY_ALIAS) + 1; sharedSecret->val = (uint8_t *)HcMalloc(sharedKeyAliasLen, 0); @@ -189,8 +270,8 @@ static int32_t GetSharedSecretForAccountInPake(const char *userId, const char *a } sharedSecret->length = sharedKeyAliasLen; (void)memcpy_s(sharedSecret->val, sharedKeyAliasLen, SHARED_KEY_ALIAS, sharedKeyAliasLen); - ret = GetLoaderInstance()->agreeSharedSecretWithStorage(&priAliasKeyBuff, &publicKeyBuff, - P256, P256_SHARED_SECRET_KEY_SIZE, sharedSecret); + ret = GetLoaderInstance()->agreeSharedSecretWithStorage( + &priAliasKeyBuff, &publicKeyBuff, P256, P256_SHARED_SECRET_KEY_SIZE, sharedSecret); HcFree(priAliasVal); ClearFreeUint8Buff(&peerPkBuff); if (ret != HC_SUCCESS) { @@ -255,8 +336,8 @@ static int32_t GetCertInfo(int32_t osAccountId, const char *userId, const char * return HC_SUCCESS; } -static int32_t GetAccountAsymIdentityInfo(int32_t osAccountId, const char *userId, const char *authId, - IdentityInfo *info, bool isNeedGeneratePdid) +static int32_t GetAccountAsymIdentityInfo( + int32_t osAccountId, const char *userId, const char *authId, IdentityInfo *info, bool isNeedGeneratePdid) { int32_t ret = GetCertInfo(osAccountId, userId, authId, &info->proof.certInfo); if (ret != HC_SUCCESS) { @@ -288,8 +369,7 @@ static int32_t GetAccountAsymIdentityInfo(int32_t osAccountId, const char *userI return HC_SUCCESS; } -static int32_t GetLocalDeviceType(int32_t osAccountId, const CJson *in, const char *groupId, - int32_t *localDevType) +static int32_t GetLocalDeviceType(int32_t osAccountId, const CJson *in, const char *groupId, int32_t *localDevType) { TrustedDeviceEntry *deviceEntry = CreateDeviceEntry(); if (deviceEntry == NULL) { @@ -353,8 +433,8 @@ static int32_t GenerateAuthTokenForAccessory(int32_t osAccountId, const char *gr return ret; } -static int32_t GenerateTokenAliasForController(int32_t osAccountId, const CJson *in, const char *groupId, - Uint8Buff *authTokenAlias) +static int32_t GenerateTokenAliasForController( + int32_t osAccountId, const CJson *in, const char *groupId, Uint8Buff *authTokenAlias) { TrustedDeviceEntry *deviceEntry = CreateDeviceEntry(); if (deviceEntry == NULL) { @@ -385,8 +465,8 @@ static int32_t GenerateTokenAliasForController(int32_t osAccountId, const CJson return ret; } -static int32_t GenerateAuthTokenByDevType(const CJson *in, const CJson *urlJson, Uint8Buff *authToken, - bool *isTokenStored) +static int32_t GenerateAuthTokenByDevType( + const CJson *in, const CJson *urlJson, Uint8Buff *authToken, bool *isTokenStored) { int32_t osAccountId = INVALID_OS_ACCOUNT; if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { @@ -413,8 +493,8 @@ static int32_t GenerateAuthTokenByDevType(const CJson *in, const CJson *urlJson, return ret; } -static int32_t GetSelfAccountIdentityInfo(int32_t osAccountId, const char *groupId, IdentityInfo *info, - bool isNeedGeneratePdid) +static int32_t GetSelfAccountIdentityInfo( + int32_t osAccountId, const char *groupId, IdentityInfo *info, bool isNeedGeneratePdid) { TrustedDeviceEntry *deviceEntry = CreateDeviceEntry(); if (deviceEntry == NULL) { @@ -462,8 +542,8 @@ static bool isNeedGeneratePdidByPeerCert(int32_t osAccountId, const CertInfo *ce #endif } -int32_t GetAccountRelatedCredInfo(int32_t osAccountId, const char *groupId, const char *deviceId, - bool isUdid, IdentityInfo *info) +int32_t GetAccountRelatedCredInfo( + int32_t osAccountId, const char *groupId, const char *deviceId, bool isUdid, IdentityInfo *info) { if (groupId == NULL || deviceId == NULL || info == NULL) { LOGE("Invalid input params!"); @@ -501,8 +581,8 @@ int32_t GetAccountRelatedCredInfo(int32_t osAccountId, const char *groupId, cons } } -static int32_t GetSharedSecretByPeerCertFromPlugin(int32_t osAccountId, const CertInfo *peerCertInfo, - Uint8Buff *sharedSecret) +static int32_t GetSharedSecretByPeerCertFromPlugin( + int32_t osAccountId, const CertInfo *peerCertInfo, Uint8Buff *sharedSecret) { CJson *input = CreateJson(); if (input == NULL) { diff --git a/services/identity_manager/src/credential_operator.c b/services/identity_manager/src/credential_operator.c new file mode 100644 index 00000000..17c10edd --- /dev/null +++ b/services/identity_manager/src/credential_operator.c @@ -0,0 +1,667 @@ +/* + * Copyright (C) 2023 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 "alg_defs.h" +#include "alg_loader.h" +#include "das_standard_token_manager.h" +#include "hc_dev_info.h" +#include "hc_log.h" +#include "identity_manager.h" +#include "os_account_adapter.h" + +typedef struct { + int32_t osAccountId; + int32_t acquireType; + char *deviceId; + int32_t flag; + Uint8Buff *publicKey; + char *serviceType; +} CredentialRequestParamT; + +static int32_t CombineServiceId(const Uint8Buff *pkgName, const Uint8Buff *serviceType, Uint8Buff *serviceId) +{ + int32_t res = HC_SUCCESS; + Uint8Buff serviceIdPlain = { NULL, 0 }; + serviceIdPlain.length = pkgName->length + serviceType->length; + serviceIdPlain.val = (uint8_t *)HcMalloc(serviceIdPlain.length, 0); + if (serviceIdPlain.val == NULL) { + LOGE("malloc serviceIdPlain.val failed."); + res = HC_ERR_ALLOC_MEMORY; + goto ERR; + } + if (memcpy_s(serviceIdPlain.val, serviceIdPlain.length, pkgName->val, pkgName->length) != EOK) { + LOGE("Copy service id: pkgName failed."); + res = HC_ERR_MEMORY_COPY; + goto ERR; + } + if (memcpy_s(serviceIdPlain.val + pkgName->length, serviceIdPlain.length - pkgName->length, serviceType->val, + serviceType->length) != EOK) { + LOGE("Copy service id: serviceType failed."); + res = HC_ERR_MEMORY_COPY; + goto ERR; + } + res = GetLoaderInstance()->sha256(&serviceIdPlain, serviceId); + if (res != HC_SUCCESS) { + LOGE("Service id Sha256 failed."); + goto ERR; + } +ERR: + HcFree(serviceIdPlain.val); + return res; +} + +static int32_t CombineKeyAlias( + const Uint8Buff *serviceId, const Uint8Buff *keyType, const Uint8Buff *authId, Uint8Buff *keyAliasHash) +{ + int32_t res = HC_SUCCESS; + Uint8Buff keyAliasBuff = { NULL, 0 }; + keyAliasBuff.length = serviceId->length + authId->length + keyType->length; + keyAliasBuff.val = (uint8_t *)HcMalloc(keyAliasBuff.length, 0); + if (keyAliasBuff.val == NULL) { + LOGE("Malloc mem failed."); + return HC_ERR_ALLOC_MEMORY; + } + uint32_t totalLen = keyAliasBuff.length; + uint32_t usedLen = 0; + if (memcpy_s(keyAliasBuff.val, totalLen, serviceId->val, serviceId->length) != EOK) { + LOGE("Copy serviceId failed."); + res = HC_ERR_MEMORY_COPY; + goto ERR; + } + usedLen = usedLen + serviceId->length; + if (memcpy_s(keyAliasBuff.val + usedLen, totalLen - usedLen, keyType->val, keyType->length) != EOK) { + LOGE("Copy keyType failed."); + res = HC_ERR_MEMORY_COPY; + goto ERR; + } + usedLen = usedLen + keyType->length; + if (memcpy_s(keyAliasBuff.val + usedLen, totalLen - usedLen, authId->val, authId->length) != EOK) { + LOGE("Copy authId failed."); + res = HC_ERR_MEMORY_COPY; + goto ERR; + } + res = GetLoaderInstance()->sha256(&keyAliasBuff, keyAliasHash); + if (res != HC_SUCCESS) { + LOGE("Sha256 failed."); + goto ERR; + } +ERR: + HcFree(keyAliasBuff.val); + return res; +} + +static int32_t CombineKeyAliasForPake( + const Uint8Buff *serviceId, const Uint8Buff *keyType, const Uint8Buff *authId, Uint8Buff *outKeyAlias) +{ + int32_t res; + Uint8Buff keyAliasHash = { NULL, SHA256_LEN }; + char *outKeyAliasHex = NULL; + if (outKeyAlias->length != SHA256_LEN * BYTE_TO_HEX_OPER_LENGTH) { + res = HC_ERR_INVALID_LEN; + goto ERR; + } + keyAliasHash.val = (uint8_t *)HcMalloc(keyAliasHash.length, 0); + if (keyAliasHash.val == NULL) { + LOGE("Malloc keyAliasHash failed"); + res = HC_ERR_ALLOC_MEMORY; + goto ERR; + } + res = CombineKeyAlias(serviceId, keyType, authId, &keyAliasHash); + if (res != HC_SUCCESS) { + LOGE("CombineKeyAlias failed."); + goto ERR; + } + uint32_t outKeyAliasHexLen = keyAliasHash.length * BYTE_TO_HEX_OPER_LENGTH + 1; + outKeyAliasHex = (char *)HcMalloc(outKeyAliasHexLen, 0); + res = ByteToHexString(keyAliasHash.val, keyAliasHash.length, outKeyAliasHex, outKeyAliasHexLen); + if (res != HC_SUCCESS) { + LOGE("ByteToHexString failed"); + goto ERR; + } + if (memcpy_s(outKeyAlias->val, outKeyAlias->length, outKeyAliasHex, strlen(outKeyAliasHex)) != EOK) { + LOGE("memcpy outkeyalias failed."); + res = HC_ERR_MEMORY_COPY; + goto ERR; + } +ERR: + HcFree(keyAliasHash.val); + HcFree(outKeyAliasHex); + return res; +} + +static int32_t GenerateKeyAliasInner( + const char *pkgName, const char *serviceType, const char *authId, int keyAliasType, Uint8Buff *outKeyAlias) +{ + CHECK_PTR_RETURN_ERROR_CODE(pkgName, "pkgName"); + CHECK_PTR_RETURN_ERROR_CODE(serviceType, "serviceType"); + CHECK_PTR_RETURN_ERROR_CODE(authId, "authId"); + CHECK_PTR_RETURN_ERROR_CODE(outKeyAlias, "outKeyAlias"); + if (strlen(pkgName) == 0 || strlen(serviceType) == 0 || strlen(authId) == 0) { + LOGE("Invalid zero length params exist."); + return HC_ERR_INVALID_LEN; + } + Uint8Buff pkgNameBuff = { (uint8_t *)pkgName, strlen(pkgName) }; + Uint8Buff serviceTypeBuff = { (uint8_t *)serviceType, strlen(serviceType) }; + Uint8Buff authIdBuff = { NULL, HcStrlen(authId) }; + authIdBuff.val = (uint8_t *)HcMalloc(authIdBuff.length, 0); + if (authIdBuff.val == NULL) { + LOGE("Failed to allocate authIdBuff memory!"); + return HC_ERR_ALLOC_MEMORY; + } + if (memcpy_s(authIdBuff.val, authIdBuff.length, authId, authIdBuff.length) != EOK) { + LOGE("Failed to copy authId!"); + HcFree(authIdBuff.val); + return HC_ERR_MEMORY_COPY; + } + if (pkgNameBuff.length > PACKAGE_NAME_MAX_LEN || serviceTypeBuff.length > SERVICE_TYPE_MAX_LEN || + authIdBuff.length > AUTH_ID_MAX_LEN || keyAliasType >= KEY_ALIAS_TYPE_END) { + LOGE("Out of length params exist."); + HcFree(authIdBuff.val); + return HC_ERR_INVALID_LEN; + } + + int32_t res; + Uint8Buff serviceId = { NULL, SHA256_LEN }; + serviceId.val = (uint8_t *)HcMalloc(serviceId.length, 0); + if (serviceId.val == NULL) { + LOGE("Malloc for serviceId failed."); + HcFree(authIdBuff.val); + HcFree(serviceId.val); + return HC_ERR_ALLOC_MEMORY; + } + res = CombineServiceId(&pkgNameBuff, &serviceTypeBuff, &serviceId); + if (res != HC_SUCCESS) { + LOGE("CombineServiceId failed, res: %x.", res); + HcFree(authIdBuff.val); + HcFree(serviceId.val); + return res; + } + + Uint8Buff keyTypeBuff = { GetKeyTypePair(keyAliasType), KEY_TYPE_PAIR_LEN }; + res = CombineKeyAliasForPake(&serviceId, &keyTypeBuff, &authIdBuff, outKeyAlias); + if (res != HC_SUCCESS) { + LOGE("CombineKeyAlias failed, keyType: %d, res: %d", keyAliasType, res); + HcFree(authIdBuff.val); + HcFree(serviceId.val); + return res; + } + + HcFree(authIdBuff.val); + HcFree(serviceId.val); + return res; +} + +static void FreeCredParam(CredentialRequestParamT *param) +{ + if (param) { + HcFree(param->deviceId); + param->deviceId = NULL; + + HcFree(param->serviceType); + param->serviceType = NULL; + + if (param->publicKey) { + if (param->publicKey->val) { + HcFree(param->publicKey->val); + } + HcFree(param->publicKey); + param->publicKey = NULL; + } + + HcFree(param); + param = NULL; + } +} + +static int32_t DecodeServiceTypeAndPublicKey(CredentialRequestParamT *param, CJson *reqJson) +{ + if (!param || !reqJson) { + LOGE("reqJson and param must not null ! "); + return HC_ERR_INVALID_PARAMS; + } + + const char *serviceType = GetStringFromJson(reqJson, FIELD_SERVICE_TYPE); + if (serviceType == NULL) { + param->serviceType = strdup(DEFAULT_SERVICE_TYPE); + } else { + param->serviceType = strdup(serviceType); + } + + const char *publicKeyStr = GetStringFromJson(reqJson, FIELD_PUBLIC_KEY); + if (publicKeyStr != NULL && HcStrlen(publicKeyStr) > 0) { + if (HcStrlen(publicKeyStr) > PAKE_ED25519_KEY_STR_LEN) { + LOGE("public key longer then %d.", PAKE_ED25519_KEY_STR_LEN); + return HC_ERR_INVALID_LEN; + } + param->publicKey = (Uint8Buff *)HcMalloc(sizeof(Uint8Buff), 0); + int32_t res = InitUint8Buff(param->publicKey, PAKE_ED25519_KEY_PAIR_LEN); + if (res != HC_SUCCESS) { + LOGE("allocate publicKey memory fail. res: %d", res); + return HC_ERR_ALLOC_MEMORY; + } + if (GetByteFromJson(reqJson, FIELD_PUBLIC_KEY, param->publicKey->val, param->publicKey->length) != + HC_SUCCESS) { + LOGE("get authPkC from reqJson fail."); + return HC_ERR_JSON_GET; + } else { + LOGI("decode publicKey success."); + } + } else { + param->publicKey = NULL; + } + + return HC_SUCCESS; +} + +static CredentialRequestParamT *DecodeRequestParam(const char *reqJsonStr) +{ + if (!reqJsonStr) { + LOGE("reqJsonStr must not null ! "); + return NULL; + } + CredentialRequestParamT *param = (CredentialRequestParamT *)HcMalloc(sizeof(CredentialRequestParamT), 0); + if (param == NULL) { + LOGE("Failed to ALLOC!"); + return NULL; + } + CJson *json = CreateJsonFromString(reqJsonStr); + if (json == NULL) { + LOGE("Failed to create json from string!"); + FreeCredParam(param); + param = NULL; + goto ERR; + } + if (GetIntFromJson(json, FIELD_OS_ACCOUNT_ID, ¶m->osAccountId) != HC_SUCCESS) { + LOGE("Failed to get osAccountId from reqJsonStr!"); + FreeCredParam(param); + param = NULL; + goto ERR; + } + if (GetIntFromJson(json, FIELD_ACQURIED_TYPE, ¶m->acquireType) != HC_SUCCESS) { + LOGE("Failed to get acquireType from reqJsonStr!"); + FreeCredParam(param); + param = NULL; + goto ERR; + } + if (GetIntFromJson(json, FIELD_CRED_OP_FLAG, ¶m->flag) != HC_SUCCESS) { + LOGI("reqJsonStr not contains flag!"); + } + const char *deviceId = GetStringFromJson(json, FIELD_DEVICE_ID); + if (deviceId == NULL) { + LOGE("Failed to get deviceId from reqJsonStr!"); + FreeCredParam(param); + param = NULL; + goto ERR; + } else { + param->deviceId = strdup(deviceId); + } + if (DecodeServiceTypeAndPublicKey(param, json) != HC_SUCCESS) { + LOGE("Failed to DecodeServiceTypeAndPublicKey from reqJsonStr!"); + goto ERR; + } +ERR: + FreeJson(json); + return param; +} + +static int32_t PackPublicKeyToJson( + CJson *out, int32_t osAccountId, int32_t keyType, const char *authId, const char *serviceType) +{ + osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId); + if ((authId == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) { + LOGE("Invalid input parameters!"); + return HC_ERR_INVALID_PARAMS; + } + Uint8Buff authIdBuff = { (uint8_t *)authId, HcStrlen(authId) }; + uint8_t returnPkBytes[PUBLIC_KEY_MAX_LENGTH] = { 0 }; + Uint8Buff returnPkBuff = { returnPkBytes, PUBLIC_KEY_MAX_LENGTH }; + int32_t res = GetStandardTokenManagerInstance()->getPublicKey( + DEFAULT_PACKAGE_NAME, serviceType, &authIdBuff, keyType, &returnPkBuff); + if (res != HC_SUCCESS) { + LOGE("Failed to getPublicKey!"); + return HC_ERR_LOCAL_IDENTITY_NOT_EXIST; + } + + char returnPkHexStr[SHA256_LEN * BYTE_TO_HEX_OPER_LENGTH + 1] = { 0 }; + res = ByteToHexString(returnPkBuff.val, returnPkBuff.length, returnPkHexStr, sizeof(returnPkHexStr)); + if (res != HC_SUCCESS) { + LOGE("Failed to get hex str for pk!"); + return HC_ERR_HASH_FAIL; + } + + if (AddStringToJson(out, FIELD_PUBLIC_KEY, (const char *)returnPkHexStr) != HC_SUCCESS) { + LOGE("Failed to ADD pubKey to returnData!"); + return HC_ERR_JSON_ADD; + } + return HC_SUCCESS; +} + +static char *PackResultToJson(CJson *out, int32_t res) +{ + if (out == NULL) { + LOGE("param is null !"); + return NULL; + } + if (AddIntToJson(out, FIELD_CRED_OP_RESULT, res) != HC_SUCCESS) { + LOGE("Failed to set result to json"); + return NULL; + } + + return PackJsonToString(out); +} + +static int32_t QueryCredential(const char *reqJsonStr, char **returnData) +{ + int32_t res; + CJson *out = CreateJson(); + if (out == NULL) { + LOGE("Failed to CreateJson!"); + return HC_ERR_JSON_CREATE; + } + CredentialRequestParamT *param = DecodeRequestParam(reqJsonStr); + if (param == NULL) { + LOGE("Failed to DecodeCredParam from reqJsonStr!"); + res = HC_ERR_JSON_GET; + goto ERR; + } + int32_t osAccountId = param->osAccountId; + int32_t keyType = (param->acquireType == P2P_BIND) ? KEY_ALIAS_P2P_AUTH : param->acquireType; + const char *serviceType = param->serviceType; + const char *authId = param->deviceId; + int32_t flag = param->flag; + osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId); + if ((authId == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) { + LOGE("Invalid input parameters!"); + res = HC_ERR_INVALID_PARAMS; + goto ERR; + } + const AlgLoader *loader = GetLoaderInstance(); + uint8_t keyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 }; + Uint8Buff keyAliasBuff = { keyAliasVal, PAKE_KEY_ALIAS_LEN }; + res = GenerateKeyAliasInner(DEFAULT_PACKAGE_NAME, serviceType, authId, keyType, &keyAliasBuff); + if (res != HC_SUCCESS) { + LOGE("Failed to generate identity keyPair alias!"); + goto ERR; + } + LOGI("KeyPair alias(HEX): %x%x%x%x****.", keyAliasVal[DEV_AUTH_ZERO], keyAliasVal[DEV_AUTH_ONE], + keyAliasVal[DEV_AUTH_TWO], keyAliasVal[DEV_AUTH_THREE]); + + res = loader->checkKeyExist(&keyAliasBuff); + if (res != HC_SUCCESS) { + LOGD("Key pair not exist."); + res = HC_ERR_LOCAL_IDENTITY_NOT_EXIST; + goto ERR; + } + if (RETURN_FLAG_PUBLIC_KEY == flag) { + res = PackPublicKeyToJson(out, osAccountId, keyType, authId, serviceType); + if (res != HC_SUCCESS) { + LOGD("PackPublicKeyToJson failed"); + goto ERR; + } + } +ERR: + if (returnData) { + *returnData = PackResultToJson(out, res); + } + FreeJson(out); + FreeCredParam(param); + return res; +} + +static int32_t GenarateCredential(const char *reqJsonStr, char **returnData) +{ + int32_t res; + CJson *out = CreateJson(); + if (out == NULL) { + LOGE("Failed to CreateJson!"); + return HC_ERR_JSON_CREATE; + } + CredentialRequestParamT *param = DecodeRequestParam(reqJsonStr); + if (param == NULL) { + LOGE("Failed to DecodeCredParam from reqJsonStr!"); + res = HC_ERR_INVALID_PARAMS; + goto ERR; + } + int32_t osAccountId = param->osAccountId; + int32_t keyType = (param->acquireType == P2P_BIND) ? KEY_ALIAS_P2P_AUTH : param->acquireType; + const char *serviceType = param->serviceType; + const char *authId = param->deviceId; + int32_t flag = param->flag; + osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId); + if ((authId == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) { + LOGE("Invalid input parameters!"); + res = HC_ERR_INVALID_PARAMS; + goto ERR; + } + const AlgLoader *loader = GetLoaderInstance(); + uint8_t keyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 }; + Uint8Buff keyAliasBuff = { keyAliasVal, PAKE_KEY_ALIAS_LEN }; + res = GenerateKeyAliasInner(DEFAULT_PACKAGE_NAME, serviceType, authId, keyType, &keyAliasBuff); + if (res != HC_SUCCESS) { + LOGE("Failed to generate identity keyPair alias!"); + goto ERR; + } + LOGI("KeyPair alias(HEX): %x%x%x%x****.", keyAliasVal[DEV_AUTH_ZERO], keyAliasVal[DEV_AUTH_ONE], + keyAliasVal[DEV_AUTH_TWO], keyAliasVal[DEV_AUTH_THREE]); + + res = loader->checkKeyExist(&keyAliasBuff); + if (res == HC_SUCCESS) { + LOGD("Key pair already exist."); + res = HC_ERR_IDENTITY_DUPLICATED; + goto ERR; + } + Uint8Buff authIdBuff = { (uint8_t *)authId, HcStrlen(authId) }; + res = GetStandardTokenManagerInstance()->registerLocalIdentity( + DEFAULT_PACKAGE_NAME, serviceType, &authIdBuff, keyType); + if (res != HC_SUCCESS) { + LOGE("Failed to registerLocalIdentity!"); + goto ERR; + } + if (RETURN_FLAG_PUBLIC_KEY == flag) { + res = PackPublicKeyToJson(out, osAccountId, keyType, authId, serviceType); + if (res != HC_SUCCESS) { + LOGE("PackPublicKeyToJson failed"); + goto ERR; + } + } +ERR: + if (returnData) { + *returnData = PackResultToJson(out, res); + } + FreeJson(out); + FreeCredParam(param); + + return res; +} + +static int32_t ComputeAndSavePsk(const char *peerServiceType, const char *peerAuthId, int keyType) +{ + uint8_t selfKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 }; + Uint8Buff selfKeyAlias = { selfKeyAliasVal, PAKE_KEY_ALIAS_LEN }; + uint8_t peerKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 }; + Uint8Buff peerKeyAlias = { peerKeyAliasVal, PAKE_KEY_ALIAS_LEN }; + + char selfAuthId[INPUT_UDID_LEN] = { 0 }; + int32_t res = HcGetUdid((uint8_t *)selfAuthId, INPUT_UDID_LEN); + if (res != HC_SUCCESS) { + LOGE("Failed to get local udid! res: %d", res); + return HC_ERR_DB; + } + + res = GenerateKeyAliasInner(DEFAULT_PACKAGE_NAME, DEFAULT_SERVICE_TYPE, selfAuthId, keyType, &selfKeyAlias); + if (res != HC_SUCCESS) { + LOGE("generateKeyAlias self failed"); + return res; + } + LOGI("selfKeyAlias(HEX): %x%x%x%x****", selfKeyAliasVal[DEV_AUTH_ZERO], selfKeyAliasVal[DEV_AUTH_ONE], + selfKeyAliasVal[DEV_AUTH_TWO], selfKeyAliasVal[DEV_AUTH_THREE]); + + res = GenerateKeyAliasInner(DEFAULT_PACKAGE_NAME, peerServiceType, peerAuthId, keyType, &peerKeyAlias); + if (res != HC_SUCCESS) { + LOGE("generateKeyAlias peer failed"); + return res; + } + LOGI("peerKeyAlias(HEX): %x%x%x%x****", peerKeyAliasVal[DEV_AUTH_ZERO], peerKeyAliasVal[DEV_AUTH_ONE], + peerKeyAliasVal[DEV_AUTH_TWO], peerKeyAliasVal[DEV_AUTH_THREE]); + res = GetLoaderInstance()->checkKeyExist(&selfKeyAlias); + if (res != HC_SUCCESS) { + LOGE("self auth keyPair not exist ."); + return res; + } + res = GetLoaderInstance()->checkKeyExist(&peerKeyAlias); + if (res != HC_SUCCESS) { + LOGE("peer auth pubKey not exist"); + return res; + } + + uint8_t sharedKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 }; + Uint8Buff sharedKeyAlias = { sharedKeyAliasVal, PAKE_KEY_ALIAS_LEN }; + res = GenerateKeyAliasInner(DEFAULT_PACKAGE_NAME, peerServiceType, peerAuthId, KEY_ALIAS_PSK, &sharedKeyAlias); + if (res != HC_SUCCESS) { + LOGE("generateKeyAlias psk failed"); + return res; + } + LOGI("psk alias(HEX): %x%x%x%x****", sharedKeyAliasVal[DEV_AUTH_ZERO], sharedKeyAliasVal[DEV_AUTH_ONE], + sharedKeyAliasVal[DEV_AUTH_TWO], sharedKeyAliasVal[DEV_AUTH_THREE]); + + KeyBuff selfKeyAliasBuff = { selfKeyAlias.val, selfKeyAlias.length, true }; + KeyBuff peerKeyAliasBuff = { peerKeyAlias.val, peerKeyAlias.length, true }; + return GetLoaderInstance()->agreeSharedSecretWithStorage( + &selfKeyAliasBuff, &peerKeyAliasBuff, ED25519, PAKE_PSK_LEN, &sharedKeyAlias); +} + +static int32_t ImportCredential(const char *reqJsonStr, char **returnData) +{ + int32_t res; + CJson *out = CreateJson(); + if (out == NULL) { + LOGE("Failed to CreateJson!"); + return HC_ERR_JSON_CREATE; + } + CredentialRequestParamT *param = DecodeRequestParam(reqJsonStr); + if (param == NULL || param->publicKey == NULL) { + LOGE("Failed to DecodeCredParam from reqJsonStr!"); + res = HC_ERR_JSON_GET; + goto ERR; + } + int32_t osAccountId = param->osAccountId; + int32_t keyType = (param->acquireType == P2P_BIND) ? KEY_ALIAS_P2P_AUTH : param->acquireType; + const char *serviceType = param->serviceType; + const char *authId = param->deviceId; + Uint8Buff *publicKey = param->publicKey; + osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId); + if ((authId == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) { + LOGE("Invalid input parameters!"); + return HC_ERR_INVALID_PARAMS; + } + const AlgLoader *loader = GetLoaderInstance(); + uint8_t keyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 }; + Uint8Buff keyAliasBuff = { keyAliasVal, PAKE_KEY_ALIAS_LEN }; + res = GenerateKeyAliasInner(DEFAULT_PACKAGE_NAME, serviceType, authId, keyType, &keyAliasBuff); + if (res != HC_SUCCESS) { + LOGE("Failed to generate identity keyPair alias!"); + goto ERR; + } + LOGI("KeyPair alias(HEX): %x%x%x%x****.", keyAliasVal[DEV_AUTH_ZERO], keyAliasVal[DEV_AUTH_ONE], + keyAliasVal[DEV_AUTH_TWO], keyAliasVal[DEV_AUTH_THREE]); + res = loader->checkKeyExist(&keyAliasBuff); + if (res == HC_SUCCESS) { + LOGD("Key pair already exist."); + res = HC_ERR_IDENTITY_DUPLICATED; + goto ERR; + } + Uint8Buff authIdBuff = { (uint8_t *)authId, strlen(authId) }; + ExtraInfo exInfo = { authIdBuff, keyType, PAIR_TYPE_BIND }; + res = loader->importPublicKey(&keyAliasBuff, publicKey, ED25519, &exInfo); + if (res != HC_SUCCESS) { + LOGE("Failed to importPublicKey!"); + goto ERR; + } + res = ComputeAndSavePsk(serviceType, authId, keyType); + if (res != HC_SUCCESS) { + LOGE("Failed to ComputeAndSavePsk!"); + goto ERR; + } + +ERR: + if (returnData) { + *returnData = PackResultToJson(out, res); + } + FreeJson(out); + FreeCredParam(param); + return res; +} + +static int32_t DeleteCredential(const char *reqJsonStr, char **returnData) +{ + int32_t res; + CJson *out = CreateJson(); + if (out == NULL) { + LOGE("Failed to CreateJson!"); + return HC_ERR_JSON_CREATE; + } + CredentialRequestParamT *param = DecodeRequestParam(reqJsonStr); + if (param == NULL) { + LOGE("Failed to DecodeCredParam from reqJsonStr!"); + res = HC_ERR_JSON_GET; + goto ERR; + } + int32_t osAccountId = param->osAccountId; + int32_t keyType = (param->acquireType == P2P_BIND) ? KEY_ALIAS_P2P_AUTH : param->acquireType; + const char *serviceType = param->serviceType; + const char *authId = param->deviceId; + osAccountId = DevAuthGetRealOsAccountLocalId(osAccountId); + if ((authId == NULL) || (osAccountId == INVALID_OS_ACCOUNT)) { + LOGE("Invalid input parameters!"); + res = HC_ERR_INVALID_PARAMS; + goto ERR; + } + Uint8Buff authIdBuff = { (uint8_t *)authId, strlen(authId) }; + res = GetStandardTokenManagerInstance()->unregisterLocalIdentity( + DEFAULT_PACKAGE_NAME, serviceType, &authIdBuff, KEY_ALIAS_PSK); + if (res != HC_SUCCESS) { + LOGE("Failed to delete psk!"); + goto ERR; + } + LOGI("Psk deleted successfully!"); + + res = GetStandardTokenManagerInstance()->unregisterLocalIdentity( + DEFAULT_PACKAGE_NAME, serviceType, &authIdBuff, keyType); + if (res != HC_SUCCESS) { + LOGE("Failed to delete identity keyPair!"); + goto ERR; + } + LOGI("PubKey deleted successfully!"); + +ERR: + if (returnData) { + *returnData = PackResultToJson(out, res); + } + FreeJson(out); + FreeCredParam(param); + return res; +} + +static const CredentialOperator g_credentialOperator = { + .queryCredential = QueryCredential, + .genarateCredential = GenarateCredential, + .importCredential = ImportCredential, + .deleteCredential = DeleteCredential, +}; + +const CredentialOperator *GetCredentialOperator(void) +{ + return &g_credentialOperator; +} \ No newline at end of file diff --git a/services/identity_manager/src/identity_common.c b/services/identity_manager/src/identity_common.c new file mode 100644 index 00000000..0eee0054 --- /dev/null +++ b/services/identity_manager/src/identity_common.c @@ -0,0 +1,189 @@ +/* + * Copyright (C) 2023 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 "group_auth_data_operation.h" +#include "hc_dev_info.h" +#include "hc_log.h" +#include "hc_vector.h" +#include "identity_manager.h" + +static void UpperToLowercase(Uint8Buff *hex) +{ + for (uint32_t i = 0; i < hex->length; i++) { + if (hex->val[i] >= 'A' && hex->val[i] <= 'F') { + hex->val[i] += ASCII_CASE_DIFFERENCE_VALUE; + } + } +} + +int32_t ConvertPsk(const Uint8Buff *srcPsk, Uint8Buff *sharedSecret) +{ + uint32_t len = PAKE_PSK_LEN * BYTE_TO_HEX_OPER_LENGTH; + sharedSecret->val = (uint8_t *)HcMalloc(len + 1, 0); + if (sharedSecret->val == NULL) { + LOGE("Failed to alloc memory for sharedSecret!"); + return HC_ERR_ALLOC_MEMORY; + } + + if (ByteToHexString(srcPsk->val, srcPsk->length, (char *)sharedSecret->val, len + 1) != HC_SUCCESS) { + LOGE("Convert psk from byte to hex string failed!"); + HcFree(sharedSecret->val); + return HC_ERR_CONVERT_FAILED; + } + sharedSecret->length = len; + (void)UpperToLowercase(sharedSecret); + return HC_SUCCESS; +} + +int32_t SetPreSharedUrlForProof(const char *urlStr, Uint8Buff *preSharedUrl) +{ + uint32_t urlLen = HcStrlen(urlStr); + preSharedUrl->val = (uint8_t *)HcMalloc(urlLen + 1, 0); + if (preSharedUrl->val == NULL) { + LOGE("Failed to alloc preSharedUrl memory!"); + return HC_ERR_ALLOC_MEMORY; + } + if (memcpy_s(preSharedUrl->val, urlLen + 1, urlStr, urlLen) != EOK) { + LOGE("Failed to copy url string to preSharedUrl"); + HcFree(preSharedUrl->val); + preSharedUrl->val = NULL; + return HC_ERR_MEMORY_COPY; + } + preSharedUrl->length = urlLen + 1; + return HC_SUCCESS; +} + +CJson *CreateCredUrlJson(int32_t credentailType, int32_t keyType, int32_t trustType) +{ + CJson *urlJson = CreateJson(); + if (urlJson == NULL) { + LOGE("Failed to create url json!"); + return NULL; + } + if (AddIntToJson(urlJson, PRESHARED_URL_CREDENTIAL_TYPE, credentailType) != HC_SUCCESS) { + LOGE("Failed to add credential type!"); + FreeJson(urlJson); + return NULL; + } + if (AddIntToJson(urlJson, PRESHARED_URL_KEY_TYPE, keyType) != HC_SUCCESS) { + LOGE("Failed to add key type!"); + FreeJson(urlJson); + return NULL; + } + if (AddIntToJson(urlJson, PRESHARED_URL_TRUST_TYPE, trustType) != HC_SUCCESS) { + LOGE("Failed to add trust type!"); + FreeJson(urlJson); + return NULL; + } + + return urlJson; +} + +#if 1 + +IMPLEMENT_HC_VECTOR(ProtocolEntityVec, ProtocolEntity *, 1) +IMPLEMENT_HC_VECTOR(IdentityInfoVec, IdentityInfo *, 1) + +int32_t GetSelfDeviceEntry(int32_t osAccountId, const char *groupId, TrustedDeviceEntry *deviceEntry) +{ + char selfUdid[INPUT_UDID_LEN] = { 0 }; + int32_t ret = HcGetUdid((uint8_t *)selfUdid, INPUT_UDID_LEN); + if (ret != HC_SUCCESS) { + LOGE("Failed to get local udid!"); + return ret; + } + return GaGetTrustedDeviceEntryById(osAccountId, selfUdid, true, groupId, deviceEntry); +} + +const char *GetPeerDevIdFromJson(const CJson *in, bool *isUdid) +{ + const char *deviceId = GetStringFromJson(in, FIELD_PEER_UDID); + if (deviceId != NULL) { + *isUdid = true; + return deviceId; + } + return GetStringFromJson(in, FIELD_PEER_AUTH_ID); +} + +int32_t GetPeerDeviceEntry( + int32_t osAccountId, const CJson *in, const char *groupId, TrustedDeviceEntry *returnDeviceEntry) +{ + bool isUdid = false; + const char *peerDeviceId = GetPeerDevIdFromJson(in, &isUdid); + if (peerDeviceId == NULL) { + LOGE("Failed to get peer deviceId!"); + return HC_ERR_JSON_GET; + } + return GaGetTrustedDeviceEntryById(osAccountId, peerDeviceId, isUdid, groupId, returnDeviceEntry); +} + +void FreeBuffData(Uint8Buff *buff) +{ + if (buff == NULL) { + return; + } + HcFree(buff->val); + buff->val = NULL; + buff->length = 0; +} + +IdentityInfo *CreateIdentityInfo(void) +{ + IdentityInfo *info = (IdentityInfo *)HcMalloc(sizeof(IdentityInfo), 0); + if (info == NULL) { + LOGE("Failed to alloc memory for identity info!"); + return NULL; + } + info->protocolVec = CreateProtocolEntityVec(); + return info; +} + +void DestroyIdentityInfo(IdentityInfo *info) +{ + if (info == NULL) { + return; + } + + FreeBuffData(&info->proof.preSharedUrl); + FreeBuffData(&info->proof.certInfo.pkInfoStr); + FreeBuffData(&info->proof.certInfo.pkInfoSignature); + ClearProtocolEntityVec(&info->protocolVec); + + HcFree(info); +} + +void ClearIdentityInfoVec(IdentityInfoVec *vec) +{ + uint32_t index; + IdentityInfo **info; + FOR_EACH_HC_VECTOR(*vec, index, info) + { + DestroyIdentityInfo(*info); + } + DESTROY_HC_VECTOR(IdentityInfoVec, vec); +} + +void ClearProtocolEntityVec(ProtocolEntityVec *vec) +{ + uint32_t index; + ProtocolEntity **entity; + FOR_EACH_HC_VECTOR(*vec, index, entity) + { + HcFree(*entity); + } + DESTROY_HC_VECTOR(ProtocolEntityVec, vec); +} + +#endif \ No newline at end of file diff --git a/services/identity_manager/src/identity_group.c b/services/identity_manager/src/identity_group.c new file mode 100644 index 00000000..5763336e --- /dev/null +++ b/services/identity_manager/src/identity_group.c @@ -0,0 +1,808 @@ +/* + * Copyright (C) 2023 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 "account_auth_plugin_proxy.h" +#include "account_related_group_auth.h" +#include "alg_defs.h" +#include "alg_loader.h" +#include "cert_operation.h" +#include "group_auth_data_operation.h" +#include "group_operation_common.h" +#include "hc_log.h" +#include "identity_manager.h" + +static int32_t GetAccountRelatedCandidateGroups( + int32_t osAccountId, const CJson *in, bool isDeviceLevel, GroupEntryVec *vec) +{ + BaseGroupAuth *groupAuth = GetAccountRelatedGroupAuth(); + if (groupAuth == NULL) { + return HC_ERR_NULL_PTR; + } + QueryGroupParams queryParams = InitQueryGroupParams(); + if (!isDeviceLevel) { + queryParams.groupVisibility = GROUP_VISIBILITY_PUBLIC; + } + ((AccountRelatedGroupAuth *)groupAuth)->getAccountCandidateGroup(osAccountId, in, &queryParams, vec); + // All return success, only notify the plugin. + if (HasAccountAuthPlugin() == HC_SUCCESS && vec->size(vec) == 0) { + CJson *input = CreateJson(); + if (input == NULL) { + return HC_SUCCESS; + } + CJson *output = CreateJson(); + if (output == NULL) { + FreeJson(input); + return HC_SUCCESS; + } + int32_t ret = ExcuteCredMgrCmd(osAccountId, QUERY_SELF_CREDENTIAL_INFO, input, output); + if (ret != HC_SUCCESS) { + LOGE("Account cred is empty."); + } + FreeJson(input); + FreeJson(output); + } + return HC_SUCCESS; +} + +static int32_t GetAccountUnrelatedCandidateGroups(int32_t osAccountId, bool isDeviceLevel, GroupEntryVec *vec) +{ + QueryGroupParams queryParams = InitQueryGroupParams(); + queryParams.groupType = PEER_TO_PEER_GROUP; + if (!isDeviceLevel) { + queryParams.groupVisibility = GROUP_VISIBILITY_PUBLIC; + } + return QueryGroups(osAccountId, &queryParams, vec); +} + +static void GetGroupInfoByGroupId(int32_t osAccountId, const char *groupId, GroupEntryVec *groupEntryVec) +{ + QueryGroupParams queryParams = InitQueryGroupParams(); + queryParams.groupId = groupId; + int32_t ret = QueryGroups(osAccountId, &queryParams, groupEntryVec); + if (ret != HC_SUCCESS) { + LOGE("Failed to query groups for groupId: %s!", groupId); + } +} + +static void GetCandidateGroups(int32_t osAccountId, const CJson *in, GroupEntryVec *groupEntryVec) +{ + bool isDeviceLevel = false; + (void)GetBoolFromJson(in, FIELD_IS_DEVICE_LEVEL, &isDeviceLevel); + + int32_t ret = GetAccountRelatedCandidateGroups(osAccountId, in, isDeviceLevel, groupEntryVec); + if (ret != HC_SUCCESS) { + LOGE("Failed to get account related groups!"); + } + + ret = GetAccountUnrelatedCandidateGroups(osAccountId, isDeviceLevel, groupEntryVec); + if (ret != HC_SUCCESS) { + LOGE("Failed to get p2p groups!"); + } +} + +static bool IsDeviceInGroup( + int32_t osAccountId, int32_t groupType, const char *deviceId, const char *groupId, bool isUdid) +{ + if (isUdid) { + return GaIsDeviceInGroup(groupType, osAccountId, deviceId, NULL, groupId); + } else { + return GaIsDeviceInGroup(groupType, osAccountId, NULL, deviceId, groupId); + } +} + +static int32_t SetProtocolsToIdentityInfo(int32_t keyType, IdentityInfo *info) +{ + if (keyType == KEY_TYPE_ASYM) { +#ifdef ENABLE_P2P_AUTH_EC_SPEKE + ProtocolEntity *entity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); + if (entity == NULL) { + LOGE("Failed to alloc memory for entity!"); + return HC_ERR_ALLOC_MEMORY; + } + entity->protocolType = ALG_EC_SPEKE; + info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&entity); +#else + (void)info; +#endif + } else { +#ifdef ENABLE_P2P_AUTH_ISO + ProtocolEntity *entity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); + if (entity == NULL) { + LOGE("Failed to alloc memory for entity!"); + return HC_ERR_ALLOC_MEMORY; + } + entity->protocolType = ALG_ISO; + info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&entity); +#else + (void)info; +#endif + } + + return HC_SUCCESS; +} + +static bool IsP2pAuthTokenExist(const TrustedDeviceEntry *deviceEntry) +{ + Uint8Buff pkgNameBuff = { (uint8_t *)GROUP_MANAGER_PACKAGE_NAME, strlen(GROUP_MANAGER_PACKAGE_NAME) }; + + const char *serviceType = StringGet(&deviceEntry->serviceType); + Uint8Buff serviceTypeBuff = { (uint8_t *)serviceType, strlen(serviceType) }; + + const char *peerAuthId = StringGet(&deviceEntry->authId); + Uint8Buff peerAuthIdBuff = { (uint8_t *)peerAuthId, strlen(peerAuthId) }; + + uint8_t keyAliasVal[ISO_KEY_ALIAS_LEN] = { 0 }; + Uint8Buff keyAlias = { keyAliasVal, ISO_KEY_ALIAS_LEN }; + int32_t ret = + GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, KEY_ALIAS_AUTH_TOKEN, &peerAuthIdBuff, &keyAlias); + if (ret != HC_SUCCESS) { + LOGE("Failed to generate key alias!"); + return false; + } + + ret = GetLoaderInstance()->checkKeyExist(&keyAlias); + if (ret != HC_SUCCESS) { + LOGE("auth token not exist!"); + return false; + } + return true; +} + +static int32_t GetAccountUnrelatedIdentityInfo( + int32_t osAccountId, const char *groupId, const char *deviceId, bool isUdid, IdentityInfo *info) +{ + TrustedDeviceEntry *deviceEntry = CreateDeviceEntry(); + if (deviceEntry == NULL) { + LOGE("Failed to create deviceEntry!"); + return HC_ERR_ALLOC_MEMORY; + } + int32_t ret = GaGetTrustedDeviceEntryById(osAccountId, deviceId, isUdid, groupId, deviceEntry); + if (ret != HC_SUCCESS) { + LOGE("Failed to get device entry!"); + DestroyDeviceEntry(deviceEntry); + return ret; + } + + int32_t keyType = IsP2pAuthTokenExist(deviceEntry) ? KEY_TYPE_SYM : KEY_TYPE_ASYM; + DestroyDeviceEntry(deviceEntry); + CJson *urlJson = CreateCredUrlJson(PRE_SHARED, keyType, TRUST_TYPE_P2P); + + if (!urlJson) { + LOGE("Failed to create CredUrlJson info!"); + return HC_ERR_ALLOC_MEMORY; + } + if (AddStringToJson(urlJson, FIELD_GROUP_ID, groupId) != HC_SUCCESS) { + LOGE("Failed to add group id!"); + FreeJson(urlJson); + return HC_ERR_JSON_ADD; + } + + char *urlStr = PackJsonToString(urlJson); + FreeJson(urlJson); + if (urlStr == NULL) { + LOGE("Failed to pack url json to string!"); + return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL; + } + + ret = SetPreSharedUrlForProof(urlStr, &info->proof.preSharedUrl); + FreeJsonString(urlStr); + if (ret != HC_SUCCESS) { + LOGE("Failed to set preSharedUrl of proof!"); + return ret; + } + + ret = SetProtocolsToIdentityInfo(keyType, info); + if (ret != HC_SUCCESS) { + LOGE("Failed to set protocols!"); + return ret; + } + + info->proofType = PRE_SHARED; + if (ret != HC_SUCCESS) { + LOGE("Failed to get p2p identity by key type!"); + } + return ret; +} + +static int32_t GetIdentityInfo(int32_t osAccountId, const TrustedGroupEntry *groupEntry, const char *deviceId, + bool isUdid, IdentityInfo **returnInfo) +{ + IdentityInfo *info = CreateIdentityInfo(); + if (info == NULL) { + LOGE("Failed to create identity info!"); + return HC_ERR_ALLOC_MEMORY; + } + int32_t ret; + const char *groupId = StringGet(&groupEntry->id); + if (groupEntry->type == PEER_TO_PEER_GROUP) { + ret = GetAccountUnrelatedIdentityInfo(osAccountId, groupId, deviceId, isUdid, info); + } else { + ret = GetAccountRelatedCredInfo(osAccountId, groupId, deviceId, isUdid, info); + } + if (ret != HC_SUCCESS) { + LOGE("Failed to get identity info!"); + DestroyIdentityInfo(info); + return ret; + } + *returnInfo = info; + return HC_SUCCESS; +} + +static void AddNoPseudonymIdentityInfo(int32_t osAccountId, const TrustedGroupEntry *groupEntry, + const char *deviceId, bool isUdid, IdentityInfoVec *identityInfoVec) +{ + IdentityInfo *info = NULL; + if (GetIdentityInfo(osAccountId, groupEntry, deviceId, isUdid, &info) != HC_SUCCESS) { + return; + } + info->proof.certInfo.isPseudonym = false; + identityInfoVec->pushBack(identityInfoVec, (const IdentityInfo **)&info); +} + +static int32_t GetIdentityInfos( + int32_t osAccountId, const CJson *in, const GroupEntryVec *groupEntryVec, IdentityInfoVec *identityInfoVec) +{ + const char *pkgName = GetStringFromJson(in, FIELD_SERVICE_PKG_NAME); + if (pkgName == NULL) { + LOGE("Failed to get service package name!"); + return HC_ERR_JSON_GET; + } + bool isUdid = false; + const char *deviceId = GetPeerDevIdFromJson(in, &isUdid); + if (deviceId == NULL) { + LOGE("Failed to get peer device id!"); + return HC_ERR_JSON_GET; + } + uint32_t index; + TrustedGroupEntry **ptr = NULL; + FOR_EACH_HC_VECTOR(*groupEntryVec, index, ptr) + { + const TrustedGroupEntry *groupEntry = (TrustedGroupEntry *)(*ptr); + const char *groupId = StringGet(&(groupEntry->id)); + if (groupId == NULL) { + continue; + } + if (!GaIsGroupAccessible(osAccountId, groupId, pkgName)) { + continue; + } + if (!IsDeviceInGroup(osAccountId, groupEntry->type, deviceId, groupId, isUdid)) { + continue; + } + IdentityInfo *info = NULL; + if (GetIdentityInfo(osAccountId, groupEntry, deviceId, isUdid, &info) != HC_SUCCESS) { + continue; + } + if (info->proofType == CERTIFICATED) { + info->proof.certInfo.isPseudonym = true; + } + identityInfoVec->pushBack(identityInfoVec, (const IdentityInfo **)&info); + if (info->proofType == CERTIFICATED) { + AddNoPseudonymIdentityInfo(osAccountId, groupEntry, deviceId, isUdid, identityInfoVec); + } + } + LOGI("The identity info size is: %u", identityInfoVec->size(identityInfoVec)); + return HC_SUCCESS; +} + +static int32_t GetCredInfosByPeerIdentity(const CJson *in, IdentityInfoVec *identityInfoVec) +{ + int32_t osAccountId = INVALID_OS_ACCOUNT; + int32_t ret; + if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { + LOGE("Failed to get osAccountId!"); + return HC_ERR_JSON_GET; + } + const char *groupId = GetStringFromJson(in, FIELD_GROUP_ID); + if (groupId == NULL) { + groupId = GetStringFromJson(in, FIELD_SERVICE_TYPE); + } + GroupEntryVec groupEntryVec = CreateGroupEntryVec(); + if (groupId == NULL) { + GetCandidateGroups(osAccountId, in, &groupEntryVec); + } else { + GetGroupInfoByGroupId(osAccountId, groupId, &groupEntryVec); + } + + bool isDeviceLevel = false; + (void)GetBoolFromJson(in, FIELD_IS_DEVICE_LEVEL, &isDeviceLevel); + if (groupEntryVec.size(&groupEntryVec) == 0) { + if (isDeviceLevel) { + // device level auth still has the chance to try p2p direct auth + // so, do not report error here. + LOGI("No satisfied candidate group!"); + } else { + LOGE("No satisfied candidate group!"); + } + ClearGroupEntryVec(&groupEntryVec); + return HC_ERR_NO_CANDIDATE_GROUP; + } + ret = GetIdentityInfos(osAccountId, in, &groupEntryVec, identityInfoVec); + ClearGroupEntryVec(&groupEntryVec); + return ret; +} + +static int32_t CheckAndGetP2pCredInfo(const CJson *in, const CJson *urlJson, IdentityInfo *info) +{ + int32_t osAccountId = INVALID_OS_ACCOUNT; + if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { + LOGE("Failed to get osAccountId!"); + return HC_ERR_JSON_GET; + } + + const char *groupId = GetStringFromJson(urlJson, FIELD_GROUP_ID); + if (groupId == NULL) { + LOGE("Failed to get groupId!"); + return HC_ERR_JSON_GET; + } + int32_t ret = CheckGroupExist(osAccountId, groupId); + if (ret != HC_SUCCESS) { + LOGE("group not exist!"); + return ret; + } + TrustedDeviceEntry *deviceEntry = CreateDeviceEntry(); + if (deviceEntry == NULL) { + LOGE("Failed to create device entry!"); + return HC_ERR_ALLOC_MEMORY; + } + ret = GetPeerDeviceEntry(osAccountId, in, groupId, deviceEntry); + DestroyDeviceEntry(deviceEntry); + if (ret != HC_SUCCESS) { + LOGE("peer device not found!"); + return ret; + } + + int32_t keyType = 0; + if (GetIntFromJson(urlJson, PRESHARED_URL_KEY_TYPE, &keyType) != HC_SUCCESS) { + LOGE("Failed to get trust type!"); + return HC_ERR_JSON_GET; + } + + char *urlStr = PackJsonToString(urlJson); + if (urlStr == NULL) { + LOGE("Failed to pack url json to string!"); + return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL; + } + ret = SetPreSharedUrlForProof(urlStr, &info->proof.preSharedUrl); + FreeJsonString(urlStr); + if (ret != HC_SUCCESS) { + LOGE("Failed to set preSharedUrl of proof!"); + return ret; + } + + ret = SetProtocolsToIdentityInfo(keyType, info); + if (ret != HC_SUCCESS) { + LOGE("Failed to set protocols!"); + return ret; + } + + info->proofType = PRE_SHARED; + + if (ret != HC_SUCCESS) { + LOGE("Failed to get p2p identity info by key type!"); + } + return ret; +} + +static int32_t GetCredInfoByPeerUrl(const CJson *in, const Uint8Buff *presharedUrl, IdentityInfo **returnInfo) +{ + if (in == NULL || presharedUrl == NULL || returnInfo == NULL) { + LOGE("Invalid input params!"); + return HC_ERR_INVALID_PARAMS; + } + + CJson *urlJson = CreateJsonFromString((const char *)presharedUrl->val); + if (urlJson == NULL) { + LOGE("Failed to create url json!"); + return HC_ERR_JSON_CREATE; + } + + int32_t trustType = 0; + if (GetIntFromJson(urlJson, PRESHARED_URL_TRUST_TYPE, &trustType) != HC_SUCCESS) { + LOGE("Failed to get trust type!"); + FreeJson(urlJson); + return HC_ERR_JSON_GET; + } + + IdentityInfo *info = CreateIdentityInfo(); + if (info == NULL) { + LOGE("Failed to create identity info!"); + return HC_ERR_ALLOC_MEMORY; + } + int32_t ret; + switch (trustType) { + case TRUST_TYPE_UID: + ret = GetAccountSymCredInfoByPeerUrl(in, urlJson, info); + break; + case TRUST_TYPE_P2P: + ret = CheckAndGetP2pCredInfo(in, urlJson, info); + break; + default: + LOGE("Invalid trust type!"); + ret = HC_ERR_INVALID_PARAMS; + break; + } + FreeJson(urlJson); + + *returnInfo = info; + return ret; +} + +static int32_t GenerateKeyAliasInIso(const CJson *in, const char *groupId, uint8_t *keyAlias, uint32_t keyAliasLen) +{ + int32_t osAccountId = INVALID_OS_ACCOUNT; + if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { + LOGE("Failed to get osAccountId!"); + return HC_ERR_JSON_GET; + } + TrustedDeviceEntry *deviceEntry = CreateDeviceEntry(); + if (deviceEntry == NULL) { + LOGE("Failed to create device entry!"); + return HC_ERR_ALLOC_MEMORY; + } + int32_t ret = GetPeerDeviceEntry(osAccountId, in, groupId, deviceEntry); + if (ret != HC_SUCCESS) { + LOGE("Failed to get peer device entry!"); + DestroyDeviceEntry(deviceEntry); + return ret; + } + Uint8Buff pkgNameBuff = { (uint8_t *)GROUP_MANAGER_PACKAGE_NAME, + (uint32_t)strlen(GROUP_MANAGER_PACKAGE_NAME) }; + const char *serviceType = StringGet(&deviceEntry->serviceType); + Uint8Buff serviceTypeBuff = { (uint8_t *)serviceType, (uint32_t)strlen(serviceType) }; + const char *peerAuthId = StringGet(&deviceEntry->authId); + Uint8Buff peerAuthIdBuff = { (uint8_t *)peerAuthId, (uint32_t)strlen(peerAuthId) }; + Uint8Buff outKeyAlias = { keyAlias, keyAliasLen }; + ret = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, KEY_ALIAS_AUTH_TOKEN, &peerAuthIdBuff, &outKeyAlias); + DestroyDeviceEntry(deviceEntry); + return ret; +} + +static int32_t AuthGeneratePsk( + const CJson *in, const char *groupId, const Uint8Buff *seed, Uint8Buff *sharedSecret) +{ + uint8_t keyAlias[ISO_KEY_ALIAS_LEN] = { 0 }; + int ret = GenerateKeyAliasInIso(in, groupId, keyAlias, sizeof(keyAlias)); + if (ret != HC_SUCCESS) { + LOGE("Failed to generate key alias in iso!"); + return ret; + } + Uint8Buff keyAliasBuf = { keyAlias, sizeof(keyAlias) }; + return GetLoaderInstance()->computeHmac(&keyAliasBuf, seed, sharedSecret, true); +} + +static int32_t GetSharedSecretForP2pInIso(const CJson *in, const char *groupId, Uint8Buff *sharedSecret) +{ + uint8_t *seedVal = (uint8_t *)HcMalloc(SEED_LEN, 0); + if (seedVal == NULL) { + LOGE("Failed to alloc memory for seed!"); + return HC_ERR_ALLOC_MEMORY; + } + Uint8Buff seedBuff = { seedVal, SEED_LEN }; + int32_t ret = GetByteFromJson(in, FIELD_SEED, seedBuff.val, seedBuff.length); + if (ret != HC_SUCCESS) { + LOGE("Failed to get seed!"); + HcFree(seedVal); + return HC_ERR_JSON_GET; + } + uint8_t *pskVal = (uint8_t *)HcMalloc(ISO_PSK_LEN, 0); + if (pskVal == NULL) { + LOGE("Failed to alloc memory for psk!"); + HcFree(seedVal); + return HC_ERR_ALLOC_MEMORY; + } + sharedSecret->val = pskVal; + sharedSecret->length = ISO_PSK_LEN; + ret = AuthGeneratePsk(in, groupId, &seedBuff, sharedSecret); + HcFree(seedVal); + if (ret != HC_SUCCESS) { + LOGE("Failed to generate psk!"); + FreeBuffData(sharedSecret); + } + return ret; +} + +static int32_t GetSelfAuthIdAndUserType( + int32_t osAccountId, const char *groupId, Uint8Buff *authIdBuff, int32_t *userType) +{ + TrustedDeviceEntry *deviceEntry = CreateDeviceEntry(); + if (deviceEntry == NULL) { + LOGE("Failed to create device entry!"); + return HC_ERR_ALLOC_MEMORY; + } + int32_t ret = GetSelfDeviceEntry(osAccountId, groupId, deviceEntry); + if (ret != HC_SUCCESS) { + LOGE("Failed to get self device entry!"); + DestroyDeviceEntry(deviceEntry); + return ret; + } + const char *selfAuthId = StringGet(&deviceEntry->authId); + uint32_t authIdLen = strlen(selfAuthId); + authIdBuff->val = (uint8_t *)HcMalloc(authIdLen + 1, 0); + if (authIdBuff->val == NULL) { + LOGE("Failed to alloc memory for authId!"); + DestroyDeviceEntry(deviceEntry); + return HC_ERR_ALLOC_MEMORY; + } + if (memcpy_s(authIdBuff->val, authIdLen + 1, selfAuthId, authIdLen) != EOK) { + LOGE("Failed to copy authId!"); + HcFree(authIdBuff->val); + authIdBuff->val = NULL; + DestroyDeviceEntry(deviceEntry); + return HC_ERR_MEMORY_COPY; + } + authIdBuff->length = authIdLen; + *userType = deviceEntry->devType; + DestroyDeviceEntry(deviceEntry); + return HC_SUCCESS; +} + +static int32_t ComputeAndSavePsk(int32_t osAccountId, const char *groupId, + const TrustedDeviceEntry *peerDeviceEntry, const Uint8Buff *sharedKeyAlias) +{ + Uint8Buff selfAuthIdBuff = { NULL, 0 }; + int32_t selfUserType = 0; + int32_t ret = GetSelfAuthIdAndUserType(osAccountId, groupId, &selfAuthIdBuff, &selfUserType); + if (ret != HC_SUCCESS) { + LOGE("Failed to get self auth id and user type!"); + return ret; + } + + Uint8Buff pkgNameBuff = { (uint8_t *)GROUP_MANAGER_PACKAGE_NAME, strlen(GROUP_MANAGER_PACKAGE_NAME) }; + const char *serviceType = StringGet(&peerDeviceEntry->serviceType); + Uint8Buff serviceTypeBuff = { (uint8_t *)serviceType, strlen(serviceType) }; + KeyAliasType keyType = (KeyAliasType)selfUserType; + uint8_t selfKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 }; + Uint8Buff selfKeyAlias = { selfKeyAliasVal, PAKE_KEY_ALIAS_LEN }; + ret = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, keyType, &selfAuthIdBuff, &selfKeyAlias); + HcFree(selfAuthIdBuff.val); + if (ret != HC_SUCCESS) { + LOGE("Failed to generate self key alias!"); + return ret; + } + +#ifdef DEV_AUTH_FUNC_TEST + KeyAliasType keyTypePeer = KEY_ALIAS_LT_KEY_PAIR; +#else + KeyAliasType keyTypePeer = (KeyAliasType)peerDeviceEntry->devType; +#endif + const char *peerAuthId = StringGet(&peerDeviceEntry->authId); + Uint8Buff peerAuthIdBuff = { (uint8_t *)peerAuthId, strlen(peerAuthId) }; + uint8_t peerKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 }; + Uint8Buff peerKeyAlias = { peerKeyAliasVal, PAKE_KEY_ALIAS_LEN }; + ret = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, keyTypePeer, &peerAuthIdBuff, &peerKeyAlias); + if (ret != HC_SUCCESS) { + LOGE("Failed to generate peer key alias!"); + return ret; + } + + ret = GetLoaderInstance()->checkKeyExist(&selfKeyAlias); + if (ret != HC_SUCCESS) { + LOGE("self auth keyPair not exist!"); + return ret; + } + ret = GetLoaderInstance()->checkKeyExist(&peerKeyAlias); + if (ret != HC_SUCCESS) { + LOGE("peer auth pubKey not exist!"); + return ret; + } + + KeyBuff selfKeyAliasBuff = { selfKeyAlias.val, selfKeyAlias.length, true }; + KeyBuff peerKeyAliasBuff = { peerKeyAlias.val, peerKeyAlias.length, true }; + return GetLoaderInstance()->agreeSharedSecretWithStorage( + &selfKeyAliasBuff, &peerKeyAliasBuff, ED25519, PAKE_PSK_LEN, sharedKeyAlias); +} + +static int32_t GeneratePskAliasAndCheckExist(const CJson *in, const char *groupId, Uint8Buff *pskKeyAlias) +{ + int32_t osAccountId = INVALID_OS_ACCOUNT; + if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { + LOGE("Failed to get osAccountId!"); + return HC_ERR_JSON_GET; + } + TrustedDeviceEntry *deviceEntry = CreateDeviceEntry(); + if (deviceEntry == NULL) { + LOGE("Failed to create device entry!"); + return HC_ERR_ALLOC_MEMORY; + } + int32_t ret = GetPeerDeviceEntry(osAccountId, in, groupId, deviceEntry); + if (ret != HC_SUCCESS) { + LOGE("Failed to get peer device entry!"); + DestroyDeviceEntry(deviceEntry); + return ret; + } + Uint8Buff pkgNameBuff = { (uint8_t *)GROUP_MANAGER_PACKAGE_NAME, strlen(GROUP_MANAGER_PACKAGE_NAME) }; + const char *serviceType = StringGet(&deviceEntry->serviceType); + Uint8Buff serviceTypeBuff = { (uint8_t *)serviceType, strlen(serviceType) }; + const char *peerAuthId = StringGet(&deviceEntry->authId); + Uint8Buff peerAuthIdBuff = { (uint8_t *)peerAuthId, strlen(peerAuthId) }; + ret = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, KEY_ALIAS_PSK, &peerAuthIdBuff, pskKeyAlias); + if (ret != HC_SUCCESS) { + LOGE("Failed to generate psk key alias!"); + DestroyDeviceEntry(deviceEntry); + return ret; + } + LOGI("psk alias: %x %x %x %x****.", pskKeyAlias->val[DEV_AUTH_ZERO], pskKeyAlias->val[DEV_AUTH_ONE], + pskKeyAlias->val[DEV_AUTH_TWO], pskKeyAlias->val[DEV_AUTH_THREE]); + if (GetLoaderInstance()->checkKeyExist(pskKeyAlias) != HC_SUCCESS) { + ret = ComputeAndSavePsk(osAccountId, groupId, deviceEntry, pskKeyAlias); + } + DestroyDeviceEntry(deviceEntry); + return ret; +} + +static int32_t GetSharedSecretForP2pInPake(const CJson *in, const char *groupId, Uint8Buff *sharedSecret) +{ + uint8_t pskKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 }; + Uint8Buff pskKeyAlias = { pskKeyAliasVal, PAKE_KEY_ALIAS_LEN }; + int32_t ret = GeneratePskAliasAndCheckExist(in, groupId, &pskKeyAlias); + if (ret != HC_SUCCESS) { + LOGE("Failed to generate key alias for psk!"); + return ret; + } + uint8_t *pskVal = (uint8_t *)HcMalloc(PAKE_PSK_LEN, 0); + if (pskVal == NULL) { + LOGE("Failed to alloc memory for psk!"); + return HC_ERR_ALLOC_MEMORY; + } + Uint8Buff pskBuff = { pskVal, PAKE_PSK_LEN }; + uint8_t *nonceVal = (uint8_t *)HcMalloc(PAKE_NONCE_LEN, 0); + if (nonceVal == NULL) { + LOGE("Failed to alloc memory for nonce!"); + HcFree(pskVal); + return HC_ERR_ALLOC_MEMORY; + } + Uint8Buff nonceBuff = { nonceVal, PAKE_NONCE_LEN }; + ret = GetByteFromJson(in, FIELD_NONCE, nonceBuff.val, nonceBuff.length); + if (ret != HC_SUCCESS) { + LOGE("Failed to get nonce!"); + HcFree(pskVal); + HcFree(nonceVal); + return HC_ERR_JSON_GET; + } + Uint8Buff keyInfo = { (uint8_t *)TMP_AUTH_KEY_FACTOR, strlen(TMP_AUTH_KEY_FACTOR) }; + ret = GetLoaderInstance()->computeHkdf(&pskKeyAlias, &nonceBuff, &keyInfo, &pskBuff, true); + HcFree(nonceVal); + if (ret != HC_SUCCESS) { + LOGE("Failed to compute hkdf for psk!"); + HcFree(pskVal); + return ret; + } + + ret = ConvertPsk(&pskBuff, sharedSecret); + HcFree(pskVal); + if (ret != HC_SUCCESS) { + LOGE("Failed to convert psk!"); + } + return ret; +} + +static int32_t GetSharedSecretForP2p( + const CJson *in, const CJson *urlJson, ProtocolAlgType protocolType, Uint8Buff *sharedSecret) +{ + const char *groupId = GetStringFromJson(urlJson, FIELD_GROUP_ID); + if (groupId == NULL) { + LOGE("Failed to get groupId!"); + return HC_ERR_JSON_GET; + } + int32_t ret; + if (protocolType == ALG_ISO) { + ret = GetSharedSecretForP2pInIso(in, groupId, sharedSecret); + LOGI("get shared secret for p2p in iso result: %d", ret); + } else { + ret = GetSharedSecretForP2pInPake(in, groupId, sharedSecret); + LOGI("get shared secret for p2p in pake result: %d", ret); + } + return ret; +} + +static int32_t GetSharedSecretByUrl( + const CJson *in, const Uint8Buff *presharedUrl, ProtocolAlgType protocolType, Uint8Buff *sharedSecret) +{ + if (in == NULL || presharedUrl == NULL || sharedSecret == NULL) { + LOGE("Invalid input params!"); + return HC_ERR_INVALID_PARAMS; + } + + CJson *urlJson = CreateJsonFromString((const char *)presharedUrl->val); + if (urlJson == NULL) { + LOGE("Failed to create url json!"); + return HC_ERR_JSON_CREATE; + } + + int32_t trustType = 0; + if (GetIntFromJson(urlJson, PRESHARED_URL_TRUST_TYPE, &trustType) != HC_SUCCESS) { + LOGE("Failed to get trust type!"); + FreeJson(urlJson); + return HC_ERR_JSON_GET; + } + + int32_t ret; + switch (trustType) { + case TRUST_TYPE_P2P: + ret = GetSharedSecretForP2p(in, urlJson, protocolType, sharedSecret); + break; + case TRUST_TYPE_UID: + if (protocolType != ALG_ISO) { + LOGE("protocol type is not iso, not supported!"); + ret = HC_ERR_INVALID_PARAMS; + } else { + ret = GetAccountSymSharedSecret(in, urlJson, sharedSecret); + } + break; + default: + LOGE("Invalid trust type!"); + ret = HC_ERR_INVALID_PARAMS; + break; + } + FreeJson(urlJson); + + return ret; +} + +static int32_t GetCredInfoByPeerCert(const CJson *in, const CertInfo *certInfo, IdentityInfo **returnInfo) +{ + if (in == NULL || certInfo == NULL || returnInfo == NULL) { + LOGE("Invalid input params!"); + return HC_ERR_INVALID_PARAMS; + } + int32_t osAccountId = INVALID_OS_ACCOUNT; + if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { + LOGE("Failed to get osAccountId!"); + return HC_ERR_JSON_GET; + } + int32_t res = GetAccountAsymCredInfo(osAccountId, certInfo, returnInfo); + if (res != HC_SUCCESS) { + LOGE("Failed to get account asym cred info!"); + return res; + } + if (certInfo->isPseudonym) { + (*returnInfo)->proof.certInfo.isPseudonym = true; + } else { + (*returnInfo)->proof.certInfo.isPseudonym = false; + } + return HC_SUCCESS; +} + +static int32_t GetSharedSecretByPeerCert( + const CJson *in, const CertInfo *peerCertInfo, ProtocolAlgType protocolType, Uint8Buff *sharedSecret) +{ + if (in == NULL || peerCertInfo == NULL || sharedSecret == NULL) { + LOGE("Invalid input params!"); + return HC_ERR_INVALID_PARAMS; + } + if (protocolType != ALG_EC_SPEKE) { + LOGE("protocol type is not ec speke, not support!"); + return HC_ERR_INVALID_PARAMS; + } + int32_t osAccountId = INVALID_OS_ACCOUNT; + if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { + LOGE("Failed to get osAccountId!"); + return HC_ERR_JSON_GET; + } + return GetAccountAsymSharedSecret(osAccountId, peerCertInfo, sharedSecret); +} + +static const AuthIdentity g_authIdentity = { + .getCredInfosByPeerIdentity = GetCredInfosByPeerIdentity, + .getCredInfoByPeerUrl = GetCredInfoByPeerUrl, + .getSharedSecretByUrl = GetSharedSecretByUrl, + .getCredInfoByPeerCert = GetCredInfoByPeerCert, + .getSharedSecretByPeerCert = GetSharedSecretByPeerCert, +}; + +const AuthIdentity *GetGroupAuthIdentity(void) +{ + return &g_authIdentity; +} \ No newline at end of file diff --git a/services/identity_manager/src/identity_manager.c b/services/identity_manager/src/identity_manager.c new file mode 100644 index 00000000..574a0e44 --- /dev/null +++ b/services/identity_manager/src/identity_manager.c @@ -0,0 +1,61 @@ +/* + * Copyright (C) 2023 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 "identity_manager.h" + +#include "hc_log.h" + +/* in order to expand to uint16_t */ +static const uint8_t KEY_TYPE_PAIRS[KEY_ALIAS_TYPE_END][KEY_TYPE_PAIR_LEN] = { + { 0x00, 0x00 }, /* ACCESSOR_PK */ + { 0x00, 0x01 }, /* CONTROLLER_PK */ + { 0x00, 0x02 }, /* ed25519 KEYPAIR */ + { 0x00, 0x03 }, /* KEK, key encryption key, used only by DeviceAuthService */ + { 0x00, 0x04 }, /* DEK, data encryption key, used only by upper apps */ + { 0x00, 0x05 }, /* key tmp */ + { 0x00, 0x06 }, /* PSK, preshared key index */ + { 0x00, 0x07 }, /* AUTHTOKEN */ + { 0x00, 0x08 } /* P2P_AUTH */ +}; + +uint8_t *GetKeyTypePair(KeyAliasType keyAliasType) +{ + return (uint8_t *)KEY_TYPE_PAIRS[keyAliasType]; +} + +const AuthIdentity *GetAuthIdentityByType(AuthIdentityType type) +{ + switch (type) { + case AUTH_IDENTITY_TYPE_GROUP: + return GetGroupAuthIdentity(); + case AUTH_IDENTITY_TYPE_PIN: + return GetPinAuthIdentity(); + case AUTH_IDENTITY_TYPE_P2P: + return GetP2pAuthIdentity(); + default: + LOGE("unknow AuthIdentityType: %d", type); + return NULL; + } +} + +static const AuthIdentityManager g_identityManager = { + .getAuthIdentityByType = GetAuthIdentityByType, + .getCredentialOperator = GetCredentialOperator, +}; + +const AuthIdentityManager *GetAuthIdentityManager(void) +{ + return &g_identityManager; +} diff --git a/services/identity_manager/src/identity_p2p.c b/services/identity_manager/src/identity_p2p.c new file mode 100644 index 00000000..db76cfc4 --- /dev/null +++ b/services/identity_manager/src/identity_p2p.c @@ -0,0 +1,333 @@ +/* + * Copyright (C) 2023 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 "alg_defs.h" +#include "alg_loader.h" +#include "hc_log.h" +#include "identity_manager.h" + +static int32_t SetProtocolsToIdentityInfo(IdentityInfo *info) +{ + ProtocolEntity *ecSpekeEntity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); + if (ecSpekeEntity == NULL) { + LOGE("Failed to alloc memory for ec speke entity!"); + return HC_ERR_ALLOC_MEMORY; + } + ecSpekeEntity->protocolType = ALG_EC_SPEKE; + ecSpekeEntity->expandProcessCmds = 0; + info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&ecSpekeEntity); + + return HC_SUCCESS; +} + +static int32_t IsPeerDevicePublicKeyExist(const CJson *in) +{ + int32_t osAccountId = INVALID_OS_ACCOUNT; + if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { + LOGE("Failed to get osAccountId from context!"); + return HC_ERR_JSON_GET; + } + const char *peerConnDeviceId = GetStringFromJson(in, FIELD_PEER_CONN_DEVICE_ID); + if (peerConnDeviceId == NULL) { + LOGE("Failed to get peerConnDeviceId from context, need peerConnDeviceId!"); + return HC_ERR_JSON_GET; + } + int32_t acquireType = P2P_BIND; + if (GetIntFromJson(in, FIELD_ACQURIED_TYPE, &acquireType) != HC_SUCCESS) { + LOGI("Failed to get acquireType from context!"); + } + CJson *paramsJson = CreateJson(); + if (paramsJson == NULL) { + LOGE("alloc memory error!"); + return HC_ERR_ALLOC_MEMORY; + } + if (AddIntToJson(paramsJson, FIELD_OS_ACCOUNT_ID, osAccountId) != HC_SUCCESS) { + LOGE("add osAccountId to json error!"); + FreeJson(paramsJson); + return HC_ERR_JSON_ADD; + } + if (AddIntToJson(paramsJson, FIELD_ACQURIED_TYPE, acquireType) != HC_SUCCESS) { + LOGE("add acquireType to json error!"); + FreeJson(paramsJson); + return HC_ERR_JSON_ADD; + } + if (AddIntToJson(paramsJson, FIELD_CRED_OP_FLAG, RETURN_FLAG_DEFAULT) != HC_SUCCESS) { + LOGE("add flag to json error!"); + FreeJson(paramsJson); + return HC_ERR_JSON_ADD; + } + if (AddStringToJson(paramsJson, FIELD_DEVICE_ID, peerConnDeviceId) != HC_SUCCESS) { + LOGE("add device id to json error!"); + FreeJson(paramsJson); + return HC_ERR_JSON_ADD; + } + const char *requestParams = PackJsonToString(paramsJson); + FreeJson(paramsJson); + + const CredentialOperator *credOperator = GetCredentialOperator(); + if (credOperator == NULL) { + LOGE("credOperator is null!"); + return HC_ERR_NOT_SUPPORT; + } + return credOperator->queryCredential(requestParams, NULL); +} + +static int32_t GetCredInfosByPeerIdentity(const CJson *in, IdentityInfoVec *vec) +{ + int32_t keyType = KEY_TYPE_ASYM; + (void)GetIntFromJson(in, FIELD_KEY_TYPE, &keyType); + + int32_t ret = IsPeerDevicePublicKeyExist(in); + if (ret != HC_SUCCESS) { + LOGE("Failed to get peer device public key!"); + return ret; + } + CJson *urlJson = CreateCredUrlJson(PRE_SHARED, keyType, TRUST_TYPE_P2P); + if (!urlJson) { + LOGE("Failed to create CredUrlJson info!"); + return HC_ERR_ALLOC_MEMORY; + } + if (AddBoolToJson(urlJson, FIELD_IS_DIRECT_AUTH, true) != HC_SUCCESS) { + LOGE("Failed to add isDirectAuth to preshared url!"); + FreeJson(urlJson); + return HC_ERR_JSON_ADD; + } else { + LOGI("add isDirectAuth:true into urlJson!"); + } + char *urlStr = PackJsonToString(urlJson); + FreeJson(urlJson); + if (urlStr == NULL) { + LOGE("Failed to pack url json to string!"); + return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL; + } + IdentityInfo *info = CreateIdentityInfo(); + if (info == NULL) { + LOGE("Failed to create identity info!"); + return HC_ERR_ALLOC_MEMORY; + } + ret = SetPreSharedUrlForProof(urlStr, &info->proof.preSharedUrl); + FreeJsonString(urlStr); + if (ret != HC_SUCCESS) { + LOGE("Failed to set preSharedUrl of proof!"); + return ret; + } + ret = SetProtocolsToIdentityInfo(info); + if (ret != HC_SUCCESS) { + LOGE("Failed to set protocols!"); + return ret; + } + info->proofType = PRE_SHARED; + info->IdInfoType = P2P_DIRECT_AUTH; + vec->pushBack(vec, (const IdentityInfo **)&info); + return HC_SUCCESS; +} + +static int32_t GetCredInfoByPeerUrl(const CJson *in, const Uint8Buff *presharedUrl, IdentityInfo **returnInfo) +{ + if (in == NULL || presharedUrl == NULL || returnInfo == NULL) { + LOGE("Invalid input params!"); + return HC_ERR_INVALID_PARAMS; + } + IdentityInfo *info = CreateIdentityInfo(); + if (info == NULL) { + LOGE("Failed to create identity info!"); + return HC_ERR_ALLOC_MEMORY; + } + int32_t ret = SetPreSharedUrlForProof((const char *)presharedUrl->val, &info->proof.preSharedUrl); + if (ret != HC_SUCCESS) { + LOGE("Failed to set preSharedUrl of proof!"); + return ret; + } + ret = SetProtocolsToIdentityInfo(info); + if (ret != HC_SUCCESS) { + LOGE("Failed to set protocols!"); + return ret; + } + info->proofType = PRE_SHARED; + info->IdInfoType = P2P_DIRECT_AUTH; + *returnInfo = info; + return HC_SUCCESS; +} + +/** + * @brief compute shared key alias + * + * @param osAccountId + * @param selfAuthId self device udid + * @param peerAuthId peer device udid + * @param sharedKeyAlias + * @return int32_t + */ +static int32_t ComputeAndSaveDirectAuthPsk(int32_t osAccountId, const char *selfAuthId, const char *peerAuthId, + const char *peerServiceType, const Uint8Buff *sharedKeyAlias) +{ + Uint8Buff selfAuthIdBuff = { (uint8_t *)selfAuthId, strlen(selfAuthId) }; + Uint8Buff pkgNameBuff = { (uint8_t *)DEFAULT_PACKAGE_NAME, strlen(DEFAULT_PACKAGE_NAME) }; + Uint8Buff serviceTypeBuff = { (uint8_t *)DEFAULT_SERVICE_TYPE, strlen(DEFAULT_SERVICE_TYPE) }; + KeyAliasType keyType = KEY_ALIAS_P2P_AUTH; + uint8_t selfKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 }; + Uint8Buff selfKeyAlias = { selfKeyAliasVal, PAKE_KEY_ALIAS_LEN }; + int32_t ret = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, keyType, &selfAuthIdBuff, &selfKeyAlias); + if (ret != HC_SUCCESS) { + LOGE("Failed to generate self key alias!"); + return ret; + } + LOGI("selfKeyAlias: %x %x %x %x****.", selfKeyAlias.val[DEV_AUTH_ZERO], selfKeyAlias.val[DEV_AUTH_ONE], + selfKeyAlias.val[DEV_AUTH_TWO], selfKeyAlias.val[DEV_AUTH_THREE]); + + Uint8Buff peerServiceTypeBuff = { (uint8_t *)peerServiceType, strlen(peerServiceType) }; + KeyAliasType keyTypePeer = KEY_ALIAS_P2P_AUTH; + Uint8Buff peerAuthIdBuff = { (uint8_t *)peerAuthId, strlen(peerAuthId) }; + uint8_t peerKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 }; + Uint8Buff peerKeyAlias = { peerKeyAliasVal, PAKE_KEY_ALIAS_LEN }; + ret = GenerateKeyAlias(&pkgNameBuff, &peerServiceTypeBuff, keyTypePeer, &peerAuthIdBuff, &peerKeyAlias); + if (ret != HC_SUCCESS) { + LOGE("Failed to generate peer key alias!"); + return ret; + } + LOGI("peerKeyAlias: %x %x %x %x****.", peerKeyAlias.val[DEV_AUTH_ZERO], peerKeyAlias.val[DEV_AUTH_ONE], + peerKeyAlias.val[DEV_AUTH_TWO], peerKeyAlias.val[DEV_AUTH_THREE]); + + ret = GetLoaderInstance()->checkKeyExist(&selfKeyAlias); + if (ret != HC_SUCCESS) { + LOGE("self auth keyPair not exist!"); + return ret; + } + ret = GetLoaderInstance()->checkKeyExist(&peerKeyAlias); + if (ret != HC_SUCCESS) { + LOGE("peer auth pubKey not exist!"); + return ret; + } + + KeyBuff selfKeyAliasBuff = { selfKeyAlias.val, selfKeyAlias.length, true }; + KeyBuff peerKeyAliasBuff = { peerKeyAlias.val, peerKeyAlias.length, true }; + return GetLoaderInstance()->agreeSharedSecretWithStorage( + &selfKeyAliasBuff, &peerKeyAliasBuff, ED25519, PAKE_PSK_LEN, sharedKeyAlias); +} + +static int32_t GetDirectAuthPskAliasCreateIfNeeded(const CJson *in, Uint8Buff *pskKeyAlias) +{ + int32_t osAccountId = INVALID_OS_ACCOUNT; + if (GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, &osAccountId) != HC_SUCCESS) { + LOGE("Failed to get osAccountId!"); + return HC_ERR_JSON_GET; + } + const char *selfAuthId = GetStringFromJson(in, FIELD_AUTH_ID); + if (selfAuthId == NULL) { + LOGE("get authId from context fail."); + return HC_ERR_JSON_GET; + } + const char *peerAuthId = GetStringFromJson(in, FIELD_PEER_CONN_DEVICE_ID); + if (peerAuthId == NULL) { + LOGE("get peerConnDeviceId from json fail."); + return HC_ERR_JSON_GET; + } + const char *peerServieType = GetStringFromJson(in, FIELD_SERVICE_TYPE); + if (peerServieType == NULL) { + LOGI("get serviceType from json fail, replace by default"); + peerServieType = DEFAULT_SERVICE_TYPE; + } + Uint8Buff pkgNameBuff = { (uint8_t *)DEFAULT_PACKAGE_NAME, strlen(DEFAULT_PACKAGE_NAME) }; + Uint8Buff serviceTypeBuff = { (uint8_t *)peerServieType, strlen(peerServieType) }; + Uint8Buff peerAuthIdBuff = { (uint8_t *)peerAuthId, strlen(peerAuthId) }; + int32_t ret = GenerateKeyAlias(&pkgNameBuff, &serviceTypeBuff, KEY_ALIAS_PSK, &peerAuthIdBuff, pskKeyAlias); + if (ret != HC_SUCCESS) { + LOGE("Failed to generate psk key alias!"); + return ret; + } + LOGI("psk alias: %x %x %x %x****.", pskKeyAlias->val[DEV_AUTH_ZERO], pskKeyAlias->val[DEV_AUTH_ONE], + pskKeyAlias->val[DEV_AUTH_TWO], pskKeyAlias->val[DEV_AUTH_THREE]); + ret = GetLoaderInstance()->checkKeyExist(pskKeyAlias); + if (ret != HC_SUCCESS) { + ret = ComputeAndSaveDirectAuthPsk(osAccountId, selfAuthId, peerAuthId, peerServieType, pskKeyAlias); + } + return ret; +} + +static int32_t GetSharedSecretByUrl( + const CJson *in, const Uint8Buff *presharedUrl, ProtocolAlgType protocolType, Uint8Buff *sharedSecret) +{ + if (in == NULL || presharedUrl == NULL || sharedSecret == NULL) { + LOGE("Invalid input params!"); + return HC_ERR_INVALID_PARAMS; + } + uint8_t pskKeyAliasVal[PAKE_KEY_ALIAS_LEN] = { 0 }; + Uint8Buff pskKeyAlias = { pskKeyAliasVal, PAKE_KEY_ALIAS_LEN }; + int32_t ret = GetDirectAuthPskAliasCreateIfNeeded(in, &pskKeyAlias); + if (ret != HC_SUCCESS) { + LOGE("Failed to generate key alias for psk!"); + return ret; + } + uint8_t *pskVal = (uint8_t *)HcMalloc(PAKE_PSK_LEN, 0); + if (pskVal == NULL) { + LOGE("Failed to alloc memory for psk!"); + return HC_ERR_ALLOC_MEMORY; + } + Uint8Buff pskBuff = { pskVal, PAKE_PSK_LEN }; + uint8_t *nonceVal = (uint8_t *)HcMalloc(PAKE_NONCE_LEN, 0); + if (nonceVal == NULL) { + LOGE("Failed to alloc memory for nonce!"); + HcFree(pskVal); + return HC_ERR_ALLOC_MEMORY; + } + Uint8Buff nonceBuff = { nonceVal, PAKE_NONCE_LEN }; + ret = GetByteFromJson(in, FIELD_NONCE, nonceBuff.val, nonceBuff.length); + if (ret != HC_SUCCESS) { + LOGE("Failed to get nonce!"); + HcFree(pskVal); + HcFree(nonceVal); + return HC_ERR_JSON_GET; + } + Uint8Buff keyInfo = { (uint8_t *)TMP_AUTH_KEY_FACTOR, strlen(TMP_AUTH_KEY_FACTOR) }; + ret = GetLoaderInstance()->computeHkdf(&pskKeyAlias, &nonceBuff, &keyInfo, &pskBuff, true); + HcFree(nonceVal); + if (ret != HC_SUCCESS) { + LOGE("Failed to compute hkdf for psk!"); + HcFree(pskVal); + return ret; + } + ret = ConvertPsk(&pskBuff, sharedSecret); + HcFree(pskVal); + if (ret != HC_SUCCESS) { + LOGE("Failed to convert psk!"); + } + return ret; +} + +static int32_t GetCredInfoByPeerCert(const CJson *in, const CertInfo *certInfo, IdentityInfo **returnInfo) +{ + // NOT SUPPORT FOR P2P AUTH + return HC_ERR_ALG_FAIL; +} + +static int32_t GetSharedSecretByPeerCert( + const CJson *in, const CertInfo *peerCertInfo, ProtocolAlgType protocolType, Uint8Buff *sharedSecret) +{ + // NOT SUPPORT P2P AUTH + return HC_ERR_ALG_FAIL; +} + +static const AuthIdentity g_authIdentity = { + .getCredInfosByPeerIdentity = GetCredInfosByPeerIdentity, + .getCredInfoByPeerUrl = GetCredInfoByPeerUrl, + .getSharedSecretByUrl = GetSharedSecretByUrl, + .getCredInfoByPeerCert = GetCredInfoByPeerCert, + .getSharedSecretByPeerCert = GetSharedSecretByPeerCert, +}; + +const AuthIdentity *GetP2pAuthIdentity(void) +{ + return &g_authIdentity; +} \ No newline at end of file diff --git a/services/identity_manager/src/identity_pin.c b/services/identity_manager/src/identity_pin.c new file mode 100644 index 00000000..8512c9b3 --- /dev/null +++ b/services/identity_manager/src/identity_pin.c @@ -0,0 +1,363 @@ +/* + * Copyright (C) 2023 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 "alg_defs.h" +#include "alg_loader.h" +#include "hc_log.h" +#include "identity_manager.h" + +static int32_t SetDlSpekeProtocol(IdentityInfo *info) +{ +#ifdef ENABLE_P2P_BIND_DL_SPEKE + ProtocolEntity *dlSpekeEntity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); + if (dlSpekeEntity == NULL) { + LOGE("Failed to alloc memory for dl speke entity!"); + return HC_ERR_ALLOC_MEMORY; + } + dlSpekeEntity->protocolType = ALG_DL_SPEKE; + dlSpekeEntity->expandProcessCmds = CMD_IMPORT_AUTH_CODE | CMD_ADD_TRUST_DEVICE; + if (info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&dlSpekeEntity) == NULL) { + LOGE("Failed to push dl speke entity!"); + HcFree(dlSpekeEntity); + return HC_ERR_ALLOC_MEMORY; + } + return HC_SUCCESS; +#else + (void)info; + return HC_SUCCESS; +#endif +} + +static int32_t SetIsoProtocol(IdentityInfo *info) +{ +#ifdef ENABLE_P2P_BIND_ISO + ProtocolEntity *isoEntity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); + if (isoEntity == NULL) { + LOGE("Failed to alloc memory for iso entity!"); + return HC_ERR_ALLOC_MEMORY; + } + isoEntity->protocolType = ALG_ISO; + isoEntity->expandProcessCmds = CMD_IMPORT_AUTH_CODE | CMD_ADD_TRUST_DEVICE; + if (info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&isoEntity) == NULL) { + LOGE("Failed to push iso entity!"); + HcFree(isoEntity); + return HC_ERR_ALLOC_MEMORY; + } + return HC_SUCCESS; +#else + (void)info; + return HC_SUCCESS; +#endif +} + +static int32_t SetLiteProtocols(IdentityInfo *info) +{ + int32_t res = SetDlSpekeProtocol(info); + if (res != HC_SUCCESS) { + return res; + } + return SetIsoProtocol(info); +} + +static int32_t SetLiteProtocolsForPinType(const CJson *in, IdentityInfo *info) +{ +#ifndef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK + (void)in; + return SetLiteProtocols(info); +#else + int32_t protocolExpandVal = INVALID_PROTOCOL_EXPAND_VALUE; + (void)GetIntFromJson(in, FIELD_PROTOCOL_EXPAND, &protocolExpandVal); + int32_t res = HC_SUCCESS; + if (protocolExpandVal == LITE_PROTOCOL_STANDARD_MODE || + protocolExpandVal == LITE_PROTOCOL_COMPATIBILITY_MODE) { + res = SetLiteProtocols(info); + } + return res; +#endif +} + +static int32_t SetProtocolsForPinType(const CJson *in, IdentityInfo *info) +{ +#ifdef ENABLE_P2P_BIND_EC_SPEKE + ProtocolEntity *ecSpekeEntity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); + if (ecSpekeEntity == NULL) { + LOGE("Failed to alloc memory for ec speke entity!"); + return HC_ERR_ALLOC_MEMORY; + } + ecSpekeEntity->protocolType = ALG_EC_SPEKE; + ecSpekeEntity->expandProcessCmds = CMD_EXCHANGE_PK | CMD_ADD_TRUST_DEVICE; + if (info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&ecSpekeEntity) == NULL) { + LOGE("Failed to push ec speke entity!"); + HcFree(ecSpekeEntity); + return HC_ERR_ALLOC_MEMORY; + } +#endif + + return SetLiteProtocolsForPinType(in, info); +} + +static bool IsDirectAuth(const CJson *context) +{ + bool isDirectAuth = false; + (void)GetBoolFromJson(context, FIELD_IS_DIRECT_AUTH, &isDirectAuth); + return isDirectAuth; +} + +static int32_t SetProtocolsForDirectAuth(IdentityInfo *info) +{ +#ifdef ENABLE_P2P_AUTH_EC_SPEKE + ProtocolEntity *ecSpekeEntity = (ProtocolEntity *)HcMalloc(sizeof(ProtocolEntity), 0); + if (ecSpekeEntity == NULL) { + LOGE("Failed to alloc memory for ec speke entity!"); + return HC_ERR_ALLOC_MEMORY; + } + ecSpekeEntity->protocolType = ALG_EC_SPEKE; + ecSpekeEntity->expandProcessCmds = 0; + info->protocolVec.pushBack(&info->protocolVec, (const ProtocolEntity **)&ecSpekeEntity); +#else +#endif + + return HC_SUCCESS; +} + +static int32_t GetCredInfosByPeerIdentity(const CJson *in, IdentityInfoVec *vec) +{ + IdentityInfo *info = CreateIdentityInfo(); + if (info == NULL) { + LOGE("Failed to create identity info!"); + return HC_ERR_ALLOC_MEMORY; + } + CJson *urlJson = CreateCredUrlJson(PRE_SHARED, KEY_TYPE_SYM, TRUST_TYPE_PIN); + if (!urlJson) { + LOGE("Failed to create CredUrlJson info!"); + return HC_ERR_ALLOC_MEMORY; + } + if (IsDirectAuth(in) && AddBoolToJson(urlJson, FIELD_IS_DIRECT_AUTH, true) != HC_SUCCESS) { + LOGE("Failed to isDirectAuth to preshared url!"); + FreeJson(urlJson); + return HC_ERR_JSON_ADD; + } + char *urlStr = PackJsonToString(urlJson); + FreeJson(urlJson); + if (urlStr == NULL) { + LOGE("Failed to pack url json to string!"); + return HC_ERR_PACKAGE_JSON_TO_STRING_FAIL; + } + int32_t ret = SetPreSharedUrlForProof(urlStr, &info->proof.preSharedUrl); + FreeJsonString(urlStr); + if (ret != HC_SUCCESS) { + LOGE("Failed to set preSharedUrl of proof!"); + return ret; + } + if (IsDirectAuth(in)) { + ret = SetProtocolsForDirectAuth(info); + info->IdInfoType = P2P_DIRECT_AUTH; + } else { + ret = SetProtocolsForPinType(in, info); + } + if (ret != HC_SUCCESS) { + LOGE("Failed to set protocols!"); + return ret; + } + info->proofType = PRE_SHARED; + vec->pushBack(vec, (const IdentityInfo **)&info); + return HC_SUCCESS; +} + +static int32_t GetCredInfoByPeerUrl(const CJson *in, const Uint8Buff *presharedUrl, IdentityInfo **returnInfo) +{ + if (in == NULL || presharedUrl == NULL || returnInfo == NULL) { + LOGE("Invalid input params!"); + return HC_ERR_INVALID_PARAMS; + } + IdentityInfo *info = CreateIdentityInfo(); + if (info == NULL) { + LOGE("Failed to create identity info!"); + return HC_ERR_ALLOC_MEMORY; + } + CJson *urlJson = CreateJsonFromString((const char *)presharedUrl->val); + if (urlJson == NULL) { + LOGE("Failed to create url json!"); + return HC_ERR_JSON_CREATE; + } + int32_t credentialType = PRE_SHARED; + if (GetIntFromJson(urlJson, PRESHARED_URL_CREDENTIAL_TYPE, &credentialType) != HC_SUCCESS) { + LOGE("Failed to get credential type!"); + FreeJson(urlJson); + return HC_ERR_JSON_GET; + } + FreeJson(urlJson); + int32_t ret = SetPreSharedUrlForProof((const char *)presharedUrl->val, &info->proof.preSharedUrl); + if (ret != HC_SUCCESS) { + LOGE("Failed to set preSharedUrl of proof!"); + return ret; + } + if (IsDirectAuth(in)) { + ret = SetProtocolsForDirectAuth(info); + info->IdInfoType = P2P_DIRECT_AUTH; + } else { + ret = SetProtocolsForPinType(in, info); + } + if (ret != HC_SUCCESS) { + LOGE("Failed to set protocols!"); + return ret; + } + info->proofType = credentialType; + *returnInfo = info; + return HC_SUCCESS; +} + +static int32_t AuthGeneratePskUsePin(const Uint8Buff *seed, const char *pinCode, Uint8Buff *sharedSecret) +{ + Uint8Buff messageBuf = { (uint8_t *)pinCode, (uint32_t)strlen(pinCode) }; + uint8_t hash[SHA256_LEN] = { 0 }; + Uint8Buff hashBuf = { hash, sizeof(hash) }; + int ret = GetLoaderInstance()->sha256(&messageBuf, &hashBuf); + if (ret != HC_SUCCESS) { + LOGE("sha256 failed, ret:%d", ret); + return ret; + } + return GetLoaderInstance()->computeHmac(&hashBuf, seed, sharedSecret, false); +} + +#ifdef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK +static bool CheckPinLenForStandardIso(const CJson *in, const char *pinCode) +{ + int32_t protocolExpandVal = INVALID_PROTOCOL_EXPAND_VALUE; + (void)GetIntFromJson(in, FIELD_PROTOCOL_EXPAND, &protocolExpandVal); + if (protocolExpandVal != LITE_PROTOCOL_STANDARD_MODE) { + LOGI("not standard iso, no need to check."); + return true; + } + return HcStrlen(pinCode) >= PIN_CODE_LEN_LONG; +} +#endif + +static int32_t GetSharedSecretForPinInIso(const CJson *in, Uint8Buff *sharedSecret) +{ + const char *pinCode = GetStringFromJson(in, FIELD_PIN_CODE); + if (pinCode == NULL) { + LOGE("Failed to get pinCode!"); + return HC_ERR_JSON_GET; + } + if (HcStrlen(pinCode) < PIN_CODE_LEN_SHORT) { + LOGE("Pin code is too short!"); + return HC_ERR_INVALID_LEN; + } +#ifdef ENABLE_P2P_BIND_LITE_PROTOCOL_CHECK + if (!CheckPinLenForStandardIso(in, pinCode)) { + LOGE("Invalid pin code len!"); + return HC_ERR_INVALID_LEN; + } +#endif + uint8_t *seedVal = (uint8_t *)HcMalloc(SEED_LEN, 0); + if (seedVal == NULL) { + LOGE("Failed to alloc seed memory!"); + return HC_ERR_ALLOC_MEMORY; + } + Uint8Buff seedBuff = { seedVal, SEED_LEN }; + int32_t ret = GetByteFromJson(in, FIELD_SEED, seedBuff.val, seedBuff.length); + if (ret != HC_SUCCESS) { + LOGE("Failed to get seed!"); + HcFree(seedVal); + return HC_ERR_JSON_GET; + } + uint8_t *pskVal = (uint8_t *)HcMalloc(ISO_PSK_LEN, 0); + if (pskVal == NULL) { + LOGE("Failed to alloc psk memory!"); + HcFree(seedVal); + return HC_ERR_ALLOC_MEMORY; + } + sharedSecret->val = pskVal; + sharedSecret->length = ISO_PSK_LEN; + ret = AuthGeneratePskUsePin(&seedBuff, pinCode, sharedSecret); + HcFree(seedVal); + if (ret != HC_SUCCESS) { + LOGE("Failed to generate psk use pin!"); + FreeBuffData(sharedSecret); + } + return ret; +} + +static int32_t GetSharedSecretForPinInPake(const CJson *in, Uint8Buff *sharedSecret) +{ + const char *pinCode = GetStringFromJson(in, FIELD_PIN_CODE); + if (pinCode == NULL) { + LOGE("Failed to get pinCode!"); + return HC_ERR_JSON_GET; + } + uint32_t pinLen = strlen(pinCode); + if (pinLen < PIN_CODE_LEN_SHORT) { + LOGE("Invalid pin code len!"); + return HC_ERR_INVALID_LEN; + } + sharedSecret->val = (uint8_t *)HcMalloc(pinLen, 0); + if (sharedSecret->val == NULL) { + LOGE("Failed to alloc sharedSecret memory!"); + return HC_ERR_ALLOC_MEMORY; + } + if (memcpy_s(sharedSecret->val, pinLen, pinCode, pinLen) != HC_SUCCESS) { + LOGE("Failed to memcpy pinCode!"); + FreeBuffData(sharedSecret); + return HC_ERR_MEMORY_COPY; + } + sharedSecret->length = pinLen; + return HC_SUCCESS; +} + +static int32_t GetSharedSecretByUrl( + const CJson *in, const Uint8Buff *presharedUrl, ProtocolAlgType protocolType, Uint8Buff *sharedSecret) +{ + if (in == NULL || presharedUrl == NULL || sharedSecret == NULL) { + LOGE("Invalid input params!"); + return HC_ERR_INVALID_PARAMS; + } + int32_t ret; + if (protocolType == ALG_ISO) { + ret = GetSharedSecretForPinInIso(in, sharedSecret); + LOGI("get shared secret for pin in iso result: %d", ret); + } else { + ret = GetSharedSecretForPinInPake(in, sharedSecret); + LOGI("get shared secret for pin in pake result: %d", ret); + } + + return ret; +} + +static int32_t GetCredInfoByPeerCert(const CJson *in, const CertInfo *certInfo, IdentityInfo **returnInfo) +{ + // NOT SUPPORT FOR PIN + return HC_ERR_ALG_FAIL; +} + +static int32_t GetSharedSecretByPeerCert( + const CJson *in, const CertInfo *peerCertInfo, ProtocolAlgType protocolType, Uint8Buff *sharedSecret) +{ + // NOT SUPPORT FOR PIN + return HC_ERR_ALG_FAIL; +} + +static const AuthIdentity g_authIdentity = { + .getCredInfosByPeerIdentity = GetCredInfosByPeerIdentity, + .getCredInfoByPeerUrl = GetCredInfoByPeerUrl, + .getSharedSecretByUrl = GetSharedSecretByUrl, + .getCredInfoByPeerCert = GetCredInfoByPeerCert, + .getSharedSecretByPeerCert = GetSharedSecretByPeerCert, +}; + +const AuthIdentity *GetPinAuthIdentity(void) +{ + return &g_authIdentity; +} \ No newline at end of file diff --git a/services/creds_manager/src/account_related_mock/account_related_creds_manager_mock.c b/services/identity_manager/src/mock/cert_operation_mock.c similarity index 89% rename from services/creds_manager/src/account_related_mock/account_related_creds_manager_mock.c rename to services/identity_manager/src/mock/cert_operation_mock.c index f2bc57ed..eb2a2535 100644 --- a/services/creds_manager/src/account_related_mock/account_related_creds_manager_mock.c +++ b/services/identity_manager/src/mock/cert_operation_mock.c @@ -13,12 +13,11 @@ * limitations under the License. */ -#include "account_related_creds_manager.h" - +#include "cert_operation.h" #include "device_auth_defines.h" -int32_t GetAccountRelatedCredInfo(int32_t osAccountId, const char *groupId, const char *deviceId, - bool isUdid, IdentityInfo *info) +int32_t GetAccountRelatedCredInfo( + int32_t osAccountId, const char *groupId, const char *deviceId, bool isUdid, IdentityInfo *info) { (void)osAccountId; (void)groupId; diff --git a/services/identity_manager/src/mock/identity_common_mock.c b/services/identity_manager/src/mock/identity_common_mock.c new file mode 100644 index 00000000..892db72f --- /dev/null +++ b/services/identity_manager/src/mock/identity_common_mock.c @@ -0,0 +1,51 @@ +/* + * Copyright (C) 2023 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 "identity_common.h" +#include "securec.h" + +IdentityInfo *CreateIdentityInfo(void) +{ + return NULL; +} + +void DestroyIdentityInfo(IdentityInfo *info) +{ + (void)info; +} + +IdentityInfoVec CreateIdentityInfoVec(void) +{ + IdentityInfoVec v; + (void)memset_s(&v, sizeof(IdentityInfo), 0, sizeof(IdentityInfo)); + return v; +} + +void ClearIdentityInfoVec(IdentityInfoVec *vec) +{ + (void)vec; +} + +ProtocolEntityVec CreateProtocolEntityVec(void) +{ + ProtocolEntityVec v; + (void)memset_s(&v, sizeof(ProtocolEntityVec), 0, sizeof(ProtocolEntityVec)); + return v; +} + +void ClearProtocolEntityVec(ProtocolEntityVec *vec) +{ + (void)vec; +} \ No newline at end of file diff --git a/services/identity_manager/src/mock/identity_manager_mock.c b/services/identity_manager/src/mock/identity_manager_mock.c new file mode 100644 index 00000000..b6910224 --- /dev/null +++ b/services/identity_manager/src/mock/identity_manager_mock.c @@ -0,0 +1,65 @@ +/* + * Copyright (C) 2023 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 "identity_manager.h" + +/* in order to expand to uint16_t */ +static const uint8_t KEY_TYPE_PAIRS[KEY_ALIAS_TYPE_END][KEY_TYPE_PAIR_LEN] = { + { 0x00, 0x00 }, /* ACCESSOR_PK */ + { 0x00, 0x01 }, /* CONTROLLER_PK */ + { 0x00, 0x02 }, /* ed25519 KEYPAIR */ + { 0x00, 0x03 }, /* KEK, key encryption key, used only by DeviceAuthService */ + { 0x00, 0x04 }, /* DEK, data encryption key, used only by upper apps */ + { 0x00, 0x05 }, /* key tmp */ + { 0x00, 0x06 }, /* PSK, preshared key index */ + { 0x00, 0x07 }, /* AUTHTOKEN */ + { 0x00, 0x08 } /* P2P_AUTH */ +}; + +uint8_t *GetKeyTypePair(KeyAliasType keyAliasType) +{ + return (uint8_t *)KEY_TYPE_PAIRS[keyAliasType]; +} + +const AuthIdentity *GetAuthIdentityByType(AuthIdentityType type) +{ + (void)type; + return NULL; +} + +const AuthIdentityManager *GetAuthIdentityManager(void) +{ + return NULL; +} + +const AuthIdentity *GetGroupAuthIdentity(void) +{ + return NULL; +} + +const AuthIdentity *GetPinAuthIdentity(void) +{ + return NULL; +} + +const AuthIdentity *GetP2pAuthIdentity(void) +{ + return NULL; +} + +const CredentialOperator *GetCredentialOperator(void) +{ + return NULL; +} diff --git a/services/authenticators/inc/account_related/account_module.h b/services/legacy/authenticators/inc/account_related/account_module.h similarity index 100% rename from services/authenticators/inc/account_related/account_module.h rename to services/legacy/authenticators/inc/account_related/account_module.h diff --git a/services/authenticators/inc/account_related/account_module_defines.h b/services/legacy/authenticators/inc/account_related/account_module_defines.h similarity index 100% rename from services/authenticators/inc/account_related/account_module_defines.h rename to services/legacy/authenticators/inc/account_related/account_module_defines.h diff --git a/services/authenticators/inc/account_related/account_multi_task_manager.h b/services/legacy/authenticators/inc/account_related/account_multi_task_manager.h similarity index 96% rename from services/authenticators/inc/account_related/account_multi_task_manager.h rename to services/legacy/authenticators/inc/account_related/account_multi_task_manager.h index 3d384b6f..66fcd794 100644 --- a/services/authenticators/inc/account_related/account_multi_task_manager.h +++ b/services/legacy/authenticators/inc/account_related/account_multi_task_manager.h @@ -1,46 +1,46 @@ -/* - * Copyright (C) 2022 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 ACCOUNT_MULTI_TASK_MANAGER_H -#define ACCOUNT_MULTI_TASK_MANAGER_H - -#include "account_task_main.h" - -#define ACCOUNT_MULTI_TASK_MAX_SIZE 64 - -typedef struct { - int32_t count; - AccountTask *taskArray[ACCOUNT_MULTI_TASK_MAX_SIZE]; - bool (*isTaskNumUpToMax)(void); - int32_t (*addTaskToManager)(AccountTask *taskBase); - AccountTask *(*getTaskFromManager)(int32_t taskId); - void (*deleteTaskFromManager)(int32_t taskId); -} AccountMultiTaskManager; - -#ifdef __cplusplus -extern "C" { -#endif - -AccountMultiTaskManager *GetAccountMultiTaskManager(void); - -void InitAccountMultiTaskManager(void); - -void DestroyAccountMultiTaskManager(void); - -#ifdef __cplusplus -} -#endif - -#endif +/* + * Copyright (C) 2022 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 ACCOUNT_MULTI_TASK_MANAGER_H +#define ACCOUNT_MULTI_TASK_MANAGER_H + +#include "account_task_main.h" + +#define ACCOUNT_MULTI_TASK_MAX_SIZE 64 + +typedef struct { + int32_t count; + AccountTask *taskArray[ACCOUNT_MULTI_TASK_MAX_SIZE]; + bool (*isTaskNumUpToMax)(void); + int32_t (*addTaskToManager)(AccountTask *taskBase); + AccountTask *(*getTaskFromManager)(int32_t taskId); + void (*deleteTaskFromManager)(int32_t taskId); +} AccountMultiTaskManager; + +#ifdef __cplusplus +extern "C" { +#endif + +AccountMultiTaskManager *GetAccountMultiTaskManager(void); + +void InitAccountMultiTaskManager(void); + +void DestroyAccountMultiTaskManager(void); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/services/authenticators/inc/account_related/account_task_main.h b/services/legacy/authenticators/inc/account_related/account_task_main.h similarity index 96% rename from services/authenticators/inc/account_related/account_task_main.h rename to services/legacy/authenticators/inc/account_related/account_task_main.h index 99995945..e0591024 100644 --- a/services/authenticators/inc/account_related/account_task_main.h +++ b/services/legacy/authenticators/inc/account_related/account_task_main.h @@ -1,47 +1,47 @@ -/* - * Copyright (C) 2022 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 ACCOUNT_TASK_MAIN_H -#define ACCOUNT_TASK_MAIN_H - -#include "json_utils.h" -#include "account_module_defines.h" - -typedef struct TaskBaseT { - AccountTaskType (*getTaskType)(void); - void (*destroyTask)(struct TaskBaseT *); - int32_t (*process)(struct TaskBaseT *, const CJson *in, CJson *out, int32_t *status); - int32_t taskStatus; -} TaskBase; - -typedef struct AccountTaskT { - int32_t taskId; - void (*destroyTask)(struct AccountTaskT *); - int32_t (*processTask)(struct AccountTaskT *, const CJson *in, CJson *out, int32_t *status); - int32_t versionStatus; - TaskBase *subTask; -} AccountTask; - -#ifdef __cplusplus -extern "C" { -#endif - -AccountTask *CreateAccountTaskT(int32_t *taskId, const CJson *in, CJson *out); - -#ifdef __cplusplus -} -#endif - -#endif +/* + * Copyright (C) 2022 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 ACCOUNT_TASK_MAIN_H +#define ACCOUNT_TASK_MAIN_H + +#include "json_utils.h" +#include "account_module_defines.h" + +typedef struct TaskBaseT { + AccountTaskType (*getTaskType)(void); + void (*destroyTask)(struct TaskBaseT *); + int32_t (*process)(struct TaskBaseT *, const CJson *in, CJson *out, int32_t *status); + int32_t taskStatus; +} TaskBase; + +typedef struct AccountTaskT { + int32_t taskId; + void (*destroyTask)(struct AccountTaskT *); + int32_t (*processTask)(struct AccountTaskT *, const CJson *in, CJson *out, int32_t *status); + int32_t versionStatus; + TaskBase *subTask; +} AccountTask; + +#ifdef __cplusplus +extern "C" { +#endif + +AccountTask *CreateAccountTaskT(int32_t *taskId, const CJson *in, CJson *out); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/services/authenticators/inc/account_related/account_version_util.h b/services/legacy/authenticators/inc/account_related/account_version_util.h similarity index 96% rename from services/authenticators/inc/account_related/account_version_util.h rename to services/legacy/authenticators/inc/account_related/account_version_util.h index 968baa0b..28d8dd71 100644 --- a/services/authenticators/inc/account_related/account_version_util.h +++ b/services/legacy/authenticators/inc/account_related/account_version_util.h @@ -1,69 +1,69 @@ -/* - * Copyright (C) 2022 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 ACCOUNT_VERSION_UTIL_H -#define ACCOUNT_VERSION_UTIL_H - -#include "alg_defs.h" -#include "json_utils.h" -#include "pake_defs.h" -#include "protocol_common.h" -#include "account_task_main.h" - -typedef enum { - BIND_VERSION_NO_NONE = 0, - BIND_PAKE_V2_DL = 0x0001, - BIND_PAKE_V2_EC_P256 = 0x0002, - BIND_PAKE_V2_EC_P256_WITH_PROOF = 0x0004, - BIND_PAKE_V2_EC_X25519 = 0x0008, - BIND_PAKE_V1_DL = 0x0010, -} BindVersionNo; - -typedef enum { - AUTH_VERSION_NO_NONE = 0, - AUTH_PAKE_V2_EC_P256 = 0x0001, - AUTH_ISO = 0x0002, -} AuthVersionNo; - -typedef enum { - VERSION_INITIAL = 0, - VERSION_NEGOTIATION = 1, - VERSION_CONFIRMED = 2, -} AccountVersionStatus; - -typedef struct AccountVersionInfoT { - uint64_t versionNo; - ProtocolType protocolType; - PakeAlgType pakeAlgType; - CurveType curveType; - bool withExtraOperation; - bool (*isTaskSupported)(void); - TaskBase *(*createTask)(const CJson *, CJson *, const struct AccountVersionInfoT *); -} AccountVersionInfo; - -#ifdef __cplusplus -extern "C" { -#endif - -void InitVersionInfos(void); -void DestroyVersionInfos(void); -uint64_t GetSupportedVersionNo(int32_t operationCode); -const AccountVersionInfo *GetNegotiatedVersionInfo(int32_t operationCode, int32_t credentialType); - -#ifdef __cplusplus -} -#endif - -#endif +/* + * Copyright (C) 2022 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 ACCOUNT_VERSION_UTIL_H +#define ACCOUNT_VERSION_UTIL_H + +#include "alg_defs.h" +#include "json_utils.h" +#include "pake_defs.h" +#include "protocol_common.h" +#include "account_task_main.h" + +typedef enum { + BIND_VERSION_NO_NONE = 0, + BIND_PAKE_V2_DL = 0x0001, + BIND_PAKE_V2_EC_P256 = 0x0002, + BIND_PAKE_V2_EC_P256_WITH_PROOF = 0x0004, + BIND_PAKE_V2_EC_X25519 = 0x0008, + BIND_PAKE_V1_DL = 0x0010, +} BindVersionNo; + +typedef enum { + AUTH_VERSION_NO_NONE = 0, + AUTH_PAKE_V2_EC_P256 = 0x0001, + AUTH_ISO = 0x0002, +} AuthVersionNo; + +typedef enum { + VERSION_INITIAL = 0, + VERSION_NEGOTIATION = 1, + VERSION_CONFIRMED = 2, +} AccountVersionStatus; + +typedef struct AccountVersionInfoT { + uint64_t versionNo; + ProtocolType protocolType; + PakeAlgType pakeAlgType; + CurveType curveType; + bool withExtraOperation; + bool (*isTaskSupported)(void); + TaskBase *(*createTask)(const CJson *, CJson *, const struct AccountVersionInfoT *); +} AccountVersionInfo; + +#ifdef __cplusplus +extern "C" { +#endif + +void InitVersionInfos(void); +void DestroyVersionInfos(void); +uint64_t GetSupportedVersionNo(int32_t operationCode); +const AccountVersionInfo *GetNegotiatedVersionInfo(int32_t operationCode, int32_t credentialType); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/services/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_client_task.h b/services/legacy/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_client_task.h old mode 100755 new mode 100644 similarity index 96% rename from services/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_client_task.h rename to services/legacy/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_client_task.h index 129c463e..89d6e790 --- a/services/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_client_task.h +++ b/services/legacy/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_client_task.h @@ -1,39 +1,39 @@ -/* - * Copyright (C) 2022 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 ISO_AUTH_CLIENT_TASK_H -#define ISO_AUTH_CLIENT_TASK_H - -#include "account_task_main.h" -#include "account_version_util.h" -#include "json_utils.h" -#include "iso_auth_task_common.h" - -typedef struct { - TaskBase taskBase; - IsoAuthParams params; -} IsoAuthClientTask; - -#ifdef __cplusplus -extern "C" { -#endif - -TaskBase *CreateIsoAuthClientTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo); - -#ifdef __cplusplus -} -#endif - +/* + * Copyright (C) 2022 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 ISO_AUTH_CLIENT_TASK_H +#define ISO_AUTH_CLIENT_TASK_H + +#include "account_task_main.h" +#include "account_version_util.h" +#include "json_utils.h" +#include "iso_auth_task_common.h" + +typedef struct { + TaskBase taskBase; + IsoAuthParams params; +} IsoAuthClientTask; + +#ifdef __cplusplus +extern "C" { +#endif + +TaskBase *CreateIsoAuthClientTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo); + +#ifdef __cplusplus +} +#endif + #endif \ No newline at end of file diff --git a/services/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_server_task.h b/services/legacy/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_server_task.h old mode 100755 new mode 100644 similarity index 96% rename from services/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_server_task.h rename to services/legacy/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_server_task.h index 59e82895..b7d8cbc9 --- a/services/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_server_task.h +++ b/services/legacy/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_server_task.h @@ -1,39 +1,39 @@ -/* - * Copyright (C) 2022 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 ISO_AUTH_SERVER_TASK_H -#define ISO_AUTH_SERVER_TASK_H - -#include "account_task_main.h" -#include "account_version_util.h" -#include "json_utils.h" -#include "iso_auth_task_common.h" - -typedef struct { - TaskBase taskBase; - IsoAuthParams params; -} IsoAuthServerTask; - -#ifdef __cplusplus -extern "C" { -#endif - -TaskBase *CreateIsoAuthServerTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo); - -#ifdef __cplusplus -} -#endif - +/* + * Copyright (C) 2022 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 ISO_AUTH_SERVER_TASK_H +#define ISO_AUTH_SERVER_TASK_H + +#include "account_task_main.h" +#include "account_version_util.h" +#include "json_utils.h" +#include "iso_auth_task_common.h" + +typedef struct { + TaskBase taskBase; + IsoAuthParams params; +} IsoAuthServerTask; + +#ifdef __cplusplus +extern "C" { +#endif + +TaskBase *CreateIsoAuthServerTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo); + +#ifdef __cplusplus +} +#endif + #endif \ No newline at end of file diff --git a/services/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_task_common.h b/services/legacy/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_task_common.h old mode 100755 new mode 100644 similarity index 96% rename from services/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_task_common.h rename to services/legacy/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_task_common.h index 05892ad0..db956c1e --- a/services/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_task_common.h +++ b/services/legacy/authenticators/inc/account_related/auth/iso_auth_task/iso_auth_task_common.h @@ -1,62 +1,62 @@ -/* - * Copyright (C) 2022 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 ISO_AUTH_TASK_COMMON_H -#define ISO_AUTH_TASK_COMMON_H - -#include "account_module_defines.h" -#include "account_task_main.h" -#include "account_version_util.h" -#include "iso_protocol_common.h" -#include "json_utils.h" - -typedef struct { - uint64_t versionNo; - int32_t authForm; - int32_t credentialType; - int32_t localDevType; - int32_t keyLength; - uint8_t seed[SEED_SIZE]; - uint8_t hmacToken[HMAC_TOKEN_SIZE]; - Uint8Buff challenge; - Uint8Buff devIdSelf; - Uint8Buff devIdPeer; - char *userIdSelf; - char *userIdPeer; - char *deviceIdSelf; - char *deviceIdPeer; - IsoBaseParams isoBaseParams; -} IsoAuthParams; - -#ifdef __cplusplus -extern "C" { -#endif - -bool IsIsoAuthTaskSupported(void); - -TaskBase *CreateIsoAuthTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo); - -int32_t InitIsoAuthParams(const CJson *in, IsoAuthParams *params, const AccountVersionInfo *verInfo); -void DestroyIsoAuthParams(IsoAuthParams *params); - -int32_t AccountAuthGeneratePsk(IsoAuthParams *params); -int32_t ExtractAndVerifyPayload(IsoAuthParams *params, const CJson *in); -int32_t AuthIsoSendFinalToOut(IsoAuthParams *params, CJson *out); - -#ifdef __cplusplus -} -#endif - -#endif +/* + * Copyright (C) 2022 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 ISO_AUTH_TASK_COMMON_H +#define ISO_AUTH_TASK_COMMON_H + +#include "account_module_defines.h" +#include "account_task_main.h" +#include "account_version_util.h" +#include "iso_protocol_common.h" +#include "json_utils.h" + +typedef struct { + uint64_t versionNo; + int32_t authForm; + int32_t credentialType; + int32_t localDevType; + int32_t keyLength; + uint8_t seed[SEED_SIZE]; + uint8_t hmacToken[HMAC_TOKEN_SIZE]; + Uint8Buff challenge; + Uint8Buff devIdSelf; + Uint8Buff devIdPeer; + char *userIdSelf; + char *userIdPeer; + char *deviceIdSelf; + char *deviceIdPeer; + IsoBaseParams isoBaseParams; +} IsoAuthParams; + +#ifdef __cplusplus +extern "C" { +#endif + +bool IsIsoAuthTaskSupported(void); + +TaskBase *CreateIsoAuthTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo); + +int32_t InitIsoAuthParams(const CJson *in, IsoAuthParams *params, const AccountVersionInfo *verInfo); +void DestroyIsoAuthParams(IsoAuthParams *params); + +int32_t AccountAuthGeneratePsk(IsoAuthParams *params); +int32_t ExtractAndVerifyPayload(IsoAuthParams *params, const CJson *in); +int32_t AuthIsoSendFinalToOut(IsoAuthParams *params, CJson *out); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/services/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_client_task.h b/services/legacy/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_client_task.h similarity index 96% rename from services/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_client_task.h rename to services/legacy/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_client_task.h index c88390fb..77cd617e 100644 --- a/services/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_client_task.h +++ b/services/legacy/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_client_task.h @@ -1,39 +1,39 @@ -/* - * Copyright (C) 2022 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 PAKE_V2_AUTH_CLIENT_TASK_H -#define PAKE_V2_AUTH_CLIENT_TASK_H - -#include "json_utils.h" -#include "pake_v2_auth_task_common.h" -#include "account_task_main.h" -#include "account_version_util.h" - -typedef struct { - TaskBase taskBase; - PakeAuthParams params; -} PakeV2AuthClientTask; - -#ifdef __cplusplus -extern "C" { -#endif - -TaskBase *CreatePakeV2AuthClientTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo); - -#ifdef __cplusplus -} -#endif - +/* + * Copyright (C) 2022 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 PAKE_V2_AUTH_CLIENT_TASK_H +#define PAKE_V2_AUTH_CLIENT_TASK_H + +#include "json_utils.h" +#include "pake_v2_auth_task_common.h" +#include "account_task_main.h" +#include "account_version_util.h" + +typedef struct { + TaskBase taskBase; + PakeAuthParams params; +} PakeV2AuthClientTask; + +#ifdef __cplusplus +extern "C" { +#endif + +TaskBase *CreatePakeV2AuthClientTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo); + +#ifdef __cplusplus +} +#endif + #endif \ No newline at end of file diff --git a/services/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_server_task.h b/services/legacy/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_server_task.h similarity index 96% rename from services/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_server_task.h rename to services/legacy/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_server_task.h index 5ddc374d..f5056921 100644 --- a/services/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_server_task.h +++ b/services/legacy/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_server_task.h @@ -1,39 +1,39 @@ -/* - * Copyright (C) 2022 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 PAKE_V2_AUTH_SERVER_TASK_H -#define PAKE_V2_AUTH_SERVER_TASK_H - -#include "json_utils.h" -#include "pake_v2_auth_task_common.h" -#include "account_task_main.h" -#include "account_version_util.h" - -typedef struct { - TaskBase taskBase; - PakeAuthParams params; -} PakeV2AuthServerTask; - -#ifdef __cplusplus -extern "C" { -#endif - -TaskBase *CreatePakeV2AuthServerTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo); - -#ifdef __cplusplus -} -#endif - +/* + * Copyright (C) 2022 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 PAKE_V2_AUTH_SERVER_TASK_H +#define PAKE_V2_AUTH_SERVER_TASK_H + +#include "json_utils.h" +#include "pake_v2_auth_task_common.h" +#include "account_task_main.h" +#include "account_version_util.h" + +typedef struct { + TaskBase taskBase; + PakeAuthParams params; +} PakeV2AuthServerTask; + +#ifdef __cplusplus +extern "C" { +#endif + +TaskBase *CreatePakeV2AuthServerTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo); + +#ifdef __cplusplus +} +#endif + #endif \ No newline at end of file diff --git a/services/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_task_common.h b/services/legacy/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_task_common.h similarity index 96% rename from services/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_task_common.h rename to services/legacy/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_task_common.h index 28e4e9c3..8404d33c 100644 --- a/services/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_task_common.h +++ b/services/legacy/authenticators/inc/account_related/auth/pake_v2_auth_task/pake_v2_auth_task_common.h @@ -1,76 +1,76 @@ -/* - * Copyright (C) 2022 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 PAKE_V2_AUTH_TASK_COMMON_H -#define PAKE_V2_AUTH_TASK_COMMON_H - -#include "json_utils.h" -#include "pake_defs.h" -#include "string_util.h" -#include "account_module_defines.h" -#include "account_task_main.h" -#include "account_version_util.h" - -typedef struct { - PakeBaseParams pakeParams; - uint64_t versionNo; - int32_t authForm; - int32_t credentialType; - int32_t osAccountId; - int32_t authKeyAlgEncode; - Uint8Buff deviceIdSelf; - Uint8Buff deviceIdPeer; - Uint8Buff devIdSelf; - Uint8Buff devIdPeer; - uint8_t userIdSelf[DEV_AUTH_USER_ID_SIZE]; - uint8_t userIdPeer[DEV_AUTH_USER_ID_SIZE]; - uint8_t pkSelf[PK_SIZE]; - Uint8Buff pkInfoSelf; - Uint8Buff pkInfoSignSelf; - uint8_t pkPeer[PK_SIZE]; - Uint8Buff pkInfoPeer; - Uint8Buff pkInfoSignPeer; -} PakeAuthParams; - -#ifdef __cplusplus -extern "C" { -#endif -bool IsPakeV2AuthTaskSupported(void); - -TaskBase *CreatePakeV2AuthTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo); - -int32_t VerifyPkSignPeer(const PakeAuthParams *params); - -int32_t GenerateEcdhSharedKey(PakeAuthParams *params); - -int32_t GetPkInfoPeer(PakeAuthParams *params, const CJson *in); - -int32_t InitPakeAuthParams(const CJson *in, PakeAuthParams *params, const AccountVersionInfo *verInfo); - -void DestroyPakeAuthParams(PakeAuthParams *params); - -int32_t ExtractPakePeerId(PakeAuthParams *params, const CJson *in); - -int32_t ExtractPakeSelfId(PakeAuthParams *params); - -int32_t ExtractPeerDeviceId(PakeAuthParams *params, const CJson *in); - -int32_t ExtractPeerDevId(PakeAuthParams *params, const CJson *in); - -#ifdef __cplusplus -} -#endif - -#endif +/* + * Copyright (C) 2022 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 PAKE_V2_AUTH_TASK_COMMON_H +#define PAKE_V2_AUTH_TASK_COMMON_H + +#include "json_utils.h" +#include "pake_defs.h" +#include "string_util.h" +#include "account_module_defines.h" +#include "account_task_main.h" +#include "account_version_util.h" + +typedef struct { + PakeBaseParams pakeParams; + uint64_t versionNo; + int32_t authForm; + int32_t credentialType; + int32_t osAccountId; + int32_t authKeyAlgEncode; + Uint8Buff deviceIdSelf; + Uint8Buff deviceIdPeer; + Uint8Buff devIdSelf; + Uint8Buff devIdPeer; + uint8_t userIdSelf[DEV_AUTH_USER_ID_SIZE]; + uint8_t userIdPeer[DEV_AUTH_USER_ID_SIZE]; + uint8_t pkSelf[PK_SIZE]; + Uint8Buff pkInfoSelf; + Uint8Buff pkInfoSignSelf; + uint8_t pkPeer[PK_SIZE]; + Uint8Buff pkInfoPeer; + Uint8Buff pkInfoSignPeer; +} PakeAuthParams; + +#ifdef __cplusplus +extern "C" { +#endif +bool IsPakeV2AuthTaskSupported(void); + +TaskBase *CreatePakeV2AuthTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo); + +int32_t VerifyPkSignPeer(const PakeAuthParams *params); + +int32_t GenerateEcdhSharedKey(PakeAuthParams *params); + +int32_t GetPkInfoPeer(PakeAuthParams *params, const CJson *in); + +int32_t InitPakeAuthParams(const CJson *in, PakeAuthParams *params, const AccountVersionInfo *verInfo); + +void DestroyPakeAuthParams(PakeAuthParams *params); + +int32_t ExtractPakePeerId(PakeAuthParams *params, const CJson *in); + +int32_t ExtractPakeSelfId(PakeAuthParams *params); + +int32_t ExtractPeerDeviceId(PakeAuthParams *params, const CJson *in); + +int32_t ExtractPeerDevId(PakeAuthParams *params, const CJson *in); + +#ifdef __cplusplus +} +#endif + +#endif diff --git a/services/authenticators/inc/account_related/creds_manager/asy_token_manager.h b/services/legacy/authenticators/inc/account_related/creds_manager/asy_token_manager.h similarity index 100% rename from services/authenticators/inc/account_related/creds_manager/asy_token_manager.h rename to services/legacy/authenticators/inc/account_related/creds_manager/asy_token_manager.h diff --git a/services/authenticators/inc/account_related/creds_manager/sym_token_manager.h b/services/legacy/authenticators/inc/account_related/creds_manager/sym_token_manager.h similarity index 100% rename from services/authenticators/inc/account_related/creds_manager/sym_token_manager.h rename to services/legacy/authenticators/inc/account_related/creds_manager/sym_token_manager.h diff --git a/services/authenticators/inc/account_unrelated/base_sub_task.h b/services/legacy/authenticators/inc/account_unrelated/base_sub_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/base_sub_task.h rename to services/legacy/authenticators/inc/account_unrelated/base_sub_task.h diff --git a/services/authenticators/inc/account_unrelated/das_module.h b/services/legacy/authenticators/inc/account_unrelated/das_module.h similarity index 100% rename from services/authenticators/inc/account_unrelated/das_module.h rename to services/legacy/authenticators/inc/account_unrelated/das_module.h diff --git a/services/authenticators/inc/account_unrelated/das_module_defines.h b/services/legacy/authenticators/inc/account_unrelated/das_module_defines.h similarity index 86% rename from services/authenticators/inc/account_unrelated/das_module_defines.h rename to services/legacy/authenticators/inc/account_unrelated/das_module_defines.h index dd424726..cc0f5bcc 100644 --- a/services/authenticators/inc/account_unrelated/das_module_defines.h +++ b/services/legacy/authenticators/inc/account_unrelated/das_module_defines.h @@ -75,17 +75,4 @@ typedef enum CurTaskTypeT { TASK_TYPE_NONE, } CurTaskType; -typedef enum { - KEY_ALIAS_ACCESSOR_PK = DEVICE_TYPE_ACCESSORY, - KEY_ALIAS_CONTROLLER_PK = DEVICE_TYPE_CONTROLLER, - KEY_ALIAS_LT_KEY_PAIR = 2, - KEY_ALIAS_KEK = 3, - KEY_ALIAS_DEK = 4, - KEY_ALIAS_TMP = 5, - KEY_ALIAS_PSK = 6, - KEY_ALIAS_AUTH_TOKEN = 7, - - KEY_ALIAS_TYPE_END -} KeyAliasType; // 0 ~ 2^8-1, don't change the order - #endif diff --git a/services/authenticators/inc/account_unrelated/das_task_common.h b/services/legacy/authenticators/inc/account_unrelated/das_task_common.h similarity index 98% rename from services/authenticators/inc/account_unrelated/das_task_common.h rename to services/legacy/authenticators/inc/account_unrelated/das_task_common.h index 3a4cf3f3..088757fb 100644 --- a/services/authenticators/inc/account_unrelated/das_task_common.h +++ b/services/legacy/authenticators/inc/account_unrelated/das_task_common.h @@ -17,6 +17,7 @@ #define DAS_COMMON_H #include "das_module_defines.h" +#include "identity_defines.h" #include "hc_types.h" #include "json_utils.h" #include "string_util.h" diff --git a/services/authenticators/inc/account_unrelated/das_task_main.h b/services/legacy/authenticators/inc/account_unrelated/das_task_main.h similarity index 100% rename from services/authenticators/inc/account_unrelated/das_task_main.h rename to services/legacy/authenticators/inc/account_unrelated/das_task_main.h diff --git a/services/authenticators/inc/account_unrelated/das_token_manager.h b/services/legacy/authenticators/inc/account_unrelated/das_token_manager.h similarity index 100% rename from services/authenticators/inc/account_unrelated/das_token_manager.h rename to services/legacy/authenticators/inc/account_unrelated/das_token_manager.h diff --git a/services/authenticators/inc/account_unrelated/das_version_util.h b/services/legacy/authenticators/inc/account_unrelated/das_version_util.h similarity index 100% rename from services/authenticators/inc/account_unrelated/das_version_util.h rename to services/legacy/authenticators/inc/account_unrelated/das_version_util.h diff --git a/services/authenticators/inc/account_unrelated/iso_task/iso_base_cur_task.h b/services/legacy/authenticators/inc/account_unrelated/iso_task/iso_base_cur_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/iso_task/iso_base_cur_task.h rename to services/legacy/authenticators/inc/account_unrelated/iso_task/iso_base_cur_task.h diff --git a/services/authenticators/inc/account_unrelated/iso_task/iso_client_task.h b/services/legacy/authenticators/inc/account_unrelated/iso_task/iso_client_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/iso_task/iso_client_task.h rename to services/legacy/authenticators/inc/account_unrelated/iso_task/iso_client_task.h diff --git a/services/authenticators/inc/account_unrelated/iso_task/iso_protocol_task/iso_client_protocol_task.h b/services/legacy/authenticators/inc/account_unrelated/iso_task/iso_protocol_task/iso_client_protocol_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/iso_task/iso_protocol_task/iso_client_protocol_task.h rename to services/legacy/authenticators/inc/account_unrelated/iso_task/iso_protocol_task/iso_client_protocol_task.h diff --git a/services/authenticators/inc/account_unrelated/iso_task/iso_protocol_task/iso_server_protocol_task.h b/services/legacy/authenticators/inc/account_unrelated/iso_task/iso_protocol_task/iso_server_protocol_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/iso_task/iso_protocol_task/iso_server_protocol_task.h rename to services/legacy/authenticators/inc/account_unrelated/iso_task/iso_protocol_task/iso_server_protocol_task.h diff --git a/services/authenticators/inc/account_unrelated/iso_task/iso_server_task.h b/services/legacy/authenticators/inc/account_unrelated/iso_task/iso_server_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/iso_task/iso_server_task.h rename to services/legacy/authenticators/inc/account_unrelated/iso_task/iso_server_task.h diff --git a/services/authenticators/inc/account_unrelated/iso_task/iso_task_common.h b/services/legacy/authenticators/inc/account_unrelated/iso_task/iso_task_common.h similarity index 100% rename from services/authenticators/inc/account_unrelated/iso_task/iso_task_common.h rename to services/legacy/authenticators/inc/account_unrelated/iso_task/iso_task_common.h diff --git a/services/authenticators/inc/account_unrelated/iso_task/iso_task_main.h b/services/legacy/authenticators/inc/account_unrelated/iso_task/iso_task_main.h similarity index 100% rename from services/authenticators/inc/account_unrelated/iso_task/iso_task_main.h rename to services/legacy/authenticators/inc/account_unrelated/iso_task/iso_task_main.h diff --git a/services/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/das_lite_token_manager.h b/services/legacy/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/das_lite_token_manager.h similarity index 100% rename from services/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/das_lite_token_manager.h rename to services/legacy/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/das_lite_token_manager.h diff --git a/services/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_client_bind_exchange_task.h b/services/legacy/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_client_bind_exchange_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_client_bind_exchange_task.h rename to services/legacy/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_client_bind_exchange_task.h diff --git a/services/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_client_unbind_exchange_task.h b/services/legacy/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_client_unbind_exchange_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_client_unbind_exchange_task.h rename to services/legacy/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_client_unbind_exchange_task.h diff --git a/services/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_server_bind_exchange_task.h b/services/legacy/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_server_bind_exchange_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_server_bind_exchange_task.h rename to services/legacy/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_server_bind_exchange_task.h diff --git a/services/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_server_unbind_exchange_task.h b/services/legacy/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_server_unbind_exchange_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_server_unbind_exchange_task.h rename to services/legacy/authenticators/inc/account_unrelated/iso_task/lite_exchange_task/iso_server_unbind_exchange_task.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/common_standard_bind_exchange.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/common_standard_bind_exchange.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/common_standard_bind_exchange.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/common_standard_bind_exchange.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/das_standard_token_manager.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/das_standard_token_manager.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/das_standard_token_manager.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/das_standard_token_manager.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/pake_base_cur_task.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/pake_base_cur_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/pake_base_cur_task.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/pake_base_cur_task.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/pake_message_util.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/pake_message_util.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/pake_message_util.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/pake_message_util.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/pake_task_common.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/pake_task_common.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/pake_task_common.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/pake_task_common.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_client_protocol_task.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_client_protocol_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_client_protocol_task.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_client_protocol_task.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_client_task.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_client_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_client_task.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_client_task.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task_common.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task_common.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task_common.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task_common.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_server_protocol_task.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_server_protocol_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_server_protocol_task.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_server_protocol_task.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_server_task.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_server_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_server_task.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_server_task.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_task_main.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_task_main.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_task_main.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v1_task/pake_v1_task_main.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_client_protocol_task.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_client_protocol_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_client_protocol_task.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_client_protocol_task.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_client_task.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_client_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_client_task.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_client_task.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_protocol_task_common.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_protocol_task_common.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_protocol_task_common.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_protocol_task_common.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_server_protocol_task.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_server_protocol_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_server_protocol_task.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_server_protocol_task.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_server_task.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_server_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_server_task.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_server_task.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_task_main.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_task_main.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_task_main.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/pake_v2_task/pake_v2_task_main.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/standard_client_bind_exchange_task.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/standard_client_bind_exchange_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/standard_client_bind_exchange_task.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/standard_client_bind_exchange_task.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/standard_exchange_message_util.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/standard_exchange_message_util.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/standard_exchange_message_util.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/standard_exchange_message_util.h diff --git a/services/authenticators/inc/account_unrelated/pake_task/standard_server_bind_exchange_task.h b/services/legacy/authenticators/inc/account_unrelated/pake_task/standard_server_bind_exchange_task.h similarity index 100% rename from services/authenticators/inc/account_unrelated/pake_task/standard_server_bind_exchange_task.h rename to services/legacy/authenticators/inc/account_unrelated/pake_task/standard_server_bind_exchange_task.h diff --git a/services/authenticators/src/account_related/account_module.c b/services/legacy/authenticators/src/account_related/account_module.c similarity index 100% rename from services/authenticators/src/account_related/account_module.c rename to services/legacy/authenticators/src/account_related/account_module.c diff --git a/services/authenticators/src/account_related/account_multi_task_manager.c b/services/legacy/authenticators/src/account_related/account_multi_task_manager.c similarity index 96% rename from services/authenticators/src/account_related/account_multi_task_manager.c rename to services/legacy/authenticators/src/account_related/account_multi_task_manager.c index dcadc6db..9a25daed 100644 --- a/services/authenticators/src/account_related/account_multi_task_manager.c +++ b/services/legacy/authenticators/src/account_related/account_multi_task_manager.c @@ -1,128 +1,128 @@ -/* - * Copyright (C) 2022 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 "account_multi_task_manager.h" -#include "device_auth.h" -#include "device_auth_defines.h" -#include "hc_log.h" -#include "hc_types.h" - -static AccountMultiTaskManager g_taskManager; - -static bool IsManagerHasTaskId(int32_t taskId) -{ - for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) { - if (g_taskManager.taskArray[i] != NULL && taskId == g_taskManager.taskArray[i]->taskId) { - LOGD("Task already exists, taskId: %d.", taskId); - return true; - } - } - LOGD("Multi auth manager do not has task id(%d).", taskId); - return false; -} - -static bool IsTaskNumUpToMax(void) -{ - if (g_taskManager.count >= ACCOUNT_MULTI_TASK_MAX_SIZE) { - LOGD("The number of tasks reaches maximun."); - return true; - } - return false; -} - -static bool CanAddTaskInManager(int32_t taskId) -{ - if (IsTaskNumUpToMax()) { - LOGE("Task number is up to limit."); - return false; - } - if (IsManagerHasTaskId(taskId)) { - LOGE("Task id is already in exist."); - return false; - } - return true; -} - -static int32_t AddTaskToManager(AccountTask *task) -{ - if (task == NULL) { - LOGE("Task is null."); - return HC_ERR_NULL_PTR; - } - - if (!CanAddTaskInManager(task->taskId)) { - LOGE("Can not add task into manager."); - return HC_ERR_ADD_ACCOUNT_TASK; - } - for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) { - if (g_taskManager.taskArray[i] == NULL) { - g_taskManager.taskArray[i] = task; - g_taskManager.count++; - return HC_SUCCESS; - } - } - LOGE("There is no empty space in the task manager."); - return HC_ERR_OUT_OF_LIMIT; -} - -static AccountTask *GetTaskFromManager(int32_t taskId) -{ - for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) { - if ((g_taskManager.taskArray[i] != NULL) && (g_taskManager.taskArray[i]->taskId == taskId)) { - return g_taskManager.taskArray[i]; - } - } - LOGE("Task does not exist, taskId: %d.", taskId); - return NULL; -} - -static void DeleteTaskFromManager(int32_t taskId) -{ - for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) { - if ((g_taskManager.taskArray[i] != NULL) && (g_taskManager.taskArray[i]->taskId == taskId)) { - g_taskManager.taskArray[i]->destroyTask(g_taskManager.taskArray[i]); - g_taskManager.taskArray[i] = NULL; - g_taskManager.count--; - } - } -} - -void InitAccountMultiTaskManager(void) -{ - DestroyAccountMultiTaskManager(); - g_taskManager.count = 0; - g_taskManager.isTaskNumUpToMax = IsTaskNumUpToMax; - g_taskManager.addTaskToManager = AddTaskToManager; - g_taskManager.getTaskFromManager = GetTaskFromManager; - g_taskManager.deleteTaskFromManager = DeleteTaskFromManager; -} - -AccountMultiTaskManager *GetAccountMultiTaskManager(void) -{ - return &g_taskManager; -} - -void DestroyAccountMultiTaskManager(void) -{ - for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) { - if (g_taskManager.taskArray[i] != NULL) { - if (g_taskManager.taskArray[i]->destroyTask != NULL) { - g_taskManager.taskArray[i]->destroyTask(g_taskManager.taskArray[i]); - } - g_taskManager.taskArray[i] = NULL; - } - } - (void)memset_s(&g_taskManager, sizeof(AccountMultiTaskManager), 0, sizeof(AccountMultiTaskManager)); +/* + * Copyright (C) 2022 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 "account_multi_task_manager.h" +#include "device_auth.h" +#include "device_auth_defines.h" +#include "hc_log.h" +#include "hc_types.h" + +static AccountMultiTaskManager g_taskManager; + +static bool IsManagerHasTaskId(int32_t taskId) +{ + for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) { + if (g_taskManager.taskArray[i] != NULL && taskId == g_taskManager.taskArray[i]->taskId) { + LOGD("Task already exists, taskId: %d.", taskId); + return true; + } + } + LOGD("Multi auth manager do not has task id(%d).", taskId); + return false; +} + +static bool IsTaskNumUpToMax(void) +{ + if (g_taskManager.count >= ACCOUNT_MULTI_TASK_MAX_SIZE) { + LOGD("The number of tasks reaches maximun."); + return true; + } + return false; +} + +static bool CanAddTaskInManager(int32_t taskId) +{ + if (IsTaskNumUpToMax()) { + LOGE("Task number is up to limit."); + return false; + } + if (IsManagerHasTaskId(taskId)) { + LOGE("Task id is already in exist."); + return false; + } + return true; +} + +static int32_t AddTaskToManager(AccountTask *task) +{ + if (task == NULL) { + LOGE("Task is null."); + return HC_ERR_NULL_PTR; + } + + if (!CanAddTaskInManager(task->taskId)) { + LOGE("Can not add task into manager."); + return HC_ERR_ADD_ACCOUNT_TASK; + } + for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) { + if (g_taskManager.taskArray[i] == NULL) { + g_taskManager.taskArray[i] = task; + g_taskManager.count++; + return HC_SUCCESS; + } + } + LOGE("There is no empty space in the task manager."); + return HC_ERR_OUT_OF_LIMIT; +} + +static AccountTask *GetTaskFromManager(int32_t taskId) +{ + for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) { + if ((g_taskManager.taskArray[i] != NULL) && (g_taskManager.taskArray[i]->taskId == taskId)) { + return g_taskManager.taskArray[i]; + } + } + LOGE("Task does not exist, taskId: %d.", taskId); + return NULL; +} + +static void DeleteTaskFromManager(int32_t taskId) +{ + for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) { + if ((g_taskManager.taskArray[i] != NULL) && (g_taskManager.taskArray[i]->taskId == taskId)) { + g_taskManager.taskArray[i]->destroyTask(g_taskManager.taskArray[i]); + g_taskManager.taskArray[i] = NULL; + g_taskManager.count--; + } + } +} + +void InitAccountMultiTaskManager(void) +{ + DestroyAccountMultiTaskManager(); + g_taskManager.count = 0; + g_taskManager.isTaskNumUpToMax = IsTaskNumUpToMax; + g_taskManager.addTaskToManager = AddTaskToManager; + g_taskManager.getTaskFromManager = GetTaskFromManager; + g_taskManager.deleteTaskFromManager = DeleteTaskFromManager; +} + +AccountMultiTaskManager *GetAccountMultiTaskManager(void) +{ + return &g_taskManager; +} + +void DestroyAccountMultiTaskManager(void) +{ + for (uint32_t i = 0; i < ACCOUNT_MULTI_TASK_MAX_SIZE; ++i) { + if (g_taskManager.taskArray[i] != NULL) { + if (g_taskManager.taskArray[i]->destroyTask != NULL) { + g_taskManager.taskArray[i]->destroyTask(g_taskManager.taskArray[i]); + } + g_taskManager.taskArray[i] = NULL; + } + } + (void)memset_s(&g_taskManager, sizeof(AccountMultiTaskManager), 0, sizeof(AccountMultiTaskManager)); } \ No newline at end of file diff --git a/services/authenticators/src/account_related/account_task_main.c b/services/legacy/authenticators/src/account_related/account_task_main.c similarity index 96% rename from services/authenticators/src/account_related/account_task_main.c rename to services/legacy/authenticators/src/account_related/account_task_main.c index a3d7e2a7..d4d137db 100644 --- a/services/authenticators/src/account_related/account_task_main.c +++ b/services/legacy/authenticators/src/account_related/account_task_main.c @@ -1,221 +1,221 @@ -/* - * Copyright (C) 2022 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 "account_task_main.h" -#include "alg_defs.h" -#include "alg_loader.h" -#include "common_defs.h" -#include "device_auth.h" -#include "device_auth_defines.h" -#include "clib_error.h" -#include "hc_log.h" -#include "json_utils.h" -#include "account_version_util.h" - -static void AccountSendErrMsgToSelf(CJson *out, int32_t errCode) -{ - CJson *sendToSelf = CreateJson(); - if (sendToSelf == NULL) { - LOGE("Create sendToSelf json failed."); - return; - } - if (AddIntToJson(sendToSelf, FIELD_ERROR_CODE, errCode) != CLIB_SUCCESS) { - LOGE("Add errCode to self json failed."); - FreeJson(sendToSelf); - return; - } - if (AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf) != CLIB_SUCCESS) { - LOGE("Add sendToSelf obj to out json failed."); - FreeJson(sendToSelf); - return; - } - FreeJson(sendToSelf); -} - -static void AccountSendErrMsgToOut(CJson *out, int32_t opCode, int32_t errCode) -{ - CJson *sendToSelf = CreateJson(); - if (sendToSelf == NULL) { - LOGE("Create sendToSelf json failed."); - return; - } - CJson *sendToPeer = CreateJson(); - if (sendToPeer == NULL) { - LOGE("Create sendToPeer json failed."); - FreeJson(sendToSelf); - return; - } - if (opCode == OP_BIND) { - if (AddIntToJson(sendToPeer, FIELD_MESSAGE, ERR_MSG) != CLIB_SUCCESS) { - LOGE("Failed to add error message to json for bind."); - goto CLEAN_UP; - } - } else { - if (AddIntToJson(sendToPeer, FIELD_STEP, ERR_MSG) != CLIB_SUCCESS) { - LOGE("Failed to add error message to json for auth."); - goto CLEAN_UP; - } - } - if (AddIntToJson(sendToPeer, FIELD_ERROR_CODE, errCode) != CLIB_SUCCESS) { - LOGE("Add errCode to json failed."); - goto CLEAN_UP; - } - if (AddIntToJson(sendToSelf, FIELD_AUTH_FORM, ACCOUNT_MODULE) != CLIB_SUCCESS) { - LOGE("Add auth form to json failed."); - goto CLEAN_UP; - } - if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) { - LOGE("Add sendToPeer to json failed."); - goto CLEAN_UP; - } - if (AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf) != CLIB_SUCCESS) { - LOGE("Add sendToSelf to json failed."); - goto CLEAN_UP; - } - -CLEAN_UP: - FreeJson(sendToPeer); - FreeJson(sendToSelf); - return; -} - -static void DestroyTaskT(AccountTask *task) -{ - if (task == NULL) { - return; - } - if (task->subTask != NULL) { - task->subTask->destroyTask(task->subTask); - } - HcFree(task); -} - -static bool IsPeerErrMessage(const CJson *in) -{ - int32_t res = 0; - int32_t message = 0; - if ((GetIntFromJson(in, FIELD_MESSAGE, &message) != CLIB_SUCCESS) && - (GetIntFromJson(in, FIELD_STEP, &message) != CLIB_SUCCESS)) { - LOGD("There is no message code."); // The first message of the client has no message code - return false; - } - if (message != ERR_MSG) { - return false; - } - - if (GetIntFromJson(in, FIELD_ERROR_CODE, &res) != CLIB_SUCCESS) { - LOGE("Get peer error code failed."); - } - LOGE("Receive error message from peer, errCode: %x.", res); - return true; -} - -static int32_t MapSubTaskTypeToOpCode(AccountTaskType subTaskType) -{ - if (subTaskType >= TASK_TYPE_PAKE_V2_AUTH_CLIENT && subTaskType <= TASK_TYPE_ISO_AUTH_SERVER) { - return AUTHENTICATE; - } - return CODE_NULL; -} - -static int32_t ProcessTaskT(AccountTask *task, const CJson *in, CJson *out, int32_t *status) -{ - if (IsPeerErrMessage(in)) { - AccountSendErrMsgToSelf(out, HC_ERR_PEER_ERROR); - return HC_ERR_PEER_ERROR; - } - int32_t res = task->subTask->process(task->subTask, in, out, status); - if (res != HC_SUCCESS) { - LOGE("Process subTask failed, res: %x.", res); - int32_t operationCode = MapSubTaskTypeToOpCode(task->subTask->getTaskType()); - AccountSendErrMsgToOut(out, operationCode, res); - } - return res; -} - -static int32_t NegotiateAndCreateSubTask(AccountTask *task, const CJson *in, CJson *out) -{ - int32_t operationCode = 0; - int32_t credentialType = INVALID_CRED; - if (GetIntFromJson(in, FIELD_OPERATION_CODE, &operationCode) != CLIB_SUCCESS) { - LOGE("Get operationCode from json failed."); - return HC_ERR_JSON_GET; - } - if (GetIntFromJson(in, FIELD_CREDENTIAL_TYPE, &credentialType) != CLIB_SUCCESS) { - LOGE("Failed to get credential type from input data."); - return HC_ERR_JSON_GET; - } - const AccountVersionInfo *verInfo = GetNegotiatedVersionInfo(operationCode, credentialType); - if (verInfo == NULL) { - LOGE("Get Negotiated versionInfo failed."); - return HC_ERR_UNSUPPORTED_VERSION; - } - task->subTask = verInfo->createTask(in, out, verInfo); - if (task->subTask == NULL) { - LOGE("Create sub task failed."); - return HC_ERR_ALLOC_MEMORY; - } - task->versionStatus = VERSION_CONFIRMED; - return HC_SUCCESS; -} - -static void AccountSendCreateError(const CJson *in, CJson *out, int32_t errCode) -{ - bool isClient = false; - if (GetBoolFromJson(in, FIELD_IS_CLIENT, &isClient) != CLIB_SUCCESS) { - LOGE("Get isClient from json failed."); - } - if (isClient) { - AccountSendErrMsgToSelf(out, errCode); - return; - } - int32_t operationCode = CODE_NULL; - if (GetIntFromJson(in, FIELD_OPERATION_CODE, &operationCode) != CLIB_SUCCESS) { - LOGE("Get operationCode from json failed."); - } else { - AccountSendErrMsgToOut(out, operationCode, errCode); - } -} - -AccountTask *CreateAccountTaskT(int32_t *taskId, const CJson *in, CJson *out) -{ - int32_t res; - AccountTask *task = (AccountTask *)HcMalloc(sizeof(AccountTask), 0); - if (task == NULL) { - LOGE("Malloc for account related task failed."); - res = HC_ERR_ALLOC_MEMORY; - goto ERR; - } - task->destroyTask = DestroyTaskT; - task->processTask = ProcessTaskT; - task->versionStatus = VERSION_INITIAL; - Uint8Buff taskIdBuf = { (uint8_t *)taskId, sizeof(int32_t) }; - res = GetLoaderInstance()->generateRandom(&taskIdBuf); - if (res != HC_SUCCESS) { - LOGE("Generate taskId failed, res: %d.", res); - goto ERR; - } - task->taskId = *taskId; - res = NegotiateAndCreateSubTask(task, in, out); - if (res != HC_SUCCESS) { - LOGE("NegotiateAndCreateSubTask failed, res: %d.", res); - goto ERR; - } - return task; -ERR: - AccountSendCreateError(in, out, res); - DestroyTaskT(task); - return NULL; -} +/* + * Copyright (C) 2022 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 "account_task_main.h" +#include "alg_defs.h" +#include "alg_loader.h" +#include "common_defs.h" +#include "device_auth.h" +#include "device_auth_defines.h" +#include "clib_error.h" +#include "hc_log.h" +#include "json_utils.h" +#include "account_version_util.h" + +static void AccountSendErrMsgToSelf(CJson *out, int32_t errCode) +{ + CJson *sendToSelf = CreateJson(); + if (sendToSelf == NULL) { + LOGE("Create sendToSelf json failed."); + return; + } + if (AddIntToJson(sendToSelf, FIELD_ERROR_CODE, errCode) != CLIB_SUCCESS) { + LOGE("Add errCode to self json failed."); + FreeJson(sendToSelf); + return; + } + if (AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf) != CLIB_SUCCESS) { + LOGE("Add sendToSelf obj to out json failed."); + FreeJson(sendToSelf); + return; + } + FreeJson(sendToSelf); +} + +static void AccountSendErrMsgToOut(CJson *out, int32_t opCode, int32_t errCode) +{ + CJson *sendToSelf = CreateJson(); + if (sendToSelf == NULL) { + LOGE("Create sendToSelf json failed."); + return; + } + CJson *sendToPeer = CreateJson(); + if (sendToPeer == NULL) { + LOGE("Create sendToPeer json failed."); + FreeJson(sendToSelf); + return; + } + if (opCode == OP_BIND) { + if (AddIntToJson(sendToPeer, FIELD_MESSAGE, ERR_MSG) != CLIB_SUCCESS) { + LOGE("Failed to add error message to json for bind."); + goto CLEAN_UP; + } + } else { + if (AddIntToJson(sendToPeer, FIELD_STEP, ERR_MSG) != CLIB_SUCCESS) { + LOGE("Failed to add error message to json for auth."); + goto CLEAN_UP; + } + } + if (AddIntToJson(sendToPeer, FIELD_ERROR_CODE, errCode) != CLIB_SUCCESS) { + LOGE("Add errCode to json failed."); + goto CLEAN_UP; + } + if (AddIntToJson(sendToSelf, FIELD_AUTH_FORM, ACCOUNT_MODULE) != CLIB_SUCCESS) { + LOGE("Add auth form to json failed."); + goto CLEAN_UP; + } + if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) { + LOGE("Add sendToPeer to json failed."); + goto CLEAN_UP; + } + if (AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf) != CLIB_SUCCESS) { + LOGE("Add sendToSelf to json failed."); + goto CLEAN_UP; + } + +CLEAN_UP: + FreeJson(sendToPeer); + FreeJson(sendToSelf); + return; +} + +static void DestroyTaskT(AccountTask *task) +{ + if (task == NULL) { + return; + } + if (task->subTask != NULL) { + task->subTask->destroyTask(task->subTask); + } + HcFree(task); +} + +static bool IsPeerErrMessage(const CJson *in) +{ + int32_t res = 0; + int32_t message = 0; + if ((GetIntFromJson(in, FIELD_MESSAGE, &message) != CLIB_SUCCESS) && + (GetIntFromJson(in, FIELD_STEP, &message) != CLIB_SUCCESS)) { + LOGD("There is no message code."); // The first message of the client has no message code + return false; + } + if (message != ERR_MSG) { + return false; + } + + if (GetIntFromJson(in, FIELD_ERROR_CODE, &res) != CLIB_SUCCESS) { + LOGE("Get peer error code failed."); + } + LOGE("Receive error message from peer, errCode: %x.", res); + return true; +} + +static int32_t MapSubTaskTypeToOpCode(AccountTaskType subTaskType) +{ + if (subTaskType >= TASK_TYPE_PAKE_V2_AUTH_CLIENT && subTaskType <= TASK_TYPE_ISO_AUTH_SERVER) { + return AUTHENTICATE; + } + return CODE_NULL; +} + +static int32_t ProcessTaskT(AccountTask *task, const CJson *in, CJson *out, int32_t *status) +{ + if (IsPeerErrMessage(in)) { + AccountSendErrMsgToSelf(out, HC_ERR_PEER_ERROR); + return HC_ERR_PEER_ERROR; + } + int32_t res = task->subTask->process(task->subTask, in, out, status); + if (res != HC_SUCCESS) { + LOGE("Process subTask failed, res: %x.", res); + int32_t operationCode = MapSubTaskTypeToOpCode(task->subTask->getTaskType()); + AccountSendErrMsgToOut(out, operationCode, res); + } + return res; +} + +static int32_t NegotiateAndCreateSubTask(AccountTask *task, const CJson *in, CJson *out) +{ + int32_t operationCode = 0; + int32_t credentialType = INVALID_CRED; + if (GetIntFromJson(in, FIELD_OPERATION_CODE, &operationCode) != CLIB_SUCCESS) { + LOGE("Get operationCode from json failed."); + return HC_ERR_JSON_GET; + } + if (GetIntFromJson(in, FIELD_CREDENTIAL_TYPE, &credentialType) != CLIB_SUCCESS) { + LOGE("Failed to get credential type from input data."); + return HC_ERR_JSON_GET; + } + const AccountVersionInfo *verInfo = GetNegotiatedVersionInfo(operationCode, credentialType); + if (verInfo == NULL) { + LOGE("Get Negotiated versionInfo failed."); + return HC_ERR_UNSUPPORTED_VERSION; + } + task->subTask = verInfo->createTask(in, out, verInfo); + if (task->subTask == NULL) { + LOGE("Create sub task failed."); + return HC_ERR_ALLOC_MEMORY; + } + task->versionStatus = VERSION_CONFIRMED; + return HC_SUCCESS; +} + +static void AccountSendCreateError(const CJson *in, CJson *out, int32_t errCode) +{ + bool isClient = false; + if (GetBoolFromJson(in, FIELD_IS_CLIENT, &isClient) != CLIB_SUCCESS) { + LOGE("Get isClient from json failed."); + } + if (isClient) { + AccountSendErrMsgToSelf(out, errCode); + return; + } + int32_t operationCode = CODE_NULL; + if (GetIntFromJson(in, FIELD_OPERATION_CODE, &operationCode) != CLIB_SUCCESS) { + LOGE("Get operationCode from json failed."); + } else { + AccountSendErrMsgToOut(out, operationCode, errCode); + } +} + +AccountTask *CreateAccountTaskT(int32_t *taskId, const CJson *in, CJson *out) +{ + int32_t res; + AccountTask *task = (AccountTask *)HcMalloc(sizeof(AccountTask), 0); + if (task == NULL) { + LOGE("Malloc for account related task failed."); + res = HC_ERR_ALLOC_MEMORY; + goto ERR; + } + task->destroyTask = DestroyTaskT; + task->processTask = ProcessTaskT; + task->versionStatus = VERSION_INITIAL; + Uint8Buff taskIdBuf = { (uint8_t *)taskId, sizeof(int32_t) }; + res = GetLoaderInstance()->generateRandom(&taskIdBuf); + if (res != HC_SUCCESS) { + LOGE("Generate taskId failed, res: %d.", res); + goto ERR; + } + task->taskId = *taskId; + res = NegotiateAndCreateSubTask(task, in, out); + if (res != HC_SUCCESS) { + LOGE("NegotiateAndCreateSubTask failed, res: %d.", res); + goto ERR; + } + return task; +ERR: + AccountSendCreateError(in, out, res); + DestroyTaskT(task); + return NULL; +} diff --git a/services/authenticators/src/account_related/account_version_util.c b/services/legacy/authenticators/src/account_related/account_version_util.c similarity index 97% rename from services/authenticators/src/account_related/account_version_util.c rename to services/legacy/authenticators/src/account_related/account_version_util.c index b990edd2..de4ba739 100644 --- a/services/authenticators/src/account_related/account_version_util.c +++ b/services/legacy/authenticators/src/account_related/account_version_util.c @@ -1,106 +1,106 @@ -/* - * Copyright (C) 2022 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 "account_version_util.h" -#include "common_defs.h" -#include "hc_log.h" -#include "hc_types.h" -#include "iso_auth_task_common.h" -#include "pake_defs.h" -#include "pake_protocol_dl_common.h" -#include "pake_protocol_ec_common.h" -#include "pake_v2_auth_task_common.h" - -#define IS_SUPPORT_CURVE_256 true -#define IS_SUPPORT_CURVE_25519 false - -DECLARE_HC_VECTOR(AccountVersionInfoVec, void *) -IMPLEMENT_HC_VECTOR(AccountVersionInfoVec, void *, 1) - -static AccountVersionInfoVec g_authVersionInfoVec; - -static uint64_t g_authVersionNo = 0; - -static bool IsAuthPakeV2EcP256Supported(void) -{ - return IsPakeV2AuthTaskSupported() && (GetPakeEcAlg() == PAKE_ALG_EC) && IS_SUPPORT_CURVE_256; -} - -static bool IsAuthIsoSupported(void) -{ - return IsIsoAuthTaskSupported(); -} - -static AccountVersionInfo g_authVersionInfoAll[] = { - { AUTH_PAKE_V2_EC_P256, PAKE_V2, PAKE_ALG_EC, CURVE_256, false, IsAuthPakeV2EcP256Supported, CreatePakeV2AuthTask}, - { AUTH_ISO, ISO, PAKE_ALG_NONE, CURVE_NONE, false, IsAuthIsoSupported, CreateIsoAuthTask } -}; - -void InitVersionInfos(void) -{ - g_authVersionInfoVec = CREATE_HC_VECTOR(AccountVersionInfoVec); - uint32_t size = sizeof(g_authVersionInfoAll) / sizeof(AccountVersionInfo); - for (uint32_t i = 0; i < size; i++) { - if (!g_authVersionInfoAll[i].isTaskSupported()) { - continue; - } - (void)g_authVersionInfoVec.pushBackT(&g_authVersionInfoVec, (void *)(&g_authVersionInfoAll[i])); - g_authVersionNo |= g_authVersionInfoAll[i].versionNo; - } -} - -void DestroyVersionInfos(void) -{ - DESTROY_HC_VECTOR(AccountVersionInfoVec, &g_authVersionInfoVec); -} - -static const AccountVersionInfo *NegotiateForAuth(int32_t credentialType) -{ - uint64_t versionNo; - if (credentialType == SYMMETRIC_CRED) { - versionNo = AUTH_ISO; - } else if (credentialType == ASYMMETRIC_CRED) { - versionNo = AUTH_PAKE_V2_EC_P256; - } else { - LOGE("Invalid credential type for auth: %d.", credentialType); - return NULL; - } - uint32_t index; - void **ptr = NULL; - FOR_EACH_HC_VECTOR(g_authVersionInfoVec, index, ptr) { - AccountVersionInfo *temp = (AccountVersionInfo *)(*ptr); - if ((temp->versionNo & versionNo) == versionNo) { - return temp; - } - } - LOGE("Version is not matched, failed to negotiate for account auth."); - return NULL; -} - -const AccountVersionInfo *GetNegotiatedVersionInfo(int32_t operationCode, int32_t credentialType) -{ - // Now, only support auth negotiate. - if (operationCode != AUTHENTICATE) { - LOGE("operationCode is not auth, not supported."); - return NULL; - } - return NegotiateForAuth(credentialType); -} - -uint64_t GetSupportedVersionNo(int32_t operationCode) -{ - (void)operationCode; // Now, only support auth negotiate. - return g_authVersionNo; -} +/* + * Copyright (C) 2022 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 "account_version_util.h" +#include "common_defs.h" +#include "hc_log.h" +#include "hc_types.h" +#include "iso_auth_task_common.h" +#include "pake_defs.h" +#include "pake_protocol_dl_common.h" +#include "pake_protocol_ec_common.h" +#include "pake_v2_auth_task_common.h" + +#define IS_SUPPORT_CURVE_256 true +#define IS_SUPPORT_CURVE_25519 false + +DECLARE_HC_VECTOR(AccountVersionInfoVec, void *) +IMPLEMENT_HC_VECTOR(AccountVersionInfoVec, void *, 1) + +static AccountVersionInfoVec g_authVersionInfoVec; + +static uint64_t g_authVersionNo = 0; + +static bool IsAuthPakeV2EcP256Supported(void) +{ + return IsPakeV2AuthTaskSupported() && (GetPakeEcAlg() == PAKE_ALG_EC) && IS_SUPPORT_CURVE_256; +} + +static bool IsAuthIsoSupported(void) +{ + return IsIsoAuthTaskSupported(); +} + +static AccountVersionInfo g_authVersionInfoAll[] = { + { AUTH_PAKE_V2_EC_P256, PAKE_V2, PAKE_ALG_EC, CURVE_256, false, IsAuthPakeV2EcP256Supported, CreatePakeV2AuthTask}, + { AUTH_ISO, ISO, PAKE_ALG_NONE, CURVE_NONE, false, IsAuthIsoSupported, CreateIsoAuthTask } +}; + +void InitVersionInfos(void) +{ + g_authVersionInfoVec = CREATE_HC_VECTOR(AccountVersionInfoVec); + uint32_t size = sizeof(g_authVersionInfoAll) / sizeof(AccountVersionInfo); + for (uint32_t i = 0; i < size; i++) { + if (!g_authVersionInfoAll[i].isTaskSupported()) { + continue; + } + (void)g_authVersionInfoVec.pushBackT(&g_authVersionInfoVec, (void *)(&g_authVersionInfoAll[i])); + g_authVersionNo |= g_authVersionInfoAll[i].versionNo; + } +} + +void DestroyVersionInfos(void) +{ + DESTROY_HC_VECTOR(AccountVersionInfoVec, &g_authVersionInfoVec); +} + +static const AccountVersionInfo *NegotiateForAuth(int32_t credentialType) +{ + uint64_t versionNo; + if (credentialType == SYMMETRIC_CRED) { + versionNo = AUTH_ISO; + } else if (credentialType == ASYMMETRIC_CRED) { + versionNo = AUTH_PAKE_V2_EC_P256; + } else { + LOGE("Invalid credential type for auth: %d.", credentialType); + return NULL; + } + uint32_t index; + void **ptr = NULL; + FOR_EACH_HC_VECTOR(g_authVersionInfoVec, index, ptr) { + AccountVersionInfo *temp = (AccountVersionInfo *)(*ptr); + if ((temp->versionNo & versionNo) == versionNo) { + return temp; + } + } + LOGE("Version is not matched, failed to negotiate for account auth."); + return NULL; +} + +const AccountVersionInfo *GetNegotiatedVersionInfo(int32_t operationCode, int32_t credentialType) +{ + // Now, only support auth negotiate. + if (operationCode != AUTHENTICATE) { + LOGE("operationCode is not auth, not supported."); + return NULL; + } + return NegotiateForAuth(credentialType); +} + +uint64_t GetSupportedVersionNo(int32_t operationCode) +{ + (void)operationCode; // Now, only support auth negotiate. + return g_authVersionNo; +} diff --git a/services/authenticators/src/account_related/auth/iso_auth_task/iso_auth_client_task.c b/services/legacy/authenticators/src/account_related/auth/iso_auth_task/iso_auth_client_task.c old mode 100755 new mode 100644 similarity index 97% rename from services/authenticators/src/account_related/auth/iso_auth_task/iso_auth_client_task.c rename to services/legacy/authenticators/src/account_related/auth/iso_auth_task/iso_auth_client_task.c index d3f770b5..4643210e --- a/services/authenticators/src/account_related/auth/iso_auth_task/iso_auth_client_task.c +++ b/services/legacy/authenticators/src/account_related/auth/iso_auth_task/iso_auth_client_task.c @@ -1,387 +1,387 @@ -/* - * Copyright (C) 2022 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 "iso_auth_client_task.h" -#include "account_module_defines.h" -#include "clib_error.h" -#include "common_defs.h" -#include "device_auth.h" -#include "device_auth_defines.h" -#include "hc_log.h" -#include "hc_types.h" -#include "iso_auth_task_common.h" -#include "iso_protocol_common.h" -#include "protocol_common.h" - -enum { - TASK_STATUS_ISO_MAIN_BEGIN = 0, - TASK_STATUS_ISO_MAIN_STEP_ONE = 1, - TASK_STATUS_ISO_MAIN_STEP_TWO = 2, - TASK_STATUS_ISO_MAIN_END = 3, -}; - -static AccountTaskType GetIsoAuthClientType(void) -{ - return TASK_TYPE_ISO_AUTH_CLIENT; -} - -static int32_t AddBeginDataToJson(const IsoAuthParams *params, CJson *sendToPeer) -{ - CJson *data = CreateJson(); - if (data == NULL) { - LOGE("Create data json failed."); - return HC_ERR_JSON_CREATE; - } - - if (AddByteToJson(data, FIELD_SALT, - params->isoBaseParams.randSelf.val, params->isoBaseParams.randSelf.length) != CLIB_SUCCESS) { - LOGE("Add saltSelf to json failed."); - goto CLEAN_UP; - } - if (AddByteToJson(data, FIELD_PAYLOAD, - params->isoBaseParams.authIdSelf.val, params->isoBaseParams.authIdSelf.length) != CLIB_SUCCESS) { - LOGE("Add payloadSelf to json failed."); - goto CLEAN_UP; - } - if (AddByteToJson(data, FIELD_SEED, params->seed, sizeof(params->seed)) != CLIB_SUCCESS) { - LOGE("Add seed to json failed."); - goto CLEAN_UP; - } - if (AddObjToJson(sendToPeer, FIELD_DATA, data) != CLIB_SUCCESS) { - LOGE("Add data json obj to json failed."); - goto CLEAN_UP; - } - - FreeJson(data); - return HC_SUCCESS; -CLEAN_UP: - FreeJson(data); - return HC_ERR_JSON_ADD; -} - -static int32_t PackIsoAuthClientBeginMsg(const IsoAuthParams *params, CJson *out) -{ - CJson *sendToPeer = CreateJson(); - if (sendToPeer == NULL) { - LOGE("Create sendToPeer json failed."); - return HC_ERR_JSON_CREATE; - } - - if (AddIntToJson(sendToPeer, FIELD_AUTH_FORM, params->authForm) != CLIB_SUCCESS) { - LOGE("Add authForm to json failed."); - goto CLEAN_UP; - } - if (AddIntToJson(sendToPeer, FIELD_STEP, CMD_ISO_AUTH_MAIN_ONE) != CLIB_SUCCESS) { - LOGE("Add step code to json failed."); - goto CLEAN_UP; - } - if (AddIntToJson(sendToPeer, FIELD_CREDENTIAL_TYPE, params->credentialType) != CLIB_SUCCESS) { - LOGE("Add credentialType to json failed."); - goto CLEAN_UP; - } - if (AddStringToJson(sendToPeer, FIELD_USER_ID, params->userIdSelf) != CLIB_SUCCESS) { - LOGE("Add userIdSelf to json failed."); - goto CLEAN_UP; - } - if (AddByteToJson(sendToPeer, FIELD_DEV_ID, params->devIdSelf.val, params->devIdSelf.length) != CLIB_SUCCESS) { - LOGE("Add devIdSelf to json failed."); - goto CLEAN_UP; - } - if (AddStringToJson(sendToPeer, FIELD_DEVICE_ID, params->deviceIdSelf) != CLIB_SUCCESS) { - LOGE("Add deviceIdSelf to json failed."); - goto CLEAN_UP; - } - - if (AddBeginDataToJson(params, sendToPeer) != HC_SUCCESS) { - LOGE("AddBeginDataToJson failed."); - goto CLEAN_UP; - } - - if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) { - LOGE("Add sendToPeer to json failed."); - goto CLEAN_UP; - } - FreeJson(sendToPeer); - return HC_SUCCESS; -CLEAN_UP: - FreeJson(sendToPeer); - return HC_ERR_JSON_ADD; -} - -static int32_t AccountAuthGenSeed(IsoAuthParams *params) -{ - Uint8Buff seedBuff = { params->seed, sizeof(params->seed) }; - int32_t res = params->isoBaseParams.loader->generateRandom(&seedBuff); - if (res != HC_SUCCESS) { - LOGE("GenerateRandom for seed failed, res: %d.", res); - } - return res; -} - -static int32_t IsoAuthClientBegin(TaskBase *task, const CJson *in, CJson *out, int32_t *status) -{ - (void)in; - if (task->taskStatus != TASK_STATUS_ISO_MAIN_BEGIN) { - LOGD("The message is repeated, ignore it, taskStatus: %d.", task->taskStatus); - *status = IGNORE_MSG; - return HC_SUCCESS; - } - - IsoAuthClientTask *innerTask = (IsoAuthClientTask *)task; - int32_t ret = IsoClientGenRandom(&innerTask->params.isoBaseParams); - if (ret != HC_SUCCESS) { - LOGE("IsoClientGenRandom failed, res: %d.", ret); - return ret; - } - ret = AccountAuthGenSeed(&innerTask->params); - if (ret != HC_SUCCESS) { - LOGE("AccountAuthGenSeed failed, res: %d.", ret); - return ret; - } - - // Send params to server. - ret = PackIsoAuthClientBeginMsg(&innerTask->params, out); - if (ret != HC_SUCCESS) { - LOGE("PackIsoAuthClientBeginMsg failed, ret: %d.", ret); - return ret; - } - - innerTask->taskBase.taskStatus = TASK_STATUS_ISO_MAIN_STEP_ONE; - *status = CONTINUE; - return HC_SUCCESS; -} - -static int32_t ParseIsoAuthServerGetTokenMsg(IsoAuthParams *params, const CJson *in, Uint8Buff *peerToken) -{ - const char *userIdPeer = GetStringFromJson(in, FIELD_USER_ID); - if (userIdPeer == NULL) { - LOGE("Failed to get userIdPeer from input data for client in sym auth."); - return HC_ERR_JSON_GET; - } - if (strcpy_s(params->userIdPeer, DEV_AUTH_USER_ID_SIZE, userIdPeer) != EOK) { - LOGE("Copy for userIdPeer failed for client in sym auth."); - return HC_ERR_MEMORY_COPY; - } - if (GetByteFromJson(in, FIELD_SALT, params->isoBaseParams.randPeer.val, - params->isoBaseParams.randPeer.length) != CLIB_SUCCESS) { - LOGE("Get saltPeer from json failed for client."); - return HC_ERR_JSON_GET; - } - if (GetByteFromJson(in, FIELD_TOKEN, peerToken->val, peerToken->length) != CLIB_SUCCESS) { - LOGE("Get peerToken from json failed for client."); - return HC_ERR_JSON_GET; - } - int32_t res = ExtractAndVerifyPayload(params, in); - if (res != HC_SUCCESS) { - LOGE("ExtractAndVerifyPayload failed for client, res: %d.", res); - } - return res; -} - -static int32_t PackIsoAuthClientGetTokenMsg(const IsoAuthParams *params, CJson *out) -{ - CJson *sendToPeer = CreateJson(); - if (sendToPeer == NULL) { - LOGE("Create sendToPeer json failed."); - return HC_ERR_JSON_CREATE; - } - CJson *data = CreateJson(); - if (data == NULL) { - LOGE("Create data json failed."); - FreeJson(sendToPeer); - return HC_ERR_JSON_CREATE; - } - - if (AddIntToJson(sendToPeer, FIELD_AUTH_FORM, params->authForm) != CLIB_SUCCESS) { - LOGE("Add authForm to json failed."); - goto CLEAN_UP; - } - if (AddIntToJson(sendToPeer, FIELD_STEP, CMD_ISO_AUTH_MAIN_TWO) != CLIB_SUCCESS) { - LOGE("Add step code to json failed."); - goto CLEAN_UP; - } - if (AddByteToJson(data, FIELD_TOKEN, params->hmacToken, sizeof(params->hmacToken)) != CLIB_SUCCESS) { - LOGE("Add hmacToken to json failed."); - goto CLEAN_UP; - } - if (AddObjToJson(sendToPeer, FIELD_DATA, data) != CLIB_SUCCESS) { - LOGE("Add data json obj to json failed."); - goto CLEAN_UP; - } - if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) { - LOGE("Add sendToPeer to json failed."); - goto CLEAN_UP; - } - FreeJson(sendToPeer); - FreeJson(data); - return HC_SUCCESS; -CLEAN_UP: - FreeJson(sendToPeer); - FreeJson(data); - return HC_ERR_JSON_ADD; -} - -static int32_t IsoAuthClientGetToken(TaskBase *task, const CJson *in, CJson *out, int32_t *status) -{ - IsoAuthClientTask *innerTask = (IsoAuthClientTask *)task; - if (innerTask->taskBase.taskStatus < TASK_STATUS_ISO_MAIN_STEP_ONE) { - LOGE("Message code is not match with task status, taskStatus: %d", innerTask->taskBase.taskStatus); - return HC_ERR_BAD_MESSAGE; - } - if (innerTask->taskBase.taskStatus > TASK_STATUS_ISO_MAIN_STEP_ONE) { - LOGI("The message is repeated, ignore it, taskStatus: %d.", innerTask->taskBase.taskStatus); - *status = IGNORE_MSG; - return HC_SUCCESS; - } - - // Receive params from server. - uint8_t peerToken[HMAC_TOKEN_SIZE] = { 0 }; - Uint8Buff peerTokenBuf = { peerToken, HMAC_TOKEN_SIZE }; - int32_t res = ParseIsoAuthServerGetTokenMsg(&innerTask->params, in, &peerTokenBuf); - if (res != HC_SUCCESS) { - LOGE("ParseIsoAuthServerGetTokenMsg failed, res: %d.", res); - return res; - } - - // Get psk and process hmacToken. - res = AccountAuthGeneratePsk(&innerTask->params); - if (res != HC_SUCCESS) { - LOGE("AccountAuthGeneratePsk failed, res: %d.", res); - return res; - } - Uint8Buff selfTokenBuf = { innerTask->params.hmacToken, HMAC_TOKEN_SIZE }; - res = IsoClientCheckAndGenToken(&(innerTask->params.isoBaseParams), &peerTokenBuf, &selfTokenBuf); - if (res != HC_SUCCESS) { - LOGE("IsoClientCheckAndGenToken failed, res: %d.", res); - return res; - } - - // Send params to server. - res = PackIsoAuthClientGetTokenMsg(&innerTask->params, out); - if (res != HC_SUCCESS) { - LOGE("PackIsoAuthClientGetTokenMsg failed, res: %d.", res); - return res; - } - - innerTask->taskBase.taskStatus = TASK_STATUS_ISO_MAIN_STEP_TWO; - *status = CONTINUE; - return HC_SUCCESS; -} - -static int32_t IsoAuthClientGetSessionKey(TaskBase *task, const CJson *in, CJson *out, int32_t *status) -{ - IsoAuthClientTask *innerTask = (IsoAuthClientTask *)task; - if (innerTask->taskBase.taskStatus < TASK_STATUS_ISO_MAIN_STEP_TWO) { - LOGE("Message code is not match with task status, taskStatus: %d", innerTask->taskBase.taskStatus); - return HC_ERR_BAD_MESSAGE; - } - if (innerTask->taskBase.taskStatus > TASK_STATUS_ISO_MAIN_STEP_TWO) { - LOGI("The message is repeated, ignore it, taskStatus: %d", innerTask->taskBase.taskStatus); - *status = IGNORE_MSG; - return HC_SUCCESS; - } - - // Receive params from server. - uint8_t authResultHmac[AUTH_RESULT_MAC_SIZE] = { 0 }; - if (GetByteFromJson(in, FIELD_AUTH_RESULT_MAC, authResultHmac, sizeof(authResultHmac)) != CLIB_SUCCESS) { - LOGE("Get authResultHmac from json failed."); - return HC_ERR_JSON_GET; - } - - // Generate and verify the HMAC, then generate session key. - int32_t res = IsoClientGenSessionKey(&(innerTask->params.isoBaseParams), 0, authResultHmac, sizeof(authResultHmac)); - if (res != HC_SUCCESS) { - LOGE("IsoClientGenSessionKey failed, res: %d.", res); - return res; - } - - res = AuthIsoSendFinalToOut(&innerTask->params, out); - if (res != HC_SUCCESS) { - LOGE("AuthIsoSendFinalToOut failed, res: %d.", res); - return res; - } - - innerTask->taskBase.taskStatus = TASK_STATUS_ISO_MAIN_END; - *status = FINISH; - return HC_SUCCESS; -} - -static int32_t ProcessClientTask(TaskBase *task, const CJson *in, CJson *out, int32_t *status) -{ - int32_t res; - if (task->taskStatus == TASK_STATUS_ISO_MAIN_BEGIN) { - res = IsoAuthClientBegin(task, in, out, status); - if (res != HC_SUCCESS) { - LOGE("IsoAuthClientBegin failed, res: %d.", res); - } - return res; - } - - int32_t authStep; - if (GetIntFromJson(in, FIELD_STEP, &authStep) != CLIB_SUCCESS) { - LOGE("Get message code from json failed."); - return HC_ERR_JSON_GET; - } - switch (authStep) { - case RET_ISO_AUTH_FOLLOWER_ONE: - res = IsoAuthClientGetToken(task, in, out, status); - break; - case RET_ISO_AUTH_FOLLOWER_TWO: - res = IsoAuthClientGetSessionKey(task, in, out, status); - break; - default: - res = HC_ERR_BAD_MESSAGE; - } - if (res != HC_SUCCESS) { - LOGE("Process iso auth client failed, step: %d, res: %d.", authStep, res); - } - return res; -} - -static void DestroyAuthClientAuthTask(TaskBase *task) -{ - if (task == NULL) { - return; - } - IsoAuthClientTask *innerTask = (IsoAuthClientTask *)task; - DestroyIsoAuthParams(&(innerTask->params)); - HcFree(innerTask); -} - -TaskBase *CreateIsoAuthClientTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo) -{ - if ((in == NULL) || (out == NULL) || (verInfo == NULL)) { - LOGE("Params is null for client sym auth."); - return NULL; - } - IsoAuthClientTask *task = (IsoAuthClientTask *)HcMalloc(sizeof(IsoAuthClientTask), 0); - if (task == NULL) { - LOGE("Malloc for IsoAuthClientTask failed."); - return NULL; - } - task->taskBase.getTaskType = GetIsoAuthClientType; - task->taskBase.process = ProcessClientTask; - task->taskBase.destroyTask = DestroyAuthClientAuthTask; - - int32_t res = InitIsoAuthParams(in, &(task->params), verInfo); - if (res != HC_SUCCESS) { - LOGE("InitIsoAuthParams failed, res: %d.", res); - DestroyAuthClientAuthTask((TaskBase *)task); - return NULL; - } - - task->taskBase.taskStatus = TASK_STATUS_ISO_MAIN_BEGIN; - return (TaskBase *)task; -} +/* + * Copyright (C) 2022 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 "iso_auth_client_task.h" +#include "account_module_defines.h" +#include "clib_error.h" +#include "common_defs.h" +#include "device_auth.h" +#include "device_auth_defines.h" +#include "hc_log.h" +#include "hc_types.h" +#include "iso_auth_task_common.h" +#include "iso_protocol_common.h" +#include "protocol_common.h" + +enum { + TASK_STATUS_ISO_MAIN_BEGIN = 0, + TASK_STATUS_ISO_MAIN_STEP_ONE = 1, + TASK_STATUS_ISO_MAIN_STEP_TWO = 2, + TASK_STATUS_ISO_MAIN_END = 3, +}; + +static AccountTaskType GetIsoAuthClientType(void) +{ + return TASK_TYPE_ISO_AUTH_CLIENT; +} + +static int32_t AddBeginDataToJson(const IsoAuthParams *params, CJson *sendToPeer) +{ + CJson *data = CreateJson(); + if (data == NULL) { + LOGE("Create data json failed."); + return HC_ERR_JSON_CREATE; + } + + if (AddByteToJson(data, FIELD_SALT, + params->isoBaseParams.randSelf.val, params->isoBaseParams.randSelf.length) != CLIB_SUCCESS) { + LOGE("Add saltSelf to json failed."); + goto CLEAN_UP; + } + if (AddByteToJson(data, FIELD_PAYLOAD, + params->isoBaseParams.authIdSelf.val, params->isoBaseParams.authIdSelf.length) != CLIB_SUCCESS) { + LOGE("Add payloadSelf to json failed."); + goto CLEAN_UP; + } + if (AddByteToJson(data, FIELD_SEED, params->seed, sizeof(params->seed)) != CLIB_SUCCESS) { + LOGE("Add seed to json failed."); + goto CLEAN_UP; + } + if (AddObjToJson(sendToPeer, FIELD_DATA, data) != CLIB_SUCCESS) { + LOGE("Add data json obj to json failed."); + goto CLEAN_UP; + } + + FreeJson(data); + return HC_SUCCESS; +CLEAN_UP: + FreeJson(data); + return HC_ERR_JSON_ADD; +} + +static int32_t PackIsoAuthClientBeginMsg(const IsoAuthParams *params, CJson *out) +{ + CJson *sendToPeer = CreateJson(); + if (sendToPeer == NULL) { + LOGE("Create sendToPeer json failed."); + return HC_ERR_JSON_CREATE; + } + + if (AddIntToJson(sendToPeer, FIELD_AUTH_FORM, params->authForm) != CLIB_SUCCESS) { + LOGE("Add authForm to json failed."); + goto CLEAN_UP; + } + if (AddIntToJson(sendToPeer, FIELD_STEP, CMD_ISO_AUTH_MAIN_ONE) != CLIB_SUCCESS) { + LOGE("Add step code to json failed."); + goto CLEAN_UP; + } + if (AddIntToJson(sendToPeer, FIELD_CREDENTIAL_TYPE, params->credentialType) != CLIB_SUCCESS) { + LOGE("Add credentialType to json failed."); + goto CLEAN_UP; + } + if (AddStringToJson(sendToPeer, FIELD_USER_ID, params->userIdSelf) != CLIB_SUCCESS) { + LOGE("Add userIdSelf to json failed."); + goto CLEAN_UP; + } + if (AddByteToJson(sendToPeer, FIELD_DEV_ID, params->devIdSelf.val, params->devIdSelf.length) != CLIB_SUCCESS) { + LOGE("Add devIdSelf to json failed."); + goto CLEAN_UP; + } + if (AddStringToJson(sendToPeer, FIELD_DEVICE_ID, params->deviceIdSelf) != CLIB_SUCCESS) { + LOGE("Add deviceIdSelf to json failed."); + goto CLEAN_UP; + } + + if (AddBeginDataToJson(params, sendToPeer) != HC_SUCCESS) { + LOGE("AddBeginDataToJson failed."); + goto CLEAN_UP; + } + + if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) { + LOGE("Add sendToPeer to json failed."); + goto CLEAN_UP; + } + FreeJson(sendToPeer); + return HC_SUCCESS; +CLEAN_UP: + FreeJson(sendToPeer); + return HC_ERR_JSON_ADD; +} + +static int32_t AccountAuthGenSeed(IsoAuthParams *params) +{ + Uint8Buff seedBuff = { params->seed, sizeof(params->seed) }; + int32_t res = params->isoBaseParams.loader->generateRandom(&seedBuff); + if (res != HC_SUCCESS) { + LOGE("GenerateRandom for seed failed, res: %d.", res); + } + return res; +} + +static int32_t IsoAuthClientBegin(TaskBase *task, const CJson *in, CJson *out, int32_t *status) +{ + (void)in; + if (task->taskStatus != TASK_STATUS_ISO_MAIN_BEGIN) { + LOGD("The message is repeated, ignore it, taskStatus: %d.", task->taskStatus); + *status = IGNORE_MSG; + return HC_SUCCESS; + } + + IsoAuthClientTask *innerTask = (IsoAuthClientTask *)task; + int32_t ret = IsoClientGenRandom(&innerTask->params.isoBaseParams); + if (ret != HC_SUCCESS) { + LOGE("IsoClientGenRandom failed, res: %d.", ret); + return ret; + } + ret = AccountAuthGenSeed(&innerTask->params); + if (ret != HC_SUCCESS) { + LOGE("AccountAuthGenSeed failed, res: %d.", ret); + return ret; + } + + // Send params to server. + ret = PackIsoAuthClientBeginMsg(&innerTask->params, out); + if (ret != HC_SUCCESS) { + LOGE("PackIsoAuthClientBeginMsg failed, ret: %d.", ret); + return ret; + } + + innerTask->taskBase.taskStatus = TASK_STATUS_ISO_MAIN_STEP_ONE; + *status = CONTINUE; + return HC_SUCCESS; +} + +static int32_t ParseIsoAuthServerGetTokenMsg(IsoAuthParams *params, const CJson *in, Uint8Buff *peerToken) +{ + const char *userIdPeer = GetStringFromJson(in, FIELD_USER_ID); + if (userIdPeer == NULL) { + LOGE("Failed to get userIdPeer from input data for client in sym auth."); + return HC_ERR_JSON_GET; + } + if (strcpy_s(params->userIdPeer, DEV_AUTH_USER_ID_SIZE, userIdPeer) != EOK) { + LOGE("Copy for userIdPeer failed for client in sym auth."); + return HC_ERR_MEMORY_COPY; + } + if (GetByteFromJson(in, FIELD_SALT, params->isoBaseParams.randPeer.val, + params->isoBaseParams.randPeer.length) != CLIB_SUCCESS) { + LOGE("Get saltPeer from json failed for client."); + return HC_ERR_JSON_GET; + } + if (GetByteFromJson(in, FIELD_TOKEN, peerToken->val, peerToken->length) != CLIB_SUCCESS) { + LOGE("Get peerToken from json failed for client."); + return HC_ERR_JSON_GET; + } + int32_t res = ExtractAndVerifyPayload(params, in); + if (res != HC_SUCCESS) { + LOGE("ExtractAndVerifyPayload failed for client, res: %d.", res); + } + return res; +} + +static int32_t PackIsoAuthClientGetTokenMsg(const IsoAuthParams *params, CJson *out) +{ + CJson *sendToPeer = CreateJson(); + if (sendToPeer == NULL) { + LOGE("Create sendToPeer json failed."); + return HC_ERR_JSON_CREATE; + } + CJson *data = CreateJson(); + if (data == NULL) { + LOGE("Create data json failed."); + FreeJson(sendToPeer); + return HC_ERR_JSON_CREATE; + } + + if (AddIntToJson(sendToPeer, FIELD_AUTH_FORM, params->authForm) != CLIB_SUCCESS) { + LOGE("Add authForm to json failed."); + goto CLEAN_UP; + } + if (AddIntToJson(sendToPeer, FIELD_STEP, CMD_ISO_AUTH_MAIN_TWO) != CLIB_SUCCESS) { + LOGE("Add step code to json failed."); + goto CLEAN_UP; + } + if (AddByteToJson(data, FIELD_TOKEN, params->hmacToken, sizeof(params->hmacToken)) != CLIB_SUCCESS) { + LOGE("Add hmacToken to json failed."); + goto CLEAN_UP; + } + if (AddObjToJson(sendToPeer, FIELD_DATA, data) != CLIB_SUCCESS) { + LOGE("Add data json obj to json failed."); + goto CLEAN_UP; + } + if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) { + LOGE("Add sendToPeer to json failed."); + goto CLEAN_UP; + } + FreeJson(sendToPeer); + FreeJson(data); + return HC_SUCCESS; +CLEAN_UP: + FreeJson(sendToPeer); + FreeJson(data); + return HC_ERR_JSON_ADD; +} + +static int32_t IsoAuthClientGetToken(TaskBase *task, const CJson *in, CJson *out, int32_t *status) +{ + IsoAuthClientTask *innerTask = (IsoAuthClientTask *)task; + if (innerTask->taskBase.taskStatus < TASK_STATUS_ISO_MAIN_STEP_ONE) { + LOGE("Message code is not match with task status, taskStatus: %d", innerTask->taskBase.taskStatus); + return HC_ERR_BAD_MESSAGE; + } + if (innerTask->taskBase.taskStatus > TASK_STATUS_ISO_MAIN_STEP_ONE) { + LOGI("The message is repeated, ignore it, taskStatus: %d.", innerTask->taskBase.taskStatus); + *status = IGNORE_MSG; + return HC_SUCCESS; + } + + // Receive params from server. + uint8_t peerToken[HMAC_TOKEN_SIZE] = { 0 }; + Uint8Buff peerTokenBuf = { peerToken, HMAC_TOKEN_SIZE }; + int32_t res = ParseIsoAuthServerGetTokenMsg(&innerTask->params, in, &peerTokenBuf); + if (res != HC_SUCCESS) { + LOGE("ParseIsoAuthServerGetTokenMsg failed, res: %d.", res); + return res; + } + + // Get psk and process hmacToken. + res = AccountAuthGeneratePsk(&innerTask->params); + if (res != HC_SUCCESS) { + LOGE("AccountAuthGeneratePsk failed, res: %d.", res); + return res; + } + Uint8Buff selfTokenBuf = { innerTask->params.hmacToken, HMAC_TOKEN_SIZE }; + res = IsoClientCheckAndGenToken(&(innerTask->params.isoBaseParams), &peerTokenBuf, &selfTokenBuf); + if (res != HC_SUCCESS) { + LOGE("IsoClientCheckAndGenToken failed, res: %d.", res); + return res; + } + + // Send params to server. + res = PackIsoAuthClientGetTokenMsg(&innerTask->params, out); + if (res != HC_SUCCESS) { + LOGE("PackIsoAuthClientGetTokenMsg failed, res: %d.", res); + return res; + } + + innerTask->taskBase.taskStatus = TASK_STATUS_ISO_MAIN_STEP_TWO; + *status = CONTINUE; + return HC_SUCCESS; +} + +static int32_t IsoAuthClientGetSessionKey(TaskBase *task, const CJson *in, CJson *out, int32_t *status) +{ + IsoAuthClientTask *innerTask = (IsoAuthClientTask *)task; + if (innerTask->taskBase.taskStatus < TASK_STATUS_ISO_MAIN_STEP_TWO) { + LOGE("Message code is not match with task status, taskStatus: %d", innerTask->taskBase.taskStatus); + return HC_ERR_BAD_MESSAGE; + } + if (innerTask->taskBase.taskStatus > TASK_STATUS_ISO_MAIN_STEP_TWO) { + LOGI("The message is repeated, ignore it, taskStatus: %d", innerTask->taskBase.taskStatus); + *status = IGNORE_MSG; + return HC_SUCCESS; + } + + // Receive params from server. + uint8_t authResultHmac[AUTH_RESULT_MAC_SIZE] = { 0 }; + if (GetByteFromJson(in, FIELD_AUTH_RESULT_MAC, authResultHmac, sizeof(authResultHmac)) != CLIB_SUCCESS) { + LOGE("Get authResultHmac from json failed."); + return HC_ERR_JSON_GET; + } + + // Generate and verify the HMAC, then generate session key. + int32_t res = IsoClientGenSessionKey(&(innerTask->params.isoBaseParams), 0, authResultHmac, sizeof(authResultHmac)); + if (res != HC_SUCCESS) { + LOGE("IsoClientGenSessionKey failed, res: %d.", res); + return res; + } + + res = AuthIsoSendFinalToOut(&innerTask->params, out); + if (res != HC_SUCCESS) { + LOGE("AuthIsoSendFinalToOut failed, res: %d.", res); + return res; + } + + innerTask->taskBase.taskStatus = TASK_STATUS_ISO_MAIN_END; + *status = FINISH; + return HC_SUCCESS; +} + +static int32_t ProcessClientTask(TaskBase *task, const CJson *in, CJson *out, int32_t *status) +{ + int32_t res; + if (task->taskStatus == TASK_STATUS_ISO_MAIN_BEGIN) { + res = IsoAuthClientBegin(task, in, out, status); + if (res != HC_SUCCESS) { + LOGE("IsoAuthClientBegin failed, res: %d.", res); + } + return res; + } + + int32_t authStep; + if (GetIntFromJson(in, FIELD_STEP, &authStep) != CLIB_SUCCESS) { + LOGE("Get message code from json failed."); + return HC_ERR_JSON_GET; + } + switch (authStep) { + case RET_ISO_AUTH_FOLLOWER_ONE: + res = IsoAuthClientGetToken(task, in, out, status); + break; + case RET_ISO_AUTH_FOLLOWER_TWO: + res = IsoAuthClientGetSessionKey(task, in, out, status); + break; + default: + res = HC_ERR_BAD_MESSAGE; + } + if (res != HC_SUCCESS) { + LOGE("Process iso auth client failed, step: %d, res: %d.", authStep, res); + } + return res; +} + +static void DestroyAuthClientAuthTask(TaskBase *task) +{ + if (task == NULL) { + return; + } + IsoAuthClientTask *innerTask = (IsoAuthClientTask *)task; + DestroyIsoAuthParams(&(innerTask->params)); + HcFree(innerTask); +} + +TaskBase *CreateIsoAuthClientTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo) +{ + if ((in == NULL) || (out == NULL) || (verInfo == NULL)) { + LOGE("Params is null for client sym auth."); + return NULL; + } + IsoAuthClientTask *task = (IsoAuthClientTask *)HcMalloc(sizeof(IsoAuthClientTask), 0); + if (task == NULL) { + LOGE("Malloc for IsoAuthClientTask failed."); + return NULL; + } + task->taskBase.getTaskType = GetIsoAuthClientType; + task->taskBase.process = ProcessClientTask; + task->taskBase.destroyTask = DestroyAuthClientAuthTask; + + int32_t res = InitIsoAuthParams(in, &(task->params), verInfo); + if (res != HC_SUCCESS) { + LOGE("InitIsoAuthParams failed, res: %d.", res); + DestroyAuthClientAuthTask((TaskBase *)task); + return NULL; + } + + task->taskBase.taskStatus = TASK_STATUS_ISO_MAIN_BEGIN; + return (TaskBase *)task; +} diff --git a/services/authenticators/src/account_related/auth/iso_auth_task/iso_auth_server_task.c b/services/legacy/authenticators/src/account_related/auth/iso_auth_task/iso_auth_server_task.c old mode 100755 new mode 100644 similarity index 97% rename from services/authenticators/src/account_related/auth/iso_auth_task/iso_auth_server_task.c rename to services/legacy/authenticators/src/account_related/auth/iso_auth_task/iso_auth_server_task.c index 050f79bd..346ecc44 --- a/services/authenticators/src/account_related/auth/iso_auth_task/iso_auth_server_task.c +++ b/services/legacy/authenticators/src/account_related/auth/iso_auth_task/iso_auth_server_task.c @@ -1,343 +1,343 @@ -/* - * Copyright (C) 2022 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 "iso_auth_server_task.h" -#include "account_module_defines.h" -#include "clib_error.h" -#include "common_defs.h" -#include "device_auth.h" -#include "device_auth_defines.h" -#include "hc_log.h" -#include "hc_types.h" -#include "iso_auth_task_common.h" -#include "iso_protocol_common.h" -#include "protocol_common.h" - -enum { - TASK_STATUS_SERVER_BEGIN_TOKEN = 0, - TASK_STATUS_SERVER_GEN_SESSION_KEY = 1, - TASK_STATUS_SERVER_END = 2, -}; - -static AccountTaskType GetIsoAuthServerType(void) -{ - return TASK_TYPE_ISO_AUTH_SERVER; -} - -static int32_t ParseIsoAuthClientBeginMsg(IsoAuthParams *params, const CJson *in) -{ - const char *userIdPeer = GetStringFromJson(in, FIELD_USER_ID); - if (userIdPeer == NULL) { - LOGE("Failed to get userIdPeer from input data for server in sym auth."); - return HC_ERR_JSON_GET; - } - if (strcpy_s(params->userIdPeer, DEV_AUTH_USER_ID_SIZE, userIdPeer) != EOK) { - LOGE("Copy for userIdPeer failed for server in sym auth."); - return HC_ERR_MEMORY_COPY; - } - if (GetByteFromJson(in, FIELD_SEED, params->seed, sizeof(params->seed)) != CLIB_SUCCESS) { - LOGE("Get seed from json failed for server."); - return HC_ERR_JSON_GET; - } - if (GetByteFromJson(in, FIELD_SALT, params->isoBaseParams.randPeer.val, - params->isoBaseParams.randPeer.length) != CLIB_SUCCESS) { - LOGE("Get saltPeer from json failed for server."); - return HC_ERR_JSON_GET; - } - int32_t res = ExtractAndVerifyPayload(params, in); - if (res != HC_SUCCESS) { - LOGE("ExtractAndVerifyPayload failed for server, res: %d.", res); - } - return res; -} - -static int32_t AddGetTokenDataToJson(const IsoAuthParams *params, CJson *sendToPeer) -{ - CJson *data = CreateJson(); - if (data == NULL) { - LOGE("Create data json failed."); - return HC_ERR_JSON_CREATE; - } - if (AddByteToJson(data, FIELD_PAYLOAD, - params->isoBaseParams.authIdSelf.val, params->isoBaseParams.authIdSelf.length) != CLIB_SUCCESS) { - LOGE("Add payloadSelf to json failed."); - goto CLEAN_UP; - } - if (AddByteToJson(data, FIELD_TOKEN, params->hmacToken, sizeof(params->hmacToken)) != CLIB_SUCCESS) { - LOGE("Add hmacToken to json failed."); - goto CLEAN_UP; - } - if (AddByteToJson(data, FIELD_SALT, - params->isoBaseParams.randSelf.val, params->isoBaseParams.randSelf.length) != CLIB_SUCCESS) { - LOGE("Add saltSelf to json failed."); - goto CLEAN_UP; - } - if (AddObjToJson(sendToPeer, FIELD_DATA, data) != CLIB_SUCCESS) { - LOGE("Add data json obj to json failed."); - goto CLEAN_UP; - } - - FreeJson(data); - return HC_SUCCESS; -CLEAN_UP: - FreeJson(data); - return HC_ERR_JSON_ADD; -} - -static int32_t PackIsoAuthServerGetTokenMsg(const IsoAuthParams *params, CJson *out) -{ - CJson *sendToPeer = CreateJson(); - if (sendToPeer == NULL) { - LOGE("Create sendToPeer json is null in server."); - return HC_ERR_JSON_CREATE; - } - - if (AddIntToJson(sendToPeer, FIELD_STEP, RET_ISO_AUTH_FOLLOWER_ONE) != CLIB_SUCCESS) { - LOGE("Add step code to json failed in server."); - goto CLEAN_UP; - } - if (AddIntToJson(sendToPeer, FIELD_AUTH_FORM, params->authForm) != CLIB_SUCCESS) { - LOGE("Add authForm to json failed in server."); - goto CLEAN_UP; - } - if (AddStringToJson(sendToPeer, FIELD_USER_ID, params->userIdSelf) != CLIB_SUCCESS) { - LOGE("Add userIdSelf to json failed in server."); - goto CLEAN_UP; - } - if (AddByteToJson(sendToPeer, FIELD_DEV_ID, params->devIdSelf.val, params->devIdSelf.length) != CLIB_SUCCESS) { - LOGE("Add devIdSelf to json failed in server."); - goto CLEAN_UP; - } - if (AddStringToJson(sendToPeer, FIELD_DEVICE_ID, params->deviceIdSelf) != CLIB_SUCCESS) { - LOGE("Add deviceIdSelf to json failed in server."); - goto CLEAN_UP; - } - - int32_t res = AddGetTokenDataToJson(params, sendToPeer); - if (res != HC_SUCCESS) { - LOGE("AddGetTokenDataToJson failed, res: %d.", res); - FreeJson(sendToPeer); - return res; - } - - if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) { - LOGE("Add sendToPeer to json failed."); - goto CLEAN_UP; - } - - FreeJson(sendToPeer); - return HC_SUCCESS; -CLEAN_UP: - FreeJson(sendToPeer); - return HC_ERR_JSON_ADD; -} - -static int32_t IsoAuthServerGetToken(TaskBase *task, const CJson *in, CJson *out, int32_t *status) -{ - IsoAuthServerTask *innerTask = (IsoAuthServerTask *)task; - if (innerTask->taskBase.taskStatus < TASK_STATUS_SERVER_BEGIN_TOKEN) { - LOGE("Message code is not match with task status, taskStatus: %d", innerTask->taskBase.taskStatus); - return HC_ERR_BAD_MESSAGE; - } - if (innerTask->taskBase.taskStatus > TASK_STATUS_SERVER_BEGIN_TOKEN) { - LOGI("The message is repeated, ignore it, taskStatus: %d.", innerTask->taskBase.taskStatus); - *status = IGNORE_MSG; - return HC_SUCCESS; - } - - // Receive params from client. - int32_t res = ParseIsoAuthClientBeginMsg(&innerTask->params, in); - if (res != HC_SUCCESS) { - LOGE("ParseIsoAuthClientBeginMsg failed, res: %d.", res); - return res; - } - - // Get psk and process hmacToken. - res = AccountAuthGeneratePsk(&innerTask->params); - if (res != HC_SUCCESS) { - LOGE("AccountAuthGeneratePsk failed, res: %d.", res); - return res; - } - Uint8Buff selfTokenBuf = { innerTask->params.hmacToken, HMAC_TOKEN_SIZE }; - res = IsoServerGenRandomAndToken(&innerTask->params.isoBaseParams, &selfTokenBuf); - if (res != HC_SUCCESS) { - LOGE("IsoServerGenRandomAndToken failed, res: %d.", res); - return res; - } - - // Send params to client. - res = PackIsoAuthServerGetTokenMsg(&innerTask->params, out); - if (res != HC_SUCCESS) { - LOGE("PackIsoAuthServerGetTokenMsg failed, res: %d.", res); - return res; - } - - innerTask->taskBase.taskStatus = TASK_STATUS_SERVER_GEN_SESSION_KEY; - *status = CONTINUE; - return HC_SUCCESS; -} - -static int32_t PackCalTokenAndSessionKeyMsg(const IsoAuthParams *params, CJson *out, const Uint8Buff *authResultMac) -{ - CJson *sendToPeer = CreateJson(); - if (sendToPeer == NULL) { - LOGE("Create sendToPeer json failed."); - return HC_ERR_JSON_CREATE; - } - CJson *data = CreateJson(); - if (data == NULL) { - LOGE("Create data json failed."); - FreeJson(sendToPeer); - return HC_ERR_JSON_CREATE; - } - - if (AddIntToJson(sendToPeer, FIELD_STEP, RET_ISO_AUTH_FOLLOWER_TWO) != CLIB_SUCCESS) { - LOGE("Add step code to json failed."); - goto CLEAN_UP; - } - if (AddIntToJson(sendToPeer, FIELD_AUTH_FORM, params->authForm) != CLIB_SUCCESS) { - LOGE("Add authForm to json failed."); - goto CLEAN_UP; - } - if (AddByteToJson(data, FIELD_AUTH_RESULT_MAC, authResultMac->val, authResultMac->length) != CLIB_SUCCESS) { - LOGE("Add authResultMac to json failed."); - goto CLEAN_UP; - } - if (AddObjToJson(sendToPeer, FIELD_DATA, data) != CLIB_SUCCESS) { - LOGE("Add data json obj to json failed."); - goto CLEAN_UP; - } - if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) { - LOGE("Add sendToPeer to json failed."); - goto CLEAN_UP; - } - FreeJson(sendToPeer); - FreeJson(data); - return HC_SUCCESS; -CLEAN_UP: - FreeJson(sendToPeer); - FreeJson(data); - return HC_ERR_JSON_ADD; -} - -static int32_t IsoAuthServerCalTokenAndSessionKey(TaskBase *task, const CJson *in, CJson *out, int32_t *status) -{ - IsoAuthServerTask *innerTask = (IsoAuthServerTask *)task; - if (innerTask->taskBase.taskStatus < TASK_STATUS_SERVER_GEN_SESSION_KEY) { - LOGE("Message code is not match with task status, taskStatus: %d", innerTask->taskBase.taskStatus); - return HC_ERR_BAD_MESSAGE; - } - if (innerTask->taskBase.taskStatus > TASK_STATUS_SERVER_GEN_SESSION_KEY) { - LOGI("The message is repeated, ignore it, taskStatus: %d.", innerTask->taskBase.taskStatus); - *status = IGNORE_MSG; - return HC_SUCCESS; - } - - // Receive params from client. - uint8_t peerToken[HMAC_TOKEN_SIZE] = { 0 }; - Uint8Buff peerTokenBuf = { peerToken, HMAC_TOKEN_SIZE }; - if (GetByteFromJson(in, FIELD_TOKEN, peerToken, sizeof(peerToken)) != CLIB_SUCCESS) { - LOGE("Get peerToken from json failed."); - return HC_ERR_JSON_GET; - } - - // Process hmacToken and generate session key. - uint8_t authResultMac[AUTH_RESULT_MAC_SIZE] = { 0 }; - Uint8Buff authResultMacBuf = { authResultMac, AUTH_RESULT_MAC_SIZE }; - int32_t res = IsoServerGenSessionKeyAndCalToken(&(innerTask->params.isoBaseParams), - &peerTokenBuf, &authResultMacBuf); - if (res != HC_SUCCESS) { - LOGE("IsoServerGenSessionKeyAndCalToken failed, res: %d.", res); - return res; - } - - // Return params to client. - res = PackCalTokenAndSessionKeyMsg(&innerTask->params, out, &authResultMacBuf); - if (res != HC_SUCCESS) { - LOGE("PackCalTokenAndSessionKeyMsg failed, res: %d.", res); - return res; - } - - // Return params to server self. - res = AuthIsoSendFinalToOut(&innerTask->params, out); - if (res != HC_SUCCESS) { - LOGE("AuthIsoSendFinalToOut failed, res: %d.", res); - return res; - } - - innerTask->taskBase.taskStatus = TASK_STATUS_SERVER_END; - *status = FINISH; - return HC_SUCCESS; -} - -static int32_t ProcessServerTask(TaskBase *task, const CJson *in, CJson *out, int32_t *status) -{ - int32_t authStep; - if (GetIntFromJson(in, FIELD_STEP, &authStep) != CLIB_SUCCESS) { - LOGE("Get step code from json failed."); - return HC_ERR_JSON_GET; - } - int32_t res; - switch (authStep) { - case CMD_ISO_AUTH_MAIN_ONE: - res = IsoAuthServerGetToken(task, in, out, status); - break; - case CMD_ISO_AUTH_MAIN_TWO: - res = IsoAuthServerCalTokenAndSessionKey(task, in, out, status); - break; - default: - res = HC_ERR_BAD_MESSAGE; - } - if (res != HC_SUCCESS) { - LOGE("Process iso auth server failed, step: %d, res: %d.", authStep, res); - } - return res; -} - -static void DestroyAuthServerAuthTask(TaskBase *task) -{ - if (task == NULL) { - return; - } - IsoAuthServerTask *innerTask = (IsoAuthServerTask *)task; - DestroyIsoAuthParams(&(innerTask->params)); - HcFree(innerTask); -} - -TaskBase *CreateIsoAuthServerTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo) -{ - if ((in == NULL) || (out == NULL) || (verInfo == NULL)) { - LOGE("Params is null for server sym auth."); - return NULL; - } - IsoAuthServerTask *task = (IsoAuthServerTask *)HcMalloc(sizeof(IsoAuthServerTask), 0); - if (task == NULL) { - LOGE("Malloc for IsoAuthServerTask failed."); - return NULL; - } - task->taskBase.getTaskType = GetIsoAuthServerType; - task->taskBase.process = ProcessServerTask; - task->taskBase.destroyTask = DestroyAuthServerAuthTask; - - int32_t res = InitIsoAuthParams(in, &(task->params), verInfo); - if (res != HC_SUCCESS) { - LOGE("InitIsoAuthParams failed, res: %d.", res); - DestroyAuthServerAuthTask((TaskBase *)task); - return NULL; - } - - task->taskBase.taskStatus = TASK_STATUS_SERVER_BEGIN_TOKEN; - return (TaskBase *)task; -} +/* + * Copyright (C) 2022 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 "iso_auth_server_task.h" +#include "account_module_defines.h" +#include "clib_error.h" +#include "common_defs.h" +#include "device_auth.h" +#include "device_auth_defines.h" +#include "hc_log.h" +#include "hc_types.h" +#include "iso_auth_task_common.h" +#include "iso_protocol_common.h" +#include "protocol_common.h" + +enum { + TASK_STATUS_SERVER_BEGIN_TOKEN = 0, + TASK_STATUS_SERVER_GEN_SESSION_KEY = 1, + TASK_STATUS_SERVER_END = 2, +}; + +static AccountTaskType GetIsoAuthServerType(void) +{ + return TASK_TYPE_ISO_AUTH_SERVER; +} + +static int32_t ParseIsoAuthClientBeginMsg(IsoAuthParams *params, const CJson *in) +{ + const char *userIdPeer = GetStringFromJson(in, FIELD_USER_ID); + if (userIdPeer == NULL) { + LOGE("Failed to get userIdPeer from input data for server in sym auth."); + return HC_ERR_JSON_GET; + } + if (strcpy_s(params->userIdPeer, DEV_AUTH_USER_ID_SIZE, userIdPeer) != EOK) { + LOGE("Copy for userIdPeer failed for server in sym auth."); + return HC_ERR_MEMORY_COPY; + } + if (GetByteFromJson(in, FIELD_SEED, params->seed, sizeof(params->seed)) != CLIB_SUCCESS) { + LOGE("Get seed from json failed for server."); + return HC_ERR_JSON_GET; + } + if (GetByteFromJson(in, FIELD_SALT, params->isoBaseParams.randPeer.val, + params->isoBaseParams.randPeer.length) != CLIB_SUCCESS) { + LOGE("Get saltPeer from json failed for server."); + return HC_ERR_JSON_GET; + } + int32_t res = ExtractAndVerifyPayload(params, in); + if (res != HC_SUCCESS) { + LOGE("ExtractAndVerifyPayload failed for server, res: %d.", res); + } + return res; +} + +static int32_t AddGetTokenDataToJson(const IsoAuthParams *params, CJson *sendToPeer) +{ + CJson *data = CreateJson(); + if (data == NULL) { + LOGE("Create data json failed."); + return HC_ERR_JSON_CREATE; + } + if (AddByteToJson(data, FIELD_PAYLOAD, + params->isoBaseParams.authIdSelf.val, params->isoBaseParams.authIdSelf.length) != CLIB_SUCCESS) { + LOGE("Add payloadSelf to json failed."); + goto CLEAN_UP; + } + if (AddByteToJson(data, FIELD_TOKEN, params->hmacToken, sizeof(params->hmacToken)) != CLIB_SUCCESS) { + LOGE("Add hmacToken to json failed."); + goto CLEAN_UP; + } + if (AddByteToJson(data, FIELD_SALT, + params->isoBaseParams.randSelf.val, params->isoBaseParams.randSelf.length) != CLIB_SUCCESS) { + LOGE("Add saltSelf to json failed."); + goto CLEAN_UP; + } + if (AddObjToJson(sendToPeer, FIELD_DATA, data) != CLIB_SUCCESS) { + LOGE("Add data json obj to json failed."); + goto CLEAN_UP; + } + + FreeJson(data); + return HC_SUCCESS; +CLEAN_UP: + FreeJson(data); + return HC_ERR_JSON_ADD; +} + +static int32_t PackIsoAuthServerGetTokenMsg(const IsoAuthParams *params, CJson *out) +{ + CJson *sendToPeer = CreateJson(); + if (sendToPeer == NULL) { + LOGE("Create sendToPeer json is null in server."); + return HC_ERR_JSON_CREATE; + } + + if (AddIntToJson(sendToPeer, FIELD_STEP, RET_ISO_AUTH_FOLLOWER_ONE) != CLIB_SUCCESS) { + LOGE("Add step code to json failed in server."); + goto CLEAN_UP; + } + if (AddIntToJson(sendToPeer, FIELD_AUTH_FORM, params->authForm) != CLIB_SUCCESS) { + LOGE("Add authForm to json failed in server."); + goto CLEAN_UP; + } + if (AddStringToJson(sendToPeer, FIELD_USER_ID, params->userIdSelf) != CLIB_SUCCESS) { + LOGE("Add userIdSelf to json failed in server."); + goto CLEAN_UP; + } + if (AddByteToJson(sendToPeer, FIELD_DEV_ID, params->devIdSelf.val, params->devIdSelf.length) != CLIB_SUCCESS) { + LOGE("Add devIdSelf to json failed in server."); + goto CLEAN_UP; + } + if (AddStringToJson(sendToPeer, FIELD_DEVICE_ID, params->deviceIdSelf) != CLIB_SUCCESS) { + LOGE("Add deviceIdSelf to json failed in server."); + goto CLEAN_UP; + } + + int32_t res = AddGetTokenDataToJson(params, sendToPeer); + if (res != HC_SUCCESS) { + LOGE("AddGetTokenDataToJson failed, res: %d.", res); + FreeJson(sendToPeer); + return res; + } + + if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) { + LOGE("Add sendToPeer to json failed."); + goto CLEAN_UP; + } + + FreeJson(sendToPeer); + return HC_SUCCESS; +CLEAN_UP: + FreeJson(sendToPeer); + return HC_ERR_JSON_ADD; +} + +static int32_t IsoAuthServerGetToken(TaskBase *task, const CJson *in, CJson *out, int32_t *status) +{ + IsoAuthServerTask *innerTask = (IsoAuthServerTask *)task; + if (innerTask->taskBase.taskStatus < TASK_STATUS_SERVER_BEGIN_TOKEN) { + LOGE("Message code is not match with task status, taskStatus: %d", innerTask->taskBase.taskStatus); + return HC_ERR_BAD_MESSAGE; + } + if (innerTask->taskBase.taskStatus > TASK_STATUS_SERVER_BEGIN_TOKEN) { + LOGI("The message is repeated, ignore it, taskStatus: %d.", innerTask->taskBase.taskStatus); + *status = IGNORE_MSG; + return HC_SUCCESS; + } + + // Receive params from client. + int32_t res = ParseIsoAuthClientBeginMsg(&innerTask->params, in); + if (res != HC_SUCCESS) { + LOGE("ParseIsoAuthClientBeginMsg failed, res: %d.", res); + return res; + } + + // Get psk and process hmacToken. + res = AccountAuthGeneratePsk(&innerTask->params); + if (res != HC_SUCCESS) { + LOGE("AccountAuthGeneratePsk failed, res: %d.", res); + return res; + } + Uint8Buff selfTokenBuf = { innerTask->params.hmacToken, HMAC_TOKEN_SIZE }; + res = IsoServerGenRandomAndToken(&innerTask->params.isoBaseParams, &selfTokenBuf); + if (res != HC_SUCCESS) { + LOGE("IsoServerGenRandomAndToken failed, res: %d.", res); + return res; + } + + // Send params to client. + res = PackIsoAuthServerGetTokenMsg(&innerTask->params, out); + if (res != HC_SUCCESS) { + LOGE("PackIsoAuthServerGetTokenMsg failed, res: %d.", res); + return res; + } + + innerTask->taskBase.taskStatus = TASK_STATUS_SERVER_GEN_SESSION_KEY; + *status = CONTINUE; + return HC_SUCCESS; +} + +static int32_t PackCalTokenAndSessionKeyMsg(const IsoAuthParams *params, CJson *out, const Uint8Buff *authResultMac) +{ + CJson *sendToPeer = CreateJson(); + if (sendToPeer == NULL) { + LOGE("Create sendToPeer json failed."); + return HC_ERR_JSON_CREATE; + } + CJson *data = CreateJson(); + if (data == NULL) { + LOGE("Create data json failed."); + FreeJson(sendToPeer); + return HC_ERR_JSON_CREATE; + } + + if (AddIntToJson(sendToPeer, FIELD_STEP, RET_ISO_AUTH_FOLLOWER_TWO) != CLIB_SUCCESS) { + LOGE("Add step code to json failed."); + goto CLEAN_UP; + } + if (AddIntToJson(sendToPeer, FIELD_AUTH_FORM, params->authForm) != CLIB_SUCCESS) { + LOGE("Add authForm to json failed."); + goto CLEAN_UP; + } + if (AddByteToJson(data, FIELD_AUTH_RESULT_MAC, authResultMac->val, authResultMac->length) != CLIB_SUCCESS) { + LOGE("Add authResultMac to json failed."); + goto CLEAN_UP; + } + if (AddObjToJson(sendToPeer, FIELD_DATA, data) != CLIB_SUCCESS) { + LOGE("Add data json obj to json failed."); + goto CLEAN_UP; + } + if (AddObjToJson(out, FIELD_SEND_TO_PEER, sendToPeer) != CLIB_SUCCESS) { + LOGE("Add sendToPeer to json failed."); + goto CLEAN_UP; + } + FreeJson(sendToPeer); + FreeJson(data); + return HC_SUCCESS; +CLEAN_UP: + FreeJson(sendToPeer); + FreeJson(data); + return HC_ERR_JSON_ADD; +} + +static int32_t IsoAuthServerCalTokenAndSessionKey(TaskBase *task, const CJson *in, CJson *out, int32_t *status) +{ + IsoAuthServerTask *innerTask = (IsoAuthServerTask *)task; + if (innerTask->taskBase.taskStatus < TASK_STATUS_SERVER_GEN_SESSION_KEY) { + LOGE("Message code is not match with task status, taskStatus: %d", innerTask->taskBase.taskStatus); + return HC_ERR_BAD_MESSAGE; + } + if (innerTask->taskBase.taskStatus > TASK_STATUS_SERVER_GEN_SESSION_KEY) { + LOGI("The message is repeated, ignore it, taskStatus: %d.", innerTask->taskBase.taskStatus); + *status = IGNORE_MSG; + return HC_SUCCESS; + } + + // Receive params from client. + uint8_t peerToken[HMAC_TOKEN_SIZE] = { 0 }; + Uint8Buff peerTokenBuf = { peerToken, HMAC_TOKEN_SIZE }; + if (GetByteFromJson(in, FIELD_TOKEN, peerToken, sizeof(peerToken)) != CLIB_SUCCESS) { + LOGE("Get peerToken from json failed."); + return HC_ERR_JSON_GET; + } + + // Process hmacToken and generate session key. + uint8_t authResultMac[AUTH_RESULT_MAC_SIZE] = { 0 }; + Uint8Buff authResultMacBuf = { authResultMac, AUTH_RESULT_MAC_SIZE }; + int32_t res = IsoServerGenSessionKeyAndCalToken(&(innerTask->params.isoBaseParams), + &peerTokenBuf, &authResultMacBuf); + if (res != HC_SUCCESS) { + LOGE("IsoServerGenSessionKeyAndCalToken failed, res: %d.", res); + return res; + } + + // Return params to client. + res = PackCalTokenAndSessionKeyMsg(&innerTask->params, out, &authResultMacBuf); + if (res != HC_SUCCESS) { + LOGE("PackCalTokenAndSessionKeyMsg failed, res: %d.", res); + return res; + } + + // Return params to server self. + res = AuthIsoSendFinalToOut(&innerTask->params, out); + if (res != HC_SUCCESS) { + LOGE("AuthIsoSendFinalToOut failed, res: %d.", res); + return res; + } + + innerTask->taskBase.taskStatus = TASK_STATUS_SERVER_END; + *status = FINISH; + return HC_SUCCESS; +} + +static int32_t ProcessServerTask(TaskBase *task, const CJson *in, CJson *out, int32_t *status) +{ + int32_t authStep; + if (GetIntFromJson(in, FIELD_STEP, &authStep) != CLIB_SUCCESS) { + LOGE("Get step code from json failed."); + return HC_ERR_JSON_GET; + } + int32_t res; + switch (authStep) { + case CMD_ISO_AUTH_MAIN_ONE: + res = IsoAuthServerGetToken(task, in, out, status); + break; + case CMD_ISO_AUTH_MAIN_TWO: + res = IsoAuthServerCalTokenAndSessionKey(task, in, out, status); + break; + default: + res = HC_ERR_BAD_MESSAGE; + } + if (res != HC_SUCCESS) { + LOGE("Process iso auth server failed, step: %d, res: %d.", authStep, res); + } + return res; +} + +static void DestroyAuthServerAuthTask(TaskBase *task) +{ + if (task == NULL) { + return; + } + IsoAuthServerTask *innerTask = (IsoAuthServerTask *)task; + DestroyIsoAuthParams(&(innerTask->params)); + HcFree(innerTask); +} + +TaskBase *CreateIsoAuthServerTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo) +{ + if ((in == NULL) || (out == NULL) || (verInfo == NULL)) { + LOGE("Params is null for server sym auth."); + return NULL; + } + IsoAuthServerTask *task = (IsoAuthServerTask *)HcMalloc(sizeof(IsoAuthServerTask), 0); + if (task == NULL) { + LOGE("Malloc for IsoAuthServerTask failed."); + return NULL; + } + task->taskBase.getTaskType = GetIsoAuthServerType; + task->taskBase.process = ProcessServerTask; + task->taskBase.destroyTask = DestroyAuthServerAuthTask; + + int32_t res = InitIsoAuthParams(in, &(task->params), verInfo); + if (res != HC_SUCCESS) { + LOGE("InitIsoAuthParams failed, res: %d.", res); + DestroyAuthServerAuthTask((TaskBase *)task); + return NULL; + } + + task->taskBase.taskStatus = TASK_STATUS_SERVER_BEGIN_TOKEN; + return (TaskBase *)task; +} diff --git a/services/authenticators/src/account_related/auth/iso_auth_task/iso_auth_task_common.c b/services/legacy/authenticators/src/account_related/auth/iso_auth_task/iso_auth_task_common.c old mode 100755 new mode 100644 similarity index 97% rename from services/authenticators/src/account_related/auth/iso_auth_task/iso_auth_task_common.c rename to services/legacy/authenticators/src/account_related/auth/iso_auth_task/iso_auth_task_common.c index ec7d3514..87eda842 --- a/services/authenticators/src/account_related/auth/iso_auth_task/iso_auth_task_common.c +++ b/services/legacy/authenticators/src/account_related/auth/iso_auth_task/iso_auth_task_common.c @@ -1,424 +1,424 @@ -/* - * Copyright (C) 2022 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 "iso_auth_task_common.h" -#include "clib_error.h" -#include "common_defs.h" -#include "device_auth.h" -#include "device_auth_defines.h" -#include "hc_log.h" -#include "hc_types.h" -#include "iso_auth_client_task.h" -#include "iso_auth_server_task.h" -#include "protocol_common.h" -#include "sym_token_manager.h" - -#define KEY_INFO_PERSISTENT_TOKEN "persistent_token" -#define AUTH_TOKEN_SIZE_BYTE 32 - -bool IsIsoAuthTaskSupported(void) -{ - return true; -} - -TaskBase *CreateIsoAuthTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo) -{ - bool isClient = false; - if (GetBoolFromJson(in, FIELD_IS_CLIENT, &isClient) != CLIB_SUCCESS) { - LOGD("Get isClient from json failed."); /* default: server. */ - } - return isClient ? CreateIsoAuthClientTask(in, out, verInfo) : - CreateIsoAuthServerTask(in, out, verInfo); -} - -static int32_t FillUserId(const CJson *in, IsoAuthParams *params) -{ - params->userIdSelf = (char *)HcMalloc(DEV_AUTH_USER_ID_SIZE, 0); - if (params->userIdSelf == NULL) { - LOGE("Failed to malloc for userIdSelf."); - return HC_ERR_ALLOC_MEMORY; - } - params->userIdPeer = (char *)HcMalloc(DEV_AUTH_USER_ID_SIZE, 0); - if (params->userIdPeer == NULL) { - LOGE("Failed to malloc for userIdPeer."); - return HC_ERR_ALLOC_MEMORY; - } - const char *userIdSelf = GetStringFromJson(in, FIELD_SELF_USER_ID); - if (userIdSelf == NULL) { - LOGE("Failed to get self userId from input data in sym auth."); - return HC_ERR_JSON_GET; - } - - if (strcpy_s(params->userIdSelf, DEV_AUTH_USER_ID_SIZE, userIdSelf) != EOK) { - LOGE("Copy for userIdSelf failed in sym auth."); - return HC_ERR_MEMORY_COPY; - } - return HC_SUCCESS; -} - -static int32_t FillPayload(const CJson *in, IsoAuthParams *params) -{ - int32_t res = InitSingleParam(¶ms->devIdSelf, DEV_AUTH_DEVICE_ID_SIZE); - if (res != HC_SUCCESS) { - LOGE("InitSingleParam for devIdSelf failed, res: %d.", res); - return res; - } - const char *devIdSelf = GetStringFromJson(in, FIELD_SELF_DEV_ID); - if (devIdSelf == NULL) { - LOGE("Failed to get devIdSelf in sym auth."); - return HC_ERR_JSON_GET; - } - uint32_t devIdLen = HcStrlen(devIdSelf); - if (memcpy_s(params->devIdSelf.val, params->devIdSelf.length, devIdSelf, devIdLen + 1) != EOK) { - LOGE("Copy for self devId failed in sym auth."); - return HC_ERR_MEMORY_COPY; - } - params->devIdSelf.length = devIdLen; - const char *selfDeviceId = GetStringFromJson(in, FIELD_SELF_DEVICE_ID); - if (selfDeviceId == NULL) { - LOGE("Failed to get self deviceId from input data in sym auth."); - return HC_ERR_JSON_GET; - } - uint32_t selfDeviceIdLen = HcStrlen(selfDeviceId); - params->deviceIdSelf = (char *)HcMalloc(selfDeviceIdLen + 1, 0); - if (params->deviceIdSelf == NULL) { - LOGE("Failed to malloc for selfDeviceId."); - return HC_ERR_ALLOC_MEMORY; - } - if (memcpy_s(params->deviceIdSelf, selfDeviceIdLen + 1, selfDeviceId, selfDeviceIdLen) != EOK) { - LOGE("Copy for deviceIdSelf failed in sym auth."); - return HC_ERR_MEMORY_COPY; - } - params->isoBaseParams.authIdSelf.length = params->devIdSelf.length + HcStrlen(params->deviceIdSelf); - res = InitSingleParam(¶ms->isoBaseParams.authIdSelf, params->isoBaseParams.authIdSelf.length); - if (res != HC_SUCCESS) { - LOGE("InitSingleParam for authIdSelf failed, res: %d.", res); - return res; - } - if (memcpy_s(params->isoBaseParams.authIdSelf.val, params->isoBaseParams.authIdSelf.length, - params->devIdSelf.val, params->devIdSelf.length) != EOK) { - LOGE("Failed to memcpy devIdSelf for authId in sym auth."); - return HC_ERR_MEMORY_COPY; - } - if (memcpy_s(params->isoBaseParams.authIdSelf.val + params->devIdSelf.length, - params->isoBaseParams.authIdSelf.length - params->devIdSelf.length, - params->deviceIdSelf, selfDeviceIdLen) != EOK) { - LOGE("Failed to memcpy deviceIdSelf for authId in sym auth."); - return HC_ERR_MEMORY_COPY; - } - return HC_SUCCESS; -} - -static int32_t SetChallenge(IsoAuthParams *params, const CJson *in) -{ - if (((uint32_t)params->credentialType & SYMMETRIC_CRED) == SYMMETRIC_CRED) { - params->challenge.length = HcStrlen(KEY_INFO_PERSISTENT_TOKEN); - params->challenge.val = (uint8_t *)HcMalloc(params->challenge.length, 0); - if (params->challenge.val == NULL) { - LOGE("Failed to malloc for challenge."); - return HC_ERR_ALLOC_MEMORY; - } - if (memcpy_s(params->challenge.val, params->challenge.length, KEY_INFO_PERSISTENT_TOKEN, - HcStrlen(KEY_INFO_PERSISTENT_TOKEN)) != EOK) { - LOGE("Copy for challenge failed in sym auth."); - return HC_ERR_MEMORY_COPY; - } - return HC_SUCCESS; - } - LOGE("Invalid credentialType: %d", params->credentialType); - return HC_ERR_INVALID_PARAMS; -} - -static int32_t GenerateAuthTokenForAccessory(const IsoAuthParams *params, Uint8Buff *outKey) -{ - uint8_t keyAliasVal[SHA256_LEN] = { 0 }; - Uint8Buff keyAlias = { keyAliasVal, SHA256_LEN }; - int32_t res = GetSymTokenManager()->generateKeyAlias(params->userIdSelf, (const char *)(params->devIdSelf.val), - &keyAlias); - if (res != HC_SUCCESS) { - LOGE("Failed to generate key alias for authCode!"); - return res; - } - res = InitSingleParam(outKey, AUTH_TOKEN_SIZE_BYTE); - if (res != HC_SUCCESS) { - LOGE("Malloc for authToken failed, res: %d.", res); - return res; - } - Uint8Buff userIdSelfBuff = { - .val = (uint8_t *)(params->userIdSelf), - .length = HcStrlen(params->userIdSelf) - }; - res = params->isoBaseParams.loader->computeHkdf(&keyAlias, &userIdSelfBuff, ¶ms->challenge, outKey, true); - if (res != HC_SUCCESS) { - LOGE("Failed to computeHkdf from authCode to authToken."); - FreeAndCleanKey(outKey); - } - return res; -} - -static int32_t GenerateTokenAliasForController(const IsoAuthParams *params, Uint8Buff *authTokenAlias) -{ - int32_t res = InitSingleParam(authTokenAlias, SHA256_LEN); - if (res != HC_SUCCESS) { - LOGE("Malloc for authToken alias failed, res: %d.", res); - return res; - } - res = GetSymTokenManager()->generateKeyAlias(params->userIdPeer, (const char *)(params->devIdPeer.val), - authTokenAlias); - if (res != HC_SUCCESS) { - LOGE("Failed to generate key alias for authToken."); - HcFree(authTokenAlias->val); - authTokenAlias->val = NULL; - } - return res; -} - -int32_t AccountAuthGeneratePsk(IsoAuthParams *params) -{ - bool isTokenStored = true; - Uint8Buff authToken = { NULL, 0 }; - int32_t res; - if (params->localDevType == DEVICE_TYPE_ACCESSORY) { - LOGI("Account sym auth for accessory."); - isTokenStored = false; - res = GenerateAuthTokenForAccessory(params, &authToken); - } else { - LOGI("Account sym auth for controller."); - res = GenerateTokenAliasForController(params, &authToken); - } - if (res != HC_SUCCESS) { - LOGE("Failed to generate token-related info, res = %d.", res); - return res; - } - Uint8Buff pskBuf = { params->isoBaseParams.psk, PSK_SIZE }; - Uint8Buff seedBuf = { params->seed, sizeof(params->seed) }; - res = params->isoBaseParams.loader->computeHmac(&authToken, &seedBuf, &pskBuf, isTokenStored); - FreeAndCleanKey(&authToken); - if (res != HC_SUCCESS) { - LOGE("ComputeHmac for psk failed, res: %d.", res); - } - return res; -} - -int32_t InitIsoAuthParams(const CJson *in, IsoAuthParams *params, const AccountVersionInfo *verInfo) -{ - params->versionNo = verInfo->versionNo; - int32_t res = HC_ERR_JSON_GET; - if (GetIntFromJson(in, FIELD_AUTH_FORM, ¶ms->authForm) != CLIB_SUCCESS) { - LOGE("Failed to get authForm from json in sym auth."); - goto CLEAN_UP; - } - if (GetIntFromJson(in, FIELD_CREDENTIAL_TYPE, ¶ms->credentialType) != CLIB_SUCCESS) { - LOGE("Failed to get credentialType from json in sym auth."); - goto CLEAN_UP; - } - if (GetIntFromJson(in, FIELD_LOCAL_DEVICE_TYPE, ¶ms->localDevType) != CLIB_SUCCESS) { - LOGE("Failed to get localDevType from json in sym auth."); - goto CLEAN_UP; - } - res = InitIsoBaseParams(¶ms->isoBaseParams); - if (res != HC_SUCCESS) { - LOGE("InitIsoBaseParams failed, res: %x.", res); - goto CLEAN_UP; - } - res = FillUserId(in, params); - if (res != HC_SUCCESS) { - LOGE("Failed to fill userId info, res = %d.", res); - goto CLEAN_UP; - } - res = FillPayload(in, params); - if (res != HC_SUCCESS) { - LOGE("Failed to fill payload info, res = %d.", res); - goto CLEAN_UP; - } - if (params->localDevType == DEVICE_TYPE_ACCESSORY) { - res = SetChallenge(params, in); - if (res != HC_SUCCESS) { - LOGE("SetChallenge failed, res = %d.", res); - goto CLEAN_UP; - } - } - return HC_SUCCESS; -CLEAN_UP: - DestroyIsoAuthParams(params); - return res; -} - -void DestroyIsoAuthParams(IsoAuthParams *params) -{ - LOGI("Destroy iso auth params begin."); - if (params == NULL) { - return; - } - DestroyIsoBaseParams(¶ms->isoBaseParams); - - HcFree(params->challenge.val); - params->challenge.val = NULL; - - HcFree(params->userIdSelf); - params->userIdSelf = NULL; - - HcFree(params->userIdPeer); - params->userIdPeer = NULL; - - HcFree(params->devIdSelf.val); - params->devIdSelf.val = NULL; - - HcFree(params->devIdPeer.val); - params->devIdPeer.val = NULL; - - HcFree(params->deviceIdSelf); - params->deviceIdSelf = NULL; - - HcFree(params->deviceIdPeer); - params->deviceIdPeer = NULL; -} - -static int32_t GetPayloadValue(IsoAuthParams *params, const CJson *in) -{ - const char *devIdPeerHex = GetStringFromJson(in, FIELD_DEV_ID); - if (devIdPeerHex == NULL) { - LOGE("Get peer devId hex failed."); - return HC_ERR_JSON_GET; - } - uint32_t devIdPeerHexLen = HcStrlen(devIdPeerHex); - // DevId is string, the id from phone is byte. For both cases, apply one more bit for '\0'. - params->devIdPeer.val = (uint8_t *)HcMalloc(devIdPeerHexLen / BYTE_TO_HEX_OPER_LENGTH + 1, 0); - if (params->devIdPeer.val == NULL) { - LOGE("Failed to malloc for peer devId."); - return HC_ERR_ALLOC_MEMORY; - } - params->devIdPeer.length = devIdPeerHexLen / BYTE_TO_HEX_OPER_LENGTH; - if (HexStringToByte(devIdPeerHex, params->devIdPeer.val, params->devIdPeer.length) != CLIB_SUCCESS) { - LOGE("Failed to convert peer devId."); - return HC_ERR_CONVERT_FAILED; - } - const char *deviceIdPeer = GetStringFromJson(in, FIELD_DEVICE_ID); - if (deviceIdPeer == NULL) { - LOGE("Get peer deviceId failed."); - return HC_ERR_JSON_GET; - } - uint32_t deviceIdPeerLen = HcStrlen(deviceIdPeer); - params->deviceIdPeer = (char *)HcMalloc(deviceIdPeerLen + 1, 0); - if (params->deviceIdPeer == NULL) { - LOGE("Failed to malloc for peer deviceId."); - return HC_ERR_ALLOC_MEMORY; - } - if (memcpy_s(params->deviceIdPeer, deviceIdPeerLen + 1, deviceIdPeer, deviceIdPeerLen) != EOK) { - LOGE("Failed to copy peer deviceId."); - return HC_ERR_MEMORY_COPY; - } - return HC_SUCCESS; -} - -static int32_t ExtractPeerAuthId(IsoAuthParams *params, const CJson *in) -{ - const char *payloadHex = GetStringFromJson(in, FIELD_PAYLOAD); - if (payloadHex == NULL) { - LOGE("Get payloadHex peer from json failed."); - return HC_ERR_JSON_GET; - } - int32_t res = InitSingleParam(&(params->isoBaseParams.authIdPeer), HcStrlen(payloadHex) / BYTE_TO_HEX_OPER_LENGTH); - if (res != HC_SUCCESS) { - LOGE("InitSingleParam for payload peer failed, res: %d.", res); - return res; - } - if (HexStringToByte(payloadHex, params->isoBaseParams.authIdPeer.val, - params->isoBaseParams.authIdPeer.length) != CLIB_SUCCESS) { - LOGE("Convert payloadPeer from hex string to byte failed."); - return HC_ERR_CONVERT_FAILED; - } - return HC_SUCCESS; -} - -int32_t ExtractAndVerifyPayload(IsoAuthParams *params, const CJson *in) -{ - int32_t res = ExtractPeerAuthId(params, in); - if (res != HC_SUCCESS) { - LOGE("ExtractPeerAuthId failed, res: %d.", res); - return res; - } - res = GetPayloadValue(params, in); - if (res != HC_SUCCESS) { - LOGE("GetPayloadValue failed, res: %d.", res); - return res; - } - uint32_t deviceIdPeerLen = HcStrlen(params->deviceIdPeer); - uint32_t len = params->devIdPeer.length + deviceIdPeerLen; - char *combineString = (char *)HcMalloc(len, 0); - if (combineString == NULL) { - LOGE("Failed to malloc for combineString."); - return HC_ERR_ALLOC_MEMORY; - } - if (memcpy_s(combineString, len, params->devIdPeer.val, params->devIdPeer.length) != EOK) { - LOGE("Failed to copy peer devId."); - HcFree(combineString); - return HC_ERR_MEMORY_COPY; - } - if (memcpy_s(combineString + params->devIdPeer.length, len - params->devIdPeer.length, params->deviceIdPeer, - deviceIdPeerLen) != EOK) { - LOGE("Failed to copy peer deviceId."); - HcFree(combineString); - return HC_ERR_MEMORY_COPY; - } - if (memcmp(combineString, params->isoBaseParams.authIdPeer.val, len) != 0) { - LOGE("Payload is not equal."); - HcFree(combineString); - return HC_ERR_MEMORY_COMPARE; - } - HcFree(combineString); - return HC_SUCCESS; -} - -int32_t AuthIsoSendFinalToOut(IsoAuthParams *params, CJson *out) -{ - CJson *sendToSelf = CreateJson(); - if (sendToSelf == NULL) { - LOGE("Create sendToSelf json failed."); - return HC_ERR_JSON_CREATE; - } - if (AddByteToJson(sendToSelf, FIELD_SESSION_KEY, - params->isoBaseParams.sessionKey.val, params->isoBaseParams.sessionKey.length) != CLIB_SUCCESS) { - LOGE("Add sessionKey to json failed."); - goto CLEAN_UP; - } - if (AddStringToJson(sendToSelf, FIELD_USER_ID, params->userIdPeer) != CLIB_SUCCESS) { - LOGE("Add userIdPeer to json failed."); - goto CLEAN_UP; - } - if (AddStringToJson(sendToSelf, FIELD_DEVICE_ID, params->deviceIdPeer) != CLIB_SUCCESS) { - LOGE("Add deviceIdPeer to json failed."); - goto CLEAN_UP; - } - if (AddIntToJson(sendToSelf, FIELD_CREDENTIAL_TYPE, params->credentialType) != CLIB_SUCCESS) { - LOGE("Add credentialType to json failed."); - goto CLEAN_UP; - } - if (AddStringToJson(sendToSelf, FIELD_DEV_ID, (char *)params->devIdPeer.val) != CLIB_SUCCESS) { - LOGE("Add devIdPeer to json failed."); - goto CLEAN_UP; - } - if (AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf) != CLIB_SUCCESS) { - LOGE("Add sendToSelf to json failed."); - goto CLEAN_UP; - } - FreeJson(sendToSelf); - FreeAndCleanKey(&(params->isoBaseParams.sessionKey)); - return HC_SUCCESS; -CLEAN_UP: - FreeJson(sendToSelf); - FreeAndCleanKey(&(params->isoBaseParams.sessionKey)); - return HC_ERR_JSON_ADD; -} +/* + * Copyright (C) 2022 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 "iso_auth_task_common.h" +#include "clib_error.h" +#include "common_defs.h" +#include "device_auth.h" +#include "device_auth_defines.h" +#include "hc_log.h" +#include "hc_types.h" +#include "iso_auth_client_task.h" +#include "iso_auth_server_task.h" +#include "protocol_common.h" +#include "sym_token_manager.h" + +#define KEY_INFO_PERSISTENT_TOKEN "persistent_token" +#define AUTH_TOKEN_SIZE_BYTE 32 + +bool IsIsoAuthTaskSupported(void) +{ + return true; +} + +TaskBase *CreateIsoAuthTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo) +{ + bool isClient = false; + if (GetBoolFromJson(in, FIELD_IS_CLIENT, &isClient) != CLIB_SUCCESS) { + LOGD("Get isClient from json failed."); /* default: server. */ + } + return isClient ? CreateIsoAuthClientTask(in, out, verInfo) : + CreateIsoAuthServerTask(in, out, verInfo); +} + +static int32_t FillUserId(const CJson *in, IsoAuthParams *params) +{ + params->userIdSelf = (char *)HcMalloc(DEV_AUTH_USER_ID_SIZE, 0); + if (params->userIdSelf == NULL) { + LOGE("Failed to malloc for userIdSelf."); + return HC_ERR_ALLOC_MEMORY; + } + params->userIdPeer = (char *)HcMalloc(DEV_AUTH_USER_ID_SIZE, 0); + if (params->userIdPeer == NULL) { + LOGE("Failed to malloc for userIdPeer."); + return HC_ERR_ALLOC_MEMORY; + } + const char *userIdSelf = GetStringFromJson(in, FIELD_SELF_USER_ID); + if (userIdSelf == NULL) { + LOGE("Failed to get self userId from input data in sym auth."); + return HC_ERR_JSON_GET; + } + + if (strcpy_s(params->userIdSelf, DEV_AUTH_USER_ID_SIZE, userIdSelf) != EOK) { + LOGE("Copy for userIdSelf failed in sym auth."); + return HC_ERR_MEMORY_COPY; + } + return HC_SUCCESS; +} + +static int32_t FillPayload(const CJson *in, IsoAuthParams *params) +{ + int32_t res = InitSingleParam(¶ms->devIdSelf, DEV_AUTH_DEVICE_ID_SIZE); + if (res != HC_SUCCESS) { + LOGE("InitSingleParam for devIdSelf failed, res: %d.", res); + return res; + } + const char *devIdSelf = GetStringFromJson(in, FIELD_SELF_DEV_ID); + if (devIdSelf == NULL) { + LOGE("Failed to get devIdSelf in sym auth."); + return HC_ERR_JSON_GET; + } + uint32_t devIdLen = HcStrlen(devIdSelf); + if (memcpy_s(params->devIdSelf.val, params->devIdSelf.length, devIdSelf, devIdLen + 1) != EOK) { + LOGE("Copy for self devId failed in sym auth."); + return HC_ERR_MEMORY_COPY; + } + params->devIdSelf.length = devIdLen; + const char *selfDeviceId = GetStringFromJson(in, FIELD_SELF_DEVICE_ID); + if (selfDeviceId == NULL) { + LOGE("Failed to get self deviceId from input data in sym auth."); + return HC_ERR_JSON_GET; + } + uint32_t selfDeviceIdLen = HcStrlen(selfDeviceId); + params->deviceIdSelf = (char *)HcMalloc(selfDeviceIdLen + 1, 0); + if (params->deviceIdSelf == NULL) { + LOGE("Failed to malloc for selfDeviceId."); + return HC_ERR_ALLOC_MEMORY; + } + if (memcpy_s(params->deviceIdSelf, selfDeviceIdLen + 1, selfDeviceId, selfDeviceIdLen) != EOK) { + LOGE("Copy for deviceIdSelf failed in sym auth."); + return HC_ERR_MEMORY_COPY; + } + params->isoBaseParams.authIdSelf.length = params->devIdSelf.length + HcStrlen(params->deviceIdSelf); + res = InitSingleParam(¶ms->isoBaseParams.authIdSelf, params->isoBaseParams.authIdSelf.length); + if (res != HC_SUCCESS) { + LOGE("InitSingleParam for authIdSelf failed, res: %d.", res); + return res; + } + if (memcpy_s(params->isoBaseParams.authIdSelf.val, params->isoBaseParams.authIdSelf.length, + params->devIdSelf.val, params->devIdSelf.length) != EOK) { + LOGE("Failed to memcpy devIdSelf for authId in sym auth."); + return HC_ERR_MEMORY_COPY; + } + if (memcpy_s(params->isoBaseParams.authIdSelf.val + params->devIdSelf.length, + params->isoBaseParams.authIdSelf.length - params->devIdSelf.length, + params->deviceIdSelf, selfDeviceIdLen) != EOK) { + LOGE("Failed to memcpy deviceIdSelf for authId in sym auth."); + return HC_ERR_MEMORY_COPY; + } + return HC_SUCCESS; +} + +static int32_t SetChallenge(IsoAuthParams *params, const CJson *in) +{ + if (((uint32_t)params->credentialType & SYMMETRIC_CRED) == SYMMETRIC_CRED) { + params->challenge.length = HcStrlen(KEY_INFO_PERSISTENT_TOKEN); + params->challenge.val = (uint8_t *)HcMalloc(params->challenge.length, 0); + if (params->challenge.val == NULL) { + LOGE("Failed to malloc for challenge."); + return HC_ERR_ALLOC_MEMORY; + } + if (memcpy_s(params->challenge.val, params->challenge.length, KEY_INFO_PERSISTENT_TOKEN, + HcStrlen(KEY_INFO_PERSISTENT_TOKEN)) != EOK) { + LOGE("Copy for challenge failed in sym auth."); + return HC_ERR_MEMORY_COPY; + } + return HC_SUCCESS; + } + LOGE("Invalid credentialType: %d", params->credentialType); + return HC_ERR_INVALID_PARAMS; +} + +static int32_t GenerateAuthTokenForAccessory(const IsoAuthParams *params, Uint8Buff *outKey) +{ + uint8_t keyAliasVal[SHA256_LEN] = { 0 }; + Uint8Buff keyAlias = { keyAliasVal, SHA256_LEN }; + int32_t res = GetSymTokenManager()->generateKeyAlias(params->userIdSelf, (const char *)(params->devIdSelf.val), + &keyAlias); + if (res != HC_SUCCESS) { + LOGE("Failed to generate key alias for authCode!"); + return res; + } + res = InitSingleParam(outKey, AUTH_TOKEN_SIZE_BYTE); + if (res != HC_SUCCESS) { + LOGE("Malloc for authToken failed, res: %d.", res); + return res; + } + Uint8Buff userIdSelfBuff = { + .val = (uint8_t *)(params->userIdSelf), + .length = HcStrlen(params->userIdSelf) + }; + res = params->isoBaseParams.loader->computeHkdf(&keyAlias, &userIdSelfBuff, ¶ms->challenge, outKey, true); + if (res != HC_SUCCESS) { + LOGE("Failed to computeHkdf from authCode to authToken."); + FreeAndCleanKey(outKey); + } + return res; +} + +static int32_t GenerateTokenAliasForController(const IsoAuthParams *params, Uint8Buff *authTokenAlias) +{ + int32_t res = InitSingleParam(authTokenAlias, SHA256_LEN); + if (res != HC_SUCCESS) { + LOGE("Malloc for authToken alias failed, res: %d.", res); + return res; + } + res = GetSymTokenManager()->generateKeyAlias(params->userIdPeer, (const char *)(params->devIdPeer.val), + authTokenAlias); + if (res != HC_SUCCESS) { + LOGE("Failed to generate key alias for authToken."); + HcFree(authTokenAlias->val); + authTokenAlias->val = NULL; + } + return res; +} + +int32_t AccountAuthGeneratePsk(IsoAuthParams *params) +{ + bool isTokenStored = true; + Uint8Buff authToken = { NULL, 0 }; + int32_t res; + if (params->localDevType == DEVICE_TYPE_ACCESSORY) { + LOGI("Account sym auth for accessory."); + isTokenStored = false; + res = GenerateAuthTokenForAccessory(params, &authToken); + } else { + LOGI("Account sym auth for controller."); + res = GenerateTokenAliasForController(params, &authToken); + } + if (res != HC_SUCCESS) { + LOGE("Failed to generate token-related info, res = %d.", res); + return res; + } + Uint8Buff pskBuf = { params->isoBaseParams.psk, PSK_SIZE }; + Uint8Buff seedBuf = { params->seed, sizeof(params->seed) }; + res = params->isoBaseParams.loader->computeHmac(&authToken, &seedBuf, &pskBuf, isTokenStored); + FreeAndCleanKey(&authToken); + if (res != HC_SUCCESS) { + LOGE("ComputeHmac for psk failed, res: %d.", res); + } + return res; +} + +int32_t InitIsoAuthParams(const CJson *in, IsoAuthParams *params, const AccountVersionInfo *verInfo) +{ + params->versionNo = verInfo->versionNo; + int32_t res = HC_ERR_JSON_GET; + if (GetIntFromJson(in, FIELD_AUTH_FORM, ¶ms->authForm) != CLIB_SUCCESS) { + LOGE("Failed to get authForm from json in sym auth."); + goto CLEAN_UP; + } + if (GetIntFromJson(in, FIELD_CREDENTIAL_TYPE, ¶ms->credentialType) != CLIB_SUCCESS) { + LOGE("Failed to get credentialType from json in sym auth."); + goto CLEAN_UP; + } + if (GetIntFromJson(in, FIELD_LOCAL_DEVICE_TYPE, ¶ms->localDevType) != CLIB_SUCCESS) { + LOGE("Failed to get localDevType from json in sym auth."); + goto CLEAN_UP; + } + res = InitIsoBaseParams(¶ms->isoBaseParams); + if (res != HC_SUCCESS) { + LOGE("InitIsoBaseParams failed, res: %x.", res); + goto CLEAN_UP; + } + res = FillUserId(in, params); + if (res != HC_SUCCESS) { + LOGE("Failed to fill userId info, res = %d.", res); + goto CLEAN_UP; + } + res = FillPayload(in, params); + if (res != HC_SUCCESS) { + LOGE("Failed to fill payload info, res = %d.", res); + goto CLEAN_UP; + } + if (params->localDevType == DEVICE_TYPE_ACCESSORY) { + res = SetChallenge(params, in); + if (res != HC_SUCCESS) { + LOGE("SetChallenge failed, res = %d.", res); + goto CLEAN_UP; + } + } + return HC_SUCCESS; +CLEAN_UP: + DestroyIsoAuthParams(params); + return res; +} + +void DestroyIsoAuthParams(IsoAuthParams *params) +{ + LOGI("Destroy iso auth params begin."); + if (params == NULL) { + return; + } + DestroyIsoBaseParams(¶ms->isoBaseParams); + + HcFree(params->challenge.val); + params->challenge.val = NULL; + + HcFree(params->userIdSelf); + params->userIdSelf = NULL; + + HcFree(params->userIdPeer); + params->userIdPeer = NULL; + + HcFree(params->devIdSelf.val); + params->devIdSelf.val = NULL; + + HcFree(params->devIdPeer.val); + params->devIdPeer.val = NULL; + + HcFree(params->deviceIdSelf); + params->deviceIdSelf = NULL; + + HcFree(params->deviceIdPeer); + params->deviceIdPeer = NULL; +} + +static int32_t GetPayloadValue(IsoAuthParams *params, const CJson *in) +{ + const char *devIdPeerHex = GetStringFromJson(in, FIELD_DEV_ID); + if (devIdPeerHex == NULL) { + LOGE("Get peer devId hex failed."); + return HC_ERR_JSON_GET; + } + uint32_t devIdPeerHexLen = HcStrlen(devIdPeerHex); + // DevId is string, the id from phone is byte. For both cases, apply one more bit for '\0'. + params->devIdPeer.val = (uint8_t *)HcMalloc(devIdPeerHexLen / BYTE_TO_HEX_OPER_LENGTH + 1, 0); + if (params->devIdPeer.val == NULL) { + LOGE("Failed to malloc for peer devId."); + return HC_ERR_ALLOC_MEMORY; + } + params->devIdPeer.length = devIdPeerHexLen / BYTE_TO_HEX_OPER_LENGTH; + if (HexStringToByte(devIdPeerHex, params->devIdPeer.val, params->devIdPeer.length) != CLIB_SUCCESS) { + LOGE("Failed to convert peer devId."); + return HC_ERR_CONVERT_FAILED; + } + const char *deviceIdPeer = GetStringFromJson(in, FIELD_DEVICE_ID); + if (deviceIdPeer == NULL) { + LOGE("Get peer deviceId failed."); + return HC_ERR_JSON_GET; + } + uint32_t deviceIdPeerLen = HcStrlen(deviceIdPeer); + params->deviceIdPeer = (char *)HcMalloc(deviceIdPeerLen + 1, 0); + if (params->deviceIdPeer == NULL) { + LOGE("Failed to malloc for peer deviceId."); + return HC_ERR_ALLOC_MEMORY; + } + if (memcpy_s(params->deviceIdPeer, deviceIdPeerLen + 1, deviceIdPeer, deviceIdPeerLen) != EOK) { + LOGE("Failed to copy peer deviceId."); + return HC_ERR_MEMORY_COPY; + } + return HC_SUCCESS; +} + +static int32_t ExtractPeerAuthId(IsoAuthParams *params, const CJson *in) +{ + const char *payloadHex = GetStringFromJson(in, FIELD_PAYLOAD); + if (payloadHex == NULL) { + LOGE("Get payloadHex peer from json failed."); + return HC_ERR_JSON_GET; + } + int32_t res = InitSingleParam(&(params->isoBaseParams.authIdPeer), HcStrlen(payloadHex) / BYTE_TO_HEX_OPER_LENGTH); + if (res != HC_SUCCESS) { + LOGE("InitSingleParam for payload peer failed, res: %d.", res); + return res; + } + if (HexStringToByte(payloadHex, params->isoBaseParams.authIdPeer.val, + params->isoBaseParams.authIdPeer.length) != CLIB_SUCCESS) { + LOGE("Convert payloadPeer from hex string to byte failed."); + return HC_ERR_CONVERT_FAILED; + } + return HC_SUCCESS; +} + +int32_t ExtractAndVerifyPayload(IsoAuthParams *params, const CJson *in) +{ + int32_t res = ExtractPeerAuthId(params, in); + if (res != HC_SUCCESS) { + LOGE("ExtractPeerAuthId failed, res: %d.", res); + return res; + } + res = GetPayloadValue(params, in); + if (res != HC_SUCCESS) { + LOGE("GetPayloadValue failed, res: %d.", res); + return res; + } + uint32_t deviceIdPeerLen = HcStrlen(params->deviceIdPeer); + uint32_t len = params->devIdPeer.length + deviceIdPeerLen; + char *combineString = (char *)HcMalloc(len, 0); + if (combineString == NULL) { + LOGE("Failed to malloc for combineString."); + return HC_ERR_ALLOC_MEMORY; + } + if (memcpy_s(combineString, len, params->devIdPeer.val, params->devIdPeer.length) != EOK) { + LOGE("Failed to copy peer devId."); + HcFree(combineString); + return HC_ERR_MEMORY_COPY; + } + if (memcpy_s(combineString + params->devIdPeer.length, len - params->devIdPeer.length, params->deviceIdPeer, + deviceIdPeerLen) != EOK) { + LOGE("Failed to copy peer deviceId."); + HcFree(combineString); + return HC_ERR_MEMORY_COPY; + } + if (memcmp(combineString, params->isoBaseParams.authIdPeer.val, len) != 0) { + LOGE("Payload is not equal."); + HcFree(combineString); + return HC_ERR_MEMORY_COMPARE; + } + HcFree(combineString); + return HC_SUCCESS; +} + +int32_t AuthIsoSendFinalToOut(IsoAuthParams *params, CJson *out) +{ + CJson *sendToSelf = CreateJson(); + if (sendToSelf == NULL) { + LOGE("Create sendToSelf json failed."); + return HC_ERR_JSON_CREATE; + } + if (AddByteToJson(sendToSelf, FIELD_SESSION_KEY, + params->isoBaseParams.sessionKey.val, params->isoBaseParams.sessionKey.length) != CLIB_SUCCESS) { + LOGE("Add sessionKey to json failed."); + goto CLEAN_UP; + } + if (AddStringToJson(sendToSelf, FIELD_USER_ID, params->userIdPeer) != CLIB_SUCCESS) { + LOGE("Add userIdPeer to json failed."); + goto CLEAN_UP; + } + if (AddStringToJson(sendToSelf, FIELD_DEVICE_ID, params->deviceIdPeer) != CLIB_SUCCESS) { + LOGE("Add deviceIdPeer to json failed."); + goto CLEAN_UP; + } + if (AddIntToJson(sendToSelf, FIELD_CREDENTIAL_TYPE, params->credentialType) != CLIB_SUCCESS) { + LOGE("Add credentialType to json failed."); + goto CLEAN_UP; + } + if (AddStringToJson(sendToSelf, FIELD_DEV_ID, (char *)params->devIdPeer.val) != CLIB_SUCCESS) { + LOGE("Add devIdPeer to json failed."); + goto CLEAN_UP; + } + if (AddObjToJson(out, FIELD_SEND_TO_SELF, sendToSelf) != CLIB_SUCCESS) { + LOGE("Add sendToSelf to json failed."); + goto CLEAN_UP; + } + FreeJson(sendToSelf); + FreeAndCleanKey(&(params->isoBaseParams.sessionKey)); + return HC_SUCCESS; +CLEAN_UP: + FreeJson(sendToSelf); + FreeAndCleanKey(&(params->isoBaseParams.sessionKey)); + return HC_ERR_JSON_ADD; +} diff --git a/services/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_client_task.c b/services/legacy/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_client_task.c similarity index 100% rename from services/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_client_task.c rename to services/legacy/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_client_task.c diff --git a/services/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_server_task.c b/services/legacy/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_server_task.c similarity index 100% rename from services/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_server_task.c rename to services/legacy/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_server_task.c diff --git a/services/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_task_common.c b/services/legacy/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_task_common.c similarity index 97% rename from services/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_task_common.c rename to services/legacy/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_task_common.c index af50c57e..9c9767f9 100644 --- a/services/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_task_common.c +++ b/services/legacy/authenticators/src/account_related/auth/pake_v2_auth_task/pake_v2_auth_task_common.c @@ -1,455 +1,455 @@ -/* - * Copyright (C) 2022 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 "pake_v2_auth_task_common.h" - -#include -#include "account_module.h" -#include "asy_token_manager.h" -#include "common_defs.h" -#include "device_auth_defines.h" -#include "hc_dev_info.h" -#include "hc_log.h" -#include "hc_types.h" -#include "pake_v2_protocol_common.h" -#include "pake_v2_auth_client_task.h" -#include "pake_v2_auth_server_task.h" -#include "protocol_common.h" -#include "string_util.h" - -#define P256_SHARED_SECRET_KEY_SIZE 32 -#define P256_PUBLIC_SIZE 64 -#define P256_KEY_SIZE 32 - -#define SHARED_KEY_ALIAS "sharedKeyAlias" - -bool IsPakeV2AuthTaskSupported(void) -{ - return true; -} - -TaskBase *CreatePakeV2AuthTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo) -{ - bool isClient = false; - if (GetBoolFromJson(in, FIELD_IS_CLIENT, &isClient) != HC_SUCCESS) { - LOGD("Get isClient from json failed."); - isClient = false; - } - if (isClient) { - return CreatePakeV2AuthClientTask(in, out, verInfo); - } - return CreatePakeV2AuthServerTask(in, out, verInfo); -} - -int32_t VerifyPkSignPeer(const PakeAuthParams *params) -{ - uint8_t *serverPkAlias = (uint8_t *)HcMalloc(SHA256_LEN, 0); - if (serverPkAlias == NULL) { - LOGE("Failed to malloc for serverPk key alias."); - return HC_ERR_ALLOC_MEMORY; - } - Uint8Buff serverPkAliasBuff = { - .val = serverPkAlias, - .length = SHA256_LEN - }; - - int32_t res = GetAccountAuthTokenManager()->generateKeyAlias((const char *)(params->userIdSelf), - (const char *)params->devIdSelf.val, &serverPkAliasBuff, true); - if (res != HC_SUCCESS) { - HcFree(serverPkAlias); - return res; - } - - Uint8Buff messageBuff = { - .val = params->pkInfoPeer.val, - .length = params->pkInfoPeer.length - }; - Uint8Buff peerSignBuff = { - .val = params->pkInfoSignPeer.val, - .length = params->pkInfoSignPeer.length - }; - res = params->pakeParams.loader->verify(&serverPkAliasBuff, &messageBuff, P256, &peerSignBuff, true); - HcFree(serverPkAlias); - if (res != HC_SUCCESS) { - LOGE("Verify pk sign failed."); - return HC_ERR_VERIFY_FAILED; - } - return HC_SUCCESS; -} - -int32_t GenerateEcdhSharedKey(PakeAuthParams *params) -{ - uint8_t *priAliasVal = (uint8_t *)HcMalloc(SHA256_LEN, 0); - if (priAliasVal == NULL) { - LOGE("Failed to malloc for self key alias."); - return HC_ERR_ALLOC_MEMORY; - } - Uint8Buff aliasBuff = { - .val = priAliasVal, - .length = SHA256_LEN - }; - int32_t res = GetAccountAuthTokenManager()->generateKeyAlias((const char *)(params->userIdSelf), - (const char *)params->devIdSelf.val, &aliasBuff, false); - if (res != HC_SUCCESS) { - HcFree(priAliasVal); - return res; - } - KeyBuff priAliasKeyBuff = { - .key = aliasBuff.val, - .keyLen = aliasBuff.length, - .isAlias = true - }; - KeyBuff publicKeyBuff = { - .key = params->pkPeer, - .keyLen = sizeof(params->pkPeer), - .isAlias = false - }; - uint32_t sharedKeyAliasLen = HcStrlen(SHARED_KEY_ALIAS) + 1; - params->pakeParams.psk.val = (uint8_t *)HcMalloc(sharedKeyAliasLen, 0); - if (params->pakeParams.psk.val == NULL) { - LOGE("Failed to malloc for psk alias."); - HcFree(priAliasVal); - return HC_ERR_ALLOC_MEMORY; - } - params->pakeParams.psk.length = sharedKeyAliasLen; - (void)memcpy_s(params->pakeParams.psk.val, sharedKeyAliasLen, SHARED_KEY_ALIAS, sharedKeyAliasLen); - res = params->pakeParams.loader->agreeSharedSecretWithStorage(&priAliasKeyBuff, &publicKeyBuff, - P256, P256_SHARED_SECRET_KEY_SIZE, &(params->pakeParams.psk)); - HcFree(priAliasVal); - return res; -} - -static int32_t InitCharStringBuff(Uint8Buff *param, uint32_t len) -{ - if (param == NULL || len <= 0) { - LOGE("param is invalid for init."); - return HC_ERR_NULL_PTR; - } - if (InitSingleParam(param, len + 1) != HC_SUCCESS) { - return HC_ERR_ALLOC_MEMORY; - } - param->length = len; - return HC_SUCCESS; -} - -int32_t ExtractPakePeerId(PakeAuthParams *params, const CJson *in) -{ - if (params == NULL || in == NULL) { - LOGE("Input params is invalid."); - return HC_ERR_INVALID_PARAMS; - } - uint32_t deviceIdPeerLen = HcStrlen((const char *)params->deviceIdPeer.val); - if (InitCharStringBuff(¶ms->pakeParams.idPeer, - params->devIdPeer.length + deviceIdPeerLen) != HC_SUCCESS) { - LOGE("InitCharStringBuff: idPeer failed."); - return HC_ERR_AUTH_INTERNAL; - } - (void)memcpy_s(params->pakeParams.idPeer.val, params->pakeParams.idPeer.length, params->devIdPeer.val, - params->devIdPeer.length); - (void)memcpy_s(params->pakeParams.idPeer.val + params->devIdPeer.length, - params->pakeParams.idPeer.length - params->devIdPeer.length, params->deviceIdPeer.val, deviceIdPeerLen); - return HC_SUCCESS; -} - -int32_t ExtractPakeSelfId(PakeAuthParams *params) -{ - if (params == NULL) { - LOGE("Input params NULL."); - return HC_ERR_INVALID_PARAMS; - } - uint32_t deviceIdSelfLen = HcStrlen((const char *)params->deviceIdSelf.val); - if (InitCharStringBuff(¶ms->pakeParams.idSelf, - params->devIdSelf.length + deviceIdSelfLen) != HC_SUCCESS) { - LOGE("InitCharStringBuff: idSelf failed."); - return HC_ERR_AUTH_INTERNAL; - } - - (void)memcpy_s(params->pakeParams.idSelf.val, params->pakeParams.idSelf.length, params->devIdSelf.val, - params->devIdSelf.length); - (void)memcpy_s(params->pakeParams.idSelf.val + params->devIdSelf.length, - params->pakeParams.idSelf.length - params->devIdSelf.length, params->deviceIdSelf.val, deviceIdSelfLen); - return HC_SUCCESS; -} - -static int32_t ExtractSelfDeviceId(PakeAuthParams *params, const CJson *in, bool useSelfPrefix) -{ - if (params == NULL || in == NULL) { - LOGE("Input params NULL."); - return HC_ERR_INVALID_PARAMS; - } - const char *deviceId = NULL; - if (useSelfPrefix) { - deviceId = GetStringFromJson(in, FIELD_SELF_DEVICE_ID); - } else { - deviceId = GetStringFromJson(in, FIELD_DEVICE_ID); - } - if (deviceId == NULL) { - LOGE("Get selfDeviceId from json failed."); - return HC_ERR_JSON_GET; - } - params->deviceIdSelf.length = HcStrlen(deviceId); - params->deviceIdSelf.val = (uint8_t *)HcMalloc(params->deviceIdSelf.length + 1, 0); - if (params->deviceIdSelf.val == NULL) { - LOGE("Failed to malloc for deviceIdSelf."); - return HC_ERR_ALLOC_MEMORY; - } - if (memcpy_s(params->deviceIdSelf.val, params->deviceIdSelf.length + 1, - deviceId, params->deviceIdSelf.length) != EOK) { - LOGE("Memcpy_s for deviceIdSelf failed."); - return HC_ERR_MEMORY_COPY; - } - return HC_SUCCESS; -} - -int32_t ExtractPeerDeviceId(PakeAuthParams *params, const CJson *in) -{ - if (params == NULL || in == NULL) { - LOGE("Input params NULL."); - return HC_ERR_INVALID_PARAMS; - } - const char *deviceId = GetStringFromJson(in, FIELD_DEVICE_ID); - if (deviceId == NULL) { - LOGE("Get peer deviceId failed."); - return HC_ERR_JSON_GET; - } - uint32_t len = HcStrlen(deviceId); - if (InitCharStringBuff(¶ms->deviceIdPeer, len) != HC_SUCCESS) { - LOGE("InitCharStringBuff: deviceIdPeer failed."); - return HC_ERR_AUTH_INTERNAL; - } - if (memcpy_s(params->deviceIdPeer.val, params->deviceIdPeer.length + 1, deviceId, len) != EOK) { - LOGE("memcpy_s deviceId failed."); - return HC_ERR_MEMORY_COPY; - } - for (uint32_t i = 0; i < params->deviceIdPeer.length; i++) { - // Change a - f charactor to upper charactor. - if (params->deviceIdPeer.val[i] >= 'a' && params->deviceIdPeer.val[i] <= 'f') { - params->deviceIdPeer.val[i] = (uint8_t)toupper(params->deviceIdPeer.val[i]); - } - } - return HC_SUCCESS; -} - -static int32_t ExtractSelfDevId(PakeAuthParams *params, const CJson *in) -{ - if (params == NULL || in == NULL) { - LOGE("Input params is invalid."); - return HC_ERR_INVALID_PARAMS; - } - const char *devIdSelf = GetStringFromJson(in, FIELD_SELF_DEV_ID); - if (devIdSelf == NULL) { - LOGE("Get devIdSelf failed."); - return HC_ERR_JSON_GET; - } - params->devIdSelf.length = HcStrlen(devIdSelf); - params->devIdSelf.val = (uint8_t *)HcMalloc(params->devIdSelf.length + 1, 0); - if (params->devIdSelf.val == NULL) { - LOGE("Malloc for devIdSelf failed."); - return HC_ERR_ALLOC_MEMORY; - } - if (memcpy_s(params->devIdSelf.val, params->devIdSelf.length, devIdSelf, - params->devIdSelf.length) != EOK) { - LOGE("Copy for self devId failed."); - return HC_ERR_MEMORY_COPY; - } - return HC_SUCCESS; -} - -int32_t ExtractPeerDevId(PakeAuthParams *params, const CJson *in) -{ - if (params == NULL || in == NULL) { - LOGE("Input params is invalid."); - return HC_ERR_INVALID_PARAMS; - } - const char *devId = GetStringFromJson(in, FIELD_DEV_ID); - if (devId == NULL) { - LOGE("Get PeerDevId failed."); - return HC_ERR_JSON_GET; - } - uint32_t len = HcStrlen(devId); - // Peer devId type is hex string, no need to transfer. - if (InitCharStringBuff(¶ms->devIdPeer, len) != HC_SUCCESS) { - LOGE("InitCharStringBuff: idPeer failed."); - return HC_ERR_AUTH_INTERNAL; - } - if (memcpy_s(params->devIdPeer.val, params->devIdPeer.length, devId, len) != EOK) { - LOGE("Failed to copy devId."); - return HC_ERR_MEMORY_COPY; - } - return HC_SUCCESS; -} - -int32_t GetPkInfoPeer(PakeAuthParams *params, const CJson *in) -{ - if (params == NULL || in == NULL) { - LOGE("Input params is invalid."); - return HC_ERR_INVALID_PARAMS; - } - - const char *pkInfoPeerStr = GetStringFromJson(in, FIELD_AUTH_PK_INFO); - if (pkInfoPeerStr == NULL) { - LOGE("Failed to get peer pkInfo string."); - return HC_ERR_JSON_GET; - } - uint32_t len = HcStrlen(pkInfoPeerStr) + 1; - if (InitSingleParam(¶ms->pkInfoPeer, len) != HC_SUCCESS) { - LOGE("Failed to malloc for peer pkInfo."); - return HC_ERR_ALLOC_MEMORY; - } - if (memcpy_s(params->pkInfoPeer.val, len, pkInfoPeerStr, len) != EOK) { - LOGE("GetPkInfoPeer: copy pkInfoPeer failed."); - HcFree(params->pkInfoPeer.val); - params->pkInfoPeer.val = NULL; - return HC_ERR_ALLOC_MEMORY; - } - CJson *info = CreateJsonFromString(pkInfoPeerStr); - if (info == NULL) { - LOGE("Failed to create json for peer pkInfo."); - HcFree(params->pkInfoPeer.val); - params->pkInfoPeer.val = NULL; - return HC_ERR_JSON_CREATE; - } - if (GetByteFromJson(info, FIELD_DEVICE_PK, params->pkPeer, PK_SIZE) != HC_SUCCESS) { - LOGE("Failed to get devicePk."); - FreeJson(info); - HcFree(params->pkInfoPeer.val); - params->pkInfoPeer.val = NULL; - return HC_ERR_JSON_GET; - } - FreeJson(info); - return HC_SUCCESS; -} - -static int32_t GetAsyPubKeyInfo(PakeAuthParams *params) -{ - AccountToken *token = CreateAccountToken(); - if (token == NULL) { - LOGE("Failed to create token."); - return HC_ERR_ALLOC_MEMORY; - } - int32_t res = HC_ERR_GET_PK_INFO; - do { - if (GetAccountAuthTokenManager()->getToken(params->osAccountId, token, - (const char *)params->userIdSelf, (const char *)params->devIdSelf.val) != HC_SUCCESS) { - LOGE("Get token from local error."); - break; - } - uint32_t pkInfoLen = token->pkInfoStr.length; - if (pkInfoLen >= PUBLIC_KEY_INFO_SIZE) { - LOGE("Length of pkInfo from local is error."); - break; - } - if (InitSingleParam(¶ms->pkInfoSelf, pkInfoLen) != HC_SUCCESS) { - LOGE("InitSingleParam: pkInfoSelf failed."); - break; - } - if (memcpy_s(params->pkInfoSelf.val, params->pkInfoSelf.length, token->pkInfoStr.val, pkInfoLen) != EOK) { - LOGE("Copy pkInfoSelf failed."); - break; - } - if (memcpy_s(params->pkSelf, PK_SIZE, token->pkInfo.devicePk.val, token->pkInfo.devicePk.length) != EOK) { - LOGE("Copy pkSelf failed."); - break; - } - if (memcpy_s(params->pkInfoSignSelf.val, params->pkInfoSignSelf.length, token->pkInfoSignature.val, - token->pkInfoSignature.length) != EOK) { - LOGE("Copy pkInfoSignSelf failed."); - break; - } - params->pkInfoSignSelf.length = token->pkInfoSignature.length; - res = HC_SUCCESS; - } while (0); - DestroyAccountToken(token); - return res; -} - -static int32_t FillUserIdForAuth(const CJson *in, PakeAuthParams *params) -{ - const char *userIdSelf = GetStringFromJson(in, FIELD_SELF_USER_ID); - if (userIdSelf == NULL) { - LOGE("Failed to get self userId from input data."); - return HC_ERR_JSON_GET; - } - if (memcpy_s(params->userIdSelf, sizeof(params->userIdSelf), userIdSelf, - sizeof(params->userIdSelf)) != EOK) { - LOGE("Copy for userIdSelf failed."); - return HC_ERR_MEMORY_COPY; - } - return HC_SUCCESS; -} - -int32_t InitPakeAuthParams(const CJson *in, PakeAuthParams *params, const AccountVersionInfo *verInfo) -{ - if (in == NULL || params == NULL || verInfo == NULL) { - LOGE("Input params is NULL."); - return HC_ERR_INVALID_PARAMS; - } - const char *deviceId = GetStringFromJson(in, FIELD_SELF_DEVICE_ID); - if (deviceId == NULL) { - LOGE("Self deviceId is NULL."); - return HC_ERR_INVALID_PARAMS; - } - uint32_t deviceIdLen = HcStrlen(deviceId); - GOTO_IF_ERR(GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, ¶ms->osAccountId)); - GOTO_IF_ERR(InitPakeV2BaseParams(¶ms->pakeParams)); - GOTO_IF_ERR(InitSingleParam(¶ms->pakeParams.epkPeer, P256_PUBLIC_SIZE)); - GOTO_IF_ERR(InitSingleParam(¶ms->pkInfoSignSelf, SIGNATURE_SIZE)); - GOTO_IF_ERR(InitSingleParam(¶ms->pkInfoSignPeer, SIGNATURE_SIZE)); - GOTO_IF_ERR(InitSingleParam(¶ms->pakeParams.idSelf, deviceIdLen + 1)); - GOTO_IF_ERR(ExtractSelfDeviceId(params, in, true)); - GOTO_IF_ERR(ExtractSelfDevId(params, in)); - (void)memcpy_s(params->pakeParams.idSelf.val, deviceIdLen, deviceId, deviceIdLen); - params->pakeParams.idSelf.length = deviceIdLen; - GOTO_IF_ERR(FillUserIdForAuth(in, params)); - GOTO_IF_ERR(GetBoolFromJson(in, FIELD_IS_CLIENT, ¶ms->pakeParams.isClient)); - GOTO_IF_ERR(GetAsyPubKeyInfo(params)); - - params->pakeParams.supportedPakeAlg = verInfo->pakeAlgType; - params->pakeParams.curveType = verInfo->curveType; - params->versionNo = verInfo->versionNo; -#ifdef ACCOUNT_PAKE_DL_PRIME_LEN_384 - params->pakeParams.supportedDlPrimeMod = (uint32_t)params->pakeParams.supportedDlPrimeMod | DL_PRIME_MOD_384; -#endif -#ifdef ACCOUNT_PAKE_DL_PRIME_LEN_256 - params->pakeParams.supportedDlPrimeMod = (uint32_t)params->pakeParams.supportedDlPrimeMod | DL_PRIME_MOD_256; -#endif - return HC_SUCCESS; -ERR: - LOGE("InitPakeAuthParams failed."); - return HC_ERR_AUTH_INTERNAL; -} - -void DestroyPakeAuthParams(PakeAuthParams *params) -{ - if (params == NULL) { - LOGE("Pointer is NULL."); - return; - } - (void)memset_s(params->userIdSelf, sizeof(params->userIdSelf), 0, sizeof(params->userIdSelf)); - (void)memset_s(params->userIdPeer, sizeof(params->userIdPeer), 0, sizeof(params->userIdPeer)); - (void)memset_s(params->pkSelf, sizeof(params->pkSelf), 0, sizeof(params->pkSelf)); - (void)memset_s(params->pkPeer, sizeof(params->pkPeer), 0, sizeof(params->pkPeer)); - (void)memset_s(params->pkInfoPeer.val, params->pkInfoPeer.length, 0, params->pkInfoPeer.length); - FreeUint8Buff(¶ms->pkInfoPeer); - FreeUint8Buff(¶ms->deviceIdPeer); - FreeUint8Buff(¶ms->devIdSelf); - FreeUint8Buff(¶ms->devIdPeer); - FreeUint8Buff(¶ms->pkInfoSelf); - FreeUint8Buff(¶ms->pkInfoSignPeer); - FreeUint8Buff(¶ms->pkInfoSignSelf); - DestroyPakeV2BaseParams(¶ms->pakeParams); - HcFree(params->deviceIdSelf.val); - params->deviceIdSelf.val = NULL; +/* + * Copyright (C) 2022 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 "pake_v2_auth_task_common.h" + +#include +#include "account_module.h" +#include "asy_token_manager.h" +#include "common_defs.h" +#include "device_auth_defines.h" +#include "hc_dev_info.h" +#include "hc_log.h" +#include "hc_types.h" +#include "pake_v2_protocol_common.h" +#include "pake_v2_auth_client_task.h" +#include "pake_v2_auth_server_task.h" +#include "protocol_common.h" +#include "string_util.h" + +#define P256_SHARED_SECRET_KEY_SIZE 32 +#define P256_PUBLIC_SIZE 64 +#define P256_KEY_SIZE 32 + +#define SHARED_KEY_ALIAS "sharedKeyAlias" + +bool IsPakeV2AuthTaskSupported(void) +{ + return true; +} + +TaskBase *CreatePakeV2AuthTask(const CJson *in, CJson *out, const AccountVersionInfo *verInfo) +{ + bool isClient = false; + if (GetBoolFromJson(in, FIELD_IS_CLIENT, &isClient) != HC_SUCCESS) { + LOGD("Get isClient from json failed."); + isClient = false; + } + if (isClient) { + return CreatePakeV2AuthClientTask(in, out, verInfo); + } + return CreatePakeV2AuthServerTask(in, out, verInfo); +} + +int32_t VerifyPkSignPeer(const PakeAuthParams *params) +{ + uint8_t *serverPkAlias = (uint8_t *)HcMalloc(SHA256_LEN, 0); + if (serverPkAlias == NULL) { + LOGE("Failed to malloc for serverPk key alias."); + return HC_ERR_ALLOC_MEMORY; + } + Uint8Buff serverPkAliasBuff = { + .val = serverPkAlias, + .length = SHA256_LEN + }; + + int32_t res = GetAccountAuthTokenManager()->generateKeyAlias((const char *)(params->userIdSelf), + (const char *)params->devIdSelf.val, &serverPkAliasBuff, true); + if (res != HC_SUCCESS) { + HcFree(serverPkAlias); + return res; + } + + Uint8Buff messageBuff = { + .val = params->pkInfoPeer.val, + .length = params->pkInfoPeer.length + }; + Uint8Buff peerSignBuff = { + .val = params->pkInfoSignPeer.val, + .length = params->pkInfoSignPeer.length + }; + res = params->pakeParams.loader->verify(&serverPkAliasBuff, &messageBuff, P256, &peerSignBuff, true); + HcFree(serverPkAlias); + if (res != HC_SUCCESS) { + LOGE("Verify pk sign failed."); + return HC_ERR_VERIFY_FAILED; + } + return HC_SUCCESS; +} + +int32_t GenerateEcdhSharedKey(PakeAuthParams *params) +{ + uint8_t *priAliasVal = (uint8_t *)HcMalloc(SHA256_LEN, 0); + if (priAliasVal == NULL) { + LOGE("Failed to malloc for self key alias."); + return HC_ERR_ALLOC_MEMORY; + } + Uint8Buff aliasBuff = { + .val = priAliasVal, + .length = SHA256_LEN + }; + int32_t res = GetAccountAuthTokenManager()->generateKeyAlias((const char *)(params->userIdSelf), + (const char *)params->devIdSelf.val, &aliasBuff, false); + if (res != HC_SUCCESS) { + HcFree(priAliasVal); + return res; + } + KeyBuff priAliasKeyBuff = { + .key = aliasBuff.val, + .keyLen = aliasBuff.length, + .isAlias = true + }; + KeyBuff publicKeyBuff = { + .key = params->pkPeer, + .keyLen = sizeof(params->pkPeer), + .isAlias = false + }; + uint32_t sharedKeyAliasLen = HcStrlen(SHARED_KEY_ALIAS) + 1; + params->pakeParams.psk.val = (uint8_t *)HcMalloc(sharedKeyAliasLen, 0); + if (params->pakeParams.psk.val == NULL) { + LOGE("Failed to malloc for psk alias."); + HcFree(priAliasVal); + return HC_ERR_ALLOC_MEMORY; + } + params->pakeParams.psk.length = sharedKeyAliasLen; + (void)memcpy_s(params->pakeParams.psk.val, sharedKeyAliasLen, SHARED_KEY_ALIAS, sharedKeyAliasLen); + res = params->pakeParams.loader->agreeSharedSecretWithStorage(&priAliasKeyBuff, &publicKeyBuff, + P256, P256_SHARED_SECRET_KEY_SIZE, &(params->pakeParams.psk)); + HcFree(priAliasVal); + return res; +} + +static int32_t InitCharStringBuff(Uint8Buff *param, uint32_t len) +{ + if (param == NULL || len <= 0) { + LOGE("param is invalid for init."); + return HC_ERR_NULL_PTR; + } + if (InitSingleParam(param, len + 1) != HC_SUCCESS) { + return HC_ERR_ALLOC_MEMORY; + } + param->length = len; + return HC_SUCCESS; +} + +int32_t ExtractPakePeerId(PakeAuthParams *params, const CJson *in) +{ + if (params == NULL || in == NULL) { + LOGE("Input params is invalid."); + return HC_ERR_INVALID_PARAMS; + } + uint32_t deviceIdPeerLen = HcStrlen((const char *)params->deviceIdPeer.val); + if (InitCharStringBuff(¶ms->pakeParams.idPeer, + params->devIdPeer.length + deviceIdPeerLen) != HC_SUCCESS) { + LOGE("InitCharStringBuff: idPeer failed."); + return HC_ERR_AUTH_INTERNAL; + } + (void)memcpy_s(params->pakeParams.idPeer.val, params->pakeParams.idPeer.length, params->devIdPeer.val, + params->devIdPeer.length); + (void)memcpy_s(params->pakeParams.idPeer.val + params->devIdPeer.length, + params->pakeParams.idPeer.length - params->devIdPeer.length, params->deviceIdPeer.val, deviceIdPeerLen); + return HC_SUCCESS; +} + +int32_t ExtractPakeSelfId(PakeAuthParams *params) +{ + if (params == NULL) { + LOGE("Input params NULL."); + return HC_ERR_INVALID_PARAMS; + } + uint32_t deviceIdSelfLen = HcStrlen((const char *)params->deviceIdSelf.val); + if (InitCharStringBuff(¶ms->pakeParams.idSelf, + params->devIdSelf.length + deviceIdSelfLen) != HC_SUCCESS) { + LOGE("InitCharStringBuff: idSelf failed."); + return HC_ERR_AUTH_INTERNAL; + } + + (void)memcpy_s(params->pakeParams.idSelf.val, params->pakeParams.idSelf.length, params->devIdSelf.val, + params->devIdSelf.length); + (void)memcpy_s(params->pakeParams.idSelf.val + params->devIdSelf.length, + params->pakeParams.idSelf.length - params->devIdSelf.length, params->deviceIdSelf.val, deviceIdSelfLen); + return HC_SUCCESS; +} + +static int32_t ExtractSelfDeviceId(PakeAuthParams *params, const CJson *in, bool useSelfPrefix) +{ + if (params == NULL || in == NULL) { + LOGE("Input params NULL."); + return HC_ERR_INVALID_PARAMS; + } + const char *deviceId = NULL; + if (useSelfPrefix) { + deviceId = GetStringFromJson(in, FIELD_SELF_DEVICE_ID); + } else { + deviceId = GetStringFromJson(in, FIELD_DEVICE_ID); + } + if (deviceId == NULL) { + LOGE("Get selfDeviceId from json failed."); + return HC_ERR_JSON_GET; + } + params->deviceIdSelf.length = HcStrlen(deviceId); + params->deviceIdSelf.val = (uint8_t *)HcMalloc(params->deviceIdSelf.length + 1, 0); + if (params->deviceIdSelf.val == NULL) { + LOGE("Failed to malloc for deviceIdSelf."); + return HC_ERR_ALLOC_MEMORY; + } + if (memcpy_s(params->deviceIdSelf.val, params->deviceIdSelf.length + 1, + deviceId, params->deviceIdSelf.length) != EOK) { + LOGE("Memcpy_s for deviceIdSelf failed."); + return HC_ERR_MEMORY_COPY; + } + return HC_SUCCESS; +} + +int32_t ExtractPeerDeviceId(PakeAuthParams *params, const CJson *in) +{ + if (params == NULL || in == NULL) { + LOGE("Input params NULL."); + return HC_ERR_INVALID_PARAMS; + } + const char *deviceId = GetStringFromJson(in, FIELD_DEVICE_ID); + if (deviceId == NULL) { + LOGE("Get peer deviceId failed."); + return HC_ERR_JSON_GET; + } + uint32_t len = HcStrlen(deviceId); + if (InitCharStringBuff(¶ms->deviceIdPeer, len) != HC_SUCCESS) { + LOGE("InitCharStringBuff: deviceIdPeer failed."); + return HC_ERR_AUTH_INTERNAL; + } + if (memcpy_s(params->deviceIdPeer.val, params->deviceIdPeer.length + 1, deviceId, len) != EOK) { + LOGE("memcpy_s deviceId failed."); + return HC_ERR_MEMORY_COPY; + } + for (uint32_t i = 0; i < params->deviceIdPeer.length; i++) { + // Change a - f charactor to upper charactor. + if (params->deviceIdPeer.val[i] >= 'a' && params->deviceIdPeer.val[i] <= 'f') { + params->deviceIdPeer.val[i] = (uint8_t)toupper(params->deviceIdPeer.val[i]); + } + } + return HC_SUCCESS; +} + +static int32_t ExtractSelfDevId(PakeAuthParams *params, const CJson *in) +{ + if (params == NULL || in == NULL) { + LOGE("Input params is invalid."); + return HC_ERR_INVALID_PARAMS; + } + const char *devIdSelf = GetStringFromJson(in, FIELD_SELF_DEV_ID); + if (devIdSelf == NULL) { + LOGE("Get devIdSelf failed."); + return HC_ERR_JSON_GET; + } + params->devIdSelf.length = HcStrlen(devIdSelf); + params->devIdSelf.val = (uint8_t *)HcMalloc(params->devIdSelf.length + 1, 0); + if (params->devIdSelf.val == NULL) { + LOGE("Malloc for devIdSelf failed."); + return HC_ERR_ALLOC_MEMORY; + } + if (memcpy_s(params->devIdSelf.val, params->devIdSelf.length, devIdSelf, + params->devIdSelf.length) != EOK) { + LOGE("Copy for self devId failed."); + return HC_ERR_MEMORY_COPY; + } + return HC_SUCCESS; +} + +int32_t ExtractPeerDevId(PakeAuthParams *params, const CJson *in) +{ + if (params == NULL || in == NULL) { + LOGE("Input params is invalid."); + return HC_ERR_INVALID_PARAMS; + } + const char *devId = GetStringFromJson(in, FIELD_DEV_ID); + if (devId == NULL) { + LOGE("Get PeerDevId failed."); + return HC_ERR_JSON_GET; + } + uint32_t len = HcStrlen(devId); + // Peer devId type is hex string, no need to transfer. + if (InitCharStringBuff(¶ms->devIdPeer, len) != HC_SUCCESS) { + LOGE("InitCharStringBuff: idPeer failed."); + return HC_ERR_AUTH_INTERNAL; + } + if (memcpy_s(params->devIdPeer.val, params->devIdPeer.length, devId, len) != EOK) { + LOGE("Failed to copy devId."); + return HC_ERR_MEMORY_COPY; + } + return HC_SUCCESS; +} + +int32_t GetPkInfoPeer(PakeAuthParams *params, const CJson *in) +{ + if (params == NULL || in == NULL) { + LOGE("Input params is invalid."); + return HC_ERR_INVALID_PARAMS; + } + + const char *pkInfoPeerStr = GetStringFromJson(in, FIELD_AUTH_PK_INFO); + if (pkInfoPeerStr == NULL) { + LOGE("Failed to get peer pkInfo string."); + return HC_ERR_JSON_GET; + } + uint32_t len = HcStrlen(pkInfoPeerStr) + 1; + if (InitSingleParam(¶ms->pkInfoPeer, len) != HC_SUCCESS) { + LOGE("Failed to malloc for peer pkInfo."); + return HC_ERR_ALLOC_MEMORY; + } + if (memcpy_s(params->pkInfoPeer.val, len, pkInfoPeerStr, len) != EOK) { + LOGE("GetPkInfoPeer: copy pkInfoPeer failed."); + HcFree(params->pkInfoPeer.val); + params->pkInfoPeer.val = NULL; + return HC_ERR_ALLOC_MEMORY; + } + CJson *info = CreateJsonFromString(pkInfoPeerStr); + if (info == NULL) { + LOGE("Failed to create json for peer pkInfo."); + HcFree(params->pkInfoPeer.val); + params->pkInfoPeer.val = NULL; + return HC_ERR_JSON_CREATE; + } + if (GetByteFromJson(info, FIELD_DEVICE_PK, params->pkPeer, PK_SIZE) != HC_SUCCESS) { + LOGE("Failed to get devicePk."); + FreeJson(info); + HcFree(params->pkInfoPeer.val); + params->pkInfoPeer.val = NULL; + return HC_ERR_JSON_GET; + } + FreeJson(info); + return HC_SUCCESS; +} + +static int32_t GetAsyPubKeyInfo(PakeAuthParams *params) +{ + AccountToken *token = CreateAccountToken(); + if (token == NULL) { + LOGE("Failed to create token."); + return HC_ERR_ALLOC_MEMORY; + } + int32_t res = HC_ERR_GET_PK_INFO; + do { + if (GetAccountAuthTokenManager()->getToken(params->osAccountId, token, + (const char *)params->userIdSelf, (const char *)params->devIdSelf.val) != HC_SUCCESS) { + LOGE("Get token from local error."); + break; + } + uint32_t pkInfoLen = token->pkInfoStr.length; + if (pkInfoLen >= PUBLIC_KEY_INFO_SIZE) { + LOGE("Length of pkInfo from local is error."); + break; + } + if (InitSingleParam(¶ms->pkInfoSelf, pkInfoLen) != HC_SUCCESS) { + LOGE("InitSingleParam: pkInfoSelf failed."); + break; + } + if (memcpy_s(params->pkInfoSelf.val, params->pkInfoSelf.length, token->pkInfoStr.val, pkInfoLen) != EOK) { + LOGE("Copy pkInfoSelf failed."); + break; + } + if (memcpy_s(params->pkSelf, PK_SIZE, token->pkInfo.devicePk.val, token->pkInfo.devicePk.length) != EOK) { + LOGE("Copy pkSelf failed."); + break; + } + if (memcpy_s(params->pkInfoSignSelf.val, params->pkInfoSignSelf.length, token->pkInfoSignature.val, + token->pkInfoSignature.length) != EOK) { + LOGE("Copy pkInfoSignSelf failed."); + break; + } + params->pkInfoSignSelf.length = token->pkInfoSignature.length; + res = HC_SUCCESS; + } while (0); + DestroyAccountToken(token); + return res; +} + +static int32_t FillUserIdForAuth(const CJson *in, PakeAuthParams *params) +{ + const char *userIdSelf = GetStringFromJson(in, FIELD_SELF_USER_ID); + if (userIdSelf == NULL) { + LOGE("Failed to get self userId from input data."); + return HC_ERR_JSON_GET; + } + if (memcpy_s(params->userIdSelf, sizeof(params->userIdSelf), userIdSelf, + sizeof(params->userIdSelf)) != EOK) { + LOGE("Copy for userIdSelf failed."); + return HC_ERR_MEMORY_COPY; + } + return HC_SUCCESS; +} + +int32_t InitPakeAuthParams(const CJson *in, PakeAuthParams *params, const AccountVersionInfo *verInfo) +{ + if (in == NULL || params == NULL || verInfo == NULL) { + LOGE("Input params is NULL."); + return HC_ERR_INVALID_PARAMS; + } + const char *deviceId = GetStringFromJson(in, FIELD_SELF_DEVICE_ID); + if (deviceId == NULL) { + LOGE("Self deviceId is NULL."); + return HC_ERR_INVALID_PARAMS; + } + uint32_t deviceIdLen = HcStrlen(deviceId); + GOTO_IF_ERR(GetIntFromJson(in, FIELD_OS_ACCOUNT_ID, ¶ms->osAccountId)); + GOTO_IF_ERR(InitPakeV2BaseParams(¶ms->pakeParams)); + GOTO_IF_ERR(InitSingleParam(¶ms->pakeParams.epkPeer, P256_PUBLIC_SIZE)); + GOTO_IF_ERR(InitSingleParam(¶ms->pkInfoSignSelf, SIGNATURE_SIZE)); + GOTO_IF_ERR(InitSingleParam(¶ms->pkInfoSignPeer, SIGNATURE_SIZE)); + GOTO_IF_ERR(InitSingleParam(¶ms->pakeParams.idSelf, deviceIdLen + 1)); + GOTO_IF_ERR(ExtractSelfDeviceId(params, in, true)); + GOTO_IF_ERR(ExtractSelfDevId(params, in)); + (void)memcpy_s(params->pakeParams.idSelf.val, deviceIdLen, deviceId, deviceIdLen); + params->pakeParams.idSelf.length = deviceIdLen; + GOTO_IF_ERR(FillUserIdForAuth(in, params)); + GOTO_IF_ERR(GetBoolFromJson(in, FIELD_IS_CLIENT, ¶ms->pakeParams.isClient)); + GOTO_IF_ERR(GetAsyPubKeyInfo(params)); + + params->pakeParams.supportedPakeAlg = verInfo->pakeAlgType; + params->pakeParams.curveType = verInfo->curveType; + params->versionNo = verInfo->versionNo; +#ifdef ACCOUNT_PAKE_DL_PRIME_LEN_384 + params->pakeParams.supportedDlPrimeMod = (uint32_t)params->pakeParams.supportedDlPrimeMod | DL_PRIME_MOD_384; +#endif +#ifdef ACCOUNT_PAKE_DL_PRIME_LEN_256 + params->pakeParams.supportedDlPrimeMod = (uint32_t)params->pakeParams.supportedDlPrimeMod | DL_PRIME_MOD_256; +#endif + return HC_SUCCESS; +ERR: + LOGE("InitPakeAuthParams failed."); + return HC_ERR_AUTH_INTERNAL; +} + +void DestroyPakeAuthParams(PakeAuthParams *params) +{ + if (params == NULL) { + LOGE("Pointer is NULL."); + return; + } + (void)memset_s(params->userIdSelf, sizeof(params->userIdSelf), 0, sizeof(params->userIdSelf)); + (void)memset_s(params->userIdPeer, sizeof(params->userIdPeer), 0, sizeof(params->userIdPeer)); + (void)memset_s(params->pkSelf, sizeof(params->pkSelf), 0, sizeof(params->pkSelf)); + (void)memset_s(params->pkPeer, sizeof(params->pkPeer), 0, sizeof(params->pkPeer)); + (void)memset_s(params->pkInfoPeer.val, params->pkInfoPeer.length, 0, params->pkInfoPeer.length); + FreeUint8Buff(¶ms->pkInfoPeer); + FreeUint8Buff(¶ms->deviceIdPeer); + FreeUint8Buff(¶ms->devIdSelf); + FreeUint8Buff(¶ms->devIdPeer); + FreeUint8Buff(¶ms->pkInfoSelf); + FreeUint8Buff(¶ms->pkInfoSignPeer); + FreeUint8Buff(¶ms->pkInfoSignSelf); + DestroyPakeV2BaseParams(¶ms->pakeParams); + HcFree(params->deviceIdSelf.val); + params->deviceIdSelf.val = NULL; } \ No newline at end of file diff --git a/services/authenticators/src/account_related/creds_manager/asy_token_manager.c b/services/legacy/authenticators/src/account_related/creds_manager/asy_token_manager.c similarity index 100% rename from services/authenticators/src/account_related/creds_manager/asy_token_manager.c rename to services/legacy/authenticators/src/account_related/creds_manager/asy_token_manager.c diff --git a/services/authenticators/src/account_related/creds_manager/sym_token_manager.c b/services/legacy/authenticators/src/account_related/creds_manager/sym_token_manager.c similarity index 100% rename from services/authenticators/src/account_related/creds_manager/sym_token_manager.c rename to services/legacy/authenticators/src/account_related/creds_manager/sym_token_manager.c diff --git a/services/authenticators/src/account_related_mock/account_module_mock.c b/services/legacy/authenticators/src/account_related_mock/account_module_mock.c similarity index 100% rename from services/authenticators/src/account_related_mock/account_module_mock.c rename to services/legacy/authenticators/src/account_related_mock/account_module_mock.c diff --git a/services/authenticators/src/account_unrelated/das_module.c b/services/legacy/authenticators/src/account_unrelated/das_module.c similarity index 100% rename from services/authenticators/src/account_unrelated/das_module.c rename to services/legacy/authenticators/src/account_unrelated/das_module.c diff --git a/services/authenticators/src/account_unrelated/das_task_common.c b/services/legacy/authenticators/src/account_unrelated/das_task_common.c similarity index 95% rename from services/authenticators/src/account_unrelated/das_task_common.c rename to services/legacy/authenticators/src/account_unrelated/das_task_common.c index e4dcb2d6..2a70c7d6 100644 --- a/services/authenticators/src/account_unrelated/das_task_common.c +++ b/services/legacy/authenticators/src/account_unrelated/das_task_common.c @@ -22,26 +22,9 @@ #include "protocol_common.h" #include "string_util.h" -#define KEY_TYPE_PAIR_LEN 2 -#define PACKAGE_NAME_MAX_LEN 256 -#define SERVICE_TYPE_MAX_LEN 256 -#define AUTH_ID_MAX_LEN 64 - #define MESSAGE_RETURN 0x8000 #define MESSAGE_PREFIX 0x0010 -/* in order to expand to uint16_t */ -static const uint8_t KEY_TYPE_PAIRS[KEY_ALIAS_TYPE_END][KEY_TYPE_PAIR_LEN] = { - { 0x00, 0x00 }, /* ACCESSOR_PK */ - { 0x00, 0x01 }, /* CONTROLLER_PK */ - { 0x00, 0x02 }, /* ed25519 KEYPAIR */ - { 0x00, 0x03 }, /* KEK, key encryption key, used only by DeviceAuthService */ - { 0x00, 0x04 }, /* DEK, data encryption key, used only by upper apps */ - { 0x00, 0x05 }, /* key tmp */ - { 0x00, 0x06 }, /* PSK, preshared key index */ - { 0x00, 0x07 } /* AUTHTOKEN */ -}; - void DasSendErrorToOut(CJson *out, int errCode) { CJson *sendToSelf = CreateJson(); @@ -331,7 +314,7 @@ int32_t GenerateKeyAlias(const Uint8Buff *pkgName, const Uint8Buff *serviceType, LOGE("CombineServiceId failed, res: %x.", res); goto ERR; } - Uint8Buff keyTypeBuff = { (uint8_t *)KEY_TYPE_PAIRS[keyType], KEY_TYPE_PAIR_LEN }; + Uint8Buff keyTypeBuff = { GetKeyTypePair(keyType), KEY_TYPE_PAIR_LEN }; if (keyType == KEY_ALIAS_AUTH_TOKEN) { res = CombineKeyAliasForIso(&serviceId, &keyTypeBuff, authId, outKeyAlias); } else { diff --git a/services/authenticators/src/account_unrelated/das_task_main.c b/services/legacy/authenticators/src/account_unrelated/das_task_main.c similarity index 100% rename from services/authenticators/src/account_unrelated/das_task_main.c rename to services/legacy/authenticators/src/account_unrelated/das_task_main.c diff --git a/services/authenticators/src/account_unrelated/das_version_util.c b/services/legacy/authenticators/src/account_unrelated/das_version_util.c similarity index 100% rename from services/authenticators/src/account_unrelated/das_version_util.c rename to services/legacy/authenticators/src/account_unrelated/das_version_util.c diff --git a/services/authenticators/src/account_unrelated/iso_task/iso_client_task.c b/services/legacy/authenticators/src/account_unrelated/iso_task/iso_client_task.c similarity index 100% rename from services/authenticators/src/account_unrelated/iso_task/iso_client_task.c rename to services/legacy/authenticators/src/account_unrelated/iso_task/iso_client_task.c diff --git a/services/authenticators/src/account_unrelated/iso_task/iso_protocol_task/iso_client_protocol_task.c b/services/legacy/authenticators/src/account_unrelated/iso_task/iso_protocol_task/iso_client_protocol_task.c similarity index 100% rename from services/authenticators/src/account_unrelated/iso_task/iso_protocol_task/iso_client_protocol_task.c rename to services/legacy/authenticators/src/account_unrelated/iso_task/iso_protocol_task/iso_client_protocol_task.c diff --git a/services/authenticators/src/account_unrelated/iso_task/iso_protocol_task/iso_server_protocol_task.c b/services/legacy/authenticators/src/account_unrelated/iso_task/iso_protocol_task/iso_server_protocol_task.c similarity index 100% rename from services/authenticators/src/account_unrelated/iso_task/iso_protocol_task/iso_server_protocol_task.c rename to services/legacy/authenticators/src/account_unrelated/iso_task/iso_protocol_task/iso_server_protocol_task.c diff --git a/services/authenticators/src/account_unrelated/iso_task/iso_server_task.c b/services/legacy/authenticators/src/account_unrelated/iso_task/iso_server_task.c similarity index 100% rename from services/authenticators/src/account_unrelated/iso_task/iso_server_task.c rename to services/legacy/authenticators/src/account_unrelated/iso_task/iso_server_task.c diff --git a/services/authenticators/src/account_unrelated/iso_task/iso_task_common.c b/services/legacy/authenticators/src/account_unrelated/iso_task/iso_task_common.c similarity index 100% rename from services/authenticators/src/account_unrelated/iso_task/iso_task_common.c rename to services/legacy/authenticators/src/account_unrelated/iso_task/iso_task_common.c diff --git a/services/authenticators/src/account_unrelated/iso_task/iso_task_main.c b/services/legacy/authenticators/src/account_unrelated/iso_task/iso_task_main.c similarity index 100% rename from services/authenticators/src/account_unrelated/iso_task/iso_task_main.c rename to services/legacy/authenticators/src/account_unrelated/iso_task/iso_task_main.c diff --git a/services/authenticators/src/account_unrelated/iso_task/lite_exchange_task/das_lite_token_manager.c b/services/legacy/authenticators/src/account_unrelated/iso_task/lite_exchange_task/das_lite_token_manager.c similarity index 100% rename from services/authenticators/src/account_unrelated/iso_task/lite_exchange_task/das_lite_token_manager.c rename to services/legacy/authenticators/src/account_unrelated/iso_task/lite_exchange_task/das_lite_token_manager.c diff --git a/services/authenticators/src/account_unrelated/iso_task/lite_exchange_task/iso_client_bind_exchange_task.c b/services/legacy/authenticators/src/account_unrelated/iso_task/lite_exchange_task/iso_client_bind_exchange_task.c similarity index 100% rename from services/authenticators/src/account_unrelated/iso_task/lite_exchange_task/iso_client_bind_exchange_task.c rename to services/legacy/authenticators/src/account_unrelated/iso_task/lite_exchange_task/iso_client_bind_exchange_task.c diff --git a/services/authenticators/src/account_unrelated/iso_task/lite_exchange_task/iso_server_bind_exchange_task.c b/services/legacy/authenticators/src/account_unrelated/iso_task/lite_exchange_task/iso_server_bind_exchange_task.c similarity index 100% rename from services/authenticators/src/account_unrelated/iso_task/lite_exchange_task/iso_server_bind_exchange_task.c rename to services/legacy/authenticators/src/account_unrelated/iso_task/lite_exchange_task/iso_server_bind_exchange_task.c diff --git a/services/authenticators/src/account_unrelated/iso_task_mock/iso_task_main_mock.c b/services/legacy/authenticators/src/account_unrelated/iso_task_mock/iso_task_main_mock.c similarity index 100% rename from services/authenticators/src/account_unrelated/iso_task_mock/iso_task_main_mock.c rename to services/legacy/authenticators/src/account_unrelated/iso_task_mock/iso_task_main_mock.c diff --git a/services/authenticators/src/account_unrelated/pake_task/pake_message_util.c b/services/legacy/authenticators/src/account_unrelated/pake_task/pake_message_util.c similarity index 100% rename from services/authenticators/src/account_unrelated/pake_task/pake_message_util.c rename to services/legacy/authenticators/src/account_unrelated/pake_task/pake_message_util.c diff --git a/services/authenticators/src/account_unrelated/pake_task/pake_task_common.c b/services/legacy/authenticators/src/account_unrelated/pake_task/pake_task_common.c similarity index 100% rename from services/authenticators/src/account_unrelated/pake_task/pake_task_common.c rename to services/legacy/authenticators/src/account_unrelated/pake_task/pake_task_common.c diff --git a/services/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_client_task.c b/services/legacy/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_client_task.c similarity index 100% rename from services/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_client_task.c rename to services/legacy/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_client_task.c diff --git a/services/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task/pake_v1_client_protocol_task.c b/services/legacy/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task/pake_v1_client_protocol_task.c similarity index 100% rename from services/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task/pake_v1_client_protocol_task.c rename to services/legacy/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task/pake_v1_client_protocol_task.c diff --git a/services/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task/pake_v1_protocol_task_common.c b/services/legacy/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task/pake_v1_protocol_task_common.c similarity index 100% rename from services/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task/pake_v1_protocol_task_common.c rename to services/legacy/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task/pake_v1_protocol_task_common.c diff --git a/services/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task/pake_v1_server_protocol_task.c b/services/legacy/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task/pake_v1_server_protocol_task.c similarity index 100% rename from services/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task/pake_v1_server_protocol_task.c rename to services/legacy/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_protocol_task/pake_v1_server_protocol_task.c diff --git a/services/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_server_task.c b/services/legacy/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_server_task.c similarity index 100% rename from services/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_server_task.c rename to services/legacy/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_server_task.c diff --git a/services/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_task_main.c b/services/legacy/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_task_main.c similarity index 100% rename from services/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_task_main.c rename to services/legacy/authenticators/src/account_unrelated/pake_task/pake_v1_task/pake_v1_task_main.c diff --git a/services/authenticators/src/account_unrelated/pake_task/pake_v1_task_mock/pake_v1_task_main_mock.c b/services/legacy/authenticators/src/account_unrelated/pake_task/pake_v1_task_mock/pake_v1_task_main_mock.c similarity index 100% rename from services/authenticators/src/account_unrelated/pake_task/pake_v1_task_mock/pake_v1_task_main_mock.c rename to services/legacy/authenticators/src/account_unrelated/pake_task/pake_v1_task_mock/pake_v1_task_main_mock.c diff --git a/services/authenticators/src/account_unrelated/pake_task/pake_v2_task_mock/pake_v2_task_main_mock.c b/services/legacy/authenticators/src/account_unrelated/pake_task/pake_v2_task_mock/pake_v2_task_main_mock.c similarity index 100% rename from services/authenticators/src/account_unrelated/pake_task/pake_v2_task_mock/pake_v2_task_main_mock.c rename to services/legacy/authenticators/src/account_unrelated/pake_task/pake_v2_task_mock/pake_v2_task_main_mock.c diff --git a/services/authenticators/src/account_unrelated/pake_task/standard_exchange_task/common_standard_bind_exchange.c b/services/legacy/authenticators/src/account_unrelated/pake_task/standard_exchange_task/common_standard_bind_exchange.c similarity index 100% rename from services/authenticators/src/account_unrelated/pake_task/standard_exchange_task/common_standard_bind_exchange.c rename to services/legacy/authenticators/src/account_unrelated/pake_task/standard_exchange_task/common_standard_bind_exchange.c diff --git a/services/authenticators/src/account_unrelated/pake_task/standard_exchange_task/das_standard_token_manager.c b/services/legacy/authenticators/src/account_unrelated/pake_task/standard_exchange_task/das_standard_token_manager.c similarity index 100% rename from services/authenticators/src/account_unrelated/pake_task/standard_exchange_task/das_standard_token_manager.c rename to services/legacy/authenticators/src/account_unrelated/pake_task/standard_exchange_task/das_standard_token_manager.c diff --git a/services/authenticators/src/account_unrelated/pake_task/standard_exchange_task/standard_client_bind_exchange_task.c b/services/legacy/authenticators/src/account_unrelated/pake_task/standard_exchange_task/standard_client_bind_exchange_task.c similarity index 100% rename from services/authenticators/src/account_unrelated/pake_task/standard_exchange_task/standard_client_bind_exchange_task.c rename to services/legacy/authenticators/src/account_unrelated/pake_task/standard_exchange_task/standard_client_bind_exchange_task.c diff --git a/services/authenticators/src/account_unrelated/pake_task/standard_exchange_task/standard_exchange_message_util.c b/services/legacy/authenticators/src/account_unrelated/pake_task/standard_exchange_task/standard_exchange_message_util.c similarity index 100% rename from services/authenticators/src/account_unrelated/pake_task/standard_exchange_task/standard_exchange_message_util.c rename to services/legacy/authenticators/src/account_unrelated/pake_task/standard_exchange_task/standard_exchange_message_util.c diff --git a/services/authenticators/src/account_unrelated/pake_task/standard_exchange_task/standard_server_bind_exchange_task.c b/services/legacy/authenticators/src/account_unrelated/pake_task/standard_exchange_task/standard_server_bind_exchange_task.c similarity index 100% rename from services/authenticators/src/account_unrelated/pake_task/standard_exchange_task/standard_server_bind_exchange_task.c rename to services/legacy/authenticators/src/account_unrelated/pake_task/standard_exchange_task/standard_server_bind_exchange_task.c diff --git a/services/authenticators/src/account_unrelated/pake_task/standard_exchange_task_mock/standard_exchange_task_mock.c b/services/legacy/authenticators/src/account_unrelated/pake_task/standard_exchange_task_mock/standard_exchange_task_mock.c similarity index 100% rename from services/authenticators/src/account_unrelated/pake_task/standard_exchange_task_mock/standard_exchange_task_mock.c rename to services/legacy/authenticators/src/account_unrelated/pake_task/standard_exchange_task_mock/standard_exchange_task_mock.c diff --git a/services/authenticators/src/account_unrelated_mock/das_module_mock.c b/services/legacy/authenticators/src/account_unrelated_mock/das_module_mock.c similarity index 100% rename from services/authenticators/src/account_unrelated_mock/das_module_mock.c rename to services/legacy/authenticators/src/account_unrelated_mock/das_module_mock.c diff --git a/services/group_auth/inc/account_related_group_auth/account_related_group_auth.h b/services/legacy/group_auth/inc/account_related_group_auth/account_related_group_auth.h similarity index 100% rename from services/group_auth/inc/account_related_group_auth/account_related_group_auth.h rename to services/legacy/group_auth/inc/account_related_group_auth/account_related_group_auth.h diff --git a/services/group_auth/inc/account_unrelated_group_auth/account_unrelated_group_auth.h b/services/legacy/group_auth/inc/account_unrelated_group_auth/account_unrelated_group_auth.h similarity index 100% rename from services/group_auth/inc/account_unrelated_group_auth/account_unrelated_group_auth.h rename to services/legacy/group_auth/inc/account_unrelated_group_auth/account_unrelated_group_auth.h diff --git a/services/group_auth/inc/base_group_auth.h b/services/legacy/group_auth/inc/base_group_auth.h similarity index 100% rename from services/group_auth/inc/base_group_auth.h rename to services/legacy/group_auth/inc/base_group_auth.h diff --git a/services/group_auth/inc/group_auth_data_operation.h b/services/legacy/group_auth/inc/group_auth_data_operation.h similarity index 100% rename from services/group_auth/inc/group_auth_data_operation.h rename to services/legacy/group_auth/inc/group_auth_data_operation.h diff --git a/services/group_auth/src/group_auth_manager/account_related_group_auth/account_related_group_auth.c b/services/legacy/group_auth/src/group_auth_manager/account_related_group_auth/account_related_group_auth.c similarity index 100% rename from services/group_auth/src/group_auth_manager/account_related_group_auth/account_related_group_auth.c rename to services/legacy/group_auth/src/group_auth_manager/account_related_group_auth/account_related_group_auth.c diff --git a/services/group_auth/src/group_auth_manager/account_related_group_auth_mock/account_related_group_auth_mock.c b/services/legacy/group_auth/src/group_auth_manager/account_related_group_auth_mock/account_related_group_auth_mock.c similarity index 100% rename from services/group_auth/src/group_auth_manager/account_related_group_auth_mock/account_related_group_auth_mock.c rename to services/legacy/group_auth/src/group_auth_manager/account_related_group_auth_mock/account_related_group_auth_mock.c diff --git a/services/group_auth/src/group_auth_manager/account_unrelated_group_auth/account_unrelated_group_auth.c b/services/legacy/group_auth/src/group_auth_manager/account_unrelated_group_auth/account_unrelated_group_auth.c similarity index 100% rename from services/group_auth/src/group_auth_manager/account_unrelated_group_auth/account_unrelated_group_auth.c rename to services/legacy/group_auth/src/group_auth_manager/account_unrelated_group_auth/account_unrelated_group_auth.c diff --git a/services/group_auth/src/group_auth_manager/account_unrelated_group_auth_mock/account_unrelated_group_auth_mock.c b/services/legacy/group_auth/src/group_auth_manager/account_unrelated_group_auth_mock/account_unrelated_group_auth_mock.c similarity index 100% rename from services/group_auth/src/group_auth_manager/account_unrelated_group_auth_mock/account_unrelated_group_auth_mock.c rename to services/legacy/group_auth/src/group_auth_manager/account_unrelated_group_auth_mock/account_unrelated_group_auth_mock.c diff --git a/services/group_auth/src/group_auth_manager/group_auth_data_operation.c b/services/legacy/group_auth/src/group_auth_manager/group_auth_data_operation.c similarity index 100% rename from services/group_auth/src/group_auth_manager/group_auth_data_operation.c rename to services/legacy/group_auth/src/group_auth_manager/group_auth_data_operation.c diff --git a/services/group_manager/inc/across_account_group.h b/services/legacy/group_manager/inc/across_account_group.h similarity index 100% rename from services/group_manager/inc/across_account_group.h rename to services/legacy/group_manager/inc/across_account_group.h diff --git a/services/group_manager/inc/base_group.h b/services/legacy/group_manager/inc/base_group.h similarity index 100% rename from services/group_manager/inc/base_group.h rename to services/legacy/group_manager/inc/base_group.h diff --git a/services/group_manager/inc/base_group_manager_task.h b/services/legacy/group_manager/inc/base_group_manager_task.h similarity index 100% rename from services/group_manager/inc/base_group_manager_task.h rename to services/legacy/group_manager/inc/base_group_manager_task.h diff --git a/services/group_manager/inc/broadcast_manager/broadcast_manager.h b/services/legacy/group_manager/inc/broadcast_manager/broadcast_manager.h similarity index 100% rename from services/group_manager/inc/broadcast_manager/broadcast_manager.h rename to services/legacy/group_manager/inc/broadcast_manager/broadcast_manager.h diff --git a/services/group_manager/inc/callback_manager/callback_manager.h b/services/legacy/group_manager/inc/callback_manager/callback_manager.h similarity index 100% rename from services/group_manager/inc/callback_manager/callback_manager.h rename to services/legacy/group_manager/inc/callback_manager/callback_manager.h diff --git a/services/group_manager/inc/channel_manager/channel_manager.h b/services/legacy/group_manager/inc/channel_manager/channel_manager.h similarity index 100% rename from services/group_manager/inc/channel_manager/channel_manager.h rename to services/legacy/group_manager/inc/channel_manager/channel_manager.h diff --git a/services/group_manager/inc/channel_manager/soft_bus_channel/soft_bus_channel.h b/services/legacy/group_manager/inc/channel_manager/soft_bus_channel/soft_bus_channel.h similarity index 100% rename from services/group_manager/inc/channel_manager/soft_bus_channel/soft_bus_channel.h rename to services/legacy/group_manager/inc/channel_manager/soft_bus_channel/soft_bus_channel.h diff --git a/services/group_manager/inc/group_manager.h b/services/legacy/group_manager/inc/group_manager.h similarity index 100% rename from services/group_manager/inc/group_manager.h rename to services/legacy/group_manager/inc/group_manager.h diff --git a/services/group_manager/inc/group_manager_common.h b/services/legacy/group_manager/inc/group_manager_common.h similarity index 100% rename from services/group_manager/inc/group_manager_common.h rename to services/legacy/group_manager/inc/group_manager_common.h diff --git a/services/group_manager/inc/group_operation.h b/services/legacy/group_manager/inc/group_operation.h similarity index 100% rename from services/group_manager/inc/group_operation.h rename to services/legacy/group_manager/inc/group_operation.h diff --git a/services/group_manager/inc/group_operation_common.h b/services/legacy/group_manager/inc/group_operation_common.h similarity index 100% rename from services/group_manager/inc/group_operation_common.h rename to services/legacy/group_manager/inc/group_operation_common.h diff --git a/services/group_manager/inc/identical_account_group.h b/services/legacy/group_manager/inc/identical_account_group.h similarity index 100% rename from services/group_manager/inc/identical_account_group.h rename to services/legacy/group_manager/inc/identical_account_group.h diff --git a/services/group_manager/inc/peer_to_peer_group.h b/services/legacy/group_manager/inc/peer_to_peer_group.h similarity index 100% rename from services/group_manager/inc/peer_to_peer_group.h rename to services/legacy/group_manager/inc/peer_to_peer_group.h diff --git a/services/group_manager/src/broadcast_manager/broadcast_manager.c b/services/legacy/group_manager/src/broadcast_manager/broadcast_manager.c similarity index 100% rename from services/group_manager/src/broadcast_manager/broadcast_manager.c rename to services/legacy/group_manager/src/broadcast_manager/broadcast_manager.c diff --git a/services/group_manager/src/broadcast_manager_mock/broadcast_manager_mock.c b/services/legacy/group_manager/src/broadcast_manager_mock/broadcast_manager_mock.c similarity index 100% rename from services/group_manager/src/broadcast_manager_mock/broadcast_manager_mock.c rename to services/legacy/group_manager/src/broadcast_manager_mock/broadcast_manager_mock.c diff --git a/services/group_manager/src/callback_manager/callback_manager.c b/services/legacy/group_manager/src/callback_manager/callback_manager.c similarity index 100% rename from services/group_manager/src/callback_manager/callback_manager.c rename to services/legacy/group_manager/src/callback_manager/callback_manager.c diff --git a/services/group_manager/src/channel_manager/channel_manager.c b/services/legacy/group_manager/src/channel_manager/channel_manager.c similarity index 100% rename from services/group_manager/src/channel_manager/channel_manager.c rename to services/legacy/group_manager/src/channel_manager/channel_manager.c diff --git a/services/group_manager/src/channel_manager/soft_bus_channel/soft_bus_channel.c b/services/legacy/group_manager/src/channel_manager/soft_bus_channel/soft_bus_channel.c similarity index 100% rename from services/group_manager/src/channel_manager/soft_bus_channel/soft_bus_channel.c rename to services/legacy/group_manager/src/channel_manager/soft_bus_channel/soft_bus_channel.c diff --git a/services/group_manager/src/channel_manager/soft_bus_channel_mock/soft_bus_channel_mock.c b/services/legacy/group_manager/src/channel_manager/soft_bus_channel_mock/soft_bus_channel_mock.c similarity index 100% rename from services/group_manager/src/channel_manager/soft_bus_channel_mock/soft_bus_channel_mock.c rename to services/legacy/group_manager/src/channel_manager/soft_bus_channel_mock/soft_bus_channel_mock.c diff --git a/services/group_manager/src/group_manager.c b/services/legacy/group_manager/src/group_manager.c similarity index 100% rename from services/group_manager/src/group_manager.c rename to services/legacy/group_manager/src/group_manager.c diff --git a/services/group_manager/src/group_manager_common.c b/services/legacy/group_manager/src/group_manager_common.c similarity index 100% rename from services/group_manager/src/group_manager_common.c rename to services/legacy/group_manager/src/group_manager_common.c diff --git a/services/group_manager/src/group_operation/across_account_group/across_account_group.c b/services/legacy/group_manager/src/group_operation/across_account_group/across_account_group.c similarity index 97% rename from services/group_manager/src/group_operation/across_account_group/across_account_group.c rename to services/legacy/group_manager/src/group_operation/across_account_group/across_account_group.c index 2314b786..bdb46232 100644 --- a/services/group_manager/src/group_operation/across_account_group/across_account_group.c +++ b/services/legacy/group_manager/src/group_operation/across_account_group/across_account_group.c @@ -1,664 +1,664 @@ -/* - * Copyright (C) 2022 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 "across_account_group.h" - -#include "account_module.h" -#include "alg_defs.h" -#include "callback_manager.h" -#include "common_defs.h" -#include "cred_manager.h" -#include "data_manager.h" -#include "device_auth_defines.h" -#include "group_operation_common.h" -#include "hc_dev_info.h" -#include "hc_log.h" -#include "string_util.h" - -/* 1: s1 > s2, -1: s1 <= s2 */ -static int32_t CompareString(const char *s1, const char *s2) -{ - if ((s1 == NULL) || (s2 == NULL)) { - LOGE("The input string contains NULL value!"); - return 0; - } - const char *tempChar1 = s1; - const char *tempChar2 = s2; - while ((*tempChar1 != '\0') && (*tempChar2 != '\0')) { - if (*tempChar1 > *tempChar2) { - return 1; - } else if (*tempChar1 < *tempChar2) { - return -1; - } - tempChar1++; - tempChar2++; - } - if (*tempChar1 != '\0') { - return 1; - } - return -1; -} - -static int32_t GenerateGroupId(const char *userId, const char *sharedUserId, char **returnGroupId) -{ - /* across account group: groupId = sha256(userId1 | userId2) */ - uint8_t *hashMessage = NULL; - uint32_t messageSize = 0; - const char *firstUserId = userId; - const char *secondUserId = sharedUserId; - if (CompareString(firstUserId, secondUserId) > 0) { - firstUserId = sharedUserId; - secondUserId = userId; - } - Uint8Buff firstUserIdBuff = { (uint8_t *)firstUserId, HcStrlen(firstUserId) }; - Uint8Buff secondUserIdBuff = { (uint8_t *)secondUserId, HcStrlen(secondUserId) }; - int32_t result = GetHashMessage(&firstUserIdBuff, &secondUserIdBuff, &hashMessage, &messageSize); - if (result != HC_SUCCESS) { - return result; - } - int hashStrLen = SHA256_LEN * BYTE_TO_HEX_OPER_LENGTH + 1; - *returnGroupId = (char *)HcMalloc(hashStrLen, 0); - if (*returnGroupId == NULL) { - LOGE("Failed to allocate returnGroupId memory!"); - HcFree(hashMessage); - return HC_ERR_ALLOC_MEMORY; - } - result = GetHashResult(hashMessage, messageSize, *returnGroupId, hashStrLen); - HcFree(hashMessage); - if (result != HC_SUCCESS) { - LOGE("Failed to get hash for groupId!"); - HcFree(*returnGroupId); - *returnGroupId = NULL; - return HC_ERR_HASH_FAIL; - } - return HC_SUCCESS; -} - -static int32_t AddCredTypeToParamsFromIdenticalGroup(int32_t osAccountId, CJson *jsonParams) -{ - char *userId = NULL; - int32_t result = GetUserIdFromJson(jsonParams, &userId); - if (result != HC_SUCCESS) { - return result; - } - char localUdid[INPUT_UDID_LEN] = { 0 }; - int32_t res = HcGetUdid((uint8_t *)localUdid, INPUT_UDID_LEN); - if (res != HC_SUCCESS) { - LOGE("Failed to get local udid!"); - HcFree(userId); - return res; - } - DeviceEntryVec deviceEntryVec = CREATE_HC_VECTOR(DeviceEntryVec); - QueryDeviceParams params = InitQueryDeviceParams(); - params.userId = userId; - params.udid = localUdid; - if ((QueryDevices(osAccountId, ¶ms, &deviceEntryVec) != HC_SUCCESS) || - (deviceEntryVec.size(&deviceEntryVec) <= 0)) { - LOGE("query trusted devices failed!"); - HcFree(userId); - ClearDeviceEntryVec(&deviceEntryVec); - return HC_ERR_DEVICE_NOT_EXIST; - } - TrustedDeviceEntry *deviceEntry = deviceEntryVec.get(&deviceEntryVec, 0); - if (AddIntToJson(jsonParams, FIELD_CREDENTIAL_TYPE, deviceEntry->credential) != HC_SUCCESS) { - LOGE("Failed to add credentialType to jsonParams!"); - HcFree(userId); - ClearDeviceEntryVec(&deviceEntryVec); - return HC_ERR_JSON_ADD; - } - HcFree(userId); - ClearDeviceEntryVec(&deviceEntryVec); - return HC_SUCCESS; -} - -static int32_t GenerateDevParams(const CJson *jsonParams, const char *groupId, TrustedDeviceEntry *devParams) -{ - int32_t result; - if (((result = AddSelfUdidToParams(devParams)) != HC_SUCCESS) || - ((result = AddAuthIdToParamsOrDefault(jsonParams, devParams)) != HC_SUCCESS) || - ((result = AddCredTypeToParams(jsonParams, devParams)) != HC_SUCCESS) || - ((result = AddUserIdToDevParams(jsonParams, devParams)) != HC_SUCCESS) || - ((result = AddSourceToParams(SELF_CREATED, devParams)) != HC_SUCCESS) || - ((result = AddUserTypeToParamsOrDefault(jsonParams, devParams)) != HC_SUCCESS) || - ((result = AddGroupIdToDevParams(groupId, devParams)) != HC_SUCCESS) || - ((result = AddServiceTypeToParams(groupId, devParams)) != HC_SUCCESS)) { - return result; - } - return HC_SUCCESS; -} - -static int32_t GenerateGroupParams(const CJson *jsonParams, const char *groupId, TrustedGroupEntry *groupParams) -{ - const char *appId = GetStringFromJson(jsonParams, FIELD_APP_ID); - if (appId == NULL) { - LOGE("Failed to get appId from jsonParams!"); - return HC_ERR_JSON_GET; - } - int32_t result; - if (((result = AddGroupTypeToParams(ACROSS_ACCOUNT_AUTHORIZE_GROUP, groupParams)) != HC_SUCCESS) || - ((result = AddGroupNameToParams(groupId, groupParams)) != HC_SUCCESS) || - ((result = AddGroupIdToParams(groupId, groupParams)) != HC_SUCCESS) || - ((result = AddUserIdToGroupParams(jsonParams, groupParams)) != HC_SUCCESS) || - ((result = AddSharedUserIdToGroupParams(jsonParams, groupParams)) != HC_SUCCESS) || - ((result = AddGroupOwnerToParams(appId, groupParams)) != HC_SUCCESS) || - ((result = AddGroupVisibilityOrDefault(jsonParams, groupParams)) != HC_SUCCESS) || - ((result = AddExpireTimeOrDefault(jsonParams, groupParams)) != HC_SUCCESS)) { - return result; - } - return HC_SUCCESS; -} - -static int32_t GenerateAcrossAccountGroupId(const CJson *jsonParams, char **returnGroupId) -{ - char *userId = NULL; - char *sharedUserId = NULL; - int32_t result = GetUserIdFromJson(jsonParams, &userId); - if (result != HC_SUCCESS) { - return result; - } - result = GetSharedUserIdFromJson(jsonParams, &sharedUserId); - if (result != HC_SUCCESS) { - HcFree(userId); - return result; - } - result = GenerateGroupId(userId, sharedUserId, returnGroupId); - HcFree(userId); - HcFree(sharedUserId); - if (result != HC_SUCCESS) { - LOGE("Failed to generate groupId!"); - return result; - } - return HC_SUCCESS; -} - -static int32_t AssertIdenticalGroupExist(int32_t osAccountId, const CJson *jsonParams) -{ - char *userId = NULL; - int32_t result = GetUserIdFromJson(jsonParams, &userId); - if (result != HC_SUCCESS) { - return result; - } - GroupEntryVec groupEntryVec = CreateGroupEntryVec(); - QueryGroupParams params = InitQueryGroupParams(); - params.groupType = IDENTICAL_ACCOUNT_GROUP; - result = QueryGroups(osAccountId, ¶ms, &groupEntryVec); - if (result != HC_SUCCESS) { - LOGE("Failed to query groups!"); - HcFree(userId); - ClearGroupEntryVec(&groupEntryVec); - return result; - } - bool isExist = false; - uint32_t index; - TrustedGroupEntry **entry = NULL; - FOR_EACH_HC_VECTOR(groupEntryVec, index, entry) { - if (strcmp(userId, StringGet(&((*entry)->userId))) == 0) { - isExist = true; - break; - } - } - HcFree(userId); - ClearGroupEntryVec(&groupEntryVec); - if (!isExist) { - LOGE("The identical account group has not been created!"); - return HC_ERR_GROUP_NOT_EXIST; - } - return HC_SUCCESS; -} - -static int32_t AssertSharedUserIdValid(const CJson *jsonParams) -{ - const char *userId = GetStringFromJson(jsonParams, FIELD_USER_ID); - if (userId == NULL) { - LOGE("Failed to get userId from jsonParams!"); - return HC_ERR_JSON_GET; - } - const char *sharedUserId = GetStringFromJson(jsonParams, FIELD_PEER_USER_ID); - if (sharedUserId == NULL) { - LOGE("Failed to get sharedUserId from jsonParams!"); - return HC_ERR_JSON_GET; - } - if (strcmp(sharedUserId, userId) == 0) { - LOGE("The input peerUserId is the same as the local userId!"); - return HC_ERR_INVALID_PARAMS; - } - return HC_SUCCESS; -} - -static int32_t CheckCreateParams(int32_t osAccountId, const CJson *jsonParams) -{ - const char *appId = GetStringFromJson(jsonParams, FIELD_APP_ID); - if (appId == NULL) { - LOGE("Failed to get appId from jsonParams!"); - return HC_ERR_JSON_GET; - } - int32_t result; - if (((result = CheckUserTypeIfExist(jsonParams)) != HC_SUCCESS) || - ((result = CheckGroupVisibilityIfExist(jsonParams)) != HC_SUCCESS) || - ((result = CheckExpireTimeIfExist(jsonParams)) != HC_SUCCESS) || - ((result = AssertUserIdExist(jsonParams)) != HC_SUCCESS) || - ((result = AssertSharedUserIdValid(jsonParams)) != HC_SUCCESS) || - ((result = AssertIdenticalGroupExist(osAccountId, jsonParams)) != HC_SUCCESS)) { - return result; - } - return HC_SUCCESS; -} - -static int32_t GenerateAddTokenParams(const CJson *deviceInfo, CJson *addParams) -{ - const char *userId = GetStringFromJson(deviceInfo, FIELD_USER_ID); - if (userId == NULL) { - LOGE("Failed to get userId from json!"); - return HC_ERR_JSON_GET; - } - const char *deviceId = GetStringFromJson(deviceInfo, FIELD_DEVICE_ID); - if (deviceId == NULL) { - LOGE("Failed to get deviceId from json!"); - return HC_ERR_JSON_GET; - } - if (AddStringToJson(addParams, FIELD_DEVICE_ID, deviceId) != HC_SUCCESS) { - LOGE("Failed to add deviceId to json!"); - return HC_ERR_JSON_ADD; - } - if (AddStringToJson(addParams, FIELD_USER_ID, userId) != HC_SUCCESS) { - LOGE("Failed to add userId to json!"); - return HC_ERR_JSON_ADD; - } - return HC_SUCCESS; -} - -static int32_t GenerateDelTokenParams(const TrustedDeviceEntry *entry, CJson *delParams) -{ - if (AddIntToJson(delParams, FIELD_CREDENTIAL_TYPE, (int32_t)entry->credential) != HC_SUCCESS) { - LOGE("Failed to add credentialType to json!"); - return HC_ERR_JSON_ADD; - } - if (AddStringToJson(delParams, FIELD_USER_ID, StringGet(&entry->userId)) != HC_SUCCESS) { - LOGE("Failed to add userId to json!"); - return HC_ERR_JSON_ADD; - } - if (AddStringToJson(delParams, FIELD_DEVICE_ID, StringGet(&entry->authId)) != HC_SUCCESS) { - LOGE("Failed to add deviceId to json!"); - return HC_ERR_JSON_ADD; - } - return HC_SUCCESS; -} - -static int32_t DelPeerDeviceToken(int32_t osAccountId, const TrustedDeviceEntry *entry) -{ - CJson *delParams = CreateJson(); - if (delParams == NULL) { - LOGE("Failed to allocate delParams memory!"); - return HC_ERR_ALLOC_MEMORY; - } - int32_t res = GenerateDelTokenParams(entry, delParams); - if (res != HC_SUCCESS) { - FreeJson(delParams); - return res; - } - res = ProcCred(ACCOUNT_RELATED_PLUGIN, osAccountId, DELETE_TRUSTED_CREDENTIALS, delParams, NULL); - FreeJson(delParams); - return res; -} - -static void DelAllPeerTokens(int32_t osAccountId, const DeviceEntryVec *vec) -{ - int32_t res; - uint32_t index; - TrustedDeviceEntry **entry = NULL; - FOR_EACH_HC_VECTOR(*vec, index, entry) { - if (IsLocalDevice(StringGet(&(*entry)->udid))) { - continue; - } - res = DelPeerDeviceToken(osAccountId, *entry); - if (res != HC_SUCCESS) { - LOGE("Failed to delete peer device token! res: %d", res); - } - } -} - -static int32_t DelGroupAndTokens(int32_t osAccountId, const char *groupId) -{ - DeviceEntryVec deviceList = CreateDeviceEntryVec(); - (void)GetTrustedDevices(osAccountId, groupId, &deviceList); - int32_t res = DelGroupFromDb(osAccountId, groupId); - DelAllPeerTokens(osAccountId, &deviceList); - ClearDeviceEntryVec(&deviceList); - return res; -} - -static int32_t CheckChangeParams(int32_t osAccountId, const char *appId, CJson *jsonParams) -{ - const char *groupId = GetStringFromJson(jsonParams, FIELD_GROUP_ID); - if (groupId == NULL) { - LOGE("Failed to get groupId from json!"); - return HC_ERR_JSON_GET; - } - int32_t groupType; - int32_t result; - if (((result = CheckGroupExist(osAccountId, groupId)) != HC_SUCCESS) || - ((result = GetGroupTypeFromDb(osAccountId, groupId, &groupType)) != HC_SUCCESS) || - ((result = AssertGroupTypeMatch(groupType, ACROSS_ACCOUNT_AUTHORIZE_GROUP)) != HC_SUCCESS) || - ((result = CheckGroupEditAllowed(osAccountId, groupId, appId)) != HC_SUCCESS)) { - return result; - } - return HC_SUCCESS; -} - -static int32_t DelDeviceById(int32_t osAccountId, const char *groupId, const char *deviceId, bool isUdid) -{ - QueryDeviceParams queryDeviceParams = InitQueryDeviceParams(); - queryDeviceParams.groupId = groupId; - if (isUdid) { - queryDeviceParams.udid = deviceId; - } else { - queryDeviceParams.authId = deviceId; - } - return DelTrustedDevice(osAccountId, &queryDeviceParams); -} - -static int32_t GenerateTrustedDevParams(const CJson *jsonParams, const char *groupId, TrustedDeviceEntry *devParams) -{ - int32_t result; - if (((result = AddUdidToParams(jsonParams, devParams)) != HC_SUCCESS) || - ((result = AddAuthIdToParams(jsonParams, devParams)) != HC_SUCCESS) || - ((result = AddCredTypeToParams(jsonParams, devParams)) != HC_SUCCESS) || - ((result = AddUserIdToDevParams(jsonParams, devParams)) != HC_SUCCESS) || - ((result = AddSourceToParams(IMPORTED_FROM_CLOUD, devParams)) != HC_SUCCESS) || - ((result = AddUserTypeToParamsOrDefault(jsonParams, devParams)) != HC_SUCCESS) || - ((result = AddGroupIdToDevParams(groupId, devParams)) != HC_SUCCESS) || - ((result = AddServiceTypeToParams(groupId, devParams)) != HC_SUCCESS)) { - return result; - } - return HC_SUCCESS; -} - -static int32_t CheckPeerDeviceNotSelf(const CJson *deviceInfo) -{ - const char *udid = GetStringFromJson(deviceInfo, FIELD_UDID); - if (udid == NULL) { - LOGE("Failed to get udid from json!"); - return HC_ERR_JSON_GET; - } - return AssertPeerDeviceNotSelf(udid); -} - -static int32_t AddDeviceAndToken(int32_t osAccountId, const CJson *jsonParams, CJson *deviceInfo) -{ - const char *groupId = GetStringFromJson(jsonParams, FIELD_GROUP_ID); - if (groupId == NULL) { - LOGE("Failed to get groupId from json!"); - return HC_ERR_JSON_GET; - } - CJson *credential = GetObjFromJson(deviceInfo, FIELD_CREDENTIAL); - if (credential == NULL) { - LOGE("Failed to get credential from json!"); - return HC_ERR_JSON_GET; - } - int32_t res = GenerateAddTokenParams(deviceInfo, credential); - if (res != HC_SUCCESS) { - return res; - } - res = ProcCred(ACCOUNT_RELATED_PLUGIN, osAccountId, IMPORT_TRUSTED_CREDENTIALS, credential, NULL); - if (res != HC_SUCCESS) { - LOGE("Failed to import device token! res: %d", res); - return res; - } - res = AddDeviceToDatabaseByJson(osAccountId, GenerateTrustedDevParams, deviceInfo, groupId); - if (res != HC_SUCCESS) { - LOGE("Failed to add device to database! res: %d", res); - } - return res; -} - -static int32_t DelPeerDeviceAndToken(int32_t osAccountId, CJson *jsonParams, CJson *deviceInfo) -{ - const char *groupId = GetStringFromJson(jsonParams, FIELD_GROUP_ID); - if (groupId == NULL) { - LOGE("Failed to get groupId from json!"); - return HC_ERR_JSON_GET; - } - const char *deviceId = GetStringFromJson(deviceInfo, FIELD_DEVICE_ID); - if (deviceId == NULL) { - LOGE("Failed to get deviceId from json!"); - return HC_ERR_JSON_GET; - } - TrustedDeviceEntry *entry = GetTrustedDeviceEntryById(osAccountId, deviceId, false, groupId); - if (entry == NULL) { - LOGE("Failed to get device from db!"); - return HC_ERR_DEVICE_NOT_EXIST; - } - if (IsLocalDevice(StringGet(&entry->udid))) { - LOGE("Do not delete the local device!"); - DestroyDeviceEntry(entry); - return HC_ERR_INVALID_PARAMS; - } - int32_t res = DelDeviceById(osAccountId, groupId, deviceId, false); - if (res != HC_SUCCESS) { - LOGE("Failed to delete device from database! res: %d", res); - DestroyDeviceEntry(entry); - return res; - } - res = DelPeerDeviceToken(osAccountId, entry); - DestroyDeviceEntry(entry); - if (res != HC_SUCCESS) { - LOGE("Failed to delete token! res: %d", res); - } - return res; -} - -static int32_t AddGroupAndLocalDev(int32_t osAccountId, CJson *jsonParams, const char *groupId) -{ - int32_t res = AddGroupToDatabaseByJson(osAccountId, GenerateGroupParams, jsonParams, groupId); - if (res != HC_SUCCESS) { - LOGE("Failed to add group to database!"); - return res; - } - res = AddDeviceToDatabaseByJson(osAccountId, GenerateDevParams, jsonParams, groupId); - if (res != HC_SUCCESS) { - LOGE("Failed to add device to database!"); - (void)DelGroupFromDb(osAccountId, groupId); - return res; - } - res = SaveOsAccountDb(osAccountId); - if (res != HC_SUCCESS) { - LOGE("Failed to save database!"); - (void)DelGroupFromDb(osAccountId, groupId); - } - return res; -} - -static int32_t CheckUserIdValid(int32_t osAccountId, const CJson *jsonParams, const CJson *deviceInfo) -{ - const char *userId = GetStringFromJson(deviceInfo, FIELD_USER_ID); - if (userId == NULL) { - LOGE("Failed to get userId from json!"); - return HC_ERR_JSON_GET; - } - const char *groupId = GetStringFromJson(jsonParams, FIELD_GROUP_ID); - if (groupId == NULL) { - LOGE("Failed to get groupId from json!"); - return HC_ERR_JSON_GET; - } - uint32_t index; - TrustedGroupEntry **entry = NULL; - GroupEntryVec groupEntryVec = CreateGroupEntryVec(); - QueryGroupParams params = InitQueryGroupParams(); - params.groupId = groupId; - params.groupType = ACROSS_ACCOUNT_AUTHORIZE_GROUP; - if (QueryGroups(osAccountId, ¶ms, &groupEntryVec) != HC_SUCCESS) { - LOGE("Failed to query groups!"); - ClearGroupEntryVec(&groupEntryVec); - return HC_ERR_DB; - } - FOR_EACH_HC_VECTOR(groupEntryVec, index, entry) { - if (strcmp(userId, StringGet(&(*entry)->sharedUserId)) == 0) { - ClearGroupEntryVec(&groupEntryVec); - return HC_SUCCESS; - } - } - LOGE("The input userId is inconsistent with the sharedUserId!"); - ClearGroupEntryVec(&groupEntryVec); - return HC_ERR_INVALID_PARAMS; -} - -static int32_t CheckDeviceInfoValid(int32_t osAccountId, const CJson *jsonParams, const CJson *deviceInfo) -{ - int32_t res = CheckPeerDeviceNotSelf(deviceInfo); - if (res != HC_SUCCESS) { - LOGE("The peer device udid is equals to the local udid!"); - return res; - } - /* Across account group: input userId must be consistent with the sharedUserId. */ - return CheckUserIdValid(osAccountId, jsonParams, deviceInfo); -} - -static int32_t CreateGroup(int32_t osAccountId, CJson *jsonParams, char **returnJsonStr) -{ - LOGI("[Start]: Start to create a across account group!"); - if ((jsonParams == NULL) || (returnJsonStr == NULL)) { - LOGE("The input parameters contains NULL value!"); - return HC_ERR_INVALID_PARAMS; - } - char *groupId = NULL; - int32_t result; - if (((result = CheckCreateParams(osAccountId, jsonParams)) != HC_SUCCESS) || - ((result = GenerateAcrossAccountGroupId(jsonParams, &groupId)) != HC_SUCCESS) || - ((result = AssertSameGroupNotExist(osAccountId, groupId)) != HC_SUCCESS) || - ((result = AddCredTypeToParamsFromIdenticalGroup(osAccountId, jsonParams)) != HC_SUCCESS) || - ((result = AddGroupAndLocalDev(osAccountId, jsonParams, groupId)) != HC_SUCCESS) || - ((result = ConvertGroupIdToJsonStr(groupId, returnJsonStr)) != HC_SUCCESS)) { - HcFree(groupId); - return result; - } - HcFree(groupId); - LOGI("[End]: Create a across account group successfully!"); - return HC_SUCCESS; -} - -static int32_t DeleteGroup(int32_t osAccountId, CJson *jsonParams, char **returnJsonStr) -{ - LOGI("[Start]: Start to delete a across account group!"); - if ((jsonParams == NULL) || (returnJsonStr == NULL)) { - LOGE("The input parameters contains NULL value!"); - return HC_ERR_INVALID_PARAMS; - } - int32_t result; - const char *groupId = NULL; - if (((result = GetGroupIdFromJson(jsonParams, &groupId)) != HC_SUCCESS) || - ((result = DelGroupAndTokens(osAccountId, groupId)) != HC_SUCCESS) || - ((result = ConvertGroupIdToJsonStr(groupId, returnJsonStr)) != HC_SUCCESS)) { - return result; - } - LOGI("[End]: Delete a across account group successfully!"); - return HC_SUCCESS; -} - -static int32_t AddMultiMembersToGroup(int32_t osAccountId, const char *appId, CJson *jsonParams) -{ - LOGI("[Start]: Start to add multiple members to a across account group!"); - if ((appId == NULL) || (jsonParams == NULL)) { - LOGE("Invalid params!"); - return HC_ERR_INVALID_PARAMS; - } - int32_t res = CheckChangeParams(osAccountId, appId, jsonParams); - if (res != HC_SUCCESS) { - return res; - } - CJson *deviceList = GetObjFromJson(jsonParams, FIELD_DEVICE_LIST); - if (deviceList == NULL) { - LOGE("Failed to get deviceList from json!"); - return HC_ERR_JSON_GET; - } - int32_t deviceNum = GetItemNum(deviceList); - int32_t addedCount = 0; - for (int32_t i = 0; i < deviceNum; i++) { - CJson *deviceInfo = GetItemFromArray(deviceList, i); - if (deviceInfo == NULL) { - LOGE("The deviceInfo is NULL!"); - continue; - } - if (CheckDeviceInfoValid(osAccountId, jsonParams, deviceInfo) != HC_SUCCESS) { - continue; - } - if (AddDeviceAndToken(osAccountId, jsonParams, deviceInfo) == HC_SUCCESS) { - addedCount++; - } - } - res = SaveOsAccountDb(osAccountId); - if (res != HC_SUCCESS) { - LOGE("Failed to save database!"); - return res; - } - LOGI("[End]: Add multiple members to a across account group successfully! [ListNum]: %d, [AddedNum]: %d", - deviceNum, addedCount); - return HC_SUCCESS; -} - -static int32_t DelMultiMembersFromGroup(int32_t osAccountId, const char *appId, CJson *jsonParams) -{ - LOGI("[Start]: Start to delete multiple members from a across account group!"); - if ((appId == NULL) || (jsonParams == NULL)) { - LOGE("Invalid params!"); - return HC_ERR_INVALID_PARAMS; - } - int32_t res = CheckChangeParams(osAccountId, appId, jsonParams); - if (res != HC_SUCCESS) { - return res; - } - CJson *deviceList = GetObjFromJson(jsonParams, FIELD_DEVICE_LIST); - if (deviceList == NULL) { - LOGE("Failed to get deviceList from json!"); - return HC_ERR_JSON_GET; - } - int32_t deviceNum = GetItemNum(deviceList); - int32_t deletedCount = 0; - for (int32_t i = 0; i < deviceNum; i++) { - CJson *deviceInfo = GetItemFromArray(deviceList, i); - if (deviceInfo == NULL) { - LOGE("The deviceInfo is NULL!"); - continue; - } - if (DelPeerDeviceAndToken(osAccountId, jsonParams, deviceInfo) == HC_SUCCESS) { - deletedCount++; - } - } - res = SaveOsAccountDb(osAccountId); - if (res != HC_SUCCESS) { - LOGE("Failed to save database!"); - return res; - } - LOGI("[End]: Delete multiple members from a across account group successfully! [ListNum]: %d, [DeletedNum]: %d", - deviceNum, deletedCount); - return HC_SUCCESS; -} - -static AcrossAccountGroup g_acrossAccountGroup = { - .base.type = ACROSS_ACCOUNT_AUTHORIZE_GROUP, - .base.createGroup = CreateGroup, - .base.deleteGroup = DeleteGroup, - .addMultiMembersToGroup = AddMultiMembersToGroup, - .delMultiMembersFromGroup = DelMultiMembersFromGroup, -}; - -BaseGroup *GetAcrossAccountGroupInstance(void) -{ - return (BaseGroup *)&g_acrossAccountGroup; -} - -bool IsAcrossAccountGroupSupported(void) -{ - return true; -} +/* + * Copyright (C) 2022 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 "across_account_group.h" + +#include "account_module.h" +#include "alg_defs.h" +#include "callback_manager.h" +#include "common_defs.h" +#include "cred_manager.h" +#include "data_manager.h" +#include "device_auth_defines.h" +#include "group_operation_common.h" +#include "hc_dev_info.h" +#include "hc_log.h" +#include "string_util.h" + +/* 1: s1 > s2, -1: s1 <= s2 */ +static int32_t CompareString(const char *s1, const char *s2) +{ + if ((s1 == NULL) || (s2 == NULL)) { + LOGE("The input string contains NULL value!"); + return 0; + } + const char *tempChar1 = s1; + const char *tempChar2 = s2; + while ((*tempChar1 != '\0') && (*tempChar2 != '\0')) { + if (*tempChar1 > *tempChar2) { + return 1; + } else if (*tempChar1 < *tempChar2) { + return -1; + } + tempChar1++; + tempChar2++; + } + if (*tempChar1 != '\0') { + return 1; + } + return -1; +} + +static int32_t GenerateGroupId(const char *userId, const char *sharedUserId, char **returnGroupId) +{ + /* across account group: groupId = sha256(userId1 | userId2) */ + uint8_t *hashMessage = NULL; + uint32_t messageSize = 0; + const char *firstUserId = userId; + const char *secondUserId = sharedUserId; + if (CompareString(firstUserId, secondUserId) > 0) { + firstUserId = sharedUserId; + secondUserId = userId; + } + Uint8Buff firstUserIdBuff = { (uint8_t *)firstUserId, HcStrlen(firstUserId) }; + Uint8Buff secondUserIdBuff = { (uint8_t *)secondUserId, HcStrlen(secondUserId) }; + int32_t result = GetHashMessage(&firstUserIdBuff, &secondUserIdBuff, &hashMessage, &messageSize); + if (result != HC_SUCCESS) { + return result; + } + int hashStrLen = SHA256_LEN * BYTE_TO_HEX_OPER_LENGTH + 1; + *returnGroupId = (char *)HcMalloc(hashStrLen, 0); + if (*returnGroupId == NULL) { + LOGE("Failed to allocate returnGroupId memory!"); + HcFree(hashMessage); + return HC_ERR_ALLOC_MEMORY; + } + result = GetHashResult(hashMessage, messageSize, *returnGroupId, hashStrLen); + HcFree(hashMessage); + if (result != HC_SUCCESS) { + LOGE("Failed to get hash for groupId!"); + HcFree(*returnGroupId); + *returnGroupId = NULL; + return HC_ERR_HASH_FAIL; + } + return HC_SUCCESS; +} + +static int32_t AddCredTypeToParamsFromIdenticalGroup(int32_t osAccountId, CJson *jsonParams) +{ + char *userId = NULL; + int32_t result = GetUserIdFromJson(jsonParams, &userId); + if (result != HC_SUCCESS) { + return result; + } + char localUdid[INPUT_UDID_LEN] = { 0 }; + int32_t res = HcGetUdid((uint8_t *)localUdid, INPUT_UDID_LEN); + if (res != HC_SUCCESS) { + LOGE("Failed to get local udid!"); + HcFree(userId); + return res; + } + DeviceEntryVec deviceEntryVec = CREATE_HC_VECTOR(DeviceEntryVec); + QueryDeviceParams params = InitQueryDeviceParams(); + params.userId = userId; + params.udid = localUdid; + if ((QueryDevices(osAccountId, ¶ms, &deviceEntryVec) != HC_SUCCESS) || + (deviceEntryVec.size(&deviceEntryVec) <= 0)) { + LOGE("query trusted devices failed!"); + HcFree(userId); + ClearDeviceEntryVec(&deviceEntryVec); + return HC_ERR_DEVICE_NOT_EXIST; + } + TrustedDeviceEntry *deviceEntry = deviceEntryVec.get(&deviceEntryVec, 0); + if (AddIntToJson(jsonParams, FIELD_CREDENTIAL_TYPE, deviceEntry->credential) != HC_SUCCESS) { + LOGE("Failed to add credentialType to jsonParams!"); + HcFree(userId); + ClearDeviceEntryVec(&deviceEntryVec); + return HC_ERR_JSON_ADD; + } + HcFree(userId); + ClearDeviceEntryVec(&deviceEntryVec); + return HC_SUCCESS; +} + +static int32_t GenerateDevParams(const CJson *jsonParams, const char *groupId, TrustedDeviceEntry *devParams) +{ + int32_t result; + if (((result = AddSelfUdidToParams(devParams)) != HC_SUCCESS) || + ((result = AddAuthIdToParamsOrDefault(jsonParams, devParams)) != HC_SUCCESS) || + ((result = AddCredTypeToParams(jsonParams, devParams)) != HC_SUCCESS) || + ((result = AddUserIdToDevParams(jsonParams, devParams)) != HC_SUCCESS) || + ((result = AddSourceToParams(SELF_CREATED, devParams)) != HC_SUCCESS) || + ((result = AddUserTypeToParamsOrDefault(jsonParams, devParams)) != HC_SUCCESS) || + ((result = AddGroupIdToDevParams(groupId, devParams)) != HC_SUCCESS) || + ((result = AddServiceTypeToParams(groupId, devParams)) != HC_SUCCESS)) { + return result; + } + return HC_SUCCESS; +} + +static int32_t GenerateGroupParams(const CJson *jsonParams, const char *groupId, TrustedGroupEntry *groupParams) +{ + const char *appId = GetStringFromJson(jsonParams, FIELD_APP_ID); + if (appId == NULL) { + LOGE("Failed to get appId from jsonParams!"); + return HC_ERR_JSON_GET; + } + int32_t result; + if (((result = AddGroupTypeToParams(ACROSS_ACCOUNT_AUTHORIZE_GROUP, groupParams)) != HC_SUCCESS) || + ((result = AddGroupNameToParams(groupId, groupParams)) != HC_SUCCESS) || + ((result = AddGroupIdToParams(groupId, groupParams)) != HC_SUCCESS) || + ((result = AddUserIdToGroupParams(jsonParams, groupParams)) != HC_SUCCESS) || + ((result = AddSharedUserIdToGroupParams(jsonParams, groupParams)) != HC_SUCCESS) || + ((result = AddGroupOwnerToParams(appId, groupParams)) != HC_SUCCESS) || + ((result = AddGroupVisibilityOrDefault(jsonParams, groupParams)) != HC_SUCCESS) || + ((result = AddExpireTimeOrDefault(jsonParams, groupParams)) != HC_SUCCESS)) { + return result; + } + return HC_SUCCESS; +} + +static int32_t GenerateAcrossAccountGroupId(const CJson *jsonParams, char **returnGroupId) +{ + char *userId = NULL; + char *sharedUserId = NULL; + int32_t result = GetUserIdFromJson(jsonParams, &userId); + if (result != HC_SUCCESS) { + return result; + } + result = GetSharedUserIdFromJson(jsonParams, &sharedUserId); + if (result != HC_SUCCESS) { + HcFree(userId); + return result; + } + result = GenerateGroupId(userId, sharedUserId, returnGroupId); + HcFree(userId); + HcFree(sharedUserId); + if (result != HC_SUCCESS) { + LOGE("Failed to generate groupId!"); + return result; + } + return HC_SUCCESS; +} + +static int32_t AssertIdenticalGroupExist(int32_t osAccountId, const CJson *jsonParams) +{ + char *userId = NULL; + int32_t result = GetUserIdFromJson(jsonParams, &userId); + if (result != HC_SUCCESS) { + return result; + } + GroupEntryVec groupEntryVec = CreateGroupEntryVec(); + QueryGroupParams params = InitQueryGroupParams(); + params.groupType = IDENTICAL_ACCOUNT_GROUP; + result = QueryGroups(osAccountId, ¶ms, &groupEntryVec); + if (result != HC_SUCCESS) { + LOGE("Failed to query groups!"); + HcFree(userId); + ClearGroupEntryVec(&groupEntryVec); + return result; + } + bool isExist = false; + uint32_t index; + TrustedGroupEntry **entry = NULL; + FOR_EACH_HC_VECTOR(groupEntryVec, index, entry) { + if (strcmp(userId, StringGet(&((*entry)->userId))) == 0) { + isExist = true; + break; + } + } + HcFree(userId); + ClearGroupEntryVec(&groupEntryVec); + if (!isExist) { + LOGE("The identical account group has not been created!"); + return HC_ERR_GROUP_NOT_EXIST; + } + return HC_SUCCESS; +} + +static int32_t AssertSharedUserIdValid(const CJson *jsonParams) +{ + const char *userId = GetStringFromJson(jsonParams, FIELD_USER_ID); + if (userId == NULL) { + LOGE("Failed to get userId from jsonParams!"); + return HC_ERR_JSON_GET; + } + const char *sharedUserId = GetStringFromJson(jsonParams, FIELD_PEER_USER_ID); + if (sharedUserId == NULL) { + LOGE("Failed to get sharedUserId from jsonParams!"); + return HC_ERR_JSON_GET; + } + if (strcmp(sharedUserId, userId) == 0) { + LOGE("The input peerUserId is the same as the local userId!"); + return HC_ERR_INVALID_PARAMS; + } + return HC_SUCCESS; +} + +static int32_t CheckCreateParams(int32_t osAccountId, const CJson *jsonParams) +{ + const char *appId = GetStringFromJson(jsonParams, FIELD_APP_ID); + if (appId == NULL) { + LOGE("Failed to get appId from jsonParams!"); + return HC_ERR_JSON_GET; + } + int32_t result; + if (((result = CheckUserTypeIfExist(jsonParams)) != HC_SUCCESS) || + ((result = CheckGroupVisibilityIfExist(jsonParams)) != HC_SUCCESS) || + ((result = CheckExpireTimeIfExist(jsonParams)) != HC_SUCCESS) || + ((result = AssertUserIdExist(jsonParams)) != HC_SUCCESS) || + ((result = AssertSharedUserIdValid(jsonParams)) != HC_SUCCESS) || + ((result = AssertIdenticalGroupExist(osAccountId, jsonParams)) != HC_SUCCESS)) { + return result; + } + return HC_SUCCESS; +} + +static int32_t GenerateAddTokenParams(const CJson *deviceInfo, CJson *addParams) +{ + const char *userId = GetStringFromJson(deviceInfo, FIELD_USER_ID); + if (userId == NULL) { + LOGE("Failed to get userId from json!"); + return HC_ERR_JSON_GET; + } + const char *deviceId = GetStringFromJson(deviceInfo, FIELD_DEVICE_ID); + if (deviceId == NULL) { + LOGE("Failed to get deviceId from json!"); + return HC_ERR_JSON_GET; + } + if (AddStringToJson(addParams, FIELD_DEVICE_ID, deviceId) != HC_SUCCESS) { + LOGE("Failed to add deviceId to json!"); + return HC_ERR_JSON_ADD; + } + if (AddStringToJson(addParams, FIELD_USER_ID, userId) != HC_SUCCESS) { + LOGE("Failed to add userId to json!"); + return HC_ERR_JSON_ADD; + } + return HC_SUCCESS; +} + +static int32_t GenerateDelTokenParams(const TrustedDeviceEntry *entry, CJson *delParams) +{ + if (AddIntToJson(delParams, FIELD_CREDENTIAL_TYPE, (int32_t)entry->credential) != HC_SUCCESS) { + LOGE("Failed to add credentialType to json!"); + return HC_ERR_JSON_ADD; + } + if (AddStringToJson(delParams, FIELD_USER_ID, StringGet(&entry->userId)) != HC_SUCCESS) { + LOGE("Failed to add userId to json!"); + return HC_ERR_JSON_ADD; + } + if (AddStringToJson(delParams, FIELD_DEVICE_ID, StringGet(&entry->authId)) != HC_SUCCESS) { + LOGE("Failed to add deviceId to json!"); + return HC_ERR_JSON_ADD; + } + return HC_SUCCESS; +} + +static int32_t DelPeerDeviceToken(int32_t osAccountId, const TrustedDeviceEntry *entry) +{ + CJson *delParams = CreateJson(); + if (delParams == NULL) { + LOGE("Failed to allocate delParams memory!"); + return HC_ERR_ALLOC_MEMORY; + } + int32_t res = GenerateDelTokenParams(entry, delParams); + if (res != HC_SUCCESS) { + FreeJson(delParams); + return res; + } + res = ProcCred(ACCOUNT_RELATED_PLUGIN, osAccountId, DELETE_TRUSTED_CREDENTIALS, delParams, NULL); + FreeJson(delParams); + return res; +} + +static void DelAllPeerTokens(int32_t osAccountId, const DeviceEntryVec *vec) +{ + int32_t res; + uint32_t index; + TrustedDeviceEntry **entry = NULL; + FOR_EACH_HC_VECTOR(*vec, index, entry) { + if (IsLocalDevice(StringGet(&(*entry)->udid))) { + continue; + } + res = DelPeerDeviceToken(osAccountId, *entry); + if (res != HC_SUCCESS) { + LOGE("Failed to delete peer device token! res: %d", res); + } + } +} + +static int32_t DelGroupAndTokens(int32_t osAccountId, const char *groupId) +{ + DeviceEntryVec deviceList = CreateDeviceEntryVec(); + (void)GetTrustedDevices(osAccountId, groupId, &deviceList); + int32_t res = DelGroupFromDb(osAccountId, groupId); + DelAllPeerTokens(osAccountId, &deviceList); + ClearDeviceEntryVec(&deviceList); + return res; +} + +static int32_t CheckChangeParams(int32_t osAccountId, const char *appId, CJson *jsonParams) +{ + const char *groupId = GetStringFromJson(jsonParams, FIELD_GROUP_ID); + if (groupId == NULL) { + LOGE("Failed to get groupId from json!"); + return HC_ERR_JSON_GET; + } + int32_t groupType; + int32_t result; + if (((result = CheckGroupExist(osAccountId, groupId)) != HC_SUCCESS) || + ((result = GetGroupTypeFromDb(osAccountId, groupId, &groupType)) != HC_SUCCESS) || + ((result = AssertGroupTypeMatch(groupType, ACROSS_ACCOUNT_AUTHORIZE_GROUP)) != HC_SUCCESS) || + ((result = CheckGroupEditAllowed(osAccountId, groupId, appId)) != HC_SUCCESS)) { + return result; + } + return HC_SUCCESS; +} + +static int32_t DelDeviceById(int32_t osAccountId, const char *groupId, const char *deviceId, bool isUdid) +{ + QueryDeviceParams queryDeviceParams = InitQueryDeviceParams(); + queryDeviceParams.groupId = groupId; + if (isUdid) { + queryDeviceParams.udid = deviceId; + } else { + queryDeviceParams.authId = deviceId; + } + return DelTrustedDevice(osAccountId, &queryDeviceParams); +} + +static int32_t GenerateTrustedDevParams(const CJson *jsonParams, const char *groupId, TrustedDeviceEntry *devParams) +{ + int32_t result; + if (((result = AddUdidToParams(jsonParams, devParams)) != HC_SUCCESS) || + ((result = AddAuthIdToParams(jsonParams, devParams)) != HC_SUCCESS) || + ((result = AddCredTypeToParams(jsonParams, devParams)) != HC_SUCCESS) || + ((result = AddUserIdToDevParams(jsonParams, devParams)) != HC_SUCCESS) || + ((result = AddSourceToParams(IMPORTED_FROM_CLOUD, devParams)) != HC_SUCCESS) || + ((result = AddUserTypeToParamsOrDefault(jsonParams, devParams)) != HC_SUCCESS) || + ((result = AddGroupIdToDevParams(groupId, devParams)) != HC_SUCCESS) || + ((result = AddServiceTypeToParams(groupId, devParams)) != HC_SUCCESS)) { + return result; + } + return HC_SUCCESS; +} + +static int32_t CheckPeerDeviceNotSelf(const CJson *deviceInfo) +{ + const char *udid = GetStringFromJson(deviceInfo, FIELD_UDID); + if (udid == NULL) { + LOGE("Failed to get udid from json!"); + return HC_ERR_JSON_GET; + } + return AssertPeerDeviceNotSelf(udid); +} + +static int32_t AddDeviceAndToken(int32_t osAccountId, const CJson *jsonParams, CJson *deviceInfo) +{ + const char *groupId = GetStringFromJson(jsonParams, FIELD_GROUP_ID); + if (groupId == NULL) { + LOGE("Failed to get groupId from json!"); + return HC_ERR_JSON_GET; + } + CJson *credential = GetObjFromJson(deviceInfo, FIELD_CREDENTIAL); + if (credential == NULL) { + LOGE("Failed to get credential from json!"); + return HC_ERR_JSON_GET; + } + int32_t res = GenerateAddTokenParams(deviceInfo, credential); + if (res != HC_SUCCESS) { + return res; + } + res = ProcCred(ACCOUNT_RELATED_PLUGIN, osAccountId, IMPORT_TRUSTED_CREDENTIALS, credential, NULL); + if (res != HC_SUCCESS) { + LOGE("Failed to import device token! res: %d", res); + return res; + } + res = AddDeviceToDatabaseByJson(osAccountId, GenerateTrustedDevParams, deviceInfo, groupId); + if (res != HC_SUCCESS) { + LOGE("Failed to add device to database! res: %d", res); + } + return res; +} + +static int32_t DelPeerDeviceAndToken(int32_t osAccountId, CJson *jsonParams, CJson *deviceInfo) +{ + const char *groupId = GetStringFromJson(jsonParams, FIELD_GROUP_ID); + if (groupId == NULL) { + LOGE("Failed to get groupId from json!"); + return HC_ERR_JSON_GET; + } + const char *deviceId = GetStringFromJson(deviceInfo, FIELD_DEVICE_ID); + if (deviceId == NULL) { + LOGE("Failed to get deviceId from json!"); + return HC_ERR_JSON_GET; + } + TrustedDeviceEntry *entry = GetTrustedDeviceEntryById(osAccountId, deviceId, false, groupId); + if (entry == NULL) { + LOGE("Failed to get device from db!"); + return HC_ERR_DEVICE_NOT_EXIST; + } + if (IsLocalDevice(StringGet(&entry->udid))) { + LOGE("Do not delete the local device!"); + DestroyDeviceEntry(entry); + return HC_ERR_INVALID_PARAMS; + } + int32_t res = DelDeviceById(osAccountId, groupId, deviceId, false); + if (res != HC_SUCCESS) { + LOGE("Failed to delete device from database! res: %d", res); + DestroyDeviceEntry(entry); + return res; + } + res = DelPeerDeviceToken(osAccountId, entry); + DestroyDeviceEntry(entry); + if (res != HC_SUCCESS) { + LOGE("Failed to delete token! res: %d", res); + } + return res; +} + +static int32_t AddGroupAndLocalDev(int32_t osAccountId, CJson *jsonParams, const char *groupId) +{ + int32_t res = AddGroupToDatabaseByJson(osAccountId, GenerateGroupParams, jsonParams, groupId); + if (res != HC_SUCCESS) { + LOGE("Failed to add group to database!"); + return res; + } + res = AddDeviceToDatabaseByJson(osAccountId, GenerateDevParams, jsonParams, groupId); + if (res != HC_SUCCESS) { + LOGE("Failed to add device to database!"); + (void)DelGroupFromDb(osAccountId, groupId); + return res; + } + res = SaveOsAccountDb(osAccountId); + if (res != HC_SUCCESS) { + LOGE("Failed to save database!"); + (void)DelGroupFromDb(osAccountId, groupId); + } + return res; +} + +static int32_t CheckUserIdValid(int32_t osAccountId, const CJson *jsonParams, const CJson *deviceInfo) +{ + const char *userId = GetStringFromJson(deviceInfo, FIELD_USER_ID); + if (userId == NULL) { + LOGE("Failed to get userId from json!"); + return HC_ERR_JSON_GET; + } + const char *groupId = GetStringFromJson(jsonParams, FIELD_GROUP_ID); + if (groupId == NULL) { + LOGE("Failed to get groupId from json!"); + return HC_ERR_JSON_GET; + } + uint32_t index; + TrustedGroupEntry **entry = NULL; + GroupEntryVec groupEntryVec = CreateGroupEntryVec(); + QueryGroupParams params = InitQueryGroupParams(); + params.groupId = groupId; + params.groupType = ACROSS_ACCOUNT_AUTHORIZE_GROUP; + if (QueryGroups(osAccountId, ¶ms, &groupEntryVec) != HC_SUCCESS) { + LOGE("Failed to query groups!"); + ClearGroupEntryVec(&groupEntryVec); + return HC_ERR_DB; + } + FOR_EACH_HC_VECTOR(groupEntryVec, index, entry) { + if (strcmp(userId, StringGet(&(*entry)->sharedUserId)) == 0) { + ClearGroupEntryVec(&groupEntryVec); + return HC_SUCCESS; + } + } + LOGE("The input userId is inconsistent with the sharedUserId!"); + ClearGroupEntryVec(&groupEntryVec); + return HC_ERR_INVALID_PARAMS; +} + +static int32_t CheckDeviceInfoValid(int32_t osAccountId, const CJson *jsonParams, const CJson *deviceInfo) +{ + int32_t res = CheckPeerDeviceNotSelf(deviceInfo); + if (res != HC_SUCCESS) { + LOGE("The peer device udid is equals to the local udid!"); + return res; + } + /* Across account group: input userId must be consistent with the sharedUserId. */ + return CheckUserIdValid(osAccountId, jsonParams, deviceInfo); +} + +static int32_t CreateGroup(int32_t osAccountId, CJson *jsonParams, char **returnJsonStr) +{ + LOGI("[Start]: Start to create a across account group!"); + if ((jsonParams == NULL) || (returnJsonStr == NULL)) { + LOGE("The input parameters contains NULL value!"); + return HC_ERR_INVALID_PARAMS; + } + char *groupId = NULL; + int32_t result; + if (((result = CheckCreateParams(osAccountId, jsonParams)) != HC_SUCCESS) || + ((result = GenerateAcrossAccountGroupId(jsonParams, &groupId)) != HC_SUCCESS) || + ((result = AssertSameGroupNotExist(osAccountId, groupId)) != HC_SUCCESS) || + ((result = AddCredTypeToParamsFromIdenticalGroup(osAccountId, jsonParams)) != HC_SUCCESS) || + ((result = AddGroupAndLocalDev(osAccountId, jsonParams, groupId)) != HC_SUCCESS) || + ((result = ConvertGroupIdToJsonStr(groupId, returnJsonStr)) != HC_SUCCESS)) { + HcFree(groupId); + return result; + } + HcFree(groupId); + LOGI("[End]: Create a across account group successfully!"); + return HC_SUCCESS; +} + +static int32_t DeleteGroup(int32_t osAccountId, CJson *jsonParams, char **returnJsonStr) +{ + LOGI("[Start]: Start to delete a across account group!"); + if ((jsonParams == NULL) || (returnJsonStr == NULL)) { + LOGE("The input parameters contains NULL value!"); + return HC_ERR_INVALID_PARAMS; + } + int32_t result; + const char *groupId = NULL; + if (((result = GetGroupIdFromJson(jsonParams, &groupId)) != HC_SUCCESS) || + ((result = DelGroupAndTokens(osAccountId, groupId)) != HC_SUCCESS) || + ((result = ConvertGroupIdToJsonStr(groupId, returnJsonStr)) != HC_SUCCESS)) { + return result; + } + LOGI("[End]: Delete a across account group successfully!"); + return HC_SUCCESS; +} + +static int32_t AddMultiMembersToGroup(int32_t osAccountId, const char *appId, CJson *jsonParams) +{ + LOGI("[Start]: Start to add multiple members to a across account group!"); + if ((appId == NULL) || (jsonParams == NULL)) { + LOGE("Invalid params!"); + return HC_ERR_INVALID_PARAMS; + } + int32_t res = CheckChangeParams(osAccountId, appId, jsonParams); + if (res != HC_SUCCESS) { + return res; + } + CJson *deviceList = GetObjFromJson(jsonParams, FIELD_DEVICE_LIST); + if (deviceList == NULL) { + LOGE("Failed to get deviceList from json!"); + return HC_ERR_JSON_GET; + } + int32_t deviceNum = GetItemNum(deviceList); + int32_t addedCount = 0; + for (int32_t i = 0; i < deviceNum; i++) { + CJson *deviceInfo = GetItemFromArray(deviceList, i); + if (deviceInfo == NULL) { + LOGE("The deviceInfo is NULL!"); + continue; + } + if (CheckDeviceInfoValid(osAccountId, jsonParams, deviceInfo) != HC_SUCCESS) { + continue; + } + if (AddDeviceAndToken(osAccountId, jsonParams, deviceInfo) == HC_SUCCESS) { + addedCount++; + } + } + res = SaveOsAccountDb(osAccountId); + if (res != HC_SUCCESS) { + LOGE("Failed to save database!"); + return res; + } + LOGI("[End]: Add multiple members to a across account group successfully! [ListNum]: %d, [AddedNum]: %d", + deviceNum, addedCount); + return HC_SUCCESS; +} + +static int32_t DelMultiMembersFromGroup(int32_t osAccountId, const char *appId, CJson *jsonParams) +{ + LOGI("[Start]: Start to delete multiple members from a across account group!"); + if ((appId == NULL) || (jsonParams == NULL)) { + LOGE("Invalid params!"); + return HC_ERR_INVALID_PARAMS; + } + int32_t res = CheckChangeParams(osAccountId, appId, jsonParams); + if (res != HC_SUCCESS) { + return res; + } + CJson *deviceList = GetObjFromJson(jsonParams, FIELD_DEVICE_LIST); + if (deviceList == NULL) { + LOGE("Failed to get deviceList from json!"); + return HC_ERR_JSON_GET; + } + int32_t deviceNum = GetItemNum(deviceList); + int32_t deletedCount = 0; + for (int32_t i = 0; i < deviceNum; i++) { + CJson *deviceInfo = GetItemFromArray(deviceList, i); + if (deviceInfo == NULL) { + LOGE("The deviceInfo is NULL!"); + continue; + } + if (DelPeerDeviceAndToken(osAccountId, jsonParams, deviceInfo) == HC_SUCCESS) { + deletedCount++; + } + } + res = SaveOsAccountDb(osAccountId); + if (res != HC_SUCCESS) { + LOGE("Failed to save database!"); + return res; + } + LOGI("[End]: Delete multiple members from a across account group successfully! [ListNum]: %d, [DeletedNum]: %d", + deviceNum, deletedCount); + return HC_SUCCESS; +} + +static AcrossAccountGroup g_acrossAccountGroup = { + .base.type = ACROSS_ACCOUNT_AUTHORIZE_GROUP, + .base.createGroup = CreateGroup, + .base.deleteGroup = DeleteGroup, + .addMultiMembersToGroup = AddMultiMembersToGroup, + .delMultiMembersFromGroup = DelMultiMembersFromGroup, +}; + +BaseGroup *GetAcrossAccountGroupInstance(void) +{ + return (BaseGroup *)&g_acrossAccountGroup; +} + +bool IsAcrossAccountGroupSupported(void) +{ + return true; +} diff --git a/services/group_manager/src/group_operation/across_account_group_mock/across_account_group_mock.c b/services/legacy/group_manager/src/group_operation/across_account_group_mock/across_account_group_mock.c similarity index 100% rename from services/group_manager/src/group_operation/across_account_group_mock/across_account_group_mock.c rename to services/legacy/group_manager/src/group_operation/across_account_group_mock/across_account_group_mock.c diff --git a/services/group_manager/src/group_operation/group_operation.c b/services/legacy/group_manager/src/group_operation/group_operation.c similarity index 100% rename from services/group_manager/src/group_operation/group_operation.c rename to services/legacy/group_manager/src/group_operation/group_operation.c diff --git a/services/group_manager/src/group_operation/group_operation_common.c b/services/legacy/group_manager/src/group_operation/group_operation_common.c similarity index 100% rename from services/group_manager/src/group_operation/group_operation_common.c rename to services/legacy/group_manager/src/group_operation/group_operation_common.c diff --git a/services/group_manager/src/group_operation/identical_account_group/identical_account_group.c b/services/legacy/group_manager/src/group_operation/identical_account_group/identical_account_group.c similarity index 100% rename from services/group_manager/src/group_operation/identical_account_group/identical_account_group.c rename to services/legacy/group_manager/src/group_operation/identical_account_group/identical_account_group.c diff --git a/services/group_manager/src/group_operation/identical_account_group_mock/identical_account_group_mock.c b/services/legacy/group_manager/src/group_operation/identical_account_group_mock/identical_account_group_mock.c similarity index 100% rename from services/group_manager/src/group_operation/identical_account_group_mock/identical_account_group_mock.c rename to services/legacy/group_manager/src/group_operation/identical_account_group_mock/identical_account_group_mock.c diff --git a/services/group_manager/src/group_operation/peer_to_peer_group/peer_to_peer_group.c b/services/legacy/group_manager/src/group_operation/peer_to_peer_group/peer_to_peer_group.c similarity index 100% rename from services/group_manager/src/group_operation/peer_to_peer_group/peer_to_peer_group.c rename to services/legacy/group_manager/src/group_operation/peer_to_peer_group/peer_to_peer_group.c diff --git a/services/group_manager/src/group_operation/peer_to_peer_group_mock/peer_to_peer_group_mock.c b/services/legacy/group_manager/src/group_operation/peer_to_peer_group_mock/peer_to_peer_group_mock.c similarity index 100% rename from services/group_manager/src/group_operation/peer_to_peer_group_mock/peer_to_peer_group_mock.c rename to services/legacy/group_manager/src/group_operation/peer_to_peer_group_mock/peer_to_peer_group_mock.c diff --git a/services/session_manager/inc/session/dev_session_def.h b/services/session_manager/inc/session/dev_session_def.h index ced1dad6..a7350aea 100644 --- a/services/session_manager/inc/session/dev_session_def.h +++ b/services/session_manager/inc/session/dev_session_def.h @@ -19,7 +19,7 @@ #include "auth_sub_session.h" #include "compatible_sub_session.h" #include "expand_sub_session.h" -#include "creds_manager_defines.h" +#include "identity_defines.h" #include "dev_session_fwk.h" #include "hc_vector.h" diff --git a/services/session_manager/inc/session/v2/dev_session_util.h b/services/session_manager/inc/session/v2/dev_session_util.h index 12989413..c78daf05 100644 --- a/services/session_manager/inc/session/v2/dev_session_util.h +++ b/services/session_manager/inc/session/v2/dev_session_util.h @@ -16,7 +16,7 @@ #ifndef DEV_SESSION_UTIL_H #define DEV_SESSION_UTIL_H -#include "creds_manager_defines.h" +#include "identity_defines.h" #include "data_manager.h" #include "json_utils.h" diff --git a/services/session_manager/src/session/dev_session_fwk.c b/services/session_manager/src/session/dev_session_fwk.c index b9d6b7c6..5d8f8a4e 100644 --- a/services/session_manager/src/session/dev_session_fwk.c +++ b/services/session_manager/src/session/dev_session_fwk.c @@ -20,11 +20,11 @@ #include "alg_loader.h" #include "callback_manager.h" #include "channel_manager.h" +#include "identity_common.h" #include "common_defs.h" #include "compatible_sub_session.h" #include "compatible_bind_sub_session_util.h" #include "compatible_auth_sub_session_util.h" -#include "creds_operation_utils.h" #include "data_manager.h" #include "dev_session_v2.h" #include "hc_dev_info.h" @@ -40,12 +40,18 @@ static int32_t StartV1Session(SessionImpl *impl, CJson **sendMsg) { bool isBind = true; + bool isDeviceLevel = false; (void)GetBoolFromJson(impl->context, FIELD_IS_BIND, &isBind); + (void)GetBoolFromJson(impl->context, FIELD_IS_DEVICE_LEVEL, &isDeviceLevel); SubSessionTypeValue subSessionType = isBind ? TYPE_CLIENT_BIND_SUB_SESSION : TYPE_CLIENT_AUTH_SUB_SESSION; int32_t res = CreateCompatibleSubSession(subSessionType, impl->context, &impl->base.callback, &impl->compatibleSubSession); if (res != HC_SUCCESS) { - LOGE("create compatibleSubSession fail. [Res]: %d", res); + if (isDeviceLevel && res == HC_ERR_NO_CANDIDATE_GROUP) { + LOGI("create compatibleSubSession fail. no candidate group"); + } else { + LOGE("create compatibleSubSession fail. [Res]: %d", res); + } return res; } int32_t status; @@ -224,10 +230,24 @@ static int32_t StartSession(DevSession *self) int32_t res; do { CJson *sendMsg = NULL; - res = StartV1Session(impl, &sendMsg); - if (res != HC_SUCCESS) { - LOGE("start v1 session event fail."); - break; + /* auth with credentials directly no need to start the v1 session. */ + bool isDirectAuth = false; + bool isDeviceLevel = false; + (void)GetBoolFromJson(impl->context, FIELD_IS_DIRECT_AUTH, &isDirectAuth); + if (!isDirectAuth) { + (void)GetBoolFromJson(impl->context, FIELD_IS_DEVICE_LEVEL, &isDeviceLevel); + res = StartV1Session(impl, &sendMsg); + if ((res != HC_SUCCESS) + && (res != HC_ERR_NO_CANDIDATE_GROUP || !isDeviceLevel)) { + // if it's device level auth and no group founded, + // we also need try auth with credentails directly. + LOGE("start v1 session event fail."); + break; + } + } + if (sendMsg == NULL && (sendMsg = CreateJson()) == NULL) { + LOGE("allocate sendMsg fail."); + return HC_ERR_ALLOC_MEMORY; } if (IsSupportSessionV2()) { res = StartV2Session(impl, sendMsg); diff --git a/services/session_manager/src/session/v1/compatible_auth_sub_session/compatible_auth_sub_session.c b/services/session_manager/src/session/v1/compatible_auth_sub_session/compatible_auth_sub_session.c index 39ece3c4..affcfd2e 100644 --- a/services/session_manager/src/session/v1/compatible_auth_sub_session/compatible_auth_sub_session.c +++ b/services/session_manager/src/session/v1/compatible_auth_sub_session/compatible_auth_sub_session.c @@ -44,7 +44,7 @@ static int32_t CreateClientAuthSubSessionInner(int32_t osAccountId, CJson *jsonP CreateAuthParamsList(&authParamsVec); int32_t res = GetAuthParamsVec(osAccountId, jsonParams, &authParamsVec); if (res != HC_SUCCESS) { - LOGE("Failed to get auth param list!"); + LOGW("Failed to get auth param list!"); DestroyAuthParamsList(&authParamsVec); return res; } diff --git a/services/session_manager/src/session/v1/compatible_auth_sub_session/compatible_auth_sub_session_common.c b/services/session_manager/src/session/v1/compatible_auth_sub_session/compatible_auth_sub_session_common.c index bf6c675a..b486cc79 100644 --- a/services/session_manager/src/session/v1/compatible_auth_sub_session/compatible_auth_sub_session_common.c +++ b/services/session_manager/src/session/v1/compatible_auth_sub_session/compatible_auth_sub_session_common.c @@ -227,7 +227,7 @@ static int32_t GetCandidateAuthInfo(int32_t osAccountId, const char *groupId, GetGroupInfoByGroupId(osAccountId, groupId, &vec); } if (vec.size(&vec) == 0) { - LOGE("No satisfied candidate group!"); + LOGW("No satisfied candidate group!"); ClearGroupEntryVec(&vec); return HC_ERR_NO_CANDIDATE_GROUP; } diff --git a/services/session_manager/src/session/v2/dev_session_util.c b/services/session_manager/src/session/v2/dev_session_util.c index 57f0b45e..d0525b54 100644 --- a/services/session_manager/src/session/v2/dev_session_util.c +++ b/services/session_manager/src/session/v2/dev_session_util.c @@ -298,6 +298,12 @@ int32_t SetPeerAuthIdToContextIfNeeded(CJson *context, const IdentityInfo *info) LOGI("Not p2p auth, no need to set peer authId!"); return HC_SUCCESS; } + /* auth with credentials directly no need set peer auth id here */ + bool isDirectAuth = false; + (void)GetBoolFromJson(context, FIELD_IS_DIRECT_AUTH, &isDirectAuth); + if (isDirectAuth) { + return HC_SUCCESS; + } CJson *urlJson = CreateJsonFromString((const char *)info->proof.preSharedUrl.val); if (urlJson == NULL) { LOGE("Failed to create urlJson!"); diff --git a/services/session_manager/src/session/v2/dev_session_v2.c b/services/session_manager/src/session/v2/dev_session_v2.c index 82d16e7e..095ae36f 100644 --- a/services/session_manager/src/session/v2/dev_session_v2.c +++ b/services/session_manager/src/session/v2/dev_session_v2.c @@ -22,7 +22,6 @@ #include "channel_manager.h" #include "common_defs.h" #include "creds_manager.h" -#include "creds_operation_utils.h" #include "data_manager.h" #include "dev_session_util.h" #include "hc_dev_info.h" @@ -508,6 +507,19 @@ static int32_t GetPreSharedCredInfo(SessionImpl *impl, const CJson *credInfo, Id LOGE("get preSharedUrl from json fail."); return HC_ERR_JSON_GET; } + CJson *urlJson = CreateJsonFromString(preSharedUrl); + if (urlJson == NULL) { + LOGE("Failed to create url json!"); + return HC_ERR_JSON_FAIL; + } + bool isDirectAuth = false; + (void)GetBoolFromJson(urlJson, FIELD_IS_DIRECT_AUTH, &isDirectAuth); + if (AddBoolToJson(impl->context, FIELD_IS_DIRECT_AUTH, isDirectAuth) != HC_SUCCESS) { + LOGE("Faild to add isDirectAuth to context"); + FreeJson(urlJson); + return HC_ERR_JSON_ADD; + } + FreeJson(urlJson); Uint8Buff peerSharedUrl = { (uint8_t *)preSharedUrl, HcStrlen(preSharedUrl) + 1 }; IdentityInfo *info; int32_t res = GetCredInfoByPeerUrl(impl->context, &peerSharedUrl, &info); @@ -714,6 +726,30 @@ static int32_t AddSessionInfoToEventData(SessionImpl *impl, CJson *eventData) return HC_SUCCESS; } +/** + * @brief auth with credentials directly no need for abilities negotiation of two devices, + * so we set support commands empty here. + * + * @param eventData + * @return int32_t + */ +static int32_t AddSupportCmdsForDirectAuth(CJson *eventData) +{ + // added empty spCmds array to eventData + CJson *supportCmds = CreateJsonArray(); + if (supportCmds == NULL) { + LOGE("allocate supportCmds memory fail."); + return HC_ERR_ALLOC_MEMORY; + } + if (AddObjToJson(eventData, FIELD_SP_CMDS, supportCmds) != HC_SUCCESS) { + LOGE("add supportCmds to json fail."); + FreeJson(supportCmds); + return HC_ERR_JSON_ADD; + } + FreeJson(supportCmds); + return HC_SUCCESS; +} + static int32_t AddSupportCmdsToEventData(CJson *eventData) { CJson *supportCmds = CreateJsonArray(); @@ -750,7 +786,14 @@ static int32_t GenerateHandshakeEventData(SessionImpl *impl, IdentityInfo *cred, if (res != HC_SUCCESS) { return res; } - return AddSupportCmdsToEventData(eventData); + bool isDirectAuth = false; + (void)GetBoolFromJson(impl->context, FIELD_IS_DIRECT_AUTH, &isDirectAuth); + if (isDirectAuth) { + return AddSupportCmdsForDirectAuth(eventData); + } else { + return AddSupportCmdsToEventData(eventData); + } + return HC_SUCCESS; } static int32_t SetAuthProtectedMsg(SessionImpl *impl, const CJson *msgJson, bool isSelf) @@ -1177,12 +1220,20 @@ static int32_t AddAuthInfoToContextByCred(SessionImpl *impl, IdentityInfo *cred) return res; } PRINT_SENSITIVE_DATA("SelfUdid", selfUdid); + bool isDirectAuth = false; + (void)GetBoolFromJson(impl->context, FIELD_IS_DIRECT_AUTH, &isDirectAuth); if (cred->proofType == CERTIFICATED) { if (AddStringToJson(impl->context, FIELD_AUTH_ID, selfUdid) != HC_SUCCESS) { LOGE("add selfAuthId to json fail."); return HC_ERR_ALLOC_MEMORY; } return AddAuthInfoToContextByCert(impl); + } else if (isDirectAuth) { // auth with credentials directly + if (AddStringToJson(impl->context, FIELD_AUTH_ID, selfUdid) != HC_SUCCESS) { + LOGE("add selfAuthId to json fail."); + return HC_ERR_ALLOC_MEMORY; + } + return HC_SUCCESS; } CJson *urlJson = CreateJsonFromString((const char *)cred->proof.preSharedUrl.val); if (urlJson == NULL) { @@ -1264,6 +1315,11 @@ static int32_t ProcStartEventInner(SessionImpl *impl, CJson *sessionMsg) } impl->credCurIndex += 1; IdentityInfo *curCred = HC_VECTOR_GET(&impl->credList, 0); + bool isDirectAuth = curCred->IdInfoType == P2P_DIRECT_AUTH ? true : false; + if (AddBoolToJson(impl->context, FIELD_IS_DIRECT_AUTH, isDirectAuth) != HC_SUCCESS) { + LOGE("Failed to add isDirectAuth to context!"); + return HC_ERR_JSON_ADD; + } res = ClientCreateAuthSubSessionByCred(impl, curCred); if (res != HC_SUCCESS) { return res; @@ -1272,7 +1328,8 @@ static int32_t ProcStartEventInner(SessionImpl *impl, CJson *sessionMsg) if (res != HC_SUCCESS) { return res; } - return AddAllAuthFirstMsg(impl, sessionMsg, IsP2pAuth(curCred)); + /* auth with credentail directly no need replace auth id with random number */ + return AddAllAuthFirstMsg(impl, sessionMsg, (IsP2pAuth(curCred) && !isDirectAuth)); } static int32_t GetSessionSaltFromInput(SessionImpl *impl, const CJson *inputData) @@ -1389,7 +1446,13 @@ static int32_t GenerateHandshakeRspEventData(SessionImpl *impl, IdentityInfo *se if (res != HC_SUCCESS) { return res; } - return AddSupportCmdsToEventData(eventData); + bool isDirectAuth = false; + (void)GetBoolFromJson(impl->context, FIELD_IS_DIRECT_AUTH, &isDirectAuth); + if (isDirectAuth) { + return AddSupportCmdsForDirectAuth(eventData); + } else { + return AddSupportCmdsToEventData(eventData); + } } static int32_t AddHandshakeRspMsg(SessionImpl *impl, IdentityInfo *selfCred, CJson *sessionMsg) @@ -1589,6 +1652,11 @@ static int32_t ProcHandshakeReqEventInner(SessionImpl *impl, SessionEvent *input } CheckAllCredsValidity(impl); IdentityInfo *selfCred = HC_VECTOR_GET(&impl->credList, 0); + bool isDirectAuth = selfCred->IdInfoType == P2P_DIRECT_AUTH ? true : false; + if (AddBoolToJson(impl->context, FIELD_IS_DIRECT_AUTH, isDirectAuth) != HC_SUCCESS) { + LOGE("Failed to add isDirectAuth to context!"); + return HC_ERR_JSON_ADD; + } res = SetPeerAuthIdToContextIfNeeded(impl->context, selfCred); if (res != HC_SUCCESS) { return res; @@ -1644,6 +1712,11 @@ static int32_t RemoveInvalidAuthSubSession(SessionImpl *impl) static int32_t ProcHandshakeRspEventInner(SessionImpl *impl, SessionEvent *inputEvent) { IdentityInfo *selfCred = impl->credList.get(&impl->credList, 0); + bool isDirectAuth = selfCred->IdInfoType == P2P_DIRECT_AUTH ? true : false; + if (AddBoolToJson(impl->context, FIELD_IS_DIRECT_AUTH, isDirectAuth) != HC_SUCCESS) { + LOGE("Failed to add isDirectAuth to context!"); + return HC_ERR_JSON_ADD; + } int32_t res = SetPeerAuthIdToContextIfNeeded(impl->context, selfCred); if (res != HC_SUCCESS) { return res; @@ -1772,7 +1845,14 @@ static int32_t ProcAuthEventInner(SessionImpl *impl, SessionEvent *inputEvent, C return HC_SUCCESS; } IdentityInfo *selfCred = HC_VECTOR_GET(&impl->credList, 0); - if (isServerProcess && IsP2pAuth(selfCred)) { + bool isDirectAuth = selfCred->IdInfoType == P2P_DIRECT_AUTH ? true : false; + if (AddBoolToJson(impl->context, FIELD_IS_DIRECT_AUTH, isDirectAuth) != HC_SUCCESS) { + LOGE("Failed to add isDirectAuth to context!"); + return HC_ERR_JSON_ADD; + } + bool isP2pAuth = IsP2pAuth(selfCred); + /* auth with credentail directly no need replace auth id with random number*/ + if (isServerProcess && isP2pAuth && !isDirectAuth) { res = ProcAuthSubSessionMsg(curAuthSubSession, inputEvent->data, sessionMsg, true); } else { res = ProcAuthSubSessionMsg(curAuthSubSession, inputEvent->data, sessionMsg, false); diff --git a/services/session_manager/src/session/v2/expand_sub_session/expand_process_lib/auth_code_import.c b/services/session_manager/src/session/v2/expand_sub_session/expand_process_lib/auth_code_import.c index 2ca87478..76de4f87 100644 --- a/services/session_manager/src/session/v2/expand_sub_session/expand_process_lib/auth_code_import.c +++ b/services/session_manager/src/session/v2/expand_sub_session/expand_process_lib/auth_code_import.c @@ -18,12 +18,7 @@ #include "alg_loader.h" #include "device_auth_defines.h" #include "hc_log.h" - -#define AUTH_CODE_LEN 32 -#define KEY_ALIAS_LEN 32 -#define KEY_ALIAS_AUTH_TOKEN 7 -#define KEY_TYPE_PAIR_LEN 2 -#define KEY_ALIAS_TYPE_END 8 +#include "identity_defines.h" #define START_CMD_EVENT_NAME "StartCmd" #define GEN_AUTH_CODE_EVENT_NAME "GenAuthCode" @@ -41,18 +36,6 @@ #define FIELD_ERR_CODE "errCode" #define FIELD_ERR_MSG "errMsg" -/* in order to expand to uint16_t */ -static const uint8_t KEY_TYPE_PAIRS[KEY_ALIAS_TYPE_END][KEY_TYPE_PAIR_LEN] = { - { 0x00, 0x00 }, /* ACCESSOR_PK */ - { 0x00, 0x01 }, /* CONTROLLER_PK */ - { 0x00, 0x02 }, /* ed25519 KEYPAIR */ - { 0x00, 0x03 }, /* KEK, key encryption key, used only by DeviceAuthService */ - { 0x00, 0x04 }, /* DEK, data encryption key, used only by upper apps */ - { 0x00, 0x05 }, /* key tmp */ - { 0x00, 0x06 }, /* PSK, preshared key index */ - { 0x00, 0x07 } /* AUTHTOKEN */ -}; - typedef struct { int32_t userTypeSelf; int32_t userTypePeer; @@ -179,7 +162,7 @@ static int32_t GenerateKeyAlias(const CmdParams *params, Uint8Buff *keyAlias) LOGE("CombineServiceId failed, res: %x.", res); return res; } - Uint8Buff keyTypeBuff = { (uint8_t *)KEY_TYPE_PAIRS[KEY_ALIAS_AUTH_TOKEN], KEY_TYPE_PAIR_LEN }; + Uint8Buff keyTypeBuff = { GetKeyTypePair(KEY_ALIAS_AUTH_TOKEN), KEY_TYPE_PAIR_LEN }; return CalKeyAlias(&serviceId, &keyTypeBuff, ¶ms->authIdPeer, keyAlias); } diff --git a/services/session_manager/src/session/v2/expand_sub_session/expand_process_lib/pub_key_exchange.c b/services/session_manager/src/session/v2/expand_sub_session/expand_process_lib/pub_key_exchange.c index e008cf1a..43523e1f 100644 --- a/services/session_manager/src/session/v2/expand_sub_session/expand_process_lib/pub_key_exchange.c +++ b/services/session_manager/src/session/v2/expand_sub_session/expand_process_lib/pub_key_exchange.c @@ -18,11 +18,7 @@ #include "alg_loader.h" #include "device_auth_defines.h" #include "hc_log.h" - -#define KEY_TYPE_PAIR_LEN 2 -#define PAKE_KEY_ALIAS_LEN 64 -#define PAKE_ED25519_KEY_PAIR_LEN 32 -#define PAKE_PSK_LEN 32 +#include "identity_defines.h" #define START_CMD_EVENT_NAME "StartCmd" #define FAIL_EVENT_NAME "CmdFail" @@ -38,31 +34,6 @@ #define FIELD_ERR_CODE "errCode" #define FIELD_ERR_MSG "errMsg" -typedef enum { - KEY_ALIAS_ACCESSOR_PK = 0, - KEY_ALIAS_CONTROLLER_PK = 1, - KEY_ALIAS_LT_KEY_PAIR = 2, - KEY_ALIAS_KEK = 3, - KEY_ALIAS_DEK = 4, - KEY_ALIAS_TMP = 5, - KEY_ALIAS_PSK = 6, - KEY_ALIAS_AUTH_TOKEN = 7, - - KEY_ALIAS_TYPE_END -} KeyAliasType; // 0 ~ 2^8-1, don't change the order - -/* in order to expand to uint16_t */ -static const uint8_t KEY_TYPE_PAIRS[KEY_ALIAS_TYPE_END][KEY_TYPE_PAIR_LEN] = { - { 0x00, 0x00 }, /* ACCESSOR_PK */ - { 0x00, 0x01 }, /* CONTROLLER_PK */ - { 0x00, 0x02 }, /* ed25519 KEYPAIR */ - { 0x00, 0x03 }, /* KEK, key encryption key, used only by DeviceAuthService */ - { 0x00, 0x04 }, /* DEK, data encryption key, used only by upper apps */ - { 0x00, 0x05 }, /* key tmp */ - { 0x00, 0x06 }, /* PSK, preshared key index */ - { 0x00, 0x07 } /* AUTHTOKEN */ -}; - typedef struct { int32_t userTypeSelf; int32_t userTypePeer; @@ -197,7 +168,7 @@ static int32_t GenerateKeyAlias(const CmdParams *params, bool isSelf, bool isPsk int32_t userType = isSelf ? params->userTypeSelf : params->userTypePeer; #endif KeyAliasType keyAliasType = isPsk ? KEY_ALIAS_PSK : userType; - Uint8Buff keyTypeBuff = { (uint8_t *)KEY_TYPE_PAIRS[keyAliasType], KEY_TYPE_PAIR_LEN }; + Uint8Buff keyTypeBuff = { GetKeyTypePair(keyAliasType), KEY_TYPE_PAIR_LEN }; uint8_t keyAliasByteVal[SHA256_LEN] = { 0 }; Uint8Buff keyAliasByte = { keyAliasByteVal, SHA256_LEN }; res = CalKeyAlias(&serviceId, &keyTypeBuff, authId, &keyAliasByte); diff --git a/test/unittest/deviceauth/BUILD.gn b/test/unittest/deviceauth/BUILD.gn index 4a28bb52..b3a7df21 100644 --- a/test/unittest/deviceauth/BUILD.gn +++ b/test/unittest/deviceauth/BUILD.gn @@ -84,6 +84,9 @@ ohos_unittest("deviceauth_llt") { sources += security_label_adapter_files + include_dirs += identity_manager_inc + sources += identity_manager_files + sources -= [ "${authenticators_path}/src/account_unrelated/iso_task/iso_task_main.c", "${authenticators_path}/src/account_unrelated/pake_task/pake_v1_task/pake_v1_task_main.c", @@ -245,6 +248,10 @@ ohos_unittest("device_auth_func_test") { "ENABLE_PSEUDONYM", ] + sources += identity_manager_files + include_dirs += identity_manager_inc + sources += [ "source/deviceauth_func_test.cpp" ] + cflags = [ "-DHILOG_ENABLE" ] cflags += [ "-DDEV_AUTH_WORK_THREAD_STACK_SIZE=${deviceauth_hichain_thread_stack_size}", @@ -303,6 +310,8 @@ ohos_unittest("deviceauth_unit_test") { "source/hc_dev_info_mock.c", ] + include_dirs += identity_manager_inc + sources += identity_manager_files sources += dev_frameworks_files sources += deviceauth_common_files sources += database_manager_files @@ -343,10 +352,10 @@ ohos_unittest("deviceauth_unit_test") { ] sources -= [ - "//base/security/device_auth/services/authenticators/src/account_related/creds_manager/asy_token_manager.c", - "//base/security/device_auth/services/group_manager/src/group_operation/across_account_group/across_account_group.c", - "//base/security/device_auth/services/group_manager/src/group_operation/identical_account_group/identical_account_group.c", - "//base/security/device_auth/services/group_manager/src/group_operation/peer_to_peer_group/peer_to_peer_group.c", + "${authenticators_path}/src/account_related/creds_manager/asy_token_manager.c", + "${group_manager_path}/src/group_operation/across_account_group/across_account_group.c", + "${group_manager_path}/src/group_operation/identical_account_group/identical_account_group.c", + "${group_manager_path}/src/group_operation/peer_to_peer_group/peer_to_peer_group.c", ] sources += [ @@ -414,6 +423,8 @@ ohos_unittest("device_auth_ipc_test") { "//third_party/googletest:gtest_main", ] + cflags = [ "-DHILOG_ENABLE" ] + external_deps = [ "c_utils:utils", "device_auth:deviceauth_sdk", diff --git a/test/unittest/deviceauth/source/device_auth_ipc_test.cpp b/test/unittest/deviceauth/source/device_auth_ipc_test.cpp index c7545136..faaa74f3 100644 --- a/test/unittest/deviceauth/source/device_auth_ipc_test.cpp +++ b/test/unittest/deviceauth/source/device_auth_ipc_test.cpp @@ -23,6 +23,7 @@ #include "securec.h" #include "nativetoken_kit.h" #include "token_setproc.h" +#include "hc_dev_info.h" using namespace std; using namespace testing::ext; @@ -94,6 +95,18 @@ static const char *g_getRegisterInfoParams = "{\"version\":\"1.0.0\",\"deviceId\":\"TestAuthId\",\"userId\":" "\"4269DC28B639681698809A67EDAD08E39F207900038F91FEF95DD042FE2874E4\"}"; +static const char* g_authWithPinParams = "{\"osAccountId\":100,\"acquireType\":0,\"pinCode\":\"123456\"}"; + +static const char* g_authDirectParams = + "{\"osAccountId\":100,\"acquireType\":0,\"serviceType\":\"service.type.import\",\"peerConnDeviceId\":" + "\"52E2706717D5C39D736E134CC1E3BE1BAA2AA52DB7C76A37C" + "749558BD2E6492C\"}"; +#define FIELD_PUBLIC_KEY "publicKey" +#define FIELD_PIN_CODE "pinCode" +#define SERVICE_TYPE_IMPORT "service.type.import" +#define DEFAULT_SERVICE_TYPE "service.type.default" +static const int32_t TEST_AUTH_OS_ACCOUNT_ID = 100; + enum AsyncStatus { ASYNC_STATUS_WAITING = 0, ASYNC_STATUS_TRANSMIT = 1, @@ -190,6 +203,28 @@ static char *OnAuthRequest2(int64_t requestId, int operationCode, const char* re return returnDataStr; } +static char *OnAuthRequestDirectTmp(int64_t requestId, int operationCode, const char *reqParam) +{ + CJson *json = CreateJson(); + AddIntToJson(json, FIELD_CONFIRMATION, REQUEST_ACCEPTED); + AddStringToJson(json, FIELD_PIN_CODE, TEST_PIN_CODE); + AddStringToJson(json, FIELD_PEER_CONN_DEVICE_ID, TEST_UDID_CLIENT); + char *returnDataStr = PackJsonToString(json); + FreeJson(json); + return returnDataStr; +} + +static char *OnAuthRequestDirect(int64_t requestId, int operationCode, const char *reqParam) +{ + CJson *json = CreateJson(); + AddIntToJson(json, FIELD_CONFIRMATION, REQUEST_ACCEPTED); + AddStringToJson(json, FIELD_PEER_CONN_DEVICE_ID, TEST_UDID_CLIENT); + AddStringToJson(json, FIELD_SERVICE_TYPE, SERVICE_TYPE_IMPORT); + char *returnDataStr = PackJsonToString(json); + FreeJson(json); + return returnDataStr; +} + static DeviceAuthCallback g_gmCallback = { .onTransmit = OnTransmit, .onSessionKeyReturned = OnSessionKeyReturned, @@ -222,6 +257,22 @@ static DeviceAuthCallback g_gaCallback2 = { .onRequest = OnAuthRequest2 }; +static DeviceAuthCallback g_daTmpCallback = { + .onTransmit = OnTransmit, + .onSessionKeyReturned = OnSessionKeyReturned, + .onFinish = OnFinish, + .onError = OnError, + .onRequest = OnAuthRequestDirectTmp +}; + +static DeviceAuthCallback g_daLTCallback = { + .onTransmit = OnTransmit, + .onSessionKeyReturned = OnSessionKeyReturned, + .onFinish = OnFinish, + .onError = OnError, + .onRequest = OnAuthRequestDirect +}; + static void OnGroupCreated(const char *groupInfo) { (void)groupInfo; @@ -2182,4 +2233,349 @@ HWTEST_F(GaCancelRequestTest, GaCancelRequestTest002, TestSize.Level0) ASSERT_NE(ga, nullptr); ga->cancelRequest(TEST_REQ_ID, TEST_APP_ID); } + +static const char *CreateCredentialParam( + int32_t osAccountId, const char *deviceId, int32_t flag, const char *serviceType, const char *publicKey) +{ + CJson *json = CreateJson(); + + AddIntToJson(json, FIELD_OS_ACCOUNT_ID, osAccountId); + AddStringToJson(json, FIELD_DEVICE_ID, deviceId); + AddStringToJson(json, FIELD_SERVICE_TYPE, serviceType); + AddIntToJson(json, FIELD_ACQURIED_TYPE, P2P_BIND); + + if (flag >= 0) { + AddIntToJson(json, FIELD_CRED_OP_FLAG, flag); + } + + if (publicKey) { + AddStringToJson(json, FIELD_PUBLIC_KEY, publicKey); + } + + char *returnDataStr = PackJsonToString(json); + FreeJson(json); + return returnDataStr; +} + +static char *GetSelfUdid() +{ + printf("%s called.\n", __FUNCTION__); + char udid[INPUT_UDID_LEN] = { 0 }; + int32_t res = HcGetUdid((uint8_t *)udid, INPUT_UDID_LEN); + if (res != HC_SUCCESS) { + printf("Failed to get self udid! res: %d", res); + return nullptr; + } + + printf("self udid: %s\n", udid); + return strdup(udid); +} + +static int32_t CreateServerKeyPair() +{ + char *selfUdid = GetSelfUdid(); + const char *requestParams = + CreateCredentialParam(TEST_AUTH_OS_ACCOUNT_ID, selfUdid, RETURN_FLAG_PUBLIC_KEY, DEFAULT_SERVICE_TYPE, nullptr); + free(selfUdid); + char *returnData = nullptr; + + printf("ProcessCredentialDemo: operationCode=%d\n", CRED_OP_CREATE); + int32_t res = ProcessCredential(CRED_OP_CREATE, requestParams, &returnData); + + if (returnData) { + printf("returnData: %s\n", returnData); + CJson *in = CreateJsonFromString(returnData); + if (in == nullptr) { + printf("CreateJsonFromString returnData failed !\n"); + } else { + if (GetIntFromJson(in, FIELD_CRED_OP_RESULT, &res) != HC_SUCCESS) { + printf("GetIntFromJson result failed !\n"); + FreeJson(in); + return HC_ERR_INVALID_PARAMS; + } + printf("get result from returnData: %d\n", res); + return res; + } + } + + printf("returnData is null !\n"); + + return res; +} + +static int32_t DeleteServerKeyPair() +{ + char *selfUdid = GetSelfUdid(); + const char *requestParams = + CreateCredentialParam(TEST_AUTH_OS_ACCOUNT_ID, selfUdid, 1, DEFAULT_SERVICE_TYPE, nullptr); + free(selfUdid); + char *returnData = nullptr; + + printf("ProcessCredentialDemo: operationCode=%d\n", CRED_OP_DELETE); + int32_t res = ProcessCredential(CRED_OP_DELETE, requestParams, &returnData); + + if (returnData) { + printf("returnData: %s\n", returnData); + CJson *in = CreateJsonFromString(returnData); + if (in == nullptr) { + printf("CreateJsonFromString returnData failed !\n"); + } else { + if (GetIntFromJson(in, FIELD_CRED_OP_RESULT, &res) != HC_SUCCESS) { + printf("GetIntFromJson result failed !\n"); + FreeJson(in); + return HC_ERR_INVALID_PARAMS; + } + printf("get result from returnData: %d\n", res); + return res; + } + } + + printf("returnData is null !\n"); + + return res; +} + +static int32_t ProcessCredentialDemo(int operationCode, const char *serviceType) +{ + int32_t flag = -1; + if (operationCode == CRED_OP_CREATE || operationCode == CRED_OP_QUERY) { + flag = 1; + } + const char *requestParams = CreateCredentialParam(TEST_AUTH_OS_ACCOUNT_ID, TEST_UDID, flag, serviceType, nullptr); + char *returnData = nullptr; + + printf("ProcessCredentialDemo: operationCode=%d\n", operationCode); + int32_t res = ProcessCredential(operationCode, requestParams, &returnData); + + if (returnData) { + printf("returnData: %s\n", returnData); + CJson *in = CreateJsonFromString(returnData); + if (in == nullptr) { + printf("CreateJsonFromString returnData failed !\n"); + } else { + if (GetIntFromJson(in, FIELD_CRED_OP_RESULT, &res) != HC_SUCCESS) { + printf("GetIntFromJson result failed !\n"); + FreeJson(in); + return HC_ERR_INVALID_PARAMS; + } + printf("get result from returnData: %d\n", res); + return res; + } + } + + printf("returnData is null !\n"); + + return res; +} + +static int32_t ProcessCredentialDemoImport(const char *importServiceType) +{ + const char *requestParams = CreateCredentialParam(TEST_AUTH_OS_ACCOUNT_ID, TEST_UDID, -1, importServiceType, + "CA32A9DFACB944B1F6292C9AE10783F6376A987A9CE30C13300BC866917DFF2E"); + char *returnData = nullptr; + + printf("ProcessCredentialDemoImport\n"); + int32_t res = ProcessCredential(CRED_OP_IMPORT, requestParams, &returnData); + + if (returnData) { + CJson *in = CreateJsonFromString(returnData); + if (in == nullptr) { + printf("CreateJsonFromString returnData failed !\n"); + } else { + if (GetIntFromJson(in, FIELD_CRED_OP_RESULT, &res) != HC_SUCCESS) { + printf("GetIntFromJson result failed !\n"); + FreeJson(in); + return HC_ERR_INVALID_PARAMS; + } + printf("get result from returnData: %d\n", res); + return res; + } + } + + printf("returnData is null !\n"); + + return res; +} + +class DaAuthDeviceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void DaAuthDeviceTest::SetUpTestCase() {} + +void DaAuthDeviceTest::TearDownTestCase() {} + +void DaAuthDeviceTest::SetUp() +{ + NativeTokenSet(PROC_NAME_DEVICE_MANAGER); + int32_t ret = InitDeviceAuthService(); + ASSERT_EQ(ret, HC_SUCCESS); +} + +void DaAuthDeviceTest::TearDown() +{ + DestroyDeviceAuthService(); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest001, TestSize.Level0) +{ + int32_t res = StartAuthDevice(TEST_REQ_ID, g_authWithPinParams, &g_daTmpCallback); + ASSERT_EQ(res, HC_SUCCESS); + res = CancelAuthRequest(TEST_REQ_ID, g_authWithPinParams); + ASSERT_EQ(res, HC_SUCCESS); +} +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest002, TestSize.Level0) +{ + int32_t res = StartAuthDevice(TEST_REQ_ID, g_authDirectParams, &g_daLTCallback); + ASSERT_EQ(res, HC_SUCCESS); + res = CancelAuthRequest(TEST_REQ_ID, g_authDirectParams); + ASSERT_EQ(res, HC_SUCCESS); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest003, TestSize.Level0) +{ + int32_t res = ProcessCredentialDemo(CRED_OP_DELETE, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, DEFAULT_SERVICE_TYPE); + ASSERT_NE(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_CREATE, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_DELETE, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, DEFAULT_SERVICE_TYPE); + ASSERT_NE(res, HC_SUCCESS); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest004, TestSize.Level0) +{ + int32_t res = ProcessCredentialDemo(CRED_OP_CREATE, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_DELETE, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, DEFAULT_SERVICE_TYPE); + ASSERT_NE(res, HC_SUCCESS); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest005, TestSize.Level0) +{ + int32_t res = CreateServerKeyPair(); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemoImport(SERVICE_TYPE_IMPORT); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, SERVICE_TYPE_IMPORT); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_DELETE, SERVICE_TYPE_IMPORT); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, SERVICE_TYPE_IMPORT); + ASSERT_NE(res, HC_SUCCESS); + res = DeleteServerKeyPair(); + ASSERT_EQ(res, HC_SUCCESS); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest006, TestSize.Level0) +{ + int32_t res = CreateServerKeyPair(); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemoImport(SERVICE_TYPE_IMPORT); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemoImport(SERVICE_TYPE_IMPORT); + ASSERT_NE(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, SERVICE_TYPE_IMPORT); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_DELETE, SERVICE_TYPE_IMPORT); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, SERVICE_TYPE_IMPORT); + ASSERT_NE(res, HC_SUCCESS); + res = DeleteServerKeyPair(); + ASSERT_EQ(res, HC_SUCCESS); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest007, TestSize.Level0) +{ + int32_t res = ProcessCredentialDemo(CRED_OP_CREATE, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_CREATE, DEFAULT_SERVICE_TYPE); + ASSERT_NE(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_DELETE, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, DEFAULT_SERVICE_TYPE); + ASSERT_NE(res, HC_SUCCESS); +} + +class ApiAccessBlockTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void ApiAccessBlockTest::SetUpTestCase() {} + +void ApiAccessBlockTest::TearDownTestCase() {} + +void ApiAccessBlockTest::SetUp() +{ + NativeTokenSet(TEST_APP_ID2); + int32_t ret = InitDeviceAuthService(); + ASSERT_EQ(ret, HC_SUCCESS); +} + +void ApiAccessBlockTest::TearDown() +{ + DestroyDeviceAuthService(); +} + +HWTEST_F(ApiAccessBlockTest, ApiAccessBlockTest001, TestSize.Level0) +{ + int32_t res = ProcessCredentialDemo(CRED_OP_CREATE, DEFAULT_SERVICE_TYPE); + ASSERT_NE(res, HC_SUCCESS); +} + +class ApiAccessPassTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void ApiAccessPassTest::SetUpTestCase() {} + +void ApiAccessPassTest::TearDownTestCase() {} + +void ApiAccessPassTest::SetUp() +{ + NativeTokenSet(PROC_NAME_DEVICE_MANAGER); + int32_t ret = InitDeviceAuthService(); + ASSERT_EQ(ret, HC_SUCCESS); +} + +void ApiAccessPassTest::TearDown() +{ + DestroyDeviceAuthService(); +} + +HWTEST_F(ApiAccessPassTest, ApiAccessPassTest001, TestSize.Level0) +{ + int32_t res = ProcessCredentialDemo(CRED_OP_CREATE, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_DELETE, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, DEFAULT_SERVICE_TYPE); + ASSERT_NE(res, HC_SUCCESS); +} + } diff --git a/test/unittest/deviceauth/source/deviceauth_func_test.cpp b/test/unittest/deviceauth/source/deviceauth_func_test.cpp new file mode 100644 index 00000000..e9898583 --- /dev/null +++ b/test/unittest/deviceauth/source/deviceauth_func_test.cpp @@ -0,0 +1,889 @@ +/* + * Copyright (C) 2021-2022 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 +#include + +#include "account_module_defines.h" +#include "alg_loader.h" +#include "common_defs.h" +#include "creds_manager.h" +#include "device_auth.h" +#include "device_auth_defines.h" +#include "device_auth_ext.h" +#include "deviceauth_standard_test.h" +#include "hc_dev_info_mock.h" +#include "json_utils.h" +#include "json_utils_mock.h" +#include "protocol_task_main_mock.h" +#include "securec.h" + +using namespace std; +using namespace testing::ext; + +namespace { +#define TEST_REQ_ID 123 +#define TEST_REQ_ID2 321 +#define TEST_APP_ID "TestAppId" +#define TEST_UDID "TestUdid" +#define TEST_UDID_CLIENT "5420459D93FE773F9945FD64277FBA2CAB8FB996DDC1D0B97676FBB1242B3930" +#define TEST_UDID_SERVER "52E2706717D5C39D736E134CC1E3BE1BAA2AA52DB7C76A37C749558BD2E6492C" +#define TEST_PIN_CODE "123456" +#define TEST_DEV_AUTH_SLEEP_TIME 50000 +static const int32_t TEST_AUTH_OS_ACCOUNT_ID = 100; + +static const char *g_authWithPinParams = "{\"osAccountId\":100,\"acquireType\":0,\"pinCode\":\"123456\"}"; + +static const char *g_authDirectParams = + "{\"osAccountId\":100,\"acquireType\":0,\"serviceType\":\"service.type.import\",\"peerConnDeviceId\":" + "\"52E2706717D5C39D736E134CC1E3BE1BAA2AA52DB7C76A37C" + "749558BD2E6492C\"}"; + +static const char *g_deviceLevelAuthParams = + "{\"peerConnDeviceId\":\"52E2706717D5C39D736E134CC1E3BE1BAA2AA52DB7C76A37C" + "749558BD2E6492C\",\"servicePkgName\":\"TestAppId\",\"isClient\":true, \"isDeviceLevel\":true}"; + +enum AsyncStatus { + ASYNC_STATUS_WAITING = 0, + ASYNC_STATUS_TRANSMIT = 1, + ASYNC_STATUS_FINISH = 2, + ASYNC_STATUS_ERROR = 3 +}; + +static AsyncStatus volatile g_asyncStatus; +static uint32_t g_transmitDataMaxLen = 2048; +static uint8_t g_transmitData[2048] = { 0 }; +static uint32_t g_transmitDataLen = 0; + +static bool OnTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) +{ + if (memcpy_s(g_transmitData, g_transmitDataMaxLen, data, dataLen) != EOK) { + return false; + } + g_transmitDataLen = dataLen; + g_asyncStatus = ASYNC_STATUS_TRANSMIT; + return true; +} + +static void OnSessionKeyReturned(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) +{ + (void)requestId; + (void)sessionKey; + (void)sessionKeyLen; + return; +} + +static void OnFinish(int64_t requestId, int operationCode, const char *authReturn) +{ + g_asyncStatus = ASYNC_STATUS_FINISH; +} + +static void OnError(int64_t requestId, int operationCode, int errorCode, const char *errorReturn) +{ + g_asyncStatus = ASYNC_STATUS_ERROR; +} + +static char *OnAuthRequest(int64_t requestId, int operationCode, const char *reqParam) +{ + CJson *json = CreateJson(); + AddIntToJson(json, FIELD_CONFIRMATION, REQUEST_ACCEPTED); + AddIntToJson(json, FIELD_OS_ACCOUNT_ID, TEST_AUTH_OS_ACCOUNT_ID); + AddStringToJson(json, FIELD_PEER_CONN_DEVICE_ID, TEST_UDID_CLIENT); + AddStringToJson(json, FIELD_SERVICE_PKG_NAME, TEST_APP_ID); + char *returnDataStr = PackJsonToString(json); + FreeJson(json); + return returnDataStr; +} + +static char *OnAuthRequestDirectTmp(int64_t requestId, int operationCode, const char *reqParam) +{ + CJson *json = CreateJson(); + AddIntToJson(json, FIELD_CONFIRMATION, REQUEST_ACCEPTED); + AddStringToJson(json, FIELD_PIN_CODE, TEST_PIN_CODE); + AddStringToJson(json, FIELD_PEER_CONN_DEVICE_ID, TEST_UDID_CLIENT); + char *returnDataStr = PackJsonToString(json); + FreeJson(json); + return returnDataStr; +} + +static char *OnAuthRequestDirect(int64_t requestId, int operationCode, const char *reqParam) +{ + CJson *json = CreateJson(); + AddIntToJson(json, FIELD_CONFIRMATION, REQUEST_ACCEPTED); + AddStringToJson(json, FIELD_PEER_CONN_DEVICE_ID, TEST_UDID_CLIENT); + AddStringToJson(json, FIELD_SERVICE_TYPE, SERVICE_TYPE_IMPORT); + char *returnDataStr = PackJsonToString(json); + FreeJson(json); + return returnDataStr; +} + +static DeviceAuthCallback g_gaCallback = { .onTransmit = OnTransmit, + .onSessionKeyReturned = OnSessionKeyReturned, + .onFinish = OnFinish, + .onError = OnError, + .onRequest = OnAuthRequest }; + +static DeviceAuthCallback g_daTmpCallback = { .onTransmit = OnTransmit, + .onSessionKeyReturned = OnSessionKeyReturned, + .onFinish = OnFinish, + .onError = OnError, + .onRequest = OnAuthRequestDirectTmp }; + +static DeviceAuthCallback g_daLTCallback = { .onTransmit = OnTransmit, + .onSessionKeyReturned = OnSessionKeyReturned, + .onFinish = OnFinish, + .onError = OnError, + .onRequest = OnAuthRequestDirect }; + +static void AuthDeviceDirectWithPinDemo(void) +{ + g_asyncStatus = ASYNC_STATUS_WAITING; + bool isClient = true; + SetDeviceStatus(isClient); + + int32_t ret = StartAuthDevice(TEST_REQ_ID, g_authWithPinParams, &g_daTmpCallback); + if (ret != HC_SUCCESS) { + g_asyncStatus = ASYNC_STATUS_ERROR; + return; + } + while (g_asyncStatus == ASYNC_STATUS_WAITING) { + usleep(TEST_DEV_AUTH_SLEEP_TIME); + } + while (g_asyncStatus == ASYNC_STATUS_TRANSMIT) { + isClient = !isClient; + SetDeviceStatus(isClient); + g_asyncStatus = ASYNC_STATUS_WAITING; + CJson *json = CreateJson(); + AddIntToJson(json, FIELD_OS_ACCOUNT_ID, TEST_AUTH_OS_ACCOUNT_ID); + AddStringToJson(json, "data", (const char *)g_transmitData); + const char *autParams = PackJsonToString(json); + FreeJson(json); + if (isClient) { + ret = ProcessAuthDevice(TEST_REQ_ID, autParams, &g_daTmpCallback); + } else { + ret = ProcessAuthDevice(TEST_REQ_ID2, autParams, &g_daTmpCallback); + } + (void)memset_s(g_transmitData, g_transmitDataMaxLen, 0, g_transmitDataMaxLen); + g_transmitDataLen = 0; + if (ret != HC_SUCCESS) { + g_asyncStatus = ASYNC_STATUS_ERROR; + return; + } + while (g_asyncStatus == ASYNC_STATUS_WAITING) { + usleep(TEST_DEV_AUTH_SLEEP_TIME); + } + if (g_asyncStatus == ASYNC_STATUS_ERROR) { + break; + } + if (g_transmitDataLen > 0) { + g_asyncStatus = ASYNC_STATUS_TRANSMIT; + } + } + SetDeviceStatus(true); +} + +static void AuthDeviceDirectDemo(void) +{ + g_asyncStatus = ASYNC_STATUS_WAITING; + bool isClient = true; + SetDeviceStatus(isClient); + + int32_t ret = StartAuthDevice(TEST_REQ_ID, g_authDirectParams, &g_daLTCallback); + if (ret != HC_SUCCESS) { + g_asyncStatus = ASYNC_STATUS_ERROR; + return; + } + while (g_asyncStatus == ASYNC_STATUS_WAITING) { + usleep(TEST_DEV_AUTH_SLEEP_TIME); + } + while (g_asyncStatus == ASYNC_STATUS_TRANSMIT) { + isClient = !isClient; + SetDeviceStatus(isClient); + g_asyncStatus = ASYNC_STATUS_WAITING; + CJson *json = CreateJson(); + AddIntToJson(json, FIELD_OS_ACCOUNT_ID, TEST_AUTH_OS_ACCOUNT_ID); + AddStringToJson(json, "data", (const char *)g_transmitData); + const char *autParams = PackJsonToString(json); + FreeJson(json); + if (isClient) { + ret = ProcessAuthDevice(TEST_REQ_ID, autParams, &g_daLTCallback); + } else { + ret = ProcessAuthDevice(TEST_REQ_ID2, autParams, &g_daLTCallback); + } + (void)memset_s(g_transmitData, g_transmitDataMaxLen, 0, g_transmitDataMaxLen); + g_transmitDataLen = 0; + if (ret != HC_SUCCESS) { + g_asyncStatus = ASYNC_STATUS_ERROR; + return; + } + while (g_asyncStatus == ASYNC_STATUS_WAITING) { + usleep(TEST_DEV_AUTH_SLEEP_TIME); + } + if (g_asyncStatus == ASYNC_STATUS_ERROR) { + break; + } + if (g_transmitDataLen > 0) { + g_asyncStatus = ASYNC_STATUS_TRANSMIT; + } + } + SetDeviceStatus(true); +} + +static void DeviceLevelAuthDemo(void) +{ + g_asyncStatus = ASYNC_STATUS_WAITING; + bool isClient = true; + SetDeviceStatus(isClient); + const GroupAuthManager *ga = GetGaInstance(); + ASSERT_NE(ga, nullptr); + int32_t ret = ga->authDevice(DEFAULT_OS_ACCOUNT, TEST_REQ_ID, g_deviceLevelAuthParams, &g_gaCallback); + if (ret != HC_SUCCESS) { + g_asyncStatus = ASYNC_STATUS_ERROR; + return; + } + while (g_asyncStatus == ASYNC_STATUS_WAITING) { + usleep(TEST_DEV_AUTH_SLEEP_TIME); + } + while (g_asyncStatus == ASYNC_STATUS_TRANSMIT) { + isClient = !isClient; + SetDeviceStatus(isClient); + g_asyncStatus = ASYNC_STATUS_WAITING; + if (isClient) { + ret = ga->processData(TEST_REQ_ID, g_transmitData, g_transmitDataLen, &g_gaCallback); + } else { + ret = ga->processData(TEST_REQ_ID2, g_transmitData, g_transmitDataLen, &g_gaCallback); + } + (void)memset_s(g_transmitData, g_transmitDataMaxLen, 0, g_transmitDataMaxLen); + g_transmitDataLen = 0; + if (ret != HC_SUCCESS) { + g_asyncStatus = ASYNC_STATUS_ERROR; + return; + } + while (g_asyncStatus == ASYNC_STATUS_WAITING) { + usleep(TEST_DEV_AUTH_SLEEP_TIME); + } + if (g_asyncStatus == ASYNC_STATUS_ERROR) { + break; + } + if (g_transmitDataLen > 0) { + g_asyncStatus = ASYNC_STATUS_TRANSMIT; + } + } + SetDeviceStatus(true); +} + +static const char *CreateCredentialParam( + int32_t osAccountId, const char *deviceId, int32_t flag, const char *serviceType, const char *publicKey) +{ + CJson *json = CreateJson(); + + AddIntToJson(json, FIELD_OS_ACCOUNT_ID, osAccountId); + AddStringToJson(json, FIELD_DEVICE_ID, deviceId); + AddStringToJson(json, FIELD_SERVICE_TYPE, serviceType); + AddIntToJson(json, FIELD_ACQURIED_TYPE, P2P_BIND); + + if (flag >= 0) { + AddIntToJson(json, FIELD_CRED_OP_FLAG, flag); + } + + if (publicKey) { + AddStringToJson(json, FIELD_PUBLIC_KEY, publicKey); + } + + char *returnDataStr = PackJsonToString(json); + FreeJson(json); + return returnDataStr; +} + +static int32_t ProcessCredentiaCreateDemo(const int32_t osAccountId, const bool isClient, const char *udid) +{ + int32_t flag = RETURN_FLAG_PUBLIC_KEY; + const char *requestParams = CreateCredentialParam(osAccountId, udid, flag, DEFAULT_SERVICE_TYPE, nullptr); + char *returnData = nullptr; + SetDeviceStatus(isClient); + + int32_t res = ProcessCredential(CRED_OP_CREATE, requestParams, &returnData); + + if (returnData) { + printf("returnData: %s\n", returnData); + CJson *in = CreateJsonFromString(returnData); + if (in == nullptr) { + printf("CreateJsonFromString returnData failed !\n"); + } else { + if (GetIntFromJson(in, FIELD_CRED_OP_RESULT, &res) != HC_SUCCESS) { + printf("GetIntFromJson result failed !\n"); + FreeJson(in); + return HC_ERR_INVALID_PARAMS; + } + printf("get result from returnData: %d\n", res); + SetDeviceStatus(true); + return res; + } + } + + printf("returnData is null !\n"); + + SetDeviceStatus(true); + return res; +} + +static int32_t ProcessCredentialQueryDemo( + const int32_t osAccountId, const bool isClient, const char *udid, char **publicKey) +{ + int32_t flag = RETURN_FLAG_PUBLIC_KEY; + + char *returnData = nullptr; + SetDeviceStatus(isClient); + const char *requestParams = CreateCredentialParam(osAccountId, udid, flag, DEFAULT_SERVICE_TYPE, nullptr); + + int32_t res = ProcessCredential(CRED_OP_QUERY, requestParams, &returnData); + + if (returnData) { + printf("returnData: %s\n", returnData); + CJson *in = CreateJsonFromString(returnData); + if (in == nullptr) { + printf("CreateJsonFromString returnData failed !\n"); + } else { + if (GetIntFromJson(in, FIELD_CRED_OP_RESULT, &res) != HC_SUCCESS) { + printf("GetIntFromJson result failed !\n"); + FreeJson(in); + return HC_ERR_INVALID_PARAMS; + } + printf("get result from returnData: %d\n", res); + *publicKey = (char *)GetStringFromJson(in, FIELD_PUBLIC_KEY); + SetDeviceStatus(true); + return res; + } + } + + printf("returnData is null !\n"); + + SetDeviceStatus(true); + return res; +} + +static int32_t ProcessCredentialDemoImpPubKey( + const int32_t osAccountId, const bool isClient, const char *udid, const char *publicKey) +{ + const char *requestParams = + CreateCredentialParam(osAccountId, udid, RETURN_FLAG_INVALID, SERVICE_TYPE_IMPORT, publicKey); + char *returnData = nullptr; + SetDeviceStatus(isClient); + + int32_t res = ProcessCredential(CRED_OP_IMPORT, requestParams, &returnData); + + if (returnData) { + CJson *in = CreateJsonFromString(returnData); + if (in == nullptr) { + printf("CreateJsonFromString returnData failed !\n"); + } else { + if (GetIntFromJson(in, FIELD_CRED_OP_RESULT, &res) != HC_SUCCESS) { + printf("GetIntFromJson result failed !\n"); + FreeJson(in); + return HC_ERR_INVALID_PARAMS; + } + printf("get result from returnData: %d\n", res); + SetDeviceStatus(true); + return res; + } + } + + printf("returnData is null !\n"); + + SetDeviceStatus(true); + return res; +} + +static int32_t CreateServerKeyPair() +{ + SetDeviceStatus(false); + const char *requestParams = CreateCredentialParam( + TEST_AUTH_OS_ACCOUNT_ID, TEST_UDID_SERVER, RETURN_FLAG_PUBLIC_KEY, DEFAULT_SERVICE_TYPE, nullptr); + char *returnData = nullptr; + + printf("ProcessCredentialDemo: operationCode=%d\n", CRED_OP_CREATE); + int32_t res = ProcessCredential(CRED_OP_CREATE, requestParams, &returnData); + + if (returnData) { + printf("returnData: %s\n", returnData); + CJson *in = CreateJsonFromString(returnData); + if (in == nullptr) { + printf("CreateJsonFromString returnData failed !\n"); + } else { + if (GetIntFromJson(in, FIELD_CRED_OP_RESULT, &res) != HC_SUCCESS) { + printf("GetIntFromJson result failed !\n"); + FreeJson(in); + return HC_ERR_INVALID_PARAMS; + } + printf("get result from returnData: %d\n", res); + return res; + } + } + + printf("returnData is null !\n"); + + SetDeviceStatus(true); + return res; +} + +static int32_t DeleteServerKeyPair() +{ + SetDeviceStatus(false); + const char *requestParams = CreateCredentialParam( + TEST_AUTH_OS_ACCOUNT_ID, TEST_UDID_SERVER, RETURN_FLAG_PUBLIC_KEY, DEFAULT_SERVICE_TYPE, nullptr); + char *returnData = nullptr; + + printf("ProcessCredentialDemo: operationCode=%d\n", CRED_OP_DELETE); + int32_t res = ProcessCredential(CRED_OP_DELETE, requestParams, &returnData); + + if (returnData) { + printf("returnData: %s\n", returnData); + CJson *in = CreateJsonFromString(returnData); + if (in == nullptr) { + printf("CreateJsonFromString returnData failed !\n"); + } else { + if (GetIntFromJson(in, FIELD_CRED_OP_RESULT, &res) != HC_SUCCESS) { + printf("GetIntFromJson result failed !\n"); + FreeJson(in); + return HC_ERR_INVALID_PARAMS; + } + printf("get result from returnData: %d\n", res); + return res; + } + } + + printf("returnData is null !\n"); + + SetDeviceStatus(true); + return res; +} + +static int32_t ProcessCredentialDemo(int operationCode, const char *serviceType) +{ + int32_t flag = RETURN_FLAG_INVALID; + if (operationCode == CRED_OP_CREATE || operationCode == CRED_OP_QUERY) { + flag = RETURN_FLAG_PUBLIC_KEY; + } + const char *requestParams = CreateCredentialParam(TEST_AUTH_OS_ACCOUNT_ID, TEST_UDID, flag, serviceType, nullptr); + char *returnData = nullptr; + bool isClient = true; + SetDeviceStatus(isClient); + + printf("ProcessCredentialDemo: operationCode=%d\n", operationCode); + int32_t res = ProcessCredential(operationCode, requestParams, &returnData); + + if (returnData) { + printf("returnData: %s\n", returnData); + CJson *in = CreateJsonFromString(returnData); + if (in == nullptr) { + printf("CreateJsonFromString returnData failed !\n"); + } else { + if (GetIntFromJson(in, FIELD_CRED_OP_RESULT, &res) != HC_SUCCESS) { + printf("GetIntFromJson result failed !\n"); + FreeJson(in); + return HC_ERR_INVALID_PARAMS; + } + printf("get result from returnData: %d\n", res); + SetDeviceStatus(true); + return res; + } + } + + printf("returnData is null !\n"); + + SetDeviceStatus(true); + return res; +} + +static int32_t ProcessCredentialDemoImport(const char *importServiceType) +{ + const char *requestParams = CreateCredentialParam(TEST_AUTH_OS_ACCOUNT_ID, TEST_UDID, RETURN_FLAG_INVALID, + importServiceType, "CA32A9DFACB944B1F6292C9AE10783F6376A987A9CE30C13300BC866917DFF2E"); + char *returnData = nullptr; + bool isClient = false; + SetDeviceStatus(isClient); + + printf("ProcessCredentialDemoImport\n"); + int32_t res = ProcessCredential(CRED_OP_IMPORT, requestParams, &returnData); + + if (returnData) { + CJson *in = CreateJsonFromString(returnData); + if (in == nullptr) { + printf("CreateJsonFromString returnData failed !\n"); + } else { + if (GetIntFromJson(in, FIELD_CRED_OP_RESULT, &res) != HC_SUCCESS) { + printf("GetIntFromJson result failed !\n"); + FreeJson(in); + return HC_ERR_INVALID_PARAMS; + } + printf("get result from returnData: %d\n", res); + SetDeviceStatus(true); + return res; + } + } + + printf("returnData is null !\n"); + + SetDeviceStatus(true); + return res; +} + +class DaAuthDeviceTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +}; + +void DaAuthDeviceTest::SetUpTestCase() {} + +void DaAuthDeviceTest::TearDownTestCase() {} + +void DaAuthDeviceTest::SetUp() +{ + int32_t ret = InitDeviceAuthService(); + ASSERT_EQ(ret, HC_SUCCESS); +} + +void DaAuthDeviceTest::TearDown() +{ + DestroyDeviceAuthService(); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest001, TestSize.Level0) +{ + SetIsoSupported(false); + SetPakeV1Supported(true); + SetDeviceStatus(true); + AuthDeviceDirectWithPinDemo(); + ASSERT_EQ(g_asyncStatus, ASYNC_STATUS_FINISH); +} +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest002, TestSize.Level0) +{ + SetIsoSupported(false); + SetPakeV1Supported(true); + SetDeviceStatus(true); + ProcessCredentiaCreateDemo(TEST_AUTH_OS_ACCOUNT_ID, true, TEST_UDID_CLIENT); + ProcessCredentiaCreateDemo(TEST_AUTH_OS_ACCOUNT_ID, false, TEST_UDID_SERVER); + char *publicKey = nullptr; + ProcessCredentialQueryDemo(TEST_AUTH_OS_ACCOUNT_ID, false, TEST_UDID_SERVER, &publicKey); + ProcessCredentialDemoImpPubKey(TEST_AUTH_OS_ACCOUNT_ID, true, TEST_UDID_SERVER, publicKey); + ProcessCredentialQueryDemo(TEST_AUTH_OS_ACCOUNT_ID, true, TEST_UDID_CLIENT, &publicKey); + ProcessCredentialDemoImpPubKey(TEST_AUTH_OS_ACCOUNT_ID, false, TEST_UDID_CLIENT, publicKey); + AuthDeviceDirectDemo(); + ASSERT_EQ(g_asyncStatus, ASYNC_STATUS_FINISH); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest003, TestSize.Level0) +{ + SetIsoSupported(false); + SetPakeV1Supported(true); + SetDeviceStatus(true); + int32_t res = ProcessCredentialDemo(CRED_OP_DELETE, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, DEFAULT_SERVICE_TYPE); + ASSERT_NE(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_CREATE, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_DELETE, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, DEFAULT_SERVICE_TYPE); + ASSERT_NE(res, HC_SUCCESS); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest004, TestSize.Level0) +{ + SetIsoSupported(false); + SetPakeV1Supported(true); + SetDeviceStatus(true); + + int32_t res = ProcessCredentialDemo(CRED_OP_CREATE, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_DELETE, DEFAULT_SERVICE_TYPE); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, DEFAULT_SERVICE_TYPE); + ASSERT_NE(res, HC_SUCCESS); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest005, TestSize.Level0) +{ + SetIsoSupported(false); + SetPakeV1Supported(true); + SetDeviceStatus(true); + int32_t res = CreateServerKeyPair(); + ASSERT_NE(res, HC_SUCCESS); + res = ProcessCredentialDemoImport(SERVICE_TYPE_IMPORT); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, SERVICE_TYPE_IMPORT); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_DELETE, SERVICE_TYPE_IMPORT); + ASSERT_EQ(res, HC_SUCCESS); + res = ProcessCredentialDemo(CRED_OP_QUERY, SERVICE_TYPE_IMPORT); + ASSERT_NE(res, HC_SUCCESS); + res = DeleteServerKeyPair(); + ASSERT_EQ(res, HC_SUCCESS); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest006, TestSize.Level0) +{ + SetIsoSupported(false); + SetPakeV1Supported(true); + SetDeviceStatus(true); + ProcessCredentiaCreateDemo(TEST_AUTH_OS_ACCOUNT_ID, true, TEST_UDID_CLIENT); + ProcessCredentiaCreateDemo(TEST_AUTH_OS_ACCOUNT_ID, false, TEST_UDID_SERVER); + char *publicKey = nullptr; + ProcessCredentialQueryDemo(TEST_AUTH_OS_ACCOUNT_ID, false, TEST_UDID_SERVER, &publicKey); + ProcessCredentialDemoImpPubKey(TEST_AUTH_OS_ACCOUNT_ID, true, TEST_UDID_SERVER, publicKey); + ProcessCredentialQueryDemo(TEST_AUTH_OS_ACCOUNT_ID, true, TEST_UDID_CLIENT, &publicKey); + ProcessCredentialDemoImpPubKey(TEST_AUTH_OS_ACCOUNT_ID, false, TEST_UDID_CLIENT, publicKey); + DeviceLevelAuthDemo(); + ASSERT_EQ(g_asyncStatus, ASYNC_STATUS_FINISH); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest007, TestSize.Level0) +{ + SetIsoSupported(false); + SetPakeV1Supported(true); + SetDeviceStatus(true); + + CJson *in = CreateJsonFromString("{\"testKey\":\"testValue\"}"); + CertInfo *certInfo = (CertInfo *)HcMalloc(sizeof(CertInfo *), 0); + IdentityInfo *identityInfo = (IdentityInfo *)HcMalloc(sizeof(IdentityInfo *), 0); + + int32_t res = GetCredInfoByPeerCert(in, certInfo, &identityInfo); + + HcFree(identityInfo); + HcFree(certInfo); + FreeJson(in); + + ASSERT_NE(res, HC_SUCCESS); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest008, TestSize.Level0) +{ + SetIsoSupported(false); + SetPakeV1Supported(true); + SetDeviceStatus(true); + + CJson *in = CreateJsonFromString("{\"osAccountId\":\"100\"}"); + CertInfo *certInfo = (CertInfo *)HcMalloc(sizeof(CertInfo *), 0); + uint8_t val[] = { 0, 0 }; + Uint8Buff sharedSecret = { val, sizeof(val) }; + + int32_t res = GetSharedSecretByPeerCert(in, certInfo, ALG_EC_SPEKE, &sharedSecret); + HcFree(certInfo); + FreeJson(in); + ASSERT_NE(res, HC_SUCCESS); + + res = GetSharedSecretByPeerCert(nullptr, nullptr, ALG_EC_SPEKE, &sharedSecret); + ASSERT_NE(res, HC_SUCCESS); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest009, TestSize.Level0) +{ + SetIsoSupported(false); + SetPakeV1Supported(true); + SetDeviceStatus(true); + + CJson *in = CreateJsonFromString("{\"osAccountId\":\"100\"}"); + uint8_t val[] = { 0, 0 }; + Uint8Buff sharedSecret = { val, sizeof(val) }; + Uint8Buff presharedUrl = { val, sizeof(val) }; + + int32_t res = GetSharedSecretByUrl(in, &presharedUrl, ALG_ISO, &sharedSecret); + FreeJson(in); + ASSERT_NE(res, HC_SUCCESS); + + res = GetSharedSecretByUrl(nullptr, &presharedUrl, ALG_ISO, &sharedSecret); + ASSERT_NE(res, HC_SUCCESS); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest010, TestSize.Level0) +{ + SetIsoSupported(false); + SetPakeV1Supported(true); + SetDeviceStatus(true); + + CJson *in = CreateJsonFromString("{\"pinCode\":\"123456\",\"seed\":" + "\"CA32A9DFACB944B1F6292C9AE10783F6376A987A9CE30C13300BC866917DFF2E\"}"); + uint8_t val[] = { 0, 0 }; + Uint8Buff sharedSecret = { val, sizeof(val) }; + Uint8Buff presharedUrl = { val, sizeof(val) }; + + int32_t res = GetSharedSecretByUrl(in, &presharedUrl, ALG_ISO, &sharedSecret); + FreeJson(in); + ASSERT_EQ(res, HC_SUCCESS); + + res = GetSharedSecretByUrl(nullptr, &presharedUrl, ALG_ISO, &sharedSecret); + ASSERT_NE(res, HC_SUCCESS); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest011, TestSize.Level0) +{ + SetIsoSupported(false); + SetPakeV1Supported(true); + SetDeviceStatus(true); + + const AuthIdentityManager *authIdentityManager = GetAuthIdentityManager(); + ASSERT_NE(authIdentityManager, nullptr); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest012, TestSize.Level0) +{ + SetIsoSupported(false); + SetPakeV1Supported(true); + SetDeviceStatus(true); + + const AuthIdentity *authIdentity = GetAuthIdentityByType(AUTH_IDENTITY_TYPE_INVALID); + ASSERT_EQ(authIdentity, nullptr); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest013, TestSize.Level0) +{ + SetIsoSupported(false); + SetPakeV1Supported(true); + SetDeviceStatus(true); + + CJson *in = CreateJsonFromString("{\"groupId\":\"123456\",\"seed\":" + "\"CA32A9DFACB944B1F6292C9AE10783F6376A987A9CE30C13300BC866917DFF2E\"}"); + uint8_t val[] = { 0, 0 }; + Uint8Buff sharedSecret = { val, sizeof(val) }; + const char *credUrl = "{\"credentialType\":0,\"keyType\":1,\"trustType\":1,\"groupId\":\"123456\"}"; + Uint8Buff presharedUrl = { (uint8_t *)credUrl, HcStrlen(credUrl) }; + + int32_t res = GetSharedSecretByUrl(in, &presharedUrl, ALG_ISO, &sharedSecret); + FreeJson(in); + ASSERT_NE(res, HC_SUCCESS); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest014, TestSize.Level0) +{ + SetIsoSupported(false); + SetPakeV1Supported(true); + SetDeviceStatus(true); + + const CredentialOperator *credentialOperator = GetCredentialOperator(); + + int32_t res = credentialOperator->queryCredential(nullptr, nullptr); + ASSERT_NE(res, HC_SUCCESS); + + res = credentialOperator->genarateCredential(nullptr, nullptr); + ASSERT_NE(res, HC_SUCCESS); + + res = credentialOperator->importCredential(nullptr, nullptr); + ASSERT_NE(res, HC_SUCCESS); + + res = credentialOperator->deleteCredential(nullptr, nullptr); + ASSERT_NE(res, HC_SUCCESS); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest015, TestSize.Level0) +{ + SetIsoSupported(false); + SetPakeV1Supported(true); + SetDeviceStatus(true); + + const CredentialOperator *credentialOperator = GetCredentialOperator(); + + const char *reqJsonStr = "{\"deviceId\":\"123456\",\"osAccountId\":0,\"acquireType\":0}"; + char *returnData = nullptr; + int32_t res = credentialOperator->queryCredential(reqJsonStr, &returnData); + ASSERT_NE(res, HC_SUCCESS); + + res = credentialOperator->genarateCredential(reqJsonStr, &returnData); + ASSERT_EQ(res, HC_SUCCESS); + + res = credentialOperator->importCredential(reqJsonStr, &returnData); + ASSERT_NE(res, HC_SUCCESS); + + res = credentialOperator->deleteCredential(reqJsonStr, &returnData); + ASSERT_EQ(res, HC_SUCCESS); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest016, TestSize.Level0) +{ + SetIsoSupported(false); + SetPakeV1Supported(true); + SetDeviceStatus(true); + + const CredentialOperator *credentialOperator = GetCredentialOperator(); + + const char *reqJsonStr = "{\"osAccountId\":0,\"acquireType\":0}"; + char *returnData = nullptr; + int32_t res = credentialOperator->queryCredential(reqJsonStr, &returnData); + ASSERT_NE(res, HC_SUCCESS); + + res = credentialOperator->genarateCredential(reqJsonStr, &returnData); + ASSERT_NE(res, HC_SUCCESS); + + res = credentialOperator->importCredential(reqJsonStr, &returnData); + ASSERT_NE(res, HC_SUCCESS); + + res = credentialOperator->deleteCredential(reqJsonStr, &returnData); + ASSERT_NE(res, HC_SUCCESS); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest017, TestSize.Level0) +{ + SetIsoSupported(false); + SetPakeV1Supported(true); + SetDeviceStatus(true); + + const CredentialOperator *credentialOperator = GetCredentialOperator(); + + const char *reqJsonStr = "{\"deviceId\":\"123456\",\"acquireType\":0}"; + char *returnData = nullptr; + int32_t res = credentialOperator->queryCredential(reqJsonStr, &returnData); + ASSERT_NE(res, HC_SUCCESS); + + res = credentialOperator->genarateCredential(reqJsonStr, &returnData); + ASSERT_NE(res, HC_SUCCESS); + + res = credentialOperator->importCredential(reqJsonStr, &returnData); + ASSERT_NE(res, HC_SUCCESS); + + res = credentialOperator->deleteCredential(reqJsonStr, &returnData); + ASSERT_NE(res, HC_SUCCESS); +} + +HWTEST_F(DaAuthDeviceTest, DaAuthDeviceTest018, TestSize.Level0) +{ + SetIsoSupported(false); + SetPakeV1Supported(true); + SetDeviceStatus(true); + + const CredentialOperator *credentialOperator = GetCredentialOperator(); + + const char *reqJsonStr = "{\"deviceId\":\"123456\",\"osAccountId\":0}"; + char *returnData = nullptr; + int32_t res = credentialOperator->queryCredential(reqJsonStr, &returnData); + ASSERT_NE(res, HC_SUCCESS); + + res = credentialOperator->genarateCredential(reqJsonStr, &returnData); + ASSERT_NE(res, HC_SUCCESS); + + res = credentialOperator->importCredential(reqJsonStr, &returnData); + ASSERT_NE(res, HC_SUCCESS); + + res = credentialOperator->deleteCredential(reqJsonStr, &returnData); + ASSERT_NE(res, HC_SUCCESS); +} +} // namespace diff --git a/test/unittest/deviceauth/source/standard_exchange_task_test.cpp b/test/unittest/deviceauth/source/standard_exchange_task_test.cpp index c8b683d3..ad8da2d0 100644 --- a/test/unittest/deviceauth/source/standard_exchange_task_test.cpp +++ b/test/unittest/deviceauth/source/standard_exchange_task_test.cpp @@ -19,6 +19,7 @@ #include "alg_loader.h" #include "device_auth_defines.h" #include "securec.h" +#include "identity_defines.h" extern "C"{ #include "common_standard_bind_exchange.h" @@ -128,7 +129,7 @@ HWTEST_F(StandardExchangeTaskTest, StandardExchangeTaskTest003, TestSize.Level0) pakeParams.baseParams.idSelf.val = authId; pakeParams.baseParams.idSelf.length = AUTH_ID_LENGTH; pakeParams.baseParams.loader = GetLoaderInstance(); - + StandardBindExchangeParams exchangeParams; exchangeParams.exInfoCipher.length = INVALID_CIPHER_LENGTH; diff --git a/test/unittest/deviceauth/unit_test/source/account_related_creds_manager_dir_test.cpp b/test/unittest/deviceauth/unit_test/source/account_related_creds_manager_dir_test.cpp index a1aca99b..bcf881a1 100644 --- a/test/unittest/deviceauth/unit_test/source/account_related_creds_manager_dir_test.cpp +++ b/test/unittest/deviceauth/unit_test/source/account_related_creds_manager_dir_test.cpp @@ -23,7 +23,7 @@ #include "hc_log.h" #include "json_utils.h" #include "securec.h" -#include "../../../../../services/authenticators/src/account_related/creds_manager/asy_token_manager.c" +#include "../../../../../services/legacy/authenticators/src/account_related/creds_manager/asy_token_manager.c" using namespace std; using namespace testing::ext; diff --git a/test/unittest/deviceauth/unit_test/source/across_account_group_test.cpp b/test/unittest/deviceauth/unit_test/source/across_account_group_test.cpp index 585126f2..9da8f515 100644 --- a/test/unittest/deviceauth/unit_test/source/across_account_group_test.cpp +++ b/test/unittest/deviceauth/unit_test/source/across_account_group_test.cpp @@ -22,7 +22,7 @@ #include "device_auth_defines.h" #include "hc_log.h" #include "json_utils.h" -#include "../../../../../services/group_manager/src/group_operation/across_account_group/across_account_group.c" +#include "../../../../../services/legacy/group_manager/src/group_operation/across_account_group/across_account_group.c" using namespace std; using namespace testing::ext; diff --git a/test/unittest/deviceauth/unit_test/source/identical_account_group_test.cpp b/test/unittest/deviceauth/unit_test/source/identical_account_group_test.cpp index cfcda77c..6f62f3c6 100644 --- a/test/unittest/deviceauth/unit_test/source/identical_account_group_test.cpp +++ b/test/unittest/deviceauth/unit_test/source/identical_account_group_test.cpp @@ -22,7 +22,7 @@ #include "device_auth_defines.h" #include "hc_log.h" #include "json_utils.h" -#include "../../../../../services/group_manager/src/group_operation/identical_account_group/identical_account_group.c" +#include "../../../../../services/legacy/group_manager/src/group_operation/identical_account_group/identical_account_group.c" using namespace std; using namespace testing::ext; diff --git a/test/unittest/deviceauth/unit_test/source/peer_to_peer_group_test.cpp b/test/unittest/deviceauth/unit_test/source/peer_to_peer_group_test.cpp index 6267009b..f7f5d5dd 100644 --- a/test/unittest/deviceauth/unit_test/source/peer_to_peer_group_test.cpp +++ b/test/unittest/deviceauth/unit_test/source/peer_to_peer_group_test.cpp @@ -22,7 +22,7 @@ #include "device_auth_defines.h" #include "hc_log.h" #include "json_utils.h" -#include "../../../../../services/group_manager/src/group_operation/peer_to_peer_group/peer_to_peer_group.c" +#include "../../../../../services/legacy/group_manager/src/group_operation/peer_to_peer_group/peer_to_peer_group.c" using namespace std; using namespace testing::ext; diff --git a/test/unittest/tdd_framework/unit_test/services/creds_manager/BUILD.gn b/test/unittest/tdd_framework/unit_test/services/creds_manager/BUILD.gn index 9e05a7d1..ce25de0a 100644 --- a/test/unittest/tdd_framework/unit_test/services/creds_manager/BUILD.gn +++ b/test/unittest/tdd_framework/unit_test/services/creds_manager/BUILD.gn @@ -59,6 +59,9 @@ ohos_unittest("creds_manager_test") { "${tdd_framework_path}/common/src/os_account_adapter_mock.c", ] + include_dirs += identity_manager_inc + sources += identity_manager_files + defines = deviceauth_defines defines += [ "DEV_AUTH_HIVIEW_ENABLE" ] defines -= [ "ENABLE_PSEUDONYM" ] diff --git a/test/unittest/tdd_framework/unit_test/services/creds_manager/creds_manager_test.cpp b/test/unittest/tdd_framework/unit_test/services/creds_manager/creds_manager_test.cpp index 1b1279d9..ee70f4b2 100644 --- a/test/unittest/tdd_framework/unit_test/services/creds_manager/creds_manager_test.cpp +++ b/test/unittest/tdd_framework/unit_test/services/creds_manager/creds_manager_test.cpp @@ -22,7 +22,6 @@ #include "asy_token_manager.h" #include "common_defs.h" #include "creds_manager.h" -#include "creds_operation_utils.h" #include "device_auth.h" #include "device_auth_defines.h" #include "hc_dev_info_mock.h" diff --git a/test/unittest/tdd_framework/unit_test/services/frameworks/os_account_adapter/BUILD.gn b/test/unittest/tdd_framework/unit_test/services/frameworks/os_account_adapter/BUILD.gn index a4cb7f9f..e0fcb764 100644 --- a/test/unittest/tdd_framework/unit_test/services/frameworks/os_account_adapter/BUILD.gn +++ b/test/unittest/tdd_framework/unit_test/services/frameworks/os_account_adapter/BUILD.gn @@ -56,6 +56,9 @@ if (support_os_account) { sources += account_subscriber_files sources += sa_subscriber_files + include_dirs += identity_manager_inc + sources += identity_manager_files + cflags = [ "-DHILOG_ENABLE" ] cflags += [ "-DDEV_AUTH_WORK_THREAD_STACK_SIZE=${deviceauth_hichain_thread_stack_size}", diff --git a/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/BUILD.gn b/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/BUILD.gn index 2b293111..9f0446fe 100644 --- a/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/BUILD.gn +++ b/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/BUILD.gn @@ -37,6 +37,23 @@ ohos_unittest("expand_sub_session_test") { sources += pub_key_exchange_files sources += [ "expand_sub_session_test.cpp" ] + include_dirs += identity_manager_inc + include_dirs += [ + "${dev_frameworks_path}/inc", + "${group_manager_path}/inc", + "${group_auth_path}/inc", + "${dev_frameworks_path}/inc/os_account_adapter", + "${dev_frameworks_path}/inc/plugin_adapter", + "${protocol_path}/inc/pake_protocol", + "${data_manager_path}/inc", + "${session_manager_path}/inc/session/v1", + "${session_manager_path}/inc/session/v1/compatible_auth_sub_session", + "${group_auth_path}/inc/account_related_group_auth", + "${authenticators_path}/inc/account_unrelated/pake_task", + "${authenticators_path}/inc/account_unrelated", + ] + sources += identity_manager_files + cflags = [ "-DHILOG_ENABLE" ] defines = [ diff --git a/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/expand_process_lib/BUILD.gn b/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/expand_process_lib/BUILD.gn index 698cdb84..f1462a00 100644 --- a/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/expand_process_lib/BUILD.gn +++ b/test/unittest/tdd_framework/unit_test/services/session_manager/session/v2/expand_sub_session/expand_process_lib/BUILD.gn @@ -34,6 +34,23 @@ ohos_unittest("auth_code_import_test") { sources = auth_code_import_files sources += [ "auth_code_import_test.cpp" ] + include_dirs += identity_manager_inc + include_dirs += [ + "${dev_frameworks_path}/inc", + "${group_manager_path}/inc", + "${group_auth_path}/inc", + "${dev_frameworks_path}/inc/os_account_adapter", + "${dev_frameworks_path}/inc/plugin_adapter", + "${protocol_path}/inc/pake_protocol", + "${data_manager_path}/inc", + "${session_manager_path}/inc/session/v1", + "${session_manager_path}/inc/session/v1/compatible_auth_sub_session", + "${group_auth_path}/inc/account_related_group_auth", + "${authenticators_path}/inc/account_unrelated/pake_task", + "${authenticators_path}/inc/account_unrelated", + ] + sources += identity_manager_files + defines = [ "DEV_AUTH_MEMORY_DEBUG", "ENABLE_AUTH_CODE_IMPORT", @@ -71,6 +88,23 @@ ohos_unittest("pub_key_exchange_test") { sources = pub_key_exchange_files sources += [ "pub_key_exchange_test.cpp" ] + include_dirs += identity_manager_inc + include_dirs += [ + "${dev_frameworks_path}/inc", + "${group_manager_path}/inc", + "${group_auth_path}/inc", + "${dev_frameworks_path}/inc/os_account_adapter", + "${dev_frameworks_path}/inc/plugin_adapter", + "${protocol_path}/inc/pake_protocol", + "${data_manager_path}/inc", + "${session_manager_path}/inc/session/v1", + "${session_manager_path}/inc/session/v1/compatible_auth_sub_session", + "${group_auth_path}/inc/account_related_group_auth", + "${authenticators_path}/inc/account_unrelated/pake_task", + "${authenticators_path}/inc/account_unrelated", + ] + sources += identity_manager_files + defines = [ "DEV_AUTH_MEMORY_DEBUG", "ENABLE_PUB_KEY_EXCHANGE",