From 2c8a6d3c8e2f83446c66c18674c9da57f62eff36 Mon Sep 17 00:00:00 2001 From: ZHANGHE24 <9525444+zhanghe24@user.noreply.gitee.com> Date: Mon, 24 Feb 2025 11:08:41 +0800 Subject: [PATCH 001/382] feat: state machine --- .../include/authentication_v2/auth_context.h | 176 ++++++++++++++++ .../include/authentication_v2/auth_manager.h | 55 +++++ .../auth_message_processor.h | 39 ++++ .../include/authentication_v2/auth_state.h | 35 ++++ .../authentication_v2/auth_state_machine.h | 92 ++++++++ .../src/authentication_v2/README.md | 120 +++++++++++ .../src/authentication_v2/auth_manager.cpp | 38 ++++ .../auth_message_processor.cpp | 31 +++ .../auth_stages/auth_acl.cpp | 34 +++ .../auth_stages/auth_confirm.cpp | 31 +++ .../auth_stages/auth_credential.cpp | 43 ++++ .../auth_stages/auth_negotiate.cpp | 35 ++++ .../auth_stages/auth_pin_auth.cpp | 35 ++++ .../authentication_v2/auth_state_machine.cpp | 197 ++++++++++++++++++ 14 files changed, 961 insertions(+) create mode 100644 services/implementation/include/authentication_v2/auth_context.h create mode 100644 services/implementation/include/authentication_v2/auth_manager.h create mode 100644 services/implementation/include/authentication_v2/auth_message_processor.h create mode 100644 services/implementation/include/authentication_v2/auth_state.h create mode 100644 services/implementation/include/authentication_v2/auth_state_machine.h create mode 100644 services/implementation/src/authentication_v2/README.md create mode 100644 services/implementation/src/authentication_v2/auth_manager.cpp create mode 100644 services/implementation/src/authentication_v2/auth_message_processor.cpp create mode 100644 services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp create mode 100644 services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp create mode 100644 services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp create mode 100644 services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp create mode 100644 services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp create mode 100644 services/implementation/src/authentication_v2/auth_state_machine.cpp diff --git a/services/implementation/include/authentication_v2/auth_context.h b/services/implementation/include/authentication_v2/auth_context.h new file mode 100644 index 000000000..38b52497c --- /dev/null +++ b/services/implementation/include/authentication_v2/auth_context.h @@ -0,0 +1,176 @@ +/* + * 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_H +#define OHOS_DM_AUTH_CONTEXT_H + +#include +#include + +namespace OHOS { +namespace DistributedHardware { + +// 状态类型 +enum DmAuthStateType : int32_t { + AuthIdleState = 0, // 设备初始化时 + // source端的状态 + AuthSrcStartState, // 用户触发BindTarget + AuthSrcNegotiateState, // 收到软总线回调函数OnSessionOpened,发送80报文 + AuthSrcConfirmState, // 收到90授权结果报文,发送100报文 + AuthSrcPinAuthStartState, // 收到110授权结果报文,发送120报文 + AuthSrcPinAuthMsgNegotiateState, // 收到130认证PIN结果报文,发送121报文 + AuthSrcPinAuthDoneState, // 收到131认证PIN结果报文,调用processData + AuthSrcCredentialExchangeState, // 触发Onfinish回调事件,发送140报文 + AuthSrcCredentialAuthStartState, // 收到150加密报文,发送160报文 + AuthSrcCredentialAuthNegotiateState, // 收到170凭据认证报文,发送161报文 + AuthSrcCredentialAuthDoneState, // 收到171凭据认证报文 + AuthSrcDataSyncState, // 触发Onfinish回调事件,发送180报文 + AuthSrcFinishState, // 收到190报文,发送200报文 + + // sink端的状态 + AuthSinkStartState = 50, // 总线触发OnSessionOpened + AuthSinkNegotiateState, // 收到80可信关系协商报文,发送90报文 + AuthSinkConfirmState, // 收到100用户授权报文,发送110报文 + AuthSinkPinAuthStartState, // 收到120认证PIN报文,发送130报文 + AuthSinkPinAuthMsgNegotiateState, // 收到121认证PIN报文,发送131报文 + AuthSinkPinAuthDoneState, // 触发Onfinish回调事件 + AuthSinkCredentialExchangeState, // 收到140加密报文,发送150报文 + AuthSinkCredentialAuthStartState, // 收到160凭证认证报文,发送170报文 + AuthSinkCredentialAuthNegotiateState, // 收到161凭据协商报文 + AuthSinkCredentialAuthDoneState, // 触发Onfinish回调事件 + AuthSinkDataSyncState, // 收到180同步报文,发送190报文 + AuthSinkFinishState, // 收到200结束报文 +}; + +// 报文类型 +enum DmMsgType : int32_t { + // 终止/异常报文 + MSG_TYPE_UNKNOWN = 0, + MSG_TYPE_AUTH_TERMINATE = 1, + // 正常报文 + 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_FINISH = 200, +}; + +// PIN码认证类型 +enum DmAuthType : int32_t { + AUTH_TYPE_PIN_SHOW = 0, // 弹PIN码 + AUTH_TYPE_PIN_ULTRASONIC, // 超声PIN码 + AUTH_TYPE_PIN_IMPORT, // 导入PIN码 +}; + +enum DmAuthDirection { + DM_AUTH_SOURCE = 0, + DM_AUTH_SINK, +}; + +enum BindType { + DM_AUTH_USERID = 1, + DM_AUTH_SYSTEM_SERVICE, + DM_AUTH_APP_SERVICE, + DM_AUTH_DEVICEID, +}; + +struct PeerTargetAddress { + std::string peerBrMacAddress; //一碰投使用,直接可以蓝牙建链 + std::string peerBleMacAddress; //一碰投使用,直接可以蓝牙建链 + std::string peerWifiMacAddress; //一碰投使用,直接可以蓝牙建链 + std::string peerActionMacAddress; //一碰投使用,直接可以蓝牙建链 + std::string peerWifiChannel; //一碰投使用 + std::string peerWifiIp; //一碰投使用 + uint16_t peerWifiPort; //一碰投使用 +}; + +struct PeerTarget { + BindType peerType; // 绑定目标的类型 + std::string peerDeivceId; // 兼容性,UDID,哈希值,PUBLIC权限 + int64_t peerServiceId; // Serviceid,主推,PUBLIC权限 + uint64_t peerSaTokenId; // SA-TokenID,过度,SA使用,校验系统权限 + std::string peerBundleName; //过度,同厂商使用,PUBLIC权限 + PeerTargetAddress PeerTargetAddress; //通信对象的物理地址,校验系统权限 +}; + +struct DmAccess { + std::string deviceName; + int32_t deviceType; // PC、mobile、手表、大屏等类型,为业务透传的数据,无需自定义 + std::string deviceId; // A->B, 无论是A端还是B端,Accesser对象都存A端的deviceId,Accessee对象都存B端的deviceId + int32_t userId; + std::string accountId; + uint64_t tokenId; + std::string bundleName; // 存PacketName + int64_t serviceId; // 保留字段,后续会使用 + std::string accesserHapSignature; + int32_t bindLevel; // 为业务透传数据,无需自定义 + std::string publicKey; // T公钥长度 + int32_t userCredentialId; // 用户凭据ID + int32_t credentialId; // 应用凭据ID + int32_t status; // 表示服务为前台还是后台,业务透传,只保存 + int32_t sessionKeyId; // 作为秘钥派送的材料,在总线中取出sk + int64_t skTimeStamp; // 老化,时间为2天 + bool isAuthed; + bool isOnline; + std::string dmVersion; // 格式为 5.0.3 + std::string aclList; //可信关系列表,用于数据老化 KV格式 + std::string credentialInfos; //凭据信息(点对点,同账号,..) 只保存凭据类型 kv结构 + std::string extraInfo; //可扩展字段,kv结构 +}; + +struct DmAuthContext { + DmMsgType msgType; // 报文类型,枚举MsgType + int32_t sessionId; // 总线传输会话ID + int64_t requestId; // hichain认证ID + UiAction authResult; // 授权结果(使用0、1、6,即单次,取消和始终信任,enum UiAction) + DmAuthType authType; // 认证方式,弹pin码、超声pin码、导入pin码 + int32_t authFailTimes; // 认证失败次数,查过3次结束认证 + int32_t pinCode; // 保存业务导入的pin码 + int32_t connDelayCloseTime; // 链路延迟释放时间, 授权结束后不自动断链(有业务需要使用)保留字段 + int32_t reason; // 本端失败的原因 + int32_t reply; // 对端回复的结果 引用common/include/dm_constants.h,有新的错误码可新增 + bool normalFinishAuth; // 标识认证过程是否正常结束 + bool authenticating; // 标识正在认证中 + std::string pkgName; // 业务传入的标识,业务自定义,有被仿冒的风险 + std::string importCodeBundleName; // 导入pin码的包名,从系统中读取,与acceserBundleName一致 + std::string appThumbnail; // 应用图标 + std::string appOperation; // 授权弹框中显示本次绑定用于什么操作 + std::string customData; // 业务自定义字段,详细提示用户本次绑定的操作 + std::string extraInfo; // 可扩展字段,kv结构 + DmAuthDirection direction; // 标识认证方向 + ProcessInfo processInfo; // 进程信息 + PeerTarget peerTarget; // 对端目标的信息 + DmAccess accesser; + DmAccess accessee; + std::multimap proxy; // 前面是accesser,后面是accessee + + std::shared_ptr authStateMachine; // 状态机 +}; + +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_CONTEXT_H 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 000000000..cfed4fc49 --- /dev/null +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -0,0 +1,55 @@ +/* + * 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_H +#define OHOS_DM_AUTH_MANAGER_H + +#include + +#include "auth_context.h" + +namespace OHOS { +namespace DistributedHardware { + +class AuthManager { +public: + void SetAuthContext(std::shared_ptr context); + + std::shared_ptr GetAuthContext(); + + // 各类事件触发的函数实现(虚函数) + +private: + // 上下文(需在该层级进行创建) + std::shared_ptr context_; +}; + +class AuthSrcManager : public AuthManager { +public: + // 各类事件触发的函数实现(继承) +private: + +}; + +class AuthSinkManager : public AuthManager { +public: + // 各类事件触发的函数实现(继承) +private: + +}; + +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_MANAGER_H \ No newline at end of file diff --git a/services/implementation/include/authentication_v2/auth_message_processor.h b/services/implementation/include/authentication_v2/auth_message_processor.h new file mode 100644 index 000000000..2a93a5262 --- /dev/null +++ b/services/implementation/include/authentication_v2/auth_message_processor.h @@ -0,0 +1,39 @@ +/* + * 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_H +#define OHOS_DM_AUTH_MESSAGE_PROCESSOR_H + +#include + +#include "auth_context.h" + +namespace OHOS { +namespace DistributedHardware { + +class AuthMessageProcessor { +public: + // 解析报文,返回值为错误码,实际解析出来的信息保存到context中 + int32_t ParseMessage(std::shared_ptr context, const std::string &message); + // 创建报文,入参data可为空,构造对应msgType的报文,返回值为json格式报文的字符串 + std::string CreateMessage(DmMsgType msgType, std::shared_ptr context, const uint8_t *data, uint32_t dataLen); +private: + // 内部各类报文的实现 + +}; + +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_MESSAGE_PROCESSOR_H \ No newline at end of file diff --git a/services/implementation/include/authentication_v2/auth_state.h b/services/implementation/include/authentication_v2/auth_state.h new file mode 100644 index 000000000..6e17a2cc1 --- /dev/null +++ b/services/implementation/include/authentication_v2/auth_state.h @@ -0,0 +1,35 @@ +/* + * 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_H +#define OHOS_DM_AUTH_STATE_H + +#include + +#include "auth_context.h" + +namespace OHOS { +namespace DistributedHardware { + +class AuthState { +public: + virtual ~AuthState() {}; // TODO: 确认是否有状态重置那些操作 + virtual DmAuthStateType GetStateType() = 0; + virtual int32_t Action(std::shared_ptr context) = 0; // 执行状态对应的action动作 +}; + +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_STATE_H \ No newline at end of file diff --git a/services/implementation/include/authentication_v2/auth_state_machine.h b/services/implementation/include/authentication_v2/auth_state_machine.h new file mode 100644 index 000000000..365ef4e62 --- /dev/null +++ b/services/implementation/include/authentication_v2/auth_state_machine.h @@ -0,0 +1,92 @@ +/* + * 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_H +#define OHOS_DM_AUTH_STATE_MACHINE_H + +#include +#include +#include +#include +#include +#include +#include + +#include "auth_state.h" +#include "auth_context.h" + +namespace OHOS { +namespace DistributedHardware { + +// 事件等待超时时间 +constexpr const int EVENT_TIMEOUT = 5000; // 5000 毫秒 = 5 秒 + +// 定义状态迁移表类型 +using StateTransitionTable = std::map>; + +enum EventType { + ON_TRANSMIT = 0, + ON_SESSION_KEY_RETURNED, + ON_REQUEST, + ON_FINISH, + ON_ERROR, + ON_SCREEN_LOCKED, // 锁屏 +}; + +class AuthStateMachine { +public: + AuthStateMachine() = delete; + AuthStateMachine(std::shared_ptr context); + ~AuthStateMachine(); + + // 通知状态迁移,执行状态对应具体action与异常处理(只允许在OnDataReceived中调用) + int32_t TransitionTo(std::shared_ptr state); + // action内部的期望事件,用于阻塞,当等到期望事件完成时,返回成功,而等到其他异常,则返回失败(只允许在action中调用) + bool WaitExpectEvent(EventType eventType); + // 事件完成调用,传事件枚举(只允许在事件触发中调用),如果是异常事件,需在context的reason或者reply记录 + void NotifyEventFinish(EventType eventType); + // 获取当前状态 + DmAuthStateType GetCurState(); +private: + // 循环等待状态转移,执行action + void Run(std::shared_ptr context); + // 停止线程 + void Stop(); + // 获取状态,进行执行 + std::optional> FetchState(); + // 设置当前状态 + void SetCurState(DmAuthStateType state); + // 检验下一状态迁移合法性 + bool CheckStateTransitValid(DmAuthStateType nextState); + + // 存储当前状态 + DmAuthStateType curState_; + // 正常状态迁移表,但所有状态切换到Finish状态是合法的 + StateTransitionTable stateTransitionTable_; + + // 实际事件 + EventType actualEventType_; + std::thread thread_; + std::atomic running_; + std::queue> statesQueue_; + // 同步原语 + std::mutex mutex_; + std::condition_variable stateCv_; + std::condition_variable eventCv_; +}; + +} // namespace DistributedHardware +} // namespace OHOS +#endif // OHOS_DM_AUTH_STATE_MACHINE_H diff --git a/services/implementation/src/authentication_v2/README.md b/services/implementation/src/authentication_v2/README.md new file mode 100644 index 000000000..050a6e657 --- /dev/null +++ b/services/implementation/src/authentication_v2/README.md @@ -0,0 +1,120 @@ +1. source和sink的状态机(枚举) +2. 使用sessionId做src端的状态机资源隔离 +3. 实现状态管理类 + 1) 使用transitionTo进行状态迁移 + 2) 对于状态内部,会有action + +##### source +```C++ +// 业务初始化 ->S0 +S0:AuthSrcIdleState // 用户触发BindTarget (S0->S1) +S1:AuthSrcStartState // 收到软总线回调函数OnSessionOpened (S1->S2) +S2:AuthSrcNegotiateState // 收到90协商回复报文 (S2->S3) +S3:AuthSrcConfirmState // 收到110授权结果报文 (S3->S4) +S4:AuthSrcPinAuthStartState // 收到130认证PIN结果报文 (S4->S5) +S5:AuthSrcPinAuthMsgNegotiateState // 收到131认证PIN结果报文(S5->S6) +S6:AuthSrcPinAuthDoneState // 触发Onfinish回调事件 (S6->S7) +S7:AuthSrcCredentialExchangeState // 收到150加密报文 (S7->S8) +S8:AuthSrcCredetialAuthStartState // 收到170凭据认证报文 (S8->S9) +S9:AuthSrcCredetialAuthNegotiateState // 收到171凭据认证报文 (S9->S10) +S10:AuthSrcCredetialAuthDoneState // 触发Onfinish回调事件 (S10->S11) +S11:AuthSrcDataSyncState // 收到190同步报文 (S11->S12) +S12:AuthSrcFinishState + +异常: +1、IPC接口StopAuthenticateDevice触发 // 事件触发 +2、收到MSG_TYPE_REQ_AUTH_TERMINATE +3、各状态下流程超时(丢包) +4、锁屏 +5、参数不合法 +6、pin码输入超时 +7、pin码输入错误(3次前,重回状态,3次后,S8) +以上异常都会让任意状态迁移到S8 + +重点:使用sessionId做src端的状态机资源隔离 + +--- +class AuthSrcStateMachinePool +存储多个状态机实例(AuthSrcStateMachine) +成员函数: +get和set接口(sessionId入参) +成员变量: +使用sessionId隔离多份AuthSrcStateMachine + +--- +class AuthSrcStateMachine +1、提供context上下文存储(设置,获取) +2、操作当前状态(设置、获取(打印)) +3、状态迁移检验功能(下一状态是否在列表中) +4、提供transitionTo函数(事件触发 - 用于事件发生时调用) + +成员变量: +context 上下文 +AuthSrcState 状态 + +--- +class AuthSrcState +Source端的状态基类,提供handleEvent函数: + 1)enter:状态检验 + 2)action:状态迁移时需要做的动作 + 3)exit:状态切换 + +每个state都会继承自改基类,做以上4个函数的具体实现 +``` + +##### sink +```C++ +// 业务初始化 ->S0 +S0:AuthSinkIdleState // 总线触发OnSessionOpened (S0->S1) +S1:AuthSinkStartState // 收到80可信关系协商报文 (S1->S2) +S2:AuthSinkNegotiateState // 收到100用户授权报文 (S2->S3) +S3:AuthSinkConfirmState // 收到120认证PIN报文 (S3->S4) +S4:AuthSinkPinAuthStartState // 收到121认证PIN报文 (S4->S5) +S5: AuthSinkPinAuthMsgNegotiateState // 触发Onfinish回调事件 (S5->S6) +S6: AuthSinkPinAuthDoneState // 收到140加密报文 (S6->S7) +S7:AuthSinkCredentialExchangeState // 收到160凭证认证报文 (S7->S8) +S8:AuthSinkCredetialAuthStartState // 收到161凭据协商报文 (S8->S9) +S9:AuthSinkCredetialAuthNegotiateState // 触发Onfinish回调事件 (S9->S10) +S10: AuthSinkCredetialAuthDoneState // 收到180同步报文 (S10->S11) +S11:AuthSinkDataSyncState // 收到200结束报文 (S11->S12) +S12:AuthSinkFinishState + +异常:(扩展性) +1、IPC接口StopAuthenticateDevice触发 +2、收到MSG_TYPE_REQ_AUTH_TERMINATE +3、各状态下流程超时(丢包) +4、锁屏 +5、参数不合法 +6、pin码输入超时 +7、pin码输入错误(3次前,重回状态,3次后,S8) +8、周边依赖crush => 超时,错误=>异常 + +--- +class AuthSinkStateMachinePool +存储多个状态机实例(AuthSinkStateMachine) +成员函数: +get和set接口(sessionId入参) +成员变量: +使用sessionId隔离多份AuthSinkStateMachine + +--- +class AuthSinkStateMachine +1、提供context上下文存储(设置,获取) +2、操作当前状态(设置、获取(打印)) +3、状态迁移检验功能(下一状态是否在列表中) +4、提供transitionTo函数(事件触发 - 用于事件发生时调用) + +成员变量: +context 上下文 +AuthSinkState 状态 + +--- +class AuthSinkState +Sink端的状态基类,提供transitionTo函数: + 1)enter:状态检验 + 2)action:状态迁移时需要做的动作 + 3)exit:状态切换 + +每个state都会继承自改基类,做以上4个函数的具体实现 + +``` diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp new file mode 100644 index 000000000..05557990d --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -0,0 +1,38 @@ +/* + * 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. + */ + +#include "auth_manager.h" + +namespace OHOS { +namespace DistributedHardware { + +void AuthManager::SetAuthContext(std::shared_ptr context) +{ + this->context_ = context; +} + +std::shared_ptr AuthManager::GetAuthContext() +{ + return this->context_; +} + +// 各类事件触发的函数实现(子类继承实现) +// AuthSrcManager + +// AuthSinkManager + + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_message_processor.cpp b/services/implementation/src/authentication_v2/auth_message_processor.cpp new file mode 100644 index 000000000..89dc6726b --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_message_processor.cpp @@ -0,0 +1,31 @@ +/* + * 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. + */ + +#include "auth_message_processor.h" + +namespace OHOS { +namespace DistributedHardware { + + +// 解析报文,返回值为错误码,实际解析出来的信息保存到context中 +int32_t AuthMessageProcessor::ParseMessage(std::shared_ptr context, const std::string &message); +// 创建报文,入参data可为空,构造对应msgType的报文,返回值为json格式报文的字符串 +std::string AuthMessageProcessor::CreateMessage(DmMsgType msgType, std::shared_ptr context, const uint8_t *data, uint32_t dataLen); + +// 内部各类报文的实现 + + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp new file mode 100644 index 000000000..b699a81b3 --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -0,0 +1,34 @@ +/* + * 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. + */ + +#include "auth_state.h" + +namespace OHOS { +namespace DistributedHardware { + +/* +数据同步,ACL老化与保存(180、190和200报文处理) +source端状态: +AuthSrcDataSyncState, // 触发Onfinish回调事件,发送180报文 +AuthSrcFinishState, // 收到190报文,发送200报文 + +sink端状态: +AuthSinkDataSyncState, // 收到180同步报文,发送190报文 +AuthSinkFinishState, // 收到200结束报文 + +*/ + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp new file mode 100644 index 000000000..f039d61a2 --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -0,0 +1,31 @@ +/* + * 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. + */ + +#include "auth_state.h" + +namespace OHOS { +namespace DistributedHardware { + +/* +用户授权(100和110报文处理) +source端状态: +AuthSrcConfirmState, // 收到90授权结果报文,发送100报文 + +sink端状态: +AuthSinkConfirmState, // 收到100用户授权报文,发送110报文 +*/ + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp new file mode 100644 index 000000000..f235af880 --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -0,0 +1,43 @@ +/* + * 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. + */ + +#include "auth_state.h" + +namespace OHOS { +namespace DistributedHardware { + +/* +凭据生成(140和150报文处理) +source端状态: +AuthSrcCredentialExchangeState, // 触发Onfinish回调事件,发送140报文 + +sink端状态: +AuthSinkCredentialExchangeState, // 收到140加密报文,发送150报文 + +凭据协商(160和170报文处理、161和171报文处理) +source端状态: +AuthSrcCredentialAuthStartState, // 收到150加密报文,发送160报文 +AuthSrcCredentialAuthNegotiateState, // 收到170凭据认证报文,发送161报文 +AuthSrcCredentialAuthDoneState, // 收到171凭据认证报文 + +sink端状态: +AuthSinkCredentialAuthStartState, // 收到160凭证认证报文,发送170报文 +AuthSinkCredentialAuthNegotiateState, // 收到161凭据协商报文 +AuthSinkCredentialAuthDoneState, // 触发Onfinish回调事件 + +*/ + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp new file mode 100644 index 000000000..973006c4b --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -0,0 +1,35 @@ +/* + * 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. + */ + +#include "auth_state.h" + +namespace OHOS { +namespace DistributedHardware { + +/* +能力协商(80和90报文处理) +source端状态: +AuthIdleState, // 设备初始化时, 无需实现 +AuthSrcStartState, // 用户触发BindTarget +AuthSrcNegotiateState, // 收到软总线回调函数OnSessionOpened,发送80报文 + +sink端状态: +AuthIdleState, // 设备初始化时, 无需实现 +AuthSinkStartState, // 总线触发OnSessionOpened +AuthSinkNegotiateState, // 收到80可信关系协商报文,发送90报文 +*/ + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp new file mode 100644 index 000000000..0ca65e616 --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -0,0 +1,35 @@ +/* + * 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. + */ + +#include "auth_state.h" + +namespace OHOS { +namespace DistributedHardware { + +/* +pin码认证(120和130报文处理、121和131报文处理) +source端状态: +AuthSrcPinAuthStartState, // 收到110授权结果报文,发送120报文 +AuthSrcPinAuthMsgNegotiateState, // 收到130认证PIN结果报文,发送121报文 +AuthSrcPinAuthDoneState, // 收到131认证PIN结果报文,调用processData + +sink端状态: +AuthSinkPinAuthStartState, // 收到120认证PIN报文,发送130报文 +AuthSinkPinAuthMsgNegotiateState, // 收到121认证PIN报文,发送131报文 +AuthSinkPinAuthDoneState, // 触发Onfinish回调事件 +*/ + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_state_machine.cpp b/services/implementation/src/authentication_v2/auth_state_machine.cpp new file mode 100644 index 000000000..d611e9129 --- /dev/null +++ b/services/implementation/src/authentication_v2/auth_state_machine.cpp @@ -0,0 +1,197 @@ +/* + * 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. + */ + +#include "auth_state.h" +#include "auth_context.h" + +#include "auth_state_machine.h" + +namespace OHOS { +namespace DistributedHardware { + + +AuthStateMachine::AuthStateMachine(std::shared_ptr context) { + stateTransitionTable_ = { // 此处省略下一状态为AuthXXXFinishState的迁移情况 + // Source端 状态迁移表 + {AuthIdleState, {AuthSrcStartState}}, + {AuthSrcStartState, {AuthSrcNegotiateState}}, + {AuthSrcNegotiateState, {AuthSrcConfirmState}}, + {AuthSrcConfirmState, {AuthSrcPinAuthStartState}}, + {AuthSrcPinAuthStartState, {AuthSrcPinAuthMsgNegotiateState, AuthSinkConfirmState}}, // PIN输入错误,3次内会回到AuthSinkConfirmState + {AuthSrcPinAuthMsgNegotiateState, {AuthSrcPinAuthDoneState}}, + {AuthSrcPinAuthDoneState, {AuthSrcCredentialExchangeState}}, + {AuthSrcCredentialExchangeState, {AuthSrcCredentialAuthStartState}}, + {AuthSrcCredentialAuthStartState, {AuthSrcCredentialAuthNegotiateState}}, + {AuthSrcCredentialAuthNegotiateState, {AuthSrcCredentialAuthDoneState}}, + {AuthSrcCredentialAuthDoneState, {AuthSrcDataSyncState}}, + {AuthSrcDataSyncState, {}}, + // Sink端 状态迁移表 + {AuthIdleState, {AuthSinkStartState}}, + {AuthSinkStartState, {AuthSinkNegotiateState}}, + {AuthSinkNegotiateState, {AuthSinkConfirmState}}, + {AuthSinkConfirmState, {AuthSinkPinAuthStartState}}, + {AuthSinkPinAuthStartState, {AuthSinkPinAuthMsgNegotiateState}}, + {AuthSinkPinAuthMsgNegotiateState, {AuthSinkPinAuthDoneState}}, + {AuthSinkPinAuthDoneState, {AuthSinkCredentialExchangeState}}, + {AuthSinkCredentialExchangeState, {AuthSinkCredentialAuthStartState}}, + {AuthSinkCredentialAuthStartState, {AuthSinkCredentialAuthNegotiateState}}, + {AuthSinkCredentialAuthNegotiateState, {AuthSinkCredentialAuthDoneState}}, + {AuthSinkCredentialAuthDoneState, {AuthSinkDataSyncState}}, + {AuthSinkDataSyncState, {AuthSinkFinishState}}, + {AuthSinkFinishState, {}}, + }; + running_ = true; + this->SetCurState(AuthIdleState); + thread_ = std::thread(AuthStateMachine::Run, context); +} +AuthStateMachine::~AuthStateMachine() +{ + Stop(); + thread_.join(); +}; + +// 通知状态迁移,执行状态对应具体action与异常处理(只允许在OnDataReceived中调用) +int32_t AuthStateMachine::TransitionTo(std::shared_ptr state) +{ + int32_t ret = DM_OK; + DmAuthStateType nextState = state->GetStateType(); + if (this->CheckStateTransitValid(nextState)) { + std::lock_guard lock(mutex_); + // 存入到队列中 + statesQueue_.push(state); + stateCv_.notify_one(); + } else { + // 切换状态不合法,打印错误日志并返回错误码 + LOGE("AuthStateMachine: The state transition does not meet the rule."); + ret = ERR_DM_NEXT_STATE_INVALID; // 下一状态不合法错误码 + } + return ret; +} + +// action内部的期望事件,用于阻塞,当等到期望事件完成时,返回成功,而等到其他异常,则返回失败(只允许在action中调用) +bool AuthStateMachine::WaitExpectEvent(EventType eventType) +{ + /* + 1、实际事件 = 期望事件,返回true + 2、实际事件 = 异常事件 或 事件超时时,返回false + 3、实际事件 = 其余事件,继续阻塞 + */ + std::unique_lock lock(mutex_); + // 记录进入函数的时间 + auto startTime = std::chrono::high_resolution_clock::now(); + while (true) { + eventCv_.wait(lock); + if (actualEventType_ == eventType) { + return true; + } else if (actualEventType_ == ON_ERROR) { + return false; + } + // 做一个超时退出机制 + // 已经经过的时间 + auto elapsedTime = std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - startTime); + if (elapsedTime.count() >= EVENT_TIMEOUT) { + break; + } + } + return false; +} + +// 事件完成调用,传事件枚举(只允许在事件触发中调用),如果是异常事件,需在context的reason或者reply记录 +void AuthStateMachine::NotifyEventFinish(EventType eventType) +{ + actualEventType_ = eventType; + eventCv_.notify_one(); +} + +// 循环等待状态转移,执行action +void AuthStateMachine::Run(std::shared_ptr context) +{ + while (running_.load()) { + std::shared_ptr state = FetchState(); + if (!state.has_value()) { + // 睡眠 100 毫秒 + std::this_thread::sleep_for(std::chrono::milliseconds(100)); + continue; + } + // 获取到状态,执行状态的action + DmAuthStateType stateType = state->GetStateType(); + this->SetCurState(stateType); + ret = state->Action(context); + if (ret != DM_OK) { + context->reason = ret; + if (context->direction == DM_AUTH_SOURCE) { + this->TransitionTo(std::make_shared()); + } else { + this->TransitionTo(std::make_shared()); + } + // finish需要,清理context以及重启状态机 + } + } +} + +std::optional> AuthStateMachine::FetchState() +{ + std::unique_lock lock(mutex_); + stateCv_.wait(lock, [&] { + return !running_.load() || !statesQueue_.empty(); + }); + + if (!running_.load()) return std::nullopt; + + std::shared_ptr state = statesQueue_.front(); + statesQueue_.pop(); + return state; +} + +// 停止线程 +void AuthStateMachine::Stop() +{ + running_.store(false); + stateCv_.notify_all(); + eventCv_.notify_all(); +} + + +// 设置当前状态 +void AuthStateMachine::SetCurState(DmAuthStateType state) +{ + curState_ = state; +} + +// 获取当前状态 +DmAuthStateType AuthStateMachine::GetCurState() +{ + return curState_; +} + +// 检验下一状态迁移合法性 +bool AuthStateMachine::CheckStateTransitValid(DmAuthStateType nextState) +{ + // 判断下一状态是否为AuthXXXFinishState,可直接切状态,返回 + if (nextState == AuthSrcFinishState || nextState == AuthSinkFinishState) { + return true; + } + // 判断是否符合状态迁移表 + auto it = transitionTable.find(curState_); + if (it != transitionTable.end()) { + const std::set& allowedStates = it->second; + return allowedStates.find(nextState) != allowedStates.end(); + } + return false; +} + + +} // namespace DistributedHardware +} // namespace OHOS -- Gitee From 3cd082e89ca90e6223cb3b1778456af8aed90d12 Mon Sep 17 00:00:00 2001 From: ZHANGHE24 <9525444+zhanghe24@user.noreply.gitee.com> Date: Mon, 24 Feb 2025 11:25:35 +0800 Subject: [PATCH 002/382] fix: state machine error code --- common/include/dm_constants.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index c759db158..2c92a3e8f 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -130,7 +130,8 @@ enum { ERR_DM_HILINKSVC_DISCONNECT = 96929829, ERR_DM_WISE_NEED_LOGIN = 96929830, ERR_DM_NAME_EMPTY = 96929831, - ERR_DM_HICHAIN_PROOFMISMATCH = 96929832 + ERR_DM_HICHAIN_PROOFMISMATCH = 96929832, + ERR_DM_NEXT_STATE_INVALID = 96929833 }; constexpr const char* TAG_GROUP_ID = "groupId"; -- Gitee From ef6f452ecaefbf7500d1c7b4df8820fdad26d5fd Mon Sep 17 00:00:00 2001 From: ZHANGHE24 <9525444+zhanghe24@user.noreply.gitee.com> Date: Tue, 25 Feb 2025 09:57:31 +0800 Subject: [PATCH 003/382] fix: remove CreateMessage Redundant Input Parameters --- .../implementation/include/authentication_v2/auth_context.h | 2 +- .../include/authentication_v2/auth_message_processor.h | 4 ++-- .../implementation/include/authentication_v2/auth_state.h | 2 +- .../src/authentication_v2/auth_message_processor.cpp | 4 ++-- 4 files changed, 6 insertions(+), 6 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_context.h b/services/implementation/include/authentication_v2/auth_context.h index 38b52497c..085a6b756 100644 --- a/services/implementation/include/authentication_v2/auth_context.h +++ b/services/implementation/include/authentication_v2/auth_context.h @@ -136,7 +136,7 @@ struct DmAccess { int64_t skTimeStamp; // 老化,时间为2天 bool isAuthed; bool isOnline; - std::string dmVersion; // 格式为 5.0.3 + std::string dmVersion; // 版本 5.1.0 std::string aclList; //可信关系列表,用于数据老化 KV格式 std::string credentialInfos; //凭据信息(点对点,同账号,..) 只保存凭据类型 kv结构 std::string extraInfo; //可扩展字段,kv结构 diff --git a/services/implementation/include/authentication_v2/auth_message_processor.h b/services/implementation/include/authentication_v2/auth_message_processor.h index 2a93a5262..5bea8783f 100644 --- a/services/implementation/include/authentication_v2/auth_message_processor.h +++ b/services/implementation/include/authentication_v2/auth_message_processor.h @@ -27,8 +27,8 @@ class AuthMessageProcessor { public: // 解析报文,返回值为错误码,实际解析出来的信息保存到context中 int32_t ParseMessage(std::shared_ptr context, const std::string &message); - // 创建报文,入参data可为空,构造对应msgType的报文,返回值为json格式报文的字符串 - std::string CreateMessage(DmMsgType msgType, std::shared_ptr context, const uint8_t *data, uint32_t dataLen); + // 创建报文,构造对应msgType的报文,返回值为json格式报文的字符串 + std::string CreateMessage(DmMsgType msgType, std::shared_ptr context); private: // 内部各类报文的实现 diff --git a/services/implementation/include/authentication_v2/auth_state.h b/services/implementation/include/authentication_v2/auth_state.h index 6e17a2cc1..c7832c64b 100644 --- a/services/implementation/include/authentication_v2/auth_state.h +++ b/services/implementation/include/authentication_v2/auth_state.h @@ -25,7 +25,7 @@ namespace DistributedHardware { class AuthState { public: - virtual ~AuthState() {}; // TODO: 确认是否有状态重置那些操作 + virtual ~AuthState() {}; virtual DmAuthStateType GetStateType() = 0; virtual int32_t Action(std::shared_ptr context) = 0; // 执行状态对应的action动作 }; diff --git a/services/implementation/src/authentication_v2/auth_message_processor.cpp b/services/implementation/src/authentication_v2/auth_message_processor.cpp index 89dc6726b..8bd837e76 100644 --- a/services/implementation/src/authentication_v2/auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/auth_message_processor.cpp @@ -21,8 +21,8 @@ namespace DistributedHardware { // 解析报文,返回值为错误码,实际解析出来的信息保存到context中 int32_t AuthMessageProcessor::ParseMessage(std::shared_ptr context, const std::string &message); -// 创建报文,入参data可为空,构造对应msgType的报文,返回值为json格式报文的字符串 -std::string AuthMessageProcessor::CreateMessage(DmMsgType msgType, std::shared_ptr context, const uint8_t *data, uint32_t dataLen); +// 创建报文,构造对应msgType的报文,返回值为json格式报文的字符串 +std::string AuthMessageProcessor::CreateMessage(DmMsgType msgType, std::shared_ptr context); // 内部各类报文的实现 -- Gitee From e20ca9f25882af40c2add11cfab10ac3a76bf989 Mon Sep 17 00:00:00 2001 From: ZHANGHE24 <9525444+zhanghe24@user.noreply.gitee.com> Date: Tue, 25 Feb 2025 10:22:40 +0800 Subject: [PATCH 004/382] fix: modify machine WaitExpectEvent interface return type --- .../authentication_v2/auth_state_machine.h | 5 +++-- .../authentication_v2/auth_state_machine.cpp | 18 ++++++++---------- 2 files changed, 11 insertions(+), 12 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_state_machine.h b/services/implementation/include/authentication_v2/auth_state_machine.h index 365ef4e62..ff3ee6519 100644 --- a/services/implementation/include/authentication_v2/auth_state_machine.h +++ b/services/implementation/include/authentication_v2/auth_state_machine.h @@ -42,6 +42,7 @@ enum EventType { ON_REQUEST, ON_FINISH, ON_ERROR, + ON_TIMEOUT, // 超时 ON_SCREEN_LOCKED, // 锁屏 }; @@ -53,8 +54,8 @@ public: // 通知状态迁移,执行状态对应具体action与异常处理(只允许在OnDataReceived中调用) int32_t TransitionTo(std::shared_ptr state); - // action内部的期望事件,用于阻塞,当等到期望事件完成时,返回成功,而等到其他异常,则返回失败(只允许在action中调用) - bool WaitExpectEvent(EventType eventType); + // action内部的期望事件,用于阻塞,当等到期望事件完成或其他异常时,返回实际发生的事件,而其他正常事件则会继续阻塞(只允许在action中调用) + EventType WaitExpectEvent(EventType eventType); // 事件完成调用,传事件枚举(只允许在事件触发中调用),如果是异常事件,需在context的reason或者reply记录 void NotifyEventFinish(EventType eventType); // 获取当前状态 diff --git a/services/implementation/src/authentication_v2/auth_state_machine.cpp b/services/implementation/src/authentication_v2/auth_state_machine.cpp index d611e9129..f0b1aae09 100644 --- a/services/implementation/src/authentication_v2/auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/auth_state_machine.cpp @@ -80,23 +80,21 @@ int32_t AuthStateMachine::TransitionTo(std::shared_ptr state) return ret; } -// action内部的期望事件,用于阻塞,当等到期望事件完成时,返回成功,而等到其他异常,则返回失败(只允许在action中调用) -bool AuthStateMachine::WaitExpectEvent(EventType eventType) +// action内部的期望事件,用于阻塞,当等到期望事件完成或其他异常时,返回实际发生的事件,而其他正常事件则会继续阻塞(只允许在action中调用) +EventType AuthStateMachine::WaitExpectEvent(EventType eventType) { /* - 1、实际事件 = 期望事件,返回true - 2、实际事件 = 异常事件 或 事件超时时,返回false - 3、实际事件 = 其余事件,继续阻塞 + 1、实际事件 = 期望事件,返回实际事件 + 2、实际事件 = 异常事件(事件超时等),同样返回实际事件 + 3、实际事件 = 其余事件,继续阻塞,但有个超时时间限制 */ std::unique_lock lock(mutex_); // 记录进入函数的时间 auto startTime = std::chrono::high_resolution_clock::now(); while (true) { eventCv_.wait(lock); - if (actualEventType_ == eventType) { - return true; - } else if (actualEventType_ == ON_ERROR) { - return false; + if (actualEventType_ == eventType || actualEventType_ == ON_ERROR) { + return actualEventType_; } // 做一个超时退出机制 // 已经经过的时间 @@ -105,7 +103,7 @@ bool AuthStateMachine::WaitExpectEvent(EventType eventType) break; } } - return false; + return EventType::ON_TIMEOUT; } // 事件完成调用,传事件枚举(只允许在事件触发中调用),如果是异常事件,需在context的reason或者reply记录 -- Gitee From abd4f4ef158ccf643c857516f977be88e8818e41 Mon Sep 17 00:00:00 2001 From: ZHANGHE24 <9525444+zhanghe24@user.noreply.gitee.com> Date: Wed, 26 Feb 2025 00:47:30 +0800 Subject: [PATCH 005/382] fix: Rectify compilation problems. --- services/implementation/BUILD.gn | 9 +++ .../include/authentication_v2/auth_manager.h | 8 +-- .../include/authentication_v2/auth_state.h | 35 ---------- .../{auth_context.h => dm_auth_context.h} | 61 +++++------------ ...rocessor.h => dm_auth_message_processor.h} | 12 ++-- .../include/authentication_v2/dm_auth_state.h | 67 +++++++++++++++++++ ...tate_machine.h => dm_auth_state_machine.h} | 34 +++++----- .../auth_stages/auth_acl.cpp | 2 +- .../auth_stages/auth_confirm.cpp | 2 +- .../auth_stages/auth_credential.cpp | 2 +- .../auth_stages/auth_negotiate.cpp | 2 +- .../auth_stages/auth_pin_auth.cpp | 2 +- ...ssor.cpp => dm_auth_message_processor.cpp} | 12 +++- ..._machine.cpp => dm_auth_state_machine.cpp} | 53 ++++++++------- 14 files changed, 163 insertions(+), 138 deletions(-) delete mode 100644 services/implementation/include/authentication_v2/auth_state.h rename services/implementation/include/authentication_v2/{auth_context.h => dm_auth_context.h} (68%) rename services/implementation/include/authentication_v2/{auth_message_processor.h => dm_auth_message_processor.h} (78%) create mode 100644 services/implementation/include/authentication_v2/dm_auth_state.h rename services/implementation/include/authentication_v2/{auth_state_machine.h => dm_auth_state_machine.h} (77%) rename services/implementation/src/authentication_v2/{auth_message_processor.cpp => dm_auth_message_processor.cpp} (75%) rename services/implementation/src/authentication_v2/{auth_state_machine.cpp => dm_auth_state_machine.cpp} (79%) diff --git a/services/implementation/BUILD.gn b/services/implementation/BUILD.gn index 94f967c62..8e661159f 100644 --- a/services/implementation/BUILD.gn +++ b/services/implementation/BUILD.gn @@ -114,6 +114,7 @@ if (defined(ohos_lite)) { "include/config", "include/adapter", "include/authentication", + "include/authentication_v2", "include/authentication/showconfirm/standard", "include/ability", "include/credential", @@ -179,6 +180,14 @@ if (defined(ohos_lite)) { "src/authentication/auth_ui_state_manager.cpp", "src/authentication/dm_auth_manager.cpp", "src/authentication/showconfirm/standard/show_confirm.cpp", + "src/authentication_v2/auth_stages/auth_acl.cpp", + "src/authentication_v2/auth_stages/auth_confirm.cpp", + "src/authentication_v2/auth_stages/auth_credential.cpp", + "src/authentication_v2/auth_stages/auth_negotiate.cpp", + "src/authentication_v2/auth_stages/auth_pin_auth.cpp", + "src/authentication_v2/auth_manager.cpp", + "src/authentication_v2/dm_auth_message_processor.cpp", + "src/authentication_v2/dm_auth_state_machine.cpp", "src/config/dm_config_manager.cpp", "src/credential/dm_credential_manager.cpp", "src/cryptomgr/crypto_mgr.cpp", diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index cfed4fc49..63d526023 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -13,12 +13,12 @@ * limitations under the License. */ -#ifndef OHOS_DM_AUTH_MANAGER_H -#define OHOS_DM_AUTH_MANAGER_H +#ifndef OHOS_DM_AUTH_MANAGER_V2_H +#define OHOS_DM_AUTH_MANAGER_V2_H #include -#include "auth_context.h" +#include "dm_auth_context.h" namespace OHOS { namespace DistributedHardware { @@ -52,4 +52,4 @@ private: } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_AUTH_MANAGER_H \ No newline at end of file +#endif // OHOS_DM_AUTH_MANAGER_V2_H \ No newline at end of file diff --git a/services/implementation/include/authentication_v2/auth_state.h b/services/implementation/include/authentication_v2/auth_state.h deleted file mode 100644 index c7832c64b..000000000 --- a/services/implementation/include/authentication_v2/auth_state.h +++ /dev/null @@ -1,35 +0,0 @@ -/* - * 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_H -#define OHOS_DM_AUTH_STATE_H - -#include - -#include "auth_context.h" - -namespace OHOS { -namespace DistributedHardware { - -class AuthState { -public: - virtual ~AuthState() {}; - virtual DmAuthStateType GetStateType() = 0; - virtual int32_t Action(std::shared_ptr context) = 0; // 执行状态对应的action动作 -}; - -} // namespace DistributedHardware -} // namespace OHOS -#endif // OHOS_DM_AUTH_STATE_H \ No newline at end of file diff --git a/services/implementation/include/authentication_v2/auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h similarity index 68% rename from services/implementation/include/authentication_v2/auth_context.h rename to services/implementation/include/authentication_v2/dm_auth_context.h index 085a6b756..41f5ead5a 100644 --- a/services/implementation/include/authentication_v2/auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -13,49 +13,22 @@ * limitations under the License. */ -#ifndef OHOS_DM_AUTH_CONTEXT_H -#define OHOS_DM_AUTH_CONTEXT_H +#ifndef OHOS_DM_AUTH_CONTEXT_V2_H +#define OHOS_DM_AUTH_CONTEXT_V2_H #include #include +#include "dm_device_info.h" +#include "dm_ability_manager.h" + namespace OHOS { namespace DistributedHardware { -// 状态类型 -enum DmAuthStateType : int32_t { - AuthIdleState = 0, // 设备初始化时 - // source端的状态 - AuthSrcStartState, // 用户触发BindTarget - AuthSrcNegotiateState, // 收到软总线回调函数OnSessionOpened,发送80报文 - AuthSrcConfirmState, // 收到90授权结果报文,发送100报文 - AuthSrcPinAuthStartState, // 收到110授权结果报文,发送120报文 - AuthSrcPinAuthMsgNegotiateState, // 收到130认证PIN结果报文,发送121报文 - AuthSrcPinAuthDoneState, // 收到131认证PIN结果报文,调用processData - AuthSrcCredentialExchangeState, // 触发Onfinish回调事件,发送140报文 - AuthSrcCredentialAuthStartState, // 收到150加密报文,发送160报文 - AuthSrcCredentialAuthNegotiateState, // 收到170凭据认证报文,发送161报文 - AuthSrcCredentialAuthDoneState, // 收到171凭据认证报文 - AuthSrcDataSyncState, // 触发Onfinish回调事件,发送180报文 - AuthSrcFinishState, // 收到190报文,发送200报文 - - // sink端的状态 - AuthSinkStartState = 50, // 总线触发OnSessionOpened - AuthSinkNegotiateState, // 收到80可信关系协商报文,发送90报文 - AuthSinkConfirmState, // 收到100用户授权报文,发送110报文 - AuthSinkPinAuthStartState, // 收到120认证PIN报文,发送130报文 - AuthSinkPinAuthMsgNegotiateState, // 收到121认证PIN报文,发送131报文 - AuthSinkPinAuthDoneState, // 触发Onfinish回调事件 - AuthSinkCredentialExchangeState, // 收到140加密报文,发送150报文 - AuthSinkCredentialAuthStartState, // 收到160凭证认证报文,发送170报文 - AuthSinkCredentialAuthNegotiateState, // 收到161凭据协商报文 - AuthSinkCredentialAuthDoneState, // 触发Onfinish回调事件 - AuthSinkDataSyncState, // 收到180同步报文,发送190报文 - AuthSinkFinishState, // 收到200结束报文 -}; +class DmAuthStateMachine; // 报文类型 -enum DmMsgType : int32_t { +enum DmMessageType { // 终止/异常报文 MSG_TYPE_UNKNOWN = 0, MSG_TYPE_AUTH_TERMINATE = 1, @@ -80,7 +53,7 @@ enum DmMsgType : int32_t { }; // PIN码认证类型 -enum DmAuthType : int32_t { +enum DmAuthType { AUTH_TYPE_PIN_SHOW = 0, // 弹PIN码 AUTH_TYPE_PIN_ULTRASONIC, // 超声PIN码 AUTH_TYPE_PIN_IMPORT, // 导入PIN码 @@ -91,14 +64,14 @@ enum DmAuthDirection { DM_AUTH_SINK, }; -enum BindType { +enum DmBindType { DM_AUTH_USERID = 1, DM_AUTH_SYSTEM_SERVICE, DM_AUTH_APP_SERVICE, DM_AUTH_DEVICEID, }; -struct PeerTargetAddress { +struct DmPeerTargetAddress { std::string peerBrMacAddress; //一碰投使用,直接可以蓝牙建链 std::string peerBleMacAddress; //一碰投使用,直接可以蓝牙建链 std::string peerWifiMacAddress; //一碰投使用,直接可以蓝牙建链 @@ -108,13 +81,13 @@ struct PeerTargetAddress { uint16_t peerWifiPort; //一碰投使用 }; -struct PeerTarget { - BindType peerType; // 绑定目标的类型 +struct DmPeerTarget { + DmBindType peerType; // 绑定目标的类型 std::string peerDeivceId; // 兼容性,UDID,哈希值,PUBLIC权限 int64_t peerServiceId; // Serviceid,主推,PUBLIC权限 uint64_t peerSaTokenId; // SA-TokenID,过度,SA使用,校验系统权限 std::string peerBundleName; //过度,同厂商使用,PUBLIC权限 - PeerTargetAddress PeerTargetAddress; //通信对象的物理地址,校验系统权限 + DmPeerTargetAddress peerTargetAddress; //通信对象的物理地址,校验系统权限 }; struct DmAccess { @@ -143,7 +116,7 @@ struct DmAccess { }; struct DmAuthContext { - DmMsgType msgType; // 报文类型,枚举MsgType + DmMessageType msgType; // 报文类型,枚举MsgType int32_t sessionId; // 总线传输会话ID int64_t requestId; // hichain认证ID UiAction authResult; // 授权结果(使用0、1、6,即单次,取消和始终信任,enum UiAction) @@ -163,14 +136,14 @@ struct DmAuthContext { std::string extraInfo; // 可扩展字段,kv结构 DmAuthDirection direction; // 标识认证方向 ProcessInfo processInfo; // 进程信息 - PeerTarget peerTarget; // 对端目标的信息 + DmPeerTarget peerTarget; // 对端目标的信息 DmAccess accesser; DmAccess accessee; std::multimap proxy; // 前面是accesser,后面是accessee - std::shared_ptr authStateMachine; // 状态机 + std::shared_ptr authStateMachine; // 状态机 }; } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_AUTH_CONTEXT_H +#endif // OHOS_DM_AUTH_CONTEXT_V2_H diff --git a/services/implementation/include/authentication_v2/auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h similarity index 78% rename from services/implementation/include/authentication_v2/auth_message_processor.h rename to services/implementation/include/authentication_v2/dm_auth_message_processor.h index 5bea8783f..d60139046 100644 --- a/services/implementation/include/authentication_v2/auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -13,22 +13,22 @@ * limitations under the License. */ -#ifndef OHOS_DM_AUTH_MESSAGE_PROCESSOR_H -#define OHOS_DM_AUTH_MESSAGE_PROCESSOR_H +#ifndef OHOS_DM_AUTH_MESSAGE_PROCESSOR_V2_H +#define OHOS_DM_AUTH_MESSAGE_PROCESSOR_V2_H #include -#include "auth_context.h" +#include "dm_auth_context.h" namespace OHOS { namespace DistributedHardware { -class AuthMessageProcessor { +class DmAuthMessageProcessor { public: // 解析报文,返回值为错误码,实际解析出来的信息保存到context中 int32_t ParseMessage(std::shared_ptr context, const std::string &message); // 创建报文,构造对应msgType的报文,返回值为json格式报文的字符串 - std::string CreateMessage(DmMsgType msgType, std::shared_ptr context); + std::string CreateMessage(DmMessageType msgType, std::shared_ptr context); private: // 内部各类报文的实现 @@ -36,4 +36,4 @@ private: } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_AUTH_MESSAGE_PROCESSOR_H \ No newline at end of file +#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 000000000..5c1b8e22f --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -0,0 +1,67 @@ +/* + * 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 "dm_auth_context.h" + +namespace OHOS { +namespace DistributedHardware { + +// 状态类型 +enum DmAuthStateType { + AuthIdleState = 0, // 设备初始化时 + // source端的状态 + AuthSrcStartState, // 用户触发BindTarget + AuthSrcNegotiateState, // 收到软总线回调函数OnSessionOpened,发送80报文 + AuthSrcConfirmState, // 收到90授权结果报文,发送100报文 + AuthSrcPinAuthStartState, // 收到110授权结果报文,发送120报文 + AuthSrcPinAuthMsgNegotiateState, // 收到130认证PIN结果报文,发送121报文 + AuthSrcPinAuthDoneState, // 收到131认证PIN结果报文,调用processData + AuthSrcCredentialExchangeState, // 触发Onfinish回调事件,发送140报文 + AuthSrcCredentialAuthStartState, // 收到150加密报文,发送160报文 + AuthSrcCredentialAuthNegotiateState, // 收到170凭据认证报文,发送161报文 + AuthSrcCredentialAuthDoneState, // 收到171凭据认证报文 + AuthSrcDataSyncState, // 触发Onfinish回调事件,发送180报文 + AuthSrcFinishState, // 收到190报文,发送200报文 + + // sink端的状态 + AuthSinkStartState = 50, // 总线触发OnSessionOpened + AuthSinkNegotiateState, // 收到80可信关系协商报文,发送90报文 + AuthSinkConfirmState, // 收到100用户授权报文,发送110报文 + AuthSinkPinAuthStartState, // 收到120认证PIN报文,发送130报文 + AuthSinkPinAuthMsgNegotiateState, // 收到121认证PIN报文,发送131报文 + AuthSinkPinAuthDoneState, // 触发Onfinish回调事件 + AuthSinkCredentialExchangeState, // 收到140加密报文,发送150报文 + AuthSinkCredentialAuthStartState, // 收到160凭证认证报文,发送170报文 + AuthSinkCredentialAuthNegotiateState, // 收到161凭据协商报文 + AuthSinkCredentialAuthDoneState, // 触发Onfinish回调事件 + AuthSinkDataSyncState, // 收到180同步报文,发送190报文 + AuthSinkFinishState, // 收到200结束报文 +}; + +class DmAuthState { +public: + virtual ~DmAuthState() {}; + virtual DmAuthStateType GetStateType() = 0; + virtual int32_t Action(std::shared_ptr context) = 0; // 执行状态对应的action动作 +}; + +} // 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/auth_state_machine.h b/services/implementation/include/authentication_v2/dm_auth_state_machine.h similarity index 77% rename from services/implementation/include/authentication_v2/auth_state_machine.h rename to services/implementation/include/authentication_v2/dm_auth_state_machine.h index ff3ee6519..53d630458 100644 --- a/services/implementation/include/authentication_v2/auth_state_machine.h +++ b/services/implementation/include/authentication_v2/dm_auth_state_machine.h @@ -13,10 +13,12 @@ * limitations under the License. */ -#ifndef OHOS_DM_AUTH_STATE_MACHINE_H -#define OHOS_DM_AUTH_STATE_MACHINE_H +#ifndef OHOS_DM_AUTH_STATE_MACHINE_V2_H +#define OHOS_DM_AUTH_STATE_MACHINE_V2_H +#include #include +#include #include #include #include @@ -24,8 +26,8 @@ #include #include -#include "auth_state.h" -#include "auth_context.h" +#include "dm_auth_state.h" +#include "dm_auth_context.h" namespace OHOS { namespace DistributedHardware { @@ -36,7 +38,7 @@ constexpr const int EVENT_TIMEOUT = 5000; // 5000 毫秒 = 5 秒 // 定义状态迁移表类型 using StateTransitionTable = std::map>; -enum EventType { +enum DmEventType { ON_TRANSMIT = 0, ON_SESSION_KEY_RETURNED, ON_REQUEST, @@ -46,18 +48,18 @@ enum EventType { ON_SCREEN_LOCKED, // 锁屏 }; -class AuthStateMachine { +class DmAuthStateMachine { public: - AuthStateMachine() = delete; - AuthStateMachine(std::shared_ptr context); - ~AuthStateMachine(); + DmAuthStateMachine() = delete; + DmAuthStateMachine(std::shared_ptr context); + ~DmAuthStateMachine(); // 通知状态迁移,执行状态对应具体action与异常处理(只允许在OnDataReceived中调用) - int32_t TransitionTo(std::shared_ptr state); + int32_t TransitionTo(std::shared_ptr state); // action内部的期望事件,用于阻塞,当等到期望事件完成或其他异常时,返回实际发生的事件,而其他正常事件则会继续阻塞(只允许在action中调用) - EventType WaitExpectEvent(EventType eventType); + DmEventType WaitExpectEvent(DmEventType eventType); // 事件完成调用,传事件枚举(只允许在事件触发中调用),如果是异常事件,需在context的reason或者reply记录 - void NotifyEventFinish(EventType eventType); + void NotifyEventFinish(DmEventType eventType); // 获取当前状态 DmAuthStateType GetCurState(); private: @@ -66,7 +68,7 @@ private: // 停止线程 void Stop(); // 获取状态,进行执行 - std::optional> FetchState(); + std::optional> FetchState(); // 设置当前状态 void SetCurState(DmAuthStateType state); // 检验下一状态迁移合法性 @@ -78,10 +80,10 @@ private: StateTransitionTable stateTransitionTable_; // 实际事件 - EventType actualEventType_; + DmEventType actualEventType_; std::thread thread_; std::atomic running_; - std::queue> statesQueue_; + std::queue> statesQueue_; // 同步原语 std::mutex mutex_; std::condition_variable stateCv_; @@ -90,4 +92,4 @@ private: } // namespace DistributedHardware } // namespace OHOS -#endif // OHOS_DM_AUTH_STATE_MACHINE_H +#endif // OHOS_DM_AUTH_STATE_MACHINE_V2_H diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index b699a81b3..0d987f571 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "auth_state.h" +#include "dm_auth_state.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index f039d61a2..6c7bc889b 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "auth_state.h" +#include "dm_auth_state.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index f235af880..b61adfb84 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "auth_state.h" +#include "dm_auth_state.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 973006c4b..e451732e8 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "auth_state.h" +#include "dm_auth_state.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 0ca65e616..309f24a56 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -13,7 +13,7 @@ * limitations under the License. */ -#include "auth_state.h" +#include "dm_auth_state.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/implementation/src/authentication_v2/auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp similarity index 75% rename from services/implementation/src/authentication_v2/auth_message_processor.cpp rename to services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 8bd837e76..3d8efd700 100644 --- a/services/implementation/src/authentication_v2/auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -13,16 +13,22 @@ * limitations under the License. */ -#include "auth_message_processor.h" +#include "dm_auth_message_processor.h" namespace OHOS { namespace DistributedHardware { // 解析报文,返回值为错误码,实际解析出来的信息保存到context中 -int32_t AuthMessageProcessor::ParseMessage(std::shared_ptr context, const std::string &message); +int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr context, const std::string &message) +{ + return 0; +} // 创建报文,构造对应msgType的报文,返回值为json格式报文的字符串 -std::string AuthMessageProcessor::CreateMessage(DmMsgType msgType, std::shared_ptr context); +std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::shared_ptr context) +{ + return ""; +} // 内部各类报文的实现 diff --git a/services/implementation/src/authentication_v2/auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp similarity index 79% rename from services/implementation/src/authentication_v2/auth_state_machine.cpp rename to services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index f0b1aae09..99a0f134f 100644 --- a/services/implementation/src/authentication_v2/auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -13,16 +13,19 @@ * limitations under the License. */ -#include "auth_state.h" -#include "auth_context.h" +#include "dm_log.h" +#include "dm_constants.h" +#include "dm_auth_state.h" +#include "dm_auth_context.h" -#include "auth_state_machine.h" +#include "dm_auth_state_machine.h" namespace OHOS { namespace DistributedHardware { -AuthStateMachine::AuthStateMachine(std::shared_ptr context) { +DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) +{ stateTransitionTable_ = { // 此处省略下一状态为AuthXXXFinishState的迁移情况 // Source端 状态迁移表 {AuthIdleState, {AuthSrcStartState}}, @@ -54,16 +57,16 @@ AuthStateMachine::AuthStateMachine(std::shared_ptr context) { }; running_ = true; this->SetCurState(AuthIdleState); - thread_ = std::thread(AuthStateMachine::Run, context); + thread_ = std::thread(DmAuthStateMachine::Run, this, context); } -AuthStateMachine::~AuthStateMachine() +DmAuthStateMachine::~DmAuthStateMachine() { Stop(); thread_.join(); }; // 通知状态迁移,执行状态对应具体action与异常处理(只允许在OnDataReceived中调用) -int32_t AuthStateMachine::TransitionTo(std::shared_ptr state) +int32_t DmAuthStateMachine::TransitionTo(std::shared_ptr state) { int32_t ret = DM_OK; DmAuthStateType nextState = state->GetStateType(); @@ -74,14 +77,14 @@ int32_t AuthStateMachine::TransitionTo(std::shared_ptr state) stateCv_.notify_one(); } else { // 切换状态不合法,打印错误日志并返回错误码 - LOGE("AuthStateMachine: The state transition does not meet the rule."); + LOGE("DmAuthStateMachine: The state transition does not meet the rule."); ret = ERR_DM_NEXT_STATE_INVALID; // 下一状态不合法错误码 } return ret; } // action内部的期望事件,用于阻塞,当等到期望事件完成或其他异常时,返回实际发生的事件,而其他正常事件则会继续阻塞(只允许在action中调用) -EventType AuthStateMachine::WaitExpectEvent(EventType eventType) +DmEventType DmAuthStateMachine::WaitExpectEvent(DmEventType eventType) { /* 1、实际事件 = 期望事件,返回实际事件 @@ -103,43 +106,43 @@ EventType AuthStateMachine::WaitExpectEvent(EventType eventType) break; } } - return EventType::ON_TIMEOUT; + return DmEventType::ON_TIMEOUT; } // 事件完成调用,传事件枚举(只允许在事件触发中调用),如果是异常事件,需在context的reason或者reply记录 -void AuthStateMachine::NotifyEventFinish(EventType eventType) +void DmAuthStateMachine::NotifyEventFinish(DmEventType eventType) { actualEventType_ = eventType; eventCv_.notify_one(); } // 循环等待状态转移,执行action -void AuthStateMachine::Run(std::shared_ptr context) +void DmAuthStateMachine::Run(std::shared_ptr context) { while (running_.load()) { - std::shared_ptr state = FetchState(); + auto state = FetchState(); if (!state.has_value()) { // 睡眠 100 毫秒 std::this_thread::sleep_for(std::chrono::milliseconds(100)); continue; } // 获取到状态,执行状态的action - DmAuthStateType stateType = state->GetStateType(); + DmAuthStateType stateType = state.value()->GetStateType(); this->SetCurState(stateType); - ret = state->Action(context); + int32_t ret = state.value()->Action(context); if (ret != DM_OK) { context->reason = ret; if (context->direction == DM_AUTH_SOURCE) { - this->TransitionTo(std::make_shared()); + // this->TransitionTo(std::make_shared()); } else { - this->TransitionTo(std::make_shared()); + // this->TransitionTo(std::make_shared()); } // finish需要,清理context以及重启状态机 } } } -std::optional> AuthStateMachine::FetchState() +std::optional> DmAuthStateMachine::FetchState() { std::unique_lock lock(mutex_); stateCv_.wait(lock, [&] { @@ -148,13 +151,13 @@ std::optional> AuthStateMachine::FetchState() if (!running_.load()) return std::nullopt; - std::shared_ptr state = statesQueue_.front(); + std::shared_ptr state = statesQueue_.front(); statesQueue_.pop(); return state; } // 停止线程 -void AuthStateMachine::Stop() +void DmAuthStateMachine::Stop() { running_.store(false); stateCv_.notify_all(); @@ -163,27 +166,27 @@ void AuthStateMachine::Stop() // 设置当前状态 -void AuthStateMachine::SetCurState(DmAuthStateType state) +void DmAuthStateMachine::SetCurState(DmAuthStateType state) { curState_ = state; } // 获取当前状态 -DmAuthStateType AuthStateMachine::GetCurState() +DmAuthStateType DmAuthStateMachine::GetCurState() { return curState_; } // 检验下一状态迁移合法性 -bool AuthStateMachine::CheckStateTransitValid(DmAuthStateType nextState) +bool DmAuthStateMachine::CheckStateTransitValid(DmAuthStateType nextState) { // 判断下一状态是否为AuthXXXFinishState,可直接切状态,返回 if (nextState == AuthSrcFinishState || nextState == AuthSinkFinishState) { return true; } // 判断是否符合状态迁移表 - auto it = transitionTable.find(curState_); - if (it != transitionTable.end()) { + auto it = stateTransitionTable_.find(curState_); + if (it != stateTransitionTable_.end()) { const std::set& allowedStates = it->second; return allowedStates.find(nextState) != allowedStates.end(); } -- Gitee From 9739de3acf452c271d584fd84e5e1f52003c25ed Mon Sep 17 00:00:00 2001 From: ZHANGHE24 <9525444+zhanghe24@user.noreply.gitee.com> Date: Wed, 26 Feb 2025 17:12:01 +0800 Subject: [PATCH 006/382] fix: Rectify compilation problems. --- .../src/authentication_v2/dm_auth_state_machine.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 99a0f134f..8cf5d6440 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -57,7 +57,7 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) }; running_ = true; this->SetCurState(AuthIdleState); - thread_ = std::thread(DmAuthStateMachine::Run, this, context); + thread_ = std::thread(&DmAuthStateMachine::Run, this, context); } DmAuthStateMachine::~DmAuthStateMachine() { -- Gitee From b7d1bbec61c5a4e1221ebe5fba909b99dc58e261 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 27 Feb 2025 06:19:04 +0000 Subject: [PATCH 007/382] =?UTF-8?q?=E3=80=90=E6=96=B0=E5=8D=8F=E8=AE=AE?= =?UTF-8?q?=E3=80=91s100-s131=20commit=20=E6=96=B0=E5=8D=8F=E8=AE=AE100?= =?UTF-8?q?=E6=8A=A5=E6=96=87=E5=88=B0131=E6=8A=A5=E6=96=87=E7=9A=84?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/implementation/BUILD.gn | 1 + .../include/authentication_v2/auth_manager.h | 24 +- .../authentication_v2/dm_auth_context.h | 41 +-- .../dm_auth_message_processor.h | 54 +++- .../include/authentication_v2/dm_auth_state.h | 124 ++++++-- .../authentication_v2/dm_auth_state_machine.h | 6 +- .../hichain/hichain_auth_connector.h | 1 + .../src/authentication_v2/auth_manager.cpp | 186 +++++++++++ .../auth_stages/auth_confirm.cpp | 195 ++++++++++++ .../auth_stages/auth_pin_auth.cpp | 291 ++++++++++++++++++ .../dm_auth_message_processor.cpp | 80 +++++ .../src/authentication_v2/dm_auth_state.cpp | 50 +++ .../dm_auth_state_machine.cpp | 56 ++-- .../hichain/hichain_auth_connector.cpp | 6 + 14 files changed, 1024 insertions(+), 91 deletions(-) create mode 100644 services/implementation/src/authentication_v2/dm_auth_state.cpp diff --git a/services/implementation/BUILD.gn b/services/implementation/BUILD.gn index 8e661159f..53ad73bc7 100644 --- a/services/implementation/BUILD.gn +++ b/services/implementation/BUILD.gn @@ -188,6 +188,7 @@ if (defined(ohos_lite)) { "src/authentication_v2/auth_manager.cpp", "src/authentication_v2/dm_auth_message_processor.cpp", "src/authentication_v2/dm_auth_state_machine.cpp", + "src/authentication_v2/dm_auth_state.cpp", "src/config/dm_config_manager.cpp", "src/credential/dm_credential_manager.cpp", "src/cryptomgr/crypto_mgr.cpp", diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 63d526023..e52fba7d8 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -17,21 +17,25 @@ #define OHOS_DM_AUTH_MANAGER_V2_H #include - -#include "dm_auth_context.h" +#include "hichain_auth_connector.h" +#include "hichain_connector.h" +#include "softbus_connector.h" +#include "softbus_session.h" namespace OHOS { namespace DistributedHardware { - -class AuthManager { +struct DmAuthContext; +class AuthManager : public ISoftbusSessionCallback, + public IDmDeviceAuthCallback, + public std::enable_shared_from_this { public: void SetAuthContext(std::shared_ptr context); std::shared_ptr GetAuthContext(); // 各类事件触发的函数实现(虚函数) - -private: + int32_t GetPinCode(int32_t &code) override; +protected: // 上下文(需在该层级进行创建) std::shared_ptr context_; }; @@ -39,6 +43,10 @@ private: class AuthSrcManager : public AuthManager { public: // 各类事件触发的函数实现(继承) + int32_t OnUserOperation(int32_t action, const std::string ¶ms); + 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; private: }; @@ -46,6 +54,10 @@ private: class AuthSinkManager : public AuthManager { public: // 各类事件触发的函数实现(继承) + int32_t OnUserOperation(int32_t action, const std::string ¶ms); + 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; private: }; diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 41f5ead5a..12beada18 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -19,6 +19,13 @@ #include #include +#include "dm_timer.h" +#include "auth_ui_state_manager.h" +#include "hichain_auth_connector.h" +#include "hichain_connector.h" +#include "dm_auth_message_processor.h" +#include "softbus_connector.h" +#include "softbus_session.h" #include "dm_device_info.h" #include "dm_ability_manager.h" @@ -27,31 +34,6 @@ namespace DistributedHardware { class DmAuthStateMachine; -// 报文类型 -enum DmMessageType { - // 终止/异常报文 - MSG_TYPE_UNKNOWN = 0, - MSG_TYPE_AUTH_TERMINATE = 1, - // 正常报文 - 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_FINISH = 200, -}; - // PIN码认证类型 enum DmAuthType { AUTH_TYPE_PIN_SHOW = 0, // 弹PIN码 @@ -121,7 +103,7 @@ struct DmAuthContext { int64_t requestId; // hichain认证ID UiAction authResult; // 授权结果(使用0、1、6,即单次,取消和始终信任,enum UiAction) DmAuthType authType; // 认证方式,弹pin码、超声pin码、导入pin码 - int32_t authFailTimes; // 认证失败次数,查过3次结束认证 + int32_t authFailTimes{0}; // 认证失败次数,查过3次结束认证 int32_t pinCode; // 保存业务导入的pin码 int32_t connDelayCloseTime; // 链路延迟释放时间, 授权结束后不自动断链(有业务需要使用)保留字段 int32_t reason; // 本端失败的原因 @@ -142,6 +124,13 @@ struct DmAuthContext { std::multimap proxy; // 前面是accesser,后面是accessee std::shared_ptr authStateMachine; // 状态机 + bool fallBackToInputPin{false}; // 是否已经回退到输入PIN码 + std::string transmitData; // 保存 onTrasmit返回数据 + std::shared_ptr timer; + std::shared_ptr authUiStateMgr; + std::shared_ptr hiChainAuthConnector; + std::shared_ptr authMessageProcessor; + std::shared_ptr softbusConnector; }; } // namespace DistributedHardware diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index d60139046..c68231aa3 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -17,11 +17,35 @@ #define OHOS_DM_AUTH_MESSAGE_PROCESSOR_V2_H #include - -#include "dm_auth_context.h" +#include "nlohmann/json.hpp" namespace OHOS { namespace DistributedHardware { +struct DmAuthContext; +// 报文类型 +enum DmMessageType { + // 终止/异常报文 + MSG_TYPE_UNKNOWN = 0, + MSG_TYPE_AUTH_TERMINATE = 1, + // 正常报文 + 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_FINISH = 200, +}; class DmAuthMessageProcessor { public: @@ -29,9 +53,35 @@ public: int32_t ParseMessage(std::shared_ptr context, const std::string &message); // 创建报文,构造对应msgType的报文,返回值为json格式报文的字符串 std::string CreateMessage(DmMessageType msgType, std::shared_ptr context); + // 创建报文并发送 + void CreateAndSendMsg(DmMessageType msgType, std::shared_ptr context); private: // 内部各类报文的实现 + // 解析 90 报文 + void ParseMessageRespAclNegotiate(const nlohmann::json &json, std::shared_ptr context); + // 解析 100 报文 + void ParseMessageReqUserConfirm(const nlohmann::json &json, std::shared_ptr context); + // 解析 110 报文 + void ParseMessageRespUserConfirm(const nlohmann::json &json, std::shared_ptr context); + // 解析 120 报文 + void ParseMessageReqPinAuthStart(const nlohmann::json &json, std::shared_ptr context); + // 解析 130 报文 + void ParseMessageRespPinAuthStart(const nlohmann::json &json, std::shared_ptr context); + // 解析 121 报文 + void ParseMessageReqPinAuthNegotiate(const nlohmann::json &json, std::shared_ptr context); + // 创建 100 报文 + void CreateMessageReqUserConfirm(nlohmann::json &json, std::shared_ptr context); + // 创建 110 报文 + void CreateMessageRespUserConfirm(nlohmann::json &json, std::shared_ptr context); + // 创建 120 报文 + void CreateMessageReqPinAuthStart(nlohmann::json &json, std::shared_ptr context); + // 创建 130 报文 + void CreateMessageRespPinAuthStart(nlohmann::json &json, std::shared_ptr context); + // 创建 121 报文 + void CreateMessageReqPinAuthNegotiate(nlohmann::json &json, std::shared_ptr context); + // 创建 131 报文 + void CreateMessageRespPinAuthNegotiate(nlohmann::json &json, std::shared_ptr context); }; } // namespace DistributedHardware diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 5c1b8e22f..c19343493 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -18,41 +18,40 @@ #include -#include "dm_auth_context.h" - namespace OHOS { namespace DistributedHardware { +struct DmAuthContext; // 状态类型 -enum DmAuthStateType { - AuthIdleState = 0, // 设备初始化时 +enum class DmAuthStateType { + AUTH_IDLE_STATE = 0, // 设备初始化时 // source端的状态 - AuthSrcStartState, // 用户触发BindTarget - AuthSrcNegotiateState, // 收到软总线回调函数OnSessionOpened,发送80报文 - AuthSrcConfirmState, // 收到90授权结果报文,发送100报文 - AuthSrcPinAuthStartState, // 收到110授权结果报文,发送120报文 - AuthSrcPinAuthMsgNegotiateState, // 收到130认证PIN结果报文,发送121报文 - AuthSrcPinAuthDoneState, // 收到131认证PIN结果报文,调用processData - AuthSrcCredentialExchangeState, // 触发Onfinish回调事件,发送140报文 - AuthSrcCredentialAuthStartState, // 收到150加密报文,发送160报文 - AuthSrcCredentialAuthNegotiateState, // 收到170凭据认证报文,发送161报文 - AuthSrcCredentialAuthDoneState, // 收到171凭据认证报文 - AuthSrcDataSyncState, // 触发Onfinish回调事件,发送180报文 - AuthSrcFinishState, // 收到190报文,发送200报文 + AUTH_SRC_START_STATE, // 用户触发BindTarget + AUTH_SRC_NEGOTIATE_STATE, // 收到软总线回调函数OnSessionOpened,发送80报文 + AUTH_SRC_CONFIRM_STATE, // 收到90授权结果报文,发送100报文 + AUTH_SRC_PIN_AUTH_START_STATE, // 收到110授权结果报文,发送120报文 + AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, // 收到130认证PIN结果报文,发送121报文 + AUTH_SRC_PIN_AUTH_DONE_STATE, // 收到131认证PIN结果报文,调用processData + AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, // 触发Onfinish回调事件,发送140报文 + AUTH_SRC_CREDENTIAL_AUTH_START_STATE, // 收到150加密报文,发送160报文 + AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE, // 收到170凭据认证报文,发送161报文 + AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE, // 收到171凭据认证报文 + AUTH_SRC_DATA_SYNC_STATE, // 触发Onfinish回调事件,发送180报文 + AUTH_SRC_FINISH_STATE, // 收到190报文,发送200报文 // sink端的状态 - AuthSinkStartState = 50, // 总线触发OnSessionOpened - AuthSinkNegotiateState, // 收到80可信关系协商报文,发送90报文 - AuthSinkConfirmState, // 收到100用户授权报文,发送110报文 - AuthSinkPinAuthStartState, // 收到120认证PIN报文,发送130报文 - AuthSinkPinAuthMsgNegotiateState, // 收到121认证PIN报文,发送131报文 - AuthSinkPinAuthDoneState, // 触发Onfinish回调事件 - AuthSinkCredentialExchangeState, // 收到140加密报文,发送150报文 - AuthSinkCredentialAuthStartState, // 收到160凭证认证报文,发送170报文 - AuthSinkCredentialAuthNegotiateState, // 收到161凭据协商报文 - AuthSinkCredentialAuthDoneState, // 触发Onfinish回调事件 - AuthSinkDataSyncState, // 收到180同步报文,发送190报文 - AuthSinkFinishState, // 收到200结束报文 + AUTH_SINK_START_STATE = 50, // 总线触发OnSessionOpened + AUTH_SINK_NEGOTIATE_STATE, // 收到80可信关系协商报文,发送90报文 + AUTH_SINK_CONFIRM_STATE, // 收到100用户授权报文,发送110报文 + AUTH_SINK_PIN_AUTH_START_STATE, // 收到120认证PIN报文,发送130报文 + AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, // 收到121认证PIN报文,发送131报文 + AUTH_SINK_PIN_AUTH_DONE_STATE, // 触发Onfinish回调事件 + AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, // 收到140加密报文,发送150报文 + AUTH_SINK_CREDENTIAL_AUTH_START_STATE, // 收到160凭证认证报文,发送170报文 + AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE, // 收到161凭据协商报文 + AUTH_SINK_CREDENTIAL_AUTH_DONE_STATE, // 触发Onfinish回调事件 + AUTH_SINK_DATA_SYNC_STATE, // 收到180同步报文,发送190报文 + AUTH_SINK_FINISH_STATE, // 收到200结束报文 }; class DmAuthState { @@ -60,6 +59,75 @@ public: virtual ~DmAuthState() {}; virtual DmAuthStateType GetStateType() = 0; virtual int32_t Action(std::shared_ptr context) = 0; // 执行状态对应的action动作 + static bool IsScreenLocked(); + 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; +}; + +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 GetAuthType(std::shared_ptr context); // 从DP配置读取授权类型 + int32_t ShowConfigDialog(std::shared_ptr context); // 提示用户授权对话框 + int64_t GenRequestId(std::shared_ptr context); // 生成HiChain请求ID +}; + +class AuthSrcPinAuthStartState : public DmAuthState { +public: + virtual ~AuthSrcPinAuthStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +private: + int32_t GetPinCode(std::shared_ptr context); // 获取PIN码 + int32_t ShowStartAuthDialog(std::shared_ptr context); // 向用户显示PIN输入框 + int32_t GetPinCodeFromServerInfo(std::shared_ptr context); // 从服务端配置信息中获取PIN码 + int32_t AuthDevice(std::shared_ptr context); // 向HiChain发起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; }; } // namespace DistributedHardware diff --git a/services/implementation/include/authentication_v2/dm_auth_state_machine.h b/services/implementation/include/authentication_v2/dm_auth_state_machine.h index 53d630458..d6d029ad2 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state_machine.h +++ b/services/implementation/include/authentication_v2/dm_auth_state_machine.h @@ -27,7 +27,6 @@ #include #include "dm_auth_state.h" -#include "dm_auth_context.h" namespace OHOS { namespace DistributedHardware { @@ -44,7 +43,10 @@ enum DmEventType { ON_REQUEST, ON_FINISH, ON_ERROR, - ON_TIMEOUT, // 超时 + + ON_TIMEOUT, // 超时 + ON_USER_OPERATION, // 用户操作 + ON_FAIL, // 失败流程 ON_SCREEN_LOCKED, // 锁屏 }; diff --git a/services/implementation/include/dependency/hichain/hichain_auth_connector.h b/services/implementation/include/dependency/hichain/hichain_auth_connector.h index cc92df1fc..edf1cee17 100644 --- a/services/implementation/include/dependency/hichain/hichain_auth_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_auth_connector.h @@ -58,6 +58,7 @@ public: int32_t DeleteCredential(const std::string &deviceId, int32_t userId); int32_t RegisterHiChainAuthCallback(std::shared_ptr callback); int32_t GetCredential(std::string &localUdid, int32_t osAccountId, std::string &publicKey); + int32_t ProcessCredData(int64_t authReqId, const std::string &data); private: void FreeJsonString(char *jsonStr); diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 05557990d..e5c592a51 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -14,10 +14,17 @@ */ #include "auth_manager.h" +#include "dm_auth_context.h" +#include "dm_log.h" +#include "dm_auth_state_machine.h" +#undef LOG_TAG +#define LOG_TAG "DHDM_V2" namespace OHOS { namespace DistributedHardware { +const int32_t MAX_AUTH_FAIL_TIMES = 3; + void AuthManager::SetAuthContext(std::shared_ptr context) { this->context_ = context; @@ -34,5 +41,184 @@ std::shared_ptr AuthManager::GetAuthContext() // AuthSinkManager +int32_t AuthSinkManager::OnUserOperation(int32_t action, const std::string ¶ms) +{ + LOGI("AuthSinkManager::OnUserOperation start."); + if (context_ == nullptr || context_->authStateMachine == nullptr) { + LOGE("OnUserOperation: Authenticate is not start"); + return ERR_DM_AUTH_NOT_START; + } + + switch (action) { + case USER_OPERATION_TYPE_CANCEL_AUTH: + case USER_OPERATION_TYPE_ALLOW_AUTH: + case USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS: + context_->authResult = static_cast(action); + context_->reply = USER_OPERATION_TYPE_ALLOW_AUTH; + if (action == USER_OPERATION_TYPE_CANCEL_AUTH) { + context_->reply = USER_OPERATION_TYPE_CANCEL_AUTH; + } + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_USER_OPERATION); + break; + case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT: + context_->reason = ERR_DM_TIME_OUT; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + break; + case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY: + context_->reason = ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + break; + default: + LOGE("this action id not support"); + break; + } + LOGI("AuthSinkManager::OnUserOperation leave."); + return DM_OK; +} + +int32_t AuthSrcManager::OnUserOperation(int32_t action, const std::string ¶ms) +{ + LOGI("AuthSrcManager::OnUserOperation start."); + if (context_ == nullptr || context_->authStateMachine == nullptr) { + LOGE("OnUserOperation: Authenticate is not start"); + return ERR_DM_AUTH_NOT_START; + } + + switch (action) { + case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT: + context_->reason = ERR_DM_BIND_USER_CANCEL_ERROR; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + break; + case USER_OPERATION_TYPE_DONE_PINCODE_INPUT: + context_->pinCode = std::atoi(params.c_str()); + break; + default: + LOGE("this action id not support"); + break; + } + LOGI("AuthSrcManager::OnUserOperation leave."); + return DM_OK; +} + +void AuthSrcManager::AuthDeviceError(int64_t requestId, int32_t errorCode) +{ + LOGI("AuthSrcManager::AuthDeviceError start."); + auto curState = context_->authStateMachine->GetCurState(); + if (curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE || + curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE || + curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE) { + LOGI("AuthSrcManager::AuthDeviceError Auth pin err."); + if (context_->authType == DmAuthType::AUTH_TYPE_PIN_SHOW) { + context_->authFailTimes++; + } else if (!context_->fallBackToInputPin) { + LOGI("AuthSrcManager::AuthDeviceError fallback to input pin."); + context_->fallBackToInputPin = true; + } else { + context_->authFailTimes++; + } + + // 失败 MAX_AUTH_FAIL_TIMES 次后,走认证失败 ON_FAIL + if (context_->authFailTimes >= MAX_AUTH_FAIL_TIMES) { + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + } else { + // Notify ON_ERROR 事件,对应 Action 内会当正常重试处理,而非失败 + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); + // 回退状态到 AuthSrcPinAuthStartState + context_->authStateMachine->TransitionTo(std::make_shared()); + } + } + LOGI("AuthSrcManager::AuthDeviceError leave."); +} + +void AuthSinkManager::AuthDeviceError(int64_t requestId, int32_t errorCode) +{ + LOGI("AuthSinkManager::AuthDeviceError start."); + auto curState = context_->authStateMachine->GetCurState(); + if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE || + curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE) { + LOGI("AuthSinkManager::AuthDeviceError Auth pin err."); + if (context_->authType == DmAuthType::AUTH_TYPE_PIN_SHOW) { + context_->authFailTimes++; + } else if (!context_->fallBackToInputPin) { + LOGI("AuthSinkManager::AuthDeviceError fallback to input pin."); + context_->fallBackToInputPin = true; + // 生成PIN码 + AuthSinkStatePinAuthComm::GeneratePincode(context_); + // 显示PIN码 + if (AuthSinkStatePinAuthComm::ShowAuthInfoDialog(context_) != DM_OK) { + LOGI("ShowAuthInfoDialog err."); + context_->reason = ERR_DM_BIND_USER_CANCEL; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + } + } else { + context_->authFailTimes++; + } + // 失败 MAX_AUTH_FAIL_TIMES 次后,走认证失败 ON_FAIL + if (context_->authFailTimes >= MAX_AUTH_FAIL_TIMES) { + context_->reason = ERR_DM_INPUT_PARA_INVALID; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + } else { + // Notify ON_ERROR 事件,对应 Action 内会当正常重试处理,而非失败 + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); + // 将由新收到的120报文触发回退状态到 AuthSinkPinAuthStartState + } + } + LOGI("AuthSinkManager::AuthDeviceError leave."); +} + +bool AuthSrcManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) +{ + LOGI("AuthSrcManager::AuthDeviceTransmit start."); + // check request id first + if (requestId != context_->requestId) { + LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64"is error.", requestId); + return false; + } + + context_->transmitData = std::string(reinterpret_cast(data), dataLen); + context_->authStateMachine->NotifyEventFinish(ON_TRANSMIT); + LOGI("AuthSrcManager::AuthDeviceTransmit leave."); + return true; +} + +bool AuthSinkManager::AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) +{ + LOGI("AuthSinkManager::AuthDeviceTransmit start."); + // check request id first + if (requestId != context_->requestId) { + LOGE("AuthSinkManager::onTransmit requestId %{public}" PRId64"is error.", requestId); + return false; + } + + context_->transmitData = std::string(reinterpret_cast(data), dataLen); + context_->authStateMachine->NotifyEventFinish(ON_TRANSMIT); + LOGI("AuthSinkManager::AuthDeviceTransmit leave."); + return true; +} +void AuthSrcManager::AuthDeviceFinish(int64_t requestId) +{ + LOGI("AuthSrcManager::AuthDeviceFinish start."); + context_->authStateMachine->NotifyEventFinish(ON_FINISH); + LOGI("AuthSrcManager::AuthDeviceFinish leave."); +} + +void AuthSinkManager::AuthDeviceFinish(int64_t requestId) +{ + LOGI("AuthSinkManager::AuthDeviceFinish start."); + context_->authStateMachine->NotifyEventFinish(ON_FINISH); + LOGI("AuthSinkManager::AuthDeviceFinish leave."); +} + +int32_t AuthManager::GetPinCode(int32_t &code) +{ + if (context_ == nullptr) { + LOGE("AuthManager failed to GetPinCode because context_ is nullptr"); + return ERR_DM_FAILED; + } + LOGI("GetPinCode called."); + code = context_->pinCode; + return DM_OK; +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 6c7bc889b..de29f1f18 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -14,10 +14,25 @@ */ #include "dm_auth_state.h" +// #include "service_info_profile.h" +#include "dm_auth_context.h" +#include "dm_log.h" +#include "dm_dialog_manager.h" +#include "dm_anonymous.h" +#include "dm_auth_state_machine.h" +#include "deviceprofile_connector.h" +#undef LOG_TAG +#define LOG_TAG "DHDM_V2" namespace OHOS { namespace DistributedHardware { +constexpr const char* TAG_APP_OPERATION = "APPOPERATION"; +constexpr const char* TAG_CUSTOM_DESCRIPTION = "CUSTOMDESC"; +constexpr const char* TAG_LOCAL_DEVICE_TYPE = "LOCALDEVICETYPE"; +constexpr const char* TAG_REQUESTER = "REQUESTER"; +constexpr const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; + /* 用户授权(100和110报文处理) source端状态: @@ -27,5 +42,185 @@ sink端状态: AuthSinkConfirmState, // 收到100用户授权报文,发送110报文 */ +DmAuthStateType AuthSrcConfirmState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_CONFIRM_STATE; +} + +int32_t AuthSrcConfirmState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcConfirmState::Action start"); + + LOGI("AuthSrcConfirmState::Action ok"); + return DM_OK; +} + +DmAuthStateType AuthSinkConfirmState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_CONFIRM_STATE; +} + +int32_t AuthSinkConfirmState::ShowConfigDialog(std::shared_ptr context) +{ + LOGI("AuthSinkConfirmState::ShowConfigDialog start"); + + if (IsScreenLocked()) { + LOGE("AuthSinkConfirmState::ShowStartAuthDialog screen is locked."); + context->reason = ERR_DM_BIND_USER_CANCEL; + context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + return STOP_BIND; + } + + nlohmann::json jsonObj; + jsonObj[TAG_APP_OPERATION] = context->appOperation; + jsonObj[TAG_CUSTOM_DESCRIPTION] = context->customData; + jsonObj[TAG_LOCAL_DEVICE_TYPE] = context->accesser.deviceType; + jsonObj[TAG_REQUESTER] = context->accesser.deviceName; + jsonObj[TAG_HOST_PKGLABEL] = context->pkgName; + + const std::string params = SafetyDump(jsonObj); + DmDialogManager::GetInstance().ShowConfirmDialog(params); + + LOGI("AuthSinkConfirmState::ShowConfigDialog end"); + return DM_OK; +} +#if 0 +int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context) +{ + // DP 接口 查询ServiceInfoProfile + std::vector serviceInfos; + DistributedDeviceProfile::ServiceInfoUniqueKey key(context->accessee.deviceId, + context->accessee.userId, context->accessee.tokenId, context->accessee.serviceId); + if (DeviceProfileConnector::GetInstance().GetServiceInfoProfileListByTokenId(key, serviceInfos) != DM_OK) { + // 获取不到走PIN认证方案 + context->authType = DmAuthType::AUTH_TYPE_PIN_SHOW; + return DM_OK; + } + + LOGI("AuthSinkConfirmState::Action GetServiceInfoByTokenId ret ok"); + + // 过滤掉 以下2个字段不为空(或0)的 serviceInfo + // serviceId 发布的服务ID,服务的唯一标识 + // serviceType 发布的服务类型 + std::vector filterServiceInfos; + for (auto& serviceInfo : serviceInfos) { + if (serviceInfo.GetServiceId() == 0 && serviceInfo.GetServiceType().empty()) { + filterServiceInfos.push_back(serviceInfo); + } + } + + // 期望有且仅有一条符合的 serviceInfo + if (filterServiceInfos.size() != 1) { + LOGE("AuthSinkConfirmState::GetAuthType filterServiceInfo not unique"); + return STOP_BIND; + } + + auto& srvInfo = filterServiceInfos[0]; // 弹框用到 serviceInfo 中的内容? + + auto authBoxType = srvInfo.GetAuthBoxType(); + int32_t pinExchangeType = srvInfo.GetPinExchangeType(); + if (authBoxType == DistributedDeviceProfile::NUM_1) { + context->authType = DmAuthType::AUTH_TYPE_PIN_SHOW; // 三态框 + return DM_OK; + } else if (authBoxType == DistributedDeviceProfile::NUM_2) { + int32_t authResult = srvInfo.GetAuthType(); + if (authResult == 0) { + context->authResult = USER_OPERATION_TYPE_ALLOW_AUTH; + } else if (authResult == DistributedDeviceProfile::NUM_1) { + context->authResult = USER_OPERATION_TYPE_CANCEL_AUTH; + } else if (authResult == DistributedDeviceProfile::NUM_6) { + context->authResult = USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + } + + if (pinExchangeType == DistributedDeviceProfile::NUM_2) { // 超声交换PIN + context->authType = DmAuthType::AUTH_TYPE_PIN_ULTRASONIC; + return DM_OK; + } else if (pinExchangeType == DistributedDeviceProfile::NUM_3) { // 导入PIN + context->authType = DmAuthType::AUTH_TYPE_PIN_IMPORT; + // 读取PIN码 + std::string pinCode = srvInfo.GetPinCode(); + context->pinCode = std::stoi(pinCode); + return DM_OK; + } + } + + LOGE("AuthSinkConfirmState::GetAuthType authType not support"); + return STOP_BIND; +} +#else +int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context) +{ + context->authResult = USER_OPERATION_TYPE_ALLOW_AUTH; + return DM_OK; +} +#endif + +int64_t AuthSinkConfirmState::GenRequestId(std::shared_ptr context) +{ + uint64_t requestId = static_cast(context->sessionId); + requestId <<= 32; // 高32位为sessionId + requestId += static_cast(DmAuthStateType::AUTH_SINK_CONFIRM_STATE); // 低32位为状态编号 + return static_cast(requestId); +} + +int32_t AuthSinkConfirmState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkConfirmState::Action start"); + // 停止授权报文计时 + context->timer->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); + context->requestId = GenRequestId(context); + auto ret = GetAuthType(context); + if (ret != DM_OK) { + return ret; + } + + if (context->authType == DmAuthType::AUTH_TYPE_PIN_SHOW) { // 三态框 + LOGI("AuthSinkConfirmState::Action AUTH_TYPE_PIN_SHOW "); + // 拉起授权确认页面 + if ((ret = ShowConfigDialog(context)) != DM_OK) { + return ret; + } + // 等待用户授权操作完成 + if(DmEventType::ON_USER_OPERATION != context->authStateMachine->WaitExpectEvent(DmEventType::ON_USER_OPERATION)) { + LOGE("AuthSinkConfirmState::Action wait ON_USER_OPERATION err"); + return STOP_BIND; // 外部事件错误,中止流程 + } + // 判断授权结果 + if (context->reply == USER_OPERATION_TYPE_ALLOW_AUTH) { + LOGI("AuthSinkConfirmState::Action USER_OPERATION_TYPE_ALLOW_AUTH"); + // 发送110报文 + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); + // 生成PIN码 + AuthSinkStatePinAuthComm::GeneratePincode(context); + // 显示PIN码 + if ((ret = AuthSinkStatePinAuthComm::ShowAuthInfoDialog(context)) != DM_OK) { + return ret; + } + } else { + LOGI("AuthSinkConfirmState::Action USER_OPERATION_TYPE_CANCEL_AUTH"); + context->reason = ERR_DM_BIND_USER_CANCEL; + return STOP_BIND; // 用户取消授权 + } + } else { + if (context->authResult == USER_OPERATION_TYPE_CANCEL_AUTH) { + LOGI("AuthSinkConfirmState::Action USER_OPERATION_TYPE_CANCEL_AUTH"); + context->reason = ERR_DM_BIND_USER_CANCEL; + return STOP_BIND; // 用户取消授权 + } + if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { // 超声交换PIN + LOGI("AuthSinkConfirmState::Action AUTH_TYPE_PIN_ULTRASONIC"); + // 发送110报文 + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); + // 请求发送超声PIN码 + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_IMPORT) { // 导入PIN + LOGI("AuthSinkConfirmState::Action AUTH_TYPE_PIN_IMPORT"); + // 发送110报文 + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); + } + } + LOGI("AuthSinkConfirmState::Action ok"); + return DM_OK; +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 309f24a56..81bd9d03c 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -14,10 +14,25 @@ */ #include "dm_auth_state.h" +#include "dm_auth_context.h" +#include "dm_log.h" +#include "dm_dialog_manager.h" +#include "dm_anonymous.h" +#include "service_info_profile.h" +#include "dm_auth_state_machine.h" +#include "deviceprofile_connector.h" +#include "dm_random.h" +#include "multiple_user_connector.h" +#undef LOG_TAG +#define LOG_TAG "DHDM_V2" namespace OHOS { namespace DistributedHardware { +constexpr int32_t SESSION_HEARTBEAT_TIMEOUT = 20; +constexpr int32_t MIN_PIN_CODE = 100000; +constexpr int32_t MAX_PIN_CODE = 999999; + /* pin码认证(120和130报文处理、121和131报文处理) source端状态: @@ -31,5 +46,281 @@ AuthSinkPinAuthMsgNegotiateState, // 收到121认证PIN报文,发送131报文 AuthSinkPinAuthDoneState, // 触发Onfinish回调事件 */ +int32_t AuthSinkStatePinAuthComm::ShowAuthInfoDialog(std::shared_ptr context) +{ + LOGI("AuthSinkConfirmState::ShowAuthInfoDialog start"); + if (DmAuthState::IsScreenLocked()) { + LOGE("AuthSinkConfirmState::ShowAuthInfoDialog screen is locked."); + context->reason = ERR_DM_BIND_USER_CANCEL; + context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + return STOP_BIND; + } + + DmDialogManager::GetInstance().ShowPinDialog(std::to_string(context->pinCode)); + + context->timer->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), + SESSION_HEARTBEAT_TIMEOUT, [context] (std::string name) { + AuthSinkStatePinAuthComm::HandleSessionHeartbeat(context, name); + }); + return DM_OK; +} + +void AuthSinkStatePinAuthComm::HandleSessionHeartbeat(std::shared_ptr context, std::string name) +{ + if (context->timer == nullptr) { + return; + } + context->timer->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK)); + + LOGI("DmAuthManager::HandleSessionHeartbeat name %{public}s", name.c_str()); + nlohmann::json jsonObj; + jsonObj[TAG_SESSION_HEARTBEAT] = TAG_SESSION_HEARTBEAT; + std::string message = SafetyDump(jsonObj); + context->softbusConnector->GetSoftbusSession()->SendHeartbeatData(context->sessionId, message); + + context->timer->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), + SESSION_HEARTBEAT_TIMEOUT, [context] (std::string name) { + AuthSinkStatePinAuthComm::HandleSessionHeartbeat(context, name); + }); + + LOGI("DmAuthManager::HandleSessionHeartbeat complete"); +} + +void AuthSinkStatePinAuthComm::GeneratePincode(std::shared_ptr context) +{ + context->pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); +} + +DmAuthStateType AuthSrcPinAuthStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE; +} + +int32_t AuthSrcPinAuthStartState::ShowStartAuthDialog(std::shared_ptr context) +{ + LOGI("AuthSrcPinAuthStartState::ShowStartAuthDialog start."); + if (DmAuthState::IsScreenLocked()) { + LOGE("ShowStartAuthDialog screen is locked."); + context->reason = ERR_DM_BIND_USER_CANCEL; + return STOP_BIND; + } + DmDialogManager::GetInstance().ShowInputDialog(context->accessee.deviceName); + LOGI("AuthSrcPinAuthStartState::ShowStartAuthDialog end."); + return DM_OK; +} + +int32_t AuthSrcPinAuthStartState::GetPinCodeFromServerInfo(std::shared_ptr context) +{ + LOGI("AuthSrcPinAuthStartState::GetPinCodeFromServerInfo start"); + int32_t pinCode = 0; // 没获取到返回默认0, 失败后会进入用户输入PIN流程 +#if 0 + std::vector serviceInfos; + DistributedDeviceProfile::ServiceInfoUniqueKey key(context->accesser.deviceId, context->accesser.userId, + context->accesser.tokenId, context->accesser.serviceId); + if (DeviceProfileConnector::GetInstance().GetServiceInfoProfileListByTokenId(key, serviceInfos) == DM_OK) { + std::vector filterServiceInfos; + for (auto& serviceInfo : serviceInfos) { + if (serviceInfo.GetServiceId() == 0 && serviceInfo.GetServiceType().empty()) { + filterServiceInfos.push_back(serviceInfo); + } + } + if (filterServiceInfos.size() == 1) { + auto& srvInfo = filterServiceInfos[0]; + LOGI("AuthSrcPinAuthStartState::GetPinCodeFromServerInfo got pincode from ServiceInfoProfile"); + pinCode = std::atoi(srvInfo.GetPinCode().c_str()); + } + } +#endif + return pinCode; +} + +int32_t AuthSrcPinAuthStartState::GetPinCode(std::shared_ptr context) +{ + LOGI("AuthSrcPinAuthStartState::GetPinCode start"); + if (context->authFailTimes == 0) { + if (context->authType == DmAuthType::AUTH_TYPE_PIN_SHOW || context->fallBackToInputPin) { + // 拉起PIN码输入界面 + auto ret = ShowStartAuthDialog(context); + if (ret != DM_OK) { + return ret; + } + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { + // todo: 预留超声PinCode获取 + return DM_OK; + } else { + // 从serverInfo中读取PIN码 + context->pinCode = GetPinCodeFromServerInfo(context); + return DM_OK; + } + } else { + // 清空PIN输入框,提示用户重试 + context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); + } + + LOGI("AuthSrcPinAuthStartState::GetPinCode waitting user operation"); + // 等待用户输密码操作完成 + if(DmEventType::ON_USER_OPERATION != context->authStateMachine->WaitExpectEvent(DmEventType::ON_USER_OPERATION)) { + LOGI("AuthSrcPinAuthStartState::GetPinCode wait ON_USER_OPERATION err"); + return STOP_BIND; // 外部事件错误,中止流程 + } + + if (context->authResult != USER_OPERATION_TYPE_DONE_PINCODE_INPUT) { + LOGE("AuthSrcPinAuthStartState::GetPinCode not USER_OPERATION_TYPE_DONE_PINCODE_INPUT err"); + return STOP_BIND; + } + LOGI("AuthSrcPinAuthStartState::GetPinCode input ok"); + return DM_OK; +} + + +int32_t AuthSrcPinAuthStartState::AuthDevice(std::shared_ptr context) +{ + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + auto ret = context->hiChainAuthConnector->AuthDevice(context->pinCode, osAccountId, + context->accessee.deviceId, context->requestId); + if (ret != DM_OK) { + LOGE("AuthSrcPinAuthStartState::AuthDevice failed."); + return ret; + } + // 等待hiChain响应 transmit + auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); + if (retEvent == DmEventType::ON_TRANSMIT) { + // 发送120报文 + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_PIN_AUTH_START, context); + return DM_OK; + } else if (retEvent == DmEventType::ON_ERROR) { + LOGI("AuthSrcPinAuthStartState::AuthDevice ON_ERROR failed."); + return DM_OK; + } + + return STOP_BIND; +} + +int32_t AuthSrcPinAuthStartState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcPinAuthStartState::Action start"); + // 首次进入停止计时器 + if (context->authFailTimes == 0 && !context->fallBackToInputPin) { + context->timer->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); + } + + // 获取PIN码 + auto ret = GetPinCode(context); + if (ret != DM_OK) { + LOGE("AuthSrcPinAuthStartState::Action GetPinCode err"); + return ret; + } + + // 做认证 发120报文 + return AuthDevice(context); +} + +DmAuthStateType AuthSinkPinAuthStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE; +} + +int32_t AuthSinkPinAuthStartState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkPinAuthStartState::Action start"); + + auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); + if (ret != DM_OK) { + LOGE("AuthSinkPinAuthStartState::Action call ProcessCredData err"); + return ret; + } + // 等待hiChain响应 transmit + auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); + if (retEvent == DmEventType::ON_TRANSMIT) { + // 发送130报文 + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_PIN_AUTH_START, context); + return DM_OK; + } + if (retEvent == DmEventType::ON_ERROR) { + LOGI("AuthSrcPinAuthStartState::AuthDevice ON_ERROR failed."); + return DM_OK; + } + return STOP_BIND; // 外部事件错误,中止流程 +} + +DmAuthStateType AuthSrcPinAuthMsgNegotiateState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE; +} + +int32_t AuthSrcPinAuthMsgNegotiateState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcPinAuthMsgNegotiateState::Action start"); + auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); + if (ret != DM_OK) { + LOGE("AuthSrcPinAuthMsgNegotiateState::Action call ProcessCredData err"); + return ret; + } + // 等待hiChain响应 transmit + auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); + if (retEvent == DmEventType::ON_TRANSMIT) { + // 发送121报文 + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, context); + return DM_OK; + } + if (retEvent == DmEventType::ON_ERROR) { + LOGI("AuthSrcPinAuthMsgNegotiateState::AuthDevice ON_ERROR failed."); + return DM_OK; + } + return STOP_BIND; // 外部事件错误,中止流程 +} + +DmAuthStateType AuthSinkPinAuthMsgNegotiateState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE; +} + +int32_t AuthSinkPinAuthMsgNegotiateState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkPinAuthMsgNegotiateState::Action start"); + auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); + if (ret != DM_OK) { + LOGE("AuthSinkPinAuthMsgNegotiateState::Action call ProcessCredData err"); + return ret; + } + // 等待hiChain响应 transmit + auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); + if (retEvent == DmEventType::ON_TRANSMIT) { + // 发送131报文 + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, context); + } else if (retEvent == DmEventType::ON_ERROR) { + LOGI("AuthSinkPinAuthMsgNegotiateState::AuthDevice WAIT ON_TRANSMIT ON_ERROR failed."); + return DM_OK; + } else { + return STOP_BIND; + } + + retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_SESSION_KEY_RETURNED); + if (retEvent == DmEventType::ON_SESSION_KEY_RETURNED) { + retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_FINISH); + if (retEvent == DmEventType::ON_FINISH || retEvent == DmEventType::ON_ERROR) { + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } + } else if (retEvent == DmEventType::ON_ERROR) { + LOGI("AuthSinkPinAuthMsgNegotiateState::AuthDevice WAIT ON_SESSION_KEY_RETURNED ON_ERROR failed."); + return DM_OK; + } + + LOGE("AuthSinkPinAuthMsgNegotiateState::AuthDevice failed."); + return STOP_BIND; // 外部事件错误,中止流程 +} + +DmAuthStateType AuthSinkPinAuthDoneState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE; +} + +int32_t AuthSinkPinAuthDoneState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkPinAuthDoneState Action"); + return DM_OK; +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 3d8efd700..65b8b886d 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -14,10 +14,14 @@ */ #include "dm_auth_message_processor.h" +#include "dm_auth_context.h" +#include "dm_auth_state_machine.h" namespace OHOS { namespace DistributedHardware { +constexpr const char* TAG_REPLY = "reply"; +constexpr const char* TAG_DATA = "data"; // 解析报文,返回值为错误码,实际解析出来的信息保存到context中 int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr context, const std::string &message) @@ -33,5 +37,81 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh // 内部各类报文的实现 +void DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const nlohmann::json &json, std::shared_ptr context) +{ + // todo +} +void DmAuthMessageProcessor::ParseMessageReqUserConfirm(const nlohmann::json &json, std::shared_ptr context) +{ + // todo + context->authStateMachine->TransitionTo(std::make_shared()); +} +void DmAuthMessageProcessor::ParseMessageRespUserConfirm(const nlohmann::json &json, std::shared_ptr context) +{ + context->authType = static_cast(json[TAG_AUTH_TYPE].get()); + context->requestId = json[TAG_REQUEST_ID].get(); + if (context->authType == DmAuthType::AUTH_TYPE_PIN_SHOW) { + context->reply = json[TAG_REPLY].get(); + } + + context->authStateMachine->TransitionTo(std::make_shared()); +} +void DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const nlohmann::json &json, std::shared_ptr context) +{ + context->transmitData = json[TAG_DATA].get(); + context->authStateMachine->TransitionTo(std::make_shared()); +} +void DmAuthMessageProcessor::ParseMessageRespPinAuthStart(const nlohmann::json &json, std::shared_ptr context) +{ + context->transmitData = json[TAG_DATA].get(); + context->authStateMachine->TransitionTo(std::make_shared()); + +} +void DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate(const nlohmann::json &json, std::shared_ptr context) +{ + context->transmitData = json[TAG_DATA].get(); + context->authStateMachine->TransitionTo(std::make_shared()); +} + +void DmAuthMessageProcessor::CreateMessageReqUserConfirm(nlohmann::json &json, std::shared_ptr context) +{ + // todo +} + +void DmAuthMessageProcessor::CreateMessageRespUserConfirm(nlohmann::json &json, std::shared_ptr context) +{ + json[TAG_AUTH_TYPE] = context->authType; + json[TAG_REQUEST_ID] = context->requestId; + if (context->authType == DmAuthType::AUTH_TYPE_PIN_SHOW) { + json[TAG_REPLY] = context->reply; + } +} + +void DmAuthMessageProcessor::CreateMessageReqPinAuthStart(nlohmann::json &json, std::shared_ptr context) +{ + json[TAG_DATA] = context->transmitData; +} + +void DmAuthMessageProcessor::CreateMessageRespPinAuthStart(nlohmann::json &json, std::shared_ptr context) +{ + json[TAG_DATA] = context->transmitData; +} + +void DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate(nlohmann::json &json, std::shared_ptr context) +{ + json[TAG_DATA] = context->transmitData; +} + +void DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate(nlohmann::json &json, std::shared_ptr context) +{ + json[TAG_DATA] = context->transmitData; +} + +void DmAuthMessageProcessor::CreateAndSendMsg(DmMessageType msgType, std::shared_ptr context) +{ + auto message = CreateMessage(msgType, context); + context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp new file mode 100644 index 000000000..a1dc8fd31 --- /dev/null +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -0,0 +1,50 @@ +/* + * 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. + */ + +#include "dm_auth_state.h" +#include "dm_auth_context.h" +#include "dm_auth_state_machine.h" +#if defined(SUPPORT_SCREENLOCK) +#include "screenlock_manager.h" +#endif +#include "dm_log.h" + +#undef LOG_TAG +#define LOG_TAG "DHDM_V2" + +namespace OHOS { +namespace DistributedHardware { + +void DmAuthState::HandleAuthenticateTimeout(std::shared_ptr context, std::string name) +{ + LOGI("DmAuthContext::HandleAuthenticateTimeout start timer name %{public}s", name.c_str()); + context->timer->DeleteTimer(name); + context->reason = ERR_DM_TIME_OUT; + context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + LOGI("DmAuthContext::HandleAuthenticateTimeout complete"); +} + +bool DmAuthState::IsScreenLocked() +{ + bool isLocked = false; +#if defined(SUPPORT_SCREENLOCK) + isLocked = OHOS::ScreenLock::ScreenLockManager::GetInstance()->IsScreenLocked(); +#endif + LOGI("IsScreenLocked isLocked: %{public}d.", isLocked); + return isLocked; +} + +} // namespace DistributedHardware +} // namespace OHOS diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 8cf5d6440..11791d0a4 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -28,35 +28,37 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) { stateTransitionTable_ = { // 此处省略下一状态为AuthXXXFinishState的迁移情况 // Source端 状态迁移表 - {AuthIdleState, {AuthSrcStartState}}, - {AuthSrcStartState, {AuthSrcNegotiateState}}, - {AuthSrcNegotiateState, {AuthSrcConfirmState}}, - {AuthSrcConfirmState, {AuthSrcPinAuthStartState}}, - {AuthSrcPinAuthStartState, {AuthSrcPinAuthMsgNegotiateState, AuthSinkConfirmState}}, // PIN输入错误,3次内会回到AuthSinkConfirmState - {AuthSrcPinAuthMsgNegotiateState, {AuthSrcPinAuthDoneState}}, - {AuthSrcPinAuthDoneState, {AuthSrcCredentialExchangeState}}, - {AuthSrcCredentialExchangeState, {AuthSrcCredentialAuthStartState}}, - {AuthSrcCredentialAuthStartState, {AuthSrcCredentialAuthNegotiateState}}, - {AuthSrcCredentialAuthNegotiateState, {AuthSrcCredentialAuthDoneState}}, - {AuthSrcCredentialAuthDoneState, {AuthSrcDataSyncState}}, - {AuthSrcDataSyncState, {}}, + {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SRC_START_STATE}}, + {DmAuthStateType::AUTH_SRC_START_STATE, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE}}, + {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE}}, + {DmAuthStateType::AUTH_SRC_CONFIRM_STATE, {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE}}, + {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, {DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, + DmAuthStateType::AUTH_SINK_CONFIRM_STATE}}, // PIN输入错误,3次内会回到AuthSinkConfirmState + {DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE}}, + {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE}}, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE}}, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE}}, + {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, {}}, // Sink端 状态迁移表 - {AuthIdleState, {AuthSinkStartState}}, - {AuthSinkStartState, {AuthSinkNegotiateState}}, - {AuthSinkNegotiateState, {AuthSinkConfirmState}}, - {AuthSinkConfirmState, {AuthSinkPinAuthStartState}}, - {AuthSinkPinAuthStartState, {AuthSinkPinAuthMsgNegotiateState}}, - {AuthSinkPinAuthMsgNegotiateState, {AuthSinkPinAuthDoneState}}, - {AuthSinkPinAuthDoneState, {AuthSinkCredentialExchangeState}}, - {AuthSinkCredentialExchangeState, {AuthSinkCredentialAuthStartState}}, - {AuthSinkCredentialAuthStartState, {AuthSinkCredentialAuthNegotiateState}}, - {AuthSinkCredentialAuthNegotiateState, {AuthSinkCredentialAuthDoneState}}, - {AuthSinkCredentialAuthDoneState, {AuthSinkDataSyncState}}, - {AuthSinkDataSyncState, {AuthSinkFinishState}}, - {AuthSinkFinishState, {}}, + {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SINK_START_STATE}}, + {DmAuthStateType::AUTH_SINK_START_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, + {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SINK_CONFIRM_STATE}}, + {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, {DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE}}, + {DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, {DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE}}, + {DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE}}, + {DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE}}, + {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, + {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, + {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_DONE_STATE}}, + {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE}}, + {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, {DmAuthStateType::AUTH_SINK_FINISH_STATE}}, + {DmAuthStateType::AUTH_SINK_FINISH_STATE, {}}, }; running_ = true; - this->SetCurState(AuthIdleState); + + this->SetCurState(DmAuthStateType::AUTH_IDLE_STATE); thread_ = std::thread(&DmAuthStateMachine::Run, this, context); } DmAuthStateMachine::~DmAuthStateMachine() @@ -181,7 +183,7 @@ DmAuthStateType DmAuthStateMachine::GetCurState() bool DmAuthStateMachine::CheckStateTransitValid(DmAuthStateType nextState) { // 判断下一状态是否为AuthXXXFinishState,可直接切状态,返回 - if (nextState == AuthSrcFinishState || nextState == AuthSinkFinishState) { + if (nextState == DmAuthStateType::AUTH_SRC_FINISH_STATE || nextState == DmAuthStateType::AUTH_SINK_FINISH_STATE) { return true; } // 判断是否符合状态迁移表 diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 2c22d3baf..99018df91 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -88,6 +88,12 @@ int32_t HiChainAuthConnector::ProcessAuthData(int64_t requestId, std::string aut return DM_OK; } +int32_t HiChainAuthConnector::ProcessCredData(int64_t authReqId, const std::string &data) +{ + // todo + return DM_OK; +} + bool HiChainAuthConnector::onTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) { LOGI("AuthDevice onTransmit, requestId %{public}" PRId64, requestId); -- Gitee From bd291497741c1dd3d205425eeb5271e16700ebe0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B0=A2=E4=BC=9F?= <2247596987@qq.com> Date: Thu, 27 Feb 2025 10:46:29 +0000 Subject: [PATCH 008/382] =?UTF-8?q?!12=20feat=EF=BC=9A=E6=96=B0=E5=8D=8F?= =?UTF-8?q?=E8=AE=AE=E8=AE=A4=E8=AF=81=E7=BB=91=E5=AE=9A=E5=87=AD=E6=8D=AE?= =?UTF-8?q?=E5=8D=8F=E5=95=86=E5=8A=9F=E8=83=BD=E5=AE=9E=E7=8E=B0=EF=BC=88?= =?UTF-8?q?140-150=EF=BC=89=20feat=EF=BC=9A=E6=96=B0=E5=8D=8F=E8=AE=AE?= =?UTF-8?q?=E7=BB=91=E5=AE=9A=E8=AE=A4=E8=AF=81=E5=87=AD=E6=8D=AE=E4=BA=A4?= =?UTF-8?q?=E6=8D=A2=E5=8D=8F=E5=95=86=E5=8A=9F=E8=83=BD=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/implementation/BUILD.gn | 1 + .../include/authentication_v2/auth_manager.h | 2 + .../authentication_v2/dm_auth_context.h | 70 ++++- .../dm_auth_message_processor.h | 68 ++++- .../include/authentication_v2/dm_auth_state.h | 89 ++++++ .../hichain/hichain_auth_connector.h | 15 + .../src/authentication_v2/auth_manager.cpp | 56 +++- .../auth_stages/auth_credential.cpp | 288 ++++++++++++++++++ .../auth_stages/auth_pin_auth.cpp | 52 ++++ .../src/authentication_v2/dm_auth_context.cpp | 161 ++++++++++ .../dm_auth_message_processor.cpp | 245 ++++++++++++++- .../hichain/hichain_auth_connector.cpp | 125 +++++++- 12 files changed, 1136 insertions(+), 36 deletions(-) create mode 100644 services/implementation/src/authentication_v2/dm_auth_context.cpp diff --git a/services/implementation/BUILD.gn b/services/implementation/BUILD.gn index 53ad73bc7..dbbf49a7f 100644 --- a/services/implementation/BUILD.gn +++ b/services/implementation/BUILD.gn @@ -189,6 +189,7 @@ if (defined(ohos_lite)) { "src/authentication_v2/dm_auth_message_processor.cpp", "src/authentication_v2/dm_auth_state_machine.cpp", "src/authentication_v2/dm_auth_state.cpp", + "src/authentication_v2/dm_auth_context.cpp", "src/config/dm_config_manager.cpp", "src/credential/dm_credential_manager.cpp", "src/cryptomgr/crypto_mgr.cpp", diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index e52fba7d8..d3ae5b279 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -47,6 +47,7 @@ public: 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; private: }; @@ -58,6 +59,7 @@ public: 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; private: }; diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 12beada18..950c5b357 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -26,8 +26,13 @@ #include "dm_auth_message_processor.h" #include "softbus_connector.h" #include "softbus_session.h" +#include "nlohmann/json.hpp" + #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 { @@ -53,6 +58,19 @@ enum DmBindType { DM_AUTH_DEVICEID, }; +// 本端/远端 +enum DmAuthSide { + DM_AUTH_LOCAL_SIDE = 0, // 本端 + DM_AUTH_REMOTE_SIDE, // 远端 +}; + +// 凭据或公钥级别 authorizedScope +enum DmAuthScope { + DM_AUTH_SCOPE_DEVICE = 1, // 设备级凭据 + DM_AUTH_SCOPE_USER, // 用户级凭据 + DM_AUTH_SCOPE_APP, // 应用级凭据 +}; + struct DmPeerTargetAddress { std::string peerBrMacAddress; //一碰投使用,直接可以蓝牙建链 std::string peerBleMacAddress; //一碰投使用,直接可以蓝牙建链 @@ -83,9 +101,10 @@ struct DmAccess { int64_t serviceId; // 保留字段,后续会使用 std::string accesserHapSignature; int32_t bindLevel; // 为业务透传数据,无需自定义 - std::string publicKey; // T公钥长度 - int32_t userCredentialId; // 用户凭据ID - int32_t credentialId; // 应用凭据ID + std::string userCredentialId; // 用户级凭据Id + std::string appCredentialId; // 应用级凭据Id + std::string userPublicKey; // 用户级公钥 + std::string appPublicKey; // 应用级公钥 int32_t status; // 表示服务为前台还是后台,业务透传,只保存 int32_t sessionKeyId; // 作为秘钥派送的材料,在总线中取出sk int64_t skTimeStamp; // 老化,时间为2天 @@ -98,6 +117,7 @@ struct DmAccess { }; struct DmAuthContext { + bool isOnline; // 是否上线 DmMessageType msgType; // 报文类型,枚举MsgType int32_t sessionId; // 总线传输会话ID int64_t requestId; // hichain认证ID @@ -119,6 +139,7 @@ struct DmAuthContext { DmAuthDirection direction; // 标识认证方向 ProcessInfo processInfo; // 进程信息 DmPeerTarget peerTarget; // 对端目标的信息 + bool isAppCredentialVerified; // 应用级凭据是否认证 DmAccess accesser; DmAccess accessee; std::multimap proxy; // 前面是accesser,后面是accessee @@ -128,9 +149,46 @@ struct DmAuthContext { std::string transmitData; // 保存 onTrasmit返回数据 std::shared_ptr timer; std::shared_ptr authUiStateMgr; - std::shared_ptr hiChainAuthConnector; - std::shared_ptr authMessageProcessor; - std::shared_ptr softbusConnector; + std::shared_ptr hiChainAuthConnector; // HiChain交互接口 + std::shared_ptr authMessageProcessor; // 报文处理接口 + std::shared_ptr softbusConnector; // 软总线接口 + + // 获取设备ID + std::string GetDeviceId(DmAuthSide side); + // 获取凭据ID + std::string GetCredentialId(DmAuthSide side, DmAuthScope authorizedScope); + // 获取公钥 + std::string GetPublicKey(DmAuthSide side, DmAuthScope authorizedScope); + // 设置凭据ID + int32_t SetCredentialId(DmAuthSide side, DmAuthScope authorizedScope, const std::string &credentialId); + // 设置公钥 + int32_t SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope, const std::string &publicKey); + + // 设置扩展字段,key-value格式 + template + int32_t SetContextExtra(const std::string &key, const T &value) + { + nlohmann::json jsonExtra = nlohmann::json::parse(extraInfo); + if (jsonExtra.is_discarded()) { + return ERR_DM_FAILED; + } + + jsonExtra[key] = value; + extraInfo = SafetyDump(jsonExtra); + return DM_OK; + } + + // 获取扩展字段中key对应的value + template + int32_t GetFromContextExtra(const std::string &key, T &value) + { + nlohmann::json jsonExtra = nlohmann::json::parse(extraInfo); + if (jsonExtra.is_discarded()) { + return ERR_DM_FAILED; + } + value = jsonExtra[key].get(); + return DM_OK; + } }; } // namespace DistributedHardware diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index c68231aa3..c1d0b0ac9 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -19,6 +19,8 @@ #include #include "nlohmann/json.hpp" +#include "crypto_mgr.h" + namespace OHOS { namespace DistributedHardware { struct DmAuthContext; @@ -47,6 +49,29 @@ enum DmMessageType { MSG_TYPE_AUTH_FINISH = 200, }; +constexpr const char *DM_TAG_MSG_TYPE = "messageType"; // 报文类型 +constexpr const char *DM_TAG_DATA = "data"; // 报文数据 +constexpr const char *DM_TAG_USER_PUBLICK_KEY = "userPublicKey"; // 用户级公钥 userPublicKey +constexpr const char *DM_TAG_APP_PUBLICK_KEY = "appPublicKey"; // 应用级公钥 appPublicKey +constexpr const char *DM_TAG_USER_CREDENTIAL_ID = "userCredentialId"; // 用户级凭据Id +constexpr const char *DM_TAG_APP_CREDENTIAL_ID = "appCredentialId"; // 应用级凭据Id +constexpr const char *DM_TAG_ON_TRANSMIT_DATA = "onTransmitData"; // onTransmitData接口返回信息 + +// is接口入参 json格式字符串中的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 = "credentialOwner"; +constexpr const char *DM_AUTH_CREDENTIAL_OWNER = "DM"; // 凭据拥有者 + class DmAuthMessageProcessor { public: // 解析报文,返回值为错误码,实际解析出来的信息保存到context中 @@ -55,33 +80,50 @@ public: std::string CreateMessage(DmMessageType msgType, std::shared_ptr context); // 创建报文并发送 void CreateAndSendMsg(DmMessageType msgType, std::shared_ptr context); + // 保存秘钥 + int32_t SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyLen); private: // 内部各类报文的实现 // 解析 90 报文 - void ParseMessageRespAclNegotiate(const nlohmann::json &json, std::shared_ptr context); + int32_t ParseMessageRespAclNegotiate(const nlohmann::json &json, std::shared_ptr context); // 解析 100 报文 - void ParseMessageReqUserConfirm(const nlohmann::json &json, std::shared_ptr context); + int32_t ParseMessageReqUserConfirm(const nlohmann::json &json, std::shared_ptr context); // 解析 110 报文 - void ParseMessageRespUserConfirm(const nlohmann::json &json, std::shared_ptr context); + int32_t ParseMessageRespUserConfirm(const nlohmann::json &json, std::shared_ptr context); // 解析 120 报文 - void ParseMessageReqPinAuthStart(const nlohmann::json &json, std::shared_ptr context); + int32_t ParseMessageReqPinAuthStart(const nlohmann::json &json, std::shared_ptr context); // 解析 130 报文 - void ParseMessageRespPinAuthStart(const nlohmann::json &json, std::shared_ptr context); + int32_t ParseMessageRespPinAuthStart(const nlohmann::json &json, std::shared_ptr context); // 解析 121 报文 - void ParseMessageReqPinAuthNegotiate(const nlohmann::json &json, std::shared_ptr context); - + int32_t ParseMessageReqPinAuthNegotiate(const nlohmann::json &json, std::shared_ptr context); + // 解析131报文onTransmitData返回的数据,存在contextd->extra中 + int32_t ParseMessageOnTransmit(const nlohmann::json &jsonObject, std::shared_ptr context); + // 解析140报文信息MSG_TYPE_REQ_CREDENTIAL_EXCHANGE,SINK端存放对方公钥 + int32_t ParseMessageReqCredExchange(const nlohmann::json &jsonObject, std::shared_ptr context); + // 解析150报文信息MSG_TYPE_RESP_CREDENTIAL_EXCHANGE,存放对方公钥,和协商凭据Id + int32_t ParseMessageRspCredExchange(const nlohmann::json &jsonObject, std::shared_ptr context); // 创建 100 报文 - void CreateMessageReqUserConfirm(nlohmann::json &json, std::shared_ptr context); + void CreateMessageReqUserConfirm(std::shared_ptr context, nlohmann::json &json); // 创建 110 报文 - void CreateMessageRespUserConfirm(nlohmann::json &json, std::shared_ptr context); + void CreateMessageRespUserConfirm(std::shared_ptr context, nlohmann::json &json); // 创建 120 报文 - void CreateMessageReqPinAuthStart(nlohmann::json &json, std::shared_ptr context); + void CreateMessageReqPinAuthStart(std::shared_ptr context, nlohmann::json &json); // 创建 130 报文 - void CreateMessageRespPinAuthStart(nlohmann::json &json, std::shared_ptr context); + void CreateMessageRespPinAuthStart(std::shared_ptr context, nlohmann::json &json); // 创建 121 报文 - void CreateMessageReqPinAuthNegotiate(nlohmann::json &json, std::shared_ptr context); + void CreateMessageReqPinAuthNegotiate(std::shared_ptr context, nlohmann::json &json); // 创建 131 报文 - void CreateMessageRespPinAuthNegotiate(nlohmann::json &json, std::shared_ptr context); + void CreateMessageRespPinAuthNegotiate(std::shared_ptr context, nlohmann::json &json); + // 创建140报文 + void CreateMessageReqCredExchange(std::shared_ptr context, nlohmann::json &jsonObject); + // 创建150报文 + void CreateMessageRspCredExchange(std::shared_ptr context, nlohmann::json &jsonObject); + // 创建160报文 + void CreateMessageReqCredAuthStart(std::shared_ptr context, nlohmann::json &jsonObject); + +private: + // 内部各类报文的实现 + std::shared_ptr cryptoMgr_ = nullptr; }; } // namespace DistributedHardware diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index c19343493..0dcfc65b6 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -18,6 +18,8 @@ #include +#include "dm_auth_context.h" + namespace OHOS { namespace DistributedHardware { struct DmAuthContext; @@ -130,6 +132,93 @@ public: 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; +}; + +// 凭据协商阶段,AuthSrcCredentialExchangeState AuthSinkCredentialExchangeState AuthSrcCredentialAuthStartState +// 中间类 封装业务相关的公共接口 +class AuthCredentialAgreeState : public DmAuthState { +public: + virtual ~AuthCredentialAgreeState() {}; +protected: + // 凭据添加方式 + enum DmAuthCredentialAddMethod { + DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE = 1, // 生成 + DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT, // 导入 + }; + + // 凭据主体 + enum DmAuthCredentialSubject { + DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY = 1, // 主控 + DM_AUTH_CREDENTIAL_SUBJECT_SUPPLEMENT, // 配件 + }; + + // 凭据与账号关联 + enum DmAuthCredentialAccountRelation { + DM_AUTH_CREDENTIAL_ACCOUNT_RELATED = 1, // 账号相关 + DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED, // 账号无关 + }; + + // 秘钥类型 + enum DmAuthKeyFormat { + 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 { + 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 { + DM_AUTH_CREDENTIAL_PROOF_PSK = 1, // PSK + DM_AUTH_CREDENTIAL_PROOF_PKI, // PKI + }; + + // 生成凭据协商状态下的authParams的json格式字符串 + std::string CreateAuthParamsString(DmAuthScope authorizedScope, DmAuthCredentialAddMethod method, + const std::shared_ptr &authContext); + // 生成凭据Id和公钥 + 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; +}; + } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_AUTH_STATE_V2_H \ No newline at end of file diff --git a/services/implementation/include/dependency/hichain/hichain_auth_connector.h b/services/implementation/include/dependency/hichain/hichain_auth_connector.h index edf1cee17..f03781e12 100644 --- a/services/implementation/include/dependency/hichain/hichain_auth_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_auth_connector.h @@ -58,7 +58,22 @@ public: int32_t DeleteCredential(const std::string &deviceId, int32_t userId); int32_t RegisterHiChainAuthCallback(std::shared_ptr callback); int32_t GetCredential(std::string &localUdid, int32_t osAccountId, std::string &publicKey); + + // 处理凭据认证报文 int32_t ProcessCredData(int64_t authReqId, const std::string &data); + // 生成凭据,返回凭据Id + int32_t AddCredential(int32_t osAccountId, const std::string &authParams, std::string &creId); + // 根据凭据Id导出公钥 + int32_t ExportCredential(int32_t osAccountId, const std::string &credId, std::string &publicKey); + // 凭据协商 + int32_t AgreeCredential(int32_t osAccountId, const std::string selfCredId, const std::string &authParams, + std::string &credId); + // 删除凭据 + int32_t DeleteCredential(int32_t osAccountId, const std::string &creId); + // 凭据认证 pinCode pin码(点对点临时凭据必填) + int32_t AuthCredential(int32_t osAccountId, int64_t authReqId, const std::string &credId, + const std::string &pinCode); + private: void FreeJsonString(char *jsonStr); diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index e5c592a51..70c197cd2 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -13,6 +13,10 @@ * limitations under the License. */ +#include + +#include "dm_auth_message_processor.h" +#include "dm_auth_state_machine.h" #include "auth_manager.h" #include "dm_auth_context.h" #include "dm_log.h" @@ -38,8 +42,28 @@ std::shared_ptr AuthManager::GetAuthContext() // 各类事件触发的函数实现(子类继承实现) // AuthSrcManager -// AuthSinkManager +// 保存秘钥 +void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) +{ + LOGI("AuthSrcManager::AuthDeviceSessionKey start. keyLen: %{public}u", sessionKeyLen); + if (context_ == nullptr || context_->authMessageProcessor == nullptr || context_->authStateMachine == nullptr) { + LOGE("AuthSrcManager::AuthDeviceSessionKey failed, auth context not initial."); + return; + } + if (requestId != context_->requestId) { + LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64 "is error.", requestId); + return; + } + int32_t ret = context_->authMessageProcessor->SaveSessionKey(sessionKey, sessionKeyLen); + if (ret != DM_OK) { + LOGE("AuthSrcManager::AuthDeviceSessionKey, save session key error, ret: %{public}d", ret); + } + + // 通知ON_SESSION_KEY_RETURNED事件完成 + context_->authStateMachine->NotifyEventFinish(ON_SESSION_KEY_RETURNED); +} +// AuthSinkManager int32_t AuthSinkManager::OnUserOperation(int32_t action, const std::string ¶ms) { @@ -199,6 +223,16 @@ void AuthSrcManager::AuthDeviceFinish(int64_t requestId) { LOGI("AuthSrcManager::AuthDeviceFinish start."); context_->authStateMachine->NotifyEventFinish(ON_FINISH); + // 根据当前状态进行业务处理 + DmAuthStateType curState = context_->authStateMachine->GetCurState(); + switch (curState) { + case DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE: + // ON_FINISH事件到来,启动凭据交换 + context_->authStateMachine->TransitionTo(std::make_shared()); + break; + default: + break; + } LOGI("AuthSrcManager::AuthDeviceFinish leave."); } @@ -209,6 +243,26 @@ void AuthSinkManager::AuthDeviceFinish(int64_t requestId) LOGI("AuthSinkManager::AuthDeviceFinish leave."); } +void AuthSinkManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) +{ + LOGI("AuthSrcManager::AuthDeviceSessionKey start. keyLen: %{public}u", sessionKeyLen); + if (context_ == nullptr || context_->authMessageProcessor == nullptr || context_->authStateMachine == nullptr) { + LOGE("AuthSrcManager::AuthDeviceSessionKey failed, auth context not initial."); + return; + } + if (requestId != context_->requestId) { + LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64 "is error.", requestId); + return; + } + int32_t ret = context_->authMessageProcessor->SaveSessionKey(sessionKey, sessionKeyLen); + if (ret != DM_OK) { + LOGE("AuthSrcManager::AuthDeviceSessionKey, save session key error, ret: %{public}d", ret); + } + + // 通知ON_SESSION_KEY_RETURNED事件完成 + context_->authStateMachine->NotifyEventFinish(ON_SESSION_KEY_RETURNED); +} + int32_t AuthManager::GetPinCode(int32_t &code) { if (context_ == nullptr) { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index b61adfb84..1f8488d04 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -13,6 +13,13 @@ * limitations under the License. */ +#include +#include +#include + +#include "dm_auth_state_machine.h" +#include "multiple_user_connector.h" +#include "dm_auth_message_processor.h" #include "dm_auth_state.h" namespace OHOS { @@ -39,5 +46,286 @@ AuthSinkCredentialAuthDoneState, // 触发Onfinish回调事件 */ +// 生成凭据协商状态下的authParams的json格式字符串 +// authScope 设备级还是应用级 +// method 凭据生成方式 +// authContext 上下文指针 +std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authorizedScope, + DmAuthCredentialAddMethod method, const std::shared_ptr &authContext) +{ + // 参数校验 + if ((authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP) || + (method != DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE && method != DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT)) { + return std::string(""); + } + + nlohmann::json jsonObj; + jsonObj[DM_TAG_METHOD] = method; // 凭据生成方式 + jsonObj[DM_TAG_DEVICE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? // 设备ID 生成是本端,导入是对端 + authContext->GetDeviceId(DM_AUTH_LOCAL_SIDE) : authContext->GetDeviceId(DM_AUTH_REMOTE_SIDE); + jsonObj[DM_TAG_PEER_USER_SPACE_ID] = std::to_string(-1); // -1 非法值 + jsonObj[DM_TAG_SUBJECT] = DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY; // 主控设备 + jsonObj[DM_TAG_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; // 账号无关 + jsonObj[DM_TAG_KEY_FORMAT] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? + DM_AUTH_KEY_FORMAT_ASYMM_GENERATE : DM_AUTH_KEY_FORMAT_ASYMM_IMPORT; // 生成或导入非对称秘钥 + jsonObj[DM_TAG_ALGORITHM_TYPE] = DM_AUTH_ALG_TYPE_ED25519; // ED25519; + jsonObj[DM_TAG_PROOF_TYPE] = DM_AUTH_CREDENTIAL_PROOF_PSK; // PSK + if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) { // 导入公钥 16进制字符串 + std::stringstream ss; + ss.str(""); + std::string publicKey = authContext->GetPublicKey(DM_AUTH_REMOTE_SIDE, authorizedScope); + for (auto &c : publicKey) { + ss << std::hex << std::setw(2) << std::setfill('0') << c; // 2 输出填充2字节 + } + jsonObj[DM_TAG_KEY_VALUE] = ss.str(); + } + jsonObj[DM_TAG_AUTHORIZED_SCOPE] = authorizedScope; // 用户级或者应用级 + if (authorizedScope == DM_AUTH_SCOPE_APP) { + jsonObj[DM_TAG_AUTHRIZED_APP_LIST] = {authContext->accesser.tokenId, authContext->accessee.tokenId}; + } + jsonObj[DM_TAG_CREDENTIAL_OWNER] = DM_AUTH_CREDENTIAL_OWNER; // 调用方包名DM模块 + + return SafetyDump(jsonObj); +} + +// 生成凭据Id和公钥 +// authorizedScope 用户级还是应用级 +// authContext 上下文 +int32_t AuthCredentialAgreeState::GenerateCredIdAndPublicKey(DmAuthScope authorizedScope, + std::shared_ptr &authContext) +{ + if ((authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP) || + authContext == nullptr || authContext->hiChainAuthConnector == nullptr) { + return ERR_DM_FAILED; + } + + // 创建authParams的json格式字符串 + std::string authParamsString = CreateAuthParamsString(authorizedScope, + DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE, authContext); + if (authParamsString == "") { + LOGE("AuthCredentialAgreeState::GenerateCredIdAndPublicKey() error, create authParamsString failed."); + return ERR_DM_FAILED; + } + + // 生成凭据 + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + std::string credId; + int32_t ret = authContext->hiChainAuthConnector->AddCredential(osAccountId, authParamsString, credId); + if (ret != DM_OK) { + LOGE("AuthCredentialAgreeState::GenerateCredIdAndPublicKey() error, add credential failed."); + return ret; + } + + // 导出公钥 + std::string publicKey; + ret = authContext->hiChainAuthConnector->ExportCredential(osAccountId, credId, publicKey); + if (ret != DM_OK) { + LOGE("AuthCredentialAgreeState::GenerateCredIdAndPublicKey(), export publicKey failed."); + authContext->hiChainAuthConnector->DeleteCredential(osAccountId, credId); + return ret; + } + + // 保存凭据Id和公钥 + (void)authContext->SetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope, credId); + (void)authContext->SetPublicKey(DM_AUTH_LOCAL_SIDE, authorizedScope, publicKey); + + return DM_OK; +} + +// 协商凭据得到协商凭据Id +// authorizedScope 设备级还是应用级 +// authContext 上下文 +int32_t AuthCredentialAgreeState::AgreeCredential(DmAuthScope authorizedScope, + std::shared_ptr &authContext) +{ + if ((authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP) || authContext == nullptr) { + return ERR_DM_FAILED; + } + + // 创建authParams的json格式字符串 + std::string authParamsString = CreateAuthParamsString(authorizedScope, + DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT, authContext); + if (authParamsString == "") { + LOGE("AuthCredentialAgreeState::AgreeCredential() error, create authParamsString failed."); + return ERR_DM_FAILED; + } + + // 凭据协商得到协商凭据Id + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + std::string selfCredId = authContext->GetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope); + std::string credId; + int32_t ret = authContext->hiChainAuthConnector->AgreeCredential(osAccountId, selfCredId, + authParamsString, credId); + if (ret != DM_OK) { + LOGE("AuthCredentialAgreeState::AgreeCredential() error, agree credential failed."); + } + + // 保存协商凭据Id到上下文 + (void)authContext->SetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope, credId); + + return DM_OK; +} + +DmAuthStateType AuthSrcCredentialExchangeState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE; +} + +int32_t AuthSrcCredentialExchangeState::Action(std::shared_ptr context) +{ + int32_t ret = ERR_DM_FAILED; + context->isAppCredentialVerified = false; + + // 首次认证,生成用户级凭据和公钥 + if (!context->isOnline) { + ret = GenerateCredIdAndPublicKey(DM_AUTH_SCOPE_USER, context); + if (ret != DM_OK) { + LOGE("AuthSrcCredentialExchangeState::Action() error, generate user credId and publicKey failed."); + return ret; + } + } + + // 生成应用级凭据和公钥 + ret = GenerateCredIdAndPublicKey(DM_AUTH_SCOPE_APP, context); + if (ret != DM_OK) { + LOGE("AuthSrcCredentialExchangeState::Action() error, generate app credId and publicKey failed."); + return ret; + } + + // 发送140报文 + std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, context); + return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); +} + +DmAuthStateType AuthSinkCredentialExchangeState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE; +} + +int32_t AuthSinkCredentialExchangeState::Action(std::shared_ptr context) +{ + int32_t ret = ERR_DM_FAILED; + std::string tmpCredId; + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + context->isAppCredentialVerified = false; + + if (context == nullptr || context->hiChainAuthConnector == nullptr || + context->authMessageProcessor == nullptr || context->softbusConnector == nullptr) { + return ret; + } + + // 首次认证 + if (!context->isOnline) { + // 生成用户级凭据和公钥 + ret = GenerateCredIdAndPublicKey(DM_AUTH_SCOPE_USER, context); + if (ret != DM_OK) { + LOGE("AuthSinkCredentialExchangeState::Action failed, generate user cred and publicKey failed."); + return ret; + } + + // 协商用户级凭据 + tmpCredId = context->accessee.userCredentialId; + ret = AgreeCredential(DM_AUTH_SCOPE_USER, context); + if (ret != DM_OK) { + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + context->SetCredentialId(DM_AUTH_LOCAL_SIDE, DM_AUTH_SCOPE_USER, ""); + LOGE("AuthSinkCredentialExchangeState::Action failed, agree user cred failed."); + return ret; + } + + // 删除临时用户级凭据 + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + } + + // 生成应用级凭据和公钥 + ret = GenerateCredIdAndPublicKey(DM_AUTH_SCOPE_APP, context); + if (ret != DM_OK) { + LOGE("AuthSinkCredentialExchangeState::Action failed, generate app cred and publicKey failed."); + return ret; + } + + // 协商应用级公钥 + tmpCredId = context->accessee.appCredentialId; + ret = AgreeCredential(DM_AUTH_SCOPE_APP, context); + if (ret != DM_OK) { + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + context->SetCredentialId(DM_AUTH_LOCAL_SIDE, DM_AUTH_SCOPE_APP, ""); + LOGE("AuthSinkCredentialExchangeState::Action failed, agree app cred failed."); + return ret; + } + + // 删除临时应用级凭据 + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + + // 发送150报文 + std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, context); + return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); +} + +DmAuthStateType AuthSrcCredentialAuthStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE; +} + + +int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr context) +{ + int32_t ret = ERR_DM_FAILED; + std::string tmpCredId; + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + + if (context == nullptr || context->hiChainAuthConnector == nullptr || + context->authMessageProcessor == nullptr || context->softbusConnector == nullptr) { + return ret; + } + + // 首次认证 + if (!context->isOnline) { + // 协商用户级凭据 + tmpCredId = context->accesser.userCredentialId; + ret = AgreeCredential(DM_AUTH_SCOPE_USER, context); + if (ret != DM_OK) { + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + context->SetCredentialId(DM_AUTH_LOCAL_SIDE, DM_AUTH_SCOPE_USER, ""); + LOGE("AuthSrcCredentialAuthStartState::Action failed, agree user cred failed."); + return ret; + } + + // 删除临时用户级凭据 + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + } + + // 协商应用级凭据 + tmpCredId = context->accesser.appCredentialId; + ret = AgreeCredential(DM_AUTH_SCOPE_APP, context); + if (ret != DM_OK) { + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + context->SetCredentialId(DM_AUTH_LOCAL_SIDE, DM_AUTH_SCOPE_APP, ""); + LOGE("AuthSrcCredentialAuthStartState::Action failed, agree app cred failed."); + return ret; + } + + // 删除临时应用级凭据 + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + + // 凭据认证 先进行应用级 + ret = context->hiChainAuthConnector->AuthCredential(osAccountId, context->requestId, + context->accessee.appCredentialId, std::string("")); + if (ret != DM_OK) { + LOGE("AuthSrcCredentialAuthStartState::Action failed, auth app cred failed."); + return ret; + } + + // 阻塞等待事件ON_TRANSMIT事件到来 + if (context->authStateMachine->WaitExpectEvent(ON_TRANSMIT) != ON_TRANSMIT) { + LOGE("AuthSrcCredentialAuthStartState::Action failed, ON_TRANSMIT event not arrived."); + return ERR_DM_FAILED; + } + + // 发送160报文 + std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_REQ_CREDENTIAL_AUTH_START, context); + return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 81bd9d03c..113a129cc 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -13,6 +13,10 @@ * limitations under the License. */ + +#include "hichain_auth_connector.h" +#include "dm_auth_state_machine.h" +#include "dm_auth_message_processor.h" #include "dm_auth_state.h" #include "dm_auth_context.h" #include "dm_log.h" @@ -322,5 +326,53 @@ int32_t AuthSinkPinAuthDoneState::Action(std::shared_ptr context) return DM_OK; } +DmAuthStateType AuthSrcPinAuthDoneState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE; +} + +int32_t AuthSrcPinAuthDoneState::Action(std::shared_ptr context) +{ + if (context == nullptr || context->hiChainAuthConnector == nullptr) { + LOGE("AuthSrcPinAuthDoneState::Action failed, auth context not initial."); + return ERR_DM_FAILED; + } + + std::string onTransmitData; + if (context->GetFromContextExtra(DM_TAG_DATA, onTransmitData) != DM_OK) { + LOGE("AuthSrcPinAuthDoneState::Action error, get onTransmitData From extra failed."); + return ERR_DM_FAILED; + } + + // 处理凭据数据 + if (context->hiChainAuthConnector->ProcessCredData(context->requestId, onTransmitData) != DM_OK) { + LOGE("AuthSrcPinAuthDoneState::Action failed, processCredData failed."); + return ERR_DM_FAILED; + } + + // 阻塞等待ON_SESSION_KEY_RETURNED事件到来 + DmEventType ret = context->authStateMachine->WaitExpectEvent(ON_SESSION_KEY_RETURNED); + if (ret != ON_SESSION_KEY_RETURNED) { + if (ret == ON_ERROR) { // ON_ERROR事件到来,返回DM_OK, OnError回调中判断是否重试 + LOGE("AuthSrcPinAuthDoneState::Action, ON_SESSION_KEY_RETURNED event not arriverd, try again."); + return DM_OK; + } else { // 其它事件到来 + LOGE("AuthSrcPinAuthDoneState::Action failed, ON_SESSION_KEY_RETURNED event failed, other event arriverd."); + return ERR_DM_FAILED; + } + } + + // 阻塞等待ON_FINISH事件到来 + ret = context->authStateMachine->WaitExpectEvent(ON_FINISH); + if (ret == ON_FINISH) { + return DM_OK; + } else if (ret == ON_ERROR) { // ON_ERROR事件到来,返回DM_OK, OnError回调中判断是否重试 + return DM_OK; + LOGE("AuthSrcPinAuthDoneState::Action, ON_FINISH event not arriverd, try again."); + } + + return ERR_DM_FAILED; +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_context.cpp b/services/implementation/src/authentication_v2/dm_auth_context.cpp new file mode 100644 index 000000000..1446b268f --- /dev/null +++ b/services/implementation/src/authentication_v2/dm_auth_context.cpp @@ -0,0 +1,161 @@ +/* + * 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. + */ + +#include "dm_auth_context.h" + +namespace OHOS { +namespace DistributedHardware { + +// 获取设备ID +std::string DmAuthContext::GetDeviceId(DmAuthSide side) +{ + if (side == DM_AUTH_LOCAL_SIDE) { + return (direction == DM_AUTH_SOURCE) ? accesser.deviceId : accessee.deviceId; + } else if (side == DM_AUTH_REMOTE_SIDE) { + return (direction == DM_AUTH_SOURCE) ? accessee.deviceId : accesser.deviceId; + } else { + return std::string(""); + } +} + +// 获取凭据ID +std::string DmAuthContext::GetCredentialId(DmAuthSide side, DmAuthScope authorizedScope) +{ + if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || + (authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP)) { + return std::string(""); + } + + if (side == DM_AUTH_LOCAL_SIDE) { + if (direction == DM_AUTH_SOURCE) { + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.userCredentialId : accesser.appCredentialId; + } else { + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.userCredentialId : accessee.appCredentialId; + } + } else { + if (direction == DM_AUTH_SOURCE) { + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.userCredentialId : accessee.appCredentialId; + } else { + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.userCredentialId : accesser.appCredentialId; + } + } +} + +// 获取公钥 +std::string DmAuthContext::GetPublicKey(DmAuthSide side, DmAuthScope authorizedScope) +{ + if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || + (authorizedScope != DM_AUTH_SCOPE_USER && DM_AUTH_SCOPE_USER != DM_AUTH_SCOPE_APP)) { + return std::string(""); + } + + if (side == DM_AUTH_LOCAL_SIDE) { + if (direction == DM_AUTH_SOURCE) { + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.userPublicKey : accesser.appPublicKey; + } else { + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.userPublicKey : accessee.appPublicKey; + } + } else { + if (direction == DM_AUTH_SOURCE) { + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.userPublicKey : accessee.appPublicKey; + } else { + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.userPublicKey : accesser.appPublicKey; + } + } +} + +// 设置凭据ID +int32_t DmAuthContext::SetCredentialId(DmAuthSide side, DmAuthScope authorizedScope, const std::string &credentialId) +{ + if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || + (authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP)) { + LOGE("DmAuthContext::SetCredentialId() error, invalid input parameters"); + return ERR_DM_FAILED; + } + if (side == DM_AUTH_LOCAL_SIDE) { + if (direction == DM_AUTH_SOURCE) { + if (authorizedScope == DM_AUTH_SCOPE_USER) { + accesser.userCredentialId = credentialId; + } else { + accesser.appCredentialId = credentialId; + } + } else { + if (authorizedScope == DM_AUTH_SCOPE_USER) { + accessee.userCredentialId = credentialId; + } else { + accessee.appCredentialId = credentialId; + } + } + } else { + if (direction == DM_AUTH_SOURCE) { + if (authorizedScope == DM_AUTH_SCOPE_USER) { + accessee.userCredentialId = credentialId; + } else { + accessee.appCredentialId = credentialId; + } + } else { + if (authorizedScope == DM_AUTH_SCOPE_USER) { + accesser.userCredentialId = credentialId; + } else { + accesser.appCredentialId = credentialId; + } + } + } + return DM_OK; +} + +// 设置公钥 +int32_t DmAuthContext::SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope, const std::string &publicKey) +{ + if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || + (authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP)) { + LOGE("DmAuthContext::SetPublicKey() error, invalid input parameters"); + return ERR_DM_FAILED; + } + + if (side == DM_AUTH_LOCAL_SIDE) { + if (direction == DM_AUTH_SOURCE) { + if (authorizedScope == DM_AUTH_SCOPE_USER) { + accesser.userPublicKey = publicKey; + } else { + accesser.appPublicKey = publicKey; + } + } else { + if (authorizedScope == DM_AUTH_SCOPE_USER) { + accessee.userPublicKey = publicKey; + } else { + accessee.appPublicKey = publicKey; + } + } + } else { + if (direction == DM_AUTH_SOURCE) { + if (authorizedScope == DM_AUTH_SCOPE_USER) { + accessee.userPublicKey = publicKey; + } else { + accessee.appPublicKey = publicKey; + } + } else { + if (authorizedScope == DM_AUTH_SCOPE_USER) { + accesser.userPublicKey = publicKey; + } else { + accesser.appPublicKey = publicKey; + } + } + } + + return DM_OK; +} +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 65b8b886d..ac23b00ca 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -23,30 +23,237 @@ namespace DistributedHardware { constexpr const char* TAG_REPLY = "reply"; constexpr const char* TAG_DATA = "data"; +// 保存秘钥 +int32_t DmAuthMessageProcessor::SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyLen) +{ + if (cryptoMgr_ == nullptr) { + LOGE("DmAuthMessageProcessor::SaveSessionKey failed, cryptoMgr_ is nullptr."); + return ERR_DM_FAILED; + } + return cryptoMgr_->SaveSessionKey(sessionKey, keyLen); +} + // 解析报文,返回值为错误码,实际解析出来的信息保存到context中 int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr context, const std::string &message) { - return 0; + if (context == nullptr) { + return ERR_DM_FAILED; + } + + nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("DmAuthMessageProcessor::ParseMessage failed, decodeRequestAuth jsonStr error"); + return ERR_DM_FAILED; + } + if (!IsInt32(jsonObject, TAG_MSG_TYPE)) { + LOGE("DmAuthMessageProcessor::ParseMessage failed, message type error."); + return ERR_DM_FAILED; + } + DmMessageType msgType = static_cast(jsonObject[TAG_MSG_TYPE].get()); + context->msgType = msgType; + LOGI("DmAuthMessageProcessor::ParseMessage message type %{public}d", context->msgType); + switch (msgType) { + case MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE: + return ParseMessageOnTransmit(jsonObject, context); + case MSG_TYPE_REQ_CREDENTIAL_EXCHANGE: + return ParseMessageReqCredExchange(jsonObject, context); + case MSG_TYPE_RESP_CREDENTIAL_EXCHANGE: + return ParseMessageRspCredExchange(jsonObject, context); + default: + break; + } + return ERR_DM_FAILED; +} + +// 解析onTransmit返回的数据,保存到context->extra中 +int32_t DmAuthMessageProcessor::ParseMessageOnTransmit(const nlohmann::json &jsonObject, + std::shared_ptr context) +{ + if (jsonObject.is_discarded() || !IsString(jsonObject, DM_TAG_DATA)) { + LOGE("DmAuthMessageProcessor::ParseMessageOnTransmit failed, decodeRequestAuth jsonStr error"); + return ERR_DM_FAILED; + } + + context->SetContextExtra(DM_TAG_ON_TRANSMIT_DATA, jsonObject[DM_TAG_DATA].get()); + return DM_OK; +} + +// 解析140报文信息MSG_TYPE_REQ_CREDENTIAL_EXCHANGE,SINK端存放对方公钥 +int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const nlohmann::json &jsonObject, + std::shared_ptr context) +{ + if (jsonObject.is_discarded() || !IsString(jsonObject, DM_TAG_DATA)) { + LOGE("DecodeRequestAuth jsonStr error"); + return ERR_DM_FAILED; + } + + // 解密 + std::string plainText; + if (cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA].get(), plainText) != DM_OK) { + LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange() error, decrypt data failed."); + return ERR_DM_FAILED; + } + nlohmann::json jsonData = nlohmann::json::parse(plainText, nullptr, false); + + // 首次认证,解析用户级公钥 + if (!context->isOnline) { + if (!IsString(jsonData, DM_TAG_USER_PUBLICK_KEY)) { + LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange() error, first auth, no userPublicKey."); + return ERR_DM_FAILED; + } + context->accesser.userPublicKey = jsonData[DM_TAG_USER_PUBLICK_KEY].get(); + } + + // 解析应用级公钥 + if (!IsString(jsonData, DM_TAG_APP_PUBLICK_KEY)) { + LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange() error, no appPublicKey."); + return ERR_DM_FAILED; + } + context->accesser.appPublicKey = jsonData[DM_TAG_APP_PUBLICK_KEY].get(); + return DM_OK; } + +// 解析150报文信息MSG_TYPE_RESP_CREDENTIAL_EXCHANGE,SRC端存放对方公钥,和协商凭据Id +int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const nlohmann::json &jsonObject, + std::shared_ptr context) +{ + if (jsonObject.is_discarded() || !IsString(jsonObject, DM_TAG_DATA)) { + LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange, DecodeRequestAuth jsonStr error"); + return ERR_DM_FAILED; + } + + // 解密 + std::string plainText; + if (cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA].get(), plainText) != DM_OK) { + LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange error, decrypt data failed."); + return ERR_DM_FAILED; + } + nlohmann::json jsonData = nlohmann::json::parse(plainText, nullptr, false); + + // 首次认证,解析对方用户级公钥和协商用户级凭据Id + std::string tmpString; + if (!context->isOnline) { + if (!IsString(jsonData, DM_TAG_USER_PUBLICK_KEY) || !IsString(jsonData, DM_TAG_USER_CREDENTIAL_ID)) { + LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange failed, first auth but no userPublicKey or " + "userCredentialId."); + return ERR_DM_FAILED; + } + context->accessee.userPublicKey = jsonData[DM_TAG_USER_PUBLICK_KEY].get(); + context->accessee.userCredentialId = jsonData[DM_TAG_USER_CREDENTIAL_ID].get(); + } + + // 解析对方应用级公钥和协商应用级凭据Id + if (!IsString(jsonData, DM_TAG_APP_PUBLICK_KEY) || !IsString(jsonData, DM_TAG_APP_CREDENTIAL_ID)) { + LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange failed, no appPublicKey or appCredentialId."); + return ERR_DM_FAILED; + } + context->accessee.appPublicKey = jsonData[DM_TAG_APP_PUBLICK_KEY].get(); + context->accessee.appCredentialId = jsonData[DM_TAG_APP_CREDENTIAL_ID].get(); + return DM_OK; +} + // 创建报文,构造对应msgType的报文,返回值为json格式报文的字符串 std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::shared_ptr context) { - return ""; + LOGI("DmAuthMessageProcessor::CreateMessage start. msgType is %{public}d", msgType); + nlohmann::json jsonObj; + jsonObj[TAG_MSG_TYPE] = msgType; + switch (msgType) { + case MSG_TYPE_REQ_CREDENTIAL_EXCHANGE: + CreateMessageReqCredExchange(context, jsonObj); + break; + case MSG_TYPE_RESP_CREDENTIAL_EXCHANGE: + CreateMessageRspCredExchange(context, jsonObj); + break; + case MSG_TYPE_REQ_CREDENTIAL_AUTH_START: + CreateMessageReqCredAuthStart(context, jsonObj); + break; + default: + LOGE("DmAuthMessageProcessor::CreateMessage msgType %{public}d error.", msgType); + break; + } + return SafetyDump(jsonObj); } // 内部各类报文的实现 +// 创建140报文 +void DmAuthMessageProcessor::CreateMessageReqCredExchange(std::shared_ptr context, + nlohmann::json &jsonObject) +{ + nlohmann::json jsonData; + if (!context->isOnline) { + jsonData[DM_TAG_USER_PUBLICK_KEY] = context->accesser.userPublicKey; + } + jsonData[DM_TAG_APP_PUBLICK_KEY] = context->accesser.appPublicKey; + std::string plainText = SafetyDump(jsonData); + std::string cipherText; + cryptoMgr_->EncryptMessage(plainText, cipherText); + jsonObject[DM_TAG_DATA] = cipherText; +} -void DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const nlohmann::json &json, std::shared_ptr context) +// 创建150报文 +void DmAuthMessageProcessor::CreateMessageRspCredExchange(std::shared_ptr context, + nlohmann::json &jsonObject) +{ + nlohmann::json jsonData; + if (!context->isOnline) { + jsonData[DM_TAG_USER_PUBLICK_KEY] = context->accessee.userPublicKey; + jsonData[DM_TAG_USER_CREDENTIAL_ID] = context->accessee.userCredentialId; + } + jsonData[DM_TAG_APP_PUBLICK_KEY] = context->accessee.appPublicKey; + jsonData[DM_TAG_APP_CREDENTIAL_ID] = context->accessee.appCredentialId; + + std::string plainText = SafetyDump(jsonData); + std::string cipherText; + cryptoMgr_->EncryptMessage(plainText, cipherText); + jsonObject[DM_TAG_DATA] = cipherText; +} + +// 创建160报文 +void DmAuthMessageProcessor::CreateMessageReqCredAuthStart(std::shared_ptr context, + nlohmann::json &jsonObject) +{ + std::string onTransmitData; + if (context->GetFromContextExtra(DM_TAG_ON_TRANSMIT_DATA, onTransmitData) != DM_OK) { + LOGE("DmAuthMessageProcessor::CreateMessageReqCredAuthStart failed, get onTransmitData from extra failed."); + return; + } + + nlohmann::json jsonData; + jsonData[DM_TAG_ON_TRANSMIT_DATA] = onTransmitData; + if (!context->isAppCredentialVerified) { // 应用级凭据认证 + jsonData[DM_TAG_APP_CREDENTIAL_ID] = context->accesser.appCredentialId; + } else if (!context->isOnline) { // 首次用户级凭据认证 + jsonData[DM_TAG_USER_CREDENTIAL_ID] = context->accesser.userCredentialId; + } + + std::string plainText = SafetyDump(jsonData); + std::string cipherText; + if (cryptoMgr_->EncryptMessage(plainText, cipherText) != DM_OK) { + LOGE("DmAuthMessageProcessor::CreateMessageReqCredAuthStart failed, encrypt data failed."); + return; + } + + jsonObject[DM_TAG_DATA] = cipherText; +} + + +int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const nlohmann::json &json, + std::shared_ptr context) { // todo + return DM_OK; } -void DmAuthMessageProcessor::ParseMessageReqUserConfirm(const nlohmann::json &json, std::shared_ptr context) +int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const nlohmann::json &json, + std::shared_ptr context) { // todo context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; } -void DmAuthMessageProcessor::ParseMessageRespUserConfirm(const nlohmann::json &json, std::shared_ptr context) +int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const nlohmann::json &json, + std::shared_ptr context) { context->authType = static_cast(json[TAG_AUTH_TYPE].get()); context->requestId = json[TAG_REQUEST_ID].get(); @@ -55,30 +262,36 @@ void DmAuthMessageProcessor::ParseMessageRespUserConfirm(const nlohmann::json &j } context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; } -void DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const nlohmann::json &json, std::shared_ptr context) +int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const nlohmann::json &json, + std::shared_ptr context) { context->transmitData = json[TAG_DATA].get(); context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; } -void DmAuthMessageProcessor::ParseMessageRespPinAuthStart(const nlohmann::json &json, std::shared_ptr context) +int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthStart(const nlohmann::json &json, + std::shared_ptr context) { context->transmitData = json[TAG_DATA].get(); context->authStateMachine->TransitionTo(std::make_shared()); - + return DM_OK; } -void DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate(const nlohmann::json &json, std::shared_ptr context) +int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate(const nlohmann::json &json, + std::shared_ptr context) { context->transmitData = json[TAG_DATA].get(); context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; } -void DmAuthMessageProcessor::CreateMessageReqUserConfirm(nlohmann::json &json, std::shared_ptr context) +void DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, nlohmann::json &json) { // todo } -void DmAuthMessageProcessor::CreateMessageRespUserConfirm(nlohmann::json &json, std::shared_ptr context) +void DmAuthMessageProcessor::CreateMessageRespUserConfirm(std::shared_ptr context, nlohmann::json &json) { json[TAG_AUTH_TYPE] = context->authType; json[TAG_REQUEST_ID] = context->requestId; @@ -87,22 +300,24 @@ void DmAuthMessageProcessor::CreateMessageRespUserConfirm(nlohmann::json &json, } } -void DmAuthMessageProcessor::CreateMessageReqPinAuthStart(nlohmann::json &json, std::shared_ptr context) +void DmAuthMessageProcessor::CreateMessageReqPinAuthStart(std::shared_ptr context, nlohmann::json &json) { json[TAG_DATA] = context->transmitData; } -void DmAuthMessageProcessor::CreateMessageRespPinAuthStart(nlohmann::json &json, std::shared_ptr context) +void DmAuthMessageProcessor::CreateMessageRespPinAuthStart(std::shared_ptr context, nlohmann::json &json) { json[TAG_DATA] = context->transmitData; } -void DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate(nlohmann::json &json, std::shared_ptr context) +void DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate(std::shared_ptr context, + nlohmann::json &json) { json[TAG_DATA] = context->transmitData; } -void DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate(nlohmann::json &json, std::shared_ptr context) +void DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate(std::shared_ptr context, + nlohmann::json &json) { json[TAG_DATA] = context->transmitData; } diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 99018df91..b9d6a5e25 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -88,9 +88,132 @@ int32_t HiChainAuthConnector::ProcessAuthData(int64_t requestId, std::string aut return DM_OK; } +// 处理凭据认证报文 +// authReqId 认证Id +// data 对端报文内容 int32_t HiChainAuthConnector::ProcessCredData(int64_t authReqId, const std::string &data) { - // todo + LOGI("HiChainAuthConnector::ProcessCredData start."); + const CredAuthManager *credAuthManager = GetCredAuthInstance(); + int32_t ret = credAuthManager->processCredData(authReqId, reinterpret_cast(data.c_str()), + data.length(), &deviceAuthCallback_); + if (ret != HC_SUCCESS) { + LOGE("Hichain processData failed ret %{public}d.", ret); + return ERR_DM_FAILED; + } + return DM_OK; +} + +// 生成凭据,返回凭据Id +// osAccountId 本段UserId +// authParams json格式字符串,key-value根据上下文确定 +// credId 返回的凭据Id +int32_t HiChainAuthConnector::AddCredential(int32_t osAccountId, const std::string &authParams, std::string &credId) +{ + LOGI("HiChainAuthConnector::AddCredential start."); + char *returnData = NULL; + const CredManager *credManager = GetCredMgrInstance(); + int32_t ret = credManager->addCredential(osAccountId, authParams.c_str(), &returnData); + if (ret != HC_SUCCESS) { + LOGE("Hichain addCredential failed ret %{public}d.", ret); + credManager->destroyInfo(&returnData); + return ERR_DM_FAILED; + } + credId = static_cast(returnData); + credManager->destroyInfo(&returnData); + return DM_OK; +} + +// 根据凭据Id导出公钥 +// osAccountId 本段UserId +// credId 凭据Id +// publicKey 公钥 +int32_t HiChainAuthConnector::ExportCredential(int32_t osAccountId, const std::string &credId, std::string &publicKey) +{ + LOGI("HiChainAuthConnector::ExportCredential start."); + char *returnData = NULL; + const CredManager *credManager = GetCredMgrInstance(); + int32_t ret = credManager->exportCredential(osAccountId, credId.c_str(), &returnData); + if (ret != HC_SUCCESS) { + LOGE("Hichain exportCredential failed ret %{public}d.", ret); + credManager->destroyInfo(&returnData); + return ERR_DM_FAILED; + } + publicKey = static_cast(returnData); + credManager->destroyInfo(&returnData); + return DM_OK; +} + +// 凭据协商 +// osAccountId 本段UserId +// selfCredId 本段凭据Id +// authParams 协商参数 +// credId 返回的凭据Id +int32_t HiChainAuthConnector::AgreeCredential(int32_t osAccountId, const std::string selfCredId, + const std::string &authParams, std::string &credId) +{ + LOGI("HiChainAuthConnector::AgreeCredential start."); + // TODO:IS黄区代码中没有这个接口 + // char *returnData = NULL; + // const CredManager *credManager = GetCredMgrInstance(); + // int32_t ret = credManager->agreeCredential(osAccountId, selfCredId.c_str(), authParams.c_str(), &returnData); + // if (ret != HC_SUCCESS) { + // LOGE("Hichain agreeCredential failed ret %{public}d.", ret); + // credManager->destroyInfo(&returnData); + // return ERR_DM_FAILED; + // } + // credId = static_cast(returnData); + // credManager->destroyInfo(&returnData); + return DM_OK; +} + +// 删除凭据 +// osAccountId 本段用户Id +// credId 待删除的凭据Id +int32_t HiChainAuthConnector::DeleteCredential(int32_t osAccountId, const std::string &credId) +{ + LOGI("HiChainAuthConnector::DeleteCredential start."); + const CredManager *credManager = GetCredMgrInstance(); + int32_t ret = credManager->deleteCredential(osAccountId, credId.c_str()); + if (ret != HC_SUCCESS) { + LOGE("Hichain deleteCredential failed ret %{public}d.", ret); + return ERR_DM_FAILED; + } + return DM_OK; +} + +// 凭据认证 +// osAccountId 系统用户参数 +// authReqId 认证请求id +// credId 对端凭据Id +// pinCode pin码认证(点对点临时凭据不能为空) +int32_t HiChainAuthConnector::AuthCredential(int32_t osAccountId, int64_t authReqId, const std::string &credId, + const std::string &pinCode) +{ + LOGI("HiChainAuthConnector::AuthCredential start."); + if (credId.empty() && pinCode.empty()) { + LOGE("HiChainAuthConnector::AuthCredential failed, credId and pinCode is empty."); + return ERR_DM_FAILED; + } + + // 创建authParams的json格式字符串 + nlohmann::json jsonAuthParam; + if (!credId.empty()) { + jsonAuthParam["credId"] = credId; + } + if (!pinCode.empty()) { + jsonAuthParam["pinCode"] = pinCode; + } + std::string authParams = SafetyDump(jsonAuthParam); + + // 凭据认证 + const CredAuthManager *credAuthManager = GetCredAuthInstance(); + int32_t ret = credAuthManager->authCredential(osAccountId, authReqId, authParams.c_str(), &deviceAuthCallback_); + if (ret != HC_SUCCESS) { + LOGE("HiChainAuthConnector::AuthCredential failed ret %{public}d.", ret); + return ERR_DM_FAILED; + } + return DM_OK; } -- Gitee From 9ec2ea23931d8ab70aaefaa68fa07b262f3b13bc Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Thu, 27 Feb 2025 22:02:53 +0800 Subject: [PATCH 009/382] =?UTF-8?q?feat:=20=E5=AE=8C=E6=88=9080/90?= =?UTF-8?q?=E6=8A=A5=E6=96=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/auth_manager.h | 54 ++ .../authentication_v2/dm_auth_context.h | 42 +- .../dm_auth_message_processor.h | 73 ++- .../include/authentication_v2/dm_auth_state.h | 106 ++-- .../authentication_v2/dm_auth_state_machine.h | 1 - .../hichain/hichain_auth_connector.h | 1 + .../src/authentication_v2/auth_manager.cpp | 523 +++++++++++++++++- .../auth_stages/auth_negotiate.cpp | 329 +++++++++++ .../dm_auth_message_processor.cpp | 57 ++ .../src/authentication_v2/dm_auth_state.cpp | 35 ++ .../hichain/hichain_auth_connector.cpp | 48 ++ 11 files changed, 1187 insertions(+), 82 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index d3ae5b279..5e60e6137 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -25,6 +25,39 @@ namespace OHOS { namespace DistributedHardware { struct DmAuthContext; + +const int32_t DM_AUTH_TYPE_MAX = 5; +const int32_t DM_AUTH_TYPE_MIN = 0; +const int32_t MIN_PIN_TOKEN = 10000000; +const int32_t MAX_PIN_TOKEN = 90000000; +const int32_t NEGOTIATE_TIMEOUT = 10; +const int32_t WAIT_REQUEST_TIMEOUT = 10; +const int32_t HML_SESSION_TIMEOUT = 10; +const int32_t AUTHENTICATE_TIMEOUT = 120; +constexpr const char* DM_VERSION_5_1_0 = "5.1.0"; +// TODO: 黄蓝区同步,部分代码冲突,冲突时删除此处 +constexpr const char* PARAM_KEY_HML_ENABLE_160M = "hmlEnable160M"; +constexpr const char* PARAM_KEY_HML_ACTIONID = "hmlActionId"; +constexpr const char* PARAM_KEY_CONN_SESSIONTYPE = "connSessionType"; + +constexpr const char* BUNDLE_NAME_KEY = "bundleName"; + +// 取自security_device_auth中的identity_operation.h,该头文件为内部头文件,不能直接引用 +// 若冲突删除此处 +enum { + ACCOUNT_RELATED = 1, + ACCOUNT_UNRELATED, + ACCOUNT_ACROSS +}; + +// 取自security_device_auth中的identity_operation.h,该头文件为内部头文件,不能直接引用 +// 若冲突删除此处 +enum { + SCOPE_DEVICE = 1, + SCOPE_USER, + SCOPE_APP, +}; + class AuthManager : public ISoftbusSessionCallback, public IDmDeviceAuthCallback, public std::enable_shared_from_this { @@ -35,9 +68,30 @@ public: // 各类事件触发的函数实现(虚函数) int32_t GetPinCode(int32_t &code) override; + + int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam); protected: // 上下文(需在该层级进行创建) std::shared_ptr context_; +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(nlohmann::json jsonObject); + void ParseJsonObject(nlohmann::json jsonObject); + void GetAuthParam(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra); + std::string GetBundleName(nlohmann::json &jsonObject); + int32_t GetBindLevel(int32_t bindLevel); + void SetAuthType(int32_t authType); + bool IsAuthTypeSupported(const int32_t &authType); + bool IsAuthCodeReady(const std::string &pkgName); + int32_t CheckAuthParamVaild(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra); + void InitAuthState(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra); + int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra); }; class AuthSrcManager : public AuthManager { diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 950c5b357..f725d0bbe 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -19,15 +19,16 @@ #include #include -#include "dm_timer.h" +#include "nlohmann/json.hpp" #include "auth_ui_state_manager.h" #include "hichain_auth_connector.h" #include "hichain_connector.h" -#include "dm_auth_message_processor.h" #include "softbus_connector.h" #include "softbus_session.h" -#include "nlohmann/json.hpp" +#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" @@ -38,13 +39,15 @@ namespace OHOS { namespace DistributedHardware { class DmAuthStateMachine; +class DmAuthMessageProcessor; // PIN码认证类型 -enum DmAuthType { +typedef enum { AUTH_TYPE_PIN_SHOW = 0, // 弹PIN码 AUTH_TYPE_PIN_ULTRASONIC, // 超声PIN码 AUTH_TYPE_PIN_IMPORT, // 导入PIN码 -}; + AUTH_TYPE_IMPORT_AUTH_CODE, // 导入认证码 +} DmAuthType; enum DmAuthDirection { DM_AUTH_SOURCE = 0, @@ -94,9 +97,16 @@ struct DmAccess { std::string deviceName; int32_t deviceType; // PC、mobile、手表、大屏等类型,为业务透传的数据,无需自定义 std::string deviceId; // A->B, 无论是A端还是B端,Accesser对象都存A端的deviceId,Accessee对象都存B端的deviceId + std::string deviceIdHash; + std::string addr; // Q: 旧协议有用到addr,新设计没有,需要确认 int32_t userId; + std::string userIdHash; std::string accountId; + std::string accountIdHash; uint64_t tokenId; + std::string tokenIdHash; + std::string token; // Q: 旧协议有用到token,新设计没有,需要确认 + std::string networkId; std::string bundleName; // 存PacketName int64_t serviceId; // 保留字段,后续会使用 std::string accesserHapSignature; @@ -105,6 +115,9 @@ struct DmAccess { std::string appCredentialId; // 应用级凭据Id std::string userPublicKey; // 用户级公钥 std::string appPublicKey; // 应用级公钥 + std::vector bindType; // 绑定类型,如DM_IDENTICAL_ACCOUNT、DM_ACROSS_ACCOUNT、DM_POINT_TO_POINT + std::string publicKey; // T公钥长度 + int32_t credentialId; // 应用凭据ID int32_t status; // 表示服务为前台还是后台,业务透传,只保存 int32_t sessionKeyId; // 作为秘钥派送的材料,在总线中取出sk int64_t skTimeStamp; // 老化,时间为2天 @@ -128,13 +141,17 @@ struct DmAuthContext { int32_t connDelayCloseTime; // 链路延迟释放时间, 授权结束后不自动断链(有业务需要使用)保留字段 int32_t reason; // 本端失败的原因 int32_t reply; // 对端回复的结果 引用common/include/dm_constants.h,有新的错误码可新增 + int32_t hmlActionId = 0; bool normalFinishAuth; // 标识认证过程是否正常结束 bool authenticating; // 标识正在认证中 + bool hmlEnable160M = false; std::string pkgName; // 业务传入的标识,业务自定义,有被仿冒的风险 + std::string pkgLabel; std::string importCodeBundleName; // 导入pin码的包名,从系统中读取,与acceserBundleName一致 std::string appThumbnail; // 应用图标 std::string appOperation; // 授权弹框中显示本次绑定用于什么操作 std::string customData; // 业务自定义字段,详细提示用户本次绑定的操作 + std::string connSessionType; std::string extraInfo; // 可扩展字段,kv结构 DmAuthDirection direction; // 标识认证方向 ProcessInfo processInfo; // 进程信息 @@ -145,14 +162,23 @@ struct DmAuthContext { std::multimap proxy; // 前面是accesser,后面是accessee std::shared_ptr authStateMachine; // 状态机 - bool fallBackToInputPin{false}; // 是否已经回退到输入PIN码 - std::string transmitData; // 保存 onTrasmit返回数据 - std::shared_ptr timer; std::shared_ptr authUiStateMgr; std::shared_ptr hiChainAuthConnector; // HiChain交互接口 std::shared_ptr authMessageProcessor; // 报文处理接口 std::shared_ptr softbusConnector; // 软总线接口 + std::shared_ptr listener; + std::shared_ptr authPtr; + std::shared_ptr timer; + std::string transmitData; // 保存 onTrasmit返回数据 + std::string importPkgName = ""; + std::string importAuthCode = ""; + std::map> authenticationMap; + PeerTargetId peerTargetId; + bool fallBackToInputPin{false}; // 是否已经回退到输入PIN码 + bool isAuthenticateDevice = false; + // 获取超时时间 + int32_t GetTaskTimeout(const char* taskName, int32_t taskTimeOut); // 获取设备ID std::string GetDeviceId(DmAuthSide side); // 获取凭据ID diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index c1d0b0ac9..a8fb4213d 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -24,6 +24,45 @@ namespace OHOS { namespace DistributedHardware { struct DmAuthContext; + +constexpr const char *DM_TAG_MSG_TYPE = "messageType"; // 报文类型 +constexpr const char *DM_TAG_DATA = "data"; // 报文数据 +constexpr const char *DM_TAG_USER_PUBLICK_KEY = "userPublicKey"; // 用户级公钥 userPublicKey +constexpr const char *DM_TAG_APP_PUBLICK_KEY = "appPublicKey"; // 应用级公钥 appPublicKey +constexpr const char *DM_TAG_USER_CREDENTIAL_ID = "userCredentialId"; // 用户级凭据Id +constexpr const char *DM_TAG_APP_CREDENTIAL_ID = "appCredentialId"; // 应用级凭据Id +constexpr const char *DM_TAG_ON_TRANSMIT_DATA = "onTransmitData"; // onTransmitData接口返回信息 + +// is接口入参 json格式字符串中的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 = "credentialOwner"; +constexpr const char *DM_AUTH_CREDENTIAL_OWNER = "DM"; // 凭据拥有者 + +constexpr const char* APP_OPERATION_KEY = "appOperation"; +constexpr const char* APP_THUMBNAIL = "appThumbnail"; +constexpr const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; + +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_PKG_NAME = "pkgName"; + // 报文类型 enum DmMessageType { // 终止/异常报文 @@ -49,29 +88,6 @@ enum DmMessageType { MSG_TYPE_AUTH_FINISH = 200, }; -constexpr const char *DM_TAG_MSG_TYPE = "messageType"; // 报文类型 -constexpr const char *DM_TAG_DATA = "data"; // 报文数据 -constexpr const char *DM_TAG_USER_PUBLICK_KEY = "userPublicKey"; // 用户级公钥 userPublicKey -constexpr const char *DM_TAG_APP_PUBLICK_KEY = "appPublicKey"; // 应用级公钥 appPublicKey -constexpr const char *DM_TAG_USER_CREDENTIAL_ID = "userCredentialId"; // 用户级凭据Id -constexpr const char *DM_TAG_APP_CREDENTIAL_ID = "appCredentialId"; // 应用级凭据Id -constexpr const char *DM_TAG_ON_TRANSMIT_DATA = "onTransmitData"; // onTransmitData接口返回信息 - -// is接口入参 json格式字符串中的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 = "credentialOwner"; -constexpr const char *DM_AUTH_CREDENTIAL_OWNER = "DM"; // 凭据拥有者 - class DmAuthMessageProcessor { public: // 解析报文,返回值为错误码,实际解析出来的信息保存到context中 @@ -84,6 +100,8 @@ public: int32_t SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyLen); private: // 内部各类报文的实现 + // 解析 80报文 + void ParseNegotiateMessage(nlohmann::json &jsonObject, std::shared_ptr context); // 解析 90 报文 int32_t ParseMessageRespAclNegotiate(const nlohmann::json &json, std::shared_ptr context); // 解析 100 报文 @@ -96,12 +114,15 @@ private: int32_t ParseMessageRespPinAuthStart(const nlohmann::json &json, std::shared_ptr context); // 解析 121 报文 int32_t ParseMessageReqPinAuthNegotiate(const nlohmann::json &json, std::shared_ptr context); - // 解析131报文onTransmitData返回的数据,存在contextd->extra中 + // 解析 131报文onTransmitData返回的数据,存在contextd->extra中 int32_t ParseMessageOnTransmit(const nlohmann::json &jsonObject, std::shared_ptr context); - // 解析140报文信息MSG_TYPE_REQ_CREDENTIAL_EXCHANGE,SINK端存放对方公钥 + // 解析 140报文信息MSG_TYPE_REQ_CREDENTIAL_EXCHANGE,SINK端存放对方公钥 int32_t ParseMessageReqCredExchange(const nlohmann::json &jsonObject, std::shared_ptr context); - // 解析150报文信息MSG_TYPE_RESP_CREDENTIAL_EXCHANGE,存放对方公钥,和协商凭据Id + // 解析 150报文信息MSG_TYPE_RESP_CREDENTIAL_EXCHANGE,存放对方公钥,和协商凭据Id int32_t ParseMessageRspCredExchange(const nlohmann::json &jsonObject, std::shared_ptr context); + + // 创建 80报文 + void CreateNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject); // 创建 100 报文 void CreateMessageReqUserConfirm(std::shared_ptr context, nlohmann::json &json); // 创建 110 报文 diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 0dcfc65b6..cb603762e 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -18,6 +18,9 @@ #include +#include "access_control_profile.h" + +#include "dm_auth_state.h" #include "dm_auth_context.h" namespace OHOS { @@ -56,12 +59,53 @@ enum class DmAuthStateType { AUTH_SINK_FINISH_STATE, // 收到200结束报文 }; +// 凭据添加方式 +enum DmAuthCredentialAddMethod { + DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE = 1, // 生成 + DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT, // 导入 +}; + +// 凭据主体 +enum DmAuthCredentialSubject { + DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY = 1, // 主控 + DM_AUTH_CREDENTIAL_SUBJECT_SUPPLEMENT, // 配件 +}; + +// 凭据与账号关联 +enum DmAuthCredentialAccountRelation { + DM_AUTH_CREDENTIAL_ACCOUNT_RELATED = 1, // 账号相关 + DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED, // 账号无关 +}; + +// 秘钥类型 +enum DmAuthKeyFormat { + 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 { + 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 { + 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动作 static bool IsScreenLocked(); + static int32_t GetTaskTimeout(const char* taskName, int32_t taskTimeOut); static void HandleAuthenticateTimeout(std::shared_ptr context, std::string name); protected: }; @@ -138,6 +182,13 @@ public: virtual ~AuthSrcPinAuthDoneState() {}; 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 @@ -146,46 +197,6 @@ class AuthCredentialAgreeState : public DmAuthState { public: virtual ~AuthCredentialAgreeState() {}; protected: - // 凭据添加方式 - enum DmAuthCredentialAddMethod { - DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE = 1, // 生成 - DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT, // 导入 - }; - - // 凭据主体 - enum DmAuthCredentialSubject { - DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY = 1, // 主控 - DM_AUTH_CREDENTIAL_SUBJECT_SUPPLEMENT, // 配件 - }; - - // 凭据与账号关联 - enum DmAuthCredentialAccountRelation { - DM_AUTH_CREDENTIAL_ACCOUNT_RELATED = 1, // 账号相关 - DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED, // 账号无关 - }; - - // 秘钥类型 - enum DmAuthKeyFormat { - 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 { - 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 { - DM_AUTH_CREDENTIAL_PROOF_PSK = 1, // PSK - DM_AUTH_CREDENTIAL_PROOF_PKI, // PKI - }; - // 生成凭据协商状态下的authParams的json格式字符串 std::string CreateAuthParamsString(DmAuthScope authorizedScope, DmAuthCredentialAddMethod method, const std::shared_ptr &authContext); @@ -217,6 +228,21 @@ public: virtual ~AuthSrcCredentialAuthStartState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; +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 HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList); + int32_t GetCredentialType(std::shared_ptr context, nlohmann::json credInfo); + 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); }; } // namespace DistributedHardware diff --git a/services/implementation/include/authentication_v2/dm_auth_state_machine.h b/services/implementation/include/authentication_v2/dm_auth_state_machine.h index d6d029ad2..e793c4ac8 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state_machine.h +++ b/services/implementation/include/authentication_v2/dm_auth_state_machine.h @@ -52,7 +52,6 @@ enum DmEventType { class DmAuthStateMachine { public: - DmAuthStateMachine() = delete; DmAuthStateMachine(std::shared_ptr context); ~DmAuthStateMachine(); diff --git a/services/implementation/include/dependency/hichain/hichain_auth_connector.h b/services/implementation/include/dependency/hichain/hichain_auth_connector.h index f03781e12..e2291f10e 100644 --- a/services/implementation/include/dependency/hichain/hichain_auth_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_auth_connector.h @@ -54,6 +54,7 @@ public: int32_t ProcessAuthData(int64_t requestId, std::string authData, int32_t osAccountId); int32_t GenerateCredential(std::string &localUdid, int32_t osAccountId, std::string &publicKey); bool QueryCredential(std::string &localUdid, int32_t osAccountId); + int32_t QueryCredentialInfo(int32_t userId, nlohmann::json queryParams, nlohmann::json &resultJson); int32_t ImportCredential(int32_t osAccountId, std::string deviceId, std::string publicKey); int32_t DeleteCredential(const std::string &deviceId, int32_t userId); int32_t RegisterHiChainAuthCallback(std::shared_ptr callback); diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 70c197cd2..abfd3517b 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -15,20 +15,147 @@ #include -#include "dm_auth_message_processor.h" -#include "dm_auth_state_machine.h" -#include "auth_manager.h" -#include "dm_auth_context.h" +#include "app_manager.h" +#include "softbus_common.h" +#include "system_ability_definition.h" +#include "iservice_registry.h" +#include "parameter.h" +#include "deviceprofile_connector.h" +#include "multiple_user_connector.h" + +#include "dm_constants.h" +#include "dm_crypto.h" +#include "dm_random.h" #include "dm_log.h" +#include "dm_timer.h" +#include "dm_radar_helper.h" +#include "dm_device_info.h" +#include "dm_anonymous.h" #include "dm_auth_state_machine.h" +#include "dm_auth_context.h" +#include "dm_auth_message_processor.h" +#include "auth_manager.h" #undef LOG_TAG #define LOG_TAG "DHDM_V2" namespace OHOS { namespace DistributedHardware { +namespace { const int32_t MAX_AUTH_FAIL_TIMES = 3; +// TODO: 黄蓝区未同步,无CONN_SESSION_TYPE_HML符号 +bool IsHmlSessionType(std::string sessionType) +{ + return false; + // return sessionType == CONN_SESSION_TYPE_HML; +} + +int32_t GetCloseSessionDelaySeconds(std::string &delaySecondsStr) +{ + if (!IsNumberString(delaySecondsStr)) { + LOGE("Invalid parameter, param is not number."); + return 0; + } + const int32_t CLOSE_SESSION_DELAY_SECONDS_MAX = 10; + int32_t delaySeconds = std::atoi(delaySecondsStr.c_str()); + if (delaySeconds < 0 || delaySeconds > CLOSE_SESSION_DELAY_SECONDS_MAX) { + LOGE("Invalid parameter, param out of range."); + return 0; + } + return delaySeconds; +} + +std::string GetBundleLable(const std::string &bundleName) +{ + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + LOGE("Get ability manager failed"); + return bundleName; + } + + sptr object = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (object == nullptr) { + LOGE("object is NULL."); + return bundleName; + } + + sptr bms = iface_cast(object); + if (bms == nullptr) { + LOGE("bundle manager service is NULL."); + return bundleName; + } + + auto bundleResourceProxy = bms->GetBundleResourceProxy(); + if (bundleResourceProxy == nullptr) { + LOGE("GetBundleResourceProxy fail"); + return bundleName; + } + AppExecFwk::BundleResourceInfo resourceInfo; + auto result = bundleResourceProxy->GetBundleResourceInfo(bundleName, + static_cast(OHOS::AppExecFwk::ResourceFlag::GET_RESOURCE_INFO_ALL), resourceInfo); + if (result != ERR_OK) { + LOGE("GetBundleResourceInfo failed"); + return bundleName; + } + LOGI("bundle resource label is %{public}s ", (resourceInfo.label).c_str()); + return resourceInfo.label; +} + +bool IsAllowDeviceBind(void) +{ + if (AppManager::GetInstance().IsSystemSA()) { + return true; + } + return false; +} + +int32_t CheckAuthParamVaildExtra(const std::string &extra) +{ + nlohmann::json jsonObject = nlohmann::json::parse(extra, nullptr, false); + if (jsonObject.is_discarded() || jsonObject.find(TAG_BIND_LEVEL) == jsonObject.end() || + !IsInt32(jsonObject, TAG_BIND_LEVEL)) { + return DM_OK; + } + int32_t bindLevel = jsonObject[TAG_BIND_LEVEL].get(); + if (static_cast(bindLevel) > APP || bindLevel < INVALID_TYPE) { + LOGE("bindlevel error %{public}d.", bindLevel); + return ERR_DM_INPUT_PARA_INVALID; + } + + if (static_cast(bindLevel) == DEVICE && !IsAllowDeviceBind()) { + LOGE("not allowd device level bind bindlevel: %{public}d.", bindLevel); + return ERR_DM_INPUT_PARA_INVALID; + } + return DM_OK; +} + +std::string ParseExtraFromMap(const std::map &bindParam) +{ + auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA); + if (iter != bindParam.end()) { + return iter->second; + } + return ConvertMapToJsonString(bindParam); +} + +} // namespace + +AuthManager::AuthManager(std::shared_ptr softbusConnector, + std::shared_ptr hiChainConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector) + : context_->softbusConnector(softbusConnector), context_->hiChainAuthConnector(hiChainConnector), + context_->listener(listener), context_->hiChainAuthConnector(hiChainAuthConnector) +{ + LOGI("DmAuthManager constructor"); + context_->authUiStateMgr = std::make_shared(context_->listener); + context->authenticationMap[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; + context->authenticationMap[AUTH_TYPE_CRE] = nullptr; + context->accesser.dmVersion = DM_VERSION_5_1_0; + context->accessee.dmVersion = DM_VERSION_5_1_0; +} + void AuthManager::SetAuthContext(std::shared_ptr context) { this->context_ = context; @@ -39,8 +166,29 @@ std::shared_ptr AuthManager::GetAuthContext() return this->context_; } -// 各类事件触发的函数实现(子类继承实现) -// AuthSrcManager +int32_t AuthManager::ParseAuthType(const std::map &bindParam, int32_t &authType) +{ + auto iter = bindParam.find(PARAM_KEY_AUTH_TYPE); + if (iter == bindParam.end()) { + LOGE("AuthManager::ParseAuthType bind param key: %{public}s not exist.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + std::string authTypeStr = iter->second; + if (authTypeStr.empty()) { + LOGE("AuthManager::ParseAuthType bind param %{public}s is empty.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + if (authTypeStr.length() > 1) { + LOGE("AuthManager::ParseAuthType bind param %{public}s length is unsupported.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + if (!isdigit(authTypeStr[0])) { + LOGE("AuthManager::ParseAuthType bind param %{public}s fromat is unsupported.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + authType = std::atoi(authTypeStr.c_str()); + return DM_OK; +} // 保存秘钥 void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) @@ -63,7 +211,368 @@ void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sess context_->authStateMachine->NotifyEventFinish(ON_SESSION_KEY_RETURNED); } -// AuthSinkManager +int32_t AuthManager::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType) +{ + int32_t index = 0; + std::shared_ptr deviceInfo = std::make_shared(); + ConnectionAddr addr; + if (!targetId.wifiIp.empty() && targetId.wifiIp.length() <= IP_STR_MAX_LEN) { + LOGI("AuthManager::ParseConnectAddr parse wifiIp: %{public}s.", GetAnonyString(targetId.wifiIp).c_str()); + if (!addrType.empty()) { + addr.type = static_cast(std::atoi(addrType.c_str())); + } else { + addr.type = ConnectionAddrType::CONNECTION_ADDR_WLAN; + } + memcpy_s(addr.info.ip.ip, IP_STR_MAX_LEN, targetId.wifiIp.c_str(), targetId.wifiIp.length()); + addr.info.ip.port = targetId.wifiPort; + deviceInfo->addr[index] = addr; + deviceId = targetId.wifiIp; + index++; + } else if (!targetId.brMac.empty() && targetId.brMac.length() <= BT_MAC_LEN) { + LOGI("AuthManager::ParseConnectAddr parse brMac: %{public}s.", GetAnonyString(targetId.brMac).c_str()); + addr.type = ConnectionAddrType::CONNECTION_ADDR_BR; + memcpy_s(addr.info.br.brMac, BT_MAC_LEN, targetId.brMac.c_str(), targetId.brMac.length()); + deviceInfo->addr[index] = addr; + deviceId = targetId.brMac; + index++; + } else if (!targetId.bleMac.empty() && targetId.bleMac.length() <= BT_MAC_LEN) { + LOGI("AuthManager::ParseConnectAddr parse bleMac: %{public}s.", GetAnonyString(targetId.bleMac).c_str()); + addr.type = ConnectionAddrType::CONNECTION_ADDR_BLE; + memcpy_s(addr.info.ble.bleMac, BT_MAC_LEN, targetId.bleMac.c_str(), targetId.bleMac.length()); + if (!targetId.deviceId.empty()) { + Crypto::ConvertHexStringToBytes(addr.info.ble.udidHash, UDID_HASH_LEN, + targetId.deviceId.c_str(), targetId.deviceId.length()); + } + deviceInfo->addr[index] = addr; + deviceId = targetId.bleMac; + index++; + } else { + LOGE("AuthManager::ParseConnectAddr failed, not addr."); + return ERR_DM_INPUT_PARA_INVALID; + } + + deviceInfo->addrNum = static_cast(index); + if (context_->softbusConnector->AddMemberToDiscoverMap(deviceId, deviceInfo) != DM_OK) { + LOGE("AuthManager::ParseConnectAddr failed, AddMemberToDiscoverMap failed."); + return ERR_DM_INPUT_PARA_INVALID; + } + deviceInfo = nullptr; + return DM_OK; +} + +void AuthManager::SetAuthType(int32_t authType) +{ + context_->authType = (DmAuthType)authType; +} + +bool AuthManager::IsAuthTypeSupported(const int32_t &authType) +{ + if (context_->authenticationMap.find(authType) == context_->authenticationMap.end()) { + LOGE("IsAuthTypeSupported failed, authType is not supported."); + return false; + } + return true; +} + +bool AuthManager::IsAuthCodeReady(const std::string &pkgName) +{ + if (context_->importAuthCode.empty() || context_->importPkgName.empty()) { + LOGE("AuthManager::IsAuthCodeReady, auth code not ready."); + return false; + } + if (pkgName != context_->importPkgName) { + LOGE("IsAuthCodeReady failed, pkgName not supported."); + return false; + } + return true; +} + +int32_t AuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("AuthManager::CheckAuthParamVaild start."); + if (authType < DM_AUTH_TYPE_MIN || authType > DM_AUTH_TYPE_MAX) { + LOGE("CheckAuthParamVaild failed, authType is illegal."); + return ERR_DM_AUTH_FAILED; + } + if (pkgName.empty() || deviceId.empty()) { + LOGE("AuthManager::CheckAuthParamVaild failed, pkgName is %{public}s, deviceId is %{public}s, extra is" + "%{public}s.", pkgName.c_str(), GetAnonyString(deviceId).c_str(), extra.c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + if (context_->listener == nullptr || context_->authUiStateMgr == nullptr) { + LOGE("AuthManager::CheckAuthParamVaild listener or authUiStateMgr is nullptr."); + return ERR_DM_INPUT_PARA_INVALID; + } + + if (!IsAuthTypeSupported(authType)) { + LOGE("AuthManager::CheckAuthParamVaild authType %{public}d not support.", authType); + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", STATUS_DM_AUTH_DEFAULT, + ERR_DM_UNSUPPORTED_AUTH_TYPE); + context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, ""); + return ERR_DM_UNSUPPORTED_AUTH_TYPE; + } + + if (!context_->softbusConnector->HaveDeviceInMap(deviceId)) { + LOGE("CheckAuthParamVaild failed, the discoveryDeviceInfoMap_ not have this device."); + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", + STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); + context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); + return ERR_DM_INPUT_PARA_INVALID; + } + + if ((authType == AUTH_TYPE_IMPORT_AUTH_CODE) && (!IsAuthCodeReady(pkgName))) { + LOGE("Auth code not exist."); + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", + STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); + context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); + return ERR_DM_INPUT_PARA_INVALID; + } + return DM_OK; +} + +void AuthManager::ParseHmlInfoInJsonObject(nlohmann::json jsonObject) +{ + if (IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE)) { + context_->connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].get(); + LOGI("connSessionType %{public}s", context_->connSessionType.c_str()); + } + if (!IsHmlSessionType(context_->connSessionType)) { + return; + } + context_->connDelayCloseTime = HML_SESSION_TIMEOUT; + if (IsBool(jsonObject, PARAM_KEY_HML_ENABLE_160M)) { + context_->hmlEnable160M = jsonObject[PARAM_KEY_HML_ENABLE_160M].get(); + LOGI("hmlEnable160M %{public}d", context_->hmlEnable160M); + } + if (IsInt32(jsonObject, PARAM_KEY_HML_ACTIONID)) { + context_->hmlActionId = jsonObject[PARAM_KEY_HML_ACTIONID].get(); + if (context_->hmlActionId <= 0) { + context_->hmlActionId = 0; + } + LOGI("hmlActionId %{public}d", context_->hmlActionId); + } + + return; +} + +std::string AuthManager::GetBundleName(nlohmann::json &jsonObject) +{ + if (!jsonObject.is_discarded() && IsString(jsonObject, BUNDLE_NAME_KEY)) { + return jsonObject[BUNDLE_NAME_KEY].get(); + } + bool isSystemSA = false; + std::string bundleName; + AppManager::GetInstance().GetCallerName(isSystemSA, bundleName); + return bundleName; +} + +void AuthManager::ParseJsonObject(nlohmann::json jsonObject) +{ + if (jsonObject.is_discarded()) { + return; + } + + // 由于旧协议中没怎么用,新协议的设计也没有该字段 + // 故废弃了targetPkgName + + // 填充context_ + if (IsString(jsonObject, APP_OPERATION_KEY)) { + context_->appOperation = jsonObject[APP_OPERATION_KEY].get(); + } + if (IsString(jsonObject, CUSTOM_DESCRIPTION_KEY)) { + context_->customData = jsonObject[CUSTOM_DESCRIPTION_KEY].get(); + } + if (IsString(jsonObject, APP_THUMBNAIL)) { + context_->appThumbnail = jsonObject[APP_THUMBNAIL].get(); + } + context_->connDelayCloseTime = 0; + if (IsString(jsonObject, PARAM_CLOSE_SESSION_DELAY_SECONDS)) { + std::string delaySecondsStr = jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].get(); + context_->connDelayCloseTime = GetCloseSessionDelaySeconds(delaySecondsStr); + } + + // 填充context_->accesser + if (IsInt32(jsonObject, TAG_BIND_LEVEL)) { + context_->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].get(); + } + context_->accesser.bundleName = GetBundleName(jsonObject); + + // 填充context_accessee + if (IsString(jsonObject, TAG_PEER_BUNDLE_NAME)) { + context_->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].get(); + if (context_->accessee.bundleName == "") { + context_->accessee.bundleName = context_->pkgName; + } + LOGI("ParseJsonObject accessee bundleName = %{public}s", context_->accessee.bundleName.c_str()); + } else { + context_->accessee.bundleName = context_->pkgName; + } + + ParseHmlInfoInJsonObject(jsonObject); + return; +} + +int32_t AuthManager::GetBindLevel(int32_t bindLevel) +{ +#ifdef DEVICE_MANAGER_COMMON_FLAG + LOGI("device_manager_common is true!"); + std::string processName = ""; + int32_t ret = AppManager::GetInstance().GetCallerProcessName(processName); + LOGI("GetBindLevel processName = %{public}s", GetAnonyString(processName).c_str()); + if (ret == DM_OK && CheckProcessNameInWhiteList(processName)) { + return DEVICE; + } +#endif + if (IsAllowDeviceBind()) { + if (static_cast(bindLevel) == INVALIED_TYPE || static_cast(bindLevel) > APP || + static_cast(bindLevel) < DEVICE) { + return DEVICE; + } + return bindLevel; + } + if (static_cast(bindLevel) == INVALIED_TYPE || (static_cast(bindLevel) != APP && + static_cast(bindLevel) != SERVICE)) { + return APP; + } + return bindLevel; +} + +void AuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("Get auth param."); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = static_cast(localDeviceId); + context_->pkgName = pkgName; + context_->pkgLabel = GetBundleLable(pkgName); + context_->authType = (DmAuthType)authType; + context_->accesser.deviceName = context_->softbusConnector->GetLocalDeviceName(); + context_->accesser.deviceType = context_->softbusConnector->GetLocalDeviceTypeId(); + context_->accesser.deviceId = localUdid; + context_->accesser.dmVersion = DM_VERSION_5_1_0; + uint32_t tokenId = 0 ; + MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, context_->accesser.userId); + context_->accesser.tokenId = static_cast(tokenId); + context_->accesser.accountId = MultipleUserConnector::GetOhosAccountIdByUserId(context_->accesser.userId); + context_->accesser.isOnline = false; + context_->accesser.isAuthed = !context_->accesser.bindType.empty(); + context_->accesser.bindLevel = INVALIED_TYPE; + + context_->accessee.deviceId = deviceId; + context_->accessee.addr = deviceId; + nlohmann::json jsonObject = nlohmann::json::parse(extra, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("extra string not a json type."); + return; + } + ParseJsonObject(jsonObject); + + context_->accesser.token = std::to_string(GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN)); + context_->accesser.bindLevel = this->GetBindLevel(context_->accesser.bindLevel); +} + +void AuthManager::InitAuthState(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + auto iter = context_->authenticationMap.find(authType); + if (iter != context_->authenticationMap.end()) { + context_->authPtr = iter->second; + } + + if (authType > AUTH_TYPE_IMPORT_AUTH_CODE || authType < AUTH_TYPE_PIN_SHOW) { + LOGE("AuthManager::InitAuthState invalid authType"); + return; + } + + if (context_->timer == nullptr) { + context_->timer = std::make_shared(); + } + context_->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context_, AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context_, name); + }); + context_->authMessageProcessor = std::make_shared(); + GetAuthParam(pkgName, authType, deviceId, extra); + context_->authStateMachine = std::make_shared(context_); + LOGI("AuthManager::AuthenticateDevice complete"); + + return; +} + +int32_t AuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("AuthManager::AuthenticateDevice start auth type %{public}d.", authType); + SetAuthType(authType); + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + context_->processInfo.pkgName = pkgName; + context_->processInfo.userId = userId; + int32_t ret = CheckAuthParamVaild(pkgName, authType, deviceId, extra); + if (ret != DM_OK) { + LOGE("AuthManager::AuthenticateDevice failed, param is invaild."); + return ret; + } + ret = CheckAuthParamVaildExtra(extra); + if (ret != DM_OK) { + LOGE("CheckAuthParamVaildExtra failed, param is invaild."); + return ret; + } + context_->isAuthenticateDevice = true; + // TODO: 当前已经没有AUTH_TYPE_CRE类型,待确认 + // if (authType == AUTH_TYPE_CRE) { + // LOGI("AuthManager::AuthenticateDevice for credential type, joinLNN directly."); + // context_->softbusConnector->JoinLnn(deviceId); + // context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", + // STATUS_DM_AUTH_DEFAULT, DM_OK); + // context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + // DM_OK, STATUS_DM_AUTH_DEFAULT, ""); + // return DM_OK; + // } + InitAuthState(pkgName, authType, deviceId, extra); + return DM_OK; +} + +int32_t AuthManager::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam) +{ + struct RadarInfo info = { + .funcName = "AuthenticateDevice", + .stageRes = static_cast(StageRes::STAGE_SUCC), + .bizState = static_cast(BizState::BIZ_STATE_END), + }; + if (!DmRadarHelper::GetInstance().ReportDiscoverUserRes(info)) { + LOGE("ReportDiscoverUserRes failed"); + } + if (pkgName.empty()) { + LOGE("AuthManager::BindTarget failed, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t authType = -1; + if (ParseAuthType(bindParam, authType) != DM_OK) { + LOGE("AuthManager::BindTarget failed, key: %{public}s error.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + context_->peerTargetId = targetId; + std::string deviceId = ""; + std::string addrType; + if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) { + addrType = bindParam.at(PARAM_KEY_CONN_ADDR_TYPE); + } + if (ParseConnectAddr(targetId, deviceId, addrType) == DM_OK) { + return AuthenticateDevice(pkgName, authType, deviceId, ParseExtraFromMap(bindParam)); + } else if (!targetId.deviceId.empty()) { + return AuthenticateDevice(pkgName, authType, targetId.deviceId, ParseExtraFromMap(bindParam)); + } else { + LOGE("AuthManager::BindTarget failed, targetId is error."); + return ERR_DM_INPUT_PARA_INVALID; + } +} int32_t AuthSinkManager::OnUserOperation(int32_t action, const std::string ¶ms) { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index e451732e8..df68e3cec 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -13,11 +13,340 @@ * limitations under the License. */ +#include +#include "nlohmann/json.hpp" + +#include "parameter.h" +#include "multiple_user_connector.h" +#include "app_manager.h" +#include "hap_token_info.h" +#include "deviceprofile_connector.h" +#include "device_auth.h" +#include "access_control_profile.h" +#include "accesser.h" +#include "accessee.h" + +#include "dm_crypto.h" +#include "dm_log.h" +#include "dm_timer.h" +#include "dm_constants.h" +#include "dm_anonymous.h" +#include "dm_auth_context.h" +#include "auth_manager.h" #include "dm_auth_state.h" namespace OHOS { namespace DistributedHardware { +int32_t AuthSrcNegotiateStateMachine::Action(std::shared_ptr context) +{ + LOGI("AuthSrcNegotiateStateMachine::Action sessionId %{public}d.", context->sessionId); + + // Q:为什么会让对端deviceId等于自己的deviceId? + context->accessee.deviceId = context->accesser.deviceId; + context->reply = ERR_DM_AUTH_REJECT; + // authType、deviceId已在BindTarget赋值 + // accountGroupIdHash已废弃,无组的概念 + // hostPkgName已废弃,直接取context的pkgName,已在初始化时赋值 + context->accessee.bundleName = context->accesser.bundleName; // 初始化时已赋值,这里是不是存在冲突? + // context的accesser和accessee的bundleName已经覆盖peerBundleName + // pkgLabel已赋值 + // tokenId已不在80报文中传输 + // bindLevel已在BindTarget赋值 + // bindType已在BindTarget赋值 + // isOnline已在BindTarget赋值 + // authed替换为isAuthed,已在BindTarget赋值 + // 为什么之前DmVersion传空? + context->accessee.dmVersion = ""; + // accountId不再在80报文中传输 + // userId不再在80报文中传输 + // isIdenticalAccount不再在80报文中传输 + // edition不再在80报文中传输 + // remoteDeviceName + + // 计算哈希值 + context->accesser.deviceIdHash = Crypto::Sha256(context->accesser.deviceId); + context->accesser.userIdHash = Crypto::Sha256(std::to_string(context->accesser.userId)); + context->accesser.accountIdHash = Crypto::Sha256(context->accesser.accountId); + context->accesser.tokenIdHash = Crypto::Sha256(std::to_string(context->accesser.tokenId)); + + std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_REQ_ACL_NEGOTIATE, context); + context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); + if (context->timer != nullptr) { + context->timer->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT), [this, context] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context, name); + }); + } + + return DM_OK; +} + +int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptr context) +{ + int32_t ret; + + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + context->accessee.deviceId = static_cast(localDeviceId); + + if (context->accesser.tokenIdHash.empty()) { + // 单用户:特征为accesser未传输tokenIdHash + // 适用于:FA-FA、SA-SA + // 当前无FA-FA_service、SA-SA_service、FA-device(bindTarget暂无peerType) + std::vector userVec; + + ret = MultipleUserConnector::GetForegroundUserIds(userVec); + if (ret != DM_OK) { + LOGE("RespQueryTokenId: GetForegroundUserIds failed, ret: %{public}d", ret); + return ret; + } + + context->accessee.userId = MultipleUserConnector::GetFirstForegroundUserId(); + context->accessee.accountId = MultipleUserConnector:: + GetOhosAccountIdByUserId(context->accessee.userId); + + int64_t tokenId = 0; + ret = AppManager::GetInstance().GetHapTokenIdByName(context->accessee.userId, + context->accessee.bundleName, 0, tokenId); + if (ret != DM_OK) { + LOGI("RespQueryTokenId: get tokenId by bundleName failed %{public}s", + GetAnonyString(context->accessee.bundleName).c_str()); + return ret; + } + context->accessee.tokenId = tokenId; + } else { + // 多用户:特征为accesser传输了tokenId + // 适用于:FA-FA多用户 + // Security::AccessToken::HapTokenInfo tokenInfo; + // TODO: tokenId涉及安全问题,暂无法在80报文中传输 + // ret = AccessTokenKit::GetHapTokenInfo(authResponseContext_->remoteTokenId, tokenInfo); + // if (ret != DM_OK) { + // LOGE("RespQueryTokenId: GetHapTokenInfo failed."); + // return ret; + // } + // authResponseContext_->localUserId = tokenInfo.userID; + // authResponseContext_->localAccountId = MultipleUserConnector:: + // GetOhosAccountIdByUserId(authResponseContext_->localUserId); + // if (ret != DM_OK) { + // LOGI("RespQueryTokenId: get tokenId by bundleName failed %{public}s", + // GetAnonyString(authResponseContext_->bundleName).c_str()); + // return ret; + // } + + // 由于前面无法传输tokenId,暂时中断 + return ERR_DM_FAILED; + } + + return ret; +} + +bool AuthSinkNegotiateStateMachine::HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList) +{ + if (tokenList.size() != 2) { + LOGE("HaveSameTokenId invalid tokenList size."); + return false; + } + + const std::string &src_tokenId = tokenList[0]; + const std::string &sink_tokenId = tokenList[1]; + + // 计算src_tokenId的哈希值 + std::string src_tokenIdHash = Crypto::Sha256(src_tokenId); + + // 比较src_tokenId的哈希值和sink_tokenId + if (src_tokenIdHash != context->accesser.tokenIdHash) { + return false; + } + + if (sink_tokenId != std::to_string(context->accessee.tokenId)) { + return false; + } + + return true; +} + +int32_t AuthSinkNegotiateStateMachine::GetCredentialType(std::shared_ptr context, nlohmann::json credInfo) +{ + // 判断是否同账号 + // TODO: 需要确定截断长度 + if (Crypto::Sha256(context->accessee.accountId) == context->accesser.accountIdHash && + context->accessee.accountId != "ohosAnonymousUid") { + if (credInfo["credType"] == ACCOUNT_RELATED && credInfo["authorizedScope"] == SCOPE_USER) { + return DM_IDENTICAL_ACCOUNT; + } + } else { + if (credInfo["credType"] == ACCOUNT_ACROSS && credInfo["authorizedScope"] == SCOPE_USER) { + return DM_ACROSS_ACCOUNT; + } + if (credInfo["credType"] == ACCOUNT_UNRELATED && credInfo["authorizedScope"] == SCOPE_APP && + HaveSameTokenId(context, credInfo["authorizedAppList"]) == true) { + return DM_POINT_TO_POINT; + } + } + + // 未确定凭据类型 + return DM_INVALIED_BINDTYPE; +} + +// 比较ACL四元组:双端的deviceId和userId +bool AuthSinkNegotiateStateMachine::AclCompareTwoIds(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + // TODO: 需确定deviceId、userId哈希值的截断位数是多少 + return Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash && + Crypto::Sha256(std::to_string(accesser.GetAccesserUserId())) == context->accesser.userIdHash && + accessee.GetAccesseeDeviceId() == context->accessee.deviceId && + accessee.GetAccesseeUserId() == context->accessee.userId; +} + +// 比较ACL八元组:四元组加双端的accountId和tokenId +bool AuthSinkNegotiateStateMachine::AclCompareFourIds(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + return AclCompareTwoIds(context, accesser, accessee) && + // TODO: 需确定deviceId、userId哈希值的截断位数是多少 + Crypto::Sha256(accesser.GetAccesserAccountId()) == context->accesser.accountIdHash && + Crypto::Sha256(std::to_string(accesser.GetAccesserTokenId())) == context->accesser.tokenIdHash && + accessee.GetAccesseeAccountId() == context->accessee.accountId && + accessee.GetAccesseeTokenId() == static_cast(context->accessee.tokenId); +} + +/** + 有无凭据确认逻辑:以ACL的credId为索引,在凭据列表中寻找凭据,若没找到则认为无对应凭据 + - 由于获取凭据时没有对端信息,无法基于对端信息查询凭据,只能通过ACL确认 + 凭据类型获取逻辑:GetCredentialType + + 问题: + 1. 无法确定有凭据无ACL的场景(因为需要基于ACL的ids与凭据匹配,匹配不上的则无信息) + */ +int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptr context) +{ + int32_t ret; + nlohmann::json queryParams; + nlohmann::json queryResult; + + // 1. 获取所有凭据 + queryParams["deviceIdHash"] = context->accesser.deviceIdHash; + queryParams["userIdHash"] = context->accesser.userIdHash; + // TODO: 以下魔鬼数字待谢伟代码上后换成相关宏 + queryParams["subject"] = 2; // 2: 配件 + queryParams["keyFormat"] = 2; // 2: 非对称密钥公钥 + queryParams["algorithmType"] = 4; // 4- ED25519 + queryParams["proofType"] = 1; // 1: PSK + queryParams["credentialOwner"] = "DM"; + ret = context->hiChainAuthConnector->QueryCredentialInfo(context->accessee.userId, queryParams, queryResult); + if (ret != DM_OK) { + LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to query credential id list."); + context->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + return ret; + } + + // 2. 获取所有ACL + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAccessControlProfile(); + bool isAclActive = false; + for (auto &item : profiles) { + auto accesser = item.GetAccesser(); + auto accessee = item.GetAccessee(); + + // 确保凭据能跟ACL对应上。 + std::string credId = std::to_string(accessee.GetAccesseeCredentialId()); + if (queryResult.find(credId) == queryResult.end() || item.GetStatus() != ACTIVE) { + continue; + } + + // 确认凭据类型 + int32_t credType = GetCredentialType(context, queryResult[credId]); + if (credType == DM_INVALIED_BINDTYPE) { + continue; + } + queryResult[credId]["credType"] = credType; + + // 确认是否有可信关系 + if (credType == DM_IDENTICAL_ACCOUNT || credType == DM_ACROSS_ACCOUNT) { + queryResult[credId]["isAclActive"] = AclCompareTwoIds(context, accesser, accessee); + } else if (credType == DM_POINT_TO_POINT) { + queryResult[credId]["isAclActive"] = AclCompareFourIds(context, accesser, accessee); + } + } + + // 3. 筛选凭据 + std::vector invalidCredIds; + for (auto &pair : queryResult) { + std::string key = pair.first; + nlohmann::json value = pair.second; + + if (value.find("isAclActive") == value.end() || value["isAclActive"] == false) { + invalidCredIds.push_back(key); + } + } + + return DM_OK; +} + +int32_t AuthSinkNegotiateStateMachine::ProcRespNegotiate5_1_0(std::shared_ptr context) +{ + // 获取accesee四元组:uid、userId、accountId、tokenId + int32_t ret = RespQueryAcceseeIds(context); + if (ret != DM_OK) { + LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to get tokenId."); + context->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + return ERR_DM_FAILED; + } + + // 检查accesser_deviceId是否上线 + // Q: 80报文未传输accesser.deviceId,无法校验是否上线 + // context->accesser.isOnline = context->softbusConnector->CheckIsOnline(context->accesser.deviceId); + + // 获取凭据信息 + ret = GetAuthCredentialInfo(context); + if (ret != DM_OK) { + LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to get credential."); + context->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + return ERR_DM_FAILED; + } + + // 状态跳转在100报文中处理 + return DM_OK; +} + +int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr context) +{ + LOGI("AuthSinkNegotiateStateMachine::Action sessionid %{public}d", context->sessionId); + + // 1. 停止定时器 + if (context->timer != nullptr) { + context->timer->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); + } + + // 2. 获取deviceName和udid + context->accessee.deviceName = context->softbusConnector->GetLocalDeviceName(); + char localDeviceId[DEVICE_UUID_LENGTH]; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + context->accessee.deviceId = static_cast(localDeviceId); + + // 解析message时,accesser.deviceId已赋值 + // remoteDeviceId_ = authResponseContext_->localDeviceId; + context->accessee.networkId = context->softbusConnector->GetLocalDeviceNetworkId(); + context->accessee.deviceName = context->softbusConnector->GetLocalDeviceName(); + if (CompareVersion(context->accesser.dmVersion, std::string(DM_VERSION_5_1_0)) == false) { + LOGE("AuthSinkNegotiateStateMachine::Action incompatible version compare to 5.1.0"); + return ERR_DM_VERSION_INCOMPATIBLE; + } + + int32_t ret = ProcRespNegotiate5_1_0(context); + if (ret != DM_OK) { + LOGE("AuthSinkNegotiateStateMachine::Action proc response negotiate failed"); + return ret; + } + context->timer->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context_, WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this, context] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context, name); + }); + return DM_OK; +} + /* 能力协商(80和90报文处理) source端状态: diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index ac23b00ca..737f86175 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -13,6 +13,8 @@ * limitations under the License. */ +#include "dm_anonymous.h" +#include "dm_auth_context.h" #include "dm_auth_message_processor.h" #include "dm_auth_context.h" #include "dm_auth_state_machine.h" @@ -238,6 +240,61 @@ void DmAuthMessageProcessor::CreateMessageReqCredAuthStart(std::shared_ptr context, nlohmann::json &jsonObject) +{ + // 目前未看到使用了cryptoAdapter_,删除 + jsonObject[TAG_DEVICE_VERSION] = context->accesser.dmVersion; + jsonObject[TAG_DEVICE_NAME] = context->accesser.deviceName; + + jsonObject[TAG_DEVICE_ID_HASH] = context->accesser.deviceIdHash; + jsonObject[TAG_USER_ID_HASH] = context->accesser.userIdHash; + jsonObject[TAG_ACCOUNT_ID_HASH] = context->accesser.accountIdHash; + jsonObject[TAG_TOKEN_ID_HASH] = context->accesser.tokenIdHash; + + jsonObject[TAG_BUNDLE_NAME] = context->accesser.bundleName; + jsonObject[TAG_PEER_BUNDLE_NAME] = context->accessee.bundleName; + jsonObject[TAG_BIND_LEVEL] = context->accesser.bindLevel; + // 暂无serviceId的定义 + // tokenId、deviceId是否有安全问题?暂未传输 + + return; +} + +void DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject, std::shared_ptr context) +{ + if (IsString(jsonObject, TAG_DEVICE_VERSION)) { + context->accesser.dmVersion = jsonObject[TAG_DEVICE_VERSION].get(); + } + if (IsString(jsonObject, TAG_DEVICE_NAME)) { + context->accesser.deviceName = jsonObject[TAG_DEVICE_NAME].get(); + } + + if (IsString(jsonObject, TAG_DEVICE_ID_HASH)) { + context->accesser.deviceIdHash = jsonObject[TAG_DEVICE_ID_HASH].get(); + } + if (IsString(jsonObject, TAG_USER_ID_HASH)) { + context->accesser.userIdHash = jsonObject[TAG_USER_ID_HASH].get(); + } + if (IsString(jsonObject, TAG_ACCOUNT_ID_HASH)) { + context->accesser.accountIdHash = jsonObject[TAG_ACCOUNT_ID_HASH].get(); + } + if (IsString(jsonObject, TAG_TOKEN_ID_HASH)) { + context->accesser.tokenIdHash = jsonObject[TAG_TOKEN_ID_HASH].get(); + } + + if (IsString(jsonObject, TAG_BUNDLE_NAME)) { + context->accesser.bundleName = jsonObject[TAG_BUNDLE_NAME].get(); + } + if (IsString(jsonObject, TAG_PEER_BUNDLE_NAME)) { + context->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].get(); + } + if (IsInt32(jsonObject, TAG_BIND_LEVEL)) { + context->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].get(); + } + + return; +} int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const nlohmann::json &json, std::shared_ptr context) diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index a1dc8fd31..344355eb3 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -27,6 +27,41 @@ namespace OHOS { namespace DistributedHardware { +namespace { + +const int32_t CLONE_AUTHENTICATE_TIMEOUT = 20; +const int32_t CLONE_NEGOTIATE_TIMEOUT = 10; +const int32_t CLONE_CONFIRM_TIMEOUT = 10; +const int32_t CLONE_ADD_TIMEOUT = 10; +const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10; +const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10; +const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20; + +} + +// clone task timeout map +const std::map TASK_TIME_OUT_MAP = { + { std::string(AUTHENTICATE_TIMEOUT_TASK), CLONE_AUTHENTICATE_TIMEOUT }, + { std::string(NEGOTIATE_TIMEOUT_TASK), CLONE_NEGOTIATE_TIMEOUT }, + { std::string(CONFIRM_TIMEOUT_TASK), CLONE_CONFIRM_TIMEOUT }, + { std::string(ADD_TIMEOUT_TASK), CLONE_ADD_TIMEOUT }, + { std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), CLONE_WAIT_NEGOTIATE_TIMEOUT }, + { std::string(WAIT_REQUEST_TIMEOUT_TASK), CLONE_WAIT_REQUEST_TIMEOUT }, + { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT } +}; + +int32_t DmAuthContext::GetTaskTimeout(const char* taskName, int32_t taskTimeOut) +{ + LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, authType); + if (authType == AUTH_TYPE_IMPORT_AUTH_CODE) { + auto timeout = TASK_TIME_OUT_MAP.find(std::string(taskName)); + if (timeout != TASK_TIME_OUT_MAP.end()) { + return timeout->second; + } + } + return taskTimeOut; +} + void DmAuthState::HandleAuthenticateTimeout(std::shared_ptr context, std::string name) { LOGI("DmAuthContext::HandleAuthenticateTimeout start timer name %{public}s", name.c_str()); diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index b9d6a5e25..ce4ae13c8 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -326,6 +326,54 @@ int32_t HiChainAuthConnector::GenerateCredential(std::string &localUdid, int32_t return DM_OK; } +int32_t HiChainAuthConnector::QueryCredentialInfo(int32_t userId, nlohmann::json queryParams, + nlohmann::json &resultJson) +{ + int32_t ret; + + const CredManager *cm = GetCredMgrInstance(); + char *credIdList = nullptr; + // Q: 之前都是用的ProcessCredential查询,现在是否可用queryCredentialByParams查询? + ret = cm->queryCredentialByParams(userId, SafetyDump(queryParams).c_str(), + &credIdList); + if (ret != DM_OK) { + LOGE("HiChainAuthConnector::QueryCredentialInfo fail to query credential id list."); + return ERR_DM_FAILED; + } + nlohmann::json credIdListJson = nlohmann::json::parse(credIdList, nullptr, false); + FreeJsonString(credIdList); + if (credIdListJson.is_discarded()) { + LOGE("HiChainAuthConnector::QueryCredentialInfo credential id list to jsonStr error"); + return ERR_DM_FAILED; + } + + std::set credBindTypes; + for (const auto& element : credIdListJson) { + if (!element.is_string()) { + continue; + } + std::string credId = element.get(); + + char *returnCredInfo = nullptr; + ret = cm->queryCredInfoByCredId(userId, credId.c_str(), &returnCredInfo); + if (ret != DM_OK) { + LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to query credential info."); + context->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + return ERR_DM_FAILED; + } + nlohmann::json credInfoJson = nlohmann::json::parse(returnCredInfo, nullptr, false); + FreeJsonString(returnCredInfo); + if (credInfoJson.is_discarded()) { + LOGE("DmAuthManager::ProcRespNegotiate5_1_0 credential info jsonStr error"); + return ERR_DM_FAILED; + } + + resultJson[credId] = credInfoJson; + } + + return DM_OK; +} + bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAccountId) { LOGI("HiChainAuthConnector::QueryCredential start."); -- Gitee From 33b66cb63af35c8bf151d0a2a41df25fb7b935d4 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Fri, 28 Feb 2025 09:46:12 +0800 Subject: [PATCH 010/382] =?UTF-8?q?test:=20=E8=A1=A5=E5=85=85=E6=B3=A8?= =?UTF-8?q?=E9=87=8A?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication_v2/auth_stages/auth_negotiate.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index df68e3cec..b73a2037e 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -229,12 +229,12 @@ int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptraccesser.deviceIdHash; queryParams["userIdHash"] = context->accesser.userIdHash; - // TODO: 以下魔鬼数字待谢伟代码上后换成相关宏 - queryParams["subject"] = 2; // 2: 配件 - queryParams["keyFormat"] = 2; // 2: 非对称密钥公钥 - queryParams["algorithmType"] = 4; // 4- ED25519 - queryParams["proofType"] = 1; // 1: PSK - queryParams["credentialOwner"] = "DM"; + // 2/27会上讨论,以下字段不需要传输,只传id相关即可 + // queryParams["subject"] = 2; // 2: 配件 + // queryParams["keyFormat"] = 2; // 2: 非对称密钥公钥 + // queryParams["algorithmType"] = 4; // 4- ED25519 + // queryParams["proofType"] = 1; // 1: PSK + // queryParams["credentialOwner"] = "DM"; ret = context->hiChainAuthConnector->QueryCredentialInfo(context->accessee.userId, queryParams, queryResult); if (ret != DM_OK) { LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to query credential id list."); -- Gitee From 79c9401b520873398a2a3fff698824838e04b19f Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Fri, 28 Feb 2025 11:17:44 +0800 Subject: [PATCH 011/382] =?UTF-8?q?test:=20=E8=A7=A3=E5=86=B3=E7=BC=96?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/auth_manager.h | 3 +++ .../include/authentication_v2/dm_auth_context.h | 2 -- .../include/authentication_v2/dm_auth_state.h | 8 ++++++-- .../src/authentication_v2/auth_manager.cpp | 15 ++++++++------- .../auth_stages/auth_negotiate.cpp | 7 ++----- .../src/authentication_v2/dm_auth_state.cpp | 6 +++--- 6 files changed, 22 insertions(+), 19 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 5e60e6137..2b14619d5 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -62,6 +62,9 @@ class AuthManager : public ISoftbusSessionCallback, public IDmDeviceAuthCallback, public std::enable_shared_from_this { public: + AuthManager(std::shared_ptr softbusConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector); void SetAuthContext(std::shared_ptr context); std::shared_ptr GetAuthContext(); diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index f725d0bbe..b3942cb08 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -177,8 +177,6 @@ struct DmAuthContext { bool fallBackToInputPin{false}; // 是否已经回退到输入PIN码 bool isAuthenticateDevice = false; - // 获取超时时间 - int32_t GetTaskTimeout(const char* taskName, int32_t taskTimeOut); // 获取设备ID std::string GetDeviceId(DmAuthSide side); // 获取凭据ID diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index cb603762e..711948c19 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -105,7 +105,7 @@ public: virtual DmAuthStateType GetStateType() = 0; virtual int32_t Action(std::shared_ptr context) = 0; // 执行状态对应的action动作 static bool IsScreenLocked(); - static int32_t GetTaskTimeout(const char* taskName, int32_t taskTimeOut); + 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: }; @@ -182,7 +182,7 @@ public: virtual ~AuthSrcPinAuthDoneState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; -} +}; class AuthSrcNegotiateStateMachine : public DmAuthState { public: @@ -228,6 +228,9 @@ public: virtual ~AuthSrcCredentialAuthStartState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; +}; + +// 收到80报文,准备发送90报文 class AuthSinkNegotiateStateMachine : public DmAuthState { public: virtual ~AuthSinkNegotiateStateMachine() {}; @@ -243,6 +246,7 @@ private: 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); }; } // namespace DistributedHardware diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index abfd3517b..d8ecfedc2 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -142,18 +142,19 @@ std::string ParseExtraFromMap(const std::map &bindPara } // namespace AuthManager::AuthManager(std::shared_ptr softbusConnector, - std::shared_ptr hiChainConnector, std::shared_ptr listener, std::shared_ptr hiChainAuthConnector) - : context_->softbusConnector(softbusConnector), context_->hiChainAuthConnector(hiChainConnector), - context_->listener(listener), context_->hiChainAuthConnector(hiChainAuthConnector) { LOGI("DmAuthManager constructor"); + context_ = std::make_shared(); + context_->softbusConnector = softbusConnector; + context_->listener = listener; + context_->hiChainAuthConnector = hiChainAuthConnector; + context_->authUiStateMgr = std::make_shared(context_->listener); - context->authenticationMap[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; - context->authenticationMap[AUTH_TYPE_CRE] = nullptr; - context->accesser.dmVersion = DM_VERSION_5_1_0; - context->accessee.dmVersion = DM_VERSION_5_1_0; + context_->authenticationMap[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; + context_->accesser.dmVersion = DM_VERSION_5_1_0; + context_->accessee.dmVersion = DM_VERSION_5_1_0; } void AuthManager::SetAuthContext(std::shared_ptr context) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index b73a2037e..cae47b95f 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -273,10 +273,7 @@ int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptr invalidCredIds; - for (auto &pair : queryResult) { - std::string key = pair.first; - nlohmann::json value = pair.second; - + for (auto& [key, value] : queryResult.items()) { if (value.find("isAclActive") == value.end() || value["isAclActive"] == false) { invalidCredIds.push_back(key); } @@ -341,7 +338,7 @@ int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr con return ret; } context->timer->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), - DmAuthState::GetTaskTimeout(context_, WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this, context] (std::string name) { + DmAuthState::GetTaskTimeout(context, WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this, context] (std::string name) { DmAuthState::HandleAuthenticateTimeout(context, name); }); return DM_OK; diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 344355eb3..c6aadf4c1 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -50,10 +50,10 @@ const std::map TASK_TIME_OUT_MAP = { { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT } }; -int32_t DmAuthContext::GetTaskTimeout(const char* taskName, int32_t taskTimeOut) +int32_t DmAuthState::GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut) { - LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, authType); - if (authType == AUTH_TYPE_IMPORT_AUTH_CODE) { + LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, acontext->uthType); + if (context->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { auto timeout = TASK_TIME_OUT_MAP.find(std::string(taskName)); if (timeout != TASK_TIME_OUT_MAP.end()) { return timeout->second; -- Gitee From 2f801cf120e6934429f00acbde9d1e8d88836542 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Fri, 28 Feb 2025 03:20:38 +0000 Subject: [PATCH 012/382] =?UTF-8?q?=E3=80=90=E6=96=B0=E5=8D=8F=E8=AE=AE?= =?UTF-8?q?=E3=80=91=20=E5=AE=9E=E7=8E=B080/90=E6=8A=A5=E6=96=87=E4=B8=9A?= =?UTF-8?q?=E5=8A=A1=E9=80=BB=E8=BE=91=20=E5=AE=9E=E7=8E=B080/90=E6=8A=A5?= =?UTF-8?q?=E6=96=87=E4=B8=9A=E5=8A=A1=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/auth_manager.h | 57 ++ .../authentication_v2/dm_auth_context.h | 40 +- .../dm_auth_message_processor.h | 73 ++- .../include/authentication_v2/dm_auth_state.h | 110 ++-- .../authentication_v2/dm_auth_state_machine.h | 1 - .../hichain/hichain_auth_connector.h | 1 + .../src/authentication_v2/auth_manager.cpp | 524 +++++++++++++++++- .../auth_stages/auth_negotiate.cpp | 326 +++++++++++ .../dm_auth_message_processor.cpp | 57 ++ .../src/authentication_v2/dm_auth_state.cpp | 35 ++ .../hichain/hichain_auth_connector.cpp | 48 ++ 11 files changed, 1190 insertions(+), 82 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index d3ae5b279..2b14619d5 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -25,19 +25,76 @@ namespace OHOS { namespace DistributedHardware { struct DmAuthContext; + +const int32_t DM_AUTH_TYPE_MAX = 5; +const int32_t DM_AUTH_TYPE_MIN = 0; +const int32_t MIN_PIN_TOKEN = 10000000; +const int32_t MAX_PIN_TOKEN = 90000000; +const int32_t NEGOTIATE_TIMEOUT = 10; +const int32_t WAIT_REQUEST_TIMEOUT = 10; +const int32_t HML_SESSION_TIMEOUT = 10; +const int32_t AUTHENTICATE_TIMEOUT = 120; +constexpr const char* DM_VERSION_5_1_0 = "5.1.0"; +// TODO: 黄蓝区同步,部分代码冲突,冲突时删除此处 +constexpr const char* PARAM_KEY_HML_ENABLE_160M = "hmlEnable160M"; +constexpr const char* PARAM_KEY_HML_ACTIONID = "hmlActionId"; +constexpr const char* PARAM_KEY_CONN_SESSIONTYPE = "connSessionType"; + +constexpr const char* BUNDLE_NAME_KEY = "bundleName"; + +// 取自security_device_auth中的identity_operation.h,该头文件为内部头文件,不能直接引用 +// 若冲突删除此处 +enum { + ACCOUNT_RELATED = 1, + ACCOUNT_UNRELATED, + ACCOUNT_ACROSS +}; + +// 取自security_device_auth中的identity_operation.h,该头文件为内部头文件,不能直接引用 +// 若冲突删除此处 +enum { + SCOPE_DEVICE = 1, + SCOPE_USER, + SCOPE_APP, +}; + class AuthManager : public ISoftbusSessionCallback, public IDmDeviceAuthCallback, public std::enable_shared_from_this { public: + AuthManager(std::shared_ptr softbusConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector); void SetAuthContext(std::shared_ptr context); std::shared_ptr GetAuthContext(); // 各类事件触发的函数实现(虚函数) int32_t GetPinCode(int32_t &code) override; + + int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam); protected: // 上下文(需在该层级进行创建) std::shared_ptr context_; +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(nlohmann::json jsonObject); + void ParseJsonObject(nlohmann::json jsonObject); + void GetAuthParam(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra); + std::string GetBundleName(nlohmann::json &jsonObject); + int32_t GetBindLevel(int32_t bindLevel); + void SetAuthType(int32_t authType); + bool IsAuthTypeSupported(const int32_t &authType); + bool IsAuthCodeReady(const std::string &pkgName); + int32_t CheckAuthParamVaild(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra); + void InitAuthState(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra); + int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra); }; class AuthSrcManager : public AuthManager { diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 950c5b357..b3942cb08 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -19,15 +19,16 @@ #include #include -#include "dm_timer.h" +#include "nlohmann/json.hpp" #include "auth_ui_state_manager.h" #include "hichain_auth_connector.h" #include "hichain_connector.h" -#include "dm_auth_message_processor.h" #include "softbus_connector.h" #include "softbus_session.h" -#include "nlohmann/json.hpp" +#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" @@ -38,13 +39,15 @@ namespace OHOS { namespace DistributedHardware { class DmAuthStateMachine; +class DmAuthMessageProcessor; // PIN码认证类型 -enum DmAuthType { +typedef enum { AUTH_TYPE_PIN_SHOW = 0, // 弹PIN码 AUTH_TYPE_PIN_ULTRASONIC, // 超声PIN码 AUTH_TYPE_PIN_IMPORT, // 导入PIN码 -}; + AUTH_TYPE_IMPORT_AUTH_CODE, // 导入认证码 +} DmAuthType; enum DmAuthDirection { DM_AUTH_SOURCE = 0, @@ -94,9 +97,16 @@ struct DmAccess { std::string deviceName; int32_t deviceType; // PC、mobile、手表、大屏等类型,为业务透传的数据,无需自定义 std::string deviceId; // A->B, 无论是A端还是B端,Accesser对象都存A端的deviceId,Accessee对象都存B端的deviceId + std::string deviceIdHash; + std::string addr; // Q: 旧协议有用到addr,新设计没有,需要确认 int32_t userId; + std::string userIdHash; std::string accountId; + std::string accountIdHash; uint64_t tokenId; + std::string tokenIdHash; + std::string token; // Q: 旧协议有用到token,新设计没有,需要确认 + std::string networkId; std::string bundleName; // 存PacketName int64_t serviceId; // 保留字段,后续会使用 std::string accesserHapSignature; @@ -105,6 +115,9 @@ struct DmAccess { std::string appCredentialId; // 应用级凭据Id std::string userPublicKey; // 用户级公钥 std::string appPublicKey; // 应用级公钥 + std::vector bindType; // 绑定类型,如DM_IDENTICAL_ACCOUNT、DM_ACROSS_ACCOUNT、DM_POINT_TO_POINT + std::string publicKey; // T公钥长度 + int32_t credentialId; // 应用凭据ID int32_t status; // 表示服务为前台还是后台,业务透传,只保存 int32_t sessionKeyId; // 作为秘钥派送的材料,在总线中取出sk int64_t skTimeStamp; // 老化,时间为2天 @@ -128,13 +141,17 @@ struct DmAuthContext { int32_t connDelayCloseTime; // 链路延迟释放时间, 授权结束后不自动断链(有业务需要使用)保留字段 int32_t reason; // 本端失败的原因 int32_t reply; // 对端回复的结果 引用common/include/dm_constants.h,有新的错误码可新增 + int32_t hmlActionId = 0; bool normalFinishAuth; // 标识认证过程是否正常结束 bool authenticating; // 标识正在认证中 + bool hmlEnable160M = false; std::string pkgName; // 业务传入的标识,业务自定义,有被仿冒的风险 + std::string pkgLabel; std::string importCodeBundleName; // 导入pin码的包名,从系统中读取,与acceserBundleName一致 std::string appThumbnail; // 应用图标 std::string appOperation; // 授权弹框中显示本次绑定用于什么操作 std::string customData; // 业务自定义字段,详细提示用户本次绑定的操作 + std::string connSessionType; std::string extraInfo; // 可扩展字段,kv结构 DmAuthDirection direction; // 标识认证方向 ProcessInfo processInfo; // 进程信息 @@ -145,13 +162,20 @@ struct DmAuthContext { std::multimap proxy; // 前面是accesser,后面是accessee std::shared_ptr authStateMachine; // 状态机 - bool fallBackToInputPin{false}; // 是否已经回退到输入PIN码 - std::string transmitData; // 保存 onTrasmit返回数据 - std::shared_ptr timer; std::shared_ptr authUiStateMgr; std::shared_ptr hiChainAuthConnector; // HiChain交互接口 std::shared_ptr authMessageProcessor; // 报文处理接口 std::shared_ptr softbusConnector; // 软总线接口 + std::shared_ptr listener; + std::shared_ptr authPtr; + std::shared_ptr timer; + std::string transmitData; // 保存 onTrasmit返回数据 + std::string importPkgName = ""; + std::string importAuthCode = ""; + std::map> authenticationMap; + PeerTargetId peerTargetId; + bool fallBackToInputPin{false}; // 是否已经回退到输入PIN码 + bool isAuthenticateDevice = false; // 获取设备ID std::string GetDeviceId(DmAuthSide side); diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index c1d0b0ac9..a8fb4213d 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -24,6 +24,45 @@ namespace OHOS { namespace DistributedHardware { struct DmAuthContext; + +constexpr const char *DM_TAG_MSG_TYPE = "messageType"; // 报文类型 +constexpr const char *DM_TAG_DATA = "data"; // 报文数据 +constexpr const char *DM_TAG_USER_PUBLICK_KEY = "userPublicKey"; // 用户级公钥 userPublicKey +constexpr const char *DM_TAG_APP_PUBLICK_KEY = "appPublicKey"; // 应用级公钥 appPublicKey +constexpr const char *DM_TAG_USER_CREDENTIAL_ID = "userCredentialId"; // 用户级凭据Id +constexpr const char *DM_TAG_APP_CREDENTIAL_ID = "appCredentialId"; // 应用级凭据Id +constexpr const char *DM_TAG_ON_TRANSMIT_DATA = "onTransmitData"; // onTransmitData接口返回信息 + +// is接口入参 json格式字符串中的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 = "credentialOwner"; +constexpr const char *DM_AUTH_CREDENTIAL_OWNER = "DM"; // 凭据拥有者 + +constexpr const char* APP_OPERATION_KEY = "appOperation"; +constexpr const char* APP_THUMBNAIL = "appThumbnail"; +constexpr const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; + +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_PKG_NAME = "pkgName"; + // 报文类型 enum DmMessageType { // 终止/异常报文 @@ -49,29 +88,6 @@ enum DmMessageType { MSG_TYPE_AUTH_FINISH = 200, }; -constexpr const char *DM_TAG_MSG_TYPE = "messageType"; // 报文类型 -constexpr const char *DM_TAG_DATA = "data"; // 报文数据 -constexpr const char *DM_TAG_USER_PUBLICK_KEY = "userPublicKey"; // 用户级公钥 userPublicKey -constexpr const char *DM_TAG_APP_PUBLICK_KEY = "appPublicKey"; // 应用级公钥 appPublicKey -constexpr const char *DM_TAG_USER_CREDENTIAL_ID = "userCredentialId"; // 用户级凭据Id -constexpr const char *DM_TAG_APP_CREDENTIAL_ID = "appCredentialId"; // 应用级凭据Id -constexpr const char *DM_TAG_ON_TRANSMIT_DATA = "onTransmitData"; // onTransmitData接口返回信息 - -// is接口入参 json格式字符串中的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 = "credentialOwner"; -constexpr const char *DM_AUTH_CREDENTIAL_OWNER = "DM"; // 凭据拥有者 - class DmAuthMessageProcessor { public: // 解析报文,返回值为错误码,实际解析出来的信息保存到context中 @@ -84,6 +100,8 @@ public: int32_t SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyLen); private: // 内部各类报文的实现 + // 解析 80报文 + void ParseNegotiateMessage(nlohmann::json &jsonObject, std::shared_ptr context); // 解析 90 报文 int32_t ParseMessageRespAclNegotiate(const nlohmann::json &json, std::shared_ptr context); // 解析 100 报文 @@ -96,12 +114,15 @@ private: int32_t ParseMessageRespPinAuthStart(const nlohmann::json &json, std::shared_ptr context); // 解析 121 报文 int32_t ParseMessageReqPinAuthNegotiate(const nlohmann::json &json, std::shared_ptr context); - // 解析131报文onTransmitData返回的数据,存在contextd->extra中 + // 解析 131报文onTransmitData返回的数据,存在contextd->extra中 int32_t ParseMessageOnTransmit(const nlohmann::json &jsonObject, std::shared_ptr context); - // 解析140报文信息MSG_TYPE_REQ_CREDENTIAL_EXCHANGE,SINK端存放对方公钥 + // 解析 140报文信息MSG_TYPE_REQ_CREDENTIAL_EXCHANGE,SINK端存放对方公钥 int32_t ParseMessageReqCredExchange(const nlohmann::json &jsonObject, std::shared_ptr context); - // 解析150报文信息MSG_TYPE_RESP_CREDENTIAL_EXCHANGE,存放对方公钥,和协商凭据Id + // 解析 150报文信息MSG_TYPE_RESP_CREDENTIAL_EXCHANGE,存放对方公钥,和协商凭据Id int32_t ParseMessageRspCredExchange(const nlohmann::json &jsonObject, std::shared_ptr context); + + // 创建 80报文 + void CreateNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject); // 创建 100 报文 void CreateMessageReqUserConfirm(std::shared_ptr context, nlohmann::json &json); // 创建 110 报文 diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 0dcfc65b6..711948c19 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -18,6 +18,9 @@ #include +#include "access_control_profile.h" + +#include "dm_auth_state.h" #include "dm_auth_context.h" namespace OHOS { @@ -56,12 +59,53 @@ enum class DmAuthStateType { AUTH_SINK_FINISH_STATE, // 收到200结束报文 }; +// 凭据添加方式 +enum DmAuthCredentialAddMethod { + DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE = 1, // 生成 + DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT, // 导入 +}; + +// 凭据主体 +enum DmAuthCredentialSubject { + DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY = 1, // 主控 + DM_AUTH_CREDENTIAL_SUBJECT_SUPPLEMENT, // 配件 +}; + +// 凭据与账号关联 +enum DmAuthCredentialAccountRelation { + DM_AUTH_CREDENTIAL_ACCOUNT_RELATED = 1, // 账号相关 + DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED, // 账号无关 +}; + +// 秘钥类型 +enum DmAuthKeyFormat { + 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 { + 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 { + 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动作 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: }; @@ -140,52 +184,19 @@ public: 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: - // 凭据添加方式 - enum DmAuthCredentialAddMethod { - DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE = 1, // 生成 - DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT, // 导入 - }; - - // 凭据主体 - enum DmAuthCredentialSubject { - DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY = 1, // 主控 - DM_AUTH_CREDENTIAL_SUBJECT_SUPPLEMENT, // 配件 - }; - - // 凭据与账号关联 - enum DmAuthCredentialAccountRelation { - DM_AUTH_CREDENTIAL_ACCOUNT_RELATED = 1, // 账号相关 - DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED, // 账号无关 - }; - - // 秘钥类型 - enum DmAuthKeyFormat { - 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 { - 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 { - DM_AUTH_CREDENTIAL_PROOF_PSK = 1, // PSK - DM_AUTH_CREDENTIAL_PROOF_PKI, // PKI - }; - // 生成凭据协商状态下的authParams的json格式字符串 std::string CreateAuthParamsString(DmAuthScope authorizedScope, DmAuthCredentialAddMethod method, const std::shared_ptr &authContext); @@ -219,6 +230,25 @@ public: int32_t Action(std::shared_ptr context) override; }; +// 收到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 HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList); + int32_t GetCredentialType(std::shared_ptr context, nlohmann::json credInfo); + 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); +}; + } // 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 index d6d029ad2..e793c4ac8 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state_machine.h +++ b/services/implementation/include/authentication_v2/dm_auth_state_machine.h @@ -52,7 +52,6 @@ enum DmEventType { class DmAuthStateMachine { public: - DmAuthStateMachine() = delete; DmAuthStateMachine(std::shared_ptr context); ~DmAuthStateMachine(); diff --git a/services/implementation/include/dependency/hichain/hichain_auth_connector.h b/services/implementation/include/dependency/hichain/hichain_auth_connector.h index f03781e12..e2291f10e 100644 --- a/services/implementation/include/dependency/hichain/hichain_auth_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_auth_connector.h @@ -54,6 +54,7 @@ public: int32_t ProcessAuthData(int64_t requestId, std::string authData, int32_t osAccountId); int32_t GenerateCredential(std::string &localUdid, int32_t osAccountId, std::string &publicKey); bool QueryCredential(std::string &localUdid, int32_t osAccountId); + int32_t QueryCredentialInfo(int32_t userId, nlohmann::json queryParams, nlohmann::json &resultJson); int32_t ImportCredential(int32_t osAccountId, std::string deviceId, std::string publicKey); int32_t DeleteCredential(const std::string &deviceId, int32_t userId); int32_t RegisterHiChainAuthCallback(std::shared_ptr callback); diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 70c197cd2..d8ecfedc2 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -15,20 +15,148 @@ #include -#include "dm_auth_message_processor.h" -#include "dm_auth_state_machine.h" -#include "auth_manager.h" -#include "dm_auth_context.h" +#include "app_manager.h" +#include "softbus_common.h" +#include "system_ability_definition.h" +#include "iservice_registry.h" +#include "parameter.h" +#include "deviceprofile_connector.h" +#include "multiple_user_connector.h" + +#include "dm_constants.h" +#include "dm_crypto.h" +#include "dm_random.h" #include "dm_log.h" +#include "dm_timer.h" +#include "dm_radar_helper.h" +#include "dm_device_info.h" +#include "dm_anonymous.h" #include "dm_auth_state_machine.h" +#include "dm_auth_context.h" +#include "dm_auth_message_processor.h" +#include "auth_manager.h" #undef LOG_TAG #define LOG_TAG "DHDM_V2" namespace OHOS { namespace DistributedHardware { +namespace { const int32_t MAX_AUTH_FAIL_TIMES = 3; +// TODO: 黄蓝区未同步,无CONN_SESSION_TYPE_HML符号 +bool IsHmlSessionType(std::string sessionType) +{ + return false; + // return sessionType == CONN_SESSION_TYPE_HML; +} + +int32_t GetCloseSessionDelaySeconds(std::string &delaySecondsStr) +{ + if (!IsNumberString(delaySecondsStr)) { + LOGE("Invalid parameter, param is not number."); + return 0; + } + const int32_t CLOSE_SESSION_DELAY_SECONDS_MAX = 10; + int32_t delaySeconds = std::atoi(delaySecondsStr.c_str()); + if (delaySeconds < 0 || delaySeconds > CLOSE_SESSION_DELAY_SECONDS_MAX) { + LOGE("Invalid parameter, param out of range."); + return 0; + } + return delaySeconds; +} + +std::string GetBundleLable(const std::string &bundleName) +{ + auto samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager(); + if (samgr == nullptr) { + LOGE("Get ability manager failed"); + return bundleName; + } + + sptr object = samgr->GetSystemAbility(BUNDLE_MGR_SERVICE_SYS_ABILITY_ID); + if (object == nullptr) { + LOGE("object is NULL."); + return bundleName; + } + + sptr bms = iface_cast(object); + if (bms == nullptr) { + LOGE("bundle manager service is NULL."); + return bundleName; + } + + auto bundleResourceProxy = bms->GetBundleResourceProxy(); + if (bundleResourceProxy == nullptr) { + LOGE("GetBundleResourceProxy fail"); + return bundleName; + } + AppExecFwk::BundleResourceInfo resourceInfo; + auto result = bundleResourceProxy->GetBundleResourceInfo(bundleName, + static_cast(OHOS::AppExecFwk::ResourceFlag::GET_RESOURCE_INFO_ALL), resourceInfo); + if (result != ERR_OK) { + LOGE("GetBundleResourceInfo failed"); + return bundleName; + } + LOGI("bundle resource label is %{public}s ", (resourceInfo.label).c_str()); + return resourceInfo.label; +} + +bool IsAllowDeviceBind(void) +{ + if (AppManager::GetInstance().IsSystemSA()) { + return true; + } + return false; +} + +int32_t CheckAuthParamVaildExtra(const std::string &extra) +{ + nlohmann::json jsonObject = nlohmann::json::parse(extra, nullptr, false); + if (jsonObject.is_discarded() || jsonObject.find(TAG_BIND_LEVEL) == jsonObject.end() || + !IsInt32(jsonObject, TAG_BIND_LEVEL)) { + return DM_OK; + } + int32_t bindLevel = jsonObject[TAG_BIND_LEVEL].get(); + if (static_cast(bindLevel) > APP || bindLevel < INVALID_TYPE) { + LOGE("bindlevel error %{public}d.", bindLevel); + return ERR_DM_INPUT_PARA_INVALID; + } + + if (static_cast(bindLevel) == DEVICE && !IsAllowDeviceBind()) { + LOGE("not allowd device level bind bindlevel: %{public}d.", bindLevel); + return ERR_DM_INPUT_PARA_INVALID; + } + return DM_OK; +} + +std::string ParseExtraFromMap(const std::map &bindParam) +{ + auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA); + if (iter != bindParam.end()) { + return iter->second; + } + return ConvertMapToJsonString(bindParam); +} + +} // namespace + +AuthManager::AuthManager(std::shared_ptr softbusConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector) +{ + LOGI("DmAuthManager constructor"); + context_ = std::make_shared(); + context_->softbusConnector = softbusConnector; + context_->listener = listener; + context_->hiChainAuthConnector = hiChainAuthConnector; + + context_->authUiStateMgr = std::make_shared(context_->listener); + context_->authenticationMap[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; + context_->accesser.dmVersion = DM_VERSION_5_1_0; + context_->accessee.dmVersion = DM_VERSION_5_1_0; +} + void AuthManager::SetAuthContext(std::shared_ptr context) { this->context_ = context; @@ -39,8 +167,29 @@ std::shared_ptr AuthManager::GetAuthContext() return this->context_; } -// 各类事件触发的函数实现(子类继承实现) -// AuthSrcManager +int32_t AuthManager::ParseAuthType(const std::map &bindParam, int32_t &authType) +{ + auto iter = bindParam.find(PARAM_KEY_AUTH_TYPE); + if (iter == bindParam.end()) { + LOGE("AuthManager::ParseAuthType bind param key: %{public}s not exist.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + std::string authTypeStr = iter->second; + if (authTypeStr.empty()) { + LOGE("AuthManager::ParseAuthType bind param %{public}s is empty.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + if (authTypeStr.length() > 1) { + LOGE("AuthManager::ParseAuthType bind param %{public}s length is unsupported.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + if (!isdigit(authTypeStr[0])) { + LOGE("AuthManager::ParseAuthType bind param %{public}s fromat is unsupported.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + authType = std::atoi(authTypeStr.c_str()); + return DM_OK; +} // 保存秘钥 void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) @@ -63,7 +212,368 @@ void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sess context_->authStateMachine->NotifyEventFinish(ON_SESSION_KEY_RETURNED); } -// AuthSinkManager +int32_t AuthManager::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType) +{ + int32_t index = 0; + std::shared_ptr deviceInfo = std::make_shared(); + ConnectionAddr addr; + if (!targetId.wifiIp.empty() && targetId.wifiIp.length() <= IP_STR_MAX_LEN) { + LOGI("AuthManager::ParseConnectAddr parse wifiIp: %{public}s.", GetAnonyString(targetId.wifiIp).c_str()); + if (!addrType.empty()) { + addr.type = static_cast(std::atoi(addrType.c_str())); + } else { + addr.type = ConnectionAddrType::CONNECTION_ADDR_WLAN; + } + memcpy_s(addr.info.ip.ip, IP_STR_MAX_LEN, targetId.wifiIp.c_str(), targetId.wifiIp.length()); + addr.info.ip.port = targetId.wifiPort; + deviceInfo->addr[index] = addr; + deviceId = targetId.wifiIp; + index++; + } else if (!targetId.brMac.empty() && targetId.brMac.length() <= BT_MAC_LEN) { + LOGI("AuthManager::ParseConnectAddr parse brMac: %{public}s.", GetAnonyString(targetId.brMac).c_str()); + addr.type = ConnectionAddrType::CONNECTION_ADDR_BR; + memcpy_s(addr.info.br.brMac, BT_MAC_LEN, targetId.brMac.c_str(), targetId.brMac.length()); + deviceInfo->addr[index] = addr; + deviceId = targetId.brMac; + index++; + } else if (!targetId.bleMac.empty() && targetId.bleMac.length() <= BT_MAC_LEN) { + LOGI("AuthManager::ParseConnectAddr parse bleMac: %{public}s.", GetAnonyString(targetId.bleMac).c_str()); + addr.type = ConnectionAddrType::CONNECTION_ADDR_BLE; + memcpy_s(addr.info.ble.bleMac, BT_MAC_LEN, targetId.bleMac.c_str(), targetId.bleMac.length()); + if (!targetId.deviceId.empty()) { + Crypto::ConvertHexStringToBytes(addr.info.ble.udidHash, UDID_HASH_LEN, + targetId.deviceId.c_str(), targetId.deviceId.length()); + } + deviceInfo->addr[index] = addr; + deviceId = targetId.bleMac; + index++; + } else { + LOGE("AuthManager::ParseConnectAddr failed, not addr."); + return ERR_DM_INPUT_PARA_INVALID; + } + + deviceInfo->addrNum = static_cast(index); + if (context_->softbusConnector->AddMemberToDiscoverMap(deviceId, deviceInfo) != DM_OK) { + LOGE("AuthManager::ParseConnectAddr failed, AddMemberToDiscoverMap failed."); + return ERR_DM_INPUT_PARA_INVALID; + } + deviceInfo = nullptr; + return DM_OK; +} + +void AuthManager::SetAuthType(int32_t authType) +{ + context_->authType = (DmAuthType)authType; +} + +bool AuthManager::IsAuthTypeSupported(const int32_t &authType) +{ + if (context_->authenticationMap.find(authType) == context_->authenticationMap.end()) { + LOGE("IsAuthTypeSupported failed, authType is not supported."); + return false; + } + return true; +} + +bool AuthManager::IsAuthCodeReady(const std::string &pkgName) +{ + if (context_->importAuthCode.empty() || context_->importPkgName.empty()) { + LOGE("AuthManager::IsAuthCodeReady, auth code not ready."); + return false; + } + if (pkgName != context_->importPkgName) { + LOGE("IsAuthCodeReady failed, pkgName not supported."); + return false; + } + return true; +} + +int32_t AuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("AuthManager::CheckAuthParamVaild start."); + if (authType < DM_AUTH_TYPE_MIN || authType > DM_AUTH_TYPE_MAX) { + LOGE("CheckAuthParamVaild failed, authType is illegal."); + return ERR_DM_AUTH_FAILED; + } + if (pkgName.empty() || deviceId.empty()) { + LOGE("AuthManager::CheckAuthParamVaild failed, pkgName is %{public}s, deviceId is %{public}s, extra is" + "%{public}s.", pkgName.c_str(), GetAnonyString(deviceId).c_str(), extra.c_str()); + return ERR_DM_INPUT_PARA_INVALID; + } + if (context_->listener == nullptr || context_->authUiStateMgr == nullptr) { + LOGE("AuthManager::CheckAuthParamVaild listener or authUiStateMgr is nullptr."); + return ERR_DM_INPUT_PARA_INVALID; + } + + if (!IsAuthTypeSupported(authType)) { + LOGE("AuthManager::CheckAuthParamVaild authType %{public}d not support.", authType); + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", STATUS_DM_AUTH_DEFAULT, + ERR_DM_UNSUPPORTED_AUTH_TYPE); + context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, ""); + return ERR_DM_UNSUPPORTED_AUTH_TYPE; + } + + if (!context_->softbusConnector->HaveDeviceInMap(deviceId)) { + LOGE("CheckAuthParamVaild failed, the discoveryDeviceInfoMap_ not have this device."); + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", + STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); + context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); + return ERR_DM_INPUT_PARA_INVALID; + } + + if ((authType == AUTH_TYPE_IMPORT_AUTH_CODE) && (!IsAuthCodeReady(pkgName))) { + LOGE("Auth code not exist."); + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", + STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); + context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + ERR_DM_INPUT_PARA_INVALID, STATUS_DM_AUTH_DEFAULT, ""); + return ERR_DM_INPUT_PARA_INVALID; + } + return DM_OK; +} + +void AuthManager::ParseHmlInfoInJsonObject(nlohmann::json jsonObject) +{ + if (IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE)) { + context_->connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].get(); + LOGI("connSessionType %{public}s", context_->connSessionType.c_str()); + } + if (!IsHmlSessionType(context_->connSessionType)) { + return; + } + context_->connDelayCloseTime = HML_SESSION_TIMEOUT; + if (IsBool(jsonObject, PARAM_KEY_HML_ENABLE_160M)) { + context_->hmlEnable160M = jsonObject[PARAM_KEY_HML_ENABLE_160M].get(); + LOGI("hmlEnable160M %{public}d", context_->hmlEnable160M); + } + if (IsInt32(jsonObject, PARAM_KEY_HML_ACTIONID)) { + context_->hmlActionId = jsonObject[PARAM_KEY_HML_ACTIONID].get(); + if (context_->hmlActionId <= 0) { + context_->hmlActionId = 0; + } + LOGI("hmlActionId %{public}d", context_->hmlActionId); + } + + return; +} + +std::string AuthManager::GetBundleName(nlohmann::json &jsonObject) +{ + if (!jsonObject.is_discarded() && IsString(jsonObject, BUNDLE_NAME_KEY)) { + return jsonObject[BUNDLE_NAME_KEY].get(); + } + bool isSystemSA = false; + std::string bundleName; + AppManager::GetInstance().GetCallerName(isSystemSA, bundleName); + return bundleName; +} + +void AuthManager::ParseJsonObject(nlohmann::json jsonObject) +{ + if (jsonObject.is_discarded()) { + return; + } + + // 由于旧协议中没怎么用,新协议的设计也没有该字段 + // 故废弃了targetPkgName + + // 填充context_ + if (IsString(jsonObject, APP_OPERATION_KEY)) { + context_->appOperation = jsonObject[APP_OPERATION_KEY].get(); + } + if (IsString(jsonObject, CUSTOM_DESCRIPTION_KEY)) { + context_->customData = jsonObject[CUSTOM_DESCRIPTION_KEY].get(); + } + if (IsString(jsonObject, APP_THUMBNAIL)) { + context_->appThumbnail = jsonObject[APP_THUMBNAIL].get(); + } + context_->connDelayCloseTime = 0; + if (IsString(jsonObject, PARAM_CLOSE_SESSION_DELAY_SECONDS)) { + std::string delaySecondsStr = jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].get(); + context_->connDelayCloseTime = GetCloseSessionDelaySeconds(delaySecondsStr); + } + + // 填充context_->accesser + if (IsInt32(jsonObject, TAG_BIND_LEVEL)) { + context_->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].get(); + } + context_->accesser.bundleName = GetBundleName(jsonObject); + + // 填充context_accessee + if (IsString(jsonObject, TAG_PEER_BUNDLE_NAME)) { + context_->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].get(); + if (context_->accessee.bundleName == "") { + context_->accessee.bundleName = context_->pkgName; + } + LOGI("ParseJsonObject accessee bundleName = %{public}s", context_->accessee.bundleName.c_str()); + } else { + context_->accessee.bundleName = context_->pkgName; + } + + ParseHmlInfoInJsonObject(jsonObject); + return; +} + +int32_t AuthManager::GetBindLevel(int32_t bindLevel) +{ +#ifdef DEVICE_MANAGER_COMMON_FLAG + LOGI("device_manager_common is true!"); + std::string processName = ""; + int32_t ret = AppManager::GetInstance().GetCallerProcessName(processName); + LOGI("GetBindLevel processName = %{public}s", GetAnonyString(processName).c_str()); + if (ret == DM_OK && CheckProcessNameInWhiteList(processName)) { + return DEVICE; + } +#endif + if (IsAllowDeviceBind()) { + if (static_cast(bindLevel) == INVALIED_TYPE || static_cast(bindLevel) > APP || + static_cast(bindLevel) < DEVICE) { + return DEVICE; + } + return bindLevel; + } + if (static_cast(bindLevel) == INVALIED_TYPE || (static_cast(bindLevel) != APP && + static_cast(bindLevel) != SERVICE)) { + return APP; + } + return bindLevel; +} + +void AuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("Get auth param."); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string localUdid = static_cast(localDeviceId); + context_->pkgName = pkgName; + context_->pkgLabel = GetBundleLable(pkgName); + context_->authType = (DmAuthType)authType; + context_->accesser.deviceName = context_->softbusConnector->GetLocalDeviceName(); + context_->accesser.deviceType = context_->softbusConnector->GetLocalDeviceTypeId(); + context_->accesser.deviceId = localUdid; + context_->accesser.dmVersion = DM_VERSION_5_1_0; + uint32_t tokenId = 0 ; + MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, context_->accesser.userId); + context_->accesser.tokenId = static_cast(tokenId); + context_->accesser.accountId = MultipleUserConnector::GetOhosAccountIdByUserId(context_->accesser.userId); + context_->accesser.isOnline = false; + context_->accesser.isAuthed = !context_->accesser.bindType.empty(); + context_->accesser.bindLevel = INVALIED_TYPE; + + context_->accessee.deviceId = deviceId; + context_->accessee.addr = deviceId; + nlohmann::json jsonObject = nlohmann::json::parse(extra, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("extra string not a json type."); + return; + } + ParseJsonObject(jsonObject); + + context_->accesser.token = std::to_string(GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN)); + context_->accesser.bindLevel = this->GetBindLevel(context_->accesser.bindLevel); +} + +void AuthManager::InitAuthState(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + auto iter = context_->authenticationMap.find(authType); + if (iter != context_->authenticationMap.end()) { + context_->authPtr = iter->second; + } + + if (authType > AUTH_TYPE_IMPORT_AUTH_CODE || authType < AUTH_TYPE_PIN_SHOW) { + LOGE("AuthManager::InitAuthState invalid authType"); + return; + } + + if (context_->timer == nullptr) { + context_->timer = std::make_shared(); + } + context_->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context_, AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context_, name); + }); + context_->authMessageProcessor = std::make_shared(); + GetAuthParam(pkgName, authType, deviceId, extra); + context_->authStateMachine = std::make_shared(context_); + LOGI("AuthManager::AuthenticateDevice complete"); + + return; +} + +int32_t AuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("AuthManager::AuthenticateDevice start auth type %{public}d.", authType); + SetAuthType(authType); + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + context_->processInfo.pkgName = pkgName; + context_->processInfo.userId = userId; + int32_t ret = CheckAuthParamVaild(pkgName, authType, deviceId, extra); + if (ret != DM_OK) { + LOGE("AuthManager::AuthenticateDevice failed, param is invaild."); + return ret; + } + ret = CheckAuthParamVaildExtra(extra); + if (ret != DM_OK) { + LOGE("CheckAuthParamVaildExtra failed, param is invaild."); + return ret; + } + context_->isAuthenticateDevice = true; + // TODO: 当前已经没有AUTH_TYPE_CRE类型,待确认 + // if (authType == AUTH_TYPE_CRE) { + // LOGI("AuthManager::AuthenticateDevice for credential type, joinLNN directly."); + // context_->softbusConnector->JoinLnn(deviceId); + // context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", + // STATUS_DM_AUTH_DEFAULT, DM_OK); + // context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, + // DM_OK, STATUS_DM_AUTH_DEFAULT, ""); + // return DM_OK; + // } + InitAuthState(pkgName, authType, deviceId, extra); + return DM_OK; +} + +int32_t AuthManager::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam) +{ + struct RadarInfo info = { + .funcName = "AuthenticateDevice", + .stageRes = static_cast(StageRes::STAGE_SUCC), + .bizState = static_cast(BizState::BIZ_STATE_END), + }; + if (!DmRadarHelper::GetInstance().ReportDiscoverUserRes(info)) { + LOGE("ReportDiscoverUserRes failed"); + } + if (pkgName.empty()) { + LOGE("AuthManager::BindTarget failed, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + int32_t authType = -1; + if (ParseAuthType(bindParam, authType) != DM_OK) { + LOGE("AuthManager::BindTarget failed, key: %{public}s error.", PARAM_KEY_AUTH_TYPE); + return ERR_DM_INPUT_PARA_INVALID; + } + context_->peerTargetId = targetId; + std::string deviceId = ""; + std::string addrType; + if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) { + addrType = bindParam.at(PARAM_KEY_CONN_ADDR_TYPE); + } + if (ParseConnectAddr(targetId, deviceId, addrType) == DM_OK) { + return AuthenticateDevice(pkgName, authType, deviceId, ParseExtraFromMap(bindParam)); + } else if (!targetId.deviceId.empty()) { + return AuthenticateDevice(pkgName, authType, targetId.deviceId, ParseExtraFromMap(bindParam)); + } else { + LOGE("AuthManager::BindTarget failed, targetId is error."); + return ERR_DM_INPUT_PARA_INVALID; + } +} int32_t AuthSinkManager::OnUserOperation(int32_t action, const std::string ¶ms) { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index e451732e8..cae47b95f 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -13,11 +13,337 @@ * limitations under the License. */ +#include +#include "nlohmann/json.hpp" + +#include "parameter.h" +#include "multiple_user_connector.h" +#include "app_manager.h" +#include "hap_token_info.h" +#include "deviceprofile_connector.h" +#include "device_auth.h" +#include "access_control_profile.h" +#include "accesser.h" +#include "accessee.h" + +#include "dm_crypto.h" +#include "dm_log.h" +#include "dm_timer.h" +#include "dm_constants.h" +#include "dm_anonymous.h" +#include "dm_auth_context.h" +#include "auth_manager.h" #include "dm_auth_state.h" namespace OHOS { namespace DistributedHardware { +int32_t AuthSrcNegotiateStateMachine::Action(std::shared_ptr context) +{ + LOGI("AuthSrcNegotiateStateMachine::Action sessionId %{public}d.", context->sessionId); + + // Q:为什么会让对端deviceId等于自己的deviceId? + context->accessee.deviceId = context->accesser.deviceId; + context->reply = ERR_DM_AUTH_REJECT; + // authType、deviceId已在BindTarget赋值 + // accountGroupIdHash已废弃,无组的概念 + // hostPkgName已废弃,直接取context的pkgName,已在初始化时赋值 + context->accessee.bundleName = context->accesser.bundleName; // 初始化时已赋值,这里是不是存在冲突? + // context的accesser和accessee的bundleName已经覆盖peerBundleName + // pkgLabel已赋值 + // tokenId已不在80报文中传输 + // bindLevel已在BindTarget赋值 + // bindType已在BindTarget赋值 + // isOnline已在BindTarget赋值 + // authed替换为isAuthed,已在BindTarget赋值 + // 为什么之前DmVersion传空? + context->accessee.dmVersion = ""; + // accountId不再在80报文中传输 + // userId不再在80报文中传输 + // isIdenticalAccount不再在80报文中传输 + // edition不再在80报文中传输 + // remoteDeviceName + + // 计算哈希值 + context->accesser.deviceIdHash = Crypto::Sha256(context->accesser.deviceId); + context->accesser.userIdHash = Crypto::Sha256(std::to_string(context->accesser.userId)); + context->accesser.accountIdHash = Crypto::Sha256(context->accesser.accountId); + context->accesser.tokenIdHash = Crypto::Sha256(std::to_string(context->accesser.tokenId)); + + std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_REQ_ACL_NEGOTIATE, context); + context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); + if (context->timer != nullptr) { + context->timer->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT), [this, context] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context, name); + }); + } + + return DM_OK; +} + +int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptr context) +{ + int32_t ret; + + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + context->accessee.deviceId = static_cast(localDeviceId); + + if (context->accesser.tokenIdHash.empty()) { + // 单用户:特征为accesser未传输tokenIdHash + // 适用于:FA-FA、SA-SA + // 当前无FA-FA_service、SA-SA_service、FA-device(bindTarget暂无peerType) + std::vector userVec; + + ret = MultipleUserConnector::GetForegroundUserIds(userVec); + if (ret != DM_OK) { + LOGE("RespQueryTokenId: GetForegroundUserIds failed, ret: %{public}d", ret); + return ret; + } + + context->accessee.userId = MultipleUserConnector::GetFirstForegroundUserId(); + context->accessee.accountId = MultipleUserConnector:: + GetOhosAccountIdByUserId(context->accessee.userId); + + int64_t tokenId = 0; + ret = AppManager::GetInstance().GetHapTokenIdByName(context->accessee.userId, + context->accessee.bundleName, 0, tokenId); + if (ret != DM_OK) { + LOGI("RespQueryTokenId: get tokenId by bundleName failed %{public}s", + GetAnonyString(context->accessee.bundleName).c_str()); + return ret; + } + context->accessee.tokenId = tokenId; + } else { + // 多用户:特征为accesser传输了tokenId + // 适用于:FA-FA多用户 + // Security::AccessToken::HapTokenInfo tokenInfo; + // TODO: tokenId涉及安全问题,暂无法在80报文中传输 + // ret = AccessTokenKit::GetHapTokenInfo(authResponseContext_->remoteTokenId, tokenInfo); + // if (ret != DM_OK) { + // LOGE("RespQueryTokenId: GetHapTokenInfo failed."); + // return ret; + // } + // authResponseContext_->localUserId = tokenInfo.userID; + // authResponseContext_->localAccountId = MultipleUserConnector:: + // GetOhosAccountIdByUserId(authResponseContext_->localUserId); + // if (ret != DM_OK) { + // LOGI("RespQueryTokenId: get tokenId by bundleName failed %{public}s", + // GetAnonyString(authResponseContext_->bundleName).c_str()); + // return ret; + // } + + // 由于前面无法传输tokenId,暂时中断 + return ERR_DM_FAILED; + } + + return ret; +} + +bool AuthSinkNegotiateStateMachine::HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList) +{ + if (tokenList.size() != 2) { + LOGE("HaveSameTokenId invalid tokenList size."); + return false; + } + + const std::string &src_tokenId = tokenList[0]; + const std::string &sink_tokenId = tokenList[1]; + + // 计算src_tokenId的哈希值 + std::string src_tokenIdHash = Crypto::Sha256(src_tokenId); + + // 比较src_tokenId的哈希值和sink_tokenId + if (src_tokenIdHash != context->accesser.tokenIdHash) { + return false; + } + + if (sink_tokenId != std::to_string(context->accessee.tokenId)) { + return false; + } + + return true; +} + +int32_t AuthSinkNegotiateStateMachine::GetCredentialType(std::shared_ptr context, nlohmann::json credInfo) +{ + // 判断是否同账号 + // TODO: 需要确定截断长度 + if (Crypto::Sha256(context->accessee.accountId) == context->accesser.accountIdHash && + context->accessee.accountId != "ohosAnonymousUid") { + if (credInfo["credType"] == ACCOUNT_RELATED && credInfo["authorizedScope"] == SCOPE_USER) { + return DM_IDENTICAL_ACCOUNT; + } + } else { + if (credInfo["credType"] == ACCOUNT_ACROSS && credInfo["authorizedScope"] == SCOPE_USER) { + return DM_ACROSS_ACCOUNT; + } + if (credInfo["credType"] == ACCOUNT_UNRELATED && credInfo["authorizedScope"] == SCOPE_APP && + HaveSameTokenId(context, credInfo["authorizedAppList"]) == true) { + return DM_POINT_TO_POINT; + } + } + + // 未确定凭据类型 + return DM_INVALIED_BINDTYPE; +} + +// 比较ACL四元组:双端的deviceId和userId +bool AuthSinkNegotiateStateMachine::AclCompareTwoIds(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + // TODO: 需确定deviceId、userId哈希值的截断位数是多少 + return Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash && + Crypto::Sha256(std::to_string(accesser.GetAccesserUserId())) == context->accesser.userIdHash && + accessee.GetAccesseeDeviceId() == context->accessee.deviceId && + accessee.GetAccesseeUserId() == context->accessee.userId; +} + +// 比较ACL八元组:四元组加双端的accountId和tokenId +bool AuthSinkNegotiateStateMachine::AclCompareFourIds(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + return AclCompareTwoIds(context, accesser, accessee) && + // TODO: 需确定deviceId、userId哈希值的截断位数是多少 + Crypto::Sha256(accesser.GetAccesserAccountId()) == context->accesser.accountIdHash && + Crypto::Sha256(std::to_string(accesser.GetAccesserTokenId())) == context->accesser.tokenIdHash && + accessee.GetAccesseeAccountId() == context->accessee.accountId && + accessee.GetAccesseeTokenId() == static_cast(context->accessee.tokenId); +} + +/** + 有无凭据确认逻辑:以ACL的credId为索引,在凭据列表中寻找凭据,若没找到则认为无对应凭据 + - 由于获取凭据时没有对端信息,无法基于对端信息查询凭据,只能通过ACL确认 + 凭据类型获取逻辑:GetCredentialType + + 问题: + 1. 无法确定有凭据无ACL的场景(因为需要基于ACL的ids与凭据匹配,匹配不上的则无信息) + */ +int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptr context) +{ + int32_t ret; + nlohmann::json queryParams; + nlohmann::json queryResult; + + // 1. 获取所有凭据 + queryParams["deviceIdHash"] = context->accesser.deviceIdHash; + queryParams["userIdHash"] = context->accesser.userIdHash; + // 2/27会上讨论,以下字段不需要传输,只传id相关即可 + // queryParams["subject"] = 2; // 2: 配件 + // queryParams["keyFormat"] = 2; // 2: 非对称密钥公钥 + // queryParams["algorithmType"] = 4; // 4- ED25519 + // queryParams["proofType"] = 1; // 1: PSK + // queryParams["credentialOwner"] = "DM"; + ret = context->hiChainAuthConnector->QueryCredentialInfo(context->accessee.userId, queryParams, queryResult); + if (ret != DM_OK) { + LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to query credential id list."); + context->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + return ret; + } + + // 2. 获取所有ACL + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAccessControlProfile(); + bool isAclActive = false; + for (auto &item : profiles) { + auto accesser = item.GetAccesser(); + auto accessee = item.GetAccessee(); + + // 确保凭据能跟ACL对应上。 + std::string credId = std::to_string(accessee.GetAccesseeCredentialId()); + if (queryResult.find(credId) == queryResult.end() || item.GetStatus() != ACTIVE) { + continue; + } + + // 确认凭据类型 + int32_t credType = GetCredentialType(context, queryResult[credId]); + if (credType == DM_INVALIED_BINDTYPE) { + continue; + } + queryResult[credId]["credType"] = credType; + + // 确认是否有可信关系 + if (credType == DM_IDENTICAL_ACCOUNT || credType == DM_ACROSS_ACCOUNT) { + queryResult[credId]["isAclActive"] = AclCompareTwoIds(context, accesser, accessee); + } else if (credType == DM_POINT_TO_POINT) { + queryResult[credId]["isAclActive"] = AclCompareFourIds(context, accesser, accessee); + } + } + + // 3. 筛选凭据 + std::vector invalidCredIds; + for (auto& [key, value] : queryResult.items()) { + if (value.find("isAclActive") == value.end() || value["isAclActive"] == false) { + invalidCredIds.push_back(key); + } + } + + return DM_OK; +} + +int32_t AuthSinkNegotiateStateMachine::ProcRespNegotiate5_1_0(std::shared_ptr context) +{ + // 获取accesee四元组:uid、userId、accountId、tokenId + int32_t ret = RespQueryAcceseeIds(context); + if (ret != DM_OK) { + LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to get tokenId."); + context->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + return ERR_DM_FAILED; + } + + // 检查accesser_deviceId是否上线 + // Q: 80报文未传输accesser.deviceId,无法校验是否上线 + // context->accesser.isOnline = context->softbusConnector->CheckIsOnline(context->accesser.deviceId); + + // 获取凭据信息 + ret = GetAuthCredentialInfo(context); + if (ret != DM_OK) { + LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to get credential."); + context->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + return ERR_DM_FAILED; + } + + // 状态跳转在100报文中处理 + return DM_OK; +} + +int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr context) +{ + LOGI("AuthSinkNegotiateStateMachine::Action sessionid %{public}d", context->sessionId); + + // 1. 停止定时器 + if (context->timer != nullptr) { + context->timer->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); + } + + // 2. 获取deviceName和udid + context->accessee.deviceName = context->softbusConnector->GetLocalDeviceName(); + char localDeviceId[DEVICE_UUID_LENGTH]; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + context->accessee.deviceId = static_cast(localDeviceId); + + // 解析message时,accesser.deviceId已赋值 + // remoteDeviceId_ = authResponseContext_->localDeviceId; + context->accessee.networkId = context->softbusConnector->GetLocalDeviceNetworkId(); + context->accessee.deviceName = context->softbusConnector->GetLocalDeviceName(); + if (CompareVersion(context->accesser.dmVersion, std::string(DM_VERSION_5_1_0)) == false) { + LOGE("AuthSinkNegotiateStateMachine::Action incompatible version compare to 5.1.0"); + return ERR_DM_VERSION_INCOMPATIBLE; + } + + int32_t ret = ProcRespNegotiate5_1_0(context); + if (ret != DM_OK) { + LOGE("AuthSinkNegotiateStateMachine::Action proc response negotiate failed"); + return ret; + } + context->timer->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this, context] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context, name); + }); + return DM_OK; +} + /* 能力协商(80和90报文处理) source端状态: diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index ac23b00ca..737f86175 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -13,6 +13,8 @@ * limitations under the License. */ +#include "dm_anonymous.h" +#include "dm_auth_context.h" #include "dm_auth_message_processor.h" #include "dm_auth_context.h" #include "dm_auth_state_machine.h" @@ -238,6 +240,61 @@ void DmAuthMessageProcessor::CreateMessageReqCredAuthStart(std::shared_ptr context, nlohmann::json &jsonObject) +{ + // 目前未看到使用了cryptoAdapter_,删除 + jsonObject[TAG_DEVICE_VERSION] = context->accesser.dmVersion; + jsonObject[TAG_DEVICE_NAME] = context->accesser.deviceName; + + jsonObject[TAG_DEVICE_ID_HASH] = context->accesser.deviceIdHash; + jsonObject[TAG_USER_ID_HASH] = context->accesser.userIdHash; + jsonObject[TAG_ACCOUNT_ID_HASH] = context->accesser.accountIdHash; + jsonObject[TAG_TOKEN_ID_HASH] = context->accesser.tokenIdHash; + + jsonObject[TAG_BUNDLE_NAME] = context->accesser.bundleName; + jsonObject[TAG_PEER_BUNDLE_NAME] = context->accessee.bundleName; + jsonObject[TAG_BIND_LEVEL] = context->accesser.bindLevel; + // 暂无serviceId的定义 + // tokenId、deviceId是否有安全问题?暂未传输 + + return; +} + +void DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject, std::shared_ptr context) +{ + if (IsString(jsonObject, TAG_DEVICE_VERSION)) { + context->accesser.dmVersion = jsonObject[TAG_DEVICE_VERSION].get(); + } + if (IsString(jsonObject, TAG_DEVICE_NAME)) { + context->accesser.deviceName = jsonObject[TAG_DEVICE_NAME].get(); + } + + if (IsString(jsonObject, TAG_DEVICE_ID_HASH)) { + context->accesser.deviceIdHash = jsonObject[TAG_DEVICE_ID_HASH].get(); + } + if (IsString(jsonObject, TAG_USER_ID_HASH)) { + context->accesser.userIdHash = jsonObject[TAG_USER_ID_HASH].get(); + } + if (IsString(jsonObject, TAG_ACCOUNT_ID_HASH)) { + context->accesser.accountIdHash = jsonObject[TAG_ACCOUNT_ID_HASH].get(); + } + if (IsString(jsonObject, TAG_TOKEN_ID_HASH)) { + context->accesser.tokenIdHash = jsonObject[TAG_TOKEN_ID_HASH].get(); + } + + if (IsString(jsonObject, TAG_BUNDLE_NAME)) { + context->accesser.bundleName = jsonObject[TAG_BUNDLE_NAME].get(); + } + if (IsString(jsonObject, TAG_PEER_BUNDLE_NAME)) { + context->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].get(); + } + if (IsInt32(jsonObject, TAG_BIND_LEVEL)) { + context->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].get(); + } + + return; +} int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const nlohmann::json &json, std::shared_ptr context) diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index a1dc8fd31..c6aadf4c1 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -27,6 +27,41 @@ namespace OHOS { namespace DistributedHardware { +namespace { + +const int32_t CLONE_AUTHENTICATE_TIMEOUT = 20; +const int32_t CLONE_NEGOTIATE_TIMEOUT = 10; +const int32_t CLONE_CONFIRM_TIMEOUT = 10; +const int32_t CLONE_ADD_TIMEOUT = 10; +const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10; +const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10; +const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20; + +} + +// clone task timeout map +const std::map TASK_TIME_OUT_MAP = { + { std::string(AUTHENTICATE_TIMEOUT_TASK), CLONE_AUTHENTICATE_TIMEOUT }, + { std::string(NEGOTIATE_TIMEOUT_TASK), CLONE_NEGOTIATE_TIMEOUT }, + { std::string(CONFIRM_TIMEOUT_TASK), CLONE_CONFIRM_TIMEOUT }, + { std::string(ADD_TIMEOUT_TASK), CLONE_ADD_TIMEOUT }, + { std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), CLONE_WAIT_NEGOTIATE_TIMEOUT }, + { std::string(WAIT_REQUEST_TIMEOUT_TASK), CLONE_WAIT_REQUEST_TIMEOUT }, + { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT } +}; + +int32_t DmAuthState::GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut) +{ + LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, acontext->uthType); + if (context->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { + auto timeout = TASK_TIME_OUT_MAP.find(std::string(taskName)); + if (timeout != TASK_TIME_OUT_MAP.end()) { + return timeout->second; + } + } + return taskTimeOut; +} + void DmAuthState::HandleAuthenticateTimeout(std::shared_ptr context, std::string name) { LOGI("DmAuthContext::HandleAuthenticateTimeout start timer name %{public}s", name.c_str()); diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index b9d6a5e25..ce4ae13c8 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -326,6 +326,54 @@ int32_t HiChainAuthConnector::GenerateCredential(std::string &localUdid, int32_t return DM_OK; } +int32_t HiChainAuthConnector::QueryCredentialInfo(int32_t userId, nlohmann::json queryParams, + nlohmann::json &resultJson) +{ + int32_t ret; + + const CredManager *cm = GetCredMgrInstance(); + char *credIdList = nullptr; + // Q: 之前都是用的ProcessCredential查询,现在是否可用queryCredentialByParams查询? + ret = cm->queryCredentialByParams(userId, SafetyDump(queryParams).c_str(), + &credIdList); + if (ret != DM_OK) { + LOGE("HiChainAuthConnector::QueryCredentialInfo fail to query credential id list."); + return ERR_DM_FAILED; + } + nlohmann::json credIdListJson = nlohmann::json::parse(credIdList, nullptr, false); + FreeJsonString(credIdList); + if (credIdListJson.is_discarded()) { + LOGE("HiChainAuthConnector::QueryCredentialInfo credential id list to jsonStr error"); + return ERR_DM_FAILED; + } + + std::set credBindTypes; + for (const auto& element : credIdListJson) { + if (!element.is_string()) { + continue; + } + std::string credId = element.get(); + + char *returnCredInfo = nullptr; + ret = cm->queryCredInfoByCredId(userId, credId.c_str(), &returnCredInfo); + if (ret != DM_OK) { + LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to query credential info."); + context->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + return ERR_DM_FAILED; + } + nlohmann::json credInfoJson = nlohmann::json::parse(returnCredInfo, nullptr, false); + FreeJsonString(returnCredInfo); + if (credInfoJson.is_discarded()) { + LOGE("DmAuthManager::ProcRespNegotiate5_1_0 credential info jsonStr error"); + return ERR_DM_FAILED; + } + + resultJson[credId] = credInfoJson; + } + + return DM_OK; +} + bool HiChainAuthConnector::QueryCredential(std::string &localUdid, int32_t osAccountId) { LOGI("HiChainAuthConnector::QueryCredential start."); -- Gitee From e1009d880000ec055c2254e3c87d02f519897ee7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E8=B0=A2=E4=BC=9F?= <2247596987@qq.com> Date: Fri, 28 Feb 2025 06:24:16 +0000 Subject: [PATCH 013/382] =?UTF-8?q?fix=EF=BC=9A140-150=E6=8A=A5=E6=96=87?= =?UTF-8?q?=E5=8A=A0=E5=AF=86=E4=BC=A0=E8=BE=93=E6=9C=AC=E7=AB=AF=E8=AE=BE?= =?UTF-8?q?=E5=A4=87id=EF=BC=8C=E7=94=A8=E6=88=B7id=EF=BC=8Ctokenid?= =?UTF-8?q?=E7=BB=99=E8=BF=9C=E7=AB=AF=20140-150=E6=8A=A5=E6=96=87?= =?UTF-8?q?=E5=8A=A0=E5=AF=86=E4=BC=A0=E8=BE=93=E6=9C=AC=E7=AB=AF=E8=AE=BE?= =?UTF-8?q?=E5=A4=87id=EF=BC=8C=E7=94=A8=E6=88=B7id=EF=BC=8Ctokenid?= =?UTF-8?q?=E7=BB=99=E8=BF=9C=E7=AB=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication_v2/dm_auth_context.h | 2 ++ .../dm_auth_message_processor.h | 1 + .../include/authentication_v2/dm_auth_state.h | 12 +++---- .../auth_stages/auth_credential.cpp | 4 ++- .../src/authentication_v2/dm_auth_context.cpp | 10 ++++++ .../dm_auth_message_processor.cpp | 35 ++++++++++++++----- 6 files changed, 49 insertions(+), 15 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index b3942cb08..20a778a6b 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -179,6 +179,8 @@ struct DmAuthContext { // 获取设备ID std::string GetDeviceId(DmAuthSide side); + // 获取用户ID + int32_t GetUserId(DmAuthSide side); // 获取凭据ID std::string GetCredentialId(DmAuthSide side, DmAuthScope authorizedScope); // 获取公钥 diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index a8fb4213d..6b3aabf89 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -47,6 +47,7 @@ constexpr const char *DM_TAG_AUTHORIZED_SCOPE = "authorizedScope"; constexpr const char *DM_TAG_AUTHRIZED_APP_LIST = "authorizedAppList"; constexpr const char *DM_TAG_CREDENTIAL_OWNER = "credentialOwner"; constexpr const char *DM_AUTH_CREDENTIAL_OWNER = "DM"; // 凭据拥有者 +constexpr const char *DM_TAG_TOKEN_ID = "tokenId"; constexpr const char* APP_OPERATION_KEY = "appOperation"; constexpr const char* APP_THUMBNAIL = "appThumbnail"; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 711948c19..a282d4f02 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -60,25 +60,25 @@ enum class DmAuthStateType { }; // 凭据添加方式 -enum DmAuthCredentialAddMethod { +enum DmAuthCredentialAddMethod : uint8_t { DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE = 1, // 生成 DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT, // 导入 }; // 凭据主体 -enum DmAuthCredentialSubject { +enum DmAuthCredentialSubject : uint8_t { DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY = 1, // 主控 DM_AUTH_CREDENTIAL_SUBJECT_SUPPLEMENT, // 配件 }; // 凭据与账号关联 -enum DmAuthCredentialAccountRelation { +enum DmAuthCredentialAccountRelation : uint8_t { DM_AUTH_CREDENTIAL_ACCOUNT_RELATED = 1, // 账号相关 DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED, // 账号无关 }; // 秘钥类型 -enum DmAuthKeyFormat { +enum DmAuthKeyFormat : uint8_t { DM_AUTH_KEY_FORMAT_SYMM_IMPORT = 1, // 对称密钥(仅在导入下支持) DM_AUTH_KEY_FORMAT_ASYMM_IMPORT, // 非对称密钥公钥(仅在导入下支持) DM_AUTH_KEY_FORMAT_ASYMM_GENERATE, // 非对称密钥(仅在生成下支持) @@ -86,7 +86,7 @@ enum DmAuthKeyFormat { }; // 算法类型 -enum DmAuthAlgorithmType { +enum DmAuthAlgorithmType : uint8_t { DM_AUTH_ALG_TYPE_AES256 = 1, // AES256 DM_AUTH_ALG_TYPE_AES128, // AES128 DM_AUTH_ALG_TYPE_P256, // P256 @@ -94,7 +94,7 @@ enum DmAuthAlgorithmType { }; // 凭据证明类型 -enum DmAuthCredentialProofType { +enum DmAuthCredentialProofType : uint8_t { DM_AUTH_CREDENTIAL_PROOF_PSK = 1, // PSK DM_AUTH_CREDENTIAL_PROOF_PKI, // PKI }; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 1f8488d04..1096820f6 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -63,7 +63,9 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori jsonObj[DM_TAG_METHOD] = method; // 凭据生成方式 jsonObj[DM_TAG_DEVICE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? // 设备ID 生成是本端,导入是对端 authContext->GetDeviceId(DM_AUTH_LOCAL_SIDE) : authContext->GetDeviceId(DM_AUTH_REMOTE_SIDE); - jsonObj[DM_TAG_PEER_USER_SPACE_ID] = std::to_string(-1); // -1 非法值 + if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) { + jsonObj[DM_TAG_PEER_USER_SPACE_ID] = authContext->GetDeviceId(DM_AUTH_REMOTE_SIDE); // 对端userId + } jsonObj[DM_TAG_SUBJECT] = DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY; // 主控设备 jsonObj[DM_TAG_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; // 账号无关 jsonObj[DM_TAG_KEY_FORMAT] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? diff --git a/services/implementation/src/authentication_v2/dm_auth_context.cpp b/services/implementation/src/authentication_v2/dm_auth_context.cpp index 1446b268f..58f7a24b3 100644 --- a/services/implementation/src/authentication_v2/dm_auth_context.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_context.cpp @@ -30,6 +30,16 @@ std::string DmAuthContext::GetDeviceId(DmAuthSide side) } } +// 获取用户ID +int32_t DmAuthContext::GetUserId(DmAuthSide side) +{ + if (side == DM_AUTH_LOCAL_SIDE) { + return (direction == DM_AUTH_SOURCE) ? accesser.userId : accessee.userId; + } else { + return (direction == DM_AUTH_SOURCE) ? accessee.userId : accesser.userId; + } +} + // 获取凭据ID std::string DmAuthContext::GetCredentialId(DmAuthSide side, DmAuthScope authorizedScope) { diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 737f86175..726031c5e 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -106,12 +106,17 @@ int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const nlohmann::json context->accesser.userPublicKey = jsonData[DM_TAG_USER_PUBLICK_KEY].get(); } - // 解析应用级公钥 - if (!IsString(jsonData, DM_TAG_APP_PUBLICK_KEY)) { - LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange() error, no appPublicKey."); + if (!IsString(jsonData, DM_TAG_APP_PUBLICK_KEY) || + !IsString(jsonData, DM_TAG_DEVICE_ID) || + !IsInt32(jsonData, DM_TAG_PEER_USER_SPACE_ID) || + !IsInt64(jsonData, DM_TAG_TOKEN_ID)) { + LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange, MSG_TYPE_REQ_CREDENTIAL_EXCHANGE message error."); return ERR_DM_FAILED; } - context->accesser.appPublicKey = jsonData[DM_TAG_APP_PUBLICK_KEY].get(); + context->accesser.appPublicKey = jsonData[DM_TAG_APP_PUBLICK_KEY].get(); // 解析应用级公钥 + context->accesser.deviceId = jsonData[DM_TAG_DEVICE_ID].get(); // 解析deviceId + context->accesser.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].get(); // 解析userId + context->accesser.tokenId = jsonData[DM_TAG_TOKEN_ID].get(); // 解析tokenId return DM_OK; } @@ -145,12 +150,20 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const nlohmann::json } // 解析对方应用级公钥和协商应用级凭据Id - if (!IsString(jsonData, DM_TAG_APP_PUBLICK_KEY) || !IsString(jsonData, DM_TAG_APP_CREDENTIAL_ID)) { - LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange failed, no appPublicKey or appCredentialId."); + if (!IsString(jsonData, DM_TAG_APP_PUBLICK_KEY) || + !IsString(jsonData, DM_TAG_APP_CREDENTIAL_ID) || + !IsString(jsonData, DM_TAG_DEVICE_ID) || + !IsInt32(jsonData, DM_TAG_PEER_USER_SPACE_ID) || + !IsInt64(jsonData, DM_TAG_TOKEN_ID)) { + LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange failed, decode MSG_TYPE_RESP_CREDENTIAL_EXCHANGE " + "message error."); return ERR_DM_FAILED; } context->accessee.appPublicKey = jsonData[DM_TAG_APP_PUBLICK_KEY].get(); context->accessee.appCredentialId = jsonData[DM_TAG_APP_CREDENTIAL_ID].get(); + context->accessee.deviceId = jsonData[DM_TAG_DEVICE_ID].get(); // 解析deviceId + context->accessee.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].get(); // 解析userId + context->accessee.tokenId = jsonData[DM_TAG_TOKEN_ID].get(); // 解析tokenId return DM_OK; } @@ -187,6 +200,9 @@ void DmAuthMessageProcessor::CreateMessageReqCredExchange(std::shared_ptraccesser.userPublicKey; } jsonData[DM_TAG_APP_PUBLICK_KEY] = context->accesser.appPublicKey; + jsonData[DM_TAG_DEVICE_ID] = context->accesser.deviceId; + jsonData[DM_TAG_PEER_USER_SPACE_ID] = context->accesser.userId; + jsonData[DM_TAG_TOKEN_ID] = context->accesser.tokenId; std::string plainText = SafetyDump(jsonData); std::string cipherText; @@ -203,8 +219,11 @@ void DmAuthMessageProcessor::CreateMessageRspCredExchange(std::shared_ptraccessee.userPublicKey; jsonData[DM_TAG_USER_CREDENTIAL_ID] = context->accessee.userCredentialId; } - jsonData[DM_TAG_APP_PUBLICK_KEY] = context->accessee.appPublicKey; - jsonData[DM_TAG_APP_CREDENTIAL_ID] = context->accessee.appCredentialId; + jsonData[DM_TAG_APP_PUBLICK_KEY] = context->accessee.appPublicKey; // 本端应用级公钥 + jsonData[DM_TAG_APP_CREDENTIAL_ID] = context->accessee.appCredentialId; // 本端应用级凭据Id + jsonData[DM_TAG_DEVICE_ID] = context->accessee.deviceId; // 本端deviceId + jsonData[DM_TAG_PEER_USER_SPACE_ID] = context->accessee.userId; // 本端userId + jsonData[DM_TAG_TOKEN_ID] = context->accessee.tokenId; // 本端tokenId std::string plainText = SafetyDump(jsonData); std::string cipherText; -- Gitee From fdb3ad8cc7efd46ac943308d0baaa84f5a903e47 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 27 Feb 2025 20:26:35 +0800 Subject: [PATCH 014/382] tmp commit --- .../auth_stages/auth_confirm.cpp | 54 ++++++++++-- .../auth_stages/auth_pin_auth.cpp | 7 +- .../dm_auth_message_processor.cpp | 87 ++++++++++++++++--- 3 files changed, 129 insertions(+), 19 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index de29f1f18..8930fd528 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -33,6 +33,8 @@ constexpr const char* TAG_LOCAL_DEVICE_TYPE = "LOCALDEVICETYPE"; constexpr const char* TAG_REQUESTER = "REQUESTER"; constexpr const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; +std::set g_shareByPinAuthDeviceTypeSet{DmDeviceType::DEVICE_TYPE_SMART_DISPLAY}; + /* 用户授权(100和110报文处理) source端状态: @@ -50,6 +52,36 @@ DmAuthStateType AuthSrcConfirmState::GetStateType() int32_t AuthSrcConfirmState::Action(std::shared_ptr context) { LOGI("AuthSrcConfirmState::Action start"); +#if 0 + // 转结束绑定 + + // 转凭据认证 + + // 有无可信关系的分享凭据 + if (g_shareByPinAuthDeviceTypeSet.contains(static_cast(context->deviceType))) { + // 走弹PIN + context->authType = DmAuthType::AUTH_TYPE_PIN_SHOW; + // send 100 + } else { + // 转凭据认证 + } + + // 有点对点可信 + if (context->authType == DmAuthType::AUTH_TYPE_PIN_IMPORT) { + // 走PIN码导入 + // send 100 + } else { + // 结束绑定 + } +#endif + // 无凭据 + // send 100 + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_USER_CONFIRM, context); + + context->timer->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), + CONFIRM_TIMEOUT, [context] (std::string name) { + AuthSinkStatePinAuthComm::HandleSessionHeartbeat(context, name); + }); LOGI("AuthSrcConfirmState::Action ok"); return DM_OK; @@ -93,7 +125,10 @@ int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context context->accessee.userId, context->accessee.tokenId, context->accessee.serviceId); if (DeviceProfileConnector::GetInstance().GetServiceInfoProfileListByTokenId(key, serviceInfos) != DM_OK) { // 获取不到走PIN认证方案 - context->authType = DmAuthType::AUTH_TYPE_PIN_SHOW; + if (context->authType != DmAuthType::AUTH_TYPE_PIN_SHOW) { + LOGE("AuthSinkConfirmState::GetAuthType AUTH_TYPE_PIN_SHOW not match"); + return STOP_BIND; + } return DM_OK; } @@ -119,8 +154,11 @@ int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context auto authBoxType = srvInfo.GetAuthBoxType(); int32_t pinExchangeType = srvInfo.GetPinExchangeType(); - if (authBoxType == DistributedDeviceProfile::NUM_1) { - context->authType = DmAuthType::AUTH_TYPE_PIN_SHOW; // 三态框 + if (authBoxType == DistributedDeviceProfile::NUM_1) { // 三态框 + if (context->authType != DmAuthType::AUTH_TYPE_PIN_SHOW) { + LOGE("AuthSinkConfirmState::GetAuthType AUTH_TYPE_PIN_SHOW not match"); + return STOP_BIND; + } return DM_OK; } else if (authBoxType == DistributedDeviceProfile::NUM_2) { int32_t authResult = srvInfo.GetAuthType(); @@ -133,10 +171,16 @@ int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context } if (pinExchangeType == DistributedDeviceProfile::NUM_2) { // 超声交换PIN - context->authType = DmAuthType::AUTH_TYPE_PIN_ULTRASONIC; + if (context->authType != DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { + LOGE("AuthSinkConfirmState::GetAuthType AUTH_TYPE_PIN_ULTRASONIC not match"); + return STOP_BIND; + } return DM_OK; } else if (pinExchangeType == DistributedDeviceProfile::NUM_3) { // 导入PIN - context->authType = DmAuthType::AUTH_TYPE_PIN_IMPORT; + if (context->authType != DmAuthType::AUTH_TYPE_PIN_IMPORT) { + LOGE("AuthSinkConfirmState::GetAuthType AUTH_TYPE_PIN_IMPORT not match"); + return STOP_BIND; + } // 读取PIN码 std::string pinCode = srvInfo.GetPinCode(); context->pinCode = std::stoi(pinCode); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 113a129cc..5c1c003b5 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -180,8 +180,11 @@ int32_t AuthSrcPinAuthStartState::GetPinCode(std::shared_ptr cont int32_t AuthSrcPinAuthStartState::AuthDevice(std::shared_ptr context) { int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); - auto ret = context->hiChainAuthConnector->AuthDevice(context->pinCode, osAccountId, - context->accessee.deviceId, context->requestId); + + std::string credId; // leave empty for pin auth + std::string pinCode = std::to_string(context->pinCode); + auto ret = context->hiChainAuthConnector->AuthCredential(osAccountId, context->requestId, credId, pinCode); + if (ret != DM_OK) { LOGE("AuthSrcPinAuthStartState::AuthDevice failed."); return ret; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 737f86175..c59a4f251 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -24,6 +24,7 @@ namespace DistributedHardware { constexpr const char* TAG_REPLY = "reply"; constexpr const char* TAG_DATA = "data"; +constexpr const char* TAG_DEVICE_TYPE = "deviceType"; // 保存秘钥 int32_t DmAuthMessageProcessor::SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyLen) @@ -55,6 +56,18 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont context->msgType = msgType; LOGI("DmAuthMessageProcessor::ParseMessage message type %{public}d", context->msgType); switch (msgType) { + case MSG_TYPE_RESP_ACL_NEGOTIATE: + return ParseMessageRespAclNegotiate(jsonObject, context); + case MSG_TYPE_REQ_USER_CONFIRM: + return ParseMessageReqUserConfirm(jsonObject, context); + case MSG_TYPE_RESP_USER_CONFIRM: + return ParseMessageRespUserConfirm(jsonObject, context); + case MSG_TYPE_REQ_PIN_AUTH_START: + return ParseMessageReqPinAuthStart(jsonObject, context); + case MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE: + return ParseMessageReqPinAuthNegotiate(jsonObject, context); + case MSG_TYPE_RESP_PIN_AUTH_START: + return ParseMessageRespPinAuthStart(jsonObject, context); case MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE: return ParseMessageOnTransmit(jsonObject, context); case MSG_TYPE_REQ_CREDENTIAL_EXCHANGE: @@ -161,6 +174,24 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = msgType; switch (msgType) { + case MSG_TYPE_REQ_USER_CONFIRM: + CreateMessageReqUserConfirm(context, jsonObj); + break; + case MSG_TYPE_RESP_USER_CONFIRM: + CreateMessageRespUserConfirm(context, jsonObj); + break; + case MSG_TYPE_REQ_PIN_AUTH_START: + CreateMessageReqPinAuthStart(context, jsonObj); + break; + case MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE: + CreateMessageReqPinAuthNegotiate(context, jsonObj); + break; + case MSG_TYPE_RESP_PIN_AUTH_START: + CreateMessageRespPinAuthStart(context, jsonObj); + break; + case MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE: + CreateMessageRespPinAuthNegotiate(context, jsonObj); + break; case MSG_TYPE_REQ_CREDENTIAL_EXCHANGE: CreateMessageReqCredExchange(context, jsonObj); break; @@ -305,17 +336,40 @@ int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const nlohmann::jso int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const nlohmann::json &json, std::shared_ptr context) { - // todo + if (IsInt32(json, TAG_AUTH_TYPE)) { + context->authType = static_cast(json[TAG_AUTH_TYPE].get()); + } + + if (IsString(json, APP_OPERATION_KEY)) { + context->appOperation = json[APP_OPERATION_KEY].get(); + } + if (IsString(json, CUSTOM_DESCRIPTION_KEY)) { + context->customData = json[CUSTOM_DESCRIPTION_KEY].get(); + } + if (IsInt32(json, TAG_DEVICE_TYPE)) { + context->accesser.deviceType = json[TAG_AUTH_TYPE].get(); + } + if (IsString(json, TAG_DEVICE_NAME)) { + context->accesser.deviceName = json[TAG_DEVICE_NAME].get(); + } + if (IsString(json, TAG_PKG_NAME)) { + context->pkgName = json[TAG_PKG_NAME].get(); + } + if (IsString(json, APP_THUMBNAIL)) { + context->appThumbnail = json[APP_THUMBNAIL].get(); + } + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const nlohmann::json &json, std::shared_ptr context) { - context->authType = static_cast(json[TAG_AUTH_TYPE].get()); - context->requestId = json[TAG_REQUEST_ID].get(); - if (context->authType == DmAuthType::AUTH_TYPE_PIN_SHOW) { - context->reply = json[TAG_REPLY].get(); + if (IsInt32(json, TAG_AUTH_TYPE)) { + context->authType = static_cast(json[TAG_AUTH_TYPE].get()); + } + if (IsInt64(json, TAG_REQUEST_ID)) { + context->requestId = json[TAG_REQUEST_ID].get(); } context->authStateMachine->TransitionTo(std::make_shared()); @@ -324,37 +378,46 @@ int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const nlohmann::json int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const nlohmann::json &json, std::shared_ptr context) { - context->transmitData = json[TAG_DATA].get(); + if (IsString(json, TAG_DATA)) { + context->transmitData = json[TAG_DATA].get(); + } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthStart(const nlohmann::json &json, std::shared_ptr context) { - context->transmitData = json[TAG_DATA].get(); + if (IsString(json, TAG_DATA)) { + context->transmitData = json[TAG_DATA].get(); + } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate(const nlohmann::json &json, std::shared_ptr context) { - context->transmitData = json[TAG_DATA].get(); + if (IsString(json, TAG_DATA)) { + context->transmitData = json[TAG_DATA].get(); + } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } void DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, nlohmann::json &json) { - // todo + json[TAG_AUTH_TYPE] = context->authType; + json[APP_OPERATION_KEY] = context->appOperation; + json[CUSTOM_DESCRIPTION_KEY] = context->customData; + json[TAG_DEVICE_TYPE] = context->accesser.deviceType; + json[TAG_DEVICE_NAME] = context->accesser.deviceName; + json[TAG_PKG_NAME] = context->pkgName; + json[APP_THUMBNAIL] = context->appThumbnail; } void DmAuthMessageProcessor::CreateMessageRespUserConfirm(std::shared_ptr context, nlohmann::json &json) { json[TAG_AUTH_TYPE] = context->authType; json[TAG_REQUEST_ID] = context->requestId; - if (context->authType == DmAuthType::AUTH_TYPE_PIN_SHOW) { - json[TAG_REPLY] = context->reply; - } } void DmAuthMessageProcessor::CreateMessageReqPinAuthStart(std::shared_ptr context, nlohmann::json &json) -- Gitee From e7b9aa3cedc7ca8ab9c206848faaecd9fea1f525 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Feb 2025 15:45:25 +0800 Subject: [PATCH 015/382] new auth manager --- .../include/authentication_v2/auth_manager.h | 3 +- .../include/device_manager_service_impl.h | 2 + .../src/device_manager_service_impl.cpp | 44 ++++++++++++++++--- 3 files changed, 41 insertions(+), 8 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 2b14619d5..f0be2be2f 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -36,10 +36,11 @@ const int32_t HML_SESSION_TIMEOUT = 10; const int32_t AUTHENTICATE_TIMEOUT = 120; constexpr const char* DM_VERSION_5_1_0 = "5.1.0"; // TODO: 黄蓝区同步,部分代码冲突,冲突时删除此处 +#if 0 constexpr const char* PARAM_KEY_HML_ENABLE_160M = "hmlEnable160M"; constexpr const char* PARAM_KEY_HML_ACTIONID = "hmlActionId"; constexpr const char* PARAM_KEY_CONN_SESSIONTYPE = "connSessionType"; - +#endif constexpr const char* BUNDLE_NAME_KEY = "bundleName"; // 取自security_device_auth中的identity_operation.h,该头文件为内部头文件,不能直接引用 diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 55e5426b0..a63a51b03 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -31,6 +31,7 @@ #include "dm_single_instance.h" #include "softbus_connector.h" #include "mine_hichain_connector.h" +#include "auth_manager.h" namespace OHOS { namespace DistributedHardware { @@ -154,6 +155,7 @@ private: void HandleUserRemoved(int32_t preUserId); void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid); DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); + int32_t InitAndRegisterAuthMgr(bool isSrcSide); private: std::shared_ptr authMgr_; diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 0a0898740..f69478813 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -44,6 +44,26 @@ DeviceManagerServiceImpl::~DeviceManagerServiceImpl() { LOGI("DeviceManagerServiceImpl destructor"); } +int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide) +{ + if (authMgr_ == nullptr) { + if (isSrcSide) { + authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, listener_, + hiChainAuthConnector_); + } else { + authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, listener_, + hiChainAuthConnector_); + } + softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); + hiChainConnector_->RegisterHiChainCallback(authMgr_); + hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); + } else { + // 线程已创建authMgr_,说明已有绑定事件,其他请求拒绝,返回错误码 + LOGE("BindTarget failed, this device is being bound. Please try again later."); + return ERR_DM_AUTH_BUSINESS_BUSY; + } + return DM_OK; +} int32_t DeviceManagerServiceImpl::Initialize(const std::shared_ptr &listener) { @@ -65,13 +85,13 @@ int32_t DeviceManagerServiceImpl::Initialize(const std::shared_ptrRegisterSoftbusStateCallback(); } - if (authMgr_ == nullptr) { - authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, listener, - hiChainAuthConnector_); - softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); - hiChainConnector_->RegisterHiChainCallback(authMgr_); - hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); - } + // if (authMgr_ == nullptr) { + // authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, listener, + // hiChainAuthConnector_); + // softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); + // hiChainConnector_->RegisterHiChainCallback(authMgr_); + // hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); + // } if (credentialMgr_ == nullptr) { credentialMgr_ = std::make_shared(hiChainConnector_, listener); } @@ -298,6 +318,11 @@ std::string DeviceManagerServiceImpl::GetUdidHashByNetworkId(const std::string & int DeviceManagerServiceImpl::OnSessionOpened(int sessionId, int result) { + // sink端绑定对象初始化与方法注册 + int32_t ret = InitAndRegisterAuthMgr(false); + if (ret != DM_OK) { + return ret; + } std::string peerUdid = ""; softbusConnector_->GetSoftbusSession()->GetPeerDeviceId(sessionId, peerUdid); struct RadarInfo info = { @@ -583,6 +608,11 @@ int32_t DeviceManagerServiceImpl::ExportAuthCode(std::string &authCode) int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, const std::map &bindParam) { + // source端绑定对象初始化与方法注册 + int32_t ret = InitAndRegisterAuthMgr(true); + if (ret != DM_OK) { + return ret; + } if (pkgName.empty()) { LOGE("BindTarget failed, pkgName is empty"); return ERR_DM_INPUT_PARA_INVALID; -- Gitee From f4a64e798e9acaf601e762e7a3eb20d89c653a5a Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Feb 2025 15:59:21 +0800 Subject: [PATCH 016/382] tmp --- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 2 +- .../implementation/src/authentication_v2/dm_auth_state.cpp | 2 +- .../src/dependency/hichain/hichain_auth_connector.cpp | 6 ++---- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 8930fd528..1486b2a00 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -80,7 +80,7 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) context->timer->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), CONFIRM_TIMEOUT, [context] (std::string name) { - AuthSinkStatePinAuthComm::HandleSessionHeartbeat(context, name); + AuthSinkStatePinAuthComm::HandleAuthenticateTimeout(context, name); }); LOGI("AuthSrcConfirmState::Action ok"); diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index c6aadf4c1..424dd1a37 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -52,7 +52,7 @@ const std::map TASK_TIME_OUT_MAP = { int32_t DmAuthState::GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut) { - LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, acontext->uthType); + LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, context->authType); if (context->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { auto timeout = TASK_TIME_OUT_MAP.find(std::string(taskName)); if (timeout != TASK_TIME_OUT_MAP.end()) { diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index ce4ae13c8..f212f645a 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -347,7 +347,6 @@ int32_t HiChainAuthConnector::QueryCredentialInfo(int32_t userId, nlohmann::json return ERR_DM_FAILED; } - std::set credBindTypes; for (const auto& element : credIdListJson) { if (!element.is_string()) { continue; @@ -357,14 +356,13 @@ int32_t HiChainAuthConnector::QueryCredentialInfo(int32_t userId, nlohmann::json char *returnCredInfo = nullptr; ret = cm->queryCredInfoByCredId(userId, credId.c_str(), &returnCredInfo); if (ret != DM_OK) { - LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to query credential info."); - context->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + LOGE("HiChainAuthConnector::QueryCredentialInfo fail to query credential info."); return ERR_DM_FAILED; } nlohmann::json credInfoJson = nlohmann::json::parse(returnCredInfo, nullptr, false); FreeJsonString(returnCredInfo); if (credInfoJson.is_discarded()) { - LOGE("DmAuthManager::ProcRespNegotiate5_1_0 credential info jsonStr error"); + LOGE("HiChainAuthConnector::QueryCredentialInfo credential info jsonStr error"); return ERR_DM_FAILED; } -- Gitee From df2439643a5983b65dcbd9a7764179f954eaec6e Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Feb 2025 16:12:47 +0800 Subject: [PATCH 017/382] tmp --- .../implementation/include/authentication_v2/auth_manager.h | 1 + .../src/authentication_v2/auth_stages/auth_confirm.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index f0be2be2f..a157e1baa 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -32,6 +32,7 @@ const int32_t MIN_PIN_TOKEN = 10000000; const int32_t MAX_PIN_TOKEN = 90000000; const int32_t NEGOTIATE_TIMEOUT = 10; const int32_t WAIT_REQUEST_TIMEOUT = 10; +const int32_t CONFIRM_TIMEOUT = 10; const int32_t HML_SESSION_TIMEOUT = 10; const int32_t AUTHENTICATE_TIMEOUT = 120; constexpr const char* DM_VERSION_5_1_0 = "5.1.0"; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 1486b2a00..5b7da12f7 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -80,7 +80,7 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) context->timer->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), CONFIRM_TIMEOUT, [context] (std::string name) { - AuthSinkStatePinAuthComm::HandleAuthenticateTimeout(context, name); + HandleAuthenticateTimeout(context, name); }); LOGI("AuthSrcConfirmState::Action ok"); -- Gitee From 0339da4596c10988a06649f156f44582145212de Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Feb 2025 16:21:10 +0800 Subject: [PATCH 018/382] tmp --- services/implementation/include/authentication_v2/auth_manager.h | 1 - .../src/authentication_v2/auth_stages/auth_confirm.cpp | 1 + 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index a157e1baa..f0be2be2f 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -32,7 +32,6 @@ const int32_t MIN_PIN_TOKEN = 10000000; const int32_t MAX_PIN_TOKEN = 90000000; const int32_t NEGOTIATE_TIMEOUT = 10; const int32_t WAIT_REQUEST_TIMEOUT = 10; -const int32_t CONFIRM_TIMEOUT = 10; const int32_t HML_SESSION_TIMEOUT = 10; const int32_t AUTHENTICATE_TIMEOUT = 120; constexpr const char* DM_VERSION_5_1_0 = "5.1.0"; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 5b7da12f7..9d7223de5 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -33,6 +33,7 @@ constexpr const char* TAG_LOCAL_DEVICE_TYPE = "LOCALDEVICETYPE"; constexpr const char* TAG_REQUESTER = "REQUESTER"; constexpr const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; +constexpr int32_t CONFIRM_TIMEOUT = 60; std::set g_shareByPinAuthDeviceTypeSet{DmDeviceType::DEVICE_TYPE_SMART_DISPLAY}; /* -- Gitee From 30c0de1a7bcdfb70e66cc1cde7e87433cf9c702f Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Fri, 28 Feb 2025 08:42:29 +0000 Subject: [PATCH 019/382] =?UTF-8?q?=E3=80=90=E6=96=B0=E5=8D=8F=E8=AE=AE?= =?UTF-8?q?=E3=80=91=20161-170=E9=80=BB=E8=BE=91=EF=BC=88TODO=20=E5=8E=8B?= =?UTF-8?q?=E7=BC=A9=E5=92=8Cchecksum=E5=BE=85=E5=AE=8C=E6=88=90=EF=BC=89?= =?UTF-8?q?=20=E3=80=90=E6=96=B0=E5=8D=8F=E8=AE=AE=E3=80=91=20161-170?= =?UTF-8?q?=E9=80=BB=E8=BE=91=EF=BC=88TODO=20=E5=8E=8B=E7=BC=A9=E5=92=8Cch?= =?UTF-8?q?ecksum=E5=BE=85=E5=AE=8C=E6=88=90=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/dm_constants.h | 3 +- .../include/authentication_v2/auth_manager.h | 5 - .../authentication_v2/dm_auth_context.h | 7 +- .../dm_auth_message_processor.h | 56 ++++- .../include/authentication_v2/dm_auth_state.h | 29 ++- .../include/cryptomgr/crypto_mgr.h | 1 + .../auth_stages/auth_credential.cpp | 235 ++++++++++++++++-- .../dm_auth_message_processor.cpp | 209 +++++++++++++++- .../src/authentication_v2/dm_auth_state.cpp | 2 +- .../src/cryptomgr/crypto_mgr.cpp | 8 + 10 files changed, 516 insertions(+), 39 deletions(-) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index 2c92a3e8f..d66527a92 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -131,7 +131,8 @@ enum { ERR_DM_WISE_NEED_LOGIN = 96929830, ERR_DM_NAME_EMPTY = 96929831, ERR_DM_HICHAIN_PROOFMISMATCH = 96929832, - ERR_DM_NEXT_STATE_INVALID = 96929833 + ERR_DM_NEXT_STATE_INVALID = 96929833, + ERR_DM_GET_SESSION_KEY_FAILED = 96929834, }; constexpr const char* TAG_GROUP_ID = "groupId"; diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 2b14619d5..da27042c2 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -35,11 +35,6 @@ const int32_t WAIT_REQUEST_TIMEOUT = 10; const int32_t HML_SESSION_TIMEOUT = 10; const int32_t AUTHENTICATE_TIMEOUT = 120; constexpr const char* DM_VERSION_5_1_0 = "5.1.0"; -// TODO: 黄蓝区同步,部分代码冲突,冲突时删除此处 -constexpr const char* PARAM_KEY_HML_ENABLE_160M = "hmlEnable160M"; -constexpr const char* PARAM_KEY_HML_ACTIONID = "hmlActionId"; -constexpr const char* PARAM_KEY_CONN_SESSIONTYPE = "connSessionType"; - constexpr const char* BUNDLE_NAME_KEY = "bundleName"; // 取自security_device_auth中的identity_operation.h,该头文件为内部头文件,不能直接引用 diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 20a778a6b..a146b51fa 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -119,8 +119,6 @@ struct DmAccess { std::string publicKey; // T公钥长度 int32_t credentialId; // 应用凭据ID int32_t status; // 表示服务为前台还是后台,业务透传,只保存 - int32_t sessionKeyId; // 作为秘钥派送的材料,在总线中取出sk - int64_t skTimeStamp; // 老化,时间为2天 bool isAuthed; bool isOnline; std::string dmVersion; // 版本 5.1.0 @@ -141,9 +139,14 @@ struct DmAuthContext { int32_t connDelayCloseTime; // 链路延迟释放时间, 授权结束后不自动断链(有业务需要使用)保留字段 int32_t reason; // 本端失败的原因 int32_t reply; // 对端回复的结果 引用common/include/dm_constants.h,有新的错误码可新增 + int32_t appSessionKeyId; // 本端永久应用SKID,由DP返回用于ACL的更新、老化 + int32_t userSessionKeyId; // 本端永久用户SKID,由DP返回用于ACL的更新、老化 + int64_t appSkTimeStamp; // 老化,时间为2天 应用级凭据时间戳 + int64_t userSkTimeStamp; // 老化,时间为2天 用户级凭据时间戳 int32_t hmlActionId = 0; bool normalFinishAuth; // 标识认证过程是否正常结束 bool authenticating; // 标识正在认证中 + bool isAppCredentailVerified = false; // 标识用户凭据是否认证 bool hmlEnable160M = false; std::string pkgName; // 业务传入的标识,业务自定义,有被仿冒的风险 std::string pkgLabel; diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 6b3aabf89..f2257c30e 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -18,12 +18,14 @@ #include #include "nlohmann/json.hpp" - #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"; // 报文数据 @@ -48,11 +50,9 @@ constexpr const char *DM_TAG_AUTHRIZED_APP_LIST = "authorizedAppList"; constexpr const char *DM_TAG_CREDENTIAL_OWNER = "credentialOwner"; constexpr const char *DM_AUTH_CREDENTIAL_OWNER = "DM"; // 凭据拥有者 constexpr const char *DM_TAG_TOKEN_ID = "tokenId"; - constexpr const char* APP_OPERATION_KEY = "appOperation"; constexpr const char* APP_THUMBNAIL = "appThumbnail"; constexpr const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; - constexpr const char* TAG_DEVICE_VERSION = "deviceVersion"; constexpr const char* TAG_DEVICE_NAME = "deviceName"; constexpr const char* TAG_DEVICE_ID_HASH = "deviceIdHash"; @@ -63,6 +63,16 @@ 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_PKG_NAME = "pkgName"; +constexpr const char *DM_TAG_DMVERSION = "dmVersion"; +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_SERVICEINFO = "serviceInfo"; +constexpr const char *DM_TAG_APPSKID = "accesserAppSKId"; +constexpr const char *DM_TAG_USERSKID = "accesserUserSKId"; +constexpr const char *DM_TAG_APPSK_TIMESTAMP = "accesserAppSKTimeStamp"; +constexpr const char *DM_TAG_USERSK_TIMESTAMP = "accesserUserSKTimeStamp"; +constexpr const char *DM_TAG_SYNC = "syncMessage"; // 报文类型 enum DmMessageType { @@ -89,18 +99,49 @@ enum DmMessageType { MSG_TYPE_AUTH_FINISH = 200, }; +// 用于同步ACL的access结构 +struct DmAccessToSync { + std::string deviceName; + std::string deviceId; // A->B, 无论是A端还是B端,Accesser对象都存A端的deviceId,Accessee对象都存B端的deviceId + int32_t userId; + std::string accountId; + uint64_t tokenId; + std::string bundleName; // 存PacketName + int32_t bindLevel; // 为业务透传数据,无需自定义 + int32_t sessionKeyId; // 用户凭据ID + int64_t skTimeStamp; // 老化,时间为2天 用户级凭据时间戳 + // 使用宏进行序列化和反序列化 + NLOHMANN_DEFINE_TYPE_INTRUSIVE(DmAccessToSync, deviceName, deviceId, userId, accountId, tokenId, bundleName, + bindLevel, sessionKeyId, skTimeStamp) +}; + class DmAuthMessageProcessor { public: + DmAuthMessageProcessor(); + ~DmAuthMessageProcessor(); // 解析报文,返回值为错误码,实际解析出来的信息保存到context中 int32_t ParseMessage(std::shared_ptr context, const std::string &message); // 创建报文,构造对应msgType的报文,返回值为json格式报文的字符串 std::string CreateMessage(DmMessageType msgType, std::shared_ptr context); + + // 解析透传ON_TRANSMIT字段 + std::string GetTransmitFromContext(std::shared_ptr &context); + // 创建报文并发送 void CreateAndSendMsg(DmMessageType msgType, std::shared_ptr context); + // 保存秘钥 int32_t SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyLen); + + std::shared_ptr cryptoMgr_ = nullptr; private: // 内部各类报文的实现 + + // 用于组装syncMsg中的加密部分 + int32_t EncryptSyncMessage(std::shared_ptr &context, std::vector aclList, + DmAccess &accessSide, std::string &encSyncMsg); + int32_t ParseAuthStartMessgae(nlohmann::json &jsonObject, std::shared_ptr &context); + // 解析 80报文 void ParseNegotiateMessage(nlohmann::json &jsonObject, std::shared_ptr context); // 解析 90 报文 @@ -121,6 +162,8 @@ private: int32_t ParseMessageReqCredExchange(const nlohmann::json &jsonObject, std::shared_ptr context); // 解析 150报文信息MSG_TYPE_RESP_CREDENTIAL_EXCHANGE,存放对方公钥,和协商凭据Id int32_t ParseMessageRspCredExchange(const nlohmann::json &jsonObject, std::shared_ptr context); + // 解析161 170 171 + int32_t ParseMessageNegotiateTransmit(const nlohmann::json &jsonObject, std::shared_ptr &context); // 创建 80报文 void CreateNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject); @@ -143,9 +186,10 @@ private: // 创建160报文 void CreateMessageReqCredAuthStart(std::shared_ptr context, nlohmann::json &jsonObject); -private: - // 内部各类报文的实现 - std::shared_ptr cryptoMgr_ = nullptr; + // 161 170 171 透传凭据认证消息构造 + int32_t CreateCredentialNegotiateMessage(std::shared_ptr &context, nlohmann::json &jsonObject); + // 180 190 消息构造 + int32_t CreateSyncMessage(std::shared_ptr &context, nlohmann::json &jsonObject); }; } // namespace DistributedHardware diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index a282d4f02..3719fad2f 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -19,13 +19,11 @@ #include #include "access_control_profile.h" - #include "dm_auth_state.h" #include "dm_auth_context.h" namespace OHOS { namespace DistributedHardware { -struct DmAuthContext; // 状态类型 enum class DmAuthStateType { @@ -229,6 +227,33 @@ public: DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; }; +// 收到170凭据认证报文,解析ontransmit,回复161报文 +class AuthSrcCredentialAuthNegotiateState : public DmAuthState { + virtual ~AuthSrcCredentialAuthNegotiateState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; // 执行状态对应的action动作 +}; + +// 收到171凭据认证报文 发送160/180 报文 +class AuthSrcCredentialAuthDoneState : public DmAuthState { + virtual ~AuthSrcCredentialAuthDoneState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; // 执行状态对应的action动作 +}; + +// 收到160凭证认证报文 发送170报文 +class AuthSinkCredentialAuthStartState : public DmAuthState { + virtual ~AuthSinkCredentialAuthStartState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; // 执行状态对应的action动作 +}; + +// 收到161凭据协商报文 并回复171报文 +class AuthSinkCredentialAuthNegotiateState : public DmAuthState { + virtual ~AuthSinkCredentialAuthNegotiateState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; // 执行状态对应的action动作 +}; // 收到80报文,准备发送90报文 class AuthSinkNegotiateStateMachine : public DmAuthState { diff --git a/services/implementation/include/cryptomgr/crypto_mgr.h b/services/implementation/include/cryptomgr/crypto_mgr.h index dc02f7b90..487018a4c 100644 --- a/services/implementation/include/cryptomgr/crypto_mgr.h +++ b/services/implementation/include/cryptomgr/crypto_mgr.h @@ -51,6 +51,7 @@ public: int32_t DecryptMessage(const std::string &inputMsg, std::string &outputMsg); int32_t SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyLen); void ClearSessionKey(); + uint32_t GetSessionKey(uint8_t *sesionKey); private: int32_t DoEncryptData(AesGcmCipherKey *cipherKey, const unsigned char *input, uint32_t inLen, diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 1096820f6..29475c5a0 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -12,39 +12,232 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#include #include #include #include - +#include "dm_auth_state.h" +#include "dm_auth_context.h" #include "dm_auth_state_machine.h" -#include "multiple_user_connector.h" #include "dm_auth_message_processor.h" -#include "dm_auth_state.h" +#include "dm_log.h" +#include "dm_constants.h" +#include "multiple_user_connector.h" +#include "deviceprofile_connector.h" +#include "hichain_auth_connector.h" namespace OHOS { namespace DistributedHardware { -/* -凭据生成(140和150报文处理) -source端状态: -AuthSrcCredentialExchangeState, // 触发Onfinish回调事件,发送140报文 +// 从context中提取transmit data,使用SK解密,并透传给HICHAIN +// 如果ontransmit事件,在对应回调解析并保存在context +// 如果onsessionkeyreturned事件,在对应回调解析并保存在cryptomgr +static int32_t AuthCredentialTransmitDecryptProcess(std::shared_ptr context, DmEventType event) +{ + std::string transmitStr; + if (context->GetFromContextExtra(DM_TAG_ON_TRANSMIT_DATA, transmitStr) != DM_OK) { + LOGE("DmAuthMessageProcessor::CreateMessageReqCredAuthStart failed, get onTransmitData from extra failed."); + return ERR_DM_FAILED; + } + + // 透传给hichain + int32_t ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, transmitStr); + if (ret != DM_OK) { + LOGE("AuthCredentialTransmitDecryptProcess: ProcessCredData transmit data failed"); + return ERR_DM_FAILED; + } + // 等待hichain返回结果 + if (context->authStateMachine->WaitExpectEvent(event) != event) { + LOGE("AuthCredentialTransmitDecryptProcess: Hichain auth transmit data failed"); + return ERR_DM_FAILED; + } + return DM_OK; +} + +// 解析HICHAIN transmit data,并透传给对端 +static int32_t AuthCredentialTransmitSend(std::shared_ptr context, DmMessageType msgType) +{ + // 获取transmit data + std::string transmitStr; + transmitStr = context->authMessageProcessor->GetTransmitFromContext(context); + if (transmitStr.empty()) { + LOGE("AuthCredentialTransmitSend: GetTransmitFromContext from HICHAIN failed"); + return ERR_DM_FAILED; + } -sink端状态: -AuthSinkCredentialExchangeState, // 收到140加密报文,发送150报文 + std::string message = + context->authMessageProcessor->CreateMessage(msgType, context); // 不需要额外传data,context中均有 + if (message.empty()) { + LOGE("AuthCredentialTransmitSend: CreateMessage AuthCredential transmit data failed"); + return ERR_DM_FAILED; + } + // 发送报文 + return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); +} -凭据协商(160和170报文处理、161和171报文处理) -source端状态: -AuthSrcCredentialAuthStartState, // 收到150加密报文,发送160报文 -AuthSrcCredentialAuthNegotiateState, // 收到170凭据认证报文,发送161报文 -AuthSrcCredentialAuthDoneState, // 收到171凭据认证报文 +// SOURCE端凭据校验操作 -sink端状态: -AuthSinkCredentialAuthStartState, // 收到160凭证认证报文,发送170报文 -AuthSinkCredentialAuthNegotiateState, // 收到161凭据协商报文 -AuthSinkCredentialAuthDoneState, // 触发Onfinish回调事件 +DmAuthStateType AuthSrcCredentialAuthNegotiateState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE; +} +// 收到170凭据认证报文,解析ontransmit,回复161报文 +int32_t AuthSrcCredentialAuthNegotiateState::Action(std::shared_ptr context) +{ + // 解密并透传transmitData + int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_TRANSMIT); + if (ret != DM_OK) { + return ret; + } + // 发送161报文 + return AuthCredentialTransmitSend(context, DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE); +} -*/ +DmAuthStateType AuthSrcCredentialAuthDoneState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE; +} +// 收到171凭据认证报文 +int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr context) +{ + // 解密并透传transmitData + // 171报文在首次认证情况下会发生两次,先进行应用凭据认证,后进行用户凭据认证;非首次认证仅进行用户凭据认证 + // 最后一次认证结束后会收到ON_FINISH + int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_SESSION_KEY_RETURNED); + if (ret != DM_OK) { + return ret; + } + + // 认证结束触发Onfinish回调事件 + if (context->authStateMachine->WaitExpectEvent(ON_FINISH) != ON_FINISH) { + LOGE("AuthSrcCredentialAuthDoneState::Action Hichain auth SINK transmit data failed"); + return ERR_DM_FAILED; + } + int32_t skId; + DmMessageType msgType; + uint8_t* sessionKey = nullptr; + uint32_t sessionKeyLen = 0; + sessionKeyLen = context->authMessageProcessor->cryptoMgr_->GetSessionKey(sessionKey); + ret = DeviceProfileConnector::PutSessionKey(sessionKey, sessionKeyLen, skId); // 保存到DP + if (ret != DM_OK) { + LOGE("AuthSrcCredentialAuthDoneState::Action DP save user session key failed"); + return ret; + } + // 首次认证 且 应用凭据流程 + if (context->isOnline == false && context->isAppCredentailVerified == false) { + context->isAppCredentailVerified = true; + // 保存到DP 获取应用凭据ID 并保存 + context->appSkTimeStamp = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) + .count(); + context->appSessionKeyId = skId; + msgType = MSG_TYPE_REQ_CREDENTIAL_AUTH_START; // 发送160 + // 认证用户凭据 + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + ret = context->hiChainAuthConnector->AuthCredential(osAccountId, context->requestId, + context->accessee.userCredentialId, std::string("")); + if (ret != DM_OK) { + LOGE("AuthSrcCredentialAuthDoneState::Action Hichain auth credentail failed"); + return ret; + } + } else if (context->isOnline == false) { + // 首次认证 且 用户凭据流程 + // 保存到DP 获取用户凭据ID 并保存 + context->userSkTimeStamp = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) + .count(); + context->userSessionKeyId = skId; + msgType = MSG_TYPE_REQ_DATA_SYNC; // 发送180 + } else { + // 非首次认证 应用凭据流程 + // 保存到DP 获取应用凭据ID 并保存 + context->appSkTimeStamp = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) + .count(); + context->appSessionKeyId = skId; + msgType = MSG_TYPE_REQ_DATA_SYNC; // 发送180 + } + std::string message = + context->authMessageProcessor->CreateMessage(msgType, context); // 不需要额外传data,context中均有 + if (message.empty()) { + LOGE("AuthSrcCredentialAuthDoneState::Action CreateMessage failed"); + return ERR_DM_FAILED; + } + + return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); +} + +// SINK端凭据校验操作 +DmAuthStateType AuthSinkCredentialAuthStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE; +} +// 收到160凭证认证报文,发送170报文 +int32_t AuthSinkCredentialAuthStartState::Action(std::shared_ptr context) +{ + // 解密并透传transmitData + int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_TRANSMIT); + if (ret != DM_OK) { + return ret; + } + // 构造并发送170报文 + return AuthCredentialTransmitSend(context, DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_START); +} + +DmAuthStateType AuthSinkCredentialAuthNegotiateState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE; +} + +// 收到161凭据协商报文,并回复171报文 +// 通过isAppCredentailVerified关键词区分首次认证、非首次认证 +int32_t AuthSinkCredentialAuthNegotiateState::Action(std::shared_ptr context) +{ + // 解密并透传transmitData + int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_TRANSMIT); + if (ret != DM_OK) { + return ret; // 内部有日志 不重复打印 + } + // 构造并发送171报文 + ret = AuthCredentialTransmitSend(context, DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE); + if (ret != DM_OK) { + return ret; // 内部有日志 不重复打印 + } + + if (context->authStateMachine->WaitExpectEvent(ON_SESSION_KEY_RETURNED) != ON_SESSION_KEY_RETURNED) { + LOGE("AuthSinkCredentialAuthNegotiateState::Action Hichain auth SINK transmit data failed"); + return ERR_DM_FAILED; + } + + if (context->authStateMachine->WaitExpectEvent(ON_FINISH) != ON_FINISH) { + LOGE("AuthSinkCredentialAuthNegotiateState::Action Hichain auth SINK transmit data failed"); + return ERR_DM_FAILED; + } + int32_t skId; + uint8_t* sessionKey = nullptr; + uint32_t sessionKeyLen = 0; + sessionKeyLen = context->authMessageProcessor->cryptoMgr_->GetSessionKey(sessionKey); + ret = DeviceProfileConnector::PutSessionKey(sessionKey, sessionKeyLen, skId); + if (ret != DM_OK) { + LOGE("AuthSinkCredentialAuthNegotiateState::Action DP save user session key failed"); + return ret; + } + + if (context->isOnline == false && + context->isAppCredentailVerified == true) { // SINK首次认证场景,第二次收到161的流程 保存用户级永久SK到DP + context->userSkTimeStamp = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) + .count(); + context->userSessionKeyId = skId; + } else { // 应用级凭据认证流程 首次认证的第一次161处理 和 非首次认证的161处理 + context->isAppCredentailVerified = true; // 用于指示 首次认证的应用级凭据已认证 + context->appSkTimeStamp = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) + .count(); + context->appSessionKeyId = skId; + } + return DM_OK; +} // 生成凭据协商状态下的authParams的json格式字符串 // authScope 设备级还是应用级 @@ -330,4 +523,4 @@ int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr c } } // namespace DistributedHardware -} // namespace OHOS \ No newline at end of file +} // namespace OHOS diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 726031c5e..4a1ccde00 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -16,6 +16,14 @@ #include "dm_anonymous.h" #include "dm_auth_context.h" #include "dm_auth_message_processor.h" +#include "distributed_device_profile_client.h" +#include "deviceprofile_connector.h" +#include "service_info_profile.h" +#include "service_info_unique_key.h" +#include "dm_log.h" +#include "dm_constants.h" +#include "dm_anonymous.h" +#include "access_control_profile.h" #include "dm_auth_context.h" #include "dm_auth_state_machine.h" @@ -35,6 +43,20 @@ int32_t DmAuthMessageProcessor::SaveSessionKey(const uint8_t *sessionKey, const return cryptoMgr_->SaveSessionKey(sessionKey, keyLen); } +DmAuthMessageProcessor::DmAuthMessageProcessor() +{ + LOGI("DmAuthMessageProcessor constructor"); + cryptoMgr_ = std::make_shared(); +} + +DmAuthMessageProcessor::~DmAuthMessageProcessor() +{ + if (cryptoMgr_ != nullptr) { + cryptoMgr_->ClearSessionKey(); + cryptoMgr_ = nullptr; + } +} + // 解析报文,返回值为错误码,实际解析出来的信息保存到context中 int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr context, const std::string &message) { @@ -55,8 +77,13 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont context->msgType = msgType; LOGI("DmAuthMessageProcessor::ParseMessage message type %{public}d", context->msgType); switch (msgType) { + case MSG_TYPE_REQ_CREDENTIAL_AUTH_START: // 160 + return ParseAuthStartMessgae(jsonObject, context); + case MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE: // 161 + case MSG_TYPE_RESP_CREDENTIAL_AUTH_START: // 170 + case MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE: // 171 case MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE: - return ParseMessageOnTransmit(jsonObject, context); + return ParseMessageNegotiateTransmit(jsonObject, context); case MSG_TYPE_REQ_CREDENTIAL_EXCHANGE: return ParseMessageReqCredExchange(jsonObject, context); case MSG_TYPE_RESP_CREDENTIAL_EXCHANGE: @@ -67,6 +94,29 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont return ERR_DM_FAILED; } +int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const nlohmann::json &jsonObject, + std::shared_ptr &context) +{ + if (jsonObject.is_discarded() || !jsonObject.contains(DM_TAG_DATA) || !jsonObject[DM_TAG_DATA].is_string()) { + LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae Unlegal json string failed"); + return ERR_DM_FAILED; + } + // 解密 + std::string plainText; + int32_t ret = context->authMessageProcessor->cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA], plainText); + if (ret != DM_OK) { + LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae DecryptMessage failed"); + return ret; + } + + nlohmann::json jsonDecrptObj = plainText; + if (ParseMessageOnTransmit(jsonDecrptObj, context) != DM_OK) { + LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae ParseMessageOnTransmit failed"); + return ERR_DM_FAILED; + } + return DM_OK; +} + // 解析onTransmit返回的数据,保存到context->extra中 int32_t DmAuthMessageProcessor::ParseMessageOnTransmit(const nlohmann::json &jsonObject, std::shared_ptr context) @@ -183,6 +233,18 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh case MSG_TYPE_REQ_CREDENTIAL_AUTH_START: CreateMessageReqCredAuthStart(context, jsonObj); break; + case MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE: // 161 + case MSG_TYPE_RESP_CREDENTIAL_AUTH_START: // 170 + case MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE: // 171 + if (CreateCredentialNegotiateMessage(context, jsonObj) != DM_OK) { + return ""; + } + break; + case MSG_TYPE_REQ_DATA_SYNC: + if (CreateSyncMessage(context, jsonObj)!= DM_OK) { + return ""; + } + break; default: LOGE("DmAuthMessageProcessor::CreateMessage msgType %{public}d error.", msgType); break; @@ -191,6 +253,20 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh } // 内部各类报文的实现 +int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr &context, nlohmann::json &jsonObject) +{ + std::string encryptMsg; + int32_t ret = context->authMessageProcessor->cryptoMgr_->EncryptMessage( + DmAuthMessageProcessor::GetTransmitFromContext(context), encryptMsg); // 临时SK加密 + if (ret != DM_OK) { + LOGE("DmAuthMessageProcessor::CreateSyncMessage encrypt failed"); + return ret; + } + jsonObject[DM_TAG_DATA] = encryptMsg; + return DM_OK; +} + + // 创建140报文 void DmAuthMessageProcessor::CreateMessageReqCredExchange(std::shared_ptr context, nlohmann::json &jsonObject) @@ -403,6 +479,137 @@ void DmAuthMessageProcessor::CreateAndSendMsg(DmMessageType msgType, std::shared auto message = CreateMessage(msgType, context); context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); } +// 用于组装syncMsg中的加密部分 +int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptr &context, + std::vector aclList, DmAccess &accessSide, std::string &encSyncMsg) +{ + nlohmann::json syncMsg; + DmAccessToSync accessToSync; + accessToSync.deviceName = accessSide.deviceName; + accessToSync.deviceId = accessSide.deviceId; + accessToSync.userId = accessSide.userId; + accessToSync.accountId = accessSide.accountId; + accessToSync.tokenId = accessSide.tokenId; + accessToSync.bundleName = accessSide.bundleName; + accessToSync.bindLevel = accessSide.bindLevel; + + if (context->isOnline) { // 非首次认证 + accessToSync.sessionKeyId = context->appSessionKeyId; + accessToSync.skTimeStamp = context->appSkTimeStamp; + syncMsg[DM_TAG_APPSKID]=std::to_string(context->appSessionKeyId); + syncMsg[DM_TAG_APPSK_TIMESTAMP]=std::to_string(context->appSkTimeStamp); + } else { // 首次认证 + accessToSync.sessionKeyId = context->userSessionKeyId; + accessToSync.skTimeStamp = context->userSkTimeStamp; + syncMsg[DM_TAG_APPSKID]=std::to_string(context->appSessionKeyId); + syncMsg[DM_TAG_USERSKID]=std::to_string(context->userSessionKeyId); + syncMsg[DM_TAG_APPSK_TIMESTAMP]=std::to_string(context->appSkTimeStamp); + syncMsg[DM_TAG_USERSK_TIMESTAMP]=std::to_string(context->userSkTimeStamp); + } + + nlohmann::json accessJsonObj = accessToSync; // 直接使用宏构造json + nlohmann::json aclJsonObj = aclList; + syncMsg[DM_TAG_DMVERSION] = accessSide.dmVersion; + syncMsg[DM_TAG_ACCESS] = accessJsonObj.dump(); // 接收端需要再拆一次json + syncMsg[DM_TAG_PROXY] = ""; // 预留字段 留空即可 + syncMsg[DM_TAG_ACL] = aclJsonObj.dump(); // 接收端需要再拆一次json + syncMsg[DM_TAG_SERVICEINFO]=""; // 与yangwei确认内容&格式 + + // 加密整个字段 + return context->authMessageProcessor->cryptoMgr_->EncryptMessage(SafetyDump(syncMsg), encSyncMsg); +} + +int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr &context, nlohmann::json &jsonObject) +{ + // 查询ACL + std::vector profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfile(); + std::vector aclList; + for (auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == context->accesser.deviceId && + item.GetAccesser().GetAccesserUserId() == context->accesser.userId && + item.GetAccessee().GetAccesseeDeviceId() == context->accessee.deviceId && + item.GetAccessee().GetAccesseeUserId() == context->accessee.userId) { + aclList.push_back(item.dump()); // 打印并写入 + } + } + if (aclList.empty()) { + LOGE("DmAuthMessageProcessor::CreateSyncMessage get acl failed"); + return ERR_DM_FAILED; + } + // 查询SP + DmAccess accessSide; // 代表本端的access + if (context->direction == DM_AUTH_SOURCE) { + accessSide = context->accesser; + } else { + accessSide = context->accessee; + } + DistributedDeviceProfile::ServiceInfoUniqueKey serviceInfoKey; + serviceInfoKey.SetDeviceId(accessSide.deviceId); + serviceInfoKey.SetUserId(accessSide.userId); + serviceInfoKey.SetTokenId(std::to_string(accessSide.tokenId)); + std::string encSyncMsg; + int32_t ret = EncryptSyncMessage(context, aclList, accessSide, encSyncMsg); + if (ret != DM_OK) { + LOGE("DmAuthMessageProcessor::CreateSyncMessage encrypt failed"); + return ret; + } + jsonObject[DM_TAG_SYNC] = encSyncMsg; + + // TODO 与yangwei确认压缩encMsg接口 + // TODO ACL改用verison+checksum传输 + + return DM_OK; +} + +std::string DmAuthMessageProcessor::GetTransmitFromContext(std::shared_ptr &context) +{ + // 解析出ontransmit字段 + std::string transmitStr = ""; + nlohmann::json jsonObject = nlohmann::json::parse(context->extraInfo, nullptr, false); + if (jsonObject.is_discarded() || !jsonObject.contains(DM_TAG_DATA) || !jsonObject[DM_TAG_DATA].is_string()) { + LOGE("DmAuthMessageProcessor::GetTransmitFromContext extraInfo jsonStr error"); + return transmitStr; + } + return SafetyDump(jsonObject[DM_TAG_DATA]); +} +// 解析transmit和PSKID +int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(nlohmann::json &jsonObject, std::shared_ptr &context) +{ + if (jsonObject.is_discarded() || !jsonObject.contains(DM_TAG_DATA) || + !jsonObject[DM_TAG_DATA].is_string()) { + LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae Unlegal json string failed"); + return ERR_DM_FAILED; + } + + // 解密 + std::string plainText; + int32_t ret = context->authMessageProcessor->cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA], plainText); + if (ret != DM_OK) { + LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae DecryptMessage failed"); + return ret; + } + nlohmann::json jsonDecrptObj = plainText; + + if (ParseMessageOnTransmit(jsonDecrptObj, context) != DM_OK) { + LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae ParseMessageOnTransmit failed"); + return ERR_DM_FAILED; + } + std::string jsonTag; + if (context->isOnline == false && context->isAppCredentailVerified == false) { // 首次认证的应用凭据 + jsonTag = DM_TAG_APP_CREDENTIAL_ID; + } else if (context->isOnline == false) { // 首次认证的用户凭据 + jsonTag = DM_TAG_USER_CREDENTIAL_ID; + } else { // 非首次认证的应用凭据 + jsonTag = DM_TAG_APP_CREDENTIAL_ID; + } + + if (!jsonDecrptObj.contains(jsonTag) || !jsonDecrptObj[jsonTag].is_string()) { + LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae Unlegal json CRED ID"); + return ERR_DM_FAILED; + } + context->accesser.appCredentialId = jsonDecrptObj[jsonTag].get(); + return DM_OK; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index c6aadf4c1..424dd1a37 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -52,7 +52,7 @@ const std::map TASK_TIME_OUT_MAP = { int32_t DmAuthState::GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut) { - LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, acontext->uthType); + LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, context->authType); if (context->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { auto timeout = TASK_TIME_OUT_MAP.find(std::string(taskName)); if (timeout != TASK_TIME_OUT_MAP.end()) { diff --git a/services/implementation/src/cryptomgr/crypto_mgr.cpp b/services/implementation/src/cryptomgr/crypto_mgr.cpp index 441e9e606..d8b04f776 100644 --- a/services/implementation/src/cryptomgr/crypto_mgr.cpp +++ b/services/implementation/src/cryptomgr/crypto_mgr.cpp @@ -17,6 +17,7 @@ #include #include +#include #include "mbedtls/base64.h" #include "mbedtls/cipher.h" @@ -302,6 +303,13 @@ int32_t CryptoMgr::SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyL return DM_OK; } +uint32_t CryptoMgr::GetSessionKey(uint8_t *sessionKey) +{ + std::lock_guard lock(sessionKeyMtx_); + sessionKey = sessionKey_.key; + return sessionKey_.keyLen; +} + void CryptoMgr::ClearSessionKey() { std::lock_guard lock(sessionKeyMtx_); -- Gitee From 13f8a5ca9569a9c14edd1d4c29d1fa16e2c30050 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Feb 2025 16:47:35 +0800 Subject: [PATCH 020/382] tmp --- .../include/authentication_v2/auth_manager.h | 8 ++++++++ .../src/authentication_v2/auth_manager.cpp | 14 ++++++++++++++ 2 files changed, 22 insertions(+) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index f0be2be2f..04d692da8 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -100,6 +100,10 @@ private: class AuthSrcManager : public AuthManager { public: + AuthSrcManager(std::shared_ptr softbusConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector); + ~AuthSrcManager() override = default; // 各类事件触发的函数实现(继承) int32_t OnUserOperation(int32_t action, const std::string ¶ms); bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) override; @@ -112,6 +116,10 @@ private: class AuthSinkManager : public AuthManager { public: + AuthSinkManager(std::shared_ptr softbusConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector); + ~AuthSinkManager() override = default; // 各类事件触发的函数实现(继承) int32_t OnUserOperation(int32_t action, const std::string ¶ms); bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) override; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index d8ecfedc2..f1c90eb03 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -575,6 +575,13 @@ int32_t AuthManager::BindTarget(const std::string &pkgName, const PeerTargetId & } } +AuthSinkManager::AuthSinkManager(std::shared_ptr softbusConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector) + : AuthManager(softbusConnector, listener, hiChainAuthConnector) +{ +} + int32_t AuthSinkManager::OnUserOperation(int32_t action, const std::string ¶ms) { LOGI("AuthSinkManager::OnUserOperation start."); @@ -610,6 +617,13 @@ int32_t AuthSinkManager::OnUserOperation(int32_t action, const std::string ¶ return DM_OK; } +AuthSrcManager::AuthSrcManager(std::shared_ptr softbusConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector) + : AuthManager(softbusConnector, listener, hiChainAuthConnector) +{ +} + int32_t AuthSrcManager::OnUserOperation(int32_t action, const std::string ¶ms) { LOGI("AuthSrcManager::OnUserOperation start."); -- Gitee From 02c683e82da8f5f42ae7763d492e658797bfdbd7 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Feb 2025 16:53:36 +0800 Subject: [PATCH 021/382] tmp --- .../implementation/include/authentication_v2/auth_manager.h | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 04d692da8..5d238c528 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -66,6 +66,7 @@ public: AuthManager(std::shared_ptr softbusConnector, std::shared_ptr listener, std::shared_ptr hiChainAuthConnector); + virtual ~AuthManager() = default; void SetAuthContext(std::shared_ptr context); std::shared_ptr GetAuthContext(); @@ -103,7 +104,7 @@ public: AuthSrcManager(std::shared_ptr softbusConnector, std::shared_ptr listener, std::shared_ptr hiChainAuthConnector); - ~AuthSrcManager() override = default; + virtual ~AuthSrcManager() override = default; // 各类事件触发的函数实现(继承) int32_t OnUserOperation(int32_t action, const std::string ¶ms); bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) override; @@ -119,7 +120,7 @@ public: AuthSinkManager(std::shared_ptr softbusConnector, std::shared_ptr listener, std::shared_ptr hiChainAuthConnector); - ~AuthSinkManager() override = default; + virtual ~AuthSinkManager() override = default; // 各类事件触发的函数实现(继承) int32_t OnUserOperation(int32_t action, const std::string ¶ms); bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) override; -- Gitee From 9328326e9f3824e961314b33bb96dad991740331 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Feb 2025 17:04:23 +0800 Subject: [PATCH 022/382] tmp --- .../include/authentication_v2/auth_manager.h | 12 +++++ .../src/authentication_v2/auth_manager.cpp | 52 ++++++++++++++++++- 2 files changed, 63 insertions(+), 1 deletion(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 5d238c528..0bfe9b173 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -111,6 +111,12 @@ public: 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; + 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; + void GetRemoteDeviceId(std::string &deviceId) override; private: }; @@ -127,6 +133,12 @@ public: 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; + 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; + void GetRemoteDeviceId(std::string &deviceId) override; private: }; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index f1c90eb03..1675b5695 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -581,7 +581,31 @@ AuthSinkManager::AuthSinkManager(std::shared_ptr softbusConnec : AuthManager(softbusConnector, listener, hiChainAuthConnector) { } - +void AuthSinkManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) +{ + LOGI("AuthSinkManager::OnSessionOpened start."); +} +void AuthSinkManager::OnSessionClosed(int32_t sessionId) +{ + LOGI("AuthSinkManager::OnSessionClosed start."); +} +void AuthSinkManager::OnDataReceived(int32_t sessionId, std::string message) +{ + LOGI("AuthSinkManager::OnDataReceived start."); +} +bool AuthSinkManager::GetIsCryptoSupport() +{ + LOGI("AuthSinkManager::GetIsCryptoSupport start."); + return false; +} +void AuthSinkManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string message) +{ + LOGI("AuthSinkManager::OnAuthDeviceDataReceived start."); +} +void AuthSinkManager::GetRemoteDeviceId(std::string &deviceId) +{ + LOGI("AuthSinkManager::GetRemoteDeviceId start."); +} int32_t AuthSinkManager::OnUserOperation(int32_t action, const std::string ¶ms) { LOGI("AuthSinkManager::OnUserOperation start."); @@ -624,6 +648,32 @@ AuthSrcManager::AuthSrcManager(std::shared_ptr softbusConnecto { } +void AuthSrcManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) +{ + LOGI("AuthSrcManager::OnSessionOpened start."); +} +void AuthSrcManager::OnSessionClosed(int32_t sessionId) +{ + LOGI("AuthSrcManager::OnSessionClosed start."); +} +void AuthSrcManager::OnDataReceived(int32_t sessionId, std::string message) +{ + LOGI("AuthSrcManager::OnDataReceived start."); +} +bool AuthSrcManager::GetIsCryptoSupport() +{ + LOGI("AuthSrcManager::GetIsCryptoSupport start."); + return false; +} +void AuthSrcManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string message) +{ + LOGI("AuthSrcManager::OnAuthDeviceDataReceived start."); +} +void AuthSrcManager::GetRemoteDeviceId(std::string &deviceId) +{ + LOGI("AuthSrcManager::GetRemoteDeviceId start."); +} + int32_t AuthSrcManager::OnUserOperation(int32_t action, const std::string ¶ms) { LOGI("AuthSrcManager::OnUserOperation start."); -- Gitee From 9cf310c4f51bda6845ebf3f0ef498b8c765164e5 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Feb 2025 17:51:39 +0800 Subject: [PATCH 023/382] tmp --- .../include/authentication_v2/auth_manager.h | 55 +++++++++++++++ .../src/authentication_v2/auth_manager.cpp | 67 +++++++++++++++++++ 2 files changed, 122 insertions(+) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 0bfe9b173..68aec7e68 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -21,6 +21,7 @@ #include "hichain_connector.h" #include "softbus_connector.h" #include "softbus_session.h" +#include "auth_ui_state_manager.h" namespace OHOS { namespace DistributedHardware { @@ -76,9 +77,63 @@ public: int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, const std::map &bindParam); + /** + * @tc.name: AuthManager::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 GeneratePincode(); + /** + * @tc.name: AuthManager::ImportAuthCode + * @tc.desc: Import auth code + * @tc.type: FUNC + */ + int32_t ImportAuthCode(const std::string &pkgName, const std::string &authCode); + /** + * @tc.name: AuthManager::RegisterUiStateCallback + * @tc.desc: Register ui state callback + * @tc.type: FUNC + */ + int32_t RegisterUiStateCallback(const std::string pkgName); + + /** + * @tc.name: AuthManager::UnRegisterUiStateCallback + * @tc.desc: Unregister ui state callback + * @tc.type: FUNC + */ + int32_t UnRegisterUiStateCallback(const std::string pkgName); + + /** + * @tc.name: AuthManager::UnAuthenticateDevice + * @tc.desc: UnAuthenticate Device of the DeviceManager Authenticate Manager + * @tc.type: FUNC + */ + int32_t UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel); + + /** + * @brief UnBind device. + * @param pkgName package name. + * @param deviceId device id. + * @return Return 0 if success. + */ + int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel, const std::string &extra); + int32_t StopAuthenticateDevice(const std::string &pkgName); + + void OnScreenLocked(); + void HandleDeviceNotTrust(const std::string &udid); + int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); + int32_t RegisterAuthenticationType(int32_t authenticationType); protected: // 上下文(需在该层级进行创建) std::shared_ptr context_; + std::shared_ptr authUiStateMgr_; private: int32_t ParseAuthType(const std::map &bindParam, int32_t &authType); int32_t ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType); diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 1675b5695..0b4fc1d80 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -42,6 +42,8 @@ namespace OHOS { namespace DistributedHardware { namespace { +constexpr int32_t MIN_PIN_CODE = 100000; +constexpr int32_t MAX_PIN_CODE = 999999; const int32_t MAX_AUTH_FAIL_TIMES = 3; // TODO: 黄蓝区未同步,无CONN_SESSION_TYPE_HML符号 @@ -190,6 +192,71 @@ int32_t AuthManager::ParseAuthType(const std::map &bin authType = std::atoi(authTypeStr.c_str()); return DM_OK; } +void AuthManager::GeneratePincode(std::shared_ptr context) +{ + context_->pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); +} + +int32_t AuthManager::RegisterUiStateCallback(const std::string pkgName) +{ + LOGI("AuthManager::RegisterUiStateCallback start"); + if (context_->authUiStateMgr == nullptr) { + LOGE("AuthManager::RegisterUiStateCallback context_->authUiStateMgr is null."); + return ERR_DM_FAILED; + } + context_->authUiStateMgr->RegisterUiStateCallback(pkgName); + return DM_OK; +} + +int32_t AuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) +{ + LOGI("AuthManager::UnAuthenticateDevice start"); + return ERR_DM_FAILED; +} + + +int32_t AuthManager::UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel, const std::string &extra) +{ + LOGI("AuthManager::UnBindDevice start"); + return ERR_DM_FAILED; +} +int32_t AuthManager::StopAuthenticateDevice(const std::string &pkgName) +{ + LOGI("AuthManager::StopAuthenticateDevice start"); + return ERR_DM_FAILED; +} + +void AuthManager::OnScreenLocked() +{ + LOGI("AuthManager::OnScreenLocked start"); +} +void AuthManager::HandleDeviceNotTrust(const std::string &udid) +{ + LOGI("AuthManager::HandleDeviceNotTrust start"); +} +int32_t AuthManager::DeleteGroup(const std::string &pkgName, const std::string &deviceId) +{ + LOGI("AuthManager::DeleteGroup start"); + return ERR_DM_FAILED; +} +int32_t AuthManager::RegisterAuthenticationType(int32_t authenticationType) +{ + LOGI("AuthManager::RegisterAuthenticationType start"); + return ERR_DM_FAILED; +} + + +int32_t AuthManager::UnRegisterUiStateCallback(const std::string pkgName) +{ + LOGI("AuthManager::UnRegisterUiStateCallback start"); + if (context_->authUiStateMgr == nullptr) { + LOGE("AuthManager::UnRegisterUiStateCallback context_->authUiStateMgr is null."); + return ERR_DM_FAILED; + } + context_->authUiStateMgr->UnRegisterUiStateCallback(pkgName); + return DM_OK; +} // 保存秘钥 void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) -- Gitee From b5f3a97c4e9ebf6f3e26f0e72e26acfce6d82846 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Feb 2025 17:59:12 +0800 Subject: [PATCH 024/382] tmp --- .../include/authentication_v2/auth_manager.h | 4 +- .../src/authentication_v2/auth_manager.cpp | 48 ++++++++++++++----- 2 files changed, 38 insertions(+), 14 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 68aec7e68..0ddcfd7e5 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -161,7 +161,7 @@ public: std::shared_ptr hiChainAuthConnector); virtual ~AuthSrcManager() override = default; // 各类事件触发的函数实现(继承) - int32_t OnUserOperation(int32_t action, const std::string ¶ms); + int32_t OnUserOperation(int32_t action, const std::string ¶ms) override; 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; @@ -183,7 +183,7 @@ public: std::shared_ptr hiChainAuthConnector); virtual ~AuthSinkManager() override = default; // 各类事件触发的函数实现(继承) - int32_t OnUserOperation(int32_t action, const std::string ¶ms); + int32_t OnUserOperation(int32_t action, const std::string ¶ms) override; 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; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 0b4fc1d80..bcd2887ca 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -208,56 +208,68 @@ int32_t AuthManager::RegisterUiStateCallback(const std::string pkgName) return DM_OK; } +int32_t AuthManager::UnRegisterUiStateCallback(const std::string pkgName) +{ + LOGI("AuthManager::UnRegisterUiStateCallback start"); + if (context_->authUiStateMgr == nullptr) { + LOGE("AuthManager::UnRegisterUiStateCallback context_->authUiStateMgr is null."); + return ERR_DM_FAILED; + } + context_->authUiStateMgr->UnRegisterUiStateCallback(pkgName); + return DM_OK; +} + int32_t AuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) { + // todo LOGI("AuthManager::UnAuthenticateDevice start"); return ERR_DM_FAILED; } +int32_t AuthManager::ImportAuthCode(const std::string &pkgName, const std::string &authCode) +{ + // todo + LOGI("AuthManager::ImportAuthCode start"); + return ERR_DM_FAILED; +} int32_t AuthManager::UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel, const std::string &extra) { + // todo LOGI("AuthManager::UnBindDevice start"); return ERR_DM_FAILED; } int32_t AuthManager::StopAuthenticateDevice(const std::string &pkgName) { + // todo LOGI("AuthManager::StopAuthenticateDevice start"); return ERR_DM_FAILED; } void AuthManager::OnScreenLocked() { + // todo LOGI("AuthManager::OnScreenLocked start"); } void AuthManager::HandleDeviceNotTrust(const std::string &udid) { + // todo LOGI("AuthManager::HandleDeviceNotTrust start"); } int32_t AuthManager::DeleteGroup(const std::string &pkgName, const std::string &deviceId) { + // todo LOGI("AuthManager::DeleteGroup start"); return ERR_DM_FAILED; } int32_t AuthManager::RegisterAuthenticationType(int32_t authenticationType) { + // todo LOGI("AuthManager::RegisterAuthenticationType start"); return ERR_DM_FAILED; } - -int32_t AuthManager::UnRegisterUiStateCallback(const std::string pkgName) -{ - LOGI("AuthManager::UnRegisterUiStateCallback start"); - if (context_->authUiStateMgr == nullptr) { - LOGE("AuthManager::UnRegisterUiStateCallback context_->authUiStateMgr is null."); - return ERR_DM_FAILED; - } - context_->authUiStateMgr->UnRegisterUiStateCallback(pkgName); - return DM_OK; -} - // 保存秘钥 void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) { @@ -650,27 +662,33 @@ AuthSinkManager::AuthSinkManager(std::shared_ptr softbusConnec } void AuthSinkManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) { + // todo LOGI("AuthSinkManager::OnSessionOpened start."); } void AuthSinkManager::OnSessionClosed(int32_t sessionId) { + // todo LOGI("AuthSinkManager::OnSessionClosed start."); } void AuthSinkManager::OnDataReceived(int32_t sessionId, std::string message) { + // todo LOGI("AuthSinkManager::OnDataReceived start."); } bool AuthSinkManager::GetIsCryptoSupport() { + // todo LOGI("AuthSinkManager::GetIsCryptoSupport start."); return false; } void AuthSinkManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string message) { + // todo LOGI("AuthSinkManager::OnAuthDeviceDataReceived start."); } void AuthSinkManager::GetRemoteDeviceId(std::string &deviceId) { + // todo LOGI("AuthSinkManager::GetRemoteDeviceId start."); } int32_t AuthSinkManager::OnUserOperation(int32_t action, const std::string ¶ms) @@ -717,27 +735,33 @@ AuthSrcManager::AuthSrcManager(std::shared_ptr softbusConnecto void AuthSrcManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) { + // todo LOGI("AuthSrcManager::OnSessionOpened start."); } void AuthSrcManager::OnSessionClosed(int32_t sessionId) { + // todo LOGI("AuthSrcManager::OnSessionClosed start."); } void AuthSrcManager::OnDataReceived(int32_t sessionId, std::string message) { + // todo LOGI("AuthSrcManager::OnDataReceived start."); } bool AuthSrcManager::GetIsCryptoSupport() { + // todo LOGI("AuthSrcManager::GetIsCryptoSupport start."); return false; } void AuthSrcManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string message) { + // todo LOGI("AuthSrcManager::OnAuthDeviceDataReceived start."); } void AuthSrcManager::GetRemoteDeviceId(std::string &deviceId) { + // todo LOGI("AuthSrcManager::GetRemoteDeviceId start."); } -- Gitee From 07b0b92c648257973fcba8ef8c90fe7ecbaef038 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Fri, 28 Feb 2025 18:02:39 +0800 Subject: [PATCH 025/382] =?UTF-8?q?fix:=20=E6=8F=90=E4=BE=9B90=E6=8A=A5?= =?UTF-8?q?=E6=96=87=E8=A1=A5=E5=85=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/auth_manager.h | 6 -- .../dm_auth_message_processor.h | 5 ++ .../auth_stages/auth_negotiate.cpp | 20 +++++- .../dm_auth_message_processor.cpp | 61 ++++++++++++------- 4 files changed, 64 insertions(+), 28 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 0ddcfd7e5..577de52da 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -36,12 +36,6 @@ const int32_t WAIT_REQUEST_TIMEOUT = 10; const int32_t HML_SESSION_TIMEOUT = 10; const int32_t AUTHENTICATE_TIMEOUT = 120; constexpr const char* DM_VERSION_5_1_0 = "5.1.0"; -// TODO: 黄蓝区同步,部分代码冲突,冲突时删除此处 -#if 0 -constexpr const char* PARAM_KEY_HML_ENABLE_160M = "hmlEnable160M"; -constexpr const char* PARAM_KEY_HML_ACTIONID = "hmlActionId"; -constexpr const char* PARAM_KEY_CONN_SESSIONTYPE = "connSessionType"; -#endif constexpr const char* BUNDLE_NAME_KEY = "bundleName"; // 取自security_device_auth中的identity_operation.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 index f2257c30e..ebd23f65b 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -73,6 +73,9 @@ constexpr const char *DM_TAG_USERSKID = "accesserUserSKId"; constexpr const char *DM_TAG_APPSK_TIMESTAMP = "accesserAppSKTimeStamp"; constexpr const char *DM_TAG_USERSK_TIMESTAMP = "accesserUserSKTimeStamp"; constexpr const char *DM_TAG_SYNC = "syncMessage"; +constexpr const char* TAG_IS_ONLINE = "isOnline"; +constexpr const char* TAG_IS_AUTHED = "isAuthed"; +constexpr const char* TAG_CREDENTIAL_INFO = "credentialInfo"; // 报文类型 enum DmMessageType { @@ -167,6 +170,8 @@ private: // 创建 80报文 void CreateNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject); + // 创建 90报文 + void CreateRespNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject); // 创建 100 报文 void CreateMessageReqUserConfirm(std::shared_ptr context, nlohmann::json &json); // 创建 110 报文 diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index cae47b95f..1025fc06e 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -219,6 +219,13 @@ bool AuthSinkNegotiateStateMachine::AclCompareFourIds(std::shared_ptr context) { @@ -273,12 +280,18 @@ int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptr invalidCredIds; + nlohmann::json packResult; // 需要打包发送到对端的数据 for (auto& [key, value] : queryResult.items()) { if (value.find("isAclActive") == value.end() || value["isAclActive"] == false) { - invalidCredIds.push_back(key); + continue; } + + packResult[key] = value["credType"]; } + context->accessee.isAuthed = !queryResult.empty(); + context->accessee.credentialInfos = SafetyDump(packResult); + return DM_OK; } @@ -304,6 +317,11 @@ int32_t AuthSinkNegotiateStateMachine::ProcRespNegotiate5_1_0(std::shared_ptraccessee.deviceIdHash = Crypto::Sha256(context->accessee.deviceId); + context->accessee.userIdHash = Crypto::Sha256(std::to_string(context->accessee.userId)); + context->accessee.accountIdHash = Crypto::Sha256(context->accessee.accountId); + context->accessee.tokenIdHash = Crypto::Sha256(std::to_string(context->accessee.tokenId)); + // 状态跳转在100报文中处理 return DM_OK; } diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index f781d5a6e..490782e67 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -297,6 +297,46 @@ int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr return DM_OK; } +// 创建80报文 +void DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject) +{ + // 目前未看到使用了cryptoAdapter_,删除 + jsonObject[TAG_DEVICE_VERSION] = context->accesser.dmVersion; + jsonObject[TAG_DEVICE_NAME] = context->accesser.deviceName; + + jsonObject[TAG_DEVICE_ID_HASH] = context->accesser.deviceIdHash; + jsonObject[TAG_USER_ID_HASH] = context->accesser.userIdHash; + jsonObject[TAG_ACCOUNT_ID_HASH] = context->accesser.accountIdHash; + jsonObject[TAG_TOKEN_ID_HASH] = context->accesser.tokenIdHash; + + jsonObject[TAG_BUNDLE_NAME] = context->accesser.bundleName; + jsonObject[TAG_PEER_BUNDLE_NAME] = context->accessee.bundleName; + jsonObject[TAG_BIND_LEVEL] = context->accesser.bindLevel; + // 暂无serviceId的定义 + // tokenId、deviceId是否有安全问题?暂未传输 + + return; +} + +// 创建90报文 +void DmAuthMessageProcessor::CreateRespNegotiateMessage(std::shared_ptr context, + nlohmann::json &jsonObject) +{ + jsonObject[TAG_DEVICE_VERSION] = context->accessee.dmVersion; + jsonObject[TAG_DEVICE_NAME] = context->accessee.deviceName; + + jsonObject[TAG_DEVICE_ID_HASH] = context->accessee.deviceIdHash; + jsonObject[TAG_USER_ID_HASH] = context->accessee.userIdHash; + jsonObject[TAG_ACCOUNT_ID_HASH] = context->accessee.accountIdHash; + jsonObject[TAG_TOKEN_ID_HASH] = context->accessee.tokenIdHash; + + jsonObject[TAG_BUNDLE_NAME] = context->accessee.bundleName; + jsonObject[TAG_IS_ONLINE] = context->isOnline; + jsonObject[TAG_IS_AUTHED] = context->accessee.isAuthed; + jsonObject[TAG_CREDENTIAL_INFO] = context->accessee.credentialInfos; + + return; +} // 创建140报文 void DmAuthMessageProcessor::CreateMessageReqCredExchange(std::shared_ptr context, @@ -366,27 +406,6 @@ void DmAuthMessageProcessor::CreateMessageReqCredAuthStart(std::shared_ptr context, nlohmann::json &jsonObject) -{ - // 目前未看到使用了cryptoAdapter_,删除 - jsonObject[TAG_DEVICE_VERSION] = context->accesser.dmVersion; - jsonObject[TAG_DEVICE_NAME] = context->accesser.deviceName; - - jsonObject[TAG_DEVICE_ID_HASH] = context->accesser.deviceIdHash; - jsonObject[TAG_USER_ID_HASH] = context->accesser.userIdHash; - jsonObject[TAG_ACCOUNT_ID_HASH] = context->accesser.accountIdHash; - jsonObject[TAG_TOKEN_ID_HASH] = context->accesser.tokenIdHash; - - jsonObject[TAG_BUNDLE_NAME] = context->accesser.bundleName; - jsonObject[TAG_PEER_BUNDLE_NAME] = context->accessee.bundleName; - jsonObject[TAG_BIND_LEVEL] = context->accesser.bindLevel; - // 暂无serviceId的定义 - // tokenId、deviceId是否有安全问题?暂未传输 - - return; -} - void DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject, std::shared_ptr context) { if (IsString(jsonObject, TAG_DEVICE_VERSION)) { -- Gitee From b0603d841feaedc89034f37ba01a89311d1b1551 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Feb 2025 18:38:00 +0800 Subject: [PATCH 026/382] tmp --- .../src/authentication_v2/auth_manager.cpp | 4 +++- .../authentication_v2/auth_stages/auth_confirm.cpp | 4 ++-- .../auth_stages/auth_credential.cpp | 12 ++++++++++-- .../authentication_v2/auth_stages/auth_pin_auth.cpp | 2 +- 4 files changed, 16 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index bcd2887ca..6baecb9ed 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -192,9 +192,11 @@ int32_t AuthManager::ParseAuthType(const std::map &bin authType = std::atoi(authTypeStr.c_str()); return DM_OK; } -void AuthManager::GeneratePincode(std::shared_ptr context) + +int32_t AuthManager::GeneratePincode(std::shared_ptr context) { context_->pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); + return context_->pinCode; } int32_t AuthManager::RegisterUiStateCallback(const std::string pkgName) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 9d7223de5..863e3bf80 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -53,7 +53,7 @@ DmAuthStateType AuthSrcConfirmState::GetStateType() int32_t AuthSrcConfirmState::Action(std::shared_ptr context) { LOGI("AuthSrcConfirmState::Action start"); -#if 0 +#if 0 // todo // 转结束绑定 // 转凭据认证 @@ -117,7 +117,7 @@ int32_t AuthSinkConfirmState::ShowConfigDialog(std::shared_ptr co LOGI("AuthSinkConfirmState::ShowConfigDialog end"); return DM_OK; } -#if 0 +#if 0 // todo int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context) { // DP 接口 查询ServiceInfoProfile diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 29475c5a0..d6ca7c5f9 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -39,7 +39,7 @@ static int32_t AuthCredentialTransmitDecryptProcess(std::shared_ptrhiChainAuthConnector->ProcessCredData(context->requestId, transmitStr); if (ret != DM_OK) { @@ -118,7 +118,11 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co uint8_t* sessionKey = nullptr; uint32_t sessionKeyLen = 0; sessionKeyLen = context->authMessageProcessor->cryptoMgr_->GetSessionKey(sessionKey); + #if 0 // todo ret = DeviceProfileConnector::PutSessionKey(sessionKey, sessionKeyLen, skId); // 保存到DP + #else + skId = 0; + #endif if (ret != DM_OK) { LOGE("AuthSrcCredentialAuthDoneState::Action DP save user session key failed"); return ret; @@ -217,7 +221,11 @@ int32_t AuthSinkCredentialAuthNegotiateState::Action(std::shared_ptrauthMessageProcessor->cryptoMgr_->GetSessionKey(sessionKey); - ret = DeviceProfileConnector::PutSessionKey(sessionKey, sessionKeyLen, skId); + #if 0 // todo + ret = DeviceProfileConnector::PutSessionKey(sessionKey, sessionKeyLen, skId); // 保存到DP + #else + skId = 0; + #endif if (ret != DM_OK) { LOGE("AuthSinkCredentialAuthNegotiateState::Action DP save user session key failed"); return ret; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 5c1c003b5..dbed2bc7c 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -117,7 +117,7 @@ int32_t AuthSrcPinAuthStartState::GetPinCodeFromServerInfo(std::shared_ptr serviceInfos; DistributedDeviceProfile::ServiceInfoUniqueKey key(context->accesser.deviceId, context->accesser.userId, context->accesser.tokenId, context->accesser.serviceId); -- Gitee From a1842ff676e37cb31e089e421f65e980ef787b07 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Feb 2025 18:46:33 +0800 Subject: [PATCH 027/382] tmp --- services/implementation/src/authentication_v2/auth_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 6baecb9ed..10170b4bb 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -193,7 +193,7 @@ int32_t AuthManager::ParseAuthType(const std::map &bin return DM_OK; } -int32_t AuthManager::GeneratePincode(std::shared_ptr context) +int32_t AuthManager::GeneratePincode() { context_->pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); return context_->pinCode; -- Gitee From 93bf06e2bd787d7035b9ca4159ee609bc4979dfd Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Feb 2025 19:12:42 +0800 Subject: [PATCH 028/382] tmp --- .../auth_stages/auth_confirm.cpp | 6 +++ .../dm_auth_message_processor.cpp | 41 ++++++++++++++++++- 2 files changed, 46 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 863e3bf80..a8c42416c 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -53,6 +53,12 @@ DmAuthStateType AuthSrcConfirmState::GetStateType() int32_t AuthSrcConfirmState::Action(std::shared_ptr context) { LOGI("AuthSrcConfirmState::Action start"); + context->timer->Deletetimer(std::string(NEGOTIATE_TIMEOUT_TASK)); + nlohmann::json jsonObject = nlohmann::json::parse(context->accessee.credentialInfos, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("AuthSrcConfirmState::Action parse credentialInfos error"); + return ERR_DM_FAILED; + } #if 0 // todo // 转结束绑定 diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 490782e67..5c2509774 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -444,7 +444,46 @@ void DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject, s int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const nlohmann::json &json, std::shared_ptr context) { - // todo + if (IsString(jsonObject, TAG_DEVICE_VERSION)) { + context->accessee.dmVersion = jsonObject[TAG_DEVICE_VERSION].get(); + } + + if (IsString(jsonObject, TAG_DEVICE_NAME)) { + context->accessee.deviceName = jsonObject[TAG_DEVICE_NAME].get(); + } + + if (IsString(jsonObject, TAG_DEVICE_ID_HASH)) { + context->accessee.deviceIdHash = jsonObject[TAG_DEVICE_ID_HASH].get(); + } + + if (IsString(jsonObject, TAG_USER_ID_HASH)) { + context->accessee.userIdHash = jsonObject[TAG_USER_ID_HASH].get(); + } + + if (IsString(jsonObject, TAG_ACCOUNT_ID_HASH)) { + context->accessee.accountIdHash = jsonObject[TAG_ACCOUNT_ID_HASH].get(); + } + + if (IsString(jsonObject, TAG_TOKEN_ID_HASH)) { + context->accessee.tokenIdHash = jsonObject[TAG_TOKEN_ID_HASH].get(); + } + + if (IsString(jsonObject, TAG_BUNDLE_NAME)) { + context->accessee.bundleName = jsonObject[TAG_BUNDLE_NAME].get(); + } + + if (IsBool(jsonObject, TAG_IS_ONLINE)) { + context->isOnline = jsonObject[TAG_IS_ONLINE].get(); + } + + if (IsBool(jsonObject, TAG_IS_AUTHED)) { + context->accessee.isAuthed = jsonObject[TAG_IS_AUTHED].get(); + } + + if (IsString(jsonObject, TAG_CREDENTIAL_INFO)) { + context->accessee.credentialInfos = jsonObject[TAG_CREDENTIAL_INFO].get(); + } + return DM_OK; } int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const nlohmann::json &json, -- Gitee From f35d31ec46dade8d505e9a4fa29648c03138df45 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Feb 2025 19:16:07 +0800 Subject: [PATCH 029/382] tmp --- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index a8c42416c..498dd723e 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -53,7 +53,7 @@ DmAuthStateType AuthSrcConfirmState::GetStateType() int32_t AuthSrcConfirmState::Action(std::shared_ptr context) { LOGI("AuthSrcConfirmState::Action start"); - context->timer->Deletetimer(std::string(NEGOTIATE_TIMEOUT_TASK)); + context->timer->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); nlohmann::json jsonObject = nlohmann::json::parse(context->accessee.credentialInfos, nullptr, false); if (jsonObject.is_discarded()) { LOGE("AuthSrcConfirmState::Action parse credentialInfos error"); -- Gitee From 85f1dbf2b73d122e016a6fb5d44fff39c0fec061 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Feb 2025 19:18:50 +0800 Subject: [PATCH 030/382] tmp --- .../src/authentication_v2/dm_auth_message_processor.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 5c2509774..acc610f32 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -441,11 +441,11 @@ void DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject, s return; } -int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const nlohmann::json &json, +int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const nlohmann::json &jsonObject, std::shared_ptr context) { if (IsString(jsonObject, TAG_DEVICE_VERSION)) { - context->accessee.dmVersion = jsonObject[TAG_DEVICE_VERSION].get(); + context->accessee.dmVersion = json[TAG_DEVICE_VERSION].get(); } if (IsString(jsonObject, TAG_DEVICE_NAME)) { -- Gitee From d896ca1e0393823feb4439a1863cb84df5d6aa8c Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Feb 2025 19:23:06 +0800 Subject: [PATCH 031/382] tmp --- .../src/authentication_v2/dm_auth_message_processor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index acc610f32..615ec72ed 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -445,7 +445,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const nlohmann::jso std::shared_ptr context) { if (IsString(jsonObject, TAG_DEVICE_VERSION)) { - context->accessee.dmVersion = json[TAG_DEVICE_VERSION].get(); + context->accessee.dmVersion = jsonObject[TAG_DEVICE_VERSION].get(); } if (IsString(jsonObject, TAG_DEVICE_NAME)) { -- Gitee From 766f98da58991900c7322bedf9e140a5b4c46353 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Feb 2025 19:45:14 +0800 Subject: [PATCH 032/382] tmp --- .../implementation/include/device_manager_service_impl.h | 2 +- services/implementation/src/device_manager_service_impl.cpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index a63a51b03..5f9bb02cb 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -158,7 +158,7 @@ private: int32_t InitAndRegisterAuthMgr(bool isSrcSide); private: - std::shared_ptr authMgr_; + std::shared_ptr authMgr_; std::shared_ptr deviceStateMgr_; std::shared_ptr softbusConnector_; std::shared_ptr abilityMgr_; diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index f69478813..8429eb772 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -48,14 +48,14 @@ int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide) { if (authMgr_ == nullptr) { if (isSrcSide) { - authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, listener_, + authMgr_ = std::make_shared(softbusConnector_, listener_, hiChainAuthConnector_); } else { - authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, listener_, + authMgr_ = std::make_shared(softbusConnector_, listener_, hiChainAuthConnector_); } softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); - hiChainConnector_->RegisterHiChainCallback(authMgr_); + // hiChainConnector_->RegisterHiChainCallback(authMgr_); hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); } else { // 线程已创建authMgr_,说明已有绑定事件,其他请求拒绝,返回错误码 -- Gitee From c7a12950317ecb0118cda1960d8a19d17525ca43 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 11:44:17 +0800 Subject: [PATCH 033/382] tmp --- .../implementation/src/authentication_v2/auth_manager.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 10170b4bb..5c157a957 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -195,6 +195,7 @@ int32_t AuthManager::ParseAuthType(const std::map &bin int32_t AuthManager::GeneratePincode() { + LOGI("AuthManager::GeneratePincode start"); context_->pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); return context_->pinCode; } @@ -681,7 +682,7 @@ bool AuthSinkManager::GetIsCryptoSupport() { // todo LOGI("AuthSinkManager::GetIsCryptoSupport start."); - return false; + return true; } void AuthSinkManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string message) { @@ -754,7 +755,7 @@ bool AuthSrcManager::GetIsCryptoSupport() { // todo LOGI("AuthSrcManager::GetIsCryptoSupport start."); - return false; + return true; } void AuthSrcManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string message) { -- Gitee From b2542ddd68246b058ea437f0e2c462b1580b972b Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 14:32:40 +0800 Subject: [PATCH 034/382] tmp --- common/include/dm_error_type.h | 4 +++- .../include/authentication_v2/auth_manager.h | 8 ++++++++ .../include/authentication_v2/dm_auth_state.h | 4 +--- .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 6 +++--- 4 files changed, 15 insertions(+), 7 deletions(-) diff --git a/common/include/dm_error_type.h b/common/include/dm_error_type.h index 06b2f8824..81fca4823 100644 --- a/common/include/dm_error_type.h +++ b/common/include/dm_error_type.h @@ -117,7 +117,9 @@ enum { ERR_DM_HILINKSVC_DISCONNECT = 96929829, ERR_DM_WISE_NEED_LOGIN = 96929830, ERR_DM_NAME_EMPTY = 96929831, - ERR_DM_HICHAIN_PROOFMISMATCH = 96929832 + ERR_DM_HICHAIN_PROOFMISMATCH = 96929832, + ERR_DM_NEXT_STATE_INVALID = 96929833, + ERR_DM_GET_SESSION_KEY_FAILED = 96929834, }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 577de52da..5299da3f1 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -38,6 +38,14 @@ const int32_t AUTHENTICATE_TIMEOUT = 120; constexpr const char* DM_VERSION_5_1_0 = "5.1.0"; constexpr const char* BUNDLE_NAME_KEY = "bundleName"; +constexpr const char* NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:negotiate"; +constexpr const char* CONFIRM_TIMEOUT_TASK = "deviceManagerTimer:confirm"; +constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; +constexpr const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; +constexpr const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; +constexpr const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; + + // 取自security_device_auth中的identity_operation.h,该头文件为内部头文件,不能直接引用 // 若冲突删除此处 enum { diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 3719fad2f..d2c6fb1c3 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -19,12 +19,10 @@ #include #include "access_control_profile.h" -#include "dm_auth_state.h" #include "dm_auth_context.h" namespace OHOS { namespace DistributedHardware { - // 状态类型 enum class DmAuthStateType { AUTH_IDLE_STATE = 0, // 设备初始化时 @@ -265,7 +263,7 @@ public: private: int32_t RespQueryAcceseeIds(std::shared_ptr context); bool HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList); - int32_t GetCredentialType(std::shared_ptr context, nlohmann::json credInfo); + uint32_t GetCredentialType(std::shared_ptr context, nlohmann::json credInfo); bool AclCompareTwoIds(std::shared_ptr context, const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); bool AclCompareFourIds(std::shared_ptr context, diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 1025fc06e..9d3b6e231 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -166,7 +166,7 @@ bool AuthSinkNegotiateStateMachine::HaveSameTokenId(std::shared_ptr context, nlohmann::json credInfo) +uint32_t AuthSinkNegotiateStateMachine::GetCredentialType(std::shared_ptr context, nlohmann::json credInfo) { // 判断是否同账号 // TODO: 需要确定截断长度 @@ -250,7 +250,7 @@ int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptr profiles = + std::vector profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfile(); bool isAclActive = false; for (auto &item : profiles) { @@ -264,7 +264,7 @@ int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptr Date: Mon, 3 Mar 2025 14:37:11 +0800 Subject: [PATCH 035/382] tmp --- .../include/authentication_v2/auth_manager.h | 8 -------- .../include/authentication_v2/dm_auth_state.h | 7 +++++++ 2 files changed, 7 insertions(+), 8 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 5299da3f1..577de52da 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -38,14 +38,6 @@ const int32_t AUTHENTICATE_TIMEOUT = 120; constexpr const char* DM_VERSION_5_1_0 = "5.1.0"; constexpr const char* BUNDLE_NAME_KEY = "bundleName"; -constexpr const char* NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:negotiate"; -constexpr const char* CONFIRM_TIMEOUT_TASK = "deviceManagerTimer:confirm"; -constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; -constexpr const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; -constexpr const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; -constexpr const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; - - // 取自security_device_auth中的identity_operation.h,该头文件为内部头文件,不能直接引用 // 若冲突删除此处 enum { diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index d2c6fb1c3..cc763b813 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -21,6 +21,13 @@ #include "access_control_profile.h" #include "dm_auth_context.h" +constexpr const char* NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:negotiate"; +constexpr const char* CONFIRM_TIMEOUT_TASK = "deviceManagerTimer:confirm"; +constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; +constexpr const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; +constexpr const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; +constexpr const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; + namespace OHOS { namespace DistributedHardware { // 状态类型 -- Gitee From 4035303eea919ff29d9fff31a00dd427b83b8d8c Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 14:44:37 +0800 Subject: [PATCH 036/382] tmp --- .../implementation/include/authentication_v2/dm_auth_state.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index cc763b813..ed09232ba 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -21,12 +21,14 @@ #include "access_control_profile.h" #include "dm_auth_context.h" +constexpr const char* AUTHENTICATE_TIMEOUT_TASK = "deviceManagerTimer:authenticate"; constexpr const char* NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:negotiate"; constexpr const char* CONFIRM_TIMEOUT_TASK = "deviceManagerTimer:confirm"; constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; constexpr const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; constexpr const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; constexpr const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; +constexpr const char* ADD_TIMEOUT_TASK = "deviceManagerTimer:add"; namespace OHOS { namespace DistributedHardware { -- Gitee From 4c416c3cc922c9caec59264261cbc59741ce3a1c Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 14:58:45 +0800 Subject: [PATCH 037/382] tmp --- .../src/authentication_v2/auth_stages/auth_credential.cpp | 2 ++ .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 2 ++ .../implementation/src/authentication_v2/dm_auth_context.cpp | 2 ++ .../src/authentication_v2/dm_auth_message_processor.cpp | 2 ++ .../src/authentication_v2/dm_auth_state_machine.cpp | 2 ++ 5 files changed, 10 insertions(+) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index d6ca7c5f9..85b8c3741 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -25,6 +25,8 @@ #include "multiple_user_connector.h" #include "deviceprofile_connector.h" #include "hichain_auth_connector.h" +#undef LOG_TAG +#define LOG_TAG "DHDM_V2" namespace OHOS { namespace DistributedHardware { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 9d3b6e231..dd757ced9 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -34,6 +34,8 @@ #include "dm_auth_context.h" #include "auth_manager.h" #include "dm_auth_state.h" +#undef LOG_TAG +#define LOG_TAG "DHDM_V2" namespace OHOS { namespace DistributedHardware { diff --git a/services/implementation/src/authentication_v2/dm_auth_context.cpp b/services/implementation/src/authentication_v2/dm_auth_context.cpp index 58f7a24b3..1ffe1eb5e 100644 --- a/services/implementation/src/authentication_v2/dm_auth_context.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_context.cpp @@ -14,6 +14,8 @@ */ #include "dm_auth_context.h" +#undef LOG_TAG +#define LOG_TAG "DHDM_V2" namespace OHOS { namespace DistributedHardware { diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 615ec72ed..eaa9c9d6a 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -26,6 +26,8 @@ #include "access_control_profile.h" #include "dm_auth_context.h" #include "dm_auth_state_machine.h" +#undef LOG_TAG +#define LOG_TAG "DHDM_V2" namespace OHOS { namespace DistributedHardware { diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 11791d0a4..9e72af88d 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -19,6 +19,8 @@ #include "dm_auth_context.h" #include "dm_auth_state_machine.h" +#undef LOG_TAG +#define LOG_TAG "DHDM_V2" namespace OHOS { namespace DistributedHardware { -- Gitee From 203537cad12f0e8d8290249d68ca16eea1351fc4 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 15:31:03 +0800 Subject: [PATCH 038/382] tmp --- .../include/authentication_v2/dm_auth_context.h | 12 ++++++------ .../src/authentication_v2/auth_manager.cpp | 3 +++ 2 files changed, 9 insertions(+), 6 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index a146b51fa..0a245e220 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -43,10 +43,10 @@ class DmAuthMessageProcessor; // PIN码认证类型 typedef enum { - AUTH_TYPE_PIN_SHOW = 0, // 弹PIN码 - AUTH_TYPE_PIN_ULTRASONIC, // 超声PIN码 - AUTH_TYPE_PIN_IMPORT, // 导入PIN码 - AUTH_TYPE_IMPORT_AUTH_CODE, // 导入认证码 + AUTH_TYPE_PIN_SHOW = 1, // 弹PIN码 + AUTH_TYPE_PIN_ULTRASONIC = 2, // 超声PIN码 + AUTH_TYPE_PIN_IMPORT = 3, // 导入PIN码 + AUTH_TYPE_IMPORT_AUTH_CODE = 5, // 导入认证码 } DmAuthType; enum DmAuthDirection { @@ -133,7 +133,7 @@ struct DmAuthContext { int32_t sessionId; // 总线传输会话ID int64_t requestId; // hichain认证ID UiAction authResult; // 授权结果(使用0、1、6,即单次,取消和始终信任,enum UiAction) - DmAuthType authType; // 认证方式,弹pin码、超声pin码、导入pin码 + DmAuthType authType{DmAuthType::AUTH_TYPE_PIN_SHOW}; // 认证方式,弹pin码、超声pin码、导入pin码 int32_t authFailTimes{0}; // 认证失败次数,查过3次结束认证 int32_t pinCode; // 保存业务导入的pin码 int32_t connDelayCloseTime; // 链路延迟释放时间, 授权结束后不自动断链(有业务需要使用)保留字段 @@ -146,7 +146,7 @@ struct DmAuthContext { int32_t hmlActionId = 0; bool normalFinishAuth; // 标识认证过程是否正常结束 bool authenticating; // 标识正在认证中 - bool isAppCredentailVerified = false; // 标识用户凭据是否认证 + bool isAppCredentailVerified = false; // 标识用户凭据是否认证 bool hmlEnable160M = false; std::string pkgName; // 业务传入的标识,业务自定义,有被仿冒的风险 std::string pkgLabel; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 5c157a957..889309fca 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -155,6 +155,9 @@ AuthManager::AuthManager(std::shared_ptr softbusConnector, context_->authUiStateMgr = std::make_shared(context_->listener); context_->authenticationMap[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; + context_->authenticationMap[AUTH_TYPE_PIN_SHOW] = nullptr; + context_->authenticationMap[AUTH_TYPE_PIN_ULTRASONIC] = nullptr; + context_->authenticationMap[AUTH_TYPE_PIN_IMPORT] = nullptr; context_->accesser.dmVersion = DM_VERSION_5_1_0; context_->accessee.dmVersion = DM_VERSION_5_1_0; } -- Gitee From 3dbae76e788ce82485be9032c30215574841c46b Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 16:02:44 +0800 Subject: [PATCH 039/382] tmp --- .../src/authentication_v2/auth_manager.cpp | 3 +- .../dm_auth_state_machine.cpp | 28 +++++++++++-------- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 889309fca..f1d8089cf 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -160,6 +160,7 @@ AuthManager::AuthManager(std::shared_ptr softbusConnector, context_->authenticationMap[AUTH_TYPE_PIN_IMPORT] = nullptr; context_->accesser.dmVersion = DM_VERSION_5_1_0; context_->accessee.dmVersion = DM_VERSION_5_1_0; + context_->authStateMachine = std::make_shared(context_); } void AuthManager::SetAuthContext(std::shared_ptr context) @@ -584,7 +585,6 @@ void AuthManager::InitAuthState(const std::string &pkgName, int32_t authType, }); context_->authMessageProcessor = std::make_shared(); GetAuthParam(pkgName, authType, deviceId, extra); - context_->authStateMachine = std::make_shared(context_); LOGI("AuthManager::AuthenticateDevice complete"); return; @@ -621,6 +621,7 @@ int32_t AuthManager::AuthenticateDevice(const std::string &pkgName, int32_t auth // return DM_OK; // } InitAuthState(pkgName, authType, deviceId, extra); + context_->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 9e72af88d..dee3218c1 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -30,26 +30,32 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) { stateTransitionTable_ = { // 此处省略下一状态为AuthXXXFinishState的迁移情况 // Source端 状态迁移表 - {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SRC_START_STATE}}, - {DmAuthStateType::AUTH_SRC_START_STATE, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE}}, + {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE}}, + //{DmAuthStateType::AUTH_SRC_START_STATE, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE}}, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE}}, - {DmAuthStateType::AUTH_SRC_CONFIRM_STATE, {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE}}, + {DmAuthStateType::AUTH_SRC_CONFIRM_STATE, {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, + DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, // to check {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, {DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, - DmAuthStateType::AUTH_SINK_CONFIRM_STATE}}, // PIN输入错误,3次内会回到AuthSinkConfirmState - {DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE}}, - {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE}}, + DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE}}, + {DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, + DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE}}, + {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, + DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE}}, {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE}}, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE}}, {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, {}}, // Sink端 状态迁移表 - {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SINK_START_STATE}}, - {DmAuthStateType::AUTH_SINK_START_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, - {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SINK_CONFIRM_STATE}}, + {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, + //{DmAuthStateType::AUTH_SINK_START_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, + {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, + DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, // to check {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, {DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE}}, - {DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, {DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE}}, - {DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE}}, + {DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, {DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, + DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE}}, + {DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, + DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE}}, {DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE}}, {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, -- Gitee From fd746b0bfd6e6fe4d8560b09b8caeae0bfaf7410 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 16:06:26 +0800 Subject: [PATCH 040/382] tmp --- services/implementation/src/authentication_v2/auth_manager.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index f1d8089cf..bc05c4ed3 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -35,6 +35,7 @@ #include "dm_auth_context.h" #include "dm_auth_message_processor.h" #include "auth_manager.h" +#include "auth_state.h" #undef LOG_TAG #define LOG_TAG "DHDM_V2" @@ -621,7 +622,7 @@ int32_t AuthManager::AuthenticateDevice(const std::string &pkgName, int32_t auth // return DM_OK; // } InitAuthState(pkgName, authType, deviceId, extra); - context_->authStateMachine->TransitionTo(std::make_shared()); + context_->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } -- Gitee From 6d791639d349ad3a78c9139abd89989974e12561 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 16:25:20 +0800 Subject: [PATCH 041/382] tmp --- services/implementation/src/authentication_v2/auth_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index bc05c4ed3..cd3c1baee 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -35,7 +35,7 @@ #include "dm_auth_context.h" #include "dm_auth_message_processor.h" #include "auth_manager.h" -#include "auth_state.h" +#include "dm_auth_state.h" #undef LOG_TAG #define LOG_TAG "DHDM_V2" -- Gitee From c403f1bb94f71d8ac38fe2f254873afd700083c6 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 16:29:26 +0800 Subject: [PATCH 042/382] tmp --- .../src/authentication_v2/dm_auth_message_processor.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index eaa9c9d6a..25b7e8888 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -486,6 +486,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const nlohmann::jso context->accessee.credentialInfos = jsonObject[TAG_CREDENTIAL_INFO].get(); } + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const nlohmann::json &json, -- Gitee From 784ced57ccbb51eeb637dd1baeaea7df38e1b79f Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 16:35:27 +0800 Subject: [PATCH 043/382] tmp --- .../authentication_v2/auth_stages/auth_negotiate.cpp | 11 +++++++++++ 1 file changed, 11 insertions(+) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index dd757ced9..c475e5af4 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -40,6 +40,12 @@ namespace OHOS { namespace DistributedHardware { + +DmAuthStateType AuthSrcNegotiateStateMachine::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE; +} + int32_t AuthSrcNegotiateStateMachine::Action(std::shared_ptr context) { LOGI("AuthSrcNegotiateStateMachine::Action sessionId %{public}d.", context->sessionId); @@ -84,6 +90,11 @@ int32_t AuthSrcNegotiateStateMachine::Action(std::shared_ptr cont return DM_OK; } +DmAuthStateType AuthSinkNegotiateStateMachine::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE; +} + int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptr context) { int32_t ret; -- Gitee From 5eea781bb9bf5e765df8979cbb4e0c8c87f18cb1 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 16:42:51 +0800 Subject: [PATCH 044/382] =?UTF-8?q?feat:=20=E5=AE=8C=E6=88=90OnXx=E7=9B=B8?= =?UTF-8?q?=E5=85=B3=E5=8A=9F=E8=83=BD?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/auth_manager.h | 1 + .../dm_auth_message_processor.h | 22 +-- .../include/authentication_v2/dm_auth_state.h | 5 +- .../src/authentication_v2/auth_manager.cpp | 159 +++++++++++++++--- 4 files changed, 151 insertions(+), 36 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 577de52da..9c54b7dea 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -33,6 +33,7 @@ const int32_t MIN_PIN_TOKEN = 10000000; const int32_t MAX_PIN_TOKEN = 90000000; const int32_t NEGOTIATE_TIMEOUT = 10; const int32_t WAIT_REQUEST_TIMEOUT = 10; +const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; const int32_t HML_SESSION_TIMEOUT = 10; const int32_t AUTHENTICATE_TIMEOUT = 120; constexpr const char* DM_VERSION_5_1_0 = "5.1.0"; diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index ebd23f65b..36e4aeee7 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -29,6 +29,7 @@ struct DmAccess; constexpr const char *DM_TAG_MSG_TYPE = "messageType"; // 报文类型 constexpr const char *DM_TAG_DATA = "data"; // 报文数据 +constexpr const char* DM_TAG_DATA_LEN = "dataLen"; constexpr const char *DM_TAG_USER_PUBLICK_KEY = "userPublicKey"; // 用户级公钥 userPublicKey constexpr const char *DM_TAG_APP_PUBLICK_KEY = "appPublicKey"; // 应用级公钥 appPublicKey constexpr const char *DM_TAG_USER_CREDENTIAL_ID = "userCredentialId"; // 用户级凭据Id @@ -50,6 +51,17 @@ constexpr const char *DM_TAG_AUTHRIZED_APP_LIST = "authorizedAppList"; constexpr const char *DM_TAG_CREDENTIAL_OWNER = "credentialOwner"; constexpr const char *DM_AUTH_CREDENTIAL_OWNER = "DM"; // 凭据拥有者 constexpr const char *DM_TAG_TOKEN_ID = "tokenId"; +constexpr const char *DM_TAG_SYNC = "syncMessage"; +constexpr const char *DM_TAG_DMVERSION = "dmVersion"; +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_SERVICEINFO = "serviceInfo"; +constexpr const char *DM_TAG_APPSKID = "accesserAppSKId"; +constexpr const char *DM_TAG_USERSKID = "accesserUserSKId"; +constexpr const char *DM_TAG_APPSK_TIMESTAMP = "accesserAppSKTimeStamp"; +constexpr const char *DM_TAG_USERSK_TIMESTAMP = "accesserUserSKTimeStamp"; + constexpr const char* APP_OPERATION_KEY = "appOperation"; constexpr const char* APP_THUMBNAIL = "appThumbnail"; constexpr const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; @@ -63,16 +75,6 @@ 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_PKG_NAME = "pkgName"; -constexpr const char *DM_TAG_DMVERSION = "dmVersion"; -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_SERVICEINFO = "serviceInfo"; -constexpr const char *DM_TAG_APPSKID = "accesserAppSKId"; -constexpr const char *DM_TAG_USERSKID = "accesserUserSKId"; -constexpr const char *DM_TAG_APPSK_TIMESTAMP = "accesserAppSKTimeStamp"; -constexpr const char *DM_TAG_USERSK_TIMESTAMP = "accesserUserSKTimeStamp"; -constexpr const char *DM_TAG_SYNC = "syncMessage"; constexpr const char* TAG_IS_ONLINE = "isOnline"; constexpr const char* TAG_IS_AUTHED = "isAuthed"; constexpr const char* TAG_CREDENTIAL_INFO = "credentialInfo"; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index ed09232ba..ef4dd9010 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -21,6 +21,9 @@ #include "access_control_profile.h" #include "dm_auth_context.h" +namespace OHOS { +namespace DistributedHardware { + constexpr const char* AUTHENTICATE_TIMEOUT_TASK = "deviceManagerTimer:authenticate"; constexpr const char* NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:negotiate"; constexpr const char* CONFIRM_TIMEOUT_TASK = "deviceManagerTimer:confirm"; @@ -30,8 +33,6 @@ constexpr const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_ constexpr const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; constexpr const char* ADD_TIMEOUT_TASK = "deviceManagerTimer:add"; -namespace OHOS { -namespace DistributedHardware { // 状态类型 enum class DmAuthStateType { AUTH_IDLE_STATE = 0, // 设备初始化时 diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index cd3c1baee..3c0c0954b 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -668,36 +668,97 @@ AuthSinkManager::AuthSinkManager(std::shared_ptr softbusConnec : AuthManager(softbusConnector, listener, hiChainAuthConnector) { } + void AuthSinkManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) { - // todo - LOGI("AuthSinkManager::OnSessionOpened start."); + LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result); + if (context_->authMessageProcessor == nullptr) { + // authMessage为空,开始初始化 + context_->authMessageProcessor = std::make_shared(); + context_->sessionId = sessionId; + context_->timer = std::make_shared(); + context_->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context_, AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), + [this] (std::string name) { DmAuthState::HandleAuthenticateTimeout(context_, name); + }); + context_->timer->StartTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context_, WAIT_NEGOTIATE_TIMEOUT_TASK, WAIT_NEGOTIATE_TIMEOUT), + [this] (std::string name) { DmAuthState::HandleAuthenticateTimeout(context_, name); + }); + } else { + context_->reply = ERR_DM_AUTH_BUSINESS_BUSY; + std::string message = context_->authMessageProcessor->CreateMessage(MSG_TYPE_AUTH_TERMINATE, context_); + context_->softbusConnector->GetSoftbusSession()->SendData(sessionId, message); + } + + return; } + void AuthSinkManager::OnSessionClosed(int32_t sessionId) { - // todo - LOGI("AuthSinkManager::OnSessionClosed start."); + LOGI("AuthSrcManager::OnSessionClosed sessionId = %{public}d", sessionId); } + void AuthSinkManager::OnDataReceived(int32_t sessionId, std::string message) { - // todo - LOGI("AuthSinkManager::OnDataReceived start."); + if (context_->authMessageProcessor == nullptr) { + LOGE("OnDataReceived failed, authMessageProcessor is nullptr."); + return; + } + + context_->sessionId = sessionId; + int32_t ret = context_->authMessageProcessor->ParseMessage(context_, message); + if (ret != DM_OK) { + LOGE("OnDataReceived failed, parse input message error."); + } + + return; } + bool AuthSinkManager::GetIsCryptoSupport() { - // todo - LOGI("AuthSinkManager::GetIsCryptoSupport start."); + if (context_->authStateMachine->GetCurState() != DmAuthStateType::AUTH_SINK_FINISH_STATE) { + return false; + } + + // TODO: 当前是否还需要isCryptoSupport_,还是说通过已经没有TAG_CRYPTO_SUPPORT了 return true; } + void AuthSinkManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string message) { - // todo - LOGI("AuthSinkManager::OnAuthDeviceDataReceived start."); + if (context_->hiChainAuthConnector == nullptr) { + LOGE("OnAuthDeviceDataReceived param is invalid"); + return; + } + + if (context_->sessionId != sessionId) { + LOGE("OnAuthDeviceDataReceived unmatched sessionId"); + return; + } + + nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return; + } + if (!IsString(jsonObject, DM_TAG_DATA) || !IsInt32(jsonObject, DM_TAG_DATA_LEN) || + !IsInt32(jsonObject, TAG_MSG_TYPE)) { + LOGE("Auth device data is error."); + return; + } + LOGI("OnAuthDeviceDataReceived start msgType %{public}d.", jsonObject[TAG_MSG_TYPE].get()); + std::string authData = jsonObject[DM_TAG_DATA].get(); + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + context_->hiChainAuthConnector->ProcessAuthData(context_->requestId, authData, osAccountId); + + return; } + void AuthSinkManager::GetRemoteDeviceId(std::string &deviceId) { - // todo - LOGI("AuthSinkManager::GetRemoteDeviceId start."); + deviceId = (context_->direction == DM_AUTH_SOURCE) ? context_->accessee.deviceId : context_->accesser.deviceId; + return; } int32_t AuthSinkManager::OnUserOperation(int32_t action, const std::string ¶ms) { @@ -743,34 +804,84 @@ AuthSrcManager::AuthSrcManager(std::shared_ptr softbusConnecto void AuthSrcManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) { - // todo - LOGI("AuthSrcManager::OnSessionOpened start."); + LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result); + + if (context_->authMessageProcessor == nullptr) { + context_->softbusConnector->GetSoftbusSession()->CloseAuthSession(sessionId); + LOGE("AuthSrcManager::OnSessionOpened but request state is wrong"); + return; + } + + context_->sessionId = sessionId; + context_->authStateMachine->TransitionTo(std::make_shared()); + struct RadarInfo info = { .funcName = "OnSessionOpened" }; + info.channelId = sessionId; + DmRadarHelper::GetInstance().ReportAuthSendRequest(info); + + return; } + void AuthSrcManager::OnSessionClosed(int32_t sessionId) { - // todo - LOGI("AuthSrcManager::OnSessionClosed start."); + LOGI("AuthSrcManager::OnSessionClosed sessionId = %{public}d", sessionId); } void AuthSrcManager::OnDataReceived(int32_t sessionId, std::string message) { - // todo - LOGI("AuthSrcManager::OnDataReceived start."); + if (context_->authMessageProcessor == nullptr) { + LOGE("OnDataReceived failed, authMessageProcessor is nullptr."); + return; + } + + context_->sessionId = sessionId; + int32_t ret = context_->authMessageProcessor->ParseMessage(context_, message); + if (ret != DM_OK) { + LOGE("OnDataReceived failed, parse input message error."); + } + + return; } bool AuthSrcManager::GetIsCryptoSupport() { - // todo - LOGI("AuthSrcManager::GetIsCryptoSupport start."); + if (context_->authStateMachine->GetCurState() != DmAuthStateType::AUTH_SRC_FINISH_STATE) { + return false; + } + + // TODO: 当前是否还需要isCryptoSupport_,还是说通过已经没有TAG_CRYPTO_SUPPORT了 return true; } void AuthSrcManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string message) { - // todo - LOGI("AuthSrcManager::OnAuthDeviceDataReceived start."); + if (context_->hiChainAuthConnector == nullptr) { + LOGE("OnAuthDeviceDataReceived param is invalid"); + return; + } + + if (context_->sessionId != sessionId) { + LOGE("OnAuthDeviceDataReceived unmatched sessionId"); + return; + } + + nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("DecodeRequestAuth jsonStr error"); + return; + } + if (!IsString(jsonObject, DM_TAG_DATA) || !IsInt32(jsonObject, DM_TAG_DATA_LEN) || + !IsInt32(jsonObject, TAG_MSG_TYPE)) { + LOGE("Auth device data is error."); + return; + } + LOGI("OnAuthDeviceDataReceived start msgType %{public}d.", jsonObject[TAG_MSG_TYPE].get()); + std::string authData = jsonObject[DM_TAG_DATA].get(); + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + context_->hiChainAuthConnector->ProcessAuthData(context_->requestId, authData, osAccountId); + + return; } void AuthSrcManager::GetRemoteDeviceId(std::string &deviceId) { - // todo - LOGI("AuthSrcManager::GetRemoteDeviceId start."); + deviceId = (context_->direction == DM_AUTH_SOURCE) ? context_->accessee.deviceId : context_->accesser.deviceId; + return; } int32_t AuthSrcManager::OnUserOperation(int32_t action, const std::string ¶ms) -- Gitee From eba6223995dbca5383e32c988840f507789c545c Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 16:53:22 +0800 Subject: [PATCH 045/382] tmp --- .../implementation/src/authentication_v2/auth_manager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 3c0c0954b..84f2a07ae 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -161,7 +161,6 @@ AuthManager::AuthManager(std::shared_ptr softbusConnector, context_->authenticationMap[AUTH_TYPE_PIN_IMPORT] = nullptr; context_->accesser.dmVersion = DM_VERSION_5_1_0; context_->accessee.dmVersion = DM_VERSION_5_1_0; - context_->authStateMachine = std::make_shared(context_); } void AuthManager::SetAuthContext(std::shared_ptr context) @@ -586,6 +585,7 @@ void AuthManager::InitAuthState(const std::string &pkgName, int32_t authType, }); context_->authMessageProcessor = std::make_shared(); GetAuthParam(pkgName, authType, deviceId, extra); + context_->authStateMachine = std::make_shared(context_); LOGI("AuthManager::AuthenticateDevice complete"); return; @@ -622,7 +622,6 @@ int32_t AuthManager::AuthenticateDevice(const std::string &pkgName, int32_t auth // return DM_OK; // } InitAuthState(pkgName, authType, deviceId, extra); - context_->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -675,6 +674,7 @@ void AuthSinkManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, in if (context_->authMessageProcessor == nullptr) { // authMessage为空,开始初始化 context_->authMessageProcessor = std::make_shared(); + context_->authStateMachine = std::make_shared(context_); context_->sessionId = sessionId; context_->timer = std::make_shared(); context_->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), -- Gitee From 06f166cbc854bda0494732d5b6c8338cebf79ca4 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 17:49:24 +0800 Subject: [PATCH 046/382] add src start state --- .../include/authentication_v2/dm_auth_state.h | 7 +++++++ .../implementation/src/authentication_v2/auth_manager.cpp | 1 + .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 4 ++++ .../src/authentication_v2/dm_auth_state_machine.cpp | 4 ++-- 4 files changed, 14 insertions(+), 2 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index ef4dd9010..ce74f9e3b 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -190,6 +190,13 @@ public: 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() {}; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 84f2a07ae..bbc7b28e6 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -586,6 +586,7 @@ void AuthManager::InitAuthState(const std::string &pkgName, int32_t authType, context_->authMessageProcessor = std::make_shared(); GetAuthParam(pkgName, authType, deviceId, extra); context_->authStateMachine = std::make_shared(context_); + context_->authStateMachine->TransitionTo(std::make_shared()); LOGI("AuthManager::AuthenticateDevice complete"); return; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index c475e5af4..9e5d59ac2 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -40,6 +40,10 @@ namespace OHOS { namespace DistributedHardware { +DmAuthStateType AuthSrcStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_START_STATE; +} DmAuthStateType AuthSrcNegotiateStateMachine::GetStateType() { diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index dee3218c1..61b526bdb 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -30,8 +30,8 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) { stateTransitionTable_ = { // 此处省略下一状态为AuthXXXFinishState的迁移情况 // Source端 状态迁移表 - {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE}}, - //{DmAuthStateType::AUTH_SRC_START_STATE, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE}}, + {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SRC_START_STATE}}, + {DmAuthStateType::AUTH_SRC_START_STATE, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE}}, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE}}, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE, {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, // to check -- Gitee From 4ae70331ffe13cdb3df7b662062ef456bcc5248f Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 17:55:58 +0800 Subject: [PATCH 047/382] =?UTF-8?q?feat:=20=E5=AE=9E=E7=8E=B0authStart?= =?UTF-8?q?=E7=9A=84action?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/auth_manager.h | 2 + .../src/authentication_v2/auth_manager.cpp | 12 +++--- .../auth_stages/auth_negotiate.cpp | 38 +++++++++++++++++++ 3 files changed, 45 insertions(+), 7 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 9c54b7dea..f61dcfb53 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -125,6 +125,8 @@ public: void HandleDeviceNotTrust(const std::string &udid); int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); int32_t RegisterAuthenticationType(int32_t authenticationType); + + static bool IsHmlSessionType(std::string sessionType); protected: // 上下文(需在该层级进行创建) std::shared_ptr context_; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index bbc7b28e6..6c7be499c 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -47,13 +47,6 @@ constexpr int32_t MIN_PIN_CODE = 100000; constexpr int32_t MAX_PIN_CODE = 999999; const int32_t MAX_AUTH_FAIL_TIMES = 3; -// TODO: 黄蓝区未同步,无CONN_SESSION_TYPE_HML符号 -bool IsHmlSessionType(std::string sessionType) -{ - return false; - // return sessionType == CONN_SESSION_TYPE_HML; -} - int32_t GetCloseSessionDelaySeconds(std::string &delaySecondsStr) { if (!IsNumberString(delaySecondsStr)) { @@ -144,6 +137,11 @@ std::string ParseExtraFromMap(const std::map &bindPara } // namespace +bool AuthManager::IsHmlSessionType(std::string sessionType) +{ + return sessionType == CONN_SESSION_TYPE_HML; +} + AuthManager::AuthManager(std::shared_ptr softbusConnector, std::shared_ptr listener, std::shared_ptr hiChainAuthConnector) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 9e5d59ac2..2cb636230 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -29,6 +29,7 @@ #include "dm_crypto.h" #include "dm_log.h" #include "dm_timer.h" +#include "dm_radar_helper.h" #include "dm_constants.h" #include "dm_anonymous.h" #include "dm_auth_context.h" @@ -45,6 +46,43 @@ DmAuthStateType AuthSrcStartState::GetStateType() return DmAuthStateType::AUTH_SRC_START_STATE; } +int32_t AuthSrcStartState::Action(std::shared_ptr context) +{ + int32_t sessionId = 0; + if (AuthManager::IsHmlSessionType(context->connSessionType)) { + LOGI("hmlActionId %{public}d, hmlReleaseTime %{public}d, hmlEnable160M %{public}d", + context->hmlActionId, context->connDelayCloseTime, context->hmlEnable160M); + sessionId = context->softbusConnector->GetSoftbusSession() + ->OpenAuthSessionWithPara(context->accesser.deviceId, context->hmlActionId, context->hmlEnable160M); + } else { + sessionId = context->softbusConnector->GetSoftbusSession()->OpenAuthSession(context->accesser.deviceId); + } + + struct RadarInfo info = { + .funcName = "EstablishAuthChannel", + .stageRes = (sessionId > 0) ? + static_cast(StageRes::STAGE_IDLE) : static_cast(StageRes::STAGE_FAIL), + .bizState = (sessionId > 0) ? + static_cast(BizState::BIZ_STATE_START) : static_cast(BizState::BIZ_STATE_END), + .localSessName = DM_SESSION_NAME, + .peerSessName = DM_SESSION_NAME, + .isTrust = static_cast(TrustStatus::NOT_TRUST), + .commServ = static_cast(CommServ::USE_SOFTBUS), + .peerUdid = context->accessee.deviceId, + .channelId = sessionId, + .errCode = sessionId, + }; + if (!DmRadarHelper::GetInstance().ReportAuthOpenSession(info)) { + LOGE("ReportAuthOpenSession failed"); + } + if (sessionId < 0) { + LOGE("OpenAuthSession failed, stop the authentication"); + // Q: 之前做了一系列资源创建和转换,目前看来直接返回错误即可 + return ERR_DM_FAILED; + } + return DM_OK; +} + DmAuthStateType AuthSrcNegotiateStateMachine::GetStateType() { return DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE; -- Gitee From b77f01ba6d154a34fec52fb188f8cba78454cf8c Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 18:53:55 +0800 Subject: [PATCH 048/382] tmp --- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 7 ++++--- .../src/authentication_v2/auth_stages/auth_credential.cpp | 4 ++-- .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 7 ++++--- 3 files changed, 10 insertions(+), 8 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 498dd723e..90861842f 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -123,13 +123,14 @@ int32_t AuthSinkConfirmState::ShowConfigDialog(std::shared_ptr co LOGI("AuthSinkConfirmState::ShowConfigDialog end"); return DM_OK; } -#if 0 // todo +#if 1 // todo int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context) { // DP 接口 查询ServiceInfoProfile std::vector serviceInfos; - DistributedDeviceProfile::ServiceInfoUniqueKey key(context->accessee.deviceId, - context->accessee.userId, context->accessee.tokenId, context->accessee.serviceId); + DistributedDeviceProfile::ServiceInfoUniqueKey key; + auto tokenId = std::to_string(context->accessee.tokenId); + key.SetTokenId(tokenId); if (DeviceProfileConnector::GetInstance().GetServiceInfoProfileListByTokenId(key, serviceInfos) != DM_OK) { // 获取不到走PIN认证方案 if (context->authType != DmAuthType::AUTH_TYPE_PIN_SHOW) { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 85b8c3741..b057ab0d9 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -120,7 +120,7 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co uint8_t* sessionKey = nullptr; uint32_t sessionKeyLen = 0; sessionKeyLen = context->authMessageProcessor->cryptoMgr_->GetSessionKey(sessionKey); - #if 0 // todo + #if 1 // todo ret = DeviceProfileConnector::PutSessionKey(sessionKey, sessionKeyLen, skId); // 保存到DP #else skId = 0; @@ -223,7 +223,7 @@ int32_t AuthSinkCredentialAuthNegotiateState::Action(std::shared_ptrauthMessageProcessor->cryptoMgr_->GetSessionKey(sessionKey); - #if 0 // todo + #if 1 // todo ret = DeviceProfileConnector::PutSessionKey(sessionKey, sessionKeyLen, skId); // 保存到DP #else skId = 0; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index dbed2bc7c..3d86deb1e 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -117,10 +117,11 @@ int32_t AuthSrcPinAuthStartState::GetPinCodeFromServerInfo(std::shared_ptr serviceInfos; - DistributedDeviceProfile::ServiceInfoUniqueKey key(context->accesser.deviceId, context->accesser.userId, - context->accesser.tokenId, context->accesser.serviceId); + DistributedDeviceProfile::ServiceInfoUniqueKey key; + auto tokenId = std::to_string(context->accessee.tokenId); + key.SetTokenId(tokenId); if (DeviceProfileConnector::GetInstance().GetServiceInfoProfileListByTokenId(key, serviceInfos) == DM_OK) { std::vector filterServiceInfos; for (auto& serviceInfo : serviceInfos) { -- Gitee From ddd0603f1d9f9543daed3134fb2f3f92da9f5803 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 18:56:19 +0800 Subject: [PATCH 049/382] tmp --- .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 2cb636230..708ba4f29 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -53,9 +53,9 @@ int32_t AuthSrcStartState::Action(std::shared_ptr context) LOGI("hmlActionId %{public}d, hmlReleaseTime %{public}d, hmlEnable160M %{public}d", context->hmlActionId, context->connDelayCloseTime, context->hmlEnable160M); sessionId = context->softbusConnector->GetSoftbusSession() - ->OpenAuthSessionWithPara(context->accesser.deviceId, context->hmlActionId, context->hmlEnable160M); + ->OpenAuthSessionWithPara(context->accessee.deviceId, context->hmlActionId, context->hmlEnable160M); } else { - sessionId = context->softbusConnector->GetSoftbusSession()->OpenAuthSession(context->accesser.deviceId); + sessionId = context->softbusConnector->GetSoftbusSession()->OpenAuthSession(context->accessee.deviceId); } struct RadarInfo info = { -- Gitee From fadb56c4d7e5edd1ef40c244cda42ad10d566208 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 19:33:55 +0800 Subject: [PATCH 050/382] tmp --- .../implementation/src/authentication_v2/auth_manager.cpp | 2 +- services/implementation/src/device_manager_service_impl.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 6c7be499c..23f6cb32d 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -812,7 +812,7 @@ void AuthSrcManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int } context_->sessionId = sessionId; - context_->authStateMachine->TransitionTo(std::make_shared()); + context_->authStateMachine->TransitionTo(std::make_shared()); struct RadarInfo info = { .funcName = "OnSessionOpened" }; info.channelId = sessionId; DmRadarHelper::GetInstance().ReportAuthSendRequest(info); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 1722753ce..5ac777a7e 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -62,8 +62,8 @@ int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide) hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); } else { // 线程已创建authMgr_,说明已有绑定事件,其他请求拒绝,返回错误码 - LOGE("BindTarget failed, this device is being bound. Please try again later."); - return ERR_DM_AUTH_BUSINESS_BUSY; + LOGI("BindTarget failed, this device is being bound. Please try again later."); + //return ERR_DM_AUTH_BUSINESS_BUSY; } return DM_OK; } -- Gitee From d61178341edd91b9341dcd6d2a097a00330a7b6a Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 19:37:28 +0800 Subject: [PATCH 051/382] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E7=9B=B8=E5=85=B3=E8=B0=83=E6=B5=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/dm_auth_state.h | 48 +++++++++---------- .../dm_auth_state_machine.cpp | 3 +- 2 files changed, 26 insertions(+), 25 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index ce74f9e3b..cf46f6ffa 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -37,32 +37,32 @@ constexpr const char* ADD_TIMEOUT_TASK = "deviceManagerTimer:add"; enum class DmAuthStateType { AUTH_IDLE_STATE = 0, // 设备初始化时 // source端的状态 - AUTH_SRC_START_STATE, // 用户触发BindTarget - AUTH_SRC_NEGOTIATE_STATE, // 收到软总线回调函数OnSessionOpened,发送80报文 - AUTH_SRC_CONFIRM_STATE, // 收到90授权结果报文,发送100报文 - AUTH_SRC_PIN_AUTH_START_STATE, // 收到110授权结果报文,发送120报文 - AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, // 收到130认证PIN结果报文,发送121报文 - AUTH_SRC_PIN_AUTH_DONE_STATE, // 收到131认证PIN结果报文,调用processData - AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, // 触发Onfinish回调事件,发送140报文 - AUTH_SRC_CREDENTIAL_AUTH_START_STATE, // 收到150加密报文,发送160报文 - AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE, // 收到170凭据认证报文,发送161报文 - AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE, // 收到171凭据认证报文 - AUTH_SRC_DATA_SYNC_STATE, // 触发Onfinish回调事件,发送180报文 - AUTH_SRC_FINISH_STATE, // 收到190报文,发送200报文 + AUTH_SRC_START_STATE = 1, // 用户触发BindTarget + AUTH_SRC_NEGOTIATE_STATE = 2, // 收到软总线回调函数OnSessionOpened,发送80报文 + AUTH_SRC_CONFIRM_STATE = 3, // 收到90授权结果报文,发送100报文 + AUTH_SRC_PIN_AUTH_START_STATE = 4, // 收到110授权结果报文,发送120报文 + AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE = 5, // 收到130认证PIN结果报文,发送121报文 + AUTH_SRC_PIN_AUTH_DONE_STATE = 6, // 收到131认证PIN结果报文,调用processData + AUTH_SRC_CREDENTIAL_EXCHANGE_STATE = 7, // 触发Onfinish回调事件,发送140报文 + AUTH_SRC_CREDENTIAL_AUTH_START_STATE = 8, // 收到150加密报文,发送160报文 + AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE = 9, // 收到170凭据认证报文,发送161报文 + AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE = 10, // 收到171凭据认证报文 + AUTH_SRC_DATA_SYNC_STATE = 11, // 触发Onfinish回调事件,发送180报文 + AUTH_SRC_FINISH_STATE = 12, // 收到190报文,发送200报文 // sink端的状态 - AUTH_SINK_START_STATE = 50, // 总线触发OnSessionOpened - AUTH_SINK_NEGOTIATE_STATE, // 收到80可信关系协商报文,发送90报文 - AUTH_SINK_CONFIRM_STATE, // 收到100用户授权报文,发送110报文 - AUTH_SINK_PIN_AUTH_START_STATE, // 收到120认证PIN报文,发送130报文 - AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, // 收到121认证PIN报文,发送131报文 - AUTH_SINK_PIN_AUTH_DONE_STATE, // 触发Onfinish回调事件 - AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, // 收到140加密报文,发送150报文 - AUTH_SINK_CREDENTIAL_AUTH_START_STATE, // 收到160凭证认证报文,发送170报文 - AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE, // 收到161凭据协商报文 - AUTH_SINK_CREDENTIAL_AUTH_DONE_STATE, // 触发Onfinish回调事件 - AUTH_SINK_DATA_SYNC_STATE, // 收到180同步报文,发送190报文 - AUTH_SINK_FINISH_STATE, // 收到200结束报文 + AUTH_SINK_START_STATE = 50, // 总线触发OnSessionOpened + AUTH_SINK_NEGOTIATE_STATE = 51, // 收到80可信关系协商报文,发送90报文 + AUTH_SINK_CONFIRM_STATE = 52, // 收到100用户授权报文,发送110报文 + AUTH_SINK_PIN_AUTH_START_STATE = 53, // 收到120认证PIN报文,发送130报文 + AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE = 54, // 收到121认证PIN报文,发送131报文 + AUTH_SINK_PIN_AUTH_DONE_STATE = 55, // 触发Onfinish回调事件 + AUTH_SINK_CREDENTIAL_EXCHANGE_STATE = 56, // 收到140加密报文,发送150报文 + AUTH_SINK_CREDENTIAL_AUTH_START_STATE = 57, // 收到160凭证认证报文,发送170报文 + AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE = 58, // 收到161凭据协商报文 + AUTH_SINK_CREDENTIAL_AUTH_DONE_STATE = 59, // 触发Onfinish回调事件 + AUTH_SINK_DATA_SYNC_STATE = 60, // 收到180同步报文,发送190报文 + AUTH_SINK_FINISH_STATE = 61, // 收到200结束报文 }; // 凭据添加方式 diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 61b526bdb..71271b8ca 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -87,7 +87,8 @@ int32_t DmAuthStateMachine::TransitionTo(std::shared_ptr state) stateCv_.notify_one(); } else { // 切换状态不合法,打印错误日志并返回错误码 - LOGE("DmAuthStateMachine: The state transition does not meet the rule."); + LOGE("DmAuthStateMachine: The state transition does not meet the rule from %d to %d.", + GetCurState(), nextState); ret = ERR_DM_NEXT_STATE_INVALID; // 下一状态不合法错误码 } return ret; -- Gitee From ff1fec027e1d46a9e677e5486bb7460d3fdd2e1b Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 19:41:53 +0800 Subject: [PATCH 052/382] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E5=A4=96?= =?UTF-8?q?=E9=83=A8=E6=96=87=E4=BB=B6=E9=94=99=E8=AF=AF=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_credential.cpp | 4 ++-- .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 1 - 2 files changed, 2 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index b057ab0d9..85b8c3741 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -120,7 +120,7 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co uint8_t* sessionKey = nullptr; uint32_t sessionKeyLen = 0; sessionKeyLen = context->authMessageProcessor->cryptoMgr_->GetSessionKey(sessionKey); - #if 1 // todo + #if 0 // todo ret = DeviceProfileConnector::PutSessionKey(sessionKey, sessionKeyLen, skId); // 保存到DP #else skId = 0; @@ -223,7 +223,7 @@ int32_t AuthSinkCredentialAuthNegotiateState::Action(std::shared_ptrauthMessageProcessor->cryptoMgr_->GetSessionKey(sessionKey); - #if 1 // todo + #if 0 // todo ret = DeviceProfileConnector::PutSessionKey(sessionKey, sessionKeyLen, skId); // 保存到DP #else skId = 0; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 708ba4f29..d73669b6c 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -397,7 +397,6 @@ int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr con context->accessee.deviceId = static_cast(localDeviceId); // 解析message时,accesser.deviceId已赋值 - // remoteDeviceId_ = authResponseContext_->localDeviceId; context->accessee.networkId = context->softbusConnector->GetLocalDeviceNetworkId(); context->accessee.deviceName = context->softbusConnector->GetLocalDeviceName(); if (CompareVersion(context->accesser.dmVersion, std::string(DM_VERSION_5_1_0)) == false) { -- Gitee From 49602028ba6db83f4db7f37b5ad1ca17875dbf1b Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 19:46:47 +0800 Subject: [PATCH 053/382] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A080/90?= =?UTF-8?q?=E6=8A=A5=E6=96=87=E5=88=9B=E5=BB=BAcase?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 25b7e8888..45e5e89dd 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -80,6 +80,8 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont context->msgType = msgType; LOGI("DmAuthMessageProcessor::ParseMessage message type %{public}d", context->msgType); switch (msgType) { + case MSG_TYPE_REQ_ACL_NEGOTIATE: + return ParseNegotiateMessage(jsonObject, context); case MSG_TYPE_RESP_ACL_NEGOTIATE: return ParseMessageRespAclNegotiate(jsonObject, context); case MSG_TYPE_REQ_USER_CONFIRM: @@ -239,6 +241,10 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh nlohmann::json jsonObj; jsonObj[TAG_MSG_TYPE] = msgType; switch (msgType) { + case MSG_TYPE_REQ_ACL_NEGOTIATE: + CreateNegotiateMessage(context, jsonObj); + case MSG_TYPE_RESP_ACL_NEGOTIATE: + CreateRespNegotiateMessage(context, jsonObj); case MSG_TYPE_REQ_USER_CONFIRM: CreateMessageReqUserConfirm(context, jsonObj); break; @@ -408,6 +414,7 @@ void DmAuthMessageProcessor::CreateMessageReqCredAuthStart(std::shared_ptr context) { if (IsString(jsonObject, TAG_DEVICE_VERSION)) { -- Gitee From 49616309180cb0429b09f8196a5acbd9607ffaa6 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Mon, 3 Mar 2025 19:48:00 +0800 Subject: [PATCH 054/382] Merge branch 'acl3-1' of https://gitee.com/yuanzichun1/distributedhardware_device_manager_1 into gl2 --- bundle.json | 3 +- services/implementation/BUILD.gn | 2 + .../dm_auth_message_processor.h | 44 +++++- .../auth_stages/auth_credential.cpp | 20 +-- .../dm_auth_message_processor.cpp | 146 ++++++++++++++---- 5 files changed, 165 insertions(+), 50 deletions(-) diff --git a/bundle.json b/bundle.json index 1abf4373d..f0bcdfccc 100644 --- a/bundle.json +++ b/bundle.json @@ -59,7 +59,8 @@ "resource_management", "wifi", "screenlock_mgr", - "mbedtls" + "mbedtls", + "zlib" ], "third_party": [] }, diff --git a/services/implementation/BUILD.gn b/services/implementation/BUILD.gn index 412efc03c..b86107f9f 100644 --- a/services/implementation/BUILD.gn +++ b/services/implementation/BUILD.gn @@ -44,6 +44,7 @@ if (defined(ohos_lite)) { "${utils_path}/include/fwkload/lite", "${utils_path}/include/timer/lite", "//third_party/json/include", + "//third_party/zlib/zlib.h", "${services_path}/include", "${services_path}/include/ipc/lite", "${interfaces_path}/c/ipc/include", @@ -89,6 +90,7 @@ if (defined(ohos_lite)) { "//foundation/systemabilitymgr/safwk_lite:safwk_lite", "//foundation/systemabilitymgr/samgr_lite/samgr:samgr", "//third_party/bounds_checking_function:libsec_shared", + "//third_party/zlib", ] cflags = [ diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 36e4aeee7..432846658 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -75,6 +75,20 @@ 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_PKG_NAME = "pkgName"; +constexpr const char *DM_TAG_DMVERSION = "dmVersion"; +constexpr const char *DM_TAG_ACCESS = "dmAccess"; +constexpr const char *DM_TAG_PROXY = "proxy"; +constexpr const char *DM_TAG_ACL_CHECKSUM = "aclCheckSum"; +constexpr const char *DM_TAG_SERVICEINFO = "serviceInfo"; +constexpr const char *DM_TAG_APPSKID = "accesserAppSKId"; +constexpr const char *DM_TAG_USERSKID = "accesserUserSKId"; +constexpr const char *DM_TAG_APPSK_TIMESTAMP = "accesserAppSKTimeStamp"; +constexpr const char *DM_TAG_USERSK_TIMESTAMP = "accesserUserSKTimeStamp"; +constexpr const char *DM_TAG_SYNC = "syncMessage"; +constexpr const char *DM_TAG_COMPRESS_ORI_LEN = "compressOriLen"; +constexpr const char *DM_TAG_COMPRESS = "compressMsg"; + +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"; @@ -120,6 +134,25 @@ struct DmAccessToSync { bindLevel, sessionKeyId, skTimeStamp) }; +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; + NLOHMANN_DEFINE_TYPE_INTRUSIVE(DmAccessControlTable, accessControlId, accesserId, accesseeId, deviceId, sessionKey, + bindType, authType, deviceType, deviceIdHash, status, validPeriod, lastAuthTime, + bindLevel, deviceIdHash) +}; + class DmAuthMessageProcessor { public: DmAuthMessageProcessor(); @@ -138,7 +171,8 @@ public: // 保存秘钥 int32_t SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyLen); - std::shared_ptr cryptoMgr_ = nullptr; + // 保存永久SK + int32_t SaveSessionKeyToDP(int32_t &skId); private: // 内部各类报文的实现 @@ -192,11 +226,17 @@ private: void CreateMessageRspCredExchange(std::shared_ptr context, nlohmann::json &jsonObject); // 创建160报文 void CreateMessageReqCredAuthStart(std::shared_ptr context, nlohmann::json &jsonObject); - // 161 170 171 透传凭据认证消息构造 int32_t CreateCredentialNegotiateMessage(std::shared_ptr &context, nlohmann::json &jsonObject); // 180 190 消息构造 int32_t CreateSyncMessage(std::shared_ptr &context, nlohmann::json &jsonObject); + // 压缩sync 消息 + std::string compressSyncMsg(std::string &inputStr); + // 解压缩sync 消息 + std::string decompressSyncMsg(std::string& compressed, uint32_t oriLen); + // 序列化acl + int32_t ACLToStr(DistributedDeviceProfile::AccessControlProfile acl, std::string aclStr); + std::shared_ptr cryptoMgr_ = nullptr; }; } // namespace DistributedHardware diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 85b8c3741..c216085b0 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -115,16 +115,9 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co LOGE("AuthSrcCredentialAuthDoneState::Action Hichain auth SINK transmit data failed"); return ERR_DM_FAILED; } - int32_t skId; DmMessageType msgType; - uint8_t* sessionKey = nullptr; - uint32_t sessionKeyLen = 0; - sessionKeyLen = context->authMessageProcessor->cryptoMgr_->GetSessionKey(sessionKey); - #if 0 // todo - ret = DeviceProfileConnector::PutSessionKey(sessionKey, sessionKeyLen, skId); // 保存到DP - #else - skId = 0; - #endif + int32_t skId; + ret = context->authMessageProcessor->SaveSessionKeyToDP(skId); if (ret != DM_OK) { LOGE("AuthSrcCredentialAuthDoneState::Action DP save user session key failed"); return ret; @@ -220,14 +213,7 @@ int32_t AuthSinkCredentialAuthNegotiateState::Action(std::shared_ptrauthMessageProcessor->cryptoMgr_->GetSessionKey(sessionKey); - #if 0 // todo - ret = DeviceProfileConnector::PutSessionKey(sessionKey, sessionKeyLen, skId); // 保存到DP - #else - skId = 0; - #endif + ret = context->authMessageProcessor->SaveSessionKeyToDP(skId); if (ret != DM_OK) { LOGE("AuthSinkCredentialAuthNegotiateState::Action DP save user session key failed"); return ret; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 45e5e89dd..ef6d53669 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -12,7 +12,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ - +#include #include "dm_anonymous.h" #include "dm_auth_context.h" #include "dm_auth_message_processor.h" @@ -26,6 +26,7 @@ #include "access_control_profile.h" #include "dm_auth_context.h" #include "dm_auth_state_machine.h" +#include "dm_crypto.h" #undef LOG_TAG #define LOG_TAG "DHDM_V2" @@ -46,6 +47,18 @@ int32_t DmAuthMessageProcessor::SaveSessionKey(const uint8_t *sessionKey, const return cryptoMgr_->SaveSessionKey(sessionKey, keyLen); } +// 保存永久SK +int32_t DmAuthMessageProcessor::SaveSessionKeyToDP(int32_t &skId) +{ + if (cryptoMgr_ == nullptr) { + LOGE("DmAuthMessageProcessor::SaveSessionKey failed, cryptoMgr_ is nullptr."); + return ERR_DM_FAILED; + } + uint8_t* sessionKey = nullptr; + uint32_t skLen = cryptoMgr_->GetSessionKey(sessionKey); + return DeviceProfileConnector::GetInstance().PutSessionKey(sessionKey, skLen, skId); +} + DmAuthMessageProcessor::DmAuthMessageProcessor() { LOGI("DmAuthMessageProcessor constructor"); @@ -120,7 +133,7 @@ int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const nlohmann::js } // 解密 std::string plainText; - int32_t ret = context->authMessageProcessor->cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA], plainText); + int32_t ret = cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA], plainText); if (ret != DM_OK) { LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae DecryptMessage failed"); return ret; @@ -295,8 +308,7 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr &context, nlohmann::json &jsonObject) { std::string encryptMsg; - int32_t ret = context->authMessageProcessor->cryptoMgr_->EncryptMessage( - DmAuthMessageProcessor::GetTransmitFromContext(context), encryptMsg); // 临时SK加密 + int32_t ret = cryptoMgr_->EncryptMessage(DmAuthMessageProcessor::GetTransmitFromContext(context), encryptMsg); // 临时SK加密 if (ret != DM_OK) { LOGE("DmAuthMessageProcessor::CreateSyncMessage encrypt failed"); return ret; @@ -610,11 +622,45 @@ void DmAuthMessageProcessor::CreateAndSendMsg(DmMessageType msgType, std::shared auto message = CreateMessage(msgType, context); context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); } + +std::string DmAuthMessageProcessor::compressSyncMsg(std::string &inputStr) +{ + uint32_t srcLen = inputStr.size(); + uint32_t boundSize = compressBound(srcLen); // 最大压缩长度 + std::string compressed(boundSize, '\0'); + + // 压缩到预留空间 + unsigned long destSize = boundSize; // 实际可用长度 + int32_t ret = compress(reinterpret_cast(&compressed[0]), &destSize, + reinterpret_cast(inputStr.data()), srcLen); + if (ret != Z_OK) { + LOGE("DmAuthMessageProcessor::compressSyncMsg zlib compress failed"); + return ""; + } + compressed.resize(destSize); // 实际使用长度 + return compressed; +} + +std::string DmAuthMessageProcessor::decompressSyncMsg(std::string& compressed, uint32_t oriLen) +{ + std::string decompressed; + decompressed.resize(oriLen); + unsigned long destLen = oriLen; // 实际使用长度 + int32_t ret = uncompress(reinterpret_cast(&decompressed[0]), &destLen, + reinterpret_cast(compressed.data()), // 解压时跳过头部 + compressed.size()); + if (ret != Z_OK || destLen != oriLen) { + LOGE("DmAuthMessageProcessor::decompressSyncMsg decompress failed"); + return ""; + } + return decompressed; +} + // 用于组装syncMsg中的加密部分 int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptr &context, std::vector aclList, DmAccess &accessSide, std::string &encSyncMsg) { - nlohmann::json syncMsg; + nlohmann::json syncMsgJson; // 完整的180/190 消息 未经压缩&加密 DmAccessToSync accessToSync; accessToSync.deviceName = accessSide.deviceName; accessToSync.deviceId = accessSide.deviceId; @@ -627,40 +673,84 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptrisOnline) { // 非首次认证 accessToSync.sessionKeyId = context->appSessionKeyId; accessToSync.skTimeStamp = context->appSkTimeStamp; - syncMsg[DM_TAG_APPSKID]=std::to_string(context->appSessionKeyId); - syncMsg[DM_TAG_APPSK_TIMESTAMP]=std::to_string(context->appSkTimeStamp); + syncMsgJson[DM_TAG_APPSKID]=std::to_string(context->appSessionKeyId); + syncMsgJson[DM_TAG_APPSK_TIMESTAMP]=std::to_string(context->appSkTimeStamp); } else { // 首次认证 accessToSync.sessionKeyId = context->userSessionKeyId; accessToSync.skTimeStamp = context->userSkTimeStamp; - syncMsg[DM_TAG_APPSKID]=std::to_string(context->appSessionKeyId); - syncMsg[DM_TAG_USERSKID]=std::to_string(context->userSessionKeyId); - syncMsg[DM_TAG_APPSK_TIMESTAMP]=std::to_string(context->appSkTimeStamp); - syncMsg[DM_TAG_USERSK_TIMESTAMP]=std::to_string(context->userSkTimeStamp); + syncMsgJson[DM_TAG_APPSKID]=std::to_string(context->appSessionKeyId); + syncMsgJson[DM_TAG_USERSKID]=std::to_string(context->userSessionKeyId); + syncMsgJson[DM_TAG_APPSK_TIMESTAMP]=std::to_string(context->appSkTimeStamp); + syncMsgJson[DM_TAG_USERSK_TIMESTAMP]=std::to_string(context->userSkTimeStamp); + } + + nlohmann::json accessJsonObj = accessToSync; // 直接使用宏构造 access json + syncMsgJson[DM_TAG_DMVERSION] = accessSide.dmVersion; + syncMsgJson[DM_TAG_ACCESS] = accessJsonObj.dump(); // 接收端需要再拆一次json + syncMsgJson[DM_TAG_PROXY] = ""; // 预留字段 留空即可 + std::vector> aclHashList; + for (auto &item : aclList) { + uint8_t aclHash[DM_HASH_LEN] = {0}; + Crypto::DmGenerateStrHash(item.data(), item.size(), aclHash, DM_HASH_LEN, 0); + aclHashList.push_back(std::vector(aclHash, aclHash + DM_HASH_LEN)); + } + syncMsgJson[DM_TAG_ACL_CHECKSUM] = aclHashList; + std::string syncMsg = SafetyDump(syncMsgJson); // 消息构造完成 + + std::string compressMsg = compressSyncMsg(syncMsg); // 压缩 + if (compressMsg.empty()) { + LOGE("DmAuthMessageProcessor::EncryptSyncMessage compress failed"); + return ERR_DM_FAILED; } - - nlohmann::json accessJsonObj = accessToSync; // 直接使用宏构造json - nlohmann::json aclJsonObj = aclList; - syncMsg[DM_TAG_DMVERSION] = accessSide.dmVersion; - syncMsg[DM_TAG_ACCESS] = accessJsonObj.dump(); // 接收端需要再拆一次json - syncMsg[DM_TAG_PROXY] = ""; // 预留字段 留空即可 - syncMsg[DM_TAG_ACL] = aclJsonObj.dump(); // 接收端需要再拆一次json - syncMsg[DM_TAG_SERVICEINFO]=""; // 与yangwei确认内容&格式 - + nlohmann::json plainJson; + plainJson[DM_TAG_COMPRESS_ORI_LEN] = syncMsg.size(); // 记录压缩前原始长度 用于接收端解析 + plainJson[DM_TAG_COMPRESS] = compressMsg; // 加密整个字段 - return context->authMessageProcessor->cryptoMgr_->EncryptMessage(SafetyDump(syncMsg), encSyncMsg); + return cryptoMgr_->EncryptMessage(plainJson.dump(), encSyncMsg); +} + +int32_t DmAuthMessageProcessor::ACLToStr(DistributedDeviceProfile::AccessControlProfile acl, std::string aclStr) +{ + DmAccessControlTable dmAcl; + dmAcl.accessControlId = acl.GetAccessControlId(); + dmAcl.accesserId = acl.GetAccesserId(); + dmAcl.accesseeId = acl.GetAccesseeId(); + dmAcl.deviceId = acl.GetTrustDeviceId(); + dmAcl.sessionKey = acl.GetSessionKey(); + dmAcl.bindType = acl.GetBindType(); + dmAcl.authType = acl.GetAuthenticationType(); + dmAcl.deviceType = acl.GetDeviceIdType(); + dmAcl.deviceIdHash = acl.GetDeviceIdHash(); + dmAcl.status = acl.GetStatus(); + dmAcl.validPeriod = acl.GetValidPeriod(); + dmAcl.lastAuthTime = acl.GetLastAuthTime(); + dmAcl.bindLevel = acl.GetBindType(); + nlohmann::json aclJsonObj = dmAcl; + aclStr = aclJsonObj.dump(); + if (aclStr.empty()) { + LOGE("DmAuthMessageProcessor::ACLToStr normalized acl failed"); + return ERR_DM_FAILED; + } + return DM_OK; } - int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr &context, nlohmann::json &jsonObject) { // 查询ACL std::vector profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfile(); std::vector aclList; + int32_t ret; for (auto &item : profiles) { if (item.GetAccesser().GetAccesserDeviceId() == context->accesser.deviceId && item.GetAccesser().GetAccesserUserId() == context->accesser.userId && item.GetAccessee().GetAccesseeDeviceId() == context->accessee.deviceId && item.GetAccessee().GetAccesseeUserId() == context->accessee.userId) { - aclList.push_back(item.dump()); // 打印并写入 + std::string aclStr; + ret = ACLToStr(item, aclStr); + if (aclStr.empty()) { + LOGE("DmAuthMessageProcessor::CreateSyncMessage normalized acl failed"); + return ERR_DM_FAILED; + } + aclList.push_back(aclStr); // 打印并写入 } } if (aclList.empty()) { @@ -679,16 +769,12 @@ int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr serviceInfoKey.SetUserId(accessSide.userId); serviceInfoKey.SetTokenId(std::to_string(accessSide.tokenId)); std::string encSyncMsg; - int32_t ret = EncryptSyncMessage(context, aclList, accessSide, encSyncMsg); + ret = EncryptSyncMessage(context, aclList, accessSide, encSyncMsg); if (ret != DM_OK) { LOGE("DmAuthMessageProcessor::CreateSyncMessage encrypt failed"); return ret; } - jsonObject[DM_TAG_SYNC] = encSyncMsg; - - // TODO 与yangwei确认压缩encMsg接口 - // TODO ACL改用verison+checksum传输 - + jsonObject[DM_TAG_SYNC] = encSyncMsg; return DM_OK; } @@ -714,7 +800,7 @@ int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(nlohmann::json &jsonObject // 解密 std::string plainText; - int32_t ret = context->authMessageProcessor->cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA], plainText); + int32_t ret = cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA], plainText); if (ret != DM_OK) { LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae DecryptMessage failed"); return ret; -- Gitee From fbf4be708f233c54a8bc0070f53e0f6207d70eb1 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 19:48:40 +0800 Subject: [PATCH 055/382] test: --- .../include/authentication_v2/dm_auth_message_processor.h | 2 +- .../src/authentication_v2/dm_auth_message_processor.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 36e4aeee7..3ad6b9a5e 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -148,7 +148,7 @@ private: int32_t ParseAuthStartMessgae(nlohmann::json &jsonObject, std::shared_ptr &context); // 解析 80报文 - void ParseNegotiateMessage(nlohmann::json &jsonObject, std::shared_ptr context); + int32_t ParseNegotiateMessage(nlohmann::json &jsonObject, std::shared_ptr context); // 解析 90 报文 int32_t ParseMessageRespAclNegotiate(const nlohmann::json &json, std::shared_ptr context); // 解析 100 报文 diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 45e5e89dd..05cb431f0 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -447,7 +447,7 @@ void DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject, s context->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].get(); } - return; + return DM_OK; } int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const nlohmann::json &jsonObject, -- Gitee From e6939a0fdfaebe0d5089ed4f4c3b0459681e6b08 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 19:54:18 +0800 Subject: [PATCH 056/382] test: --- .../src/authentication_v2/dm_auth_message_processor.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 05cb431f0..e061f6d3e 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -243,8 +243,10 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh switch (msgType) { case MSG_TYPE_REQ_ACL_NEGOTIATE: CreateNegotiateMessage(context, jsonObj); + break; case MSG_TYPE_RESP_ACL_NEGOTIATE: CreateRespNegotiateMessage(context, jsonObj); + break; case MSG_TYPE_REQ_USER_CONFIRM: CreateMessageReqUserConfirm(context, jsonObj); break; -- Gitee From 44657d4309cc1483db1d675f35bd927a94b55da5 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 19:55:48 +0800 Subject: [PATCH 057/382] test: --- .../src/authentication_v2/dm_auth_message_processor.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index e061f6d3e..fabcccc10 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -417,7 +417,8 @@ void DmAuthMessageProcessor::CreateMessageReqCredAuthStart(std::shared_ptr context) +int32_t DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject, + std::shared_ptr context) { if (IsString(jsonObject, TAG_DEVICE_VERSION)) { context->accesser.dmVersion = jsonObject[TAG_DEVICE_VERSION].get(); -- Gitee From bfba12433701316e313db208bf9d148c87cd4acd Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Mon, 3 Mar 2025 19:56:53 +0800 Subject: [PATCH 058/382] =?UTF-8?q?=E5=90=8C=E6=AD=A5=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication_v2/dm_auth_message_processor.h | 9 --------- 1 file changed, 9 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 432846658..ec3fce0f8 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -75,19 +75,10 @@ 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_PKG_NAME = "pkgName"; -constexpr const char *DM_TAG_DMVERSION = "dmVersion"; -constexpr const char *DM_TAG_ACCESS = "dmAccess"; -constexpr const char *DM_TAG_PROXY = "proxy"; constexpr const char *DM_TAG_ACL_CHECKSUM = "aclCheckSum"; -constexpr const char *DM_TAG_SERVICEINFO = "serviceInfo"; -constexpr const char *DM_TAG_APPSKID = "accesserAppSKId"; -constexpr const char *DM_TAG_USERSKID = "accesserUserSKId"; -constexpr const char *DM_TAG_APPSK_TIMESTAMP = "accesserAppSKTimeStamp"; -constexpr const char *DM_TAG_USERSK_TIMESTAMP = "accesserUserSKTimeStamp"; constexpr const char *DM_TAG_SYNC = "syncMessage"; constexpr const char *DM_TAG_COMPRESS_ORI_LEN = "compressOriLen"; constexpr const char *DM_TAG_COMPRESS = "compressMsg"; - constexpr const int32_t DM_HASH_LEN = 32; constexpr const char* TAG_IS_ONLINE = "isOnline"; constexpr const char* TAG_IS_AUTHED = "isAuthed"; -- Gitee From 6a1585e28145dc3f2b193aa1b0ab52906097f2f2 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 19:59:10 +0800 Subject: [PATCH 059/382] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D80=E6=8A=A5?= =?UTF-8?q?=E6=96=87=E9=80=BB=E8=BE=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index d73669b6c..6d0925525 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -93,7 +93,7 @@ int32_t AuthSrcNegotiateStateMachine::Action(std::shared_ptr cont LOGI("AuthSrcNegotiateStateMachine::Action sessionId %{public}d.", context->sessionId); // Q:为什么会让对端deviceId等于自己的deviceId? - context->accessee.deviceId = context->accesser.deviceId; + // context->accessee.deviceId = context->accesser.deviceId; context->reply = ERR_DM_AUTH_REJECT; // authType、deviceId已在BindTarget赋值 // accountGroupIdHash已废弃,无组的概念 -- Gitee From 2ac33d08cfa0af130599de9ac26ed338d069d168 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 20:13:05 +0800 Subject: [PATCH 060/382] =?UTF-8?q?fix:=20=E8=B7=B3=E8=BD=AC=E6=8A=A5?= =?UTF-8?q?=E6=96=87=E5=88=B090?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 2 +- .../src/authentication_v2/dm_auth_message_processor.cpp | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 6d0925525..1e047bede 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -387,7 +387,7 @@ int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr con // 1. 停止定时器 if (context->timer != nullptr) { - context->timer->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); + context->timer->DeleteTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK)); } // 2. 获取deviceName和udid diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index fabcccc10..c38393238 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -450,6 +450,7 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject context->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].get(); } + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } -- Gitee From 0e2424a20a9e7efda5fd26c8a84834cb5dcab1bb Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 20:19:42 +0800 Subject: [PATCH 061/382] =?UTF-8?q?test:=20=E5=8A=A0=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E8=B7=B3=E8=BD=AC=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_state_machine.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 71271b8ca..41d9b2580 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -87,7 +87,7 @@ int32_t DmAuthStateMachine::TransitionTo(std::shared_ptr state) stateCv_.notify_one(); } else { // 切换状态不合法,打印错误日志并返回错误码 - LOGE("DmAuthStateMachine: The state transition does not meet the rule from %d to %d.", + LOGE("DmAuthStateMachine: The state transition does not meet the rule from %{public}d to %{public}d.", GetCurState(), nextState); ret = ERR_DM_NEXT_STATE_INVALID; // 下一状态不合法错误码 } -- Gitee From df13be8d8bd1d6d9c7599120bee3b20edc7e3d56 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 20:22:00 +0800 Subject: [PATCH 062/382] tmp --- .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 3d86deb1e..3740fc93a 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -280,7 +280,7 @@ int32_t AuthSrcPinAuthMsgNegotiateState::Action(std::shared_ptr c DmAuthStateType AuthSinkPinAuthMsgNegotiateState::GetStateType() { - return DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE; + return DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE; } int32_t AuthSinkPinAuthMsgNegotiateState::Action(std::shared_ptr context) -- Gitee From 48af356af9a3b4fc72d7277ee3affe79a4a967ba Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 20:29:11 +0800 Subject: [PATCH 063/382] test: --- .../implementation/src/authentication_v2/auth_manager.cpp | 4 ---- 1 file changed, 4 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 23f6cb32d..112cc1295 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -684,10 +684,6 @@ void AuthSinkManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, in DmAuthState::GetTaskTimeout(context_, WAIT_NEGOTIATE_TIMEOUT_TASK, WAIT_NEGOTIATE_TIMEOUT), [this] (std::string name) { DmAuthState::HandleAuthenticateTimeout(context_, name); }); - } else { - context_->reply = ERR_DM_AUTH_BUSINESS_BUSY; - std::string message = context_->authMessageProcessor->CreateMessage(MSG_TYPE_AUTH_TERMINATE, context_); - context_->softbusConnector->GetSoftbusSession()->SendData(sessionId, message); } return; -- Gitee From f968678cef815924a90b26dcbdb894f55348c3b9 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 20:36:21 +0800 Subject: [PATCH 064/382] tmp --- .../src/authentication_v2/dm_auth_state_machine.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 41d9b2580..9559c27af 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -29,8 +29,8 @@ namespace DistributedHardware { DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) { stateTransitionTable_ = { // 此处省略下一状态为AuthXXXFinishState的迁移情况 + {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SRC_START_STATE, DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, // Source端 状态迁移表 - {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SRC_START_STATE}}, {DmAuthStateType::AUTH_SRC_START_STATE, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE}}, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE}}, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE, {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, @@ -47,7 +47,7 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE}}, {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, {}}, // Sink端 状态迁移表 - {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, + //{DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, //{DmAuthStateType::AUTH_SINK_START_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, // to check -- Gitee From 7755b86fb9d1414652147363be695a6b83ca1321 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Mon, 3 Mar 2025 20:37:59 +0800 Subject: [PATCH 065/382] =?UTF-8?q?=E9=80=82=E9=85=8D=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/implementation/BUILD.gn | 1 + .../include/authentication_v2/dm_auth_message_processor.h | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/BUILD.gn b/services/implementation/BUILD.gn index b86107f9f..ffe08042b 100644 --- a/services/implementation/BUILD.gn +++ b/services/implementation/BUILD.gn @@ -250,6 +250,7 @@ if (defined(ohos_lite)) { "os_account:libaccountkits", "resource_management:resmgr_napi_core", "samgr:samgr_proxy", + "zlib:shared_libz", ] if (support_screenlock && device_manager_feature_product == "default") { diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index ec3fce0f8..ec9b7049e 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -76,7 +76,6 @@ constexpr const char* TAG_PEER_BUNDLE_NAME = "peerBundleName"; constexpr const char* TAG_BIND_LEVEL = "bindLevel"; constexpr const char* TAG_PKG_NAME = "pkgName"; constexpr const char *DM_TAG_ACL_CHECKSUM = "aclCheckSum"; -constexpr const char *DM_TAG_SYNC = "syncMessage"; constexpr const char *DM_TAG_COMPRESS_ORI_LEN = "compressOriLen"; constexpr const char *DM_TAG_COMPRESS = "compressMsg"; constexpr const int32_t DM_HASH_LEN = 32; -- Gitee From ff395520f22e8ee45392972b9149739cac4e2a39 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 20:54:38 +0800 Subject: [PATCH 066/382] test: --- .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 1e047bede..848221df8 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -399,8 +399,9 @@ int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr con // 解析message时,accesser.deviceId已赋值 context->accessee.networkId = context->softbusConnector->GetLocalDeviceNetworkId(); context->accessee.deviceName = context->softbusConnector->GetLocalDeviceName(); - if (CompareVersion(context->accesser.dmVersion, std::string(DM_VERSION_5_1_0)) == false) { - LOGE("AuthSinkNegotiateStateMachine::Action incompatible version compare to 5.1.0"); + if (CompareVersion(context->accesser.dmVersion, std::string(DM_VERSION_5_1_0))) { + LOGE("AuthSinkNegotiateStateMachine::Action incompatible version %{public}s compare to 5.1.0", + context->accesser.dmVersion); return ERR_DM_VERSION_INCOMPATIBLE; } -- Gitee From 7f7fe2aefc5eb28404d757cff85b47d84c7aaa9f Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 20:55:04 +0800 Subject: [PATCH 067/382] test: --- .../authentication_v2/auth_stages/auth_negotiate.cpp | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 848221df8..a6d25acc6 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -399,11 +399,12 @@ int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr con // 解析message时,accesser.deviceId已赋值 context->accessee.networkId = context->softbusConnector->GetLocalDeviceNetworkId(); context->accessee.deviceName = context->softbusConnector->GetLocalDeviceName(); - if (CompareVersion(context->accesser.dmVersion, std::string(DM_VERSION_5_1_0))) { - LOGE("AuthSinkNegotiateStateMachine::Action incompatible version %{public}s compare to 5.1.0", - context->accesser.dmVersion); - return ERR_DM_VERSION_INCOMPATIBLE; - } + // TODO: + // if (CompareVersion(context->accesser.dmVersion, std::string(DM_VERSION_5_1_0))) { + // LOGE("AuthSinkNegotiateStateMachine::Action incompatible version %{public}s compare to 5.1.0", + // context->accesser.dmVersion); + // return ERR_DM_VERSION_INCOMPATIBLE; + // } int32_t ret = ProcRespNegotiate5_1_0(context); if (ret != DM_OK) { -- Gitee From 4577941883060e71d2a06ba02763ea8f342bfde1 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 20:58:48 +0800 Subject: [PATCH 068/382] =?UTF-8?q?test:=20=E6=B7=BB=E5=8A=A0=E6=8A=A5?= =?UTF-8?q?=E6=96=87=E6=89=93=E5=8D=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index c38393238..26331140f 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -290,6 +290,8 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh LOGE("DmAuthMessageProcessor::CreateMessage msgType %{public}d error.", msgType); break; } + // TODO:调试信息,上库前删除 + LOGD("DmAuthMessageProcessor::CreateMessage %{public}s", SafetyDump(jsonObj)); return SafetyDump(jsonObj); } -- Gitee From e1c60dc264153f210068255c8a912a8e41e7e1c2 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 21:01:13 +0800 Subject: [PATCH 069/382] test: --- .../src/authentication_v2/dm_auth_message_processor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 26331140f..a72c96eb9 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -291,7 +291,7 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh break; } // TODO:调试信息,上库前删除 - LOGD("DmAuthMessageProcessor::CreateMessage %{public}s", SafetyDump(jsonObj)); + LOGD("DmAuthMessageProcessor::CreateMessage %{public}s", SafetyDump(jsonObj).c_str()); return SafetyDump(jsonObj); } -- Gitee From 2054717dc69489ee5bc7edf4d6f0da647ccfb60c Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 21:03:12 +0800 Subject: [PATCH 070/382] test: --- .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index a6d25acc6..0dd94de16 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -145,7 +145,7 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptraccessee.deviceId = static_cast(localDeviceId); - if (context->accesser.tokenIdHash.empty()) { + if (context->accesser.tokenId.empty()) { // 单用户:特征为accesser未传输tokenIdHash // 适用于:FA-FA、SA-SA // 当前无FA-FA_service、SA-SA_service、FA-device(bindTarget暂无peerType) @@ -190,6 +190,7 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptr Date: Mon, 3 Mar 2025 21:04:46 +0800 Subject: [PATCH 071/382] test: --- .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 0dd94de16..753564d76 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -145,7 +145,7 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptraccessee.deviceId = static_cast(localDeviceId); - if (context->accesser.tokenId.empty()) { + if (context->accesser.tokenId == 0) { // 单用户:特征为accesser未传输tokenIdHash // 适用于:FA-FA、SA-SA // 当前无FA-FA_service、SA-SA_service、FA-device(bindTarget暂无peerType) -- Gitee From 660996e0d27509ac374ac4569152b7e5c2fe61f4 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 21:07:36 +0800 Subject: [PATCH 072/382] tmp --- .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 3740fc93a..6b54c32c3 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -120,7 +120,7 @@ int32_t AuthSrcPinAuthStartState::GetPinCodeFromServerInfo(std::shared_ptr serviceInfos; DistributedDeviceProfile::ServiceInfoUniqueKey key; - auto tokenId = std::to_string(context->accessee.tokenId); + auto tokenId = std::to_string(context->accesser.tokenId); key.SetTokenId(tokenId); if (DeviceProfileConnector::GetInstance().GetServiceInfoProfileListByTokenId(key, serviceInfos) == DM_OK) { std::vector filterServiceInfos; -- Gitee From 801983b15b249fc11b87375de71513ee9b616885 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 21:08:52 +0800 Subject: [PATCH 073/382] test: --- .../auth_stages/auth_negotiate.cpp | 13 +++++++------ 1 file changed, 7 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 753564d76..0035ccd72 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -366,12 +366,13 @@ int32_t AuthSinkNegotiateStateMachine::ProcRespNegotiate5_1_0(std::shared_ptraccesser.isOnline = context->softbusConnector->CheckIsOnline(context->accesser.deviceId); // 获取凭据信息 - ret = GetAuthCredentialInfo(context); - if (ret != DM_OK) { - LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to get credential."); - context->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; - return ERR_DM_FAILED; - } + // TODO: 暂时注释 + // ret = GetAuthCredentialInfo(context); + // if (ret != DM_OK) { + // LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to get credential."); + // context->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + // return ERR_DM_FAILED; + // } context->accessee.deviceIdHash = Crypto::Sha256(context->accessee.deviceId); context->accessee.userIdHash = Crypto::Sha256(std::to_string(context->accessee.userId)); -- Gitee From 3ad0a204b3dca8175f69997ee894fb49a0ddecaf Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 21:17:41 +0800 Subject: [PATCH 074/382] test: --- .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 0035ccd72..8711094a3 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -366,7 +366,7 @@ int32_t AuthSinkNegotiateStateMachine::ProcRespNegotiate5_1_0(std::shared_ptraccesser.isOnline = context->softbusConnector->CheckIsOnline(context->accesser.deviceId); // 获取凭据信息 - // TODO: 暂时注释 + // TODO: 暂时注释,不阻塞云瑞联调 // ret = GetAuthCredentialInfo(context); // if (ret != DM_OK) { // LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to get credential."); @@ -413,6 +413,7 @@ int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr con LOGE("AuthSinkNegotiateStateMachine::Action proc response negotiate failed"); return ret; } + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_ACL_NEGOTIATE, context); context->timer->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), DmAuthState::GetTaskTimeout(context, WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this, context] (std::string name) { DmAuthState::HandleAuthenticateTimeout(context, name); -- Gitee From 5d207e6a23c6d0de96935b51102f03ed0c557c35 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 3 Mar 2025 21:29:49 +0800 Subject: [PATCH 075/382] test: --- .../src/authentication_v2/dm_auth_message_processor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index a72c96eb9..21f4e756e 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -291,7 +291,7 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh break; } // TODO:调试信息,上库前删除 - LOGD("DmAuthMessageProcessor::CreateMessage %{public}s", SafetyDump(jsonObj).c_str()); + LOGI("DmAuthMessageProcessor::CreateMessage %{public}s", SafetyDump(jsonObj).c_str()); return SafetyDump(jsonObj); } -- Gitee From 12ce87de203913ef8bd3878ed3813f9ec2510215 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 21:31:51 +0800 Subject: [PATCH 076/382] tmp --- .../implementation/src/authentication/dm_auth_manager.cpp | 6 +++--- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 99e7125d1..3c7063a58 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -58,13 +58,13 @@ const int32_t NEGOTIATE_TIMEOUT = 10; const int32_t INPUT_TIMEOUT = 60; const int32_t ADD_TIMEOUT = 10; const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; -const int32_t WAIT_REQUEST_TIMEOUT = 10; +const int32_t WAIT_REQUEST_TIMEOUT = 60; const int32_t CLONE_AUTHENTICATE_TIMEOUT = 20; -const int32_t CLONE_CONFIRM_TIMEOUT = 10; +const int32_t CLONE_CONFIRM_TIMEOUT = 60; const int32_t CLONE_NEGOTIATE_TIMEOUT = 10; const int32_t CLONE_ADD_TIMEOUT = 10; const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10; -const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10; +const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 60; const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20; const int32_t HML_SESSION_TIMEOUT = 10; const int32_t CANCEL_PIN_CODE_DISPLAY = 1; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 90861842f..48cc5f48d 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -54,12 +54,12 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) { LOGI("AuthSrcConfirmState::Action start"); context->timer->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); +#if 0 // todo nlohmann::json jsonObject = nlohmann::json::parse(context->accessee.credentialInfos, nullptr, false); if (jsonObject.is_discarded()) { LOGE("AuthSrcConfirmState::Action parse credentialInfos error"); return ERR_DM_FAILED; } -#if 0 // todo // 转结束绑定 // 转凭据认证 -- Gitee From 46baa134d693f5d10ff0fca3ddf58a014a108a0e Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 22:26:23 +0800 Subject: [PATCH 077/382] tmp --- .../implementation/src/authentication_v2/auth_manager.cpp | 6 ++++++ .../src/authentication_v2/auth_stages/auth_confirm.cpp | 2 +- 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 112cc1295..3fc1df3ee 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -770,15 +770,18 @@ int32_t AuthSinkManager::OnUserOperation(int32_t action, const std::string ¶ context_->authResult = static_cast(action); context_->reply = USER_OPERATION_TYPE_ALLOW_AUTH; if (action == USER_OPERATION_TYPE_CANCEL_AUTH) { + LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_CANCEL_AUTH."); context_->reply = USER_OPERATION_TYPE_CANCEL_AUTH; } context_->authStateMachine->NotifyEventFinish(DmEventType::ON_USER_OPERATION); break; case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT: + LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT."); context_->reason = ERR_DM_TIME_OUT; context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); break; case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY: + LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY."); context_->reason = ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY; context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); break; @@ -889,11 +892,14 @@ int32_t AuthSrcManager::OnUserOperation(int32_t action, const std::string ¶m switch (action) { case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT: + LOGE("AuthSrcManager OnUserOperation user cancel"); context_->reason = ERR_DM_BIND_USER_CANCEL_ERROR; context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); break; case USER_OPERATION_TYPE_DONE_PINCODE_INPUT: + LOGE("AuthSrcManager OnUserOperation user input done"); context_->pinCode = std::atoi(params.c_str()); + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_USER_OPERATION); break; default: LOGE("this action id not support"); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 48cc5f48d..c8d695174 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -219,7 +219,7 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) { LOGI("AuthSinkConfirmState::Action start"); // 停止授权报文计时 - context->timer->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); + context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); context->requestId = GenRequestId(context); auto ret = GetAuthType(context); if (ret != DM_OK) { -- Gitee From 0dd1c98b3f63be7e034776bd3429c1ae7973b4b2 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 22:42:36 +0800 Subject: [PATCH 078/382] tmp --- .../implementation/src/authentication_v2/auth_manager.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 3fc1df3ee..b794dc394 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -777,11 +777,13 @@ int32_t AuthSinkManager::OnUserOperation(int32_t action, const std::string ¶ break; case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT: LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT."); + context->authResult = USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT; context_->reason = ERR_DM_TIME_OUT; context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); break; case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY: LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY."); + context->authResult = USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY; context_->reason = ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY; context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); break; @@ -893,11 +895,13 @@ int32_t AuthSrcManager::OnUserOperation(int32_t action, const std::string ¶m switch (action) { case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT: LOGE("AuthSrcManager OnUserOperation user cancel"); + context->authResult = USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT; context_->reason = ERR_DM_BIND_USER_CANCEL_ERROR; context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); break; case USER_OPERATION_TYPE_DONE_PINCODE_INPUT: LOGE("AuthSrcManager OnUserOperation user input done"); + context->authResult = USER_OPERATION_TYPE_DONE_PINCODE_INPUT; context_->pinCode = std::atoi(params.c_str()); context_->authStateMachine->NotifyEventFinish(DmEventType::ON_USER_OPERATION); break; -- Gitee From 72f235c5e33997afef5dac2d7713b44f92649a07 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 3 Mar 2025 22:43:59 +0800 Subject: [PATCH 079/382] tmp --- .../implementation/src/authentication_v2/auth_manager.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index b794dc394..82304639c 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -777,13 +777,13 @@ int32_t AuthSinkManager::OnUserOperation(int32_t action, const std::string ¶ break; case USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT: LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT."); - context->authResult = USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT; + context_->authResult = USER_OPERATION_TYPE_AUTH_CONFIRM_TIMEOUT; context_->reason = ERR_DM_TIME_OUT; context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); break; case USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY: LOGI("AuthSinkManager::OnUserOperation USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY."); - context->authResult = USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY; + context_->authResult = USER_OPERATION_TYPE_CANCEL_PINCODE_DISPLAY; context_->reason = ERR_DM_BIND_USER_CANCEL_PIN_CODE_DISPLAY; context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); break; @@ -895,13 +895,13 @@ int32_t AuthSrcManager::OnUserOperation(int32_t action, const std::string ¶m switch (action) { case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT: LOGE("AuthSrcManager OnUserOperation user cancel"); - context->authResult = USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT; + context_->authResult = USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT; context_->reason = ERR_DM_BIND_USER_CANCEL_ERROR; context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); break; case USER_OPERATION_TYPE_DONE_PINCODE_INPUT: LOGE("AuthSrcManager OnUserOperation user input done"); - context->authResult = USER_OPERATION_TYPE_DONE_PINCODE_INPUT; + context_->authResult = USER_OPERATION_TYPE_DONE_PINCODE_INPUT; context_->pinCode = std::atoi(params.c_str()); context_->authStateMachine->NotifyEventFinish(DmEventType::ON_USER_OPERATION); break; -- Gitee From b68ac45644a434bfe6ac6d5e09d37afb647405da Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 10:46:49 +0800 Subject: [PATCH 080/382] auth pin code hichain fix --- .../hichain/hichain_auth_connector.h | 3 ++ .../auth_stages/auth_pin_auth.cpp | 3 +- .../hichain/hichain_auth_connector.cpp | 29 +++++++++++++++++++ 3 files changed, 33 insertions(+), 2 deletions(-) diff --git a/services/implementation/include/dependency/hichain/hichain_auth_connector.h b/services/implementation/include/dependency/hichain/hichain_auth_connector.h index ad5bea6e0..edbdc064f 100644 --- a/services/implementation/include/dependency/hichain/hichain_auth_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_auth_connector.h @@ -73,6 +73,9 @@ public: // 凭据认证 pinCode pin码(点对点临时凭据必填) int32_t AuthCredential(int32_t osAccountId, int64_t authReqId, const std::string &credId, const std::string &pinCode); + // pin码 认证 + int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, const std::string &pkgName, + const std::string &pinCode); private: void FreeJsonString(char *jsonStr); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 6b54c32c3..b8bf10b10 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -182,9 +182,8 @@ int32_t AuthSrcPinAuthStartState::AuthDevice(std::shared_ptr cont { int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); - std::string credId; // leave empty for pin auth std::string pinCode = std::to_string(context->pinCode); - auto ret = context->hiChainAuthConnector->AuthCredential(osAccountId, context->requestId, credId, pinCode); + auto ret = context->hiChainAuthConnector->AuthCredentialPinCode(osAccountId, context->requestId, context->pkgName, pinCode); if (ret != DM_OK) { LOGE("AuthSrcPinAuthStartState::AuthDevice failed."); diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 3f82df5de..a973476c4 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -218,6 +218,35 @@ int32_t HiChainAuthConnector::AuthCredential(int32_t osAccountId, int64_t authRe return DM_OK; } +// pin码认证 +int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, const std::string &pkgName, + const std::string &pinCode) +{ + LOGI("HiChainAuthConnector::AuthCredential start."); + if (credId.empty() || pinCode.empty()) { + LOGE("HiChainAuthConnector::AuthCredentialPinCode failed, pkgName or pinCode is empty."); + return ERR_DM_FAILED; + } + + // 创建authParams的json格式字符串 + nlohmann::json jsonAuthParam; + + jsonAuthParam["pinCode"] = pinCode; + jsonAuthParam["servicePkgName"] = pkgName; + + std::string authParams = SafetyDump(jsonAuthParam); + + // 凭据认证 + const CredAuthManager *credAuthManager = GetCredAuthInstance(); + int32_t ret = credAuthManager->authCredential(osAccountId, authReqId, authParams.c_str(), &deviceAuthCallback_); + if (ret != HC_SUCCESS) { + LOGE("HiChainAuthConnector::AuthCredential failed ret %{public}d.", ret); + return ERR_DM_FAILED; + } + + return DM_OK; +} + bool HiChainAuthConnector::onTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) { LOGI("AuthDevice onTransmit, requestId %{public}" PRId64, requestId); -- Gitee From 6f3c0baf4da866c3f9cd31cbb02d6b856bfd5458 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 10:49:33 +0800 Subject: [PATCH 081/382] auth pin code hichain fix --- .../include/dependency/hichain/hichain_auth_connector.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/include/dependency/hichain/hichain_auth_connector.h b/services/implementation/include/dependency/hichain/hichain_auth_connector.h index edbdc064f..f8c1562e5 100644 --- a/services/implementation/include/dependency/hichain/hichain_auth_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_auth_connector.h @@ -74,7 +74,7 @@ public: int32_t AuthCredential(int32_t osAccountId, int64_t authReqId, const std::string &credId, const std::string &pinCode); // pin码 认证 - int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, const std::string &pkgName, + int32_t AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, const std::string &pkgName, const std::string &pinCode); private: -- Gitee From 78243817a58c71ba928d089b46f5889a9a13d45c Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 10:55:00 +0800 Subject: [PATCH 082/382] auth pin code hichain fix --- .../src/dependency/hichain/hichain_auth_connector.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index a973476c4..af801fecf 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -223,7 +223,7 @@ int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t const std::string &pinCode) { LOGI("HiChainAuthConnector::AuthCredential start."); - if (credId.empty() || pinCode.empty()) { + if (pkgName.empty() || pinCode.empty()) { LOGE("HiChainAuthConnector::AuthCredentialPinCode failed, pkgName or pinCode is empty."); return ERR_DM_FAILED; } -- Gitee From 3da2d246ea486c3fbcdf2b7528165dae709b3623 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 11:23:00 +0800 Subject: [PATCH 083/382] pin code hichain --- .../include/authentication_v2/auth_manager.h | 2 +- .../dependency/hichain/hichain_auth_connector.h | 2 +- .../dependency/hichain/hichain_connector_callback.h | 2 +- .../src/authentication_v2/auth_manager.cpp | 3 ++- .../authentication_v2/auth_stages/auth_pin_auth.cpp | 6 ++---- .../dependency/hichain/hichain_auth_connector.cpp | 12 +++++++----- 6 files changed, 14 insertions(+), 13 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index f61dcfb53..d3aeb9455 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -68,7 +68,7 @@ public: std::shared_ptr GetAuthContext(); // 各类事件触发的函数实现(虚函数) - int32_t GetPinCode(int32_t &code) override; + int32_t GetPinCode(std::string &pkgName, int32_t &code) override; int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, const std::map &bindParam); diff --git a/services/implementation/include/dependency/hichain/hichain_auth_connector.h b/services/implementation/include/dependency/hichain/hichain_auth_connector.h index f8c1562e5..a70057831 100644 --- a/services/implementation/include/dependency/hichain/hichain_auth_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_auth_connector.h @@ -75,7 +75,7 @@ public: const std::string &pinCode); // pin码 认证 int32_t AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, const std::string &pkgName, - const std::string &pinCode); + int32_t pinCode); private: void FreeJsonString(char *jsonStr); diff --git a/services/implementation/include/dependency/hichain/hichain_connector_callback.h b/services/implementation/include/dependency/hichain/hichain_connector_callback.h index 1e8e73f43..3e5911e6c 100644 --- a/services/implementation/include/dependency/hichain/hichain_connector_callback.h +++ b/services/implementation/include/dependency/hichain/hichain_connector_callback.h @@ -37,7 +37,7 @@ public: virtual void AuthDeviceFinish(int64_t requestId) = 0; virtual void AuthDeviceError(int64_t requestId, int32_t errorCode) = 0; virtual void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) = 0; - virtual int32_t GetPinCode(int32_t &code) = 0; + virtual int32_t GetPinCode(std::string &pkgName, int32_t &code) = 0; virtual void GetRemoteDeviceId(std::string &deviceId) = 0; }; } // namespace DistributedHardware diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 82304639c..1685ce63e 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -1052,13 +1052,14 @@ void AuthSinkManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *ses context_->authStateMachine->NotifyEventFinish(ON_SESSION_KEY_RETURNED); } -int32_t AuthManager::GetPinCode(int32_t &code) +int32_t AuthManager::GetPinCode(std::string &pkgName, int32_t &code) { if (context_ == nullptr) { LOGE("AuthManager failed to GetPinCode because context_ is nullptr"); return ERR_DM_FAILED; } LOGI("GetPinCode called."); + pkgName = context_->pkgName; code = context_->pinCode; return DM_OK; } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index b8bf10b10..5542b7faf 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -181,10 +181,8 @@ int32_t AuthSrcPinAuthStartState::GetPinCode(std::shared_ptr cont int32_t AuthSrcPinAuthStartState::AuthDevice(std::shared_ptr context) { int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); - - std::string pinCode = std::to_string(context->pinCode); - auto ret = context->hiChainAuthConnector->AuthCredentialPinCode(osAccountId, context->requestId, context->pkgName, pinCode); - + auto ret = context->hiChainAuthConnector->AuthCredentialPinCode(osAccountId, context->requestId, + context->pkgName, context->pinCode); if (ret != DM_OK) { LOGE("AuthSrcPinAuthStartState::AuthDevice failed."); return ret; diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index af801fecf..79508cf00 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -220,10 +220,10 @@ int32_t HiChainAuthConnector::AuthCredential(int32_t osAccountId, int64_t authRe // pin码认证 int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, const std::string &pkgName, - const std::string &pinCode) + int32_t pinCode) { LOGI("HiChainAuthConnector::AuthCredential start."); - if (pkgName.empty() || pinCode.empty()) { + if (pkgName.empty() || pinCode == INVALID_PINCODE) { LOGE("HiChainAuthConnector::AuthCredentialPinCode failed, pkgName or pinCode is empty."); return ERR_DM_FAILED; } @@ -231,8 +231,8 @@ int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t // 创建authParams的json格式字符串 nlohmann::json jsonAuthParam; - jsonAuthParam["pinCode"] = pinCode; - jsonAuthParam["servicePkgName"] = pkgName; + jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); + jsonObj[FIELD_SERVICE_PKG_NAME] = pkgName; std::string authParams = SafetyDump(jsonAuthParam); @@ -268,11 +268,13 @@ char *HiChainAuthConnector::onRequest(int64_t requestId, int operationCode, cons } nlohmann::json jsonObj; int32_t pinCode = INVALID_PINCODE; - if (dmDeviceAuthCallback_->GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE) { + std::string pkgName; + if (dmDeviceAuthCallback_->GetPinCode(pkgName, pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE || pkgName.empty()) { jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; } else { jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); + jsonObj[FIELD_SERVICE_PKG_NAME] = pkgName; } std::string deviceId = ""; dmDeviceAuthCallback_->GetRemoteDeviceId(deviceId); -- Gitee From 7f5057e165f8f96c0c74ef3d7a8e7727129be965 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Tue, 4 Mar 2025 11:23:47 +0800 Subject: [PATCH 084/382] =?UTF-8?q?fix:=20=E4=BF=AE=E6=AD=A380=E4=B8=AD?= =?UTF-8?q?=E7=9A=84dmVersion?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 223a26ff6..100c8f99e 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -325,7 +325,7 @@ int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr void DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject) { // 目前未看到使用了cryptoAdapter_,删除 - jsonObject[TAG_DEVICE_VERSION] = context->accesser.dmVersion; + jsonObject[DM_TAG_DMVERSION] = context->accesser.dmVersion; jsonObject[TAG_DEVICE_NAME] = context->accesser.deviceName; jsonObject[TAG_DEVICE_ID_HASH] = context->accesser.deviceIdHash; -- Gitee From 0e2cd9963839ff49868c03029868bb34030f1247 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 11:36:52 +0800 Subject: [PATCH 085/382] pin code hichain --- .../dependency/hichain/hichain_connector_callback.h | 7 ++++++- .../src/dependency/hichain/hichain_auth_connector.cpp | 6 ++++-- 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/services/implementation/include/dependency/hichain/hichain_connector_callback.h b/services/implementation/include/dependency/hichain/hichain_connector_callback.h index 3e5911e6c..92f11240b 100644 --- a/services/implementation/include/dependency/hichain/hichain_connector_callback.h +++ b/services/implementation/include/dependency/hichain/hichain_connector_callback.h @@ -37,7 +37,12 @@ public: virtual void AuthDeviceFinish(int64_t requestId) = 0; virtual void AuthDeviceError(int64_t requestId, int32_t errorCode) = 0; virtual void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) = 0; - virtual int32_t GetPinCode(std::string &pkgName, int32_t &code) = 0; + virtual int32_t GetPinCode(std::string &pkgName, int32_t &code) + { + pkgName = ""; + return GetPinCode(code); + }; + virtual int32_t GetPinCode(int32_t &code) = 0; virtual void GetRemoteDeviceId(std::string &deviceId) = 0; }; } // namespace DistributedHardware diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 79508cf00..9977d4d2c 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -269,12 +269,14 @@ char *HiChainAuthConnector::onRequest(int64_t requestId, int operationCode, cons nlohmann::json jsonObj; int32_t pinCode = INVALID_PINCODE; std::string pkgName; - if (dmDeviceAuthCallback_->GetPinCode(pkgName, pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE || pkgName.empty()) { + if (dmDeviceAuthCallback_->GetPinCode(pkgName, pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE) { jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; } else { jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); - jsonObj[FIELD_SERVICE_PKG_NAME] = pkgName; + if (!pkgName.empty()) { + jsonObj[FIELD_SERVICE_PKG_NAME] = pkgName; + } } std::string deviceId = ""; dmDeviceAuthCallback_->GetRemoteDeviceId(deviceId); -- Gitee From 6dd11144deede4d5fc8c3d4c361429b36f7de08a Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 11:39:06 +0800 Subject: [PATCH 086/382] pin code hichain --- .../src/dependency/hichain/hichain_auth_connector.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 9977d4d2c..d2411ea76 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -231,8 +231,8 @@ int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t // 创建authParams的json格式字符串 nlohmann::json jsonAuthParam; - jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); - jsonObj[FIELD_SERVICE_PKG_NAME] = pkgName; + jsonAuthParam[FIELD_PIN_CODE] = std::to_string(pinCode); + jsonAuthParam[FIELD_SERVICE_PKG_NAME] = pkgName; std::string authParams = SafetyDump(jsonAuthParam); -- Gitee From e38e590618dc94c478d1e1f36433c07b97f8b6cd Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 11:43:53 +0800 Subject: [PATCH 087/382] pin code hichain --- .../implementation/include/authentication_v2/auth_manager.h | 1 + .../implementation/src/authentication_v2/auth_manager.cpp | 6 ++++++ 2 files changed, 7 insertions(+) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index d3aeb9455..00abe1737 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -69,6 +69,7 @@ public: // 各类事件触发的函数实现(虚函数) int32_t GetPinCode(std::string &pkgName, int32_t &code) override; + int32_t GetPinCode(int32_t &code) override; int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, const std::map &bindParam); diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 1685ce63e..5177b8d70 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -1064,5 +1064,11 @@ int32_t AuthManager::GetPinCode(std::string &pkgName, int32_t &code) return DM_OK; } +int32_t AuthManager::GetPinCode(int32_t &code) +{ + std::string pkgName; + return GetPinCode(pkgName, code); +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file -- Gitee From 2b9cc469e0233d6069506cd11b300a04990b3079 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 11:55:11 +0800 Subject: [PATCH 088/382] tmp --- .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 5542b7faf..dc154d45d 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -277,7 +277,7 @@ int32_t AuthSrcPinAuthMsgNegotiateState::Action(std::shared_ptr c DmAuthStateType AuthSinkPinAuthMsgNegotiateState::GetStateType() { - return DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE; + return DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE; } int32_t AuthSinkPinAuthMsgNegotiateState::Action(std::shared_ptr context) -- Gitee From 92cc21cce11807703f397291d4a0c87843c87ab3 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Tue, 4 Mar 2025 14:05:37 +0800 Subject: [PATCH 089/382] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E8=B7=B3=E8=BD=AC?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.h | 2 +- .../dm_auth_message_processor.cpp | 20 +++++++++++++++++-- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 5e635dc70..66f979ae9 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -192,7 +192,7 @@ private: // 解析 150报文信息MSG_TYPE_RESP_CREDENTIAL_EXCHANGE,存放对方公钥,和协商凭据Id int32_t ParseMessageRspCredExchange(const nlohmann::json &jsonObject, std::shared_ptr context); // 解析161 170 171 - int32_t ParseMessageNegotiateTransmit(const nlohmann::json &jsonObject, std::shared_ptr &context); + int32_t ParseMessageNegotiateTransmit(const nlohmann::json &jsonObject, std::shared_ptr &context, DmMessageType msgType); // 创建 80报文 void CreateNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject); diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 100c8f99e..c86b0c69c 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -112,8 +112,9 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont case MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE: // 161 case MSG_TYPE_RESP_CREDENTIAL_AUTH_START: // 170 case MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE: // 171 + return ParseMessageNegotiateTransmit(jsonObject, context, msgType); case MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE: - return ParseMessageNegotiateTransmit(jsonObject, context); + case MSG_TYPE_REQ_CREDENTIAL_EXCHANGE: return ParseMessageReqCredExchange(jsonObject, context); case MSG_TYPE_RESP_CREDENTIAL_EXCHANGE: @@ -125,7 +126,7 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont } int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const nlohmann::json &jsonObject, - std::shared_ptr &context) + std::shared_ptr &context, DmMessageType msgType) { if (jsonObject.is_discarded() || !jsonObject.contains(DM_TAG_DATA) || !jsonObject[DM_TAG_DATA].is_string()) { LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae Unlegal json string failed"); @@ -144,6 +145,20 @@ int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const nlohmann::js LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae ParseMessageOnTransmit failed"); return ERR_DM_FAILED; } + switch (msgType) { + case MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE: // 161 + context->authStateMachine->TransitionTo(std::make_shared()); + break; + case MSG_TYPE_RESP_CREDENTIAL_AUTH_START: // 170 + context->authStateMachine->TransitionTo(std::make_shared()); + break; + case MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE: // 171 + context->authStateMachine->TransitionTo(std::make_shared()); + break; + default: + return ERR_DM_FAILED; + } + return DM_OK; } @@ -831,6 +846,7 @@ int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(nlohmann::json &jsonObject return ERR_DM_FAILED; } context->accesser.appCredentialId = jsonDecrptObj[jsonTag].get(); + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } -- Gitee From f748e6373cdbf3a8a9b005d6d6bff5d6ab6a231a Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Tue, 4 Mar 2025 14:10:16 +0800 Subject: [PATCH 090/382] =?UTF-8?q?fix=EF=BC=9Atmp140-150=E5=8A=A0?= =?UTF-8?q?=E4=B8=8A=E8=B7=B3=E8=BD=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.h | 6 +++-- .../auth_stages/auth_pin_auth.cpp | 2 +- .../dm_auth_message_processor.cpp | 24 +++++++++++++++---- 3 files changed, 25 insertions(+), 7 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 66f979ae9..b1e902531 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -154,7 +154,7 @@ public: // 解析透传ON_TRANSMIT字段 std::string GetTransmitFromContext(std::shared_ptr &context); - + // 创建报文并发送 void CreateAndSendMsg(DmMessageType msgType, std::shared_ptr context); @@ -185,7 +185,9 @@ private: int32_t ParseMessageRespPinAuthStart(const nlohmann::json &json, std::shared_ptr context); // 解析 121 报文 int32_t ParseMessageReqPinAuthNegotiate(const nlohmann::json &json, std::shared_ptr context); - // 解析 131报文onTransmitData返回的数据,存在contextd->extra中 + // 解析 131报文 + int32_t ParseMessageRespPinAuthNegotiate(const nlohmann::json &jsonObject, std::shared_ptr context) + // 解析onTransmit int32_t ParseMessageOnTransmit(const nlohmann::json &jsonObject, std::shared_ptr context); // 解析 140报文信息MSG_TYPE_REQ_CREDENTIAL_EXCHANGE,SINK端存放对方公钥 int32_t ParseMessageReqCredExchange(const nlohmann::json &jsonObject, std::shared_ptr context); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index dc154d45d..bd5c4d8e3 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -340,7 +340,7 @@ int32_t AuthSrcPinAuthDoneState::Action(std::shared_ptr context) } std::string onTransmitData; - if (context->GetFromContextExtra(DM_TAG_DATA, onTransmitData) != DM_OK) { + if (context->GetFromContextExtra(DM_TAG_ON_TRANSMIT_DATA, onTransmitData) != DM_OK) { LOGE("AuthSrcPinAuthDoneState::Action error, get onTransmitData From extra failed."); return ERR_DM_FAILED; } diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index c86b0c69c..ede512bcc 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -54,7 +54,7 @@ int32_t DmAuthMessageProcessor::SaveSessionKeyToDP(int32_t &skId) LOGE("DmAuthMessageProcessor::SaveSessionKey failed, cryptoMgr_ is nullptr."); return ERR_DM_FAILED; } - uint8_t* sessionKey = nullptr; + uint8_t* sessionKey = nullptr; uint32_t skLen = cryptoMgr_->GetSessionKey(sessionKey); return DeviceProfileConnector::GetInstance().PutSessionKey(sessionKey, skLen, skId); } @@ -114,7 +114,7 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont case MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE: // 171 return ParseMessageNegotiateTransmit(jsonObject, context, msgType); case MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE: - + return ParseMessageRespPinAuthNegotiate(jsonObject, context); case MSG_TYPE_REQ_CREDENTIAL_EXCHANGE: return ParseMessageReqCredExchange(jsonObject, context); case MSG_TYPE_RESP_CREDENTIAL_EXCHANGE: @@ -158,7 +158,7 @@ int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const nlohmann::js default: return ERR_DM_FAILED; } - + return DM_OK; } @@ -175,6 +175,20 @@ int32_t DmAuthMessageProcessor::ParseMessageOnTransmit(const nlohmann::json &jso return DM_OK; } +// 解析131报文信息MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE +int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate(const nlohmann::json &jsonObject, + std::shared_ptr context) +{ + if (jsonObject.is_discarded() || !IsString(jsonObject, DM_TAG_DATA)) { + LOGE("DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate failed, decodeRequestAuth jsonStr error"); + return ERR_DM_FAILED; + } + + context->SetContextExtra(DM_TAG_ON_TRANSMIT_DATA, jsonObject[DM_TAG_DATA].get()); + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + // 解析140报文信息MSG_TYPE_REQ_CREDENTIAL_EXCHANGE,SINK端存放对方公钥 int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const nlohmann::json &jsonObject, std::shared_ptr context) @@ -212,6 +226,7 @@ int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const nlohmann::json context->accesser.deviceId = jsonData[DM_TAG_DEVICE_ID].get(); // 解析deviceId context->accesser.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].get(); // 解析userId context->accesser.tokenId = jsonData[DM_TAG_TOKEN_ID].get(); // 解析tokenId + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -259,6 +274,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const nlohmann::json context->accessee.deviceId = jsonData[DM_TAG_DEVICE_ID].get(); // 解析deviceId context->accessee.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].get(); // 解析userId context->accessee.tokenId = jsonData[DM_TAG_TOKEN_ID].get(); // 解析tokenId + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -795,7 +811,7 @@ int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr LOGE("DmAuthMessageProcessor::CreateSyncMessage encrypt failed"); return ret; } - jsonObject[DM_TAG_SYNC] = encSyncMsg; + jsonObject[DM_TAG_SYNC] = encSyncMsg; return DM_OK; } -- Gitee From ac15449512e3a73f9af76aa38c1a6ce53607ad56 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 14:28:01 +0800 Subject: [PATCH 091/382] tmp --- .../src/authentication_v2/dm_auth_message_processor.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index ede512bcc..807de6d27 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -129,20 +129,20 @@ int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const nlohmann::js std::shared_ptr &context, DmMessageType msgType) { if (jsonObject.is_discarded() || !jsonObject.contains(DM_TAG_DATA) || !jsonObject[DM_TAG_DATA].is_string()) { - LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae Unlegal json string failed"); + LOGE("DmAuthMessageProcessor::ParseMessageNegotiateTransmit Unlegal json string failed"); return ERR_DM_FAILED; } // 解密 std::string plainText; int32_t ret = cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA], plainText); if (ret != DM_OK) { - LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae DecryptMessage failed"); + LOGE("DmAuthMessageProcessor::ParseMessageNegotiateTransmit DecryptMessage failed"); return ret; } nlohmann::json jsonDecrptObj = plainText; if (ParseMessageOnTransmit(jsonDecrptObj, context) != DM_OK) { - LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae ParseMessageOnTransmit failed"); + LOGE("DmAuthMessageProcessor::ParseMessageNegotiateTransmit ParseMessageOnTransmit failed"); return ERR_DM_FAILED; } switch (msgType) { -- Gitee From f920fda9e21828b7e2af0582c450bc4151b67284 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 14:32:14 +0800 Subject: [PATCH 092/382] tmp --- .../include/authentication_v2/dm_auth_message_processor.h | 5 +++-- .../implementation/include/authentication_v2/dm_auth_state.h | 4 ++++ 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index b1e902531..4daff9006 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -186,7 +186,7 @@ private: // 解析 121 报文 int32_t ParseMessageReqPinAuthNegotiate(const nlohmann::json &json, std::shared_ptr context); // 解析 131报文 - int32_t ParseMessageRespPinAuthNegotiate(const nlohmann::json &jsonObject, std::shared_ptr context) + int32_t ParseMessageRespPinAuthNegotiate(const nlohmann::json &jsonObject, std::shared_ptr context); // 解析onTransmit int32_t ParseMessageOnTransmit(const nlohmann::json &jsonObject, std::shared_ptr context); // 解析 140报文信息MSG_TYPE_REQ_CREDENTIAL_EXCHANGE,SINK端存放对方公钥 @@ -194,7 +194,8 @@ private: // 解析 150报文信息MSG_TYPE_RESP_CREDENTIAL_EXCHANGE,存放对方公钥,和协商凭据Id int32_t ParseMessageRspCredExchange(const nlohmann::json &jsonObject, std::shared_ptr context); // 解析161 170 171 - int32_t ParseMessageNegotiateTransmit(const nlohmann::json &jsonObject, std::shared_ptr &context, DmMessageType msgType); + int32_t ParseMessageNegotiateTransmit(const nlohmann::json &jsonObject, std::shared_ptr &context, + DmMessageType msgType); // 创建 80报文 void CreateNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject); diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index cf46f6ffa..6bb7a5556 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -244,6 +244,7 @@ public: }; // 收到170凭据认证报文,解析ontransmit,回复161报文 class AuthSrcCredentialAuthNegotiateState : public DmAuthState { +public: virtual ~AuthSrcCredentialAuthNegotiateState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; // 执行状态对应的action动作 @@ -251,6 +252,7 @@ class AuthSrcCredentialAuthNegotiateState : public DmAuthState { // 收到171凭据认证报文 发送160/180 报文 class AuthSrcCredentialAuthDoneState : public DmAuthState { +public: virtual ~AuthSrcCredentialAuthDoneState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; // 执行状态对应的action动作 @@ -258,6 +260,7 @@ class AuthSrcCredentialAuthDoneState : public DmAuthState { // 收到160凭证认证报文 发送170报文 class AuthSinkCredentialAuthStartState : public DmAuthState { +public: virtual ~AuthSinkCredentialAuthStartState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; // 执行状态对应的action动作 @@ -265,6 +268,7 @@ class AuthSinkCredentialAuthStartState : public DmAuthState { // 收到161凭据协商报文 并回复171报文 class AuthSinkCredentialAuthNegotiateState : public DmAuthState { +public: virtual ~AuthSinkCredentialAuthNegotiateState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; // 执行状态对应的action动作 -- Gitee From 8d1cb9d85c701710ad0f8eb3489f5d94ece171f3 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Tue, 4 Mar 2025 15:02:28 +0800 Subject: [PATCH 093/382] =?UTF-8?q?fix=EF=BC=9Atmp140-150?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/dm_auth_context.h | 1 + .../implementation/src/authentication_v2/auth_manager.cpp | 3 +++ .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 7 +------ .../src/authentication_v2/dm_auth_message_processor.cpp | 8 ++------ 4 files changed, 7 insertions(+), 12 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 0a245e220..a1c6efef0 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -127,6 +127,7 @@ struct DmAccess { std::string extraInfo; //可扩展字段,kv结构 }; +// TODO 统一用初始化列表进行初始化 struct DmAuthContext { bool isOnline; // 是否上线 DmMessageType msgType; // 报文类型,枚举MsgType diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 5177b8d70..a92070829 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -159,6 +159,8 @@ AuthManager::AuthManager(std::shared_ptr softbusConnector, context_->authenticationMap[AUTH_TYPE_PIN_IMPORT] = nullptr; context_->accesser.dmVersion = DM_VERSION_5_1_0; context_->accessee.dmVersion = DM_VERSION_5_1_0; + + // TODO:上下文的成员,authStateMachine、authMessageProcessor等成员是否统一在构造函数中初始化比较好,目前比较分散 } void AuthManager::SetAuthContext(std::shared_ptr context) @@ -191,6 +193,7 @@ int32_t AuthManager::ParseAuthType(const std::map &bin LOGE("AuthManager::ParseAuthType bind param %{public}s fromat is unsupported.", PARAM_KEY_AUTH_TYPE); return ERR_DM_INPUT_PARA_INVALID; } + // TODO:std::atoi统一排查换成strtol函数 authType = std::atoi(authTypeStr.c_str()); return DM_OK; } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index bd5c4d8e3..fd1724fe5 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -339,13 +339,8 @@ int32_t AuthSrcPinAuthDoneState::Action(std::shared_ptr context) return ERR_DM_FAILED; } - std::string onTransmitData; - if (context->GetFromContextExtra(DM_TAG_ON_TRANSMIT_DATA, onTransmitData) != DM_OK) { - LOGE("AuthSrcPinAuthDoneState::Action error, get onTransmitData From extra failed."); - return ERR_DM_FAILED; - } - // 处理凭据数据 + std::string onTransmitData = context->transmitData; if (context->hiChainAuthConnector->ProcessCredData(context->requestId, onTransmitData) != DM_OK) { LOGE("AuthSrcPinAuthDoneState::Action failed, processCredData failed."); return ERR_DM_FAILED; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 807de6d27..6104dd056 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -184,7 +184,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate(const nlohmann: return ERR_DM_FAILED; } - context->SetContextExtra(DM_TAG_ON_TRANSMIT_DATA, jsonObject[DM_TAG_DATA].get()); + context->transmitData = jsonObject[DM_TAG_DATA].get(); context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -438,13 +438,9 @@ void DmAuthMessageProcessor::CreateMessageReqCredAuthStart(std::shared_ptrGetFromContextExtra(DM_TAG_ON_TRANSMIT_DATA, onTransmitData) != DM_OK) { - LOGE("DmAuthMessageProcessor::CreateMessageReqCredAuthStart failed, get onTransmitData from extra failed."); - return; - } nlohmann::json jsonData; - jsonData[DM_TAG_ON_TRANSMIT_DATA] = onTransmitData; + jsonData[DM_TAG_ON_TRANSMIT_DATA] = context->transmitData; if (!context->isAppCredentialVerified) { // 应用级凭据认证 jsonData[DM_TAG_APP_CREDENTIAL_ID] = context->accesser.appCredentialId; } else if (!context->isOnline) { // 首次用户级凭据认证 -- Gitee From 40223f6c83f33262f624098791bb52d5313f5a64 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 15:05:10 +0800 Subject: [PATCH 094/382] tmp --- .../implementation/src/authentication_v2/auth_manager.cpp | 6 +++++- .../src/authentication_v2/dm_auth_state_machine.cpp | 2 ++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index a92070829..83b9c8808 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -935,12 +935,14 @@ void AuthSrcManager::AuthDeviceError(int64_t requestId, int32_t errorCode) // 失败 MAX_AUTH_FAIL_TIMES 次后,走认证失败 ON_FAIL if (context_->authFailTimes >= MAX_AUTH_FAIL_TIMES) { + LOGI("AuthSrcManager::AuthDeviceError Auth pin err fail."); context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); } else { // Notify ON_ERROR 事件,对应 Action 内会当正常重试处理,而非失败 context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); // 回退状态到 AuthSrcPinAuthStartState context_->authStateMachine->TransitionTo(std::make_shared()); + LOGI("AuthSrcManager::AuthDeviceError Auth pin err, will retry."); } } LOGI("AuthSrcManager::AuthDeviceError leave."); @@ -952,7 +954,7 @@ void AuthSinkManager::AuthDeviceError(int64_t requestId, int32_t errorCode) auto curState = context_->authStateMachine->GetCurState(); if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE || curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE) { - LOGI("AuthSinkManager::AuthDeviceError Auth pin err."); + if (context_->authType == DmAuthType::AUTH_TYPE_PIN_SHOW) { context_->authFailTimes++; } else if (!context_->fallBackToInputPin) { @@ -971,12 +973,14 @@ void AuthSinkManager::AuthDeviceError(int64_t requestId, int32_t errorCode) } // 失败 MAX_AUTH_FAIL_TIMES 次后,走认证失败 ON_FAIL if (context_->authFailTimes >= MAX_AUTH_FAIL_TIMES) { + LOGI("AuthSinkManager::AuthDeviceError Auth pin err fail."); context_->reason = ERR_DM_INPUT_PARA_INVALID; context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); } else { // Notify ON_ERROR 事件,对应 Action 内会当正常重试处理,而非失败 context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); // 将由新收到的120报文触发回退状态到 AuthSinkPinAuthStartState + LOGI("AuthSinkManager::AuthDeviceError Auth pin err, will retry."); } } LOGI("AuthSinkManager::AuthDeviceError leave."); diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 9559c27af..2eaca1186 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -81,6 +81,8 @@ int32_t DmAuthStateMachine::TransitionTo(std::shared_ptr state) int32_t ret = DM_OK; DmAuthStateType nextState = state->GetStateType(); if (this->CheckStateTransitValid(nextState)) { + LOGE("DmAuthStateMachine: The state transition from %{public}d to %{public}d.", + GetCurState(), nextState); std::lock_guard lock(mutex_); // 存入到队列中 statesQueue_.push(state); -- Gitee From 7fb4d6dd0876df7b8bb6911dc1798185a4672d07 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Tue, 4 Mar 2025 15:36:27 +0800 Subject: [PATCH 095/382] =?UTF-8?q?fix=EF=BC=9A140-150=E5=8A=A0=E6=97=A5?= =?UTF-8?q?=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/dm_auth_context.h | 13 ++++++++++--- .../src/authentication_v2/auth_manager.cpp | 1 + .../auth_stages/auth_credential.cpp | 2 ++ 3 files changed, 13 insertions(+), 3 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index a1c6efef0..228dec44b 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -198,9 +198,12 @@ struct DmAuthContext { template int32_t SetContextExtra(const std::string &key, const T &value) { - nlohmann::json jsonExtra = nlohmann::json::parse(extraInfo); - if (jsonExtra.is_discarded()) { - return ERR_DM_FAILED; + nlohmann::json jsonExtra; + if (!extraInfo.empty()) { + jsonExtra = nlohmann::json::parse(extraInfo); + if (jsonExtra.is_discarded()) { + return ERR_DM_FAILED; + } } jsonExtra[key] = value; @@ -212,6 +215,10 @@ struct DmAuthContext { template int32_t GetFromContextExtra(const std::string &key, T &value) { + if (extraInfo.empty()) { + return DM_OK; + } + nlohmann::json jsonExtra = nlohmann::json::parse(extraInfo); if (jsonExtra.is_discarded()) { return ERR_DM_FAILED; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 83b9c8808..1f79f0dc0 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -297,6 +297,7 @@ void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sess // 通知ON_SESSION_KEY_RETURNED事件完成 context_->authStateMachine->NotifyEventFinish(ON_SESSION_KEY_RETURNED); + LOGI("AuthSrcManager::AuthDeviceSessionKey leave."); } int32_t AuthManager::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index c216085b0..ef904072e 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -364,6 +364,7 @@ DmAuthStateType AuthSrcCredentialExchangeState::GetStateType() int32_t AuthSrcCredentialExchangeState::Action(std::shared_ptr context) { + LOGI("AuthSrcCredentialExchangeState::Action() start."); int32_t ret = ERR_DM_FAILED; context->isAppCredentialVerified = false; @@ -385,6 +386,7 @@ int32_t AuthSrcCredentialExchangeState::Action(std::shared_ptr co // 发送140报文 std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, context); + LOGI("AuthSrcCredentialExchangeState::Action() leave."); return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); } -- Gitee From 3ec46544231a02d3443ac71b11f7368e8235899e Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 16:13:59 +0800 Subject: [PATCH 096/382] event queue --- .../authentication_v2/dm_auth_state_machine.h | 7 +++-- .../dm_auth_state_machine.cpp | 29 ++++++++++++++++--- 2 files changed, 30 insertions(+), 6 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state_machine.h b/services/implementation/include/authentication_v2/dm_auth_state_machine.h index e793c4ac8..3242f51d3 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state_machine.h +++ b/services/implementation/include/authentication_v2/dm_auth_state_machine.h @@ -80,8 +80,11 @@ private: // 正常状态迁移表,但所有状态切换到Finish状态是合法的 StateTransitionTable stateTransitionTable_; - // 实际事件 - DmEventType actualEventType_; + // 事件队列 + std::queue eventQueue_; + // 异常事件集合 + std::set exceptionEvent_; + std::thread thread_; std::atomic running_; std::queue> statesQueue_; diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 2eaca1186..0e4af9eae 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -64,6 +64,13 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, {DmAuthStateType::AUTH_SINK_FINISH_STATE}}, {DmAuthStateType::AUTH_SINK_FINISH_STATE, {}}, }; + exceptionEvent_= { + DmEventType::ON_ERROR, // ERROR 错误 + DmEventType::ON_TIMEOUT, // 超时 + DmEventType::ON_FAIL, // 失败流程 + DmEventType::ON_SCREEN_LOCKED, // 锁屏 + }; + running_ = true; this->SetCurState(DmAuthStateType::AUTH_IDLE_STATE); @@ -81,7 +88,7 @@ int32_t DmAuthStateMachine::TransitionTo(std::shared_ptr state) int32_t ret = DM_OK; DmAuthStateType nextState = state->GetStateType(); if (this->CheckStateTransitValid(nextState)) { - LOGE("DmAuthStateMachine: The state transition from %{public}d to %{public}d.", + LOGI("DmAuthStateMachine: The state transition from %{public}d to %{public}d.", GetCurState(), nextState); std::lock_guard lock(mutex_); // 存入到队列中 @@ -109,8 +116,17 @@ DmEventType DmAuthStateMachine::WaitExpectEvent(DmEventType eventType) auto startTime = std::chrono::high_resolution_clock::now(); while (true) { eventCv_.wait(lock); - if (actualEventType_ == eventType || actualEventType_ == ON_ERROR) { - return actualEventType_; + // 判断是否有事件到来 + if (!eventQueue_.empty()) { + // 获取事件, TODO:假设正常事件按序到达(状态机单线程按序等待), 是否成立? + DmEventType actualEventType = eventQueue_.front(); + eventQueue_.pop(); + // 判断是否是期望事件 + if (actualEventType == eventType || exceptionEvent_.contains(actualEventType)) { + return actualEventType; + } else { + // TODO: 非期望事件,忽略 or 结束流程 ? + } } // 做一个超时退出机制 // 已经经过的时间 @@ -125,7 +141,12 @@ DmEventType DmAuthStateMachine::WaitExpectEvent(DmEventType eventType) // 事件完成调用,传事件枚举(只允许在事件触发中调用),如果是异常事件,需在context的reason或者reply记录 void DmAuthStateMachine::NotifyEventFinish(DmEventType eventType) { - actualEventType_ = eventType; + LOGI("DmAuthStateMachine: NotifyEventFinish Event:%{public}d.", eventType); + { + // 添加事件到事件队列 + std::unique_lock lock(mutex_); + eventQueue_.push(eventType); + } eventCv_.notify_one(); } -- Gitee From 3aefe49988bca7b0616f81f11e9c856d34656b4e Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 16:23:51 +0800 Subject: [PATCH 097/382] event queue --- .../src/authentication_v2/dm_auth_state_machine.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 0e4af9eae..5897f4c8d 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -122,7 +122,7 @@ DmEventType DmAuthStateMachine::WaitExpectEvent(DmEventType eventType) DmEventType actualEventType = eventQueue_.front(); eventQueue_.pop(); // 判断是否是期望事件 - if (actualEventType == eventType || exceptionEvent_.contains(actualEventType)) { + if (actualEventType == eventType || (exceptionEvent_.find(actualEventType) != exceptionEvent_.end())) { return actualEventType; } else { // TODO: 非期望事件,忽略 or 结束流程 ? -- Gitee From a46bfa074e6f364f37328f3be77b27fe4c6f0c6f Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 16:59:51 +0800 Subject: [PATCH 098/382] event queue --- .../include/authentication_v2/dm_auth_state_machine.h | 3 ++- .../src/authentication_v2/dm_auth_state_machine.cpp | 8 ++++---- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state_machine.h b/services/implementation/include/authentication_v2/dm_auth_state_machine.h index 3242f51d3..cbb5f29a2 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state_machine.h +++ b/services/implementation/include/authentication_v2/dm_auth_state_machine.h @@ -89,8 +89,9 @@ private: std::atomic running_; std::queue> statesQueue_; // 同步原语 - std::mutex mutex_; + std::mutex stateMutex_; std::condition_variable stateCv_; + std::mutex eventMutex_; std::condition_variable eventCv_; }; diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 5897f4c8d..25accd765 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -90,7 +90,7 @@ int32_t DmAuthStateMachine::TransitionTo(std::shared_ptr state) if (this->CheckStateTransitValid(nextState)) { LOGI("DmAuthStateMachine: The state transition from %{public}d to %{public}d.", GetCurState(), nextState); - std::lock_guard lock(mutex_); + std::lock_guard lock(stateMutex_); // 存入到队列中 statesQueue_.push(state); stateCv_.notify_one(); @@ -111,7 +111,7 @@ DmEventType DmAuthStateMachine::WaitExpectEvent(DmEventType eventType) 2、实际事件 = 异常事件(事件超时等),同样返回实际事件 3、实际事件 = 其余事件,继续阻塞,但有个超时时间限制 */ - std::unique_lock lock(mutex_); + std::unique_lock lock(eventMutex_); // 记录进入函数的时间 auto startTime = std::chrono::high_resolution_clock::now(); while (true) { @@ -144,7 +144,7 @@ void DmAuthStateMachine::NotifyEventFinish(DmEventType eventType) LOGI("DmAuthStateMachine: NotifyEventFinish Event:%{public}d.", eventType); { // 添加事件到事件队列 - std::unique_lock lock(mutex_); + std::unique_lock lock(eventMutex_); eventQueue_.push(eventType); } eventCv_.notify_one(); @@ -178,7 +178,7 @@ void DmAuthStateMachine::Run(std::shared_ptr context) std::optional> DmAuthStateMachine::FetchState() { - std::unique_lock lock(mutex_); + std::unique_lock lock(stateMutex_); stateCv_.wait(lock, [&] { return !running_.load() || !statesQueue_.empty(); }); -- Gitee From 64b8dbfff3823317bc717dbdc2c4cf9bfeaf1859 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 17:13:55 +0800 Subject: [PATCH 099/382] event queue --- .../src/authentication_v2/dm_auth_state_machine.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 25accd765..73ae4dd5f 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -156,6 +156,7 @@ void DmAuthStateMachine::Run(std::shared_ptr context) while (running_.load()) { auto state = FetchState(); if (!state.has_value()) { + LOGI("DmAuthStateMachine::Run : No state to fetch."); // 睡眠 100 毫秒 std::this_thread::sleep_for(std::chrono::milliseconds(100)); continue; @@ -165,6 +166,7 @@ void DmAuthStateMachine::Run(std::shared_ptr context) this->SetCurState(stateType); int32_t ret = state.value()->Action(context); if (ret != DM_OK) { + LOGE("DmAuthStateMachine::Run err:%{public}d", ret); context->reason = ret; if (context->direction == DM_AUTH_SOURCE) { // this->TransitionTo(std::make_shared()); @@ -174,6 +176,7 @@ void DmAuthStateMachine::Run(std::shared_ptr context) // finish需要,清理context以及重启状态机 } } + LOGE("DmAuthStateMachine::Run end"); } std::optional> DmAuthStateMachine::FetchState() @@ -202,6 +205,7 @@ void DmAuthStateMachine::Stop() // 设置当前状态 void DmAuthStateMachine::SetCurState(DmAuthStateType state) { + LOGE("DmAuthStateMachine::SetCurState:%{public}d", state); curState_ = state; } -- Gitee From 132705e32fc2c60a6c5f13974ba2a2a0b55da38a Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 17:24:14 +0800 Subject: [PATCH 100/382] event queue --- .../src/authentication_v2/dm_auth_state_machine.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 73ae4dd5f..1e2059591 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -90,9 +90,11 @@ int32_t DmAuthStateMachine::TransitionTo(std::shared_ptr state) if (this->CheckStateTransitValid(nextState)) { LOGI("DmAuthStateMachine: The state transition from %{public}d to %{public}d.", GetCurState(), nextState); - std::lock_guard lock(stateMutex_); - // 存入到队列中 - statesQueue_.push(state); + { + std::lock_guard lock(stateMutex_); + // 存入到队列中 + statesQueue_.push(state); + } stateCv_.notify_one(); } else { // 切换状态不合法,打印错误日志并返回错误码 -- Gitee From 1cc2a33cd70d22dee75544fde09a57dfb4c7d70f Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 17:54:21 +0800 Subject: [PATCH 101/382] event queue --- .../auth_stages/auth_pin_auth.cpp | 3 +++ .../dm_auth_state_machine.cpp | 25 ++++++++++--------- 2 files changed, 16 insertions(+), 12 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index fd1724fe5..07cd40aa4 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -339,6 +339,7 @@ int32_t AuthSrcPinAuthDoneState::Action(std::shared_ptr context) return ERR_DM_FAILED; } + LOGI("AuthSrcPinAuthDoneState::Action start"); // 处理凭据数据 std::string onTransmitData = context->transmitData; if (context->hiChainAuthConnector->ProcessCredData(context->requestId, onTransmitData) != DM_OK) { @@ -358,9 +359,11 @@ int32_t AuthSrcPinAuthDoneState::Action(std::shared_ptr context) } } + LOGI("AuthSrcPinAuthDoneState::Action wait ON_SESSION_KEY_RETURNED done"); // 阻塞等待ON_FINISH事件到来 ret = context->authStateMachine->WaitExpectEvent(ON_FINISH); if (ret == ON_FINISH) { + LOGI("AuthSrcPinAuthDoneState::Action wait ON_FINISH done"); return DM_OK; } else if (ret == ON_ERROR) { // ON_ERROR事件到来,返回DM_OK, OnError回调中判断是否重试 return DM_OK; diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 1e2059591..8e9f8e449 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -117,18 +117,17 @@ DmEventType DmAuthStateMachine::WaitExpectEvent(DmEventType eventType) // 记录进入函数的时间 auto startTime = std::chrono::high_resolution_clock::now(); while (true) { - eventCv_.wait(lock); - // 判断是否有事件到来 - if (!eventQueue_.empty()) { - // 获取事件, TODO:假设正常事件按序到达(状态机单线程按序等待), 是否成立? - DmEventType actualEventType = eventQueue_.front(); - eventQueue_.pop(); - // 判断是否是期望事件 - if (actualEventType == eventType || (exceptionEvent_.find(actualEventType) != exceptionEvent_.end())) { - return actualEventType; - } else { - // TODO: 非期望事件,忽略 or 结束流程 ? - } + eventCv_.wait(lock, [&] { + return !eventQueue_.empty(); + }); + // 获取事件, TODO:假设正常事件按序到达(状态机单线程按序等待), 是否成立? + DmEventType actualEventType = eventQueue_.front(); + eventQueue_.pop(); + // 判断是否是期望事件 + if (actualEventType == eventType || (exceptionEvent_.find(actualEventType) != exceptionEvent_.end())) { + return actualEventType; + } else { + // TODO: 非期望事件,忽略 or 结束流程 ? } // 做一个超时退出机制 // 已经经过的时间 @@ -176,6 +175,8 @@ void DmAuthStateMachine::Run(std::shared_ptr context) // this->TransitionTo(std::make_shared()); } // finish需要,清理context以及重启状态机 + } else { + LOGE("DmAuthStateMachine::Run ok state:%{public}d", stateType); } } LOGE("DmAuthStateMachine::Run end"); -- Gitee From 969409f7a6eddf391796f504064015b6d83d210d Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Tue, 4 Mar 2025 19:07:04 +0800 Subject: [PATCH 102/382] =?UTF-8?q?fix=EF=BC=9A140-150=EF=BC=8C=E4=BF=AE?= =?UTF-8?q?=E6=94=B9DM=5FTAG=5FCREDENTIAL=5FOWNER=E5=AD=97=E6=AE=B5?= =?UTF-8?q?=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/dm_auth_message_processor.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 4daff9006..420a04abd 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -48,7 +48,7 @@ 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 = "credentialOwner"; +constexpr const char *DM_TAG_CREDENTIAL_OWNER = "credOwner"; constexpr const char *DM_AUTH_CREDENTIAL_OWNER = "DM"; // 凭据拥有者 constexpr const char *DM_TAG_TOKEN_ID = "tokenId"; constexpr const char *DM_TAG_SYNC = "syncMessage"; -- Gitee From 7fdca1a89b65ae23b7728195697c6d794ad8382e Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 19:28:17 +0800 Subject: [PATCH 103/382] tmp --- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 4 +++- .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 5 ++++- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index c8d695174..37ab5ca64 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -131,7 +131,9 @@ int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context DistributedDeviceProfile::ServiceInfoUniqueKey key; auto tokenId = std::to_string(context->accessee.tokenId); key.SetTokenId(tokenId); - if (DeviceProfileConnector::GetInstance().GetServiceInfoProfileListByTokenId(key, serviceInfos) != DM_OK) { + auto ret = DeviceProfileConnector::GetInstance().GetServiceInfoProfileListByTokenId(key, serviceInfos); + if (ret != DM_OK) { + LOGE("AuthSinkConfirmState::GetAuthType GetServiceInfoByTokenId err %{public}d", ret); // 获取不到走PIN认证方案 if (context->authType != DmAuthType::AUTH_TYPE_PIN_SHOW) { LOGE("AuthSinkConfirmState::GetAuthType AUTH_TYPE_PIN_SHOW not match"); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 07cd40aa4..78cb866c2 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -122,7 +122,8 @@ int32_t AuthSrcPinAuthStartState::GetPinCodeFromServerInfo(std::shared_ptraccesser.tokenId); key.SetTokenId(tokenId); - if (DeviceProfileConnector::GetInstance().GetServiceInfoProfileListByTokenId(key, serviceInfos) == DM_OK) { + auto ret = DeviceProfileConnector::GetInstance().GetServiceInfoProfileListByTokenId(key, serviceInfos); + if (ret == DM_OK) { std::vector filterServiceInfos; for (auto& serviceInfo : serviceInfos) { if (serviceInfo.GetServiceId() == 0 && serviceInfo.GetServiceType().empty()) { @@ -134,6 +135,8 @@ int32_t AuthSrcPinAuthStartState::GetPinCodeFromServerInfo(std::shared_ptr Date: Tue, 4 Mar 2025 19:42:11 +0800 Subject: [PATCH 104/382] =?UTF-8?q?fix=EF=BC=9A140-150=E4=BF=AE=E6=94=B9os?= =?UTF-8?q?AccountId=E8=8E=B7=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/dm_auth_context.h | 2 ++ .../auth_stages/auth_credential.cpp | 15 +++++++-------- .../src/authentication_v2/dm_auth_context.cpp | 9 +++++++++ 3 files changed, 18 insertions(+), 8 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 228dec44b..2cab03235 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -193,6 +193,8 @@ struct DmAuthContext { int32_t SetCredentialId(DmAuthSide side, DmAuthScope authorizedScope, const std::string &credentialId); // 设置公钥 int32_t SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope, const std::string &publicKey); + // 获取账号ID + std::string GetAccountId(DmAuthSide side); // 设置扩展字段,key-value格式 template diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index ef904072e..0f88eb16f 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -132,7 +132,7 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co context->appSessionKeyId = skId; msgType = MSG_TYPE_REQ_CREDENTIAL_AUTH_START; // 发送160 // 认证用户凭据 - int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + int32_t osAccountId = authContext->GetAccountId(DM_AUTH_LOCAL_SIDE); ret = context->hiChainAuthConnector->AuthCredential(osAccountId, context->requestId, context->accessee.userCredentialId, std::string("")); if (ret != DM_OK) { @@ -252,9 +252,8 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori jsonObj[DM_TAG_METHOD] = method; // 凭据生成方式 jsonObj[DM_TAG_DEVICE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? // 设备ID 生成是本端,导入是对端 authContext->GetDeviceId(DM_AUTH_LOCAL_SIDE) : authContext->GetDeviceId(DM_AUTH_REMOTE_SIDE); - if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) { - jsonObj[DM_TAG_PEER_USER_SPACE_ID] = authContext->GetDeviceId(DM_AUTH_REMOTE_SIDE); // 对端userId - } + jsonObj[DM_TAG_PEER_USER_SPACE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) ? + authContext->GetUserId(DM_AUTH_REMOTE_SIDE) : std::to_string(-1); jsonObj[DM_TAG_SUBJECT] = DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY; // 主控设备 jsonObj[DM_TAG_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; // 账号无关 jsonObj[DM_TAG_KEY_FORMAT] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? @@ -299,7 +298,7 @@ int32_t AuthCredentialAgreeState::GenerateCredIdAndPublicKey(DmAuthScope authori } // 生成凭据 - int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + int32_t osAccountId = authContext->GetAccountId(DM_AUTH_LOCAL_SIDE); std::string credId; int32_t ret = authContext->hiChainAuthConnector->AddCredential(osAccountId, authParamsString, credId); if (ret != DM_OK) { @@ -342,7 +341,7 @@ int32_t AuthCredentialAgreeState::AgreeCredential(DmAuthScope authorizedScope, } // 凭据协商得到协商凭据Id - int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + int32_t osAccountId = authContext->GetAccountId(DM_AUTH_LOCAL_SIDE); std::string selfCredId = authContext->GetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope); std::string credId; int32_t ret = authContext->hiChainAuthConnector->AgreeCredential(osAccountId, selfCredId, @@ -399,7 +398,7 @@ int32_t AuthSinkCredentialExchangeState::Action(std::shared_ptr c { int32_t ret = ERR_DM_FAILED; std::string tmpCredId; - int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + int32_t osAccountId = authContext->GetAccountId(DM_AUTH_LOCAL_SIDE); context->isAppCredentialVerified = false; if (context == nullptr || context->hiChainAuthConnector == nullptr || @@ -465,7 +464,7 @@ int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr c { int32_t ret = ERR_DM_FAILED; std::string tmpCredId; - int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + int32_t osAccountId = authContext->GetAccountId(DM_AUTH_LOCAL_SIDE); if (context == nullptr || context->hiChainAuthConnector == nullptr || context->authMessageProcessor == nullptr || context->softbusConnector == nullptr) { diff --git a/services/implementation/src/authentication_v2/dm_auth_context.cpp b/services/implementation/src/authentication_v2/dm_auth_context.cpp index 1ffe1eb5e..cfccddcb4 100644 --- a/services/implementation/src/authentication_v2/dm_auth_context.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_context.cpp @@ -169,5 +169,14 @@ int32_t DmAuthContext::SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope return DM_OK; } + +std::string DmAuthContext::GetAccountId(DmAuthSide side) +{ + if (side == DM_AUTH_LOCAL_SIDE) { + return (direction == DM_AUTH_SOURCE) ? accesser.accountId : accessee.accountId; + } else { + return (direction == DM_AUTH_SOURCE) ? accessee.accountId : accesser.accountId; + } +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file -- Gitee From c18e1be970dfa9719ff6a745edaaa1e1b2892d9b Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Tue, 4 Mar 2025 20:36:09 +0800 Subject: [PATCH 105/382] =?UTF-8?q?fix=EF=BC=9A140-150=20tmp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth_stages/auth_credential.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 0f88eb16f..15854d6c3 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -132,7 +132,7 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co context->appSessionKeyId = skId; msgType = MSG_TYPE_REQ_CREDENTIAL_AUTH_START; // 发送160 // 认证用户凭据 - int32_t osAccountId = authContext->GetAccountId(DM_AUTH_LOCAL_SIDE); + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); ret = context->hiChainAuthConnector->AuthCredential(osAccountId, context->requestId, context->accessee.userCredentialId, std::string("")); if (ret != DM_OK) { @@ -253,7 +253,7 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori jsonObj[DM_TAG_DEVICE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? // 设备ID 生成是本端,导入是对端 authContext->GetDeviceId(DM_AUTH_LOCAL_SIDE) : authContext->GetDeviceId(DM_AUTH_REMOTE_SIDE); jsonObj[DM_TAG_PEER_USER_SPACE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) ? - authContext->GetUserId(DM_AUTH_REMOTE_SIDE) : std::to_string(-1); + std::to_string(authContext->GetUserId(DM_AUTH_REMOTE_SIDE)) : std::to_string(-1); jsonObj[DM_TAG_SUBJECT] = DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY; // 主控设备 jsonObj[DM_TAG_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; // 账号无关 jsonObj[DM_TAG_KEY_FORMAT] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? @@ -298,7 +298,7 @@ int32_t AuthCredentialAgreeState::GenerateCredIdAndPublicKey(DmAuthScope authori } // 生成凭据 - int32_t osAccountId = authContext->GetAccountId(DM_AUTH_LOCAL_SIDE); + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); std::string credId; int32_t ret = authContext->hiChainAuthConnector->AddCredential(osAccountId, authParamsString, credId); if (ret != DM_OK) { @@ -341,7 +341,7 @@ int32_t AuthCredentialAgreeState::AgreeCredential(DmAuthScope authorizedScope, } // 凭据协商得到协商凭据Id - int32_t osAccountId = authContext->GetAccountId(DM_AUTH_LOCAL_SIDE); + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();; std::string selfCredId = authContext->GetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope); std::string credId; int32_t ret = authContext->hiChainAuthConnector->AgreeCredential(osAccountId, selfCredId, @@ -398,7 +398,7 @@ int32_t AuthSinkCredentialExchangeState::Action(std::shared_ptr c { int32_t ret = ERR_DM_FAILED; std::string tmpCredId; - int32_t osAccountId = authContext->GetAccountId(DM_AUTH_LOCAL_SIDE); + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();; context->isAppCredentialVerified = false; if (context == nullptr || context->hiChainAuthConnector == nullptr || @@ -464,7 +464,7 @@ int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr c { int32_t ret = ERR_DM_FAILED; std::string tmpCredId; - int32_t osAccountId = authContext->GetAccountId(DM_AUTH_LOCAL_SIDE); + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();; if (context == nullptr || context->hiChainAuthConnector == nullptr || context->authMessageProcessor == nullptr || context->softbusConnector == nullptr) { -- Gitee From d0be5510cb569fa063dc704c3d13ccb778610904 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 21:18:37 +0800 Subject: [PATCH 106/382] tmp --- .../include/authentication_v2/dm_auth_context.h | 2 +- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 2 ++ .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 4 +++- 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 2cab03235..2ae8467ce 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -136,7 +136,7 @@ struct DmAuthContext { UiAction authResult; // 授权结果(使用0、1、6,即单次,取消和始终信任,enum UiAction) DmAuthType authType{DmAuthType::AUTH_TYPE_PIN_SHOW}; // 认证方式,弹pin码、超声pin码、导入pin码 int32_t authFailTimes{0}; // 认证失败次数,查过3次结束认证 - int32_t pinCode; // 保存业务导入的pin码 + int32_t pinCode{INVALID_PINCODE}; // 保存业务导入的pin码 int32_t connDelayCloseTime; // 链路延迟释放时间, 授权结束后不自动断链(有业务需要使用)保留字段 int32_t reason; // 本端失败的原因 int32_t reply; // 对端回复的结果 引用common/include/dm_constants.h,有新的错误码可新增 diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 37ab5ca64..3d077c393 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -130,6 +130,8 @@ int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context std::vector serviceInfos; DistributedDeviceProfile::ServiceInfoUniqueKey key; auto tokenId = std::to_string(context->accessee.tokenId); + key.SetUserId(context->accessee.userId); + key.SetDeviceId(context->accessee.deviceId); key.SetTokenId(tokenId); auto ret = DeviceProfileConnector::GetInstance().GetServiceInfoProfileListByTokenId(key, serviceInfos); if (ret != DM_OK) { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 78cb866c2..6c08deb37 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -116,11 +116,13 @@ int32_t AuthSrcPinAuthStartState::ShowStartAuthDialog(std::shared_ptr context) { LOGI("AuthSrcPinAuthStartState::GetPinCodeFromServerInfo start"); - int32_t pinCode = 0; // 没获取到返回默认0, 失败后会进入用户输入PIN流程 + int32_t pinCode = INVALID_PINCODE; // 没获取到返回默认INVALID_PINCODE, 失败后会进入用户输入PIN流程 #if 1 // todo std::vector serviceInfos; DistributedDeviceProfile::ServiceInfoUniqueKey key; auto tokenId = std::to_string(context->accesser.tokenId); + key.SetUserId(context->accesser.userId); + key.SetDeviceId(context->accesser.deviceId); key.SetTokenId(tokenId); auto ret = DeviceProfileConnector::GetInstance().GetServiceInfoProfileListByTokenId(key, serviceInfos); if (ret == DM_OK) { -- Gitee From f9cefb436cadfc5590b39bdfd2ed6daf932de39d Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 21:35:30 +0800 Subject: [PATCH 107/382] auth result 110 --- .../authentication_v2/dm_auth_context.h | 1 + .../dm_auth_message_processor.h | 1 + .../src/authentication_v2/auth_manager.cpp | 4 +-- .../auth_stages/auth_pin_auth.cpp | 2 +- .../dm_auth_message_processor.cpp | 26 ++++++++++--------- 5 files changed, 19 insertions(+), 15 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 2ae8467ce..a599938e5 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -133,6 +133,7 @@ struct DmAuthContext { DmMessageType msgType; // 报文类型,枚举MsgType int32_t sessionId; // 总线传输会话ID int64_t requestId; // hichain认证ID + UiAction pinInputResult; // 输入PIN码结果 UiAction authResult; // 授权结果(使用0、1、6,即单次,取消和始终信任,enum UiAction) DmAuthType authType{DmAuthType::AUTH_TYPE_PIN_SHOW}; // 认证方式,弹pin码、超声pin码、导入pin码 int32_t authFailTimes{0}; // 认证失败次数,查过3次结束认证 diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 420a04abd..de65209dd 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -35,6 +35,7 @@ constexpr const char *DM_TAG_APP_PUBLICK_KEY = "appPublicKey"; // 应用级公 constexpr const char *DM_TAG_USER_CREDENTIAL_ID = "userCredentialId"; // 用户级凭据Id constexpr const char *DM_TAG_APP_CREDENTIAL_ID = "appCredentialId"; // 应用级凭据Id constexpr const char *DM_TAG_ON_TRANSMIT_DATA = "onTransmitData"; // onTransmitData接口返回信息 +constexpr const char *DM_TAG_AUTH_RESULT = "authResult"; // 授权结果 // is接口入参 json格式字符串中的key constexpr const char *DM_TAG_METHOD = "method"; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 1f79f0dc0..a1a946a74 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -899,13 +899,13 @@ int32_t AuthSrcManager::OnUserOperation(int32_t action, const std::string ¶m switch (action) { case USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT: LOGE("AuthSrcManager OnUserOperation user cancel"); - context_->authResult = USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT; + context_->pinInputResult = USER_OPERATION_TYPE_CANCEL_PINCODE_INPUT; context_->reason = ERR_DM_BIND_USER_CANCEL_ERROR; context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); break; case USER_OPERATION_TYPE_DONE_PINCODE_INPUT: LOGE("AuthSrcManager OnUserOperation user input done"); - context_->authResult = USER_OPERATION_TYPE_DONE_PINCODE_INPUT; + context_->pinInputResult = USER_OPERATION_TYPE_DONE_PINCODE_INPUT; context_->pinCode = std::atoi(params.c_str()); context_->authStateMachine->NotifyEventFinish(DmEventType::ON_USER_OPERATION); break; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 6c08deb37..5e700b8da 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -174,7 +174,7 @@ int32_t AuthSrcPinAuthStartState::GetPinCode(std::shared_ptr cont return STOP_BIND; // 外部事件错误,中止流程 } - if (context->authResult != USER_OPERATION_TYPE_DONE_PINCODE_INPUT) { + if (context->pinInputResult != USER_OPERATION_TYPE_DONE_PINCODE_INPUT) { LOGE("AuthSrcPinAuthStartState::GetPinCode not USER_OPERATION_TYPE_DONE_PINCODE_INPUT err"); return STOP_BIND; } diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 6104dd056..48cb43eb9 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -33,8 +33,6 @@ namespace OHOS { namespace DistributedHardware { -constexpr const char* TAG_REPLY = "reply"; -constexpr const char* TAG_DATA = "data"; constexpr const char* TAG_DEVICE_TYPE = "deviceType"; // 保存秘钥 @@ -579,6 +577,9 @@ int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const nlohmann::json if (IsInt64(json, TAG_REQUEST_ID)) { context->requestId = json[TAG_REQUEST_ID].get(); } + if (IsInt32(json, DM_TAG_AUTH_RESULT)) { + context->authResult = static_cast(json[DM_TAG_AUTH_RESULT].get()); + } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; @@ -586,8 +587,8 @@ int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const nlohmann::json int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const nlohmann::json &json, std::shared_ptr context) { - if (IsString(json, TAG_DATA)) { - context->transmitData = json[TAG_DATA].get(); + if (IsString(json, DM_TAG_DATA)) { + context->transmitData = json[DM_TAG_DATA].get(); } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; @@ -595,8 +596,8 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const nlohmann::json int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthStart(const nlohmann::json &json, std::shared_ptr context) { - if (IsString(json, TAG_DATA)) { - context->transmitData = json[TAG_DATA].get(); + if (IsString(json, DM_TAG_DATA)) { + context->transmitData = json[DM_TAG_DATA].get(); } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; @@ -604,8 +605,8 @@ int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthStart(const nlohmann::jso int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate(const nlohmann::json &json, std::shared_ptr context) { - if (IsString(json, TAG_DATA)) { - context->transmitData = json[TAG_DATA].get(); + if (IsString(json, DM_TAG_DATA)) { + context->transmitData = json[DM_TAG_DATA].get(); } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; @@ -625,29 +626,30 @@ void DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, nlohmann::json &json) { json[TAG_AUTH_TYPE] = context->authType; + json[DM_TAG_AUTH_RESULT] = context->authResult; json[TAG_REQUEST_ID] = context->requestId; } void DmAuthMessageProcessor::CreateMessageReqPinAuthStart(std::shared_ptr context, nlohmann::json &json) { - json[TAG_DATA] = context->transmitData; + json[DM_TAG_DATA] = context->transmitData; } void DmAuthMessageProcessor::CreateMessageRespPinAuthStart(std::shared_ptr context, nlohmann::json &json) { - json[TAG_DATA] = context->transmitData; + json[DM_TAG_DATA] = context->transmitData; } void DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate(std::shared_ptr context, nlohmann::json &json) { - json[TAG_DATA] = context->transmitData; + json[DM_TAG_DATA] = context->transmitData; } void DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate(std::shared_ptr context, nlohmann::json &json) { - json[TAG_DATA] = context->transmitData; + json[DM_TAG_DATA] = context->transmitData; } void DmAuthMessageProcessor::CreateAndSendMsg(DmMessageType msgType, std::shared_ptr context) -- Gitee From e0b130d8dc4bdfcc478b8178d285bb9396ed5266 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 21:38:01 +0800 Subject: [PATCH 108/382] auth result 110 --- .../src/authentication_v2/dm_auth_message_processor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 48cb43eb9..c0311eba1 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -578,7 +578,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const nlohmann::json context->requestId = json[TAG_REQUEST_ID].get(); } if (IsInt32(json, DM_TAG_AUTH_RESULT)) { - context->authResult = static_cast(json[DM_TAG_AUTH_RESULT].get()); + context->authResult = static_cast(json[DM_TAG_AUTH_RESULT].get()); } context->authStateMachine->TransitionTo(std::make_shared()); -- Gitee From 34f274d0991ab7db53da912450eace78ede35be8 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 4 Mar 2025 21:58:32 +0800 Subject: [PATCH 109/382] tmp --- .../src/authentication_v2/dm_auth_state_machine.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 8e9f8e449..4e32fa608 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -176,7 +176,7 @@ void DmAuthStateMachine::Run(std::shared_ptr context) } // finish需要,清理context以及重启状态机 } else { - LOGE("DmAuthStateMachine::Run ok state:%{public}d", stateType); + LOGI("DmAuthStateMachine::Run ok state:%{public}d", stateType); } } LOGE("DmAuthStateMachine::Run end"); @@ -208,7 +208,7 @@ void DmAuthStateMachine::Stop() // 设置当前状态 void DmAuthStateMachine::SetCurState(DmAuthStateType state) { - LOGE("DmAuthStateMachine::SetCurState:%{public}d", state); + LOGE("DmAuthStateMachine:: TODO LOGI SetCurState:%{public}d", state); curState_ = state; } -- Gitee From 97e27d64ab695ef7fda4234942c7b185a36a9148 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Tue, 4 Mar 2025 22:32:43 +0800 Subject: [PATCH 110/382] =?UTF-8?q?fix=EF=BC=9A140-150=EF=BC=8C=E4=BF=AE?= =?UTF-8?q?=E6=94=B9authParams=E5=8F=82=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication_v2/dm_auth_message_processor.h | 4 +++- .../auth_stages/auth_credential.cpp | 13 ++++++++++--- 2 files changed, 13 insertions(+), 4 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index de65209dd..90ec97404 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -50,7 +50,7 @@ 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_AUTH_CREDENTIAL_OWNER = "test"; // 凭据拥有者 constexpr const char *DM_TAG_TOKEN_ID = "tokenId"; constexpr const char *DM_TAG_SYNC = "syncMessage"; constexpr const char *DM_TAG_DMVERSION = "dmVersion"; @@ -62,6 +62,8 @@ constexpr const char *DM_TAG_APPSKID = "accesserAppSKId"; constexpr const char *DM_TAG_USERSKID = "accesserUserSKId"; constexpr const char *DM_TAG_APPSK_TIMESTAMP = "accesserAppSKTimeStamp"; constexpr const char *DM_TAG_USERSK_TIMESTAMP = "accesserUserSKTimeStamp"; +constexpr const char *DM_TAG_USER_ID = "userId"; +constexpr const char *DM_TAG_ISSUER = "issuer"; constexpr const char* APP_OPERATION_KEY = "appOperation"; constexpr const char* APP_THUMBNAIL = "appThumbnail"; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 15854d6c3..b2b0e7868 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -249,16 +249,21 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori } nlohmann::json jsonObj; - jsonObj[DM_TAG_METHOD] = method; // 凭据生成方式 + if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) { + jsonObj[DM_TAG_METHOD] = method; // 凭据生成方式 + } + jsonObj[DM_TAG_DEVICE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? // 设备ID 生成是本端,导入是对端 authContext->GetDeviceId(DM_AUTH_LOCAL_SIDE) : authContext->GetDeviceId(DM_AUTH_REMOTE_SIDE); jsonObj[DM_TAG_PEER_USER_SPACE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) ? - std::to_string(authContext->GetUserId(DM_AUTH_REMOTE_SIDE)) : std::to_string(-1); + std::to_string(authContext->GetUserId(DM_AUTH_REMOTE_SIDE)) : nullptr; jsonObj[DM_TAG_SUBJECT] = DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY; // 主控设备 + jsonObj[DM_TAG_USER_ID] = nullptr; + jsonObj[DM_TAG_ISSUER] = 0; jsonObj[DM_TAG_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; // 账号无关 jsonObj[DM_TAG_KEY_FORMAT] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? DM_AUTH_KEY_FORMAT_ASYMM_GENERATE : DM_AUTH_KEY_FORMAT_ASYMM_IMPORT; // 生成或导入非对称秘钥 - jsonObj[DM_TAG_ALGORITHM_TYPE] = DM_AUTH_ALG_TYPE_ED25519; // ED25519; + jsonObj[DM_TAG_ALGORITHM_TYPE] = DM_AUTH_ALG_TYPE_P256; // ED25519还没开发完,目前用P256 jsonObj[DM_TAG_PROOF_TYPE] = DM_AUTH_CREDENTIAL_PROOF_PSK; // PSK if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) { // 导入公钥 16进制字符串 std::stringstream ss; @@ -268,6 +273,8 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori ss << std::hex << std::setw(2) << std::setfill('0') << c; // 2 输出填充2字节 } jsonObj[DM_TAG_KEY_VALUE] = ss.str(); + } else { + jsonObj[DM_TAG_KEY_VALUE] = nullptr; } jsonObj[DM_TAG_AUTHORIZED_SCOPE] = authorizedScope; // 用户级或者应用级 if (authorizedScope == DM_AUTH_SCOPE_APP) { -- Gitee From 5c820263613b0c83eca5c4a7f3ad650d5502b260 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Wed, 5 Mar 2025 09:33:15 +0800 Subject: [PATCH 111/382] =?UTF-8?q?fix=EF=BC=9A140-150=20=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth_stages/auth_credential.cpp | 12 ++++++++++-- .../dependency/hichain/hichain_auth_connector.cpp | 7 ++++++- 2 files changed, 16 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index b2b0e7868..04ff995b2 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -242,6 +242,7 @@ int32_t AuthSinkCredentialAuthNegotiateState::Action(std::shared_ptr &authContext) { + LOGI("AuthCredentialAgreeState::CreateAuthParamsString start."); // 参数校验 if ((authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP) || (method != DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE && method != DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT)) { @@ -282,6 +283,7 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori } jsonObj[DM_TAG_CREDENTIAL_OWNER] = DM_AUTH_CREDENTIAL_OWNER; // 调用方包名DM模块 + LOGI("AuthCredentialAgreeState::CreateAuthParamsString leave."); return SafetyDump(jsonObj); } @@ -291,6 +293,7 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori int32_t AuthCredentialAgreeState::GenerateCredIdAndPublicKey(DmAuthScope authorizedScope, std::shared_ptr &authContext) { + LOGI("AuthCredentialAgreeState::GenerateCredIdAndPublicKey start."); if ((authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP) || authContext == nullptr || authContext->hiChainAuthConnector == nullptr) { return ERR_DM_FAILED; @@ -325,7 +328,7 @@ int32_t AuthCredentialAgreeState::GenerateCredIdAndPublicKey(DmAuthScope authori // 保存凭据Id和公钥 (void)authContext->SetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope, credId); (void)authContext->SetPublicKey(DM_AUTH_LOCAL_SIDE, authorizedScope, publicKey); - + LOGI("AuthCredentialAgreeState::GenerateCredIdAndPublicKey leave."); return DM_OK; } @@ -335,6 +338,7 @@ int32_t AuthCredentialAgreeState::GenerateCredIdAndPublicKey(DmAuthScope authori int32_t AuthCredentialAgreeState::AgreeCredential(DmAuthScope authorizedScope, std::shared_ptr &authContext) { + LOGI("AuthCredentialAgreeState::AgreeCredential start."); if ((authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP) || authContext == nullptr) { return ERR_DM_FAILED; } @@ -359,7 +363,7 @@ int32_t AuthCredentialAgreeState::AgreeCredential(DmAuthScope authorizedScope, // 保存协商凭据Id到上下文 (void)authContext->SetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope, credId); - + LOGI("AuthCredentialAgreeState::AgreeCredential leave."); return DM_OK; } @@ -403,6 +407,7 @@ DmAuthStateType AuthSinkCredentialExchangeState::GetStateType() int32_t AuthSinkCredentialExchangeState::Action(std::shared_ptr context) { + LOGI("AuthSinkCredentialExchangeState::Action start."); int32_t ret = ERR_DM_FAILED; std::string tmpCredId; int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();; @@ -458,6 +463,7 @@ int32_t AuthSinkCredentialExchangeState::Action(std::shared_ptr c // 发送150报文 std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, context); + LOGI("AuthSinkCredentialExchangeState::Action leave."); return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); } @@ -469,6 +475,7 @@ DmAuthStateType AuthSrcCredentialAuthStartState::GetStateType() int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr context) { + LOGI(" AuthSrcCredentialAuthStartState::Action start."); int32_t ret = ERR_DM_FAILED; std::string tmpCredId; int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();; @@ -523,6 +530,7 @@ int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr c // 发送160报文 std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_REQ_CREDENTIAL_AUTH_START, context); + LOGI(" AuthSrcCredentialAuthStartState::Action leave."); return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); } diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index d2411ea76..861ae9863 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -102,6 +102,7 @@ int32_t HiChainAuthConnector::ProcessCredData(int64_t authReqId, const std::stri LOGE("Hichain processData failed ret %{public}d.", ret); return ERR_DM_FAILED; } + LOGI("HiChainAuthConnector::ProcessCredData leave."); return DM_OK; } @@ -122,6 +123,7 @@ int32_t HiChainAuthConnector::AddCredential(int32_t osAccountId, const std::stri } credId = static_cast(returnData); credManager->destroyInfo(&returnData); + LOGI("HiChainAuthConnector::AddCredential leave."); return DM_OK; } @@ -142,6 +144,7 @@ int32_t HiChainAuthConnector::ExportCredential(int32_t osAccountId, const std::s } publicKey = static_cast(returnData); credManager->destroyInfo(&returnData); + LOGI("HiChainAuthConnector::ExportCredential leave."); return DM_OK; } @@ -165,6 +168,7 @@ int32_t HiChainAuthConnector::AgreeCredential(int32_t osAccountId, const std::st // } // credId = static_cast(returnData); // credManager->destroyInfo(&returnData); + LOGI("HiChainAuthConnector::AgreeCredential leave."); return DM_OK; } @@ -180,6 +184,7 @@ int32_t HiChainAuthConnector::DeleteCredential(int32_t osAccountId, const std::s LOGE("Hichain deleteCredential failed ret %{public}d.", ret); return ERR_DM_FAILED; } + LOGI("HiChainAuthConnector::DeleteCredential leave."); return DM_OK; } @@ -214,7 +219,7 @@ int32_t HiChainAuthConnector::AuthCredential(int32_t osAccountId, int64_t authRe LOGE("HiChainAuthConnector::AuthCredential failed ret %{public}d.", ret); return ERR_DM_FAILED; } - + LOGI("HiChainAuthConnector::AuthCredential leave."); return DM_OK; } -- Gitee From b1d9300469409d19c20c12bb1ecdba370c12d1b8 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Wed, 5 Mar 2025 10:09:10 +0800 Subject: [PATCH 112/382] =?UTF-8?q?fix=EF=BC=9Atmp=20140-150?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_credential.cpp | 8 +++----- 1 file changed, 3 insertions(+), 5 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 04ff995b2..02a809c40 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -256,10 +256,10 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori jsonObj[DM_TAG_DEVICE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? // 设备ID 生成是本端,导入是对端 authContext->GetDeviceId(DM_AUTH_LOCAL_SIDE) : authContext->GetDeviceId(DM_AUTH_REMOTE_SIDE); - jsonObj[DM_TAG_PEER_USER_SPACE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) ? - std::to_string(authContext->GetUserId(DM_AUTH_REMOTE_SIDE)) : nullptr; + if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) { + jsonObj[DM_TAG_PEER_USER_SPACE_ID] = std::to_string(authContext->GetUserId(DM_AUTH_REMOTE_SIDE)); + } jsonObj[DM_TAG_SUBJECT] = DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY; // 主控设备 - jsonObj[DM_TAG_USER_ID] = nullptr; jsonObj[DM_TAG_ISSUER] = 0; jsonObj[DM_TAG_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; // 账号无关 jsonObj[DM_TAG_KEY_FORMAT] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? @@ -274,8 +274,6 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori ss << std::hex << std::setw(2) << std::setfill('0') << c; // 2 输出填充2字节 } jsonObj[DM_TAG_KEY_VALUE] = ss.str(); - } else { - jsonObj[DM_TAG_KEY_VALUE] = nullptr; } jsonObj[DM_TAG_AUTHORIZED_SCOPE] = authorizedScope; // 用户级或者应用级 if (authorizedScope == DM_AUTH_SCOPE_APP) { -- Gitee From 620004888efe04e343441034a95459e313c8aeab Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Wed, 5 Mar 2025 10:35:11 +0800 Subject: [PATCH 113/382] =?UTF-8?q?fix=EF=BC=9A=E6=B7=BB=E5=8A=A0=E6=97=A5?= =?UTF-8?q?=E5=BF=97=E6=89=93=E5=8D=B0140-150?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/dependency/hichain/hichain_auth_connector.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 861ae9863..96c483d47 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -116,6 +116,8 @@ int32_t HiChainAuthConnector::AddCredential(int32_t osAccountId, const std::stri char *returnData = NULL; const CredManager *credManager = GetCredMgrInstance(); int32_t ret = credManager->addCredential(osAccountId, authParams.c_str(), &returnData); + LOGI("HiChainAuthConnector::AddCredential osAccount=%{public}d, authParams=%{public}s\n", + osAccountId. authParams.c_str()); if (ret != HC_SUCCESS) { LOGE("Hichain addCredential failed ret %{public}d.", ret); credManager->destroyInfo(&returnData); -- Gitee From 1489670131a3e27ab7b960d81332bd064d3b6237 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Wed, 5 Mar 2025 10:40:45 +0800 Subject: [PATCH 114/382] =?UTF-8?q?fix=EF=BC=9Atmp=E8=A1=A5=E5=85=85?= =?UTF-8?q?=E5=85=A5=E5=8F=82=E4=BF=A1=E6=81=AF=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/dependency/hichain/hichain_auth_connector.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 96c483d47..69abfb05d 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -113,11 +113,11 @@ int32_t HiChainAuthConnector::ProcessCredData(int64_t authReqId, const std::stri int32_t HiChainAuthConnector::AddCredential(int32_t osAccountId, const std::string &authParams, std::string &credId) { LOGI("HiChainAuthConnector::AddCredential start."); + LOGI("HiChainAuthConnector::AddCredential osAccount=%{public}d, authParams=%{public}s\n", + osAccountId. authParams.c_str()); char *returnData = NULL; const CredManager *credManager = GetCredMgrInstance(); int32_t ret = credManager->addCredential(osAccountId, authParams.c_str(), &returnData); - LOGI("HiChainAuthConnector::AddCredential osAccount=%{public}d, authParams=%{public}s\n", - osAccountId. authParams.c_str()); if (ret != HC_SUCCESS) { LOGE("Hichain addCredential failed ret %{public}d.", ret); credManager->destroyInfo(&returnData); -- Gitee From 399528847a3138f507db161fce453e6fe4dae0a3 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Wed, 5 Mar 2025 10:42:36 +0800 Subject: [PATCH 115/382] fix:tmp --- .../src/dependency/hichain/hichain_auth_connector.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 69abfb05d..c70e4013b 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -114,7 +114,7 @@ int32_t HiChainAuthConnector::AddCredential(int32_t osAccountId, const std::stri { LOGI("HiChainAuthConnector::AddCredential start."); LOGI("HiChainAuthConnector::AddCredential osAccount=%{public}d, authParams=%{public}s\n", - osAccountId. authParams.c_str()); + osAccountId, authParams.c_str()); char *returnData = NULL; const CredManager *credManager = GetCredMgrInstance(); int32_t ret = credManager->addCredential(osAccountId, authParams.c_str(), &returnData); -- Gitee From 38f923176be592f300a41a927b4b8cb73b0da5af Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Wed, 5 Mar 2025 10:45:05 +0800 Subject: [PATCH 116/382] fix:tmp --- .../src/dependency/hichain/hichain_auth_connector.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index c70e4013b..d367fd5cc 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -123,7 +123,7 @@ int32_t HiChainAuthConnector::AddCredential(int32_t osAccountId, const std::stri credManager->destroyInfo(&returnData); return ERR_DM_FAILED; } - credId = static_cast(returnData); + credId = returnData; credManager->destroyInfo(&returnData); LOGI("HiChainAuthConnector::AddCredential leave."); return DM_OK; -- Gitee From 17183dc0cc5ba3cd7d77fc98ad5c5e7c95c8a361 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Wed, 5 Mar 2025 11:05:41 +0800 Subject: [PATCH 117/382] tmp --- .../implementation/src/authentication_v2/auth_manager.cpp | 2 +- .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 6 +++--- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index a1a946a74..6cb7a09b8 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -536,7 +536,7 @@ void AuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, LOGI("Get auth param."); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - std::string localUdid = static_cast(localDeviceId); + std::string localUdid = std::string(localDeviceId); context_->pkgName = pkgName; context_->pkgLabel = GetBundleLable(pkgName); context_->authType = (DmAuthType)authType; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 8711094a3..115040259 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -143,7 +143,7 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptraccessee.deviceId = static_cast(localDeviceId); + context->accessee.deviceId = std::string(localDeviceId); if (context->accesser.tokenId == 0) { // 单用户:特征为accesser未传输tokenIdHash @@ -396,12 +396,12 @@ int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr con context->accessee.deviceName = context->softbusConnector->GetLocalDeviceName(); char localDeviceId[DEVICE_UUID_LENGTH]; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - context->accessee.deviceId = static_cast(localDeviceId); + context->accessee.deviceId = std::string(localDeviceId); // 解析message时,accesser.deviceId已赋值 context->accessee.networkId = context->softbusConnector->GetLocalDeviceNetworkId(); context->accessee.deviceName = context->softbusConnector->GetLocalDeviceName(); - // TODO: + // TODO: // if (CompareVersion(context->accesser.dmVersion, std::string(DM_VERSION_5_1_0))) { // LOGE("AuthSinkNegotiateStateMachine::Action incompatible version %{public}s compare to 5.1.0", // context->accesser.dmVersion); -- Gitee From 23a6169f46cf1c0b5977dd05d3a446b556dea1fd Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Wed, 5 Mar 2025 11:07:57 +0800 Subject: [PATCH 118/382] =?UTF-8?q?FIX=EF=BC=9Atmp=20140-150=20static=5Fca?= =?UTF-8?q?st=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.h | 2 +- .../auth_stages/auth_credential.cpp | 9 +------ .../hichain/hichain_auth_connector.cpp | 27 +++++++++---------- 3 files changed, 15 insertions(+), 23 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 90ec97404..08955c554 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -50,7 +50,7 @@ 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 = "test"; // 凭据拥有者 +constexpr const char *DM_AUTH_CREDENTIAL_OWNER = "DM"; // 凭据拥有者 constexpr const char *DM_TAG_TOKEN_ID = "tokenId"; constexpr const char *DM_TAG_SYNC = "syncMessage"; constexpr const char *DM_TAG_DMVERSION = "dmVersion"; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 02a809c40..29a85cdf6 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -260,20 +260,13 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori jsonObj[DM_TAG_PEER_USER_SPACE_ID] = std::to_string(authContext->GetUserId(DM_AUTH_REMOTE_SIDE)); } jsonObj[DM_TAG_SUBJECT] = DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY; // 主控设备 - jsonObj[DM_TAG_ISSUER] = 0; jsonObj[DM_TAG_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; // 账号无关 jsonObj[DM_TAG_KEY_FORMAT] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? DM_AUTH_KEY_FORMAT_ASYMM_GENERATE : DM_AUTH_KEY_FORMAT_ASYMM_IMPORT; // 生成或导入非对称秘钥 jsonObj[DM_TAG_ALGORITHM_TYPE] = DM_AUTH_ALG_TYPE_P256; // ED25519还没开发完,目前用P256 jsonObj[DM_TAG_PROOF_TYPE] = DM_AUTH_CREDENTIAL_PROOF_PSK; // PSK if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) { // 导入公钥 16进制字符串 - std::stringstream ss; - ss.str(""); - std::string publicKey = authContext->GetPublicKey(DM_AUTH_REMOTE_SIDE, authorizedScope); - for (auto &c : publicKey) { - ss << std::hex << std::setw(2) << std::setfill('0') << c; // 2 输出填充2字节 - } - jsonObj[DM_TAG_KEY_VALUE] = ss.str(); + jsonObj[DM_TAG_KEY_VALUE] = authContext->GetPublicKey(DM_AUTH_REMOTE_SIDE, authorizedScope); } jsonObj[DM_TAG_AUTHORIZED_SCOPE] = authorizedScope; // 用户级或者应用级 if (authorizedScope == DM_AUTH_SCOPE_APP) { diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index d367fd5cc..b40d8424b 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -118,7 +118,7 @@ int32_t HiChainAuthConnector::AddCredential(int32_t osAccountId, const std::stri char *returnData = NULL; const CredManager *credManager = GetCredMgrInstance(); int32_t ret = credManager->addCredential(osAccountId, authParams.c_str(), &returnData); - if (ret != HC_SUCCESS) { + if (ret != HC_SUCCESS || returnData == NULL) { LOGE("Hichain addCredential failed ret %{public}d.", ret); credManager->destroyInfo(&returnData); return ERR_DM_FAILED; @@ -139,12 +139,12 @@ int32_t HiChainAuthConnector::ExportCredential(int32_t osAccountId, const std::s char *returnData = NULL; const CredManager *credManager = GetCredMgrInstance(); int32_t ret = credManager->exportCredential(osAccountId, credId.c_str(), &returnData); - if (ret != HC_SUCCESS) { + if (ret != HC_SUCCESS || returnData == NULL) { LOGE("Hichain exportCredential failed ret %{public}d.", ret); credManager->destroyInfo(&returnData); return ERR_DM_FAILED; } - publicKey = static_cast(returnData); + publicKey = returnData; credManager->destroyInfo(&returnData); LOGI("HiChainAuthConnector::ExportCredential leave."); return DM_OK; @@ -159,17 +159,16 @@ int32_t HiChainAuthConnector::AgreeCredential(int32_t osAccountId, const std::st const std::string &authParams, std::string &credId) { LOGI("HiChainAuthConnector::AgreeCredential start."); - // TODO:IS黄区代码中没有这个接口 - // char *returnData = NULL; - // const CredManager *credManager = GetCredMgrInstance(); - // int32_t ret = credManager->agreeCredential(osAccountId, selfCredId.c_str(), authParams.c_str(), &returnData); - // if (ret != HC_SUCCESS) { - // LOGE("Hichain agreeCredential failed ret %{public}d.", ret); - // credManager->destroyInfo(&returnData); - // return ERR_DM_FAILED; - // } - // credId = static_cast(returnData); - // credManager->destroyInfo(&returnData); + char *returnData = NULL; + const CredManager *credManager = GetCredMgrInstance(); + int32_t ret = credManager->agreeCredential(osAccountId, selfCredId.c_str(), authParams.c_str(), &returnData); + if (ret != HC_SUCCESS || returnData == NULL) { + LOGE("Hichain agreeCredential failed ret %{public}d.", ret); + credManager->destroyInfo(&returnData); + return ERR_DM_FAILED; + } + credId = returnData; + credManager->destroyInfo(&returnData); LOGI("HiChainAuthConnector::AgreeCredential leave."); return DM_OK; } -- Gitee From c712464f8df9e6af56d92fff1fbb5f18f9c6e31f Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Wed, 5 Mar 2025 11:36:11 +0800 Subject: [PATCH 119/382] =?UTF-8?q?fix=EF=BC=9Atmp=20=E5=8A=A0=E6=97=A5?= =?UTF-8?q?=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/dependency/hichain/hichain_auth_connector.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index b40d8424b..acdfbef5d 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -123,7 +123,10 @@ int32_t HiChainAuthConnector::AddCredential(int32_t osAccountId, const std::stri credManager->destroyInfo(&returnData); return ERR_DM_FAILED; } + LOGI("HiChainAuthConnector::AddCredential addCredential success ret=%{public}d, returnData=%{public}s.", + ret, returnData); credId = returnData; + LOGI("HiChainAuthConnector::AddCredential credId=%{public}s.", credId.c_str()); credManager->destroyInfo(&returnData); LOGI("HiChainAuthConnector::AddCredential leave."); return DM_OK; -- Gitee From bdcdac5695b5b2b510e9fb2680802476cb7e28b2 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Wed, 5 Mar 2025 11:38:00 +0800 Subject: [PATCH 120/382] tmp --- .../src/dependency/hichain/hichain_auth_connector.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index acdfbef5d..b543f6f5e 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -125,7 +125,7 @@ int32_t HiChainAuthConnector::AddCredential(int32_t osAccountId, const std::stri } LOGI("HiChainAuthConnector::AddCredential addCredential success ret=%{public}d, returnData=%{public}s.", ret, returnData); - credId = returnData; + credId = std::string(returnData); LOGI("HiChainAuthConnector::AddCredential credId=%{public}s.", credId.c_str()); credManager->destroyInfo(&returnData); LOGI("HiChainAuthConnector::AddCredential leave."); -- Gitee From 18a72f042b69312fc392dcb9414bb9e38e9d342b Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Wed, 5 Mar 2025 11:54:21 +0800 Subject: [PATCH 121/382] =?UTF-8?q?fix=EF=BC=9Atmp=20free=E9=87=8A?= =?UTF-8?q?=E6=94=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependency/hichain/hichain_auth_connector.cpp | 14 ++++++++------ 1 file changed, 8 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index b543f6f5e..6ae38ab09 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -12,6 +12,8 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + +#include #include "hichain_auth_connector.h" #include "dm_log.h" @@ -120,14 +122,14 @@ int32_t HiChainAuthConnector::AddCredential(int32_t osAccountId, const std::stri int32_t ret = credManager->addCredential(osAccountId, authParams.c_str(), &returnData); if (ret != HC_SUCCESS || returnData == NULL) { LOGE("Hichain addCredential failed ret %{public}d.", ret); - credManager->destroyInfo(&returnData); + free(returnData); return ERR_DM_FAILED; } LOGI("HiChainAuthConnector::AddCredential addCredential success ret=%{public}d, returnData=%{public}s.", ret, returnData); credId = std::string(returnData); LOGI("HiChainAuthConnector::AddCredential credId=%{public}s.", credId.c_str()); - credManager->destroyInfo(&returnData); + free(returnData); LOGI("HiChainAuthConnector::AddCredential leave."); return DM_OK; } @@ -144,11 +146,11 @@ int32_t HiChainAuthConnector::ExportCredential(int32_t osAccountId, const std::s int32_t ret = credManager->exportCredential(osAccountId, credId.c_str(), &returnData); if (ret != HC_SUCCESS || returnData == NULL) { LOGE("Hichain exportCredential failed ret %{public}d.", ret); - credManager->destroyInfo(&returnData); + free(returnData); return ERR_DM_FAILED; } publicKey = returnData; - credManager->destroyInfo(&returnData); + free(returnData); LOGI("HiChainAuthConnector::ExportCredential leave."); return DM_OK; } @@ -167,11 +169,11 @@ int32_t HiChainAuthConnector::AgreeCredential(int32_t osAccountId, const std::st int32_t ret = credManager->agreeCredential(osAccountId, selfCredId.c_str(), authParams.c_str(), &returnData); if (ret != HC_SUCCESS || returnData == NULL) { LOGE("Hichain agreeCredential failed ret %{public}d.", ret); - credManager->destroyInfo(&returnData); + free(returnData); return ERR_DM_FAILED; } credId = returnData; - credManager->destroyInfo(&returnData); + free(returnData); LOGI("HiChainAuthConnector::AgreeCredential leave."); return DM_OK; } -- Gitee From fe0bfe7312ea24b776f227e89e87e3c3457bf06c Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Wed, 5 Mar 2025 14:52:32 +0800 Subject: [PATCH 122/382] =?UTF-8?q?fix=EF=BC=9Atmp=20=E4=BF=AE=E6=94=B9tok?= =?UTF-8?q?enId?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_credential.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 29a85cdf6..19cf8fd24 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -270,7 +270,8 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori } jsonObj[DM_TAG_AUTHORIZED_SCOPE] = authorizedScope; // 用户级或者应用级 if (authorizedScope == DM_AUTH_SCOPE_APP) { - jsonObj[DM_TAG_AUTHRIZED_APP_LIST] = {authContext->accesser.tokenId, authContext->accessee.tokenId}; + jsonObj[DM_TAG_AUTHRIZED_APP_LIST] = {std::to_string(authContext->accesser.tokenId), + std::to_string(authContext->accessee.tokenId)}; } jsonObj[DM_TAG_CREDENTIAL_OWNER] = DM_AUTH_CREDENTIAL_OWNER; // 调用方包名DM模块 -- Gitee From 2f3281e5ddd15882b0fcc8abc5ff2504971d8478 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Wed, 5 Mar 2025 15:29:30 +0800 Subject: [PATCH 123/382] =?UTF-8?q?fix=EF=BC=9Atmp=20150-160=20=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 7 +++++++ .../src/dependency/hichain/hichain_auth_connector.cpp | 3 ++- 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index c0311eba1..f05b3fe6e 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -232,6 +232,7 @@ int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const nlohmann::json int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const nlohmann::json &jsonObject, std::shared_ptr context) { + LOGI("DmAuthMessageProcessor::ParseMessageRspCredExchange start."); if (jsonObject.is_discarded() || !IsString(jsonObject, DM_TAG_DATA)) { LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange, DecodeRequestAuth jsonStr error"); return ERR_DM_FAILED; @@ -243,6 +244,9 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const nlohmann::json LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange error, decrypt data failed."); return ERR_DM_FAILED; } + + LOGI("DmAuthMessageProcessor::ParseMessageRspCredExchange plainText=%{public}s", plainText.c_str()); + nlohmann::json jsonData = nlohmann::json::parse(plainText, nullptr, false); // 首次认证,解析对方用户级公钥和协商用户级凭据Id @@ -272,6 +276,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const nlohmann::json context->accessee.deviceId = jsonData[DM_TAG_DEVICE_ID].get(); // 解析deviceId context->accessee.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].get(); // 解析userId context->accessee.tokenId = jsonData[DM_TAG_TOKEN_ID].get(); // 解析tokenId + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -414,6 +419,7 @@ void DmAuthMessageProcessor::CreateMessageReqCredExchange(std::shared_ptr context, nlohmann::json &jsonObject) { + LOGI("DmAuthMessageProcessor::CreateMessageRspCredExchange start."); nlohmann::json jsonData; if (!context->isOnline) { jsonData[DM_TAG_USER_PUBLICK_KEY] = context->accessee.userPublicKey; @@ -427,6 +433,7 @@ void DmAuthMessageProcessor::CreateMessageRspCredExchange(std::shared_ptrEncryptMessage(plainText, cipherText); jsonObject[DM_TAG_DATA] = cipherText; } diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 6ae38ab09..3fdbcb64e 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -164,12 +164,13 @@ int32_t HiChainAuthConnector::AgreeCredential(int32_t osAccountId, const std::st const std::string &authParams, std::string &credId) { LOGI("HiChainAuthConnector::AgreeCredential start."); + LOGI("HiChainAuthConnector::AgreeCredential osAccountId=%{public}d, selfCredId=%{public}s, authParams=%{public}s\n", + osAccountId, selfCredId.c_str(), authParams.c_str()); char *returnData = NULL; const CredManager *credManager = GetCredMgrInstance(); int32_t ret = credManager->agreeCredential(osAccountId, selfCredId.c_str(), authParams.c_str(), &returnData); if (ret != HC_SUCCESS || returnData == NULL) { LOGE("Hichain agreeCredential failed ret %{public}d.", ret); - free(returnData); return ERR_DM_FAILED; } credId = returnData; -- Gitee From 1f2f3c3961d73c50affa17dc378c7cd6beac5dd5 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Wed, 5 Mar 2025 16:23:55 +0800 Subject: [PATCH 124/382] =?UTF-8?q?fix=EF=BC=9A140-150=20=E6=9F=A5?= =?UTF-8?q?=E7=9C=8Bpublickey?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_credential.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 19cf8fd24..f3ab87d39 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -320,6 +320,9 @@ int32_t AuthCredentialAgreeState::GenerateCredIdAndPublicKey(DmAuthScope authori // 保存凭据Id和公钥 (void)authContext->SetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope, credId); (void)authContext->SetPublicKey(DM_AUTH_LOCAL_SIDE, authorizedScope, publicKey); + LOGI("AuthCredentialAgreeState::GenerateCredIdAndPublicKey credId=%{public}s, publicKey=%{public}s.\n", + authContext->GetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope).c_str(), + authContext->GetPublicKey(DM_AUTH_LOCAL_SIDE, authorizedScope).c_str()); LOGI("AuthCredentialAgreeState::GenerateCredIdAndPublicKey leave."); return DM_OK; } -- Gitee From 70cf75e3b2eba3375d4cd09922d0d0aab70141b0 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Wed, 5 Mar 2025 17:17:33 +0800 Subject: [PATCH 125/382] =?UTF-8?q?fix=EF=BC=9Atmp=20140-=20150=20?= =?UTF-8?q?=E6=97=A5=E5=BF=97?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/dependency/hichain/hichain_auth_connector.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 3fdbcb64e..1909a2e83 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -150,6 +150,7 @@ int32_t HiChainAuthConnector::ExportCredential(int32_t osAccountId, const std::s return ERR_DM_FAILED; } publicKey = returnData; + LOGI("HiChainAuthConnector::ExportCredential publicKey=%{public}s\n.", publicKey.c_str()); free(returnData); LOGI("HiChainAuthConnector::ExportCredential leave."); return DM_OK; -- Gitee From 3cbbfc13869d0d73076cb751b63cc2447074f057 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 6 Mar 2025 09:41:05 +0800 Subject: [PATCH 126/382] tmp --- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 3d077c393..143bd4dd2 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -54,6 +54,12 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) { LOGI("AuthSrcConfirmState::Action start"); context->timer->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); + if (CompareVersion(context->accessee.dmVersion, std::string(DM_VERSION_5_1_0))) { + LOGE("AuthSrcConfirmState::Action incompatible version %{public}s compare to 5.1.0", + context->accessee.dmVersion); + context->reason = ERR_DM_VERSION_INCOMPATIBLE; + return ERR_DM_VERSION_INCOMPATIBLE; + } #if 0 // todo nlohmann::json jsonObject = nlohmann::json::parse(context->accessee.credentialInfos, nullptr, false); if (jsonObject.is_discarded()) { -- Gitee From bb783a6a296daae5bc478530585dd0cfd562912b Mon Sep 17 00:00:00 2001 From: gaoqiang Date: Wed, 5 Mar 2025 11:48:21 +0000 Subject: [PATCH 127/382] =?UTF-8?q?pick=E3=80=90=E6=96=B0=E5=8D=8F?= =?UTF-8?q?=E8=AE=AE=E3=80=91180-200=E6=8A=A5=E6=96=87=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- common/include/dm_error_type.h | 2 + .../include/deviceprofile_connector.h | 1 + .../src/deviceprofile_connector.cpp | 11 + .../authentication_v2/dm_auth_context.h | 10 + .../dm_auth_message_processor.h | 30 +- .../include/authentication_v2/dm_auth_state.h | 28 ++ .../auth_stages/auth_acl.cpp | 176 ++++++++++ .../dm_auth_message_processor.cpp | 303 +++++++++++++++++- .../src/authentication_v2/dm_auth_state.cpp | 16 + 9 files changed, 566 insertions(+), 11 deletions(-) diff --git a/common/include/dm_error_type.h b/common/include/dm_error_type.h index 81fca4823..6b15e7402 100644 --- a/common/include/dm_error_type.h +++ b/common/include/dm_error_type.h @@ -21,6 +21,7 @@ namespace DistributedHardware { enum { DM_OK = 0, SOFTBUS_OK = 0, + DM_AUTHENTICATE_FINISH = 0, STOP_BIND = 1, /* Transfer to the other end device, not define specification error code */ @@ -120,6 +121,7 @@ enum { ERR_DM_HICHAIN_PROOFMISMATCH = 96929832, ERR_DM_NEXT_STATE_INVALID = 96929833, ERR_DM_GET_SESSION_KEY_FAILED = 96929834, + ERR_DM_QUADRUPLE_NOT_SAME = 96929835, }; } // namespace DistributedHardware } // namespace OHOS diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 30869a252..cd7c9ed08 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -187,6 +187,7 @@ public: int32_t GetServiceInfoProfileListByBundleName(const DistributedDeviceProfile::ServiceInfoUniqueKey& key, std::vector& serviceInfoProfiles); int32_t PutSessionKey(const uint8_t* sessionKey, uint32_t length, int32_t& sessionKeyId); + int32_t DeleteSessionKey(int32_t sessionKeyId); private: int32_t HandleDmAuthForm(DistributedDeviceProfile::AccessControlProfile profiles, DmDiscoveryInfo discoveryInfo); diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 63207c775..2de4c116f 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -1840,6 +1840,17 @@ int32_t DeviceProfileConnector::PutSessionKey( return DM_OK; } +int32_t DeviceProfileConnector::DeleteSessionKey(int32_t sessionKeyId) +{ + uint32_t userId = static_cast(MultipleUserConnector::GetCurrentAccountUserID()); + int32_t ret = DistributedDeviceProfileClient::GetInstance().DeleteSessionKey(userId, sessionKeyId); + if (ret != DM_OK) { + LOGE("failed: %{public}d", ret); + return ret; + } + return DM_OK; +} + IDeviceProfileConnector *CreateDpConnectorInstance() { return &DeviceProfileConnector::GetInstance(); diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index a599938e5..6a395c94b 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -119,10 +119,17 @@ struct DmAccess { std::string publicKey; // T公钥长度 int32_t credentialId; // 应用凭据ID int32_t status; // 表示服务为前台还是后台,业务透传,只保存 + int32_t sessionKeyId; // 作为秘钥派送的材料,在总线中取出sk + int32_t appSessionKeyId; // 本端永久应用SKID,由DP返回用于ACL的更新、老化 + int32_t userSessionKeyId; // 本端永久用户SKID,由DP返回用于ACL的更新、老化 + int64_t appSkTimeStamp; // 老化,时间为2天 应用级凭据时间戳 + int64_t userSkTimeStamp; // 老化,时间为2天 用户级凭据时间戳 + int64_t skTimeStamp; // 老化,时间为2天 bool isAuthed; bool isOnline; std::string dmVersion; // 版本 5.1.0 std::string aclList; //可信关系列表,用于数据老化 KV格式 + std::vector aclChecksumList; // 可信关系列表,用于数据老化 std::string credentialInfos; //凭据信息(点对点,同账号,..) 只保存凭据类型 kv结构 std::string extraInfo; //可扩展字段,kv结构 }; @@ -141,6 +148,7 @@ struct DmAuthContext { int32_t connDelayCloseTime; // 链路延迟释放时间, 授权结束后不自动断链(有业务需要使用)保留字段 int32_t reason; // 本端失败的原因 int32_t reply; // 对端回复的结果 引用common/include/dm_constants.h,有新的错误码可新增 + int32_t state; // 结束的状态 int32_t appSessionKeyId; // 本端永久应用SKID,由DP返回用于ACL的更新、老化 int32_t userSessionKeyId; // 本端永久用户SKID,由DP返回用于ACL的更新、老化 int64_t appSkTimeStamp; // 老化,时间为2天 应用级凭据时间戳 @@ -164,6 +172,8 @@ struct DmAuthContext { bool isAppCredentialVerified; // 应用级凭据是否认证 DmAccess accesser; DmAccess accessee; + DmAccess encryAccesser; // 密文阶段accesser + DmAccess encryAccessee; // 密文阶段accessee std::multimap proxy; // 前面是accesser,后面是accessee std::shared_ptr authStateMachine; // 状态机 diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 08955c554..f4ba95384 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -81,6 +81,10 @@ constexpr const char* TAG_PKG_NAME = "pkgName"; 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 int32_t DM_HASH_LEN = 32; constexpr const char* TAG_IS_ONLINE = "isOnline"; constexpr const char* TAG_IS_AUTHED = "isAuthed"; @@ -166,6 +170,13 @@ public: // 保存永久SK int32_t SaveSessionKeyToDP(int32_t &skId); + + // 保留本次acl + int32_t PutAccessControlList(std::shared_ptr context, + DmAccess &access, std::string trustDeviceId) + + // 对acl进行checksum + std::string ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl); private: // 内部各类报文的实现 @@ -199,6 +210,12 @@ private: // 解析161 170 171 int32_t ParseMessageNegotiateTransmit(const nlohmann::json &jsonObject, std::shared_ptr &context, DmMessageType msgType); + // 解析 180报文信息 MSG_TYPE_REQ_DATA_SYNC 存放对方密文四元组,acl,sp skid + int32_t ParseMessageSyncReq(const nlohmann::json &jsonObject, std::shared_ptr context); + // 解析 190报文信息 MSG_TYPE_RESP_DATA_SYNC 存放对方密文四元组,acl sp skid + int32_t ParseMessageSyncResp(const nlohmann::json &jsonObject, std::shared_ptr context); + // 解析 200报文信息 + int32_t ParseMessageFinish(std::shared_ptr context, nlohmann::json &jsonObject); // 创建 80报文 void CreateNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject); @@ -227,11 +244,20 @@ private: // 180 190 消息构造 int32_t CreateSyncMessage(std::shared_ptr &context, nlohmann::json &jsonObject); // 压缩sync 消息 - std::string compressSyncMsg(std::string &inputStr); + std::string CompressSyncMsg(std::string &inputStr); // 解压缩sync 消息 - std::string decompressSyncMsg(std::string& compressed, uint32_t oriLen); + std::string DecompressSyncMsg(std::string& compressed, uint32_t oriLen); // 序列化acl int32_t ACLToStr(DistributedDeviceProfile::AccessControlProfile acl, std::string aclStr); + // 创建190报文 + void CreateMessageSyncResp(std::shared_ptr context, nlohmann::json &jsonObject); + // 创建200报文 + void CreateMessageFinish(std::shared_ptr context, nlohmann::json &jsonObject); + // 解密180 190报文 + int32_t DecryptSyncMessage(std::shared_ptr &context, + DmAccess &access, std::string &enSyncMsg); + int32_t ParseSyncMessage(std::shared_ptr &context, + DmAccess &access, nlohmann::json jsonObject); std::shared_ptr cryptoMgr_ = nullptr; }; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 6bb7a5556..07d8bcff7 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -110,6 +110,8 @@ public: virtual ~DmAuthState() {}; virtual DmAuthStateType GetStateType() = 0; virtual int32_t Action(std::shared_ptr context) = 0; // 执行状态对应的action动作 + void SyncAclList(std::shared_ptr context, int32_t accountId, + std::string credId, int32_t sessionKeyId, int32_t aclId); 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); @@ -293,6 +295,32 @@ private: int32_t GetAuthCredentialInfo(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; +}; + +// AuthSrcFinishState // 收到190报文,发送200报文 +class AuthSrcFinishState : public DmAuthState { + public: + virtual ~AuthSrcFinishState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; + void SourceFinish(std::shared_ptr context); +}; + +// AuthSinkFinishState // 收到200结束报文 +class AuthSinkFinishState : public DmAuthState { + public: + virtual ~AuthSinkFinishState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; + void SinkFinish(std::shared_ptr context); +}; } // namespace DistributedHardware } // namespace OHOS #endif // OHOS_DM_AUTH_STATE_V2_H \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 0d987f571..c71adcb91 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -15,6 +15,12 @@ #include "dm_auth_state.h" +#include +#include + +#include "deviceprofile_connector.h" +#include "dm_auth_context.h" +#include "dm_constants.h" namespace OHOS { namespace DistributedHardware { @@ -29,6 +35,176 @@ AuthSinkDataSyncState, // 收到180同步报文,发送190报文 AuthSinkFinishState, // 收到200结束报文 */ +const int32_t USLEEP_TIME_US_500000 = 500000; // 500ms +// 收到180同步报文,发送190报文 +int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkDataSyncState::Action start"); + // 判断密文阶段和明文阶段的四元组是否相同,不同则直接结束 + bool isSame = context->encryAccesser.deviceId == context->accesser.deviceId && + context->encryAccesser.userId == context->accesser.userId && + context->encryAccesser.accountId == context->accesser.accountId && + context->encryAccesser.tokenId == context->accesser.tokenId; + if (!isSame) { + LOGE("data between two stages different, stop auth"); + context->reply = DM_AUTHENTICATE_FINISH; + context->reason = ERR_DM_QUADRUPLE_NOT_SAME; + context->state = static_cast(GetStateType()); + return ERR_DM_FAILED; + } + // 查询sink端acl + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAccessControlProfile(); + std::vector sinkAclList; + for (auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == context->accesser.deviceId && + item.GetAccesser().GetAccesserUserId() == context->accesser.userId && + item.GetAccessee().GetAccesseeDeviceId() == context->accessee.deviceId && + item.GetAccessee().GetAccesseeUserId() == context->accessee.userId) { + sinkAclList.push_back(item); // 打印并写入 + } + } + if (sinkAclList.empty()) { + LOGE("get acl failed"); + return ERR_DM_FAILED; + } + // 比较双端的acl + for (auto &sinkAcl : sinkAclList) { + std::string aclChecksum = context->authMessageProcessor->ChecksumAcl(sinkAcl); + auto item = find(context->encryAccesser.aclChecksumList.begin(), + context->encryAccesser.aclChecksumList.end(), aclChecksum); + if (item != context->encryAccesser.aclChecksumList.end()) { + continue; + } + SyncAclList(context, std::atoi(sinkAcl.GetAccessee().GetAccesseeAccountId().c_str()), + std::to_string(sinkAcl.GetAccessee().GetAccesseeCredentialId()), + sinkAcl.GetAccessee().GetAccesseeSessionKeyId(), sinkAcl.GetAccessControlId()); + } + // 保存本次acl + context->authMessageProcessor->PutAccessControlList(context, context->accessee, context->accesser.deviceId); + + // 同步本端的sp信息,不确定格式,暂不做 + + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_DATA_SYNC, context); + LOGI("AuthSinkDataSyncState::Action ok"); + return DM_OK; +} + +DmAuthStateType AuthSinkDataSyncState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE; +} + +// 收到190报文,发送200报文 +int32_t AuthSrcFinishState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcFinishState::Action start"); + // 判断密文阶段和明文阶段的四元组是否相同,不同则直接结束 + bool isSame = context->encryAccessee.deviceId == context->accessee.deviceId && + context->encryAccessee.userId == context->accessee.userId && + context->encryAccessee.accountId == context->accessee.accountId && + context->encryAccessee.tokenId == context->accessee.tokenId; + if (!isSame) { + LOGE("data between two stages different, stop auth"); + // 不同直接结束,发送200给sink端 + context->reason = ERR_DM_QUADRUPLE_NOT_SAME; + context->reply = DM_AUTHENTICATE_FINISH; + context->state = static_cast(GetStateType()); + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_FINISH, context); + return ERR_DM_FAILED; + } + // 查询sink端acl + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAccessControlProfile(); + std::vector srcAclList; + for (auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == context->accesser.deviceId && + item.GetAccesser().GetAccesserUserId() == context->accesser.userId && + item.GetAccessee().GetAccesseeDeviceId() == context->accessee.deviceId && + item.GetAccessee().GetAccesseeUserId() == context->accessee.userId) { + srcAclList.push_back(item); // 打印并写入 + } + } + if (srcAclList.empty()) { + LOGE("get acl failed"); + return ERR_DM_FAILED; + } + // 比较双端的acl + for (auto &srcAcl : srcAclList) { + std::string aclChecksum = context->authMessageProcessor->ChecksumAcl(srcAcl); + auto item = find(context->encryAccessee.aclChecksumList.begin(), + context->encryAccessee.aclChecksumList.end(), aclChecksum); + if (item != context->encryAccessee.aclChecksumList.end()) { + continue; + } + SyncAclList(context, std::atoi(srcAcl.GetAccesser().GetAccesserAccountId().c_str()), + std::to_string(srcAcl.GetAccesser().GetAccesserCredentialId()), + srcAcl.GetAccesser().GetAccesserSessionKeyId(), srcAcl.GetAccessControlId()); + } + // 保存本次acl + context->authMessageProcessor->PutAccessControlList(context, context->accesser, context->accessee.deviceId); + // 同步本端的sp信息,不确定格式,暂不做 + + // 触发组网 + if (!context->accesser.isOnline) { + context->softbusConnector->JoinLnn(context->accessee.deviceId); + } + context->reason = DM_OK; + context->reply = DM_AUTHENTICATE_FINISH; + context->state = static_cast(GetStateType()); + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_FINISH, context); + LOGI("AuthSrcFinishState::Action ok"); + SourceFinish(context); + return DM_OK; +} + +DmAuthStateType AuthSrcFinishState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_FINISH_STATE; +} + +void AuthSrcFinishState::SourceFinish(std::shared_ptr context) +{ + context->authStateMachine = nullptr; + context->authUiStateMgr = nullptr; + context->hiChainAuthConnector = nullptr; + context->authMessageProcessor = nullptr; + usleep(USLEEP_TIME_US_500000); // 500ms + context->softbusConnector->GetSoftbusSession()->CloseAuthSession(context->sessionId); + context->softbusConnector = nullptr; + context->listener = nullptr; + context->authPtr = nullptr; + context->timer->DeleteAll(); + context->timer = nullptr; + context = nullptr; +} + +// 收到200结束报文 +int32_t AuthSinkFinishState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkFinishState::Action start"); + SinkFinish(context); + LOGI("AuthSinkFinishState::Action ok"); + return DM_OK; +} + +DmAuthStateType AuthSinkFinishState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_FINISH_STATE; +} +void AuthSinkFinishState::SinkFinish(std::shared_ptr context) +{ + context->authStateMachine = nullptr; + context->authUiStateMgr = nullptr; + context->hiChainAuthConnector = nullptr; + context->authMessageProcessor = nullptr; + context->softbusConnector = nullptr; + context->listener = nullptr; + context->authPtr = nullptr; + context->timer->DeleteAll(); + context->timer = nullptr; + context = nullptr; +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index f05b3fe6e..d1c157f9f 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -57,6 +57,58 @@ int32_t DmAuthMessageProcessor::SaveSessionKeyToDP(int32_t &skId) return DeviceProfileConnector::GetInstance().PutSessionKey(sessionKey, skLen, skId); } +int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptr context, + DmAccess &access, std::string trustDeviceId) +{ + LOGI("Start."); + uint32_t bindType = DM_ACROSS_ACCOUNT; + if (context->accesser.accountId == "ohosAnonymousUid" || context->accessee.accountId == "ohosAnonymousUid") { + bindType = DM_POINT_TO_POINT; + } + uint32_t authenticationType = ALLOW_AUTH_ONCE; + if (context->authResult == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + authenticationType = ALLOW_AUTH_ALWAYS; + } + DistributedDeviceProfile::Accesser accesser; + accesser.SetAccesserDeviceId(context->accesser.deviceId); + accesser.SetAccesserUserId(context->accesser.userId); + accesser.SetAccesserAccountId(context->accesser.accountId); + accesser.SetAccesserTokenId(context->accesser.tokenId); + accesser.SetAccesserBundleName(context->accesser.bundleName); + accesser.SetAccesserDeviceName(context->accesser.deviceName); + accesser.SetAccesserServiceId(context->accesser.serviceId); + accesser.SetAccesserCredentialId(context->accesser.credentialId); + accesser.SetAccesserSessionKeyId(context->accesser.sessionKeyId); + accesser.SetAccesserSKTimeStamp(context->accesser.skTimeStamp); + DistributedDeviceProfile::Accessee accessee; + accessee.SetAccesseeDeviceId(context->accessee.deviceId); + accessee.SetAccesseeUserId(context->accessee.userId); + accessee.SetAccesseeAccountId(context->accessee.accountId); + accessee.SetAccesseeTokenId(context->accessee.tokenId); + accessee.SetAccesseeBundleName(context->accessee.bundleName); + accessee.SetAccesseeDeviceName(context->accessee.deviceName); + accessee.SetAccesseeServiceId(context->accessee.serviceId); + accessee.SetAccesseeCredentialId(context->accessee.credentialId); + accessee.SetAccesseeSessionKeyId(context->accessee.sessionKeyId); + accessee.SetAccesseeSKTimeStamp(context->accessee.skTimeStamp); + DistributedDeviceProfile::AccessControlProfile profile; + profile.SetBindType(bindType); + profile.SetBindLevel(access.bindLevel); + profile.SetStatus(ACTIVE); + profile.SetTrustDeviceId(trustDeviceId); + profile.SetDeviceIdType((int32_t)DistributedDeviceProfile::DeviceIdType::UDID); + profile.SetDeviceIdHash(access.deviceIdHash); + profile.SetAuthenticationType(authenticationType); + profile.SetAccessee(accessee); + profile.SetAccesser(accesser); + int32_t ret = + DistributedDeviceProfile::DistributedDeviceProfileClient::GetInstance().PutAccessControlProfile(profile); + if (ret != DM_OK) { + LOGE("PutAccessControlProfile failed."); + } + return ret; +} + DmAuthMessageProcessor::DmAuthMessageProcessor() { LOGI("DmAuthMessageProcessor constructor"); @@ -117,6 +169,10 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont return ParseMessageReqCredExchange(jsonObject, context); case MSG_TYPE_RESP_CREDENTIAL_EXCHANGE: return ParseMessageRspCredExchange(jsonObject, context); + case MSG_TYPE_REQ_DATA_SYNC: + return ParseMessageSyncReq(jsonObject, context); + case MSG_TYPE_RESP_DATA_SYNC: + return ParseMessageSyncResp(jsonObject, context); default: break; } @@ -333,6 +389,12 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh return ""; } break; + case MSG_TYPE_RESP_DATA_SYNC: + CreateMessageSyncResp(context, jsonObj); + break; + case MSG_TYPE_AUTH_FINISH: + CreateMessageFinish(context, jsonObj); + break; default: LOGE("DmAuthMessageProcessor::CreateMessage msgType %{public}d error.", msgType); break; @@ -462,9 +524,232 @@ void DmAuthMessageProcessor::CreateMessageReqCredAuthStart(std::shared_ptr(checksum)); +} + +// 创建190报文 +void DmAuthMessageProcessor::CreateMessageSyncResp(std::shared_ptr context, + nlohmann::json &jsonObject) +{ + // 查询ACL + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAccessControlProfile(); + std::vector sinkAclList; // 保存本端ACL的checksum + for (auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == context->accesser.deviceId && + item.GetAccesser().GetAccesserUserId() == context->accesser.userId && + item.GetAccessee().GetAccesseeDeviceId() == context->accessee.deviceId && + item.GetAccessee().GetAccesseeUserId() == context->accessee.userId) { + sinkAclList.push_back(ChecksumAcl(item)); // 打印并写入 + } + } + if (sinkAclList.empty()) { + LOGE("DmAuthMessageProcessor::CreateMessageSyncResp get acl checksum failed"); + return; + } + DmAccess access; // 代表本端的access + if (context->direction == DM_AUTH_SINK) { + access = context->accessee; + } else { + access = context->accesser; + } + + std::string encSyncMsg; + int32_t ret = EncryptSyncMessage(context, sinkAclList, access, encSyncMsg); + if (ret != DM_OK) { + LOGE("DmAuthMessageProcessor::CreateMessageSyncResp encrypt failed"); + return; + } + jsonObject[DM_TAG_SYNC] = encSyncMsg; + return; +} + +// 创建200报文 +void DmAuthMessageProcessor::CreateMessageFinish(std::shared_ptr context, + nlohmann::json &jsonObject) +{ + jsonObject[DM_TAG_REPLY] = context->reply; + jsonObject[DM_TAG_STATE] = context->state; + jsonObject[DM_TAG_REASON] = context->reason; + return; +} + +int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr &context, + DmAccess &access, nlohmann::json jsonObject) +{ + if (!IsString(jsonObject, DM_TAG_USERSKID)) { + LOGE("ParseSyncMessage DM_TAG_USERSKID error"); + return ERR_DM_FAILED; + } + context->userSessionKeyId = std::atoi(jsonObject[DM_TAG_USERSKID].get().c_str()); + if (!IsString(jsonObject, DM_TAG_USERSK_TIMESTAMP)) { + LOGE("ParseSyncMessage DM_TAG_USERSK_TIMESTAMP error"); + return ERR_DM_FAILED; + } + context->userSkTimeStamp = std::atoi(jsonObject[DM_TAG_USERSK_TIMESTAMP].get().c_str()); + if (!IsString(jsonObject, DM_TAG_DMVERSION)) { + LOGE("ParseSyncMessage DM_TAG_DMVERSION error"); + return ERR_DM_FAILED; + } + access.dmVersion = jsonObject[DM_TAG_DMVERSION].get(); + if (!IsString(jsonObject, DM_TAG_ACCESS)) { // 再解析一次 + LOGE("ParseSyncMessage DM_TAG_ACCESS error"); + return ERR_DM_FAILED; + } + std::string srcAccessStr = jsonObject[DM_TAG_ACCESS].get(); + // 解析到 access里面 + nlohmann::json accessjson = nlohmann::json::parse(srcAccessStr, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("ParseSyncMessage srcAccessStr error"); + return ERR_DM_FAILED; + } + DmAccessToSync srcAccessToSync = accessjson; + access.deviceName = srcAccessToSync.deviceName; + access.deviceId = srcAccessToSync.deviceId; + access.userId = srcAccessToSync.userId; + access.accountId = srcAccessToSync.accountId; + access.tokenId = srcAccessToSync.tokenId; + access.bundleName = srcAccessToSync.bundleName; + access.bindLevel = srcAccessToSync.bindLevel; + access.sessionKeyId = srcAccessToSync.sessionKeyId; + access.skTimeStamp = srcAccessToSync.skTimeStamp; + if (context->isOnline) { + access.appSessionKeyId = srcAccessToSync.sessionKeyId; + access.appSkTimeStamp = srcAccessToSync.skTimeStamp; + } else { + access.userSessionKeyId = srcAccessToSync.sessionKeyId; + access.userSkTimeStamp = srcAccessToSync.skTimeStamp; + } + if (IsString(jsonObject, DM_TAG_PROXY)) { // 预留字段 + std::string proxyInfo = jsonObject[DM_TAG_PROXY].get(); + } + if (IsArray(jsonObject, DM_TAG_ACL_CHECKSUM)) { // 再解析一次 acl + LOGE("ParseSyncMessage DM_TAG_ACL_CHECKSUM error"); + return ERR_DM_FAILED; + } + access.aclChecksumList = jsonObject[DM_TAG_ACL_CHECKSUM].get>(); + if (IsString(jsonObject, DM_TAG_SERVICEINFO)) { // sp 暂时没有传 + std::string serviceInfo = jsonObject[DM_TAG_SERVICEINFO].get(); + } + return DM_OK; +} + +int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptr &context, + DmAccess &access, std::string &enSyncMsg) +{ + // 解密整个字段 + std::string syncMsgCompress = ""; + int32_t ret = cryptoMgr_->DecryptMessage(enSyncMsg, syncMsgCompress); + if (ret != DM_OK) { + LOGE("DecryptSyncMessage syncMsg error"); + return ret; + } + nlohmann::json plainJson = nlohmann::json::parse(syncMsgCompress, nullptr, false); + if (plainJson.is_discarded()) { + LOGE("DecryptSyncMessage plainJson error"); + return ERR_DM_FAILED; + } + if (!IsInt32(plainJson, DM_TAG_COMPRESS_ORI_LEN)) { + LOGE("DecryptSyncMessage DM_TAG_COMPRESS_ORI_LEN json error"); + return ERR_DM_FAILED; + } + int32_t dataLen = plainJson[DM_TAG_COMPRESS_ORI_LEN].get(); + if (!IsString(plainJson, DM_TAG_COMPRESS)) { + LOGE("DecryptSyncMessage DM_TAG_COMPRESS_ORI_LEN json error"); + return ERR_DM_FAILED; + } + std::string compressMsg = plainJson[DM_TAG_COMPRESS].get(); + // 解压缩 + std::string syncMsg = DecompressSyncMsg(compressMsg, dataLen); + // 解析字段 + nlohmann::json jsonObject = nlohmann::json::parse(syncMsg, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("DmAuthMessageProcessor::GetTransmitFromContext extraInfo jsonStr error"); + return ERR_DM_FAILED; + } + if (IsString(jsonObject, DM_TAG_APPSKID)) { + context->appSessionKeyId = std::atoi(jsonObject[DM_TAG_APPSKID].get().c_str()); + } + if (IsString(jsonObject, DM_TAG_APPSK_TIMESTAMP)) { + context->appSkTimeStamp = std::atoi(jsonObject[DM_TAG_APPSK_TIMESTAMP].get().c_str()); + } + ret = ParseSyncMessage(context, access, jsonObject); + if (ret != DM_OK) { + LOGE("DecryptSyncMessage ParseSyncMessage jsonStr error"); + return ret; + } + return DM_OK; +} + +// 解析 180报文信息 MSG_TYPE_REQ_DATA_SYNC 存放对方密文四元组,acl,sp skid +int32_t DmAuthMessageProcessor::ParseMessageSyncReq(const nlohmann::json &jsonObject, std::shared_ptr context) +{ + // 解析json中的加密数据 + if (!IsString(jsonObject, DM_TAG_SYNC)) { // 再解析一次 acl + LOGE("ParseMessageSyncReq json error"); + return ERR_DM_FAILED; + } + std::string enSyncMsg = jsonObject[DM_TAG_SYNC].get(); + // 解密数据 + 解析数据到context中 + int32_t ret = DecryptSyncMessage(context, context->encryAccesser, enSyncMsg); + if (ret != DM_OK) { + LOGE("DecryptSyncMessage enSyncMsg error"); + return ret; + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +// 解析 190报文信息 MSG_TYPE_RESP_DATA_SYNC 存放对方密文四元组,acl sp skid +int32_t DmAuthMessageProcessor::ParseMessageSyncResp(const nlohmann::json &jsonObject, + std::shared_ptr context) +{ + // 解析json中的加密数据 + if (!IsString(jsonObject, DM_TAG_SYNC)) { // 再解析一次 acl + LOGE("ParseMessageSyncResp json error"); + return ERR_DM_FAILED; + } + std::string enSyncMsg = jsonObject[DM_TAG_SYNC].get(); + // 解密数据 + 解析数据到context中 + int32_t ret = DecryptSyncMessage(context, context->encryAccessee, enSyncMsg); + if (ret != DM_OK) { + LOGE("DecryptSyncMessage enSyncMsg error"); + return ret; + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +// 解析200报文 +int32_t DmAuthMessageProcessor::ParseMessageFinish(std::shared_ptr context, + nlohmann::json &jsonObject) +{ + if (IsInt32(jsonObject, DM_TAG_REPLY)) { + context->reply = jsonObject[DM_TAG_REPLY].get(); + } + if (IsInt32(jsonObject, DM_TAG_STATE)) { + context->state = jsonObject[DM_TAG_STATE].get(); + } + if (IsInt32(jsonObject, DM_TAG_REASON)) { + context->reason = jsonObject[DM_TAG_REASON].get(); + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + +void DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject, std::shared_ptr context) { if (IsString(jsonObject, TAG_DEVICE_VERSION)) { context->accesser.dmVersion = jsonObject[TAG_DEVICE_VERSION].get(); @@ -665,7 +950,7 @@ void DmAuthMessageProcessor::CreateAndSendMsg(DmMessageType msgType, std::shared context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); } -std::string DmAuthMessageProcessor::compressSyncMsg(std::string &inputStr) +std::string DmAuthMessageProcessor::CompressSyncMsg(std::string &inputStr) { uint32_t srcLen = inputStr.size(); uint32_t boundSize = compressBound(srcLen); // 最大压缩长度 @@ -676,14 +961,14 @@ std::string DmAuthMessageProcessor::compressSyncMsg(std::string &inputStr) int32_t ret = compress(reinterpret_cast(&compressed[0]), &destSize, reinterpret_cast(inputStr.data()), srcLen); if (ret != Z_OK) { - LOGE("DmAuthMessageProcessor::compressSyncMsg zlib compress failed"); + LOGE("DmAuthMessageProcessor::CompressSyncMsg zlib compress failed"); return ""; } compressed.resize(destSize); // 实际使用长度 return compressed; } -std::string DmAuthMessageProcessor::decompressSyncMsg(std::string& compressed, uint32_t oriLen) +std::string DmAuthMessageProcessor::DecompressSyncMsg(std::string& compressed, uint32_t oriLen) { std::string decompressed; decompressed.resize(oriLen); @@ -692,7 +977,7 @@ std::string DmAuthMessageProcessor::decompressSyncMsg(std::string& compressed, u reinterpret_cast(compressed.data()), // 解压时跳过头部 compressed.size()); if (ret != Z_OK || destLen != oriLen) { - LOGE("DmAuthMessageProcessor::decompressSyncMsg decompress failed"); + LOGE("DmAuthMessageProcessor::DecompressSyncMsg decompress failed"); return ""; } return decompressed; @@ -730,16 +1015,16 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptr> aclHashList; + std::vector aclHashList; for (auto &item : aclList) { uint8_t aclHash[DM_HASH_LEN] = {0}; Crypto::DmGenerateStrHash(item.data(), item.size(), aclHash, DM_HASH_LEN, 0); - aclHashList.push_back(std::vector(aclHash, aclHash + DM_HASH_LEN)); + aclHashList.push_back(std::string(reinterpret_cast(aclHash))); } syncMsgJson[DM_TAG_ACL_CHECKSUM] = aclHashList; std::string syncMsg = SafetyDump(syncMsgJson); // 消息构造完成 - std::string compressMsg = compressSyncMsg(syncMsg); // 压缩 + std::string compressMsg = CompressSyncMsg(syncMsg); // 压缩 if (compressMsg.empty()) { LOGE("DmAuthMessageProcessor::EncryptSyncMessage compress failed"); return ERR_DM_FAILED; diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 424dd1a37..2c1fda0ec 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -81,5 +81,21 @@ bool DmAuthState::IsScreenLocked() return isLocked; } +void DmAuthState::SyncAclList(std::shared_ptr context, int32_t accountId, + std::string credId, int32_t sessionKeyId, int32_t aclId) +{ + // 根据凭据id 删除sink端多余的凭据 + int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, credId); + if (ret != DM_OK) { + LOGE("SyncAclList DeleteCredential failed."); + } + // 根据skid删除sk,删除skid + ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(sessionKeyId); + if (ret != DM_OK) { + LOGE("SyncAclList DeleteSessionKey failed."); + } + // 删除本条acl + DeviceProfileConnector::GetInstance().DeleteAccessControlById(aclId); +} } // namespace DistributedHardware } // namespace OHOS -- Gitee From 4fbda239ffa122c43fea509fcaee7f6af89d2e93 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 6 Mar 2025 10:21:55 +0800 Subject: [PATCH 128/382] pick 180-200 \fix --- .../include/authentication_v2/dm_auth_message_processor.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index f4ba95384..4f4ab042a 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -173,7 +173,7 @@ public: // 保留本次acl int32_t PutAccessControlList(std::shared_ptr context, - DmAccess &access, std::string trustDeviceId) + DmAccess &access, std::string trustDeviceId); // 对acl进行checksum std::string ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl); -- Gitee From f16b6ef878ee726aa5d83904f5371736ce964551 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 6 Mar 2025 10:24:35 +0800 Subject: [PATCH 129/382] pick 180-200 \fix --- .../src/authentication_v2/dm_auth_message_processor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index d1c157f9f..e89616a9a 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -749,7 +749,7 @@ int32_t DmAuthMessageProcessor::ParseMessageFinish(std::shared_ptr context) +int32_t DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject, std::shared_ptr context) { if (IsString(jsonObject, TAG_DEVICE_VERSION)) { context->accesser.dmVersion = jsonObject[TAG_DEVICE_VERSION].get(); -- Gitee From 8b7d1b6cbea71d06ea47db852406334c2967d22b Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 6 Mar 2025 10:27:20 +0800 Subject: [PATCH 130/382] tmp --- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 143bd4dd2..f4c547544 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -21,6 +21,7 @@ #include "dm_anonymous.h" #include "dm_auth_state_machine.h" #include "deviceprofile_connector.h" +#include "auth_manager.h" #undef LOG_TAG #define LOG_TAG "DHDM_V2" @@ -56,7 +57,7 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) context->timer->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); if (CompareVersion(context->accessee.dmVersion, std::string(DM_VERSION_5_1_0))) { LOGE("AuthSrcConfirmState::Action incompatible version %{public}s compare to 5.1.0", - context->accessee.dmVersion); + context->accessee.dmVersion.c_str()); context->reason = ERR_DM_VERSION_INCOMPATIBLE; return ERR_DM_VERSION_INCOMPATIBLE; } -- Gitee From c2667e566de39b864769dd7d22cb44d4f17a8072 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Thu, 6 Mar 2025 11:52:32 +0800 Subject: [PATCH 131/382] =?UTF-8?q?fix=EF=BC=9A140-150-160=E8=B0=83?= =?UTF-8?q?=E9=80=9A=E5=90=8E=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_manager.cpp | 2 ++ .../authentication_v2/auth_stages/auth_credential.cpp | 2 +- .../src/authentication_v2/dm_auth_context.cpp | 2 +- .../src/dependency/hichain/hichain_auth_connector.cpp | 11 +++++++++-- 4 files changed, 13 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 6cb7a09b8..0b0de6499 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -669,6 +669,7 @@ AuthSinkManager::AuthSinkManager(std::shared_ptr softbusConnec std::shared_ptr hiChainAuthConnector) : AuthManager(softbusConnector, listener, hiChainAuthConnector) { + context_->direction = DM_AUTH_SINK; } void AuthSinkManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) @@ -804,6 +805,7 @@ AuthSrcManager::AuthSrcManager(std::shared_ptr softbusConnecto std::shared_ptr hiChainAuthConnector) : AuthManager(softbusConnector, listener, hiChainAuthConnector) { + context_->direction = DM_AUTH_SOURCE; } void AuthSrcManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index f3ab87d39..49e0d3496 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -511,7 +511,7 @@ int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr c // 凭据认证 先进行应用级 ret = context->hiChainAuthConnector->AuthCredential(osAccountId, context->requestId, - context->accessee.appCredentialId, std::string("")); + context->accesser.appCredentialId, std::string("")); if (ret != DM_OK) { LOGE("AuthSrcCredentialAuthStartState::Action failed, auth app cred failed."); return ret; diff --git a/services/implementation/src/authentication_v2/dm_auth_context.cpp b/services/implementation/src/authentication_v2/dm_auth_context.cpp index cfccddcb4..8db58bb7f 100644 --- a/services/implementation/src/authentication_v2/dm_auth_context.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_context.cpp @@ -69,7 +69,7 @@ std::string DmAuthContext::GetCredentialId(DmAuthSide side, DmAuthScope authoriz std::string DmAuthContext::GetPublicKey(DmAuthSide side, DmAuthScope authorizedScope) { if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || - (authorizedScope != DM_AUTH_SCOPE_USER && DM_AUTH_SCOPE_USER != DM_AUTH_SCOPE_APP)) { + (authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP)) { return std::string(""); } diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 1909a2e83..8522c069e 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -149,9 +149,16 @@ int32_t HiChainAuthConnector::ExportCredential(int32_t osAccountId, const std::s free(returnData); return ERR_DM_FAILED; } - publicKey = returnData; - LOGI("HiChainAuthConnector::ExportCredential publicKey=%{public}s\n.", publicKey.c_str()); + + // 导出的公钥是json格式,需要解析 + nlohmann::json jsonAuthParam = nlohmann::json::parse(returnData, nullptr, false); free(returnData); + if (jsonAuthParam.is_discarded() || !IsString(jsonAuthParam, "keyValue")) { + LOGE("Hichain exportCredential failed, returnData is invalid."); + return ERR_DM_FAILED; + } + + publicKey = jsonAuthParam["keyValue"].get(); LOGI("HiChainAuthConnector::ExportCredential leave."); return DM_OK; } -- Gitee From bf927d4ea21ca7ff5a3bc2fc16f4963c647b2b0d Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Thu, 6 Mar 2025 14:16:23 +0800 Subject: [PATCH 132/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9authCred?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_credential.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 49e0d3496..8266a0c4c 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -134,7 +134,7 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co // 认证用户凭据 int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); ret = context->hiChainAuthConnector->AuthCredential(osAccountId, context->requestId, - context->accessee.userCredentialId, std::string("")); + context->accesser.userCredentialId, std::string("")); if (ret != DM_OK) { LOGE("AuthSrcCredentialAuthDoneState::Action Hichain auth credentail failed"); return ret; -- Gitee From 9201aebae0244da19e102534d9c9564c0c7efa6d Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 6 Mar 2025 15:11:43 +0800 Subject: [PATCH 133/382] tmp --- .../include/authentication_v2/dm_auth_context.h | 4 ++-- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 10 +++++++--- .../src/authentication_v2/dm_auth_state_machine.cpp | 9 ++++++--- 3 files changed, 15 insertions(+), 8 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 6a395c94b..f0c8ea2a9 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -46,7 +46,7 @@ typedef enum { AUTH_TYPE_PIN_SHOW = 1, // 弹PIN码 AUTH_TYPE_PIN_ULTRASONIC = 2, // 超声PIN码 AUTH_TYPE_PIN_IMPORT = 3, // 导入PIN码 - AUTH_TYPE_IMPORT_AUTH_CODE = 5, // 导入认证码 + AUTH_TYPE_IMPORT_AUTH_CODE = 5, // 导入认证码 todo del } DmAuthType; enum DmAuthDirection { @@ -146,7 +146,7 @@ struct DmAuthContext { int32_t authFailTimes{0}; // 认证失败次数,查过3次结束认证 int32_t pinCode{INVALID_PINCODE}; // 保存业务导入的pin码 int32_t connDelayCloseTime; // 链路延迟释放时间, 授权结束后不自动断链(有业务需要使用)保留字段 - int32_t reason; // 本端失败的原因 + int32_t reason{DM_OK}; // 本端失败的原因 int32_t reply; // 对端回复的结果 引用common/include/dm_constants.h,有新的错误码可新增 int32_t state; // 结束的状态 int32_t appSessionKeyId; // 本端永久应用SKID,由DP返回用于ACL的更新、老化 diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index f4c547544..a7df74283 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -58,18 +58,20 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) if (CompareVersion(context->accessee.dmVersion, std::string(DM_VERSION_5_1_0))) { LOGE("AuthSrcConfirmState::Action incompatible version %{public}s compare to 5.1.0", context->accessee.dmVersion.c_str()); - context->reason = ERR_DM_VERSION_INCOMPATIBLE; + context->reason = ERR_DM_VERSION_INCOMPATIBLE; // todo 发104报文??? return ERR_DM_VERSION_INCOMPATIBLE; } -#if 0 // todo +#if 0 // todo 有凭据情况 nlohmann::json jsonObject = nlohmann::json::parse(context->accessee.credentialInfos, nullptr, false); if (jsonObject.is_discarded()) { LOGE("AuthSrcConfirmState::Action parse credentialInfos error"); return ERR_DM_FAILED; } // 转结束绑定 + context->authStateMachine->TransitionTo(std::make_shared()); // 转凭据认证 + context->authStateMachine->TransitionTo(std::make_shared()); // 有无可信关系的分享凭据 if (g_shareByPinAuthDeviceTypeSet.contains(static_cast(context->deviceType))) { @@ -78,6 +80,7 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) // send 100 } else { // 转凭据认证 + context->authStateMachine->TransitionTo(std::make_shared()); } // 有点对点可信 @@ -86,6 +89,7 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) // send 100 } else { // 结束绑定 + context->authStateMachine->TransitionTo(std::make_shared()); } #endif // 无凭据 @@ -130,7 +134,7 @@ int32_t AuthSinkConfirmState::ShowConfigDialog(std::shared_ptr co LOGI("AuthSinkConfirmState::ShowConfigDialog end"); return DM_OK; } -#if 1 // todo +#if 1 // todo 新的获取方法 根据客户端AuthType和BundleName从服务端SP表里查询业务注册的认证类型 int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context) { // DP 接口 查询ServiceInfoProfile diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 4e32fa608..d56dce0d0 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -168,11 +168,14 @@ void DmAuthStateMachine::Run(std::shared_ptr context) int32_t ret = state.value()->Action(context); if (ret != DM_OK) { LOGE("DmAuthStateMachine::Run err:%{public}d", ret); - context->reason = ret; + if (context->reason == DM_OK) { + // 如果context的reason没有被设置,则设置为ret + context->reason = ret; + } if (context->direction == DM_AUTH_SOURCE) { - // this->TransitionTo(std::make_shared()); + this->TransitionTo(std::make_shared()); } else { - // this->TransitionTo(std::make_shared()); + this->TransitionTo(std::make_shared()); } // finish需要,清理context以及重启状态机 } else { -- Gitee From ee58be988c580929ae24d9eacc96aada1f84cbfe Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Thu, 6 Mar 2025 17:06:24 +0800 Subject: [PATCH 134/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9160=E8=A7=A3=E6=9E=90?= =?UTF-8?q?=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication_v2/dm_auth_message_processor.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index e89616a9a..22aa87059 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -220,12 +220,12 @@ int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const nlohmann::js int32_t DmAuthMessageProcessor::ParseMessageOnTransmit(const nlohmann::json &jsonObject, std::shared_ptr context) { - if (jsonObject.is_discarded() || !IsString(jsonObject, DM_TAG_DATA)) { + if (jsonObject.is_discarded() || !IsString(jsonObject, DM_TAG_ON_TRANSMIT_DATA)) { LOGE("DmAuthMessageProcessor::ParseMessageOnTransmit failed, decodeRequestAuth jsonStr error"); return ERR_DM_FAILED; } - context->SetContextExtra(DM_TAG_ON_TRANSMIT_DATA, jsonObject[DM_TAG_DATA].get()); + context->SetContextExtra(DM_TAG_ON_TRANSMIT_DATA, jsonObject[DM_TAG_ON_TRANSMIT_DATA].get()); return DM_OK; } @@ -1141,17 +1141,20 @@ int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(nlohmann::json &jsonObject std::string jsonTag; if (context->isOnline == false && context->isAppCredentailVerified == false) { // 首次认证的应用凭据 jsonTag = DM_TAG_APP_CREDENTIAL_ID; + context->accesser.appCredentialId = jsonDecrptObj[DM_TAG_APP_CREDENTIAL_ID].get(); } else if (context->isOnline == false) { // 首次认证的用户凭据 jsonTag = DM_TAG_USER_CREDENTIAL_ID; + context->accesser.userCredentialId = jsonDecrptObj[DM_TAG_USER_CREDENTIAL_ID].get(); } else { // 非首次认证的应用凭据 - jsonTag = DM_TAG_APP_CREDENTIAL_ID; + jsonTag = DM_TAG_APP_CREDENTIAL_ID; + context->accesser.appCredentialId = jsonDecrptObj[DM_TAG_APP_CREDENTIAL_ID].get(); } if (!jsonDecrptObj.contains(jsonTag) || !jsonDecrptObj[jsonTag].is_string()) { LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae Unlegal json CRED ID"); return ERR_DM_FAILED; } - context->accesser.appCredentialId = jsonDecrptObj[jsonTag].get(); + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } -- Gitee From bce9a97c353f9c365e4730359ed8084ee2e70afd Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Thu, 6 Mar 2025 17:07:40 +0800 Subject: [PATCH 135/382] =?UTF-8?q?=E5=90=8C=E7=B1=BBtag=E8=A7=A3=E6=9E=90?= =?UTF-8?q?=E5=A4=B1=E8=B4=A5=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 22aa87059..0e6c4965b 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -413,7 +413,7 @@ int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr LOGE("DmAuthMessageProcessor::CreateSyncMessage encrypt failed"); return ret; } - jsonObject[DM_TAG_DATA] = encryptMsg; + jsonObject[DM_TAG_ON_TRANSMIT_DATA] = encryptMsg; return DM_OK; } @@ -1154,7 +1154,7 @@ int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(nlohmann::json &jsonObject LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae Unlegal json CRED ID"); return ERR_DM_FAILED; } - + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } -- Gitee From d4ae95918bd80a15e8e7049a55b23b4d4f5e9c46 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Thu, 6 Mar 2025 17:55:26 +0800 Subject: [PATCH 136/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E8=A7=A3=E6=9E=90?= =?UTF-8?q?=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 0e6c4965b..c49947313 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -194,7 +194,7 @@ int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const nlohmann::js return ret; } - nlohmann::json jsonDecrptObj = plainText; + nlohmann::json jsonDecrptObj = nlohmann::json::parse(plainText, nullptr, false); if (ParseMessageOnTransmit(jsonDecrptObj, context) != DM_OK) { LOGE("DmAuthMessageProcessor::ParseMessageNegotiateTransmit ParseMessageOnTransmit failed"); return ERR_DM_FAILED; @@ -1132,7 +1132,7 @@ int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(nlohmann::json &jsonObject LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae DecryptMessage failed"); return ret; } - nlohmann::json jsonDecrptObj = plainText; + nlohmann::json jsonDecrptObj = nlohmann::json::parse(plainText, nullptr, false); if (ParseMessageOnTransmit(jsonDecrptObj, context) != DM_OK) { LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae ParseMessageOnTransmit failed"); -- Gitee From af1590a3316e8ae1552a05a112af35968e07769c Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 6 Mar 2025 19:44:21 +0800 Subject: [PATCH 137/382] tmp --- .../include/authentication_v2/dm_auth_state_machine.h | 1 + .../src/authentication_v2/dm_auth_state_machine.cpp | 8 ++++++++ 2 files changed, 9 insertions(+) diff --git a/services/implementation/include/authentication_v2/dm_auth_state_machine.h b/services/implementation/include/authentication_v2/dm_auth_state_machine.h index cbb5f29a2..b9e51ab10 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state_machine.h +++ b/services/implementation/include/authentication_v2/dm_auth_state_machine.h @@ -93,6 +93,7 @@ private: std::condition_variable stateCv_; std::mutex eventMutex_; std::condition_variable eventCv_; + DmAuthDirection direction_; }; } // namespace DistributedHardware diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index d56dce0d0..9423fa1f3 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -72,6 +72,7 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) }; running_ = true; + direction_ = context->direction; this->SetCurState(DmAuthStateType::AUTH_IDLE_STATE); thread_ = std::thread(&DmAuthStateMachine::Run, this, context); @@ -149,6 +150,13 @@ void DmAuthStateMachine::NotifyEventFinish(DmEventType eventType) eventQueue_.push(eventType); } eventCv_.notify_one(); + if (eventType == DmEventType::ON_FAIL) { + if (direction_ == DM_AUTH_SOURCE) { + this->TransitionTo(std::make_shared()); + } else { + this->TransitionTo(std::make_shared()); + } + } } // 循环等待状态转移,执行action -- Gitee From b6f54d8165b28b7daaa0cf72bd6b9f4c7fad419c Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Thu, 6 Mar 2025 20:09:37 +0800 Subject: [PATCH 138/382] =?UTF-8?q?=E5=BD=92=E4=B8=80transmitdata?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication_v2/dm_auth_context.h | 33 ------------------- .../auth_stages/auth_credential.cpp | 11 +++---- .../dm_auth_message_processor.cpp | 15 ++++----- 3 files changed, 11 insertions(+), 48 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index f0c8ea2a9..4d739bedd 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -206,39 +206,6 @@ struct DmAuthContext { int32_t SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope, const std::string &publicKey); // 获取账号ID std::string GetAccountId(DmAuthSide side); - - // 设置扩展字段,key-value格式 - template - int32_t SetContextExtra(const std::string &key, const T &value) - { - nlohmann::json jsonExtra; - if (!extraInfo.empty()) { - jsonExtra = nlohmann::json::parse(extraInfo); - if (jsonExtra.is_discarded()) { - return ERR_DM_FAILED; - } - } - - jsonExtra[key] = value; - extraInfo = SafetyDump(jsonExtra); - return DM_OK; - } - - // 获取扩展字段中key对应的value - template - int32_t GetFromContextExtra(const std::string &key, T &value) - { - if (extraInfo.empty()) { - return DM_OK; - } - - nlohmann::json jsonExtra = nlohmann::json::parse(extraInfo); - if (jsonExtra.is_discarded()) { - return ERR_DM_FAILED; - } - value = jsonExtra[key].get(); - return DM_OK; - } }; } // namespace DistributedHardware diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 8266a0c4c..c30ac89a2 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -36,14 +36,13 @@ namespace DistributedHardware { // 如果onsessionkeyreturned事件,在对应回调解析并保存在cryptomgr static int32_t AuthCredentialTransmitDecryptProcess(std::shared_ptr context, DmEventType event) { - std::string transmitStr; - if (context->GetFromContextExtra(DM_TAG_ON_TRANSMIT_DATA, transmitStr) != DM_OK) { - LOGE("DmAuthMessageProcessor::CreateMessageReqCredAuthStart failed, get onTransmitData from extra failed."); + if (context->transmitData.empty()) { + LOGE("DmAuthMessageProcessor::CreateMessageReqCredAuthStart failed, get onTransmitData failed."); return ERR_DM_FAILED; } // 透传给hichain - int32_t ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, transmitStr); + int32_t ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); if (ret != DM_OK) { LOGE("AuthCredentialTransmitDecryptProcess: ProcessCredData transmit data failed"); return ERR_DM_FAILED; @@ -60,9 +59,7 @@ static int32_t AuthCredentialTransmitDecryptProcess(std::shared_ptr context, DmMessageType msgType) { // 获取transmit data - std::string transmitStr; - transmitStr = context->authMessageProcessor->GetTransmitFromContext(context); - if (transmitStr.empty()) { + if (context->transmitStr.empty()) { LOGE("AuthCredentialTransmitSend: GetTransmitFromContext from HICHAIN failed"); return ERR_DM_FAILED; } diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index c49947313..9fdb69fea 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -216,7 +216,7 @@ int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const nlohmann::js return DM_OK; } -// 解析onTransmit返回的数据,保存到context->extra中 +// 解析onTransmit返回的数据,保存到context->transmitData int32_t DmAuthMessageProcessor::ParseMessageOnTransmit(const nlohmann::json &jsonObject, std::shared_ptr context) { @@ -224,8 +224,7 @@ int32_t DmAuthMessageProcessor::ParseMessageOnTransmit(const nlohmann::json &jso LOGE("DmAuthMessageProcessor::ParseMessageOnTransmit failed, decodeRequestAuth jsonStr error"); return ERR_DM_FAILED; } - - context->SetContextExtra(DM_TAG_ON_TRANSMIT_DATA, jsonObject[DM_TAG_ON_TRANSMIT_DATA].get()); + context->transmitData = jsonObject[DM_TAG_ON_TRANSMIT_DATA].get(); return DM_OK; } @@ -408,7 +407,7 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr &context, nlohmann::json &jsonObject) { std::string encryptMsg; - int32_t ret = cryptoMgr_->EncryptMessage(DmAuthMessageProcessor::GetTransmitFromContext(context), encryptMsg); // 临时SK加密 + int32_t ret = cryptoMgr_->EncryptMessage(context->transmitData, encryptMsg); // 临时SK加密 if (ret != DM_OK) { LOGE("DmAuthMessageProcessor::CreateSyncMessage encrypt failed"); return ret; @@ -675,7 +674,7 @@ int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptrextraInfo, nullptr, false); - if (jsonObject.is_discarded() || !jsonObject.contains(DM_TAG_DATA) || !jsonObject[DM_TAG_DATA].is_string()) { - LOGE("DmAuthMessageProcessor::GetTransmitFromContext extraInfo jsonStr error"); + if (jsonObject.is_discarded() || !jsonObject.contains(DM_TAG_ON_TRANSMIT_DATA) || !jsonObject[DM_TAG_ON_TRANSMIT_DATA].is_string()) { + LOGE("DmAuthMessageProcessor::GetTransmitFromContext jsonStr error"); return transmitStr; } - return SafetyDump(jsonObject[DM_TAG_DATA]); + return SafetyDump(jsonObject[DM_TAG_ON_TRANSMIT_DATA]); } // 解析transmit和PSKID int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(nlohmann::json &jsonObject, std::shared_ptr &context) -- Gitee From 1049cc18f8387ff5eff5569bd9e478dd2e9032dc Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Thu, 6 Mar 2025 20:13:05 +0800 Subject: [PATCH 139/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_credential.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index c30ac89a2..8f64f83ca 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -59,7 +59,7 @@ static int32_t AuthCredentialTransmitDecryptProcess(std::shared_ptr context, DmMessageType msgType) { // 获取transmit data - if (context->transmitStr.empty()) { + if (context->transmitData.empty()) { LOGE("AuthCredentialTransmitSend: GetTransmitFromContext from HICHAIN failed"); return ERR_DM_FAILED; } -- Gitee From d4f3022aa2c7820f1630713c1713ee25f7b8c6b5 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Thu, 6 Mar 2025 20:24:45 +0800 Subject: [PATCH 140/382] =?UTF-8?q?171=E6=B6=88=E6=81=AF=E6=96=B0=E5=A2=9E?= =?UTF-8?q?=E4=B8=80=E5=B1=82=E5=8A=A0=E5=AF=86=E7=BB=93=E6=9E=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 9fdb69fea..eb6c8d2e4 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -407,12 +407,14 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr &context, nlohmann::json &jsonObject) { std::string encryptMsg; - int32_t ret = cryptoMgr_->EncryptMessage(context->transmitData, encryptMsg); // 临时SK加密 + nlohmann::json jsonData; + jsonData[DM_TAG_ON_TRANSMIT_DATA] = context->transmitData; + int32_t ret = cryptoMgr_->EncryptMessage(SafeDump(context->transmitData), encryptMsg); // 临时SK加密 if (ret != DM_OK) { LOGE("DmAuthMessageProcessor::CreateSyncMessage encrypt failed"); return ret; } - jsonObject[DM_TAG_ON_TRANSMIT_DATA] = encryptMsg; + jsonObject[DM_TAG_DATA] = encryptMsg; return DM_OK; } -- Gitee From 207439500bd0b4a3feeeace9c6581f3e794b4bf0 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Thu, 6 Mar 2025 20:26:44 +0800 Subject: [PATCH 141/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E7=BC=96=E7=A0=81?= =?UTF-8?q?=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index eb6c8d2e4..d128d0a4c 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -409,7 +409,7 @@ int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr std::string encryptMsg; nlohmann::json jsonData; jsonData[DM_TAG_ON_TRANSMIT_DATA] = context->transmitData; - int32_t ret = cryptoMgr_->EncryptMessage(SafeDump(context->transmitData), encryptMsg); // 临时SK加密 + int32_t ret = cryptoMgr_->EncryptMessage(SafeDump(jsonData), encryptMsg); // 临时SK加密 if (ret != DM_OK) { LOGE("DmAuthMessageProcessor::CreateSyncMessage encrypt failed"); return ret; -- Gitee From 22c29aef72d4e491d7533447a7b3685bda067aa6 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Thu, 6 Mar 2025 21:11:07 +0800 Subject: [PATCH 142/382] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E8=B7=B3=E8=BD=AC?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.cpp | 4 +- .../dm_auth_state_machine.cpp | 57 +++++++++++-------- 2 files changed, 36 insertions(+), 25 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index d128d0a4c..0ab8d5674 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -204,7 +204,7 @@ int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const nlohmann::js context->authStateMachine->TransitionTo(std::make_shared()); break; case MSG_TYPE_RESP_CREDENTIAL_AUTH_START: // 170 - context->authStateMachine->TransitionTo(std::make_shared()); + context->authStateMachine->TransitionTo(std::make_shared()); break; case MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE: // 171 context->authStateMachine->TransitionTo(std::make_shared()); @@ -409,7 +409,7 @@ int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr std::string encryptMsg; nlohmann::json jsonData; jsonData[DM_TAG_ON_TRANSMIT_DATA] = context->transmitData; - int32_t ret = cryptoMgr_->EncryptMessage(SafeDump(jsonData), encryptMsg); // 临时SK加密 + int32_t ret = cryptoMgr_->EncryptMessage(SafetyDump(jsonData), encryptMsg); // 临时SK加密 if (ret != DM_OK) { LOGE("DmAuthMessageProcessor::CreateSyncMessage encrypt failed"); return ret; diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index d56dce0d0..8d9f575f2 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -28,39 +28,50 @@ namespace DistributedHardware { DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) { - stateTransitionTable_ = { // 此处省略下一状态为AuthXXXFinishState的迁移情况 - {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SRC_START_STATE, DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, + stateTransitionTable_ = { + // 此处省略下一状态为AuthXXXFinishState的迁移情况 + {DmAuthStateType::AUTH_IDLE_STATE, + {DmAuthStateType::AUTH_SRC_START_STATE, DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, // Source端 状态迁移表 {DmAuthStateType::AUTH_SRC_START_STATE, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE}}, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE}}, - {DmAuthStateType::AUTH_SRC_CONFIRM_STATE, {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, - DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, // to check - {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, {DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, - DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE}}, - {DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, - DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE}}, - {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, - DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE}}, + {DmAuthStateType::AUTH_SRC_CONFIRM_STATE, + {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, + DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, // to check + {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, + {DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE}}, + {DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, + {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE}}, + {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE}}, {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, - {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, - {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE}}, - {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE}}, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE}}, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE, + {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, {}}, // Sink端 状态迁移表 //{DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, //{DmAuthStateType::AUTH_SINK_START_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, - {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, - DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, // to check + {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE, + {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, + DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, // to check {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, {DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE}}, - {DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, {DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, - DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE}}, - {DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, - DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE}}, + {DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, + {DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE}}, + {DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, + {DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE}}, {DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE}}, - {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, - {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, - {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_DONE_STATE}}, - {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE}}, + {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, + {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, + {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, + {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, + {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE, + {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_DONE_STATE}}, + {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_DONE_STATE, + {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, {DmAuthStateType::AUTH_SINK_FINISH_STATE}}, {DmAuthStateType::AUTH_SINK_FINISH_STATE, {}}, }; -- Gitee From 07f56a46aad395fe647b826106f3b38c207ba133 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 6 Mar 2025 21:27:52 +0800 Subject: [PATCH 143/382] tmp --- .../include/authentication_v2/auth_manager.h | 57 ++++++++++++------- 1 file changed, 36 insertions(+), 21 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 00abe1737..52f6de44d 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -63,14 +63,14 @@ public: std::shared_ptr listener, std::shared_ptr hiChainAuthConnector); virtual ~AuthManager() = default; - void SetAuthContext(std::shared_ptr context); - - std::shared_ptr GetAuthContext(); - - // 各类事件触发的函数实现(虚函数) - int32_t GetPinCode(std::string &pkgName, int32_t &code) override; - int32_t GetPinCode(int32_t &code) override; + // 对外API 实现 begin + 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 &pkgName, const PeerTargetId &targetId, const std::map &bindParam); /** @@ -78,12 +78,6 @@ public: * @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 GeneratePincode(); /** * @tc.name: AuthManager::ImportAuthCode @@ -126,7 +120,16 @@ public: void HandleDeviceNotTrust(const std::string &udid); int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); int32_t RegisterAuthenticationType(int32_t authenticationType); + // 对外API 实现 end + // IDmDeviceAuthCallback implement begin + int32_t GetPinCode(std::string &pkgName, int32_t &code) override; + int32_t GetPinCode(int32_t &code) override; + // IDmDeviceAuthCallback implement end + + // AuthManager 内部使用的接口 begin + void SetAuthContext(std::shared_ptr context); + std::shared_ptr GetAuthContext(); static bool IsHmlSessionType(std::string sessionType); protected: // 上下文(需在该层级进行创建) @@ -158,20 +161,26 @@ public: std::shared_ptr listener, std::shared_ptr hiChainAuthConnector); virtual ~AuthSrcManager() override = default; - // 各类事件触发的函数实现(继承) + + // 对外API 实现 begin int32_t OnUserOperation(int32_t action, const std::string ¶ms) override; + // 对外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; + void GetRemoteDeviceId(std::string &deviceId) 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; - void GetRemoteDeviceId(std::string &deviceId) override; -private: - + // ISoftbusSessionCallback implement end }; class AuthSinkManager : public AuthManager { @@ -180,20 +189,26 @@ public: std::shared_ptr listener, std::shared_ptr hiChainAuthConnector); virtual ~AuthSinkManager() override = default; - // 各类事件触发的函数实现(继承) + + // 对外API 实现 begin int32_t OnUserOperation(int32_t action, const std::string ¶ms) override; + // 对外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; + void GetRemoteDeviceId(std::string &deviceId) 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; - void GetRemoteDeviceId(std::string &deviceId) override; -private: - + // ISoftbusSessionCallback implement end }; } // namespace DistributedHardware -- Gitee From 62d451e700f3bf275ff4b38eef5a99646f5b9052 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Thu, 6 Mar 2025 22:14:02 +0800 Subject: [PATCH 144/382] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E8=B7=B3=E8=BD=AC=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/dm_auth_state.h | 9 ++++--- .../dm_auth_message_processor.cpp | 1 + .../dm_auth_state_machine.cpp | 24 +++++++++++-------- 3 files changed, 19 insertions(+), 15 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 07d8bcff7..e78f71412 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -46,7 +46,7 @@ enum class DmAuthStateType { AUTH_SRC_CREDENTIAL_EXCHANGE_STATE = 7, // 触发Onfinish回调事件,发送140报文 AUTH_SRC_CREDENTIAL_AUTH_START_STATE = 8, // 收到150加密报文,发送160报文 AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE = 9, // 收到170凭据认证报文,发送161报文 - AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE = 10, // 收到171凭据认证报文 + AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE = 10, // 收到171凭据认证报文,回复161报文或者181报文 AUTH_SRC_DATA_SYNC_STATE = 11, // 触发Onfinish回调事件,发送180报文 AUTH_SRC_FINISH_STATE = 12, // 收到190报文,发送200报文 @@ -59,10 +59,9 @@ enum class DmAuthStateType { AUTH_SINK_PIN_AUTH_DONE_STATE = 55, // 触发Onfinish回调事件 AUTH_SINK_CREDENTIAL_EXCHANGE_STATE = 56, // 收到140加密报文,发送150报文 AUTH_SINK_CREDENTIAL_AUTH_START_STATE = 57, // 收到160凭证认证报文,发送170报文 - AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE = 58, // 收到161凭据协商报文 - AUTH_SINK_CREDENTIAL_AUTH_DONE_STATE = 59, // 触发Onfinish回调事件 - AUTH_SINK_DATA_SYNC_STATE = 60, // 收到180同步报文,发送190报文 - AUTH_SINK_FINISH_STATE = 61, // 收到200结束报文 + AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE = 58, // 收到161凭据协商报文,回复171报文 + AUTH_SINK_DATA_SYNC_STATE = 59, // 收到180同步报文,发送190报文 + AUTH_SINK_FINISH_STATE = 60, // 收到200结束报文 }; // 凭据添加方式 diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 0ab8d5674..d0c645163 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -404,6 +404,7 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh } // 内部各类报文的实现 +// 161 170 171消息构造 int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr &context, nlohmann::json &jsonObject) { std::string encryptMsg; diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 8d9f575f2..6457a22ac 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -45,12 +45,15 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE}}, {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, - {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, // 收到150的处理状态,发送160 {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, - {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE, + + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE, // 收到170的处理状态,后发送161 {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE}}, - {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE, - {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, + + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE, // 收到171的处理状态 发送160/180 + {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, + {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, {}}, // Sink端 状态迁移表 //{DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, @@ -66,13 +69,14 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) {DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE}}, {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, - {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, + + {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, // 收到160的处理状态,回复170 {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, - {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE, - {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_DONE_STATE}}, - {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_DONE_STATE, - {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, - {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, {DmAuthStateType::AUTH_SINK_FINISH_STATE}}, + + {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE, // 收到161的处理状态,回复171 + {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE}}, + + {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, {DmAuthStateType::AUTH_SINK_FINISH_STATE}}, // 收到180,回复190 {DmAuthStateType::AUTH_SINK_FINISH_STATE, {}}, }; exceptionEvent_= { -- Gitee From 52ea55dfa55f9d73165ffcbd92e175ad5e64b65f Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 6 Mar 2025 22:14:41 +0800 Subject: [PATCH 145/382] tmp --- .../include/authentication_v2/auth_manager.h | 9 +++++++-- .../src/authentication_v2/auth_manager.cpp | 13 +++++++++++-- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 52f6de44d..fa75dc094 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -66,6 +66,7 @@ public: // 对外API 实现 begin virtual int32_t OnUserOperation(int32_t action, const std::string ¶ms) = 0; + void OnScreenLocked(); /** * @tc.name: AuthManager::GeneratePincode * @tc.desc: Generate Pincode of the DeviceManager Authenticate Manager @@ -73,6 +74,9 @@ public: */ int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, const std::map &bindParam); + // 停止绑定 TODO 如果多会话实例隔离后,pkgName 是不是不需要了? 后续其他API同理? + int32_t StopAuthenticateDevice(const std::string &pkgName); + /** * @tc.name: AuthManager::OnUserOperation * @tc.desc: User Operation of the DeviceManager Authenticate Manager @@ -84,6 +88,7 @@ public: * @tc.desc: Import auth code * @tc.type: FUNC */ + // todo 新协议是通过DP去查询的? int32_t ImportAuthCode(const std::string &pkgName, const std::string &authCode); /** * @tc.name: AuthManager::RegisterUiStateCallback @@ -114,11 +119,11 @@ public: */ int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel, const std::string &extra); - int32_t StopAuthenticateDevice(const std::string &pkgName); - void OnScreenLocked(); void HandleDeviceNotTrust(const std::string &udid); int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); + + // todo 是指authResult,新协议是110报文sink端返回的? int32_t RegisterAuthenticationType(int32_t authenticationType); // 对外API 实现 end diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 0b0de6499..4aba0087e 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -250,15 +250,24 @@ int32_t AuthManager::UnBindDevice(const std::string &pkgName, const std::string } int32_t AuthManager::StopAuthenticateDevice(const std::string &pkgName) { - // todo + // todo pkgName 是否还需要 LOGI("AuthManager::StopAuthenticateDevice start"); - return ERR_DM_FAILED; + + context_->reason = STOP_BIND; + if (context_->direction == DM_AUTH_SOURCE) { + this->TransitionTo(std::make_shared()); + } else { + this->TransitionTo(std::make_shared()); + } + return DM_OK; } void AuthManager::OnScreenLocked() { // todo LOGI("AuthManager::OnScreenLocked start"); + context_->reason = ERR_DM_BIND_USER_CANCEL; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); } void AuthManager::HandleDeviceNotTrust(const std::string &udid) { -- Gitee From f92cdbbe41749b2d0419c4d6f84ad56123b17248 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 6 Mar 2025 22:16:28 +0800 Subject: [PATCH 146/382] tmp --- .../include/authentication_v2/auth_manager.h | 4 ++-- .../implementation/src/authentication_v2/auth_manager.cpp | 7 +------ 2 files changed, 3 insertions(+), 8 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index fa75dc094..4cce41056 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -130,6 +130,7 @@ public: // IDmDeviceAuthCallback implement begin int32_t GetPinCode(std::string &pkgName, int32_t &code) override; int32_t GetPinCode(int32_t &code) override; + void GetRemoteDeviceId(std::string &deviceId) override; // IDmDeviceAuthCallback implement end // AuthManager 内部使用的接口 begin @@ -176,7 +177,7 @@ public: 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; - void GetRemoteDeviceId(std::string &deviceId) override; + // IDmDeviceAuthCallback implement end // ISoftbusSessionCallback implement begin @@ -204,7 +205,6 @@ public: 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; - void GetRemoteDeviceId(std::string &deviceId) override; // IDmDeviceAuthCallback implement end // ISoftbusSessionCallback implement begin diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 4aba0087e..222a5bd73 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -764,7 +764,7 @@ void AuthSinkManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string me return; } -void AuthSinkManager::GetRemoteDeviceId(std::string &deviceId) +void AuthManager::GetRemoteDeviceId(std::string &deviceId) { deviceId = (context_->direction == DM_AUTH_SOURCE) ? context_->accessee.deviceId : context_->accesser.deviceId; return; @@ -893,11 +893,6 @@ void AuthSrcManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string mes return; } -void AuthSrcManager::GetRemoteDeviceId(std::string &deviceId) -{ - deviceId = (context_->direction == DM_AUTH_SOURCE) ? context_->accessee.deviceId : context_->accesser.deviceId; - return; -} int32_t AuthSrcManager::OnUserOperation(int32_t action, const std::string ¶ms) { -- Gitee From 84ae4be9377d7361bfec5a9beeef84f1213cce16 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 6 Mar 2025 22:19:09 +0800 Subject: [PATCH 147/382] tmp --- .../implementation/src/authentication_v2/auth_manager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 222a5bd73..7204f0885 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -255,9 +255,9 @@ int32_t AuthManager::StopAuthenticateDevice(const std::string &pkgName) context_->reason = STOP_BIND; if (context_->direction == DM_AUTH_SOURCE) { - this->TransitionTo(std::make_shared()); + context_->authStateMachine->TransitionTo(std::make_shared()); } else { - this->TransitionTo(std::make_shared()); + context_->authStateMachine->TransitionTo(std::make_shared()); } return DM_OK; } -- Gitee From 1cbae8f127d317b7d21c2c18fdc30e1195e22065 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 6 Mar 2025 22:39:57 +0800 Subject: [PATCH 148/382] tmp --- .../implementation/include/authentication_v2/auth_manager.h | 3 +++ .../implementation/src/authentication_v2/auth_manager.cpp | 5 +++++ 2 files changed, 8 insertions(+) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 4cce41056..d386a45a0 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -128,6 +128,7 @@ public: // 对外API 实现 end // IDmDeviceAuthCallback implement begin + // todo IDmDeviceAuthCallback新加了这个 是否可以? int32_t GetPinCode(std::string &pkgName, int32_t &code) override; int32_t GetPinCode(int32_t &code) override; void GetRemoteDeviceId(std::string &deviceId) override; @@ -184,6 +185,8 @@ public: 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; + + // 下面2个接口还需要实现吗? bool GetIsCryptoSupport() override; void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) override; // ISoftbusSessionCallback implement end diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 7204f0885..f6819805b 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -640,6 +640,11 @@ int32_t AuthManager::AuthenticateDevice(const std::string &pkgName, int32_t auth int32_t AuthManager::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, const std::map &bindParam) { + LOGI("AuthManager::BindTarget start. pkgName: %{public}s", pkgName); + for (auto iter = bindParam.begin(); iter != bindParam.end(); iter++) { + LOGI("AuthManager::BindTarget para: %{public}s : %{public}s ", iter->first, iter->second); + } + struct RadarInfo info = { .funcName = "AuthenticateDevice", .stageRes = static_cast(StageRes::STAGE_SUCC), -- Gitee From c9202684aae280cba63715b7ef8f46e2da3c6d3b Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 6 Mar 2025 22:41:52 +0800 Subject: [PATCH 149/382] tmp --- .../implementation/src/authentication_v2/auth_manager.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index f6819805b..68168ab7f 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -640,9 +640,9 @@ int32_t AuthManager::AuthenticateDevice(const std::string &pkgName, int32_t auth int32_t AuthManager::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, const std::map &bindParam) { - LOGI("AuthManager::BindTarget start. pkgName: %{public}s", pkgName); + LOGI("AuthManager::BindTarget start. pkgName: %{public}s", pkgName.c_str()); for (auto iter = bindParam.begin(); iter != bindParam.end(); iter++) { - LOGI("AuthManager::BindTarget para: %{public}s : %{public}s ", iter->first, iter->second); + LOGI("AuthManager::BindTarget para: %{public}s : %{public}s ", iter->first.c_str(), iter->second.c_str()); } struct RadarInfo info = { -- Gitee From 9fd47f9495f0d9f77a72567de6e8a4f4dd9ad228 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 7 Mar 2025 15:08:10 +0800 Subject: [PATCH 150/382] onrequest to authmanager --- .../include/authentication/dm_auth_manager.h | 1 + .../include/authentication_v2/auth_manager.h | 19 +++++---- .../hichain/hichain_auth_connector.h | 3 +- .../hichain/hichain_connector_callback.h | 15 +++---- .../src/authentication/dm_auth_manager.cpp | 21 ++++++++++ .../src/authentication_v2/auth_manager.cpp | 41 +++++++++++++++---- .../auth_stages/auth_pin_auth.cpp | 2 +- .../hichain/hichain_auth_connector.cpp | 30 +++----------- 8 files changed, 82 insertions(+), 50 deletions(-) diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index aef138cdf..01347c002 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -536,6 +536,7 @@ public: void AuthDeviceError(int64_t requestId, int32_t errorCode); void GetRemoteDeviceId(std::string &deviceId); void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen); + char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) override; void OnAuthDeviceDataReceived(const int32_t sessionId, const std::string message); void OnScreenLocked(); void HandleDeviceNotTrust(const std::string &udid); diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index d386a45a0..442a92c42 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -127,21 +127,24 @@ public: int32_t RegisterAuthenticationType(int32_t authenticationType); // 对外API 实现 end - // IDmDeviceAuthCallback implement begin - // todo IDmDeviceAuthCallback新加了这个 是否可以? - int32_t GetPinCode(std::string &pkgName, int32_t &code) override; - int32_t GetPinCode(int32_t &code) override; - void GetRemoteDeviceId(std::string &deviceId) override; - // IDmDeviceAuthCallback implement end // AuthManager 内部使用的接口 begin void SetAuthContext(std::shared_ptr context); std::shared_ptr GetAuthContext(); static bool IsHmlSessionType(std::string sessionType); + + // IDmDeviceAuthCallback 转内部接口 protected: // 上下文(需在该层级进行创建) std::shared_ptr context_; std::shared_ptr authUiStateMgr_; + + + // pkgName是#define DM_APP_ID "ohos.distributedhardware.devicemanager" + // int32_t GetPinCode(std::string &pkgName, int32_t &code); + int32_t GetPinCode(int32_t &code); + void GetRemoteDeviceId(std::string &deviceId); + // IDmDeviceAuthCallback 转内部接口 private: int32_t ParseAuthType(const std::map &bindParam, int32_t &authType); int32_t ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType); @@ -178,7 +181,7 @@ public: 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 @@ -188,6 +191,7 @@ public: // 下面2个接口还需要实现吗? bool GetIsCryptoSupport() override; + // 与 OnDataReceived 合并实现 void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) override; // ISoftbusSessionCallback implement end }; @@ -208,6 +212,7 @@ public: 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 diff --git a/services/implementation/include/dependency/hichain/hichain_auth_connector.h b/services/implementation/include/dependency/hichain/hichain_auth_connector.h index a70057831..306d000c6 100644 --- a/services/implementation/include/dependency/hichain/hichain_auth_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_auth_connector.h @@ -74,8 +74,7 @@ public: int32_t AuthCredential(int32_t osAccountId, int64_t authReqId, const std::string &credId, const std::string &pinCode); // pin码 认证 - int32_t AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, const std::string &pkgName, - int32_t pinCode); + int32_t AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, int32_t pinCode); private: void FreeJsonString(char *jsonStr); diff --git a/services/implementation/include/dependency/hichain/hichain_connector_callback.h b/services/implementation/include/dependency/hichain/hichain_connector_callback.h index 92f11240b..caa7c68ac 100644 --- a/services/implementation/include/dependency/hichain/hichain_connector_callback.h +++ b/services/implementation/include/dependency/hichain/hichain_connector_callback.h @@ -37,13 +37,14 @@ public: virtual void AuthDeviceFinish(int64_t requestId) = 0; virtual void AuthDeviceError(int64_t requestId, int32_t errorCode) = 0; virtual void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) = 0; - virtual int32_t GetPinCode(std::string &pkgName, int32_t &code) - { - pkgName = ""; - return GetPinCode(code); - }; - virtual int32_t GetPinCode(int32_t &code) = 0; - virtual void GetRemoteDeviceId(std::string &deviceId) = 0; + // virtual int32_t GetPinCode(std::string &pkgName, int32_t &code) + // { + // pkgName = ""; + // return GetPinCode(code); + // }; + // virtual int32_t GetPinCode(int32_t &code) = 0; + // virtual void GetRemoteDeviceId(std::string &deviceId) = 0; + char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 3c7063a58..45f03d3be 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -2488,6 +2488,27 @@ void DmAuthManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessi } } +char *DmAuthManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) +{ + LOGI("DmAuthManager::AuthDeviceRequest start."); + (void)requestId; + (void)reqParams; + nlohmann::json jsonObj; + int32_t pinCode = INVALID_PINCODE; + if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE) { + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; + } else { + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); + } + std::string deviceId = ""; + GetRemoteDeviceId(deviceId); + jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; + std::string jsonStr = SafetyDump(jsonObj); + char *buffer = strdup(jsonStr.c_str()); + return buffer; +} + void DmAuthManager::GetRemoteDeviceId(std::string &deviceId) { LOGI("GetRemoteDeviceId start."); diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 68168ab7f..0d35d955f 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -309,6 +309,12 @@ void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sess LOGI("AuthSrcManager::AuthDeviceSessionKey leave."); } +char *AuthSrcManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) +{ + LOGI("AuthSrcManager::AuthDeviceRequest start"); + +} + int32_t AuthManager::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType) { int32_t index = 0; @@ -1071,23 +1077,42 @@ void AuthSinkManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *ses context_->authStateMachine->NotifyEventFinish(ON_SESSION_KEY_RETURNED); } -int32_t AuthManager::GetPinCode(std::string &pkgName, int32_t &code) +char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) +{ + LOGI("AuthSrcManager::AuthDeviceRequest start"); + (void)requestId; + (void)reqParams; + nlohmann::json jsonObj; + + DmAuthStateType curState = context_->authStateMachine->GetCurState(); + if (curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE) { + int32_t pinCode = INVALID_PINCODE; + if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE) { + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; + } else { + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); + jsonObj[FIELD_SERVICE_PKG_NAME] = std::string(DM_PKG_NAME); + } + } + std::string deviceId = ""; + dmDeviceAuthCallback_->GetRemoteDeviceId(deviceId); + jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; + std::string jsonStr = SafetyDump(jsonObj); + char *buffer = strdup(jsonStr.c_str()); + return buffer; +} + +int32_t AuthManager::GetPinCode(int32_t &code) { if (context_ == nullptr) { LOGE("AuthManager failed to GetPinCode because context_ is nullptr"); return ERR_DM_FAILED; } LOGI("GetPinCode called."); - pkgName = context_->pkgName; code = context_->pinCode; return DM_OK; } -int32_t AuthManager::GetPinCode(int32_t &code) -{ - std::string pkgName; - return GetPinCode(pkgName, code); -} - } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 5e700b8da..b7ac0a8c5 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -187,7 +187,7 @@ int32_t AuthSrcPinAuthStartState::AuthDevice(std::shared_ptr cont { int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); auto ret = context->hiChainAuthConnector->AuthCredentialPinCode(osAccountId, context->requestId, - context->pkgName, context->pinCode); + context->pinCode); if (ret != DM_OK) { LOGE("AuthSrcPinAuthStartState::AuthDevice failed."); return ret; diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 8522c069e..098728c97 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -239,12 +239,11 @@ int32_t HiChainAuthConnector::AuthCredential(int32_t osAccountId, int64_t authRe } // pin码认证 -int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, const std::string &pkgName, - int32_t pinCode) +int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, int32_t pinCode) { LOGI("HiChainAuthConnector::AuthCredential start."); - if (pkgName.empty() || pinCode == INVALID_PINCODE) { - LOGE("HiChainAuthConnector::AuthCredentialPinCode failed, pkgName or pinCode is empty."); + if (pinCode == INVALID_PINCODE) { + LOGE("HiChainAuthConnector::AuthCredentialPinCode failed, pinCode is empty."); return ERR_DM_FAILED; } @@ -252,7 +251,7 @@ int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t nlohmann::json jsonAuthParam; jsonAuthParam[FIELD_PIN_CODE] = std::to_string(pinCode); - jsonAuthParam[FIELD_SERVICE_PKG_NAME] = pkgName; + jsonAuthParam[FIELD_SERVICE_PKG_NAME] = std::string(DM_PKG_NAME); std::string authParams = SafetyDump(jsonAuthParam); @@ -280,30 +279,11 @@ bool HiChainAuthConnector::onTransmit(int64_t requestId, const uint8_t *data, ui char *HiChainAuthConnector::onRequest(int64_t requestId, int operationCode, const char *reqParams) { LOGI("HiChainAuthConnector::onRequest start."); - (void)requestId; - (void)reqParams; if (dmDeviceAuthCallback_ == nullptr) { LOGE("HiChainAuthConnector::onRequest dmDeviceAuthCallback_ is nullptr."); return nullptr; } - nlohmann::json jsonObj; - int32_t pinCode = INVALID_PINCODE; - std::string pkgName; - if (dmDeviceAuthCallback_->GetPinCode(pkgName, pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE) { - jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; - } else { - jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; - jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); - if (!pkgName.empty()) { - jsonObj[FIELD_SERVICE_PKG_NAME] = pkgName; - } - } - std::string deviceId = ""; - dmDeviceAuthCallback_->GetRemoteDeviceId(deviceId); - jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; - std::string jsonStr = SafetyDump(jsonObj); - char *buffer = strdup(jsonStr.c_str()); - return buffer; + return dmDeviceAuthCallback_->AuthDeviceRequest(requestId, operationCode, reqParams); } void HiChainAuthConnector::onFinish(int64_t requestId, int operationCode, const char *returnData) -- Gitee From 52e5bedc3f76f0bec531fbff52a70cd39700dce6 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 7 Mar 2025 15:28:37 +0800 Subject: [PATCH 151/382] tmp --- .../implementation/include/authentication/dm_auth_manager.h | 2 +- .../include/dependency/hichain/hichain_connector_callback.h | 2 +- .../implementation/src/authentication_v2/auth_manager.cpp | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 01347c002..5a8f79b17 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -536,7 +536,7 @@ public: void AuthDeviceError(int64_t requestId, int32_t errorCode); void GetRemoteDeviceId(std::string &deviceId); void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen); - char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) override; + char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams); void OnAuthDeviceDataReceived(const int32_t sessionId, const std::string message); void OnScreenLocked(); void HandleDeviceNotTrust(const std::string &udid); diff --git a/services/implementation/include/dependency/hichain/hichain_connector_callback.h b/services/implementation/include/dependency/hichain/hichain_connector_callback.h index caa7c68ac..4242a0092 100644 --- a/services/implementation/include/dependency/hichain/hichain_connector_callback.h +++ b/services/implementation/include/dependency/hichain/hichain_connector_callback.h @@ -44,7 +44,7 @@ public: // }; // virtual int32_t GetPinCode(int32_t &code) = 0; // virtual void GetRemoteDeviceId(std::string &deviceId) = 0; - char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams); + virtual char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 0d35d955f..81fd44751 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -312,7 +312,7 @@ void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sess char *AuthSrcManager::AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) { LOGI("AuthSrcManager::AuthDeviceRequest start"); - + return nullptr; } int32_t AuthManager::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType) @@ -1096,7 +1096,7 @@ char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, c } } std::string deviceId = ""; - dmDeviceAuthCallback_->GetRemoteDeviceId(deviceId); + GetRemoteDeviceId(deviceId); jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; std::string jsonStr = SafetyDump(jsonObj); char *buffer = strdup(jsonStr.c_str()); -- Gitee From a18ed6b1e9ad8ce9dc2d67dfbb81d0cfb6b50c73 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 7 Mar 2025 15:39:37 +0800 Subject: [PATCH 152/382] tmp --- .../include/dependency/hichain/hichain_connector_callback.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/include/dependency/hichain/hichain_connector_callback.h b/services/implementation/include/dependency/hichain/hichain_connector_callback.h index 4242a0092..26ab01576 100644 --- a/services/implementation/include/dependency/hichain/hichain_connector_callback.h +++ b/services/implementation/include/dependency/hichain/hichain_connector_callback.h @@ -44,7 +44,7 @@ public: // }; // virtual int32_t GetPinCode(int32_t &code) = 0; // virtual void GetRemoteDeviceId(std::string &deviceId) = 0; - virtual char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams); + virtual char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) = 0; }; } // namespace DistributedHardware } // namespace OHOS -- Gitee From 8349b32843dc7efc39d9468c1ee398f34619a23e Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Fri, 7 Mar 2025 16:02:30 +0800 Subject: [PATCH 153/382] =?UTF-8?q?=E4=BF=AE=E5=A4=8Dhichain=20onrequest?= =?UTF-8?q?=E7=BC=BA=E5=A4=B1?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/dm_auth_context.h | 3 +-- .../src/authentication_v2/auth_manager.cpp | 8 +++++++- .../auth_stages/auth_credential.cpp | 12 ++++++------ .../authentication_v2/dm_auth_message_processor.cpp | 2 +- 4 files changed, 15 insertions(+), 10 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 4d739bedd..34dec2588 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -156,7 +156,7 @@ struct DmAuthContext { int32_t hmlActionId = 0; bool normalFinishAuth; // 标识认证过程是否正常结束 bool authenticating; // 标识正在认证中 - bool isAppCredentailVerified = false; // 标识用户凭据是否认证 + bool isAppCredentialVerified = false; // 应用凭据是否认证 bool hmlEnable160M = false; std::string pkgName; // 业务传入的标识,业务自定义,有被仿冒的风险 std::string pkgLabel; @@ -169,7 +169,6 @@ struct DmAuthContext { DmAuthDirection direction; // 标识认证方向 ProcessInfo processInfo; // 进程信息 DmPeerTarget peerTarget; // 对端目标的信息 - bool isAppCredentialVerified; // 应用级凭据是否认证 DmAccess accesser; DmAccess accessee; DmAccess encryAccesser; // 密文阶段accesser diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 81fd44751..801b17ae3 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -1085,7 +1085,7 @@ char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, c nlohmann::json jsonObj; DmAuthStateType curState = context_->authStateMachine->GetCurState(); - if (curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE) { + if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE) { int32_t pinCode = INVALID_PINCODE; if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE) { jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; @@ -1094,6 +1094,12 @@ char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, c jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); jsonObj[FIELD_SERVICE_PKG_NAME] = std::string(DM_PKG_NAME); } + } else if (curState == DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE) { + if (context_->isOnline) { // 非首次认证 + jsonObj[FIELD_CRED_ID] = context_->accessee.appCredentialId; + } else { // 首次认证 + jsonObj[FIELD_CRED_ID] = context_->accessee.userCredentialId; + } } std::string deviceId = ""; GetRemoteDeviceId(deviceId); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 8f64f83ca..4b41bb464 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -100,7 +100,7 @@ DmAuthStateType AuthSrcCredentialAuthDoneState::GetStateType() int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr context) { // 解密并透传transmitData - // 171报文在首次认证情况下会发生两次,先进行应用凭据认证,后进行用户凭据认证;非首次认证仅进行用户凭据认证 + // 171报文在首次认证情况下会发生两次,先进行应用凭据认证,后进行用户凭据认证;非首次认证仅进行应用凭据认证 // 最后一次认证结束后会收到ON_FINISH int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_SESSION_KEY_RETURNED); if (ret != DM_OK) { @@ -120,8 +120,8 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co return ret; } // 首次认证 且 应用凭据流程 - if (context->isOnline == false && context->isAppCredentailVerified == false) { - context->isAppCredentailVerified = true; + if (context->isOnline == false && context->isAppCredentialVerified == false) { + context->isAppCredentialVerified = true; // 保存到DP 获取应用凭据ID 并保存 context->appSkTimeStamp = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) @@ -186,7 +186,7 @@ DmAuthStateType AuthSinkCredentialAuthNegotiateState::GetStateType() } // 收到161凭据协商报文,并回复171报文 -// 通过isAppCredentailVerified关键词区分首次认证、非首次认证 +// 通过isAppCredentialVerified关键词区分首次认证、非首次认证 int32_t AuthSinkCredentialAuthNegotiateState::Action(std::shared_ptr context) { // 解密并透传transmitData @@ -217,13 +217,13 @@ int32_t AuthSinkCredentialAuthNegotiateState::Action(std::shared_ptrisOnline == false && - context->isAppCredentailVerified == true) { // SINK首次认证场景,第二次收到161的流程 保存用户级永久SK到DP + context->isAppCredentialVerified == true) { // SINK首次认证场景,第二次收到161的流程 保存用户级永久SK到DP context->userSkTimeStamp = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) .count(); context->userSessionKeyId = skId; } else { // 应用级凭据认证流程 首次认证的第一次161处理 和 非首次认证的161处理 - context->isAppCredentailVerified = true; // 用于指示 首次认证的应用级凭据已认证 + context->isAppCredentialVerified = true; // 用于指示 首次认证的应用级凭据已认证 context->appSkTimeStamp = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) .count(); diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index d0c645163..2483ede86 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1141,7 +1141,7 @@ int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(nlohmann::json &jsonObject return ERR_DM_FAILED; } std::string jsonTag; - if (context->isOnline == false && context->isAppCredentailVerified == false) { // 首次认证的应用凭据 + if (context->isOnline == false && context->isAppCredentialVerified == false) { // 首次认证的应用凭据 jsonTag = DM_TAG_APP_CREDENTIAL_ID; context->accesser.appCredentialId = jsonDecrptObj[DM_TAG_APP_CREDENTIAL_ID].get(); } else if (context->isOnline == false) { // 首次认证的用户凭据 -- Gitee From e4c3b085c67d3e63f894d4fd75f458bd162f5e95 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Fri, 7 Mar 2025 16:25:56 +0800 Subject: [PATCH 154/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9credid=E8=AE=A4?= =?UTF-8?q?=E8=AF=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../implementation/src/authentication_v2/auth_manager.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 801b17ae3..45ce873e5 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -1092,15 +1092,17 @@ char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, c } else { jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; jsonObj[FIELD_PIN_CODE] = std::to_string(pinCode); - jsonObj[FIELD_SERVICE_PKG_NAME] = std::string(DM_PKG_NAME); } } else if (curState == DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE) { if (context_->isOnline) { // 非首次认证 + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; jsonObj[FIELD_CRED_ID] = context_->accessee.appCredentialId; } else { // 首次认证 + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; jsonObj[FIELD_CRED_ID] = context_->accessee.userCredentialId; } } + jsonObj[FIELD_SERVICE_PKG_NAME] = std::string(DM_PKG_NAME); std::string deviceId = ""; GetRemoteDeviceId(deviceId); jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; -- Gitee From 598b192bde2ff323375f4200cac53d3905062c84 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Fri, 7 Mar 2025 16:26:56 +0800 Subject: [PATCH 155/382] =?UTF-8?q?=E5=88=A0=E9=99=A4deviceid?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/implementation/src/authentication_v2/auth_manager.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 45ce873e5..9cf56d376 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -1103,9 +1103,6 @@ char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, c } } jsonObj[FIELD_SERVICE_PKG_NAME] = std::string(DM_PKG_NAME); - std::string deviceId = ""; - GetRemoteDeviceId(deviceId); - jsonObj[FIELD_PEER_CONN_DEVICE_ID] = deviceId; std::string jsonStr = SafetyDump(jsonObj); char *buffer = strdup(jsonStr.c_str()); return buffer; -- Gitee From f7b914eff6d0c2fc90ea7b8b87b75cedafc77d6f Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 7 Mar 2025 17:58:33 +0800 Subject: [PATCH 156/382] tmp --- .../include/authentication_v2/auth_manager.h | 3 +- .../authentication_v2/dm_auth_context.h | 22 +++++++----- .../src/authentication_v2/auth_manager.cpp | 36 ++++++++++++------- .../auth_stages/auth_confirm.cpp | 24 ++++++------- .../auth_stages/auth_pin_auth.cpp | 2 +- 5 files changed, 51 insertions(+), 36 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 442a92c42..43dd5b393 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -123,7 +123,6 @@ public: void HandleDeviceNotTrust(const std::string &udid); int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); - // todo 是指authResult,新协议是110报文sink端返回的? int32_t RegisterAuthenticationType(int32_t authenticationType); // 对外API 实现 end @@ -133,13 +132,13 @@ public: std::shared_ptr GetAuthContext(); static bool IsHmlSessionType(std::string sessionType); - // IDmDeviceAuthCallback 转内部接口 protected: // 上下文(需在该层级进行创建) std::shared_ptr context_; std::shared_ptr authUiStateMgr_; + // IDmDeviceAuthCallback 转内部接口 // pkgName是#define DM_APP_ID "ohos.distributedhardware.devicemanager" // int32_t GetPinCode(std::string &pkgName, int32_t &code); int32_t GetPinCode(int32_t &code); diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 34dec2588..44e64dee1 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -42,12 +42,16 @@ class DmAuthStateMachine; class DmAuthMessageProcessor; // PIN码认证类型 -typedef enum { - AUTH_TYPE_PIN_SHOW = 1, // 弹PIN码 - AUTH_TYPE_PIN_ULTRASONIC = 2, // 超声PIN码 - AUTH_TYPE_PIN_IMPORT = 3, // 导入PIN码 - AUTH_TYPE_IMPORT_AUTH_CODE = 5, // 导入认证码 todo del -} DmAuthType; +enum DmAuthType : int32_t { + AUTH_TYPE_CRE = 0, // 新协议未使用 + AUTH_TYPE_PIN, // 输入PIN码 + AUTH_TYPE_QR_CODE, // 新协议未使用 + AUTH_TYPE_NFC, // 新协议未使用 + AUTH_TYPE_NO_INTER_ACTION, // 新协议未使用 + AUTH_TYPE_IMPORT_AUTH_CODE, // 导入PIN码 + AUTH_TYPE_UNKNOW, // 新协议未使用 + AUTH_TYPE_PIN_ULTRASONIC, // 超声PIN码 +}; enum DmAuthDirection { DM_AUTH_SOURCE = 0, @@ -142,9 +146,11 @@ struct DmAuthContext { int64_t requestId; // hichain认证ID UiAction pinInputResult; // 输入PIN码结果 UiAction authResult; // 授权结果(使用0、1、6,即单次,取消和始终信任,enum UiAction) - DmAuthType authType{DmAuthType::AUTH_TYPE_PIN_SHOW}; // 认证方式,弹pin码、超声pin码、导入pin码 + DmAuthType authType{DmAuthType::AUTH_TYPE_PIN}; // 认证方式,弹pin码、超声pin码、导入pin码 int32_t authFailTimes{0}; // 认证失败次数,查过3次结束认证 - int32_t pinCode{INVALID_PINCODE}; // 保存业务导入的pin码 + int32_t pinCode{INVALID_PINCODE}; // 生成的PIN码 + std::string importAuthCode; // 保存业务导入的pin码 + std::string importPkgName; // 保存业务导入的pkgName int32_t connDelayCloseTime; // 链路延迟释放时间, 授权结束后不自动断链(有业务需要使用)保留字段 int32_t reason{DM_OK}; // 本端失败的原因 int32_t reply; // 对端回复的结果 引用common/include/dm_constants.h,有新的错误码可新增 diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 9cf56d376..516fa2291 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -153,10 +153,9 @@ AuthManager::AuthManager(std::shared_ptr softbusConnector, context_->hiChainAuthConnector = hiChainAuthConnector; context_->authUiStateMgr = std::make_shared(context_->listener); + context_->authenticationMap[AUTH_TYPE_PIN] = nullptr; context_->authenticationMap[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; - context_->authenticationMap[AUTH_TYPE_PIN_SHOW] = nullptr; context_->authenticationMap[AUTH_TYPE_PIN_ULTRASONIC] = nullptr; - context_->authenticationMap[AUTH_TYPE_PIN_IMPORT] = nullptr; context_->accesser.dmVersion = DM_VERSION_5_1_0; context_->accessee.dmVersion = DM_VERSION_5_1_0; @@ -236,9 +235,13 @@ int32_t AuthManager::UnAuthenticateDevice(const std::string &pkgName, const std: int32_t AuthManager::ImportAuthCode(const std::string &pkgName, const std::string &authCode) { - // todo - LOGI("AuthManager::ImportAuthCode start"); - return ERR_DM_FAILED; + if (authCode.empty() || pkgName.empty()) { + LOGE("ImportAuthCode failed, authCode or pkgName is empty"); + return ERR_DM_INPUT_PARA_INVALID; + } + context_->importAuthCode = authCode; + context_->importPkgName = pkgName; + return DM_OK; } int32_t AuthManager::UnBindDevice(const std::string &pkgName, const std::string &udid, @@ -250,7 +253,7 @@ int32_t AuthManager::UnBindDevice(const std::string &pkgName, const std::string } int32_t AuthManager::StopAuthenticateDevice(const std::string &pkgName) { - // todo pkgName 是否还需要 + (void)pkgName; LOGI("AuthManager::StopAuthenticateDevice start"); context_->reason = STOP_BIND; @@ -264,8 +267,11 @@ int32_t AuthManager::StopAuthenticateDevice(const std::string &pkgName) void AuthManager::OnScreenLocked() { - // todo LOGI("AuthManager::OnScreenLocked start"); + if (context_->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + LOGI("OnScreenLocked authtype is: %{public}d, no need stop bind.", context_->authType); + return; + } context_->reason = ERR_DM_BIND_USER_CANCEL; context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); } @@ -282,9 +288,13 @@ int32_t AuthManager::DeleteGroup(const std::string &pkgName, const std::string & } int32_t AuthManager::RegisterAuthenticationType(int32_t authenticationType) { - // todo - LOGI("AuthManager::RegisterAuthenticationType start"); - return ERR_DM_FAILED; + if (authenticationType != USER_OPERATION_TYPE_ALLOW_AUTH && + authenticationType != USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + LOGE("Invalid parameter."); + return ERR_DM_INPUT_PARA_INVALID; + } + context_->authResult = static_cast(authenticationType); + return DM_OK; } // 保存秘钥 @@ -588,7 +598,7 @@ void AuthManager::InitAuthState(const std::string &pkgName, int32_t authType, context_->authPtr = iter->second; } - if (authType > AUTH_TYPE_IMPORT_AUTH_CODE || authType < AUTH_TYPE_PIN_SHOW) { + if (authType > AUTH_TYPE_IMPORT_AUTH_CODE || authType < AUTH_TYPE_PIN) { LOGE("AuthManager::InitAuthState invalid authType"); return; } @@ -942,7 +952,7 @@ void AuthSrcManager::AuthDeviceError(int64_t requestId, int32_t errorCode) curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE || curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE) { LOGI("AuthSrcManager::AuthDeviceError Auth pin err."); - if (context_->authType == DmAuthType::AUTH_TYPE_PIN_SHOW) { + if (context_->authType == DmAuthType::AUTH_TYPE_PIN) { context_->authFailTimes++; } else if (!context_->fallBackToInputPin) { LOGI("AuthSrcManager::AuthDeviceError fallback to input pin."); @@ -973,7 +983,7 @@ void AuthSinkManager::AuthDeviceError(int64_t requestId, int32_t errorCode) if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE || curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE) { - if (context_->authType == DmAuthType::AUTH_TYPE_PIN_SHOW) { + if (context_->authType == DmAuthType::AUTH_TYPE_PIN) { context_->authFailTimes++; } else if (!context_->fallBackToInputPin) { LOGI("AuthSinkManager::AuthDeviceError fallback to input pin."); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index a7df74283..ae63e57d4 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -76,7 +76,7 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) // 有无可信关系的分享凭据 if (g_shareByPinAuthDeviceTypeSet.contains(static_cast(context->deviceType))) { // 走弹PIN - context->authType = DmAuthType::AUTH_TYPE_PIN_SHOW; + context->authType = DmAuthType::AUTH_TYPE_PIN; // send 100 } else { // 转凭据认证 @@ -84,7 +84,7 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) } // 有点对点可信 - if (context->authType == DmAuthType::AUTH_TYPE_PIN_IMPORT) { + if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { // 走PIN码导入 // send 100 } else { @@ -148,8 +148,8 @@ int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context if (ret != DM_OK) { LOGE("AuthSinkConfirmState::GetAuthType GetServiceInfoByTokenId err %{public}d", ret); // 获取不到走PIN认证方案 - if (context->authType != DmAuthType::AUTH_TYPE_PIN_SHOW) { - LOGE("AuthSinkConfirmState::GetAuthType AUTH_TYPE_PIN_SHOW not match"); + if (context->authType != DmAuthType::AUTH_TYPE_PIN) { + LOGE("AuthSinkConfirmState::GetAuthType AUTH_TYPE_PIN not match"); return STOP_BIND; } return DM_OK; @@ -178,8 +178,8 @@ int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context auto authBoxType = srvInfo.GetAuthBoxType(); int32_t pinExchangeType = srvInfo.GetPinExchangeType(); if (authBoxType == DistributedDeviceProfile::NUM_1) { // 三态框 - if (context->authType != DmAuthType::AUTH_TYPE_PIN_SHOW) { - LOGE("AuthSinkConfirmState::GetAuthType AUTH_TYPE_PIN_SHOW not match"); + if (context->authType != DmAuthType::AUTH_TYPE_PIN) { + LOGE("AuthSinkConfirmState::GetAuthType AUTH_TYPE_PIN not match"); return STOP_BIND; } return DM_OK; @@ -200,8 +200,8 @@ int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context } return DM_OK; } else if (pinExchangeType == DistributedDeviceProfile::NUM_3) { // 导入PIN - if (context->authType != DmAuthType::AUTH_TYPE_PIN_IMPORT) { - LOGE("AuthSinkConfirmState::GetAuthType AUTH_TYPE_PIN_IMPORT not match"); + if (context->authType != DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + LOGE("AuthSinkConfirmState::GetAuthType AUTH_TYPE_IMPORT_AUTH_CODE not match"); return STOP_BIND; } // 读取PIN码 @@ -241,8 +241,8 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) return ret; } - if (context->authType == DmAuthType::AUTH_TYPE_PIN_SHOW) { // 三态框 - LOGI("AuthSinkConfirmState::Action AUTH_TYPE_PIN_SHOW "); + if (context->authType == DmAuthType::AUTH_TYPE_PIN) { // 三态框 + LOGI("AuthSinkConfirmState::Action AUTH_TYPE_PIN "); // 拉起授权确认页面 if ((ret = ShowConfigDialog(context)) != DM_OK) { return ret; @@ -279,8 +279,8 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) // 发送110报文 context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); // 请求发送超声PIN码 - } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_IMPORT) { // 导入PIN - LOGI("AuthSinkConfirmState::Action AUTH_TYPE_PIN_IMPORT"); + } else if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { // 导入PIN + LOGI("AuthSinkConfirmState::Action AUTH_TYPE_IMPORT_AUTH_CODE"); // 发送110报文 context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index b7ac0a8c5..5fcaa04fc 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -148,7 +148,7 @@ int32_t AuthSrcPinAuthStartState::GetPinCode(std::shared_ptr cont { LOGI("AuthSrcPinAuthStartState::GetPinCode start"); if (context->authFailTimes == 0) { - if (context->authType == DmAuthType::AUTH_TYPE_PIN_SHOW || context->fallBackToInputPin) { + if (context->authType == DmAuthType::AUTH_TYPE_PIN || context->fallBackToInputPin) { // 拉起PIN码输入界面 auto ret = ShowStartAuthDialog(context); if (ret != DM_OK) { -- Gitee From 9586b5ce34ee87d8d98c3b4bd4bcf50c477c5a00 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 7 Mar 2025 18:01:27 +0800 Subject: [PATCH 157/382] tmp --- .../implementation/include/authentication_v2/dm_auth_context.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 44e64dee1..c85b41ba9 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -149,8 +149,6 @@ struct DmAuthContext { DmAuthType authType{DmAuthType::AUTH_TYPE_PIN}; // 认证方式,弹pin码、超声pin码、导入pin码 int32_t authFailTimes{0}; // 认证失败次数,查过3次结束认证 int32_t pinCode{INVALID_PINCODE}; // 生成的PIN码 - std::string importAuthCode; // 保存业务导入的pin码 - std::string importPkgName; // 保存业务导入的pkgName int32_t connDelayCloseTime; // 链路延迟释放时间, 授权结束后不自动断链(有业务需要使用)保留字段 int32_t reason{DM_OK}; // 本端失败的原因 int32_t reply; // 对端回复的结果 引用common/include/dm_constants.h,有新的错误码可新增 -- Gitee From 3f632cf0b4c24a044102df9dea2956c1406d19cf Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Sat, 8 Mar 2025 11:15:03 +0800 Subject: [PATCH 158/382] =?UTF-8?q?bugfix:sk=E6=9C=AA=E4=BF=9D=E5=AD=98?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../implementation/src/authentication_v2/auth_manager.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 9cf56d376..dd8e4b0e6 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -1097,7 +1097,10 @@ char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, c if (context_->isOnline) { // 非首次认证 jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; jsonObj[FIELD_CRED_ID] = context_->accessee.appCredentialId; - } else { // 首次认证 + } else if (!context_->isAppCredentialVerified) { // 首次认证 && 应用凭据认证 + jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; + jsonObj[FIELD_CRED_ID] = context_->accessee.appCredentialId; + } else { // 首次认证 && 用户凭据认证 jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; jsonObj[FIELD_CRED_ID] = context_->accessee.userCredentialId; } -- Gitee From e02ecb966be874d9c2619da97c9b780137652c78 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Sat, 8 Mar 2025 11:18:29 +0800 Subject: [PATCH 159/382] =?UTF-8?q?bugfix:=20=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 5 +++-- services/implementation/src/cryptomgr/crypto_mgr.cpp | 6 +++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 2483ede86..f4f2a822e 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -52,8 +52,9 @@ int32_t DmAuthMessageProcessor::SaveSessionKeyToDP(int32_t &skId) LOGE("DmAuthMessageProcessor::SaveSessionKey failed, cryptoMgr_ is nullptr."); return ERR_DM_FAILED; } - uint8_t* sessionKey = nullptr; - uint32_t skLen = cryptoMgr_->GetSessionKey(sessionKey); + uint32_t skLen = cryptoMgr_->GetSessionKey(nullptr); + uint8_t sessionKey[skLen]; + skLen = cryptoMgr_->GetSessionKey(sessionKey); return DeviceProfileConnector::GetInstance().PutSessionKey(sessionKey, skLen, skId); } diff --git a/services/implementation/src/cryptomgr/crypto_mgr.cpp b/services/implementation/src/cryptomgr/crypto_mgr.cpp index aca240d3a..ef81bbf92 100644 --- a/services/implementation/src/cryptomgr/crypto_mgr.cpp +++ b/services/implementation/src/cryptomgr/crypto_mgr.cpp @@ -305,6 +305,7 @@ int32_t CryptoMgr::SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyL std::lock_guard lock(sessionKeyMtx_); sessionKey_.key = (uint8_t*)calloc(keyLen, sizeof(uint8_t)); sessionKey_.keyLen = keyLen; + memcpy_s(sessionKey_.key, keyLen, sessionKey, keyLen); } return DM_OK; } @@ -312,7 +313,10 @@ int32_t CryptoMgr::SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyL uint32_t CryptoMgr::GetSessionKey(uint8_t *sessionKey) { std::lock_guard lock(sessionKeyMtx_); - sessionKey = sessionKey_.key; + if (sessionKey == nullptr) { // 用于获取密钥长度 外部进行内存申请 + return sessionKey_.keyLen; + } + memcpy_s(sessionKey, sessionKey_.keyLen, sessionKey_.key, sessionKey_.keyLen); return sessionKey_.keyLen; } -- Gitee From 21f2ae65ff791324a0c8364f2c2f9ae0fabfecac Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Sat, 8 Mar 2025 11:29:27 +0800 Subject: [PATCH 160/382] =?UTF-8?q?bugfix:=2058-57=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E8=B7=B3=E8=BD=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_state_machine.cpp | 21 ++++++++++--------- 1 file changed, 11 insertions(+), 10 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index e5af6b880..dbe12b547 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -37,7 +37,7 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE}}, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE, {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, - DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, // to check + DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, // to check {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, {DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE}}, {DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, @@ -45,13 +45,13 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE}}, {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, - {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, // 收到150的处理状态,发送160 + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, // 收到150的处理状态,发送160 {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, - {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE, // 收到170的处理状态,后发送161 + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE, // 收到170的处理状态,后发送161 {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE}}, - {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE, // 收到171的处理状态 发送160/180 + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE, // 收到171的处理状态 发送160/180 {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, {}}, @@ -60,7 +60,7 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) //{DmAuthStateType::AUTH_SINK_START_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, - DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, // to check + DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, // to check {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, {DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE}}, {DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, {DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE}}, @@ -70,13 +70,14 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, - {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, // 收到160的处理状态,回复170 + {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, // 收到160的处理状态,回复170 {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, - {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE, // 收到161的处理状态,回复171 - {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE}}, - - {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, {DmAuthStateType::AUTH_SINK_FINISH_STATE}}, // 收到180,回复190 + {DmAuthStateType:: + AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE, // 收到161的处理状态,回复171;发送171后收到160 回退到AUTH_SINK_CREDENTIAL_AUTH_START_STATE进行第二次凭据认证 + {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, + + {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, {DmAuthStateType::AUTH_SINK_FINISH_STATE}}, // 收到180,回复190 {DmAuthStateType::AUTH_SINK_FINISH_STATE, {}}, }; exceptionEvent_= { -- Gitee From 95845b157bd2e88b93aa2a78d3ec7fb8613a2f7f Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Sat, 8 Mar 2025 15:01:40 +0800 Subject: [PATCH 161/382] =?UTF-8?q?BUGFIX=EF=BC=9A171=E7=8A=B6=E6=80=81?= =?UTF-8?q?=E9=81=97=E6=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/dm_auth_state.h | 4 ++-- .../src/authentication_v2/auth_stages/auth_credential.cpp | 6 ++++++ 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index e78f71412..8c2ad990b 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -46,8 +46,8 @@ enum class DmAuthStateType { AUTH_SRC_CREDENTIAL_EXCHANGE_STATE = 7, // 触发Onfinish回调事件,发送140报文 AUTH_SRC_CREDENTIAL_AUTH_START_STATE = 8, // 收到150加密报文,发送160报文 AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE = 9, // 收到170凭据认证报文,发送161报文 - AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE = 10, // 收到171凭据认证报文,回复161报文或者181报文 - AUTH_SRC_DATA_SYNC_STATE = 11, // 触发Onfinish回调事件,发送180报文 + AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE = 10, // 收到171凭据认证报文,回复160报文或者180报文 + AUTH_SRC_DATA_SYNC_STATE = 11, // 触发Onfinish回调事件,发送180报文 todo 可以删除 AUTH_SRC_FINISH_STATE = 12, // 收到190报文,发送200报文 // sink端的状态 diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 4b41bb464..854e55044 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -136,6 +136,12 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co LOGE("AuthSrcCredentialAuthDoneState::Action Hichain auth credentail failed"); return ret; } + + // 等待onTransmit事件 + if (context->authStateMachine->WaitExpectEvent(ON_TRANSMIT) != ON_TRANSMIT) { + LOGE("AuthSrcCredentialAuthDoneState::Action failed, ON_TRANSMIT event not arrived."); + return ERR_DM_FAILED; + } } else if (context->isOnline == false) { // 首次认证 且 用户凭据流程 // 保存到DP 获取用户凭据ID 并保存 -- Gitee From 638f1c1ee732320a3bddded2ea5adcecd988e9bb Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Sat, 8 Mar 2025 15:16:31 +0800 Subject: [PATCH 162/382] =?UTF-8?q?BUGFIX:=E9=A6=96=E6=AC=A1=E8=AE=A4?= =?UTF-8?q?=E8=AF=81=E6=97=A0ACL?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_acl.cpp | 6 ++---- .../src/authentication_v2/dm_auth_message_processor.cpp | 3 +-- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index c71adcb91..a40260434 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -65,8 +65,7 @@ int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) } } if (sinkAclList.empty()) { - LOGE("get acl failed"); - return ERR_DM_FAILED; + LOGI("AuthSinkDataSyncState::Action acl is empty"); // 首次认证 无acl同步 } // 比较双端的acl for (auto &sinkAcl : sinkAclList) { @@ -126,8 +125,7 @@ int32_t AuthSrcFinishState::Action(std::shared_ptr context) } } if (srcAclList.empty()) { - LOGE("get acl failed"); - return ERR_DM_FAILED; + LOGI("AuthSrcFinishState::Action acl is empty"); // 首次认证 无acl同步 } // 比较双端的acl for (auto &srcAcl : srcAclList) { diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index f4f2a822e..64a1f0f52 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1084,8 +1084,7 @@ int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr } } if (aclList.empty()) { - LOGE("DmAuthMessageProcessor::CreateSyncMessage get acl failed"); - return ERR_DM_FAILED; + LOGI("DmAuthMessageProcessor::CreateSyncMessage acl lis is empty"); // 双方无旧ACL需要同步 } // 查询SP DmAccess accessSide; // 代表本端的access -- Gitee From f1a2b316c813c8a04e8e7e91d092ed9731766552 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Sat, 8 Mar 2025 16:37:27 +0800 Subject: [PATCH 163/382] =?UTF-8?q?BUGFIX=EF=BC=9A=E8=BD=AC=E7=A0=81?= =?UTF-8?q?=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 64a1f0f52..4d1a097d8 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1016,7 +1016,7 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptr aclHashList; for (auto &item : aclList) { @@ -1036,7 +1036,7 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptrEncryptMessage(plainJson.dump(), encSyncMsg); + return cryptoMgr_->EncryptMessage(SafetyDump(plainJson), encSyncMsg); } int32_t DmAuthMessageProcessor::ACLToStr(DistributedDeviceProfile::AccessControlProfile acl, std::string aclStr) @@ -1056,7 +1056,7 @@ int32_t DmAuthMessageProcessor::ACLToStr(DistributedDeviceProfile::AccessControl dmAcl.lastAuthTime = acl.GetLastAuthTime(); dmAcl.bindLevel = acl.GetBindType(); nlohmann::json aclJsonObj = dmAcl; - aclStr = aclJsonObj.dump(); + aclStr = SafetyDump(aclJsonObj); if (aclStr.empty()) { LOGE("DmAuthMessageProcessor::ACLToStr normalized acl failed"); return ERR_DM_FAILED; -- Gitee From d2096c555419617ff4f64b165efc71a6cab3ebc6 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Mon, 10 Mar 2025 17:43:03 +0800 Subject: [PATCH 164/382] =?UTF-8?q?BUGFIX:=E4=BF=AE=E6=94=B9acl=E5=90=8C?= =?UTF-8?q?=E6=AD=A5=E6=97=B6=E7=9A=84accesser=E3=80=81accessee=E9=80=BB?= =?UTF-8?q?=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.h | 71 ++++--- .../dm_auth_message_processor.cpp | 173 +++++++++++------- 2 files changed, 151 insertions(+), 93 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 4f4ab042a..f94965f7e 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -57,11 +57,13 @@ constexpr const char *DM_TAG_DMVERSION = "dmVersion"; 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"; -constexpr const char *DM_TAG_APPSKID = "accesserAppSKId"; -constexpr const char *DM_TAG_USERSKID = "accesserUserSKId"; -constexpr const char *DM_TAG_APPSK_TIMESTAMP = "accesserAppSKTimeStamp"; -constexpr const char *DM_TAG_USERSK_TIMESTAMP = "accesserUserSKTimeStamp"; +constexpr const char *DM_TAG_APP_SK_ID = "accessAppSKId"; // 本端sk信息 同步给对端 用于构造acl-accesser/accessee +constexpr const char *DM_TAG_USER_SK_ID = "accessUserSKId"; +constexpr const char *DM_TAG_APP_SK_TIMESTAMP = "accessAppSKTimeStamp"; +constexpr const char *DM_TAG_USER_SK_TIMESTAMP = "accessUserSKTimeStamp"; constexpr const char *DM_TAG_USER_ID = "userId"; constexpr const char *DM_TAG_ISSUER = "issuer"; @@ -90,6 +92,34 @@ constexpr const char* TAG_IS_ONLINE = "isOnline"; constexpr const char* TAG_IS_AUTHED = "isAuthed"; constexpr const char* TAG_CREDENTIAL_INFO = "credentialInfo"; +// accesser table内容 用于同步ACL +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_DEVICE_NAME = "accesserDeviceName"; +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内容 用于同步ACL +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_DEVICE_NAME = "accesseeDeviceName"; +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 { // 终止/异常报文 @@ -131,25 +161,6 @@ struct DmAccessToSync { bindLevel, sessionKeyId, skTimeStamp) }; -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; - NLOHMANN_DEFINE_TYPE_INTRUSIVE(DmAccessControlTable, accessControlId, accesserId, accesseeId, deviceId, sessionKey, - bindType, authType, deviceType, deviceIdHash, status, validPeriod, lastAuthTime, - bindLevel, deviceIdHash) -}; - class DmAuthMessageProcessor { public: DmAuthMessageProcessor(); @@ -176,13 +187,15 @@ public: DmAccess &access, std::string trustDeviceId); // 对acl进行checksum - std::string ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl); + std::string ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl);+ + + // 提取本端ACL 用于消息解析和总线使用 无ACL会返回空字符串 json格式字符串:{dmversion:x,accesser:[{accesserDeviceId:y,...},...],accessee:{...}} + int32_t GetAclListStr(, std::shared_ptr &context, std::string &aclList); private: // 内部各类报文的实现 // 用于组装syncMsg中的加密部分 - int32_t EncryptSyncMessage(std::shared_ptr &context, std::vector aclList, - DmAccess &accessSide, std::string &encSyncMsg); + int32_t EncryptSyncMessage(std::shared_ptr &context, DmAccess &accessSide, std::string &encSyncMsg); int32_t ParseAuthStartMessgae(nlohmann::json &jsonObject, std::shared_ptr &context); // 解析 80报文 @@ -258,6 +271,12 @@ private: DmAccess &access, std::string &enSyncMsg); int32_t ParseSyncMessage(std::shared_ptr &context, DmAccess &access, nlohmann::json jsonObject); + + // DP中accesser_table记录转string + void AccesserToStr(DistributedDeviceProfile::AccessControlProfile acl, std::string accesserStr); + // DP中accessee_table记录转string + void AccesseeToStr(DistributedDeviceProfile::AccessControlProfile acl, std::string accesseeStr); + std::shared_ptr cryptoMgr_ = nullptr; }; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 4d1a097d8..6c7fb972c 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -545,22 +545,6 @@ std::string DmAuthMessageProcessor::ChecksumAcl(DistributedDeviceProfile::Access void DmAuthMessageProcessor::CreateMessageSyncResp(std::shared_ptr context, nlohmann::json &jsonObject) { - // 查询ACL - std::vector profiles = - DeviceProfileConnector::GetInstance().GetAccessControlProfile(); - std::vector sinkAclList; // 保存本端ACL的checksum - for (auto &item : profiles) { - if (item.GetAccesser().GetAccesserDeviceId() == context->accesser.deviceId && - item.GetAccesser().GetAccesserUserId() == context->accesser.userId && - item.GetAccessee().GetAccesseeDeviceId() == context->accessee.deviceId && - item.GetAccessee().GetAccesseeUserId() == context->accessee.userId) { - sinkAclList.push_back(ChecksumAcl(item)); // 打印并写入 - } - } - if (sinkAclList.empty()) { - LOGE("DmAuthMessageProcessor::CreateMessageSyncResp get acl checksum failed"); - return; - } DmAccess access; // 代表本端的access if (context->direction == DM_AUTH_SINK) { access = context->accessee; @@ -569,7 +553,7 @@ void DmAuthMessageProcessor::CreateMessageSyncResp(std::shared_ptr int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr &context, DmAccess &access, nlohmann::json jsonObject) { - if (!IsString(jsonObject, DM_TAG_USERSKID)) { - LOGE("ParseSyncMessage DM_TAG_USERSKID error"); + if (!IsString(jsonObject, DM_TAG_USER_SK_ID)) { + LOGE("ParseSyncMessage DM_TAG_USER_SK_ID error"); return ERR_DM_FAILED; } - context->userSessionKeyId = std::atoi(jsonObject[DM_TAG_USERSKID].get().c_str()); - if (!IsString(jsonObject, DM_TAG_USERSK_TIMESTAMP)) { - LOGE("ParseSyncMessage DM_TAG_USERSK_TIMESTAMP error"); + context->userSessionKeyId = std::atoi(jsonObject[DM_TAG_USER_SK_ID].get().c_str()); + if (!IsString(jsonObject, DM_TAG_USER_SK_TIMESTAMP)) { + LOGE("ParseSyncMessage DM_TAG_USER_SK_TIMESTAMP error"); return ERR_DM_FAILED; } - context->userSkTimeStamp = std::atoi(jsonObject[DM_TAG_USERSK_TIMESTAMP].get().c_str()); + context->userSkTimeStamp = std::atoi(jsonObject[DM_TAG_USER_SK_TIMESTAMP].get().c_str()); if (!IsString(jsonObject, DM_TAG_DMVERSION)) { LOGE("ParseSyncMessage DM_TAG_DMVERSION error"); return ERR_DM_FAILED; @@ -681,11 +665,11 @@ int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptrappSessionKeyId = std::atoi(jsonObject[DM_TAG_APPSKID].get().c_str()); + if (IsString(jsonObject, DM_TAG_APP_SK_ID)) { + context->appSessionKeyId = std::atoi(jsonObject[DM_TAG_APP_SK_ID].get().c_str()); } - if (IsString(jsonObject, DM_TAG_APPSK_TIMESTAMP)) { - context->appSkTimeStamp = std::atoi(jsonObject[DM_TAG_APPSK_TIMESTAMP].get().c_str()); + if (IsString(jsonObject, DM_TAG_APP_SK_TIMESTAMP)) { + context->appSkTimeStamp = std::atoi(jsonObject[DM_TAG_APP_SK_TIMESTAMP].get().c_str()); } ret = ParseSyncMessage(context, access, jsonObject); if (ret != DM_OK) { @@ -987,8 +971,8 @@ std::string DmAuthMessageProcessor::DecompressSyncMsg(std::string& compressed, u } // 用于组装syncMsg中的加密部分 -int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptr &context, - std::vector aclList, DmAccess &accessSide, std::string &encSyncMsg) +int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptr &context, DmAccess &accessSide, + std::string &encSyncMsg) { nlohmann::json syncMsgJson; // 完整的180/190 消息 未经压缩&加密 DmAccessToSync accessToSync; @@ -1003,27 +987,28 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptrisOnline) { // 非首次认证 accessToSync.sessionKeyId = context->appSessionKeyId; accessToSync.skTimeStamp = context->appSkTimeStamp; - syncMsgJson[DM_TAG_APPSKID]=std::to_string(context->appSessionKeyId); - syncMsgJson[DM_TAG_APPSK_TIMESTAMP]=std::to_string(context->appSkTimeStamp); + syncMsgJson[DM_TAG_APP_SK_ID]=std::to_string(context->appSessionKeyId); + syncMsgJson[DM_TAG_APP_SK_TIMESTAMP]=std::to_string(context->appSkTimeStamp); } else { // 首次认证 accessToSync.sessionKeyId = context->userSessionKeyId; accessToSync.skTimeStamp = context->userSkTimeStamp; - syncMsgJson[DM_TAG_APPSKID]=std::to_string(context->appSessionKeyId); - syncMsgJson[DM_TAG_USERSKID]=std::to_string(context->userSessionKeyId); - syncMsgJson[DM_TAG_APPSK_TIMESTAMP]=std::to_string(context->appSkTimeStamp); - syncMsgJson[DM_TAG_USERSK_TIMESTAMP]=std::to_string(context->userSkTimeStamp); + syncMsgJson[DM_TAG_APP_SK_ID]=std::to_string(context->appSessionKeyId); + syncMsgJson[DM_TAG_USER_SK_ID]=std::to_string(context->userSessionKeyId); + syncMsgJson[DM_TAG_APP_SK_TIMESTAMP]=std::to_string(context->appSkTimeStamp); + syncMsgJson[DM_TAG_USER_SK_TIMESTAMP]=std::to_string(context->userSkTimeStamp); } nlohmann::json accessJsonObj = accessToSync; // 直接使用宏构造 access json syncMsgJson[DM_TAG_DMVERSION] = accessSide.dmVersion; syncMsgJson[DM_TAG_ACCESS] = SafetyDump(accessJsonObj); // 接收端需要再拆一次json syncMsgJson[DM_TAG_PROXY] = ""; // 预留字段 留空即可 - std::vector aclHashList; - for (auto &item : aclList) { - uint8_t aclHash[DM_HASH_LEN] = {0}; - Crypto::DmGenerateStrHash(item.data(), item.size(), aclHash, DM_HASH_LEN, 0); - aclHashList.push_back(std::string(reinterpret_cast(aclHash))); + std::string aclHashList; + int32_t ret = GetAclListStr(aclHashList); + if (ret != DM_OK) { + LOGE("DmAuthMessageProcessor::EncryptSyncMessage GetAclListStr failed"); + return ERR_DM_FAILED; } + syncMsgJson[DM_TAG_ACL_CHECKSUM] = aclHashList; std::string syncMsg = SafetyDump(syncMsgJson); // 消息构造完成 @@ -1063,42 +1048,53 @@ int32_t DmAuthMessageProcessor::ACLToStr(DistributedDeviceProfile::AccessControl } return DM_OK; } + +std::string DmAuthMessageProcessor::AccesserToStr(DistributedDeviceProfile::AccessControlProfile acl) +{ + nlohmann::json jsonAccesserObj; + jsonAccesserObj[DM_TAG_ACCESSER_DEVICE_ID] = acl.GetAccesser.GetAccesserDeviceId(); + jsonAccesserObj[DM_TAG_ACCESSER_USER_ID] = acl.GetAccesser.GetAccesserUserId(); + jsonAccesserObj[DM_TAG_ACCESSER_ACOUNT_ID] = acl.GetAccesser.GetAccesserAccountId(); + jsonAccesserObj[DM_TAG_ACCESSER_TOKEN_ID] = acl.GetAccesser.GetAccesserTokenId(); + jsonAccesserObj[DM_TAG_ACCESSER_DEVICE_NAME] = acl.GetAccesser.GetAccesserDeviceName(); + jsonAccesserObj[DM_TAG_ACCESSER_BUNDLE_NAME] = acl.GetAccesser.GetAccesserBundlerName(); + jsonAccesserObj[DM_TAG_ACCESSER_HAP_SIGNATURE] = acl.GetAccesser.GetAccesserHapSignature(); + jsonAccesserObj[DM_TAG_ACCESSER_BIND_LEVEL] = acl.GetAccesser.GetAccesserBindLevel(); + jsonAccesserObj[DM_TAG_ACCESSER_CREDENTIAL_ID] = acl.GetAccesser.GetAccesserBindLevel(); + jsonAccesserObj[DM_TAG_ACCESSER_STATUS] = acl.GetAccesser.GetAccesserStatus(); + jsonAccesserObj[DM_TAG_ACCESSER_SK_ID] = acl.GetAccesser.GetAccesserSessionKeyId(); + jsonAccesserObj[DM_TAG_ACCESSER_SK_TIMESTAMP] = acl.GetAccesser.GetAccesserSKTimeStamp(); + return SafetyDump(jsonAccesserObj); +} + +std::string DmAuthMessageProcessor::AccesseeToStr(DistributedDeviceProfile::AccessControlProfile acl) +{ + nlohmann::json jsonAccesseeObj; + jsonAccesseeObj[DM_TAG_ACCESSEE_DEVICE_ID] = acl.GetAccessee.GetAccesseeDeviceId(); + jsonAccesseeObj[DM_TAG_ACCESSEE_USER_ID] = acl.GetAccessee.GetAccesseeUserId(); + jsonAccesseeObj[DM_TAG_ACCESSEE_ACOUNT_ID] = acl.GetAccessee.GetAccesseeAccountId(); + jsonAccesseeObj[DM_TAG_ACCESSEE_TOKEN_ID] = acl.GetAccessee.GetAccesseeTokenId(); + jsonAccesseeObj[DM_TAG_ACCESSEE_DEVICE_NAME] = acl.GetAccessee.GetAccesseeDeviceName(); + jsonAccesseeObj[DM_TAG_ACCESSEE_BUNDLE_NAME] = acl.GetAccessee.GetAccesseeBundlerName(); + jsonAccesseeObj[DM_TAG_ACCESSEE_HAP_SIGNATURE] = acl.GetAccessee.GetAccesseeHapSignature(); + jsonAccesseeObj[DM_TAG_ACCESSEE_BIND_LEVEL] = acl.GetAccessee.GetAccesseeBindLevel(); + jsonAccesseeObj[DM_TAG_ACCESSEE_CREDENTIAL_ID] = acl.GetAccessee.GetAccesseeBindLevel(); + jsonAccesseeObj[DM_TAG_ACCESSEE_STATUS] = acl.GetAccessee.GetAccesseeStatus(); + jsonAccesseeObj[DM_TAG_ACCESSEE_SK_ID] = acl.GetAccessee.GetAccesseeSessionKeyId(); + jsonAccesseeObj[DM_TAG_ACCESSEE_SK_TIMESTAMP] = acl.GetAccessee.GetAccesseeSKTimeStamp(); + return SafetyDump(jsonAccesserObj); +} + int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr &context, nlohmann::json &jsonObject) { - // 查询ACL - std::vector profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfile(); - std::vector aclList; - int32_t ret; - for (auto &item : profiles) { - if (item.GetAccesser().GetAccesserDeviceId() == context->accesser.deviceId && - item.GetAccesser().GetAccesserUserId() == context->accesser.userId && - item.GetAccessee().GetAccesseeDeviceId() == context->accessee.deviceId && - item.GetAccessee().GetAccesseeUserId() == context->accessee.userId) { - std::string aclStr; - ret = ACLToStr(item, aclStr); - if (aclStr.empty()) { - LOGE("DmAuthMessageProcessor::CreateSyncMessage normalized acl failed"); - return ERR_DM_FAILED; - } - aclList.push_back(aclStr); // 打印并写入 - } - } - if (aclList.empty()) { - LOGI("DmAuthMessageProcessor::CreateSyncMessage acl lis is empty"); // 双方无旧ACL需要同步 - } - // 查询SP DmAccess accessSide; // 代表本端的access if (context->direction == DM_AUTH_SOURCE) { accessSide = context->accesser; } else { accessSide = context->accessee; } - DistributedDeviceProfile::ServiceInfoUniqueKey serviceInfoKey; - serviceInfoKey.SetDeviceId(accessSide.deviceId); - serviceInfoKey.SetUserId(accessSide.userId); - serviceInfoKey.SetTokenId(std::to_string(accessSide.tokenId)); std::string encSyncMsg; - ret = EncryptSyncMessage(context, aclList, accessSide, encSyncMsg); + ret = EncryptSyncMessage(context, accessSide, encSyncMsg); if (ret != DM_OK) { LOGE("DmAuthMessageProcessor::CreateSyncMessage encrypt failed"); return ret; @@ -1161,5 +1157,48 @@ int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(nlohmann::json &jsonObject return DM_OK; } +int32_t DmAuthMessageProcessor::GetAclListStr(std::shared_ptr &context, std:string &aclList) +{ + nlohmann::json jsonAclListObj; + jsonAclListObj[DM_TAG_DMVERSION] = context->accesser.dmVersion; // 在80/90 流程会协商出双方均兼容的版本号,此处取accesser的ver即可 + + // 查询ACL + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAccessControlProfile(); + std::vector accceserStrList; + std::vector accceseeStrList; + // 遍历acl table 找到双端历史acl记录 + for (auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == context->accesser.deviceId && + item.GetAccesser().GetAccesserUserId() == context->accesser.userId && + item.GetAccessee().GetAccesseeDeviceId() == context->accessee.deviceId && + item.GetAccessee().GetAccesseeUserId() == context->accessee.userId) { + // 以SHA256的摘要保存 + uint8_t accesserHash[DM_HASH_LEN] = {0}; + std::string accesserStr = AccesserToStr(item); + Crypto::DmGenerateStrHash(accesserStr.data(), accesserStr.size(), accesserHash, DM_HASH_LEN, 0); + accceserStrList.push_back(accesserHash); + + uint8_t accesseeHash[DM_HASH_LEN] = {0}; + std::string accesseeStr = AccesseeToStr(item); + Crypto::DmGenerateStrHash(accesseeStr.data(), accesseeStr.size(), accesseeHash, DM_HASH_LEN, 0); + accceseeStrList.push_back(accesseeHash); + } + } + if (accceserStrList.empty() || accceseeStrList.empty()) { + LOGI("DmAuthMessageProcessor::CreateSyncMessage acl lis is empty"); // 双方无旧ACL需要同步 此时返回空字符串 + } + + for (auto &item : aclList) { + uint8_t aclHash[DM_HASH_LEN] = {0}; + + aclHashList.push_back(std::string(reinterpret_cast(aclHash))); + } + jsonAclListObj[DM_TAG_ACCESSER] = accceserStrList; + jsonAclListObj[DM_TAG_ACCESSEE] = accceseeStrList; + aclList = SafetyDump(jsonAclListObj); + return DM_OK; +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file -- Gitee From f96f38d9cf5e7f848e61f715c6d53c9624f69929 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Mon, 10 Mar 2025 17:53:17 +0800 Subject: [PATCH 165/382] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.h | 27 ++++++++++++++++--- .../dm_auth_message_processor.cpp | 2 +- 2 files changed, 24 insertions(+), 5 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index f94965f7e..966715248 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -145,6 +145,25 @@ enum DmMessageType { MSG_TYPE_AUTH_FINISH = 200, }; +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; + NLOHMANN_DEFINE_TYPE_INTRUSIVE(DmAccessControlTable, accessControlId, accesserId, accesseeId, deviceId, sessionKey, + bindType, authType, deviceType, deviceIdHash, status, validPeriod, lastAuthTime, + bindLevel, deviceIdHash) +}; + // 用于同步ACL的access结构 struct DmAccessToSync { std::string deviceName; @@ -187,10 +206,10 @@ public: DmAccess &access, std::string trustDeviceId); // 对acl进行checksum - std::string ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl);+ + std::string ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl); // 提取本端ACL 用于消息解析和总线使用 无ACL会返回空字符串 json格式字符串:{dmversion:x,accesser:[{accesserDeviceId:y,...},...],accessee:{...}} - int32_t GetAclListStr(, std::shared_ptr &context, std::string &aclList); + int32_t GetAclListStr(std::shared_ptr &context, std::string &aclList); private: // 内部各类报文的实现 @@ -273,9 +292,9 @@ private: DmAccess &access, nlohmann::json jsonObject); // DP中accesser_table记录转string - void AccesserToStr(DistributedDeviceProfile::AccessControlProfile acl, std::string accesserStr); + std::string AccesserToStr(DistributedDeviceProfile::AccessControlProfile acl); // DP中accessee_table记录转string - void AccesseeToStr(DistributedDeviceProfile::AccessControlProfile acl, std::string accesseeStr); + std::string AccesseeToStr(DistributedDeviceProfile::AccessControlProfile acl); std::shared_ptr cryptoMgr_ = nullptr; }; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 6c7fb972c..20e663113 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1003,7 +1003,7 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptr Date: Mon, 10 Mar 2025 18:00:08 +0800 Subject: [PATCH 166/382] =?UTF-8?q?BUGFIX:=E9=9D=99=E6=80=81=E5=BC=95?= =?UTF-8?q?=E7=94=A8=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.cpp | 50 ++++++++++--------- 1 file changed, 26 insertions(+), 24 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 20e663113..5b8035734 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1052,36 +1052,38 @@ int32_t DmAuthMessageProcessor::ACLToStr(DistributedDeviceProfile::AccessControl std::string DmAuthMessageProcessor::AccesserToStr(DistributedDeviceProfile::AccessControlProfile acl) { nlohmann::json jsonAccesserObj; - jsonAccesserObj[DM_TAG_ACCESSER_DEVICE_ID] = acl.GetAccesser.GetAccesserDeviceId(); - jsonAccesserObj[DM_TAG_ACCESSER_USER_ID] = acl.GetAccesser.GetAccesserUserId(); - jsonAccesserObj[DM_TAG_ACCESSER_ACOUNT_ID] = acl.GetAccesser.GetAccesserAccountId(); - jsonAccesserObj[DM_TAG_ACCESSER_TOKEN_ID] = acl.GetAccesser.GetAccesserTokenId(); - jsonAccesserObj[DM_TAG_ACCESSER_DEVICE_NAME] = acl.GetAccesser.GetAccesserDeviceName(); - jsonAccesserObj[DM_TAG_ACCESSER_BUNDLE_NAME] = acl.GetAccesser.GetAccesserBundlerName(); - jsonAccesserObj[DM_TAG_ACCESSER_HAP_SIGNATURE] = acl.GetAccesser.GetAccesserHapSignature(); - jsonAccesserObj[DM_TAG_ACCESSER_BIND_LEVEL] = acl.GetAccesser.GetAccesserBindLevel(); - jsonAccesserObj[DM_TAG_ACCESSER_CREDENTIAL_ID] = acl.GetAccesser.GetAccesserBindLevel(); - jsonAccesserObj[DM_TAG_ACCESSER_STATUS] = acl.GetAccesser.GetAccesserStatus(); - jsonAccesserObj[DM_TAG_ACCESSER_SK_ID] = acl.GetAccesser.GetAccesserSessionKeyId(); - jsonAccesserObj[DM_TAG_ACCESSER_SK_TIMESTAMP] = acl.GetAccesser.GetAccesserSKTimeStamp(); + DistributedDeviceProfile::Accesser accesser = acl.GetAccesser; + jsonAccesserObj[DM_TAG_ACCESSER_DEVICE_ID] = accesserGetAccesserDeviceId(); + jsonAccesserObj[DM_TAG_ACCESSER_USER_ID] = accesserGetAccesserUserId(); + jsonAccesserObj[DM_TAG_ACCESSER_ACOUNT_ID] = accesserGetAccesserAccountId(); + jsonAccesserObj[DM_TAG_ACCESSER_TOKEN_ID] = accesserGetAccesserTokenId(); + jsonAccesserObj[DM_TAG_ACCESSER_DEVICE_NAME] = accesserGetAccesserDeviceName(); + jsonAccesserObj[DM_TAG_ACCESSER_BUNDLE_NAME] = accesserGetAccesserBundlerName(); + jsonAccesserObj[DM_TAG_ACCESSER_HAP_SIGNATURE] = accesserGetAccesserHapSignature(); + jsonAccesserObj[DM_TAG_ACCESSER_BIND_LEVEL] = accesserGetAccesserBindLevel(); + jsonAccesserObj[DM_TAG_ACCESSER_CREDENTIAL_ID] = accesserGetAccesserBindLevel(); + jsonAccesserObj[DM_TAG_ACCESSER_STATUS] = accesserGetAccesserStatus(); + jsonAccesserObj[DM_TAG_ACCESSER_SK_ID] = accesserGetAccesserSessionKeyId(); + jsonAccesserObj[DM_TAG_ACCESSER_SK_TIMESTAMP] = accesserGetAccesserSKTimeStamp(); return SafetyDump(jsonAccesserObj); } std::string DmAuthMessageProcessor::AccesseeToStr(DistributedDeviceProfile::AccessControlProfile acl) { nlohmann::json jsonAccesseeObj; - jsonAccesseeObj[DM_TAG_ACCESSEE_DEVICE_ID] = acl.GetAccessee.GetAccesseeDeviceId(); - jsonAccesseeObj[DM_TAG_ACCESSEE_USER_ID] = acl.GetAccessee.GetAccesseeUserId(); - jsonAccesseeObj[DM_TAG_ACCESSEE_ACOUNT_ID] = acl.GetAccessee.GetAccesseeAccountId(); - jsonAccesseeObj[DM_TAG_ACCESSEE_TOKEN_ID] = acl.GetAccessee.GetAccesseeTokenId(); - jsonAccesseeObj[DM_TAG_ACCESSEE_DEVICE_NAME] = acl.GetAccessee.GetAccesseeDeviceName(); - jsonAccesseeObj[DM_TAG_ACCESSEE_BUNDLE_NAME] = acl.GetAccessee.GetAccesseeBundlerName(); - jsonAccesseeObj[DM_TAG_ACCESSEE_HAP_SIGNATURE] = acl.GetAccessee.GetAccesseeHapSignature(); - jsonAccesseeObj[DM_TAG_ACCESSEE_BIND_LEVEL] = acl.GetAccessee.GetAccesseeBindLevel(); - jsonAccesseeObj[DM_TAG_ACCESSEE_CREDENTIAL_ID] = acl.GetAccessee.GetAccesseeBindLevel(); - jsonAccesseeObj[DM_TAG_ACCESSEE_STATUS] = acl.GetAccessee.GetAccesseeStatus(); - jsonAccesseeObj[DM_TAG_ACCESSEE_SK_ID] = acl.GetAccessee.GetAccesseeSessionKeyId(); - jsonAccesseeObj[DM_TAG_ACCESSEE_SK_TIMESTAMP] = acl.GetAccessee.GetAccesseeSKTimeStamp(); + DistributedDeviceProfile::Accessee accessee = acl.GetAccessee; + jsonAccesseeObj[DM_TAG_ACCESSEE_DEVICE_ID] = accesseeGetAccesseeDeviceId(); + jsonAccesseeObj[DM_TAG_ACCESSEE_USER_ID] = accesseeGetAccesseeUserId(); + jsonAccesseeObj[DM_TAG_ACCESSEE_ACOUNT_ID] = accesseeGetAccesseeAccountId(); + jsonAccesseeObj[DM_TAG_ACCESSEE_TOKEN_ID] = accesseeGetAccesseeTokenId(); + jsonAccesseeObj[DM_TAG_ACCESSEE_DEVICE_NAME] = accesseeGetAccesseeDeviceName(); + jsonAccesseeObj[DM_TAG_ACCESSEE_BUNDLE_NAME] = accesseeGetAccesseeBundlerName(); + jsonAccesseeObj[DM_TAG_ACCESSEE_HAP_SIGNATURE] = accesseeGetAccesseeHapSignature(); + jsonAccesseeObj[DM_TAG_ACCESSEE_BIND_LEVEL] = accesseeGetAccesseeBindLevel(); + jsonAccesseeObj[DM_TAG_ACCESSEE_CREDENTIAL_ID] = accesseeGetAccesseeBindLevel(); + jsonAccesseeObj[DM_TAG_ACCESSEE_STATUS] = accesseeGetAccesseeStatus(); + jsonAccesseeObj[DM_TAG_ACCESSEE_SK_ID] = accesseeGetAccesseeSessionKeyId(); + jsonAccesseeObj[DM_TAG_ACCESSEE_SK_TIMESTAMP] = accesseeGetAccesseeSKTimeStamp(); return SafetyDump(jsonAccesserObj); } -- Gitee From 9b469eacd0eb8c2ac77e10ff78256aee10180dc5 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Mon, 10 Mar 2025 19:31:01 +0800 Subject: [PATCH 167/382] =?UTF-8?q?BUGFIX:=E7=BC=96=E8=AF=91=E9=94=99?= =?UTF-8?q?=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.cpp | 62 +++++++++---------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 5b8035734..6c474b36f 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1052,39 +1052,39 @@ int32_t DmAuthMessageProcessor::ACLToStr(DistributedDeviceProfile::AccessControl std::string DmAuthMessageProcessor::AccesserToStr(DistributedDeviceProfile::AccessControlProfile acl) { nlohmann::json jsonAccesserObj; - DistributedDeviceProfile::Accesser accesser = acl.GetAccesser; - jsonAccesserObj[DM_TAG_ACCESSER_DEVICE_ID] = accesserGetAccesserDeviceId(); - jsonAccesserObj[DM_TAG_ACCESSER_USER_ID] = accesserGetAccesserUserId(); - jsonAccesserObj[DM_TAG_ACCESSER_ACOUNT_ID] = accesserGetAccesserAccountId(); - jsonAccesserObj[DM_TAG_ACCESSER_TOKEN_ID] = accesserGetAccesserTokenId(); - jsonAccesserObj[DM_TAG_ACCESSER_DEVICE_NAME] = accesserGetAccesserDeviceName(); - jsonAccesserObj[DM_TAG_ACCESSER_BUNDLE_NAME] = accesserGetAccesserBundlerName(); - jsonAccesserObj[DM_TAG_ACCESSER_HAP_SIGNATURE] = accesserGetAccesserHapSignature(); - jsonAccesserObj[DM_TAG_ACCESSER_BIND_LEVEL] = accesserGetAccesserBindLevel(); - jsonAccesserObj[DM_TAG_ACCESSER_CREDENTIAL_ID] = accesserGetAccesserBindLevel(); - jsonAccesserObj[DM_TAG_ACCESSER_STATUS] = accesserGetAccesserStatus(); - jsonAccesserObj[DM_TAG_ACCESSER_SK_ID] = accesserGetAccesserSessionKeyId(); - jsonAccesserObj[DM_TAG_ACCESSER_SK_TIMESTAMP] = accesserGetAccesserSKTimeStamp(); + DistributedDeviceProfile::Accesser accesser = acl.GetAccesser(); + jsonAccesserObj[DM_TAG_ACCESSER_DEVICE_ID] = accesser.GetAccesserDeviceId(); + jsonAccesserObj[DM_TAG_ACCESSER_USER_ID] = accesser.GetAccesserUserId(); + jsonAccesserObj[DM_TAG_ACCESSER_ACOUNT_ID] = accesser.GetAccesserAccountId(); + jsonAccesserObj[DM_TAG_ACCESSER_TOKEN_ID] = accesser.GetAccesserTokenId(); + jsonAccesserObj[DM_TAG_ACCESSER_DEVICE_NAME] = accesser.GetAccesserDeviceName(); + jsonAccesserObj[DM_TAG_ACCESSER_BUNDLE_NAME] = accesser.GetAccesserBundleName(); + jsonAccesserObj[DM_TAG_ACCESSER_HAP_SIGNATURE] = accesser.GetAccesserHapSignature(); + jsonAccesserObj[DM_TAG_ACCESSER_BIND_LEVEL] = accesser.GetAccesserBindLevel(); + jsonAccesserObj[DM_TAG_ACCESSER_CREDENTIAL_ID] = accesser.GetAccesserBindLevel(); + jsonAccesserObj[DM_TAG_ACCESSER_STATUS] = accesser.GetAccesserStatus(); + jsonAccesserObj[DM_TAG_ACCESSER_SK_ID] = accesser.GetAccesserSessionKeyId(); + jsonAccesserObj[DM_TAG_ACCESSER_SK_TIMESTAMP] = accesser.GetAccesserSKTimeStamp(); return SafetyDump(jsonAccesserObj); } std::string DmAuthMessageProcessor::AccesseeToStr(DistributedDeviceProfile::AccessControlProfile acl) { nlohmann::json jsonAccesseeObj; - DistributedDeviceProfile::Accessee accessee = acl.GetAccessee; - jsonAccesseeObj[DM_TAG_ACCESSEE_DEVICE_ID] = accesseeGetAccesseeDeviceId(); - jsonAccesseeObj[DM_TAG_ACCESSEE_USER_ID] = accesseeGetAccesseeUserId(); - jsonAccesseeObj[DM_TAG_ACCESSEE_ACOUNT_ID] = accesseeGetAccesseeAccountId(); - jsonAccesseeObj[DM_TAG_ACCESSEE_TOKEN_ID] = accesseeGetAccesseeTokenId(); - jsonAccesseeObj[DM_TAG_ACCESSEE_DEVICE_NAME] = accesseeGetAccesseeDeviceName(); - jsonAccesseeObj[DM_TAG_ACCESSEE_BUNDLE_NAME] = accesseeGetAccesseeBundlerName(); - jsonAccesseeObj[DM_TAG_ACCESSEE_HAP_SIGNATURE] = accesseeGetAccesseeHapSignature(); - jsonAccesseeObj[DM_TAG_ACCESSEE_BIND_LEVEL] = accesseeGetAccesseeBindLevel(); - jsonAccesseeObj[DM_TAG_ACCESSEE_CREDENTIAL_ID] = accesseeGetAccesseeBindLevel(); - jsonAccesseeObj[DM_TAG_ACCESSEE_STATUS] = accesseeGetAccesseeStatus(); - jsonAccesseeObj[DM_TAG_ACCESSEE_SK_ID] = accesseeGetAccesseeSessionKeyId(); - jsonAccesseeObj[DM_TAG_ACCESSEE_SK_TIMESTAMP] = accesseeGetAccesseeSKTimeStamp(); - return SafetyDump(jsonAccesserObj); + DistributedDeviceProfile::Accessee accessee = acl.GetAccessee(); + jsonAccesseeObj[DM_TAG_ACCESSEE_DEVICE_ID] = accessee.GetAccesseeDeviceId(); + jsonAccesseeObj[DM_TAG_ACCESSEE_USER_ID] = accessee.GetAccesseeUserId(); + jsonAccesseeObj[DM_TAG_ACCESSEE_ACOUNT_ID] = accessee.GetAccesseeAccountId(); + jsonAccesseeObj[DM_TAG_ACCESSEE_TOKEN_ID] = accessee.GetAccesseeTokenId(); + jsonAccesseeObj[DM_TAG_ACCESSEE_DEVICE_NAME] = accessee.GetAccesseeDeviceName(); + jsonAccesseeObj[DM_TAG_ACCESSEE_BUNDLE_NAME] = accessee.GetAccesseeBundleName(); + jsonAccesseeObj[DM_TAG_ACCESSEE_HAP_SIGNATURE] = accessee.GetAccesseeHapSignature(); + jsonAccesseeObj[DM_TAG_ACCESSEE_BIND_LEVEL] = accessee.GetAccesseeBindLevel(); + jsonAccesseeObj[DM_TAG_ACCESSEE_CREDENTIAL_ID] = accessee.GetAccesseeBindLevel(); + jsonAccesseeObj[DM_TAG_ACCESSEE_STATUS] = accessee.GetAccesseeStatus(); + jsonAccesseeObj[DM_TAG_ACCESSEE_SK_ID] = accessee.GetAccesseeSessionKeyId(); + jsonAccesseeObj[DM_TAG_ACCESSEE_SK_TIMESTAMP] = accessee.GetAccesseeSKTimeStamp(); + return SafetyDump(jsonAccesseeObj); } int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr &context, nlohmann::json &jsonObject) @@ -1096,7 +1096,7 @@ int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr accessSide = context->accessee; } std::string encSyncMsg; - ret = EncryptSyncMessage(context, accessSide, encSyncMsg); + int32_t ret = EncryptSyncMessage(context, accessSide, encSyncMsg); if (ret != DM_OK) { LOGE("DmAuthMessageProcessor::CreateSyncMessage encrypt failed"); return ret; @@ -1159,7 +1159,7 @@ int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(nlohmann::json &jsonObject return DM_OK; } -int32_t DmAuthMessageProcessor::GetAclListStr(std::shared_ptr &context, std:string &aclList) +int32_t DmAuthMessageProcessor::GetAclListStr(std::shared_ptr &context, std::string &aclList) { nlohmann::json jsonAclListObj; jsonAclListObj[DM_TAG_DMVERSION] = context->accesser.dmVersion; // 在80/90 流程会协商出双方均兼容的版本号,此处取accesser的ver即可 @@ -1179,12 +1179,12 @@ int32_t DmAuthMessageProcessor::GetAclListStr(std::shared_ptr &co uint8_t accesserHash[DM_HASH_LEN] = {0}; std::string accesserStr = AccesserToStr(item); Crypto::DmGenerateStrHash(accesserStr.data(), accesserStr.size(), accesserHash, DM_HASH_LEN, 0); - accceserStrList.push_back(accesserHash); + accceserStrList.push_back(reiterpret_cast(accesserHash)); uint8_t accesseeHash[DM_HASH_LEN] = {0}; std::string accesseeStr = AccesseeToStr(item); Crypto::DmGenerateStrHash(accesseeStr.data(), accesseeStr.size(), accesseeHash, DM_HASH_LEN, 0); - accceseeStrList.push_back(accesseeHash); + accceseeStrList.push_back(reiterpret_cast(accesseeHash)); } } if (accceserStrList.empty() || accceseeStrList.empty()) { -- Gitee From 87c1c7ea3ff52e72c663f061272d0641bbc8add6 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Mon, 10 Mar 2025 19:33:07 +0800 Subject: [PATCH 168/382] =?UTF-8?q?BUGFIX:=E5=88=A0=E9=99=A4=E5=86=97?= =?UTF-8?q?=E4=BD=99=E4=BB=A3=E7=A0=81?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 6c474b36f..42d67b0cb 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1179,23 +1179,18 @@ int32_t DmAuthMessageProcessor::GetAclListStr(std::shared_ptr &co uint8_t accesserHash[DM_HASH_LEN] = {0}; std::string accesserStr = AccesserToStr(item); Crypto::DmGenerateStrHash(accesserStr.data(), accesserStr.size(), accesserHash, DM_HASH_LEN, 0); - accceserStrList.push_back(reiterpret_cast(accesserHash)); + accceserStrList.push_back(reinterpret_cast(accesserHash)); uint8_t accesseeHash[DM_HASH_LEN] = {0}; std::string accesseeStr = AccesseeToStr(item); Crypto::DmGenerateStrHash(accesseeStr.data(), accesseeStr.size(), accesseeHash, DM_HASH_LEN, 0); - accceseeStrList.push_back(reiterpret_cast(accesseeHash)); + accceseeStrList.push_back(reinterpret_cast(accesseeHash)); } } if (accceserStrList.empty() || accceseeStrList.empty()) { LOGI("DmAuthMessageProcessor::CreateSyncMessage acl lis is empty"); // 双方无旧ACL需要同步 此时返回空字符串 } - for (auto &item : aclList) { - uint8_t aclHash[DM_HASH_LEN] = {0}; - - aclHashList.push_back(std::string(reinterpret_cast(aclHash))); - } jsonAclListObj[DM_TAG_ACCESSER] = accceserStrList; jsonAclListObj[DM_TAG_ACCESSEE] = accceseeStrList; aclList = SafetyDump(jsonAclListObj); -- Gitee From b1cc2a54f213f7924487c2f9c1a829e6476ee220 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Tue, 11 Mar 2025 12:13:20 +0800 Subject: [PATCH 169/382] =?UTF-8?q?BUGFIX:=E8=A1=A5=E5=85=85base64?= =?UTF-8?q?=EF=BC=8C=E8=A7=A3=E5=86=B3=E7=BC=96=E8=A7=A3=E7=A0=81=E4=B8=80?= =?UTF-8?q?=E8=87=B4=E6=80=A7=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.h | 3 +- .../dm_auth_message_processor.cpp | 47 ++++++++++++++++++- 2 files changed, 47 insertions(+), 3 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 966715248..ba5e65071 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -295,7 +295,8 @@ private: std::string AccesserToStr(DistributedDeviceProfile::AccessControlProfile acl); // DP中accessee_table记录转string std::string AccesseeToStr(DistributedDeviceProfile::AccessControlProfile acl); - + std::string Base64Encode(std::string &inputStr); + std::string Base64Decode(std::string &inputStr); std::shared_ptr cryptoMgr_ = nullptr; }; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 42d67b0cb..669d91473 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -13,6 +13,7 @@ * limitations under the License. */ #include +#include #include "dm_anonymous.h" #include "dm_auth_context.h" #include "dm_auth_message_processor.h" @@ -658,7 +659,7 @@ int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptr(); // 解压缩 - std::string syncMsg = DecompressSyncMsg(compressMsg, dataLen); + std::string syncMsg = DecompressSyncMsg(Base64Decode(compressMsg), dataLen); // 解析字段 nlohmann::json jsonObject = nlohmann::json::parse(syncMsg, nullptr, false); if (jsonObject.is_discarded()) { @@ -970,6 +971,48 @@ std::string DmAuthMessageProcessor::DecompressSyncMsg(std::string& compressed, u return decompressed; } +std::string DmAuthMessageProcessor::Base64Encode(std::string &inputStr) +{ + // 输入字符串转二进制 + const unsigned char* src = reinterpret_cast(inputStr.data()); + size_t srcLen = inputStr.size(); + + // 计算base64 后最大长度 + size_t maxEncodeLen = ((srcLen + 2) / 3) * 4 + 1; + std::vector buffer(maxEncodeLen); + + // 实际编码长度 + size_t encodedLen = 0; + int32_t ret = mbedtls_base64_encode(buffer.data(), buffer.size(), &encodedLen, src, srcLen); + if (ret != 0) { + LOGE("DmAuthMessageProcessor::Base64Encode mbedtls_base64_encode failed"); + return ""; + } + return std::string(reinterpret_cast(buffer.data()), encodedLen); // 无需终止符 +} + + +std::string DmAuthMessageProcessor::Base64Decode(std::string &inputStr) +{ + // 输入字符串转二进制 + const unsigned char* src = reinterpret_cast(inputStr.data()); + size_t srcLen = inputStr.size(); + + // 计算base64 后最大长度 + size_t maxEncodeLen = (srcLen / 4) * 3 + 1; + std::vector buffer(maxEncodeLen); + + // 实际编码长度 + size_t decodedLen = 0; + int32_t ret = mbedtls_base64_decode(buffer.data(), buffer.size(), &decodedLen, src, srcLen); + if (ret != 0) { + LOGE("DmAuthMessageProcessor::Base64Decode mbedtls_base64_decode failed"); + return ""; + } + return std::string(reinterpret_cast(buffer.data()), decodedLen); // 无需终止符 +} + + // 用于组装syncMsg中的加密部分 int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptr &context, DmAccess &accessSide, std::string &encSyncMsg) @@ -1019,7 +1062,7 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptrEncryptMessage(SafetyDump(plainJson), encSyncMsg); } -- Gitee From 462095f1040d4d78028d685da354acc7923e5596 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Tue, 11 Mar 2025 12:16:12 +0800 Subject: [PATCH 170/382] =?UTF-8?q?BUGFIX:=E8=A7=A3=E5=86=B3=E7=BC=96?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 669d91473..3dc00ef82 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -659,7 +659,8 @@ int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptr(); // 解压缩 - std::string syncMsg = DecompressSyncMsg(Base64Decode(compressMsg), dataLen); + std::string compressBase64 = Base64Decode(compressMsg); + std::string syncMsg = DecompressSyncMsg(compressBase64, dataLen); // 解析字段 nlohmann::json jsonObject = nlohmann::json::parse(syncMsg, nullptr, false); if (jsonObject.is_discarded()) { -- Gitee From 2d884348936d0325a0eda90670c46f7eb18dda9b Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 11 Mar 2025 14:55:16 +0800 Subject: [PATCH 171/382] tmp --- .../include/authentication_v2/dm_auth_state.h | 2 +- .../auth_stages/auth_confirm.cpp | 20 +++++++++---------- .../auth_stages/auth_pin_auth.cpp | 2 +- 3 files changed, 12 insertions(+), 12 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 8c2ad990b..48d13f233 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -138,7 +138,7 @@ public: DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; private: - int32_t GetAuthType(std::shared_ptr context); // 从DP配置读取授权类型 + int32_t MatchAuthType(std::shared_ptr context); // 从DP配置读取授权类型 int32_t ShowConfigDialog(std::shared_ptr context); // 提示用户授权对话框 int64_t GenRequestId(std::shared_ptr context); // 生成HiChain请求ID }; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index ae63e57d4..46af56964 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -135,7 +135,7 @@ int32_t AuthSinkConfirmState::ShowConfigDialog(std::shared_ptr co return DM_OK; } #if 1 // todo 新的获取方法 根据客户端AuthType和BundleName从服务端SP表里查询业务注册的认证类型 -int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context) +int32_t AuthSinkConfirmState::MatchAuthType(std::shared_ptr context) { // DP 接口 查询ServiceInfoProfile std::vector serviceInfos; @@ -146,10 +146,10 @@ int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context key.SetTokenId(tokenId); auto ret = DeviceProfileConnector::GetInstance().GetServiceInfoProfileListByTokenId(key, serviceInfos); if (ret != DM_OK) { - LOGE("AuthSinkConfirmState::GetAuthType GetServiceInfoByTokenId err %{public}d", ret); + LOGE("AuthSinkConfirmState::MatchAuthType GetServiceInfoByTokenId err %{public}d", ret); // 获取不到走PIN认证方案 if (context->authType != DmAuthType::AUTH_TYPE_PIN) { - LOGE("AuthSinkConfirmState::GetAuthType AUTH_TYPE_PIN not match"); + LOGE("AuthSinkConfirmState::MatchAuthType AUTH_TYPE_PIN not match"); return STOP_BIND; } return DM_OK; @@ -169,7 +169,7 @@ int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context // 期望有且仅有一条符合的 serviceInfo if (filterServiceInfos.size() != 1) { - LOGE("AuthSinkConfirmState::GetAuthType filterServiceInfo not unique"); + LOGE("AuthSinkConfirmState::MatchAuthType filterServiceInfo not unique"); return STOP_BIND; } @@ -179,7 +179,7 @@ int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context int32_t pinExchangeType = srvInfo.GetPinExchangeType(); if (authBoxType == DistributedDeviceProfile::NUM_1) { // 三态框 if (context->authType != DmAuthType::AUTH_TYPE_PIN) { - LOGE("AuthSinkConfirmState::GetAuthType AUTH_TYPE_PIN not match"); + LOGE("AuthSinkConfirmState::MatchAuthType AUTH_TYPE_PIN not match"); return STOP_BIND; } return DM_OK; @@ -195,13 +195,13 @@ int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context if (pinExchangeType == DistributedDeviceProfile::NUM_2) { // 超声交换PIN if (context->authType != DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { - LOGE("AuthSinkConfirmState::GetAuthType AUTH_TYPE_PIN_ULTRASONIC not match"); + LOGE("AuthSinkConfirmState::MatchAuthType AUTH_TYPE_PIN_ULTRASONIC not match"); return STOP_BIND; } return DM_OK; } else if (pinExchangeType == DistributedDeviceProfile::NUM_3) { // 导入PIN if (context->authType != DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { - LOGE("AuthSinkConfirmState::GetAuthType AUTH_TYPE_IMPORT_AUTH_CODE not match"); + LOGE("AuthSinkConfirmState::MatchAuthType AUTH_TYPE_IMPORT_AUTH_CODE not match"); return STOP_BIND; } // 读取PIN码 @@ -211,11 +211,11 @@ int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context } } - LOGE("AuthSinkConfirmState::GetAuthType authType not support"); + LOGE("AuthSinkConfirmState::MatchAuthType authType not support"); return STOP_BIND; } #else -int32_t AuthSinkConfirmState::GetAuthType(std::shared_ptr context) +int32_t AuthSinkConfirmState::MatchAuthType(std::shared_ptr context) { context->authResult = USER_OPERATION_TYPE_ALLOW_AUTH; return DM_OK; @@ -236,7 +236,7 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) // 停止授权报文计时 context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); context->requestId = GenRequestId(context); - auto ret = GetAuthType(context); + auto ret = MatchAuthType(context); if (ret != DM_OK) { return ret; } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 5fcaa04fc..ea23fa35e 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -138,7 +138,7 @@ int32_t AuthSrcPinAuthStartState::GetPinCodeFromServerInfo(std::shared_ptr Date: Tue, 11 Mar 2025 15:03:06 +0800 Subject: [PATCH 172/382] authentication_v2 pkgName => sessionName --- .../include/authentication_v2/auth_manager.h | 30 ++++---- .../authentication_v2/dm_auth_context.h | 2 +- .../dm_auth_message_processor.h | 2 +- .../src/authentication_v2/auth_manager.cpp | 76 +++++++++---------- .../auth_stages/auth_confirm.cpp | 2 +- .../dm_auth_message_processor.cpp | 6 +- 6 files changed, 59 insertions(+), 59 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 43dd5b393..79abe8902 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -72,10 +72,10 @@ public: * @tc.desc: Generate Pincode of the DeviceManager Authenticate Manager * @tc.type: FUNC */ - int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + int32_t BindTarget(const std::string &sessionName, const PeerTargetId &targetId, const std::map &bindParam); // 停止绑定 TODO 如果多会话实例隔离后,pkgName 是不是不需要了? 后续其他API同理? - int32_t StopAuthenticateDevice(const std::string &pkgName); + int32_t StopAuthenticateDevice(const std::string &sessionName); /** * @tc.name: AuthManager::OnUserOperation @@ -89,39 +89,39 @@ public: * @tc.type: FUNC */ // todo 新协议是通过DP去查询的? - int32_t ImportAuthCode(const std::string &pkgName, const std::string &authCode); + 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 pkgName); + 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 pkgName); + 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 &pkgName, const std::string &udid, int32_t bindLevel); + int32_t UnAuthenticateDevice(const std::string &sessionName, const std::string &udid, int32_t bindLevel); /** * @brief UnBind device. - * @param pkgName package name. + * @param sessionName package name. * @param deviceId device id. * @return Return 0 if success. */ - int32_t UnBindDevice(const std::string &pkgName, const std::string &udid, + 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 DeleteGroup(const std::string &pkgName, const std::string &deviceId); + int32_t DeleteGroup(const std::string &sessionName, const std::string &deviceId); int32_t RegisterAuthenticationType(int32_t authenticationType); // 对外API 实现 end @@ -140,7 +140,7 @@ protected: // IDmDeviceAuthCallback 转内部接口 // pkgName是#define DM_APP_ID "ohos.distributedhardware.devicemanager" - // int32_t GetPinCode(std::string &pkgName, int32_t &code); + // int32_t GetPinCode(std::string &sessionName, int32_t &code); int32_t GetPinCode(int32_t &code); void GetRemoteDeviceId(std::string &deviceId); // IDmDeviceAuthCallback 转内部接口 @@ -149,18 +149,18 @@ private: int32_t ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType); void ParseHmlInfoInJsonObject(nlohmann::json jsonObject); void ParseJsonObject(nlohmann::json jsonObject); - void GetAuthParam(const std::string &pkgName, int32_t authType, + void GetAuthParam(const std::string &sessionName, int32_t authType, const std::string &deviceId, const std::string &extra); std::string GetBundleName(nlohmann::json &jsonObject); int32_t GetBindLevel(int32_t bindLevel); void SetAuthType(int32_t authType); bool IsAuthTypeSupported(const int32_t &authType); - bool IsAuthCodeReady(const std::string &pkgName); - int32_t CheckAuthParamVaild(const std::string &pkgName, 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 &pkgName, int32_t authType, + void InitAuthState(const std::string &sessionName, int32_t authType, const std::string &deviceId, const std::string &extra); - int32_t AuthenticateDevice(const std::string &pkgName, int32_t authType, + int32_t AuthenticateDevice(const std::string &sessionName, int32_t authType, const std::string &deviceId, const std::string &extra); }; diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index c85b41ba9..1b1b69bc5 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -162,7 +162,7 @@ struct DmAuthContext { bool authenticating; // 标识正在认证中 bool isAppCredentialVerified = false; // 应用凭据是否认证 bool hmlEnable160M = false; - std::string pkgName; // 业务传入的标识,业务自定义,有被仿冒的风险 + std::string sessionName; // 业务传入的标识,业务自定义,有被仿冒的风险 std::string pkgLabel; std::string importCodeBundleName; // 导入pin码的包名,从系统中读取,与acceserBundleName一致 std::string appThumbnail; // 应用图标 diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index ba5e65071..159ba9be3 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -79,7 +79,7 @@ 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_PKG_NAME = "pkgName"; +constexpr const char* TAG_PKG_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"; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 929b49f6d..84245d1b5 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -204,56 +204,56 @@ int32_t AuthManager::GeneratePincode() return context_->pinCode; } -int32_t AuthManager::RegisterUiStateCallback(const std::string pkgName) +int32_t AuthManager::RegisterUiStateCallback(const std::string sessionName) { LOGI("AuthManager::RegisterUiStateCallback start"); if (context_->authUiStateMgr == nullptr) { LOGE("AuthManager::RegisterUiStateCallback context_->authUiStateMgr is null."); return ERR_DM_FAILED; } - context_->authUiStateMgr->RegisterUiStateCallback(pkgName); + context_->authUiStateMgr->RegisterUiStateCallback(sessionName); return DM_OK; } -int32_t AuthManager::UnRegisterUiStateCallback(const std::string pkgName) +int32_t AuthManager::UnRegisterUiStateCallback(const std::string sessionName) { LOGI("AuthManager::UnRegisterUiStateCallback start"); if (context_->authUiStateMgr == nullptr) { LOGE("AuthManager::UnRegisterUiStateCallback context_->authUiStateMgr is null."); return ERR_DM_FAILED; } - context_->authUiStateMgr->UnRegisterUiStateCallback(pkgName); + context_->authUiStateMgr->UnRegisterUiStateCallback(sessionName); return DM_OK; } -int32_t AuthManager::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) +int32_t AuthManager::UnAuthenticateDevice(const std::string &sessionName, const std::string &udid, int32_t bindLevel) { // todo LOGI("AuthManager::UnAuthenticateDevice start"); return ERR_DM_FAILED; } -int32_t AuthManager::ImportAuthCode(const std::string &pkgName, const std::string &authCode) +int32_t AuthManager::ImportAuthCode(const std::string &sessionName, const std::string &authCode) { - if (authCode.empty() || pkgName.empty()) { - LOGE("ImportAuthCode failed, authCode or pkgName is empty"); + if (authCode.empty() || sessionName.empty()) { + LOGE("ImportAuthCode failed, authCode or sessionName is empty"); return ERR_DM_INPUT_PARA_INVALID; } context_->importAuthCode = authCode; - context_->importPkgName = pkgName; + context_->importPkgName = sessionName; return DM_OK; } -int32_t AuthManager::UnBindDevice(const std::string &pkgName, const std::string &udid, +int32_t AuthManager::UnBindDevice(const std::string &sessionName, const std::string &udid, int32_t bindLevel, const std::string &extra) { // todo LOGI("AuthManager::UnBindDevice start"); return ERR_DM_FAILED; } -int32_t AuthManager::StopAuthenticateDevice(const std::string &pkgName) +int32_t AuthManager::StopAuthenticateDevice(const std::string &sessionName) { - (void)pkgName; + (void)sessionName; LOGI("AuthManager::StopAuthenticateDevice start"); context_->reason = STOP_BIND; @@ -280,7 +280,7 @@ void AuthManager::HandleDeviceNotTrust(const std::string &udid) // todo LOGI("AuthManager::HandleDeviceNotTrust start"); } -int32_t AuthManager::DeleteGroup(const std::string &pkgName, const std::string &deviceId) +int32_t AuthManager::DeleteGroup(const std::string &sessionName, const std::string &deviceId) { // todo LOGI("AuthManager::DeleteGroup start"); @@ -388,20 +388,20 @@ bool AuthManager::IsAuthTypeSupported(const int32_t &authType) return true; } -bool AuthManager::IsAuthCodeReady(const std::string &pkgName) +bool AuthManager::IsAuthCodeReady(const std::string &sessionName) { if (context_->importAuthCode.empty() || context_->importPkgName.empty()) { LOGE("AuthManager::IsAuthCodeReady, auth code not ready."); return false; } - if (pkgName != context_->importPkgName) { - LOGE("IsAuthCodeReady failed, pkgName not supported."); + if (sessionName != context_->importPkgName) { + LOGE("IsAuthCodeReady failed, sessionName not supported."); return false; } return true; } -int32_t AuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t authType, +int32_t AuthManager::CheckAuthParamVaild(const std::string &sessionName, int32_t authType, const std::string &deviceId, const std::string &extra) { LOGI("AuthManager::CheckAuthParamVaild start."); @@ -409,9 +409,9 @@ int32_t AuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t aut LOGE("CheckAuthParamVaild failed, authType is illegal."); return ERR_DM_AUTH_FAILED; } - if (pkgName.empty() || deviceId.empty()) { - LOGE("AuthManager::CheckAuthParamVaild failed, pkgName is %{public}s, deviceId is %{public}s, extra is" - "%{public}s.", pkgName.c_str(), GetAnonyString(deviceId).c_str(), extra.c_str()); + if (sessionName.empty() || deviceId.empty()) { + LOGE("AuthManager::CheckAuthParamVaild failed, sessionName is %{public}s, deviceId is %{public}s, extra is" + "%{public}s.", sessionName.c_str(), GetAnonyString(deviceId).c_str(), extra.c_str()); return ERR_DM_INPUT_PARA_INVALID; } if (context_->listener == nullptr || context_->authUiStateMgr == nullptr) { @@ -437,7 +437,7 @@ int32_t AuthManager::CheckAuthParamVaild(const std::string &pkgName, int32_t aut return ERR_DM_INPUT_PARA_INVALID; } - if ((authType == AUTH_TYPE_IMPORT_AUTH_CODE) && (!IsAuthCodeReady(pkgName))) { + if ((authType == AUTH_TYPE_IMPORT_AUTH_CODE) && (!IsAuthCodeReady(sessionName))) { LOGE("Auth code not exist."); context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); @@ -519,11 +519,11 @@ void AuthManager::ParseJsonObject(nlohmann::json jsonObject) if (IsString(jsonObject, TAG_PEER_BUNDLE_NAME)) { context_->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].get(); if (context_->accessee.bundleName == "") { - context_->accessee.bundleName = context_->pkgName; + context_->accessee.bundleName = context_->sessionName; } LOGI("ParseJsonObject accessee bundleName = %{public}s", context_->accessee.bundleName.c_str()); } else { - context_->accessee.bundleName = context_->pkgName; + context_->accessee.bundleName = context_->sessionName; } ParseHmlInfoInJsonObject(jsonObject); @@ -555,15 +555,15 @@ int32_t AuthManager::GetBindLevel(int32_t bindLevel) return bindLevel; } -void AuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, +void AuthManager::GetAuthParam(const std::string &sessionName, int32_t authType, const std::string &deviceId, const std::string &extra) { LOGI("Get auth param."); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localDeviceId); - context_->pkgName = pkgName; - context_->pkgLabel = GetBundleLable(pkgName); + context_->sessionName = sessionName; + context_->pkgLabel = GetBundleLable(sessionName); context_->authType = (DmAuthType)authType; context_->accesser.deviceName = context_->softbusConnector->GetLocalDeviceName(); context_->accesser.deviceType = context_->softbusConnector->GetLocalDeviceTypeId(); @@ -590,7 +590,7 @@ void AuthManager::GetAuthParam(const std::string &pkgName, int32_t authType, context_->accesser.bindLevel = this->GetBindLevel(context_->accesser.bindLevel); } -void AuthManager::InitAuthState(const std::string &pkgName, int32_t authType, +void AuthManager::InitAuthState(const std::string &sessionName, int32_t authType, const std::string &deviceId, const std::string &extra) { auto iter = context_->authenticationMap.find(authType); @@ -611,7 +611,7 @@ void AuthManager::InitAuthState(const std::string &pkgName, int32_t authType, DmAuthState::HandleAuthenticateTimeout(context_, name); }); context_->authMessageProcessor = std::make_shared(); - GetAuthParam(pkgName, authType, deviceId, extra); + GetAuthParam(sessionName, authType, deviceId, extra); context_->authStateMachine = std::make_shared(context_); context_->authStateMachine->TransitionTo(std::make_shared()); LOGI("AuthManager::AuthenticateDevice complete"); @@ -619,16 +619,16 @@ void AuthManager::InitAuthState(const std::string &pkgName, int32_t authType, return; } -int32_t AuthManager::AuthenticateDevice(const std::string &pkgName, int32_t authType, +int32_t AuthManager::AuthenticateDevice(const std::string &sessionName, int32_t authType, const std::string &deviceId, const std::string &extra) { LOGI("AuthManager::AuthenticateDevice start auth type %{public}d.", authType); SetAuthType(authType); int32_t userId = -1; MultipleUserConnector::GetCallerUserId(userId); - context_->processInfo.pkgName = pkgName; + context_->processInfo.sessionName = sessionName; context_->processInfo.userId = userId; - int32_t ret = CheckAuthParamVaild(pkgName, authType, deviceId, extra); + int32_t ret = CheckAuthParamVaild(sessionName, authType, deviceId, extra); if (ret != DM_OK) { LOGE("AuthManager::AuthenticateDevice failed, param is invaild."); return ret; @@ -649,14 +649,14 @@ int32_t AuthManager::AuthenticateDevice(const std::string &pkgName, int32_t auth // DM_OK, STATUS_DM_AUTH_DEFAULT, ""); // return DM_OK; // } - InitAuthState(pkgName, authType, deviceId, extra); + InitAuthState(sessionName, authType, deviceId, extra); return DM_OK; } -int32_t AuthManager::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, +int32_t AuthManager::BindTarget(const std::string &sessionName, const PeerTargetId &targetId, const std::map &bindParam) { - LOGI("AuthManager::BindTarget start. pkgName: %{public}s", pkgName.c_str()); + LOGI("AuthManager::BindTarget start. sessionName: %{public}s", sessionName.c_str()); for (auto iter = bindParam.begin(); iter != bindParam.end(); iter++) { LOGI("AuthManager::BindTarget para: %{public}s : %{public}s ", iter->first.c_str(), iter->second.c_str()); } @@ -669,8 +669,8 @@ int32_t AuthManager::BindTarget(const std::string &pkgName, const PeerTargetId & if (!DmRadarHelper::GetInstance().ReportDiscoverUserRes(info)) { LOGE("ReportDiscoverUserRes failed"); } - if (pkgName.empty()) { - LOGE("AuthManager::BindTarget failed, pkgName is empty."); + if (sessionName.empty()) { + LOGE("AuthManager::BindTarget failed, sessionName is empty."); return ERR_DM_INPUT_PARA_INVALID; } int32_t authType = -1; @@ -685,9 +685,9 @@ int32_t AuthManager::BindTarget(const std::string &pkgName, const PeerTargetId & addrType = bindParam.at(PARAM_KEY_CONN_ADDR_TYPE); } if (ParseConnectAddr(targetId, deviceId, addrType) == DM_OK) { - return AuthenticateDevice(pkgName, authType, deviceId, ParseExtraFromMap(bindParam)); + return AuthenticateDevice(sessionName, authType, deviceId, ParseExtraFromMap(bindParam)); } else if (!targetId.deviceId.empty()) { - return AuthenticateDevice(pkgName, authType, targetId.deviceId, ParseExtraFromMap(bindParam)); + return AuthenticateDevice(sessionName, authType, targetId.deviceId, ParseExtraFromMap(bindParam)); } else { LOGE("AuthManager::BindTarget failed, targetId is error."); return ERR_DM_INPUT_PARA_INVALID; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 46af56964..49bcc8974 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -126,7 +126,7 @@ int32_t AuthSinkConfirmState::ShowConfigDialog(std::shared_ptr co jsonObj[TAG_CUSTOM_DESCRIPTION] = context->customData; jsonObj[TAG_LOCAL_DEVICE_TYPE] = context->accesser.deviceType; jsonObj[TAG_REQUESTER] = context->accesser.deviceName; - jsonObj[TAG_HOST_PKGLABEL] = context->pkgName; + jsonObj[TAG_HOST_PKGLABEL] = context->sessionName; const std::string params = SafetyDump(jsonObj); DmDialogManager::GetInstance().ShowConfirmDialog(params); diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 3dc00ef82..a097ac738 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -840,7 +840,7 @@ int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const nlohmann::json context->accesser.deviceName = json[TAG_DEVICE_NAME].get(); } if (IsString(json, TAG_PKG_NAME)) { - context->pkgName = json[TAG_PKG_NAME].get(); + context->sessionName = json[TAG_PKG_NAME].get(); } if (IsString(json, APP_THUMBNAIL)) { context->appThumbnail = json[APP_THUMBNAIL].get(); @@ -900,7 +900,7 @@ void DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptrcustomData; json[TAG_DEVICE_TYPE] = context->accesser.deviceType; json[TAG_DEVICE_NAME] = context->accesser.deviceName; - json[TAG_PKG_NAME] = context->pkgName; + json[TAG_PKG_NAME] = context->sessionName; json[APP_THUMBNAIL] = context->appThumbnail; } @@ -1224,7 +1224,7 @@ int32_t DmAuthMessageProcessor::GetAclListStr(std::shared_ptr &co std::string accesserStr = AccesserToStr(item); Crypto::DmGenerateStrHash(accesserStr.data(), accesserStr.size(), accesserHash, DM_HASH_LEN, 0); accceserStrList.push_back(reinterpret_cast(accesserHash)); - + uint8_t accesseeHash[DM_HASH_LEN] = {0}; std::string accesseeStr = AccesseeToStr(item); Crypto::DmGenerateStrHash(accesseeStr.data(), accesseeStr.size(), accesseeHash, DM_HASH_LEN, 0); -- Gitee From 78998145715cbbee1e9d5daeebcbf38d12655a73 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 11 Mar 2025 15:06:11 +0800 Subject: [PATCH 173/382] authentication_v2 pkgName => sessionName revert processInfo.pkgName --- services/implementation/src/authentication_v2/auth_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 84245d1b5..fc815a6eb 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -626,7 +626,7 @@ int32_t AuthManager::AuthenticateDevice(const std::string &sessionName, int32_t SetAuthType(authType); int32_t userId = -1; MultipleUserConnector::GetCallerUserId(userId); - context_->processInfo.sessionName = sessionName; + context_->processInfo.pkgName = sessionName; context_->processInfo.userId = userId; int32_t ret = CheckAuthParamVaild(sessionName, authType, deviceId, extra); if (ret != DM_OK) { -- Gitee From 550b89bf1678d450b48b582f49e5a041051987c6 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Tue, 11 Mar 2025 15:06:32 +0800 Subject: [PATCH 174/382] =?UTF-8?q?=E8=A1=A5=E5=85=85getacl=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3=E5=AF=B9=E5=A4=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../implementation/include/authentication_v2/auth_manager.h | 3 +++ .../implementation/src/authentication_v2/auth_manager.cpp | 5 +++++ 2 files changed, 8 insertions(+) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 43dd5b393..31b9de9b4 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -132,6 +132,9 @@ public: std::shared_ptr GetAuthContext(); static bool IsHmlSessionType(std::string sessionType); + // 提取本端ACL 用于消息解析和总线使用 无ACL会返回空字符串 json格式字符串:{dmversion:x,accesser:[{accesserDeviceId:y,...},...],accessee:{...}} + int32_t GetAclListStr(std::string &aclList); + protected: // 上下文(需在该层级进行创建) std::shared_ptr context_; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 929b49f6d..385b22129 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -297,6 +297,11 @@ int32_t AuthManager::RegisterAuthenticationType(int32_t authenticationType) return DM_OK; } +int32_t AuthManager::GetAclListStr(std::string &aclList) +{ + return context_->authMessageProcessor->GetAclListStr(context_, aclList); +} + // 保存秘钥 void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) { -- Gitee From 81cce0968364f94b11320c7bb28d0760eb28dd10 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Tue, 11 Mar 2025 15:16:57 +0800 Subject: [PATCH 175/382] =?UTF-8?q?BUGFIX:=E6=A0=B9=E6=8D=AE=E5=AF=B9?= =?UTF-8?q?=E9=BD=90=E6=84=8F=E8=A7=81=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 3dc00ef82..96b90d8ae 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1101,7 +1101,9 @@ std::string DmAuthMessageProcessor::AccesserToStr(DistributedDeviceProfile::Acce jsonAccesserObj[DM_TAG_ACCESSER_USER_ID] = accesser.GetAccesserUserId(); jsonAccesserObj[DM_TAG_ACCESSER_ACOUNT_ID] = accesser.GetAccesserAccountId(); jsonAccesserObj[DM_TAG_ACCESSER_TOKEN_ID] = accesser.GetAccesserTokenId(); - jsonAccesserObj[DM_TAG_ACCESSER_DEVICE_NAME] = accesser.GetAccesserDeviceName(); + std::string deviceId; + accesser.GetAccesserDeviceId(deviceId); // void接口 + jsonAccesserObj[DM_TAG_ACCESSER_DEVICE_NAME] = deviceId; jsonAccesserObj[DM_TAG_ACCESSER_BUNDLE_NAME] = accesser.GetAccesserBundleName(); jsonAccesserObj[DM_TAG_ACCESSER_HAP_SIGNATURE] = accesser.GetAccesserHapSignature(); jsonAccesserObj[DM_TAG_ACCESSER_BIND_LEVEL] = accesser.GetAccesserBindLevel(); @@ -1120,6 +1122,9 @@ std::string DmAuthMessageProcessor::AccesseeToStr(DistributedDeviceProfile::Acce jsonAccesseeObj[DM_TAG_ACCESSEE_USER_ID] = accessee.GetAccesseeUserId(); jsonAccesseeObj[DM_TAG_ACCESSEE_ACOUNT_ID] = accessee.GetAccesseeAccountId(); jsonAccesseeObj[DM_TAG_ACCESSEE_TOKEN_ID] = accessee.GetAccesseeTokenId(); + std::string deviceId; + accessee.GetAccesseeDeviceId(deviceId); // void接口 + jsonAccesserObj[DM_TAG_ACCESSEE_DEVICE_NAME] = deviceId; jsonAccesseeObj[DM_TAG_ACCESSEE_DEVICE_NAME] = accessee.GetAccesseeDeviceName(); jsonAccesseeObj[DM_TAG_ACCESSEE_BUNDLE_NAME] = accessee.GetAccesseeBundleName(); jsonAccesseeObj[DM_TAG_ACCESSEE_HAP_SIGNATURE] = accessee.GetAccesseeHapSignature(); -- Gitee From cffdf7785872b553d401ca78e396354c0c5c58cd Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 11 Mar 2025 15:20:09 +0800 Subject: [PATCH 176/382] tmp --- .../dm_auth_message_processor.h | 2 +- .../dm_auth_message_processor.cpp | 18 +++--------------- 2 files changed, 4 insertions(+), 16 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 159ba9be3..90f9d6db9 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -79,7 +79,7 @@ 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_PKG_NAME = "sessionName"; +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"; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index a097ac738..05b56da7e 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -827,23 +827,14 @@ int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const nlohmann::json context->authType = static_cast(json[TAG_AUTH_TYPE].get()); } - if (IsString(json, APP_OPERATION_KEY)) { - context->appOperation = json[APP_OPERATION_KEY].get(); - } - if (IsString(json, CUSTOM_DESCRIPTION_KEY)) { - context->customData = json[CUSTOM_DESCRIPTION_KEY].get(); - } if (IsInt32(json, TAG_DEVICE_TYPE)) { context->accesser.deviceType = json[TAG_AUTH_TYPE].get(); } if (IsString(json, TAG_DEVICE_NAME)) { context->accesser.deviceName = json[TAG_DEVICE_NAME].get(); } - if (IsString(json, TAG_PKG_NAME)) { - context->sessionName = json[TAG_PKG_NAME].get(); - } - if (IsString(json, APP_THUMBNAIL)) { - context->appThumbnail = json[APP_THUMBNAIL].get(); + if (IsString(json, TAG_SESSION_NAME)) { + context->sessionName = json[TAG_SESSION_NAME].get(); } context->authStateMachine->TransitionTo(std::make_shared()); @@ -896,12 +887,9 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate(const nlohmann:: void DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, nlohmann::json &json) { json[TAG_AUTH_TYPE] = context->authType; - json[APP_OPERATION_KEY] = context->appOperation; - json[CUSTOM_DESCRIPTION_KEY] = context->customData; json[TAG_DEVICE_TYPE] = context->accesser.deviceType; json[TAG_DEVICE_NAME] = context->accesser.deviceName; - json[TAG_PKG_NAME] = context->sessionName; - json[APP_THUMBNAIL] = context->appThumbnail; + json[TAG_SESSION_NAME] = context->sessionName; } void DmAuthMessageProcessor::CreateMessageRespUserConfirm(std::shared_ptr context, nlohmann::json &json) -- Gitee From c82ad95794969e09b2aef2a1d8b9df7c2cdae0a6 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Tue, 11 Mar 2025 15:20:53 +0800 Subject: [PATCH 177/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 96b90d8ae..85b21bc86 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1101,9 +1101,7 @@ std::string DmAuthMessageProcessor::AccesserToStr(DistributedDeviceProfile::Acce jsonAccesserObj[DM_TAG_ACCESSER_USER_ID] = accesser.GetAccesserUserId(); jsonAccesserObj[DM_TAG_ACCESSER_ACOUNT_ID] = accesser.GetAccesserAccountId(); jsonAccesserObj[DM_TAG_ACCESSER_TOKEN_ID] = accesser.GetAccesserTokenId(); - std::string deviceId; - accesser.GetAccesserDeviceId(deviceId); // void接口 - jsonAccesserObj[DM_TAG_ACCESSER_DEVICE_NAME] = deviceId; + jsonAccesserObj[DM_TAG_ACCESSER_DEVICE_NAME] = accesser.GetAccesserDeviceId();; jsonAccesserObj[DM_TAG_ACCESSER_BUNDLE_NAME] = accesser.GetAccesserBundleName(); jsonAccesserObj[DM_TAG_ACCESSER_HAP_SIGNATURE] = accesser.GetAccesserHapSignature(); jsonAccesserObj[DM_TAG_ACCESSER_BIND_LEVEL] = accesser.GetAccesserBindLevel(); @@ -1122,9 +1120,7 @@ std::string DmAuthMessageProcessor::AccesseeToStr(DistributedDeviceProfile::Acce jsonAccesseeObj[DM_TAG_ACCESSEE_USER_ID] = accessee.GetAccesseeUserId(); jsonAccesseeObj[DM_TAG_ACCESSEE_ACOUNT_ID] = accessee.GetAccesseeAccountId(); jsonAccesseeObj[DM_TAG_ACCESSEE_TOKEN_ID] = accessee.GetAccesseeTokenId(); - std::string deviceId; - accessee.GetAccesseeDeviceId(deviceId); // void接口 - jsonAccesserObj[DM_TAG_ACCESSEE_DEVICE_NAME] = deviceId; + jsonAccesserObj[DM_TAG_ACCESSEE_DEVICE_NAME] = accessee.GetAccesseeDeviceId(); jsonAccesseeObj[DM_TAG_ACCESSEE_DEVICE_NAME] = accessee.GetAccesseeDeviceName(); jsonAccesseeObj[DM_TAG_ACCESSEE_BUNDLE_NAME] = accessee.GetAccesseeBundleName(); jsonAccesseeObj[DM_TAG_ACCESSEE_HAP_SIGNATURE] = accessee.GetAccesseeHapSignature(); -- Gitee From 7c66c5250364657af266ab87a6da59b7fe52e882 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Tue, 11 Mar 2025 15:27:52 +0800 Subject: [PATCH 178/382] =?UTF-8?q?BUGFIX=EF=BC=9A=E4=BF=AE=E6=94=B9servic?= =?UTF-8?q?ename=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/dm_auth_message_processor.h | 4 ++-- .../src/authentication_v2/dm_auth_message_processor.cpp | 5 ++--- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index ba5e65071..03accb4a9 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -97,7 +97,7 @@ 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_DEVICE_NAME = "accesserDeviceName"; +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"; @@ -111,7 +111,7 @@ 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_DEVICE_NAME = "accesseeDeviceName"; +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"; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 85b21bc86..a9d6ffa5b 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1101,7 +1101,7 @@ std::string DmAuthMessageProcessor::AccesserToStr(DistributedDeviceProfile::Acce jsonAccesserObj[DM_TAG_ACCESSER_USER_ID] = accesser.GetAccesserUserId(); jsonAccesserObj[DM_TAG_ACCESSER_ACOUNT_ID] = accesser.GetAccesserAccountId(); jsonAccesserObj[DM_TAG_ACCESSER_TOKEN_ID] = accesser.GetAccesserTokenId(); - jsonAccesserObj[DM_TAG_ACCESSER_DEVICE_NAME] = accesser.GetAccesserDeviceId();; + jsonAccesserObj[DM_TAG_ACCESSER_SERVICE_NAME] = {}; // 预留字段 DP库未适配 jsonAccesserObj[DM_TAG_ACCESSER_BUNDLE_NAME] = accesser.GetAccesserBundleName(); jsonAccesserObj[DM_TAG_ACCESSER_HAP_SIGNATURE] = accesser.GetAccesserHapSignature(); jsonAccesserObj[DM_TAG_ACCESSER_BIND_LEVEL] = accesser.GetAccesserBindLevel(); @@ -1120,8 +1120,7 @@ std::string DmAuthMessageProcessor::AccesseeToStr(DistributedDeviceProfile::Acce jsonAccesseeObj[DM_TAG_ACCESSEE_USER_ID] = accessee.GetAccesseeUserId(); jsonAccesseeObj[DM_TAG_ACCESSEE_ACOUNT_ID] = accessee.GetAccesseeAccountId(); jsonAccesseeObj[DM_TAG_ACCESSEE_TOKEN_ID] = accessee.GetAccesseeTokenId(); - jsonAccesserObj[DM_TAG_ACCESSEE_DEVICE_NAME] = accessee.GetAccesseeDeviceId(); - jsonAccesseeObj[DM_TAG_ACCESSEE_DEVICE_NAME] = accessee.GetAccesseeDeviceName(); + jsonAccesserObj[DM_TAG_ACCESSEE_SERVICE_NAME] = {}; // 预留字段 DP库未适配 jsonAccesseeObj[DM_TAG_ACCESSEE_BUNDLE_NAME] = accessee.GetAccesseeBundleName(); jsonAccesseeObj[DM_TAG_ACCESSEE_HAP_SIGNATURE] = accessee.GetAccesseeHapSignature(); jsonAccesseeObj[DM_TAG_ACCESSEE_BIND_LEVEL] = accessee.GetAccesseeBindLevel(); -- Gitee From f093a216b1ccaf711fcea8f79c94dd450f463159 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Tue, 11 Mar 2025 15:31:58 +0800 Subject: [PATCH 179/382] =?UTF-8?q?BUGFIX:=E4=BF=AE=E6=94=B9=E7=BC=96?= =?UTF-8?q?=E8=AF=91=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index c9b38d07a..7a9b2843c 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1108,7 +1108,7 @@ std::string DmAuthMessageProcessor::AccesseeToStr(DistributedDeviceProfile::Acce jsonAccesseeObj[DM_TAG_ACCESSEE_USER_ID] = accessee.GetAccesseeUserId(); jsonAccesseeObj[DM_TAG_ACCESSEE_ACOUNT_ID] = accessee.GetAccesseeAccountId(); jsonAccesseeObj[DM_TAG_ACCESSEE_TOKEN_ID] = accessee.GetAccesseeTokenId(); - jsonAccesserObj[DM_TAG_ACCESSEE_SERVICE_NAME] = {}; // 预留字段 DP库未适配 + jsonAccesseeObj[DM_TAG_ACCESSEE_SERVICE_NAME] = {}; // 预留字段 DP库未适配 jsonAccesseeObj[DM_TAG_ACCESSEE_BUNDLE_NAME] = accessee.GetAccesseeBundleName(); jsonAccesseeObj[DM_TAG_ACCESSEE_HAP_SIGNATURE] = accessee.GetAccesseeHapSignature(); jsonAccesseeObj[DM_TAG_ACCESSEE_BIND_LEVEL] = accessee.GetAccesseeBindLevel(); -- Gitee From 28523a818c8753e0931d15e65c614c3cf5b22824 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Wed, 12 Mar 2025 09:27:15 +0800 Subject: [PATCH 180/382] =?UTF-8?q?feat:=20=E5=AE=8C=E6=88=9090=E6=8A=A5?= =?UTF-8?q?=E6=96=87=E8=A7=A3=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/auth_manager.h | 4 +- .../authentication_v2/dm_auth_context.h | 5 +- .../dm_auth_message_processor.h | 6 +- .../dependency/softbus/softbus_connector.h | 1 + .../src/authentication_v2/auth_manager.cpp | 48 ++-- .../auth_stages/auth_negotiate.cpp | 257 +++++++++++------- .../dm_auth_message_processor.cpp | 35 ++- .../dm_auth_state_machine.cpp | 5 + .../hichain/hichain_auth_connector.cpp | 1 + .../dependency/softbus/softbus_connector.cpp | 11 +- .../src/device_manager_service_impl.cpp | 6 +- 11 files changed, 237 insertions(+), 142 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 5515ffdea..ac8a28d6e 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -36,6 +36,8 @@ const int32_t WAIT_REQUEST_TIMEOUT = 10; const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; const int32_t HML_SESSION_TIMEOUT = 10; const int32_t AUTHENTICATE_TIMEOUT = 120; +constexpr const char* DM_VERSION_5_0_1 = "5.0.1"; +constexpr const char* DM_VERSION_5_0_4 = "5.0.4"; constexpr const char* DM_VERSION_5_1_0 = "5.1.0"; constexpr const char* BUNDLE_NAME_KEY = "bundleName"; @@ -126,11 +128,11 @@ public: int32_t RegisterAuthenticationType(int32_t authenticationType); // 对外API 实现 end - // AuthManager 内部使用的接口 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); // 提取本端ACL 用于消息解析和总线使用 无ACL会返回空字符串 json格式字符串:{dmversion:x,accesser:[{accesserDeviceId:y,...},...],accessee:{...}} int32_t GetAclListStr(std::string &aclList); diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 1b1b69bc5..233238802 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -102,14 +102,14 @@ struct DmAccess { int32_t deviceType; // PC、mobile、手表、大屏等类型,为业务透传的数据,无需自定义 std::string deviceId; // A->B, 无论是A端还是B端,Accesser对象都存A端的deviceId,Accessee对象都存B端的deviceId std::string deviceIdHash; - std::string addr; // Q: 旧协议有用到addr,新设计没有,需要确认 + std::string addr; int32_t userId; std::string userIdHash; std::string accountId; std::string accountIdHash; uint64_t tokenId; std::string tokenIdHash; - std::string token; // Q: 旧协议有用到token,新设计没有,需要确认 + std::string token; std::string networkId; std::string bundleName; // 存PacketName int64_t serviceId; // 保留字段,后续会使用 @@ -132,6 +132,7 @@ struct DmAccess { bool isAuthed; bool isOnline; std::string dmVersion; // 版本 5.1.0 + std::string edition; // 用于5.1.0版本前的兼容,协助版本协商 std::string aclList; //可信关系列表,用于数据老化 KV格式 std::vector aclChecksumList; // 可信关系列表,用于数据老化 std::string credentialInfos; //凭据信息(点对点,同账号,..) 只保存凭据类型 kv结构 diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 806585c45..6f3aac3f6 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -51,9 +51,9 @@ 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_TOKEN_ID = "tokenId"; constexpr const char *DM_TAG_SYNC = "syncMessage"; constexpr const char *DM_TAG_DMVERSION = "dmVersion"; +constexpr const char *DM_TAG_EDITION = "edition"; constexpr const char *DM_TAG_ACCESS = "dmAccess"; constexpr const char *DM_TAG_PROXY = "proxy"; constexpr const char *DM_TAG_ACL = "accessControlTable"; @@ -65,6 +65,7 @@ constexpr const char *DM_TAG_USER_SK_ID = "accessUserSKId"; constexpr const char *DM_TAG_APP_SK_TIMESTAMP = "accessAppSKTimeStamp"; constexpr const char *DM_TAG_USER_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_OPERATION_KEY = "appOperation"; @@ -86,6 +87,9 @@ 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"; diff --git a/services/implementation/include/dependency/softbus/softbus_connector.h b/services/implementation/include/dependency/softbus/softbus_connector.h index 0d759f901..a277e763f 100644 --- a/services/implementation/include/dependency/softbus/softbus_connector.h +++ b/services/implementation/include/dependency/softbus/softbus_connector.h @@ -111,6 +111,7 @@ public: void HandleDeviceOffline(std::string deviceId); void SetProcessInfo(ProcessInfo processInfo); bool CheckIsOnline(const std::string &targetDeviceId); + bool CheckIsOnline(const std::string &targetDeviceIdHash, bool isHash); void SetProcessInfoVec(std::vector processInfoVec); std::vector GetProcessInfo(); void ClearProcessInfo(); diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 85d85613b..1287fce96 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -495,9 +495,6 @@ void AuthManager::ParseJsonObject(nlohmann::json jsonObject) return; } - // 由于旧协议中没怎么用,新协议的设计也没有该字段 - // 故废弃了targetPkgName - // 填充context_ if (IsString(jsonObject, APP_OPERATION_KEY)) { context_->appOperation = jsonObject[APP_OPERATION_KEY].get(); @@ -560,6 +557,19 @@ int32_t AuthManager::GetBindLevel(int32_t bindLevel) return bindLevel; } +int32_t AuthManager::GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId) +{ + int32_t ret = AppManager::GetInstance().GetNativeTokenIdByName(bundleName, tokenId); + if (ret == DM_OK) { + return DM_OK; + } + ret = AppManager::GetInstance().GetHapTokenIdByName(userId, bundleName, 0, tokenId); + if (ret != DM_OK) { + LOGE("get tokenId by bundleName failed %{public}s", GetAnonyString(bundleName).c_str()); + } + return ret; +} + void AuthManager::GetAuthParam(const std::string &sessionName, int32_t authType, const std::string &deviceId, const std::string &extra) { @@ -567,16 +577,22 @@ void AuthManager::GetAuthParam(const std::string &sessionName, int32_t authType, char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localDeviceId); + std::string realPkgName = GetSubStr(sessionName, PICKER_PROXY_SPLIT, 1); + realPkgName = realPkgName.empty() ? sessionName : realPkgName; context_->sessionName = sessionName; context_->pkgLabel = GetBundleLable(sessionName); context_->authType = (DmAuthType)authType; context_->accesser.deviceName = context_->softbusConnector->GetLocalDeviceName(); context_->accesser.deviceType = context_->softbusConnector->GetLocalDeviceTypeId(); context_->accesser.deviceId = localUdid; - context_->accesser.dmVersion = DM_VERSION_5_1_0; uint32_t tokenId = 0 ; MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, context_->accesser.userId); - context_->accesser.tokenId = static_cast(tokenId); + context_->accesser.tokenId = static_cast(tokenId); + if (realPkgName != sessionName) { + int64_t tmpTokenId = 0; + GetTokenIdByBundleName(context_->accesser.userId, realPkgName, tmpTokenId); + context_->accesser.tokenId = static_cast(tmpTokenId); + } context_->accesser.accountId = MultipleUserConnector::GetOhosAccountIdByUserId(context_->accesser.userId); context_->accesser.isOnline = false; context_->accesser.isAuthed = !context_->accesser.bindType.empty(); @@ -603,10 +619,10 @@ void AuthManager::InitAuthState(const std::string &sessionName, int32_t authType context_->authPtr = iter->second; } - if (authType > AUTH_TYPE_IMPORT_AUTH_CODE || authType < AUTH_TYPE_PIN) { - LOGE("AuthManager::InitAuthState invalid authType"); - return; - } + // if (authType > AUTH_TYPE_IMPORT_AUTH_CODE || authType < AUTH_TYPE_PIN) { + // LOGE("AuthManager::InitAuthState invalid authType"); + // return; + // } if (context_->timer == nullptr) { context_->timer = std::make_shared(); @@ -752,12 +768,7 @@ void AuthSinkManager::OnDataReceived(int32_t sessionId, std::string message) bool AuthSinkManager::GetIsCryptoSupport() { - if (context_->authStateMachine->GetCurState() != DmAuthStateType::AUTH_SINK_FINISH_STATE) { - return false; - } - - // TODO: 当前是否还需要isCryptoSupport_,还是说通过已经没有TAG_CRYPTO_SUPPORT了 - return true; + return false; } void AuthSinkManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string message) @@ -883,12 +894,7 @@ void AuthSrcManager::OnDataReceived(int32_t sessionId, std::string message) } bool AuthSrcManager::GetIsCryptoSupport() { - if (context_->authStateMachine->GetCurState() != DmAuthStateType::AUTH_SRC_FINISH_STATE) { - return false; - } - - // TODO: 当前是否还需要isCryptoSupport_,还是说通过已经没有TAG_CRYPTO_SUPPORT了 - return true; + return false; } void AuthSrcManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string message) { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 115040259..507e83e57 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -22,6 +22,7 @@ #include "hap_token_info.h" #include "deviceprofile_connector.h" #include "device_auth.h" +#include "accesstoken_kit.h" #include "access_control_profile.h" #include "accesser.h" #include "accessee.h" @@ -35,12 +36,56 @@ #include "dm_auth_context.h" #include "auth_manager.h" #include "dm_auth_state.h" + +#ifdef OS_ACCOUNT_PART_EXISTS +#include "os_account_manager.h" +using namespace OHOS::AccountSA; +#endif // OS_ACCOUNT_PART_EXISTS + +using namespace OHOS::Security::AccessToken; + #undef LOG_TAG #define LOG_TAG "DHDM_V2" namespace OHOS { namespace DistributedHardware { +namespace { + +// security_device_auth凭据查询相关定义,保持与device_auth.h一致 +const char * const FILED_DEVICE_ID = "deviceId"; +const char * const FILED_DEVICE_ID_HASH = "deviceIdHash"; +const char * const FILED_PEER_USER_SPACE_ID = "peerUserSpaceId"; +const char * const FILED_CRED_TYPE = "credType"; +const char * const FILED_AUTHORIZED_APP_LIST = "authorizedAppList"; +const char * const FILED_AUTHORIZED_SCOPE = "authorizedScope"; + +enum DmRole { + DM_ROLE_UNKNOWN = 0, + DM_ROLE_FA_TO_FA, + DM_ROLE_FA_TO_FA_SERVICE, + DM_ROLE_SA_TO_SA, + DM_ROLE_SA_TO_SA_SERVICE, + DM_ROLE_FA_TO_DEVICE +}; + +std::string ConvertSrcVersion(const std::string &version, const std::string &edition) +{ + std::string srcVersion = ""; + if (version == "" && edition != "") { + srcVersion = edition; + } else if (version == "" && edition == "") { + srcVersion = DM_VERSION_5_0_1; + } else if (version != "" && edition == "") { + srcVersion = version; + } + LOGI("ConvertSrcVersion version %{public}s, edition %{public}s, srcVersion is %{public}s.", + version.c_str(), edition.c_str(), srcVersion.c_str()); + return srcVersion; +} + +} + DmAuthStateType AuthSrcStartState::GetStateType() { return DmAuthStateType::AUTH_SRC_START_STATE; @@ -77,7 +122,6 @@ int32_t AuthSrcStartState::Action(std::shared_ptr context) } if (sessionId < 0) { LOGE("OpenAuthSession failed, stop the authentication"); - // Q: 之前做了一系列资源创建和转换,目前看来直接返回错误即可 return ERR_DM_FAILED; } return DM_OK; @@ -92,27 +136,12 @@ int32_t AuthSrcNegotiateStateMachine::Action(std::shared_ptr cont { LOGI("AuthSrcNegotiateStateMachine::Action sessionId %{public}d.", context->sessionId); - // Q:为什么会让对端deviceId等于自己的deviceId? - // context->accessee.deviceId = context->accesser.deviceId; context->reply = ERR_DM_AUTH_REJECT; - // authType、deviceId已在BindTarget赋值 - // accountGroupIdHash已废弃,无组的概念 - // hostPkgName已废弃,直接取context的pkgName,已在初始化时赋值 - context->accessee.bundleName = context->accesser.bundleName; // 初始化时已赋值,这里是不是存在冲突? - // context的accesser和accessee的bundleName已经覆盖peerBundleName - // pkgLabel已赋值 - // tokenId已不在80报文中传输 - // bindLevel已在BindTarget赋值 - // bindType已在BindTarget赋值 - // isOnline已在BindTarget赋值 - // authed替换为isAuthed,已在BindTarget赋值 + // Q: 初始化时已赋值,此处需确认调试结果 + context->accessee.bundleName = context->accesser.bundleName; + //TODO: 传输tokenId // 为什么之前DmVersion传空? context->accessee.dmVersion = ""; - // accountId不再在80报文中传输 - // userId不再在80报文中传输 - // isIdenticalAccount不再在80报文中传输 - // edition不再在80报文中传输 - // remoteDeviceName // 计算哈希值 context->accesser.deviceIdHash = Crypto::Sha256(context->accesser.deviceId); @@ -140,61 +169,72 @@ DmAuthStateType AuthSinkNegotiateStateMachine::GetStateType() int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptr context) { int32_t ret; + int32_t dmRole = DM_ROLE_UNKNOWN; + // 1. 获取deviceId char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); context->accessee.deviceId = std::string(localDeviceId); - if (context->accesser.tokenId == 0) { - // 单用户:特征为accesser未传输tokenIdHash - // 适用于:FA-FA、SA-SA - // 当前无FA-FA_service、SA-SA_service、FA-device(bindTarget暂无peerType) - std::vector userVec; + // 2. 获取userId + std::vector userVec; + ret = MultipleUserConnector::GetForegroundUserIds(userVec); + if (ret != DM_OK) { + LOGE("RespQueryTokenId: GetForegroundUserIds failed, ret: %{public}d", ret); + return ret; + } + if (userVec.size() == 0) { + LOGE("RespQueryTokenId: GetForegroundUserIds no foreground users"); + return ERR_DM_FAILED; + } - ret = MultipleUserConnector::GetForegroundUserIds(userVec); + // 场景1:对端指定了userId -> 校验是否为前台用户 + // 场景2:对端未指定userId + // 场景2.1: 单用户 -> 使用当前唯一前台用户 + // 场景2.2: 多用户 -> 使用当前主屏用户 + if (context->accessee.userId != 0) { + if (std::find(userVec.begin(), userVec.end(), context->accessee.userId) == userVec.end()) { + LOGE("RespQueryTokenId: userId not in foreground users"); + return ERR_DM_FAILED; + } + } else if (userVec.size() == 1) { + context->accessee.userId = userVec[0]; + } else { +#ifdef OS_ACCOUNT_PART_EXISTS + ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(context->accessee.userId); if (ret != DM_OK) { - LOGE("RespQueryTokenId: GetForegroundUserIds failed, ret: %{public}d", ret); - return ret; + LOGE("RespQueryAcceseeIds: get foreground user failed in multi users with error %{public}d", ret); + return ERR_DM_FAILED; } +#else + LOGE("RespQueryAcceseeIds: get foreground user failed because no OsAcccountManager"); + return ERR_DM_FAILED; +#endif + } - context->accessee.userId = MultipleUserConnector::GetFirstForegroundUserId(); - context->accessee.accountId = MultipleUserConnector:: - GetOhosAccountIdByUserId(context->accessee.userId); + // 3. 获取accountId + context->accessee.accountId = MultipleUserConnector::GetOhosAccountIdByUserId(context->accessee.userId); - int64_t tokenId = 0; - ret = AppManager::GetInstance().GetHapTokenIdByName(context->accessee.userId, - context->accessee.bundleName, 0, tokenId); - if (ret != DM_OK) { - LOGI("RespQueryTokenId: get tokenId by bundleName failed %{public}s", - GetAnonyString(context->accessee.bundleName).c_str()); - return ret; + // 4. 获取tokenId + std::string tmpBundleName = context->accessee.bundleName.empty() ? + context->accesser.bundleName : context->accessee.bundleName; + int64_t tokenId; + ret = AppManager::GetInstance().GetHapTokenIdByName(context->accessee.userId, tmpBundleName, 0, tokenId); + if (ret != DM_OK) { + // 不传bundleName且无法获取到tokenId时,即为FA-device + if (context->accessee.bundleName.empty()) { + dmRole = DM_ROLE_FA_TO_DEVICE; + LOGI("RespQueryTokenId: FA to device"); + return DM_OK; } - context->accessee.tokenId = tokenId; - } else { - // 多用户:特征为accesser传输了tokenId - // 适用于:FA-FA多用户 - // Security::AccessToken::HapTokenInfo tokenInfo; - // TODO: tokenId涉及安全问题,暂无法在80报文中传输 - // ret = AccessTokenKit::GetHapTokenInfo(authResponseContext_->remoteTokenId, tokenInfo); - // if (ret != DM_OK) { - // LOGE("RespQueryTokenId: GetHapTokenInfo failed."); - // return ret; - // } - // authResponseContext_->localUserId = tokenInfo.userID; - // authResponseContext_->localAccountId = MultipleUserConnector:: - // GetOhosAccountIdByUserId(authResponseContext_->localUserId); - // if (ret != DM_OK) { - // LOGI("RespQueryTokenId: get tokenId by bundleName failed %{public}s", - // GetAnonyString(authResponseContext_->bundleName).c_str()); - // return ret; - // } - - // 由于前面无法传输tokenId,暂时中断 - LOGI("RespQueryTokenId: cant't transfer tokenId"); - return ERR_DM_FAILED; + LOGE("RespQueryTokenId: get tokenId by bundleName failed %{public}s", + GetAnonyString(context->accessee.bundleName).c_str()); + return ret; } + context->accessee.bundleName = tmpBundleName; + context->accessee.tokenId = static_cast(tokenId); - return ret; + return DM_OK; } bool AuthSinkNegotiateStateMachine::HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList) @@ -228,15 +268,15 @@ uint32_t AuthSinkNegotiateStateMachine::GetCredentialType(std::shared_ptraccessee.accountId) == context->accesser.accountIdHash && context->accessee.accountId != "ohosAnonymousUid") { - if (credInfo["credType"] == ACCOUNT_RELATED && credInfo["authorizedScope"] == SCOPE_USER) { + if (credInfo[FILED_CRED_TYPE] == ACCOUNT_RELATED && credInfo[FILED_AUTHORIZED_SCOPE] == SCOPE_USER) { return DM_IDENTICAL_ACCOUNT; } } else { - if (credInfo["credType"] == ACCOUNT_ACROSS && credInfo["authorizedScope"] == SCOPE_USER) { + if (credInfo[FILED_CRED_TYPE] == ACCOUNT_ACROSS && credInfo[FILED_AUTHORIZED_SCOPE] == SCOPE_USER) { return DM_ACROSS_ACCOUNT; } - if (credInfo["credType"] == ACCOUNT_UNRELATED && credInfo["authorizedScope"] == SCOPE_APP && - HaveSameTokenId(context, credInfo["authorizedAppList"]) == true) { + if (credInfo[FILED_CRED_TYPE] == ACCOUNT_UNRELATED && credInfo[FILED_AUTHORIZED_SCOPE] == SCOPE_APP && + HaveSameTokenId(context, credInfo[FILED_AUTHORIZED_APP_LIST]) == true) { return DM_POINT_TO_POINT; } } @@ -286,18 +326,21 @@ bool AuthSinkNegotiateStateMachine::AclCompareFourIds(std::shared_ptr context) { int32_t ret; + uint32_t credType; nlohmann::json queryParams; nlohmann::json queryResult; // 1. 获取所有凭据 - queryParams["deviceIdHash"] = context->accesser.deviceIdHash; - queryParams["userIdHash"] = context->accesser.userIdHash; - // 2/27会上讨论,以下字段不需要传输,只传id相关即可 - // queryParams["subject"] = 2; // 2: 配件 - // queryParams["keyFormat"] = 2; // 2: 非对称密钥公钥 - // queryParams["algorithmType"] = 4; // 4- ED25519 - // queryParams["proofType"] = 1; // 1: PSK - // queryParams["credentialOwner"] = "DM"; + // 本端deviceId、userId + 对端deviceId、userId + // 本端userId为QueryCredentialInfo第一个参数 + queryParams[FILED_DEVICE_ID] = context->accessee.deviceId; + queryParams[FILED_DEVICE_ID_HASH] = context->accesser.deviceIdHash; + queryParams[FILED_PEER_USER_SPACE_ID] = context->accesser.userIdHash; + // 同账号凭据 + if (context->accessee.accountId != "ohosAnonymousUid" && + Crypto::Sha256(context->accessee.accountId) == context->accesser.accountIdHash) { + queryParams[FILED_CRED_TYPE] = 1; // 1 - 账号相关 + } ret = context->hiChainAuthConnector->QueryCredentialInfo(context->accessee.userId, queryParams, queryResult); if (ret != DM_OK) { LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to query credential id list."); @@ -305,11 +348,21 @@ int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptr profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfile(); bool isAclActive = false; - for (auto &item : profiles) { + for (const auto &item : profiles) { auto accesser = item.GetAccesser(); auto accessee = item.GetAccessee(); @@ -319,14 +372,8 @@ int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptr invalidCredIds; nlohmann::json packResult; // 需要打包发送到对端的数据 - for (auto& [key, value] : queryResult.items()) { - if (value.find("isAclActive") == value.end() || value["isAclActive"] == false) { + for (const auto& [credId, cred] : queryResult.items()) { + if (cred.find("isAclActive") == cred.end() || cred["isAclActive"] == false) { continue; } - packResult[key] = value["credType"]; + packResult[credId] = cred[FILED_CRED_TYPE]; } context->accessee.isAuthed = !queryResult.empty(); @@ -356,23 +403,17 @@ int32_t AuthSinkNegotiateStateMachine::ProcRespNegotiate5_1_0(std::shared_ptrreply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to get all id."); return ERR_DM_FAILED; } - // 检查accesser_deviceId是否上线 - // Q: 80报文未传输accesser.deviceId,无法校验是否上线 - // context->accesser.isOnline = context->softbusConnector->CheckIsOnline(context->accesser.deviceId); - + context->accesser.isOnline = context->softbusConnector->CheckIsOnline(context->accesser.deviceIdHash, true); // 获取凭据信息 - // TODO: 暂时注释,不阻塞云瑞联调 - // ret = GetAuthCredentialInfo(context); - // if (ret != DM_OK) { - // LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to get credential."); - // context->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; - // return ERR_DM_FAILED; - // } + ret = GetAuthCredentialInfo(context); + if (ret != DM_OK) { + LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to get credential."); + return ERR_DM_FAILED; + } context->accessee.deviceIdHash = Crypto::Sha256(context->accessee.deviceId); context->accessee.userIdHash = Crypto::Sha256(std::to_string(context->accessee.userId)); @@ -398,15 +439,20 @@ int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr con GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); context->accessee.deviceId = std::string(localDeviceId); - // 解析message时,accesser.deviceId已赋值 context->accessee.networkId = context->softbusConnector->GetLocalDeviceNetworkId(); context->accessee.deviceName = context->softbusConnector->GetLocalDeviceName(); - // TODO: - // if (CompareVersion(context->accesser.dmVersion, std::string(DM_VERSION_5_1_0))) { - // LOGE("AuthSinkNegotiateStateMachine::Action incompatible version %{public}s compare to 5.1.0", - // context->accesser.dmVersion); - // return ERR_DM_VERSION_INCOMPATIBLE; - // } + // 为兼容历史版本,通过ConvertSrcVersion获取src端实际version + context->accesser.dmVersion = ConvertSrcVersion(context->accesser.dmVersion, + context->accesser.edition); + // 新协议只支持5.0.4之后的版本 + std::string preVersion = std::string(DM_VERSION_5_0_4); + LOGI("AuthSinkNegotiateStateMachine::Action start version compare %{public}s to %{public}s", + context->accesser.dmVersion.c_str(), preVersion.c_str()); + if (CompareVersion(context->accesser.dmVersion, preVersion) == false) { + LOGE("AuthSinkNegotiateStateMachine::Action incompatible version"); + context->reason = ERR_DM_VERSION_INCOMPATIBLE; + return ERR_DM_VERSION_INCOMPATIBLE; + } int32_t ret = ProcRespNegotiate5_1_0(context); if (ret != DM_OK) { @@ -415,7 +461,8 @@ int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr con } context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_ACL_NEGOTIATE, context); context->timer->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), - DmAuthState::GetTaskTimeout(context, WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), [this, context] (std::string name) { + DmAuthState::GetTaskTimeout(context, WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), + [this, context] (std::string name) { DmAuthState::HandleAuthenticateTimeout(context, name); }); return DM_OK; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 7a9b2843c..29933e1d3 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -34,8 +34,24 @@ namespace OHOS { namespace DistributedHardware { +namespace { + constexpr const char* TAG_DEVICE_TYPE = "deviceType"; +void ParseNegotiateExtraInfoMessage(nlohmann::json &jsonObject, std::shared_ptr context) +{ + // accesser在extra中传输对端peerUserId和peerDisplayId时,从中获取userId + if (IsInt32(jsonObject, DM_TAG_PEER_USER_ID)) { + context->accessee.userId = jsonObject[DM_TAG_PEER_USER_ID].get(); + } else if (IsInt32(jsonObject, DM_TAG_PEER_DISPLAY_ID)) { + context->accessee.userId = jsonObject[DM_TAG_PEER_DISPLAY_ID].get(); + } + + return; +} + +} + // 保存秘钥 int32_t DmAuthMessageProcessor::SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyLen) { @@ -144,6 +160,8 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont DmMessageType msgType = static_cast(jsonObject[TAG_MSG_TYPE].get()); context->msgType = msgType; LOGI("DmAuthMessageProcessor::ParseMessage message type %{public}d", context->msgType); + // TODO:调试信息,上库前删除 + LOGI("DmAuthMessageProcessor::ParseMessage %{public}s", SafetyDump(jsonObject).c_str()); switch (msgType) { case MSG_TYPE_REQ_ACL_NEGOTIATE: return ParseNegotiateMessage(jsonObject, context); @@ -424,7 +442,6 @@ int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr // 创建80报文 void DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject) { - // 目前未看到使用了cryptoAdapter_,删除 jsonObject[DM_TAG_DMVERSION] = context->accesser.dmVersion; jsonObject[TAG_DEVICE_NAME] = context->accesser.deviceName; @@ -436,8 +453,6 @@ void DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptraccesser.bundleName; jsonObject[TAG_PEER_BUNDLE_NAME] = context->accessee.bundleName; jsonObject[TAG_BIND_LEVEL] = context->accesser.bindLevel; - // 暂无serviceId的定义 - // tokenId、deviceId是否有安全问题?暂未传输 return; } @@ -738,10 +753,14 @@ int32_t DmAuthMessageProcessor::ParseMessageFinish(std::shared_ptr context) +int32_t DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject, + std::shared_ptr context) { - if (IsString(jsonObject, TAG_DEVICE_VERSION)) { - context->accesser.dmVersion = jsonObject[TAG_DEVICE_VERSION].get(); + if (IsString(jsonObject, DM_TAG_DMVERSION)) { + context->accesser.dmVersion = jsonObject[DM_TAG_DMVERSION].get(); + } + if (IsString(jsonObject, DM_TAG_EDITION)) { + context->accesser.edition = jsonObject[DM_TAG_EDITION].get(); } if (IsString(jsonObject, TAG_DEVICE_NAME)) { context->accesser.deviceName = jsonObject[TAG_DEVICE_NAME].get(); @@ -770,6 +789,10 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject context->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].get(); } + if (jsonObject.contains(DM_TAG_EXTRA_INFO) && jsonObject[DM_TAG_EXTRA_INFO].is_object()) { + ParseNegotiateExtraInfoMessage(jsonObject[DM_TAG_EXTRA_INFO], context); + } + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index dbe12b547..3853448e5 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -248,6 +248,11 @@ DmAuthStateType DmAuthStateMachine::GetCurState() // 检验下一状态迁移合法性 bool DmAuthStateMachine::CheckStateTransitValid(DmAuthStateType nextState) { + if (curState_ == nextState || curState_ == DmAuthStateType::AUTH_SRC_FINISH_STATE || + curState_ == DmAuthStateType::AUTH_SINK_FINISH_STATE) { + return false; + } + // 判断下一状态是否为AuthXXXFinishState,可直接切状态,返回 if (nextState == DmAuthStateType::AUTH_SRC_FINISH_STATE || nextState == DmAuthStateType::AUTH_SINK_FINISH_STATE) { return true; diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 098728c97..bdb7fa049 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -370,6 +370,7 @@ int32_t HiChainAuthConnector::QueryCredentialInfo(int32_t userId, nlohmann::json // Q: 之前都是用的ProcessCredential查询,现在是否可用queryCredentialByParams查询? ret = cm->queryCredentialByParams(userId, SafetyDump(queryParams).c_str(), &credIdList); + // TODO: 可能是空的,要返回DM_OK if (ret != DM_OK) { LOGE("HiChainAuthConnector::QueryCredentialInfo fail to query credential id list."); return ERR_DM_FAILED; diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 03296edad..c83f3f9cf 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -441,7 +441,8 @@ void SoftbusConnector::DeleteOffLineTimer(std::string &udidHash) } } -bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) +// isHash:传入的deviceId是否为哈希值 +bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceIdHash, bool isHash) { LOGI("Check the device is online."); int32_t deviceCount = 0; @@ -458,7 +459,8 @@ bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) LOGE("[SOFTBUS]GetNodeKeyInfo failed."); } std::string udid = reinterpret_cast(mUdid); - if (udid == targetDeviceId) { + if ((isHash == false && udid == targetDeviceIdHash) || + (isHash == true && Crypto::Sha256(udid).find(targetDeviceIdHash) == 0)) { LOGI("The device is online."); FreeNodeInfo(nodeInfo); return true; @@ -469,6 +471,11 @@ bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) return false; } +bool SoftbusConnector::CheckIsOnline(const std::string &targetDeviceId) +{ + return CheckIsOnline(targetDeviceId, false); +} + DmDeviceInfo SoftbusConnector::GetDeviceInfoByDeviceId(const std::string &deviceId) { LOGI("SoftbusConnector::GetDeviceInfoBydeviceId"); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 5ac777a7e..8eea0739e 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -51,11 +51,9 @@ int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide) { if (authMgr_ == nullptr) { if (isSrcSide) { - authMgr_ = std::make_shared(softbusConnector_, listener_, - hiChainAuthConnector_); + authMgr_ = std::make_shared(softbusConnector_, listener_, hiChainAuthConnector_); } else { - authMgr_ = std::make_shared(softbusConnector_, listener_, - hiChainAuthConnector_); + authMgr_ = std::make_shared(softbusConnector_, listener_, hiChainAuthConnector_); } softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); // hiChainConnector_->RegisterHiChainCallback(authMgr_); -- Gitee From 69d6056a24e97e8dee33c5d511d601ff58d07bfa Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Wed, 12 Mar 2025 10:18:42 +0800 Subject: [PATCH 181/382] new pin auth tmp --- .../authentication_v2/dm_auth_context.h | 5 +- .../dm_auth_message_processor.h | 1 + .../include/authentication_v2/dm_auth_state.h | 3 + .../auth_stages/auth_confirm.cpp | 36 ++++++++-- .../auth_stages/auth_negotiate.cpp | 68 +++++++++++++++++++ .../dm_auth_message_processor.cpp | 48 ++++++++++--- 6 files changed, 145 insertions(+), 16 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 233238802..6cae529ff 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -145,9 +145,12 @@ struct DmAuthContext { DmMessageType msgType; // 报文类型,枚举MsgType int32_t sessionId; // 总线传输会话ID int64_t requestId; // hichain认证ID + int32_t authBoxType{-1}; // 认证框类型 UiAction pinInputResult; // 输入PIN码结果 - UiAction authResult; // 授权结果(使用0、1、6,即单次,取消和始终信任,enum UiAction) + UiAction authResult{UiAction::USER_OPERATION_TYPE_ALLOW_AUTH}; // 授权结果(使用0、1、6,即单次,取消和始终信任,enum UiAction) DmAuthType authType{DmAuthType::AUTH_TYPE_PIN}; // 认证方式,弹pin码、超声pin码、导入pin码 + std::vector authTypeList; // 共有认证方式列表 + int32_t currentAuthTypeIdx{0}; // 认证方式索引 int32_t authFailTimes{0}; // 认证失败次数,查过3次结束认证 int32_t pinCode{INVALID_PINCODE}; // 生成的PIN码 int32_t connDelayCloseTime; // 链路延迟释放时间, 授权结束后不自动断链(有业务需要使用)保留字段 diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 6f3aac3f6..5b1435478 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -36,6 +36,7 @@ constexpr const char *DM_TAG_USER_CREDENTIAL_ID = "userCredentialId"; // 用户 constexpr const char *DM_TAG_APP_CREDENTIAL_ID = "appCredentialId"; // 应用级凭据Id constexpr const char *DM_TAG_ON_TRANSMIT_DATA = "onTransmitData"; // onTransmitData接口返回信息 constexpr const char *DM_TAG_AUTH_RESULT = "authResult"; // 授权结果 +constexpr const char *DM_TAG_AUTH_TYPE_LIST = "authTypeList"; // 授权类型列表 // is接口入参 json格式字符串中的key constexpr const char *DM_TAG_METHOD = "method"; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 48d13f233..ecbccba43 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -292,6 +292,9 @@ private: 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(); + void NegotiatePinAuthType(std::shared_ptr context); }; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 49bcc8974..f4b7a3fd2 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -51,6 +51,28 @@ DmAuthStateType AuthSrcConfirmState::GetStateType() return DmAuthStateType::AUTH_SRC_CONFIRM_STATE; } +void AuthSrcConfirmState::DoPinAuth(std::shared_ptr context) +{ + if (context->authTypeList.empty()) { + // no auth type goto finished + } + + auto firstAuthType = context->authTypeList[0]; + if (firstAuthType == DmAuthType::AUTH_TYPE_PIN) { + // send 100 + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_USER_CONFIRM, context); + + context->timer->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), + CONFIRM_TIMEOUT, [context] (std::string name) { + HandleAuthenticateTimeout(context, name); + }); + // 后续110 报文触发 AuthSrcPinAuthStartState + } else { + // 少一轮 100,110 + // 转 AuthSrcPinAuthStartState + } +} + int32_t AuthSrcConfirmState::Action(std::shared_ptr context) { LOGI("AuthSrcConfirmState::Action start"); @@ -75,24 +97,25 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) // 有无可信关系的分享凭据 if (g_shareByPinAuthDeviceTypeSet.contains(static_cast(context->deviceType))) { - // 走弹PIN - context->authType = DmAuthType::AUTH_TYPE_PIN; - // send 100 + // 走PIN码认证 + DoPinAuth(context); } else { // 转凭据认证 context->authStateMachine->TransitionTo(std::make_shared()); } // 有点对点可信 - if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + // if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + if (!context->authTypeList.empty() && context->authTypeList[0] == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { // 走PIN码导入 - // send 100 + DoPinAuth(context); } else { // 结束绑定 context->authStateMachine->TransitionTo(std::make_shared()); } -#endif // 无凭据 + //DoPinAuth(context); +#endif // send 100 context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_USER_CONFIRM, context); @@ -100,7 +123,6 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) CONFIRM_TIMEOUT, [context] (std::string name) { HandleAuthenticateTimeout(context, name); }); - LOGI("AuthSrcConfirmState::Action ok"); return DM_OK; } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 507e83e57..844a03e67 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -21,6 +21,7 @@ #include "app_manager.h" #include "hap_token_info.h" #include "deviceprofile_connector.h" +#include "local_service_info_manager.h" #include "device_auth.h" #include "accesstoken_kit.h" #include "access_control_profile.h" @@ -52,6 +53,12 @@ namespace DistributedHardware { namespace { +using FallBackKey = std::pair; // accessee.bundleName, authType +constexpr static std::map g_pinAuthTypeFallBackMap = { + {{"cast_engine_service", DmAuthType::AUTH_TYPE_PIN_PROMPT}, DmAuthType::AUTH_TYPE_PIN}, +}; +constexpr size_t MAX_FALLBACK_LOOPKUP_TIMES = 2; // 最大递归查找次数 + // security_device_auth凭据查询相关定义,保持与device_auth.h一致 const char * const FILED_DEVICE_ID = "deviceId"; const char * const FILED_DEVICE_ID_HASH = "deviceIdHash"; @@ -424,6 +431,66 @@ int32_t AuthSinkNegotiateStateMachine::ProcRespNegotiate5_1_0(std::shared_ptr context, DmAuthType authType) +{ + for (size_t i = 0; i < MAX_FALLBACK_LOOPKUP_TIMES; i++) { + auto it = g_pinAuthTypeFallBackMap.find({context->accessee.bundleName, authType}); + if (it != g_pinAuthTypeFallBackMap.end()) { + authType = it->second; + context->authTypeList.push_back(authType); + } else { + break; + } + } +} + +int64_t AuthSinkNegotiateStateMachine::GenRequestId() +{ + // 随机生成 PIN认证 的 requestId + int32_t part1 = GenRandInt(std::numeric_limits::min(), std::numeric_limits::max()); + int32_t part2 = GenRandInt(std::numeric_limits::min(), std::numeric_limits::max()); + uint64_t requestId = (staic_cast(part1) << 32) | staic_cast(part2); + return static_cast(requestId); +} + +void AuthSinkNegotiateStateMachine::NegotiatePinAuthType(std::shared_ptr context) +{ + context->requestId = GenRequestId(); + authTypeList.clear(); + // 根据 accessee.bundleName 和 src端 authType 查询 SP + LocalServiceInfo srvInfo; + auto ret = LocalServiceInfoManager::GetInstance().GetLocalServiceInfoByBundleAndPinType( + context->accessee.bundleName, context->authType, srvInfo); + if (ret == OHOS::DistributedDeviceProfile::DP_SUCCESS) { + context->authTypeList.push_back(context->authType); // 匹配到,则添加到候选列表 + context->authBoxType = srvInfo.GetAuthBoxType(); + + if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + // 读取PIN码 + std::string pinCode = srvInfo.GetPinCode(); + context->pinCode = std::stoi(pinCode); + } + + if (authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { // 免弹框 + int32_t authResult = srvInfo.GetAuthType(); + if (authResult == 0) { + context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH; + } else if (authResult == OHOS::DistributedDeviceProfile::NUM_1) { + context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; + } else if (authResult == OHOS::DistributedDeviceProfile::NUM_6) { + context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + } + } else { + context->customData = srvInfo.GetDescription(); + } + } else if (context->authType != DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + context->authTypeList.push_back(context->authType); // 没匹配到,但是不是导入授权码,也添加到候选列表 + } + // 查询回退表 + MatchFallBackCandidateList(context, context->authType); +} + int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr context) { LOGI("AuthSinkNegotiateStateMachine::Action sessionid %{public}d", context->sessionId); @@ -459,6 +526,7 @@ int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr con LOGE("AuthSinkNegotiateStateMachine::Action proc response negotiate failed"); return ret; } + NegotiatePinAuthType(context); context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_ACL_NEGOTIATE, context); context->timer->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), DmAuthState::GetTaskTimeout(context, WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 29933e1d3..794b088d1 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -442,6 +442,7 @@ int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr // 创建80报文 void DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject) { + json[TAG_AUTH_TYPE] = context->authType; jsonObject[DM_TAG_DMVERSION] = context->accesser.dmVersion; jsonObject[TAG_DEVICE_NAME] = context->accesser.deviceName; @@ -474,6 +475,9 @@ void DmAuthMessageProcessor::CreateRespNegotiateMessage(std::shared_ptraccessee.isAuthed; jsonObject[TAG_CREDENTIAL_INFO] = context->accessee.credentialInfos; + json[DM_TAG_AUTH_TYPE_LIST] = vectorToString(context->authTypeList); + json[DM_TAG_AUTH_RESULT] = context->authResult; + json[TAG_REQUEST_ID] = context->requestId; return; } @@ -788,6 +792,9 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject if (IsInt32(jsonObject, TAG_BIND_LEVEL)) { context->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].get(); } + if (IsInt32(json, TAG_AUTH_TYPE)) { + context->authType = static_cast(json[TAG_AUTH_TYPE].get()); + } if (jsonObject.contains(DM_TAG_EXTRA_INFO) && jsonObject[DM_TAG_EXTRA_INFO].is_object()) { ParseNegotiateExtraInfoMessage(jsonObject[DM_TAG_EXTRA_INFO], context); @@ -840,6 +847,17 @@ int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const nlohmann::jso context->accessee.credentialInfos = jsonObject[TAG_CREDENTIAL_INFO].get(); } + if (IsString(json, DM_TAG_AUTH_TYPE_LIST)) { + auto strList = json[DM_TAG_AUTH_TYPE_LIST].get(); + context->authTypeList = sstringToVector(strList); + } + if (IsInt64(json, TAG_REQUEST_ID)) { + context->requestId = json[TAG_REQUEST_ID].get(); + } + if (IsInt32(json, DM_TAG_AUTH_RESULT)) { + context->authResult = static_cast(json[DM_TAG_AUTH_RESULT].get()); + } + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -863,15 +881,31 @@ int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const nlohmann::json context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } + +static std::vector stringToVector(const std::string& str) { + std::vector vec; + std::istringstream iss(str); + int32_t num; + while (iss >> num) { + vec.push_back(statis_cast(num)); + } + return vec; +} + +static std::string vectorToString(const std::vector& vec) { + std::ostringstream oss; + for (size_t i = 0; i < vec.size(); ++i) { + oss << static_cast(vec[i]); + if (i != vec.size() - 1) { + oss << " "; // 添加分隔符(例如空格) + } + } + return oss.str(); +} + int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const nlohmann::json &json, std::shared_ptr context) { - if (IsInt32(json, TAG_AUTH_TYPE)) { - context->authType = static_cast(json[TAG_AUTH_TYPE].get()); - } - if (IsInt64(json, TAG_REQUEST_ID)) { - context->requestId = json[TAG_REQUEST_ID].get(); - } if (IsInt32(json, DM_TAG_AUTH_RESULT)) { context->authResult = static_cast(json[DM_TAG_AUTH_RESULT].get()); } @@ -917,9 +951,7 @@ void DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, nlohmann::json &json) { - json[TAG_AUTH_TYPE] = context->authType; json[DM_TAG_AUTH_RESULT] = context->authResult; - json[TAG_REQUEST_ID] = context->requestId; } void DmAuthMessageProcessor::CreateMessageReqPinAuthStart(std::shared_ptr context, nlohmann::json &json) -- Gitee From 8edda9a73306a9fdf202c5a58a23506bf2db7569 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Wed, 12 Mar 2025 11:26:52 +0800 Subject: [PATCH 182/382] tmp --- .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 844a03e67..784afc110 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -21,7 +21,6 @@ #include "app_manager.h" #include "hap_token_info.h" #include "deviceprofile_connector.h" -#include "local_service_info_manager.h" #include "device_auth.h" #include "accesstoken_kit.h" #include "access_control_profile.h" @@ -459,8 +458,8 @@ void AuthSinkNegotiateStateMachine::NegotiatePinAuthType(std::shared_ptrrequestId = GenRequestId(); authTypeList.clear(); // 根据 accessee.bundleName 和 src端 authType 查询 SP - LocalServiceInfo srvInfo; - auto ret = LocalServiceInfoManager::GetInstance().GetLocalServiceInfoByBundleAndPinType( + OHOS::DistributedDeviceProfile::LocalServiceInfo srvInfo; + auto ret = OHOS::DeviceProfileConnector::GetInstance().GetLocalServiceInfoByBundleAndPinType( context->accessee.bundleName, context->authType, srvInfo); if (ret == OHOS::DistributedDeviceProfile::DP_SUCCESS) { context->authTypeList.push_back(context->authType); // 匹配到,则添加到候选列表 -- Gitee From 072d8391e008780b6d8931da08a9866b344a05b9 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Wed, 12 Mar 2025 12:44:44 +0800 Subject: [PATCH 183/382] tmp --- .../auth_stages/auth_negotiate.cpp | 10 ++++--- .../dm_auth_message_processor.cpp | 27 ++++++++++--------- 2 files changed, 20 insertions(+), 17 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 784afc110..00d0707a0 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -14,6 +14,7 @@ */ #include +#include #include "nlohmann/json.hpp" #include "parameter.h" @@ -33,6 +34,7 @@ #include "dm_radar_helper.h" #include "dm_constants.h" #include "dm_anonymous.h" +#include "dm_random.h" #include "dm_auth_context.h" #include "auth_manager.h" #include "dm_auth_state.h" @@ -53,7 +55,7 @@ namespace DistributedHardware { namespace { using FallBackKey = std::pair; // accessee.bundleName, authType -constexpr static std::map g_pinAuthTypeFallBackMap = { +static std::map g_pinAuthTypeFallBackMap = { {{"cast_engine_service", DmAuthType::AUTH_TYPE_PIN_PROMPT}, DmAuthType::AUTH_TYPE_PIN}, }; constexpr size_t MAX_FALLBACK_LOOPKUP_TIMES = 2; // 最大递归查找次数 @@ -456,10 +458,10 @@ int64_t AuthSinkNegotiateStateMachine::GenRequestId() void AuthSinkNegotiateStateMachine::NegotiatePinAuthType(std::shared_ptr context) { context->requestId = GenRequestId(); - authTypeList.clear(); + context->authTypeList.clear(); // 根据 accessee.bundleName 和 src端 authType 查询 SP OHOS::DistributedDeviceProfile::LocalServiceInfo srvInfo; - auto ret = OHOS::DeviceProfileConnector::GetInstance().GetLocalServiceInfoByBundleAndPinType( + auto ret = OHOS::DeviceProfileConnector::GetInstance().GetLocalServiceInfoByBundleNameAndPinExchangeType( context->accessee.bundleName, context->authType, srvInfo); if (ret == OHOS::DistributedDeviceProfile::DP_SUCCESS) { context->authTypeList.push_back(context->authType); // 匹配到,则添加到候选列表 @@ -471,7 +473,7 @@ void AuthSinkNegotiateStateMachine::NegotiatePinAuthType(std::shared_ptrpinCode = std::stoi(pinCode); } - if (authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { // 免弹框 + if (context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { // 免弹框 int32_t authResult = srvInfo.GetAuthType(); if (authResult == 0) { context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 794b088d1..592458865 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -72,7 +72,8 @@ int32_t DmAuthMessageProcessor::SaveSessionKeyToDP(int32_t &skId) uint32_t skLen = cryptoMgr_->GetSessionKey(nullptr); uint8_t sessionKey[skLen]; skLen = cryptoMgr_->GetSessionKey(sessionKey); - return DeviceProfileConnector::GetInstance().PutSessionKey(sessionKey, skLen, skId); + std::vector sk(sessionKey, sessionKey + skLen); + return DeviceProfileConnector::GetInstance().PutSessionKey(sk, skId); } int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptr context, @@ -442,7 +443,7 @@ int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr // 创建80报文 void DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject) { - json[TAG_AUTH_TYPE] = context->authType; + jsonObject[TAG_AUTH_TYPE] = context->authType; jsonObject[DM_TAG_DMVERSION] = context->accesser.dmVersion; jsonObject[TAG_DEVICE_NAME] = context->accesser.deviceName; @@ -475,9 +476,9 @@ void DmAuthMessageProcessor::CreateRespNegotiateMessage(std::shared_ptraccessee.isAuthed; jsonObject[TAG_CREDENTIAL_INFO] = context->accessee.credentialInfos; - json[DM_TAG_AUTH_TYPE_LIST] = vectorToString(context->authTypeList); - json[DM_TAG_AUTH_RESULT] = context->authResult; - json[TAG_REQUEST_ID] = context->requestId; + jsonObject[DM_TAG_AUTH_TYPE_LIST] = vectorToString(context->authTypeList); + jsonObject[DM_TAG_AUTH_RESULT] = context->authResult; + jsonObject[TAG_REQUEST_ID] = context->requestId; return; } @@ -792,8 +793,8 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject if (IsInt32(jsonObject, TAG_BIND_LEVEL)) { context->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].get(); } - if (IsInt32(json, TAG_AUTH_TYPE)) { - context->authType = static_cast(json[TAG_AUTH_TYPE].get()); + if (IsInt32(jsonObject, TAG_AUTH_TYPE)) { + context->authType = static_cast(jsonObject[TAG_AUTH_TYPE].get()); } if (jsonObject.contains(DM_TAG_EXTRA_INFO) && jsonObject[DM_TAG_EXTRA_INFO].is_object()) { @@ -847,15 +848,15 @@ int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const nlohmann::jso context->accessee.credentialInfos = jsonObject[TAG_CREDENTIAL_INFO].get(); } - if (IsString(json, DM_TAG_AUTH_TYPE_LIST)) { - auto strList = json[DM_TAG_AUTH_TYPE_LIST].get(); + if (IsString(jsonObject, DM_TAG_AUTH_TYPE_LIST)) { + auto strList = jsonObject[DM_TAG_AUTH_TYPE_LIST].get(); context->authTypeList = sstringToVector(strList); } - if (IsInt64(json, TAG_REQUEST_ID)) { - context->requestId = json[TAG_REQUEST_ID].get(); + if (IsInt64(jsonObject, TAG_REQUEST_ID)) { + context->requestId = jsonObject[TAG_REQUEST_ID].get(); } - if (IsInt32(json, DM_TAG_AUTH_RESULT)) { - context->authResult = static_cast(json[DM_TAG_AUTH_RESULT].get()); + if (IsInt32(jsonObject, DM_TAG_AUTH_RESULT)) { + context->authResult = static_cast(jsonObject[DM_TAG_AUTH_RESULT].get()); } context->authStateMachine->TransitionTo(std::make_shared()); -- Gitee From 5b84afe1d6a4fe191e8002beb4f08ae0d4ddbd5e Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Wed, 12 Mar 2025 12:58:47 +0800 Subject: [PATCH 184/382] tmp --- .../auth_stages/auth_negotiate.cpp | 3 +- .../dm_auth_message_processor.cpp | 43 ++++++++++--------- 2 files changed, 24 insertions(+), 22 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 00d0707a0..013b3d6b4 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -22,6 +22,7 @@ #include "app_manager.h" #include "hap_token_info.h" #include "deviceprofile_connector.h" +#include "distributed_device_profile_errors.h" #include "device_auth.h" #include "accesstoken_kit.h" #include "access_control_profile.h" @@ -451,7 +452,7 @@ int64_t AuthSinkNegotiateStateMachine::GenRequestId() // 随机生成 PIN认证 的 requestId int32_t part1 = GenRandInt(std::numeric_limits::min(), std::numeric_limits::max()); int32_t part2 = GenRandInt(std::numeric_limits::min(), std::numeric_limits::max()); - uint64_t requestId = (staic_cast(part1) << 32) | staic_cast(part2); + uint64_t requestId = (static_cast(part1) << 32) | static_cast(part2); return static_cast(requestId); } diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 592458865..e20258dbd 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -13,6 +13,7 @@ * limitations under the License. */ #include +#include #include #include "dm_anonymous.h" #include "dm_auth_context.h" @@ -200,6 +201,27 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont return ERR_DM_FAILED; } +static std::vector stringToVector(const std::string& str) { + std::vector vec; + std::istringstream iss(str); + int32_t num; + while (iss >> num) { + vec.push_back(static_cast(num)); + } + return vec; +} + +static std::string vectorToString(const std::vector& vec) { + std::ostringstream oss; + for (size_t i = 0; i < vec.size(); ++i) { + oss << static_cast(vec[i]); + if (i != vec.size() - 1) { + oss << " "; // 添加分隔符(例如空格) + } + } + return oss.str(); +} + int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const nlohmann::json &jsonObject, std::shared_ptr &context, DmMessageType msgType) { @@ -883,27 +905,6 @@ int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const nlohmann::json return DM_OK; } -static std::vector stringToVector(const std::string& str) { - std::vector vec; - std::istringstream iss(str); - int32_t num; - while (iss >> num) { - vec.push_back(statis_cast(num)); - } - return vec; -} - -static std::string vectorToString(const std::vector& vec) { - std::ostringstream oss; - for (size_t i = 0; i < vec.size(); ++i) { - oss << static_cast(vec[i]); - if (i != vec.size() - 1) { - oss << " "; // 添加分隔符(例如空格) - } - } - return oss.str(); -} - int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const nlohmann::json &json, std::shared_ptr context) { -- Gitee From 9316c276287219ba7fdc7c03a45899c0f534dd25 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Wed, 12 Mar 2025 13:04:35 +0800 Subject: [PATCH 185/382] tmp --- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 2 +- .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 4 ++-- .../src/authentication_v2/dm_auth_message_processor.cpp | 3 ++- 3 files changed, 5 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index f4b7a3fd2..5c8f5f4b5 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -156,7 +156,7 @@ int32_t AuthSinkConfirmState::ShowConfigDialog(std::shared_ptr co LOGI("AuthSinkConfirmState::ShowConfigDialog end"); return DM_OK; } -#if 1 // todo 新的获取方法 根据客户端AuthType和BundleName从服务端SP表里查询业务注册的认证类型 +#if 0 // todo 新的获取方法 根据客户端AuthType和BundleName从服务端SP表里查询业务注册的认证类型 int32_t AuthSinkConfirmState::MatchAuthType(std::shared_ptr context) { // DP 接口 查询ServiceInfoProfile diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 013b3d6b4..fc58af9ab 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -57,7 +57,7 @@ namespace { using FallBackKey = std::pair; // accessee.bundleName, authType static std::map g_pinAuthTypeFallBackMap = { - {{"cast_engine_service", DmAuthType::AUTH_TYPE_PIN_PROMPT}, DmAuthType::AUTH_TYPE_PIN}, + {{"cast_engine_service", DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE}, DmAuthType::AUTH_TYPE_PIN}, }; constexpr size_t MAX_FALLBACK_LOOPKUP_TIMES = 2; // 最大递归查找次数 @@ -462,7 +462,7 @@ void AuthSinkNegotiateStateMachine::NegotiatePinAuthType(std::shared_ptrauthTypeList.clear(); // 根据 accessee.bundleName 和 src端 authType 查询 SP OHOS::DistributedDeviceProfile::LocalServiceInfo srvInfo; - auto ret = OHOS::DeviceProfileConnector::GetInstance().GetLocalServiceInfoByBundleNameAndPinExchangeType( + auto ret = DeviceProfileConnector::GetInstance().GetLocalServiceInfoByBundleNameAndPinExchangeType( context->accessee.bundleName, context->authType, srvInfo); if (ret == OHOS::DistributedDeviceProfile::DP_SUCCESS) { context->authTypeList.push_back(context->authType); // 匹配到,则添加到候选列表 diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index e20258dbd..7cf737154 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -14,6 +14,7 @@ */ #include #include +#include #include #include "dm_anonymous.h" #include "dm_auth_context.h" @@ -872,7 +873,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const nlohmann::jso if (IsString(jsonObject, DM_TAG_AUTH_TYPE_LIST)) { auto strList = jsonObject[DM_TAG_AUTH_TYPE_LIST].get(); - context->authTypeList = sstringToVector(strList); + context->authTypeList = stringToVector(strList); } if (IsInt64(jsonObject, TAG_REQUEST_ID)) { context->requestId = jsonObject[TAG_REQUEST_ID].get(); -- Gitee From a40d455c96d29f56a5f7a1ea25e1da237ac730c5 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Wed, 12 Mar 2025 13:07:29 +0800 Subject: [PATCH 186/382] tmp --- .../implementation/include/authentication_v2/dm_auth_state.h | 2 ++ .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 2 +- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index ecbccba43..e23a49bfc 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -122,6 +122,8 @@ public: virtual ~AuthSrcConfirmState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; +private: + void DoPinAuth(std::shared_ptr context); }; class AuthSinkStatePinAuthComm { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index ea23fa35e..0255089d4 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -117,7 +117,7 @@ int32_t AuthSrcPinAuthStartState::GetPinCodeFromServerInfo(std::shared_ptr serviceInfos; DistributedDeviceProfile::ServiceInfoUniqueKey key; auto tokenId = std::to_string(context->accesser.tokenId); -- Gitee From a7f0f03256853880c8727577350dd9acb7659067 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Wed, 12 Mar 2025 14:30:14 +0800 Subject: [PATCH 187/382] =?UTF-8?q?=E5=BC=B9=E6=8E=88=E6=9D=83=E6=A1=86?= =?UTF-8?q?=E4=B8=8D=E7=A9=BFreason=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 5c8f5f4b5..5f44e83c1 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -144,7 +144,6 @@ int32_t AuthSinkConfirmState::ShowConfigDialog(std::shared_ptr co } nlohmann::json jsonObj; - jsonObj[TAG_APP_OPERATION] = context->appOperation; jsonObj[TAG_CUSTOM_DESCRIPTION] = context->customData; jsonObj[TAG_LOCAL_DEVICE_TYPE] = context->accesser.deviceType; jsonObj[TAG_REQUESTER] = context->accesser.deviceName; -- Gitee From 6f21715f2ddebf3b9edfd6345580aa5a91f06b31 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Wed, 12 Mar 2025 15:04:47 +0800 Subject: [PATCH 188/382] =?UTF-8?q?BUGFIX:=E5=88=A0=E9=99=A4160-171=20SK?= =?UTF-8?q?=E5=8A=A0=E5=AF=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.cpp | 85 +++---------------- 1 file changed, 12 insertions(+), 73 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 7cf737154..94ae8c4f0 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -230,19 +230,9 @@ int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const nlohmann::js LOGE("DmAuthMessageProcessor::ParseMessageNegotiateTransmit Unlegal json string failed"); return ERR_DM_FAILED; } - // 解密 - std::string plainText; - int32_t ret = cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA], plainText); - if (ret != DM_OK) { - LOGE("DmAuthMessageProcessor::ParseMessageNegotiateTransmit DecryptMessage failed"); - return ret; - } - nlohmann::json jsonDecrptObj = nlohmann::json::parse(plainText, nullptr, false); - if (ParseMessageOnTransmit(jsonDecrptObj, context) != DM_OK) { - LOGE("DmAuthMessageProcessor::ParseMessageNegotiateTransmit ParseMessageOnTransmit failed"); - return ERR_DM_FAILED; - } + context->transmitData = jsonObject[DM_TAG_DATA].get(); + switch (msgType) { case MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE: // 161 context->authStateMachine->TransitionTo(std::make_shared()); @@ -260,18 +250,6 @@ int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const nlohmann::js return DM_OK; } -// 解析onTransmit返回的数据,保存到context->transmitData -int32_t DmAuthMessageProcessor::ParseMessageOnTransmit(const nlohmann::json &jsonObject, - std::shared_ptr context) -{ - if (jsonObject.is_discarded() || !IsString(jsonObject, DM_TAG_ON_TRANSMIT_DATA)) { - LOGE("DmAuthMessageProcessor::ParseMessageOnTransmit failed, decodeRequestAuth jsonStr error"); - return ERR_DM_FAILED; - } - context->transmitData = jsonObject[DM_TAG_ON_TRANSMIT_DATA].get(); - return DM_OK; -} - // 解析131报文信息MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate(const nlohmann::json &jsonObject, std::shared_ptr context) @@ -452,14 +430,7 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr &context, nlohmann::json &jsonObject) { std::string encryptMsg; - nlohmann::json jsonData; - jsonData[DM_TAG_ON_TRANSMIT_DATA] = context->transmitData; - int32_t ret = cryptoMgr_->EncryptMessage(SafetyDump(jsonData), encryptMsg); // 临时SK加密 - if (ret != DM_OK) { - LOGE("DmAuthMessageProcessor::CreateSyncMessage encrypt failed"); - return ret; - } - jsonObject[DM_TAG_DATA] = encryptMsg; + jsonObject[DM_TAG_DATA] = context->transmitData; return DM_OK; } @@ -554,21 +525,12 @@ void DmAuthMessageProcessor::CreateMessageReqCredAuthStart(std::shared_ptrtransmitData; + jsonObject[DM_TAG_DATA] = context->transmitData; if (!context->isAppCredentialVerified) { // 应用级凭据认证 - jsonData[DM_TAG_APP_CREDENTIAL_ID] = context->accesser.appCredentialId; + jsonObject[DM_TAG_APP_CREDENTIAL_ID] = context->accesser.appCredentialId; } else if (!context->isOnline) { // 首次用户级凭据认证 - jsonData[DM_TAG_USER_CREDENTIAL_ID] = context->accesser.userCredentialId; - } - - std::string plainText = SafetyDump(jsonData); - std::string cipherText; - if (cryptoMgr_->EncryptMessage(plainText, cipherText) != DM_OK) { - LOGE("DmAuthMessageProcessor::CreateMessageReqCredAuthStart failed, encrypt data failed."); - return; + jsonObject[DM_TAG_USER_CREDENTIAL_ID] = context->accesser.userCredentialId; } - - jsonObject[DM_TAG_DATA] = cipherText; } std::string DmAuthMessageProcessor::ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl) @@ -1195,18 +1157,7 @@ int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr return DM_OK; } -std::string DmAuthMessageProcessor::GetTransmitFromContext(std::shared_ptr &context) -{ - // 解析出ontransmit字段 - std::string transmitStr = ""; - nlohmann::json jsonObject = nlohmann::json::parse(context->extraInfo, nullptr, false); - if (jsonObject.is_discarded() || !jsonObject.contains(DM_TAG_ON_TRANSMIT_DATA) || !jsonObject[DM_TAG_ON_TRANSMIT_DATA].is_string()) { - LOGE("DmAuthMessageProcessor::GetTransmitFromContext jsonStr error"); - return transmitStr; - } - return SafetyDump(jsonObject[DM_TAG_ON_TRANSMIT_DATA]); -} -// 解析transmit和PSKID +// 解析transmit和PSKID 解析160 int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(nlohmann::json &jsonObject, std::shared_ptr &context) { if (jsonObject.is_discarded() || !jsonObject.contains(DM_TAG_DATA) || @@ -1214,33 +1165,21 @@ int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(nlohmann::json &jsonObject LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae Unlegal json string failed"); return ERR_DM_FAILED; } + context->transmitData = jsonObject[DM_TAG_DATA].get(); - // 解密 - std::string plainText; - int32_t ret = cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA], plainText); - if (ret != DM_OK) { - LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae DecryptMessage failed"); - return ret; - } - nlohmann::json jsonDecrptObj = nlohmann::json::parse(plainText, nullptr, false); - - if (ParseMessageOnTransmit(jsonDecrptObj, context) != DM_OK) { - LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae ParseMessageOnTransmit failed"); - return ERR_DM_FAILED; - } std::string jsonTag; if (context->isOnline == false && context->isAppCredentialVerified == false) { // 首次认证的应用凭据 jsonTag = DM_TAG_APP_CREDENTIAL_ID; - context->accesser.appCredentialId = jsonDecrptObj[DM_TAG_APP_CREDENTIAL_ID].get(); + context->accesser.appCredentialId = jsonObject[DM_TAG_APP_CREDENTIAL_ID].get(); } else if (context->isOnline == false) { // 首次认证的用户凭据 jsonTag = DM_TAG_USER_CREDENTIAL_ID; - context->accesser.userCredentialId = jsonDecrptObj[DM_TAG_USER_CREDENTIAL_ID].get(); + context->accesser.userCredentialId = jsonObject[DM_TAG_USER_CREDENTIAL_ID].get(); } else { // 非首次认证的应用凭据 jsonTag = DM_TAG_APP_CREDENTIAL_ID; - context->accesser.appCredentialId = jsonDecrptObj[DM_TAG_APP_CREDENTIAL_ID].get(); + context->accesser.appCredentialId = jsonObject[DM_TAG_APP_CREDENTIAL_ID].get(); } - if (!jsonDecrptObj.contains(jsonTag) || !jsonDecrptObj[jsonTag].is_string()) { + if (!jsonObject.contains(jsonTag) || !jsonObject[jsonTag].is_string()) { LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae Unlegal json CRED ID"); return ERR_DM_FAILED; } -- Gitee From 8a894691e95e7cffd3d7ebd2f30544463356ba09 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Wed, 12 Mar 2025 15:40:02 +0800 Subject: [PATCH 189/382] =?UTF-8?q?BUGFIX:=E5=88=A0=E9=99=A4=E5=86=97?= =?UTF-8?q?=E4=BD=99=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/dm_auth_message_processor.h | 6 ------ .../src/authentication_v2/auth_stages/auth_credential.cpp | 2 +- 2 files changed, 1 insertion(+), 7 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 5b1435478..0fc2adf74 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -34,7 +34,6 @@ constexpr const char *DM_TAG_USER_PUBLICK_KEY = "userPublicKey"; // 用户级 constexpr const char *DM_TAG_APP_PUBLICK_KEY = "appPublicKey"; // 应用级公钥 appPublicKey constexpr const char *DM_TAG_USER_CREDENTIAL_ID = "userCredentialId"; // 用户级凭据Id constexpr const char *DM_TAG_APP_CREDENTIAL_ID = "appCredentialId"; // 应用级凭据Id -constexpr const char *DM_TAG_ON_TRANSMIT_DATA = "onTransmitData"; // onTransmitData接口返回信息 constexpr const char *DM_TAG_AUTH_RESULT = "authResult"; // 授权结果 constexpr const char *DM_TAG_AUTH_TYPE_LIST = "authTypeList"; // 授权类型列表 @@ -194,9 +193,6 @@ public: // 创建报文,构造对应msgType的报文,返回值为json格式报文的字符串 std::string CreateMessage(DmMessageType msgType, std::shared_ptr context); - // 解析透传ON_TRANSMIT字段 - std::string GetTransmitFromContext(std::shared_ptr &context); - // 创建报文并发送 void CreateAndSendMsg(DmMessageType msgType, std::shared_ptr context); @@ -238,8 +234,6 @@ private: int32_t ParseMessageReqPinAuthNegotiate(const nlohmann::json &json, std::shared_ptr context); // 解析 131报文 int32_t ParseMessageRespPinAuthNegotiate(const nlohmann::json &jsonObject, std::shared_ptr context); - // 解析onTransmit - int32_t ParseMessageOnTransmit(const nlohmann::json &jsonObject, std::shared_ptr context); // 解析 140报文信息MSG_TYPE_REQ_CREDENTIAL_EXCHANGE,SINK端存放对方公钥 int32_t ParseMessageReqCredExchange(const nlohmann::json &jsonObject, std::shared_ptr context); // 解析 150报文信息MSG_TYPE_RESP_CREDENTIAL_EXCHANGE,存放对方公钥,和协商凭据Id diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 854e55044..4c21787f5 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -60,7 +60,7 @@ static int32_t AuthCredentialTransmitSend(std::shared_ptr context { // 获取transmit data if (context->transmitData.empty()) { - LOGE("AuthCredentialTransmitSend: GetTransmitFromContext from HICHAIN failed"); + LOGE("AuthCredentialTransmitSend: Get onTransmitData failed."); return ERR_DM_FAILED; } -- Gitee From 4ecf3574298b7ba759b6d2477880f4a09e056141 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Wed, 12 Mar 2025 16:21:11 +0800 Subject: [PATCH 190/382] tmp --- .../authentication_v2/dm_auth_context.h | 2 +- .../include/authentication_v2/dm_auth_state.h | 1 + .../src/authentication_v2/auth_manager.cpp | 7 +++--- .../auth_stages/auth_confirm.cpp | 4 ++-- .../auth_stages/auth_negotiate.cpp | 23 +++++++++++++++++-- .../src/device_manager_service_impl.cpp | 5 +++- 6 files changed, 33 insertions(+), 9 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 6cae529ff..4fae600f4 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -192,7 +192,7 @@ struct DmAuthContext { std::shared_ptr authPtr; std::shared_ptr timer; std::string transmitData; // 保存 onTrasmit返回数据 - std::string importPkgName = ""; + std::string importSessionName = ""; std::string importAuthCode = ""; std::map> authenticationMap; PeerTargetId peerTargetId; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index e23a49bfc..797a48273 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -296,6 +296,7 @@ private: 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); }; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 1287fce96..b5907ca10 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -240,7 +240,8 @@ int32_t AuthManager::ImportAuthCode(const std::string &sessionName, const std::s return ERR_DM_INPUT_PARA_INVALID; } context_->importAuthCode = authCode; - context_->importPkgName = sessionName; + context_->importSessionName = sessionName; + context_->pinCode = std::atoi(authCode.c_str()); return DM_OK; } @@ -395,11 +396,11 @@ bool AuthManager::IsAuthTypeSupported(const int32_t &authType) bool AuthManager::IsAuthCodeReady(const std::string &sessionName) { - if (context_->importAuthCode.empty() || context_->importPkgName.empty()) { + if (context_->importAuthCode.empty() || context_->importSessionName.empty()) { LOGE("AuthManager::IsAuthCodeReady, auth code not ready."); return false; } - if (sessionName != context_->importPkgName) { + if (sessionName != context_->importSessionName) { LOGE("IsAuthCodeReady failed, sessionName not supported."); return false; } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 5f44e83c1..f3a8b4e81 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -80,7 +80,7 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) if (CompareVersion(context->accessee.dmVersion, std::string(DM_VERSION_5_1_0))) { LOGE("AuthSrcConfirmState::Action incompatible version %{public}s compare to 5.1.0", context->accessee.dmVersion.c_str()); - context->reason = ERR_DM_VERSION_INCOMPATIBLE; // todo 发104报文??? + context->reason = ERR_DM_VERSION_INCOMPATIBLE; // todo 发104报文???应该finished状态处理 return ERR_DM_VERSION_INCOMPATIBLE; } #if 0 // todo 有凭据情况 @@ -114,7 +114,7 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) context->authStateMachine->TransitionTo(std::make_shared()); } // 无凭据 - //DoPinAuth(context); + DoPinAuth(context); #endif // send 100 context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_USER_CONFIRM, context); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index fc58af9ab..b8fe2307a 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -456,6 +456,19 @@ int64_t AuthSinkNegotiateStateMachine::GenRequestId() return static_cast(requestId); } +bool AuthSinkNegotiateStateMachine::IsAuthCodeReady(std::shared_ptr context) +{ + if (context->importAuthCode.empty() || context->importSessionName.empty()) { + LOGE("AuthSinkNegotiateStateMachine::IsAuthCodeReady, auth code not ready."); + return false; + } + if (context->sessionName != context->importSessionName) { + LOGE("IsAuthCodeReady failed, sessionName not supported."); + return false; + } + return true; +} + void AuthSinkNegotiateStateMachine::NegotiatePinAuthType(std::shared_ptr context) { context->requestId = GenRequestId(); @@ -486,8 +499,14 @@ void AuthSinkNegotiateStateMachine::NegotiatePinAuthType(std::shared_ptrcustomData = srvInfo.GetDescription(); } - } else if (context->authType != DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { - context->authTypeList.push_back(context->authType); // 没匹配到,但是不是导入授权码,也添加到候选列表 + } else { + if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + if (IsAuthCodeReady(context)) { + context->authTypeList.push_back(context->authType); + } + } else { + context->authTypeList.push_back(context->authType); // 没匹配到,但是不是导入授权码,也添加到候选列表 + } } // 查询回退表 MatchFallBackCandidateList(context, context->authType); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index aa262ca7a..a98a29207 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -29,6 +29,7 @@ #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "dm_common_event_manager.h" #include "parameter.h" +#include "dm_random.h" #include "common_event_support.h" using namespace OHOS::EventFwk; #endif @@ -37,6 +38,8 @@ namespace OHOS { namespace DistributedHardware { // One year 365 * 24 * 60 * 60 constexpr int32_t MAX_ALWAYS_ALLOW_SECONDS = 31536000; +constexpr int32_t MIN_PIN_CODE = 100000; +constexpr int32_t MAX_PIN_CODE = 999999; DeviceManagerServiceImpl::DeviceManagerServiceImpl() { @@ -601,7 +604,7 @@ int32_t DeviceManagerServiceImpl::ImportAuthCode(const std::string &pkgName, con int32_t DeviceManagerServiceImpl::ExportAuthCode(std::string &authCode) { - int32_t ret = authMgr_->GeneratePincode(); + int32_t ret = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); authCode = std::to_string(ret); LOGI("ExportAuthCode success, authCode: %{public}s.", GetAnonyString(authCode).c_str()); return DM_OK; -- Gitee From e220354acc4f28c46b92502c553aaeb3d8aa91c9 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Wed, 12 Mar 2025 17:57:30 +0800 Subject: [PATCH 191/382] tmp --- .../authentication_v2/dm_auth_context.h | 4 +- .../dm_auth_message_processor.h | 1 + .../include/authentication_v2/dm_auth_state.h | 2 +- .../auth_stages/auth_confirm.cpp | 98 ++++++++++++++++--- .../auth_stages/auth_negotiate.cpp | 5 + .../auth_stages/auth_pin_auth.cpp | 10 ++ .../dm_auth_message_processor.cpp | 14 +++ 7 files changed, 120 insertions(+), 14 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 4fae600f4..b4329f0c5 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -145,12 +145,12 @@ struct DmAuthContext { DmMessageType msgType; // 报文类型,枚举MsgType int32_t sessionId; // 总线传输会话ID int64_t requestId; // hichain认证ID - int32_t authBoxType{-1}; // 认证框类型 + int32_t authBoxType{1}; // 认证框类型 UiAction pinInputResult; // 输入PIN码结果 UiAction authResult{UiAction::USER_OPERATION_TYPE_ALLOW_AUTH}; // 授权结果(使用0、1、6,即单次,取消和始终信任,enum UiAction) DmAuthType authType{DmAuthType::AUTH_TYPE_PIN}; // 认证方式,弹pin码、超声pin码、导入pin码 std::vector authTypeList; // 共有认证方式列表 - int32_t currentAuthTypeIdx{0}; // 认证方式索引 + uint32_t currentAuthTypeIdx{0}; // 认证方式索引 int32_t authFailTimes{0}; // 认证失败次数,查过3次结束认证 int32_t pinCode{INVALID_PINCODE}; // 生成的PIN码 int32_t connDelayCloseTime; // 链路延迟释放时间, 授权结束后不自动断链(有业务需要使用)保留字段 diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 5b1435478..75c941ce5 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -37,6 +37,7 @@ constexpr const char *DM_TAG_APP_CREDENTIAL_ID = "appCredentialId"; // 应用 constexpr const char *DM_TAG_ON_TRANSMIT_DATA = "onTransmitData"; // onTransmitData接口返回信息 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接口入参 json格式字符串中的key constexpr const char *DM_TAG_METHOD = "method"; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 797a48273..d149e82fd 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -123,7 +123,7 @@ public: DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; private: - void DoPinAuth(std::shared_ptr context); + int32_t DoPinAuth(std::shared_ptr context); }; class AuthSinkStatePinAuthComm { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index f3a8b4e81..7cb543f83 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -51,14 +51,27 @@ DmAuthStateType AuthSrcConfirmState::GetStateType() return DmAuthStateType::AUTH_SRC_CONFIRM_STATE; } -void AuthSrcConfirmState::DoPinAuth(std::shared_ptr context) +int32_t AuthSrcConfirmState::DoPinAuth(std::shared_ptr context) { + LOGI("AuthSrcConfirmState::DoPinAuth start"); + int32_t authResult = context->authResult; + if (authResult != USER_OPERATION_TYPE_ALLOW_AUTH && + authResult != USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + LOGE("AuthSrcConfirmState::DoPinAuth authResult not allow"); + context->reason = ERR_DM_BIND_USER_CANCEL; + return ERR_DM_BIND_USER_CANCEL; + } + if (context->authTypeList.empty()) { - // no auth type goto finished + LOGE("AuthSrcConfirmState::DoPinAuth authTypeList empty"); + context->reason = ERR_DM_UNSUPPORTED_AUTH_TYPE; + reutrn ERR_DM_UNSUPPORTED_AUTH_TYPE; } - auto firstAuthType = context->authTypeList[0]; - if (firstAuthType == DmAuthType::AUTH_TYPE_PIN) { + context->currentAuthTypeIdx = 0; + context->authType = context->authTypeList[0]; + // 首次认证是输入PIN时,先授权 + if (context->authType == DmAuthType::AUTH_TYPE_PIN) { // send 100 context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_USER_CONFIRM, context); @@ -66,11 +79,13 @@ void AuthSrcConfirmState::DoPinAuth(std::shared_ptr context) CONFIRM_TIMEOUT, [context] (std::string name) { HandleAuthenticateTimeout(context, name); }); - // 后续110 报文触发 AuthSrcPinAuthStartState } else { // 少一轮 100,110 // 转 AuthSrcPinAuthStartState + context->authStateMachine->TransitionTo(std::make_shared()); } + LOGI("AuthSrcConfirmState::DoPinAuth end"); + return DM_OK; } int32_t AuthSrcConfirmState::Action(std::shared_ptr context) @@ -98,7 +113,7 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) // 有无可信关系的分享凭据 if (g_shareByPinAuthDeviceTypeSet.contains(static_cast(context->deviceType))) { // 走PIN码认证 - DoPinAuth(context); + return DoPinAuth(context); } else { // 转凭据认证 context->authStateMachine->TransitionTo(std::make_shared()); @@ -108,15 +123,15 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) // if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { if (!context->authTypeList.empty() && context->authTypeList[0] == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { // 走PIN码导入 - DoPinAuth(context); + return DoPinAuth(context); } else { // 结束绑定 context->authStateMachine->TransitionTo(std::make_shared()); } // 无凭据 - DoPinAuth(context); -#endif - // send 100 + return DoPinAuth(context); +#else + // todo del 无凭据 send 100 context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_USER_CONFIRM, context); context->timer->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), @@ -125,6 +140,7 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) }); LOGI("AuthSrcConfirmState::Action ok"); return DM_OK; +#endif } DmAuthStateType AuthSinkConfirmState::GetStateType() @@ -155,7 +171,7 @@ int32_t AuthSinkConfirmState::ShowConfigDialog(std::shared_ptr co LOGI("AuthSinkConfirmState::ShowConfigDialog end"); return DM_OK; } -#if 0 // todo 新的获取方法 根据客户端AuthType和BundleName从服务端SP表里查询业务注册的认证类型 +#if 0 // todo del 新的获取方法 根据客户端AuthType和BundleName从服务端SP表里查询业务注册的认证类型 int32_t AuthSinkConfirmState::MatchAuthType(std::shared_ptr context) { // DP 接口 查询ServiceInfoProfile @@ -253,6 +269,65 @@ int64_t AuthSinkConfirmState::GenRequestId(std::shared_ptr contex int32_t AuthSinkConfirmState::Action(std::shared_ptr context) { +#if 1 + LOGI("AuthSinkConfirmState::Action start"); + // 停止授权报文计时 + context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); + + if (context->authTypeList.empty()) { + LOGE("AuthSinkConfirmState::Action authTypeList empty"); + context->reason = ERR_DM_UNSUPPORTED_AUTH_TYPE; + reutrn ERR_DM_UNSUPPORTED_AUTH_TYPE; + } + context->authType = authTypeList[context->currentAuthTypeIdx]; + + if (context->authBoxType == DistributedDeviceProfile::NUM_1) { // 三态框 + LOGI("AuthSinkConfirmState::Action 3box"); + // 拉起授权确认页面 + if ((ret = ShowConfigDialog(context)) != DM_OK) { + return ret; + } + // 等待用户授权操作完成 + if(DmEventType::ON_USER_OPERATION != context->authStateMachine->WaitExpectEvent(DmEventType::ON_USER_OPERATION)) { + LOGE("AuthSinkConfirmState::Action wait ON_USER_OPERATION err"); + return STOP_BIND; // 外部事件错误,中止流程 + } + // 判断授权结果 + if (context->reply == USER_OPERATION_TYPE_ALLOW_AUTH) { + LOGI("AuthSinkConfirmState::Action USER_OPERATION_TYPE_ALLOW_AUTH"); + // 发送110报文 + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); + + if (context->authType == DmAuthType::AUTH_TYPE_PIN) { + // 生成PIN码 + AuthSinkStatePinAuthComm::GeneratePincode(context); + // 显示PIN码 + if ((ret = AuthSinkStatePinAuthComm::ShowAuthInfoDialog(context)) != DM_OK) { + return ret; + } + } + } else { + LOGI("AuthSinkConfirmState::Action USER_OPERATION_TYPE_CANCEL_AUTH"); + context->reason = ERR_DM_BIND_USER_CANCEL; + return STOP_BIND; // 用户取消授权 + } + } else if (context->authBoxType == DistributedDeviceProfile::NUM_2) { // 免弹框 + if (context->authResult == USER_OPERATION_TYPE_CANCEL_AUTH) { + LOGI("AuthSinkConfirmState::Action USER_OPERATION_TYPE_CANCEL_AUTH"); + context->reason = ERR_DM_BIND_USER_CANCEL; + return STOP_BIND; // 用户取消授权 + } + // 发送110报文 + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); + } else { + LOGE("AuthSinkConfirmState::Action authBoxType not support"); + context->reason = ERR_DM_UNSUPPORTED_AUTH_TYPE; + return ERR_DM_UNSUPPORTED_AUTH_TYPE; + } + LOGI("AuthSinkConfirmState::Action ok"); + return DM_OK; + +#else // todo del LOGI("AuthSinkConfirmState::Action start"); // 停止授权报文计时 context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); @@ -308,6 +383,7 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) } LOGI("AuthSinkConfirmState::Action ok"); return DM_OK; +#endif } } // namespace DistributedHardware diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index b8fe2307a..9b5758ac1 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -500,6 +500,11 @@ void AuthSinkNegotiateStateMachine::NegotiatePinAuthType(std::shared_ptrcustomData = srvInfo.GetDescription(); } } else { + if (context->authType == DmAuthType::AUTH_TYPE_PIN) { + context->authBoxType = OHOS::DistributedDeviceProfile::NUM_1; // 三态框 + } else { + context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // 免弹框 + } if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { if (IsAuthCodeReady(context)) { context->authTypeList.push_back(context->authType); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 0255089d4..2118ad257 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -147,6 +147,7 @@ int32_t AuthSrcPinAuthStartState::GetPinCodeFromServerInfo(std::shared_ptr context) { LOGI("AuthSrcPinAuthStartState::GetPinCode start"); +#if 0 // todo del if (context->authFailTimes == 0) { if (context->authType == DmAuthType::AUTH_TYPE_PIN || context->fallBackToInputPin) { // 拉起PIN码输入界面 @@ -178,6 +179,13 @@ int32_t AuthSrcPinAuthStartState::GetPinCode(std::shared_ptr cont LOGE("AuthSrcPinAuthStartState::GetPinCode not USER_OPERATION_TYPE_DONE_PINCODE_INPUT err"); return STOP_BIND; } +#else + // 如果是PIN,拉界面 + // 如果超声 TODO + // 如果导入PIN 直接获得 + + // 失败重试前,设置错误次数和类型切换 +#endif LOGI("AuthSrcPinAuthStartState::GetPinCode input ok"); return DM_OK; } @@ -209,6 +217,8 @@ int32_t AuthSrcPinAuthStartState::AuthDevice(std::shared_ptr cont int32_t AuthSrcPinAuthStartState::Action(std::shared_ptr context) { LOGI("AuthSrcPinAuthStartState::Action start"); + + context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); // 首次进入停止计时器 if (context->authFailTimes == 0 && !context->fallBackToInputPin) { context->timer->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 7cf737154..31bcd3a14 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -901,6 +901,12 @@ int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const nlohmann::json if (IsString(json, TAG_SESSION_NAME)) { context->sessionName = json[TAG_SESSION_NAME].get(); } + if (IsUint32(json, DM_TAG_CURRENT_AUTH_TYPE_IDX)) { + auto idx = json[DM_TAG_CURRENT_AUTH_TYPE_IDX].get(); + if (idx < authTypeList.size()) { + context->currentAuthTypeIdx = idx; + } + } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; @@ -922,6 +928,12 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const nlohmann::json if (IsString(json, DM_TAG_DATA)) { context->transmitData = json[DM_TAG_DATA].get(); } + if (IsUint32(json, DM_TAG_CURRENT_AUTH_TYPE_IDX)) { + auto idx = json[DM_TAG_CURRENT_AUTH_TYPE_IDX].get(); + if (idx < authTypeList.size()) { + context->currentAuthTypeIdx = idx; + } + } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -950,6 +962,7 @@ void DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptraccesser.deviceType; json[TAG_DEVICE_NAME] = context->accesser.deviceName; json[TAG_SESSION_NAME] = context->sessionName; + json[DM_TAG_CURRENT_AUTH_TYPE_IDX] = context->currentAuthTypeIdx; } void DmAuthMessageProcessor::CreateMessageRespUserConfirm(std::shared_ptr context, nlohmann::json &json) @@ -960,6 +973,7 @@ void DmAuthMessageProcessor::CreateMessageRespUserConfirm(std::shared_ptr context, nlohmann::json &json) { json[DM_TAG_DATA] = context->transmitData; + json[DM_TAG_CURRENT_AUTH_TYPE_IDX] = context->currentAuthTypeIdx; } void DmAuthMessageProcessor::CreateMessageRespPinAuthStart(std::shared_ptr context, nlohmann::json &json) -- Gitee From e5ce3b9694414c4560d2dd3d57eb9b19a0c96b50 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 13 Mar 2025 11:39:07 +0800 Subject: [PATCH 192/382] tmp --- .../dm_auth_message_processor.cpp | 14 ++++++++++++-- 1 file changed, 12 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 3305874cd..ac492b524 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -865,8 +865,13 @@ int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const nlohmann::json } if (IsUint32(json, DM_TAG_CURRENT_AUTH_TYPE_IDX)) { auto idx = json[DM_TAG_CURRENT_AUTH_TYPE_IDX].get(); - if (idx < authTypeList.size()) { + if (idx < context->authTypeList.size()) { context->currentAuthTypeIdx = idx; + } else { + LOGI("DmAuthMessageProcessor::ParseMessageReqUserConfirm currentAuthTypeIdx err."); + context_>reason = ERR_DM_INPUT_PARA_INVALID; + context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + return STOP_BIND; } } @@ -892,8 +897,13 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const nlohmann::json } if (IsUint32(json, DM_TAG_CURRENT_AUTH_TYPE_IDX)) { auto idx = json[DM_TAG_CURRENT_AUTH_TYPE_IDX].get(); - if (idx < authTypeList.size()) { + if (idx < context->authTypeList.size()) { context->currentAuthTypeIdx = idx; + } else { + LOGI("DmAuthMessageProcessor::ParseMessageReqUserConfirm currentAuthTypeIdx err."); + context_>reason = ERR_DM_INPUT_PARA_INVALID; + context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); + return STOP_BIND; } } context->authStateMachine->TransitionTo(std::make_shared()); -- Gitee From 329eeeea721d782bbc3c34f72deca672618940ef Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 13 Mar 2025 11:40:15 +0800 Subject: [PATCH 193/382] tmp --- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 7cb543f83..f836c4203 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -279,7 +279,7 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) context->reason = ERR_DM_UNSUPPORTED_AUTH_TYPE; reutrn ERR_DM_UNSUPPORTED_AUTH_TYPE; } - context->authType = authTypeList[context->currentAuthTypeIdx]; + context->authType = context->authTypeList[context->currentAuthTypeIdx]; if (context->authBoxType == DistributedDeviceProfile::NUM_1) { // 三态框 LOGI("AuthSinkConfirmState::Action 3box"); -- Gitee From b0a64de93968061ddb4ac7af3e24841f04fba310 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 13 Mar 2025 11:41:51 +0800 Subject: [PATCH 194/382] tmp --- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index f836c4203..04f0fc00f 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -284,7 +284,8 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) if (context->authBoxType == DistributedDeviceProfile::NUM_1) { // 三态框 LOGI("AuthSinkConfirmState::Action 3box"); // 拉起授权确认页面 - if ((ret = ShowConfigDialog(context)) != DM_OK) { + auto ret = ShowConfigDialog(context); + if (ret != DM_OK) { return ret; } // 等待用户授权操作完成 -- Gitee From 602729f149282c7a5eb48f4d1217c01127b982cd Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 13 Mar 2025 11:46:35 +0800 Subject: [PATCH 195/382] tmp --- .../src/authentication_v2/dm_auth_message_processor.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index ac492b524..2b06e08cf 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -869,7 +869,7 @@ int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const nlohmann::json context->currentAuthTypeIdx = idx; } else { LOGI("DmAuthMessageProcessor::ParseMessageReqUserConfirm currentAuthTypeIdx err."); - context_>reason = ERR_DM_INPUT_PARA_INVALID; + context->reason = ERR_DM_INPUT_PARA_INVALID; context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); return STOP_BIND; } @@ -901,7 +901,7 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const nlohmann::json context->currentAuthTypeIdx = idx; } else { LOGI("DmAuthMessageProcessor::ParseMessageReqUserConfirm currentAuthTypeIdx err."); - context_>reason = ERR_DM_INPUT_PARA_INVALID; + context->reason = ERR_DM_INPUT_PARA_INVALID; context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); return STOP_BIND; } -- Gitee From 12360b96d0b6dadfd870dbd660f9a8fd77239b1a Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 13 Mar 2025 11:50:27 +0800 Subject: [PATCH 196/382] tmp --- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 6 +++--- .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 04f0fc00f..29c593f30 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -65,7 +65,7 @@ int32_t AuthSrcConfirmState::DoPinAuth(std::shared_ptr context) if (context->authTypeList.empty()) { LOGE("AuthSrcConfirmState::DoPinAuth authTypeList empty"); context->reason = ERR_DM_UNSUPPORTED_AUTH_TYPE; - reutrn ERR_DM_UNSUPPORTED_AUTH_TYPE; + return ERR_DM_UNSUPPORTED_AUTH_TYPE; } context->currentAuthTypeIdx = 0; @@ -269,7 +269,7 @@ int64_t AuthSinkConfirmState::GenRequestId(std::shared_ptr contex int32_t AuthSinkConfirmState::Action(std::shared_ptr context) { -#if 1 +#if 0 LOGI("AuthSinkConfirmState::Action start"); // 停止授权报文计时 context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); @@ -277,7 +277,7 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) if (context->authTypeList.empty()) { LOGE("AuthSinkConfirmState::Action authTypeList empty"); context->reason = ERR_DM_UNSUPPORTED_AUTH_TYPE; - reutrn ERR_DM_UNSUPPORTED_AUTH_TYPE; + return ERR_DM_UNSUPPORTED_AUTH_TYPE; } context->authType = context->authTypeList[context->currentAuthTypeIdx]; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 2118ad257..cc1cc9341 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -147,7 +147,7 @@ int32_t AuthSrcPinAuthStartState::GetPinCodeFromServerInfo(std::shared_ptr context) { LOGI("AuthSrcPinAuthStartState::GetPinCode start"); -#if 0 // todo del +#if 1 // todo del if (context->authFailTimes == 0) { if (context->authType == DmAuthType::AUTH_TYPE_PIN || context->fallBackToInputPin) { // 拉起PIN码输入界面 -- Gitee From e863f31624b3345abb3df26162ca414aa325176c Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 13 Mar 2025 16:14:15 +0800 Subject: [PATCH 197/382] =?UTF-8?q?PIN=E7=A0=81=E8=AE=A4=E8=AF=81=EF=BC=8C?= =?UTF-8?q?=E7=8A=B6=E6=80=81=E6=9C=BA=E8=B0=83=E6=95=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/dm_auth_state.h | 82 +++++++++++++++---- .../auth_stages/auth_confirm.cpp | 30 +++---- .../auth_stages/auth_pin_auth.cpp | 62 +++++++++++++- .../dm_auth_state_machine.cpp | 72 ++++++++++++---- 4 files changed, 197 insertions(+), 49 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index d149e82fd..3b65f42b9 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -40,28 +40,34 @@ enum class DmAuthStateType { AUTH_SRC_START_STATE = 1, // 用户触发BindTarget AUTH_SRC_NEGOTIATE_STATE = 2, // 收到软总线回调函数OnSessionOpened,发送80报文 AUTH_SRC_CONFIRM_STATE = 3, // 收到90授权结果报文,发送100报文 - AUTH_SRC_PIN_AUTH_START_STATE = 4, // 收到110授权结果报文,发送120报文 - AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE = 5, // 收到130认证PIN结果报文,发送121报文 - AUTH_SRC_PIN_AUTH_DONE_STATE = 6, // 收到131认证PIN结果报文,调用processData - AUTH_SRC_CREDENTIAL_EXCHANGE_STATE = 7, // 触发Onfinish回调事件,发送140报文 - AUTH_SRC_CREDENTIAL_AUTH_START_STATE = 8, // 收到150加密报文,发送160报文 - AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE = 9, // 收到170凭据认证报文,发送161报文 - AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE = 10, // 收到171凭据认证报文,回复160报文或者180报文 - AUTH_SRC_DATA_SYNC_STATE = 11, // 触发Onfinish回调事件,发送180报文 todo 可以删除 - AUTH_SRC_FINISH_STATE = 12, // 收到190报文,发送200报文 + 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, // 触发Onfinish回调事件,发送180报文 todo 可以删除 + AUTH_SRC_FINISH_STATE = 15, // 收到190报文,发送200报文 // sink端的状态 AUTH_SINK_START_STATE = 50, // 总线触发OnSessionOpened AUTH_SINK_NEGOTIATE_STATE = 51, // 收到80可信关系协商报文,发送90报文 AUTH_SINK_CONFIRM_STATE = 52, // 收到100用户授权报文,发送110报文 - AUTH_SINK_PIN_AUTH_START_STATE = 53, // 收到120认证PIN报文,发送130报文 - AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE = 54, // 收到121认证PIN报文,发送131报文 - AUTH_SINK_PIN_AUTH_DONE_STATE = 55, // 触发Onfinish回调事件 - AUTH_SINK_CREDENTIAL_EXCHANGE_STATE = 56, // 收到140加密报文,发送150报文 - AUTH_SINK_CREDENTIAL_AUTH_START_STATE = 57, // 收到160凭证认证报文,发送170报文 - AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE = 58, // 收到161凭据协商报文,回复171报文 - AUTH_SINK_DATA_SYNC_STATE = 59, // 收到180同步报文,发送190报文 - AUTH_SINK_FINISH_STATE = 60, // 收到200结束报文 + 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结束报文 }; // 凭据添加方式 @@ -145,6 +151,48 @@ private: int64_t GenRequestId(std::shared_ptr context); // 生成HiChain请求ID }; +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; +}; + +class AuthSrcPinNegotiateUltrasonicPinState : public DmAuthState { +public: + virtual ~AuthSrcPinNegotiateUltrasonicPinState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + +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 AuthSinkPinNegotiateUltrasonicPinState : public DmAuthState { +public: + virtual ~AuthSinkPinNegotiateUltrasonicPinState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; +}; + class AuthSrcPinAuthStartState : public DmAuthState { public: virtual ~AuthSrcPinAuthStartState() {}; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 29c593f30..1e17386a5 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -269,7 +269,7 @@ int64_t AuthSinkConfirmState::GenRequestId(std::shared_ptr contex int32_t AuthSinkConfirmState::Action(std::shared_ptr context) { -#if 0 +#if 0 // 新状态流程,待测试 LOGI("AuthSinkConfirmState::Action start"); // 停止授权报文计时 context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); @@ -294,20 +294,7 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) return STOP_BIND; // 外部事件错误,中止流程 } // 判断授权结果 - if (context->reply == USER_OPERATION_TYPE_ALLOW_AUTH) { - LOGI("AuthSinkConfirmState::Action USER_OPERATION_TYPE_ALLOW_AUTH"); - // 发送110报文 - context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); - - if (context->authType == DmAuthType::AUTH_TYPE_PIN) { - // 生成PIN码 - AuthSinkStatePinAuthComm::GeneratePincode(context); - // 显示PIN码 - if ((ret = AuthSinkStatePinAuthComm::ShowAuthInfoDialog(context)) != DM_OK) { - return ret; - } - } - } else { + if (context->reply != USER_OPERATION_TYPE_ALLOW_AUTH) { LOGI("AuthSinkConfirmState::Action USER_OPERATION_TYPE_CANCEL_AUTH"); context->reason = ERR_DM_BIND_USER_CANCEL; return STOP_BIND; // 用户取消授权 @@ -318,13 +305,22 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) context->reason = ERR_DM_BIND_USER_CANCEL; return STOP_BIND; // 用户取消授权 } - // 发送110报文 - context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); } else { LOGE("AuthSinkConfirmState::Action authBoxType not support"); context->reason = ERR_DM_UNSUPPORTED_AUTH_TYPE; return ERR_DM_UNSUPPORTED_AUTH_TYPE; } + + // 发送110报文 + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); + if (context->authType == DmAuthType::AUTH_TYPE_PIN) { + // 生成PIN码 + AuthSinkStatePinAuthComm::GeneratePincode(context); + // 显示PIN码 + if ((ret = AuthSinkStatePinAuthComm::ShowAuthInfoDialog(context)) != DM_OK) { + return ret; + } + } LOGI("AuthSinkConfirmState::Action ok"); return DM_OK; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index cc1cc9341..2d6993c15 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -179,7 +179,7 @@ int32_t AuthSrcPinAuthStartState::GetPinCode(std::shared_ptr cont LOGE("AuthSrcPinAuthStartState::GetPinCode not USER_OPERATION_TYPE_DONE_PINCODE_INPUT err"); return STOP_BIND; } -#else +#else // 新状态流程,待测试 // 如果是PIN,拉界面 // 如果超声 TODO // 如果导入PIN 直接获得 @@ -388,5 +388,65 @@ int32_t AuthSrcPinAuthDoneState::Action(std::shared_ptr context) return ERR_DM_FAILED; } +DmAuthStateType AuthSrcPinNegotiateStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE; +} + +int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr context) +{ + return DM_ERR_FAILED; +} + +DmAuthStateType AuthSrcPinInputState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_PIN_INPUT_STATE; +} + +int32_t AuthSrcPinInputState::Action(std::shared_ptr context) +{ + return DM_ERR_FAILED; +} + +DmAuthStateType AuthSrcPinNegotiateUltrasonicPinState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE; +} + +int32_t AuthSrcPinNegotiateUltrasonicPinState::Action(std::shared_ptr context) +{ + return DM_ERR_FAILED; +} + +DmAuthStateType AuthSinkPinNegotiateStartState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE; +} + +int32_t AuthSinkPinNegotiateStartState::Action(std::shared_ptr context) +{ + return DM_ERR_FAILED; +} + +DmAuthStateType AuthSinkPinDisplayState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_PIN_DISPLAY_STATE; +} + +int32_t AuthSinkPinDisplayState::Action(std::shared_ptr context) +{ + return DM_ERR_FAILED; +} + +DmAuthStateType AuthSinkPinNegotiateUltrasonicPinState::GetStateType() +{ + return DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE; +} + +int32_t AuthSinkPinNegotiateUltrasonicPinState::Action(std::shared_ptr context) +{ + return DM_ERR_FAILED; +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 3853448e5..ac67450dd 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -35,15 +35,38 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) // Source端 状态迁移表 {DmAuthStateType::AUTH_SRC_START_STATE, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE}}, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE}}, - {DmAuthStateType::AUTH_SRC_CONFIRM_STATE, - {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, - DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, // to check - {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, - {DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE}}, - {DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, - {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE}}, - {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, - {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE}}, + {DmAuthStateType::AUTH_SRC_CONFIRM_STATE, { + DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, // todo del + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, { + DmAuthStateType::AUTH_SRC_PIN_INPUT_STATE, + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE, + DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_PIN_INPUT_STATE, { + DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE, { + DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, { + DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, + DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, // todo del + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, { + DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, + DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, // todo del + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, { + DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, + DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, // todo del + DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + }}, {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, // 收到150的处理状态,发送160 {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, @@ -61,11 +84,32 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, // to check - {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, {DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE}}, - {DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, - {DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE}}, - {DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, - {DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE}}, + {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, { + DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, // todo del + DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, { + DmAuthStateType::AUTH_SINK_PIN_DISPLAY_STATE, + DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE, + DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_PIN_DISPLAY_STATE, { + DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE, { + DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, + DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, { + DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, + DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, // todo del + DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, { + DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, + DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, // todo del + DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, + }}, {DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE}}, {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, -- Gitee From 71a4a23a3948da6856867490dc9efa56eaa4891a Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 13 Mar 2025 16:19:23 +0800 Subject: [PATCH 198/382] tmp --- .../authentication_v2/auth_stages/auth_pin_auth.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 2d6993c15..06355754f 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -395,7 +395,7 @@ DmAuthStateType AuthSrcPinNegotiateStartState::GetStateType() int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr context) { - return DM_ERR_FAILED; + return ERR_DM_FAILED; } DmAuthStateType AuthSrcPinInputState::GetStateType() @@ -405,7 +405,7 @@ DmAuthStateType AuthSrcPinInputState::GetStateType() int32_t AuthSrcPinInputState::Action(std::shared_ptr context) { - return DM_ERR_FAILED; + return ERR_DM_FAILED; } DmAuthStateType AuthSrcPinNegotiateUltrasonicPinState::GetStateType() @@ -415,7 +415,7 @@ DmAuthStateType AuthSrcPinNegotiateUltrasonicPinState::GetStateType() int32_t AuthSrcPinNegotiateUltrasonicPinState::Action(std::shared_ptr context) { - return DM_ERR_FAILED; + return ERR_DM_FAILED; } DmAuthStateType AuthSinkPinNegotiateStartState::GetStateType() @@ -425,7 +425,7 @@ DmAuthStateType AuthSinkPinNegotiateStartState::GetStateType() int32_t AuthSinkPinNegotiateStartState::Action(std::shared_ptr context) { - return DM_ERR_FAILED; + return ERR_DM_FAILED; } DmAuthStateType AuthSinkPinDisplayState::GetStateType() @@ -435,7 +435,7 @@ DmAuthStateType AuthSinkPinDisplayState::GetStateType() int32_t AuthSinkPinDisplayState::Action(std::shared_ptr context) { - return DM_ERR_FAILED; + return ERR_DM_FAILED; } DmAuthStateType AuthSinkPinNegotiateUltrasonicPinState::GetStateType() @@ -445,7 +445,7 @@ DmAuthStateType AuthSinkPinNegotiateUltrasonicPinState::GetStateType() int32_t AuthSinkPinNegotiateUltrasonicPinState::Action(std::shared_ptr context) { - return DM_ERR_FAILED; + return ERR_DM_FAILED; } } // namespace DistributedHardware -- Gitee From 36d29a12f1a5b2e660d03f7d5915d031f3bc3c36 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 13 Mar 2025 16:21:42 +0800 Subject: [PATCH 199/382] tmp --- .../include/authentication_v2/dm_auth_state.h | 12 ++++++------ .../auth_stages/auth_pin_auth.cpp | 18 +++++++++--------- 2 files changed, 15 insertions(+), 15 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 3b65f42b9..edc83180d 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -165,23 +165,23 @@ public: int32_t Action(std::shared_ptr context) override; }; -class AuthSrcPinNegotiateUltrasonicPinState : public DmAuthState { +class AuthSinkPinNegotiateStartState : public DmAuthState { public: - virtual ~AuthSrcPinNegotiateUltrasonicPinState() {}; + virtual ~AuthSinkPinNegotiateStartState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; }; -class AuthSinkPinNegotiateStartState : public DmAuthState { +class AuthSinkPinDisplayState : public DmAuthState { public: - virtual ~AuthSinkPinNegotiateStartState() {}; + virtual ~AuthSinkPinDisplayState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; }; -class AuthSinkPinDisplayState : public DmAuthState { +class AuthSrcPinNegotiateUltrasonicPinState : public DmAuthState { public: - virtual ~AuthSinkPinDisplayState() {}; + virtual ~AuthSrcPinNegotiateUltrasonicPinState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; }; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 06355754f..dad765e71 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -408,32 +408,32 @@ int32_t AuthSrcPinInputState::Action(std::shared_ptr context) return ERR_DM_FAILED; } -DmAuthStateType AuthSrcPinNegotiateUltrasonicPinState::GetStateType() +DmAuthStateType AuthSinkPinNegotiateStartState::GetStateType() { - return DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE; + return DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE; } -int32_t AuthSrcPinNegotiateUltrasonicPinState::Action(std::shared_ptr context) +int32_t AuthSinkPinNegotiateStartState::Action(std::shared_ptr context) { return ERR_DM_FAILED; } -DmAuthStateType AuthSinkPinNegotiateStartState::GetStateType() +DmAuthStateType AuthSinkPinDisplayState::GetStateType() { - return DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE; + return DmAuthStateType::AUTH_SINK_PIN_DISPLAY_STATE; } -int32_t AuthSinkPinNegotiateStartState::Action(std::shared_ptr context) +int32_t AuthSinkPinDisplayState::Action(std::shared_ptr context) { return ERR_DM_FAILED; } -DmAuthStateType AuthSinkPinDisplayState::GetStateType() +DmAuthStateType AuthSrcPinNegotiateUltrasonicPinState::GetStateType() { - return DmAuthStateType::AUTH_SINK_PIN_DISPLAY_STATE; + return DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE; } -int32_t AuthSinkPinDisplayState::Action(std::shared_ptr context) +int32_t AuthSrcPinNegotiateUltrasonicPinState::Action(std::shared_ptr context) { return ERR_DM_FAILED; } -- Gitee From 503f201c18a3c01becf97869796321571d3dde07 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Thu, 13 Mar 2025 19:14:27 +0800 Subject: [PATCH 200/382] =?UTF-8?q?feat:=20=E5=AE=9E=E7=8E=B0=E6=96=B0?= =?UTF-8?q?=E8=80=81=E5=8D=8F=E8=AE=AE=E5=85=BC=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/implementation/BUILD.gn | 2 + .../include/authentication/dm_auth_manager.h | 7 +- .../include/authentication_v2/auth_manager.h | 12 +- .../authentication_v2/dm_auth_context.h | 1 + .../authentication_v2/dm_auth_manager_base.h | 147 +++++++++ .../dm_auth_message_processor.h | 2 - .../include/device_manager_service_impl.h | 4 +- .../src/authentication/dm_auth_manager.cpp | 32 +- .../src/authentication_v2/auth_manager.cpp | 24 ++ .../auth_stages/auth_negotiate.cpp | 31 +- .../dm_auth_manager_base.cpp | 289 ++++++++++++++++++ .../dm_auth_message_processor.cpp | 28 +- .../dependency/softbus/softbus_session.cpp | 2 +- .../src/device_manager_service_impl.cpp | 163 +++++++++- 14 files changed, 676 insertions(+), 68 deletions(-) create mode 100644 services/implementation/include/authentication_v2/dm_auth_manager_base.h create mode 100644 services/implementation/src/authentication_v2/dm_auth_manager_base.cpp diff --git a/services/implementation/BUILD.gn b/services/implementation/BUILD.gn index ffe08042b..e4e9c9b02 100644 --- a/services/implementation/BUILD.gn +++ b/services/implementation/BUILD.gn @@ -193,6 +193,7 @@ if (defined(ohos_lite)) { "src/authentication_v2/dm_auth_state_machine.cpp", "src/authentication_v2/dm_auth_state.cpp", "src/authentication_v2/dm_auth_context.cpp", + "src/authentication_v2/dm_auth_manager_base.cpp", "src/config/dm_config_manager.cpp", "src/credential/dm_credential_manager.cpp", "src/cryptomgr/crypto_mgr.cpp", @@ -248,6 +249,7 @@ if (defined(ohos_lite)) { "mbedtls:mbedtls_shared", "openssl:libcrypto_shared", "os_account:libaccountkits", + "os_account:os_account_innerkits", "resource_management:resmgr_napi_core", "samgr:samgr_proxy", "zlib:shared_libz", diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 0f29a009b..2db8af888 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -28,6 +28,7 @@ #include "deviceprofile_connector.h" #include "dm_ability_manager.h" #include "dm_adapter_manager.h" +#include "dm_auth_manager_base.h" #include "dm_constants.h" #include "dm_device_info.h" #include "dm_timer.h" @@ -203,9 +204,7 @@ typedef struct DmAuthResponseContext { class AuthMessageProcessor; -class DmAuthManager final : public ISoftbusSessionCallback, - public IHiChainConnectorCallback, - public IDmDeviceAuthCallback, +class DmAuthManager final : public AuthManagerBase, public std::enable_shared_from_this { public: DmAuthManager(std::shared_ptr softbusConnector, @@ -570,8 +569,6 @@ private: void SrcAuthenticateFinish(); std::string GetBundleLable(const std::string &bundleName); bool IsScreenLocked(); - std::string ConvertSrcVersion(const std::string &version, const std::string &edition); - std::string ConvertSinkVersion(const std::string &version); void NegotiateRespMsg(const std::string &version); void SetAuthType(int32_t authType); int32_t GetTaskTimeout(const char* taskName, int32_t taskTimeOut); diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index ac8a28d6e..a43453db6 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -22,6 +22,7 @@ #include "softbus_connector.h" #include "softbus_session.h" #include "auth_ui_state_manager.h" +#include "dm_auth_manager_base.h" namespace OHOS { namespace DistributedHardware { @@ -37,8 +38,7 @@ const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; const int32_t HML_SESSION_TIMEOUT = 10; const int32_t AUTHENTICATE_TIMEOUT = 120; constexpr const char* DM_VERSION_5_0_1 = "5.0.1"; -constexpr const char* DM_VERSION_5_0_4 = "5.0.4"; -constexpr const char* DM_VERSION_5_1_0 = "5.1.0"; +constexpr const char* DM_VERSION_5_0_9 = "5.0.9"; // 预估的旧版本最高版本号 constexpr const char* BUNDLE_NAME_KEY = "bundleName"; // 取自security_device_auth中的identity_operation.h,该头文件为内部头文件,不能直接引用 @@ -57,8 +57,7 @@ enum { SCOPE_APP, }; -class AuthManager : public ISoftbusSessionCallback, - public IDmDeviceAuthCallback, +class AuthManager : public AuthManagerBase, public std::enable_shared_from_this { public: AuthManager(std::shared_ptr softbusConnector, @@ -133,6 +132,9 @@ public: 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(); // 提取本端ACL 用于消息解析和总线使用 无ACL会返回空字符串 json格式字符串:{dmversion:x,accesser:[{accesserDeviceId:y,...},...],accessee:{...}} int32_t GetAclListStr(std::string &aclList); @@ -141,7 +143,7 @@ protected: // 上下文(需在该层级进行创建) std::shared_ptr context_; std::shared_ptr authUiStateMgr_; - + std::map bindParam_; // IDmDeviceAuthCallback 转内部接口 // pkgName是#define DM_APP_ID "ohos.distributedhardware.devicemanager" diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index b4329f0c5..3ec41017b 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -105,6 +105,7 @@ struct DmAccess { std::string addr; int32_t userId; std::string userIdHash; + int32_t displayId = 0; // 逻辑屏幕id std::string accountId; std::string accountIdHash; uint64_t tokenId; 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 000000000..32184d205 --- /dev/null +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h @@ -0,0 +1,147 @@ +/* + * 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 { + +// device_manager_service_impl.cpp需要此定义,所以放在此处 +constexpr const char *DM_TAG_DMVERSION = "dmVersion"; +constexpr const char *DM_TAG_EDITION = "edition"; +constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5.1"; +constexpr const char* DM_VERSION_5_1_0 = "5.1.0"; + +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) = 0; + + // 5.1.0版本新增接口 + virtual int32_t GetReason(); + // 新协议切换到老协议时,需要获取之前的Params,以供老协议使用 + virtual void GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, + std::map &bindParam); + + // 公共函数 + static std::string ConvertSrcVersion(const std::string &version, const std::string &edition); + static std::string ConvertSinkVersion(const std::string &version); + + // 公共变量 + 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 index 26113694e..640494ff1 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -53,8 +53,6 @@ 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_DMVERSION = "dmVersion"; -constexpr const char *DM_TAG_EDITION = "edition"; constexpr const char *DM_TAG_ACCESS = "dmAccess"; constexpr const char *DM_TAG_PROXY = "proxy"; constexpr const char *DM_TAG_ACL = "accessControlTable"; diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index f8e0d0a7a..8fac2b80a 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -21,6 +21,7 @@ #include "access_control_profile.h" #include "dm_ability_manager.h" +#include "dm_auth_manager_base.h" #include "dm_auth_manager.h" #include "dm_common_event_manager.h" #include "dm_credential_manager.h" @@ -156,9 +157,10 @@ private: void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid); DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); int32_t InitAndRegisterAuthMgr(bool isSrcSide); + int32_t CreateAuthMgrByMessage(int sessionId, const void *data, unsigned int dataLen); private: - std::shared_ptr authMgr_; + std::shared_ptr authMgr_; std::shared_ptr deviceStateMgr_; std::shared_ptr softbusConnector_; std::shared_ptr abilityMgr_; diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 4d9b92f21..eda9c8262 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -115,7 +115,6 @@ constexpr const char* TARGET_PKG_NAME_KEY = "targetPkgName"; constexpr const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; constexpr const char* CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay"; constexpr const char* BUNDLE_NAME_KEY = "bundleName"; -constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5.1"; constexpr const char* DM_VERSION_5_0_1 = "5.0.1"; constexpr const char* DM_VERSION_5_0_2 = "5.0.2"; constexpr const char* DM_VERSION_5_0_3 = "5.0.3"; @@ -1023,7 +1022,7 @@ void DmAuthManager::RespNegotiate(const int32_t &sessionId) remoteDeviceId_ = authResponseContext_->localDeviceId; authResponseContext_->networkId = softbusConnector_->GetLocalDeviceNetworkId(); authResponseContext_->targetDeviceName = softbusConnector_->GetLocalDeviceName(); - remoteVersion_ = ConvertSrcVersion(authResponseContext_->dmVersion, authResponseContext_->edition); + remoteVersion_ = AuthManagerBase::ConvertSrcVersion(authResponseContext_->dmVersion, authResponseContext_->edition); NegotiateRespMsg(remoteVersion_); if (CompareVersion(remoteVersion_, std::string(DM_VERSION_4_1_5_1)) && (static_cast(authResponseContext_->bindLevel) >= DEVICE && @@ -1072,7 +1071,7 @@ void DmAuthManager::SendAuthRequest(const int32_t &sessionId) } remoteDeviceId_ = authResponseContext_->localDeviceId; authRequestContext_->remoteDeviceName = authResponseContext_->targetDeviceName; - remoteVersion_ = ConvertSinkVersion(authResponseContext_->dmVersion); + remoteVersion_ = AuthManagerBase::ConvertSinkVersion(authResponseContext_->dmVersion); if (timer_ != nullptr) { timer_->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); } @@ -3015,33 +3014,6 @@ void DmAuthManager::HandleDeviceNotTrust(const std::string &udid) hiChainConnector_->DeleteAllGroupByUdid(udid); } -std::string DmAuthManager::ConvertSrcVersion(const std::string &version, const std::string &edition) -{ - std::string srcVersion = ""; - if (version == "" && edition != "") { - srcVersion = edition; - } else if (version == "" && edition == "") { - srcVersion = DM_VERSION_5_0_1; - } else if (version != "" && edition == "") { - srcVersion = version; - } - LOGI("ConvertSrcVersion version %{public}s, edition %{public}s, srcVersion is %{public}s.", - version.c_str(), edition.c_str(), srcVersion.c_str()); - return srcVersion; -} - -std::string DmAuthManager::ConvertSinkVersion(const std::string &version) -{ - std::string sinkVersion = ""; - if (version == "") { - sinkVersion = DM_VERSION_4_1_5_1; - } else { - sinkVersion = version; - } - LOGI("ConvertSinkVersion version %{public}s, sinkVersion is %{public}s.", version.c_str(), sinkVersion.c_str()); - return sinkVersion; -} - void DmAuthManager::SetAuthType(int32_t authType) { authType_ = authType; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index b5907ca10..d8fbe7414 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -303,6 +303,11 @@ int32_t AuthManager::GetAclListStr(std::string &aclList) return context_->authMessageProcessor->GetAclListStr(context_, aclList); } +int32_t AuthManager::GetReason() +{ + return context_->reason; +} + // 保存秘钥 void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) { @@ -528,6 +533,12 @@ void AuthManager::ParseJsonObject(nlohmann::json jsonObject) } else { context_->accessee.bundleName = context_->sessionName; } + if (IsInt32(jsonObject, DM_TAG_PEER_USER_ID)) { + context_->accessee.userId = jsonObject[DM_TAG_PEER_USER_ID].get(); + } + if (IsInt32(jsonObject, DM_TAG_PEER_DISPLAY_ID)) { + context_->accessee.displayId = jsonObject[DM_TAG_PEER_DISPLAY_ID].get(); + } ParseHmlInfoInJsonObject(jsonObject); return; @@ -701,6 +712,7 @@ int32_t AuthManager::BindTarget(const std::string &sessionName, const PeerTarget return ERR_DM_INPUT_PARA_INVALID; } context_->peerTargetId = targetId; + bindParam_ = bindParam; std::string deviceId = ""; std::string addrType; if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) { @@ -1144,5 +1156,17 @@ int32_t AuthManager::GetPinCode(int32_t &code) return DM_OK; } +// 重新获取BindParams,以重建链路,一般用于新老协议对象切换 +void AuthManager::GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, + std::map &bindParam) +{ + pkgName = context_->sessionName; + targetId = context_->peerTargetId; + bindParam = bindParam_; + + LOGI("AuthManager::GetBindTargetParams get pkgName %{public}s to reuse", pkgName.c_str()); + return; +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 9b5758ac1..4713ae2c2 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -24,6 +24,7 @@ #include "deviceprofile_connector.h" #include "distributed_device_profile_errors.h" #include "device_auth.h" +#include "os_account_manager.h" #include "accesstoken_kit.h" #include "access_control_profile.h" #include "accesser.h" @@ -78,21 +79,6 @@ enum DmRole { DM_ROLE_FA_TO_DEVICE }; -std::string ConvertSrcVersion(const std::string &version, const std::string &edition) -{ - std::string srcVersion = ""; - if (version == "" && edition != "") { - srcVersion = edition; - } else if (version == "" && edition == "") { - srcVersion = DM_VERSION_5_0_1; - } else if (version != "" && edition == "") { - srcVersion = version; - } - LOGI("ConvertSrcVersion version %{public}s, edition %{public}s, srcVersion is %{public}s.", - version.c_str(), edition.c_str(), srcVersion.c_str()); - return srcVersion; -} - } DmAuthStateType AuthSrcStartState::GetStateType() @@ -197,6 +183,15 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptraccessee.displayId != 0) { + ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(context->accessee.displayId, + context->accessee.userId); + if (ret != DM_OK) { + LOGE("RespQueryTokenId: fail to get userId by displayId %{public}d", context->accessee.displayId); + return ERR_DM_FAILED; + } + } + // 场景1:对端指定了userId -> 校验是否为前台用户 // 场景2:对端未指定userId // 场景2.1: 单用户 -> 使用当前唯一前台用户 @@ -535,10 +530,10 @@ int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr con context->accessee.networkId = context->softbusConnector->GetLocalDeviceNetworkId(); context->accessee.deviceName = context->softbusConnector->GetLocalDeviceName(); // 为兼容历史版本,通过ConvertSrcVersion获取src端实际version - context->accesser.dmVersion = ConvertSrcVersion(context->accesser.dmVersion, + context->accesser.dmVersion = AuthManagerBase::ConvertSrcVersion(context->accesser.dmVersion, context->accesser.edition); - // 新协议只支持5.0.4之后的版本 - std::string preVersion = std::string(DM_VERSION_5_0_4); + // 旧协议最高只到5.0.9版本 + std::string preVersion = std::string(DM_VERSION_5_0_9); LOGI("AuthSinkNegotiateStateMachine::Action start version compare %{public}s to %{public}s", context->accesser.dmVersion.c_str(), preVersion.c_str()); if (CompareVersion(context->accesser.dmVersion, preVersion) == false) { diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp new file mode 100644 index 000000000..2a5fce0e9 --- /dev/null +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp @@ -0,0 +1,289 @@ +/* + * 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. + */ + +#include "dm_error_type.h" +#include "dm_auth_manager_base.h" + +#undef LOG_TAG +#define LOG_TAG "DHDM_V2" + +namespace OHOS { +namespace DistributedHardware { + +int32_t AuthManagerBase::AuthenticateDevice(const std::string &pkgName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGE("AuthenticateDevice is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::UnAuthenticateDevice(const std::string &pkgName, const std::string &udid, int32_t bindLevel) +{ + LOGE("UnAuthenticateDevice is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::UnBindDevice(const std::string &pkgName, const std::string &udid, + int32_t bindLevel, const std::string &extra) +{ + LOGE("UnBindDevice is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) +{ + LOGE("OnSessionOpened is not implemented in the current version"); +} + +void AuthManagerBase::OnSessionClosed(const int32_t sessionId) +{ + LOGE("OnSessionClosed is not implemented in the current version"); +} + +void AuthManagerBase::OnDataReceived(const int32_t sessionId, const std::string message) +{ + LOGE("OnDataReceived is not implemented in the current version"); +} + +void AuthManagerBase::OnGroupCreated(int64_t requestId, const std::string &groupId) +{ + LOGE("OnGroupCreated is not implemented in the current version"); +} + +void AuthManagerBase::OnMemberJoin(int64_t requestId, int32_t status) +{ + LOGE("OnMemberJoin is not implemented in the current version"); +} + +int32_t AuthManagerBase::EstablishAuthChannel(const std::string &deviceId) +{ + LOGE("EstablishAuthChannel is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::StartNegotiate(const int32_t &sessionId) +{ + LOGE("StartNegotiate is not implemented in the current version"); +} + +void AuthManagerBase::RespNegotiate(const int32_t &sessionId) +{ + LOGE("RespNegotiate is not implemented in the current version"); +} + +void AuthManagerBase::SendAuthRequest(const int32_t &sessionId) +{ + LOGE("SendAuthRequest is not implemented in the current version"); +} + +int32_t AuthManagerBase::StartAuthProcess(const int32_t &action) +{ + LOGE("StartAuthProcess is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::StartRespAuthProcess() +{ + LOGE("StartRespAuthProcess is not implemented in the current version"); +} + +int32_t AuthManagerBase::CreateGroup() +{ + LOGE("CreateGroup is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::ProcessPincode(int32_t pinCode) +{ + LOGE("ProcessPincode is not implemented in the current version"); + return ERR_DM_FAILED; +} + +std::string AuthManagerBase::GetConnectAddr(std::string deviceId) +{ + LOGE("GetConnectAddr is not implemented in the current version"); + return ""; +} + +int32_t AuthManagerBase::JoinNetwork() +{ + LOGE("JoinNetwork is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::AuthenticateFinish() +{ + LOGE("AuthenticateFinish is not implemented in the current version"); +} + +bool AuthManagerBase::GetIsCryptoSupport() +{ + LOGE("GetIsCryptoSupport is not implemented in the current version"); + return false; +} + +int32_t AuthManagerBase::SetAuthRequestState(std::shared_ptr authRequestState) +{ + LOGE("SetAuthRequestState is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::SetAuthResponseState(std::shared_ptr authResponseState) +{ + LOGE("SetAuthResponseState is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::GetPinCode(int32_t &code) +{ + LOGE("GetPinCode is not implemented in the current version"); + return ERR_DM_FAILED; +} + +std::string AuthManagerBase::GenerateGroupName() +{ + LOGE("GenerateGroupName is not implemented in the current version"); + return ""; +} + +void AuthManagerBase::HandleAuthenticateTimeout(std::string name) +{ + LOGE("HandleAuthenticateTimeout is not implemented in the current version"); +} + +int32_t AuthManagerBase::GeneratePincode() +{ + LOGE("GeneratePincode is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::ShowConfigDialog() +{ + LOGE("ShowConfigDialog is not implemented in the current version"); +} + +void AuthManagerBase::ShowAuthInfoDialog(bool authDeviceError) +{ + LOGE("ShowAuthInfoDialog is not implemented in the current version"); +} + +void AuthManagerBase::ShowStartAuthDialog() +{ + LOGE("ShowStartAuthDialog is not implemented in the current version"); +} + +int32_t AuthManagerBase::OnUserOperation(int32_t action, const std::string ¶ms) +{ + LOGE("OnUserOperation is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::SetPageId(int32_t pageId) +{ + LOGE("SetPageId is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::SetReasonAndFinish(int32_t reason, int32_t state) +{ + LOGE("SetReasonAndFinish is not implemented in the current version"); + return ERR_DM_FAILED; +} + +bool AuthManagerBase::IsIdenticalAccount() +{ + LOGE("IsIdenticalAccount is not implemented in the current version"); + return false; +} + +int32_t AuthManagerBase::RegisterUiStateCallback(const std::string pkgName) +{ + LOGE("RegisterUiStateCallback is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::UnRegisterUiStateCallback(const std::string pkgName) +{ + LOGE("UnRegisterUiStateCallback is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::ImportAuthCode(const std::string &pkgName, const std::string &authCode) +{ + LOGE("ImportAuthCode is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, + const std::map &bindParam) +{ + LOGE("BindTarget is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::RegisterAuthenticationType(int32_t authenticationType) +{ + LOGE("RegisterAuthenticationType is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::StopAuthenticateDevice(const std::string &pkgName) +{ + LOGE("StopAuthenticateDevice is not implemented in the current version"); + return ERR_DM_FAILED; +} + +int32_t AuthManagerBase::GetReason() +{ + LOGE("GetReason is not implemented in the current version"); + return ERR_DM_FAILED; +} + +void AuthManagerBase::GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, + std::map &bindParam) +{ + LOGE("GetBindTargetParams is not implemented in the current version"); + return; +} + +std::string AuthManagerBase::ConvertSrcVersion(const std::string &version, const std::string &edition) +{ + std::string srcVersion = ""; + if (version == "" && edition != "") { + srcVersion = edition; + } else if (version == "" && edition == "") { + srcVersion = DM_VERSION_5_1_0; + } else if (version != "" && edition == "") { + srcVersion = version; + } + LOGI("ConvertSrcVersion version %{public}s, edition %{public}s, srcVersion is %{public}s.", + version.c_str(), edition.c_str(), srcVersion.c_str()); + return srcVersion; +} + +std::string AuthManagerBase::ConvertSinkVersion(const std::string &version) +{ + std::string sinkVersion = ""; + if (version == "") { + sinkVersion = DM_VERSION_4_1_5_1; + } else { + sinkVersion = version; + } + LOGI("ConvertSinkVersion version %{public}s, sinkVersion is %{public}s.", version.c_str(), sinkVersion.c_str()); + return sinkVersion; +} + +} // namespace DistributedHardware +} // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 2b06e08cf..23d078cf1 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -27,6 +27,7 @@ #include "dm_constants.h" #include "dm_anonymous.h" #include "access_control_profile.h" +#include "dm_auth_manager_base.h" #include "dm_auth_context.h" #include "dm_auth_state_machine.h" #include "dm_crypto.h" @@ -40,13 +41,22 @@ namespace { constexpr const char* TAG_DEVICE_TYPE = "deviceType"; -void ParseNegotiateExtraInfoMessage(nlohmann::json &jsonObject, std::shared_ptr context) +void CreateNegotiateExtraInfoMessage(std::shared_ptr context, nlohmann::json &jsonExtraObject) +{ + if (context->accessee.displayId != 0) { + jsonExtraObject[DM_TAG_PEER_DISPLAY_ID] = context->accessee.displayId; + } + + return; +} + +void ParseNegotiateExtraInfoMessage(nlohmann::json &jsonExtraObject, std::shared_ptr context) { // accesser在extra中传输对端peerUserId和peerDisplayId时,从中获取userId - if (IsInt32(jsonObject, DM_TAG_PEER_USER_ID)) { - context->accessee.userId = jsonObject[DM_TAG_PEER_USER_ID].get(); - } else if (IsInt32(jsonObject, DM_TAG_PEER_DISPLAY_ID)) { - context->accessee.userId = jsonObject[DM_TAG_PEER_DISPLAY_ID].get(); + if (IsInt32(jsonExtraObject, DM_TAG_ACCESSEE_USER_ID)) { + context->accessee.userId = jsonExtraObject[DM_TAG_ACCESSEE_USER_ID].get(); + } else if (IsInt32(jsonExtraObject, DM_TAG_PEER_DISPLAY_ID)) { + context->accessee.displayId = jsonExtraObject[DM_TAG_PEER_DISPLAY_ID].get(); } return; @@ -441,6 +451,8 @@ void DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptraccesser.dmVersion; jsonObject[TAG_DEVICE_NAME] = context->accesser.deviceName; + jsonObject[DM_TAG_TOKEN_ID] = static_cast(context->accesser.tokenId); + jsonObject[TAG_DEVICE_ID_HASH] = context->accesser.deviceIdHash; jsonObject[TAG_USER_ID_HASH] = context->accesser.userIdHash; jsonObject[TAG_ACCOUNT_ID_HASH] = context->accesser.accountIdHash; @@ -450,6 +462,9 @@ void DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptraccessee.bundleName; jsonObject[TAG_BIND_LEVEL] = context->accesser.bindLevel; + jsonObject[DM_TAG_EXTRA_INFO] = nlohmann::json::object(); + CreateNegotiateExtraInfoMessage(context, jsonObject[DM_TAG_EXTRA_INFO]); + return; } @@ -755,6 +770,9 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject if (IsString(jsonObject, TAG_DEVICE_NAME)) { context->accesser.deviceName = jsonObject[TAG_DEVICE_NAME].get(); } + if (IsInt64(jsonObject, DM_TAG_TOKEN_ID)) { + context->accesser.tokenId = static_cast(jsonObject[DM_TAG_TOKEN_ID].get()); + } if (IsString(jsonObject, TAG_DEVICE_ID_HASH)) { context->accesser.deviceIdHash = jsonObject[TAG_DEVICE_ID_HASH].get(); diff --git a/services/implementation/src/dependency/softbus/softbus_session.cpp b/services/implementation/src/dependency/softbus/softbus_session.cpp index 633aca531..b10bb1137 100644 --- a/services/implementation/src/dependency/softbus/softbus_session.cpp +++ b/services/implementation/src/dependency/softbus/softbus_session.cpp @@ -172,7 +172,7 @@ int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) } int32_t msgType = jsonObject[TAG_MSG_TYPE].get(); LOGI("start, msgType: %{public}d.", msgType); - if (sessionCallback_->GetIsCryptoSupport()) { + if (sessionCallback_ != nullptr && sessionCallback_->GetIsCryptoSupport()) { LOGI("SendData Start encryption."); } int32_t ret = SendBytes(sessionId, message.c_str(), strlen(message.c_str())); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 2a3927731..bb1ab1e39 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -18,6 +18,7 @@ #include #include "app_manager.h" +#include "dm_error_type.h" #include "dm_anonymous.h" #include "dm_constants.h" #include "dm_crypto.h" @@ -36,10 +37,65 @@ using namespace OHOS::EventFwk; namespace OHOS { namespace DistributedHardware { + +namespace { + // One year 365 * 24 * 60 * 60 constexpr int32_t MAX_ALWAYS_ALLOW_SECONDS = 31536000; constexpr int32_t MIN_PIN_CODE = 100000; constexpr int32_t MAX_PIN_CODE = 999999; +// 新协议字段定义,为避免对新协议头文件依赖,不直接依赖新协议头文件 +// TODO: 需要统一到公共头文件中 +constexpr int32_t MSG_TYPE_REQ_ACL_NEGOTIATE = 80; +constexpr int32_t MSG_TYPE_RESP_ACL_NEGOTIATE = 90; +constexpr int32_t MSG_TYPE_REQ_AUTH_TERMINATE = 104; +constexpr int32_t AUTH_SRC_FINISH_STATE = 12; +constexpr const char *DM_TAG_REPLY = "REPLY"; +constexpr const char *TAG_AUTH_FINISH = "isFinish"; + +bool IsMessageOldVersion(int sessionId, const void *data, unsigned int dataLen) +{ + std::string message = std::string(reinterpret_cast(data), dataLen); + nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); + if (jsonObject.is_discarded() || !IsInt32(jsonObject, TAG_MSG_TYPE)) { + LOGE("IsMessageOldVersion decode jsonStr error"); + return false; + } + + if (jsonObject[TAG_MSG_TYPE].get() != MSG_TYPE_REQ_ACL_NEGOTIATE && + jsonObject[TAG_MSG_TYPE].get() != MSG_TYPE_RESP_ACL_NEGOTIATE) { + return false; + } + + std::string dmVersion = ""; + std::string edition = ""; + if (IsString(jsonObject, DM_TAG_DMVERSION)) { + dmVersion = jsonObject[DM_TAG_DMVERSION].get(); + } + if (IsString(jsonObject, DM_TAG_EDITION)) { + edition = jsonObject[DM_TAG_EDITION].get(); + } + dmVersion = AuthManagerBase::ConvertSrcVersion(dmVersion, edition); + + // 若版本号高于5.0.4旧协议最高版本,则不需要切换老协议 + if (CompareVersion(dmVersion, DM_VERSION_5_0_9) == true) { + return false; + } + + return true; +} + +std::string CreateTerminateMessage(void) +{ + nlohmann::json jsonObject; + jsonObject[TAG_MSG_TYPE] = MSG_TYPE_REQ_AUTH_TERMINATE; + jsonObject[DM_TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE; + jsonObject[TAG_AUTH_FINISH] = false; + + return jsonObject.dump(); +} + +} DeviceManagerServiceImpl::DeviceManagerServiceImpl() { @@ -63,7 +119,7 @@ int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide) hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); } else { // 线程已创建authMgr_,说明已有绑定事件,其他请求拒绝,返回错误码 - LOGI("BindTarget failed, this device is being bound. Please try again later."); + LOGI("DeviceManagerServiceImpl::InitAndRegisterAuthMgr authMgr_ is not null, no need to create"); //return ERR_DM_AUTH_BUSINESS_BUSY; } return DM_OK; @@ -348,9 +404,113 @@ void DeviceManagerServiceImpl::OnSessionClosed(int sessionId) SoftbusSession::OnSessionClosed(sessionId); } +int32_t DeviceManagerServiceImpl::CreateAuthMgrByMessage(int sessionId, const void *data, unsigned int dataLen) +{ + if (data == nullptr || dataLen < 0) { + LOGE("DeviceManagerServiceImpl::CreateAuthMgrByMessage fail to reveive data from DeviceManagerServiceImpl " + "with dataLen: %{public}d", dataLen); + return ERR_DM_INPUT_PARA_INVALID; + } + + std::string message = std::string(reinterpret_cast(data), dataLen); + nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); + if (jsonObject.is_discarded()) { + LOGE("DeviceManagerServiceImpl::CreateAuthMgrByMessage decode jsonStr error"); + return ERR_DM_JSON_PARSE_STRING; + } + + // 获取版本号 + std::string dmVersion; + std::string edition = ""; + if (IsString(jsonObject, DM_TAG_DMVERSION) == false) { + LOGE("DeviceManagerServiceImpl::CreateAuthMgrByMessage decode dmversion error"); + return ERR_DM_JSON_PARSE_STRING; + } + dmVersion = jsonObject[DM_TAG_DMVERSION].get(); + if (IsString(jsonObject, DM_TAG_EDITION)) { + edition = jsonObject[DM_TAG_EDITION].get(); + } + dmVersion = AuthManagerBase::ConvertSrcVersion(dmVersion, edition); + + if (CompareVersion(dmVersion, DM_VERSION_5_1_0) == false) { + // 创建老协议对象 + authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, + listener_, hiChainAuthConnector_); + + // 参数2 sessionSide为0,authMgr_为空一定是sink端,src端会在BindTarget时创建协议对象 + authMgr_->OnSessionOpened(sessionId, 0, 0); + LOGI("DeviceManagerServiceImpl::CreateAuthMgrByMessage sink transfer to old version success"); + return DM_OK; + } + + // 创建新协议对象 + return InitAndRegisterAuthMgr(false); +} + +// 版本降级时,基于报文判断是src还是sink +// src: 收到90报文 +// sink:收到80报文 +bool IsAuthManagerSourceByMessage(const void *data, unsigned int dataLen) +{ + std::string message = std::string(reinterpret_cast(data), dataLen); + // 走到这里已经确认可以转json,所以不需要再判断 + nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); + + return jsonObject[TAG_MSG_TYPE].get() == MSG_TYPE_RESP_ACL_NEGOTIATE; +} + void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) { + int32_t ret; + + if (data == nullptr || dataLen < 0) { + LOGE("DeviceManagerServiceImpl::OnBytesReceived fail to reveive data from DeviceManagerServiceImpl " + "with dataLen: %{public}d", dataLen); + return; + } + + /** + 监听80/90报文 + 新-老:src端收到90报文时发现版本不匹配问题,重新BindTartget + 老-新:sink端收到80报文时发现版本不匹配问题,重新OnSessionOpened和OnBytesReceived + + TODO: 考虑authMgr_的切换是否有多线程问题 + */ + if (authMgr_->isAuthNewVersion_ && IsMessageOldVersion(sessionId, data, dataLen)) { + std::string pkgName; + PeerTargetId peerTargetId; + std::map bindParam; + authMgr_->GetBindTargetParams(pkgName, peerTargetId, bindParam); + authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, + listener_, hiChainAuthConnector_); + authMgr_->isAuthNewVersion_ = false; + softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); + hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); + + if (IsAuthManagerSourceByMessage(data, dataLen)) { + // 发送停止报文 + // 不能走新协议的停止,新协议是信号机制,无法串行停止,会存在时延,导致未停止就创建了新对象, + // 然后新协议的超时机制会再次停止softbus + std::string endMessage = CreateTerminateMessage(); + (void)softbusConnector_->GetSoftbusSession()->SendData(sessionId, endMessage); + softbusConnector_->GetSoftbusSession()->OnSessionClosed(sessionId); + + ret = authMgr_->BindTarget(pkgName, peerTargetId, bindParam); + if (ret != DM_OK) { + LOGE("DeviceManagerServiceImpl::OnBytesReceived authManager BindTarget failed"); + return; + } + LOGI("DeviceManagerServiceImpl::OnBytesReceived src transfer to old version success"); + return; + } + + // 参数2 sessionSide为0,authMgr_为空一定是sink端,src端会在BindTarget时创建协议对象 + authMgr_->OnSessionOpened(sessionId, 0, 0); + LOGI("DeviceManagerServiceImpl::OnBytesReceived src transfer to old version success"); + } + SoftbusSession::OnBytesReceived(sessionId, data, dataLen); + LOGI("DeviceManagerServiceImpl::OnBytesReceived in bytes received"); } int32_t DeviceManagerServiceImpl::RequestCredential(const std::string &reqJsonStr, std::string &returnJsonStr) @@ -1115,3 +1275,4 @@ extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) } } // namespace DistributedHardware } // namespace OHOS +; \ No newline at end of file -- Gitee From 6b3e651f13e952b8670c0ca42549c5f940557b33 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 13 Mar 2025 19:28:32 +0800 Subject: [PATCH 201/382] =?UTF-8?q?=E6=96=B0PIN=E8=AE=A4=E8=AF=81=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E6=9C=BA=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication_v2/dm_auth_context.h | 4 +- .../include/authentication_v2/dm_auth_state.h | 2 + .../src/authentication_v2/auth_manager.cpp | 37 +++-- .../auth_stages/auth_confirm.cpp | 23 ++- .../auth_stages/auth_pin_auth.cpp | 132 +++++++++++++++--- .../dm_auth_message_processor.cpp | 5 +- 6 files changed, 162 insertions(+), 41 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index b4329f0c5..b0de06b78 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -151,7 +151,7 @@ struct DmAuthContext { DmAuthType authType{DmAuthType::AUTH_TYPE_PIN}; // 认证方式,弹pin码、超声pin码、导入pin码 std::vector authTypeList; // 共有认证方式列表 uint32_t currentAuthTypeIdx{0}; // 认证方式索引 - int32_t authFailTimes{0}; // 认证失败次数,查过3次结束认证 + int32_t inputPinAuthFailTimes{0}; // 输入PIN认证失败次数,超过3次则失败 int32_t pinCode{INVALID_PINCODE}; // 生成的PIN码 int32_t connDelayCloseTime; // 链路延迟释放时间, 授权结束后不自动断链(有业务需要使用)保留字段 int32_t reason{DM_OK}; // 本端失败的原因 @@ -196,7 +196,7 @@ struct DmAuthContext { std::string importAuthCode = ""; std::map> authenticationMap; PeerTargetId peerTargetId; - bool fallBackToInputPin{false}; // 是否已经回退到输入PIN码 + bool pinNegotiateStarted{false}; // pin协商是否已开始 bool isAuthenticateDevice = false; // 获取设备ID diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index edc83180d..8f889bc71 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -163,6 +163,8 @@ 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 { diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index b5907ca10..248beb419 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -964,17 +964,18 @@ void AuthSrcManager::AuthDeviceError(int64_t requestId, int32_t errorCode) curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE || curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE) { LOGI("AuthSrcManager::AuthDeviceError Auth pin err."); + #ifndef NEW_PIN_STATE // todo del if (context_->authType == DmAuthType::AUTH_TYPE_PIN) { - context_->authFailTimes++; - } else if (!context_->fallBackToInputPin) { + context_->inputPinAuthFailTimes++; + } else if (!context_->pinNegotiateStarted) { LOGI("AuthSrcManager::AuthDeviceError fallback to input pin."); - context_->fallBackToInputPin = true; + context_->pinNegotiateStarted = true; } else { - context_->authFailTimes++; + context_->inputPinAuthFailTimes++; } // 失败 MAX_AUTH_FAIL_TIMES 次后,走认证失败 ON_FAIL - if (context_->authFailTimes >= MAX_AUTH_FAIL_TIMES) { + if (context_->inputPinAuthFailTimes >= MAX_AUTH_FAIL_TIMES) { LOGI("AuthSrcManager::AuthDeviceError Auth pin err fail."); context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); } else { @@ -984,6 +985,13 @@ void AuthSrcManager::AuthDeviceError(int64_t requestId, int32_t errorCode) context_->authStateMachine->TransitionTo(std::make_shared()); LOGI("AuthSrcManager::AuthDeviceError Auth pin err, will retry."); } + #else + if (context_->authType == DmAuthType::AUTH_TYPE_PIN) { + context_->inputPinAuthFailTimes++; + } + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); + context_->authStateMachine->TransitionTo(std::make_shared()); + #endif } LOGI("AuthSrcManager::AuthDeviceError leave."); } @@ -995,11 +1003,12 @@ void AuthSinkManager::AuthDeviceError(int64_t requestId, int32_t errorCode) if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE || curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE) { + #ifndef NEW_PIN_STATE // todo del if (context_->authType == DmAuthType::AUTH_TYPE_PIN) { - context_->authFailTimes++; - } else if (!context_->fallBackToInputPin) { + context_->inputPinAuthFailTimes++; + } else if (!context_->pinNegotiateStarted) { LOGI("AuthSinkManager::AuthDeviceError fallback to input pin."); - context_->fallBackToInputPin = true; + context_->pinNegotiateStarted = true; // 生成PIN码 AuthSinkStatePinAuthComm::GeneratePincode(context_); // 显示PIN码 @@ -1009,19 +1018,27 @@ void AuthSinkManager::AuthDeviceError(int64_t requestId, int32_t errorCode) context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); } } else { - context_->authFailTimes++; + context_->inputPinAuthFailTimes++; } // 失败 MAX_AUTH_FAIL_TIMES 次后,走认证失败 ON_FAIL - if (context_->authFailTimes >= MAX_AUTH_FAIL_TIMES) { + if (context_->inputPinAuthFailTimes >= MAX_AUTH_FAIL_TIMES) { LOGI("AuthSinkManager::AuthDeviceError Auth pin err fail."); context_->reason = ERR_DM_INPUT_PARA_INVALID; context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); } else { // Notify ON_ERROR 事件,对应 Action 内会当正常重试处理,而非失败 + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); // 将由新收到的120报文触发回退状态到 AuthSinkPinAuthStartState LOGI("AuthSinkManager::AuthDeviceError Auth pin err, will retry."); } + #else + if (context_->authType == DmAuthType::AUTH_TYPE_PIN) { + context_->inputPinAuthFailTimes++; + } + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); + context_->authStateMachine->TransitionTo(std::make_shared()); + #endif } LOGI("AuthSinkManager::AuthDeviceError leave."); } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 1e17386a5..498b2aa95 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -70,8 +70,8 @@ int32_t AuthSrcConfirmState::DoPinAuth(std::shared_ptr context) context->currentAuthTypeIdx = 0; context->authType = context->authTypeList[0]; - // 首次认证是输入PIN时,先授权 - if (context->authType == DmAuthType::AUTH_TYPE_PIN) { + // 首次认证是输入PIN或超声PIN时,先授权 + if (context->authType == DmAuthType::AUTH_TYPE_PIN || context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { // send 100 context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_USER_CONFIRM, context); @@ -82,7 +82,7 @@ int32_t AuthSrcConfirmState::DoPinAuth(std::shared_ptr context) } else { // 少一轮 100,110 // 转 AuthSrcPinAuthStartState - context->authStateMachine->TransitionTo(std::make_shared()); + context->authStateMachine->TransitionTo(std::make_shared()); } LOGI("AuthSrcConfirmState::DoPinAuth end"); return DM_OK; @@ -131,6 +131,7 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) // 无凭据 return DoPinAuth(context); #else +#ifndef NEW_PIN_STATE // todo del // todo del 无凭据 send 100 context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_USER_CONFIRM, context); @@ -140,6 +141,9 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) }); LOGI("AuthSrcConfirmState::Action ok"); return DM_OK; +#else + return DoPinAuth(context); +#endif #endif } @@ -269,7 +273,7 @@ int64_t AuthSinkConfirmState::GenRequestId(std::shared_ptr contex int32_t AuthSinkConfirmState::Action(std::shared_ptr context) { -#if 0 // 新状态流程,待测试 +#ifdef NEW_PIN_STATE // todo 新状态流程,待测试 LOGI("AuthSinkConfirmState::Action start"); // 停止授权报文计时 context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); @@ -313,14 +317,9 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) // 发送110报文 context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); - if (context->authType == DmAuthType::AUTH_TYPE_PIN) { - // 生成PIN码 - AuthSinkStatePinAuthComm::GeneratePincode(context); - // 显示PIN码 - if ((ret = AuthSinkStatePinAuthComm::ShowAuthInfoDialog(context)) != DM_OK) { - return ret; - } - } + + context->authStateMachine->TransitionTo(std::make_shared()); + LOGI("AuthSinkConfirmState::Action ok"); return DM_OK; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index dad765e71..590dd62b1 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -147,9 +147,8 @@ int32_t AuthSrcPinAuthStartState::GetPinCodeFromServerInfo(std::shared_ptr context) { LOGI("AuthSrcPinAuthStartState::GetPinCode start"); -#if 1 // todo del - if (context->authFailTimes == 0) { - if (context->authType == DmAuthType::AUTH_TYPE_PIN || context->fallBackToInputPin) { + if (context->inputPinAuthFailTimes == 0) { + if (context->authType == DmAuthType::AUTH_TYPE_PIN || context->pinNegotiateStarted) { // 拉起PIN码输入界面 auto ret = ShowStartAuthDialog(context); if (ret != DM_OK) { @@ -179,13 +178,7 @@ int32_t AuthSrcPinAuthStartState::GetPinCode(std::shared_ptr cont LOGE("AuthSrcPinAuthStartState::GetPinCode not USER_OPERATION_TYPE_DONE_PINCODE_INPUT err"); return STOP_BIND; } -#else // 新状态流程,待测试 - // 如果是PIN,拉界面 - // 如果超声 TODO - // 如果导入PIN 直接获得 - // 失败重试前,设置错误次数和类型切换 -#endif LOGI("AuthSrcPinAuthStartState::GetPinCode input ok"); return DM_OK; } @@ -217,10 +210,10 @@ int32_t AuthSrcPinAuthStartState::AuthDevice(std::shared_ptr cont int32_t AuthSrcPinAuthStartState::Action(std::shared_ptr context) { LOGI("AuthSrcPinAuthStartState::Action start"); - + #ifndef NEW_PIN_STATE // todo del context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); // 首次进入停止计时器 - if (context->authFailTimes == 0 && !context->fallBackToInputPin) { + if (context->inputPinAuthFailTimes == 0 && !context->pinNegotiateStarted) { context->timer->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); } @@ -230,7 +223,7 @@ int32_t AuthSrcPinAuthStartState::Action(std::shared_ptr context) LOGE("AuthSrcPinAuthStartState::Action GetPinCode err"); return ret; } - + #endif // 做认证 发120报文 return AuthDevice(context); } @@ -395,7 +388,43 @@ DmAuthStateType AuthSrcPinNegotiateStartState::GetStateType() int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr context) { - return ERR_DM_FAILED; + if (!context->pinNegotiateStarted) { + // 首次认证 + context->pinNegotiateStarted = true; + context->timer->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); + int32_t authResult = context->authResult; + if (authResult != USER_OPERATION_TYPE_ALLOW_AUTH && + authResult != USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + LOGE("AuthSrcPinNegotiateStartState::Action authResult not allow"); + context->reason = ERR_DM_BIND_USER_CANCEL; + return ERR_DM_BIND_USER_CANCEL; + } + } else { + // 回退处理 + if (context->authType == DmAuthType::AUTH_TYPE_PIN && context->inputPinAuthFailTimes < MAX_AUTH_FAIL_TIMES) { + LOGI("AuthSrcPinNegotiateStartState::Action input pin auth err, retry"); + } else { + if (context->currentAuthTypeIdx + 1 >= context->authTypeList.size()) { + LOGE("AuthSrcPinNegotiateStartState::Action all auth type failed"); + context->reason = ERR_DM_AUTH_REJECT; + return ERR_DM_AUTH_REJECT; + } + context->currentAuthTypeIdx++; + context->authType = context->authTypeList[context->currentAuthTypeIdx]; + } + } + + if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + context->authStateMachine->TransitionTo(std::make_shared()); + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN) { + context->authStateMachine->TransitionTo(std::make_shared()); + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { + context->authStateMachine->TransitionTo(std::make_shared()); + } else { + LOGE("AuthSrcPinNegotiateStartState::Action authType not support"); + return ERR_DM_FAILED; + } + return DM_OK; } DmAuthStateType AuthSrcPinInputState::GetStateType() @@ -403,9 +432,47 @@ DmAuthStateType AuthSrcPinInputState::GetStateType() return DmAuthStateType::AUTH_SRC_PIN_INPUT_STATE; } +int32_t AuthSrcPinInputState::ShowStartAuthDialog(std::shared_ptr context) +{ + LOGI("AuthSrcPinInputState::ShowStartAuthDialog start."); + if (DmAuthState::IsScreenLocked()) { + LOGE("AuthSrcPinInputState screen is locked."); + context->reason = ERR_DM_BIND_USER_CANCEL; + return STOP_BIND; + } + DmDialogManager::GetInstance().ShowInputDialog(context->accessee.deviceName); + LOGI("AuthSrcPinInputState::ShowStartAuthDialog end."); + return DM_OK; +} + int32_t AuthSrcPinInputState::Action(std::shared_ptr context) { - return ERR_DM_FAILED; + LOGI("AuthSrcPinInputState::Action start"); + if (context->inputPinAuthFailTimes == 0) { + // 拉起PIN码输入界面 + auto ret = ShowStartAuthDialog(context); + if (ret != DM_OK) { + return ret; + } + } else { + // 清空PIN输入框,提示用户重试 + context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); + } + + LOGI("AuthSrcPinInputState::Action waitting user operation"); + // 等待用户输密码操作完成 + if(DmEventType::ON_USER_OPERATION != context->authStateMachine->WaitExpectEvent(DmEventType::ON_USER_OPERATION)) { + LOGI("AuthSrcPinInputState::Action wait ON_USER_OPERATION err"); + return STOP_BIND; // 外部事件错误,中止流程 + } + + if (context->pinInputResult != USER_OPERATION_TYPE_DONE_PINCODE_INPUT) { + LOGE("AuthSrcPinInputState::Action not USER_OPERATION_TYPE_DONE_PINCODE_INPUT err"); + return STOP_BIND; + } + context->authStateMachine->TransitionTo(std::make_shared()); + LOGI("AuthSrcPinInputState::Action input ok"); + return DM_OK; } DmAuthStateType AuthSinkPinNegotiateStartState::GetStateType() @@ -415,7 +482,34 @@ DmAuthStateType AuthSinkPinNegotiateStartState::GetStateType() int32_t AuthSinkPinNegotiateStartState::Action(std::shared_ptr context) { - return ERR_DM_FAILED; + if (!context->pinNegotiateStarted) { + context->pinNegotiateStarted = true; + } else { + // 回退处理 + if (context->authType == DmAuthType::AUTH_TYPE_PIN && context->inputPinAuthFailTimes < MAX_AUTH_FAIL_TIMES) { + LOGI("AuthSinkPinNegotiateStartState::Action input pin auth err, retry"); + } else { + if (context->currentAuthTypeIdx + 1 >= context->authTypeList.size()) { + LOGE("AuthSinkPinNegotiateStartState::Action all auth type failed"); + context->reason = ERR_DM_AUTH_REJECT; + return ERR_DM_AUTH_REJECT; + } + context->currentAuthTypeIdx++; + context->authType = context->authTypeList[context->currentAuthTypeIdx]; + } + } + if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + LOGI("AuthSinkPinNegotiateStartState::Action import auth code"); + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN) { + LOGI("AuthSinkPinNegotiateStartState::Action input pin"); + context->authStateMachine->TransitionTo(std::make_shared()); + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { + LOGI("AuthSinkPinNegotiateStartState::Action ultrasonic pin"); + } else { + LOGE("AuthSrcPinNegotiateStartState::Action authType not support"); + return ERR_DM_FAILED; + } + return DM_OK; } DmAuthStateType AuthSinkPinDisplayState::GetStateType() @@ -425,7 +519,13 @@ DmAuthStateType AuthSinkPinDisplayState::GetStateType() int32_t AuthSinkPinDisplayState::Action(std::shared_ptr context) { - return ERR_DM_FAILED; + if (context->inputPinAuthFailTimes == 0) { + // 生成PIN码 + AuthSinkStatePinAuthComm::GeneratePincode(context); + // 显示PIN码 + return AuthSinkStatePinAuthComm::ShowAuthInfoDialog(context); + } + return DM_OK; } DmAuthStateType AuthSrcPinNegotiateUltrasonicPinState::GetStateType() diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 2b06e08cf..17e8a4030 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -885,8 +885,11 @@ int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const nlohmann::json if (IsInt32(json, DM_TAG_AUTH_RESULT)) { context->authResult = static_cast(json[DM_TAG_AUTH_RESULT].get()); } - +#ifndef NEW_PIN_STATE // todo del context->authStateMachine->TransitionTo(std::make_shared()); +#else + context->authStateMachine->TransitionTo(std::make_shared()); +#endif return DM_OK; } int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const nlohmann::json &json, -- Gitee From 5da0b91f0e47ddd315c5a9452929ca8a71d09470 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 13 Mar 2025 19:34:15 +0800 Subject: [PATCH 202/382] =?UTF-8?q?=E6=96=B0PIN=E8=AE=A4=E8=AF=81=E7=8A=B6?= =?UTF-8?q?=E6=80=81=E6=9C=BA=E5=AE=9E=E7=8E=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../implementation/src/authentication_v2/auth_manager.cpp | 2 ++ .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 7 +++++-- 2 files changed, 7 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 248beb419..22736b3df 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -45,7 +45,9 @@ namespace { constexpr int32_t MIN_PIN_CODE = 100000; constexpr int32_t MAX_PIN_CODE = 999999; +#ifndef NEW_PIN_STATE // todo del const int32_t MAX_AUTH_FAIL_TIMES = 3; +#endif int32_t GetCloseSessionDelaySeconds(std::string &delaySecondsStr) { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 590dd62b1..818ee8e50 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -33,6 +33,7 @@ namespace OHOS { namespace DistributedHardware { +constexpr int32_t MAX_AUTH_INPUT_PIN_FAIL_TIMES = 3; constexpr int32_t SESSION_HEARTBEAT_TIMEOUT = 20; constexpr int32_t MIN_PIN_CODE = 100000; constexpr int32_t MAX_PIN_CODE = 999999; @@ -401,7 +402,8 @@ int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr con } } else { // 回退处理 - if (context->authType == DmAuthType::AUTH_TYPE_PIN && context->inputPinAuthFailTimes < MAX_AUTH_FAIL_TIMES) { + if (context->authType == DmAuthType::AUTH_TYPE_PIN && + context->inputPinAuthFailTimes < MAX_AUTH_INPUT_PIN_FAIL_TIMES) { LOGI("AuthSrcPinNegotiateStartState::Action input pin auth err, retry"); } else { if (context->currentAuthTypeIdx + 1 >= context->authTypeList.size()) { @@ -486,7 +488,8 @@ int32_t AuthSinkPinNegotiateStartState::Action(std::shared_ptr co context->pinNegotiateStarted = true; } else { // 回退处理 - if (context->authType == DmAuthType::AUTH_TYPE_PIN && context->inputPinAuthFailTimes < MAX_AUTH_FAIL_TIMES) { + if (context->authType == DmAuthType::AUTH_TYPE_PIN && + context->inputPinAuthFailTimes < MAX_AUTH_INPUT_PIN_FAIL_TIMES) { LOGI("AuthSinkPinNegotiateStartState::Action input pin auth err, retry"); } else { if (context->currentAuthTypeIdx + 1 >= context->authTypeList.size()) { -- Gitee From d965f3ca61fe0c5c5a4ae6244e137db186d7a07c Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Thu, 13 Mar 2025 20:05:52 +0800 Subject: [PATCH 203/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9180-200?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../authentication_v2/dm_auth_context.h | 6 +- .../dm_auth_message_processor.h | 11 +- .../include/authentication_v2/dm_auth_state.h | 2 +- .../dependency/softbus/softbus_connector.h | 1 + .../auth_stages/auth_acl.cpp | 86 ++++++++++---- .../dm_auth_message_processor.cpp | 107 +++++++++++++----- .../src/authentication_v2/dm_auth_state.cpp | 6 +- .../dependency/softbus/softbus_connector.cpp | 21 ++++ 8 files changed, 181 insertions(+), 59 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index b4329f0c5..5a206a32c 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -134,9 +134,11 @@ struct DmAccess { std::string dmVersion; // 版本 5.1.0 std::string edition; // 用于5.1.0版本前的兼容,协助版本协商 std::string aclList; //可信关系列表,用于数据老化 KV格式 - std::vector aclChecksumList; // 可信关系列表,用于数据老化 + std::vector accesserStrList; + std::vector accesseeStrList; // 可信关系列表,用于数据老化 std::string credentialInfos; //凭据信息(点对点,同账号,..) 只保存凭据类型 kv结构 std::string extraInfo; //可扩展字段,kv结构 + std::string OpenAuthDeviceId; }; // TODO 统一用初始化列表进行初始化 @@ -179,8 +181,6 @@ struct DmAuthContext { DmPeerTarget peerTarget; // 对端目标的信息 DmAccess accesser; DmAccess accessee; - DmAccess encryAccesser; // 密文阶段accesser - DmAccess encryAccessee; // 密文阶段accessee std::multimap proxy; // 前面是accesser,后面是accessee std::shared_ptr authStateMachine; // 状态机 diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 26113694e..d68d022e9 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -208,7 +208,8 @@ public: DmAccess &access, std::string trustDeviceId); // 对acl进行checksum - std::string ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl); + bool ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl, + std::vector &accesserStrList, std::vector &accesseeStrList); // 提取本端ACL 用于消息解析和总线使用 无ACL会返回空字符串 json格式字符串:{dmversion:x,accesser:[{accesserDeviceId:y,...},...],accessee:{...}} int32_t GetAclListStr(std::shared_ptr &context, std::string &aclList); @@ -247,7 +248,7 @@ private: // 解析 190报文信息 MSG_TYPE_RESP_DATA_SYNC 存放对方密文四元组,acl sp skid int32_t ParseMessageSyncResp(const nlohmann::json &jsonObject, std::shared_ptr context); // 解析 200报文信息 - int32_t ParseMessageFinish(std::shared_ptr context, nlohmann::json &jsonObject); + int32_t ParseMessageFinish(const nlohmann::json &jsonObject, std::shared_ptr context); // 创建 80报文 void CreateNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject); @@ -297,6 +298,12 @@ private: 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 SetAppAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee); + void SetUserAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee); std::shared_ptr cryptoMgr_ = nullptr; }; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index edc83180d..d5f860689 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -115,7 +115,7 @@ public: virtual ~DmAuthState() {}; virtual DmAuthStateType GetStateType() = 0; virtual int32_t Action(std::shared_ptr context) = 0; // 执行状态对应的action动作 - void SyncAclList(std::shared_ptr context, int32_t accountId, + void SyncAclList(std::shared_ptr context, std::string credId, int32_t sessionKeyId, int32_t aclId); static bool IsScreenLocked(); static int32_t GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut); diff --git a/services/implementation/include/dependency/softbus/softbus_connector.h b/services/implementation/include/dependency/softbus/softbus_connector.h index 996ff36df..3dde3b95b 100644 --- a/services/implementation/include/dependency/softbus/softbus_connector.h +++ b/services/implementation/include/dependency/softbus/softbus_connector.h @@ -85,6 +85,7 @@ public: */ static void JoinLnnByHml(int32_t sessionId, int32_t sessionKeyId, int32_t remoteSessionKeyId); + static void JoinLnn(const std::string &deviceId, const std::string &remoteUdidHash); public: SoftbusConnector(); ~SoftbusConnector(); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index a40260434..9561ebb48 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -21,6 +21,9 @@ #include "deviceprofile_connector.h" #include "dm_auth_context.h" #include "dm_constants.h" +#include "auth_manager.h" +#include "multiple_user_connector.h" +#include "dm_crypto.h" namespace OHOS { namespace DistributedHardware { @@ -41,10 +44,10 @@ int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) { LOGI("AuthSinkDataSyncState::Action start"); // 判断密文阶段和明文阶段的四元组是否相同,不同则直接结束 - bool isSame = context->encryAccesser.deviceId == context->accesser.deviceId && - context->encryAccesser.userId == context->accesser.userId && - context->encryAccesser.accountId == context->accesser.accountId && - context->encryAccesser.tokenId == context->accesser.tokenId; + bool isSame = Crypto::Sha256(context->accesser.deviceId) == context->accesser.deviceIdHash && + Crypto::Sha256(std::to_string(context->accesser.userId)) == context->accesser.userIdHash && + Crypto::Sha256(context->accesser.accountId) == context->accesser.accountIdHash && + Crypto::Sha256(std::to_string(context->accesser.tokenId)) == context->accesser.tokenIdHash; if (!isSame) { LOGE("data between two stages different, stop auth"); context->reply = DM_AUTHENTICATE_FINISH; @@ -69,19 +72,14 @@ int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) } // 比较双端的acl for (auto &sinkAcl : sinkAclList) { - std::string aclChecksum = context->authMessageProcessor->ChecksumAcl(sinkAcl); - auto item = find(context->encryAccesser.aclChecksumList.begin(), - context->encryAccesser.aclChecksumList.end(), aclChecksum); - if (item != context->encryAccesser.aclChecksumList.end()) { + bool res = context->authMessageProcessor->ChecksumAcl(srcAcl, + context->accesser.accesserStrList, context->accesser.accesseeStrList); + if (res) { continue; } - SyncAclList(context, std::atoi(sinkAcl.GetAccessee().GetAccesseeAccountId().c_str()), - std::to_string(sinkAcl.GetAccessee().GetAccesseeCredentialId()), + SyncAclList(context, std::to_string(sinkAcl.GetAccessee().GetAccesseeCredentialId()), sinkAcl.GetAccessee().GetAccesseeSessionKeyId(), sinkAcl.GetAccessControlId()); } - // 保存本次acl - context->authMessageProcessor->PutAccessControlList(context, context->accessee, context->accesser.deviceId); - // 同步本端的sp信息,不确定格式,暂不做 context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_DATA_SYNC, context); @@ -99,10 +97,10 @@ int32_t AuthSrcFinishState::Action(std::shared_ptr context) { LOGI("AuthSrcFinishState::Action start"); // 判断密文阶段和明文阶段的四元组是否相同,不同则直接结束 - bool isSame = context->encryAccessee.deviceId == context->accessee.deviceId && - context->encryAccessee.userId == context->accessee.userId && - context->encryAccessee.accountId == context->accessee.accountId && - context->encryAccessee.tokenId == context->accessee.tokenId; + bool isSame = Crypto::Sha256(context->accessee.deviceId) == context->accessee.deviceIdHash && + Crypto::Sha256(std::to_string(context->accessee.userId)) == context->accessee.userIdHash && + Crypto::Sha256(context->accessee.accountId) == context->accessee.accountIdHash && + Crypto::Sha256(std::to_string(context->accessee.tokenId)) == context->accessee.tokenIdHash; if (!isSame) { LOGE("data between two stages different, stop auth"); // 不同直接结束,发送200给sink端 @@ -129,14 +127,12 @@ int32_t AuthSrcFinishState::Action(std::shared_ptr context) } // 比较双端的acl for (auto &srcAcl : srcAclList) { - std::string aclChecksum = context->authMessageProcessor->ChecksumAcl(srcAcl); - auto item = find(context->encryAccessee.aclChecksumList.begin(), - context->encryAccessee.aclChecksumList.end(), aclChecksum); - if (item != context->encryAccessee.aclChecksumList.end()) { + bool res = context->authMessageProcessor->ChecksumAcl(srcAcl, + context->accessee.accesserStrList, context->accessee.accesseeStrList); + if (res) { continue; } - SyncAclList(context, std::atoi(srcAcl.GetAccesser().GetAccesserAccountId().c_str()), - std::to_string(srcAcl.GetAccesser().GetAccesserCredentialId()), + SyncAclList(context, std::to_string(srcAcl.GetAccesser().GetAccesserCredentialId()), srcAcl.GetAccesser().GetAccesserSessionKeyId(), srcAcl.GetAccessControlId()); } // 保存本次acl @@ -145,7 +141,20 @@ int32_t AuthSrcFinishState::Action(std::shared_ptr context) // 触发组网 if (!context->accesser.isOnline) { - context->softbusConnector->JoinLnn(context->accessee.deviceId); + if (AuthManager::IsHmlSessionType(context->connSessionType)) { + LOGI("AuthSrcFinishState joinLnn context.userSessionKeyId: %{public}d, ee.userSessionKeyId: %{public}d", + context->userSessionKeyId, context->accessee.userSessionKeyId); + context->softbusConnector->JoinLnnByHml(context->sessionId, + context->userSessionKeyId, context->accessee.userSessionKeyId); + } else { + char udidHashTmp[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetUdidHash(context->accessee.deviceId, reinterpret_cast(udidHashTmp)) != DM_OK) { + LOGE("AuthSrcFinishState joinLnn get udidhash by udid: %{public}s failed", context->accessee.deviceId.c_str()); + return ERR_DM_FAILED; + } + std::string peerUdidHash = std::string(udidHashTmp); + context->softbusConnector->JoinLnn(context->accessee.OpenAuthDeviceId, peerUdidHash); + } } context->reason = DM_OK; context->reply = DM_AUTHENTICATE_FINISH; @@ -163,6 +172,20 @@ DmAuthStateType AuthSrcFinishState::GetStateType() void AuthSrcFinishState::SourceFinish(std::shared_ptr context) { + if (context->reason != DM_OK) { + int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); + // 根据凭据id 删除sink端多余的凭据 + int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, context->accesser.appCredentialId); + if (ret != DM_OK) { + LOGE("SourceFinish DeleteCredential failed."); + } + // 根据skid删除sk,删除skid + ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accesser.sessionKeyId); + if (ret != DM_OK) { + LOGE("SourceFinish DeleteSessionKey failed."); + } + } + context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); context->authStateMachine = nullptr; context->authUiStateMgr = nullptr; context->hiChainAuthConnector = nullptr; @@ -181,6 +204,7 @@ void AuthSrcFinishState::SourceFinish(std::shared_ptr context) int32_t AuthSinkFinishState::Action(std::shared_ptr context) { LOGI("AuthSinkFinishState::Action start"); + context->authMessageProcessor->PutAccessControlList(context, context->accessee, context->accesser.deviceId); SinkFinish(context); LOGI("AuthSinkFinishState::Action ok"); return DM_OK; @@ -193,6 +217,20 @@ DmAuthStateType AuthSinkFinishState::GetStateType() void AuthSinkFinishState::SinkFinish(std::shared_ptr context) { + if (context->reason != DM_OK) { + int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); + // 根据凭据id 删除sink端多余的凭据 + int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, context->accessee.appCredentialId); + if (ret != DM_OK) { + LOGE("SinkFinish DeleteCredential failed."); + } + // 根据skid删除sk,删除skid + ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accessee.sessionKeyId); + if (ret != DM_OK) { + LOGE("SinkFinish DeleteSessionKey failed."); + } + } + context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); context->authStateMachine = nullptr; context->authUiStateMgr = nullptr; context->hiChainAuthConnector = nullptr; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 2b06e08cf..da115b086 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -78,10 +78,9 @@ int32_t DmAuthMessageProcessor::SaveSessionKeyToDP(int32_t &skId) return DeviceProfileConnector::GetInstance().PutSessionKey(sk, skId); } -int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptr context, - DmAccess &access, std::string trustDeviceId) +void DmAuthMessageProcessor::SetAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::AccessControlProfile &profile) { - LOGI("Start."); uint32_t bindType = DM_ACROSS_ACCOUNT; if (context->accesser.accountId == "ohosAnonymousUid" || context->accessee.accountId == "ohosAnonymousUid") { bindType = DM_POINT_TO_POINT; @@ -90,7 +89,15 @@ int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptrauthResult == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { authenticationType = ALLOW_AUTH_ALWAYS; } - DistributedDeviceProfile::Accesser accesser; + profile.SetBindType(bindType); + profile.SetAuthenticationType(authenticationType); + profile.SetStatus(ACTIVE); + profile.SetDeviceIdType((int32_t)DistributedDeviceProfile::DeviceIdType::UDID); +} + +void DmAuthMessageProcessor::SetAppAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee) +{ accesser.SetAccesserDeviceId(context->accesser.deviceId); accesser.SetAccesserUserId(context->accesser.userId); accesser.SetAccesserAccountId(context->accesser.accountId); @@ -99,9 +106,8 @@ int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptraccesser.deviceName); accesser.SetAccesserServiceId(context->accesser.serviceId); accesser.SetAccesserCredentialId(context->accesser.credentialId); - accesser.SetAccesserSessionKeyId(context->accesser.sessionKeyId); + accesser.SetAccesserSessionKeyId(context->accesser.appSessionKeyId); accesser.SetAccesserSKTimeStamp(context->accesser.skTimeStamp); - DistributedDeviceProfile::Accessee accessee; accessee.SetAccesseeDeviceId(context->accessee.deviceId); accessee.SetAccesseeUserId(context->accessee.userId); accessee.SetAccesseeAccountId(context->accessee.accountId); @@ -110,16 +116,43 @@ int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptraccessee.deviceName); accessee.SetAccesseeServiceId(context->accessee.serviceId); accessee.SetAccesseeCredentialId(context->accessee.credentialId); - accessee.SetAccesseeSessionKeyId(context->accessee.sessionKeyId); + accessee.SetAccesseeSessionKeyId(context->accessee.appSessionKeyId); + accessee.SetAccesseeSKTimeStamp(context->accessee.skTimeStamp); +} + +void DmAuthMessageProcessor::SetUserAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee) +{ + accesser.SetAccesserDeviceId(context->accesser.deviceId); + accesser.SetAccesserUserId(context->accesser.userId); + accesser.SetAccesserAccountId(context->accesser.accountId); + accesser.SetAccesserDeviceName(context->accesser.deviceName); + accesser.SetAccesserServiceId(context->accesser.serviceId); + accesser.SetAccesserCredentialId(context->accesser.credentialId); + accesser.SetAccesserSessionKeyId(context->accesser.userSessionKeyId); + accesser.SetAccesserSKTimeStamp(context->accesser.skTimeStamp); + accessee.SetAccesseeDeviceId(context->accessee.deviceId); + accessee.SetAccesseeUserId(context->accessee.userId); + accessee.SetAccesseeAccountId(context->accessee.accountId); + accessee.SetAccesseeDeviceName(context->accessee.deviceName); + accessee.SetAccesseeServiceId(context->accessee.serviceId); + accessee.SetAccesseeCredentialId(context->accessee.credentialId); + accessee.SetAccesseeSessionKeyId(context->accessee.userSessionKeyId); accessee.SetAccesseeSKTimeStamp(context->accessee.skTimeStamp); +} + +int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptr context, + DmAccess &access, std::string trustDeviceId) +{ + LOGI("Start."); + DistributedDeviceProfile::Accesser accesser; + DistributedDeviceProfile::Accessee accessee; + SetUserAccessControlList(context, accesser, accessee); DistributedDeviceProfile::AccessControlProfile profile; - profile.SetBindType(bindType); + SetAccessControlList(context, profile); profile.SetBindLevel(access.bindLevel); - profile.SetStatus(ACTIVE); profile.SetTrustDeviceId(trustDeviceId); - profile.SetDeviceIdType((int32_t)DistributedDeviceProfile::DeviceIdType::UDID); profile.SetDeviceIdHash(access.deviceIdHash); - profile.SetAuthenticationType(authenticationType); profile.SetAccessee(accessee); profile.SetAccesser(accesser); int32_t ret = @@ -127,6 +160,14 @@ int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptr cont return ParseMessageSyncReq(jsonObject, context); case MSG_TYPE_RESP_DATA_SYNC: return ParseMessageSyncResp(jsonObject, context); + case MSG_TYPE_AUTH_FINISH: + return ParseMessageFinish(jsonObject, context); default: break; } @@ -585,12 +628,12 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr LOGE("ParseSyncMessage DM_TAG_USER_SK_ID error"); return ERR_DM_FAILED; } - context->userSessionKeyId = std::atoi(jsonObject[DM_TAG_USER_SK_ID].get().c_str()); + access.userSessionKeyId = std::atoi(jsonObject[DM_TAG_USER_SK_ID].get().c_str()); if (!IsString(jsonObject, DM_TAG_USER_SK_TIMESTAMP)) { LOGE("ParseSyncMessage DM_TAG_USER_SK_TIMESTAMP error"); return ERR_DM_FAILED; } - context->userSkTimeStamp = std::atoi(jsonObject[DM_TAG_USER_SK_TIMESTAMP].get().c_str()); + access.userSkTimeStamp = std::atoi(jsonObject[DM_TAG_USER_SK_TIMESTAMP].get().c_str()); if (!IsString(jsonObject, DM_TAG_DMVERSION)) { LOGE("ParseSyncMessage DM_TAG_DMVERSION error"); return ERR_DM_FAILED; @@ -617,21 +660,29 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr access.bindLevel = srcAccessToSync.bindLevel; access.sessionKeyId = srcAccessToSync.sessionKeyId; access.skTimeStamp = srcAccessToSync.skTimeStamp; - if (context->isOnline) { - access.appSessionKeyId = srcAccessToSync.sessionKeyId; - access.appSkTimeStamp = srcAccessToSync.skTimeStamp; - } else { - access.userSessionKeyId = srcAccessToSync.sessionKeyId; - access.userSkTimeStamp = srcAccessToSync.skTimeStamp; - } if (IsString(jsonObject, DM_TAG_PROXY)) { // 预留字段 std::string proxyInfo = jsonObject[DM_TAG_PROXY].get(); } - if (IsArray(jsonObject, DM_TAG_ACL_CHECKSUM)) { // 再解析一次 acl + if (!IsString(jsonObject, DM_TAG_ACL_CHECKSUM)) { // 再解析一次 acl LOGE("ParseSyncMessage DM_TAG_ACL_CHECKSUM error"); return ERR_DM_FAILED; } - access.aclChecksumList = jsonObject[DM_TAG_ACL_CHECKSUM].get>(); + std::string aclChecksumList = jsonObject[DM_TAG_ACL_CHECKSUM].get(); + nlohmann::json aclChecksumjson = nlohmann::json::parse(aclChecksumList, nullptr, false); + if (aclChecksumjson.is_discarded()) { + LOGE("ParseSyncMessage aclChecksumjson error"); + return ERR_DM_FAILED; + } + if (!IsArray(aclChecksumjson, DM_TAG_ACCESSER)) { + LOGE("ParseSyncMessage DM_TAG_ACCESSER error"); + return ERR_DM_FAILED; + } + access.accesserStrList = aclChecksumjson[DM_TAG_ACCESSER].get>(); + if (!IsArray(aclChecksumjson, DM_TAG_ACCESSEE)) { + LOGE("ParseSyncMessage DM_TAG_ACCESSEE error"); + return ERR_DM_FAILED; + } + access.accesseeStrList = aclChecksumjson[DM_TAG_ACCESSEE].get>(); if (IsString(jsonObject, DM_TAG_SERVICEINFO)) { // sp 暂时没有传 std::string serviceInfo = jsonObject[DM_TAG_SERVICEINFO].get(); } @@ -673,10 +724,10 @@ int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptrappSessionKeyId = std::atoi(jsonObject[DM_TAG_APP_SK_ID].get().c_str()); + access.appSessionKeyId = std::atoi(jsonObject[DM_TAG_APP_SK_ID].get().c_str()); } if (IsString(jsonObject, DM_TAG_APP_SK_TIMESTAMP)) { - context->appSkTimeStamp = std::atoi(jsonObject[DM_TAG_APP_SK_TIMESTAMP].get().c_str()); + access.appSkTimeStamp = std::atoi(jsonObject[DM_TAG_APP_SK_TIMESTAMP].get().c_str()); } ret = ParseSyncMessage(context, access, jsonObject); if (ret != DM_OK) { @@ -697,7 +748,7 @@ int32_t DmAuthMessageProcessor::ParseMessageSyncReq(const nlohmann::json &jsonOb } std::string enSyncMsg = jsonObject[DM_TAG_SYNC].get(); // 解密数据 + 解析数据到context中 - int32_t ret = DecryptSyncMessage(context, context->encryAccesser, enSyncMsg); + int32_t ret = DecryptSyncMessage(context, context->accesser, enSyncMsg); if (ret != DM_OK) { LOGE("DecryptSyncMessage enSyncMsg error"); return ret; @@ -717,7 +768,7 @@ int32_t DmAuthMessageProcessor::ParseMessageSyncResp(const nlohmann::json &jsonO } std::string enSyncMsg = jsonObject[DM_TAG_SYNC].get(); // 解密数据 + 解析数据到context中 - int32_t ret = DecryptSyncMessage(context, context->encryAccessee, enSyncMsg); + int32_t ret = DecryptSyncMessage(context, context->accessee, enSyncMsg); if (ret != DM_OK) { LOGE("DecryptSyncMessage enSyncMsg error"); return ret; @@ -727,8 +778,8 @@ int32_t DmAuthMessageProcessor::ParseMessageSyncResp(const nlohmann::json &jsonO } // 解析200报文 -int32_t DmAuthMessageProcessor::ParseMessageFinish(std::shared_ptr context, - nlohmann::json &jsonObject) +int32_t DmAuthMessageProcessor::ParseMessageFinish(nlohmann::json &jsonObject, + std::shared_ptr context) { if (IsInt32(jsonObject, DM_TAG_REPLY)) { context->reply = jsonObject[DM_TAG_REPLY].get(); diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 2c1fda0ec..1c2cf553c 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -16,6 +16,7 @@ #include "dm_auth_state.h" #include "dm_auth_context.h" #include "dm_auth_state_machine.h" +#include "multiple_user_connector.h" #if defined(SUPPORT_SCREENLOCK) #include "screenlock_manager.h" #endif @@ -81,9 +82,12 @@ bool DmAuthState::IsScreenLocked() return isLocked; } -void DmAuthState::SyncAclList(std::shared_ptr context, int32_t accountId, +void DmAuthState::SyncAclList(std::shared_ptr context, std::string credId, int32_t sessionKeyId, int32_t aclId) { + int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); + LOGI("SyncAclList accountId:%{public}d, credId:%{public}s, sessionKeyId:%{public}d, aclId:%{public}d", + accountId, credId.c_str(), sessionKeyId, aclId); // 根据凭据id 删除sink端多余的凭据 int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, credId); if (ret != DM_OK) { diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index a4dc3ac87..a5479f5ad 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -96,6 +96,27 @@ void SoftbusConnector::JoinLnn(const std::string &deviceId, bool isForceJoin) return; } +void SoftbusConnector::JoinLnn(const std::string &deviceId, const std::string &remoteUdidHash) +{ + std::string connectAddr; + LOGI("start, deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); + ConnectionAddr *addrInfo = GetConnectAddr(deviceId, connectAddr); + if (addrInfo == nullptr) { + LOGE("addrInfo is nullptr."); + return; + } + if (Crypto::ConvertHexStringToBytes(addrInfo->info.ble.udidHash, UDID_HASH_LEN, + remoteUdidHash.c_str(), remoteUdidHash.length()) != DM_OK) { + LOGE("convert remoteUdid hash failed, remoteUdidHash_: %{public}s.", GetAnonyString(remoteUdidHash).c_str()); + return; + } + int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo, OnSoftbusJoinLNNResult); + if (ret != DM_OK) { + LOGE("[SOFTBUS]JoinLNN failed, ret: %{public}d.", ret); + } + return; +} + void SoftbusConnector::JoinLnnByHml(int32_t sessionId, int32_t sessionKeyId, int32_t remoteSessionKeyId) { LOGI("start, JoinLnnByHml sessionId: %{public}d.", sessionId); -- Gitee From d6438fccbedc15f0bbd23b9db61f44a487324624 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Thu, 13 Mar 2025 20:08:50 +0800 Subject: [PATCH 204/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9180-200?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../auth_stages/auth_negotiate.cpp | 1 + .../dm_auth_message_processor.cpp | 25 +++++++++++-------- 2 files changed, 15 insertions(+), 11 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 9b5758ac1..cef56766a 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -109,6 +109,7 @@ int32_t AuthSrcStartState::Action(std::shared_ptr context) sessionId = context->softbusConnector->GetSoftbusSession() ->OpenAuthSessionWithPara(context->accessee.deviceId, context->hmlActionId, context->hmlEnable160M); } else { + context->accessee.OpenAuthDeviceId = context->accessee.deviceId; sessionId = context->softbusConnector->GetSoftbusSession()->OpenAuthSession(context->accessee.deviceId); } diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index da115b086..49ea13bcf 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -576,18 +576,21 @@ void DmAuthMessageProcessor::CreateMessageReqCredAuthStart(std::shared_ptr &accesserStrList, std::vector &accesseeStrList) { - std::string aclChecksum = ""; - std::string aclStr = ""; - int32_t ret = ACLToStr(acl, aclStr); - if (ret != DM_OK) { - LOGE("ChecksumAcl ACLToStr failed"); - return aclChecksum; - } - uint8_t checksum[DM_HASH_LEN] = {0}; - Crypto::DmGenerateStrHash(aclStr.data(), aclStr.size(), checksum, 32, 0); - return std::string(reinterpret_cast(checksum)); + uint8_t accesserHash[DM_HASH_LEN] = {0}; + std::string accesserStr = AccesserToStr(acl); + Crypto::DmGenerateStrHash(accesserStr.data(), accesserStr.size(), accesserHash, DM_HASH_LEN, 0); + auto accesserIter = find(accesserStrList.begin(), accesserStrList.end(), + std::string(reinterpret_cast(accesserHash)); + + uint8_t accesseeHash[DM_HASH_LEN] = {0}; + std::string accesseeStr = AccesseeToStr(acl); + Crypto::DmGenerateStrHash(accesseeStr.data(), accesseeStr.size(), accesseeHash, DM_HASH_LEN, 0); + auto accesseeIter = find(accesseeStrList.begin(), accesseeStrList.end(), + std::string(reinterpret_cast(accesseeHash)); + return (accesserIter != accesserStrList.end()) && (accesseeIter != accesseeStrList.end()) } // 创建190报文 -- Gitee From a5c888fc8dd2399fba3ad196997571ef7c4f1dd8 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 13 Mar 2025 21:48:50 +0800 Subject: [PATCH 205/382] show dialog reserved userId --- common/include/dm_constants.h | 1 + common/src/dm_constants.cpp | 1 + .../src/authentication_v2/auth_stages/auth_confirm.cpp | 1 + 3 files changed, 3 insertions(+) diff --git a/common/include/dm_constants.h b/common/include/dm_constants.h index fc275dc0d..d51e9fca4 100755 --- a/common/include/dm_constants.h +++ b/common/include/dm_constants.h @@ -26,6 +26,7 @@ extern const char* TAG_GROUP_ID; extern const char* TAG_GROUP_NAME; extern const char* TAG_REQUEST_ID; extern const char* TAG_DEVICE_ID; +extern const char* TAG_USER_ID; extern const char* TAG_AUTH_TYPE; extern const char* TAG_CRYPTO_SUPPORT; extern const char* TAG_VER; diff --git a/common/src/dm_constants.cpp b/common/src/dm_constants.cpp index 2f91c8ca5..ba1fa49b0 100644 --- a/common/src/dm_constants.cpp +++ b/common/src/dm_constants.cpp @@ -21,6 +21,7 @@ const char* TAG_GROUP_ID = "groupId"; const char* TAG_GROUP_NAME = "GROUPNAME"; const char* TAG_REQUEST_ID = "REQUESTID"; const char* TAG_DEVICE_ID = "DEVICEID"; +const char* TAG_USER_ID = "USERID"; const char* TAG_AUTH_TYPE = "AUTHTYPE"; const char* TAG_CRYPTO_SUPPORT = "CRYPTOSUPPORT"; const char* TAG_VER = "ITF_VER"; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 498b2aa95..e68aed6f8 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -167,6 +167,7 @@ int32_t AuthSinkConfirmState::ShowConfigDialog(std::shared_ptr co jsonObj[TAG_CUSTOM_DESCRIPTION] = context->customData; jsonObj[TAG_LOCAL_DEVICE_TYPE] = context->accesser.deviceType; jsonObj[TAG_REQUESTER] = context->accesser.deviceName; + jsonObj[TAG_USER_ID] = context->accessee.userId; jsonObj[TAG_HOST_PKGLABEL] = context->sessionName; const std::string params = SafetyDump(jsonObj); -- Gitee From 6d292aeeb7ebec2b41348d0353a872ab81d937ea Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 13 Mar 2025 21:58:09 +0800 Subject: [PATCH 206/382] tmp --- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 1 - .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 3 ++- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index e68aed6f8..07295dbe4 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -81,7 +81,6 @@ int32_t AuthSrcConfirmState::DoPinAuth(std::shared_ptr context) }); } else { // 少一轮 100,110 - // 转 AuthSrcPinAuthStartState context->authStateMachine->TransitionTo(std::make_shared()); } LOGI("AuthSrcConfirmState::DoPinAuth end"); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 4713ae2c2..47604e80a 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -495,7 +495,8 @@ void AuthSinkNegotiateStateMachine::NegotiatePinAuthType(std::shared_ptrcustomData = srvInfo.GetDescription(); } } else { - if (context->authType == DmAuthType::AUTH_TYPE_PIN) { + if (context->authType == DmAuthType::AUTH_TYPE_PIN || + context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { context->authBoxType = OHOS::DistributedDeviceProfile::NUM_1; // 三态框 } else { context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // 免弹框 -- Gitee From 3167381e0fd49b198103669eb3c3ab2bb54bb428 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 13 Mar 2025 22:40:35 +0800 Subject: [PATCH 207/382] tmp --- .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 2 +- .../src/authentication_v2/dm_auth_state_machine.cpp | 8 +++++--- 2 files changed, 6 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 818ee8e50..a8231b33f 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -237,7 +237,7 @@ DmAuthStateType AuthSinkPinAuthStartState::GetStateType() int32_t AuthSinkPinAuthStartState::Action(std::shared_ptr context) { LOGI("AuthSinkPinAuthStartState::Action start"); - + context->pinNegotiateStarted = true; auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); if (ret != DM_OK) { LOGE("AuthSinkPinAuthStartState::Action call ProcessCredData err"); diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index ac67450dd..0476e81d2 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -81,9 +81,11 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) // Sink端 状态迁移表 //{DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, //{DmAuthStateType::AUTH_SINK_START_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, - {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE, - {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, - DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, // to check + {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE, { + DmAuthStateType::AUTH_SINK_CONFIRM_STATE, + DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, + DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE + }}, // to check {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, { DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, // todo del DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, -- Gitee From eeb2bf5c6df069928ceda419364a1ec2a98aa9bc Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 13 Mar 2025 22:52:10 +0800 Subject: [PATCH 208/382] tmp --- .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index a8231b33f..215590f1a 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -237,6 +237,7 @@ DmAuthStateType AuthSinkPinAuthStartState::GetStateType() int32_t AuthSinkPinAuthStartState::Action(std::shared_ptr context) { LOGI("AuthSinkPinAuthStartState::Action start"); + context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); context->pinNegotiateStarted = true; auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); if (ret != DM_OK) { -- Gitee From 3a73cbcf02119792db05efe166b4290b5abd1948 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 13 Mar 2025 23:01:17 +0800 Subject: [PATCH 209/382] tmp --- .../src/authentication_v2/auth_stages/auth_credential.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 4c21787f5..f89b41552 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -177,6 +177,7 @@ DmAuthStateType AuthSinkCredentialAuthStartState::GetStateType() // 收到160凭证认证报文,发送170报文 int32_t AuthSinkCredentialAuthStartState::Action(std::shared_ptr context) { + context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); // 解密并透传transmitData int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_TRANSMIT); if (ret != DM_OK) { -- Gitee From ef7431708ac68f0f9b55e893351bac97eaf93492 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 13 Mar 2025 23:04:51 +0800 Subject: [PATCH 210/382] tmp --- .../src/authentication_v2/dm_auth_message_processor.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index c9815a99b..d923d1b2d 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -885,6 +885,7 @@ int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const nlohmann::json auto idx = json[DM_TAG_CURRENT_AUTH_TYPE_IDX].get(); if (idx < context->authTypeList.size()) { context->currentAuthTypeIdx = idx; + context->authType = context->authTypeList[idx]; } else { LOGI("DmAuthMessageProcessor::ParseMessageReqUserConfirm currentAuthTypeIdx err."); context->reason = ERR_DM_INPUT_PARA_INVALID; @@ -920,6 +921,7 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const nlohmann::json auto idx = json[DM_TAG_CURRENT_AUTH_TYPE_IDX].get(); if (idx < context->authTypeList.size()) { context->currentAuthTypeIdx = idx; + context->authType = context->authTypeList[idx]; } else { LOGI("DmAuthMessageProcessor::ParseMessageReqUserConfirm currentAuthTypeIdx err."); context->reason = ERR_DM_INPUT_PARA_INVALID; -- Gitee From 68295168c045eb056bd244b16141fa5adfde88ae Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Fri, 14 Mar 2025 06:18:58 +0000 Subject: [PATCH 211/382] =?UTF-8?q?=E5=9B=9E=E9=80=80=20'Pull=20Request=20?= =?UTF-8?q?!3=20:=20=E4=BF=AE=E6=94=B9180-200'?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication_v2/dm_auth_context.h | 6 +- .../dm_auth_message_processor.h | 11 +- .../include/authentication_v2/dm_auth_state.h | 2 +- .../dependency/softbus/softbus_connector.h | 1 - .../auth_stages/auth_acl.cpp | 86 ++++-------- .../auth_stages/auth_negotiate.cpp | 1 - .../dm_auth_message_processor.cpp | 132 ++++++------------ .../src/authentication_v2/dm_auth_state.cpp | 6 +- .../dependency/softbus/softbus_connector.cpp | 21 --- 9 files changed, 70 insertions(+), 196 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 00b4a7394..7263362a2 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -135,11 +135,9 @@ struct DmAccess { std::string dmVersion; // 版本 5.1.0 std::string edition; // 用于5.1.0版本前的兼容,协助版本协商 std::string aclList; //可信关系列表,用于数据老化 KV格式 - std::vector accesserStrList; - std::vector accesseeStrList; // 可信关系列表,用于数据老化 + std::vector aclChecksumList; // 可信关系列表,用于数据老化 std::string credentialInfos; //凭据信息(点对点,同账号,..) 只保存凭据类型 kv结构 std::string extraInfo; //可扩展字段,kv结构 - std::string OpenAuthDeviceId; }; // TODO 统一用初始化列表进行初始化 @@ -182,6 +180,8 @@ struct DmAuthContext { DmPeerTarget peerTarget; // 对端目标的信息 DmAccess accesser; DmAccess accessee; + DmAccess encryAccesser; // 密文阶段accesser + DmAccess encryAccessee; // 密文阶段accessee std::multimap proxy; // 前面是accesser,后面是accessee std::shared_ptr authStateMachine; // 状态机 diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 4a8140e62..640494ff1 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -206,8 +206,7 @@ public: DmAccess &access, std::string trustDeviceId); // 对acl进行checksum - bool ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl, - std::vector &accesserStrList, std::vector &accesseeStrList); + std::string ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl); // 提取本端ACL 用于消息解析和总线使用 无ACL会返回空字符串 json格式字符串:{dmversion:x,accesser:[{accesserDeviceId:y,...},...],accessee:{...}} int32_t GetAclListStr(std::shared_ptr &context, std::string &aclList); @@ -246,7 +245,7 @@ private: // 解析 190报文信息 MSG_TYPE_RESP_DATA_SYNC 存放对方密文四元组,acl sp skid int32_t ParseMessageSyncResp(const nlohmann::json &jsonObject, std::shared_ptr context); // 解析 200报文信息 - int32_t ParseMessageFinish(const nlohmann::json &jsonObject, std::shared_ptr context); + int32_t ParseMessageFinish(std::shared_ptr context, nlohmann::json &jsonObject); // 创建 80报文 void CreateNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject); @@ -296,12 +295,6 @@ private: 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 SetAppAccessControlList(std::shared_ptr context, - DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee); - void SetUserAccessControlList(std::shared_ptr context, - DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee); std::shared_ptr cryptoMgr_ = nullptr; }; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 7ff86c1ac..8f889bc71 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -115,7 +115,7 @@ public: virtual ~DmAuthState() {}; virtual DmAuthStateType GetStateType() = 0; virtual int32_t Action(std::shared_ptr context) = 0; // 执行状态对应的action动作 - void SyncAclList(std::shared_ptr context, + void SyncAclList(std::shared_ptr context, int32_t accountId, std::string credId, int32_t sessionKeyId, int32_t aclId); static bool IsScreenLocked(); static int32_t GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut); diff --git a/services/implementation/include/dependency/softbus/softbus_connector.h b/services/implementation/include/dependency/softbus/softbus_connector.h index 3dde3b95b..996ff36df 100644 --- a/services/implementation/include/dependency/softbus/softbus_connector.h +++ b/services/implementation/include/dependency/softbus/softbus_connector.h @@ -85,7 +85,6 @@ public: */ static void JoinLnnByHml(int32_t sessionId, int32_t sessionKeyId, int32_t remoteSessionKeyId); - static void JoinLnn(const std::string &deviceId, const std::string &remoteUdidHash); public: SoftbusConnector(); ~SoftbusConnector(); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 9561ebb48..a40260434 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -21,9 +21,6 @@ #include "deviceprofile_connector.h" #include "dm_auth_context.h" #include "dm_constants.h" -#include "auth_manager.h" -#include "multiple_user_connector.h" -#include "dm_crypto.h" namespace OHOS { namespace DistributedHardware { @@ -44,10 +41,10 @@ int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) { LOGI("AuthSinkDataSyncState::Action start"); // 判断密文阶段和明文阶段的四元组是否相同,不同则直接结束 - bool isSame = Crypto::Sha256(context->accesser.deviceId) == context->accesser.deviceIdHash && - Crypto::Sha256(std::to_string(context->accesser.userId)) == context->accesser.userIdHash && - Crypto::Sha256(context->accesser.accountId) == context->accesser.accountIdHash && - Crypto::Sha256(std::to_string(context->accesser.tokenId)) == context->accesser.tokenIdHash; + bool isSame = context->encryAccesser.deviceId == context->accesser.deviceId && + context->encryAccesser.userId == context->accesser.userId && + context->encryAccesser.accountId == context->accesser.accountId && + context->encryAccesser.tokenId == context->accesser.tokenId; if (!isSame) { LOGE("data between two stages different, stop auth"); context->reply = DM_AUTHENTICATE_FINISH; @@ -72,14 +69,19 @@ int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) } // 比较双端的acl for (auto &sinkAcl : sinkAclList) { - bool res = context->authMessageProcessor->ChecksumAcl(srcAcl, - context->accesser.accesserStrList, context->accesser.accesseeStrList); - if (res) { + std::string aclChecksum = context->authMessageProcessor->ChecksumAcl(sinkAcl); + auto item = find(context->encryAccesser.aclChecksumList.begin(), + context->encryAccesser.aclChecksumList.end(), aclChecksum); + if (item != context->encryAccesser.aclChecksumList.end()) { continue; } - SyncAclList(context, std::to_string(sinkAcl.GetAccessee().GetAccesseeCredentialId()), + SyncAclList(context, std::atoi(sinkAcl.GetAccessee().GetAccesseeAccountId().c_str()), + std::to_string(sinkAcl.GetAccessee().GetAccesseeCredentialId()), sinkAcl.GetAccessee().GetAccesseeSessionKeyId(), sinkAcl.GetAccessControlId()); } + // 保存本次acl + context->authMessageProcessor->PutAccessControlList(context, context->accessee, context->accesser.deviceId); + // 同步本端的sp信息,不确定格式,暂不做 context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_DATA_SYNC, context); @@ -97,10 +99,10 @@ int32_t AuthSrcFinishState::Action(std::shared_ptr context) { LOGI("AuthSrcFinishState::Action start"); // 判断密文阶段和明文阶段的四元组是否相同,不同则直接结束 - bool isSame = Crypto::Sha256(context->accessee.deviceId) == context->accessee.deviceIdHash && - Crypto::Sha256(std::to_string(context->accessee.userId)) == context->accessee.userIdHash && - Crypto::Sha256(context->accessee.accountId) == context->accessee.accountIdHash && - Crypto::Sha256(std::to_string(context->accessee.tokenId)) == context->accessee.tokenIdHash; + bool isSame = context->encryAccessee.deviceId == context->accessee.deviceId && + context->encryAccessee.userId == context->accessee.userId && + context->encryAccessee.accountId == context->accessee.accountId && + context->encryAccessee.tokenId == context->accessee.tokenId; if (!isSame) { LOGE("data between two stages different, stop auth"); // 不同直接结束,发送200给sink端 @@ -127,12 +129,14 @@ int32_t AuthSrcFinishState::Action(std::shared_ptr context) } // 比较双端的acl for (auto &srcAcl : srcAclList) { - bool res = context->authMessageProcessor->ChecksumAcl(srcAcl, - context->accessee.accesserStrList, context->accessee.accesseeStrList); - if (res) { + std::string aclChecksum = context->authMessageProcessor->ChecksumAcl(srcAcl); + auto item = find(context->encryAccessee.aclChecksumList.begin(), + context->encryAccessee.aclChecksumList.end(), aclChecksum); + if (item != context->encryAccessee.aclChecksumList.end()) { continue; } - SyncAclList(context, std::to_string(srcAcl.GetAccesser().GetAccesserCredentialId()), + SyncAclList(context, std::atoi(srcAcl.GetAccesser().GetAccesserAccountId().c_str()), + std::to_string(srcAcl.GetAccesser().GetAccesserCredentialId()), srcAcl.GetAccesser().GetAccesserSessionKeyId(), srcAcl.GetAccessControlId()); } // 保存本次acl @@ -141,20 +145,7 @@ int32_t AuthSrcFinishState::Action(std::shared_ptr context) // 触发组网 if (!context->accesser.isOnline) { - if (AuthManager::IsHmlSessionType(context->connSessionType)) { - LOGI("AuthSrcFinishState joinLnn context.userSessionKeyId: %{public}d, ee.userSessionKeyId: %{public}d", - context->userSessionKeyId, context->accessee.userSessionKeyId); - context->softbusConnector->JoinLnnByHml(context->sessionId, - context->userSessionKeyId, context->accessee.userSessionKeyId); - } else { - char udidHashTmp[DM_MAX_DEVICE_ID_LEN] = {0}; - if (Crypto::GetUdidHash(context->accessee.deviceId, reinterpret_cast(udidHashTmp)) != DM_OK) { - LOGE("AuthSrcFinishState joinLnn get udidhash by udid: %{public}s failed", context->accessee.deviceId.c_str()); - return ERR_DM_FAILED; - } - std::string peerUdidHash = std::string(udidHashTmp); - context->softbusConnector->JoinLnn(context->accessee.OpenAuthDeviceId, peerUdidHash); - } + context->softbusConnector->JoinLnn(context->accessee.deviceId); } context->reason = DM_OK; context->reply = DM_AUTHENTICATE_FINISH; @@ -172,20 +163,6 @@ DmAuthStateType AuthSrcFinishState::GetStateType() void AuthSrcFinishState::SourceFinish(std::shared_ptr context) { - if (context->reason != DM_OK) { - int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); - // 根据凭据id 删除sink端多余的凭据 - int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, context->accesser.appCredentialId); - if (ret != DM_OK) { - LOGE("SourceFinish DeleteCredential failed."); - } - // 根据skid删除sk,删除skid - ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accesser.sessionKeyId); - if (ret != DM_OK) { - LOGE("SourceFinish DeleteSessionKey failed."); - } - } - context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); context->authStateMachine = nullptr; context->authUiStateMgr = nullptr; context->hiChainAuthConnector = nullptr; @@ -204,7 +181,6 @@ void AuthSrcFinishState::SourceFinish(std::shared_ptr context) int32_t AuthSinkFinishState::Action(std::shared_ptr context) { LOGI("AuthSinkFinishState::Action start"); - context->authMessageProcessor->PutAccessControlList(context, context->accessee, context->accesser.deviceId); SinkFinish(context); LOGI("AuthSinkFinishState::Action ok"); return DM_OK; @@ -217,20 +193,6 @@ DmAuthStateType AuthSinkFinishState::GetStateType() void AuthSinkFinishState::SinkFinish(std::shared_ptr context) { - if (context->reason != DM_OK) { - int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); - // 根据凭据id 删除sink端多余的凭据 - int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, context->accessee.appCredentialId); - if (ret != DM_OK) { - LOGE("SinkFinish DeleteCredential failed."); - } - // 根据skid删除sk,删除skid - ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accessee.sessionKeyId); - if (ret != DM_OK) { - LOGE("SinkFinish DeleteSessionKey failed."); - } - } - context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); context->authStateMachine = nullptr; context->authUiStateMgr = nullptr; context->hiChainAuthConnector = nullptr; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 338c11126..47604e80a 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -95,7 +95,6 @@ int32_t AuthSrcStartState::Action(std::shared_ptr context) sessionId = context->softbusConnector->GetSoftbusSession() ->OpenAuthSessionWithPara(context->accessee.deviceId, context->hmlActionId, context->hmlEnable160M); } else { - context->accessee.OpenAuthDeviceId = context->accessee.deviceId; sessionId = context->softbusConnector->GetSoftbusSession()->OpenAuthSession(context->accessee.deviceId); } diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index d79d8d912..d923d1b2d 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -88,9 +88,10 @@ int32_t DmAuthMessageProcessor::SaveSessionKeyToDP(int32_t &skId) return DeviceProfileConnector::GetInstance().PutSessionKey(sk, skId); } -void DmAuthMessageProcessor::SetAccessControlList(std::shared_ptr context, - DistributedDeviceProfile::AccessControlProfile &profile) +int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptr context, + DmAccess &access, std::string trustDeviceId) { + LOGI("Start."); uint32_t bindType = DM_ACROSS_ACCOUNT; if (context->accesser.accountId == "ohosAnonymousUid" || context->accessee.accountId == "ohosAnonymousUid") { bindType = DM_POINT_TO_POINT; @@ -99,15 +100,7 @@ void DmAuthMessageProcessor::SetAccessControlList(std::shared_ptr if (context->authResult == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { authenticationType = ALLOW_AUTH_ALWAYS; } - profile.SetBindType(bindType); - profile.SetAuthenticationType(authenticationType); - profile.SetStatus(ACTIVE); - profile.SetDeviceIdType((int32_t)DistributedDeviceProfile::DeviceIdType::UDID); -} - -void DmAuthMessageProcessor::SetAppAccessControlList(std::shared_ptr context, - DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee) -{ + DistributedDeviceProfile::Accesser accesser; accesser.SetAccesserDeviceId(context->accesser.deviceId); accesser.SetAccesserUserId(context->accesser.userId); accesser.SetAccesserAccountId(context->accesser.accountId); @@ -116,8 +109,9 @@ void DmAuthMessageProcessor::SetAppAccessControlList(std::shared_ptraccesser.deviceName); accesser.SetAccesserServiceId(context->accesser.serviceId); accesser.SetAccesserCredentialId(context->accesser.credentialId); - accesser.SetAccesserSessionKeyId(context->accesser.appSessionKeyId); + accesser.SetAccesserSessionKeyId(context->accesser.sessionKeyId); accesser.SetAccesserSKTimeStamp(context->accesser.skTimeStamp); + DistributedDeviceProfile::Accessee accessee; accessee.SetAccesseeDeviceId(context->accessee.deviceId); accessee.SetAccesseeUserId(context->accessee.userId); accessee.SetAccesseeAccountId(context->accessee.accountId); @@ -126,43 +120,16 @@ void DmAuthMessageProcessor::SetAppAccessControlList(std::shared_ptraccessee.deviceName); accessee.SetAccesseeServiceId(context->accessee.serviceId); accessee.SetAccesseeCredentialId(context->accessee.credentialId); - accessee.SetAccesseeSessionKeyId(context->accessee.appSessionKeyId); - accessee.SetAccesseeSKTimeStamp(context->accessee.skTimeStamp); -} - -void DmAuthMessageProcessor::SetUserAccessControlList(std::shared_ptr context, - DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee) -{ - accesser.SetAccesserDeviceId(context->accesser.deviceId); - accesser.SetAccesserUserId(context->accesser.userId); - accesser.SetAccesserAccountId(context->accesser.accountId); - accesser.SetAccesserDeviceName(context->accesser.deviceName); - accesser.SetAccesserServiceId(context->accesser.serviceId); - accesser.SetAccesserCredentialId(context->accesser.credentialId); - accesser.SetAccesserSessionKeyId(context->accesser.userSessionKeyId); - accesser.SetAccesserSKTimeStamp(context->accesser.skTimeStamp); - accessee.SetAccesseeDeviceId(context->accessee.deviceId); - accessee.SetAccesseeUserId(context->accessee.userId); - accessee.SetAccesseeAccountId(context->accessee.accountId); - accessee.SetAccesseeDeviceName(context->accessee.deviceName); - accessee.SetAccesseeServiceId(context->accessee.serviceId); - accessee.SetAccesseeCredentialId(context->accessee.credentialId); - accessee.SetAccesseeSessionKeyId(context->accessee.userSessionKeyId); + accessee.SetAccesseeSessionKeyId(context->accessee.sessionKeyId); accessee.SetAccesseeSKTimeStamp(context->accessee.skTimeStamp); -} - -int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptr context, - DmAccess &access, std::string trustDeviceId) -{ - LOGI("Start."); - DistributedDeviceProfile::Accesser accesser; - DistributedDeviceProfile::Accessee accessee; - SetUserAccessControlList(context, accesser, accessee); DistributedDeviceProfile::AccessControlProfile profile; - SetAccessControlList(context, profile); + profile.SetBindType(bindType); profile.SetBindLevel(access.bindLevel); + profile.SetStatus(ACTIVE); profile.SetTrustDeviceId(trustDeviceId); + profile.SetDeviceIdType((int32_t)DistributedDeviceProfile::DeviceIdType::UDID); profile.SetDeviceIdHash(access.deviceIdHash); + profile.SetAuthenticationType(authenticationType); profile.SetAccessee(accessee); profile.SetAccesser(accesser); int32_t ret = @@ -170,14 +137,6 @@ int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptr cont return ParseMessageSyncReq(jsonObject, context); case MSG_TYPE_RESP_DATA_SYNC: return ParseMessageSyncResp(jsonObject, context); - case MSG_TYPE_AUTH_FINISH: - return ParseMessageFinish(jsonObject, context); default: break; } @@ -591,21 +548,18 @@ void DmAuthMessageProcessor::CreateMessageReqCredAuthStart(std::shared_ptr &accesserStrList, std::vector &accesseeStrList) +std::string DmAuthMessageProcessor::ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl) { - uint8_t accesserHash[DM_HASH_LEN] = {0}; - std::string accesserStr = AccesserToStr(acl); - Crypto::DmGenerateStrHash(accesserStr.data(), accesserStr.size(), accesserHash, DM_HASH_LEN, 0); - auto accesserIter = find(accesserStrList.begin(), accesserStrList.end(), - std::string(reinterpret_cast(accesserHash)); - - uint8_t accesseeHash[DM_HASH_LEN] = {0}; - std::string accesseeStr = AccesseeToStr(acl); - Crypto::DmGenerateStrHash(accesseeStr.data(), accesseeStr.size(), accesseeHash, DM_HASH_LEN, 0); - auto accesseeIter = find(accesseeStrList.begin(), accesseeStrList.end(), - std::string(reinterpret_cast(accesseeHash)); - return (accesserIter != accesserStrList.end()) && (accesseeIter != accesseeStrList.end()) + std::string aclChecksum = ""; + std::string aclStr = ""; + int32_t ret = ACLToStr(acl, aclStr); + if (ret != DM_OK) { + LOGE("ChecksumAcl ACLToStr failed"); + return aclChecksum; + } + uint8_t checksum[DM_HASH_LEN] = {0}; + Crypto::DmGenerateStrHash(aclStr.data(), aclStr.size(), checksum, 32, 0); + return std::string(reinterpret_cast(checksum)); } // 创建190报文 @@ -646,12 +600,12 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr LOGE("ParseSyncMessage DM_TAG_USER_SK_ID error"); return ERR_DM_FAILED; } - access.userSessionKeyId = std::atoi(jsonObject[DM_TAG_USER_SK_ID].get().c_str()); + context->userSessionKeyId = std::atoi(jsonObject[DM_TAG_USER_SK_ID].get().c_str()); if (!IsString(jsonObject, DM_TAG_USER_SK_TIMESTAMP)) { LOGE("ParseSyncMessage DM_TAG_USER_SK_TIMESTAMP error"); return ERR_DM_FAILED; } - access.userSkTimeStamp = std::atoi(jsonObject[DM_TAG_USER_SK_TIMESTAMP].get().c_str()); + context->userSkTimeStamp = std::atoi(jsonObject[DM_TAG_USER_SK_TIMESTAMP].get().c_str()); if (!IsString(jsonObject, DM_TAG_DMVERSION)) { LOGE("ParseSyncMessage DM_TAG_DMVERSION error"); return ERR_DM_FAILED; @@ -678,29 +632,21 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr access.bindLevel = srcAccessToSync.bindLevel; access.sessionKeyId = srcAccessToSync.sessionKeyId; access.skTimeStamp = srcAccessToSync.skTimeStamp; + if (context->isOnline) { + access.appSessionKeyId = srcAccessToSync.sessionKeyId; + access.appSkTimeStamp = srcAccessToSync.skTimeStamp; + } else { + access.userSessionKeyId = srcAccessToSync.sessionKeyId; + access.userSkTimeStamp = srcAccessToSync.skTimeStamp; + } if (IsString(jsonObject, DM_TAG_PROXY)) { // 预留字段 std::string proxyInfo = jsonObject[DM_TAG_PROXY].get(); } - if (!IsString(jsonObject, DM_TAG_ACL_CHECKSUM)) { // 再解析一次 acl + if (IsArray(jsonObject, DM_TAG_ACL_CHECKSUM)) { // 再解析一次 acl LOGE("ParseSyncMessage DM_TAG_ACL_CHECKSUM error"); return ERR_DM_FAILED; } - std::string aclChecksumList = jsonObject[DM_TAG_ACL_CHECKSUM].get(); - nlohmann::json aclChecksumjson = nlohmann::json::parse(aclChecksumList, nullptr, false); - if (aclChecksumjson.is_discarded()) { - LOGE("ParseSyncMessage aclChecksumjson error"); - return ERR_DM_FAILED; - } - if (!IsArray(aclChecksumjson, DM_TAG_ACCESSER)) { - LOGE("ParseSyncMessage DM_TAG_ACCESSER error"); - return ERR_DM_FAILED; - } - access.accesserStrList = aclChecksumjson[DM_TAG_ACCESSER].get>(); - if (!IsArray(aclChecksumjson, DM_TAG_ACCESSEE)) { - LOGE("ParseSyncMessage DM_TAG_ACCESSEE error"); - return ERR_DM_FAILED; - } - access.accesseeStrList = aclChecksumjson[DM_TAG_ACCESSEE].get>(); + access.aclChecksumList = jsonObject[DM_TAG_ACL_CHECKSUM].get>(); if (IsString(jsonObject, DM_TAG_SERVICEINFO)) { // sp 暂时没有传 std::string serviceInfo = jsonObject[DM_TAG_SERVICEINFO].get(); } @@ -742,10 +688,10 @@ int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptr().c_str()); + context->appSessionKeyId = std::atoi(jsonObject[DM_TAG_APP_SK_ID].get().c_str()); } if (IsString(jsonObject, DM_TAG_APP_SK_TIMESTAMP)) { - access.appSkTimeStamp = std::atoi(jsonObject[DM_TAG_APP_SK_TIMESTAMP].get().c_str()); + context->appSkTimeStamp = std::atoi(jsonObject[DM_TAG_APP_SK_TIMESTAMP].get().c_str()); } ret = ParseSyncMessage(context, access, jsonObject); if (ret != DM_OK) { @@ -766,7 +712,7 @@ int32_t DmAuthMessageProcessor::ParseMessageSyncReq(const nlohmann::json &jsonOb } std::string enSyncMsg = jsonObject[DM_TAG_SYNC].get(); // 解密数据 + 解析数据到context中 - int32_t ret = DecryptSyncMessage(context, context->accesser, enSyncMsg); + int32_t ret = DecryptSyncMessage(context, context->encryAccesser, enSyncMsg); if (ret != DM_OK) { LOGE("DecryptSyncMessage enSyncMsg error"); return ret; @@ -786,7 +732,7 @@ int32_t DmAuthMessageProcessor::ParseMessageSyncResp(const nlohmann::json &jsonO } std::string enSyncMsg = jsonObject[DM_TAG_SYNC].get(); // 解密数据 + 解析数据到context中 - int32_t ret = DecryptSyncMessage(context, context->accessee, enSyncMsg); + int32_t ret = DecryptSyncMessage(context, context->encryAccessee, enSyncMsg); if (ret != DM_OK) { LOGE("DecryptSyncMessage enSyncMsg error"); return ret; @@ -796,8 +742,8 @@ int32_t DmAuthMessageProcessor::ParseMessageSyncResp(const nlohmann::json &jsonO } // 解析200报文 -int32_t DmAuthMessageProcessor::ParseMessageFinish(nlohmann::json &jsonObject, - std::shared_ptr context) +int32_t DmAuthMessageProcessor::ParseMessageFinish(std::shared_ptr context, + nlohmann::json &jsonObject) { if (IsInt32(jsonObject, DM_TAG_REPLY)) { context->reply = jsonObject[DM_TAG_REPLY].get(); diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 1c2cf553c..2c1fda0ec 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -16,7 +16,6 @@ #include "dm_auth_state.h" #include "dm_auth_context.h" #include "dm_auth_state_machine.h" -#include "multiple_user_connector.h" #if defined(SUPPORT_SCREENLOCK) #include "screenlock_manager.h" #endif @@ -82,12 +81,9 @@ bool DmAuthState::IsScreenLocked() return isLocked; } -void DmAuthState::SyncAclList(std::shared_ptr context, +void DmAuthState::SyncAclList(std::shared_ptr context, int32_t accountId, std::string credId, int32_t sessionKeyId, int32_t aclId) { - int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); - LOGI("SyncAclList accountId:%{public}d, credId:%{public}s, sessionKeyId:%{public}d, aclId:%{public}d", - accountId, credId.c_str(), sessionKeyId, aclId); // 根据凭据id 删除sink端多余的凭据 int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, credId); if (ret != DM_OK) { diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index a5479f5ad..a4dc3ac87 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -96,27 +96,6 @@ void SoftbusConnector::JoinLnn(const std::string &deviceId, bool isForceJoin) return; } -void SoftbusConnector::JoinLnn(const std::string &deviceId, const std::string &remoteUdidHash) -{ - std::string connectAddr; - LOGI("start, deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - ConnectionAddr *addrInfo = GetConnectAddr(deviceId, connectAddr); - if (addrInfo == nullptr) { - LOGE("addrInfo is nullptr."); - return; - } - if (Crypto::ConvertHexStringToBytes(addrInfo->info.ble.udidHash, UDID_HASH_LEN, - remoteUdidHash.c_str(), remoteUdidHash.length()) != DM_OK) { - LOGE("convert remoteUdid hash failed, remoteUdidHash_: %{public}s.", GetAnonyString(remoteUdidHash).c_str()); - return; - } - int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo, OnSoftbusJoinLNNResult); - if (ret != DM_OK) { - LOGE("[SOFTBUS]JoinLNN failed, ret: %{public}d.", ret); - } - return; -} - void SoftbusConnector::JoinLnnByHml(int32_t sessionId, int32_t sessionKeyId, int32_t remoteSessionKeyId) { LOGI("start, JoinLnnByHml sessionId: %{public}d.", sessionId); -- Gitee From 1a4e4313e048b4b6ca2693944e02d7e591ed7620 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 14 Mar 2025 16:32:26 +0800 Subject: [PATCH 212/382] new ok,old pin state del --- .../include/authentication_v2/dm_auth_state.h | 4 - .../src/authentication_v2/auth_manager.cpp | 59 +------ .../auth_stages/auth_confirm.cpp | 158 ------------------ .../auth_stages/auth_pin_auth.cpp | 108 +----------- .../dm_auth_message_processor.cpp | 4 - .../dm_auth_state_machine.cpp | 7 - 6 files changed, 3 insertions(+), 337 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 8f889bc71..f3dd6438b 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -146,7 +146,6 @@ public: DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; private: - int32_t MatchAuthType(std::shared_ptr context); // 从DP配置读取授权类型 int32_t ShowConfigDialog(std::shared_ptr context); // 提示用户授权对话框 int64_t GenRequestId(std::shared_ptr context); // 生成HiChain请求ID }; @@ -201,10 +200,7 @@ public: DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; private: - int32_t GetPinCode(std::shared_ptr context); // 获取PIN码 int32_t ShowStartAuthDialog(std::shared_ptr context); // 向用户显示PIN输入框 - int32_t GetPinCodeFromServerInfo(std::shared_ptr context); // 从服务端配置信息中获取PIN码 - int32_t AuthDevice(std::shared_ptr context); // 向HiChain发起PIN认证请求 }; class AuthSinkPinAuthStartState : public DmAuthState { diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index da9a7e4be..11ca33b6b 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -45,9 +45,6 @@ namespace { constexpr int32_t MIN_PIN_CODE = 100000; constexpr int32_t MAX_PIN_CODE = 999999; -#ifndef NEW_PIN_STATE // todo del -const int32_t MAX_AUTH_FAIL_TIMES = 3; -#endif int32_t GetCloseSessionDelaySeconds(std::string &delaySecondsStr) { @@ -978,34 +975,11 @@ void AuthSrcManager::AuthDeviceError(int64_t requestId, int32_t errorCode) curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE || curState == DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE) { LOGI("AuthSrcManager::AuthDeviceError Auth pin err."); - #ifndef NEW_PIN_STATE // todo del - if (context_->authType == DmAuthType::AUTH_TYPE_PIN) { - context_->inputPinAuthFailTimes++; - } else if (!context_->pinNegotiateStarted) { - LOGI("AuthSrcManager::AuthDeviceError fallback to input pin."); - context_->pinNegotiateStarted = true; - } else { - context_->inputPinAuthFailTimes++; - } - - // 失败 MAX_AUTH_FAIL_TIMES 次后,走认证失败 ON_FAIL - if (context_->inputPinAuthFailTimes >= MAX_AUTH_FAIL_TIMES) { - LOGI("AuthSrcManager::AuthDeviceError Auth pin err fail."); - context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); - } else { - // Notify ON_ERROR 事件,对应 Action 内会当正常重试处理,而非失败 - context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); - // 回退状态到 AuthSrcPinAuthStartState - context_->authStateMachine->TransitionTo(std::make_shared()); - LOGI("AuthSrcManager::AuthDeviceError Auth pin err, will retry."); - } - #else if (context_->authType == DmAuthType::AUTH_TYPE_PIN) { context_->inputPinAuthFailTimes++; } context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); context_->authStateMachine->TransitionTo(std::make_shared()); - #endif } LOGI("AuthSrcManager::AuthDeviceError leave."); } @@ -1016,43 +990,12 @@ void AuthSinkManager::AuthDeviceError(int64_t requestId, int32_t errorCode) auto curState = context_->authStateMachine->GetCurState(); if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE || curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE) { - - #ifndef NEW_PIN_STATE // todo del - if (context_->authType == DmAuthType::AUTH_TYPE_PIN) { - context_->inputPinAuthFailTimes++; - } else if (!context_->pinNegotiateStarted) { - LOGI("AuthSinkManager::AuthDeviceError fallback to input pin."); - context_->pinNegotiateStarted = true; - // 生成PIN码 - AuthSinkStatePinAuthComm::GeneratePincode(context_); - // 显示PIN码 - if (AuthSinkStatePinAuthComm::ShowAuthInfoDialog(context_) != DM_OK) { - LOGI("ShowAuthInfoDialog err."); - context_->reason = ERR_DM_BIND_USER_CANCEL; - context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); - } - } else { - context_->inputPinAuthFailTimes++; - } - // 失败 MAX_AUTH_FAIL_TIMES 次后,走认证失败 ON_FAIL - if (context_->inputPinAuthFailTimes >= MAX_AUTH_FAIL_TIMES) { - LOGI("AuthSinkManager::AuthDeviceError Auth pin err fail."); - context_->reason = ERR_DM_INPUT_PARA_INVALID; - context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); - } else { - // Notify ON_ERROR 事件,对应 Action 内会当正常重试处理,而非失败 - - context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); - // 将由新收到的120报文触发回退状态到 AuthSinkPinAuthStartState - LOGI("AuthSinkManager::AuthDeviceError Auth pin err, will retry."); - } - #else + LOGI("AuthSrcManager::AuthDeviceError Auth pin err."); if (context_->authType == DmAuthType::AUTH_TYPE_PIN) { context_->inputPinAuthFailTimes++; } context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); context_->authStateMachine->TransitionTo(std::make_shared()); - #endif } LOGI("AuthSinkManager::AuthDeviceError leave."); } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 07295dbe4..ca316470d 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -129,21 +129,9 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) } // 无凭据 return DoPinAuth(context); -#else -#ifndef NEW_PIN_STATE // todo del - // todo del 无凭据 send 100 - context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_USER_CONFIRM, context); - - context->timer->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), - CONFIRM_TIMEOUT, [context] (std::string name) { - HandleAuthenticateTimeout(context, name); - }); - LOGI("AuthSrcConfirmState::Action ok"); - return DM_OK; #else return DoPinAuth(context); #endif -#endif } DmAuthStateType AuthSinkConfirmState::GetStateType() @@ -175,93 +163,6 @@ int32_t AuthSinkConfirmState::ShowConfigDialog(std::shared_ptr co LOGI("AuthSinkConfirmState::ShowConfigDialog end"); return DM_OK; } -#if 0 // todo del 新的获取方法 根据客户端AuthType和BundleName从服务端SP表里查询业务注册的认证类型 -int32_t AuthSinkConfirmState::MatchAuthType(std::shared_ptr context) -{ - // DP 接口 查询ServiceInfoProfile - std::vector serviceInfos; - DistributedDeviceProfile::ServiceInfoUniqueKey key; - auto tokenId = std::to_string(context->accessee.tokenId); - key.SetUserId(context->accessee.userId); - key.SetDeviceId(context->accessee.deviceId); - key.SetTokenId(tokenId); - auto ret = DeviceProfileConnector::GetInstance().GetServiceInfoProfileListByTokenId(key, serviceInfos); - if (ret != DM_OK) { - LOGE("AuthSinkConfirmState::MatchAuthType GetServiceInfoByTokenId err %{public}d", ret); - // 获取不到走PIN认证方案 - if (context->authType != DmAuthType::AUTH_TYPE_PIN) { - LOGE("AuthSinkConfirmState::MatchAuthType AUTH_TYPE_PIN not match"); - return STOP_BIND; - } - return DM_OK; - } - - LOGI("AuthSinkConfirmState::Action GetServiceInfoByTokenId ret ok"); - - // 过滤掉 以下2个字段不为空(或0)的 serviceInfo - // serviceId 发布的服务ID,服务的唯一标识 - // serviceType 发布的服务类型 - std::vector filterServiceInfos; - for (auto& serviceInfo : serviceInfos) { - if (serviceInfo.GetServiceId() == 0 && serviceInfo.GetServiceType().empty()) { - filterServiceInfos.push_back(serviceInfo); - } - } - - // 期望有且仅有一条符合的 serviceInfo - if (filterServiceInfos.size() != 1) { - LOGE("AuthSinkConfirmState::MatchAuthType filterServiceInfo not unique"); - return STOP_BIND; - } - - auto& srvInfo = filterServiceInfos[0]; // 弹框用到 serviceInfo 中的内容? - - auto authBoxType = srvInfo.GetAuthBoxType(); - int32_t pinExchangeType = srvInfo.GetPinExchangeType(); - if (authBoxType == DistributedDeviceProfile::NUM_1) { // 三态框 - if (context->authType != DmAuthType::AUTH_TYPE_PIN) { - LOGE("AuthSinkConfirmState::MatchAuthType AUTH_TYPE_PIN not match"); - return STOP_BIND; - } - return DM_OK; - } else if (authBoxType == DistributedDeviceProfile::NUM_2) { - int32_t authResult = srvInfo.GetAuthType(); - if (authResult == 0) { - context->authResult = USER_OPERATION_TYPE_ALLOW_AUTH; - } else if (authResult == DistributedDeviceProfile::NUM_1) { - context->authResult = USER_OPERATION_TYPE_CANCEL_AUTH; - } else if (authResult == DistributedDeviceProfile::NUM_6) { - context->authResult = USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; - } - - if (pinExchangeType == DistributedDeviceProfile::NUM_2) { // 超声交换PIN - if (context->authType != DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { - LOGE("AuthSinkConfirmState::MatchAuthType AUTH_TYPE_PIN_ULTRASONIC not match"); - return STOP_BIND; - } - return DM_OK; - } else if (pinExchangeType == DistributedDeviceProfile::NUM_3) { // 导入PIN - if (context->authType != DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { - LOGE("AuthSinkConfirmState::MatchAuthType AUTH_TYPE_IMPORT_AUTH_CODE not match"); - return STOP_BIND; - } - // 读取PIN码 - std::string pinCode = srvInfo.GetPinCode(); - context->pinCode = std::stoi(pinCode); - return DM_OK; - } - } - - LOGE("AuthSinkConfirmState::MatchAuthType authType not support"); - return STOP_BIND; -} -#else -int32_t AuthSinkConfirmState::MatchAuthType(std::shared_ptr context) -{ - context->authResult = USER_OPERATION_TYPE_ALLOW_AUTH; - return DM_OK; -} -#endif int64_t AuthSinkConfirmState::GenRequestId(std::shared_ptr context) { @@ -273,7 +174,6 @@ int64_t AuthSinkConfirmState::GenRequestId(std::shared_ptr contex int32_t AuthSinkConfirmState::Action(std::shared_ptr context) { -#ifdef NEW_PIN_STATE // todo 新状态流程,待测试 LOGI("AuthSinkConfirmState::Action start"); // 停止授权报文计时 context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); @@ -322,64 +222,6 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) LOGI("AuthSinkConfirmState::Action ok"); return DM_OK; - -#else // todo del - LOGI("AuthSinkConfirmState::Action start"); - // 停止授权报文计时 - context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); - context->requestId = GenRequestId(context); - auto ret = MatchAuthType(context); - if (ret != DM_OK) { - return ret; - } - - if (context->authType == DmAuthType::AUTH_TYPE_PIN) { // 三态框 - LOGI("AuthSinkConfirmState::Action AUTH_TYPE_PIN "); - // 拉起授权确认页面 - if ((ret = ShowConfigDialog(context)) != DM_OK) { - return ret; - } - // 等待用户授权操作完成 - if(DmEventType::ON_USER_OPERATION != context->authStateMachine->WaitExpectEvent(DmEventType::ON_USER_OPERATION)) { - LOGE("AuthSinkConfirmState::Action wait ON_USER_OPERATION err"); - return STOP_BIND; // 外部事件错误,中止流程 - } - // 判断授权结果 - if (context->reply == USER_OPERATION_TYPE_ALLOW_AUTH) { - LOGI("AuthSinkConfirmState::Action USER_OPERATION_TYPE_ALLOW_AUTH"); - // 发送110报文 - context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); - // 生成PIN码 - AuthSinkStatePinAuthComm::GeneratePincode(context); - // 显示PIN码 - if ((ret = AuthSinkStatePinAuthComm::ShowAuthInfoDialog(context)) != DM_OK) { - return ret; - } - } else { - LOGI("AuthSinkConfirmState::Action USER_OPERATION_TYPE_CANCEL_AUTH"); - context->reason = ERR_DM_BIND_USER_CANCEL; - return STOP_BIND; // 用户取消授权 - } - } else { - if (context->authResult == USER_OPERATION_TYPE_CANCEL_AUTH) { - LOGI("AuthSinkConfirmState::Action USER_OPERATION_TYPE_CANCEL_AUTH"); - context->reason = ERR_DM_BIND_USER_CANCEL; - return STOP_BIND; // 用户取消授权 - } - if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { // 超声交换PIN - LOGI("AuthSinkConfirmState::Action AUTH_TYPE_PIN_ULTRASONIC"); - // 发送110报文 - context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); - // 请求发送超声PIN码 - } else if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { // 导入PIN - LOGI("AuthSinkConfirmState::Action AUTH_TYPE_IMPORT_AUTH_CODE"); - // 发送110报文 - context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); - } - } - LOGI("AuthSinkConfirmState::Action ok"); - return DM_OK; -#endif } } // namespace DistributedHardware diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 215590f1a..9acf16432 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -101,92 +101,9 @@ DmAuthStateType AuthSrcPinAuthStartState::GetStateType() return DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE; } -int32_t AuthSrcPinAuthStartState::ShowStartAuthDialog(std::shared_ptr context) -{ - LOGI("AuthSrcPinAuthStartState::ShowStartAuthDialog start."); - if (DmAuthState::IsScreenLocked()) { - LOGE("ShowStartAuthDialog screen is locked."); - context->reason = ERR_DM_BIND_USER_CANCEL; - return STOP_BIND; - } - DmDialogManager::GetInstance().ShowInputDialog(context->accessee.deviceName); - LOGI("AuthSrcPinAuthStartState::ShowStartAuthDialog end."); - return DM_OK; -} - -int32_t AuthSrcPinAuthStartState::GetPinCodeFromServerInfo(std::shared_ptr context) -{ - LOGI("AuthSrcPinAuthStartState::GetPinCodeFromServerInfo start"); - int32_t pinCode = INVALID_PINCODE; // 没获取到返回默认INVALID_PINCODE, 失败后会进入用户输入PIN流程 -#if 0 // todo - std::vector serviceInfos; - DistributedDeviceProfile::ServiceInfoUniqueKey key; - auto tokenId = std::to_string(context->accesser.tokenId); - key.SetUserId(context->accesser.userId); - key.SetDeviceId(context->accesser.deviceId); - key.SetTokenId(tokenId); - auto ret = DeviceProfileConnector::GetInstance().GetServiceInfoProfileListByTokenId(key, serviceInfos); - if (ret == DM_OK) { - std::vector filterServiceInfos; - for (auto& serviceInfo : serviceInfos) { - if (serviceInfo.GetServiceId() == 0 && serviceInfo.GetServiceType().empty()) { - filterServiceInfos.push_back(serviceInfo); - } - } - if (filterServiceInfos.size() == 1) { - auto& srvInfo = filterServiceInfos[0]; - LOGI("AuthSrcPinAuthStartState::GetPinCodeFromServerInfo got pincode from ServiceInfoProfile"); - pinCode = std::atoi(srvInfo.GetPinCode().c_str()); - } - } else { - LOGE("AuthSinkConfirmState::GetPinCodeFromServerInfo GetServiceInfoByTokenId err %{public}d", ret); - } -#endif - return pinCode; -} - -int32_t AuthSrcPinAuthStartState::GetPinCode(std::shared_ptr context) -{ - LOGI("AuthSrcPinAuthStartState::GetPinCode start"); - if (context->inputPinAuthFailTimes == 0) { - if (context->authType == DmAuthType::AUTH_TYPE_PIN || context->pinNegotiateStarted) { - // 拉起PIN码输入界面 - auto ret = ShowStartAuthDialog(context); - if (ret != DM_OK) { - return ret; - } - } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { - // todo: 预留超声PinCode获取 - return DM_OK; - } else { - // 从serverInfo中读取PIN码 - context->pinCode = GetPinCodeFromServerInfo(context); - return DM_OK; - } - } else { - // 清空PIN输入框,提示用户重试 - context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); - } - - LOGI("AuthSrcPinAuthStartState::GetPinCode waitting user operation"); - // 等待用户输密码操作完成 - if(DmEventType::ON_USER_OPERATION != context->authStateMachine->WaitExpectEvent(DmEventType::ON_USER_OPERATION)) { - LOGI("AuthSrcPinAuthStartState::GetPinCode wait ON_USER_OPERATION err"); - return STOP_BIND; // 外部事件错误,中止流程 - } - - if (context->pinInputResult != USER_OPERATION_TYPE_DONE_PINCODE_INPUT) { - LOGE("AuthSrcPinAuthStartState::GetPinCode not USER_OPERATION_TYPE_DONE_PINCODE_INPUT err"); - return STOP_BIND; - } - - LOGI("AuthSrcPinAuthStartState::GetPinCode input ok"); - return DM_OK; -} - - -int32_t AuthSrcPinAuthStartState::AuthDevice(std::shared_ptr context) +int32_t AuthSrcPinAuthStartState::Action(std::shared_ptr context) { + LOGI("AuthSrcPinAuthStartState::Action start"); int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); auto ret = context->hiChainAuthConnector->AuthCredentialPinCode(osAccountId, context->requestId, context->pinCode); @@ -208,27 +125,6 @@ int32_t AuthSrcPinAuthStartState::AuthDevice(std::shared_ptr cont return STOP_BIND; } -int32_t AuthSrcPinAuthStartState::Action(std::shared_ptr context) -{ - LOGI("AuthSrcPinAuthStartState::Action start"); - #ifndef NEW_PIN_STATE // todo del - context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); - // 首次进入停止计时器 - if (context->inputPinAuthFailTimes == 0 && !context->pinNegotiateStarted) { - context->timer->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); - } - - // 获取PIN码 - auto ret = GetPinCode(context); - if (ret != DM_OK) { - LOGE("AuthSrcPinAuthStartState::Action GetPinCode err"); - return ret; - } - #endif - // 做认证 发120报文 - return AuthDevice(context); -} - DmAuthStateType AuthSinkPinAuthStartState::GetStateType() { return DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index d923d1b2d..9534720e8 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -904,11 +904,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const nlohmann::json if (IsInt32(json, DM_TAG_AUTH_RESULT)) { context->authResult = static_cast(json[DM_TAG_AUTH_RESULT].get()); } -#ifndef NEW_PIN_STATE // todo del - context->authStateMachine->TransitionTo(std::make_shared()); -#else context->authStateMachine->TransitionTo(std::make_shared()); -#endif return DM_OK; } int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const nlohmann::json &json, diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 0476e81d2..4dc3fb7f2 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -36,7 +36,6 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) {DmAuthStateType::AUTH_SRC_START_STATE, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE}}, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE}}, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE, { - DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, // todo del DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, }}, @@ -54,17 +53,14 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) }}, {DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, { DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, - DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, // todo del DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, }}, {DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE, { DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, - DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, // todo del DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, }}, {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, { DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, - DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, // todo del DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, }}, {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, @@ -87,7 +83,6 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE }}, // to check {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, { - DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, // todo del DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, }}, {DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, { @@ -104,12 +99,10 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) }}, {DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, { DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, - DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, // todo del DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, }}, {DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE, { DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, - DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, // todo del DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, }}, {DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE}}, -- Gitee From cc0980880de92616356ec9c08c2ecd2a10085b0b Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 17 Mar 2025 16:36:46 +0800 Subject: [PATCH 213/382] =?UTF-8?q?sessionname=20=E5=9C=A880=E6=8A=A5?= =?UTF-8?q?=E6=96=87=E4=BC=A0=E9=80=92?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 9534720e8..1046acd19 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -448,6 +448,7 @@ int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr void DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject) { jsonObject[TAG_AUTH_TYPE] = context->authType; + jsonObject[TAG_SESSION_NAME] = context->sessionName; jsonObject[DM_TAG_DMVERSION] = context->accesser.dmVersion; jsonObject[TAG_DEVICE_NAME] = context->accesser.deviceName; @@ -799,6 +800,9 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject if (IsInt32(jsonObject, TAG_AUTH_TYPE)) { context->authType = static_cast(jsonObject[TAG_AUTH_TYPE].get()); } + if (IsString(jsonObject, TAG_SESSION_NAME)) { + context->sessionName = jsonObject[TAG_SESSION_NAME].get(); + } if (jsonObject.contains(DM_TAG_EXTRA_INFO) && jsonObject[DM_TAG_EXTRA_INFO].is_object()) { ParseNegotiateExtraInfoMessage(jsonObject[DM_TAG_EXTRA_INFO], context); @@ -878,9 +882,6 @@ int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const nlohmann::json if (IsString(json, TAG_DEVICE_NAME)) { context->accesser.deviceName = json[TAG_DEVICE_NAME].get(); } - if (IsString(json, TAG_SESSION_NAME)) { - context->sessionName = json[TAG_SESSION_NAME].get(); - } if (IsUint32(json, DM_TAG_CURRENT_AUTH_TYPE_IDX)) { auto idx = json[DM_TAG_CURRENT_AUTH_TYPE_IDX].get(); if (idx < context->authTypeList.size()) { @@ -952,7 +953,6 @@ void DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptrauthType; json[TAG_DEVICE_TYPE] = context->accesser.deviceType; json[TAG_DEVICE_NAME] = context->accesser.deviceName; - json[TAG_SESSION_NAME] = context->sessionName; json[DM_TAG_CURRENT_AUTH_TYPE_IDX] = context->currentAuthTypeIdx; } -- Gitee From 7cfbaa7f6287b8a3edfca97cfc6eac72df1aaf01 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 17 Mar 2025 16:52:11 +0800 Subject: [PATCH 214/382] tmp --- .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 47604e80a..c310a7973 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -498,12 +498,11 @@ void AuthSinkNegotiateStateMachine::NegotiatePinAuthType(std::shared_ptrauthType == DmAuthType::AUTH_TYPE_PIN || context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { context->authBoxType = OHOS::DistributedDeviceProfile::NUM_1; // 三态框 - } else { - context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // 免弹框 } if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { if (IsAuthCodeReady(context)) { context->authTypeList.push_back(context->authType); + context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // 免弹框 } } else { context->authTypeList.push_back(context->authType); // 没匹配到,但是不是导入授权码,也添加到候选列表 -- Gitee From 6f432b1b98fae9ddd472c715e2540a4eb815fde6 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 17 Mar 2025 17:27:58 +0800 Subject: [PATCH 215/382] Revert "tmp" This reverts commit 7cfbaa7f6287b8a3edfca97cfc6eac72df1aaf01. --- .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index c310a7973..47604e80a 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -498,11 +498,12 @@ void AuthSinkNegotiateStateMachine::NegotiatePinAuthType(std::shared_ptrauthType == DmAuthType::AUTH_TYPE_PIN || context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { context->authBoxType = OHOS::DistributedDeviceProfile::NUM_1; // 三态框 + } else { + context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // 免弹框 } if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { if (IsAuthCodeReady(context)) { context->authTypeList.push_back(context->authType); - context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // 免弹框 } } else { context->authTypeList.push_back(context->authType); // 没匹配到,但是不是导入授权码,也添加到候选列表 -- Gitee From acb258ead57a274c67c23208935bb2b955cb6a12 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Thu, 13 Mar 2025 14:03:05 +0800 Subject: [PATCH 216/382] =?UTF-8?q?fix=EF=BC=9Anlohmann::json=E6=9B=BF?= =?UTF-8?q?=E6=8D=A2=E6=88=90common=E4=B8=8B=E9=9D=A2=E7=9A=84Cjson?= =?UTF-8?q?=E5=B0=81=E8=A3=85?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/auth_manager.h | 7 +- .../authentication_v2/dm_auth_context.h | 1 - .../dm_auth_message_processor.h | 70 ++- .../include/authentication_v2/dm_auth_state.h | 2 +- .../src/authentication_v2/auth_manager.cpp | 86 ++-- .../auth_stages/auth_confirm.cpp | 8 +- .../auth_stages/auth_credential.cpp | 6 +- .../auth_stages/auth_negotiate.cpp | 29 +- .../auth_stages/auth_pin_auth.cpp | 4 +- .../dm_auth_message_processor.cpp | 405 +++++++++--------- 10 files changed, 312 insertions(+), 306 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index a43453db6..2d17b0978 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -17,6 +17,7 @@ #define OHOS_DM_AUTH_MANAGER_V2_H #include +#include "json_ojbect.h" #include "hichain_auth_connector.h" #include "hichain_connector.h" #include "softbus_connector.h" @@ -154,11 +155,11 @@ protected: 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(nlohmann::json jsonObject); - void ParseJsonObject(nlohmann::json jsonObject); + void ParseHmlInfoInJsonObject(JsonObject jsonObject); + void ParseJsonObject(JsonObject jsonObject); void GetAuthParam(const std::string &sessionName, int32_t authType, const std::string &deviceId, const std::string &extra); - std::string GetBundleName(nlohmann::json &jsonObject); + std::string GetBundleName(JsonObject &jsonObject); int32_t GetBindLevel(int32_t bindLevel); void SetAuthType(int32_t authType); bool IsAuthTypeSupported(const int32_t &authType); diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 7263362a2..9cb528bb0 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -19,7 +19,6 @@ #include #include -#include "nlohmann/json.hpp" #include "auth_ui_state_manager.h" #include "hichain_auth_connector.h" #include "hichain_connector.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 index 640494ff1..33b096a4c 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -17,7 +17,7 @@ #define OHOS_DM_AUTH_MESSAGE_PROCESSOR_V2_H #include -#include "nlohmann/json.hpp" +#include "json_object.h" #include "crypto_mgr.h" #include "access_control_profile.h" #include "deviceprofile_connector.h" @@ -162,9 +162,6 @@ struct DmAccessControlTable { int32_t validPeriod; int32_t lastAuthTime; uint32_t bindLevel; - NLOHMANN_DEFINE_TYPE_INTRUSIVE(DmAccessControlTable, accessControlId, accesserId, accesseeId, deviceId, sessionKey, - bindType, authType, deviceType, deviceIdHash, status, validPeriod, lastAuthTime, - bindLevel, deviceIdHash) }; // 用于同步ACL的access结构 @@ -178,9 +175,6 @@ struct DmAccessToSync { int32_t bindLevel; // 为业务透传数据,无需自定义 int32_t sessionKeyId; // 用户凭据ID int64_t skTimeStamp; // 老化,时间为2天 用户级凭据时间戳 - // 使用宏进行序列化和反序列化 - NLOHMANN_DEFINE_TYPE_INTRUSIVE(DmAccessToSync, deviceName, deviceId, userId, accountId, tokenId, bundleName, - bindLevel, sessionKeyId, skTimeStamp) }; class DmAuthMessageProcessor { @@ -215,64 +209,64 @@ private: // 用于组装syncMsg中的加密部分 int32_t EncryptSyncMessage(std::shared_ptr &context, DmAccess &accessSide, std::string &encSyncMsg); - int32_t ParseAuthStartMessgae(nlohmann::json &jsonObject, std::shared_ptr &context); + int32_t ParseAuthStartMessgae(JsonObject &jsonObject, std::shared_ptr &context); // 解析 80报文 - int32_t ParseNegotiateMessage(nlohmann::json &jsonObject, std::shared_ptr context); + int32_t ParseNegotiateMessage(JsonObject &jsonObject, std::shared_ptr context); // 解析 90 报文 - int32_t ParseMessageRespAclNegotiate(const nlohmann::json &json, std::shared_ptr context); + int32_t ParseMessageRespAclNegotiate(const JsonObject &json, std::shared_ptr context); // 解析 100 报文 - int32_t ParseMessageReqUserConfirm(const nlohmann::json &json, std::shared_ptr context); + int32_t ParseMessageReqUserConfirm(const JsonObject &json, std::shared_ptr context); // 解析 110 报文 - int32_t ParseMessageRespUserConfirm(const nlohmann::json &json, std::shared_ptr context); + int32_t ParseMessageRespUserConfirm(const JsonObject &json, std::shared_ptr context); // 解析 120 报文 - int32_t ParseMessageReqPinAuthStart(const nlohmann::json &json, std::shared_ptr context); + int32_t ParseMessageReqPinAuthStart(const JsonObject &json, std::shared_ptr context); // 解析 130 报文 - int32_t ParseMessageRespPinAuthStart(const nlohmann::json &json, std::shared_ptr context); + int32_t ParseMessageRespPinAuthStart(const JsonObject &json, std::shared_ptr context); // 解析 121 报文 - int32_t ParseMessageReqPinAuthNegotiate(const nlohmann::json &json, std::shared_ptr context); + int32_t ParseMessageReqPinAuthNegotiate(const JsonObject &json, std::shared_ptr context); // 解析 131报文 - int32_t ParseMessageRespPinAuthNegotiate(const nlohmann::json &jsonObject, std::shared_ptr context); + int32_t ParseMessageRespPinAuthNegotiate(const JsonObject &jsonObject, std::shared_ptr context); // 解析 140报文信息MSG_TYPE_REQ_CREDENTIAL_EXCHANGE,SINK端存放对方公钥 - int32_t ParseMessageReqCredExchange(const nlohmann::json &jsonObject, std::shared_ptr context); + int32_t ParseMessageReqCredExchange(const JsonObject &jsonObject, std::shared_ptr context); // 解析 150报文信息MSG_TYPE_RESP_CREDENTIAL_EXCHANGE,存放对方公钥,和协商凭据Id - int32_t ParseMessageRspCredExchange(const nlohmann::json &jsonObject, std::shared_ptr context); + int32_t ParseMessageRspCredExchange(const JsonObject &jsonObject, std::shared_ptr context); // 解析161 170 171 - int32_t ParseMessageNegotiateTransmit(const nlohmann::json &jsonObject, std::shared_ptr &context, + int32_t ParseMessageNegotiateTransmit(const JsonObject &jsonObject, std::shared_ptr &context, DmMessageType msgType); // 解析 180报文信息 MSG_TYPE_REQ_DATA_SYNC 存放对方密文四元组,acl,sp skid - int32_t ParseMessageSyncReq(const nlohmann::json &jsonObject, std::shared_ptr context); + int32_t ParseMessageSyncReq(const JsonObject &jsonObject, std::shared_ptr context); // 解析 190报文信息 MSG_TYPE_RESP_DATA_SYNC 存放对方密文四元组,acl sp skid - int32_t ParseMessageSyncResp(const nlohmann::json &jsonObject, std::shared_ptr context); + int32_t ParseMessageSyncResp(const JsonObject &jsonObject, std::shared_ptr context); // 解析 200报文信息 - int32_t ParseMessageFinish(std::shared_ptr context, nlohmann::json &jsonObject); + int32_t ParseMessageFinish(std::shared_ptr context, JsonObject &jsonObject); // 创建 80报文 - void CreateNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject); + void CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); // 创建 90报文 - void CreateRespNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject); + void CreateRespNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); // 创建 100 报文 - void CreateMessageReqUserConfirm(std::shared_ptr context, nlohmann::json &json); + void CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json); // 创建 110 报文 - void CreateMessageRespUserConfirm(std::shared_ptr context, nlohmann::json &json); + void CreateMessageRespUserConfirm(std::shared_ptr context, JsonObject &json); // 创建 120 报文 - void CreateMessageReqPinAuthStart(std::shared_ptr context, nlohmann::json &json); + void CreateMessageReqPinAuthStart(std::shared_ptr context, JsonObject &json); // 创建 130 报文 - void CreateMessageRespPinAuthStart(std::shared_ptr context, nlohmann::json &json); + void CreateMessageRespPinAuthStart(std::shared_ptr context, JsonObject &json); // 创建 121 报文 - void CreateMessageReqPinAuthNegotiate(std::shared_ptr context, nlohmann::json &json); + void CreateMessageReqPinAuthNegotiate(std::shared_ptr context, JsonObject &json); // 创建 131 报文 - void CreateMessageRespPinAuthNegotiate(std::shared_ptr context, nlohmann::json &json); + void CreateMessageRespPinAuthNegotiate(std::shared_ptr context, JsonObject &json); // 创建140报文 - void CreateMessageReqCredExchange(std::shared_ptr context, nlohmann::json &jsonObject); + void CreateMessageReqCredExchange(std::shared_ptr context, JsonObject &jsonObject); // 创建150报文 - void CreateMessageRspCredExchange(std::shared_ptr context, nlohmann::json &jsonObject); + void CreateMessageRspCredExchange(std::shared_ptr context, JsonObject &jsonObject); // 创建160报文 - void CreateMessageReqCredAuthStart(std::shared_ptr context, nlohmann::json &jsonObject); + void CreateMessageReqCredAuthStart(std::shared_ptr context, JsonObject &jsonObject); // 161 170 171 透传凭据认证消息构造 - int32_t CreateCredentialNegotiateMessage(std::shared_ptr &context, nlohmann::json &jsonObject); + int32_t CreateCredentialNegotiateMessage(std::shared_ptr &context, JsonObject &jsonObject); // 180 190 消息构造 - int32_t CreateSyncMessage(std::shared_ptr &context, nlohmann::json &jsonObject); + int32_t CreateSyncMessage(std::shared_ptr &context, JsonObject &jsonObject); // 压缩sync 消息 std::string CompressSyncMsg(std::string &inputStr); // 解压缩sync 消息 @@ -280,14 +274,14 @@ private: // 序列化acl int32_t ACLToStr(DistributedDeviceProfile::AccessControlProfile acl, std::string aclStr); // 创建190报文 - void CreateMessageSyncResp(std::shared_ptr context, nlohmann::json &jsonObject); + void CreateMessageSyncResp(std::shared_ptr context, JsonObject &jsonObject); // 创建200报文 - void CreateMessageFinish(std::shared_ptr context, nlohmann::json &jsonObject); + void CreateMessageFinish(std::shared_ptr context, JsonObject &jsonObject); // 解密180 190报文 int32_t DecryptSyncMessage(std::shared_ptr &context, DmAccess &access, std::string &enSyncMsg); int32_t ParseSyncMessage(std::shared_ptr &context, - DmAccess &access, nlohmann::json jsonObject); + DmAccess &access, JsonObject jsonObject); // DP中accesser_table记录转string std::string AccesserToStr(DistributedDeviceProfile::AccessControlProfile acl); diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index f3dd6438b..8b1ef4f0d 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -333,7 +333,7 @@ public: private: int32_t RespQueryAcceseeIds(std::shared_ptr context); bool HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList); - uint32_t GetCredentialType(std::shared_ptr context, nlohmann::json credInfo); + uint32_t GetCredentialType(std::shared_ptr context, JsonObject credInfo); bool AclCompareTwoIds(std::shared_ptr context, const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); bool AclCompareFourIds(std::shared_ptr context, diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 11ca33b6b..d1108f578 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -107,12 +107,12 @@ bool IsAllowDeviceBind(void) int32_t CheckAuthParamVaildExtra(const std::string &extra) { - nlohmann::json jsonObject = nlohmann::json::parse(extra, nullptr, false); - if (jsonObject.is_discarded() || jsonObject.find(TAG_BIND_LEVEL) == jsonObject.end() || - !IsInt32(jsonObject, TAG_BIND_LEVEL)) { + JsonObject jsonObject(extra); + if (jsonObject.IsDiscarded() || !jsonObject.Contains(TAG_BIND_LEVEL) || + !jsonObject[TAG_BIND_LEVEL].IsNumberInteger()) { return DM_OK; } - int32_t bindLevel = jsonObject[TAG_BIND_LEVEL].get(); + int32_t bindLevel = jsonObject[TAG_BIND_LEVEL].Get(); if (static_cast(bindLevel) > APP || bindLevel < INVALID_TYPE) { LOGE("bindlevel error %{public}d.", bindLevel); return ERR_DM_INPUT_PARA_INVALID; @@ -458,22 +458,22 @@ int32_t AuthManager::CheckAuthParamVaild(const std::string &sessionName, int32_t return DM_OK; } -void AuthManager::ParseHmlInfoInJsonObject(nlohmann::json jsonObject) +void AuthManager::ParseHmlInfoInJsonObject(JsonObject jsonObject) { - if (IsString(jsonObject, PARAM_KEY_CONN_SESSIONTYPE)) { - context_->connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].get(); + if (jsonObject[PARAM_KEY_CONN_SESSIONTYPE].IsString()) { + context_->connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get(); LOGI("connSessionType %{public}s", context_->connSessionType.c_str()); } if (!IsHmlSessionType(context_->connSessionType)) { return; } context_->connDelayCloseTime = HML_SESSION_TIMEOUT; - if (IsBool(jsonObject, PARAM_KEY_HML_ENABLE_160M)) { - context_->hmlEnable160M = jsonObject[PARAM_KEY_HML_ENABLE_160M].get(); + if (jsonObject[PARAM_KEY_HML_ENABLE_160M].IsBool()) { + context_->hmlEnable160M = jsonObject[PARAM_KEY_HML_ENABLE_160M].Get(); LOGI("hmlEnable160M %{public}d", context_->hmlEnable160M); } - if (IsInt32(jsonObject, PARAM_KEY_HML_ACTIONID)) { - context_->hmlActionId = jsonObject[PARAM_KEY_HML_ACTIONID].get(); + if (jsonObject[PARAM_KEY_HML_ACTIONID].IsNumberInteger()) { + context_->hmlActionId = jsonObject[PARAM_KEY_HML_ACTIONID].Get(); if (context_->hmlActionId <= 0) { context_->hmlActionId = 0; } @@ -483,10 +483,10 @@ void AuthManager::ParseHmlInfoInJsonObject(nlohmann::json jsonObject) return; } -std::string AuthManager::GetBundleName(nlohmann::json &jsonObject) +std::string AuthManager::GetBundleName(JsonObject &jsonObject) { - if (!jsonObject.is_discarded() && IsString(jsonObject, BUNDLE_NAME_KEY)) { - return jsonObject[BUNDLE_NAME_KEY].get(); + if (!jsonObject.IsDiscarded() && jsonObject[BUNDLE_NAME_KEY].IsString()) { + return jsonObject[BUNDLE_NAME_KEY].Get(); } bool isSystemSA = false; std::string bundleName; @@ -494,37 +494,37 @@ std::string AuthManager::GetBundleName(nlohmann::json &jsonObject) return bundleName; } -void AuthManager::ParseJsonObject(nlohmann::json jsonObject) +void AuthManager::ParseJsonObject(JsonObject jsonObject) { - if (jsonObject.is_discarded()) { + if (jsonObject.IsDiscarded()) { return; } // 填充context_ - if (IsString(jsonObject, APP_OPERATION_KEY)) { - context_->appOperation = jsonObject[APP_OPERATION_KEY].get(); + if (jsonObject[APP_OPERATION_KEY].IsString()) { + context_->appOperation = jsonObject[APP_OPERATION_KEY].Get(); } - if (IsString(jsonObject, CUSTOM_DESCRIPTION_KEY)) { - context_->customData = jsonObject[CUSTOM_DESCRIPTION_KEY].get(); + if (jsonObject[CUSTOM_DESCRIPTION_KEY].IsString()) { + context_->customData = jsonObject[CUSTOM_DESCRIPTION_KEY].Get(); } - if (IsString(jsonObject, APP_THUMBNAIL)) { - context_->appThumbnail = jsonObject[APP_THUMBNAIL].get(); + if (jsonObject[APP_THUMBNAIL].IsString()) { + context_->appThumbnail = jsonObject[APP_THUMBNAIL].Get(); } context_->connDelayCloseTime = 0; - if (IsString(jsonObject, PARAM_CLOSE_SESSION_DELAY_SECONDS)) { - std::string delaySecondsStr = jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].get(); + if (jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].IsString()) { + std::string delaySecondsStr = jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].Get(); context_->connDelayCloseTime = GetCloseSessionDelaySeconds(delaySecondsStr); } // 填充context_->accesser - if (IsInt32(jsonObject, TAG_BIND_LEVEL)) { - context_->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].get(); + if (jsonObject[TAG_BIND_LEVEL].IsNumberInteger()) { + context_->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].Get(); } context_->accesser.bundleName = GetBundleName(jsonObject); // 填充context_accessee - if (IsString(jsonObject, TAG_PEER_BUNDLE_NAME)) { - context_->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].get(); + if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString()) { + context_->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); if (context_->accessee.bundleName == "") { context_->accessee.bundleName = context_->sessionName; } @@ -611,8 +611,8 @@ void AuthManager::GetAuthParam(const std::string &sessionName, int32_t authType, context_->accessee.deviceId = deviceId; context_->accessee.addr = deviceId; - nlohmann::json jsonObject = nlohmann::json::parse(extra, nullptr, false); - if (jsonObject.is_discarded()) { + JsonObject jsonObject(extra); + if (jsonObject.IsDiscarded()) { LOGE("extra string not a json type."); return; } @@ -795,18 +795,18 @@ void AuthSinkManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string me return; } - nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); - if (jsonObject.is_discarded()) { + JsonObject jsonObject(message); + if (jsonObject.IsDiscarded()) { LOGE("DecodeRequestAuth jsonStr error"); return; } - if (!IsString(jsonObject, DM_TAG_DATA) || !IsInt32(jsonObject, DM_TAG_DATA_LEN) || - !IsInt32(jsonObject, TAG_MSG_TYPE)) { + if (!jsonObject[DM_TAG_DATA].IsString() || !jsonObject[DM_TAG_DATA_LEN].IsNumberInteger() || + !jsonObject[TAG_MSG_TYPE].IsNumberInteger()) { LOGE("Auth device data is error."); return; } - LOGI("OnAuthDeviceDataReceived start msgType %{public}d.", jsonObject[TAG_MSG_TYPE].get()); - std::string authData = jsonObject[DM_TAG_DATA].get(); + LOGI("OnAuthDeviceDataReceived start msgType %{public}d.", jsonObject[TAG_MSG_TYPE].Get()); + std::string authData = jsonObject[DM_TAG_DATA].Get(); int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); context_->hiChainAuthConnector->ProcessAuthData(context_->requestId, authData, osAccountId); @@ -920,18 +920,18 @@ void AuthSrcManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string mes return; } - nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); - if (jsonObject.is_discarded()) { + JsonObject jsonObject(message); + if (jsonObject.IsDiscarded()) { LOGE("DecodeRequestAuth jsonStr error"); return; } - if (!IsString(jsonObject, DM_TAG_DATA) || !IsInt32(jsonObject, DM_TAG_DATA_LEN) || - !IsInt32(jsonObject, TAG_MSG_TYPE)) { + if (!jsonObject[DM_TAG_DATA].IsNumberInteger() || !jsonObject[DM_TAG_DATA_LEN].IsNumberInteger() || + !jsonObject[TAG_MSG_TYPE].IsNumberInteger()) { LOGE("Auth device data is error."); return; } - LOGI("OnAuthDeviceDataReceived start msgType %{public}d.", jsonObject[TAG_MSG_TYPE].get()); - std::string authData = jsonObject[DM_TAG_DATA].get(); + LOGI("OnAuthDeviceDataReceived start msgType %{public}d.", jsonObject[TAG_MSG_TYPE].Get()); + std::string authData = jsonObject[DM_TAG_DATA].Get(); int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); context_->hiChainAuthConnector->ProcessAuthData(context_->requestId, authData, osAccountId); @@ -1078,7 +1078,7 @@ char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, c LOGI("AuthSrcManager::AuthDeviceRequest start"); (void)requestId; (void)reqParams; - nlohmann::json jsonObj; + JsonObject jsonObj; DmAuthStateType curState = context_->authStateMachine->GetCurState(); if (curState == DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE) { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index ca316470d..c8ebb9cae 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -98,8 +98,8 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) return ERR_DM_VERSION_INCOMPATIBLE; } #if 0 // todo 有凭据情况 - nlohmann::json jsonObject = nlohmann::json::parse(context->accessee.credentialInfos, nullptr, false); - if (jsonObject.is_discarded()) { + JsonObject jsonObject(context->accessee.credentialInfos); + if (jsonObject.IsDiscarded()) { LOGE("AuthSrcConfirmState::Action parse credentialInfos error"); return ERR_DM_FAILED; } @@ -150,14 +150,14 @@ int32_t AuthSinkConfirmState::ShowConfigDialog(std::shared_ptr co return STOP_BIND; } - nlohmann::json jsonObj; + JsonObject jsonObj; jsonObj[TAG_CUSTOM_DESCRIPTION] = context->customData; jsonObj[TAG_LOCAL_DEVICE_TYPE] = context->accesser.deviceType; jsonObj[TAG_REQUESTER] = context->accesser.deviceName; jsonObj[TAG_USER_ID] = context->accessee.userId; jsonObj[TAG_HOST_PKGLABEL] = context->sessionName; - const std::string params = SafetyDump(jsonObj); + const std::string params = jsonObj.Dump(); DmDialogManager::GetInstance().ShowConfirmDialog(params); LOGI("AuthSinkConfirmState::ShowConfigDialog end"); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index f89b41552..15e6ff43d 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -253,7 +253,7 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori return std::string(""); } - nlohmann::json jsonObj; + JsonObject jsonObj; if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) { jsonObj[DM_TAG_METHOD] = method; // 凭据生成方式 } @@ -267,7 +267,7 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori jsonObj[DM_TAG_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; // 账号无关 jsonObj[DM_TAG_KEY_FORMAT] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? DM_AUTH_KEY_FORMAT_ASYMM_GENERATE : DM_AUTH_KEY_FORMAT_ASYMM_IMPORT; // 生成或导入非对称秘钥 - jsonObj[DM_TAG_ALGORITHM_TYPE] = DM_AUTH_ALG_TYPE_P256; // ED25519还没开发完,目前用P256 + jsonObj[DM_TAG_ALGORITHM_TYPE] = DM_AUTH_ALG_TYPE_ED25519; // ED25519 jsonObj[DM_TAG_PROOF_TYPE] = DM_AUTH_CREDENTIAL_PROOF_PSK; // PSK if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) { // 导入公钥 16进制字符串 jsonObj[DM_TAG_KEY_VALUE] = authContext->GetPublicKey(DM_AUTH_REMOTE_SIDE, authorizedScope); @@ -280,7 +280,7 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori jsonObj[DM_TAG_CREDENTIAL_OWNER] = DM_AUTH_CREDENTIAL_OWNER; // 调用方包名DM模块 LOGI("AuthCredentialAgreeState::CreateAuthParamsString leave."); - return SafetyDump(jsonObj); + return jsonObj.Dump(); } // 生成凭据Id和公钥 diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 47604e80a..7c4012591 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -15,7 +15,7 @@ #include #include -#include "nlohmann/json.hpp" +#include "json_object.h" #include "parameter.h" #include "multiple_user_connector.h" @@ -266,7 +266,7 @@ bool AuthSinkNegotiateStateMachine::HaveSameTokenId(std::shared_ptr context, nlohmann::json credInfo) +uint32_t AuthSinkNegotiateStateMachine::GetCredentialType(std::shared_ptr context, JsonObject credInfo) { // 判断是否同账号 // TODO: 需要确定截断长度 @@ -331,8 +331,9 @@ int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptr invalidCredIds; - nlohmann::json packResult; // 需要打包发送到对端的数据 - for (const auto& [credId, cred] : queryResult.items()) { - if (cred.find("isAclActive") == cred.end() || cred["isAclActive"] == false) { + JsonObject packResult; // 需要打包发送到对端的数据 + for (const auto &item : queryResult.Items()) { + credId = item.Key(); + JsonObject cred = item[credId]; + if (!cred.Contains("isAclActive") || cred["isAclActive"] == false) { continue; } - - packResult[credId] = cred[FILED_CRED_TYPE]; + packResult[credId] = cred[FILED_CRED_TYPE]; } - context->accessee.isAuthed = !queryResult.empty(); - context->accessee.credentialInfos = SafetyDump(packResult); + context->accessee.isAuthed = isEmpty; + context->accessee.credentialInfos = packResult.Dump(); return DM_OK; } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 9acf16432..ff3c3fdaa 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -78,9 +78,9 @@ void AuthSinkStatePinAuthComm::HandleSessionHeartbeat(std::shared_ptrtimer->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK)); LOGI("DmAuthManager::HandleSessionHeartbeat name %{public}s", name.c_str()); - nlohmann::json jsonObj; + JsonObject jsonObj; jsonObj[TAG_SESSION_HEARTBEAT] = TAG_SESSION_HEARTBEAT; - std::string message = SafetyDump(jsonObj); + std::string message = jsonObj.Dump(); context->softbusConnector->GetSoftbusSession()->SendHeartbeatData(context->sessionId, message); context->timer->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 1046acd19..9744fa8ba 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -41,7 +41,7 @@ namespace { constexpr const char* TAG_DEVICE_TYPE = "deviceType"; -void CreateNegotiateExtraInfoMessage(std::shared_ptr context, nlohmann::json &jsonExtraObject) +void CreateNegotiateExtraInfoMessage(std::shared_ptr context, JsonItemObject &jsonExtraObject) { if (context->accessee.displayId != 0) { jsonExtraObject[DM_TAG_PEER_DISPLAY_ID] = context->accessee.displayId; @@ -50,13 +50,14 @@ void CreateNegotiateExtraInfoMessage(std::shared_ptr context, nlo return; } -void ParseNegotiateExtraInfoMessage(nlohmann::json &jsonExtraObject, std::shared_ptr context) +void ParseNegotiateExtraInfoMessage(const JsonItemObject &jsonExtraObject, std::shared_ptr context) { // accesser在extra中传输对端peerUserId和peerDisplayId时,从中获取userId - if (IsInt32(jsonExtraObject, DM_TAG_ACCESSEE_USER_ID)) { - context->accessee.userId = jsonExtraObject[DM_TAG_ACCESSEE_USER_ID].get(); - } else if (IsInt32(jsonExtraObject, DM_TAG_PEER_DISPLAY_ID)) { - context->accessee.displayId = jsonExtraObject[DM_TAG_PEER_DISPLAY_ID].get(); + if (jsonExtraObject[DM_TAG_ACCESSEE_USER_ID].IsNumberInteger()) { + + context->accessee.userId = jsonExtraObject[DM_TAG_ACCESSEE_USER_ID].Get(); + } else if (jsonExtraObject[DM_TAG_PEER_DISPLAY_ID].IsNumberInteger()) { + context->accessee.displayId = jsonExtraObject[DM_TAG_PEER_DISPLAY_ID].Get(); } return; @@ -161,20 +162,20 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont return ERR_DM_FAILED; } - nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); - if (jsonObject.is_discarded()) { + JsonObject jsonObject(message); + if (jsonObject.Isdiscarded()) { LOGE("DmAuthMessageProcessor::ParseMessage failed, decodeRequestAuth jsonStr error"); return ERR_DM_FAILED; } - if (!IsInt32(jsonObject, TAG_MSG_TYPE)) { + if (!jsonObject[TAG_MSG_TYPE].IsNumberInteger()) { LOGE("DmAuthMessageProcessor::ParseMessage failed, message type error."); return ERR_DM_FAILED; } - DmMessageType msgType = static_cast(jsonObject[TAG_MSG_TYPE].get()); + DmMessageType msgType = static_cast(jsonObject[TAG_MSG_TYPE].Get()); context->msgType = msgType; LOGI("DmAuthMessageProcessor::ParseMessage message type %{public}d", context->msgType); // TODO:调试信息,上库前删除 - LOGI("DmAuthMessageProcessor::ParseMessage %{public}s", SafetyDump(jsonObject).c_str()); + LOGI("DmAuthMessageProcessor::ParseMessage %{public}s", jsonObject.Dump().c_str()); switch (msgType) { case MSG_TYPE_REQ_ACL_NEGOTIATE: return ParseNegotiateMessage(jsonObject, context); @@ -232,16 +233,15 @@ static std::string vectorToString(const std::vector& vec) { } return oss.str(); } - -int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const nlohmann::json &jsonObject, +int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const JsonObject &jsonObject, std::shared_ptr &context, DmMessageType msgType) { - if (jsonObject.is_discarded() || !jsonObject.contains(DM_TAG_DATA) || !jsonObject[DM_TAG_DATA].is_string()) { + if (jsonObject.Isdiscarded() || !jsonObject.Contains(DM_TAG_DATA) || !jsonObject[DM_TAG_DATA].IsString()) { LOGE("DmAuthMessageProcessor::ParseMessageNegotiateTransmit Unlegal json string failed"); return ERR_DM_FAILED; } - context->transmitData = jsonObject[DM_TAG_DATA].get(); + context->transmitData = jsonObject[DM_TAG_DATA].Get(); switch (msgType) { case MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE: // 161 @@ -261,108 +261,108 @@ int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const nlohmann::js } // 解析131报文信息MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE -int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate(const nlohmann::json &jsonObject, +int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate(const JsonObject &jsonObject, std::shared_ptr context) { - if (jsonObject.is_discarded() || !IsString(jsonObject, DM_TAG_DATA)) { + if (jsonObject.Isdiscarded() || !jsonObject[DM_TAG_DATA].IsString()) { LOGE("DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate failed, decodeRequestAuth jsonStr error"); return ERR_DM_FAILED; } - context->transmitData = jsonObject[DM_TAG_DATA].get(); + context->transmitData = jsonObject[DM_TAG_DATA].Get(); context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } // 解析140报文信息MSG_TYPE_REQ_CREDENTIAL_EXCHANGE,SINK端存放对方公钥 -int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const nlohmann::json &jsonObject, +int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const JsonObject &jsonObject, std::shared_ptr context) { - if (jsonObject.is_discarded() || !IsString(jsonObject, DM_TAG_DATA)) { + if (jsonObject.Isdiscarded() || !jsonObject[DM_TAG_DATA].IsString()) { LOGE("DecodeRequestAuth jsonStr error"); return ERR_DM_FAILED; } // 解密 std::string plainText; - if (cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA].get(), plainText) != DM_OK) { + if (cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA].Get(), plainText) != DM_OK) { LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange() error, decrypt data failed."); return ERR_DM_FAILED; } - nlohmann::json jsonData = nlohmann::json::parse(plainText, nullptr, false); + JsonObject jsonData(plainText); // 首次认证,解析用户级公钥 if (!context->isOnline) { - if (!IsString(jsonData, DM_TAG_USER_PUBLICK_KEY)) { + if (!jsonData[DM_TAG_USER_PUBLICK_KEY].IsString()) { LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange() error, first auth, no userPublicKey."); return ERR_DM_FAILED; } - context->accesser.userPublicKey = jsonData[DM_TAG_USER_PUBLICK_KEY].get(); + context->accesser.userPublicKey = jsonData[DM_TAG_USER_PUBLICK_KEY].Get(); } - if (!IsString(jsonData, DM_TAG_APP_PUBLICK_KEY) || - !IsString(jsonData, DM_TAG_DEVICE_ID) || - !IsInt32(jsonData, DM_TAG_PEER_USER_SPACE_ID) || - !IsInt64(jsonData, DM_TAG_TOKEN_ID)) { + if (!jsonData[DM_TAG_APP_PUBLICK_KEY].IsString() || + !jsonData[DM_TAG_DEVICE_ID].IsString() || + !jsonData[DM_TAG_PEER_USER_SPACE_ID].IsNumberInteger() || + !jsonData[DM_TAG_TOKEN_ID].IsNumberInteger()) { LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange, MSG_TYPE_REQ_CREDENTIAL_EXCHANGE message error."); return ERR_DM_FAILED; } - context->accesser.appPublicKey = jsonData[DM_TAG_APP_PUBLICK_KEY].get(); // 解析应用级公钥 - context->accesser.deviceId = jsonData[DM_TAG_DEVICE_ID].get(); // 解析deviceId - context->accesser.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].get(); // 解析userId - context->accesser.tokenId = jsonData[DM_TAG_TOKEN_ID].get(); // 解析tokenId + context->accesser.appPublicKey = jsonData[DM_TAG_APP_PUBLICK_KEY].Get(); // 解析应用级公钥 + context->accesser.deviceId = jsonData[DM_TAG_DEVICE_ID].Get(); // 解析deviceId + context->accesser.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].Get(); // 解析userId + context->accesser.tokenId = jsonData[DM_TAG_TOKEN_ID].Get(); // 解析tokenId context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } // 解析150报文信息MSG_TYPE_RESP_CREDENTIAL_EXCHANGE,SRC端存放对方公钥,和协商凭据Id -int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const nlohmann::json &jsonObject, +int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &jsonObject, std::shared_ptr context) { LOGI("DmAuthMessageProcessor::ParseMessageRspCredExchange start."); - if (jsonObject.is_discarded() || !IsString(jsonObject, DM_TAG_DATA)) { + if (jsonObject.Isdiscarded() || !jsonObject[DM_TAG_DATA].IsString()) { LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange, DecodeRequestAuth jsonStr error"); return ERR_DM_FAILED; } // 解密 std::string plainText; - if (cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA].get(), plainText) != DM_OK) { + if (cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA].Get(), plainText) != DM_OK) { LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange error, decrypt data failed."); return ERR_DM_FAILED; } LOGI("DmAuthMessageProcessor::ParseMessageRspCredExchange plainText=%{public}s", plainText.c_str()); - nlohmann::json jsonData = nlohmann::json::parse(plainText, nullptr, false); + JsonObject jsonData(plainText); // 首次认证,解析对方用户级公钥和协商用户级凭据Id std::string tmpString; if (!context->isOnline) { - if (!IsString(jsonData, DM_TAG_USER_PUBLICK_KEY) || !IsString(jsonData, DM_TAG_USER_CREDENTIAL_ID)) { + if (!jsonData[DM_TAG_USER_PUBLICK_KEY].IsString() || !jsonData[DM_TAG_USER_CREDENTIAL_ID].IsString()) { LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange failed, first auth but no userPublicKey or " "userCredentialId."); return ERR_DM_FAILED; } - context->accessee.userPublicKey = jsonData[DM_TAG_USER_PUBLICK_KEY].get(); + context->accessee.userPublicKey = jsonData[DM_TAG_USER_PUBLICK_KEY].Get(); context->accessee.userCredentialId = jsonData[DM_TAG_USER_CREDENTIAL_ID].get(); } // 解析对方应用级公钥和协商应用级凭据Id - if (!IsString(jsonData, DM_TAG_APP_PUBLICK_KEY) || - !IsString(jsonData, DM_TAG_APP_CREDENTIAL_ID) || - !IsString(jsonData, DM_TAG_DEVICE_ID) || - !IsInt32(jsonData, DM_TAG_PEER_USER_SPACE_ID) || - !IsInt64(jsonData, DM_TAG_TOKEN_ID)) { + if (!jsonData[DM_TAG_APP_PUBLICK_KEY].IsString() || + !jsonData[DM_TAG_APP_CREDENTIAL_ID].IsString() || + !jsonData[DM_TAG_DEVICE_ID].IsString() || + !jsonData[DM_TAG_PEER_USER_SPACE_ID].IsNumberInteger() || + !jsonData[DM_TAG_TOKEN_ID].IsNumberInteger()) { LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange failed, decode MSG_TYPE_RESP_CREDENTIAL_EXCHANGE " "message error."); return ERR_DM_FAILED; } - context->accessee.appPublicKey = jsonData[DM_TAG_APP_PUBLICK_KEY].get(); - context->accessee.appCredentialId = jsonData[DM_TAG_APP_CREDENTIAL_ID].get(); - context->accessee.deviceId = jsonData[DM_TAG_DEVICE_ID].get(); // 解析deviceId - context->accessee.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].get(); // 解析userId - context->accessee.tokenId = jsonData[DM_TAG_TOKEN_ID].get(); // 解析tokenId + context->accessee.appPublicKey = jsonData[DM_TAG_APP_PUBLICK_KEY].Get(); + context->accessee.appCredentialId = jsonData[DM_TAG_APP_CREDENTIAL_ID].Get(); + context->accessee.deviceId = jsonData[DM_TAG_DEVICE_ID].Get(); // 解析deviceId + context->accessee.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].Get(); // 解析userId + context->accessee.tokenId = jsonData[DM_TAG_TOKEN_ID].Get(); // 解析tokenId context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; @@ -372,7 +372,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const nlohmann::json std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::shared_ptr context) { LOGI("DmAuthMessageProcessor::CreateMessage start. msgType is %{public}d", msgType); - nlohmann::json jsonObj; + JsonObject jsonObj; jsonObj[TAG_MSG_TYPE] = msgType; switch (msgType) { case MSG_TYPE_REQ_ACL_NEGOTIATE: @@ -431,13 +431,15 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh break; } // TODO:调试信息,上库前删除 - LOGI("DmAuthMessageProcessor::CreateMessage %{public}s", SafetyDump(jsonObj).c_str()); - return SafetyDump(jsonObj); + LOGI("DmAuthMessageProcessor::CreateMessage %{public}s", jsonObj.Dump().c_str()); + + return jsonObj.Dump(); } // 内部各类报文的实现 // 161 170 171消息构造 -int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr &context, nlohmann::json &jsonObject) +int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr &context, + JsonObject &jsonObject) { std::string encryptMsg; jsonObject[DM_TAG_DATA] = context->transmitData; @@ -445,7 +447,7 @@ int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr } // 创建80报文 -void DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, nlohmann::json &jsonObject) +void DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject) { jsonObject[TAG_AUTH_TYPE] = context->authType; jsonObject[TAG_SESSION_NAME] = context->sessionName; @@ -471,7 +473,7 @@ void DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, - nlohmann::json &jsonObject) + JsonObject &jsonObject) { jsonObject[TAG_DEVICE_VERSION] = context->accessee.dmVersion; jsonObject[TAG_DEVICE_NAME] = context->accessee.deviceName; @@ -494,9 +496,9 @@ void DmAuthMessageProcessor::CreateRespNegotiateMessage(std::shared_ptr context, - nlohmann::json &jsonObject) + JsonObject &jsonObject) { - nlohmann::json jsonData; + JsonObject jsonData; if (!context->isOnline) { jsonData[DM_TAG_USER_PUBLICK_KEY] = context->accesser.userPublicKey; } @@ -505,7 +507,7 @@ void DmAuthMessageProcessor::CreateMessageReqCredExchange(std::shared_ptraccesser.userId; jsonData[DM_TAG_TOKEN_ID] = context->accesser.tokenId; - std::string plainText = SafetyDump(jsonData); + std::string plainText = jsonData.Dump(); std::string cipherText; cryptoMgr_->EncryptMessage(plainText, cipherText); jsonObject[DM_TAG_DATA] = cipherText; @@ -513,10 +515,10 @@ void DmAuthMessageProcessor::CreateMessageReqCredExchange(std::shared_ptr context, - nlohmann::json &jsonObject) + JsonObject &jsonObject) { LOGI("DmAuthMessageProcessor::CreateMessageRspCredExchange start."); - nlohmann::json jsonData; + JsonObject jsonData; if (!context->isOnline) { jsonData[DM_TAG_USER_PUBLICK_KEY] = context->accessee.userPublicKey; jsonData[DM_TAG_USER_CREDENTIAL_ID] = context->accessee.userCredentialId; @@ -527,7 +529,7 @@ void DmAuthMessageProcessor::CreateMessageRspCredExchange(std::shared_ptraccessee.userId; // 本端userId jsonData[DM_TAG_TOKEN_ID] = context->accessee.tokenId; // 本端tokenId - std::string plainText = SafetyDump(jsonData); + std::string plainText = jsonData.Dump(); std::string cipherText; LOGI("DmAuthMessageProcessor::CreateMessageRspCredExchange plainText=%{public}s", plainText.c_str()); cryptoMgr_->EncryptMessage(plainText, cipherText); @@ -536,11 +538,11 @@ void DmAuthMessageProcessor::CreateMessageRspCredExchange(std::shared_ptr context, - nlohmann::json &jsonObject) + JsonObject &jsonObject) { std::string onTransmitData; - nlohmann::json jsonData; + JsonObject jsonData; jsonObject[DM_TAG_DATA] = context->transmitData; if (!context->isAppCredentialVerified) { // 应用级凭据认证 jsonObject[DM_TAG_APP_CREDENTIAL_ID] = context->accesser.appCredentialId; @@ -565,7 +567,7 @@ std::string DmAuthMessageProcessor::ChecksumAcl(DistributedDeviceProfile::Access // 创建190报文 void DmAuthMessageProcessor::CreateMessageSyncResp(std::shared_ptr context, - nlohmann::json &jsonObject) + JsonObject &jsonObject) { DmAccess access; // 代表本端的access if (context->direction == DM_AUTH_SINK) { @@ -586,7 +588,7 @@ void DmAuthMessageProcessor::CreateMessageSyncResp(std::shared_ptr context, - nlohmann::json &jsonObject) + JsonObject &jsonObject) { jsonObject[DM_TAG_REPLY] = context->reply; jsonObject[DM_TAG_STATE] = context->state; @@ -595,35 +597,35 @@ void DmAuthMessageProcessor::CreateMessageFinish(std::shared_ptr } int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr &context, - DmAccess &access, nlohmann::json jsonObject) + DmAccess &access, JsonObject jsonObject) { - if (!IsString(jsonObject, DM_TAG_USER_SK_ID)) { + if (!jsonObject[DM_TAG_USER_SK_ID].IsString()) { LOGE("ParseSyncMessage DM_TAG_USER_SK_ID error"); return ERR_DM_FAILED; } - context->userSessionKeyId = std::atoi(jsonObject[DM_TAG_USER_SK_ID].get().c_str()); - if (!IsString(jsonObject, DM_TAG_USER_SK_TIMESTAMP)) { + context->userSessionKeyId = std::atoi(jsonObject[DM_TAG_USER_SK_ID].Get().c_str()); + if (!jsonObject[DM_TAG_USER_SK_TIMESTAMP].IsString()) { LOGE("ParseSyncMessage DM_TAG_USER_SK_TIMESTAMP error"); return ERR_DM_FAILED; } - context->userSkTimeStamp = std::atoi(jsonObject[DM_TAG_USER_SK_TIMESTAMP].get().c_str()); - if (!IsString(jsonObject, DM_TAG_DMVERSION)) { + context->userSkTimeStamp = std::atoi(jsonObject[DM_TAG_USER_SK_TIMESTAMP].Get().c_str()); + if (!jsonObject[DM_TAG_DMVERSION].IsString()) { LOGE("ParseSyncMessage DM_TAG_DMVERSION error"); return ERR_DM_FAILED; } - access.dmVersion = jsonObject[DM_TAG_DMVERSION].get(); - if (!IsString(jsonObject, DM_TAG_ACCESS)) { // 再解析一次 + access.dmVersion = jsonObject[DM_TAG_DMVERSION].Get(); + if (!jsonObject[DM_TAG_ACCESS].IsString()) { // 再解析一次 LOGE("ParseSyncMessage DM_TAG_ACCESS error"); return ERR_DM_FAILED; } - std::string srcAccessStr = jsonObject[DM_TAG_ACCESS].get(); + std::string srcAccessStr = jsonObject[DM_TAG_ACCESS].Get(); // 解析到 access里面 - nlohmann::json accessjson = nlohmann::json::parse(srcAccessStr, nullptr, false); - if (jsonObject.is_discarded()) { + JsonObject accessjson(srcAccessStr); + if (jsonObject.Isdiscarded()) { LOGE("ParseSyncMessage srcAccessStr error"); return ERR_DM_FAILED; } - DmAccessToSync srcAccessToSync = accessjson; + DmAccessToSync srcAccessToSync = accessjson.Get(); access.deviceName = srcAccessToSync.deviceName; access.deviceId = srcAccessToSync.deviceId; access.userId = srcAccessToSync.userId; @@ -640,16 +642,16 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr access.userSessionKeyId = srcAccessToSync.sessionKeyId; access.userSkTimeStamp = srcAccessToSync.skTimeStamp; } - if (IsString(jsonObject, DM_TAG_PROXY)) { // 预留字段 - std::string proxyInfo = jsonObject[DM_TAG_PROXY].get(); + if (jsonObject[DM_TAG_PROXY].IsString();) { // 预留字段 + std::string proxyInfo = jsonObject[DM_TAG_PROXY].Get(); } - if (IsArray(jsonObject, DM_TAG_ACL_CHECKSUM)) { // 再解析一次 acl + if (jsonObject[DM_TAG_ACL_CHECKSUM].IsArray();) { // 再解析一次 acl LOGE("ParseSyncMessage DM_TAG_ACL_CHECKSUM error"); return ERR_DM_FAILED; } - access.aclChecksumList = jsonObject[DM_TAG_ACL_CHECKSUM].get>(); - if (IsString(jsonObject, DM_TAG_SERVICEINFO)) { // sp 暂时没有传 - std::string serviceInfo = jsonObject[DM_TAG_SERVICEINFO].get(); + access.aclChecksumList = jsonObject[DM_TAG_ACL_CHECKSUM].Get>(); + if (jsonObject[DM_TAG_SERVICEINFO].IsString()) { // sp 暂时没有传 + std::string serviceInfo = jsonObject[DM_TAG_SERVICEINFO].Get(); } return DM_OK; } @@ -664,35 +666,35 @@ int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptr(); - if (!IsString(plainJson, DM_TAG_COMPRESS)) { + int32_t dataLen = plainJson[DM_TAG_COMPRESS_ORI_LEN].Get(); + if (!plainJson[DM_TAG_COMPRESS].IsString()) { LOGE("DecryptSyncMessage DM_TAG_COMPRESS_ORI_LEN json error"); return ERR_DM_FAILED; } - std::string compressMsg = plainJson[DM_TAG_COMPRESS].get(); + std::string compressMsg = plainJson[DM_TAG_COMPRESS].Get(); // 解压缩 std::string compressBase64 = Base64Decode(compressMsg); std::string syncMsg = DecompressSyncMsg(compressBase64, dataLen); // 解析字段 - nlohmann::json jsonObject = nlohmann::json::parse(syncMsg, nullptr, false); - if (jsonObject.is_discarded()) { + JsonObject jsonObject(syncMsg); + if (jsonObject.Isdiscarded()) { LOGE("DmAuthMessageProcessor::DecryptSyncMessage jsonStr error"); return ERR_DM_FAILED; } - if (IsString(jsonObject, DM_TAG_APP_SK_ID)) { - context->appSessionKeyId = std::atoi(jsonObject[DM_TAG_APP_SK_ID].get().c_str()); + if (jsonObject[DM_TAG_APP_SK_ID].IsString()) { + context->appSessionKeyId = std::atoi(jsonObject[DM_TAG_APP_SK_ID].Get().c_str()); } - if (IsString(jsonObject, DM_TAG_APP_SK_TIMESTAMP)) { - context->appSkTimeStamp = std::atoi(jsonObject[DM_TAG_APP_SK_TIMESTAMP].get().c_str()); + if (jsonObject[DM_TAG_APP_SK_TIMESTAMP].IsString()) { + context->appSkTimeStamp = std::atoi(jsonObject[DM_TAG_APP_SK_TIMESTAMP].Get().c_str()); } ret = ParseSyncMessage(context, access, jsonObject); if (ret != DM_OK) { @@ -703,15 +705,15 @@ int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptr context) { // 解析json中的加密数据 - if (!IsString(jsonObject, DM_TAG_SYNC)) { // 再解析一次 acl + if (!jsonObject[DM_TAG_SYNC].IsString()) { // 再解析一次 acl LOGE("ParseMessageSyncReq json error"); return ERR_DM_FAILED; } - std::string enSyncMsg = jsonObject[DM_TAG_SYNC].get(); + std::string enSyncMsg = jsonObject[DM_TAG_SYNC].Get(); // 解密数据 + 解析数据到context中 int32_t ret = DecryptSyncMessage(context, context->encryAccesser, enSyncMsg); if (ret != DM_OK) { @@ -723,15 +725,15 @@ int32_t DmAuthMessageProcessor::ParseMessageSyncReq(const nlohmann::json &jsonOb } // 解析 190报文信息 MSG_TYPE_RESP_DATA_SYNC 存放对方密文四元组,acl sp skid -int32_t DmAuthMessageProcessor::ParseMessageSyncResp(const nlohmann::json &jsonObject, +int32_t DmAuthMessageProcessor::ParseMessageSyncResp(const JsonObject &jsonObject, std::shared_ptr context) { // 解析json中的加密数据 - if (!IsString(jsonObject, DM_TAG_SYNC)) { // 再解析一次 acl + if (!jsonObject[DM_TAG_SYNC].IsString()) { // 再解析一次 acl LOGE("ParseMessageSyncResp json error"); return ERR_DM_FAILED; } - std::string enSyncMsg = jsonObject[DM_TAG_SYNC].get(); + std::string enSyncMsg = jsonObject[DM_TAG_SYNC].Get(); // 解密数据 + 解析数据到context中 int32_t ret = DecryptSyncMessage(context, context->encryAccessee, enSyncMsg); if (ret != DM_OK) { @@ -744,58 +746,61 @@ int32_t DmAuthMessageProcessor::ParseMessageSyncResp(const nlohmann::json &jsonO // 解析200报文 int32_t DmAuthMessageProcessor::ParseMessageFinish(std::shared_ptr context, - nlohmann::json &jsonObject) + JsonObject &jsonObject) { - if (IsInt32(jsonObject, DM_TAG_REPLY)) { - context->reply = jsonObject[DM_TAG_REPLY].get(); + if (jsonObject[DM_TAG_REPLY].IsNumberInteger()) { + context->reply = jsonObject[DM_TAG_REPLY].Get(); } - if (IsInt32(jsonObject, DM_TAG_STATE)) { - context->state = jsonObject[DM_TAG_STATE].get(); + if (jsonObject[DM_TAG_STATE].IsNumberInteger()) { + context->state = jsonObject[DM_TAG_STATE].Get(); } - if (IsInt32(jsonObject, DM_TAG_REASON)) { - context->reason = jsonObject[DM_TAG_REASON].get(); + if (jsonObject[DM_TAG_REASON].IsNumberInteger()) { + context->reason = jsonObject[DM_TAG_REASON].Get(); } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } -int32_t DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject, +int32_t DmAuthMessageProcessor::ParseNegotiateMessage(JsonObject &jsonObject, std::shared_ptr context) { - if (IsString(jsonObject, DM_TAG_DMVERSION)) { - context->accesser.dmVersion = jsonObject[DM_TAG_DMVERSION].get(); + if (jsonObject[DM_TAG_DMVERSION].IsString()) { + + context->accesser.dmVersion = jsonObject[DM_TAG_DMVERSION].Get(); } - if (IsString(jsonObject, DM_TAG_EDITION)) { - context->accesser.edition = jsonObject[DM_TAG_EDITION].get(); + if (jsonObject[DM_TAG_EDITION].IsString()) { + + context->accesser.edition = jsonObject[DM_TAG_EDITION].Get(); } - if (IsString(jsonObject, TAG_DEVICE_NAME)) { - context->accesser.deviceName = jsonObject[TAG_DEVICE_NAME].get(); + if (jsonObject[TAG_DEVICE_NAME].IsString()) { + + context->accesser.deviceName = jsonObject[TAG_DEVICE_NAME].Get(); } if (IsInt64(jsonObject, DM_TAG_TOKEN_ID)) { context->accesser.tokenId = static_cast(jsonObject[DM_TAG_TOKEN_ID].get()); } - if (IsString(jsonObject, TAG_DEVICE_ID_HASH)) { - context->accesser.deviceIdHash = jsonObject[TAG_DEVICE_ID_HASH].get(); + if (jsonObject[TAG_DEVICE_ID_HASH].IsString()) { + context->accesser.deviceIdHash = jsonObject[TAG_DEVICE_ID_HASH].Get(); } - if (IsString(jsonObject, TAG_USER_ID_HASH)) { - context->accesser.userIdHash = jsonObject[TAG_USER_ID_HASH].get(); + if (jsonObject[TAG_USER_ID_HASH].IsString()) { + context->accesser.userIdHash = jsonObject[TAG_USER_ID_HASH].Get(); } - if (IsString(jsonObject, TAG_ACCOUNT_ID_HASH)) { - context->accesser.accountIdHash = jsonObject[TAG_ACCOUNT_ID_HASH].get(); + if (jsonObject[TAG_ACCOUNT_ID_HASH].IsString()) { + context->accesser.accountIdHash = jsonObject[TAG_ACCOUNT_ID_HASH].Get(); } - if (IsString(jsonObject, TAG_TOKEN_ID_HASH)) { - context->accesser.tokenIdHash = jsonObject[TAG_TOKEN_ID_HASH].get(); + if (jsonObject[TAG_TOKEN_ID_HASH].IsString()) { + context->accesser.tokenIdHash = jsonObject[TAG_TOKEN_ID_HASH].Get(); } - if (IsString(jsonObject, TAG_BUNDLE_NAME)) { - context->accesser.bundleName = jsonObject[TAG_BUNDLE_NAME].get(); + if (jsonObject[TAG_BUNDLE_NAME].IsString()) { + context->accesser.bundleName = jsonObject[TAG_BUNDLE_NAME].Get(); } - if (IsString(jsonObject, TAG_PEER_BUNDLE_NAME)) { - context->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].get(); + if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString()) { + context->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); } - if (IsInt32(jsonObject, TAG_BIND_LEVEL)) { - context->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].get(); + if (jsonObject[TAG_BIND_LEVEL].IsNumberInteger()) { + context->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].Get(); } if (IsInt32(jsonObject, TAG_AUTH_TYPE)) { context->authType = static_cast(jsonObject[TAG_AUTH_TYPE].get()); @@ -804,7 +809,8 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject context->sessionName = jsonObject[TAG_SESSION_NAME].get(); } - if (jsonObject.contains(DM_TAG_EXTRA_INFO) && jsonObject[DM_TAG_EXTRA_INFO].is_object()) { + if (jsonObject.Contains(DM_TAG_EXTRA_INFO) && jsonObject[DM_TAG_EXTRA_INFO].IsObject()) { + ParseNegotiateExtraInfoMessage(jsonObject[DM_TAG_EXTRA_INFO], context); } @@ -812,47 +818,47 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(nlohmann::json &jsonObject return DM_OK; } -int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const nlohmann::json &jsonObject, +int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const JsonObject &jsonObject, std::shared_ptr context) { - if (IsString(jsonObject, TAG_DEVICE_VERSION)) { - context->accessee.dmVersion = jsonObject[TAG_DEVICE_VERSION].get(); + if (jsonObject[TAG_DEVICE_VERSION].IsString()) { + context->accessee.dmVersion = jsonObject[TAG_DEVICE_VERSION].Get(); } - if (IsString(jsonObject, TAG_DEVICE_NAME)) { - context->accessee.deviceName = jsonObject[TAG_DEVICE_NAME].get(); + if (jsonObject[TAG_DEVICE_NAME].IsString()) { + context->accessee.deviceName = jsonObject[TAG_DEVICE_NAME].Get(); } - if (IsString(jsonObject, TAG_DEVICE_ID_HASH)) { - context->accessee.deviceIdHash = jsonObject[TAG_DEVICE_ID_HASH].get(); + if (jsonObject[TAG_DEVICE_ID_HASH].IsString()) { + context->accessee.deviceIdHash = jsonObject[TAG_DEVICE_ID_HASH].Get(); } - if (IsString(jsonObject, TAG_USER_ID_HASH)) { - context->accessee.userIdHash = jsonObject[TAG_USER_ID_HASH].get(); + if (jsonObject[TAG_USER_ID_HASH].IsString()) { + context->accessee.userIdHash = jsonObject[TAG_USER_ID_HASH].Get(); } - if (IsString(jsonObject, TAG_ACCOUNT_ID_HASH)) { - context->accessee.accountIdHash = jsonObject[TAG_ACCOUNT_ID_HASH].get(); + if (jsonObject[TAG_ACCOUNT_ID_HASH].IsString()) { + context->accessee.accountIdHash = jsonObject[TAG_ACCOUNT_ID_HASH].Get(); } - if (IsString(jsonObject, TAG_TOKEN_ID_HASH)) { - context->accessee.tokenIdHash = jsonObject[TAG_TOKEN_ID_HASH].get(); + if (jsonObject[TAG_TOKEN_ID_HASH].IsString()) { + context->accessee.tokenIdHash = jsonObject[TAG_TOKEN_ID_HASH].Get(); } - if (IsString(jsonObject, TAG_BUNDLE_NAME)) { - context->accessee.bundleName = jsonObject[TAG_BUNDLE_NAME].get(); + if (jsonObject[TAG_BUNDLE_NAME].IsString()) { + context->accessee.bundleName = jsonObject[TAG_BUNDLE_NAME].Get(); } - if (IsBool(jsonObject, TAG_IS_ONLINE)) { - context->isOnline = jsonObject[TAG_IS_ONLINE].get(); + if (jsonObject[TAG_IS_ONLINE].IsBool()) { + context->isOnline = jsonObject[TAG_IS_ONLINE].Get(); } - if (IsBool(jsonObject, TAG_IS_AUTHED)) { - context->accessee.isAuthed = jsonObject[TAG_IS_AUTHED].get(); + if (jsonObject[TAG_IS_AUTHED].IsBool()) { + context->accessee.isAuthed = jsonObject[TAG_IS_AUTHED].Get(); } - if (IsString(jsonObject, TAG_CREDENTIAL_INFO)) { - context->accessee.credentialInfos = jsonObject[TAG_CREDENTIAL_INFO].get(); + if (jsonObject[TAG_CREDENTIAL_INFO].IsString()) { + context->accessee.credentialInfos = jsonObject[TAG_CREDENTIAL_INFO].Get(); } if (IsString(jsonObject, DM_TAG_AUTH_TYPE_LIST)) { @@ -869,18 +875,19 @@ int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const nlohmann::jso context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } -int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const nlohmann::json &json, + +int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const JsonObject &json, std::shared_ptr context) { - if (IsInt32(json, TAG_AUTH_TYPE)) { - context->authType = static_cast(json[TAG_AUTH_TYPE].get()); + if (json[TAG_AUTH_TYPE].IsNumberInteger()) { + context->authType = static_cast(json[TAG_AUTH_TYPE].Get()); } - if (IsInt32(json, TAG_DEVICE_TYPE)) { - context->accesser.deviceType = json[TAG_AUTH_TYPE].get(); + if (json[TAG_DEVICE_TYPE].IsNumberInteger()) { + context->accesser.deviceType = json[TAG_AUTH_TYPE].Get(); } - if (IsString(json, TAG_DEVICE_NAME)) { - context->accesser.deviceName = json[TAG_DEVICE_NAME].get(); + if (json[TAG_DEVICE_NAME].IsString()) { + context->accesser.deviceName = json[TAG_DEVICE_NAME].Get(); } if (IsUint32(json, DM_TAG_CURRENT_AUTH_TYPE_IDX)) { auto idx = json[DM_TAG_CURRENT_AUTH_TYPE_IDX].get(); @@ -899,20 +906,21 @@ int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const nlohmann::json return DM_OK; } -int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const nlohmann::json &json, +int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const JsonObject &json, std::shared_ptr context) { - if (IsInt32(json, DM_TAG_AUTH_RESULT)) { - context->authResult = static_cast(json[DM_TAG_AUTH_RESULT].get()); + if (json[DM_TAG_AUTH_RESULT].IsNumberInteger()) { + context->authResult = static_cast(json[DM_TAG_AUTH_RESULT].Get()); } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } -int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const nlohmann::json &json, + +int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const JsonObject &json, std::shared_ptr context) { - if (IsString(json, DM_TAG_DATA)) { - context->transmitData = json[DM_TAG_DATA].get(); + if (json[DM_TAG_DATA].IsString()) { + context->transmitData = json[DM_TAG_DATA].Get(); } if (IsUint32(json, DM_TAG_CURRENT_AUTH_TYPE_IDX)) { auto idx = json[DM_TAG_CURRENT_AUTH_TYPE_IDX].get(); @@ -929,26 +937,28 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const nlohmann::json context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } -int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthStart(const nlohmann::json &json, + +int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthStart(const JsonObject &json, std::shared_ptr context) { - if (IsString(json, DM_TAG_DATA)) { - context->transmitData = json[DM_TAG_DATA].get(); + if (json[DM_TAG_DATA].IsString()) { + context->transmitData = json[DM_TAG_DATA].Get(); } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } -int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate(const nlohmann::json &json, + +int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate(const JsonObject &json, std::shared_ptr context) { - if (IsString(json, DM_TAG_DATA)) { - context->transmitData = json[DM_TAG_DATA].get(); + if (json[DM_TAG_DATA].IsString()) { + context->transmitData = json[DM_TAG_DATA].Get(); } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } -void DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, nlohmann::json &json) +void DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json) { json[TAG_AUTH_TYPE] = context->authType; json[TAG_DEVICE_TYPE] = context->accesser.deviceType; @@ -956,30 +966,30 @@ void DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptrcurrentAuthTypeIdx; } -void DmAuthMessageProcessor::CreateMessageRespUserConfirm(std::shared_ptr context, nlohmann::json &json) +void DmAuthMessageProcessor::CreateMessageRespUserConfirm(std::shared_ptr context, JsonObject &json) { json[DM_TAG_AUTH_RESULT] = context->authResult; } -void DmAuthMessageProcessor::CreateMessageReqPinAuthStart(std::shared_ptr context, nlohmann::json &json) +void DmAuthMessageProcessor::CreateMessageReqPinAuthStart(std::shared_ptr context, JsonObject &json) { json[DM_TAG_DATA] = context->transmitData; json[DM_TAG_CURRENT_AUTH_TYPE_IDX] = context->currentAuthTypeIdx; } -void DmAuthMessageProcessor::CreateMessageRespPinAuthStart(std::shared_ptr context, nlohmann::json &json) +void DmAuthMessageProcessor::CreateMessageRespPinAuthStart(std::shared_ptr context, JsonObject &json) { json[DM_TAG_DATA] = context->transmitData; } void DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate(std::shared_ptr context, - nlohmann::json &json) + JsonObject &json) { json[DM_TAG_DATA] = context->transmitData; } void DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate(std::shared_ptr context, - nlohmann::json &json) + JsonObject &json) { json[DM_TAG_DATA] = context->transmitData; } @@ -1043,7 +1053,6 @@ std::string DmAuthMessageProcessor::Base64Encode(std::string &inputStr) return std::string(reinterpret_cast(buffer.data()), encodedLen); // 无需终止符 } - std::string DmAuthMessageProcessor::Base64Decode(std::string &inputStr) { // 输入字符串转二进制 @@ -1069,7 +1078,7 @@ std::string DmAuthMessageProcessor::Base64Decode(std::string &inputStr) int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptr &context, DmAccess &accessSide, std::string &encSyncMsg) { - nlohmann::json syncMsgJson; // 完整的180/190 消息 未经压缩&加密 + JsonObject syncMsgJson; // 完整的180/190 消息 未经压缩&加密 DmAccessToSync accessToSync; accessToSync.deviceName = accessSide.deviceName; accessToSync.deviceId = accessSide.deviceId; @@ -1093,9 +1102,9 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptruserSkTimeStamp); } - nlohmann::json accessJsonObj = accessToSync; // 直接使用宏构造 access json + JsonObject accessJsonObj = accessToSync; // 直接使用宏构造 access json syncMsgJson[DM_TAG_DMVERSION] = accessSide.dmVersion; - syncMsgJson[DM_TAG_ACCESS] = SafetyDump(accessJsonObj); // 接收端需要再拆一次json + syncMsgJson[DM_TAG_ACCESS] = accessJsonObj.Dump(); // 接收端需要再拆一次json syncMsgJson[DM_TAG_PROXY] = ""; // 预留字段 留空即可 std::string aclHashList; int32_t ret = GetAclListStr(context, aclHashList); @@ -1105,18 +1114,18 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptrEncryptMessage(SafetyDump(plainJson), encSyncMsg); + return cryptoMgr_->EncryptMessage(plainJson.Dump(), encSyncMsg); } int32_t DmAuthMessageProcessor::ACLToStr(DistributedDeviceProfile::AccessControlProfile acl, std::string aclStr) @@ -1135,8 +1144,8 @@ int32_t DmAuthMessageProcessor::ACLToStr(DistributedDeviceProfile::AccessControl dmAcl.validPeriod = acl.GetValidPeriod(); dmAcl.lastAuthTime = acl.GetLastAuthTime(); dmAcl.bindLevel = acl.GetBindType(); - nlohmann::json aclJsonObj = dmAcl; - aclStr = SafetyDump(aclJsonObj); + JsonObject aclJsonObj = dmAcl; + aclStr = aclJsonObj.Dump(); if (aclStr.empty()) { LOGE("DmAuthMessageProcessor::ACLToStr normalized acl failed"); return ERR_DM_FAILED; @@ -1146,7 +1155,7 @@ int32_t DmAuthMessageProcessor::ACLToStr(DistributedDeviceProfile::AccessControl std::string DmAuthMessageProcessor::AccesserToStr(DistributedDeviceProfile::AccessControlProfile acl) { - nlohmann::json jsonAccesserObj; + JsonObject jsonAccesserObj; DistributedDeviceProfile::Accesser accesser = acl.GetAccesser(); jsonAccesserObj[DM_TAG_ACCESSER_DEVICE_ID] = accesser.GetAccesserDeviceId(); jsonAccesserObj[DM_TAG_ACCESSER_USER_ID] = accesser.GetAccesserUserId(); @@ -1160,12 +1169,12 @@ std::string DmAuthMessageProcessor::AccesserToStr(DistributedDeviceProfile::Acce jsonAccesserObj[DM_TAG_ACCESSER_STATUS] = accesser.GetAccesserStatus(); jsonAccesserObj[DM_TAG_ACCESSER_SK_ID] = accesser.GetAccesserSessionKeyId(); jsonAccesserObj[DM_TAG_ACCESSER_SK_TIMESTAMP] = accesser.GetAccesserSKTimeStamp(); - return SafetyDump(jsonAccesserObj); + return jsonAccesserObj.Dump(); } std::string DmAuthMessageProcessor::AccesseeToStr(DistributedDeviceProfile::AccessControlProfile acl) { - nlohmann::json jsonAccesseeObj; + JsonObject jsonAccesseeObj; DistributedDeviceProfile::Accessee accessee = acl.GetAccessee(); jsonAccesseeObj[DM_TAG_ACCESSEE_DEVICE_ID] = accessee.GetAccesseeDeviceId(); jsonAccesseeObj[DM_TAG_ACCESSEE_USER_ID] = accessee.GetAccesseeUserId(); @@ -1179,10 +1188,10 @@ std::string DmAuthMessageProcessor::AccesseeToStr(DistributedDeviceProfile::Acce jsonAccesseeObj[DM_TAG_ACCESSEE_STATUS] = accessee.GetAccesseeStatus(); jsonAccesseeObj[DM_TAG_ACCESSEE_SK_ID] = accessee.GetAccesseeSessionKeyId(); jsonAccesseeObj[DM_TAG_ACCESSEE_SK_TIMESTAMP] = accessee.GetAccesseeSKTimeStamp(); - return SafetyDump(jsonAccesseeObj); + return jsonAccesseeObj.Dump(); } -int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr &context, nlohmann::json &jsonObject) +int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr &context, JsonObject &jsonObject) { DmAccess accessSide; // 代表本端的access if (context->direction == DM_AUTH_SOURCE) { @@ -1201,10 +1210,10 @@ int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr } // 解析transmit和PSKID 解析160 -int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(nlohmann::json &jsonObject, std::shared_ptr &context) +int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(JsonObject &jsonObject, std::shared_ptr &context) { - if (jsonObject.is_discarded() || !jsonObject.contains(DM_TAG_DATA) || - !jsonObject[DM_TAG_DATA].is_string()) { + if (jsonObject.Isdiscarded() || !jsonObject.Contains(DM_TAG_DATA) || + !jsonObject[DM_TAG_DATA].IsString()) { LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae Unlegal json string failed"); return ERR_DM_FAILED; } @@ -1213,16 +1222,16 @@ int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(nlohmann::json &jsonObject std::string jsonTag; if (context->isOnline == false && context->isAppCredentialVerified == false) { // 首次认证的应用凭据 jsonTag = DM_TAG_APP_CREDENTIAL_ID; - context->accesser.appCredentialId = jsonObject[DM_TAG_APP_CREDENTIAL_ID].get(); + context->accesser.appCredentialId = jsonObject[DM_TAG_APP_CREDENTIAL_ID].Get(); } else if (context->isOnline == false) { // 首次认证的用户凭据 jsonTag = DM_TAG_USER_CREDENTIAL_ID; - context->accesser.userCredentialId = jsonObject[DM_TAG_USER_CREDENTIAL_ID].get(); + context->accesser.userCredentialId = jsonObject[DM_TAG_USER_CREDENTIAL_ID].Get(); } else { // 非首次认证的应用凭据 jsonTag = DM_TAG_APP_CREDENTIAL_ID; - context->accesser.appCredentialId = jsonObject[DM_TAG_APP_CREDENTIAL_ID].get(); + context->accesser.appCredentialId = jsonObject[DM_TAG_APP_CREDENTIAL_ID].Get(); } - if (!jsonObject.contains(jsonTag) || !jsonObject[jsonTag].is_string()) { + if (!jsonObject.Contains(jsonTag) || !jsonObject[jsonTag].IsString()) { LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae Unlegal json CRED ID"); return ERR_DM_FAILED; } @@ -1233,7 +1242,7 @@ int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(nlohmann::json &jsonObject int32_t DmAuthMessageProcessor::GetAclListStr(std::shared_ptr &context, std::string &aclList) { - nlohmann::json jsonAclListObj; + JsonObject jsonAclListObj; jsonAclListObj[DM_TAG_DMVERSION] = context->accesser.dmVersion; // 在80/90 流程会协商出双方均兼容的版本号,此处取accesser的ver即可 // 查询ACL @@ -1265,7 +1274,7 @@ int32_t DmAuthMessageProcessor::GetAclListStr(std::shared_ptr &co jsonAclListObj[DM_TAG_ACCESSER] = accceserStrList; jsonAclListObj[DM_TAG_ACCESSEE] = accceseeStrList; - aclList = SafetyDump(jsonAclListObj); + aclList = jsonAclListObj.Dump(); return DM_OK; } -- Gitee From de004dd76553c52f82e737b86c5389cba57fb190 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Thu, 13 Mar 2025 15:56:13 +0800 Subject: [PATCH 217/382] =?UTF-8?q?fix=EF=BC=9Ajson=5Freplace=20tmp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/auth_manager.h | 2 +- .../dm_auth_message_processor.h | 2 +- .../auth_stages/auth_credential.cpp | 3 +- .../dm_auth_message_processor.cpp | 68 +++++++++---------- 4 files changed, 38 insertions(+), 37 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 2d17b0978..d66466d0b 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -17,7 +17,7 @@ #define OHOS_DM_AUTH_MANAGER_V2_H #include -#include "json_ojbect.h" +#include "json_object.h" #include "hichain_auth_connector.h" #include "hichain_connector.h" #include "softbus_connector.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 index 33b096a4c..410a814a5 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -281,7 +281,7 @@ private: int32_t DecryptSyncMessage(std::shared_ptr &context, DmAccess &access, std::string &enSyncMsg); int32_t ParseSyncMessage(std::shared_ptr &context, - DmAccess &access, JsonObject jsonObject); + DmAccess &access, JsonObject &jsonObject); // DP中accesser_table记录转string std::string AccesserToStr(DistributedDeviceProfile::AccessControlProfile acl); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 15e6ff43d..e92a99eed 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -274,8 +274,9 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori } jsonObj[DM_TAG_AUTHORIZED_SCOPE] = authorizedScope; // 用户级或者应用级 if (authorizedScope == DM_AUTH_SCOPE_APP) { - jsonObj[DM_TAG_AUTHRIZED_APP_LIST] = {std::to_string(authContext->accesser.tokenId), + std::vector tokenIds = {std::to_string(authContext->accesser.tokenId), std::to_string(authContext->accessee.tokenId)}; + jsonObj[DM_TAG_AUTHRIZED_APP_LIST] = tokenIds; } jsonObj[DM_TAG_CREDENTIAL_OWNER] = DM_AUTH_CREDENTIAL_OWNER; // 调用方包名DM模块 diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 9744fa8ba..70d9005c1 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -54,7 +54,6 @@ void ParseNegotiateExtraInfoMessage(const JsonItemObject &jsonExtraObject, std:: { // accesser在extra中传输对端peerUserId和peerDisplayId时,从中获取userId if (jsonExtraObject[DM_TAG_ACCESSEE_USER_ID].IsNumberInteger()) { - context->accessee.userId = jsonExtraObject[DM_TAG_ACCESSEE_USER_ID].Get(); } else if (jsonExtraObject[DM_TAG_PEER_DISPLAY_ID].IsNumberInteger()) { context->accessee.displayId = jsonExtraObject[DM_TAG_PEER_DISPLAY_ID].Get(); @@ -163,7 +162,7 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont } JsonObject jsonObject(message); - if (jsonObject.Isdiscarded()) { + if (jsonObject.IsDiscarded()) { LOGE("DmAuthMessageProcessor::ParseMessage failed, decodeRequestAuth jsonStr error"); return ERR_DM_FAILED; } @@ -236,7 +235,7 @@ static std::string vectorToString(const std::vector& vec) { int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const JsonObject &jsonObject, std::shared_ptr &context, DmMessageType msgType) { - if (jsonObject.Isdiscarded() || !jsonObject.Contains(DM_TAG_DATA) || !jsonObject[DM_TAG_DATA].IsString()) { + if (jsonObject.IsDiscarded() || !jsonObject.Contains(DM_TAG_DATA) || !jsonObject[DM_TAG_DATA].IsString()) { LOGE("DmAuthMessageProcessor::ParseMessageNegotiateTransmit Unlegal json string failed"); return ERR_DM_FAILED; } @@ -264,7 +263,7 @@ int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const JsonObject & int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate(const JsonObject &jsonObject, std::shared_ptr context) { - if (jsonObject.Isdiscarded() || !jsonObject[DM_TAG_DATA].IsString()) { + if (jsonObject.IsDiscarded() || !jsonObject[DM_TAG_DATA].IsString()) { LOGE("DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate failed, decodeRequestAuth jsonStr error"); return ERR_DM_FAILED; } @@ -278,7 +277,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate(const JsonObjec int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const JsonObject &jsonObject, std::shared_ptr context) { - if (jsonObject.Isdiscarded() || !jsonObject[DM_TAG_DATA].IsString()) { + if (jsonObject.IsDiscarded() || !jsonObject[DM_TAG_DATA].IsString()) { LOGE("DecodeRequestAuth jsonStr error"); return ERR_DM_FAILED; } @@ -320,7 +319,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &js std::shared_ptr context) { LOGI("DmAuthMessageProcessor::ParseMessageRspCredExchange start."); - if (jsonObject.Isdiscarded() || !jsonObject[DM_TAG_DATA].IsString()) { + if (jsonObject.IsDiscarded() || !jsonObject[DM_TAG_DATA].IsString()) { LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange, DecodeRequestAuth jsonStr error"); return ERR_DM_FAILED; } @@ -345,7 +344,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &js return ERR_DM_FAILED; } context->accessee.userPublicKey = jsonData[DM_TAG_USER_PUBLICK_KEY].Get(); - context->accessee.userCredentialId = jsonData[DM_TAG_USER_CREDENTIAL_ID].get(); + context->accessee.userCredentialId = jsonData[DM_TAG_USER_CREDENTIAL_ID].Get(); } // 解析对方应用级公钥和协商应用级凭据Id @@ -465,8 +464,9 @@ void DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptraccessee.bundleName; jsonObject[TAG_BIND_LEVEL] = context->accesser.bindLevel; - jsonObject[DM_TAG_EXTRA_INFO] = nlohmann::json::object(); - CreateNegotiateExtraInfoMessage(context, jsonObject[DM_TAG_EXTRA_INFO]); + JsonObject jsonExtraObject; + CreateNegotiateExtraInfoMessage(context, jsonExtraObject); + jsonObject.Insert(DM_TAG_EXTRA_INFO, jsonExtraObject); return; } @@ -597,7 +597,7 @@ void DmAuthMessageProcessor::CreateMessageFinish(std::shared_ptr } int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr &context, - DmAccess &access, JsonObject jsonObject) + DmAccess &access, JsonObject &jsonObject) { if (!jsonObject[DM_TAG_USER_SK_ID].IsString()) { LOGE("ParseSyncMessage DM_TAG_USER_SK_ID error"); @@ -621,7 +621,7 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr std::string srcAccessStr = jsonObject[DM_TAG_ACCESS].Get(); // 解析到 access里面 JsonObject accessjson(srcAccessStr); - if (jsonObject.Isdiscarded()) { + if (jsonObject.IsDiscarded()) { LOGE("ParseSyncMessage srcAccessStr error"); return ERR_DM_FAILED; } @@ -642,10 +642,10 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr access.userSessionKeyId = srcAccessToSync.sessionKeyId; access.userSkTimeStamp = srcAccessToSync.skTimeStamp; } - if (jsonObject[DM_TAG_PROXY].IsString();) { // 预留字段 + if (jsonObject[DM_TAG_PROXY].IsString()) { // 预留字段 std::string proxyInfo = jsonObject[DM_TAG_PROXY].Get(); } - if (jsonObject[DM_TAG_ACL_CHECKSUM].IsArray();) { // 再解析一次 acl + if (jsonObject[DM_TAG_ACL_CHECKSUM].IsArray()) { // 再解析一次 acl LOGE("ParseSyncMessage DM_TAG_ACL_CHECKSUM error"); return ERR_DM_FAILED; } @@ -667,7 +667,7 @@ int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptraccesser.bindLevel = jsonObject[TAG_BIND_LEVEL].Get(); } - if (IsInt32(jsonObject, TAG_AUTH_TYPE)) { - context->authType = static_cast(jsonObject[TAG_AUTH_TYPE].get()); + if (jsonObject[TAG_AUTH_TYPE].IsNumberInteger()) { + context->authType = static_cast(jsonObject[TAG_AUTH_TYPE].Get()); } if (IsString(jsonObject, TAG_SESSION_NAME)) { context->sessionName = jsonObject[TAG_SESSION_NAME].get(); } if (jsonObject.Contains(DM_TAG_EXTRA_INFO) && jsonObject[DM_TAG_EXTRA_INFO].IsObject()) { - ParseNegotiateExtraInfoMessage(jsonObject[DM_TAG_EXTRA_INFO], context); } @@ -849,11 +848,11 @@ int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const JsonObject &j context->accessee.bundleName = jsonObject[TAG_BUNDLE_NAME].Get(); } - if (jsonObject[TAG_IS_ONLINE].IsBool()) { + if (jsonObject[TAG_IS_ONLINE].IsBoolean()) { context->isOnline = jsonObject[TAG_IS_ONLINE].Get(); } - if (jsonObject[TAG_IS_AUTHED].IsBool()) { + if (jsonObject[TAG_IS_AUTHED].IsBoolean()) { context->accessee.isAuthed = jsonObject[TAG_IS_AUTHED].Get(); } @@ -861,15 +860,16 @@ int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const JsonObject &j context->accessee.credentialInfos = jsonObject[TAG_CREDENTIAL_INFO].Get(); } - if (IsString(jsonObject, DM_TAG_AUTH_TYPE_LIST)) { - auto strList = jsonObject[DM_TAG_AUTH_TYPE_LIST].get(); + if (jsonObject[DM_TAG_AUTH_TYPE_LIST].IsString()) { + auto strList = jsonObject[DM_TAG_AUTH_TYPE_LIST].Get(); context->authTypeList = stringToVector(strList); } - if (IsInt64(jsonObject, TAG_REQUEST_ID)) { - context->requestId = jsonObject[TAG_REQUEST_ID].get(); + if (jsonObject[TAG_REQUEST_ID].IsNumberInteger()) { + + context->requestId = jsonObject[TAG_REQUEST_ID].Get(); } - if (IsInt32(jsonObject, DM_TAG_AUTH_RESULT)) { - context->authResult = static_cast(jsonObject[DM_TAG_AUTH_RESULT].get()); + if (jsonObject[DM_TAG_AUTH_RESULT].IsNumberInteger()) { + context->authResult = static_cast(jsonObject[DM_TAG_AUTH_RESULT].Get()); } context->authStateMachine->TransitionTo(std::make_shared()); @@ -889,8 +889,8 @@ int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const JsonObject &jso if (json[TAG_DEVICE_NAME].IsString()) { context->accesser.deviceName = json[TAG_DEVICE_NAME].Get(); } - if (IsUint32(json, DM_TAG_CURRENT_AUTH_TYPE_IDX)) { - auto idx = json[DM_TAG_CURRENT_AUTH_TYPE_IDX].get(); + if (json[DM_TAG_CURRENT_AUTH_TYPE_IDX].IsNumberInteger()) { + auto idx = json[DM_TAG_CURRENT_AUTH_TYPE_IDX].Get(); if (idx < context->authTypeList.size()) { context->currentAuthTypeIdx = idx; context->authType = context->authTypeList[idx]; @@ -922,8 +922,8 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const JsonObject &js if (json[DM_TAG_DATA].IsString()) { context->transmitData = json[DM_TAG_DATA].Get(); } - if (IsUint32(json, DM_TAG_CURRENT_AUTH_TYPE_IDX)) { - auto idx = json[DM_TAG_CURRENT_AUTH_TYPE_IDX].get(); + if (json[DM_TAG_CURRENT_AUTH_TYPE_IDX].IsNumberInteger()) { + auto idx = json[DM_TAG_CURRENT_AUTH_TYPE_IDX].Get(); if (idx < context->authTypeList.size()) { context->currentAuthTypeIdx = idx; context->authType = context->authTypeList[idx]; @@ -1161,7 +1161,7 @@ std::string DmAuthMessageProcessor::AccesserToStr(DistributedDeviceProfile::Acce jsonAccesserObj[DM_TAG_ACCESSER_USER_ID] = accesser.GetAccesserUserId(); jsonAccesserObj[DM_TAG_ACCESSER_ACOUNT_ID] = accesser.GetAccesserAccountId(); jsonAccesserObj[DM_TAG_ACCESSER_TOKEN_ID] = accesser.GetAccesserTokenId(); - jsonAccesserObj[DM_TAG_ACCESSER_SERVICE_NAME] = {}; // 预留字段 DP库未适配 + jsonAccesserObj[DM_TAG_ACCESSER_SERVICE_NAME] = std::vector(); // 预留字段 DP库未适配 jsonAccesserObj[DM_TAG_ACCESSER_BUNDLE_NAME] = accesser.GetAccesserBundleName(); jsonAccesserObj[DM_TAG_ACCESSER_HAP_SIGNATURE] = accesser.GetAccesserHapSignature(); jsonAccesserObj[DM_TAG_ACCESSER_BIND_LEVEL] = accesser.GetAccesserBindLevel(); @@ -1180,7 +1180,7 @@ std::string DmAuthMessageProcessor::AccesseeToStr(DistributedDeviceProfile::Acce jsonAccesseeObj[DM_TAG_ACCESSEE_USER_ID] = accessee.GetAccesseeUserId(); jsonAccesseeObj[DM_TAG_ACCESSEE_ACOUNT_ID] = accessee.GetAccesseeAccountId(); jsonAccesseeObj[DM_TAG_ACCESSEE_TOKEN_ID] = accessee.GetAccesseeTokenId(); - jsonAccesseeObj[DM_TAG_ACCESSEE_SERVICE_NAME] = {}; // 预留字段 DP库未适配 + jsonAccesseeObj[DM_TAG_ACCESSEE_SERVICE_NAME] = std::vector(); // 预留字段 DP库未适配 jsonAccesseeObj[DM_TAG_ACCESSEE_BUNDLE_NAME] = accessee.GetAccesseeBundleName(); jsonAccesseeObj[DM_TAG_ACCESSEE_HAP_SIGNATURE] = accessee.GetAccesseeHapSignature(); jsonAccesseeObj[DM_TAG_ACCESSEE_BIND_LEVEL] = accessee.GetAccesseeBindLevel(); @@ -1212,12 +1212,12 @@ int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr // 解析transmit和PSKID 解析160 int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(JsonObject &jsonObject, std::shared_ptr &context) { - if (jsonObject.Isdiscarded() || !jsonObject.Contains(DM_TAG_DATA) || + if (jsonObject.IsDiscarded() || !jsonObject.Contains(DM_TAG_DATA) || !jsonObject[DM_TAG_DATA].IsString()) { LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae Unlegal json string failed"); return ERR_DM_FAILED; } - context->transmitData = jsonObject[DM_TAG_DATA].get(); + context->transmitData = jsonObject[DM_TAG_DATA].Get(); std::string jsonTag; if (context->isOnline == false && context->isAppCredentialVerified == false) { // 首次认证的应用凭据 -- Gitee From db53945433e1b5f0f65956a05892a3a9960279ea Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Thu, 13 Mar 2025 19:29:55 +0800 Subject: [PATCH 218/382] =?UTF-8?q?fix=EF=BC=9Ajson=E6=9B=BF=E6=8D=A2=20hi?= =?UTF-8?q?chain=E9=80=82=E9=85=8D=E6=8E=A5=E5=8F=A3=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/auth_manager.h | 6 +- .../dm_auth_message_processor.h | 7 ++ .../include/authentication_v2/dm_auth_state.h | 2 +- .../src/authentication_v2/auth_manager.cpp | 10 +- .../auth_stages/auth_negotiate.cpp | 25 +++-- .../dm_auth_message_processor.cpp | 104 ++++++++++++++++++ .../hichain/hichain_auth_connector.cpp | 29 ++--- 7 files changed, 149 insertions(+), 34 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index d66466d0b..da3cddb8f 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -155,11 +155,11 @@ protected: 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(JsonObject jsonObject); - void ParseJsonObject(JsonObject jsonObject); + 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(JsonObject &jsonObject); + std::string GetBundleName(const JsonObject &jsonObject); int32_t GetBindLevel(int32_t bindLevel); void SetAuthType(int32_t authType); bool IsAuthTypeSupported(const int32_t &authType); diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 410a814a5..c8bebde92 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -177,6 +177,13 @@ struct DmAccessToSync { int64_t skTimeStamp; // 老化,时间为2天 用户级凭据时间戳 }; +// json和结构体转换函数 +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: DmAuthMessageProcessor(); diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 8b1ef4f0d..583d702f4 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -333,7 +333,7 @@ public: private: int32_t RespQueryAcceseeIds(std::shared_ptr context); bool HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList); - uint32_t GetCredentialType(std::shared_ptr context, JsonObject credInfo); + uint32_t GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo); bool AclCompareTwoIds(std::shared_ptr context, const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); bool AclCompareFourIds(std::shared_ptr context, diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index d1108f578..e6df96536 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -458,7 +458,7 @@ int32_t AuthManager::CheckAuthParamVaild(const std::string &sessionName, int32_t return DM_OK; } -void AuthManager::ParseHmlInfoInJsonObject(JsonObject jsonObject) +void AuthManager::ParseHmlInfoInJsonObject(const JsonObject &jsonObject) { if (jsonObject[PARAM_KEY_CONN_SESSIONTYPE].IsString()) { context_->connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get(); @@ -468,7 +468,7 @@ void AuthManager::ParseHmlInfoInJsonObject(JsonObject jsonObject) return; } context_->connDelayCloseTime = HML_SESSION_TIMEOUT; - if (jsonObject[PARAM_KEY_HML_ENABLE_160M].IsBool()) { + if (jsonObject[PARAM_KEY_HML_ENABLE_160M].IsBoolean()) { context_->hmlEnable160M = jsonObject[PARAM_KEY_HML_ENABLE_160M].Get(); LOGI("hmlEnable160M %{public}d", context_->hmlEnable160M); } @@ -483,7 +483,7 @@ void AuthManager::ParseHmlInfoInJsonObject(JsonObject jsonObject) return; } -std::string AuthManager::GetBundleName(JsonObject &jsonObject) +std::string AuthManager::GetBundleName(const JsonObject &jsonObject) { if (!jsonObject.IsDiscarded() && jsonObject[BUNDLE_NAME_KEY].IsString()) { return jsonObject[BUNDLE_NAME_KEY].Get(); @@ -494,7 +494,7 @@ std::string AuthManager::GetBundleName(JsonObject &jsonObject) return bundleName; } -void AuthManager::ParseJsonObject(JsonObject jsonObject) +void AuthManager::ParseJsonObject(const JsonObject &jsonObject) { if (jsonObject.IsDiscarded()) { return; @@ -1102,7 +1102,7 @@ char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, c } } jsonObj[FIELD_SERVICE_PKG_NAME] = std::string(DM_PKG_NAME); - std::string jsonStr = SafetyDump(jsonObj); + std::string jsonStr = jsonObj.Dump(); char *buffer = strdup(jsonStr.c_str()); return buffer; } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 7c4012591..a7799405d 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -266,21 +266,25 @@ bool AuthSinkNegotiateStateMachine::HaveSameTokenId(std::shared_ptr context, JsonObject credInfo) +uint32_t AuthSinkNegotiateStateMachine::GetCredentialType(std::shared_ptr context, + const JsonItemObject &credInfo) { // 判断是否同账号 // TODO: 需要确定截断长度 if (Crypto::Sha256(context->accessee.accountId) == context->accesser.accountIdHash && context->accessee.accountId != "ohosAnonymousUid") { - if (credInfo[FILED_CRED_TYPE] == ACCOUNT_RELATED && credInfo[FILED_AUTHORIZED_SCOPE] == SCOPE_USER) { + if (credInfo[FILED_CRED_TYPE].Get() == ACCOUNT_RELATED && + credInfo[FILED_AUTHORIZED_SCOPE].Get() == SCOPE_USER) { return DM_IDENTICAL_ACCOUNT; } } else { - if (credInfo[FILED_CRED_TYPE] == ACCOUNT_ACROSS && credInfo[FILED_AUTHORIZED_SCOPE] == SCOPE_USER) { + if (credInfo[FILED_CRED_TYPE].Get() == ACCOUNT_ACROSS && + credInfo[FILED_AUTHORIZED_SCOPE].Get() == SCOPE_USER) { return DM_ACROSS_ACCOUNT; } - if (credInfo[FILED_CRED_TYPE] == ACCOUNT_UNRELATED && credInfo[FILED_AUTHORIZED_SCOPE] == SCOPE_APP && - HaveSameTokenId(context, credInfo[FILED_AUTHORIZED_APP_LIST]) == true) { + if (credInfo[FILED_CRED_TYPE].Get() == ACCOUNT_UNRELATED && + credInfo[FILED_AUTHORIZED_SCOPE].Get() == SCOPE_APP && + HaveSameTokenId(context, credInfo[FILED_AUTHORIZED_APP_LIST].Get>()) == true) { return DM_POINT_TO_POINT; } } @@ -374,12 +378,12 @@ int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptr(); if (credType == DM_IDENTICAL_ACCOUNT || credType == DM_ACROSS_ACCOUNT) { queryResult[credId]["isAclActive"] = AclCompareTwoIds(context, accesser, accessee); } else if (credType == DM_POINT_TO_POINT) { @@ -391,12 +395,11 @@ int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptr invalidCredIds; JsonObject packResult; // 需要打包发送到对端的数据 for (const auto &item : queryResult.Items()) { - credId = item.Key(); - JsonObject cred = item[credId]; - if (!cred.Contains("isAclActive") || cred["isAclActive"] == false) { + std::string credId = item.Key(); + if (!item[credId].Contains("isAclActive") || item[credId]["isAclActive"].Get() == false) { continue; } - packResult[credId] = cred[FILED_CRED_TYPE]; + packResult[credId] = item[credId][FILED_CRED_TYPE].Get>(); } context->accessee.isAuthed = isEmpty; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 70d9005c1..344548d3e 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1278,5 +1278,109 @@ int32_t DmAuthMessageProcessor::GetAclListStr(std::shared_ptr &co return DM_OK; } +void ToJson(JsonItemObject &itemObject, const DmAccessControlTable &table) +{ + itemObject["accessControlId"] = table.accessControlId; + itemObject["accesserId"] = table.accesserId; + itemObject["accesseeId"] = table.accesseeId; + itemObject["deviceId"] = table.deviceId; + itemObject["sessionKey"] = table.sessionKey; + itemObject["bindType"] = table.bindType; + itemObject["authType"] = table.authType; + itemObject["deviceType"] = table.deviceType; + itemObject["deviceIdHash"] = table.deviceIdHash; + itemObject["status"] = table.status; + itemObject["validPeriod"] = table.validPeriod; + itemObject["lastAuthTime"] = table.lastAuthTime; + itemObject["bindLevel"] = table.bindLevel; +} + +void FromJson(const JsonItemObject &itemObject, DmAccessControlTable &table) +{ + if (itemObject.Contains("accessControlId") && itemObject["accessControlId"].IsNumberInteger()) { + table.accessControlId = itemObject["accessControlId"].Get(); + } + if (itemObject.Contains("accesserId") && itemObject["accesserId"].IsNumberInteger()) { + table.accesserId = itemObject["accesserId"].Get(); + } + if (itemObject.Contains("accesseeId") && itemObject["accesseeId"].IsNumberInteger()) { + table.accesseeId = itemObject["accesseeId"].Get(); + } + if (itemObject.Contains("deviceId") && itemObject["deviceId"].IsString()) { + table.deviceId = itemObject["deviceId"].Get(); + } + if (itemObject.Contains("sessionKey") && itemObject["sessionKey"].IsString()) { + table.sessionKey = itemObject["sessionKey"].Get(); + } + if (itemObject.Contains("bindType") && itemObject["bindType"].IsNumberInteger()) { + table.bindType = itemObject["bindType"].Get(); + } + if (itemObject.Contains("authType") && itemObject["authType"].IsNumberInteger()) { + table.authType = itemObject["authType"].Get(); + } + if (itemObject.Contains("deviceType") && itemObject["deviceType"].IsNumberInteger()) { + table.deviceType = itemObject["deviceType"].Get(); + } + if (itemObject.Contains("deviceIdHash") && itemObject["deviceIdHash"].IsString()) { + table.deviceIdHash = itemObject["deviceIdHash"].Get(); + } + if (itemObject.Contains("status") && itemObject["status"].IsNumberInteger()) { + table.status = itemObject["status"].Get(); + } + if (itemObject.Contains("validPeriod") && itemObject["validPeriod"].IsNumberInteger()) { + table.validPeriod = itemObject["validPeriod"].Get(); + } + if (itemObject.Contains("lastAuthTime") && itemObject["lastAuthTime"].IsNumberInteger()) { + table.lastAuthTime = itemObject["lastAuthTime"].Get(); + } + if (itemObject.Contains("bindLevel") && itemObject["bindLevel"].IsNumberInteger()) { + table.bindLevel = itemObject["bindLevel"].Get(); + } +} + +void ToJson(JsonItemObject &itemObject, const DmAccessToSync &table) +{ + itemObject["deviceName"] = table.deviceName; + itemObject["deviceId"] = table.deviceId; + itemObject["userId"] = table.userId; + itemObject["accountId"] = table.accountId; + itemObject["tokenId"] = table.tokenId; + itemObject["bundleName"] = table.bundleName; + itemObject["bindLevel"] = table.bindLevel; + itemObject["sessionKeyId"] = table.sessionKeyId; + itemObject["skTimeStamp"] = table.skTimeStamp; +} + +void FromJson(const JsonItemObject &itemObject, DmAccessToSync &table) +{ + if (itemObject.Contains("deviceName") && itemObject["deviceName"].IsString()) { + table.deviceName = itemObject["deviceName"].Get(); + } + if (itemObject.Contains("deviceId") && itemObject["deviceId"].IsString()) { + table.deviceId = itemObject["deviceId"].Get(); + } + if (itemObject.Contains("userId") && itemObject["userId"].IsNumberInteger()) { + table.userId = itemObject["userId"].Get(); + } + if (itemObject.Contains("accountId") && itemObject["accountId"].IsString()) { + table.accountId = itemObject["accountId"].Get(); + } + if (itemObject.Contains("tokenId") && itemObject["tokenId"].IsNumberInteger()) { + table.tokenId = itemObject["tokenId"].Get(); + } + if (itemObject.Contains("bundleName") && itemObject["bundleName"].IsString()) { + table.bundleName = itemObject["bundleName"].Get(); + } + if (itemObject.Contains("bindLevel") && itemObject["bindLevel"].IsNumberInteger()) { + table.bindLevel = itemObject["bindLevel"].Get(); + } + if (itemObject.Contains("sessionKeyId") && itemObject["sessionKeyId"].IsNumberInteger()) { + table.sessionKeyId = itemObject["sessionKeyId"].Get(); + } + if (itemObject.Contains("skTimeStamp") && itemObject["skTimeStamp"].IsNumberInteger()) { + table.skTimeStamp = itemObject["skTimeStamp"].Get(); + } +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index bdb7fa049..d88dd9c9c 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -22,6 +22,7 @@ #include "hichain_connector_callback.h" #include "parameter.h" #include "cJSON.h" +#include "json_object.h" namespace OHOS { namespace DistributedHardware { @@ -151,9 +152,9 @@ int32_t HiChainAuthConnector::ExportCredential(int32_t osAccountId, const std::s } // 导出的公钥是json格式,需要解析 - nlohmann::json jsonAuthParam = nlohmann::json::parse(returnData, nullptr, false); + JsonObject jsonAuthParam(returnData); free(returnData); - if (jsonAuthParam.is_discarded() || !IsString(jsonAuthParam, "keyValue")) { + if (jsonAuthParam.IsDiscarded() || !jsonAuthParam["keyValue"].IsString()) { LOGE("Hichain exportCredential failed, returnData is invalid."); return ERR_DM_FAILED; } @@ -218,14 +219,14 @@ int32_t HiChainAuthConnector::AuthCredential(int32_t osAccountId, int64_t authRe } // 创建authParams的json格式字符串 - nlohmann::json jsonAuthParam; + JsonObject jsonAuthParam; if (!credId.empty()) { jsonAuthParam["credId"] = credId; } if (!pinCode.empty()) { jsonAuthParam["pinCode"] = pinCode; } - std::string authParams = SafetyDump(jsonAuthParam); + std::string authParams = jsonAuthParam.Dump(); // 凭据认证 const CredAuthManager *credAuthManager = GetCredAuthInstance(); @@ -248,12 +249,12 @@ int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t } // 创建authParams的json格式字符串 - nlohmann::json jsonAuthParam; + JsonObject jsonAuthParam; jsonAuthParam[FIELD_PIN_CODE] = std::to_string(pinCode); jsonAuthParam[FIELD_SERVICE_PKG_NAME] = std::string(DM_PKG_NAME); - std::string authParams = SafetyDump(jsonAuthParam); + std::string authParams = jsonAuthParam.Dump(); // 凭据认证 const CredAuthManager *credAuthManager = GetCredAuthInstance(); @@ -360,30 +361,30 @@ int32_t HiChainAuthConnector::GenerateCredential(std::string &localUdid, int32_t return DM_OK; } -int32_t HiChainAuthConnector::QueryCredentialInfo(int32_t userId, nlohmann::json queryParams, - nlohmann::json &resultJson) +int32_t HiChainAuthConnector::QueryCredentialInfo(int32_t userId, JsonObject &queryParams, + JsonObject &resultJson) { int32_t ret; const CredManager *cm = GetCredMgrInstance(); char *credIdList = nullptr; // Q: 之前都是用的ProcessCredential查询,现在是否可用queryCredentialByParams查询? - ret = cm->queryCredentialByParams(userId, SafetyDump(queryParams).c_str(), + ret = cm->queryCredentialByParams(userId, queryParams.Dump().c_str(), &credIdList); // TODO: 可能是空的,要返回DM_OK if (ret != DM_OK) { LOGE("HiChainAuthConnector::QueryCredentialInfo fail to query credential id list."); return ERR_DM_FAILED; } - nlohmann::json credIdListJson = nlohmann::json::parse(credIdList, nullptr, false); + JsonObject credIdListJson(credIdList); FreeJsonString(credIdList); - if (credIdListJson.is_discarded()) { + if (credIdListJson.IsDiscarded()) { LOGE("HiChainAuthConnector::QueryCredentialInfo credential id list to jsonStr error"); return ERR_DM_FAILED; } for (const auto& element : credIdListJson) { - if (!element.is_string()) { + if (!element.IsString()) { continue; } std::string credId = element.get(); @@ -394,9 +395,9 @@ int32_t HiChainAuthConnector::QueryCredentialInfo(int32_t userId, nlohmann::json LOGE("HiChainAuthConnector::QueryCredentialInfo fail to query credential info."); return ERR_DM_FAILED; } - nlohmann::json credInfoJson = nlohmann::json::parse(returnCredInfo, nullptr, false); + JsonObject credInfoJson(returnCredInfo); FreeJsonString(returnCredInfo); - if (credInfoJson.is_discarded()) { + if (credInfoJson.IsDiscarded()) { LOGE("HiChainAuthConnector::QueryCredentialInfo credential info jsonStr error"); return ERR_DM_FAILED; } -- Gitee From 7101c8b7798b4f19182d4cd8e7114190e2b20220 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Thu, 13 Mar 2025 19:36:41 +0800 Subject: [PATCH 219/382] =?UTF-8?q?fix=EF=BC=9Ahichain=20json=20tmp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/dependency/hichain/hichain_auth_connector.h | 3 ++- .../src/dependency/hichain/hichain_auth_connector.cpp | 1 - 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/include/dependency/hichain/hichain_auth_connector.h b/services/implementation/include/dependency/hichain/hichain_auth_connector.h index 306d000c6..cdf16d790 100644 --- a/services/implementation/include/dependency/hichain/hichain_auth_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_auth_connector.h @@ -21,6 +21,7 @@ #include "device_auth_defines.h" #include "hichain_connector_callback.h" #include "nlohmann/json.hpp" +#include "json_object.h" namespace OHOS { namespace DistributedHardware { @@ -53,7 +54,7 @@ public: int32_t ProcessAuthData(int64_t requestId, std::string authData, int32_t osAccountId); int32_t GenerateCredential(std::string &localUdid, int32_t osAccountId, std::string &publicKey); bool QueryCredential(std::string &localUdid, int32_t osAccountId); - int32_t QueryCredentialInfo(int32_t userId, nlohmann::json queryParams, nlohmann::json &resultJson); + int32_t QueryCredentialInfo(int32_t userId, const JsonObject &queryParams, JsonObject &resultJson); int32_t ImportCredential(int32_t osAccountId, std::string deviceId, std::string publicKey); int32_t DeleteCredential(const std::string &deviceId, int32_t userId); int32_t RegisterHiChainAuthCallback(std::shared_ptr callback); diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index d88dd9c9c..77c3cb754 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -22,7 +22,6 @@ #include "hichain_connector_callback.h" #include "parameter.h" #include "cJSON.h" -#include "json_object.h" namespace OHOS { namespace DistributedHardware { -- Gitee From 64b013fad1812f4642918a19b36832a7291b7f85 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Fri, 14 Mar 2025 10:05:45 +0800 Subject: [PATCH 220/382] =?UTF-8?q?fix=EF=BC=9Ajson=E6=9B=BF=E6=8D=A2?= =?UTF-8?q?=EF=BC=8C=E4=B8=B4=E6=97=B6=EF=BC=8CGet=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E5=BE=97=E5=88=B0=E5=88=97=E8=A1=A8=E8=BF=9B=E8=A1=8C=E4=BF=AE?= =?UTF-8?q?=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication_v2/auth_stages/auth_negotiate.cpp | 8 ++++++-- .../authentication_v2/dm_auth_message_processor.cpp | 8 +++++--- .../src/dependency/hichain/hichain_auth_connector.cpp | 10 +++++----- 3 files changed, 16 insertions(+), 10 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index a7799405d..dbfbb0b70 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -282,9 +282,11 @@ uint32_t AuthSinkNegotiateStateMachine::GetCredentialType(std::shared_ptr() == SCOPE_USER) { return DM_ACROSS_ACCOUNT; } + std::vector appList; + credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList) if (credInfo[FILED_CRED_TYPE].Get() == ACCOUNT_UNRELATED && credInfo[FILED_AUTHORIZED_SCOPE].Get() == SCOPE_APP && - HaveSameTokenId(context, credInfo[FILED_AUTHORIZED_APP_LIST].Get>()) == true) { + HaveSameTokenId(context, appList) == true) { return DM_POINT_TO_POINT; } } @@ -399,7 +401,9 @@ int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptr() == false) { continue; } - packResult[credId] = item[credId][FILED_CRED_TYPE].Get>(); + std::vector credTypeList; + item[credId][FILED_CRED_TYPE].Get(credTypeList); + packResult[credId] = credTypeList; } context->accessee.isAuthed = isEmpty; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 344548d3e..1ea494f74 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -649,7 +649,7 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr LOGE("ParseSyncMessage DM_TAG_ACL_CHECKSUM error"); return ERR_DM_FAILED; } - access.aclChecksumList = jsonObject[DM_TAG_ACL_CHECKSUM].Get>(); + jsonObject[DM_TAG_ACL_CHECKSUM].Get(access.aclChecksumList); if (jsonObject[DM_TAG_SERVICEINFO].IsString()) { // sp 暂时没有传 std::string serviceInfo = jsonObject[DM_TAG_SERVICEINFO].Get(); } @@ -1102,7 +1102,8 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptruserSkTimeStamp); } - JsonObject accessJsonObj = accessToSync; // 直接使用宏构造 access json + JsonObject accessJsonObj; + accessJsonObj = accessToSync; syncMsgJson[DM_TAG_DMVERSION] = accessSide.dmVersion; syncMsgJson[DM_TAG_ACCESS] = accessJsonObj.Dump(); // 接收端需要再拆一次json syncMsgJson[DM_TAG_PROXY] = ""; // 预留字段 留空即可 @@ -1144,7 +1145,8 @@ int32_t DmAuthMessageProcessor::ACLToStr(DistributedDeviceProfile::AccessControl dmAcl.validPeriod = acl.GetValidPeriod(); dmAcl.lastAuthTime = acl.GetLastAuthTime(); dmAcl.bindLevel = acl.GetBindType(); - JsonObject aclJsonObj = dmAcl; + JsonObject aclJsonObj; + aclJsonObj = dmAcl; aclStr = aclJsonObj.Dump(); if (aclStr.empty()) { LOGE("DmAuthMessageProcessor::ACLToStr normalized acl failed"); diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 77c3cb754..938155324 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -158,7 +158,7 @@ int32_t HiChainAuthConnector::ExportCredential(int32_t osAccountId, const std::s return ERR_DM_FAILED; } - publicKey = jsonAuthParam["keyValue"].get(); + publicKey = jsonAuthParam["keyValue"].Get(); LOGI("HiChainAuthConnector::ExportCredential leave."); return DM_OK; } @@ -360,7 +360,7 @@ int32_t HiChainAuthConnector::GenerateCredential(std::string &localUdid, int32_t return DM_OK; } -int32_t HiChainAuthConnector::QueryCredentialInfo(int32_t userId, JsonObject &queryParams, +int32_t HiChainAuthConnector::QueryCredentialInfo(int32_t userId, const JsonObject &queryParams, JsonObject &resultJson) { int32_t ret; @@ -382,11 +382,11 @@ int32_t HiChainAuthConnector::QueryCredentialInfo(int32_t userId, JsonObject &qu return ERR_DM_FAILED; } - for (const auto& element : credIdListJson) { + for (const auto& element : credIdListJson.Items()) { if (!element.IsString()) { continue; } - std::string credId = element.get(); + std::string credId = element.Get(); char *returnCredInfo = nullptr; ret = cm->queryCredInfoByCredId(userId, credId.c_str(), &returnCredInfo); @@ -401,7 +401,7 @@ int32_t HiChainAuthConnector::QueryCredentialInfo(int32_t userId, JsonObject &qu return ERR_DM_FAILED; } - resultJson[credId] = credInfoJson; + resultJson.Insert(credId, credInfoJson); } return DM_OK; -- Gitee From fa02fa90eb268e18ed1d143d3b7ccaebed6cbd7c Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Fri, 14 Mar 2025 10:12:23 +0800 Subject: [PATCH 221/382] =?UTF-8?q?fix=EF=BC=9A.gn=E6=96=87=E4=BB=B6?= =?UTF-8?q?=E4=B8=AD=E6=B7=BB=E5=8A=A0cjson=E4=BE=9D=E8=B5=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ext/pin_auth/BUILD.gn | 1 + services/implementation/BUILD.gn | 2 ++ 2 files changed, 3 insertions(+) diff --git a/ext/pin_auth/BUILD.gn b/ext/pin_auth/BUILD.gn index dcf41d8da..675a103db 100644 --- a/ext/pin_auth/BUILD.gn +++ b/ext/pin_auth/BUILD.gn @@ -97,6 +97,7 @@ ohos_shared_library("devicemanagerext_pin_auth") { "resource_management:resmgr_napi_core", "safwk:system_ability_fwk", "samgr:samgr_proxy", + "cJSON:cjson" ] defines = [ diff --git a/services/implementation/BUILD.gn b/services/implementation/BUILD.gn index e4e9c9b02..5ae153ed9 100644 --- a/services/implementation/BUILD.gn +++ b/services/implementation/BUILD.gn @@ -45,6 +45,7 @@ if (defined(ohos_lite)) { "${utils_path}/include/timer/lite", "//third_party/json/include", "//third_party/zlib/zlib.h", + "//third_party/cJSON/cJson.h", "${services_path}/include", "${services_path}/include/ipc/lite", "${interfaces_path}/c/ipc/include", @@ -91,6 +92,7 @@ if (defined(ohos_lite)) { "//foundation/systemabilitymgr/samgr_lite/samgr:samgr", "//third_party/bounds_checking_function:libsec_shared", "//third_party/zlib", + "//third_party/cJSON" ] cflags = [ -- Gitee From b60d15ac3497f046656202125ea8e2268f5eb95e Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Fri, 14 Mar 2025 15:31:55 +0800 Subject: [PATCH 222/382] =?UTF-8?q?fix=EF=BC=9Ajson=E6=9B=BF=E6=8D=A2?= =?UTF-8?q?=EF=BC=8Cget=E6=8E=A5=E5=8F=A3=E6=9B=BF=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../implementation/src/authentication_v2/auth_manager.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index e6df96536..392f180b4 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -532,11 +532,11 @@ void AuthManager::ParseJsonObject(const JsonObject &jsonObject) } else { context_->accessee.bundleName = context_->sessionName; } - if (IsInt32(jsonObject, DM_TAG_PEER_USER_ID)) { - context_->accessee.userId = jsonObject[DM_TAG_PEER_USER_ID].get(); + if (jsonObject[DM_TAG_PEER_USER_ID].IsNumberInteger()) { + context_->accessee.userId = jsonObject[DM_TAG_PEER_USER_ID].Get(); } - if (IsInt32(jsonObject, DM_TAG_PEER_DISPLAY_ID)) { - context_->accessee.displayId = jsonObject[DM_TAG_PEER_DISPLAY_ID].get(); + if (jsonObject[DM_TAG_PEER_DISPLAY_ID].IsNumberInteger()) { + context_->accessee.displayId = jsonObject[DM_TAG_PEER_DISPLAY_ID].Get(); } ParseHmlInfoInJsonObject(jsonObject); -- Gitee From eefac5b68720a6d114356e0e520ac18b4cc695ce Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Fri, 14 Mar 2025 16:50:26 +0800 Subject: [PATCH 223/382] =?UTF-8?q?fix=EF=BC=9Ajson=E6=9B=BF=E6=8D=A2?= =?UTF-8?q?=EF=BC=8C=E8=A7=A3=E5=86=B3=E7=BC=96=E8=AF=91=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_negotiate.cpp | 2 +- .../src/authentication_v2/dm_auth_message_processor.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index dbfbb0b70..2ae7db8b7 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -283,7 +283,7 @@ uint32_t AuthSinkNegotiateStateMachine::GetCredentialType(std::shared_ptr appList; - credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList) + credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList); if (credInfo[FILED_CRED_TYPE].Get() == ACCOUNT_UNRELATED && credInfo[FILED_AUTHORIZED_SCOPE].Get() == SCOPE_APP && HaveSameTokenId(context, appList) == true) { diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 1ea494f74..40a2b982c 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -776,8 +776,8 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(JsonObject &jsonObject, context->accesser.deviceName = jsonObject[TAG_DEVICE_NAME].Get(); } - if (IsInt64(jsonObject, DM_TAG_TOKEN_ID)) { - context->accesser.tokenId = static_cast(jsonObject[DM_TAG_TOKEN_ID].get()); + if (jsonObject[DM_TAG_TOKEN_ID].IsNumberInteger()) { + context->accesser.tokenId = static_cast(jsonObject[DM_TAG_TOKEN_ID].Get()); } if (jsonObject[TAG_DEVICE_ID_HASH].IsString()) { -- Gitee From 6175d674f83b7d8b1eeb5ed95d830a4acf56ebc6 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Mon, 17 Mar 2025 19:20:37 +0800 Subject: [PATCH 224/382] =?UTF-8?q?fix=EF=BC=9Ajson=E6=9B=BF=E6=8D=A2?= =?UTF-8?q?=EF=BC=8Cget=E6=9B=BF=E6=8D=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 40a2b982c..44e80f254 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -805,8 +805,8 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(JsonObject &jsonObject, if (jsonObject[TAG_AUTH_TYPE].IsNumberInteger()) { context->authType = static_cast(jsonObject[TAG_AUTH_TYPE].Get()); } - if (IsString(jsonObject, TAG_SESSION_NAME)) { - context->sessionName = jsonObject[TAG_SESSION_NAME].get(); + if (jsonObject[TAG_SESSION_NAME].IsString()) { + context->sessionName = jsonObject[TAG_SESSION_NAME].Get(); } if (jsonObject.Contains(DM_TAG_EXTRA_INFO) && jsonObject[DM_TAG_EXTRA_INFO].IsObject()) { -- Gitee From 1c8d9b425c540a0e9ad29bbc6ad07753f7aa271c Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Thu, 13 Mar 2025 15:56:13 +0800 Subject: [PATCH 225/382] =?UTF-8?q?fix=EF=BC=9Ajson=5Freplace=20tmp?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 44e80f254..377d17fba 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -805,9 +805,6 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(JsonObject &jsonObject, if (jsonObject[TAG_AUTH_TYPE].IsNumberInteger()) { context->authType = static_cast(jsonObject[TAG_AUTH_TYPE].Get()); } - if (jsonObject[TAG_SESSION_NAME].IsString()) { - context->sessionName = jsonObject[TAG_SESSION_NAME].Get(); - } if (jsonObject.Contains(DM_TAG_EXTRA_INFO) && jsonObject[DM_TAG_EXTRA_INFO].IsObject()) { ParseNegotiateExtraInfoMessage(jsonObject[DM_TAG_EXTRA_INFO], context); -- Gitee From 44d00d1f696148b5f94c977c08ff1ffebf8f506c Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Mon, 17 Mar 2025 11:27:59 +0800 Subject: [PATCH 226/382] =?UTF-8?q?fix=EF=BC=9AAuthManager=E8=B5=84?= =?UTF-8?q?=E6=BA=90=E5=BD=92=E4=B8=80=E5=8C=96=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication_v2/dm_auth_context.h | 5 +++++ .../include/device_manager_service_impl.h | 1 + .../src/authentication_v2/auth_manager.cpp | 20 ------------------- .../src/authentication_v2/dm_auth_context.cpp | 20 +++++++++++++++++++ .../src/device_manager_service_impl.cpp | 18 +++++++++++++++++ 5 files changed, 44 insertions(+), 20 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 9cb528bb0..9ea07f636 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -199,6 +199,11 @@ struct DmAuthContext { bool pinNegotiateStarted{false}; // pin协商是否已开始 bool isAuthenticateDevice = false; + // 构造函数 + DmAuthContext(std::shared_ptr softbusConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector); + // 获取设备ID std::string GetDeviceId(DmAuthSide side); // 获取用户ID diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 8fac2b80a..2e6680e7c 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -158,6 +158,7 @@ private: DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); int32_t InitAndRegisterAuthMgr(bool isSrcSide); int32_t CreateAuthMgrByMessage(int sessionId, const void *data, unsigned int dataLen); + bool IsAuthManagerInitSuccess(); private: std::shared_ptr authMgr_; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 392f180b4..3c5f260b8 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -147,18 +147,6 @@ AuthManager::AuthManager(std::shared_ptr softbusConnector, { LOGI("DmAuthManager constructor"); context_ = std::make_shared(); - context_->softbusConnector = softbusConnector; - context_->listener = listener; - context_->hiChainAuthConnector = hiChainAuthConnector; - - context_->authUiStateMgr = std::make_shared(context_->listener); - context_->authenticationMap[AUTH_TYPE_PIN] = nullptr; - context_->authenticationMap[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; - context_->authenticationMap[AUTH_TYPE_PIN_ULTRASONIC] = nullptr; - context_->accesser.dmVersion = DM_VERSION_5_1_0; - context_->accessee.dmVersion = DM_VERSION_5_1_0; - - // TODO:上下文的成员,authStateMachine、authMessageProcessor等成员是否统一在构造函数中初始化比较好,目前比较分散 } void AuthManager::SetAuthContext(std::shared_ptr context) @@ -635,16 +623,11 @@ void AuthManager::InitAuthState(const std::string &sessionName, int32_t authType // return; // } - if (context_->timer == nullptr) { - context_->timer = std::make_shared(); - } context_->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), DmAuthState::GetTaskTimeout(context_, AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) { DmAuthState::HandleAuthenticateTimeout(context_, name); }); - context_->authMessageProcessor = std::make_shared(); GetAuthParam(sessionName, authType, deviceId, extra); - context_->authStateMachine = std::make_shared(context_); context_->authStateMachine->TransitionTo(std::make_shared()); LOGI("AuthManager::AuthenticateDevice complete"); @@ -740,10 +723,7 @@ void AuthSinkManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, in LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result); if (context_->authMessageProcessor == nullptr) { // authMessage为空,开始初始化 - context_->authMessageProcessor = std::make_shared(); - context_->authStateMachine = std::make_shared(context_); context_->sessionId = sessionId; - context_->timer = std::make_shared(); context_->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), DmAuthState::GetTaskTimeout(context_, AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) { DmAuthState::HandleAuthenticateTimeout(context_, name); diff --git a/services/implementation/src/authentication_v2/dm_auth_context.cpp b/services/implementation/src/authentication_v2/dm_auth_context.cpp index 8db58bb7f..699ceea32 100644 --- a/services/implementation/src/authentication_v2/dm_auth_context.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_context.cpp @@ -20,6 +20,26 @@ namespace OHOS { namespace DistributedHardware { + // 构造函数 +DmAuthContext::DmAuthContext(std::shared_ptr softbusConnector, + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector) +{ + LOGI("DmAuthContext constructor."); + this->softbusConnector = softbusConnector; + this->listener = listener; + this->hiChainAuthConnector = hiChainAuthConnector; + this->authUiStateMgr = std::make_shared(this->listener); + this->authenticationMap[AUTH_TYPE_PIN] = nullptr; + this->authenticationMap[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; + this->authenticationMap[AUTH_TYPE_PIN_ULTRASONIC] = nullptr; + this->accesser.dmVersion = DM_VERSION_5_1_0; + this->accessee.dmVersion = DM_VERSION_5_1_0; + this->timer = std::make_shared(); + this->authMessageProcessor = std::make_shared(); + this->authStateMachine = std::make_shared(this); +} + // 获取设备ID std::string DmAuthContext::GetDeviceId(DmAuthSide side) { diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index bb1ab1e39..9d1957358 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -106,6 +106,7 @@ DeviceManagerServiceImpl::~DeviceManagerServiceImpl() { LOGI("DeviceManagerServiceImpl destructor"); } + int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide) { if (authMgr_ == nullptr) { @@ -117,6 +118,10 @@ int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide) softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); // hiChainConnector_->RegisterHiChainCallback(authMgr_); hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); + if (IsAuthManagerInitSuccess(dynamic_cast(authMgr_)) != true) { + LOGE("DeviceManagerServiceImpl::InitAndRegisterAuthMgr failed."); + return ERR_DM_FAILED; + } } else { // 线程已创建authMgr_,说明已有绑定事件,其他请求拒绝,返回错误码 LOGI("DeviceManagerServiceImpl::InitAndRegisterAuthMgr authMgr_ is not null, no need to create"); @@ -1273,6 +1278,19 @@ extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; } + +bool DeviceManagerServiceImpl::IsAuthManagerInitSuccess(const AuthManager &authMgr) +{ + return authMgr.context_ != nullptr && + authMgr.context_->softbusConnector != nullptr && + authMgr.context_->listener != nullptr && + authMgr.context_->hiChainAuthConnector != nullptr && + authMgr.context_->authUiStateMgr != nullptr && + authMgr.context_->timer != nullptr && + authMgr.context_->authMessageProcessor != nullptr && + authMgr.context_->authStateMachine != nullptr; +} + } // namespace DistributedHardware } // namespace OHOS ; \ No newline at end of file -- Gitee From 259fe5fb6bbef1978f65f585734b0384e079b4e9 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Mon, 17 Mar 2025 15:22:44 +0800 Subject: [PATCH 227/382] =?UTF-8?q?fix=EF=BC=9A=E8=B5=84=E6=BA=90=E5=8C=96?= =?UTF-8?q?=E5=BD=92=E4=B8=80=E5=AE=9E=E7=8E=B0=E4=BF=AE=E6=94=B9=E3=80=82?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication/dm_auth_manager.h | 1 + .../include/authentication_v2/auth_manager.h | 2 ++ .../authentication_v2/dm_auth_context.h | 5 ---- .../authentication_v2/dm_auth_manager_base.h | 3 +++ .../include/device_manager_service_impl.h | 1 - .../src/authentication/dm_auth_manager.cpp | 6 +++++ .../src/authentication_v2/auth_manager.cpp | 24 +++++++++++++++++++ .../src/authentication_v2/dm_auth_context.cpp | 20 ---------------- .../src/device_manager_service_impl.cpp | 15 +----------- 9 files changed, 37 insertions(+), 40 deletions(-) diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 2db8af888..0470959c1 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -483,6 +483,7 @@ public: static bool IsPinCodeValid(int32_t numpin); bool IsImportedAuthCodeValid(); bool IsSrc(); + bool IsAuthManagerConstructSuccess() override; private: bool IsHmlSessionType(); diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index da3cddb8f..8712b6c85 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -140,6 +140,8 @@ public: // 提取本端ACL 用于消息解析和总线使用 无ACL会返回空字符串 json格式字符串:{dmversion:x,accesser:[{accesserDeviceId:y,...},...],accessee:{...}} int32_t GetAclListStr(std::string &aclList); + bool IsAuthManagerConstructSuccess() override; + protected: // 上下文(需在该层级进行创建) std::shared_ptr context_; diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 9ea07f636..9cb528bb0 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -199,11 +199,6 @@ struct DmAuthContext { bool pinNegotiateStarted{false}; // pin协商是否已开始 bool isAuthenticateDevice = false; - // 构造函数 - DmAuthContext(std::shared_ptr softbusConnector, - std::shared_ptr listener, - std::shared_ptr hiChainAuthConnector); - // 获取设备ID std::string GetDeviceId(DmAuthSide side); // 获取用户ID diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h b/services/implementation/include/authentication_v2/dm_auth_manager_base.h index 32184d205..c5a047b4f 100644 --- a/services/implementation/include/authentication_v2/dm_auth_manager_base.h +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h @@ -134,6 +134,9 @@ public: virtual void GetBindTargetParams(std::string &pkgName, PeerTargetId &targetId, std::map &bindParam); + // 检查authManager是否初始化成功 + virtual bool IsAuthManagerConstructSuccess() = 0; + // 公共函数 static std::string ConvertSrcVersion(const std::string &version, const std::string &edition); static std::string ConvertSinkVersion(const std::string &version); diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 2e6680e7c..8fac2b80a 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -158,7 +158,6 @@ private: DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); int32_t InitAndRegisterAuthMgr(bool isSrcSide); int32_t CreateAuthMgrByMessage(int sessionId, const void *data, unsigned int dataLen); - bool IsAuthManagerInitSuccess(); private: std::shared_ptr authMgr_; diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index eda9c8262..e3519ebcd 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -3332,5 +3332,11 @@ int32_t DmAuthManager::GetTokenIdByBundleName(int32_t userId, std::string &bundl } return ret; } + +bool DmAuthManager::IsAuthManagerInitSuccess(const AuthManager &authMgr) +{ + LOGI("DmAuthManager::IsAuthManagerInitSuccess start, nothing to do."); + return true; +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 3c5f260b8..2a3ca1427 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -147,6 +147,30 @@ AuthManager::AuthManager(std::shared_ptr softbusConnector, { LOGI("DmAuthManager constructor"); context_ = std::make_shared(); + context_->softbusConnector = softbusConnector; + context_->listener = listener; + context_->hiChainAuthConnector = hiChainAuthConnector; + context_->authUiStateMgr = std::make_shared(context_->listener); + context_->authenticationMap[AUTH_TYPE_PIN] = nullptr; + context_->authenticationMap[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; + context_->authenticationMap[AUTH_TYPE_PIN_ULTRASONIC] = nullptr; + context_->accesser.dmVersion = DM_VERSION_5_1_0; + context_->accessee.dmVersion = DM_VERSION_5_1_0; + context_->timer = std::make_shared(); + context_->authMessageProcessor = std::make_shared(); + context_->authStateMachine = std::make_shared(context_); +} + +bool AuthManager::IsAuthManagerConstructSuccess() +{ + return context_ != nullptr && + context_->softbusConnector != nullptr && + context_->listener != nullptr && + context_->hiChainAuthConnector != nullptr && + context_->authUiStateMgr != nullptr && + context_->timer != nullptr && + context_->authMessageProcessor != nullptr && + context_->authStateMachine != nullptr; } void AuthManager::SetAuthContext(std::shared_ptr context) diff --git a/services/implementation/src/authentication_v2/dm_auth_context.cpp b/services/implementation/src/authentication_v2/dm_auth_context.cpp index 699ceea32..8db58bb7f 100644 --- a/services/implementation/src/authentication_v2/dm_auth_context.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_context.cpp @@ -20,26 +20,6 @@ namespace OHOS { namespace DistributedHardware { - // 构造函数 -DmAuthContext::DmAuthContext(std::shared_ptr softbusConnector, - std::shared_ptr listener, - std::shared_ptr hiChainAuthConnector) -{ - LOGI("DmAuthContext constructor."); - this->softbusConnector = softbusConnector; - this->listener = listener; - this->hiChainAuthConnector = hiChainAuthConnector; - this->authUiStateMgr = std::make_shared(this->listener); - this->authenticationMap[AUTH_TYPE_PIN] = nullptr; - this->authenticationMap[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; - this->authenticationMap[AUTH_TYPE_PIN_ULTRASONIC] = nullptr; - this->accesser.dmVersion = DM_VERSION_5_1_0; - this->accessee.dmVersion = DM_VERSION_5_1_0; - this->timer = std::make_shared(); - this->authMessageProcessor = std::make_shared(); - this->authStateMachine = std::make_shared(this); -} - // 获取设备ID std::string DmAuthContext::GetDeviceId(DmAuthSide side) { diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 9d1957358..2e1fa7359 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -118,7 +118,7 @@ int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide) softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); // hiChainConnector_->RegisterHiChainCallback(authMgr_); hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); - if (IsAuthManagerInitSuccess(dynamic_cast(authMgr_)) != true) { + if (!authMgr_->IsAuthManagerConstructSuccess()) { LOGE("DeviceManagerServiceImpl::InitAndRegisterAuthMgr failed."); return ERR_DM_FAILED; } @@ -1278,19 +1278,6 @@ extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; } - -bool DeviceManagerServiceImpl::IsAuthManagerInitSuccess(const AuthManager &authMgr) -{ - return authMgr.context_ != nullptr && - authMgr.context_->softbusConnector != nullptr && - authMgr.context_->listener != nullptr && - authMgr.context_->hiChainAuthConnector != nullptr && - authMgr.context_->authUiStateMgr != nullptr && - authMgr.context_->timer != nullptr && - authMgr.context_->authMessageProcessor != nullptr && - authMgr.context_->authStateMachine != nullptr; -} - } // namespace DistributedHardware } // namespace OHOS ; \ No newline at end of file -- Gitee From 5a8043b64fd0a03bd0b6b0c6be7a5af962e85316 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Mon, 17 Mar 2025 15:52:45 +0800 Subject: [PATCH 228/382] =?UTF-8?q?fix=EF=BC=9A=E8=B5=84=E6=BA=90=E5=BD=92?= =?UTF-8?q?=E4=B8=80=E8=A7=A3=E5=86=B3=E7=BC=96=E8=AF=91=E6=8A=A5=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../implementation/include/authentication/dm_auth_manager.h | 2 +- .../implementation/include/authentication_v2/auth_manager.h | 2 +- .../implementation/src/authentication/dm_auth_manager.cpp | 4 ++-- .../implementation/src/authentication_v2/auth_manager.cpp | 1 + 4 files changed, 5 insertions(+), 4 deletions(-) diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index 0470959c1..81e7f0431 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -483,7 +483,7 @@ public: static bool IsPinCodeValid(int32_t numpin); bool IsImportedAuthCodeValid(); bool IsSrc(); - bool IsAuthManagerConstructSuccess() override; + bool IsAuthManagerConstructSuccess(); private: bool IsHmlSessionType(); diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 8712b6c85..f39525796 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -140,7 +140,7 @@ public: // 提取本端ACL 用于消息解析和总线使用 无ACL会返回空字符串 json格式字符串:{dmversion:x,accesser:[{accesserDeviceId:y,...},...],accessee:{...}} int32_t GetAclListStr(std::string &aclList); - bool IsAuthManagerConstructSuccess() override; + bool IsAuthManagerConstructSuccess(); protected: // 上下文(需在该层级进行创建) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index e3519ebcd..37ede335f 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -3333,9 +3333,9 @@ int32_t DmAuthManager::GetTokenIdByBundleName(int32_t userId, std::string &bundl return ret; } -bool DmAuthManager::IsAuthManagerInitSuccess(const AuthManager &authMgr) +bool DmAuthManager::IsAuthManagerConstructSuccess() { - LOGI("DmAuthManager::IsAuthManagerInitSuccess start, nothing to do."); + LOGI("DmAuthManager::IsAuthManagerConstructSuccess start, nothing to do."); return true; } } // namespace DistributedHardware diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 2a3ca1427..bbfc9df0e 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -163,6 +163,7 @@ AuthManager::AuthManager(std::shared_ptr softbusConnector, bool AuthManager::IsAuthManagerConstructSuccess() { + LOGI("AuthManager::IsAuthManagerConstructSuccess, check authManager member."); return context_ != nullptr && context_->softbusConnector != nullptr && context_->listener != nullptr && -- Gitee From a1a2af6c0f729c6395ae831b590789012f70597a Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 17 Mar 2025 20:28:53 +0800 Subject: [PATCH 229/382] =?UTF-8?q?feat:=20=E5=AE=8C=E6=88=9090=E6=8A=A5?= =?UTF-8?q?=E6=96=87=E4=B8=AD=E7=9A=84=E5=87=AD=E6=8D=AE=E6=9F=A5=E8=AF=A2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth_stages/auth_credential.cpp | 16 ++++++++-- .../auth_stages/auth_negotiate.cpp | 29 +++++++++++++------ .../dm_auth_message_processor.cpp | 6 ++-- .../hichain/hichain_auth_connector.cpp | 2 +- .../src/device_manager_service_impl.cpp | 2 +- 5 files changed, 39 insertions(+), 16 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index e92a99eed..6dc73f568 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -31,6 +31,12 @@ namespace OHOS { namespace DistributedHardware { +namespace { + +const char * const FILED_DEVICE_ID = "deviceId"; + +} + // 从context中提取transmit data,使用SK解密,并透传给HICHAIN // 如果ontransmit事件,在对应回调解析并保存在context // 如果onsessionkeyreturned事件,在对应回调解析并保存在cryptomgr @@ -255,7 +261,7 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori JsonObject jsonObj; if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) { - jsonObj[DM_TAG_METHOD] = method; // 凭据生成方式 + jsonObj[DM_TAG_METHOD] = method; // 凭据生成方式,只有导入时,需要传入method } jsonObj[DM_TAG_DEVICE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? // 设备ID 生成是本端,导入是对端 @@ -263,6 +269,8 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) { jsonObj[DM_TAG_PEER_USER_SPACE_ID] = std::to_string(authContext->GetUserId(DM_AUTH_REMOTE_SIDE)); } + jsonObj[DM_TAG_USER_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? + authContext->GetAccountId(DM_AUTH_LOCAL_SIDE) : authContext->GetAccountId(DM_AUTH_REMOTE_SIDE); jsonObj[DM_TAG_SUBJECT] = DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY; // 主控设备 jsonObj[DM_TAG_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; // 账号无关 jsonObj[DM_TAG_KEY_FORMAT] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? @@ -305,7 +313,8 @@ int32_t AuthCredentialAgreeState::GenerateCredIdAndPublicKey(DmAuthScope authori } // 生成凭据 - int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + int32_t osAccountId = authContext->direction == DM_AUTH_SOURCE ? + authContext->accesser.userId : authContext->accessee.userId; std::string credId; int32_t ret = authContext->hiChainAuthConnector->AddCredential(osAccountId, authParamsString, credId); if (ret != DM_OK) { @@ -352,7 +361,8 @@ int32_t AuthCredentialAgreeState::AgreeCredential(DmAuthScope authorizedScope, } // 凭据协商得到协商凭据Id - int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();; + int32_t osAccountId = authContext->direction == DM_AUTH_SOURCE ? + authContext->accesser.userId : authContext->accessee.userId; std::string selfCredId = authContext->GetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope); std::string credId; int32_t ret = authContext->hiChainAuthConnector->AgreeCredential(osAccountId, selfCredId, diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 2ae7db8b7..9bf828e93 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -65,6 +65,7 @@ constexpr size_t MAX_FALLBACK_LOOPKUP_TIMES = 2; // 最大递归查找次数 // security_device_auth凭据查询相关定义,保持与device_auth.h一致 const char * const FILED_DEVICE_ID = "deviceId"; const char * const FILED_DEVICE_ID_HASH = "deviceIdHash"; +const char * const FILED_USER_ID = "userId"; const char * const FILED_PEER_USER_SPACE_ID = "peerUserSpaceId"; const char * const FILED_CRED_TYPE = "credType"; const char * const FILED_AUTHORIZED_APP_LIST = "authorizedAppList"; @@ -231,9 +232,10 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptraccessee.bundleName).c_str()); - return ret; + // 对于FA-device,无tokenId + return DM_OK; } context->accessee.bundleName = tmpBundleName; context->accessee.tokenId = static_cast(tokenId); @@ -341,12 +343,10 @@ int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptraccessee.deviceId; + // 1. 获取所有凭据(参考addCredential和agreeCredential) queryParams[FILED_DEVICE_ID_HASH] = context->accesser.deviceIdHash; - queryParams[FILED_PEER_USER_SPACE_ID] = context->accesser.userIdHash; + queryParams[FILED_PEER_USER_SPACE_ID] = context->accesser.userId; + queryParams[FILED_USER_ID] = context->accessee.userId; // 同账号凭据 if (context->accessee.accountId != "ohosAnonymousUid" && Crypto::Sha256(context->accessee.accountId) == context->accesser.accountIdHash) { @@ -354,10 +354,12 @@ int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptrhiChainAuthConnector->QueryCredentialInfo(context->accessee.userId, queryParams, queryResult); if (ret != DM_OK) { - LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to query credential id list."); - context->reply = ERR_DM_UNSUPPORTED_AUTH_TYPE; + LOGE("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo fail to query credential id list."); return ret; } + LOGI("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo for userId %{public}d and queryParams %{public}s " + "query credentialInfo: %{public}s", context->accessee.userId, queryParams.Dump().c_str(), + queryResult.Dump().c_str()); for (auto& item : queryResult.Items()) { isEmpty = false; @@ -378,6 +380,14 @@ int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptraccesser.dmVersion; jsonObject[TAG_DEVICE_NAME] = context->accesser.deviceName; + jsonObject[DM_TAG_USER_ID] = context->accesser.userId; jsonObject[DM_TAG_TOKEN_ID] = static_cast(context->accesser.tokenId); jsonObject[TAG_DEVICE_ID_HASH] = context->accesser.deviceIdHash; @@ -769,13 +770,14 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(JsonObject &jsonObject, context->accesser.dmVersion = jsonObject[DM_TAG_DMVERSION].Get(); } if (jsonObject[DM_TAG_EDITION].IsString()) { - context->accesser.edition = jsonObject[DM_TAG_EDITION].Get(); } if (jsonObject[TAG_DEVICE_NAME].IsString()) { - context->accesser.deviceName = jsonObject[TAG_DEVICE_NAME].Get(); } + if (jsonObject[DM_TAG_USER_ID].IsNumberInteger()) { + context->accesser.userId = jsonObject[DM_TAG_USER_ID].Get(); + } if (jsonObject[DM_TAG_TOKEN_ID].IsNumberInteger()) { context->accesser.tokenId = static_cast(jsonObject[DM_TAG_TOKEN_ID].Get()); } diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 938155324..24e0a909d 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -372,7 +372,7 @@ int32_t HiChainAuthConnector::QueryCredentialInfo(int32_t userId, const JsonObje &credIdList); // TODO: 可能是空的,要返回DM_OK if (ret != DM_OK) { - LOGE("HiChainAuthConnector::QueryCredentialInfo fail to query credential id list."); + LOGE("HiChainAuthConnector::QueryCredentialInfo fail to query credential id list with ret %{public}d.", ret); return ERR_DM_FAILED; } JsonObject credIdListJson(credIdList); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 2e1fa7359..848dd5bba 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -511,7 +511,7 @@ void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, // 参数2 sessionSide为0,authMgr_为空一定是sink端,src端会在BindTarget时创建协议对象 authMgr_->OnSessionOpened(sessionId, 0, 0); - LOGI("DeviceManagerServiceImpl::OnBytesReceived src transfer to old version success"); + LOGI("DeviceManagerServiceImpl::OnBytesReceived sink transfer to old version success"); } SoftbusSession::OnBytesReceived(sessionId, data, dataLen); -- Gitee From e9ffd1801dcc44a461db662fefa157a7a154af2f Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 18 Mar 2025 10:00:22 +0800 Subject: [PATCH 230/382] TIMEOUT revert fix --- .../implementation/src/authentication/dm_auth_manager.cpp | 6 +++--- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 3 ++- .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 6 ++++-- 3 files changed, 9 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 37ede335f..3fb4567e5 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -58,13 +58,13 @@ const int32_t NEGOTIATE_TIMEOUT = 10; const int32_t INPUT_TIMEOUT = 60; const int32_t ADD_TIMEOUT = 10; const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; -const int32_t WAIT_REQUEST_TIMEOUT = 60; +const int32_t WAIT_REQUEST_TIMEOUT = 10; const int32_t CLONE_AUTHENTICATE_TIMEOUT = 20; -const int32_t CLONE_CONFIRM_TIMEOUT = 60; +const int32_t CLONE_CONFIRM_TIMEOUT = 10; const int32_t CLONE_NEGOTIATE_TIMEOUT = 10; const int32_t CLONE_ADD_TIMEOUT = 10; const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10; -const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 60; +const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10; const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20; const int32_t HML_SESSION_TIMEOUT = 10; const int32_t CANCEL_PIN_CODE_DISPLAY = 1; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index c8ebb9cae..42735cf6b 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -76,7 +76,8 @@ int32_t AuthSrcConfirmState::DoPinAuth(std::shared_ptr context) context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_USER_CONFIRM, context); context->timer->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), - CONFIRM_TIMEOUT, [context] (std::string name) { + DmAuthState::GetTaskTimeout(context, CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), + [context] (std::string name) { HandleAuthenticateTimeout(context, name); }); } else { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index ff3c3fdaa..04f03dc9a 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -64,7 +64,8 @@ int32_t AuthSinkStatePinAuthComm::ShowAuthInfoDialog(std::shared_ptrpinCode)); context->timer->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), - SESSION_HEARTBEAT_TIMEOUT, [context] (std::string name) { + DmAuthState::GetTaskTimeout(context, SESSION_HEARTBEAT_TIMEOUT_TASK,SESSION_HEARTBEAT_TIMEOUT), + [context] (std::string name) { AuthSinkStatePinAuthComm::HandleSessionHeartbeat(context, name); }); return DM_OK; @@ -84,7 +85,8 @@ void AuthSinkStatePinAuthComm::HandleSessionHeartbeat(std::shared_ptrsoftbusConnector->GetSoftbusSession()->SendHeartbeatData(context->sessionId, message); context->timer->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), - SESSION_HEARTBEAT_TIMEOUT, [context] (std::string name) { + DmAuthState::GetTaskTimeout(context, SESSION_HEARTBEAT_TIMEOUT_TASK,SESSION_HEARTBEAT_TIMEOUT), + [context] (std::string name) { AuthSinkStatePinAuthComm::HandleSessionHeartbeat(context, name); }); -- Gitee From b75ee661b0e2671bc8c2955ac29381dc68c1f2b2 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Tue, 18 Mar 2025 17:10:40 +0800 Subject: [PATCH 231/382] =?UTF-8?q?test:=20=E8=A7=A3=E5=86=B3=E9=BB=84?= =?UTF-8?q?=E5=8C=BA=E7=BC=96=E8=AF=91=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index c189a7487..be00f715d 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -107,7 +107,7 @@ int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptraccesser.tokenId); accesser.SetAccesserBundleName(context->accesser.bundleName); accesser.SetAccesserDeviceName(context->accesser.deviceName); - accesser.SetAccesserServiceId(context->accesser.serviceId); + // accesser.SetAccesserServiceId(context->accesser.serviceId); accesser.SetAccesserCredentialId(context->accesser.credentialId); accesser.SetAccesserSessionKeyId(context->accesser.sessionKeyId); accesser.SetAccesserSKTimeStamp(context->accesser.skTimeStamp); @@ -118,7 +118,7 @@ int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptraccessee.tokenId); accessee.SetAccesseeBundleName(context->accessee.bundleName); accessee.SetAccesseeDeviceName(context->accessee.deviceName); - accessee.SetAccesseeServiceId(context->accessee.serviceId); + // accessee.SetAccesseeServiceId(context->accessee.serviceId); accessee.SetAccesseeCredentialId(context->accessee.credentialId); accessee.SetAccesseeSessionKeyId(context->accessee.sessionKeyId); accessee.SetAccesseeSKTimeStamp(context->accessee.skTimeStamp); -- Gitee From b622592c20d3115c35039c3582494cac268a8c1f Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Tue, 18 Mar 2025 21:36:55 +0800 Subject: [PATCH 232/382] =?UTF-8?q?test:=20=E5=B0=81=E8=A3=85userId?= =?UTF-8?q?=E8=8E=B7=E5=8F=96=E6=8E=A5=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication_v2/dm_auth_manager_base.h | 1 + .../auth_stages/auth_negotiate.cpp | 49 +-------------- .../dm_auth_manager_base.cpp | 60 +++++++++++++++++++ 3 files changed, 64 insertions(+), 46 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h b/services/implementation/include/authentication_v2/dm_auth_manager_base.h index c5a047b4f..2e4508d95 100644 --- a/services/implementation/include/authentication_v2/dm_auth_manager_base.h +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h @@ -140,6 +140,7 @@ public: // 公共函数 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); // 公共变量 bool isAuthNewVersion_ = true; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 9bf828e93..461ddaa08 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -41,11 +41,6 @@ #include "auth_manager.h" #include "dm_auth_state.h" -#ifdef OS_ACCOUNT_PART_EXISTS -#include "os_account_manager.h" -using namespace OHOS::AccountSA; -#endif // OS_ACCOUNT_PART_EXISTS - using namespace OHOS::Security::AccessToken; #undef LOG_TAG @@ -173,49 +168,11 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptraccessee.deviceId = std::string(localDeviceId); // 2. 获取userId - std::vector userVec; - ret = MultipleUserConnector::GetForegroundUserIds(userVec); - if (ret != DM_OK) { - LOGE("RespQueryTokenId: GetForegroundUserIds failed, ret: %{public}d", ret); - return ret; - } - if (userVec.size() == 0) { - LOGE("RespQueryTokenId: GetForegroundUserIds no foreground users"); - return ERR_DM_FAILED; - } - - if (context->accessee.displayId != 0) { - ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(context->accessee.displayId, - context->accessee.userId); - if (ret != DM_OK) { - LOGE("RespQueryTokenId: fail to get userId by displayId %{public}d", context->accessee.displayId); - return ERR_DM_FAILED; - } - } - - // 场景1:对端指定了userId -> 校验是否为前台用户 - // 场景2:对端未指定userId - // 场景2.1: 单用户 -> 使用当前唯一前台用户 - // 场景2.2: 多用户 -> 使用当前主屏用户 - if (context->accessee.userId != 0) { - if (std::find(userVec.begin(), userVec.end(), context->accessee.userId) == userVec.end()) { - LOGE("RespQueryTokenId: userId not in foreground users"); - return ERR_DM_FAILED; - } - } else if (userVec.size() == 1) { - context->accessee.userId = userVec[0]; - } else { -#ifdef OS_ACCOUNT_PART_EXISTS - ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(context->accessee.userId); - if (ret != DM_OK) { - LOGE("RespQueryAcceseeIds: get foreground user failed in multi users with error %{public}d", ret); - return ERR_DM_FAILED; - } -#else - LOGE("RespQueryAcceseeIds: get foreground user failed because no OsAcccountManager"); + int32_t userId = AuthManagerBase::DmGetUserId(context->accessee.displayId, context->accessee.userId); + if (userId != -1) { return ERR_DM_FAILED; -#endif } + context->accessee.userId = userId; // 3. 获取accountId context->accessee.accountId = MultipleUserConnector::GetOhosAccountIdByUserId(context->accessee.userId); diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp index 2a5fce0e9..e8912d559 100644 --- a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp @@ -13,9 +13,17 @@ * limitations under the License. */ +#include "multiple_user_connector.h" +#include "os_account_manager.h" + #include "dm_error_type.h" #include "dm_auth_manager_base.h" +#ifdef OS_ACCOUNT_PART_EXISTS +#include "os_account_manager.h" +using namespace OHOS::AccountSA; +#endif // OS_ACCOUNT_PART_EXISTS + #undef LOG_TAG #define LOG_TAG "DHDM_V2" @@ -285,5 +293,57 @@ std::string AuthManagerBase::ConvertSinkVersion(const std::string &version) return sinkVersion; } +int32_t AuthManagerBase::DmGetUserId(int32_t displayId, int32_t targetUserId) +{ + int32_t ret; + int32_t userId; + + std::vector userIds; + ret = MultipleUserConnector::GetForegroundUserIds(userIds); + if (ret != DM_OK) { + LOGE("RespQueryTokenId: GetForegroundUserIds failed, ret: %{public}d", ret); + return -1; + } + if (userIds.size() == 0) { + LOGE("RespQueryTokenId: GetForegroundUserIds no foreground users"); + return -1; + } + + if (displayId != 0) { + ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(displayId, userId); + if (ret != DM_OK) { + LOGE("RespQueryTokenId: fail to get userId by displayId %{public}d", displayId); + return -1; + } + } + + // 场景1:对端指定了userId -> 校验是否为前台用户 + // 场景2:对端未指定userId + // 场景2.1: 单用户 -> 使用当前唯一前台用户 + // 场景2.2: 多用户 -> 使用当前主屏用户 + if (targetUserId != 0) { + if (std::find(userIds.begin(), userIds.end(), targetUserId) == userIds.end()) { + LOGE("RespQueryTokenId: userId not in foreground users"); + return -1; + } + return targetUserId; + } + + if (userIds.size() == 1) { + return userIds[0]; + } else { +#ifdef OS_ACCOUNT_PART_EXISTS + ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId); + if (ret != DM_OK) { + LOGE("RespQueryAcceseeIds: get foreground user failed in multi users with error %{public}d", ret); + return -1; + } +#else + LOGE("RespQueryAcceseeIds: get foreground user failed because no OsAcccountManager"); + return -1; +#endif + } +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file -- Gitee From 425c84aada1e0612b6aa24636f2b2e117ccd39c2 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Wed, 19 Mar 2025 10:25:09 +0800 Subject: [PATCH 233/382] =?UTF-8?q?test:=20importAuthCode=E8=B0=83?= =?UTF-8?q?=E8=AF=95=E5=88=B0100=E6=8A=A5=E6=96=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/device_manager_service_impl.h | 3 ++ .../auth_stages/auth_negotiate.cpp | 2 +- .../src/device_manager_service_impl.cpp | 31 ++++++++++++++++++- 3 files changed, 34 insertions(+), 2 deletions(-) diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 67265d269..c7a5e288e 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -172,6 +172,9 @@ private: std::shared_ptr listener_; std::atomic isCredentialType_ = false; sptr dpInitedCallback_ = nullptr; + + std::string importAuthCode_; + std::string importPkgName_; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 461ddaa08..35c97fbc0 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -169,7 +169,7 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptraccessee.displayId, context->accessee.userId); - if (userId != -1) { + if (userId < 0) { return ERR_DM_FAILED; } context->accessee.userId = userId; diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 0bdf0daba..72a027cd2 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -109,6 +109,8 @@ DeviceManagerServiceImpl::~DeviceManagerServiceImpl() int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide) { + int32_t ret; + if (authMgr_ == nullptr) { if (isSrcSide) { authMgr_ = std::make_shared(softbusConnector_, listener_, hiChainAuthConnector_); @@ -122,6 +124,16 @@ int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide) LOGE("DeviceManagerServiceImpl::InitAndRegisterAuthMgr failed."); return ERR_DM_FAILED; } + + if (!importAuthCode_.empty() && !importPkgName_.empty()) { + ret = authMgr_->ImportAuthCode(importPkgName_, importAuthCode_); + if (ret != DM_OK) { + LOGE("DeviceManagerServiceImpl::OnBytesReceived import authCode failed"); + authMgr_ = nullptr; + return ERR_DM_FAILED; + } + } + } else { // 线程已创建authMgr_,说明已有绑定事件,其他请求拒绝,返回错误码 LOGI("DeviceManagerServiceImpl::InitAndRegisterAuthMgr authMgr_ is not null, no need to create"); @@ -489,6 +501,14 @@ void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); + if (!importAuthCode_.empty() && !importPkgName_.empty()) { + ret = authMgr_->ImportAuthCode(importPkgName_, importAuthCode_); + if (ret != DM_OK) { + LOGE("DeviceManagerServiceImpl::OnBytesReceived import authCode failed"); + return; + } + } + if (IsAuthManagerSourceByMessage(data, dataLen)) { // 发送停止报文 // 不能走新协议的停止,新协议是信号机制,无法串行停止,会存在时延,导致未停止就创建了新对象, @@ -761,7 +781,16 @@ int32_t DeviceManagerServiceImpl::ImportAuthCode(const std::string &pkgName, con return ERR_DM_INPUT_PARA_INVALID; } - return authMgr_->ImportAuthCode(pkgName, authCode); + int32_t ret = InitAndRegisterAuthMgr(true); + if (ret != DM_OK) { + return ret; + } + + importAuthCode_ = authCode; + importPkgName_ = pkgName; + + return DM_OK; + // return authMgr_->ImportAuthCode(pkgName, authCode); } int32_t DeviceManagerServiceImpl::ExportAuthCode(std::string &authCode) -- Gitee From 21bbd664628b12a98adf0c5f043d2f29de59fae3 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Wed, 19 Mar 2025 11:51:49 +0800 Subject: [PATCH 234/382] test: --- services/implementation/src/device_manager_service_impl.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 72a027cd2..489dbffb9 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -125,6 +125,8 @@ int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide) return ERR_DM_FAILED; } + LOGI(" DeviceManagerServiceImpl::InitAndRegisterAuthMgr import authcode ${public}s and pkgName %{public}s", + importAuthCode_, importPkgName_); if (!importAuthCode_.empty() && !importPkgName_.empty()) { ret = authMgr_->ImportAuthCode(importPkgName_, importAuthCode_); if (ret != DM_OK) { -- Gitee From 2eadbce758c6c27d8c75e3f5f7efb9bc7bc93bab Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Wed, 19 Mar 2025 15:27:54 +0800 Subject: [PATCH 235/382] =?UTF-8?q?feat:=20=E5=AE=8C=E6=88=90SA-SA?= =?UTF-8?q?=E8=B0=83=E8=AF=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_manager.cpp | 5 +++-- .../authentication_v2/auth_stages/auth_negotiate.cpp | 3 ++- .../authentication_v2/dm_auth_message_processor.cpp | 3 +++ .../src/device_manager_service_impl.cpp | 11 ++++------- 4 files changed, 12 insertions(+), 10 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index bbfc9df0e..af0b943e1 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -418,7 +418,8 @@ bool AuthManager::IsAuthCodeReady(const std::string &sessionName) return false; } if (sessionName != context_->importSessionName) { - LOGE("IsAuthCodeReady failed, sessionName not supported."); + LOGE("AuthManager::IsAuthCodeReady sessionName %{public}s not supported with import sessionName %{public}s.", + sessionName.c_str(), context_->importSessionName.c_str()); return false; } return true; @@ -597,7 +598,7 @@ int32_t AuthManager::GetTokenIdByBundleName(int32_t userId, std::string &bundleN void AuthManager::GetAuthParam(const std::string &sessionName, int32_t authType, const std::string &deviceId, const std::string &extra) { - LOGI("Get auth param."); + LOGI("Get auth param with sessionName %{public}s and extra %{public}s.", sessionName.c_str(), extra.c_str()); char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localDeviceId); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 35c97fbc0..53f3d54a2 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -436,7 +436,8 @@ bool AuthSinkNegotiateStateMachine::IsAuthCodeReady(std::shared_ptrsessionName != context->importSessionName) { - LOGE("IsAuthCodeReady failed, sessionName not supported."); + LOGE("AuthSinkNegotiateStateMachine::IsAuthCodeReady sessionName %{public}s not supported with " + "import sessionName %{public}s.", context->sessionName.c_str(), context->importSessionName.c_str()); return false; } return true; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index be00f715d..f9a083afa 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -795,6 +795,9 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(JsonObject &jsonObject, context->accesser.tokenIdHash = jsonObject[TAG_TOKEN_ID_HASH].Get(); } + if (jsonObject[TAG_SESSION_NAME].IsString()) { + context->sessionName = jsonObject[TAG_SESSION_NAME].Get(); + } if (jsonObject[TAG_BUNDLE_NAME].IsString()) { context->accesser.bundleName = jsonObject[TAG_BUNDLE_NAME].Get(); } diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 489dbffb9..33314b774 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -125,8 +125,8 @@ int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide) return ERR_DM_FAILED; } - LOGI(" DeviceManagerServiceImpl::InitAndRegisterAuthMgr import authcode ${public}s and pkgName %{public}s", - importAuthCode_, importPkgName_); + LOGI(" DeviceManagerServiceImpl::InitAndRegisterAuthMgr import authcode %{public}s and pkgName %{public}s", + importAuthCode_.c_str(), importPkgName_.c_str()); if (!importAuthCode_.empty() && !importPkgName_.empty()) { ret = authMgr_->ImportAuthCode(importPkgName_, importAuthCode_); if (ret != DM_OK) { @@ -783,14 +783,11 @@ int32_t DeviceManagerServiceImpl::ImportAuthCode(const std::string &pkgName, con return ERR_DM_INPUT_PARA_INVALID; } - int32_t ret = InitAndRegisterAuthMgr(true); - if (ret != DM_OK) { - return ret; - } - + // TODO:需要用config结构体包装 importAuthCode_ = authCode; importPkgName_ = pkgName; + LOGI("%{public}s success to import authCode %{public}s", pkgName.c_str(), authCode.c_str()); return DM_OK; // return authMgr_->ImportAuthCode(pkgName, authCode); } -- Gitee From 751d67e4b22ad87485ea0c809b0ca251b883e3ad Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Wed, 19 Mar 2025 16:19:37 +0800 Subject: [PATCH 236/382] test: --- .../src/authentication_v2/auth_manager.cpp | 10 ---------- .../authentication_v2/auth_stages/auth_negotiate.cpp | 3 --- .../src/dependency/hichain/hichain_auth_connector.cpp | 1 - 3 files changed, 14 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index af0b943e1..eff1b22a7 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -680,16 +680,6 @@ int32_t AuthManager::AuthenticateDevice(const std::string &sessionName, int32_t return ret; } context_->isAuthenticateDevice = true; - // TODO: 当前已经没有AUTH_TYPE_CRE类型,待确认 - // if (authType == AUTH_TYPE_CRE) { - // LOGI("AuthManager::AuthenticateDevice for credential type, joinLNN directly."); - // context_->softbusConnector->JoinLnn(deviceId); - // context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", - // STATUS_DM_AUTH_DEFAULT, DM_OK); - // context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, - // DM_OK, STATUS_DM_AUTH_DEFAULT, ""); - // return DM_OK; - // } InitAuthState(sessionName, authType, deviceId, extra); return DM_OK; } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 53f3d54a2..94d38dca6 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -130,7 +130,6 @@ int32_t AuthSrcNegotiateStateMachine::Action(std::shared_ptr cont context->reply = ERR_DM_AUTH_REJECT; // Q: 初始化时已赋值,此处需确认调试结果 context->accessee.bundleName = context->accesser.bundleName; - //TODO: 传输tokenId // 为什么之前DmVersion传空? context->accessee.dmVersion = ""; @@ -258,7 +257,6 @@ uint32_t AuthSinkNegotiateStateMachine::GetCredentialType(std::shared_ptr context, const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) { - // TODO: 需确定deviceId、userId哈希值的截断位数是多少 return Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash && Crypto::Sha256(std::to_string(accesser.GetAccesserUserId())) == context->accesser.userIdHash && accessee.GetAccesseeDeviceId() == context->accessee.deviceId && @@ -270,7 +268,6 @@ bool AuthSinkNegotiateStateMachine::AclCompareFourIds(std::shared_ptraccesser.accountIdHash && Crypto::Sha256(std::to_string(accesser.GetAccesserTokenId())) == context->accesser.tokenIdHash && accessee.GetAccesseeAccountId() == context->accessee.accountId && diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index 1029aead8..c7094be88 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -370,7 +370,6 @@ int32_t HiChainAuthConnector::QueryCredentialInfo(int32_t userId, const JsonObje // Q: 之前都是用的ProcessCredential查询,现在是否可用queryCredentialByParams查询? ret = cm->queryCredentialByParams(userId, queryParams.Dump().c_str(), &credIdList); - // TODO: 可能是空的,要返回DM_OK if (ret != DM_OK) { LOGE("HiChainAuthConnector::QueryCredentialInfo fail to query credential id list with ret %{public}d.", ret); return ERR_DM_FAILED; -- Gitee From 3a970100771c91b5fdb0a2b0a8d3ef4a70dfc3c0 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Wed, 19 Mar 2025 17:32:21 +0800 Subject: [PATCH 237/382] style adj --- .../auth_stages/auth_acl.cpp | 2 +- .../auth_stages/auth_confirm.cpp | 15 ++----------- .../auth_stages/auth_credential.cpp | 6 ++--- .../auth_stages/auth_negotiate.cpp | 12 +++++----- .../auth_stages/auth_pin_auth.cpp | 22 ++++--------------- 5 files changed, 14 insertions(+), 43 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index a40260434..0282b1104 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -125,7 +125,7 @@ int32_t AuthSrcFinishState::Action(std::shared_ptr context) } } if (srcAclList.empty()) { - LOGI("AuthSrcFinishState::Action acl is empty"); // 首次认证 无acl同步 + LOGI("AuthSrcFinishState::Action acl is empty"); // 首次认证 无acl同步 } // 比较双端的acl for (auto &srcAcl : srcAclList) { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 42735cf6b..40c561245 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -14,7 +14,6 @@ */ #include "dm_auth_state.h" -// #include "service_info_profile.h" #include "dm_auth_context.h" #include "dm_log.h" #include "dm_dialog_manager.h" @@ -22,8 +21,6 @@ #include "dm_auth_state_machine.h" #include "deviceprofile_connector.h" #include "auth_manager.h" -#undef LOG_TAG -#define LOG_TAG "DHDM_V2" namespace OHOS { namespace DistributedHardware { @@ -37,15 +34,6 @@ constexpr const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; constexpr int32_t CONFIRM_TIMEOUT = 60; std::set g_shareByPinAuthDeviceTypeSet{DmDeviceType::DEVICE_TYPE_SMART_DISPLAY}; -/* -用户授权(100和110报文处理) -source端状态: -AuthSrcConfirmState, // 收到90授权结果报文,发送100报文 - -sink端状态: -AuthSinkConfirmState, // 收到100用户授权报文,发送110报文 -*/ - DmAuthStateType AuthSrcConfirmState::GetStateType() { return DmAuthStateType::AUTH_SRC_CONFIRM_STATE; @@ -194,7 +182,8 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) return ret; } // 等待用户授权操作完成 - if(DmEventType::ON_USER_OPERATION != context->authStateMachine->WaitExpectEvent(DmEventType::ON_USER_OPERATION)) { + if (DmEventType::ON_USER_OPERATION != + context->authStateMachine->WaitExpectEvent(DmEventType::ON_USER_OPERATION)) { LOGE("AuthSinkConfirmState::Action wait ON_USER_OPERATION err"); return STOP_BIND; // 外部事件错误,中止流程 } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 6dc73f568..06b0eff09 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -25,8 +25,6 @@ #include "multiple_user_connector.h" #include "deviceprofile_connector.h" #include "hichain_auth_connector.h" -#undef LOG_TAG -#define LOG_TAG "DHDM_V2" namespace OHOS { namespace DistributedHardware { @@ -420,7 +418,7 @@ int32_t AuthSinkCredentialExchangeState::Action(std::shared_ptr c LOGI("AuthSinkCredentialExchangeState::Action start."); int32_t ret = ERR_DM_FAILED; std::string tmpCredId; - int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();; + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); context->isAppCredentialVerified = false; if (context == nullptr || context->hiChainAuthConnector == nullptr || @@ -488,7 +486,7 @@ int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr c LOGI(" AuthSrcCredentialAuthStartState::Action start."); int32_t ret = ERR_DM_FAILED; std::string tmpCredId; - int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID();; + int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); if (context == nullptr || context->hiChainAuthConnector == nullptr || context->authMessageProcessor == nullptr || context->softbusConnector == nullptr) { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 94d38dca6..79ec2003b 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -43,9 +43,6 @@ using namespace OHOS::Security::AccessToken; -#undef LOG_TAG -#define LOG_TAG "DHDM_V2" - namespace OHOS { namespace DistributedHardware { @@ -143,7 +140,8 @@ int32_t AuthSrcNegotiateStateMachine::Action(std::shared_ptr cont context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); if (context->timer != nullptr) { context->timer->StartTimer(std::string(NEGOTIATE_TIMEOUT_TASK), - DmAuthState::GetTaskTimeout(context, NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT), [this, context] (std::string name) { + DmAuthState::GetTaskTimeout(context, NEGOTIATE_TIMEOUT_TASK, NEGOTIATE_TIMEOUT), + [this, context] (std::string name) { DmAuthState::HandleAuthenticateTimeout(context, name); }); } @@ -199,9 +197,10 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptr context, const std::vector &tokenList) +bool AuthSinkNegotiateStateMachine::HaveSameTokenId(std::shared_ptr context, + const std::vector &tokenList) { - if (tokenList.size() != 2) { + if (tokenList.size() != 2) { // 2端的token LOGE("HaveSameTokenId invalid tokenList size."); return false; } @@ -211,7 +210,6 @@ bool AuthSinkNegotiateStateMachine::HaveSameTokenId(std::shared_ptraccesser.tokenIdHash) { return false; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 04f03dc9a..319a37870 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -27,8 +27,6 @@ #include "deviceprofile_connector.h" #include "dm_random.h" #include "multiple_user_connector.h" -#undef LOG_TAG -#define LOG_TAG "DHDM_V2" namespace OHOS { namespace DistributedHardware { @@ -38,19 +36,6 @@ constexpr int32_t SESSION_HEARTBEAT_TIMEOUT = 20; constexpr int32_t MIN_PIN_CODE = 100000; constexpr int32_t MAX_PIN_CODE = 999999; -/* -pin码认证(120和130报文处理、121和131报文处理) -source端状态: -AuthSrcPinAuthStartState, // 收到110授权结果报文,发送120报文 -AuthSrcPinAuthMsgNegotiateState, // 收到130认证PIN结果报文,发送121报文 -AuthSrcPinAuthDoneState, // 收到131认证PIN结果报文,调用processData - -sink端状态: -AuthSinkPinAuthStartState, // 收到120认证PIN报文,发送130报文 -AuthSinkPinAuthMsgNegotiateState, // 收到121认证PIN报文,发送131报文 -AuthSinkPinAuthDoneState, // 触发Onfinish回调事件 -*/ - int32_t AuthSinkStatePinAuthComm::ShowAuthInfoDialog(std::shared_ptr context) { LOGI("AuthSinkConfirmState::ShowAuthInfoDialog start"); @@ -64,7 +49,7 @@ int32_t AuthSinkStatePinAuthComm::ShowAuthInfoDialog(std::shared_ptrpinCode)); context->timer->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), - DmAuthState::GetTaskTimeout(context, SESSION_HEARTBEAT_TIMEOUT_TASK,SESSION_HEARTBEAT_TIMEOUT), + DmAuthState::GetTaskTimeout(context, SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [context] (std::string name) { AuthSinkStatePinAuthComm::HandleSessionHeartbeat(context, name); }); @@ -85,7 +70,7 @@ void AuthSinkStatePinAuthComm::HandleSessionHeartbeat(std::shared_ptrsoftbusConnector->GetSoftbusSession()->SendHeartbeatData(context->sessionId, message); context->timer->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), - DmAuthState::GetTaskTimeout(context, SESSION_HEARTBEAT_TIMEOUT_TASK,SESSION_HEARTBEAT_TIMEOUT), + DmAuthState::GetTaskTimeout(context, SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), [context] (std::string name) { AuthSinkStatePinAuthComm::HandleSessionHeartbeat(context, name); }); @@ -362,7 +347,8 @@ int32_t AuthSrcPinInputState::Action(std::shared_ptr context) LOGI("AuthSrcPinInputState::Action waitting user operation"); // 等待用户输密码操作完成 - if(DmEventType::ON_USER_OPERATION != context->authStateMachine->WaitExpectEvent(DmEventType::ON_USER_OPERATION)) { + if (DmEventType::ON_USER_OPERATION != + context->authStateMachine->WaitExpectEvent(DmEventType::ON_USER_OPERATION)) { LOGI("AuthSrcPinInputState::Action wait ON_USER_OPERATION err"); return STOP_BIND; // 外部事件错误,中止流程 } -- Gitee From ae8c62a04c241b54763d47aa0386a11ea7a93ea3 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Thu, 20 Mar 2025 15:02:31 +0800 Subject: [PATCH 238/382] =?UTF-8?q?=E4=BF=AE=E5=A4=8D180-200?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- common/include/dm_error_type.h | 1 - .../authentication_v2/dm_auth_context.h | 6 +- .../dm_auth_message_processor.h | 11 +- .../include/authentication_v2/dm_auth_state.h | 2 +- .../dependency/softbus/softbus_connector.h | 5 + .../auth_stages/auth_acl.cpp | 94 +++++++++---- .../auth_stages/auth_negotiate.cpp | 1 + .../dm_auth_message_processor.cpp | 132 ++++++++++++------ .../src/authentication_v2/dm_auth_state.cpp | 6 +- .../dependency/softbus/softbus_connector.cpp | 57 ++++++++ 10 files changed, 239 insertions(+), 76 deletions(-) diff --git a/common/include/dm_error_type.h b/common/include/dm_error_type.h index 5e368d757..1557ace99 100644 --- a/common/include/dm_error_type.h +++ b/common/include/dm_error_type.h @@ -21,7 +21,6 @@ namespace DistributedHardware { enum { DM_OK = 0, SOFTBUS_OK = 0, - DM_AUTHENTICATE_FINISH = 0, STOP_BIND = 1, /* Transfer to the other end device, not define specification error code */ diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 9cb528bb0..e44ee4e1f 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -134,9 +134,11 @@ struct DmAccess { std::string dmVersion; // 版本 5.1.0 std::string edition; // 用于5.1.0版本前的兼容,协助版本协商 std::string aclList; //可信关系列表,用于数据老化 KV格式 - std::vector aclChecksumList; // 可信关系列表,用于数据老化 + std::vector accesserStrList; + std::vector accesseeStrList; std::string credentialInfos; //凭据信息(点对点,同账号,..) 只保存凭据类型 kv结构 std::string extraInfo; //可扩展字段,kv结构 + std::string openAuthDeviceId; }; // TODO 统一用初始化列表进行初始化 @@ -179,8 +181,6 @@ struct DmAuthContext { DmPeerTarget peerTarget; // 对端目标的信息 DmAccess accesser; DmAccess accessee; - DmAccess encryAccesser; // 密文阶段accesser - DmAccess encryAccessee; // 密文阶段accessee std::multimap proxy; // 前面是accesser,后面是accessee std::shared_ptr authStateMachine; // 状态机 diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index c8bebde92..c96863ec9 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -207,7 +207,8 @@ public: DmAccess &access, std::string trustDeviceId); // 对acl进行checksum - std::string ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl); + bool ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl, + std::vector &accesserStrList, std::vector &accesseeStrList); // 提取本端ACL 用于消息解析和总线使用 无ACL会返回空字符串 json格式字符串:{dmversion:x,accesser:[{accesserDeviceId:y,...},...],accessee:{...}} int32_t GetAclListStr(std::shared_ptr &context, std::string &aclList); @@ -246,7 +247,7 @@ private: // 解析 190报文信息 MSG_TYPE_RESP_DATA_SYNC 存放对方密文四元组,acl sp skid int32_t ParseMessageSyncResp(const JsonObject &jsonObject, std::shared_ptr context); // 解析 200报文信息 - int32_t ParseMessageFinish(std::shared_ptr context, JsonObject &jsonObject); + int32_t ParseMessageFinish(const JsonObject &jsonObject, std::shared_ptr context); // 创建 80报文 void CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); @@ -296,6 +297,12 @@ private: 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 SetAppAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee); + void SetUserAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee); std::shared_ptr cryptoMgr_ = nullptr; }; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 583d702f4..db4b2f5ed 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -115,7 +115,7 @@ public: virtual ~DmAuthState() {}; virtual DmAuthStateType GetStateType() = 0; virtual int32_t Action(std::shared_ptr context) = 0; // 执行状态对应的action动作 - void SyncAclList(std::shared_ptr context, int32_t accountId, + void SyncAclList(std::shared_ptr context, std::string credId, int32_t sessionKeyId, int32_t aclId); static bool IsScreenLocked(); static int32_t GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut); diff --git a/services/implementation/include/dependency/softbus/softbus_connector.h b/services/implementation/include/dependency/softbus/softbus_connector.h index 996ff36df..b57ea7ae6 100644 --- a/services/implementation/include/dependency/softbus/softbus_connector.h +++ b/services/implementation/include/dependency/softbus/softbus_connector.h @@ -85,6 +85,11 @@ public: */ static void JoinLnnByHml(int32_t sessionId, int32_t sessionKeyId, int32_t remoteSessionKeyId); + static void JoinLnn(const std::string &deviceId, const std::string &remoteUdidHash); + + static void JoinLNNBySkId(int32_t sessionId, int32_t sessionKeyId, int32_t remoteSessionKeyId, + std::string udid, std::string udidHash); + public: SoftbusConnector(); ~SoftbusConnector(); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 0282b1104..59b0ad8e1 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -21,6 +21,9 @@ #include "deviceprofile_connector.h" #include "dm_auth_context.h" #include "dm_constants.h" +#include "auth_manager.h" +#include "multiple_user_connector.h" +#include "dm_crypto.h" namespace OHOS { namespace DistributedHardware { @@ -41,13 +44,13 @@ int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) { LOGI("AuthSinkDataSyncState::Action start"); // 判断密文阶段和明文阶段的四元组是否相同,不同则直接结束 - bool isSame = context->encryAccesser.deviceId == context->accesser.deviceId && - context->encryAccesser.userId == context->accesser.userId && - context->encryAccesser.accountId == context->accesser.accountId && - context->encryAccesser.tokenId == context->accesser.tokenId; + bool isSame = Crypto::Sha256(context->accesser.deviceId) == context->accesser.deviceIdHash && + Crypto::Sha256(std::to_string(context->accesser.userId)) == context->accesser.userIdHash && + Crypto::Sha256(context->accesser.accountId) == context->accesser.accountIdHash && + Crypto::Sha256(std::to_string(context->accesser.tokenId)) == context->accesser.tokenIdHash; if (!isSame) { LOGE("data between two stages different, stop auth"); - context->reply = DM_AUTHENTICATE_FINISH; + context->reply = ERR_DM_QUADRUPLE_NOT_SAME; context->reason = ERR_DM_QUADRUPLE_NOT_SAME; context->state = static_cast(GetStateType()); return ERR_DM_FAILED; @@ -69,19 +72,14 @@ int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) } // 比较双端的acl for (auto &sinkAcl : sinkAclList) { - std::string aclChecksum = context->authMessageProcessor->ChecksumAcl(sinkAcl); - auto item = find(context->encryAccesser.aclChecksumList.begin(), - context->encryAccesser.aclChecksumList.end(), aclChecksum); - if (item != context->encryAccesser.aclChecksumList.end()) { + bool res = context->authMessageProcessor->ChecksumAcl(sinkAcl, + context->accesser.accesserStrList, context->accesser.accesseeStrList); + if (res) { continue; } - SyncAclList(context, std::atoi(sinkAcl.GetAccessee().GetAccesseeAccountId().c_str()), - std::to_string(sinkAcl.GetAccessee().GetAccesseeCredentialId()), + SyncAclList(context, std::to_string(sinkAcl.GetAccessee().GetAccesseeCredentialId()), sinkAcl.GetAccessee().GetAccesseeSessionKeyId(), sinkAcl.GetAccessControlId()); } - // 保存本次acl - context->authMessageProcessor->PutAccessControlList(context, context->accessee, context->accesser.deviceId); - // 同步本端的sp信息,不确定格式,暂不做 context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_DATA_SYNC, context); @@ -99,15 +97,15 @@ int32_t AuthSrcFinishState::Action(std::shared_ptr context) { LOGI("AuthSrcFinishState::Action start"); // 判断密文阶段和明文阶段的四元组是否相同,不同则直接结束 - bool isSame = context->encryAccessee.deviceId == context->accessee.deviceId && - context->encryAccessee.userId == context->accessee.userId && - context->encryAccessee.accountId == context->accessee.accountId && - context->encryAccessee.tokenId == context->accessee.tokenId; + bool isSame = Crypto::Sha256(context->accessee.deviceId) == context->accessee.deviceIdHash && + Crypto::Sha256(std::to_string(context->accessee.userId)) == context->accessee.userIdHash && + Crypto::Sha256(context->accessee.accountId) == context->accessee.accountIdHash && + Crypto::Sha256(std::to_string(context->accessee.tokenId)) == context->accessee.tokenIdHash; if (!isSame) { LOGE("data between two stages different, stop auth"); // 不同直接结束,发送200给sink端 context->reason = ERR_DM_QUADRUPLE_NOT_SAME; - context->reply = DM_AUTHENTICATE_FINISH; + context->reply = ERR_DM_QUADRUPLE_NOT_SAME; context->state = static_cast(GetStateType()); context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_FINISH, context); return ERR_DM_FAILED; @@ -129,14 +127,12 @@ int32_t AuthSrcFinishState::Action(std::shared_ptr context) } // 比较双端的acl for (auto &srcAcl : srcAclList) { - std::string aclChecksum = context->authMessageProcessor->ChecksumAcl(srcAcl); - auto item = find(context->encryAccessee.aclChecksumList.begin(), - context->encryAccessee.aclChecksumList.end(), aclChecksum); - if (item != context->encryAccessee.aclChecksumList.end()) { + bool res = context->authMessageProcessor->ChecksumAcl(srcAcl, + context->accessee.accesserStrList, context->accessee.accesseeStrList); + if (res) { continue; } - SyncAclList(context, std::atoi(srcAcl.GetAccesser().GetAccesserAccountId().c_str()), - std::to_string(srcAcl.GetAccesser().GetAccesserCredentialId()), + SyncAclList(context, std::to_string(srcAcl.GetAccesser().GetAccesserCredentialId()), srcAcl.GetAccesser().GetAccesserSessionKeyId(), srcAcl.GetAccessControlId()); } // 保存本次acl @@ -145,10 +141,23 @@ int32_t AuthSrcFinishState::Action(std::shared_ptr context) // 触发组网 if (!context->accesser.isOnline) { - context->softbusConnector->JoinLnn(context->accessee.deviceId); + char udidHashTmp[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetUdidHash(context->accessee.deviceId, reinterpret_cast(udidHashTmp)) != DM_OK) { + LOGE("AuthSrcFinishState joinLnn get udidhash by udid: %{public}s failed", context->accessee.deviceId.c_str()); + return ERR_DM_FAILED; + } + std::string peerUdidHash = std::string(udidHashTmp); + if (AuthManager::IsHmlSessionType(context->connSessionType)) { + LOGI("AuthSrcFinishState joinLnn context.appSessionKeyId: %{public}d, ee.appSessionKeyId: %{public}d", + context->appSessionKeyId, context->accessee.appSessionKeyId); + context->softbusConnector->JoinLnnByHml(context->sessionId, context->appSessionKeyId, + context->accessee.appSessionKeyId, context->accessee.deviceId, peerUdidHash); + } else { + context->softbusConnector->JoinLnn(context->accessee.openAuthDeviceId, peerUdidHash); + } } context->reason = DM_OK; - context->reply = DM_AUTHENTICATE_FINISH; + context->reply = DM_OK; context->state = static_cast(GetStateType()); context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_FINISH, context); LOGI("AuthSrcFinishState::Action ok"); @@ -163,6 +172,20 @@ DmAuthStateType AuthSrcFinishState::GetStateType() void AuthSrcFinishState::SourceFinish(std::shared_ptr context) { + if (context->reason != DM_OK) { + int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); + // 根据凭据id 删除sink端多余的凭据 + int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, context->accesser.appCredentialId); + if (ret != DM_OK) { + LOGE("SourceFinish DeleteCredential failed."); + } + // 根据skid删除sk,删除skid + ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accesser.sessionKeyId); + if (ret != DM_OK) { + LOGE("SourceFinish DeleteSessionKey failed."); + } + } + context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); context->authStateMachine = nullptr; context->authUiStateMgr = nullptr; context->hiChainAuthConnector = nullptr; @@ -181,6 +204,9 @@ void AuthSrcFinishState::SourceFinish(std::shared_ptr context) int32_t AuthSinkFinishState::Action(std::shared_ptr context) { LOGI("AuthSinkFinishState::Action start"); + if (context->reason == DM_OK) { + context->authMessageProcessor->PutAccessControlList(context, context->accessee, context->accesser.deviceId); + } SinkFinish(context); LOGI("AuthSinkFinishState::Action ok"); return DM_OK; @@ -193,6 +219,20 @@ DmAuthStateType AuthSinkFinishState::GetStateType() void AuthSinkFinishState::SinkFinish(std::shared_ptr context) { + if (context->reason != DM_OK) { + int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); + // 根据凭据id 删除sink端多余的凭据 + int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, context->accessee.appCredentialId); + if (ret != DM_OK) { + LOGE("SinkFinish DeleteCredential failed."); + } + // 根据skid删除sk,删除skid + ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accessee.sessionKeyId); + if (ret != DM_OK) { + LOGE("SinkFinish DeleteSessionKey failed."); + } + } + context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); context->authStateMachine = nullptr; context->authUiStateMgr = nullptr; context->hiChainAuthConnector = nullptr; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 79ec2003b..5b7989eb3 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -88,6 +88,7 @@ int32_t AuthSrcStartState::Action(std::shared_ptr context) sessionId = context->softbusConnector->GetSoftbusSession() ->OpenAuthSessionWithPara(context->accessee.deviceId, context->hmlActionId, context->hmlEnable160M); } else { + context->accessee.openAuthDeviceId = context->accessee.deviceId; sessionId = context->softbusConnector->GetSoftbusSession()->OpenAuthSession(context->accessee.deviceId); } diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index f9a083afa..cf362c0f8 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -88,10 +88,9 @@ int32_t DmAuthMessageProcessor::SaveSessionKeyToDP(int32_t &skId) return DeviceProfileConnector::GetInstance().PutSessionKey(sk, skId); } -int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptr context, - DmAccess &access, std::string trustDeviceId) +void DmAuthMessageProcessor::SetAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::AccessControlProfile &profile) { - LOGI("Start."); uint32_t bindType = DM_ACROSS_ACCOUNT; if (context->accesser.accountId == "ohosAnonymousUid" || context->accessee.accountId == "ohosAnonymousUid") { bindType = DM_POINT_TO_POINT; @@ -100,36 +99,66 @@ int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptrauthResult == USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { authenticationType = ALLOW_AUTH_ALWAYS; } - DistributedDeviceProfile::Accesser accesser; + profile.SetBindType(bindType); + profile.SetAuthenticationType(authenticationType); + profile.SetStatus(ACTIVE); + profile.SetDeviceIdType((int32_t)DistributedDeviceProfile::DeviceIdType::UDID); +} + +void DmAuthMessageProcessor::SetAppAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee) +{ accesser.SetAccesserDeviceId(context->accesser.deviceId); accesser.SetAccesserUserId(context->accesser.userId); accesser.SetAccesserAccountId(context->accesser.accountId); accesser.SetAccesserTokenId(context->accesser.tokenId); accesser.SetAccesserBundleName(context->accesser.bundleName); accesser.SetAccesserDeviceName(context->accesser.deviceName); - // accesser.SetAccesserServiceId(context->accesser.serviceId); accesser.SetAccesserCredentialId(context->accesser.credentialId); - accesser.SetAccesserSessionKeyId(context->accesser.sessionKeyId); + accesser.SetAccesserSessionKeyId(context->accesser.appSessionKeyId); accesser.SetAccesserSKTimeStamp(context->accesser.skTimeStamp); - DistributedDeviceProfile::Accessee accessee; accessee.SetAccesseeDeviceId(context->accessee.deviceId); accessee.SetAccesseeUserId(context->accessee.userId); accessee.SetAccesseeAccountId(context->accessee.accountId); accessee.SetAccesseeTokenId(context->accessee.tokenId); accessee.SetAccesseeBundleName(context->accessee.bundleName); accessee.SetAccesseeDeviceName(context->accessee.deviceName); - // accessee.SetAccesseeServiceId(context->accessee.serviceId); accessee.SetAccesseeCredentialId(context->accessee.credentialId); - accessee.SetAccesseeSessionKeyId(context->accessee.sessionKeyId); + accessee.SetAccesseeSessionKeyId(context->accessee.appSessionKeyId); accessee.SetAccesseeSKTimeStamp(context->accessee.skTimeStamp); +} + +void DmAuthMessageProcessor::SetUserAccessControlList(std::shared_ptr context, + DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee) +{ + accesser.SetAccesserDeviceId(context->accesser.deviceId); + accesser.SetAccesserUserId(context->accesser.userId); + accesser.SetAccesserAccountId(context->accesser.accountId); + accesser.SetAccesserDeviceName(context->accesser.deviceName); + accesser.SetAccesserCredentialId(context->accesser.credentialId); + accesser.SetAccesserSessionKeyId(context->accesser.userSessionKeyId); + accesser.SetAccesserSKTimeStamp(context->accesser.skTimeStamp); + accessee.SetAccesseeDeviceId(context->accessee.deviceId); + accessee.SetAccesseeUserId(context->accessee.userId); + accessee.SetAccesseeAccountId(context->accessee.accountId); + accessee.SetAccesseeDeviceName(context->accessee.deviceName); + accessee.SetAccesseeCredentialId(context->accessee.credentialId); + accessee.SetAccesseeSessionKeyId(context->accessee.userSessionKeyId); + accessee.SetAccesseeSKTimeStamp(context->accessee.skTimeStamp); +} + +int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptr context, + DmAccess &access, std::string trustDeviceId) +{ + LOGI("Start."); + DistributedDeviceProfile::Accesser accesser; + DistributedDeviceProfile::Accessee accessee; + SetUserAccessControlList(context, accesser, accessee); DistributedDeviceProfile::AccessControlProfile profile; - profile.SetBindType(bindType); + SetAccessControlList(context, profile); profile.SetBindLevel(access.bindLevel); - profile.SetStatus(ACTIVE); profile.SetTrustDeviceId(trustDeviceId); - profile.SetDeviceIdType((int32_t)DistributedDeviceProfile::DeviceIdType::UDID); profile.SetDeviceIdHash(access.deviceIdHash); - profile.SetAuthenticationType(authenticationType); profile.SetAccessee(accessee); profile.SetAccesser(accesser); int32_t ret = @@ -137,6 +166,14 @@ int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptr cont return ParseMessageSyncReq(jsonObject, context); case MSG_TYPE_RESP_DATA_SYNC: return ParseMessageSyncResp(jsonObject, context); + case MSG_TYPE_AUTH_FINISH: + return ParseMessageFinish(jsonObject, context); default: break; } @@ -552,18 +591,21 @@ void DmAuthMessageProcessor::CreateMessageReqCredAuthStart(std::shared_ptr &accesserStrList, std::vector &accesseeStrList) { - std::string aclChecksum = ""; - std::string aclStr = ""; - int32_t ret = ACLToStr(acl, aclStr); - if (ret != DM_OK) { - LOGE("ChecksumAcl ACLToStr failed"); - return aclChecksum; - } - uint8_t checksum[DM_HASH_LEN] = {0}; - Crypto::DmGenerateStrHash(aclStr.data(), aclStr.size(), checksum, 32, 0); - return std::string(reinterpret_cast(checksum)); + uint8_t accesserHash[DM_HASH_LEN] = {0}; + std::string accesserStr = AccesserToStr(acl); + Crypto::DmGenerateStrHash(accesserStr.data(), accesserStr.size(), accesserHash, DM_HASH_LEN, 0); + auto accesserIter = find(accesserStrList.begin(), accesserStrList.end(), + std::string(reinterpret_cast(accesserHash))); + + uint8_t accesseeHash[DM_HASH_LEN] = {0}; + std::string accesseeStr = AccesseeToStr(acl); + Crypto::DmGenerateStrHash(accesseeStr.data(), accesseeStr.size(), accesseeHash, DM_HASH_LEN, 0); + auto accesseeIter = find(accesseeStrList.begin(), accesseeStrList.end(), + std::string(reinterpret_cast(accesseeHash))); + return (accesserIter != accesserStrList.end()) && (accesseeIter != accesseeStrList.end()); } // 创建190报文 @@ -604,12 +646,12 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr LOGE("ParseSyncMessage DM_TAG_USER_SK_ID error"); return ERR_DM_FAILED; } - context->userSessionKeyId = std::atoi(jsonObject[DM_TAG_USER_SK_ID].Get().c_str()); + access.userSessionKeyId = std::atoi(jsonObject[DM_TAG_USER_SK_ID].Get().c_str()); if (!jsonObject[DM_TAG_USER_SK_TIMESTAMP].IsString()) { LOGE("ParseSyncMessage DM_TAG_USER_SK_TIMESTAMP error"); return ERR_DM_FAILED; } - context->userSkTimeStamp = std::atoi(jsonObject[DM_TAG_USER_SK_TIMESTAMP].Get().c_str()); + access.userSkTimeStamp = std::atoi(jsonObject[DM_TAG_USER_SK_TIMESTAMP].Get().c_str()); if (!jsonObject[DM_TAG_DMVERSION].IsString()) { LOGE("ParseSyncMessage DM_TAG_DMVERSION error"); return ERR_DM_FAILED; @@ -636,21 +678,29 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr access.bindLevel = srcAccessToSync.bindLevel; access.sessionKeyId = srcAccessToSync.sessionKeyId; access.skTimeStamp = srcAccessToSync.skTimeStamp; - if (context->isOnline) { - access.appSessionKeyId = srcAccessToSync.sessionKeyId; - access.appSkTimeStamp = srcAccessToSync.skTimeStamp; - } else { - access.userSessionKeyId = srcAccessToSync.sessionKeyId; - access.userSkTimeStamp = srcAccessToSync.skTimeStamp; - } if (jsonObject[DM_TAG_PROXY].IsString()) { // 预留字段 std::string proxyInfo = jsonObject[DM_TAG_PROXY].Get(); } - if (jsonObject[DM_TAG_ACL_CHECKSUM].IsArray()) { // 再解析一次 acl + if (!jsonObject[DM_TAG_ACL_CHECKSUM].IsString()) { // 再解析一次 acl LOGE("ParseSyncMessage DM_TAG_ACL_CHECKSUM error"); return ERR_DM_FAILED; } - jsonObject[DM_TAG_ACL_CHECKSUM].Get(access.aclChecksumList); + std::string aclChecksumList = jsonObject[DM_TAG_ACL_CHECKSUM].Get(); + JsonObject aclChecksumjson(aclChecksumList); + if (aclChecksumjson.IsDiscarded()) { + LOGE("ParseSyncMessage aclChecksumjson error"); + return ERR_DM_FAILED; + } + if (!aclChecksumjson[DM_TAG_ACCESSER].IsArray()) { // 再解析一次 acl + LOGE("ParseSyncMessage DM_TAG_ACCESSER error"); + return ERR_DM_FAILED; + } + aclChecksumjson[DM_TAG_ACCESSER].Get(access.accesserStrList); + if (!aclChecksumjson[DM_TAG_ACCESSEE].IsArray()) { // 再解析一次 acl + LOGE("ParseSyncMessage DM_TAG_ACCESSEE error"); + return ERR_DM_FAILED; + } + aclChecksumjson[DM_TAG_ACCESSEE].Get(access.accesseeStrList); if (jsonObject[DM_TAG_SERVICEINFO].IsString()) { // sp 暂时没有传 std::string serviceInfo = jsonObject[DM_TAG_SERVICEINFO].Get(); } @@ -692,10 +742,10 @@ int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptrappSessionKeyId = std::atoi(jsonObject[DM_TAG_APP_SK_ID].Get().c_str()); + access.appSessionKeyId = std::atoi(jsonObject[DM_TAG_APP_SK_ID].Get().c_str()); } if (jsonObject[DM_TAG_APP_SK_TIMESTAMP].IsString()) { - context->appSkTimeStamp = std::atoi(jsonObject[DM_TAG_APP_SK_TIMESTAMP].Get().c_str()); + access.appSkTimeStamp = std::atoi(jsonObject[DM_TAG_APP_SK_TIMESTAMP].Get().c_str()); } ret = ParseSyncMessage(context, access, jsonObject); if (ret != DM_OK) { @@ -716,7 +766,7 @@ int32_t DmAuthMessageProcessor::ParseMessageSyncReq(const JsonObject &jsonObject } std::string enSyncMsg = jsonObject[DM_TAG_SYNC].Get(); // 解密数据 + 解析数据到context中 - int32_t ret = DecryptSyncMessage(context, context->encryAccesser, enSyncMsg); + int32_t ret = DecryptSyncMessage(context, context->accesser, enSyncMsg); if (ret != DM_OK) { LOGE("DecryptSyncMessage enSyncMsg error"); return ret; @@ -736,7 +786,7 @@ int32_t DmAuthMessageProcessor::ParseMessageSyncResp(const JsonObject &jsonObjec } std::string enSyncMsg = jsonObject[DM_TAG_SYNC].Get(); // 解密数据 + 解析数据到context中 - int32_t ret = DecryptSyncMessage(context, context->encryAccessee, enSyncMsg); + int32_t ret = DecryptSyncMessage(context, context->accessee, enSyncMsg); if (ret != DM_OK) { LOGE("DecryptSyncMessage enSyncMsg error"); return ret; @@ -746,8 +796,8 @@ int32_t DmAuthMessageProcessor::ParseMessageSyncResp(const JsonObject &jsonObjec } // 解析200报文 -int32_t DmAuthMessageProcessor::ParseMessageFinish(std::shared_ptr context, - JsonObject &jsonObject) +int32_t DmAuthMessageProcessor::ParseMessageFinish(const JsonObject &jsonObject, + std::shared_ptr context) { if (jsonObject[DM_TAG_REPLY].IsNumberInteger()) { context->reply = jsonObject[DM_TAG_REPLY].Get(); diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 2c1fda0ec..1c2cf553c 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -16,6 +16,7 @@ #include "dm_auth_state.h" #include "dm_auth_context.h" #include "dm_auth_state_machine.h" +#include "multiple_user_connector.h" #if defined(SUPPORT_SCREENLOCK) #include "screenlock_manager.h" #endif @@ -81,9 +82,12 @@ bool DmAuthState::IsScreenLocked() return isLocked; } -void DmAuthState::SyncAclList(std::shared_ptr context, int32_t accountId, +void DmAuthState::SyncAclList(std::shared_ptr context, std::string credId, int32_t sessionKeyId, int32_t aclId) { + int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); + LOGI("SyncAclList accountId:%{public}d, credId:%{public}s, sessionKeyId:%{public}d, aclId:%{public}d", + accountId, credId.c_str(), sessionKeyId, aclId); // 根据凭据id 删除sink端多余的凭据 int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, credId); if (ret != DM_OK) { diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 09704b418..73856ee07 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -96,6 +96,63 @@ void SoftbusConnector::JoinLnn(const std::string &deviceId, bool isForceJoin) return; } +void SoftbusConnector::JoinLnn(const std::string &deviceId, const std::string &remoteUdidHash) +{ + std::string connectAddr; + LOGI("start, deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); + ConnectionAddr *addrInfo = GetConnectAddr(deviceId, connectAddr); + if (addrInfo == nullptr) { + LOGE("addrInfo is nullptr."); + return; + } + if (Crypto::ConvertHexStringToBytes(addrInfo->info.ble.udidHash, UDID_HASH_LEN, + remoteUdidHash.c_str(), remoteUdidHash.length()) != DM_OK) { + LOGE("convert remoteUdid hash failed, remoteUdidHash_: %{public}s.", GetAnonyString(remoteUdidHash).c_str()); + return; + } + int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo, OnSoftbusJoinLNNResult, false); + if (ret != DM_OK) { + LOGE("[SOFTBUS]JoinLNN failed, ret: %{public}d.", ret); + } + return; +} + +void SoftbusConnector::JoinLNNBySkId(int32_t sessionId, int32_t sessionKeyId, int32_t remoteSessionKeyId, + std::string udid, std::string udidHash) +{ + LOGI("start, JoinLNNBySkId sessionId: %{public}d, udid: %{public}s.", sessionId, GetAnonyString(udid).c_str()); + std::string connectAddr; + ConnectionAddr *addrInfo = GetConnectAddr(udid, connectAddr); + if (addrInfo == nullptr) { + LOGE("addrInfo is nullptr."); + return; + } + if (Crypto::ConvertHexStringToBytes(addrInfo->info.ble.udidHash, UDID_HASH_LEN, + udidHash.c_str(), udidHash.length()) != DM_OK) { + LOGE("convert remoteUdid hash failed, udidHash: %{public}s.", GetAnonyString(udidHash).c_str()); + return; + } + LOGI("addrInfo->type: %{public}d", addrInfo->type); + addrInfo->info.session.sessionId = sessionId; + // addrInfo->deviceKeyId.hasDeviceKeyId = true; // 总线修改后适配 + if (sessionKeyId > 0 && remoteSessionKeyId > 0) { + addrInfo->info.session.localDeviceKeyId = sessionKeyId; + addrInfo->info.session.remoteDeviceKeyId = remoteSessionKeyId; + // addrInfo->deviceKeyId.localDeviceKeyId = sessionKeyId; // 总线修改后适配 + // addrInfo->deviceKeyId.remoteDeviceKeyId = remoteSessionKeyId; // 总线修改后适配 + LOGI("sessionKeyId valid"); + } else { + addrInfo->info.session.localDeviceKeyId = 0; + addrInfo->info.session.remoteDeviceKeyId = 0; + // addrInfo->deviceKeyId.localDeviceKeyId = 0; // 总线修改后适配 + // addrInfo->deviceKeyId.remoteDeviceKeyId = 0; // 总线修改后适配 + } + int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo, OnSoftbusJoinLNNResult, false); + if (ret != DM_OK) { + LOGE("[SOFTBUS]JoinLNNBySkId failed, ret: %{public}d.", ret); + } +} + void SoftbusConnector::JoinLnnByHml(int32_t sessionId, int32_t sessionKeyId, int32_t remoteSessionKeyId) { LOGI("start, JoinLnnByHml sessionId: %{public}d.", sessionId); -- Gitee From 4b521b97a8893666f1fca241e57ad05fd2f233cc Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 20 Mar 2025 15:49:44 +0800 Subject: [PATCH 239/382] sink idx update --- .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 8 +++++--- .../src/authentication_v2/dm_auth_message_processor.cpp | 4 ++-- 2 files changed, 7 insertions(+), 5 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 319a37870..2eb24f16f 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -377,13 +377,15 @@ int32_t AuthSinkPinNegotiateStartState::Action(std::shared_ptr co context->inputPinAuthFailTimes < MAX_AUTH_INPUT_PIN_FAIL_TIMES) { LOGI("AuthSinkPinNegotiateStartState::Action input pin auth err, retry"); } else { - if (context->currentAuthTypeIdx + 1 >= context->authTypeList.size()) { + auto idx = context->currentAuthTypeIdx; + if (idx + 1 >= context->authTypeList.size()) { LOGE("AuthSinkPinNegotiateStartState::Action all auth type failed"); context->reason = ERR_DM_AUTH_REJECT; return ERR_DM_AUTH_REJECT; } - context->currentAuthTypeIdx++; - context->authType = context->authTypeList[context->currentAuthTypeIdx]; + ++idx; + context->currentAuthTypeIdx = idx; + context->authType = context->authTypeList[idx]; } } if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index cf362c0f8..358c0db3a 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -943,7 +943,7 @@ int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const JsonObject &jso } if (json[DM_TAG_CURRENT_AUTH_TYPE_IDX].IsNumberInteger()) { auto idx = json[DM_TAG_CURRENT_AUTH_TYPE_IDX].Get(); - if (idx < context->authTypeList.size()) { + if (idx < context->authTypeList.size() && idx >= context->currentAuthTypeIdx) { context->currentAuthTypeIdx = idx; context->authType = context->authTypeList[idx]; } else { @@ -976,7 +976,7 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const JsonObject &js } if (json[DM_TAG_CURRENT_AUTH_TYPE_IDX].IsNumberInteger()) { auto idx = json[DM_TAG_CURRENT_AUTH_TYPE_IDX].Get(); - if (idx < context->authTypeList.size()) { + if (idx < context->authTypeList.size() && idx >= context->currentAuthTypeIdx) { context->currentAuthTypeIdx = idx; context->authType = context->authTypeList[idx]; } else { -- Gitee From 1b7ba31fef7811b2180590010ffee30cd6994a67 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 20 Mar 2025 16:00:41 +0800 Subject: [PATCH 240/382] style --- .../src/authentication_v2/auth_stages/auth_acl.cpp | 3 ++- .../src/authentication_v2/dm_auth_state_machine.cpp | 4 ++-- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 59b0ad8e1..95b659dd9 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -143,7 +143,8 @@ int32_t AuthSrcFinishState::Action(std::shared_ptr context) if (!context->accesser.isOnline) { char udidHashTmp[DM_MAX_DEVICE_ID_LEN] = {0}; if (Crypto::GetUdidHash(context->accessee.deviceId, reinterpret_cast(udidHashTmp)) != DM_OK) { - LOGE("AuthSrcFinishState joinLnn get udidhash by udid: %{public}s failed", context->accessee.deviceId.c_str()); + LOGE("AuthSrcFinishState joinLnn get udidhash by udid: %{public}s failed", + context->accessee.deviceId.c_str()); return ERR_DM_FAILED; } std::string peerUdidHash = std::string(udidHashTmp); diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 4dc3fb7f2..6ced4eac2 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -112,8 +112,8 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, // 收到160的处理状态,回复170 {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, - {DmAuthStateType:: - AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE, // 收到161的处理状态,回复171;发送171后收到160 回退到AUTH_SINK_CREDENTIAL_AUTH_START_STATE进行第二次凭据认证 + // 收到161的处理状态,回复171;发送171后收到160 回退到AUTH_SINK_CREDENTIAL_AUTH_START_STATE进行第二次凭据认证 + {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, {DmAuthStateType::AUTH_SINK_FINISH_STATE}}, // 收到180,回复190 -- Gitee From b72b62ffe982fafc5e2eeca361e85732b45b1d19 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Thu, 20 Mar 2025 16:49:09 +0800 Subject: [PATCH 241/382] =?UTF-8?q?=E4=BF=AE=E5=A4=8D=E7=BC=96=E8=AF=91?= =?UTF-8?q?=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_acl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 95b659dd9..f0319c73b 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -151,7 +151,7 @@ int32_t AuthSrcFinishState::Action(std::shared_ptr context) if (AuthManager::IsHmlSessionType(context->connSessionType)) { LOGI("AuthSrcFinishState joinLnn context.appSessionKeyId: %{public}d, ee.appSessionKeyId: %{public}d", context->appSessionKeyId, context->accessee.appSessionKeyId); - context->softbusConnector->JoinLnnByHml(context->sessionId, context->appSessionKeyId, + context->softbusConnector->JoinLNNBySkId(context->sessionId, context->appSessionKeyId, context->accessee.appSessionKeyId, context->accessee.deviceId, peerUdidHash); } else { context->softbusConnector->JoinLnn(context->accessee.openAuthDeviceId, peerUdidHash); -- Gitee From 3bcc6b08e40337b4add310d6b1f6d6ce9f8674fd Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 20 Mar 2025 17:18:37 +0800 Subject: [PATCH 242/382] style --- services/implementation/include/authentication_v2/auth_manager.h | 1 + .../src/authentication_v2/auth_stages/auth_confirm.cpp | 1 - 2 files changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index f39525796..0ef75d8b5 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -35,6 +35,7 @@ const int32_t MIN_PIN_TOKEN = 10000000; const int32_t MAX_PIN_TOKEN = 90000000; const int32_t NEGOTIATE_TIMEOUT = 10; const int32_t WAIT_REQUEST_TIMEOUT = 10; +constexpr int32_t CONFIRM_TIMEOUT = 60; const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; const int32_t HML_SESSION_TIMEOUT = 10; const int32_t AUTHENTICATE_TIMEOUT = 120; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 40c561245..3b02fdce5 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -31,7 +31,6 @@ constexpr const char* TAG_LOCAL_DEVICE_TYPE = "LOCALDEVICETYPE"; constexpr const char* TAG_REQUESTER = "REQUESTER"; constexpr const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; -constexpr int32_t CONFIRM_TIMEOUT = 60; std::set g_shareByPinAuthDeviceTypeSet{DmDeviceType::DEVICE_TYPE_SMART_DISPLAY}; DmAuthStateType AuthSrcConfirmState::GetStateType() -- Gitee From 47172214ab8b3ac04598ffc371a8b5c3c7b49433 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 20 Mar 2025 17:44:06 +0800 Subject: [PATCH 243/382] style --- .../implementation/include/authentication_v2/auth_manager.h | 1 + .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 2 +- 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 0ef75d8b5..bdb09dab1 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -36,6 +36,7 @@ const int32_t MAX_PIN_TOKEN = 90000000; const int32_t NEGOTIATE_TIMEOUT = 10; const int32_t WAIT_REQUEST_TIMEOUT = 10; constexpr int32_t CONFIRM_TIMEOUT = 60; +constexpr int32_t SESSION_HEARTBEAT_TIMEOUT = 50; const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; const int32_t HML_SESSION_TIMEOUT = 10; const int32_t AUTHENTICATE_TIMEOUT = 120; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 2eb24f16f..55804601b 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -27,12 +27,12 @@ #include "deviceprofile_connector.h" #include "dm_random.h" #include "multiple_user_connector.h" +#include "auth_manager.h" namespace OHOS { namespace DistributedHardware { constexpr int32_t MAX_AUTH_INPUT_PIN_FAIL_TIMES = 3; -constexpr int32_t SESSION_HEARTBEAT_TIMEOUT = 20; constexpr int32_t MIN_PIN_CODE = 100000; constexpr int32_t MAX_PIN_CODE = 999999; -- Gitee From bae10e763fb4ed177f1b2d136ad98f74c103c428 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Thu, 20 Mar 2025 21:10:17 +0800 Subject: [PATCH 244/382] =?UTF-8?q?=E4=BF=AE=E5=A4=8Djson=20obj?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/implementation/src/authentication/dm_auth_manager.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 3385c42fd..1f6b60c8e 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -2572,7 +2572,7 @@ char *DmAuthManager::AuthDeviceRequest(int64_t requestId, int operationCode, con LOGI("DmAuthManager::AuthDeviceRequest start."); (void)requestId; (void)reqParams; - nlohmann::json jsonObj; + JsonObject jsonObj; int32_t pinCode = INVALID_PINCODE; if (GetPinCode(pinCode) == ERR_DM_FAILED || pinCode == INVALID_PINCODE) { jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_REJECTED; -- Gitee From ed6018baa7adf308a89214b8540fcb705d7b6bc5 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Thu, 20 Mar 2025 21:44:18 +0800 Subject: [PATCH 245/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9json=E9=81=97?= =?UTF-8?q?=E6=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/device_manager_service_impl.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 33314b774..7cd265373 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -56,8 +56,8 @@ constexpr const char *TAG_AUTH_FINISH = "isFinish"; bool IsMessageOldVersion(int sessionId, const void *data, unsigned int dataLen) { std::string message = std::string(reinterpret_cast(data), dataLen); - nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); - if (jsonObject.is_discarded() || !IsInt32(jsonObject, TAG_MSG_TYPE)) { + JsonObject jsonObject(message); + if (jsonObject.IsDiscarded() || !IsInt32(jsonObject, TAG_MSG_TYPE)) { LOGE("IsMessageOldVersion decode jsonStr error"); return false; } @@ -87,7 +87,7 @@ bool IsMessageOldVersion(int sessionId, const void *data, unsigned int dataLen) std::string CreateTerminateMessage(void) { - nlohmann::json jsonObject; + JsonObject jsonObject; jsonObject[TAG_MSG_TYPE] = MSG_TYPE_REQ_AUTH_TERMINATE; jsonObject[DM_TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE; jsonObject[TAG_AUTH_FINISH] = false; @@ -429,8 +429,8 @@ int32_t DeviceManagerServiceImpl::CreateAuthMgrByMessage(int sessionId, const vo } std::string message = std::string(reinterpret_cast(data), dataLen); - nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); - if (jsonObject.is_discarded()) { + JsonObject jsonObject(message); + if (jsonObject.IsDiscarded()) { LOGE("DeviceManagerServiceImpl::CreateAuthMgrByMessage decode jsonStr error"); return ERR_DM_JSON_PARSE_STRING; } @@ -470,7 +470,7 @@ bool IsAuthManagerSourceByMessage(const void *data, unsigned int dataLen) { std::string message = std::string(reinterpret_cast(data), dataLen); // 走到这里已经确认可以转json,所以不需要再判断 - nlohmann::json jsonObject = nlohmann::json::parse(message, nullptr, false); + JsonObject jsonObject(message); return jsonObject[TAG_MSG_TYPE].get() == MSG_TYPE_RESP_ACL_NEGOTIATE; } -- Gitee From fbb04a3f15f433ccdfe82a20a262734ae5de001a Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Thu, 20 Mar 2025 21:48:31 +0800 Subject: [PATCH 246/382] =?UTF-8?q?BUGFIX:=E4=BF=AE=E6=94=B9json=E9=81=97?= =?UTF-8?q?=E6=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/device_manager_service_impl.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 7cd265373..c6713ab1e 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -62,18 +62,18 @@ bool IsMessageOldVersion(int sessionId, const void *data, unsigned int dataLen) return false; } - if (jsonObject[TAG_MSG_TYPE].get() != MSG_TYPE_REQ_ACL_NEGOTIATE && - jsonObject[TAG_MSG_TYPE].get() != MSG_TYPE_RESP_ACL_NEGOTIATE) { + if (jsonObject[TAG_MSG_TYPE].Get() != MSG_TYPE_REQ_ACL_NEGOTIATE && + jsonObject[TAG_MSG_TYPE].Get() != MSG_TYPE_RESP_ACL_NEGOTIATE) { return false; } std::string dmVersion = ""; std::string edition = ""; if (IsString(jsonObject, DM_TAG_DMVERSION)) { - dmVersion = jsonObject[DM_TAG_DMVERSION].get(); + dmVersion = jsonObject[DM_TAG_DMVERSION].Get(); } if (IsString(jsonObject, DM_TAG_EDITION)) { - edition = jsonObject[DM_TAG_EDITION].get(); + edition = jsonObject[DM_TAG_EDITION].Get(); } dmVersion = AuthManagerBase::ConvertSrcVersion(dmVersion, edition); @@ -442,9 +442,9 @@ int32_t DeviceManagerServiceImpl::CreateAuthMgrByMessage(int sessionId, const vo LOGE("DeviceManagerServiceImpl::CreateAuthMgrByMessage decode dmversion error"); return ERR_DM_JSON_PARSE_STRING; } - dmVersion = jsonObject[DM_TAG_DMVERSION].get(); + dmVersion = jsonObject[DM_TAG_DMVERSION].Get(); if (IsString(jsonObject, DM_TAG_EDITION)) { - edition = jsonObject[DM_TAG_EDITION].get(); + edition = jsonObject[DM_TAG_EDITION].Get(); } dmVersion = AuthManagerBase::ConvertSrcVersion(dmVersion, edition); @@ -472,7 +472,7 @@ bool IsAuthManagerSourceByMessage(const void *data, unsigned int dataLen) // 走到这里已经确认可以转json,所以不需要再判断 JsonObject jsonObject(message); - return jsonObject[TAG_MSG_TYPE].get() == MSG_TYPE_RESP_ACL_NEGOTIATE; + return jsonObject[TAG_MSG_TYPE].Get() == MSG_TYPE_RESP_ACL_NEGOTIATE; } void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) -- Gitee From c9c9d89551457e56219bca9bfa4b737f7f5a3dcd Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Thu, 20 Mar 2025 21:51:55 +0800 Subject: [PATCH 247/382] =?UTF-8?q?BUGFIX:json=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/implementation/src/device_manager_service_impl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index c6713ab1e..c0ff40053 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -92,7 +92,7 @@ std::string CreateTerminateMessage(void) jsonObject[DM_TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE; jsonObject[TAG_AUTH_FINISH] = false; - return jsonObject.dump(); + return SafetyDump(jsonObject); } } -- Gitee From 969c8da31d651ad92a24f920f78416d2d5ff4aaa Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Fri, 21 Mar 2025 11:31:13 +0800 Subject: [PATCH 248/382] =?UTF-8?q?=E4=B8=B4=E6=97=B6=E9=80=82=E9=85=8D?= =?UTF-8?q?=E6=80=BB=E7=BA=BF=E7=BA=BF=E4=B8=8B=E5=8C=85=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependency/softbus/softbus_connector.cpp | 18 +++++++++--------- 1 file changed, 9 insertions(+), 9 deletions(-) diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 73856ee07..9d1ae5811 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -134,18 +134,18 @@ void SoftbusConnector::JoinLNNBySkId(int32_t sessionId, int32_t sessionKeyId, in } LOGI("addrInfo->type: %{public}d", addrInfo->type); addrInfo->info.session.sessionId = sessionId; - // addrInfo->deviceKeyId.hasDeviceKeyId = true; // 总线修改后适配 + addrInfo->deviceKeyId.hasDeviceKeyId = true; // 总线修改后适配 if (sessionKeyId > 0 && remoteSessionKeyId > 0) { - addrInfo->info.session.localDeviceKeyId = sessionKeyId; - addrInfo->info.session.remoteDeviceKeyId = remoteSessionKeyId; - // addrInfo->deviceKeyId.localDeviceKeyId = sessionKeyId; // 总线修改后适配 - // addrInfo->deviceKeyId.remoteDeviceKeyId = remoteSessionKeyId; // 总线修改后适配 + // addrInfo->info.session.localDeviceKeyId = sessionKeyId; + // addrInfo->info.session.remoteDeviceKeyId = remoteSessionKeyId; + addrInfo->deviceKeyId.localDeviceKeyId = sessionKeyId; // 总线修改后适配 + addrInfo->deviceKeyId.remoteDeviceKeyId = remoteSessionKeyId; // 总线修改后适配 LOGI("sessionKeyId valid"); } else { - addrInfo->info.session.localDeviceKeyId = 0; - addrInfo->info.session.remoteDeviceKeyId = 0; - // addrInfo->deviceKeyId.localDeviceKeyId = 0; // 总线修改后适配 - // addrInfo->deviceKeyId.remoteDeviceKeyId = 0; // 总线修改后适配 + // addrInfo->info.session.localDeviceKeyId = 0; + // addrInfo->info.session.remoteDeviceKeyId = 0; + addrInfo->deviceKeyId.localDeviceKeyId = 0; // 总线修改后适配 + addrInfo->deviceKeyId.remoteDeviceKeyId = 0; // 总线修改后适配 } int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo, OnSoftbusJoinLNNResult, false); if (ret != DM_OK) { -- Gitee From d2e4b532003730c00d977adaad55d5367112a5a7 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 21 Mar 2025 16:18:18 +0800 Subject: [PATCH 249/382] stop HEARTBEAT_TIMEOUT task when finished --- .../include/authentication_v2/dm_auth_context.h | 1 + .../src/authentication_v2/auth_stages/auth_acl.cpp | 2 ++ .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 4 ++-- 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index e44ee4e1f..e54f22d4b 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -166,6 +166,7 @@ struct DmAuthContext { int32_t hmlActionId = 0; bool normalFinishAuth; // 标识认证过程是否正常结束 bool authenticating; // 标识正在认证中 + bool isFinished{false}; // 是否走到完成状态 bool isAppCredentialVerified = false; // 应用凭据是否认证 bool hmlEnable160M = false; std::string sessionName; // 业务传入的标识,业务自定义,有被仿冒的风险 diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index f0319c73b..d788209bc 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -96,6 +96,7 @@ DmAuthStateType AuthSinkDataSyncState::GetStateType() int32_t AuthSrcFinishState::Action(std::shared_ptr context) { LOGI("AuthSrcFinishState::Action start"); + context->isFinished = true; // 判断密文阶段和明文阶段的四元组是否相同,不同则直接结束 bool isSame = Crypto::Sha256(context->accessee.deviceId) == context->accessee.deviceIdHash && Crypto::Sha256(std::to_string(context->accessee.userId)) == context->accessee.userIdHash && @@ -205,6 +206,7 @@ void AuthSrcFinishState::SourceFinish(std::shared_ptr context) int32_t AuthSinkFinishState::Action(std::shared_ptr context) { LOGI("AuthSinkFinishState::Action start"); + context->isFinished = true; if (context->reason == DM_OK) { context->authMessageProcessor->PutAccessControlList(context, context->accessee, context->accesser.deviceId); } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 55804601b..e21550d3c 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -58,10 +58,10 @@ int32_t AuthSinkStatePinAuthComm::ShowAuthInfoDialog(std::shared_ptr context, std::string name) { - if (context->timer == nullptr) { + context->timer->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK)); + if (context->isFinished) { return; } - context->timer->DeleteTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK)); LOGI("DmAuthManager::HandleSessionHeartbeat name %{public}s", name.c_str()); JsonObject jsonObj; -- Gitee From 811387dd69e4fada3bd92a84f3a4dfabecf9c6a0 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 21 Mar 2025 16:55:13 +0800 Subject: [PATCH 250/382] pin input add timeout timer --- .../include/authentication_v2/auth_manager.h | 1 + .../include/authentication_v2/dm_auth_state.h | 1 + .../authentication_v2/auth_stages/auth_pin_auth.cpp | 12 ++++++++++++ 3 files changed, 14 insertions(+) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index bdb09dab1..ea7213be2 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -37,6 +37,7 @@ const int32_t NEGOTIATE_TIMEOUT = 10; const int32_t WAIT_REQUEST_TIMEOUT = 10; constexpr int32_t CONFIRM_TIMEOUT = 60; constexpr int32_t SESSION_HEARTBEAT_TIMEOUT = 50; +const int32_t INPUT_TIMEOUT = 60; const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; const int32_t HML_SESSION_TIMEOUT = 10; const int32_t AUTHENTICATE_TIMEOUT = 120; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index db4b2f5ed..421f49ee0 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -28,6 +28,7 @@ constexpr const char* AUTHENTICATE_TIMEOUT_TASK = "deviceManagerTimer:authentica constexpr const char* NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:negotiate"; constexpr const char* CONFIRM_TIMEOUT_TASK = "deviceManagerTimer:confirm"; constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; +constexpr const char* INPUT_TIMEOUT_TASK = "deviceManagerTimer:input"; constexpr const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; constexpr const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; constexpr const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index e21550d3c..35d460158 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -334,6 +334,12 @@ int32_t AuthSrcPinInputState::ShowStartAuthDialog(std::shared_ptr int32_t AuthSrcPinInputState::Action(std::shared_ptr context) { LOGI("AuthSrcPinInputState::Action start"); + context->timer->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); + context->timer->StartTimer(std::string(INPUT_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), + [context] (std::string name) { + HandleAuthenticateTimeout(context, name); + }); if (context->inputPinAuthFailTimes == 0) { // 拉起PIN码输入界面 auto ret = ShowStartAuthDialog(context); @@ -409,6 +415,12 @@ DmAuthStateType AuthSinkPinDisplayState::GetStateType() int32_t AuthSinkPinDisplayState::Action(std::shared_ptr context) { + context->timer->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); + context->timer->StartTimer(std::string(INPUT_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), + [context] (std::string name) { + HandleAuthenticateTimeout(context, name); + }); if (context->inputPinAuthFailTimes == 0) { // 生成PIN码 AuthSinkStatePinAuthComm::GeneratePincode(context); -- Gitee From 1ec3c3bc86ea7a7f85cacae8dbb8bc8b8cd96924 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 21 Mar 2025 17:17:49 +0800 Subject: [PATCH 251/382] pin auth add timeout timer --- .../include/authentication_v2/auth_manager.h | 2 +- .../include/authentication_v2/dm_auth_state.h | 1 - .../auth_stages/auth_pin_auth.cpp | 34 +++++++++++-------- .../src/authentication_v2/dm_auth_state.cpp | 2 ++ 4 files changed, 23 insertions(+), 16 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index ea7213be2..13bedf0e5 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -37,7 +37,7 @@ const int32_t NEGOTIATE_TIMEOUT = 10; const int32_t WAIT_REQUEST_TIMEOUT = 10; constexpr int32_t CONFIRM_TIMEOUT = 60; constexpr int32_t SESSION_HEARTBEAT_TIMEOUT = 50; -const int32_t INPUT_TIMEOUT = 60; +const int32_t AUTH_DEVICE_TIMEOUT = 30; const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; const int32_t HML_SESSION_TIMEOUT = 10; const int32_t AUTHENTICATE_TIMEOUT = 120; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 421f49ee0..db4b2f5ed 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -28,7 +28,6 @@ constexpr const char* AUTHENTICATE_TIMEOUT_TASK = "deviceManagerTimer:authentica constexpr const char* NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:negotiate"; constexpr const char* CONFIRM_TIMEOUT_TASK = "deviceManagerTimer:confirm"; constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; -constexpr const char* INPUT_TIMEOUT_TASK = "deviceManagerTimer:input"; constexpr const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; constexpr const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; constexpr const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 35d460158..444bc6435 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -121,7 +121,14 @@ int32_t AuthSinkPinAuthStartState::Action(std::shared_ptr context { LOGI("AuthSinkPinAuthStartState::Action start"); context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); - context->pinNegotiateStarted = true; + if (!context->pinNegotiateStarted) { + context->pinNegotiateStarted = true; + context->timer->StartTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, AUTH_DEVICE_TIMEOUT_TASK, AUTH_DEVICE_TIMEOUT), + [context] (std::string name) { + HandleAuthenticateTimeout(context, name); + }); + } auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); if (ret != DM_OK) { LOGE("AuthSinkPinAuthStartState::Action call ProcessCredData err"); @@ -299,7 +306,12 @@ int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr con context->authType = context->authTypeList[context->currentAuthTypeIdx]; } } - + context->timer->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK)); + context->timer->StartTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, AUTH_DEVICE_TIMEOUT_TASK, AUTH_DEVICE_TIMEOUT), + [context] (std::string name) { + HandleAuthenticateTimeout(context, name); + }); if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { context->authStateMachine->TransitionTo(std::make_shared()); } else if (context->authType == DmAuthType::AUTH_TYPE_PIN) { @@ -334,12 +346,6 @@ int32_t AuthSrcPinInputState::ShowStartAuthDialog(std::shared_ptr int32_t AuthSrcPinInputState::Action(std::shared_ptr context) { LOGI("AuthSrcPinInputState::Action start"); - context->timer->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); - context->timer->StartTimer(std::string(INPUT_TIMEOUT_TASK), - DmAuthState::GetTaskTimeout(context, INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), - [context] (std::string name) { - HandleAuthenticateTimeout(context, name); - }); if (context->inputPinAuthFailTimes == 0) { // 拉起PIN码输入界面 auto ret = ShowStartAuthDialog(context); @@ -394,6 +400,12 @@ int32_t AuthSinkPinNegotiateStartState::Action(std::shared_ptr co context->authType = context->authTypeList[idx]; } } + context->timer->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK)); + context->timer->StartTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, AUTH_DEVICE_TIMEOUT_TASK, AUTH_DEVICE_TIMEOUT), + [context] (std::string name) { + HandleAuthenticateTimeout(context, name); + }); if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { LOGI("AuthSinkPinNegotiateStartState::Action import auth code"); } else if (context->authType == DmAuthType::AUTH_TYPE_PIN) { @@ -415,12 +427,6 @@ DmAuthStateType AuthSinkPinDisplayState::GetStateType() int32_t AuthSinkPinDisplayState::Action(std::shared_ptr context) { - context->timer->DeleteTimer(std::string(INPUT_TIMEOUT_TASK)); - context->timer->StartTimer(std::string(INPUT_TIMEOUT_TASK), - DmAuthState::GetTaskTimeout(context, INPUT_TIMEOUT_TASK, INPUT_TIMEOUT), - [context] (std::string name) { - HandleAuthenticateTimeout(context, name); - }); if (context->inputPinAuthFailTimes == 0) { // 生成PIN码 AuthSinkStatePinAuthComm::GeneratePincode(context); diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 1c2cf553c..4ee472772 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -37,6 +37,7 @@ const int32_t CLONE_ADD_TIMEOUT = 10; const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10; const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10; const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20; +const int32_t CLONE_AUTH_DEVICE_TIMEOUT = 10; } @@ -48,6 +49,7 @@ const std::map TASK_TIME_OUT_MAP = { { std::string(ADD_TIMEOUT_TASK), CLONE_ADD_TIMEOUT }, { std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), CLONE_WAIT_NEGOTIATE_TIMEOUT }, { std::string(WAIT_REQUEST_TIMEOUT_TASK), CLONE_WAIT_REQUEST_TIMEOUT }, + { std::string(AUTH_DEVICE_TIMEOUT_TASK), CLONE_AUTH_DEVICE_TIMEOUT }, { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT } }; -- Gitee From 57fd94107d6da3188ccb2bae1dda7d5a5d5c2300 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 21 Mar 2025 17:35:44 +0800 Subject: [PATCH 252/382] style:pin auth timer rename --- .../include/authentication_v2/auth_manager.h | 2 +- .../include/authentication_v2/dm_auth_state.h | 1 + .../auth_stages/auth_pin_auth.cpp | 16 ++++++++-------- .../src/authentication_v2/dm_auth_state.cpp | 4 ++-- 4 files changed, 12 insertions(+), 11 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 13bedf0e5..aeb6a3b12 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -37,7 +37,7 @@ const int32_t NEGOTIATE_TIMEOUT = 10; const int32_t WAIT_REQUEST_TIMEOUT = 10; constexpr int32_t CONFIRM_TIMEOUT = 60; constexpr int32_t SESSION_HEARTBEAT_TIMEOUT = 50; -const int32_t AUTH_DEVICE_TIMEOUT = 30; +const int32_t PIN_AUTH_TIMEOUT = 60; const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; const int32_t HML_SESSION_TIMEOUT = 10; const int32_t AUTHENTICATE_TIMEOUT = 120; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index db4b2f5ed..b81ec91c7 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -30,6 +30,7 @@ constexpr const char* CONFIRM_TIMEOUT_TASK = "deviceManagerTimer:confirm"; constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; constexpr const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; constexpr const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; +constexpr const char* WAIT_PIN_AUTH_TIMEOUT_TASK = "deviceManagerTimer:waitPinAuth"; constexpr const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; constexpr const char* ADD_TIMEOUT_TASK = "deviceManagerTimer:add"; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 444bc6435..663a9671e 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -123,8 +123,8 @@ int32_t AuthSinkPinAuthStartState::Action(std::shared_ptr context context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); if (!context->pinNegotiateStarted) { context->pinNegotiateStarted = true; - context->timer->StartTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK), - DmAuthState::GetTaskTimeout(context, AUTH_DEVICE_TIMEOUT_TASK, AUTH_DEVICE_TIMEOUT), + context->timer->StartTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, WAIT_PIN_AUTH_TIMEOUT_TASK, PIN_AUTH_TIMEOUT), [context] (std::string name) { HandleAuthenticateTimeout(context, name); }); @@ -306,9 +306,9 @@ int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr con context->authType = context->authTypeList[context->currentAuthTypeIdx]; } } - context->timer->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK)); - context->timer->StartTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK), - DmAuthState::GetTaskTimeout(context, AUTH_DEVICE_TIMEOUT_TASK, AUTH_DEVICE_TIMEOUT), + context->timer->DeleteTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK)); + context->timer->StartTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, WAIT_PIN_AUTH_TIMEOUT_TASK, PIN_AUTH_TIMEOUT), [context] (std::string name) { HandleAuthenticateTimeout(context, name); }); @@ -400,9 +400,9 @@ int32_t AuthSinkPinNegotiateStartState::Action(std::shared_ptr co context->authType = context->authTypeList[idx]; } } - context->timer->DeleteTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK)); - context->timer->StartTimer(std::string(AUTH_DEVICE_TIMEOUT_TASK), - DmAuthState::GetTaskTimeout(context, AUTH_DEVICE_TIMEOUT_TASK, AUTH_DEVICE_TIMEOUT), + context->timer->DeleteTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK)); + context->timer->StartTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, WAIT_PIN_AUTH_TIMEOUT_TASK, PIN_AUTH_TIMEOUT), [context] (std::string name) { HandleAuthenticateTimeout(context, name); }); diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 4ee472772..fde57c866 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -37,7 +37,7 @@ const int32_t CLONE_ADD_TIMEOUT = 10; const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10; const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10; const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20; -const int32_t CLONE_AUTH_DEVICE_TIMEOUT = 10; +const int32_t CLONE_PIN_AUTH_TIMEOUT = 10; } @@ -49,7 +49,7 @@ const std::map TASK_TIME_OUT_MAP = { { std::string(ADD_TIMEOUT_TASK), CLONE_ADD_TIMEOUT }, { std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), CLONE_WAIT_NEGOTIATE_TIMEOUT }, { std::string(WAIT_REQUEST_TIMEOUT_TASK), CLONE_WAIT_REQUEST_TIMEOUT }, - { std::string(AUTH_DEVICE_TIMEOUT_TASK), CLONE_AUTH_DEVICE_TIMEOUT }, + { std::string(WAIT_PIN_AUTH_TIMEOUT_TASK), CLONE_PIN_AUTH_TIMEOUT }, { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT } }; -- Gitee From c114342e7e878f79e7d5efc985fe9cac63638658 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Fri, 21 Mar 2025 17:50:40 +0800 Subject: [PATCH 253/382] =?UTF-8?q?=E6=B7=BB=E5=8A=A0201=E6=8A=A5=E6=96=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../dm_auth_message_processor.h | 7 +- .../include/authentication_v2/dm_auth_state.h | 26 +++-- .../authentication_v2/dm_auth_state_machine.h | 5 +- .../auth_stages/auth_acl.cpp | 109 +++++------------- .../dm_auth_message_processor.cpp | 30 ++++- .../src/authentication_v2/dm_auth_state.cpp | 43 +++++++ .../dm_auth_state_machine.cpp | 4 +- 7 files changed, 126 insertions(+), 98 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index c96863ec9..5d9cebbd9 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -145,7 +145,8 @@ enum DmMessageType { MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE = 171, MSG_TYPE_REQ_DATA_SYNC = 180, MSG_TYPE_RESP_DATA_SYNC = 190, - MSG_TYPE_AUTH_FINISH = 200, + MSG_TYPE_AUTH_REQ_FINISH = 200, + MSG_TYPE_AUTH_RESP_FINISH = 201, }; struct DmAccessControlTable { @@ -247,7 +248,9 @@ private: // 解析 190报文信息 MSG_TYPE_RESP_DATA_SYNC 存放对方密文四元组,acl sp skid int32_t ParseMessageSyncResp(const JsonObject &jsonObject, std::shared_ptr context); // 解析 200报文信息 - int32_t ParseMessageFinish(const JsonObject &jsonObject, std::shared_ptr context); + int32_t ParseMessageSinkFinish(const JsonObject &jsonObject, std::shared_ptr context); + // 解析 201报文信息 + int32_t ParseMessageSrcFinish(const JsonObject &jsonObject, std::shared_ptr context); // 创建 80报文 void CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index b81ec91c7..78b3332de 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -51,8 +51,8 @@ enum class DmAuthStateType { 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, // 触发Onfinish回调事件,发送180报文 todo 可以删除 - AUTH_SRC_FINISH_STATE = 15, // 收到190报文,发送200报文 + AUTH_SRC_DATA_SYNC_STATE = 14, // 收到190报文,发送200报文 + AUTH_SRC_FINISH_STATE = 15, // 收到201报文 // sink端的状态 AUTH_SINK_START_STATE = 50, // 总线触发OnSessionOpened @@ -68,7 +68,7 @@ enum class DmAuthStateType { 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结束报文 + AUTH_SINK_FINISH_STATE = 63, // 收到200结束报文, 发送201报文 }; // 凭据添加方式 @@ -118,6 +118,8 @@ public: 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); @@ -356,22 +358,28 @@ class AuthSinkDataSyncState : public DmAuthState { int32_t Action(std::shared_ptr context) override; }; -// AuthSrcFinishState // 收到190报文,发送200报文 -class AuthSrcFinishState : public DmAuthState { +// AuthSrcDataSyncState // 收到190报文,发送200报文 +class AuthSrcDataSyncState : public DmAuthState { public: - virtual ~AuthSrcFinishState() {}; + virtual ~AuthSrcDataSyncState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; - void SourceFinish(std::shared_ptr context); }; -// AuthSinkFinishState // 收到200结束报文 +// AuthSinkFinishState // 收到200结束报文,发送201 sink结束 class AuthSinkFinishState : public DmAuthState { public: virtual ~AuthSinkFinishState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; - void SinkFinish(std::shared_ptr context); +}; + +// 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 diff --git a/services/implementation/include/authentication_v2/dm_auth_state_machine.h b/services/implementation/include/authentication_v2/dm_auth_state_machine.h index b9e51ab10..5029c1c81 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state_machine.h +++ b/services/implementation/include/authentication_v2/dm_auth_state_machine.h @@ -63,11 +63,12 @@ public: void NotifyEventFinish(DmEventType eventType); // 获取当前状态 DmAuthStateType GetCurState(); + // 停止线程 + void Stop(); private: // 循环等待状态转移,执行action void Run(std::shared_ptr context); - // 停止线程 - void Stop(); + // 获取状态,进行执行 std::optional> FetchState(); // 设置当前状态 diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index d788209bc..f34a77b81 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -30,12 +30,12 @@ namespace DistributedHardware { /* 数据同步,ACL老化与保存(180、190和200报文处理) source端状态: -AuthSrcDataSyncState, // 触发Onfinish回调事件,发送180报文 -AuthSrcFinishState, // 收到190报文,发送200报文 +AuthSrcDataSyncState, // 收到190报文,发送200报文 +AuthSrcFinishState, // 收到201结束报文 sink端状态: AuthSinkDataSyncState, // 收到180同步报文,发送190报文 -AuthSinkFinishState, // 收到200结束报文 +AuthSinkFinishState, // 收到200结束报文 发送201 */ const int32_t USLEEP_TIME_US_500000 = 500000; // 500ms @@ -53,7 +53,8 @@ int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) context->reply = ERR_DM_QUADRUPLE_NOT_SAME; context->reason = ERR_DM_QUADRUPLE_NOT_SAME; context->state = static_cast(GetStateType()); - return ERR_DM_FAILED; + SinkFinish(context); // sink端异常时,sink结束,清理凭据,skid,停止计时器,发送201给source + return DM_OK; } // 查询sink端acl std::vector profiles = @@ -93,10 +94,9 @@ DmAuthStateType AuthSinkDataSyncState::GetStateType() } // 收到190报文,发送200报文 -int32_t AuthSrcFinishState::Action(std::shared_ptr context) +int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) { - LOGI("AuthSrcFinishState::Action start"); - context->isFinished = true; + LOGI("AuthSrcDataSyncState::Action start"); // 判断密文阶段和明文阶段的四元组是否相同,不同则直接结束 bool isSame = Crypto::Sha256(context->accessee.deviceId) == context->accessee.deviceIdHash && Crypto::Sha256(std::to_string(context->accessee.userId)) == context->accessee.userIdHash && @@ -108,8 +108,8 @@ int32_t AuthSrcFinishState::Action(std::shared_ptr context) context->reason = ERR_DM_QUADRUPLE_NOT_SAME; context->reply = ERR_DM_QUADRUPLE_NOT_SAME; context->state = static_cast(GetStateType()); - context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_FINISH, context); - return ERR_DM_FAILED; + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_REQ_FINISH, context); // source异常时,source不结束,发送200给sink,等sink回201 + return DM_OK; } // 查询sink端acl std::vector profiles = @@ -124,7 +124,7 @@ int32_t AuthSrcFinishState::Action(std::shared_ptr context) } } if (srcAclList.empty()) { - LOGI("AuthSrcFinishState::Action acl is empty"); // 首次认证 无acl同步 + LOGI("AuthSrcDataSyncState::Action acl is empty"); // 首次认证 无acl同步 } // 比较双端的acl for (auto &srcAcl : srcAclList) { @@ -144,15 +144,14 @@ int32_t AuthSrcFinishState::Action(std::shared_ptr context) if (!context->accesser.isOnline) { char udidHashTmp[DM_MAX_DEVICE_ID_LEN] = {0}; if (Crypto::GetUdidHash(context->accessee.deviceId, reinterpret_cast(udidHashTmp)) != DM_OK) { - LOGE("AuthSrcFinishState joinLnn get udidhash by udid: %{public}s failed", - context->accessee.deviceId.c_str()); + LOGE("AuthSrcDataSyncState joinLnn get udidhash by udid: %{public}s failed", context->accessee.deviceId.c_str()); return ERR_DM_FAILED; } std::string peerUdidHash = std::string(udidHashTmp); if (AuthManager::IsHmlSessionType(context->connSessionType)) { - LOGI("AuthSrcFinishState joinLnn context.appSessionKeyId: %{public}d, ee.appSessionKeyId: %{public}d", + LOGI("AuthSrcDataSyncState joinLnn context.appSessionKeyId: %{public}d, ee.appSessionKeyId: %{public}d", context->appSessionKeyId, context->accessee.appSessionKeyId); - context->softbusConnector->JoinLNNBySkId(context->sessionId, context->appSessionKeyId, + context->softbusConnector->JoinLnnByHml(context->sessionId, context->appSessionKeyId, context->accessee.appSessionKeyId, context->accessee.deviceId, peerUdidHash); } else { context->softbusConnector->JoinLnn(context->accessee.openAuthDeviceId, peerUdidHash); @@ -161,55 +160,21 @@ int32_t AuthSrcFinishState::Action(std::shared_ptr context) context->reason = DM_OK; context->reply = DM_OK; context->state = static_cast(GetStateType()); - context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_FINISH, context); - LOGI("AuthSrcFinishState::Action ok"); - SourceFinish(context); + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_REQ_FINISH, context); + LOGI("AuthSrcDataSyncState::Action ok"); return DM_OK; } -DmAuthStateType AuthSrcFinishState::GetStateType() -{ - return DmAuthStateType::AUTH_SRC_FINISH_STATE; -} - -void AuthSrcFinishState::SourceFinish(std::shared_ptr context) +DmAuthStateType AuthSrcDataSyncState::GetStateType() { - if (context->reason != DM_OK) { - int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); - // 根据凭据id 删除sink端多余的凭据 - int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, context->accesser.appCredentialId); - if (ret != DM_OK) { - LOGE("SourceFinish DeleteCredential failed."); - } - // 根据skid删除sk,删除skid - ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accesser.sessionKeyId); - if (ret != DM_OK) { - LOGE("SourceFinish DeleteSessionKey failed."); - } - } - context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); - context->authStateMachine = nullptr; - context->authUiStateMgr = nullptr; - context->hiChainAuthConnector = nullptr; - context->authMessageProcessor = nullptr; - usleep(USLEEP_TIME_US_500000); // 500ms - context->softbusConnector->GetSoftbusSession()->CloseAuthSession(context->sessionId); - context->softbusConnector = nullptr; - context->listener = nullptr; - context->authPtr = nullptr; - context->timer->DeleteAll(); - context->timer = nullptr; - context = nullptr; + return AuthSrcDataSyncState::AUTH_SRC_DATA_SYNC_STATE; } -// 收到200结束报文 +// 收到200结束报文 发送201 int32_t AuthSinkFinishState::Action(std::shared_ptr context) { LOGI("AuthSinkFinishState::Action start"); - context->isFinished = true; - if (context->reason == DM_OK) { - context->authMessageProcessor->PutAccessControlList(context, context->accessee, context->accesser.deviceId); - } + context->state = static_cast(GetStateType()); SinkFinish(context); LOGI("AuthSinkFinishState::Action ok"); return DM_OK; @@ -220,32 +185,18 @@ DmAuthStateType AuthSinkFinishState::GetStateType() return DmAuthStateType::AUTH_SINK_FINISH_STATE; } -void AuthSinkFinishState::SinkFinish(std::shared_ptr context) +// 收到201结束报文 +int32_t AuthSrcFinishState::Action(std::shared_ptr context) { - if (context->reason != DM_OK) { - int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); - // 根据凭据id 删除sink端多余的凭据 - int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, context->accessee.appCredentialId); - if (ret != DM_OK) { - LOGE("SinkFinish DeleteCredential failed."); - } - // 根据skid删除sk,删除skid - ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accessee.sessionKeyId); - if (ret != DM_OK) { - LOGE("SinkFinish DeleteSessionKey failed."); - } - } - context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); - context->authStateMachine = nullptr; - context->authUiStateMgr = nullptr; - context->hiChainAuthConnector = nullptr; - context->authMessageProcessor = nullptr; - context->softbusConnector = nullptr; - context->listener = nullptr; - context->authPtr = nullptr; - context->timer->DeleteAll(); - context->timer = nullptr; - context = nullptr; + LOGI("AuthSrcFinishState::Action start"); + SourceFinish(context); + LOGI("AuthSrcFinishState::Action ok"); + return DM_OK; +} + +DmAuthStateType AuthSrcFinishState::GetStateType() +{ + return DmAuthStateType::AUTH_SRC_FINISH_STATE; } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 358c0db3a..d981e7297 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -243,8 +243,10 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont return ParseMessageSyncReq(jsonObject, context); case MSG_TYPE_RESP_DATA_SYNC: return ParseMessageSyncResp(jsonObject, context); - case MSG_TYPE_AUTH_FINISH: - return ParseMessageFinish(jsonObject, context); + case MSG_TYPE_AUTH_REQ_FINISH: + return ParseMessageSinkFinish(jsonObject, context); + case MSG_TYPE_AUTH_RESP_FINISH: + return ParseMessageSrcFinish(jsonObject, context); default: break; } @@ -461,7 +463,8 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh case MSG_TYPE_RESP_DATA_SYNC: CreateMessageSyncResp(context, jsonObj); break; - case MSG_TYPE_AUTH_FINISH: + case MSG_TYPE_AUTH_REQ_FINISH: + case MSG_TYPE_AUTH_RESP_FINISH: CreateMessageFinish(context, jsonObj); break; default: @@ -791,12 +794,12 @@ int32_t DmAuthMessageProcessor::ParseMessageSyncResp(const JsonObject &jsonObjec LOGE("DecryptSyncMessage enSyncMsg error"); return ret; } - context->authStateMachine->TransitionTo(std::make_shared()); + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } // 解析200报文 -int32_t DmAuthMessageProcessor::ParseMessageFinish(const JsonObject &jsonObject, +int32_t DmAuthMessageProcessor::ParseMessageSinkFinish(const JsonObject &jsonObject, std::shared_ptr context) { if (jsonObject[DM_TAG_REPLY].IsNumberInteger()) { @@ -812,6 +815,23 @@ int32_t DmAuthMessageProcessor::ParseMessageFinish(const JsonObject &jsonObject, return DM_OK; } +// 解析201报文 +int32_t DmAuthMessageProcessor::ParseMessageSrcFinish(const JsonObject &jsonObject, + std::shared_ptr context) +{ + if (jsonObject[DM_TAG_REPLY].IsNumberInteger()) { + context->reply = jsonObject[DM_TAG_REPLY].Get(); + } + if (jsonObject[DM_TAG_STATE].IsNumberInteger()) { + context->state = jsonObject[DM_TAG_STATE].Get(); + } + if (jsonObject[DM_TAG_REASON].IsNumberInteger()) { + context->reason = jsonObject[DM_TAG_REASON].Get(); + } + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; +} + int32_t DmAuthMessageProcessor::ParseNegotiateMessage(JsonObject &jsonObject, std::shared_ptr context) { diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index fde57c866..67c5f8ba2 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -103,5 +103,48 @@ void DmAuthState::SyncAclList(std::shared_ptr context, // 删除本条acl DeviceProfileConnector::GetInstance().DeleteAccessControlById(aclId); } + +void DmAuthState::SourceFinish(std::shared_ptr context) +{ + if (context->reason != DM_OK) { + int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); + // 根据凭据id 删除sink端多余的凭据 + int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, context->accesser.appCredentialId); + if (ret != DM_OK) { + LOGE("SourceFinish DeleteCredential failed."); + } + // 根据skid删除sk,删除skid + ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accesser.sessionKeyId); + if (ret != DM_OK) { + LOGE("SourceFinish DeleteSessionKey failed."); + } + } + context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_INPUT); + context->authStateMachine->Stop(); + context->timer->DeleteAll(); +} + +void DmAuthState::SinkFinish(std::shared_ptr context) +{ + if (context->reason != DM_OK) { + int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); + // 根据凭据id 删除sink端多余的凭据 + int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, context->accessee.appCredentialId); + if (ret != DM_OK) { + LOGE("SinkFinish DeleteCredential failed."); + } + // 根据skid删除sk,删除skid + ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accessee.sessionKeyId); + if (ret != DM_OK) { + LOGE("SinkFinish DeleteSessionKey failed."); + } + } else { + context->authMessageProcessor->PutAccessControlList(context, context->accessee, context->accesser.deviceId); + } + context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_CANCEL_PIN_CODE_SHOW); + context->authStateMachine->Stop(); + context->timer->DeleteAll(); + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_RESP_FINISH, context); // 发送201给source侧 +} } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 6ced4eac2..79c67ab81 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -73,7 +73,9 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE, // 收到171的处理状态 发送160/180 {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, - {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, {}}, + {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, // 收到190. 发送200报文 + {DmAuthStateType::AUTH_SRC_FINISH_STATE}}, + {DmAuthStateType::AUTH_SRC_FINISH_STATE, {}}, // Sink端 状态迁移表 //{DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, //{DmAuthStateType::AUTH_SINK_START_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, -- Gitee From 4d9fd5dc233c483b4a5028921cf60520d4077b4f Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Sat, 22 Mar 2025 09:57:40 +0800 Subject: [PATCH 254/382] =?UTF-8?q?BUGFIX:=E7=BC=96=E8=AF=91=E9=94=99?= =?UTF-8?q?=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_acl.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index f34a77b81..5d8833c64 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -151,7 +151,7 @@ int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) if (AuthManager::IsHmlSessionType(context->connSessionType)) { LOGI("AuthSrcDataSyncState joinLnn context.appSessionKeyId: %{public}d, ee.appSessionKeyId: %{public}d", context->appSessionKeyId, context->accessee.appSessionKeyId); - context->softbusConnector->JoinLnnByHml(context->sessionId, context->appSessionKeyId, + context->softbusConnector->JoinLNNBySkId(context->sessionId, context->appSessionKeyId, context->accessee.appSessionKeyId, context->accessee.deviceId, peerUdidHash); } else { context->softbusConnector->JoinLnn(context->accessee.openAuthDeviceId, peerUdidHash); @@ -167,7 +167,7 @@ int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) DmAuthStateType AuthSrcDataSyncState::GetStateType() { - return AuthSrcDataSyncState::AUTH_SRC_DATA_SYNC_STATE; + return DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE; } // 收到200结束报文 发送201 -- Gitee From 225026be20a1c3c7867bdb54e6d755eb1a2f7be0 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Sat, 22 Mar 2025 16:33:25 +0800 Subject: [PATCH 255/382] =?UTF-8?q?=E6=97=A7joinlnn=E5=BA=9F=E5=BC=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_acl.cpp | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 5d8833c64..17a2d58de 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -148,14 +148,8 @@ int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) return ERR_DM_FAILED; } std::string peerUdidHash = std::string(udidHashTmp); - if (AuthManager::IsHmlSessionType(context->connSessionType)) { - LOGI("AuthSrcDataSyncState joinLnn context.appSessionKeyId: %{public}d, ee.appSessionKeyId: %{public}d", - context->appSessionKeyId, context->accessee.appSessionKeyId); - context->softbusConnector->JoinLNNBySkId(context->sessionId, context->appSessionKeyId, - context->accessee.appSessionKeyId, context->accessee.deviceId, peerUdidHash); - } else { - context->softbusConnector->JoinLnn(context->accessee.openAuthDeviceId, peerUdidHash); - } + context->softbusConnector->JoinLNNBySkId(context->sessionId, context->appSessionKeyId, + context->accessee.appSessionKeyId, context->accessee.addr, peerUdidHash); } context->reason = DM_OK; context->reply = DM_OK; -- Gitee From 6120e25bfb674b125b45a035f8ac82f5e39bdf8e Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 24 Mar 2025 11:50:34 +0800 Subject: [PATCH 256/382] authresult default cancel --- .../authentication_v2/dm_auth_context.h | 2 +- .../auth_stages/auth_negotiate.cpp | 16 +++++---- .../auth_stages/auth_pin_auth.cpp | 9 +++++ .../dm_auth_message_processor.cpp | 34 ++----------------- 4 files changed, 22 insertions(+), 39 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index e54f22d4b..f9f54b8ea 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -149,7 +149,7 @@ struct DmAuthContext { int64_t requestId; // hichain认证ID int32_t authBoxType{1}; // 认证框类型 UiAction pinInputResult; // 输入PIN码结果 - UiAction authResult{UiAction::USER_OPERATION_TYPE_ALLOW_AUTH}; // 授权结果(使用0、1、6,即单次,取消和始终信任,enum UiAction) + UiAction authResult{UiAction::USER_OPERATION_TYPE_CANCEL_AUTH}; // 授权结果(使用0、1、6,即单次,取消和始终信任,enum UiAction) DmAuthType authType{DmAuthType::AUTH_TYPE_PIN}; // 认证方式,弹pin码、超声pin码、导入pin码 std::vector authTypeList; // 共有认证方式列表 uint32_t currentAuthTypeIdx{0}; // 认证方式索引 diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 5b7989eb3..b1f00dfdd 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -436,6 +436,11 @@ bool AuthSinkNegotiateStateMachine::IsAuthCodeReady(std::shared_ptrsessionName.c_str(), context->importSessionName.c_str()); return false; } + if (context->authResult != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH && + context->authResult != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + LOGE("AuthSinkNegotiateStateMachine::IsAuthCodeReady authResult not ok"); + return false; + } return true; } @@ -470,15 +475,11 @@ void AuthSinkNegotiateStateMachine::NegotiatePinAuthType(std::shared_ptrcustomData = srvInfo.GetDescription(); } } else { - if (context->authType == DmAuthType::AUTH_TYPE_PIN || - context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { - context->authBoxType = OHOS::DistributedDeviceProfile::NUM_1; // 三态框 - } else { - context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // 免弹框 - } + context->authBoxType = OHOS::DistributedDeviceProfile::NUM_1; // 默认三态框 if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { if (IsAuthCodeReady(context)) { context->authTypeList.push_back(context->authType); + context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // 免弹框 } } else { context->authTypeList.push_back(context->authType); // 没匹配到,但是不是导入授权码,也添加到候选列表 @@ -486,6 +487,9 @@ void AuthSinkNegotiateStateMachine::NegotiatePinAuthType(std::shared_ptrauthType); + if (context->authTypeList.size() > 0) { + context->authType = context->authTypeList[0]; + } } int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr context) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 663a9671e..9c4c598f5 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -129,6 +129,15 @@ int32_t AuthSinkPinAuthStartState::Action(std::shared_ptr context HandleAuthenticateTimeout(context, name); }); } + + // 拦截异常认证流程 + if (context->authTypeList.empty() || + (context->authResult != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH && + context->authResult != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS)) { + LOGE("AuthSinkPinAuthStartState::Action invalid parameter."); + return ERR_DM_INPUT_PARA_INVALID; + } + auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); if (ret != DM_OK) { LOGE("AuthSinkPinAuthStartState::Action call ProcessCredData err"); diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index d981e7297..f686514e0 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -951,28 +951,12 @@ int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const JsonObject &j int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const JsonObject &json, std::shared_ptr context) { - if (json[TAG_AUTH_TYPE].IsNumberInteger()) { - context->authType = static_cast(json[TAG_AUTH_TYPE].Get()); - } - if (json[TAG_DEVICE_TYPE].IsNumberInteger()) { - context->accesser.deviceType = json[TAG_AUTH_TYPE].Get(); + context->accesser.deviceType = json[TAG_DEVICE_TYPE].Get(); } if (json[TAG_DEVICE_NAME].IsString()) { context->accesser.deviceName = json[TAG_DEVICE_NAME].Get(); } - if (json[DM_TAG_CURRENT_AUTH_TYPE_IDX].IsNumberInteger()) { - auto idx = json[DM_TAG_CURRENT_AUTH_TYPE_IDX].Get(); - if (idx < context->authTypeList.size() && idx >= context->currentAuthTypeIdx) { - context->currentAuthTypeIdx = idx; - context->authType = context->authTypeList[idx]; - } else { - LOGI("DmAuthMessageProcessor::ParseMessageReqUserConfirm currentAuthTypeIdx err."); - context->reason = ERR_DM_INPUT_PARA_INVALID; - context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); - return STOP_BIND; - } - } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; @@ -994,18 +978,7 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const JsonObject &js if (json[DM_TAG_DATA].IsString()) { context->transmitData = json[DM_TAG_DATA].Get(); } - if (json[DM_TAG_CURRENT_AUTH_TYPE_IDX].IsNumberInteger()) { - auto idx = json[DM_TAG_CURRENT_AUTH_TYPE_IDX].Get(); - if (idx < context->authTypeList.size() && idx >= context->currentAuthTypeIdx) { - context->currentAuthTypeIdx = idx; - context->authType = context->authTypeList[idx]; - } else { - LOGI("DmAuthMessageProcessor::ParseMessageReqUserConfirm currentAuthTypeIdx err."); - context->reason = ERR_DM_INPUT_PARA_INVALID; - context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); - return STOP_BIND; - } - } + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -1032,10 +1005,8 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate(const JsonObject void DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json) { - json[TAG_AUTH_TYPE] = context->authType; json[TAG_DEVICE_TYPE] = context->accesser.deviceType; json[TAG_DEVICE_NAME] = context->accesser.deviceName; - json[DM_TAG_CURRENT_AUTH_TYPE_IDX] = context->currentAuthTypeIdx; } void DmAuthMessageProcessor::CreateMessageRespUserConfirm(std::shared_ptr context, JsonObject &json) @@ -1046,7 +1017,6 @@ void DmAuthMessageProcessor::CreateMessageRespUserConfirm(std::shared_ptr context, JsonObject &json) { json[DM_TAG_DATA] = context->transmitData; - json[DM_TAG_CURRENT_AUTH_TYPE_IDX] = context->currentAuthTypeIdx; } void DmAuthMessageProcessor::CreateMessageRespPinAuthStart(std::shared_ptr context, JsonObject &json) -- Gitee From 7e6f570db42d56ab8a0292d49b002c847f76127f Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Mon, 24 Mar 2025 11:55:05 +0800 Subject: [PATCH 257/382] =?UTF-8?q?feat=EF=BC=9A=E6=96=B0=E5=A2=9E80-171?= =?UTF-8?q?=E9=98=B6=E6=AE=B5UT=E5=92=8CFUZZ=E6=B5=8B=E8=AF=95=E7=94=A8?= =?UTF-8?q?=E4=BE=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- test/commonfuzztest/BUILD.gn | 2 + .../dmauthmanagerv2_fuzzer/BUILD.gn | 79 ++ .../dmauthmanagerv2_fuzzer/corpus/init | 13 + .../dm_auth_manager_fuzzer.cpp | 121 ++ .../dm_auth_manager_fuzzer.h | 21 + .../dmauthmanagerv2_fuzzer/project.xml | 25 + .../ondatareceivedv2_fuzzer/BUILD.gn | 78 ++ .../ondatareceivedv2_fuzzer/corpus/init | 13 + .../on_data_received_fuzzer.cpp | 71 ++ .../on_data_received_fuzzer.h | 21 + .../ondatareceivedv2_fuzzer/project.xml | 25 + .../UTTest_hichain_auth_connector.cpp | 7 + .../UTTest_hichain_auth_connector.h | 1 + test/unittest/BUILD.gn | 95 ++ .../unittest/UTTest_auth_credential_state.cpp | 1104 +++++++++++++++++ test/unittest/UTTest_auth_credential_state.h | 50 + test/unittest/UTTest_auth_negotiate_state.cpp | 193 +++ test/unittest/UTTest_auth_negotiate_state.h | 48 + test/unittest/UTTest_auth_pin_auth_state.cpp | 564 +++++++++ test/unittest/UTTest_auth_pin_auth_state.h | 45 + .../mock/dm_auth_message_processor_mock.cpp | 27 + .../mock/dm_auth_message_processor_mock.h | 34 + .../mock/dm_auth_state_machine_mock.cpp | 27 + .../mock/dm_auth_state_machine_mock.h | 33 + .../mock/hichain_auth_connector_mock.cpp | 44 + .../mock/hichain_auth_connector_mock.h | 25 + test/unittest/mock/softbus_connector_mock.cpp | 5 + test/unittest/mock/softbus_connector_mock.h | 2 + test/unittest/mock/softbus_session_mock.cpp | 15 + test/unittest/mock/softbus_session_mock.h | 7 + 30 files changed, 2795 insertions(+) create mode 100644 test/commonfuzztest/dmauthmanagerv2_fuzzer/BUILD.gn create mode 100644 test/commonfuzztest/dmauthmanagerv2_fuzzer/corpus/init create mode 100644 test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.cpp create mode 100644 test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.h create mode 100644 test/commonfuzztest/dmauthmanagerv2_fuzzer/project.xml create mode 100644 test/commonfuzztest/ondatareceivedv2_fuzzer/BUILD.gn create mode 100644 test/commonfuzztest/ondatareceivedv2_fuzzer/corpus/init create mode 100644 test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp create mode 100644 test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.h create mode 100644 test/commonfuzztest/ondatareceivedv2_fuzzer/project.xml create mode 100644 test/unittest/UTTest_auth_credential_state.cpp create mode 100644 test/unittest/UTTest_auth_credential_state.h create mode 100644 test/unittest/UTTest_auth_negotiate_state.cpp create mode 100644 test/unittest/UTTest_auth_negotiate_state.h create mode 100644 test/unittest/UTTest_auth_pin_auth_state.cpp create mode 100644 test/unittest/UTTest_auth_pin_auth_state.h create mode 100644 test/unittest/mock/dm_auth_message_processor_mock.cpp create mode 100644 test/unittest/mock/dm_auth_message_processor_mock.h create mode 100644 test/unittest/mock/dm_auth_state_machine_mock.cpp create mode 100644 test/unittest/mock/dm_auth_state_machine_mock.h diff --git a/test/commonfuzztest/BUILD.gn b/test/commonfuzztest/BUILD.gn index 4430b898c..c88c67ba2 100644 --- a/test/commonfuzztest/BUILD.gn +++ b/test/commonfuzztest/BUILD.gn @@ -19,12 +19,14 @@ group("fuzztest") { "authenticatedeviceservice_fuzzer:fuzztest", "authenticatedeviceserviceimpl_fuzzer:fuzztest", "dmauthmanager_fuzzer:fuzztest", + "dmauthmanagerv2_fuzzer:fuzztest", "dmcommoneventmanager_fuzzer:fuzztest", "dmcredentialimpl_fuzzer:fuzztest", "generateencrypteduuid_fuzzer:fuzztest", "getdeviceinfo_fuzzer:fuzztest", "hichainconnector_fuzzer:fuzztest", "ondatareceived_fuzzer:fuzztest", + "ondatareceivedv2_fuzzer:fuzztest", "onerror_fuzzer:fuzztest", "onfinish_fuzzer:fuzztest", "onrequest_fuzzer:fuzztest", diff --git a/test/commonfuzztest/dmauthmanagerv2_fuzzer/BUILD.gn b/test/commonfuzztest/dmauthmanagerv2_fuzzer/BUILD.gn new file mode 100644 index 000000000..5265a5250 --- /dev/null +++ b/test/commonfuzztest/dmauthmanagerv2_fuzzer/BUILD.gn @@ -0,0 +1,79 @@ +# Copyright (c) 2023-2024 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import("//foundation/distributedhardware/device_manager/device_manager.gni") + +##############################fuzztest########################################## +ohos_fuzztest("DmAuthManagerV2FuzzTest") { + module_out_path = fuzz_test_output_path + fuzz_config_file = + "${devicemanager_path}/test/commonfuzztest/dmauthmanagerv2_fuzzer" + + include_dirs = [ + "${innerkits_path}/native_cpp/include", + "${servicesimpl_path}/include/ability", + "${servicesimpl_path}/include/adapter", + "${servicesimpl_path}/include/authentication_v2", + "${servicesimpl_path}/include/dependency/hichain", + "${servicesimpl_path}/include/dependency/softbus", + "${servicesimpl_path}/include/dependency/timer", + ] + + cflags = [ + "-g", + "-O0", + "-Dprivate=public", + "-Dprotected=public", + "-Werror", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "dm_auth_manager_fuzzer.cpp" ] + + deps = [ + "${innerkits_path}/native_cpp:devicemanagersdk", + "${services_path}:devicemanagerservice", + "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", + ] + + external_deps = [ + "device_auth:deviceauth_sdk", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "cJSON:cjson", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"DmAuthManagerV2FuzzTest\"", + "LOG_DOMAIN=0xD004110", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + + deps = [ ":DmAuthManagerV2FuzzTest" ] +} +############################################################################### diff --git a/test/commonfuzztest/dmauthmanagerv2_fuzzer/corpus/init b/test/commonfuzztest/dmauthmanagerv2_fuzzer/corpus/init new file mode 100644 index 000000000..dc83418e8 --- /dev/null +++ b/test/commonfuzztest/dmauthmanagerv2_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# 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. +FUZZ \ No newline at end of file diff --git a/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.cpp b/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.cpp new file mode 100644 index 000000000..9e099bb7b --- /dev/null +++ b/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.cpp @@ -0,0 +1,121 @@ +/* + * Copyright (c) 2025-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. + */ + +#include +#include +#include "device_manager_service_listener.h" +#include "auth_manager.h" +#include "dm_auth_manager_fuzzer.h" + +namespace OHOS { +namespace DistributedHardware { + +int32_t g_sessionId = 1; +int32_t g_sessionSide = 0; +int32_t g_result = 1; +int32_t g_authType = 1; +int32_t g_status = 1; +int32_t g_pinCode = 1; +int32_t g_action = 1; +int32_t g_userId = 1; +int32_t g_pageId = 1; +int32_t g_reason = 1; +int32_t g_state = 1; +int64_t g_requestId = 1; +int64_t g_operationCode = 1; + +std::map g_bindParam; + +PeerTargetId g_targetId = { + .deviceId = "deviceId", + .brMac = "brMac", + .bleMac = "bleMac", + .wifiIp = "wifiIp", +}; + +// AuthSrcManager fuzz +void DmAuthSrcManagerFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainAuthConnector = std::make_shared(); + FuzzedDataProvider fdp(data, size); + std::string str(reinterpret_cast(data), size); + int32_t bindLevel = fdp.ConsumeIntegral(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + + authManager->OnUserOperation(g_action, str); + authManager->BindTarget(str, g_targetId, g_bindParam); + authManager->StopAuthenticateDevice(str); + authManager->ImportAuthCode(str, str); + authManager->RegisterUiStateCallback(str); + authManager->UnRegisterUiStateCallback(str); + authManager->UnAuthenticateDevice(str, str, bindLevel); + authManager->UnBindDevice(str, str, bindLevel, str); + authManager->HandleDeviceNotTrust(str); + authManager->DeleteGroup(str, str); + authManager->AuthDeviceTransmit(g_requestId, data, size); + authManager->AuthDeviceSessionKey(g_requestId, data, size); + authManager->AuthDeviceRequest(g_requestId, g_operationCode, str.c_str()); + authManager->OnDataReceived(g_sessionId, str); + authManager->OnAuthDeviceDataReceived(g_sessionId, str); +} + +// AuthSinkManager fuzz +void DmAuthSinkManagerFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainAuthConnector = std::make_shared(); + FuzzedDataProvider fdp(data, size); + std::string str(reinterpret_cast(data), size); + int32_t bindLevel = fdp.ConsumeIntegral(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + + authManager->OnUserOperation(g_action, str); + authManager->BindTarget(str, g_targetId, g_bindParam); + authManager->StopAuthenticateDevice(str); + authManager->ImportAuthCode(str, str); + authManager->RegisterUiStateCallback(str); + authManager->UnRegisterUiStateCallback(str); + authManager->UnAuthenticateDevice(str, str, bindLevel); + authManager->UnBindDevice(str, str, bindLevel, str); + authManager->HandleDeviceNotTrust(str); + authManager->DeleteGroup(str, str); + authManager->AuthDeviceTransmit(g_requestId, data, size); + authManager->AuthDeviceSessionKey(g_requestId, data, size); + authManager->AuthDeviceRequest(g_requestId, g_operationCode, str.c_str()); + authManager->OnDataReceived(g_sessionId, str); + authManager->OnAuthDeviceDataReceived(g_sessionId, str); +} +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DistributedHardware::DmAuthSrcManagerFuzzTest(data, size); + OHOS::DistributedHardware::DmAuthSinkManagerFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.h b/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.h new file mode 100644 index 000000000..bb94714cf --- /dev/null +++ b/test/commonfuzztest/dmauthmanagerv2_fuzzer/dm_auth_manager_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 DM_AUTH_MANAGER_FUZZER_H +#define DM_AUTH_MANAGER_FUZZER_H + +#define FUZZ_PROJECT_NAME "dmauthmanagerv2_fuzzer" + +#endif // DM_AUTH_MANAGER_FUZZER_H \ No newline at end of file diff --git a/test/commonfuzztest/dmauthmanagerv2_fuzzer/project.xml b/test/commonfuzztest/dmauthmanagerv2_fuzzer/project.xml new file mode 100644 index 000000000..9f9a25246 --- /dev/null +++ b/test/commonfuzztest/dmauthmanagerv2_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/commonfuzztest/ondatareceivedv2_fuzzer/BUILD.gn b/test/commonfuzztest/ondatareceivedv2_fuzzer/BUILD.gn new file mode 100644 index 000000000..785b9f960 --- /dev/null +++ b/test/commonfuzztest/ondatareceivedv2_fuzzer/BUILD.gn @@ -0,0 +1,78 @@ +# Copyright (c) 2023-2024 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. + +#####################hydra-fuzz################### +import("//build/config/features.gni") +import("//build/test.gni") +import("//foundation/distributedhardware/device_manager/device_manager.gni") + +##############################fuzztest########################################## +ohos_fuzztest("OnDataReceivedV2FuzzTest") { + module_out_path = fuzz_test_output_path + fuzz_config_file = + "${devicemanager_path}/test/commonfuzztest/ondatareceivedv2_fuzzer" + + include_dirs = [ + "${innerkits_path}/native_cpp/include", + "${servicesimpl_path}/include/ability", + "${servicesimpl_path}/include/adapter", + "${servicesimpl_path}/include/authentication", + "${servicesimpl_path}/include/dependency/hichain", + "${servicesimpl_path}/include/dependency/softbus", + "${servicesimpl_path}/include/dependency/timer", + ] + + cflags = [ + "-g", + "-O0", + "-Dprivate=public", + "-Dprotected=public", + "-Werror", + "-Wno-unused-variable", + "-fno-omit-frame-pointer", + ] + + sources = [ "on_data_received_fuzzer.cpp" ] + + deps = [ + "${services_path}:devicemanagerservice", + "${servicesimpl_path}:devicemanagerserviceimpl", + "${utils_path}:devicemanagerutils", + ] + + external_deps = [ + "device_auth:deviceauth_sdk", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "dsoftbus:softbus_client", + "ffrt:libffrt", + "hilog:libhilog", + "ipc:ipc_single", + "safwk:system_ability_fwk", + "cJSON:cjson", + ] + + defines = [ + "HI_LOG_ENABLE", + "DH_LOG_TAG=\"OnDataReceivedV2FuzzTest\"", + "LOG_DOMAIN=0xD004110", + ] +} + +############################################################################### +group("fuzztest") { + testonly = true + + deps = [ ":OnDataReceivedV2FuzzTest" ] +} +############################################################################### diff --git a/test/commonfuzztest/ondatareceivedv2_fuzzer/corpus/init b/test/commonfuzztest/ondatareceivedv2_fuzzer/corpus/init new file mode 100644 index 000000000..dc83418e8 --- /dev/null +++ b/test/commonfuzztest/ondatareceivedv2_fuzzer/corpus/init @@ -0,0 +1,13 @@ +# 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. +FUZZ \ No newline at end of file diff --git a/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp b/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp new file mode 100644 index 000000000..92d35f26d --- /dev/null +++ b/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp @@ -0,0 +1,71 @@ +/* + * Copyright (c) 2023-2024 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 "auth_manager.h" +#include "device_manager_service_listener.h" +#include "on_data_received_fuzzer.h" + +namespace OHOS { +namespace DistributedHardware { +// AuthSrcManager fuzz +void OnDataReceivedSrcFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainAuthConnector = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + // FuzzedDataProvider fdp(data, size); + // int32_t sessionId = fdp.ConsumeIntegral(); + // std::string message(reinterpret_cast(data), size); + // authManager->OnDataReceived(sessionId, message); + // authManager->OnSessionClosed(sessionId); +} + +// AuthSinkManager fuzz +void OnDataReceivedSinkFuzzTest(const uint8_t* data, size_t size) +{ + if ((data == nullptr) || (size < sizeof(int32_t))) { + return; + } + + std::shared_ptr softbusConnector = std::make_shared(); + std::shared_ptr listener = std::make_shared(); + std::shared_ptr hiChainAuthConnector = std::make_shared(); + std::shared_ptr authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); +// FuzzedDataProvider fdp(data, size); +// int32_t sessionId = fdp.ConsumeIntegral(); +// std::string message(reinterpret_cast(data), size); +// authManager->OnDataReceived(sessionId, message); +// authManager->OnSessionClosed(sessionId); +} +} +} + +/* Fuzzer entry point */ +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) +{ + /* Run your code on data */ + OHOS::DistributedHardware::OnDataReceivedSrcFuzzTest(data, size); + OHOS::DistributedHardware::OnDataReceivedSinkFuzzTest(data, size); + return 0; +} \ No newline at end of file diff --git a/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.h b/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.h new file mode 100644 index 000000000..3bd499b23 --- /dev/null +++ b/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.h @@ -0,0 +1,21 @@ +/* + * 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 ON_DATA_RECEIVED_FUZZER_H +#define ON_DATA_RECEIVED_FUZZER_H + +#define FUZZ_PROJECT_NAME "ondatareceivedv2_fuzzer" + +#endif // ON_DATA_RECEIVED_FUZZER_H \ No newline at end of file diff --git a/test/commonfuzztest/ondatareceivedv2_fuzzer/project.xml b/test/commonfuzztest/ondatareceivedv2_fuzzer/project.xml new file mode 100644 index 000000000..9f9a25246 --- /dev/null +++ b/test/commonfuzztest/ondatareceivedv2_fuzzer/project.xml @@ -0,0 +1,25 @@ + + + + + + 1000 + + 300 + + 4096 + + \ No newline at end of file diff --git a/test/commonunittest/UTTest_hichain_auth_connector.cpp b/test/commonunittest/UTTest_hichain_auth_connector.cpp index a33d4b17b..7b193c53d 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.cpp +++ b/test/commonunittest/UTTest_hichain_auth_connector.cpp @@ -80,6 +80,13 @@ public: { (void)deviceId; } + char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) override + { + (void)requestId; + (void)operationCode; + (void)reqParams; + return nullptr; + } private: int32_t pinCode = 0; }; diff --git a/test/commonunittest/UTTest_hichain_auth_connector.h b/test/commonunittest/UTTest_hichain_auth_connector.h index 3c708b598..f2a675310 100644 --- a/test/commonunittest/UTTest_hichain_auth_connector.h +++ b/test/commonunittest/UTTest_hichain_auth_connector.h @@ -46,6 +46,7 @@ public: (int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen), (override)); MOCK_METHOD(void, GetRemoteDeviceId, (std::string &deviceId), (override)); MOCK_METHOD(int32_t, GetPinCode, (int32_t &code), (override)); + MOCK_METHOD(char *, AuthDeviceRequest, (int64_t requestId, int operationCode, const char *reqParams), (override)); }; } // namespace DistributedHardware } // namespace OHOS diff --git a/test/unittest/BUILD.gn b/test/unittest/BUILD.gn index 3770a184f..b202201b3 100644 --- a/test/unittest/BUILD.gn +++ b/test/unittest/BUILD.gn @@ -91,6 +91,9 @@ group("unittest") { ":UTTest_softbus_listener_two", ":UTTest_softbus_publish", ":UTTest_softbus_session", + ":UTTest_auth_credential_state", + ":UTTest_auth_pin_auth_state", + ":UTTest_auth_negotiate_state", ] } @@ -1975,6 +1978,98 @@ ohos_unittest("UTTest_json_object") { ## UnitTest UTTest_json_object }}} +## UnitTest UTTest_auth_credential_state {{{ + +ohos_unittest("UTTest_auth_credential_state") { + module_out_path = module_out_path + + include_dirs = [ + + ] + + sources = [ + "${devicemanager_path}/test/unittest/UTTest_auth_credential_state.cpp", + "${devicemanager_path}/test/unittest/mock/hichain_auth_connector_mock.cpp", + "${devicemanager_path}/test/unittest/mock/softbus_session_mock.cpp", + "${devicemanager_path}/test/unittest/mock/dm_auth_state_machine_mock.cpp" + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "googletest:gmock", + "googletest:gmock_main", + "hilog:libhilog", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "device_auth:deviceauth_sdk", + "ffrt:libffrt", + ] +} + + +## UnitTest UTTest_auth_credential_state }}} + +## UnitTest UTTest_auth_negotiate_state {{{ + +ohos_unittest("UTTest_auth_negotiate_state") { + module_out_path = module_out_path + + include_dirs = [ + + ] + + sources = [ + "${devicemanager_path}/test/unittest/UTTest_auth_negotiate_state.cpp", + "${devicemanager_path}/test/unittest/mock/softbus_session_mock.cpp", + "${devicemanager_path}/test/unittest/mock/softbus_connector_mock.cpp", + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "googletest:gmock", + "googletest:gmock_main", + "hilog:libhilog", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "device_auth:deviceauth_sdk", + "ffrt:libffrt", + ] +} + +## UnitTest UTTest_auth_negotiate_state }}} + +## UnitTest UTTest_auth_pin_auth_state {{{ + +ohos_unittest("UTTest_auth_pin_auth_state") { + module_out_path = module_out_path + + include_dirs = [ + + ] + + sources = [ + "${devicemanager_path}/test/unittest/UTTest_auth_pin_auth_state.cpp", + "${devicemanager_path}/test/unittest/mock/hichain_auth_connector_mock.cpp", + "${devicemanager_path}/test/unittest/mock/dm_auth_state_machine_mock.cpp" + ] + + deps = [ ":device_manager_test_common" ] + + external_deps = [ + "googletest:gmock", + "googletest:gmock_main", + "hilog:libhilog", + "device_info_manager:distributed_device_profile_common", + "device_info_manager:distributed_device_profile_sdk", + "device_auth:deviceauth_sdk", + "ffrt:libffrt", + ] +} + +## UnitTest UTTest_auth_pin_auth_state }}} + ## Build device_manager_test_common.a {{{ config("device_manager_test_common_public_config") { include_dirs = [ diff --git a/test/unittest/UTTest_auth_credential_state.cpp b/test/unittest/UTTest_auth_credential_state.cpp new file mode 100644 index 000000000..27a269233 --- /dev/null +++ b/test/unittest/UTTest_auth_credential_state.cpp @@ -0,0 +1,1104 @@ +/* + * 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. + */ + +#include "dm_auth_state.h" +#include "UTTest_auth_credential_state.h" +#include "dm_auth_message_processor_mock.h" +#include "device_manager_service_listener.h" + +using namespace testing; + +namespace OHOS { +namespace DistributedHardware { + +constexpr const char *TEST_NONE_EMPTY_STRING = "test"; + +void AuthCredentialStateTest::SetUpTestCase() +{ + LOGI("AuthCredentialStateTest::SetUpTestCase start."); + DmHiChainAuthConnector::dmHiChainAuthConnector = dmHiChainAuthConnectorMock; + DmSoftbusSession::dmSoftbusSession = dmSoftbusSessionMock; + DmAuthStateMachineMock::dmAuthStateMachineMock = dmAuthStateMachineMock; + DmAuthMessageProcessorMock::dmAuthMessageProcessorMock = std::make_shared(); +} + +void AuthCredentialStateTest::TearDownTestCase() +{ + LOGI("AuthCredentialStateTest::TearDownTestCase start."); + DmHiChainAuthConnector::dmHiChainAuthConnector = nullptr; + dmHiChainAuthConnectorMock = nullptr; + DmSoftbusSession::dmSoftbusSession = nullptr; + dmSoftbusSessionMock = nullptr; + DmAuthStateMachineMock::dmAuthStateMachineMock = nullptr; + dmAuthStateMachineMock = nullptr; + DmAuthMessageProcessorMock::dmAuthMessageProcessorMock = nullptr; +} + +void AuthCredentialStateTest::SetUp() +{ + LOGI("AuthCredentialStateTest::SetUp start."); + softbusConnector = std::make_shared(); + listener = std::make_shared(); + hiChainAuthConnector = std::make_shared(); + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + + // 重置mock对象的期望 + Mock::VerifyAndClearExpectations(&*DmHiChainAuthConnector::dmHiChainAuthConnector); + Mock::VerifyAndClearExpectations(&*DmSoftbusSession::dmSoftbusSession); + Mock::VerifyAndClearExpectations(&*DmAuthStateMachineMock::dmAuthStateMachineMock); + Mock::VerifyAndClearExpectations(&*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock); +} + +void AuthCredentialStateTest::TearDown() +{ + LOGI("AuthCredentialStateTest::TearDown start."); + softbusConnector = nullptr; + listener = nullptr; + hiChainAuthConnector = nullptr; + authManager = nullptr; + context = nullptr; +} + +// AuthSrcCredentialExchangeState 测试用例 +// GetStateType接口 +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE); +} + +// AuthSrcCredentialExchangeState 测试用例 +// Action接口 +// 正常流程 期待成功 +// 打桩 AddCredential 期待成功 +// 打桩 ExportCredential 期待成功 +// 打桩 SendData 期待成功 +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AddCredential 期待成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)).WillRepeatedly(Return(DM_OK)); + + // 打桩 ExportCredential 期待成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)).WillRepeatedly(Return(DM_OK)); + + // 打桩 SendData 期待成功 + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSrcCredentialExchangeState 测试用例 +// Action接口 第一次添加凭据失败,期待ERR_DM_FAILED +// 打桩 AddCredential 第一次失败,第二次成功 +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AddCredential 第一次失败,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(ERR_DM_FAILED)) + .WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialExchangeState 测试用例 +// Action接口 第一次导出公钥失败,期待ERR_DM_FAILED +// 打桩 AddCredential 第一次成功,第二次成功 +// 打桩 ExportCredential 第一次失败,第二次成功 +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AddCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 ExportCredential 第一次失败,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(ERR_DM_FAILED)) + .WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialExchangeState 测试用例 +// Action接口 第二次添加凭据失败,期待ERR_DM_FAILED +// 打桩 AddCredential 第一次成功,第二次失败 +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AddCredential 第一次成功,第二次失败 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialExchangeState 测试用例 +// Action接口 第二次导出公钥失败,期待ERR_DM_FAILED +// 打桩 AddCredential 第一次成功,第二次成功 +// 打桩 ExportCredential 第一次成功,第二次失败 +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_006, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AddCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 ExportCredential 第一次成功,第二次失败 + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialExchangeState 测试用例 +// Action接口 发送数据失败 期待ERR_DM_FAILED +// 打桩 AddCredential 第一次成功,第二次成功 +// 打桩 ExportCredential 第一次成功,第二次成功 +// 打桩 SendData 期待失败 +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialExchangeState_007, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AddCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 ExportCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 SendData 期待失败 + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSinkCredentialExchangeState 测试用例 +// GetStateType接口 +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE); +} + + +// AuthSinkCredentialExchangeState 测试用例 +// Action接口 正常流程 期待成功 +// 打桩 AddCredential 期待成功 +// 打桩 ExportCredential 期待成功 +// 打桩 AgreeCredential 期待成功 +// 打桩 SendData 期待成功 +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AddCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 ExportCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 AgreeCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 SendData 期待成功 + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSinkCredentialExchangeState 测试用例 +// Action接口 第一次生成凭据失败,期待ERR_DM_FAILED +// 打桩 AddCredential 第一次失败,第二次成功 +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AddCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(ERR_DM_FAILED)) + .WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSinkCredentialExchangeState 测试用例 +// Action接口 第二次生成凭据失败,期待ERR_DM_FAILED +// 打桩 AddCredential 第一次成功,第二次失败 +// 打桩 ExportCredential 第一次成功,第二次成功 +// 打桩 AgreeCredential 第一次成功,第二次成功 +// 打桩 SendData 期待成功 +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AddCredential 第一次成功,第二次失败 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSinkCredentialExchangeState 测试用例 +// Action接口 第一次导出公钥失败,期待ERR_DM_FAILED +// 打桩 AddCredential 第一次成功,第二次成功 +// 打桩 ExportCredential 第一次失败,第二次成功 +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AddCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 ExportCredential 第一次失败,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(ERR_DM_FAILED)) + .WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSinkCredentialExchangeState 测试用例 +// Action接口 第二次导出公钥失败,期待ERR_DM_FAILED +// 打桩 AddCredential 第一次成功,第二次成功 +// 打桩 ExportCredential 第一次成功,第二次失败 +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_006, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AddCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 ExportCredential 第一次成功,第二次失败 + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSinkCredentialExchangeState 测试用例 +// Action接口 第一次协商凭据失败,期待ERR_DM_FAILED +// 打桩 AddCredential 第一次成功,第二次成功 +// 打桩 ExportCredential 第一次成功,第二次成功 +// 打桩 AgreeCredential 第一次失败,第二次成功 +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_007, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AddCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 ExportCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 AgreeCredential 第一次失败,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(ERR_DM_FAILED)) + .WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSinkCredentialExchangeState 测试用例 +// Action接口 第二次协商凭据失败,期待ERR_DM_FAILED +// 打桩 AddCredential 第一次成功,第二次成功 +// 打桩 ExportCredential 第一次成功,第二次成功 +// 打桩 AgreeCredential 第一次成功,第二次失败 +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_008, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AddCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 ExportCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 AgreeCredential 第一次成功,第二次失败 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSinkCredentialExchangeState 测试用例 +// Action接口 第二次协商凭据失败,期待ERR_DM_FAILED +// 打桩 AddCredential 第一次成功,第二次成功 +// 打桩 ExportCredential 第一次成功,第二次成功 +// 打桩 AgreeCredential 第一次成功,第二次成功 +// 打桩 SendData 期待失败 +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialExchangeState_009, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AddCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AddCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 ExportCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, ExportCredential(_, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 AgreeCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 SendData 期待失败 + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialAuthStartState 测试用例 +// GetStateType接口 +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE); +} + +// AuthSrcCredentialAuthStartState 测试用例 +// Action接口 正常流程 期待成功 +// 打桩 AgreeCredential 第一次成功,第二次成功 +// 打桩 AuthCredential 期待成功 +// 打桩 WaitExpectEvent 接口 期待成功 +// 打桩 SendData 期待成功 +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AgreeCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 AuthCredential 第一次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待ON_TRANSMIT + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_TRANSMIT)); + + // 打桩 SendData 期待成功 + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSrcCredentialAuthStartState 测试用例 +// Action接口 第一次协商凭据失败,期待ERR_DM_FAILED +// 打桩 AgreeCredential 第一次失败 +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AgreeCredential 第一次失败 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialAuthStartState 测试用例 +// Action接口 第二次协商凭据失败,期待ERR_DM_FAILED +// 打桩 AgreeCredential 第一次成功,第二次失败 +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AgreeCredential 第一次成功,第二次失败 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialAuthStartState 测试用例 +// Action接口 凭据认证失败,期待ERR_DM_FAILED +// 打桩 AgreeCredential 第一次成功,第二次成功 +// 打桩 AuthCredential 期待失败 +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_006, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AgreeCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 AuthCredential 期待失败 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSrcCredentialAuthStartState 测试用例 +// Action接口 WaitExpectEvent接口返回其它事件,期待ERR_DM_FAILED +// 打桩 AgreeCredential 第一次成功,第二次成功 +// 打桩 AuthCredential 期待成功 +// 打桩 WaitExpectEvent接口 其它事件 返回ON_FINISH +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_007, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AgreeCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 AuthCredential 期待成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 返回非ON_TRANSMIT,返回ON_FINISH + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_FINISH)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialAuthStartState 测试用例 +// Action接口 发送数据失败 期待ERR_DM_FAILED +// 打桩 AgreeCredential 第一次成功,第二次成功 +// 打桩 AuthCredential 期待成功 +// 打桩 WaitExpectEvent接口 期待成功 +// 打桩 SendData 期待失败 +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthStartState_008, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AgreeCredential 第一次成功,第二次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AgreeCredential(_, _, _, _)) + .WillOnce(Return(DM_OK)) + .WillOnce(Return(DM_OK)); + + // 打桩 AuthCredential 第一次成功 + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待ON_TRANSMIT + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_TRANSMIT)); + + // 打桩 SendData 期待失败 + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSinkCredentialAuthStartState 测试用例 +// GetStateType 接口 +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE); +} + +// AuthSinkCredentialAuthStartState 测试用例 +// Action 接口 正常流程 期待返回DM_OK +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待返回ON_TRANSMIT +// 打桩 SendData 期待返回DM_OK +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待返回ON_TRANSMIT + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_TRANSMIT)); + + // 打桩 SendData 期待返回DM_OK + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSinkCredentialAuthStartState 测试用例 +// Action 接口 ProcessCredData 失败 期待返回 ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回 ERR_DM_FAILED +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回 ERR_DM_FAILED + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSinkCredentialAuthStartState 测试用例 +// Action 接口 WaitExpectEvent发生其它事件 期待返回 ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待返回非ON_TRANSMIT +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待返回非ON_TRANSMIT,返回ON_ERROR + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSinkCredentialAuthStartState 测试用例 +// Action 接口 SendData发送数据失败 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待返回ON_TRANSMIT +// 打桩 SendData 期待返回ERR_DM_FAILED +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthStartState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待返回ON_TRANSMIT + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_TRANSMIT)); + + // 打桩 SendData 期待返回ERR_DM_FAILED + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialAuthNegotiateState 测试用例 +// GetStateType 接口 +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE); +} + +// AuthSrcCredentialAuthNegotiateState 测试用例 +// Action 接口 正常流程 期待返回DM_OK +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待返回ON_TRANSMIT +// 打桩 SendData 期待返回DM_OK +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待返回ON_TRANSMIT + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_TRANSMIT)); + + // 打桩 SendData 期待返回DM_OK + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSrcCredentialAuthNegotiateState 测试用例 +// Action 接口 ProcessCredData失败 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回ERR_DM_FAILED +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回ERR_DM_FAILED + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialAuthNegotiateState 测试用例 +// Action 接口 WaitExpectEvent返回其它事件 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待返回非ON_TRANSMIT +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待返回非ON_TRANSMIT + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialAuthNegotiateState 测试用例 +// Action 接口 SendData发送数失败 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待返回ON_TRANSMIT +// 打桩 SendData 期待返回ERR_DM_FAILED +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthNegotiateState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待返回ON_TRANSMIT + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)).WillOnce(Return(ON_TRANSMIT)); + + // 打桩 SendData 期待返回ERR_DM_FAILED + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSinkCredentialAuthNegotiateState 测试用例 +// GetStateType 接口 +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE); +} + +// AuthSinkCredentialAuthNegotiateState 测试用例 +// Action 正常流程 期待返回DM_OK +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 第一次返回ON_TRANSMIT 第二次返回ON_SESSION_KEY_RETURNED 第三次返回ON_FINISH +// 打桩 SaveSessionKeyToDP 期待返回DM_OK +// 打桩 SendData 期待返回DM_OK +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 第一次返回ON_TRANSMIT 第二次返回ON_SESSION_KEY_RETURNED 第三次返回ON_FINISH + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)); + + // 打桩 SaveSessionKeyToDP 期待返回DM_OK + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_)) + .WillOnce(Return(DM_OK)); + + // 打桩 SendData 期待返回DM_OK + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSinkCredentialAuthNegotiateState 测试用例 +// Action ProcessCredData失败 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回ERR_DM_FAILED +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回ERR_DM_FAILED + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSinkCredentialAuthNegotiateState 测试用例 +// Action 第一次WaitExpectEvent返回其它事件 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 第一次返回非ON_TRANSMIT +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 第一次返回非ON_TRANSMIT + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSinkCredentialAuthNegotiateState 测试用例 +// Action WaitExpectEvent第二次返回其它事件 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 第一次返回ON_TRANSMIT 第二次返回非ON_SESSION_KEY_RETURNED +// 打桩 SaveSessionKeyToDP 期待返回DM_OK +// 打桩 SendData 期待返回DM_OK +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 第一次返回ON_TRANSMIT 第二次返回非ON_SESSION_KEY_RETURNED + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSinkCredentialAuthNegotiateState 测试用例 +// Action WaitExpectEvent第三次返回其它事件 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 第一次返回ON_TRANSMIT 第二次返回ON_SESSION_KEY_RETURNED 第三次返回非ON_FINISH +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_006, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 第一次返回ON_TRANSMIT 第二次返回ON_SESSION_KEY_RETURNED 第三次返回非ON_FINISH + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSinkCredentialAuthNegotiateState 测试用例 +// Action 保存秘钥到DP失败 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 第一次返回ON_TRANSMIT 第二次返回ON_SESSION_KEY_RETURNED 第三次返回ON_FINISH +// 打桩 SaveSessionKeyToDP 期待返回ERR_DM_FAILED +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_007, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 第一次返回ON_TRANSMIT 第二次返回ON_SESSION_KEY_RETURNED 第三次返回ON_FINISH + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)); + + // 打桩 SaveSessionKeyToDP 期待返回ERR_DM_FAILED + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSinkCredentialAuthNegotiateState 测试用例 +// Action SendData发送数据失败 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 第一次返回ON_TRANSMIT 第二次返回ON_SESSION_KEY_RETURNED 第三次返回ON_FINISH +// 打桩 SaveSessionKeyToDP 期待返回DM_OK +// 打桩 SendData 期待返回ERR_DM_FAILED +HWTEST_F(AuthCredentialStateTest, AuthSinkCredentialAuthNegotiateState_008, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 第一次返回ON_TRANSMIT 第二次返回ON_SESSION_KEY_RETURNED 第三次返回ON_FINISH + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)); + + // 打桩 SaveSessionKeyToDP 期待返回DM_OK + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_)) + .WillOnce(Return(DM_OK)); + + // 打桩 SendData 期待返回ERR_DM_FAILED + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialAuthDoneState 测试用例 +// GetStateType 接口 +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE); +} + +// AuthSrcCredentialAuthDoneState 测试用例 +// Action 接口 期待返回DM_OK +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 第一次返回ON_SESSION_KEY_RETURNED 第二次返回ON_FINISH 第三次返回ON_TRANSMIT +// 打桩 SaveSessionKeyToDP 期待返回DM_OK +// 打桩 AuthCredential 期待返回DM_OK +// 打桩 CreateMessage 期待返回非空string +// 打桩SendData 期待返回DM_OK +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 第一次返回ON_SESSION_KEY_RETURNED 第二次返回ON_FINISH 第三次返回ON_TRANSMIT + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)) + .WillOnce(Return(ON_TRANSMIT)); + + // 打桩 SaveSessionKeyToDP 期待返回DM_OK + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_)) + .WillOnce(Return(DM_OK)); + + // 打桩 AuthCredential 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + + // 打桩 CreateMessage 期待返回非空string + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, CreateMessage(_, _)) + .WillOnce(Return(TEST_NONE_EMPTY_STRING)); + + // 打桩 SendData 期待返回DM_OK + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(DM_OK)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSrcCredentialAuthDoneState 测试用例 +// Action 接口 ProcessCredData处理失败 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回ERR_DM_FAILED +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回ERR_DM_FAILED + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialAuthDoneState 测试用例 +// Action 接口 WaitExpectEvent 第一次返回其它事件 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 第一次返回非ON_SESSION_KEY_RETURNED + +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 第一次返回非ON_SESSION_KEY_RETURNED 第二次返回ON_FINISH 第三次返回ON_TRANSMIT + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialAuthDoneState 测试用例 +// Action 接口 WaitExpectEvent第二次返回其它事件 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 第一次返回ON_SESSION_KEY_RETURNED 第二次返回非ON_FINISH +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 第一次返回ON_SESSION_KEY_RETURNED 第二次返回非ON_FINISH + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialAuthDoneState 测试用例 +// Action 接口 WaitExpectEvent第三次返回其它事件 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 第一次返回ON_SESSION_KEY_RETURNED 第二次返回ON_FINISH 第三次返回非ON_TRANSMIT +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_006, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 第一次返回ON_SESSION_KEY_RETURNED 第二次返回ON_FINISH 第三次返回非ON_TRANSMIT + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialAuthDoneState 测试用例 +// Action 接口 SaveSessionKeyToDP保存秘钥到Dp失败 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 第一次返回ON_SESSION_KEY_RETURNED 第二次返回ON_FINISH 第三次返回ON_TRANSMIT +// 打桩 SaveSessionKeyToDP 期待返回ERR_DM_FAILED +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_007, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 第一次返回ON_SESSION_KEY_RETURNED 第二次返回ON_FINISH 第三次返回ON_TRANSMIT + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)) + .WillOnce(Return(ON_TRANSMIT)); + + // 打桩 SaveSessionKeyToDP 期待返回ERR_DM_FAILED + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialAuthDoneState 测试用例 +// Action 接口 AuthCredential 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 第一次返回ON_SESSION_KEY_RETURNED 第二次返回ON_FINISH 第三次返回ON_TRANSMIT +// 打桩 SaveSessionKeyToDP 期待返回DM_OK +// 打桩 AuthCredential 期待返回ERR_DM_FAILED +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_008, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 第一次返回ON_SESSION_KEY_RETURNED 第二次返回ON_FINISH 第三次返回ON_TRANSMIT + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)) + .WillOnce(Return(ON_TRANSMIT)); + + // 打桩 SaveSessionKeyToDP 期待返回DM_OK + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_)) + .WillOnce(Return(DM_OK)); + + // 打桩 AuthCredential 期待返回ERR_DM_FAILED + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialAuthDoneState 测试用例 +// Action 接口 CreateMessage创建空消息字符串 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 第一次返回ON_SESSION_KEY_RETURNED 第二次返回ON_FINISH 第三次返回ON_TRANSMIT +// 打桩 SaveSessionKeyToDP 期待返回DM_OK +// 打桩 AuthCredential 期待返回DM_OK +// 打桩 CreateMessage 期待返回空string +// 打桩SendData 期待返回DM_OK +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_009, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 第一次返回ON_SESSION_KEY_RETURNED 第二次返回ON_FINISH 第三次返回ON_TRANSMIT + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)) + .WillOnce(Return(ON_TRANSMIT)); + + // 打桩 SaveSessionKeyToDP 期待返回DM_OK + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_)) + .WillOnce(Return(DM_OK)); + + // 打桩 AuthCredential 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + + // 打桩 CreateMessage 期待返回非空string + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, CreateMessage(_, _)) + .WillOnce(Return("")); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcCredentialAuthDoneState 测试用例 +// Action 接口 SendData发送数据失败 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 第一次返回ON_SESSION_KEY_RETURNED 第二次返回ON_FINISH 第三次返回ON_TRANSMIT +// 打桩 SaveSessionKeyToDP 期待返回DM_OK +// 打桩 AuthCredential 期待返回DM_OK +// 打桩 CreateMessage 期待返回非空string +// 打桩 SendData 期待返回ERR_DM_FAILED +HWTEST_F(AuthCredentialStateTest, AuthSrcCredentialAuthDoneState_0010, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, ProcessCredData(_, _)).WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 第一次返回ON_SESSION_KEY_RETURNED 第二次返回ON_FINISH 第三次返回ON_TRANSMIT + EXPECT_CALL(*dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)) + .WillOnce(Return(ON_TRANSMIT)); + + // 打桩 SaveSessionKeyToDP 期待返回DM_OK + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, SaveSessionKeyToDP(_)) + .WillOnce(Return(DM_OK)); + + // 打桩 AuthCredential 期待返回DM_OK + EXPECT_CALL(*dmHiChainAuthConnectorMock, AuthCredential(_, _, _, _)).WillOnce(Return(DM_OK)); + + // 打桩 CreateMessage 期待返回非空string + EXPECT_CALL(*DmAuthMessageProcessorMock::dmAuthMessageProcessorMock, CreateMessage(_, _)) + .WillOnce(Return(TEST_NONE_EMPTY_STRING)); + + // 打桩 SendData 期待返回ERR_DM_FAILED + EXPECT_CALL(*dmSoftbusSessionMock, SendData(_, _)).WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +} +} \ No newline at end of file diff --git a/test/unittest/UTTest_auth_credential_state.h b/test/unittest/UTTest_auth_credential_state.h new file mode 100644 index 000000000..ba2893051 --- /dev/null +++ b/test/unittest/UTTest_auth_credential_state.h @@ -0,0 +1,50 @@ +/* + * 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 UTTEST_AUTH_CREDENTIAL_STATE_H +#define UTTEST_AUTH_CREDENTIAL_STATE_H + +#include +#include "hichain_auth_connector_mock.h" +#include "softbus_session_mock.h" +#include "dm_auth_state_machine_mock.h" +#include "auth_manager.h" + +namespace OHOS { +namespace DistributedHardware { + +class AuthCredentialStateTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +private: + static inline std::shared_ptr dmHiChainAuthConnectorMock = + std::make_shared(); + static inline std::shared_ptr dmSoftbusSessionMock = + std::make_shared(); + static inline std::shared_ptr dmAuthStateMachineMock = + std::make_shared(); + std::shared_ptr softbusConnector; + std::shared_ptr listener; + std::shared_ptr hiChainAuthConnector; + std::shared_ptr authManager; + std::shared_ptr context; +}; + +} +} +#endif \ No newline at end of file diff --git a/test/unittest/UTTest_auth_negotiate_state.cpp b/test/unittest/UTTest_auth_negotiate_state.cpp new file mode 100644 index 000000000..16968395a --- /dev/null +++ b/test/unittest/UTTest_auth_negotiate_state.cpp @@ -0,0 +1,193 @@ +/* + * 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. + */ + +#include "device_manager_service_listener.h" +#include "dm_auth_state.h" +#include "UTTest_auth_negotiate_state.h" + +using namespace testing; + +namespace OHOS { +namespace DistributedHardware { + +constexpr const char* TEST_STRING = "test_string"; +constexpr int32_t TEST_NEGATIVE = -1; +constexpr int32_t TEST_POSITIVE = 1; + +void AuthNegotiateStateTest::SetUpTestCase() +{ + LOGI("AuthNegotiateStateTest::SetUpTestCase start."); + + DmSoftbusConnector::dmSoftbusConnector = softbusConnectorMock; + DmSoftbusSession::dmSoftbusSession = softbusSessionMock; +} + +void AuthNegotiateStateTest::TearDownTestCase() +{ + LOGI("AuthNegotiateStateTest::TearDownTestCase done."); + softbusConnectorMock = nullptr; + softbusSessionMock = nullptr; + DmSoftbusConnector::dmSoftbusConnector = nullptr; + DmSoftbusSession::dmSoftbusSession = nullptr; +} + +void AuthNegotiateStateTest::SetUp() +{ + LOGI("AuthNegotiateStateTest::SetUp start."); + softbusConnector = std::make_shared(); + listener = std::make_shared(); + hiChainAuthConnector = std::make_shared(); + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + softbusSession = std::make_shared(); + + Mock::VerifyAndClearExpectations(&*softbusConnectorMock); + Mock::VerifyAndClearExpectations(&*softbusSessionMock); +} + +void AuthNegotiateStateTest::TearDown() +{ + LOGI("AuthNegotiateStateTest::TearDown done."); + softbusConnector = nullptr; + listener = nullptr; + hiChainAuthConnector = nullptr; + authManager = nullptr; + context = nullptr; + softbusSession = nullptr; +} + + +// AuthSrcStartState 状态测试用例 +// GetStateType 接口 +HWTEST_F(AuthNegotiateStateTest, AuthSrcStartState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_START_STATE); +} + +// AuthSrcStartState 状态测试用例 +// Action 接口 正常流程,期待返回DM_OK +// 上下文中设置 connSessionType == CONN_SESSION_TYPE_HML +// 打桩 GetSoftbusSession 接口 返回非空的SoftbusSession对象 +// 打桩 OpenAuthSessionWithPara 接口 期待返回非负数TEST_POSITIVE +HWTEST_F(AuthNegotiateStateTest, AuthSrcStartState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 上下文中设置 connSessionType == CONN_SESSION_TYPE_HML + context->connSessionType = CONN_SESSION_TYPE_HML; + + // 打桩 GetSoftbusSession 接口 返回非空的SoftbusSession对象 + EXPECT_CALL(*softbusConnectorMock, GetSoftbusSession) + .WillOnce(Return(softbusSession)); + + // 打桩 OpenAuthSessionWithPara 接口 期待返回非负数TEST_POSITIVE + EXPECT_CALL(*softbusSessionMock, OpenAuthSessionWithPara) + .WillOnce(Return(TEST_POSITIVE)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSrcStartState 状态测试用例 +// Action 接口 正常流程,期待返回DM_OK +// 上下文中设置 connSessionType != CONN_SESSION_TYPE_HML +// 打桩 GetSoftbusSession 接口,返回非空的SoftbusSession对象 +// 打桩 OpenAuthSession 接口,返回非负数TEST_POSITIVE +HWTEST_F(AuthNegotiateStateTest, AuthSrcStartState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 上下文中设置 connSessionType != CONN_SESSION_TYPE_HML + context->connSessionType = TEST_STRING; + + // 打桩 GetSoftbusSession 接口 返回非空的SoftbusSession对象 + EXPECT_CALL(*softbusConnectorMock, GetSoftbusSession()) + .WillOnce(Return(softbusSession)); + + // 打桩 OpenAuthSession 接口,返回非负数TEST_POSITIVE + EXPECT_CALL(*softbusSessionMock, OpenAuthSession(_)) + .WillOnce(Return(TEST_POSITIVE)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSrcStartState 状态测试用例 +// Action 接口 异常流程,期待返回ERR_DM_FAILED +// connSessionType != CONN_SESSION_TYPE_HML +// 打桩 GetSoftbusSession 接口,返回非空的SoftbusSession对象 +// 打桩 OpenAuthSession 接口,返回负数TEST_NEGATIVE +HWTEST_F(AuthNegotiateStateTest, AuthSrcStartState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 上下文中设置 connSessionType == CONN_SESSION_TYPE_HML + context->connSessionType = CONN_SESSION_TYPE_HML; + + // 打桩 GetSoftbusSession 接口 返回非空的SoftbusSession对象 + EXPECT_CALL(*softbusConnectorMock, GetSoftbusSession) + .WillOnce(Return(softbusSession)); + + // 打桩 OpenAuthSession 接口,返回负数TEST_NEGATIVE + EXPECT_CALL(*softbusSessionMock, OpenAuthSessionWithPara) + .WillOnce(Return(TEST_NEGATIVE)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + + +// AuthSrcNegotiateStateMachine 状态测试用例 +// GetStateType 接口 +HWTEST_F(AuthNegotiateStateTest, AuthSrcNegotiateStateMachine_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE); +} + +// AuthSrcNegotiateStateMachine 状态测试用例 +// Actions 接口 正常流程 期待DM_OK +HWTEST_F(AuthNegotiateStateTest, AuthSrcNegotiateStateMachine_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSinkNegotiateStateMachine 状态测试用例 +// GetStateType 接口 +HWTEST_F(AuthNegotiateStateTest, AuthSinkNegotiateStateMachine_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE); +} + +// AuthSinkNegotiateStateMachine 状态测试用例 +// Action 接口 正常流程 期待DM_OK +// 打桩 DeleteTimer 接口 +// 打桩 GetLocalDeviceName 期待成功 +// GetLocalDeviceNetworkId +// GetLocalDeviceName +// 设置上下文版本,期待CompareVersion 返回true +// CheckIsOnline +// HWTEST_F(AuthNegotiateStateTest, AuthSinkNegotiateStateMachine_001, testing::ext::TestSize.Level1) +// { +// std::shared_ptr authState = std::make_shared(); + + + +// EXPECT_EQ(authState->Action(context), DM_OK); +// } + +} +} \ No newline at end of file diff --git a/test/unittest/UTTest_auth_negotiate_state.h b/test/unittest/UTTest_auth_negotiate_state.h new file mode 100644 index 000000000..d385723bc --- /dev/null +++ b/test/unittest/UTTest_auth_negotiate_state.h @@ -0,0 +1,48 @@ +/* + * 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 UTTEST_AUTH_NEGOTIATE_STATE_H +#define UTTEST_AUTH_NEGOTIATE_STATE_H + +#include "gtest/gtest.h" +#include "auth_manager.h" +#include "softbus_connector_mock.h" +#include "softbus_session_mock.h" + +namespace OHOS { +namespace DistributedHardware { + +class AuthNegotiateStateTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +private: + static inline std::shared_ptr softbusConnectorMock = + std::make_shared(); + static inline std::shared_ptr softbusSessionMock = + std::make_shared(); + std::shared_ptr softbusConnector; + std::shared_ptr listener; + std::shared_ptr hiChainAuthConnector; + std::shared_ptr authManager; + std::shared_ptr context; + std::shared_ptr softbusSession; +}; + +} +} +#endif \ No newline at end of file diff --git a/test/unittest/UTTest_auth_pin_auth_state.cpp b/test/unittest/UTTest_auth_pin_auth_state.cpp new file mode 100644 index 000000000..ef8abc9f7 --- /dev/null +++ b/test/unittest/UTTest_auth_pin_auth_state.cpp @@ -0,0 +1,564 @@ +/* + * 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. + */ + + +#include "dm_auth_state_machine_mock.h" +#include "UTTest_auth_pin_auth_state.h" + +using namespace testing; + +namespace OHOS { +namespace DistributedHardware { + +void AuthPinAuthStateTest::SetUpTestCase() +{ + // 创建mock类 + LOGI("AuthPinAuthStateTest::SetUpTestCase start."); + DmHiChainAuthConnector::dmHiChainAuthConnector = hiChainAuthConnectorMock; + DmAuthStateMachineMock::dmAuthStateMachineMock = std::make_shared(); +} + +void AuthPinAuthStateTest::TearDownTestCase() +{ + LOGI("AuthPinAuthStateTest::TearDownTestCase start."); + DmHiChainAuthConnector::dmHiChainAuthConnector = nullptr; + DmAuthStateMachineMock::dmAuthStateMachineMock = nullptr; + hiChainAuthConnectorMock = nullptr; +} + +void AuthPinAuthStateTest::SetUp() +{ + LOGI("AuthPinAuthStateTest::SetUp start."); + softbusConnector = std::make_shared(); + listener = std::make_shared(); + hiChainAuthConnector = std::make_shared(); + authManager = std::make_shared(softbusConnector, listener, + hiChainAuthConnector); + context = authManager->GetAuthContext(); + + Mock::VerifyAndClearExpectations(&*hiChainAuthConnectorMock); + Mock::VerifyAndClearExpectations(&*DmAuthStateMachineMock::dmAuthStateMachineMock); +} + +void AuthPinAuthStateTest::TearDown() +{ + LOGI("AuthPinAuthStateTest::TearDown start."); + softbusConnector = nullptr; + listener = nullptr; + hiChainAuthConnector = nullptr; + authManager = nullptr; + context = nullptr; +} + +// AuthSrcPinAuthStartState 测试用例 +// GetStateType 接口 +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthStartState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE); +} + +// AuthSrcPinAuthStartState 测试用例 +// Action接口 正常流程 期待返回DM_OK +// 打桩 AuthCredentialPinCode 期待返回DM_OK +// 打桩 WaitExpectEvent 期待返回ON_TRANSMIT +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthStartState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AuthCredentialPinCode 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, AuthCredentialPinCode(_, _, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待返回ON_TRANSMIT + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSrcPinAuthStartState 测试用例 +// Action接口 正常流程 期待返回DM_OK +// 打桩 AuthCredentialPinCode 期待返回DM_OK +// 打桩 WaitExpectEvent 期待返回ON_ERROR +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthStartState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AuthCredentialPinCode 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, AuthCredentialPinCode(_, _, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待返回ON_ERROR + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSrcPinAuthStartState 测试用例 +// Action接口 异常流程 PIN码认证失败 期待返回ERR_DM_FAILED +// 打桩 AuthCredentialPinCode 期待返回ERR_DM_FAILED +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthStartState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AuthCredentialPinCode 期待返回ERR_DM_FAILED + EXPECT_CALL(*hiChainAuthConnectorMock, AuthCredentialPinCode(_, _, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcPinAuthStartState 测试用例 +// Action接口 异常流程 未等到期望事件发生 期待返回STOP_BIND +// 打桩 AuthCredentialPinCode 期待返回DM_OK +// 打桩 WaitExpectEvent 期待返回非ON_TRANSMIT且非ON_ERROR +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthStartState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 AuthCredentialPinCode 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, AuthCredentialPinCode(_, _, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待返回非ON_TRANSMIT且非ON_ERROR 返回ON_SESSION_KEY_RETURNED + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)); + + EXPECT_EQ(authState->Action(context), STOP_BIND); +} + +// AuthSinkPinAuthStartState 测试用例 +// GetStateType 接口 +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE); +} + +// AuthSinkPinAuthStartState 测试用例 +// Action 接口 正常流程 期待返回DM_OK +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待返回ON_TRANSMIT +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待返回ON_TRANSMIT + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)); + + EXPECT_EQ(authState->Action(context), DM_OK); + +} + +// AuthSinkPinAuthStartState 测试用例 +// Action 接口 正常流程 期待返回DM_OK +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待返回ON_ERROR +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待返回ON_ERROR + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSinkPinAuthStartState 测试用例 +// Action 接口 异常流程 ProcessCredData处理失败 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回ERR_DM_FAILED +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回ERR_DM_FAILED + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); + +} + +// AuthSinkPinAuthStartState 测试用例 +// Action 接口 异常流程 期待返回STOP_BIND +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待返回非ON_ERROR和非ON_TRANSMIT 返回ON_SESSION_KEY_RETURNED +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待返回非ON_ERROR和非ON_TRANSMIT 返回ON_SESSION_KEY_RETURNED + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)); + + EXPECT_EQ(authState->Action(context), STOP_BIND); +} + +// AuthSrcPinAuthMsgNegotiateState 测试用例 +// GetStateType 接口 +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthMsgNegotiateState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_PIN_AUTH_MSG_NEGOTIATE_STATE); +} + +// AuthSrcPinAuthMsgNegotiateState 测试用例 +// Action 接口 正常流程 期待返回DM_OK +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待返回ON_TRANSMIT +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthMsgNegotiateState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待返回ON_TRANSMIT + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSrcPinAuthMsgNegotiateState 测试用例 +// Action 接口 正常流程 期待返回DM_OK +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待返回ON_ERROR +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthMsgNegotiateState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待返回ON_ERROR + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSrcPinAuthMsgNegotiateState 测试用例 +// Action 接口 异常流程 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回ERR_DM_FAILED +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthMsgNegotiateState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回ERR_DM_FAILED + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcPinAuthMsgNegotiateState 测试用例 +// Action 接口 异常流程 期待返回STOP_BIND +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待返回ON_REQUEST +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthMsgNegotiateState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待返回ON_REQUEST + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_REQUEST)); + + EXPECT_EQ(authState->Action(context), STOP_BIND); +} + +// AuthSinkPinAuthMsgNegotiateState 测试用例 +// GetStateType 接口 +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_PIN_AUTH_MSG_NEGOTIATE_STATE); +} + +// AuthSinkPinAuthMsgNegotiateState 测试用例 +// Action 接口 正常流程 期待返回DM_OK +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待第一次返回ON_TRANSMIT 第二次返回ON_SESSION_KEY_RETURNED 第三次ON_FINISH +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待第一次返回ON_TRANSMIT 第二次返回ON_SESSION_KEY_RETURNED 第三次ON_FINISH + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_REQUEST)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSinkPinAuthMsgNegotiateState 测试用例 +// Action 接口 异常流程 ProcessCredData处理PIN码失败 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回ERR_DM_FAILED +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回ERR_DM_FAILED + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSinkPinAuthMsgNegotiateState 测试用例 +// Action 接口 重试流程 期待返回DM_OK +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待第一次返回ON_ERROR +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待第一次返回ON_ERROR + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSinkPinAuthMsgNegotiateState 测试用例 +// Action 接口 异常流程 期待返回STOP_BIND +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待第一次返回ON_SESSION_KEY_RETURNED +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待第一次返回ON_SESSION_KEY_RETURNED + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)); + + EXPECT_EQ(authState->Action(context), STOP_BIND); +} + +// AuthSinkPinAuthMsgNegotiateState 测试用例 +// Action 接口 重试流程 期待返回DM_OK +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待第一次返回ON_TRANSMIT 第二次返回ON_ERROR +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_006, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待第一次返回ON_TRANSMIT 第二次返回ON_ERROR + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSinkPinAuthMsgNegotiateState 测试用例 +// Action 接口 异常流程 期待返回STOP_BIND +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待第一次返回ON_TRANSMIT 第二次返回ON_SESSION_KEY_RETURNED,第三次返回ON_SESSION_KEY_RETURNED +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthMsgNegotiateState_007, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待第一次返回ON_TRANSMIT 第二次返回ON_ERROR + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_TRANSMIT)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)); + + EXPECT_EQ(authState->Action(context), STOP_BIND); +} + +// AuthSrcPinAuthDoneState 测试用例 +// GetStateType 接口 +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE); +} + +// AuthSrcPinAuthDoneState 测试用例 +// Action 接口 正常流程 期待返回DM_OK +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待第一次返回ON_SESSION_KEY_RETURNED 第二次返回ON_FINISH +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待第一次返回ON_SESSION_KEY_RETURNED 第二次返回ON_FINISH + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_FINISH)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSrcPinAuthDoneState 测试用例 +// Action 接口 异常流程处理凭据数据失败 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回ERR_DM_FAILED +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_003, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回ERR_DM_FAILED + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(ERR_DM_FAILED)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcPinAuthDoneState 测试用例 +// Action 接口 重试流程 期待返回DM_OK +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待返回ON_ERROR +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_004, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待返回ON_ERROR + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSrcPinAuthDoneState 测试用例 +// Action 接口 异常流程 第一次返回其它事件 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待返回ON_REQUEST +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_005, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待返回ON_REQUEST + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_REQUEST)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSrcPinAuthDoneState 测试用例 +// Action 接口 重试流程 期待返回DM_OK +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待第一次返回ON_SESSION_KEY_RETURNED 第二次返回ON_ERROR +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_006, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待第一次返回ON_SESSION_KEY_RETURNED 第二次返回ON_ERROR + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_ERROR)); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +// AuthSrcPinAuthDoneState 测试用例 +// Action 接口 异常流程 期待返回ERR_DM_FAILED +// 打桩 ProcessCredData 期待返回DM_OK +// 打桩 WaitExpectEvent 期待第一次返回ON_SESSION_KEY_RETURNED 第二次返回ON_REQUEST +HWTEST_F(AuthPinAuthStateTest, AuthSrcPinAuthDoneState_007, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + // 打桩 ProcessCredData 期待返回DM_OK + EXPECT_CALL(*hiChainAuthConnectorMock, ProcessCredData(_, _)) + .WillOnce(Return(DM_OK)); + + // 打桩 WaitExpectEvent 期待第一次返回ON_SESSION_KEY_RETURNED 第二次返回ON_REQUEST + EXPECT_CALL(*DmAuthStateMachineMock::dmAuthStateMachineMock, WaitExpectEvent(_)) + .WillOnce(Return(ON_SESSION_KEY_RETURNED)) + .WillOnce(Return(ON_REQUEST)); + + EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); +} + +// AuthSinkPinAuthDoneState 测试用例 +// GetStateType 接口 +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthDoneState_001, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE); +} + +// AuthSinkPinAuthDoneState 测试用例 +// Action 接口 正常流程,期待返回DM_OK +HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthDoneState_002, testing::ext::TestSize.Level1) +{ + std::shared_ptr authState = std::make_shared(); + + EXPECT_EQ(authState->Action(context), DM_OK); +} + +} +} \ No newline at end of file diff --git a/test/unittest/UTTest_auth_pin_auth_state.h b/test/unittest/UTTest_auth_pin_auth_state.h new file mode 100644 index 000000000..0cd480ebd --- /dev/null +++ b/test/unittest/UTTest_auth_pin_auth_state.h @@ -0,0 +1,45 @@ +/* + * 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 UTTEST_AUTH_PIN_AUTH_STATE_H +#define UTTEST_AUTH_PIN_AUTH_STATE_H + +#include +#include "device_manager_service_listener.h" +#include "hichain_auth_connector_mock.h" +#include "auth_manager.h" + +namespace OHOS { +namespace DistributedHardware { + +class AuthPinAuthStateTest : public testing::Test { +public: + static void SetUpTestCase(); + static void TearDownTestCase(); + void SetUp(); + void TearDown(); +private: + static inline std::shared_ptr hiChainAuthConnectorMock = + std::make_shared(); + std::shared_ptr softbusConnector; + std::shared_ptr listener; + std::shared_ptr hiChainAuthConnector; + std::shared_ptr authManager; + std::shared_ptr context; +}; + +} +} +#endif \ No newline at end of file diff --git a/test/unittest/mock/dm_auth_message_processor_mock.cpp b/test/unittest/mock/dm_auth_message_processor_mock.cpp new file mode 100644 index 000000000..e113adcad --- /dev/null +++ b/test/unittest/mock/dm_auth_message_processor_mock.cpp @@ -0,0 +1,27 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License") = 0; + * 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 "dm_auth_message_processor_mock.h" + +namespace OHOS { +namespace DistributedHardware { + +int32_t DmAuthMessageProcessor::SaveSessionKeyToDP(int32_t &skId) +{ + return DmAuthMessageProcessorMock::dmAuthMessageProcessorMock->SaveSessionKeyToDP(skId); +} + +} +} \ No newline at end of file diff --git a/test/unittest/mock/dm_auth_message_processor_mock.h b/test/unittest/mock/dm_auth_message_processor_mock.h new file mode 100644 index 000000000..5d9d35088 --- /dev/null +++ b/test/unittest/mock/dm_auth_message_processor_mock.h @@ -0,0 +1,34 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License") = 0; + * 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 DM_AUTH_MESSAGE_PROCESSOR_MOCK_H +#define DM_AUTH_MESSAGE_PROCESSOR_MOCK_H + +#include +#include "dm_auth_message_processor.h" + +namespace OHOS { +namespace DistributedHardware { + +class DmAuthMessageProcessorMock { +public: + MOCK_METHOD(int32_t, SaveSessionKeyToDP, (int32_t &)); + MOCK_METHOD(std::string, CreateMessage, (DmMessageType, std::shared_ptr)); + static inline std::shared_ptr dmAuthMessageProcessorMock = nullptr; +}; + +} +} +#endif \ No newline at end of file diff --git a/test/unittest/mock/dm_auth_state_machine_mock.cpp b/test/unittest/mock/dm_auth_state_machine_mock.cpp new file mode 100644 index 000000000..49da4bfb2 --- /dev/null +++ b/test/unittest/mock/dm_auth_state_machine_mock.cpp @@ -0,0 +1,27 @@ +/* + * 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 "dm_auth_state_machine_mock.h" + +namespace OHOS { +namespace DistributedHardware { + +DmEventType DmAuthStateMachine::WaitExpectEvent(DmEventType eventType) +{ + return DmAuthStateMachineMock::dmAuthStateMachineMock->WaitExpectEvent(eventType); +} + +} +} \ No newline at end of file diff --git a/test/unittest/mock/dm_auth_state_machine_mock.h b/test/unittest/mock/dm_auth_state_machine_mock.h new file mode 100644 index 000000000..9489d08fd --- /dev/null +++ b/test/unittest/mock/dm_auth_state_machine_mock.h @@ -0,0 +1,33 @@ +/* + * Copyright (c) 2025 Huawei Device Co., Ltd. + * Licensed under the Apache License, Version 2.0 (the "License") = 0; + * 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 DM_AUTH_STATE_MACHINE_MOCK_H +#define DM_AUTH_STATE_MACHINE_MOCK_H + +#include +#include "dm_auth_state_machine.h" + +namespace OHOS { +namespace DistributedHardware { + +class DmAuthStateMachineMock { +public: + MOCK_METHOD(DmEventType, WaitExpectEvent, (DmEventType)); + static inline std::shared_ptr dmAuthStateMachineMock = nullptr; +}; + +} +} +#endif \ No newline at end of file diff --git a/test/unittest/mock/hichain_auth_connector_mock.cpp b/test/unittest/mock/hichain_auth_connector_mock.cpp index e6c8451c8..d1d2dcbe8 100644 --- a/test/unittest/mock/hichain_auth_connector_mock.cpp +++ b/test/unittest/mock/hichain_auth_connector_mock.cpp @@ -33,5 +33,49 @@ int32_t HiChainAuthConnector::ImportCredential(int32_t osAccountId, std::string { return DmHiChainAuthConnector::dmHiChainAuthConnector->ImportCredential(osAccountId, deviceId, publicKey); } + +// 处理凭据认证报文 +int32_t HiChainAuthConnector::ProcessCredData(int64_t authReqId, const std::string &data) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->ProcessCredData(authReqId, data); +} + +// 生成凭据,返回凭据Id +int32_t HiChainAuthConnector::AddCredential(int32_t osAccountId, const std::string &authParams, std::string &creId) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->AddCredential(osAccountId, authParams, creId); +} + +// 根据凭据Id导出公钥 +int32_t HiChainAuthConnector::ExportCredential(int32_t osAccountId, const std::string &credId, std::string &publicKey) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->ExportCredential(osAccountId, credId, publicKey); +} + +// 凭据协商 +int32_t HiChainAuthConnector::AgreeCredential(int32_t osAccountId, const std::string selfCredId, + const std::string &authParams, std::string &credId) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->AgreeCredential(osAccountId, selfCredId, authParams, credId); +} + +// 删除凭据 +int32_t HiChainAuthConnector::DeleteCredential(int32_t osAccountId, const std::string &creId) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->DeleteCredential(osAccountId, creId); +} +// 凭据认证 pinCode pin码(点对点临时凭据必填) +int32_t HiChainAuthConnector::AuthCredential(int32_t osAccountId, int64_t authReqId, const std::string &credId, + const std::string &pinCode) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->AuthCredential(osAccountId, authReqId, credId, pinCode); +} + +// pin码 认证 +int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, int32_t pinCode) +{ + return DmHiChainAuthConnector::dmHiChainAuthConnector->AuthCredentialPinCode(osAccountId, authReqId, pinCode); +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/hichain_auth_connector_mock.h b/test/unittest/mock/hichain_auth_connector_mock.h index 174867f64..a7c8d9e9f 100644 --- a/test/unittest/mock/hichain_auth_connector_mock.h +++ b/test/unittest/mock/hichain_auth_connector_mock.h @@ -30,6 +30,23 @@ public: virtual int32_t AuthDevice(int32_t pinCode, int32_t osAccountId, std::string udid, int64_t requestId) = 0; virtual int32_t ImportCredential(int32_t osAccountId, std::string deviceId, std::string publicKey) = 0; + + // 处理凭据认证报文 + virtual int32_t ProcessCredData(int64_t authReqId, const std::string &data) = 0; + // 生成凭据,返回凭据Id + virtual int32_t AddCredential(int32_t osAccountId, const std::string &authParams, std::string &creId) = 0; + // 根据凭据Id导出公钥 + virtual int32_t ExportCredential(int32_t osAccountId, const std::string &credId, std::string &publicKey) = 0; + // 凭据协商 + virtual int32_t AgreeCredential(int32_t osAccountId, const std::string selfCredId, const std::string &authParams, + std::string &credId) = 0; + // 删除凭据 + virtual int32_t DeleteCredential(int32_t osAccountId, const std::string &creId) = 0; + // 凭据认证 pinCode pin码(点对点临时凭据必填) + virtual int32_t AuthCredential(int32_t osAccountId, int64_t authReqId, const std::string &credId, + const std::string &pinCode) = 0; + // pin码 认证 + virtual int32_t AuthCredentialPinCode(int32_t osAccountId, int64_t authReqId, int32_t pinCode) = 0; public: static inline std::shared_ptr dmHiChainAuthConnector = nullptr; }; @@ -39,6 +56,14 @@ public: MOCK_METHOD(bool, QueryCredential, (std::string &, int32_t)); MOCK_METHOD(int32_t, AuthDevice, (int32_t, int32_t, std::string, int64_t)); MOCK_METHOD(int32_t, ImportCredential, (int32_t, std::string, std::string)); + + MOCK_METHOD(int32_t, ProcessCredData, (int64_t, const std::string &)); + MOCK_METHOD(int32_t, AddCredential, (int32_t, const std::string &, std::string &)); + MOCK_METHOD(int32_t, ExportCredential, (int32_t, const std::string &, std::string &)); + MOCK_METHOD(int32_t, AgreeCredential, (int32_t, const std::string, const std::string &, std::string &)); + MOCK_METHOD(int32_t, DeleteCredential, (int32_t, const std::string &)); + MOCK_METHOD(int32_t, AuthCredential, (int32_t, int64_t, const std::string &, const std::string &)); + MOCK_METHOD(int32_t, AuthCredentialPinCode, (int32_t, int64_t, int32_t)); }; } } diff --git a/test/unittest/mock/softbus_connector_mock.cpp b/test/unittest/mock/softbus_connector_mock.cpp index 171311d9e..77c65ea49 100644 --- a/test/unittest/mock/softbus_connector_mock.cpp +++ b/test/unittest/mock/softbus_connector_mock.cpp @@ -39,5 +39,10 @@ DmDeviceInfo SoftbusConnector::GetDeviceInfoByDeviceId(const std::string &device { return DmSoftbusConnector::dmSoftbusConnector->GetDeviceInfoByDeviceId(deviceId); } + +std::shared_ptr SoftbusConnector::GetSoftbusSession() +{ + return DmSoftbusConnector::dmSoftbusConnector->GetSoftbusSession(); +} } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_connector_mock.h b/test/unittest/mock/softbus_connector_mock.h index fa25cade0..a8caf1492 100644 --- a/test/unittest/mock/softbus_connector_mock.h +++ b/test/unittest/mock/softbus_connector_mock.h @@ -30,6 +30,7 @@ public: virtual bool CheckIsOnline(const std::string &targetDeviceId) = 0; virtual std::vector GetProcessInfo() = 0; virtual DmDeviceInfo GetDeviceInfoByDeviceId(const std::string &deviceId) = 0; + virtual std::shared_ptr GetSoftbusSession(); public: static inline std::shared_ptr dmSoftbusConnector = nullptr; }; @@ -40,6 +41,7 @@ public: MOCK_METHOD(bool, CheckIsOnline, (const std::string &)); MOCK_METHOD(std::vector, GetProcessInfo, ()); MOCK_METHOD(DmDeviceInfo, GetDeviceInfoByDeviceId, (const std::string &deviceId)); + MOCK_METHOD(std::shared_ptr, GetSoftbusSession, ()); }; } } diff --git a/test/unittest/mock/softbus_session_mock.cpp b/test/unittest/mock/softbus_session_mock.cpp index 1c657174e..c85d7045d 100644 --- a/test/unittest/mock/softbus_session_mock.cpp +++ b/test/unittest/mock/softbus_session_mock.cpp @@ -25,5 +25,20 @@ int32_t SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevI return DmSoftbusSession::dmSoftbusSession->GetPeerDeviceId(sessionId, peerDevId); } +int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) +{ + return DmSoftbusSession::dmSoftbusSession->SendData(sessionId, message); +} + +int32_t SoftbusSession::OpenAuthSessionWithPara(const std::string &deviceId, int32_t actionId, bool isEnable160m) +{ + return DmSoftbusSession::dmSoftbusSession->OpenAuthSessionWithPara(deviceId, actionId, isEnable160m); +} + +int32_t SoftbusSession::OpenAuthSession(const std::string &deviceId) +{ + return DmSoftbusSession::dmSoftbusSession->OpenAuthSession(deviceId); +} + } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/test/unittest/mock/softbus_session_mock.h b/test/unittest/mock/softbus_session_mock.h index 732174ef4..9f386d183 100644 --- a/test/unittest/mock/softbus_session_mock.h +++ b/test/unittest/mock/softbus_session_mock.h @@ -27,6 +27,10 @@ public: virtual ~DmSoftbusSession() = default; public: virtual int32_t GetPeerDeviceId(int32_t sessionId, std::string &peerDevId) = 0; + virtual int32_t SendData(int32_t sessionId, std::string &message) = 0; + virtual int32_t OpenAuthSessionWithPara(const std::string &deviceId, int32_t actionId, bool isEnable160m) = 0; + virtual int32_t OpenAuthSession(const std::string &deviceId) = 0; + public: static inline std::shared_ptr dmSoftbusSession = nullptr; }; @@ -34,6 +38,9 @@ public: class SoftbusSessionMock : public DmSoftbusSession { public: MOCK_METHOD(int32_t, GetPeerDeviceId, (int32_t, std::string &)); + MOCK_METHOD(int32_t, SendData, (int32_t, std::string &)); + MOCK_METHOD(int32_t, OpenAuthSessionWithPara, (const std::string &, int32_t, bool)); + MOCK_METHOD(int32_t, OpenAuthSession, (const std::string &)); }; } } -- Gitee From 4b563c9d6178f53782691459465a27364a5eff54 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 24 Mar 2025 15:05:49 +0800 Subject: [PATCH 258/382] =?UTF-8?q?feat:=20=E4=BF=AE=E6=94=B9=E5=A4=B4?= =?UTF-8?q?=E6=96=87=E4=BB=B6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/auth_manager.h | 20 +----- .../authentication_v2/dm_auth_manager_base.h | 41 +++++++++++- .../dm_auth_message_processor.h | 2 - .../authentication_v2/dm_auth_state_machine.h | 3 - .../src/authentication/dm_auth_manager.cpp | 26 -------- .../src/authentication_v2/auth_manager.cpp | 4 +- .../auth_stages/auth_negotiate.cpp | 8 +-- .../src/authentication_v2/dm_auth_context.cpp | 4 +- .../dm_auth_manager_base.cpp | 63 +++++++++++++++---- .../dm_auth_message_processor.cpp | 7 +-- .../dm_auth_state_machine.cpp | 7 +++ .../src/device_manager_service_impl.cpp | 2 +- 12 files changed, 109 insertions(+), 78 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index aeb6a3b12..8ea5cf057 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -29,23 +29,7 @@ namespace OHOS { namespace DistributedHardware { struct DmAuthContext; -const int32_t DM_AUTH_TYPE_MAX = 5; -const int32_t DM_AUTH_TYPE_MIN = 0; -const int32_t MIN_PIN_TOKEN = 10000000; -const int32_t MAX_PIN_TOKEN = 90000000; -const int32_t NEGOTIATE_TIMEOUT = 10; -const int32_t WAIT_REQUEST_TIMEOUT = 10; -constexpr int32_t CONFIRM_TIMEOUT = 60; -constexpr int32_t SESSION_HEARTBEAT_TIMEOUT = 50; -const int32_t PIN_AUTH_TIMEOUT = 60; -const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; -const int32_t HML_SESSION_TIMEOUT = 10; -const int32_t AUTHENTICATE_TIMEOUT = 120; -constexpr const char* DM_VERSION_5_0_1 = "5.0.1"; -constexpr const char* DM_VERSION_5_0_9 = "5.0.9"; // 预估的旧版本最高版本号 -constexpr const char* BUNDLE_NAME_KEY = "bundleName"; - -// 取自security_device_auth中的identity_operation.h,该头文件为内部头文件,不能直接引用 +// 取自security_device_auth中的identity_service_defines.h,该头文件为内部头文件,不能直接引用 // 若冲突删除此处 enum { ACCOUNT_RELATED = 1, @@ -53,7 +37,7 @@ enum { ACCOUNT_ACROSS }; -// 取自security_device_auth中的identity_operation.h,该头文件为内部头文件,不能直接引用 +// 取自security_device_auth中的identity_service_defines.h,该头文件为内部头文件,不能直接引用 // 若冲突删除此处 enum { SCOPE_DEVICE = 1, diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h b/services/implementation/include/authentication_v2/dm_auth_manager_base.h index 2e4508d95..093a1e754 100644 --- a/services/implementation/include/authentication_v2/dm_auth_manager_base.h +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h @@ -31,11 +31,48 @@ 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 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 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; + + // device_manager_service_impl.cpp需要此定义,所以放在此处 constexpr const char *DM_TAG_DMVERSION = "dmVersion"; constexpr const char *DM_TAG_EDITION = "edition"; -constexpr const char* DM_VERSION_4_1_5_1 = "4.1.5.1"; -constexpr const char* DM_VERSION_5_1_0 = "5.1.0"; class AuthManagerBase : public ISoftbusSessionCallback, public IHiChainConnectorCallback, diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 5d9cebbd9..827bb8722 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -67,9 +67,7 @@ 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_OPERATION_KEY = "appOperation"; constexpr const char* APP_THUMBNAIL = "appThumbnail"; -constexpr const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; constexpr const char* TAG_DEVICE_VERSION = "deviceVersion"; constexpr const char* TAG_DEVICE_NAME = "deviceName"; constexpr const char* TAG_DEVICE_ID_HASH = "deviceIdHash"; diff --git a/services/implementation/include/authentication_v2/dm_auth_state_machine.h b/services/implementation/include/authentication_v2/dm_auth_state_machine.h index 5029c1c81..f7de4b30f 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state_machine.h +++ b/services/implementation/include/authentication_v2/dm_auth_state_machine.h @@ -31,9 +31,6 @@ namespace OHOS { namespace DistributedHardware { -// 事件等待超时时间 -constexpr const int EVENT_TIMEOUT = 5000; // 5000 毫秒 = 5 秒 - // 定义状态迁移表类型 using StateTransitionTable = std::map>; diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 1f6b60c8e..f11671499 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -52,21 +52,6 @@ namespace OHOS { namespace DistributedHardware { -const int32_t AUTHENTICATE_TIMEOUT = 120; -const int32_t CONFIRM_TIMEOUT = 60; -const int32_t NEGOTIATE_TIMEOUT = 10; -const int32_t INPUT_TIMEOUT = 60; -const int32_t ADD_TIMEOUT = 10; -const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; -const int32_t WAIT_REQUEST_TIMEOUT = 10; -const int32_t CLONE_AUTHENTICATE_TIMEOUT = 20; -const int32_t CLONE_CONFIRM_TIMEOUT = 10; -const int32_t CLONE_NEGOTIATE_TIMEOUT = 10; -const int32_t CLONE_ADD_TIMEOUT = 10; -const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10; -const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10; -const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20; -const int32_t HML_SESSION_TIMEOUT = 10; const int32_t CANCEL_PIN_CODE_DISPLAY = 1; const int32_t DEVICE_ID_HALF = 2; const int32_t MAX_AUTH_TIMES = 3; @@ -79,7 +64,6 @@ const int32_t DM_AUTH_TYPE_MIN = 0; const int32_t AUTH_SESSION_SIDE_SERVER = 0; const int32_t USLEEP_TIME_US_500000 = 500000; // 500ms const int32_t AUTH_DEVICE_TIMEOUT = 10; -const int32_t SESSION_HEARTBEAT_TIMEOUT = 50; const int32_t ALREADY_BIND = 1; const int32_t STRTOLL_BASE_10 = 10; const int32_t MAX_PUT_SESSIONKEY_TIMEOUT = 100; //ms @@ -110,16 +94,6 @@ const std::map TASK_TIME_OUT_MAP = { { std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), CLONE_SESSION_HEARTBEAT_TIMEOUT } }; -constexpr const char* APP_OPERATION_KEY = "appOperation"; -constexpr const char* TARGET_PKG_NAME_KEY = "targetPkgName"; -constexpr const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; -constexpr const char* CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay"; -constexpr const char* BUNDLE_NAME_KEY = "bundleName"; -constexpr const char* DM_VERSION_5_0_1 = "5.0.1"; -constexpr const char* DM_VERSION_5_0_2 = "5.0.2"; -constexpr const char* DM_VERSION_5_0_3 = "5.0.3"; -constexpr const char* DM_VERSION_5_0_4 = "5.0.4"; -constexpr const char* DM_VERSION_5_0_5 = "5.0.5"; std::mutex g_authFinishLock; DmAuthManager::DmAuthManager(std::shared_ptr softbusConnector, diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index eff1b22a7..911f9f266 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -546,8 +546,8 @@ void AuthManager::ParseJsonObject(const JsonObject &jsonObject) } else { context_->accessee.bundleName = context_->sessionName; } - if (jsonObject[DM_TAG_PEER_USER_ID].IsNumberInteger()) { - context_->accessee.userId = jsonObject[DM_TAG_PEER_USER_ID].Get(); + if (jsonObject[DM_TAG_ACCESSEE_USER_ID].IsNumberInteger()) { + context_->accessee.userId = jsonObject[DM_TAG_ACCESSEE_USER_ID].Get(); } if (jsonObject[DM_TAG_PEER_DISPLAY_ID].IsNumberInteger()) { context_->accessee.displayId = jsonObject[DM_TAG_PEER_DISPLAY_ID].Get(); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index b1f00dfdd..402ab1548 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -19,12 +19,12 @@ #include "parameter.h" #include "multiple_user_connector.h" -#include "app_manager.h" #include "hap_token_info.h" #include "deviceprofile_connector.h" #include "distributed_device_profile_errors.h" #include "device_auth.h" #include "os_account_manager.h" +#include "app_manager.h" #include "accesstoken_kit.h" #include "access_control_profile.h" #include "accesser.h" @@ -503,17 +503,15 @@ int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr con // 2. 获取deviceName和udid context->accessee.deviceName = context->softbusConnector->GetLocalDeviceName(); - char localDeviceId[DEVICE_UUID_LENGTH]; + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); context->accessee.deviceId = std::string(localDeviceId); context->accessee.networkId = context->softbusConnector->GetLocalDeviceNetworkId(); - context->accessee.deviceName = context->softbusConnector->GetLocalDeviceName(); // 为兼容历史版本,通过ConvertSrcVersion获取src端实际version context->accesser.dmVersion = AuthManagerBase::ConvertSrcVersion(context->accesser.dmVersion, context->accesser.edition); - // 旧协议最高只到5.0.9版本 - std::string preVersion = std::string(DM_VERSION_5_0_9); + std::string preVersion = std::string(DM_VERSION_5_0_OLD_MAX); LOGI("AuthSinkNegotiateStateMachine::Action start version compare %{public}s to %{public}s", context->accesser.dmVersion.c_str(), preVersion.c_str()); if (CompareVersion(context->accesser.dmVersion, preVersion) == false) { diff --git a/services/implementation/src/authentication_v2/dm_auth_context.cpp b/services/implementation/src/authentication_v2/dm_auth_context.cpp index 8db58bb7f..9e19ec1d7 100644 --- a/services/implementation/src/authentication_v2/dm_auth_context.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_context.cpp @@ -94,7 +94,7 @@ int32_t DmAuthContext::SetCredentialId(DmAuthSide side, DmAuthScope authorizedSc if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || (authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP)) { LOGE("DmAuthContext::SetCredentialId() error, invalid input parameters"); - return ERR_DM_FAILED; + return ERR_DM_INPUT_PARA_INVALID; } if (side == DM_AUTH_LOCAL_SIDE) { if (direction == DM_AUTH_SOURCE) { @@ -134,7 +134,7 @@ int32_t DmAuthContext::SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || (authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP)) { LOGE("DmAuthContext::SetPublicKey() error, invalid input parameters"); - return ERR_DM_FAILED; + return ERR_DM_INPUT_PARA_INVALID; } if (side == DM_AUTH_LOCAL_SIDE) { diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp index e8912d559..b29d09b09 100644 --- a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp @@ -30,6 +30,40 @@ using namespace OHOS::AccountSA; namespace OHOS { namespace DistributedHardware { +const char* DM_VERSION_4_1_5_1 = "4.1.5.1"; +const char* DM_VERSION_5_0_1 = "5.0.1"; +const char* DM_VERSION_5_0_2 = "5.0.2"; +const char* DM_VERSION_5_0_3 = "5.0.3"; +const char* DM_VERSION_5_0_4 = "5.0.4"; +const char* DM_VERSION_5_0_5 = "5.0.5"; +const char* DM_VERSION_5_1_0 = "5.1.0"; +const char* DM_VERSION_5_0_OLD_MAX = "5.0.9"; // 预估的旧版本最高版本号 + +const char* APP_OPERATION_KEY = "appOperation"; +const char* TARGET_PKG_NAME_KEY = "targetPkgName"; +const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; +const char* CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay"; +const char* BUNDLE_NAME_KEY = "bundleName"; + +const int32_t AUTHENTICATE_TIMEOUT = 120; +const int32_t CONFIRM_TIMEOUT = 60; +const int32_t NEGOTIATE_TIMEOUT = 10; +const int32_t INPUT_TIMEOUT = 60; +const int32_t ADD_TIMEOUT = 10; +const int32_t WAIT_NEGOTIATE_TIMEOUT = 10; +const int32_t WAIT_REQUEST_TIMEOUT = 10; +const int32_t CLONE_AUTHENTICATE_TIMEOUT = 20; +const int32_t CLONE_CONFIRM_TIMEOUT = 10; +const int32_t CLONE_NEGOTIATE_TIMEOUT = 10; +const int32_t CLONE_ADD_TIMEOUT = 10; +const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10; +const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10; +const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20; +const int32_t HML_SESSION_TIMEOUT = 10; +const int32_t SESSION_HEARTBEAT_TIMEOUT = 50; +const int32_t PIN_AUTH_TIMEOUT = 60; + + int32_t AuthManagerBase::AuthenticateDevice(const std::string &pkgName, int32_t authType, const std::string &deviceId, const std::string &extra) { @@ -293,10 +327,14 @@ std::string AuthManagerBase::ConvertSinkVersion(const std::string &version) return sinkVersion; } +// 场景1:对端指定了userId -> 校验是否为前台用户 +// 场景2:对端未指定userId +// 场景2.1: 单用户 -> 使用当前唯一前台用户 +// 场景2.2: 多用户 -> 使用当前主屏用户 int32_t AuthManagerBase::DmGetUserId(int32_t displayId, int32_t targetUserId) { int32_t ret; - int32_t userId; + int32_t userId = -1; std::vector userIds; ret = MultipleUserConnector::GetForegroundUserIds(userIds); @@ -309,18 +347,6 @@ int32_t AuthManagerBase::DmGetUserId(int32_t displayId, int32_t targetUserId) return -1; } - if (displayId != 0) { - ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(displayId, userId); - if (ret != DM_OK) { - LOGE("RespQueryTokenId: fail to get userId by displayId %{public}d", displayId); - return -1; - } - } - - // 场景1:对端指定了userId -> 校验是否为前台用户 - // 场景2:对端未指定userId - // 场景2.1: 单用户 -> 使用当前唯一前台用户 - // 场景2.2: 多用户 -> 使用当前主屏用户 if (targetUserId != 0) { if (std::find(userIds.begin(), userIds.end(), targetUserId) == userIds.end()) { LOGE("RespQueryTokenId: userId not in foreground users"); @@ -328,16 +354,27 @@ int32_t AuthManagerBase::DmGetUserId(int32_t displayId, int32_t targetUserId) } return targetUserId; } + + if (displayId != 0) { + ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(displayId, userId); + if (ret != DM_OK) { + LOGE("RespQueryTokenId: fail to get userId by displayId %{public}d", displayId); + return -1; + } + return userId; + } if (userIds.size() == 1) { return userIds[0]; } else { + // userIds.size() > 1的情况下,需要找到主屏用户 #ifdef OS_ACCOUNT_PART_EXISTS ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId); if (ret != DM_OK) { LOGE("RespQueryAcceseeIds: get foreground user failed in multi users with error %{public}d", ret); return -1; } + return userId; #else LOGE("RespQueryAcceseeIds: get foreground user failed because no OsAcccountManager"); return -1; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index f686514e0..5bf9a11db 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -46,6 +46,9 @@ void CreateNegotiateExtraInfoMessage(std::shared_ptr context, Jso if (context->accessee.displayId != 0) { jsonExtraObject[DM_TAG_PEER_DISPLAY_ID] = context->accessee.displayId; } + if (context->accessee.userId != 0) { + jsonExtraObject[DM_TAG_ACCESSEE_USER_ID] = context->accessee.userId; + } return; } @@ -493,7 +496,6 @@ void DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptrauthType; jsonObject[TAG_SESSION_NAME] = context->sessionName; jsonObject[DM_TAG_DMVERSION] = context->accesser.dmVersion; - jsonObject[TAG_DEVICE_NAME] = context->accesser.deviceName; jsonObject[DM_TAG_USER_ID] = context->accesser.userId; jsonObject[DM_TAG_TOKEN_ID] = static_cast(context->accesser.tokenId); @@ -842,9 +844,6 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(JsonObject &jsonObject, if (jsonObject[DM_TAG_EDITION].IsString()) { context->accesser.edition = jsonObject[DM_TAG_EDITION].Get(); } - if (jsonObject[TAG_DEVICE_NAME].IsString()) { - context->accesser.deviceName = jsonObject[TAG_DEVICE_NAME].Get(); - } if (jsonObject[DM_TAG_USER_ID].IsNumberInteger()) { context->accesser.userId = jsonObject[DM_TAG_USER_ID].Get(); } diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 79c67ab81..6fc10fdd3 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -25,6 +25,13 @@ namespace OHOS { namespace DistributedHardware { +namespace { + +// 事件等待超时时间 +constexpr const int EVENT_TIMEOUT = 5000; // 5000 毫秒 = 5 秒 + +} + DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) { diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index c0ff40053..1145fd277 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -78,7 +78,7 @@ bool IsMessageOldVersion(int sessionId, const void *data, unsigned int dataLen) dmVersion = AuthManagerBase::ConvertSrcVersion(dmVersion, edition); // 若版本号高于5.0.4旧协议最高版本,则不需要切换老协议 - if (CompareVersion(dmVersion, DM_VERSION_5_0_9) == true) { + if (CompareVersion(dmVersion, DM_VERSION_5_0_OLD_MAX) == true) { return false; } -- Gitee From 89fc38a4d05c1d0b5c3a943157ed032fce99325d Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Mon, 24 Mar 2025 16:05:13 +0800 Subject: [PATCH 259/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9app/user=20sk?= =?UTF-8?q?=E5=91=BD=E5=90=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.h | 8 ++--- .../dm_auth_message_processor.cpp | 32 +++++++++---------- 2 files changed, 20 insertions(+), 20 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 827bb8722..94d58bfb3 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -59,10 +59,10 @@ 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"; -constexpr const char *DM_TAG_APP_SK_ID = "accessAppSKId"; // 本端sk信息 同步给对端 用于构造acl-accesser/accessee -constexpr const char *DM_TAG_USER_SK_ID = "accessUserSKId"; -constexpr const char *DM_TAG_APP_SK_TIMESTAMP = "accessAppSKTimeStamp"; -constexpr const char *DM_TAG_USER_SK_TIMESTAMP = "accessUserSKTimeStamp"; +constexpr const char *DM_TAG_TRANSMIT_SK_ID = "accessTransmitSKId"; // 本端sk信息 同步给对端 用于构造acl-accesser/accessee +constexpr const char *DM_TAG_LNN_SK_ID = "accessLnnSKId"; +constexpr const char *DM_TAG_TRANSMIT_SK_TIMESTAMP = "accessAppTransmitTimeStamp"; +constexpr const char *DM_TAG_LNN_SK_TIMESTAMP = "accessLnnSKTimeStamp"; constexpr const char *DM_TAG_USER_ID = "userId"; constexpr const char* DM_TAG_TOKEN_ID = "tokenId"; constexpr const char *DM_TAG_ISSUER = "issuer"; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 5bf9a11db..e5701944c 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -647,16 +647,16 @@ void DmAuthMessageProcessor::CreateMessageFinish(std::shared_ptr int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr &context, DmAccess &access, JsonObject &jsonObject) { - if (!jsonObject[DM_TAG_USER_SK_ID].IsString()) { - LOGE("ParseSyncMessage DM_TAG_USER_SK_ID error"); + if (!jsonObject[DM_TAG_LNN_SK_ID].IsString()) { + LOGE("ParseSyncMessage DM_TAG_LNN_SK_ID error"); return ERR_DM_FAILED; } - access.userSessionKeyId = std::atoi(jsonObject[DM_TAG_USER_SK_ID].Get().c_str()); - if (!jsonObject[DM_TAG_USER_SK_TIMESTAMP].IsString()) { - LOGE("ParseSyncMessage DM_TAG_USER_SK_TIMESTAMP error"); + access.userSessionKeyId = std::atoi(jsonObject[DM_TAG_LNN_SK_ID].Get().c_str()); + if (!jsonObject[DM_TAG_LNN_SK_TIMESTAMP].IsString()) { + LOGE("ParseSyncMessage DM_TAG_LNN_SK_TIMESTAMP error"); return ERR_DM_FAILED; } - access.userSkTimeStamp = std::atoi(jsonObject[DM_TAG_USER_SK_TIMESTAMP].Get().c_str()); + access.userSkTimeStamp = std::atoi(jsonObject[DM_TAG_LNN_SK_TIMESTAMP].Get().c_str()); if (!jsonObject[DM_TAG_DMVERSION].IsString()) { LOGE("ParseSyncMessage DM_TAG_DMVERSION error"); return ERR_DM_FAILED; @@ -746,11 +746,11 @@ int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptr().c_str()); + if (jsonObject[DM_TAG_TRANSMIT_SK_ID].IsString()) { + access.appSessionKeyId = std::atoi(jsonObject[DM_TAG_TRANSMIT_SK_ID].Get().c_str()); } - if (jsonObject[DM_TAG_APP_SK_TIMESTAMP].IsString()) { - access.appSkTimeStamp = std::atoi(jsonObject[DM_TAG_APP_SK_TIMESTAMP].Get().c_str()); + if (jsonObject[DM_TAG_TRANSMIT_SK_TIMESTAMP].IsString()) { + access.appSkTimeStamp = std::atoi(jsonObject[DM_TAG_TRANSMIT_SK_TIMESTAMP].Get().c_str()); } ret = ParseSyncMessage(context, access, jsonObject); if (ret != DM_OK) { @@ -1132,15 +1132,15 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptrisOnline) { // 非首次认证 accessToSync.sessionKeyId = context->appSessionKeyId; accessToSync.skTimeStamp = context->appSkTimeStamp; - syncMsgJson[DM_TAG_APP_SK_ID]=std::to_string(context->appSessionKeyId); - syncMsgJson[DM_TAG_APP_SK_TIMESTAMP]=std::to_string(context->appSkTimeStamp); + syncMsgJson[DM_TAG_TRANSMIT_SK_ID]=std::to_string(context->appSessionKeyId); + syncMsgJson[DM_TAG_TRANSMIT_SK_TIMESTAMP]=std::to_string(context->appSkTimeStamp); } else { // 首次认证 accessToSync.sessionKeyId = context->userSessionKeyId; accessToSync.skTimeStamp = context->userSkTimeStamp; - syncMsgJson[DM_TAG_APP_SK_ID]=std::to_string(context->appSessionKeyId); - syncMsgJson[DM_TAG_USER_SK_ID]=std::to_string(context->userSessionKeyId); - syncMsgJson[DM_TAG_APP_SK_TIMESTAMP]=std::to_string(context->appSkTimeStamp); - syncMsgJson[DM_TAG_USER_SK_TIMESTAMP]=std::to_string(context->userSkTimeStamp); + syncMsgJson[DM_TAG_TRANSMIT_SK_ID]=std::to_string(context->appSessionKeyId); + syncMsgJson[DM_TAG_LNN_SK_ID]=std::to_string(context->userSessionKeyId); + syncMsgJson[DM_TAG_TRANSMIT_SK_TIMESTAMP]=std::to_string(context->appSkTimeStamp); + syncMsgJson[DM_TAG_LNN_SK_TIMESTAMP]=std::to_string(context->userSkTimeStamp); } JsonObject accessJsonObj; -- Gitee From 80b949cdd3362d88b115f7003855d9241c3413f0 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Mon, 24 Mar 2025 17:55:08 +0800 Subject: [PATCH 260/382] =?UTF-8?q?appsk=E4=BF=AE=E6=94=B9=E4=B8=BAtransmi?= =?UTF-8?q?tsk=EF=BC=9Busersk=E4=BF=AE=E6=94=B9=E4=B8=BAlnnskid=EF=BC=9B?= =?UTF-8?q?=E4=BC=98=E5=8C=96=E5=BA=9F=E5=BC=83context=E5=A4=96=E9=83=A8?= =?UTF-8?q?=E7=9A=84sk=E5=AE=9A=E4=B9=89=EF=BC=8C=E5=B1=9E=E4=BA=8E?= =?UTF-8?q?=E9=87=8D=E5=A4=8D=E5=AE=9A=E4=B9=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication_v2/dm_auth_context.h | 13 ++--- .../dm_auth_message_processor.h | 8 ++- .../auth_stages/auth_acl.cpp | 4 +- .../auth_stages/auth_credential.cpp | 20 +++---- .../dm_auth_message_processor.cpp | 58 ++++++++----------- 5 files changed, 46 insertions(+), 57 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index f9f54b8ea..e966e2744 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -121,13 +121,12 @@ struct DmAccess { std::string appPublicKey; // 应用级公钥 std::vector bindType; // 绑定类型,如DM_IDENTICAL_ACCOUNT、DM_ACROSS_ACCOUNT、DM_POINT_TO_POINT std::string publicKey; // T公钥长度 - int32_t credentialId; // 应用凭据ID int32_t status; // 表示服务为前台还是后台,业务透传,只保存 int32_t sessionKeyId; // 作为秘钥派送的材料,在总线中取出sk - int32_t appSessionKeyId; // 本端永久应用SKID,由DP返回用于ACL的更新、老化 - int32_t userSessionKeyId; // 本端永久用户SKID,由DP返回用于ACL的更新、老化 - int64_t appSkTimeStamp; // 老化,时间为2天 应用级凭据时间戳 - int64_t userSkTimeStamp; // 老化,时间为2天 用户级凭据时间戳 + int32_t transmitSessionKeyId; // 本端永久应用SKID,由DP返回用于ACL的更新、老化 + int32_t lnnSessionKeyId; // 本端永久用户SKID,由DP返回用于ACL的更新、老化 + int64_t transmitSkTimeStamp; // 老化,时间为2天 应用级凭据时间戳 + int64_t lnnSkTimeStamp; // 老化,时间为2天 用户级凭据时间戳 int64_t skTimeStamp; // 老化,时间为2天 bool isAuthed; bool isOnline; @@ -159,10 +158,6 @@ struct DmAuthContext { int32_t reason{DM_OK}; // 本端失败的原因 int32_t reply; // 对端回复的结果 引用common/include/dm_constants.h,有新的错误码可新增 int32_t state; // 结束的状态 - int32_t appSessionKeyId; // 本端永久应用SKID,由DP返回用于ACL的更新、老化 - int32_t userSessionKeyId; // 本端永久用户SKID,由DP返回用于ACL的更新、老化 - int64_t appSkTimeStamp; // 老化,时间为2天 应用级凭据时间戳 - int64_t userSkTimeStamp; // 老化,时间为2天 用户级凭据时间戳 int32_t hmlActionId = 0; bool normalFinishAuth; // 标识认证过程是否正常结束 bool authenticating; // 标识正在认证中 diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 94d58bfb3..88dc1862c 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -146,7 +146,8 @@ enum DmMessageType { 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; @@ -164,6 +165,7 @@ struct DmAccessControlTable { }; // 用于同步ACL的access结构 +// 注意:修改本结构体 需要同步修改dm_auth_message_processor.cpp中的From/ToJson函数 struct DmAccessToSync { std::string deviceName; std::string deviceId; // A->B, 无论是A端还是B端,Accesser对象都存A端的deviceId,Accessee对象都存B端的deviceId @@ -300,9 +302,9 @@ private: std::string Base64Decode(std::string &inputStr); void SetAccessControlList(std::shared_ptr context, DistributedDeviceProfile::AccessControlProfile &profile); - void SetAppAccessControlList(std::shared_ptr context, + void SetTransmitAccessControlList(std::shared_ptr context, DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee); - void SetUserAccessControlList(std::shared_ptr context, + void SetLnnAccessControlList(std::shared_ptr context, DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee); std::shared_ptr cryptoMgr_ = nullptr; }; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 17a2d58de..11a3956e4 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -148,8 +148,8 @@ int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) return ERR_DM_FAILED; } std::string peerUdidHash = std::string(udidHashTmp); - context->softbusConnector->JoinLNNBySkId(context->sessionId, context->appSessionKeyId, - context->accessee.appSessionKeyId, context->accessee.addr, peerUdidHash); + context->softbusConnector->JoinLNNBySkId(context->sessionId, context->accesser.transmitSessionKeyId, + context->accessee.transmitSessionKeyId, context->accessee.addr, peerUdidHash); } context->reason = DM_OK; context->reply = DM_OK; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 06b0eff09..8415252a6 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -127,10 +127,10 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co if (context->isOnline == false && context->isAppCredentialVerified == false) { context->isAppCredentialVerified = true; // 保存到DP 获取应用凭据ID 并保存 - context->appSkTimeStamp = + context->accesser.transmitSkTimeStamp = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) .count(); - context->appSessionKeyId = skId; + context->accesser.transmitSessionKeyId = skId; msgType = MSG_TYPE_REQ_CREDENTIAL_AUTH_START; // 发送160 // 认证用户凭据 int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); @@ -149,18 +149,18 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co } else if (context->isOnline == false) { // 首次认证 且 用户凭据流程 // 保存到DP 获取用户凭据ID 并保存 - context->userSkTimeStamp = + context->accesser.lnnSkTimeStamp = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) .count(); - context->userSessionKeyId = skId; + context->accesser.lnnSessionKeyId = skId; msgType = MSG_TYPE_REQ_DATA_SYNC; // 发送180 } else { // 非首次认证 应用凭据流程 // 保存到DP 获取应用凭据ID 并保存 - context->appSkTimeStamp = + context->accesser.transmitSkTimeStamp = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) .count(); - context->appSessionKeyId = skId; + context->accesser.transmitSessionKeyId = skId; msgType = MSG_TYPE_REQ_DATA_SYNC; // 发送180 } std::string message = @@ -229,16 +229,16 @@ int32_t AuthSinkCredentialAuthNegotiateState::Action(std::shared_ptrisOnline == false && context->isAppCredentialVerified == true) { // SINK首次认证场景,第二次收到161的流程 保存用户级永久SK到DP - context->userSkTimeStamp = + context->accessee.lnnSkTimeStamp = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) .count(); - context->userSessionKeyId = skId; + context->accessee.lnnSessionKeyId = skId; } else { // 应用级凭据认证流程 首次认证的第一次161处理 和 非首次认证的161处理 context->isAppCredentialVerified = true; // 用于指示 首次认证的应用级凭据已认证 - context->appSkTimeStamp = + context->accessee.transmitSkTimeStamp = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) .count(); - context->appSessionKeyId = skId; + context->accessee.transmitSessionKeyId = skId; } return DM_OK; } diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index e5701944c..f3d816cd1 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -108,7 +108,7 @@ void DmAuthMessageProcessor::SetAccessControlList(std::shared_ptr profile.SetDeviceIdType((int32_t)DistributedDeviceProfile::DeviceIdType::UDID); } -void DmAuthMessageProcessor::SetAppAccessControlList(std::shared_ptr context, +void DmAuthMessageProcessor::SetTransmitAccessControlList(std::shared_ptr context, DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee) { accesser.SetAccesserDeviceId(context->accesser.deviceId); @@ -117,37 +117,37 @@ void DmAuthMessageProcessor::SetAppAccessControlList(std::shared_ptraccesser.tokenId); accesser.SetAccesserBundleName(context->accesser.bundleName); accesser.SetAccesserDeviceName(context->accesser.deviceName); - accesser.SetAccesserCredentialId(context->accesser.credentialId); - accesser.SetAccesserSessionKeyId(context->accesser.appSessionKeyId); - accesser.SetAccesserSKTimeStamp(context->accesser.skTimeStamp); + accesser.SetAccesserCredentialId(context->accesser.transmitCredentialId); + accesser.SetAccesserSessionKeyId(context->accesser.transmitSessionKeyId); + accesser.SetAccesserSKTimeStamp(context->accesser.transmitSkTimeStamp); accessee.SetAccesseeDeviceId(context->accessee.deviceId); accessee.SetAccesseeUserId(context->accessee.userId); accessee.SetAccesseeAccountId(context->accessee.accountId); accessee.SetAccesseeTokenId(context->accessee.tokenId); accessee.SetAccesseeBundleName(context->accessee.bundleName); accessee.SetAccesseeDeviceName(context->accessee.deviceName); - accessee.SetAccesseeCredentialId(context->accessee.credentialId); - accessee.SetAccesseeSessionKeyId(context->accessee.appSessionKeyId); - accessee.SetAccesseeSKTimeStamp(context->accessee.skTimeStamp); + accessee.SetAccesseeCredentialId(context->accessee.transmitCredentialId); + accessee.SetAccesseeSessionKeyId(context->accessee.transmitSessionKeyId); + accessee.SetAccesseeSKTimeStamp(context->accessee.transmitSkTimeStamp); } -void DmAuthMessageProcessor::SetUserAccessControlList(std::shared_ptr context, +void DmAuthMessageProcessor::SetLnnAccessControlList(std::shared_ptr context, DistributedDeviceProfile::Accesser &accesser, DistributedDeviceProfile::Accessee &accessee) { accesser.SetAccesserDeviceId(context->accesser.deviceId); accesser.SetAccesserUserId(context->accesser.userId); accesser.SetAccesserAccountId(context->accesser.accountId); accesser.SetAccesserDeviceName(context->accesser.deviceName); - accesser.SetAccesserCredentialId(context->accesser.credentialId); - accesser.SetAccesserSessionKeyId(context->accesser.userSessionKeyId); - accesser.SetAccesserSKTimeStamp(context->accesser.skTimeStamp); + accesser.SetAccesserCredentialId(context->accesser.lnnCredentialId); + accesser.SetAccesserSessionKeyId(context->accesser.lnnSessionKeyId); + accesser.SetAccesserSKTimeStamp(context->accesser.lnnSkTimeStamp); accessee.SetAccesseeDeviceId(context->accessee.deviceId); accessee.SetAccesseeUserId(context->accessee.userId); accessee.SetAccesseeAccountId(context->accessee.accountId); accessee.SetAccesseeDeviceName(context->accessee.deviceName); - accessee.SetAccesseeCredentialId(context->accessee.credentialId); - accessee.SetAccesseeSessionKeyId(context->accessee.userSessionKeyId); - accessee.SetAccesseeSKTimeStamp(context->accessee.skTimeStamp); + accessee.SetAccesseeCredentialId(context->accessee.lnnCredentialId); + accessee.SetAccesseeSessionKeyId(context->accessee.lnnSessionKeyId); + accessee.SetAccesseeSKTimeStamp(context->accessee.lnnSkTimeStamp); } int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptr context, @@ -156,7 +156,7 @@ int32_t DmAuthMessageProcessor::PutAccessControlList(std::shared_ptr LOGE("ParseSyncMessage DM_TAG_LNN_SK_ID error"); return ERR_DM_FAILED; } - access.userSessionKeyId = std::atoi(jsonObject[DM_TAG_LNN_SK_ID].Get().c_str()); + access.lnnSessionKeyId = std::atoi(jsonObject[DM_TAG_LNN_SK_ID].Get().c_str()); if (!jsonObject[DM_TAG_LNN_SK_TIMESTAMP].IsString()) { LOGE("ParseSyncMessage DM_TAG_LNN_SK_TIMESTAMP error"); return ERR_DM_FAILED; } - access.userSkTimeStamp = std::atoi(jsonObject[DM_TAG_LNN_SK_TIMESTAMP].Get().c_str()); + access.lnnSkTimeStamp = std::atoi(jsonObject[DM_TAG_LNN_SK_TIMESTAMP].Get().c_str()); if (!jsonObject[DM_TAG_DMVERSION].IsString()) { LOGE("ParseSyncMessage DM_TAG_DMVERSION error"); return ERR_DM_FAILED; @@ -747,10 +747,10 @@ int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptr().c_str()); + access.transmitSessionKeyId = std::atoi(jsonObject[DM_TAG_TRANSMIT_SK_ID].Get().c_str()); } if (jsonObject[DM_TAG_TRANSMIT_SK_TIMESTAMP].IsString()) { - access.appSkTimeStamp = std::atoi(jsonObject[DM_TAG_TRANSMIT_SK_TIMESTAMP].Get().c_str()); + access.transmitSkTimeStamp = std::atoi(jsonObject[DM_TAG_TRANSMIT_SK_TIMESTAMP].Get().c_str()); } ret = ParseSyncMessage(context, access, jsonObject); if (ret != DM_OK) { @@ -1128,19 +1128,11 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptrisOnline) { // 非首次认证 - accessToSync.sessionKeyId = context->appSessionKeyId; - accessToSync.skTimeStamp = context->appSkTimeStamp; - syncMsgJson[DM_TAG_TRANSMIT_SK_ID]=std::to_string(context->appSessionKeyId); - syncMsgJson[DM_TAG_TRANSMIT_SK_TIMESTAMP]=std::to_string(context->appSkTimeStamp); - } else { // 首次认证 - accessToSync.sessionKeyId = context->userSessionKeyId; - accessToSync.skTimeStamp = context->userSkTimeStamp; - syncMsgJson[DM_TAG_TRANSMIT_SK_ID]=std::to_string(context->appSessionKeyId); - syncMsgJson[DM_TAG_LNN_SK_ID]=std::to_string(context->userSessionKeyId); - syncMsgJson[DM_TAG_TRANSMIT_SK_TIMESTAMP]=std::to_string(context->appSkTimeStamp); - syncMsgJson[DM_TAG_LNN_SK_TIMESTAMP]=std::to_string(context->userSkTimeStamp); + syncMsgJson[DM_TAG_TRANSMIT_SK_ID]=std::to_string(accessToSync.sessionKeyId); + syncMsgJson[DM_TAG_TRANSMIT_SK_TIMESTAMP]=std::to_string(accessToSync.skTimeStamp); + if (!context->isOnline) { // 首次认证 + syncMsgJson[DM_TAG_LNN_SK_ID]=std::to_string(accessToSync.lnnSessionKeyId); + syncMsgJson[DM_TAG_LNN_SK_TIMESTAMP]=std::to_string(accessToSync.lnnSkTimeStamp); } JsonObject accessJsonObj; -- Gitee From 38c3fa180821098b50d31d7b0506498528109ae5 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 24 Mar 2025 17:54:40 +0800 Subject: [PATCH 261/382] default authed for import pin --- .../include/authentication_v2/dm_auth_context.h | 3 ++- .../auth_stages/auth_confirm.cpp | 2 +- .../auth_stages/auth_negotiate.cpp | 16 +++++++++++----- .../dm_auth_message_processor.cpp | 7 +++++-- 4 files changed, 19 insertions(+), 9 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index e966e2744..6bed08cd1 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -148,7 +148,8 @@ struct DmAuthContext { int64_t requestId; // hichain认证ID int32_t authBoxType{1}; // 认证框类型 UiAction pinInputResult; // 输入PIN码结果 - UiAction authResult{UiAction::USER_OPERATION_TYPE_CANCEL_AUTH}; // 授权结果(使用0、1、6,即单次,取消和始终信任,enum UiAction) + UiAction authResult{UiAction::USER_OPERATION_TYPE_ALLOW_AUTH}; // 授权结果(使用0、1、6,即单次,取消和始终信任,enum UiAction) + bool authResultReady{false}; DmAuthType authType{DmAuthType::AUTH_TYPE_PIN}; // 认证方式,弹pin码、超声pin码、导入pin码 std::vector authTypeList; // 共有认证方式列表 uint32_t currentAuthTypeIdx{0}; // 认证方式索引 diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 3b02fdce5..6b9e0de5c 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -58,7 +58,7 @@ int32_t AuthSrcConfirmState::DoPinAuth(std::shared_ptr context) context->currentAuthTypeIdx = 0; context->authType = context->authTypeList[0]; // 首次认证是输入PIN或超声PIN时,先授权 - if (context->authType == DmAuthType::AUTH_TYPE_PIN || context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { + if (!context->authResultReady) { // send 100 context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_USER_CONFIRM, context); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 402ab1548..16b5e8808 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -436,11 +436,7 @@ bool AuthSinkNegotiateStateMachine::IsAuthCodeReady(std::shared_ptrsessionName.c_str(), context->importSessionName.c_str()); return false; } - if (context->authResult != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH && - context->authResult != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { - LOGE("AuthSinkNegotiateStateMachine::IsAuthCodeReady authResult not ok"); - return false; - } + return true; } @@ -470,20 +466,30 @@ void AuthSinkNegotiateStateMachine::NegotiatePinAuthType(std::shared_ptrauthResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; } else if (authResult == OHOS::DistributedDeviceProfile::NUM_6) { context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + } else { + context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; } + context->authResultReady = true; } else { context->customData = srvInfo.GetDescription(); } } else { context->authBoxType = OHOS::DistributedDeviceProfile::NUM_1; // 默认三态框 + + // 特殊应用导入了PIN码 if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { if (IsAuthCodeReady(context)) { context->authTypeList.push_back(context->authType); context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // 免弹框 + context->authResultReady = true; } } else { context->authTypeList.push_back(context->authType); // 没匹配到,但是不是导入授权码,也添加到候选列表 } + // 如果不是免弹框则授权类型默认为取消 + if (context->authBoxType != OHOS::DistributedDeviceProfile::NUM_2) { + context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; + } } // 查询回退表 MatchFallBackCandidateList(context, context->authType); diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index f3d816cd1..08eb242fb 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -534,7 +534,9 @@ void DmAuthMessageProcessor::CreateRespNegotiateMessage(std::shared_ptraccessee.credentialInfos; jsonObject[DM_TAG_AUTH_TYPE_LIST] = vectorToString(context->authTypeList); - jsonObject[DM_TAG_AUTH_RESULT] = context->authResult; + if (context->authResultReady) { + jsonObject[DM_TAG_AUTH_RESULT] = context->authResult; + } jsonObject[TAG_REQUEST_ID] = context->requestId; return; } @@ -939,8 +941,9 @@ int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const JsonObject &j context->requestId = jsonObject[TAG_REQUEST_ID].Get(); } - if (jsonObject[DM_TAG_AUTH_RESULT].IsNumberInteger()) { + if (jsonObject.Contains(DM_TAG_AUTH_RESULT) && jsonObject[DM_TAG_AUTH_RESULT].IsNumberInteger()) { context->authResult = static_cast(jsonObject[DM_TAG_AUTH_RESULT].Get()); + context->authResultReady = true; } context->authStateMachine->TransitionTo(std::make_shared()); -- Gitee From f259ec4a06efa31a649147a6589fa80bb9c68608 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Mon, 24 Mar 2025 18:00:49 +0800 Subject: [PATCH 262/382] =?UTF-8?q?=E8=A1=A5=E5=85=85bindlevel=E6=A0=A1?= =?UTF-8?q?=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_acl.cpp | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 11a3956e4..351e9c33a 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -43,11 +43,12 @@ const int32_t USLEEP_TIME_US_500000 = 500000; // 500ms int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) { LOGI("AuthSinkDataSyncState::Action start"); - // 判断密文阶段和明文阶段的四元组是否相同,不同则直接结束 + // 判断密文阶段和明文阶段的四元组是否相同,两端的bindlevel是否相同,不同则直接结束 bool isSame = Crypto::Sha256(context->accesser.deviceId) == context->accesser.deviceIdHash && Crypto::Sha256(std::to_string(context->accesser.userId)) == context->accesser.userIdHash && Crypto::Sha256(context->accesser.accountId) == context->accesser.accountIdHash && - Crypto::Sha256(std::to_string(context->accesser.tokenId)) == context->accesser.tokenIdHash; + Crypto::Sha256(std::to_string(context->accesser.tokenId)) == context->accesser.tokenIdHash && + context->accesser.bindLevel == context->accessee.bindLevel; if (!isSame) { LOGE("data between two stages different, stop auth"); context->reply = ERR_DM_QUADRUPLE_NOT_SAME; @@ -101,7 +102,8 @@ int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) bool isSame = Crypto::Sha256(context->accessee.deviceId) == context->accessee.deviceIdHash && Crypto::Sha256(std::to_string(context->accessee.userId)) == context->accessee.userIdHash && Crypto::Sha256(context->accessee.accountId) == context->accessee.accountIdHash && - Crypto::Sha256(std::to_string(context->accessee.tokenId)) == context->accessee.tokenIdHash; + Crypto::Sha256(std::to_string(context->accessee.tokenId)) == context->accessee.tokenIdHash && + context->accesser.bindLevel == context->accessee.bindLevel; if (!isSame) { LOGE("data between two stages different, stop auth"); // 不同直接结束,发送200给sink端 -- Gitee From 0607d092bae94bda9542bc07c00a676eae52bf01 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 24 Mar 2025 19:21:41 +0800 Subject: [PATCH 263/382] style --- .../auth_stages/auth_confirm.cpp | 12 ++++++------ .../auth_stages/auth_pin_auth.cpp | 19 +++++++++---------- .../dm_auth_message_processor.cpp | 6 ++++-- 3 files changed, 19 insertions(+), 18 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 6b9e0de5c..80f511379 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -13,14 +13,14 @@ * limitations under the License. */ -#include "dm_auth_state.h" -#include "dm_auth_context.h" -#include "dm_log.h" -#include "dm_dialog_manager.h" +#include "auth_manager.h" +#include "deviceprofile_connector.h" #include "dm_anonymous.h" +#include "dm_auth_context.h" +#include "dm_auth_state.h" #include "dm_auth_state_machine.h" -#include "deviceprofile_connector.h" -#include "auth_manager.h" +#include "dm_dialog_manager.h" +#include "dm_log.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 9c4c598f5..90bd30038 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -13,21 +13,20 @@ * limitations under the License. */ - -#include "hichain_auth_connector.h" -#include "dm_auth_state_machine.h" +#include "auth_manager.h" +#include "deviceprofile_connector.h" +#include "dm_anonymous.h" +#include "dm_auth_context.h" #include "dm_auth_message_processor.h" +#include "dm_auth_state_machine.h" #include "dm_auth_state.h" -#include "dm_auth_context.h" -#include "dm_log.h" -#include "dm_dialog_manager.h" -#include "dm_anonymous.h" -#include "service_info_profile.h" #include "dm_auth_state_machine.h" -#include "deviceprofile_connector.h" +#include "dm_dialog_manager.h" +#include "dm_log.h" #include "dm_random.h" +#include "hichain_auth_connector.h" #include "multiple_user_connector.h" -#include "auth_manager.h" +#include "service_info_profile.h" namespace OHOS { namespace DistributedHardware { diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 08eb242fb..a88ad4140 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -256,7 +256,8 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont return ERR_DM_FAILED; } -static std::vector stringToVector(const std::string& str) { +static std::vector stringToVector(const std::string& str) +{ std::vector vec; std::istringstream iss(str); int32_t num; @@ -266,7 +267,8 @@ static std::vector stringToVector(const std::string& str) { return vec; } -static std::string vectorToString(const std::vector& vec) { +static std::string vectorToString(const std::vector& vec) +{ std::ostringstream oss; for (size_t i = 0; i < vec.size(); ++i) { oss << static_cast(vec[i]); -- Gitee From 1dd0f68b74c8b958375e0cca3f53466be33e4f21 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Mon, 24 Mar 2025 19:34:34 +0800 Subject: [PATCH 264/382] =?UTF-8?q?BUGFIX:=E4=BF=AE=E5=A4=8Duser/app=20sk?= =?UTF-8?q?=E5=91=BD=E5=90=8D=E9=81=97=E6=BC=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication_v2/dm_auth_context.h | 8 ++-- .../dm_auth_message_processor.h | 8 ++-- .../src/authentication_v2/auth_manager.cpp | 6 +-- .../auth_stages/auth_credential.cpp | 12 ++--- .../src/authentication_v2/dm_auth_context.cpp | 48 +++++++++---------- .../dm_auth_message_processor.cpp | 48 +++++++++---------- .../src/authentication_v2/dm_auth_state.cpp | 4 +- 7 files changed, 67 insertions(+), 67 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 6bed08cd1..23f7a3381 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -115,10 +115,10 @@ struct DmAccess { int64_t serviceId; // 保留字段,后续会使用 std::string accesserHapSignature; int32_t bindLevel; // 为业务透传数据,无需自定义 - std::string userCredentialId; // 用户级凭据Id - std::string appCredentialId; // 应用级凭据Id - std::string userPublicKey; // 用户级公钥 - std::string appPublicKey; // 应用级公钥 + std::string lnnCredentialId; // 用户级凭据Id + std::string transmitCredentialId; // 应用级凭据Id + std::string lnnPublicKey; // 用户级公钥 + std::string transmitPublicKey; // 应用级公钥 std::vector bindType; // 绑定类型,如DM_IDENTICAL_ACCOUNT、DM_ACROSS_ACCOUNT、DM_POINT_TO_POINT std::string publicKey; // T公钥长度 int32_t status; // 表示服务为前台还是后台,业务透传,只保存 diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 88dc1862c..cf36be258 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -30,10 +30,10 @@ struct DmAccess; constexpr const char *DM_TAG_MSG_TYPE = "messageType"; // 报文类型 constexpr const char *DM_TAG_DATA = "data"; // 报文数据 constexpr const char* DM_TAG_DATA_LEN = "dataLen"; -constexpr const char *DM_TAG_USER_PUBLICK_KEY = "userPublicKey"; // 用户级公钥 userPublicKey -constexpr const char *DM_TAG_APP_PUBLICK_KEY = "appPublicKey"; // 应用级公钥 appPublicKey -constexpr const char *DM_TAG_USER_CREDENTIAL_ID = "userCredentialId"; // 用户级凭据Id -constexpr const char *DM_TAG_APP_CREDENTIAL_ID = "appCredentialId"; // 应用级凭据Id +constexpr const char *DM_TAG_LNN_PUBLICK_KEY = "lnnPublicKey"; // 用户级公钥 lnnPublicKey +constexpr const char *DM_TAG_TRANSMIT_PUBLICK_KEY = "transmitPublicKey"; // 应用级公钥 transmitPublicKey +constexpr const char *DM_TAG_USER_CREDENTIAL_ID = "lnnCredentialId"; // 用户级凭据Id +constexpr const char *DM_TAG_APP_CREDENTIAL_ID = "transmitCredentialId"; // 应用级凭据Id 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"; // 当前授权类型索引 diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 911f9f266..c72df4284 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -1088,13 +1088,13 @@ char *AuthSinkManager::AuthDeviceRequest(int64_t requestId, int operationCode, c } else if (curState == DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE) { if (context_->isOnline) { // 非首次认证 jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; - jsonObj[FIELD_CRED_ID] = context_->accessee.appCredentialId; + jsonObj[FIELD_CRED_ID] = context_->accessee.transmitCredentialId; } else if (!context_->isAppCredentialVerified) { // 首次认证 && 应用凭据认证 jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; - jsonObj[FIELD_CRED_ID] = context_->accessee.appCredentialId; + jsonObj[FIELD_CRED_ID] = context_->accessee.transmitCredentialId; } else { // 首次认证 && 用户凭据认证 jsonObj[FIELD_CONFIRMATION] = RequestResponse::REQUEST_ACCEPTED; - jsonObj[FIELD_CRED_ID] = context_->accessee.userCredentialId; + jsonObj[FIELD_CRED_ID] = context_->accessee.lnnCredentialId; } } jsonObj[FIELD_SERVICE_PKG_NAME] = std::string(DM_PKG_NAME); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 8415252a6..1ac29a31d 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -135,7 +135,7 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co // 认证用户凭据 int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); ret = context->hiChainAuthConnector->AuthCredential(osAccountId, context->requestId, - context->accesser.userCredentialId, std::string("")); + context->accesser.lnnCredentialId, std::string("")); if (ret != DM_OK) { LOGE("AuthSrcCredentialAuthDoneState::Action Hichain auth credentail failed"); return ret; @@ -436,7 +436,7 @@ int32_t AuthSinkCredentialExchangeState::Action(std::shared_ptr c } // 协商用户级凭据 - tmpCredId = context->accessee.userCredentialId; + tmpCredId = context->accessee.lnnCredentialId; ret = AgreeCredential(DM_AUTH_SCOPE_USER, context); if (ret != DM_OK) { context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); @@ -457,7 +457,7 @@ int32_t AuthSinkCredentialExchangeState::Action(std::shared_ptr c } // 协商应用级公钥 - tmpCredId = context->accessee.appCredentialId; + tmpCredId = context->accessee.transmitCredentialId; ret = AgreeCredential(DM_AUTH_SCOPE_APP, context); if (ret != DM_OK) { context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); @@ -496,7 +496,7 @@ int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr c // 首次认证 if (!context->isOnline) { // 协商用户级凭据 - tmpCredId = context->accesser.userCredentialId; + tmpCredId = context->accesser.lnnCredentialId; ret = AgreeCredential(DM_AUTH_SCOPE_USER, context); if (ret != DM_OK) { context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); @@ -510,7 +510,7 @@ int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr c } // 协商应用级凭据 - tmpCredId = context->accesser.appCredentialId; + tmpCredId = context->accesser.transmitCredentialId; ret = AgreeCredential(DM_AUTH_SCOPE_APP, context); if (ret != DM_OK) { context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); @@ -524,7 +524,7 @@ int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr c // 凭据认证 先进行应用级 ret = context->hiChainAuthConnector->AuthCredential(osAccountId, context->requestId, - context->accesser.appCredentialId, std::string("")); + context->accesser.transmitCredentialId, std::string("")); if (ret != DM_OK) { LOGE("AuthSrcCredentialAuthStartState::Action failed, auth app cred failed."); return ret; diff --git a/services/implementation/src/authentication_v2/dm_auth_context.cpp b/services/implementation/src/authentication_v2/dm_auth_context.cpp index 9e19ec1d7..25410cb1d 100644 --- a/services/implementation/src/authentication_v2/dm_auth_context.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_context.cpp @@ -52,15 +52,15 @@ std::string DmAuthContext::GetCredentialId(DmAuthSide side, DmAuthScope authoriz if (side == DM_AUTH_LOCAL_SIDE) { if (direction == DM_AUTH_SOURCE) { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.userCredentialId : accesser.appCredentialId; + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnCredentialId : accesser.transmitCredentialId; } else { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.userCredentialId : accessee.appCredentialId; + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnCredentialId : accessee.transmitCredentialId; } } else { if (direction == DM_AUTH_SOURCE) { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.userCredentialId : accessee.appCredentialId; + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnCredentialId : accessee.transmitCredentialId; } else { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.userCredentialId : accesser.appCredentialId; + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnCredentialId : accesser.transmitCredentialId; } } } @@ -75,15 +75,15 @@ std::string DmAuthContext::GetPublicKey(DmAuthSide side, DmAuthScope authorizedS if (side == DM_AUTH_LOCAL_SIDE) { if (direction == DM_AUTH_SOURCE) { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.userPublicKey : accesser.appPublicKey; + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnPublicKey : accesser.transmitPublicKey; } else { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.userPublicKey : accessee.appPublicKey; + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnPublicKey : accessee.transmitPublicKey; } } else { if (direction == DM_AUTH_SOURCE) { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.userPublicKey : accessee.appPublicKey; + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnPublicKey : accessee.transmitPublicKey; } else { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.userPublicKey : accesser.appPublicKey; + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnPublicKey : accesser.transmitPublicKey; } } } @@ -99,29 +99,29 @@ int32_t DmAuthContext::SetCredentialId(DmAuthSide side, DmAuthScope authorizedSc if (side == DM_AUTH_LOCAL_SIDE) { if (direction == DM_AUTH_SOURCE) { if (authorizedScope == DM_AUTH_SCOPE_USER) { - accesser.userCredentialId = credentialId; + accesser.lnnCredentialId = credentialId; } else { - accesser.appCredentialId = credentialId; + accesser.transmitCredentialId = credentialId; } } else { if (authorizedScope == DM_AUTH_SCOPE_USER) { - accessee.userCredentialId = credentialId; + accessee.lnnCredentialId = credentialId; } else { - accessee.appCredentialId = credentialId; + accessee.transmitCredentialId = credentialId; } } } else { if (direction == DM_AUTH_SOURCE) { if (authorizedScope == DM_AUTH_SCOPE_USER) { - accessee.userCredentialId = credentialId; + accessee.lnnCredentialId = credentialId; } else { - accessee.appCredentialId = credentialId; + accessee.transmitCredentialId = credentialId; } } else { if (authorizedScope == DM_AUTH_SCOPE_USER) { - accesser.userCredentialId = credentialId; + accesser.lnnCredentialId = credentialId; } else { - accesser.appCredentialId = credentialId; + accesser.transmitCredentialId = credentialId; } } } @@ -140,29 +140,29 @@ int32_t DmAuthContext::SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope if (side == DM_AUTH_LOCAL_SIDE) { if (direction == DM_AUTH_SOURCE) { if (authorizedScope == DM_AUTH_SCOPE_USER) { - accesser.userPublicKey = publicKey; + accesser.lnnPublicKey = publicKey; } else { - accesser.appPublicKey = publicKey; + accesser.transmitPublicKey = publicKey; } } else { if (authorizedScope == DM_AUTH_SCOPE_USER) { - accessee.userPublicKey = publicKey; + accessee.lnnPublicKey = publicKey; } else { - accessee.appPublicKey = publicKey; + accessee.transmitPublicKey = publicKey; } } } else { if (direction == DM_AUTH_SOURCE) { if (authorizedScope == DM_AUTH_SCOPE_USER) { - accessee.userPublicKey = publicKey; + accessee.lnnPublicKey = publicKey; } else { - accessee.appPublicKey = publicKey; + accessee.transmitPublicKey = publicKey; } } else { if (authorizedScope == DM_AUTH_SCOPE_USER) { - accesser.userPublicKey = publicKey; + accesser.lnnPublicKey = publicKey; } else { - accesser.appPublicKey = publicKey; + accesser.transmitPublicKey = publicKey; } } } diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 08eb242fb..4981a7cc8 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -336,21 +336,21 @@ int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const JsonObject &js // 首次认证,解析用户级公钥 if (!context->isOnline) { - if (!jsonData[DM_TAG_USER_PUBLICK_KEY].IsString()) { - LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange() error, first auth, no userPublicKey."); + if (!jsonData[DM_TAG_LNN_PUBLICK_KEY].IsString()) { + LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange() error, first auth, no lnnPublicKey."); return ERR_DM_FAILED; } - context->accesser.userPublicKey = jsonData[DM_TAG_USER_PUBLICK_KEY].Get(); + context->accesser.lnnPublicKey = jsonData[DM_TAG_LNN_PUBLICK_KEY].Get(); } - if (!jsonData[DM_TAG_APP_PUBLICK_KEY].IsString() || + if (!jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY].IsString() || !jsonData[DM_TAG_DEVICE_ID].IsString() || !jsonData[DM_TAG_PEER_USER_SPACE_ID].IsNumberInteger() || !jsonData[DM_TAG_TOKEN_ID].IsNumberInteger()) { LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange, MSG_TYPE_REQ_CREDENTIAL_EXCHANGE message error."); return ERR_DM_FAILED; } - context->accesser.appPublicKey = jsonData[DM_TAG_APP_PUBLICK_KEY].Get(); // 解析应用级公钥 + context->accesser.transmitPublicKey = jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY].Get(); // 解析应用级公钥 context->accesser.deviceId = jsonData[DM_TAG_DEVICE_ID].Get(); // 解析deviceId context->accesser.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].Get(); // 解析userId context->accesser.tokenId = jsonData[DM_TAG_TOKEN_ID].Get(); // 解析tokenId @@ -382,17 +382,17 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &js // 首次认证,解析对方用户级公钥和协商用户级凭据Id std::string tmpString; if (!context->isOnline) { - if (!jsonData[DM_TAG_USER_PUBLICK_KEY].IsString() || !jsonData[DM_TAG_USER_CREDENTIAL_ID].IsString()) { - LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange failed, first auth but no userPublicKey or " - "userCredentialId."); + if (!jsonData[DM_TAG_LNN_PUBLICK_KEY].IsString() || !jsonData[DM_TAG_USER_CREDENTIAL_ID].IsString()) { + LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange failed, first auth but no lnnPublicKey or " + "lnnCredentialId."); return ERR_DM_FAILED; } - context->accessee.userPublicKey = jsonData[DM_TAG_USER_PUBLICK_KEY].Get(); - context->accessee.userCredentialId = jsonData[DM_TAG_USER_CREDENTIAL_ID].Get(); + context->accessee.lnnPublicKey = jsonData[DM_TAG_LNN_PUBLICK_KEY].Get(); + context->accessee.lnnCredentialId = jsonData[DM_TAG_USER_CREDENTIAL_ID].Get(); } // 解析对方应用级公钥和协商应用级凭据Id - if (!jsonData[DM_TAG_APP_PUBLICK_KEY].IsString() || + if (!jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY].IsString() || !jsonData[DM_TAG_APP_CREDENTIAL_ID].IsString() || !jsonData[DM_TAG_DEVICE_ID].IsString() || !jsonData[DM_TAG_PEER_USER_SPACE_ID].IsNumberInteger() || @@ -401,8 +401,8 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &js "message error."); return ERR_DM_FAILED; } - context->accessee.appPublicKey = jsonData[DM_TAG_APP_PUBLICK_KEY].Get(); - context->accessee.appCredentialId = jsonData[DM_TAG_APP_CREDENTIAL_ID].Get(); + context->accessee.transmitPublicKey = jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY].Get(); + context->accessee.transmitCredentialId = jsonData[DM_TAG_APP_CREDENTIAL_ID].Get(); context->accessee.deviceId = jsonData[DM_TAG_DEVICE_ID].Get(); // 解析deviceId context->accessee.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].Get(); // 解析userId context->accessee.tokenId = jsonData[DM_TAG_TOKEN_ID].Get(); // 解析tokenId @@ -547,9 +547,9 @@ void DmAuthMessageProcessor::CreateMessageReqCredExchange(std::shared_ptrisOnline) { - jsonData[DM_TAG_USER_PUBLICK_KEY] = context->accesser.userPublicKey; + jsonData[DM_TAG_LNN_PUBLICK_KEY] = context->accesser.lnnPublicKey; } - jsonData[DM_TAG_APP_PUBLICK_KEY] = context->accesser.appPublicKey; + jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY] = context->accesser.transmitPublicKey; jsonData[DM_TAG_DEVICE_ID] = context->accesser.deviceId; jsonData[DM_TAG_PEER_USER_SPACE_ID] = context->accesser.userId; jsonData[DM_TAG_TOKEN_ID] = context->accesser.tokenId; @@ -567,11 +567,11 @@ void DmAuthMessageProcessor::CreateMessageRspCredExchange(std::shared_ptrisOnline) { - jsonData[DM_TAG_USER_PUBLICK_KEY] = context->accessee.userPublicKey; - jsonData[DM_TAG_USER_CREDENTIAL_ID] = context->accessee.userCredentialId; + jsonData[DM_TAG_LNN_PUBLICK_KEY] = context->accessee.lnnPublicKey; + jsonData[DM_TAG_USER_CREDENTIAL_ID] = context->accessee.lnnCredentialId; } - jsonData[DM_TAG_APP_PUBLICK_KEY] = context->accessee.appPublicKey; // 本端应用级公钥 - jsonData[DM_TAG_APP_CREDENTIAL_ID] = context->accessee.appCredentialId; // 本端应用级凭据Id + jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY] = context->accessee.transmitPublicKey; // 本端应用级公钥 + jsonData[DM_TAG_APP_CREDENTIAL_ID] = context->accessee.transmitCredentialId; // 本端应用级凭据Id jsonData[DM_TAG_DEVICE_ID] = context->accessee.deviceId; // 本端deviceId jsonData[DM_TAG_PEER_USER_SPACE_ID] = context->accessee.userId; // 本端userId jsonData[DM_TAG_TOKEN_ID] = context->accessee.tokenId; // 本端tokenId @@ -592,9 +592,9 @@ void DmAuthMessageProcessor::CreateMessageReqCredAuthStart(std::shared_ptrtransmitData; if (!context->isAppCredentialVerified) { // 应用级凭据认证 - jsonObject[DM_TAG_APP_CREDENTIAL_ID] = context->accesser.appCredentialId; + jsonObject[DM_TAG_APP_CREDENTIAL_ID] = context->accesser.transmitCredentialId; } else if (!context->isOnline) { // 首次用户级凭据认证 - jsonObject[DM_TAG_USER_CREDENTIAL_ID] = context->accesser.userCredentialId; + jsonObject[DM_TAG_USER_CREDENTIAL_ID] = context->accesser.lnnCredentialId; } } @@ -1260,13 +1260,13 @@ int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(JsonObject &jsonObject, st std::string jsonTag; if (context->isOnline == false && context->isAppCredentialVerified == false) { // 首次认证的应用凭据 jsonTag = DM_TAG_APP_CREDENTIAL_ID; - context->accesser.appCredentialId = jsonObject[DM_TAG_APP_CREDENTIAL_ID].Get(); + context->accesser.transmitCredentialId = jsonObject[DM_TAG_APP_CREDENTIAL_ID].Get(); } else if (context->isOnline == false) { // 首次认证的用户凭据 jsonTag = DM_TAG_USER_CREDENTIAL_ID; - context->accesser.userCredentialId = jsonObject[DM_TAG_USER_CREDENTIAL_ID].Get(); + context->accesser.lnnCredentialId = jsonObject[DM_TAG_USER_CREDENTIAL_ID].Get(); } else { // 非首次认证的应用凭据 jsonTag = DM_TAG_APP_CREDENTIAL_ID; - context->accesser.appCredentialId = jsonObject[DM_TAG_APP_CREDENTIAL_ID].Get(); + context->accesser.transmitCredentialId = jsonObject[DM_TAG_APP_CREDENTIAL_ID].Get(); } if (!jsonObject.Contains(jsonTag) || !jsonObject[jsonTag].IsString()) { diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 67c5f8ba2..40a6a8420 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -109,7 +109,7 @@ void DmAuthState::SourceFinish(std::shared_ptr context) if (context->reason != DM_OK) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); // 根据凭据id 删除sink端多余的凭据 - int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, context->accesser.appCredentialId); + int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, context->accesser.transmitCredentialId); if (ret != DM_OK) { LOGE("SourceFinish DeleteCredential failed."); } @@ -129,7 +129,7 @@ void DmAuthState::SinkFinish(std::shared_ptr context) if (context->reason != DM_OK) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); // 根据凭据id 删除sink端多余的凭据 - int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, context->accessee.appCredentialId); + int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, context->accessee.transmitCredentialId); if (ret != DM_OK) { LOGE("SinkFinish DeleteCredential failed."); } -- Gitee From 021eec6e84ae2458936045d375a1d6ad71871428 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 24 Mar 2025 19:34:43 +0800 Subject: [PATCH 265/382] remove requestId in 90 --- .../src/authentication_v2/auth_manager.cpp | 1 + .../authentication_v2/auth_stages/auth_negotiate.cpp | 10 ---------- .../authentication_v2/dm_auth_message_processor.cpp | 6 +----- 3 files changed, 2 insertions(+), 15 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 911f9f266..8e8543a11 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -654,6 +654,7 @@ void AuthManager::InitAuthState(const std::string &sessionName, int32_t authType DmAuthState::HandleAuthenticateTimeout(context_, name); }); GetAuthParam(sessionName, authType, deviceId, extra); + context_->requestId = context_->accesser.tokenId; context_->authStateMachine->TransitionTo(std::make_shared()); LOGI("AuthManager::AuthenticateDevice complete"); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 16b5e8808..dee10b91c 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -416,15 +416,6 @@ void AuthSinkNegotiateStateMachine::MatchFallBackCandidateList( } } -int64_t AuthSinkNegotiateStateMachine::GenRequestId() -{ - // 随机生成 PIN认证 的 requestId - int32_t part1 = GenRandInt(std::numeric_limits::min(), std::numeric_limits::max()); - int32_t part2 = GenRandInt(std::numeric_limits::min(), std::numeric_limits::max()); - uint64_t requestId = (static_cast(part1) << 32) | static_cast(part2); - return static_cast(requestId); -} - bool AuthSinkNegotiateStateMachine::IsAuthCodeReady(std::shared_ptr context) { if (context->importAuthCode.empty() || context->importSessionName.empty()) { @@ -442,7 +433,6 @@ bool AuthSinkNegotiateStateMachine::IsAuthCodeReady(std::shared_ptr context) { - context->requestId = GenRequestId(); context->authTypeList.clear(); // 根据 accessee.bundleName 和 src端 authType 查询 SP OHOS::DistributedDeviceProfile::LocalServiceInfo srvInfo; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index a88ad4140..41f4570d3 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -539,7 +539,6 @@ void DmAuthMessageProcessor::CreateRespNegotiateMessage(std::shared_ptrauthResultReady) { jsonObject[DM_TAG_AUTH_RESULT] = context->authResult; } - jsonObject[TAG_REQUEST_ID] = context->requestId; return; } @@ -853,6 +852,7 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(JsonObject &jsonObject, } if (jsonObject[DM_TAG_TOKEN_ID].IsNumberInteger()) { context->accesser.tokenId = static_cast(jsonObject[DM_TAG_TOKEN_ID].Get()); + context->requestId = context->accesser.tokenId; } if (jsonObject[TAG_DEVICE_ID_HASH].IsString()) { @@ -939,10 +939,6 @@ int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const JsonObject &j auto strList = jsonObject[DM_TAG_AUTH_TYPE_LIST].Get(); context->authTypeList = stringToVector(strList); } - if (jsonObject[TAG_REQUEST_ID].IsNumberInteger()) { - - context->requestId = jsonObject[TAG_REQUEST_ID].Get(); - } if (jsonObject.Contains(DM_TAG_AUTH_RESULT) && jsonObject[DM_TAG_AUTH_RESULT].IsNumberInteger()) { context->authResult = static_cast(jsonObject[DM_TAG_AUTH_RESULT].Get()); context->authResultReady = true; -- Gitee From 317c0b318eb5396cb75adddae5462baac8e82e63 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Mon, 24 Mar 2025 19:49:38 +0800 Subject: [PATCH 266/382] =?UTF-8?q?BUGFIX:=E4=BF=AE=E6=94=B9credential?= =?UTF-8?q?=E7=BC=96=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 9aa80be56..e4029532c 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -117,7 +117,7 @@ void DmAuthMessageProcessor::SetTransmitAccessControlList(std::shared_ptraccesser.tokenId); accesser.SetAccesserBundleName(context->accesser.bundleName); accesser.SetAccesserDeviceName(context->accesser.deviceName); - accesser.SetAccesserCredentialId(context->accesser.transmitCredentialId); + accesser.SetAccesserCredentialId(stoi(context->accesser.transmitCredentialId)); accesser.SetAccesserSessionKeyId(context->accesser.transmitSessionKeyId); accesser.SetAccesserSKTimeStamp(context->accesser.transmitSkTimeStamp); accessee.SetAccesseeDeviceId(context->accessee.deviceId); @@ -126,7 +126,7 @@ void DmAuthMessageProcessor::SetTransmitAccessControlList(std::shared_ptraccessee.tokenId); accessee.SetAccesseeBundleName(context->accessee.bundleName); accessee.SetAccesseeDeviceName(context->accessee.deviceName); - accessee.SetAccesseeCredentialId(context->accessee.transmitCredentialId); + accessee.SetAccesseeCredentialId(stoi(context->accessee.transmitCredentialId)); accessee.SetAccesseeSessionKeyId(context->accessee.transmitSessionKeyId); accessee.SetAccesseeSKTimeStamp(context->accessee.transmitSkTimeStamp); } @@ -138,14 +138,14 @@ void DmAuthMessageProcessor::SetLnnAccessControlList(std::shared_ptraccesser.userId); accesser.SetAccesserAccountId(context->accesser.accountId); accesser.SetAccesserDeviceName(context->accesser.deviceName); - accesser.SetAccesserCredentialId(context->accesser.lnnCredentialId); + accesser.SetAccesserCredentialId(stoi(context->accesser.lnnCredentialId)); accesser.SetAccesserSessionKeyId(context->accesser.lnnSessionKeyId); accesser.SetAccesserSKTimeStamp(context->accesser.lnnSkTimeStamp); accessee.SetAccesseeDeviceId(context->accessee.deviceId); accessee.SetAccesseeUserId(context->accessee.userId); accessee.SetAccesseeAccountId(context->accessee.accountId); accessee.SetAccesseeDeviceName(context->accessee.deviceName); - accessee.SetAccesseeCredentialId(context->accessee.lnnCredentialId); + accessee.SetAccesseeCredentialId(stoi(context->accessee.lnnCredentialId)); accessee.SetAccesseeSessionKeyId(context->accessee.lnnSessionKeyId); accessee.SetAccesseeSKTimeStamp(context->accessee.lnnSkTimeStamp); } -- Gitee From 5e1847f5fe74c282832bfc83cae6c36ff83189cb Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Mon, 24 Mar 2025 19:59:40 +0800 Subject: [PATCH 267/382] =?UTF-8?q?BUGFIX:=E4=BF=AE=E5=A4=8D=E9=94=99?= =?UTF-8?q?=E8=AF=AF=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication_v2/dm_auth_message_processor.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index e4029532c..91f8812e1 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -684,8 +684,8 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr access.tokenId = srcAccessToSync.tokenId; access.bundleName = srcAccessToSync.bundleName; access.bindLevel = srcAccessToSync.bindLevel; - access.sessionKeyId = srcAccessToSync.sessionKeyId; - access.skTimeStamp = srcAccessToSync.skTimeStamp; + access.transmitSessionKeyId = srcAccessToSync.sessionKeyId; + access.transmitSkTimeStamp = srcAccessToSync.skTimeStamp; if (jsonObject[DM_TAG_PROXY].IsString()) { // 预留字段 std::string proxyInfo = jsonObject[DM_TAG_PROXY].Get(); } @@ -1129,11 +1129,11 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptrisOnline) { // 首次认证 - syncMsgJson[DM_TAG_LNN_SK_ID]=std::to_string(accessToSync.lnnSessionKeyId); - syncMsgJson[DM_TAG_LNN_SK_TIMESTAMP]=std::to_string(accessToSync.lnnSkTimeStamp); + syncMsgJson[DM_TAG_LNN_SK_ID]=std::to_string(accessSide.lnnSessionKeyId); + syncMsgJson[DM_TAG_LNN_SK_TIMESTAMP]=std::to_string(accessSide.lnnSkTimeStamp); } JsonObject accessJsonObj; -- Gitee From 57cd4c55287c6c4496267c8dce273b621a4adb2a Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Mon, 24 Mar 2025 20:09:22 +0800 Subject: [PATCH 268/382] =?UTF-8?q?BUGFIX:=E4=BF=AE=E6=94=B9=E7=BC=96?= =?UTF-8?q?=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../implementation/src/authentication_v2/dm_auth_state.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 40a6a8420..48797afee 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -109,12 +109,12 @@ void DmAuthState::SourceFinish(std::shared_ptr context) if (context->reason != DM_OK) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); // 根据凭据id 删除sink端多余的凭据 - int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, context->accesser.transmitCredentialId); + int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, context->accesser.transmitCredentialId); // 这里只删除1个应该是bug? if (ret != DM_OK) { LOGE("SourceFinish DeleteCredential failed."); } // 根据skid删除sk,删除skid - ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accesser.sessionKeyId); + ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accesser.transmitSessionKeyId); if (ret != DM_OK) { LOGE("SourceFinish DeleteSessionKey failed."); } @@ -134,7 +134,7 @@ void DmAuthState::SinkFinish(std::shared_ptr context) LOGE("SinkFinish DeleteCredential failed."); } // 根据skid删除sk,删除skid - ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accessee.sessionKeyId); + ret = DeviceProfileConnector::GetInstance().DeleteSessionKey(context->accessee.transmitSessionKeyId); if (ret != DM_OK) { LOGE("SinkFinish DeleteSessionKey failed."); } -- Gitee From 65f2b25a14ae5578d1693b1557a14ebe1c0cfd87 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Mon, 24 Mar 2025 20:14:52 +0800 Subject: [PATCH 269/382] =?UTF-8?q?test:=20=E7=BF=BB=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/auth_manager.h | 45 ++-- .../authentication_v2/dm_auth_context.h | 198 +++++++++--------- .../authentication_v2/dm_auth_manager_base.h | 27 ++- .../dm_auth_message_processor.h | 161 +++++++------- .../include/authentication_v2/dm_auth_state.h | 47 ++--- .../authentication_v2/dm_auth_state_machine.h | 54 +++-- .../hichain/hichain_connector_callback.h | 7 - .../src/authentication/dm_auth_manager.cpp | 10 - .../src/authentication_v2/auth_manager.cpp | 10 +- .../auth_stages/auth_credential.cpp | 1 + .../dm_auth_manager_base.cpp | 18 ++ .../dm_auth_message_processor.cpp | 8 +- .../src/authentication_v2/dm_auth_state.cpp | 14 +- 13 files changed, 304 insertions(+), 296 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 8ea5cf057..f7d6f7a29 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -29,16 +29,14 @@ namespace OHOS { namespace DistributedHardware { struct DmAuthContext; -// 取自security_device_auth中的identity_service_defines.h,该头文件为内部头文件,不能直接引用 -// 若冲突删除此处 +// From identity_service_defines.h in security_device_auth enum { ACCOUNT_RELATED = 1, ACCOUNT_UNRELATED, ACCOUNT_ACROSS }; -// 取自security_device_auth中的identity_service_defines.h,该头文件为内部头文件,不能直接引用 -// 若冲突删除此处 +// From identity_service_defines.h in security_device_auth enum { SCOPE_DEVICE = 1, SCOPE_USER, @@ -53,9 +51,14 @@ public: std::shared_ptr hiChainAuthConnector); virtual ~AuthManager() = default; - // 对外API 实现 begin + // 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; - void OnScreenLocked(); + /** * @tc.name: AuthManager::GeneratePincode * @tc.desc: Generate Pincode of the DeviceManager Authenticate Manager @@ -63,8 +66,6 @@ public: */ int32_t BindTarget(const std::string &sessionName, const PeerTargetId &targetId, const std::map &bindParam); - // 停止绑定 TODO 如果多会话实例隔离后,pkgName 是不是不需要了? 后续其他API同理? - int32_t StopAuthenticateDevice(const std::string &sessionName); /** * @tc.name: AuthManager::OnUserOperation @@ -72,13 +73,14 @@ public: * @tc.type: FUNC */ int32_t GeneratePincode(); + /** * @tc.name: AuthManager::ImportAuthCode * @tc.desc: Import auth code * @tc.type: FUNC */ - // todo 新协议是通过DP去查询的? int32_t ImportAuthCode(const std::string &sessionName, const std::string &authCode); + /** * @tc.name: AuthManager::RegisterUiStateCallback * @tc.desc: Register ui state callback @@ -110,12 +112,13 @@ public: int32_t bindLevel, const std::string &extra); void HandleDeviceNotTrust(const std::string &udid); - int32_t DeleteGroup(const std::string &sessionName, const std::string &deviceId); int32_t RegisterAuthenticationType(int32_t authenticationType); - // 对外API 实现 end + void OnScreenLocked(); + int32_t StopAuthenticateDevice(const std::string &sessionName); + // External API begin end - // AuthManager 内部使用的接口 begin + // Internal API begin void SetAuthContext(std::shared_ptr context); std::shared_ptr GetAuthContext(); static bool IsHmlSessionType(std::string sessionType); @@ -124,23 +127,19 @@ public: std::map &bindParam); int32_t GetReason(); - // 提取本端ACL 用于消息解析和总线使用 无ACL会返回空字符串 json格式字符串:{dmversion:x,accesser:[{accesserDeviceId:y,...},...],accessee:{...}} + // 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_; - // IDmDeviceAuthCallback 转内部接口 - // pkgName是#define DM_APP_ID "ohos.distributedhardware.devicemanager" - // int32_t GetPinCode(std::string &sessionName, int32_t &code); int32_t GetPinCode(int32_t &code); void GetRemoteDeviceId(std::string &deviceId); - // IDmDeviceAuthCallback 转内部接口 private: int32_t ParseAuthType(const std::map &bindParam, int32_t &authType); int32_t ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType); @@ -168,9 +167,9 @@ public: std::shared_ptr hiChainAuthConnector); virtual ~AuthSrcManager() override = default; - // 对外API 实现 begin + // External API begin int32_t OnUserOperation(int32_t action, const std::string ¶ms) override; - // 对外API 实现 end + // External API end // IDmDeviceAuthCallback implement begin bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) override; @@ -185,9 +184,7 @@ public: void OnSessionClosed(int32_t sessionId) override; void OnDataReceived(int32_t sessionId, std::string message) override; - // 下面2个接口还需要实现吗? bool GetIsCryptoSupport() override; - // 与 OnDataReceived 合并实现 void OnAuthDeviceDataReceived(int32_t sessionId, std::string message) override; // ISoftbusSessionCallback implement end }; @@ -199,9 +196,9 @@ public: std::shared_ptr hiChainAuthConnector); virtual ~AuthSinkManager() override = default; - // 对外API 实现 begin + // External API begin int32_t OnUserOperation(int32_t action, const std::string ¶ms) override; - // 对外API 实现 end + // External API end // IDmDeviceAuthCallback implement begin bool AuthDeviceTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) override; diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 23f7a3381..0844a562c 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -40,16 +40,16 @@ namespace DistributedHardware { class DmAuthStateMachine; class DmAuthMessageProcessor; -// PIN码认证类型 +// PIN Code Authentication Type enum DmAuthType : int32_t { - AUTH_TYPE_CRE = 0, // 新协议未使用 - AUTH_TYPE_PIN, // 输入PIN码 - AUTH_TYPE_QR_CODE, // 新协议未使用 - AUTH_TYPE_NFC, // 新协议未使用 - AUTH_TYPE_NO_INTER_ACTION, // 新协议未使用 - AUTH_TYPE_IMPORT_AUTH_CODE, // 导入PIN码 - AUTH_TYPE_UNKNOW, // 新协议未使用 - AUTH_TYPE_PIN_ULTRASONIC, // 超声PIN码 + 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 { @@ -64,151 +64,149 @@ enum DmBindType { DM_AUTH_DEVICEID, }; -// 本端/远端 enum DmAuthSide { - DM_AUTH_LOCAL_SIDE = 0, // 本端 - DM_AUTH_REMOTE_SIDE, // 远端 + DM_AUTH_LOCAL_SIDE = 0, + DM_AUTH_REMOTE_SIDE, }; -// 凭据或公钥级别 authorizedScope enum DmAuthScope { - DM_AUTH_SCOPE_DEVICE = 1, // 设备级凭据 - DM_AUTH_SCOPE_USER, // 用户级凭据 - DM_AUTH_SCOPE_APP, // 应用级凭据 + DM_AUTH_SCOPE_DEVICE = 1, + DM_AUTH_SCOPE_USER, + DM_AUTH_SCOPE_APP, }; +// Used for one-touch pairing struct DmPeerTargetAddress { - std::string peerBrMacAddress; //一碰投使用,直接可以蓝牙建链 - std::string peerBleMacAddress; //一碰投使用,直接可以蓝牙建链 - std::string peerWifiMacAddress; //一碰投使用,直接可以蓝牙建链 - std::string peerActionMacAddress; //一碰投使用,直接可以蓝牙建链 - std::string peerWifiChannel; //一碰投使用 - std::string peerWifiIp; //一碰投使用 - uint16_t peerWifiPort; //一碰投使用 + // 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 peerDeivceId; // 兼容性,UDID,哈希值,PUBLIC权限 - int64_t peerServiceId; // Serviceid,主推,PUBLIC权限 - uint64_t peerSaTokenId; // SA-TokenID,过度,SA使用,校验系统权限 - std::string peerBundleName; //过度,同厂商使用,PUBLIC权限 - DmPeerTargetAddress peerTargetAddress; //通信对象的物理地址,校验系统权限 + DmBindType peerType; + std::string peerDeviceId; + int64_t peerServiceId; + uint64_t peerSaTokenId; + std::string peerBundleName; + DmPeerTargetAddress peerTargetAddress; }; struct DmAccess { std::string deviceName; - int32_t deviceType; // PC、mobile、手表、大屏等类型,为业务透传的数据,无需自定义 - std::string deviceId; // A->B, 无论是A端还是B端,Accesser对象都存A端的deviceId,Accessee对象都存B端的deviceId + 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; // 逻辑屏幕id + 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; // 存PacketName - int64_t serviceId; // 保留字段,后续会使用 + 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; // 用户级凭据Id - std::string transmitCredentialId; // 应用级凭据Id - std::string lnnPublicKey; // 用户级公钥 - std::string transmitPublicKey; // 应用级公钥 - std::vector bindType; // 绑定类型,如DM_IDENTICAL_ACCOUNT、DM_ACROSS_ACCOUNT、DM_POINT_TO_POINT - std::string publicKey; // T公钥长度 - int32_t status; // 表示服务为前台还是后台,业务透传,只保存 - int32_t sessionKeyId; // 作为秘钥派送的材料,在总线中取出sk - int32_t transmitSessionKeyId; // 本端永久应用SKID,由DP返回用于ACL的更新、老化 - int32_t lnnSessionKeyId; // 本端永久用户SKID,由DP返回用于ACL的更新、老化 - int64_t transmitSkTimeStamp; // 老化,时间为2天 应用级凭据时间戳 - int64_t lnnSkTimeStamp; // 老化,时间为2天 用户级凭据时间戳 - int64_t skTimeStamp; // 老化,时间为2天 + 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 transmitPublicKey; // 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; // 版本 5.1.0 - std::string edition; // 用于5.1.0版本前的兼容,协助版本协商 - std::string aclList; //可信关系列表,用于数据老化 KV格式 + 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; //凭据信息(点对点,同账号,..) 只保存凭据类型 kv结构 - std::string extraInfo; //可扩展字段,kv结构 + std::string credentialInfos; // Credential information (point-to-point, same account, etc.) + std::string extraInfo; // Expandable field, JSON format, KV structure std::string openAuthDeviceId; }; -// TODO 统一用初始化列表进行初始化 struct DmAuthContext { - bool isOnline; // 是否上线 - DmMessageType msgType; // 报文类型,枚举MsgType - int32_t sessionId; // 总线传输会话ID - int64_t requestId; // hichain认证ID - int32_t authBoxType{1}; // 认证框类型 - UiAction pinInputResult; // 输入PIN码结果 - UiAction authResult{UiAction::USER_OPERATION_TYPE_ALLOW_AUTH}; // 授权结果(使用0、1、6,即单次,取消和始终信任,enum UiAction) + 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_CANCEL_AUTH}; bool authResultReady{false}; - DmAuthType authType{DmAuthType::AUTH_TYPE_PIN}; // 认证方式,弹pin码、超声pin码、导入pin码 - std::vector authTypeList; // 共有认证方式列表 - uint32_t currentAuthTypeIdx{0}; // 认证方式索引 - int32_t inputPinAuthFailTimes{0}; // 输入PIN认证失败次数,超过3次则失败 - int32_t pinCode{INVALID_PINCODE}; // 生成的PIN码 - int32_t connDelayCloseTime; // 链路延迟释放时间, 授权结束后不自动断链(有业务需要使用)保留字段 - int32_t reason{DM_OK}; // 本端失败的原因 - int32_t reply; // 对端回复的结果 引用common/include/dm_constants.h,有新的错误码可新增 - int32_t state; // 结束的状态 + 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; // 标识正在认证中 - bool isFinished{false}; // 是否走到完成状态 - bool isAppCredentialVerified = false; // 应用凭据是否认证 - bool hmlEnable160M = false; - std::string sessionName; // 业务传入的标识,业务自定义,有被仿冒的风险 + 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; // 导入pin码的包名,从系统中读取,与acceserBundleName一致 - std::string appThumbnail; // 应用图标 - std::string appOperation; // 授权弹框中显示本次绑定用于什么操作 - std::string customData; // 业务自定义字段,详细提示用户本次绑定的操作 + 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; // 可扩展字段,kv结构 - DmAuthDirection direction; // 标识认证方向 - ProcessInfo processInfo; // 进程信息 - DmPeerTarget peerTarget; // 对端目标的信息 + 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; // 前面是accesser,后面是accessee + std::multimap proxy; // Multimap where the key is the accessor and the value is the accesssee - std::shared_ptr authStateMachine; // 状态机 + std::shared_ptr authStateMachine; std::shared_ptr authUiStateMgr; - std::shared_ptr hiChainAuthConnector; // HiChain交互接口 - std::shared_ptr authMessageProcessor; // 报文处理接口 - std::shared_ptr softbusConnector; // 软总线接口 + std::shared_ptr hiChainAuthConnector; + std::shared_ptr authMessageProcessor; + std::shared_ptr softbusConnector; std::shared_ptr listener; - std::shared_ptr authPtr; + std::shared_ptr authPtr; // Pointer to authentication interface std::shared_ptr timer; - std::string transmitData; // 保存 onTrasmit返回数据 + std::string transmitData; // Data returned from onTrasmit function std::string importSessionName = ""; std::string importAuthCode = ""; std::map> authenticationMap; PeerTargetId peerTargetId; - bool pinNegotiateStarted{false}; // pin协商是否已开始 - bool isAuthenticateDevice = false; + bool pinNegotiateStarted{false}; + bool isAuthenticateDevice{false}; // Whether device authentication is in progress - // 获取设备ID std::string GetDeviceId(DmAuthSide side); - // 获取用户ID int32_t GetUserId(DmAuthSide side); - // 获取凭据ID std::string GetCredentialId(DmAuthSide side, DmAuthScope authorizedScope); - // 获取公钥 std::string GetPublicKey(DmAuthSide side, DmAuthScope authorizedScope); - // 设置凭据ID int32_t SetCredentialId(DmAuthSide side, DmAuthScope authorizedScope, const std::string &credentialId); - // 设置公钥 int32_t SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope, const std::string &publicKey); - // 获取账号ID std::string GetAccountId(DmAuthSide side); }; diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h b/services/implementation/include/authentication_v2/dm_auth_manager_base.h index 093a1e754..41040630b 100644 --- a/services/implementation/include/authentication_v2/dm_auth_manager_base.h +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h @@ -46,6 +46,17 @@ 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; @@ -60,6 +71,7 @@ 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; @@ -70,7 +82,7 @@ extern const int32_t MIN_PIN_TOKEN; extern const int32_t MAX_PIN_TOKEN; -// device_manager_service_impl.cpp需要此定义,所以放在此处 +// need by device_manager_service_impl.cpp constexpr const char *DM_TAG_DMVERSION = "dmVersion"; constexpr const char *DM_TAG_EDITION = "edition"; @@ -163,23 +175,24 @@ public: virtual void HandleDeviceNotTrust(const std::string &udid) = 0; - virtual int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId) = 0; + virtual int32_t DeleteGroup(const std::string &pkgName, const std::string &deviceId); - // 5.1.0版本新增接口 + // New interface added in version 5.1.0 virtual int32_t GetReason(); - // 新协议切换到老协议时,需要获取之前的Params,以供老协议使用 + // 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); - // 检查authManager是否初始化成功 + // 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; }; diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index cf36be258..b023d8e5f 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -27,18 +27,18 @@ namespace DistributedHardware { struct DmAuthContext; struct DmAccess; -constexpr const char *DM_TAG_MSG_TYPE = "messageType"; // 报文类型 -constexpr const char *DM_TAG_DATA = "data"; // 报文数据 +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"; // 用户级公钥 lnnPublicKey -constexpr const char *DM_TAG_TRANSMIT_PUBLICK_KEY = "transmitPublicKey"; // 应用级公钥 transmitPublicKey -constexpr const char *DM_TAG_USER_CREDENTIAL_ID = "lnnCredentialId"; // 用户级凭据Id -constexpr const char *DM_TAG_APP_CREDENTIAL_ID = "transmitCredentialId"; // 应用级凭据Id -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"; // 当前授权类型索引 +constexpr const char *DM_TAG_LNN_PUBLICK_KEY = "lnnPublicKey"; +constexpr const char *DM_TAG_TRANSMIT_PUBLICK_KEY = "transmitPublicKey"; +constexpr const char *DM_TAG_USER_CREDENTIAL_ID = "lnnCredentialId"; +constexpr const char *DM_TAG_APP_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接口入参 json格式字符串中的key +// 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"; @@ -51,7 +51,7 @@ 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_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"; @@ -59,10 +59,11 @@ 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"; -constexpr const char *DM_TAG_TRANSMIT_SK_ID = "accessTransmitSKId"; // 本端sk信息 同步给对端 用于构造acl-accesser/accessee -constexpr const char *DM_TAG_LNN_SK_ID = "accessLnnSKId"; -constexpr const char *DM_TAG_TRANSMIT_SK_TIMESTAMP = "accessAppTransmitTimeStamp"; -constexpr const char *DM_TAG_LNN_SK_TIMESTAMP = "accessLnnSKTimeStamp"; +// 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"; @@ -93,7 +94,7 @@ constexpr const char* TAG_IS_ONLINE = "isOnline"; constexpr const char* TAG_IS_AUTHED = "isAuthed"; constexpr const char* TAG_CREDENTIAL_INFO = "credentialInfo"; -// accesser table内容 用于同步ACL +// 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"; @@ -107,7 +108,7 @@ 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内容 用于同步ACL +// 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"; @@ -121,12 +122,11 @@ 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, @@ -164,21 +164,23 @@ struct DmAccessControlTable { uint32_t bindLevel; }; -// 用于同步ACL的access结构 -// 注意:修改本结构体 需要同步修改dm_auth_message_processor.cpp中的From/ToJson函数 +// 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; - std::string deviceId; // A->B, 无论是A端还是B端,Accesser对象都存A端的deviceId,Accessee对象都存B端的deviceId + // 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; // 存PacketName - int32_t bindLevel; // 为业务透传数据,无需自定义 - int32_t sessionKeyId; // 用户凭据ID - int64_t skTimeStamp; // 老化,时间为2天 用户级凭据时间戳 + 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和结构体转换函数 +// 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); @@ -189,114 +191,119 @@ class DmAuthMessageProcessor { public: DmAuthMessageProcessor(); ~DmAuthMessageProcessor(); - // 解析报文,返回值为错误码,实际解析出来的信息保存到context中 + // Parse the message, and save the parsed information to the context int32_t ParseMessage(std::shared_ptr context, const std::string &message); - // 创建报文,构造对应msgType的报文,返回值为json格式报文的字符串 + // 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); - // 保存永久SK + // Save the permanent session key to the data profile int32_t SaveSessionKeyToDP(int32_t &skId); - // 保留本次acl + // Save the current access control list int32_t PutAccessControlList(std::shared_ptr context, DmAccess &access, std::string trustDeviceId); - // 对acl进行checksum + // Calculate the checksum for the access control list bool ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl, std::vector &accesserStrList, std::vector &accesseeStrList); - // 提取本端ACL 用于消息解析和总线使用 无ACL会返回空字符串 json格式字符串:{dmversion:x,accesser:[{accesserDeviceId:y,...},...],accessee:{...}} + // 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 - // 用于组装syncMsg中的加密部分 + // Used to encrypt the synchronization message int32_t EncryptSyncMessage(std::shared_ptr &context, DmAccess &accessSide, std::string &encSyncMsg); - int32_t ParseAuthStartMessgae(JsonObject &jsonObject, std::shared_ptr &context); + // Parse the authentication start message + int32_t ParseAuthStartMessage(JsonObject &jsonObject, std::shared_ptr &context); - // 解析 80报文 + // Parse the 80 message int32_t ParseNegotiateMessage(JsonObject &jsonObject, std::shared_ptr context); - // 解析 90 报文 + // Parse the 90 message int32_t ParseMessageRespAclNegotiate(const JsonObject &json, std::shared_ptr context); - // 解析 100 报文 + // Parse the 100 message int32_t ParseMessageReqUserConfirm(const JsonObject &json, std::shared_ptr context); - // 解析 110 报文 + // Parse the 110 message int32_t ParseMessageRespUserConfirm(const JsonObject &json, std::shared_ptr context); - // 解析 120 报文 + // Parse the 120 message int32_t ParseMessageReqPinAuthStart(const JsonObject &json, std::shared_ptr context); - // 解析 130 报文 + // Parse the 130 message int32_t ParseMessageRespPinAuthStart(const JsonObject &json, std::shared_ptr context); - // 解析 121 报文 + // Parse the 121 message int32_t ParseMessageReqPinAuthNegotiate(const JsonObject &json, std::shared_ptr context); - // 解析 131报文 + // Parse the 131 message int32_t ParseMessageRespPinAuthNegotiate(const JsonObject &jsonObject, std::shared_ptr context); - // 解析 140报文信息MSG_TYPE_REQ_CREDENTIAL_EXCHANGE,SINK端存放对方公钥 + // Parse the 140 message int32_t ParseMessageReqCredExchange(const JsonObject &jsonObject, std::shared_ptr context); - // 解析 150报文信息MSG_TYPE_RESP_CREDENTIAL_EXCHANGE,存放对方公钥,和协商凭据Id + // Parse the 150 message int32_t ParseMessageRspCredExchange(const JsonObject &jsonObject, std::shared_ptr context); - // 解析161 170 171 + // Parse the 161, 170, and 171 messages int32_t ParseMessageNegotiateTransmit(const JsonObject &jsonObject, std::shared_ptr &context, DmMessageType msgType); - // 解析 180报文信息 MSG_TYPE_REQ_DATA_SYNC 存放对方密文四元组,acl,sp skid + // Parse the 180 message int32_t ParseMessageSyncReq(const JsonObject &jsonObject, std::shared_ptr context); - // 解析 190报文信息 MSG_TYPE_RESP_DATA_SYNC 存放对方密文四元组,acl sp skid + // Parse the 190 message int32_t ParseMessageSyncResp(const JsonObject &jsonObject, std::shared_ptr context); - // 解析 200报文信息 + // Parse the 200 message int32_t ParseMessageSinkFinish(const JsonObject &jsonObject, std::shared_ptr context); - // 解析 201报文信息 + // Parse the 201 message int32_t ParseMessageSrcFinish(const JsonObject &jsonObject, std::shared_ptr context); - // 创建 80报文 + // Create the 80 message void CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); - // 创建 90报文 + // Create the 90 message void CreateRespNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); - // 创建 100 报文 + // Create the 100 message void CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json); - // 创建 110 报文 + // Create the 110 message void CreateMessageRespUserConfirm(std::shared_ptr context, JsonObject &json); - // 创建 120 报文 + // Create the 120 message void CreateMessageReqPinAuthStart(std::shared_ptr context, JsonObject &json); - // 创建 130 报文 + // Create the 130 message void CreateMessageRespPinAuthStart(std::shared_ptr context, JsonObject &json); - // 创建 121 报文 + // Create the 121 message void CreateMessageReqPinAuthNegotiate(std::shared_ptr context, JsonObject &json); - // 创建 131 报文 + // Create the 131 message void CreateMessageRespPinAuthNegotiate(std::shared_ptr context, JsonObject &json); - // 创建140报文 + // Create the 140 message void CreateMessageReqCredExchange(std::shared_ptr context, JsonObject &jsonObject); - // 创建150报文 + // Create the 150 message void CreateMessageRspCredExchange(std::shared_ptr context, JsonObject &jsonObject); - // 创建160报文 + // Create the 160 message void CreateMessageReqCredAuthStart(std::shared_ptr context, JsonObject &jsonObject); - // 161 170 171 透传凭据认证消息构造 + // Construct the 161, 170, and 171 credential authentication messages int32_t CreateCredentialNegotiateMessage(std::shared_ptr &context, JsonObject &jsonObject); - // 180 190 消息构造 + // Construct the 180 and 190 sync messages int32_t CreateSyncMessage(std::shared_ptr &context, JsonObject &jsonObject); - // 压缩sync 消息 + // Create the 190 message + void CreateMessageSyncResp(std::shared_ptr context, JsonObject &jsonObject); + // Create the 200 message + void CreateMessageFinish(std::shared_ptr context, JsonObject &jsonObject); + + // Compress the sync message std::string CompressSyncMsg(std::string &inputStr); - // 解压缩sync 消息 + // Decompress the sync message std::string DecompressSyncMsg(std::string& compressed, uint32_t oriLen); - // 序列化acl + // Serialize the ACL int32_t ACLToStr(DistributedDeviceProfile::AccessControlProfile acl, std::string aclStr); - // 创建190报文 - void CreateMessageSyncResp(std::shared_ptr context, JsonObject &jsonObject); - // 创建200报文 - void CreateMessageFinish(std::shared_ptr context, JsonObject &jsonObject); - // 解密180 190报文 + // 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); - // DP中accesser_table记录转string + // Convert the accesser_table record in DP to a string std::string AccesserToStr(DistributedDeviceProfile::AccessControlProfile acl); - // DP中accessee_table记录转string + // 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); diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 78b3332de..3617e5645 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -24,16 +24,6 @@ namespace OHOS { namespace DistributedHardware { -constexpr const char* AUTHENTICATE_TIMEOUT_TASK = "deviceManagerTimer:authenticate"; -constexpr const char* NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:negotiate"; -constexpr const char* CONFIRM_TIMEOUT_TASK = "deviceManagerTimer:confirm"; -constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; -constexpr const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; -constexpr const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; -constexpr const char* WAIT_PIN_AUTH_TIMEOUT_TASK = "deviceManagerTimer:waitPinAuth"; -constexpr const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; -constexpr const char* ADD_TIMEOUT_TASK = "deviceManagerTimer:add"; - // 状态类型 enum class DmAuthStateType { AUTH_IDLE_STATE = 0, // 设备初始化时 @@ -73,42 +63,42 @@ enum class DmAuthStateType { // 凭据添加方式 enum DmAuthCredentialAddMethod : uint8_t { - DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE = 1, // 生成 - DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT, // 导入 + 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, // 配件 + 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, // 账号无关 + 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证书 + 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 + 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 + DM_AUTH_CREDENTIAL_PROOF_PSK = 1, // PSK + DM_AUTH_CREDENTIAL_PROOF_PKI, // PKI }; class DmAuthState { @@ -149,8 +139,8 @@ public: DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; private: - int32_t ShowConfigDialog(std::shared_ptr context); // 提示用户授权对话框 - int64_t GenRequestId(std::shared_ptr context); // 生成HiChain请求ID + int32_t ShowConfigDialog(std::shared_ptr context); // 提示用户授权对话框 + int64_t GenRequestId(std::shared_ptr context); // 生成HiChain请求ID }; class AuthSrcPinNegotiateStartState : public DmAuthState { @@ -265,7 +255,6 @@ protected: // 生成凭据协商状态下的authParams的json格式字符串 std::string CreateAuthParamsString(DmAuthScope authorizedScope, DmAuthCredentialAddMethod method, const std::shared_ptr &authContext); - // 生成凭据Id和公钥 int32_t GenerateCredIdAndPublicKey(DmAuthScope authorizedScope, std::shared_ptr &authContext); // 协商凭据得到协商凭据Id int32_t AgreeCredential(DmAuthScope authorizedScope, std::shared_ptr &authContext); diff --git a/services/implementation/include/authentication_v2/dm_auth_state_machine.h b/services/implementation/include/authentication_v2/dm_auth_state_machine.h index f7de4b30f..60af69c5f 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state_machine.h +++ b/services/implementation/include/authentication_v2/dm_auth_state_machine.h @@ -31,7 +31,7 @@ namespace OHOS { namespace DistributedHardware { -// 定义状态迁移表类型 +// Define the state transition table type using StateTransitionTable = std::map>; enum DmEventType { @@ -41,10 +41,10 @@ enum DmEventType { ON_FINISH, ON_ERROR, - ON_TIMEOUT, // 超时 - ON_USER_OPERATION, // 用户操作 - ON_FAIL, // 失败流程 - ON_SCREEN_LOCKED, // 锁屏 + ON_TIMEOUT, + ON_USER_OPERATION, + ON_FAIL, + ON_SCREEN_LOCKED, }; class DmAuthStateMachine { @@ -52,45 +52,61 @@ public: DmAuthStateMachine(std::shared_ptr context); ~DmAuthStateMachine(); - // 通知状态迁移,执行状态对应具体action与异常处理(只允许在OnDataReceived中调用) + // 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); - // action内部的期望事件,用于阻塞,当等到期望事件完成或其他异常时,返回实际发生的事件,而其他正常事件则会继续阻塞(只允许在action中调用) + + // 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); - // 事件完成调用,传事件枚举(只允许在事件触发中调用),如果是异常事件,需在context的reason或者reply记录 + + // 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: - // 循环等待状态转移,执行action + // Loop to wait for state transitions and execute actions void Run(std::shared_ptr context); - // 获取状态,进行执行 + // Fetch the current state and execute it std::optional> FetchState(); - // 设置当前状态 + void SetCurState(DmAuthStateType state); - // 检验下一状态迁移合法性 + bool CheckStateTransitValid(DmAuthStateType nextState); - // 存储当前状态 DmAuthStateType curState_; - // 正常状态迁移表,但所有状态切换到Finish状态是合法的 + + // 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_; }; diff --git a/services/implementation/include/dependency/hichain/hichain_connector_callback.h b/services/implementation/include/dependency/hichain/hichain_connector_callback.h index 26ab01576..56dd42bbc 100644 --- a/services/implementation/include/dependency/hichain/hichain_connector_callback.h +++ b/services/implementation/include/dependency/hichain/hichain_connector_callback.h @@ -37,13 +37,6 @@ public: virtual void AuthDeviceFinish(int64_t requestId) = 0; virtual void AuthDeviceError(int64_t requestId, int32_t errorCode) = 0; virtual void AuthDeviceSessionKey(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) = 0; - // virtual int32_t GetPinCode(std::string &pkgName, int32_t &code) - // { - // pkgName = ""; - // return GetPinCode(code); - // }; - // virtual int32_t GetPinCode(int32_t &code) = 0; - // virtual void GetRemoteDeviceId(std::string &deviceId) = 0; virtual char *AuthDeviceRequest(int64_t requestId, int operationCode, const char *reqParams) = 0; }; } // namespace DistributedHardware diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index f11671499..6a63d5ece 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -68,16 +68,6 @@ const int32_t ALREADY_BIND = 1; const int32_t STRTOLL_BASE_10 = 10; const int32_t MAX_PUT_SESSIONKEY_TIMEOUT = 100; //ms -constexpr const char* AUTHENTICATE_TIMEOUT_TASK = "deviceManagerTimer:authenticate"; -constexpr const char* NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:negotiate"; -constexpr const char* CONFIRM_TIMEOUT_TASK = "deviceManagerTimer:confirm"; -constexpr const char* INPUT_TIMEOUT_TASK = "deviceManagerTimer:input"; -constexpr const char* ADD_TIMEOUT_TASK = "deviceManagerTimer:add"; -constexpr const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; -constexpr const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; -constexpr const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; -constexpr const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; - constexpr int32_t PROCESS_NAME_WHITE_LIST_NUM = 1; constexpr const static char* PROCESS_NAME_WHITE_LIST[PROCESS_NAME_WHITE_LIST_NUM] = { "com.example.myapplication", diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 004a2940e..1d63d5456 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -293,12 +293,7 @@ void AuthManager::HandleDeviceNotTrust(const std::string &udid) // todo LOGI("AuthManager::HandleDeviceNotTrust start"); } -int32_t AuthManager::DeleteGroup(const std::string &sessionName, const std::string &deviceId) -{ - // todo - LOGI("AuthManager::DeleteGroup start"); - return ERR_DM_FAILED; -} + int32_t AuthManager::RegisterAuthenticationType(int32_t authenticationType) { if (authenticationType != USER_OPERATION_TYPE_ALLOW_AUTH && @@ -310,6 +305,9 @@ int32_t AuthManager::RegisterAuthenticationType(int32_t authenticationType) return DM_OK; } +// Extract the local ACL for message parsing and bus usage. +// Without ACL, an empty string will be returned. +// JSON format string: {dmversion:x,accesser:[{accesserDeviceId:y,...},...],accessee:{...}} int32_t AuthManager::GetAclListStr(std::string &aclList) { return context_->authMessageProcessor->GetAclListStr(context_, aclList); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 1ac29a31d..462a19bae 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -18,6 +18,7 @@ #include #include "dm_auth_state.h" #include "dm_auth_context.h" +#include "dm_auth_manager_base.h" #include "dm_auth_state_machine.h" #include "dm_auth_message_processor.h" #include "dm_log.h" diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp index b29d09b09..9014006bb 100644 --- a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp @@ -45,6 +45,17 @@ const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; const char* CANCEL_DISPLAY_KEY = "cancelPinCodeDisplay"; const char* BUNDLE_NAME_KEY = "bundleName"; +const char* AUTHENTICATE_TIMEOUT_TASK = "deviceManagerTimer:authenticate"; +const char* NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:negotiate"; +const char* CONFIRM_TIMEOUT_TASK = "deviceManagerTimer:confirm"; +const char* INPUT_TIMEOUT_TASK = "deviceManagerTimer:input"; +const char* SESSION_HEARTBEAT_TIMEOUT_TASK = "deviceManagerTimer:sessionHeartbeat"; +const char* WAIT_REQUEST_TIMEOUT_TASK = "deviceManagerTimer:waitRequest"; +const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; +const char* WAIT_PIN_AUTH_TIMEOUT_TASK = "deviceManagerTimer:waitPinAuth"; +const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; +const char* ADD_TIMEOUT_TASK = "deviceManagerTimer:add"; + const int32_t AUTHENTICATE_TIMEOUT = 120; const int32_t CONFIRM_TIMEOUT = 60; const int32_t NEGOTIATE_TIMEOUT = 10; @@ -59,6 +70,7 @@ const int32_t CLONE_ADD_TIMEOUT = 10; const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10; const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10; const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20; +const int32_t CLONE_PIN_AUTH_TIMEOUT = 10; const int32_t HML_SESSION_TIMEOUT = 10; const int32_t SESSION_HEARTBEAT_TIMEOUT = 50; const int32_t PIN_AUTH_TIMEOUT = 60; @@ -287,6 +299,12 @@ int32_t AuthManagerBase::StopAuthenticateDevice(const std::string &pkgName) return ERR_DM_FAILED; } +int32_t AuthManagerBase::DeleteGroup(const std::string &pkgName, const std::string &deviceId) +{ + LOGE("DeleteGroup is not implemented in the current version"); + return ERR_DM_FAILED; +} + int32_t AuthManagerBase::GetReason() { LOGE("GetReason is not implemented in the current version"); diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 91f8812e1..657b4c603 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -231,7 +231,7 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont case MSG_TYPE_RESP_PIN_AUTH_START: return ParseMessageRespPinAuthStart(jsonObject, context); case MSG_TYPE_REQ_CREDENTIAL_AUTH_START: // 160 - return ParseAuthStartMessgae(jsonObject, context); + return ParseAuthStartMessage(jsonObject, context); case MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE: // 161 case MSG_TYPE_RESP_CREDENTIAL_AUTH_START: // 170 case MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE: // 171 @@ -1246,11 +1246,11 @@ int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr } // 解析transmit和PSKID 解析160 -int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(JsonObject &jsonObject, std::shared_ptr &context) +int32_t DmAuthMessageProcessor::ParseAuthStartMessage(JsonObject &jsonObject, std::shared_ptr &context) { if (jsonObject.IsDiscarded() || !jsonObject.Contains(DM_TAG_DATA) || !jsonObject[DM_TAG_DATA].IsString()) { - LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae Unlegal json string failed"); + LOGE("DmAuthMessageProcessor::ParseAuthStartMessage Unlegal json string failed"); return ERR_DM_FAILED; } context->transmitData = jsonObject[DM_TAG_DATA].Get(); @@ -1268,7 +1268,7 @@ int32_t DmAuthMessageProcessor::ParseAuthStartMessgae(JsonObject &jsonObject, st } if (!jsonObject.Contains(jsonTag) || !jsonObject[jsonTag].IsString()) { - LOGE("DmAuthMessageProcessor::ParseAuthStartMessgae Unlegal json CRED ID"); + LOGE("DmAuthMessageProcessor::ParseAuthStartMessage Unlegal json CRED ID"); return ERR_DM_FAILED; } diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 48797afee..087000909 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -15,6 +15,7 @@ #include "dm_auth_state.h" #include "dm_auth_context.h" +#include "dm_auth_manager_base.h" #include "dm_auth_state_machine.h" #include "multiple_user_connector.h" #if defined(SUPPORT_SCREENLOCK) @@ -28,19 +29,6 @@ namespace OHOS { namespace DistributedHardware { -namespace { - -const int32_t CLONE_AUTHENTICATE_TIMEOUT = 20; -const int32_t CLONE_NEGOTIATE_TIMEOUT = 10; -const int32_t CLONE_CONFIRM_TIMEOUT = 10; -const int32_t CLONE_ADD_TIMEOUT = 10; -const int32_t CLONE_WAIT_NEGOTIATE_TIMEOUT = 10; -const int32_t CLONE_WAIT_REQUEST_TIMEOUT = 10; -const int32_t CLONE_SESSION_HEARTBEAT_TIMEOUT = 20; -const int32_t CLONE_PIN_AUTH_TIMEOUT = 10; - -} - // clone task timeout map const std::map TASK_TIME_OUT_MAP = { { std::string(AUTHENTICATE_TIMEOUT_TASK), CLONE_AUTHENTICATE_TIMEOUT }, -- Gitee From ad3626c66526a9dd36c6510fe1233cfce43c61ab Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 24 Mar 2025 20:53:00 +0800 Subject: [PATCH 270/382] style --- .../include/authentication_v2/dm_auth_state.h | 3 +- .../auth_stages/auth_confirm.cpp | 71 +++----------- .../auth_stages/auth_negotiate.cpp | 27 +++--- .../auth_stages/auth_pin_auth.cpp | 94 +++++++++---------- 4 files changed, 75 insertions(+), 120 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 3617e5645..f42d1cbac 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -139,8 +139,7 @@ public: DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; private: - int32_t ShowConfigDialog(std::shared_ptr context); // 提示用户授权对话框 - int64_t GenRequestId(std::shared_ptr context); // 生成HiChain请求ID + int32_t ShowConfigDialog(std::shared_ptr context); }; class AuthSrcPinNegotiateStartState : public DmAuthState { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 80f511379..5c2d1481e 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -57,9 +57,8 @@ int32_t AuthSrcConfirmState::DoPinAuth(std::shared_ptr context) context->currentAuthTypeIdx = 0; context->authType = context->authTypeList[0]; - // 首次认证是输入PIN或超声PIN时,先授权 if (!context->authResultReady) { - // send 100 + // send 100 msg context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_USER_CONFIRM, context); context->timer->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), @@ -68,58 +67,26 @@ int32_t AuthSrcConfirmState::DoPinAuth(std::shared_ptr context) HandleAuthenticateTimeout(context, name); }); } else { - // 少一轮 100,110 + // skip 100, 110 msg context->authStateMachine->TransitionTo(std::make_shared()); } - LOGI("AuthSrcConfirmState::DoPinAuth end"); return DM_OK; } int32_t AuthSrcConfirmState::Action(std::shared_ptr context) { LOGI("AuthSrcConfirmState::Action start"); + // check version compatibility context->timer->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); if (CompareVersion(context->accessee.dmVersion, std::string(DM_VERSION_5_1_0))) { LOGE("AuthSrcConfirmState::Action incompatible version %{public}s compare to 5.1.0", context->accessee.dmVersion.c_str()); - context->reason = ERR_DM_VERSION_INCOMPATIBLE; // todo 发104报文???应该finished状态处理 + context->reason = ERR_DM_VERSION_INCOMPATIBLE; return ERR_DM_VERSION_INCOMPATIBLE; } -#if 0 // todo 有凭据情况 - JsonObject jsonObject(context->accessee.credentialInfos); - if (jsonObject.IsDiscarded()) { - LOGE("AuthSrcConfirmState::Action parse credentialInfos error"); - return ERR_DM_FAILED; - } - // 转结束绑定 - context->authStateMachine->TransitionTo(std::make_shared()); - - // 转凭据认证 - context->authStateMachine->TransitionTo(std::make_shared()); - - // 有无可信关系的分享凭据 - if (g_shareByPinAuthDeviceTypeSet.contains(static_cast(context->deviceType))) { - // 走PIN码认证 - return DoPinAuth(context); - } else { - // 转凭据认证 - context->authStateMachine->TransitionTo(std::make_shared()); - } - // 有点对点可信 - // if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { - if (!context->authTypeList.empty() && context->authTypeList[0] == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { - // 走PIN码导入 - return DoPinAuth(context); - } else { - // 结束绑定 - context->authStateMachine->TransitionTo(std::make_shared()); - } - // 无凭据 - return DoPinAuth(context); -#else + // no credential, try to do pin auth return DoPinAuth(context); -#endif } DmAuthStateType AuthSinkConfirmState::GetStateType() @@ -152,18 +119,9 @@ int32_t AuthSinkConfirmState::ShowConfigDialog(std::shared_ptr co return DM_OK; } -int64_t AuthSinkConfirmState::GenRequestId(std::shared_ptr context) -{ - uint64_t requestId = static_cast(context->sessionId); - requestId <<= 32; // 高32位为sessionId - requestId += static_cast(DmAuthStateType::AUTH_SINK_CONFIRM_STATE); // 低32位为状态编号 - return static_cast(requestId); -} - int32_t AuthSinkConfirmState::Action(std::shared_ptr context) { LOGI("AuthSinkConfirmState::Action start"); - // 停止授权报文计时 context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); if (context->authTypeList.empty()) { @@ -173,30 +131,29 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) } context->authType = context->authTypeList[context->currentAuthTypeIdx]; - if (context->authBoxType == DistributedDeviceProfile::NUM_1) { // 三态框 + if (context->authBoxType == DistributedDeviceProfile::NUM_1) { // tristate box LOGI("AuthSinkConfirmState::Action 3box"); - // 拉起授权确认页面 + // show user confirmation dialog auto ret = ShowConfigDialog(context); if (ret != DM_OK) { return ret; } - // 等待用户授权操作完成 + // wait for user opration if (DmEventType::ON_USER_OPERATION != context->authStateMachine->WaitExpectEvent(DmEventType::ON_USER_OPERATION)) { LOGE("AuthSinkConfirmState::Action wait ON_USER_OPERATION err"); - return STOP_BIND; // 外部事件错误,中止流程 + return STOP_BIND; } - // 判断授权结果 if (context->reply != USER_OPERATION_TYPE_ALLOW_AUTH) { LOGI("AuthSinkConfirmState::Action USER_OPERATION_TYPE_CANCEL_AUTH"); context->reason = ERR_DM_BIND_USER_CANCEL; - return STOP_BIND; // 用户取消授权 + return STOP_BIND; } - } else if (context->authBoxType == DistributedDeviceProfile::NUM_2) { // 免弹框 + } else if (context->authBoxType == DistributedDeviceProfile::NUM_2) { // no authorization box if (context->authResult == USER_OPERATION_TYPE_CANCEL_AUTH) { LOGI("AuthSinkConfirmState::Action USER_OPERATION_TYPE_CANCEL_AUTH"); context->reason = ERR_DM_BIND_USER_CANCEL; - return STOP_BIND; // 用户取消授权 + return STOP_BIND; } } else { LOGE("AuthSinkConfirmState::Action authBoxType not support"); @@ -204,12 +161,10 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) return ERR_DM_UNSUPPORTED_AUTH_TYPE; } - // 发送110报文 + // send 110 msg context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); context->authStateMachine->TransitionTo(std::make_shared()); - - LOGI("AuthSinkConfirmState::Action ok"); return DM_OK; } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index dee10b91c..07254ad24 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -48,11 +48,13 @@ namespace DistributedHardware { namespace { +// authType fallback table using FallBackKey = std::pair; // accessee.bundleName, authType static std::map g_pinAuthTypeFallBackMap = { {{"cast_engine_service", DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE}, DmAuthType::AUTH_TYPE_PIN}, }; -constexpr size_t MAX_FALLBACK_LOOPKUP_TIMES = 2; // 最大递归查找次数 +// Maximum number of recursive lookups +constexpr size_t MAX_FALLBACK_LOOPKUP_TIMES = 2; // security_device_auth凭据查询相关定义,保持与device_auth.h一致 const char * const FILED_DEVICE_ID = "deviceId"; @@ -434,21 +436,22 @@ bool AuthSinkNegotiateStateMachine::IsAuthCodeReady(std::shared_ptr context) { context->authTypeList.clear(); - // 根据 accessee.bundleName 和 src端 authType 查询 SP + // query ServiceInfo by accessee.bundleName and authType from client OHOS::DistributedDeviceProfile::LocalServiceInfo srvInfo; auto ret = DeviceProfileConnector::GetInstance().GetLocalServiceInfoByBundleNameAndPinExchangeType( context->accessee.bundleName, context->authType, srvInfo); if (ret == OHOS::DistributedDeviceProfile::DP_SUCCESS) { - context->authTypeList.push_back(context->authType); // 匹配到,则添加到候选列表 + // ServiceInfo found + context->authTypeList.push_back(context->authType); context->authBoxType = srvInfo.GetAuthBoxType(); if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { - // 读取PIN码 + // read pincode std::string pinCode = srvInfo.GetPinCode(); context->pinCode = std::stoi(pinCode); } - if (context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { // 免弹框 + if (context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { // no authorization box int32_t authResult = srvInfo.GetAuthType(); if (authResult == 0) { context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH; @@ -464,24 +467,26 @@ void AuthSinkNegotiateStateMachine::NegotiatePinAuthType(std::shared_ptrcustomData = srvInfo.GetDescription(); } } else { - context->authBoxType = OHOS::DistributedDeviceProfile::NUM_1; // 默认三态框 + context->authBoxType = OHOS::DistributedDeviceProfile::NUM_1; // default: tristate box - // 特殊应用导入了PIN码 if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + // need to check if pincode ready if (IsAuthCodeReady(context)) { + // only special scenarios can import pincode context->authTypeList.push_back(context->authType); - context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // 免弹框 + context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // no authorization box context->authResultReady = true; } } else { - context->authTypeList.push_back(context->authType); // 没匹配到,但是不是导入授权码,也添加到候选列表 + // match fail, also add src's authType + context->authTypeList.push_back(context->authType); } - // 如果不是免弹框则授权类型默认为取消 + // not special scenarios, reset authResult to cancel if (context->authBoxType != OHOS::DistributedDeviceProfile::NUM_2) { context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; } } - // 查询回退表 + // lookup fallback table MatchFallBackCandidateList(context, context->authType); if (context->authTypeList.size() > 0) { context->authType = context->authTypeList[0]; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 90bd30038..bc6a91bdf 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -74,7 +74,7 @@ void AuthSinkStatePinAuthComm::HandleSessionHeartbeat(std::shared_ptr context) @@ -90,21 +90,22 @@ DmAuthStateType AuthSrcPinAuthStartState::GetStateType() int32_t AuthSrcPinAuthStartState::Action(std::shared_ptr context) { LOGI("AuthSrcPinAuthStartState::Action start"); + // auth pincode int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); auto ret = context->hiChainAuthConnector->AuthCredentialPinCode(osAccountId, context->requestId, context->pinCode); if (ret != DM_OK) { - LOGE("AuthSrcPinAuthStartState::AuthDevice failed."); + LOGE("AuthSrcPinAuthStartState::AuthDevice call AuthCredentialPinCode failed."); return ret; } - // 等待hiChain响应 transmit + // wait for onTransmit from hiChain auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); if (retEvent == DmEventType::ON_TRANSMIT) { - // 发送120报文 + // send 120 msg context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_PIN_AUTH_START, context); return DM_OK; } else if (retEvent == DmEventType::ON_ERROR) { - LOGI("AuthSrcPinAuthStartState::AuthDevice ON_ERROR failed."); + LOGI("AuthSrcPinAuthStartState::AuthDevice ON_ERROR failed, maybe retry."); return DM_OK; } @@ -129,7 +130,7 @@ int32_t AuthSinkPinAuthStartState::Action(std::shared_ptr context }); } - // 拦截异常认证流程 + // Stop the abnormal authentication process if (context->authTypeList.empty() || (context->authResult != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH && context->authResult != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS)) { @@ -137,23 +138,24 @@ int32_t AuthSinkPinAuthStartState::Action(std::shared_ptr context return ERR_DM_INPUT_PARA_INVALID; } + // process pincode auth auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); if (ret != DM_OK) { - LOGE("AuthSinkPinAuthStartState::Action call ProcessCredData err"); + LOGE("AuthSinkPinAuthStartState::Action call ProcessCredData err."); return ret; } - // 等待hiChain响应 transmit + // wait for onTransmit from hiChain auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); if (retEvent == DmEventType::ON_TRANSMIT) { - // 发送130报文 + // send 130 msg context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_PIN_AUTH_START, context); return DM_OK; } if (retEvent == DmEventType::ON_ERROR) { - LOGI("AuthSrcPinAuthStartState::AuthDevice ON_ERROR failed."); + LOGI("AuthSrcPinAuthStartState::AuthDevice ON_ERROR failed, maybe retry."); return DM_OK; } - return STOP_BIND; // 外部事件错误,中止流程 + return STOP_BIND; } DmAuthStateType AuthSrcPinAuthMsgNegotiateState::GetStateType() @@ -166,21 +168,22 @@ int32_t AuthSrcPinAuthMsgNegotiateState::Action(std::shared_ptr c LOGI("AuthSrcPinAuthMsgNegotiateState::Action start"); auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); if (ret != DM_OK) { - LOGE("AuthSrcPinAuthMsgNegotiateState::Action call ProcessCredData err"); + LOGE("AuthSrcPinAuthMsgNegotiateState::Action call ProcessCredData err."); return ret; } - // 等待hiChain响应 transmit + // wait for onTransmit from hiChain auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); if (retEvent == DmEventType::ON_TRANSMIT) { - // 发送121报文 + // send 121 msg context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, context); return DM_OK; } if (retEvent == DmEventType::ON_ERROR) { - LOGI("AuthSrcPinAuthMsgNegotiateState::AuthDevice ON_ERROR failed."); + LOGI("AuthSrcPinAuthMsgNegotiateState::AuthDevice ON_ERROR failed, maybe retry."); return DM_OK; } - return STOP_BIND; // 外部事件错误,中止流程 + LOGE("AuthSrcPinAuthMsgNegotiateState::Action failed."); + return STOP_BIND; } DmAuthStateType AuthSinkPinAuthMsgNegotiateState::GetStateType() @@ -193,16 +196,16 @@ int32_t AuthSinkPinAuthMsgNegotiateState::Action(std::shared_ptr LOGI("AuthSinkPinAuthMsgNegotiateState::Action start"); auto ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); if (ret != DM_OK) { - LOGE("AuthSinkPinAuthMsgNegotiateState::Action call ProcessCredData err"); + LOGE("AuthSinkPinAuthMsgNegotiateState::Action call ProcessCredData err."); return ret; } - // 等待hiChain响应 transmit + // wait for onTransmit from hiChain auto retEvent = context->authStateMachine->WaitExpectEvent(DmEventType::ON_TRANSMIT); if (retEvent == DmEventType::ON_TRANSMIT) { - // 发送131报文 + // send 131 msg context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, context); } else if (retEvent == DmEventType::ON_ERROR) { - LOGI("AuthSinkPinAuthMsgNegotiateState::AuthDevice WAIT ON_TRANSMIT ON_ERROR failed."); + LOGI("AuthSinkPinAuthMsgNegotiateState::AuthDevice WAIT ON_TRANSMIT ON_ERROR failed, maybe retry."); return DM_OK; } else { return STOP_BIND; @@ -216,12 +219,12 @@ int32_t AuthSinkPinAuthMsgNegotiateState::Action(std::shared_ptr return DM_OK; } } else if (retEvent == DmEventType::ON_ERROR) { - LOGI("AuthSinkPinAuthMsgNegotiateState::AuthDevice WAIT ON_SESSION_KEY_RETURNED ON_ERROR failed."); + LOGI("AuthSinkPinAuthMsgNegotiateState::AuthDevice WAIT ON_SESSION_KEY_RETURNED ON_ERROR failed, maybe retry."); return DM_OK; } LOGE("AuthSinkPinAuthMsgNegotiateState::AuthDevice failed."); - return STOP_BIND; // 外部事件错误,中止流程 + return STOP_BIND; } DmAuthStateType AuthSinkPinAuthDoneState::GetStateType() @@ -242,40 +245,33 @@ DmAuthStateType AuthSrcPinAuthDoneState::GetStateType() int32_t AuthSrcPinAuthDoneState::Action(std::shared_ptr context) { - if (context == nullptr || context->hiChainAuthConnector == nullptr) { - LOGE("AuthSrcPinAuthDoneState::Action failed, auth context not initial."); - return ERR_DM_FAILED; - } - LOGI("AuthSrcPinAuthDoneState::Action start"); - // 处理凭据数据 std::string onTransmitData = context->transmitData; if (context->hiChainAuthConnector->ProcessCredData(context->requestId, onTransmitData) != DM_OK) { LOGE("AuthSrcPinAuthDoneState::Action failed, processCredData failed."); return ERR_DM_FAILED; } - // 阻塞等待ON_SESSION_KEY_RETURNED事件到来 + // wait for ON_SESSION_KEY_RETURNED from hichain DmEventType ret = context->authStateMachine->WaitExpectEvent(ON_SESSION_KEY_RETURNED); if (ret != ON_SESSION_KEY_RETURNED) { - if (ret == ON_ERROR) { // ON_ERROR事件到来,返回DM_OK, OnError回调中判断是否重试 - LOGE("AuthSrcPinAuthDoneState::Action, ON_SESSION_KEY_RETURNED event not arriverd, try again."); + if (ret == ON_ERROR) { + LOGE("AuthSrcPinAuthDoneState::Action, ON_SESSION_KEY_RETURNED event not arriverd, maybe retry."); return DM_OK; - } else { // 其它事件到来 + } else { LOGE("AuthSrcPinAuthDoneState::Action failed, ON_SESSION_KEY_RETURNED event failed, other event arriverd."); return ERR_DM_FAILED; } } - LOGI("AuthSrcPinAuthDoneState::Action wait ON_SESSION_KEY_RETURNED done"); - // 阻塞等待ON_FINISH事件到来 + // wait for ON_FINISH from hichain ret = context->authStateMachine->WaitExpectEvent(ON_FINISH); if (ret == ON_FINISH) { LOGI("AuthSrcPinAuthDoneState::Action wait ON_FINISH done"); return DM_OK; - } else if (ret == ON_ERROR) { // ON_ERROR事件到来,返回DM_OK, OnError回调中判断是否重试 + } else if (ret == ON_ERROR) { return DM_OK; - LOGE("AuthSrcPinAuthDoneState::Action, ON_FINISH event not arriverd, try again."); + LOGE("AuthSrcPinAuthDoneState::Action, ON_FINISH event not arriverd, maybe retry."); } return ERR_DM_FAILED; @@ -289,22 +285,22 @@ DmAuthStateType AuthSrcPinNegotiateStartState::GetStateType() int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr context) { if (!context->pinNegotiateStarted) { - // 首次认证 context->pinNegotiateStarted = true; context->timer->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); int32_t authResult = context->authResult; - if (authResult != USER_OPERATION_TYPE_ALLOW_AUTH && - authResult != USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + if (context->authTypeList.empty() || + (authResult != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH && + authResult != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS)) { LOGE("AuthSrcPinNegotiateStartState::Action authResult not allow"); context->reason = ERR_DM_BIND_USER_CANCEL; return ERR_DM_BIND_USER_CANCEL; } } else { - // 回退处理 if (context->authType == DmAuthType::AUTH_TYPE_PIN && context->inputPinAuthFailTimes < MAX_AUTH_INPUT_PIN_FAIL_TIMES) { LOGI("AuthSrcPinNegotiateStartState::Action input pin auth err, retry"); } else { + // try to fallback to next auth type if (context->currentAuthTypeIdx + 1 >= context->authTypeList.size()) { LOGE("AuthSrcPinNegotiateStartState::Action all auth type failed"); context->reason = ERR_DM_AUTH_REJECT; @@ -314,6 +310,8 @@ int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr con context->authType = context->authTypeList[context->currentAuthTypeIdx]; } } + + // restart pin auth timer context->timer->DeleteTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK)); context->timer->StartTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK), DmAuthState::GetTaskTimeout(context, WAIT_PIN_AUTH_TIMEOUT_TASK, PIN_AUTH_TIMEOUT), @@ -347,7 +345,6 @@ int32_t AuthSrcPinInputState::ShowStartAuthDialog(std::shared_ptr return STOP_BIND; } DmDialogManager::GetInstance().ShowInputDialog(context->accessee.deviceName); - LOGI("AuthSrcPinInputState::ShowStartAuthDialog end."); return DM_OK; } @@ -355,22 +352,21 @@ int32_t AuthSrcPinInputState::Action(std::shared_ptr context) { LOGI("AuthSrcPinInputState::Action start"); if (context->inputPinAuthFailTimes == 0) { - // 拉起PIN码输入界面 auto ret = ShowStartAuthDialog(context); if (ret != DM_OK) { return ret; } } else { - // 清空PIN输入框,提示用户重试 + // clear input pin box, and show try again context->authUiStateMgr->UpdateUiState(DmUiStateMsg::MSG_PIN_CODE_ERROR); } LOGI("AuthSrcPinInputState::Action waitting user operation"); - // 等待用户输密码操作完成 + // wait for user operation if (DmEventType::ON_USER_OPERATION != context->authStateMachine->WaitExpectEvent(DmEventType::ON_USER_OPERATION)) { LOGI("AuthSrcPinInputState::Action wait ON_USER_OPERATION err"); - return STOP_BIND; // 外部事件错误,中止流程 + return STOP_BIND; } if (context->pinInputResult != USER_OPERATION_TYPE_DONE_PINCODE_INPUT) { @@ -378,7 +374,6 @@ int32_t AuthSrcPinInputState::Action(std::shared_ptr context) return STOP_BIND; } context->authStateMachine->TransitionTo(std::make_shared()); - LOGI("AuthSrcPinInputState::Action input ok"); return DM_OK; } @@ -392,11 +387,11 @@ int32_t AuthSinkPinNegotiateStartState::Action(std::shared_ptr co if (!context->pinNegotiateStarted) { context->pinNegotiateStarted = true; } else { - // 回退处理 if (context->authType == DmAuthType::AUTH_TYPE_PIN && context->inputPinAuthFailTimes < MAX_AUTH_INPUT_PIN_FAIL_TIMES) { LOGI("AuthSinkPinNegotiateStartState::Action input pin auth err, retry"); } else { + // try to fallback to next auth type auto idx = context->currentAuthTypeIdx; if (idx + 1 >= context->authTypeList.size()) { LOGE("AuthSinkPinNegotiateStartState::Action all auth type failed"); @@ -408,6 +403,7 @@ int32_t AuthSinkPinNegotiateStartState::Action(std::shared_ptr co context->authType = context->authTypeList[idx]; } } + // restart pin auth timer context->timer->DeleteTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK)); context->timer->StartTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK), DmAuthState::GetTaskTimeout(context, WAIT_PIN_AUTH_TIMEOUT_TASK, PIN_AUTH_TIMEOUT), @@ -436,9 +432,9 @@ DmAuthStateType AuthSinkPinDisplayState::GetStateType() int32_t AuthSinkPinDisplayState::Action(std::shared_ptr context) { if (context->inputPinAuthFailTimes == 0) { - // 生成PIN码 + // gen pincode AuthSinkStatePinAuthComm::GeneratePincode(context); - // 显示PIN码 + // show pincode return AuthSinkStatePinAuthComm::ShowAuthInfoDialog(context); } return DM_OK; -- Gitee From 7feaec61500cfca4d2659cdc6356a2b0fc586aa6 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 24 Mar 2025 22:02:33 +0800 Subject: [PATCH 271/382] fix while(true) --- .../authentication_v2/dm_auth_state_machine.cpp | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 6fc10fdd3..1701b1208 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -181,22 +181,25 @@ DmEventType DmAuthStateMachine::WaitExpectEvent(DmEventType eventType) std::unique_lock lock(eventMutex_); // 记录进入函数的时间 auto startTime = std::chrono::high_resolution_clock::now(); - while (true) { + while (!running_.load()) { eventCv_.wait(lock, [&] { - return !eventQueue_.empty(); + return !running_.load() || !eventQueue_.empty(); }); - // 获取事件, TODO:假设正常事件按序到达(状态机单线程按序等待), 是否成立? + if (!running_.load()) { + return DmEventType::ON_FAIL; + } + + // 获取事件, 假设正常事件按序到达(状态机单线程按序等待) DmEventType actualEventType = eventQueue_.front(); eventQueue_.pop(); // 判断是否是期望事件 if (actualEventType == eventType || (exceptionEvent_.find(actualEventType) != exceptionEvent_.end())) { return actualEventType; - } else { - // TODO: 非期望事件,忽略 or 结束流程 ? } // 做一个超时退出机制 // 已经经过的时间 - auto elapsedTime = std::chrono::duration_cast(std::chrono::high_resolution_clock::now() - startTime); + auto elapsedTime = std::chrono::duration_cast( + std::chrono::high_resolution_clock::now() - startTime); if (elapsedTime.count() >= EVENT_TIMEOUT) { break; } -- Gitee From fe1ac1879cc9d552ef8d52a5084c0852ef5f03d8 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 24 Mar 2025 22:06:34 +0800 Subject: [PATCH 272/382] style --- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 5c2d1481e..570b3af30 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -25,7 +25,6 @@ namespace OHOS { namespace DistributedHardware { -constexpr const char* TAG_APP_OPERATION = "APPOPERATION"; constexpr const char* TAG_CUSTOM_DESCRIPTION = "CUSTOMDESC"; constexpr const char* TAG_LOCAL_DEVICE_TYPE = "LOCALDEVICETYPE"; constexpr const char* TAG_REQUESTER = "REQUESTER"; -- Gitee From 745cfece26838abd10b1abb4eb3c715d46e6455c Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 24 Mar 2025 22:14:50 +0800 Subject: [PATCH 273/382] fix typo --- .../src/authentication_v2/dm_auth_state_machine.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 1701b1208..96eef8073 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -181,7 +181,7 @@ DmEventType DmAuthStateMachine::WaitExpectEvent(DmEventType eventType) std::unique_lock lock(eventMutex_); // 记录进入函数的时间 auto startTime = std::chrono::high_resolution_clock::now(); - while (!running_.load()) { + while (running_.load()) { eventCv_.wait(lock, [&] { return !running_.load() || !eventQueue_.empty(); }); -- Gitee From 8c414824d42aff6dcd05bb71fea6c23e7e4df4dd Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 24 Mar 2025 22:24:01 +0800 Subject: [PATCH 274/382] set finished var --- .../src/authentication_v2/auth_stages/auth_acl.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 351e9c33a..987f6f0f9 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -170,6 +170,7 @@ DmAuthStateType AuthSrcDataSyncState::GetStateType() int32_t AuthSinkFinishState::Action(std::shared_ptr context) { LOGI("AuthSinkFinishState::Action start"); + context->isFinished = true; context->state = static_cast(GetStateType()); SinkFinish(context); LOGI("AuthSinkFinishState::Action ok"); @@ -185,6 +186,7 @@ DmAuthStateType AuthSinkFinishState::GetStateType() int32_t AuthSrcFinishState::Action(std::shared_ptr context) { LOGI("AuthSrcFinishState::Action start"); + context->isFinished = true; SourceFinish(context); LOGI("AuthSrcFinishState::Action ok"); return DM_OK; -- Gitee From 78ca3efb15094646d3cbd3ff29d10ee83c072c17 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Mon, 24 Mar 2025 22:27:12 +0800 Subject: [PATCH 275/382] set finished var --- .../src/authentication_v2/auth_stages/auth_acl.cpp | 2 -- services/implementation/src/authentication_v2/dm_auth_state.cpp | 2 ++ 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 987f6f0f9..351e9c33a 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -170,7 +170,6 @@ DmAuthStateType AuthSrcDataSyncState::GetStateType() int32_t AuthSinkFinishState::Action(std::shared_ptr context) { LOGI("AuthSinkFinishState::Action start"); - context->isFinished = true; context->state = static_cast(GetStateType()); SinkFinish(context); LOGI("AuthSinkFinishState::Action ok"); @@ -186,7 +185,6 @@ DmAuthStateType AuthSinkFinishState::GetStateType() int32_t AuthSrcFinishState::Action(std::shared_ptr context) { LOGI("AuthSrcFinishState::Action start"); - context->isFinished = true; SourceFinish(context); LOGI("AuthSrcFinishState::Action ok"); return DM_OK; diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 087000909..4aa71c958 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -94,6 +94,7 @@ void DmAuthState::SyncAclList(std::shared_ptr context, void DmAuthState::SourceFinish(std::shared_ptr context) { + context->isFinished = true; if (context->reason != DM_OK) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); // 根据凭据id 删除sink端多余的凭据 @@ -114,6 +115,7 @@ void DmAuthState::SourceFinish(std::shared_ptr context) void DmAuthState::SinkFinish(std::shared_ptr context) { + context->isFinished = true; if (context->reason != DM_OK) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); // 根据凭据id 删除sink端多余的凭据 -- Gitee From 4740440436641c1b4b466ed40cb31854b75a03e9 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 25 Mar 2025 09:50:56 +0800 Subject: [PATCH 276/382] revert default auth type --- .../implementation/include/authentication_v2/dm_auth_context.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 0844a562c..3af62ba0e 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -149,7 +149,7 @@ struct DmAuthContext { 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_CANCEL_AUTH}; + 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; -- Gitee From b302f8d642c03cd541fc2ba48d8c603de422881f Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 25 Mar 2025 10:32:04 +0800 Subject: [PATCH 277/382] notify a event, when recved 200 and 201 --- .../src/authentication_v2/dm_auth_message_processor.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 657b4c603..ceb9e9e51 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -807,6 +807,9 @@ int32_t DmAuthMessageProcessor::ParseMessageSyncResp(const JsonObject &jsonObjec int32_t DmAuthMessageProcessor::ParseMessageSinkFinish(const JsonObject &jsonObject, std::shared_ptr context) { + /* In case of an exception, there may be a state waiting for an event. + In the normal process, no state is waiting for events. */ + context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); if (jsonObject[DM_TAG_REPLY].IsNumberInteger()) { context->reply = jsonObject[DM_TAG_REPLY].Get(); } @@ -824,6 +827,9 @@ int32_t DmAuthMessageProcessor::ParseMessageSinkFinish(const JsonObject &jsonObj int32_t DmAuthMessageProcessor::ParseMessageSrcFinish(const JsonObject &jsonObject, std::shared_ptr context) { + /* In case of an exception, there may be a state waiting for an event. + In the normal process, no state is waiting for events. */ + context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); if (jsonObject[DM_TAG_REPLY].IsNumberInteger()) { context->reply = jsonObject[DM_TAG_REPLY].Get(); } -- Gitee From b7ab21fb923a0f8a8842786b672f108492ca2f1a Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Tue, 25 Mar 2025 11:21:03 +0800 Subject: [PATCH 278/382] fix state machine direction init err --- services/implementation/src/authentication_v2/auth_manager.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 1d63d5456..e7838d7a1 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -158,7 +158,6 @@ AuthManager::AuthManager(std::shared_ptr softbusConnector, context_->accessee.dmVersion = DM_VERSION_5_1_0; context_->timer = std::make_shared(); context_->authMessageProcessor = std::make_shared(); - context_->authStateMachine = std::make_shared(context_); } bool AuthManager::IsAuthManagerConstructSuccess() @@ -731,6 +730,7 @@ AuthSinkManager::AuthSinkManager(std::shared_ptr softbusConnec : AuthManager(softbusConnector, listener, hiChainAuthConnector) { context_->direction = DM_AUTH_SINK; + context_->authStateMachine = std::make_shared(context_); } void AuthSinkManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) @@ -859,6 +859,7 @@ AuthSrcManager::AuthSrcManager(std::shared_ptr softbusConnecto : AuthManager(softbusConnector, listener, hiChainAuthConnector) { context_->direction = DM_AUTH_SOURCE; + context_->authStateMachine = std::make_shared(context_); } void AuthSrcManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) -- Gitee From 61261df6d5644ad1039cf9db85be09431d809e98 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Tue, 25 Mar 2025 12:05:57 +0800 Subject: [PATCH 279/382] =?UTF-8?q?fix=EF=BC=9A=E6=B8=85=E7=90=86dm=5Fauth?= =?UTF-8?q?=5Fmessage=5Fprocessor.cpp=E5=92=8Cauth=5Fcredential.cpp?= =?UTF-8?q?=E6=96=87=E4=BB=B6=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.h | 45 ++- .../auth_stages/auth_credential.cpp | 34 +- .../dm_auth_message_processor.cpp | 341 ++++++++---------- 3 files changed, 196 insertions(+), 224 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index b023d8e5f..5d519f8fa 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -186,9 +186,13 @@ 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 @@ -223,10 +227,10 @@ private: // 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(JsonObject &jsonObject, std::shared_ptr &context); + int32_t ParseAuthStartMessage(const JsonObject &jsonObject, std::shared_ptr context); // Parse the 80 message - int32_t ParseNegotiateMessage(JsonObject &jsonObject, std::shared_ptr context); + 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 @@ -246,8 +250,7 @@ private: // 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, - DmMessageType msgType); + 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 @@ -258,35 +261,35 @@ private: int32_t ParseMessageSrcFinish(const JsonObject &jsonObject, std::shared_ptr context); // Create the 80 message - void CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); + int32_t CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); // Create the 90 message - void CreateRespNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); + int32_t CreateRespNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject); // Create the 100 message - void CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json); + int32_t CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json); // Create the 110 message - void CreateMessageRespUserConfirm(std::shared_ptr context, JsonObject &json); + int32_t CreateMessageRespUserConfirm(std::shared_ptr context, JsonObject &json); // Create the 120 message - void CreateMessageReqPinAuthStart(std::shared_ptr context, JsonObject &json); + int32_t CreateMessageReqPinAuthStart(std::shared_ptr context, JsonObject &json); // Create the 130 message - void CreateMessageRespPinAuthStart(std::shared_ptr context, JsonObject &json); + int32_t CreateMessageRespPinAuthStart(std::shared_ptr context, JsonObject &json); // Create the 121 message - void CreateMessageReqPinAuthNegotiate(std::shared_ptr context, JsonObject &json); + int32_t CreateMessageReqPinAuthNegotiate(std::shared_ptr context, JsonObject &json); // Create the 131 message - void CreateMessageRespPinAuthNegotiate(std::shared_ptr context, JsonObject &json); + int32_t CreateMessageRespPinAuthNegotiate(std::shared_ptr context, JsonObject &json); // Create the 140 message - void CreateMessageReqCredExchange(std::shared_ptr context, JsonObject &jsonObject); + int32_t CreateMessageReqCredExchange(std::shared_ptr context, JsonObject &jsonObject); // Create the 150 message - void CreateMessageRspCredExchange(std::shared_ptr context, JsonObject &jsonObject); + int32_t CreateMessageRspCredExchange(std::shared_ptr context, JsonObject &jsonObject); // Create the 160 message - void CreateMessageReqCredAuthStart(std::shared_ptr context, JsonObject &jsonObject); + 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); + 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); + int32_t CreateSyncMessage(std::shared_ptr context, JsonObject &jsonObject); // Create the 190 message - void CreateMessageSyncResp(std::shared_ptr context, JsonObject &jsonObject); + int32_t CreateMessageSyncResp(std::shared_ptr context, JsonObject &jsonObject); // Create the 200 message - void CreateMessageFinish(std::shared_ptr context, JsonObject &jsonObject); + int32_t CreateMessageFinish(std::shared_ptr context, JsonObject &jsonObject); // Compress the sync message std::string CompressSyncMsg(std::string &inputStr); @@ -314,6 +317,8 @@ private: 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 diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 462a19bae..7cc4a5583 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -34,12 +34,10 @@ namespace { const char * const FILED_DEVICE_ID = "deviceId"; -} - // 从context中提取transmit data,使用SK解密,并透传给HICHAIN // 如果ontransmit事件,在对应回调解析并保存在context // 如果onsessionkeyreturned事件,在对应回调解析并保存在cryptomgr -static int32_t AuthCredentialTransmitDecryptProcess(std::shared_ptr context, DmEventType event) +int32_t AuthCredentialTransmitDecryptProcess(std::shared_ptr context, DmEventType event) { if (context->transmitData.empty()) { LOGE("DmAuthMessageProcessor::CreateMessageReqCredAuthStart failed, get onTransmitData failed."); @@ -61,7 +59,7 @@ static int32_t AuthCredentialTransmitDecryptProcess(std::shared_ptr context, DmMessageType msgType) +int32_t AuthCredentialTransmitSend(std::shared_ptr context, DmMessageType msgType) { // 获取transmit data if (context->transmitData.empty()) { @@ -75,11 +73,19 @@ static int32_t AuthCredentialTransmitSend(std::shared_ptr context LOGE("AuthCredentialTransmitSend: CreateMessage AuthCredential transmit data failed"); return ERR_DM_FAILED; } - // 发送报文 + // 发送报文 return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); } -// SOURCE端凭据校验操作 +void SetAuthContext(int32_t skId, int64_t &appSkTimeStamp, int32_t &appSessionKeyId) +{ + appSkTimeStamp = + std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()).count(); + appSessionKeyId = skId; + return; +} + +} DmAuthStateType AuthSrcCredentialAuthNegotiateState::GetStateType() { @@ -101,6 +107,7 @@ DmAuthStateType AuthSrcCredentialAuthDoneState::GetStateType() { return DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE; } + // 收到171凭据认证报文 int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr context) { @@ -128,10 +135,7 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co if (context->isOnline == false && context->isAppCredentialVerified == false) { context->isAppCredentialVerified = true; // 保存到DP 获取应用凭据ID 并保存 - context->accesser.transmitSkTimeStamp = - std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) - .count(); - context->accesser.transmitSessionKeyId = skId; + SetAuthContext(skId, context->accesser.transmitSkTimeStamp, context->accesser.transmitSessionKeyId); msgType = MSG_TYPE_REQ_CREDENTIAL_AUTH_START; // 发送160 // 认证用户凭据 int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); @@ -150,18 +154,12 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co } else if (context->isOnline == false) { // 首次认证 且 用户凭据流程 // 保存到DP 获取用户凭据ID 并保存 - context->accesser.lnnSkTimeStamp = - std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) - .count(); - context->accesser.lnnSessionKeyId = skId; + SetAuthContext(skId, context->accesser.lnnSkTimeStamp, context->accesser.lnnSessionKeyId); msgType = MSG_TYPE_REQ_DATA_SYNC; // 发送180 } else { // 非首次认证 应用凭据流程 // 保存到DP 获取应用凭据ID 并保存 - context->accesser.transmitSkTimeStamp = - std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) - .count(); - context->accesser.transmitSessionKeyId = skId; + SetAuthContext(skId, context->accesser.transmitSkTimeStamp, context->accesser.transmitSessionKeyId); msgType = MSG_TYPE_REQ_DATA_SYNC; // 发送180 } std::string message = diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index ceb9e9e51..7410bbeab 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -65,6 +65,54 @@ void ParseNegotiateExtraInfoMessage(const JsonItemObject &jsonExtraObject, std:: return; } +void ParseDmAccessToSync(const JsonItemObject &jsonObject, DmAccess &access) +{ + DmAccessToSync srcAccessToSync = jsonObject.Get(); + access.deviceName = srcAccessToSync.deviceName; + access.deviceId = srcAccessToSync.deviceId; + access.userId = srcAccessToSync.userId; + access.accountId = srcAccessToSync.accountId; + access.tokenId = srcAccessToSync.tokenId; + access.bundleName = srcAccessToSync.bundleName; + access.bindLevel = srcAccessToSync.bindLevel; + access.sessionKeyId = srcAccessToSync.sessionKeyId; + access.skTimeStamp = srcAccessToSync.skTimeStamp; + return; +} + +int32_t ParaseAclChecksumList(const JsonItemObject &aclChecksumjson, DmAccess &access) +{ + if (aclChecksumjson.IsDiscarded()) { + LOGE("ParseSyncMessage aclChecksumjson error"); + return ERR_DM_FAILED; + } + if (!aclChecksumjson[DM_TAG_ACCESSER].IsArray()) { // 再解析一次 acl + LOGE("ParseSyncMessage DM_TAG_ACCESSER error"); + return ERR_DM_FAILED; + } + aclChecksumjson[DM_TAG_ACCESSER].Get(access.accesserStrList); + if (!aclChecksumjson[DM_TAG_ACCESSEE].IsArray()) { // 再解析一次 acl + LOGE("ParseSyncMessage DM_TAG_ACCESSEE error"); + return ERR_DM_FAILED; + } + aclChecksumjson[DM_TAG_ACCESSEE].Get(access.accesseeStrList); + + return DM_OK; +} + +bool IsMessageValid(const JsonItemObject &jsonObject) +{ + if (jsonObject.IsDiscarded()) { + LOGE("DmAuthMessageProcessor::ParseMessage failed, decodeRequestAuth jsonStr error"); + return false; + } + if (!jsonObject[TAG_MSG_TYPE].IsNumberInteger()) { + LOGE("DmAuthMessageProcessor::ParseMessage failed, message type error."); + return false; + } + return true; +} + } // 保存秘钥 @@ -184,6 +232,46 @@ DmAuthMessageProcessor::DmAuthMessageProcessor() { LOGI("DmAuthMessageProcessor constructor"); cryptoMgr_ = std::make_shared(); + createMessageFuncMap_ = { + {MSG_TYPE_REQ_ACL_NEGOTIATE, &DmAuthMessageProcessor::CreateNegotiateMessage}, + {MSG_TYPE_RESP_ACL_NEGOTIATE, &DmAuthMessageProcessor::CreateRespNegotiateMessage}, + {MSG_TYPE_REQ_USER_CONFIRM, &DmAuthMessageProcessor::CreateMessageReqUserConfirm}, + {MSG_TYPE_RESP_USER_CONFIRM, &DmAuthMessageProcessor::CreateMessageRespUserConfirm}, + {MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqPinAuthStart}, + {MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate}, + {MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageRespPinAuthStart}, + {MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate}, + {MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageReqCredExchange}, + {MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageRspCredExchange}, + {MSG_TYPE_REQ_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqCredAuthStart}, + {MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE, &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, + {MSG_TYPE_RESP_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, + {MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE, &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, + {MSG_TYPE_REQ_DATA_SYNC, &DmAuthMessageProcessor::CreateSyncMessage}, + {MSG_TYPE_RESP_DATA_SYNC, &DmAuthMessageProcessor::CreateMessageSyncResp}, + {MSG_TYPE_AUTH_REQ_FINISH, &DmAuthMessageProcessor::CreateMessageFinish}, + {MSG_TYPE_AUTH_RESP_FINISH, &DmAuthMessageProcessor::CreateMessageFinish}, + }; + paraseMessageFuncMap_ = { + {MSG_TYPE_REQ_ACL_NEGOTIATE, &DmAuthMessageProcessor::ParseNegotiateMessage}, + {MSG_TYPE_RESP_ACL_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageRespAclNegotiate}, + {MSG_TYPE_REQ_USER_CONFIRM, &DmAuthMessageProcessor::ParseMessageReqUserConfirm}, + {MSG_TYPE_RESP_USER_CONFIRM, &DmAuthMessageProcessor::ParseMessageRespUserConfirm}, + {MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::ParseMessageReqPinAuthStart}, + {MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate}, + {MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::ParseMessageRespPinAuthStart}, + {MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate}, + {MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::ParseMessageReqCredExchange}, + {MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::ParseMessageRspCredExchange}, + {MSG_TYPE_REQ_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::ParseAuthStartMessage}, + {MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, + {MSG_TYPE_RESP_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, + {MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, + {MSG_TYPE_REQ_DATA_SYNC, &DmAuthMessageProcessor::ParseMessageSyncReq}, + {MSG_TYPE_RESP_DATA_SYNC, &DmAuthMessageProcessor::ParseMessageSyncResp}, + {MSG_TYPE_AUTH_REQ_FINISH, &DmAuthMessageProcessor::ParseMessageSinkFinish}, + {MSG_TYPE_AUTH_RESP_FINISH, &DmAuthMessageProcessor::ParseMessageSrcFinish}, + }; } DmAuthMessageProcessor::~DmAuthMessageProcessor() @@ -197,63 +285,19 @@ DmAuthMessageProcessor::~DmAuthMessageProcessor() // 解析报文,返回值为错误码,实际解析出来的信息保存到context中 int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr context, const std::string &message) { - if (context == nullptr) { - return ERR_DM_FAILED; - } - JsonObject jsonObject(message); - if (jsonObject.IsDiscarded()) { - LOGE("DmAuthMessageProcessor::ParseMessage failed, decodeRequestAuth jsonStr error"); - return ERR_DM_FAILED; - } - if (!jsonObject[TAG_MSG_TYPE].IsNumberInteger()) { - LOGE("DmAuthMessageProcessor::ParseMessage failed, message type error."); + if (context == nullptr || !IsMessageValid(jsonObject)) { return ERR_DM_FAILED; } DmMessageType msgType = static_cast(jsonObject[TAG_MSG_TYPE].Get()); context->msgType = msgType; LOGI("DmAuthMessageProcessor::ParseMessage message type %{public}d", context->msgType); - // TODO:调试信息,上库前删除 - LOGI("DmAuthMessageProcessor::ParseMessage %{public}s", jsonObject.Dump().c_str()); - switch (msgType) { - case MSG_TYPE_REQ_ACL_NEGOTIATE: - return ParseNegotiateMessage(jsonObject, context); - case MSG_TYPE_RESP_ACL_NEGOTIATE: - return ParseMessageRespAclNegotiate(jsonObject, context); - case MSG_TYPE_REQ_USER_CONFIRM: - return ParseMessageReqUserConfirm(jsonObject, context); - case MSG_TYPE_RESP_USER_CONFIRM: - return ParseMessageRespUserConfirm(jsonObject, context); - case MSG_TYPE_REQ_PIN_AUTH_START: - return ParseMessageReqPinAuthStart(jsonObject, context); - case MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE: - return ParseMessageReqPinAuthNegotiate(jsonObject, context); - case MSG_TYPE_RESP_PIN_AUTH_START: - return ParseMessageRespPinAuthStart(jsonObject, context); - case MSG_TYPE_REQ_CREDENTIAL_AUTH_START: // 160 - return ParseAuthStartMessage(jsonObject, context); - case MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE: // 161 - case MSG_TYPE_RESP_CREDENTIAL_AUTH_START: // 170 - case MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE: // 171 - return ParseMessageNegotiateTransmit(jsonObject, context, msgType); - case MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE: - return ParseMessageRespPinAuthNegotiate(jsonObject, context); - case MSG_TYPE_REQ_CREDENTIAL_EXCHANGE: - return ParseMessageReqCredExchange(jsonObject, context); - case MSG_TYPE_RESP_CREDENTIAL_EXCHANGE: - return ParseMessageRspCredExchange(jsonObject, context); - case MSG_TYPE_REQ_DATA_SYNC: - return ParseMessageSyncReq(jsonObject, context); - case MSG_TYPE_RESP_DATA_SYNC: - return ParseMessageSyncResp(jsonObject, context); - case MSG_TYPE_AUTH_REQ_FINISH: - return ParseMessageSinkFinish(jsonObject, context); - case MSG_TYPE_AUTH_RESP_FINISH: - return ParseMessageSrcFinish(jsonObject, context); - default: - break; + auto itr = paraseMessageFuncMap_.find(msgType); + if (itr == paraseMessageFuncMap_.end()) { + LOGI("DmAuthMessageProcessor::ParseMessage message type error %{public}d", context->msgType); + return ERR_DM_FAILED; } - return ERR_DM_FAILED; + return (this->*(itr->second))(jsonObject, context); } static std::vector stringToVector(const std::string& str) @@ -279,7 +323,7 @@ static std::string vectorToString(const std::vector& vec) return oss.str(); } int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const JsonObject &jsonObject, - std::shared_ptr &context, DmMessageType msgType) + std::shared_ptr context) { if (jsonObject.IsDiscarded() || !jsonObject.Contains(DM_TAG_DATA) || !jsonObject[DM_TAG_DATA].IsString()) { LOGE("DmAuthMessageProcessor::ParseMessageNegotiateTransmit Unlegal json string failed"); @@ -288,7 +332,7 @@ int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const JsonObject & context->transmitData = jsonObject[DM_TAG_DATA].Get(); - switch (msgType) { + switch (context->msgType) { case MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE: // 161 context->authStateMachine->TransitionTo(std::make_shared()); break; @@ -384,18 +428,15 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &js // 首次认证,解析对方用户级公钥和协商用户级凭据Id std::string tmpString; if (!context->isOnline) { - if (!jsonData[DM_TAG_LNN_PUBLICK_KEY].IsString() || !jsonData[DM_TAG_USER_CREDENTIAL_ID].IsString()) { - LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange failed, first auth but no lnnPublicKey or " - "lnnCredentialId."); + if (!jsonData[DM_TAG_LNN_PUBLICK_KEY].IsString()) { + LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange failed, first auth but no lnnPublicKey."); return ERR_DM_FAILED; } context->accessee.lnnPublicKey = jsonData[DM_TAG_LNN_PUBLICK_KEY].Get(); - context->accessee.lnnCredentialId = jsonData[DM_TAG_USER_CREDENTIAL_ID].Get(); } // 解析对方应用级公钥和协商应用级凭据Id if (!jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY].IsString() || - !jsonData[DM_TAG_APP_CREDENTIAL_ID].IsString() || !jsonData[DM_TAG_DEVICE_ID].IsString() || !jsonData[DM_TAG_PEER_USER_SPACE_ID].IsNumberInteger() || !jsonData[DM_TAG_TOKEN_ID].IsNumberInteger()) { @@ -404,7 +445,6 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &js return ERR_DM_FAILED; } context->accessee.transmitPublicKey = jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY].Get(); - context->accessee.transmitCredentialId = jsonData[DM_TAG_APP_CREDENTIAL_ID].Get(); context->accessee.deviceId = jsonData[DM_TAG_DEVICE_ID].Get(); // 解析deviceId context->accessee.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].Get(); // 解析userId context->accessee.tokenId = jsonData[DM_TAG_TOKEN_ID].Get(); // 解析tokenId @@ -419,72 +459,18 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh LOGI("DmAuthMessageProcessor::CreateMessage start. msgType is %{public}d", msgType); JsonObject jsonObj; jsonObj[TAG_MSG_TYPE] = msgType; - switch (msgType) { - case MSG_TYPE_REQ_ACL_NEGOTIATE: - CreateNegotiateMessage(context, jsonObj); - break; - case MSG_TYPE_RESP_ACL_NEGOTIATE: - CreateRespNegotiateMessage(context, jsonObj); - break; - case MSG_TYPE_REQ_USER_CONFIRM: - CreateMessageReqUserConfirm(context, jsonObj); - break; - case MSG_TYPE_RESP_USER_CONFIRM: - CreateMessageRespUserConfirm(context, jsonObj); - break; - case MSG_TYPE_REQ_PIN_AUTH_START: - CreateMessageReqPinAuthStart(context, jsonObj); - break; - case MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE: - CreateMessageReqPinAuthNegotiate(context, jsonObj); - break; - case MSG_TYPE_RESP_PIN_AUTH_START: - CreateMessageRespPinAuthStart(context, jsonObj); - break; - case MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE: - CreateMessageRespPinAuthNegotiate(context, jsonObj); - break; - case MSG_TYPE_REQ_CREDENTIAL_EXCHANGE: - CreateMessageReqCredExchange(context, jsonObj); - break; - case MSG_TYPE_RESP_CREDENTIAL_EXCHANGE: - CreateMessageRspCredExchange(context, jsonObj); - break; - case MSG_TYPE_REQ_CREDENTIAL_AUTH_START: - CreateMessageReqCredAuthStart(context, jsonObj); - break; - case MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE: // 161 - case MSG_TYPE_RESP_CREDENTIAL_AUTH_START: // 170 - case MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE: // 171 - if (CreateCredentialNegotiateMessage(context, jsonObj) != DM_OK) { - return ""; - } - break; - case MSG_TYPE_REQ_DATA_SYNC: - if (CreateSyncMessage(context, jsonObj)!= DM_OK) { - return ""; - } - break; - case MSG_TYPE_RESP_DATA_SYNC: - CreateMessageSyncResp(context, jsonObj); - break; - case MSG_TYPE_AUTH_REQ_FINISH: - case MSG_TYPE_AUTH_RESP_FINISH: - CreateMessageFinish(context, jsonObj); - break; - default: - LOGE("DmAuthMessageProcessor::CreateMessage msgType %{public}d error.", msgType); - break; + auto itr = createMessageFuncMap_.find(msgType); + if (itr == createMessageFuncMap_.end()) { + LOGE("DmAuthMessageProcessor::CreateMessage msgType %{public}d error.", msgType); + return ""; } - // TODO:调试信息,上库前删除 - LOGI("DmAuthMessageProcessor::CreateMessage %{public}s", jsonObj.Dump().c_str()); - - return jsonObj.Dump(); + int32_t ret = (this->*(itr->second))(context, jsonObj); + return (ret == DM_OK) ? jsonObj.Dump() : ""; } // 内部各类报文的实现 // 161 170 171消息构造 -int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr &context, +int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject) { std::string encryptMsg; @@ -493,7 +479,7 @@ int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr } // 创建80报文 -void DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject) +int32_t DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject) { jsonObject[TAG_AUTH_TYPE] = context->authType; jsonObject[TAG_SESSION_NAME] = context->sessionName; @@ -515,11 +501,11 @@ void DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, +int32_t DmAuthMessageProcessor::CreateRespNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject) { jsonObject[TAG_DEVICE_VERSION] = context->accessee.dmVersion; @@ -539,11 +525,11 @@ void DmAuthMessageProcessor::CreateRespNegotiateMessage(std::shared_ptrauthResultReady) { jsonObject[DM_TAG_AUTH_RESULT] = context->authResult; } - return; + return DM_OK; } // 创建140报文 -void DmAuthMessageProcessor::CreateMessageReqCredExchange(std::shared_ptr context, +int32_t DmAuthMessageProcessor::CreateMessageReqCredExchange(std::shared_ptr context, JsonObject &jsonObject) { JsonObject jsonData; @@ -557,22 +543,25 @@ void DmAuthMessageProcessor::CreateMessageReqCredExchange(std::shared_ptrEncryptMessage(plainText, cipherText); + int32_t ret = cryptoMgr_->EncryptMessage(plainText, cipherText); + if (ret != DM_OK) { + LOGI("DmAuthMessageProcessor::CreateMessageReqCredExchange encryptMessage failed."); + return ret; + } jsonObject[DM_TAG_DATA] = cipherText; + return ret; } // 创建150报文 -void DmAuthMessageProcessor::CreateMessageRspCredExchange(std::shared_ptr context, +int32_t DmAuthMessageProcessor::CreateMessageRspCredExchange(std::shared_ptr context, JsonObject &jsonObject) { LOGI("DmAuthMessageProcessor::CreateMessageRspCredExchange start."); JsonObject jsonData; if (!context->isOnline) { jsonData[DM_TAG_LNN_PUBLICK_KEY] = context->accessee.lnnPublicKey; - jsonData[DM_TAG_USER_CREDENTIAL_ID] = context->accessee.lnnCredentialId; } jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY] = context->accessee.transmitPublicKey; // 本端应用级公钥 - jsonData[DM_TAG_APP_CREDENTIAL_ID] = context->accessee.transmitCredentialId; // 本端应用级凭据Id jsonData[DM_TAG_DEVICE_ID] = context->accessee.deviceId; // 本端deviceId jsonData[DM_TAG_PEER_USER_SPACE_ID] = context->accessee.userId; // 本端userId jsonData[DM_TAG_TOKEN_ID] = context->accessee.tokenId; // 本端tokenId @@ -580,23 +569,24 @@ void DmAuthMessageProcessor::CreateMessageRspCredExchange(std::shared_ptrEncryptMessage(plainText, cipherText); + int32_t ret = cryptoMgr_->EncryptMessage(plainText, cipherText); + if (ret != DM_OK) { + LOGI("DmAuthMessageProcessor::CreateMessageRspCredExchange encryptMessage failed."); + return ret; + } jsonObject[DM_TAG_DATA] = cipherText; + return ret; } // 创建160报文 -void DmAuthMessageProcessor::CreateMessageReqCredAuthStart(std::shared_ptr context, +int32_t DmAuthMessageProcessor::CreateMessageReqCredAuthStart(std::shared_ptr context, JsonObject &jsonObject) { std::string onTransmitData; JsonObject jsonData; jsonObject[DM_TAG_DATA] = context->transmitData; - if (!context->isAppCredentialVerified) { // 应用级凭据认证 - jsonObject[DM_TAG_APP_CREDENTIAL_ID] = context->accesser.transmitCredentialId; - } else if (!context->isOnline) { // 首次用户级凭据认证 - jsonObject[DM_TAG_USER_CREDENTIAL_ID] = context->accesser.lnnCredentialId; - } + return DM_OK; } bool DmAuthMessageProcessor::ChecksumAcl(DistributedDeviceProfile::AccessControlProfile &acl, @@ -617,7 +607,7 @@ bool DmAuthMessageProcessor::ChecksumAcl(DistributedDeviceProfile::AccessControl } // 创建190报文 -void DmAuthMessageProcessor::CreateMessageSyncResp(std::shared_ptr context, +int32_t DmAuthMessageProcessor::CreateMessageSyncResp(std::shared_ptr context, JsonObject &jsonObject) { DmAccess access; // 代表本端的access @@ -631,20 +621,20 @@ void DmAuthMessageProcessor::CreateMessageSyncResp(std::shared_ptr context, +int32_t DmAuthMessageProcessor::CreateMessageFinish(std::shared_ptr context, JsonObject &jsonObject) { jsonObject[DM_TAG_REPLY] = context->reply; jsonObject[DM_TAG_STATE] = context->state; jsonObject[DM_TAG_REASON] = context->reason; - return; + return DM_OK; } int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr &context, @@ -672,47 +662,20 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr std::string srcAccessStr = jsonObject[DM_TAG_ACCESS].Get(); // 解析到 access里面 JsonObject accessjson(srcAccessStr); - if (jsonObject.IsDiscarded()) { - LOGE("ParseSyncMessage srcAccessStr error"); - return ERR_DM_FAILED; - } - DmAccessToSync srcAccessToSync = accessjson.Get(); - access.deviceName = srcAccessToSync.deviceName; - access.deviceId = srcAccessToSync.deviceId; - access.userId = srcAccessToSync.userId; - access.accountId = srcAccessToSync.accountId; - access.tokenId = srcAccessToSync.tokenId; - access.bundleName = srcAccessToSync.bundleName; - access.bindLevel = srcAccessToSync.bindLevel; - access.transmitSessionKeyId = srcAccessToSync.sessionKeyId; - access.transmitSkTimeStamp = srcAccessToSync.skTimeStamp; + ParseDmAccessToSync(accessjson, access); if (jsonObject[DM_TAG_PROXY].IsString()) { // 预留字段 std::string proxyInfo = jsonObject[DM_TAG_PROXY].Get(); } + if (jsonObject[DM_TAG_SERVICEINFO].IsString()) { // sp 暂时没有传 + std::string serviceInfo = jsonObject[DM_TAG_SERVICEINFO].Get(); + } if (!jsonObject[DM_TAG_ACL_CHECKSUM].IsString()) { // 再解析一次 acl LOGE("ParseSyncMessage DM_TAG_ACL_CHECKSUM error"); return ERR_DM_FAILED; } - std::string aclChecksumList = jsonObject[DM_TAG_ACL_CHECKSUM].Get(); - JsonObject aclChecksumjson(aclChecksumList); - if (aclChecksumjson.IsDiscarded()) { - LOGE("ParseSyncMessage aclChecksumjson error"); - return ERR_DM_FAILED; - } - if (!aclChecksumjson[DM_TAG_ACCESSER].IsArray()) { // 再解析一次 acl - LOGE("ParseSyncMessage DM_TAG_ACCESSER error"); - return ERR_DM_FAILED; - } - aclChecksumjson[DM_TAG_ACCESSER].Get(access.accesserStrList); - if (!aclChecksumjson[DM_TAG_ACCESSEE].IsArray()) { // 再解析一次 acl - LOGE("ParseSyncMessage DM_TAG_ACCESSEE error"); - return ERR_DM_FAILED; - } - aclChecksumjson[DM_TAG_ACCESSEE].Get(access.accesseeStrList); - if (jsonObject[DM_TAG_SERVICEINFO].IsString()) { // sp 暂时没有传 - std::string serviceInfo = jsonObject[DM_TAG_SERVICEINFO].Get(); - } - return DM_OK; + std::string aclChecksumList = jsonObject[DM_TAG_ACL_CHECKSUM].Get(); + JsonObject aclChecksumjson(aclChecksumList); + return ParaseAclChecksumList(aclChecksumjson, access); } int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptr &context, @@ -843,11 +806,10 @@ int32_t DmAuthMessageProcessor::ParseMessageSrcFinish(const JsonObject &jsonObje return DM_OK; } -int32_t DmAuthMessageProcessor::ParseNegotiateMessage(JsonObject &jsonObject, +int32_t DmAuthMessageProcessor::ParseNegotiateMessage(const JsonObject &jsonObject, std::shared_ptr context) { if (jsonObject[DM_TAG_DMVERSION].IsString()) { - context->accesser.dmVersion = jsonObject[DM_TAG_DMVERSION].Get(); } if (jsonObject[DM_TAG_EDITION].IsString()) { @@ -1009,37 +971,43 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate(const JsonObject return DM_OK; } -void DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json) +int32_t DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json) { json[TAG_DEVICE_TYPE] = context->accesser.deviceType; json[TAG_DEVICE_NAME] = context->accesser.deviceName; + return DM_OK; } -void DmAuthMessageProcessor::CreateMessageRespUserConfirm(std::shared_ptr context, JsonObject &json) +int32_t DmAuthMessageProcessor::CreateMessageRespUserConfirm(std::shared_ptr context, JsonObject &json) { json[DM_TAG_AUTH_RESULT] = context->authResult; + return DM_OK; } -void DmAuthMessageProcessor::CreateMessageReqPinAuthStart(std::shared_ptr context, JsonObject &json) +int32_t DmAuthMessageProcessor::CreateMessageReqPinAuthStart(std::shared_ptr context, JsonObject &json) { json[DM_TAG_DATA] = context->transmitData; + return DM_OK; } -void DmAuthMessageProcessor::CreateMessageRespPinAuthStart(std::shared_ptr context, JsonObject &json) +int32_t DmAuthMessageProcessor::CreateMessageRespPinAuthStart(std::shared_ptr context, JsonObject &json) { json[DM_TAG_DATA] = context->transmitData; + return DM_OK; } -void DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate(std::shared_ptr context, +int32_t DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate(std::shared_ptr context, JsonObject &json) { json[DM_TAG_DATA] = context->transmitData; + return DM_OK; } -void DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate(std::shared_ptr context, +int32_t DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate(std::shared_ptr context, JsonObject &json) { json[DM_TAG_DATA] = context->transmitData; + return DM_OK; } void DmAuthMessageProcessor::CreateAndSendMsg(DmMessageType msgType, std::shared_ptr context) @@ -1142,7 +1110,7 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptr &context, JsonObject &jsonObject) +int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr context, JsonObject &jsonObject) { DmAccess accessSide; // 代表本端的access if (context->direction == DM_AUTH_SOURCE) { @@ -1252,7 +1220,8 @@ int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr } // 解析transmit和PSKID 解析160 -int32_t DmAuthMessageProcessor::ParseAuthStartMessage(JsonObject &jsonObject, std::shared_ptr &context) +int32_t DmAuthMessageProcessor::ParseAuthStartMessage(const JsonObject &jsonObject, + std::shared_ptr context) { if (jsonObject.IsDiscarded() || !jsonObject.Contains(DM_TAG_DATA) || !jsonObject[DM_TAG_DATA].IsString()) { -- Gitee From 5ed9dbb62641f0ec1be8c9433da8e0c4736a3b5a Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Tue, 25 Mar 2025 15:04:39 +0800 Subject: [PATCH 280/382] =?UTF-8?q?=E6=94=B9=E5=90=8D&=E5=B1=8F=E8=94=BDbi?= =?UTF-8?q?ndlevel=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/dm_auth_context.h | 2 +- .../dm_auth_message_processor.h | 2 +- .../authentication_v2/auth_stages/auth_acl.cpp | 8 ++++---- .../src/authentication_v2/dm_auth_context.cpp | 16 ++++++++-------- .../dm_auth_message_processor.cpp | 8 ++++---- 5 files changed, 18 insertions(+), 18 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 3af62ba0e..15df14b5b 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -119,7 +119,7 @@ struct DmAccess { std::string lnnCredentialId; // User-level credential ID std::string transmitCredentialId; // Application-level credential ID std::string lnnPublicKey; // User-level public key - std::string transmitPublicKey; // Application-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 diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 5d519f8fa..ad0d96d5d 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -31,7 +31,7 @@ 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 = "transmitPublicKey"; +constexpr const char *DM_TAG_TRANSMIT_PUBLICK_KEY = "ephemeralPublicKey"; constexpr const char *DM_TAG_USER_CREDENTIAL_ID = "lnnCredentialId"; constexpr const char *DM_TAG_APP_CREDENTIAL_ID = "transmitCredentialId"; constexpr const char *DM_TAG_AUTH_RESULT = "authResult"; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 351e9c33a..0ad02acc7 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -47,8 +47,8 @@ int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) bool isSame = Crypto::Sha256(context->accesser.deviceId) == context->accesser.deviceIdHash && Crypto::Sha256(std::to_string(context->accesser.userId)) == context->accesser.userIdHash && Crypto::Sha256(context->accesser.accountId) == context->accesser.accountIdHash && - Crypto::Sha256(std::to_string(context->accesser.tokenId)) == context->accesser.tokenIdHash && - context->accesser.bindLevel == context->accessee.bindLevel; + Crypto::Sha256(std::to_string(context->accesser.tokenId)) == context->accesser.tokenIdHash; + // && context->accesser.bindLevel == context->accessee.bindLevel; bindlevel协商能力补齐后打开 if (!isSame) { LOGE("data between two stages different, stop auth"); context->reply = ERR_DM_QUADRUPLE_NOT_SAME; @@ -102,8 +102,8 @@ int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) bool isSame = Crypto::Sha256(context->accessee.deviceId) == context->accessee.deviceIdHash && Crypto::Sha256(std::to_string(context->accessee.userId)) == context->accessee.userIdHash && Crypto::Sha256(context->accessee.accountId) == context->accessee.accountIdHash && - Crypto::Sha256(std::to_string(context->accessee.tokenId)) == context->accessee.tokenIdHash && - context->accesser.bindLevel == context->accessee.bindLevel; + Crypto::Sha256(std::to_string(context->accessee.tokenId)) == context->accessee.tokenIdHash; + // && context->accesser.bindLevel == context->accessee.bindLevel; bindlevel协商能力补齐后打开 if (!isSame) { LOGE("data between two stages different, stop auth"); // 不同直接结束,发送200给sink端 diff --git a/services/implementation/src/authentication_v2/dm_auth_context.cpp b/services/implementation/src/authentication_v2/dm_auth_context.cpp index 25410cb1d..fe0b1f182 100644 --- a/services/implementation/src/authentication_v2/dm_auth_context.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_context.cpp @@ -75,15 +75,15 @@ std::string DmAuthContext::GetPublicKey(DmAuthSide side, DmAuthScope authorizedS if (side == DM_AUTH_LOCAL_SIDE) { if (direction == DM_AUTH_SOURCE) { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnPublicKey : accesser.transmitPublicKey; + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnPublicKey : accesser.ephemeralPublicKey; } else { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnPublicKey : accessee.transmitPublicKey; + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnPublicKey : accessee.ephemeralPublicKey; } } else { if (direction == DM_AUTH_SOURCE) { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnPublicKey : accessee.transmitPublicKey; + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnPublicKey : accessee.ephemeralPublicKey; } else { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnPublicKey : accesser.transmitPublicKey; + return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnPublicKey : accesser.ephemeralPublicKey; } } } @@ -142,13 +142,13 @@ int32_t DmAuthContext::SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope if (authorizedScope == DM_AUTH_SCOPE_USER) { accesser.lnnPublicKey = publicKey; } else { - accesser.transmitPublicKey = publicKey; + accesser.ephemeralPublicKey = publicKey; } } else { if (authorizedScope == DM_AUTH_SCOPE_USER) { accessee.lnnPublicKey = publicKey; } else { - accessee.transmitPublicKey = publicKey; + accessee.ephemeralPublicKey = publicKey; } } } else { @@ -156,13 +156,13 @@ int32_t DmAuthContext::SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope if (authorizedScope == DM_AUTH_SCOPE_USER) { accessee.lnnPublicKey = publicKey; } else { - accessee.transmitPublicKey = publicKey; + accessee.ephemeralPublicKey = publicKey; } } else { if (authorizedScope == DM_AUTH_SCOPE_USER) { accesser.lnnPublicKey = publicKey; } else { - accesser.transmitPublicKey = publicKey; + accesser.ephemeralPublicKey = publicKey; } } } diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 7410bbeab..ac1331a52 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -396,7 +396,7 @@ int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const JsonObject &js LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange, MSG_TYPE_REQ_CREDENTIAL_EXCHANGE message error."); return ERR_DM_FAILED; } - context->accesser.transmitPublicKey = jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY].Get(); // 解析应用级公钥 + context->accesser.ephemeralPublicKey = jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY].Get(); // 解析应用级公钥 context->accesser.deviceId = jsonData[DM_TAG_DEVICE_ID].Get(); // 解析deviceId context->accesser.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].Get(); // 解析userId context->accesser.tokenId = jsonData[DM_TAG_TOKEN_ID].Get(); // 解析tokenId @@ -444,7 +444,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &js "message error."); return ERR_DM_FAILED; } - context->accessee.transmitPublicKey = jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY].Get(); + context->accessee.ephemeralPublicKey = jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY].Get(); context->accessee.deviceId = jsonData[DM_TAG_DEVICE_ID].Get(); // 解析deviceId context->accessee.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].Get(); // 解析userId context->accessee.tokenId = jsonData[DM_TAG_TOKEN_ID].Get(); // 解析tokenId @@ -536,7 +536,7 @@ int32_t DmAuthMessageProcessor::CreateMessageReqCredExchange(std::shared_ptrisOnline) { jsonData[DM_TAG_LNN_PUBLICK_KEY] = context->accesser.lnnPublicKey; } - jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY] = context->accesser.transmitPublicKey; + jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY] = context->accesser.ephemeralPublicKey; jsonData[DM_TAG_DEVICE_ID] = context->accesser.deviceId; jsonData[DM_TAG_PEER_USER_SPACE_ID] = context->accesser.userId; jsonData[DM_TAG_TOKEN_ID] = context->accesser.tokenId; @@ -561,7 +561,7 @@ int32_t DmAuthMessageProcessor::CreateMessageRspCredExchange(std::shared_ptrisOnline) { jsonData[DM_TAG_LNN_PUBLICK_KEY] = context->accessee.lnnPublicKey; } - jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY] = context->accessee.transmitPublicKey; // 本端应用级公钥 + jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY] = context->accessee.ephemeralPublicKey; // 本端应用级公钥 jsonData[DM_TAG_DEVICE_ID] = context->accessee.deviceId; // 本端deviceId jsonData[DM_TAG_PEER_USER_SPACE_ID] = context->accessee.userId; // 本端userId jsonData[DM_TAG_TOKEN_ID] = context->accessee.tokenId; // 本端tokenId -- Gitee From 5bccecd79aa2fc828939808abd13457a62a27c12 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Tue, 25 Mar 2025 17:12:17 +0800 Subject: [PATCH 281/382] =?UTF-8?q?feat:=20=E5=87=AD=E6=8D=AE=E3=80=81ACL?= =?UTF-8?q?=E6=9F=A5=E8=AF=A2=E8=A7=A3=E8=80=A6src=E3=80=81sink?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/dm_auth_state.h | 2 - .../auth_stages/auth_negotiate.cpp | 258 ++++++++---------- 2 files changed, 113 insertions(+), 147 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index f42d1cbac..4f6dfd220 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -323,8 +323,6 @@ public: private: int32_t RespQueryAcceseeIds(std::shared_ptr context); - bool HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList); - uint32_t GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo); bool AclCompareTwoIds(std::shared_ptr context, const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee); bool AclCompareFourIds(std::shared_ptr context, diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 07254ad24..e99941dd9 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -56,7 +56,7 @@ static std::map g_pinAuthTypeFallBackMap = { // Maximum number of recursive lookups constexpr size_t MAX_FALLBACK_LOOPKUP_TIMES = 2; -// security_device_auth凭据查询相关定义,保持与device_auth.h一致 +// Security device auth credential query related definitions, keep consistent with device_auth.h const char * const FILED_DEVICE_ID = "deviceId"; const char * const FILED_DEVICE_ID_HASH = "deviceIdHash"; const char * const FILED_USER_ID = "userId"; @@ -74,6 +74,83 @@ enum DmRole { DM_ROLE_FA_TO_DEVICE }; +bool HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList) +{ + // Store the token of src and sink. The size must be 2. + if (tokenList.size() != 2) { + LOGE("HaveSameTokenId invalid tokenList size."); + return false; + } + + // tokenIdList = [srcTokenId, sinkTokenId] + std::string srcTokenIdHash = Crypto::Sha256(tokenList[0]); + std::string sinkTokenIdHash = Crypto::Sha256(tokenList[1]); + + return (srcTokenIdHash == context->accesser.tokenIdHash) && + (sinkTokenIdHash == context->accessee.tokenIdHash); +} + +uint32_t GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo) +{ + if (!credInfo[FILED_CRED_TYPE].IsNumberInteger() || !credInfo[FILED_AUTHORIZED_SCOPE].IsNumber()) { + return DM_INVALIED_BINDTYPE; + } + + int32_t credType = credInfo[FILED_CRED_TYPE].Get(); + int32_t authorizedScope = credInfo[FILED_AUTHORIZED_SCOPE].Get(); + if (authorizedScope == SCOPE_USER) { + if (credType == ACCOUNT_RELATED) { + return DM_IDENTICAL_ACCOUNT; + } else if (credType == ACCOUNT_ACROSS) { + return DM_ACROSS_ACCOUNT; + } + } + + std::vector appList; + credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList); + if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_APP && HaveSameTokenId(context, appList)) { + return DM_POINT_TO_POINT; + } + + // 未确定凭据类型 + return DM_INVALIED_BINDTYPE; +} + +int32_t DmQueryCredential(std::shared_ptr context, JsonObject &queryResult) +{ + int32_t ret; + uint32_t credType; + JsonObject queryParams; + + DmAccess access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; + DmAccess remoteAccess = context->direction == DM_AUTH_SOURCE ? context->accessee : context->accesser; + + queryParams[FILED_DEVICE_ID_HASH] = remoteAccess.deviceId; + queryParams[FILED_USER_ID] = access.userId; + queryParams[FILED_PEER_USER_SPACE_ID] = remoteAccess.userId; + ret = context->hiChainAuthConnector->QueryCredentialInfo(access.userId, queryParams, queryResult); + if (ret != DM_OK) { + LOGE("DmQueryCredential fail to query credential id list."); + return ret; + } + // TODO: delete + LOGI("DmQueryCredential for userId %{public}d and queryParams %{public}s " + "query credentialInfo: %{public}s", access.userId, queryParams.Dump().c_str(), + queryResult.Dump().c_str()); + + for (auto& item : queryResult.Items()) { + // 确认凭据类型 + credType = GetCredentialType(context, item); + if (credType == DM_INVALIED_BINDTYPE) { + continue; + } + + item[FILED_CRED_TYPE] = credType; + } + + return DM_OK; +} + } DmAuthStateType AuthSrcStartState::GetStateType() @@ -128,9 +205,7 @@ int32_t AuthSrcNegotiateStateMachine::Action(std::shared_ptr cont LOGI("AuthSrcNegotiateStateMachine::Action sessionId %{public}d.", context->sessionId); context->reply = ERR_DM_AUTH_REJECT; - // Q: 初始化时已赋值,此处需确认调试结果 context->accessee.bundleName = context->accesser.bundleName; - // 为什么之前DmVersion传空? context->accessee.dmVersion = ""; // 计算哈希值 @@ -162,179 +237,90 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptraccessee.deviceId = std::string(localDeviceId); - - // 2. 获取userId + context->accessee.deviceIdHash = Crypto::Sha256(context->accessee.deviceId); + + // 2. Get userId int32_t userId = AuthManagerBase::DmGetUserId(context->accessee.displayId, context->accessee.userId); if (userId < 0) { return ERR_DM_FAILED; } context->accessee.userId = userId; + context->accessee.userIdHash = Crypto::Sha256(std::to_string(context->accessee.userId)); - // 3. 获取accountId + // 3. Get accountId context->accessee.accountId = MultipleUserConnector::GetOhosAccountIdByUserId(context->accessee.userId); + context->accessee.accountIdHash = Crypto::Sha256(context->accessee.accountId); - // 4. 获取tokenId + // 4. Get tokenId std::string tmpBundleName = context->accessee.bundleName.empty() ? context->accesser.bundleName : context->accessee.bundleName; int64_t tokenId; ret = AppManager::GetInstance().GetHapTokenIdByName(context->accessee.userId, tmpBundleName, 0, tokenId); if (ret != DM_OK) { - // 不传bundleName且无法获取到tokenId时,即为FA-device + // If bundleName is not passed and tokenId cannot be obtained, it is an FA-device. if (context->accessee.bundleName.empty()) { dmRole = DM_ROLE_FA_TO_DEVICE; LOGI("RespQueryTokenId: FA to device"); return DM_OK; } - LOGI("RespQueryTokenId: get tokenId by bundleName failed %{public}s, may be FA-device", + LOGE("RespQueryTokenId: get tokenId by bundleName failed %{public}s", GetAnonyString(context->accessee.bundleName).c_str()); - // 对于FA-device,无tokenId - return DM_OK; + return ERR_DM_FAILED; } context->accessee.bundleName = tmpBundleName; context->accessee.tokenId = static_cast(tokenId); + context->accessee.tokenIdHash = Crypto::Sha256(std::to_string(context->accessee.tokenId)); return DM_OK; } -bool AuthSinkNegotiateStateMachine::HaveSameTokenId(std::shared_ptr context, - const std::vector &tokenList) -{ - if (tokenList.size() != 2) { // 2端的token - LOGE("HaveSameTokenId invalid tokenList size."); - return false; - } - - const std::string &src_tokenId = tokenList[0]; - const std::string &sink_tokenId = tokenList[1]; - - // 计算src_tokenId的哈希值 - std::string src_tokenIdHash = Crypto::Sha256(src_tokenId); - // 比较src_tokenId的哈希值和sink_tokenId - if (src_tokenIdHash != context->accesser.tokenIdHash) { - return false; - } - - if (sink_tokenId != std::to_string(context->accessee.tokenId)) { - return false; - } - - return true; -} - -uint32_t AuthSinkNegotiateStateMachine::GetCredentialType(std::shared_ptr context, - const JsonItemObject &credInfo) -{ - // 判断是否同账号 - // TODO: 需要确定截断长度 - if (Crypto::Sha256(context->accessee.accountId) == context->accesser.accountIdHash && - context->accessee.accountId != "ohosAnonymousUid") { - if (credInfo[FILED_CRED_TYPE].Get() == ACCOUNT_RELATED && - credInfo[FILED_AUTHORIZED_SCOPE].Get() == SCOPE_USER) { - return DM_IDENTICAL_ACCOUNT; - } - } else { - if (credInfo[FILED_CRED_TYPE].Get() == ACCOUNT_ACROSS && - credInfo[FILED_AUTHORIZED_SCOPE].Get() == SCOPE_USER) { - return DM_ACROSS_ACCOUNT; - } - std::vector appList; - credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList); - if (credInfo[FILED_CRED_TYPE].Get() == ACCOUNT_UNRELATED && - credInfo[FILED_AUTHORIZED_SCOPE].Get() == SCOPE_APP && - HaveSameTokenId(context, appList) == true) { - return DM_POINT_TO_POINT; - } - } - - // 未确定凭据类型 - return DM_INVALIED_BINDTYPE; -} - -// 比较ACL四元组:双端的deviceId和userId +// Compares hashs of the device IDs and user IDs bool AuthSinkNegotiateStateMachine::AclCompareTwoIds(std::shared_ptr context, const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) { return Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash && Crypto::Sha256(std::to_string(accesser.GetAccesserUserId())) == context->accesser.userIdHash && - accessee.GetAccesseeDeviceId() == context->accessee.deviceId && - accessee.GetAccesseeUserId() == context->accessee.userId; + Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash && + Crypto::Sha256(std::to_string(accessee.GetAccesseeUserId())) == context->accessee.userIdHash; } -// 比较ACL八元组:四元组加双端的accountId和tokenId +// Compares hashs of the device IDs, user IDs, account IDs, and token IDs bool AuthSinkNegotiateStateMachine::AclCompareFourIds(std::shared_ptr context, const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) { return AclCompareTwoIds(context, accesser, accessee) && Crypto::Sha256(accesser.GetAccesserAccountId()) == context->accesser.accountIdHash && Crypto::Sha256(std::to_string(accesser.GetAccesserTokenId())) == context->accesser.tokenIdHash && - accessee.GetAccesseeAccountId() == context->accessee.accountId && - accessee.GetAccesseeTokenId() == static_cast(context->accessee.tokenId); + Crypto::Sha256(accessee.GetAccesseeAccountId()) == context->accessee.accountIdHash && + Crypto::Sha256(std::to_string(accessee.GetAccesseeTokenId())) == context->accessee.tokenIdHash; } -/** - 有无凭据确认逻辑:以ACL的credId为索引,在凭据列表中寻找凭据,若没找到则认为无对应凭据 - - 由于获取凭据时没有对端信息,无法基于对端信息查询凭据,只能通过ACL确认 - 凭据类型获取逻辑:GetCredentialType - - 问题: - 1. 无法确定有凭据无ACL的场景(因为需要基于ACL的ids与凭据匹配,匹配不上的则无信息) - - 输出: - isAuthed = true/false - credentialInfos = "{ - "[credId1]": "[credType1]", - "[credId2]": "[credType2]" - }" - */ int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptr context) { int32_t ret; - uint32_t credType; - JsonObject queryParams; JsonObject queryResult; - bool isEmpty = true; - - // 1. 获取所有凭据(参考addCredential和agreeCredential) - queryParams[FILED_DEVICE_ID_HASH] = context->accesser.deviceIdHash; - queryParams[FILED_PEER_USER_SPACE_ID] = context->accesser.userId; - queryParams[FILED_USER_ID] = context->accessee.userId; - // 同账号凭据 - if (context->accessee.accountId != "ohosAnonymousUid" && - Crypto::Sha256(context->accessee.accountId) == context->accesser.accountIdHash) { - queryParams[FILED_CRED_TYPE] = 1; // 1 - 账号相关 - } - ret = context->hiChainAuthConnector->QueryCredentialInfo(context->accessee.userId, queryParams, queryResult); + JsonObject packResult; // Data to be packed and sent to the peer + + // 1. Retrieve all credentials + ret = DmQueryCredential(context, queryResult); if (ret != DM_OK) { - LOGE("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo fail to query credential id list."); + LOGE("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo fail to query credential"); return ret; } - LOGI("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo for userId %{public}d and queryParams %{public}s " - "query credentialInfo: %{public}s", context->accessee.userId, queryParams.Dump().c_str(), - queryResult.Dump().c_str()); - - for (auto& item : queryResult.Items()) { - isEmpty = false; - // 确认凭据类型 - credType = GetCredentialType(context, item); - if (credType == DM_INVALIED_BINDTYPE) { - continue; - } - - item[FILED_CRED_TYPE] = credType; - } - // 2. 获取所有ACL + // 2. Retrieve all ACLs std::vector profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfile(); - bool isAclActive = false; for (const auto &item : profiles) { + bool isAclMatched = false; auto accesser = item.GetAccesser(); auto accessee = item.GetAccessee(); + // TODO: delete LOGD("Got acl: credId - %{public}d ", accessee.GetAccesseeCredentialId()); LOGD("accesser: deviceId - %{public}s, userId - %{public}d, accountId - %{public}s, tokenId - %{public}ld", accesser.GetAccesserDeviceId().c_str(), accesser.GetAccesserUserId(), @@ -343,36 +329,26 @@ int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptr(); + // Confirm if there is a trusted relationship + uint32_t credType = queryResult[credId][FILED_CRED_TYPE].Get(); if (credType == DM_IDENTICAL_ACCOUNT || credType == DM_ACROSS_ACCOUNT) { - queryResult[credId]["isAclActive"] = AclCompareTwoIds(context, accesser, accessee); + isAclMatched = AclCompareTwoIds(context, accesser, accessee); } else if (credType == DM_POINT_TO_POINT) { - queryResult[credId]["isAclActive"] = AclCompareFourIds(context, accesser, accessee); + isAclMatched = AclCompareFourIds(context, accesser, accessee); } - LOGD("credential match to acl success with credType %{public}d", credType); - } - - // 3. 筛选凭据 - std::vector invalidCredIds; - JsonObject packResult; // 需要打包发送到对端的数据 - for (const auto &item : queryResult.Items()) { - std::string credId = item.Key(); - if (!item[credId].Contains("isAclActive") || item[credId]["isAclActive"].Get() == false) { - continue; + + if (isAclMatched) { + packResult[credId] = credType; + LOGI("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo success to get credType %{public}d", credType); } - std::vector credTypeList; - item[credId][FILED_CRED_TYPE].Get(credTypeList); - packResult[credId] = credTypeList; } - context->accessee.isAuthed = isEmpty; context->accessee.credentialInfos = packResult.Dump(); return DM_OK; @@ -380,7 +356,6 @@ int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptr context) { - // 获取accesee四元组:uid、userId、accountId、tokenId int32_t ret = RespQueryAcceseeIds(context); if (ret != DM_OK) { LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to get all id."); @@ -388,19 +363,12 @@ int32_t AuthSinkNegotiateStateMachine::ProcRespNegotiate5_1_0(std::shared_ptraccesser.isOnline = context->softbusConnector->CheckIsOnline(context->accesser.deviceIdHash, true); - // 获取凭据信息 ret = GetAuthCredentialInfo(context); if (ret != DM_OK) { LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to get credential."); return ERR_DM_FAILED; } - context->accessee.deviceIdHash = Crypto::Sha256(context->accessee.deviceId); - context->accessee.userIdHash = Crypto::Sha256(std::to_string(context->accessee.userId)); - context->accessee.accountIdHash = Crypto::Sha256(context->accessee.accountId); - context->accessee.tokenIdHash = Crypto::Sha256(std::to_string(context->accessee.tokenId)); - - // 状态跳转在100报文中处理 return DM_OK; } -- Gitee From 53d995098561eb8dcd1ff2deccf7af53f2106049 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Tue, 25 Mar 2025 14:38:00 +0800 Subject: [PATCH 282/382] =?UTF-8?q?fix=EF=BC=9Abugfix=EF=BC=8Cauth=5Fcrede?= =?UTF-8?q?ntial.cpp=E4=B8=ADosAccountId=E6=9F=A5=E8=AF=A2=E6=96=B9?= =?UTF-8?q?=E6=B3=95=E4=BF=AE=E6=94=B9=E4=B8=BA=E4=BB=8E=E4=B8=8A=E4=B8=8B?= =?UTF-8?q?=E6=96=87=E4=B8=ADuserId=E8=8E=B7=E5=8F=96?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication_v2/auth_stages/auth_credential.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 7cc4a5583..ebbafb751 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -138,8 +138,7 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co SetAuthContext(skId, context->accesser.transmitSkTimeStamp, context->accesser.transmitSessionKeyId); msgType = MSG_TYPE_REQ_CREDENTIAL_AUTH_START; // 发送160 // 认证用户凭据 - int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); - ret = context->hiChainAuthConnector->AuthCredential(osAccountId, context->requestId, + ret = context->hiChainAuthConnector->AuthCredential(authContext->accesser.userId, context->requestId, context->accesser.lnnCredentialId, std::string("")); if (ret != DM_OK) { LOGE("AuthSrcCredentialAuthDoneState::Action Hichain auth credentail failed"); @@ -310,7 +309,7 @@ int32_t AuthCredentialAgreeState::GenerateCredIdAndPublicKey(DmAuthScope authori } // 生成凭据 - int32_t osAccountId = authContext->direction == DM_AUTH_SOURCE ? + int32_t osAccountId = (authContext->direction == DM_AUTH_SOURCE) ? authContext->accesser.userId : authContext->accessee.userId; std::string credId; int32_t ret = authContext->hiChainAuthConnector->AddCredential(osAccountId, authParamsString, credId); @@ -417,7 +416,7 @@ int32_t AuthSinkCredentialExchangeState::Action(std::shared_ptr c LOGI("AuthSinkCredentialExchangeState::Action start."); int32_t ret = ERR_DM_FAILED; std::string tmpCredId; - int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + int32_t osAccountId = authContext->accessee.userId; context->isAppCredentialVerified = false; if (context == nullptr || context->hiChainAuthConnector == nullptr || @@ -485,7 +484,7 @@ int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr c LOGI(" AuthSrcCredentialAuthStartState::Action start."); int32_t ret = ERR_DM_FAILED; std::string tmpCredId; - int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); + int32_t osAccountId = authContext->accesser.userId; if (context == nullptr || context->hiChainAuthConnector == nullptr || context->authMessageProcessor == nullptr || context->softbusConnector == nullptr) { -- Gitee From f6a2dfbbf3ba12066d049595512d6b0f19910ff8 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Tue, 25 Mar 2025 14:43:38 +0800 Subject: [PATCH 283/382] =?UTF-8?q?fix=EF=BC=9A=E7=BC=96=E8=AF=91=E6=8A=A5?= =?UTF-8?q?=E9=94=99?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_credential.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index ebbafb751..28bc97258 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -138,7 +138,7 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co SetAuthContext(skId, context->accesser.transmitSkTimeStamp, context->accesser.transmitSessionKeyId); msgType = MSG_TYPE_REQ_CREDENTIAL_AUTH_START; // 发送160 // 认证用户凭据 - ret = context->hiChainAuthConnector->AuthCredential(authContext->accesser.userId, context->requestId, + ret = context->hiChainAuthConnector->AuthCredential(context->accesser.userId, context->requestId, context->accesser.lnnCredentialId, std::string("")); if (ret != DM_OK) { LOGE("AuthSrcCredentialAuthDoneState::Action Hichain auth credentail failed"); @@ -416,7 +416,7 @@ int32_t AuthSinkCredentialExchangeState::Action(std::shared_ptr c LOGI("AuthSinkCredentialExchangeState::Action start."); int32_t ret = ERR_DM_FAILED; std::string tmpCredId; - int32_t osAccountId = authContext->accessee.userId; + int32_t osAccountId = context->accessee.userId; context->isAppCredentialVerified = false; if (context == nullptr || context->hiChainAuthConnector == nullptr || @@ -484,7 +484,7 @@ int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr c LOGI(" AuthSrcCredentialAuthStartState::Action start."); int32_t ret = ERR_DM_FAILED; std::string tmpCredId; - int32_t osAccountId = authContext->accesser.userId; + int32_t osAccountId = context->accesser.userId; if (context == nullptr || context->hiChainAuthConnector == nullptr || context->authMessageProcessor == nullptr || context->softbusConnector == nullptr) { -- Gitee From a848b29fa4f03d7dcff3bb5763c2a4994f61885d Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Tue, 25 Mar 2025 15:58:11 +0800 Subject: [PATCH 284/382] =?UTF-8?q?fix=EF=BC=9Atmp=20=E8=A7=A3=E5=86=B3?= =?UTF-8?q?=E8=BF=90=E8=A1=8C=E6=8C=82=E4=BA=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.cpp | 78 ++++++++++--------- 1 file changed, 42 insertions(+), 36 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index ac1331a52..ff09f2d8c 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -233,45 +233,51 @@ DmAuthMessageProcessor::DmAuthMessageProcessor() LOGI("DmAuthMessageProcessor constructor"); cryptoMgr_ = std::make_shared(); createMessageFuncMap_ = { - {MSG_TYPE_REQ_ACL_NEGOTIATE, &DmAuthMessageProcessor::CreateNegotiateMessage}, - {MSG_TYPE_RESP_ACL_NEGOTIATE, &DmAuthMessageProcessor::CreateRespNegotiateMessage}, - {MSG_TYPE_REQ_USER_CONFIRM, &DmAuthMessageProcessor::CreateMessageReqUserConfirm}, - {MSG_TYPE_RESP_USER_CONFIRM, &DmAuthMessageProcessor::CreateMessageRespUserConfirm}, - {MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqPinAuthStart}, - {MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate}, - {MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageRespPinAuthStart}, - {MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate}, - {MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageReqCredExchange}, - {MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageRspCredExchange}, - {MSG_TYPE_REQ_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqCredAuthStart}, - {MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE, &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, - {MSG_TYPE_RESP_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, - {MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE, &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, - {MSG_TYPE_REQ_DATA_SYNC, &DmAuthMessageProcessor::CreateSyncMessage}, - {MSG_TYPE_RESP_DATA_SYNC, &DmAuthMessageProcessor::CreateMessageSyncResp}, - {MSG_TYPE_AUTH_REQ_FINISH, &DmAuthMessageProcessor::CreateMessageFinish}, - {MSG_TYPE_AUTH_RESP_FINISH, &DmAuthMessageProcessor::CreateMessageFinish}, + {DmMessageType::MSG_TYPE_REQ_ACL_NEGOTIATE, &DmAuthMessageProcessor::CreateNegotiateMessage}, + {DmMessageType::MSG_TYPE_RESP_ACL_NEGOTIATE, &DmAuthMessageProcessor::CreateRespNegotiateMessage}, + {DmMessageType::MSG_TYPE_REQ_USER_CONFIRM, &DmAuthMessageProcessor::CreateMessageReqUserConfirm}, + {DmMessageType::MSG_TYPE_RESP_USER_CONFIRM, &DmAuthMessageProcessor::CreateMessageRespUserConfirm}, + {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqPinAuthStart}, + {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageRespPinAuthStart}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, + &DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageReqCredExchange}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageRspCredExchange}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqCredAuthStart}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE, + &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE, + &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, + {DmMessageType::MSG_TYPE_REQ_DATA_SYNC, &DmAuthMessageProcessor::CreateSyncMessage}, + {DmMessageType::MSG_TYPE_RESP_DATA_SYNC, &DmAuthMessageProcessor::CreateMessageSyncResp}, + {DmMessageType::MSG_TYPE_AUTH_REQ_FINISH, &DmAuthMessageProcessor::CreateMessageFinish}, + {DmMessageType::MSG_TYPE_AUTH_RESP_FINISH, &DmAuthMessageProcessor::CreateMessageFinish}, }; paraseMessageFuncMap_ = { - {MSG_TYPE_REQ_ACL_NEGOTIATE, &DmAuthMessageProcessor::ParseNegotiateMessage}, - {MSG_TYPE_RESP_ACL_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageRespAclNegotiate}, - {MSG_TYPE_REQ_USER_CONFIRM, &DmAuthMessageProcessor::ParseMessageReqUserConfirm}, - {MSG_TYPE_RESP_USER_CONFIRM, &DmAuthMessageProcessor::ParseMessageRespUserConfirm}, - {MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::ParseMessageReqPinAuthStart}, - {MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate}, - {MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::ParseMessageRespPinAuthStart}, - {MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate}, - {MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::ParseMessageReqCredExchange}, - {MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::ParseMessageRspCredExchange}, - {MSG_TYPE_REQ_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::ParseAuthStartMessage}, - {MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, - {MSG_TYPE_RESP_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, - {MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, - {MSG_TYPE_REQ_DATA_SYNC, &DmAuthMessageProcessor::ParseMessageSyncReq}, - {MSG_TYPE_RESP_DATA_SYNC, &DmAuthMessageProcessor::ParseMessageSyncResp}, - {MSG_TYPE_AUTH_REQ_FINISH, &DmAuthMessageProcessor::ParseMessageSinkFinish}, - {MSG_TYPE_AUTH_RESP_FINISH, &DmAuthMessageProcessor::ParseMessageSrcFinish}, + {DmMessageType::MSG_TYPE_REQ_ACL_NEGOTIATE, &DmAuthMessageProcessor::ParseNegotiateMessage}, + {DmMessageType::MSG_TYPE_RESP_ACL_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageRespAclNegotiate}, + {DmMessageType::MSG_TYPE_REQ_USER_CONFIRM, &DmAuthMessageProcessor::ParseMessageReqUserConfirm}, + {DmMessageType::MSG_TYPE_RESP_USER_CONFIRM, &DmAuthMessageProcessor::ParseMessageRespUserConfirm}, + {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::ParseMessageReqPinAuthStart}, + {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::ParseMessageRespPinAuthStart}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, + &DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::ParseMessageReqCredExchange}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::ParseMessageRspCredExchange}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::ParseAuthStartMessage}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE, + &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, + {DmMessageType::MSG_TYPE_REQ_DATA_SYNC, &DmAuthMessageProcessor::ParseMessageSyncReq}, + {DmMessageType::MSG_TYPE_RESP_DATA_SYNC, &DmAuthMessageProcessor::ParseMessageSyncResp}, + {DmMessageType::MSG_TYPE_AUTH_REQ_FINISH, &DmAuthMessageProcessor::ParseMessageSinkFinish}, + {DmMessageType::MSG_TYPE_AUTH_RESP_FINISH, &DmAuthMessageProcessor::ParseMessageSrcFinish}, }; + LOGI("DmAuthMessageProcessor constructor leave."); } DmAuthMessageProcessor::~DmAuthMessageProcessor() -- Gitee From 1eb76c4d41373e2b6584428177de9e0deaac29e7 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Tue, 25 Mar 2025 16:43:34 +0800 Subject: [PATCH 285/382] =?UTF-8?q?fix=EF=BC=9Amessage=E7=B1=BB=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E5=9B=9E=E9=80=80?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.h | 7 - .../dm_auth_message_processor.cpp | 155 +++++++++++------- 2 files changed, 99 insertions(+), 63 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index ad0d96d5d..a72afe550 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -188,11 +188,6 @@ 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 @@ -317,8 +312,6 @@ private: 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 diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index ff09f2d8c..b06896b28 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -232,51 +232,6 @@ DmAuthMessageProcessor::DmAuthMessageProcessor() { LOGI("DmAuthMessageProcessor constructor"); cryptoMgr_ = std::make_shared(); - createMessageFuncMap_ = { - {DmMessageType::MSG_TYPE_REQ_ACL_NEGOTIATE, &DmAuthMessageProcessor::CreateNegotiateMessage}, - {DmMessageType::MSG_TYPE_RESP_ACL_NEGOTIATE, &DmAuthMessageProcessor::CreateRespNegotiateMessage}, - {DmMessageType::MSG_TYPE_REQ_USER_CONFIRM, &DmAuthMessageProcessor::CreateMessageReqUserConfirm}, - {DmMessageType::MSG_TYPE_RESP_USER_CONFIRM, &DmAuthMessageProcessor::CreateMessageRespUserConfirm}, - {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqPinAuthStart}, - {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate}, - {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageRespPinAuthStart}, - {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, - &DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate}, - {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageReqCredExchange}, - {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageRspCredExchange}, - {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqCredAuthStart}, - {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE, - &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, - {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, - {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE, - &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, - {DmMessageType::MSG_TYPE_REQ_DATA_SYNC, &DmAuthMessageProcessor::CreateSyncMessage}, - {DmMessageType::MSG_TYPE_RESP_DATA_SYNC, &DmAuthMessageProcessor::CreateMessageSyncResp}, - {DmMessageType::MSG_TYPE_AUTH_REQ_FINISH, &DmAuthMessageProcessor::CreateMessageFinish}, - {DmMessageType::MSG_TYPE_AUTH_RESP_FINISH, &DmAuthMessageProcessor::CreateMessageFinish}, - }; - paraseMessageFuncMap_ = { - {DmMessageType::MSG_TYPE_REQ_ACL_NEGOTIATE, &DmAuthMessageProcessor::ParseNegotiateMessage}, - {DmMessageType::MSG_TYPE_RESP_ACL_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageRespAclNegotiate}, - {DmMessageType::MSG_TYPE_REQ_USER_CONFIRM, &DmAuthMessageProcessor::ParseMessageReqUserConfirm}, - {DmMessageType::MSG_TYPE_RESP_USER_CONFIRM, &DmAuthMessageProcessor::ParseMessageRespUserConfirm}, - {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::ParseMessageReqPinAuthStart}, - {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate}, - {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::ParseMessageRespPinAuthStart}, - {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, - &DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate}, - {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::ParseMessageReqCredExchange}, - {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::ParseMessageRspCredExchange}, - {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::ParseAuthStartMessage}, - {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, - {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, - {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE, - &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, - {DmMessageType::MSG_TYPE_REQ_DATA_SYNC, &DmAuthMessageProcessor::ParseMessageSyncReq}, - {DmMessageType::MSG_TYPE_RESP_DATA_SYNC, &DmAuthMessageProcessor::ParseMessageSyncResp}, - {DmMessageType::MSG_TYPE_AUTH_REQ_FINISH, &DmAuthMessageProcessor::ParseMessageSinkFinish}, - {DmMessageType::MSG_TYPE_AUTH_RESP_FINISH, &DmAuthMessageProcessor::ParseMessageSrcFinish}, - }; LOGI("DmAuthMessageProcessor constructor leave."); } @@ -298,12 +253,47 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont DmMessageType msgType = static_cast(jsonObject[TAG_MSG_TYPE].Get()); context->msgType = msgType; LOGI("DmAuthMessageProcessor::ParseMessage message type %{public}d", context->msgType); - auto itr = paraseMessageFuncMap_.find(msgType); - if (itr == paraseMessageFuncMap_.end()) { - LOGI("DmAuthMessageProcessor::ParseMessage message type error %{public}d", context->msgType); - return ERR_DM_FAILED; + // TODO:调试信息,上库前删除 + LOGI("DmAuthMessageProcessor::ParseMessage %{public}s", jsonObject.Dump().c_str()); + switch (msgType) { + case MSG_TYPE_REQ_ACL_NEGOTIATE: + return ParseNegotiateMessage(jsonObject, context); + case MSG_TYPE_RESP_ACL_NEGOTIATE: + return ParseMessageRespAclNegotiate(jsonObject, context); + case MSG_TYPE_REQ_USER_CONFIRM: + return ParseMessageReqUserConfirm(jsonObject, context); + case MSG_TYPE_RESP_USER_CONFIRM: + return ParseMessageRespUserConfirm(jsonObject, context); + case MSG_TYPE_REQ_PIN_AUTH_START: + return ParseMessageReqPinAuthStart(jsonObject, context); + case MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE: + return ParseMessageReqPinAuthNegotiate(jsonObject, context); + case MSG_TYPE_RESP_PIN_AUTH_START: + return ParseMessageRespPinAuthStart(jsonObject, context); + case MSG_TYPE_REQ_CREDENTIAL_AUTH_START: // 160 + return ParseAuthStartMessage(jsonObject, context); + case MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE: // 161 + case MSG_TYPE_RESP_CREDENTIAL_AUTH_START: // 170 + case MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE: // 171 + return ParseMessageNegotiateTransmit(jsonObject, context); + case MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE: + return ParseMessageRespPinAuthNegotiate(jsonObject, context); + case MSG_TYPE_REQ_CREDENTIAL_EXCHANGE: + return ParseMessageReqCredExchange(jsonObject, context); + case MSG_TYPE_RESP_CREDENTIAL_EXCHANGE: + return ParseMessageRspCredExchange(jsonObject, context); + case MSG_TYPE_REQ_DATA_SYNC: + return ParseMessageSyncReq(jsonObject, context); + case MSG_TYPE_RESP_DATA_SYNC: + return ParseMessageSyncResp(jsonObject, context); + case MSG_TYPE_AUTH_REQ_FINISH: + return ParseMessageSinkFinish(jsonObject, context); + case MSG_TYPE_AUTH_RESP_FINISH: + return ParseMessageSrcFinish(jsonObject, context); + default: + break; } - return (this->*(itr->second))(jsonObject, context); + return ERR_DM_FAILED; } static std::vector stringToVector(const std::string& str) @@ -465,13 +455,66 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh LOGI("DmAuthMessageProcessor::CreateMessage start. msgType is %{public}d", msgType); JsonObject jsonObj; jsonObj[TAG_MSG_TYPE] = msgType; - auto itr = createMessageFuncMap_.find(msgType); - if (itr == createMessageFuncMap_.end()) { - LOGE("DmAuthMessageProcessor::CreateMessage msgType %{public}d error.", msgType); - return ""; + switch (msgType) { + case MSG_TYPE_REQ_ACL_NEGOTIATE: + CreateNegotiateMessage(context, jsonObj); + break; + case MSG_TYPE_RESP_ACL_NEGOTIATE: + CreateRespNegotiateMessage(context, jsonObj); + break; + case MSG_TYPE_REQ_USER_CONFIRM: + CreateMessageReqUserConfirm(context, jsonObj); + break; + case MSG_TYPE_RESP_USER_CONFIRM: + CreateMessageRespUserConfirm(context, jsonObj); + break; + case MSG_TYPE_REQ_PIN_AUTH_START: + CreateMessageReqPinAuthStart(context, jsonObj); + break; + case MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE: + CreateMessageReqPinAuthNegotiate(context, jsonObj); + break; + case MSG_TYPE_RESP_PIN_AUTH_START: + CreateMessageRespPinAuthStart(context, jsonObj); + break; + case MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE: + CreateMessageRespPinAuthNegotiate(context, jsonObj); + break; + case MSG_TYPE_REQ_CREDENTIAL_EXCHANGE: + CreateMessageReqCredExchange(context, jsonObj); + break; + case MSG_TYPE_RESP_CREDENTIAL_EXCHANGE: + CreateMessageRspCredExchange(context, jsonObj); + break; + case MSG_TYPE_REQ_CREDENTIAL_AUTH_START: + CreateMessageReqCredAuthStart(context, jsonObj); + break; + case MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE: // 161 + case MSG_TYPE_RESP_CREDENTIAL_AUTH_START: // 170 + case MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE: // 171 + if (CreateCredentialNegotiateMessage(context, jsonObj) != DM_OK) { + return ""; + } + break; + case MSG_TYPE_REQ_DATA_SYNC: + if (CreateSyncMessage(context, jsonObj)!= DM_OK) { + return ""; + } + break; + case MSG_TYPE_RESP_DATA_SYNC: + CreateMessageSyncResp(context, jsonObj); + break; + case MSG_TYPE_AUTH_REQ_FINISH: + case MSG_TYPE_AUTH_RESP_FINISH: + CreateMessageFinish(context, jsonObj); + break; + default: + LOGE("DmAuthMessageProcessor::CreateMessage msgType %{public}d error.", msgType); + break; } - int32_t ret = (this->*(itr->second))(context, jsonObj); - return (ret == DM_OK) ? jsonObj.Dump() : ""; + // TODO:调试信息,上库前删除 + LOGI("DmAuthMessageProcessor::CreateMessage %{public}s", jsonObj.Dump().c_str()); + return jsonObj.Dump(); } // 内部各类报文的实现 -- Gitee From a6537bb06d904e2fb3a660f34e36dce8c358d485 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Tue, 25 Mar 2025 17:30:03 +0800 Subject: [PATCH 286/382] =?UTF-8?q?fix=EF=BC=9A160=E8=A7=A3=E6=9E=90?= =?UTF-8?q?=E5=88=A0=E9=99=A4=E6=8E=89credid=E5=AD=97=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.cpp | 17 ----------------- 1 file changed, 17 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index b06896b28..8f5c0e2eb 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1279,23 +1279,6 @@ int32_t DmAuthMessageProcessor::ParseAuthStartMessage(const JsonObject &jsonObje } context->transmitData = jsonObject[DM_TAG_DATA].Get(); - std::string jsonTag; - if (context->isOnline == false && context->isAppCredentialVerified == false) { // 首次认证的应用凭据 - jsonTag = DM_TAG_APP_CREDENTIAL_ID; - context->accesser.transmitCredentialId = jsonObject[DM_TAG_APP_CREDENTIAL_ID].Get(); - } else if (context->isOnline == false) { // 首次认证的用户凭据 - jsonTag = DM_TAG_USER_CREDENTIAL_ID; - context->accesser.lnnCredentialId = jsonObject[DM_TAG_USER_CREDENTIAL_ID].Get(); - } else { // 非首次认证的应用凭据 - jsonTag = DM_TAG_APP_CREDENTIAL_ID; - context->accesser.transmitCredentialId = jsonObject[DM_TAG_APP_CREDENTIAL_ID].Get(); - } - - if (!jsonObject.Contains(jsonTag) || !jsonObject[jsonTag].IsString()) { - LOGE("DmAuthMessageProcessor::ParseAuthStartMessage Unlegal json CRED ID"); - return ERR_DM_FAILED; - } - context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } -- Gitee From b9552769072357fba312130045581ff4a80fde09 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Tue, 25 Mar 2025 17:44:22 +0800 Subject: [PATCH 287/382] =?UTF-8?q?180/190=E5=90=8C=E6=AD=A5credid?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.h | 4 +- .../dm_auth_message_processor.cpp | 47 +++++++++++++------ 2 files changed, 35 insertions(+), 16 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index a72afe550..f3a1337a3 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -32,8 +32,8 @@ constexpr const char *DM_TAG_DATA = "data"; // M 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_USER_CREDENTIAL_ID = "lnnCredentialId"; -constexpr const char *DM_TAG_APP_CREDENTIAL_ID = "transmitCredentialId"; +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"; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 8f5c0e2eb..0b3e77ac4 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -689,20 +689,42 @@ int32_t DmAuthMessageProcessor::CreateMessageFinish(std::shared_ptr &context, DmAccess &access, JsonObject &jsonObject) { - if (!jsonObject[DM_TAG_LNN_SK_ID].IsString()) { - LOGE("ParseSyncMessage DM_TAG_LNN_SK_ID error"); + // transmit session key is mandatory + if (!jsonObject[DM_TAG_TRANSMIT_SK_ID].IsString()) { + LOGE("ParseSyncMessage DM_TAG_TRANSMIT_SK_ID error"); return ERR_DM_FAILED; } - access.lnnSessionKeyId = std::atoi(jsonObject[DM_TAG_LNN_SK_ID].Get().c_str()); - if (!jsonObject[DM_TAG_LNN_SK_TIMESTAMP].IsString()) { - LOGE("ParseSyncMessage DM_TAG_LNN_SK_TIMESTAMP error"); + access.transmitSessionKeyId = std::atoi(jsonObject[DM_TAG_TRANSMIT_SK_ID].Get().c_str()); + + if (!jsonObject[DM_TAG_TRANSMIT_SK_TIMESTAMP].IsString()) { + LOGE("ParseSyncMessage DM_TAG_TRANSMIT_SK_TIMESTAMP error"); + return ERR_DM_FAILED; + } + access.transmitSkTimeStamp = std::atoi(jsonObject[DM_TAG_TRANSMIT_SK_TIMESTAMP].Get().c_str()); + + if (!jsonObject[DM_TAG_TRANSMIT_CREDENTIAL_ID].IsString()) { + LOGE("ParseSyncMessage DM_TAG_TRANSMIT_CREDENTIAL_ID error"); return ERR_DM_FAILED; } - access.lnnSkTimeStamp = std::atoi(jsonObject[DM_TAG_LNN_SK_TIMESTAMP].Get().c_str()); + access.transmitCredentialId = std::atoi(jsonObject[DM_TAG_TRANSMIT_CREDENTIAL_ID].Get().c_str()); + + // lnn session key is optional + if (jsonObject[DM_TAG_LNN_SK_ID].IsString()) { + access.lnnSessionKeyId = std::atoi(jsonObject[DM_TAG_LNN_SK_ID].Get().c_str()); + } + if (jsonObject[DM_TAG_LNN_SK_TIMESTAMP].IsString()) { + access.lnnSkTimeStamp = std::atoi(jsonObject[DM_TAG_LNN_SK_TIMESTAMP].Get().c_str()); + } + + if (jsonObject[DM_TAG_LNN_CREDENTIAL_ID].IsString()) { + access.lnnCredentialId = std::atoi(jsonObject[DM_TAG_LNN_CREDENTIAL_ID].Get().c_str()); + } + if (!jsonObject[DM_TAG_DMVERSION].IsString()) { LOGE("ParseSyncMessage DM_TAG_DMVERSION error"); return ERR_DM_FAILED; } + access.dmVersion = jsonObject[DM_TAG_DMVERSION].Get(); if (!jsonObject[DM_TAG_ACCESS].IsString()) { // 再解析一次 LOGE("ParseSyncMessage DM_TAG_ACCESS error"); @@ -761,12 +783,7 @@ int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptr().c_str()); - } - if (jsonObject[DM_TAG_TRANSMIT_SK_TIMESTAMP].IsString()) { - access.transmitSkTimeStamp = std::atoi(jsonObject[DM_TAG_TRANSMIT_SK_TIMESTAMP].Get().c_str()); - } + ret = ParseSyncMessage(context, access, jsonObject); if (ret != DM_OK) { LOGE("DecryptSyncMessage ParseSyncMessage jsonStr error"); @@ -1152,11 +1169,13 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptrisOnline) { // 首次认证 syncMsgJson[DM_TAG_LNN_SK_ID]=std::to_string(accessSide.lnnSessionKeyId); syncMsgJson[DM_TAG_LNN_SK_TIMESTAMP]=std::to_string(accessSide.lnnSkTimeStamp); + syncMsgJson[DM_TAG_LNN_CREDENTIAL_ID] = accessSide.lnnCredentialId; } JsonObject accessJsonObj{}; -- Gitee From 8245885cacdddbf3590d41b2a7a894b71d660c73 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Tue, 25 Mar 2025 19:47:25 +0800 Subject: [PATCH 288/382] =?UTF-8?q?BUGFIX:=E4=BF=AE=E5=A4=8D180/190=20cred?= =?UTF-8?q?id=E8=A7=A3=E6=9E=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 0b3e77ac4..cb5580992 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -706,7 +706,7 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr LOGE("ParseSyncMessage DM_TAG_TRANSMIT_CREDENTIAL_ID error"); return ERR_DM_FAILED; } - access.transmitCredentialId = std::atoi(jsonObject[DM_TAG_TRANSMIT_CREDENTIAL_ID].Get().c_str()); + access.transmitCredentialId = jsonObject[DM_TAG_TRANSMIT_CREDENTIAL_ID].Get().c_str(); // lnn session key is optional if (jsonObject[DM_TAG_LNN_SK_ID].IsString()) { @@ -717,7 +717,7 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr } if (jsonObject[DM_TAG_LNN_CREDENTIAL_ID].IsString()) { - access.lnnCredentialId = std::atoi(jsonObject[DM_TAG_LNN_CREDENTIAL_ID].Get().c_str()); + access.lnnCredentialId = jsonObject[DM_TAG_LNN_CREDENTIAL_ID].Get().c_str(); } if (!jsonObject[DM_TAG_DMVERSION].IsString()) { -- Gitee From 57ce15c6ab56f09822544301aee6f36935b0bdee Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Tue, 25 Mar 2025 19:53:23 +0800 Subject: [PATCH 289/382] =?UTF-8?q?app=E8=A7=A3=E7=BB=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../include/deviceprofile_connector.h | 11 ++ .../src/deviceprofile_connector.cpp | 187 +++++++++++++++++- .../include/device_manager_service_impl.h | 2 + .../dm_auth_message_processor.cpp | 2 + .../src/device_manager_service_impl.cpp | 57 +++++- 5 files changed, 255 insertions(+), 4 deletions(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 52501ed83..8df1217e0 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -112,6 +112,8 @@ public: class DeviceProfileConnector : public IDeviceProfileConnector { DM_DECLARE_SINGLE_INSTANCE(DeviceProfileConnector); public: + DmOfflineParam DeleteAccessControlList_v2(const uint32_t tokenId, const std::string &localDeviceId, + const std::string &remoteDeviceId, int32_t bindLevel, const std::string &extra); std::vector GetAccessControlProfile(); std::vector GetAccessControlProfileByUserId(int32_t userId); std::vector GetAclProfileByDeviceIdAndUserId( @@ -241,6 +243,15 @@ private: bool CheckAclStatusNotMatch(const DistributedDeviceProfile::AccessControlProfile &profile, const std::string &localUdid, const std::vector &foregroundUserIds, const std::vector &backgroundUserIds); + void DeleteAppBindLevel_v2(DmOfflineParam &offlineParam, const uint32_t tokenId, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid); + void DeleteAppBindLevel_v2(DmOfflineParam &offlineParam, const uint32_t tokenId, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid, const std::string &extra); + void DeleteServiceBindLevel_v2(DmOfflineParam &offlineParam, const uint32_t tokenId, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid); }; extern "C" IDeviceProfileConnector *CreateDpConnectorInstance(); diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 4a04307d4..0febd3901 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -39,11 +39,192 @@ const uint32_t DM_INVALIED_BINDTYPE = 2048; const uint32_t DEVICE = 1; const uint32_t SERVICE = 2; const uint32_t APP = 3; +const uint32_t USER = 1; constexpr uint32_t MAX_SESSION_KEY_LENGTH = 512; namespace OHOS { namespace DistributedHardware { DM_IMPLEMENT_SINGLE_INSTANCE(DeviceProfileConnector); +DmOfflineParam DeviceProfileConnector::DeleteAccessControlList_v2(const uint32_t tokenId, + const std::string &localDeviceId, const std::string &remoteDeviceId, int32_t bindLevel, const std::string &extra) +{ + LOGI("localDeviceId %{public}s, remoteDeviceId %{public}s, bindLevel %{public}d.", + GetAnonyString(localDeviceId).c_str(), GetAnonyString(remoteDeviceId).c_str(), bindLevel); + DmOfflineParam offlineParam; + offlineParam.bindType = INVALIED_TYPE; + if (static_cast(bindLevel) > APP || static_cast(bindLevel) < USER) { + LOGE("Invalied bindlevel."); + return offlineParam; + } + int32_t userId = -1; + MultipleUserConnector::GetCallerUserId(userId); + std::vector profiles = GetAclProfileByDeviceIdAndUserId(localDeviceId, userId); + if (profiles.empty()) { + LOGE("Acl is empty."); + return offlineParam; + } + switch (bindLevel) { + case APP: + if (extra == "") { + DeleteAppBindLevel_v2(offlineParam, tokenId, profiles, localDeviceId, remoteDeviceId); + } else { + DeleteAppBindLevel_v2(offlineParam, tokenId, profiles, localDeviceId, remoteDeviceId, extra); + } + break; + case SERVICE: + DeleteServiceBindLevel_v2(offlineParam, tokenId, profiles, localDeviceId, remoteDeviceId); + break; + case DEVICE: + DeleteDeviceBindLevel(offlineParam, profiles, localDeviceId, remoteDeviceId); + break; + default: + break; + } + return offlineParam; +} + +void DeviceProfileConnector::DeleteAppBindLevel_v2(DmOfflineParam &offlineParam, const uint32_t tokenId, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid) +{ + int32_t bindNums = 0; + int32_t deleteNums = 0; + for (auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != APP) { + continue; + } + bindNums++; + if ((item.GetAccesser().GetAccesserTokenId() == static_cast(tokenId) || + item.GetAccesser().GetAccesserTokenId() == 0) && + item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); + LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + if ((item.GetAccessee().GetAccesseeTokenId() == static_cast(tokenId) || + item.GetAccessee().GetAccesseeTokenId() == 0) && + item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); + LOGI("Sink delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + } + offlineParam.leftAclNumber = bindNums - deleteNums; +} + +void DeviceProfileConnector::DeleteAppBindLevel_v2(DmOfflineParam &offlineParam, const uint32_t tokenId, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid, const std::string &extra) +{ + LOGI("DeviceProfileConnector::DeleteAppBindLevel extra %{public}s", extra.c_str()); + int32_t bindNums = 0; + int32_t deleteNums = 0; + uint32_t peerTokenId = std::atoi(extra.c_str()); + for (auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != APP) { + continue; + } + bindNums++; + if ((item.GetAccesser().GetAccesserTokenId() == static_cast(tokenId) || + item.GetAccesser().GetAccesserTokenId() == 0) && + (item.GetAccessee().GetAccesseeTokenId() == static_cast(peerTokenId) || + item.GetAccessee().GetAccesseeTokenId() == 0) && + item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); + LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + if ((item.GetAccessee().GetAccesseeTokenId() == static_cast(tokenId) || + item.GetAccessee().GetAccesseeTokenId() == 0) && + (item.GetAccesser().GetAccesserTokenId() == static_cast(peerTokenId) || + item.GetAccesser().GetAccesserTokenId() == 0) && + item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); + LOGI("Sink delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + } + offlineParam.leftAclNumber = bindNums - deleteNums; +} + +void DeviceProfileConnector::DeleteServiceBindLevel_v2(DmOfflineParam &offlineParam, const uint32_t tokenId, + const std::vector &profiles, const std::string &localUdid, + const std::string &remoteUdid) +{ + int32_t bindNums = 0; + int32_t deleteNums = 0; + for (auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != SERVICE) { + continue; + } + bindNums++; + if ((item.GetAccesser().GetAccesserTokenId() == static_cast(tokenId) || + item.GetAccesser().GetAccesserTokenId() == 0) && + item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = SERVICE; + LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + if ((item.GetAccessee().GetAccesseeTokenId() == static_cast(tokenId) || + item.GetAccessee().GetAccesseeTokenId() == 0) && + item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = SERVICE; + LOGI("Sink delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", + item.GetBindType(), GetAnonyString(localUdid).c_str(), + GetAnonyString(remoteUdid).c_str()); + continue; + } + } + offlineParam.leftAclNumber = bindNums - deleteNums; +} + std::vector DeviceProfileConnector::GetAccessControlProfile() { std::vector profiles; @@ -1230,7 +1411,8 @@ OHOS::DistributedHardware::ProcessInfo DeviceProfileConnector::HandleAppUnBindEv } if (item.GetAccesser().GetAccesserUserId() == remoteUserId && item.GetAccesser().GetAccesserDeviceId() == remoteUdid && - static_cast(item.GetAccesser().GetAccesserTokenId()) == tokenId && + (static_cast(item.GetAccesser().GetAccesserTokenId()) == tokenId || + static_cast(item.GetAccesser().GetAccesserTokenId()) == 0) && item.GetAccessee().GetAccesseeDeviceId() == localUdid) { LOGI("Src device unbind."); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); @@ -1240,7 +1422,8 @@ OHOS::DistributedHardware::ProcessInfo DeviceProfileConnector::HandleAppUnBindEv } if (item.GetAccessee().GetAccesseeUserId() == remoteUserId && item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && - static_cast(item.GetAccessee().GetAccesseeTokenId()) == tokenId && + (static_cast(item.GetAccessee().GetAccesseeTokenId()) == tokenId || + static_cast(item.GetAccessee().GetAccesseeTokenId()) == 0) && item.GetAccesser().GetAccesserDeviceId() == localUdid) { LOGI("Sink device unbind."); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index c7a5e288e..02e63514e 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -139,6 +139,8 @@ public: void DeleteAlwaysAllowTimeOut(); void CheckDeleteCredential(const std::string &remoteUdid); int32_t CheckDeviceInfoPermission(const std::string &localUdid, const std::string &peerDeviceId); + int32_t DeleteAcl(const std::string &sessionName, const std::string &localUdid, const std::string &remoteUdid, + int32_t bindLevel, const std::string &extra); private: int32_t PraseNotifyEventJson(const std::string &event, JsonObject &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index cb5580992..3f7a7cfe2 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -185,6 +185,7 @@ void DmAuthMessageProcessor::SetLnnAccessControlList(std::shared_ptraccesser.deviceId); accesser.SetAccesserUserId(context->accesser.userId); accesser.SetAccesserAccountId(context->accesser.accountId); + accesser.SetAccesserTokenId(0); accesser.SetAccesserDeviceName(context->accesser.deviceName); accesser.SetAccesserCredentialId(stoi(context->accesser.lnnCredentialId)); accesser.SetAccesserSessionKeyId(context->accesser.lnnSessionKeyId); @@ -192,6 +193,7 @@ void DmAuthMessageProcessor::SetLnnAccessControlList(std::shared_ptraccessee.deviceId); accessee.SetAccesseeUserId(context->accessee.userId); accessee.SetAccesseeAccountId(context->accessee.accountId); + accessee.SetAccesseeTokenId(0); accessee.SetAccesseeDeviceName(context->accessee.deviceName); accessee.SetAccesseeCredentialId(stoi(context->accessee.lnnCredentialId)); accessee.SetAccesseeSessionKeyId(context->accessee.lnnSessionKeyId); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 1145fd277..80c792de7 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -229,7 +229,12 @@ int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const return ERR_DM_INPUT_PARA_INVALID; } std::string extra = ""; - return authMgr_->UnBindDevice(pkgName, udid, bindLevel, extra); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + if (bindLevel == DEVICE) { + DeleteGroup(pkgName, udid); + } + return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel, extra); } int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid, @@ -240,7 +245,12 @@ int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const pkgName.c_str(), GetAnonyString(udid).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - return authMgr_->UnBindDevice(pkgName, udid, bindLevel, extra); + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + if (bindLevel == DEVICE) { + DeleteGroup(pkgName, udid); + } + return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel, extra); } int32_t DeviceManagerServiceImpl::SetUserOperation(std::string &pkgName, int32_t action, @@ -1303,6 +1313,49 @@ int32_t DeviceManagerServiceImpl::CheckDeviceInfoPermission(const std::string &l return DM_OK; } +int32_t DeviceManagerServiceImpl::DeleteAcl(const std::string &sessionName, const std::string &localUdid, + const std::string &remoteUdid, int32_t bindLevel, const std::string &extra) +{ + LOGI("DeleteAcl sessionName %{public}s, localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.", + sessionName.c_str(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel); + uint32_t tokenId = 0; + int32_t userId = 0; + MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, userId); + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().DeleteAccessControlList_v2( + tokenId, localUdid, remoteUdid, bindLevel, extra); + if (offlineParam.bindType == INVALIED_TYPE) { + LOGE("Acl not contain the sessionName bind data."); + return ERR_DM_FAILED; + } + if (bindLevel == APP) { + ProcessInfo processInfo; + processInfo.pkgName = sessionName; + MultipleUserConnector::GetCallerUserId(processInfo.userId); + if (offlineParam.leftAclNumber != 0) { + LOGI("The sessionName unbind app-level type leftAclNumber not zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + softbusConnector_->HandleDeviceOffline(remoteUdid); + return DM_OK; + } + if (offlineParam.leftAclNumber == 0) { + LOGI("The sessionName unbind app-level type leftAclNumber is zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + return DM_OK; + } + } + if (bindLevel == DEVICE && offlineParam.leftAclNumber != 0) { + LOGI("Unbind deivce-level, retain identical account bind type."); + return DM_OK; + } + if (bindLevel == DEVICE && offlineParam.leftAclNumber == 0) { + LOGI("Unbind deivce-level, retain null."); + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + return DM_OK; + } + return ERR_DM_FAILED; +} + extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) { return new DeviceManagerServiceImpl; -- Gitee From ffec1b22b8467d5bd5a9da718b196075c32edcad Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Tue, 25 Mar 2025 19:48:32 +0800 Subject: [PATCH 290/382] =?UTF-8?q?fix=EF=BC=9Adm=5Fauth=5Fmessage=5Fproce?= =?UTF-8?q?ssor=E4=B8=AD=E6=94=B6=E5=8F=91=E6=B6=88=E6=81=AF=E7=94=A8map?= =?UTF-8?q?=E5=AE=9E=E7=8E=B0=EF=BC=8C=E8=A7=A3=E5=86=B3=E8=B6=85=E5=A4=A7?= =?UTF-8?q?=E5=87=BD=E6=95=B0=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.h | 7 + .../dm_auth_message_processor.cpp | 155 +++++++----------- 2 files changed, 63 insertions(+), 99 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index f3a1337a3..9cf8204c5 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -188,6 +188,11 @@ 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 @@ -312,6 +317,8 @@ private: 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 diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 3f7a7cfe2..ed4410980 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -234,6 +234,51 @@ DmAuthMessageProcessor::DmAuthMessageProcessor() { LOGI("DmAuthMessageProcessor constructor"); cryptoMgr_ = std::make_shared(); + createMessageFuncMap_ = { + {DmMessageType::MSG_TYPE_REQ_ACL_NEGOTIATE, &DmAuthMessageProcessor::CreateNegotiateMessage}, + {DmMessageType::MSG_TYPE_RESP_ACL_NEGOTIATE, &DmAuthMessageProcessor::CreateRespNegotiateMessage}, + {DmMessageType::MSG_TYPE_REQ_USER_CONFIRM, &DmAuthMessageProcessor::CreateMessageReqUserConfirm}, + {DmMessageType::MSG_TYPE_RESP_USER_CONFIRM, &DmAuthMessageProcessor::CreateMessageRespUserConfirm}, + {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqPinAuthStart}, + {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::CreateMessageRespPinAuthStart}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, + &DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageReqCredExchange}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::CreateMessageRspCredExchange}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::CreateMessageReqCredAuthStart}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE, + &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE, + &DmAuthMessageProcessor::CreateCredentialNegotiateMessage}, + {DmMessageType::MSG_TYPE_REQ_DATA_SYNC, &DmAuthMessageProcessor::CreateSyncMessage}, + {DmMessageType::MSG_TYPE_RESP_DATA_SYNC, &DmAuthMessageProcessor::CreateMessageSyncResp}, + {DmMessageType::MSG_TYPE_AUTH_REQ_FINISH, &DmAuthMessageProcessor::CreateMessageFinish}, + {DmMessageType::MSG_TYPE_AUTH_RESP_FINISH, &DmAuthMessageProcessor::CreateMessageFinish}, + }; + paraseMessageFuncMap_ = { + {DmMessageType::MSG_TYPE_REQ_ACL_NEGOTIATE, &DmAuthMessageProcessor::ParseNegotiateMessage}, + {DmMessageType::MSG_TYPE_RESP_ACL_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageRespAclNegotiate}, + {DmMessageType::MSG_TYPE_REQ_USER_CONFIRM, &DmAuthMessageProcessor::ParseMessageReqUserConfirm}, + {DmMessageType::MSG_TYPE_RESP_USER_CONFIRM, &DmAuthMessageProcessor::ParseMessageRespUserConfirm}, + {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_START, &DmAuthMessageProcessor::ParseMessageReqPinAuthStart}, + {DmMessageType::MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_START, &DmAuthMessageProcessor::ParseMessageRespPinAuthStart}, + {DmMessageType::MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE, + &DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::ParseMessageReqCredExchange}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, &DmAuthMessageProcessor::ParseMessageRspCredExchange}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::ParseAuthStartMessage}, + {DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE, &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_START, &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, + {DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE, + &DmAuthMessageProcessor::ParseMessageNegotiateTransmit}, + {DmMessageType::MSG_TYPE_REQ_DATA_SYNC, &DmAuthMessageProcessor::ParseMessageSyncReq}, + {DmMessageType::MSG_TYPE_RESP_DATA_SYNC, &DmAuthMessageProcessor::ParseMessageSyncResp}, + {DmMessageType::MSG_TYPE_AUTH_REQ_FINISH, &DmAuthMessageProcessor::ParseMessageSinkFinish}, + {DmMessageType::MSG_TYPE_AUTH_RESP_FINISH, &DmAuthMessageProcessor::ParseMessageSrcFinish}, + }; LOGI("DmAuthMessageProcessor constructor leave."); } @@ -255,47 +300,12 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont DmMessageType msgType = static_cast(jsonObject[TAG_MSG_TYPE].Get()); context->msgType = msgType; LOGI("DmAuthMessageProcessor::ParseMessage message type %{public}d", context->msgType); - // TODO:调试信息,上库前删除 - LOGI("DmAuthMessageProcessor::ParseMessage %{public}s", jsonObject.Dump().c_str()); - switch (msgType) { - case MSG_TYPE_REQ_ACL_NEGOTIATE: - return ParseNegotiateMessage(jsonObject, context); - case MSG_TYPE_RESP_ACL_NEGOTIATE: - return ParseMessageRespAclNegotiate(jsonObject, context); - case MSG_TYPE_REQ_USER_CONFIRM: - return ParseMessageReqUserConfirm(jsonObject, context); - case MSG_TYPE_RESP_USER_CONFIRM: - return ParseMessageRespUserConfirm(jsonObject, context); - case MSG_TYPE_REQ_PIN_AUTH_START: - return ParseMessageReqPinAuthStart(jsonObject, context); - case MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE: - return ParseMessageReqPinAuthNegotiate(jsonObject, context); - case MSG_TYPE_RESP_PIN_AUTH_START: - return ParseMessageRespPinAuthStart(jsonObject, context); - case MSG_TYPE_REQ_CREDENTIAL_AUTH_START: // 160 - return ParseAuthStartMessage(jsonObject, context); - case MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE: // 161 - case MSG_TYPE_RESP_CREDENTIAL_AUTH_START: // 170 - case MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE: // 171 - return ParseMessageNegotiateTransmit(jsonObject, context); - case MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE: - return ParseMessageRespPinAuthNegotiate(jsonObject, context); - case MSG_TYPE_REQ_CREDENTIAL_EXCHANGE: - return ParseMessageReqCredExchange(jsonObject, context); - case MSG_TYPE_RESP_CREDENTIAL_EXCHANGE: - return ParseMessageRspCredExchange(jsonObject, context); - case MSG_TYPE_REQ_DATA_SYNC: - return ParseMessageSyncReq(jsonObject, context); - case MSG_TYPE_RESP_DATA_SYNC: - return ParseMessageSyncResp(jsonObject, context); - case MSG_TYPE_AUTH_REQ_FINISH: - return ParseMessageSinkFinish(jsonObject, context); - case MSG_TYPE_AUTH_RESP_FINISH: - return ParseMessageSrcFinish(jsonObject, context); - default: - break; + auto itr = paraseMessageFuncMap_.find(msgType); + if (itr == paraseMessageFuncMap_.end()) { + LOGI("DmAuthMessageProcessor::ParseMessage message type error %{public}d", context->msgType); + return ERR_DM_FAILED; } - return ERR_DM_FAILED; + return (this->*(itr->second))(jsonObject, context); } static std::vector stringToVector(const std::string& str) @@ -457,66 +467,13 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh LOGI("DmAuthMessageProcessor::CreateMessage start. msgType is %{public}d", msgType); JsonObject jsonObj; jsonObj[TAG_MSG_TYPE] = msgType; - switch (msgType) { - case MSG_TYPE_REQ_ACL_NEGOTIATE: - CreateNegotiateMessage(context, jsonObj); - break; - case MSG_TYPE_RESP_ACL_NEGOTIATE: - CreateRespNegotiateMessage(context, jsonObj); - break; - case MSG_TYPE_REQ_USER_CONFIRM: - CreateMessageReqUserConfirm(context, jsonObj); - break; - case MSG_TYPE_RESP_USER_CONFIRM: - CreateMessageRespUserConfirm(context, jsonObj); - break; - case MSG_TYPE_REQ_PIN_AUTH_START: - CreateMessageReqPinAuthStart(context, jsonObj); - break; - case MSG_TYPE_REQ_PIN_AUTH_MSG_NEGOTIATE: - CreateMessageReqPinAuthNegotiate(context, jsonObj); - break; - case MSG_TYPE_RESP_PIN_AUTH_START: - CreateMessageRespPinAuthStart(context, jsonObj); - break; - case MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE: - CreateMessageRespPinAuthNegotiate(context, jsonObj); - break; - case MSG_TYPE_REQ_CREDENTIAL_EXCHANGE: - CreateMessageReqCredExchange(context, jsonObj); - break; - case MSG_TYPE_RESP_CREDENTIAL_EXCHANGE: - CreateMessageRspCredExchange(context, jsonObj); - break; - case MSG_TYPE_REQ_CREDENTIAL_AUTH_START: - CreateMessageReqCredAuthStart(context, jsonObj); - break; - case MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE: // 161 - case MSG_TYPE_RESP_CREDENTIAL_AUTH_START: // 170 - case MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE: // 171 - if (CreateCredentialNegotiateMessage(context, jsonObj) != DM_OK) { - return ""; - } - break; - case MSG_TYPE_REQ_DATA_SYNC: - if (CreateSyncMessage(context, jsonObj)!= DM_OK) { - return ""; - } - break; - case MSG_TYPE_RESP_DATA_SYNC: - CreateMessageSyncResp(context, jsonObj); - break; - case MSG_TYPE_AUTH_REQ_FINISH: - case MSG_TYPE_AUTH_RESP_FINISH: - CreateMessageFinish(context, jsonObj); - break; - default: - LOGE("DmAuthMessageProcessor::CreateMessage msgType %{public}d error.", msgType); - break; + auto itr = createMessageFuncMap_.find(msgType); + if (itr == createMessageFuncMap_.end()) { + LOGE("DmAuthMessageProcessor::CreateMessage msgType %{public}d error.", msgType); + return ""; } - // TODO:调试信息,上库前删除 - LOGI("DmAuthMessageProcessor::CreateMessage %{public}s", jsonObj.Dump().c_str()); - return jsonObj.Dump(); + int32_t ret = (this->*(itr->second))(context, jsonObj); + return (ret == DM_OK) ? jsonObj.Dump() : ""; } // 内部各类报文的实现 -- Gitee From 929a46e9a478b8da19910f0128c50bf07d0a35bb Mon Sep 17 00:00:00 2001 From: ZHANGHE24 Date: Tue, 25 Mar 2025 14:36:47 +0000 Subject: [PATCH 291/382] !13 fix: state machine * fix: state machine --- .../authentication_v2/dm_auth_state_machine.h | 2 + .../dm_auth_state_machine.cpp | 172 +++++++++--------- 2 files changed, 91 insertions(+), 83 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state_machine.h b/services/implementation/include/authentication_v2/dm_auth_state_machine.h index 60af69c5f..349aa708d 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state_machine.h +++ b/services/implementation/include/authentication_v2/dm_auth_state_machine.h @@ -73,6 +73,8 @@ public: 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(); diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 96eef8073..7d8a907ac 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -19,27 +19,43 @@ #include "dm_auth_context.h" #include "dm_auth_state_machine.h" -#undef LOG_TAG -#define LOG_TAG "DHDM_V2" namespace OHOS { namespace DistributedHardware { -namespace { +DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) +{ + exceptionEvent_= { + DmEventType::ON_ERROR, // Authentication error, there is a possibility of retry. + DmEventType::ON_TIMEOUT, + DmEventType::ON_FAIL, // Authentication failed + DmEventType::ON_SCREEN_LOCKED, + }; -// 事件等待超时时间 -constexpr const int EVENT_TIMEOUT = 5000; // 5000 毫秒 = 5 秒 + running_ = true; + direction_ = context->direction; + if (direction_ == DM_AUTH_SOURCE) { + this->InsertSrcTransTable(); + } else { + this->InsertSinkTransTable(); + } + + this->SetCurState(DmAuthStateType::AUTH_IDLE_STATE); + thread_ = std::thread(&DmAuthStateMachine::Run, this, context); } +DmAuthStateMachine::~DmAuthStateMachine() +{ + Stop(); + thread_.join(); +}; -DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) +void DmAuthStateMachine::InsertSrcTransTable() { - stateTransitionTable_ = { - // 此处省略下一状态为AuthXXXFinishState的迁移情况 - {DmAuthStateType::AUTH_IDLE_STATE, - {DmAuthStateType::AUTH_SRC_START_STATE, DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, - // Source端 状态迁移表 + // Source-end state transition table + stateTransitionTable_.insert({ + {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SRC_START_STATE}}, {DmAuthStateType::AUTH_SRC_START_STATE, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE}}, {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE}}, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE, { @@ -71,26 +87,33 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, }}, {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, - {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, // 收到150的处理状态,发送160 + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, - {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE, // 收到170的处理状态,后发送161 + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE}}, - {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE, // 收到171的处理状态 发送160/180 + {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, - {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, // 收到190. 发送200报文 - {DmAuthStateType::AUTH_SRC_FINISH_STATE}}, - {DmAuthStateType::AUTH_SRC_FINISH_STATE, {}}, - // Sink端 状态迁移表 - //{DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, - //{DmAuthStateType::AUTH_SINK_START_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, + {DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, {DmAuthStateType::AUTH_SRC_FINISH_STATE}}, + + {DmAuthStateType::AUTH_SRC_FINISH_STATE, {}} + }); + + return; +} + +void DmAuthStateMachine::InsertSinkTransTable() +{ + // Sink-end state transition table + stateTransitionTable_.insert({ + {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE, { DmAuthStateType::AUTH_SINK_CONFIRM_STATE, DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, - DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE - }}, // to check + DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, + }}, {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, { DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, }}, @@ -115,39 +138,23 @@ DmAuthStateMachine::DmAuthStateMachine(std::shared_ptr context) DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, }}, {DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE}}, - {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, - {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, - - {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, // 收到160的处理状态,回复170 - {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, - - // 收到161的处理状态,回复171;发送171后收到160 回退到AUTH_SINK_CREDENTIAL_AUTH_START_STATE进行第二次凭据认证 + {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, { + DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, + }}, + {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, { + DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE, + }}, {DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE}}, - {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, {DmAuthStateType::AUTH_SINK_FINISH_STATE}}, // 收到180,回复190 - {DmAuthStateType::AUTH_SINK_FINISH_STATE, {}}, - }; - exceptionEvent_= { - DmEventType::ON_ERROR, // ERROR 错误 - DmEventType::ON_TIMEOUT, // 超时 - DmEventType::ON_FAIL, // 失败流程 - DmEventType::ON_SCREEN_LOCKED, // 锁屏 - }; - - running_ = true; - direction_ = context->direction; + {DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE, {DmAuthStateType::AUTH_SINK_FINISH_STATE}}, + {DmAuthStateType::AUTH_SINK_FINISH_STATE, {}} + }); - this->SetCurState(DmAuthStateType::AUTH_IDLE_STATE); - thread_ = std::thread(&DmAuthStateMachine::Run, this, context); + return; } -DmAuthStateMachine::~DmAuthStateMachine() -{ - Stop(); - thread_.join(); -}; -// 通知状态迁移,执行状态对应具体action与异常处理(只允许在OnDataReceived中调用) +// Notification status transition. The execution status corresponds to specific actions and exception handling. int32_t DmAuthStateMachine::TransitionTo(std::shared_ptr state) { int32_t ret = DM_OK; @@ -157,29 +164,31 @@ int32_t DmAuthStateMachine::TransitionTo(std::shared_ptr state) GetCurState(), nextState); { std::lock_guard lock(stateMutex_); - // 存入到队列中 statesQueue_.push(state); } stateCv_.notify_one(); } else { - // 切换状态不合法,打印错误日志并返回错误码 + // The state transition is invalid. LOGE("DmAuthStateMachine: The state transition does not meet the rule from %{public}d to %{public}d.", GetCurState(), nextState); - ret = ERR_DM_NEXT_STATE_INVALID; // 下一状态不合法错误码 + ret = ERR_DM_NEXT_STATE_INVALID; } return ret; } -// action内部的期望事件,用于阻塞,当等到期望事件完成或其他异常时,返回实际发生的事件,而其他正常事件则会继续阻塞(只允许在action中调用) +/* +Expected event in an action, which is used for blocking. +When the expected event is complete or other exceptions occur, the actual event is returned. +Other normal events continue to be blocked (only in the action). +*/ DmEventType DmAuthStateMachine::WaitExpectEvent(DmEventType eventType) { /* - 1、实际事件 = 期望事件,返回实际事件 - 2、实际事件 = 异常事件(事件超时等),同样返回实际事件 - 3、实际事件 = 其余事件,继续阻塞,但有个超时时间限制 + 1. Actual event = Expected event, return actual event + 2. Actual event = Abnormal event (event timeout). The actual event is also returned. + 3. Actual event = Other events, continue to block, but there is a timeout limit. */ std::unique_lock lock(eventMutex_); - // 记录进入函数的时间 auto startTime = std::chrono::high_resolution_clock::now(); while (running_.load()) { eventCv_.wait(lock, [&] { @@ -189,15 +198,13 @@ DmEventType DmAuthStateMachine::WaitExpectEvent(DmEventType eventType) return DmEventType::ON_FAIL; } - // 获取事件, 假设正常事件按序到达(状态机单线程按序等待) DmEventType actualEventType = eventQueue_.front(); eventQueue_.pop(); - // 判断是否是期望事件 + // Determine whether the event is an expected event or abnormal event in list. if (actualEventType == eventType || (exceptionEvent_.find(actualEventType) != exceptionEvent_.end())) { return actualEventType; } - // 做一个超时退出机制 - // 已经经过的时间 + // Event Wait Timeout auto elapsedTime = std::chrono::duration_cast( std::chrono::high_resolution_clock::now() - startTime); if (elapsedTime.count() >= EVENT_TIMEOUT) { @@ -207,12 +214,15 @@ DmEventType DmAuthStateMachine::WaitExpectEvent(DmEventType eventType) return DmEventType::ON_TIMEOUT; } -// 事件完成调用,传事件枚举(只允许在事件触发中调用),如果是异常事件,需在context的reason或者reply记录 +/* +The event is invoked after the event is complete. +The event enumeration can be invoked only when the event is triggered. +If the event is an abnormal event, the reason or reply of the context must be recorded. +*/ void DmAuthStateMachine::NotifyEventFinish(DmEventType eventType) { LOGI("DmAuthStateMachine: NotifyEventFinish Event:%{public}d.", eventType); { - // 添加事件到事件队列 std::unique_lock lock(eventMutex_); eventQueue_.push(eventType); } @@ -226,25 +236,19 @@ void DmAuthStateMachine::NotifyEventFinish(DmEventType eventType) } } -// 循环等待状态转移,执行action +// Cyclically wait for state transition and execute action. void DmAuthStateMachine::Run(std::shared_ptr context) { while (running_.load()) { auto state = FetchState(); - if (!state.has_value()) { - LOGI("DmAuthStateMachine::Run : No state to fetch."); - // 睡眠 100 毫秒 - std::this_thread::sleep_for(std::chrono::milliseconds(100)); - continue; - } - // 获取到状态,执行状态的action + // Obtain the status and execute the status action. DmAuthStateType stateType = state.value()->GetStateType(); this->SetCurState(stateType); int32_t ret = state.value()->Action(context); if (ret != DM_OK) { LOGE("DmAuthStateMachine::Run err:%{public}d", ret); if (context->reason == DM_OK) { - // 如果context的reason没有被设置,则设置为ret + // If the reason of the context is not set, set this parameter to ret. context->reason = ret; } if (context->direction == DM_AUTH_SOURCE) { @@ -252,12 +256,11 @@ void DmAuthStateMachine::Run(std::shared_ptr context) } else { this->TransitionTo(std::make_shared()); } - // finish需要,清理context以及重启状态机 } else { LOGI("DmAuthStateMachine::Run ok state:%{public}d", stateType); } } - LOGE("DmAuthStateMachine::Run end"); + LOGI("DmAuthStateMachine::Run end"); } std::optional> DmAuthStateMachine::FetchState() @@ -274,7 +277,6 @@ std::optional> DmAuthStateMachine::FetchState() return state; } -// 停止线程 void DmAuthStateMachine::Stop() { running_.store(false); @@ -282,21 +284,18 @@ void DmAuthStateMachine::Stop() eventCv_.notify_all(); } - -// 设置当前状态 void DmAuthStateMachine::SetCurState(DmAuthStateType state) { - LOGE("DmAuthStateMachine:: TODO LOGI SetCurState:%{public}d", state); + LOGD("DmAuthStateMachine::SetCurState state: %{public}d", state); curState_ = state; } -// 获取当前状态 DmAuthStateType DmAuthStateMachine::GetCurState() { return curState_; } -// 检验下一状态迁移合法性 +// Verify the validity of the next state transition. bool DmAuthStateMachine::CheckStateTransitValid(DmAuthStateType nextState) { if (curState_ == nextState || curState_ == DmAuthStateType::AUTH_SRC_FINISH_STATE || @@ -304,12 +303,19 @@ bool DmAuthStateMachine::CheckStateTransitValid(DmAuthStateType nextState) return false; } - // 判断下一状态是否为AuthXXXFinishState,可直接切状态,返回 + /* + Check whether the next state is AuthSrcFinishState or AuthSinkFinishState + which can directly switch to the state and return. + */ if (nextState == DmAuthStateType::AUTH_SRC_FINISH_STATE || nextState == DmAuthStateType::AUTH_SINK_FINISH_STATE) { return true; } - // 判断是否符合状态迁移表 - auto it = stateTransitionTable_.find(curState_); + // Check whether the state transition table is met. + DmAuthStateType state = curState_; + if (!statesQueue_.empty()) { + state = statesQueue_.back()->GetStateType(); + } + auto it = stateTransitionTable_.find(state); if (it != stateTransitionTable_.end()) { const std::set& allowedStates = it->second; return allowedStates.find(nextState) != allowedStates.end(); -- Gitee From e6ff992bed3340b71ea8e2f467c43f70a5f2c1bd Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Wed, 26 Mar 2025 14:47:24 +0800 Subject: [PATCH 292/382] =?UTF-8?q?fix=EF=BC=9A190bug=E5=87=AD=E6=8D=AEid?= =?UTF-8?q?=E8=BD=ACint=E4=BC=9A=E6=BA=A2=E5=87=BA=E5=A4=B1=E8=B4=A5?= =?UTF-8?q?=EF=BC=8C=E6=9A=82=E6=97=B6=E4=B8=8D=E5=86=99=E5=85=A5pskid?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth_stages/auth_credential.cpp | 37 +++++++------------ .../dm_auth_message_processor.cpp | 26 ++++++------- 2 files changed, 26 insertions(+), 37 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 28bc97258..fbd69cafe 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -32,11 +32,6 @@ namespace DistributedHardware { namespace { -const char * const FILED_DEVICE_ID = "deviceId"; - -// 从context中提取transmit data,使用SK解密,并透传给HICHAIN -// 如果ontransmit事件,在对应回调解析并保存在context -// 如果onsessionkeyreturned事件,在对应回调解析并保存在cryptomgr int32_t AuthCredentialTransmitDecryptProcess(std::shared_ptr context, DmEventType event) { if (context->transmitData.empty()) { @@ -44,13 +39,12 @@ int32_t AuthCredentialTransmitDecryptProcess(std::shared_ptr cont return ERR_DM_FAILED; } - // 透传给hichain int32_t ret = context->hiChainAuthConnector->ProcessCredData(context->requestId, context->transmitData); if (ret != DM_OK) { LOGE("AuthCredentialTransmitDecryptProcess: ProcessCredData transmit data failed"); return ERR_DM_FAILED; } - // 等待hichain返回结果 + if (context->authStateMachine->WaitExpectEvent(event) != event) { LOGE("AuthCredentialTransmitDecryptProcess: Hichain auth transmit data failed"); return ERR_DM_FAILED; @@ -58,22 +52,20 @@ int32_t AuthCredentialTransmitDecryptProcess(std::shared_ptr cont return DM_OK; } -// 解析HICHAIN transmit data,并透传给对端 int32_t AuthCredentialTransmitSend(std::shared_ptr context, DmMessageType msgType) { - // 获取transmit data if (context->transmitData.empty()) { LOGE("AuthCredentialTransmitSend: Get onTransmitData failed."); return ERR_DM_FAILED; } std::string message = - context->authMessageProcessor->CreateMessage(msgType, context); // 不需要额外传data,context中均有 + context->authMessageProcessor->CreateMessage(msgType, context); if (message.empty()) { LOGE("AuthCredentialTransmitSend: CreateMessage AuthCredential transmit data failed"); return ERR_DM_FAILED; } - // 发送报文 + return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); } @@ -91,15 +83,16 @@ DmAuthStateType AuthSrcCredentialAuthNegotiateState::GetStateType() { return DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE; } -// 收到170凭据认证报文,解析ontransmit,回复161报文 + +// parse the ontransmit data, respond with 161 message int32_t AuthSrcCredentialAuthNegotiateState::Action(std::shared_ptr context) { - // 解密并透传transmitData + // decrypt and transmit transmitData int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_TRANSMIT); if (ret != DM_OK) { return ret; } - // 发送161报文 + // send 161 message return AuthCredentialTransmitSend(context, DmMessageType::MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE); } @@ -108,18 +101,15 @@ DmAuthStateType AuthSrcCredentialAuthDoneState::GetStateType() return DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_DONE_STATE; } -// 收到171凭据认证报文 int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr context) { - // 解密并透传transmitData - // 171报文在首次认证情况下会发生两次,先进行应用凭据认证,后进行用户凭据认证;非首次认证仅进行应用凭据认证 - // 最后一次认证结束后会收到ON_FINISH + // decrypt and transmit transmitData int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_SESSION_KEY_RETURNED); if (ret != DM_OK) { return ret; } - // 认证结束触发Onfinish回调事件 + // Authentication completion triggers the Onfinish callback event. if (context->authStateMachine->WaitExpectEvent(ON_FINISH) != ON_FINISH) { LOGE("AuthSrcCredentialAuthDoneState::Action Hichain auth SINK transmit data failed"); return ERR_DM_FAILED; @@ -131,13 +121,12 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co LOGE("AuthSrcCredentialAuthDoneState::Action DP save user session key failed"); return ret; } - // 首次认证 且 应用凭据流程 + + // first time joinLnn, auth lnnCredential if (context->isOnline == false && context->isAppCredentialVerified == false) { context->isAppCredentialVerified = true; - // 保存到DP 获取应用凭据ID 并保存 SetAuthContext(skId, context->accesser.transmitSkTimeStamp, context->accesser.transmitSessionKeyId); - msgType = MSG_TYPE_REQ_CREDENTIAL_AUTH_START; // 发送160 - // 认证用户凭据 + msgType = MSG_TYPE_REQ_CREDENTIAL_AUTH_START; ret = context->hiChainAuthConnector->AuthCredential(context->accesser.userId, context->requestId, context->accesser.lnnCredentialId, std::string("")); if (ret != DM_OK) { @@ -145,7 +134,7 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co return ret; } - // 等待onTransmit事件 + // wait for onTransmit event if (context->authStateMachine->WaitExpectEvent(ON_TRANSMIT) != ON_TRANSMIT) { LOGE("AuthSrcCredentialAuthDoneState::Action failed, ON_TRANSMIT event not arrived."); return ERR_DM_FAILED; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index ed4410980..e9ddc8500 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -65,9 +65,10 @@ void ParseNegotiateExtraInfoMessage(const JsonItemObject &jsonExtraObject, std:: return; } -void ParseDmAccessToSync(const JsonItemObject &jsonObject, DmAccess &access) +void ParseDmAccessToSync(const std::string &jsonString, DmAccess &access) { - DmAccessToSync srcAccessToSync = jsonObject.Get(); + JsonObject accessjson(jsonString); + DmAccessToSync srcAccessToSync = accessjson.Get(); access.deviceName = srcAccessToSync.deviceName; access.deviceId = srcAccessToSync.deviceId; access.userId = srcAccessToSync.userId; @@ -80,8 +81,9 @@ void ParseDmAccessToSync(const JsonItemObject &jsonObject, DmAccess &access) return; } -int32_t ParaseAclChecksumList(const JsonItemObject &aclChecksumjson, DmAccess &access) +int32_t ParaseAclChecksumList(const std::string &jsonString, DmAccess &access) { + JsonObject aclChecksumjson(jsonString); if (aclChecksumjson.IsDiscarded()) { LOGE("ParseSyncMessage aclChecksumjson error"); return ERR_DM_FAILED; @@ -96,7 +98,6 @@ int32_t ParaseAclChecksumList(const JsonItemObject &aclChecksumjson, DmAccess &a return ERR_DM_FAILED; } aclChecksumjson[DM_TAG_ACCESSEE].Get(access.accesseeStrList); - return DM_OK; } @@ -165,7 +166,7 @@ void DmAuthMessageProcessor::SetTransmitAccessControlList(std::shared_ptraccesser.tokenId); accesser.SetAccesserBundleName(context->accesser.bundleName); accesser.SetAccesserDeviceName(context->accesser.deviceName); - accesser.SetAccesserCredentialId(stoi(context->accesser.transmitCredentialId)); + // accesser.SetAccesserCredentialId(stoi(context->accesser.transmitCredentialId)); accesser.SetAccesserSessionKeyId(context->accesser.transmitSessionKeyId); accesser.SetAccesserSKTimeStamp(context->accesser.transmitSkTimeStamp); accessee.SetAccesseeDeviceId(context->accessee.deviceId); @@ -174,7 +175,7 @@ void DmAuthMessageProcessor::SetTransmitAccessControlList(std::shared_ptraccessee.tokenId); accessee.SetAccesseeBundleName(context->accessee.bundleName); accessee.SetAccesseeDeviceName(context->accessee.deviceName); - accessee.SetAccesseeCredentialId(stoi(context->accessee.transmitCredentialId)); + // accessee.SetAccesseeCredentialId(stoi(context->accessee.transmitCredentialId)); accessee.SetAccesseeSessionKeyId(context->accessee.transmitSessionKeyId); accessee.SetAccesseeSKTimeStamp(context->accessee.transmitSkTimeStamp); } @@ -187,7 +188,7 @@ void DmAuthMessageProcessor::SetLnnAccessControlList(std::shared_ptraccesser.accountId); accesser.SetAccesserTokenId(0); accesser.SetAccesserDeviceName(context->accesser.deviceName); - accesser.SetAccesserCredentialId(stoi(context->accesser.lnnCredentialId)); + // accesser.SetAccesserCredentialId(stoi(context->accesser.lnnCredentialId)); accesser.SetAccesserSessionKeyId(context->accesser.lnnSessionKeyId); accesser.SetAccesserSKTimeStamp(context->accesser.lnnSkTimeStamp); accessee.SetAccesseeDeviceId(context->accessee.deviceId); @@ -195,7 +196,7 @@ void DmAuthMessageProcessor::SetLnnAccessControlList(std::shared_ptraccessee.accountId); accessee.SetAccesseeTokenId(0); accessee.SetAccesseeDeviceName(context->accessee.deviceName); - accessee.SetAccesseeCredentialId(stoi(context->accessee.lnnCredentialId)); + // accessee.SetAccesseeCredentialId(stoi(context->accessee.lnnCredentialId)); accessee.SetAccesseeSessionKeyId(context->accessee.lnnSessionKeyId); accessee.SetAccesseeSKTimeStamp(context->accessee.lnnSkTimeStamp); } @@ -691,8 +692,7 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr } std::string srcAccessStr = jsonObject[DM_TAG_ACCESS].Get(); // 解析到 access里面 - JsonObject accessjson(srcAccessStr); - ParseDmAccessToSync(accessjson, access); + ParseDmAccessToSync(srcAccessStr, access); if (jsonObject[DM_TAG_PROXY].IsString()) { // 预留字段 std::string proxyInfo = jsonObject[DM_TAG_PROXY].Get(); } @@ -704,11 +704,11 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr return ERR_DM_FAILED; } std::string aclChecksumList = jsonObject[DM_TAG_ACL_CHECKSUM].Get(); - JsonObject aclChecksumjson(aclChecksumList); - return ParaseAclChecksumList(aclChecksumjson, access); + return ParaseAclChecksumList(aclChecksumList, access); } -int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptr &context, +int32_t DmAuthMessageProcessor:: +DecryptSyncMessage(std::shared_ptr &context, DmAccess &access, std::string &enSyncMsg) { // 解密整个字段 -- Gitee From e6ff6091836e1436975f5cf4a09caf61c3bc3e30 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Wed, 26 Mar 2025 16:05:51 +0800 Subject: [PATCH 293/382] =?UTF-8?q?=E6=B7=BB=E5=8A=A0=E5=9B=9E=E8=B0=83?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../include/authentication_v2/dm_auth_state.h | 1 + .../src/authentication_v2/dm_auth_state.cpp | 22 +++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 4f6dfd220..946e96d05 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -110,6 +110,7 @@ public: std::string credId, int32_t sessionKeyId, int32_t aclId); void SourceFinish(std::shared_ptr context); void SinkFinish(std::shared_ptr context); + std::string GenerateBindResultContent(DmAccess &access); 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); diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 4aa71c958..10162a9ea 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -18,6 +18,7 @@ #include "dm_auth_manager_base.h" #include "dm_auth_state_machine.h" #include "multiple_user_connector.h" +#include "dm_crypto.h" #if defined(SUPPORT_SCREENLOCK) #include "screenlock_manager.h" #endif @@ -94,6 +95,10 @@ void DmAuthState::SyncAclList(std::shared_ptr context, void DmAuthState::SourceFinish(std::shared_ptr context) { + context->listener->OnAuthResult(context->processInfo, context->peerTargetId.deviceId, context->token, + context->state, context->reason); + context->listener->OnBindResult(context->processInfo, context->peerTargetId, context->reply, + context->state, GenerateBindResultContent(context->accessee)); context->isFinished = true; if (context->reason != DM_OK) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); @@ -115,6 +120,8 @@ void DmAuthState::SourceFinish(std::shared_ptr context) void DmAuthState::SinkFinish(std::shared_ptr context) { + context->listener->OnSinkBindResult(context->processInfo, context->peerTargetId, context->reply, + context->state, GenerateBindResultContent(context->accesser)); context->isFinished = true; if (context->reason != DM_OK) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); @@ -136,5 +143,20 @@ void DmAuthState::SinkFinish(std::shared_ptr context) context->timer->DeleteAll(); context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_RESP_FINISH, context); // 发送201给source侧 } + +std::string DmAuthState::GenerateBindResultContent(DmAccess &access) +{ + JsonObject jsonObj; + jsonObj[DM_BIND_RESULT_NETWORK_ID] = access.networkId; + if (access.deviceId.empty()) { + jsonObj[TAG_DEVICE_ID] = ""; + } else { + char deviceIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + Crypto::GetUdidHash(access.deviceId, reinterpret_cast(deviceIdHash)); + jsonObj[TAG_DEVICE_ID] = deviceIdHash; + } + std::string content = jsonObj.Dump(); + return content; +} } // namespace DistributedHardware } // namespace OHOS -- Gitee From 55335b36be69bb84bb819069bed26256ce6e5c9b Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Wed, 26 Mar 2025 17:06:04 +0800 Subject: [PATCH 294/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9=E5=BC=82=E5=B8=B8?= =?UTF-8?q?=E6=97=B6=E8=B7=B3=E8=BD=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../src/authentication_v2/auth_stages/auth_acl.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 0ad02acc7..c383ea1b1 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -54,7 +54,8 @@ int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) context->reply = ERR_DM_QUADRUPLE_NOT_SAME; context->reason = ERR_DM_QUADRUPLE_NOT_SAME; context->state = static_cast(GetStateType()); - SinkFinish(context); // sink端异常时,sink结束,清理凭据,skid,停止计时器,发送201给source + // sink端异常时,sink结束,清理凭据,skid,停止计时器,发送201给source + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } // 查询sink端acl -- Gitee From 00c6f41a06cc769e52705f9dcfe2b56480857b95 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Wed, 26 Mar 2025 20:59:00 +0800 Subject: [PATCH 295/382] =?UTF-8?q?test:=20=E5=A4=84=E7=90=86=E5=87=AD?= =?UTF-8?q?=E6=8D=AE=E8=B7=B3=E8=BD=AC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/auth_manager.h | 14 -- .../authentication_v2/dm_auth_context.h | 7 +- .../authentication_v2/dm_auth_manager_base.h | 1 + .../dm_auth_message_processor.h | 1 + .../include/authentication_v2/dm_auth_state.h | 15 +- .../auth_stages/auth_acl.cpp | 2 +- .../auth_stages/auth_confirm.cpp | 108 +++++++++ .../auth_stages/auth_negotiate.cpp | 162 ------------- .../auth_stages/auth_pin_auth.cpp | 5 + .../dm_auth_manager_base.cpp | 1 + .../dm_auth_message_processor.cpp | 38 ++- .../src/authentication_v2/dm_auth_state.cpp | 229 ++++++++++++++++++ .../dm_auth_state_machine.cpp | 2 +- 13 files changed, 394 insertions(+), 191 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index f7d6f7a29..18ea5206d 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -29,20 +29,6 @@ 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: diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 15df14b5b..82d96993d 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -25,6 +25,7 @@ #include "softbus_connector.h" #include "softbus_session.h" #include "authentication.h" +#include "access_control_profile.h" #include "dm_timer.h" #include "dm_auth_message_processor.h" @@ -136,7 +137,10 @@ struct DmAccess { 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::map credentialInfos; // map: , cred is string tranformed by json + // map: + std::map aclProfiles; + std::vector credentialTypeLists; // point-to-point, same account, etc. std::string extraInfo; // Expandable field, JSON format, KV structure std::string openAuthDeviceId; }; @@ -200,6 +204,7 @@ struct DmAuthContext { PeerTargetId peerTargetId; bool pinNegotiateStarted{false}; bool isAuthenticateDevice{false}; // Whether device authentication is in progress + bool needAgreeCredential{true}; std::string GetDeviceId(DmAuthSide side); int32_t GetUserId(DmAuthSide side); diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h b/services/implementation/include/authentication_v2/dm_auth_manager_base.h index 41040630b..490417553 100644 --- a/services/implementation/include/authentication_v2/dm_auth_manager_base.h +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h @@ -75,6 +75,7 @@ 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 EVENT_TIMEOUT; extern const int32_t DM_AUTH_TYPE_MAX; extern const int32_t DM_AUTH_TYPE_MIN; diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 9cf8204c5..13e4e53cb 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -93,6 +93,7 @@ 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"; +constexpr const char* TAG_CERT_INFO = "certInfo"; // Accesser table content is used for ACL synchronization. constexpr const char* DM_TAG_ACCESSER_DEVICE_ID = "accesserDeviceId"; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 946e96d05..cb2937745 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -115,6 +115,11 @@ public: 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: + int32_t GetAuthCredentialInfo(std::shared_ptr context); + int32_t NeedReqUserConfirm(std::shared_ptr context); + int32_t NeedPinAuth(std::shared_ptr context); + int32_t NeedAgreeCredential(std::shared_ptr context); + int32_t NeedAgreeAcl(std::shared_ptr context); }; class AuthSrcConfirmState : public DmAuthState { @@ -123,6 +128,9 @@ public: DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; private: + void NegotiateCredential(std::shared_ptr context); + void NegotiateAcl(std::shared_ptr context); + int32_t NoNeedAction(std::shared_ptr context); int32_t DoPinAuth(std::shared_ptr context); }; @@ -140,6 +148,8 @@ public: DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; private: + void NegotiateCredential(std::shared_ptr context); + void NegotiateAcl(std::shared_ptr context); int32_t ShowConfigDialog(std::shared_ptr context); }; @@ -324,12 +334,7 @@ public: 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); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index c383ea1b1..28be628b1 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -152,7 +152,7 @@ int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) } std::string peerUdidHash = std::string(udidHashTmp); context->softbusConnector->JoinLNNBySkId(context->sessionId, context->accesser.transmitSessionKeyId, - context->accessee.transmitSessionKeyId, context->accessee.addr, peerUdidHash); + context->accessee.transmitSessionKeyId, context->accessee.addr, peerUdidHash); } context->reason = DM_OK; context->reply = DM_OK; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 570b3af30..0f85429be 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -14,6 +14,7 @@ */ #include "auth_manager.h" +#include "access_control_profile.h" #include "deviceprofile_connector.h" #include "dm_anonymous.h" #include "dm_auth_context.h" @@ -72,6 +73,51 @@ int32_t AuthSrcConfirmState::DoPinAuth(std::shared_ptr context) return DM_OK; } +void AuthSrcConfirmState::NegotiateCredential(std::shared_ptr context) +{ + std::vector srcCredTypeList = context->accesser.credentialTypeLists; + std::vector sinkCredTypeList = context->accessee.credentialTypeLists; + + std::sort(srcCredTypeList.begin(), srcCredTypeList.end()); + std::sort(sinkCredTypeList.begin(), sinkCredTypeList.end()); + + // 使用 set_intersection 找出交集 + std::vector intersection; + std::set_intersection(srcCredTypeList.begin(), srcCredTypeList.end(), + sinkCredTypeList.begin(), sinkCredTypeList.end(), std::back_inserter(intersection)); + + // TODO: 添加配件判断 + if (!intersection.empty()) { + // 如果交集不为空,将第一个值赋值给 context->accesser.credTypeList + // TODO: 确认优先级是否正确 + // TODO: 需确认凭据id + JsonObject credInfo(context->accesser.credentialInfos[intersection.front()]); + if (credInfo.Contains("id") && credInfo["id"].IsString()) { + context->accesser.credentialTypeLists.clear(); + context->accesser.credentialTypeLists.push_back(intersection.front()); + context->needAgreeCredential = false; + context->accessee.transmitCredentialId = credInfo["id"].Get(); + } + } + + return; +} + +void AuthSrcConfirmState::NegotiateAcl(std::shared_ptr context) +{ + if (!context->accesser.isAuthed || context->accesser.credentialTypeLists.size() != 1) { + return; + } + int32_t credType = context->accesser.credentialTypeLists.front(); + + DistributedDeviceProfile::Accesser accesser = context->accesser.aclProfiles[credType].GetAccesser(); + DistributedDeviceProfile::Accessee accessee = context->accesser.aclProfiles[credType].GetAccessee(); + context->accesser.transmitSessionKeyId = accesser.GetAccesserSessionKeyId(); + context->accessee.transmitSessionKeyId = accessee.GetAccesseeSessionKeyId(); + + return; +} + int32_t AuthSrcConfirmState::Action(std::shared_ptr context) { LOGI("AuthSrcConfirmState::Action start"); @@ -84,6 +130,21 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) return ERR_DM_VERSION_INCOMPATIBLE; } + int32_t ret = GetAuthCredentialInfo(context); + if (ret != DM_OK) { + LOGE("AuthSrcConfirmState::Action GetAuthCredentialInfo failed"); + return false; + } + + NegotiateCredential(context); + NegotiateAcl(context); + + // if (!NeedReqUserConfirm(context)) { + // context->authStateMachine->TransitionTo(std::make_shared()); + // LOGI("AuthSrcConfirmState::Action no need action"); + // return DM_OK; + // } + // no credential, try to do pin auth return DoPinAuth(context); } @@ -118,11 +179,58 @@ int32_t AuthSinkConfirmState::ShowConfigDialog(std::shared_ptr co return DM_OK; } +void AuthSinkConfirmState::NegotiateCredential(std::shared_ptr context) +{ + if (context->accesser.credentialTypeLists.size() != 1) { + return; + } + + int32_t credType = context->accesser.credentialTypeLists.front(); + std::vector sinkCredTypeLists = context->accessee.credentialTypeLists; + if (std::find(sinkCredTypeLists.begin(), sinkCredTypeLists.end(), credType) == sinkCredTypeLists.end()) { + LOGI("AuthSinkConfirmState::NegotiateCredential credType %{public}d not found in sink", credType); + return; + } + + JsonObject credInfo(context->accessee.credentialInfos[credType]); + if (credInfo.Contains("id") && credInfo["id"].IsString()) { + sinkCredTypeLists.clear(); + sinkCredTypeLists.push_back(credType); + context->accessee.transmitCredentialId = credInfo["id"].Get(); + } + + return; +} + +void AuthSinkConfirmState::NegotiateAcl(std::shared_ptr context) +{ + if (!context->accesser.isAuthed || !context->accessee.isAuthed || + context->accessee.credentialTypeLists.size() != 1) { + return; + } + + int32_t credType = context->accessee.credentialTypeLists.front(); + if (context->accessee.aclProfiles.find(credType) == context->accessee.aclProfiles.end()) { + context->accessee.isAuthed = false; + return; + } + + DistributedDeviceProfile::Accesser accesser = context->accesser.aclProfiles[credType].GetAccesser(); + DistributedDeviceProfile::Accessee accessee = context->accesser.aclProfiles[credType].GetAccessee(); + context->accesser.transmitSessionKeyId = accesser.GetAccesserSessionKeyId(); + context->accessee.transmitSessionKeyId = accessee.GetAccesseeSessionKeyId(); + + return; +} + int32_t AuthSinkConfirmState::Action(std::shared_ptr context) { LOGI("AuthSinkConfirmState::Action start"); context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); + NegotiateCredential(context); + NegotiateAcl(context); + if (context->authTypeList.empty()) { LOGE("AuthSinkConfirmState::Action authTypeList empty"); context->reason = ERR_DM_UNSUPPORTED_AUTH_TYPE; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index e99941dd9..afcf7130e 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -56,15 +56,6 @@ static std::map g_pinAuthTypeFallBackMap = { // Maximum number of recursive lookups constexpr size_t MAX_FALLBACK_LOOPKUP_TIMES = 2; -// Security device auth credential query related definitions, keep consistent with device_auth.h -const char * const FILED_DEVICE_ID = "deviceId"; -const char * const FILED_DEVICE_ID_HASH = "deviceIdHash"; -const char * const FILED_USER_ID = "userId"; -const char * const FILED_PEER_USER_SPACE_ID = "peerUserSpaceId"; -const char * const FILED_CRED_TYPE = "credType"; -const char * const FILED_AUTHORIZED_APP_LIST = "authorizedAppList"; -const char * const FILED_AUTHORIZED_SCOPE = "authorizedScope"; - enum DmRole { DM_ROLE_UNKNOWN = 0, DM_ROLE_FA_TO_FA, @@ -74,83 +65,6 @@ enum DmRole { DM_ROLE_FA_TO_DEVICE }; -bool HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList) -{ - // Store the token of src and sink. The size must be 2. - if (tokenList.size() != 2) { - LOGE("HaveSameTokenId invalid tokenList size."); - return false; - } - - // tokenIdList = [srcTokenId, sinkTokenId] - std::string srcTokenIdHash = Crypto::Sha256(tokenList[0]); - std::string sinkTokenIdHash = Crypto::Sha256(tokenList[1]); - - return (srcTokenIdHash == context->accesser.tokenIdHash) && - (sinkTokenIdHash == context->accessee.tokenIdHash); -} - -uint32_t GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo) -{ - if (!credInfo[FILED_CRED_TYPE].IsNumberInteger() || !credInfo[FILED_AUTHORIZED_SCOPE].IsNumber()) { - return DM_INVALIED_BINDTYPE; - } - - int32_t credType = credInfo[FILED_CRED_TYPE].Get(); - int32_t authorizedScope = credInfo[FILED_AUTHORIZED_SCOPE].Get(); - if (authorizedScope == SCOPE_USER) { - if (credType == ACCOUNT_RELATED) { - return DM_IDENTICAL_ACCOUNT; - } else if (credType == ACCOUNT_ACROSS) { - return DM_ACROSS_ACCOUNT; - } - } - - std::vector appList; - credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList); - if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_APP && HaveSameTokenId(context, appList)) { - return DM_POINT_TO_POINT; - } - - // 未确定凭据类型 - return DM_INVALIED_BINDTYPE; -} - -int32_t DmQueryCredential(std::shared_ptr context, JsonObject &queryResult) -{ - int32_t ret; - uint32_t credType; - JsonObject queryParams; - - DmAccess access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; - DmAccess remoteAccess = context->direction == DM_AUTH_SOURCE ? context->accessee : context->accesser; - - queryParams[FILED_DEVICE_ID_HASH] = remoteAccess.deviceId; - queryParams[FILED_USER_ID] = access.userId; - queryParams[FILED_PEER_USER_SPACE_ID] = remoteAccess.userId; - ret = context->hiChainAuthConnector->QueryCredentialInfo(access.userId, queryParams, queryResult); - if (ret != DM_OK) { - LOGE("DmQueryCredential fail to query credential id list."); - return ret; - } - // TODO: delete - LOGI("DmQueryCredential for userId %{public}d and queryParams %{public}s " - "query credentialInfo: %{public}s", access.userId, queryParams.Dump().c_str(), - queryResult.Dump().c_str()); - - for (auto& item : queryResult.Items()) { - // 确认凭据类型 - credType = GetCredentialType(context, item); - if (credType == DM_INVALIED_BINDTYPE) { - continue; - } - - item[FILED_CRED_TYPE] = credType; - } - - return DM_OK; -} - } DmAuthStateType AuthSrcStartState::GetStateType() @@ -278,82 +192,6 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptr context, - const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) -{ - return Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash && - Crypto::Sha256(std::to_string(accesser.GetAccesserUserId())) == context->accesser.userIdHash && - Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash && - Crypto::Sha256(std::to_string(accessee.GetAccesseeUserId())) == context->accessee.userIdHash; -} - -// Compares hashs of the device IDs, user IDs, account IDs, and token IDs -bool AuthSinkNegotiateStateMachine::AclCompareFourIds(std::shared_ptr context, - const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) -{ - return AclCompareTwoIds(context, accesser, accessee) && - Crypto::Sha256(accesser.GetAccesserAccountId()) == context->accesser.accountIdHash && - Crypto::Sha256(std::to_string(accesser.GetAccesserTokenId())) == context->accesser.tokenIdHash && - Crypto::Sha256(accessee.GetAccesseeAccountId()) == context->accessee.accountIdHash && - Crypto::Sha256(std::to_string(accessee.GetAccesseeTokenId())) == context->accessee.tokenIdHash; -} - -int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptr context) -{ - int32_t ret; - JsonObject queryResult; - JsonObject packResult; // Data to be packed and sent to the peer - - // 1. Retrieve all credentials - ret = DmQueryCredential(context, queryResult); - if (ret != DM_OK) { - LOGE("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo fail to query credential"); - return ret; - } - - // 2. Retrieve all ACLs - std::vector profiles = - DeviceProfileConnector::GetInstance().GetAccessControlProfile(); - for (const auto &item : profiles) { - bool isAclMatched = false; - auto accesser = item.GetAccesser(); - auto accessee = item.GetAccessee(); - - // TODO: delete - LOGD("Got acl: credId - %{public}d ", accessee.GetAccesseeCredentialId()); - LOGD("accesser: deviceId - %{public}s, userId - %{public}d, accountId - %{public}s, tokenId - %{public}ld", - accesser.GetAccesserDeviceId().c_str(), accesser.GetAccesserUserId(), - accesser.GetAccesserAccountId().c_str(), accesser.GetAccesserTokenId()); - LOGD("accessee: deviceId - %{public}s, userId - %{public}d, accountId - %{public}s, tokenId - %{public}ld", - accessee.GetAccesseeDeviceId().c_str(), accessee.GetAccesseeUserId(), - accessee.GetAccesseeAccountId().c_str(), accessee.GetAccesseeTokenId()); - - // Ensure credentials match with ACL - std::string credId = std::to_string(accessee.GetAccesseeCredentialId()); - if (!queryResult.Contains(credId) || item.GetStatus() != ACTIVE) { - continue; - } - - // Confirm if there is a trusted relationship - uint32_t credType = queryResult[credId][FILED_CRED_TYPE].Get(); - if (credType == DM_IDENTICAL_ACCOUNT || credType == DM_ACROSS_ACCOUNT) { - isAclMatched = AclCompareTwoIds(context, accesser, accessee); - } else if (credType == DM_POINT_TO_POINT) { - isAclMatched = AclCompareFourIds(context, accesser, accessee); - } - - if (isAclMatched) { - packResult[credId] = credType; - LOGI("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo success to get credType %{public}d", credType); - } - } - - context->accessee.credentialInfos = packResult.Dump(); - - return DM_OK; -} - int32_t AuthSinkNegotiateStateMachine::ProcRespNegotiate5_1_0(std::shared_ptr context) { int32_t ret = RespQueryAcceseeIds(context); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index bc6a91bdf..1bc706d70 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -284,6 +284,11 @@ DmAuthStateType AuthSrcPinNegotiateStartState::GetStateType() int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr context) { + // if (!NeedPinAuth(context)) { + // context->authStateMachine->TransitionTo(std::make_shared()); + // return DM_OK; + // } + if (!context->pinNegotiateStarted) { context->pinNegotiateStarted = true; context->timer->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp index 9014006bb..c161a951b 100644 --- a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp @@ -74,6 +74,7 @@ const int32_t CLONE_PIN_AUTH_TIMEOUT = 10; const int32_t HML_SESSION_TIMEOUT = 10; const int32_t SESSION_HEARTBEAT_TIMEOUT = 50; const int32_t PIN_AUTH_TIMEOUT = 60; +const int32_t EVENT_TIMEOUT = 5000; // 5000 ms int32_t AuthManagerBase::AuthenticateDevice(const std::string &pkgName, int32_t authType, diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index e9ddc8500..e97acb0c4 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -309,7 +309,7 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont return (this->*(itr->second))(jsonObject, context); } -static std::vector stringToVector(const std::string& str) +static std::vector stringToVectorAuthType(const std::string& str) { std::vector vec; std::istringstream iss(str); @@ -320,7 +320,30 @@ static std::vector stringToVector(const std::string& str) return vec; } -static std::string vectorToString(const std::vector& vec) +static std::vector stringToVectorInt32(const std::string& str) +{ + std::vector vec; + std::istringstream iss(str); + int32_t num; + while (iss >> num) { + vec.push_back(static_cast(num)); + } + return vec; +} + +static std::string vectorAuthTypeToString(const std::vector& vec) +{ + std::ostringstream oss; + for (size_t i = 0; i < vec.size(); ++i) { + oss << static_cast(vec[i]); + if (i != vec.size() - 1) { + oss << " "; // 添加分隔符(例如空格) + } + } + return oss.str(); +} + +static std::string vectorInt32ToString(const std::vector& vec) { std::ostringstream oss; for (size_t i = 0; i < vec.size(); ++i) { @@ -331,6 +354,7 @@ static std::string vectorToString(const std::vector& vec) } return oss.str(); } + int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const JsonObject &jsonObject, std::shared_ptr context) { @@ -528,9 +552,9 @@ int32_t DmAuthMessageProcessor::CreateRespNegotiateMessage(std::shared_ptraccessee.bundleName; jsonObject[TAG_IS_ONLINE] = context->isOnline; jsonObject[TAG_IS_AUTHED] = context->accessee.isAuthed; - jsonObject[TAG_CREDENTIAL_INFO] = context->accessee.credentialInfos; + jsonObject[TAG_CERT_INFO] = vectorInt32ToString(context->accessee.credentialTypeLists); - jsonObject[DM_TAG_AUTH_TYPE_LIST] = vectorToString(context->authTypeList); + jsonObject[DM_TAG_AUTH_TYPE_LIST] = vectorAuthTypeToString(context->authTypeList); if (context->authResultReady) { jsonObject[DM_TAG_AUTH_RESULT] = context->authResult; } @@ -924,13 +948,13 @@ int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const JsonObject &j context->accessee.isAuthed = jsonObject[TAG_IS_AUTHED].Get(); } - if (jsonObject[TAG_CREDENTIAL_INFO].IsString()) { - context->accessee.credentialInfos = jsonObject[TAG_CREDENTIAL_INFO].Get(); + if (jsonObject[TAG_CERT_INFO].IsString()) { + context->accessee.credentialTypeLists = stringToVectorInt32(jsonObject[TAG_CERT_INFO].Get()); } if (jsonObject[DM_TAG_AUTH_TYPE_LIST].IsString()) { auto strList = jsonObject[DM_TAG_AUTH_TYPE_LIST].Get(); - context->authTypeList = stringToVector(strList); + context->authTypeList = stringToVectorAuthType(strList); } if (jsonObject.Contains(DM_TAG_AUTH_RESULT) && jsonObject[DM_TAG_AUTH_RESULT].IsNumberInteger()) { context->authResult = static_cast(jsonObject[DM_TAG_AUTH_RESULT].Get()); diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 10162a9ea..6d2d5e9b2 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -13,6 +13,8 @@ * limitations under the License. */ +#include "access_control_profile.h" +#include "dm_crypto.h" #include "dm_auth_state.h" #include "dm_auth_context.h" #include "dm_auth_manager_base.h" @@ -30,6 +32,131 @@ namespace OHOS { namespace DistributedHardware { +namespace { + +enum { + ACCOUNT_RELATED = 1, + ACCOUNT_UNRELATED, + ACCOUNT_ACROSS +}; + +enum { + SCOPE_DEVICE = 1, + SCOPE_USER, + SCOPE_APP, +}; + +// Security device auth credential query related definitions, keep consistent with device_auth.h +const char* const FILED_DEVICE_ID = "deviceId"; +const char* const FILED_USER_ID = "userId"; +const char* const FILED_DEVICE_ID_HASH = "deviceIdHash"; +const char* const FILED_PEER_USER_SPACE_ID = "peerUserSpaceId"; +const char* const FILED_CRED_TYPE = "credType"; +const char* const FILED_AUTHORIZED_SCOPE = "authorizedScope"; +const char* const FILED_AUTHORIZED_APP_LIST = "authorizedAppList"; + +bool HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList) +{ + // Store the token of src and sink. The size must be 2. + if (tokenList.size() != 2) { + LOGE("HaveSameTokenId invalid tokenList size."); + return false; + } + + // tokenIdList = [srcTokenId, sinkTokenId] + std::string srcTokenIdHash = Crypto::Sha256(tokenList[0]); + std::string sinkTokenIdHash = Crypto::Sha256(tokenList[1]); + + return (srcTokenIdHash == context->accesser.tokenIdHash) && + (sinkTokenIdHash == context->accessee.tokenIdHash); +} + +uint32_t GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo) +{ + if (!credInfo[FILED_CRED_TYPE].IsNumberInteger() || !credInfo[FILED_AUTHORIZED_SCOPE].IsNumber()) { + return DM_INVALIED_BINDTYPE; + } + + int32_t credType = credInfo[FILED_CRED_TYPE].Get(); + int32_t authorizedScope = credInfo[FILED_AUTHORIZED_SCOPE].Get(); + if (authorizedScope == SCOPE_USER) { + if (credType == ACCOUNT_RELATED) { + return DM_IDENTICAL_ACCOUNT; + } else if (credType == ACCOUNT_ACROSS) { + return DM_ACROSS_ACCOUNT; + } + } + + std::vector appList; + credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList); + if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_APP && HaveSameTokenId(context, appList)) { + return DM_POINT_TO_POINT; + } + + // 未确定凭据类型 + return DM_INVALIED_BINDTYPE; +} + +int32_t DmQueryCredential(std::shared_ptr context, JsonObject &queryResult) +{ + int32_t ret; + uint32_t credType; + JsonObject queryParams; + + DmAccess access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; + DmAccess remoteAccess = context->direction == DM_AUTH_SOURCE ? context->accessee : context->accesser; + + queryParams[FILED_DEVICE_ID_HASH] = remoteAccess.deviceId; + queryParams[FILED_USER_ID] = access.userId; + queryParams[FILED_PEER_USER_SPACE_ID] = remoteAccess.userId; + ret = context->hiChainAuthConnector->QueryCredentialInfo(access.userId, queryParams, queryResult); + if (ret != DM_OK) { + LOGE("DmQueryCredential fail to query credential id list."); + return ret; + } + // TODO: delete + LOGI("DmQueryCredential for userId %{public}d and queryParams %{public}s " + "query credentialInfo: %{public}s", access.userId, queryParams.Dump().c_str(), + queryResult.Dump().c_str()); + + for (auto& item : queryResult.Items()) { + // 确认凭据类型 + credType = GetCredentialType(context, item); + if (credType == DM_INVALIED_BINDTYPE) { + continue; + } + + item[FILED_CRED_TYPE] = credType; + // TODO: 确认credInfo中是否有id信息 + access.credentialInfos[credType] = item.Dump(); + } + + return DM_OK; +} + +// Compares hashs of the device IDs and user IDs +bool AclCompareTwoIds(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + return Crypto::Sha256(accesser.GetAccesserDeviceId()) == context->accesser.deviceIdHash && + Crypto::Sha256(std::to_string(accesser.GetAccesserUserId())) == context->accesser.userIdHash && + Crypto::Sha256(accessee.GetAccesseeDeviceId()) == context->accessee.deviceIdHash && + Crypto::Sha256(std::to_string(accessee.GetAccesseeUserId())) == context->accessee.userIdHash; +} + +// Compares hashs of the device IDs, user IDs, account IDs, and token IDs +bool AclCompareFourIds(std::shared_ptr context, + const DistributedDeviceProfile::Accesser &accesser, const DistributedDeviceProfile::Accessee &accessee) +{ + return AclCompareTwoIds(context, accesser, accessee) && + Crypto::Sha256(accesser.GetAccesserAccountId()) == context->accesser.accountIdHash && + Crypto::Sha256(std::to_string(accesser.GetAccesserTokenId())) == context->accesser.tokenIdHash && + Crypto::Sha256(accessee.GetAccesseeAccountId()) == context->accessee.accountIdHash && + Crypto::Sha256(std::to_string(accessee.GetAccesseeTokenId())) == context->accessee.tokenIdHash; +} + +} + // clone task timeout map const std::map TASK_TIME_OUT_MAP = { { std::string(AUTHENTICATE_TIMEOUT_TASK), CLONE_AUTHENTICATE_TIMEOUT }, @@ -158,5 +285,107 @@ std::string DmAuthState::GenerateBindResultContent(DmAccess &access) std::string content = jsonObj.Dump(); return content; } + +int32_t DmAuthState::GetAuthCredentialInfo(std::shared_ptr context) +{ + int32_t ret; + JsonObject queryResult; + std::vector credTypeList; + + // 1. Retrieve all credentials + ret = DmQueryCredential(context, queryResult); + if (ret != DM_OK) { + LOGE("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo fail to query credential"); + return ret; + } + + // 2. Retrieve all ACLs + DmAccess access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAccessControlProfile(); + for (const DistributedDeviceProfile::AccessControlProfile &item : profiles) { + bool isAclMatched = false; + DistributedDeviceProfile::Accesser accesser = item.GetAccesser(); + DistributedDeviceProfile::Accessee accessee = item.GetAccessee(); + + // Ensure credentials match with ACL + std::string credId = std::to_string(accessee.GetAccesseeCredentialId()); + if (!queryResult.Contains(credId) || item.GetStatus() != ACTIVE) { + continue; + } + + // Confirm if there is a trusted relationship + uint32_t credType = queryResult[credId][FILED_CRED_TYPE].Get(); + if (credType == DM_IDENTICAL_ACCOUNT || credType == DM_ACROSS_ACCOUNT) { + isAclMatched = AclCompareTwoIds(context, accesser, accessee); + } else if (credType == DM_POINT_TO_POINT) { + isAclMatched = AclCompareFourIds(context, accesser, accessee); + } + + if (isAclMatched) { + credTypeList.push_back(credType); + access.aclProfiles[credType] = item; + LOGI("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo success to get credType %{public}d", credType); + } + } + + if (!credTypeList.empty()) { + access.credentialTypeLists = credTypeList; + access.isAuthed = true; + } + + return DM_OK; +} + +int32_t DmAuthState::NeedReqUserConfirm(std::shared_ptr context) +{ + // 不管是否有可信关系,都需要走pin码认证,主要指鸿蒙环PIN码导入场景 + if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + return true; + } + + // 有ACL,跳转到结束状态,发200报文,直接组网 + DmAccess access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; + if (access.isAuthed) { + return false; + } + + return true; +} + +int32_t DmAuthState::NeedPinAuth(std::shared_ptr context) +{ + if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + return true; + } + + DmAccess access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; + if (access.isAuthed) { + return false; + } + + std::vector credTypeLists = context->accesser.credentialTypeLists; + if (credTypeLists.size() == 1) { + int32_t credType = credTypeLists.front(); + if (credType == DM_IDENTICAL_ACCOUNT || credType == DM_ACROSS_ACCOUNT) { + return false; + } + } + + return true; +} + +int32_t DmAuthState::NeedAgreeCredential(std::shared_ptr context) +{ + return context->needAgreeCredential; +} + +int32_t DmAuthState::NeedAgreeAcl(std::shared_ptr context) +{ + DmAccess access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; + DmAccess remoteAccess = context->direction == DM_AUTH_SOURCE ? context->accessee : context->accesser; + return access.transmitSessionKeyId != 0 && access.transmitSessionKeyId != 0; +} + } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 7d8a907ac..33ed84cc1 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -17,7 +17,7 @@ #include "dm_constants.h" #include "dm_auth_state.h" #include "dm_auth_context.h" - +#include "dm_auth_manager_base.h" #include "dm_auth_state_machine.h" namespace OHOS { -- Gitee From 0d125e93ca05f24bca0e89f000ed96d671114be5 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Wed, 26 Mar 2025 21:08:58 +0800 Subject: [PATCH 296/382] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8D=E7=BC=96?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_acl.cpp | 1 + .../src/authentication_v2/dm_auth_state.cpp | 8 ++++---- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 28be628b1..0dadc4897 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -20,6 +20,7 @@ #include "deviceprofile_connector.h" #include "dm_auth_context.h" +#include "dm_auth_state_machine.h" #include "dm_constants.h" #include "auth_manager.h" #include "multiple_user_connector.h" diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 6d2d5e9b2..0c9d1cc69 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -222,10 +222,10 @@ void DmAuthState::SyncAclList(std::shared_ptr context, void DmAuthState::SourceFinish(std::shared_ptr context) { - context->listener->OnAuthResult(context->processInfo, context->peerTargetId.deviceId, context->token, - context->state, context->reason); - context->listener->OnBindResult(context->processInfo, context->peerTargetId, context->reply, - context->state, GenerateBindResultContent(context->accessee)); + // context->listener->OnAuthResult(context->processInfo, context->peerTargetId.deviceId, context->token, + // context->state, context->reason); + // context->listener->OnBindResult(context->processInfo, context->peerTargetId, context->reply, + // context->state, GenerateBindResultContent(context->accessee)); context->isFinished = true; if (context->reason != DM_OK) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); -- Gitee From 1036480778d9662b152338e7d059dc131c6f83f7 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Wed, 26 Mar 2025 21:09:51 +0800 Subject: [PATCH 297/382] tmp new pin auth --- .../authentication_v2/dm_auth_context.h | 2 +- .../include/authentication_v2/dm_auth_state.h | 12 +- .../auth_stages/auth_confirm.cpp | 161 +++++++++++++++++- .../auth_stages/auth_negotiate.cpp | 6 +- .../auth_stages/auth_pin_auth.cpp | 74 ++++++++ .../dm_auth_message_processor.cpp | 29 +++- .../dm_auth_state_machine.cpp | 5 +- 7 files changed, 272 insertions(+), 17 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 15df14b5b..14de3f650 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -150,7 +150,7 @@ struct DmAuthContext { 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}; + bool authResultReady{false}; // todo del DmAuthType authType{DmAuthType::AUTH_TYPE_PIN}; // PIN code, ultrasonic PIN code, imported PIN code std::vector authTypeList; uint32_t currentAuthTypeIdx{0}; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 4f6dfd220..7ad1b2e35 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -140,6 +140,11 @@ public: int32_t Action(std::shared_ptr context) override; private: int32_t ShowConfigDialog(std::shared_ptr context); +#ifdef NEW_PIN_AUTH326 // todo enable + void ReadServiceInfo(std::shared_ptr context); + void MatchFallBackCandidateList(std::shared_ptr context, DmAuthType authType); + bool IsAuthCodeReady(std::shared_ptr context); +#endif }; class AuthSrcPinNegotiateStartState : public DmAuthState { @@ -329,10 +334,9 @@ private: 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); + void MatchFallBackCandidateList(std::shared_ptr context, DmAuthType authType); // todo del + bool IsAuthCodeReady(std::shared_ptr context); // todo del + void NegotiatePinAuthType(std::shared_ptr context); // todo del }; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 570b3af30..18505f6b9 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -30,7 +30,17 @@ constexpr const char* TAG_LOCAL_DEVICE_TYPE = "LOCALDEVICETYPE"; constexpr const char* TAG_REQUESTER = "REQUESTER"; constexpr const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; -std::set g_shareByPinAuthDeviceTypeSet{DmDeviceType::DEVICE_TYPE_SMART_DISPLAY}; +std::set g_shareByPinAuthDeviceTypeSet{DmDeviceType::DEVICE_TYPE_SMART_DISPLAY}; // todo del + +#ifdef NEW_PIN_AUTH326 +// authType fallback table +using FallBackKey = std::pair; // accessee.bundleName, authType +static std::map g_pinAuthTypeFallBackMap = { + {{"cast_engine_service", DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE}, DmAuthType::AUTH_TYPE_PIN}, +}; +// Maximum number of recursive lookups +constexpr size_t MAX_FALLBACK_LOOPKUP_TIMES = 2; +#endif DmAuthStateType AuthSrcConfirmState::GetStateType() { @@ -71,7 +81,7 @@ int32_t AuthSrcConfirmState::DoPinAuth(std::shared_ptr context) } return DM_OK; } - +#ifndef NEW_PIN_AUTH326 int32_t AuthSrcConfirmState::Action(std::shared_ptr context) { LOGI("AuthSrcConfirmState::Action start"); @@ -87,7 +97,35 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) // no credential, try to do pin auth return DoPinAuth(context); } +#else +int32_t AuthSrcConfirmState::Action(std::shared_ptr context) +{ + LOGI("AuthSrcConfirmState::Action start"); + // check version compatibility + context->timer->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); + if (CompareVersion(context->accessee.dmVersion, std::string(DM_VERSION_5_1_0))) { + LOGE("AuthSrcConfirmState::Action incompatible version %{public}s compare to 5.1.0", + context->accessee.dmVersion.c_str()); + context->reason = ERR_DM_VERSION_INCOMPATIBLE; + return ERR_DM_VERSION_INCOMPATIBLE; + } + + // todo 凭据协商 + + if (false) { // todo 判断 src.authtype != 导入PIN && 有可信关系 + // todo goto 组网 + return DM_OK; + } + // send 100 msg + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_USER_CONFIRM, context); + context->timer->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), + [context] (std::string name) { + HandleAuthenticateTimeout(context, name); + }); +} +#endif DmAuthStateType AuthSinkConfirmState::GetStateType() { return DmAuthStateType::AUTH_SINK_CONFIRM_STATE; @@ -117,7 +155,125 @@ int32_t AuthSinkConfirmState::ShowConfigDialog(std::shared_ptr co LOGI("AuthSinkConfirmState::ShowConfigDialog end"); return DM_OK; } +#ifdef NEW_PIN_AUTH326 +void AuthSinkConfirmState::MatchFallBackCandidateList( + std::shared_ptr context, DmAuthType authType) +{ + for (size_t i = 0; i < MAX_FALLBACK_LOOPKUP_TIMES; i++) { + auto it = g_pinAuthTypeFallBackMap.find({context->accessee.bundleName, authType}); + if (it != g_pinAuthTypeFallBackMap.end()) { + authType = it->second; + context->authTypeList.push_back(authType); + } else { + break; + } + } +} + +bool AuthSinkConfirmState::IsAuthCodeReady(std::shared_ptr context) +{ + if (context->importAuthCode.empty() || context->importSessionName.empty()) { + LOGE("AuthSinkNegotiateStateMachine::IsAuthCodeReady, auth code not ready."); + return false; + } + if (context->sessionName != context->importSessionName) { + LOGE("AuthSinkNegotiateStateMachine::IsAuthCodeReady sessionName %{public}s not supported with " + "import sessionName %{public}s.", context->sessionName.c_str(), context->importSessionName.c_str()); + return false; + } + return true; +} + +void AuthSinkConfirmState::ReadServiceInfo(std::shared_ptr context) +{ + // query ServiceInfo by accessee.bundleName and authType from client + OHOS::DistributedDeviceProfile::LocalServiceInfo srvInfo; + auto ret = DeviceProfileConnector::GetInstance().GetLocalServiceInfoByBundleNameAndPinExchangeType( + context->accessee.bundleName, context->authType, srvInfo); + if (ret == OHOS::DistributedDeviceProfile::DP_SUCCESS) { + // ServiceInfo found + context->authBoxType = srvInfo.GetAuthBoxType(); // read authBoxType + if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + std::string pinCode = srvInfo.GetPinCode(); // read pincode + context->pinCode = std::stoi(pinCode); + } + if (context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { // no authorization box + int32_t authResult = srvInfo.GetAuthType(); // read authResult + if (authResult == 0) { + context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH; + } else if (authResult == OHOS::DistributedDeviceProfile::NUM_1) { + context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; + } else if (authResult == OHOS::DistributedDeviceProfile::NUM_6) { + context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + } else { + context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; + } + context->authResultReady = true; + } + context->customData = srvInfo.GetDescription(); // read customData + } else if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE && IsAuthCodeReady(context)) { + // only special scenarios can import pincode + context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // no authorization box + context->authResultReady = true; + } else { + // not special scenarios, reset authResult to cancel + context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; + context->authBoxType = OHOS::DistributedDeviceProfile::NUM_1; // default: tristate box + } +} +int32_t AuthSinkConfirmState::Action(std::shared_ptr context) +{ + LOGI("AuthSinkConfirmState::Action start"); + ReadServiceInfo(context); + bool authTypeCheckOk = false; + if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE && + IsAuthCodeReady(context) && + context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { + /* The value of authresult may be the default value of temporary trust, + or the value of authresult may be set by the service. */ + authTypeCheckOk = true; + } else if ((context->authType == DmAuthType::AUTH_TYPE_PIN || + context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) && + context->authBoxType = OHOS::DistributedDeviceProfile::NUM_1) { + if (false) { /* todo authform 同账号 或 分享 凭据判断 */ + context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); + return DM_OK; + } else { + context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); + // show user confirmation dialog + auto ret = ShowConfigDialog(context); + if (ret != DM_OK) { + return ret; + } + // wait for user opration + if (DmEventType::ON_USER_OPERATION != + context->authStateMachine->WaitExpectEvent(DmEventType::ON_USER_OPERATION)) { + LOGE("AuthSinkConfirmState::Action wait ON_USER_OPERATION err"); + return STOP_BIND; + } + if (context->reply != USER_OPERATION_TYPE_ALLOW_AUTH) { + LOGI("AuthSinkConfirmState::Action USER_OPERATION_TYPE_CANCEL_AUTH"); + context->reason = ERR_DM_BIND_USER_CANCEL; + return STOP_BIND; + } + authTypeCheckOk = true; + } + } + context->authTypeList.clear(); + if (authTypeCheckOk) { + context->authTypeList.push_back(context->authType); + MatchFallBackCandidateList(context, context->authType); + // send 110 msg + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } + context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; + return ERR_DM_UNSUPPORTED_AUTH_TYPE; +} +#else int32_t AuthSinkConfirmState::Action(std::shared_ptr context) { LOGI("AuthSinkConfirmState::Action start"); @@ -166,6 +322,7 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } +#endif } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index e99941dd9..015fe3185 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -242,7 +242,7 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptraccessee.deviceId = std::string(localDeviceId); context->accessee.deviceIdHash = Crypto::Sha256(context->accessee.deviceId); - + // 2. Get userId int32_t userId = AuthManagerBase::DmGetUserId(context->accessee.displayId, context->accessee.userId); if (userId < 0) { @@ -342,7 +342,7 @@ int32_t AuthSinkNegotiateStateMachine::GetAuthCredentialInfo(std::shared_ptr con LOGE("AuthSinkNegotiateStateMachine::Action proc response negotiate failed"); return ret; } +#ifndef NEW_PIN_AUTH326 // todo rm -R NegotiatePinAuthType NegotiatePinAuthType(context); +#endif context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_ACL_NEGOTIATE, context); context->timer->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), DmAuthState::GetTaskTimeout(context, WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index bc6a91bdf..00f58bb42 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -281,7 +281,79 @@ DmAuthStateType AuthSrcPinNegotiateStartState::GetStateType() { return DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE; } +#ifdef NEW_PIN_AUTH326 +int32_t AuthSrcPinNegotiateStartState::NegotiatePinAuth(std::shared_ptr context, bool firstTime) +{ + if (firstTime) { + if (context->authTypeList.empty()) { + LOGE("AuthSrcPinNegotiateStartState::Action authTypeList empty"); + context->reason = ERR_DM_AUTH_REJECT; + return ERR_DM_AUTH_REJECT; + } + context->currentAuthTypeIdx = 0; + context->authType = context->authTypeList[0]; + } else { + if (context->authType == DmAuthType::AUTH_TYPE_PIN && + context->inputPinAuthFailTimes < MAX_AUTH_INPUT_PIN_FAIL_TIMES) { + LOGI("AuthSrcPinNegotiateStartState::Action input pin auth err, retry"); + } else { + // try to fallback to next auth type + if (context->currentAuthTypeIdx + 1 >= context->authTypeList.size()) { + LOGE("AuthSrcPinNegotiateStartState::Action all auth type failed"); + context->reason = ERR_DM_AUTH_REJECT; + return ERR_DM_AUTH_REJECT; + } + context->currentAuthTypeIdx++; + context->authType = context->authTypeList[context->currentAuthTypeIdx]; + } + } + // restart pin auth timer + context->timer->DeleteTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK)); + context->timer->StartTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, WAIT_PIN_AUTH_TIMEOUT_TASK, PIN_AUTH_TIMEOUT), + [context] (std::string name) { + HandleAuthenticateTimeout(context, name); + }); + if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + context->authStateMachine->TransitionTo(std::make_shared()); + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN) { + context->authStateMachine->TransitionTo(std::make_shared()); + } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { + context->authStateMachine->TransitionTo(std::make_shared()); + } else { + LOGE("AuthSrcPinNegotiateStartState::Action authType not support"); + return ERR_DM_FAILED; + } + return DM_OK; +} +int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr context) +{ + if (!context->pinNegotiateStarted) { + context->pinNegotiateStarted = true; + context->timer->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); + int32_t authResult = context->authResult; + if (authResult != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH && + authResult != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { + LOGE("AuthSrcPinNegotiateStartState::Action authResult not allow"); + context->reason = ERR_DM_BIND_USER_CANCEL; + return ERR_DM_BIND_USER_CANCEL; + } + // import pin code auth always excute + if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE && + !context->authTypeList.empty() && + context->authTypeList[0] == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + return NegotiatePinAuth(context, true); + } else if (false) { /* todo check 有凭据判断 !context->accesser.credentialTypeLists.empty() */ + // have credential available, skip pin auth + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } + return NegotiatePinAuth(context, true); + } + return NegotiatePinAuth(context, false); +} +#else int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr context) { if (!context->pinNegotiateStarted) { @@ -330,6 +402,7 @@ int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr con } return DM_OK; } +#endif DmAuthStateType AuthSrcPinInputState::GetStateType() { @@ -385,6 +458,7 @@ DmAuthStateType AuthSinkPinNegotiateStartState::GetStateType() int32_t AuthSinkPinNegotiateStartState::Action(std::shared_ptr context) { if (!context->pinNegotiateStarted) { + context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); context->pinNegotiateStarted = true; } else { if (context->authType == DmAuthType::AUTH_TYPE_PIN && diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index e9ddc8500..c54abde06 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -490,7 +490,7 @@ int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr // 创建80报文 int32_t DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject) { - jsonObject[TAG_AUTH_TYPE] = context->authType; + jsonObject[TAG_AUTH_TYPE] = context->authType; // todo del jsonObject[TAG_SESSION_NAME] = context->sessionName; jsonObject[DM_TAG_DMVERSION] = context->accesser.dmVersion; @@ -530,8 +530,8 @@ int32_t DmAuthMessageProcessor::CreateRespNegotiateMessage(std::shared_ptraccessee.isAuthed; jsonObject[TAG_CREDENTIAL_INFO] = context->accessee.credentialInfos; - jsonObject[DM_TAG_AUTH_TYPE_LIST] = vectorToString(context->authTypeList); - if (context->authResultReady) { + jsonObject[DM_TAG_AUTH_TYPE_LIST] = vectorToString(context->authTypeList); // todo del + if (context->authResultReady) { // todo del jsonObject[DM_TAG_AUTH_RESULT] = context->authResult; } return DM_OK; @@ -873,7 +873,7 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(const JsonObject &jsonObje if (jsonObject[TAG_BIND_LEVEL].IsNumberInteger()) { context->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].Get(); } - if (jsonObject[TAG_AUTH_TYPE].IsNumberInteger()) { + if (jsonObject[TAG_AUTH_TYPE].IsNumberInteger()) { // todo del context->authType = static_cast(jsonObject[TAG_AUTH_TYPE].Get()); } @@ -927,7 +927,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const JsonObject &j if (jsonObject[TAG_CREDENTIAL_INFO].IsString()) { context->accessee.credentialInfos = jsonObject[TAG_CREDENTIAL_INFO].Get(); } - +#ifndef NEW_PIN_AUTH326 // todo del if (jsonObject[DM_TAG_AUTH_TYPE_LIST].IsString()) { auto strList = jsonObject[DM_TAG_AUTH_TYPE_LIST].Get(); context->authTypeList = stringToVector(strList); @@ -936,7 +936,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const JsonObject &j context->authResult = static_cast(jsonObject[DM_TAG_AUTH_RESULT].Get()); context->authResultReady = true; } - +#endif context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -950,7 +950,12 @@ int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const JsonObject &jso if (json[TAG_DEVICE_NAME].IsString()) { context->accesser.deviceName = json[TAG_DEVICE_NAME].Get(); } - +#ifdef NEW_PIN_AUTH326 + if (json[TAG_AUTH_TYPE].IsNumberInteger()) { + context->authType = static_cast(json[TAG_AUTH_TYPE].Get()); + } + // todo parse authform +#endif context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -961,6 +966,13 @@ int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const JsonObject &js if (json[DM_TAG_AUTH_RESULT].IsNumberInteger()) { context->authResult = static_cast(json[DM_TAG_AUTH_RESULT].Get()); } + +#ifdef NEW_PIN_AUTH326 + if (json[DM_TAG_AUTH_TYPE_LIST].IsString()) { + auto strList = json[DM_TAG_AUTH_TYPE_LIST].Get(); + context->authTypeList = stringToVector(strList); + } +#endif context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -998,6 +1010,8 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate(const JsonObject int32_t DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json) { + json[TAG_AUTH_TYPE] = context->authType; + // todo send authform json[TAG_DEVICE_TYPE] = context->accesser.deviceType; json[TAG_DEVICE_NAME] = context->accesser.deviceName; return DM_OK; @@ -1006,6 +1020,7 @@ int32_t DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json) { json[DM_TAG_AUTH_RESULT] = context->authResult; + json[DM_TAG_AUTH_TYPE_LIST] = vectorToString(context->authTypeList); return DM_OK; } diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 7d8a907ac..5bdc210a1 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -60,9 +60,11 @@ void DmAuthStateMachine::InsertSrcTransTable() {DmAuthStateType::AUTH_SRC_NEGOTIATE_STATE, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE}}, {DmAuthStateType::AUTH_SRC_CONFIRM_STATE, { DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, - DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, + DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, + DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, // todo del }}, {DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, { + DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, DmAuthStateType::AUTH_SRC_PIN_INPUT_STATE, DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_ULTRASONIC_PIN_STATE, DmAuthStateType::AUTH_SRC_PIN_AUTH_START_STATE, @@ -85,6 +87,7 @@ void DmAuthStateMachine::InsertSrcTransTable() {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, { DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, }}, {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, -- Gitee From a3b0f7b8d398f4f2d4d221b6ca23225f77d6717a Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Wed, 26 Mar 2025 21:12:42 +0800 Subject: [PATCH 298/382] =?UTF-8?q?test:=20=E4=BF=AE=E6=94=B9=E8=BF=94?= =?UTF-8?q?=E5=9B=9E=E5=80=BC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/dm_auth_state.h | 8 ++++---- .../src/authentication_v2/dm_auth_state.cpp | 8 ++++---- 2 files changed, 8 insertions(+), 8 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index cb2937745..cb853e316 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -116,10 +116,10 @@ public: static void HandleAuthenticateTimeout(std::shared_ptr context, std::string name); protected: int32_t GetAuthCredentialInfo(std::shared_ptr context); - int32_t NeedReqUserConfirm(std::shared_ptr context); - int32_t NeedPinAuth(std::shared_ptr context); - int32_t NeedAgreeCredential(std::shared_ptr context); - int32_t NeedAgreeAcl(std::shared_ptr context); + bool NeedReqUserConfirm(std::shared_ptr context); + bool NeedPinAuth(std::shared_ptr context); + bool NeedAgreeCredential(std::shared_ptr context); + bool NeedAgreeAcl(std::shared_ptr context); }; class AuthSrcConfirmState : public DmAuthState { diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 0c9d1cc69..b3c9a87f5 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -337,7 +337,7 @@ int32_t DmAuthState::GetAuthCredentialInfo(std::shared_ptr contex return DM_OK; } -int32_t DmAuthState::NeedReqUserConfirm(std::shared_ptr context) +bool DmAuthState::NeedReqUserConfirm(std::shared_ptr context) { // 不管是否有可信关系,都需要走pin码认证,主要指鸿蒙环PIN码导入场景 if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { @@ -353,7 +353,7 @@ int32_t DmAuthState::NeedReqUserConfirm(std::shared_ptr context) return true; } -int32_t DmAuthState::NeedPinAuth(std::shared_ptr context) +bool DmAuthState::NeedPinAuth(std::shared_ptr context) { if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { return true; @@ -375,12 +375,12 @@ int32_t DmAuthState::NeedPinAuth(std::shared_ptr context) return true; } -int32_t DmAuthState::NeedAgreeCredential(std::shared_ptr context) +bool DmAuthState::NeedAgreeCredential(std::shared_ptr context) { return context->needAgreeCredential; } -int32_t DmAuthState::NeedAgreeAcl(std::shared_ptr context) +bool DmAuthState::NeedAgreeAcl(std::shared_ptr context) { DmAccess access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; DmAccess remoteAccess = context->direction == DM_AUTH_SOURCE ? context->accessee : context->accesser; -- Gitee From 0339c93c2bff53877fe17587cde4768d5047f6ed Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Wed, 26 Mar 2025 21:17:24 +0800 Subject: [PATCH 299/382] =?UTF-8?q?=E4=BF=AE=E5=A4=8Donbind=E5=9B=9E?= =?UTF-8?q?=E8=B0=83=E7=BC=96=E8=AF=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../src/authentication_v2/dm_auth_state.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index b3c9a87f5..f2724fabc 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -222,10 +222,10 @@ void DmAuthState::SyncAclList(std::shared_ptr context, void DmAuthState::SourceFinish(std::shared_ptr context) { - // context->listener->OnAuthResult(context->processInfo, context->peerTargetId.deviceId, context->token, - // context->state, context->reason); - // context->listener->OnBindResult(context->processInfo, context->peerTargetId, context->reply, - // context->state, GenerateBindResultContent(context->accessee)); + context->listener->OnAuthResult(context->processInfo, context->peerTargetId.deviceId, context->accessee.token, + context->state, context->reason); + context->listener->OnBindResult(context->processInfo, context->peerTargetId, context->reply, + context->state, GenerateBindResultContent(context->accessee)); context->isFinished = true; if (context->reason != DM_OK) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); -- Gitee From e4bb584b1f1046d2d05e5df224835f01b5edb98c Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Wed, 26 Mar 2025 21:17:38 +0800 Subject: [PATCH 300/382] =?UTF-8?q?fix=EF=BC=9A=E6=9C=89=E5=87=AD=E6=8D=AE?= =?UTF-8?q?=E7=9B=B4=E6=8E=A5=E7=BB=84=E7=BD=91=EF=BC=8C=E8=B7=B3=E8=BF=87?= =?UTF-8?q?=E5=8D=8F=E5=95=86=E5=92=8Cacl=E4=BF=9D=E5=AD=98=E9=98=B6?= =?UTF-8?q?=E6=AE=B5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth_stages/auth_acl.cpp | 83 ++++++++++--------- .../auth_stages/auth_credential.cpp | 44 +++++----- 2 files changed, 66 insertions(+), 61 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 0dadc4897..e6ca9b3f4 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -100,49 +100,52 @@ DmAuthStateType AuthSinkDataSyncState::GetStateType() int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) { LOGI("AuthSrcDataSyncState::Action start"); - // 判断密文阶段和明文阶段的四元组是否相同,不同则直接结束 - bool isSame = Crypto::Sha256(context->accessee.deviceId) == context->accessee.deviceIdHash && - Crypto::Sha256(std::to_string(context->accessee.userId)) == context->accessee.userIdHash && - Crypto::Sha256(context->accessee.accountId) == context->accessee.accountIdHash && - Crypto::Sha256(std::to_string(context->accessee.tokenId)) == context->accessee.tokenIdHash; - // && context->accesser.bindLevel == context->accessee.bindLevel; bindlevel协商能力补齐后打开 - if (!isSame) { - LOGE("data between two stages different, stop auth"); - // 不同直接结束,发送200给sink端 - context->reason = ERR_DM_QUADRUPLE_NOT_SAME; - context->reply = ERR_DM_QUADRUPLE_NOT_SAME; - context->state = static_cast(GetStateType()); - context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_REQ_FINISH, context); // source异常时,source不结束,发送200给sink,等sink回201 - return DM_OK; - } - // 查询sink端acl - std::vector profiles = - DeviceProfileConnector::GetInstance().GetAccessControlProfile(); - std::vector srcAclList; - for (auto &item : profiles) { - if (item.GetAccesser().GetAccesserDeviceId() == context->accesser.deviceId && - item.GetAccesser().GetAccesserUserId() == context->accesser.userId && - item.GetAccessee().GetAccesseeDeviceId() == context->accessee.deviceId && - item.GetAccessee().GetAccesseeUserId() == context->accessee.userId) { - srcAclList.push_back(item); // 打印并写入 + + if (NeedAgreeAcl(context)) { + // 判断密文阶段和明文阶段的四元组是否相同,不同则直接结束 + bool isSame = Crypto::Sha256(context->accessee.deviceId) == context->accessee.deviceIdHash && + Crypto::Sha256(std::to_string(context->accessee.userId)) == context->accessee.userIdHash && + Crypto::Sha256(context->accessee.accountId) == context->accessee.accountIdHash && + Crypto::Sha256(std::to_string(context->accessee.tokenId)) == context->accessee.tokenIdHash; + // && context->accesser.bindLevel == context->accessee.bindLevel; bindlevel协商能力补齐后打开 + if (!isSame) { + LOGE("data between two stages different, stop auth"); + // 不同直接结束,发送200给sink端 + context->reason = ERR_DM_QUADRUPLE_NOT_SAME; + context->reply = ERR_DM_QUADRUPLE_NOT_SAME; + context->state = static_cast(GetStateType()); + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_REQ_FINISH, context); // source异常时,source不结束,发送200给sink,等sink回201 + return DM_OK; } - } - if (srcAclList.empty()) { - LOGI("AuthSrcDataSyncState::Action acl is empty"); // 首次认证 无acl同步 - } - // 比较双端的acl - for (auto &srcAcl : srcAclList) { - bool res = context->authMessageProcessor->ChecksumAcl(srcAcl, - context->accessee.accesserStrList, context->accessee.accesseeStrList); - if (res) { - continue; + // 查询sink端acl + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAccessControlProfile(); + std::vector srcAclList; + for (auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == context->accesser.deviceId && + item.GetAccesser().GetAccesserUserId() == context->accesser.userId && + item.GetAccessee().GetAccesseeDeviceId() == context->accessee.deviceId && + item.GetAccessee().GetAccesseeUserId() == context->accessee.userId) { + srcAclList.push_back(item); // 打印并写入 + } } - SyncAclList(context, std::to_string(srcAcl.GetAccesser().GetAccesserCredentialId()), - srcAcl.GetAccesser().GetAccesserSessionKeyId(), srcAcl.GetAccessControlId()); + if (srcAclList.empty()) { + LOGI("AuthSrcDataSyncState::Action acl is empty"); // 首次认证 无acl同步 + } + // 比较双端的acl + for (auto &srcAcl : srcAclList) { + bool res = context->authMessageProcessor->ChecksumAcl(srcAcl, + context->accessee.accesserStrList, context->accessee.accesseeStrList); + if (res) { + continue; + } + SyncAclList(context, std::to_string(srcAcl.GetAccesser().GetAccesserCredentialId()), + srcAcl.GetAccesser().GetAccesserSessionKeyId(), srcAcl.GetAccessControlId()); + } + // 保存本次acl + context->authMessageProcessor->PutAccessControlList(context, context->accesser, context->accessee.deviceId); + // 同步本端的sp信息,不确定格式,暂不做 } - // 保存本次acl - context->authMessageProcessor->PutAccessControlList(context, context->accesser, context->accessee.deviceId); - // 同步本端的sp信息,不确定格式,暂不做 // 触发组网 if (!context->accesser.isOnline) { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index fbd69cafe..680ea9740 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -480,35 +480,37 @@ int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr c return ret; } - // 首次认证 - if (!context->isOnline) { - // 协商用户级凭据 - tmpCredId = context->accesser.lnnCredentialId; - ret = AgreeCredential(DM_AUTH_SCOPE_USER, context); + if (NeedAgreeCredential(context)) { + // 首次认证 + if (!context->isOnline) { + // 协商用户级凭据 + tmpCredId = context->accesser.lnnCredentialId; + ret = AgreeCredential(DM_AUTH_SCOPE_USER, context); + if (ret != DM_OK) { + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + context->SetCredentialId(DM_AUTH_LOCAL_SIDE, DM_AUTH_SCOPE_USER, ""); + LOGE("AuthSrcCredentialAuthStartState::Action failed, agree user cred failed."); + return ret; + } + + // 删除临时用户级凭据 + context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); + } + + // 协商应用级凭据 + tmpCredId = context->accesser.transmitCredentialId; + ret = AgreeCredential(DM_AUTH_SCOPE_APP, context); if (ret != DM_OK) { context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); - context->SetCredentialId(DM_AUTH_LOCAL_SIDE, DM_AUTH_SCOPE_USER, ""); - LOGE("AuthSrcCredentialAuthStartState::Action failed, agree user cred failed."); + context->SetCredentialId(DM_AUTH_LOCAL_SIDE, DM_AUTH_SCOPE_APP, ""); + LOGE("AuthSrcCredentialAuthStartState::Action failed, agree app cred failed."); return ret; } - // 删除临时用户级凭据 + // 删除临时应用级凭据 context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); } - // 协商应用级凭据 - tmpCredId = context->accesser.transmitCredentialId; - ret = AgreeCredential(DM_AUTH_SCOPE_APP, context); - if (ret != DM_OK) { - context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); - context->SetCredentialId(DM_AUTH_LOCAL_SIDE, DM_AUTH_SCOPE_APP, ""); - LOGE("AuthSrcCredentialAuthStartState::Action failed, agree app cred failed."); - return ret; - } - - // 删除临时应用级凭据 - context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); - // 凭据认证 先进行应用级 ret = context->hiChainAuthConnector->AuthCredential(osAccountId, context->requestId, context->accesser.transmitCredentialId, std::string("")); -- Gitee From 6accc601f2c219659c805e7a53aa5e435baadd5c Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Wed, 26 Mar 2025 21:42:38 +0800 Subject: [PATCH 301/382] modify state tarns --- .../dm_auth_message_processor.cpp | 2 +- .../authentication_v2/dm_auth_state_machine.cpp | 15 +++++++++++---- 2 files changed, 12 insertions(+), 5 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index ff9ab0b1b..4b55305e8 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1044,7 +1044,7 @@ int32_t DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json) { json[DM_TAG_AUTH_RESULT] = context->authResult; - json[DM_TAG_AUTH_TYPE_LIST] = vectorToString(context->authTypeList); + json[DM_TAG_AUTH_TYPE_LIST] = vectorAuthTypeToString(context->authTypeList); return DM_OK; } diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index d36a678e9..0c9a80ee2 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -87,9 +87,11 @@ void DmAuthStateMachine::InsertSrcTransTable() {DmAuthStateType::AUTH_SRC_PIN_AUTH_DONE_STATE, { DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, + }}, + {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, { DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, + DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, }}, - {DmAuthStateType::AUTH_SRC_CREDENTIAL_EXCHANGE_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE}}, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, {DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE}}, @@ -114,11 +116,12 @@ void DmAuthStateMachine::InsertSinkTransTable() {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE, { DmAuthStateType::AUTH_SINK_CONFIRM_STATE, - DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, - DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, + DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, // todo del + DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, // todo del }}, {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, { DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, + DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, }}, {DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, { DmAuthStateType::AUTH_SINK_PIN_DISPLAY_STATE, @@ -140,7 +143,11 @@ void DmAuthStateMachine::InsertSinkTransTable() DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, }}, - {DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE}}, + {DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, { + DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, + DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, + DmAuthStateType::AUTH_SINK_FINISH_STATE, // tdo check ?? or DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE ? + }}, {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, { DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, }}, -- Gitee From 430c04aecd54b20eb8e804aec559bb49872570cb Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Wed, 26 Mar 2025 21:46:08 +0800 Subject: [PATCH 302/382] =?UTF-8?q?fix=EF=BC=9A=E6=B7=BB=E5=8A=A0=E6=8A=A5?= =?UTF-8?q?=E6=96=87=E6=89=93=E5=8D=B0=E4=BF=A1=E6=81=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 4b55305e8..6e5b206c9 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -301,6 +301,7 @@ int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr cont DmMessageType msgType = static_cast(jsonObject[TAG_MSG_TYPE].Get()); context->msgType = msgType; LOGI("DmAuthMessageProcessor::ParseMessage message type %{public}d", context->msgType); + LOGI("DmAuthMessageProcessor::ParseMessage message is %{public}s", message.c_str()); auto itr = paraseMessageFuncMap_.find(msgType); if (itr == paraseMessageFuncMap_.end()) { LOGI("DmAuthMessageProcessor::ParseMessage message type error %{public}d", context->msgType); @@ -498,6 +499,7 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh return ""; } int32_t ret = (this->*(itr->second))(context, jsonObj); + LOGI("DmAuthMessageProcessor::CreateMessage start. message is %{public}s", jsonObj.Dump().c_str()); return (ret == DM_OK) ? jsonObj.Dump() : ""; } -- Gitee From 018ba3f7afe63effdd8655cf7ee532c80689f7e5 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Wed, 26 Mar 2025 21:55:27 +0800 Subject: [PATCH 303/382] tmp --- .../include/authentication_v2/dm_auth_context.h | 2 +- .../include/authentication_v2/dm_auth_state.h | 6 +++++- .../auth_stages/auth_confirm.cpp | 17 +++++++++++++---- .../auth_stages/auth_pin_auth.cpp | 4 ++-- .../dm_auth_message_processor.cpp | 7 ++++++- 5 files changed, 27 insertions(+), 9 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index c42ae9395..52c801096 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -15,7 +15,7 @@ #ifndef OHOS_DM_AUTH_CONTEXT_V2_H #define OHOS_DM_AUTH_CONTEXT_V2_H - +#define NEW_PIN_AUTH326 #include #include diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index bcd960f68..3d73569b0 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -131,7 +131,7 @@ private: void NegotiateCredential(std::shared_ptr context); void NegotiateAcl(std::shared_ptr context); int32_t NoNeedAction(std::shared_ptr context); - int32_t DoPinAuth(std::shared_ptr context); + int32_t DoPinAuth(std::shared_ptr context); // todo del }; class AuthSinkStatePinAuthComm { @@ -163,6 +163,10 @@ public: virtual ~AuthSrcPinNegotiateStartState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; +#ifdef NEW_PIN_AUTH326 +private: + int32_t NegotiatePinAuth(std::shared_ptr context, bool firstTime); +#endif }; class AuthSrcPinInputState : public DmAuthState { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 66dd1dff4..6169844fb 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -16,6 +16,7 @@ #include "auth_manager.h" #include "access_control_profile.h" #include "deviceprofile_connector.h" +#include "distributed_device_profile_errors.h" #include "dm_anonymous.h" #include "dm_auth_context.h" #include "dm_auth_state.h" @@ -181,8 +182,12 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) NegotiateCredential(context); NegotiateAcl(context); - if (false) { // todo 判断 src.authtype != 导入PIN && 有可信关系 - // todo goto 组网 + // not pin import, and have acl + if (context->authType != DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE && + context->accesser.transmitSessionKeyId != 0 && + context->accessee.transmitSessionKeyId != 0) { + // finished, goto join lnn + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } // send 100 msg @@ -193,6 +198,7 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) [context] (std::string name) { HandleAuthenticateTimeout(context, name); }); + return DM_OK; } #endif DmAuthStateType AuthSinkConfirmState::GetStateType() @@ -350,8 +356,11 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) authTypeCheckOk = true; } else if ((context->authType == DmAuthType::AUTH_TYPE_PIN || context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) && - context->authBoxType = OHOS::DistributedDeviceProfile::NUM_1) { - if (false) { /* todo authform 同账号 或 分享 凭据判断 */ + context->authBoxType == OHOS::DistributedDeviceProfile::NUM_1) { + auto& credTypeLists = context->accesser.credentialTypeLists; + if ((!credTypeLists.empty()) && + (credTypeLists[0] == DM_IDENTICAL_ACCOUNT || credTypeLists[0] == DM_ACROSS_ACCOUNT)) { + // have DM_IDENTICAL_ACCOUNT or DM_ACROSS_ACCOUNT context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); return DM_OK; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 131083ab3..92449d69a 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -341,10 +341,10 @@ int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr con } // import pin code auth always excute if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE && - !context->authTypeList.empty() && + (!context->authTypeList.empty()) && context->authTypeList[0] == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { return NegotiatePinAuth(context, true); - } else if (false) { /* todo check 有凭据判断 !context->accesser.credentialTypeLists.empty() */ + } else if (!context->accesser.credentialTypeLists.empty()) { // have credential available, skip pin auth context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 6e5b206c9..644bf9166 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -981,6 +981,9 @@ int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const JsonObject &jso context->authType = static_cast(json[TAG_AUTH_TYPE].Get()); } // todo parse authform + if (json[TAG_CERT_INFO].IsString()) { + context->accesser.credentialTypeLists = stringToVectorInt32(json[TAG_CERT_INFO].Get()); + } #endif context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; @@ -996,7 +999,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const JsonObject &js #ifdef NEW_PIN_AUTH326 if (json[DM_TAG_AUTH_TYPE_LIST].IsString()) { auto strList = json[DM_TAG_AUTH_TYPE_LIST].Get(); - context->authTypeList = stringToVector(strList); + context->authTypeList = stringToVectorAuthType(strList); } #endif context->authStateMachine->TransitionTo(std::make_shared()); @@ -1038,6 +1041,8 @@ int32_t DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptrauthType; // todo send authform + + json[TAG_CERT_INFO] = vectorInt32ToString(context->accesser.credentialTypeLists); json[TAG_DEVICE_TYPE] = context->accesser.deviceType; json[TAG_DEVICE_NAME] = context->accesser.deviceName; return DM_OK; -- Gitee From d6b9362147484042e73eea01932cfd369fd2dc42 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Thu, 27 Mar 2025 10:29:40 +0800 Subject: [PATCH 304/382] =?UTF-8?q?test:=20=E8=A7=A3=E5=86=B3SA-SA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_manager.cpp | 3 +- .../auth_stages/auth_confirm.cpp | 29 +++++++++++++++---- .../auth_stages/auth_negotiate.cpp | 18 +++++++----- 3 files changed, 36 insertions(+), 14 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index e7838d7a1..e5759ab5c 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -411,7 +411,8 @@ bool AuthManager::IsAuthTypeSupported(const int32_t &authType) bool AuthManager::IsAuthCodeReady(const std::string &sessionName) { if (context_->importAuthCode.empty() || context_->importSessionName.empty()) { - LOGE("AuthManager::IsAuthCodeReady, auth code not ready."); + LOGE("AuthManager::IsAuthCodeReady, auth code not ready with authCode %{public}s and sessionName %{public}s.", + context_->importAuthCode.c_str(), context_->importSessionName.c_str()); return false; } if (sessionName != context_->importSessionName) { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 6169844fb..568dc3c1c 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -27,6 +27,7 @@ namespace OHOS { namespace DistributedHardware { +constexpr const char* TAG_CRED_ID = "credId"; constexpr const char* TAG_CUSTOM_DESCRIPTION = "CUSTOMDESC"; constexpr const char* TAG_LOCAL_DEVICE_TYPE = "LOCALDEVICETYPE"; constexpr const char* TAG_REQUESTER = "REQUESTER"; @@ -97,17 +98,26 @@ void AuthSrcConfirmState::NegotiateCredential(std::shared_ptr con std::set_intersection(srcCredTypeList.begin(), srcCredTypeList.end(), sinkCredTypeList.begin(), sinkCredTypeList.end(), std::back_inserter(intersection)); + if (context->accessee.tokenIdHash.empty()) { + context->accesser.bindLevel = SERVICE; // SA-SA + } else { + context->accesser.bindLevel = APP; // FA-FA + } + if (!intersection.empty() && + (intersection.front() == DM_IDENTICAL_ACCOUNT || intersection.front() == DM_ACROSS_ACCOUNT)) { + context->accesser.bindLevel = DEVICE; // Exceptions: account related is DEVICE + } + // TODO: 添加配件判断 if (!intersection.empty()) { // 如果交集不为空,将第一个值赋值给 context->accesser.credTypeList // TODO: 确认优先级是否正确 - // TODO: 需确认凭据id JsonObject credInfo(context->accesser.credentialInfos[intersection.front()]); - if (credInfo.Contains("id") && credInfo["id"].IsString()) { + if (credInfo.Contains(TAG_CRED_ID) && credInfo[TAG_CRED_ID].IsString()) { context->accesser.credentialTypeLists.clear(); context->accesser.credentialTypeLists.push_back(intersection.front()); context->needAgreeCredential = false; - context->accessee.transmitCredentialId = credInfo["id"].Get(); + context->accessee.transmitCredentialId = credInfo[TAG_CRED_ID].Get(); } } @@ -238,6 +248,15 @@ void AuthSinkConfirmState::NegotiateCredential(std::shared_ptr co } int32_t credType = context->accesser.credentialTypeLists.front(); + if (context->accessee.tokenIdHash.empty()) { + context->accessee.bindLevel = SERVICE; // SA-SA + } else { + context->accessee.bindLevel = APP; // FA-FA + } + if (credType == DM_IDENTICAL_ACCOUNT || credType == DM_ACROSS_ACCOUNT) { + context->accesser.bindLevel = DEVICE; // Exceptions: account related is DEVICE + } + std::vector sinkCredTypeLists = context->accessee.credentialTypeLists; if (std::find(sinkCredTypeLists.begin(), sinkCredTypeLists.end(), credType) == sinkCredTypeLists.end()) { LOGI("AuthSinkConfirmState::NegotiateCredential credType %{public}d not found in sink", credType); @@ -245,10 +264,10 @@ void AuthSinkConfirmState::NegotiateCredential(std::shared_ptr co } JsonObject credInfo(context->accessee.credentialInfos[credType]); - if (credInfo.Contains("id") && credInfo["id"].IsString()) { + if (credInfo.Contains(TAG_CRED_ID) && credInfo[TAG_CRED_ID].IsString()) { sinkCredTypeLists.clear(); sinkCredTypeLists.push_back(credType); - context->accessee.transmitCredentialId = credInfo["id"].Get(); + context->accessee.transmitCredentialId = credInfo[TAG_CRED_ID].Get(); } return; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 70eaee430..dcc0150b2 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -149,7 +149,6 @@ DmAuthStateType AuthSinkNegotiateStateMachine::GetStateType() int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptr context) { int32_t ret; - int32_t dmRole = DM_ROLE_UNKNOWN; // 1. Get deviceId char localDeviceId[DEVICE_UUID_LENGTH] = {0}; @@ -175,15 +174,18 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptraccessee.userId, tmpBundleName, 0, tokenId); if (ret != DM_OK) { - // If bundleName is not passed and tokenId cannot be obtained, it is an FA-device. - if (context->accessee.bundleName.empty()) { - dmRole = DM_ROLE_FA_TO_DEVICE; - LOGI("RespQueryTokenId: FA to device"); - return DM_OK; - } LOGE("RespQueryTokenId: get tokenId by bundleName failed %{public}s", GetAnonyString(context->accessee.bundleName).c_str()); - return ERR_DM_FAILED; + if (AppManager::GetInstance().GetNativeTokenIdByName(tmpBundleName, tokenId) != DM_OK) { + // it is FA-device, reject + LOGE("RespQueryTokenId: FA-device, reject"); + context->reason = ERR_DM_NOT_SYSTEM_APP; + context->reply = ERR_DM_NOT_SYSTEM_APP; + return ERR_DM_NOT_SYSTEM_APP; + } + + LOGI("RespQueryTokenId: SA-SA"); + return DM_OK; } context->accessee.bundleName = tmpBundleName; context->accessee.tokenId = static_cast(tokenId); -- Gitee From 9c309f0f6c6a25042edfc90350eedaa94ce49c71 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 27 Mar 2025 10:52:29 +0800 Subject: [PATCH 305/382] remove old pin auth before 326 --- .../authentication_v2/dm_auth_context.h | 2 - .../include/authentication_v2/dm_auth_state.h | 9 -- .../auth_stages/auth_confirm.cpp | 131 +----------------- .../auth_stages/auth_negotiate.cpp | 100 ------------- .../auth_stages/auth_pin_auth.cpp | 57 +------- .../dm_auth_message_processor.cpp | 27 +--- .../dm_auth_state_machine.cpp | 3 - 7 files changed, 6 insertions(+), 323 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 52c801096..70a38343a 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -15,7 +15,6 @@ #ifndef OHOS_DM_AUTH_CONTEXT_V2_H #define OHOS_DM_AUTH_CONTEXT_V2_H -#define NEW_PIN_AUTH326 #include #include @@ -154,7 +153,6 @@ struct DmAuthContext { 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}; // todo del DmAuthType authType{DmAuthType::AUTH_TYPE_PIN}; // PIN code, ultrasonic PIN code, imported PIN code std::vector authTypeList; uint32_t currentAuthTypeIdx{0}; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 3d73569b0..727db282c 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -130,8 +130,6 @@ public: private: void NegotiateCredential(std::shared_ptr context); void NegotiateAcl(std::shared_ptr context); - int32_t NoNeedAction(std::shared_ptr context); - int32_t DoPinAuth(std::shared_ptr context); // todo del }; class AuthSinkStatePinAuthComm { @@ -151,11 +149,9 @@ private: void NegotiateCredential(std::shared_ptr context); void NegotiateAcl(std::shared_ptr context); int32_t ShowConfigDialog(std::shared_ptr context); -#ifdef NEW_PIN_AUTH326 // todo enable void ReadServiceInfo(std::shared_ptr context); void MatchFallBackCandidateList(std::shared_ptr context, DmAuthType authType); bool IsAuthCodeReady(std::shared_ptr context); -#endif }; class AuthSrcPinNegotiateStartState : public DmAuthState { @@ -163,10 +159,8 @@ public: virtual ~AuthSrcPinNegotiateStartState() {}; DmAuthStateType GetStateType() override; int32_t Action(std::shared_ptr context) override; -#ifdef NEW_PIN_AUTH326 private: int32_t NegotiatePinAuth(std::shared_ptr context, bool firstTime); -#endif }; class AuthSrcPinInputState : public DmAuthState { @@ -344,9 +338,6 @@ public: private: int32_t RespQueryAcceseeIds(std::shared_ptr context); int32_t ProcRespNegotiate5_1_0(std::shared_ptr context); - void MatchFallBackCandidateList(std::shared_ptr context, DmAuthType authType); // todo del - bool IsAuthCodeReady(std::shared_ptr context); // todo del - void NegotiatePinAuthType(std::shared_ptr context); // todo del }; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 6169844fb..8272a0805 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -32,9 +32,6 @@ constexpr const char* TAG_LOCAL_DEVICE_TYPE = "LOCALDEVICETYPE"; constexpr const char* TAG_REQUESTER = "REQUESTER"; constexpr const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; -std::set g_shareByPinAuthDeviceTypeSet{DmDeviceType::DEVICE_TYPE_SMART_DISPLAY}; // todo del - -#ifdef NEW_PIN_AUTH326 // authType fallback table using FallBackKey = std::pair; // accessee.bundleName, authType static std::map g_pinAuthTypeFallBackMap = { @@ -42,48 +39,12 @@ static std::map g_pinAuthTypeFallBackMap = { }; // Maximum number of recursive lookups constexpr size_t MAX_FALLBACK_LOOPKUP_TIMES = 2; -#endif DmAuthStateType AuthSrcConfirmState::GetStateType() { return DmAuthStateType::AUTH_SRC_CONFIRM_STATE; } -int32_t AuthSrcConfirmState::DoPinAuth(std::shared_ptr context) -{ - LOGI("AuthSrcConfirmState::DoPinAuth start"); - int32_t authResult = context->authResult; - if (authResult != USER_OPERATION_TYPE_ALLOW_AUTH && - authResult != USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS) { - LOGE("AuthSrcConfirmState::DoPinAuth authResult not allow"); - context->reason = ERR_DM_BIND_USER_CANCEL; - return ERR_DM_BIND_USER_CANCEL; - } - - if (context->authTypeList.empty()) { - LOGE("AuthSrcConfirmState::DoPinAuth authTypeList empty"); - context->reason = ERR_DM_UNSUPPORTED_AUTH_TYPE; - return ERR_DM_UNSUPPORTED_AUTH_TYPE; - } - - context->currentAuthTypeIdx = 0; - context->authType = context->authTypeList[0]; - if (!context->authResultReady) { - // send 100 msg - context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_REQ_USER_CONFIRM, context); - - context->timer->StartTimer(std::string(CONFIRM_TIMEOUT_TASK), - DmAuthState::GetTaskTimeout(context, CONFIRM_TIMEOUT_TASK, CONFIRM_TIMEOUT), - [context] (std::string name) { - HandleAuthenticateTimeout(context, name); - }); - } else { - // skip 100, 110 msg - context->authStateMachine->TransitionTo(std::make_shared()); - } - return DM_OK; -} - void AuthSrcConfirmState::NegotiateCredential(std::shared_ptr context) { std::vector srcCredTypeList = context->accesser.credentialTypeLists; @@ -129,38 +90,6 @@ void AuthSrcConfirmState::NegotiateAcl(std::shared_ptr context) return; } -#ifndef NEW_PIN_AUTH326 -int32_t AuthSrcConfirmState::Action(std::shared_ptr context) -{ - LOGI("AuthSrcConfirmState::Action start"); - // check version compatibility - context->timer->DeleteTimer(std::string(NEGOTIATE_TIMEOUT_TASK)); - if (CompareVersion(context->accessee.dmVersion, std::string(DM_VERSION_5_1_0))) { - LOGE("AuthSrcConfirmState::Action incompatible version %{public}s compare to 5.1.0", - context->accessee.dmVersion.c_str()); - context->reason = ERR_DM_VERSION_INCOMPATIBLE; - return ERR_DM_VERSION_INCOMPATIBLE; - } - - int32_t ret = GetAuthCredentialInfo(context); - if (ret != DM_OK) { - LOGE("AuthSrcConfirmState::Action GetAuthCredentialInfo failed"); - return false; - } - - NegotiateCredential(context); - NegotiateAcl(context); - - // if (!NeedReqUserConfirm(context)) { - // context->authStateMachine->TransitionTo(std::make_shared()); - // LOGI("AuthSrcConfirmState::Action no need action"); - // return DM_OK; - // } - - // no credential, try to do pin auth - return DoPinAuth(context); -} -#else int32_t AuthSrcConfirmState::Action(std::shared_ptr context) { LOGI("AuthSrcConfirmState::Action start"); @@ -200,7 +129,7 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) }); return DM_OK; } -#endif + DmAuthStateType AuthSinkConfirmState::GetStateType() { return DmAuthStateType::AUTH_SINK_CONFIRM_STATE; @@ -274,7 +203,7 @@ void AuthSinkConfirmState::NegotiateAcl(std::shared_ptr context) return; } -#ifdef NEW_PIN_AUTH326 + void AuthSinkConfirmState::MatchFallBackCandidateList( std::shared_ptr context, DmAuthType authType) { @@ -327,13 +256,12 @@ void AuthSinkConfirmState::ReadServiceInfo(std::shared_ptr contex } else { context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; } - context->authResultReady = true; } context->customData = srvInfo.GetDescription(); // read customData } else if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE && IsAuthCodeReady(context)) { // only special scenarios can import pincode context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // no authorization box - context->authResultReady = true; + } else { // not special scenarios, reset authResult to cancel context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; @@ -397,59 +325,6 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; return ERR_DM_UNSUPPORTED_AUTH_TYPE; } -#else -int32_t AuthSinkConfirmState::Action(std::shared_ptr context) -{ - LOGI("AuthSinkConfirmState::Action start"); - context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); - - NegotiateCredential(context); - NegotiateAcl(context); - - if (context->authTypeList.empty()) { - LOGE("AuthSinkConfirmState::Action authTypeList empty"); - context->reason = ERR_DM_UNSUPPORTED_AUTH_TYPE; - return ERR_DM_UNSUPPORTED_AUTH_TYPE; - } - context->authType = context->authTypeList[context->currentAuthTypeIdx]; - - if (context->authBoxType == DistributedDeviceProfile::NUM_1) { // tristate box - LOGI("AuthSinkConfirmState::Action 3box"); - // show user confirmation dialog - auto ret = ShowConfigDialog(context); - if (ret != DM_OK) { - return ret; - } - // wait for user opration - if (DmEventType::ON_USER_OPERATION != - context->authStateMachine->WaitExpectEvent(DmEventType::ON_USER_OPERATION)) { - LOGE("AuthSinkConfirmState::Action wait ON_USER_OPERATION err"); - return STOP_BIND; - } - if (context->reply != USER_OPERATION_TYPE_ALLOW_AUTH) { - LOGI("AuthSinkConfirmState::Action USER_OPERATION_TYPE_CANCEL_AUTH"); - context->reason = ERR_DM_BIND_USER_CANCEL; - return STOP_BIND; - } - } else if (context->authBoxType == DistributedDeviceProfile::NUM_2) { // no authorization box - if (context->authResult == USER_OPERATION_TYPE_CANCEL_AUTH) { - LOGI("AuthSinkConfirmState::Action USER_OPERATION_TYPE_CANCEL_AUTH"); - context->reason = ERR_DM_BIND_USER_CANCEL; - return STOP_BIND; - } - } else { - LOGE("AuthSinkConfirmState::Action authBoxType not support"); - context->reason = ERR_DM_UNSUPPORTED_AUTH_TYPE; - return ERR_DM_UNSUPPORTED_AUTH_TYPE; - } - - // send 110 msg - context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); - - context->authStateMachine->TransitionTo(std::make_shared()); - return DM_OK; -} -#endif } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 70eaee430..d6a3cd131 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -48,14 +48,6 @@ namespace DistributedHardware { namespace { -// authType fallback table -using FallBackKey = std::pair; // accessee.bundleName, authType -static std::map g_pinAuthTypeFallBackMap = { - {{"cast_engine_service", DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE}, DmAuthType::AUTH_TYPE_PIN}, -}; -// Maximum number of recursive lookups -constexpr size_t MAX_FALLBACK_LOOPKUP_TIMES = 2; - enum DmRole { DM_ROLE_UNKNOWN = 0, DM_ROLE_FA_TO_FA, @@ -210,95 +202,6 @@ int32_t AuthSinkNegotiateStateMachine::ProcRespNegotiate5_1_0(std::shared_ptr context, DmAuthType authType) -{ - for (size_t i = 0; i < MAX_FALLBACK_LOOPKUP_TIMES; i++) { - auto it = g_pinAuthTypeFallBackMap.find({context->accessee.bundleName, authType}); - if (it != g_pinAuthTypeFallBackMap.end()) { - authType = it->second; - context->authTypeList.push_back(authType); - } else { - break; - } - } -} - -bool AuthSinkNegotiateStateMachine::IsAuthCodeReady(std::shared_ptr context) -{ - if (context->importAuthCode.empty() || context->importSessionName.empty()) { - LOGE("AuthSinkNegotiateStateMachine::IsAuthCodeReady, auth code not ready."); - return false; - } - if (context->sessionName != context->importSessionName) { - LOGE("AuthSinkNegotiateStateMachine::IsAuthCodeReady sessionName %{public}s not supported with " - "import sessionName %{public}s.", context->sessionName.c_str(), context->importSessionName.c_str()); - return false; - } - - return true; -} - -void AuthSinkNegotiateStateMachine::NegotiatePinAuthType(std::shared_ptr context) -{ - context->authTypeList.clear(); - // query ServiceInfo by accessee.bundleName and authType from client - OHOS::DistributedDeviceProfile::LocalServiceInfo srvInfo; - auto ret = DeviceProfileConnector::GetInstance().GetLocalServiceInfoByBundleNameAndPinExchangeType( - context->accessee.bundleName, context->authType, srvInfo); - if (ret == OHOS::DistributedDeviceProfile::DP_SUCCESS) { - // ServiceInfo found - context->authTypeList.push_back(context->authType); - context->authBoxType = srvInfo.GetAuthBoxType(); - - if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { - // read pincode - std::string pinCode = srvInfo.GetPinCode(); - context->pinCode = std::stoi(pinCode); - } - - if (context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { // no authorization box - int32_t authResult = srvInfo.GetAuthType(); - if (authResult == 0) { - context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH; - } else if (authResult == OHOS::DistributedDeviceProfile::NUM_1) { - context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; - } else if (authResult == OHOS::DistributedDeviceProfile::NUM_6) { - context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; - } else { - context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; - } - context->authResultReady = true; - } else { - context->customData = srvInfo.GetDescription(); - } - } else { - context->authBoxType = OHOS::DistributedDeviceProfile::NUM_1; // default: tristate box - - if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { - // need to check if pincode ready - if (IsAuthCodeReady(context)) { - // only special scenarios can import pincode - context->authTypeList.push_back(context->authType); - context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // no authorization box - context->authResultReady = true; - } - } else { - // match fail, also add src's authType - context->authTypeList.push_back(context->authType); - } - // not special scenarios, reset authResult to cancel - if (context->authBoxType != OHOS::DistributedDeviceProfile::NUM_2) { - context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; - } - } - // lookup fallback table - MatchFallBackCandidateList(context, context->authType); - if (context->authTypeList.size() > 0) { - context->authType = context->authTypeList[0]; - } -} - int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr context) { LOGI("AuthSinkNegotiateStateMachine::Action sessionid %{public}d", context->sessionId); @@ -332,9 +235,6 @@ int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr con LOGE("AuthSinkNegotiateStateMachine::Action proc response negotiate failed"); return ret; } -#ifndef NEW_PIN_AUTH326 // todo rm -R - NegotiatePinAuthType(context); -#endif context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_ACL_NEGOTIATE, context); context->timer->StartTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK), DmAuthState::GetTaskTimeout(context, WAIT_REQUEST_TIMEOUT_TASK, WAIT_REQUEST_TIMEOUT), diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 92449d69a..528c4600f 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -281,7 +281,7 @@ DmAuthStateType AuthSrcPinNegotiateStartState::GetStateType() { return DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE; } -#ifdef NEW_PIN_AUTH326 + int32_t AuthSrcPinNegotiateStartState::NegotiatePinAuth(std::shared_ptr context, bool firstTime) { if (firstTime) { @@ -353,61 +353,6 @@ int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr con } return NegotiatePinAuth(context, false); } -#else -int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr context) -{ - // if (!NeedPinAuth(context)) { - // context->authStateMachine->TransitionTo(std::make_shared()); - // return DM_OK; - // } - - if (!context->pinNegotiateStarted) { - context->pinNegotiateStarted = true; - context->timer->DeleteTimer(std::string(CONFIRM_TIMEOUT_TASK)); - int32_t authResult = context->authResult; - if (context->authTypeList.empty() || - (authResult != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH && - authResult != UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS)) { - LOGE("AuthSrcPinNegotiateStartState::Action authResult not allow"); - context->reason = ERR_DM_BIND_USER_CANCEL; - return ERR_DM_BIND_USER_CANCEL; - } - } else { - if (context->authType == DmAuthType::AUTH_TYPE_PIN && - context->inputPinAuthFailTimes < MAX_AUTH_INPUT_PIN_FAIL_TIMES) { - LOGI("AuthSrcPinNegotiateStartState::Action input pin auth err, retry"); - } else { - // try to fallback to next auth type - if (context->currentAuthTypeIdx + 1 >= context->authTypeList.size()) { - LOGE("AuthSrcPinNegotiateStartState::Action all auth type failed"); - context->reason = ERR_DM_AUTH_REJECT; - return ERR_DM_AUTH_REJECT; - } - context->currentAuthTypeIdx++; - context->authType = context->authTypeList[context->currentAuthTypeIdx]; - } - } - - // restart pin auth timer - context->timer->DeleteTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK)); - context->timer->StartTimer(std::string(WAIT_PIN_AUTH_TIMEOUT_TASK), - DmAuthState::GetTaskTimeout(context, WAIT_PIN_AUTH_TIMEOUT_TASK, PIN_AUTH_TIMEOUT), - [context] (std::string name) { - HandleAuthenticateTimeout(context, name); - }); - if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { - context->authStateMachine->TransitionTo(std::make_shared()); - } else if (context->authType == DmAuthType::AUTH_TYPE_PIN) { - context->authStateMachine->TransitionTo(std::make_shared()); - } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { - context->authStateMachine->TransitionTo(std::make_shared()); - } else { - LOGE("AuthSrcPinNegotiateStartState::Action authType not support"); - return ERR_DM_FAILED; - } - return DM_OK; -} -#endif DmAuthStateType AuthSrcPinInputState::GetStateType() { diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 644bf9166..fa63636d9 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -516,7 +516,6 @@ int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr // 创建80报文 int32_t DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject) { - jsonObject[TAG_AUTH_TYPE] = context->authType; // todo del jsonObject[TAG_SESSION_NAME] = context->sessionName; jsonObject[DM_TAG_DMVERSION] = context->accesser.dmVersion; @@ -556,10 +555,6 @@ int32_t DmAuthMessageProcessor::CreateRespNegotiateMessage(std::shared_ptraccessee.isAuthed; jsonObject[TAG_CERT_INFO] = vectorInt32ToString(context->accessee.credentialTypeLists); - jsonObject[DM_TAG_AUTH_TYPE_LIST] = vectorAuthTypeToString(context->authTypeList); // todo del - if (context->authResultReady) { - jsonObject[DM_TAG_AUTH_RESULT] = context->authResult; - } return DM_OK; } @@ -899,9 +894,6 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(const JsonObject &jsonObje if (jsonObject[TAG_BIND_LEVEL].IsNumberInteger()) { context->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].Get(); } - if (jsonObject[TAG_AUTH_TYPE].IsNumberInteger()) { // todo del - context->authType = static_cast(jsonObject[TAG_AUTH_TYPE].Get()); - } if (jsonObject.Contains(DM_TAG_EXTRA_INFO) && jsonObject[DM_TAG_EXTRA_INFO].IsObject()) { ParseNegotiateExtraInfoMessage(jsonObject[DM_TAG_EXTRA_INFO], context); @@ -953,16 +945,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const JsonObject &j if (jsonObject[TAG_CERT_INFO].IsString()) { context->accessee.credentialTypeLists = stringToVectorInt32(jsonObject[TAG_CERT_INFO].Get()); } -#ifndef NEW_PIN_AUTH326 // todo del - if (jsonObject[DM_TAG_AUTH_TYPE_LIST].IsString()) { - auto strList = jsonObject[DM_TAG_AUTH_TYPE_LIST].Get(); - context->authTypeList = stringToVectorAuthType(strList); - } - if (jsonObject.Contains(DM_TAG_AUTH_RESULT) && jsonObject[DM_TAG_AUTH_RESULT].IsNumberInteger()) { - context->authResult = static_cast(jsonObject[DM_TAG_AUTH_RESULT].Get()); - context->authResultReady = true; - } -#endif + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -976,15 +959,12 @@ int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const JsonObject &jso if (json[TAG_DEVICE_NAME].IsString()) { context->accesser.deviceName = json[TAG_DEVICE_NAME].Get(); } -#ifdef NEW_PIN_AUTH326 if (json[TAG_AUTH_TYPE].IsNumberInteger()) { context->authType = static_cast(json[TAG_AUTH_TYPE].Get()); } - // todo parse authform if (json[TAG_CERT_INFO].IsString()) { context->accesser.credentialTypeLists = stringToVectorInt32(json[TAG_CERT_INFO].Get()); } -#endif context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -996,12 +976,11 @@ int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const JsonObject &js context->authResult = static_cast(json[DM_TAG_AUTH_RESULT].Get()); } -#ifdef NEW_PIN_AUTH326 if (json[DM_TAG_AUTH_TYPE_LIST].IsString()) { auto strList = json[DM_TAG_AUTH_TYPE_LIST].Get(); context->authTypeList = stringToVectorAuthType(strList); } -#endif + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -1040,8 +1019,6 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate(const JsonObject int32_t DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json) { json[TAG_AUTH_TYPE] = context->authType; - // todo send authform - json[TAG_CERT_INFO] = vectorInt32ToString(context->accesser.credentialTypeLists); json[TAG_DEVICE_TYPE] = context->accesser.deviceType; json[TAG_DEVICE_NAME] = context->accesser.deviceName; diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 0c9a80ee2..795aeec3e 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -61,7 +61,6 @@ void DmAuthStateMachine::InsertSrcTransTable() {DmAuthStateType::AUTH_SRC_CONFIRM_STATE, { DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, DmAuthStateType::AUTH_SRC_DATA_SYNC_STATE, - DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, // todo del }}, {DmAuthStateType::AUTH_SRC_PIN_NEGOTIATE_START_STATE, { DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_START_STATE, @@ -116,8 +115,6 @@ void DmAuthStateMachine::InsertSinkTransTable() {DmAuthStateType::AUTH_IDLE_STATE, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE}}, {DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE, { DmAuthStateType::AUTH_SINK_CONFIRM_STATE, - DmAuthStateType::AUTH_SINK_PIN_AUTH_START_STATE, // todo del - DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, // todo del }}, {DmAuthStateType::AUTH_SINK_CONFIRM_STATE, { DmAuthStateType::AUTH_SINK_PIN_NEGOTIATE_START_STATE, -- Gitee From 9a73a0f6581b55a2fe29b0fc101c8072310181f3 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 27 Mar 2025 10:59:21 +0800 Subject: [PATCH 306/382] style --- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 75e1f2d97..10b3d6a0c 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -280,7 +280,6 @@ void AuthSinkConfirmState::ReadServiceInfo(std::shared_ptr contex } else if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE && IsAuthCodeReady(context)) { // only special scenarios can import pincode context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // no authorization box - } else { // not special scenarios, reset authResult to cancel context->authResult = UiAction::USER_OPERATION_TYPE_CANCEL_AUTH; -- Gitee From 550251287d9fb1eec0ab53e2463a7f1d20cafe97 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Thu, 27 Mar 2025 14:48:56 +0800 Subject: [PATCH 307/382] =?UTF-8?q?feat:=20=E5=BE=AE=E8=B0=83=E5=87=AD?= =?UTF-8?q?=E6=8D=AE=E5=A4=84=E7=90=86=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_state.cpp | 39 ++++++++++++------- 1 file changed, 26 insertions(+), 13 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index f2724fabc..c57fd981f 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -119,6 +119,7 @@ int32_t DmQueryCredential(std::shared_ptr context, JsonObject &qu "query credentialInfo: %{public}s", access.userId, queryParams.Dump().c_str(), queryResult.Dump().c_str()); + std::vector credTypeList; for (auto& item : queryResult.Items()) { // 确认凭据类型 credType = GetCredentialType(context, item); @@ -129,7 +130,16 @@ int32_t DmQueryCredential(std::shared_ptr context, JsonObject &qu item[FILED_CRED_TYPE] = credType; // TODO: 确认credInfo中是否有id信息 access.credentialInfos[credType] = item.Dump(); + // duplicate acl and credType is not allowed + if (std::find(credTypeList.begin(), credTypeList.end(), credType) != credTypeList.end()) { + LOGE("DmQueryCredential duplicate credType %{public}d", credType); + context->reply = ERR_DM_FAILED; + context->reason = ERR_DM_FAILED; + return ERR_DM_FAILED; + } + credTypeList.push_back(credType); } + access.credentialTypeLists = credTypeList; return DM_OK; } @@ -290,7 +300,6 @@ int32_t DmAuthState::GetAuthCredentialInfo(std::shared_ptr contex { int32_t ret; JsonObject queryResult; - std::vector credTypeList; // 1. Retrieve all credentials ret = DmQueryCredential(context, queryResult); @@ -303,17 +312,29 @@ int32_t DmAuthState::GetAuthCredentialInfo(std::shared_ptr contex DmAccess access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; std::vector profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfile(); + LOGI("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo success to get %{public}ld acls", profiles.size()); for (const DistributedDeviceProfile::AccessControlProfile &item : profiles) { bool isAclMatched = false; DistributedDeviceProfile::Accesser accesser = item.GetAccesser(); DistributedDeviceProfile::Accessee accessee = item.GetAccessee(); // Ensure credentials match with ACL - std::string credId = std::to_string(accessee.GetAccesseeCredentialId()); + std::string credId = context->direction == DM_AUTH_SOURCE ? std::to_string(accesser.GetAccesserCredentialId()) : + std::to_string(accessee.GetAccesseeCredentialId()); + LOGI("Got acl: credId - %{public}d ", accessee.GetAccesseeCredentialId()); // TODO: delete if (!queryResult.Contains(credId) || item.GetStatus() != ACTIVE) { continue; } + // TODO: delete + LOGI("accesser: deviceId - %{public}s, userId - %{public}d, accountId - %{public}s, tokenId - %{public}ld", + accesser.GetAccesserDeviceId().c_str(), accesser.GetAccesserUserId(), + accesser.GetAccesserAccountId().c_str(), accesser.GetAccesserTokenId()); + LOGI("accessee: deviceId - %{public}s, userId - %{public}d, accountId - %{public}s, tokenId - %{public}ld", + accessee.GetAccesseeDeviceId().c_str(), accessee.GetAccesseeUserId(), + accessee.GetAccesseeAccountId().c_str(), accessee.GetAccesseeTokenId()); + + LOGI("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo success to get acl %{public}s", item.dump().c_str()); // Confirm if there is a trusted relationship uint32_t credType = queryResult[credId][FILED_CRED_TYPE].Get(); if (credType == DM_IDENTICAL_ACCOUNT || credType == DM_ACROSS_ACCOUNT) { @@ -321,19 +342,13 @@ int32_t DmAuthState::GetAuthCredentialInfo(std::shared_ptr contex } else if (credType == DM_POINT_TO_POINT) { isAclMatched = AclCompareFourIds(context, accesser, accessee); } - + if (isAclMatched) { - credTypeList.push_back(credType); access.aclProfiles[credType] = item; - LOGI("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo success to get credType %{public}d", credType); + LOGI("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo get acl credType %{public}d", credType); } } - if (!credTypeList.empty()) { - access.credentialTypeLists = credTypeList; - access.isAuthed = true; - } - return DM_OK; } @@ -382,9 +397,7 @@ bool DmAuthState::NeedAgreeCredential(std::shared_ptr context) bool DmAuthState::NeedAgreeAcl(std::shared_ptr context) { - DmAccess access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; - DmAccess remoteAccess = context->direction == DM_AUTH_SOURCE ? context->accessee : context->accesser; - return access.transmitSessionKeyId != 0 && access.transmitSessionKeyId != 0; + return context->accesser.isAuthed && context->accessee.isAuthed; } } // namespace DistributedHardware -- Gitee From afb168c712c64683d1849f41dc5eea4e48939171 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Thu, 27 Mar 2025 15:13:18 +0800 Subject: [PATCH 308/382] =?UTF-8?q?=E4=BF=AE=E6=94=B9codecheck?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../implementation/src/authentication_v2/dm_auth_state.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index c57fd981f..95d4482f4 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -240,7 +240,8 @@ void DmAuthState::SourceFinish(std::shared_ptr context) if (context->reason != DM_OK) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); // 根据凭据id 删除sink端多余的凭据 - int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, context->accesser.transmitCredentialId); // 这里只删除1个应该是bug? + int32_t ret = + context->hiChainAuthConnector->DeleteCredential(accountId, context->accesser.transmitCredentialId); if (ret != DM_OK) { LOGE("SourceFinish DeleteCredential failed."); } @@ -263,7 +264,8 @@ void DmAuthState::SinkFinish(std::shared_ptr context) if (context->reason != DM_OK) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); // 根据凭据id 删除sink端多余的凭据 - int32_t ret = context->hiChainAuthConnector->DeleteCredential(accountId, context->accessee.transmitCredentialId); + int32_t ret = + context->hiChainAuthConnector->DeleteCredential(accountId, context->accessee.transmitCredentialId); if (ret != DM_OK) { LOGE("SinkFinish DeleteCredential failed."); } -- Gitee From 5638c005de480c58856138ca933bd4a7c369bbd9 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Thu, 27 Mar 2025 09:37:13 +0800 Subject: [PATCH 309/382] =?UTF-8?q?fix=EF=BC=9A=E6=B7=BB=E5=8A=A0is?= =?UTF-8?q?=E4=BA=A4=E4=BA=92=E6=8E=A5=E5=8F=A3=E7=9A=84=E6=97=A5=E5=BF=97?= =?UTF-8?q?=E6=89=93=E5=8D=B0=EF=BC=8C=E8=B0=83=E8=AF=95=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependency/hichain/hichain_auth_connector.cpp | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index c7094be88..ce6aacfc1 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -128,7 +128,7 @@ int32_t HiChainAuthConnector::AddCredential(int32_t osAccountId, const std::stri LOGI("HiChainAuthConnector::AddCredential addCredential success ret=%{public}d, returnData=%{public}s.", ret, returnData); credId = std::string(returnData); - LOGI("HiChainAuthConnector::AddCredential credId=%{public}s.", credId.c_str()); + LOGI("HiChainAuthConnector::AddCredential addCredId=%{public}s.", credId.c_str()); free(returnData); LOGI("HiChainAuthConnector::AddCredential leave."); return DM_OK; @@ -140,7 +140,8 @@ int32_t HiChainAuthConnector::AddCredential(int32_t osAccountId, const std::stri // publicKey 公钥 int32_t HiChainAuthConnector::ExportCredential(int32_t osAccountId, const std::string &credId, std::string &publicKey) { - LOGI("HiChainAuthConnector::ExportCredential start."); + LOGI("HiChainAuthConnector::ExportCredential start. osAccountId=%{public}d, credId=%{public}s", + osAccountId, credId.c_str()); char *returnData = NULL; const CredManager *credManager = GetCredMgrInstance(); int32_t ret = credManager->exportCredential(osAccountId, credId.c_str(), &returnData); @@ -159,7 +160,7 @@ int32_t HiChainAuthConnector::ExportCredential(int32_t osAccountId, const std::s } publicKey = jsonAuthParam["keyValue"].Get(); - LOGI("HiChainAuthConnector::ExportCredential leave."); + LOGI("HiChainAuthConnector::ExportCredential leave. publicKey=%{public}s", publicKey.c_str()); return DM_OK; } @@ -183,7 +184,7 @@ int32_t HiChainAuthConnector::AgreeCredential(int32_t osAccountId, const std::st } credId = returnData; free(returnData); - LOGI("HiChainAuthConnector::AgreeCredential leave."); + LOGI("HiChainAuthConnector::AgreeCredential leave agreeCredId=%{public}s.", credId.c_str()); return DM_OK; } @@ -192,7 +193,8 @@ int32_t HiChainAuthConnector::AgreeCredential(int32_t osAccountId, const std::st // credId 待删除的凭据Id int32_t HiChainAuthConnector::DeleteCredential(int32_t osAccountId, const std::string &credId) { - LOGI("HiChainAuthConnector::DeleteCredential start."); + LOGI("HiChainAuthConnector::DeleteCredential start. osAccountId=%{public}d, credId=%{public}s", osAccountId, + credId.c_str()); const CredManager *credManager = GetCredMgrInstance(); int32_t ret = credManager->deleteCredential(osAccountId, credId.c_str()); if (ret != HC_SUCCESS) { @@ -211,7 +213,8 @@ int32_t HiChainAuthConnector::DeleteCredential(int32_t osAccountId, const std::s int32_t HiChainAuthConnector::AuthCredential(int32_t osAccountId, int64_t authReqId, const std::string &credId, const std::string &pinCode) { - LOGI("HiChainAuthConnector::AuthCredential start."); + LOGI("HiChainAuthConnector::AuthCredential start. osAccountId=%{public}d, credId=%{public}s", osAccountId, + credId.c_str()); if (credId.empty() && pinCode.empty()) { LOGE("HiChainAuthConnector::AuthCredential failed, credId and pinCode is empty."); return ERR_DM_FAILED; -- Gitee From 293a1e0d66d5e097b169427aedc2a3e25b9d6179 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Thu, 27 Mar 2025 16:29:41 +0800 Subject: [PATCH 310/382] =?UTF-8?q?fix=EF=BC=9A=E6=B3=A8=E9=87=8A=E6=94=B9?= =?UTF-8?q?=E4=B8=BA=E8=8B=B1=E6=96=87?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../auth_stages/auth_credential.cpp | 136 +++++++-------- .../dm_auth_message_processor.cpp | 155 ++++++++---------- 2 files changed, 124 insertions(+), 167 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 680ea9740..5fc3cbe31 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -13,19 +13,19 @@ * limitations under the License. */ #include -#include -#include #include -#include "dm_auth_state.h" +#include +#include #include "dm_auth_context.h" #include "dm_auth_manager_base.h" -#include "dm_auth_state_machine.h" #include "dm_auth_message_processor.h" -#include "dm_log.h" +#include "dm_auth_state.h" +#include "dm_auth_state_machine.h" #include "dm_constants.h" -#include "multiple_user_connector.h" +#include "dm_log.h" #include "deviceprofile_connector.h" #include "hichain_auth_connector.h" +#include "multiple_user_connector.h" namespace OHOS { namespace DistributedHardware { @@ -84,7 +84,7 @@ DmAuthStateType AuthSrcCredentialAuthNegotiateState::GetStateType() return DmAuthStateType::AUTH_SRC_CREDENTIAL_AUTH_NEGOTIATE_STATE; } -// parse the ontransmit data, respond with 161 message +// Parse the ontransmit data, respond with 161 message int32_t AuthSrcCredentialAuthNegotiateState::Action(std::shared_ptr context) { // decrypt and transmit transmitData @@ -92,7 +92,8 @@ int32_t AuthSrcCredentialAuthNegotiateState::Action(std::shared_ptr co LOGE("AuthSrcCredentialAuthDoneState::Action failed, ON_TRANSMIT event not arrived."); return ERR_DM_FAILED; } - } else if (context->isOnline == false) { - // 首次认证 且 用户凭据流程 - // 保存到DP 获取用户凭据ID 并保存 + } else if (context->isOnline == false) { // First-time authentication and Lnn credential process SetAuthContext(skId, context->accesser.lnnSkTimeStamp, context->accesser.lnnSessionKeyId); - msgType = MSG_TYPE_REQ_DATA_SYNC; // 发送180 - } else { - // 非首次认证 应用凭据流程 - // 保存到DP 获取应用凭据ID 并保存 + msgType = MSG_TYPE_REQ_DATA_SYNC; + } else { // Non-first-time authentication transport credential process SetAuthContext(skId, context->accesser.transmitSkTimeStamp, context->accesser.transmitSessionKeyId); - msgType = MSG_TYPE_REQ_DATA_SYNC; // 发送180 + msgType = MSG_TYPE_REQ_DATA_SYNC; } std::string message = - context->authMessageProcessor->CreateMessage(msgType, context); // 不需要额外传data,context中均有 + context->authMessageProcessor->CreateMessage(msgType, context); if (message.empty()) { LOGE("AuthSrcCredentialAuthDoneState::Action CreateMessage failed"); return ERR_DM_FAILED; @@ -160,21 +157,20 @@ int32_t AuthSrcCredentialAuthDoneState::Action(std::shared_ptr co return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); } -// SINK端凭据校验操作 DmAuthStateType AuthSinkCredentialAuthStartState::GetStateType() { return DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE; } -// 收到160凭证认证报文,发送170报文 + int32_t AuthSinkCredentialAuthStartState::Action(std::shared_ptr context) { context->timer->DeleteTimer(std::string(WAIT_REQUEST_TIMEOUT_TASK)); - // 解密并透传transmitData + int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_TRANSMIT); if (ret != DM_OK) { return ret; } - // 构造并发送170报文 + return AuthCredentialTransmitSend(context, DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_START); } @@ -183,19 +179,17 @@ DmAuthStateType AuthSinkCredentialAuthNegotiateState::GetStateType() return DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_NEGOTIATE_STATE; } -// 收到161凭据协商报文,并回复171报文 -// 通过isAppCredentialVerified关键词区分首次认证、非首次认证 int32_t AuthSinkCredentialAuthNegotiateState::Action(std::shared_ptr context) { - // 解密并透传transmitData int32_t ret = AuthCredentialTransmitDecryptProcess(context, ON_TRANSMIT); if (ret != DM_OK) { - return ret; // 内部有日志 不重复打印 + return ret; } - // 构造并发送171报文 + + // Construct and send 171 message ret = AuthCredentialTransmitSend(context, DmMessageType::MSG_TYPE_RESP_CREDENTIAL_AUTH_NEGOTIATE); if (ret != DM_OK) { - return ret; // 内部有日志 不重复打印 + return ret; } if (context->authStateMachine->WaitExpectEvent(ON_SESSION_KEY_RETURNED) != ON_SESSION_KEY_RETURNED) { @@ -214,14 +208,15 @@ int32_t AuthSinkCredentialAuthNegotiateState::Action(std::shared_ptrisOnline == false && - context->isAppCredentialVerified == true) { // SINK首次认证场景,第二次收到161的流程 保存用户级永久SK到DP + context->isAppCredentialVerified == true) { context->accessee.lnnSkTimeStamp = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) .count(); context->accessee.lnnSessionKeyId = skId; - } else { // 应用级凭据认证流程 首次认证的第一次161处理 和 非首次认证的161处理 - context->isAppCredentialVerified = true; // 用于指示 首次认证的应用级凭据已认证 + } else { // Twice transport cred auth + context->isAppCredentialVerified = true; context->accessee.transmitSkTimeStamp = std::chrono::duration_cast(std::chrono::system_clock::now().time_since_epoch()) .count(); @@ -230,15 +225,13 @@ int32_t AuthSinkCredentialAuthNegotiateState::Action(std::shared_ptr &authContext) { LOGI("AuthCredentialAgreeState::CreateAuthParamsString start."); - // 参数校验 + if ((authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP) || (method != DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE && method != DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT)) { return std::string(""); @@ -246,40 +239,38 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori JsonObject jsonObj; if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) { - jsonObj[DM_TAG_METHOD] = method; // 凭据生成方式,只有导入时,需要传入method + jsonObj[DM_TAG_METHOD] = method; } - jsonObj[DM_TAG_DEVICE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? // 设备ID 生成是本端,导入是对端 + jsonObj[DM_TAG_DEVICE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? authContext->GetDeviceId(DM_AUTH_LOCAL_SIDE) : authContext->GetDeviceId(DM_AUTH_REMOTE_SIDE); if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) { jsonObj[DM_TAG_PEER_USER_SPACE_ID] = std::to_string(authContext->GetUserId(DM_AUTH_REMOTE_SIDE)); } jsonObj[DM_TAG_USER_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? authContext->GetAccountId(DM_AUTH_LOCAL_SIDE) : authContext->GetAccountId(DM_AUTH_REMOTE_SIDE); - jsonObj[DM_TAG_SUBJECT] = DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY; // 主控设备 - jsonObj[DM_TAG_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; // 账号无关 + jsonObj[DM_TAG_SUBJECT] = DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY; + jsonObj[DM_TAG_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; jsonObj[DM_TAG_KEY_FORMAT] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? - DM_AUTH_KEY_FORMAT_ASYMM_GENERATE : DM_AUTH_KEY_FORMAT_ASYMM_IMPORT; // 生成或导入非对称秘钥 - jsonObj[DM_TAG_ALGORITHM_TYPE] = DM_AUTH_ALG_TYPE_ED25519; // ED25519 - jsonObj[DM_TAG_PROOF_TYPE] = DM_AUTH_CREDENTIAL_PROOF_PSK; // PSK - if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) { // 导入公钥 16进制字符串 + DM_AUTH_KEY_FORMAT_ASYMM_GENERATE : DM_AUTH_KEY_FORMAT_ASYMM_IMPORT; + jsonObj[DM_TAG_ALGORITHM_TYPE] = DM_AUTH_ALG_TYPE_ED25519; + jsonObj[DM_TAG_PROOF_TYPE] = DM_AUTH_CREDENTIAL_PROOF_PSK; + if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) { jsonObj[DM_TAG_KEY_VALUE] = authContext->GetPublicKey(DM_AUTH_REMOTE_SIDE, authorizedScope); } - jsonObj[DM_TAG_AUTHORIZED_SCOPE] = authorizedScope; // 用户级或者应用级 + jsonObj[DM_TAG_AUTHORIZED_SCOPE] = authorizedScope; if (authorizedScope == DM_AUTH_SCOPE_APP) { std::vector tokenIds = {std::to_string(authContext->accesser.tokenId), std::to_string(authContext->accessee.tokenId)}; jsonObj[DM_TAG_AUTHRIZED_APP_LIST] = tokenIds; } - jsonObj[DM_TAG_CREDENTIAL_OWNER] = DM_AUTH_CREDENTIAL_OWNER; // 调用方包名DM模块 + jsonObj[DM_TAG_CREDENTIAL_OWNER] = DM_AUTH_CREDENTIAL_OWNER; LOGI("AuthCredentialAgreeState::CreateAuthParamsString leave."); return jsonObj.Dump(); } -// 生成凭据Id和公钥 -// authorizedScope 用户级还是应用级 -// authContext 上下文 +// Generate credential ID and public key int32_t AuthCredentialAgreeState::GenerateCredIdAndPublicKey(DmAuthScope authorizedScope, std::shared_ptr &authContext) { @@ -289,7 +280,6 @@ int32_t AuthCredentialAgreeState::GenerateCredIdAndPublicKey(DmAuthScope authori return ERR_DM_FAILED; } - // 创建authParams的json格式字符串 std::string authParamsString = CreateAuthParamsString(authorizedScope, DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE, authContext); if (authParamsString == "") { @@ -297,7 +287,6 @@ int32_t AuthCredentialAgreeState::GenerateCredIdAndPublicKey(DmAuthScope authori return ERR_DM_FAILED; } - // 生成凭据 int32_t osAccountId = (authContext->direction == DM_AUTH_SOURCE) ? authContext->accesser.userId : authContext->accessee.userId; std::string credId; @@ -307,7 +296,6 @@ int32_t AuthCredentialAgreeState::GenerateCredIdAndPublicKey(DmAuthScope authori return ret; } - // 导出公钥 std::string publicKey; ret = authContext->hiChainAuthConnector->ExportCredential(osAccountId, credId, publicKey); if (ret != DM_OK) { @@ -316,7 +304,6 @@ int32_t AuthCredentialAgreeState::GenerateCredIdAndPublicKey(DmAuthScope authori return ret; } - // 保存凭据Id和公钥 (void)authContext->SetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope, credId); (void)authContext->SetPublicKey(DM_AUTH_LOCAL_SIDE, authorizedScope, publicKey); LOGI("AuthCredentialAgreeState::GenerateCredIdAndPublicKey credId=%{public}s, publicKey=%{public}s.\n", @@ -326,9 +313,7 @@ int32_t AuthCredentialAgreeState::GenerateCredIdAndPublicKey(DmAuthScope authori return DM_OK; } -// 协商凭据得到协商凭据Id -// authorizedScope 设备级还是应用级 -// authContext 上下文 +// Get the negotiation credential ID by agree credential int32_t AuthCredentialAgreeState::AgreeCredential(DmAuthScope authorizedScope, std::shared_ptr &authContext) { @@ -337,15 +322,13 @@ int32_t AuthCredentialAgreeState::AgreeCredential(DmAuthScope authorizedScope, return ERR_DM_FAILED; } - // 创建authParams的json格式字符串 std::string authParamsString = CreateAuthParamsString(authorizedScope, DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT, authContext); if (authParamsString == "") { - LOGE("AuthCredentialAgreeState::AgreeCredential() error, create authParamsString failed."); + LOGE("AuthCredentialAgreeState::AgreeCredential error, create authParamsString failed."); return ERR_DM_FAILED; } - // 凭据协商得到协商凭据Id int32_t osAccountId = authContext->direction == DM_AUTH_SOURCE ? authContext->accesser.userId : authContext->accessee.userId; std::string selfCredId = authContext->GetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope); @@ -353,10 +336,9 @@ int32_t AuthCredentialAgreeState::AgreeCredential(DmAuthScope authorizedScope, int32_t ret = authContext->hiChainAuthConnector->AgreeCredential(osAccountId, selfCredId, authParamsString, credId); if (ret != DM_OK) { - LOGE("AuthCredentialAgreeState::AgreeCredential() error, agree credential failed."); + LOGE("AuthCredentialAgreeState::AgreeCredential error, agree credential failed."); } - // 保存协商凭据Id到上下文 (void)authContext->SetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope, credId); LOGI("AuthCredentialAgreeState::AgreeCredential leave."); return DM_OK; @@ -373,7 +355,7 @@ int32_t AuthSrcCredentialExchangeState::Action(std::shared_ptr co int32_t ret = ERR_DM_FAILED; context->isAppCredentialVerified = false; - // 首次认证,生成用户级凭据和公钥 + // First authentication, generate LNN credentials and public key if (!context->isOnline) { ret = GenerateCredIdAndPublicKey(DM_AUTH_SCOPE_USER, context); if (ret != DM_OK) { @@ -382,14 +364,13 @@ int32_t AuthSrcCredentialExchangeState::Action(std::shared_ptr co } } - // 生成应用级凭据和公钥 + // Generate transmit credentials and public key ret = GenerateCredIdAndPublicKey(DM_AUTH_SCOPE_APP, context); if (ret != DM_OK) { LOGE("AuthSrcCredentialExchangeState::Action() error, generate app credId and publicKey failed."); return ret; } - // 发送140报文 std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_REQ_CREDENTIAL_EXCHANGE, context); LOGI("AuthSrcCredentialExchangeState::Action() leave."); return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); @@ -413,16 +394,16 @@ int32_t AuthSinkCredentialExchangeState::Action(std::shared_ptr c return ret; } - // 首次认证 + // First authentication lnn cred if (!context->isOnline) { - // 生成用户级凭据和公钥 + // Generate credentials and public key ret = GenerateCredIdAndPublicKey(DM_AUTH_SCOPE_USER, context); if (ret != DM_OK) { LOGE("AuthSinkCredentialExchangeState::Action failed, generate user cred and publicKey failed."); return ret; } - // 协商用户级凭据 + // Agree credentials tmpCredId = context->accessee.lnnCredentialId; ret = AgreeCredential(DM_AUTH_SCOPE_USER, context); if (ret != DM_OK) { @@ -432,18 +413,18 @@ int32_t AuthSinkCredentialExchangeState::Action(std::shared_ptr c return ret; } - // 删除临时用户级凭据 + // Delete temporary credentials context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); } - // 生成应用级凭据和公钥 + // Generate transport credentials and public key ret = GenerateCredIdAndPublicKey(DM_AUTH_SCOPE_APP, context); if (ret != DM_OK) { LOGE("AuthSinkCredentialExchangeState::Action failed, generate app cred and publicKey failed."); return ret; } - // 协商应用级公钥 + // Agree transport credentials and public key tmpCredId = context->accessee.transmitCredentialId; ret = AgreeCredential(DM_AUTH_SCOPE_APP, context); if (ret != DM_OK) { @@ -453,10 +434,9 @@ int32_t AuthSinkCredentialExchangeState::Action(std::shared_ptr c return ret; } - // 删除临时应用级凭据 + // Delete temporary transport credentials context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); - // 发送150报文 std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_RESP_CREDENTIAL_EXCHANGE, context); LOGI("AuthSinkCredentialExchangeState::Action leave."); return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); @@ -481,9 +461,9 @@ int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr c } if (NeedAgreeCredential(context)) { - // 首次认证 + // First authentication if (!context->isOnline) { - // 协商用户级凭据 + // Agree lnn credentials and public key tmpCredId = context->accesser.lnnCredentialId; ret = AgreeCredential(DM_AUTH_SCOPE_USER, context); if (ret != DM_OK) { @@ -493,11 +473,11 @@ int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr c return ret; } - // 删除临时用户级凭据 + // Delete temporary lnn credentials context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); } - // 协商应用级凭据 + // Agree transport credentials and public key tmpCredId = context->accesser.transmitCredentialId; ret = AgreeCredential(DM_AUTH_SCOPE_APP, context); if (ret != DM_OK) { @@ -507,11 +487,11 @@ int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr c return ret; } - // 删除临时应用级凭据 + // Delete temporary transport credentials context->hiChainAuthConnector->DeleteCredential(osAccountId, tmpCredId); } - // 凭据认证 先进行应用级 + // Transport credential authentication ret = context->hiChainAuthConnector->AuthCredential(osAccountId, context->requestId, context->accesser.transmitCredentialId, std::string("")); if (ret != DM_OK) { @@ -519,13 +499,11 @@ int32_t AuthSrcCredentialAuthStartState::Action(std::shared_ptr c return ret; } - // 阻塞等待事件ON_TRANSMIT事件到来 if (context->authStateMachine->WaitExpectEvent(ON_TRANSMIT) != ON_TRANSMIT) { LOGE("AuthSrcCredentialAuthStartState::Action failed, ON_TRANSMIT event not arrived."); return ERR_DM_FAILED; } - // 发送160报文 std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_REQ_CREDENTIAL_AUTH_START, context); LOGI(" AuthSrcCredentialAuthStartState::Action leave."); return context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index fa63636d9..ffed701b2 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -55,13 +55,11 @@ void CreateNegotiateExtraInfoMessage(std::shared_ptr context, Jso void ParseNegotiateExtraInfoMessage(const JsonItemObject &jsonExtraObject, std::shared_ptr context) { - // accesser在extra中传输对端peerUserId和peerDisplayId时,从中获取userId if (jsonExtraObject[DM_TAG_ACCESSEE_USER_ID].IsNumberInteger()) { context->accessee.userId = jsonExtraObject[DM_TAG_ACCESSEE_USER_ID].Get(); } else if (jsonExtraObject[DM_TAG_PEER_DISPLAY_ID].IsNumberInteger()) { context->accessee.displayId = jsonExtraObject[DM_TAG_PEER_DISPLAY_ID].Get(); } - return; } @@ -88,12 +86,12 @@ int32_t ParaseAclChecksumList(const std::string &jsonString, DmAccess &access) LOGE("ParseSyncMessage aclChecksumjson error"); return ERR_DM_FAILED; } - if (!aclChecksumjson[DM_TAG_ACCESSER].IsArray()) { // 再解析一次 acl + if (!aclChecksumjson[DM_TAG_ACCESSER].IsArray()) { LOGE("ParseSyncMessage DM_TAG_ACCESSER error"); return ERR_DM_FAILED; } aclChecksumjson[DM_TAG_ACCESSER].Get(access.accesserStrList); - if (!aclChecksumjson[DM_TAG_ACCESSEE].IsArray()) { // 再解析一次 acl + if (!aclChecksumjson[DM_TAG_ACCESSEE].IsArray()) { LOGE("ParseSyncMessage DM_TAG_ACCESSEE error"); return ERR_DM_FAILED; } @@ -116,7 +114,6 @@ bool IsMessageValid(const JsonItemObject &jsonObject) } -// 保存秘钥 int32_t DmAuthMessageProcessor::SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyLen) { if (cryptoMgr_ == nullptr) { @@ -126,7 +123,6 @@ int32_t DmAuthMessageProcessor::SaveSessionKey(const uint8_t *sessionKey, const return cryptoMgr_->SaveSessionKey(sessionKey, keyLen); } -// 保存永久SK int32_t DmAuthMessageProcessor::SaveSessionKeyToDP(int32_t &skId) { if (cryptoMgr_ == nullptr) { @@ -291,7 +287,6 @@ DmAuthMessageProcessor::~DmAuthMessageProcessor() } } -// 解析报文,返回值为错误码,实际解析出来的信息保存到context中 int32_t DmAuthMessageProcessor::ParseMessage(std::shared_ptr context, const std::string &message) { JsonObject jsonObject(message); @@ -338,7 +333,7 @@ static std::string vectorAuthTypeToString(const std::vector& vec) for (size_t i = 0; i < vec.size(); ++i) { oss << static_cast(vec[i]); if (i != vec.size() - 1) { - oss << " "; // 添加分隔符(例如空格) + oss << " "; // Add a separator (e.g. space) } } return oss.str(); @@ -350,7 +345,7 @@ static std::string vectorInt32ToString(const std::vector& vec) for (size_t i = 0; i < vec.size(); ++i) { oss << static_cast(vec[i]); if (i != vec.size() - 1) { - oss << " "; // 添加分隔符(例如空格) + oss << " "; // Add a separator (e.g. space) } } return oss.str(); @@ -383,7 +378,6 @@ int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const JsonObject & return DM_OK; } -// 解析131报文信息MSG_TYPE_RESP_PIN_AUTH_MSG_NEGOTIATE int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate(const JsonObject &jsonObject, std::shared_ptr context) { @@ -397,7 +391,6 @@ int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate(const JsonObjec return DM_OK; } -// 解析140报文信息MSG_TYPE_REQ_CREDENTIAL_EXCHANGE,SINK端存放对方公钥 int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const JsonObject &jsonObject, std::shared_ptr context) { @@ -406,7 +399,6 @@ int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const JsonObject &js return ERR_DM_FAILED; } - // 解密 std::string plainText; if (cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA].Get(), plainText) != DM_OK) { LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange() error, decrypt data failed."); @@ -414,7 +406,7 @@ int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const JsonObject &js } JsonObject jsonData(plainText); - // 首次认证,解析用户级公钥 + // First authentication, parse lnn public key if (!context->isOnline) { if (!jsonData[DM_TAG_LNN_PUBLICK_KEY].IsString()) { LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange() error, first auth, no lnnPublicKey."); @@ -430,15 +422,14 @@ int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const JsonObject &js LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange, MSG_TYPE_REQ_CREDENTIAL_EXCHANGE message error."); return ERR_DM_FAILED; } - context->accesser.ephemeralPublicKey = jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY].Get(); // 解析应用级公钥 - context->accesser.deviceId = jsonData[DM_TAG_DEVICE_ID].Get(); // 解析deviceId - context->accesser.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].Get(); // 解析userId - context->accesser.tokenId = jsonData[DM_TAG_TOKEN_ID].Get(); // 解析tokenId + context->accesser.ephemeralPublicKey = jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY].Get(); + context->accesser.deviceId = jsonData[DM_TAG_DEVICE_ID].Get(); + context->accesser.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].Get(); + context->accesser.tokenId = jsonData[DM_TAG_TOKEN_ID].Get(); context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } -// 解析150报文信息MSG_TYPE_RESP_CREDENTIAL_EXCHANGE,SRC端存放对方公钥,和协商凭据Id int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &jsonObject, std::shared_ptr context) { @@ -448,7 +439,6 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &js return ERR_DM_FAILED; } - // 解密 std::string plainText; if (cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA].Get(), plainText) != DM_OK) { LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange error, decrypt data failed."); @@ -459,7 +449,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &js JsonObject jsonData(plainText); - // 首次认证,解析对方用户级公钥和协商用户级凭据Id + // First authentication, parse lnn public key std::string tmpString; if (!context->isOnline) { if (!jsonData[DM_TAG_LNN_PUBLICK_KEY].IsString()) { @@ -469,7 +459,7 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &js context->accessee.lnnPublicKey = jsonData[DM_TAG_LNN_PUBLICK_KEY].Get(); } - // 解析对方应用级公钥和协商应用级凭据Id + // First authentication, parse transmit public key if (!jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY].IsString() || !jsonData[DM_TAG_DEVICE_ID].IsString() || !jsonData[DM_TAG_PEER_USER_SPACE_ID].IsNumberInteger() || @@ -479,15 +469,14 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &js return ERR_DM_FAILED; } context->accessee.ephemeralPublicKey = jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY].Get(); - context->accessee.deviceId = jsonData[DM_TAG_DEVICE_ID].Get(); // 解析deviceId - context->accessee.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].Get(); // 解析userId - context->accessee.tokenId = jsonData[DM_TAG_TOKEN_ID].Get(); // 解析tokenId + context->accessee.deviceId = jsonData[DM_TAG_DEVICE_ID].Get(); + context->accessee.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].Get(); + context->accessee.tokenId = jsonData[DM_TAG_TOKEN_ID].Get(); context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } -// 创建报文,构造对应msgType的报文,返回值为json格式报文的字符串 std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::shared_ptr context) { LOGI("DmAuthMessageProcessor::CreateMessage start. msgType is %{public}d", msgType); @@ -503,8 +492,6 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh return (ret == DM_OK) ? jsonObj.Dump() : ""; } -// 内部各类报文的实现 -// 161 170 171消息构造 int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject) { @@ -513,7 +500,7 @@ int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr return DM_OK; } -// 创建80报文 +// Create 80 message. int32_t DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject) { jsonObject[TAG_SESSION_NAME] = context->sessionName; @@ -538,7 +525,7 @@ int32_t DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject) { @@ -558,7 +545,7 @@ int32_t DmAuthMessageProcessor::CreateRespNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject) { @@ -582,7 +569,7 @@ int32_t DmAuthMessageProcessor::CreateMessageReqCredExchange(std::shared_ptr context, JsonObject &jsonObject) { @@ -591,10 +578,10 @@ int32_t DmAuthMessageProcessor::CreateMessageRspCredExchange(std::shared_ptrisOnline) { jsonData[DM_TAG_LNN_PUBLICK_KEY] = context->accessee.lnnPublicKey; } - jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY] = context->accessee.ephemeralPublicKey; // 本端应用级公钥 - jsonData[DM_TAG_DEVICE_ID] = context->accessee.deviceId; // 本端deviceId - jsonData[DM_TAG_PEER_USER_SPACE_ID] = context->accessee.userId; // 本端userId - jsonData[DM_TAG_TOKEN_ID] = context->accessee.tokenId; // 本端tokenId + jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY] = context->accessee.ephemeralPublicKey; + jsonData[DM_TAG_DEVICE_ID] = context->accessee.deviceId; + jsonData[DM_TAG_PEER_USER_SPACE_ID] = context->accessee.userId; + jsonData[DM_TAG_TOKEN_ID] = context->accessee.tokenId; std::string plainText = jsonData.Dump(); std::string cipherText; @@ -608,7 +595,7 @@ int32_t DmAuthMessageProcessor::CreateMessageRspCredExchange(std::shared_ptr context, JsonObject &jsonObject) { @@ -636,11 +623,11 @@ bool DmAuthMessageProcessor::ChecksumAcl(DistributedDeviceProfile::AccessControl return (accesserIter != accesserStrList.end()) && (accesseeIter != accesseeStrList.end()); } -// 创建190报文 +// Create 190 message. int32_t DmAuthMessageProcessor::CreateMessageSyncResp(std::shared_ptr context, JsonObject &jsonObject) { - DmAccess access; // 代表本端的access + DmAccess access; if (context->direction == DM_AUTH_SINK) { access = context->accessee; } else { @@ -657,7 +644,7 @@ int32_t DmAuthMessageProcessor::CreateMessageSyncResp(std::shared_ptr context, JsonObject &jsonObject) { @@ -707,20 +694,20 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr } access.dmVersion = jsonObject[DM_TAG_DMVERSION].Get(); - if (!jsonObject[DM_TAG_ACCESS].IsString()) { // 再解析一次 + if (!jsonObject[DM_TAG_ACCESS].IsString()) { LOGE("ParseSyncMessage DM_TAG_ACCESS error"); return ERR_DM_FAILED; } std::string srcAccessStr = jsonObject[DM_TAG_ACCESS].Get(); - // 解析到 access里面 + // Parse into access ParseDmAccessToSync(srcAccessStr, access); - if (jsonObject[DM_TAG_PROXY].IsString()) { // 预留字段 + if (jsonObject[DM_TAG_PROXY].IsString()) { // Reserved field std::string proxyInfo = jsonObject[DM_TAG_PROXY].Get(); } - if (jsonObject[DM_TAG_SERVICEINFO].IsString()) { // sp 暂时没有传 + if (jsonObject[DM_TAG_SERVICEINFO].IsString()) { // sp not yet uploaded std::string serviceInfo = jsonObject[DM_TAG_SERVICEINFO].Get(); } - if (!jsonObject[DM_TAG_ACL_CHECKSUM].IsString()) { // 再解析一次 acl + if (!jsonObject[DM_TAG_ACL_CHECKSUM].IsString()) { // Re-parse the acl LOGE("ParseSyncMessage DM_TAG_ACL_CHECKSUM error"); return ERR_DM_FAILED; } @@ -728,11 +715,9 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr return ParaseAclChecksumList(aclChecksumList, access); } -int32_t DmAuthMessageProcessor:: -DecryptSyncMessage(std::shared_ptr &context, +int32_t DmAuthMessageProcessor::DecryptSyncMessage(std::shared_ptr &context, DmAccess &access, std::string &enSyncMsg) { - // 解密整个字段 std::string syncMsgCompress = ""; int32_t ret = cryptoMgr_->DecryptMessage(enSyncMsg, syncMsgCompress); if (ret != DM_OK) { @@ -754,10 +739,8 @@ DecryptSyncMessage(std::shared_ptr &context, return ERR_DM_FAILED; } std::string compressMsg = plainJson[DM_TAG_COMPRESS].Get(); - // 解压缩 std::string compressBase64 = Base64Decode(compressMsg); std::string syncMsg = DecompressSyncMsg(compressBase64, dataLen); - // 解析字段 JsonObject jsonObject(syncMsg); if (jsonObject.IsDiscarded()) { LOGE("DmAuthMessageProcessor::DecryptSyncMessage jsonStr error"); @@ -773,16 +756,16 @@ DecryptSyncMessage(std::shared_ptr &context, } // 解析 180报文信息 MSG_TYPE_REQ_DATA_SYNC 存放对方密文四元组,acl,sp skid +// Parse 180 message, save remote encrypted quadruple, acl, sp skid int32_t DmAuthMessageProcessor::ParseMessageSyncReq(const JsonObject &jsonObject, std::shared_ptr context) { - // 解析json中的加密数据 - if (!jsonObject[DM_TAG_SYNC].IsString()) { // 再解析一次 acl + if (!jsonObject[DM_TAG_SYNC].IsString()) { LOGE("ParseMessageSyncReq json error"); return ERR_DM_FAILED; } std::string enSyncMsg = jsonObject[DM_TAG_SYNC].Get(); - // 解密数据 + 解析数据到context中 + // Decrypt data and parse data into context int32_t ret = DecryptSyncMessage(context, context->accesser, enSyncMsg); if (ret != DM_OK) { LOGE("DecryptSyncMessage enSyncMsg error"); @@ -792,17 +775,16 @@ int32_t DmAuthMessageProcessor::ParseMessageSyncReq(const JsonObject &jsonObject return DM_OK; } -// 解析 190报文信息 MSG_TYPE_RESP_DATA_SYNC 存放对方密文四元组,acl sp skid +// Parse 190 message save the remote encrypted quadruple, acl sp skid int32_t DmAuthMessageProcessor::ParseMessageSyncResp(const JsonObject &jsonObject, std::shared_ptr context) { - // 解析json中的加密数据 - if (!jsonObject[DM_TAG_SYNC].IsString()) { // 再解析一次 acl + if (!jsonObject[DM_TAG_SYNC].IsString()) { LOGE("ParseMessageSyncResp json error"); return ERR_DM_FAILED; } std::string enSyncMsg = jsonObject[DM_TAG_SYNC].Get(); - // 解密数据 + 解析数据到context中 + // Decrypt data and parse data into context int32_t ret = DecryptSyncMessage(context, context->accessee, enSyncMsg); if (ret != DM_OK) { LOGE("DecryptSyncMessage enSyncMsg error"); @@ -832,7 +814,7 @@ int32_t DmAuthMessageProcessor::ParseMessageSinkFinish(const JsonObject &jsonObj return DM_OK; } -// 解析201报文 +// Parse 201 message int32_t DmAuthMessageProcessor::ParseMessageSrcFinish(const JsonObject &jsonObject, std::shared_ptr context) { @@ -1067,18 +1049,18 @@ void DmAuthMessageProcessor::CreateAndSendMsg(DmMessageType msgType, std::shared std::string DmAuthMessageProcessor::CompressSyncMsg(std::string &inputStr) { uint32_t srcLen = inputStr.size(); - uint32_t boundSize = compressBound(srcLen); // 最大压缩长度 + uint32_t boundSize = compressBound(srcLen); // Maximum compression length std::string compressed(boundSize, '\0'); - // 压缩到预留空间 - unsigned long destSize = boundSize; // 实际可用长度 + // Compress to reserved space + unsigned long destSize = boundSize; // Actual usable length int32_t ret = compress(reinterpret_cast(&compressed[0]), &destSize, reinterpret_cast(inputStr.data()), srcLen); if (ret != Z_OK) { LOGE("DmAuthMessageProcessor::CompressSyncMsg zlib compress failed"); return ""; } - compressed.resize(destSize); // 实际使用长度 + compressed.resize(destSize); // Actual usage length return compressed; } @@ -1086,9 +1068,9 @@ std::string DmAuthMessageProcessor::DecompressSyncMsg(std::string& compressed, u { std::string decompressed; decompressed.resize(oriLen); - unsigned long destLen = oriLen; // 实际使用长度 + unsigned long destLen = oriLen; // Actual usage length int32_t ret = uncompress(reinterpret_cast(&decompressed[0]), &destLen, - reinterpret_cast(compressed.data()), // 解压时跳过头部 + reinterpret_cast(compressed.data()), // Skip header when decompressing compressed.size()); if (ret != Z_OK || destLen != oriLen) { LOGE("DmAuthMessageProcessor::DecompressSyncMsg decompress failed"); @@ -1099,35 +1081,35 @@ std::string DmAuthMessageProcessor::DecompressSyncMsg(std::string& compressed, u std::string DmAuthMessageProcessor::Base64Encode(std::string &inputStr) { - // 输入字符串转二进制 + // Convert input string to binary const unsigned char* src = reinterpret_cast(inputStr.data()); size_t srcLen = inputStr.size(); - // 计算base64 后最大长度 + // Calculate the maximum length after base64 encoding size_t maxEncodeLen = ((srcLen + 2) / 3) * 4 + 1; std::vector buffer(maxEncodeLen); - // 实际编码长度 + // Actual encoding length size_t encodedLen = 0; int32_t ret = mbedtls_base64_encode(buffer.data(), buffer.size(), &encodedLen, src, srcLen); if (ret != 0) { LOGE("DmAuthMessageProcessor::Base64Encode mbedtls_base64_encode failed"); return ""; } - return std::string(reinterpret_cast(buffer.data()), encodedLen); // 无需终止符 + return std::string(reinterpret_cast(buffer.data()), encodedLen); // No terminator needed } std::string DmAuthMessageProcessor::Base64Decode(std::string &inputStr) { - // 输入字符串转二进制 + // Convert input string to binary const unsigned char* src = reinterpret_cast(inputStr.data()); size_t srcLen = inputStr.size(); - // 计算base64 后最大长度 + // Calculate the maximum length after base64 encoding size_t maxEncodeLen = (srcLen / 4) * 3 + 1; std::vector buffer(maxEncodeLen); - // 实际编码长度 + // Actual encoding length size_t decodedLen = 0; int32_t ret = mbedtls_base64_decode(buffer.data(), buffer.size(), &decodedLen, src, srcLen); if (ret != 0) { @@ -1138,11 +1120,10 @@ std::string DmAuthMessageProcessor::Base64Decode(std::string &inputStr) } -// 用于组装syncMsg中的加密部分 int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptr &context, DmAccess &accessSide, std::string &encSyncMsg) { - JsonObject syncMsgJson; // 完整的180/190 消息 未经压缩&加密 + JsonObject syncMsgJson; DmAccessToSync accessToSync; accessToSync.deviceName = accessSide.deviceName; accessToSync.deviceId = accessSide.deviceId; @@ -1154,7 +1135,7 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptrisOnline) { // 首次认证 + if (!context->isOnline) { // First certification syncMsgJson[DM_TAG_LNN_SK_ID]=std::to_string(accessSide.lnnSessionKeyId); syncMsgJson[DM_TAG_LNN_SK_TIMESTAMP]=std::to_string(accessSide.lnnSkTimeStamp); syncMsgJson[DM_TAG_LNN_CREDENTIAL_ID] = accessSide.lnnCredentialId; @@ -1163,8 +1144,8 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptrEncryptMessage(plainJson.Dump(), encSyncMsg); } @@ -1221,7 +1201,7 @@ std::string DmAuthMessageProcessor::AccesserToStr(DistributedDeviceProfile::Acce jsonAccesserObj[DM_TAG_ACCESSER_USER_ID] = accesser.GetAccesserUserId(); jsonAccesserObj[DM_TAG_ACCESSER_ACOUNT_ID] = accesser.GetAccesserAccountId(); jsonAccesserObj[DM_TAG_ACCESSER_TOKEN_ID] = accesser.GetAccesserTokenId(); - jsonAccesserObj[DM_TAG_ACCESSER_SERVICE_NAME] = std::vector(); // 预留字段 DP库未适配 + jsonAccesserObj[DM_TAG_ACCESSER_SERVICE_NAME] = std::vector(); // Reserved field jsonAccesserObj[DM_TAG_ACCESSER_BUNDLE_NAME] = accesser.GetAccesserBundleName(); jsonAccesserObj[DM_TAG_ACCESSER_HAP_SIGNATURE] = accesser.GetAccesserHapSignature(); jsonAccesserObj[DM_TAG_ACCESSER_BIND_LEVEL] = accesser.GetAccesserBindLevel(); @@ -1240,7 +1220,7 @@ std::string DmAuthMessageProcessor::AccesseeToStr(DistributedDeviceProfile::Acce jsonAccesseeObj[DM_TAG_ACCESSEE_USER_ID] = accessee.GetAccesseeUserId(); jsonAccesseeObj[DM_TAG_ACCESSEE_ACOUNT_ID] = accessee.GetAccesseeAccountId(); jsonAccesseeObj[DM_TAG_ACCESSEE_TOKEN_ID] = accessee.GetAccesseeTokenId(); - jsonAccesseeObj[DM_TAG_ACCESSEE_SERVICE_NAME] = std::vector(); // 预留字段 DP库未适配 + jsonAccesseeObj[DM_TAG_ACCESSEE_SERVICE_NAME] = std::vector(); // Reserved field jsonAccesseeObj[DM_TAG_ACCESSEE_BUNDLE_NAME] = accessee.GetAccesseeBundleName(); jsonAccesseeObj[DM_TAG_ACCESSEE_HAP_SIGNATURE] = accessee.GetAccesseeHapSignature(); jsonAccesseeObj[DM_TAG_ACCESSEE_BIND_LEVEL] = accessee.GetAccesseeBindLevel(); @@ -1253,7 +1233,7 @@ std::string DmAuthMessageProcessor::AccesseeToStr(DistributedDeviceProfile::Acce int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr context, JsonObject &jsonObject) { - DmAccess accessSide; // 代表本端的access + DmAccess accessSide; if (context->direction == DM_AUTH_SOURCE) { accessSide = context->accesser; } else { @@ -1269,7 +1249,6 @@ int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr return DM_OK; } -// 解析transmit和PSKID 解析160 int32_t DmAuthMessageProcessor::ParseAuthStartMessage(const JsonObject &jsonObject, std::shared_ptr context) { @@ -1287,20 +1266,20 @@ int32_t DmAuthMessageProcessor::ParseAuthStartMessage(const JsonObject &jsonObje int32_t DmAuthMessageProcessor::GetAclListStr(std::shared_ptr &context, std::string &aclList) { JsonObject jsonAclListObj; - jsonAclListObj[DM_TAG_DMVERSION] = context->accesser.dmVersion; // 在80/90 流程会协商出双方均兼容的版本号,此处取accesser的ver即可 + jsonAclListObj[DM_TAG_DMVERSION] = context->accesser.dmVersion; - // 查询ACL + // Query ACL. std::vector profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfile(); std::vector accceserStrList; std::vector accceseeStrList; - // 遍历acl table 找到双端历史acl记录 + // Traverse the ACL table to find historical ACL records at both ends. for (auto &item : profiles) { if (item.GetAccesser().GetAccesserDeviceId() == context->accesser.deviceId && item.GetAccesser().GetAccesserUserId() == context->accesser.userId && item.GetAccessee().GetAccesseeDeviceId() == context->accessee.deviceId && item.GetAccessee().GetAccesseeUserId() == context->accessee.userId) { - // 以SHA256的摘要保存 + // Save the digest using SHA256. uint8_t accesserHash[DM_HASH_LEN] = {0}; std::string accesserStr = AccesserToStr(item); Crypto::DmGenerateStrHash(accesserStr.data(), accesserStr.size(), accesserHash, DM_HASH_LEN, 0); @@ -1313,7 +1292,7 @@ int32_t DmAuthMessageProcessor::GetAclListStr(std::shared_ptr &co } } if (accceserStrList.empty() || accceseeStrList.empty()) { - LOGI("DmAuthMessageProcessor::CreateSyncMessage acl lis is empty"); // 双方无旧ACL需要同步 此时返回空字符串 + LOGI("DmAuthMessageProcessor::CreateSyncMessage acl lis is empty"); } jsonAclListObj[DM_TAG_ACCESSER] = accceserStrList; -- Gitee From dd0a2dbe00aa055ccd8702d660764f9ca5ef5618 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Thu, 27 Mar 2025 17:21:08 +0800 Subject: [PATCH 311/382] =?UTF-8?q?feat:=20tag=E6=95=B4=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication/auth_message_processor.h | 9 - .../authentication_v2/dm_auth_manager_base.h | 15 +- .../dm_auth_message_processor.h | 161 +++---- .../authentication/auth_message_processor.cpp | 9 - .../src/authentication/dm_auth_manager.cpp | 4 +- .../src/authentication_v2/auth_manager.cpp | 20 +- .../auth_stages/auth_credential.cpp | 28 +- .../dm_auth_manager_base.cpp | 10 + .../dm_auth_message_processor.cpp | 449 +++++++++++------- .../src/device_manager_service_impl.cpp | 16 +- 10 files changed, 397 insertions(+), 324 deletions(-) diff --git a/services/implementation/include/authentication/auth_message_processor.h b/services/implementation/include/authentication/auth_message_processor.h index dde7dbf83..fdc0a4a40 100644 --- a/services/implementation/include/authentication/auth_message_processor.h +++ b/services/implementation/include/authentication/auth_message_processor.h @@ -27,7 +27,6 @@ namespace OHOS { namespace DistributedHardware { -extern const char* TAG_REPLY; extern const char* TAG_NET_ID; extern const char* TAG_TARGET; extern const char* TAG_APP_OPERATION; @@ -48,7 +47,6 @@ extern const char* TAG_CRYPTO_NAME; extern const char* TAG_CRYPTO_VERSION; extern const char* TAG_IDENTICAL_ACCOUNT; extern const char* TAG_ACCOUNT_GROUPID; -extern const char* APP_THUMBNAIL; extern const char* QR_CODE_KEY; extern const char* TAG_AUTH_TOKEN; extern const char* NFC_CODE_KEY; @@ -58,25 +56,18 @@ extern const char* TAG_AUTH_FINISH; extern const char* TAG_HAVE_CREDENTIAL; extern const char* TAG_PUBLICKEY; extern const char* TAG_SESSIONKEY; -extern const char* TAG_BIND_LEVEL; extern const char* TAG_LOCAL_USERID; extern const char* TAG_BIND_TYPE_SIZE; extern const char* TAG_ISONLINE; extern const char* TAG_AUTHED; extern const char* TAG_LOCAL_ACCOUNTID; -extern const char* TAG_DMVERSION; extern const char* TAG_HOST_PKGNAME; extern const char* TAG_TOKENID; extern const char* TAG_HAVECREDENTIAL; extern const char* TAG_CONFIRM_OPERATION; -extern const char* TAG_DATA; -extern const char* TAG_DATA_LEN; extern const char* TAG_IMPORT_AUTH_CODE; extern const char* TAG_HOST_PKGLABEL; -extern const char* TAG_EDITION; -extern const char* TAG_BUNDLE_NAME; extern const char* TAG_CRYPTIC_MSG; -extern const char* TAG_PEER_BUNDLE_NAME; extern const char* TAG_REMOTE_DEVICE_NAME; extern const char* TAG_SESSIONKEY_ID; diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h b/services/implementation/include/authentication_v2/dm_auth_manager_base.h index 490417553..25acb1dc4 100644 --- a/services/implementation/include/authentication_v2/dm_auth_manager_base.h +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h @@ -40,6 +40,16 @@ 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* TAG_DMVERSION; +extern const char* TAG_EDITION; +extern const char* TAG_DATA; +extern const char* TAG_DATA_LEN; +extern const char* TAG_BUNDLE_NAME; +extern const char* TAG_PEER_BUNDLE_NAME; +extern const char* TAG_BIND_LEVEL; +extern const char* TAG_REPLY; +extern const char* TAG_APP_THUMBNAIL2; // Naming Add 2 to resolve conflicts with TAG_APP_THUMBNAIL + extern const char* APP_OPERATION_KEY; extern const char* TARGET_PKG_NAME_KEY; extern const char* CUSTOM_DESCRIPTION_KEY; @@ -82,11 +92,6 @@ 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 { diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 13e4e53cb..7b9c83d1f 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -27,101 +27,90 @@ 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"; +extern const char* TAG_LNN_PUBLICK_KEY; +extern const char* TAG_TRANSMIT_PUBLICK_KEY; +extern const char* TAG_LNN_CREDENTIAL_ID; +extern const char* TAG_TRANSMIT_CREDENTIAL_ID; +extern const char* TAG_AUTH_RESULT; +extern const char* TAG_AUTH_TYPE_LIST; +extern const char* TAG_CURRENT_AUTH_TYPE_IDX; // 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"; +extern const char* TAG_METHOD; +extern const char* TAG_PEER_USER_SPACE_ID; +extern const char* TAG_SUBJECT; +extern const char* TAG_CRED_TYPE; +extern const char* TAG_KEY_FORMAT; +extern const char* TAG_ALGORITHM_TYPE; +extern const char* TAG_PROOF_TYPE; +extern const char* TAG_KEY_VALUE; +extern const char* TAG_AUTHORIZED_SCOPE; +extern const char* TAG_AUTHRIZED_APP_LIST; +extern const char* TAG_CREDENTIAL_OWNER; +extern const char* TAG_SYNC; +extern const char* TAG_ACCESS; +extern const char* TAG_PROXY; +extern const char* TAG_ACL; +extern const char* TAG_ACCESSER; +extern const char* TAG_ACCESSEE; +extern const char* TAG_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"; +extern const char* TAG_TRANSMIT_SK_ID; +extern const char* TAG_LNN_SK_ID; +extern const char* TAG_TRANSMIT_SK_TIMESTAMP; +extern const char* TAG_LNN_SK_TIMESTAMP; +extern const char* TAG_TOKEN_ID; +extern const char* TAG_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"; +extern const char* TAG_DEVICE_VERSION; +extern const char* TAG_DEVICE_NAME; +extern const char* TAG_DEVICE_ID_HASH; +extern const char* TAG_USER_ID_HASH; +extern const char* TAG_ACCOUNT_ID_HASH; +extern const char* TAG_TOKEN_ID_HASH; +extern const char* TAG_SESSION_NAME; +extern const char* TAG_ACL_CHECKSUM; +extern const char* TAG_COMPRESS_ORI_LEN; +extern const char* TAG_COMPRESS; +extern const char* TAG_REPLY; +extern const char* TAG_STATE; +extern const char* TAG_REASON; +extern const char* TAG_PEER_USER_ID; +extern const char* TAG_PEER_DISPLAY_ID; +extern const char* TAG_EXTRA_INFO; -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"; -constexpr const char* TAG_CERT_INFO = "certInfo"; +extern const char* TAG_IS_ONLINE; +extern const char* TAG_IS_AUTHED; +extern const char* TAG_CREDENTIAL_INFO; +extern const char* TAG_CERT_INFO; // 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"; +extern const char* TAG_ACCESSER_DEVICE_ID; +extern const char* TAG_ACCESSER_USER_ID; +extern const char* TAG_ACCESSER_ACOUNT_ID; +extern const char* TAG_ACCESSER_TOKEN_ID; +extern const char* TAG_ACCESSER_SERVICE_NAME; +extern const char* TAG_ACCESSER_BUNDLE_NAME; +extern const char* TAG_ACCESSER_HAP_SIGNATURE; +extern const char* TAG_ACCESSER_BIND_LEVEL; +extern const char* TAG_ACCESSER_CREDENTIAL_ID; +extern const char* TAG_ACCESSER_STATUS; +extern const char* TAG_ACCESSER_SK_ID; +extern const char* TAG_ACCESSER_SK_TIMESTAMP; // 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"; +extern const char* TAG_ACCESSEE_DEVICE_ID; +extern const char* TAG_ACCESSEE_USER_ID; +extern const char* TAG_ACCESSEE_ACOUNT_ID; +extern const char* TAG_ACCESSEE_TOKEN_ID; +extern const char* TAG_ACCESSEE_SERVICE_NAME; +extern const char* TAG_ACCESSEE_BUNDLE_NAME; +extern const char* TAG_ACCESSEE_HAP_SIGNATURE; +extern const char* TAG_ACCESSEE_BIND_LEVEL; +extern const char* TAG_ACCESSEE_CREDENTIAL_ID; +extern const char* TAG_ACCESSEE_STATUS; +extern const char* TAG_ACCESSEE_SK_ID; +extern const char* TAG_ACCESSEE_SK_TIMESTAMP; enum DmMessageType { // Terminate/Exception Message diff --git a/services/implementation/src/authentication/auth_message_processor.cpp b/services/implementation/src/authentication/auth_message_processor.cpp index 273db6dfb..89ab8ae41 100644 --- a/services/implementation/src/authentication/auth_message_processor.cpp +++ b/services/implementation/src/authentication/auth_message_processor.cpp @@ -22,7 +22,6 @@ namespace OHOS { namespace DistributedHardware { -const char* TAG_REPLY = "REPLY"; const char* TAG_NET_ID = "NETID"; const char* TAG_TARGET = "TARGET"; const char* TAG_APP_OPERATION = "APPOPERATION"; @@ -43,7 +42,6 @@ const char* TAG_CRYPTO_NAME = "CRYPTONAME"; const char* TAG_CRYPTO_VERSION = "CRYPTOVERSION"; const char* TAG_IDENTICAL_ACCOUNT = "IDENTICALACCOUNT"; const char* TAG_ACCOUNT_GROUPID = "ACCOUNTGROUPID"; -const char* APP_THUMBNAIL = "appThumbnail"; const char* QR_CODE_KEY = "qrCode"; const char* TAG_AUTH_TOKEN = "authToken"; const char* NFC_CODE_KEY = "nfcCode"; @@ -53,25 +51,18 @@ const char* TAG_AUTH_FINISH = "isFinish"; const char* TAG_HAVE_CREDENTIAL = "haveCredential"; const char* TAG_PUBLICKEY = "publicKey"; const char* TAG_SESSIONKEY = "sessionKey"; -const char* TAG_BIND_LEVEL = "bindLevel"; const char* TAG_LOCAL_USERID = "localUserId"; const char* TAG_BIND_TYPE_SIZE = "bindTypeSize"; const char* TAG_ISONLINE = "isOnline"; const char* TAG_AUTHED = "authed"; const char* TAG_LOCAL_ACCOUNTID = "localAccountId"; -const char* TAG_DMVERSION = "dmVersion"; const char* TAG_HOST_PKGNAME = "hostPkgname"; const char* TAG_TOKENID = "tokenId"; const char* TAG_HAVECREDENTIAL = "haveCredential"; const char* TAG_CONFIRM_OPERATION = "confirmOperation"; -const char* TAG_DATA = "data"; -const char* TAG_DATA_LEN = "dataLen"; const char* TAG_IMPORT_AUTH_CODE = "IMPORT_AUTH_CODE"; const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; -const char* TAG_EDITION = "edition"; -const char* TAG_BUNDLE_NAME = "bundleName"; const char* TAG_CRYPTIC_MSG = "encryptMsg"; -const char* TAG_PEER_BUNDLE_NAME = "PEER_BUNDLE_NAME"; const char* TAG_REMOTE_DEVICE_NAME = "REMOTE_DEVICE_NAME"; const char* TAG_SESSIONKEY_ID = "sessionKeyId"; diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 6a63d5ece..054615bb0 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -302,8 +302,8 @@ void DmAuthManager::ParseJsonObject(JsonObject &jsonObject) authRequestContext_->customDesc = DmLanguageManager::GetInstance(). GetTextBySystemLanguage(jsonObject[CUSTOM_DESCRIPTION_KEY].Get()); } - if (IsString(jsonObject, APP_THUMBNAIL)) { - authRequestContext_->appThumbnail = jsonObject[APP_THUMBNAIL].Get(); + if (IsString(jsonObject, TAG_APP_THUMBNAIL2)) { + authRequestContext_->appThumbnail = jsonObject[TAG_APP_THUMBNAIL2].Get(); } CheckBindLevel(jsonObject, TAG_BIND_LEVEL, authRequestContext_->bindLevel); authRequestContext_->closeSessionDelaySeconds = 0; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index e5759ab5c..613046349 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -519,8 +519,8 @@ void AuthManager::ParseJsonObject(const JsonObject &jsonObject) if (jsonObject[CUSTOM_DESCRIPTION_KEY].IsString()) { context_->customData = jsonObject[CUSTOM_DESCRIPTION_KEY].Get(); } - if (jsonObject[APP_THUMBNAIL].IsString()) { - context_->appThumbnail = jsonObject[APP_THUMBNAIL].Get(); + if (jsonObject[TAG_APP_THUMBNAIL2].IsString()) { + context_->appThumbnail = jsonObject[TAG_APP_THUMBNAIL2].Get(); } context_->connDelayCloseTime = 0; if (jsonObject[PARAM_CLOSE_SESSION_DELAY_SECONDS].IsString()) { @@ -544,11 +544,11 @@ void AuthManager::ParseJsonObject(const JsonObject &jsonObject) } else { context_->accessee.bundleName = context_->sessionName; } - if (jsonObject[DM_TAG_ACCESSEE_USER_ID].IsNumberInteger()) { - context_->accessee.userId = jsonObject[DM_TAG_ACCESSEE_USER_ID].Get(); + if (jsonObject[TAG_ACCESSEE_USER_ID].IsNumberInteger()) { + context_->accessee.userId = jsonObject[TAG_ACCESSEE_USER_ID].Get(); } - if (jsonObject[DM_TAG_PEER_DISPLAY_ID].IsNumberInteger()) { - context_->accessee.displayId = jsonObject[DM_TAG_PEER_DISPLAY_ID].Get(); + if (jsonObject[TAG_PEER_DISPLAY_ID].IsNumberInteger()) { + context_->accessee.displayId = jsonObject[TAG_PEER_DISPLAY_ID].Get(); } ParseHmlInfoInJsonObject(jsonObject); @@ -796,13 +796,13 @@ void AuthSinkManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string me LOGE("DecodeRequestAuth jsonStr error"); return; } - if (!jsonObject[DM_TAG_DATA].IsString() || !jsonObject[DM_TAG_DATA_LEN].IsNumberInteger() || + if (!jsonObject[TAG_DATA].IsString() || !jsonObject[TAG_DATA_LEN].IsNumberInteger() || !jsonObject[TAG_MSG_TYPE].IsNumberInteger()) { LOGE("Auth device data is error."); return; } LOGI("OnAuthDeviceDataReceived start msgType %{public}d.", jsonObject[TAG_MSG_TYPE].Get()); - std::string authData = jsonObject[DM_TAG_DATA].Get(); + std::string authData = jsonObject[TAG_DATA].Get(); int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); context_->hiChainAuthConnector->ProcessAuthData(context_->requestId, authData, osAccountId); @@ -922,13 +922,13 @@ void AuthSrcManager::OnAuthDeviceDataReceived(int32_t sessionId, std::string mes LOGE("DecodeRequestAuth jsonStr error"); return; } - if (!jsonObject[DM_TAG_DATA].IsNumberInteger() || !jsonObject[DM_TAG_DATA_LEN].IsNumberInteger() || + if (!jsonObject[TAG_DATA].IsNumberInteger() || !jsonObject[TAG_DATA_LEN].IsNumberInteger() || !jsonObject[TAG_MSG_TYPE].IsNumberInteger()) { LOGE("Auth device data is error."); return; } LOGI("OnAuthDeviceDataReceived start msgType %{public}d.", jsonObject[TAG_MSG_TYPE].Get()); - std::string authData = jsonObject[DM_TAG_DATA].Get(); + std::string authData = jsonObject[TAG_DATA].Get(); int32_t osAccountId = MultipleUserConnector::GetCurrentAccountUserID(); context_->hiChainAuthConnector->ProcessAuthData(context_->requestId, authData, osAccountId); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 680ea9740..557af5e6b 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -32,6 +32,8 @@ namespace DistributedHardware { namespace { +const char* DM_AUTH_CREDENTIAL_OWNER = "DM"; + int32_t AuthCredentialTransmitDecryptProcess(std::shared_ptr context, DmEventType event) { if (context->transmitData.empty()) { @@ -246,32 +248,32 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori JsonObject jsonObj; if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) { - jsonObj[DM_TAG_METHOD] = method; // 凭据生成方式,只有导入时,需要传入method + jsonObj[TAG_METHOD] = method; // 凭据生成方式,只有导入时,需要传入method } - jsonObj[DM_TAG_DEVICE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? // 设备ID 生成是本端,导入是对端 + jsonObj[TAG_DEVICE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? // 设备ID 生成是本端,导入是对端 authContext->GetDeviceId(DM_AUTH_LOCAL_SIDE) : authContext->GetDeviceId(DM_AUTH_REMOTE_SIDE); if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) { - jsonObj[DM_TAG_PEER_USER_SPACE_ID] = std::to_string(authContext->GetUserId(DM_AUTH_REMOTE_SIDE)); + jsonObj[TAG_PEER_USER_SPACE_ID] = std::to_string(authContext->GetUserId(DM_AUTH_REMOTE_SIDE)); } - jsonObj[DM_TAG_USER_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? + jsonObj[TAG_USER_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? authContext->GetAccountId(DM_AUTH_LOCAL_SIDE) : authContext->GetAccountId(DM_AUTH_REMOTE_SIDE); - jsonObj[DM_TAG_SUBJECT] = DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY; // 主控设备 - jsonObj[DM_TAG_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; // 账号无关 - jsonObj[DM_TAG_KEY_FORMAT] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? + jsonObj[TAG_SUBJECT] = DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY; // 主控设备 + jsonObj[TAG_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; // 账号无关 + jsonObj[TAG_KEY_FORMAT] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? DM_AUTH_KEY_FORMAT_ASYMM_GENERATE : DM_AUTH_KEY_FORMAT_ASYMM_IMPORT; // 生成或导入非对称秘钥 - jsonObj[DM_TAG_ALGORITHM_TYPE] = DM_AUTH_ALG_TYPE_ED25519; // ED25519 - jsonObj[DM_TAG_PROOF_TYPE] = DM_AUTH_CREDENTIAL_PROOF_PSK; // PSK + jsonObj[TAG_ALGORITHM_TYPE] = DM_AUTH_ALG_TYPE_ED25519; // ED25519 + jsonObj[TAG_PROOF_TYPE] = DM_AUTH_CREDENTIAL_PROOF_PSK; // PSK if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) { // 导入公钥 16进制字符串 - jsonObj[DM_TAG_KEY_VALUE] = authContext->GetPublicKey(DM_AUTH_REMOTE_SIDE, authorizedScope); + jsonObj[TAG_KEY_VALUE] = authContext->GetPublicKey(DM_AUTH_REMOTE_SIDE, authorizedScope); } - jsonObj[DM_TAG_AUTHORIZED_SCOPE] = authorizedScope; // 用户级或者应用级 + jsonObj[TAG_AUTHORIZED_SCOPE] = authorizedScope; // 用户级或者应用级 if (authorizedScope == DM_AUTH_SCOPE_APP) { std::vector tokenIds = {std::to_string(authContext->accesser.tokenId), std::to_string(authContext->accessee.tokenId)}; - jsonObj[DM_TAG_AUTHRIZED_APP_LIST] = tokenIds; + jsonObj[TAG_AUTHRIZED_APP_LIST] = tokenIds; } - jsonObj[DM_TAG_CREDENTIAL_OWNER] = DM_AUTH_CREDENTIAL_OWNER; // 调用方包名DM模块 + jsonObj[TAG_CREDENTIAL_OWNER] = DM_AUTH_CREDENTIAL_OWNER; // 调用方包名DM模块 LOGI("AuthCredentialAgreeState::CreateAuthParamsString leave."); return jsonObj.Dump(); diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp index c161a951b..302368300 100644 --- a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp @@ -39,6 +39,16 @@ const char* DM_VERSION_5_0_5 = "5.0.5"; const char* DM_VERSION_5_1_0 = "5.1.0"; const char* DM_VERSION_5_0_OLD_MAX = "5.0.9"; // 预估的旧版本最高版本号 +const char* TAG_DMVERSION = "dmVersion"; +const char* TAG_EDITION = "edition"; +const char* TAG_DATA = "data"; +const char* TAG_DATA_LEN = "dataLen"; +const char* TAG_BUNDLE_NAME = "bundleName"; +const char* TAG_PEER_BUNDLE_NAME = "PEER_BUNDLE_NAME"; +const char* TAG_BIND_LEVEL = "bindLevel"; +const char* TAG_REPLY = "REPLY"; +const char* TAG_APP_THUMBNAIL2 = "appThumbnail"; // Naming Add 2 to resolve conflicts with TAG_APP_THUMBNAIL + const char* APP_OPERATION_KEY = "appOperation"; const char* TARGET_PKG_NAME_KEY = "targetPkgName"; const char* CUSTOM_DESCRIPTION_KEY = "customDescription"; diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index fa63636d9..64b2c9638 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -37,17 +37,102 @@ namespace OHOS { namespace DistributedHardware { +const char* TAG_LNN_PUBLICK_KEY = "lnnPublicKey"; +const char* TAG_TRANSMIT_PUBLICK_KEY = "ephemeralPublicKey"; +const char* TAG_LNN_CREDENTIAL_ID = "lnnCredentialId"; +const char* TAG_TRANSMIT_CREDENTIAL_ID = "transmitCredentialId"; +const char* TAG_AUTH_RESULT = "authResult"; +const char* TAG_AUTH_TYPE_LIST = "authTypeList"; +const char* TAG_CURRENT_AUTH_TYPE_IDX = "currentAuthTypeIdx"; + +// IS interface input parameter json format string key +const char* TAG_METHOD = "method"; +const char* TAG_PEER_USER_SPACE_ID = "peerUserSpaceId"; +const char* TAG_SUBJECT = "subject"; +const char* TAG_CRED_TYPE = "credType"; +const char* TAG_KEY_FORMAT = "keyFormat"; +const char* TAG_ALGORITHM_TYPE = "algorithmType"; +const char* TAG_PROOF_TYPE = "proofType"; +const char* TAG_KEY_VALUE = "keyValue"; +const char* TAG_AUTHORIZED_SCOPE = "authorizedScope"; +const char* TAG_AUTHRIZED_APP_LIST = "authorizedAppList"; +const char* TAG_CREDENTIAL_OWNER = "credOwner"; +const char* TAG_SYNC = "syncMessage"; +const char* TAG_ACCESS = "dmAccess"; +const char* TAG_PROXY = "proxy"; +const char* TAG_ACL = "accessControlTable"; +const char* TAG_ACCESSER = "dmAccesser"; +const char* TAG_ACCESSEE = "dmAccessee"; +const char* TAG_SERVICEINFO = "serviceInfo"; +// The local SK information is synchronized to the remote end to construct acl-accesser/accessee. +const char* TAG_TRANSMIT_SK_ID = "accessAppSKId"; +const char* TAG_LNN_SK_ID = "accessUserSKId"; +const char* TAG_TRANSMIT_SK_TIMESTAMP = "accessAppSKTimeStamp"; +const char* TAG_LNN_SK_TIMESTAMP = "accessUserSKTimeStamp"; +const char* TAG_TOKEN_ID = "tokenId"; +const char* TAG_ISSUER = "issuer"; + +const char* TAG_DEVICE_VERSION = "deviceVersion"; +const char* TAG_DEVICE_NAME = "deviceName"; +const char* TAG_DEVICE_ID_HASH = "deviceIdHash"; +const char* TAG_USER_ID_HASH = "userIdHash"; +const char* TAG_ACCOUNT_ID_HASH = "accountIdHash"; +const char* TAG_TOKEN_ID_HASH = "tokenIdHash"; +const char* TAG_SESSION_NAME = "sessionName"; +const char* TAG_ACL_CHECKSUM = "aclCheckSum"; +const char* TAG_COMPRESS_ORI_LEN = "compressOriLen"; +const char* TAG_COMPRESS = "compressMsg"; +const char* TAG_STATE = "state"; +const char* TAG_REASON = "reason"; +const char* TAG_PEER_USER_ID = "peerUserId"; +const char* TAG_PEER_DISPLAY_ID = "peerDisplayId"; +const char* TAG_EXTRA_INFO = "extraInfo"; + +const char* TAG_IS_ONLINE = "isOnline"; +const char* TAG_IS_AUTHED = "isAuthed"; +const char* TAG_CREDENTIAL_INFO = "credentialInfo"; +const char* TAG_CERT_INFO = "certInfo"; + +// Accesser table content is used for ACL synchronization. +const char* TAG_ACCESSER_DEVICE_ID = "accesserDeviceId"; +const char* TAG_ACCESSER_USER_ID = "accesserUserId"; +const char* TAG_ACCESSER_ACOUNT_ID = "accesserAcountId"; +const char* TAG_ACCESSER_TOKEN_ID = "accesserTokenId"; +const char* TAG_ACCESSER_SERVICE_NAME = "accesserServiceName"; +const char* TAG_ACCESSER_BUNDLE_NAME = "accesserBundleName"; +const char* TAG_ACCESSER_HAP_SIGNATURE = "accesserHapSignature"; +const char* TAG_ACCESSER_BIND_LEVEL = "accesserBindLevel"; +const char* TAG_ACCESSER_CREDENTIAL_ID = "accesserCredetialId"; +const char* TAG_ACCESSER_STATUS = "accesserStatus"; +const char* TAG_ACCESSER_SK_ID = "accesserSessionKeyId"; +const char* TAG_ACCESSER_SK_TIMESTAMP = "accesserSKTimeStamp"; + +// Accessee table content is used for ACL synchronization. +const char* TAG_ACCESSEE_DEVICE_ID = "accesseeDeviceId"; +const char* TAG_ACCESSEE_USER_ID = "accesseeUserId"; +const char* TAG_ACCESSEE_ACOUNT_ID = "accesseeAcountId"; +const char* TAG_ACCESSEE_TOKEN_ID = "accesseeTokenId"; +const char* TAG_ACCESSEE_SERVICE_NAME = "accesseeServiceName"; +const char* TAG_ACCESSEE_BUNDLE_NAME = "accesseeBundleName"; +const char* TAG_ACCESSEE_HAP_SIGNATURE = "accesseeHapSignature"; +const char* TAG_ACCESSEE_BIND_LEVEL = "accesseeBindLevel"; +const char* TAG_ACCESSEE_CREDENTIAL_ID = "accesseeCredetialId"; +const char* TAG_ACCESSEE_STATUS = "accesseeStatus"; +const char* TAG_ACCESSEE_SK_ID = "accesseeSessionKeyId"; +const char* TAG_ACCESSEE_SK_TIMESTAMP = "accesseeSKTimeStamp"; + namespace { -constexpr const char* TAG_DEVICE_TYPE = "deviceType"; +constexpr const int32_t DM_HASH_LEN = 32; +const char* TAG_DEVICE_TYPE = "DEVICETYPE"; void CreateNegotiateExtraInfoMessage(std::shared_ptr context, JsonItemObject &jsonExtraObject) { if (context->accessee.displayId != 0) { - jsonExtraObject[DM_TAG_PEER_DISPLAY_ID] = context->accessee.displayId; + jsonExtraObject[TAG_PEER_DISPLAY_ID] = context->accessee.displayId; } if (context->accessee.userId != 0) { - jsonExtraObject[DM_TAG_ACCESSEE_USER_ID] = context->accessee.userId; + jsonExtraObject[TAG_ACCESSEE_USER_ID] = context->accessee.userId; } return; @@ -56,10 +141,10 @@ void CreateNegotiateExtraInfoMessage(std::shared_ptr context, Jso void ParseNegotiateExtraInfoMessage(const JsonItemObject &jsonExtraObject, std::shared_ptr context) { // accesser在extra中传输对端peerUserId和peerDisplayId时,从中获取userId - if (jsonExtraObject[DM_TAG_ACCESSEE_USER_ID].IsNumberInteger()) { - context->accessee.userId = jsonExtraObject[DM_TAG_ACCESSEE_USER_ID].Get(); - } else if (jsonExtraObject[DM_TAG_PEER_DISPLAY_ID].IsNumberInteger()) { - context->accessee.displayId = jsonExtraObject[DM_TAG_PEER_DISPLAY_ID].Get(); + if (jsonExtraObject[TAG_ACCESSEE_USER_ID].IsNumberInteger()) { + context->accessee.userId = jsonExtraObject[TAG_ACCESSEE_USER_ID].Get(); + } else if (jsonExtraObject[TAG_PEER_DISPLAY_ID].IsNumberInteger()) { + context->accessee.displayId = jsonExtraObject[TAG_PEER_DISPLAY_ID].Get(); } return; @@ -88,16 +173,16 @@ int32_t ParaseAclChecksumList(const std::string &jsonString, DmAccess &access) LOGE("ParseSyncMessage aclChecksumjson error"); return ERR_DM_FAILED; } - if (!aclChecksumjson[DM_TAG_ACCESSER].IsArray()) { // 再解析一次 acl - LOGE("ParseSyncMessage DM_TAG_ACCESSER error"); + if (!aclChecksumjson[TAG_ACCESSER].IsArray()) { // 再解析一次 acl + LOGE("ParseSyncMessage TAG_ACCESSER error"); return ERR_DM_FAILED; } - aclChecksumjson[DM_TAG_ACCESSER].Get(access.accesserStrList); - if (!aclChecksumjson[DM_TAG_ACCESSEE].IsArray()) { // 再解析一次 acl - LOGE("ParseSyncMessage DM_TAG_ACCESSEE error"); + aclChecksumjson[TAG_ACCESSER].Get(access.accesserStrList); + if (!aclChecksumjson[TAG_ACCESSEE].IsArray()) { // 再解析一次 acl + LOGE("ParseSyncMessage TAG_ACCESSEE error"); return ERR_DM_FAILED; } - aclChecksumjson[DM_TAG_ACCESSEE].Get(access.accesseeStrList); + aclChecksumjson[TAG_ACCESSEE].Get(access.accesseeStrList); return DM_OK; } @@ -359,12 +444,12 @@ static std::string vectorInt32ToString(const std::vector& vec) int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const JsonObject &jsonObject, std::shared_ptr context) { - if (jsonObject.IsDiscarded() || !jsonObject.Contains(DM_TAG_DATA) || !jsonObject[DM_TAG_DATA].IsString()) { + if (jsonObject.IsDiscarded() || !jsonObject.Contains(TAG_DATA) || !jsonObject[TAG_DATA].IsString()) { LOGE("DmAuthMessageProcessor::ParseMessageNegotiateTransmit Unlegal json string failed"); return ERR_DM_FAILED; } - context->transmitData = jsonObject[DM_TAG_DATA].Get(); + context->transmitData = jsonObject[TAG_DATA].Get(); switch (context->msgType) { case MSG_TYPE_REQ_CREDENTIAL_AUTH_NEGOTIATE: // 161 @@ -387,12 +472,12 @@ int32_t DmAuthMessageProcessor::ParseMessageNegotiateTransmit(const JsonObject & int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate(const JsonObject &jsonObject, std::shared_ptr context) { - if (jsonObject.IsDiscarded() || !jsonObject[DM_TAG_DATA].IsString()) { + if (jsonObject.IsDiscarded() || !jsonObject[TAG_DATA].IsString()) { LOGE("DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate failed, decodeRequestAuth jsonStr error"); return ERR_DM_FAILED; } - context->transmitData = jsonObject[DM_TAG_DATA].Get(); + context->transmitData = jsonObject[TAG_DATA].Get(); context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -401,14 +486,14 @@ int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthNegotiate(const JsonObjec int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const JsonObject &jsonObject, std::shared_ptr context) { - if (jsonObject.IsDiscarded() || !jsonObject[DM_TAG_DATA].IsString()) { + if (jsonObject.IsDiscarded() || !jsonObject[TAG_DATA].IsString()) { LOGE("DecodeRequestAuth jsonStr error"); return ERR_DM_FAILED; } // 解密 std::string plainText; - if (cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA].Get(), plainText) != DM_OK) { + if (cryptoMgr_->DecryptMessage(jsonObject[TAG_DATA].Get(), plainText) != DM_OK) { LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange() error, decrypt data failed."); return ERR_DM_FAILED; } @@ -416,24 +501,24 @@ int32_t DmAuthMessageProcessor::ParseMessageReqCredExchange(const JsonObject &js // 首次认证,解析用户级公钥 if (!context->isOnline) { - if (!jsonData[DM_TAG_LNN_PUBLICK_KEY].IsString()) { + if (!jsonData[TAG_LNN_PUBLICK_KEY].IsString()) { LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange() error, first auth, no lnnPublicKey."); return ERR_DM_FAILED; } - context->accesser.lnnPublicKey = jsonData[DM_TAG_LNN_PUBLICK_KEY].Get(); + context->accesser.lnnPublicKey = jsonData[TAG_LNN_PUBLICK_KEY].Get(); } - if (!jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY].IsString() || - !jsonData[DM_TAG_DEVICE_ID].IsString() || - !jsonData[DM_TAG_PEER_USER_SPACE_ID].IsNumberInteger() || - !jsonData[DM_TAG_TOKEN_ID].IsNumberInteger()) { + if (!jsonData[TAG_TRANSMIT_PUBLICK_KEY].IsString() || + !jsonData[TAG_DEVICE_ID].IsString() || + !jsonData[TAG_PEER_USER_SPACE_ID].IsNumberInteger() || + !jsonData[TAG_TOKEN_ID].IsNumberInteger()) { LOGE("DmAuthMessageProcessor::ParseMessageReqCredExchange, MSG_TYPE_REQ_CREDENTIAL_EXCHANGE message error."); return ERR_DM_FAILED; } - context->accesser.ephemeralPublicKey = jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY].Get(); // 解析应用级公钥 - context->accesser.deviceId = jsonData[DM_TAG_DEVICE_ID].Get(); // 解析deviceId - context->accesser.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].Get(); // 解析userId - context->accesser.tokenId = jsonData[DM_TAG_TOKEN_ID].Get(); // 解析tokenId + context->accesser.ephemeralPublicKey = jsonData[TAG_TRANSMIT_PUBLICK_KEY].Get(); // 解析应用级公钥 + context->accesser.deviceId = jsonData[TAG_DEVICE_ID].Get(); // 解析deviceId + context->accesser.userId = jsonData[TAG_PEER_USER_SPACE_ID].Get(); // 解析userId + context->accesser.tokenId = jsonData[TAG_TOKEN_ID].Get(); // 解析tokenId context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } @@ -443,14 +528,14 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &js std::shared_ptr context) { LOGI("DmAuthMessageProcessor::ParseMessageRspCredExchange start."); - if (jsonObject.IsDiscarded() || !jsonObject[DM_TAG_DATA].IsString()) { + if (jsonObject.IsDiscarded() || !jsonObject[TAG_DATA].IsString()) { LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange, DecodeRequestAuth jsonStr error"); return ERR_DM_FAILED; } // 解密 std::string plainText; - if (cryptoMgr_->DecryptMessage(jsonObject[DM_TAG_DATA].Get(), plainText) != DM_OK) { + if (cryptoMgr_->DecryptMessage(jsonObject[TAG_DATA].Get(), plainText) != DM_OK) { LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange error, decrypt data failed."); return ERR_DM_FAILED; } @@ -462,26 +547,26 @@ int32_t DmAuthMessageProcessor::ParseMessageRspCredExchange(const JsonObject &js // 首次认证,解析对方用户级公钥和协商用户级凭据Id std::string tmpString; if (!context->isOnline) { - if (!jsonData[DM_TAG_LNN_PUBLICK_KEY].IsString()) { + if (!jsonData[TAG_LNN_PUBLICK_KEY].IsString()) { LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange failed, first auth but no lnnPublicKey."); return ERR_DM_FAILED; } - context->accessee.lnnPublicKey = jsonData[DM_TAG_LNN_PUBLICK_KEY].Get(); + context->accessee.lnnPublicKey = jsonData[TAG_LNN_PUBLICK_KEY].Get(); } // 解析对方应用级公钥和协商应用级凭据Id - if (!jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY].IsString() || - !jsonData[DM_TAG_DEVICE_ID].IsString() || - !jsonData[DM_TAG_PEER_USER_SPACE_ID].IsNumberInteger() || - !jsonData[DM_TAG_TOKEN_ID].IsNumberInteger()) { + if (!jsonData[TAG_TRANSMIT_PUBLICK_KEY].IsString() || + !jsonData[TAG_DEVICE_ID].IsString() || + !jsonData[TAG_PEER_USER_SPACE_ID].IsNumberInteger() || + !jsonData[TAG_TOKEN_ID].IsNumberInteger()) { LOGE("DmAuthMessageProcessor::ParseMessageRspCredExchange failed, decode MSG_TYPE_RESP_CREDENTIAL_EXCHANGE " "message error."); return ERR_DM_FAILED; } - context->accessee.ephemeralPublicKey = jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY].Get(); - context->accessee.deviceId = jsonData[DM_TAG_DEVICE_ID].Get(); // 解析deviceId - context->accessee.userId = jsonData[DM_TAG_PEER_USER_SPACE_ID].Get(); // 解析userId - context->accessee.tokenId = jsonData[DM_TAG_TOKEN_ID].Get(); // 解析tokenId + context->accessee.ephemeralPublicKey = jsonData[TAG_TRANSMIT_PUBLICK_KEY].Get(); + context->accessee.deviceId = jsonData[TAG_DEVICE_ID].Get(); // 解析deviceId + context->accessee.userId = jsonData[TAG_PEER_USER_SPACE_ID].Get(); // 解析userId + context->accessee.tokenId = jsonData[TAG_TOKEN_ID].Get(); // 解析tokenId context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; @@ -509,7 +594,7 @@ int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr JsonObject &jsonObject) { std::string encryptMsg; - jsonObject[DM_TAG_DATA] = context->transmitData; + jsonObject[TAG_DATA] = context->transmitData; return DM_OK; } @@ -517,10 +602,10 @@ int32_t DmAuthMessageProcessor::CreateCredentialNegotiateMessage(std::shared_ptr int32_t DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptr context, JsonObject &jsonObject) { jsonObject[TAG_SESSION_NAME] = context->sessionName; - jsonObject[DM_TAG_DMVERSION] = context->accesser.dmVersion; + jsonObject[TAG_DMVERSION] = context->accesser.dmVersion; - jsonObject[DM_TAG_USER_ID] = context->accesser.userId; - jsonObject[DM_TAG_TOKEN_ID] = static_cast(context->accesser.tokenId); + jsonObject[TAG_USER_ID] = context->accesser.userId; + jsonObject[TAG_TOKEN_ID] = static_cast(context->accesser.tokenId); jsonObject[TAG_DEVICE_ID_HASH] = context->accesser.deviceIdHash; jsonObject[TAG_USER_ID_HASH] = context->accesser.userIdHash; @@ -533,7 +618,7 @@ int32_t DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptrisOnline) { - jsonData[DM_TAG_LNN_PUBLICK_KEY] = context->accesser.lnnPublicKey; + jsonData[TAG_LNN_PUBLICK_KEY] = context->accesser.lnnPublicKey; } - jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY] = context->accesser.ephemeralPublicKey; - jsonData[DM_TAG_DEVICE_ID] = context->accesser.deviceId; - jsonData[DM_TAG_PEER_USER_SPACE_ID] = context->accesser.userId; - jsonData[DM_TAG_TOKEN_ID] = context->accesser.tokenId; + jsonData[TAG_TRANSMIT_PUBLICK_KEY] = context->accesser.ephemeralPublicKey; + jsonData[TAG_DEVICE_ID] = context->accesser.deviceId; + jsonData[TAG_PEER_USER_SPACE_ID] = context->accesser.userId; + jsonData[TAG_TOKEN_ID] = context->accesser.tokenId; std::string plainText = jsonData.Dump(); std::string cipherText; @@ -578,7 +663,7 @@ int32_t DmAuthMessageProcessor::CreateMessageReqCredExchange(std::shared_ptrisOnline) { - jsonData[DM_TAG_LNN_PUBLICK_KEY] = context->accessee.lnnPublicKey; + jsonData[TAG_LNN_PUBLICK_KEY] = context->accessee.lnnPublicKey; } - jsonData[DM_TAG_TRANSMIT_PUBLICK_KEY] = context->accessee.ephemeralPublicKey; // 本端应用级公钥 - jsonData[DM_TAG_DEVICE_ID] = context->accessee.deviceId; // 本端deviceId - jsonData[DM_TAG_PEER_USER_SPACE_ID] = context->accessee.userId; // 本端userId - jsonData[DM_TAG_TOKEN_ID] = context->accessee.tokenId; // 本端tokenId + jsonData[TAG_TRANSMIT_PUBLICK_KEY] = context->accessee.ephemeralPublicKey; // 本端应用级公钥 + jsonData[TAG_DEVICE_ID] = context->accessee.deviceId; // 本端deviceId + jsonData[TAG_PEER_USER_SPACE_ID] = context->accessee.userId; // 本端userId + jsonData[TAG_TOKEN_ID] = context->accessee.tokenId; // 本端tokenId std::string plainText = jsonData.Dump(); std::string cipherText; @@ -604,7 +689,7 @@ int32_t DmAuthMessageProcessor::CreateMessageRspCredExchange(std::shared_ptrtransmitData; + jsonObject[TAG_DATA] = context->transmitData; return DM_OK; } @@ -653,7 +738,7 @@ int32_t DmAuthMessageProcessor::CreateMessageSyncResp(std::shared_ptr context, JsonObject &jsonObject) { - jsonObject[DM_TAG_REPLY] = context->reply; - jsonObject[DM_TAG_STATE] = context->state; - jsonObject[DM_TAG_REASON] = context->reason; + jsonObject[TAG_REPLY] = context->reply; + jsonObject[TAG_STATE] = context->state; + jsonObject[TAG_REASON] = context->reason; return DM_OK; } @@ -671,60 +756,60 @@ int32_t DmAuthMessageProcessor::ParseSyncMessage(std::shared_ptr DmAccess &access, JsonObject &jsonObject) { // transmit session key is mandatory - if (!jsonObject[DM_TAG_TRANSMIT_SK_ID].IsString()) { - LOGE("ParseSyncMessage DM_TAG_TRANSMIT_SK_ID error"); + if (!jsonObject[TAG_TRANSMIT_SK_ID].IsString()) { + LOGE("ParseSyncMessage TAG_TRANSMIT_SK_ID error"); return ERR_DM_FAILED; } - access.transmitSessionKeyId = std::atoi(jsonObject[DM_TAG_TRANSMIT_SK_ID].Get().c_str()); + access.transmitSessionKeyId = std::atoi(jsonObject[TAG_TRANSMIT_SK_ID].Get().c_str()); - if (!jsonObject[DM_TAG_TRANSMIT_SK_TIMESTAMP].IsString()) { - LOGE("ParseSyncMessage DM_TAG_TRANSMIT_SK_TIMESTAMP error"); + if (!jsonObject[TAG_TRANSMIT_SK_TIMESTAMP].IsString()) { + LOGE("ParseSyncMessage TAG_TRANSMIT_SK_TIMESTAMP error"); return ERR_DM_FAILED; } - access.transmitSkTimeStamp = std::atoi(jsonObject[DM_TAG_TRANSMIT_SK_TIMESTAMP].Get().c_str()); + access.transmitSkTimeStamp = std::atoi(jsonObject[TAG_TRANSMIT_SK_TIMESTAMP].Get().c_str()); - if (!jsonObject[DM_TAG_TRANSMIT_CREDENTIAL_ID].IsString()) { - LOGE("ParseSyncMessage DM_TAG_TRANSMIT_CREDENTIAL_ID error"); + if (!jsonObject[TAG_TRANSMIT_CREDENTIAL_ID].IsString()) { + LOGE("ParseSyncMessage TAG_TRANSMIT_CREDENTIAL_ID error"); return ERR_DM_FAILED; } - access.transmitCredentialId = jsonObject[DM_TAG_TRANSMIT_CREDENTIAL_ID].Get().c_str(); + access.transmitCredentialId = jsonObject[TAG_TRANSMIT_CREDENTIAL_ID].Get().c_str(); // lnn session key is optional - if (jsonObject[DM_TAG_LNN_SK_ID].IsString()) { - access.lnnSessionKeyId = std::atoi(jsonObject[DM_TAG_LNN_SK_ID].Get().c_str()); + if (jsonObject[TAG_LNN_SK_ID].IsString()) { + access.lnnSessionKeyId = std::atoi(jsonObject[TAG_LNN_SK_ID].Get().c_str()); } - if (jsonObject[DM_TAG_LNN_SK_TIMESTAMP].IsString()) { - access.lnnSkTimeStamp = std::atoi(jsonObject[DM_TAG_LNN_SK_TIMESTAMP].Get().c_str()); + if (jsonObject[TAG_LNN_SK_TIMESTAMP].IsString()) { + access.lnnSkTimeStamp = std::atoi(jsonObject[TAG_LNN_SK_TIMESTAMP].Get().c_str()); } - if (jsonObject[DM_TAG_LNN_CREDENTIAL_ID].IsString()) { - access.lnnCredentialId = jsonObject[DM_TAG_LNN_CREDENTIAL_ID].Get().c_str(); + if (jsonObject[TAG_LNN_CREDENTIAL_ID].IsString()) { + access.lnnCredentialId = jsonObject[TAG_LNN_CREDENTIAL_ID].Get().c_str(); } - if (!jsonObject[DM_TAG_DMVERSION].IsString()) { - LOGE("ParseSyncMessage DM_TAG_DMVERSION error"); + if (!jsonObject[TAG_DMVERSION].IsString()) { + LOGE("ParseSyncMessage TAG_DMVERSION error"); return ERR_DM_FAILED; } - access.dmVersion = jsonObject[DM_TAG_DMVERSION].Get(); - if (!jsonObject[DM_TAG_ACCESS].IsString()) { // 再解析一次 - LOGE("ParseSyncMessage DM_TAG_ACCESS error"); + access.dmVersion = jsonObject[TAG_DMVERSION].Get(); + if (!jsonObject[TAG_ACCESS].IsString()) { // 再解析一次 + LOGE("ParseSyncMessage TAG_ACCESS error"); return ERR_DM_FAILED; } - std::string srcAccessStr = jsonObject[DM_TAG_ACCESS].Get(); + std::string srcAccessStr = jsonObject[TAG_ACCESS].Get(); // 解析到 access里面 ParseDmAccessToSync(srcAccessStr, access); - if (jsonObject[DM_TAG_PROXY].IsString()) { // 预留字段 - std::string proxyInfo = jsonObject[DM_TAG_PROXY].Get(); + if (jsonObject[TAG_PROXY].IsString()) { // 预留字段 + std::string proxyInfo = jsonObject[TAG_PROXY].Get(); } - if (jsonObject[DM_TAG_SERVICEINFO].IsString()) { // sp 暂时没有传 - std::string serviceInfo = jsonObject[DM_TAG_SERVICEINFO].Get(); + if (jsonObject[TAG_SERVICEINFO].IsString()) { // sp 暂时没有传 + std::string serviceInfo = jsonObject[TAG_SERVICEINFO].Get(); } - if (!jsonObject[DM_TAG_ACL_CHECKSUM].IsString()) { // 再解析一次 acl - LOGE("ParseSyncMessage DM_TAG_ACL_CHECKSUM error"); + if (!jsonObject[TAG_ACL_CHECKSUM].IsString()) { // 再解析一次 acl + LOGE("ParseSyncMessage TAG_ACL_CHECKSUM error"); return ERR_DM_FAILED; } - std::string aclChecksumList = jsonObject[DM_TAG_ACL_CHECKSUM].Get(); + std::string aclChecksumList = jsonObject[TAG_ACL_CHECKSUM].Get(); return ParaseAclChecksumList(aclChecksumList, access); } @@ -744,16 +829,16 @@ DecryptSyncMessage(std::shared_ptr &context, LOGE("DecryptSyncMessage plainJson error"); return ERR_DM_FAILED; } - if (!plainJson[DM_TAG_COMPRESS_ORI_LEN].IsNumberInteger()) { - LOGE("DecryptSyncMessage DM_TAG_COMPRESS_ORI_LEN json error"); + if (!plainJson[TAG_COMPRESS_ORI_LEN].IsNumberInteger()) { + LOGE("DecryptSyncMessage TAG_COMPRESS_ORI_LEN json error"); return ERR_DM_FAILED; } - int32_t dataLen = plainJson[DM_TAG_COMPRESS_ORI_LEN].Get(); - if (!plainJson[DM_TAG_COMPRESS].IsString()) { - LOGE("DecryptSyncMessage DM_TAG_COMPRESS_ORI_LEN json error"); + int32_t dataLen = plainJson[TAG_COMPRESS_ORI_LEN].Get(); + if (!plainJson[TAG_COMPRESS].IsString()) { + LOGE("DecryptSyncMessage TAG_COMPRESS_ORI_LEN json error"); return ERR_DM_FAILED; } - std::string compressMsg = plainJson[DM_TAG_COMPRESS].Get(); + std::string compressMsg = plainJson[TAG_COMPRESS].Get(); // 解压缩 std::string compressBase64 = Base64Decode(compressMsg); std::string syncMsg = DecompressSyncMsg(compressBase64, dataLen); @@ -777,11 +862,11 @@ int32_t DmAuthMessageProcessor::ParseMessageSyncReq(const JsonObject &jsonObject std::shared_ptr context) { // 解析json中的加密数据 - if (!jsonObject[DM_TAG_SYNC].IsString()) { // 再解析一次 acl + if (!jsonObject[TAG_SYNC].IsString()) { // 再解析一次 acl LOGE("ParseMessageSyncReq json error"); return ERR_DM_FAILED; } - std::string enSyncMsg = jsonObject[DM_TAG_SYNC].Get(); + std::string enSyncMsg = jsonObject[TAG_SYNC].Get(); // 解密数据 + 解析数据到context中 int32_t ret = DecryptSyncMessage(context, context->accesser, enSyncMsg); if (ret != DM_OK) { @@ -797,11 +882,11 @@ int32_t DmAuthMessageProcessor::ParseMessageSyncResp(const JsonObject &jsonObjec std::shared_ptr context) { // 解析json中的加密数据 - if (!jsonObject[DM_TAG_SYNC].IsString()) { // 再解析一次 acl + if (!jsonObject[TAG_SYNC].IsString()) { // 再解析一次 acl LOGE("ParseMessageSyncResp json error"); return ERR_DM_FAILED; } - std::string enSyncMsg = jsonObject[DM_TAG_SYNC].Get(); + std::string enSyncMsg = jsonObject[TAG_SYNC].Get(); // 解密数据 + 解析数据到context中 int32_t ret = DecryptSyncMessage(context, context->accessee, enSyncMsg); if (ret != DM_OK) { @@ -819,14 +904,14 @@ int32_t DmAuthMessageProcessor::ParseMessageSinkFinish(const JsonObject &jsonObj /* In case of an exception, there may be a state waiting for an event. In the normal process, no state is waiting for events. */ context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); - if (jsonObject[DM_TAG_REPLY].IsNumberInteger()) { - context->reply = jsonObject[DM_TAG_REPLY].Get(); + if (jsonObject[TAG_REPLY].IsNumberInteger()) { + context->reply = jsonObject[TAG_REPLY].Get(); } - if (jsonObject[DM_TAG_STATE].IsNumberInteger()) { - context->state = jsonObject[DM_TAG_STATE].Get(); + if (jsonObject[TAG_STATE].IsNumberInteger()) { + context->state = jsonObject[TAG_STATE].Get(); } - if (jsonObject[DM_TAG_REASON].IsNumberInteger()) { - context->reason = jsonObject[DM_TAG_REASON].Get(); + if (jsonObject[TAG_REASON].IsNumberInteger()) { + context->reason = jsonObject[TAG_REASON].Get(); } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; @@ -839,14 +924,14 @@ int32_t DmAuthMessageProcessor::ParseMessageSrcFinish(const JsonObject &jsonObje /* In case of an exception, there may be a state waiting for an event. In the normal process, no state is waiting for events. */ context->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); - if (jsonObject[DM_TAG_REPLY].IsNumberInteger()) { - context->reply = jsonObject[DM_TAG_REPLY].Get(); + if (jsonObject[TAG_REPLY].IsNumberInteger()) { + context->reply = jsonObject[TAG_REPLY].Get(); } - if (jsonObject[DM_TAG_STATE].IsNumberInteger()) { - context->state = jsonObject[DM_TAG_STATE].Get(); + if (jsonObject[TAG_STATE].IsNumberInteger()) { + context->state = jsonObject[TAG_STATE].Get(); } - if (jsonObject[DM_TAG_REASON].IsNumberInteger()) { - context->reason = jsonObject[DM_TAG_REASON].Get(); + if (jsonObject[TAG_REASON].IsNumberInteger()) { + context->reason = jsonObject[TAG_REASON].Get(); } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; @@ -855,17 +940,17 @@ int32_t DmAuthMessageProcessor::ParseMessageSrcFinish(const JsonObject &jsonObje int32_t DmAuthMessageProcessor::ParseNegotiateMessage(const JsonObject &jsonObject, std::shared_ptr context) { - if (jsonObject[DM_TAG_DMVERSION].IsString()) { - context->accesser.dmVersion = jsonObject[DM_TAG_DMVERSION].Get(); + if (jsonObject[TAG_DMVERSION].IsString()) { + context->accesser.dmVersion = jsonObject[TAG_DMVERSION].Get(); } - if (jsonObject[DM_TAG_EDITION].IsString()) { - context->accesser.edition = jsonObject[DM_TAG_EDITION].Get(); + if (jsonObject[TAG_EDITION].IsString()) { + context->accesser.edition = jsonObject[TAG_EDITION].Get(); } - if (jsonObject[DM_TAG_USER_ID].IsNumberInteger()) { - context->accesser.userId = jsonObject[DM_TAG_USER_ID].Get(); + if (jsonObject[TAG_USER_ID].IsNumberInteger()) { + context->accesser.userId = jsonObject[TAG_USER_ID].Get(); } - if (jsonObject[DM_TAG_TOKEN_ID].IsNumberInteger()) { - context->accesser.tokenId = static_cast(jsonObject[DM_TAG_TOKEN_ID].Get()); + if (jsonObject[TAG_TOKEN_ID].IsNumberInteger()) { + context->accesser.tokenId = static_cast(jsonObject[TAG_TOKEN_ID].Get()); context->requestId = context->accesser.tokenId; } @@ -895,8 +980,8 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(const JsonObject &jsonObje context->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].Get(); } - if (jsonObject.Contains(DM_TAG_EXTRA_INFO) && jsonObject[DM_TAG_EXTRA_INFO].IsObject()) { - ParseNegotiateExtraInfoMessage(jsonObject[DM_TAG_EXTRA_INFO], context); + if (jsonObject.Contains(TAG_EXTRA_INFO) && jsonObject[TAG_EXTRA_INFO].IsObject()) { + ParseNegotiateExtraInfoMessage(jsonObject[TAG_EXTRA_INFO], context); } context->authStateMachine->TransitionTo(std::make_shared()); @@ -972,12 +1057,12 @@ int32_t DmAuthMessageProcessor::ParseMessageReqUserConfirm(const JsonObject &jso int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const JsonObject &json, std::shared_ptr context) { - if (json[DM_TAG_AUTH_RESULT].IsNumberInteger()) { - context->authResult = static_cast(json[DM_TAG_AUTH_RESULT].Get()); + if (json[TAG_AUTH_RESULT].IsNumberInteger()) { + context->authResult = static_cast(json[TAG_AUTH_RESULT].Get()); } - if (json[DM_TAG_AUTH_TYPE_LIST].IsString()) { - auto strList = json[DM_TAG_AUTH_TYPE_LIST].Get(); + if (json[TAG_AUTH_TYPE_LIST].IsString()) { + auto strList = json[TAG_AUTH_TYPE_LIST].Get(); context->authTypeList = stringToVectorAuthType(strList); } @@ -988,8 +1073,8 @@ int32_t DmAuthMessageProcessor::ParseMessageRespUserConfirm(const JsonObject &js int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const JsonObject &json, std::shared_ptr context) { - if (json[DM_TAG_DATA].IsString()) { - context->transmitData = json[DM_TAG_DATA].Get(); + if (json[TAG_DATA].IsString()) { + context->transmitData = json[TAG_DATA].Get(); } context->authStateMachine->TransitionTo(std::make_shared()); @@ -999,8 +1084,8 @@ int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthStart(const JsonObject &js int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthStart(const JsonObject &json, std::shared_ptr context) { - if (json[DM_TAG_DATA].IsString()) { - context->transmitData = json[DM_TAG_DATA].Get(); + if (json[TAG_DATA].IsString()) { + context->transmitData = json[TAG_DATA].Get(); } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; @@ -1009,8 +1094,8 @@ int32_t DmAuthMessageProcessor::ParseMessageRespPinAuthStart(const JsonObject &j int32_t DmAuthMessageProcessor::ParseMessageReqPinAuthNegotiate(const JsonObject &json, std::shared_ptr context) { - if (json[DM_TAG_DATA].IsString()) { - context->transmitData = json[DM_TAG_DATA].Get(); + if (json[TAG_DATA].IsString()) { + context->transmitData = json[TAG_DATA].Get(); } context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; @@ -1027,34 +1112,34 @@ int32_t DmAuthMessageProcessor::CreateMessageReqUserConfirm(std::shared_ptr context, JsonObject &json) { - json[DM_TAG_AUTH_RESULT] = context->authResult; - json[DM_TAG_AUTH_TYPE_LIST] = vectorAuthTypeToString(context->authTypeList); + json[TAG_AUTH_RESULT] = context->authResult; + json[TAG_AUTH_TYPE_LIST] = vectorAuthTypeToString(context->authTypeList); return DM_OK; } int32_t DmAuthMessageProcessor::CreateMessageReqPinAuthStart(std::shared_ptr context, JsonObject &json) { - json[DM_TAG_DATA] = context->transmitData; + json[TAG_DATA] = context->transmitData; return DM_OK; } int32_t DmAuthMessageProcessor::CreateMessageRespPinAuthStart(std::shared_ptr context, JsonObject &json) { - json[DM_TAG_DATA] = context->transmitData; + json[TAG_DATA] = context->transmitData; return DM_OK; } int32_t DmAuthMessageProcessor::CreateMessageReqPinAuthNegotiate(std::shared_ptr context, JsonObject &json) { - json[DM_TAG_DATA] = context->transmitData; + json[TAG_DATA] = context->transmitData; return DM_OK; } int32_t DmAuthMessageProcessor::CreateMessageRespPinAuthNegotiate(std::shared_ptr context, JsonObject &json) { - json[DM_TAG_DATA] = context->transmitData; + json[TAG_DATA] = context->transmitData; return DM_OK; } @@ -1151,20 +1236,20 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptrisOnline) { // 首次认证 - syncMsgJson[DM_TAG_LNN_SK_ID]=std::to_string(accessSide.lnnSessionKeyId); - syncMsgJson[DM_TAG_LNN_SK_TIMESTAMP]=std::to_string(accessSide.lnnSkTimeStamp); - syncMsgJson[DM_TAG_LNN_CREDENTIAL_ID] = accessSide.lnnCredentialId; + syncMsgJson[TAG_LNN_SK_ID]=std::to_string(accessSide.lnnSessionKeyId); + syncMsgJson[TAG_LNN_SK_TIMESTAMP]=std::to_string(accessSide.lnnSkTimeStamp); + syncMsgJson[TAG_LNN_CREDENTIAL_ID] = accessSide.lnnCredentialId; } JsonObject accessJsonObj{}; accessJsonObj = accessToSync; - syncMsgJson[DM_TAG_DMVERSION] = accessSide.dmVersion; - syncMsgJson[DM_TAG_ACCESS] = accessJsonObj.Dump(); // 接收端需要再拆一次json - syncMsgJson[DM_TAG_PROXY] = ""; // 预留字段 留空即可 + syncMsgJson[TAG_DMVERSION] = accessSide.dmVersion; + syncMsgJson[TAG_ACCESS] = accessJsonObj.Dump(); // 接收端需要再拆一次json + syncMsgJson[TAG_PROXY] = ""; // 预留字段 留空即可 std::string aclHashList; int32_t ret = GetAclListStr(context, aclHashList); if (ret != DM_OK) { @@ -1172,7 +1257,7 @@ int32_t DmAuthMessageProcessor::EncryptSyncMessage(std::shared_ptrEncryptMessage(plainJson.Dump(), encSyncMsg); } @@ -1217,18 +1302,18 @@ std::string DmAuthMessageProcessor::AccesserToStr(DistributedDeviceProfile::Acce { JsonObject jsonAccesserObj; DistributedDeviceProfile::Accesser accesser = acl.GetAccesser(); - jsonAccesserObj[DM_TAG_ACCESSER_DEVICE_ID] = accesser.GetAccesserDeviceId(); - jsonAccesserObj[DM_TAG_ACCESSER_USER_ID] = accesser.GetAccesserUserId(); - jsonAccesserObj[DM_TAG_ACCESSER_ACOUNT_ID] = accesser.GetAccesserAccountId(); - jsonAccesserObj[DM_TAG_ACCESSER_TOKEN_ID] = accesser.GetAccesserTokenId(); - jsonAccesserObj[DM_TAG_ACCESSER_SERVICE_NAME] = std::vector(); // 预留字段 DP库未适配 - jsonAccesserObj[DM_TAG_ACCESSER_BUNDLE_NAME] = accesser.GetAccesserBundleName(); - jsonAccesserObj[DM_TAG_ACCESSER_HAP_SIGNATURE] = accesser.GetAccesserHapSignature(); - jsonAccesserObj[DM_TAG_ACCESSER_BIND_LEVEL] = accesser.GetAccesserBindLevel(); - jsonAccesserObj[DM_TAG_ACCESSER_CREDENTIAL_ID] = accesser.GetAccesserBindLevel(); - jsonAccesserObj[DM_TAG_ACCESSER_STATUS] = accesser.GetAccesserStatus(); - jsonAccesserObj[DM_TAG_ACCESSER_SK_ID] = accesser.GetAccesserSessionKeyId(); - jsonAccesserObj[DM_TAG_ACCESSER_SK_TIMESTAMP] = accesser.GetAccesserSKTimeStamp(); + jsonAccesserObj[TAG_ACCESSER_DEVICE_ID] = accesser.GetAccesserDeviceId(); + jsonAccesserObj[TAG_ACCESSER_USER_ID] = accesser.GetAccesserUserId(); + jsonAccesserObj[TAG_ACCESSER_ACOUNT_ID] = accesser.GetAccesserAccountId(); + jsonAccesserObj[TAG_ACCESSER_TOKEN_ID] = accesser.GetAccesserTokenId(); + jsonAccesserObj[TAG_ACCESSER_SERVICE_NAME] = std::vector(); // 预留字段 DP库未适配 + jsonAccesserObj[TAG_ACCESSER_BUNDLE_NAME] = accesser.GetAccesserBundleName(); + jsonAccesserObj[TAG_ACCESSER_HAP_SIGNATURE] = accesser.GetAccesserHapSignature(); + jsonAccesserObj[TAG_ACCESSER_BIND_LEVEL] = accesser.GetAccesserBindLevel(); + jsonAccesserObj[TAG_ACCESSER_CREDENTIAL_ID] = accesser.GetAccesserBindLevel(); + jsonAccesserObj[TAG_ACCESSER_STATUS] = accesser.GetAccesserStatus(); + jsonAccesserObj[TAG_ACCESSER_SK_ID] = accesser.GetAccesserSessionKeyId(); + jsonAccesserObj[TAG_ACCESSER_SK_TIMESTAMP] = accesser.GetAccesserSKTimeStamp(); return jsonAccesserObj.Dump(); } @@ -1236,18 +1321,18 @@ std::string DmAuthMessageProcessor::AccesseeToStr(DistributedDeviceProfile::Acce { JsonObject jsonAccesseeObj; DistributedDeviceProfile::Accessee accessee = acl.GetAccessee(); - jsonAccesseeObj[DM_TAG_ACCESSEE_DEVICE_ID] = accessee.GetAccesseeDeviceId(); - jsonAccesseeObj[DM_TAG_ACCESSEE_USER_ID] = accessee.GetAccesseeUserId(); - jsonAccesseeObj[DM_TAG_ACCESSEE_ACOUNT_ID] = accessee.GetAccesseeAccountId(); - jsonAccesseeObj[DM_TAG_ACCESSEE_TOKEN_ID] = accessee.GetAccesseeTokenId(); - jsonAccesseeObj[DM_TAG_ACCESSEE_SERVICE_NAME] = std::vector(); // 预留字段 DP库未适配 - jsonAccesseeObj[DM_TAG_ACCESSEE_BUNDLE_NAME] = accessee.GetAccesseeBundleName(); - jsonAccesseeObj[DM_TAG_ACCESSEE_HAP_SIGNATURE] = accessee.GetAccesseeHapSignature(); - jsonAccesseeObj[DM_TAG_ACCESSEE_BIND_LEVEL] = accessee.GetAccesseeBindLevel(); - jsonAccesseeObj[DM_TAG_ACCESSEE_CREDENTIAL_ID] = accessee.GetAccesseeBindLevel(); - jsonAccesseeObj[DM_TAG_ACCESSEE_STATUS] = accessee.GetAccesseeStatus(); - jsonAccesseeObj[DM_TAG_ACCESSEE_SK_ID] = accessee.GetAccesseeSessionKeyId(); - jsonAccesseeObj[DM_TAG_ACCESSEE_SK_TIMESTAMP] = accessee.GetAccesseeSKTimeStamp(); + jsonAccesseeObj[TAG_ACCESSEE_DEVICE_ID] = accessee.GetAccesseeDeviceId(); + jsonAccesseeObj[TAG_ACCESSEE_USER_ID] = accessee.GetAccesseeUserId(); + jsonAccesseeObj[TAG_ACCESSEE_ACOUNT_ID] = accessee.GetAccesseeAccountId(); + jsonAccesseeObj[TAG_ACCESSEE_TOKEN_ID] = accessee.GetAccesseeTokenId(); + jsonAccesseeObj[TAG_ACCESSEE_SERVICE_NAME] = std::vector(); // 预留字段 DP库未适配 + jsonAccesseeObj[TAG_ACCESSEE_BUNDLE_NAME] = accessee.GetAccesseeBundleName(); + jsonAccesseeObj[TAG_ACCESSEE_HAP_SIGNATURE] = accessee.GetAccesseeHapSignature(); + jsonAccesseeObj[TAG_ACCESSEE_BIND_LEVEL] = accessee.GetAccesseeBindLevel(); + jsonAccesseeObj[TAG_ACCESSEE_CREDENTIAL_ID] = accessee.GetAccesseeBindLevel(); + jsonAccesseeObj[TAG_ACCESSEE_STATUS] = accessee.GetAccesseeStatus(); + jsonAccesseeObj[TAG_ACCESSEE_SK_ID] = accessee.GetAccesseeSessionKeyId(); + jsonAccesseeObj[TAG_ACCESSEE_SK_TIMESTAMP] = accessee.GetAccesseeSKTimeStamp(); return jsonAccesseeObj.Dump(); } @@ -1265,7 +1350,7 @@ int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr LOGE("DmAuthMessageProcessor::CreateSyncMessage encrypt failed"); return ret; } - jsonObject[DM_TAG_SYNC] = encSyncMsg; + jsonObject[TAG_SYNC] = encSyncMsg; return DM_OK; } @@ -1273,12 +1358,12 @@ int32_t DmAuthMessageProcessor::CreateSyncMessage(std::shared_ptr int32_t DmAuthMessageProcessor::ParseAuthStartMessage(const JsonObject &jsonObject, std::shared_ptr context) { - if (jsonObject.IsDiscarded() || !jsonObject.Contains(DM_TAG_DATA) || - !jsonObject[DM_TAG_DATA].IsString()) { + if (jsonObject.IsDiscarded() || !jsonObject.Contains(TAG_DATA) || + !jsonObject[TAG_DATA].IsString()) { LOGE("DmAuthMessageProcessor::ParseAuthStartMessage Unlegal json string failed"); return ERR_DM_FAILED; } - context->transmitData = jsonObject[DM_TAG_DATA].Get(); + context->transmitData = jsonObject[TAG_DATA].Get(); context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; @@ -1287,7 +1372,7 @@ int32_t DmAuthMessageProcessor::ParseAuthStartMessage(const JsonObject &jsonObje int32_t DmAuthMessageProcessor::GetAclListStr(std::shared_ptr &context, std::string &aclList) { JsonObject jsonAclListObj; - jsonAclListObj[DM_TAG_DMVERSION] = context->accesser.dmVersion; // 在80/90 流程会协商出双方均兼容的版本号,此处取accesser的ver即可 + jsonAclListObj[TAG_DMVERSION] = context->accesser.dmVersion; // 在80/90 流程会协商出双方均兼容的版本号,此处取accesser的ver即可 // 查询ACL std::vector profiles = @@ -1316,8 +1401,8 @@ int32_t DmAuthMessageProcessor::GetAclListStr(std::shared_ptr &co LOGI("DmAuthMessageProcessor::CreateSyncMessage acl lis is empty"); // 双方无旧ACL需要同步 此时返回空字符串 } - jsonAclListObj[DM_TAG_ACCESSER] = accceserStrList; - jsonAclListObj[DM_TAG_ACCESSEE] = accceseeStrList; + jsonAclListObj[TAG_ACCESSER] = accceserStrList; + jsonAclListObj[TAG_ACCESSEE] = accceseeStrList; aclList = jsonAclListObj.Dump(); return DM_OK; } diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 80c792de7..49dc900b9 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -69,11 +69,11 @@ bool IsMessageOldVersion(int sessionId, const void *data, unsigned int dataLen) std::string dmVersion = ""; std::string edition = ""; - if (IsString(jsonObject, DM_TAG_DMVERSION)) { - dmVersion = jsonObject[DM_TAG_DMVERSION].Get(); + if (IsString(jsonObject, TAG_DMVERSION)) { + dmVersion = jsonObject[TAG_DMVERSION].Get(); } - if (IsString(jsonObject, DM_TAG_EDITION)) { - edition = jsonObject[DM_TAG_EDITION].Get(); + if (IsString(jsonObject, TAG_EDITION)) { + edition = jsonObject[TAG_EDITION].Get(); } dmVersion = AuthManagerBase::ConvertSrcVersion(dmVersion, edition); @@ -448,13 +448,13 @@ int32_t DeviceManagerServiceImpl::CreateAuthMgrByMessage(int sessionId, const vo // 获取版本号 std::string dmVersion; std::string edition = ""; - if (IsString(jsonObject, DM_TAG_DMVERSION) == false) { + if (IsString(jsonObject, TAG_DMVERSION) == false) { LOGE("DeviceManagerServiceImpl::CreateAuthMgrByMessage decode dmversion error"); return ERR_DM_JSON_PARSE_STRING; } - dmVersion = jsonObject[DM_TAG_DMVERSION].Get(); - if (IsString(jsonObject, DM_TAG_EDITION)) { - edition = jsonObject[DM_TAG_EDITION].Get(); + dmVersion = jsonObject[TAG_DMVERSION].Get(); + if (IsString(jsonObject, TAG_EDITION)) { + edition = jsonObject[TAG_EDITION].Get(); } dmVersion = AuthManagerBase::ConvertSrcVersion(dmVersion, edition); -- Gitee From 51d3b8eda0647c2b218432960c46cf451099d282 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Thu, 27 Mar 2025 20:30:29 +0800 Subject: [PATCH 312/382] =?UTF-8?q?fix=EF=BC=9A=E5=87=AD=E6=8D=AE=E5=86=99?= =?UTF-8?q?=E5=85=A50=EF=BC=8C=E8=B0=83=E8=AF=95=E4=BD=BF=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../implementation/src/authentication_v2/auth_manager.cpp | 1 - .../src/authentication_v2/dm_auth_message_processor.cpp | 4 ++++ 2 files changed, 4 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 613046349..ffb78be10 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -162,7 +162,6 @@ AuthManager::AuthManager(std::shared_ptr softbusConnector, bool AuthManager::IsAuthManagerConstructSuccess() { - LOGI("AuthManager::IsAuthManagerConstructSuccess, check authManager member."); return context_ != nullptr && context_->softbusConnector != nullptr && context_->listener != nullptr && diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 2658bd470..da3e37402 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -248,6 +248,7 @@ void DmAuthMessageProcessor::SetTransmitAccessControlList(std::shared_ptraccesser.bundleName); accesser.SetAccesserDeviceName(context->accesser.deviceName); // accesser.SetAccesserCredentialId(stoi(context->accesser.transmitCredentialId)); + accesser.SetAccesserCredentialId(0); accesser.SetAccesserSessionKeyId(context->accesser.transmitSessionKeyId); accesser.SetAccesserSKTimeStamp(context->accesser.transmitSkTimeStamp); accessee.SetAccesseeDeviceId(context->accessee.deviceId); @@ -257,6 +258,7 @@ void DmAuthMessageProcessor::SetTransmitAccessControlList(std::shared_ptraccessee.bundleName); accessee.SetAccesseeDeviceName(context->accessee.deviceName); // accessee.SetAccesseeCredentialId(stoi(context->accessee.transmitCredentialId)); + accessee.SetAccesseeCredentialId(0); accessee.SetAccesseeSessionKeyId(context->accessee.transmitSessionKeyId); accessee.SetAccesseeSKTimeStamp(context->accessee.transmitSkTimeStamp); } @@ -270,6 +272,7 @@ void DmAuthMessageProcessor::SetLnnAccessControlList(std::shared_ptraccesser.deviceName); // accesser.SetAccesserCredentialId(stoi(context->accesser.lnnCredentialId)); + accesser.SetAccesserCredentialId(0); accesser.SetAccesserSessionKeyId(context->accesser.lnnSessionKeyId); accesser.SetAccesserSKTimeStamp(context->accesser.lnnSkTimeStamp); accessee.SetAccesseeDeviceId(context->accessee.deviceId); @@ -278,6 +281,7 @@ void DmAuthMessageProcessor::SetLnnAccessControlList(std::shared_ptraccessee.deviceName); // accessee.SetAccesseeCredentialId(stoi(context->accessee.lnnCredentialId)); + accessee.SetAccesseeCredentialId(0); accessee.SetAccesseeSessionKeyId(context->accessee.lnnSessionKeyId); accessee.SetAccesseeSKTimeStamp(context->accessee.lnnSkTimeStamp); } -- Gitee From 957ef0b81a77bd76022af5b593efb3c65d74404c Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Thu, 27 Mar 2025 20:46:40 +0800 Subject: [PATCH 313/382] =?UTF-8?q?fix=EF=BC=9A=E5=87=AD=E6=8D=AEid?= =?UTF-8?q?=E6=9A=82=E6=97=B6=E7=94=A8userId=E4=BB=A3=E6=9B=BF=EF=BC=8Ctes?= =?UTF-8?q?t=E7=94=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_message_processor.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index da3e37402..27128b009 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -248,7 +248,7 @@ void DmAuthMessageProcessor::SetTransmitAccessControlList(std::shared_ptraccesser.bundleName); accesser.SetAccesserDeviceName(context->accesser.deviceName); // accesser.SetAccesserCredentialId(stoi(context->accesser.transmitCredentialId)); - accesser.SetAccesserCredentialId(0); + accesser.SetAccesserCredentialId(context->accesser.userId); accesser.SetAccesserSessionKeyId(context->accesser.transmitSessionKeyId); accesser.SetAccesserSKTimeStamp(context->accesser.transmitSkTimeStamp); accessee.SetAccesseeDeviceId(context->accessee.deviceId); @@ -258,7 +258,7 @@ void DmAuthMessageProcessor::SetTransmitAccessControlList(std::shared_ptraccessee.bundleName); accessee.SetAccesseeDeviceName(context->accessee.deviceName); // accessee.SetAccesseeCredentialId(stoi(context->accessee.transmitCredentialId)); - accessee.SetAccesseeCredentialId(0); + accessee.SetAccesseeCredentialId(context->accessee.userId); accessee.SetAccesseeSessionKeyId(context->accessee.transmitSessionKeyId); accessee.SetAccesseeSKTimeStamp(context->accessee.transmitSkTimeStamp); } @@ -272,7 +272,7 @@ void DmAuthMessageProcessor::SetLnnAccessControlList(std::shared_ptraccesser.deviceName); // accesser.SetAccesserCredentialId(stoi(context->accesser.lnnCredentialId)); - accesser.SetAccesserCredentialId(0); + accesser.SetAccesserCredentialId(context->accesser.userId); accesser.SetAccesserSessionKeyId(context->accesser.lnnSessionKeyId); accesser.SetAccesserSKTimeStamp(context->accesser.lnnSkTimeStamp); accessee.SetAccesseeDeviceId(context->accessee.deviceId); @@ -281,7 +281,7 @@ void DmAuthMessageProcessor::SetLnnAccessControlList(std::shared_ptraccessee.deviceName); // accessee.SetAccesseeCredentialId(stoi(context->accessee.lnnCredentialId)); - accessee.SetAccesseeCredentialId(0); + accessee.SetAccesseeCredentialId(context->accessee.userId); accessee.SetAccesseeSessionKeyId(context->accessee.lnnSessionKeyId); accessee.SetAccesseeSKTimeStamp(context->accessee.lnnSkTimeStamp); } -- Gitee From 17cf00e473d206dbfcca9b09ecfa5f08643b5289 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Thu, 27 Mar 2025 21:27:17 +0800 Subject: [PATCH 314/382] add nfc auth type support(same as import auth code type) --- .../include/authentication_v2/dm_auth_state.h | 1 + .../src/authentication_v2/auth_manager.cpp | 5 +++-- .../auth_stages/auth_confirm.cpp | 10 +++++----- .../auth_stages/auth_pin_auth.cpp | 8 ++++---- .../src/authentication_v2/dm_auth_state.cpp | 15 ++++++++++++--- 5 files changed, 25 insertions(+), 14 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 727db282c..0d8480e7d 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -114,6 +114,7 @@ public: 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); + static bool IsImportAuthCodeCompatibility(DmAuthType authType); protected: int32_t GetAuthCredentialInfo(std::shared_ptr context); bool NeedReqUserConfirm(std::shared_ptr context); diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index ffb78be10..8254f8d86 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -154,6 +154,7 @@ AuthManager::AuthManager(std::shared_ptr softbusConnector, context_->authenticationMap[AUTH_TYPE_PIN] = nullptr; context_->authenticationMap[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; context_->authenticationMap[AUTH_TYPE_PIN_ULTRASONIC] = nullptr; + context_->authenticationMap[AUTH_TYPE_NFC] = nullptr; context_->accesser.dmVersion = DM_VERSION_5_1_0; context_->accessee.dmVersion = DM_VERSION_5_1_0; context_->timer = std::make_shared(); @@ -279,7 +280,7 @@ int32_t AuthManager::StopAuthenticateDevice(const std::string &sessionName) void AuthManager::OnScreenLocked() { LOGI("AuthManager::OnScreenLocked start"); - if (context_->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + if (DmAuthState::IsImportAuthCodeCompatibility(context_->authType)) { LOGI("OnScreenLocked authtype is: %{public}d, no need stop bind.", context_->authType); return; } @@ -458,7 +459,7 @@ int32_t AuthManager::CheckAuthParamVaild(const std::string &sessionName, int32_t return ERR_DM_INPUT_PARA_INVALID; } - if ((authType == AUTH_TYPE_IMPORT_AUTH_CODE) && (!IsAuthCodeReady(sessionName))) { + if (DmAuthState::IsImportAuthCodeCompatibility(static_cast(authType)) && (!IsAuthCodeReady(sessionName))) { LOGE("Auth code not exist."); context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 10b3d6a0c..e561a1fa2 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -36,7 +36,7 @@ constexpr const char* TAG_HOST_PKGLABEL = "hostPkgLabel"; // authType fallback table using FallBackKey = std::pair; // accessee.bundleName, authType static std::map g_pinAuthTypeFallBackMap = { - {{"cast_engine_service", DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE}, DmAuthType::AUTH_TYPE_PIN}, + {{"CastEngineService", DmAuthType::AUTH_TYPE_NFC}, DmAuthType::AUTH_TYPE_PIN}, }; // Maximum number of recursive lookups constexpr size_t MAX_FALLBACK_LOOPKUP_TIMES = 2; @@ -122,7 +122,7 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) NegotiateAcl(context); // not pin import, and have acl - if (context->authType != DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE && + if ((!DmAuthState::IsImportAuthCodeCompatibility(context->authType)) && context->accesser.transmitSessionKeyId != 0 && context->accessee.transmitSessionKeyId != 0) { // finished, goto join lnn @@ -260,7 +260,7 @@ void AuthSinkConfirmState::ReadServiceInfo(std::shared_ptr contex if (ret == OHOS::DistributedDeviceProfile::DP_SUCCESS) { // ServiceInfo found context->authBoxType = srvInfo.GetAuthBoxType(); // read authBoxType - if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { std::string pinCode = srvInfo.GetPinCode(); // read pincode context->pinCode = std::stoi(pinCode); } @@ -277,7 +277,7 @@ void AuthSinkConfirmState::ReadServiceInfo(std::shared_ptr contex } } context->customData = srvInfo.GetDescription(); // read customData - } else if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE && IsAuthCodeReady(context)) { + } else if (DmAuthState::IsImportAuthCodeCompatibility(context->authType) && IsAuthCodeReady(context)) { // only special scenarios can import pincode context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // no authorization box } else { @@ -294,7 +294,7 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) NegotiateAcl(context); ReadServiceInfo(context); bool authTypeCheckOk = false; - if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE && + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType) && IsAuthCodeReady(context) && context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { /* The value of authresult may be the default value of temporary trust, diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 528c4600f..521a4b1e0 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -315,7 +315,7 @@ int32_t AuthSrcPinNegotiateStartState::NegotiatePinAuth(std::shared_ptrauthType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { context->authStateMachine->TransitionTo(std::make_shared()); } else if (context->authType == DmAuthType::AUTH_TYPE_PIN) { context->authStateMachine->TransitionTo(std::make_shared()); @@ -340,9 +340,9 @@ int32_t AuthSrcPinNegotiateStartState::Action(std::shared_ptr con return ERR_DM_BIND_USER_CANCEL; } // import pin code auth always excute - if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE && + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType) && (!context->authTypeList.empty()) && - context->authTypeList[0] == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + DmAuthState::IsImportAuthCodeCompatibility(context->authTypeList[0])) { return NegotiatePinAuth(context, true); } else if (!context->accesser.credentialTypeLists.empty()) { // have credential available, skip pin auth @@ -434,7 +434,7 @@ int32_t AuthSinkPinNegotiateStartState::Action(std::shared_ptr co [context] (std::string name) { HandleAuthenticateTimeout(context, name); }); - if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { LOGI("AuthSinkPinNegotiateStartState::Action import auth code"); } else if (context->authType == DmAuthType::AUTH_TYPE_PIN) { LOGI("AuthSinkPinNegotiateStartState::Action input pin"); diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 95d4482f4..f4e28ac30 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -182,7 +182,7 @@ const std::map TASK_TIME_OUT_MAP = { int32_t DmAuthState::GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut) { LOGI("GetTaskTimeout, taskName: %{public}s, authType_: %{public}d", taskName, context->authType); - if (context->authType == AUTH_TYPE_IMPORT_AUTH_CODE) { + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { auto timeout = TASK_TIME_OUT_MAP.find(std::string(taskName)); if (timeout != TASK_TIME_OUT_MAP.end()) { return timeout->second; @@ -357,7 +357,7 @@ int32_t DmAuthState::GetAuthCredentialInfo(std::shared_ptr contex bool DmAuthState::NeedReqUserConfirm(std::shared_ptr context) { // 不管是否有可信关系,都需要走pin码认证,主要指鸿蒙环PIN码导入场景 - if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { return true; } @@ -372,7 +372,7 @@ bool DmAuthState::NeedReqUserConfirm(std::shared_ptr context) bool DmAuthState::NeedPinAuth(std::shared_ptr context) { - if (context->authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE) { + if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { return true; } @@ -402,5 +402,14 @@ bool DmAuthState::NeedAgreeAcl(std::shared_ptr context) return context->accesser.isAuthed && context->accessee.isAuthed; } +bool DmAuthState::IsImportAuthCodeCompatibility(DmAuthType authType) +{ + if (authType == DmAuthType::AUTH_TYPE_IMPORT_AUTH_CODE || + authType == DmAuthType::AUTH_TYPE_NFC) { + return true; + } + return false; +} + } // namespace DistributedHardware } // namespace OHOS -- Gitee From 77edcd4acfa4e7d38aec23f6da29ad2411e2b0f2 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Thu, 27 Mar 2025 23:56:01 +0800 Subject: [PATCH 315/382] =?UTF-8?q?feat:=20=E8=A7=A3=E5=86=B3bindLevel?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 4 +++- .../authentication_v2/auth_stages/auth_credential.cpp | 8 ++++++-- .../authentication_v2/auth_stages/auth_negotiate.cpp | 10 +++++----- .../src/authentication_v2/dm_auth_manager_base.cpp | 6 +++--- .../src/authentication_v2/dm_auth_state.cpp | 2 +- 5 files changed, 18 insertions(+), 12 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 10b3d6a0c..1d986c291 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -68,6 +68,7 @@ void AuthSrcConfirmState::NegotiateCredential(std::shared_ptr con (intersection.front() == DM_IDENTICAL_ACCOUNT || intersection.front() == DM_ACROSS_ACCOUNT)) { context->accesser.bindLevel = DEVICE; // Exceptions: account related is DEVICE } + context->accessee.bindLevel = context->accesser.bindLevel; // TODO: 添加配件判断 if (!intersection.empty()) { @@ -183,8 +184,9 @@ void AuthSinkConfirmState::NegotiateCredential(std::shared_ptr co context->accessee.bindLevel = APP; // FA-FA } if (credType == DM_IDENTICAL_ACCOUNT || credType == DM_ACROSS_ACCOUNT) { - context->accesser.bindLevel = DEVICE; // Exceptions: account related is DEVICE + context->accessee.bindLevel = DEVICE; // Exceptions: account related is DEVICE } + context->accesser.bindLevel = context->accessee.bindLevel; std::vector sinkCredTypeLists = context->accessee.credentialTypeLists; if (std::find(sinkCredTypeLists.begin(), sinkCredTypeLists.end(), credType) == sinkCredTypeLists.end()) { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index f99656226..e0298fe30 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -32,6 +32,10 @@ namespace DistributedHardware { namespace { +// tag in Lowercase, need by hichain tag +const char* TAG_LOWER_DEVICE_ID = "deviceId"; +const char* TAG_LOWER_USER_ID = "userId"; + const char* DM_AUTH_CREDENTIAL_OWNER = "DM"; int32_t AuthCredentialTransmitDecryptProcess(std::shared_ptr context, DmEventType event) @@ -244,12 +248,12 @@ std::string AuthCredentialAgreeState::CreateAuthParamsString(DmAuthScope authori jsonObj[TAG_METHOD] = method; } - jsonObj[TAG_DEVICE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? + jsonObj[TAG_LOWER_DEVICE_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? authContext->GetDeviceId(DM_AUTH_LOCAL_SIDE) : authContext->GetDeviceId(DM_AUTH_REMOTE_SIDE); if (method == DM_AUTH_CREDENTIAL_ADD_METHOD_IMPORT) { jsonObj[TAG_PEER_USER_SPACE_ID] = std::to_string(authContext->GetUserId(DM_AUTH_REMOTE_SIDE)); } - jsonObj[TAG_USER_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? + jsonObj[TAG_LOWER_USER_ID] = (method == DM_AUTH_CREDENTIAL_ADD_METHOD_GENERATE) ? authContext->GetAccountId(DM_AUTH_LOCAL_SIDE) : authContext->GetAccountId(DM_AUTH_REMOTE_SIDE); jsonObj[TAG_SUBJECT] = DM_AUTH_CREDENTIAL_SUBJECT_PRIMARY; jsonObj[TAG_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 376c4142d..bbbc855c2 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -50,11 +50,9 @@ namespace { enum DmRole { DM_ROLE_UNKNOWN = 0, - DM_ROLE_FA_TO_FA, - DM_ROLE_FA_TO_FA_SERVICE, - DM_ROLE_SA_TO_SA, - DM_ROLE_SA_TO_SA_SERVICE, - DM_ROLE_FA_TO_DEVICE + DM_ROLE_USER, + DM_ROLE_SA, + DM_ROLE_FA, }; } @@ -176,9 +174,11 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptraccessee.bindLevel = DmRole::DM_ROLE_SA; LOGI("RespQueryTokenId: SA-SA"); return DM_OK; } + context->accessee.bindLevel = DmRole::DM_ROLE_FA; context->accessee.bundleName = tmpBundleName; context->accessee.tokenId = static_cast(tokenId); context->accessee.tokenIdHash = Crypto::Sha256(std::to_string(context->accessee.tokenId)); diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp index 3d31313ef..b2b900d4a 100644 --- a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp @@ -385,7 +385,7 @@ int32_t AuthManagerBase::DmGetUserId(int32_t displayId, int32_t targetUserId) return targetUserId; } - if (displayId != 0) { + if (displayId != -1) { ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(displayId, userId); if (ret != DM_OK) { LOGE("RespQueryTokenId: fail to get userId by displayId %{public}d", displayId); @@ -401,12 +401,12 @@ int32_t AuthManagerBase::DmGetUserId(int32_t displayId, int32_t targetUserId) #ifdef OS_ACCOUNT_PART_EXISTS ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(userId); if (ret != DM_OK) { - LOGE("RespQueryAcceseeIds: get foreground user failed in multi users with error %{public}d", ret); + LOGE("AuthManagerBase::DmGetUserId: get foreground user failed in multi users with error %{public}d", ret); return -1; } return userId; #else - LOGE("RespQueryAcceseeIds: get foreground user failed because no OsAcccountManager"); + LOGE("AuthManagerBase::DmGetUserId: get foreground user failed because no OsAcccountManager"); return -1; #endif } diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 95d4482f4..4f3b89ae4 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -399,7 +399,7 @@ bool DmAuthState::NeedAgreeCredential(std::shared_ptr context) bool DmAuthState::NeedAgreeAcl(std::shared_ptr context) { - return context->accesser.isAuthed && context->accessee.isAuthed; + return !(context->accesser.isAuthed && context->accessee.isAuthed); } } // namespace DistributedHardware -- Gitee From d293871c245386f75d00bd5b5b5af59c09b5c02e Mon Sep 17 00:00:00 2001 From: ZHANGHE24 Date: Fri, 28 Mar 2025 01:39:22 +0800 Subject: [PATCH 316/382] fix: Transmit the token ID to the upper-layer UI. --- .../ets/UIExtAbility/ConfirmUIExtAbility.ets | 3 +++ .../ets/UIExtAbility/InputUIExtAbility.ets | 3 +++ .../ets/UIExtAbility/PincodeUIExtAbility.ets | 3 +++ .../src/main/ets/pages/ConfirmDialog.ets | 19 ++++++++++++++++--- .../main/ets/pages/ConfirmDialogWearable.ets | 10 ++++++++-- .../src/main/ets/pages/InputPinDialog.ets | 10 ++++++++-- .../main/ets/pages/InputPinDialogWearable.ets | 10 ++++++++-- .../entry/src/main/ets/pages/PinDialog.ets | 18 +++++++++++++++--- .../src/main/ets/pages/PinDialogWearable.ets | 10 ++++++++-- 9 files changed, 72 insertions(+), 14 deletions(-) diff --git a/display/entry/src/main/ets/UIExtAbility/ConfirmUIExtAbility.ets b/display/entry/src/main/ets/UIExtAbility/ConfirmUIExtAbility.ets index 6b5055fe7..512d9660c 100644 --- a/display/entry/src/main/ets/UIExtAbility/ConfirmUIExtAbility.ets +++ b/display/entry/src/main/ets/UIExtAbility/ConfirmUIExtAbility.ets @@ -39,6 +39,9 @@ export default class ConfirmUIExtAbility extends UIExtensionAbility { if (want.parameters.hostPkgLabel) { AppStorage.setOrCreate('hostPkgLabel', want.parameters.hostPkgLabel); } + if (want.parameters.tokenId) { + AppStorage.setOrCreate('tokenId', want.parameters.tokenId); + } let param: Record = { 'session': session diff --git a/display/entry/src/main/ets/UIExtAbility/InputUIExtAbility.ets b/display/entry/src/main/ets/UIExtAbility/InputUIExtAbility.ets index 15a8081dc..07200108d 100644 --- a/display/entry/src/main/ets/UIExtAbility/InputUIExtAbility.ets +++ b/display/entry/src/main/ets/UIExtAbility/InputUIExtAbility.ets @@ -27,6 +27,9 @@ export default class InputUIExtAbility extends UIExtensionAbility { if (want.parameters && want.parameters.model) { AppStorage.setOrCreate('model', want.parameters.model); } + if (want.parameters && want.parameters.tokenId) { + AppStorage.setOrCreate('tokenId', want.parameters.tokenId); + } let param: Record = { 'session': session diff --git a/display/entry/src/main/ets/UIExtAbility/PincodeUIExtAbility.ets b/display/entry/src/main/ets/UIExtAbility/PincodeUIExtAbility.ets index ad4d9c6dd..c6fcd9d9e 100644 --- a/display/entry/src/main/ets/UIExtAbility/PincodeUIExtAbility.ets +++ b/display/entry/src/main/ets/UIExtAbility/PincodeUIExtAbility.ets @@ -24,6 +24,9 @@ export default class InputUIExtAbility extends UIExtensionAbility { if (want.parameters && want.parameters.pinCode) { AppStorage.setOrCreate('pinCode', want.parameters.pinCode); } + if (want.parameters && want.parameters.tokenId) { + AppStorage.setOrCreate('tokenId', want.parameters.tokenId); + } let param: Record = { 'session': session diff --git a/display/entry/src/main/ets/pages/ConfirmDialog.ets b/display/entry/src/main/ets/pages/ConfirmDialog.ets index 43a0bd10a..0777881ad 100644 --- a/display/entry/src/main/ets/pages/ConfirmDialog.ets +++ b/display/entry/src/main/ets/pages/ConfirmDialog.ets @@ -39,6 +39,7 @@ struct ConfirmCustomDialog { @State peerCustomDescription: string = ''; @State peerDeviceName: string = ''; @State peerDeviceType: number = 0; + @State tokenId: number = 0; @State secondsNum: number = 30; @State times: number = 0; @State isAvailableType: boolean = false; @@ -80,6 +81,11 @@ struct ConfirmCustomDialog { console.log('peerDeviceType is ' + this.peerDeviceType); } + if (AppStorage.get('tokenId') != null) { + this.tokenId = AppStorage.get('tokenId') as number; + console.log('tokenId is ' + this.tokenId); + } + this.times = setInterval(() => { console.info('devicemanagerui confirm dialog run seconds:' + this.secondsNum); this.secondsNum--; @@ -138,7 +144,8 @@ struct ConfirmCustomDialog { return; } try { - dmClass.setUserOperation(operation, 'extra'); + let paramJsonStr = `{"tokenId": ${this.tokenId}}`; + dmClass.setUserOperation(operation, paramJsonStr); } catch (error) { console.log(TAG + 'dmClass setUserOperation failed') } @@ -348,6 +355,7 @@ struct ConfirmCustomDialog { @Entry @Component struct dialogPlusPage { + @State tokenId: number = 0; dialogController: CustomDialogController = new CustomDialogController({ builder: ConfirmCustomDialog(), autoCancel: false, @@ -365,7 +373,11 @@ struct dialogPlusPage { console.log(TAG + 'deviceManager exist') return } - deviceManager.createDeviceManager('com.ohos.devicemanagerui.confirm', + if (AppStorage.get('tokenId') != null) { + this.tokenId = AppStorage.get('tokenId') as number; + console.log('tokenId is ' + this.tokenId); + } + deviceManager.createDeviceManager('com.ohos.devicemanagerui.confirm' + ' ' + this.tokenId, (err: Error, dm: deviceManager.DeviceManager) => { if (err) { console.log('createDeviceManager err:' + JSON.stringify(err) + ' --fail:' + JSON.stringify(dm)) @@ -398,7 +410,8 @@ struct dialogPlusPage { return; } try { - dmClass.setUserOperation(operation, 'extra'); + let paramJsonStr = `{"tokenId": ${this.tokenId}}`; + dmClass.setUserOperation(operation, paramJsonStr); } catch (error) { console.log(TAG + 'dmClass setUserOperation failed') } diff --git a/display/entry/src/main/ets/pages/ConfirmDialogWearable.ets b/display/entry/src/main/ets/pages/ConfirmDialogWearable.ets index 567ad3f20..c25de2042 100644 --- a/display/entry/src/main/ets/pages/ConfirmDialogWearable.ets +++ b/display/entry/src/main/ets/pages/ConfirmDialogWearable.ets @@ -34,6 +34,7 @@ struct Index { @State peerCustomDescription: string = ''; @State peerDeviceName: string = ''; @State peerDeviceType: number = 0; + @State tokenId: number = 0; @State secondsNum: number = 30; @State times: number = 0; @State isAvailableType: boolean = false; @@ -45,7 +46,11 @@ struct Index { console.log(TAG + 'deviceManager exist'); return; } - deviceManager.createDeviceManager('com.ohos.devicemanagerui.confirm', + if (AppStorage.get('tokenId') != null) { + this.tokenId = AppStorage.get('tokenId') as number; + console.log('tokenId is ' + this.tokenId); + } + deviceManager.createDeviceManager('com.ohos.devicemanagerui.confirm' + ' ' + this.tokenId, (err: Error, dm: deviceManager.DeviceManager) => { if (err) { console.log('createDeviceManager err:' + JSON.stringify(err) + ' --fail:' + JSON.stringify(dm)); @@ -133,7 +138,8 @@ struct Index { } try { this.isUserOperate = true; - dmClass.setUserOperation(operation, 'extra'); + let paramJsonStr = `{"tokenId": ${this.tokenId}}`; + dmClass.setUserOperation(operation, paramJsonStr); } catch (error) { console.log(TAG + 'dmClass setUserOperation failed'); } diff --git a/display/entry/src/main/ets/pages/InputPinDialog.ets b/display/entry/src/main/ets/pages/InputPinDialog.ets index 1add1ade8..cec6e619e 100644 --- a/display/entry/src/main/ets/pages/InputPinDialog.ets +++ b/display/entry/src/main/ets/pages/InputPinDialog.ets @@ -41,6 +41,7 @@ struct InputCustomDialog { @State errorTipsVisible: Visibility = Visibility.None; @State heightNum: number = 600; @State targetDeviceName: string = ''; + @State tokenId: number = 0; @State model: string = MODEL_PIN; @State isPC: boolean = false; @State btnColor: ResourceColor = Color.Transparent; @@ -80,7 +81,11 @@ struct InputCustomDialog { this.model = AppStorage.get('model') as string; console.log('model is ' + this.model); } - deviceManager.createDeviceManager('com.ohos.devicemanagerui.input', + if (AppStorage.get('tokenId') != null) { + this.tokenId = AppStorage.get('tokenId') as number; + console.log('tokenId is ' + this.tokenId); + } + deviceManager.createDeviceManager('com.ohos.devicemanagerui.input' + ' ' + this.tokenId, (err: Error, dm: deviceManager.DeviceManager) => { if (err) { console.log('createDeviceManager err:' + JSON.stringify(err) + ' --fail:' + '${dm}'); @@ -179,7 +184,8 @@ struct InputCustomDialog { return; } try { - dmClass.setUserOperation(operation, extra); + let paramJsonStr = `{"pinCode": ${extra}, "tokenId": ${this.tokenId}}`; + dmClass.setUserOperation(operation, paramJsonStr); } catch (error) { console.log('dmClass setUserOperation failed'); } diff --git a/display/entry/src/main/ets/pages/InputPinDialogWearable.ets b/display/entry/src/main/ets/pages/InputPinDialogWearable.ets index 581575719..1f95a3cca 100644 --- a/display/entry/src/main/ets/pages/InputPinDialogWearable.ets +++ b/display/entry/src/main/ets/pages/InputPinDialogWearable.ets @@ -30,6 +30,7 @@ const MAX_PINCODE_LENGTH = 6; @Component struct Index { @State isTimes: number = 3; + @State tokenId: number = 0; @State passwordCircle: string[] = ['', '', '', '', '', '']; @State errorTips: Resource = $r('app.plural.dm_incorrect_code', this.isTimes, this.isTimes); @State @Watch('onChangeInput') input: string = ''; @@ -55,7 +56,11 @@ struct Index { console.log(TAG + 'deviceManager exist'); return; } - deviceManager.createDeviceManager('com.ohos.devicemanagerui.input', + if (AppStorage.get('tokenId') != null) { + this.tokenId = AppStorage.get('tokenId') as number; + console.log('tokenId is ' + this.tokenId); + } + deviceManager.createDeviceManager('com.ohos.devicemanagerui.input' + ' ' + this.tokenId, (err: Error, dm: deviceManager.DeviceManager) => { if (err) { console.log('createDeviceManager err:' + JSON.stringify(err) + ' --fail:' + '${dm}'); @@ -132,7 +137,8 @@ struct Index { } try { this.isUserOperate = true; - dmClass.setUserOperation(operation, extra); + let paramJsonStr = `{"pinCode": ${extra}, "tokenId": ${this.tokenId}}`; + dmClass.setUserOperation(operation, paramJsonStr); } catch (error) { console.log('dmClass setUserOperation failed'); } diff --git a/display/entry/src/main/ets/pages/PinDialog.ets b/display/entry/src/main/ets/pages/PinDialog.ets index df0408e3a..0f0a58faf 100644 --- a/display/entry/src/main/ets/pages/PinDialog.ets +++ b/display/entry/src/main/ets/pages/PinDialog.ets @@ -28,6 +28,7 @@ const MSG_CANCEL_PIN_CODE_SHOW: number = 2; @CustomDialog struct PinCustomDialog { @State pinCode: string = ''; + @State tokenId: number = 0; @State pinCodeArr: Array = []; @State btnColor: ResourceColor = Color.Transparent; @State isPC: boolean = false; @@ -53,6 +54,10 @@ struct PinCustomDialog { this.pinCode = AppStorage.get('pinCode') as string; this.pinCodeArr = this.pinCode.split(''); console.log(TAG + 'this.pinCodeArr' + this.pinCodeArr); + if (AppStorage.get('tokenId') != null) { + this.tokenId = AppStorage.get('tokenId') as number; + console.log('tokenId is ' + this.tokenId); + } } setUserOperation(operation: number) { @@ -62,7 +67,8 @@ struct PinCustomDialog { return; } try { - dmClass.setUserOperation(operation, 'extra'); + let paramJsonStr = `{"tokenId": ${this.tokenId}}`; + dmClass.setUserOperation(operation, paramJsonStr); } catch (error) { console.log(TAG + 'dmClass setUserOperation failed'); } @@ -176,6 +182,7 @@ struct PinCustomDialog { @Entry @Component struct dialogPlusPage { + @State tokenId: number = 0; dialogController: CustomDialogController = new CustomDialogController({ builder: PinCustomDialog(), cancel: this.onCancel, @@ -227,7 +234,11 @@ struct dialogPlusPage { console.log(TAG + 'deviceManager exist'); return; } - deviceManager.createDeviceManager('com.ohos.devicemanagerui.pin', + if (AppStorage.get('tokenId') != null) { + this.tokenId = AppStorage.get('tokenId') as number; + console.log('tokenId is ' + this.tokenId); + } + deviceManager.createDeviceManager('com.ohos.devicemanagerui.pin' + ' ' + this.tokenId, (err: Error, dm: deviceManager.DeviceManager) => { if (err) { console.log('createDeviceManager err:' + JSON.stringify(err) + ' --fail:' + JSON.stringify(dm)) @@ -252,7 +263,8 @@ struct dialogPlusPage { return; } try { - dmClass.setUserOperation(operation, 'extra'); + let paramJsonStr = `{"tokenId": ${this.tokenId}}`; + dmClass.setUserOperation(operation, paramJsonStr); } catch (error) { console.log(TAG + 'dmClass setUserOperation failed') } diff --git a/display/entry/src/main/ets/pages/PinDialogWearable.ets b/display/entry/src/main/ets/pages/PinDialogWearable.ets index 58bf8acfd..8e9fd0b49 100644 --- a/display/entry/src/main/ets/pages/PinDialogWearable.ets +++ b/display/entry/src/main/ets/pages/PinDialogWearable.ets @@ -25,6 +25,7 @@ const MSG_CANCEL_PIN_CODE_SHOW: number = 2; @Component struct PinDialog { @State pinCode: string = ''; + @State tokenId: number = 0; @State pinCodeArr: Array = []; @State btnColor: ResourceColor = Color.Transparent; @State isUserOperate: boolean = false; @@ -83,7 +84,11 @@ struct PinDialog { console.log(TAG + 'deviceManager exist'); return; } - deviceManager.createDeviceManager('com.ohos.devicemanagerui.pin', + if (AppStorage.get('tokenId') != null) { + this.tokenId = AppStorage.get('tokenId') as number; + console.log('tokenId is ' + this.tokenId); + } + deviceManager.createDeviceManager('com.ohos.devicemanagerui.pin' + ' ' + this.tokenId, (err: Error, dm: deviceManager.DeviceManager) => { if (err) { console.log('createDeviceManager err:' + JSON.stringify(err) + ' --fail:' + JSON.stringify(dm)); @@ -109,7 +114,8 @@ struct PinDialog { } try { this.isUserOperate = true; - dmClass.setUserOperation(operation, 'extra'); + let paramJsonStr = `{"tokenId": ${this.tokenId}}`; + dmClass.setUserOperation(operation, paramJsonStr); } catch (error) { console.log(TAG + 'dmClass setUserOperation failed'); } -- Gitee From 3e9a464224efca7d19734ad7321ce6e9edd061d0 Mon Sep 17 00:00:00 2001 From: ZHANGHE24 Date: Fri, 28 Mar 2025 01:39:37 +0800 Subject: [PATCH 317/382] fix: modify multi session implement(header file) --- common/include/dm_error_type.h | 1 + .../include/ability/dm_dialog_manager.h | 5 ++ .../include/authentication/dm_auth_manager.h | 2 +- .../include/authentication_v2/auth_manager.h | 8 +-- .../authentication_v2/dm_auth_context.h | 5 ++ .../authentication_v2/dm_auth_manager_base.h | 7 +- .../dm_auth_message_processor.h | 4 ++ .../authentication_v2/dm_auth_state_machine.h | 1 + .../hichain/hichain_auth_connector.h | 5 ++ .../dependency/hichain/hichain_connector.h | 2 +- .../include/device_manager_service_impl.h | 69 +++++++++++++++++-- 11 files changed, 95 insertions(+), 14 deletions(-) diff --git a/common/include/dm_error_type.h b/common/include/dm_error_type.h index 1557ace99..0ee98c188 100644 --- a/common/include/dm_error_type.h +++ b/common/include/dm_error_type.h @@ -124,6 +124,7 @@ enum { ERR_DM_NEXT_STATE_INVALID = 96929836, ERR_DM_HILINKSVC_SCAS_CHECK_FAILED = 96929837, ERR_DM_FIND_NETWORKID_LIST_EMPTY = 96929838, + ERR_DM_LOGIC_SESSION_CREATE_FAILED = 96929839, }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/include/ability/dm_dialog_manager.h b/services/implementation/include/ability/dm_dialog_manager.h index 1a42ff984..1ac717de7 100644 --- a/services/implementation/include/ability/dm_dialog_manager.h +++ b/services/implementation/include/ability/dm_dialog_manager.h @@ -77,6 +77,10 @@ public: { return hostPkgLabel_; } + static uint64_t GetTokenId() + { + return tokenId_; + } private: DmDialogManager(); ~DmDialogManager(); @@ -98,6 +102,7 @@ private: static std::string customDescriptionStr_; static std::string pinCode_; static std::string hostPkgLabel_; + static uint64_t tokenId_; static int32_t deviceType_; static std::atomic isConnectSystemUI_; static sptr dialogConnectionCallback_; diff --git a/services/implementation/include/authentication/dm_auth_manager.h b/services/implementation/include/authentication/dm_auth_manager.h index b01031854..b6fb6c5b2 100644 --- a/services/implementation/include/authentication/dm_auth_manager.h +++ b/services/implementation/include/authentication/dm_auth_manager.h @@ -474,7 +474,7 @@ public: * @tc.type: FUNC */ int32_t BindTarget(const std::string &pkgName, const PeerTargetId &targetId, - const std::map &bindParam); + const std::map &bindParam, int sessionId, int64_t logicalSessionId); void HandleSessionHeartbeat(std::string name); diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 18ea5206d..3cc498269 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -35,7 +35,7 @@ public: AuthManager(std::shared_ptr softbusConnector, std::shared_ptr listener, std::shared_ptr hiChainAuthConnector); - virtual ~AuthManager() = default; + virtual ~AuthManager(); // External API begin /** @@ -51,7 +51,7 @@ public: * @tc.type: FUNC */ int32_t BindTarget(const std::string &sessionName, const PeerTargetId &targetId, - const std::map &bindParam); + const std::map &bindParam, int sessionId, int64_t logicalSessionId); /** * @tc.name: AuthManager::OnUserOperation @@ -119,16 +119,16 @@ public: bool IsAuthManagerConstructSuccess(); // Internal API end + void RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback); + 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, diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 70a38343a..f24fbbc9c 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -40,6 +40,8 @@ namespace DistributedHardware { class DmAuthStateMachine; class DmAuthMessageProcessor; +using CleanNotifyCallback = std::function; + // PIN Code Authentication Type enum DmAuthType : int32_t { AUTH_TYPE_CRE = 0, // Not used in the new protocol @@ -146,6 +148,7 @@ struct DmAccess { struct DmAuthContext { bool isOnline; + int64_t logicalSessionId; DmMessageType msgType; int32_t sessionId; int64_t requestId; // HiChain authentication ID @@ -204,6 +207,8 @@ struct DmAuthContext { bool isAuthenticateDevice{false}; // Whether device authentication is in progress bool needAgreeCredential{true}; + CleanNotifyCallback cleanNotifyCallback; + std::string GetDeviceId(DmAuthSide side); int32_t GetUserId(DmAuthSide side); std::string GetCredentialId(DmAuthSide side, DmAuthScope authorizedScope); diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h b/services/implementation/include/authentication_v2/dm_auth_manager_base.h index e61ccb44d..c935e0c5d 100644 --- a/services/implementation/include/authentication_v2/dm_auth_manager_base.h +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h @@ -93,6 +93,8 @@ extern const int32_t DM_AUTH_TYPE_MIN; extern const int32_t MIN_PIN_TOKEN; extern const int32_t MAX_PIN_TOKEN; +using CleanNotifyCallback = std::function; + class AuthManagerBase : public ISoftbusSessionCallback, public IHiChainConnectorCallback, public IDmDeviceAuthCallback { @@ -172,7 +174,7 @@ public: 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); + const std::map &bindParam, int sessionId, int64_t logicalSessionId); virtual int32_t RegisterAuthenticationType(int32_t authenticationType); @@ -194,6 +196,9 @@ public: // Check if the authManager has been initialized successfully virtual bool IsAuthManagerConstructSuccess() = 0; + // Register the notification function when the auth_mgr event is complete. + virtual void RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback); + // Public functions static std::string ConvertSrcVersion(const std::string &version, const std::string &edition); static std::string ConvertSinkVersion(const std::string &version); diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 7b9c83d1f..7b036b51f 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -112,6 +112,10 @@ extern const char* TAG_ACCESSEE_STATUS; extern const char* TAG_ACCESSEE_SK_ID; extern const char* TAG_ACCESSEE_SK_TIMESTAMP; +// 逻辑会话Tag +constexpr const char* DM_TAG_LOGICAL_SESSION_ID = "logicalSessionId"; + +// 报文类型 enum DmMessageType { // Terminate/Exception Message MSG_TYPE_UNKNOWN = 0, diff --git a/services/implementation/include/authentication_v2/dm_auth_state_machine.h b/services/implementation/include/authentication_v2/dm_auth_state_machine.h index 349aa708d..65ce5b3a0 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state_machine.h +++ b/services/implementation/include/authentication_v2/dm_auth_state_machine.h @@ -45,6 +45,7 @@ enum DmEventType { ON_USER_OPERATION, ON_FAIL, ON_SCREEN_LOCKED, + ON_SESSION_OPENED, }; class DmAuthStateMachine { diff --git a/services/implementation/include/dependency/hichain/hichain_auth_connector.h b/services/implementation/include/dependency/hichain/hichain_auth_connector.h index 6342ee230..da5edf66d 100644 --- a/services/implementation/include/dependency/hichain/hichain_auth_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_auth_connector.h @@ -16,7 +16,9 @@ #ifndef OHOS_HICHAIN_AUTH_CONNECTOR_H #define OHOS_HICHAIN_AUTH_CONNECTOR_H +#include #include + #include "device_auth.h" #include "device_auth_defines.h" #include "hichain_connector_callback.h" @@ -57,6 +59,7 @@ public: int32_t ImportCredential(int32_t osAccountId, std::string deviceId, std::string publicKey); int32_t DeleteCredential(const std::string &deviceId, int32_t userId); int32_t RegisterHiChainAuthCallback(std::shared_ptr callback); + int32_t RegisterHiChainAuthCallbackById(int64_t id, std::shared_ptr callback); int32_t GetCredential(std::string &localUdid, int32_t osAccountId, std::string &publicKey); // 处理凭据认证报文 @@ -78,10 +81,12 @@ public: private: void FreeJsonString(char *jsonStr); + static std::shared_ptr GetDeviceAuthCallback(int64_t id); private: DeviceAuthCallback deviceAuthCallback_; static std::shared_ptr dmDeviceAuthCallback_; + static std::map> dmDeviceAuthCallbackMap_; static std::mutex dmDeviceAuthCallbackMutex_; }; } // namespace DistributedHardware diff --git a/services/implementation/include/dependency/hichain/hichain_connector.h b/services/implementation/include/dependency/hichain/hichain_connector.h index c6e518cad..c6210ddd8 100644 --- a/services/implementation/include/dependency/hichain/hichain_connector.h +++ b/services/implementation/include/dependency/hichain/hichain_connector.h @@ -155,7 +155,7 @@ public: * @tc.type: FUNC */ bool GetGroupInfo(const int32_t userId, const std::string &queryParams, std::vector &groupList); - + bool GetGroupInfoExt(const int32_t userId, const std::string &queryParams, std::vector &groupList); bool GetGroupInfoCommon(const int32_t userId, const std::string &queryParams, const char* pkgName, diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 02e63514e..6f10694d6 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -16,8 +16,12 @@ #ifndef OHOS_DM_SERVICE_IMPL_H #define OHOS_DM_SERVICE_IMPL_H +#include +#include #include #include +#include +#include #include "access_control_profile.h" #include "dm_ability_manager.h" @@ -36,6 +40,24 @@ namespace OHOS { namespace DistributedHardware { + +class Session { +public: + Session(int sessionId, std::string deviceId); + int sessionId_; + std::string deviceId_; + std::string version_{""}; + std::atomic flag_{false}; // 只允许创建一个会话,初始化为false,首次新建置true,其他进入失败 + std::set logicalSessionSet_; // 逻辑会话集合 + std::atomic logicalSessionCnt_{0}; +}; + +struct Config { + std::string pkgName; + std::string authCode; + int32_t authenticationType{0}; +}; + class DeviceManagerServiceImpl : public IDeviceManagerServiceImpl { public: DeviceManagerServiceImpl(); @@ -141,6 +163,8 @@ public: int32_t CheckDeviceInfoPermission(const std::string &localUdid, const std::string &peerDeviceId); int32_t DeleteAcl(const std::string &sessionName, const std::string &localUdid, const std::string &remoteUdid, int32_t bindLevel, const std::string &extra); + static void NotifyCleanEvent(int64_t logicalSessionId); + private: int32_t PraseNotifyEventJson(const std::string &event, JsonObject &jsonObject); std::string GetUdidHashByNetworkId(const std::string &networkId); @@ -158,25 +182,56 @@ private: void HandleUserRemoved(int32_t preUserId); void HandleRemoteUserRemoved(int32_t preUserId, const std::string &remoteUdid); DmAuthForm ConvertBindTypeToAuthForm(int32_t bindType); - int32_t InitAndRegisterAuthMgr(bool isSrcSide); - int32_t CreateAuthMgrByMessage(int sessionId, const void *data, unsigned int dataLen); + int32_t InitAndRegisterAuthMgr(bool isSrcSide, uint64_t tokenId, std::shared_ptr session, + int64_t logicalSessionId); + std::shared_ptr GetAuthMgr(); + std::shared_ptr GetAuthMgrByTokenId(uint64_t tokenId); + std::shared_ptr GetCurSession(int sessionId); + std::shared_ptr GetOrCreateSession(const std::string& deviceId, + const std::map &bindParam); + int32_t ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, + const std::map &bindParam); + std::shared_ptr GetConfigByTokenId(); + + // 清理资源线程 + void CleanWorker(); + // 停止线程 + void Stop(); + int64_t FetchCleanEvent(); + void CleanAuthMgrByLogicalSessionId(int64_t logicalSessionId); + void CleanSessionMap(int sessionId, std::shared_ptr session); + void CleanSessionMapByLogicalSessionId(int64_t logicalSessionId); private: - std::shared_ptr authMgr_; + std::shared_ptr authMgr_; // 老协议专用 + std::map> authMgrMap_; // 新协议共用 + std::shared_ptr hiChainConnector_; + std::shared_ptr hiChainAuthConnector_; std::shared_ptr deviceStateMgr_; std::shared_ptr softbusConnector_; std::shared_ptr abilityMgr_; - std::shared_ptr hiChainConnector_; std::shared_ptr mineHiChainConnector_; std::shared_ptr credentialMgr_; std::shared_ptr commonEventManager_; - std::shared_ptr hiChainAuthConnector_; std::shared_ptr listener_; std::atomic isCredentialType_ = false; sptr dpInitedCallback_ = nullptr; - std::string importAuthCode_; - std::string importPkgName_; + std::map deviceId2SessionIdMap_; // 设备Id对应的会话Id, 只在src端使用 + std::map> sessionsMap_; // sessionId对应会话对象 + std::map deviceIdMutexMap_; // 设备Id对应的锁 + std::mutex mapMutex_; // sessionsMap_的锁 + std::map sessionEnableCvMap_; // 会话对应的条件变量 + std::map sessionEnableMutexMap_; // 会话对应的锁 + std::map logicalSessionId2TokenIdMap_; // 多会话与tokenId的对应关系 + std::map logicalSessionId2SessionIdMap_; // 多会话与物理回话Id的对应关系 + std::map> configsMap_; // authMgr未初始化时导入 + + std::thread thread_; + std::atomic running_; + static std::condition_variable cleanEventCv_; + static std::mutex cleanEventMutex_; + static std::queue cleanEventQueue_; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); -- Gitee From d65e77e1ddaa0a873679acf8562e359322cdd600 Mon Sep 17 00:00:00 2001 From: ZHANGHE24 Date: Fri, 28 Mar 2025 01:40:31 +0800 Subject: [PATCH 318/382] fix: modify multi session implement(cpp) --- .../ability/standard/dm_dialog_manager.cpp | 49 +++++- .../src/authentication/dm_auth_manager.cpp | 13 +- .../src/authentication_v2/auth_manager.cpp | 147 +++++++----------- .../auth_stages/auth_acl.cpp | 2 + .../auth_stages/auth_confirm.cpp | 1 + .../auth_stages/auth_negotiate.cpp | 39 +---- .../auth_stages/auth_pin_auth.cpp | 16 +- .../dm_auth_manager_base.cpp | 13 +- .../dm_auth_message_processor.cpp | 6 +- .../hichain/hichain_auth_connector.cpp | 51 ++++-- .../dependency/softbus/softbus_session.cpp | 47 +----- 11 files changed, 193 insertions(+), 191 deletions(-) diff --git a/services/implementation/src/ability/standard/dm_dialog_manager.cpp b/services/implementation/src/ability/standard/dm_dialog_manager.cpp index 11b35a762..d7a8f229f 100644 --- a/services/implementation/src/ability/standard/dm_dialog_manager.cpp +++ b/services/implementation/src/ability/standard/dm_dialog_manager.cpp @@ -49,6 +49,7 @@ std::string DmDialogManager::customDescriptionStr_ = ""; std::string DmDialogManager::targetDeviceName_ = ""; std::string DmDialogManager::pinCode_ = ""; std::string DmDialogManager::hostPkgLabel_ = ""; +uint64_t DmDialogManager::tokenId_ = 0; int32_t DmDialogManager::deviceType_ = -1; DmDialogManager DmDialogManager::dialogMgr_; sptr DmDialogManager::dialogConnectionCallback_( @@ -78,24 +79,28 @@ void DmDialogManager::ShowConfirmDialog(const std::string param) std::string appOperationStr = ""; std::string customDescriptionStr = ""; std::string hostPkgLabel = ""; + uint64_t tokenId = 0; int32_t deviceType = -1; JsonObject jsonObject(param); if (!jsonObject.IsDiscarded()) { - if (IsString(jsonObject, TAG_REQUESTER)) { + if (jsonObject[TAG_REQUESTER].IsString()) { deviceName = jsonObject[TAG_REQUESTER].Get(); } - if (IsString(jsonObject, TAG_APP_OPERATION)) { + if (jsonObject[TAG_APP_OPERATION].IsString()) { appOperationStr = jsonObject[TAG_APP_OPERATION].Get(); } - if (IsString(jsonObject, TAG_CUSTOM_DESCRIPTION)) { + if (jsonObject[TAG_CUSTOM_DESCRIPTION].IsString()) { customDescriptionStr = jsonObject[TAG_CUSTOM_DESCRIPTION].Get(); } - if (IsInt32(jsonObject, TAG_LOCAL_DEVICE_TYPE)) { + if (jsonObject[TAG_LOCAL_DEVICE_TYPE].IsNumberInteger()) { deviceType = jsonObject[TAG_LOCAL_DEVICE_TYPE].Get(); } - if (IsString(jsonObject, TAG_HOST_PKGLABEL)) { + if (jsonObject[TAG_HOST_PKGLABEL].IsString()) { hostPkgLabel = jsonObject[TAG_HOST_PKGLABEL].Get(); } + if (jsonObject[TOKENID].IsNumberInteger()) { + tokenId = jsonObject[TOKENID].Get(); + } } bundleName_ = DM_UI_BUNDLE_NAME; @@ -105,14 +110,28 @@ void DmDialogManager::ShowConfirmDialog(const std::string param) customDescriptionStr_ = customDescriptionStr; deviceType_ = deviceType; hostPkgLabel_ = hostPkgLabel; + tokenId_ = tokenId; ConnectExtension(); } void DmDialogManager::ShowPinDialog(const std::string param) { + std::string pinCode; + uint64_t tokenId = 0; bundleName_ = DM_UI_BUNDLE_NAME; abilityName_ = PIN_ABILITY_NAME; - pinCode_ = param; + JsonObject jsonObject(param); + if (!jsonObject.IsDiscarded()) { + if (jsonObject[PIN_CODE_KEY].IsNumberInteger()) { + pinCode = std::to_string(jsonObject[PIN_CODE_KEY].Get()); + } + if (jsonObject[TOKENID].IsNumberInteger()) { + tokenId = jsonObject[TOKENID].Get(); + } + } + + pinCode_ = pinCode; + tokenId_ = tokenId; #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) ffrt::submit([]() { ConnectExtension(); }); #else @@ -127,7 +146,20 @@ void DmDialogManager::ShowPinDialog(const std::string param) void DmDialogManager::ShowInputDialog(const std::string param) { - targetDeviceName_ = param; + std::string targetDeviceName; + uint64_t tokenId = 0; + JsonObject jsonObject(param); + if (!jsonObject.IsDiscarded()) { + if (jsonObject[TAG_TARGET_DEVICE_NAME].IsString()) { + targetDeviceName = jsonObject[TAG_TARGET_DEVICE_NAME].Get(); + } + if (jsonObject[TOKENID].IsNumberInteger()) { + tokenId = jsonObject[TOKENID].Get(); + } + } + + targetDeviceName_ = targetDeviceName; + tokenId_ = tokenId; bundleName_ = DM_UI_BUNDLE_NAME; abilityName_ = INPUT_ABILITY_NAME; ConnectExtension(); @@ -201,7 +233,8 @@ void DmDialogManager::DialogAbilityConnection::OnAbilityConnectDone( param[TAG_TARGET_DEVICE_NAME] = DmDialogManager::GetTargetDeviceName(); param[TAG_HOST_PKGLABEL] = DmDialogManager::GetHostPkgLabel(); param["disableUpGesture"] = 1; - std::string paramStr = SafetyDump(param); + param[TOKENID] = DmDialogManager::GetTokenId(); + std::string paramStr = param.Dump(); data.WriteString16(Str8ToStr16(paramStr)); LOGI("show dm dialog is begin"); const uint32_t cmdCode = 1; diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 054615bb0..d905df32e 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -1893,7 +1893,16 @@ int32_t DmAuthManager::OnUserOperation(int32_t action, const std::string ¶ms } break; case USER_OPERATION_TYPE_DONE_PINCODE_INPUT: - ProcessPincode(std::atoi(params.c_str())); + { + JsonObject jsonObject(params); + if (jsonObject.IsDiscarded()) { + LOGE("OnUserOperation jsonStr error"); + return ERR_DM_INPUT_PARA_INVALID; + } + if (jsonObject[PIN_CODE_KEY].IsNumberInteger()) { + ProcessPincode(jsonObject[PIN_CODE_KEY].Get()); + } + } info.stageRes = static_cast(StageRes::STAGE_SUCC); if (!DmRadarHelper::GetInstance().ReportAuthInputPinBox(info)) { LOGE("ReportAuthInputPinBox failed"); @@ -2008,7 +2017,7 @@ int32_t DmAuthManager::ImportAuthCode(const std::string &pkgName, const std::str } int32_t DmAuthManager::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, - const std::map &bindParam) + const std::map &bindParam, int sessionId, int64_t logicalSessionId) { struct RadarInfo info = { .funcName = "AuthenticateDevice", diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 8254f8d86..e2c20974d 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -161,6 +161,30 @@ AuthManager::AuthManager(std::shared_ptr softbusConnector, context_->authMessageProcessor = std::make_shared(); } +AuthManager::~AuthManager() +{ + if (context_ != nullptr) { + context_->softbusConnector = nullptr; + context_->listener = nullptr; + context_->hiChainAuthConnector = nullptr; + context_->authUiStateMgr = nullptr; + context_->authenticationMap[AUTH_TYPE_PIN] = nullptr; + context_->authenticationMap[AUTH_TYPE_IMPORT_AUTH_CODE] = nullptr; + context_->authenticationMap[AUTH_TYPE_PIN_ULTRASONIC] = nullptr; + context_->timer = nullptr; + context_->authMessageProcessor = nullptr; + context_->authStateMachine = nullptr; + context_ = nullptr; + } + bindParam_.clear(); +} + +void AuthManager::RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback) +{ + context_->cleanNotifyCallback = cleanNotifyCallback; + return; +} + bool AuthManager::IsAuthManagerConstructSuccess() { return context_ != nullptr && @@ -345,55 +369,6 @@ char *AuthSrcManager::AuthDeviceRequest(int64_t requestId, int operationCode, co return nullptr; } -int32_t AuthManager::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, std::string &addrType) -{ - int32_t index = 0; - std::shared_ptr deviceInfo = std::make_shared(); - ConnectionAddr addr; - if (!targetId.wifiIp.empty() && targetId.wifiIp.length() <= IP_STR_MAX_LEN) { - LOGI("AuthManager::ParseConnectAddr parse wifiIp: %{public}s.", GetAnonyString(targetId.wifiIp).c_str()); - if (!addrType.empty()) { - addr.type = static_cast(std::atoi(addrType.c_str())); - } else { - addr.type = ConnectionAddrType::CONNECTION_ADDR_WLAN; - } - memcpy_s(addr.info.ip.ip, IP_STR_MAX_LEN, targetId.wifiIp.c_str(), targetId.wifiIp.length()); - addr.info.ip.port = targetId.wifiPort; - deviceInfo->addr[index] = addr; - deviceId = targetId.wifiIp; - index++; - } else if (!targetId.brMac.empty() && targetId.brMac.length() <= BT_MAC_LEN) { - LOGI("AuthManager::ParseConnectAddr parse brMac: %{public}s.", GetAnonyString(targetId.brMac).c_str()); - addr.type = ConnectionAddrType::CONNECTION_ADDR_BR; - memcpy_s(addr.info.br.brMac, BT_MAC_LEN, targetId.brMac.c_str(), targetId.brMac.length()); - deviceInfo->addr[index] = addr; - deviceId = targetId.brMac; - index++; - } else if (!targetId.bleMac.empty() && targetId.bleMac.length() <= BT_MAC_LEN) { - LOGI("AuthManager::ParseConnectAddr parse bleMac: %{public}s.", GetAnonyString(targetId.bleMac).c_str()); - addr.type = ConnectionAddrType::CONNECTION_ADDR_BLE; - memcpy_s(addr.info.ble.bleMac, BT_MAC_LEN, targetId.bleMac.c_str(), targetId.bleMac.length()); - if (!targetId.deviceId.empty()) { - Crypto::ConvertHexStringToBytes(addr.info.ble.udidHash, UDID_HASH_LEN, - targetId.deviceId.c_str(), targetId.deviceId.length()); - } - deviceInfo->addr[index] = addr; - deviceId = targetId.bleMac; - index++; - } else { - LOGE("AuthManager::ParseConnectAddr failed, not addr."); - return ERR_DM_INPUT_PARA_INVALID; - } - - deviceInfo->addrNum = static_cast(index); - if (context_->softbusConnector->AddMemberToDiscoverMap(deviceId, deviceInfo) != DM_OK) { - LOGE("AuthManager::ParseConnectAddr failed, AddMemberToDiscoverMap failed."); - return ERR_DM_INPUT_PARA_INVALID; - } - deviceInfo = nullptr; - return DM_OK; -} - void AuthManager::SetAuthType(int32_t authType) { context_->authType = (DmAuthType)authType; @@ -551,7 +526,6 @@ void AuthManager::ParseJsonObject(const JsonObject &jsonObject) context_->accessee.displayId = jsonObject[TAG_PEER_DISPLAY_ID].Get(); } - ParseHmlInfoInJsonObject(jsonObject); return; } @@ -608,7 +582,7 @@ void AuthManager::GetAuthParam(const std::string &sessionName, int32_t authType, context_->accesser.deviceName = context_->softbusConnector->GetLocalDeviceName(); context_->accesser.deviceType = context_->softbusConnector->GetLocalDeviceTypeId(); context_->accesser.deviceId = localUdid; - uint32_t tokenId = 0 ; + uint32_t tokenId = 0; MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, context_->accesser.userId); context_->accesser.tokenId = static_cast(tokenId); if (realPkgName != sessionName) { @@ -652,7 +626,6 @@ void AuthManager::InitAuthState(const std::string &sessionName, int32_t authType DmAuthState::HandleAuthenticateTimeout(context_, name); }); GetAuthParam(sessionName, authType, deviceId, extra); - context_->requestId = context_->accesser.tokenId; context_->authStateMachine->TransitionTo(std::make_shared()); LOGI("AuthManager::AuthenticateDevice complete"); @@ -684,8 +657,9 @@ int32_t AuthManager::AuthenticateDevice(const std::string &sessionName, int32_t } int32_t AuthManager::BindTarget(const std::string &sessionName, const PeerTargetId &targetId, - const std::map &bindParam) + const std::map &bindParam, int sessionId, int64_t logicalSessionId) { + int ret = DM_OK; LOGI("AuthManager::BindTarget start. sessionName: %{public}s", sessionName.c_str()); for (auto iter = bindParam.begin(); iter != bindParam.end(); iter++) { LOGI("AuthManager::BindTarget para: %{public}s : %{public}s ", iter->first.c_str(), iter->second.c_str()); @@ -710,19 +684,29 @@ int32_t AuthManager::BindTarget(const std::string &sessionName, const PeerTarget } context_->peerTargetId = targetId; bindParam_ = bindParam; - std::string deviceId = ""; - std::string addrType; - if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) { - addrType = bindParam.at(PARAM_KEY_CONN_ADDR_TYPE); - } - if (ParseConnectAddr(targetId, deviceId, addrType) == DM_OK) { - return AuthenticateDevice(sessionName, authType, deviceId, ParseExtraFromMap(bindParam)); - } else if (!targetId.deviceId.empty()) { - return AuthenticateDevice(sessionName, authType, targetId.deviceId, ParseExtraFromMap(bindParam)); + if (!targetId.deviceId.empty()) { + ret = AuthenticateDevice(sessionName, authType, targetId.deviceId, ParseExtraFromMap(bindParam)); + if (ret != DM_OK) { + return ret; + } } else { LOGE("AuthManager::BindTarget failed, targetId is error."); return ERR_DM_INPUT_PARA_INVALID; } + + if (context_->authMessageProcessor == nullptr) { + LOGE("AuthSrcManager::OnSessionOpened but request state is wrong"); + return ERR_DM_AUTH_FAILED; + } + + context_->sessionId = sessionId; + context_->logicalSessionId = logicalSessionId; + context_->requestId = logicalSessionId; + context_->authStateMachine->TransitionTo(std::make_shared()); + info = { .funcName = "BindTarget" }; + info.channelId = sessionId; + DmRadarHelper::GetInstance().ReportAuthSendRequest(info); + return ret; } AuthSinkManager::AuthSinkManager(std::shared_ptr softbusConnector, @@ -737,20 +721,6 @@ AuthSinkManager::AuthSinkManager(std::shared_ptr softbusConnec void AuthSinkManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) { LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result); - if (context_->authMessageProcessor == nullptr) { - // authMessage为空,开始初始化 - context_->sessionId = sessionId; - context_->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), - DmAuthState::GetTaskTimeout(context_, AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), - [this] (std::string name) { DmAuthState::HandleAuthenticateTimeout(context_, name); - }); - context_->timer->StartTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK), - DmAuthState::GetTaskTimeout(context_, WAIT_NEGOTIATE_TIMEOUT_TASK, WAIT_NEGOTIATE_TIMEOUT), - [this] (std::string name) { DmAuthState::HandleAuthenticateTimeout(context_, name); - }); - } - - return; } void AuthSinkManager::OnSessionClosed(int32_t sessionId) @@ -866,20 +836,6 @@ AuthSrcManager::AuthSrcManager(std::shared_ptr softbusConnecto void AuthSrcManager::OnSessionOpened(int32_t sessionId, int32_t sessionSide, int32_t result) { LOGI("sessionId = %{public}d and sessionSide = %{public}d result = %{public}d", sessionId, sessionSide, result); - - if (context_->authMessageProcessor == nullptr) { - context_->softbusConnector->GetSoftbusSession()->CloseAuthSession(sessionId); - LOGE("AuthSrcManager::OnSessionOpened but request state is wrong"); - return; - } - - context_->sessionId = sessionId; - context_->authStateMachine->TransitionTo(std::make_shared()); - struct RadarInfo info = { .funcName = "OnSessionOpened" }; - info.channelId = sessionId; - DmRadarHelper::GetInstance().ReportAuthSendRequest(info); - - return; } void AuthSrcManager::OnSessionClosed(int32_t sessionId) @@ -953,7 +909,16 @@ int32_t AuthSrcManager::OnUserOperation(int32_t action, const std::string ¶m case USER_OPERATION_TYPE_DONE_PINCODE_INPUT: LOGE("AuthSrcManager OnUserOperation user input done"); context_->pinInputResult = USER_OPERATION_TYPE_DONE_PINCODE_INPUT; - context_->pinCode = std::atoi(params.c_str()); + { + JsonObject jsonObject(params); + if (jsonObject.IsDiscarded()) { + LOGE("OnUserOperation jsonStr error"); + return ERR_DM_INPUT_PARA_INVALID; + } + if (jsonObject[PIN_CODE_KEY].IsNumberInteger()) { + context_->pinCode = jsonObject[PIN_CODE_KEY].Get(); + } + } context_->authStateMachine->NotifyEventFinish(DmEventType::ON_USER_OPERATION); break; default: diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index e6ca9b3f4..f34506ceb 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -178,6 +178,7 @@ int32_t AuthSinkFinishState::Action(std::shared_ptr context) context->state = static_cast(GetStateType()); SinkFinish(context); LOGI("AuthSinkFinishState::Action ok"); + context->cleanNotifyCallback(context->logicalSessionId); return DM_OK; } @@ -192,6 +193,7 @@ int32_t AuthSrcFinishState::Action(std::shared_ptr context) LOGI("AuthSrcFinishState::Action start"); SourceFinish(context); LOGI("AuthSrcFinishState::Action ok"); + context->cleanNotifyCallback(context->logicalSessionId); return DM_OK; } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index b2a2d4950..92991d89b 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -163,6 +163,7 @@ int32_t AuthSinkConfirmState::ShowConfigDialog(std::shared_ptr co jsonObj[TAG_REQUESTER] = context->accesser.deviceName; jsonObj[TAG_USER_ID] = context->accessee.userId; jsonObj[TAG_HOST_PKGLABEL] = context->sessionName; + jsonObj[TOKENID] = context->accessee.tokenId; const std::string params = jsonObj.Dump(); DmDialogManager::GetInstance().ShowConfirmDialog(params); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index bbbc855c2..b45509cb6 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -64,38 +64,6 @@ DmAuthStateType AuthSrcStartState::GetStateType() int32_t AuthSrcStartState::Action(std::shared_ptr context) { - int32_t sessionId = 0; - if (AuthManager::IsHmlSessionType(context->connSessionType)) { - LOGI("hmlActionId %{public}d, hmlReleaseTime %{public}d, hmlEnable160M %{public}d", - context->hmlActionId, context->connDelayCloseTime, context->hmlEnable160M); - sessionId = context->softbusConnector->GetSoftbusSession() - ->OpenAuthSessionWithPara(context->accessee.deviceId, context->hmlActionId, context->hmlEnable160M); - } else { - context->accessee.openAuthDeviceId = context->accessee.deviceId; - sessionId = context->softbusConnector->GetSoftbusSession()->OpenAuthSession(context->accessee.deviceId); - } - - struct RadarInfo info = { - .funcName = "EstablishAuthChannel", - .stageRes = (sessionId > 0) ? - static_cast(StageRes::STAGE_IDLE) : static_cast(StageRes::STAGE_FAIL), - .bizState = (sessionId > 0) ? - static_cast(BizState::BIZ_STATE_START) : static_cast(BizState::BIZ_STATE_END), - .localSessName = DM_SESSION_NAME, - .peerSessName = DM_SESSION_NAME, - .isTrust = static_cast(TrustStatus::NOT_TRUST), - .commServ = static_cast(CommServ::USE_SOFTBUS), - .peerUdid = context->accessee.deviceId, - .channelId = sessionId, - .errCode = sessionId, - }; - if (!DmRadarHelper::GetInstance().ReportAuthOpenSession(info)) { - LOGE("ReportAuthOpenSession failed"); - } - if (sessionId < 0) { - LOGE("OpenAuthSession failed, stop the authentication"); - return ERR_DM_FAILED; - } return DM_OK; } @@ -208,9 +176,12 @@ int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr con { LOGI("AuthSinkNegotiateStateMachine::Action sessionid %{public}d", context->sessionId); - // 1. 停止定时器 + // 1. 创建授权定时器 if (context->timer != nullptr) { - context->timer->DeleteTimer(std::string(WAIT_NEGOTIATE_TIMEOUT_TASK)); + context->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), + DmAuthState::GetTaskTimeout(context, AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), + [this, context] (std::string name) { DmAuthState::HandleAuthenticateTimeout(context, name); + }); } // 2. 获取deviceName和udid diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 521a4b1e0..0e3cdd77d 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -45,7 +45,12 @@ int32_t AuthSinkStatePinAuthComm::ShowAuthInfoDialog(std::shared_ptrpinCode)); + JsonObject jsonObj; + jsonObj[PIN_CODE_KEY] = context->pinCode; + jsonObj[TOKENID] = context->accessee.tokenId; + const std::string params = jsonObj.Dump(); + + DmDialogManager::GetInstance().ShowPinDialog(params); context->timer->StartTimer(std::string(SESSION_HEARTBEAT_TIMEOUT_TASK), DmAuthState::GetTaskTimeout(context, SESSION_HEARTBEAT_TIMEOUT_TASK, SESSION_HEARTBEAT_TIMEOUT), @@ -367,7 +372,14 @@ int32_t AuthSrcPinInputState::ShowStartAuthDialog(std::shared_ptr context->reason = ERR_DM_BIND_USER_CANCEL; return STOP_BIND; } - DmDialogManager::GetInstance().ShowInputDialog(context->accessee.deviceName); + + JsonObject jsonObj; + jsonObj[TAG_TARGET_DEVICE_NAME] = context->accessee.deviceName; + jsonObj[TOKENID] = context->accesser.tokenId; + const std::string params = jsonObj.Dump(); + + DmDialogManager::GetInstance().ShowInputDialog(params); + LOGI("AuthSrcPinInputState::ShowStartAuthDialog end."); return DM_OK; } diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp index b2b900d4a..5a2ac5cf7 100644 --- a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp @@ -293,7 +293,7 @@ int32_t AuthManagerBase::ImportAuthCode(const std::string &pkgName, const std::s } int32_t AuthManagerBase::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, - const std::map &bindParam) + const std::map &bindParam, int sessionId, int64_t logicalSessionId) { LOGE("BindTarget is not implemented in the current version"); return ERR_DM_FAILED; @@ -330,6 +330,12 @@ void AuthManagerBase::GetBindTargetParams(std::string &pkgName, PeerTargetId &ta return; } +void AuthManagerBase::RegisterCleanNotifyCallback(CleanNotifyCallback cleanNotifyCallback) +{ + LOGE("RegisterCleanNotifyCallback is not implemented in the current version"); + return; +} + std::string AuthManagerBase::ConvertSrcVersion(const std::string &version, const std::string &edition) { std::string srcVersion = ""; @@ -372,6 +378,10 @@ int32_t AuthManagerBase::DmGetUserId(int32_t displayId, int32_t targetUserId) LOGE("RespQueryTokenId: GetForegroundUserIds failed, ret: %{public}d", ret); return -1; } + // 场景1:对端指定了userId -> 校验是否为前台用户 + // 场景2:对端未指定userId + // 场景2.1: 单用户 -> 使用当前唯一前台用户 + // 场景2.2: 多用户 -> 使用当前主屏用户 if (userIds.size() == 0) { LOGE("RespQueryTokenId: GetForegroundUserIds no foreground users"); return -1; @@ -393,7 +403,6 @@ int32_t AuthManagerBase::DmGetUserId(int32_t displayId, int32_t targetUserId) } return userId; } - if (userIds.size() == 1) { return userIds[0]; } else { diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 27128b009..88623713c 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -571,6 +571,7 @@ std::string DmAuthMessageProcessor::CreateMessage(DmMessageType msgType, std::sh LOGI("DmAuthMessageProcessor::CreateMessage start. msgType is %{public}d", msgType); JsonObject jsonObj; jsonObj[TAG_MSG_TYPE] = msgType; + jsonObj[DM_TAG_LOGICAL_SESSION_ID] = context->logicalSessionId; auto itr = createMessageFuncMap_.find(msgType); if (itr == createMessageFuncMap_.end()) { LOGE("DmAuthMessageProcessor::CreateMessage msgType %{public}d error.", msgType); @@ -926,6 +927,10 @@ int32_t DmAuthMessageProcessor::ParseMessageSrcFinish(const JsonObject &jsonObje int32_t DmAuthMessageProcessor::ParseNegotiateMessage(const JsonObject &jsonObject, std::shared_ptr context) { + if (jsonObject[DM_TAG_LOGICAL_SESSION_ID].IsNumberInteger()) { + context->logicalSessionId = jsonObject[DM_TAG_LOGICAL_SESSION_ID].Get(); + context->requestId = context->logicalSessionId; + } if (jsonObject[TAG_DMVERSION].IsString()) { context->accesser.dmVersion = jsonObject[TAG_DMVERSION].Get(); } @@ -937,7 +942,6 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(const JsonObject &jsonObje } if (jsonObject[TAG_TOKEN_ID].IsNumberInteger()) { context->accesser.tokenId = static_cast(jsonObject[TAG_TOKEN_ID].Get()); - context->requestId = context->accesser.tokenId; } if (jsonObject[TAG_DEVICE_ID_HASH].IsString()) { diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index ce6aacfc1..b49c982e6 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -21,12 +21,12 @@ #include "dm_constants.h" #include "hichain_connector_callback.h" #include "parameter.h" -#include "cJSON.h" namespace OHOS { namespace DistributedHardware { std::shared_ptr HiChainAuthConnector::dmDeviceAuthCallback_ = nullptr; +std::map> HiChainAuthConnector::dmDeviceAuthCallbackMap_; std::mutex HiChainAuthConnector::dmDeviceAuthCallbackMutex_; void HiChainAuthConnector::FreeJsonString(char *jsonStr) @@ -49,6 +49,11 @@ HiChainAuthConnector::HiChainAuthConnector() HiChainAuthConnector::~HiChainAuthConnector() { + for (auto& pair : dmDeviceAuthCallbackMap_) { + pair.second = nullptr; + } + dmDeviceAuthCallbackMap_.clear(); + dmDeviceAuthCallback_ = nullptr; LOGI("HiChainAuthConnector::destructor."); } @@ -59,6 +64,25 @@ int32_t HiChainAuthConnector::RegisterHiChainAuthCallback(std::shared_ptr callback) +{ + std::lock_guard lock(dmDeviceAuthCallbackMutex_); + dmDeviceAuthCallbackMap_[id] = callback; + return DM_OK; +} + +std::shared_ptr HiChainAuthConnector::GetDeviceAuthCallback(int64_t id) +{ + if (dmDeviceAuthCallbackMap_.find(id) != dmDeviceAuthCallbackMap_.end()) { + LOGD("HiChainAuthConnector::GetDeviceAuthCallback dmDeviceAuthCallbackMap_ id: %{public}lu.", id); + return dmDeviceAuthCallbackMap_[id]; + } + LOGD("HiChainAuthConnector::GetDeviceAuthCallback dmDeviceAuthCallbackMap_ not found, id: %{public}lu.", id); + return dmDeviceAuthCallback_; // 找不到新协议id注册的回调,则使用老协议注册的回调, 但老协议回调有可能为空 +} + int32_t HiChainAuthConnector::AuthDevice(int32_t pinCode, int32_t osAccountId, std::string udid, int64_t requestId) { LOGI("HiChainAuthConnector::AuthDevice start."); @@ -272,21 +296,23 @@ int32_t HiChainAuthConnector::AuthCredentialPinCode(int32_t osAccountId, int64_t bool HiChainAuthConnector::onTransmit(int64_t requestId, const uint8_t *data, uint32_t dataLen) { LOGI("AuthDevice onTransmit, requestId %{public}" PRId64, requestId); - if (dmDeviceAuthCallback_ == nullptr) { + auto dmDeviceAuthCallback = GetDeviceAuthCallback(requestId); + if (dmDeviceAuthCallback == nullptr) { LOGE("HiChainAuthConnector::onTransmit dmDeviceAuthCallback_ is nullptr."); return false; } - return dmDeviceAuthCallback_->AuthDeviceTransmit(requestId, data, dataLen); + return dmDeviceAuthCallback->AuthDeviceTransmit(requestId, data, dataLen); } char *HiChainAuthConnector::onRequest(int64_t requestId, int operationCode, const char *reqParams) { LOGI("HiChainAuthConnector::onRequest start."); - if (dmDeviceAuthCallback_ == nullptr) { + auto dmDeviceAuthCallback = GetDeviceAuthCallback(requestId); + if (dmDeviceAuthCallback == nullptr) { LOGE("HiChainAuthConnector::onRequest dmDeviceAuthCallback_ is nullptr."); return nullptr; } - return dmDeviceAuthCallback_->AuthDeviceRequest(requestId, operationCode, reqParams); + return dmDeviceAuthCallback->AuthDeviceRequest(requestId, operationCode, reqParams); } void HiChainAuthConnector::onFinish(int64_t requestId, int operationCode, const char *returnData) @@ -294,11 +320,12 @@ void HiChainAuthConnector::onFinish(int64_t requestId, int operationCode, const LOGI("HiChainAuthConnector::onFinish reqId:%{public}" PRId64 ", operation:%{public}d.", requestId, operationCode); (void)returnData; - if (dmDeviceAuthCallback_ == nullptr) { + auto dmDeviceAuthCallback = GetDeviceAuthCallback(requestId); + if (dmDeviceAuthCallback == nullptr) { LOGE("HiChainAuthConnector::onFinish dmDeviceAuthCallback_ is nullptr."); return; } - dmDeviceAuthCallback_->AuthDeviceFinish(requestId); + dmDeviceAuthCallback->AuthDeviceFinish(requestId); } void HiChainAuthConnector::onError(int64_t requestId, int operationCode, int errorCode, const char *errorReturn) @@ -307,7 +334,8 @@ void HiChainAuthConnector::onError(int64_t requestId, int operationCode, int err requestId, operationCode, errorCode); (void)operationCode; (void)errorReturn; - if (dmDeviceAuthCallback_ == nullptr) { + auto dmDeviceAuthCallback = GetDeviceAuthCallback(requestId); + if (dmDeviceAuthCallback == nullptr) { LOGE("HiChainAuthConnector::onError dmDeviceAuthCallback_ is nullptr."); return; } @@ -315,17 +343,18 @@ void HiChainAuthConnector::onError(int64_t requestId, int operationCode, int err if (errorCode == PROOF_MISMATCH) { dmErrorCode = ERR_DM_HICHAIN_PROOFMISMATCH; } - dmDeviceAuthCallback_->AuthDeviceError(requestId, dmErrorCode); + dmDeviceAuthCallback->AuthDeviceError(requestId, dmErrorCode); } void HiChainAuthConnector::onSessionKeyReturned(int64_t requestId, const uint8_t *sessionKey, uint32_t sessionKeyLen) { LOGI("HiChainAuthConnector::onSessionKeyReturned start."); - if (dmDeviceAuthCallback_ == nullptr) { + auto dmDeviceAuthCallback = GetDeviceAuthCallback(requestId); + if (dmDeviceAuthCallback == nullptr) { LOGE("HiChainAuthConnector::onSessionKeyReturned dmDeviceAuthCallback_ is nullptr."); return; } - dmDeviceAuthCallback_->AuthDeviceSessionKey(requestId, sessionKey, sessionKeyLen); + dmDeviceAuthCallback->AuthDeviceSessionKey(requestId, sessionKey, sessionKeyLen); } int32_t HiChainAuthConnector::GenerateCredential(std::string &localUdid, int32_t osAccountId, std::string &publicKey) diff --git a/services/implementation/src/dependency/softbus/softbus_session.cpp b/services/implementation/src/dependency/softbus/softbus_session.cpp index 60f98164a..eb20396d8 100644 --- a/services/implementation/src/dependency/softbus/softbus_session.cpp +++ b/services/implementation/src/dependency/softbus/softbus_session.cpp @@ -161,20 +161,6 @@ int32_t SoftbusSession::GetPeerDeviceId(int32_t sessionId, std::string &peerDevI int32_t SoftbusSession::SendData(int32_t sessionId, std::string &message) { - JsonObject jsonObject(message); - if (jsonObject.IsDiscarded()) { - LOGE("extrasJson error, message: %{public}s.", GetAnonyString(message).c_str()); - return ERR_DM_FAILED; - } - if (!IsInt32(jsonObject, TAG_MSG_TYPE)) { - LOGE("SoftbusSession::SendData err json string."); - return ERR_DM_FAILED; - } - int32_t msgType = jsonObject[TAG_MSG_TYPE].Get(); - LOGI("start, msgType: %{public}d.", msgType); - if (sessionCallback_ != nullptr && sessionCallback_->GetIsCryptoSupport()) { - LOGI("SendData Start encryption."); - } int32_t ret = SendBytes(sessionId, message.c_str(), strlen(message.c_str())); if (ret != DM_OK) { LOGE("[SOFTBUS]SendBytes failed."); @@ -195,9 +181,13 @@ int32_t SoftbusSession::SendHeartbeatData(int32_t sessionId, std::string &messag int SoftbusSession::OnSessionOpened(int sessionId, int result) { + LOGD("OnSessionOpened, success, sessionId: %{public}d.", sessionId); + if (sessionCallback_ == nullptr) { + LOGD("Session callback is not registered."); + return DM_OK; + } int32_t sessionSide = GetSessionSide(sessionId); sessionCallback_->OnSessionOpened(sessionId, sessionSide, result); - LOGD("OnSessionOpened, success, sessionId: %{public}d.", sessionId); return DM_OK; } @@ -206,36 +196,13 @@ void SoftbusSession::OnSessionClosed(int sessionId) LOGI("OnSessionClosed, sessionId: %{public}d.", sessionId); CHECK_NULL_VOID(sessionCallback_); sessionCallback_->OnSessionClosed(sessionId); + return; } void SoftbusSession::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) { - if (sessionId < 0 || data == nullptr || dataLen <= 0 || dataLen > MAX_DATA_LEN) { - LOGI("[SOFTBUS]fail to receive data from softbus with sessionId: %{public}d, dataLen: %{public}d.", sessionId, - dataLen); - return; - } LOGI("start, sessionId: %{public}d, dataLen: %{public}d.", sessionId, dataLen); - if (sessionCallback_->GetIsCryptoSupport()) { - LOGI("Start decryption."); - } - std::string message = std::string(reinterpret_cast(data), dataLen); - JsonObject jsonObject(message); - if (jsonObject.IsDiscarded()) { - LOGE("DecodeRequestAuth jsonStr error"); - return; - } - if (!IsInt32(jsonObject, TAG_MSG_TYPE)) { - LOGE("err json string, first time"); - return; - } - if (jsonObject[TAG_MSG_TYPE].Get() == AUTH_DEVICE_REQ_NEGOTIATE || - jsonObject[TAG_MSG_TYPE].Get() == AUTH_DEVICE_RESP_NEGOTIATE) { - sessionCallback_->OnAuthDeviceDataReceived(sessionId, message); - } else { - sessionCallback_->OnDataReceived(sessionId, message); - } - LOGI("completed."); + return; } } // namespace DistributedHardware } // namespace OHOS -- Gitee From f905079d9f76657bec034d56d270ed968f18af44 Mon Sep 17 00:00:00 2001 From: ZHANGHE24 Date: Fri, 28 Mar 2025 01:40:59 +0800 Subject: [PATCH 319/382] feat: multi-session implementation --- .../src/device_manager_service_impl.cpp | 915 ++++++++++++++---- 1 file changed, 748 insertions(+), 167 deletions(-) diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 17b280cdb..e75ddf293 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -15,6 +15,9 @@ #include "device_manager_service_impl.h" +#include +#include +#include #include #include "app_manager.h" @@ -27,6 +30,7 @@ #include "dm_radar_helper.h" #include "dm_softbus_cache.h" #include "multiple_user_connector.h" +#include "ipc_skeleton.h" #if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) #include "dm_common_event_manager.h" #include "parameter.h" @@ -50,21 +54,14 @@ constexpr int32_t MSG_TYPE_REQ_ACL_NEGOTIATE = 80; constexpr int32_t MSG_TYPE_RESP_ACL_NEGOTIATE = 90; constexpr int32_t MSG_TYPE_REQ_AUTH_TERMINATE = 104; constexpr int32_t AUTH_SRC_FINISH_STATE = 12; +constexpr int32_t MAX_DATA_LEN = 65535; +constexpr const char* DM_TAG_LOGICAL_SESSION_ID = "logicalSessionId"; +constexpr const char* DM_TAG_PEER_DISPLAY_ID = "peerDisplayId"; +constexpr const char* DM_TAG_ACCESSEE_USER_ID = "accesseeUserId"; +constexpr const char* DM_TAG_EXTRA_INFO = "extraInfo"; -bool IsMessageOldVersion(int sessionId, const void *data, unsigned int dataLen) +static bool IsMessageOldVersion(const JsonObject &jsonObject, std::shared_ptr session) { - std::string message = std::string(reinterpret_cast(data), dataLen); - JsonObject jsonObject(message); - if (jsonObject.IsDiscarded() || !IsInt32(jsonObject, TAG_MSG_TYPE)) { - LOGE("IsMessageOldVersion decode jsonStr error"); - return false; - } - - if (jsonObject[TAG_MSG_TYPE].Get() != MSG_TYPE_REQ_ACL_NEGOTIATE && - jsonObject[TAG_MSG_TYPE].Get() != MSG_TYPE_RESP_ACL_NEGOTIATE) { - return false; - } - std::string dmVersion = ""; std::string edition = ""; if (IsString(jsonObject, TAG_DMVERSION)) { @@ -75,6 +72,9 @@ bool IsMessageOldVersion(int sessionId, const void *data, unsigned int dataLen) } dmVersion = AuthManagerBase::ConvertSrcVersion(dmVersion, edition); + // 物理会话版本赋值,并解除信号量 + session->version_ = dmVersion; + // 若版本号高于5.0.4旧协议最高版本,则不需要切换老协议 if (CompareVersion(dmVersion, DM_VERSION_5_0_OLD_MAX) == true) { return false; @@ -90,56 +90,272 @@ std::string CreateTerminateMessage(void) jsonObject[TAG_REPLY] = ERR_DM_VERSION_INCOMPATIBLE; jsonObject[TAG_AUTH_FINISH] = false; - return SafetyDump(jsonObject); + return jsonObject.Dump(); } } +std::condition_variable DeviceManagerServiceImpl::cleanEventCv_; +std::mutex DeviceManagerServiceImpl::cleanEventMutex_; +std::queue DeviceManagerServiceImpl::cleanEventQueue_; + +Session::Session(int sessionId, std::string deviceId) +{ + sessionId_ = sessionId; + deviceId_ = deviceId; +} + DeviceManagerServiceImpl::DeviceManagerServiceImpl() { + running_ = true; + thread_ = std::thread(&DeviceManagerServiceImpl::CleanWorker, this); LOGI("DeviceManagerServiceImpl constructor"); } DeviceManagerServiceImpl::~DeviceManagerServiceImpl() { + Stop(); + thread_.join(); LOGI("DeviceManagerServiceImpl destructor"); } -int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide) +static uint64_t StringToUint64(const std::string& str) { - int32_t ret; + // 计算子字符串的长度,取字符串长度和8的最小值 + size_t subStrLength = std::min(str.length(), 8lu); - if (authMgr_ == nullptr) { - if (isSrcSide) { - authMgr_ = std::make_shared(softbusConnector_, listener_, hiChainAuthConnector_); - } else { - authMgr_ = std::make_shared(softbusConnector_, listener_, hiChainAuthConnector_); + // 提取子字符串 + std::string substr = str.substr(str.length() - subStrLength); + + // 将子字符串转换为uint64_t + uint64_t result = 0; + for (size_t i = 0; i < subStrLength; ++i) { + result <<= 8; // 向左位移8位 + result |= static_cast(substr[i]); + } + + return result; +} + + +static uint64_t GetTokenId(bool isSrcSide, int32_t displayId, int32_t userId, std::string &bundleName) +{ + uint64_t tokenId = 0; + if (isSrcSide) { + // src端 + tokenId = IPCSkeleton::GetCallingTokenID(); + } else { + // sink端 + int64_t tmpTokenId; + // 获取userId + int32_t targetUserId = AuthManagerBase::DmGetUserId(displayId, userId); + if (targetUserId == -1) { + return tokenId; } - softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); - // hiChainConnector_->RegisterHiChainCallback(authMgr_); - hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); - if (!authMgr_->IsAuthManagerConstructSuccess()) { - LOGE("DeviceManagerServiceImpl::InitAndRegisterAuthMgr failed."); - return ERR_DM_FAILED; + if (AppManager::GetInstance().GetHapTokenIdByName(targetUserId, bundleName, 0, tmpTokenId) == DM_OK) { + tokenId = static_cast(tmpTokenId); + } else { + // 获取deviceId, 取其8位字符值作为tokenId + char localDeviceId[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); + std::string deviceId = std::string(localDeviceId); + if (deviceId.length() != 0) { + tokenId = StringToUint64(deviceId); + } + // TODO: 若是device绑定,其他类型绑定不允许,则使用设置标志,不允许其他类型authMgr创建 } - LOGI(" DeviceManagerServiceImpl::InitAndRegisterAuthMgr import authcode %{public}s and pkgName %{public}s", - importAuthCode_.c_str(), importPkgName_.c_str()); - if (!importAuthCode_.empty() && !importPkgName_.empty()) { - ret = authMgr_->ImportAuthCode(importPkgName_, importAuthCode_); - if (ret != DM_OK) { - LOGE("DeviceManagerServiceImpl::OnBytesReceived import authCode failed"); - authMgr_ = nullptr; - return ERR_DM_FAILED; + } + return tokenId; +} + +int64_t DeviceManagerServiceImpl::FetchCleanEvent() +{ + std::unique_lock lock(cleanEventMutex_); + cleanEventCv_.wait(lock, [&] { + return !running_.load() || !cleanEventQueue_.empty(); + }); + + if (!running_.load()) return 0; + + int64_t logicalSessionId = cleanEventQueue_.front(); + cleanEventQueue_.pop(); + return logicalSessionId; +} + +void DeviceManagerServiceImpl::CleanWorker() +{ + while (running_.load()) { + auto logicalSessionId = FetchCleanEvent(); + LOGD("DeviceManagerServiceImpl::CleanWorker clean auth_mgr, its logicalSessionId: %{public}lu", logicalSessionId); + CleanAuthMgrByLogicalSessionId(logicalSessionId); + } + LOGD("DeviceManagerServiceImpl::CleanWorker end"); +} + +void DeviceManagerServiceImpl::Stop() +{ + running_.store(false); + cleanEventCv_.notify_all(); +} + +void DeviceManagerServiceImpl::NotifyCleanEvent(int64_t logicalSessionId) +{ + LOGD("DeviceManagerServiceImpl::NotifyCleanEvent logicalSessionId: %{public}lu", logicalSessionId); + std::lock_guard lock(cleanEventMutex_); + // 存入到队列中 + cleanEventQueue_.push(logicalSessionId); + cleanEventCv_.notify_one(); +} + +int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide, uint64_t tokenId, + std::shared_ptr session, int64_t logicalSessionId) +{ + if (session == nullptr) { + LOGE("InitAndRegisterAuthMgr, The physical link is not created."); + return ERR_DM_AUTH_OPEN_SESSION_FAILED; + } + // 判断version为空,首次创建允许通过,创建新协议auth_mgr,去协商version;后续创建等待,释放后直接使用version创建对应auth_mgr + if (session->version_ == "") { + bool expected = false; + if (session->flag_.compare_exchange_strong(expected, true)) { + LOGI("The physical link is being created and the dual-end device version is aligned."); + } else { + // 不允许同时协商版本,直接报错 + LOGE("Version negotiation is not allowed at the same time."); + return ERR_DM_AUTH_BUSINESS_BUSY; + } + } + if (session->version_ == "" || CompareVersion(session->version_, DM_VERSION_5_0_OLD_MAX)) { + // 首次创建或新协议 + if (authMgrMap_.find(tokenId) == authMgrMap_.end()) { + // 创建新auth_mgr,创建authMgrMap_[tokenId] + if (isSrcSide) { + // src端 + authMgrMap_[tokenId] = std::make_shared(softbusConnector_, listener_, hiChainAuthConnector_); + } else { + // sink端 + authMgrMap_[tokenId] = std::make_shared(softbusConnector_, listener_, hiChainAuthConnector_); + } + // 资源销毁通知函数注册 + authMgrMap_[tokenId]->RegisterCleanNotifyCallback(&DeviceManagerServiceImpl::NotifyCleanEvent); + hiChainAuthConnector_->RegisterHiChainAuthCallbackById(logicalSessionId, authMgrMap_[tokenId]); + LOGD("DeviceManagerServiceImpl::Initialize authMgrMap_ token: %{public}lu.", tokenId); + // 导入配置 + if (configsMap_.find(tokenId) != configsMap_.end()) { + authMgrMap_[tokenId]->ImportAuthCode(configsMap_[tokenId]->pkgName, configsMap_[tokenId]->authCode); + authMgrMap_[tokenId]->RegisterAuthenticationType(configsMap_[tokenId]->authenticationType); + configsMap_[tokenId] = nullptr; + configsMap_.erase(tokenId); } + return DM_OK; } - } else { - // 线程已创建authMgr_,说明已有绑定事件,其他请求拒绝,返回错误码 - LOGI("DeviceManagerServiceImpl::InitAndRegisterAuthMgr authMgr_ is not null, no need to create"); - //return ERR_DM_AUTH_BUSINESS_BUSY; + if (authMgr_ == nullptr) { + // 创建老auth_mar,只创建独立的一个 + authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, listener_, + hiChainAuthConnector_); + hiChainConnector_->RegisterHiChainCallback(authMgr_); + hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); + return DM_OK; + } } - return DM_OK; + // 已创建authMgr_,说明已有绑定事件,其他请求拒绝,返回错误码 + LOGE("BindTarget failed, this device is being bound. Please try again later."); + return ERR_DM_AUTH_BUSINESS_BUSY; +} + +void DeviceManagerServiceImpl::CleanSessionMap(int sessionId, std::shared_ptr session) +{ + session->logicalSessionCnt_.fetch_sub(1); + if (session->logicalSessionCnt_.load(std::memory_order_relaxed) == 0) { + softbusConnector_->GetSoftbusSession()->OnSessionClosed(sessionId); + std::lock_guard lock(mapMutex_); + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + sessionsMap_[sessionId] = nullptr; + sessionsMap_.erase(sessionId); + } + if (deviceId2SessionIdMap_.find(session->deviceId_) != deviceId2SessionIdMap_.end()) { + deviceId2SessionIdMap_.erase(session->deviceId_); + } + } + return; +} + +void DeviceManagerServiceImpl::CleanSessionMapByLogicalSessionId(int64_t logicalSessionId) +{ + if (logicalSessionId2SessionIdMap_.find(logicalSessionId) != logicalSessionId2SessionIdMap_.end()) { + auto sessionId = logicalSessionId2SessionIdMap_[logicalSessionId]; + auto session = GetCurSession(sessionId); + if (session != nullptr) { + CleanSessionMap(sessionId, session); + } + logicalSessionId2SessionIdMap_.erase(logicalSessionId); + } + return; +} + +void DeviceManagerServiceImpl::CleanAuthMgrByLogicalSessionId(int64_t logicalSessionId) +{ + uint64_t tokenId = 0; + if (logicalSessionId2TokenIdMap_.find(logicalSessionId) != logicalSessionId2TokenIdMap_.end()) { + tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; + logicalSessionId2TokenIdMap_.erase(logicalSessionId); + } + + if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { + authMgrMap_[tokenId] = nullptr; + authMgrMap_.erase(tokenId); + } + + if (configsMap_.find(tokenId) != configsMap_.end()) { + configsMap_[tokenId] = nullptr; + configsMap_.erase(tokenId); + } + CleanSessionMapByLogicalSessionId(logicalSessionId); + + return; +} + +std::shared_ptr DeviceManagerServiceImpl::GetAuthMgr() +{ + uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); + if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { + LOGD("DeviceManagerServiceImpl::GetAuthMgr authMgrMap_ token: %{public}lu.", tokenId); + return authMgrMap_[tokenId]; + } + LOGE("DeviceManagerServiceImpl::GetAuthMgr authMgrMap_ not found, token: %{public}lu.", tokenId); + return authMgr_; // 查找不到新协议的authMgr时,返回旧协议authMgr,但可能为空 +} + +// 在回调函数中需要用到 +std::shared_ptr DeviceManagerServiceImpl::GetAuthMgrByTokenId(uint64_t tokenId) +{ + if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { + LOGD("DeviceManagerServiceImpl::GetAuthMgrByTokenId authMgrMap_ token: %{public}lu.", tokenId); + return authMgrMap_[tokenId]; + } + LOGE("DeviceManagerServiceImpl::GetAuthMgrByTokenId authMgrMap_ not found, token: %{public}lu.", tokenId); + return authMgr_; // 查找不到新协议的authMgr时,返回旧协议authMgr,但可能为空 +} + +static int64_t GenerateRandNum(int sessionId) +{ + // 获取当前时间戳 + auto timestamp = std::chrono::duration_cast(std::chrono::high_resolution_clock::now().time_since_epoch()).count(); + + // 生成随机数 + std::random_device rd; + std::mt19937 gen(rd()); + std::uniform_int_distribution<> rand_dis(0, 0xFFFFFFFF); + uint32_t random_number = rand_dis(gen); + + // 组合随机数 + int64_t randNum = (static_cast(timestamp) << 32) | + (static_cast(sessionId) << 16) | + static_cast(random_number); + + return randNum; } int32_t DeviceManagerServiceImpl::Initialize(const std::shared_ptr &listener) @@ -162,13 +378,6 @@ int32_t DeviceManagerServiceImpl::Initialize(const std::shared_ptrRegisterSoftbusStateCallback(); } - // if (authMgr_ == nullptr) { - // authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, listener, - // hiChainAuthConnector_); - // softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); - // hiChainConnector_->RegisterHiChainCallback(authMgr_); - // hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); - // } if (credentialMgr_ == nullptr) { credentialMgr_ = std::make_shared(hiChainConnector_, listener); } @@ -189,7 +398,23 @@ void DeviceManagerServiceImpl::Release() #endif softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(); hiChainConnector_->UnRegisterHiChainCallback(); - authMgr_ = nullptr; + for (auto& pair : authMgrMap_) { + pair.second = nullptr; + } + authMgrMap_.clear(); + for (auto& pair : sessionsMap_) { + pair.second = nullptr; + } + sessionsMap_.clear(); + for (auto& pair : configsMap_) { + pair.second = nullptr; + } + deviceId2SessionIdMap_.clear(); + configsMap_.clear(); + deviceIdMutexMap_.clear(); + sessionEnableMutexMap_.clear(); + sessionEnableCvMap_.clear(); + logicalSessionId2TokenIdMap_.clear(); deviceStateMgr_ = nullptr; softbusConnector_ = nullptr; abilityMgr_ = nullptr; @@ -206,7 +431,12 @@ int32_t DeviceManagerServiceImpl::UnAuthenticateDevice(const std::string &pkgNam pkgName.c_str(), GetAnonyString(udid).c_str()); return ERR_DM_INPUT_PARA_INVALID; } - return authMgr_->UnAuthenticateDevice(pkgName, udid, bindLevel); + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr_ is nullptr"); + return ERR_DM_POINT_NULL; + } + return authMgr->UnAuthenticateDevice(pkgName, udid, bindLevel); } int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgName) @@ -215,7 +445,12 @@ int32_t DeviceManagerServiceImpl::StopAuthenticateDevice(const std::string &pkgN LOGE("DeviceManagerServiceImpl::StopAuthenticateDevice failed"); return ERR_DM_INPUT_PARA_INVALID; } - return authMgr_->StopAuthenticateDevice(pkgName); + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr_ is nullptr"); + return ERR_DM_POINT_NULL; + } + return authMgr->StopAuthenticateDevice(pkgName); } int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string &udid, @@ -259,8 +494,18 @@ int32_t DeviceManagerServiceImpl::SetUserOperation(std::string &pkgName, int32_t "%{public}s", pkgName.c_str(), params.c_str()); return ERR_DM_INPUT_PARA_INVALID; } - if (authMgr_ != nullptr) { - authMgr_->OnUserOperation(action, params); + uint64_t tokenId = 0; + JsonObject jsonObject(params); + if (jsonObject.IsDiscarded()) { + LOGE("OnUserOperation jsonStr error"); + return ERR_DM_INPUT_PARA_INVALID; + } + if (jsonObject[TOKENID].IsNumberInteger()) { + tokenId = jsonObject[TOKENID].Get(); + } + auto authMgr = GetAuthMgrByTokenId(tokenId); + if (authMgr != nullptr) { + authMgr->OnUserOperation(action, params); } return DM_OK; } @@ -403,10 +648,9 @@ std::string DeviceManagerServiceImpl::GetUdidHashByNetworkId(const std::string & int DeviceManagerServiceImpl::OnSessionOpened(int sessionId, int result) { - // sink端绑定对象初始化与方法注册 - int32_t ret = InitAndRegisterAuthMgr(false); - if (ret != DM_OK) { - return ret; + { + std::lock_guard lock(sessionEnableMutexMap_[sessionId]); + sessionEnableCvMap_[sessionId].notify_all(); } std::string peerUdid = ""; softbusConnector_->GetSoftbusSession()->GetPeerDeviceId(sessionId, peerUdid); @@ -420,129 +664,207 @@ int DeviceManagerServiceImpl::OnSessionOpened(int sessionId, int result) if (!DmRadarHelper::GetInstance().ReportAuthSessionOpenCb(info)) { LOGE("ReportAuthSessionOpenCb failed"); } + + // 获取对端deviceId,sink端给sessionsMap[deviceId] = session; + { + std::lock_guard lock(mapMutex_); + if (sessionsMap_.find(sessionId) == sessionsMap_.end()) { + sessionsMap_[sessionId] = std::make_shared(sessionId, peerUdid); + } + } + return SoftbusSession::OnSessionOpened(sessionId, result); } void DeviceManagerServiceImpl::OnSessionClosed(int sessionId) { + auto session = GetCurSession(sessionId); + if (session != nullptr) { + std::lock_guard lock(mapMutex_); + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + sessionsMap_[sessionId] = nullptr; + sessionsMap_.erase(sessionId); + } + if (deviceId2SessionIdMap_.find(session->deviceId_) != deviceId2SessionIdMap_.end()) { + deviceId2SessionIdMap_.erase(session->deviceId_); + } + } SoftbusSession::OnSessionClosed(sessionId); } -int32_t DeviceManagerServiceImpl::CreateAuthMgrByMessage(int sessionId, const void *data, unsigned int dataLen) +// data 转 json +static JsonObject GetJsonObjectFromData(const void *data, unsigned int dataLen) { - if (data == nullptr || dataLen < 0) { - LOGE("DeviceManagerServiceImpl::CreateAuthMgrByMessage fail to reveive data from DeviceManagerServiceImpl " - "with dataLen: %{public}d", dataLen); - return ERR_DM_INPUT_PARA_INVALID; - } - std::string message = std::string(reinterpret_cast(data), dataLen); - JsonObject jsonObject(message); - if (jsonObject.IsDiscarded()) { - LOGE("DeviceManagerServiceImpl::CreateAuthMgrByMessage decode jsonStr error"); - return ERR_DM_JSON_PARSE_STRING; - } - - // 获取版本号 - std::string dmVersion; - std::string edition = ""; - if (IsString(jsonObject, TAG_DMVERSION) == false) { - LOGE("DeviceManagerServiceImpl::CreateAuthMgrByMessage decode dmversion error"); - return ERR_DM_JSON_PARSE_STRING; - } - dmVersion = jsonObject[TAG_DMVERSION].Get(); - if (IsString(jsonObject, TAG_EDITION)) { - edition = jsonObject[TAG_EDITION].Get(); - } - dmVersion = AuthManagerBase::ConvertSrcVersion(dmVersion, edition); - - if (CompareVersion(dmVersion, DM_VERSION_5_1_0) == false) { - // 创建老协议对象 - authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, - listener_, hiChainAuthConnector_); - - // 参数2 sessionSide为0,authMgr_为空一定是sink端,src端会在BindTarget时创建协议对象 - authMgr_->OnSessionOpened(sessionId, 0, 0); - LOGI("DeviceManagerServiceImpl::CreateAuthMgrByMessage sink transfer to old version success"); - return DM_OK; - } - - // 创建新协议对象 - return InitAndRegisterAuthMgr(false); + return JsonObject(message); } // 版本降级时,基于报文判断是src还是sink // src: 收到90报文 // sink:收到80报文 -bool IsAuthManagerSourceByMessage(const void *data, unsigned int dataLen) +static bool IsAuthManagerSourceByMessage(int32_t msgType) { - std::string message = std::string(reinterpret_cast(data), dataLen); - // 走到这里已经确认可以转json,所以不需要再判断 - JsonObject jsonObject(message); + return msgType == MSG_TYPE_RESP_ACL_NEGOTIATE; +} - return jsonObject[TAG_MSG_TYPE].Get() == MSG_TYPE_RESP_ACL_NEGOTIATE; + +// 获取当前session对象 +std::shared_ptr DeviceManagerServiceImpl::GetCurSession(int sessionId) { + std::shared_ptr curSession = nullptr; + // 获取对端deviceId,sink端给sessionsMap[deviceId] = session; + { + std::lock_guard lock(mapMutex_); + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + curSession = sessionsMap_[sessionId]; + } else { + LOGE("OnBytesReceived, The local session cannot be found."); + } + } + return curSession; } + void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) { - int32_t ret; + /* + 1、收到80报文创建auth_mgr + 2、收到80或90报文时,获取版本, 对比进行auth_mgr重建,执行老协议 + 3、分发报文 + */ + int32_t ret = DM_OK; + if (sessionId < 0 || data == nullptr || dataLen <= 0 || dataLen > MAX_DATA_LEN) { + LOGE("[OnBytesReceived] Fail to receive data from softbus with sessionId: %{public}d, dataLen: %{public}d.", + sessionId, dataLen); + return; + } + + LOGI("start, sessionId: %{public}d, dataLen: %{public}d.", sessionId, dataLen); - if (data == nullptr || dataLen < 0) { - LOGE("DeviceManagerServiceImpl::OnBytesReceived fail to reveive data from DeviceManagerServiceImpl " - "with dataLen: %{public}d", dataLen); + JsonObject jsonObject = GetJsonObjectFromData(data, dataLen); + if (jsonObject.IsDiscarded() || !jsonObject[TAG_MSG_TYPE].IsNumberInteger()) { + LOGE("OnBytesReceived, MSG_TYPE parse failed."); + return; + } + int32_t msgType = jsonObject[TAG_MSG_TYPE].Get(); + int64_t logicalSessionId = 0; + if (jsonObject[DM_TAG_LOGICAL_SESSION_ID].IsNumberInteger()) { + logicalSessionId = jsonObject[DM_TAG_LOGICAL_SESSION_ID].Get(); + } + + std::shared_ptr curSession = GetCurSession(sessionId); + + uint64_t tokenId = 0; + if (logicalSessionId != 0) { + if (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE) { + curSession->logicalSessionSet_.insert(logicalSessionId); + std::string bundleName; + int32_t displayId = 0; + int32_t userId = 0; + if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString()) { + bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); + } + if (jsonObject[DM_TAG_PEER_DISPLAY_ID].IsNumberInteger()) { + displayId = jsonObject[DM_TAG_PEER_DISPLAY_ID].Get(); + } + if (jsonObject.Contains(DM_TAG_EXTRA_INFO) && jsonObject[DM_TAG_EXTRA_INFO].IsObject()) { + if (jsonObject[DM_TAG_EXTRA_INFO][DM_TAG_ACCESSEE_USER_ID].IsNumberInteger()) { + userId = jsonObject[DM_TAG_EXTRA_INFO][DM_TAG_ACCESSEE_USER_ID].Get(); + } + } + tokenId = GetTokenId(false, displayId, userId, bundleName); + if (tokenId == 0) { + LOGE("OnBytesReceived, Get tokenId failed."); + return; + } + if (logicalSessionId2TokenIdMap_.find(logicalSessionId) != logicalSessionId2TokenIdMap_.end()) { + LOGE("OnBytesReceived, logicalSessionId exists in logicalSessionId2TokenIdMap_."); + // TODO: authMgr需要对应销毁 + return; + } + logicalSessionId2TokenIdMap_[logicalSessionId] = tokenId; + if (InitAndRegisterAuthMgr(false, tokenId, curSession, logicalSessionId) != DM_OK) { + // 内部已完成错误日志打印 + return; + } + + } else { + if (curSession->logicalSessionSet_.find(logicalSessionId) == curSession->logicalSessionSet_.end()) { + LOGE("OnBytesReceived, The logical session ID does not exist in the physical session, so the request is rejected."); + return; + } + tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; + } + } + + auto authMgr = GetAuthMgrByTokenId(tokenId); + if (authMgr == nullptr) { + // 内部已完成错误日志打印 return; } /** 监听80/90报文 - 新-老:src端收到90报文时发现版本不匹配问题,重新BindTartget + 新-老:src端收到90报文时发现版本不匹配问题,重新BindTarget 老-新:sink端收到80报文时发现版本不匹配问题,重新OnSessionOpened和OnBytesReceived TODO: 考虑authMgr_的切换是否有多线程问题 */ - if (authMgr_->isAuthNewVersion_ && IsMessageOldVersion(sessionId, data, dataLen)) { - std::string pkgName; - PeerTargetId peerTargetId; - std::map bindParam; - authMgr_->GetBindTargetParams(pkgName, peerTargetId, bindParam); - authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, - listener_, hiChainAuthConnector_); - authMgr_->isAuthNewVersion_ = false; - softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); - hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); - - if (!importAuthCode_.empty() && !importPkgName_.empty()) { - ret = authMgr_->ImportAuthCode(importPkgName_, importAuthCode_); - if (ret != DM_OK) { - LOGE("DeviceManagerServiceImpl::OnBytesReceived import authCode failed"); + if (curSession == nullptr) { + LOGE("InitAndRegisterAuthMgr, The physical link is not created."); + return; + } + if (curSession->version_ == "" && + (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE || msgType == MSG_TYPE_RESP_ACL_NEGOTIATE)) { + // IsMessageOldVersion内部会对session版本进行赋值,并解除对应物理会话信号量 + if (IsMessageOldVersion(jsonObject, curSession)) { + std::string pkgName; + PeerTargetId peerTargetId; + std::map bindParam; + authMgr->GetBindTargetParams(pkgName, peerTargetId, bindParam); + authMgr = nullptr; + authMgrMap_.erase(tokenId); + if (InitAndRegisterAuthMgr(false, tokenId, curSession, logicalSessionId) != DM_OK) { + // 内部已完成错误日志打印 return; } - } - if (IsAuthManagerSourceByMessage(data, dataLen)) { - // 发送停止报文 - // 不能走新协议的停止,新协议是信号机制,无法串行停止,会存在时延,导致未停止就创建了新对象, - // 然后新协议的超时机制会再次停止softbus - std::string endMessage = CreateTerminateMessage(); - (void)softbusConnector_->GetSoftbusSession()->SendData(sessionId, endMessage); - softbusConnector_->GetSoftbusSession()->OnSessionClosed(sessionId); - - ret = authMgr_->BindTarget(pkgName, peerTargetId, bindParam); - if (ret != DM_OK) { - LOGE("DeviceManagerServiceImpl::OnBytesReceived authManager BindTarget failed"); + authMgr = GetAuthMgrByTokenId(tokenId); // 获取到老协议的authmgr + if (authMgr == nullptr) { + // 内部已完成错误日志打印 return; } + + if (IsAuthManagerSourceByMessage(msgType)) { + // 发送停止报文 + // 不能走新协议的停止,新协议是信号机制,无法串行停止,会存在时延,导致未停止就创建了新对象, + // 然后新协议的超时机制会再次停止softbus + std::string endMessage = CreateTerminateMessage(); + (void)softbusConnector_->GetSoftbusSession()->SendData(sessionId, endMessage); + softbusConnector_->GetSoftbusSession()->OnSessionClosed(sessionId); + + ret = authMgr->BindTarget(pkgName, peerTargetId, bindParam, sessionId, 0); + if (ret != DM_OK) { + LOGE("DeviceManagerServiceImpl::OnBytesReceived authManager BindTarget failed"); + return; + } + LOGI("DeviceManagerServiceImpl::OnBytesReceived src transfer to old version success"); + return; + } + + // 参数2 sessionSide为0,authMgr_为空一定是sink端,src端会在BindTarget时创建协议对象 + authMgr->OnSessionOpened(sessionId, 0, 0); LOGI("DeviceManagerServiceImpl::OnBytesReceived src transfer to old version success"); - return; } - - // 参数2 sessionSide为0,authMgr_为空一定是sink端,src端会在BindTarget时创建协议对象 - authMgr_->OnSessionOpened(sessionId, 0, 0); - LOGI("DeviceManagerServiceImpl::OnBytesReceived sink transfer to old version success"); } - + std::string message = std::string(reinterpret_cast(data), dataLen); + if (msgType == AUTH_DEVICE_REQ_NEGOTIATE || msgType == AUTH_DEVICE_RESP_NEGOTIATE) { + authMgr->OnAuthDeviceDataReceived(sessionId, message); + } else { + authMgr->OnDataReceived(sessionId, message); + } SoftbusSession::OnBytesReceived(sessionId, data, dataLen); LOGI("DeviceManagerServiceImpl::OnBytesReceived in bytes received"); + return; } int32_t DeviceManagerServiceImpl::RequestCredential(const std::string &reqJsonStr, std::string &returnJsonStr) @@ -671,17 +993,38 @@ int32_t DeviceManagerServiceImpl::UnRegisterCredentialCallback(const std::string return credentialMgr_->UnRegisterCredentialCallback(pkgName); } +static uint64_t GetSecondElement(const std::string& input) { + std::istringstream stream(input); + std::string token; + int count = 0; + uint64_t value = 0; + + // 分割字符串并计数 + while (std::getline(stream, token, ' ')) { + if (count >= 1) { + // 转换为 uint64_t + value = std::stoull(token); + break; + } + count++; + } + + return value; +} + int32_t DeviceManagerServiceImpl::RegisterUiStateCallback(const std::string &pkgName) { if (pkgName.empty()) { LOGE("RegisterUiStateCallback failed, pkgName is empty"); return ERR_DM_INPUT_PARA_INVALID; } - if (authMgr_ == nullptr) { + uint64_t tokenId = GetSecondElement(pkgName); + auto authMgr = GetAuthMgrByTokenId(tokenId); + if (authMgr == nullptr) { LOGE("authMgr_ is nullptr"); return ERR_DM_POINT_NULL; } - return authMgr_->RegisterUiStateCallback(pkgName); + return authMgr->RegisterUiStateCallback(pkgName); } int32_t DeviceManagerServiceImpl::UnRegisterUiStateCallback(const std::string &pkgName) @@ -690,11 +1033,13 @@ int32_t DeviceManagerServiceImpl::UnRegisterUiStateCallback(const std::string &p LOGE("UnRegisterUiStateCallback failed, pkgName is empty"); return ERR_DM_INPUT_PARA_INVALID; } - if (authMgr_ == nullptr) { + uint64_t tokenId = GetSecondElement(pkgName); + auto authMgr = GetAuthMgrByTokenId(tokenId); + if (authMgr == nullptr) { LOGE("authMgr_ is nullptr"); return ERR_DM_POINT_NULL; } - return authMgr_->UnRegisterUiStateCallback(pkgName); + return authMgr->UnRegisterUiStateCallback(pkgName); } int32_t DeviceManagerServiceImpl::PraseNotifyEventJson(const std::string &event, JsonObject &jsonObject) @@ -784,6 +1129,15 @@ int32_t DeviceManagerServiceImpl::GetUdidHashByNetWorkId(const char *networkId, return DM_OK; } +std::shared_ptr DeviceManagerServiceImpl::GetConfigByTokenId() +{ + uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); + if (configsMap_.find(tokenId) == configsMap_.end()) { + configsMap_[tokenId] = std::make_shared(); + } + return configsMap_[tokenId]; +} + int32_t DeviceManagerServiceImpl::ImportAuthCode(const std::string &pkgName, const std::string &authCode) { if (pkgName.empty() || authCode.empty()) { @@ -791,13 +1145,15 @@ int32_t DeviceManagerServiceImpl::ImportAuthCode(const std::string &pkgName, con return ERR_DM_INPUT_PARA_INVALID; } - // TODO:需要用config结构体包装 - importAuthCode_ = authCode; - importPkgName_ = pkgName; + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + auto config = GetConfigByTokenId(); + config->pkgName = pkgName; + config->authCode = authCode; // 若多次注册,只保留最后一个 + return DM_OK; + } - LOGI("%{public}s success to import authCode %{public}s", pkgName.c_str(), authCode.c_str()); - return DM_OK; - // return authMgr_->ImportAuthCode(pkgName, authCode); + return authMgr->ImportAuthCode(pkgName, authCode); } int32_t DeviceManagerServiceImpl::ExportAuthCode(std::string &authCode) @@ -808,19 +1164,231 @@ int32_t DeviceManagerServiceImpl::ExportAuthCode(std::string &authCode) return DM_OK; } +static JsonObject GetExtraJsonObject(const std::map &bindParam) +{ + std::string extra; + auto iter = bindParam.find(PARAM_KEY_BIND_EXTRA_DATA); + if (iter != bindParam.end()) { + extra = iter->second; + } else { + extra = ConvertMapToJsonString(bindParam); + } + + return JsonObject(extra); +} + +static int32_t GetHmlInfo(const JsonObject &jsonObject, bool &hmlEnable160M, int32_t &hmlActionId) +{ + if (jsonObject[PARAM_KEY_HML_ENABLE_160M].IsBoolean()) { + hmlEnable160M = jsonObject[PARAM_KEY_HML_ENABLE_160M].Get(); + LOGI("hmlEnable160M %{public}d", hmlEnable160M); + } + if (jsonObject[PARAM_KEY_HML_ACTIONID].IsNumberInteger()) { + hmlActionId = jsonObject[PARAM_KEY_HML_ACTIONID].Get(); + if (hmlActionId < 0) { + hmlActionId = 0; + } + LOGI("hmlActionId %{public}d", hmlActionId); + } + return DM_OK; +} + +static bool IsHmlSessionType(const JsonObject &jsonObject) +{ + std::string connSessionType; + if (jsonObject[PARAM_KEY_CONN_SESSIONTYPE].IsString()) { + connSessionType = jsonObject[PARAM_KEY_CONN_SESSIONTYPE].Get(); + LOGI("connSessionType %{public}s", connSessionType.c_str()); + } + return connSessionType == CONN_SESSION_TYPE_HML; +} + +std::shared_ptr DeviceManagerServiceImpl::GetOrCreateSession(const std::string& deviceId, + const std::map &bindParam) +{ + std::shared_ptr instance; + int sessionId; + // 获取全局锁,确保maps的线程安全 + { + std::lock_guard lock(mapMutex_); + if (deviceId2SessionIdMap_.find(deviceId) != deviceId2SessionIdMap_.end()) { + sessionId = deviceId2SessionIdMap_[deviceId]; + } + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + return sessionsMap_[sessionId]; + } + } + + // 获取deviceId对应的锁 + std::mutex& device_mutex = deviceIdMutexMap_[deviceId]; + std::lock_guard lock(device_mutex); + + // 再次检查是否已经存在对应的对象(因为可能在上一步获取锁的过程中,其他线程已经创建了) + { + std::lock_guard lock(mapMutex_); + if (deviceId2SessionIdMap_.find(deviceId) != deviceId2SessionIdMap_.end()) { + sessionId = deviceId2SessionIdMap_[deviceId]; + } + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + return sessionsMap_[sessionId]; + } + + bool hmlEnable160M = false; + int32_t hmlActionId = 0; + JsonObject jsonObject = GetExtraJsonObject(bindParam); + if (jsonObject.IsDiscarded()) { + LOGE("extra string not a json type."); + goto error; + } + if (IsHmlSessionType(jsonObject)) { + if (GetHmlInfo(jsonObject, hmlEnable160M, hmlActionId) != DM_OK) { + goto error; + } + LOGI("hmlActionId %{public}d, hmlEnable160M %{public}d", hmlActionId, hmlEnable160M); + sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSessionWithPara(deviceId, + hmlActionId, hmlEnable160M); + } else { + sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId); + } + + if (sessionId < 0) { + goto error; + } + + std::unique_lock cvLock(sessionEnableMutexMap_[sessionId]); + sessionEnableCvMap_[sessionId].wait(cvLock); + + instance = std::make_shared(sessionId, deviceId); + deviceId2SessionIdMap_[deviceId] = sessionId; + sessionsMap_[sessionId] = instance; + } + return instance; +error: + // 会话打开失败 + LOGE("OpenAuthSession failed, stop the authentication"); + return nullptr; +} + +int32_t DeviceManagerServiceImpl::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, + const std::map &bindParam) +{ + std::string addrType; + if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) { + addrType = bindParam.at(PARAM_KEY_CONN_ADDR_TYPE); + } + int32_t index = 0; + std::shared_ptr deviceInfo = std::make_shared(); + ConnectionAddr addr; + if (!targetId.wifiIp.empty() && targetId.wifiIp.length() <= IP_STR_MAX_LEN) { + LOGI("AuthManager::ParseConnectAddr parse wifiIp: %{public}s.", GetAnonyString(targetId.wifiIp).c_str()); + if (!addrType.empty()) { + addr.type = static_cast(std::atoi(addrType.c_str())); + } else { + addr.type = ConnectionAddrType::CONNECTION_ADDR_WLAN; + } + if (memcpy_s(addr.info.ip.ip, IP_STR_MAX_LEN, targetId.wifiIp.c_str(), targetId.wifiIp.length()) != 0) { + LOGE("get ip addr: %{public}s failed", GetAnonyString(targetId.wifiIp).c_str()); + return ERR_DM_SECURITY_FUNC_FAILED; + } + addr.info.ip.port = targetId.wifiPort; + deviceInfo->addr[index] = addr; + deviceId = targetId.wifiIp; + index++; + } else if (!targetId.brMac.empty() && targetId.brMac.length() <= BT_MAC_LEN) { + LOGI("AuthManager::ParseConnectAddr parse brMac: %{public}s.", GetAnonyString(targetId.brMac).c_str()); + addr.type = ConnectionAddrType::CONNECTION_ADDR_BR; + if (memcpy_s(addr.info.br.brMac, BT_MAC_LEN, targetId.brMac.c_str(), targetId.brMac.length()) != 0) { + LOGE("get brMac addr: %{public}s failed", GetAnonyString(targetId.brMac).c_str()); + return ERR_DM_SECURITY_FUNC_FAILED; + } + deviceInfo->addr[index] = addr; + deviceId = targetId.brMac; + index++; + } else if (!targetId.bleMac.empty() && targetId.bleMac.length() <= BT_MAC_LEN) { + LOGI("AuthManager::ParseConnectAddr parse bleMac: %{public}s.", GetAnonyString(targetId.bleMac).c_str()); + addr.type = ConnectionAddrType::CONNECTION_ADDR_BLE; + if (memcpy_s(addr.info.ble.bleMac, BT_MAC_LEN, targetId.bleMac.c_str(), targetId.bleMac.length()) != 0) { + LOGE("get bleMac addr: %{public}s failed", GetAnonyString(targetId.bleMac).c_str()); + return ERR_DM_SECURITY_FUNC_FAILED; + } + if (!targetId.deviceId.empty()) { + Crypto::ConvertHexStringToBytes(addr.info.ble.udidHash, UDID_HASH_LEN, + targetId.deviceId.c_str(), targetId.deviceId.length()); + } + deviceInfo->addr[index] = addr; + deviceId = targetId.bleMac; + index++; + } else { + LOGE("AuthManager::ParseConnectAddr failed, not addr."); + return ERR_DM_INPUT_PARA_INVALID; + } + + deviceInfo->addrNum = static_cast(index); + if (softbusConnector_->AddMemberToDiscoverMap(deviceId, deviceInfo) != DM_OK) { + LOGE("AuthManager::ParseConnectAddr failed, AddMemberToDiscoverMap failed."); + return ERR_DM_INPUT_PARA_INVALID; + } + deviceInfo = nullptr; + return DM_OK; +} + int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const PeerTargetId &targetId, const std::map &bindParam) { - // source端绑定对象初始化与方法注册 - int32_t ret = InitAndRegisterAuthMgr(true); + int32_t ret = DM_OK; + if (pkgName.empty()) { + LOGE("BindTarget failed, pkgName is empty."); + return ERR_DM_INPUT_PARA_INVALID; + } + + std::string deviceId = ""; + ret = ParseConnectAddr(targetId, deviceId, bindParam); + if (ret == DM_OK) { + const_cast(targetId).deviceId = deviceId; + } else { + if (targetId.deviceId.empty()) { + LOGE("DeviceManagerServiceImpl::BindTarget failed, ParseConnectAddr failed."); + return ERR_DM_INPUT_PARA_INVALID; + } + } + // 只在source端创建,新协议同一目标设备不会重复创建 + auto curSession = GetOrCreateSession(targetId.deviceId, bindParam); + if (curSession == nullptr) { + LOGE("Failed to create the session. Target deviceId: %{public}s.", targetId.deviceId.c_str()); + return ERR_DM_AUTH_OPEN_SESSION_FAILED; + } + + // 逻辑会话随机数 + int sessionId = curSession->sessionId_; + int64_t logicalSessionId = GenerateRandNum(sessionId); + if (curSession->logicalSessionSet_.find(logicalSessionId) != curSession->logicalSessionSet_.end()) { + LOGE("Failed to create the logical session."); + return ERR_DM_LOGIC_SESSION_CREATE_FAILED; + } + + // src端创建 + uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); + ret = InitAndRegisterAuthMgr(true, tokenId, curSession, logicalSessionId); if (ret != DM_OK) { + // 内部已完成错误日志打印,传递错误码即可 return ret; } - if (pkgName.empty()) { - LOGE("BindTarget failed, pkgName is empty"); - return ERR_DM_INPUT_PARA_INVALID; + + curSession->logicalSessionSet_.insert(logicalSessionId); + curSession->logicalSessionCnt_.fetch_add(1); + logicalSessionId2TokenIdMap_[logicalSessionId] = tokenId; + logicalSessionId2SessionIdMap_[logicalSessionId] = sessionId; + + if (curSession->version_ != "" && !CompareVersion(curSession->version_, DM_VERSION_5_0_OLD_MAX)) { + softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId); + } + + // 新老协议调用 + auto authMgr = GetAuthMgr(); + if (authMgr != nullptr) { + return authMgr->BindTarget(pkgName, targetId, bindParam, sessionId, logicalSessionId); } - return authMgr_->BindTarget(pkgName, targetId, bindParam); + return ERR_DM_AUTH_FAILED; } void DeviceManagerServiceImpl::PutIdenticalAccountToAcl(std::string requestDeviceId, std::string trustDeviceId) @@ -964,12 +1532,13 @@ void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEvent { if (commonEventType == EventFwk::CommonEventSupport::COMMON_EVENT_SCREEN_LOCKED) { LOGI("DeviceManagerServiceImpl::ScreenCommonEventCallback on screen locked."); - if (authMgr_ != nullptr) { - authMgr_->OnScreenLocked(); - return; - } else { - LOGE("authMgr_ is null, cannot call OnScreenLocked."); + for (auto& pair : authMgrMap_) { + if (pair.second != nullptr) { + LOGD("DeviceManagerServiceImpl::ScreenCommonEventCallback tokenId: %{public}lu.", pair.first); + pair.second->OnScreenLocked(); + } } + return; } LOGI("DeviceManagerServiceImpl::ScreenCommonEventCallback error."); } @@ -1001,8 +1570,12 @@ void DeviceManagerServiceImpl::HandleDeviceNotTrust(const std::string &udid) LOGE("HandleDeviceNotTrust udid is empty."); return; } - CHECK_NULL_VOID(authMgr_); - authMgr_->HandleDeviceNotTrust(udid); + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr_ is nullptr"); + return; + } + authMgr->HandleDeviceNotTrust(udid); } int32_t DeviceManagerServiceImpl::GetBindLevel(const std::string &pkgName, const std::string &localUdid, @@ -1084,8 +1657,12 @@ void DeviceManagerServiceImpl::HandleDevUnBindEvent(int32_t remoteUserId, const LOGE("Invalied bindtype."); return; } - CHECK_NULL_VOID(authMgr_); - authMgr_->DeleteGroup(DM_PKG_NAME, remoteUdid); + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr_ is nullptr"); + return; + } + authMgr->DeleteGroup(DM_PKG_NAME, remoteUdid); } void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, @@ -1260,8 +1837,13 @@ void DeviceManagerServiceImpl::HandleDeviceUnBind(int32_t bindType, const std::s int32_t DeviceManagerServiceImpl::RegisterAuthenticationType(int32_t authenticationType) { - CHECK_NULL_RETURN(authMgr_, ERR_DM_POINT_NULL); - return authMgr_->RegisterAuthenticationType(authenticationType); + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + auto config = GetConfigByTokenId(); + config->authenticationType = authenticationType; // 若多次注册,只保留最后一个 + return DM_OK; + } + return authMgr->RegisterAuthenticationType(authenticationType); } void DeviceManagerServiceImpl::DeleteAlwaysAllowTimeOut() @@ -1359,5 +1941,4 @@ extern "C" IDeviceManagerServiceImpl *CreateDMServiceObject(void) return new DeviceManagerServiceImpl; } } // namespace DistributedHardware -} // namespace OHOS -; \ No newline at end of file +} // namespace OHOS \ No newline at end of file -- Gitee From 5285b2c65bdaea6a89a0a4b8444b5097d07a8b52 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Fri, 28 Mar 2025 09:29:25 +0800 Subject: [PATCH 320/382] =?UTF-8?q?BUGFIX:=E4=BF=AE=E5=A4=8D=E9=B8=BF?= =?UTF-8?q?=E8=92=99=E7=8E=AF=E5=9C=BA=E6=99=AF=E6=A0=A1=E9=AA=8C=E5=A4=B1?= =?UTF-8?q?=E8=B4=A5?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_acl.cpp | 10 +++++++--- 1 file changed, 7 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index e6ca9b3f4..246d9880c 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -105,9 +105,13 @@ int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) // 判断密文阶段和明文阶段的四元组是否相同,不同则直接结束 bool isSame = Crypto::Sha256(context->accessee.deviceId) == context->accessee.deviceIdHash && Crypto::Sha256(std::to_string(context->accessee.userId)) == context->accessee.userIdHash && - Crypto::Sha256(context->accessee.accountId) == context->accessee.accountIdHash && - Crypto::Sha256(std::to_string(context->accessee.tokenId)) == context->accessee.tokenIdHash; - // && context->accesser.bindLevel == context->accessee.bindLevel; bindlevel协商能力补齐后打开 + Crypto::Sha256(context->accessee.accountId) == context->accessee.accountIdHash; + + // 鸿蒙环场景tokenid为空,进行兼容 + isSame = Crypto::Sha256(std::to_string(context->accessee.tokenId)) == context->accessee.tokenIdHash || + (context->accessee.tokenId == 0 && context->accessee.tokenIdHash.empty()); + + // && context->accesser.bindLevel == context->accessee.bindLevel; bindlevel协商能力补齐后打开 if (!isSame) { LOGE("data between two stages different, stop auth"); // 不同直接结束,发送200给sink端 -- Gitee From 6b541aa9e024e0bb60e66868eba8764946f9643e Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Mar 2025 10:28:31 +0800 Subject: [PATCH 321/382] tmp --- services/implementation/src/authentication_v2/auth_manager.cpp | 1 + 1 file changed, 1 insertion(+) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index e2c20974d..412c538a6 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -43,6 +43,7 @@ namespace OHOS { namespace DistributedHardware { namespace { +static const char* PICKER_PROXY_SPLIT = "_pickerProxy_"; // todo check constexpr int32_t MIN_PIN_CODE = 100000; constexpr int32_t MAX_PIN_CODE = 999999; -- Gitee From 88b47797582c61345eb985b56af8af63a518f0c7 Mon Sep 17 00:00:00 2001 From: ZHANGHE24 Date: Fri, 28 Mar 2025 08:09:19 +0000 Subject: [PATCH 322/382] !16 fix: modify multi session implement * fix: fix bug * fix: fix bug * fix: fix bug * fix: fix bug * fix: fix bug * fix: modify multi session implement * fix: modify multi session implement --- .../src/device_manager_service_impl.cpp | 75 +++++++++++-------- 1 file changed, 43 insertions(+), 32 deletions(-) diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index e75ddf293..13254012f 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -64,10 +64,10 @@ static bool IsMessageOldVersion(const JsonObject &jsonObject, std::shared_ptr(); } - if (IsString(jsonObject, TAG_EDITION)) { + if (jsonObject[TAG_EDITION].IsString()) { edition = jsonObject[TAG_EDITION].Get(); } dmVersion = AuthManagerBase::ConvertSrcVersion(dmVersion, edition); @@ -197,6 +197,12 @@ void DeviceManagerServiceImpl::Stop() { running_.store(false); cleanEventCv_.notify_all(); + std::lock_guard lock(cleanEventMutex_); + while (!cleanEventQueue_.empty()) { + int64_t logicalSessionId = cleanEventQueue_.front(); + cleanEventQueue_.pop(); + CleanAuthMgrByLogicalSessionId(logicalSessionId); + } } void DeviceManagerServiceImpl::NotifyCleanEvent(int64_t logicalSessionId) @@ -255,6 +261,7 @@ int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide, uint64_ // 创建老auth_mar,只创建独立的一个 authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, listener_, hiChainAuthConnector_); + softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); hiChainConnector_->RegisterHiChainCallback(authMgr_); hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); return DM_OK; @@ -292,6 +299,7 @@ void DeviceManagerServiceImpl::CleanSessionMapByLogicalSessionId(int64_t logical } logicalSessionId2SessionIdMap_.erase(logicalSessionId); } + logicalSessionId2TokenIdMap_.erase(logicalSessionId); return; } @@ -300,7 +308,6 @@ void DeviceManagerServiceImpl::CleanAuthMgrByLogicalSessionId(int64_t logicalSes uint64_t tokenId = 0; if (logicalSessionId2TokenIdMap_.find(logicalSessionId) != logicalSessionId2TokenIdMap_.end()) { tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; - logicalSessionId2TokenIdMap_.erase(logicalSessionId); } if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { @@ -398,6 +405,7 @@ void DeviceManagerServiceImpl::Release() #endif softbusConnector_->GetSoftbusSession()->UnRegisterSessionCallback(); hiChainConnector_->UnRegisterHiChainCallback(); + authMgr_ = nullptr; for (auto& pair : authMgrMap_) { pair.second = nullptr; } @@ -410,11 +418,12 @@ void DeviceManagerServiceImpl::Release() pair.second = nullptr; } deviceId2SessionIdMap_.clear(); - configsMap_.clear(); deviceIdMutexMap_.clear(); sessionEnableMutexMap_.clear(); sessionEnableCvMap_.clear(); logicalSessionId2TokenIdMap_.clear(); + logicalSessionId2SessionIdMap_.clear(); + configsMap_.clear(); deviceStateMgr_ = nullptr; softbusConnector_ = nullptr; abilityMgr_ = nullptr; @@ -464,9 +473,9 @@ int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string extra = ""; char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - if (bindLevel == DEVICE) { - DeleteGroup(pkgName, udid); - } + // if (bindLevel == DEVICE) { + // DeleteGroup(pkgName, udid); + // } return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel, extra); } @@ -480,9 +489,9 @@ int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const } char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - if (bindLevel == DEVICE) { - DeleteGroup(pkgName, udid); - } + // if (bindLevel == DEVICE) { + // DeleteGroup(pkgName, udid); + // } return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel, extra); } @@ -681,13 +690,17 @@ void DeviceManagerServiceImpl::OnSessionClosed(int sessionId) auto session = GetCurSession(sessionId); if (session != nullptr) { std::lock_guard lock(mapMutex_); - if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { - sessionsMap_[sessionId] = nullptr; - sessionsMap_.erase(sessionId); + for (const auto& logicalSessionId : session->logicalSessionSet_) { + logicalSessionId2TokenIdMap_.erase(logicalSessionId); + logicalSessionId2SessionIdMap_.erase(logicalSessionId); } if (deviceId2SessionIdMap_.find(session->deviceId_) != deviceId2SessionIdMap_.end()) { deviceId2SessionIdMap_.erase(session->deviceId_); } + if (sessionsMap_.find(sessionId) != sessionsMap_.end()) { + sessionsMap_[sessionId] = nullptr; + sessionsMap_.erase(sessionId); + } } SoftbusSession::OnSessionClosed(sessionId); } @@ -752,10 +765,14 @@ void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, } std::shared_ptr curSession = GetCurSession(sessionId); + if (curSession == nullptr) { + LOGE("InitAndRegisterAuthMgr, The physical link is not created."); + return; + } uint64_t tokenId = 0; - if (logicalSessionId != 0) { - if (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE) { + if (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE) { + if (logicalSessionId != 0) { curSession->logicalSessionSet_.insert(logicalSessionId); std::string bundleName; int32_t displayId = 0; @@ -778,18 +795,20 @@ void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, } if (logicalSessionId2TokenIdMap_.find(logicalSessionId) != logicalSessionId2TokenIdMap_.end()) { LOGE("OnBytesReceived, logicalSessionId exists in logicalSessionId2TokenIdMap_."); - // TODO: authMgr需要对应销毁 return; } logicalSessionId2TokenIdMap_[logicalSessionId] = tokenId; - if (InitAndRegisterAuthMgr(false, tokenId, curSession, logicalSessionId) != DM_OK) { - // 内部已完成错误日志打印 - return; - } + } + if (InitAndRegisterAuthMgr(false, tokenId, curSession, logicalSessionId) != DM_OK) { + // 内部已完成错误日志打印 + return; + } - } else { + } else { + if (logicalSessionId != 0) { if (curSession->logicalSessionSet_.find(logicalSessionId) == curSession->logicalSessionSet_.end()) { - LOGE("OnBytesReceived, The logical session ID does not exist in the physical session, so the request is rejected."); + LOGE("OnBytesReceived, The logical session ID does not exist in the physical session, + so the request is rejected."); return; } tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; @@ -809,10 +828,6 @@ void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, TODO: 考虑authMgr_的切换是否有多线程问题 */ - if (curSession == nullptr) { - LOGE("InitAndRegisterAuthMgr, The physical link is not created."); - return; - } if (curSession->version_ == "" && (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE || msgType == MSG_TYPE_RESP_ACL_NEGOTIATE)) { // IsMessageOldVersion内部会对session版本进行赋值,并解除对应物理会话信号量 @@ -840,7 +855,8 @@ void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, // 然后新协议的超时机制会再次停止softbus std::string endMessage = CreateTerminateMessage(); (void)softbusConnector_->GetSoftbusSession()->SendData(sessionId, endMessage); - softbusConnector_->GetSoftbusSession()->OnSessionClosed(sessionId); + // 关闭新协议会话 + CleanSessionMapByLogicalSessionId(logicalSessionId); ret = authMgr->BindTarget(pkgName, peerTargetId, bindParam, sessionId, 0); if (ret != DM_OK) { @@ -1379,11 +1395,6 @@ int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const P logicalSessionId2TokenIdMap_[logicalSessionId] = tokenId; logicalSessionId2SessionIdMap_[logicalSessionId] = sessionId; - if (curSession->version_ != "" && !CompareVersion(curSession->version_, DM_VERSION_5_0_OLD_MAX)) { - softbusConnector_->GetSoftbusSession()->CloseAuthSession(sessionId); - } - - // 新老协议调用 auto authMgr = GetAuthMgr(); if (authMgr != nullptr) { return authMgr->BindTarget(pkgName, targetId, bindParam, sessionId, logicalSessionId); -- Gitee From af2c87958f9806d9a5e49f22af7642cbaafc4645 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Fri, 28 Mar 2025 16:53:26 +0800 Subject: [PATCH 323/382] =?UTF-8?q?BUGFIX:=E4=BF=AE=E5=A4=8DOnAuthResult?= =?UTF-8?q?=E9=94=99=E8=AF=AF?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/implementation/src/authentication_v2/dm_auth_state.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 77b83b02e..636319877 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -232,7 +232,7 @@ void DmAuthState::SyncAclList(std::shared_ptr context, void DmAuthState::SourceFinish(std::shared_ptr context) { - context->listener->OnAuthResult(context->processInfo, context->peerTargetId.deviceId, context->accessee.token, + context->listener->OnAuthResult(context->processInfo, context->peerTargetId.deviceId, context->accessee.tokenIdHash, context->state, context->reason); context->listener->OnBindResult(context->processInfo, context->peerTargetId, context->reply, context->state, GenerateBindResultContent(context->accessee)); -- Gitee From 9c69f4ac2e1290cb130f3944fdc4b100455a1997 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Mar 2025 18:07:18 +0800 Subject: [PATCH 324/382] style --- .../include/authentication_v2/dm_auth_state.h | 32 +++++++++---------- .../src/authentication_v2/auth_manager.cpp | 24 +++++++------- .../auth_stages/auth_acl.cpp | 6 ++-- .../auth_stages/auth_negotiate.cpp | 3 +- .../dm_auth_message_processor.cpp | 4 +-- .../src/authentication_v2/dm_auth_state.cpp | 4 +-- 6 files changed, 37 insertions(+), 36 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 0d8480e7d..84228eb7c 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -344,34 +344,34 @@ private: // AuthSinkDataSyncState // 收到180同步报文,发送190报文 class AuthSinkDataSyncState : public DmAuthState { - public: - virtual ~AuthSinkDataSyncState() {}; - DmAuthStateType GetStateType() override; - int32_t Action(std::shared_ptr context) override; +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; +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; +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; +public: + virtual ~AuthSrcFinishState() {}; + DmAuthStateType GetStateType() override; + int32_t Action(std::shared_ptr context) override; }; } // namespace DistributedHardware } // namespace OHOS diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index e2c20974d..e3c34c187 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -418,7 +418,8 @@ int32_t AuthManager::CheckAuthParamVaild(const std::string &sessionName, int32_t if (!IsAuthTypeSupported(authType)) { LOGE("AuthManager::CheckAuthParamVaild authType %{public}d not support.", authType); - context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", STATUS_DM_AUTH_DEFAULT, + context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", + STATUS_DM_AUTH_DEFAULT, ERR_DM_UNSUPPORTED_AUTH_TYPE); context_->listener->OnBindResult(context_->processInfo, context_->peerTargetId, ERR_DM_UNSUPPORTED_AUTH_TYPE, STATUS_DM_AUTH_DEFAULT, ""); @@ -434,7 +435,8 @@ int32_t AuthManager::CheckAuthParamVaild(const std::string &sessionName, int32_t return ERR_DM_INPUT_PARA_INVALID; } - if (DmAuthState::IsImportAuthCodeCompatibility(static_cast(authType)) && (!IsAuthCodeReady(sessionName))) { + if (DmAuthState::IsImportAuthCodeCompatibility(static_cast(authType)) && + (!IsAuthCodeReady(sessionName))) { LOGE("Auth code not exist."); context_->listener->OnAuthResult(context_->processInfo, context_->peerTargetId.deviceId, "", STATUS_DM_AUTH_DEFAULT, ERR_DM_INPUT_PARA_INVALID); @@ -585,7 +587,7 @@ void AuthManager::GetAuthParam(const std::string &sessionName, int32_t authType, uint32_t tokenId = 0; MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, context_->accesser.userId); context_->accesser.tokenId = static_cast(tokenId); - if (realPkgName != sessionName) { + if (realPkgName != sessionName) { int64_t tmpTokenId = 0; GetTokenIdByBundleName(context_->accesser.userId, realPkgName, tmpTokenId); context_->accesser.tokenId = static_cast(tmpTokenId); @@ -616,13 +618,9 @@ void AuthManager::InitAuthState(const std::string &sessionName, int32_t authType context_->authPtr = iter->second; } - // if (authType > AUTH_TYPE_IMPORT_AUTH_CODE || authType < AUTH_TYPE_PIN) { - // LOGE("AuthManager::InitAuthState invalid authType"); - // return; - // } - context_->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), - DmAuthState::GetTaskTimeout(context_, AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), [this] (std::string name) { + DmAuthState::GetTaskTimeout(context_, AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), + [this] (std::string name) { DmAuthState::HandleAuthenticateTimeout(context_, name); }); GetAuthParam(sessionName, authType, deviceId, extra); @@ -710,8 +708,8 @@ int32_t AuthManager::BindTarget(const std::string &sessionName, const PeerTarget } AuthSinkManager::AuthSinkManager(std::shared_ptr softbusConnector, - std::shared_ptr listener, - std::shared_ptr hiChainAuthConnector) + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector) : AuthManager(softbusConnector, listener, hiChainAuthConnector) { context_->direction = DM_AUTH_SINK; @@ -825,8 +823,8 @@ int32_t AuthSinkManager::OnUserOperation(int32_t action, const std::string ¶ } AuthSrcManager::AuthSrcManager(std::shared_ptr softbusConnector, - std::shared_ptr listener, - std::shared_ptr hiChainAuthConnector) + std::shared_ptr listener, + std::shared_ptr hiChainAuthConnector) : AuthManager(softbusConnector, listener, hiChainAuthConnector) { context_->direction = DM_AUTH_SOURCE; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 6e0ac977f..3d87ead3f 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -118,7 +118,8 @@ int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) context->reason = ERR_DM_QUADRUPLE_NOT_SAME; context->reply = ERR_DM_QUADRUPLE_NOT_SAME; context->state = static_cast(GetStateType()); - context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_REQ_FINISH, context); // source异常时,source不结束,发送200给sink,等sink回201 + // source异常时,source不结束,发送200给sink,等sink回201 + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_REQ_FINISH, context); return DM_OK; } // 查询sink端acl @@ -155,7 +156,8 @@ int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) if (!context->accesser.isOnline) { char udidHashTmp[DM_MAX_DEVICE_ID_LEN] = {0}; if (Crypto::GetUdidHash(context->accessee.deviceId, reinterpret_cast(udidHashTmp)) != DM_OK) { - LOGE("AuthSrcDataSyncState joinLnn get udidhash by udid: %{public}s failed", context->accessee.deviceId.c_str()); + LOGE("AuthSrcDataSyncState joinLnn get udidhash by udid: %{public}s failed", + context->accessee.deviceId.c_str()); return ERR_DM_FAILED; } std::string peerUdidHash = std::string(udidHashTmp); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index b45509cb6..5afac8960 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -180,7 +180,8 @@ int32_t AuthSinkNegotiateStateMachine::Action(std::shared_ptr con if (context->timer != nullptr) { context->timer->StartTimer(std::string(AUTHENTICATE_TIMEOUT_TASK), DmAuthState::GetTaskTimeout(context, AUTHENTICATE_TIMEOUT_TASK, AUTHENTICATE_TIMEOUT), - [this, context] (std::string name) { DmAuthState::HandleAuthenticateTimeout(context, name); + [this, context] (std::string name) { + DmAuthState::HandleAuthenticateTimeout(context, name); }); } diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 88623713c..6fdaa29e8 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1376,12 +1376,12 @@ int32_t DmAuthMessageProcessor::GetAclListStr(std::shared_ptr &co uint8_t accesserHash[DM_HASH_LEN] = {0}; std::string accesserStr = AccesserToStr(item); Crypto::DmGenerateStrHash(accesserStr.data(), accesserStr.size(), accesserHash, DM_HASH_LEN, 0); - accceserStrList.push_back(reinterpret_cast(accesserHash)); + accceserStrList.push_back(reinterpret_cast(accesserHash)); uint8_t accesseeHash[DM_HASH_LEN] = {0}; std::string accesseeStr = AccesseeToStr(item); Crypto::DmGenerateStrHash(accesseeStr.data(), accesseeStr.size(), accesseeHash, DM_HASH_LEN, 0); - accceseeStrList.push_back(reinterpret_cast(accesseeHash)); + accceseeStrList.push_back(reinterpret_cast(accesseeHash)); } } if (accceserStrList.empty() || accceseeStrList.empty()) { diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 636319877..2a26296b4 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -233,9 +233,9 @@ void DmAuthState::SyncAclList(std::shared_ptr context, void DmAuthState::SourceFinish(std::shared_ptr context) { context->listener->OnAuthResult(context->processInfo, context->peerTargetId.deviceId, context->accessee.tokenIdHash, - context->state, context->reason); + context->state, context->reason); context->listener->OnBindResult(context->processInfo, context->peerTargetId, context->reply, - context->state, GenerateBindResultContent(context->accessee)); + context->state, GenerateBindResultContent(context->accessee)); context->isFinished = true; if (context->reason != DM_OK) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); -- Gitee From 87bc3ff1bc16448e4f479d6361eac590bcf8a853 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Mar 2025 19:56:17 +0800 Subject: [PATCH 325/382] fix: pin from db --- .../implementation/include/authentication_v2/dm_auth_context.h | 1 + .../src/authentication_v2/auth_stages/auth_confirm.cpp | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index f24fbbc9c..84c9c59e2 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -161,6 +161,7 @@ struct DmAuthContext { uint32_t currentAuthTypeIdx{0}; int32_t inputPinAuthFailTimes{0}; // Number of failed PIN authentication attempts, exceeding 3 results in failure int32_t pinCode{INVALID_PINCODE}; + bool isPinCodeFromDb{false}; // Link delay release time, does not automatically disconnect after // authorization (used for specific business needs), reserved field int32_t connDelayCloseTime; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 92991d89b..dc495be39 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -266,6 +266,7 @@ void AuthSinkConfirmState::ReadServiceInfo(std::shared_ptr contex if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { std::string pinCode = srvInfo.GetPinCode(); // read pincode context->pinCode = std::stoi(pinCode); + context->isPinCodeFromDb = true; } if (context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { // no authorization box int32_t authResult = srvInfo.GetAuthType(); // read authResult @@ -298,7 +299,7 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) ReadServiceInfo(context); bool authTypeCheckOk = false; if (DmAuthState::IsImportAuthCodeCompatibility(context->authType) && - IsAuthCodeReady(context) && + (context->isPinCodeFromDb || IsAuthCodeReady(context)) && context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { /* The value of authresult may be the default value of temporary trust, or the value of authresult may be set by the service. */ -- Gitee From af16a8c2ff0e933a5359d0681fc713dff6b38bdd Mon Sep 17 00:00:00 2001 From: ZHANGHE24 Date: Fri, 28 Mar 2025 20:06:28 +0800 Subject: [PATCH 326/382] fix: fix bug --- services/implementation/src/device_manager_service_impl.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 13254012f..3594b5435 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -807,8 +807,7 @@ void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, } else { if (logicalSessionId != 0) { if (curSession->logicalSessionSet_.find(logicalSessionId) == curSession->logicalSessionSet_.end()) { - LOGE("OnBytesReceived, The logical session ID does not exist in the physical session, - so the request is rejected."); + LOGE("OnBytesReceived, The logical session ID does not exist in the physical session, so the request is rejected."); return; } tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; -- Gitee From f816aacf1e91ede50abf473bf3767aa2a701153f Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Fri, 28 Mar 2025 20:22:17 +0800 Subject: [PATCH 327/382] =?UTF-8?q?fix:=20=E5=A4=84=E7=90=86=E5=87=AD?= =?UTF-8?q?=E6=8D=AE=E9=80=BB=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication/auth_message_processor.h | 1 - .../include/authentication_v2/auth_manager.h | 1 + .../authentication_v2/dm_auth_context.h | 2 +- .../authentication_v2/dm_auth_manager_base.h | 1 + .../include/authentication_v2/dm_auth_state.h | 4 +- .../authentication/auth_message_processor.cpp | 1 - .../src/authentication_v2/auth_manager.cpp | 59 ++++++------ .../auth_stages/auth_confirm.cpp | 41 ++++++--- .../auth_stages/auth_credential.cpp | 2 + .../auth_stages/auth_negotiate.cpp | 4 +- .../dm_auth_manager_base.cpp | 9 +- .../dm_auth_message_processor.cpp | 4 - .../src/authentication_v2/dm_auth_state.cpp | 91 ++++++++++++++----- 13 files changed, 138 insertions(+), 82 deletions(-) diff --git a/services/implementation/include/authentication/auth_message_processor.h b/services/implementation/include/authentication/auth_message_processor.h index e4b32e02e..2c34222d5 100644 --- a/services/implementation/include/authentication/auth_message_processor.h +++ b/services/implementation/include/authentication/auth_message_processor.h @@ -55,7 +55,6 @@ extern const char* OLD_VERSION_ACCOUNT; extern const char* TAG_HAVE_CREDENTIAL; extern const char* TAG_PUBLICKEY; extern const char* TAG_SESSIONKEY; -extern const char* TAG_LOCAL_USERID; extern const char* TAG_BIND_TYPE_SIZE; extern const char* TAG_ISONLINE; extern const char* TAG_AUTHED; diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 3cc498269..6bc297f9c 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -131,6 +131,7 @@ private: int32_t ParseAuthType(const std::map &bindParam, int32_t &authType); void ParseHmlInfoInJsonObject(const JsonObject &jsonObject); void ParseJsonObject(const JsonObject &jsonObject); + void GetAuthIds(std::string realPkgName, const std::string &sessionName, 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); diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 84c9c59e2..1d0785271 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -122,7 +122,7 @@ struct DmAccess { 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::vector bindType; // such as DM_AUTH_CREDENTIAL_ACCOUNT_RELATED 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 diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h b/services/implementation/include/authentication_v2/dm_auth_manager_base.h index c935e0c5d..541ffa9ce 100644 --- a/services/implementation/include/authentication_v2/dm_auth_manager_base.h +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h @@ -50,6 +50,7 @@ extern const char* TAG_BIND_LEVEL; extern const char* TAG_REPLY; extern const char* TAG_APP_THUMBNAIL2; // Naming Add 2 to resolve conflicts with TAG_APP_THUMBNAIL extern const char* TAG_AUTH_FINISH; +extern const char* TAG_LOCAL_USERID; extern const char* APP_OPERATION_KEY; extern const char* TARGET_PKG_NAME_KEY; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 84228eb7c..e08ac3426 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -75,8 +75,10 @@ enum DmAuthCredentialSubject : uint8_t { // 凭据与账号关联 enum DmAuthCredentialAccountRelation : uint8_t { + DM_AUTH_CREDENTIAL_INVALID = 0, // 无效 DM_AUTH_CREDENTIAL_ACCOUNT_RELATED = 1, // 账号相关 - DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED, // 账号无关 + DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED = 2, // 账号无关 + DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS = 3, // 分享 }; // 秘钥类型 diff --git a/services/implementation/src/authentication/auth_message_processor.cpp b/services/implementation/src/authentication/auth_message_processor.cpp index 1ec99969e..fc130c5dd 100644 --- a/services/implementation/src/authentication/auth_message_processor.cpp +++ b/services/implementation/src/authentication/auth_message_processor.cpp @@ -50,7 +50,6 @@ const char* OLD_VERSION_ACCOUNT = "oldVersionAccount"; const char* TAG_HAVE_CREDENTIAL = "haveCredential"; const char* TAG_PUBLICKEY = "publicKey"; const char* TAG_SESSIONKEY = "sessionKey"; -const char* TAG_LOCAL_USERID = "localUserId"; const char* TAG_BIND_TYPE_SIZE = "bindTypeSize"; const char* TAG_ISONLINE = "isOnline"; const char* TAG_AUTHED = "authed"; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index e3c34c187..6c84d1206 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -461,8 +461,11 @@ void AuthManager::ParseHmlInfoInJsonObject(const JsonObject &jsonObject) context_->hmlEnable160M = jsonObject[PARAM_KEY_HML_ENABLE_160M].Get(); LOGI("hmlEnable160M %{public}d", context_->hmlEnable160M); } - if (jsonObject[PARAM_KEY_HML_ACTIONID].IsNumberInteger()) { - context_->hmlActionId = jsonObject[PARAM_KEY_HML_ACTIONID].Get(); + if (jsonObject[PARAM_KEY_HML_ACTIONID].IsString()) { + std::string actionIdStr = jsonObject[PARAM_KEY_HML_ACTIONID].Get(); + if (IsNumberString(actionIdStr)) { + context_->hmlActionId = std::atoi(actionIdStr.c_str()); + } if (context_->hmlActionId <= 0) { context_->hmlActionId = 0; } @@ -506,31 +509,20 @@ void AuthManager::ParseJsonObject(const JsonObject &jsonObject) } // 填充context_->accesser - if (jsonObject[TAG_BIND_LEVEL].IsNumberInteger()) { - context_->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].Get(); - } context_->accesser.bundleName = GetBundleName(jsonObject); + context_->accessee.bundleName = context_->accesser.bundleName; // 填充context_accessee if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString()) { context_->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); - if (context_->accessee.bundleName == "") { - context_->accessee.bundleName = context_->sessionName; - } - LOGI("ParseJsonObject accessee bundleName = %{public}s", context_->accessee.bundleName.c_str()); - } else { - context_->accessee.bundleName = context_->sessionName; - } - if (jsonObject[TAG_ACCESSEE_USER_ID].IsNumberInteger()) { - context_->accessee.userId = jsonObject[TAG_ACCESSEE_USER_ID].Get(); } if (jsonObject[TAG_PEER_DISPLAY_ID].IsNumberInteger()) { context_->accessee.displayId = jsonObject[TAG_PEER_DISPLAY_ID].Get(); } - return; } + int32_t AuthManager::GetBindLevel(int32_t bindLevel) { #ifdef DEVICE_MANAGER_COMMON_FLAG @@ -569,32 +561,46 @@ int32_t AuthManager::GetTokenIdByBundleName(int32_t userId, std::string &bundleN return ret; } -void AuthManager::GetAuthParam(const std::string &sessionName, int32_t authType, - const std::string &deviceId, const std::string &extra) +void AuthManager::GetAuthIds(std::string realPkgName, const std::string &sessionName, const JsonObject &jsonObject) { - LOGI("Get auth param with sessionName %{public}s and extra %{public}s.", sessionName.c_str(), extra.c_str()); + // Get deviceId char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localDeviceId); - std::string realPkgName = GetSubStr(sessionName, PICKER_PROXY_SPLIT, 1); - realPkgName = realPkgName.empty() ? sessionName : realPkgName; - context_->sessionName = sessionName; - context_->pkgLabel = GetBundleLable(sessionName); - context_->authType = (DmAuthType)authType; - context_->accesser.deviceName = context_->softbusConnector->GetLocalDeviceName(); - context_->accesser.deviceType = context_->softbusConnector->GetLocalDeviceTypeId(); context_->accesser.deviceId = localUdid; + + // Get userId and tokenId uint32_t tokenId = 0; MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, context_->accesser.userId); + if (!jsonObject.IsDiscarded() && jsonObject[TAG_LOCAL_USERID].IsNumberInteger()) { + context_->accesser.userId = jsonObject[TAG_LOCAL_USERID].Get(); + } context_->accesser.tokenId = static_cast(tokenId); if (realPkgName != sessionName) { int64_t tmpTokenId = 0; GetTokenIdByBundleName(context_->accesser.userId, realPkgName, tmpTokenId); context_->accesser.tokenId = static_cast(tmpTokenId); } + + // Get accountId context_->accesser.accountId = MultipleUserConnector::GetOhosAccountIdByUserId(context_->accesser.userId); + + return; +} + +void AuthManager::GetAuthParam(const std::string &sessionName, int32_t authType, + const std::string &deviceId, const std::string &extra) +{ + LOGI("Get auth param with sessionName %{public}s and extra %{public}s.", sessionName.c_str(), extra.c_str()); + + std::string realPkgName = GetSubStr(sessionName, PICKER_PROXY_SPLIT, 1); + realPkgName = realPkgName.empty() ? sessionName : realPkgName; + context_->sessionName = sessionName; + context_->pkgLabel = GetBundleLable(sessionName); + context_->authType = (DmAuthType)authType; + context_->accesser.deviceName = context_->softbusConnector->GetLocalDeviceName(); + context_->accesser.deviceType = context_->softbusConnector->GetLocalDeviceTypeId(); context_->accesser.isOnline = false; - context_->accesser.isAuthed = !context_->accesser.bindType.empty(); context_->accesser.bindLevel = INVALIED_TYPE; context_->accessee.deviceId = deviceId; @@ -606,6 +612,7 @@ void AuthManager::GetAuthParam(const std::string &sessionName, int32_t authType, } ParseJsonObject(jsonObject); + GetAuthIds(realPkgName, sessionName, jsonObject); context_->accesser.token = std::to_string(GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN)); context_->accesser.bindLevel = this->GetBindLevel(context_->accesser.bindLevel); } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index dc495be39..dd81669d9 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -65,18 +65,19 @@ void AuthSrcConfirmState::NegotiateCredential(std::shared_ptr con context->accesser.bindLevel = APP; // FA-FA } if (!intersection.empty() && - (intersection.front() == DM_IDENTICAL_ACCOUNT || intersection.front() == DM_ACROSS_ACCOUNT)) { + (intersection.front() == DM_AUTH_CREDENTIAL_ACCOUNT_RELATED || + intersection.front() == DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS)) { context->accesser.bindLevel = DEVICE; // Exceptions: account related is DEVICE } context->accessee.bindLevel = context->accesser.bindLevel; // TODO: 添加配件判断 + context->accesser.credentialTypeLists.clear(); if (!intersection.empty()) { // 如果交集不为空,将第一个值赋值给 context->accesser.credTypeList // TODO: 确认优先级是否正确 JsonObject credInfo(context->accesser.credentialInfos[intersection.front()]); if (credInfo.Contains(TAG_CRED_ID) && credInfo[TAG_CRED_ID].IsString()) { - context->accesser.credentialTypeLists.clear(); context->accesser.credentialTypeLists.push_back(intersection.front()); context->needAgreeCredential = false; context->accessee.transmitCredentialId = credInfo[TAG_CRED_ID].Get(); @@ -88,15 +89,27 @@ void AuthSrcConfirmState::NegotiateCredential(std::shared_ptr con void AuthSrcConfirmState::NegotiateAcl(std::shared_ptr context) { - if (!context->accesser.isAuthed || context->accesser.credentialTypeLists.size() != 1) { + context->accesser.isAuthed = false; + if (context->accesser.credentialTypeLists.size() != 1) { return; } + int32_t credType = context->accesser.credentialTypeLists.front(); + // identical and across credential, online directly + if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_RELATED || credType == DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS) { + context->accesser.isAuthed = true; + return; + } + + if (context->accesser.aclProfiles.find(credType) == context->accesser.aclProfiles.end()) { + return; + } DistributedDeviceProfile::Accesser accesser = context->accesser.aclProfiles[credType].GetAccesser(); DistributedDeviceProfile::Accessee accessee = context->accesser.aclProfiles[credType].GetAccessee(); context->accesser.transmitSessionKeyId = accesser.GetAccesserSessionKeyId(); context->accessee.transmitSessionKeyId = accessee.GetAccesseeSessionKeyId(); + context->accesser.isAuthed = true; return; } @@ -123,9 +136,7 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) NegotiateAcl(context); // not pin import, and have acl - if ((!DmAuthState::IsImportAuthCodeCompatibility(context->authType)) && - context->accesser.transmitSessionKeyId != 0 && - context->accessee.transmitSessionKeyId != 0) { + if ((!DmAuthState::IsImportAuthCodeCompatibility(context->authType)) && context->accesser.isAuthed) { // finished, goto join lnn context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; @@ -184,7 +195,7 @@ void AuthSinkConfirmState::NegotiateCredential(std::shared_ptr co } else { context->accessee.bindLevel = APP; // FA-FA } - if (credType == DM_IDENTICAL_ACCOUNT || credType == DM_ACROSS_ACCOUNT) { + if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_RELATED || credType == DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS) { context->accessee.bindLevel = DEVICE; // Exceptions: account related is DEVICE } context->accesser.bindLevel = context->accessee.bindLevel; @@ -207,17 +218,21 @@ void AuthSinkConfirmState::NegotiateCredential(std::shared_ptr co void AuthSinkConfirmState::NegotiateAcl(std::shared_ptr context) { - if (!context->accesser.isAuthed || !context->accessee.isAuthed || - context->accessee.credentialTypeLists.size() != 1) { + context->accessee.isAuthed = false; + if (!context->accesser.isAuthed || context->accessee.credentialTypeLists.size() != 1) { return; } int32_t credType = context->accessee.credentialTypeLists.front(); + if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_RELATED || credType == DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS) { + context->accessee.isAuthed = true; + return; + } if (context->accessee.aclProfiles.find(credType) == context->accessee.aclProfiles.end()) { - context->accessee.isAuthed = false; return; } + context->accessee.isAuthed = true; DistributedDeviceProfile::Accesser accesser = context->accesser.aclProfiles[credType].GetAccesser(); DistributedDeviceProfile::Accessee accessee = context->accesser.aclProfiles[credType].GetAccessee(); context->accesser.transmitSessionKeyId = accesser.GetAccesserSessionKeyId(); @@ -308,9 +323,9 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) && context->authBoxType == OHOS::DistributedDeviceProfile::NUM_1) { auto& credTypeLists = context->accesser.credentialTypeLists; - if ((!credTypeLists.empty()) && - (credTypeLists[0] == DM_IDENTICAL_ACCOUNT || credTypeLists[0] == DM_ACROSS_ACCOUNT)) { - // have DM_IDENTICAL_ACCOUNT or DM_ACROSS_ACCOUNT + if ((!credTypeLists.empty()) && (credTypeLists[0] == DM_AUTH_CREDENTIAL_ACCOUNT_RELATED || + credTypeLists[0] == DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS)) { + // have DM_AUTH_CREDENTIAL_ACCOUNT_RELATED or DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS context->authResult = UiAction::USER_OPERATION_TYPE_ALLOW_AUTH_ALWAYS; context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_RESP_USER_CONFIRM, context); return DM_OK; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index e0298fe30..b70127650 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -339,6 +339,8 @@ int32_t AuthCredentialAgreeState::AgreeCredential(DmAuthScope authorizedScope, authContext->accesser.userId : authContext->accessee.userId; std::string selfCredId = authContext->GetCredentialId(DM_AUTH_LOCAL_SIDE, authorizedScope); std::string credId; + LOGI("AuthCredentialAgreeState::AgreeCredential agree with accountId %{public}d and param %{public}s.", + osAccountId, authParamsString.c_str()); int32_t ret = authContext->hiChainAuthConnector->AgreeCredential(osAccountId, selfCredId, authParamsString, credId); if (ret != DM_OK) { diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index 5afac8960..aea99f65f 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -144,9 +144,9 @@ int32_t AuthSinkNegotiateStateMachine::RespQueryAcceseeIds(std::shared_ptraccessee.bindLevel = DmRole::DM_ROLE_SA; LOGI("RespQueryTokenId: SA-SA"); - return DM_OK; + } else { + context->accessee.bindLevel = DmRole::DM_ROLE_FA; } - context->accessee.bindLevel = DmRole::DM_ROLE_FA; context->accessee.bundleName = tmpBundleName; context->accessee.tokenId = static_cast(tokenId); context->accessee.tokenIdHash = Crypto::Sha256(std::to_string(context->accessee.tokenId)); diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp index 5a2ac5cf7..6d7124769 100644 --- a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp @@ -49,6 +49,7 @@ const char* TAG_BIND_LEVEL = "bindLevel"; const char* TAG_REPLY = "REPLY"; const char* TAG_APP_THUMBNAIL2 = "appThumbnail"; // Naming Add 2 to resolve conflicts with TAG_APP_THUMBNAIL const char* TAG_AUTH_FINISH = "isFinish"; +const char* TAG_LOCAL_USERID = "localUserId"; const char* APP_OPERATION_KEY = "appOperation"; const char* TARGET_PKG_NAME_KEY = "targetPkgName"; @@ -387,14 +388,6 @@ int32_t AuthManagerBase::DmGetUserId(int32_t displayId, int32_t targetUserId) return -1; } - if (targetUserId != 0) { - if (std::find(userIds.begin(), userIds.end(), targetUserId) == userIds.end()) { - LOGE("RespQueryTokenId: userId not in foreground users"); - return -1; - } - return targetUserId; - } - if (displayId != -1) { ret = AccountSA::OsAccountManager::GetForegroundOsAccountLocalId(displayId, userId); if (ret != DM_OK) { diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 6fdaa29e8..ca765ea22 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1013,10 +1013,6 @@ int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const JsonObject &j context->isOnline = jsonObject[TAG_IS_ONLINE].Get(); } - if (jsonObject[TAG_IS_AUTHED].IsBoolean()) { - context->accessee.isAuthed = jsonObject[TAG_IS_AUTHED].Get(); - } - if (jsonObject[TAG_CERT_INFO].IsString()) { context->accessee.credentialTypeLists = stringToVectorInt32(jsonObject[TAG_CERT_INFO].Get()); } diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 2a26296b4..3aa6e7c14 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -14,12 +14,13 @@ */ #include "access_control_profile.h" +#include "hichain_auth_connector.h" +#include "multiple_user_connector.h" #include "dm_crypto.h" #include "dm_auth_state.h" #include "dm_auth_context.h" #include "dm_auth_manager_base.h" #include "dm_auth_state_machine.h" -#include "multiple_user_connector.h" #include "dm_crypto.h" #if defined(SUPPORT_SCREENLOCK) #include "screenlock_manager.h" @@ -46,14 +47,21 @@ enum { SCOPE_APP, }; +enum DM_SUBJECT { + SUBJECT_PRIMARY = 1, + SUBJECT_SECONDARY, +}; + // Security device auth credential query related definitions, keep consistent with device_auth.h const char* const FILED_DEVICE_ID = "deviceId"; const char* const FILED_USER_ID = "userId"; const char* const FILED_DEVICE_ID_HASH = "deviceIdHash"; const char* const FILED_PEER_USER_SPACE_ID = "peerUserSpaceId"; +const char* const FILED_CRED_ID = "credId"; const char* const FILED_CRED_TYPE = "credType"; const char* const FILED_AUTHORIZED_SCOPE = "authorizedScope"; const char* const FILED_AUTHORIZED_APP_LIST = "authorizedAppList"; +const char* const FILED_SUBJECT = "subject"; bool HaveSameTokenId(std::shared_ptr context, const std::vector &tokenList) { @@ -73,28 +81,42 @@ bool HaveSameTokenId(std::shared_ptr context, const std::vector context, const JsonItemObject &credInfo) { - if (!credInfo[FILED_CRED_TYPE].IsNumberInteger() || !credInfo[FILED_AUTHORIZED_SCOPE].IsNumber()) { - return DM_INVALIED_BINDTYPE; + if (!credInfo[FILED_CRED_TYPE].IsNumberInteger() || !credInfo[FILED_AUTHORIZED_SCOPE].IsNumberInteger() || + !credInfo[FILED_SUBJECT].IsNumberInteger()) { + LOGE("credType, authorizedScope or subject invalid."); + return DM_AUTH_CREDENTIAL_INVALID; } int32_t credType = credInfo[FILED_CRED_TYPE].Get(); int32_t authorizedScope = credInfo[FILED_AUTHORIZED_SCOPE].Get(); - if (authorizedScope == SCOPE_USER) { - if (credType == ACCOUNT_RELATED) { - return DM_IDENTICAL_ACCOUNT; - } else if (credType == ACCOUNT_ACROSS) { - return DM_ACROSS_ACCOUNT; + int32_t subject = credInfo[FILED_SUBJECT].Get(); + + if (context->accesser.accountIdHash == context->accessee.accountIdHash) { + // identicail credential + if (credType == ACCOUNT_RELATED && authorizedScope == SCOPE_USER) { + return DM_AUTH_CREDENTIAL_ACCOUNT_RELATED; + } + } else if (context->accesser.accountIdHash != context->accessee.accountIdHash && + context->accesser.accountId != "ohosAnonymousUid" && context->accessee.accountId != "ohosAnonymousUid") { + // share credential + if (credType == ACCOUNT_ACROSS && authorizedScope == SCOPE_USER && + context->direction == DM_AUTH_SOURCE && subject == SUBJECT_PRIMARY) { + return DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS; + } + if (credType == ACCOUNT_ACROSS && authorizedScope == SCOPE_USER && + context->direction == DM_AUTH_SINK && subject == SUBJECT_SECONDARY) { + return DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS; } } + // point_to_point identical std::vector appList; credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList); if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_APP && HaveSameTokenId(context, appList)) { - return DM_POINT_TO_POINT; + return DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; } - // 未确定凭据类型 - return DM_INVALIED_BINDTYPE; + return DM_AUTH_CREDENTIAL_INVALID; } int32_t DmQueryCredential(std::shared_ptr context, JsonObject &queryResult) @@ -103,31 +125,37 @@ int32_t DmQueryCredential(std::shared_ptr context, JsonObject &qu uint32_t credType; JsonObject queryParams; - DmAccess access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; - DmAccess remoteAccess = context->direction == DM_AUTH_SOURCE ? context->accessee : context->accesser; + DmAccess &access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; + DmAccess &remoteAccess = context->direction == DM_AUTH_SOURCE ? context->accessee : context->accesser; - queryParams[FILED_DEVICE_ID_HASH] = remoteAccess.deviceId; - queryParams[FILED_USER_ID] = access.userId; - queryParams[FILED_PEER_USER_SPACE_ID] = remoteAccess.userId; + // queryParams[FILED_DEVICE_ID_HASH] = remoteAccess.deviceIdHash; + // queryParams[FILED_USER_ID] = access.userId; // IS中userId为string + // queryParams[FILED_PEER_USER_SPACE_ID] = remoteAccess.userId; ret = context->hiChainAuthConnector->QueryCredentialInfo(access.userId, queryParams, queryResult); if (ret != DM_OK) { LOGE("DmQueryCredential fail to query credential id list."); return ret; } // TODO: delete - LOGI("DmQueryCredential for userId %{public}d and queryParams %{public}s " - "query credentialInfo: %{public}s", access.userId, queryParams.Dump().c_str(), - queryResult.Dump().c_str()); + LOGI("DmQueryCredential for userId %{public}d and queryParams %{public}s", + access.userId, queryParams.Dump().c_str()); std::vector credTypeList; for (auto& item : queryResult.Items()) { + // 过滤掉非对端deviceIdHash的结果 + // if (Crypto::Sha256(item[FILED_DEVICE_ID]) != remoteAccess.deviceIdHash) { + // continue; + // } + // 确认凭据类型 + LOGI("DmQueryCredential credInfo: %{public}s", item.Dump().c_str()); credType = GetCredentialType(context, item); - if (credType == DM_INVALIED_BINDTYPE) { + if (credType == DM_AUTH_CREDENTIAL_INVALID) { continue; } item[FILED_CRED_TYPE] = credType; + LOGI("DmQueryCredential useful credType %{public}d", credType); // TODO: 确认credInfo中是否有id信息 access.credentialInfos[credType] = item.Dump(); // duplicate acl and credType is not allowed @@ -311,7 +339,7 @@ int32_t DmAuthState::GetAuthCredentialInfo(std::shared_ptr contex } // 2. Retrieve all ACLs - DmAccess access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; + DmAccess &access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; std::vector profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfile(); LOGI("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo success to get %{public}ld acls", profiles.size()); @@ -323,7 +351,7 @@ int32_t DmAuthState::GetAuthCredentialInfo(std::shared_ptr contex // Ensure credentials match with ACL std::string credId = context->direction == DM_AUTH_SOURCE ? std::to_string(accesser.GetAccesserCredentialId()) : std::to_string(accessee.GetAccesseeCredentialId()); - LOGI("Got acl: credId - %{public}d ", accessee.GetAccesseeCredentialId()); // TODO: delete + LOGI("Got acl: credId - %{public}s", credId.c_str()); // TODO: delete if (!queryResult.Contains(credId) || item.GetStatus() != ACTIVE) { continue; } @@ -339,9 +367,9 @@ int32_t DmAuthState::GetAuthCredentialInfo(std::shared_ptr contex LOGI("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo success to get acl %{public}s", item.dump().c_str()); // Confirm if there is a trusted relationship uint32_t credType = queryResult[credId][FILED_CRED_TYPE].Get(); - if (credType == DM_IDENTICAL_ACCOUNT || credType == DM_ACROSS_ACCOUNT) { + if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_RELATED || credType == DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS) { isAclMatched = AclCompareTwoIds(context, accesser, accessee); - } else if (credType == DM_POINT_TO_POINT) { + } else if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED) { isAclMatched = AclCompareFourIds(context, accesser, accessee); } @@ -351,6 +379,19 @@ int32_t DmAuthState::GetAuthCredentialInfo(std::shared_ptr contex } } + // 有凭据无可信关系时,作无凭据处理,删除点对点凭据 + if (access.aclProfiles.empty() && + access.credentialInfos.find(DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED) != access.credentialInfos.end()) { + JsonObject credInfo(access.credentialInfos[DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED]); + (void)context->hiChainAuthConnector->DeleteCredential(access.userId, + credInfo[FILED_CRED_ID].Get()); + + // 列表中删除对应credType + access.credentialTypeLists.erase(std::remove(access.credentialTypeLists.begin(), + access.credentialTypeLists.end(), DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED), access.credentialTypeLists.end()); + access.credentialInfos.erase(DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED); + } + return DM_OK; } @@ -384,7 +425,7 @@ bool DmAuthState::NeedPinAuth(std::shared_ptr context) std::vector credTypeLists = context->accesser.credentialTypeLists; if (credTypeLists.size() == 1) { int32_t credType = credTypeLists.front(); - if (credType == DM_IDENTICAL_ACCOUNT || credType == DM_ACROSS_ACCOUNT) { + if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_RELATED || credType == DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS) { return false; } } -- Gitee From 055ab9f112597026e74d1967541ebf2625fc952b Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Mar 2025 21:07:30 +0800 Subject: [PATCH 328/382] verify str pincode --- .../authentication_v2/dm_auth_context.h | 2 +- .../include/authentication_v2/dm_auth_state.h | 3 ++ .../src/authentication_v2/auth_manager.cpp | 1 - .../auth_stages/auth_confirm.cpp | 22 +++-------- .../auth_stages/auth_pin_auth.cpp | 39 +++++++++++++++++++ 5 files changed, 48 insertions(+), 19 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 1d0785271..20ab7f959 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -161,7 +161,7 @@ struct DmAuthContext { uint32_t currentAuthTypeIdx{0}; int32_t inputPinAuthFailTimes{0}; // Number of failed PIN authentication attempts, exceeding 3 results in failure int32_t pinCode{INVALID_PINCODE}; - bool isPinCodeFromDb{false}; + bool serviceInfoFound{false}; // Link delay release time, does not automatically disconnect after // authorization (used for specific business needs), reserved field int32_t connDelayCloseTime; diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index e08ac3426..61bb71a9a 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -137,6 +137,9 @@ private: class AuthSinkStatePinAuthComm { public: + static bool IsPinCodeValid(int32_t numpin); + static bool IsPinCodeValid(const std::string& strpin); + static bool IsAuthCodeReady(std::shared_ptr context); static void GeneratePincode(std::shared_ptr context); static int32_t ShowAuthInfoDialog(std::shared_ptr context); private: diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 6c84d1206..a7300e218 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -276,7 +276,6 @@ int32_t AuthManager::ImportAuthCode(const std::string &sessionName, const std::s } context_->importAuthCode = authCode; context_->importSessionName = sessionName; - context_->pinCode = std::atoi(authCode.c_str()); return DM_OK; } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index dd81669d9..00750d9bd 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -255,20 +255,6 @@ void AuthSinkConfirmState::MatchFallBackCandidateList( } } -bool AuthSinkConfirmState::IsAuthCodeReady(std::shared_ptr context) -{ - if (context->importAuthCode.empty() || context->importSessionName.empty()) { - LOGE("AuthSinkNegotiateStateMachine::IsAuthCodeReady, auth code not ready."); - return false; - } - if (context->sessionName != context->importSessionName) { - LOGE("AuthSinkNegotiateStateMachine::IsAuthCodeReady sessionName %{public}s not supported with " - "import sessionName %{public}s.", context->sessionName.c_str(), context->importSessionName.c_str()); - return false; - } - return true; -} - void AuthSinkConfirmState::ReadServiceInfo(std::shared_ptr context) { // query ServiceInfo by accessee.bundleName and authType from client @@ -277,11 +263,13 @@ void AuthSinkConfirmState::ReadServiceInfo(std::shared_ptr contex context->accessee.bundleName, context->authType, srvInfo); if (ret == OHOS::DistributedDeviceProfile::DP_SUCCESS) { // ServiceInfo found + context->serviceInfoFound = true; context->authBoxType = srvInfo.GetAuthBoxType(); // read authBoxType if (DmAuthState::IsImportAuthCodeCompatibility(context->authType)) { std::string pinCode = srvInfo.GetPinCode(); // read pincode - context->pinCode = std::stoi(pinCode); - context->isPinCodeFromDb = true; + if (AuthSinkStatePinAuthComm::IsPinCodeValid(pinCode)) { + context->pinCode = std::stoi(pinCode.c_str()); + } } if (context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { // no authorization box int32_t authResult = srvInfo.GetAuthType(); // read authResult @@ -314,7 +302,7 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) ReadServiceInfo(context); bool authTypeCheckOk = false; if (DmAuthState::IsImportAuthCodeCompatibility(context->authType) && - (context->isPinCodeFromDb || IsAuthCodeReady(context)) && + (context->serviceInfoFound || IsAuthCodeReady(context)) && context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { /* The value of authresult may be the default value of temporary trust, or the value of authresult may be set by the service. */ diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 0e3cdd77d..4338f4e59 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -82,6 +82,45 @@ void AuthSinkStatePinAuthComm::HandleSessionHeartbeat(std::shared_ptr MAX_PIN_CODE) { + return false; + } + return true; +} + +bool AuthSinkStatePinAuthComm::IsPinCodeValid(const std::string& strpin) +{ + if (strpin.empty()) { + return false; + } + for (size_t i = 0; i < strpin.length(); i++) { + if (!isdigit(strpin[i])) { + return false; + } + } + int32_t pinnum = std::atoi(strpin.c_str()); + return IsPinCodeValid(pinnum); +} + +bool AuthSinkStatePinAuthComm::IsAuthCodeReady(std::shared_ptr context) +{ + if (context->importAuthCode.empty() || context->importSessionName.empty()) { + LOGE("AuthSinkNegotiateStateMachine::IsAuthCodeReady, auth code not ready."); + return false; + } + if (context->sessionName != context->importSessionName) { + LOGE("AuthSinkNegotiateStateMachine::IsAuthCodeReady sessionName %{public}s not supported with " + "import sessionName %{public}s.", context->sessionName.c_str(), context->importSessionName.c_str()); + return false; + } + if (AuthSinkStatePinAuthComm::IsPinCodeValid(authCode)) { + context_->pinCode = std::stoi(authCode.c_str()); + } + return true; +} + void AuthSinkStatePinAuthComm::GeneratePincode(std::shared_ptr context) { context->pinCode = GenRandInt(MIN_PIN_CODE, MAX_PIN_CODE); -- Gitee From e1f2fe6df5c1f0618b6efd9bc01db60f3f00bb5b Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Mar 2025 21:10:34 +0800 Subject: [PATCH 329/382] erase dp pincode --- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 00750d9bd..c791a7c12 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -270,6 +270,8 @@ void AuthSinkConfirmState::ReadServiceInfo(std::shared_ptr contex if (AuthSinkStatePinAuthComm::IsPinCodeValid(pinCode)) { context->pinCode = std::stoi(pinCode.c_str()); } + srvInfo.SetPinCode("******"); + DeviceProfileConnector::GetInstance().UpdateLocalServiceInfo(srvInfo); } if (context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { // no authorization box int32_t authResult = srvInfo.GetAuthType(); // read authResult -- Gitee From 4c945b960480ec8f60c38d086660e17782832162 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Fri, 28 Mar 2025 21:14:43 +0800 Subject: [PATCH 330/382] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8Dstate=E5=88=87?= =?UTF-8?q?=E6=8D=A2=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_state_machine.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 795aeec3e..7bd27892b 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -166,13 +166,11 @@ int32_t DmAuthStateMachine::TransitionTo(std::shared_ptr state) { int32_t ret = DM_OK; DmAuthStateType nextState = state->GetStateType(); + std::lock_guard lock(stateMutex_); if (this->CheckStateTransitValid(nextState)) { LOGI("DmAuthStateMachine: The state transition from %{public}d to %{public}d.", GetCurState(), nextState); - { - std::lock_guard lock(stateMutex_); - statesQueue_.push(state); - } + statesQueue_.push(state); stateCv_.notify_one(); } else { // The state transition is invalid. -- Gitee From b4895dc7fa0d72d458687e71a55e43aeb7e96b3f Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Mar 2025 21:14:46 +0800 Subject: [PATCH 331/382] tmp --- .../implementation/include/authentication_v2/dm_auth_state.h | 1 - 1 file changed, 1 deletion(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index 61bb71a9a..b5f70c9c1 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -157,7 +157,6 @@ private: int32_t ShowConfigDialog(std::shared_ptr context); void ReadServiceInfo(std::shared_ptr context); void MatchFallBackCandidateList(std::shared_ptr context, DmAuthType authType); - bool IsAuthCodeReady(std::shared_ptr context); }; class AuthSrcPinNegotiateStartState : public DmAuthState { -- Gitee From 659452e4c767523975efc07427069904d0044816 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Fri, 28 Mar 2025 21:27:53 +0800 Subject: [PATCH 332/382] =?UTF-8?q?fix:=20=E4=BF=AE=E5=A4=8DisAuthed?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- services/implementation/src/authentication_v2/dm_auth_state.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 3aa6e7c14..2b8cbadf2 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -440,7 +440,7 @@ bool DmAuthState::NeedAgreeCredential(std::shared_ptr context) bool DmAuthState::NeedAgreeAcl(std::shared_ptr context) { - return !(context->accesser.isAuthed && context->accessee.isAuthed); + return (context->direction == DM_AUTH_SOURCE) ? !context->accesser.isAuthed : !context->accessee.isAuthed; } bool DmAuthState::IsImportAuthCodeCompatibility(DmAuthType authType) -- Gitee From 0871c2f86b213b5aa6b0c66cb6e9b36339033598 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Mar 2025 21:34:30 +0800 Subject: [PATCH 333/382] tmp --- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 5 +++-- .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 4 ++-- 2 files changed, 5 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index c791a7c12..29ca44dc5 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -286,7 +286,8 @@ void AuthSinkConfirmState::ReadServiceInfo(std::shared_ptr contex } } context->customData = srvInfo.GetDescription(); // read customData - } else if (DmAuthState::IsImportAuthCodeCompatibility(context->authType) && IsAuthCodeReady(context)) { + } else if (DmAuthState::IsImportAuthCodeCompatibility(context->authType) && + AuthSinkStatePinAuthComm::IsAuthCodeReady(context)) { // only special scenarios can import pincode context->authBoxType = OHOS::DistributedDeviceProfile::NUM_2; // no authorization box } else { @@ -304,7 +305,7 @@ int32_t AuthSinkConfirmState::Action(std::shared_ptr context) ReadServiceInfo(context); bool authTypeCheckOk = false; if (DmAuthState::IsImportAuthCodeCompatibility(context->authType) && - (context->serviceInfoFound || IsAuthCodeReady(context)) && + (context->serviceInfoFound || AuthSinkStatePinAuthComm::IsAuthCodeReady(context)) && context->authBoxType == OHOS::DistributedDeviceProfile::NUM_2) { /* The value of authresult may be the default value of temporary trust, or the value of authresult may be set by the service. */ diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 4338f4e59..1085272a2 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -115,8 +115,8 @@ bool AuthSinkStatePinAuthComm::IsAuthCodeReady(std::shared_ptr co "import sessionName %{public}s.", context->sessionName.c_str(), context->importSessionName.c_str()); return false; } - if (AuthSinkStatePinAuthComm::IsPinCodeValid(authCode)) { - context_->pinCode = std::stoi(authCode.c_str()); + if (AuthSinkStatePinAuthComm::IsPinCodeValid(context->importAuthCode)) { + context->pinCode = std::stoi(context->importAuthCode.c_str()); } return true; } -- Gitee From 3bc797c58e3e52d511189efc890e215e6f63e373 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Mar 2025 21:41:31 +0800 Subject: [PATCH 334/382] add pin import log --- services/implementation/src/authentication_v2/auth_manager.cpp | 3 ++- .../src/authentication_v2/auth_stages/auth_confirm.cpp | 1 + 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index a7300e218..f1dd4c7eb 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -276,6 +276,7 @@ int32_t AuthManager::ImportAuthCode(const std::string &sessionName, const std::s } context_->importAuthCode = authCode; context_->importSessionName = sessionName; + LOGI("AuthManager::ImportAuthCode ok"); return DM_OK; } @@ -591,7 +592,7 @@ void AuthManager::GetAuthParam(const std::string &sessionName, int32_t authType, const std::string &deviceId, const std::string &extra) { LOGI("Get auth param with sessionName %{public}s and extra %{public}s.", sessionName.c_str(), extra.c_str()); - + std::string realPkgName = GetSubStr(sessionName, PICKER_PROXY_SPLIT, 1); realPkgName = realPkgName.empty() ? sessionName : realPkgName; context_->sessionName = sessionName; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index 29ca44dc5..d413cd6cc 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -262,6 +262,7 @@ void AuthSinkConfirmState::ReadServiceInfo(std::shared_ptr contex auto ret = DeviceProfileConnector::GetInstance().GetLocalServiceInfoByBundleNameAndPinExchangeType( context->accessee.bundleName, context->authType, srvInfo); if (ret == OHOS::DistributedDeviceProfile::DP_SUCCESS) { + LOGI("AuthSinkConfirmState::ReadServiceInfo found"); // ServiceInfo found context->serviceInfoFound = true; context->authBoxType = srvInfo.GetAuthBoxType(); // read authBoxType -- Gitee From acdb2e075d8bf29b84c331757f1886ec5582928d Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Fri, 28 Mar 2025 22:59:32 +0800 Subject: [PATCH 335/382] =?UTF-8?q?fix:=20=E8=A7=A3=E5=86=B3tokenId?= =?UTF-8?q?=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/device_manager_service_impl.h | 1 + .../authentication_v2/auth_stages/auth_pin_auth.cpp | 3 ++- .../src/device_manager_service_impl.cpp | 13 ++++++++++--- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 6f10694d6..726e911b9 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -55,6 +55,7 @@ public: struct Config { std::string pkgName; std::string authCode; + uint64_t tokenId; int32_t authenticationType{0}; }; diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index 1085272a2..bb82d7e0c 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -107,7 +107,8 @@ bool AuthSinkStatePinAuthComm::IsPinCodeValid(const std::string& strpin) bool AuthSinkStatePinAuthComm::IsAuthCodeReady(std::shared_ptr context) { if (context->importAuthCode.empty() || context->importSessionName.empty()) { - LOGE("AuthSinkNegotiateStateMachine::IsAuthCodeReady, auth code not ready."); + LOGE("AuthSinkStatePinAuthComm::IsAuthCodeReady, auth code not ready with authCode %{public}s and " + "sessionName %{public}s.", context->importAuthCode.c_str(), context->importSessionName.c_str()); return false; } if (context->sessionName != context->importSessionName) { diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 3594b5435..cc7a86e6d 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -154,6 +154,8 @@ static uint64_t GetTokenId(bool isSrcSide, int32_t displayId, int32_t userId, st } if (AppManager::GetInstance().GetHapTokenIdByName(targetUserId, bundleName, 0, tmpTokenId) == DM_OK) { tokenId = static_cast(tmpTokenId); + } else if (AppManager::GetInstance().GetNativeTokenIdByName(bundleName, tmpTokenId) == DM_OK) { + tokenId = static_cast(tmpTokenId); } else { // 获取deviceId, 取其8位字符值作为tokenId char localDeviceId[DEVICE_UUID_LENGTH] = {0}; @@ -246,13 +248,14 @@ int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide, uint64_ // 资源销毁通知函数注册 authMgrMap_[tokenId]->RegisterCleanNotifyCallback(&DeviceManagerServiceImpl::NotifyCleanEvent); hiChainAuthConnector_->RegisterHiChainAuthCallbackById(logicalSessionId, authMgrMap_[tokenId]); - LOGD("DeviceManagerServiceImpl::Initialize authMgrMap_ token: %{public}lu.", tokenId); + LOGI("DeviceManagerServiceImpl::Initialize authMgrMap_ token: %{public}lu.", tokenId); // 导入配置 if (configsMap_.find(tokenId) != configsMap_.end()) { authMgrMap_[tokenId]->ImportAuthCode(configsMap_[tokenId]->pkgName, configsMap_[tokenId]->authCode); authMgrMap_[tokenId]->RegisterAuthenticationType(configsMap_[tokenId]->authenticationType); configsMap_[tokenId] = nullptr; configsMap_.erase(tokenId); + LOGI("DeviceManagerServiceImpl::InitAndRegisterAuthMgr import authCode"); } return DM_OK; } @@ -328,7 +331,7 @@ std::shared_ptr DeviceManagerServiceImpl::GetAuthMgr() { uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { - LOGD("DeviceManagerServiceImpl::GetAuthMgr authMgrMap_ token: %{public}lu.", tokenId); + LOGI("DeviceManagerServiceImpl::GetAuthMgr authMgrMap_ token: %{public}lu.", tokenId); return authMgrMap_[tokenId]; } LOGE("DeviceManagerServiceImpl::GetAuthMgr authMgrMap_ not found, token: %{public}lu.", tokenId); @@ -339,7 +342,7 @@ std::shared_ptr DeviceManagerServiceImpl::GetAuthMgr() std::shared_ptr DeviceManagerServiceImpl::GetAuthMgrByTokenId(uint64_t tokenId) { if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { - LOGD("DeviceManagerServiceImpl::GetAuthMgrByTokenId authMgrMap_ token: %{public}lu.", tokenId); + LOGI("DeviceManagerServiceImpl::GetAuthMgrByTokenId authMgrMap_ token: %{public}lu.", tokenId); return authMgrMap_[tokenId]; } LOGE("DeviceManagerServiceImpl::GetAuthMgrByTokenId authMgrMap_ not found, token: %{public}lu.", tokenId); @@ -1150,6 +1153,7 @@ std::shared_ptr DeviceManagerServiceImpl::GetConfigByTokenId() if (configsMap_.find(tokenId) == configsMap_.end()) { configsMap_[tokenId] = std::make_shared(); } + configsMap_[tokenId]->tokenId = tokenId; return configsMap_[tokenId]; } @@ -1160,9 +1164,12 @@ int32_t DeviceManagerServiceImpl::ImportAuthCode(const std::string &pkgName, con return ERR_DM_INPUT_PARA_INVALID; } + LOGI("DeviceManagerServiceImpl::ImportAuthCode pkgName is %{public}s, authCode is %{public}s", + pkgName.c_str(), authCode.c_str()); auto authMgr = GetAuthMgr(); if (authMgr == nullptr) { auto config = GetConfigByTokenId(); + LOGI("DeviceManagerServiceImpl::ImportAuthCode import for tokenId %{public}ld", config->tokenId); config->pkgName = pkgName; config->authCode = authCode; // 若多次注册,只保留最后一个 return DM_OK; -- Gitee From d552959b75c8a9e6f8b6cbdc78e93fe974c3f43d Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Fri, 28 Mar 2025 23:09:47 +0800 Subject: [PATCH 336/382] fix: import code check --- .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index bb82d7e0c..ebf5cddeb 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -361,7 +361,13 @@ int32_t AuthSrcPinNegotiateStartState::NegotiatePinAuth(std::shared_ptrauthType)) { - context->authStateMachine->TransitionTo(std::make_shared()); + if (AuthSinkStatePinAuthComm::IsAuthCodeReady(context)) { + context->authStateMachine->TransitionTo(std::make_shared()); + } else { + LOGE("AuthSrcPinNegotiateStartState::Action auth code not ready"); + context->reason = ERR_DM_INPUT_PARA_INVALID; + return ERR_DM_FAILED; + } } else if (context->authType == DmAuthType::AUTH_TYPE_PIN) { context->authStateMachine->TransitionTo(std::make_shared()); } else if (context->authType == DmAuthType::AUTH_TYPE_PIN_ULTRASONIC) { -- Gitee From 4affa5babd4c83d2efa2d7e72d012cbd3b145f08 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Sat, 29 Mar 2025 08:43:59 +0800 Subject: [PATCH 337/382] =?UTF-8?q?=E8=A7=A3=E7=BB=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../include/deviceprofile_connector.h | 10 +- .../include/multiple_user_connector.h | 1 + .../src/deviceprofile_connector.cpp | 156 ++++++++++++++++-- .../src/multiple_user_connector.cpp | 9 + .../include/device_manager_service_impl.h | 2 + .../src/device_manager_service_impl.cpp | 146 ++++++++++++---- .../include/idevice_manager_service_impl.h | 2 + .../relationship_sync_mgr.h | 2 + .../service/src/device_manager_service.cpp | 4 + .../relationship_sync_mgr.cpp | 25 ++- 10 files changed, 307 insertions(+), 50 deletions(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 8df1217e0..8197098ed 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -89,6 +89,7 @@ typedef struct DmAccessee { typedef struct DmOfflineParam { uint32_t bindType; std::vector processVec; + std::vector credIdVec; int32_t leftAclNumber; } DmOfflineParam; @@ -114,6 +115,8 @@ class DeviceProfileConnector : public IDeviceProfileConnector { public: DmOfflineParam DeleteAccessControlList_v2(const uint32_t tokenId, const std::string &localDeviceId, const std::string &remoteDeviceId, int32_t bindLevel, const std::string &extra); + DmOfflineParam HandleServiceUnBindEvent(int32_t remoteUserId, + const std::string &remoteUdid, const std::string &localUdid, int32_t tokenId); std::vector GetAccessControlProfile(); std::vector GetAccessControlProfileByUserId(int32_t userId); std::vector GetAclProfileByDeviceIdAndUserId( @@ -158,10 +161,11 @@ public: const std::string &localUdid); int32_t HandleAccountLogoutEvent(int32_t remoteUserId, const std::string &remoteAccountHash, const std::string &remoteUdid, const std::string &localUdid); - int32_t HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, const std::string &localUdid); - OHOS::DistributedHardware::ProcessInfo HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + int32_t HandleDevUnBindEvent(DmOfflineParam &offlineParam, + int32_t remoteUserId, const std::string &remoteUdid, const std::string &localUdid); + DmOfflineParam HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid); - OHOS::DistributedHardware::ProcessInfo HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, + DmOfflineParam HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid, int32_t peerTokenId); std::vector GetAllAccessControlProfile(); void DeleteAccessControlById(int64_t accessControlId); diff --git a/commondependency/include/multiple_user_connector.h b/commondependency/include/multiple_user_connector.h index ac9a105bb..29f4db486 100644 --- a/commondependency/include/multiple_user_connector.h +++ b/commondependency/include/multiple_user_connector.h @@ -104,6 +104,7 @@ public: static DMAccountInfo GetAccountInfoByUserId(int32_t userId); static void DeleteAccountInfoByUserId(int32_t userId); static void GetTokenIdAndForegroundUserId(uint32_t &tokenId, int32_t &userId); + static void GetTokenId(uint32_t &tokenId); static void GetCallerUserId(int32_t &userId); static int32_t GetForegroundUserIds(std::vector &userVec); static int32_t GetFirstForegroundUserId(void); diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 0febd3901..7ef5f8920 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -106,6 +106,7 @@ void DeviceProfileConnector::DeleteAppBindLevel_v2(DmOfflineParam &offlineParam, processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); offlineParam.processVec.push_back(processInfo); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialId()); LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -122,6 +123,7 @@ void DeviceProfileConnector::DeleteAppBindLevel_v2(DmOfflineParam &offlineParam, processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); offlineParam.processVec.push_back(processInfo); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialId()); LOGI("Sink delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -158,6 +160,7 @@ void DeviceProfileConnector::DeleteAppBindLevel_v2(DmOfflineParam &offlineParam, processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); offlineParam.processVec.push_back(processInfo); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialId()); LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -176,6 +179,7 @@ void DeviceProfileConnector::DeleteAppBindLevel_v2(DmOfflineParam &offlineParam, processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); offlineParam.processVec.push_back(processInfo); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialId()); LOGI("Sink delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -204,6 +208,11 @@ void DeviceProfileConnector::DeleteServiceBindLevel_v2(DmOfflineParam &offlinePa DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = SERVICE; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialId()); LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -216,6 +225,11 @@ void DeviceProfileConnector::DeleteServiceBindLevel_v2(DmOfflineParam &offlinePa DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = SERVICE; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialId()); LOGI("Sink delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); @@ -926,6 +940,7 @@ void DeviceProfileConnector::DeleteDeviceBindLevel(DmOfflineParam &offlineParam, DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = DEVICE; + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialId()); LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; @@ -935,6 +950,7 @@ void DeviceProfileConnector::DeleteDeviceBindLevel(DmOfflineParam &offlineParam, DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); deleteNums++; offlineParam.bindType = DEVICE; + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialId()); LOGI("Sink delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); continue; @@ -1376,11 +1392,13 @@ int32_t DeviceProfileConnector::HandleAccountLogoutEvent(int32_t remoteUserId, return bindType; } -int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, - const std::string &localUdid) +int32_t DeviceProfileConnector::HandleDevUnBindEvent(DmOfflineParam &offlineParam, + int32_t remoteUserId, const std::string &remoteUdid, const std::string &localUdid) { LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, localUdid %{public}s.", remoteUserId, GetAnonyString(remoteUdid).c_str(), GetAnonyString(localUdid).c_str()); + int32_t bindNums = 0; + int32_t deleteNums = 0; std::vector profiles = GetAclProfileByDeviceIdAndUserId(remoteUdid, remoteUserId); int32_t bindType = DM_INVALIED_BINDTYPE; for (const auto &item : profiles) { @@ -1391,24 +1409,49 @@ int32_t DeviceProfileConnector::HandleDevUnBindEvent(int32_t remoteUserId, const bindType = DM_IDENTICAL_ACCOUNT; continue; } - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - bindType = std::min(bindType, static_cast(item.GetBindType())); + bindNums++; + if (item.GetAccesser().GetAccesserDeviceId() == localUdid && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = DEVICE; + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialId()); + LOGI("Src delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), + GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); + bindType = std::min(bindType, static_cast(item.GetBindType())); + continue; + } + if (item.GetAccessee().GetAccesseeDeviceId() == localUdid && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = DEVICE; + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialId()); + LOGI("Sink delete acl bindType %{public}d, localUdid %{public}s, remoteUdid %{public}s", item.GetBindType(), + GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str()); + bindType = std::min(bindType, static_cast(item.GetBindType())); + continue; + } } + offlineParam.leftAclNumber = bindNums - deleteNums; return bindType; } -OHOS::DistributedHardware::ProcessInfo DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, +DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid) { LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}d, localUdid %{public}s.", remoteUserId, GetAnonyString(remoteUdid).c_str(), tokenId, GetAnonyString(localUdid).c_str()); - std::vector profiles = GetAccessControlProfile(); - ProcessInfo processInfo; + std::vector profiles = GetAclProfileByDeviceIdAndUserId(remoteUdid, remoteUserId); + DmOfflineParam offlineParam; + int32_t bindNums = 0; + int32_t deleteNums = 0; for (const auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetBindLevel() != APP) { continue; } + bindNums++; if (item.GetAccesser().GetAccesserUserId() == remoteUserId && item.GetAccesser().GetAccesserDeviceId() == remoteUdid && (static_cast(item.GetAccesser().GetAccesserTokenId()) == tokenId || @@ -1416,8 +1459,13 @@ OHOS::DistributedHardware::ProcessInfo DeviceProfileConnector::HandleAppUnBindEv item.GetAccessee().GetAccesseeDeviceId() == localUdid) { LOGI("Src device unbind."); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = APP; + ProcessInfo processInfo; processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialId()); continue; } if (item.GetAccessee().GetAccesseeUserId() == remoteUserId && @@ -1427,50 +1475,126 @@ OHOS::DistributedHardware::ProcessInfo DeviceProfileConnector::HandleAppUnBindEv item.GetAccesser().GetAccesserDeviceId() == localUdid) { LOGI("Sink device unbind."); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = APP; + ProcessInfo processInfo; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialId()); continue; } } - return processInfo; + offlineParam.leftAclNumber = bindNums - deleteNums; + return offlineParam; } -OHOS::DistributedHardware::ProcessInfo DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, +DmOfflineParam DeviceProfileConnector::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, const std::string &localUdid, int32_t peerTokenId) { LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}d, localUdid %{public}s.", remoteUserId, GetAnonyString(remoteUdid).c_str(), tokenId, GetAnonyString(localUdid).c_str()); - std::vector profiles = GetAccessControlProfile(); - ProcessInfo processInfo; + std::vector profiles = GetAclProfileByDeviceIdAndUserId(remoteUdid, remoteUserId); + DmOfflineParam offlineParam; + int32_t bindNums = 0; + int32_t deleteNums = 0; for (const auto &item : profiles) { if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || item.GetBindLevel() != APP) { continue; } + bindNums++; + if (item.GetAccesser().GetAccesserUserId() == remoteUserId && + item.GetAccesser().GetAccesserDeviceId() == remoteUdid && + (static_cast(item.GetAccesser().GetAccesserTokenId()) == tokenId || + static_cast(item.GetAccesser().GetAccesserTokenId()) == 0) && + (static_cast(item.GetAccessee().GetAccesseeTokenId()) == peerTokenId || + static_cast(item.GetAccessee().GetAccesseeTokenId()) == 0) && + item.GetAccessee().GetAccesseeDeviceId() == localUdid) { + LOGI("Src device unbind."); + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); + processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialId()); + continue; + } + if (item.GetAccessee().GetAccesseeUserId() == remoteUserId && + item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && + (static_cast(item.GetAccessee().GetAccesseeTokenId()) == tokenId || + static_cast(item.GetAccessee().GetAccesseeTokenId()) == 0) && + (static_cast(item.GetAccesser().GetAccesserTokenId()) == peerTokenId || + static_cast(item.GetAccesser().GetAccesserTokenId()) == 0) && + item.GetAccesser().GetAccesserDeviceId() == localUdid) { + LOGI("Sink device unbind."); + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = APP; + ProcessInfo processInfo; + processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); + processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialId()); + continue; + } + } + offlineParam.leftAclNumber = bindNums - deleteNums; + return offlineParam; +} + +DmOfflineParam DeviceProfileConnector::HandleServiceUnBindEvent(int32_t remoteUserId, + const std::string &remoteUdid, const std::string &localUdid, int32_t tokenId) +{ + LOGI("RemoteUserId %{public}d, remoteUdid %{public}s, tokenId %{public}d, localUdid %{public}s.", + remoteUserId, GetAnonyString(remoteUdid).c_str(), tokenId, GetAnonyString(localUdid).c_str()); + std::vector profiles = GetAclProfileByDeviceIdAndUserId(remoteUdid, remoteUserId); + DmOfflineParam offlineParam; + int32_t bindNums = 0; + int32_t deleteNums = 0; + for (const auto &item : profiles) { + if (item.GetTrustDeviceId() != remoteUdid || item.GetBindType() == DM_IDENTICAL_ACCOUNT || + item.GetBindLevel() != SERVICE) { + continue; + } + bindNums++; if (item.GetAccesser().GetAccesserUserId() == remoteUserId && item.GetAccesser().GetAccesserDeviceId() == remoteUdid && - static_cast(item.GetAccesser().GetAccesserTokenId()) == tokenId && - static_cast(item.GetAccessee().GetAccesseeTokenId()) == peerTokenId && + (static_cast(item.GetAccesser().GetAccesserTokenId()) == tokenId || + static_cast(item.GetAccesser().GetAccesserTokenId()) == 0) && item.GetAccessee().GetAccesseeDeviceId() == localUdid) { LOGI("Src device unbind."); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = SERVICE; + ProcessInfo processInfo; processInfo.pkgName = item.GetAccessee().GetAccesseeBundleName(); processInfo.userId = item.GetAccessee().GetAccesseeUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialId()); continue; } if (item.GetAccessee().GetAccesseeUserId() == remoteUserId && item.GetAccessee().GetAccesseeDeviceId() == remoteUdid && - static_cast(item.GetAccessee().GetAccesseeTokenId()) == tokenId && - static_cast(item.GetAccesser().GetAccesserTokenId()) == peerTokenId && + (static_cast(item.GetAccessee().GetAccesseeTokenId()) == tokenId || + static_cast(item.GetAccessee().GetAccesseeTokenId()) == 0) && item.GetAccesser().GetAccesserDeviceId() == localUdid) { LOGI("Sink device unbind."); DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + deleteNums++; + offlineParam.bindType = SERVICE; + ProcessInfo processInfo; processInfo.pkgName = item.GetAccesser().GetAccesserBundleName(); processInfo.userId = item.GetAccesser().GetAccesserUserId(); + offlineParam.processVec.push_back(processInfo); + offlineParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialId()); continue; } } - return processInfo; + offlineParam.leftAclNumber = bindNums - deleteNums; + return offlineParam; } std::vector DeviceProfileConnector::GetAllAccessControlProfile() diff --git a/commondependency/src/multiple_user_connector.cpp b/commondependency/src/multiple_user_connector.cpp index 1c7a83a98..725fa580d 100644 --- a/commondependency/src/multiple_user_connector.cpp +++ b/commondependency/src/multiple_user_connector.cpp @@ -122,6 +122,15 @@ void MultipleUserConnector::GetTokenIdAndForegroundUserId(uint32_t &tokenId, int userId = GetFirstForegroundUserId(); } +void MultipleUserConnector::GetTokenId(uint32_t &tokenId) +{ +#if !(defined(__LITEOS_M__) || defined(LITE_DEVICE)) + tokenId = OHOS::IPCSkeleton::GetCallingTokenID(); +#else + (void)tokenId; +#endif +} + void MultipleUserConnector::GetCallerUserId(int32_t &userId) { #if (defined(__LITEOS_M__) || defined(LITE_DEVICE)) diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 726e911b9..93357e6c4 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -165,6 +165,8 @@ public: int32_t DeleteAcl(const std::string &sessionName, const std::string &localUdid, const std::string &remoteUdid, int32_t bindLevel, const std::string &extra); static void NotifyCleanEvent(int64_t logicalSessionId); + void HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, + int32_t remoteTokenId); private: int32_t PraseNotifyEventJson(const std::string &event, JsonObject &jsonObject); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index cc7a86e6d..561acf582 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -1587,12 +1587,9 @@ void DeviceManagerServiceImpl::HandleDeviceNotTrust(const std::string &udid) LOGE("HandleDeviceNotTrust udid is empty."); return; } - auto authMgr = GetAuthMgr(); - if (authMgr == nullptr) { - LOGE("authMgr_ is nullptr"); - return; - } - authMgr->HandleDeviceNotTrust(udid); + DeviceProfileConnector::GetInstance().DeleteAccessControlList(udid); + CHECK_NULL_VOID(hiChainConnector_); + hiChainConnector_->DeleteAllGroupByUdid(udid); } int32_t DeviceManagerServiceImpl::GetBindLevel(const std::string &pkgName, const std::string &localUdid, @@ -1669,17 +1666,23 @@ void DeviceManagerServiceImpl::HandleDevUnBindEvent(int32_t remoteUserId, const char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localUdidTemp); - int32_t bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(remoteUserId, remoteUdid, localUdid); + DmOfflineParam offlineParam; + int32_t bindType = DeviceProfileConnector::GetInstance().HandleDevUnBindEvent(offlineParam, + remoteUserId, remoteUdid, localUdid); if (bindType == DM_INVALIED_BINDTYPE) { LOGE("Invalied bindtype."); return; } - auto authMgr = GetAuthMgr(); - if (authMgr == nullptr) { - LOGE("authMgr_ is nullptr"); - return; + // 新协议authMgr_->isAuthNewVersion_未定义 暂定义为isAuthNewVersion_ + bool isAuthNewVersion_ = true; + if (isAuthNewVersion_) { + int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); + for (auto credId : offlineParam.credIdVec) { + hiChainAuthConnector_->DeleteCredential(accountId, credId); + } + } else { + authMgr->DeleteGroup(DM_PKG_NAME, remoteUdid); } - authMgr->DeleteGroup(DM_PKG_NAME, remoteUdid); } void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, @@ -1688,15 +1691,31 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localUdidTemp); - ProcessInfo processInfo = + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid); - if (processInfo.pkgName.empty()) { - LOGE("Pkgname is empty."); + CHECK_NULL_VOID(softbusConnector_); + CHECK_NULL_VOID(hiChainAuthConnector_); + if (offlineParam.leftAclNumber != 0) { + LOGI("The sessionName unbind app-level type leftAclNumber not zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + softbusConnector_->HandleDeviceOffline(remoteUdid); + return; + } + if (offlineParam.leftAclNumber == 0) { + LOGI("The sessionName unbind app-level type leftAclNumber is zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + // 新协议authMgr_->isAuthNewVersion_未定义 暂定义为isAuthNewVersion_ + bool isAuthNewVersion_ = true; + if (isAuthNewVersion_) { + int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); + for (auto credId : offlineParam.credIdVec) { + hiChainAuthConnector_->DeleteCredential(accountId, credId); + } + } else { + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + } return; } - CHECK_NULL_VOID(softbusConnector_); - softbusConnector_->SetProcessInfo(processInfo); - softbusConnector_->HandleDeviceOffline(remoteUdid); } void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, @@ -1706,7 +1725,7 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); std::string localUdid = std::string(localUdidTemp); - ProcessInfo processInfo = + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid, peerTokenId); if (processInfo.pkgName.empty()) { @@ -1714,8 +1733,63 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const return; } CHECK_NULL_VOID(softbusConnector_); - softbusConnector_->SetProcessInfo(processInfo); - softbusConnector_->HandleDeviceOffline(remoteUdid); + CHECK_NULL_VOID(hiChainAuthConnector_); + if (offlineParam.leftAclNumber != 0) { + LOGI("The sessionName unbind app-level type leftAclNumber not zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + softbusConnector_->HandleDeviceOffline(remoteUdid); + return; + } + if (offlineParam.leftAclNumber == 0) { + LOGI("The sessionName unbind app-level type leftAclNumber is zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + // 新协议authMgr_->isAuthNewVersion_未定义 暂定义为isAuthNewVersion_ + bool isAuthNewVersion_ = true; + if (isAuthNewVersion_) { + int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); + for (auto credId : offlineParam.credIdVec) { + hiChainAuthConnector_->DeleteCredential(accountId, credId); + } + } else { + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + } + return; + } +} + +void DeviceManagerServiceImpl::HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, + int32_t remoteTokenId); +{ + LOGI("HandleServiceUnBindEvent remoteTokenId = %{public}d, userId: %{public}d, remoteUdid: %{public}s.", + remoteTokenId, userId, GetAnonyString(remoteUdid).c_str()); + char localUdidTemp[DEVICE_UUID_LENGTH] = {0}; + GetDevUdid(localUdidTemp, DEVICE_UUID_LENGTH); + std::string localUdid = std::string(localUdidTemp); + DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().HandleServiceUnBindEvent( + userId, remoteUdid, localUdid, remoteTokenId); + CHECK_NULL_VOID(softbusConnector_); + CHECK_NULL_VOID(hiChainAuthConnector_); + if (offlineParam.leftAclNumber != 0) { + LOGI("The sessionName unbind app-level type leftAclNumber not zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + softbusConnector_->HandleDeviceOffline(remoteUdid); + return; + } + if (offlineParam.leftAclNumber == 0) { + LOGI("The sessionName unbind app-level type leftAclNumber is zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); + // 新协议authMgr_->isAuthNewVersion_未定义 暂定义为isAuthNewVersion_ + bool isAuthNewVersion_ = true; + if (isAuthNewVersion_) { + int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); + for (auto credId : offlineParam.credIdVec) { + hiChainAuthConnector_->DeleteCredential(accountId, credId); + } + } else { + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + } + return; + } } void DeviceManagerServiceImpl::HandleSyncUserIdEvent(const std::vector &foregroundUserIds, @@ -1916,18 +1990,14 @@ int32_t DeviceManagerServiceImpl::DeleteAcl(const std::string &sessionName, cons LOGI("DeleteAcl sessionName %{public}s, localUdid %{public}s, remoteUdid %{public}s, bindLevel %{public}d.", sessionName.c_str(), GetAnonyString(localUdid).c_str(), GetAnonyString(remoteUdid).c_str(), bindLevel); uint32_t tokenId = 0; - int32_t userId = 0; - MultipleUserConnector::GetTokenIdAndForegroundUserId(tokenId, userId); + MultipleUserConnector::GetTokenId(tokenId); DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().DeleteAccessControlList_v2( tokenId, localUdid, remoteUdid, bindLevel, extra); if (offlineParam.bindType == INVALIED_TYPE) { LOGE("Acl not contain the sessionName bind data."); return ERR_DM_FAILED; } - if (bindLevel == APP) { - ProcessInfo processInfo; - processInfo.pkgName = sessionName; - MultipleUserConnector::GetCallerUserId(processInfo.userId); + if (bindLevel == APP || bindLevel == SERVICE) { if (offlineParam.leftAclNumber != 0) { LOGI("The sessionName unbind app-level type leftAclNumber not zero."); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); @@ -1937,7 +2007,16 @@ int32_t DeviceManagerServiceImpl::DeleteAcl(const std::string &sessionName, cons if (offlineParam.leftAclNumber == 0) { LOGI("The sessionName unbind app-level type leftAclNumber is zero."); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + // 新协议authMgr_->isAuthNewVersion_未定义 暂定义为isAuthNewVersion_ + bool isAuthNewVersion_ = true; + if (isAuthNewVersion_) { + int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); + for (auto credId : offlineParam.credIdVec) { + hiChainAuthConnector_->DeleteCredential(accountId, credId); + } + } else { + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + } return DM_OK; } } @@ -1947,7 +2026,16 @@ int32_t DeviceManagerServiceImpl::DeleteAcl(const std::string &sessionName, cons } if (bindLevel == DEVICE && offlineParam.leftAclNumber == 0) { LOGI("Unbind deivce-level, retain null."); - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + // 新协议authMgr_->isAuthNewVersion_未定义 暂定义为isAuthNewVersion_ + bool isAuthNewVersion_ = true; + if (isAuthNewVersion_) { + int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); + for (auto credId : offlineParam.credIdVec) { + hiChainAuthConnector_->DeleteCredential(accountId, credId); + } + } else { + hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); + } return DM_OK; } return ERR_DM_FAILED; diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 8ba83a8ad..fcccfc92b 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -260,6 +260,8 @@ public: virtual void DeleteAlwaysAllowTimeOut() = 0; virtual void CheckDeleteCredential(const std::string &remoteUdid) = 0; virtual int32_t CheckDeviceInfoPermission(const std::string &localUdid, const std::string &peerDeviceId) = 0; + virtual void HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, + int32_t remoteTokenId) = 0; }; using CreateDMServiceFuncPtr = IDeviceManagerServiceImpl *(*)(void); diff --git a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h index d0787d446..cc6409ce1 100644 --- a/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h +++ b/services/service/include/relationshipsyncmgr/relationship_sync_mgr.h @@ -68,6 +68,7 @@ struct RelationShipChangeMsg { void ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const; void ToDeviceUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; void ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; + void ToServiceUnbindPayLoad(uint8_t *&msg, uint32_t &len) const; bool ToSyncFrontOrBackUserIdPayLoad(uint8_t *&msg, uint32_t &len) const; void ToDelUserPayLoad(uint8_t *&msg, uint32_t &len) const; void ToStopUserPayLoad(uint8_t *&msg, uint32_t &len) const; @@ -76,6 +77,7 @@ struct RelationShipChangeMsg { bool FromAccountLogoutPayLoad(const cJSON *payloadJson); bool FromDeviceUnbindPayLoad(const cJSON *payloadJson); bool FromAppUnbindPayLoad(const cJSON *payloadJson); + bool FromServiceUnbindPayLoad(const cJSON *payloadJson); bool FromSyncFrontOrBackUserIdPayLoad(const cJSON *payloadJson); bool FromDelUserPayLoad(const cJSON *payloadJson); bool FromStopUserPayLoad(const cJSON *payloadJson); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index c237769f8..1f1571ddf 100644 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2506,6 +2506,10 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) static_cast(relationShipMsg.tokenId)); } break; + case RelationShipChangeType::APP_UNBIND: + dmServiceImpl_->HandleServiceUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid, + static_cast(relationShipMsg.tokenId)); + break; case RelationShipChangeType::SYNC_USERID: HandleUserIdsBroadCast(relationShipMsg.userIdInfos, relationShipMsg.peerUdid, relationShipMsg.syncUserIdFlag); diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp index 962391c13..1009a97e8 100644 --- a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp +++ b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp @@ -116,6 +116,10 @@ bool RelationShipChangeMsg::ToBroadcastPayLoad(uint8_t *&msg, uint32_t &len) con ToAppUnbindPayLoad(msg, len); ret = true; break; + case RelationShipChangeType::SERVICE_UNBIND: + ToServiceUnbindPayLoad(msg, len); + ret = true; + break; case RelationShipChangeType::SYNC_USERID: ret = ToSyncFrontOrBackUserIdPayLoad(msg, len); break; @@ -152,6 +156,9 @@ bool RelationShipChangeMsg::FromBroadcastPayLoad(const cJSON *payloadJson, Relat case RelationShipChangeType::APP_UNBIND: ret = FromAppUnbindPayLoad(payloadJson); break; + case RelationShipChangeType::SERVICE_UNBIND: + ret = FromServiceUnbindPayLoad(payloadJson); + break case RelationShipChangeType::SYNC_USERID: ret = FromSyncFrontOrBackUserIdPayLoad(payloadJson); break; @@ -188,6 +195,8 @@ bool RelationShipChangeMsg::IsValid() const ret = (userId != UINT32_MAX); break; case RelationShipChangeType::SERVICE_UNBIND: + ret = (userId != UINT32_MAX); + break; case RelationShipChangeType::APP_UNINSTALL: // current NOT support ret = false; @@ -210,7 +219,8 @@ bool RelationShipChangeMsg::IsChangeTypeValid() { return (type == RelationShipChangeType::ACCOUNT_LOGOUT) || (type == RelationShipChangeType::DEVICE_UNBIND) || (type == RelationShipChangeType::APP_UNBIND) || (type == RelationShipChangeType::SYNC_USERID) || - (type == RelationShipChangeType::DEL_USER) || (type == RelationShipChangeType::STOP_USER); + (type == RelationShipChangeType::DEL_USER) || (type == RelationShipChangeType::STOP_USER) || + (type == RelationShipChangeType::SERVICE_UNBIND); } bool RelationShipChangeMsg::IsChangeTypeValid(uint32_t type) @@ -220,7 +230,8 @@ bool RelationShipChangeMsg::IsChangeTypeValid(uint32_t type) (type == (uint32_t)RelationShipChangeType::APP_UNBIND) || (type == (uint32_t)RelationShipChangeType::SYNC_USERID) || (type == (uint32_t)RelationShipChangeType::DEL_USER) || - (type == (uint32_t)RelationShipChangeType::STOP_USER); + (type == (uint32_t)RelationShipChangeType::STOP_USER) || + (type == (uint32_t)RelationShipChangeType::SERVICE_UNBIND); } void RelationShipChangeMsg::ToAccountLogoutPayLoad(uint8_t *&msg, uint32_t &len) const @@ -263,6 +274,11 @@ void RelationShipChangeMsg::ToAppUnbindPayLoad(uint8_t *&msg, uint32_t &len) con len = APP_UNBIND_PAYLOAD_LEN; } +void RelationShipChangeMsg::ToServiceUnbindPayLoad(uint8_t *&msg, uint32_t &len) const +{ + ToAppUnbindPayLoad(msg, len); +} + bool RelationShipChangeMsg::ToSyncFrontOrBackUserIdPayLoad(uint8_t *&msg, uint32_t &len) const { uint32_t userIdNum = static_cast(userIdInfos.size()); @@ -407,6 +423,11 @@ bool RelationShipChangeMsg::FromAppUnbindPayLoad(const cJSON *payloadJson) return true; } +bool RelationShipChangeMsg::FromServiceUnbindPayLoad(const cJSON *payloadJson) +{ + FromAppUnbindPayLoad(payloadJson); +} + bool RelationShipChangeMsg::FromSyncFrontOrBackUserIdPayLoad(const cJSON *payloadJson) { if (payloadJson == NULL) { -- Gitee From 9d5a004644a3178f3ac391228da17d2dcd090a4a Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Sat, 29 Mar 2025 09:42:11 +0800 Subject: [PATCH 338/382] import code set random default --- .../implementation/src/authentication_v2/auth_manager.cpp | 6 ++++++ .../src/authentication_v2/auth_stages/auth_pin_auth.cpp | 3 --- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index f1dd4c7eb..7a565cbdb 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -276,6 +276,12 @@ int32_t AuthManager::ImportAuthCode(const std::string &sessionName, const std::s } context_->importAuthCode = authCode; context_->importSessionName = sessionName; + + if (AuthSinkStatePinAuthComm::IsPinCodeValid(authCode)) { + context_->pinCode = std::stoi(authCode.c_str()); + } else { + AuthSinkStatePinAuthComm::GeneratePincode(context_); + } LOGI("AuthManager::ImportAuthCode ok"); return DM_OK; } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp index ebf5cddeb..aeb8191cf 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_pin_auth.cpp @@ -116,9 +116,6 @@ bool AuthSinkStatePinAuthComm::IsAuthCodeReady(std::shared_ptr co "import sessionName %{public}s.", context->sessionName.c_str(), context->importSessionName.c_str()); return false; } - if (AuthSinkStatePinAuthComm::IsPinCodeValid(context->importAuthCode)) { - context->pinCode = std::stoi(context->importAuthCode.c_str()); - } return true; } -- Gitee From 3a886a746b7ce52870ab194248ad9d7c07ae6796 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Sat, 29 Mar 2025 10:25:28 +0800 Subject: [PATCH 339/382] style --- services/implementation/src/authentication_v2/auth_manager.cpp | 2 -- .../implementation/src/authentication_v2/dm_auth_context.cpp | 2 -- .../src/authentication_v2/dm_auth_manager_base.cpp | 3 --- .../src/authentication_v2/dm_auth_message_processor.cpp | 2 -- .../implementation/src/authentication_v2/dm_auth_state.cpp | 3 --- .../src/authentication_v2/dm_auth_state_machine.cpp | 2 +- 6 files changed, 1 insertion(+), 13 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 7a565cbdb..2957c7193 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -36,8 +36,6 @@ #include "dm_auth_message_processor.h" #include "auth_manager.h" #include "dm_auth_state.h" -#undef LOG_TAG -#define LOG_TAG "DHDM_V2" namespace OHOS { namespace DistributedHardware { diff --git a/services/implementation/src/authentication_v2/dm_auth_context.cpp b/services/implementation/src/authentication_v2/dm_auth_context.cpp index fe0b1f182..5fbb0f306 100644 --- a/services/implementation/src/authentication_v2/dm_auth_context.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_context.cpp @@ -14,8 +14,6 @@ */ #include "dm_auth_context.h" -#undef LOG_TAG -#define LOG_TAG "DHDM_V2" namespace OHOS { namespace DistributedHardware { diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp index 6d7124769..a0e175ccf 100644 --- a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp @@ -24,9 +24,6 @@ using namespace OHOS::AccountSA; #endif // OS_ACCOUNT_PART_EXISTS -#undef LOG_TAG -#define LOG_TAG "DHDM_V2" - namespace OHOS { namespace DistributedHardware { diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index ca765ea22..b80ada78f 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -31,8 +31,6 @@ #include "dm_auth_context.h" #include "dm_auth_state_machine.h" #include "dm_crypto.h" -#undef LOG_TAG -#define LOG_TAG "DHDM_V2" namespace OHOS { namespace DistributedHardware { diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 2b8cbadf2..28625be1a 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -27,9 +27,6 @@ #endif #include "dm_log.h" -#undef LOG_TAG -#define LOG_TAG "DHDM_V2" - namespace OHOS { namespace DistributedHardware { diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index 7bd27892b..ab0896277 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -143,7 +143,7 @@ void DmAuthStateMachine::InsertSinkTransTable() {DmAuthStateType::AUTH_SINK_PIN_AUTH_DONE_STATE, { DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, - DmAuthStateType::AUTH_SINK_FINISH_STATE, // tdo check ?? or DmAuthStateType::AUTH_SINK_DATA_SYNC_STATE ? + DmAuthStateType::AUTH_SINK_FINISH_STATE, }}, {DmAuthStateType::AUTH_SINK_CREDENTIAL_EXCHANGE_STATE, { DmAuthStateType::AUTH_SINK_CREDENTIAL_AUTH_START_STATE, -- Gitee From df6e8307e5546ac9ec2f7cae2c62c3024df60cc9 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Sat, 29 Mar 2025 10:39:40 +0800 Subject: [PATCH 340/382] =?UTF-8?q?=E6=89=93=E5=BC=80bindlevel=E6=A0=A1?= =?UTF-8?q?=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication_v2/auth_stages/auth_acl.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 3d87ead3f..73cf1579b 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -46,10 +46,14 @@ int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) LOGI("AuthSinkDataSyncState::Action start"); // 判断密文阶段和明文阶段的四元组是否相同,两端的bindlevel是否相同,不同则直接结束 bool isSame = Crypto::Sha256(context->accesser.deviceId) == context->accesser.deviceIdHash && - Crypto::Sha256(std::to_string(context->accesser.userId)) == context->accesser.userIdHash && - Crypto::Sha256(context->accesser.accountId) == context->accesser.accountIdHash && - Crypto::Sha256(std::to_string(context->accesser.tokenId)) == context->accesser.tokenIdHash; - // && context->accesser.bindLevel == context->accessee.bindLevel; bindlevel协商能力补齐后打开 + Crypto::Sha256(std::to_string(context->accesser.userId)) == context->accesser.userIdHash && + Crypto::Sha256(context->accesser.accountId) == context->accesser.accountIdHash && + context->accesser.bindLevel == context->accessee.bindLevel; + + // 鸿蒙环场景tokenid为空,进行兼容 + isSame = Crypto::Sha256(std::to_string(context->accesser.tokenId)) == context->accesser.tokenIdHash || + (context->accesser.tokenId == 0 && context->accesser.tokenIdHash.empty()); + if (!isSame) { LOGE("data between two stages different, stop auth"); context->reply = ERR_DM_QUADRUPLE_NOT_SAME; @@ -104,14 +108,14 @@ int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) if (NeedAgreeAcl(context)) { // 判断密文阶段和明文阶段的四元组是否相同,不同则直接结束 bool isSame = Crypto::Sha256(context->accessee.deviceId) == context->accessee.deviceIdHash && - Crypto::Sha256(std::to_string(context->accessee.userId)) == context->accessee.userIdHash && - Crypto::Sha256(context->accessee.accountId) == context->accessee.accountIdHash; + Crypto::Sha256(std::to_string(context->accessee.userId)) == context->accessee.userIdHash && + Crypto::Sha256(context->accessee.accountId) == context->accessee.accountIdHash && + context->accesser.bindLevel == context->accessee.bindLevel; // 鸿蒙环场景tokenid为空,进行兼容 isSame = Crypto::Sha256(std::to_string(context->accessee.tokenId)) == context->accessee.tokenIdHash || (context->accessee.tokenId == 0 && context->accessee.tokenIdHash.empty()); - // && context->accesser.bindLevel == context->accessee.bindLevel; bindlevel协商能力补齐后打开 if (!isSame) { LOGE("data between two stages different, stop auth"); // 不同直接结束,发送200给sink端 -- Gitee From 6564b6d1104591b2347e4fdbe1207a8bb7c08045 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Sat, 29 Mar 2025 11:02:11 +0800 Subject: [PATCH 341/382] =?UTF-8?q?BUGFIX:=E5=8E=BB=E9=99=A4token=3D0?= =?UTF-8?q?=E7=9A=84=E5=85=BC=E5=AE=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_acl.cpp | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 73cf1579b..618a5fa84 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -48,11 +48,9 @@ int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) bool isSame = Crypto::Sha256(context->accesser.deviceId) == context->accesser.deviceIdHash && Crypto::Sha256(std::to_string(context->accesser.userId)) == context->accesser.userIdHash && Crypto::Sha256(context->accesser.accountId) == context->accesser.accountIdHash && + Crypto::Sha256(std::to_string(context->accesser.tokenId)) == context->accesser.tokenIdHash && context->accesser.bindLevel == context->accessee.bindLevel; - // 鸿蒙环场景tokenid为空,进行兼容 - isSame = Crypto::Sha256(std::to_string(context->accesser.tokenId)) == context->accesser.tokenIdHash || - (context->accesser.tokenId == 0 && context->accesser.tokenIdHash.empty()); if (!isSame) { LOGE("data between two stages different, stop auth"); @@ -110,12 +108,9 @@ int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) bool isSame = Crypto::Sha256(context->accessee.deviceId) == context->accessee.deviceIdHash && Crypto::Sha256(std::to_string(context->accessee.userId)) == context->accessee.userIdHash && Crypto::Sha256(context->accessee.accountId) == context->accessee.accountIdHash && + Crypto::Sha256(std::to_string(context->accessee.tokenId)) == context->accessee.tokenIdHash && context->accesser.bindLevel == context->accessee.bindLevel; - // 鸿蒙环场景tokenid为空,进行兼容 - isSame = Crypto::Sha256(std::to_string(context->accessee.tokenId)) == context->accessee.tokenIdHash || - (context->accessee.tokenId == 0 && context->accessee.tokenIdHash.empty()); - if (!isSame) { LOGE("data between two stages different, stop auth"); // 不同直接结束,发送200给sink端 -- Gitee From cb1a9ace77e6e7e9ee07a9637a64fad321e2ebad Mon Sep 17 00:00:00 2001 From: ZHANGHE24 Date: Sat, 29 Mar 2025 07:57:07 +0000 Subject: [PATCH 342/382] !18 fix: fix bug * fix: fix bug --- .../src/device_manager_service_impl.cpp | 58 +++++++++++++------ 1 file changed, 39 insertions(+), 19 deletions(-) diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 561acf582..05e75baff 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -830,7 +830,7 @@ void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, TODO: 考虑authMgr_的切换是否有多线程问题 */ - if (curSession->version_ == "" && + if (curSession->version_ == "" && authMgr->isAuthNewVersion_ && (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE || msgType == MSG_TYPE_RESP_ACL_NEGOTIATE)) { // IsMessageOldVersion内部会对session版本进行赋值,并解除对应物理会话信号量 if (IsMessageOldVersion(jsonObject, curSession)) { @@ -850,6 +850,7 @@ void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, // 内部已完成错误日志打印 return; } + authMgr->isAuthNewVersion_ = false; if (IsAuthManagerSourceByMessage(msgType)) { // 发送停止报文 @@ -1673,9 +1674,13 @@ void DeviceManagerServiceImpl::HandleDevUnBindEvent(int32_t remoteUserId, const LOGE("Invalied bindtype."); return; } - // 新协议authMgr_->isAuthNewVersion_未定义 暂定义为isAuthNewVersion_ - bool isAuthNewVersion_ = true; - if (isAuthNewVersion_) { + + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr_ is nullptr"); + return; + } + if (authMgr->isAuthNewVersion_) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); for (auto credId : offlineParam.credIdVec) { hiChainAuthConnector_->DeleteCredential(accountId, credId); @@ -1704,9 +1709,12 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const if (offlineParam.leftAclNumber == 0) { LOGI("The sessionName unbind app-level type leftAclNumber is zero."); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - // 新协议authMgr_->isAuthNewVersion_未定义 暂定义为isAuthNewVersion_ - bool isAuthNewVersion_ = true; - if (isAuthNewVersion_) { + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr_ is nullptr"); + return; + } + if (authMgr->isAuthNewVersion_) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); for (auto credId : offlineParam.credIdVec) { hiChainAuthConnector_->DeleteCredential(accountId, credId); @@ -1743,9 +1751,12 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const if (offlineParam.leftAclNumber == 0) { LOGI("The sessionName unbind app-level type leftAclNumber is zero."); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - // 新协议authMgr_->isAuthNewVersion_未定义 暂定义为isAuthNewVersion_ - bool isAuthNewVersion_ = true; - if (isAuthNewVersion_) { + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr_ is nullptr"); + return; + } + if (authMgr->isAuthNewVersion_) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); for (auto credId : offlineParam.credIdVec) { hiChainAuthConnector_->DeleteCredential(accountId, credId); @@ -1778,9 +1789,12 @@ void DeviceManagerServiceImpl::HandleServiceUnBindEvent(int32_t userId, const st if (offlineParam.leftAclNumber == 0) { LOGI("The sessionName unbind app-level type leftAclNumber is zero."); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - // 新协议authMgr_->isAuthNewVersion_未定义 暂定义为isAuthNewVersion_ - bool isAuthNewVersion_ = true; - if (isAuthNewVersion_) { + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr_ is nullptr"); + return; + } + if (authMgr->isAuthNewVersion_) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); for (auto credId : offlineParam.credIdVec) { hiChainAuthConnector_->DeleteCredential(accountId, credId); @@ -2007,9 +2021,12 @@ int32_t DeviceManagerServiceImpl::DeleteAcl(const std::string &sessionName, cons if (offlineParam.leftAclNumber == 0) { LOGI("The sessionName unbind app-level type leftAclNumber is zero."); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - // 新协议authMgr_->isAuthNewVersion_未定义 暂定义为isAuthNewVersion_ - bool isAuthNewVersion_ = true; - if (isAuthNewVersion_) { + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr_ is nullptr"); + return ERR_DM_POINT_NULL; + } + if (authMgr->isAuthNewVersion_) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); for (auto credId : offlineParam.credIdVec) { hiChainAuthConnector_->DeleteCredential(accountId, credId); @@ -2026,9 +2043,12 @@ int32_t DeviceManagerServiceImpl::DeleteAcl(const std::string &sessionName, cons } if (bindLevel == DEVICE && offlineParam.leftAclNumber == 0) { LOGI("Unbind deivce-level, retain null."); - // 新协议authMgr_->isAuthNewVersion_未定义 暂定义为isAuthNewVersion_ - bool isAuthNewVersion_ = true; - if (isAuthNewVersion_) { + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr_ is nullptr"); + return ERR_DM_POINT_NULL; + } + if (authMgr->isAuthNewVersion_) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); for (auto credId : offlineParam.credIdVec) { hiChainAuthConnector_->DeleteCredential(accountId, credId); -- Gitee From 56dcdc6ffe6e7a9f0a601347b6d7aba684f3faba Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Sat, 29 Mar 2025 16:05:42 +0800 Subject: [PATCH 343/382] =?UTF-8?q?=E8=A7=A3=E5=86=B3=E8=A7=A3=E7=BB=91?= =?UTF-8?q?=E7=BC=96=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../authentication_v2/dm_auth_message_processor.cpp | 12 ++++-------- .../src/device_manager_service_impl.cpp | 6 +----- services/service/src/device_manager_service.cpp | 2 +- .../relationshipsyncmgr/relationship_sync_mgr.cpp | 4 ++-- 4 files changed, 8 insertions(+), 16 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index b80ada78f..cd8541578 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -245,8 +245,7 @@ void DmAuthMessageProcessor::SetTransmitAccessControlList(std::shared_ptraccesser.tokenId); accesser.SetAccesserBundleName(context->accesser.bundleName); accesser.SetAccesserDeviceName(context->accesser.deviceName); - // accesser.SetAccesserCredentialId(stoi(context->accesser.transmitCredentialId)); - accesser.SetAccesserCredentialId(context->accesser.userId); + accesser.SetAccesserCredentialId(context->accesser.transmitCredentialId); accesser.SetAccesserSessionKeyId(context->accesser.transmitSessionKeyId); accesser.SetAccesserSKTimeStamp(context->accesser.transmitSkTimeStamp); accessee.SetAccesseeDeviceId(context->accessee.deviceId); @@ -255,8 +254,7 @@ void DmAuthMessageProcessor::SetTransmitAccessControlList(std::shared_ptraccessee.tokenId); accessee.SetAccesseeBundleName(context->accessee.bundleName); accessee.SetAccesseeDeviceName(context->accessee.deviceName); - // accessee.SetAccesseeCredentialId(stoi(context->accessee.transmitCredentialId)); - accessee.SetAccesseeCredentialId(context->accessee.userId); + accessee.SetAccesseeCredentialId(context->accessee.transmitCredentialId); accessee.SetAccesseeSessionKeyId(context->accessee.transmitSessionKeyId); accessee.SetAccesseeSKTimeStamp(context->accessee.transmitSkTimeStamp); } @@ -269,8 +267,7 @@ void DmAuthMessageProcessor::SetLnnAccessControlList(std::shared_ptraccesser.accountId); accesser.SetAccesserTokenId(0); accesser.SetAccesserDeviceName(context->accesser.deviceName); - // accesser.SetAccesserCredentialId(stoi(context->accesser.lnnCredentialId)); - accesser.SetAccesserCredentialId(context->accesser.userId); + accesser.SetAccesserCredentialId(context->accesser.lnnCredentialId); accesser.SetAccesserSessionKeyId(context->accesser.lnnSessionKeyId); accesser.SetAccesserSKTimeStamp(context->accesser.lnnSkTimeStamp); accessee.SetAccesseeDeviceId(context->accessee.deviceId); @@ -278,8 +275,7 @@ void DmAuthMessageProcessor::SetLnnAccessControlList(std::shared_ptraccessee.accountId); accessee.SetAccesseeTokenId(0); accessee.SetAccesseeDeviceName(context->accessee.deviceName); - // accessee.SetAccesseeCredentialId(stoi(context->accessee.lnnCredentialId)); - accessee.SetAccesseeCredentialId(context->accessee.userId); + accessee.SetAccesseeCredentialId(context->accessee.lnnCredentialId); accessee.SetAccesseeSessionKeyId(context->accessee.lnnSessionKeyId); accessee.SetAccesseeSKTimeStamp(context->accessee.lnnSkTimeStamp); } diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 05e75baff..1f92c0056 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -1736,10 +1736,6 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const DmOfflineParam offlineParam = DeviceProfileConnector::GetInstance().HandleAppUnBindEvent(remoteUserId, remoteUdid, tokenId, localUdid, peerTokenId); - if (processInfo.pkgName.empty()) { - LOGE("Pkgname is empty."); - return; - } CHECK_NULL_VOID(softbusConnector_); CHECK_NULL_VOID(hiChainAuthConnector_); if (offlineParam.leftAclNumber != 0) { @@ -1769,7 +1765,7 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const } void DeviceManagerServiceImpl::HandleServiceUnBindEvent(int32_t userId, const std::string &remoteUdid, - int32_t remoteTokenId); + int32_t remoteTokenId) { LOGI("HandleServiceUnBindEvent remoteTokenId = %{public}d, userId: %{public}d, remoteUdid: %{public}s.", remoteTokenId, userId, GetAnonyString(remoteUdid).c_str()); diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 1f1571ddf..e12db5381 100644 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2506,7 +2506,7 @@ void DeviceManagerService::HandleDeviceTrustedChange(const std::string &msg) static_cast(relationShipMsg.tokenId)); } break; - case RelationShipChangeType::APP_UNBIND: + case RelationShipChangeType::SERVICE_UNBIND: dmServiceImpl_->HandleServiceUnBindEvent(relationShipMsg.userId, relationShipMsg.peerUdid, static_cast(relationShipMsg.tokenId)); break; diff --git a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp index 1009a97e8..ce38f2ade 100644 --- a/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp +++ b/services/service/src/relationshipsyncmgr/relationship_sync_mgr.cpp @@ -158,7 +158,7 @@ bool RelationShipChangeMsg::FromBroadcastPayLoad(const cJSON *payloadJson, Relat break; case RelationShipChangeType::SERVICE_UNBIND: ret = FromServiceUnbindPayLoad(payloadJson); - break + break; case RelationShipChangeType::SYNC_USERID: ret = FromSyncFrontOrBackUserIdPayLoad(payloadJson); break; @@ -425,7 +425,7 @@ bool RelationShipChangeMsg::FromAppUnbindPayLoad(const cJSON *payloadJson) bool RelationShipChangeMsg::FromServiceUnbindPayLoad(const cJSON *payloadJson) { - FromAppUnbindPayLoad(payloadJson); + return FromAppUnbindPayLoad(payloadJson); } bool RelationShipChangeMsg::FromSyncFrontOrBackUserIdPayLoad(const cJSON *payloadJson) -- Gitee From 91e9225ccc63de0321dee52ee0e099dbc0c04711 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Sat, 29 Mar 2025 16:19:41 +0800 Subject: [PATCH 344/382] .GetAccesseeCredentialId --- .../src/authentication_v2/auth_stages/auth_acl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 618a5fa84..5bcd24080 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -83,7 +83,7 @@ int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) if (res) { continue; } - SyncAclList(context, std::to_string(sinkAcl.GetAccessee().GetAccesseeCredentialId()), + SyncAclList(context, sinkAcl.GetAccessee().GetAccesseeCredentialId(), sinkAcl.GetAccessee().GetAccesseeSessionKeyId(), sinkAcl.GetAccessControlId()); } // 同步本端的sp信息,不确定格式,暂不做 -- Gitee From b2bf1b77fe0a78c0c7ad356aa0d3e7ca8823bc54 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Sat, 29 Mar 2025 16:45:18 +0800 Subject: [PATCH 345/382] fix compile err --- .../include/deviceprofile_connector.h | 1 - .../include/authentication_v2/auth_manager.h | 1 + .../authentication_v2/dm_auth_manager_base.h | 2 ++ .../src/authentication_v2/auth_manager.cpp | 23 +++++++++++++++++++ .../dm_auth_manager_base.cpp | 2 ++ 5 files changed, 28 insertions(+), 1 deletion(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 2e911323c..1fac75678 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -119,7 +119,6 @@ public: GetAccessControlProfile(); EXPORT DmOfflineParam HandleServiceUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, const std::string &localUdid, int32_t tokenId); - std::vector GetAccessControlProfile(); std::vector GetAccessControlProfileByUserId(int32_t userId); std::vector GetAclProfileByDeviceIdAndUserId( const std::string &deviceId, int32_t userId); diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index 6bc297f9c..a3e952d20 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -128,6 +128,7 @@ protected: int32_t GetPinCode(int32_t &code); void GetRemoteDeviceId(std::string &deviceId); private: + bool CheckProcessNameInWhiteList(const std::string &processName); int32_t ParseAuthType(const std::map &bindParam, int32_t &authType); void ParseHmlInfoInJsonObject(const JsonObject &jsonObject); void ParseJsonObject(const JsonObject &jsonObject); diff --git a/services/implementation/include/authentication_v2/dm_auth_manager_base.h b/services/implementation/include/authentication_v2/dm_auth_manager_base.h index 541ffa9ce..98ee6a839 100644 --- a/services/implementation/include/authentication_v2/dm_auth_manager_base.h +++ b/services/implementation/include/authentication_v2/dm_auth_manager_base.h @@ -68,6 +68,8 @@ 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 char* WAIT_SESSION_CLOSE_TIMEOUT_TASK; +extern const char* CLOSE_SESSION_TASK_SEPARATOR; extern const int32_t AUTHENTICATE_TIMEOUT; extern const int32_t CONFIRM_TIMEOUT; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 4740dd3bf..8ee7eeb97 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -45,6 +45,11 @@ static const char* PICKER_PROXY_SPLIT = "_pickerProxy_"; // todo check constexpr int32_t MIN_PIN_CODE = 100000; constexpr int32_t MAX_PIN_CODE = 999999; +constexpr int32_t PROCESS_NAME_WHITE_LIST_NUM = 1; +constexpr const static char* PROCESS_NAME_WHITE_LIST[PROCESS_NAME_WHITE_LIST_NUM] = { + "com.example.myapplication", +}; + int32_t GetCloseSessionDelaySeconds(std::string &delaySecondsStr) { if (!IsNumberString(delaySecondsStr)) { @@ -527,6 +532,24 @@ void AuthManager::ParseJsonObject(const JsonObject &jsonObject) return; } +bool AuthManager::CheckProcessNameInWhiteList(const std::string &processName) +{ + LOGI("DmAuthManager::CheckProcessNameInWhiteList start"); + if (processName.empty()) { + LOGE("processName is empty"); + return false; + } + uint16_t index = 0; + for (; index < PROCESS_NAME_WHITE_LIST_NUM; ++index) { + std::string whitePkgName(PROCESS_NAME_WHITE_LIST[index]); + if (processName == whitePkgName) { + LOGI("processName = %{public}s in whiteList.", processName.c_str()); + return true; + } + } + LOGI("CheckProcessNameInWhiteList: %{public}s invalid.", processName.c_str()); + return false; +} int32_t AuthManager::GetBindLevel(int32_t bindLevel) { diff --git a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp index a0e175ccf..58087414e 100644 --- a/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_manager_base.cpp @@ -64,6 +64,8 @@ const char* AUTH_DEVICE_TIMEOUT_TASK = "deviceManagerTimer:authDevice_"; const char* WAIT_PIN_AUTH_TIMEOUT_TASK = "deviceManagerTimer:waitPinAuth"; const char* WAIT_NEGOTIATE_TIMEOUT_TASK = "deviceManagerTimer:waitNegotiate"; const char* ADD_TIMEOUT_TASK = "deviceManagerTimer:add"; +const char* WAIT_SESSION_CLOSE_TIMEOUT_TASK = "deviceManagerTimer:waitSessionClose"; +const char* CLOSE_SESSION_TASK_SEPARATOR = "#"; const int32_t AUTHENTICATE_TIMEOUT = 120; const int32_t CONFIRM_TIMEOUT = 60; -- Gitee From 06473a41458c87447964e219d30126d6dc2d280a Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Sat, 29 Mar 2025 16:52:07 +0800 Subject: [PATCH 346/382] .GetAccesseeCredentialId --- .../src/authentication_v2/auth_stages/auth_acl.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 5bcd24080..1691ca298 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -143,7 +143,7 @@ int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) if (res) { continue; } - SyncAclList(context, std::to_string(srcAcl.GetAccesser().GetAccesserCredentialId()), + SyncAclList(context, srcAcl.GetAccesser().GetAccesserCredentialId(), srcAcl.GetAccesser().GetAccesserSessionKeyId(), srcAcl.GetAccessControlId()); } // 保存本次acl -- Gitee From 111dedc86bd19257c7fad8e04f8e29ceb0d9ea3d Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Sat, 29 Mar 2025 17:12:11 +0800 Subject: [PATCH 347/382] will use: compile err log, dp, --- .../src/authentication_v2/dm_auth_state.cpp | 6 +++--- .../src/dependency/hichain/hichain_auth_connector.cpp | 4 ++-- .../src/dependency/softbus/softbus_connector.cpp | 10 +++++----- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 28625be1a..98b37ad29 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -339,15 +339,15 @@ int32_t DmAuthState::GetAuthCredentialInfo(std::shared_ptr contex DmAccess &access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; std::vector profiles = DeviceProfileConnector::GetInstance().GetAccessControlProfile(); - LOGI("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo success to get %{public}ld acls", profiles.size()); + LOGI("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo success to get %{public}u acls", profiles.size()); for (const DistributedDeviceProfile::AccessControlProfile &item : profiles) { bool isAclMatched = false; DistributedDeviceProfile::Accesser accesser = item.GetAccesser(); DistributedDeviceProfile::Accessee accessee = item.GetAccessee(); // Ensure credentials match with ACL - std::string credId = context->direction == DM_AUTH_SOURCE ? std::to_string(accesser.GetAccesserCredentialId()) : - std::to_string(accessee.GetAccesseeCredentialId()); + std::string credId = context->direction == DM_AUTH_SOURCE ? accesser.GetAccesserCredentialId() : + accessee.GetAccesseeCredentialId(); LOGI("Got acl: credId - %{public}s", credId.c_str()); // TODO: delete if (!queryResult.Contains(credId) || item.GetStatus() != ACTIVE) { continue; diff --git a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp index b49c982e6..7f46d513b 100644 --- a/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp +++ b/services/implementation/src/dependency/hichain/hichain_auth_connector.cpp @@ -76,10 +76,10 @@ int32_t HiChainAuthConnector::RegisterHiChainAuthCallbackById(int64_t id, std::shared_ptr HiChainAuthConnector::GetDeviceAuthCallback(int64_t id) { if (dmDeviceAuthCallbackMap_.find(id) != dmDeviceAuthCallbackMap_.end()) { - LOGD("HiChainAuthConnector::GetDeviceAuthCallback dmDeviceAuthCallbackMap_ id: %{public}lu.", id); + LOGD("HiChainAuthConnector::GetDeviceAuthCallback dmDeviceAuthCallbackMap_ id: %{public}lld.", id); return dmDeviceAuthCallbackMap_[id]; } - LOGD("HiChainAuthConnector::GetDeviceAuthCallback dmDeviceAuthCallbackMap_ not found, id: %{public}lu.", id); + LOGD("HiChainAuthConnector::GetDeviceAuthCallback dmDeviceAuthCallbackMap_ not found, id: %{public}lld.", id); return dmDeviceAuthCallback_; // 找不到新协议id注册的回调,则使用老协议注册的回调, 但老协议回调有可能为空 } diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 239fb9009..6e9ce6afc 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -171,14 +171,14 @@ void SoftbusConnector::JoinLnnByHml(int32_t sessionId, int32_t sessionKeyId, int LOGI("start, JoinLnnByHml sessionId: %{public}d.", sessionId); ConnectionAddr addrInfo; addrInfo.type = CONNECTION_ADDR_SESSION_WITH_KEY; - addrInfo.info.session.sessionId = sessionId; + addrInfo.deviceKeyId.sessionId = sessionId; if (sessionKeyId > 0 && remoteSessionKeyId > 0) { - addrInfo.info.session.localDeviceKeyId = sessionKeyId; - addrInfo.info.session.remoteDeviceKeyId = remoteSessionKeyId; + addrInfo.deviceKeyId.localDeviceKeyId = sessionKeyId; + addrInfo.deviceKeyId.remoteDeviceKeyId = remoteSessionKeyId; LOGI("sessionKeyId valid"); } else { - addrInfo.info.session.localDeviceKeyId = 0; - addrInfo.info.session.remoteDeviceKeyId = 0; + addrInfo.deviceKeyId.localDeviceKeyId = 0; + addrInfo.deviceKeyId.remoteDeviceKeyId = 0; } int32_t ret = ::JoinLNN(DM_PKG_NAME, &addrInfo, OnSoftbusJoinLNNResult, false); if (ret != DM_OK) { -- Gitee From 0d58cd0f311791a38a3ccb3a77c0a80107814f65 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Sat, 29 Mar 2025 17:27:49 +0800 Subject: [PATCH 348/382] will use: compile err log, dp, --- .../src/authentication_v2/dm_auth_state.cpp | 4 +-- .../dependency/softbus/softbus_connector.cpp | 2 +- .../src/device_manager_service_impl.cpp | 26 +++++++++---------- 3 files changed, 16 insertions(+), 16 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 98b37ad29..b151916e5 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -354,10 +354,10 @@ int32_t DmAuthState::GetAuthCredentialInfo(std::shared_ptr contex } // TODO: delete - LOGI("accesser: deviceId - %{public}s, userId - %{public}d, accountId - %{public}s, tokenId - %{public}ld", + LOGI("accesser: deviceId - %{public}s, userId - %{public}d, accountId - %{public}s, tokenId - %{public}lld", accesser.GetAccesserDeviceId().c_str(), accesser.GetAccesserUserId(), accesser.GetAccesserAccountId().c_str(), accesser.GetAccesserTokenId()); - LOGI("accessee: deviceId - %{public}s, userId - %{public}d, accountId - %{public}s, tokenId - %{public}ld", + LOGI("accessee: deviceId - %{public}s, userId - %{public}d, accountId - %{public}s, tokenId - %{public}lld", accessee.GetAccesseeDeviceId().c_str(), accessee.GetAccesseeUserId(), accessee.GetAccesseeAccountId().c_str(), accessee.GetAccesseeTokenId()); diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 6e9ce6afc..de3238ae8 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -171,7 +171,7 @@ void SoftbusConnector::JoinLnnByHml(int32_t sessionId, int32_t sessionKeyId, int LOGI("start, JoinLnnByHml sessionId: %{public}d.", sessionId); ConnectionAddr addrInfo; addrInfo.type = CONNECTION_ADDR_SESSION_WITH_KEY; - addrInfo.deviceKeyId.sessionId = sessionId; + addrInfo.info.session.sessionId = sessionId; if (sessionKeyId > 0 && remoteSessionKeyId > 0) { addrInfo.deviceKeyId.localDeviceKeyId = sessionKeyId; addrInfo.deviceKeyId.remoteDeviceKeyId = remoteSessionKeyId; diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 3ac9187f6..6ae1c6944 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -122,7 +122,7 @@ DeviceManagerServiceImpl::~DeviceManagerServiceImpl() static uint64_t StringToUint64(const std::string& str) { // 计算子字符串的长度,取字符串长度和8的最小值 - size_t subStrLength = std::min(str.length(), 8lu); + size_t subStrLength = std::min(str.length(), 8U); // 提取子字符串 std::string substr = str.substr(str.length() - subStrLength); @@ -189,7 +189,7 @@ void DeviceManagerServiceImpl::CleanWorker() { while (running_.load()) { auto logicalSessionId = FetchCleanEvent(); - LOGD("DeviceManagerServiceImpl::CleanWorker clean auth_mgr, its logicalSessionId: %{public}lu", logicalSessionId); + LOGD("DeviceManagerServiceImpl::CleanWorker clean auth_mgr, its logicalSessionId: %{public}lld", logicalSessionId); CleanAuthMgrByLogicalSessionId(logicalSessionId); } LOGD("DeviceManagerServiceImpl::CleanWorker end"); @@ -209,7 +209,7 @@ void DeviceManagerServiceImpl::Stop() void DeviceManagerServiceImpl::NotifyCleanEvent(int64_t logicalSessionId) { - LOGD("DeviceManagerServiceImpl::NotifyCleanEvent logicalSessionId: %{public}lu", logicalSessionId); + LOGD("DeviceManagerServiceImpl::NotifyCleanEvent logicalSessionId: %{public}lld", logicalSessionId); std::lock_guard lock(cleanEventMutex_); // 存入到队列中 cleanEventQueue_.push(logicalSessionId); @@ -248,7 +248,7 @@ int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide, uint64_ // 资源销毁通知函数注册 authMgrMap_[tokenId]->RegisterCleanNotifyCallback(&DeviceManagerServiceImpl::NotifyCleanEvent); hiChainAuthConnector_->RegisterHiChainAuthCallbackById(logicalSessionId, authMgrMap_[tokenId]); - LOGI("DeviceManagerServiceImpl::Initialize authMgrMap_ token: %{public}lu.", tokenId); + LOGI("DeviceManagerServiceImpl::Initialize authMgrMap_ token: %{public}llu.", tokenId); // 导入配置 if (configsMap_.find(tokenId) != configsMap_.end()) { authMgrMap_[tokenId]->ImportAuthCode(configsMap_[tokenId]->pkgName, configsMap_[tokenId]->authCode); @@ -331,10 +331,10 @@ std::shared_ptr DeviceManagerServiceImpl::GetAuthMgr() { uint64_t tokenId = IPCSkeleton::GetCallingTokenID(); if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { - LOGI("DeviceManagerServiceImpl::GetAuthMgr authMgrMap_ token: %{public}lu.", tokenId); + LOGI("DeviceManagerServiceImpl::GetAuthMgr authMgrMap_ token: %{public}llu.", tokenId); return authMgrMap_[tokenId]; } - LOGE("DeviceManagerServiceImpl::GetAuthMgr authMgrMap_ not found, token: %{public}lu.", tokenId); + LOGE("DeviceManagerServiceImpl::GetAuthMgr authMgrMap_ not found, token: %{public}llu.", tokenId); return authMgr_; // 查找不到新协议的authMgr时,返回旧协议authMgr,但可能为空 } @@ -342,10 +342,10 @@ std::shared_ptr DeviceManagerServiceImpl::GetAuthMgr() std::shared_ptr DeviceManagerServiceImpl::GetAuthMgrByTokenId(uint64_t tokenId) { if (authMgrMap_.find(tokenId) != authMgrMap_.end()) { - LOGI("DeviceManagerServiceImpl::GetAuthMgrByTokenId authMgrMap_ token: %{public}lu.", tokenId); + LOGI("DeviceManagerServiceImpl::GetAuthMgrByTokenId authMgrMap_ token: %{public}llu.", tokenId); return authMgrMap_[tokenId]; } - LOGE("DeviceManagerServiceImpl::GetAuthMgrByTokenId authMgrMap_ not found, token: %{public}lu.", tokenId); + LOGE("DeviceManagerServiceImpl::GetAuthMgrByTokenId authMgrMap_ not found, token: %{public}llu.", tokenId); return authMgr_; // 查找不到新协议的authMgr时,返回旧协议authMgr,但可能为空 } @@ -1171,7 +1171,7 @@ int32_t DeviceManagerServiceImpl::ImportAuthCode(const std::string &pkgName, con auto authMgr = GetAuthMgr(); if (authMgr == nullptr) { auto config = GetConfigByTokenId(); - LOGI("DeviceManagerServiceImpl::ImportAuthCode import for tokenId %{public}ld", config->tokenId); + LOGI("DeviceManagerServiceImpl::ImportAuthCode import for tokenId %{public}llu", config->tokenId); config->pkgName = pkgName; config->authCode = authCode; // 若多次注册,只保留最后一个 return DM_OK; @@ -1553,7 +1553,7 @@ void DeviceManagerServiceImpl::ScreenCommonEventCallback(std::string commonEvent LOGI("DeviceManagerServiceImpl::ScreenCommonEventCallback on screen locked."); for (auto& pair : authMgrMap_) { if (pair.second != nullptr) { - LOGD("DeviceManagerServiceImpl::ScreenCommonEventCallback tokenId: %{public}lu.", pair.first); + LOGD("DeviceManagerServiceImpl::ScreenCommonEventCallback tokenId: %{public}llu.", pair.first); pair.second->OnScreenLocked(); } } @@ -2008,7 +2008,7 @@ int32_t DeviceManagerServiceImpl::DeleteAcl(const std::string &sessionName, cons LOGE("Acl not contain the sessionName bind data."); return ERR_DM_FAILED; } - if (bindLevel == APP || bindLevel == SERVICE) { + if (bindLevel == static_cast(APP) || bindLevel == static_cast(SERVICE)) { if (offlineParam.leftAclNumber != 0) { LOGI("The sessionName unbind app-level type leftAclNumber not zero."); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); @@ -2034,11 +2034,11 @@ int32_t DeviceManagerServiceImpl::DeleteAcl(const std::string &sessionName, cons return DM_OK; } } - if (bindLevel == DEVICE && offlineParam.leftAclNumber != 0) { + if (bindLevel == static_cast(DEVICE) && offlineParam.leftAclNumber != 0) { LOGI("Unbind deivce-level, retain identical account bind type."); return DM_OK; } - if (bindLevel == DEVICE && offlineParam.leftAclNumber == 0) { + if (bindLevel == static_cast(DEVICE) && offlineParam.leftAclNumber == 0) { LOGI("Unbind deivce-level, retain null."); auto authMgr = GetAuthMgr(); if (authMgr == nullptr) { -- Gitee From bbfc28bf308e0cdbd593f160c58ac9b4e99da949 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Sat, 29 Mar 2025 19:37:55 +0800 Subject: [PATCH 349/382] =?UTF-8?q?=E8=B4=A6=E5=8F=B7=E9=80=80=E5=87=BA?= =?UTF-8?q?=E5=88=A0=E9=99=A4skid=E5=92=8CcredId?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../include/deviceprofile_connector.h | 8 ++ .../src/deviceprofile_connector.cpp | 78 +++++++++++++++++++ .../include/device_manager_service_impl.h | 2 +- .../device_manager_service_impl_lite.h | 2 +- .../src/device_manager_service_impl.cpp | 47 +++++++++-- .../src/device_manager_service_impl_lite.cpp | 3 +- .../include/idevice_manager_service_impl.h | 2 +- .../service/src/device_manager_service.cpp | 2 +- .../UTTest_device_manager_service_impl.cpp | 7 +- ...Test_device_manager_service_impl_first.cpp | 2 +- 10 files changed, 139 insertions(+), 14 deletions(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 1fac75678..4f444ea27 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -93,6 +93,11 @@ typedef struct DmOfflineParam { int32_t leftAclNumber; } DmOfflineParam; +typedef struct DmAcountLogOutParam { + std::vector skIdVec; + std::vector credIdVec; +} DmAcountLogOutParam; + namespace OHOS { namespace DistributedHardware { class IDeviceProfileConnector { @@ -137,6 +142,8 @@ public: int32_t GetDeviceAclParam(DmDiscoveryInfo discoveryInfo, bool &isOnline, int32_t &authForm); EXPORT bool DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, int32_t peerUserId); + EXPORT bool DeleteAclForAccountLogOut(DmAcountLogOutParam &acountParam, const std::string &localUdid, + int32_t localUserId, const std::string &peerUdid, int32_t peerUserId); EXPORT void DeleteAclForUserRemoved(std::string localUdid, int32_t userId); EXPORT void DeleteAclForRemoteUserRemoved(std::string peerUdid, int32_t peerUserId, std::vector &userIds); @@ -202,6 +209,7 @@ public: EXPORT std::multimap GetDevIdAndUserIdByActHash( const std::string &localUdid, const std::string &peerUdid, int32_t peerUserId, const std::string &peerAccountHash); + EXPORT std::string GetAccountIdByAccountHash(const std::string &peerAccountHash); EXPORT std::multimap GetDeviceIdAndUserId( const std::string &localUdid, int32_t localUserId); EXPORT void HandleSyncBackgroundUserIdEvent( diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 7a5844d45..dd504afaf 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -739,6 +739,55 @@ EXPORT bool DeviceProfileConnector::DeleteAclForAccountLogOut( return notifyOffline; } +EXPORT bool DeviceProfileConnector::DeleteAclForAccountLogOut(DmAcountLogOutParam &acountParam, + const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, int32_t peerUserId) +{ + LOGI("localUdid %{public}s, localUserId %{public}d, peerUdid %{public}s, peerUserId %{public}d.", + GetAnonyString(localUdid).c_str(), localUserId, GetAnonyString(peerUdid).c_str(), peerUserId); + std::vector profiles = GetAllAccessControlProfile(); + std::vector deleteProfiles; + bool notifyOffline = false; + bool isDelete = false; + for (const auto &item : profiles) { + if (item.GetTrustDeviceId() != peerUdid) { + continue; + } + std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); + std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); + int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); + int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); + if (accesserUdid == localUdid && accesserUserId == localUserId && + accesseeUdid == peerUdid && accesseeUserId == peerUserId) { + if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { + isDelete = true; + } + deleteProfiles.push_back(item); + acountParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); + acountParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialId()); + notifyOffline = (item.GetStatus() == ACTIVE); + continue; + } + if (accesserUdid == peerUdid && accesserUserId == peerUserId && + accesseeUdid == localUdid && accesseeUserId == localUserId) { + if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { + isDelete = true; + } + deleteProfiles.push_back(item); + acountParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); + acountParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialId()); + notifyOffline = (item.GetStatus() == ACTIVE); + continue; + } + } + if (!isDelete) { + return false; + } + for (const auto &item : deleteProfiles) { + DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); + } + return notifyOffline; +} + EXPORT void DeviceProfileConnector::DeleteAclForUserRemoved(std::string localUdid, int32_t userId) { @@ -1864,6 +1913,35 @@ void DeviceProfileConnector::UpdatePeerUserId(AccessControlProfile profile, std: } } +EXPORT std::string DeviceProfileConnector::GetAccountIdByAccountHash(const std::string &peerAccountHash) +{ + LOGI("peerAccountHash %{public}s", peerAccountHash.c_str()); + std::vector profiles = GetAllAccessControlProfile(); + for (const auto &item : profiles) { + std::string accesserAccountId = item.GetAccesser().GetAccesserAccountId(); + std::string accesseeAccountId = item.GetAccessee().GetAccesseeAccountId(); + char accesserAccountIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetAccountIdHash(accesserAccountId, reinterpret_cast(accesserAccountIdHash)) != DM_OK) { + LOGE("GetAccountHash failed."); + return deviceIdMap; + } + char accesseeAccountIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetAccountIdHash(accesseeAccountId, reinterpret_cast(accesseeAccountIdHash)) != DM_OK) { + LOGE("GetAccountHash failed."); + return deviceIdMap; + } + LOGI("accesserAccountIdHash %{public}s, accesseeAccountIdHash %{public}s", accesserAccountIdHash, + accesseeAccountIdHash); + if (std::string(accesserAccountIdHash) == peerAccountHash) { + return accesserAccountId; + } + if (std::string(accesseeAccountIdHash) == peerAccountHash) { + return accesseeAccountId; + } + } + return ""; +} + EXPORT std::multimap DeviceProfileConnector::GetDevIdAndUserIdByActHash( const std::string &localUdid, const std::string &peerUdid, int32_t peerUserId, const std::string &peerAccountHash) diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 93357e6c4..d78b554e2 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -145,7 +145,7 @@ public: int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId); void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, - int32_t peerUserId); + int32_t peerUserId, std::string accountId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 2ad955b5e..afc109752 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -139,7 +139,7 @@ public: void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, int32_t peerTokenId); void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, - int32_t peerUserId); + int32_t peerUserId, std::string accountId); void HandleUserRemoved(int32_t preUserId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); void HandleUserSwitched(const std::vector &deviceVec, int32_t currentUserId, diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 6ae1c6944..26b84c395 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -1490,12 +1490,30 @@ void DeviceManagerServiceImpl::LoadHardwareFwkService() } void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, - const std::string &peerUdid, int32_t peerUserId) + const std::string &peerUdid, int32_t peerUserId, std::string accountId) { LOGI("localUdid %{public}s, localUserId %{public}d, peerUdid %{public}s, peerUserId %{public}d.", GetAnonyString(localUdid).c_str(), localUserId, GetAnonyString(peerUdid).c_str(), peerUserId); - bool notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, - peerUdid, peerUserId); + bool notifyOffline = false; + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr_ is nullptr"); + return; + } + if (authMgr->isAuthNewVersion_) { + DmAcountLogOutParam acountParam; + notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(acountParam, + localUdid, localUserId, peerUdid, peerUserId); + for (auto skId : acountParam.skIdVec) { + DeviceProfileConnector::GetInstance().DeleteSessionKey(skId); + } + for (auto credId : acountParam.credIdVec) { + hiChainAuthConnector_->(accountId, credId); + } + } else { + notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, + peerUdid, peerUserId); + } if (notifyOffline) { ProcessInfo processInfo; processInfo.pkgName = std::string(DM_PKG_NAME); @@ -1628,13 +1646,32 @@ void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, co std::multimap devIdAndUserMap = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, remoteUdid, remoteUserId, remoteAccountHash); + std::string accountId = DeviceProfileConnector::GetInstance().GetAccountIdByAccountHash(remoteAccountHash); CHECK_NULL_VOID(listener_); std::string uuid = ""; SoftbusCache::GetInstance().GetUuidByUdid(remoteUdid, uuid); listener_->OnDeviceTrustChange(remoteUdid, uuid, DmAuthForm::IDENTICAL_ACCOUNT); for (const auto &item : devIdAndUserMap) { - bool notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(item.first, item.second, - remoteUdid, remoteUserId); + bool notifyOffline = false; + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr_ is nullptr"); + return; + } + if (authMgr->isAuthNewVersion_) { + DmAcountLogOutParam acountParam; + notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(acountParam, + localUdid, localUserId, peerUdid, peerUserId); + for (auto skId : acountParam.skIdVec) { + DeviceProfileConnector::GetInstance().DeleteSessionKey(skId); + } + for (auto credId : acountParam.credIdVec) { + hiChainAuthConnector_->(accountId, credId); + } + } else { + notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, + peerUdid, peerUserId); + } if (notifyOffline) { ProcessInfo processInfo; processInfo.pkgName = std::string(DM_PKG_NAME); diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index f82b8f95f..e730925bf 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -490,12 +490,13 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const } void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, - const std::string &peerUdid, int32_t peerUserId) + const std::string &peerUdid, int32_t peerUserId, std::string accountId) { (void)localUdid; (void)localUserId; (void)peerUdid; (void)peerUserId; + (void)accountId; return; } diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index fcccfc92b..8fb225de6 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -239,7 +239,7 @@ public: virtual int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId) = 0; virtual void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, - const std::string &peerUdid, int32_t peerUserId) = 0; + const std::string &peerUdid, int32_t peerUserId, std::string accountId) = 0; virtual void HandleUserRemoved(int32_t preUserId) = 0; virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; virtual void HandleUserSwitched(const std::vector &deviceVec, int32_t currentUserId, diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 83cf450f3..11b310500 100644 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2103,7 +2103,7 @@ void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string SendAccountLogoutBroadCast(peerUdids, std::string(accountIdHash), accountName, userId); } for (const auto &item : deviceMap) { - dmServiceImpl_->HandleIdentAccountLogout(localUdid, userId, item.first, item.second); + dmServiceImpl_->HandleIdentAccountLogout(localUdid, userId, item.first, item.second, accountId); } } diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 7c5db51b4..22d0615dd 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -473,8 +473,9 @@ HWTEST_F(DeviceManagerServiceImplTest, NotifyEvent_005, testing::ext::TestSize.L int32_t localUserId = 123; std::string peerUdid = "peerUdid"; int32_t peerUserId = 456; + std::string accountId = "accountId"; EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _)).WillOnce(Return(true)); - deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId); + deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId, accountId); EXPECT_CALL(*dmDeviceStateManagerMock_, ProcNotifyEvent(_, _)).WillOnce(Return(DM_OK)); int ret = deviceManagerServiceImpl_->NotifyEvent(pkgName, eventId, event); @@ -1525,7 +1526,7 @@ HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_104, testing::ext::TestSize. std::string accountId = "60008"; EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _)) .Times(::testing::AtLeast(1)).WillOnce(Return(true)); - deviceManagerServiceImpl_->HandleIdentAccountLogout(udid, userId, udid, userId); + deviceManagerServiceImpl_->HandleIdentAccountLogout(udid, userId, udid, userId, accountId); deviceManagerServiceImpl_->HandleUserRemoved(userId); deviceManagerServiceImpl_->HandleDeviceNotTrust(udid); EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); @@ -1879,7 +1880,7 @@ HWTEST_F(DeviceManagerServiceImplTest, GetDeviceIdAndUserId_001, testing::ext::T if (deviceManagerServiceImpl_->deviceStateMgr_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } - deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId); + deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId, accountId); std::vector foregroundUserIds; std::vector backgroundUserIds; diff --git a/test/unittest/UTTest_device_manager_service_impl_first.cpp b/test/unittest/UTTest_device_manager_service_impl_first.cpp index c01e5136a..569a7d96f 100644 --- a/test/unittest/UTTest_device_manager_service_impl_first.cpp +++ b/test/unittest/UTTest_device_manager_service_impl_first.cpp @@ -73,7 +73,7 @@ HWTEST_F(DeviceManagerServiceImplFirstTest, GetDeviceIdAndUserId_101, testing::e if (deviceManagerServiceImpl_->deviceStateMgr_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } - deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId); + deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId, accountId); std::vector foregroundUserIds; std::vector backgroundUserIds; -- Gitee From 60b68dc303e0502426832fa68fde81616b95f003 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Sat, 29 Mar 2025 20:10:39 +0800 Subject: [PATCH 350/382] fix TransitionTo --- .../authentication_v2/dm_auth_state_machine.h | 3 +- .../dm_auth_state_machine.cpp | 42 ++++++++++++------- 2 files changed, 30 insertions(+), 15 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state_machine.h b/services/implementation/include/authentication_v2/dm_auth_state_machine.h index 65ce5b3a0..b41ce4820 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state_machine.h +++ b/services/implementation/include/authentication_v2/dm_auth_state_machine.h @@ -78,7 +78,7 @@ private: void InsertSinkTransTable(); // Fetch the current state and execute it - std::optional> FetchState(); + std::optional> FetchAndSetCurState(); void SetCurState(DmAuthStateType state); @@ -111,6 +111,7 @@ private: // Direction of authentication DmAuthDirection direction_; + int32_t reason{DM_OK}; }; } // namespace DistributedHardware diff --git a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp index ab0896277..21680b981 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state_machine.cpp @@ -166,18 +166,26 @@ int32_t DmAuthStateMachine::TransitionTo(std::shared_ptr state) { int32_t ret = DM_OK; DmAuthStateType nextState = state->GetStateType(); - std::lock_guard lock(stateMutex_); - if (this->CheckStateTransitValid(nextState)) { - LOGI("DmAuthStateMachine: The state transition from %{public}d to %{public}d.", - GetCurState(), nextState); - statesQueue_.push(state); - stateCv_.notify_one(); - } else { - // The state transition is invalid. - LOGE("DmAuthStateMachine: The state transition does not meet the rule from %{public}d to %{public}d.", - GetCurState(), nextState); - ret = ERR_DM_NEXT_STATE_INVALID; + { + std::lock_guard lock(stateMutex_); + if (this->CheckStateTransitValid(nextState)) { + LOGI("DmAuthStateMachine: The state transition from %{public}d to %{public}d.", + GetCurState(), nextState); + statesQueue_.push(state); + } else { + // The state transition is invalid. + LOGE("DmAuthStateMachine: The state transition does not meet the rule from %{public}d to %{public}d.", + GetCurState(), nextState); + ret = ERR_DM_NEXT_STATE_INVALID; + reason = ERR_DM_NEXT_STATE_INVALID; + if (direction_ == DM_AUTH_SOURCE) { + statesQueue_.push(std::make_shared()); + } else { + statesQueue_.push(std::make_shared()); + } + } } + stateCv_.notify_one(); return ret; } @@ -245,10 +253,15 @@ void DmAuthStateMachine::NotifyEventFinish(DmEventType eventType) void DmAuthStateMachine::Run(std::shared_ptr context) { while (running_.load()) { - auto state = FetchState(); + auto state = FetchAndSetCurState(); + if (!state.has_value()) { + break; + } + if (reason != DM_OK) { + context->reason = reason; + } // Obtain the status and execute the status action. DmAuthStateType stateType = state.value()->GetStateType(); - this->SetCurState(stateType); int32_t ret = state.value()->Action(context); if (ret != DM_OK) { LOGE("DmAuthStateMachine::Run err:%{public}d", ret); @@ -268,7 +281,7 @@ void DmAuthStateMachine::Run(std::shared_ptr context) LOGI("DmAuthStateMachine::Run end"); } -std::optional> DmAuthStateMachine::FetchState() +std::optional> DmAuthStateMachine::FetchAndSetCurState() { std::unique_lock lock(stateMutex_); stateCv_.wait(lock, [&] { @@ -279,6 +292,7 @@ std::optional> DmAuthStateMachine::FetchState() std::shared_ptr state = statesQueue_.front(); statesQueue_.pop(); + SetCurState(state->GetStateType()); return state; } -- Gitee From 5e4cb16e7544cd82c5d077e0675d80e384bfbb8f Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Sat, 29 Mar 2025 20:14:27 +0800 Subject: [PATCH 351/382] =?UTF-8?q?=E8=B4=A6=E5=8F=B7=E9=80=80=E5=87=BA?= =?UTF-8?q?=E5=88=A0=E9=99=A4credid=E5=92=8Cskid?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Signed-off-by: gaoqiang_strong --- .../include/deviceprofile_connector.h | 1 - .../src/deviceprofile_connector.cpp | 29 ------------------- .../include/device_manager_service_impl.h | 2 +- .../device_manager_service_impl_lite.h | 2 +- .../src/device_manager_service_impl.cpp | 9 +++--- .../src/device_manager_service_impl_lite.cpp | 3 +- .../include/idevice_manager_service_impl.h | 2 +- .../service/src/device_manager_service.cpp | 2 +- .../UTTest_device_manager_service_impl.cpp | 6 ++-- ...Test_device_manager_service_impl_first.cpp | 2 +- 10 files changed, 14 insertions(+), 44 deletions(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 4f444ea27..f94ff5c92 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -209,7 +209,6 @@ public: EXPORT std::multimap GetDevIdAndUserIdByActHash( const std::string &localUdid, const std::string &peerUdid, int32_t peerUserId, const std::string &peerAccountHash); - EXPORT std::string GetAccountIdByAccountHash(const std::string &peerAccountHash); EXPORT std::multimap GetDeviceIdAndUserId( const std::string &localUdid, int32_t localUserId); EXPORT void HandleSyncBackgroundUserIdEvent( diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index dd504afaf..489bcca2a 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -1913,35 +1913,6 @@ void DeviceProfileConnector::UpdatePeerUserId(AccessControlProfile profile, std: } } -EXPORT std::string DeviceProfileConnector::GetAccountIdByAccountHash(const std::string &peerAccountHash) -{ - LOGI("peerAccountHash %{public}s", peerAccountHash.c_str()); - std::vector profiles = GetAllAccessControlProfile(); - for (const auto &item : profiles) { - std::string accesserAccountId = item.GetAccesser().GetAccesserAccountId(); - std::string accesseeAccountId = item.GetAccessee().GetAccesseeAccountId(); - char accesserAccountIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; - if (Crypto::GetAccountIdHash(accesserAccountId, reinterpret_cast(accesserAccountIdHash)) != DM_OK) { - LOGE("GetAccountHash failed."); - return deviceIdMap; - } - char accesseeAccountIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; - if (Crypto::GetAccountIdHash(accesseeAccountId, reinterpret_cast(accesseeAccountIdHash)) != DM_OK) { - LOGE("GetAccountHash failed."); - return deviceIdMap; - } - LOGI("accesserAccountIdHash %{public}s, accesseeAccountIdHash %{public}s", accesserAccountIdHash, - accesseeAccountIdHash); - if (std::string(accesserAccountIdHash) == peerAccountHash) { - return accesserAccountId; - } - if (std::string(accesseeAccountIdHash) == peerAccountHash) { - return accesseeAccountId; - } - } - return ""; -} - EXPORT std::multimap DeviceProfileConnector::GetDevIdAndUserIdByActHash( const std::string &localUdid, const std::string &peerUdid, int32_t peerUserId, const std::string &peerAccountHash) diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index d78b554e2..93357e6c4 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -145,7 +145,7 @@ public: int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId); void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, - int32_t peerUserId, std::string accountId); + int32_t peerUserId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index afc109752..2ad955b5e 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -139,7 +139,7 @@ public: void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, int32_t peerTokenId); void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, - int32_t peerUserId, std::string accountId); + int32_t peerUserId); void HandleUserRemoved(int32_t preUserId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); void HandleUserSwitched(const std::vector &deviceVec, int32_t currentUserId, diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 26b84c395..f9d387103 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -1490,7 +1490,7 @@ void DeviceManagerServiceImpl::LoadHardwareFwkService() } void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, - const std::string &peerUdid, int32_t peerUserId, std::string accountId) + const std::string &peerUdid, int32_t peerUserId) { LOGI("localUdid %{public}s, localUserId %{public}d, peerUdid %{public}s, peerUserId %{public}d.", GetAnonyString(localUdid).c_str(), localUserId, GetAnonyString(peerUdid).c_str(), peerUserId); @@ -1507,8 +1507,9 @@ void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &local for (auto skId : acountParam.skIdVec) { DeviceProfileConnector::GetInstance().DeleteSessionKey(skId); } + int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); for (auto credId : acountParam.credIdVec) { - hiChainAuthConnector_->(accountId, credId); + hiChainAuthConnector_->DeleteCredential(accountId, credId); } } else { notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, @@ -1646,7 +1647,6 @@ void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, co std::multimap devIdAndUserMap = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, remoteUdid, remoteUserId, remoteAccountHash); - std::string accountId = DeviceProfileConnector::GetInstance().GetAccountIdByAccountHash(remoteAccountHash); CHECK_NULL_VOID(listener_); std::string uuid = ""; SoftbusCache::GetInstance().GetUuidByUdid(remoteUdid, uuid); @@ -1665,8 +1665,9 @@ void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, co for (auto skId : acountParam.skIdVec) { DeviceProfileConnector::GetInstance().DeleteSessionKey(skId); } + int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); for (auto credId : acountParam.credIdVec) { - hiChainAuthConnector_->(accountId, credId); + hiChainAuthConnector_->DeleteCredential(accountId, credId); } } else { notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index e730925bf..f82b8f95f 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -490,13 +490,12 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const } void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, - const std::string &peerUdid, int32_t peerUserId, std::string accountId) + const std::string &peerUdid, int32_t peerUserId) { (void)localUdid; (void)localUserId; (void)peerUdid; (void)peerUserId; - (void)accountId; return; } diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 8fb225de6..fcccfc92b 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -239,7 +239,7 @@ public: virtual int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId) = 0; virtual void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, - const std::string &peerUdid, int32_t peerUserId, std::string accountId) = 0; + const std::string &peerUdid, int32_t peerUserId) = 0; virtual void HandleUserRemoved(int32_t preUserId) = 0; virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; virtual void HandleUserSwitched(const std::vector &deviceVec, int32_t currentUserId, diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 11b310500..83cf450f3 100644 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2103,7 +2103,7 @@ void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string SendAccountLogoutBroadCast(peerUdids, std::string(accountIdHash), accountName, userId); } for (const auto &item : deviceMap) { - dmServiceImpl_->HandleIdentAccountLogout(localUdid, userId, item.first, item.second, accountId); + dmServiceImpl_->HandleIdentAccountLogout(localUdid, userId, item.first, item.second); } } diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 22d0615dd..8dfe8120c 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -475,7 +475,7 @@ HWTEST_F(DeviceManagerServiceImplTest, NotifyEvent_005, testing::ext::TestSize.L int32_t peerUserId = 456; std::string accountId = "accountId"; EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _)).WillOnce(Return(true)); - deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId, accountId); + deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId); EXPECT_CALL(*dmDeviceStateManagerMock_, ProcNotifyEvent(_, _)).WillOnce(Return(DM_OK)); int ret = deviceManagerServiceImpl_->NotifyEvent(pkgName, eventId, event); @@ -1526,7 +1526,7 @@ HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_104, testing::ext::TestSize. std::string accountId = "60008"; EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _)) .Times(::testing::AtLeast(1)).WillOnce(Return(true)); - deviceManagerServiceImpl_->HandleIdentAccountLogout(udid, userId, udid, userId, accountId); + deviceManagerServiceImpl_->HandleIdentAccountLogout(udid, userId, udid, userId); deviceManagerServiceImpl_->HandleUserRemoved(userId); deviceManagerServiceImpl_->HandleDeviceNotTrust(udid); EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); @@ -1880,7 +1880,7 @@ HWTEST_F(DeviceManagerServiceImplTest, GetDeviceIdAndUserId_001, testing::ext::T if (deviceManagerServiceImpl_->deviceStateMgr_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } - deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId, accountId); + deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId); std::vector foregroundUserIds; std::vector backgroundUserIds; diff --git a/test/unittest/UTTest_device_manager_service_impl_first.cpp b/test/unittest/UTTest_device_manager_service_impl_first.cpp index 569a7d96f..c01e5136a 100644 --- a/test/unittest/UTTest_device_manager_service_impl_first.cpp +++ b/test/unittest/UTTest_device_manager_service_impl_first.cpp @@ -73,7 +73,7 @@ HWTEST_F(DeviceManagerServiceImplFirstTest, GetDeviceIdAndUserId_101, testing::e if (deviceManagerServiceImpl_->deviceStateMgr_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } - deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId, accountId); + deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId); std::vector foregroundUserIds; std::vector backgroundUserIds; -- Gitee From ca636f380b02dca851cefb46e44ecde1b3d1216f Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Sat, 29 Mar 2025 20:55:24 +0800 Subject: [PATCH 352/382] =?UTF-8?q?Revert=20"=E8=B4=A6=E5=8F=B7=E9=80=80?= =?UTF-8?q?=E5=87=BA=E5=88=A0=E9=99=A4credid=E5=92=8Cskid"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit 5e4cb16e7544cd82c5d077e0675d80e384bfbb8f. --- .../include/deviceprofile_connector.h | 1 + .../src/deviceprofile_connector.cpp | 29 +++++++++++++++++++ .../include/device_manager_service_impl.h | 2 +- .../device_manager_service_impl_lite.h | 2 +- .../src/device_manager_service_impl.cpp | 9 +++--- .../src/device_manager_service_impl_lite.cpp | 3 +- .../include/idevice_manager_service_impl.h | 2 +- .../service/src/device_manager_service.cpp | 2 +- .../UTTest_device_manager_service_impl.cpp | 6 ++-- ...Test_device_manager_service_impl_first.cpp | 2 +- 10 files changed, 44 insertions(+), 14 deletions(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index f94ff5c92..4f444ea27 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -209,6 +209,7 @@ public: EXPORT std::multimap GetDevIdAndUserIdByActHash( const std::string &localUdid, const std::string &peerUdid, int32_t peerUserId, const std::string &peerAccountHash); + EXPORT std::string GetAccountIdByAccountHash(const std::string &peerAccountHash); EXPORT std::multimap GetDeviceIdAndUserId( const std::string &localUdid, int32_t localUserId); EXPORT void HandleSyncBackgroundUserIdEvent( diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index 489bcca2a..dd504afaf 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -1913,6 +1913,35 @@ void DeviceProfileConnector::UpdatePeerUserId(AccessControlProfile profile, std: } } +EXPORT std::string DeviceProfileConnector::GetAccountIdByAccountHash(const std::string &peerAccountHash) +{ + LOGI("peerAccountHash %{public}s", peerAccountHash.c_str()); + std::vector profiles = GetAllAccessControlProfile(); + for (const auto &item : profiles) { + std::string accesserAccountId = item.GetAccesser().GetAccesserAccountId(); + std::string accesseeAccountId = item.GetAccessee().GetAccesseeAccountId(); + char accesserAccountIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetAccountIdHash(accesserAccountId, reinterpret_cast(accesserAccountIdHash)) != DM_OK) { + LOGE("GetAccountHash failed."); + return deviceIdMap; + } + char accesseeAccountIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; + if (Crypto::GetAccountIdHash(accesseeAccountId, reinterpret_cast(accesseeAccountIdHash)) != DM_OK) { + LOGE("GetAccountHash failed."); + return deviceIdMap; + } + LOGI("accesserAccountIdHash %{public}s, accesseeAccountIdHash %{public}s", accesserAccountIdHash, + accesseeAccountIdHash); + if (std::string(accesserAccountIdHash) == peerAccountHash) { + return accesserAccountId; + } + if (std::string(accesseeAccountIdHash) == peerAccountHash) { + return accesseeAccountId; + } + } + return ""; +} + EXPORT std::multimap DeviceProfileConnector::GetDevIdAndUserIdByActHash( const std::string &localUdid, const std::string &peerUdid, int32_t peerUserId, const std::string &peerAccountHash) diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 93357e6c4..d78b554e2 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -145,7 +145,7 @@ public: int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId); void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, - int32_t peerUserId); + int32_t peerUserId, std::string accountId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index 2ad955b5e..afc109752 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -139,7 +139,7 @@ public: void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, int32_t peerTokenId); void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, - int32_t peerUserId); + int32_t peerUserId, std::string accountId); void HandleUserRemoved(int32_t preUserId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); void HandleUserSwitched(const std::vector &deviceVec, int32_t currentUserId, diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index f9d387103..26b84c395 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -1490,7 +1490,7 @@ void DeviceManagerServiceImpl::LoadHardwareFwkService() } void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, - const std::string &peerUdid, int32_t peerUserId) + const std::string &peerUdid, int32_t peerUserId, std::string accountId) { LOGI("localUdid %{public}s, localUserId %{public}d, peerUdid %{public}s, peerUserId %{public}d.", GetAnonyString(localUdid).c_str(), localUserId, GetAnonyString(peerUdid).c_str(), peerUserId); @@ -1507,9 +1507,8 @@ void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &local for (auto skId : acountParam.skIdVec) { DeviceProfileConnector::GetInstance().DeleteSessionKey(skId); } - int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); for (auto credId : acountParam.credIdVec) { - hiChainAuthConnector_->DeleteCredential(accountId, credId); + hiChainAuthConnector_->(accountId, credId); } } else { notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, @@ -1647,6 +1646,7 @@ void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, co std::multimap devIdAndUserMap = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, remoteUdid, remoteUserId, remoteAccountHash); + std::string accountId = DeviceProfileConnector::GetInstance().GetAccountIdByAccountHash(remoteAccountHash); CHECK_NULL_VOID(listener_); std::string uuid = ""; SoftbusCache::GetInstance().GetUuidByUdid(remoteUdid, uuid); @@ -1665,9 +1665,8 @@ void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, co for (auto skId : acountParam.skIdVec) { DeviceProfileConnector::GetInstance().DeleteSessionKey(skId); } - int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); for (auto credId : acountParam.credIdVec) { - hiChainAuthConnector_->DeleteCredential(accountId, credId); + hiChainAuthConnector_->(accountId, credId); } } else { notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index f82b8f95f..e730925bf 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -490,12 +490,13 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const } void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, - const std::string &peerUdid, int32_t peerUserId) + const std::string &peerUdid, int32_t peerUserId, std::string accountId) { (void)localUdid; (void)localUserId; (void)peerUdid; (void)peerUserId; + (void)accountId; return; } diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index fcccfc92b..8fb225de6 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -239,7 +239,7 @@ public: virtual int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId) = 0; virtual void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, - const std::string &peerUdid, int32_t peerUserId) = 0; + const std::string &peerUdid, int32_t peerUserId, std::string accountId) = 0; virtual void HandleUserRemoved(int32_t preUserId) = 0; virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; virtual void HandleUserSwitched(const std::vector &deviceVec, int32_t currentUserId, diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 83cf450f3..11b310500 100644 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2103,7 +2103,7 @@ void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string SendAccountLogoutBroadCast(peerUdids, std::string(accountIdHash), accountName, userId); } for (const auto &item : deviceMap) { - dmServiceImpl_->HandleIdentAccountLogout(localUdid, userId, item.first, item.second); + dmServiceImpl_->HandleIdentAccountLogout(localUdid, userId, item.first, item.second, accountId); } } diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 8dfe8120c..22d0615dd 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -475,7 +475,7 @@ HWTEST_F(DeviceManagerServiceImplTest, NotifyEvent_005, testing::ext::TestSize.L int32_t peerUserId = 456; std::string accountId = "accountId"; EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _)).WillOnce(Return(true)); - deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId); + deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId, accountId); EXPECT_CALL(*dmDeviceStateManagerMock_, ProcNotifyEvent(_, _)).WillOnce(Return(DM_OK)); int ret = deviceManagerServiceImpl_->NotifyEvent(pkgName, eventId, event); @@ -1526,7 +1526,7 @@ HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_104, testing::ext::TestSize. std::string accountId = "60008"; EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _)) .Times(::testing::AtLeast(1)).WillOnce(Return(true)); - deviceManagerServiceImpl_->HandleIdentAccountLogout(udid, userId, udid, userId); + deviceManagerServiceImpl_->HandleIdentAccountLogout(udid, userId, udid, userId, accountId); deviceManagerServiceImpl_->HandleUserRemoved(userId); deviceManagerServiceImpl_->HandleDeviceNotTrust(udid); EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); @@ -1880,7 +1880,7 @@ HWTEST_F(DeviceManagerServiceImplTest, GetDeviceIdAndUserId_001, testing::ext::T if (deviceManagerServiceImpl_->deviceStateMgr_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } - deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId); + deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId, accountId); std::vector foregroundUserIds; std::vector backgroundUserIds; diff --git a/test/unittest/UTTest_device_manager_service_impl_first.cpp b/test/unittest/UTTest_device_manager_service_impl_first.cpp index c01e5136a..569a7d96f 100644 --- a/test/unittest/UTTest_device_manager_service_impl_first.cpp +++ b/test/unittest/UTTest_device_manager_service_impl_first.cpp @@ -73,7 +73,7 @@ HWTEST_F(DeviceManagerServiceImplFirstTest, GetDeviceIdAndUserId_101, testing::e if (deviceManagerServiceImpl_->deviceStateMgr_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } - deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId); + deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId, accountId); std::vector foregroundUserIds; std::vector backgroundUserIds; -- Gitee From b8418e0af453c3912b490302ba84e5335cf62ef5 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Sat, 29 Mar 2025 20:55:38 +0800 Subject: [PATCH 353/382] =?UTF-8?q?Revert=20"=E8=B4=A6=E5=8F=B7=E9=80=80?= =?UTF-8?q?=E5=87=BA=E5=88=A0=E9=99=A4skid=E5=92=8CcredId"?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit This reverts commit bbfc28bf308e0cdbd593f160c58ac9b4e99da949. --- .../include/deviceprofile_connector.h | 8 -- .../src/deviceprofile_connector.cpp | 78 ------------------- .../include/device_manager_service_impl.h | 2 +- .../device_manager_service_impl_lite.h | 2 +- .../src/device_manager_service_impl.cpp | 47 ++--------- .../src/device_manager_service_impl_lite.cpp | 3 +- .../include/idevice_manager_service_impl.h | 2 +- .../service/src/device_manager_service.cpp | 2 +- .../UTTest_device_manager_service_impl.cpp | 7 +- ...Test_device_manager_service_impl_first.cpp | 2 +- 10 files changed, 14 insertions(+), 139 deletions(-) diff --git a/commondependency/include/deviceprofile_connector.h b/commondependency/include/deviceprofile_connector.h index 4f444ea27..1fac75678 100644 --- a/commondependency/include/deviceprofile_connector.h +++ b/commondependency/include/deviceprofile_connector.h @@ -93,11 +93,6 @@ typedef struct DmOfflineParam { int32_t leftAclNumber; } DmOfflineParam; -typedef struct DmAcountLogOutParam { - std::vector skIdVec; - std::vector credIdVec; -} DmAcountLogOutParam; - namespace OHOS { namespace DistributedHardware { class IDeviceProfileConnector { @@ -142,8 +137,6 @@ public: int32_t GetDeviceAclParam(DmDiscoveryInfo discoveryInfo, bool &isOnline, int32_t &authForm); EXPORT bool DeleteAclForAccountLogOut(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, int32_t peerUserId); - EXPORT bool DeleteAclForAccountLogOut(DmAcountLogOutParam &acountParam, const std::string &localUdid, - int32_t localUserId, const std::string &peerUdid, int32_t peerUserId); EXPORT void DeleteAclForUserRemoved(std::string localUdid, int32_t userId); EXPORT void DeleteAclForRemoteUserRemoved(std::string peerUdid, int32_t peerUserId, std::vector &userIds); @@ -209,7 +202,6 @@ public: EXPORT std::multimap GetDevIdAndUserIdByActHash( const std::string &localUdid, const std::string &peerUdid, int32_t peerUserId, const std::string &peerAccountHash); - EXPORT std::string GetAccountIdByAccountHash(const std::string &peerAccountHash); EXPORT std::multimap GetDeviceIdAndUserId( const std::string &localUdid, int32_t localUserId); EXPORT void HandleSyncBackgroundUserIdEvent( diff --git a/commondependency/src/deviceprofile_connector.cpp b/commondependency/src/deviceprofile_connector.cpp index dd504afaf..7a5844d45 100644 --- a/commondependency/src/deviceprofile_connector.cpp +++ b/commondependency/src/deviceprofile_connector.cpp @@ -739,55 +739,6 @@ EXPORT bool DeviceProfileConnector::DeleteAclForAccountLogOut( return notifyOffline; } -EXPORT bool DeviceProfileConnector::DeleteAclForAccountLogOut(DmAcountLogOutParam &acountParam, - const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, int32_t peerUserId) -{ - LOGI("localUdid %{public}s, localUserId %{public}d, peerUdid %{public}s, peerUserId %{public}d.", - GetAnonyString(localUdid).c_str(), localUserId, GetAnonyString(peerUdid).c_str(), peerUserId); - std::vector profiles = GetAllAccessControlProfile(); - std::vector deleteProfiles; - bool notifyOffline = false; - bool isDelete = false; - for (const auto &item : profiles) { - if (item.GetTrustDeviceId() != peerUdid) { - continue; - } - std::string accesserUdid = item.GetAccesser().GetAccesserDeviceId(); - std::string accesseeUdid = item.GetAccessee().GetAccesseeDeviceId(); - int32_t accesserUserId = item.GetAccesser().GetAccesserUserId(); - int32_t accesseeUserId = item.GetAccessee().GetAccesseeUserId(); - if (accesserUdid == localUdid && accesserUserId == localUserId && - accesseeUdid == peerUdid && accesseeUserId == peerUserId) { - if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { - isDelete = true; - } - deleteProfiles.push_back(item); - acountParam.skIdVec.push_back(item.GetAccesser().GetAccesserSessionKeyId()); - acountParam.credIdVec.push_back(item.GetAccesser().GetAccesserCredentialId()); - notifyOffline = (item.GetStatus() == ACTIVE); - continue; - } - if (accesserUdid == peerUdid && accesserUserId == peerUserId && - accesseeUdid == localUdid && accesseeUserId == localUserId) { - if (item.GetBindType() == DM_IDENTICAL_ACCOUNT) { - isDelete = true; - } - deleteProfiles.push_back(item); - acountParam.skIdVec.push_back(item.GetAccessee().GetAccesseeSessionKeyId()); - acountParam.credIdVec.push_back(item.GetAccessee().GetAccesseeCredentialId()); - notifyOffline = (item.GetStatus() == ACTIVE); - continue; - } - } - if (!isDelete) { - return false; - } - for (const auto &item : deleteProfiles) { - DistributedDeviceProfileClient::GetInstance().DeleteAccessControlProfile(item.GetAccessControlId()); - } - return notifyOffline; -} - EXPORT void DeviceProfileConnector::DeleteAclForUserRemoved(std::string localUdid, int32_t userId) { @@ -1913,35 +1864,6 @@ void DeviceProfileConnector::UpdatePeerUserId(AccessControlProfile profile, std: } } -EXPORT std::string DeviceProfileConnector::GetAccountIdByAccountHash(const std::string &peerAccountHash) -{ - LOGI("peerAccountHash %{public}s", peerAccountHash.c_str()); - std::vector profiles = GetAllAccessControlProfile(); - for (const auto &item : profiles) { - std::string accesserAccountId = item.GetAccesser().GetAccesserAccountId(); - std::string accesseeAccountId = item.GetAccessee().GetAccesseeAccountId(); - char accesserAccountIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; - if (Crypto::GetAccountIdHash(accesserAccountId, reinterpret_cast(accesserAccountIdHash)) != DM_OK) { - LOGE("GetAccountHash failed."); - return deviceIdMap; - } - char accesseeAccountIdHash[DM_MAX_DEVICE_ID_LEN] = {0}; - if (Crypto::GetAccountIdHash(accesseeAccountId, reinterpret_cast(accesseeAccountIdHash)) != DM_OK) { - LOGE("GetAccountHash failed."); - return deviceIdMap; - } - LOGI("accesserAccountIdHash %{public}s, accesseeAccountIdHash %{public}s", accesserAccountIdHash, - accesseeAccountIdHash); - if (std::string(accesserAccountIdHash) == peerAccountHash) { - return accesserAccountId; - } - if (std::string(accesseeAccountIdHash) == peerAccountHash) { - return accesseeAccountId; - } - } - return ""; -} - EXPORT std::multimap DeviceProfileConnector::GetDevIdAndUserIdByActHash( const std::string &localUdid, const std::string &peerUdid, int32_t peerUserId, const std::string &peerAccountHash) diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index d78b554e2..93357e6c4 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -145,7 +145,7 @@ public: int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId); void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, - int32_t peerUserId, std::string accountId); + int32_t peerUserId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); int32_t StopAuthenticateDevice(const std::string &pkgName); void HandleCredentialAuthStatus(const std::string &deviceList, uint16_t deviceTypeId, int32_t errcode); diff --git a/services/implementation/include/device_manager_service_impl_lite.h b/services/implementation/include/device_manager_service_impl_lite.h index afc109752..2ad955b5e 100644 --- a/services/implementation/include/device_manager_service_impl_lite.h +++ b/services/implementation/include/device_manager_service_impl_lite.h @@ -139,7 +139,7 @@ public: void HandleAppUnBindEvent(int32_t remoteUserId, const std::string &remoteUdid, int32_t tokenId, int32_t peerTokenId); void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, const std::string &peerUdid, - int32_t peerUserId, std::string accountId); + int32_t peerUserId); void HandleUserRemoved(int32_t preUserId); void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo); void HandleUserSwitched(const std::vector &deviceVec, int32_t currentUserId, diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 26b84c395..6ae1c6944 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -1490,30 +1490,12 @@ void DeviceManagerServiceImpl::LoadHardwareFwkService() } void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, - const std::string &peerUdid, int32_t peerUserId, std::string accountId) + const std::string &peerUdid, int32_t peerUserId) { LOGI("localUdid %{public}s, localUserId %{public}d, peerUdid %{public}s, peerUserId %{public}d.", GetAnonyString(localUdid).c_str(), localUserId, GetAnonyString(peerUdid).c_str(), peerUserId); - bool notifyOffline = false; - auto authMgr = GetAuthMgr(); - if (authMgr == nullptr) { - LOGE("authMgr_ is nullptr"); - return; - } - if (authMgr->isAuthNewVersion_) { - DmAcountLogOutParam acountParam; - notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(acountParam, - localUdid, localUserId, peerUdid, peerUserId); - for (auto skId : acountParam.skIdVec) { - DeviceProfileConnector::GetInstance().DeleteSessionKey(skId); - } - for (auto credId : acountParam.credIdVec) { - hiChainAuthConnector_->(accountId, credId); - } - } else { - notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, - peerUdid, peerUserId); - } + bool notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, + peerUdid, peerUserId); if (notifyOffline) { ProcessInfo processInfo; processInfo.pkgName = std::string(DM_PKG_NAME); @@ -1646,32 +1628,13 @@ void DeviceManagerServiceImpl::HandleAccountLogoutEvent(int32_t remoteUserId, co std::multimap devIdAndUserMap = DeviceProfileConnector::GetInstance().GetDevIdAndUserIdByActHash(localUdid, remoteUdid, remoteUserId, remoteAccountHash); - std::string accountId = DeviceProfileConnector::GetInstance().GetAccountIdByAccountHash(remoteAccountHash); CHECK_NULL_VOID(listener_); std::string uuid = ""; SoftbusCache::GetInstance().GetUuidByUdid(remoteUdid, uuid); listener_->OnDeviceTrustChange(remoteUdid, uuid, DmAuthForm::IDENTICAL_ACCOUNT); for (const auto &item : devIdAndUserMap) { - bool notifyOffline = false; - auto authMgr = GetAuthMgr(); - if (authMgr == nullptr) { - LOGE("authMgr_ is nullptr"); - return; - } - if (authMgr->isAuthNewVersion_) { - DmAcountLogOutParam acountParam; - notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(acountParam, - localUdid, localUserId, peerUdid, peerUserId); - for (auto skId : acountParam.skIdVec) { - DeviceProfileConnector::GetInstance().DeleteSessionKey(skId); - } - for (auto credId : acountParam.credIdVec) { - hiChainAuthConnector_->(accountId, credId); - } - } else { - notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(localUdid, localUserId, - peerUdid, peerUserId); - } + bool notifyOffline = DeviceProfileConnector::GetInstance().DeleteAclForAccountLogOut(item.first, item.second, + remoteUdid, remoteUserId); if (notifyOffline) { ProcessInfo processInfo; processInfo.pkgName = std::string(DM_PKG_NAME); diff --git a/services/implementation/src/device_manager_service_impl_lite.cpp b/services/implementation/src/device_manager_service_impl_lite.cpp index e730925bf..f82b8f95f 100644 --- a/services/implementation/src/device_manager_service_impl_lite.cpp +++ b/services/implementation/src/device_manager_service_impl_lite.cpp @@ -490,13 +490,12 @@ void DeviceManagerServiceImpl::HandleAppUnBindEvent(int32_t remoteUserId, const } void DeviceManagerServiceImpl::HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, - const std::string &peerUdid, int32_t peerUserId, std::string accountId) + const std::string &peerUdid, int32_t peerUserId) { (void)localUdid; (void)localUserId; (void)peerUdid; (void)peerUserId; - (void)accountId; return; } diff --git a/services/service/include/idevice_manager_service_impl.h b/services/service/include/idevice_manager_service_impl.h index 8fb225de6..fcccfc92b 100644 --- a/services/service/include/idevice_manager_service_impl.h +++ b/services/service/include/idevice_manager_service_impl.h @@ -239,7 +239,7 @@ public: virtual int32_t GetBindLevel(const std::string &pkgName, const std::string &localUdid, const std::string &udid, uint64_t &tokenId) = 0; virtual void HandleIdentAccountLogout(const std::string &localUdid, int32_t localUserId, - const std::string &peerUdid, int32_t peerUserId, std::string accountId) = 0; + const std::string &peerUdid, int32_t peerUserId) = 0; virtual void HandleUserRemoved(int32_t preUserId) = 0; virtual void HandleDeviceScreenStatusChange(DmDeviceInfo &devInfo) = 0; virtual void HandleUserSwitched(const std::vector &deviceVec, int32_t currentUserId, diff --git a/services/service/src/device_manager_service.cpp b/services/service/src/device_manager_service.cpp index 11b310500..83cf450f3 100644 --- a/services/service/src/device_manager_service.cpp +++ b/services/service/src/device_manager_service.cpp @@ -2103,7 +2103,7 @@ void DeviceManagerService::HandleAccountLogout(int32_t userId, const std::string SendAccountLogoutBroadCast(peerUdids, std::string(accountIdHash), accountName, userId); } for (const auto &item : deviceMap) { - dmServiceImpl_->HandleIdentAccountLogout(localUdid, userId, item.first, item.second, accountId); + dmServiceImpl_->HandleIdentAccountLogout(localUdid, userId, item.first, item.second); } } diff --git a/test/unittest/UTTest_device_manager_service_impl.cpp b/test/unittest/UTTest_device_manager_service_impl.cpp index 22d0615dd..7c5db51b4 100644 --- a/test/unittest/UTTest_device_manager_service_impl.cpp +++ b/test/unittest/UTTest_device_manager_service_impl.cpp @@ -473,9 +473,8 @@ HWTEST_F(DeviceManagerServiceImplTest, NotifyEvent_005, testing::ext::TestSize.L int32_t localUserId = 123; std::string peerUdid = "peerUdid"; int32_t peerUserId = 456; - std::string accountId = "accountId"; EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _)).WillOnce(Return(true)); - deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId, accountId); + deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId); EXPECT_CALL(*dmDeviceStateManagerMock_, ProcNotifyEvent(_, _)).WillOnce(Return(DM_OK)); int ret = deviceManagerServiceImpl_->NotifyEvent(pkgName, eventId, event); @@ -1526,7 +1525,7 @@ HWTEST_F(DeviceManagerServiceImplTest, UnBindDevice_104, testing::ext::TestSize. std::string accountId = "60008"; EXPECT_CALL(*deviceProfileConnectorMock_, DeleteAclForAccountLogOut(_, _, _, _)) .Times(::testing::AtLeast(1)).WillOnce(Return(true)); - deviceManagerServiceImpl_->HandleIdentAccountLogout(udid, userId, udid, userId, accountId); + deviceManagerServiceImpl_->HandleIdentAccountLogout(udid, userId, udid, userId); deviceManagerServiceImpl_->HandleUserRemoved(userId); deviceManagerServiceImpl_->HandleDeviceNotTrust(udid); EXPECT_NE(ret, ERR_DM_INPUT_PARA_INVALID); @@ -1880,7 +1879,7 @@ HWTEST_F(DeviceManagerServiceImplTest, GetDeviceIdAndUserId_001, testing::ext::T if (deviceManagerServiceImpl_->deviceStateMgr_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } - deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId, accountId); + deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId); std::vector foregroundUserIds; std::vector backgroundUserIds; diff --git a/test/unittest/UTTest_device_manager_service_impl_first.cpp b/test/unittest/UTTest_device_manager_service_impl_first.cpp index 569a7d96f..c01e5136a 100644 --- a/test/unittest/UTTest_device_manager_service_impl_first.cpp +++ b/test/unittest/UTTest_device_manager_service_impl_first.cpp @@ -73,7 +73,7 @@ HWTEST_F(DeviceManagerServiceImplFirstTest, GetDeviceIdAndUserId_101, testing::e if (deviceManagerServiceImpl_->deviceStateMgr_ == nullptr) { deviceManagerServiceImpl_->Initialize(listener_); } - deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId, accountId); + deviceManagerServiceImpl_->HandleIdentAccountLogout(localUdid, localUserId, peerUdid, peerUserId); std::vector foregroundUserIds; std::vector backgroundUserIds; -- Gitee From 9e4418df9c4acb94daf7f99fe7ad0c5cf6c08156 Mon Sep 17 00:00:00 2001 From: zhangyunrui6 <463180417@qq.com> Date: Sat, 29 Mar 2025 21:22:29 +0800 Subject: [PATCH 354/382] onError default fail --- .../implementation/src/authentication_v2/auth_manager.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 8ee7eeb97..59e4a94fe 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -975,6 +975,10 @@ void AuthSrcManager::AuthDeviceError(int64_t requestId, int32_t errorCode) } context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); context_->authStateMachine->TransitionTo(std::make_shared()); + } else { + LOGI("AuthSrcManager::AuthDeviceError unexpected err."); + context_->reason = errorCode; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); } LOGI("AuthSrcManager::AuthDeviceError leave."); } @@ -991,6 +995,10 @@ void AuthSinkManager::AuthDeviceError(int64_t requestId, int32_t errorCode) } context_->authStateMachine->NotifyEventFinish(DmEventType::ON_ERROR); context_->authStateMachine->TransitionTo(std::make_shared()); + } else { + LOGI("AuthSinkManager::AuthDeviceError unexpected err."); + context_->reason = errorCode; + context_->authStateMachine->NotifyEventFinish(DmEventType::ON_FAIL); } LOGI("AuthSinkManager::AuthDeviceError leave."); } -- Gitee From 47d93d21a0b097f9bbe531f1dd0394d72f612c8b Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Sat, 29 Mar 2025 23:07:52 +0800 Subject: [PATCH 355/382] =?UTF-8?q?feat:=20=E5=87=AD=E6=8D=AE=E5=8D=8F?= =?UTF-8?q?=E5=95=86=E9=80=BB=E8=BE=91=E5=A4=84=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/auth_manager.h | 1 - .../authentication_v2/dm_auth_context.h | 11 +- .../dm_auth_message_processor.h | 1 + .../src/authentication_v2/auth_manager.cpp | 27 --- .../auth_stages/auth_acl.cpp | 4 +- .../auth_stages/auth_confirm.cpp | 28 +-- .../auth_stages/auth_credential.cpp | 10 + .../auth_stages/auth_negotiate.cpp | 27 ++- .../dm_auth_message_processor.cpp | 14 +- .../src/authentication_v2/dm_auth_state.cpp | 179 ++++++++++++++---- 10 files changed, 210 insertions(+), 92 deletions(-) diff --git a/services/implementation/include/authentication_v2/auth_manager.h b/services/implementation/include/authentication_v2/auth_manager.h index a3e952d20..93308dd04 100644 --- a/services/implementation/include/authentication_v2/auth_manager.h +++ b/services/implementation/include/authentication_v2/auth_manager.h @@ -136,7 +136,6 @@ private: 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); diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 20ab7f959..364e4e4ce 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -77,6 +77,14 @@ enum DmAuthScope { DM_AUTH_SCOPE_APP, }; +enum DmRole { + DM_ROLE_UNKNOWN = 0, + DM_ROLE_DEVICE = 1, + DM_ROLE_USER = 1, + DM_ROLE_SA, + DM_ROLE_FA, +}; + // Used for one-touch pairing struct DmPeerTargetAddress { // directly establish a Bluetooth connection @@ -115,6 +123,7 @@ struct DmAccess { std::string token; std::string networkId; std::string bundleName; // Stores the PacketName + std::string language; int64_t serviceId; // Reserved field, to be used in HM 6.0 std::string accesserHapSignature; int32_t bindLevel; @@ -139,9 +148,9 @@ struct DmAccess { std::vector accesserStrList; std::vector accesseeStrList; std::map credentialInfos; // map: , cred is string tranformed by json + std::vector credentialTypeLists; // point-to-point, same account, etc. // map: std::map aclProfiles; - std::vector credentialTypeLists; // point-to-point, same account, etc. std::string extraInfo; // Expandable field, JSON format, KV structure std::string openAuthDeviceId; }; diff --git a/services/implementation/include/authentication_v2/dm_auth_message_processor.h b/services/implementation/include/authentication_v2/dm_auth_message_processor.h index 7b036b51f..a024f8731 100644 --- a/services/implementation/include/authentication_v2/dm_auth_message_processor.h +++ b/services/implementation/include/authentication_v2/dm_auth_message_processor.h @@ -83,6 +83,7 @@ extern const char* TAG_IS_ONLINE; extern const char* TAG_IS_AUTHED; extern const char* TAG_CREDENTIAL_INFO; extern const char* TAG_CERT_INFO; +extern const char* TAG_LANGUAGE; // Accesser table content is used for ACL synchronization. extern const char* TAG_ACCESSER_DEVICE_ID; diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 59e4a94fe..089a40e2a 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -551,31 +551,6 @@ bool AuthManager::CheckProcessNameInWhiteList(const std::string &processName) return false; } -int32_t AuthManager::GetBindLevel(int32_t bindLevel) -{ -#ifdef DEVICE_MANAGER_COMMON_FLAG - LOGI("device_manager_common is true!"); - std::string processName = ""; - int32_t ret = AppManager::GetInstance().GetCallerProcessName(processName); - LOGI("GetBindLevel processName = %{public}s", GetAnonyString(processName).c_str()); - if (ret == DM_OK && CheckProcessNameInWhiteList(processName)) { - return DEVICE; - } -#endif - if (IsAllowDeviceBind()) { - if (static_cast(bindLevel) == INVALIED_TYPE || static_cast(bindLevel) > APP || - static_cast(bindLevel) < DEVICE) { - return DEVICE; - } - return bindLevel; - } - if (static_cast(bindLevel) == INVALIED_TYPE || (static_cast(bindLevel) != APP && - static_cast(bindLevel) != SERVICE)) { - return APP; - } - return bindLevel; -} - int32_t AuthManager::GetTokenIdByBundleName(int32_t userId, std::string &bundleName, int64_t &tokenId) { int32_t ret = AppManager::GetInstance().GetNativeTokenIdByName(bundleName, tokenId); @@ -629,7 +604,6 @@ void AuthManager::GetAuthParam(const std::string &sessionName, int32_t authType, context_->accesser.deviceName = context_->softbusConnector->GetLocalDeviceName(); context_->accesser.deviceType = context_->softbusConnector->GetLocalDeviceTypeId(); context_->accesser.isOnline = false; - context_->accesser.bindLevel = INVALIED_TYPE; context_->accessee.deviceId = deviceId; context_->accessee.addr = deviceId; @@ -642,7 +616,6 @@ void AuthManager::GetAuthParam(const std::string &sessionName, int32_t authType, GetAuthIds(realPkgName, sessionName, jsonObject); context_->accesser.token = std::to_string(GenRandInt(MIN_PIN_TOKEN, MAX_PIN_TOKEN)); - context_->accesser.bindLevel = this->GetBindLevel(context_->accesser.bindLevel); } void AuthManager::InitAuthState(const std::string &sessionName, int32_t authType, diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index 1691ca298..c5d24a1db 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -51,9 +51,9 @@ int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) Crypto::Sha256(std::to_string(context->accesser.tokenId)) == context->accesser.tokenIdHash && context->accesser.bindLevel == context->accessee.bindLevel; - if (!isSame) { - LOGE("data between two stages different, stop auth"); + LOGE("data between two stages different with bindLevel %{public}d to %{public}d, stop auth", + context->accesser.bindLevel, context->accessee.bindLevel); context->reply = ERR_DM_QUADRUPLE_NOT_SAME; context->reason = ERR_DM_QUADRUPLE_NOT_SAME; context->state = static_cast(GetStateType()); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index d413cd6cc..c23f40734 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -59,17 +59,11 @@ void AuthSrcConfirmState::NegotiateCredential(std::shared_ptr con std::set_intersection(srcCredTypeList.begin(), srcCredTypeList.end(), sinkCredTypeList.begin(), sinkCredTypeList.end(), std::back_inserter(intersection)); - if (context->accessee.tokenIdHash.empty()) { - context->accesser.bindLevel = SERVICE; // SA-SA - } else { - context->accesser.bindLevel = APP; // FA-FA - } if (!intersection.empty() && (intersection.front() == DM_AUTH_CREDENTIAL_ACCOUNT_RELATED || intersection.front() == DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS)) { - context->accesser.bindLevel = DEVICE; // Exceptions: account related is DEVICE + context->accesser.bindLevel = DmRole::DM_ROLE_USER; // Exceptions: account related is DEVICE } - context->accessee.bindLevel = context->accesser.bindLevel; // TODO: 添加配件判断 context->accesser.credentialTypeLists.clear(); @@ -77,10 +71,10 @@ void AuthSrcConfirmState::NegotiateCredential(std::shared_ptr con // 如果交集不为空,将第一个值赋值给 context->accesser.credTypeList // TODO: 确认优先级是否正确 JsonObject credInfo(context->accesser.credentialInfos[intersection.front()]); - if (credInfo.Contains(TAG_CRED_ID) && credInfo[TAG_CRED_ID].IsString()) { + if (credInfo[TAG_CRED_ID].IsString()) { context->accesser.credentialTypeLists.push_back(intersection.front()); + context->accesser.transmitCredentialId = credInfo[TAG_CRED_ID].Get(); context->needAgreeCredential = false; - context->accessee.transmitCredentialId = credInfo[TAG_CRED_ID].Get(); } } @@ -126,6 +120,8 @@ int32_t AuthSrcConfirmState::Action(std::shared_ptr context) return ERR_DM_VERSION_INCOMPATIBLE; } + context->accesser.isOnline = context->accessee.isOnline && + context->softbusConnector->CheckIsOnline(context->accessee.deviceIdHash, true); int32_t ret = GetAuthCredentialInfo(context); if (ret != DM_OK) { LOGE("AuthSrcConfirmState::Action GetAuthCredentialInfo failed"); @@ -189,25 +185,21 @@ void AuthSinkConfirmState::NegotiateCredential(std::shared_ptr co return; } + // 确定bindLevel int32_t credType = context->accesser.credentialTypeLists.front(); - if (context->accessee.tokenIdHash.empty()) { - context->accessee.bindLevel = SERVICE; // SA-SA - } else { - context->accessee.bindLevel = APP; // FA-FA - } if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_RELATED || credType == DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS) { - context->accessee.bindLevel = DEVICE; // Exceptions: account related is DEVICE + context->accessee.bindLevel = DmRole::DM_ROLE_USER; // Exceptions: account related is DEVICE } - context->accesser.bindLevel = context->accessee.bindLevel; - std::vector sinkCredTypeLists = context->accessee.credentialTypeLists; + // 凭据与对端凭据不匹配 + std::vector &sinkCredTypeLists = context->accessee.credentialTypeLists; if (std::find(sinkCredTypeLists.begin(), sinkCredTypeLists.end(), credType) == sinkCredTypeLists.end()) { LOGI("AuthSinkConfirmState::NegotiateCredential credType %{public}d not found in sink", credType); return; } JsonObject credInfo(context->accessee.credentialInfos[credType]); - if (credInfo.Contains(TAG_CRED_ID) && credInfo[TAG_CRED_ID].IsString()) { + if (credInfo[TAG_CRED_ID].IsString()) { sinkCredTypeLists.clear(); sinkCredTypeLists.push_back(credType); context->accessee.transmitCredentialId = credInfo[TAG_CRED_ID].Get(); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index b70127650..225821c24 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -363,6 +363,16 @@ int32_t AuthSrcCredentialExchangeState::Action(std::shared_ptr co int32_t ret = ERR_DM_FAILED; context->isAppCredentialVerified = false; + if (!NeedAgreeAcl(context)) { + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } + + if (!NeedAgreeCredential(context)) { + context->authStateMachine->TransitionTo(std::make_shared()); + return DM_OK; + } + // First authentication, generate LNN credentials and public key if (!context->isOnline) { ret = GenerateCredIdAndPublicKey(DM_AUTH_SCOPE_USER, context); diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp index aea99f65f..872e5eb23 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_negotiate.cpp @@ -34,6 +34,7 @@ #include "dm_log.h" #include "dm_timer.h" #include "dm_radar_helper.h" +#include "dm_language_manager.h" #include "dm_constants.h" #include "dm_anonymous.h" #include "dm_random.h" @@ -48,12 +49,23 @@ namespace DistributedHardware { namespace { -enum DmRole { - DM_ROLE_UNKNOWN = 0, - DM_ROLE_USER, - DM_ROLE_SA, - DM_ROLE_FA, -}; +const std::string SYSTEM_LANGUAGE_KEY = "persist.global.language"; + +int32_t AuthSrcGetBindLevel(std::shared_ptr context) +{ + int64_t tokenId; + int32_t ret = AppManager::GetInstance().GetHapTokenIdByName(context->accesser.userId, context->accesser.bundleName, + 0, tokenId); + if (ret != DM_OK) { + if (AppManager::GetInstance().GetNativeTokenIdByName(context->accesser.bundleName, tokenId) != DM_OK) { + return DmRole::DM_ROLE_DEVICE; + } + + return DmRole::DM_ROLE_SA; + } + + return DmRole::DM_ROLE_FA; +} } @@ -86,6 +98,8 @@ int32_t AuthSrcNegotiateStateMachine::Action(std::shared_ptr cont context->accesser.accountIdHash = Crypto::Sha256(context->accesser.accountId); context->accesser.tokenIdHash = Crypto::Sha256(std::to_string(context->accesser.tokenId)); + context->accesser.bindLevel = AuthSrcGetBindLevel(context); + std::string message = context->authMessageProcessor->CreateMessage(MSG_TYPE_REQ_ACL_NEGOTIATE, context); context->softbusConnector->GetSoftbusSession()->SendData(context->sessionId, message); if (context->timer != nullptr) { @@ -163,6 +177,7 @@ int32_t AuthSinkNegotiateStateMachine::ProcRespNegotiate5_1_0(std::shared_ptraccesser.isOnline = context->softbusConnector->CheckIsOnline(context->accesser.deviceIdHash, true); + context->accesser.language = DmLanguageManager::GetInstance().GetSystemParam(SYSTEM_LANGUAGE_KEY); ret = GetAuthCredentialInfo(context); if (ret != DM_OK) { LOGE("DmAuthManager::ProcRespNegotiate5_1_0 fail to get credential."); diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index cd8541578..a1d1fca03 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -90,6 +90,7 @@ const char* TAG_IS_ONLINE = "isOnline"; const char* TAG_IS_AUTHED = "isAuthed"; const char* TAG_CREDENTIAL_INFO = "credentialInfo"; const char* TAG_CERT_INFO = "certInfo"; +const char* TAG_LANGUAGE = "language"; // Accesser table content is used for ACL synchronization. const char* TAG_ACCESSER_DEVICE_ID = "accesserDeviceId"; @@ -600,7 +601,7 @@ int32_t DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptraccesser.bundleName; jsonObject[TAG_PEER_BUNDLE_NAME] = context->accessee.bundleName; - jsonObject[TAG_BIND_LEVEL] = context->accesser.bindLevel; + // jsonObject[TAG_BIND_LEVEL] = context->accesser.bindLevel; JsonObject jsonExtraObject; CreateNegotiateExtraInfoMessage(context, jsonExtraObject); @@ -625,6 +626,7 @@ int32_t DmAuthMessageProcessor::CreateRespNegotiateMessage(std::shared_ptrisOnline; jsonObject[TAG_IS_AUTHED] = context->accessee.isAuthed; jsonObject[TAG_CERT_INFO] = vectorInt32ToString(context->accessee.credentialTypeLists); + jsonObject[TAG_LANGUAGE] = context->accessee.language; return DM_OK; } @@ -960,9 +962,9 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(const JsonObject &jsonObje if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString()) { context->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); } - if (jsonObject[TAG_BIND_LEVEL].IsNumberInteger()) { - context->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].Get(); - } + // if (jsonObject[TAG_BIND_LEVEL].IsNumberInteger()) { + // context->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].Get(); + // } if (jsonObject.Contains(TAG_EXTRA_INFO) && jsonObject[TAG_EXTRA_INFO].IsObject()) { ParseNegotiateExtraInfoMessage(jsonObject[TAG_EXTRA_INFO], context); @@ -1011,6 +1013,10 @@ int32_t DmAuthMessageProcessor::ParseMessageRespAclNegotiate(const JsonObject &j context->accessee.credentialTypeLists = stringToVectorInt32(jsonObject[TAG_CERT_INFO].Get()); } + if (jsonObject[TAG_LANGUAGE].IsString()) { + context->accessee.language = jsonObject[TAG_LANGUAGE].Get(); + } + context->authStateMachine->TransitionTo(std::make_shared()); return DM_OK; } diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index b151916e5..ecaa02737 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -50,6 +50,7 @@ enum DM_SUBJECT { }; // Security device auth credential query related definitions, keep consistent with device_auth.h +const char* const FILED_CRED_OWNER = "credOwner"; const char* const FILED_DEVICE_ID = "deviceId"; const char* const FILED_USER_ID = "userId"; const char* const FILED_DEVICE_ID_HASH = "deviceIdHash"; @@ -76,7 +77,8 @@ bool HaveSameTokenId(std::shared_ptr context, const std::vectoraccessee.tokenIdHash); } -uint32_t GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo) +int32_t GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo, + std::vector &p2pCredIdList, std::vector &lnnCredIdList) { if (!credInfo[FILED_CRED_TYPE].IsNumberInteger() || !credInfo[FILED_AUTHORIZED_SCOPE].IsNumberInteger() || !credInfo[FILED_SUBJECT].IsNumberInteger()) { @@ -88,7 +90,8 @@ uint32_t GetCredentialType(std::shared_ptr context, const JsonIte int32_t authorizedScope = credInfo[FILED_AUTHORIZED_SCOPE].Get(); int32_t subject = credInfo[FILED_SUBJECT].Get(); - if (context->accesser.accountIdHash == context->accessee.accountIdHash) { + if (context->accesser.accountIdHash == context->accessee.accountIdHash && + context->accesser.accountId != "ohosAnonymousUid") { // identicail credential if (credType == ACCOUNT_RELATED && authorizedScope == SCOPE_USER) { return DM_AUTH_CREDENTIAL_ACCOUNT_RELATED; @@ -108,62 +111,172 @@ uint32_t GetCredentialType(std::shared_ptr context, const JsonIte // point_to_point identical std::vector appList; + DmAccess &remoteAccess = context->direction == DM_AUTH_SOURCE ? context->accessee : context->accesser; credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList); - if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_APP && HaveSameTokenId(context, appList)) { - return DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; + if (credType == ACCOUNT_UNRELATED && + // 查询时无对端userId,只有查询出来后校验对端userId + remoteAccess.userIdHash == Crypto::Sha256(credInfo[FILED_PEER_USER_SPACE_ID].Get())) { + if (authorizedScope == SCOPE_APP && HaveSameTokenId(context, appList)) { + p2pCredIdList.push_back(credInfo[FILED_CRED_ID].Get()); + return DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; + } else if (authorizedScope == SCOPE_USER && appList.empty()) { + lnnCredIdList.push_back(credInfo[FILED_CRED_ID].Get()); + } } return DM_AUTH_CREDENTIAL_INVALID; } -int32_t DmQueryCredential(std::shared_ptr context, JsonObject &queryResult) +int32_t DmQueryDmCredential(std::shared_ptr context, JsonObject &queryResult) { - int32_t ret; - uint32_t credType; JsonObject queryParams; DmAccess &access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; DmAccess &remoteAccess = context->direction == DM_AUTH_SOURCE ? context->accessee : context->accesser; - // queryParams[FILED_DEVICE_ID_HASH] = remoteAccess.deviceIdHash; - // queryParams[FILED_USER_ID] = access.userId; // IS中userId为string - // queryParams[FILED_PEER_USER_SPACE_ID] = remoteAccess.userId; - ret = context->hiChainAuthConnector->QueryCredentialInfo(access.userId, queryParams, queryResult); - if (ret != DM_OK) { - LOGE("DmQueryCredential fail to query credential id list."); - return ret; + queryParams[FILED_DEVICE_ID_HASH] = remoteAccess.deviceIdHash; + queryParams[FILED_CRED_TYPE] = DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; + queryParams[FILED_CRED_OWNER] = "DM"; + LOGI("DmQueryCredential for userId %{public}d and queryParams %{public}s", + access.userId, queryParams.Dump().c_str()); + + return context->hiChainAuthConnector->QueryCredentialInfo(access.userId, queryParams, queryResult); +} + +int32_t DmQueryOtherCredential(std::shared_ptr context, JsonObject &queryResult) +{ + JsonObject queryParams; + + DmAccess &access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; + DmAccess &remoteAccess = context->direction == DM_AUTH_SOURCE ? context->accessee : context->accesser; + if (access.accountId == "ohosAnonymousUid" || remoteAccess.accountId == "ohosAnonymousUid") { + LOGI("DmQueryOtherCredential accountId ohosAnonymousUid no need query other credential"); + return DM_OK; } - // TODO: delete + + queryParams[FILED_DEVICE_ID] = access.deviceId; + queryParams[FILED_USER_ID] = access.accountId; + LOGI("DmQueryCredential for userId %{public}d and queryParams %{public}s", access.userId, queryParams.Dump().c_str()); + return context->hiChainAuthConnector->QueryCredentialInfo(access.userId, queryParams, queryResult); +} + +int32_t DmDeleteAbnormalCredentialAndAcl(std::shared_ptr context, std::vector &credTypeList, + std::vector &p2pCredIdList, std::vector &lnnCredIdList) +{ + DmAccess &access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; + + int32_t relatedAccountCount = std::count(credTypeList.begin(), credTypeList.end(), + DM_AUTH_CREDENTIAL_ACCOUNT_RELATED); + int32_t acrossAccountCount = std::count(credTypeList.begin(), credTypeList.end(), + DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS); + int32_t unrelatedAccountCount = std::count(credTypeList.begin(), credTypeList.end(), + DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED); + if (relatedAccountCount > 1 || acrossAccountCount > 1) { + context->reply = ERR_DM_FAILED; + context->reason = ERR_DM_FAILED; + return ERR_DM_FAILED; + } + + if (lnnCredIdList.size() > 1) { + LOGI("DmDeleteAbnormalCredentialAndAcl found duplicate lnn credential"); + for (std::string credId : lnnCredIdList) { + (void)context->hiChainAuthConnector->DeleteCredential(access.userId, credId); + } + lnnCredIdList.clear(); + } + // unrelatedAccountCount > 1,duplicate p2p credential + // for dfx: + // unrelatedAccountCount <= 1 && lnnCredIdList.size() == 0, no lnn credential, impossible, delete p2p credential too + // TODO: need delete acl? + if (unrelatedAccountCount > 1 || lnnCredIdList.size() == 0) { + LOGI("DmDeleteAbnormalCredentialAndAcl found duplicate p2p credential"); + for (std::string credId : p2pCredIdList) { + (void)context->hiChainAuthConnector->DeleteCredential(access.userId, credId); + } + p2pCredIdList.clear(); + access.credentialInfos.erase(DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED); + credTypeList.erase(std::remove(credTypeList.begin(), credTypeList.end(), + DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED), credTypeList.end()); + } + + return DM_OK; +} + +bool DmIsLnnCredential(std::shared_ptr context, const JsonItemObject &credInfo) +{ + if (!credInfo[FILED_CRED_TYPE].IsNumberInteger() || !credInfo[FILED_AUTHORIZED_SCOPE].IsNumberInteger()) { + LOGE("credType or authorizedScope invalid."); + return false; + } + + int32_t credType = credInfo[FILED_CRED_TYPE].Get(); + int32_t authorizedScope = credInfo[FILED_AUTHORIZED_SCOPE].Get(); + + // point_to_point identical + DmAccess &remoteAccess = context->direction == DM_AUTH_SOURCE ? context->accessee : context->accesser; + if (credType == ACCOUNT_UNRELATED && authorizedScope == SCOPE_USER && + // 查询时无对端userId,只有查询出来后校验对端userId + remoteAccess.userIdHash == Crypto::Sha256(credInfo[FILED_PEER_USER_SPACE_ID].Get())) { + return true; + } + + return DM_AUTH_CREDENTIAL_INVALID; +} + +int32_t DmQueryCredential(std::shared_ptr context, JsonObject &queryResult) +{ + int32_t ret; + int32_t credType; + + DmAccess &access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; + + // 1. 查询点对点凭据 + ret = DmQueryDmCredential(context, queryResult); + if (ret != DM_OK) { + return ret; + } + + // 2. 查询其他账号凭据,如同账号、分享 + ret = DmQueryOtherCredential(context, queryResult); + if (ret != DM_OK) { + return ret; + } + + // 3. 确认凭据类型 std::vector credTypeList; + std::vector p2pCredIdList; + std::vector lnnCredIdList; for (auto& item : queryResult.Items()) { - // 过滤掉非对端deviceIdHash的结果 - // if (Crypto::Sha256(item[FILED_DEVICE_ID]) != remoteAccess.deviceIdHash) { - // continue; - // } - // 确认凭据类型 LOGI("DmQueryCredential credInfo: %{public}s", item.Dump().c_str()); - credType = GetCredentialType(context, item); + credType = GetCredentialType(context, item, p2pCredIdList, lnnCredIdList); if (credType == DM_AUTH_CREDENTIAL_INVALID) { continue; } item[FILED_CRED_TYPE] = credType; LOGI("DmQueryCredential useful credType %{public}d", credType); - // TODO: 确认credInfo中是否有id信息 access.credentialInfos[credType] = item.Dump(); - // duplicate acl and credType is not allowed - if (std::find(credTypeList.begin(), credTypeList.end(), credType) != credTypeList.end()) { - LOGE("DmQueryCredential duplicate credType %{public}d", credType); - context->reply = ERR_DM_FAILED; - context->reason = ERR_DM_FAILED; - return ERR_DM_FAILED; - } credTypeList.push_back(credType); } + + ret = DmDeleteAbnormalCredentialAndAcl(context, credTypeList, p2pCredIdList, lnnCredIdList); + if (ret != DM_OK) { + access.credentialInfos.clear(); + return ret; + } + + if (lnnCredIdList.size() == 1) { + access.lnnCredentialId = lnnCredIdList.front(); + } else if (lnnCredIdList.empty() && + std::count(credTypeList.begin(), credTypeList.end(), DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED) > 0) { + // 不存在有点对点凭据,无总线凭据的情况 + LOGE("DmQueryCredential found point-to-point credential but no user credential"); + return ERR_DM_FAILED; + } access.credentialTypeLists = credTypeList; return DM_OK; @@ -338,8 +451,8 @@ int32_t DmAuthState::GetAuthCredentialInfo(std::shared_ptr contex // 2. Retrieve all ACLs DmAccess &access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; std::vector profiles = - DeviceProfileConnector::GetInstance().GetAccessControlProfile(); - LOGI("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo success to get %{public}u acls", profiles.size()); + DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); + LOGI("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo success to get %{public}ld acls", profiles.size()); for (const DistributedDeviceProfile::AccessControlProfile &item : profiles) { bool isAclMatched = false; DistributedDeviceProfile::Accesser accesser = item.GetAccesser(); @@ -354,10 +467,10 @@ int32_t DmAuthState::GetAuthCredentialInfo(std::shared_ptr contex } // TODO: delete - LOGI("accesser: deviceId - %{public}s, userId - %{public}d, accountId - %{public}s, tokenId - %{public}lld", + LOGI("accesser: deviceId - %{public}s, userId - %{public}d, accountId - %{public}s, tokenId - %{public}ld", accesser.GetAccesserDeviceId().c_str(), accesser.GetAccesserUserId(), accesser.GetAccesserAccountId().c_str(), accesser.GetAccesserTokenId()); - LOGI("accessee: deviceId - %{public}s, userId - %{public}d, accountId - %{public}s, tokenId - %{public}lld", + LOGI("accessee: deviceId - %{public}s, userId - %{public}d, accountId - %{public}s, tokenId - %{public}ld", accessee.GetAccesseeDeviceId().c_str(), accessee.GetAccesseeUserId(), accessee.GetAccesseeAccountId().c_str(), accessee.GetAccesseeTokenId()); -- Gitee From aded63526538a089fb69d01a3ea0310cc2ab1e25 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Sat, 29 Mar 2025 23:08:07 +0800 Subject: [PATCH 356/382] =?UTF-8?q?BUGFIX:=E4=BF=AE=E5=A4=8D=E9=B8=BF?= =?UTF-8?q?=E8=92=99=E7=8E=AF=E7=94=9F=E5=91=BD=E5=91=A8=E6=9C=9F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dependency/softbus/softbus_connector.h | 2 +- .../dependency/softbus/softbus_connector.cpp | 29 ++++++++++++------- .../dependency/softbus/softbus_session.cpp | 4 +-- 3 files changed, 21 insertions(+), 14 deletions(-) diff --git a/services/implementation/include/dependency/softbus/softbus_connector.h b/services/implementation/include/dependency/softbus/softbus_connector.h index b57ea7ae6..f2ba56295 100644 --- a/services/implementation/include/dependency/softbus/softbus_connector.h +++ b/services/implementation/include/dependency/softbus/softbus_connector.h @@ -48,7 +48,7 @@ public: * @tc.desc: Get Connect Addr of the SoftbusConnector * @tc.type: FUNC */ - static ConnectionAddr *GetConnectAddr(const std::string &deviceId, std::string &connectAddr); + static shared_ptr GetConnectAddr(const std::string &deviceId, std::string &connectAddr); /** * @tc.name: SoftbusConnector::GetUdidByNetworkId diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 9d1ae5811..99d71aba9 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -79,7 +79,7 @@ void SoftbusConnector::JoinLnn(const std::string &deviceId, bool isForceJoin) { std::string connectAddr; LOGI("start, deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - ConnectionAddr *addrInfo = GetConnectAddr(deviceId, connectAddr); + auto addrInfo = GetConnectAddr(deviceId, connectAddr); if (addrInfo == nullptr) { LOGE("addrInfo is nullptr."); return; @@ -89,7 +89,7 @@ void SoftbusConnector::JoinLnn(const std::string &deviceId, bool isForceJoin) LOGE("convert remoteUdid hash failed, remoteUdidHash_: %{public}s.", GetAnonyString(remoteUdidHash_).c_str()); return; } - int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo, OnSoftbusJoinLNNResult, isForceJoin); + int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo.get(), OnSoftbusJoinLNNResult, isForceJoin); if (ret != DM_OK) { LOGE("[SOFTBUS]JoinLNN failed, ret: %{public}d.", ret); } @@ -100,7 +100,7 @@ void SoftbusConnector::JoinLnn(const std::string &deviceId, const std::string &r { std::string connectAddr; LOGI("start, deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); - ConnectionAddr *addrInfo = GetConnectAddr(deviceId, connectAddr); + auto addrInfo = GetConnectAddr(deviceId, connectAddr); if (addrInfo == nullptr) { LOGE("addrInfo is nullptr."); return; @@ -110,7 +110,7 @@ void SoftbusConnector::JoinLnn(const std::string &deviceId, const std::string &r LOGE("convert remoteUdid hash failed, remoteUdidHash_: %{public}s.", GetAnonyString(remoteUdidHash).c_str()); return; } - int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo, OnSoftbusJoinLNNResult, false); + int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo.get(), OnSoftbusJoinLNNResult, false); if (ret != DM_OK) { LOGE("[SOFTBUS]JoinLNN failed, ret: %{public}d.", ret); } @@ -122,7 +122,7 @@ void SoftbusConnector::JoinLNNBySkId(int32_t sessionId, int32_t sessionKeyId, in { LOGI("start, JoinLNNBySkId sessionId: %{public}d, udid: %{public}s.", sessionId, GetAnonyString(udid).c_str()); std::string connectAddr; - ConnectionAddr *addrInfo = GetConnectAddr(udid, connectAddr); + auto addrInfo = GetConnectAddr(udid, connectAddr); if (addrInfo == nullptr) { LOGE("addrInfo is nullptr."); return; @@ -147,7 +147,7 @@ void SoftbusConnector::JoinLNNBySkId(int32_t sessionId, int32_t sessionKeyId, in addrInfo->deviceKeyId.localDeviceKeyId = 0; // 总线修改后适配 addrInfo->deviceKeyId.remoteDeviceKeyId = 0; // 总线修改后适配 } - int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo, OnSoftbusJoinLNNResult, false); + int32_t ret = ::JoinLNN(DM_PKG_NAME, addrInfo.get(), OnSoftbusJoinLNNResult, false); if (ret != DM_OK) { LOGE("[SOFTBUS]JoinLNNBySkId failed, ret: %{public}d.", ret); } @@ -216,9 +216,11 @@ ConnectionAddr *SoftbusConnector::GetConnectAddrByType(DeviceInfo *deviceInfo, C return nullptr; } -ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, std::string &connectAddr) +shared_ptr SoftbusConnector::GetConnectAddr(const std::string &deviceId, std::string &connectAddr) { DeviceInfo *deviceInfo = nullptr; + std::shared_ptr deviceInfoPtr; + std::shared_ptr connectAddrPtr = std::make_shared(); { std::lock_guard lock(discoveryDeviceInfoMutex_); auto iter = discoveryDeviceInfoMap_.find(deviceId); @@ -226,6 +228,7 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, st LOGE("deviceInfo not found by deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); return nullptr; } + deviceInfoPtr = iter->second; deviceInfo = iter->second.get(); } if (deviceInfo->addrNum <= 0 || deviceInfo->addrNum >= CONNECTION_ADDR_MAX) { @@ -235,33 +238,37 @@ ConnectionAddr *SoftbusConnector::GetConnectAddr(const std::string &deviceId, st JsonObject jsonPara; ConnectionAddr *addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_ETH); if (addr != nullptr) { + *connectAddrPtr = *addr; LOGI("[SOFTBUS]get ETH ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); jsonPara[ETH_IP] = addr->info.ip.ip; jsonPara[ETH_PORT] = addr->info.ip.port; connectAddr = SafetyDump(jsonPara); - return addr; + return connectAddrPtr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_WLAN); if (addr != nullptr) { + *connectAddrPtr = *addr; jsonPara[WIFI_IP] = addr->info.ip.ip; jsonPara[WIFI_PORT] = addr->info.ip.port; LOGI("[SOFTBUS]get WLAN ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); connectAddr = SafetyDump(jsonPara); - return addr; + return connectAddrPtr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BR); if (addr != nullptr) { + *connectAddrPtr = *addr; jsonPara[BR_MAC] = addr->info.br.brMac; LOGI("[SOFTBUS]get BR ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); connectAddr = SafetyDump(jsonPara); - return addr; + return connectAddrPtr; } addr = GetConnectAddrByType(deviceInfo, ConnectionAddrType::CONNECTION_ADDR_BLE); if (addr != nullptr) { + *connectAddrPtr = *addr; jsonPara[BLE_MAC] = addr->info.ble.bleMac; connectAddr = SafetyDump(jsonPara); addr->info.ble.priority = BLE_PRIORITY_HIGH; - return addr; + return connectAddrPtr; } LOGE("[SOFTBUS]failed to get ConnectionAddr for deviceId: %{public}s.", GetAnonyString(deviceId).c_str()); return nullptr; diff --git a/services/implementation/src/dependency/softbus/softbus_session.cpp b/services/implementation/src/dependency/softbus/softbus_session.cpp index eb20396d8..59be600ed 100644 --- a/services/implementation/src/dependency/softbus/softbus_session.cpp +++ b/services/implementation/src/dependency/softbus/softbus_session.cpp @@ -99,12 +99,12 @@ int32_t SoftbusSession::OpenAuthSession(const std::string &deviceId) DmTraceStart(std::string(DM_HITRACE_AUTH_TO_OPPEN_SESSION)); int32_t sessionId = -1; std::string connectAddr; - ConnectionAddr *addrInfo = SoftbusConnector::GetConnectAddr(deviceId, connectAddr); + auto addrInfo = SoftbusConnector::GetConnectAddr(deviceId, connectAddr); if (addrInfo == nullptr) { LOGE("[SOFTBUS]addrInfo is nullptr. sessionId: %{public}d.", sessionId); return sessionId; } - sessionId = ::OpenAuthSession(DM_SESSION_NAME, addrInfo, 1, nullptr); + sessionId = ::OpenAuthSession(DM_SESSION_NAME, addrInfo.get(), 1, nullptr); if (sessionId < 0) { LOGE("[SOFTBUS]open session error, sessionId: %{public}d.", sessionId); return sessionId; -- Gitee From b5c39da98b7bc811c9b86efb42ab544edef70039 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Sat, 29 Mar 2025 23:17:50 +0800 Subject: [PATCH 357/382] =?UTF-8?q?fix:=20=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_state.cpp | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index ecaa02737..3436528ce 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -163,7 +163,7 @@ int32_t DmQueryOtherCredential(std::shared_ptr context, JsonObjec return context->hiChainAuthConnector->QueryCredentialInfo(access.userId, queryParams, queryResult); } -int32_t DmDeleteAbnormalCredentialAndAcl(std::shared_ptr context, std::vector &credTypeList, +int32_t DmDeleteAbnormalCredential(std::shared_ptr context, std::vector &credTypeList, std::vector &p2pCredIdList, std::vector &lnnCredIdList) { DmAccess &access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; @@ -181,7 +181,7 @@ int32_t DmDeleteAbnormalCredentialAndAcl(std::shared_ptr context, } if (lnnCredIdList.size() > 1) { - LOGI("DmDeleteAbnormalCredentialAndAcl found duplicate lnn credential"); + LOGI("DmDeleteAbnormalCredential found duplicate lnn credential"); for (std::string credId : lnnCredIdList) { (void)context->hiChainAuthConnector->DeleteCredential(access.userId, credId); } @@ -190,9 +190,8 @@ int32_t DmDeleteAbnormalCredentialAndAcl(std::shared_ptr context, // unrelatedAccountCount > 1,duplicate p2p credential // for dfx: // unrelatedAccountCount <= 1 && lnnCredIdList.size() == 0, no lnn credential, impossible, delete p2p credential too - // TODO: need delete acl? if (unrelatedAccountCount > 1 || lnnCredIdList.size() == 0) { - LOGI("DmDeleteAbnormalCredentialAndAcl found duplicate p2p credential"); + LOGI("DmDeleteAbnormalCredential found duplicate p2p credential"); for (std::string credId : p2pCredIdList) { (void)context->hiChainAuthConnector->DeleteCredential(access.userId, credId); } @@ -263,7 +262,7 @@ int32_t DmQueryCredential(std::shared_ptr context, JsonObject &qu credTypeList.push_back(credType); } - ret = DmDeleteAbnormalCredentialAndAcl(context, credTypeList, p2pCredIdList, lnnCredIdList); + ret = DmDeleteAbnormalCredential(context, credTypeList, p2pCredIdList, lnnCredIdList); if (ret != DM_OK) { access.credentialInfos.clear(); return ret; -- Gitee From 6c3a94828842dec9853cc4bcb8d97de70d032546 Mon Sep 17 00:00:00 2001 From: yuanzichun Date: Sat, 29 Mar 2025 23:44:28 +0800 Subject: [PATCH 358/382] =?UTF-8?q?BUGFIX:=E9=B8=BF=E8=92=99=E7=8E=AF?= =?UTF-8?q?=E7=BB=84=E7=BD=91=E9=97=AE=E9=A2=98=E4=BF=AE=E5=A4=8D?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../implementation/src/dependency/softbus/softbus_connector.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index d55eb7529..46e6449d9 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -140,7 +140,7 @@ void SoftbusConnector::JoinLNNBySkId(int32_t sessionId, int32_t sessionKeyId, in LOGE("addrInfo is nullptr."); return; } - if (Crypto::ConvertHexStringToBytes(addrInfo->info.ble.udidHash, UDID_HASH_LEN, + if (addrInfo->type == CONNECTION_ADDR_BLE && Crypto::ConvertHexStringToBytes(addrInfo->info.ble.udidHash, UDID_HASH_LEN, udidHash.c_str(), udidHash.length()) != DM_OK) { LOGE("convert remoteUdid hash failed, udidHash: %{public}s.", GetAnonyString(udidHash).c_str()); return; -- Gitee From 8e081d7c4531bf431a9cbe4852ff6c47ecc41b86 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Thu, 27 Mar 2025 21:29:56 +0800 Subject: [PATCH 359/382] =?UTF-8?q?fix=EF=BC=9A=E4=BF=AE=E6=94=B9dm=5Fauth?= =?UTF-8?q?=5Fcontext.cpp=E4=B8=AD=E7=9A=84if=E5=B5=8C=E5=A5=97=E9=80=BB?= =?UTF-8?q?=E8=BE=91?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_context.cpp | 251 ++++++++++-------- 1 file changed, 142 insertions(+), 109 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_context.cpp b/services/implementation/src/authentication_v2/dm_auth_context.cpp index 5fbb0f306..ceaa02474 100644 --- a/services/implementation/src/authentication_v2/dm_auth_context.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_context.cpp @@ -21,69 +21,86 @@ namespace DistributedHardware { // 获取设备ID std::string DmAuthContext::GetDeviceId(DmAuthSide side) { - if (side == DM_AUTH_LOCAL_SIDE) { - return (direction == DM_AUTH_SOURCE) ? accesser.deviceId : accessee.deviceId; - } else if (side == DM_AUTH_REMOTE_SIDE) { - return (direction == DM_AUTH_SOURCE) ? accessee.deviceId : accesser.deviceId; - } else { - return std::string(""); - } + // if (side == DM_AUTH_LOCAL_SIDE) { + // return (direction == DM_AUTH_SOURCE) ? accesser.deviceId : accessee.deviceId; + // } else if (side == DM_AUTH_REMOTE_SIDE) { + // return (direction == DM_AUTH_SOURCE) ? accessee.deviceId : accesser.deviceId; + // } else { + // return std::string(""); + // } + + const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + return (side == DM_AUTH_LOCAL_SIDE) : localAccess.deviceId : remoteAccess.deviceId; } // 获取用户ID int32_t DmAuthContext::GetUserId(DmAuthSide side) { - if (side == DM_AUTH_LOCAL_SIDE) { - return (direction == DM_AUTH_SOURCE) ? accesser.userId : accessee.userId; - } else { - return (direction == DM_AUTH_SOURCE) ? accessee.userId : accesser.userId; - } + // if (side == DM_AUTH_LOCAL_SIDE) { + // return (direction == DM_AUTH_SOURCE) ? accesser.userId : accessee.userId; + // } else { + // return (direction == DM_AUTH_SOURCE) ? accessee.userId : accesser.userId; + // } + const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + return (side == DM_AUTH_LOCAL_SIDE) ? localAccess.userId : remoteAccess.userId; } // 获取凭据ID std::string DmAuthContext::GetCredentialId(DmAuthSide side, DmAuthScope authorizedScope) { - if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || - (authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP)) { - return std::string(""); - } + // if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || + // (authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP)) { + // return std::string(""); + // } - if (side == DM_AUTH_LOCAL_SIDE) { - if (direction == DM_AUTH_SOURCE) { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnCredentialId : accesser.transmitCredentialId; - } else { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnCredentialId : accessee.transmitCredentialId; - } - } else { - if (direction == DM_AUTH_SOURCE) { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnCredentialId : accessee.transmitCredentialId; - } else { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnCredentialId : accesser.transmitCredentialId; - } - } + // if (side == DM_AUTH_LOCAL_SIDE) { + // if (direction == DM_AUTH_SOURCE) { + // return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnCredentialId : accesser.transmitCredentialId; + // } else { + // return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnCredentialId : accessee.transmitCredentialId; + // } + // } else { + // if (direction == DM_AUTH_SOURCE) { + // return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnCredentialId : accessee.transmitCredentialId; + // } else { + // return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnCredentialId : accesser.transmitCredentialId; + // } + // } + + const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + const DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; + return (authorizedScope == DM_AUTH_SCOPE_USER) ? access.lnnCredentialId : access.transmitCredentialId; } // 获取公钥 std::string DmAuthContext::GetPublicKey(DmAuthSide side, DmAuthScope authorizedScope) { - if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || - (authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP)) { - return std::string(""); - } + // if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || + // (authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP)) { + // return std::string(""); + // } - if (side == DM_AUTH_LOCAL_SIDE) { - if (direction == DM_AUTH_SOURCE) { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnPublicKey : accesser.ephemeralPublicKey; - } else { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnPublicKey : accessee.ephemeralPublicKey; - } - } else { - if (direction == DM_AUTH_SOURCE) { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnPublicKey : accessee.ephemeralPublicKey; - } else { - return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnPublicKey : accesser.ephemeralPublicKey; - } - } + // if (side == DM_AUTH_LOCAL_SIDE) { + // if (direction == DM_AUTH_SOURCE) { + // return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnPublicKey : accesser.ephemeralPublicKey; + // } else { + // return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnPublicKey : accessee.ephemeralPublicKey; + // } + // } else { + // if (direction == DM_AUTH_SOURCE) { + // return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnPublicKey : accessee.ephemeralPublicKey; + // } else { + // return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnPublicKey : accesser.ephemeralPublicKey; + // } + // } + + const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + const DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; + return (authorizedScope == DM_AUTH_SCOPE_USER) ? access.lnnPublicKey : access.ephemeralPublicKey; } // 设置凭据ID @@ -94,35 +111,41 @@ int32_t DmAuthContext::SetCredentialId(DmAuthSide side, DmAuthScope authorizedSc LOGE("DmAuthContext::SetCredentialId() error, invalid input parameters"); return ERR_DM_INPUT_PARA_INVALID; } - if (side == DM_AUTH_LOCAL_SIDE) { - if (direction == DM_AUTH_SOURCE) { - if (authorizedScope == DM_AUTH_SCOPE_USER) { - accesser.lnnCredentialId = credentialId; - } else { - accesser.transmitCredentialId = credentialId; - } - } else { - if (authorizedScope == DM_AUTH_SCOPE_USER) { - accessee.lnnCredentialId = credentialId; - } else { - accessee.transmitCredentialId = credentialId; - } - } - } else { - if (direction == DM_AUTH_SOURCE) { - if (authorizedScope == DM_AUTH_SCOPE_USER) { - accessee.lnnCredentialId = credentialId; - } else { - accessee.transmitCredentialId = credentialId; - } - } else { - if (authorizedScope == DM_AUTH_SCOPE_USER) { - accesser.lnnCredentialId = credentialId; - } else { - accesser.transmitCredentialId = credentialId; - } - } - } + // if (side == DM_AUTH_LOCAL_SIDE) { + // if (direction == DM_AUTH_SOURCE) { + // if (authorizedScope == DM_AUTH_SCOPE_USER) { + // accesser.lnnCredentialId = credentialId; + // } else { + // accesser.transmitCredentialId = credentialId; + // } + // } else { + // if (authorizedScope == DM_AUTH_SCOPE_USER) { + // accessee.lnnCredentialId = credentialId; + // } else { + // accessee.transmitCredentialId = credentialId; + // } + // } + // } else { + // if (direction == DM_AUTH_SOURCE) { + // if (authorizedScope == DM_AUTH_SCOPE_USER) { + // accessee.lnnCredentialId = credentialId; + // } else { + // accessee.transmitCredentialId = credentialId; + // } + // } else { + // if (authorizedScope == DM_AUTH_SCOPE_USER) { + // accesser.lnnCredentialId = credentialId; + // } else { + // accesser.transmitCredentialId = credentialId; + // } + // } + // } + DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; + std::string &credId = (authorizedScope == DM_AUTH_SCOPE_USER) ? + access.lnnCredentialId : access.transmitCredentialId; + credId = credentialId; return DM_OK; } @@ -135,46 +158,56 @@ int32_t DmAuthContext::SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope return ERR_DM_INPUT_PARA_INVALID; } - if (side == DM_AUTH_LOCAL_SIDE) { - if (direction == DM_AUTH_SOURCE) { - if (authorizedScope == DM_AUTH_SCOPE_USER) { - accesser.lnnPublicKey = publicKey; - } else { - accesser.ephemeralPublicKey = publicKey; - } - } else { - if (authorizedScope == DM_AUTH_SCOPE_USER) { - accessee.lnnPublicKey = publicKey; - } else { - accessee.ephemeralPublicKey = publicKey; - } - } - } else { - if (direction == DM_AUTH_SOURCE) { - if (authorizedScope == DM_AUTH_SCOPE_USER) { - accessee.lnnPublicKey = publicKey; - } else { - accessee.ephemeralPublicKey = publicKey; - } - } else { - if (authorizedScope == DM_AUTH_SCOPE_USER) { - accesser.lnnPublicKey = publicKey; - } else { - accesser.ephemeralPublicKey = publicKey; - } - } - } + // if (side == DM_AUTH_LOCAL_SIDE) { + // if (direction == DM_AUTH_SOURCE) { + // if (authorizedScope == DM_AUTH_SCOPE_USER) { + // accesser.lnnPublicKey = publicKey; + // } else { + // accesser.ephemeralPublicKey = publicKey; + // } + // } else { + // if (authorizedScope == DM_AUTH_SCOPE_USER) { + // accessee.lnnPublicKey = publicKey; + // } else { + // accessee.ephemeralPublicKey = publicKey; + // } + // } + // } else { + // if (direction == DM_AUTH_SOURCE) { + // if (authorizedScope == DM_AUTH_SCOPE_USER) { + // accessee.lnnPublicKey = publicKey; + // } else { + // accessee.ephemeralPublicKey = publicKey; + // } + // } else { + // if (authorizedScope == DM_AUTH_SCOPE_USER) { + // accesser.lnnPublicKey = publicKey; + // } else { + // accesser.ephemeralPublicKey = publicKey; + // } + // } + // } + + DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; + std::string &key = (authorizedScope == DM_AUTH_SCOPE_USER) ? + access.lnnPublicKey : access.ephemeralPublicKey; + key = publicKey; return DM_OK; } std::string DmAuthContext::GetAccountId(DmAuthSide side) { - if (side == DM_AUTH_LOCAL_SIDE) { - return (direction == DM_AUTH_SOURCE) ? accesser.accountId : accessee.accountId; - } else { - return (direction == DM_AUTH_SOURCE) ? accessee.accountId : accesser.accountId; - } + // if (side == DM_AUTH_LOCAL_SIDE) { + // return (direction == DM_AUTH_SOURCE) ? accesser.accountId : accessee.accountId; + // } else { + // return (direction == DM_AUTH_SOURCE) ? accessee.accountId : accesser.accountId; + // } + DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; + DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; + return (side == DM_AUTH_LOCAL_SIDE) ? localAccess.accountId : remoteAccess.accountId; } } // namespace DistributedHardware } // namespace OHOS \ No newline at end of file -- Gitee From 5a66da6d16cac37a9c86882e98e06b8888385e1c Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Fri, 28 Mar 2025 09:36:14 +0800 Subject: [PATCH 360/382] =?UTF-8?q?fix=EF=BC=9A=E8=A7=A3=E5=86=B3=E7=BC=96?= =?UTF-8?q?=E8=AF=91=E6=8A=A5=E9=94=99=EF=BC=8Ccontext=E4=B8=ADif=E5=B5=8C?= =?UTF-8?q?=E5=A5=97=E4=BF=AE=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../implementation/src/authentication_v2/dm_auth_context.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_context.cpp b/services/implementation/src/authentication_v2/dm_auth_context.cpp index ceaa02474..c98accdda 100644 --- a/services/implementation/src/authentication_v2/dm_auth_context.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_context.cpp @@ -31,7 +31,7 @@ std::string DmAuthContext::GetDeviceId(DmAuthSide side) const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; - return (side == DM_AUTH_LOCAL_SIDE) : localAccess.deviceId : remoteAccess.deviceId; + return (side == DM_AUTH_LOCAL_SIDE) ? localAccess.deviceId : remoteAccess.deviceId; } // 获取用户ID -- Gitee From b16d112d65d14856d5b68c48332575aecf9a35a0 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Fri, 28 Mar 2025 10:44:48 +0800 Subject: [PATCH 361/382] =?UTF-8?q?fix=EF=BC=9Adm=5Fauth=5Fcontext.cpp?= =?UTF-8?q?=E4=B8=AD=E6=B7=BB=E5=8A=A0=E5=85=A5=E5=8F=82=E6=A0=A1=E9=AA=8C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_context.cpp | 132 +++--------------- 1 file changed, 17 insertions(+), 115 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_context.cpp b/services/implementation/src/authentication_v2/dm_auth_context.cpp index c98accdda..9faaa6e80 100644 --- a/services/implementation/src/authentication_v2/dm_auth_context.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_context.cpp @@ -21,14 +21,9 @@ namespace DistributedHardware { // 获取设备ID std::string DmAuthContext::GetDeviceId(DmAuthSide side) { - // if (side == DM_AUTH_LOCAL_SIDE) { - // return (direction == DM_AUTH_SOURCE) ? accesser.deviceId : accessee.deviceId; - // } else if (side == DM_AUTH_REMOTE_SIDE) { - // return (direction == DM_AUTH_SOURCE) ? accessee.deviceId : accesser.deviceId; - // } else { - // return std::string(""); - // } - + if (side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) { + return ""; + } const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; return (side == DM_AUTH_LOCAL_SIDE) ? localAccess.deviceId : remoteAccess.deviceId; @@ -37,11 +32,9 @@ std::string DmAuthContext::GetDeviceId(DmAuthSide side) // 获取用户ID int32_t DmAuthContext::GetUserId(DmAuthSide side) { - // if (side == DM_AUTH_LOCAL_SIDE) { - // return (direction == DM_AUTH_SOURCE) ? accesser.userId : accessee.userId; - // } else { - // return (direction == DM_AUTH_SOURCE) ? accessee.userId : accesser.userId; - // } + if (side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) { + return ""; + } const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; return (side == DM_AUTH_LOCAL_SIDE) ? localAccess.userId : remoteAccess.userId; @@ -50,25 +43,10 @@ int32_t DmAuthContext::GetUserId(DmAuthSide side) // 获取凭据ID std::string DmAuthContext::GetCredentialId(DmAuthSide side, DmAuthScope authorizedScope) { - // if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || - // (authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP)) { - // return std::string(""); - // } - - // if (side == DM_AUTH_LOCAL_SIDE) { - // if (direction == DM_AUTH_SOURCE) { - // return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnCredentialId : accesser.transmitCredentialId; - // } else { - // return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnCredentialId : accessee.transmitCredentialId; - // } - // } else { - // if (direction == DM_AUTH_SOURCE) { - // return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnCredentialId : accessee.transmitCredentialId; - // } else { - // return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnCredentialId : accesser.transmitCredentialId; - // } - // } - + if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || + (authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP)) { + return ""; + } const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; const DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; @@ -78,25 +56,10 @@ std::string DmAuthContext::GetCredentialId(DmAuthSide side, DmAuthScope authoriz // 获取公钥 std::string DmAuthContext::GetPublicKey(DmAuthSide side, DmAuthScope authorizedScope) { - // if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || - // (authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP)) { - // return std::string(""); - // } - - // if (side == DM_AUTH_LOCAL_SIDE) { - // if (direction == DM_AUTH_SOURCE) { - // return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnPublicKey : accesser.ephemeralPublicKey; - // } else { - // return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnPublicKey : accessee.ephemeralPublicKey; - // } - // } else { - // if (direction == DM_AUTH_SOURCE) { - // return (authorizedScope == DM_AUTH_SCOPE_USER) ? accessee.lnnPublicKey : accessee.ephemeralPublicKey; - // } else { - // return (authorizedScope == DM_AUTH_SCOPE_USER) ? accesser.lnnPublicKey : accesser.ephemeralPublicKey; - // } - // } - + if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || + (authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP)) { + return ""; + } const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; const DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; @@ -111,35 +74,6 @@ int32_t DmAuthContext::SetCredentialId(DmAuthSide side, DmAuthScope authorizedSc LOGE("DmAuthContext::SetCredentialId() error, invalid input parameters"); return ERR_DM_INPUT_PARA_INVALID; } - // if (side == DM_AUTH_LOCAL_SIDE) { - // if (direction == DM_AUTH_SOURCE) { - // if (authorizedScope == DM_AUTH_SCOPE_USER) { - // accesser.lnnCredentialId = credentialId; - // } else { - // accesser.transmitCredentialId = credentialId; - // } - // } else { - // if (authorizedScope == DM_AUTH_SCOPE_USER) { - // accessee.lnnCredentialId = credentialId; - // } else { - // accessee.transmitCredentialId = credentialId; - // } - // } - // } else { - // if (direction == DM_AUTH_SOURCE) { - // if (authorizedScope == DM_AUTH_SCOPE_USER) { - // accessee.lnnCredentialId = credentialId; - // } else { - // accessee.transmitCredentialId = credentialId; - // } - // } else { - // if (authorizedScope == DM_AUTH_SCOPE_USER) { - // accesser.lnnCredentialId = credentialId; - // } else { - // accesser.transmitCredentialId = credentialId; - // } - // } - // } DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; @@ -158,36 +92,6 @@ int32_t DmAuthContext::SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope return ERR_DM_INPUT_PARA_INVALID; } - // if (side == DM_AUTH_LOCAL_SIDE) { - // if (direction == DM_AUTH_SOURCE) { - // if (authorizedScope == DM_AUTH_SCOPE_USER) { - // accesser.lnnPublicKey = publicKey; - // } else { - // accesser.ephemeralPublicKey = publicKey; - // } - // } else { - // if (authorizedScope == DM_AUTH_SCOPE_USER) { - // accessee.lnnPublicKey = publicKey; - // } else { - // accessee.ephemeralPublicKey = publicKey; - // } - // } - // } else { - // if (direction == DM_AUTH_SOURCE) { - // if (authorizedScope == DM_AUTH_SCOPE_USER) { - // accessee.lnnPublicKey = publicKey; - // } else { - // accessee.ephemeralPublicKey = publicKey; - // } - // } else { - // if (authorizedScope == DM_AUTH_SCOPE_USER) { - // accesser.lnnPublicKey = publicKey; - // } else { - // accesser.ephemeralPublicKey = publicKey; - // } - // } - // } - DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; @@ -200,11 +104,9 @@ int32_t DmAuthContext::SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope std::string DmAuthContext::GetAccountId(DmAuthSide side) { - // if (side == DM_AUTH_LOCAL_SIDE) { - // return (direction == DM_AUTH_SOURCE) ? accesser.accountId : accessee.accountId; - // } else { - // return (direction == DM_AUTH_SOURCE) ? accessee.accountId : accesser.accountId; - // } + if (side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) { + return ""; + } DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; return (side == DM_AUTH_LOCAL_SIDE) ? localAccess.accountId : remoteAccess.accountId; -- Gitee From 733e2ae8b340e59308d876df3bc9129aca27a477 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Fri, 28 Mar 2025 21:24:17 +0800 Subject: [PATCH 362/382] =?UTF-8?q?fix=EF=BC=9A=E5=B8=B8=E9=87=8F=E6=B7=BB?= =?UTF-8?q?=E5=8A=A0constexpr=E6=A0=87=E8=AF=86=E7=AC=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/auth_stages/auth_credential.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp index 225821c24..da6d8e49d 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_credential.cpp @@ -33,10 +33,10 @@ namespace DistributedHardware { namespace { // tag in Lowercase, need by hichain tag -const char* TAG_LOWER_DEVICE_ID = "deviceId"; -const char* TAG_LOWER_USER_ID = "userId"; +constexpr const char* TAG_LOWER_DEVICE_ID = "deviceId"; +constexpr const char* TAG_LOWER_USER_ID = "userId"; -const char* DM_AUTH_CREDENTIAL_OWNER = "DM"; +constexpr const char* DM_AUTH_CREDENTIAL_OWNER = "DM"; int32_t AuthCredentialTransmitDecryptProcess(std::shared_ptr context, DmEventType event) { -- Gitee From 9ab80b8e552b794a29fd99316d8ff0b35f5a4cb6 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Sat, 29 Mar 2025 10:51:06 +0800 Subject: [PATCH 363/382] =?UTF-8?q?fix=EF=BC=9A=E4=BF=AE=E6=94=B9context?= =?UTF-8?q?=E7=BB=93=E6=9E=84=E4=BD=93=E4=B8=ADset=E5=92=8Cget=E6=8E=A5?= =?UTF-8?q?=E5=8F=A3?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../authentication_v2/dm_auth_context.h | 4 +-- .../src/authentication_v2/dm_auth_context.cpp | 36 +++---------------- 2 files changed, 6 insertions(+), 34 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_context.h b/services/implementation/include/authentication_v2/dm_auth_context.h index 364e4e4ce..43c0265dd 100644 --- a/services/implementation/include/authentication_v2/dm_auth_context.h +++ b/services/implementation/include/authentication_v2/dm_auth_context.h @@ -223,8 +223,8 @@ struct DmAuthContext { 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); + void SetCredentialId(DmAuthSide side, DmAuthScope authorizedScope, const std::string &credentialId); + void SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope, const std::string &publicKey); std::string GetAccountId(DmAuthSide side); }; diff --git a/services/implementation/src/authentication_v2/dm_auth_context.cpp b/services/implementation/src/authentication_v2/dm_auth_context.cpp index 9faaa6e80..d2fe062f8 100644 --- a/services/implementation/src/authentication_v2/dm_auth_context.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_context.cpp @@ -21,9 +21,6 @@ namespace DistributedHardware { // 获取设备ID std::string DmAuthContext::GetDeviceId(DmAuthSide side) { - if (side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) { - return ""; - } const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; return (side == DM_AUTH_LOCAL_SIDE) ? localAccess.deviceId : remoteAccess.deviceId; @@ -32,9 +29,6 @@ std::string DmAuthContext::GetDeviceId(DmAuthSide side) // 获取用户ID int32_t DmAuthContext::GetUserId(DmAuthSide side) { - if (side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) { - return ""; - } const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; return (side == DM_AUTH_LOCAL_SIDE) ? localAccess.userId : remoteAccess.userId; @@ -43,10 +37,6 @@ int32_t DmAuthContext::GetUserId(DmAuthSide side) // 获取凭据ID std::string DmAuthContext::GetCredentialId(DmAuthSide side, DmAuthScope authorizedScope) { - if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || - (authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP)) { - return ""; - } const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; const DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; @@ -56,10 +46,6 @@ std::string DmAuthContext::GetCredentialId(DmAuthSide side, DmAuthScope authoriz // 获取公钥 std::string DmAuthContext::GetPublicKey(DmAuthSide side, DmAuthScope authorizedScope) { - if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || - (authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP)) { - return ""; - } const DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; const DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; const DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; @@ -67,31 +53,20 @@ std::string DmAuthContext::GetPublicKey(DmAuthSide side, DmAuthScope authorizedS } // 设置凭据ID -int32_t DmAuthContext::SetCredentialId(DmAuthSide side, DmAuthScope authorizedScope, const std::string &credentialId) +void DmAuthContext::SetCredentialId(DmAuthSide side, DmAuthScope authorizedScope, const std::string &credentialId) { - if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || - (authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP)) { - LOGE("DmAuthContext::SetCredentialId() error, invalid input parameters"); - return ERR_DM_INPUT_PARA_INVALID; - } DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; std::string &credId = (authorizedScope == DM_AUTH_SCOPE_USER) ? access.lnnCredentialId : access.transmitCredentialId; credId = credentialId; - return DM_OK; + return; } // 设置公钥 -int32_t DmAuthContext::SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope, const std::string &publicKey) +void DmAuthContext::SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope, const std::string &publicKey) { - if ((side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) || - (authorizedScope != DM_AUTH_SCOPE_USER && authorizedScope != DM_AUTH_SCOPE_APP)) { - LOGE("DmAuthContext::SetPublicKey() error, invalid input parameters"); - return ERR_DM_INPUT_PARA_INVALID; - } - DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; DmAccess &access = (side == DM_AUTH_LOCAL_SIDE) ? localAccess : remoteAccess; @@ -99,14 +74,11 @@ int32_t DmAuthContext::SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope access.lnnPublicKey : access.ephemeralPublicKey; key = publicKey; - return DM_OK; + return; } std::string DmAuthContext::GetAccountId(DmAuthSide side) { - if (side != DM_AUTH_LOCAL_SIDE && side != DM_AUTH_REMOTE_SIDE) { - return ""; - } DmAccess &localAccess = (direction == DM_AUTH_SOURCE) ? accesser : accessee; DmAccess &remoteAccess = (direction == DM_AUTH_SOURCE) ? accessee : accesser; return (side == DM_AUTH_LOCAL_SIDE) ? localAccess.accountId : remoteAccess.accountId; -- Gitee From c703eafcef90d3df04effe5a44be20e56e90eab1 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Sat, 29 Mar 2025 19:10:07 +0800 Subject: [PATCH 364/382] =?UTF-8?q?fix=EF=BC=9A=E4=BF=AE=E6=94=B9=E5=91=8A?= =?UTF-8?q?=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../include/authentication_v2/dm_auth_state.h | 5 + .../src/authentication_v2/auth_manager.cpp | 1 - .../auth_stages/auth_acl.cpp | 60 +----------- .../dm_auth_message_processor.cpp | 91 +++++++++++-------- .../src/authentication_v2/dm_auth_state.cpp | 45 +++++++++ 5 files changed, 107 insertions(+), 95 deletions(-) diff --git a/services/implementation/include/authentication_v2/dm_auth_state.h b/services/implementation/include/authentication_v2/dm_auth_state.h index b5f70c9c1..4e175c20f 100644 --- a/services/implementation/include/authentication_v2/dm_auth_state.h +++ b/services/implementation/include/authentication_v2/dm_auth_state.h @@ -117,6 +117,11 @@ public: static int32_t GetTaskTimeout(std::shared_ptr context, const char* taskName, int32_t taskTimeOut); static void HandleAuthenticateTimeout(std::shared_ptr context, std::string name); static bool IsImportAuthCodeCompatibility(DmAuthType authType); + + // 比较明文阶段和密文阶段四元组、绑定级别是否相同 + bool IsQuadrupleAndBindLevelSame(std::shared_ptr context); + // 查询ACL列表 + std::vector GetAclList(std::shared_ptr context); protected: int32_t GetAuthCredentialInfo(std::shared_ptr context); bool NeedReqUserConfirm(std::shared_ptr context); diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 089a40e2a..f0cde08a7 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -231,7 +231,6 @@ int32_t AuthManager::ParseAuthType(const std::map &bin LOGE("AuthManager::ParseAuthType bind param %{public}s fromat is unsupported.", PARAM_KEY_AUTH_TYPE); return ERR_DM_INPUT_PARA_INVALID; } - // TODO:std::atoi统一排查换成strtol函数 authType = std::atoi(authTypeStr.c_str()); return DM_OK; } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp index c5d24a1db..a46b14f71 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_acl.cpp @@ -45,37 +45,12 @@ int32_t AuthSinkDataSyncState::Action(std::shared_ptr context) { LOGI("AuthSinkDataSyncState::Action start"); // 判断密文阶段和明文阶段的四元组是否相同,两端的bindlevel是否相同,不同则直接结束 - bool isSame = Crypto::Sha256(context->accesser.deviceId) == context->accesser.deviceIdHash && - Crypto::Sha256(std::to_string(context->accesser.userId)) == context->accesser.userIdHash && - Crypto::Sha256(context->accesser.accountId) == context->accesser.accountIdHash && - Crypto::Sha256(std::to_string(context->accesser.tokenId)) == context->accesser.tokenIdHash && - context->accesser.bindLevel == context->accessee.bindLevel; - - if (!isSame) { - LOGE("data between two stages different with bindLevel %{public}d to %{public}d, stop auth", - context->accesser.bindLevel, context->accessee.bindLevel); - context->reply = ERR_DM_QUADRUPLE_NOT_SAME; - context->reason = ERR_DM_QUADRUPLE_NOT_SAME; - context->state = static_cast(GetStateType()); - // sink端异常时,sink结束,清理凭据,skid,停止计时器,发送201给source - context->authStateMachine->TransitionTo(std::make_shared()); + if (!IsQuadrupleAndBindLevelSame(context)) { + LOGE("data between two stages different, stop auth"); return DM_OK; } // 查询sink端acl - std::vector profiles = - DeviceProfileConnector::GetInstance().GetAccessControlProfile(); - std::vector sinkAclList; - for (auto &item : profiles) { - if (item.GetAccesser().GetAccesserDeviceId() == context->accesser.deviceId && - item.GetAccesser().GetAccesserUserId() == context->accesser.userId && - item.GetAccessee().GetAccesseeDeviceId() == context->accessee.deviceId && - item.GetAccessee().GetAccesseeUserId() == context->accessee.userId) { - sinkAclList.push_back(item); // 打印并写入 - } - } - if (sinkAclList.empty()) { - LOGI("AuthSinkDataSyncState::Action acl is empty"); // 首次认证 无acl同步 - } + std::vector sinkAclList = GetAclList(context); // 比较双端的acl for (auto &sinkAcl : sinkAclList) { bool res = context->authMessageProcessor->ChecksumAcl(sinkAcl, @@ -105,37 +80,12 @@ int32_t AuthSrcDataSyncState::Action(std::shared_ptr context) if (NeedAgreeAcl(context)) { // 判断密文阶段和明文阶段的四元组是否相同,不同则直接结束 - bool isSame = Crypto::Sha256(context->accessee.deviceId) == context->accessee.deviceIdHash && - Crypto::Sha256(std::to_string(context->accessee.userId)) == context->accessee.userIdHash && - Crypto::Sha256(context->accessee.accountId) == context->accessee.accountIdHash && - Crypto::Sha256(std::to_string(context->accessee.tokenId)) == context->accessee.tokenIdHash && - context->accesser.bindLevel == context->accessee.bindLevel; - - if (!isSame) { + if (!IsQuadrupleAndBindLevelSame(context)) { LOGE("data between two stages different, stop auth"); - // 不同直接结束,发送200给sink端 - context->reason = ERR_DM_QUADRUPLE_NOT_SAME; - context->reply = ERR_DM_QUADRUPLE_NOT_SAME; - context->state = static_cast(GetStateType()); - // source异常时,source不结束,发送200给sink,等sink回201 - context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_REQ_FINISH, context); return DM_OK; } // 查询sink端acl - std::vector profiles = - DeviceProfileConnector::GetInstance().GetAccessControlProfile(); - std::vector srcAclList; - for (auto &item : profiles) { - if (item.GetAccesser().GetAccesserDeviceId() == context->accesser.deviceId && - item.GetAccesser().GetAccesserUserId() == context->accesser.userId && - item.GetAccessee().GetAccesseeDeviceId() == context->accessee.deviceId && - item.GetAccessee().GetAccesseeUserId() == context->accessee.userId) { - srcAclList.push_back(item); // 打印并写入 - } - } - if (srcAclList.empty()) { - LOGI("AuthSrcDataSyncState::Action acl is empty"); // 首次认证 无acl同步 - } + std::vector srcAclList = GetAclList(context); // 比较双端的acl for (auto &srcAcl : srcAclList) { bool res = context->authMessageProcessor->ChecksumAcl(srcAcl, diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index a1d1fca03..6f1e752dc 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1407,49 +1407,62 @@ void ToJson(JsonItemObject &itemObject, const DmAccessControlTable &table) itemObject["bindLevel"] = table.bindLevel; } -void FromJson(const JsonItemObject &itemObject, DmAccessControlTable &table) +using JsonTypeCheckFuncPtr = bool (JsonItemObject::*)() const; + +template +void SetValueFromJson(const JsonItemObject &itemObject, const std::string &key, JsonTypeCheckFuncPtr funcPtr, T &value) { - if (itemObject.Contains("accessControlId") && itemObject["accessControlId"].IsNumberInteger()) { - table.accessControlId = itemObject["accessControlId"].Get(); - } - if (itemObject.Contains("accesserId") && itemObject["accesserId"].IsNumberInteger()) { - table.accesserId = itemObject["accesserId"].Get(); - } - if (itemObject.Contains("accesseeId") && itemObject["accesseeId"].IsNumberInteger()) { - table.accesseeId = itemObject["accesseeId"].Get(); - } - if (itemObject.Contains("deviceId") && itemObject["deviceId"].IsString()) { - table.deviceId = itemObject["deviceId"].Get(); - } - if (itemObject.Contains("sessionKey") && itemObject["sessionKey"].IsString()) { - table.sessionKey = itemObject["sessionKey"].Get(); - } - if (itemObject.Contains("bindType") && itemObject["bindType"].IsNumberInteger()) { - table.bindType = itemObject["bindType"].Get(); - } - if (itemObject.Contains("authType") && itemObject["authType"].IsNumberInteger()) { - table.authType = itemObject["authType"].Get(); - } - if (itemObject.Contains("deviceType") && itemObject["deviceType"].IsNumberInteger()) { - table.deviceType = itemObject["deviceType"].Get(); - } - if (itemObject.Contains("deviceIdHash") && itemObject["deviceIdHash"].IsString()) { - table.deviceIdHash = itemObject["deviceIdHash"].Get(); - } - if (itemObject.Contains("status") && itemObject["status"].IsNumberInteger()) { - table.status = itemObject["status"].Get(); - } - if (itemObject.Contains("validPeriod") && itemObject["validPeriod"].IsNumberInteger()) { - table.validPeriod = itemObject["validPeriod"].Get(); - } - if (itemObject.Contains("lastAuthTime") && itemObject["lastAuthTime"].IsNumberInteger()) { - table.lastAuthTime = itemObject["lastAuthTime"].Get(); - } - if (itemObject.Contains("bindLevel") && itemObject["bindLevel"].IsNumberInteger()) { - table.bindLevel = itemObject["bindLevel"].Get(); + if (itemObject.Contains(key) && itemObject[key].*funcPtr()) { + value = itemObject[key].Get(); } } + +void FromJson(const JsonItemObject &itemObject, DmAccessControlTable &table) +{ + // if (itemObject.Contains("accessControlId") && itemObject["accessControlId"].IsNumberInteger()) { + // table.accessControlId = itemObject["accessControlId"].Get(); + // } + // if (itemObject.Contains("accesserId") && itemObject["accesserId"].IsNumberInteger()) { + // table.accesserId = itemObject["accesserId"].Get(); + // } + // if (itemObject.Contains("accesseeId") && itemObject["accesseeId"].IsNumberInteger()) { + // table.accesseeId = itemObject["accesseeId"].Get(); + // } + // if (itemObject.Contains("deviceId") && itemObject["deviceId"].IsString()) { + // table.deviceId = itemObject["deviceId"].Get(); + // } + // if (itemObject.Contains("sessionKey") && itemObject["sessionKey"].IsString()) { + // table.sessionKey = itemObject["sessionKey"].Get(); + // } + // if (itemObject.Contains("bindType") && itemObject["bindType"].IsNumberInteger()) { + // table.bindType = itemObject["bindType"].Get(); + // } + // if (itemObject.Contains("authType") && itemObject["authType"].IsNumberInteger()) { + // table.authType = itemObject["authType"].Get(); + // } + // if (itemObject.Contains("deviceType") && itemObject["deviceType"].IsNumberInteger()) { + // table.deviceType = itemObject["deviceType"].Get(); + // } + // if (itemObject.Contains("deviceIdHash") && itemObject["deviceIdHash"].IsString()) { + // table.deviceIdHash = itemObject["deviceIdHash"].Get(); + // } + // if (itemObject.Contains("status") && itemObject["status"].IsNumberInteger()) { + // table.status = itemObject["status"].Get(); + // } + // if (itemObject.Contains("validPeriod") && itemObject["validPeriod"].IsNumberInteger()) { + // table.validPeriod = itemObject["validPeriod"].Get(); + // } + // if (itemObject.Contains("lastAuthTime") && itemObject["lastAuthTime"].IsNumberInteger()) { + // table.lastAuthTime = itemObject["lastAuthTime"].Get(); + // } + // if (itemObject.Contains("bindLevel") && itemObject["bindLevel"].IsNumberInteger()) { + // table.bindLevel = itemObject["bindLevel"].Get(); + // } + + SetValueFromJson(itemObject, "accessControlId", &JsonItemObject::IsNumberInteger, table.accessControlId); +} + void ToJson(JsonItemObject &itemObject, const DmAccessToSync &table) { itemObject["deviceName"] = table.deviceName; diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 3436528ce..c9c1cf186 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -561,5 +561,50 @@ bool DmAuthState::IsImportAuthCodeCompatibility(DmAuthType authType) return false; } + +bool DmAuthState::IsQuadrupleAndBindLevelSame(std::shared_ptr context) +{ + const DmAccess &access = (context->direction == DM_AUTH_SOURCE) ? context->accessee : context->accesser; + bool isSame = Crypto::Sha256(context->access.deviceId) == context->access.deviceIdHash && + Crypto::Sha256(std::to_string(context->access.userId)) == context->access.userIdHash && + Crypto::Sha256(context->access.accountId) == context->access.accountIdHash && + Crypto::Sha256(std::to_string(context->access.tokenId)) == context->access.tokenIdHash && + context->accesser.bindLevel == context->accessee.bindLevel; + if (!isSame) { + context->reason = ERR_DM_QUADRUPLE_NOT_SAME; + context->reply = ERR_DM_QUADRUPLE_NOT_SAME; + context->state = static_cast(GetStateType()); + if (context->direction == DM_AUTH_SOURCE) { + context->authMessageProcessor->CreateAndSendMsg(MSG_TYPE_AUTH_REQ_FINISH, context); + } else { + context->authStateMachine->TransitionTo(std::make_shared()); + } + } + + return isSame; +} + +std::vector DmAuthState::GetAclList(std::shared_ptr + context) +{ + std::vector profiles = + DeviceProfileConnector::GetInstance().GetAccessControlProfile(); + std::vector aclList; + for (auto &item : profiles) { + if (item.GetAccesser().GetAccesserDeviceId() == context->accesser.deviceId && + item.GetAccesser().GetAccesserUserId() == context->accesser.userId && + item.GetAccessee().GetAccesseeDeviceId() == context->accessee.deviceId && + item.GetAccessee().GetAccesseeUserId() == context->accessee.userId) { + aclList.push_back(item); + } + } + + if (aclList.empty()) { + LOGI("DmAuthState::GetAclList acl is empty"); + } + + return aclList; +} + } // namespace DistributedHardware } // namespace OHOS -- Gitee From 68576237338e626d83595642bb9f8dc729bcac57 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Sat, 29 Mar 2025 19:39:38 +0800 Subject: [PATCH 365/382] =?UTF-8?q?fix=EF=BC=9AFromJson=E6=8E=A5=E5=8F=A3?= =?UTF-8?q?=E8=B6=85=E5=A4=A7=E5=9C=88=E5=A4=8D=E6=9D=82=E5=BA=A6=E4=BF=AE?= =?UTF-8?q?=E6=94=B9?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.cpp | 77 ++++++++++++------- 1 file changed, 49 insertions(+), 28 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 6f1e752dc..bb8bafb40 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1412,7 +1412,7 @@ using JsonTypeCheckFuncPtr = bool (JsonItemObject::*)() const; template void SetValueFromJson(const JsonItemObject &itemObject, const std::string &key, JsonTypeCheckFuncPtr funcPtr, T &value) { - if (itemObject.Contains(key) && itemObject[key].*funcPtr()) { + if (itemObject.Contains(key) && (itemObject[key].*funcPtr)()) { value = itemObject[key].Get(); } } @@ -1461,6 +1461,18 @@ void FromJson(const JsonItemObject &itemObject, DmAccessControlTable &table) // } SetValueFromJson(itemObject, "accessControlId", &JsonItemObject::IsNumberInteger, table.accessControlId); + SetValueFromJson(itemObject, "accesserId", &JsonItemObject::IsNumberInteger, table.accesserId); + SetValueFromJson(itemObject, "accesseeId", &JsonItemObject::IsNumberInteger, table.accesseeId); + SetValueFromJson(itemObject, "deviceId", &JsonItemObject::IsNumberInteger, table.deviceId); + SetValueFromJson(itemObject, "sessionKey", &JsonItemObject::IsString, table.sessionKey); + SetValueFromJson(itemObject, "bindType", &JsonItemObject::IsNumberInteger, table.bindType); + SetValueFromJson(itemObject, "authType", &JsonItemObject::IsNumberInteger, table.authType); + SetValueFromJson(itemObject, "deviceType", &JsonItemObject::IsNumberInteger, table.deviceType); + SetValueFromJson(itemObject, "deviceIdHash", &JsonItemObject::IsString, table.deviceIdHash); + SetValueFromJson(itemObject, "status", &JsonItemObject::IsNumberInteger, table.status); + SetValueFromJson(itemObject, "validPeriod", &JsonItemObject::IsNumberInteger, table.validPeriod); + SetValueFromJson(itemObject, "lastAuthTime", &JsonItemObject::IsNumberInteger, table.lastAuthTime); + SetValueFromJson(itemObject, "bindLevel", &JsonItemObject::IsNumberInteger, table.bindLevel); } void ToJson(JsonItemObject &itemObject, const DmAccessToSync &table) @@ -1478,33 +1490,42 @@ void ToJson(JsonItemObject &itemObject, const DmAccessToSync &table) void FromJson(const JsonItemObject &itemObject, DmAccessToSync &table) { - if (itemObject.Contains("deviceName") && itemObject["deviceName"].IsString()) { - table.deviceName = itemObject["deviceName"].Get(); - } - if (itemObject.Contains("deviceId") && itemObject["deviceId"].IsString()) { - table.deviceId = itemObject["deviceId"].Get(); - } - if (itemObject.Contains("userId") && itemObject["userId"].IsNumberInteger()) { - table.userId = itemObject["userId"].Get(); - } - if (itemObject.Contains("accountId") && itemObject["accountId"].IsString()) { - table.accountId = itemObject["accountId"].Get(); - } - if (itemObject.Contains("tokenId") && itemObject["tokenId"].IsNumberInteger()) { - table.tokenId = itemObject["tokenId"].Get(); - } - if (itemObject.Contains("bundleName") && itemObject["bundleName"].IsString()) { - table.bundleName = itemObject["bundleName"].Get(); - } - if (itemObject.Contains("bindLevel") && itemObject["bindLevel"].IsNumberInteger()) { - table.bindLevel = itemObject["bindLevel"].Get(); - } - if (itemObject.Contains("sessionKeyId") && itemObject["sessionKeyId"].IsNumberInteger()) { - table.sessionKeyId = itemObject["sessionKeyId"].Get(); - } - if (itemObject.Contains("skTimeStamp") && itemObject["skTimeStamp"].IsNumberInteger()) { - table.skTimeStamp = itemObject["skTimeStamp"].Get(); - } + // if (itemObject.Contains("deviceName") && itemObject["deviceName"].IsString()) { + // table.deviceName = itemObject["deviceName"].Get(); + // } + // if (itemObject.Contains("deviceId") && itemObject["deviceId"].IsString()) { + // table.deviceId = itemObject["deviceId"].Get(); + // } + // if (itemObject.Contains("userId") && itemObject["userId"].IsNumberInteger()) { + // table.userId = itemObject["userId"].Get(); + // } + // if (itemObject.Contains("accountId") && itemObject["accountId"].IsString()) { + // table.accountId = itemObject["accountId"].Get(); + // } + // if (itemObject.Contains("tokenId") && itemObject["tokenId"].IsNumberInteger()) { + // table.tokenId = itemObject["tokenId"].Get(); + // } + // if (itemObject.Contains("bundleName") && itemObject["bundleName"].IsString()) { + // table.bundleName = itemObject["bundleName"].Get(); + // } + // if (itemObject.Contains("bindLevel") && itemObject["bindLevel"].IsNumberInteger()) { + // table.bindLevel = itemObject["bindLevel"].Get(); + // } + // if (itemObject.Contains("sessionKeyId") && itemObject["sessionKeyId"].IsNumberInteger()) { + // table.sessionKeyId = itemObject["sessionKeyId"].Get(); + // } + // if (itemObject.Contains("skTimeStamp") && itemObject["skTimeStamp"].IsNumberInteger()) { + // table.skTimeStamp = itemObject["skTimeStamp"].Get(); + // } + SetValueFromJson(itemObject, "deviceName", &JsonItemObject::IsString, table.deviceName); + SetValueFromJson(itemObject, "deviceId", &JsonItemObject::IsString, table.deviceId); + SetValueFromJson(itemObject, "userId", &JsonItemObject::IsNumberInteger, table.userId); + SetValueFromJson(itemObject, "accountId", &JsonItemObject::IsString, table.accountId); + SetValueFromJson(itemObject, "tokenId", &JsonItemObject::IsNumberInteger, table.tokenId); + SetValueFromJson(itemObject, "bundleName", &JsonItemObject::IsString, table.bundleName); + SetValueFromJson(itemObject, "bindLevel", &JsonItemObject::IsNumberInteger, table.bindLevel); + SetValueFromJson(itemObject, "sessionKeyId", &JsonItemObject::IsNumberInteger, table.sessionKeyId); + SetValueFromJson(itemObject, "skTimeStamp", &JsonItemObject::IsNumberInteger, table.skTimeStamp); } } // namespace DistributedHardware -- Gitee From ef51cff14a4b90a1da7ae2cba4b14093fba2d100 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Sat, 29 Mar 2025 23:57:25 +0800 Subject: [PATCH 366/382] =?UTF-8?q?fix=EF=BC=9A=E5=91=8A=E8=AD=A6=E6=B8=85?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_state.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index c9c1cf186..1f7643fcf 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -113,7 +113,7 @@ int32_t GetCredentialType(std::shared_ptr context, const JsonItem std::vector appList; DmAccess &remoteAccess = context->direction == DM_AUTH_SOURCE ? context->accessee : context->accesser; credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList); - if (credType == ACCOUNT_UNRELATED && + if (credType == ACCOUNT_UNRELATED && // 查询时无对端userId,只有查询出来后校验对端userId remoteAccess.userIdHash == Crypto::Sha256(credInfo[FILED_PEER_USER_SPACE_ID].Get())) { if (authorizedScope == SCOPE_APP && HaveSameTokenId(context, appList)) { @@ -565,10 +565,10 @@ bool DmAuthState::IsImportAuthCodeCompatibility(DmAuthType authType) bool DmAuthState::IsQuadrupleAndBindLevelSame(std::shared_ptr context) { const DmAccess &access = (context->direction == DM_AUTH_SOURCE) ? context->accessee : context->accesser; - bool isSame = Crypto::Sha256(context->access.deviceId) == context->access.deviceIdHash && - Crypto::Sha256(std::to_string(context->access.userId)) == context->access.userIdHash && - Crypto::Sha256(context->access.accountId) == context->access.accountIdHash && - Crypto::Sha256(std::to_string(context->access.tokenId)) == context->access.tokenIdHash && + bool isSame = Crypto::Sha256(access.deviceId) == access.deviceIdHash && + Crypto::Sha256(std::to_string(access.userId)) == access.userIdHash && + Crypto::Sha256(access.accountId) == access.accountIdHash && + Crypto::Sha256(std::to_string(access.tokenId)) == access.tokenIdHash && context->accesser.bindLevel == context->accessee.bindLevel; if (!isSame) { context->reason = ERR_DM_QUADRUPLE_NOT_SAME; -- Gitee From cd49953bc2ebeafc3e04550843309fbddb105205 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Sun, 30 Mar 2025 11:41:54 +0800 Subject: [PATCH 367/382] =?UTF-8?q?fix=EF=BC=9A=E5=91=8A=E8=AD=A6=E6=B8=85?= =?UTF-8?q?=E7=90=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/device_manager_service_impl.cpp | 5 +++-- .../on_data_received_fuzzer.cpp | 20 +++++++++---------- test/unittest/UTTest_auth_negotiate_state.cpp | 18 ----------------- test/unittest/UTTest_auth_pin_auth_state.cpp | 2 -- 4 files changed, 13 insertions(+), 32 deletions(-) diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 6ae1c6944..d303379bf 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -726,7 +726,8 @@ static bool IsAuthManagerSourceByMessage(int32_t msgType) // 获取当前session对象 -std::shared_ptr DeviceManagerServiceImpl::GetCurSession(int sessionId) { +std::shared_ptr DeviceManagerServiceImpl::GetCurSession(int sessionId) +{ std::shared_ptr curSession = nullptr; // 获取对端deviceId,sink端给sessionsMap[deviceId] = session; { @@ -1294,7 +1295,7 @@ error: } int32_t DeviceManagerServiceImpl::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, - const std::map &bindParam) + const std::map &bindParam) { std::string addrType; if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) { diff --git a/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp b/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp index 92d35f26d..81aa2b4a4 100644 --- a/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp +++ b/test/commonfuzztest/ondatareceivedv2_fuzzer/on_data_received_fuzzer.cpp @@ -33,11 +33,11 @@ void OnDataReceivedSrcFuzzTest(const uint8_t* data, size_t size) std::shared_ptr hiChainAuthConnector = std::make_shared(); std::shared_ptr authManager = std::make_shared(softbusConnector, listener, hiChainAuthConnector); - // FuzzedDataProvider fdp(data, size); - // int32_t sessionId = fdp.ConsumeIntegral(); - // std::string message(reinterpret_cast(data), size); - // authManager->OnDataReceived(sessionId, message); - // authManager->OnSessionClosed(sessionId); + FuzzedDataProvider fdp(data, size); + int32_t sessionId = fdp.ConsumeIntegral(); + std::string message(reinterpret_cast(data), size); + authManager->OnDataReceived(sessionId, message); + authManager->OnSessionClosed(sessionId); } // AuthSinkManager fuzz @@ -52,11 +52,11 @@ void OnDataReceivedSinkFuzzTest(const uint8_t* data, size_t size) std::shared_ptr hiChainAuthConnector = std::make_shared(); std::shared_ptr authManager = std::make_shared(softbusConnector, listener, hiChainAuthConnector); -// FuzzedDataProvider fdp(data, size); -// int32_t sessionId = fdp.ConsumeIntegral(); -// std::string message(reinterpret_cast(data), size); -// authManager->OnDataReceived(sessionId, message); -// authManager->OnSessionClosed(sessionId); + FuzzedDataProvider fdp(data, size); + int32_t sessionId = fdp.ConsumeIntegral(); + std::string message(reinterpret_cast(data), size); + authManager->OnDataReceived(sessionId, message); + authManager->OnSessionClosed(sessionId); } } } diff --git a/test/unittest/UTTest_auth_negotiate_state.cpp b/test/unittest/UTTest_auth_negotiate_state.cpp index 16968395a..65f49abb7 100644 --- a/test/unittest/UTTest_auth_negotiate_state.cpp +++ b/test/unittest/UTTest_auth_negotiate_state.cpp @@ -171,23 +171,5 @@ HWTEST_F(AuthNegotiateStateTest, AuthSinkNegotiateStateMachine_001, testing::ext std::shared_ptr authState = std::make_shared(); EXPECT_EQ(authState->GetStateType(), DmAuthStateType::AUTH_SINK_NEGOTIATE_STATE); } - -// AuthSinkNegotiateStateMachine 状态测试用例 -// Action 接口 正常流程 期待DM_OK -// 打桩 DeleteTimer 接口 -// 打桩 GetLocalDeviceName 期待成功 -// GetLocalDeviceNetworkId -// GetLocalDeviceName -// 设置上下文版本,期待CompareVersion 返回true -// CheckIsOnline -// HWTEST_F(AuthNegotiateStateTest, AuthSinkNegotiateStateMachine_001, testing::ext::TestSize.Level1) -// { -// std::shared_ptr authState = std::make_shared(); - - - -// EXPECT_EQ(authState->Action(context), DM_OK); -// } - } } \ No newline at end of file diff --git a/test/unittest/UTTest_auth_pin_auth_state.cpp b/test/unittest/UTTest_auth_pin_auth_state.cpp index ef8abc9f7..8851a7562 100644 --- a/test/unittest/UTTest_auth_pin_auth_state.cpp +++ b/test/unittest/UTTest_auth_pin_auth_state.cpp @@ -166,7 +166,6 @@ HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_002, testing::ext::Test .WillOnce(Return(ON_TRANSMIT)); EXPECT_EQ(authState->Action(context), DM_OK); - } // AuthSinkPinAuthStartState 测试用例 @@ -200,7 +199,6 @@ HWTEST_F(AuthPinAuthStateTest, AuthSinkPinAuthStartState_004, testing::ext::Test .WillOnce(Return(ERR_DM_FAILED)); EXPECT_EQ(authState->Action(context), ERR_DM_FAILED); - } // AuthSinkPinAuthStartState 测试用例 -- Gitee From e4e52b80e5ef92e566fb0fffb778e11c09cf325b Mon Sep 17 00:00:00 2001 From: ZHANGHE24 Date: Sun, 30 Mar 2025 11:48:26 +0800 Subject: [PATCH 368/382] fix: codecheck --- .../include/device_manager_service_impl.h | 1 + .../src/authentication_v2/README.md | 120 ------------------ .../src/authentication_v2/auth_manager.cpp | 9 +- .../auth_stages/auth_confirm.cpp | 2 - .../dm_auth_message_processor.cpp | 40 ------ .../src/authentication_v2/dm_auth_state.cpp | 10 -- .../src/device_manager_service_impl.cpp | 66 +++++----- 7 files changed, 36 insertions(+), 212 deletions(-) delete mode 100644 services/implementation/src/authentication_v2/README.md diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 93357e6c4..55d8ff54a 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -195,6 +195,7 @@ private: int32_t ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, const std::map &bindParam); std::shared_ptr GetConfigByTokenId(); + int OpenAuthSession(const std::map &bindParam); // 清理资源线程 void CleanWorker(); diff --git a/services/implementation/src/authentication_v2/README.md b/services/implementation/src/authentication_v2/README.md deleted file mode 100644 index 050a6e657..000000000 --- a/services/implementation/src/authentication_v2/README.md +++ /dev/null @@ -1,120 +0,0 @@ -1. source和sink的状态机(枚举) -2. 使用sessionId做src端的状态机资源隔离 -3. 实现状态管理类 - 1) 使用transitionTo进行状态迁移 - 2) 对于状态内部,会有action - -##### source -```C++ -// 业务初始化 ->S0 -S0:AuthSrcIdleState // 用户触发BindTarget (S0->S1) -S1:AuthSrcStartState // 收到软总线回调函数OnSessionOpened (S1->S2) -S2:AuthSrcNegotiateState // 收到90协商回复报文 (S2->S3) -S3:AuthSrcConfirmState // 收到110授权结果报文 (S3->S4) -S4:AuthSrcPinAuthStartState // 收到130认证PIN结果报文 (S4->S5) -S5:AuthSrcPinAuthMsgNegotiateState // 收到131认证PIN结果报文(S5->S6) -S6:AuthSrcPinAuthDoneState // 触发Onfinish回调事件 (S6->S7) -S7:AuthSrcCredentialExchangeState // 收到150加密报文 (S7->S8) -S8:AuthSrcCredetialAuthStartState // 收到170凭据认证报文 (S8->S9) -S9:AuthSrcCredetialAuthNegotiateState // 收到171凭据认证报文 (S9->S10) -S10:AuthSrcCredetialAuthDoneState // 触发Onfinish回调事件 (S10->S11) -S11:AuthSrcDataSyncState // 收到190同步报文 (S11->S12) -S12:AuthSrcFinishState - -异常: -1、IPC接口StopAuthenticateDevice触发 // 事件触发 -2、收到MSG_TYPE_REQ_AUTH_TERMINATE -3、各状态下流程超时(丢包) -4、锁屏 -5、参数不合法 -6、pin码输入超时 -7、pin码输入错误(3次前,重回状态,3次后,S8) -以上异常都会让任意状态迁移到S8 - -重点:使用sessionId做src端的状态机资源隔离 - ---- -class AuthSrcStateMachinePool -存储多个状态机实例(AuthSrcStateMachine) -成员函数: -get和set接口(sessionId入参) -成员变量: -使用sessionId隔离多份AuthSrcStateMachine - ---- -class AuthSrcStateMachine -1、提供context上下文存储(设置,获取) -2、操作当前状态(设置、获取(打印)) -3、状态迁移检验功能(下一状态是否在列表中) -4、提供transitionTo函数(事件触发 - 用于事件发生时调用) - -成员变量: -context 上下文 -AuthSrcState 状态 - ---- -class AuthSrcState -Source端的状态基类,提供handleEvent函数: - 1)enter:状态检验 - 2)action:状态迁移时需要做的动作 - 3)exit:状态切换 - -每个state都会继承自改基类,做以上4个函数的具体实现 -``` - -##### sink -```C++ -// 业务初始化 ->S0 -S0:AuthSinkIdleState // 总线触发OnSessionOpened (S0->S1) -S1:AuthSinkStartState // 收到80可信关系协商报文 (S1->S2) -S2:AuthSinkNegotiateState // 收到100用户授权报文 (S2->S3) -S3:AuthSinkConfirmState // 收到120认证PIN报文 (S3->S4) -S4:AuthSinkPinAuthStartState // 收到121认证PIN报文 (S4->S5) -S5: AuthSinkPinAuthMsgNegotiateState // 触发Onfinish回调事件 (S5->S6) -S6: AuthSinkPinAuthDoneState // 收到140加密报文 (S6->S7) -S7:AuthSinkCredentialExchangeState // 收到160凭证认证报文 (S7->S8) -S8:AuthSinkCredetialAuthStartState // 收到161凭据协商报文 (S8->S9) -S9:AuthSinkCredetialAuthNegotiateState // 触发Onfinish回调事件 (S9->S10) -S10: AuthSinkCredetialAuthDoneState // 收到180同步报文 (S10->S11) -S11:AuthSinkDataSyncState // 收到200结束报文 (S11->S12) -S12:AuthSinkFinishState - -异常:(扩展性) -1、IPC接口StopAuthenticateDevice触发 -2、收到MSG_TYPE_REQ_AUTH_TERMINATE -3、各状态下流程超时(丢包) -4、锁屏 -5、参数不合法 -6、pin码输入超时 -7、pin码输入错误(3次前,重回状态,3次后,S8) -8、周边依赖crush => 超时,错误=>异常 - ---- -class AuthSinkStateMachinePool -存储多个状态机实例(AuthSinkStateMachine) -成员函数: -get和set接口(sessionId入参) -成员变量: -使用sessionId隔离多份AuthSinkStateMachine - ---- -class AuthSinkStateMachine -1、提供context上下文存储(设置,获取) -2、操作当前状态(设置、获取(打印)) -3、状态迁移检验功能(下一状态是否在列表中) -4、提供transitionTo函数(事件触发 - 用于事件发生时调用) - -成员变量: -context 上下文 -AuthSinkState 状态 - ---- -class AuthSinkState -Sink端的状态基类,提供transitionTo函数: - 1)enter:状态检验 - 2)action:状态迁移时需要做的动作 - 3)exit:状态切换 - -每个state都会继承自改基类,做以上4个函数的具体实现 - -``` diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index f0cde08a7..62308cef5 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -41,7 +41,7 @@ namespace OHOS { namespace DistributedHardware { namespace { -static const char* PICKER_PROXY_SPLIT = "_pickerProxy_"; // todo check +static const char* PICKER_PROXY_SPLIT = "_pickerProxy_"; constexpr int32_t MIN_PIN_CODE = 100000; constexpr int32_t MAX_PIN_CODE = 999999; @@ -56,9 +56,9 @@ int32_t GetCloseSessionDelaySeconds(std::string &delaySecondsStr) LOGE("Invalid parameter, param is not number."); return 0; } - const int32_t CLOSE_SESSION_DELAY_SECONDS_MAX = 10; + const int32_t closeSessionDelaySecondsMax = 10; int32_t delaySeconds = std::atoi(delaySecondsStr.c_str()); - if (delaySeconds < 0 || delaySeconds > CLOSE_SESSION_DELAY_SECONDS_MAX) { + if (delaySeconds < 0 || delaySeconds > closeSessionDelaySecondsMax) { LOGE("Invalid parameter, param out of range."); return 0; } @@ -266,7 +266,6 @@ int32_t AuthManager::UnRegisterUiStateCallback(const std::string sessionName) int32_t AuthManager::UnAuthenticateDevice(const std::string &sessionName, const std::string &udid, int32_t bindLevel) { - // todo LOGI("AuthManager::UnAuthenticateDevice start"); return ERR_DM_FAILED; } @@ -292,7 +291,6 @@ int32_t AuthManager::ImportAuthCode(const std::string &sessionName, const std::s int32_t AuthManager::UnBindDevice(const std::string &sessionName, const std::string &udid, int32_t bindLevel, const std::string &extra) { - // todo LOGI("AuthManager::UnBindDevice start"); return ERR_DM_FAILED; } @@ -322,7 +320,6 @@ void AuthManager::OnScreenLocked() } void AuthManager::HandleDeviceNotTrust(const std::string &udid) { - // todo LOGI("AuthManager::HandleDeviceNotTrust start"); } diff --git a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp index c23f40734..78cbb8e17 100644 --- a/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp +++ b/services/implementation/src/authentication_v2/auth_stages/auth_confirm.cpp @@ -65,11 +65,9 @@ void AuthSrcConfirmState::NegotiateCredential(std::shared_ptr con context->accesser.bindLevel = DmRole::DM_ROLE_USER; // Exceptions: account related is DEVICE } - // TODO: 添加配件判断 context->accesser.credentialTypeLists.clear(); if (!intersection.empty()) { // 如果交集不为空,将第一个值赋值给 context->accesser.credTypeList - // TODO: 确认优先级是否正确 JsonObject credInfo(context->accesser.credentialInfos[intersection.front()]); if (credInfo[TAG_CRED_ID].IsString()) { context->accesser.credentialTypeLists.push_back(intersection.front()); diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index bb8bafb40..9af1bfee2 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -1420,46 +1420,6 @@ void SetValueFromJson(const JsonItemObject &itemObject, const std::string &key, void FromJson(const JsonItemObject &itemObject, DmAccessControlTable &table) { - // if (itemObject.Contains("accessControlId") && itemObject["accessControlId"].IsNumberInteger()) { - // table.accessControlId = itemObject["accessControlId"].Get(); - // } - // if (itemObject.Contains("accesserId") && itemObject["accesserId"].IsNumberInteger()) { - // table.accesserId = itemObject["accesserId"].Get(); - // } - // if (itemObject.Contains("accesseeId") && itemObject["accesseeId"].IsNumberInteger()) { - // table.accesseeId = itemObject["accesseeId"].Get(); - // } - // if (itemObject.Contains("deviceId") && itemObject["deviceId"].IsString()) { - // table.deviceId = itemObject["deviceId"].Get(); - // } - // if (itemObject.Contains("sessionKey") && itemObject["sessionKey"].IsString()) { - // table.sessionKey = itemObject["sessionKey"].Get(); - // } - // if (itemObject.Contains("bindType") && itemObject["bindType"].IsNumberInteger()) { - // table.bindType = itemObject["bindType"].Get(); - // } - // if (itemObject.Contains("authType") && itemObject["authType"].IsNumberInteger()) { - // table.authType = itemObject["authType"].Get(); - // } - // if (itemObject.Contains("deviceType") && itemObject["deviceType"].IsNumberInteger()) { - // table.deviceType = itemObject["deviceType"].Get(); - // } - // if (itemObject.Contains("deviceIdHash") && itemObject["deviceIdHash"].IsString()) { - // table.deviceIdHash = itemObject["deviceIdHash"].Get(); - // } - // if (itemObject.Contains("status") && itemObject["status"].IsNumberInteger()) { - // table.status = itemObject["status"].Get(); - // } - // if (itemObject.Contains("validPeriod") && itemObject["validPeriod"].IsNumberInteger()) { - // table.validPeriod = itemObject["validPeriod"].Get(); - // } - // if (itemObject.Contains("lastAuthTime") && itemObject["lastAuthTime"].IsNumberInteger()) { - // table.lastAuthTime = itemObject["lastAuthTime"].Get(); - // } - // if (itemObject.Contains("bindLevel") && itemObject["bindLevel"].IsNumberInteger()) { - // table.bindLevel = itemObject["bindLevel"].Get(); - // } - SetValueFromJson(itemObject, "accessControlId", &JsonItemObject::IsNumberInteger, table.accessControlId); SetValueFromJson(itemObject, "accesserId", &JsonItemObject::IsNumberInteger, table.accesserId); SetValueFromJson(itemObject, "accesseeId", &JsonItemObject::IsNumberInteger, table.accesseeId); diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 1f7643fcf..713dd8218 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -460,20 +460,10 @@ int32_t DmAuthState::GetAuthCredentialInfo(std::shared_ptr contex // Ensure credentials match with ACL std::string credId = context->direction == DM_AUTH_SOURCE ? accesser.GetAccesserCredentialId() : accessee.GetAccesseeCredentialId(); - LOGI("Got acl: credId - %{public}s", credId.c_str()); // TODO: delete if (!queryResult.Contains(credId) || item.GetStatus() != ACTIVE) { continue; } - // TODO: delete - LOGI("accesser: deviceId - %{public}s, userId - %{public}d, accountId - %{public}s, tokenId - %{public}ld", - accesser.GetAccesserDeviceId().c_str(), accesser.GetAccesserUserId(), - accesser.GetAccesserAccountId().c_str(), accesser.GetAccesserTokenId()); - LOGI("accessee: deviceId - %{public}s, userId - %{public}d, accountId - %{public}s, tokenId - %{public}ld", - accessee.GetAccesseeDeviceId().c_str(), accessee.GetAccesseeUserId(), - accessee.GetAccesseeAccountId().c_str(), accessee.GetAccesseeTokenId()); - - LOGI("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo success to get acl %{public}s", item.dump().c_str()); // Confirm if there is a trusted relationship uint32_t credType = queryResult[credId][FILED_CRED_TYPE].Get(); if (credType == DM_AUTH_CREDENTIAL_ACCOUNT_RELATED || credType == DM_AUTH_CREDENTIAL_ACCOUNT_ACROSS) { diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 6ae1c6944..71ef390ed 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -49,7 +49,6 @@ constexpr int32_t MAX_ALWAYS_ALLOW_SECONDS = 31536000; constexpr int32_t MIN_PIN_CODE = 100000; constexpr int32_t MAX_PIN_CODE = 999999; // 新协议字段定义,为避免对新协议头文件依赖,不直接依赖新协议头文件 -// TODO: 需要统一到公共头文件中 constexpr int32_t MSG_TYPE_REQ_ACL_NEGOTIATE = 80; constexpr int32_t MSG_TYPE_RESP_ACL_NEGOTIATE = 90; constexpr int32_t MSG_TYPE_REQ_AUTH_TERMINATE = 104; @@ -164,9 +163,7 @@ static uint64_t GetTokenId(bool isSrcSide, int32_t displayId, int32_t userId, st if (deviceId.length() != 0) { tokenId = StringToUint64(deviceId); } - // TODO: 若是device绑定,其他类型绑定不允许,则使用设置标志,不允许其他类型authMgr创建 } - } return tokenId; } @@ -240,10 +237,12 @@ int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide, uint64_ // 创建新auth_mgr,创建authMgrMap_[tokenId] if (isSrcSide) { // src端 - authMgrMap_[tokenId] = std::make_shared(softbusConnector_, listener_, hiChainAuthConnector_); + authMgrMap_[tokenId] = std::make_shared(softbusConnector_, + listener_, hiChainAuthConnector_); } else { // sink端 - authMgrMap_[tokenId] = std::make_shared(softbusConnector_, listener_, hiChainAuthConnector_); + authMgrMap_[tokenId] = std::make_shared(softbusConnector_, + listener_, hiChainAuthConnector_); } // 资源销毁通知函数注册 authMgrMap_[tokenId]->RegisterCleanNotifyCallback(&DeviceManagerServiceImpl::NotifyCleanEvent); @@ -358,12 +357,12 @@ static int64_t GenerateRandNum(int sessionId) std::random_device rd; std::mt19937 gen(rd()); std::uniform_int_distribution<> rand_dis(0, 0xFFFFFFFF); - uint32_t random_number = rand_dis(gen); + uint32_t randomNumber = rand_dis(gen); // 组合随机数 int64_t randNum = (static_cast(timestamp) << 32) | (static_cast(sessionId) << 16) | - static_cast(random_number); + static_cast(randomNumber); return randNum; } @@ -477,9 +476,6 @@ int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const std::string extra = ""; char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - // if (bindLevel == DEVICE) { - // DeleteGroup(pkgName, udid); - // } return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel, extra); } @@ -493,9 +489,6 @@ int32_t DeviceManagerServiceImpl::UnBindDevice(const std::string &pkgName, const } char localDeviceId[DEVICE_UUID_LENGTH] = {0}; GetDevUdid(localDeviceId, DEVICE_UUID_LENGTH); - // if (bindLevel == DEVICE) { - // DeleteGroup(pkgName, udid); - // } return DeleteAcl(pkgName, std::string(localDeviceId), udid, bindLevel, extra); } @@ -811,7 +804,7 @@ void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, } else { if (logicalSessionId != 0) { if (curSession->logicalSessionSet_.find(logicalSessionId) == curSession->logicalSessionSet_.end()) { - LOGE("OnBytesReceived, The logical session ID does not exist in the physical session, so the request is rejected."); + LOGE("OnBytesReceived, The logical session ID does not exist in the physical session."); return; } tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; @@ -829,7 +822,6 @@ void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, 新-老:src端收到90报文时发现版本不匹配问题,重新BindTarget 老-新:sink端收到80报文时发现版本不匹配问题,重新OnSessionOpened和OnBytesReceived - TODO: 考虑authMgr_的切换是否有多线程问题 */ if (curSession->version_ == "" && authMgr->isAuthNewVersion_ && (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE || msgType == MSG_TYPE_RESP_ACL_NEGOTIATE)) { @@ -1013,7 +1005,8 @@ int32_t DeviceManagerServiceImpl::UnRegisterCredentialCallback(const std::string return credentialMgr_->UnRegisterCredentialCallback(pkgName); } -static uint64_t GetSecondElement(const std::string& input) { +static uint64_t GetSecondElement(const std::string& input) +{ std::istringstream stream(input); std::string token; int count = 0; @@ -1227,11 +1220,32 @@ static bool IsHmlSessionType(const JsonObject &jsonObject) return connSessionType == CONN_SESSION_TYPE_HML; } +int DeviceManagerServiceImpl::OpenAuthSession(const std::map &bindParam) +{ + bool hmlEnable160M = false; + int32_t hmlActionId = 0; + JsonObject jsonObject = GetExtraJsonObject(bindParam); + if (jsonObject.IsDiscarded()) { + LOGE("extra string not a json type."); + goto error; + } + if (IsHmlSessionType(jsonObject)) { + if (GetHmlInfo(jsonObject, hmlEnable160M, hmlActionId) != DM_OK) { + goto error; + } + LOGI("hmlActionId %{public}d, hmlEnable160M %{public}d", hmlActionId, hmlEnable160M); + return softbusConnector_->GetSoftbusSession()->OpenAuthSessionWithPara(deviceId, + hmlActionId, hmlEnable160M); + } else { + return softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId); + } +} + std::shared_ptr DeviceManagerServiceImpl::GetOrCreateSession(const std::string& deviceId, const std::map &bindParam) { std::shared_ptr instance; - int sessionId; + int sessionId = -1; // 获取全局锁,确保maps的线程安全 { std::lock_guard lock(mapMutex_); @@ -1257,23 +1271,7 @@ std::shared_ptr DeviceManagerServiceImpl::GetOrCreateSession(const std: return sessionsMap_[sessionId]; } - bool hmlEnable160M = false; - int32_t hmlActionId = 0; - JsonObject jsonObject = GetExtraJsonObject(bindParam); - if (jsonObject.IsDiscarded()) { - LOGE("extra string not a json type."); - goto error; - } - if (IsHmlSessionType(jsonObject)) { - if (GetHmlInfo(jsonObject, hmlEnable160M, hmlActionId) != DM_OK) { - goto error; - } - LOGI("hmlActionId %{public}d, hmlEnable160M %{public}d", hmlActionId, hmlEnable160M); - sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSessionWithPara(deviceId, - hmlActionId, hmlEnable160M); - } else { - sessionId = softbusConnector_->GetSoftbusSession()->OpenAuthSession(deviceId); - } + sessionId = OpenAuthSession(bindParam); if (sessionId < 0) { goto error; -- Gitee From 408d29711054de250977954ce2bb32bae6f0e2f3 Mon Sep 17 00:00:00 2001 From: ZHANGHE24 Date: Sun, 30 Mar 2025 03:49:17 +0000 Subject: [PATCH 369/382] !19 feat: feature_switch * feat: feature_switch --- .../src/authentication/dm_auth_manager.cpp | 2 +- .../src/device_manager_service_impl.cpp | 84 ++++++++++++------- 2 files changed, 56 insertions(+), 30 deletions(-) diff --git a/services/implementation/src/authentication/dm_auth_manager.cpp b/services/implementation/src/authentication/dm_auth_manager.cpp index 306eb9ae4..baf9443a9 100644 --- a/services/implementation/src/authentication/dm_auth_manager.cpp +++ b/services/implementation/src/authentication/dm_auth_manager.cpp @@ -1765,7 +1765,7 @@ void DmAuthManager::ShowAuthInfoDialog(bool authDeviceError) jsonObj[PIN_CODE_KEY] = authResponseContext_->code; std::string authParam = SafetyDump(jsonObj); pincodeDialogEverShown_ = true; - DmDialogManager::GetInstance().ShowPinDialog(std::to_string(authResponseContext_->code)); + DmDialogManager::GetInstance().ShowPinDialog(authParam); } void DmAuthManager::ShowStartAuthDialog() diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index d303379bf..b5f6011f3 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -59,6 +59,12 @@ constexpr const char* DM_TAG_LOGICAL_SESSION_ID = "logicalSessionId"; constexpr const char* DM_TAG_PEER_DISPLAY_ID = "peerDisplayId"; constexpr const char* DM_TAG_ACCESSEE_USER_ID = "accesseeUserId"; constexpr const char* DM_TAG_EXTRA_INFO = "extraInfo"; +constexpr const char* DM_TAG_ENABLE_NEW_PROTOCOL_FLAG = "enable_new_protocol_flag"; + +static int32_t GetEnableNewProtocolFlag() +{ + return GetIntParameter(DM_TAG_ENABLE_NEW_PROTOCOL_FLAG, 0); +} static bool IsMessageOldVersion(const JsonObject &jsonObject, std::shared_ptr session) { @@ -260,6 +266,7 @@ int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide, uint64_ return DM_OK; } } else { + LOGI("DeviceManagerServiceImpl::InitAndRegisterAuthMgr old authMgr."); if (authMgr_ == nullptr) { // 创建老auth_mar,只创建独立的一个 authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, listener_, @@ -269,6 +276,9 @@ int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide, uint64_ hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); return DM_OK; } + if (GetEnableNewProtocolFlag() == 0) { + return DM_OK; + } } // 已创建authMgr_,说明已有绑定事件,其他请求拒绝,返回错误码 LOGE("BindTarget failed, this device is being bound. Please try again later."); @@ -769,10 +779,16 @@ void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, logicalSessionId = jsonObject[DM_TAG_LOGICAL_SESSION_ID].Get(); } - std::shared_ptr curSession = GetCurSession(sessionId); - if (curSession == nullptr) { - LOGE("InitAndRegisterAuthMgr, The physical link is not created."); - return; + std::shared_ptr curSession = nullptr; + if (GetEnableNewProtocolFlag() == 1) { + curSession = GetCurSession(sessionId); + if (curSession == nullptr) { + LOGE("InitAndRegisterAuthMgr, The physical link is not created."); + return; + } + } else { + curSession = std::make_shared(0, std::string("")); + curSession->version = DM_VERSION_5_0_5; } uint64_t tokenId = 0; @@ -1366,29 +1382,37 @@ int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const P return ERR_DM_INPUT_PARA_INVALID; } - std::string deviceId = ""; - ret = ParseConnectAddr(targetId, deviceId, bindParam); - if (ret == DM_OK) { - const_cast(targetId).deviceId = deviceId; - } else { - if (targetId.deviceId.empty()) { - LOGE("DeviceManagerServiceImpl::BindTarget failed, ParseConnectAddr failed."); - return ERR_DM_INPUT_PARA_INVALID; + int sessionId = 0; + int64_t logicalSessionId = 0; + std::shared_ptr curSession = nullptr; + if (GetEnableNewProtocolFlag() == 1) { + std::string deviceId = ""; + ret = ParseConnectAddr(targetId, deviceId, bindParam); + if (ret == DM_OK) { + const_cast(targetId).deviceId = deviceId; + } else { + if (targetId.deviceId.empty()) { + LOGE("DeviceManagerServiceImpl::BindTarget failed, ParseConnectAddr failed."); + return ERR_DM_INPUT_PARA_INVALID; + } + } + // 只在source端创建,新协议同一目标设备不会重复创建 + curSession = GetOrCreateSession(targetId.deviceId, bindParam); + if (curSession == nullptr) { + LOGE("Failed to create the session. Target deviceId: %{public}s.", targetId.deviceId.c_str()); + return ERR_DM_AUTH_OPEN_SESSION_FAILED; } - } - // 只在source端创建,新协议同一目标设备不会重复创建 - auto curSession = GetOrCreateSession(targetId.deviceId, bindParam); - if (curSession == nullptr) { - LOGE("Failed to create the session. Target deviceId: %{public}s.", targetId.deviceId.c_str()); - return ERR_DM_AUTH_OPEN_SESSION_FAILED; - } - // 逻辑会话随机数 - int sessionId = curSession->sessionId_; - int64_t logicalSessionId = GenerateRandNum(sessionId); - if (curSession->logicalSessionSet_.find(logicalSessionId) != curSession->logicalSessionSet_.end()) { - LOGE("Failed to create the logical session."); - return ERR_DM_LOGIC_SESSION_CREATE_FAILED; + // 逻辑会话随机数 + sessionId = curSession->sessionId_; + logicalSessionId = GenerateRandNum(sessionId); + if (curSession->logicalSessionSet_.find(logicalSessionId) != curSession->logicalSessionSet_.end()) { + LOGE("Failed to create the logical session."); + return ERR_DM_LOGIC_SESSION_CREATE_FAILED; + } + } else { + curSession = std::make_shared(0, std::string("")); + curSession->version = DM_VERSION_5_0_5; } // src端创建 @@ -1399,10 +1423,12 @@ int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const P return ret; } - curSession->logicalSessionSet_.insert(logicalSessionId); - curSession->logicalSessionCnt_.fetch_add(1); - logicalSessionId2TokenIdMap_[logicalSessionId] = tokenId; - logicalSessionId2SessionIdMap_[logicalSessionId] = sessionId; + if (GetEnableNewProtocolFlag() == 1) { + curSession->logicalSessionSet_.insert(logicalSessionId); + curSession->logicalSessionCnt_.fetch_add(1); + logicalSessionId2TokenIdMap_[logicalSessionId] = tokenId; + logicalSessionId2SessionIdMap_[logicalSessionId] = sessionId; + } auto authMgr = GetAuthMgr(); if (authMgr != nullptr) { -- Gitee From b04c9b41ee5ccaca7e1bd88d2c8eada619ff6f1e Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Sun, 30 Mar 2025 12:00:24 +0800 Subject: [PATCH 370/382] =?UTF-8?q?fix=EF=BC=9A=E6=B8=85=E7=90=86=E5=91=8A?= =?UTF-8?q?=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dm_auth_message_processor.cpp | 31 ------------------- 1 file changed, 31 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 9af1bfee2..3c8944b7a 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -601,7 +601,6 @@ int32_t DmAuthMessageProcessor::CreateNegotiateMessage(std::shared_ptraccesser.bundleName; jsonObject[TAG_PEER_BUNDLE_NAME] = context->accessee.bundleName; - // jsonObject[TAG_BIND_LEVEL] = context->accesser.bindLevel; JsonObject jsonExtraObject; CreateNegotiateExtraInfoMessage(context, jsonExtraObject); @@ -962,9 +961,6 @@ int32_t DmAuthMessageProcessor::ParseNegotiateMessage(const JsonObject &jsonObje if (jsonObject[TAG_PEER_BUNDLE_NAME].IsString()) { context->accessee.bundleName = jsonObject[TAG_PEER_BUNDLE_NAME].Get(); } - // if (jsonObject[TAG_BIND_LEVEL].IsNumberInteger()) { - // context->accesser.bindLevel = jsonObject[TAG_BIND_LEVEL].Get(); - // } if (jsonObject.Contains(TAG_EXTRA_INFO) && jsonObject[TAG_EXTRA_INFO].IsObject()) { ParseNegotiateExtraInfoMessage(jsonObject[TAG_EXTRA_INFO], context); @@ -1450,33 +1446,6 @@ void ToJson(JsonItemObject &itemObject, const DmAccessToSync &table) void FromJson(const JsonItemObject &itemObject, DmAccessToSync &table) { - // if (itemObject.Contains("deviceName") && itemObject["deviceName"].IsString()) { - // table.deviceName = itemObject["deviceName"].Get(); - // } - // if (itemObject.Contains("deviceId") && itemObject["deviceId"].IsString()) { - // table.deviceId = itemObject["deviceId"].Get(); - // } - // if (itemObject.Contains("userId") && itemObject["userId"].IsNumberInteger()) { - // table.userId = itemObject["userId"].Get(); - // } - // if (itemObject.Contains("accountId") && itemObject["accountId"].IsString()) { - // table.accountId = itemObject["accountId"].Get(); - // } - // if (itemObject.Contains("tokenId") && itemObject["tokenId"].IsNumberInteger()) { - // table.tokenId = itemObject["tokenId"].Get(); - // } - // if (itemObject.Contains("bundleName") && itemObject["bundleName"].IsString()) { - // table.bundleName = itemObject["bundleName"].Get(); - // } - // if (itemObject.Contains("bindLevel") && itemObject["bindLevel"].IsNumberInteger()) { - // table.bindLevel = itemObject["bindLevel"].Get(); - // } - // if (itemObject.Contains("sessionKeyId") && itemObject["sessionKeyId"].IsNumberInteger()) { - // table.sessionKeyId = itemObject["sessionKeyId"].Get(); - // } - // if (itemObject.Contains("skTimeStamp") && itemObject["skTimeStamp"].IsNumberInteger()) { - // table.skTimeStamp = itemObject["skTimeStamp"].Get(); - // } SetValueFromJson(itemObject, "deviceName", &JsonItemObject::IsString, table.deviceName); SetValueFromJson(itemObject, "deviceId", &JsonItemObject::IsString, table.deviceId); SetValueFromJson(itemObject, "userId", &JsonItemObject::IsNumberInteger, table.userId); -- Gitee From d16e7c24392cb1d15df3f417a10cbf2c38ac169f Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Sun, 30 Mar 2025 12:16:39 +0800 Subject: [PATCH 371/382] =?UTF-8?q?fix=EF=BC=9A=E4=BF=AE=E6=94=B9auth=5Fst?= =?UTF-8?q?ate.cpp=E6=96=87=E4=BB=B6=E7=9A=84=E8=B6=85=E5=A4=A7=E5=9C=88?= =?UTF-8?q?=E5=A4=8D=E6=9D=82=E5=BA=A6=E5=87=BD=E6=95=B0?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_state.cpp | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index 713dd8218..a8ab9c954 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -77,11 +77,19 @@ bool HaveSameTokenId(std::shared_ptr context, const std::vectoraccessee.tokenIdHash); } -int32_t GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo, - std::vector &p2pCredIdList, std::vector &lnnCredIdList) +int32_t CheckCredInfo(const JsonItemObject &credInfo) { if (!credInfo[FILED_CRED_TYPE].IsNumberInteger() || !credInfo[FILED_AUTHORIZED_SCOPE].IsNumberInteger() || !credInfo[FILED_SUBJECT].IsNumberInteger()) { + return ERR_DM_FAILED; + } + return DM_OK; +} + +int32_t GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo, + std::vector &p2pCredIdList, std::vector &lnnCredIdList) +{ + if (CheckCredInfo(credInfo) != DM_OK) { LOGE("credType, authorizedScope or subject invalid."); return DM_AUTH_CREDENTIAL_INVALID; } -- Gitee From 7a5414c8d85b7ff32b3cf42cb7a6fcd56e94e108 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Sun, 30 Mar 2025 12:48:48 +0800 Subject: [PATCH 372/382] =?UTF-8?q?fix=EF=BC=9A=E6=B8=85=E7=90=86dm=5Fauth?= =?UTF-8?q?=5Fstate.cpp=E7=9A=84GetCredentialType=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../src/authentication_v2/dm_auth_state.cpp | 40 +++++++++++-------- 1 file changed, 24 insertions(+), 16 deletions(-) diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index a8ab9c954..c7ebc52ec 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -86,6 +86,29 @@ int32_t CheckCredInfo(const JsonItemObject &credInfo) return DM_OK; } +int32_t GetCredentialTypeByCrdInfo(std::shared_ptr context, const JsonItemObject &credInfo, + std::vector &p2pCredIdList, std::vector &lnnCredIdList) +{ + // point_to_point identical + int32_t credType = credInfo[FILED_CRED_TYPE].Get(); + int32_t authorizedScope = credInfo[FILED_AUTHORIZED_SCOPE].Get(); + std::vector appList; + DmAccess &remoteAccess = context->direction == DM_AUTH_SOURCE ? context->accessee : context->accesser; + credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList); + if (credType == ACCOUNT_UNRELATED && + // 查询时无对端userId,只有查询出来后校验对端userId + remoteAccess.userIdHash == Crypto::Sha256(credInfo[FILED_PEER_USER_SPACE_ID].Get())) { + if (authorizedScope == SCOPE_APP && HaveSameTokenId(context, appList)) { + p2pCredIdList.push_back(credInfo[FILED_CRED_ID].Get()); + return DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; + } else if (authorizedScope == SCOPE_USER && appList.empty()) { + lnnCredIdList.push_back(credInfo[FILED_CRED_ID].Get()); + } + } + + return DM_AUTH_CREDENTIAL_INVALID; +} + int32_t GetCredentialType(std::shared_ptr context, const JsonItemObject &credInfo, std::vector &p2pCredIdList, std::vector &lnnCredIdList) { @@ -117,22 +140,7 @@ int32_t GetCredentialType(std::shared_ptr context, const JsonItem } } - // point_to_point identical - std::vector appList; - DmAccess &remoteAccess = context->direction == DM_AUTH_SOURCE ? context->accessee : context->accesser; - credInfo[FILED_AUTHORIZED_APP_LIST].Get(appList); - if (credType == ACCOUNT_UNRELATED && - // 查询时无对端userId,只有查询出来后校验对端userId - remoteAccess.userIdHash == Crypto::Sha256(credInfo[FILED_PEER_USER_SPACE_ID].Get())) { - if (authorizedScope == SCOPE_APP && HaveSameTokenId(context, appList)) { - p2pCredIdList.push_back(credInfo[FILED_CRED_ID].Get()); - return DM_AUTH_CREDENTIAL_ACCOUNT_UNRELATED; - } else if (authorizedScope == SCOPE_USER && appList.empty()) { - lnnCredIdList.push_back(credInfo[FILED_CRED_ID].Get()); - } - } - - return DM_AUTH_CREDENTIAL_INVALID; + return GetCredentialTypeByCrdInfo(context, credInfo, p2pCredIdList, lnnCredIdList); } int32_t DmQueryDmCredential(std::shared_ptr context, JsonObject &queryResult) -- Gitee From 2b72a746c0b0ea6036333ce177bc97eaab301368 Mon Sep 17 00:00:00 2001 From: xw1997-clike <2247596987@qq.com> Date: Sun, 30 Mar 2025 12:51:05 +0800 Subject: [PATCH 373/382] =?UTF-8?q?fix=EF=BC=9A=E6=B8=85=E7=90=86impl.cpp?= =?UTF-8?q?=E5=91=8A=E8=AD=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../implementation/src/device_manager_service_impl.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index c399d5cb2..4625c34b7 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -192,7 +192,8 @@ void DeviceManagerServiceImpl::CleanWorker() { while (running_.load()) { auto logicalSessionId = FetchCleanEvent(); - LOGD("DeviceManagerServiceImpl::CleanWorker clean auth_mgr, its logicalSessionId: %{public}lld", logicalSessionId); + LOGD("DeviceManagerServiceImpl::CleanWorker clean auth_mgr, its logicalSessionId: %{public}lld", + logicalSessionId); CleanAuthMgrByLogicalSessionId(logicalSessionId); } LOGD("DeviceManagerServiceImpl::CleanWorker end"); @@ -361,7 +362,8 @@ std::shared_ptr DeviceManagerServiceImpl::GetAuthMgrByTokenId(u static int64_t GenerateRandNum(int sessionId) { // 获取当前时间戳 - auto timestamp = std::chrono::duration_cast(std::chrono::high_resolution_clock::now().time_since_epoch()).count(); + auto timestamp = std::chrono::duration_cast(std::chrono::high_resolution_clock::now(). + time_since_epoch()).count(); // 生成随机数 std::random_device rd; @@ -817,7 +819,6 @@ void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, // 内部已完成错误日志打印 return; } - } else { if (logicalSessionId != 0) { if (curSession->logicalSessionSet_.find(logicalSessionId) == curSession->logicalSessionSet_.end()) { @@ -1289,7 +1290,6 @@ std::shared_ptr DeviceManagerServiceImpl::GetOrCreateSession(const std: } sessionId = OpenAuthSession(bindParam); - if (sessionId < 0) { goto error; } -- Gitee From 7fe7853ff4727d3a092f12b4f7061846b531c383 Mon Sep 17 00:00:00 2001 From: ZHANGHE24 Date: Sun, 30 Mar 2025 15:17:38 +0800 Subject: [PATCH 374/382] fix: codecheck --- .../include/device_manager_service_impl.h | 6 + .../dependency/softbus/softbus_connector.cpp | 4 - .../dependency/softbus/softbus_session.cpp | 6 + .../src/device_manager_service_impl.cpp | 227 +++++++++--------- 4 files changed, 131 insertions(+), 112 deletions(-) diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 55d8ff54a..bc954fc54 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -197,6 +197,12 @@ private: std::shared_ptr GetConfigByTokenId(); int OpenAuthSession(const std::map &bindParam); + std::shared_ptr GetAuthMgrByMessage(int32_t msgType, int64_t logicalSessionId, + const JsonObject &jsonObject, std::shared_ptr curSession, uint64_t &tokenId); + int32_t TransferOldAuthMgr(int32_t msgType, int64_t logicalSessionId, std::shared_ptr curSession, + uint64_t tokenId, std::shared_ptr authMgr); + int32_t GetDeviceInfo(std::string &deviceId, std::shared_ptr deviceInfo, int32_t &index); + // 清理资源线程 void CleanWorker(); // 停止线程 diff --git a/services/implementation/src/dependency/softbus/softbus_connector.cpp b/services/implementation/src/dependency/softbus/softbus_connector.cpp index 46e6449d9..3bcefa4e9 100644 --- a/services/implementation/src/dependency/softbus/softbus_connector.cpp +++ b/services/implementation/src/dependency/softbus/softbus_connector.cpp @@ -149,14 +149,10 @@ void SoftbusConnector::JoinLNNBySkId(int32_t sessionId, int32_t sessionKeyId, in addrInfo->info.session.sessionId = sessionId; addrInfo->deviceKeyId.hasDeviceKeyId = true; // 总线修改后适配 if (sessionKeyId > 0 && remoteSessionKeyId > 0) { - // addrInfo->info.session.localDeviceKeyId = sessionKeyId; - // addrInfo->info.session.remoteDeviceKeyId = remoteSessionKeyId; addrInfo->deviceKeyId.localDeviceKeyId = sessionKeyId; // 总线修改后适配 addrInfo->deviceKeyId.remoteDeviceKeyId = remoteSessionKeyId; // 总线修改后适配 LOGI("sessionKeyId valid"); } else { - // addrInfo->info.session.localDeviceKeyId = 0; - // addrInfo->info.session.remoteDeviceKeyId = 0; addrInfo->deviceKeyId.localDeviceKeyId = 0; // 总线修改后适配 addrInfo->deviceKeyId.remoteDeviceKeyId = 0; // 总线修改后适配 } diff --git a/services/implementation/src/dependency/softbus/softbus_session.cpp b/services/implementation/src/dependency/softbus/softbus_session.cpp index 59be600ed..007323eea 100644 --- a/services/implementation/src/dependency/softbus/softbus_session.cpp +++ b/services/implementation/src/dependency/softbus/softbus_session.cpp @@ -201,6 +201,12 @@ void SoftbusSession::OnSessionClosed(int sessionId) void SoftbusSession::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) { + std::string message = std::string(reinterpret_cast(data), dataLen); + if (msgType == AUTH_DEVICE_REQ_NEGOTIATE || msgType == AUTH_DEVICE_RESP_NEGOTIATE) { + authMgr->OnAuthDeviceDataReceived(sessionId, message); + } else { + authMgr->OnDataReceived(sessionId, message); + } LOGI("start, sessionId: %{public}d, dataLen: %{public}d.", sessionId, dataLen); return; } diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 4625c34b7..9db786756 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -58,7 +58,7 @@ constexpr const char* DM_TAG_LOGICAL_SESSION_ID = "logicalSessionId"; constexpr const char* DM_TAG_PEER_DISPLAY_ID = "peerDisplayId"; constexpr const char* DM_TAG_ACCESSEE_USER_ID = "accesseeUserId"; constexpr const char* DM_TAG_EXTRA_INFO = "extraInfo"; -constexpr const char* DM_TAG_ENABLE_NEW_PROTOCOL_FLAG = "enable_new_protocol_flag"; +constexpr const char* DM_TAG_ENABLE_NEW_PROTOCOL_FLAG = "sec_enhance_flag"; static int32_t GetEnableNewProtocolFlag() { @@ -746,47 +746,9 @@ std::shared_ptr DeviceManagerServiceImpl::GetCurSession(int sessionId) return curSession; } - -void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) +std::shared_ptr DeviceManagerServiceImpl::GetAuthMgrByMessage(int32_t msgType, + int64_t logicalSessionId, const JsonObject &jsonObject, std::shared_ptr curSession, uint64_t &tokenId) { - /* - 1、收到80报文创建auth_mgr - 2、收到80或90报文时,获取版本, 对比进行auth_mgr重建,执行老协议 - 3、分发报文 - */ - int32_t ret = DM_OK; - if (sessionId < 0 || data == nullptr || dataLen <= 0 || dataLen > MAX_DATA_LEN) { - LOGE("[OnBytesReceived] Fail to receive data from softbus with sessionId: %{public}d, dataLen: %{public}d.", - sessionId, dataLen); - return; - } - - LOGI("start, sessionId: %{public}d, dataLen: %{public}d.", sessionId, dataLen); - - JsonObject jsonObject = GetJsonObjectFromData(data, dataLen); - if (jsonObject.IsDiscarded() || !jsonObject[TAG_MSG_TYPE].IsNumberInteger()) { - LOGE("OnBytesReceived, MSG_TYPE parse failed."); - return; - } - int32_t msgType = jsonObject[TAG_MSG_TYPE].Get(); - int64_t logicalSessionId = 0; - if (jsonObject[DM_TAG_LOGICAL_SESSION_ID].IsNumberInteger()) { - logicalSessionId = jsonObject[DM_TAG_LOGICAL_SESSION_ID].Get(); - } - - std::shared_ptr curSession = nullptr; - if (GetEnableNewProtocolFlag() == 1) { - curSession = GetCurSession(sessionId); - if (curSession == nullptr) { - LOGE("InitAndRegisterAuthMgr, The physical link is not created."); - return; - } - } else { - curSession = std::make_shared(0, std::string("")); - curSession->version = DM_VERSION_5_0_5; - } - - uint64_t tokenId = 0; if (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE) { if (logicalSessionId != 0) { curSession->logicalSessionSet_.insert(logicalSessionId); @@ -799,37 +761,119 @@ void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, if (jsonObject[DM_TAG_PEER_DISPLAY_ID].IsNumberInteger()) { displayId = jsonObject[DM_TAG_PEER_DISPLAY_ID].Get(); } - if (jsonObject.Contains(DM_TAG_EXTRA_INFO) && jsonObject[DM_TAG_EXTRA_INFO].IsObject()) { - if (jsonObject[DM_TAG_EXTRA_INFO][DM_TAG_ACCESSEE_USER_ID].IsNumberInteger()) { - userId = jsonObject[DM_TAG_EXTRA_INFO][DM_TAG_ACCESSEE_USER_ID].Get(); - } + if (jsonObject.Contains(DM_TAG_EXTRA_INFO) && jsonObject[DM_TAG_EXTRA_INFO].IsObject() && + jsonObject[DM_TAG_EXTRA_INFO][DM_TAG_ACCESSEE_USER_ID].IsNumberInteger()) { + userId = jsonObject[DM_TAG_EXTRA_INFO][DM_TAG_ACCESSEE_USER_ID].Get(); } tokenId = GetTokenId(false, displayId, userId, bundleName); if (tokenId == 0) { LOGE("OnBytesReceived, Get tokenId failed."); - return; + return nullptr; } if (logicalSessionId2TokenIdMap_.find(logicalSessionId) != logicalSessionId2TokenIdMap_.end()) { LOGE("OnBytesReceived, logicalSessionId exists in logicalSessionId2TokenIdMap_."); - return; + return nullptr; } logicalSessionId2TokenIdMap_[logicalSessionId] = tokenId; } if (InitAndRegisterAuthMgr(false, tokenId, curSession, logicalSessionId) != DM_OK) { // 内部已完成错误日志打印 - return; + return nullptr; } } else { if (logicalSessionId != 0) { if (curSession->logicalSessionSet_.find(logicalSessionId) == curSession->logicalSessionSet_.end()) { LOGE("OnBytesReceived, The logical session ID does not exist in the physical session."); - return; + return nullptr; } tokenId = logicalSessionId2TokenIdMap_[logicalSessionId]; } } - auto authMgr = GetAuthMgrByTokenId(tokenId); + return GetAuthMgrByTokenId(tokenId); +} + +int32_t DeviceManagerServiceImpl::TransferOldAuthMgr(int32_t msgType, int64_t logicalSessionId, + std::shared_ptr curSession, uint64_t tokenId, std::shared_ptr authMgr) +{ + std::string pkgName; + PeerTargetId peerTargetId; + std::map bindParam; + authMgr->GetBindTargetParams(pkgName, peerTargetId, bindParam); + authMgr = nullptr; + authMgrMap_.erase(tokenId); + if (InitAndRegisterAuthMgr(false, tokenId, curSession, logicalSessionId) != DM_OK) { + // 内部已完成错误日志打印 + return ERR_DM_AUTH_FAILED; + } + + authMgr = GetAuthMgrByTokenId(tokenId); // 获取到老协议的authmgr + if (authMgr == nullptr) { + // 内部已完成错误日志打印 + return ERR_DM_AUTH_FAILED; + } + authMgr->isAuthNewVersion_ = false; + + if (IsAuthManagerSourceByMessage(msgType)) { + // 发送停止报文 + // 不能走新协议的停止,新协议是信号机制,无法串行停止,会存在时延,导致未停止就创建了新对象, + // 然后新协议的超时机制会再次停止softbus + std::string endMessage = CreateTerminateMessage(); + (void)softbusConnector_->GetSoftbusSession()->SendData(sessionId, endMessage); + // 关闭新协议会话 + CleanSessionMapByLogicalSessionId(logicalSessionId); + + ret = authMgr->BindTarget(pkgName, peerTargetId, bindParam, sessionId, 0); + if (ret != DM_OK) { + LOGE("DeviceManagerServiceImpl::OnBytesReceived authManager BindTarget failed"); + return ERR_DM_AUTH_FAILED; + } + LOGI("DeviceManagerServiceImpl::OnBytesReceived src transfer to old version success"); + return DM_OK; + } + + // 参数2 sessionSide为0,authMgr_为空一定是sink端,src端会在BindTarget时创建协议对象 + authMgr->OnSessionOpened(sessionId, 0, 0); + LOGI("DeviceManagerServiceImpl::OnBytesReceived src transfer to old version success"); + return DM_OK; +} + + +void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) +{ + if (sessionId < 0 || data == nullptr || dataLen <= 0 || dataLen > MAX_DATA_LEN) { + LOGE("[OnBytesReceived] Fail to receive data from softbus with sessionId: %{public}d, dataLen: %{public}d.", + sessionId, dataLen); + return; + } + + LOGI("start, sessionId: %{public}d, dataLen: %{public}d.", sessionId, dataLen); + + JsonObject jsonObject = GetJsonObjectFromData(data, dataLen); + if (jsonObject.IsDiscarded() || !jsonObject[TAG_MSG_TYPE].IsNumberInteger()) { + LOGE("OnBytesReceived, MSG_TYPE parse failed."); + return; + } + int32_t msgType = jsonObject[TAG_MSG_TYPE].Get(); + int64_t logicalSessionId = 0; + if (jsonObject[DM_TAG_LOGICAL_SESSION_ID].IsNumberInteger()) { + logicalSessionId = jsonObject[DM_TAG_LOGICAL_SESSION_ID].Get(); + } + + std::shared_ptr curSession = nullptr; + if (GetEnableNewProtocolFlag() == 1) { + curSession = GetCurSession(sessionId); + if (curSession == nullptr) { + LOGE("InitAndRegisterAuthMgr, The physical link is not created."); + return; + } + } else { + curSession = std::make_shared(0, std::string("")); + curSession->version = DM_VERSION_5_0_5; + } + + uint64_t tokenId = 0; + auto authMgr = GetAuthMgrByMessage(msgType, logicalSessionId, jsonObject, curSession, tokenId); if (authMgr == nullptr) { // 内部已完成错误日志打印 return; @@ -839,59 +883,16 @@ void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, 监听80/90报文 新-老:src端收到90报文时发现版本不匹配问题,重新BindTarget 老-新:sink端收到80报文时发现版本不匹配问题,重新OnSessionOpened和OnBytesReceived - */ if (curSession->version_ == "" && authMgr->isAuthNewVersion_ && (msgType == MSG_TYPE_REQ_ACL_NEGOTIATE || msgType == MSG_TYPE_RESP_ACL_NEGOTIATE)) { - // IsMessageOldVersion内部会对session版本进行赋值,并解除对应物理会话信号量 if (IsMessageOldVersion(jsonObject, curSession)) { - std::string pkgName; - PeerTargetId peerTargetId; - std::map bindParam; - authMgr->GetBindTargetParams(pkgName, peerTargetId, bindParam); - authMgr = nullptr; - authMgrMap_.erase(tokenId); - if (InitAndRegisterAuthMgr(false, tokenId, curSession, logicalSessionId) != DM_OK) { - // 内部已完成错误日志打印 - return; - } - - authMgr = GetAuthMgrByTokenId(tokenId); // 获取到老协议的authmgr - if (authMgr == nullptr) { - // 内部已完成错误日志打印 - return; - } - authMgr->isAuthNewVersion_ = false; - - if (IsAuthManagerSourceByMessage(msgType)) { - // 发送停止报文 - // 不能走新协议的停止,新协议是信号机制,无法串行停止,会存在时延,导致未停止就创建了新对象, - // 然后新协议的超时机制会再次停止softbus - std::string endMessage = CreateTerminateMessage(); - (void)softbusConnector_->GetSoftbusSession()->SendData(sessionId, endMessage); - // 关闭新协议会话 - CleanSessionMapByLogicalSessionId(logicalSessionId); - - ret = authMgr->BindTarget(pkgName, peerTargetId, bindParam, sessionId, 0); - if (ret != DM_OK) { - LOGE("DeviceManagerServiceImpl::OnBytesReceived authManager BindTarget failed"); - return; - } - LOGI("DeviceManagerServiceImpl::OnBytesReceived src transfer to old version success"); + if (TransferOldAuthMgr(msgType, logicalSessionId, curSession, tokenId, authMgr) != DM_OK) { + LOGE("DeviceManagerServiceImpl::OnBytesReceived TransferOldAuthMgr failed"); return; } - - // 参数2 sessionSide为0,authMgr_为空一定是sink端,src端会在BindTarget时创建协议对象 - authMgr->OnSessionOpened(sessionId, 0, 0); - LOGI("DeviceManagerServiceImpl::OnBytesReceived src transfer to old version success"); } } - std::string message = std::string(reinterpret_cast(data), dataLen); - if (msgType == AUTH_DEVICE_REQ_NEGOTIATE || msgType == AUTH_DEVICE_RESP_NEGOTIATE) { - authMgr->OnAuthDeviceDataReceived(sessionId, message); - } else { - authMgr->OnDataReceived(sessionId, message); - } SoftbusSession::OnBytesReceived(sessionId, data, dataLen); LOGI("DeviceManagerServiceImpl::OnBytesReceived in bytes received"); return; @@ -1308,18 +1309,12 @@ error: return nullptr; } -int32_t DeviceManagerServiceImpl::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, - const std::map &bindParam) +int32_t DeviceManagerServiceImpl::GetDeviceInfo(std::string &deviceId, std::shared_ptr deviceInfo, + int32_t &index) { - std::string addrType; - if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) { - addrType = bindParam.at(PARAM_KEY_CONN_ADDR_TYPE); - } - int32_t index = 0; - std::shared_ptr deviceInfo = std::make_shared(); ConnectionAddr addr; if (!targetId.wifiIp.empty() && targetId.wifiIp.length() <= IP_STR_MAX_LEN) { - LOGI("AuthManager::ParseConnectAddr parse wifiIp: %{public}s.", GetAnonyString(targetId.wifiIp).c_str()); + LOGI("parse wifiIp: %{public}s.", GetAnonyString(targetId.wifiIp).c_str()); if (!addrType.empty()) { addr.type = static_cast(std::atoi(addrType.c_str())); } else { @@ -1334,7 +1329,7 @@ int32_t DeviceManagerServiceImpl::ParseConnectAddr(const PeerTargetId &targetId, deviceId = targetId.wifiIp; index++; } else if (!targetId.brMac.empty() && targetId.brMac.length() <= BT_MAC_LEN) { - LOGI("AuthManager::ParseConnectAddr parse brMac: %{public}s.", GetAnonyString(targetId.brMac).c_str()); + LOGI("parse brMac: %{public}s.", GetAnonyString(targetId.brMac).c_str()); addr.type = ConnectionAddrType::CONNECTION_ADDR_BR; if (memcpy_s(addr.info.br.brMac, BT_MAC_LEN, targetId.brMac.c_str(), targetId.brMac.length()) != 0) { LOGE("get brMac addr: %{public}s failed", GetAnonyString(targetId.brMac).c_str()); @@ -1344,7 +1339,7 @@ int32_t DeviceManagerServiceImpl::ParseConnectAddr(const PeerTargetId &targetId, deviceId = targetId.brMac; index++; } else if (!targetId.bleMac.empty() && targetId.bleMac.length() <= BT_MAC_LEN) { - LOGI("AuthManager::ParseConnectAddr parse bleMac: %{public}s.", GetAnonyString(targetId.bleMac).c_str()); + LOGI("parse bleMac: %{public}s.", GetAnonyString(targetId.bleMac).c_str()); addr.type = ConnectionAddrType::CONNECTION_ADDR_BLE; if (memcpy_s(addr.info.ble.bleMac, BT_MAC_LEN, targetId.bleMac.c_str(), targetId.bleMac.length()) != 0) { LOGE("get bleMac addr: %{public}s failed", GetAnonyString(targetId.bleMac).c_str()); @@ -1358,13 +1353,29 @@ int32_t DeviceManagerServiceImpl::ParseConnectAddr(const PeerTargetId &targetId, deviceId = targetId.bleMac; index++; } else { - LOGE("AuthManager::ParseConnectAddr failed, not addr."); + LOGE("DeviceManagerServiceImpl::GetDeviceInfo failed, not addr."); return ERR_DM_INPUT_PARA_INVALID; } + return DM_OK; +} + +int32_t DeviceManagerServiceImpl::ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, + const std::map &bindParam) +{ + std::string addrType; + if (bindParam.count(PARAM_KEY_CONN_ADDR_TYPE) != 0) { + addrType = bindParam.at(PARAM_KEY_CONN_ADDR_TYPE); + } + std::shared_ptr deviceInfo = std::make_shared(); + int32_t index = 0; + int32_t ret = GetDeviceInfo(deviceId, deviceInfo, index); + if (ret != DM_OK) { + LOGE("GetDeviceInfo failed, ret: %{public}d", ret); + } deviceInfo->addrNum = static_cast(index); if (softbusConnector_->AddMemberToDiscoverMap(deviceId, deviceInfo) != DM_OK) { - LOGE("AuthManager::ParseConnectAddr failed, AddMemberToDiscoverMap failed."); + LOGE("DeviceManagerServiceImpl::ParseConnectAddr failed, AddMemberToDiscoverMap failed."); return ERR_DM_INPUT_PARA_INVALID; } deviceInfo = nullptr; -- Gitee From 4f559ce3d45c4398d11cd321380850c1494a6cab Mon Sep 17 00:00:00 2001 From: ZHANGHE24 Date: Sun, 30 Mar 2025 13:21:39 +0800 Subject: [PATCH 375/382] fix: bug --- .../include/device_manager_service_impl.h | 3 +-- .../src/device_manager_service_impl.cpp | 16 ++++++++-------- 2 files changed, 9 insertions(+), 10 deletions(-) diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 55d8ff54a..a3fe02fac 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -55,7 +55,6 @@ public: struct Config { std::string pkgName; std::string authCode; - uint64_t tokenId; int32_t authenticationType{0}; }; @@ -195,7 +194,7 @@ private: int32_t ParseConnectAddr(const PeerTargetId &targetId, std::string &deviceId, const std::map &bindParam); std::shared_ptr GetConfigByTokenId(); - int OpenAuthSession(const std::map &bindParam); + int OpenAuthSession(const std::string& deviceId, const std::map &bindParam); // 清理资源线程 void CleanWorker(); diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 4625c34b7..28088a3d0 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -783,7 +783,7 @@ void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, } } else { curSession = std::make_shared(0, std::string("")); - curSession->version = DM_VERSION_5_0_5; + curSession->version_ = DM_VERSION_5_0_5; } uint64_t tokenId = 0; @@ -1166,7 +1166,6 @@ std::shared_ptr DeviceManagerServiceImpl::GetConfigByTokenId() if (configsMap_.find(tokenId) == configsMap_.end()) { configsMap_[tokenId] = std::make_shared(); } - configsMap_[tokenId]->tokenId = tokenId; return configsMap_[tokenId]; } @@ -1182,7 +1181,6 @@ int32_t DeviceManagerServiceImpl::ImportAuthCode(const std::string &pkgName, con auto authMgr = GetAuthMgr(); if (authMgr == nullptr) { auto config = GetConfigByTokenId(); - LOGI("DeviceManagerServiceImpl::ImportAuthCode import for tokenId %{public}llu", config->tokenId); config->pkgName = pkgName; config->authCode = authCode; // 若多次注册,只保留最后一个 return DM_OK; @@ -1238,18 +1236,20 @@ static bool IsHmlSessionType(const JsonObject &jsonObject) return connSessionType == CONN_SESSION_TYPE_HML; } -int DeviceManagerServiceImpl::OpenAuthSession(const std::map &bindParam) +int DeviceManagerServiceImpl::OpenAuthSession(const std::string& deviceId, + const std::map &bindParam) { bool hmlEnable160M = false; int32_t hmlActionId = 0; JsonObject jsonObject = GetExtraJsonObject(bindParam); if (jsonObject.IsDiscarded()) { LOGE("extra string not a json type."); - goto error; + return -1; } if (IsHmlSessionType(jsonObject)) { if (GetHmlInfo(jsonObject, hmlEnable160M, hmlActionId) != DM_OK) { - goto error; + LOGE("OpenAuthSession failed, GetHmlInfo failed."); + return -1; } LOGI("hmlActionId %{public}d, hmlEnable160M %{public}d", hmlActionId, hmlEnable160M); return softbusConnector_->GetSoftbusSession()->OpenAuthSessionWithPara(deviceId, @@ -1289,7 +1289,7 @@ std::shared_ptr DeviceManagerServiceImpl::GetOrCreateSession(const std: return sessionsMap_[sessionId]; } - sessionId = OpenAuthSession(bindParam); + sessionId = OpenAuthSession(deviceId, bindParam); if (sessionId < 0) { goto error; } @@ -1410,7 +1410,7 @@ int32_t DeviceManagerServiceImpl::BindTarget(const std::string &pkgName, const P } } else { curSession = std::make_shared(0, std::string("")); - curSession->version = DM_VERSION_5_0_5; + curSession->version_ = DM_VERSION_5_0_5; } // src端创建 -- Gitee From 2d5bc85afc420c75a95ad9b1d525f78ca9d2d2d1 Mon Sep 17 00:00:00 2001 From: gaoqiang_strong Date: Sun, 30 Mar 2025 15:38:47 +0800 Subject: [PATCH 376/382] deleteAcl codecheck Signed-off-by: gaoqiang_strong --- .../src/device_manager_service_impl.cpp | 39 +++++-------------- 1 file changed, 10 insertions(+), 29 deletions(-) diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index 66148b036..a2738e924 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -2044,43 +2044,24 @@ int32_t DeviceManagerServiceImpl::DeleteAcl(const std::string &sessionName, cons LOGE("Acl not contain the sessionName bind data."); return ERR_DM_FAILED; } - if (bindLevel == static_cast(APP) || bindLevel == static_cast(SERVICE)) { - if (offlineParam.leftAclNumber != 0) { + auto authMgr = GetAuthMgr(); + if (authMgr == nullptr) { + LOGE("authMgr_ is nullptr"); + return ERR_DM_POINT_NULL; + } + if (offlineParam.leftAclNumber != 0) { + if (bindLevel == static_cast(APP) || bindLevel == static_cast(SERVICE)) { LOGI("The sessionName unbind app-level type leftAclNumber not zero."); softbusConnector_->SetProcessInfoVec(offlineParam.processVec); softbusConnector_->HandleDeviceOffline(remoteUdid); return DM_OK; } - if (offlineParam.leftAclNumber == 0) { - LOGI("The sessionName unbind app-level type leftAclNumber is zero."); - softbusConnector_->SetProcessInfoVec(offlineParam.processVec); - auto authMgr = GetAuthMgr(); - if (authMgr == nullptr) { - LOGE("authMgr_ is nullptr"); - return ERR_DM_POINT_NULL; - } - if (authMgr->isAuthNewVersion_) { - int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); - for (auto credId : offlineParam.credIdVec) { - hiChainAuthConnector_->DeleteCredential(accountId, credId); - } - } else { - hiChainAuthConnector_->DeleteCredential(remoteUdid, MultipleUserConnector::GetCurrentAccountUserID()); - } - return DM_OK; - } - } - if (bindLevel == static_cast(DEVICE) && offlineParam.leftAclNumber != 0) { LOGI("Unbind deivce-level, retain identical account bind type."); return DM_OK; } - if (bindLevel == static_cast(DEVICE) && offlineParam.leftAclNumber == 0) { - LOGI("Unbind deivce-level, retain null."); - auto authMgr = GetAuthMgr(); - if (authMgr == nullptr) { - LOGE("authMgr_ is nullptr"); - return ERR_DM_POINT_NULL; - } + if (offlineParam.leftAclNumber == 0) { + LOGI("The sessionName unbind app-level type leftAclNumber is zero."); + softbusConnector_->SetProcessInfoVec(offlineParam.processVec); if (authMgr->isAuthNewVersion_) { int32_t accountId = MultipleUserConnector::GetCurrentAccountUserID(); for (auto credId : offlineParam.credIdVec) { -- Gitee From f05b2a8ef9c819b7a5d40cd8cf12701f13722b85 Mon Sep 17 00:00:00 2001 From: ZHANGHE24 Date: Sun, 30 Mar 2025 16:04:49 +0800 Subject: [PATCH 377/382] fix: bug --- .../implementation/src/authentication_v2/auth_manager.cpp | 4 ++-- .../src/authentication_v2/dm_auth_message_processor.cpp | 4 ++-- services/implementation/src/cryptomgr/crypto_mgr.cpp | 1 - 3 files changed, 4 insertions(+), 5 deletions(-) diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 62308cef5..688f6088d 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -359,7 +359,7 @@ void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sess LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64 "is error.", requestId); return; } - int32_t ret = context_->authMessageProcessor->SaveSessionKey(sessionKey, sessionKeyLen); + int32_t ret = context_->authMessageProcessor->ProcessSessionKey(sessionKey, sessionKeyLen); if (ret != DM_OK) { LOGE("AuthSrcManager::AuthDeviceSessionKey, save session key error, ret: %{public}d", ret); } @@ -1036,7 +1036,7 @@ void AuthSinkManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *ses LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64 "is error.", requestId); return; } - int32_t ret = context_->authMessageProcessor->SaveSessionKey(sessionKey, sessionKeyLen); + int32_t ret = context_->authMessageProcessor->ProcessSessionKey(sessionKey, sessionKeyLen); if (ret != DM_OK) { LOGE("AuthSrcManager::AuthDeviceSessionKey, save session key error, ret: %{public}d", ret); } diff --git a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp index 3c8944b7a..ff1242b68 100644 --- a/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_message_processor.cpp @@ -204,13 +204,13 @@ int32_t DmAuthMessageProcessor::SaveSessionKey(const uint8_t *sessionKey, const LOGE("DmAuthMessageProcessor::SaveSessionKey failed, cryptoMgr_ is nullptr."); return ERR_DM_FAILED; } - return cryptoMgr_->SaveSessionKey(sessionKey, keyLen); + return cryptoMgr_->ProcessSessionKey(sessionKey, keyLen); } int32_t DmAuthMessageProcessor::SaveSessionKeyToDP(int32_t &skId) { if (cryptoMgr_ == nullptr) { - LOGE("DmAuthMessageProcessor::SaveSessionKey failed, cryptoMgr_ is nullptr."); + LOGE("DmAuthMessageProcessor::SaveSessionKeyToDP failed, cryptoMgr_ is nullptr."); return ERR_DM_FAILED; } uint32_t skLen = cryptoMgr_->GetSessionKey(nullptr); diff --git a/services/implementation/src/cryptomgr/crypto_mgr.cpp b/services/implementation/src/cryptomgr/crypto_mgr.cpp index 1e9e1cf22..9c65dd373 100644 --- a/services/implementation/src/cryptomgr/crypto_mgr.cpp +++ b/services/implementation/src/cryptomgr/crypto_mgr.cpp @@ -305,7 +305,6 @@ int32_t CryptoMgr::SaveSessionKey(const uint8_t *sessionKey, const uint32_t keyL std::lock_guard lock(sessionKeyMtx_); sessionKey_.key = (uint8_t*)calloc(keyLen, sizeof(uint8_t)); sessionKey_.keyLen = keyLen; - memcpy_s(sessionKey_.key, keyLen, sessionKey, keyLen); } return DM_OK; } -- Gitee From 100892a6dd29d21c5bc5dac1b8934ce61a3921b6 Mon Sep 17 00:00:00 2001 From: ZHANGHE24 Date: Sun, 30 Mar 2025 16:19:45 +0800 Subject: [PATCH 378/382] fix: bug --- services/implementation/src/device_manager_service_impl.cpp | 3 +++ 1 file changed, 3 insertions(+) diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index a2738e924..a3a6d2538 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -271,6 +271,9 @@ int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide, uint64_ // 创建老auth_mar,只创建独立的一个 authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, listener_, hiChainAuthConnector_); + if (GetEnableNewProtocolFlag() == 0) { + authMgr_->isAuthNewVersion_ = false; + } softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); hiChainConnector_->RegisterHiChainCallback(authMgr_); hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); -- Gitee From 3c19c884ad77c66ef153783f20a0d2db465d1527 Mon Sep 17 00:00:00 2001 From: ZHANGHE24 Date: Sun, 30 Mar 2025 16:32:16 +0800 Subject: [PATCH 379/382] fix: bug --- .../implementation/src/device_manager_service_impl.cpp | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index a3a6d2538..bf6badd3d 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -271,17 +271,12 @@ int32_t DeviceManagerServiceImpl::InitAndRegisterAuthMgr(bool isSrcSide, uint64_ // 创建老auth_mar,只创建独立的一个 authMgr_ = std::make_shared(softbusConnector_, hiChainConnector_, listener_, hiChainAuthConnector_); - if (GetEnableNewProtocolFlag() == 0) { - authMgr_->isAuthNewVersion_ = false; - } + authMgr_->isAuthNewVersion_ = false; softbusConnector_->GetSoftbusSession()->RegisterSessionCallback(authMgr_); hiChainConnector_->RegisterHiChainCallback(authMgr_); hiChainAuthConnector_->RegisterHiChainAuthCallback(authMgr_); - return DM_OK; - } - if (GetEnableNewProtocolFlag() == 0) { - return DM_OK; } + return DM_OK; } // 已创建authMgr_,说明已有绑定事件,其他请求拒绝,返回错误码 LOGE("BindTarget failed, this device is being bound. Please try again later."); @@ -815,7 +810,6 @@ int32_t DeviceManagerServiceImpl::TransferOldAuthMgr(int32_t msgType, int64_t lo // 内部已完成错误日志打印 return ERR_DM_AUTH_FAILED; } - authMgr->isAuthNewVersion_ = false; if (IsAuthManagerSourceByMessage(msgType)) { // 发送停止报文 -- Gitee From c9310f035e05bc8e6b7142376cd727c54c14aa10 Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Sun, 30 Mar 2025 16:46:18 +0800 Subject: [PATCH 380/382] fix: softbus compiling error --- .../include/dependency/softbus/softbus_connector.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/services/implementation/include/dependency/softbus/softbus_connector.h b/services/implementation/include/dependency/softbus/softbus_connector.h index cb776062f..a50897695 100644 --- a/services/implementation/include/dependency/softbus/softbus_connector.h +++ b/services/implementation/include/dependency/softbus/softbus_connector.h @@ -49,7 +49,7 @@ public: * @tc.desc: Get Connect Addr of the SoftbusConnector * @tc.type: FUNC */ - static shared_ptr GetConnectAddr(const std::string &deviceId, std::string &connectAddr); + static std::shared_ptr GetConnectAddr(const std::string &deviceId, std::string &connectAddr); /** * @tc.name: SoftbusConnector::GetUdidByNetworkId -- Gitee From 80f472fb7d44d728f732d00fb7dd1da75e8707ed Mon Sep 17 00:00:00 2001 From: ZHANGHE24 Date: Sun, 30 Mar 2025 17:12:44 +0800 Subject: [PATCH 381/382] fix: bug --- .../include/device_manager_service_impl.h | 3 ++- .../src/authentication_v2/auth_manager.cpp | 5 ++--- .../src/dependency/softbus/softbus_session.cpp | 6 ------ .../src/device_manager_service_impl.cpp | 17 +++++++++++------ 4 files changed, 15 insertions(+), 16 deletions(-) diff --git a/services/implementation/include/device_manager_service_impl.h b/services/implementation/include/device_manager_service_impl.h index 56e0cc659..138e03ef2 100644 --- a/services/implementation/include/device_manager_service_impl.h +++ b/services/implementation/include/device_manager_service_impl.h @@ -200,7 +200,8 @@ private: const JsonObject &jsonObject, std::shared_ptr curSession, uint64_t &tokenId); int32_t TransferOldAuthMgr(int32_t msgType, int64_t logicalSessionId, std::shared_ptr curSession, uint64_t tokenId, std::shared_ptr authMgr); - int32_t GetDeviceInfo(std::string &deviceId, std::shared_ptr deviceInfo, int32_t &index); + int32_t GetDeviceInfo(const PeerTargetId &targetId, std::string &addrType, std::string &deviceId, + std::shared_ptr deviceInfo, int32_t &index); // 清理资源线程 void CleanWorker(); diff --git a/services/implementation/src/authentication_v2/auth_manager.cpp b/services/implementation/src/authentication_v2/auth_manager.cpp index 688f6088d..bb08246e8 100644 --- a/services/implementation/src/authentication_v2/auth_manager.cpp +++ b/services/implementation/src/authentication_v2/auth_manager.cpp @@ -41,7 +41,6 @@ namespace OHOS { namespace DistributedHardware { namespace { -static const char* PICKER_PROXY_SPLIT = "_pickerProxy_"; constexpr int32_t MIN_PIN_CODE = 100000; constexpr int32_t MAX_PIN_CODE = 999999; @@ -359,7 +358,7 @@ void AuthSrcManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *sess LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64 "is error.", requestId); return; } - int32_t ret = context_->authMessageProcessor->ProcessSessionKey(sessionKey, sessionKeyLen); + int32_t ret = context_->authMessageProcessor->SaveSessionKey(sessionKey, sessionKeyLen); if (ret != DM_OK) { LOGE("AuthSrcManager::AuthDeviceSessionKey, save session key error, ret: %{public}d", ret); } @@ -1036,7 +1035,7 @@ void AuthSinkManager::AuthDeviceSessionKey(int64_t requestId, const uint8_t *ses LOGE("AuthSrcManager::onTransmit requestId %{public}" PRId64 "is error.", requestId); return; } - int32_t ret = context_->authMessageProcessor->ProcessSessionKey(sessionKey, sessionKeyLen); + int32_t ret = context_->authMessageProcessor->SaveSessionKey(sessionKey, sessionKeyLen); if (ret != DM_OK) { LOGE("AuthSrcManager::AuthDeviceSessionKey, save session key error, ret: %{public}d", ret); } diff --git a/services/implementation/src/dependency/softbus/softbus_session.cpp b/services/implementation/src/dependency/softbus/softbus_session.cpp index 007323eea..59be600ed 100644 --- a/services/implementation/src/dependency/softbus/softbus_session.cpp +++ b/services/implementation/src/dependency/softbus/softbus_session.cpp @@ -201,12 +201,6 @@ void SoftbusSession::OnSessionClosed(int sessionId) void SoftbusSession::OnBytesReceived(int sessionId, const void *data, unsigned int dataLen) { - std::string message = std::string(reinterpret_cast(data), dataLen); - if (msgType == AUTH_DEVICE_REQ_NEGOTIATE || msgType == AUTH_DEVICE_RESP_NEGOTIATE) { - authMgr->OnAuthDeviceDataReceived(sessionId, message); - } else { - authMgr->OnDataReceived(sessionId, message); - } LOGI("start, sessionId: %{public}d, dataLen: %{public}d.", sessionId, dataLen); return; } diff --git a/services/implementation/src/device_manager_service_impl.cpp b/services/implementation/src/device_manager_service_impl.cpp index bf6badd3d..1a65f1ad2 100644 --- a/services/implementation/src/device_manager_service_impl.cpp +++ b/services/implementation/src/device_manager_service_impl.cpp @@ -811,6 +811,7 @@ int32_t DeviceManagerServiceImpl::TransferOldAuthMgr(int32_t msgType, int64_t lo return ERR_DM_AUTH_FAILED; } + int sessionId = curSession->sessionId_; if (IsAuthManagerSourceByMessage(msgType)) { // 发送停止报文 // 不能走新协议的停止,新协议是信号机制,无法串行停止,会存在时延,导致未停止就创建了新对象, @@ -820,8 +821,7 @@ int32_t DeviceManagerServiceImpl::TransferOldAuthMgr(int32_t msgType, int64_t lo // 关闭新协议会话 CleanSessionMapByLogicalSessionId(logicalSessionId); - ret = authMgr->BindTarget(pkgName, peerTargetId, bindParam, sessionId, 0); - if (ret != DM_OK) { + if (authMgr->BindTarget(pkgName, peerTargetId, bindParam, sessionId, 0) != DM_OK) { LOGE("DeviceManagerServiceImpl::OnBytesReceived authManager BindTarget failed"); return ERR_DM_AUTH_FAILED; } @@ -890,8 +890,13 @@ void DeviceManagerServiceImpl::OnBytesReceived(int sessionId, const void *data, } } } + std::string message = std::string(reinterpret_cast(data), dataLen); + if (msgType == AUTH_DEVICE_REQ_NEGOTIATE || msgType == AUTH_DEVICE_RESP_NEGOTIATE) { + authMgr->OnAuthDeviceDataReceived(sessionId, message); + } else { + authMgr->OnDataReceived(sessionId, message); + } SoftbusSession::OnBytesReceived(sessionId, data, dataLen); - LOGI("DeviceManagerServiceImpl::OnBytesReceived in bytes received"); return; } @@ -1306,8 +1311,8 @@ error: return nullptr; } -int32_t DeviceManagerServiceImpl::GetDeviceInfo(std::string &deviceId, std::shared_ptr deviceInfo, - int32_t &index) +int32_t DeviceManagerServiceImpl::GetDeviceInfo(const PeerTargetId &targetId, std::string &addrType, + std::string &deviceId, std::shared_ptr deviceInfo, int32_t &index) { ConnectionAddr addr; if (!targetId.wifiIp.empty() && targetId.wifiIp.length() <= IP_STR_MAX_LEN) { @@ -1366,7 +1371,7 @@ int32_t DeviceManagerServiceImpl::ParseConnectAddr(const PeerTargetId &targetId, std::shared_ptr deviceInfo = std::make_shared(); int32_t index = 0; - int32_t ret = GetDeviceInfo(deviceId, deviceInfo, index); + int32_t ret = GetDeviceInfo(targetId, addrType, deviceId, deviceInfo, index); if (ret != DM_OK) { LOGE("GetDeviceInfo failed, ret: %{public}d", ret); } -- Gitee From 8c6548591f6a722fab8496dae2c45de296cd258a Mon Sep 17 00:00:00 2001 From: guoliang47 Date: Sun, 30 Mar 2025 17:42:35 +0800 Subject: [PATCH 382/382] =?UTF-8?q?fix:=20=E5=A4=84=E7=90=86=E7=BC=96?= =?UTF-8?q?=E8=AF=91=E9=97=AE=E9=A2=98?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- ext/pin_auth/BUILD.gn | 2 +- services/implementation/src/authentication_v2/dm_auth_state.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/ext/pin_auth/BUILD.gn b/ext/pin_auth/BUILD.gn index 4d4dcacbb..162965b9d 100644 --- a/ext/pin_auth/BUILD.gn +++ b/ext/pin_auth/BUILD.gn @@ -95,7 +95,7 @@ ohos_shared_library("devicemanagerext_pin_auth") { "resource_management:resmgr_napi_core", "safwk:system_ability_fwk", "samgr:samgr_proxy", - "cJSON:cjson" + "cJSON:cjson", ] defines = [ diff --git a/services/implementation/src/authentication_v2/dm_auth_state.cpp b/services/implementation/src/authentication_v2/dm_auth_state.cpp index c7ebc52ec..6fa327d92 100644 --- a/services/implementation/src/authentication_v2/dm_auth_state.cpp +++ b/services/implementation/src/authentication_v2/dm_auth_state.cpp @@ -467,7 +467,7 @@ int32_t DmAuthState::GetAuthCredentialInfo(std::shared_ptr contex DmAccess &access = context->direction == DM_AUTH_SOURCE ? context->accesser : context->accessee; std::vector profiles = DeviceProfileConnector::GetInstance().GetAllAccessControlProfile(); - LOGI("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo success to get %{public}ld acls", profiles.size()); + LOGI("AuthSinkNegotiateStateMachine::GetAuthCredentialInfo success to get %{public}" PRId64 " acls", static_cast(profiles.size())); for (const DistributedDeviceProfile::AccessControlProfile &item : profiles) { bool isAclMatched = false; DistributedDeviceProfile::Accesser accesser = item.GetAccesser(); -- Gitee