• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright (c) 2025 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #ifndef OHOS_DM_AUTH_CONTEXT_V2_H
17 #define OHOS_DM_AUTH_CONTEXT_V2_H
18 #include <map>
19 #include <string>
20 
21 #include "access_control_profile.h"
22 #include "authentication.h"
23 #include "auth_manager.h"
24 #include "auth_ui_state_manager.h"
25 #include "dm_ability_manager.h"
26 #include "dm_anonymous.h"
27 #include "dm_auth_message_processor.h"
28 #include "dm_constants.h"
29 #include "dm_device_info.h"
30 #include "dm_log.h"
31 #include "dm_timer.h"
32 #include "hichain_auth_connector.h"
33 #include "hichain_connector.h"
34 #include "softbus_connector.h"
35 #include "softbus_session.h"
36 
37 namespace OHOS {
38 namespace DistributedHardware {
39 
40 class DmAuthStateMachine;
41 class DmAuthMessageProcessor;
42 
43 using CleanNotifyCallback = std::function<void(uint64_t)>;
44 
45 // PIN Code Authentication Type
46 enum DmAuthType : int32_t {
47     AUTH_TYPE_CRE = 0,
48     AUTH_TYPE_PIN,              // Input PIN code
49     AUTH_TYPE_QR_CODE,          // Not used in the new protocol
50     AUTH_TYPE_NFC,
51     AUTH_TYPE_NO_INTER_ACTION,  // Not used in the new protocol
52     AUTH_TYPE_IMPORT_AUTH_CODE, // Import PIN code
53     AUTH_TYPE_PIN_ULTRASONIC,   // Ultrasonic PIN code
54     AUTH_TYPE_UNKNOW,           // Not used in the new protocol
55 };
56 
57 enum DmAuthDirection {
58     DM_AUTH_SOURCE = 0,
59     DM_AUTH_SINK,
60 };
61 
62 enum DmBindType {
63     DM_AUTH_USERID = 1,
64     DM_AUTH_SYSTEM_SERVICE,
65     DM_AUTH_APP_SERVICE,
66     DM_AUTH_DEVICEID,
67 };
68 
69 enum DmAuthSide {
70     DM_AUTH_LOCAL_SIDE = 0,
71     DM_AUTH_REMOTE_SIDE,
72 };
73 
74 enum DmAuthScope {
75     DM_AUTH_SCOPE_INVALID = 0,
76     DM_AUTH_SCOPE_DEVICE,
77     DM_AUTH_SCOPE_USER,
78     DM_AUTH_SCOPE_APP,
79     DM_AUTH_SCOPE_LNN,
80     DM_AUTH_SCOPE_MAX,
81 };
82 
83 enum {
84     DM_UNKNOWN_TYPE = 0,
85     DM_SAME_ACCOUNT_TYPE = 1,
86     DM_SHARE_TYPE = 2,
87     DM_POINT_TO_POINT_TYPE = 256,
88     DM_SAME_GROUP_TYPE = 3,
89 };
90 
91 enum DmUltrasonicInfo {
92     // Forward means the pincode is generated at sink side, then send by ultrasonic from sink to source side.
93     DM_Ultrasonic_Forward = 0,
94     // Reverse means the pincode is generated at source side, then send by ultrasonic from source to sink side.
95     DM_Ultrasonic_Reverse = 1,
96     DM_Ultrasonic_Invalid = 2,
97 };
98 
99 typedef struct DmProxyAccess {
100     std::string pkgName;
101     std::string pkgLabel;
102     std::string bundleInfo;
103     std::string bundleName;
104     std::string peerBundleName;
105     int64_t tokenId;
106     std::string tokenIdHash;
107     int32_t bindLevel;
108     std::string transmitCredentialId;
109     std::string transmitPublicKey;
110     std::string publicKey;
111     int32_t sessionKeyId;
112     int32_t transmitSessionKeyId;
113     int64_t transmitSkTimeStamp;
114     int64_t skTimeStamp;        // Used for aging, time is 2 days
115     bool isAuthed;
116     std::string aclTypeList;        // Trust relationship list, used for data aging, KV format
117     std::string credTypeList;
118     std::string aclStrList;
119     std::map<int32_t, std::string> credentialInfos;
120     std::map<int32_t, DistributedDeviceProfile::AccessControlProfile> aclProfiles;
121     std::string credInfoJson;
122     std::string aclTypeJson;
123 } DmProxyAccess;
124 
125 struct DmProxyAuthContext {
126     std::string proxyContextId;
127     std::string customData;
128     std::string pkgLabel;
129     bool needBind{true};
130     bool needAgreeCredential{true};
131     bool needAuth{true};
132     bool IsNeedSetProxyRelationShip{false};
133     DmProxyAccess proxyAccesser;
134     DmProxyAccess proxyAccessee;
135     bool operator==(const DmProxyAuthContext &other) const
136     {
137         return (proxyContextId == other.proxyContextId);
138     }
139 
140     bool operator<(const DmProxyAuthContext &other) const
141     {
142         return proxyContextId < other.proxyContextId;
143     }
144 };
145 
146 // Used for one-touch pairing
147 struct DmPeerTargetAddress {
148     // directly establish a Bluetooth connection
149     std::string peerBrMacAddress;
150     std::string peerBleMacAddress;
151     std::string peerWifiMacAddress;
152     std::string peerActionMacAddress;
153 
154     std::string peerWifiChannel;
155     std::string peerWifiIp;
156     uint16_t peerWifiPort;
157 };
158 
159 struct DmPeerTarget {
160     DmBindType peerType;
161     std::string peerDeviceId;
162     int64_t peerServiceId;
163     int64_t peerSaTokenId;
164     std::string peerBundleName;
165     DmPeerTargetAddress peerTargetAddress;
166 };
167 
168 struct DmAccess {
169     std::string deviceName;
170     int32_t deviceType;         // Device types such as PC, mobile, watch, large screen, etc.
171     std::string deviceId;
172     std::string deviceIdHash;
173     std::string addr;
174     int32_t userId{-1};
175     int32_t displayId{-1};       // Logical screen ID, used for query userId
176     std::string accountId;
177     std::string accountIdHash;
178     int64_t tokenId;
179     std::string tokenIdHash;
180     std::string networkId;
181     std::string bundleName;     // Stores the bundleName, HAP -> bundleName in BMS, SA -> process name
182     std::string pkgName;    // store pkgName set by client
183     std::string language;
184     int64_t serviceId;          // Reserved field, to be used in HM 6.0
185     std::string accesserHapSignature;
186     int32_t bindLevel;
187     int32_t lnnBindType;
188     int32_t transmitBindType;
189     std::string lnnCredentialId; // User-level credential ID
190     std::string transmitCredentialId; // Application-level credential ID
191     std::string lnnPublicKey;   // User-level public key
192     std::string transmitPublicKey;   // Application-level public key
193     std::vector<int32_t> bindType;  // such as DM_AUTH_CREDENTIAL_ACCOUNT_RELATED
194     std::string publicKey;
195     int32_t status;             // Indicates whether the service is in the foreground or background
196     int32_t sessionKeyId;       // Used as key delivery material, retrieves the SK from the bus
197     int32_t transmitSessionKeyId; // Permanent application SKID on this end, returned by DP for ACL updates and aging
198     int32_t lnnSessionKeyId{0};    // Permanent user SKID on this end, returned by DP for ACL updates and aging
199     int32_t oldBindLevel;
200     int64_t transmitSkTimeStamp; // Used for aging, time is 2 days, application-level credential timestamp
201     int64_t lnnSkTimeStamp{0};     // Used for aging, time is 2 days, user-level credential timestamp
202     int64_t skTimeStamp;        // Used for aging, time is 2 days
203     uint64_t certRandom{0}; // Used for cert generate
204     bool isAuthed;
205     bool isUserLevelAuthed;
206     bool isOnline;
207     bool isGenerateLnnCredential{true};
208     bool isPutLnnAcl{true};
209     std::string dmVersion;
210     std::string edition;        // Used for compatibility before version 5.1.0, assists in version negotiation
211     std::string aclTypeList;        // Trust relationship list, used for data aging, KV format
212     std::string credTypeList;
213     std::string aclStrList;
214     std::map<int32_t, std::string> credentialInfos;         // map: <credType, cred>, cred is string tranformed by json
215     std::map<int32_t, DistributedDeviceProfile::AccessControlProfile> aclProfiles;
216     // construct for old version compatible start
217     // In the scenario of compatibility between the new and old protocols, it is necessary to
218     // send both the new and old protocol messages simultaneously in the 80 message when
219     // authType == import. Therefore, it is required to define these fields for compatibility processing.
220     std::string accountGroupIdHash;
221     std::string oldBundleName;
222     // construct for old version compatible end
223     std::string extraInfo;      // Expandable field, JSON format, KV structure
224     std::string cert;
225     bool isCommonFlag{false};
226     bool isGeneratedLnnCredThisBind{false};
227     bool isGeneratedTransmitThisBind{false};
228 };
229 
230 struct DmAuthContext {
231     bool isOnline;
232     uint64_t logicalSessionId;
233     DmMessageType msgType;
234     int32_t sessionId;
235     int64_t requestId;          // HiChain authentication ID
236     DMLocalServiceInfoAuthBoxType authBoxType{DMLocalServiceInfoAuthBoxType::STATE3}; // Authentication box type
237     UiAction pinInputResult;
238     // Authorization result (using 0, 1, 6, representing single use, cancel, and always trust, enum UiAction)
239     UiAction confirmOperation{UiAction::USER_OPERATION_TYPE_ALLOW_AUTH};
240     DmAuthType authType{DmAuthType::AUTH_TYPE_PIN};  // PIN code, ultrasonic PIN code, imported PIN code
241     std::vector<DmAuthType> authTypeList;
242     uint32_t currentAuthTypeIdx{0};
243     int32_t inputPinAuthFailTimes{0}; // Number of failed PIN authentication attempts, exceeding 3 results in failure
244     std::string pinCode{""};
245     bool serviceInfoFound{false};
246     // Link delay release time, does not automatically disconnect after
247     // authorization (used for specific business needs), reserved field
248     int32_t connDelayCloseTime;
249     int32_t reason{DM_OK};
250     int32_t reply;
251     std::string userOperationParam;
252     int32_t state;
253     int32_t hmlActionId = 0;
254     int64_t remainingFrozenTime = 0;
255     bool authenticating;        // Indicator whether authentication is in progress
256     bool successFinished{false};
257     bool isAppCredentialVerified{false};        // Whether the application credential has been verified
258     bool hmlEnable160M{false};
259     std::string businessId;
260     std::string pkgName;    // Business-provided identifier, custom-defined by business, carries risk of spoofing
261     std::string pkgLabel;
262     std::string importCodeBundleName;           // Bundle name for imported PIN code
263     std::string appThumbnail;   // Application thumbnail
264     // Description of the operation this binding is used for, displayed in authorization dialog
265     std::string appOperation;
266     // Custom business field, provides detailed information to the user about this binding operation
267     std::string customData;
268     std::string connSessionType;
269     std::string extraInfo;      // Expandable field, key-value structure
270     DmAuthDirection direction;  // Indicator of authentication direction
271     ProcessInfo processInfo;
272     DmPeerTarget peerTarget;
273     DmUltrasonicInfo ultrasonicInfo = DmUltrasonicInfo::DM_Ultrasonic_Forward; // Ultrasonic information
274     DmAccess accesser;
275     DmAccess accessee;
276     std::multimap<DmAccess, DmAccess> proxy;    // Multimap where the key is the accessor and the value is the accesssee
277     bool isNeedJoinLnn{true};
278     bool IsProxyBind{false};
279     bool IsCallingProxyAsSubject{true};
280     bool IsNeedSetProxy{false};
281     bool isNeedAuthorize{false};
282     std::vector<DmProxyAuthContext> subjectProxyOnes;
283     std::string reUseCreId;
284     std::string title;
285     std::string srvExtarInfo;
286 
287     std::shared_ptr<DmAuthStateMachine> authStateMachine;
288     std::shared_ptr<AuthUiStateManager> authUiStateMgr;
289     std::shared_ptr<HiChainConnector> hiChainConnector;
290     std::shared_ptr<HiChainAuthConnector> hiChainAuthConnector;
291     std::shared_ptr<DmAuthMessageProcessor> authMessageProcessor;
292     std::shared_ptr<SoftbusConnector> softbusConnector;
293     std::shared_ptr<IDeviceManagerServiceListener> listener;
294     std::shared_ptr<IAuthentication> authPtr;   // Pointer to authentication interface
295     std::shared_ptr<DmTimer> timer;
296     std::string transmitData;                   // Data returned from onTransmit function
297     std::string importPkgName = "";
298     std::string importAuthCode = "";
299     std::map<int32_t, std::shared_ptr<IAuthentication>> authenticationMap;
300     PeerTargetId peerTargetId;
301     bool pinNegotiateStarted{false};
302     bool isAuthenticateDevice{false};           // Whether device authentication is in progress
303     bool needBind{true};
304     bool needAgreeCredential{true};
305     bool needAuth{true};
306     std::mutex certMtx_; // cert lock
307     std::mutex certCVMtx_; // cert cv lock
308     std::condition_variable certCV_; // cert cv
309     CleanNotifyCallback cleanNotifyCallback{nullptr};
310 
311     std::string GetDeviceId(DmAuthSide side);
312     int32_t GetUserId(DmAuthSide side);
313     std::string GetCredentialId(DmAuthSide side, DmAuthScope authorizedScope);
314     std::string GetPublicKey(DmAuthSide side, DmAuthScope authorizedScope);
315     void SetCredentialId(DmAuthSide side, DmAuthScope authorizedScope, const std::string &credentialId);
316     void SetPublicKey(DmAuthSide side, DmAuthScope authorizedScope, const std::string &publicKey);
317     std::string GetAccountId(DmAuthSide side);
318 };
319 }  // namespace DistributedHardware
320 }  // namespace OHOS
321 #endif  // OHOS_DM_AUTH_CONTEXT_V2_H
322