diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h new file mode 100644 index 0000000000000000000000000000000000000000..f7d6f7a29ae68d488213e0d0a5960e7188e87051 --- /dev/null +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -0,0 +1,222 @@ +/* + * Copyright (c) 2025 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 OHOS_DM_AUTH_MANAGER_V2_H +#define OHOS_DM_AUTH_MANAGER_V2_H + +#include +#include "json_object.h" +#include "hichain_auth_connector.h" +#include "hichain_connector.h" +#include "softbus_connector.h" +#include "softbus_session.h" +#include "auth_ui_state_manager.h" +#include "dm_auth_manager_base.h" + +namespace OHOS { +namespace DistributedHardware { +struct DmAuthContext; + +// From identity_service_defines.h in security_device_auth +enum { + ACCOUNT_RELATED = 1, + ACCOUNT_UNRELATED, + ACCOUNT_ACROSS +}; + +// From identity_service_defines.h in security_device_auth +enum { + SCOPE_DEVICE = 1, + SCOPE_USER, + SCOPE_APP, +}; + +class AuthManager : public AuthManagerBase, + public std::enable_shared_from_this { +public: + AuthManager(std::shared_ptr softbusConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector); + virtual ~AuthManager() = default; + + // External API begin + /** + * @tc.name: DmAuthManager::OnUserOperation + * @tc.desc: User Operation of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + virtual int32_t OnUserOperation(int32_t action, const std::string ¶ms) = 0; + + /** + * @tc.name: AuthManager::GeneratePincode + * @tc.desc: Generate Pincode of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t BindTarget(const std::string &sessionName, const PeerTargetId &targetId, + const std::map &bindParam); + + /** + * @tc.name: AuthManager::OnUserOperation + * @tc.desc: User Operation of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t GeneratePincode(); + + /** + * @tc.name: AuthManager::ImportAuthCode + * @tc.desc: Import auth code + * @tc.type: FUNC + */ + int32_t ImportAuthCode(const std::string &sessionName, const std::string &authCode); + + /** + * @tc.name: AuthManager::RegisterUiStateCallback + * @tc.desc: Register ui state callback + * @tc.type: FUNC + */ + int32_t RegisterUiStateCallback(const std::string sessionName); + + /** + * @tc.name: AuthManager::UnRegisterUiStateCallback + * @tc.desc: Unregister ui state callback + * @tc.type: FUNC + */ + int32_t UnRegisterUiStateCallback(const std::string sessionName); + + /** + * @tc.name: AuthManager::UnAuthenticateDevice + * @tc.desc: UnAuthenticate Device of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t UnAuthenticateDevice(const std::string &sessionName, const std::string &udid, int32_t bindLevel); + + /** + * @brief UnBind device. + * @param sessionName package name. + * @param deviceId device id. + * @return Return 0 if success. + */ + int32_t UnBindDevice(const std::string &sessionName, const std::string &udid, + int32_t bindLevel, const std::string &extra); + + void HandleDeviceNotTrust(const std::string &udid); + + int32_t RegisterAuthenticationType(int32_t authenticationType); + void OnScreenLocked(); + int32_t StopAuthenticateDevice(const std::string &sessionName); + // External API begin end + + // Internal API begin + void SetAuthContext(std::shared_ptr context); + std::shared_ptr GetAuthContext(); + static bool IsHmlSessionType(std::string sessionType); + int32_t GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId); + void GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, + std::map &bindParam); + int32_t GetReason(); + + // Extract the local ACL for message parsing and bus usage. + int32_t GetAclListStr(std::string &aclList); + + bool IsAuthManagerConstructSuccess(); + // Internal API end + +protected: + std::shared_ptr context_; + std::shared_ptr authUiStateMgr_; + std::map bindParam_; + + int32_t GetPinCode(int32_t &code); + void GetRemoteDeviceId(std::string &deviceId); +private: + int32_t ParseAuthType(const std::map &bindParam, int32_t &authType); + int32_t ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType); + void ParseHmlInfoInJsonObject(const JsonObject &jsonObject); + void ParseJsonObject(const JsonObject &jsonObject); + void GetAuthParam(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra); + std::string GetBundleName(const JsonObject &jsonObject); + int32_t GetBindLevel(int32_t bindLevel); + void SetAuthType(int32_t authType); + bool IsAuthTypeSupported(const int32_t &authType); + bool IsAuthCodeReady(const std::string &sessionName); + int32_t CheckAuthParamVaild(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra); + void InitAuthState(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra); + int32_t AuthenticateDevice(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra); +}; + +class AuthSrcManager : public AuthManager { +public: + AuthSrcManager(std::shared_ptr softbusConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector); + virtual ~AuthSrcManager() override = default; + + // External API begin + int32_t OnUserOperation(int32_t action, const std::string ¶ms) override; + // External API end + + // IDmDeviceAuthCallback implement begin + bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) override; + void AuthDeviceError(int64_t requestId, int32_t errorCode) override; + void AuthDeviceFinish(int64_t requestId) override; + void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) override; + char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) override; + // IDmDeviceAuthCallback implement end + + // ISoftbusSessionCallback implement begin + void OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) override; + void OnSessionClosed(int32_t sessionId) override; + void OnDataReceived(int32_t sessionId, std::string message) override; + + bool GetIsCryptoSupport() override; + void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) override; + // ISoftbusSessionCallback implement end +}; + +class AuthSinkManager : public AuthManager { +public: + AuthSinkManager(std::shared_ptr softbusConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector); + virtual ~AuthSinkManager() override = default; + + // External API begin + int32_t OnUserOperation(int32_t action, const std::string ¶ms) override; + // External API end + + // IDmDeviceAuthCallback implement begin + bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) override; + void AuthDeviceError(int64_t requestId, int32_t errorCode) override; + void AuthDeviceFinish(int64_t requestId) override; + void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) override; + char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) override; + // IDmDeviceAuthCallback implement end + + // ISoftbusSessionCallback implement begin + void OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) override; + void OnSessionClosed(int32_t sessionId) override; + void OnDataReceived(int32_t sessionId, std::string message) override; + bool GetIsCryptoSupport() override; + void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) override; + // ISoftbusSessionCallback implement end +}; + +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_MANAGER_V2_H \ No newline at end of file diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h new file mode 100644 index 0000000000000000000000000000000000000000..15df14b5b3c5d40d164268472475cd004e5a4e84 --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -0,0 +1,215 @@ +/* + * Copyright (c) 2025 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 OHOS_DM_AUTH_CONTEXT_V2_H +#define OHOS_DM_AUTH_CONTEXT_V2_H + +#include +#include + +#include "auth_ui_state_manager.h" +#include "hichain_auth_connector.h" +#include "hichain_connector.h" +#include "softbus_connector.h" +#include "softbus_session.h" +#include "authentication.h" + +#include "dm_timer.h" +#include "dm_auth_message_processor.h" +#include "dm_device_info.h" +#include "dm_ability_manager.h" +#include "dm_log.h" +#include "dm_anonymous.h" +#include "dm_constants.h" + +namespace OHOS { +namespace DistributedHardware { + +class DmAuthStateMachine; +class DmAuthMessageProcessor; + +// PIN Code Authentication Type +enum DmAuthType : int32_t { + AUTH_TYPE_CRE = 0, // Not used in the new protocol + AUTH_TYPE_PIN, // Input PIN code + AUTH_TYPE_QR_CODE, // Not used in the new protocol + AUTH_TYPE_NFC, // Not used in the new protocol + AUTH_TYPE_NO_INTER_ACTION, // Not used in the new protocol + AUTH_TYPE_IMPORT_AUTH_CODE, // Import PIN code + AUTH_TYPE_UNKNOW, // Not used in the new protocol + AUTH_TYPE_PIN_ULTRASONIC, // Ultrasonic PIN code +}; + +enum DmAuthDirection { + DM_AUTH_SOURCE = 0, + DM_AUTH_SINK, +}; + +enum DmBindType { + DM_AUTH_USERID = 1, + DM_AUTH_SYSTEM_SERVICE, + DM_AUTH_APP_SERVICE, + DM_AUTH_DEVICEID, +}; + +enum DmAuthSide { + DM_AUTH_LOCAL_SIDE = 0, + DM_AUTH_REMOTE_SIDE, +}; + +enum DmAuthScope { + DM_AUTH_SCOPE_DEVICE = 1, + DM_AUTH_SCOPE_USER, + DM_AUTH_SCOPE_APP, +}; + +// Used for one-touch pairing +struct DmPeerTargetAddress { + // directly establish a Bluetooth connection + std::string peerBrMacAddress; + std::string peerBleMacAddress; + std::string peerWifiMacAddress; + std::string peerActionMacAddress; + + std::string peerWifiChannel; + std::string peerWifiIp; + uint16_t peerWifiPort; +}; + +struct DmPeerTarget { + DmBindType peerType; + std::string peerDeviceId; + int64_t peerServiceId; + uint64_t peerSaTokenId; + std::string peerBundleName; + DmPeerTargetAddress peerTargetAddress; +}; + +struct DmAccess { + std::string deviceName; + int32_t deviceType; // Device types such as PC, mobile, watch, large screen, etc. + std::string deviceId; + std::string deviceIdHash; + std::string addr; + int32_t userId; + std::string userIdHash; + int32_t displayId{0}; // Logical screen ID, used for query userId + std::string accountId; + std::string accountIdHash; + uint64_t tokenId; + std::string tokenIdHash; + std::string token; + std::string networkId; + std::string bundleName; // Stores the PacketName + int64_t serviceId; // Reserved field, to be used in HM 6.0 + std::string accesserHapSignature; + int32_t bindLevel; + std::string lnnCredentialId; // User-level credential ID + std::string transmitCredentialId; // Application-level credential ID + std::string lnnPublicKey; // User-level public key + std::string ephemeralPublicKey; // Application-level public key + std::vector bindType; // such as DM_IDENTICAL_ACCOUNT, DM_ACROSS_ACCOUNT, DM_POINT_TO_POINT + std::string publicKey; + int32_t status; // Indicates whether the service is in the foreground or background + int32_t sessionKeyId; // Used as key delivery material, retrieves the SK from the bus + int32_t transmitSessionKeyId; // Permanent application SKID on this end, returned by DP for ACL updates and aging + int32_t lnnSessionKeyId; // Permanent user SKID on this end, returned by DP for ACL updates and aging + int64_t transmitSkTimeStamp; // Used for aging, time is 2 days, application-level credential timestamp + int64_t lnnSkTimeStamp; // Used for aging, time is 2 days, user-level credential timestamp + int64_t skTimeStamp; // Used for aging, time is 2 days + bool isAuthed; + bool isOnline; + std::string dmVersion; + std::string edition; // Used for compatibility before version 5.1.0, assists in version negotiation + std::string aclList; // Trust relationship list, used for data aging, KV format + std::vector accesserStrList; + std::vector accesseeStrList; + std::string credentialInfos; // Credential information (point-to-point, same account, etc.) + std::string extraInfo; // Expandable field, JSON format, KV structure + std::string openAuthDeviceId; +}; + +struct DmAuthContext { + bool isOnline; + DmMessageType msgType; + int32_t sessionId; + int64_t requestId; // HiChain authentication ID + int32_t authBoxType{1}; // Authentication box type + UiAction pinInputResult; + // Authorization result (using 0, 1, 6, representing single use, cancel, and always trust, enum UiAction) + UiAction authResult{UiAction::USER_OPERATION_TYPE_ALLOW_AUTH}; + bool authResultReady{false}; + DmAuthType authType{DmAuthType::AUTH_TYPE_PIN}; // PIN code, ultrasonic PIN code, imported PIN code + std::vector authTypeList; + uint32_t currentAuthTypeIdx{0}; + int32_t inputPinAuthFailTimes{0}; // Number of failed PIN authentication attempts, exceeding 3 results in failure + int32_t pinCode{INVALID_PINCODE}; + // Link delay release time, does not automatically disconnect after + // authorization (used for specific business needs), reserved field + int32_t connDelayCloseTime; + int32_t reason{DM_OK}; + int32_t reply; + int32_t state; + int32_t hmlActionId = 0; + bool normalFinishAuth; + bool authenticating; // Indicator whether authentication is in progress + bool isFinished{false}; + bool isAppCredentialVerified{false}; // Whether the application credential has been verified + bool hmlEnable160M{false}; + std::string sessionName; // Business-provided identifier, custom-defined by business, carries risk of spoofing + std::string pkgLabel; + std::string importCodeBundleName; // Bundle name for imported PIN code + std::string appThumbnail; // Application thumbnail + // Description of the operation this binding is used for, displayed in authorization dialog + std::string appOperation; + // Custom business field, provides detailed information to the user about this binding operation + std::string customData; + std::string connSessionType; + std::string extraInfo; // Expandable field, key-value structure + DmAuthDirection direction; // Indicator of authentication direction + ProcessInfo processInfo; + DmPeerTarget peerTarget; + DmAccess accesser; + DmAccess accessee; + std::multimap proxy; // Multimap where the key is the accessor and the value is the accesssee + + std::shared_ptr authStateMachine; + std::shared_ptr authUiStateMgr; + std::shared_ptr hiChainAuthConnector; + std::shared_ptr authMessageProcessor; + std::shared_ptr softbusConnector; + std::shared_ptr listener; + std::shared_ptr authPtr; // Pointer to authentication interface + std::shared_ptr timer; + std::string transmitData; // Data returned from onTrasmit function + std::string importSessionName = ""; + std::string importAuthCode = ""; + std::map> authenticationMap; + PeerTargetId peerTargetId; + bool pinNegotiateStarted{false}; + bool isAuthenticateDevice{false}; // Whether device authentication is in progress + + std::string GetDeviceId(DmAuthSide side); + int32_t GetUserId(DmAuthSide side); + std::string GetCredentialId(DmAuthSide side, DmAuthScope authorizedScope); + std::string GetPublicKey(DmAuthSide side, DmAuthScope authorizedScope); + int32_t SetCredentialId(DmAuthSide side, DmAuthScope authorizedScope, const std::string &credentialId); + int32_t SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope, const std::string &publicKey); + std::string GetAccountId(DmAuthSide side); +}; + +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_CONTEXT_V2_H diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h b/services/implementation/include/authentication_v2/dm_auth_manager_base.h new file mode 100644 index 0000000000000000000000000000000000000000..41040630b4b85bdfc52dc9b95e87b388019b3dde --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h @@ -0,0 +1,201 @@ +/* + * Copyright (c) 2025 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 OHOS_DM_AUTH_ADAPTER_V2_H +#define OHOS_DM_AUTH_ADAPTER_V2_H + +#include +#include +#include +#include + +#include "softbus_session_callback.h" +#include "hichain_connector_callback.h" +#include "hichain_connector_callback.h" +#include "auth_request_state.h" +#include "auth_response_state.h" +#include "dm_device_info.h" + +namespace OHOS { +namespace DistributedHardware { + +extern const char* DM_VERSION_4_1_5_1; +extern const char* DM_VERSION_5_0_1; +extern const char* DM_VERSION_5_0_2; +extern const char* DM_VERSION_5_0_3; +extern const char* DM_VERSION_5_0_4; +extern const char* DM_VERSION_5_0_5; +extern const char* DM_VERSION_5_1_0; +extern const char* DM_VERSION_5_0_OLD_MAX; // 预估的旧版本最高版本号 + +extern const char* APP_OPERATION_KEY; +extern const char* TARGET_PKG_NAME_KEY; +extern const char* CUSTOM_DESCRIPTION_KEY; +extern const char* CANCEL_DISPLAY_KEY; +extern const char* BUNDLE_NAME_KEY; + +extern const char* AUTHENTICATE_TIMEOUT_TASK; +extern const char* NEGOTIATE_TIMEOUT_TASK; +extern const char* CONFIRM_TIMEOUT_TASK; +extern const char* INPUT_TIMEOUT_TASK; +extern const char* SESSION_HEARTBEAT_TIMEOUT_TASK; +extern const char* WAIT_REQUEST_TIMEOUT_TASK; +extern const char* AUTH_DEVICE_TIMEOUT_TASK; +extern const char* WAIT_PIN_AUTH_TIMEOUT_TASK; +extern const char* WAIT_NEGOTIATE_TIMEOUT_TASK; +extern const char* ADD_TIMEOUT_TASK; + +extern const int32_t AUTHENTICATE_TIMEOUT; +extern const int32_t CONFIRM_TIMEOUT; +extern const int32_t NEGOTIATE_TIMEOUT; +extern const int32_t INPUT_TIMEOUT; +extern const int32_t ADD_TIMEOUT; +extern const int32_t WAIT_NEGOTIATE_TIMEOUT; +extern const int32_t WAIT_REQUEST_TIMEOUT; +extern const int32_t CLONE_AUTHENTICATE_TIMEOUT; +extern const int32_t CLONE_CONFIRM_TIMEOUT; +extern const int32_t CLONE_NEGOTIATE_TIMEOUT; +extern const int32_t CLONE_ADD_TIMEOUT; +extern const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT; +extern const int32_t CLONE_WAIT_REQUEST_TIMEOUT; +extern const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT; +extern const int32_t CLONE_PIN_AUTH_TIMEOUT; +extern const int32_t HML_SESSION_TIMEOUT; +extern const int32_t SESSION_HEARTBEAT_TIMEOUT; +extern const int32_t PIN_AUTH_TIMEOUT; + +extern const int32_t DM_AUTH_TYPE_MAX; +extern const int32_t DM_AUTH_TYPE_MIN; +extern const int32_t MIN_PIN_TOKEN; +extern const int32_t MAX_PIN_TOKEN; + + +// need by device_manager_service_impl.cpp +constexpr const char *DM_TAG_DMVERSION = "dmVersion"; +constexpr const char *DM_TAG_EDITION = "edition"; + +class AuthManagerBase : public ISoftbusSessionCallback, + public IHiChainConnectorCallback, + public IDmDeviceAuthCallback { +public: + virtual int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, + const std::string &extra); + + virtual int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); + + virtual int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel, const std::string &extra); + + virtual void OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result); + + virtual void OnSessionClosed(const int32_t sessionId); + + virtual void OnDataReceived(const int32_t sessionId, const std::string message); + + virtual void OnGroupCreated(int64_t requestId, const std::string &groupId); + + virtual void OnMemberJoin(int64_t requestId, int32_t status); + + virtual int32_t EstablishAuthChannel(const std::string &deviceId); + + virtual void StartNegotiate(const int32_t &sessionId); + + virtual void RespNegotiate(const int32_t &sessionId); + + virtual void SendAuthRequest(const int32_t &sessionId); + + virtual int32_t StartAuthProcess(const int32_t &action); + + virtual void StartRespAuthProcess(); + + virtual int32_t CreateGroup(); + + virtual int32_t ProcessPincode(int32_t pinCode); + + virtual std::string GetConnectAddr(std::string deviceId); + + virtual int32_t JoinNetwork(); + + virtual void AuthenticateFinish(); + + virtual bool GetIsCryptoSupport(); + + virtual int32_t SetAuthRequestState(std::shared_ptr authRequestState); + + virtual int32_t SetAuthResponseState(std::shared_ptr authResponseState); + + virtual int32_t GetPinCode(int32_t &code); + + virtual std::string GenerateGroupName(); + + virtual void HandleAuthenticateTimeout(std::string name); + + virtual int32_t GeneratePincode(); + + virtual void ShowConfigDialog(); + + virtual void ShowAuthInfoDialog(bool authDeviceError = false); + + virtual void ShowStartAuthDialog(); + + virtual int32_t OnUserOperation(int32_t action, const std::string ¶ms); + + virtual int32_t SetPageId(int32_t pageId); + + virtual int32_t SetReasonAndFinish(int32_t reason, int32_t state); + + virtual bool IsIdenticalAccount(); + + virtual int32_t RegisterUiStateCallback(const std::string pkgName); + + virtual int32_t UnRegisterUiStateCallback(const std::string pkgName); + + virtual int32_t ImportAuthCode(const std::string &pkgName, const std::string &authCode); + + virtual int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam); + + virtual int32_t RegisterAuthenticationType(int32_t authenticationType); + + virtual int32_t StopAuthenticateDevice(const std::string &pkgName); + + virtual void OnScreenLocked() = 0; + + virtual void HandleDeviceNotTrust(const std::string &udid) = 0; + + virtual int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); + + // New interface added in version 5.1.0 + virtual int32_t GetReason(); + // When switching from the new protocol to the old protocol, the previous parameters + // need to be obtained for use by the old protocol + virtual void GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, + std::map &bindParam); + + // Check if the authManager has been initialized successfully + virtual bool IsAuthManagerConstructSuccess() = 0; + + // Public functions + static std::string ConvertSrcVersion(const std::string &version, const std::string &edition); + static std::string ConvertSinkVersion(const std::string &version); + static int32_t DmGetUserId(int32_t displayId, int32_t targetUserId); + + // Public variables + bool isAuthNewVersion_ = true; +}; + +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_ADAPTER_V2_H diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h new file mode 100644 index 0000000000000000000000000000000000000000..9cf8204c581bd24ed3868b18b6d729ee6d346d17 --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -0,0 +1,326 @@ +/* + * Copyright (c) 2025 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 OHOS_DM_AUTH_MESSAGE_PROCESSOR_V2_H +#define OHOS_DM_AUTH_MESSAGE_PROCESSOR_V2_H + +#include +#include "json_object.h" +#include "crypto_mgr.h" +#include "access_control_profile.h" +#include "deviceprofile_connector.h" + +namespace OHOS { +namespace DistributedHardware { +struct DmAuthContext; +struct DmAccess; + +constexpr const char *DM_TAG_MSG_TYPE = "messageType"; +constexpr const char *DM_TAG_DATA = "data"; // Message data +constexpr const char* DM_TAG_DATA_LEN = "dataLen"; +constexpr const char *DM_TAG_LNN_PUBLICK_KEY = "lnnPublicKey"; +constexpr const char *DM_TAG_TRANSMIT_PUBLICK_KEY = "ephemeralPublicKey"; +constexpr const char *DM_TAG_LNN_CREDENTIAL_ID = "lnnCredentialId"; +constexpr const char *DM_TAG_TRANSMIT_CREDENTIAL_ID = "transmitCredentialId"; +constexpr const char *DM_TAG_AUTH_RESULT = "authResult"; +constexpr const char *DM_TAG_AUTH_TYPE_LIST = "authTypeList"; +constexpr const char *DM_TAG_CURRENT_AUTH_TYPE_IDX = "currentAuthTypeIdx"; + +// IS interface input parameter json format string key +constexpr const char *DM_TAG_METHOD = "method"; +constexpr const char *DM_TAG_DEVICE_ID = "deviceId"; +constexpr const char *DM_TAG_PEER_USER_SPACE_ID = "peerUserSpaceId"; +constexpr const char *DM_TAG_SUBJECT = "subject"; +constexpr const char *DM_TAG_CRED_TYPE = "credType"; +constexpr const char *DM_TAG_KEY_FORMAT = "keyFormat"; +constexpr const char *DM_TAG_ALGORITHM_TYPE = "algorithmType"; +constexpr const char *DM_TAG_PROOF_TYPE = "proofType"; +constexpr const char *DM_TAG_KEY_VALUE = "keyValue"; +constexpr const char *DM_TAG_AUTHORIZED_SCOPE = "authorizedScope"; +constexpr const char *DM_TAG_AUTHRIZED_APP_LIST = "authorizedAppList"; +constexpr const char *DM_TAG_CREDENTIAL_OWNER = "credOwner"; +constexpr const char *DM_AUTH_CREDENTIAL_OWNER = "DM"; +constexpr const char *DM_TAG_SYNC = "syncMessage"; +constexpr const char *DM_TAG_ACCESS = "dmAccess"; +constexpr const char *DM_TAG_PROXY = "proxy"; +constexpr const char *DM_TAG_ACL = "accessControlTable"; +constexpr const char *DM_TAG_ACCESSER = "dmAccesser"; +constexpr const char *DM_TAG_ACCESSEE = "dmAccessee"; +constexpr const char *DM_TAG_SERVICEINFO = "serviceInfo"; +// The local SK information is synchronized to the remote end to construct acl-accesser/accessee. +constexpr const char *DM_TAG_TRANSMIT_SK_ID = "accessAppSKId"; +constexpr const char *DM_TAG_LNN_SK_ID = "accessUserSKId"; +constexpr const char *DM_TAG_TRANSMIT_SK_TIMESTAMP = "accessAppSKTimeStamp"; +constexpr const char *DM_TAG_LNN_SK_TIMESTAMP = "accessUserSKTimeStamp"; +constexpr const char *DM_TAG_USER_ID = "userId"; +constexpr const char* DM_TAG_TOKEN_ID = "tokenId"; +constexpr const char *DM_TAG_ISSUER = "issuer"; + +constexpr const char* APP_THUMBNAIL = "appThumbnail"; +constexpr const char* TAG_DEVICE_VERSION = "deviceVersion"; +constexpr const char* TAG_DEVICE_NAME = "deviceName"; +constexpr const char* TAG_DEVICE_ID_HASH = "deviceIdHash"; +constexpr const char* TAG_USER_ID_HASH = "userIdHash"; +constexpr const char* TAG_ACCOUNT_ID_HASH = "accountIdHash"; +constexpr const char* TAG_TOKEN_ID_HASH = "tokenIdHash"; +constexpr const char* TAG_BUNDLE_NAME = "bundleName"; +constexpr const char* TAG_PEER_BUNDLE_NAME = "peerBundleName"; +constexpr const char* TAG_BIND_LEVEL = "bindLevel"; +constexpr const char* TAG_SESSION_NAME = "sessionName"; +constexpr const char *DM_TAG_ACL_CHECKSUM = "aclCheckSum"; +constexpr const char *DM_TAG_COMPRESS_ORI_LEN = "compressOriLen"; +constexpr const char *DM_TAG_COMPRESS = "compressMsg"; +constexpr const char *DM_TAG_REPLY = "reply"; +constexpr const char *DM_TAG_STATE = "state"; +constexpr const char *DM_TAG_REASON = "reason"; +constexpr const char* DM_TAG_PEER_USER_ID = "peerUserId"; +constexpr const char* DM_TAG_PEER_DISPLAY_ID = "peerDisplayId"; +constexpr const char* DM_TAG_EXTRA_INFO = "extraInfo"; + +constexpr const int32_t DM_HASH_LEN = 32; +constexpr const char* TAG_IS_ONLINE = "isOnline"; +constexpr const char* TAG_IS_AUTHED = "isAuthed"; +constexpr const char* TAG_CREDENTIAL_INFO = "credentialInfo"; + +// Accesser table content is used for ACL synchronization. +constexpr const char* DM_TAG_ACCESSER_DEVICE_ID = "accesserDeviceId"; +constexpr const char* DM_TAG_ACCESSER_USER_ID = "accesserUserId"; +constexpr const char* DM_TAG_ACCESSER_ACOUNT_ID = "accesserAcountId"; +constexpr const char* DM_TAG_ACCESSER_TOKEN_ID = "accesserTokenId"; +constexpr const char* DM_TAG_ACCESSER_SERVICE_NAME = "accesserServiceName"; +constexpr const char* DM_TAG_ACCESSER_BUNDLE_NAME = "accesserBundleName"; +constexpr const char* DM_TAG_ACCESSER_HAP_SIGNATURE = "accesserHapSignature"; +constexpr const char* DM_TAG_ACCESSER_BIND_LEVEL = "accesserBindLevel"; +constexpr const char* DM_TAG_ACCESSER_CREDENTIAL_ID = "accesserCredetialId"; +constexpr const char* DM_TAG_ACCESSER_STATUS = "accesserStatus"; +constexpr const char* DM_TAG_ACCESSER_SK_ID = "accesserSessionKeyId"; +constexpr const char* DM_TAG_ACCESSER_SK_TIMESTAMP = "accesserSKTimeStamp"; + +// Accessee table content is used for ACL synchronization. +constexpr const char* DM_TAG_ACCESSEE_DEVICE_ID = "accesseeDeviceId"; +constexpr const char* DM_TAG_ACCESSEE_USER_ID = "accesseeUserId"; +constexpr const char* DM_TAG_ACCESSEE_ACOUNT_ID = "accesseeAcountId"; +constexpr const char* DM_TAG_ACCESSEE_TOKEN_ID = "accesseeTokenId"; +constexpr const char* DM_TAG_ACCESSEE_SERVICE_NAME = "accesseeServiceName"; +constexpr const char* DM_TAG_ACCESSEE_BUNDLE_NAME = "accesseeBundleName"; +constexpr const char* DM_TAG_ACCESSEE_HAP_SIGNATURE = "accesseeHapSignature"; +constexpr const char* DM_TAG_ACCESSEE_BIND_LEVEL = "accesseeBindLevel"; +constexpr const char* DM_TAG_ACCESSEE_CREDENTIAL_ID = "accesseeCredetialId"; +constexpr const char* DM_TAG_ACCESSEE_STATUS = "accesseeStatus"; +constexpr const char* DM_TAG_ACCESSEE_SK_ID = "accesseeSessionKeyId"; +constexpr const char* DM_TAG_ACCESSEE_SK_TIMESTAMP = "accesseeSKTimeStamp"; + +enum DmMessageType { + // Terminate/Exception Message + MSG_TYPE_UNKNOWN = 0, + MSG_TYPE_AUTH_TERMINATE = 1, + // Normal Message + MSG_TYPE_REQ_ACL_NEGOTIATE = 80, + MSG_TYPE_RESP_ACL_NEGOTIATE = 90, + MSG_TYPE_REQ_USER_CONFIRM = 100, + MSG_TYPE_RESP_USER_CONFIRM = 110, + MSG_TYPE_REQ_PIN_AUTH_START = 120, + MSG_TYPE_RESP_PIN_AUTH_START = 130, + MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE = 121, + MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE = 131, + MSG_TYPE_REQ_CREDENTIAL_EXCHANGE = 140, + MSG_TYPE_RESP_CREDENTIAL_EXCHANGE = 150, + MSG_TYPE_REQ_CREDENTIAL_AUTH_START = 160, + MSG_TYPE_RESP_CREDENTIAL_AUTH_START = 170, + MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE = 161, + MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE = 171, + MSG_TYPE_REQ_DATA_SYNC = 180, + MSG_TYPE_RESP_DATA_SYNC = 190, + MSG_TYPE_AUTH_REQ_FINISH = 200, + MSG_TYPE_AUTH_RESP_FINISH = 201, +}; +// 对齐数据库ACL TABLE字段 +// 注意:修改本结构体 需要同步修改dm_auth_message_processor.cpp中的From/ToJson函数 +struct DmAccessControlTable { + int32_t accessControlId; + int64_t accesserId; + int64_t accesseeId; + std::string deviceId; + std::string sessionKey; + int32_t bindType; + uint32_t authType; + uint32_t deviceType; + std::string deviceIdHash; + int32_t status; + int32_t validPeriod; + int32_t lastAuthTime; + uint32_t bindLevel; +}; + +// Structure used for synchronizing ACL access +// Attention: Modifying this structure requires updating the From/ToJson functions in dm_auth_message_processor.cpp. +struct DmAccessToSync { + std::string deviceName; + // For A->B communication, whether it's the A end or B end, the Accesser object stores + // the A end's deviceId, and the Accessee object stores the B end's deviceId + std::string deviceId; + int32_t userId; + std::string accountId; + uint64_t tokenId; + std::string bundleName; // Stores the PacketName + int32_t bindLevel; // Passed through for business purposes, no custom definition required + int32_t sessionKeyId; // User credential ID + int64_t skTimeStamp; // Used for aging, time is 2 days, user-level credential timestamp +}; + +// json and struct conversion functions +void ToJson(JsonItemObject &itemObject, const DmAccessControlTable &table); +void FromJson(const JsonItemObject &itemObject, DmAccessControlTable &table); +void ToJson(JsonItemObject &itemObject, const DmAccessToSync &table); +void FromJson(const JsonItemObject &itemObject, DmAccessToSync &table); + +class DmAuthMessageProcessor { +public: + using CreateMessageFuncPtr = + int32_t (DmAuthMessageProcessor::*)(std::shared_ptr, JsonObject &jsonObject); + using ParaseMessageFuncPtr = + int32_t (DmAuthMessageProcessor::*)(const JsonObject &, std::shared_ptr); + + DmAuthMessageProcessor(); + ~DmAuthMessageProcessor(); + // Parse the message, and save the parsed information to the context + int32_t ParseMessage(std::shared_ptr context, const std::string &message); + // Create a message, construct the corresponding message based on msgType + std::string CreateMessage(DmMessageType msgType, std::shared_ptr context); + + // Create and send a message + void CreateAndSendMsg(DmMessageType msgType, std::shared_ptr context); + + // Save the session key + int32_t SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyLen); + + // Save the permanent session key to the data profile + int32_t SaveSessionKeyToDP(int32_t &skId); + + // Save the current access control list + int32_t PutAccessControlList(std::shared_ptr context, + DmAccess &access, std::string trustDeviceId); + + // Calculate the checksum for the access control list + bool ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl, + std::vector &accesserStrList, std::vector &accesseeStrList); + + // Extract the access control list (ACL) for message parsing and bus usage. + // If no ACL is available, return an empty string. The returned string is in + // JSON format: {dmversion:x,accesser:[{accesserDeviceId:y,...},...], accessee:{...}} + int32_t GetAclListStr(std::shared_ptr &context, std::string &aclList); +private: + // Internal implementations for various message types + + // Used to encrypt the synchronization message + int32_t EncryptSyncMessage(std::shared_ptr &context, DmAccess &accessSide, std::string &encSyncMsg); + // Parse the authentication start message + int32_t ParseAuthStartMessage(const JsonObject &jsonObject, std::shared_ptr context); + + // Parse the 80 message + int32_t ParseNegotiateMessage(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 90 message + int32_t ParseMessageRespAclNegotiate(const JsonObject &json, std::shared_ptr context); + // Parse the 100 message + int32_t ParseMessageReqUserConfirm(const JsonObject &json, std::shared_ptr context); + // Parse the 110 message + int32_t ParseMessageRespUserConfirm(const JsonObject &json, std::shared_ptr context); + // Parse the 120 message + int32_t ParseMessageReqPinAuthStart(const JsonObject &json, std::shared_ptr context); + // Parse the 130 message + int32_t ParseMessageRespPinAuthStart(const JsonObject &json, std::shared_ptr context); + // Parse the 121 message + int32_t ParseMessageReqPinAuthNegotiate(const JsonObject &json, std::shared_ptr context); + // Parse the 131 message + int32_t ParseMessageRespPinAuthNegotiate(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 140 message + int32_t ParseMessageReqCredExchange(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 150 message + int32_t ParseMessageRspCredExchange(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 161, 170, and 171 messages + int32_t ParseMessageNegotiateTransmit(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 180 message + int32_t ParseMessageSyncReq(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 190 message + int32_t ParseMessageSyncResp(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 200 message + int32_t ParseMessageSinkFinish(const JsonObject &jsonObject, std::shared_ptr context); + // Parse the 201 message + int32_t ParseMessageSrcFinish(const JsonObject &jsonObject, std::shared_ptr context); + + // Create the 80 message + int32_t CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); + // Create the 90 message + int32_t CreateRespNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); + // Create the 100 message + int32_t CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json); + // Create the 110 message + int32_t CreateMessageRespUserConfirm(std::shared_ptr context, JsonObject &json); + // Create the 120 message + int32_t CreateMessageReqPinAuthStart(std::shared_ptr context, JsonObject &json); + // Create the 130 message + int32_t CreateMessageRespPinAuthStart(std::shared_ptr context, JsonObject &json); + // Create the 121 message + int32_t CreateMessageReqPinAuthNegotiate(std::shared_ptr context, JsonObject &json); + // Create the 131 message + int32_t CreateMessageRespPinAuthNegotiate(std::shared_ptr context, JsonObject &json); + // Create the 140 message + int32_t CreateMessageReqCredExchange(std::shared_ptr context, JsonObject &jsonObject); + // Create the 150 message + int32_t CreateMessageRspCredExchange(std::shared_ptr context, JsonObject &jsonObject); + // Create the 160 message + int32_t CreateMessageReqCredAuthStart(std::shared_ptr context, JsonObject &jsonObject); + // Construct the 161, 170, and 171 credential authentication messages + int32_t CreateCredentialNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); + // Construct the 180 and 190 sync messages + int32_t CreateSyncMessage(std::shared_ptr context, JsonObject &jsonObject); + // Create the 190 message + int32_t CreateMessageSyncResp(std::shared_ptr context, JsonObject &jsonObject); + // Create the 200 message + int32_t CreateMessageFinish(std::shared_ptr context, JsonObject &jsonObject); + + // Compress the sync message + std::string CompressSyncMsg(std::string &inputStr); + // Decompress the sync message + std::string DecompressSyncMsg(std::string& compressed, uint32_t oriLen); + // Serialize the ACL + int32_t ACLToStr(DistributedDeviceProfile::AccessControlProfile acl, std::string aclStr); + // Decrypt the 180 and 190 messages + int32_t DecryptSyncMessage(std::shared_ptr &context, + DmAccess &access, std::string &enSyncMsg); + // Parse the sync message + int32_t ParseSyncMessage(std::shared_ptr &context, + DmAccess &access, JsonObject &jsonObject); + + // Convert the accesser_table record in DP to a string + std::string AccesserToStr(DistributedDeviceProfile::AccessControlProfile acl); + // Convert the accessee_table record in DP to a string + std::string AccesseeToStr(DistributedDeviceProfile::AccessControlProfile acl); + std::string Base64Encode(std::string &inputStr); + std::string Base64Decode(std::string &inputStr); + void SetAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::AccessControlProfile &profile); + void SetTransmitAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee); + void SetLnnAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee); + std::shared_ptr cryptoMgr_ = nullptr; + std::unordered_map createMessageFuncMap_; + std::unordered_map paraseMessageFuncMap_; +}; + +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_MESSAGE_PROCESSOR_V2_H \ No newline at end of file diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h new file mode 100644 index 0000000000000000000000000000000000000000..4f6dfd220bd310024264b296599b2470da88b98a --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -0,0 +1,372 @@ +/* + * Copyright (c) 2025 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 OHOS_DM_AUTH_STATE_V2_H +#define OHOS_DM_AUTH_STATE_V2_H + +#include + +#include "access_control_profile.h" +#include "dm_auth_context.h" + +namespace OHOS { +namespace DistributedHardware { + +// 状态类型 +enum class DmAuthStateType { + AUTH_IDLE_STATE = 0, // 设备初始化时 + // source端的状态 + AUTH_SRC_START_STATE = 1, // 用户触发BindTarget + AUTH_SRC_NEGOTIATE_STATE = 2, // 收到软总线回调函数OnSessionOpened,发送80报文 + AUTH_SRC_CONFIRM_STATE = 3, // 收到90授权结果报文,发送100报文 + AUTH_SRC_PIN_NEGOTIATE_START_STATE = 4, // 开始协商PIN码,收到110授权结果报文 或回退 或 90跳转 + AUTH_SRC_PIN_INPUT_STATE = 5, // 输入PIN + AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE = 6, // 超声PIN协商 + AUTH_SRC_PIN_AUTH_START_STATE = 7, // 开始做认证,发送120报文 + AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE = 8, // 收到130认证PIN结果报文,发送121报文 + AUTH_SRC_PIN_AUTH_DONE_STATE = 9, // 收到131认证PIN结果报文,调用processData + AUTH_SRC_CREDENTIAL_EXCHANGE_STATE = 10, // 触发Onfinish回调事件,发送140报文 + AUTH_SRC_CREDENTIAL_AUTH_START_STATE = 11, // 收到150加密报文,发送160报文 + AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE = 12, // 收到170凭据认证报文,发送161报文 + AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE = 13, // 收到171凭据认证报文,回复160报文或者180报文 + AUTH_SRC_DATA_SYNC_STATE = 14, // 收到190报文,发送200报文 + AUTH_SRC_FINISH_STATE = 15, // 收到201报文 + + // sink端的状态 + AUTH_SINK_START_STATE = 50, // 总线触发OnSessionOpened + AUTH_SINK_NEGOTIATE_STATE = 51, // 收到80可信关系协商报文,发送90报文 + AUTH_SINK_CONFIRM_STATE = 52, // 收到100用户授权报文,发送110报文 + AUTH_SINK_PIN_NEGOTIATE_START_STATE = 53, // 开始协商PIN码,CONFIRM_STATE 主动迁移或者 错误回退 + AUTH_SINK_PIN_DISPLAY_STATE = 54, // 生成并显示PIN + AUTH_SINK_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE = 55, // 协商超声PIN状态 (收src端报文)被动触发 或 其他状态主动迁移 进入超声码协商状态 + AUTH_SINK_PIN_AUTH_START_STATE = 56, // 收到120认证PIN报文,发送130报文 + AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE = 57, // 收到121认证PIN报文,发送131报文 + AUTH_SINK_PIN_AUTH_DONE_STATE = 58, // 触发Onfinish回调事件 + AUTH_SINK_CREDENTIAL_EXCHANGE_STATE = 59, // 收到140加密报文,发送150报文 + AUTH_SINK_CREDENTIAL_AUTH_START_STATE = 60, // 收到160凭证认证报文,发送170报文 + AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE = 61, // 收到161凭据协商报文,回复171报文 + AUTH_SINK_DATA_SYNC_STATE = 62, // 收到180同步报文,发送190报文 + AUTH_SINK_FINISH_STATE = 63, // 收到200结束报文, 发送201报文 +}; + +// 凭据添加方式 +enum DmAuthCredentialAddMethod : uint8_t { + DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE = 1, // 生成 + DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT, // 导入 +}; + +// 凭据主体 +enum DmAuthCredentialSubject : uint8_t { + DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY = 1, // 主控 + DM_AUTH_CREDENTIAL_SUBJECT_SUPPLEMENT, // 配件 +}; + +// 凭据与账号关联 +enum DmAuthCredentialAccountRelation : uint8_t { + DM_AUTH_CREDENTIAL_ACCOUNT_RELATED = 1, // 账号相关 + DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED, // 账号无关 +}; + +// 秘钥类型 +enum DmAuthKeyFormat : uint8_t { + DM_AUTH_KEY_FORMAT_SYMM_IMPORT = 1, // 对称密钥(仅在导入下支持) + DM_AUTH_KEY_FORMAT_ASYMM_IMPORT, // 非对称密钥公钥(仅在导入下支持) + DM_AUTH_KEY_FORMAT_ASYMM_GENERATE, // 非对称密钥(仅在生成下支持) + DM_AUTH_KEY_FORMAT_X509, // X509证书 +}; + +// 算法类型 +enum DmAuthAlgorithmType : uint8_t { + DM_AUTH_ALG_TYPE_AES256 = 1, // AES256 + DM_AUTH_ALG_TYPE_AES128, // AES128 + DM_AUTH_ALG_TYPE_P256, // P256 + DM_AUTH_ALG_TYPE_ED25519 // ED25519 +}; + +// 凭据证明类型 +enum DmAuthCredentialProofType : uint8_t { + DM_AUTH_CREDENTIAL_PROOF_PSK = 1, // PSK + DM_AUTH_CREDENTIAL_PROOF_PKI, // PKI +}; + +class DmAuthState { +public: + virtual ~DmAuthState() {}; + virtual DmAuthStateType GetStateType() = 0; + virtual int32_t Action(std::shared_ptr context) = 0; // 执行状态对应的action动作 + void SyncAclList(std::shared_ptr context, + std::string credId, int32_t sessionKeyId, int32_t aclId); + void SourceFinish(std::shared_ptr context); + void SinkFinish(std::shared_ptr context); + static bool IsScreenLocked(); + static int32_t GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut); + static void HandleAuthenticateTimeout(std::shared_ptr context, std::string name); +protected: +}; + +class AuthSrcConfirmState : public DmAuthState { +public: + virtual ~AuthSrcConfirmState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + int32_t DoPinAuth(std::shared_ptr context); +}; + +class AuthSinkStatePinAuthComm { +public: + static void GeneratePincode(std::shared_ptr context); + static int32_t ShowAuthInfoDialog(std::shared_ptr context); +private: + static void HandleSessionHeartbeat(std::shared_ptr context, std::string name); +}; + +class AuthSinkConfirmState : public DmAuthState { +public: + virtual ~AuthSinkConfirmState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + int32_t ShowConfigDialog(std::shared_ptr context); +}; + +class AuthSrcPinNegotiateStartState : public DmAuthState { +public: + virtual ~AuthSrcPinNegotiateStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcPinInputState : public DmAuthState { +public: + virtual ~AuthSrcPinInputState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + int32_t ShowStartAuthDialog(std::shared_ptr context); +}; + +class AuthSinkPinNegotiateStartState : public DmAuthState { +public: + virtual ~AuthSinkPinNegotiateStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkPinDisplayState : public DmAuthState { +public: + virtual ~AuthSinkPinDisplayState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcPinNegotiateUltrasonicPinState : public DmAuthState { +public: + virtual ~AuthSrcPinNegotiateUltrasonicPinState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkPinNegotiateUltrasonicPinState : public DmAuthState { +public: + virtual ~AuthSinkPinNegotiateUltrasonicPinState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcPinAuthStartState : public DmAuthState { +public: + virtual ~AuthSrcPinAuthStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + int32_t ShowStartAuthDialog(std::shared_ptr context); // 向用户显示PIN输入框 +}; + +class AuthSinkPinAuthStartState : public DmAuthState { +public: + virtual ~AuthSinkPinAuthStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcPinAuthMsgNegotiateState : public DmAuthState { +public: + virtual ~AuthSrcPinAuthMsgNegotiateState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkPinAuthMsgNegotiateState : public DmAuthState { +public: + virtual ~AuthSinkPinAuthMsgNegotiateState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSinkPinAuthDoneState : public DmAuthState { +public: + virtual ~AuthSinkPinAuthDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +// 收到131认证PIN结果报文,调用processData +class AuthSrcPinAuthDoneState : public DmAuthState { +public: + virtual ~AuthSrcPinAuthDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcStartState : public DmAuthState { +public: + virtual ~AuthSrcStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +class AuthSrcNegotiateStateMachine : public DmAuthState { +public: + virtual ~AuthSrcNegotiateStateMachine() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +// 凭据协商阶段,AuthSrcCredentialExchangeState AuthSinkCredentialExchangeState AuthSrcCredentialAuthStartState +// 中间类 封装业务相关的公共接口 +class AuthCredentialAgreeState : public DmAuthState { +public: + virtual ~AuthCredentialAgreeState() {}; +protected: + // 生成凭据协商状态下的authParams的json格式字符串 + std::string CreateAuthParamsString(DmAuthScope authorizedScope, DmAuthCredentialAddMethod method, + const std::shared_ptr &authContext); + int32_t GenerateCredIdAndPublicKey(DmAuthScope authorizedScope, std::shared_ptr &authContext); + // 协商凭据得到协商凭据Id + int32_t AgreeCredential(DmAuthScope authorizedScope, std::shared_ptr &authContext); +}; + +// 收到131报文,发送140报文 +class AuthSrcCredentialExchangeState : public AuthCredentialAgreeState { +public: + virtual ~AuthSrcCredentialExchangeState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +// AuthSinkCredentialExchangeState 收到140报文发送150报文 +class AuthSinkCredentialExchangeState : public AuthCredentialAgreeState { +public: + virtual ~AuthSinkCredentialExchangeState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +// AuthSrcCredentialAuthStartState, // 收到150加密报文,发送160报文 +class AuthSrcCredentialAuthStartState : public AuthCredentialAgreeState { +public: + virtual ~AuthSrcCredentialAuthStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; +// 收到170凭据认证报文,解析ontransmit,回复161报文 +class AuthSrcCredentialAuthNegotiateState : public DmAuthState { +public: + virtual ~AuthSrcCredentialAuthNegotiateState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; // 执行状态对应的action动作 +}; + +// 收到171凭据认证报文 发送160/180 报文 +class AuthSrcCredentialAuthDoneState : public DmAuthState { +public: + virtual ~AuthSrcCredentialAuthDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; // 执行状态对应的action动作 +}; + +// 收到160凭证认证报文 发送170报文 +class AuthSinkCredentialAuthStartState : public DmAuthState { +public: + virtual ~AuthSinkCredentialAuthStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; // 执行状态对应的action动作 +}; + +// 收到161凭据协商报文 并回复171报文 +class AuthSinkCredentialAuthNegotiateState : public DmAuthState { +public: + virtual ~AuthSinkCredentialAuthNegotiateState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; // 执行状态对应的action动作 +}; + +// 收到80报文,准备发送90报文 +class AuthSinkNegotiateStateMachine : public DmAuthState { +public: + virtual ~AuthSinkNegotiateStateMachine() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; + +private: + int32_t RespQueryAcceseeIds(std::shared_ptr context); + bool AclCompareTwoIds(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + bool AclCompareFourIds(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); + int32_t ProcRespNegotiate5_1_0(std::shared_ptr context); + int32_t GetAuthCredentialInfo(std::shared_ptr context); + void MatchFallBackCandidateList(std::shared_ptr context, DmAuthType authType); + int64_t GenRequestId(); + bool IsAuthCodeReady(std::shared_ptr context); + void NegotiatePinAuthType(std::shared_ptr context); +}; + + +// AuthSinkDataSyncState // 收到180同步报文,发送190报文 +class AuthSinkDataSyncState : public DmAuthState { + public: + virtual ~AuthSinkDataSyncState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +// AuthSrcDataSyncState // 收到190报文,发送200报文 +class AuthSrcDataSyncState : public DmAuthState { + public: + virtual ~AuthSrcDataSyncState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +// AuthSinkFinishState // 收到200结束报文,发送201 sink结束 +class AuthSinkFinishState : public DmAuthState { + public: + virtual ~AuthSinkFinishState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +// AuthSrcFinishState // 收到201结束报文 source结束 +class AuthSrcFinishState : public DmAuthState { + public: + virtual ~AuthSrcFinishState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_STATE_V2_H \ No newline at end of file diff --git a/services/implementation/include/authentication_v2/dm_auth_state_machine.h b/services/implementation/include/authentication_v2/dm_auth_state_machine.h new file mode 100644 index 0000000000000000000000000000000000000000..349aa708d0b0adfe1f3e5d47bff68dbddafec049 --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_state_machine.h @@ -0,0 +1,117 @@ +/* + * Copyright (c) 2025 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 OHOS_DM_AUTH_STATE_MACHINE_V2_H +#define OHOS_DM_AUTH_STATE_MACHINE_V2_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dm_auth_state.h" + +namespace OHOS { +namespace DistributedHardware { + +// Define the state transition table type +using StateTransitionTable = std::map>; + +enum DmEventType { + ON_TRANSMIT = 0, + ON_SESSION_KEY_RETURNED, + ON_REQUEST, + ON_FINISH, + ON_ERROR, + + ON_TIMEOUT, + ON_USER_OPERATION, + ON_FAIL, + ON_SCREEN_LOCKED, +}; + +class DmAuthStateMachine { +public: + DmAuthStateMachine(std::shared_ptr context); + ~DmAuthStateMachine(); + + // Notify state transition, execute the corresponding action for the state, and handle exceptions + // only allowed to be called within OnDataReceived + int32_t TransitionTo(std::shared_ptr state); + + // Wait for the expected event within the action, block until the expected event is completed or + // an exception occurs, returning the actual event that occurred (only allowed to be called within actions) + DmEventType WaitExpectEvent(DmEventType eventType); + + // Notify the completion of an event, passing the event enumeration + // (only allowed to be called when the event is triggered). If it's an exception event, + // record it in the context's reason or reply. + void NotifyEventFinish(DmEventType eventType); + + DmAuthStateType GetCurState(); + + // Stop the thread + void Stop(); + +private: + // Loop to wait for state transitions and execute actions + void Run(std::shared_ptr context); + void InsertSrcTransTable(); + void InsertSinkTransTable(); + + // Fetch the current state and execute it + std::optional> FetchState(); + + void SetCurState(DmAuthStateType state); + + bool CheckStateTransitValid(DmAuthStateType nextState); + + DmAuthStateType curState_; + + // State transition table for normal state transitions (all state transitions to the Finish state are valid) + StateTransitionTable stateTransitionTable_; + + std::queue eventQueue_; + + // Set of exception events + std::set exceptionEvent_; + + // Thread for state machine execution + std::thread thread_; + + // Atomic flag to control the state machine's running state + std::atomic running_; + + // Queue for storing states + std::queue> statesQueue_; + + // Synchronization primitives + std::mutex stateMutex_; + std::condition_variable stateCv_; + std::mutex eventMutex_; + std::condition_variable eventCv_; + + // Direction of authentication + DmAuthDirection direction_; +}; + +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_STATE_MACHINE_V2_H