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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] =?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/211] =?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/211] =?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/211] =?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/211] =?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/211] =?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/211] =?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/211] 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/211] 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/211] 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/211] 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/211] 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/211] =?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/211] 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/211] 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/211] 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/211] 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/211] 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/211] =?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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] =?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/211] 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/211] 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/211] =?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/211] 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/211] 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/211] 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/211] =?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/211] =?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/211] =?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/211] 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/211] 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/211] 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/211] 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/211] =?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/211] =?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/211] =?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/211] =?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/211] 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/211] 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/211] 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/211] =?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/211] 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/211] 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/211] =?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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] =?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/211] 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/211] 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/211] 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/211] 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/211] =?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/211] =?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/211] 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/211] 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/211] =?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/211] 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/211] =?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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] =?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/211] 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/211] =?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/211] =?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/211] 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/211] 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/211] 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/211] 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/211] =?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/211] =?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/211] =?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/211] =?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/211] =?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/211] 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/211] 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/211] 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/211] =?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/211] =?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/211] 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/211] =?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/211] =?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/211] =?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/211] =?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/211] =?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/211] 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/211] =?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/211] 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/211] 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/211] 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/211] =?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/211] =?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/211] 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/211] =?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/211] =?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/211] =?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/211] 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/211] =?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/211] =?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/211] =?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/211] =?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/211] =?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/211] 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/211] =?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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] =?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/211] =?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/211] =?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/211] 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/211] 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/211] =?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/211] =?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/211] =?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/211] =?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/211] =?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/211] =?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/211] =?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/211] =?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/211] =?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/211] =?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/211] =?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/211] =?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/211] =?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/211] 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/211] 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/211] 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/211] =?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/211] =?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/211] 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/211] =?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/211] =?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/211] =?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/211] =?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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] =?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/211] =?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/211] =?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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] =?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/211] 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/211] 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/211] =?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/211] =?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/211] =?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/211] =?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/211] =?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/211] 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/211] 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/211] 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/211] 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/211] 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/211] 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/211] =?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